diff --git a/.claude/settings.json b/.claude/settings.json index 708783f7..0964c96e 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -17,10 +17,33 @@ "Bash(grep -r \"^parent: 代理 API$\" .)", "Bash(grep -r \"^parent: 模型组 API$\" .)", "Bash(grep -r \"^parent: 任务 API$\" .)", - "Bash(grep -r \"^parent: 训练和预测 API$\" .)" + "Bash(grep -r \"^parent: 训练和预测 API$\" .)", + "Bash(cd /tmp/opensearch-docs-check/documentation-website && find . -name \"multi-search.md\" 2>/dev/null)", + "Read(//private/tmp/opensearch-docs-check/documentation-website/**)", + "Read(//tmp/opensearch-docs-check/documentation-website/_api-reference/search-apis/**)", + "Read(//private/tmp/opensearch-docs-check/documentation-website/_api-reference/search-apis/**)", + "Bash(comm -23 /tmp/source_files.txt /tmp/translated_files.txt | wc -l)", + "Read(//private/tmp/**)", + "Bash(comm -23 /tmp/source_files.txt /tmp/translated_files.txt | head -20)", + "Bash(comm -23 /tmp/source_files.txt /tmp/translated_files.txt)", + "Bash(find _data-prepper -name \"*.md\" -type f | sort > /tmp/source_files.txt && cat /tmp/source_files.txt)", + "Bash(python3)", + "Bash(grep -E \"^\\(gsub|html-strip|index-processors|ip2geo|join|json|kv|lowercase|ml-inference|pipeline|remove-by-pattern|remove\\\\.md|remove_by_pattern|rename|script\\)\\\\.md$\")", + "Bash(grep -E \"\\\\.md$\")", + "Bash(grep -E \"\\(connector-tool|create-anomaly-detector|data-distribution-tool|list-index-tool|log-pattern-analysis-tool|log-pattern-tool|query-planning-tool|scratchpad-tools|search-template-fill-tool|web-search-tool\\)\\\\.md$\")", + "Bash(grep -E '\\\\.md$')", + "Bash(chmod +x /tmp/check_missing_files.sh)", + "Bash(/tmp/check_missing_files.sh)", + "Bash(chmod +x /tmp/check_all_files.sh)", + "Bash(/tmp/check_all_files.sh)", + "Bash(grep \"\\\\.md$\")", + "Bash(chmod +x /tmp/verify_files.sh)", + "Bash(/tmp/verify_files.sh)", + "Bash(xargs -n1 basename)" ], "additionalDirectories": [ - "/Users/yuchenghu/Documents/WorkDir/iSharkFly/iSharkFly-Docs/OpenSearch-iSharkFly-Com/i18n/zh/clients" + "/Users/yuchenghu/Documents/WorkDir/iSharkFly/iSharkFly-Docs/OpenSearch-iSharkFly-Com/i18n/zh/clients", + "/tmp" ] } } diff --git a/_about/breaking-changes.md b/_about/breaking-changes.md index 9c0bd513..ef13484c 100644 --- a/_about/breaking-changes.md +++ b/_about/breaking-changes.md @@ -5,7 +5,15 @@ nav_order: 5 permalink: /breaking-changes/ --- +# Breaking changes + +OpenSearch uses [Semantic Versioning](https://semver.org/), which means that breaking changes are only introduced between major version releases. The following sections list breaking changes introduced in OpenSearch, organized by version. + + ## 1.x + + +The following breaking changes were introduced in OpenSearch 1.x. ### Migrating to OpenSearch and limits on the number of nested JSON objects @@ -16,6 +24,8 @@ Therefore, we recommend evaluating your data for these limits before attempting ## 2.0.0 +The following breaking changes were introduced in OpenSearch 2.0.0. + ### Remove mapping types parameter The `type` parameter has been removed from all OpenSearch API endpoints. Instead, indexes can be categorized by document type. For more details, see issue [#1940](https://github.com/opensearch-project/opensearch/issues/1940). @@ -24,21 +34,218 @@ The `type` parameter has been removed from all OpenSearch API endpoints. Instead Non-inclusive terms are deprecated in version 2.x and will be permanently removed in OpenSearch 3.0. We are using the following replacements: + - "Whitelist" is now "Allow list" - "Blacklist" is now "Deny list" - "Master" is now "Cluster Manager" + + ### Add OpenSearch Notifications plugins + In OpenSearch 2.0, the Alerting plugin is now integrated with new plugins for Notifications. If you want to continue to use the notification action in the Alerting plugin, install the new backend plugins `notifications-core` and `notifications`. If you want to manage notifications in OpenSearch Dashboards, use the new `notificationsDashboards` plugin. For more information, see [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) on the OpenSearch documentation page. ### Drop support for JDK 8 -A Lucene upgrade forced OpenSearch to drop support for JDK 8. As a consequence, the [Java high-level REST client]({{site.url}}{{site.baseurl}}/clients/java-rest-high-level/) no longer supports JDK 8. Restoring JDK 8 support is currently an `opensearch-java` proposal [#156](https://github.com/opensearch-project/opensearch-java/issues/156) and will require removing OpenSearch core as a dependency from the Java client (issue [#262](https://github.com/opensearch-project/opensearch-java/issues/262)). +A Lucene upgrade forced OpenSearch to drop support for JDK 8. As a consequence, the Java high-level REST client no longer supports JDK 8. Restoring JDK 8 support is currently an `opensearch-java` proposal [#156](https://github.com/opensearch-project/opensearch-java/issues/156) and will require removing OpenSearch core as a dependency from the Java client (issue [#262](https://github.com/opensearch-project/opensearch-java/issues/262)). ## 2.5.0 +The following breaking change was introduced in OpenSearch 2.5.0. + ### Wildcard query behavior for text fields -OpenSearch 2.5 contains a bug fix to correct the behavior of the `case_insensitive` parameter for the `wildcard` query on text fields. As a result, a wildcard query on text fields that ignored case sensitivity and erroneously returned results prior to the bug fix will not return the same results. For more information, see issue [#8711](https://github.com/opensearch-project/OpenSearch/issues/8711). \ No newline at end of file +OpenSearch 2.5 contains a bug fix that corrects the behavior of the `case_insensitive` parameter for the `wildcard` query on text fields. As a result, a wildcard query on text fields that ignored case sensitivity and erroneously returned results prior to the bug fix will not return the same results. For more information, see issue [#8711](https://github.com/opensearch-project/OpenSearch/issues/8711). + +## 2.18.0 + +The following breaking change was introduced in OpenSearch 2.18.0. + +### Default k-NN engine change + +The default k-NN engine changed from NMSLIB to Faiss. If you use `space_type: "cosinesimil"` without explicitly specifying an engine, your vectors are now automatically normalized to unit length during indexing. This happens because Faiss does not natively support cosine similarity and instead uses inner product on normalized vectors. As a result, stored vector values will differ from input values, which may affect code that retrieves and compares vectors. If your vectors are already normalized, consider setting `space_type` to `innerproduct` instead of `cosinesimil` to obtain mathematically equivalent results with explicit control over normalization. For more information, see pull request [#2221](https://github.com/opensearch-project/k-NN/pull/2221). + +## 2.19.0 + +The following breaking change was introduced in OpenSearch 2.19.0. + +### Nested value support in the text embedding processor +The `text_embedding` processor no longer replaces nested values like `_ingest._value` when evaluating fields like `title_tmp:_ingest._value.title_embedding`. Instead, you must directly specify the nested key as `books.title:title_embedding` to achieve the desired output. For more information, see issue [#1243](https://github.com/opensearch-project/neural-search/issues/1243). + +## 3.0.0 + +The following breaking changes were introduced in OpenSearch 3.0.0. + +### JDK requirement + +The minimum supported JDK version is JDK 21. + +### Version compatibility setting + +The `compatibility.override_main_response_version` setting has been removed. This functionality was deprecated in OpenSearch 1.x and is no longer supported. + +For more information, see issue [#18228](https://github.com/opensearch-project/OpenSearch/issues/18228). + +For alternative approaches, see [Agents and ingestion tools]({{site.url}}{{site.baseurl}}/tools/#agents-and-ingestion-tools). + +### Index version + +Indexes created in versions earlier than `2.x.x` (including system indexes) are not supported. These indexes must be reindexed **before upgrading**. For information about reindexing, see [Reindex data]({{site.url}}{{site.baseurl}}/im-plugin/reindex-data/). + +For more information, see issue [#18717](https://github.com/opensearch-project/OpenSearch/issues/18717). + +### System index access + +Access to system indexes through the REST API is no longer provided. This functionality has been deprecated since OpenSearch 1.x. For more information, see issue [#7936](https://github.com/opensearch-project/OpenSearch/issues/7936). + +### Document ID length limits + +The document ID length limit of 512 bytes is now consistently enforced across all APIs, including the Bulk API. Previously, the Bulk API allowed document IDs longer than 512 bytes. For more information, see issue [#6595](https://github.com/opensearch-project/OpenSearch/issues/6595). + +### Node role configuration + +The configuration of empty node roles using environment variables has been fixed. Setting `node.roles=` using environment variables now properly configures a coordinating-only node, consistent with the `opensearch.yml` configuration. For more information, see issue [#3412](https://github.com/opensearch-project/OpenSearch/issues/3412). + +### JSON processing limits + +New default limits have been introduced for JSON processing (using the Jackson library) throughout OpenSearch: + +- The maximum nesting depth of JSON objects and arrays is limited to 1,000 levels. +- The maximum length of JSON property names is limited to 50,000 units (bytes or chars, depending on the input source). + +These limits help prevent potential memory issues and denial-of-service attacks. For more information, see issue [#11278](https://github.com/opensearch-project/OpenSearch/issues/11278). + +### Nested query depth + +A new `index.query.max_nested_depth` setting has been introduced with a default value of `20` and a minimum value of `1`, limiting the maximum number of nesting levels for `nested` queries. For more information, see issue [#3268](https://github.com/opensearch-project/OpenSearch/issues/3268). + +### Thread pool settings + +The following deprecated thread pool settings have been removed: +- `thread_pool.test.max_queue_size` +- `thread_pool.test.min_queue_size` +For more information, see issue [#2595](https://github.com/opensearch-project/OpenSearch/issues/2595). + +### Index store settings + +The `index.store.hybrid.mmap.extensions` setting has been removed as part of improvements to `hybridfs` file handling. For more information, see pull request [#9392](https://github.com/opensearch-project/OpenSearch/pull/9392). + +### Transport NIO plugin + +The `transport-nio` plugin has been removed. Netty remains the standard network framework for both node-to-node and client-to-server communication. For more information, see issue [#16887](https://github.com/opensearch-project/OpenSearch/issues/16887). + +### Nodes API response format + +The format of indexing buffer values in the Nodes API response has changed: + +- `total_indexing_buffer_in_bytes` now displays raw bytes (for example, `53687091`). +- `total_indexing_buffer` now displays human-readable format (for example, `51.1mb`). + +For more information, see pull request [#17070](https://github.com/opensearch-project/OpenSearch/pull/17070). + +### PathHierarchy tokenizer + +The camel case `PathHierarchy` tokenizer name has been deprecated in favor of the snake case `path_hierarchy`. For more information, see pull request [#10894](https://github.com/opensearch-project/OpenSearch/pull/10894). + +### Security plugin + +The Blake2b hash implementation now uses the salt parameter correctly, which will result in different (though correct) hash values compared to previous versions. For more information, see pull request [#5089](https://github.com/opensearch-project/security/pull/5089). + +### k-NN plugin + +The following deprecated settings have been removed from the k-NN plugin: + +- `knn.plugin.enabled` setting +- `index.knn.algo_param.ef_construction` index setting +- `index.knn.algo_param.m` index setting +- `index.knn.space_type` index setting + +The NMSLIB engine is now deprecated. We recommend using the Faiss or Lucene engines instead. + +For more information, see pull request [#2564](https://github.com/opensearch-project/k-NN/pull/2564). + +### Performance Analyzer plugin + +The `performance-analyzer-rca` agent has been removed. The agent served the Performance Analyzer API on port 9600, so the metrics, batch metrics, and root cause analysis (RCA) APIs and the PerfTop dashboards are no longer available. The Performance Analyzer plugin remains installed by default and can publish its metrics using the [metrics framework]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/metrics/), which exports them using OpenTelemetry. For more information, see [Performance Analyzer]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/performance-analyzer/) and issue [#591](https://github.com/opensearch-project/performance-analyzer-rca/issues/591). + +### SQL plugin + +- The OpenSearch query domain-specific language (DSL) response format has been removed. +- `DELETE` statement support has been removed. +- The `plugins.sql.delete.enabled` setting has been removed. +- The legacy Spark Connector module has been deprecated. For information about connecting to Spark, see [`async-query-core`](https://github.com/opensearch-project/sql/blob/main/async-query-core/README.md). +- Deprecated OpenDistro endpoints and legacy settings with the `opendistro` prefix have been removed. +- The `plugins.sql.pagination.api` has been removed and the Scroll API has been deprecated. Pagination now defaults to Point in Time. + +For more information, see issue [#3248](https://github.com/opensearch-project/sql/issues/3248). + +### OpenSearch Dashboards + +- Discover experience: + + - The `discover:newExperience` setting has been removed. + - The DataGrid table feature has been removed. + + For more information, see pull request [#9511](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/9511). + +- Visualizations: The `dashboards-visualizations` plugin (including Gantt chart visualization) has been removed. We recommend transitioning to: + + - Vega visualization for flexible visualization needs. + - Trace analytics for trace-related use cases. + + For more information, see issue [#430](https://github.com/opensearch-project/dashboards-visualizations/issues/430). + +### Dashboards Observability plugin + +The legacy notebooks feature has been removed from `dashboards-observability`. Key changes include the following: + +- Legacy notebooks (previously stored in the `.opensearch-observability` index) are no longer supported. +- Only notebooks stored in the `.kibana` index (introduced in version 2.17) are supported. +- You must migrate your notebooks to the new storage system before upgrading to version 3.0. + +For more information, see issue [#2350](https://github.com/opensearch-project/dashboards-observability/issues/2350). + +### Searchable snapshots node role + +Nodes that use searchable snapshots must have the `warm` node role. Key changes include the following: + +- The `search` role no longer supports searchable snapshots. +- Nodes that handle searchable snapshot shards must be assigned the warm role. +- You must update node role configurations before upgrading to version 3.0 if your cluster uses searchable snapshots. + +For more information, see pull request [#17573](https://github.com/opensearch-project/OpenSearch/pull/17573). + +### Query groups + +Query groups have been renamed to **workload groups**. Key changes include the following: + +- The `wlm/query_group` endpoint is now the `wlm/workload_group` endpoint. +- The API responds with a `workloadGroupID` instead of a `queryGroupID`. +- All workload management cluster settings are now prepended with `wlm.workload_group`. + +For more information, see pull request [#9813](https://github.com/opensearch-project/OpenSearch/pull/17901). + +### ML Commons plugin + +- The `CatIndexTool` is removed in favor of the `ListIndexTool`. +- The Asynchronous Batch Ingestion API (`POST /_plugins/_ml/_batch_ingestion`) is removed. For similar functionality, use [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/). For more information, see pull request [#3688](https://github.com/opensearch-project/ml-commons/pull/3688). + +### Romanian analysis + +The `romanian` analyzer now supports Romanian in its modern Unicode form and normalizes cedilla characters to their comma-based equivalents. Because both forms are still in use, we recommend reindexing existing Romanian documents to ensure consistent analysis and search behavior. + +## 3.10.0 + +The following breaking changes were introduced in OpenSearch 3.10.0. + +### ML Commons plugin + +The validation of private and internal IP addresses has been updated as follows: + +- Link-local addresses (`169.254.0.0/16` and `fe80::/10`) and cloud instance metadata addresses (`fd00:ec2::/32`, `fd20:ce::254`, and `100.100.100.200`) are always refused, regardless of the `plugins.ml_commons.connector.private_ip_enabled` setting. Requests to these addresses fail with the error `Remote inference host name has restricted ip address: `. Any connector using such an endpoint requires a different one. +- IPv6 unique-local addresses (`fc00::/7`) and the local-use NAT64 range (`64:ff9b:1::/48`) are private addresses. Connectors that use them require `plugins.ml_commons.connector.private_ip_enabled` to be `true` and, if `plugins.ml_commons.trusted_connector_private_endpoints_regex` is not empty, a matching expression in that list. +- The `plugins.ml_commons.connector.private_ip_enabled`, `plugins.ml_commons.trusted_connector_private_endpoints_regex`, and `plugins.ml_commons.connector.restricted_ip_patterns` settings also apply to streaming prediction requests that use the `openai/v1/chat/completions` or `gemini/v1beta/generatecontent` interface. These requests connect directly, without a JVM-wide HTTP proxy, and do not follow redirects. + +For more information, see [Connector endpoint settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#connector-endpoint-settings) and pull requests [#5204](https://github.com/opensearch-project/ml-commons/pull/5204) and [#5206](https://github.com/opensearch-project/ml-commons/pull/5206). diff --git a/_about/index.md b/_about/index.md index d2cc011b..d041f749 100644 --- a/_about/index.md +++ b/_about/index.md @@ -5,81 +5,119 @@ nav_order: 1 has_children: false has_toc: false nav_exclude: true +description: "Documentation for OpenSearch and OpenSearch Dashboards, the open-source suite for full-text search, application monitoring, log analytics, and vector search." permalink: /about/ redirect_from: - /docs/opensearch/ - /opensearch/ - /opensearch/index/ +why_use: + - heading: "Vector database" + description: "Use OpenSearch as a vector database to combine the power of traditional search, analytics, and vector search" + link: "/vector-search/" + image: "/images/icons/vector-search-square.png" + image_alt: "Vector search icon" + - heading: "Fast, scalable full-text search" + description: "Help users find the right information in your application, website, or data lake catalog" + link: "/search-plugins/" + image: "/images/icons/Icon_Lexical_Search-150x150.avif" + image_alt: "Lexical search icon" + - heading: "Application and infrastructure monitoring" + description: "Use observability logs, metrics, and traces to monitor your applications in real time" + link: "/observing-your-data/" + image: "/images/icons/Icon_Observability-150x150.avif" + image_alt: "Observability monitoring icon" + - heading: "Data analytics" + description: "Analyze and visualize your data in OpenSearch Dashboards" + link: "/dashboards/" + image: "/images/icons/OpenSearch-Dashboards-Square.png" + image_alt: "OpenSearch Dashboards icon" +features: + - heading: "Install and configure" + description: "Set up OpenSearch and OpenSearch Dashboards on your preferred platform" + link: "/install-and-configure/" + - heading: "Security" + description: "Configure authentication, access control, and encryption for your cluster" + link: "/security/" + - heading: "Index management" + description: "Create indexes, manage templates, and automate index lifecycle" + link: "/im-plugin/" + - heading: "Mappings" + description: "Define field types to control how data is indexed" + link: "/mappings/" + - heading: "API reference" + description: "Full reference for all OpenSearch REST and gRPC APIs" + link: "/api-reference/" + - heading: "Query DSL" + description: "Search your data using the OpenSearch query language" + link: "/query-dsl/" + - heading: "Vector search" + description: "Use vector and AI-powered search to build modern search applications" + link: "/vector-search/" + - heading: "AI and machine learning" + description: "Deploy models, connect to AI platforms, and build AI agents and assistants" + link: "/ml-commons-plugin/" +getting_started: + - heading: "Get started with OpenSearch" + description: "Learn about OpenSearch and start ingesting and searching data" + link: "/getting-started/" + image: "/images/icons/OpenSearch-Core.png" + image_alt: "OpenSearch Core icon" + - heading: "Get started with OpenSearch Dashboards" + description: "Learn about OpenSearch Dashboards applications and tools used to visualize data" + link: "/dashboards/getting-started/" + image: "/images/icons/OpenSearch-Dashboards.png" + image_alt: "OpenSearch Dashboards icon" + - heading: "Get started with vector search" + description: "Learn about vector search options and build your first vector search application" + link: "/vector-search/getting-started/" + image: "/images/icons/Vector-search-icon.avif" + image_alt: "Vector search icon" + - heading: "Get started with OpenSearch security" + description: "Learn about security in OpenSearch" + link: "/security/getting-started/" + image: "/images/icons/OpenSearch-Security.png" + image_alt: "OpenSearch Security icon" + - heading: "Get started with observability" + description: "Send logs to OpenSearch and visualize them in OpenSearch Dashboards" + link: "/observing-your-data/log-ingestion/" + image: "/images/icons/OpenSearch-Observability.png" + image_alt: "OpenSearch Observability icon" + - heading: "Explore tutorials" + description: "Follow step-by-step tutorials for search, vector search, and generative AI applications" + link: "/tutorials/" + image: "/images/icons/Workflow-Icon.avif" + image_alt: "Workflow icon" --- {%- comment -%}The `/docs/opensearch/` redirect is specifically to support the UI links in OpenSearch Dashboards 1.0.0.{%- endcomment -%} -# OpenSearch and OpenSearch Dashboards +# ![OpenSearch icon]({{site.url}}{{site.baseurl}}/images/icons/OpenSearch-Core.png){: .heading-icon} OpenSearch and OpenSearch Dashboards **Version {{site.opensearch_major_minor_version}}** {: .label .label-blue } -This section contains documentation for OpenSearch and OpenSearch Dashboards. +OpenSearch is a scalable, open-source search and analytics suite for full-text search, application monitoring, log analytics, and vector search. OpenSearch Dashboards provides the visualization and management interface. ## Getting started -- [Intro to OpenSearch]({{site.url}}{{site.baseurl}}/intro/) -- [Quickstart]({{site.url}}{{site.baseurl}}/quickstart/) -- [Install OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/) -- [Install OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) -- [See the FAQ](https://opensearch.org/faq) +{% include cards.html cards=page.getting_started %} -## Why use OpenSearch? +## Use cases -With OpenSearch, you can perform the following use cases: +{% include cards.html cards=page.why_use documentation_link=true %} - - - - - - - - - - - - - - - - - - - - - -
Fast, scalable full-text searchApplication and infrastructure monitoringSecurity and event information managementOperational health tracking
Fast, Scalable Full-text SearchApplication and Infrastructure MonitoringSecurity and Event Information ManagementOperational Health Tracking
Help users find the right information within your application, website, or data lake catalog. Easily store and analyze log data, and set automated alerts for underperformance.Centralize logs to enable real-time security monitoring and forensic analysis.Use observability logs, metrics, and traces to monitor your applications and business in real time.
+## Popular documentation -**Additional features and plugins:** +{% include cards.html cards=page.features %} -OpenSearch has several features and plugins to help index, secure, monitor, and analyze your data. Most OpenSearch plugins have corresponding OpenSearch Dashboards plugins that provide a convenient, unified user interface. -- [Anomaly detection]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/) - Identify atypical data and receive automatic notifications -- [KNN]({{site.url}}{{site.baseurl}}/search-plugins/knn/) - Find “nearest neighbors” in your vector data -- [Performance Analyzer]({{site.url}}{{site.baseurl}}/monitoring-plugins/pa/) - Monitor and optimize your cluster -- [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/index/) - Use SQL or a piped processing language to query your data -- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/) - Automate index operations -- [ML Commons plugin]({{site.url}}{{site.baseurl}}/ml-commons-plugin/index/) - Train and execute machine-learning models -- [Asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/) - Run search requests in the background -- [Cross-cluster replication]({{site.url}}{{site.baseurl}}/replication-plugin/index/) - Replicate your data across multiple OpenSearch clusters - - -## The secure path forward -OpenSearch includes a demo configuration so that you can get up and running quickly, but before using OpenSearch in a production environment, you must [configure the Security plugin manually]({{site.url}}{{site.baseurl}}/security/configuration/index/) with your own certificates, authentication method, users, and passwords. - -## Looking for the Javadoc? - -See [opensearch.org/javadocs/](https://opensearch.org/javadocs/). ## Get involved -[OpenSearch](https://opensearch.org) is supported by Amazon Web Services. All components are available under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) on [GitHub](https://github.com/opensearch-project/). -The project welcomes GitHub issues, bug fixes, features, plugins, documentation---anything at all. To get involved, see [Contributing](https://opensearch.org/source.html) on the OpenSearch website. +[OpenSearch](https://opensearch.org) is supported by the OpenSearch Software Foundation. All components are available under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) on [GitHub](https://github.com/opensearch-project/). +The project welcomes GitHub issues, bug fixes, features, plugins, documentation---anything at all. To get involved, see [Contributing](https://github.com/opensearch-project/.github/blob/main/CONTRIBUTING.md). --- -OpenSearch includes certain Apache-licensed Elasticsearch code from Elasticsearch B.V. and other source code. Elasticsearch B.V. is not the source of that other source code. ELASTICSEARCH is a registered trademark of Elasticsearch B.V. \ No newline at end of file + +OpenSearch includes certain Apache-licensed Elasticsearch code from Elasticsearch B.V. and other source code. Elasticsearch B.V. is not the source of that other source code. ELASTICSEARCH is a registered trademark of Elasticsearch B.V. + \ No newline at end of file diff --git a/_about/version-history.md b/_about/version-history.md index 25e34556..de4fc1d1 100644 --- a/_about/version-history.md +++ b/_about/version-history.md @@ -2,52 +2,88 @@ layout: default title: Version history nav_order: 4 +description: "A history of OpenSearch releases, with release highlights and release dates for each version, linked to the full release notes." permalink: /version-history/ --- # Version history -OpenSearch version | Release highlights | Release date -:--- | :--- | :--- -[2.12.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.12.0.md) | Makes concurrent segment search and conversational search generally available. Provides an experimental OpenSearch Assistant Toolkit, including agents and tools, workflow automation, and OpenSearch Assistant for OpenSearch Dashboards UI. Adds a new match-only text field, query insights to monitor top N queries, and k-NN search on nested fields. For a full list of release highlights, see the Release Notes. | 20 February 2024 -[2.11.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.1.md) | Includes maintenance changes and bug fixes for cross-cluster replication, alerting, observability, OpenSearch Dashboards, index management, machine learning, security, and security analytics. For a full list of release highlights, see the Release Notes. | 30 November 2023 -[2.11.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.0.md) | Adds multimodal and sparse neural search capability and the ability to take shallow snapshots that refer to data stored in remote-backed storage. Makes the search comparison tool generally available. Includes a simplified workflow to create threat detectors in Security Analytics and improved security in OpenSearch Dashboards. Experimental features include a new framework and toolset for distributed tracing and updates to conversational search. For a full list of release highlights, see the Release Notes. | 16 October 2023 -[2.10.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.10.0.md) | Makes remote-backed storage generally available. Adds hybrid search capability, custom log types for Security Analytics, IP2Geo ingest processor, and delimited term frequency token filter. Includes a new look and feel for OpenSearch Dashboards and updates the Discover tool. Adds Microsoft Teams webhook support for notifications. Experimental features include concurrent segment search and conversational search. For a full list of release highlights, see the Release Notes. | 25 September 2023 -[2.9.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.9.0.md) | Makes search pipelines and the Neural Search plugin generally available. Adds ML model access control and integration with external ML tools. Implements k-NN byte vectors and efficient filtering with the Faiss engine. Integrates alerting and anomaly detection with OpenSearch Dashboards and adds composite monitors. Adds two new index codec algorithm options. Includes a new ingestion schema for Security Analytics, geoshape aggregations, and extensions---a new mechanism for extending OpenSearch functionality. For a full list of release highlights, see the Release Notes. | 24 July 2023 -[2.8.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.8.0.md) | Adds cross-cluster query with PPL, search pipelines, an option to turn on segment replication as the default replication type, improved searchable snapshot performance, and Amazon OpenSearch Serverless support with SigV4 authentication for multiple data sources. Includes the UI for the flush, refresh, and clear cache operations in OpenSearch Dashboards. For a full list of release highlights, see the Release Notes. | 06 June 2023 -[2.7.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.7.0.md) | Includes searchable snapshots and segment replication, which are now generally available. Adds multiple data sources, observability features, dynamic tenant management, component templates, and shape-based map filters in OpenSearch Dashboards. Includes the flat object field type, hot shard identification, and a new automatic reloading mechanism for ML models. For a full list of release highlights, see the Release Notes. | 02 May 2023 -[2.6.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.6.0.md) | Includes simple schema for observability, index management UI enhancements, Security Analytics enhancements, search backpressure at the coordinator node level, and the ability to add maps to dashboards. Experimental features include a new ML model health dashboard, new text embedding models in ML, and SigV4 authentication in Dashboards. For a full list of release highlights, see the Release Notes. | 28 February 2023 -[2.5.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.5.0.md) | Includes index management UI enhancements, multi-layer maps, Jaeger support for observability, Debian distributions, returning cluster health by awareness attribute, cluster manager task throttling, weighted zonal search request routing policy, and query string support in index rollups. Experimental features include request-level durability in remote-backed storage and GPU acceleration for ML nodes. For a full list of release highlights, see the Release Notes. | 24 January 2023 -[2.4.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.1.md) | Includes maintenance changes and bug fixes for gradle check and indexing pressure tests. Adds support for skipping changelog. | 13 December 2022 -[2.4.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.0.md) | Includes Windows support, Point-in-time search, custom k-NN filtering, xy_point and xy_shape field types for Cartesian coordinates, GeoHex grid aggregation, and resilience enhancements, including search backpressure. In OpenSearch Dashboards, this release adds snapshot restore functionality, multiple authentication, and aggregate view of saved objects. This release includes the following experimental features: searchable snapshots, Compare Search Results, multiple data sources in OpenSearch Dashboards, a new Model Serving Framework in ML Commons, a new Neural Search plugin that supports semantic search, and a new Security Analytics plugin to analyze security logs. For a full list of release highlights, see the Release Notes. | 15 November 2022 -[2.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.3.0.md) | This release includes the following experimental features: segment replication, remote-backed storage, and drag and drop for OpenSearch Dashboards. Experimental features allow you to test new functionality in OpenSearch. Because these features are still being developed, your testing and feedback can help shape the development of the feature before it's official released. We do not recommend use of experimental features in production. Additionally, this release adds maketime and makedate datetime functions for the SQL plugin. Creates a new [OpenSearch Playground](https://playground.opensearch.org) demo site for OpenSearch Dashboards. For a full list of release highlights, see the Release Notes. | 14 September 2022 -[2.2.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.1.md) | Includes gradle updates and bug fixes for gradle check. | 01 September 2022 -[2.2.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.0.md) | Includes support for Logistic Regression and RCF Summarize machine learning algorithms in ML Commons, Lucene or C-based Nmslib and Faiss libraries for approximate k-NN search, search by relevance using SQL and PPL queries, custom region maps for visualizations, and rollup enhancements. For a full list of release highlights, see the Release Notes. | 11 August 2022 -[2.1.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.1.0.md) | Includes support for dedicated ML node in the ML Commons plugin, relevance search and other features in SQL, multi-terms aggregation, and Snapshot Management. For a full list of release highlights, see the Release Notes. | 07 July 2022 -[2.0.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.1.md) | Includes bug fixes and maintenance updates for Alerting and Anomaly Detection. | 16 June 2022 -[2.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0.md) | Includes document-level monitors for alerting, OpenSearch Notifications plugins, and Geo Map Tiles in OpenSearch Dashboards. Also adds support for Lucene 9 and bug fixes for all OpenSearch plugins. For a full list of release highlights, see the Release Notes. | 26 May 2022 -[2.0.0-rc1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0-rc1.md) | The Release Candidate for 2.0.0. This version allows you to preview the upcoming 2.0.0 release before the GA release. The preview release adds document-level alerting, support for Lucene 9, and the ability to use term lookup queries in document level security. | 03 May 2022 -[1.3.15](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.15.md) | Includes bug fixes and maintenance updates for cross-cluster replication, SQL, OpenSearch Dashboards reporting, and alerting. | 05 March 2024 -[1.3.14](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.14.md) | Includes bug fixes and maintenance updates for OpenSearch security and OpenSearch Dashboards security. | 12 December 2023 -[1.3.13](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.13.md) | Includes bug fixes for Anomaly Detection, adds maintenance updates and infrastructure enhancements. | 21 September 2023 -[1.3.12](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.12.md) | Adds maintenance updates for OpenSearch security and OpenSearch Dashboards observability. Includes bug fixes for observability, OpenSearch Dashboards visualizations, and OpenSearch security. | 10 August 2023 -[1.3.11](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.11.md) | Adds maintenance updates for OpenSearch security, OpenSearch Dashboards security, and ML Commons. | 29 June 2023 -[1.3.10](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.10.md) | Adds infrastructure enhancements and maintenance updates for anomaly detection, observability, and security. Includes bug fixes for index management and OpenSearch security. | 18 May 2023 -[1.3.9](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.9.md) | Adds Debian support. Includes upgrades, enhancements, and maintenance updates for OpenSearch core, k-NN, and OpenSearch security. | 16 March 2023 -[1.3.8](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.8.md) | Adds OpenSearch security enhancements. Updates tool scripts to run on Windows. Includes maintenance updates and bug fixes for Anomaly Detection and OpenSearch security. | 02 February 2023 -[1.3.7](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.7.md) | Adds Windows support. Includes maintenance updates and bug fixes for error handling. | 13 December 2022 -[1.3.6](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.6.md) | Includes maintenance updates and bug fixes for tenancy in the OpenSearch Security Dashboards plugin. | 06 October 2022 -[1.3.5](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.5.md) | Includes maintenance updates and bug fixes for gradle check and OpenSearch security. | 01 September 2022 -[1.3.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.4.md) | Includes maintenance updates and bug fixes for OpenSearch and OpenSearch Dashboards. | 14 July 2022 -[1.3.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.3.md) | Adds enhancements to Anomaly Detection and ML Commons. Bug fixes for Anomaly Detection, Observability, and k-NN. | 09 June 2022 -[1.3.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.2.md) | Bug fixes for Anomaly Detection and the Security Dashboards Plugin, adds the option to install OpenSearch using RPM, as well as enhancements to the ML Commons execute task, and the removal of the job-scheduler zip in Anomaly Detection. | 05 May 2022 -[1.3.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.1.md) | Bug fixes when using document-level security, and adjusted ML Commons to use the latest RCF jar and protostuff to RCF model serialization. | 30 March 2022 -[1.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.0.md) | Adds Model Type Validation to Validate Detector API, continuous transforms, custom actions, applied policy parameter to Explain API, default action retries, and new rollover and transition conditions to Index Management, new ML Commons plugin, parse command to SQL, Application Analytics, Live Tail, Correlation, and Events Flyout to Observability, and auto backport and support for OPENSEARCH_JAVA_HOME to Performance Analyzer. Bug fixes. | 17 March 2022 -[1.2.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.4.md) | Updates Performance Analyzer, SQL, and Security plugins to Log4j 2.17.1, Alerting and Job Scheduler to cron-utils 9.1.6, and gson in Anomaly Detection and SQL. | 18 January 2022 -[1.2.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.3.md) | Updates the version of Log4j used in OpenSearch to Log4j 2.17.0 as recommended by the advisory in [CVE-2021-45105](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45105). | 22 December 2021 -[1.2.0](https://github.com/opensearch-project/OpenSearch/blob/main/release-notes/opensearch.release-notes-1.2.0.md) | Adds observability, new validation API for Anomaly Detection, shard-level indexing back-pressure, new "match" query type for SQL and PPL, support for Faiss libraries in k-NN, and custom Dashboards branding. | 23 November 2021 -[1.1.0](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.1.0.md) | Adds cross-cluster replication, security for Index Management, bucket-level alerting, a CLI to help with upgrading from Elasticsearch OSS to OpenSearch, and enhancements to high cardinality data in the anomaly detection plugin. | 05 October 2021 -[1.0.1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.1.md) | Bug fixes. | 01 September 2021 -[1.0.0](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0.md) | General availability release. Adds compatibility setting for clients that require a version check before connecting. | 12 July 2021 -[1.0.0-rc1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-rc1.md) | First release candidate. | 07 June 2021 -[1.0.0-beta1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-beta1.md) | Initial beta release. Refactors plugins to work with OpenSearch. | 13 May 2021 +OpenSearch version | Release highlights | Release date +:--- | :--- | :--- +[3.10.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.1.md) | Updates the bundled JDK to 25.0.5.1+2 to address CVE-2026-114938, a remote code execution vulnerability in OpenJDK 17 and later. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.1.md). | 24 November 2026 +[3.10.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.0.md) | Introduces fusion mode for the `hybrid` query, enabling score normalization and combination directly in the query body without a search pipeline and making hybrid queries nestable inside `bool` and `dis_max` queries. Extends pull-based ingestion to data at rest in object storage (Amazon S3, Google Cloud Storage, and Azure Blob Storage) and adds post-restore hooks so Alerting and ISM resume from snapshot state instead of restarting. Introduces experimental agentic search templates, updated Google Cloud connector blueprints for Gemini, and request throttling for workload groups. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.0.md). | 16 November 2026 +[3.9.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.9.0.md) | Adds the `half_float` vector data type, the `bf16` scalar quantization encoder, 2-bit and 4-bit scalar quantization, and dynamic mapping for `knn_vector` fields. Introduces server-side batch inference for machine learning models and adaptive per-action concurrency limits. Brings anomaly detection and forecasting into the unified alerts view and makes the Resource Sharing and Access Control framework generally available. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.9.0.md). | 29 September 2026 +[3.8.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.8.0.md) | Delivers up to 4.2x faster vector ingestion with Base64-encoded vectors and up to 2.1x higher radial search throughput with improved recall. Extends Model Context Protocol (MCP) support to flow and conversational flow agents, adds a list tools API and connector-level tool description overrides, and introduces experimental retention policies for agentic memory. Adds gRPC streaming for ML predictions and agent execution, expands LLM-as-a-Judge in Search Relevance Workbench to additional models, and adds a Grok debugger in OpenSearch Dashboards. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.8.0.md). | 04 August 2026 +[3.7.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.7.0.md) | Adds native Prometheus integration with PromQL support for unified observability across logs, traces, and metrics. Delivers up to 5.5x faster vector retrieval using doc values and expands hybrid search optimization with z_score normalization and Reciprocal Rank Fusion. Introduces API keys with scoped permissions, ISM policy simulation for safe preview of index lifecycle changes, and a Query Profiler tool in OpenSearch Dashboards. Makes unified agent registration and conversational_v2 agent type generally available for production AI workloads. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.7.0.md). | 09 June 2026 +[3.6.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.6.0.md) | Introduces Agent-v2 with token usage tracking, observability traces, and relevance tuning capabilities. Adds Application Performance Monitoring (APM) to observability with service dependencies and performance metrics. Makes pull-based ingestion generally available with warmup settings and adaptive shard selection. Expands vector search with 1-bit scalar quantization and enhances Query Insights with detailed grouping and failure tracking. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.6.0.md). | 07 April 2026 +[3.5.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.5.0.md) | Introduces agentic conversation memory and context management for intelligent AI applications. Delivers 58% vector search throughput improvements with bulk SIMD implementation for FP16 operations. Expands Prometheus support with native Discover experience and enhanced PPL functions for observability workloads. Makes Search Relevance Workbench generally available with LLM-powered evaluation capabilities. Includes query insights enhancements with automatic user tracking and experimental HTTP/3 transport support. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.5.0.md). | 10 February 2026 +[3.4.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.4.0.md) | Introduces PPL alerting capabilities with monitor execution and stats management. Adds Anomaly Detection Daily Insights Page and Flow Framework enhancements including agent summary and MCP server support. Includes k-NN memory-optimized search warmup, native FP16 vector scoring, and enhanced resource sharing frameworks. Features infrastructure upgrades including JDK 25 and improved access control. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.4.0.md). | 16 December 2025 +[3.3.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.2.md) | Includes maintenance changes and bug fixes for the OpenSearch core engine and ML Commons, Neural Search, Skills, k-NN and Security plugins. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.2.md). | 30 October 2025 +[3.3.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.1.md) | Fixes backward compatibility handling of date fields while maintaining performance optimizations. The `skip_list` parameter is now automatically set to `true` for new `@timestamp` fields created since 3.3.0, while preserving `skip_list=false` for existing indexes with `@timestamp` or index sort date fields. This approach ensures date histogram aggregation performance benefits for new indexes while maintaining compatibility with existing workloads. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.1.md). | 22 October 2025 +[3.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.0.md) | Introduces redesigned Discover interface with log analytics and distributed tracing capabilities, and Apache Calcite as default PPL query engine with expanded functions. Makes agentic search and agentic memory APIs generally available for AI applications. Implements Seismic algorithm for neural sparse search performance improvements and processor chains for data transformation pipelines. Expands gRPC support for additional query types and adds experimental streaming with Apache Arrow Flight. Includes workload management enhancements with rule-based auto-tagging and query monitoring capabilities. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.0.md). | 14 October 2025 +[3.2.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.2.0.md) | Updates Search Relevance Workbench. Makes gRPC APIs generally available. Introduces derived source, updates workload management, semantic field, and star tree functionality. Adds experimental Agentic Memory APIs and Job Scheduler APIs. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.2.0.md). | 19 August 2025 +[3.1.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.1.0.md) | Makes GPU acceleration for vector index builds generally available. Introduces memory-optimized search for Faiss indexes using Lucene HNSW, semantic field type for streamlined semantic search, and Search Relevance Workbench for search quality optimization. Makes star-tree indexes generally available with support for comprehensive query types. Enhances observability with ML Commons metrics integration, custom index support for OpenTelemetry data, and new PPL commands for JSON manipulation. Improves agent management with Update Agent API and persistent MCP tools. Includes security enhancements with immutable user objects and new resource sharing framework. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.1.0.md). | 24 June 2025 +[3.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.0.0.md) | Upgrades to Lucene 10 for improved indexing and vector search. Adds experimental gRPC support and pull-based ingestion from Kafka and Kinesis. Introduces GPU acceleration for vector operations and semantic sentence highlighting. Improves range query performance and hybrid search with z-score normalization. Adds plan-execute-reflect agents and native MCP protocol support for agentic workflows. Enhances security with a new Java agent replacing the Security Manager. Includes PPL query improvements with lookup, join, and subsearch commands. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.0.0.md). | 06 May 2025 +[2.19.8](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.8.md) | Updates the bundled JDK to 21.0.13.1+2 to address CVE-2026-114938, a remote code execution vulnerability in OpenJDK 17 and later. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.8.md). | 23 November 2026 +[2.19.7](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.7.md) | Fixes bugs in alerting, job scheduling, query insights, security, and security analytics. Updates OpenSearch Dashboards dependencies to address CVEs and includes infrastructure and maintenance updates across multiple components. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.7.md). | 20 October 2026 +[2.19.6](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.6.md) | Includes bug fixes, security updates, and infrastructure maintenance across multiple components. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.6.md). | 02 July 2026 +[2.19.5](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.5.md) | Fixes security vulnerabilities with multiple CVE updates across Dashboards plugins including Assistant, Notifications, Observability, and Reporting. Resolves bugs in Alerting, Flow Framework, Security, and k-NN. Includes infrastructure and maintenance updates across multiple components. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.5.md). | 10 March 2026 +[2.19.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.4.md) | Fixes critical security vulnerabilities across multiple components including ML Commons, Query Insights Dashboards, and SQL. Resolves bugs in Flow Framework multi-tenancy, Security wildcard matching, and Query Insights time validation. Includes extensive CVE fixes and dependency updates across dashboards plugins. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.4.md). | 06 November 2025 +[2.19.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.3.md) | Improves Flow Framework with enhanced memory handling and workflow step processing. Fixes several Query Insights and Query Insights Dashboards issues. Implements security updates across multiple components. Updates infrastructure components and documentation across multiple plugins. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.3.md). | 22 July 2025 +[2.19.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.2.md) | Improves query insights with better index handling, a new verbose API parameter, and a default index template. Fixes bugs across Query Insights, Observability, Flow Framework, and Dashboards. Includes multiple CVE fixes, test enhancements, and a new PGP key for artifact verification. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.2.md). | 29 April 2025 +[2.19.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.1.md) | Adds execution hint for cardinality aggregator. Includes bug fixes for ML Commons, Query Insights Dashboards, and Remote Metadata SDK. Contains maintenance updates for several components. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.1.md). | 27 February 2025 +[2.19.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.0.md) | Adds workload management, additional query insights, and template queries. Introduces a query insights page to OpenSearch Dashboards. Includes improvements and bug fixes to snapshots, search statistics, star-tree search, and index management. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.0.md). | 11 February 2025 +[2.18.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.18.0.md) | Adds a redesigned home page, updated Discover interface, and collaborative workspaces to OpenSearch Dashboards. Includes improvements to ML inference processor and query grouping. Introduces reranking by field and paginated CAT APIs. Includes experimental OpenSearch Dashboards Assistant capabilities. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.18.0.md). | 05 November 2024 +[2.17.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.1.md) | Includes bug fixes for ML Commons, anomaly detection, k-NN, and Security Analytics. Adds various infrastructure and maintenance updates. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.1.md). | 1 October 2024 +[2.17.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.0.md) | Includes disk-optimized vector search, binary quantization, and byte vector encoding in k-NN. Adds asynchronous batch ingestion for ML tasks. Provides search and query performance enhancements and a new custom trace source in trace analytics. Includes application-based configuration templates. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.0.md). | 17 September 2024 +[2.16.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.16.0.md) | Includes built-in byte vector quantization and binary vector support in k-NN. Adds new sort, split, and ML inference search processors for search pipelines. Provides application-based configuration templates and additional plugins to integrate multiple data sources in OpenSearch Dashboards. Includes an experimental Batch Predict ML Commons API. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.16.0.md). | 06 August 2024 +[2.15.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.15.0.md) | Includes parallel ingestion processing, SIMD support for exact search, and the ability to disable doc values for the k-NN field. Adds wildcard and derived field types. Improves performance for single-cardinality aggregations, rolling upgrades to remote-backed clusters, and more metrics for top N queries. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.15.0.md). | 25 June 2024 +[2.14.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.14.0.md) | Includes performance improvements to hybrid search and date histogram queries with multi-range traversal, ML model integration within the Ingest API, semantic cache for LangChain applications, low-level vector query interface for neural sparse queries, and improved k-NN search filtering. Provides an experimental tiered cache feature. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.14.0.md). | 14 May 2024 +[2.13.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.13.0.md) | Makes agents and tools and the OpenSearch Assistant Toolkit generally available. Introduces vector quantization within OpenSearch. Adds LLM guardrails and hybrid search with aggregations. Adds the Bloom filter skipping index for Apache Spark data sources, I/O-based admission control, and the ability to add an alerting cluster that manages all alerting tasks. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.13.0.md). | 2 April 2024 +[2.12.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.12.0.md) | Makes concurrent segment search and conversational search generally available. Provides an experimental OpenSearch Assistant Toolkit, including agents and tools, workflow automation, and OpenSearch Assistant for OpenSearch Dashboards UI. Adds a new match-only text field, query insights to monitor top N queries, and k-NN search on nested fields. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.12.0.md). | 20 February 2024 +[2.11.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.1.md) | Includes maintenance changes and bug fixes for cross-cluster replication, alerting, observability, OpenSearch Dashboards, index management, machine learning, security, and Security Analytics. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.1.md). | 30 November 2023 +[2.11.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.0.md) | Adds multimodal and sparse neural search capability and the ability to take shallow snapshots that refer to data stored in remote-backed storage. Makes the search comparison tool generally available. Includes a simplified workflow to create threat detectors in Security Analytics and improved security in OpenSearch Dashboards. Experimental features include a new framework and toolset for distributed tracing and updates to conversational search. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.0.md). | 16 October 2023 +[2.10.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.10.0.md) | Makes remote-backed storage generally available. Adds hybrid search capability, custom log types for Security Analytics, IP2Geo ingest processor, and delimited term frequency token filter. Includes a new look and feel for OpenSearch Dashboards and updates the Discover tool. Adds Microsoft Teams webhook support for notifications. Experimental features include concurrent segment search and conversational search. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.10.0.md). | 25 September 2023 +[2.9.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.9.0.md) | Makes search pipelines and the Neural Search plugin generally available. Adds ML model access control and integration with external ML tools. Implements k-NN byte vectors and efficient filtering with the Faiss engine. Integrates alerting and anomaly detection with OpenSearch Dashboards and adds composite monitors. Adds two new index codec algorithm options. Includes a new ingestion schema for Security Analytics, geoshape aggregations, and extensions---a new mechanism for extending OpenSearch functionality. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.9.0.md). | 24 July 2023 +[2.8.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.8.0.md) | Adds cross-cluster query with PPL, search pipelines, an option to turn on segment replication as the default replication type, improved searchable snapshot performance, and Amazon OpenSearch Serverless support with SigV4 authentication for multiple data sources. Includes the UI for the flush, refresh, and clear cache operations in OpenSearch Dashboards. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.8.0.md). | 06 June 2023 +[2.7.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.7.0.md) | Includes searchable snapshots and segment replication, which are now generally available. Adds multiple data sources, observability features, dynamic tenant management, component templates, and shape-based map filters in OpenSearch Dashboards. Includes the flat object field type, hot shard identification, and a new automatic reloading mechanism for ML models. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.7.0.md). | 02 May 2023 +[2.6.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.6.0.md) | Includes Simple Schema for Observability, index management UI enhancements, Security Analytics enhancements, search backpressure at the coordinating node level, and the ability to add maps to dashboards. Experimental features include a new ML model health dashboard, new text embedding models in ML, and SigV4 authentication in Dashboards. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.6.0.md). | 28 February 2023 +[2.5.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.5.0.md) | Includes index management UI enhancements, multi-layer maps, Jaeger support for observability, Debian distributions, returning cluster health by awareness attribute, cluster manager task throttling, weighted zonal search request routing policy, and query string support in index rollups. Experimental features include request-level durability in remote-backed storage and GPU acceleration for ML nodes. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.5.0.md). | 24 January 2023 +[2.4.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.1.md) | Includes maintenance changes and bug fixes for Gradle check and indexing pressure tests. Adds support for skipping changelog. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.1.md). | 13 December 2022 +[2.4.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.0.md) | Includes Windows support, Point-in-time search, custom k-NN filtering, xy_point and xy_shape field types for Cartesian coordinates, GeoHex grid aggregation, and resilience enhancements, including search backpressure. In OpenSearch Dashboards, this release adds snapshot restore functionality, multiple authentication, and aggregate view of saved objects. This release includes the following experimental features: searchable snapshots, Compare Search Results, multiple data sources in OpenSearch Dashboards, a new Model Serving Framework in ML Commons, a new Neural Search plugin that supports semantic search, and a new Security Analytics plugin to analyze security logs. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.0.md). | 15 November 2022 +[2.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.3.0.md) | This release includes the following experimental features: segment replication, remote-backed storage, and drag and drop for OpenSearch Dashboards. Experimental features allow you to test new functionality in OpenSearch. Because these features are still being developed, your testing and feedback can help shape the development of the feature before it's official released. We do not recommend use of experimental features in production. Additionally, this release adds `maketime` and `makedate` `datetime` functions for the SQL plugin. Creates a new [OpenSearch Playground](https://playground.opensearch.org) demo site for OpenSearch Dashboards. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.3.0.md). | 14 September 2022 +[2.2.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.1.md) | Includes Gradle updates and bug fixes for Gradle check. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.1.md). | 01 September 2022 +[2.2.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.0.md) | Includes support for Logistic Regression and RCF Summarize machine learning algorithms in ML Commons, Lucene or C-based NMSLIB and Faiss libraries for approximate k-NN search, search by relevance using SQL and PPL queries, custom region maps for visualizations, and rollup enhancements. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.0.md). | 11 August 2022 +[2.1.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.1.0.md) | Includes support for dedicated ML node in the ML Commons plugin, relevance search and other features in SQL, multi-terms aggregation, and Snapshot Management. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.1.0.md). | 07 July 2022 +[2.0.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.1.md) | Includes bug fixes and maintenance updates for Alerting and Anomaly Detection. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.1.md). | 16 June 2022 +[2.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0.md) | Includes document-level monitors for alerting, OpenSearch Notifications plugins, and Geo Map Tiles in OpenSearch Dashboards. Also adds support for Lucene 9 and bug fixes for all OpenSearch plugins. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0.md). | 26 May 2022 +[2.0.0-rc1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0-rc1.md) | The Release Candidate for 2.0.0. This version allows you to preview the upcoming 2.0.0 release before the GA release. The preview release adds document-level alerting, support for Lucene 9, and the ability to use term lookup queries in document level security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0-rc1.md). | 03 May 2022 +[1.3.20](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.20.md) | Includes enhancements to Anomaly Detection Dashboards, bug fixes for Alerting and Dashboards Reports, and maintenance updates for several OpenSearch components. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.20.md). | 11 December 2024 +[1.3.19](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.19.md) | Includes bug fixes and maintenance updates for OpenSearch security, OpenSearch security Dashboards, and anomaly detection. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.19.md). | 27 August 2024 +[1.3.18](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.18.md) | Includes maintenance updates for OpenSearch security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.18.md). | 16 July 2024 +[1.3.17](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.17.md) | Includes maintenance updates for OpenSearch security and OpenSearch Dashboards security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.17.md). | 06 June 2024 +[1.3.16](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.16.md) | Includes bug fixes and maintenance updates for OpenSearch security, index management, Performance Analyzer, and reporting. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.16.md). | 23 April 2024 +[1.3.15](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.15.md) | Includes bug fixes and maintenance updates for cross-cluster replication, SQL, OpenSearch Dashboards reporting, and alerting. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.15.md). | 05 March 2024 +[1.3.14](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.14.md) | Includes bug fixes and maintenance updates for OpenSearch security and OpenSearch Dashboards security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.14.md). | 12 December 2023 +[1.3.13](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.13.md) | Includes bug fixes for Anomaly Detection, adds maintenance updates and infrastructure enhancements. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.13.md). | 21 September 2023 +[1.3.12](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.12.md) | Adds maintenance updates for OpenSearch security and OpenSearch Dashboards observability. Includes bug fixes for observability, OpenSearch Dashboards visualizations, and OpenSearch security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.12.md). | 10 August 2023 +[1.3.11](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.11.md) | Adds maintenance updates for OpenSearch security, OpenSearch Dashboards security, and ML Commons. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.11.md). | 29 June 2023 +[1.3.10](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.10.md) | Adds infrastructure enhancements and maintenance updates for anomaly detection, observability, and security. Includes bug fixes for index management and OpenSearch security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.10.md). | 18 May 2023 +[1.3.9](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.9.md) | Adds Debian support. Includes upgrades, enhancements, and maintenance updates for OpenSearch core, k-NN, and OpenSearch security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.9.md). | 16 March 2023 +[1.3.8](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.8.md) | Adds OpenSearch security enhancements. Updates tool scripts to run on Windows. Includes maintenance updates and bug fixes for Anomaly Detection and OpenSearch security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.8.md). | 02 February 2023 +[1.3.7](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.7.md) | Adds Windows support. Includes maintenance updates and bug fixes for error handling. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.7.md). | 13 December 2022 +[1.3.6](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.6.md) | Includes maintenance updates and bug fixes for tenancy in the OpenSearch Security Dashboards plugin. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.6.md). | 06 October 2022 +[1.3.5](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.5.md) | Includes maintenance updates and bug fixes for Gradle check and OpenSearch security. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.5.md). | 01 September 2022 +[1.3.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.4.md) | Includes maintenance updates and bug fixes for OpenSearch and OpenSearch Dashboards. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.4.md). | 14 July 2022 +[1.3.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.3.md) | Adds enhancements to Anomaly Detection and ML Commons. Bug fixes for Anomaly Detection, Observability, and k-NN. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.3.md). | 09 June 2022 +[1.3.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.2.md) | Bug fixes for Anomaly Detection and the Security Dashboards Plugin, adds the option to install OpenSearch using RPM, as well as enhancements to the ML Commons execute task, and the removal of the job-scheduler zip in Anomaly Detection. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.2.md). | 05 May 2022 +[1.3.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.1.md) | Bug fixes when using document-level security, and adjusted ML Commons to use the latest RCF jar and `protostuff` to RCF model serialization. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.1.md). | 30 March 2022 +[1.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.0.md) | Adds Model Type Validation to Validate Detector API, continuous transforms, custom actions, applied policy parameter to Explain API, default action retries, and new rollover and transition conditions to Index Management, new ML Commons plugin, parse command to SQL, Application Analytics, Live Tail, Correlation, and Events Flyout to Observability, and auto backport and support for OPENSEARCH_JAVA_HOME to Performance Analyzer. Bug fixes. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.0.md). | 17 March 2022 +[1.2.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.4.md) | Updates Performance Analyzer, SQL, and Security plugins to Log4j 2.17.1, Alerting and Job Scheduler to cron-utils 9.1.6, and `gson` in Anomaly Detection and SQL. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.4.md). | 18 January 2022 +[1.2.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.3.md) | Updates the version of Log4j used in OpenSearch to Log4j 2.17.0 as recommended by the advisory in [CVE-2021-45105](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45105). For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.3.md). | 22 December 2021 +[1.2.0](https://github.com/opensearch-project/OpenSearch/blob/main/release-notes/opensearch.release-notes-1.2.0.md) | Adds observability, new validation API for Anomaly Detection, shard-level indexing backpressure, new `match` query type for SQL and PPL, support for Faiss libraries in k-NN, and custom Dashboards branding. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/OpenSearch/blob/main/release-notes/opensearch.release-notes-1.2.0.md). | 23 November 2021 +[1.1.0](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.1.0.md) | Adds cross-cluster replication, security for Index Management, bucket-level alerting, a CLI to help with upgrading from Elasticsearch OSS to OpenSearch, and enhancements to high cardinality data in the Anomaly Detection plugin. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.1.0.md). | 05 October 2021 +[1.0.1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.1.md) | Bug fixes. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.1.md). | 01 September 2021 +[1.0.0](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0.md) | General availability release. Adds compatibility setting for clients that require a version check before connecting. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0.md). | 12 July 2021 +[1.0.0-rc1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-rc1.md) | First release candidate. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-rc1.md). | 07 June 2021 +[1.0.0-beta1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-beta1.md) | Initial beta release. Refactors plugins to work with OpenSearch. For a full list of release highlights, see the [Release Notes](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-beta1.md). | 13 May 2021 diff --git a/_aggregations/bucket/adjacency-matrix.md b/_aggregations/bucket/adjacency-matrix.md index fd521f85..4ab5c1a8 100644 --- a/_aggregations/bucket/adjacency-matrix.md +++ b/_aggregations/bucket/adjacency-matrix.md @@ -2,22 +2,40 @@ layout: default title: Adjacency matrix parent: Bucket aggregations -grand_parent: Aggregations nav_order: 10 redirect_from: - /query-dsl/aggregations/bucket/adjacency-matrix/ --- -# Adjacency matrix aggregations +# Adjacency matrix aggregation -The `adjacency_matrix` aggregation lets you define filter expressions and returns a matrix of the intersecting filters where each non-empty cell in the matrix represents a bucket. You can find how many documents fall within any combination of filters. +The `adjacency_matrix` aggregation accepts a set of named filter expressions and returns buckets representing every pair of intersecting filters. Each bucket's document count indicates how many documents matched both filters simultaneously, making it possible to analyze relationships between different document groups. -Use the `adjacency_matrix` aggregation to discover how concepts are related by visualizing the data as graphs. +Given three filters named `A`, `B`, and `C`, the response produces the following bucket structure: -For example, in the sample eCommerce dataset, to analyze how the different manufacturing companies are related: +| | `A` | `B` | `C` | +| :--- | :--- | :--- | :--- | +| `A` | `A` | `A&B` | `A&C` | +| `B` | | `B` | `B&C` | +| `C` | | | `C` | + +The matrix is symmetric---the bucket `A&C` contains the same documents as `C&A`---so only the upper triangle is returned. Filter names are sorted alphabetically, and the name that comes first always appears on the left side of the `&` separator. + +## Parameters + +The `adjacency_matrix` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `filters` | Required | Object | A set of named filters expressed as key-value pairs. Each key is the filter name and each value is a query object. | +| `separator` | Optional | String | The character used to join filter names in intersection bucket keys. Default is `&`. | + +## Example + +The following example analyzes the e-commerce dataset to determine how often products from three manufacturers appear together in the same orders: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { @@ -47,55 +65,83 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response - ```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 +{ + "took": 32, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "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 + } + ] + } + } +} ``` - Let’s take a closer look at the result: +The intersection bucket `grpA&grpB` with `doc_count` of `590` indicates that 590 orders contain products from both Low Tide Media and Elitelligence. - ```json - { - "key" : "grpA&grpB", - "doc_count" : 590 - } - ``` +## Usage with child aggregations -- `grpA`: Products manufactured by Low Tide Media. -- `grpB`: Products manufactured by Elitelligence. -- `590`: Number of products that are manufactured by both. +Nesting a child aggregation such as `date_histogram` inside `adjacency_matrix` adds a time dimension to the relationship data, enabling dynamic network analysis where you can observe how interactions between groups evolve over time. -You can use OpenSearch Dashboards to represent this data with a network graph. \ No newline at end of file +Intersection buckets with zero matching documents are omitted from the response. +{: .note} + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array | A list of buckets representing individual filters and their pairwise intersections. | +| `buckets.key` | String | The filter name for individual filter buckets, or two filter names joined by the separator for intersection buckets. | +| `buckets.doc_count` | Integer | The number of documents matching the filter or filter pair. | + +## Limitations + +The number of buckets grows quadratically with the number of filters. For `N` filters, up to `N(N+1)/2` buckets are produced (`N` individual buckets plus `N*(N-1)/2` intersection buckets). To prevent excessive memory use, the maximum number of filters defaults to `100`. You can adjust this limit per index using the `index.max_adjacency_matrix_filters` setting. + +## Related documentation + +- For a complete example of rendering adjacency matrix results as a network graph in OpenSearch Dashboards, see [Creating a Vega visualization]({{site.url}}{{site.baseurl}}/dashboards/visualize/vega/#creating-a-vega-visualization). \ No newline at end of file diff --git a/_aggregations/bucket/auto-interval-date-histogram.md b/_aggregations/bucket/auto-interval-date-histogram.md new file mode 100644 index 00000000..4570de18 --- /dev/null +++ b/_aggregations/bucket/auto-interval-date-histogram.md @@ -0,0 +1,378 @@ +--- +layout: default +title: Auto-interval date histogram +parent: Bucket aggregations +nav_order: 12 +--- + +# Auto-interval date histogram aggregation + +Similar to the [date histogram aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-histogram/), in which you must specify an interval, the `auto_date_histogram` is a multi-bucket aggregation that automatically creates date histogram buckets based on the number of buckets you provide and the time range of your data. The actual number of buckets returned is always less than or equal to the number of buckets you specify. This aggregation is particularly useful when you are working with time-series data and want to visualize or analyze data over different time intervals without manually specifying the interval size. + +## Intervals + +The bucket interval is chosen based on the collected data to ensure that the number of returned buckets is less than or equal to the requested number. + +The following table lists the possible returned intervals for each time unit. + +| Unit | Intervals | +| :--- | :---| +| Seconds| Multiples of 1, 5, 10, and 30 | +| Minutes| Multiples of 1, 5, 10, and 30 | +| Hours | Multiples of 1, 3, and 12 | +| Days | Multiples of 1 and 7 | +| Months | Multiples of 1 and 3 | +| Years | Multiples of 1, 5, 10, 20, 50, and 100 | + +If an aggregation returns too many buckets (for example, daily buckets), OpenSearch will automatically reduce the number of buckets to ensure a manageable result. Instead of returning the exact number of requested daily buckets, it will reduce them by a factor of about 1/7. For example, if you ask for 70 buckets but the data contains too many daily intervals, OpenSearch might return only 10 buckets, grouping the data into larger intervals (such as weeks) to avoid an overwhelming number of results. This helps optimize the aggregation and prevent excessive detail when too much data is available. + +## Parameters + +Auto-interval date histogram aggregations accept the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`field` | String | The field on which to aggregate. The field must contain the date or timestamp values. Either `field` or `script` is required. +`buckets` | Integer | The desired number of buckets. The returned number of buckets is less than or equal to the desired number. Optional. Default is `10`. +`minimum_interval` | String | The minimum interval to be used. Specifying a minimum interval can make the aggregation process more efficient. Valid values are `year`, `month`, `day`, `hour`, `minute`, and `second`. Optional. +`time_zone` | String | Specifies to use a time zone other than the default (UTC) for bucketing and rounding. You can specify the `time_zone` parameter as a [UTC offset](https://en.wikipedia.org/wiki/UTC_offset), such as `-04:00`, or an [IANA time zone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), such as `America/New_York`. Optional. Default is `UTC`. For more information, see [Time zone](#time-zone). +`format` | String | The format for returning dates representing bucket keys. Optional. Default is the format specified in the field mapping. For more information, see [Date format](#date-format). +`script` | String | A document-level or value-level script for aggregating values into buckets. Either `field` or `script` is required. +`missing` | String | Specifies how to handle documents in which the field value is missing. By default, such documents are ignored. If you specify a date value in the `missing` parameter, all documents in which the field value is missing are collected into the bucket with the specified date. + +## Example + +In the following example, you'll search an index containing blog posts. + +First, create a mapping for this index and specify the `date_posted` field as the `date` type: + +```json +PUT blogs +{ + "mappings" : { + "properties" : { + "date_posted" : { + "type" : "date", + "format" : "yyyy-MM-dd" + } + } + } +} +``` +{% include copy-curl.html %} + +Next, index the following documents into the `blogs` index: + +```json +PUT blogs/_doc/1 +{ + "name": "Semantic search in OpenSearch", + "date_posted": "2022-04-17" +} +``` +{% include copy-curl.html %} + +```json +PUT blogs/_doc/2 +{ + "name": "Sparse search in OpenSearch", + "date_posted": "2022-05-02" +} +``` +{% include copy-curl.html %} + +```json +PUT blogs/_doc/3 +{ + "name": "Distributed tracing with Data Prepper", + "date_posted": "2022-04-25" +} +``` +{% include copy-curl.html %} + +```json +PUT blogs/_doc/4 +{ + "name": "Observability in OpenSearch", + "date_posted": "2023-03-23" +} + +``` +{% include copy-curl.html %} + +To use the `auto_date_histogram` aggregation, specify the field containing the date or timestamp values. For example, to aggregate blog posts by `date_posted` into two buckets, send the following request: + +```json +GET /blogs/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "buckets": 2 + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response shows that the blog posts were aggregated into two buckets. The interval was automatically set to 1 year, with all three 2022 blog posts collected in one bucket and the 2023 blog post in another: + +```json +{ + "took": 20, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "histogram": { + "buckets": [ + { + "key_as_string": "2022-01-01", + "key": 1640995200000, + "doc_count": 3 + }, + { + "key_as_string": "2023-01-01", + "key": 1672531200000, + "doc_count": 1 + } + ], + "interval": "1y" + } + } +} +``` + +## Returned buckets + +Each bucket contains the following information: + +```json +{ + "key_as_string": "2023-01-01", + "key": 1672531200000, + "doc_count": 1 +} +``` + +In OpenSearch, dates are internally stored as 64-bit integers representing timestamps in milliseconds since the epoch. In the aggregation response, each bucket `key` is returned as such a timestamp. The `key_as_string` value shows the same timestamp but formatted as a date string based on the [`format`](#date-format) parameter. The `doc_count` field contains the number of documents in the bucket. + +## Date format + +If you don't specify the `format` parameter, the format defined in the field mapping is used (as seen in the preceding response). To modify the format, specify the `format` parameter: + +```json +GET /blogs/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "format": "yyyy-MM-dd HH:mm:ss" + } + } + } +} +``` +{% include copy-curl.html %} + +The `key_as_string` field is now returned in the specified format: + +```json +{ + "key_as_string": "2023-01-01 00:00:00", + "key": 1672531200000, + "doc_count": 1 +} +``` + +Alternatively, you can specify one of the built-in date [formats]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#formats): + +```json +GET /blogs/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "format": "basic_date_time_no_millis" + } + } + } +} +``` +{% include copy-curl.html %} + +The `key_as_string` field is now returned in the specified format: + +```json +{ + "key_as_string": "20230101T000000Z", + "key": 1672531200000, + "doc_count": 1 +} +``` + +## Time zone + +By default, dates are stored and processed in UTC. The `time_zone` parameter allows you to specify a different time zone for bucketing. You can specify the `time_zone` parameter as a [UTC offset](https://en.wikipedia.org/wiki/UTC_offset), such as `-04:00`, or an [IANA time zone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), such as `America/New_York`. + +As an example, index the following documents into an index: + +```json +PUT blogs1/_doc/1 +{ + "name": "Semantic search in OpenSearch", + "date_posted": "2022-04-17T01:00:00.000Z" +} +``` +{% include copy-curl.html %} + +```json +PUT blogs1/_doc/2 +{ + "name": "Sparse search in OpenSearch", + "date_posted": "2022-04-17T04:00:00.000Z" +} +``` +{% include copy-curl.html %} + +First, run an aggregation without specifying a time zone: + +```json +GET /blogs1/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "buckets": 2, + "format": "yyyy-MM-dd HH:mm:ss" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains two 3-hour buckets, starting at midnight UTC on April 17, 2022: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "histogram": { + "buckets": [ + { + "key_as_string": "2022-04-17 01:00:00", + "key": 1650157200000, + "doc_count": 1 + }, + { + "key_as_string": "2022-04-17 04:00:00", + "key": 1650168000000, + "doc_count": 1 + } + ], + "interval": "3h" + } + } +} +``` + +Now, specify a `time_zone` of `-02:00`: + +```json +GET /blogs1/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "buckets": 2, + "format": "yyyy-MM-dd HH:mm:ss", + "time_zone": "-02:00" + } + } + } +} +``` + +The response contains two buckets in which the start time is shifted by 2 hours and starts at 23:00 on April 16, 2022: + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "histogram": { + "buckets": [ + { + "key_as_string": "2022-04-16 23:00:00", + "key": 1650157200000, + "doc_count": 1 + }, + { + "key_as_string": "2022-04-17 02:00:00", + "key": 1650168000000, + "doc_count": 1 + } + ], + "interval": "3h" + } + } +} +``` + +When using time zones with daylight saving time (DST) changes, the sizes of buckets that are near the transition may differ slightly from the sizes of neighboring buckets. +{: .note} diff --git a/_aggregations/bucket/children.md b/_aggregations/bucket/children.md new file mode 100644 index 00000000..6015917c --- /dev/null +++ b/_aggregations/bucket/children.md @@ -0,0 +1,158 @@ +--- +layout: default +title: Children +parent: Bucket aggregations +nav_order: 15 +--- + +# Children aggregation + +The `children` aggregation is a bucket aggregation that creates a single bucket containing child documents, based on parent-child relationships defined in your index. + +The `children` aggregation works with the [join field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) to aggregate child documents that are associated with parent documents. + +The `children` aggregation identifies child documents that match specific child relation name, whereas the [`parent` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/parent/) identifies parent documents that have matching child documents. Both aggregations take the child relation name as input. + +## Parameters + +The `children` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `type` | Required | String | The name of the child type from the join field. This identifies the parent-child relationship to use. | + + +## Example + +The following example builds a small company database with three employees. The employee records each have a child `join` relationship with a parent department record. + +First, create a `company` index with a `join` field that maps departments (parents) to employees (children): + +```json +PUT /company +{ + "mappings": { + "properties": { + "join_field": { + "type": "join", + "relations": { + "department": "employee" + } + }, + "department_name": { + "type": "keyword" + }, + "employee_name": { + "type": "keyword" + }, + "salary": { + "type": "double" + }, + "hire_date": { + "type": "date" + } + } + } +} +``` +{% include copy-curl.html %} + +Next, populate the data with three departments and three employees. The parent-child assignments are presented in the following table. + +| Department (parent) | Employees (children) | +| :-- | :-- | +| `Accounting` | `Abel Anderson`, `Betty Billings` | +| `Engineering` | `Carl Carter` | +| `HR` | none | + +The `routing` parameter ensures that both parent and child documents are stored on the same shard, which is required in order for parent-child relationships to function correctly in OpenSearch: + +```json +POST _bulk?routing=1 +{ "create": { "_index": "company", "_id": "1" } } +{ "type": "department", "department_name": "Accounting", "join_field": "department" } +{ "create": { "_index": "company", "_id": "2" } } +{ "type": "department", "department_name": "Engineering", "join_field": "department" } +{ "create": { "_index": "company", "_id": "3" } } +{ "type": "department", "department_name": "HR", "join_field": "department" } +{ "create": { "_index": "company", "_id": "4" } } +{ "type": "employee", "employee_name": "Abel Anderson", "salary": 120000, "hire_date": "2024-04-04", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "5" } } +{ "type": "employee", "employee_name": "Betty Billings", "salary": 140000, "hire_date": "2023-05-05", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "6" } } +{ "type": "employee", "employee_name": "Carl Carter", "salary": 140000, "hire_date": "2020-06-06", "join_field": { "name": "employee", "parent": "2" } } +``` +{% include copy-curl.html %} + +The following request queries all the departments and then filters for the one named `Accounting`. It then uses the `children` aggregation to select the two documents that have a child relationship with the `Accounting` department. Finally, the `avg` subaggregation returns the average of the `Accounting` employees' salaries: + +```json +GET /company/_search +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "term": { + "join_field": "department" + } + }, + { + "term": { + "department_name": "Accounting" + } + } + ] + } + }, + "aggs": { + "acc_employees": { + "children": { + "type": "employee" + }, + "aggs": { + "avg_salary": { + "avg": { + "field": "salary" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response returns the selected department bucket, finds the `employee` type children of the department, and computes the `avg` of their salaries: + +```json +{ + "took": 379, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "acc_employees": { + "doc_count": 2, + "avg_salary": { + "value": 130000 + } + } + } +} +``` \ No newline at end of file diff --git a/_aggregations/bucket/composite.md b/_aggregations/bucket/composite.md new file mode 100644 index 00000000..96be564e --- /dev/null +++ b/_aggregations/bucket/composite.md @@ -0,0 +1,825 @@ +--- +layout: default +title: Composite +parent: Bucket aggregations +nav_order: 17 +redirect_from: + - /query-dsl/aggregations/bucket/composite/ +--- + +# Composite aggregation + +The `composite` aggregation creates buckets based on one or more document fields or sources. The `composite` aggregation creates a bucket for every combination of individual source values. By default, combinations with a missing value in one or more individual fields are omitted from the results. + +Each source has one of four types of aggregation: + +- The `terms` type groups by a unique (usually `String`) value. +- The `histogram` type groups numerically in buckets of a specified width. +- The `date_histogram` type groups by date or time ranges of a specified width. +- The `geotile_grid` type groups geopoints into a grid with a specified resolution. + +The `composite` aggregation works by combining its source keys into buckets. The resulting buckets are ordered, both across and within the sources: + +- **Across**: Buckets are nested in the order that the sources are ordered in the aggregation request. +- **Within**: The order of values in each source determines the bucket order for that source. Ordering is alphabetical, numeric, date-time, or geo-tile, as appropriate to the source type. + +Consider these fields from an index of marathon participants: + +```json +{... "city": "Albuquerque", "place": "Bronze" ...} +{... "city": "Boston", ...} +{... "city": "Chicago", "place": "Bronze" ...} +{... "city": "Albuquerque", "place": "Gold" ...} +{... "city": "Chicago", "place": "Silver" ...} +{... "city": "Boston", "place": "Bronze" ...} +{... "city": "Chicago", "place": "Gold" ...} +``` + +Assume the request specifies the sources as follows: + +```json + ... + "sources": [ + { "marathon_city": { "terms": { "field": "city" }}}, + { "participant_medal": { "terms": { "field": "place" }}} + ], + ... +``` + +You must assign a unique key name to each source. +{: .important} + +The resulting `composite` contains the following buckets, in order: + +```json +{ "city": "Albuquerque", "place": "Bronze" } +{ "city": "Albuquerque", "place": "Gold" } +{ "city": "Boston", "place": "Bronze" } +{ "city": "Boston", "place": "Silver" } +{ "city": "Chicago", "place": "Bronze" } +{ "city": "Chicago", "place": "Gold" } +{ "city": "Chicago", "place": "Silver" } +``` + +Note that the `city` and `place` fields are both ordered alphabetically. + +## Parameters + +The `composite` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `sources` | Required | Array | An array of source objects. Valid types are [`terms`](#terms), [`histogram`](#histogram), [`date_histogram`](#date-histogram), and [`geotile_grid`](#geotile-grid). | +| `size` | Optional | Numeric | The number of `composite` buckets to return in the results. The default value is `10`. See [Paginating composite results](#paginating-composite-results). | +| `after` | Optional | String | A key that specifies where to resume displaying paginated `composite` buckets. See [Paginating composite results](#paginating-composite-results). | +| `order` | Optional | String | For each source, whether to order the values in ascending or descending order. Valid values are `asc` and `desc`. Default is `asc`. | +| `missing_bucket` | Optional | Boolean | For each source, whether to include documents with a missing value. The default value is `false`. If set to `true`, OpenSearch includes the documents, supplying `null` as the field's key. Null values rank first in ascending order. | + +For aggregation-specific parameters, see the corresponding aggregation documentation. +{: .note} + +## Terms + +Use a `terms` aggregation for aggregating string or Boolean data. For more information, see [Terms aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/). + +You can use `terms` sources to create composite buckets for any type of data. However, since `terms` sources create buckets for every unique value, you'll normally use `histogram` sources for numerical data instead. +{: .note} + +The following example request returns the first `4` composite buckets for day of the week and customer gender in the OpenSearch Dashboards sample e-commerce data: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "day": { "terms": { "field": "day_of_week" }}}, + { "gender": { "terms": { "field": "customer_gender" }}} + ], + "size": 4 + } + } + } +} +``` +{% include copy-curl.html %} + +Since the dataset for this example contains valid data for every bucket, the aggregation generates a bucket for every combination of gender and day of the week, resulting in 14 total buckets. + +Because the request specifies a `size` of `4`, the response contains the first four composite buckets. Since the sources are `terms`, the buckets are ordered in ascending alphabetical order, both across and within the sources: + +```json +{ + "took": 51, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "day": "Monday", + "gender": "MALE" + }, + "buckets": [ + { + "key": { + "day": "Friday", + "gender": "FEMALE" + }, + "doc_count": 399 + }, + { + "key": { + "day": "Friday", + "gender": "MALE" + }, + "doc_count": 371 + }, + { + "key": { + "day": "Monday", + "gender": "FEMALE" + }, + "doc_count": 320 + }, + { + "key": { + "day": "Monday", + "gender": "MALE" + }, + "doc_count": 259 + } + ] + } + } +} +``` + +You can use the `after_key` returned in the response to view more results. See the example in the next section. + +## Histogram + +Use `histogram` sources to create composite aggregations of numerical data. For more information, see [Histogram aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/histogram/). + +For `histogram` sources, the name used in each `composite` bucket key is the lowest value in the key's histogram interval. Each source histogram interval contains the values in the `[lower_bound, lower_bound + interval)` range. The name of the first interval is the lowest value in the source field (for ascending-value sources). + +The following example request returns the first `6` composite buckets for quantity and base unit price in the OpenSearch Dashboards sample e-commerce data based on bucket widths of `1` and `50`, respectively: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "quantity": { "histogram": { "field": "products.quantity", "interval": 1 }}}, + { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 50 }}} + ], + "size": 6 + } + } + } +} +``` +{% include copy-curl.html %} + +The aggregation returns the first `6` bucket keys and document counts for the two `histogram` sources. As in the `terms` example, the buckets are ordered across and within the source fields. In this case, however, the order is numerical and is based on the inclusive lower bound of each histogram width: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "quantity": 2, + "unit_price": 150 + }, + "buckets": [ + { + "key": { + "quantity": 1, + "unit_price": 0 + }, + "doc_count": 17691 + }, + { + "key": { + "quantity": 1, + "unit_price": 50 + }, + "doc_count": 5014 + }, + { + "key": { + "quantity": 1, + "unit_price": 100 + }, + "doc_count": 482 + }, + { + "key": { + "quantity": 1, + "unit_price": 150 + }, + "doc_count": 148 + }, + { + "key": { + "quantity": 1, + "unit_price": 200 + }, + "doc_count": 32 + }, + { + "key": { + "quantity": 2, + "unit_price": 150 + }, + "doc_count": 4 + } + ] + } + } +} +``` + +The bucket key for each field is the lower bound of the field interval. For example, the `unit_price` key for the first `composite` bucket is `0`. + +To retrieve the next `6` buckets, supply the `after` parameter with the `after_key` object from the response as follows: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "quantity": { "histogram": { "field": "products.quantity", "interval": 1 }}}, + { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 50 }}} + ], + "size": 6, + "after": { + "quantity": 2, + "unit_price": 150 + } + } + } + } +} +``` +{% include copy-curl.html %} + +There are only two buckets remaining: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "quantity": 2, + "unit_price": 500 + }, + "buckets": [ + { + "key": { + "quantity": 2, + "unit_price": 200 + }, + "doc_count": 8 + }, + { + "key": { + "quantity": 2, + "unit_price": 500 + }, + "doc_count": 4 + } + ] + } + } +} +``` + +## Date histogram + +To create composite aggregations of date ranges, use the `date_histogram` aggregation. For more information, see [Date histogram aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-histogram/). + +OpenSearch represents dates, including `date_interval` bucket keys, as `long` integers representing milliseconds since the epoch in [Unix time](https://en.wikipedia.org/wiki/Unix_time). You can format the date output using the `format` parameter. This does not change the key order. + +OpenSearch stores date-times in UTC. You can display output results in a different time zone using the `time_zone` parameter. + +The following example request returns the first `4` composite buckets for the year in which each sold product was created and the date on which it was sold in the OpenSearch Dashboards sample e-commerce data, based on bucket widths of 1 year and 1 day, respectively: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "product_creation_date": { "date_histogram": { "field": "products.created_on", "calendar_interval": "1y", "format": "yyyy" }}}, + { "order_date": { "date_histogram": { "field": "order_date", "calendar_interval": "1d", "format": "yyyy-MM-dd" }}} + ], + "size": 4 + } + } + } +} +``` +{% include copy-curl.html %} + +The aggregation returns the formatted date-based bucket keys and counts. For the `date_interval` composite aggregation, field ordering is by date: + +```json +{ + "took": 21, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "product_creation_date": "2016", + "order_date": "2025-02-23" + }, + "buckets": [ + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-20" + }, + "doc_count": 146 + }, + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-21" + }, + "doc_count": 153 + }, + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-22" + }, + "doc_count": 143 + }, + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-23" + }, + "doc_count": 140 + } + ] + } + } +} +``` + +## Geotile grid + +Use `geotile_grid` sources to aggregate `geo_point` values into buckets representing map tiles. As with the other composite aggregation sources, by default, results include only buckets containing data. For more information, see [Geotile grid aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/geotile-grid/). + +Each cell corresponds to a [map tile](https://en.wikipedia.org/wiki/Tiled_web_map). Cell labels use the `{zoom}/{x}/{y}` format. + +The following example request returns the first `6` tiles containing locations from the `geoip.location` field at a precision of `8`: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "tile": { "geotile_grid": { "field": "geoip.location", "precision": 8 } } } + ], + "size": 6 + } + } + } +} +``` +{% include copy-curl.html %} + +The aggregation returns the specified `geo_tiles` and point counts: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "tile": "8/122/104" + }, + "buckets": [ + { + "key": { + "tile": "8/43/102" + }, + "doc_count": 310 + }, + { + "key": { + "tile": "8/75/96" + }, + "doc_count": 896 + }, + { + "key": { + "tile": "8/75/124" + }, + "doc_count": 178 + }, + { + "key": { + "tile": "8/122/104" + }, + "doc_count": 408 + } + ] + } + } +} +``` + +## Combining sources + +You can combine two or more sources of any different type. + +The following example request returns buckets composed of three different source types: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "order_date": { "date_histogram": { "field": "order_date", "calendar_interval": "1M", "format": "yyyy-MM" }}}, + { "gender": { "terms": { "field": "customer_gender" }}}, + { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 200 }}} + ], + "size": 10 + } + } + } +} +``` + +The aggregation returns the mixed-type `composite` buckets and document counts: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "order_date": "2025-03", + "gender": "MALE", + "unit_price": 200 + }, + "buckets": [ + { + "key": { + "order_date": "2025-02", + "gender": "FEMALE", + "unit_price": 0 + }, + "doc_count": 1517 + }, + { + "key": { + "order_date": "2025-02", + "gender": "MALE", + "unit_price": 0 + }, + "doc_count": 1369 + }, + { + "key": { + "order_date": "2025-02", + "gender": "MALE", + "unit_price": 200 + }, + "doc_count": 6 + }, + { + "key": { + "order_date": "2025-02", + "gender": "MALE", + "unit_price": 400 + }, + "doc_count": 1 + }, + { + "key": { + "order_date": "2025-03", + "gender": "FEMALE", + "unit_price": 0 + }, + "doc_count": 3656 + }, + { + "key": { + "order_date": "2025-03", + "gender": "FEMALE", + "unit_price": 200 + }, + "doc_count": 1 + }, + { + "key": { + "order_date": "2025-03", + "gender": "MALE", + "unit_price": 0 + }, + "doc_count": 3530 + }, + { + "key": { + "order_date": "2025-03", + "gender": "MALE", + "unit_price": 200 + }, + "doc_count": 7 + } + ] + } + } +} +``` + +## Subaggregations + +Composite aggregations are most useful when combined with subaggregations that reveal information about the documents in the `composite` buckets. + +The following example request compares average spending based on gender for each day of the week in the OpenSearch Dashboards sample e-commerce data: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "weekday": { "terms": { "field": "day_of_week" }}}, + { "gender": { "terms": { "field": "customer_gender" }}} + ], + "size": 6 + }, + "aggs": { + "avg_spend": { + "avg": { "field": "taxful_total_price" } + } + } + } + } +} +``` + +The aggregation returns the average `taxful_total_price` of the first `6` buckets: + +```json +{ + "took": 30, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "weekday": "Saturday", + "gender": "MALE" + }, + "buckets": [ + { + "key": { + "weekday": "Friday", + "gender": "FEMALE" + }, + "doc_count": 399, + "avg_spend": { + "value": 71.7733395989975 + } + }, + { + "key": { + "weekday": "Friday", + "gender": "MALE" + }, + "doc_count": 371, + "avg_spend": { + "value": 79.72514108827494 + } + }, + { + "key": { + "weekday": "Monday", + "gender": "FEMALE" + }, + "doc_count": 320, + "avg_spend": { + "value": 72.1588623046875 + } + }, + { + "key": { + "weekday": "Monday", + "gender": "MALE" + }, + "doc_count": 259, + "avg_spend": { + "value": 86.1754946911197 + } + }, + { + "key": { + "weekday": "Saturday", + "gender": "FEMALE" + }, + "doc_count": 365, + "avg_spend": { + "value": 73.53236301369863 + } + }, + { + "key": { + "weekday": "Saturday", + "gender": "MALE" + }, + "doc_count": 371, + "avg_spend": { + "value": 72.78092360175202 + } + } + ] + } + } +} +``` + +## Paginating composite results + +If a request results in more than `size` buckets, then `size` buckets are returned. In this case, the results contain an `after_key` object containing the key of the next bucket in the list. To retrieve the next `size` buckets of the request, send the request again, supplying the `after_key` in the `after` parameter. For an example, see the request in [Histogram](#histogram). + +Always use the `after_key` rather than copying the last bucket to continue a paginated response. The two are sometimes different. +{: .important} + +## Improving performance with index sorting + +To speed up composite aggregations on large datasets, you can sort your index using the same fields and order used in your aggregation sources. When the `index.sort.field` and `index.sort.order` match the source fields and order used in the composite aggregation, OpenSearch can return results more efficiently and with less memory usage. While index sorting adds minor overhead during indexing, the query performance gains for composite aggregations are significant. + +The following example request sets sort fields and a sort order for each of the fields in the `my-sorted-index` index: + +```json +PUT /my-sorted-index +{ + "settings": { + "index": { + "sort.field": ["customer_id", "timestamp"], + "sort.order": ["asc", "desc"] + } + }, + "mappings": { + "properties": { + "customer_id": { + "type": "keyword" + }, + "timestamp": { + "type": "date" + }, + "price": { + "type": "double" + } + } + } +} +``` +{% include copy-curl.html %} + +The following request creates a composite aggregation on the `my-sorted-index` index. Because the index is sorted by `customer_id` in ascending order and `timestamp` in descending order and the aggregation sources match that sort order, this query runs faster and with reduced memory pressure: + +```json +GET /my-sorted-index/_search +{ + "size": 0, + "aggs": { + "my_buckets": { + "composite": { + "size": 1000, + "sources": [ + { "customer": { "terms": { "field": "customer_id", "order": "asc" } } }, + { "time": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } } + ] + } + } + } +} +``` +{% include copy-curl.html %} \ No newline at end of file diff --git a/_aggregations/bucket/date-histogram.md b/_aggregations/bucket/date-histogram.md index e308104e..631dd3b6 100644 --- a/_aggregations/bucket/date-histogram.md +++ b/_aggregations/bucket/date-histogram.md @@ -2,27 +2,134 @@ layout: default title: Date histogram parent: Bucket aggregations -grand_parent: Aggregations nav_order: 20 redirect_from: - /query-dsl/aggregations/bucket/date-histogram/ --- -# Date histogram aggregations +# Date histogram aggregation -The `date_histogram` aggregation uses [date math]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/date/#date-math) to generate histograms for time-series data. +The `date_histogram` aggregation groups documents in a [date]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/) field into time-based buckets. Use it to roll up metrics per hour, day, or month, chart traffic trends, or fill time series dashboards. -For example, you can find how many hits your website gets per month: +## Choosing an interval + +The `date_histogram` aggregation supports two interval styles: + +- The `calendar_interval` parameter aligns buckets to calendar boundaries, such as days, months, or years. Use it when focusing on real-world calendar periods, for example, `day`, `1M`, or `year`. +- The `fixed_interval` parameter uses exact durations measured in [SI units](https://en.wikipedia.org/wiki/International_System_of_Units). Buckets are always the same length, independent of daylight saving time or month length, for example, `5m`, `12h`, or `30d`. + +### Calendar intervals + +Calendar intervals account for months of different lengths and for days that are shorter or longer because of daylight saving time changes. Each interval in the following table has two equivalent names. A calendar interval can't be a multiple. For example, `2d` returns an error. For a multi-day bucket, use `fixed_interval`. + +| Interval | Description | +| :--- | :--- | +| `minute`, `1m` | Starts at 00 seconds of each minute. | +| `hour`, `1h` | Starts at 00 minutes and 00 seconds of each hour. | +| `day`, `1d` | Starts at the beginning of each day, usually midnight, in the specified time zone. | +| `week`, `1w` | Starts on Monday of each week. | +| `month`, `1M` | Starts on the first day of each month. | +| `quarter`, `1q` | Starts on the first day of each quarter: January 1, April 1, July 1, or October 1. | +| `year`, `1y` | Starts on January 1 of each year. | + +### Fixed intervals + +Fixed intervals are always the same number of milliseconds, so you can specify any multiple of a unit, such as `90m` or `12h`. Because the length of a month or quarter varies, these units are not accepted as fixed intervals. Fractional values, such as `2.5d`, are not supported. To specify a fractional interval, use a smaller unit, for example, `60h`. For the abbreviations you can use in intervals, see [Units]({{site.url}}{{site.baseurl}}/api-reference/units/). + +The following table lists the accepted units for fixed intervals. + +| Unit | Description | +| :--- | :--- | +| `ms` | Milliseconds. | +| `s` | Seconds. Each second is 1,000 milliseconds. | +| `m` | Minutes. Each minute is 60 seconds. | +| `h` | Hours. Each hour is 60 minutes. | +| `d` | Days. Each day is exactly 24 hours, regardless of daylight saving time changes. | + +Fixed-interval buckets are aligned to the start of the Unix epoch, not to the start of the day. For example, with a `fixed_interval` of `90m`, buckets start at times such as 07:30 and 09:00 UTC. To shift the bucket start times, use the [`offset`](#example-shift-bucket-start-times-using-an-offset) parameter. + +### Bucket keys + +Each bucket contains a `key`, which is the bucket's start time as the number of milliseconds since the Unix epoch, and a `key_as_string`, which is the same time formatted as a date string. The `key_as_string` uses the date format specified in the `format` parameter. If you don't specify `format`, OpenSearch uses the date format from the field mapping. + +OpenSearch places each document in a bucket by rounding its date value down to the start of the interval. If you specify a `time_zone`, OpenSearch converts the value to local time, rounds it down, and converts the result back to UTC. The `key` is always in UTC milliseconds, while the `key_as_string` is shown in the requested time zone. + +The `date_histogram` aggregation also works on [`date_range`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/range/) fields. A document is counted in every bucket that its range overlaps. For example, a booking from March 31 to April 2 is counted in the daily buckets for March 31, April 1, and April 2. + +The legacy `interval` field is kept for compatibility but is deprecated. Use `calendar_interval` or `fixed_interval` instead. +{: .note} + + +## Parameters + +The `date_histogram` aggregation supports the following parameters. + +| Parameter | Required | Type | Description | +|:--|:--|:--|:--| +| `field` | One of the following is required: `field` or `script`. | String | The date field to bucket on. | +| `calendar_interval` | One of the following is required: `calendar_interval`, `fixed_interval`, or legacy `interval`. | String | The calendar-aware interval (for example, `day`, `1M`, `year`). Only singular calendar units are supported. | +| `fixed_interval` | One of the following is required: `calendar_interval`, `fixed_interval`, or legacy `interval`. | String | The fixed interval, for example, `5m`, `12h`, `30d`. Not for calendar units like months or quarters. | +| `time_zone` | Optional | String | The time zone used for bucketing and formatting. Accepts a time zone, such as `Europe/Dublin`, or UTC offsets, such as `-07:00`. | +| `format` | Optional | String | The output date format used for `key_as_string`, for example, `yyyy-MM-dd`. If omitted, mapping defaults apply. | +| `offset` | Optional | String | Shifts bucket boundaries by a positive or negative interval, for example, `+8h`, `-30m`. Calculated after `time_zone` is applied. | +| `min_doc_count` | Optional | Integer | The minimum number of documents required in order to return a bucket. Default is `0`, which includes empty buckets between the first and last documents. To include empty buckets beyond the range of the data, use `extended_bounds`. | +| `extended_bounds` | Optional | Object | Extends the range of buckets beyond your data: `{"min": "", "max": ""}`. | +| `hard_bounds` | Optional | Object | Strictly limits buckets to a range: `{"min": "", "max": ""}`. Buckets outside the range are never created. | +| `missing` | Optional | Date string | Treats documents missing the field as if they had this date value. | +| `keyed` | Optional | Boolean | When `true`, returns buckets as an object keyed by the formatted date string. | +| `order` | Optional | Object | Sorts buckets by `_key` or `_count`, ascending or descending. | +| `script` | One of the following is required: `field` or `script`. | Object | A script that generates the date value for each document or, when used with `field`, modifies each field value. Scripts run on every matching document, so they add overhead. For more information, see [Example: Use a script](#example-use-a-script). | + +## Example setup + +The examples on this page use a `my-logs` index containing timestamps around the start of daylight saving time in Europe on March 30, 2025. Create the index: ```json -GET opensearch_dashboards_sample_data_logs/_search +PUT my-logs +{ + "mappings": { + "properties": { + "timestamp": { "type": "date" } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents: + +```json +POST my-logs/_bulk?refresh +{ "index": { "_id": "1" } } +{ "timestamp": "2025-03-31T08:10:00Z" } +{ "index": { "_id": "2" } } +{ "timestamp": "2025-03-31T08:40:00Z" } +{ "index": { "_id": "3" } } +{ "timestamp": "2025-03-31T10:05:00Z" } +{ "index": { "_id": "4" } } +{ "timestamp": "2025-03-31T23:30:00Z" } +{ "index": { "_id": "5" } } +{ "timestamp": "2025-04-01T05:15:00Z" } +{ "index": { "_id": "6" } } +{ "timestamp": "2025-04-01T14:20:00Z" } +{ "index": { "_id": "7" } } +{ "timestamp": "2025-04-02T09:00:00Z" } +``` +{% include copy-curl.html %} + +## Example: Monthly buckets (calendar interval) + +The following request counts documents per calendar month: + +```json +GET my-logs/_search { "size": 0, "aggs": { "logs_per_month": { "date_histogram": { - "field": "@timestamp", - "interval": "month" + "field": "timestamp", + "calendar_interval": "1M" } } } @@ -30,32 +137,598 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +The response contains one bucket for March and one for April: ```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 - } - ] +{ + "aggregations": { + "logs_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 4 + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 3 + } + ] + } } } -} ``` -The response has three months worth of logs. If you graph these values, you can see the peak and valleys of the request traffic to your website month over month. +## Example: Uniform hourly buckets (fixed interval) + +The following request retrieves buckets with a fixed interval of exactly 1 hour, regardless of daylight saving time changes: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "by_hour": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "1h" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains 50 hourly buckets, from `2025-03-31T08:00:00.000Z` through `2025-04-02T09:00:00.000Z`. Because `min_doc_count` defaults to `0`, the response includes empty buckets for the hours between the first and last documents. + +## Example: Use a time zone + +By default, bucketing occurs in UTC. Set `time_zone` to align bucket boundaries to a specific time zone. + +The following request retrieves daily buckets using `Europe/Dublin`: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "by_day_ie": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "day", + "time_zone": "Europe/Dublin" + } + } + } +} +``` +{% include copy-curl.html %} + +After March 30, 2025, Dublin is one hour ahead of UTC, so document 4 (`2025-03-31T23:30:00Z`) falls on April 1 in Dublin time. In UTC, the three daily buckets contain 4, 2, and 1 documents. In Dublin time, they contain 3, 3, and 1 documents. Each `key_as_string` shows midnight in Dublin (`+01:00`), while each `key` is the same moment in UTC milliseconds: + +```json +{ + "aggregations": { + "by_day_ie": { + "buckets": [ + { + "key_as_string": "2025-03-31T00:00:00.000+01:00", + "key": 1743375600000, + "doc_count": 3 + }, + { + "key_as_string": "2025-04-01T00:00:00.000+01:00", + "key": 1743462000000, + "doc_count": 3 + }, + { + "key_as_string": "2025-04-02T00:00:00.000+01:00", + "key": 1743548400000, + "doc_count": 1 + } + ] + } + } +} +``` + +> In time zones that observe daylight saving time, buckets that include a time change can be shorter or longer than the requested interval. For example, in the `Europe/Dublin` time zone: +> +> - The daily bucket for March 30, 2025, when clocks moved forward, covers only 23 hours, and the daily bucket for October 26, 2025, when clocks moved back, covers 25 hours. +> - Hourly buckets are not lengthened when clocks move back. Instead, the repeated hour appears as two separate buckets with the same local time and different offsets, such as `2025-10-26T01:00:00.000+01:00` and `2025-10-26T01:00:00.000Z`. +> - If a bucket boundary falls on a local time that doesn't exist because clocks moved forward, the boundary moves to the next valid time. For example, with an `offset` of `+1h`, the March 30 bucket starts at 02:00 instead of 01:00. +{: .warning} + +Test your aggregations around time changes to make sure that the buckets match your expectations, and keep all servers and clients synchronized with a reliable time source, such as NTP. +{: .tip} + +## Example: Shift bucket start times using an offset + +Use the `offset` parameter to move the bucket boundary forward or backward, for example, to define a "reporting day" that runs 08:00–08:00 instead of midnight–midnight: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "by_day_shifted": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "day", + "offset": "+8h" + } + } + } +} +``` +{% include copy-curl.html %} + +Documents 1--5 were recorded between 08:00 on March 31 and 08:00 on April 1, so they are all counted in the reporting day that starts on March 31: + +```json +{ + "aggregations": { + "by_day_shifted": { + "buckets": [ + { + "key_as_string": "2025-03-31T08:00:00.000Z", + "key": 1743408000000, + "doc_count": 5 + }, + { + "key_as_string": "2025-04-01T08:00:00.000Z", + "key": 1743494400000, + "doc_count": 1 + }, + { + "key_as_string": "2025-04-02T08:00:00.000Z", + "key": 1743580800000, + "doc_count": 1 + } + ] + } + } +} +``` + +## Example: Include empty buckets in a fixed time window + +By default, `min_doc_count` is `0`, so the histogram includes empty buckets between the first and last matching documents. To return empty buckets for an entire time window, including the beginning and end of the window where there are no documents, provide the window in `extended_bounds`. The `extended_bounds` parameter only adds buckets and does not filter documents, so limit the documents to the same window using a `range` query. + +The following request retrieves hourly buckets for 06:00–12:00 on March 31, 2025, including hours with no data: + +```json +GET my-logs/_search +{ + "size": 0, + "query": { + "range": { + "timestamp": { + "gte": "2025-03-31T06:00:00Z", + "lt": "2025-03-31T12:00:00Z" + } + } + }, + "aggs": { + "morning": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "1h", + "extended_bounds": { + "min": "2025-03-31T06:00:00Z", + "max": "2025-03-31T11:00:00Z" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains a bucket for every hour in the window, including the empty buckets at 06:00, 07:00, 09:00, and 11:00: + +```json +{ + "aggregations": { + "morning": { + "buckets": [ + { + "key_as_string": "2025-03-31T06:00:00.000Z", + "key": 1743400800000, + "doc_count": 0 + }, + { + "key_as_string": "2025-03-31T07:00:00.000Z", + "key": 1743404400000, + "doc_count": 0 + }, + { + "key_as_string": "2025-03-31T08:00:00.000Z", + "key": 1743408000000, + "doc_count": 2 + }, + { + "key_as_string": "2025-03-31T09:00:00.000Z", + "key": 1743411600000, + "doc_count": 0 + }, + { + "key_as_string": "2025-03-31T10:00:00.000Z", + "key": 1743415200000, + "doc_count": 1 + }, + { + "key_as_string": "2025-03-31T11:00:00.000Z", + "key": 1743418800000, + "doc_count": 0 + } + ] + } + } +} +``` + +## Example: Strictly limit the range + +`hard_bounds` strictly limits the histogram to the specified minimum and maximum time range. No buckets are created outside these bounds, even if data falls beyond them. + +The following request retrieves buckets with a fixed interval of 30 minutes for the period between `2025-03-31T08:00:00Z` and `2025-03-31T11:00:00Z`: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "strict_range": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "30m", + "hard_bounds": { + "min": "2025-03-31T08:00:00Z", + "max": "2025-03-31T11:00:00Z" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains buckets only within the bounds. Documents outside the bounds, such as document 4, are not counted: + +```json +{ + "aggregations": { + "strict_range": { + "buckets": [ + { + "key_as_string": "2025-03-31T08:00:00.000Z", + "key": 1743408000000, + "doc_count": 1 + }, + { + "key_as_string": "2025-03-31T08:30:00.000Z", + "key": 1743409800000, + "doc_count": 1 + }, + { + "key_as_string": "2025-03-31T09:00:00.000Z", + "key": 1743411600000, + "doc_count": 0 + }, + { + "key_as_string": "2025-03-31T09:30:00.000Z", + "key": 1743413400000, + "doc_count": 0 + }, + { + "key_as_string": "2025-03-31T10:00:00.000Z", + "key": 1743415200000, + "doc_count": 1 + } + ] + } + } +} +``` + +## Example: Return a map of buckets + +Set `keyed: true` to return buckets as an object keyed by the formatted date string: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "per_month": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "1M", + "format": "yyyy-MM-dd", + "keyed": true + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains an object keyed by month: + +```json +{ + "aggregations": { + "per_month": { + "buckets": { + "2025-03-01": { + "key_as_string": "2025-03-01", + "key": 1740787200000, + "doc_count": 4 + }, + "2025-04-01": { + "key_as_string": "2025-04-01", + "key": 1743465600000, + "doc_count": 3 + } + } + } + } +} +``` + +## Example: Treat missing dates as a fixed value + +Use the `missing` parameter to assign documents with no value to a bucket at the provided date. These documents are counted in the same bucket as documents that have that date. The following example uses a `news-articles` index in which one article has no `published_on`. Create the index and add the documents: + +```json +PUT news-articles +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "published_on": { "type": "date" } + } + } +} +``` +{% include copy-curl.html %} + +```json +POST news-articles/_bulk?refresh +{ "index": { "_id": "1" } } +{ "title": "Cluster sizing basics", "published_on": "2023-06-12" } +{ "index": { "_id": "2" } } +{ "title": "Tuning shard allocation", "published_on": "2024-02-20" } +{ "index": { "_id": "3" } } +{ "title": "Snapshot strategies", "published_on": "2024-09-05" } +{ "index": { "_id": "4" } } +{ "title": "Draft: Upgrading to OpenSearch 3" } +``` +{% include copy-curl.html %} + +The following request counts articles per year and places the article without a `published_on` value in the year 2022: + +```json +GET news-articles/_search +{ + "size": 0, + "aggs": { + "published_per_year": { + "date_histogram": { + "field": "published_on", + "calendar_interval": "year", + "missing": "2022-01-01" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains a bucket for 2022 with the undated article: + +```json +{ + "aggregations": { + "published_per_year": { + "buckets": [ + { + "key_as_string": "2022-01-01T00:00:00.000Z", + "key": 1640995200000, + "doc_count": 1 + }, + { + "key_as_string": "2023-01-01T00:00:00.000Z", + "key": 1672531200000, + "doc_count": 1 + }, + { + "key_as_string": "2024-01-01T00:00:00.000Z", + "key": 1704067200000, + "doc_count": 2 + } + ] + } + } +} +``` + +## Example: Sort buckets + +By default, buckets are returned sorted by `_key` in ascending order. Use the `order` parameter to change to descending if necessary. The `order` parameter also accepts subaggregation paths in the same way as the `terms` aggregation. For more information, see [Sort order]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/#sort-order). + +The following request retrieves buckets with the most recent month first: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "recent_months": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "1M", + "order": { + "_key": "desc" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The following request orders hourly buckets by document count, highest first. It sets `min_doc_count` to `1` so that the empty hours are not included: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "busiest_hours": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "1h", + "min_doc_count": 1, + "order": { + "_count": "desc" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The first bucket in the response is `2025-03-31T08:00:00.000Z`, which contains two documents. + +## Example: Use a script + +You can use a Painless script to generate or modify the date value used for bucketing. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). Scripts run for every matching document, so they add overhead. + +The `date_histogram` aggregation supports two kinds of scripts: + +- A document-level script, specified in `script` without `field`, calculates the date value from the document. The script can return a date object or a number of epoch milliseconds. +- A value script, specified in `script` together with `field`, modifies each value of the field. The field value is available to the script as `_value`, in epoch milliseconds. + +The following request uses a document-level script that returns the `timestamp` value, which produces the same buckets as specifying `"field": "timestamp"`: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "by_hour_script": { + "date_histogram": { + "script": { + "lang": "painless", + "source": "doc['timestamp'].value" + }, + "fixed_interval": "1h" + } + } + } +} +``` +{% include copy-curl.html %} + +The following request uses a value script to shift each `timestamp` value forward by one hour (3,600,000 milliseconds) before bucketing. As a result, document 4 (`2025-03-31T23:30:00Z`) is counted on April 1: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "by_day_plus_one_hour": { + "date_histogram": { + "field": "timestamp", + "script": { + "lang": "painless", + "source": "_value + 3600000" + }, + "calendar_interval": "day" + } + } + } +} +``` +{% include copy-curl.html %} + +The daily buckets contain 3, 3, and 1 documents, compared to 4, 2, and 1 without the script: + +```json +{ + "aggregations": { + "by_day_plus_one_hour": { + "buckets": [ + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 3 + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 3 + }, + { + "key_as_string": "2025-04-02T00:00:00.000Z", + "key": 1743552000000, + "doc_count": 1 + } + ] + } + } +} +``` + +## Example: Aggregate by day of the week + +To count documents by day of the week, regardless of the date, use a `terms` aggregation with a script that returns the day of the week: + +```json +GET my-logs/_search +{ + "size": 0, + "aggs": { + "day_of_week": { + "terms": { + "script": { + "lang": "painless", + "source": "doc['timestamp'].value.dayOfWeekEnum.value" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The bucket keys are day numbers, where `1` is Monday and `7` is Sunday. The response shows four documents on Monday (March 31), two on Tuesday, and one on Wednesday: + +```json +{ + "aggregations": { + "day_of_week": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "1", + "doc_count": 4 + }, + { + "key": "2", + "doc_count": 2 + }, + { + "key": "3", + "doc_count": 1 + } + ] + } + } +} +``` diff --git a/_aggregations/bucket/date-range.md b/_aggregations/bucket/date-range.md index c7d66d72..105899e7 100644 --- a/_aggregations/bucket/date-range.md +++ b/_aggregations/bucket/date-range.md @@ -2,30 +2,114 @@ layout: default title: Date range parent: Bucket aggregations -grand_parent: Aggregations nav_order: 30 redirect_from: - /query-dsl/aggregations/bucket/date-range/ --- -# Date range aggregations +# Date range aggregation -The `date_range` aggregation is conceptually the same as the `range` aggregation, except that it lets you perform date math. -For example, you can get all documents from the last 10 days. To make the date more readable, include the format with a `format` parameter: +Use the `date_range` aggregation to group documents into buckets defined by date boundaries. The `date_range` aggregation behaves like the numeric `range` aggregation but accepts date math in addition to [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) dates and epoch milliseconds. + +Note the following details: + +- `from` is inclusive, `to` is exclusive. +- To create an open-ended bucket, omit `from` or `to`. +- Date math supports rounding: for example, `now-7d/d` (start of the day, 7 days ago). + +## Parameters + +The following is a table of parameters accepted by `date_range` aggregations. + +| Parameter | Required | Description | +| --- | --- | --- | +| `field` | Yes | The date field to aggregate on. | +| `ranges`| Yes | The non-empty array of range objects. A range that specifies neither `from` nor `to` matches every value. | +| `ranges[].from` | No | Lower inclusive bound. | +| `ranges[].to` | No | Upper exclusive bound. | +| `ranges[].key`| No | The label for the bucket.| +| `format`| No | The date format used to display the bucket boundaries in the `from_as_string` and `to_as_string` response fields and to parse date strings in `from` and `to`, for example, `yyyy-MM-dd`. | +| `time_zone` | No | The IANA time zone or UTC offset used to evaluate date math, rounding, and date strings in `from` and `to` that don't specify an offset, for example, `Europe/Dublin` or `+01:00`. With `Europe/Dublin`, `"from": "2025-10-01"` is evaluated as `2025-10-01T00:00:00+01:00`. | +| `keyed` | No | If `true`, returns the buckets as an object instead of an array. Each bucket is keyed by its `key` value, which is either the custom `key` that you specify for the range or a generated key, such as `*-2025-09-20T00:00:00.000Z`. Default is `false`. | +| `missing` | No | The value to substitute for documents in which the field is missing. | + + +### Accepted values for `from` and `to` + +The following values of `from` and `to` are accepted: + +- ISO 8601 strings: `"2025-10-01T00:00:00Z"`, `"2025-10-01"` +- Date math: `"now-7d/d"`, `"now+1M/M"`, `"2025-09-01||/M"` +- Epoch milliseconds: `1756684800000` + +If components are omitted in a date string, the missing parts are filled with defaults. For example, `"2025-10"` is treated as the start of October 2025. +{: .note} + +## Example setup + +The examples on this page use a `my-index` index. Create the index and map the `event_time` field to accept epoch milliseconds: ```json -GET opensearch_dashboards_sample_data_logs/_search +PUT my-index +{ + "mappings": { + "properties": { + "@timestamp": { "type": "date" }, + "event_time": { "type": "date", "format": "epoch_millis" } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents. Document 6 has no `@timestamp` value: + +```json +POST my-index/_bulk?refresh +{ "index": { "_id": "1" } } +{ "@timestamp": "2025-09-10T12:00:00Z", "event_time": 1697400000000 } +{ "index": { "_id": "2" } } +{ "@timestamp": "2025-09-18T09:00:00Z", "event_time": 1697500000000 } +{ "index": { "_id": "3" } } +{ "@timestamp": "2025-09-22T15:00:00Z", "event_time": 1698000000000 } +{ "index": { "_id": "4" } } +{ "@timestamp": "2025-09-26T08:00:00Z" } +{ "index": { "_id": "5" } } +{ "@timestamp": "2025-10-01T07:30:00Z" } +{ "index": { "_id": "6" } } +{ "note": "no timestamp" } +``` +{% include copy-curl.html %} + +So that the responses on this page don't depend on when you run the examples, the date math in the examples is calculated from the fixed date `2025-10-01` using the `||` separator. To calculate the ranges from the current time, replace `2025-10-01||` with `now`. For example, use `now-7d/d` instead of `2025-10-01||-7d/d`. + +## Example: Three sliding windows + +The following example produces three buckets (the last 7 days, the previous 7 days, and older), using date math and the `yyyy-MM-dd` output `format`: + +```json +GET my-index/_search { "size": 0, "aggs": { - "number_of_bytes": { + "by_range": { "date_range": { "field": "@timestamp", - "format": "MM-yyyy", + "format": "yyyy-MM-dd", "ranges": [ { - "from": "now-10d/d", - "to": "now" + "from": "2025-10-01||-7d/d", + "to": "2025-10-01||+1d/d", + "key": "last_7d" + }, + { + "from": "2025-10-01||-14d/d", + "to": "2025-10-01||-7d/d", + "key": "prev_7d" + }, + { + "to": "2025-10-01||-14d/d", + "key": "older" } ] } @@ -35,23 +119,246 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +The response contains the three buckets: ```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 - } - ] +{ + "aggregations": { + "by_range": { + "buckets": [ + { + "key": "older", + "to": 1758067200000.0, + "to_as_string": "2025-09-17", + "doc_count": 1 + }, + { + "key": "prev_7d", + "from": 1758067200000.0, + "from_as_string": "2025-09-17", + "to": 1758672000000.0, + "to_as_string": "2025-09-24", + "doc_count": 2 + }, + { + "key": "last_7d", + "from": 1758672000000.0, + "from_as_string": "2025-09-24", + "to": 1759363200000.0, + "to_as_string": "2025-10-02", + "doc_count": 2 + } + ] + } } - } } -``` \ No newline at end of file +``` + +## Example: Bucket for the last 10 days with a custom string format + +The following request creates a single bucket that covers the 10 days before October 1, 2025, and the whole day of October 1. The bucket starts at the beginning of the day 10 days earlier (`-10d/d`) and ends at the beginning of the following day (`+1d/d`, exclusive). + +The `format` determines how the bucket boundaries are displayed in the `from_as_string` and `to_as_string` response fields. It is also used to parse date strings in `from` and `to`, so the date in each boundary must use the same format. In this example, the format is `yyyy-MM`, so the boundaries start with `2025-10`, which is parsed as October 1, 2025: + +```json +GET my-index/_search +{ + "size": 0, + "aggs": { + "last_10_days": { + "date_range": { + "field": "@timestamp", + "format": "yyyy-MM", + "ranges": [ + { + "from": "2025-10||-10d/d", + "to": "2025-10||+1d/d" + } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains documents 3, 4, and 5. The `from_as_string` and `to_as_string` fields use the `yyyy-MM` format: + +```json +{ + "aggregations": { + "last_10_days": { + "buckets": [ + { + "key": "2025-09-2025-10", + "from": 1758412800000.0, + "from_as_string": "2025-09", + "to": 1759363200000.0, + "to_as_string": "2025-10", + "doc_count": 3 + } + ] + } + } +} +``` + +## Example: Keyed response and custom keys + +The following request returns an object organized by your labels for easier downstream processing: + +```json +GET my-index/_search +{ + "size": 0, + "aggs": { + "keyed_ranges": { + "date_range": { + "field": "@timestamp", + "keyed": true, + "ranges": [ + { + "from": "2025-10-01||/d", + "to": "2025-10-01||+1d/d", + "key": "today" + }, + { + "to": "2025-10-01||/d", + "key": "before_today" + } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains a `today` bucket and a `before_today` bucket: + +```json +{ + "aggregations": { + "keyed_ranges": { + "buckets": { + "before_today": { + "to": 1759276800000.0, + "to_as_string": "2025-10-01T00:00:00.000Z", + "doc_count": 4 + }, + "today": { + "from": 1759276800000.0, + "from_as_string": "2025-10-01T00:00:00.000Z", + "to": 1759363200000.0, + "to_as_string": "2025-10-02T00:00:00.000Z", + "doc_count": 1 + } + } + } + } +} +``` + +## Example: Epoch milliseconds with a time zone + +When the field value is provided in epoch milliseconds, you can still provide `from` and `to` parameters as numbers. In the following request, `time_zone` affects date math and boundary evaluation: + +```json +GET my-index/_search +{ + "size": 0, + "aggs": { + "local_ranges": { + "date_range": { + "field": "event_time", + "time_zone": "Europe/Dublin", + "format": "epoch_millis", + "ranges": [ + { + "from": "1697328000000", + "to": "1697932800000", + "key": "week_sample" + } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +The `time_zone` is applied to the boundaries even though they are epoch milliseconds. In October 2023, Dublin was one hour ahead of UTC, so both boundaries in the response are one hour (`3600000` milliseconds) earlier than the values in the request: + +```json +{ + "aggregations": { + "local_ranges": { + "buckets": [ + { + "key": "week_sample", + "from": 1697324400000.0, + "from_as_string": "1697324400000", + "to": 1697929200000.0, + "to_as_string": "1697929200000", + "doc_count": 2 + } + ] + } + } +} +``` + +## Example: Handling missing dates + +Use `missing` to route documents without a value into a bucket by substituting a default: + +```json +GET my-index/_search +{ + "size": 0, + "aggs": { + "dated_or_undated": { + "date_range": { + "field": "@timestamp", + "missing": "1970-01-01", + "ranges": [ + { + "to": "2000-01-01", + "key": "undated_or_old" + }, + { + "from": "2000-01-01", + "key": "dated_recent" + } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +Document 6, which has no `@timestamp` value, is counted in the `undated_or_old` bucket: + +```json +{ + "aggregations": { + "dated_or_undated": { + "buckets": [ + { + "key": "undated_or_old", + "to": 946684800000.0, + "to_as_string": "2000-01-01T00:00:00.000Z", + "doc_count": 1 + }, + { + "key": "dated_recent", + "from": 946684800000.0, + "from_as_string": "2000-01-01T00:00:00.000Z", + "doc_count": 5 + } + ] + } + } +} +``` diff --git a/_aggregations/bucket/diversified-sampler.md b/_aggregations/bucket/diversified-sampler.md index 7249ac35..a685cade 100644 --- a/_aggregations/bucket/diversified-sampler.md +++ b/_aggregations/bucket/diversified-sampler.md @@ -2,32 +2,76 @@ layout: default title: Diversified sampler parent: Bucket aggregations -grand_parent: Aggregations nav_order: 40 redirect_from: - /query-dsl/aggregations/bucket/diversified-sampler/ --- -# Diversified sampler +# Diversified sampler aggregation -The `diversified_sampler` aggregation lets you reduce the bias in the distribution of the sample pool by deduplicating documents containing the same `field`. It does so by using the `max_docs_per_value` and `field` settings, which limit the maximum number of documents collected on a shard for the provided `field`. The `max_docs_per_value` setting is an optional parameter used to determine the maximum number of documents that will be returned per `field`. The default value of this setting is `1`. +The `diversified_sampler` aggregation is a filtering aggregation that limits subaggregation processing to a sample of top-scoring documents while ensuring the sample contains diverse content. It extends the [`sampler` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/sampler/) by deduplicating documents that share a common field value, preventing any single category from dominating the sample. -Similarly to the [`sampler` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/sampler/), you can use the `shard_size` setting to control the maximum number of documents collected on any one shard, as shown in the following example: +Because the sample contains only the top-scoring documents, the subaggregation results focus on the most relevant matches and are not diluted by a long tail of weak matches. This aggregation is also useful when you need to ensure fair representation across different groups---for example, preventing a single prolific author from skewing analytics results or ensuring geographic diversity in location-based analysis. It also reduces the cost of expensive subaggregations like `significant_terms` by producing useful results from a smaller, more representative sample. + +## Parameters + +The `diversified_sampler` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Optional | String | The field used for deduplication. Must produce a single value per document. Either `field` or `script` is required. | +| `script` | Optional | Object | A script that generates the deduplication value. Either `field` or `script` is required. If you specify both, the script acts as a value script and receives the field value as `_value`. | +| `shard_size` | Optional | Integer | The maximum number of top-scoring documents collected on each shard. Default is `100`. | +| `max_docs_per_value` | Optional | Integer | The cap on how many documents sharing the same deduplication value can enter the sample on each shard. Default is `1`, so the sample contains at most one document for each value. | +| `execution_hint` | Optional | String | Controls how deduplication values are managed in memory. See [Execution hint](#execution-hint). | + +### Execution hint + +The following table lists the valid `execution_hint` values. + +| Value | Description | +| :--- | :--- | +| `map` | Holds field values directly in memory. | +| `global_ordinals` | Uses Lucene's ordinal mappings for the field, offering better memory efficiency on high-cardinality fields. | +| `bytes_hash` | Stores a hash of each value rather than the value itself. May improve speed in some scenarios, but if two different values have the same hash, OpenSearch treats them as one value, which can shrink the sample. | + +By default, OpenSearch uses `global_ordinals` if the field has ordinals and `map` otherwise. All three options produce the same sample unless `bytes_hash` treats two different values as duplicates because their hashes collide. They differ only in the type of value held in memory, and each option holds up to `shard_size` values. OpenSearch ignores the `execution_hint` if the chosen option does not apply to the field type, and an unrecognized value causes the request to fail. + + +The `diversified_sampler` aggregation can be nested under a `terms` aggregation. If the `terms` aggregation uses the `breadth_first` collect mode, OpenSearch replays the relevance scores of the deferred documents, so the sample is still based on the top-scoring documents. +{: .note} + +## Example: Deduplicating by field + +A sample of the top-matching documents can be dominated by a few prolific sources, such as a customer who places many similar orders. In the sample ecommerce data, one customer placed 103 of the 646 orders containing a dress. A plain `sampler` with a `shard_size` of `100` contains orders from only 16 customers. + +The following example samples the top-matching orders containing a dress but allows only one order for each `customer_id`, so that the subaggregations reflect many customers equally: ```json -GET opensearch_dashboards_sample_data_logs/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, + "query": { + "match": { + "products.product_name": "dress" + } + }, "aggs": { - "sample": { - "diversified_": { - "shard_size": 1000, - "field": "response.keyword" + "unbiased_sample": { + "diversified_sampler": { + "shard_size": 100, + "field": "customer_id" }, "aggs": { - "terms": { + "customers": { + "cardinality": { + "field": "customer_id" + } + }, + "top_manufacturers": { "terms": { - "field": "agent.keyword" + "field": "manufacturer.keyword", + "size": 3 } } } @@ -37,30 +81,148 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +The sample contains 22 orders, one from each of the 22 customers who ordered a dress: + +
+ + Response + + {: .text-delta} ```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 - } - ] +{ + "aggregations": { + "unbiased_sample": { + "doc_count": 22, + "top_manufacturers": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 17, + "buckets": [ + { + "key": "Tigress Enterprises", + "doc_count": 7 + }, + { + "key": "Low Tide Media", + "doc_count": 6 + }, + { + "key": "Oceanavigations", + "doc_count": 6 + } + ] + }, + "customers": { + "value": 22 + } } } - - } } ``` - +
+ +## Example: Deduplicating by script + +Use a script to diversify on a combination of values. The following example allows at most three orders for each combination of `customer_gender` and `day_of_week`: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "query": { + "match": { + "products.product_name": "dress" + } + }, + "aggs": { + "unbiased_sample": { + "diversified_sampler": { + "shard_size": 100, + "max_docs_per_value": 3, + "script": { + "lang": "painless", + "source": "doc['customer_gender'].value + '-' + doc['day_of_week'].value" + } + }, + "aggs": { + "by_day": { + "terms": { + "field": "day_of_week", + "size": 7 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The sample contains 27 orders: at most three for each combination of gender and day of the week. Because each day can contain orders from both female and male customers, some days contain more than three orders: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "unbiased_sample": { + "doc_count": 27, + "by_day": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "Thursday", + "doc_count": 5 + }, + { + "key": "Friday", + "doc_count": 4 + }, + { + "key": "Sunday", + "doc_count": 4 + }, + { + "key": "Tuesday", + "doc_count": 4 + }, + { + "key": "Wednesday", + "doc_count": 4 + }, + { + "key": "Monday", + "doc_count": 3 + }, + { + "key": "Saturday", + "doc_count": 3 + } + ] + } + } + } +} +``` +
+ +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The total number of documents in the diversified sample. | + +## Limitations + +The `diversified_sampler` aggregation has the following limitations: + +- The `field` or `script` must produce a single value per document. Using a multi-valued field, such as `manufacturer.keyword` in the sample ecommerce data, causes the request to fail. To diversify on all values of a multi-valued field, use a script that combines them into one value, for example, `doc['manufacturer.keyword'].hashCode()`. +- Deduplication is applied independently on each shard, so documents with the same value on different shards are not deduplicated against each other. +- There is no specialized syntax for geographic or date-based diversity values (such as `7d` or `10km`). To diversify by geographic region or time interval, write a script that buckets the raw values---for example, `(int)(doc['geoip.location'].lat / 10)` for latitude bands or `doc['order_date'].value.dayOfWeek` for day-of-week grouping. diff --git a/_aggregations/bucket/filter.md b/_aggregations/bucket/filter.md index 0768ea11..fd2ef78f 100644 --- a/_aggregations/bucket/filter.md +++ b/_aggregations/bucket/filter.md @@ -2,20 +2,23 @@ layout: default title: Filter parent: Bucket aggregations -grand_parent: Aggregations nav_order: 50 redirect_from: - /query-dsl/aggregations/bucket/filter/ --- -# Filter aggregations +# Filter aggregation -A `filter` aggregation is a query clause, exactly like a search query — `match` or `term` or `range`. You can use the `filter` aggregation to narrow down the entire set of documents to a specific set before creating buckets. +The `filter` aggregation creates a single bucket containing all documents that match a specified query. Any query clause---`match`, `term`, `range`, `bool`, and others---can serve as the filter. Subaggregations nested inside the `filter` aggregation operate only on the matching documents, making it useful for scoping expensive computations to a relevant subset. -The following example shows the `avg` aggregation running within the context of a filter. The `avg` aggregation only aggregates the documents that match the `range` query: +For filtering documents into multiple named buckets simultaneously, see the [`filters` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/filters/). + +## Example + +The following example calculates the average order total for all orders under $50 by wrapping an `avg` subaggregation inside a `range` filter: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { @@ -40,17 +43,42 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json -... -"aggregations" : { - "low_value" : { - "doc_count" : 1633, - "avg_amount" : { - "value" : 38.363175998928355 +{ + "took": 43, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "low_value": { + "doc_count": 1633, + "avg_amount": { + "value": 38.363175998928355 + } } } - } } -``` \ No newline at end of file +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The number of documents that matched the filter query. | diff --git a/_aggregations/bucket/filters.md b/_aggregations/bucket/filters.md index b3977da7..1b6c951a 100644 --- a/_aggregations/bucket/filters.md +++ b/_aggregations/bucket/filters.md @@ -2,45 +2,40 @@ layout: default title: Filters parent: Bucket aggregations -grand_parent: Aggregations nav_order: 60 redirect_from: - /query-dsl/aggregations/bucket/filters/ --- -# Filters aggregations +# Filters aggregation -A `filters` aggregation is the same as the `filter` aggregation, except that it lets you use multiple filter aggregations. -While the `filter` aggregation results in a single bucket, the `filters` aggregation returns multiple buckets, one for each of the defined filters. +The `filters` aggregation creates multiple buckets, each associated with a named or anonymous filter query. Every document is evaluated against all filters, and a document can land in multiple buckets if it matches more than one filter. This differs from the singular [`filter` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/filter/), which produces only one bucket. -To create a bucket for all the documents that didn't match the any of the filter queries, set the `other_bucket` property to `true`: +## Parameters + +The `filters` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `filters` | Required | Object or Array | The filter definitions. Provide an object with named keys for labeled buckets, or an array for anonymous (positional) buckets. | +| `other_bucket` | Optional | Boolean | When `true`, adds a bucket containing all documents that did not match any filter. Default is `false`. | +| `other_bucket_key` | Optional | String | The key name for the other bucket. Setting this implicitly enables `other_bucket`. Default is `_other_`. | + +## Example: Named filters + +When you provide filters as an object, each key becomes the bucket name in the response. The following example groups e-commerce orders into three price tiers: ```json -GET opensearch_dashboards_sample_data_logs/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "200_os": { + "price_ranges": { "filters": { - "other_bucket": true, - "filters": [ - { - "term": { - "response.keyword": "200" - } - }, - { - "term": { - "machine.os.keyword": "osx" - } - } - ] - }, - "aggs": { - "avg_amount": { - "avg": { - "field": "bytes" - } + "filters": { + "budget": { "range": { "taxful_total_price": { "lte": 50 } } }, + "mid_range": { "range": { "taxful_total_price": { "gt": 50, "lte": 100 } } }, + "premium": { "range": { "taxful_total_price": { "gt": 100 } } } } } } @@ -49,33 +44,98 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +## Example: Anonymous filters + +When you provide filters as an array, buckets are returned in the same order as the array. The following example uses anonymous filters: ```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 +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_ranges": { + "filters": { + "filters": [ + { "range": { "taxful_total_price": { "lte": 50 } } }, + { "range": { "taxful_total_price": { "gt": 50, "lte": 100 } } } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +## Example: Other bucket + +The `other_bucket` parameter captures all documents that did not match any of the defined filters. The following example uses `other_bucket_key` to assign a custom name to the catch-all bucket: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_ranges": { + "filters": { + "other_bucket": true, + "other_bucket_key": "all_others", + "filters": { + "budget": { "range": { "taxful_total_price": { "lte": 50 } } }, + "premium": { "range": { "taxful_total_price": { "gt": 100 } } } } } - ] + } } - } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +## Example response + +The following response corresponds to the other bucket example: + +```json +{ + "took": 3, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "price_ranges": { + "buckets": { + "budget": { + "doc_count": 1633 + }, + "premium": { + "doc_count": 950 + }, + "all_others": { + "doc_count": 2092 + } + } + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Object or Array | An object with named keys when using named filters, or an array of objects when using anonymous filters. | +| `buckets..doc_count` | Integer | The number of documents matching the filter for this bucket. | diff --git a/_aggregations/bucket/geo-distance.md b/_aggregations/bucket/geo-distance.md index a111015a..38c3d1e1 100644 --- a/_aggregations/bucket/geo-distance.md +++ b/_aggregations/bucket/geo-distance.md @@ -2,113 +2,48 @@ layout: default title: Geodistance parent: Bucket aggregations -grand_parent: Aggregations nav_order: 70 redirect_from: - /query-dsl/aggregations/bucket/geo-distance/ --- -# Geodistance aggregations +# Geodistance aggregation -The `geo_distance` aggregation groups documents into concentric circles based on distances from an origin `geo_point` field. -It's the same as the `range` aggregation, except that it works on geo locations. +The `geo_distance` aggregation groups documents into distance-based rings around a central point. Each range defines a ring, and documents are placed into buckets based on how far their `geo_point` field value is from the specified origin. This is conceptually similar to the [`range` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/range/) but operates on geographic coordinates rather than numeric values. -For example, you can use the `geo_distance` aggregation to find all pizza places within 1 km of you. The search results are limited to the 1 km radius specified by you, but you can add another result found within 2 km. +The target field must be mapped as `geo_point`. If a document's geo_point field contains multiple values, all distances are evaluated and the document is bucketed accordingly. -You can only use the `geo_distance` aggregation on fields mapped as `geo_point`. +## Parameters -A point is a single geographical coordinate, such as your current location shown by your smart-phone. A point in OpenSearch is represented as follows: +The `geo_distance` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The `geo_point` field to compute distances from. | +| `origin` | Required | Object, String, or Array | The center point from which distances are measured. Accepts object format (`{"lat": 40.71, "lon": -74.00}`), string format (`"40.71, -74.00"`), or GeoJSON array format (`[-74.00, 40.71]`). | +| `ranges` | Required | Array | A list of distance ranges defining the buckets. Each range can include `from`, `to`, and optionally `key`. | +| `unit` | Optional | String | The unit for distance values in `ranges`. Default is `m` (meters). Valid values: `m`, `km`, `mi`, `yd`, `in`, `cm`, `mm`. | +| `distance_type` | Optional | String | The algorithm used to compute distances.
Valid values are:
- `arc`: Computes distances using the full spherical geometry of the Earth. Most accurate but slowest.
- `plane`: Projects coordinates onto a flat plane and computes Euclidean distances. Fastest but least accurate. Only suitable for small geographic areas (approximately 5 km or less).

Default is `arc`. | +| `keyed` | Optional | Boolean | When `true`, returns buckets as an object keyed by range name instead of an array. Default is `false`. | + +## Example: Basic distance rings + +The following example groups e-commerce orders into three distance rings around New York City, measured in miles: ```json -{ - "location": { - "type": "point", - "coordinates": { - "lat": 83.76, - "lon": -81.2 - } - } -} -``` - -You can also specify the latitude and longitude as an array `[-81.20, 83.76]` or as a string `"83.76, -81.20"` - -This table lists the relevant fields of a `geo_distance` aggregation: - -Field | Description | Required -:--- | :--- |:--- -`field` | Specify the geopoint field that you want to work on. | Yes -`origin` | Specify the geopoint that's used to compute the distances from. | Yes -`ranges` | Specify a list of ranges to collect documents based on their distance from the target point. | Yes -`unit` | Define the units used in the `ranges` array. The `unit` defaults to `m` (meters), but you can switch to other units like `km` (kilometers), `mi` (miles), `in` (inches), `yd` (yards), `cm` (centimeters), and `mm` (millimeters). | No -`distance_type` | Specify how OpenSearch calculates the distance. The default is `sloppy_arc` (faster but less accurate), but can also be set to `arc` (slower but most accurate) or `plane` (fastest but least accurate). Because of high error margins, use `plane` only for small geographic areas. | No - -The syntax is as follows: - -```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" - } - ] - } - } - } -} -``` - -This example forms buckets from the following distances from a `geo-point` field: - -- Fewer than 10 km -- From 10 to 20 km -- From 20 to 50 km -- From 50 to 100 km -- Above 100 km - -```json -GET opensearch_dashboards_sample_data_logs/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "position": { + "distance_from_nyc": { "geo_distance": { - "field": "geo.coordinates", - "origin": { - "lat": 83.76, - "lon": -81.2 - }, + "field": "geoip.location", + "origin": "40.7128, -74.0060", + "unit": "mi", "ranges": [ - { - "to": 10 - }, - { - "from": 10, - "to": 20 - }, - { - "from": 20, - "to": 50 - }, - { - "from": 50, - "to": 100 - }, - { - "from": 100 - } + { "to": 50 }, + { "from": 50, "to": 500 }, + { "from": 500 } ] } } @@ -117,44 +52,87 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +## Example: Keyed response with custom range names + +Setting `keyed` to `true` returns buckets as an object instead of an array. You can assign custom names to each range using the `key` property: ```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 +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "distance_from_nyc": { + "geo_distance": { + "field": "geoip.location", + "origin": "40.7128, -74.0060", + "unit": "mi", + "keyed": true, + "ranges": [ + { "to": 50, "key": "local" }, + { "from": 50, "to": 500, "key": "domestic" }, + { "from": 500, "key": "international" } + ] } - ] + } } - } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +## Example response + +The following response corresponds to the keyed example: + +```json +{ + "took": 18, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "distance_from_nyc": { + "buckets": { + "local": { + "from": 0.0, + "to": 50.0, + "doc_count": 896 + }, + "domestic": { + "from": 50.0, + "to": 500.0, + "doc_count": 0 + }, + "international": { + "from": 500.0, + "doc_count": 3779 + } + } + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array or Object | The distance buckets. Returned as an array by default, or as an object when `keyed` is `true`. | +| `buckets.key` | String | The auto-generated range label (for example, `*-500.0` or `500.0-3000.0`), or a custom key if specified. | +| `buckets.from` | Double | The lower bound of the distance range, in the specified `unit`. | +| `buckets.to` | Double | The upper bound of the distance range, in the specified `unit`. | +| `buckets.doc_count` | Integer | The number of documents falling within this distance range. | diff --git a/_aggregations/bucket/geohash-grid.md b/_aggregations/bucket/geohash-grid.md index 13f89799..bcc300d1 100644 --- a/_aggregations/bucket/geohash-grid.md +++ b/_aggregations/bucket/geohash-grid.md @@ -2,28 +2,42 @@ layout: default title: Geohash grid parent: Bucket aggregations -grand_parent: Aggregations nav_order: 80 redirect_from: - /query-dsl/aggregations/bucket/geohash-grid/ --- -# Geohash grid aggregations +# Geohash grid aggregation -The `geohash_grid` aggregation buckets documents for geographical analysis. It organizes a geographical region into a grid of smaller regions of different sizes or precisions. Lower values of precision represent larger geographical areas, and higher values represent smaller, more precise geographical areas. You can aggregate documents on [geopoint]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point/) or [geoshape]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-shape/) fields using a geohash grid aggregation. One notable difference is that a geopoint is only present in one bucket, but a geoshape is counted in all geohash grid cells with which it intersects. +The `geohash_grid` aggregation groups documents into grid cells based on their [geohash](https://en.wikipedia.org/wiki/Geohash) value. Each cell is labeled with its geohash string, and the precision parameter controls cell size---lower precision values produce fewer, larger cells, while higher values produce many smaller cells. You can aggregate documents on [geo_point]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point/) or [geo_shape]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-shape/) fields. A geo_point is placed in exactly one cell, while a geo_shape is counted in every cell it intersects. -The number of results returned by a query might be far too many to display each geopoint individually on a map. The `geohash_grid` aggregation buckets nearby geopoints together by calculating the geohash for each point, at the level of precision that you define (between 1 to 12; the default is 5). To learn more about geohash, see [Wikipedia](https://en.wikipedia.org/wiki/Geohash). +Precision values range from 1 to 12. High-precision requests can consume significant memory and produce large responses because they generate many buckets. Filter to a small geographic area before using high precision values. +{: .note} -The web logs example data is spread over a large geographical area, so you can use a lower precision value. You can zoom in on this map by increasing the precision value: +## Parameters + +The `geohash_grid` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The field to aggregate on. Must be mapped as `geo_point` or `geo_shape`. | +| `precision` | Optional | Integer or String | The geohash length controlling cell size. Valid integer values are 1--12. You can also specify an approximate distance (for example, `1km` or `10m`), and OpenSearch selects the precision level whose cells do not exceed that size. Default is `5`. | +| `bounds` | Optional | Object | A bounding box that restricts which points are considered. Only points within the box are aggregated. Accepts all [geo_point formats]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats). | +| `size` | Optional | Integer | The maximum number of buckets to return. When there are more buckets than `size`, buckets with the highest document counts are returned. Default is `10000`. | +| `shard_size` | Optional | Integer | The maximum number of buckets returned from each shard. Default is max(10, `size` × number of shards). | + +## Example: Low-precision grid + +The following example groups e-commerce customer locations into geohash cells at precision 4 (approximately 39 km × 19.5 km): ```json -GET opensearch_dashboards_sample_data_logs/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { "geo_hash": { "geohash_grid": { - "field": "geo.coordinates", + "field": "geoip.location", "precision": 4 } } @@ -32,50 +46,100 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +## Example: High-precision grid with bounding box filter + +When zooming into a specific region, first filter documents to that area before requesting high precision. The following example uses a `geo_bounding_box` query to narrow to the New York City area, then aggregates at precision 7 (approximately 153 m × 152 m): ```json -... -"aggregations" : { - "geo_hash" : { - "buckets" : [ - { - "key" : "c1cg", - "doc_count" : 104 +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "zoomed_in": { + "filter": { + "geo_bounding_box": { + "geoip.location": { + "top_left": "41.0, -74.5", + "bottom_right": "40.5, -73.5" + } + } }, - { - "key" : "dr5r", - "doc_count" : 26 - }, - { - "key" : "9q5b", - "doc_count" : 20 - }, - { - "key" : "c20g", - "doc_count" : 19 - }, - { - "key" : "dr70", - "doc_count" : 18 + "aggs": { + "detailed_grid": { + "geohash_grid": { + "field": "geoip.location", + "precision": 7 + } + } } - ... - ] + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The following response corresponds to the high-precision example: + +```json +{ + "took": 23, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "zoomed_in": { + "doc_count": 896, + "detailed_grid": { + "buckets": [ + { + "key": "dr72h56", + "doc_count": 747 + }, + { + "key": "dr5rs14", + "doc_count": 149 + } + ] + } + } } - } } ``` -You can visualize the aggregated response on a map using OpenSearch Dashboards. +## Response body fields -The more accurate you want the aggregation to be, the more resources OpenSearch consumes because of the number of buckets that the aggregation has to calculate. By default, OpenSearch does not generate more than 10,000 buckets. You can change this behavior by using the `size` attribute, but keep in mind that the performance might suffer for very wide queries consisting of thousands of buckets. +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array | The grid cell buckets, ordered by `doc_count` descending. | +| `buckets.key` | String | The geohash string identifying the cell. | +| `buckets.doc_count` | Integer | The number of documents (or geoshape intersections) in this cell. | + +You can use a returned geohash key as both the `top_left` and `bottom_right` of a `geo_bounding_box` query to zoom into that cell at a higher precision. Client-side geohash libraries (such as [ngeohash](https://github.com/sunng87/node-geohash) for JavaScript) can decode bucket keys into lat/lon bounding boxes for map rendering. +{: .tip} ## Aggregating geoshapes To run an aggregation on a geoshape field, first create an index and map the `location` field as a `geo_shape`: ```json -PUT national_parks +PUT /national_parks { "mappings": { "properties": { @@ -91,7 +155,7 @@ PUT national_parks Next, index some documents into the `national_parks` index: ```json -PUT national_parks/_doc/1 +PUT /national_parks/_doc/1 { "name": "Yellowstone National Park", "location": @@ -101,7 +165,7 @@ PUT national_parks/_doc/1 {% include copy-curl.html %} ```json -PUT national_parks/_doc/2 +PUT /national_parks/_doc/2 { "name": "Yosemite National Park", "location": @@ -111,7 +175,7 @@ PUT national_parks/_doc/2 {% include copy-curl.html %} ```json -PUT national_parks/_doc/3 +PUT /national_parks/_doc/3 { "name": "Death Valley National Park", "location": @@ -123,7 +187,7 @@ PUT national_parks/_doc/3 You can run an aggregation on the `location` field as follows: ```json -GET national_parks/_search +GET /national_parks/_search { "aggregations": { "grouped": { @@ -137,7 +201,7 @@ GET national_parks/_search ``` {% include copy-curl.html %} -When aggregating geoshapes, one geoshape can be counted for multiple buckets because it overlaps multiple grid cells: +A geoshape can appear in multiple buckets when it spans more than one grid cell:
@@ -245,24 +309,12 @@ When aggregating geoshapes, one geoshape can be counted for multiple buckets bec ```
-Currently, OpenSearch supports geoshape aggregation through the API but not in OpenSearch Dashboards visualizations. If you'd like to see geoshape aggregation implemented for visualizations, upvote the related [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250). +OpenSearch supports geoshape aggregation through the API but not in OpenSearch Dashboards visualizations. {: .note} -## Supported parameters - -Geohash grid aggregation requests support the following parameters. - -Parameter | Data type | Description -:--- | :--- | :--- -field | String | The field on which aggregation is performed. This field must be mapped as a `geo_point` or `geo_shape` field. If the field contains an array, all array values are aggregated. Required. -precision | Integer | The granularity level used to determine grid cells for bucketing results. Cells cannot exceed the specified size (diagonal) of the required precision. Valid values are in the [0, 12] range. Optional. Default is 5. -bounds | Object | The bounding box for filtering geopoints and geoshapes. The bounding box is defined by the upper-left and lower-right vertices. Only shapes that intersect with this bounding box or are completely enclosed by this bounding box are included in the aggregation output. The vertices are specified as geopoints in one of the following formats:
- An object with a latitude and longitude
- An array in the [`longitude`, `latitude`] format
- A string in the "`latitude`,`longitude`" format
- A geohash
- WKT
See the [geopoint formats]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) for formatting examples. Optional. -size | Integer | The maximum number of buckets to return. When there are more buckets than `size`, OpenSearch returns buckets with more documents. Optional. Default is 10,000. -shard_size | Integer | The maximum number of buckets to return from each shard. Optional. Default is max (10, `size` · number of shards), which provides a more accurate count of more highly prioritized buckets. - ## Geohash precision -The relationship between geohash precision and the approximate grid cell dimensions is described in the following table. +The following table lists the approximate cell dimensions at each precision level. Cell dimensions vary with latitude; the values shown represent the widest case at the equator. Precision /
geohash length | Latitude bits | Longitude bits | Latitude error | Longitude error | Cell height | Cell width :---:|:-------------:|:--------------:|:--------------:|:---------------:|:-----------:|:----------: @@ -277,4 +329,4 @@ Precision /
geohash length | Latitude bits | Longitude bits | Latitude error 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 \ No newline at end of file + 12 | 30 | 30 | ±0.00000008 | ±0.00000017 | 1.9 cm | 3.7 cm diff --git a/_aggregations/bucket/geohex-grid.md b/_aggregations/bucket/geohex-grid.md index de110610..27aa3fdf 100644 --- a/_aggregations/bucket/geohex-grid.md +++ b/_aggregations/bucket/geohex-grid.md @@ -2,15 +2,16 @@ layout: default title: Geohex grid parent: Bucket aggregations -grand_parent: Aggregations nav_order: 85 redirect_from: + - /opensearch/geohexgrid-agg/ + - /query-dsl/aggregations/geohexgrid-agg/ - /aggregations/geohexgrid/ - /query-dsl/aggregations/geohexgrid/ - /query-dsl/aggregations/bucket/geohex-grid/ --- -# Geohex grid aggregations +# Geohex grid aggregation The Hexagonal Hierarchical Geospatial Indexing System (H3) partitions the Earth's areas into identifiable hexagon-shaped cells. @@ -387,7 +388,7 @@ Geohex grid aggregation requests support the following parameters. Parameter | Data type | Description :--- | :--- | :--- field | String | The field that contains the geopoints. This field must be mapped as a `geo_point` field. If the field contains an array, all array values are aggregated. Required. -precision | Integer | The granularity level used to determine grid cells for bucketing results. Cells cannot exceed the specified size (diagonal) of the required precision. Valid values are in the [0, 15] range. Optional. Default is 5. -bounds | Object | The bounding box for filtering geopoints. The bounding box is defined by the upper-left and lower-right vertices. The vertices are specified as geopoints in one of the following formats:
- An object with a latitude and longitude
- An array in the [`longitude`, `latitude`] format
- A string in the "`latitude`,`longitude`" format
- A geohash
- WKT
See the [geopoint formats]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) for formatting examples. Optional. -size | Integer | The maximum number of buckets to return. When there are more buckets than `size`, OpenSearch returns buckets with more documents. Optional. Default is 10,000. -shard_size | Integer | The maximum number of buckets to return from each shard. Optional. Default is max (10, `size` · number of shards), which provides a more accurate count of more highly prioritized buckets. \ No newline at end of file +`precision` | Integer | The granularity level used to determine grid cells for bucketing results. Cells cannot exceed the specified size (diagonal) of the required precision. Valid values are in the [0, 15] range. Optional. Default is 5. +`bounds` | Object | The bounding box for filtering geopoints. The bounding box is defined by the upper-left and lower-right vertices. The vertices are specified as geopoints in one of the following formats:
- An object with a latitude and longitude
- An array in the [`longitude`, `latitude`] format
- A string in the "`latitude`,`longitude`" format
- A geohash
- WKT
See the [geopoint formats]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) for formatting examples. Optional. +`size` | Integer | The maximum number of buckets to return. When there are more buckets than `size`, OpenSearch returns buckets with more documents. Optional. Default is 10,000. +`shard_size` | Integer | The maximum number of buckets to return from each shard. Optional. Default is max (10, `size` · number of shards), which provides a more accurate count of more highly prioritized buckets. \ No newline at end of file diff --git a/_aggregations/bucket/geotile-grid.md b/_aggregations/bucket/geotile-grid.md index dd0c4f8a..fc02f366 100644 --- a/_aggregations/bucket/geotile-grid.md +++ b/_aggregations/bucket/geotile-grid.md @@ -2,15 +2,14 @@ layout: default title: Geotile grid parent: Bucket aggregations -grand_parent: Aggregations nav_order: 87 redirect_from: - /query-dsl/aggregations/bucket/geotile-grid/ --- -# Geotile grid aggregations +# Geotile grid aggregation -The geotile grid aggregation groups documents into grid cells for geographical analysis. Each grid cell corresponds to a [map tile](https://en.wikipedia.org/wiki/Tiled_web_map) and is identified using the `{zoom}/{x}/{y}` format. You can aggregate documents on [geopoint]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point/) or [geoshape]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-shape/) fields using a geotile grid aggregation. One notable difference is that a geopoint is only present in one bucket, but a geoshape is counted in all geotile grid cells with which it intersects. +The geotile grid aggregation groups documents into grid cells for geographical analysis. Each grid cell corresponds to a [map tile](https://en.wikipedia.org/wiki/Tiled_web_map) and is identified using the `{zoom}/{x}/{y}` format. You can aggregate documents on [geopoint]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/) or [geoshape]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape/) fields using a geotile grid aggregation. One notable difference is that a geopoint is only present in one bucket, but a geoshape is counted in all geotile grid cells with which it intersects. ## Precision @@ -534,7 +533,7 @@ When aggregating geoshapes, one geoshape can be counted for multiple buckets bec ``` -Currently, OpenSearch supports geoshape aggregation through the API but not in OpenSearch Dashboards visualizations. If you'd like to see geoshape aggregation implemented for visualizations, upvote the related [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250). +OpenSearch supports geoshape aggregation through the API but not in OpenSearch Dashboards visualizations. If you'd like to see geoshape aggregation implemented for visualizations, upvote the related [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250). {: .note} ## Supported parameters @@ -544,7 +543,7 @@ Geotile grid aggregation requests support the following parameters. Parameter | Data type | Description :--- | :--- | :--- field | String | The field that contains the geopoints. This field must be mapped as a `geo_point` field. If the field contains an array, all array values are aggregated. Required. -precision | Integer | The granularity level used to determine grid cells for bucketing results. Cells cannot exceed the specified size (diagonal) of the required precision. Valid values are in the [0, 29] range. Optional. Default is 7. -bounds | Object | The bounding box for filtering geopoints. The bounding box is defined by the upper-left and lower-right vertices. The vertices are specified as geopoints in one of the following formats:
- An object with a latitude and longitude
- An array in the [`longitude`, `latitude`] format
- A string in the "`latitude`,`longitude`" format
- A geohash
- WKT
See the [geopoint formats]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) for formatting examples. Optional. -size | Integer | The maximum number of buckets to return. When there are more buckets than `size`, OpenSearch returns buckets with more documents. Optional. Default is 10,000. -shard_size | Integer | The maximum number of buckets to return from each shard. Optional. Default is max (10, `size` · number of shards), which provides a more accurate count of more highly prioritized buckets. \ No newline at end of file +`precision` | Integer | The granularity level used to determine grid cells for bucketing results. Cells cannot exceed the specified size (diagonal) of the required precision. Valid values are in the [0, 29] range. Optional. Default is 7. +`bounds` | Object | The bounding box for filtering geopoints. The bounding box is defined by the upper-left and lower-right vertices. The vertices are specified as geopoints in one of the following formats:
- An object with a latitude and longitude
- An array in the [`longitude`, `latitude`] format
- A string in the "`latitude`,`longitude`" format
- A geohash
- WKT
See the [geopoint formats]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) for formatting examples. Optional. +`size` | Integer | The maximum number of buckets to return. When there are more buckets than `size`, OpenSearch returns buckets with more documents. Optional. Default is 10,000. +`shard_size` | Integer | The maximum number of buckets to return from each shard. Optional. Default is max (10, `size` · number of shards), which provides a more accurate count of more highly prioritized buckets. \ No newline at end of file diff --git a/_aggregations/bucket/global.md b/_aggregations/bucket/global.md index bfd516b8..36915d50 100644 --- a/_aggregations/bucket/global.md +++ b/_aggregations/bucket/global.md @@ -2,20 +2,24 @@ layout: default title: Global parent: Bucket aggregations -grand_parent: Aggregations nav_order: 90 redirect_from: - /query-dsl/aggregations/bucket/global/ --- -# Global aggregations +# Global aggregation -The `global` aggregations lets you break out of the aggregation context of a filter aggregation. Even if you have included a filter query that narrows down a set of documents, the `global` aggregation aggregates on all documents as if the filter query wasn't there. It ignores the `filter` aggregation and implicitly assumes the `match_all` query. +The `global` aggregation creates a single bucket containing all documents in the index, regardless of the search query. Subaggregations nested inside `global` operate on the full document set, allowing you to compare filtered metrics against overall metrics in the same request. -The following example returns the `avg` value of the `taxful_total_price` field from all documents in the index: +The `global` aggregation can only be placed as a top-level aggregation. Nesting it inside another bucket aggregation has no effect. +{: .note} + +## Example + +The following example computes two averages in a single request: one scoped to the query (orders under $50) and one across all documents using the `global` aggregation: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "query": { @@ -35,25 +39,57 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } } } + }, + "filtered_avg": { + "avg": { + "field": "taxful_total_price" + } } } } ``` {% include copy-curl.html %} -#### Example response +## Example response ```json -... -"aggregations" : { - "total_avg_amount" : { - "doc_count" : 4675, - "avg_price" : { - "value" : 75.05542864304813 +{ + "took": 19, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1633, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "total_avg_amount": { + "doc_count": 4675, + "avg_price": { + "value": 75.05542864304813 + } + }, + "filtered_avg": { + "value": 38.363175998928355 } } - } } ``` -You can see that the average value for the `taxful_total_price` field is 75.05 and not the 38.36 as seen in the `filter` example when the query matched. \ No newline at end of file +The `total_avg_amount` aggregation reports the average across all 4,675 documents ($75.06), while `filtered_avg` reports the average only for the 1,633 documents matching the query ($38.36). + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The total number of documents in the index, independent of the search query. | diff --git a/_aggregations/bucket/histogram.md b/_aggregations/bucket/histogram.md index 0d9f2bb9..9a858f8d 100644 --- a/_aggregations/bucket/histogram.md +++ b/_aggregations/bucket/histogram.md @@ -2,29 +2,48 @@ layout: default title: Histogram parent: Bucket aggregations -grand_parent: Aggregations nav_order: 100 redirect_from: - /query-dsl/aggregations/bucket/histogram/ --- -# Histogram aggregations +# Histogram aggregation -The `histogram` aggregation buckets documents based on a specified interval. +The `histogram` aggregation divides a numeric field's value range into fixed-width intervals and counts documents in each interval. Each bucket's `key` represents the lower bound of that interval, computed as `Math.floor((value - offset) / interval) * interval + offset`. -With `histogram` aggregations, you can visualize the distributions of values in a given range of documents very easily. Now OpenSearch doesn’t give you back an actual graph of course, that’s what OpenSearch Dashboards is for. But it'll give you the JSON response that you can use to construct your own graph. +## Parameters -The following example buckets the `number_of_bytes` field by 10,000 intervals: +The `histogram` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The numeric field to aggregate on. | +| `interval` | Required | Number | The width of each bucket. Must be a positive value. | +| `min_doc_count` | Optional | Integer | The minimum number of documents required for a bucket to appear in the response. Set to `1` to omit empty buckets. Default is `0` (empty buckets are included). | +| `extended_bounds` | Optional | Object | Guarantees that buckets exist from `min` to `max`, even if no documents fall in that range. Does not filter out buckets beyond the bounds---to exclude buckets outside a range, use `hard_bounds` or a range query. Accepts `min` and `max` values. Only meaningful when `min_doc_count` is `0`. | +| `hard_bounds` | Optional | Object | Limits the range of buckets in the response. Accepts `min` and `max` values. Buckets outside these bounds are excluded. | +| `offset` | Optional | Number | Shifts bucket boundaries by the specified amount. Must be in the range [0, `interval`). Default is `0`. | +| `keyed` | Optional | Boolean | When `true`, returns buckets as an object keyed by bucket value instead of an array. Default is `false`. | +| `order` | Optional | Object | Controls the sort order of buckets. Accepts `_key` or `_count`, each with `asc` or `desc`. Default is `{"_key": "asc"}`. | +| `missing` | Optional | Number | The value to assign to documents missing the target field, placing them in the corresponding bucket. By default, missing documents are ignored. | + +When aggregating a [numeric range field]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/range/) rather than a single-value numeric field, a document can appear in multiple buckets---one for each interval between its lower and upper bounds. +{: .note} + +## Example: Basic histogram + +The following example groups e-commerce order totals into $50 intervals, showing only buckets that contain at least one document: ```json -GET opensearch_dashboards_sample_data_logs/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "number_of_bytes": { + "price_histogram": { "histogram": { - "field": "bytes", - "interval": 10000 + "field": "taxful_total_price", + "interval": 50, + "min_doc_count": 1 } } } @@ -32,23 +51,102 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +## Example: Using offset to shift bucket boundaries + +The `offset` parameter shifts where bucket boundaries start. The following example uses an offset of `10`, so buckets start at 10, 60, 110, and so on instead of 0, 50, 100: ```json -... -"aggregations" : { - "number_of_bytes" : { - "buckets" : [ - { - "key" : 0.0, - "doc_count" : 13372 - }, - { - "key" : 10000.0, - "doc_count" : 702 +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_histogram": { + "histogram": { + "field": "taxful_total_price", + "interval": 50, + "offset": 10, + "min_doc_count": 1 } - ] + } } - } } ``` +{% include copy-curl.html %} + +## Example response + +The following response corresponds to the basic histogram example: + +```json +{ + "took": 2, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "price_histogram": { + "buckets": [ + { + "key": 0.0, + "doc_count": 1633 + }, + { + "key": 50.0, + "doc_count": 2036 + }, + { + "key": 100.0, + "doc_count": 724 + }, + { + "key": 150.0, + "doc_count": 205 + }, + { + "key": 200.0, + "doc_count": 53 + }, + { + "key": 250.0, + "doc_count": 14 + }, + { + "key": 300.0, + "doc_count": 7 + }, + { + "key": 350.0, + "doc_count": 2 + }, + { + "key": 2250.0, + "doc_count": 1 + } + ] + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array or Object | The histogram buckets. Returned as an array by default, or as an object when `keyed` is `true`. | +| `buckets.key` | Double | The lower bound of the bucket interval. | +| `buckets.doc_count` | Integer | The number of documents in the bucket. | diff --git a/_aggregations/bucket/index.md b/_aggregations/bucket/index.md index 1658c06e..f5cac8bf 100644 --- a/_aggregations/bucket/index.md +++ b/_aggregations/bucket/index.md @@ -9,6 +9,7 @@ redirect_from: - /query-dsl/aggregations/bucket-agg/ - /query-dsl/aggregations/bucket/ - /aggregations/bucket-agg/ + - /aggregations/bucket/ --- # Bucket aggregations @@ -22,6 +23,8 @@ You can use bucket aggregations to implement faceted navigation (usually placed OpenSearch supports the following bucket aggregations: - [Adjacency matrix]({{site.url}}{{site.baseurl}}/aggregations/bucket/adjacency-matrix/) +- [Auto-interval date histogram]({{site.url}}{{site.baseurl}}/aggregations/bucket/auto-interval-date-histogram/) +- [Children]({{site.url}}{{site.baseurl}}/aggregations/bucket/children/) - [Date histogram]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-histogram/) - [Date range]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-range/) - [Diversified sampler]({{site.url}}{{site.baseurl}}/aggregations/bucket/diversified-sampler/) @@ -37,9 +40,12 @@ OpenSearch supports the following bucket aggregations: - [Missing]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) - [Multi-terms]({{site.url}}{{site.baseurl}}/aggregations/bucket/multi-terms/) - [Nested]({{site.url}}{{site.baseurl}}/aggregations/bucket/nested/) +- [Parent]({{site.url}}{{site.baseurl}}/aggregations/bucket/parent/) - [Range]({{site.url}}{{site.baseurl}}/aggregations/bucket/range/) +- [Rare terms]({{site.url}}{{site.baseurl}}/aggregations/bucket/rare-terms/) - [Reverse nested]({{site.url}}{{site.baseurl}}/aggregations/bucket/reverse-nested/) - [Sampler]({{site.url}}{{site.baseurl}}/aggregations/bucket/sampler/) - [Significant terms]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-terms/) - [Significant text]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-text/) -- [Terms]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/) \ No newline at end of file +- [Terms]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/) +- [Variable width histogram]({{site.url}}{{site.baseurl}}/aggregations/bucket/variable-width-histogram/) \ No newline at end of file diff --git a/_aggregations/bucket/ip-range.md b/_aggregations/bucket/ip-range.md index 897827d4..5e00f3e0 100644 --- a/_aggregations/bucket/ip-range.md +++ b/_aggregations/bucket/ip-range.md @@ -2,33 +2,85 @@ layout: default title: IP range parent: Bucket aggregations -grand_parent: Aggregations nav_order: 110 redirect_from: - /query-dsl/aggregations/bucket/ip-range/ --- -# IP range aggregations +# IP range aggregation -The `ip_range` aggregation is for IP addresses. -It works on `ip` type fields. You can define the IP ranges and masks in the [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation. +The `ip_range` aggregation groups documents into buckets based on IP address ranges. It operates on fields mapped as `ip` type and supports both explicit `from`/`to` boundaries and [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation using the `mask` parameter. + +## Parameters + +The `ip_range` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The `ip` field to aggregate on. | +| `ranges` | Required | Array | A list of IP ranges. Each range can specify `from` and/or `to` (explicit boundaries), or `mask` (CIDR notation). Optionally include `key` to name the bucket. | +| `keyed` | Optional | Boolean | When `true`, returns buckets as an object keyed by range name instead of an array. Default is `false`. | + +## Example setup + +To try the examples on this page, create an index containing an `ip` field: ```json -GET opensearch_dashboards_sample_data_logs/_search +PUT /network_logs +{ + "mappings": { + "properties": { + "ip": { "type": "ip" }, + "status": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Index some documents: + +```json +POST /network_logs/_bulk?refresh=true +{"index":{}} +{"ip": "10.0.0.1", "status": "ok"} +{"index":{}} +{"ip": "10.0.0.50", "status": "ok"} +{"index":{}} +{"ip": "10.0.0.100", "status": "error"} +{"index":{}} +{"ip": "10.0.0.200", "status": "ok"} +{"index":{}} +{"ip": "10.0.1.5", "status": "ok"} +{"index":{}} +{"ip": "10.0.1.100", "status": "error"} +{"index":{}} +{"ip": "172.16.0.1", "status": "ok"} +{"index":{}} +{"ip": "172.16.0.50", "status": "ok"} +{"index":{}} +{"ip": "192.168.1.1", "status": "ok"} +{"index":{}} +{"ip": "192.168.1.100", "status": "error"} +``` +{% include copy-curl.html %} + +## Example: Explicit IP ranges + +The following example partitions network log entries into three IP ranges using `from` and `to` boundaries: + +```json +GET /network_logs/_search { "size": 0, "aggs": { - "access": { + "ip_ranges": { "ip_range": { "field": "ip", "ranges": [ - { - "from": "1.0.0.0", - "to": "126.158.155.183" - }, - { - "mask": "1.0.0.0/8" - } + { "to": "10.0.1.0" }, + { "from": "10.0.1.0", "to": "172.16.0.0" }, + { "from": "172.16.0.0" } ] } } @@ -37,41 +89,98 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +The buckets are returned as an array with auto-generated keys based on the range boundaries. The `from` value is inclusive and the `to` value is exclusive: ```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 - } - ] - } - } -} -``` - -If you add a document with malformed fields to an index that has `ip_range` set to `false` in its mappings, OpenSearch rejects the entire document. You can set `ignore_malformed` to `true` to specify that OpenSearch should ignore malformed fields. The default is `false`. - -```json -... -"mappings": { - "properties": { - "ips": { - "type": "ip_range", - "ignore_malformed": true +{ + ... + "aggregations": { + "ip_ranges": { + "buckets": [ + { + "key": "*-10.0.1.0", + "to": "10.0.1.0", + "doc_count": 4 + }, + { + "key": "10.0.1.0-172.16.0.0", + "from": "10.0.1.0", + "to": "172.16.0.0", + "doc_count": 2 + }, + { + "key": "172.16.0.0-*", + "from": "172.16.0.0", + "doc_count": 4 + } + ] } } } -``` \ No newline at end of file +``` + +## Example: CIDR masks with keyed response + +You can define ranges using CIDR notation and assign custom keys. Setting `keyed` to `true` returns an object instead of an array. The following example groups traffic by RFC 1918 private address classes: + +```json +GET /network_logs/_search +{ + "size": 0, + "aggs": { + "ip_ranges": { + "ip_range": { + "field": "ip", + "ranges": [ + { "key": "private_a", "mask": "10.0.0.0/8" }, + { "key": "private_b", "mask": "172.16.0.0/12" }, + { "key": "private_c", "mask": "192.168.0.0/16" } + ], + "keyed": true + } + } + } +} +``` +{% include copy-curl.html %} + +With CIDR notation, the response includes the computed `from` and `to` boundaries derived from the mask. Because `keyed` is `true`, buckets are returned as an object with custom keys instead of an array: + +```json +{ + ... + "aggregations": { + "ip_ranges": { + "buckets": { + "private_a": { + "from": "10.0.0.0", + "to": "11.0.0.0", + "doc_count": 6 + }, + "private_b": { + "from": "172.16.0.0", + "to": "172.32.0.0", + "doc_count": 2 + }, + "private_c": { + "from": "192.168.0.0", + "to": "192.169.0.0", + "doc_count": 2 + } + } + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array or Object | The IP range buckets. Returned as an array by default, or as an object when `keyed` is `true`. | +| `buckets.key` | String | The auto-generated range label (for example, `*-10.0.1.0` or `10.0.0.0/24`), or a custom key if specified. | +| `buckets.from` | String | The lower bound IP address of the range (inclusive). | +| `buckets.to` | String | The upper bound IP address of the range (exclusive). | +| `buckets.doc_count` | Integer | The number of documents with an IP address in this range. | diff --git a/_aggregations/bucket/missing.md b/_aggregations/bucket/missing.md index 54707685..a6156c20 100644 --- a/_aggregations/bucket/missing.md +++ b/_aggregations/bucket/missing.md @@ -2,28 +2,58 @@ layout: default title: Missing parent: Bucket aggregations -grand_parent: Aggregations nav_order: 120 redirect_from: - /query-dsl/aggregations/bucket/missing/ --- -# Missing aggregations +# Missing aggregation -If you have documents in your index that don’t contain the aggregating field at all or the aggregating field has a value of NULL, use the `missing` parameter to specify the name of the bucket such documents should be placed in. +The `missing` aggregation creates a single bucket containing all documents that do not have a value for a specified field. A document is considered missing if the field is absent, `null`, or an empty array. If the field mapping defines a [`null_value`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/null-value/), explicit `null` values are indexed as that value and are not counted as missing. This aggregation is commonly paired with other bucket aggregations to account for documents that cannot be placed in any other bucket because they lack the required field. -The following example adds any missing values to a bucket named "N/A": +## Parameters + +The `missing` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The field to check for missing values. | + +If the specified field is not mapped in the index, every document is counted as missing, and no error is returned. A misspelled field name therefore produces a bucket containing all documents. If the `doc_count` equals the total number of documents, verify the field name. +{: .note} + +## Example + +The following request indexes three products into a `product_ratings` index. Product C has no `rating` field: ```json -GET opensearch_dashboards_sample_data_logs/_search +POST product_ratings/_bulk?refresh +{ "index": { "_id": "1" } } +{ "name": "Product A", "rating": 4.5, "num_reviews": 100 } +{ "index": { "_id": "2" } } +{ "name": "Product B", "rating": 3.8, "num_reviews": 50 } +{ "index": { "_id": "3" } } +{ "name": "Product C" } +``` +{% include copy-curl.html %} + +The following aggregation counts how many products are missing a rating and includes a `terms` subaggregation to identify them: + +```json +GET /product_ratings/_search { "size": 0, "aggs": { - "response_codes": { - "terms": { - "field": "response.keyword", - "size": 10, - "missing": "N/A" + "without_rating": { + "missing": { + "field": "rating" + }, + "aggs": { + "names": { + "terms": { + "field": "name.keyword" + } + } } } } @@ -31,52 +61,35 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -Because the default value for the `min_doc_count` parameter is 1, the `missing` parameter doesn't return any buckets in its response. Set `min_doc_count` parameter to 0 to see the "N/A" bucket in the response: +## Example response + +The response shows that one product (Product C) is missing the `rating` field: ```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 + ... + "aggregations": { + "without_rating": { + "doc_count": 1, + "names": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "Product C", + "doc_count": 1 + } + ] } } } } ``` -#### Example response +## Response body fields -```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 - } - ] - } - } -} -``` \ No newline at end of file +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The number of documents missing the specified field. | diff --git a/_aggregations/bucket/multi-terms.md b/_aggregations/bucket/multi-terms.md index eb779e7c..c2108630 100644 --- a/_aggregations/bucket/multi-terms.md +++ b/_aggregations/bucket/multi-terms.md @@ -2,120 +2,193 @@ layout: default title: Multi-terms parent: Bucket aggregations -grand_parent: Aggregations nav_order: 130 redirect_from: + - /query-dsl/aggregations/bucket/multi-terms/ - /query-dsl/aggregations/multi-terms/ --- -# Multi-terms aggregations +# Multi-terms aggregation -Similar to the `terms` bucket aggregation, you can also search for multiple terms using the `multi_terms` aggregation. Multi-terms aggregations are useful when you need to sort by document count, or when you need to sort by a metric aggregation on a composite key and get the top `n` results. For example, you could search for a specific number of documents (e.g., 1000) and the number of servers per location that show CPU usage greater than 90%. The top number of results would be returned for this multi-term query. +The `multi_terms` aggregation creates buckets based on the combination of values from multiple fields. Each bucket represents a unique composite key, and documents are grouped by matching all specified term values simultaneously. This is useful when you need to find the top combinations ranked by document count or by a metric subaggregation. -The `multi_terms` aggregation does consume more memory than a `terms` aggregation, so its performance might be slower. -{: .tip } +The `multi_terms` aggregation consumes more memory than a single `terms` aggregation because it builds composite keys across multiple fields. +{: .note} -## Multi-terms aggregation parameters +## Parameters -Parameter | Description -:--- | :--- -multi_terms | Indicates a multi-terms aggregation that gathers buckets of documents together based on criteria specified by multiple terms. -size | Specifies the number of buckets to return. Default is 10. -order | Indicates the order to sort the buckets. By default, buckets are ordered according to document count per bucket. If the buckets contain the same document count, then `order` can be explicitly set to the term value instead of document count. (e.g., set `order` to "max-cpu"). -doc_count | Specifies the number of documents to be returned in each bucket. By default, the top 10 terms are returned. +The `multi_terms` aggregation takes the following parameters. -#### Example request +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `terms` | Required | Array | An array of objects, each specifying a field or script that provides one part of the composite key. | +| `size` | Optional | Integer | The number of composite buckets to return. Default is `10`. | +| `shard_size` | Optional | Integer | The number of candidate buckets collected from each shard. Higher values improve accuracy at the cost of memory. Must be greater than or equal to `size`. Default is higher than `size` to improve accuracy. | +| `min_doc_count` | Optional | Integer | The minimum document count required for a bucket to appear in the response. Default is `1`. | +| `order` | Optional | Object | Controls how buckets are sorted. Accepts `_count`, `_key`, or the name of a subaggregation metric. Default is `{"_count": "desc"}`. | +| `show_term_doc_count_error` | Optional | Boolean | When `true`, includes an error estimate for each term's document count. Default is `false`. | + +Each object in the `terms` array supports the following parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `field` | String | The field to aggregate on. Must be a `keyword`, `numeric`, `ip`, `boolean`, or `date` field. Either `field` or `script` is required. | +| `script` | Object | A script that generates the values to aggregate on. Either `field` or `script` is required. When used with `field`, the script acts as a value script and receives the field value as `_value`. | +| `missing` | String or number | The value to use for documents that do not contain the field. By default, documents that do not contain the field are excluded from the aggregation. | +| `exclude` | String or array of strings | The values to exclude from the aggregation. Specify an array of exact values or a regular expression. | +| `format` | String | The format of the term in `key_as_string`, such as a date format for a `date` field. | +| `time_zone` | String | The time zone used to format `date` values, such as `+05:00` or `America/New_York`. Default is `UTC`. | +| `value_type` | String | The data type of the values produced by a `script`, such as `long` or `string`. | + +## Example: Grouping by multiple fields + +The following example identifies the most popular product categories for each gender by grouping orders on both `customer_gender` and `category` simultaneously. This query reveals the gender-category pairs that generate the most orders: ```json -GET sample-index100/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { - "size": 0, + "size": 0, "aggs": { - "hot": { + "gender_category": { "multi_terms": { - "terms": [{ - "field": "region" - },{ - "field": "host" - }], - "order": {"max-cpu": "desc"} - }, - "aggs": { - "max-cpu": { "max": { "field": "cpu" } } - } + "terms": [ + { "field": "customer_gender" }, + { "field": "category.keyword" } + ], + "size": 5 + } } } } ``` {% include copy-curl.html %} -#### Example response +The response contains composite key buckets ordered by descending document count: ```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": { + "gender_category": { "doc_count_error_upper_bound": 0, - "sum_other_doc_count": 0, + "sum_other_doc_count": 756, "buckets": [ { "key": [ - "dub", - "h1" + "MALE", + "Men's Clothing" ], - "key_as_string": "dub|h1", - "doc_count": 2, - "max-cpu": { - "value": 90.0 + "key_as_string": "MALE|Men's Clothing", + "doc_count": 1963 + }, + { + "key": [ + "FEMALE", + "Women's Clothing" + ], + "key_as_string": "FEMALE|Women's Clothing", + "doc_count": 1903 + }, + { + "key": [ + "FEMALE", + "Women's Shoes" + ], + "key_as_string": "FEMALE|Women's Shoes", + "doc_count": 1136 + }, + { + "key": [ + "MALE", + "Men's Shoes" + ], + "key_as_string": "MALE|Men's Shoes", + "doc_count": 921 + }, + { + "key": [ + "FEMALE", + "Women's Accessories" + ], + "key_as_string": "FEMALE|Women's Accessories", + "doc_count": 730 + } + ] + } + } +} +``` + +## Example: Ordering by a subaggregation metric + +The following example finds the gender-category combinations that produce the highest average order values: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "gender_category": { + "multi_terms": { + "terms": [ + { "field": "customer_gender" }, + { "field": "category.keyword" } + ], + "size": 3, + "order": { "avg_price": "desc" } + }, + "aggs": { + "avg_price": { + "avg": { "field": "taxful_total_price" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response ranks buckets by the `avg_price` subaggregation rather than document count: + +```json +{ + ... + "aggregations": { + "gender_category": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 5252, + "buckets": [ + { + "key": [ + "MALE", + "Women's Accessories" + ], + "key_as_string": "MALE|Women's Accessories", + "doc_count": 100, + "avg_price": { + "value": 101.21328125 } }, { "key": [ - "dub", - "h2" + "MALE", + "Men's Shoes" ], - "key_as_string": "dub|h2", - "doc_count": 2, - "max-cpu": { - "value": 70.0 + "key_as_string": "MALE|Men's Shoes", + "doc_count": 921, + "avg_price": { + "value": 97.41267983170466 } }, { "key": [ - "iad", - "h2" + "FEMALE", + "Women's Shoes" ], - "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 + "key_as_string": "FEMALE|Women's Shoes", + "doc_count": 1136, + "avg_price": { + "value": 92.8513836927817 } } ] @@ -123,3 +196,100 @@ GET sample-index100/_search } } ``` + +## Example: Handling documents with missing fields + +By default, a document that does not contain one of the `terms` fields is excluded from the aggregation. To include these documents, specify a `missing` value for the field. + +Create an index containing two `keyword` fields: + +```json +PUT /products +{ + "mappings": { + "properties": { + "brand": { "type": "keyword" }, + "color": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Index three documents. The second document does not contain a `color` field, and the third document does not contain a `brand` field: + +```json +POST /products/_bulk?refresh=true +{ "index": {} } +{ "brand": "Acme", "color": "red" } +{ "index": {} } +{ "brand": "Acme" } +{ "index": {} } +{ "color": "blue" } +``` +{% include copy-curl.html %} + +The following request groups products by brand and color, assigning the value `unknown` to documents that do not contain a `color` field: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "brand_color": { + "multi_terms": { + "terms": [ + { "field": "brand" }, + { "field": "color", "missing": "unknown" } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains a bucket for the document without a `color` field, using `unknown` as its color. The document without a `brand` field does not appear in any bucket because no `missing` value is specified for `brand`: + +```json +{ + ... + "aggregations": { + "brand_color": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": [ + "Acme", + "red" + ], + "key_as_string": "Acme|red", + "doc_count": 1 + }, + { + "key": [ + "Acme", + "unknown" + ], + "key_as_string": "Acme|unknown", + "doc_count": 1 + } + ] + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count_error_upper_bound` | Integer | The maximum potential error in document counts for any bucket not included in the response. | +| `sum_other_doc_count` | Integer | The total document count of all buckets that did not make it into the top `size` results. | +| `buckets` | Array | The composite key buckets, sorted according to `order`. | +| `buckets.key` | Array | An array of values representing the composite key for this bucket, in the same order as the `terms` list. | +| `buckets.key_as_string` | String | The composite key formatted as a pipe-delimited string. | +| `buckets.doc_count` | Integer | The number of documents matching this key combination. | diff --git a/_aggregations/bucket/nested.md b/_aggregations/bucket/nested.md index 94a0f441..1aecb884 100644 --- a/_aggregations/bucket/nested.md +++ b/_aggregations/bucket/nested.md @@ -2,85 +2,28 @@ layout: default title: Nested parent: Bucket aggregations -grand_parent: Aggregations nav_order: 140 redirect_from: - /query-dsl/aggregations/bucket/nested/ --- -# Nested aggregations +# Nested aggregation -The `nested` aggregation lets you aggregate on fields inside a nested object. The `nested` type is a specialized version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other +The `nested` aggregation lets you aggregate on fields inside a [nested]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/nested/) object. The `nested` type is a specialized version of the `object` data type that indexes each element of an array of objects as a separate, hidden document. This preserves the relationship between fields within the same array element so they can be queried and aggregated together. -With the `object` type, all the data is stored in the same document, so matches for a search can go across sub documents. For example, imagine a `logs` index with `pages` mapped as an `object` datatype: +## Nested aggregation example + +To aggregate over fields inside a nested array, specify the `path` to the nested field and define subaggregations under it: ```json -PUT logs/_doc/0 -{ - "response": "200", - "pages": [ - { - "page": "landing", - "load_time": 200 - }, - { - "page": "blog", - "load_time": 500 - } - ] -} -``` -{% include copy-curl.html %} - -OpenSearch merges all sub-properties of the entity relations that looks something like this: - -```json -{ - "logs": { - "pages": ["landing", "blog"], - "load_time": ["200", "500"] - } -} -``` - -So, if you wanted to search this index with `pages=landing` and `load_time=500`, this document matches the criteria even though the `load_time` value for landing is 200. - -If you want to make sure such cross-object matches don’t happen, map the field as a `nested` type: - -```json -PUT logs -{ - "mappings": { - "properties": { - "pages": { - "type": "nested", - "properties": { - "page": { "type": "text" }, - "load_time": { "type": "double" } - } - } - } - } -} -``` -{% include copy-curl.html %} - -Nested documents allow you to index the same JSON document but will keep your pages in separate Lucene documents, making only searches like `pages=landing` and `load_time=200` return the expected result. Internally, nested objects index each object in the array as a separate hidden document, meaning that each nested object can be queried independently of the others. - -You have to specify a nested path relative to parent that contains the nested documents: - - -```json -GET logs/_search +GET logs-nested/_search { "query": { "match": { "response": "200" } }, "aggs": { "pages": { - "nested": { - "path": "pages" - }, + "nested": { "path": "pages" }, "aggs": { "min_load_time": { "min": { "field": "pages.load_time" } } } @@ -90,17 +33,43 @@ GET logs/_search ``` {% include copy-curl.html %} -#### Example response +The returned hit contains the requested aggregation: ```json -... -"aggregations" : { - "pages" : { - "doc_count" : 2, - "min_price" : { - "value" : 200.0 +"hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs-nested", + "_id": "0", + "_score": 1, + "_source": { + "response": "200", + "pages": [ + { + "page": "landing", + "load_time": 200 + }, + { + "page": "blog", + "load_time": 500 + } + ] + } + } + ] + }, + "aggregations": { + "pages": { + "doc_count": 2, + "min_load_time": { + "value": 200 + } } } - } -} ``` + diff --git a/_aggregations/bucket/parent.md b/_aggregations/bucket/parent.md new file mode 100644 index 00000000..426d9c23 --- /dev/null +++ b/_aggregations/bucket/parent.md @@ -0,0 +1,153 @@ +--- +layout: default +title: Parent +parent: Bucket aggregations +nav_order: 145 +--- + +# Parent aggregation + +The `parent` aggregation is a bucket aggregation that creates a single bucket containing parent documents, based on parent-child relationships defined in your index. This aggregation enables you to perform analytics on parent documents that have the same matching child documents, allowing for powerful hierarchical data analysis. + +The `parent` aggregation works with the [`join` field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/), which establishes parent-child relationships within documents in the same index. + +The `parent` aggregation identifies parent documents that have matching child documents, whereas the [`children` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/children/) identifies child documents that match a certain child relation. Both aggregations take the child relation name as input. + + +## Parameters + +The `parent` aggregation takes the following parameters: + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `type` | Required | String | The name of the child type from the `join` field. | + +## Example + +The following example builds a small company database with three employees. The employee records each have a child `join` relationship with a parent department record. + +First, create a `company` index with a `join` field that maps departments (parents) to employees (children): + +```json +PUT /company +{ + "mappings": { + "properties": { + "join_field": { + "type": "join", + "relations": { + "department": "employee" + } + }, + "department_name": { + "type": "keyword" + }, + "employee_name": { + "type": "keyword" + }, + "salary": { + "type": "double" + }, + "hire_date": { + "type": "date" + } + } + } +} +``` +{% include copy-curl.html %} + +Next, populate the data with three departments and three employees. The parent-child assignments are presented in the following table. + +| Department (parent) | Employees (children) | +| :-- | :-- | +| `Accounting` | `Abel Anderson`, `Betty Billings` | +| `Engineering` | `Carl Carter` | +| `HR` | none | + +The `routing` parameter ensures that both parent and child documents are stored on the same shard, which is required in order for parent-child relationships to function correctly in OpenSearch: + +```json +POST _bulk?routing=1 +{ "create": { "_index": "company", "_id": "1" } } +{ "type": "department", "department_name": "Accounting", "join_field": "department" } +{ "create": { "_index": "company", "_id": "2" } } +{ "type": "department", "department_name": "Engineering", "join_field": "department" } +{ "create": { "_index": "company", "_id": "3" } } +{ "type": "department", "department_name": "HR", "join_field": "department" } +{ "create": { "_index": "company", "_id": "4" } } +{ "type": "employee", "employee_name": "Abel Anderson", "salary": 120000, "hire_date": "2024-04-04", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "5" } } +{ "type": "employee", "employee_name": "Betty Billings", "salary": 140000, "hire_date": "2023-05-05", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "6" } } +{ "type": "employee", "employee_name": "Carl Carter", "salary": 140000, "hire_date": "2020-06-06", "join_field": { "name": "employee", "parent": "2" } } +``` +{% include copy-curl.html %} + +Lastly, run an aggregation of all the departments that have a parent relationship with one or more employees: + +```json +GET /company/_search +{ + "size": 0, + "aggs": { + "all_departments": { + "parent": { + "type": "employee" + }, + "aggs": { + "departments": { + "terms": { + "field": "department_name" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The `all_departments` parent aggregation returns all the departments with employee child documents. Note that the HR department is not represented: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 6, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "all_departments": { + "doc_count": 2, + "departments": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "Accounting", + "doc_count": 1 + }, + { + "key": "Engineering", + "doc_count": 1 + } + ] + } + } + } +} +``` \ No newline at end of file diff --git a/_aggregations/bucket/range.md b/_aggregations/bucket/range.md index 61ec2f62..37afc397 100644 --- a/_aggregations/bucket/range.md +++ b/_aggregations/bucket/range.md @@ -2,40 +2,111 @@ layout: default title: Range parent: Bucket aggregations -grand_parent: Aggregations nav_order: 150 redirect_from: - /query-dsl/aggregations/bucket/range/ --- -# Range aggregations +# Range aggregation -The `range` aggregation lets you define the range for each bucket. +The `range` aggregation groups documents into buckets based on value ranges that you define. Each bucket captures documents whose field value falls within its specified `from` (inclusive) and `to` (exclusive) boundaries. Unlike the [`histogram` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/histogram/), which creates uniform intervals automatically, `range` lets you define arbitrary, non-uniform boundaries. -For example, you can find the number of bytes between 1000 and 2000, 2000 and 3000, and 3000 and 4000. -Within the `range` parameter, you can define ranges as objects of an array. +## Parameters + +The `range` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Optional | String | The numeric field to aggregate on. Either `field` or `script` is required. | +| `script` | Optional | Object | A script that produces the value to aggregate on. Either `field` or `script` is required. When used with `field`, the script acts as a value script and receives the field value as `_value`. | +| `ranges` | Required | Array | A list of range boundaries. Each entry can include `from`, `to`, and optionally `key`. | +| `keyed` | Optional | Boolean | When `true`, returns buckets as an object keyed by range name instead of an array. Default is `false`. | +| `missing` | Optional | Number | The value to use for documents missing the target field. By default, missing documents are ignored. | + +## Example: Custom-named price tiers with subaggregation + +The following example segments e-commerce orders into three price tiers and computes the average order value within each tier: ```json -GET opensearch_dashboards_sample_data_logs/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "number_of_bytes_distribution": { + "price_tiers": { "range": { - "field": "bytes", + "field": "taxful_total_price", + "keyed": true, "ranges": [ - { - "from": 1000, - "to": 2000 - }, - { - "from": 2000, - "to": 3000 - }, - { - "from": 3000, - "to": 4000 + { "key": "budget", "to": 50 }, + { "key": "mid_range", "from": 50, "to": 100 }, + { "key": "premium", "from": 100 } + ] + }, + "aggs": { + "avg_price": { + "avg": { "field": "taxful_total_price" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response groups orders into labeled tiers with their average prices: + +```json +{ + ... + "aggregations": { + "price_tiers": { + "buckets": { + "budget": { + "to": 50.0, + "doc_count": 1633, + "avg_price": { + "value": 38.363175998928355 } + }, + "mid_range": { + "from": 50.0, + "to": 100.0, + "doc_count": 2036, + "avg_price": { + "value": 72.34457883104126 + } + }, + "premium": { + "from": 100.0, + "doc_count": 1006, + "avg_price": { + "value": 140.10288270377734 + } + } + } + } + } +} +``` + +## Example: Using a script + +You can use a script instead of a field to compute values on the fly. The following example applies a 10% markup to prices before bucketing: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "marked_up_tiers": { + "range": { + "script": { + "source": "doc['taxful_total_price'].value * 1.1" + }, + "ranges": [ + { "to": 55 }, + { "from": 55, "to": 110 }, + { "from": 110 } ] } } @@ -44,35 +115,41 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -The response includes the `from` key values and excludes the `to` key values: +## Example: Transforming field values with a value script -#### Example response +When you specify both `field` and `script`, the script receives each field value as the `_value` variable. The following example converts USD prices to euros (at a 0.92 rate) before evaluating which range they fall into: ```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 +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_in_euros": { + "range": { + "field": "taxful_total_price", + "script": { + "source": "_value * 0.92" + }, + "ranges": [ + { "to": 46 }, + { "from": 46, "to": 92 }, + { "from": 92 } + ] } - ] + } } - } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array or Object | The range buckets. Returned as an array by default, or as an object when `keyed` is `true`. | +| `buckets.key` | String | The auto-generated range label (for example, `*-50.0` or `50.0-100.0`), or a custom key if specified. | +| `buckets.from` | Double | The lower bound of the range (inclusive). Omitted for open-ended ranges with no lower bound. | +| `buckets.to` | Double | The upper bound of the range (exclusive). Omitted for open-ended ranges with no upper bound. | +| `buckets.doc_count` | Integer | The number of documents falling within this range. | diff --git a/_aggregations/bucket/rare-terms.md b/_aggregations/bucket/rare-terms.md new file mode 100644 index 00000000..c640393a --- /dev/null +++ b/_aggregations/bucket/rare-terms.md @@ -0,0 +1,348 @@ +--- +layout: default +title: Rare terms +parent: Bucket aggregations +nav_order: 155 +--- + +# Rare terms aggregation + +The `rare_terms` aggregation is a bucket aggregation that identifies infrequent terms in a dataset. In contrast to the `terms` aggregation, which finds the most common terms, the `rare_terms` aggregation finds terms that appear with the lowest frequency. The `rare_terms` aggregation is suitable for applications like anomaly detection, long-tail analysis, and exception reporting. + +It is possible to use `terms` to search for infrequent values by ordering the returned values by ascending count (`"order": {"count": "asc"}`). However, we strongly discourage this practice because it can lead to inaccurate results when multiple shards are involved. A term that is globally infrequent might not appear as infrequent on every individual shard or might be entirely absent from the least frequent results returned by some shards. Conversely, a term that appears infrequently on one shard might be common on another. In both scenarios, rare terms can be missed during shard-level aggregation, resulting in incorrect overall results. Instead of the `terms` aggregation, we recommend using the `rare_terms` aggregation, which is specifically designed to handle these cases more accurately. +{: .warning} + +## Approximated results + +Computing exact results for the `rare_terms` aggregation necessitates compiling a complete map of the values on all shards, which requires excessive runtime memory. For this reason, the `rare_terms` aggregation results are approximated. + +Most errors in `rare_terms` computations are _false negatives_ or "missed" values, which define the _sensitivity_ of the aggregation's detection test. The `rare_terms` aggregation uses a CuckooFilter algorithm to achieve a balance of appropriate sensitivity and acceptable memory use. For a description of the CuckooFilter algorithm, see [this paper](https://www.cs.cmu.edu/~dga/papers/cuckoo-conext2014.pdf). + +## Controlling sensitivity + +Sensitivity error in the `rare_terms` aggregation algorithm is measured as the fraction of rare values that are missed, or `false negatives/target values`. For example, if the aggregation misses 100 rare values in a dataset with 5,000 rare values, sensitivity error is `100/5000 = 0.02`, or 2%. + +You can adjust the `precision` parameter in `rare_terms` aggregations to control the trade-off between sensitivity and memory use. + +These factors also affect the sensitivity-memory trade-off: + +- The total number of unique values +- The fraction of rare items in the dataset + +The following guidelines can help you decide which `precision` value to use. + +### Calculating memory use + +Runtime memory use is described in absolute terms, typically in MB of RAM. + +Memory use increases linearly with the number of unique items. The linear scaling factor varies from roughly 1.0 to 2.5 MB per 1 million unique values, depending on the `precision` parameter. For the default `precision` of `0.001`, the memory cost is about 1.75 MB per 1 million unique values. + +### Managing sensitivity error + +Sensitivity error increases linearly with the total number of unique values. For information about estimating the number of unique values, see [Cardinality aggregation]({{site.url}}{{site.baseurl}}/aggregations/metric/cardinality/). + +Sensitivity error rarely exceeds 2.5% at the default `precision`, even for datasets with 10--20 million unique values. For a `precision` of `0.00001`, sensitivity error is rarely above 0.6%. However, a very low absolute number of rare values can cause large variances in the error rate (if there are only two rare values, missing one of them results in a 50% error rate). + + +## Compatibility with other aggregations + +The `rare_terms` aggregation uses breadth-first collection mode and is incompatible with aggregations that require depth-first collection mode in some subaggregations and nesting configurations. + +For more information about breadth-first search in OpenSearch, see [Collect mode]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms#collect-mode). + + +## Parameters + +The `rare_terms` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The field to analyze for rare terms. Must be of a numeric type or a text type with a `keyword` mapping. | +| `max_doc_count` | Optional | Integer | The maximum document count required in order for a term to be considered rare. Default is `1`. Maximum is `100`. | +| `precision` | Optional | Integer | Controls the precision of the algorithm used to identify rare terms. Higher values provide more precise results but consume more memory. Default is `0.001`. Minimum (most precise allowable) is `0.00001`. | +| `include` | Optional | Array/regex | Terms to include in the result. Can be a regular expression or an array of values. | +| `exclude` | Optional | Array/regex | Terms to exclude from the result. Can be a regular expression or an array of values. | +| `missing` | Optional | String | The value to use for documents that do not have a value for the field being aggregated. | + + +## Example + +The following request returns all destination airport codes that appear only once in the OpenSearch Dashboards sample flight data: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 1 + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response shows that there are two airports that meet the criterion of appearing only once in the data: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "BUF", + "doc_count": 1 + } + ] + } + } +} +``` + + +## Document count limit + +Use the `max_doc_count` parameter to specify the largest document count that the `rare_terms` aggregation can return. There is no limit on the number of terms returned by `rare_terms`, so a large `max_doc_count` value can potentially return very large result sets. For this reason, `100` is the largest allowable `max_doc_count`. + +The following request returns all destination airport codes that appear two times at most in the OpenSearch Dashboards sample flight data: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2 + } + } + } +} +``` +{% include copy-curl.html %} + +The response shows that seven destination airport codes meet the criterion of appearing in two or fewer documents, including the two from the previous example: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "BUF", + "doc_count": 1 + }, + { + "key": "ABQ", + "doc_count": 2 + }, + { + "key": "AUH", + "doc_count": 2 + }, + { + "key": "BIL", + "doc_count": 2 + }, + { + "key": "BWI", + "doc_count": 2 + }, + { + "key": "MAD", + "doc_count": 2 + } + ] + } + } +} +``` + + +## Filtering (include and exclude) + +Use the `include` and `exclude` parameters to filter values returned by the `rare_terms` aggregation. Both parameters can be included in the same aggregation. The `exclude` filter takes precedence; any excluded values are removed from the result, regardless of whether they were explicitly included. + +The arguments to `include` and `exclude` can be regular expressions (regex), including string literals, or arrays. Mixing regex and array arguments results in an error. For example, the following combination is not allowed: + +```json +"rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2, + "exclude": ["ABQ", "AUH"], + "include": "A.*" +} +``` + + +### Example: Filtering + +The following example modifies the previous example to include all airport codes beginning with "A" but exclude the "ABQ" airport code: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2, + "include": "A.*", + "exclude": "ABQ" + } + } + } +} +``` +{% include copy-curl.html %} + +The response shows the two airport codes that meet the filtering requirements: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "AUH", + "doc_count": 2 + } + ] + } + } +} +``` + + +### Example: Filtering with array input + +The following example returns all destination airport codes that appear two times at most in the OpenSearch Dashboards sample flight data but specifies an array of airport codes to exclude: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2, + "exclude": ["ABQ", "BIL", "MAD"] + } + } + } +} +``` +{% include copy-curl.html %} + +The response omits the excluded airport codes: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "BUF", + "doc_count": 1 + }, + { + "key": "AUH", + "doc_count": 2 + }, + { + "key": "BWI", + "doc_count": 2 + } + ] + } + } +} +``` \ No newline at end of file diff --git a/_aggregations/bucket/reverse-nested.md b/_aggregations/bucket/reverse-nested.md index bfd04986..3c08ac42 100644 --- a/_aggregations/bucket/reverse-nested.md +++ b/_aggregations/bucket/reverse-nested.md @@ -2,42 +2,88 @@ layout: default title: Reverse nested parent: Bucket aggregations -grand_parent: Aggregations nav_order: 160 redirect_from: - /query-dsl/aggregations/bucket/reverse-nested/ --- -# Reverse nested aggregations +# Reverse nested aggregation -You can aggregate values from nested documents to their parent; this aggregation is called `reverse_nested`. -You can use `reverse_nested` to aggregate a field from the parent document after grouping by the field from the nested object. The `reverse_nested` aggregation "joins back" the root page and gets the `load_time` for each for your variations. +The `reverse_nested` aggregation allows you to aggregate on parent document fields from within a [`nested` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/nested/) context. When you group by a nested field, the aggregation context shifts to the nested documents. The `reverse_nested` aggregation breaks out of that nested context and joins back to the parent (or root) document, making parent fields accessible for further subaggregations. -The `reverse_nested` aggregation is a sub-aggregation inside a nested aggregation. It accepts a single option named `path`. This option defines how many steps backwards in the document hierarchy OpenSearch takes to calculate the aggregations. +The `reverse_nested` aggregation must be defined inside a `nested` aggregation. +{: .note} + +## Parameters + +The `reverse_nested` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `path` | Optional | String | The nested object path to join back to. Default is empty (joins back to the root document). For multi-level nesting, specify an intermediate nested path to join to that level instead of the root. | + +## Example setup + +Create an index with issues containing nested comments: ```json -GET logs/_search +PUT /issues { - "query": { - "match": { "response": "200" } - }, + "mappings": { + "properties": { + "title": { "type": "text" }, + "tags": { "type": "keyword" }, + "comments": { + "type": "nested", + "properties": { + "username": { "type": "keyword" }, + "comment": { "type": "text" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index some documents: + +```json +POST /issues/_bulk?refresh=true +{"index":{"_id":"1"}} +{"title":"Add dark mode to settings page","tags":["ui","enhancement"],"comments":[{"username":"alice","comment":"Would love this feature"},{"username":"bob","comment":"Should support system preference detection"}]} +{"index":{"_id":"2"}} +{"title":"Export report as PDF","tags":["export","enhancement"],"comments":[{"username":"alice","comment":"CSV export would also be useful"},{"username":"carol","comment":"Added to the roadmap"}]} +{"index":{"_id":"3"}} +{"title":"Improve mobile navigation","tags":["ui","mobile"],"comments":[{"username":"bob","comment":"Hamburger menu would work well"},{"username":"carol","comment":"Agree, especially for tablets"}]} +``` +{% include copy-curl.html %} + +## Example + +The following example finds the most active commenters and then uses `reverse_nested` to determine the issue tags with which each commenter is most involved. Without `reverse_nested`, the `tags` field would be inaccessible because the aggregation context is inside the nested `comments` objects: + +```json +GET /issues/_search +{ + "size": 0, "aggs": { - "pages": { + "comments": { "nested": { - "path": "pages" + "path": "comments" }, "aggs": { - "top_pages_per_load_time": { + "top_commenters": { "terms": { - "field": "pages.load_time" + "field": "comments.username" }, "aggs": { - "comment_to_logs": { + "back_to_issue": { "reverse_nested": {}, "aggs": { - "min_load_time": { - "min": { - "field": "pages.load_time" + "top_tags": { + "terms": { + "field": "tags" } } } @@ -51,42 +97,258 @@ GET logs/_search ``` {% include copy-curl.html %} -#### Example response +The response shows that Bob's comments appear on issues tagged with "ui" (2 issues), "enhancement" (1), and "mobile" (1): ```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 +{ + ... + "aggregations": { + "comments": { + "doc_count": 6, + "top_commenters": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "alice", + "doc_count": 2, + "back_to_issue": { + "doc_count": 2, + "top_tags": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "enhancement", + "doc_count": 2 + }, + { + "key": "export", + "doc_count": 1 + }, + { + "key": "ui", + "doc_count": 1 + } + ] + } + } + }, + { + "key": "bob", + "doc_count": 2, + "back_to_issue": { + "doc_count": 2, + "top_tags": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "ui", + "doc_count": 2 + }, + { + "key": "enhancement", + "doc_count": 1 + }, + { + "key": "mobile", + "doc_count": 1 + } + ] + } + } + }, + { + "key": "carol", + "doc_count": 2, + "back_to_issue": { + "doc_count": 2, + "top_tags": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "enhancement", + "doc_count": 1 + }, + { + "key": "export", + "doc_count": 1 + }, + { + "key": "mobile", + "doc_count": 1 + }, + { + "key": "ui", + "doc_count": 1 + } + ] + } } } - }, - { - "key" : 500.0, - "doc_count" : 1, - "comment_to_logs" : { - "doc_count" : 1, - "min_load_time" : { - "value" : null - } - } - } - ] + ] + } } } - } } ``` -The response shows the logs index has one page with a `load_time` of 200 and one with a `load_time` of 500. \ No newline at end of file +## Example: Using the path parameter with multi-level nesting + +When documents contain nested objects within nested objects, you can use the `path` parameter to join back to an intermediate level rather than the root. The following example uses a forum-style structure where posts contain nested comments, and each comment contains nested replies: + +```json +PUT /forum_posts +{ + "mappings": { + "properties": { + "title": { "type": "keyword" }, + "comments": { + "type": "nested", + "properties": { + "author": { "type": "keyword" }, + "replies": { + "type": "nested", + "properties": { + "author": { "type": "keyword" } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index a post with comments and replies: + +```json +POST /forum_posts/_doc/1?refresh=true +{ + "title": "Post A", + "comments": [ + { "author": "alice", "replies": [{"author": "bob"}, {"author": "carol"}] }, + { "author": "bob", "replies": [{"author": "alice"}] } + ] +} +``` +{% include copy-curl.html %} + +The following aggregation groups by reply author, then uses `reverse_nested` with `"path": "comments"` to join back to the comment level (not the root) and find which comment authors each person replied to: + +```json +GET /forum_posts/_search +{ + "size": 0, + "aggs": { + "comments": { + "nested": { "path": "comments" }, + "aggs": { + "replies": { + "nested": { "path": "comments.replies" }, + "aggs": { + "reply_authors": { + "terms": { "field": "comments.replies.author" }, + "aggs": { + "back_to_comment": { + "reverse_nested": { "path": "comments" }, + "aggs": { + "comment_authors": { + "terms": { "field": "comments.author" } + } + } + } + } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response shows that Bob replied to Alice's comment, and Carol also replied to Alice's comment: + +```json +{ + ... + "aggregations": { + "comments": { + "doc_count": 2, + "replies": { + "doc_count": 3, + "reply_authors": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "alice", + "doc_count": 1, + "back_to_comment": { + "doc_count": 1, + "comment_authors": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "bob", + "doc_count": 1 + } + ] + } + } + }, + { + "key": "bob", + "doc_count": 1, + "back_to_comment": { + "doc_count": 1, + "comment_authors": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "alice", + "doc_count": 1 + } + ] + } + } + }, + { + "key": "carol", + "doc_count": 1, + "back_to_comment": { + "doc_count": 1, + "comment_authors": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "alice", + "doc_count": 1 + } + ] + } + } + } + ] + } + } + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The number of parent documents that the aggregation joined back to. This count reflects distinct parent documents, not nested documents. | diff --git a/_aggregations/bucket/sampler.md b/_aggregations/bucket/sampler.md index 28bae47b..d935bdd9 100644 --- a/_aggregations/bucket/sampler.md +++ b/_aggregations/bucket/sampler.md @@ -2,48 +2,55 @@ layout: default title: Sampler parent: Bucket aggregations -grand_parent: Aggregations nav_order: 170 +redirect_from: + - /query-dsl/aggregations/bucket/sampler/ --- -# Sampler aggregations +# Sampler aggregation -If you're aggregating a very large number of documents, you can use a `sampler` aggregation to reduce the scope to a small sample of documents, resulting in a faster response. The `sampler` aggregation selects the samples by top-scoring documents. +The `sampler` aggregation limits subaggregation processing to the top-scoring documents on each shard. This narrows the focus to the most relevant matches rather than processing the entire result set, which reduces computation time and can improve the quality of aggregation results by excluding low-relevance documents from the long tail. -The results are approximate but closely represent the distribution of the real data. The `sampler` aggregation significantly improves query performance, but the estimated responses are not entirely reliable. +Sampling is particularly valuable with subaggregations like `significant_terms`. Without a sampler, the full result set includes a long tail of marginally relevant documents whose generic terms dominate by volume, obscuring the truly distinctive terms found in top-scoring matches. -The basic syntax is: +For diversity-based sampling that prevents any single field value from dominating the sample, see the [`diversified_sampler` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/diversified-sampler/). + +## Parameters + +The `sampler` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `shard_size` | Optional | Integer | The maximum number of top-scoring documents collected from each shard. Default is `100`. | + +The `sampler` aggregation can be nested under a `terms` aggregation. If the `terms` aggregation uses the `breadth_first` collect mode, OpenSearch replays the relevance scores of the deferred documents, so the sample is still based on the top-scoring documents. +{: .note} + +## Example: Sampling the top-scoring documents + +The following examples use a `shakespeare` index containing the complete works of Shakespeare, in which each document is one line of a play. The `text_entry` field contains the text of the line, and the `play_name` field is a `keyword` field. + +A query for `king falstaff` matches 1,545 lines. Most of them contain only the common word `king`, but the lines that also contain the rarer word `falstaff` receive the highest scores. The following request samples the 100 top-scoring lines on each shard and runs a `significant_terms` subaggregation to find the plays that are most associated with the sample: ```json -“aggs”: { - "SAMPLE": { - "sampler": { - "shard_size": 100 - }, - "aggs": {...} - } -} -``` - -## Shard size property - -The `shard_size` property tells OpenSearch how many documents (at most) to collect from each shard. - -The following example limits the number of documents collected on each shard to 1,000 and then buckets the documents by a `terms` aggregation: - -```json -GET opensearch_dashboards_sample_data_logs/_search +GET /shakespeare/_search { "size": 0, + "query": { + "match": { + "text_entry": "king falstaff" + } + }, "aggs": { "sample": { "sampler": { - "shard_size": 1000 + "shard_size": 100 }, "aggs": { - "terms": { - "terms": { - "field": "agent.keyword" + "plays": { + "significant_terms": { + "field": "play_name", + "size": 3 } } } @@ -53,32 +60,106 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +The sample contains 100 lines, and the most significant plays are *The Merry Wives of Windsor* and *Henry IV*, the plays in which Falstaff appears: ```json -... -"aggregations" : { - "sample" : { - "doc_count" : 1000, - "terms" : { - "doc_count_error_upper_bound" : 0, - "sum_other_doc_count" : 0, - "buckets" : [ +{ + ... + "aggregations": { + "sample": { + "doc_count": 100, + "plays": { + "doc_count": 100, + "bg_count": 111396, + "buckets": [ + { + "key": "Merry Wives of Windsor", + "doc_count": 41, + "score": 6.2045063935005285, + "bg_count": 2831 + }, + { + "key": "Henry IV", + "doc_count": 31, + "score": 3.0301421528861154, + "bg_count": 3205 + }, + { + "key": "Hamlet", + "doc_count": 6, + "score": 0.03449236569274269, + "bg_count": 4244 + } + ] + } + } + } +} +``` + +## Example: Running the aggregation without a sampler + +The following request runs the same `significant_terms` aggregation on all 1,545 matching lines, without a sampler: + +```json +GET /shakespeare/_search +{ + "size": 0, + "query": { + "match": { + "text_entry": "king falstaff" + } + }, + "aggs": { + "plays": { + "significant_terms": { + "field": "play_name", + "size": 3 + } + } + } +} +``` +{% include copy-curl.html %} + +Because the long tail of lines that contain only `king` outweighs the Falstaff lines, the most significant plays are the history plays about kings, such as *Henry VI, Part 3* and *Richard II*. The aggregation also processes all 1,545 matching documents instead of 100: + +```json +{ + ... + "aggregations": { + "plays": { + "doc_count": 1545, + "bg_count": 111396, + "buckets": [ { - "key" : "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1", - "doc_count" : 368 + "key": "Henry VI Part 3", + "doc_count": 168, + "score": 0.31100010146873747, + "bg_count": 3138 }, { - "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": "Richard II", + "doc_count": 143, + "score": 0.23236659237692917, + "bg_count": 2937 }, { - "key" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)", - "doc_count" : 303 + "key": "Henry VI Part 2", + "doc_count": 125, + "score": 0.13780305490414782, + "bg_count": 3334 } ] } } - } } ``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The total number of documents in the sample across all shards. | diff --git a/_aggregations/bucket/significant-terms.md b/_aggregations/bucket/significant-terms.md index 017e3b7d..d3dde5f2 100644 --- a/_aggregations/bucket/significant-terms.md +++ b/_aggregations/bucket/significant-terms.md @@ -2,34 +2,109 @@ layout: default title: Significant terms parent: Bucket aggregations -grand_parent: Aggregations nav_order: 180 +redirect_from: + - /query-dsl/aggregations/bucket/significant-terms/ --- -# Significant terms aggregations +# Significant terms aggregation -The `significant_terms` aggregation lets you spot unusual or interesting term occurrences in a filtered subset relative to the rest of the data in an index. +The `significant_terms` aggregation identifies terms that occur unusually frequently in a subset of documents (foreground set) compared to a broader reference set (background set). By default, the background set targets all documents in the target indexes. You can narrow it with `background_filter`. Use this aggregation to retrieve the *most overrepresented* values, for which a plain `terms` aggregation that shows you the *most common* values is insufficient. -A foreground set is the set of documents that you filter. A background set is a set of all documents in an index. -The `significant_terms` aggregation examines all documents in the foreground set and finds a score for significant occurrences in contrast to the documents in the background set. +Each result bucket includes: -In the sample web log data, each document has a field containing the `user-agent` of the visitor. This example searches for all requests from an iOS operating system. A regular `terms` aggregation on this foreground set returns Firefox because it has the most number of documents within this bucket. On the other hand, a `significant_terms` aggregation returns Internet Explorer (IE) because IE has a significantly higher appearance in the foreground set as compared to the background set. +- `key`: The term value. +- `doc_count`: The number of foreground documents containing the term. +- `bg_count`: The number of background documents containing the term. +- `score`: Specifies how strongly the term stands out in the foreground relative to the background. For more information, see [Heuristics and scoring](#heuristics-and-scoring). + +If the aggregation returns no buckets, it usually means that the foreground isn't filtered (for example, you used a `match_all` query) or the term distribution in the foreground is the same as in the background. +{: .note} + +## Parameters + +The `significant_terms` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The field to analyze. Use an indexed `keyword`, integer, or other exact-value field. A `text` field can be used only if `fielddata` is enabled for it, which is not recommended. Floating-point fields are not supported. For more information, see [Field type considerations](#field-type-considerations) and [Limitations](#limitations). | +| `size` | Optional | Integer | The number of buckets to return. Default is `10`. | +| `shard_size` | Optional | Integer | The number of candidate terms that each shard returns. By default, each shard returns `2 * (size * 1.5 + 10)` terms. For more information, see [Size and shard size](#size-and-shard-size). | +| `min_doc_count` | Optional | Integer | The minimum number of foreground documents that must contain a term for it to be returned. Default is `3`. | +| `shard_min_doc_count` | Optional | Integer | The minimum number of foreground documents on a shard that must contain a term for the shard to return it as a candidate. Default is `0`. | +| `include` | Optional | String or array | Limits the terms that can create buckets. Accepts a regular expression or an array of exact values. | +| `exclude` | Optional | String or array | Prevents terms from creating buckets. Accepts a regular expression or an array of exact values. | +| `background_filter` | Optional | Object | A query that limits the background set. Default is all documents in the target indexes. For more information, see [Using a background filter to narrow the background set](#using-a-background-filter-to-narrow-the-background-set). | +| `execution_hint` | Optional | String | Controls how terms are collected. Valid values are `map` and `global_ordinals`. OpenSearch selects the best option automatically. For more information, see [Execution hint](#execution-hint). | +| `jlh`, `mutual_information`, `chi_square`, `gnd`, `percentage`, or `script_heuristic` | Optional | Object | The significance heuristic used to score terms. Specify one heuristic per aggregation. Default is `jlh`. For more information, see [Heuristics and scoring](#heuristics-and-scoring). | + +## Basic example: Identify distinctive terms in high-value returns for an e-commerce application + +Create an index that contains customer orders: ```json -GET opensearch_dashboards_sample_data_logs/_search +PUT /retail_orders +{ + "mappings": { + "properties": { + "status": { "type": "keyword" }, + "order_total": { "type": "double" }, + "payment_method": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Ingest sample documents into the index: + +```json +POST _bulk?refresh +{ "index": { "_index": "retail_orders" } } +{ "status":"RETURNED", "order_total": 950, "payment_method":"gift_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"RETURNED", "order_total": 720, "payment_method":"gift_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"RETURNED", "order_total": 540, "payment_method":"gift_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"RETURNED", "order_total": 820, "payment_method":"credit_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"RETURNED", "order_total": 500, "payment_method":"paypal" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 130, "payment_method":"credit_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 75, "payment_method":"paypal" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 260, "payment_method":"paypal" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 45, "payment_method":"credit_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 310, "payment_method":"credit_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 220, "payment_method":"credit_card" } +{ "index": { "_index": "retail_orders" } } +{ "status":"DELIVERED", "order_total": 410, "payment_method":"paypal" } +``` +{% include copy-curl.html %} + +Run the following query to identify `payment_method` values that are unusually common among orders that were returned and cost over $500, compared to the entire index: + +```json +GET /retail_orders/_search { "size": 0, "query": { - "terms": { - "machine.os.keyword": [ - "ios" + "bool": { + "filter": [ + { "term": { "status": "RETURNED" } }, + { "range": { "order_total": { "gte": 500 } } } ] } }, "aggs": { - "significant_response_codes": { + "payment_signals": { "significant_terms": { - "field": "agent.keyword" + "field": "payment_method" } } } @@ -37,34 +112,775 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +The returned aggregation shows that among the five high-value returns, `gift_card` appears 3 times (60%), compared to 3 out of 12 times in the entire index (25%). As a result, it is flagged as the most overrepresented payment method: ```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 - } - ] +{ + ... + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "payment_signals": { + "doc_count": 5, + "bg_count": 12, + "buckets": [ + { + "key": "gift_card", + "doc_count": 3, + "score": 0.84, + "bg_count": 3 + } + ] + } } - } } ``` -If the `significant_terms` aggregation doesn't return any result, you might have not filtered the results with a query. Alternatively, the distribution of terms in the foreground set might be the same as the background set, implying that there isn't anything unusual in the foreground set. +## Multi-set analysis -The default source of statistical information for background term frequencies is the entire index. You can narrow this scope with a background filter for more focus +You can determine the unusual values for each category by first grouping documents into buckets and then running a `significant_terms` aggregation within each bucket. +### Example: Unusual cancellation reasons per region + +The following example uses a `rides` index containing canceled ride requests. Create the index: + +```json +PUT rides +{ + "mappings": { + "properties": { + "region": { + "type": "keyword" + }, + "cancel_reason": { + "type": "keyword" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents, which contain 7 canceled rides downtown, 6 at the airport, and 4 in the suburbs: + +```json +POST _bulk?refresh +{ "index": { "_index": "rides", "_id": "1" } } +{ "region": "airport", "cancel_reason": "could_not_find_rider" } +{ "index": { "_index": "rides", "_id": "2" } } +{ "region": "airport", "cancel_reason": "could_not_find_rider" } +{ "index": { "_index": "rides", "_id": "3" } } +{ "region": "airport", "cancel_reason": "could_not_find_rider" } +{ "index": { "_index": "rides", "_id": "4" } } +{ "region": "airport", "cancel_reason": "changed_plans" } +{ "index": { "_index": "rides", "_id": "5" } } +{ "region": "airport", "cancel_reason": "changed_plans" } +{ "index": { "_index": "rides", "_id": "6" } } +{ "region": "airport", "cancel_reason": "long_wait" } +{ "index": { "_index": "rides", "_id": "7" } } +{ "region": "downtown", "cancel_reason": "long_wait" } +{ "index": { "_index": "rides", "_id": "8" } } +{ "region": "downtown", "cancel_reason": "long_wait" } +{ "index": { "_index": "rides", "_id": "9" } } +{ "region": "downtown", "cancel_reason": "long_wait" } +{ "index": { "_index": "rides", "_id": "10" } } +{ "region": "downtown", "cancel_reason": "long_wait" } +{ "index": { "_index": "rides", "_id": "11" } } +{ "region": "downtown", "cancel_reason": "changed_plans" } +{ "index": { "_index": "rides", "_id": "12" } } +{ "region": "downtown", "cancel_reason": "changed_plans" } +{ "index": { "_index": "rides", "_id": "13" } } +{ "region": "downtown", "cancel_reason": "could_not_find_rider" } +{ "index": { "_index": "rides", "_id": "14" } } +{ "region": "suburbs", "cancel_reason": "driver_cancelled" } +{ "index": { "_index": "rides", "_id": "15" } } +{ "region": "suburbs", "cancel_reason": "driver_cancelled" } +{ "index": { "_index": "rides", "_id": "16" } } +{ "region": "suburbs", "cancel_reason": "driver_cancelled" } +{ "index": { "_index": "rides", "_id": "17" } } +{ "region": "suburbs", "cancel_reason": "changed_plans" } +``` +{% include copy-curl.html %} + +The following request groups rides by region using a `terms` aggregation and, within each region, runs `significant_terms` to identify the cancellation reasons that are disproportionately common in that region: + +```json +GET rides/_search +{ + "size": 0, + "aggs": { + "by_region": { + "terms": { + "field": "region" + }, + "aggs": { + "odd_cancellations": { + "significant_terms": { + "field": "cancel_reason" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Each region has its own overrepresented reason: downtown riders wait too long, riders at the airport can't be found by drivers, and drivers in the suburbs cancel more often. The suburbs have the fewest rides but the highest score because their reason is the most overrepresented: `driver_cancelled` accounts for three of the four suburban cancellations but only 3 of all 17 cancellations. Reasons that occur in fewer than three rides in a region, such as `could_not_find_rider` downtown, are not returned because of the default `min_doc_count` of `3`: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "by_region": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "downtown", + "doc_count": 7, + "odd_cancellations": { + "doc_count": 7, + "bg_count": 17, + "buckets": [ + { + "key": "long_wait", + "doc_count": 4, + "score": 0.5387755102040814, + "bg_count": 5 + } + ] + } + }, + { + "key": "airport", + "doc_count": 6, + "odd_cancellations": { + "doc_count": 6, + "bg_count": 17, + "buckets": [ + { + "key": "could_not_find_rider", + "doc_count": 3, + "score": 0.5625, + "bg_count": 4 + } + ] + } + }, + { + "key": "suburbs", + "doc_count": 4, + "odd_cancellations": { + "doc_count": 4, + "bg_count": 17, + "buckets": [ + { + "key": "driver_cancelled", + "doc_count": 3, + "score": 2.4375, + "bg_count": 3 + } + ] + } + } + ] + } + } +} +``` +
+ +### Example: Hotspots on a map + +You can use a `geotile_grid` aggregation to divide a map into zoom-level tiles and then run a `significant_terms` aggregation within each tile to identify local outliers. Higher `precision` produces smaller tiles, such as street or city blocks, while lower `precision` produces larger tiles, such as a city or region. + +The following example uses a `field_ops` index containing field incidents reported at sites in three cities. Create the index and map `site.location` as a `geo_point`: + +```json +PUT field_ops +{ + "mappings": { + "properties": { + "site": { + "properties": { + "name": { + "type": "text" + }, + "location": { + "type": "geo_point" + } + } + }, + "issue": { + "type": "keyword" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the following incidents. Power outages occur in every city: + +```json +POST _bulk?refresh +{ "index": { "_index": "field_ops", "_id": "1" } } +{ "site": { "name": "Seattle site 1", "location": { "lat": 47.61, "lon": -122.33 } }, "issue": "FIBER_CUT" } +{ "index": { "_index": "field_ops", "_id": "2" } } +{ "site": { "name": "Seattle site 2", "location": { "lat": 47.62, "lon": -122.34 } }, "issue": "FIBER_CUT" } +{ "index": { "_index": "field_ops", "_id": "3" } } +{ "site": { "name": "Seattle site 3", "location": { "lat": 47.63, "lon": -122.35 } }, "issue": "FIBER_CUT" } +{ "index": { "_index": "field_ops", "_id": "4" } } +{ "site": { "name": "Seattle site 4", "location": { "lat": 47.64, "lon": -122.36 } }, "issue": "POWER_OUTAGE" } +{ "index": { "_index": "field_ops", "_id": "5" } } +{ "site": { "name": "Seattle site 5", "location": { "lat": 47.65, "lon": -122.37 } }, "issue": "POWER_OUTAGE" } +{ "index": { "_index": "field_ops", "_id": "6" } } +{ "site": { "name": "Seattle site 6", "location": { "lat": 47.66, "lon": -122.38 } }, "issue": "VANDALISM" } +{ "index": { "_index": "field_ops", "_id": "7" } } +{ "site": { "name": "Denver site 1", "location": { "lat": 39.74, "lon": -104.99 } }, "issue": "VANDALISM" } +{ "index": { "_index": "field_ops", "_id": "8" } } +{ "site": { "name": "Denver site 2", "location": { "lat": 39.75, "lon": -105.0 } }, "issue": "VANDALISM" } +{ "index": { "_index": "field_ops", "_id": "9" } } +{ "site": { "name": "Denver site 3", "location": { "lat": 39.76, "lon": -105.01 } }, "issue": "VANDALISM" } +{ "index": { "_index": "field_ops", "_id": "10" } } +{ "site": { "name": "Denver site 4", "location": { "lat": 39.77, "lon": -105.02 } }, "issue": "POWER_OUTAGE" } +{ "index": { "_index": "field_ops", "_id": "11" } } +{ "site": { "name": "Denver site 5", "location": { "lat": 39.78, "lon": -105.03 } }, "issue": "EQUIPMENT_FAILURE" } +{ "index": { "_index": "field_ops", "_id": "12" } } +{ "site": { "name": "Phoenix site 1", "location": { "lat": 33.45, "lon": -112.07 } }, "issue": "EQUIPMENT_FAILURE" } +{ "index": { "_index": "field_ops", "_id": "13" } } +{ "site": { "name": "Phoenix site 2", "location": { "lat": 33.46, "lon": -112.08 } }, "issue": "EQUIPMENT_FAILURE" } +{ "index": { "_index": "field_ops", "_id": "14" } } +{ "site": { "name": "Phoenix site 3", "location": { "lat": 33.47, "lon": -112.09 } }, "issue": "EQUIPMENT_FAILURE" } +{ "index": { "_index": "field_ops", "_id": "15" } } +{ "site": { "name": "Phoenix site 4", "location": { "lat": 33.48, "lon": -112.1 } }, "issue": "POWER_OUTAGE" } +{ "index": { "_index": "field_ops", "_id": "16" } } +{ "site": { "name": "Phoenix site 5", "location": { "lat": 33.49, "lon": -112.11 } }, "issue": "POWER_OUTAGE" } +``` +{% include copy-curl.html %} + +The following request divides the sites into tiles and identifies the `issue` values that are unusually frequent in each tile: + +```json +GET field_ops/_search +{ + "size": 0, + "aggs": { + "tiles": { + "geotile_grid": { + "field": "site.location", + "precision": 6 + }, + "aggs": { + "odd_issues": { + "significant_terms": { + "field": "issue" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Each city falls into its own tile, and each tile has its own overrepresented issue: vandalism in Denver (tile `6/13/24`), equipment failures in Phoenix (tile `6/12/25`), and fiber cuts in Seattle (tile `6/10/22`). Power outages are common everywhere, so they are not returned: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "tiles": { + "buckets": [ + { + "key": "6/10/22", + "doc_count": 6, + "odd_issues": { + "doc_count": 6, + "bg_count": 16, + "buckets": [ + { + "key": "FIBER_CUT", + "doc_count": 3, + "score": 0.8333333333333333, + "bg_count": 3 + } + ] + } + }, + { + "key": "6/13/24", + "doc_count": 5, + "odd_issues": { + "doc_count": 5, + "bg_count": 16, + "buckets": [ + { + "key": "VANDALISM", + "doc_count": 3, + "score": 0.84, + "bg_count": 4 + } + ] + } + }, + { + "key": "6/12/25", + "doc_count": 5, + "odd_issues": { + "doc_count": 5, + "bg_count": 16, + "buckets": [ + { + "key": "EQUIPMENT_FAILURE", + "doc_count": 3, + "score": 0.84, + "bg_count": 4 + } + ] + } + } + ] + } + } +} +``` +
+ +### Example: Significant terms over time + +To find how significant terms change over time, use a `date_histogram` aggregation as the parent. This example and the [background filter example](#example-compare-toronto-to-the-rest-of-canada) use a `news` index containing article topics from Canadian and US cities published in October 2025. Create the index: + +```json +PUT news +{ + "mappings": { + "properties": { + "city": { + "type": "keyword" + }, + "country": { + "type": "keyword" + }, + "topic": { + "type": "keyword" + }, + "publish_date": { + "type": "date" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents. Hockey is a common topic across Canada but does not appear in the US articles: + +```json +POST _bulk?refresh +{ "index": { "_index": "news", "_id": "1" } } +{ "city": "Toronto", "country": "Canada", "topic": "transit", "publish_date": "2025-10-06" } +{ "index": { "_index": "news", "_id": "2" } } +{ "city": "Toronto", "country": "Canada", "topic": "transit", "publish_date": "2025-10-07" } +{ "index": { "_index": "news", "_id": "3" } } +{ "city": "Toronto", "country": "Canada", "topic": "transit", "publish_date": "2025-10-13" } +{ "index": { "_index": "news", "_id": "4" } } +{ "city": "Toronto", "country": "Canada", "topic": "transit", "publish_date": "2025-10-14" } +{ "index": { "_index": "news", "_id": "5" } } +{ "city": "Toronto", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-15" } +{ "index": { "_index": "news", "_id": "6" } } +{ "city": "Toronto", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-16" } +{ "index": { "_index": "news", "_id": "7" } } +{ "city": "Toronto", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-17" } +{ "index": { "_index": "news", "_id": "8" } } +{ "city": "Toronto", "country": "Canada", "topic": "weather", "publish_date": "2025-10-08" } +{ "index": { "_index": "news", "_id": "9" } } +{ "city": "Vancouver", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-13" } +{ "index": { "_index": "news", "_id": "10" } } +{ "city": "Montreal", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-14" } +{ "index": { "_index": "news", "_id": "11" } } +{ "city": "Calgary", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-15" } +{ "index": { "_index": "news", "_id": "12" } } +{ "city": "Vancouver", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-16" } +{ "index": { "_index": "news", "_id": "13" } } +{ "city": "Montreal", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-17" } +{ "index": { "_index": "news", "_id": "14" } } +{ "city": "Calgary", "country": "Canada", "topic": "hockey", "publish_date": "2025-10-13" } +{ "index": { "_index": "news", "_id": "15" } } +{ "city": "Vancouver", "country": "Canada", "topic": "weather", "publish_date": "2025-10-09" } +{ "index": { "_index": "news", "_id": "16" } } +{ "city": "Montreal", "country": "Canada", "topic": "weather", "publish_date": "2025-10-10" } +{ "index": { "_index": "news", "_id": "17" } } +{ "city": "Calgary", "country": "Canada", "topic": "weather", "publish_date": "2025-10-14" } +{ "index": { "_index": "news", "_id": "18" } } +{ "city": "Vancouver", "country": "Canada", "topic": "weather", "publish_date": "2025-10-15" } +{ "index": { "_index": "news", "_id": "19" } } +{ "city": "Montreal", "country": "Canada", "topic": "transit", "publish_date": "2025-10-20" } +{ "index": { "_index": "news", "_id": "20" } } +{ "city": "Calgary", "country": "Canada", "topic": "elections", "publish_date": "2025-10-06" } +{ "index": { "_index": "news", "_id": "21" } } +{ "city": "Chicago", "country": "United States", "topic": "elections", "publish_date": "2025-10-07" } +{ "index": { "_index": "news", "_id": "22" } } +{ "city": "Boston", "country": "United States", "topic": "elections", "publish_date": "2025-10-08" } +{ "index": { "_index": "news", "_id": "23" } } +{ "city": "Denver", "country": "United States", "topic": "elections", "publish_date": "2025-10-09" } +{ "index": { "_index": "news", "_id": "24" } } +{ "city": "Denver", "country": "United States", "topic": "baseball", "publish_date": "2025-10-24" } +{ "index": { "_index": "news", "_id": "25" } } +{ "city": "Chicago", "country": "United States", "topic": "baseball", "publish_date": "2025-10-20" } +{ "index": { "_index": "news", "_id": "26" } } +{ "city": "Boston", "country": "United States", "topic": "baseball", "publish_date": "2025-10-21" } +``` +{% include copy-curl.html %} + +The following request groups the articles by week and finds the topics that are unusually common in each week compared to the whole month: + +```json +GET news/_search +{ + "size": 0, + "aggs": { + "weeks": { + "date_histogram": { + "field": "publish_date", + "calendar_interval": "week" + }, + "aggs": { + "trending_topics": { + "significant_terms": { + "field": "topic" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Each week has its own trending topic: elections in the first week, hockey in the second, and baseball in the third. In the first week, `weather` is also returned with a lower score because it is somewhat more common in that week than in the whole month: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "weeks": { + "buckets": [ + { + "key_as_string": "2025-10-06T00:00:00.000Z", + "key": 1759708800000, + "doc_count": 9, + "trending_topics": { + "doc_count": 9, + "bg_count": 26, + "buckets": [ + { + "key": "elections", + "doc_count": 4, + "score": 0.8395061728395059, + "bg_count": 4 + }, + { + "key": "weather", + "doc_count": 3, + "score": 0.24444444444444438, + "bg_count": 5 + } + ] + } + }, + { + "key_as_string": "2025-10-13T00:00:00.000Z", + "key": 1760313600000, + "doc_count": 13, + "trending_topics": { + "doc_count": 13, + "bg_count": 26, + "buckets": [ + { + "key": "hockey", + "doc_count": 9, + "score": 0.6923076923076923, + "bg_count": 9 + } + ] + } + }, + { + "key_as_string": "2025-10-20T00:00:00.000Z", + "key": 1760918400000, + "doc_count": 4, + "trending_topics": { + "doc_count": 4, + "bg_count": 26, + "buckets": [ + { + "key": "baseball", + "doc_count": 3, + "score": 4.125, + "bg_count": 3 + } + ] + } + } + ] + } + } +} +``` +
+ +## Using a background filter to narrow the background set + +By default, the background contains the entire index. Use a `background_filter` to restrict background documents for more precise results. + +### Example: Compare Toronto to the rest of Canada + +The following example uses the `news` index created in the [preceding example](#example-significant-terms-over-time). + +The following example filters the foreground to articles from Toronto and sets a `background_filter` that contains only Canadian articles. The `significant_terms` aggregation highlights the topics that are unusually frequent in Toronto compared to the rest of Canada: + +```json +GET news/_search +{ + "size": 0, + "query": { + "term": { + "city": "Toronto" + } + }, + "aggs": { + "unusual_topics": { + "significant_terms": { + "field": "topic", + "background_filter": { + "term": { + "country": "Canada" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Only `transit` is returned. Without the `background_filter`, the background also contains the US articles, in which hockey never appears, so `hockey` is also returned as significant for Toronto. With the Canadian background, hockey is no more common in Toronto than elsewhere in Canada: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "unusual_topics": { + "doc_count": 8, + "bg_count": 20, + "buckets": [ + { + "key": "transit", + "doc_count": 4, + "score": 0.5, + "bg_count": 5 + } + ] + } + } +} +``` +
+ +Using a custom background requires additional processing because the background frequency for each candidate term must be computed by applying the filter. This can be slower than using the default index-wide counts. +{: .warning} + +## Field type considerations + +`significant_terms` aggregations work best on exact-value fields (for example, `keyword` or `numeric`). Running a `significant_terms` aggregation on a `text` field is not recommended: it requires enabling `fielddata` on the field and loads every unique term into memory, which can use a large amount of memory. For analyzed text, use [`significant_text` aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-text/), which are designed for full-text fields and support the same significance heuristics. + +## Heuristics and scoring + +The `score` ranks terms based on how much their foreground frequency differs from the background frequency. It has no units and is meaningful only for comparison within the same request and heuristic. + +You can select one heuristic per request by specifying it under `significant_terms`. The following heuristics are supported. + +### JLH + +The JLH heuristic is the default and is suitable for most general-purpose scenarios. It balances both the absolute frequency of a term and its relative overrepresentation compared to the background set, favoring terms that increase both *absolutely* and *relatively*. + +```json +"significant_terms": { + "field": "payment_method", + "jlh": {} +} +``` + +#### JLH scoring + +The JLH score is calculated as follows: + +`fg_pct = doc_count / foreground_total` and `bg_pct = bg_count / background_total`. JLH ≈ `(fg_pct − bg_pct) * (fg_pct / bg_pct)`. + +Because the absolute change is multiplied by the ratio of the foreground and background percentages, the same absolute increase produces a higher score for a term with a small background share than for a term with a large background share. For example, an increase from 1% to 2% of documents scores higher than an increase from 50% to 51%. + +If a term's foreground percentage is less than or equal to its background percentage, its JLH score is `0`, so the term is not returned. + +#### Score example calculation using JLH + +Suppose that your foreground set (high-value returns) contains `2,000` orders, and the background set (all orders) contains `120,000` orders. Consider a single term in the `significant_terms` aggregation, which has the following counts: + +- `doc_count = 160` +- `bg_count = 3,200` + +Percentages of documents containing the term are calculated as follows: + +- `fg_pct = 160 / 2000 = 0.08` +- `bg_pct = 3200 / 120000 ≈ 0.026666…` + +JLH ≈ `(0.08 − 0.026666…) * (0.08 / 0.026666…) ≈ 0.053333… * 3 ≈ 0.16` + +This positive score means that the searched term is notably more prevalent in high-value returns than it is overall. Scores are relative: use them to rank terms, not as absolute probabilities. + +### Mutual information + +Mutual information (MI) prefers frequent terms and identifies popular but still distinctive terms. Set `include_negatives: false` to ignore terms that are less common in the foreground than the background. If your background is not a superset of the foreground, set `background_is_superset: false`: + +```json +"significant_terms": { + "field": "product.keyword", + "mutual_information": { + "include_negatives": false, + "background_is_superset": true + } +} +``` + +### Chi-square + +Chi-square is a statistical test that measures how much the observed frequency of a term in a subset (foreground) deviates from the expected frequency based on a reference set (background). Similarly to [MI](#mutual-information), chi-square supports `include_negatives` and `background_is_superset`: + +```json +"significant_terms": { + "field": "error.keyword", + "chi_square": { "include_negatives": false } +} +``` + +### Google Normalized Distance + +Google Normalized Distance (GND) favors strong co-occurrence. It is useful for synonym discovery or items that tend to appear together. GND supports the `background_is_superset` parameter: + +```json +"significant_terms": { + "field": "tag.keyword", + "gnd": { "background_is_superset": true } +} +``` + +### Percentage + +Percentage sorts terms by the `doc_count`/`bg_count` ratio and identifies the number of foreground hits that a term has relative to its background hits. It doesn't account for the overall sizes of the two sets, so very rare terms can dominate. For example, a term that occurs in only one document, which is also in the foreground, has a score of `1`, the highest possible. To prevent single-occurrence terms from dominating the results, increase `min_doc_count` and `shard_min_doc_count`, for example, to `10`: + +```json +"significant_terms": { + "field": "sku.keyword", + "min_doc_count": 10, + "shard_min_doc_count": 10, + "percentage": {} +} +``` + +### Scripted heuristic + +To provide a custom heuristic formula, use the following variables: + +- `_subset_freq`: The number of documents containing the term in the foreground set. +- `_superset_freq`: The number of documents containing the term in the background set. +- `_subset_size`: The total number of documents in the foreground set. +- `_superset_size`: The total number of documents in the background set. + +The following request runs a `significant_terms` aggregation on `field.keyword` using a custom script heuristic to score terms based on their frequency in the foreground relative to the background: + +```json +"significant_terms": { + "field": "field.keyword", + "script_heuristic": { + "script": { + "lang": "painless", + "source": "params._subset_freq / (params._superset_freq - params._subset_freq + 1)" + } + } +} +``` + +### Choosing a heuristic + +The heuristics differ in the kinds of terms they favor: + +- Mutual information favors frequent terms, even if they are also frequent in the background. In natural language text, it can select stopwords, but it rarely selects very rare terms such as misspellings. +- GND favors terms that frequently co-occur with the foreground and avoids stopwords. However, it tends to select very rare terms, such as misspellings. +- Chi-square and JLH fall between these two. + +No heuristic is best for every dataset. Try several heuristics on your data and compare the results. + +## Size and shard size + +The `size` parameter controls how many buckets the aggregation returns. Each shard first selects its own candidate terms using local statistics, and the coordinating node merges the candidates from all shards into the final list. Because a shard cannot know the global frequency of a term, a term that belongs in the final results can be missing, or its counts can be slightly inaccurate. + +To reduce these errors, each shard returns more candidates than the requested `size`. By default, it returns `2 * (size * 1.5 + 10)` terms, which is twice as many as a `terms` aggregation returns. More candidates are needed because a term that is significant overall might occur only once or twice on each shard, where it looks the same as a term that is not significant. + +To control the number of candidates, set `shard_size`. A `shard_size` value much larger than `size` can improve the quality of the results, but it also increases memory usage and network traffic. + +## Minimum document count + +The `min_doc_count` parameter excludes terms that occur in fewer than the specified number of foreground documents. The default value of `3` requires some evidence that a term is meaningful: a term found in only one document is often a typo or another one-time occurrence, so setting `min_doc_count` to `1` is generally not recommended. + +The `min_doc_count` threshold is applied only after the coordinating node merges the shard results. Each shard selects candidates based on its local scores, so low-frequency terms with high local scores can take the place of terms that would have met `min_doc_count` globally. To return these terms, increase `shard_size`. + +The `shard_min_doc_count` parameter filters candidates on each shard before they are sent to the coordinating node. Use it to discard terms, such as misspellings, that are unlikely to reach `min_doc_count` even after the shard counts are merged. Set `shard_min_doc_count` well below `min_doc_count` divided by the number of shards. Otherwise, significant terms can be filtered out on individual shards. + +## Filtering values + +You can use the `include` and `exclude` parameters to limit the terms for which buckets are created. These parameters accept a regular expression or an array of exact values and work the same way as in the `terms` aggregation. For more information, see [Filtering values to a subset]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/#filtering-values-to-a-subset). + +## Collect mode + +To limit memory usage, the `significant_terms` aggregation always computes subaggregations in `breadth_first` mode. For more information about collect modes, see [Collect mode]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/#collect-mode). + +## Execution hint + +The `execution_hint` parameter accepts `map` and `global_ordinals` and works the same way as in the `terms` aggregation. OpenSearch selects the mode automatically, so you rarely need to set it. For more information, see [Execution hint]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/#execution-hint). + +## Limitations + +The `significant_terms` aggregation has the following limitations: + +- The terms must be indexed values. You cannot use a script to generate terms because calculating background frequencies for script-generated terms would require running the script on every document in the index. +- Floating-point fields are not supported. Integer fields, such as account or category numbers, can be useful to analyze, but floating-point fields usually contain quantities, for which individual values are not meaningful terms. +- Don't use `significant_terms` as the top-level aggregation when the query matches all documents. In this case, the foreground and background sets are identical, so no terms stand out. +- Avoid placing large subaggregations under `significant_terms`. Each shard produces many candidate terms, and most of them are discarded after the shard results are merged, so computing subaggregations for all candidates is expensive. Instead, run one search to retrieve the significant terms and a second search that runs the subaggregations on only those terms. +- Document counts are approximate. A `doc_count` value can be too low if some shards did not return the term among their candidates, and a `bg_count` value can be too high because background counts can include deleted documents. To improve accuracy, increase `shard_size`. diff --git a/_aggregations/bucket/significant-text.md b/_aggregations/bucket/significant-text.md index 1c136603..b57c8801 100644 --- a/_aggregations/bucket/significant-text.md +++ b/_aggregations/bucket/significant-text.md @@ -2,41 +2,61 @@ layout: default title: Significant text parent: Bucket aggregations -grand_parent: Aggregations nav_order: 190 +redirect_from: + - /query-dsl/aggregations/bucket/significant-text/ --- -# Significant text aggregations +# Significant text aggregation -The `significant_text` aggregation is similar to the `significant_terms` aggregation but it's for raw text fields. -Significant text measures the change in popularity measured between the foreground and background sets using statistical analysis. For example, it might suggest Tesla when you look for its stock acronym TSLA. +The `significant_text` aggregation identifies unusual or interesting terms in free-text fields by comparing term frequencies in a foreground set (your query results) against a background set (the full index). Unlike [`significant_terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-terms/), which operates on indexed keyword fields, `significant_text` re-analyzes the source text on the fly and can filter duplicate content that would otherwise skew results. -The `significant_text` aggregation re-analyzes the source text on the fly, filtering noisy data like duplicate paragraphs, boilerplate headers and footers, and so on, which might otherwise skew the results. +Use the `significant_text` aggregation in the following scenarios: -Re-analyzing high-cardinality datasets can be a very CPU-intensive operation. We recommend using the `significant_text` aggregation inside a sampler aggregation to limit the analysis to a small selection of top-matching documents, for example 200. +- Suggesting related terms that users can add to a search. For example, a search for "bird flu" might suggest "H5N1". +- Finding keywords that characterize a set of documents, for example, to build a document classifier. -You can set the following parameters: +The most common words in a set of search results are rarely interesting because they are common everywhere (for example, "and," "of," or "the"). A term is significant when its frequency changes noticeably between the foreground and the background. For example, a term that appears in 4 of the 100 documents in your results but in only 5 of 10 million documents in the index is strongly associated with your search. -- `min_doc_count` - Return results that match more than a configured number of top hits. We recommend not setting `min_doc_count` to 1 because it tends to return terms that are typos or misspellings. Finding more than one instance of a term helps reinforce that the significance is not the result of a one-off accident. The default value of 3 is used to provide a minimum weight-of-evidence. -- `shard_size` - Setting a high value increases stability (and accuracy) at the expense of computational performance. -- `shard_min_doc_count` - If your text contains many low frequency words and you're not interested in these (for example typos), then you can set the `shard_min_doc_count` parameter to filter out candidate terms at a shard level with a reasonable certainty to not reach the required `min_doc_count` even after merging the local significant text frequencies. The default value is 1, which has no impact until you explicitly set it. We recommend setting this value much lower than the `min_doc_count` value. +Re-analyzing large result sets is CPU intensive. Use `significant_text` inside a [`sampler`]({{site.url}}{{site.baseurl}}/aggregations/bucket/sampler/) or [`diversified_sampler`]({{site.url}}{{site.baseurl}}/aggregations/bucket/diversified-sampler/) aggregation to limit analysis to a small selection of top-matching documents (for example, 100--200). +{: .note} -Assume that you have the complete works of Shakespeare indexed in an OpenSearch cluster. You can find significant texts in relation to the word "breathe" in the `text_entry` field: +## Parameters + +The `significant_text` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The text field to analyze. | +| `size` | Optional | Integer | The number of term buckets to return. Default is `10`. | +| `shard_size` | Optional | Integer | The number of candidate terms collected from each shard. Higher values improve accuracy at the cost of performance. Default is `-1`, which sets the shard size based on `size`. For more information, see [Size and shard size](#size-and-shard-size). | +| `min_doc_count` | Optional | Integer | The minimum number of documents a term must appear in to be included. Default is `3`. Setting to `1` tends to return typos and misspellings. | +| `shard_min_doc_count` | Optional | Integer | The minimum local shard frequency for a term to be considered as a candidate. Default is `0`. | +| `background_filter` | Optional | Object | A query that narrows the background set used for comparison. By default, the entire index is used as the background. | +| `filter_duplicate_text` | Optional | Boolean | When `true`, filters out sequences of 6 or more tokens that have already been seen, reducing noise from cut-and-paste content. Default is `false`. For more information, see [Filtering duplicate text](#filtering-duplicate-text). | +| `source_fields` | Optional | Array | A list of JSON source field names from which text is analyzed. Use when the indexed field name differs from the source field (for example, with `copy_to`). For more information, see [Analyzing fields created using copy_to](#analyzing-fields-created-using-copy_to). | +| `include` | Optional | String or Array | A regular expression pattern or list of exact terms to include. | +| `exclude` | Optional | String or Array | A regular expression pattern or list of exact terms to exclude from results. | + +## Example + +The following example assumes a `shakespeare` index containing the complete works of Shakespeare with a `text_entry` text field. The query searches for documents containing "breathe," then uses `significant_text` inside a `sampler` to discover the terms that are most strongly associated with those passages compared to the full corpus: ```json -GET shakespeare/_search +GET /shakespeare/_search { + "size": 0, "query": { "match": { "text_entry": "breathe" } }, - "aggregations": { - "my_sample": { + "aggs": { + "sample": { "sampler": { "shard_size": 100 }, - "aggregations": { + "aggs": { "keywords": { "significant_text": { "field": "text_entry", @@ -50,78 +70,81 @@ GET shakespeare/_search ``` {% include copy-curl.html %} -#### Example response +The response identifies terms like "air," "dead," and "life" as significantly associated with passages about breathing: ```json -"aggregations" : { - "my_sample" : { - "doc_count" : 59, - "keywords" : { +{ + ... + "aggregations" : { + "sample" : { "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 - } - ] + "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 + } + ] + } } } - } } ``` -The most significant texts in relation to `breathe` are `air`, `dead`, and `life`. +## Example: Narrowing the background with a filter -The `significant_text` aggregation has the following limitations: +By default, term frequencies are compared against the entire index. The `background_filter` parameter narrows the comparison set, which can reveal terms that are significant within a specific context. The following example compares "breathe" passages from all plays against only the lines from "Henry IV" rather than the full corpus. -- Doesn't support child aggregations because child aggregations come at a high memory cost. As a workaround, you can add a follow-up query using a `terms` aggregation with an include clause and a child aggregation. -- Doesn't support nested objects because it works with the document JSON source. -- The counts of documents might have some (typically small) inaccuracies as it's based on summing the samples returned from each shard. You can use the `shard_size` parameter to fine-tune the trade-off between accuracy and performance. By default, the `shard_size` is set to -1 to automatically estimate the number of shards and the `size` parameter. - -The default source of statistical information for background term frequencies is the entire index. You can narrow this scope with a background filter for more focus: +Most significance heuristics assume that the background set contains the foreground set. In this example, the foreground contains lines from every play, but the background contains only Henry IV, so the term `breathe` occurs in 59 foreground documents but only 6 background documents. To score terms correctly in this case, set `background_is_superset` to `false`. The `jlh` heuristic does not support this setting, so the following request uses `chi_square`. With `chi_square`, omitting `background_is_superset: false` causes the request to fail. With the default `jlh` heuristic, the request succeeds, but the scores are calculated incorrectly: ```json -GET shakespeare/_search +GET /shakespeare/_search { + "size": 0, "query": { "match": { "text_entry": "breathe" } }, - "aggregations": { - "my_sample": { + "aggs": { + "sample": { "sampler": { "shard_size": 100 }, - "aggregations": { + "aggs": { "keywords": { "significant_text": { "field": "text_entry", + "min_doc_count": 3, "background_filter": { "term": { - "speaker": "JOHN OF GAUNT" + "play_name": "Henry IV" } + }, + "chi_square": { + "background_is_superset": false } } } @@ -129,4 +152,581 @@ GET shakespeare/_search } } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +With the background narrowed to the 3,205 lines of Henry IV, the `bg_count` values are smaller, and terms such as `awhile` and `life` are also returned: + +```json +{ + ... + "aggregations": { + "sample": { + "doc_count": 59, + "keywords": { + "doc_count": 59, + "bg_count": 3205, + "buckets": [ + { + "key": "breathe", + "doc_count": 59, + "score": 2957.161281651266, + "bg_count": 6 + }, + { + "key": "air", + "doc_count": 4, + "score": 121.01928476442328, + "bg_count": 3 + }, + { + "key": "dead", + "doc_count": 4, + "score": 45.42858478985534, + "bg_count": 13 + }, + { + "key": "awhile", + "doc_count": 3, + "score": 36.49997548041267, + "bg_count": 9 + }, + { + "key": "life", + "doc_count": 5, + "score": 29.934089933945792, + "bg_count": 31 + } + ] + } + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `doc_count` | Integer | The number of documents in the sample (at the sampler level) or in the foreground set (at the significant_text level). | +| `bg_count` | Integer | The total number of documents in the background set used for comparison. | +| `buckets` | Array | The significant term buckets, sorted by `score` descending. | +| `buckets.key` | String | The significant term. | +| `buckets.doc_count` | Integer | The number of documents in the foreground set containing this term. | +| `buckets.score` | Double | The significance score representing how much more frequently this term appears in the foreground compared to the background. | +| `buckets.bg_count` | Integer | The number of documents in the background set containing this term. | + +## Significance heuristics + +By default, significance scores use the JLH heuristic. You can select an alternative scoring algorithm by adding its name as a parameter alongside the `field`. The following heuristics are supported. + +| Heuristic | Parameter | Description | +| :--- | :--- | :--- | +| JLH | `jlh: {}` | The default. Measures the relative change in popularity between foreground and background. | +| Mutual information | `mutual_information: {}` | Measures how much information the presence of the term provides about belonging to the foreground set. Supports `include_negatives` and `background_is_superset` options. | +| Chi-square | `chi_square: {}` | A standard statistical test for independence between the term and the foreground set. Supports `include_negatives` and `background_is_superset` options. | +| GND | `gnd: {}` | Google Normalized Distance. Measures the statistical association using co-occurrence ratios. Supports `background_is_superset` option. | +| Percentage | `percentage: {}` | The ratio of foreground to background documents containing the term. Very rare terms can dominate, so consider increasing `min_doc_count`. | +| Scripted | `script_heuristic: {}` | A custom score calculated by a script. The script can use the `_subset_freq`, `_superset_freq`, `_subset_size`, and `_superset_size` parameters. | + +For a comparison of how the heuristics differ, see [Choosing a heuristic]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-terms/#choosing-a-heuristic). + +The following example uses chi-square scoring instead of the default JLH: + +```json +GET /shakespeare/_search +{ + "size": 0, + "query": { + "match": { + "text_entry": "breathe" + } + }, + "aggs": { + "sample": { + "sampler": { + "shard_size": 100 + }, + "aggs": { + "keywords": { + "significant_text": { + "field": "text_entry", + "min_doc_count": 4, + "chi_square": {} + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response shows that the same terms are identified but the score scale is different: + +```json +{ + ... + "aggregations" : { + "sample" : { + "doc_count" : 59, + "keywords" : { + "doc_count" : 59, + "bg_count" : 111396, + "buckets" : [ + { + "key" : "breathe", + "doc_count" : 59, + "score" : 111396.0, + "bg_count" : 59 + }, + { + "key" : "air", + "doc_count" : 4, + "score" : 152.27540220402065, + "bg_count" : 189 + }, + { + "key" : "dead", + "doc_count" : 4, + "score" : 53.556852313941825, + "bg_count" : 495 + }, + { + "key" : "life", + "doc_count" : 5, + "score" : 49.44532193700098, + "bg_count" : 805 + } + ] + } + } + } +} +``` + +## Filtering duplicate text + +Free-text fields often contain copied text, such as press releases republished by several sites, email reply chains, boilerplate disclaimers, or navigation menus. Rare words in copied text, such as names or product codes, occur together with your search terms in every copy, so they can dominate the results even though they are not meaningful. + +To remove this noise at query time, set `filter_duplicate_text` to `true`. As the aggregation analyzes the top-matching documents, it ignores any sequence of 6 or more tokens that it has already seen. Because similar documents tend to rank similarly, this removes most copied passages. + +The following examples use a `tech_news` index in which several articles about observability contain the same boilerplate paragraph about an awards jury. Create the index. The `all_text` field is used in the [next section](#analyzing-fields-created-using-copy_to): + +```json +PUT tech_news +{ + "mappings": { + "properties": { + "title": { + "type": "text", + "copy_to": "all_text" + }, + "content": { + "type": "text", + "copy_to": "all_text" + }, + "all_text": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents: + +```json +POST _bulk?refresh +{ "index": { "_index": "tech_news", "_id": "1" } } +{ "title": "Tracing comes to the edge", "content": "New observability agents collect traces from edge devices and forward spans to a central collector." } +{ "index": { "_index": "tech_news", "_id": "2" } } +{ "title": "Startup ships open telemetry pipeline", "content": "The observability startup released a pipeline that converts logs into metrics and traces for dashboards." } +{ "index": { "_index": "tech_news", "_id": "3" } } +{ "title": "Awards shortlist announced", "content": "The observability category of the cloud awards includes three tracing platforms. The awards jury includes Priya Ramaswamy, program director at Northwind Labs, and other industry experts." } +{ "index": { "_index": "tech_news", "_id": "4" } } +{ "title": "Finalists named for cloud awards", "content": "Judges selected observability finalists focused on traces and metrics. The awards jury includes Priya Ramaswamy, program director at Northwind Labs, and other industry experts." } +{ "index": { "_index": "tech_news", "_id": "5" } } +{ "title": "Cloud awards finalists revealed", "content": "Observability vendors with tracing dashboards lead the finalist list. The awards jury includes Priya Ramaswamy, program director at Northwind Labs, and other industry experts." } +{ "index": { "_index": "tech_news", "_id": "6" } } +{ "title": "Award nominees in observability", "content": "Several observability nominees offer metrics and tracing for containers. The awards jury includes Priya Ramaswamy, program director at Northwind Labs, and other industry experts." } +{ "index": { "_index": "tech_news", "_id": "7" } } +{ "title": "Metrics at scale", "content": "An observability team explains how it stores billions of metrics and traces per day." } +{ "index": { "_index": "tech_news", "_id": "8" } } +{ "title": "Quarterly earnings beat estimates", "content": "The retailer reported higher revenue and raised its forecast for the year." } +{ "index": { "_index": "tech_news", "_id": "9" } } +{ "title": "New phone launches", "content": "The manufacturer released a phone with a larger battery and a faster camera." } +{ "index": { "_index": "tech_news", "_id": "10" } } +{ "title": "City approves bike lanes", "content": "The council voted to add protected bike lanes downtown." } +{ "index": { "_index": "tech_news", "_id": "11" } } +{ "title": "Chip shortage eases", "content": "Suppliers report shorter lead times for processors and memory." } +{ "index": { "_index": "tech_news", "_id": "12" } } +{ "title": "Streaming service raises prices", "content": "Subscribers will pay more for the ad-free plan starting next month." } +{ "index": { "_index": "tech_news", "_id": "13" } } +{ "title": "Database release adds vector search", "content": "The new database version adds vector search and faster joins." } +{ "index": { "_index": "tech_news", "_id": "14" } } +{ "title": "Electric trucks enter service", "content": "A logistics company added electric trucks to its delivery fleet." } +{ "index": { "_index": "tech_news", "_id": "15" } } +{ "title": "Weather disrupts flights", "content": "Storms delayed hundreds of flights across the region." } +{ "index": { "_index": "tech_news", "_id": "16" } } +{ "title": "Robotics firm raises funding", "content": "The company will use the funding to expand warehouse automation." } +{ "index": { "_index": "tech_news", "_id": "17" } } +{ "title": "Programming language update", "content": "The release improves compile times and adds pattern matching." } +``` +{% include copy-curl.html %} + +The following request finds the significant terms in articles about observability without filtering duplicate text: + +```json +GET tech_news/_search +{ + "size": 0, + "query": { + "match": { + "content": "observability" + } + }, + "aggs": { + "sample": { + "sampler": { + "shard_size": 100 + }, + "aggs": { + "keywords": { + "significant_text": { + "field": "content" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Most of the returned terms, such as `priya`, `ramaswamy`, `labs`, and `director`, come from the copied jury paragraph: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "sample": { + "doc_count": 7, + "keywords": { + "doc_count": 7, + "bg_count": 17, + "buckets": [ + { + "key": "observability", + "doc_count": 7, + "score": 1.4285714285714288, + "bg_count": 7 + }, + { + "key": "ramaswamy", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "priya", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "director", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "traces", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "includes", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "program", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "at", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "labs", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "metrics", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + } + ] + } + } + } +} +``` +
+ +The following request sets `filter_duplicate_text` to `true`: + +```json +GET tech_news/_search +{ + "size": 0, + "query": { + "match": { + "content": "observability" + } + }, + "aggs": { + "sample": { + "sampler": { + "shard_size": 100 + }, + "aggs": { + "keywords": { + "significant_text": { + "field": "content", + "filter_duplicate_text": true + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The copied paragraph is counted only once, so its terms no longer reach the default `min_doc_count` of `3`. The remaining terms, such as `traces`, `metrics`, and `tracing`, describe the topic of the articles: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "sample": { + "doc_count": 7, + "keywords": { + "doc_count": 7, + "bg_count": 17, + "buckets": [ + { + "key": "observability", + "doc_count": 7, + "score": 1.4285714285714288, + "bg_count": 7 + }, + { + "key": "traces", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "metrics", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "tracing", + "doc_count": 3, + "score": 0.6122448979591836, + "bg_count": 3 + }, + { + "key": "and", + "doc_count": 6, + "score": 0.18367346938775497, + "bg_count": 12 + } + ] + } + } + } +} +``` +
+ +If you can identify duplicate documents using a single-valued field, such as a hash of the article text or the URL of an original press release, use a [`diversified_sampler`]({{site.url}}{{site.baseurl}}/aggregations/bucket/diversified-sampler/) parent aggregation to remove the duplicates from the sample instead. Removing duplicate documents before analysis is more efficient than filtering duplicate text during analysis. + +## Analyzing fields created using copy_to + +The `significant_text` aggregation reads text from the document `_source`. Usually, the indexed field and the source field have the same name. If the field is populated using [`copy_to`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/copy-to/), it does not exist in the `_source`, so the aggregation returns no buckets. To analyze such a field, list the source fields that contain its text in `source_fields`. + +In the `tech_news` index, the `title` and `content` fields are copied to `all_text`. The following request searches `all_text` and analyzes the text of the `title` and `content` source fields: + +```json +GET tech_news/_search +{ + "size": 0, + "query": { + "match": { + "all_text": "observability" + } + }, + "aggs": { + "sample": { + "sampler": { + "shard_size": 100 + }, + "aggs": { + "keywords": { + "significant_text": { + "field": "all_text", + "source_fields": [ + "title", + "content" + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains significant terms from both the titles and the content: + +
+ + Response + + {: .text-delta} + +```json +{ + "aggregations": { + "sample": { + "doc_count": 7, + "keywords": { + "doc_count": 7, + "bg_count": 17, + "buckets": [ + { + "key": "observability", + "doc_count": 7, + "score": 1.4285714285714288, + "bg_count": 7 + }, + { + "key": "at", + "doc_count": 5, + "score": 1.0204081632653061, + "bg_count": 5 + }, + { + "key": "director", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "tracing", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "includes", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "traces", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "ramaswamy", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "priya", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "program", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + }, + { + "key": "labs", + "doc_count": 4, + "score": 0.8163265306122448, + "bg_count": 4 + } + ] + } + } + } +} +``` +
+ +## Size and shard size + +The `size` parameter controls how many buckets the aggregation returns. Each shard first selects candidate terms using local statistics, and the coordinating node merges the candidates into the final list. Because a shard cannot know the global frequency of a term, the merged list can miss terms or contain slightly inaccurate counts. + +By default (`shard_size` is `-1`), each shard returns `2 * (size * 1.5 + 10)` candidate terms. Low-frequency terms can turn out to be the most significant once all results are combined, so setting `shard_size` much higher than `size` can improve the results, at the cost of more memory usage and network traffic. + +## Minimum document count + +The `min_doc_count` parameter excludes terms that occur in fewer than the specified number of foreground documents. The default value of `3` requires some evidence that a term is meaningful: a term found in only one document is often a typo or another one-time occurrence. + +The `min_doc_count` threshold is applied only after the shard results are merged. Each shard selects candidates based on its local scores, so low-frequency terms with high local scores can take the place of terms that would have met `min_doc_count` globally. To return these terms, increase `shard_size`. + +The `shard_min_doc_count` parameter filters candidates on each shard before they are sent to the coordinating node. Use it to discard terms, such as misspellings, that are unlikely to reach `min_doc_count`. Set `shard_min_doc_count` well below `min_doc_count` divided by the number of shards. Otherwise, significant terms can be filtered out on individual shards. + +## Using significant text results + +Significant terms from free text are often most useful as input to another query. The following patterns are common: + +- Find miscategorized documents: Search a structured field for one category, run `significant_text` on a free-text field, and then search for documents that are not in that category but contain the significant terms. The results are documents that might belong in the original category. +- Rank the matching documents: Use the score of each significant term as a `boost` value when you search for the terms. To balance precision and recall, set `minimum_should_match` in the follow-up query. A high value returns fewer documents that contain many of the terms, while a value of `1` returns every document that contains any of the terms. +- Show the terms in context: Significant terms are easier to interpret when readers can see where they occur. Search for the terms in the same field and add a [`highlight`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) clause to return snippets that show each term with its surrounding text. + +## Limitations + +The `significant_text` aggregation has the following limitations: + +- Does not support child aggregations because of high memory cost. To analyze specific terms further, run a separate query with a `terms` aggregation and an `include` clause containing the significant terms from the initial results. +- Does not support nested objects because it works with the document JSON source. +- Document counts are approximate. A `doc_count` value can be too low if some shards did not return the term among their candidates, and a `bg_count` value can be too high because background counts can include deleted documents. To improve accuracy, increase `shard_size`. For more information, see [Size and shard size](#size-and-shard-size). diff --git a/_aggregations/bucket/terms.md b/_aggregations/bucket/terms.md index 072ad42c..612302ad 100644 --- a/_aggregations/bucket/terms.md +++ b/_aggregations/bucket/terms.md @@ -2,14 +2,37 @@ layout: default title: Terms parent: Bucket aggregations -grand_parent: Aggregations nav_order: 200 +redirect_from: + - /query-dsl/aggregations/bucket/terms/ --- -# Terms aggregations +# Terms aggregation The `terms` aggregation dynamically creates a bucket for each unique term of a field. +## Parameters + +The `terms` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Optional | String | The field to aggregate on. Must be a `keyword`, `numeric`, `ip`, `boolean`, or `date` field. A `text` field can be used only if [`fielddata`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) is enabled for it, which can use significant memory. Either `field` or `script` is required. | +| `script` | Optional | Object | A script that generates values to aggregate on. Either `field` or `script` is required. When used with `field`, the script acts as a value script and receives the field value as `_value`. | +| `size` | Optional | Integer | The number of buckets to return. Default is `10`. | +| `shard_size` | Optional | Integer | The number of candidate terms collected from each shard. Higher values improve accuracy. Default is `size * 1.5 + 10`. | +| `min_doc_count` | Optional | Integer | The minimum document count for a bucket to be included in the response. Default is `1`. | +| `shard_min_doc_count` | Optional | Integer | The minimum document count on a shard level for a term to be a candidate. Default is `0`. | +| `show_term_doc_count_error` | Optional | Boolean | When `true`, includes a per-bucket error estimate. Default is `false`. | +| `order` | Optional | Object | Controls the sort order of buckets. Accepts `_count`, `_key`, or the name of a subaggregation metric, each with `asc` or `desc`. Default is `{"_count": "desc"}`. | +| `include` | Optional | String, Array, or Object | Filters which term values can create buckets. Accepts a regex string, an array of exact values, or a `partition` object. | +| `exclude` | Optional | String or Array | Filters which term values cannot create buckets. Accepts a regex string or an array of exact values. | +| `missing` | Optional | String or Number | The value to use for documents missing the target field, placing them in the corresponding bucket. By default, missing documents are ignored. | +| `execution_hint` | Optional | String | Controls how terms are collected. Valid values are `map` (aggregates the field values directly) and `global_ordinals` (aggregates using the global ordinals of the field). OpenSearch selects the best option automatically. For more information, see [Execution hint](#execution-hint). | +| `collect_mode` | Optional | String | Controls how nested aggregations are computed. Valid values are:
- `depth_first`: Expands all branches before pruning.
- `breadth_first`: Prunes at each level before expanding, reducing memory for deeply nested aggregations.

By default, OpenSearch selects the mode automatically. For more information, see [Collect mode](#collect-mode). | + +## Example + The following example uses the `terms` aggregation to find the number of documents per response code in web log data: ```json @@ -28,7 +51,7 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json ... @@ -55,19 +78,21 @@ GET opensearch_dashboards_sample_data_logs/_search } ``` -The values are returned with the key `key`. -`doc_count` specifies the number of documents in each bucket. By default, the buckets are sorted in descending order of `doc-count`. +Each bucket contains the term in the `key` field and the number of documents containing that term in the `doc_count` field. By default, the buckets are sorted in descending order of `doc_count`. + +It is possible to use `terms` to search for infrequent values by ordering the returned values by ascending count (`"order": {"_count": "asc"}`). However, we strongly discourage this practice because it can lead to inaccurate results when multiple shards are involved. A term that is globally infrequent might not appear as infrequent on every individual shard or might be entirely absent from the least frequent results returned by some shards. Conversely, a term that appears infrequently on one shard might be common on another. In both scenarios, rare terms can be missed during shard-level aggregation, resulting in incorrect overall results. Instead of the `terms` aggregation, we recommend using the `rare_terms` aggregation, which is specifically designed to handle these cases more accurately. +{: .warning} -## Size and shard size parameters +## The size and shard_size parameters The number of buckets returned by the `terms` aggregation is controlled by the `size` parameter, which is 10 by default. Additionally, the coordinating node responsible for the aggregation will prompt each shard for its top unique terms. The number of buckets returned by each shard is controlled by the `shard_size` parameter. This parameter is distinct from the `size` parameter and exists as a mechanism to increase the accuracy of the bucket document counts. -For example, imagine a scenario in which the `size` and `shard_size` parameters both have a value of 3. The `terms` aggregation prompts each shard for its top three unique terms. The coordinating node aggregates the results to compute the final result. If a shard contains an object that is not included in the top three, then it won't show up in the response. However, increasing the `shard_size` value for this request will allow each shard to return a larger number of unique terms, increasing the likelihood that the coordinating node will receive all relevant results. +For example, imagine a scenario in which the `size` and `shard_size` parameters both have a value of 3. The `terms` aggregation prompts each shard for its top three unique terms. The coordinating node aggregates the results to compute the final result. If a shard contains a term that is not included in its top three, then that term won't show up in the response. However, increasing the `shard_size` value for this request will allow each shard to return a larger number of unique terms, increasing the likelihood that the coordinating node will receive all relevant results. -By default, the `shard_size` parameter is set to `size * 1.5 + 10`. +By default, the `shard_size` parameter is set to `size * 1.5 + 10`. If you set `shard_size` to a value smaller than `size`, OpenSearch uses the `size` value instead. When using concurrent segment search, the `shard_size` parameter is also applied to each segment slice. @@ -83,16 +108,114 @@ The `doc_count_error_upper_bound` field represents the maximum possible count fo The `doc_count_error_upper_bound` value and the concept of accuracy are only applicable to aggregations using the default sort order---by document count, descending. This is because when you sort by descending document count, any terms that were not returned are guaranteed to include equal or fewer documents than those terms that were returned. Based on this, you can compute the `doc_count_error_upper_bound`. -If the `show_term_doc_count_error` parameter is set to `true`, then the `terms` aggregation will show the `doc_count_error_upper_bound` computed for each unique bucket in addition to the overall value. +OpenSearch calculates the overall `doc_count_error_upper_bound` as the sum of the document counts of the last term returned by each shard. Any term that was not returned could have at most that many documents. -## The `min_doc_count` and `shard_min_doc_count` parameters +If the `show_term_doc_count_error` parameter is set to `true`, then the `terms` aggregation will show the `doc_count_error_upper_bound` computed for each unique bucket in addition to the overall value. The per-bucket error is the sum of the document counts of the last term returned by each shard that did not return the bucket's term. It represents the worst-case number of documents missing from that bucket's count and can help you choose a `shard_size` value. -You can use the `min_doc_count` parameter to filter out any unique terms with fewer than `min_doc_count` results. The `min_doc_count` threshold is applied only after merging the results retrieved from all of the shards. Each shard is unaware of the global document count for a given term. If there is a significant difference between the top `shard_size` globally frequent terms and the top terms local to a shard, you may receive unexpected results when using the `min_doc_count` parameter. +When buckets are sorted by key, the error is always `0` because a shard that does not return a term does not contain it. When buckets are sorted by ascending document count or by a subaggregation, the error cannot be calculated, and `doc_count_error_upper_bound` is `-1`, indicating that the error is unbounded. -Separately, the `shard_min_doc_count` parameter is used to filter out the unique terms that a shard returns back to the coordinator with fewer than `shard_min_doc_count` results. +## The min_doc_count and shard_min_doc_count parameters + +You can use the `min_doc_count` parameter to filter out any unique terms with fewer than `min_doc_count` results. The `min_doc_count` threshold is applied only after merging the results retrieved from all of the shards. Each shard is unaware of the global document count for a given term. If there is a significant difference between the top `shard_size` globally frequent terms and the top terms local to a shard, you may receive unexpected results when using the `min_doc_count` parameter. For example, globally frequent terms can be missing from the results if each shard filled its candidate list with terms that are infrequent globally. To reduce this effect, increase `shard_size` so that each shard returns more candidate terms, at the cost of more memory and network traffic. + +Separately, the `shard_min_doc_count` parameter is used to filter out the unique terms that a shard returns back to the coordinator with fewer than `shard_min_doc_count` results. Use it to discard terms, such as misspellings, that are unlikely to reach `min_doc_count` even after the shard counts are merged. Set `shard_min_doc_count` well below `min_doc_count` divided by the number of shards. Otherwise, terms that would meet `min_doc_count` globally can be filtered out on individual shards. + +Keep the following considerations in mind when using these parameters: + +- Setting `min_doc_count` to `0` also returns buckets for terms that matched no documents. Some of these terms might exist only in deleted documents, so a `match_all` query is not guaranteed to find any documents for them. +- If you don't sort buckets by descending document count, a high `min_doc_count` value can return fewer than `size` buckets because the shards did not return enough candidate terms. To retrieve the missing buckets, increase `shard_size`. When using concurrent segment search, the `shard_min_doc_count` parameter is not applied to each segment slice. For more information, see the [related GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/11847). +## Filtering values to a subset + +You can use the `include` and `exclude` parameters to filter the term values that appear in the aggregation buckets. When both parameters are specified, `include` is evaluated first and then `exclude` is applied to the result. + +### Regular expression filtering + +Both `include` and `exclude` parameters accept a regular expression string in Lucene's [regular expression syntax]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/): + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "success_codes": { + "terms": { + "field": "response.keyword", + "include": "2.*", + "exclude": "204" + } + } + } +} +``` +{% include copy-curl.html %} + +By default, the maximum regex string length is 1000 characters. You can change this limit using the `index.max_regex_length` index setting. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +### Exact value filtering + +Both `include` and `exclude` parameters accept arrays of exact values: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "specific_codes": { + "terms": { + "field": "response.keyword", + "include": ["200", "404", "503"] + } + } + } +} +``` +{% include copy-curl.html %} + +The `include` and `exclude` parameters must use the same format: either regex strings or arrays of exact values. + +## Paginating through all terms + +When a field contains too many unique terms to retrieve in a single request, you can use partition-based filtering to retrieve all terms by sending multiple requests. Terms are assigned to partitions using a hash function, so the distribution is approximately even. + +To retrieve all unique terms, send a number of requests equal to `num_partitions`. Specify `partition` and `num_partitions` in the `include` parameter. For each request, keep `num_partitions` the same and increment `partition` from `0` to `num_partitions - 1`. The following example retrieves the first of five partitions of the client IP addresses in the sample data, which contains about 1,000 unique values: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "partitioned_terms": { + "terms": { + "field": "clientip", + "size": 250, + "include": { + "partition": 0, + "num_partitions": 5 + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the 206 client IP addresses assigned to partition 0, and `sum_other_doc_count` is `0`, which indicates that the partition was returned in full. If a field contains only a few unique terms, some partitions can be empty. For example, the three values of `response.keyword` all fall into partitions 1 and 3 when `num_partitions` is `5`. + +To choose the partition settings, use the following procedure: + +1. Estimate the number of unique terms using a [`cardinality`]({{site.url}}{{site.baseurl}}/aggregations/metric/cardinality/) aggregation. +1. Choose a `num_partitions` value and a `size` value large enough that each partition can return all of its terms. For example, 1,000 unique terms split into 5 partitions average 200 terms each. Because hashing distributes terms unevenly, some partitions contain more than the average, so add a margin and use a `size` such as `250`. +1. Run a test request for one partition. If the request fails because of a circuit breaker, the partitions are too large: increase `num_partitions`. If the request succeeds but `sum_other_doc_count` is greater than `0`, some terms did not fit: increase `size` or `num_partitions`. + +To page through every unique term or combination of terms in sorted order, consider using a [`composite`]({{site.url}}{{site.baseurl}}/aggregations/bucket/composite/) aggregation, which returns an `after_key` that you can pass to the next request. + +The `include` parameter can use only one format per request: a regex string, an array of values, or a `partition` object. Thus, you cannot combine filtering (regex- or array-based) with partition-based retrieval. When using partition-based retrieval, the `exclude` parameter is not supported. +{: .note} + + ## Collect mode There are two collect modes available: `depth_first` and `breadth_first`. The `depth_first` collection mode expands all branches of the aggregation tree in a depth-first manner and only performs pruning after the expansion is complete. @@ -101,20 +224,493 @@ However, when using nested `terms` aggregations, the cardinality of the number o You can use the `breadth_first` collection mode to address this issue. In this case, pruning will be applied to the first level of the aggregation tree before it is expanded to the next level, potentially greatly reducing the number of buckets computed. +In `breadth_first` mode, the `order` parameter can still reference a child aggregation. OpenSearch computes that child aggregation first so that it can sort the buckets before pruning them. + +Subaggregations that need relevance scores, such as `top_hits`, are supported in `breadth_first` mode. To compute them, OpenSearch replays the query, but only for the documents in the remaining top buckets. + +If you don't specify `collect_mode`, OpenSearch selects it automatically. It uses `breadth_first` when the `terms` aggregation has subaggregations and the field contains more unique terms than `shard_size` (or the number of unique terms is unknown). Otherwise, it uses `depth_first`. + Additionally, there is memory overhead associated with performing `breadth_first` collection, which is linearly related to the number of matching documents. This is because `breadth_first` collection works by caching and replaying the pruned set of buckets from the parent level. -## Account for pre-aggregated data +## Sort order -While the `doc_count` field provides a representation of the number of individual documents aggregated in a bucket, `doc_count` by itself does not have a way to correctly increment documents that store pre-aggregated data. To account for pre-aggregated data and accurately calculate the number of documents in a bucket, you can use the `_doc_count` field to add the number of documents in a single summary field. When a document includes the `_doc_count` field, all bucket aggregations recognize its value and increase the bucket `doc_count` cumulatively. Keep these considerations in mind when using the `_doc_count` field: +By default, buckets are sorted by `_count` descending (most documents first). You can change the sort order using the `order` parameter. The following example sorts response codes alphabetically: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field": "response.keyword", + "order": { "_key": "asc" } + } + } + } +} +``` +{% include copy-curl.html %} + +The response returns buckets sorted by key in ascending order: + +```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 + } + ] + } + } +} +``` + +You can also sort by a subaggregation metric. The following example sorts response codes by average bytes descending: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field": "response.keyword", + "order": { "avg_bytes": "desc" } + }, + "aggs": { + "avg_bytes": { + "avg": { "field": "bytes" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +When sorting by a subaggregation, the document counts can contain unbounded errors. Results are accurate either when the aggregation runs on a single shard or when the aggregated field is used as the [routing]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/routing/) key at index time so each term is stored on only one shard. Sorting by a [`max`]({{site.url}}{{site.baseurl}}/aggregations/metric/maximum/) subaggregation in descending order or by a [`min`]({{site.url}}{{site.baseurl}}/aggregations/metric/minimum/) subaggregation in ascending order also selects the correct top buckets, although their document counts may not be exact. +{: .warning} + +To order by a metric nested deeper in the aggregation tree, use the `>` separator to specify the path. An order path can contain any number of single-bucket aggregations, such as `filter`, separated by `>`. The last aggregation in the path must be either a single-bucket aggregation or a metrics aggregation: + +- If the last aggregation is a single-bucket aggregation, buckets are sorted by its `doc_count`. +- If the last aggregation is a single-value metrics aggregation, such as `avg`, buckets are sorted by its value. +- If the last aggregation is a multi-value metrics aggregation, such as `stats`, append the metric name using a `.` separator. + +Multi-bucket aggregations, such as `terms`, cannot appear in an order path. + +The following example sorts operating systems by average bytes of only their successful (200) responses: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "os": { + "terms": { + "field": "machine.os.keyword", + "size": 3, + "order": { "successful>avg_bytes": "desc" } + }, + "aggs": { + "successful": { + "filter": { "term": { "response.keyword": "200" } }, + "aggs": { + "avg_bytes": { + "avg": { "field": "bytes" } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response sorts OS buckets by the nested `avg_bytes` metric: + +```json +{ + ... + "aggregations" : { + "os" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 5639, + "buckets" : [ + { + "key" : "win xp", + "doc_count" : 2885, + "successful" : { + "doc_count" : 2549, + "avg_bytes" : { + "value" : 6083.602196939976 + } + } + }, + { + "key" : "ios", + "doc_count" : 2737, + "successful" : { + "doc_count" : 2512, + "avg_bytes" : { + "value" : 5954.860270700637 + } + } + }, + { + "key" : "win 8", + "doc_count" : 2813, + "successful" : { + "doc_count" : 2585, + "avg_bytes" : { + "value" : 5910.602321083172 + } + } + } + ] + } + } +} +``` + +Pipeline aggregations cannot be used for sorting because they run during the reduce phase, after the buckets have already been ordered. +{: .note} + +To sort by one metric of a multi-value metrics aggregation, use the `.` separator. The following example sorts operating systems by the largest `bytes` value in each bucket, using the `max` metric of a `stats` subaggregation: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "os": { + "terms": { + "field": "machine.os.keyword", + "size": 3, + "order": { "bytes_stats.max": "desc" } + }, + "aggs": { + "bytes_stats": { + "stats": { "field": "bytes" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +You can sort by several criteria by providing an array in the `order` parameter. OpenSearch applies the criteria in order, using each subsequent criterion to break ties. The following example sorts operating systems by the average bytes of their successful responses and then by document count: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "os": { + "terms": { + "field": "machine.os.keyword", + "order": [ + { "successful>avg_bytes": "desc" }, + { "_count": "desc" } + ] + }, + "aggs": { + "successful": { + "filter": { "term": { "response.keyword": "200" } }, + "aggs": { + "avg_bytes": { + "avg": { "field": "bytes" } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +If two buckets have the same values for all sort criteria, OpenSearch sorts them by key in ascending order. + +## Multi-field terms aggregation + +The `terms` aggregation does not natively support multiple fields because it relies on global ordinals, which exist only within a single field. To group by a combination of fields, use the [`multi_terms` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/multi-terms/) or a `script` that combines field values: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "os_and_response": { + "terms": { + "script": { + "source": "doc['machine.os.keyword'].value + ' - ' + doc['response.keyword'].value" + }, + "size": 5 + } + } + } +} +``` +{% include copy-curl.html %} + +A script that combines fields cannot use global ordinals, so it is slower than aggregating on a single field. For better performance, consider using a [`multi_terms` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/multi-terms/) or creating a combined field at index time using [`copy_to`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/copy-to/). + +## Mixing field types across indexes + +When the same field name has different numeric types across indexes (for example, `long` in one index and `double` in another), the `terms` aggregation promotes values to the broader type. Non-decimal values are cast to `double`, which can result in a loss of precision for values exceeding 2^53. +{: .warning} + +## Execution hint + +OpenSearch can collect terms in one of two ways: + +- `global_ordinals`: Aggregates using the global ordinals of the field, assigning one bucket to each ordinal. This is the default for `keyword` fields. +- `map`: Aggregates the field values directly in a map. Consider this option only when very few documents match the query. Otherwise, `global_ordinals` is usually faster. + +OpenSearch selects the mode automatically, so you rarely need to set `execution_hint`. The following example requests the `map` mode: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "response_codes": { + "terms": { + "field": "response.keyword", + "execution_hint": "map" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the same buckets as a request without `execution_hint`. Only the collection method changes. To confirm which method OpenSearch used, set `profile` to `true` in the search request and check the aggregator type in the response. + +OpenSearch ignores `execution_hint` when the requested mode does not apply. For example, numeric fields and scripts have no ordinals, so they are always aggregated without global ordinals. +{: .note} + +## Missing values + +The `missing` parameter assigns a value to documents that do not have the target field, placing them in the corresponding bucket. By default, documents without the field are excluded from the aggregation. In the sample data, most documents don't contain the `memory` field. The following example assigns the value `-1` to those documents: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "memory": { + "terms": { + "field": "memory", + "size": 3, + "missing": -1 + } + } + } +} +``` +{% include copy-curl.html %} + +The `-1` bucket contains the 13,522 documents that have no `memory` value: + +```json +{ + ... + "aggregations" : { + "memory" : { + "doc_count_error_upper_bound" : 2, + "sum_other_doc_count" : 439, + "buckets" : [ + { + "key" : -1.0, + "doc_count" : 13522 + }, + { + "key" : 73240.0, + "doc_count" : 101 + }, + { + "key" : 0.0, + "doc_count" : 12 + } + ] + } + } +} +``` + +The `missing` value is treated like any other value, so missing documents are combined with documents that contain that value. For example, setting `missing` to `0` in the preceding request produces a single `0` bucket containing 13,534 documents: the 13,522 documents without the field and the 12 documents whose `memory` value is `0`. To keep missing documents in a separate bucket, choose a value that does not occur in the field. + +## Script + +You can use a `script` instead of a `field` to compute term values dynamically. The following example classifies log entries into size categories based on the `bytes` field: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "byte_ranges": { + "terms": { + "script": { + "source": "if (doc['bytes'].value < 5000) return 'small'; if (doc['bytes'].value < 10000) return 'medium'; return 'large';" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response groups documents into computed categories: + +```json +{ + ... + "aggregations" : { + "byte_ranges" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : "medium", + "doc_count" : 6995 + }, + { + "key" : "small", + "doc_count" : 6377 + }, + { + "key" : "large", + "doc_count" : 702 + } + ] + } + } +} +``` + +### Stored script + +To reuse a script, store it using the [Create or Update Stored Script API]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/) and reference it by `id`. Pass any values the script needs in `params`. The following request stores a script that appends a suffix to a field value: + +```json +PUT _scripts/os_label +{ + "script": { + "lang": "painless", + "source": "doc[params.field].value + params.suffix" + } +} +``` +{% include copy-curl.html %} + +The following aggregation runs the stored script on the `machine.os.keyword` field: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "os": { + "terms": { + "size": 3, + "script": { + "id": "os_label", + "params": { + "field": "machine.os.keyword", + "suffix": " (OS)" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains keys such as `win xp (OS)` and `osx (OS)`. + +### Value script + +When both `field` and `script` are specified, the script acts as a value script and receives the field value as `_value`. The following example prefixes each response code with "HTTP ": + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "responses_prefixed": { + "terms": { + "field": "response.keyword", + "script": { + "source": "'HTTP ' + _value" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response shows the transformed keys: + +```json +{ + ... + "aggregations" : { + "responses_prefixed" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 0, + "buckets" : [ + { + "key" : "HTTP 200", + "doc_count" : 12832 + }, + { + "key" : "HTTP 404", + "doc_count" : 801 + }, + { + "key" : "HTTP 503", + "doc_count" : 441 + } + ] + } + } +} +``` + +## Accounting for preaggregated data + +While the `doc_count` field provides a representation of the number of individual documents aggregated in a bucket, `doc_count` by itself does not have a way to correctly increment documents that store preaggregated data. To account for preaggregated data and accurately calculate the number of documents in a bucket, you can use the `_doc_count` field to add the number of documents in a single summary field. When a document includes the `_doc_count` field, all bucket aggregations recognize its value and increase the bucket `doc_count` cumulatively. Keep these considerations in mind when using the `_doc_count` field: * The field does not support nested arrays; only positive integers can be used. * If a document does not contain the `_doc_count` field, aggregation uses the document to increase the count by 1. -OpenSearch features that rely on an accurate document count illustrate the importance of using the `_doc_count` field. To see how this field can be used to support other search tools, refer to [Index rollups](https://opensearch.org/docs/latest/im-plugin/index-rollups/index/), an OpenSearch feature for the Index Management (IM) plugin that stores documents with pre-aggregated data in rollup indexes. +OpenSearch features that rely on an accurate document count illustrate the importance of using the `_doc_count` field. To see how this field can be used to support other search tools, refer to [Index rollups]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/), an OpenSearch feature for the Index Management (IM) plugin that stores documents with preaggregated data in rollup indexes. {: .tip} -#### Example request +The following requests index three documents, each containing preaggregated data in the `_doc_count` field: ```json PUT /my_index/_doc/1 @@ -123,21 +719,32 @@ PUT /my_index/_doc/1 "date":"2022-08-05", "_doc_count": 20 } +``` +{% include copy-curl.html %} +```json PUT /my_index/_doc/2 { "response_code": 404, "date":"2022-08-06", "_doc_count": 10 } +``` +{% include copy-curl.html %} -PUT /my_index/_doc/3 +```json +PUT /my_index/_doc/3?refresh { "response_code": 200, "date":"2022-08-06", "_doc_count": 300 } +``` +{% include copy-curl.html %} +The following request runs a `terms` aggregation on the `response_code` field: + +```json GET /my_index/_search { "size": 0, @@ -150,8 +757,9 @@ GET /my_index/_search } } ``` +{% include copy-curl.html %} -#### Example response +The bucket document counts are the sums of the `_doc_count` values, not the number of indexed documents: ```json { diff --git a/_aggregations/bucket/variable-width-histogram.md b/_aggregations/bucket/variable-width-histogram.md new file mode 100644 index 00000000..df87f44d --- /dev/null +++ b/_aggregations/bucket/variable-width-histogram.md @@ -0,0 +1,208 @@ +--- +layout: default +title: Variable width histogram +parent: Bucket aggregations +nav_order: 210 +--- + +# Variable width histogram aggregation + +The `variable_width_histogram` aggregation divides a numeric field's values into a target number of buckets whose widths adapt to the data. Bucket boundaries are derived by clustering the values, so dense parts of the value range are split into narrow buckets and sparse parts are covered by wide ones. Use this aggregation for unevenly distributed data, for which a fixed `interval` in a [`histogram`]({{site.url}}{{site.baseurl}}/aggregations/bucket/histogram/) aggregation produces either many nearly empty buckets or a few buckets holding almost every document. + +Each shard buffers the first `initial_buffer` values it collects, sorts them, and divides them into a number of initial clusters equal to three-quarters of `shard_size`. It assigns each remaining value to the nearest cluster, unless the value lies more than twice the average distance between neighboring cluster centroids away from all of them and the shard holds fewer than `shard_size` clusters, in which case the shard starts a new cluster. The coordinating node collects the clusters from all shards and repeatedly merges the two clusters with the closest centroids until `buckets` remain. + +## Parameters + +The `variable_width_histogram` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `field` | Required | String | The numeric field to aggregate on. Provide either `field` or `script`. | +| `buckets` | Optional | Integer | The target number of buckets. Must be greater than `0` and cannot exceed the `search.max_buckets` setting. The response can contain fewer buckets than requested when the values do not separate into that many clusters. Default is `10`. | +| `shard_size` | Optional | Integer | The number of clusters each shard builds before its results are sent to the coordinating node. Must be greater than `1`. Larger values produce smaller clusters on each shard, which reduces overlap between the final buckets and places their boundaries more accurately, but increases both the memory used on the shards and the volume of data transferred to the coordinating node. Default is `buckets` multiplied by `50`. | +| `initial_buffer` | Optional | Integer | The number of values each shard buffers before it computes the initial cluster boundaries. Must be greater than or equal to `buckets`. A larger buffer derives the initial boundaries from a more representative sample of the data but uses more memory. Default is the smaller of `shard_size` multiplied by `10` and `50000`. | +| `script` | Optional | Object | A script that produces the numeric value to aggregate on. Provide either `field` or `script`. | +| `missing` | Optional | Number | The value to assign to documents missing the target field. By default, missing documents are ignored. | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string applied to `min`, `key`, and `max`. Returns the formatted output in the additional `min_as_string`, `key_as_string`, and `max_as_string` response fields. | + +## Example + +The following example groups ecommerce order totals into five variable-width buckets: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_buckets": { + "variable_width_histogram": { + "field": "taxful_total_price", + "buckets": 5 + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "took": 17, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "price_buckets": { + "buckets": [ + { + "min": 6.98828125, + "key": 59.14907207464146, + "max": 105.46875, + "doc_count": 3835 + }, + { + "min": 105.46875, + "key": 139.096796875, + "max": 229.5, + "doc_count": 800 + }, + { + "min": 229.5, + "key": 247.11111111111111, + "max": 304.0, + "doc_count": 27 + }, + { + "min": 304.0, + "key": 318.4, + "max": 308.0, + "doc_count": 5 + }, + { + "min": 308.0, + "key": 563.25, + "max": 2250.0, + "doc_count": 8 + } + ] + } + } +} +``` + +The buckets covering the crowded low end of the price range are a few tens of dollars wide, whereas the last bucket spans nearly $2,000 to cover the few highest orders. + +## Example: Nesting a subaggregation + +Like other bucket aggregations, `variable_width_histogram` accepts subaggregations. The following example computes the average number of items ordered in each price bucket: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_buckets": { + "variable_width_histogram": { + "field": "taxful_total_price", + "buckets": 3 + }, + "aggs": { + "avg_quantity": { + "avg": { + "field": "total_quantity" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the subaggregation result in each bucket: + +```json +{ + "aggregations": { + "price_buckets": { + "buckets": [ + { + "min": 6.98828125, + "key": 73.45130757286513, + "max": 246.0, + "doc_count": 4649, + "avg_quantity": { + "value": 2.1559475155947516 + } + }, + { + "min": 246.0, + "key": 281.9166666666667, + "max": 370.0, + "doc_count": 24, + "avg_quantity": { + "value": 2.7083333333333335 + } + }, + { + "min": 393.0, + "key": 1321.5, + "max": 2250.0, + "doc_count": 2, + "avg_quantity": { + "value": 1.5 + } + } + ] + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `buckets` | Array | The variable-width buckets, sorted by `key` in ascending order. | +| `buckets.min` | Double | The lower bound of the bucket. | +| `buckets.key` | Double | The mean of the values in the bucket. | +| `buckets.max` | Double | The upper bound of the bucket. | +| `buckets.doc_count` | Integer | The number of documents in the bucket. | +| `buckets.min_as_string` | String | The lower bound of the bucket, formatted according to `format`. Returned only when `format` is set. | +| `buckets.key_as_string` | String | The mean of the values in the bucket, formatted according to `format`. Returned only when `format` is set. | +| `buckets.max_as_string` | String | The upper bound of the bucket, formatted according to `format`. Returned only when `format` is set. | + +## Limitations + +The `variable_width_histogram` aggregation has the following limitations: + +- The aggregation cannot be nested inside a parent aggregation that collects more than one bucket. A [`terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/), [`histogram`]({{site.url}}{{site.baseurl}}/aggregations/bucket/histogram/), [`range`]({{site.url}}{{site.baseurl}}/aggregations/bucket/range/), or [`filters`]({{site.url}}{{site.baseurl}}/aggregations/bucket/filters/) parent returns the following error: + + ``` + [variable_width_histogram] cannot be nested inside an aggregation that collects more than a single bucket. + ``` + + Single-bucket parents, such as [`filter`]({{site.url}}{{site.baseurl}}/aggregations/bucket/filter/), [`global`]({{site.url}}{{site.baseurl}}/aggregations/bucket/global/), and [`nested`]({{site.url}}{{site.baseurl}}/aggregations/bucket/nested/), are supported. +- The aggregation cannot run as a child of a [`nested`]({{site.url}}{{site.baseurl}}/aggregations/bucket/nested/) aggregation when it has a subaggregation that requires document scores, such as [`top_hits`]({{site.url}}{{site.baseurl}}/aggregations/metric/top-hits/). This combination returns an error. +- The `keyed` parameter is not supported, so buckets are always returned as an array. +- The `min` and `max` bounds are approximate. While merging clusters, OpenSearch can leave two clusters whose bounds overlap as separate buckets if their centroids are far apart. It then sets the boundary between the two buckets to the midpoint of the overlap, so a bound is not necessarily a value present in the data, and the lower bucket holds more values than its bounds indicate while the upper bucket holds fewer. Lowering a bucket's `max` in this way can place it below the bucket's own `key`, which is the mean of the values in the bucket. The fourth bucket in the first example response reports a `key` of `318.4` against a `max` of `308.0` for this reason. This merging step runs on a single-shard index as well as on a multi-shard one. +- Buckets are not contiguous. Each bucket's bounds are the smallest and largest values it holds, so a gap in the data appears as a gap between adjacent buckets. In the subaggregation example response, one bucket ends at `370.0` and the next begins at `393.0`. +- Bucket bounds are sensitive to outliers. A few extreme values stretch a bucket across a wide range of the data: the last bucket in the first example response spans `308.0` to `2250.0` to hold 8 orders. +- Bucket boundaries depend on the order in which each shard collects values, so they can change as segments merge or as documents are added, even when the value distribution stays the same. diff --git a/_aggregations/index.md b/_aggregations/index.md index 1c43799a..7ae2ca86 100644 --- a/_aggregations/index.md +++ b/_aggregations/index.md @@ -1,11 +1,12 @@ --- layout: default title: Aggregations -has_children: true +has_children: false nav_order: 5 nav_exclude: true permalink: /aggregations/ redirect_from: + - /query-dsl/aggregations/aggregations/ - /opensearch/aggregations/ - /query-dsl/aggregations/ - /aggregations/index/ @@ -13,41 +14,12 @@ redirect_from: # Aggregations -OpenSearch isn’t just for search. Aggregations let you tap into OpenSearch's powerful analytics engine to analyze your data and extract statistics from it. +OpenSearch is for more than search. Aggregations let you tap into OpenSearch's powerful analytics engine to analyze your data and extract statistics from it. The use cases of aggregations vary from analyzing data in real time to take some action to using OpenSearch Dashboards to create a visualization dashboard. OpenSearch can perform aggregations on massive datasets in milliseconds. Compared to queries, aggregations consume more CPU cycles and memory. -## Aggregations on text fields - -By default, OpenSearch doesn't support aggregations on a text field. Because text fields are tokenized, an aggregation on a text field has to reverse the tokenization process back to its original string and then formulate an aggregation based on that. This kind of an operation consumes significant memory and degrades cluster performance. - -While you can enable aggregations on text fields by setting the `fielddata` parameter to `true` in the mapping, the aggregations are still based on the tokenized words and not on the raw text. - -We recommend keeping a raw version of the text field as a `keyword` field that you can aggregate on. - -In this case, you can perform aggregations on the `title.raw` field, instead of on the `title` field: - -```json -PUT movies -{ - "mappings": { - "properties": { - "title": { - "type": "text", - "fielddata": true, - "fields": { - "raw": { - "type": "keyword" - } - } - } - } - } -} -``` - ## General aggregation structure The structure of an aggregation query is as follows: @@ -57,26 +29,25 @@ GET _search { "size": 0, "aggs": { - "NAME": { - "AGG_TYPE": {} + "": { + "": {} } } } ``` +{% include copy-curl.html %} -If you’re only interested in the aggregation result and not in the results of the query, set `size` to 0. +If you're only interested in the aggregation result and not in the results of the query, set `size` to `0`. In the `aggs` property (you can use `aggregations` if you want), you can define any number of aggregations. Each aggregation is defined by its name and one of the types of aggregations that OpenSearch supports. -The name of the aggregation helps you to distinguish between different aggregations in the response. The `AGG_TYPE` property is where you specify the type of aggregation. +The name of the aggregation helps you to distinguish between different aggregations in the response. The `` placeholder specifies the aggregation type, such as `sum` or `min`. -## Sample aggregation +## Example aggregation -This section uses the OpenSearch Dashboards sample ecommerce data and web log data. To add the sample data, log in to OpenSearch Dashboards, choose **Home**, and then choose **Try our sample data**. For **Sample eCommerce orders** and **Sample web logs**, choose **Add data**. +The following example uses the OpenSearch Dashboards sample e-commerce data. To add the sample data, log in to OpenSearch Dashboards, choose **Home**, and then choose **Try our sample data**. For **Sample eCommerce orders**, choose **Add data**. -### avg - -To find the average value of the `taxful_total_price` field: +This example uses the `avg` aggregation to find the average value of the `taxful_total_price` field: ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -91,8 +62,9 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } } ``` +{% include copy-curl.html %} -#### Example response +The response includes an `aggregations` block containing the calculated average value: ```json { @@ -120,19 +92,58 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } ``` -The aggregation block in the response shows the average value for the `taxful_total_price` field. +## Aggregation types -## Types of aggregations +There are three main aggregation types: -There are three main types of aggregations: +- [Metric aggregations](#metric-aggregations) -- Calculate metrics such as `sum`, `min`, `max`, and `avg` on numeric fields. +- [Bucket aggregations](#bucket-aggregations) -- Sort query results into groups based on some criteria. +- [Pipeline aggregations](#pipeline-aggregations) -- Pipe the output of one aggregation as an input to another. -- Metric aggregations - Calculate metrics such as `sum`, `min`, `max`, and `avg` on numeric fields. -- Bucket aggregations - Sort query results into groups based on some criteria. -- Pipeline aggregations - Pipe the output of one aggregation as an input to another. +### Metric aggregations + +Metric aggregations calculate statistics on numeric field values: + +- [`avg`]({{site.url}}{{site.baseurl}}/aggregations/metric/average/) -- Calculate average values. +- [`cardinality`]({{site.url}}{{site.baseurl}}/aggregations/metric/cardinality/) -- Count unique values. +- [`extended_stats`]({{site.url}}{{site.baseurl}}/aggregations/metric/extended-stats/) -- Get comprehensive statistics including standard deviation. +- [`max`]({{site.url}}{{site.baseurl}}/aggregations/metric/maximum/) -- Find maximum values. +- [`min`]({{site.url}}{{site.baseurl}}/aggregations/metric/minimum/) -- Find minimum values. +- [`percentile`]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile/) -- Calculate percentiles (for example, median, 95th percentile). +- [`stats`]({{site.url}}{{site.baseurl}}/aggregations/metric/stats/) -- Get basic statistics (`count`, `sum`, `min`, `max`, and `avg`). +- [`sum`]({{site.url}}{{site.baseurl}}/aggregations/metric/sum/) -- Calculate sum of values. +- [`value_count`]({{site.url}}{{site.baseurl}}/aggregations/metric/value-count/) -- Count non-null values. + +For a complete list of metric aggregations, see [Metric aggregations]({{site.url}}{{site.baseurl}}/aggregations/metric/). + +### Bucket aggregations + +Bucket aggregations group documents into buckets based on field values, ranges, or other criteria: + +- [`terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/) -- Group by unique field values. +- [`date_histogram`]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-histogram/) -- Group by time intervals. +- [`histogram`]({{site.url}}{{site.baseurl}}/aggregations/bucket/histogram/) -- Group by numeric intervals. +- [`range`]({{site.url}}{{site.baseurl}}/aggregations/bucket/range/) -- Group by numeric ranges. +- [`filter`]({{site.url}}{{site.baseurl}}/aggregations/bucket/filter/) -- Create a single bucket matching a filter. +- [`filters`]({{site.url}}{{site.baseurl}}/aggregations/bucket/filters/) -- Create multiple buckets, one for each filter. +- [`missing`]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) -- Group documents that are missing a field value. +- [`significant_terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-terms/) -- Find unusual or interesting terms in a dataset. + +For a complete list of bucket aggregations, see [Bucket aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/). + +### Pipeline aggregations + +Pipeline aggregations process the output of other aggregations: + +- [`avg_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/avg-bucket/) -- Calculate the average across buckets. +- [`cumulative_sum`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/cumulative-sum/) -- Calculate a running total across buckets. +- [`bucket_sort`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/bucket-sort/) -- Sort and limit the number of buckets returned. + +For a complete list of pipeline aggregations, see [Pipeline aggregations]({{site.url}}{{site.baseurl}}/aggregations/pipeline/). ## Nested aggregations -Aggregations within aggregations are called nested or subaggregations. +Aggregations within aggregations are called _nested aggregations_ or _subaggregations_. Metric aggregations produce simple results and can't contain nested aggregations. @@ -161,8 +172,168 @@ Bucket aggregations produce buckets of documents that you can nest in other aggr The inner `aggs` keyword begins a new nested aggregation. The syntax of the parent aggregation and the nested aggregation is the same. Nested aggregations run in the context of the preceding parent aggregations. -You can also pair your aggregations with search queries to narrow down things you’re trying to analyze before aggregating. If you don't add a query, OpenSearch implicitly uses the `match_all` query. +### Nested aggregation example + +The following example uses the OpenSearch Dashboards sample e-commerce data to group orders by category and calculate the average price within each category. This query returns the top 5 categories sorted in descending alphabetical order: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "categories": { + "terms": { + "field": "category.keyword", + "size": 5, + "order": { + "_key": "desc" + } + }, + "aggs": { + "avg_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response includes buckets for each category, sorted in descending alphabetical order, with the average price calculated within each bucket: + +```json +{ + "took" : 22, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 4675, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ ] + }, + "aggregations" : { + "categories" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 572, + "buckets" : [ + { + "key" : "Women's Shoes", + "doc_count" : 1136, + "avg_price" : { + "value" : 92.8513836927817 + } + }, + { + "key" : "Women's Clothing", + "doc_count" : 1903, + "avg_price" : { + "value" : 70.99312352207042 + } + }, + { + "key" : "Women's Accessories", + "doc_count" : 830, + "avg_price" : { + "value" : 73.28953313253012 + } + }, + { + "key" : "Men's Shoes", + "doc_count" : 944, + "avg_price" : { + "value" : 97.24356130826271 + } + }, + { + "key" : "Men's Clothing", + "doc_count" : 2024, + "avg_price" : { + "value" : 73.81122043292984 + } + } + ] + } + } +} +``` + +For more examples of nested aggregations, see [Pipeline aggregations]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#buckets-path). + +You can also pair your aggregations with search queries to narrow down the data you're analyzing before aggregating. If you don't add a query, OpenSearch implicitly uses the `match_all` query. + +## Using aggregations + +You can use aggregations through the OpenSearch API or through OpenSearch Dashboards. + +### Using the aggregations API + +You can run aggregation requests from the command line using a tool such as cURL or from the OpenSearch Dashboards Dev Tools console. For more information about using the Dev Tools console, see [Running queries in the Dev Tools console]({{site.url}}{{site.baseurl}}/dashboards/visualize/run-queries/). + +See the [Example aggregation](#example-aggregation) and [Nested aggregation example](#nested-aggregation-example) sections for sample API requests and responses. For detailed syntax and parameters for each aggregation type, see the type-specific documentation pages listed in the [Aggregation types](#aggregation-types) section. For a hands-on tutorial that runs aggregations against a sample dataset, see [Summarize data using aggregations]({{site.url}}{{site.baseurl}}/getting-started/analyze-data/#summarize-data-using-aggregations). + +### Using aggregations in OpenSearch Dashboards + +Aggregations power many visualization types in OpenSearch Dashboards. When you create a visualization, OpenSearch Dashboards automatically generates aggregation queries based on your selections. If you're new to OpenSearch Dashboards, see [Getting started with OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/getting-started/). + +The metric and bucket options you see in the **Visualize** application correspond to the aggregation types described on this page. `Count` is the default Y-axis metric---it displays the number of documents in each bucket (`doc_count`) and requires no field selection. + +The following metrics are available in the **Visualize** application: `Count`, `Average`, `Max`, `Median`, `Min`, `Percentile Ranks`, `Percentiles`, `Standard Deviation`, `Sum`, `Top Hit`, `Unique Count`, `Cumulative Sum`, `Derivative`, `Moving Avg`, `Serial Diff`, `Average Bucket`, `Max Bucket`, `Min Bucket`, and `Sum Bucket`. + +The following bucket aggregations are available in the **Visualize** application: `Date Histogram`, `Date Range`, `Filters`, `Histogram`, `IPv4 Range`, `Range`, `Significant Terms`, and `Terms`. + +For descriptions of each option and how they map to the Aggregations API, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/#data-tab). For a hands-on tutorial, see [Creating aggregation-based visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/aggregation-based-viz/). + +## Aggregations on text fields + +By default, OpenSearch doesn't support aggregations on a [`text`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) field. Because `text` fields are tokenized, an aggregation on a `text` field has to reverse the tokenization process back to its original string and then formulate an aggregation based on that. This kind of an operation consumes significant memory and degrades cluster performance. + +While you can enable aggregations on `text` fields by setting the [`fielddata`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/#parameters) parameter to `true` in the mapping, the aggregations are still based on the tokenized words and not on the raw text. + +We recommend keeping a raw version of the `text` field as a [`keyword`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/keyword/) field that you can aggregate on. + +The following example creates a `product_name` field with a `keyword` subfield named `raw`. You can perform aggregations on `product_name.raw` instead of on `product_name`: + +```json +PUT products +{ + "mappings": { + "properties": { + "product_name": { + "type": "text", + "fielddata": true, + "fields": { + "raw": { + "type": "keyword" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +For more information about mappings, see [Mappings]({{site.url}}{{site.baseurl}}/mappings/). ## Limitations Because aggregators are processed using the `double` data type for all values, `long` values of 253 and greater are approximate. + +## Next steps + +- Explore [metric aggregations]({{site.url}}{{site.baseurl}}/aggregations/metric/) to calculate statistics on your data. +- Learn about [bucket aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/) to group and analyze data by categories, ranges, or time intervals. +- Discover [pipeline aggregations]({{site.url}}{{site.baseurl}}/aggregations/pipeline/) for advanced analysis using the output of other aggregations. +- Create [visualizations in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/visualize/viz-index/) using aggregations. +- For a tutorial that uses aggregations and post filters to build faceted search, see [Implementing faceted search in OpenSearch]({{site.url}}{{site.baseurl}}/tutorials/faceted-search/). diff --git a/_aggregations/metric/average.md b/_aggregations/metric/average.md index 428f1e76..9ec05cbc 100644 --- a/_aggregations/metric/average.md +++ b/_aggregations/metric/average.md @@ -2,17 +2,27 @@ layout: default title: Average parent: Metric aggregations -grand_parent: Aggregations nav_order: 10 redirect_from: - /query-dsl/aggregations/metric/average/ --- -# Average aggregations +# Average aggregation -The `avg` metric is a single-value metric aggregations that returns the average value of a field. +The `avg` metric is a single-value metric that returns the average value of a field. -The following example calculates the average of the `taxful_total_price` field: +## Parameters + +The `avg` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The field for which the average is computed. | +| `missing` | Optional | Float | The value to assign to missing instances of the field. By default, `avg` omits missing values from the calculation. | + +## Example + + The following example request calculates the average of the `taxful_total_price` field in the OpenSearch Dashboards e-commerce sample data: ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -29,7 +39,9 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response + +The response contains the average of the `taxful_total_price`: ```json { @@ -56,3 +68,117 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } } ``` + +You can use the aggregation name (`avg_taxful_total_price`) as a key to retrieve the aggregation from the response. + +## Missing values + +You can assign a value to missing instances of the aggregated field. See [Missing aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) for more information. + +Prepare an example index by ingesting the following documents. Note that the second document is missing a `gpa` value: + +```json +POST _bulk +{ "create": { "_index": "students", "_id": "1" } } +{ "name": "John Doe", "gpa": 3.89, "grad_year": 2022} +{ "create": { "_index": "students", "_id": "2" } } +{ "name": "Jonathan Powers", "grad_year": 2025 } +{ "create": { "_index": "students", "_id": "3" } } +{ "name": "Jane Doe", "gpa": 3.52, "grad_year": 2024 } +``` +{% include copy-curl.html %} + +### Example: Replacing a missing value + +Take the average, replacing the missing GPA field with `0`: + +```json +GET students/_search +{ + "size": 0, + "aggs": { + "avg_gpa": { + "avg": { + "field": "gpa", + "missing": 0 + } + } + } +} +``` +{% include copy-curl.html %} + +The response is as follows. Compare to the next example, where missing values are ignored: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "avg_gpa": { + "value": 2.4700000286102295 + } + } +} +``` + +### Example: Ignoring a missing value + +Take the average but without assigning the `missing` parameter: + +```json +GET students/_search +{ + "size": 0, + "aggs": { + "avg_gpa": { + "avg": { + "field": "gpa" + } + } + } +} +``` +{% include copy-curl.html %} + +The aggregator calculates the average, omitting documents containing missing field values (the default behavior): + +```json +{ + "took": 255, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "avg_gpa": { + "value": 3.7050000429153442 + } + } +} +``` \ No newline at end of file diff --git a/_aggregations/metric/cardinality.md b/_aggregations/metric/cardinality.md index c40dbb44..bb0f2f7f 100644 --- a/_aggregations/metric/cardinality.md +++ b/_aggregations/metric/cardinality.md @@ -2,17 +2,32 @@ layout: default title: Cardinality parent: Metric aggregations -grand_parent: Aggregations nav_order: 20 redirect_from: - /query-dsl/aggregations/metric/cardinality/ --- -# Cardinality aggregations +# Cardinality aggregation -The `cardinality` metric is a single-value metric aggregation that counts the number of unique or distinct values of a field. +The `cardinality` aggregation is a single-value metric aggregation that counts the number of unique or distinct values of a field. -The following example finds the number of unique products in an eCommerce store: + +Cardinality count is approximate. See [Controlling precision](#controlling-precision) for more information. + +## Parameters + +The `cardinality` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The field for which the cardinality is estimated. | +| `precision_threshold` | Optional | Numeric | The threshold below which counts are expected to be close to accurate. See [Controlling precision](#controlling-precision) for more information. | +| `execution_hint` | Optional | String | How to run the aggregation. Valid values are `ordinals` and `direct`. | +| `missing` | Optional | Same as `field`'s type | The bucket used to store missing instances of the field. If not provided, missing values are ignored. | + +## Example + +The following example request finds the number of unique product IDs in the OpenSearch Dashboards sample e-commerce data: ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -29,22 +44,53 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response + +As shown in the following example response, the aggregation returns the cardinality count in the `unique_products` variable: ```json -... - "aggregations" : { - "unique_products" : { - "value" : 7033 +{ + "took": 176, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "unique_products": { + "value": 7033 } } } ``` -Cardinality count is approximate. -If you have tens of thousands of products in your hypothetical store, an accurate cardinality calculation requires loading all the values into a hash set and returning its size. This approach doesn't scale well; it requires huge amounts of memory and can cause high latencies. +## Controlling precision -You can control the trade-off between memory and accuracy with the `precision_threshold` setting. This setting defines the threshold below which counts are expected to be close to accurate. Above this value, counts might become a bit less accurate. The default value of `precision_threshold` is 3,000. The maximum supported value is 40,000. +An accurate cardinality calculation requires loading all the values into a hash set and returning its size. This approach doesn't scale well; it can require huge amounts of memory and cause high latencies. + +You can control the trade-off between memory and accuracy by using the `precision_threshold` setting. This parameter sets the threshold below which counts are expected to be close to accurate. Counts higher than this value may be less accurate. + +The default value of `precision_threshold` is 3,000. The maximum supported value is 40,000. + +The cardinality aggregation uses the [HyperLogLog++ algorithm](https://static.googleusercontent.com/media/research.google.com/fr//pubs/archive/40671.pdf). Cardinality counts are typically very accurate up to the precision threshold and are within 6% of the true count in most other cases, even with a threshold of as low as 100. + +### Precomputing hashes + +For high-cardinality string fields, storing hash values for the index field and computing the cardinality of the hash can save compute and memory resources. Use this approach with caution; it is more efficient only for sets with long strings and/or high cardinality. Numeric fields and less memory-consuming string sets are better processed directly. + +### Example: Controlling precision + +Set the precision threshold to `10000` unique values: ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -59,4 +105,60 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +The response is similar to the result with the default threshold, but the returned value is slightly different. Vary the `precision_threshold` parameter to see how it affects the cardinality estimate. + +## Configuring aggregation execution + +You can control how an aggregation runs using the `execution_hint` setting. This setting supports two options: + +- `direct` – Uses field values directly. +- `ordinals` – Uses ordinals of the field. + +If you don't specify `execution_hint`, OpenSearch automatically chooses the best option for the field using the hybrid collector (enabled by default). + +Setting `ordinals` on a non-ordinal field has no effect. Similarly, `direct` has no effect on ordinal fields. +{: .note} + +This is an expert-level setting. Ordinals use byte arrays, where the array size depends on the field's cardinality. High-cardinality fields can consume significant heap memory, increasing the risk of out-of-memory errors. +{: .warning} + +### Example: Controlling execution + +The following request runs a cardinality aggregation using ordinals: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "unique_products": { + "cardinality": { + "field": "products.product_id", + "execution_hint": "ordinals" + } + } + } +} +``` +{% include copy-curl.html %} + +## Hybrid collector +**Introduced 3.4** +{: .label .label-purple } + +By default, OpenSearch uses a _hybrid collector_ for cardinality aggregations to improve speed and manage memory. The hybrid collector begins with the faster ordinals collector and monitors memory use during execution. If usage exceeds a configurable threshold, it automatically switches to the direct collector, continuing from the data already computed. + +This approach provides faster performance when memory is available while maintaining safety for high-cardinality fields. It adapts dynamically to real memory conditions and avoids the overhead of restarting the aggregation when switching collectors. + +To configure the hybrid collector, use the following cluster settings: +- `search.aggregations.cardinality.hybrid_collector.enabled` (Dynamic, Boolean): Enables the hybrid collector. When disabled, OpenSearch uses the traditional logic to select between ordinals and direct collectors. Default is `true`. +- `search.aggregations.cardinality.hybrid_collector.memory_threshold` (Dynamic, percentage or byte size): Sets the memory threshold for switching from ordinals to direct collectors. You can specify this setting as a percentage of JVM heap (for example, `1%`) or as an absolute value (for example, `10mb` or `1gb`). Default is `1%`. + +## Missing values + +You can assign a value to missing instances of the aggregated field. See [Missing aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) for more information. + +Replacing missing values in a cardinality aggregation adds the replacement value to the list of unique values, increasing the actual cardinality by one. diff --git a/_aggregations/metric/extended-stats.md b/_aggregations/metric/extended-stats.md index 633407da..84bb555e 100644 --- a/_aggregations/metric/extended-stats.md +++ b/_aggregations/metric/extended-stats.md @@ -2,16 +2,48 @@ layout: default title: Extended stats parent: Metric aggregations -grand_parent: Aggregations nav_order: 30 redirect_from: - /query-dsl/aggregations/metric/extended-stats/ --- -# Extended stats aggregations +# Extended stats aggregation + +The `extended_stats` aggregation is a more comprehensive version of the [`stats`]({{site.url}}{{site.baseurl}}/query-dsl/aggregations/metric/stats/) aggregation. As well as the basic statistical measures provided by `stats`, `extended_stats` calculates the following: + +- Sum of squares +- Variance +- Population variance +- Sampling variance +- Standard deviation +- Population standard deviation +- Sampling standard deviation +- Standard deviation bounds: + - Upper + - Lower + - Population upper + - Population lower + - Sampling upper + - Sampling lower + +The standard deviation and variance are population statistics; they are always equal to the population standard deviation and variance, respectively. + +The `std_deviation_bounds` object defines a range that spans the specified number of standard deviations above and below the mean (default is two standard deviations). This object is always included in the output but is meaningful only for normally distributed data. Before interpreting these values, verify that your dataset follows a normal distribution. + +## Parameters + +The `extended_stats` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The name of the field for which the extended stats are returned. | +| `sigma` | Optional | Double (non-negative) | The number of standard deviations above and below the mean used to calculate the `std_deviation_bounds` interval. Default is `2`. | +| `missing` | Optional | Numeric | The value assigned to missing instances of the field. If not provided, documents containing missing values are omitted from the extended stats. | + +## Example + +The following example request returns extended stats for `taxful_total_price` in the OpenSearch Dashboards sample e-commerce data: -The `extended_stats` aggregation is an extended version of the [`stats`]({{site.url}}{{site.baseurl}}/query-dsl/aggregations/metric/stats/) aggregation. Apart from including basic stats, `extended_stats` also returns stats such as `sum_of_squares`, `variance`, and `std_deviation`. -The following example returns extended stats for `taxful_total_price`: ```json GET opensearch_dashboards_sample_data_ecommerce/_search { @@ -27,7 +59,9 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response + +The response contains extended stats for `taxful_total_price`: ```json ... @@ -58,8 +92,13 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } ``` -The `std_deviation_bounds` object provides a visual variance of the data with an interval of plus/minus two standard deviations from the mean. -To set the standard deviation to a different value, say 3, set `sigma` to 3: +## Defining bounds + +You can define the number of standard deviations used to calculate the `std_deviation_bounds` interval by setting the `sigma` parameter to any non-negative value. + +### Example: Defining bounds + +Set the number of `std_deviation_bounds` standard deviations to `3`: ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -74,4 +113,145 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +This changes the standard deviation bounds: + +```json +{ +... + "aggregations": { +... + "std_deviation_bounds": { + "upper": 233.44837084770438, + "lower": -83.33751356160813, + "upper_population": 233.44837084770438, + "lower_population": -83.33751356160813, + "upper_sampling": 233.46531398752978, + "lower_sampling": -83.35445670143353 + } + } + } +} +``` + +## Missing values + +You can assign a value to missing instances of the aggregated field. See [Missing aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) for more information. + +Prepare an example index by ingesting the following documents: + +```json +POST _bulk +{ "create": { "_index": "students", "_id": "1" } } +{ "name": "John Doe", "gpa": 3.89, "grad_year": 2022} +{ "create": { "_index": "students", "_id": "2" } } +{ "name": "Jonathan Powers", "grad_year": 2025 } +{ "create": { "_index": "students", "_id": "3" } } +{ "name": "Jane Doe", "gpa": 3.52, "grad_year": 2024 } +``` +{% include copy-curl.html %} + +### Example: Replacing a missing value + +Compute `extended_stats`, replacing the missing GPA field with `0`: + +```json +GET students/_search +{ + "size": 0, + "aggs": { + "extended_stats_gpa": { + "extended_stats": { + "field": "gpa", + "missing": 0 + } + } + } +} +``` +{% include copy-curl.html %} + +In the response, all missing values of `gpa` are replaced with `0`: + +```json +... + "aggregations": { + "extended_stats_gpa": { + "count": 3, + "min": 0, + "max": 3.890000104904175, + "avg": 2.4700000286102295, + "sum": 7.4100000858306885, + "sum_of_squares": 27.522500681877148, + "variance": 3.0732667526245145, + "variance_population": 3.0732667526245145, + "variance_sampling": 4.609900128936772, + "std_deviation": 1.7530735160353415, + "std_deviation_population": 1.7530735160353415, + "std_deviation_sampling": 2.147067797936705, + "std_deviation_bounds": { + "upper": 5.976147060680912, + "lower": -1.0361470034604534, + "upper_population": 5.976147060680912, + "lower_population": -1.0361470034604534, + "upper_sampling": 6.7641356244836395, + "lower_sampling": -1.8241355672631805 + } + } + } +} +``` + +### Example: Ignoring a missing value + +Compute `extended_stats` but without assigning the `missing` parameter: + +```json +GET students/_search +{ + "size": 0, + "aggs": { + "extended_stats_gpa": { + "extended_stats": { + "field": "gpa" + } + } + } +} +``` +{% include copy-curl.html %} + +OpenSearch calculates the extended statistics, omitting documents containing missing field values (the default behavior): + +```json +... + "aggregations": { + "extended_stats_gpa": { + "count": 2, + "min": 3.5199999809265137, + "max": 3.890000104904175, + "avg": 3.7050000429153442, + "sum": 7.4100000858306885, + "sum_of_squares": 27.522500681877148, + "variance": 0.03422502293587115, + "variance_population": 0.03422502293587115, + "variance_sampling": 0.0684500458717423, + "std_deviation": 0.18500006198883057, + "std_deviation_population": 0.18500006198883057, + "std_deviation_sampling": 0.2616295967044675, + "std_deviation_bounds": { + "upper": 4.075000166893005, + "lower": 3.334999918937683, + "upper_population": 4.075000166893005, + "lower_population": 3.334999918937683, + "upper_sampling": 4.228259236324279, + "lower_sampling": 3.1817408495064092 + } + } + } +} +``` + +The document containing the missing GPA value is omitted from this calculation. Note the difference in `count`. diff --git a/_aggregations/metric/geobounds.md b/_aggregations/metric/geobounds.md index 27b7646c..abb56fd8 100644 --- a/_aggregations/metric/geobounds.md +++ b/_aggregations/metric/geobounds.md @@ -2,17 +2,27 @@ layout: default title: Geobounds parent: Metric aggregations -grand_parent: Aggregations nav_order: 40 redirect_from: - /query-dsl/aggregations/metric/geobounds/ --- -## Geobounds aggregations +# Geobounds aggregation -The `geo_bounds` metric is a multi-value metric aggregation that calculates the [geographic bounding box](https://docs.ogc.org/is/12-063r5/12-063r5.html#30) containing all values of a given `geo_point` or `geo_shape` field. The bounding box is returned as the upper-left and lower-right vertices of the rectangle in terms of latitude and longitude. +The `geo_bounds` aggregation is a multi-value aggregation that calculates the [geographic bounding box](https://docs.ogc.org/is/12-063r5/12-063r5.html#30) encompassing a set of [`geo_point`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/) or [`geo_shape`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape/) objects. The bounding box is returned as the upper-left and lower-right vertices of the rectangle given as a decimal-encoded latitude-longitude (lat-lon) pair. -The following example returns the `geo_bounds` metrics for the `geoip.location` field: +## Parameters + +The `geo_bounds` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The name of the field containing the geopoints or geoshapes for which the geobounds are computed. | +| `wrap_longitude` | Optional | Boolean | Whether to allow the bounding box to overlap the international date line. Default is `true`. | + +## Example + +The following example returns the `geo_bounds` for the `geoip.location` of every order in the e-commerce sample data (each `geoip.location` is a geopoint): ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -27,30 +37,52 @@ GET opensearch_dashboards_sample_data_ecommerce/_search } } ``` +{% include copy-curl.html %} -#### Example response +## Example response + +As shown in the following example response, the aggregation returns the `geobounds` containing all geopoints in the `geoip.location` field: ```json -"aggregations" : { - "geo" : { - "bounds" : { - "top_left" : { - "lat" : 52.49999997206032, - "lon" : -118.20000001229346 - }, - "bottom_right" : { - "lat" : 4.599999985657632, - "lon" : 55.299999956041574 +{ + "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": { + "geo": { + "bounds": { + "top_left": { + "lat": 52.49999997206032, + "lon": -118.20000001229346 + }, + "bottom_right": { + "lat": 4.599999985657632, + "lon": 55.299999956041574 + } } } } - } } ``` ## Aggregating geoshapes -To run an aggregation on a geoshape field, first create an index and map the `location` field as a `geo_shape`: +You can run a `geo_bounds` aggregation on geoshapes. + +Prepare an example by inserting an index containing a geoshape field: ```json PUT national_parks @@ -66,43 +98,27 @@ PUT national_parks ``` {% include copy-curl.html %} -Next, index some documents into the `national_parks` index: +Ingest documents into the index. GeoJSON input specifies longitude first: ```json -PUT national_parks/_doc/1 -{ - "name": "Yellowstone National Park", - "location": - {"type": "envelope","coordinates": [ [-111.15, 45.12], [-109.83, 44.12] ]} -} +POST _bulk +{ "create": { "_index": "national_parks", "_id": "1" } } +{"name": "Yellowstone National Park", "location": {"type": "envelope","coordinates": [ [-111.15, 45.12], [-109.83, 44.12] ]}} +{ "create": { "_index": "national_parks", "_id": "2" } } +{ "name": "Yosemite National Park", "location": {"type": "envelope","coordinates": [ [-120.23, 38.16], [-119.05, 37.45] ]} } +{ "create": { "_index": "national_parks", "_id": "3" } } +{ "name": "Death Valley National Park", "location": {"type": "envelope","coordinates": [ [-117.34, 37.01], [-116.38, 36.25] ]} } +{ "create": { "_index": "national_parks", "_id": "4" } } +{ "name": "War In The Pacific National Historic Park Guam", "location": {"type": "point","coordinates": [144.72, 13.47]} } ``` {% include copy-curl.html %} -```json -PUT national_parks/_doc/2 -{ - "name": "Yosemite National Park", - "location": - {"type": "envelope","coordinates": [ [-120.23, 38.16], [-119.05, 37.45] ]} -} -``` -{% include copy-curl.html %} - -```json -PUT national_parks/_doc/3 -{ - "name": "Death Valley National Park", - "location": - {"type": "envelope","coordinates": [ [-117.34, 37.01], [-116.38, 36.25] ]} -} -``` -{% include copy-curl.html %} - -You can run a `geo_bounds` aggregation on the `location` field as follows: +Run a `geo_bounds` aggregation on the `location` field: ```json GET national_parks/_search { + "size": 0, "aggregations": { "grouped": { "geo_bounds": { @@ -115,115 +131,86 @@ GET national_parks/_search ``` {% include copy-curl.html %} -The optional `wrap_longitude` parameter specifies whether the bounding box returned by the aggregation can overlap the international date line (180° meridian). If `wrap_longitude` is set to `true`, the bounding box can overlap the international date line and return a `bounds` object in which the lower-left longitude is greater than the upper-right longitude. The default value for `wrap_longitude` is `true`. - -The response contains the geo-bounding box that encloses all shapes in the `location` field: - -
- - Response - - {: .text-delta} +The response contains the smallest geo-bounding box that encloses all shapes in the `location` field: ```json { - "took" : 3, - "timed_out" : false, - "_shards" : { - "total" : 1, - "successful" : 1, - "skipped" : 0, - "failed" : 0 + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 }, - "hits" : { - "total" : { - "value" : 3, - "relation" : "eq" + "hits": { + "total": { + "value": 4, + "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 - ] - ] - } - } - } - ] + "max_score": null, + "hits": [] }, - "aggregations" : { - "Grouped" : { - "bounds" : { - "top_left" : { - "lat" : 45.11999997776002, - "lon" : -120.23000006563962 + "aggregations": { + "grouped": { + "bounds": { + "top_left": { + "lat": 45.11999997776002, + "lon": 144.71999991685152 }, - "bottom_right" : { - "lat" : 36.249999976716936, - "lon" : -109.83000006526709 + "bottom_right": { + "lat": 13.469999986700714, + "lon": -109.83000006526709 } } } } } ``` -
-Currently, OpenSearch supports geoshape aggregation through the API but not in OpenSearch Dashboards visualizations. If you'd like to see geoshape aggregation implemented for visualizations, upvote the related [GitHub issue](https://github.com/opensearch-project/dashboards-maps/issues/250). +## Wrapping longitude + +If the optional `wrap_longitude` parameter is set to `true`, the bounding box can overlap the international date line (180° meridian) and return a `bounds` object in which the upper-left longitude is greater than the lower-right longitude. The default value for `wrap_longitude` is `true`. + +Rerun the `geo_bounds` aggregation on the national parks geoshape with `wrap_longitude` set to `false`: + +```json +GET national_parks/_search +{ + "size": 0, + "aggregations": { + "grouped": { + "geo_bounds": { + "field": "location", + "wrap_longitude": false + } + } + } +} +``` +{% include copy-curl.html %} + +Note that the new resulting geobounds encompass a larger area to avoid overlapping the dateline: + +```json +{ +... + "aggregations": { + "grouped": { + "bounds": { + "top_left": { + "lat": 45.11999997776002, + "lon": -120.23000006563962 + }, + "bottom_right": { + "lat": 13.469999986700714, + "lon": 144.71999991685152 + } + } + } + } +} +``` + +OpenSearch supports geoshape aggregation through the API but not in OpenSearch Dashboards visualizations. {: .note} diff --git a/_aggregations/metric/geocentroid.md b/_aggregations/metric/geocentroid.md new file mode 100644 index 00000000..5fe00aa5 --- /dev/null +++ b/_aggregations/metric/geocentroid.md @@ -0,0 +1,199 @@ +--- +layout: default +title: Geocentroid +parent: Metric aggregations +nav_order: 45 +--- + +# Geocentroid aggregation + +The `geo_centroid` aggregation calculates the geographic center or focal point of a set of `geo_point` values. It returns the centroid location as a latitude-longitude pair. + +## Parameters + +The `geo_centroid` aggregation takes the following parameter. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The name of the field containing the geopoints for which the geocentroid is computed. | + +## Example + +The following example returns the `geo_centroid` for the `geoip.location` of every order in the e-commerce sample data. Each `geoip.location` is a geopoint: + + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "centroid": { + "geo_centroid": { + "field": "geoip.location" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response includes a `centroid` object with `lat` and `lon` properties representing the centroid location of all indexed data points: + +```json +{ + "took": 35, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "centroid": { + "location": { + "lat": 35.54990372113027, + "lon": -9.079764742533712 + }, + "count": 4675 + } + } +} +``` + +The centroid location is in the Atlantic Ocean north of Morocco. This is not very meaningful, given the wide geographical dispersion of orders in the database. + +## Nesting under other aggregations + +You can nest the `geo_centroid` aggregation inside bucket aggregations to calculate the centroid for subsets of your data. + +### Example: Nesting under a terms aggregation + +You can nest `geo_centroid` aggregations under `terms` buckets of a string field. + +To find the centroid location of `geoip` for the orders on each continent, sub-aggregate the centroid within the `geoip.continent_name` field: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "continents": { + "terms": { + "field": "geoip.continent_name" + }, + "aggs": { + "centroid": { + "geo_centroid": { + "field": "geoip.location" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +This returns a centroid location for each continent's bucket: + +
+ + Response + + {: .text-delta} + +```json +{ + "took": 34, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "continents": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "Asia", + "doc_count": 1220, + "centroid": { + "location": { + "lat": 28.023606536509163, + "lon": 47.83377046025068 + }, + "count": 1220 + } + }, + { + "key": "North America", + "doc_count": 1206, + "centroid": { + "location": { + "lat": 39.06542286878007, + "lon": -85.36152573149485 + }, + "count": 1206 + } + }, + { + "key": "Europe", + "doc_count": 1172, + "centroid": { + "location": { + "lat": 48.125767892293325, + "lon": 2.7529009746915243 + }, + "count": 1172 + } + }, + { + "key": "Africa", + "doc_count": 899, + "centroid": { + "location": { + "lat": 30.780756367941297, + "lon": 13.464182392125318 + }, + "count": 899 + } + }, + { + "key": "South America", + "doc_count": 178, + "centroid": { + "location": { + "lat": 4.599999985657632, + "lon": -74.10000007599592 + }, + "count": 178 + } + } + ] + } + } +} +``` +
diff --git a/_aggregations/metric/index.md b/_aggregations/metric/index.md index 7553933c..32678e0e 100644 --- a/_aggregations/metric/index.md +++ b/_aggregations/metric/index.md @@ -9,11 +9,12 @@ redirect_from: - /query-dsl/aggregations/metric-agg/ - /aggregations/metric-agg/ - /query-dsl/aggregations/metric/ + - /aggregations/metric/ --- # Metric aggregations -Metric aggregations let you perform simple calculations such as finding the minimum, maximum, and average values of a field. +Metric aggregations let you perform calculations such as finding the minimum, maximum, and average values of a field. ## Types of metric aggregations diff --git a/_aggregations/metric/matrix-stats.md b/_aggregations/metric/matrix-stats.md index 475e0caa..7fec1445 100644 --- a/_aggregations/metric/matrix-stats.md +++ b/_aggregations/metric/matrix-stats.md @@ -2,16 +2,31 @@ layout: default title: Matrix stats parent: Metric aggregations -grand_parent: Aggregations nav_order: 50 redirect_from: - /query-dsl/aggregations/metric/matrix-stats/ --- -# Matrix stats aggregations +# Matrix stats aggregation -The `matrix_stats` aggregation generates advanced stats for multiple fields in a matrix form. -The following example returns advanced stats in a matrix form for the `taxful_total_price` and `products.base_price` fields: +The `matrix_stats` aggregation is a multi-value metric aggregation that generates covariance statistics for two or more fields in matrix form. + +The `matrix_stats` aggregation does not support scripting. +{: .note} + +## Parameters + +The `matrix_stats` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `fields` | Required | String | An array of fields for which the matrix stats are computed. | +| `missing` | Optional | Object | The value to use in place of missing values. By default, missing values are ignored. See [Missing values](#missing-values). | +| `mode` | Optional | String | The value to use as a sample from a multi-valued or array field. Allowed values are `avg`, `min`, `max`, `sum`, and `median`. Default is `avg`. | + +## Example + +The following example returns statistics for the `taxful_total_price` and `products.base_price` fields in the OpenSearch Dashboards e-commerce sample data: ```json GET opensearch_dashboards_sample_data_ecommerce/_search @@ -28,60 +43,262 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +The response contains the aggregated results: ```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 +{ + "took": 250, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "matrix_stats_taxful_total_price": { + "doc_count": 4675, + "fields": [ + { + "name": "products.base_price", + "count": 4675, + "mean": 34.99423943014724, + "variance": 360.5035285833702, + "skewness": 5.530161335032689, + "kurtosis": 131.1630632404217, + "covariance": { + "products.base_price": 360.5035285833702, + "taxful_total_price": 846.6489362233169 + }, + "correlation": { + "products.base_price": 1, + "taxful_total_price": 0.8444765264325269 + } }, - "correlation" : { - "products.base_price" : 1.0, - "taxful_total_price" : 0.8444765264325268 + { + "name": "taxful_total_price", + "count": 4675, + "mean": 75.05542864304839, + "variance": 2788.1879749835425, + "skewness": 15.812149139923994, + "kurtosis": 619.1235507385886, + "covariance": { + "products.base_price": 846.6489362233169, + "taxful_total_price": 2788.1879749835425 + }, + "correlation": { + "products.base_price": 0.8444765264325269, + "taxful_total_price": 1 + } } - }, - { - "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 - } - } - ] + ] + } } - } } ``` -The following table lists all response fields. +The following table describes the response fields. -Statistic | Description -:--- | :--- -`count` | The number of samples measured. -`mean` | The average value of the field measured from the sample. -`variance` | How far the values of the field measured are spread out from its mean value. The larger the variance, the more it's spread from its mean value. -`skewness` | An asymmetric measure of the distribution of the field's values around the mean. -`kurtosis` | A measure of the tail heaviness of a distribution. As the tail becomes lighter, kurtosis decreases. As the tail becomes heavier, kurtosis increases. To learn about kurtosis, see [Wikipedia](https://en.wikipedia.org/wiki/Kurtosis). -`covariance` | A measure of the joint variability between two fields. A positive value means their values move in the same direction and the other way around. -`correlation` | A measure of the strength of the relationship between two fields. The valid values are between [-1, 1]. A value of -1 means that the value is negatively correlated and a value of 1 means that it's positively correlated. A value of 0 means that there's no identifiable relationship between them. \ No newline at end of file +| Statistic | Description | +| :--- | :--- | +| `count` | The number of documents sampled for the aggregation. | +| `mean` | The average value of the field computed from the sample. | +| `variance` | The square of deviation from the mean, a measure of data spread. | +| `skewness` | A measure of the distribution's asymmetry relative to the mean. See [Skewness](https://en.wikipedia.org/wiki/Skewness). | +| `kurtosis` | A measure of the tail-heaviness of a distribution. As the tails become lighter, kurtosis decreases. Kurtosis and skewness are evaluated to determine whether a population is likely to be [normally distributed](https://en.wikipedia.org/wiki/Normal_distribution). See [Kurtosis](https://en.wikipedia.org/wiki/Kurtosis).| +| `covariance` | A measure of the joint variability between two fields. A positive value means their values move in the same direction. | +| `correlation` | The normalized covariance, a measure of the strength of the relationship between two fields. Possible values are from -1 to 1, inclusive, indicating perfect negative to perfect positive linear correlation. A value of 0 indicates no discernible relationship between the variables. | + +## Missing values + +To define how missing values are treated, use the `missing` parameter. By default, missing values are ignored. + +For example, create an index in which document 1 is missing the `gpa` and `class_grades` fields: + +```json +POST _bulk +{ "create": { "_index": "students", "_id": "1" } } +{ "name": "John Doe" } +{ "create": { "_index": "students", "_id": "2" } } +{ "name": "Jonathan Powers", "gpa": 3.85, "class_grades": [3.0, 3.9, 4.0] } +{ "create": { "_index": "students", "_id": "3" } } +{ "name": "Jane Doe", "gpa": 3.52, "class_grades": [3.2, 2.1, 3.8] } +``` +{% include copy-curl.html %} + +First, run a `matrix_stats` aggregation without providing a `missing` parameter: + +```json +GET students/_search +{ + "size": 0, + "aggs": { + "matrix_stats_taxful_total_price": { + "matrix_stats": { + "fields": [ + "gpa", + "class_grades" + ], + "mode": "avg" + } + } + } +} +``` +{% include copy-curl.html %} + +OpenSearch ignores missing values when calculating the matrix statistics: + +```json +{ + "took": 5, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "matrix_stats_taxful_total_price": { + "doc_count": 2, + "fields": [ + { + "name": "gpa", + "count": 2, + "mean": 3.684999942779541, + "variance": 0.05444997482300096, + "skewness": 0, + "kurtosis": 1, + "covariance": { + "gpa": 0.05444997482300096, + "class_grades": 0.09899998760223136 + }, + "correlation": { + "gpa": 1, + "class_grades": 0.9999999999999991 + } + }, + { + "name": "class_grades", + "count": 2, + "mean": 3.333333333333333, + "variance": 0.1800000381469746, + "skewness": 0, + "kurtosis": 1, + "covariance": { + "gpa": 0.09899998760223136, + "class_grades": 0.1800000381469746 + }, + "correlation": { + "gpa": 0.9999999999999991, + "class_grades": 1 + } + } + ] + } + } +} +``` + +To set the missing fields to `0`, provide the `missing` parameter as a key-value map. Even though `class_grades` is an array field, the `matrix_stats` aggregation flattens multi-valued numeric fields into a per-document average, so you must supply a single number as the missing value: + +```json +GET students/_search +{ + "size": 0, + "aggs": { + "matrix_stats_taxful_total_price": { + "matrix_stats": { + "fields": ["gpa", "class_grades"], + "mode": "avg", + "missing": { + "gpa": 0, + "class_grades": 0 + } + } + } + } +} +``` +{% include copy-curl.html %} + +OpenSearch substitutes `0` for any missing `gpa` or `class_grades` values when calculating the matrix statistics: + +```json +{ + "took": 23, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "matrix_stats_taxful_total_price": { + "doc_count": 3, + "fields": [ + { + "name": "gpa", + "count": 3, + "mean": 2.456666628519694, + "variance": 4.55363318017324, + "skewness": -0.688130006360758, + "kurtosis": 1.5, + "covariance": { + "gpa": 4.55363318017324, + "class_grades": 4.143944374667273 + }, + "correlation": { + "gpa": 1, + "class_grades": 0.9970184390038257 + } + }, + { + "name": "class_grades", + "count": 3, + "mean": 2.2222222222222223, + "variance": 3.793703722777191, + "skewness": -0.6323693521730989, + "kurtosis": 1.5000000000000002, + "covariance": { + "gpa": 4.143944374667273, + "class_grades": 3.793703722777191 + }, + "correlation": { + "gpa": 0.9970184390038257, + "class_grades": 1 + } + } + ] + } + } +} +``` diff --git a/_aggregations/metric/maximum.md b/_aggregations/metric/maximum.md index 63b4d62a..231cd390 100644 --- a/_aggregations/metric/maximum.md +++ b/_aggregations/metric/maximum.md @@ -2,26 +2,39 @@ layout: default title: Maximum parent: Metric aggregations -grand_parent: Aggregations nav_order: 60 redirect_from: - /query-dsl/aggregations/metric/maximum/ --- -# Maximum aggregations +# Maximum aggregation -The `max` metric is a single-value metric aggregations that returns the maximum value of a field. +The `max` metric is a single-value metric that returns the maximum value of a field. -The following example calculates the maximum of the `taxful_total_price` field: +The `max` aggregation compares numeric fields using a `double` (double-precision) representation. Results should be considered approximate for fields containing `long` or `unsigned_long` integer values greater than 253 because the number of significant bits in a `double` mantissa is 53. +{: .note} + +## Parameters + +The `max` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The name of the field for which the maximum is computed. | +| `missing` | Optional | Numeric | The value to assign to missing instances of the field. If not provided, documents containing missing values are omitted from the aggregation. | + +## Example + +This following example request finds the most expensive item---the item with the maximum value of the `base_unit_price`---in the OpenSearch Dashboards e-commerce sample data: ```json GET opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "max_taxful_total_price": { + "max_base_unit_price": { "max": { - "field": "taxful_total_price" + "field": "products.base_unit_price" } } } @@ -29,11 +42,13 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response + +As shown in the following example response, the aggregation returns the maximum value of `products.base_unit_price`: ```json { - "took": 17, + "took": 24, "timed_out": false, "_shards": { "total": 1, @@ -50,9 +65,17 @@ GET opensearch_dashboards_sample_data_ecommerce/_search "hits": [] }, "aggregations": { - "max_taxful_total_price": { - "value": 2250 + "max_base_unit_price": { + "value": 540 } } } -``` \ No newline at end of file +``` + +You can use the aggregation name (`max_base_unit_price`) as a key to retrieve the aggregation from the response. + +## Missing values + +You can assign a value to missing instances of the aggregated field. See [Missing aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) for more information. + +Missing values are normally ignored by `max`. If you use `missing` to assign a value greater than any existing value, `max` returns this replacement value as the maximum value. diff --git a/_aggregations/metric/median-absolute-deviation.md b/_aggregations/metric/median-absolute-deviation.md new file mode 100644 index 00000000..60968f20 --- /dev/null +++ b/_aggregations/metric/median-absolute-deviation.md @@ -0,0 +1,141 @@ +--- +layout: default +title: Median absolute deviation +parent: Metric aggregations +nav_order: 65 +redirect_from: + - /query-dsl/aggregations/metric/median-absolute-deviation/ +--- + +# Median absolute deviation aggregation + +The `median_absolute_deviation` aggregation is a single-value metric aggregation. Median absolute deviation is a variability metric that measures dispersion from the median. + +Median absolute deviation is less affected by outliers than standard deviation, which relies on squared error terms and is useful for describing data that is not normally distributed. + +Median absolute deviation is computed as follows: + +``` +median_absolute_deviation = median( | xi - median(xi) | ) +``` + + +OpenSearch estimates `median_absolute_deviation`, rather than calculating it directly, because of memory limitations. This estimation is computationally expensive. You can adjust the trade-off between estimation accuracy and performance. For more information, see [Adjusting estimation accuracy](https://github.com/opensearch-project/documentation-website/pull/9453/files#adjusting-estimation-accuracy). + +## Parameters + +The `median_absolute_deviation` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The name of the numeric field for which the median absolute deviation is computed. | +| `missing` | Optional | Numeric | The value to assign to missing instances of the field. If not provided, documents with missing values are omitted from the estimation. | +| `compression` | Optional | Numeric | A parameter that [adjusts the balance between estimate accuracy and performance](#adjusting-estimation-accuracy). The value of `compression` must be greater than `0`. The default value is `1000`. | + +## Example + +The following example calculates the median absolute deviation of the `DistanceMiles` field in the `opensearch_dashboards_sample_data_flights` dataset: + +```json +GET opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "median_absolute_deviation_DistanceMiles": { + "median_absolute_deviation": { + "field": "DistanceMiles" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +As shown in the following example response, the aggregation returns an estimate of the median absolute deviation in the `median_absolute_deviation_DistanceMiles` variable: + +```json +{ + "took": 490, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "median_absolute_deviation_DistanceMiles": { + "value": 1830.917892238693 + } + } +} +``` + +## Missing values + +OpenSearch ignores missing and null values when computing `median_absolute_deviation`. + +You can assign a value to missing instances of the aggregated field. See [Missing aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) for more information. + +## Adjusting estimation accuracy + +The median absolute deviation is calculated using the [t-digest](https://github.com/tdunning/t-digest/tree/main) data structure, which takes a `compression` parameter to balance performance and estimation accuracy. Lower values of `compression` improve performance but may reduce estimation accuracy, as shown in the following request: + +```json +GET opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "median_absolute_deviation_DistanceMiles": { + "median_absolute_deviation": { + "field": "DistanceMiles", + "compression": 10 + } + } + } +} +``` +{% include copy-curl.html %} + +The estimation error depends on the dataset but is usually below 5%, even for `compression` values as low as `100`. (The low example value of `10` is used here to illustrate the trade-off effect and is not recommended.) + +Note the decreased computation time (`took` time) and the slightly less accurate value of the estimated parameter in the following response. + +For reference, OpenSearch's best estimate (with `compression` set arbitrarily high) for the median absolute deviation of `DistanceMiles` is `1831.076904296875`: + + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "median_absolute_deviation_DistanceMiles": { + "value": 1836.265614211182 + } + } +} +``` diff --git a/_aggregations/metric/minimum.md b/_aggregations/metric/minimum.md index dd17c854..80e254f0 100644 --- a/_aggregations/metric/minimum.md +++ b/_aggregations/metric/minimum.md @@ -2,26 +2,39 @@ layout: default title: Minimum parent: Metric aggregations -grand_parent: Aggregations nav_order: 70 redirect_from: - /query-dsl/aggregations/metric/minimum/ --- -# Minimum aggregations +# Minimum aggregation -The `min` metric is a single-value metric aggregations that returns the minimum value of a field. +The `min` metric is a single-value metric that returns the minimum value of a field. -The following example calculates the minimum of the `taxful_total_price` field: +The `min` aggregation compares numeric fields using a `double` (double-precision) representation. Results should be considered approximate for fields containing `long` or `unsigned_long` integers with absolute values greater than 253 because the number of significant bits in a `double` mantissa is 53. +{: .note} + +## Parameters + +The `min` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `field` | Required | String | The name of the field for which the minimum is computed. | +| `missing` | Optional | Numeric | The value to assign to missing instances of the field. If not provided, documents containing missing values are omitted from the aggregation. | + +## Example + +This following example request finds the least expensive item---the item with the minimum value of the `base_unit_price`---in the OpenSearch Dashboards e-commerce sample data: ```json GET opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "min_taxful_total_price": { + "min_base_unit_price": { "min": { - "field": "taxful_total_price" + "field": "products.base_unit_price" } } } @@ -29,11 +42,13 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +## Example response + +As shown in the following example response, the aggregation returns the minimum value of `products.base_unit_price`: ```json { - "took": 13, + "took": 15, "timed_out": false, "_shards": { "total": 1, @@ -50,9 +65,17 @@ GET opensearch_dashboards_sample_data_ecommerce/_search "hits": [] }, "aggregations": { - "min_taxful_total_price": { - "value": 6.98828125 + "min_base_unit_price": { + "value": 5.98828125 } } } -``` \ No newline at end of file +``` + +You can use the aggregation name (`min_base_unit_price`) as a key to retrieve the aggregation from the response. + +## Missing values + +You can assign a value to missing instances of the aggregated field. See [Missing aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/missing/) for more information. + +Missing values are normally ignored by `min`. If you use `missing` to assign a value lower than any existing value, `min` returns this replacement value as the minimum value. diff --git a/_aggregations/metric/percentile-ranks.md b/_aggregations/metric/percentile-ranks.md index 33ccb3d2..1a1b45f0 100644 --- a/_aggregations/metric/percentile-ranks.md +++ b/_aggregations/metric/percentile-ranks.md @@ -2,28 +2,45 @@ layout: default title: Percentile ranks parent: Metric aggregations -grand_parent: Aggregations nav_order: 80 redirect_from: - /query-dsl/aggregations/metric/percentile-ranks/ --- -# Percentile rank aggregations +# Percentile rank aggregation -Percentile rank is the percentile of values at or below a threshold grouped by a specified value. For example, if a value is greater than or equal to 80% of the values, it has a percentile rank of 80. +The `percentile_ranks` aggregation estimates the percentage of observed values that fall below or at given thresholds. This is useful for understanding the relative standing of a particular value within a distribution of values. + +For example, you can use a percentile rank aggregation to learn how a transaction amount of `45` compares to other transaction values in a dataset. The percentile rank aggregation returns a value like `82.3`, which means 82.3% of transactions are less than or equal to `45`. + +## Parameters + +The `percentile_ranks` aggregation takes the following parameters. + +| Parameter | Data type | Required/Optional | Description | +| ---------------------------------------- | ---------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| `field` | String | Required | The numeric field used to compute percentile ranks. | +| `values` | Array of doubles | Required | The values used to calculate percentile ranks. | +| `keyed` | Boolean | Optional | If set to `false`, returns results as an array. Otherwise returns results as a JSON object. Default is `true`. | +| `tdigest.compression` | Double | Optional | Controls accuracy and memory usage of the `tdigest` algorithm. See [Precision tuning with `tdigest`](#precision-tuning-with-tdigest). | +| `hdr.number_of_significant_value_digits` | Integer | Optional | The precision setting for the HDR histogram. See [HDR histogram](#hdr-histogram). | +| `missing` | Number | Optional | The default value used when the target field is missing in a document. | +| `script` | Object | Optional | The script used to compute custom values instead of using a field. Supports inline and stored scripts. | + + +## Example + + + +First, create a sample index: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +PUT /transaction_data { - "size": 0, - "aggs": { - "percentile_rank_taxful_total_price": { - "percentile_ranks": { - "field": "taxful_total_price", - "values": [ - 10, - 15 - ] + "mappings": { + "properties": { + "amount": { + "type": "double" } } } @@ -31,17 +48,269 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +Add sample numeric values to illustrate percentile rank calculations: ```json -... -"aggregations" : { - "percentile_rank_taxful_total_price" : { - "values" : { - "10.0" : 0.055096056411283456, - "15.0" : 0.0830092961834656 +POST /transaction_data/_bulk +{ "index": {} } +{ "amount": 10 } +{ "index": {} } +{ "amount": 20 } +{ "index": {} } +{ "amount": 30 } +{ "index": {} } +{ "amount": 40 } +{ "index": {} } +{ "amount": 50 } +{ "index": {} } +{ "amount": 60 } +{ "index": {} } +{ "amount": 70 } +``` +{% include copy-curl.html %} + + +Run a `percentile_ranks` aggregation to calculate how certain values compare to the overall distribution: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "field": "amount", + "values": [25, 55] + } } } - } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +The response demonstrates that 28.6% of the values are less than or equal to `25` and 71.4% are less than or equal to `55`: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rank_check": { + "values": { + "25.0": 28.57142857142857, + "55.0": 71.42857142857143 + } + } + } +} +``` + +## Keyed response + +You can change the format of the returned aggregation from a JSON object to a list of key-value pairs by setting the `keyed` parameter to `false`: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "field": "amount", + "values": [25, 55], + "keyed": false + } + } + } +} +``` +{% include copy-curl.html %} + +The response includes an array instead of an object: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rank_check": { + "values": [ + { + "key": 25, + "value": 28.57142857142857 + }, + { + "key": 55, + "value": 71.42857142857143 + } + ] + } + } +} +``` + + + +## Precision tuning with tdigest + + + +By default, percentile ranks are calculated using the `tdigest` algorithm. You can control the trade-off between accuracy and memory usage by specifying the `tdigest.compression` parameter. Higher values provide better accuracy but require more memory. For more information about how `tdigest` works, see [Precision tuning with `tdigest`]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile/#precision-tuning-with-tdigest). + +The following example is configured with `tdigest.compression` set to `200`: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "field": "amount", + "values": [25, 55], + "tdigest": { + "compression": 200 + } + } + } + } +} +``` +{% include copy-curl.html %} + +### HDR histogram + +As an alternative to `tdigest`, you can use the High Dynamic Range (HDR) histogram algorithm, which is better suited for large numbers of buckets and fast processing. For more information about how the HDR histogram works, see [HDR histogram]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile/#hdr-histogram). + +You should use HDR if you: + +* Are aggregating across many buckets. +* Don't require extreme precision in the tail percentiles. +* Have sufficient memory available. + +You should avoid HDR if: + +* Tail accuracy is important. +* You're analyzing skewed or sparse data distributions. + +The following example is configured with `hdr.number_of_significant_value_digits` set to `3`: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "field": "amount", + "values": [25, 55], + "hdr": { + "number_of_significant_value_digits": 3 + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Missing values + +If some documents are missing the target field, you can instruct the query to use a fallback value by setting the `missing` parameter. The following example ensures that documents without an `amount` field are treated as if their values are `0` and are included in the percentile ranks computation: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "field": "amount", + "values": [25, 55], + "missing": 0 + } + } + } +} +``` +{% include copy-curl.html %} + +### Script + +Instead of specifying a field, you can dynamically compute the value using a script. This is useful when you need to apply transformations, such as converting currencies or applying weights. + +#### Inline script + +The following example uses an inline script to calculate the percentile ranks of the transformed values `30` and `60` against values from the `amount` field, increased by 10%: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "values": [30, 60], + "script": { + "source": "doc['amount'].value * 1.1" + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Stored script + + +To use a stored script, first create it using the following request: + +```json +POST _scripts/percentile_script +{ + "script": { + "lang": "painless", + "source": "doc[params.field].value * params.multiplier" + } +} +``` +{% include copy-curl.html %} + +Then use the stored script in the `percentile_ranks` aggregation: + +```json +GET /transaction_data/_search +{ + "size": 0, + "aggs": { + "rank_check": { + "percentile_ranks": { + "values": [30, 60], + "script": { + "id": "percentile_script", + "params": { + "field": "amount", + "multiplier": 1.1 + } + } + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_aggregations/metric/percentile.md b/_aggregations/metric/percentile.md index c68b0e0e..abd93f69 100644 --- a/_aggregations/metric/percentile.md +++ b/_aggregations/metric/percentile.md @@ -2,30 +2,53 @@ layout: default title: Percentile parent: Metric aggregations -grand_parent: Aggregations nav_order: 90 redirect_from: - /query-dsl/aggregations/metric/percentile/ --- -# Percentile aggregations +# Percentile aggregation -Percentile is the percentage of the data that's at or below a certain threshold value. +The `percentiles` aggregation estimates the value at a given percentile of a numeric field. This is useful for understanding distribution boundaries. -The `percentile` metric is a multi-value metric aggregation that lets you find outliers in your data or figure out the distribution of your data. +For example, a 95th percentile of `load_time` = `120ms` means that 95% of values are less than or equal to 120 ms. -Like the `cardinality` metric, the `percentile` metric is also approximate. +Use the `percentiles` aggregation in the following scenarios: -The following example calculates the percentile in relation to the `taxful_total_price` field: +- Finding outliers, such as the slowest 1% of requests. +- Determining whether data is skewed or has more than one peak by comparing several percentiles. +- Describing typical values more reliably than an average or maximum. For example, a single very slow request can raise the maximum load time far above what most users experience. + +Similarly to the [`cardinality`]({{site.url}}{{site.baseurl}}/aggregations/metric/cardinality/) metric, the `percentiles` aggregation is approximate. For more information, see [Percentile accuracy](#percentile-accuracy). + +## Parameters + +The `percentiles` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| ---------------------------------------- | -------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------- | +| `field` | Required | String | The numeric field used to compute percentiles. | +| `percents` | Optional | Array of doubles | The list of percentiles returned in the response. Each value must be between `0` and `100`, inclusive. Default is `[1, 5, 25, 50, 75, 95, 99]`. | +| `keyed` | Optional | Boolean | If set to `false`, returns results as an array. Otherwise, returns results as a JSON object. Default is `true`. | +| `tdigest.compression` | Optional | Double | Controls accuracy and memory usage of the `tdigest` algorithm. Default is `100`. See [Precision tuning with `tdigest`](#precision-tuning-with-tdigest). | +| `hdr.number_of_significant_value_digits` | Optional | Integer | The precision setting for the HDR histogram. Valid values are 0--5. Default is `3`. See [HDR histogram](#hdr-histogram). | +| `missing` | Optional | Number | The default value used when the target field is missing in a document. | +| `script` | Optional | Object | The script used to compute custom values instead of using a field. Supports inline and stored scripts. | + +You can specify either `tdigest` or `hdr` in a request, but not both. +{: .note} + +## Example + +First, create an index: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +PUT /latency_data { - "size": 0, - "aggs": { - "percentile_taxful_total_price": { - "percentiles": { - "field": "taxful_total_price" + "mappings": { + "properties": { + "load_time": { + "type": "double" } } } @@ -33,22 +56,457 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +Add sample numeric values to illustrate percentile calculations: ```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 +POST /latency_data/_bulk?refresh +{ "index": {} } +{ "load_time": 20 } +{ "index": {} } +{ "load_time": 40 } +{ "index": {} } +{ "load_time": 60 } +{ "index": {} } +{ "load_time": 80 } +{ "index": {} } +{ "load_time": 100 } +{ "index": {} } +{ "load_time": 120 } +{ "index": {} } +{ "load_time": 140 } +``` + +{% include copy-curl.html %} + +The following example calculates the default set of percentiles for the `load_time` field: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_percentiles": { + "percentiles": { + "field": "load_time" + } } } - } } ``` +{% include copy-curl.html %} + +By default, the 1st, 5th, 25th, 50th, 75th, 95th, and 99th percentiles are returned: + +```json +{ + ... + "aggregations": { + "load_time_percentiles": { + "values": { + "1.0": 20, + "5.0": 20, + "25.0": 40, + "50.0": 80, + "75.0": 120, + "95.0": 140, + "99.0": 140 + } + } + } +} +``` + +## Custom percentiles + +You can specify the exact percentiles using the `percents` array: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_percentiles": { + "percentiles": { + "field": "load_time", + "percents": [50, 90, 99] + } + } + } +} +``` +{% include copy-curl.html %} + +The response includes only the three requested percentiles: + +```json +{ + ... + "aggregations": { + "load_time_percentiles": { + "values": { + "50.0": 80, + "90.0": 140, + "99.0": 140 + } + } + } +} +``` + +## Keyed response + +You can change the format of the returned aggregation from a JSON object to a list of key-value pairs by setting the `keyed` parameter to `false`: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_percentiles": { + "percentiles": { + "field": "load_time", + "keyed": false + } + } + } +} +``` +{% include copy-curl.html %} + +The response provides percentiles as an array of values: + +```json +{ + ... + "aggregations": { + "load_time_percentiles": { + "values": [ + { + "key": 1, + "value": 20 + }, + { + "key": 5, + "value": 20 + }, + { + "key": 25, + "value": 40 + }, + { + "key": 50, + "value": 80 + }, + { + "key": 75, + "value": 120 + }, + { + "key": 95, + "value": 140 + }, + { + "key": 99, + "value": 140 + } + ] + } + } +} +``` + +## Choosing an algorithm + +OpenSearch provides two algorithms for calculating percentiles: `tdigest` (the default) and HDR histogram. The `tdigest` algorithm uses less memory, while HDR histogram is faster but uses more memory. + + + +### Precision tuning with tdigest + + + +The `tdigest` algorithm is the default method used to calculate percentiles. It provides a memory-efficient way to estimate percentiles, especially when working with floating-point data such as response times or latencies. + +Unlike exact percentile calculations, `tdigest` uses a probabilistic approach that groups values into _centroids_---small clusters that summarize the distribution. This method enables accurate estimates for most percentiles without needing to store all the raw data in memory. + +The algorithm is designed to be highly accurate near the tails of the distribution---the low percentiles (such as 1st) and high percentiles (such as 99th)---which are often the most important for performance analysis. You can control the precision of the results using the `compression` parameter. + +A higher `compression` value means that more centroids are used, which increases accuracy (especially in the tails) but requires more memory and CPU. A lower `compression` value reduces memory usage and speeds up execution, but the results may be less accurate. The memory used by the digest grows with the `compression` value and does not depend on the number of values being aggregated. + +Use `tdigest` when: + +* Your data includes floating-point values, such as response times, latency, or duration. +* You need accurate results in the extreme percentiles, for example, the 1st or 99th. + +Avoid `tdigest` when: + +* Speed is more important than memory usage (consider using [`hdr`](#hdr-histogram) instead). + +The following example sets `tdigest.compression` to `200`: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_percentiles": { + "percentiles": { + "field": "load_time", + "tdigest": { + "compression": 200 + } + } + } + } +} +``` +{% include copy-curl.html %} + +### HDR histogram + +The High Dynamic Range (HDR) histogram is an alternative to [`tdigest`](#precision-tuning-with-tdigest) for calculating percentiles. It is especially useful when dealing with large datasets and latency measurements. It is designed for speed and supports a wide dynamic range of values while maintaining a fixed, configurable level of precision. + +Unlike [`tdigest`](#precision-tuning-with-tdigest), which offers more accuracy in the tails of a distribution (extreme percentiles), HDR prioritizes speed and uniform accuracy across the range. It works best when the number of buckets is large and extreme precision in rare values is not required. + +For example, if you're measuring response times ranging from 1 microsecond to 1 hour and configure HDR with 3 significant digits, it will record values with a precision of ±1 microsecond for values up to 1 millisecond and ±3.6 seconds for values near 1 hour. + +This trade-off makes HDR much faster and more memory-intensive than [`tdigest`](#precision-tuning-with-tdigest). + +The following table presents the breakdown of HDR significant digits. + +| Significant digits | Relative precision (max error) | +| ------------------ | ------------------------------ | +| 1 | 1 part in 10 = 10% | +| 2 | 1 part in 100 = 1% | +| 3 | 1 part in 1,000 = 0.1% | +| 4 | 1 part in 10,000 = 0.01% | +| 5 | 1 part in 100,000 = 0.001% | + +You should use HDR if you: + +* Are aggregating across many buckets. +* Have sufficient memory available. + +You should avoid HDR if your data contains negative values or if the range of values is unknown. For more information, see the note following this example. + +The following example is configured with `hdr.number_of_significant_value_digits` set to `3`: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_percentiles": { + "percentiles": { + "field": "load_time", + "hdr": { + "number_of_significant_value_digits": 3 + } + } + } + } +} +``` +{% include copy-curl.html %} + +Unlike `tdigest`, which returns exact values for this small dataset, HDR rounds each value to the configured precision: + +```json +{ + ... + "aggregations": { + "load_time_percentiles": { + "values": { + "1.0": 20.0, + "5.0": 20.0, + "25.0": 40.015625, + "50.0": 80.046875, + "75.0": 120.046875, + "95.0": 140.109375, + "99.0": 140.109375 + } + } + } +} +``` + +The HDR histogram supports only non-negative values. Avoid HDR when the range of values is unknown, because a wide range can require a large amount of memory. +{: .note} + +## Percentile accuracy + +Calculating exact percentiles requires sorting all values, which uses memory in proportion to the size of the data. To calculate percentiles across large datasets, OpenSearch uses approximation algorithms. Keep the following considerations in mind: + +- Accuracy is proportional to q(1 − q), where q is the requested percentile expressed as a fraction (for example, 0.99 for the 99th percentile). Thus, accuracy is highest for extreme percentiles, such as the 1st or 99th, and lowest for percentiles near the median. +- For small datasets, the results are exact or very close to exact. For example, the percentiles for the seven `load_time` values on this page are exact. +- As the number of values grows, the algorithm approximates the percentiles to limit memory usage. The size of the error depends on the distribution and volume of the data. +- For large datasets with a uniform distribution, the error tends to decrease as the number of values grows because the digest can summarize the distribution more evenly. Skewed distributions do not benefit in the same way. +- The results can differ slightly between requests on the same data. + +The `tdigest` algorithm is described in the paper [Computing Extremely Accurate Quantiles Using t-Digests](https://arxiv.org/abs/1902.04023). + +To balance accuracy and memory usage, use the `tdigest.compression` or `hdr.number_of_significant_value_digits` parameter. + +## Script + +Instead of specifying a field, you can dynamically compute the value using a script. This is useful when you need to apply transformations, such as converting currencies or applying weights. + +### Inline script + +Use a script to compute derived values: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "adjusted_percentiles": { + "percentiles": { + "script": { + "source": "doc['load_time'].value * 1.2" + }, + "percents": [50, 95] + } + } + } +} +``` +{% include copy-curl.html %} + +To pass values to a script, use `params`. The following example adds an estimated network overhead of 15 milliseconds to each load time: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_with_overhead": { + "percentiles": { + "script": { + "lang": "painless", + "source": "doc['load_time'].value + params.network_overhead_ms", + "params": { + "network_overhead_ms": 15 + } + }, + "percents": [ + 50, + 95 + ] + } + } + } +} +``` +{% include copy-curl.html %} + +Each percentile increases by 15 milliseconds: + +```json +{ + ... + "aggregations": { + "load_time_with_overhead": { + "values": { + "50.0": 95.0, + "95.0": 155.0 + } + } + } +} +``` + +### Stored script + +First, create a sample script using the following request: + +```json +POST _scripts/load_script +{ + "script": { + "lang": "painless", + "source": "doc[params.field].value * params.multiplier" + } +} +``` +{% include copy-curl.html %} + +Then use the stored script in the `percentiles` aggregation, providing the `params` required by the stored script: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "adjusted_percentiles": { + "percentiles": { + "script": { + "id": "load_script", + "params": { + "field": "load_time", + "multiplier": 1.2 + } + }, + "percents": [50, 95] + } + } + } +} +``` +{% include copy-curl.html %} + +## Missing values + +By default, documents that do not contain the target field are ignored. Use the `missing` setting to configure a fallback value for these documents. + +To try the `missing` setting, index a document that does not contain a `load_time` value: + +```json +PUT /latency_data/_doc/health-check?refresh +{ + "endpoint": "/health" +} +``` +{% include copy-curl.html %} + +The following request counts documents without a `load_time` value as `0`: + +```json +GET /latency_data/_search +{ + "size": 0, + "aggs": { + "load_time_percentiles": { + "percentiles": { + "field": "load_time", + "missing": 0 + } + } + } +} +``` +{% include copy-curl.html %} + +The document without a `load_time` value is counted as `0`, so the 1st and 5th percentiles decrease from `20` to `0`: + +```json +{ + ... + "aggregations": { + "load_time_percentiles": { + "values": { + "1.0": 0.0, + "5.0": 0.0, + "25.0": 40.0, + "50.0": 80.0, + "75.0": 120.0, + "95.0": 140.0, + "99.0": 140.0 + } + } + } +} +``` + +Scripts that read `doc['load_time'].value`, such as the ones in the [Script](#script) section, fail on documents without a `load_time` value. To handle these documents in a script, check `doc['load_time'].size() == 0` first. +{: .note} diff --git a/_aggregations/metric/scripted-metric.md b/_aggregations/metric/scripted-metric.md index d1807efb..099f5bd4 100644 --- a/_aggregations/metric/scripted-metric.md +++ b/_aggregations/metric/scripted-metric.md @@ -2,52 +2,443 @@ layout: default title: Scripted metric parent: Metric aggregations -grand_parent: Aggregations nav_order: 100 redirect_from: - /query-dsl/aggregations/metric/scripted-metric/ --- -# Scripted metric aggregations +# Scripted metric aggregation -The `scripted_metric` metric is a multi-value metric aggregation that returns metrics calculated from a specified script. +The `scripted_metric` aggregation is a multi-value metric aggregation that returns metrics calculated by scripts that you provide. The aggregation runs four scripts, one for each of its phases: `init`, `map`, `combine`, and `reduce`. The phases run in order and together combine results from your documents. The scripts are written in [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/), and you can provide each one inline or as a [stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/). -A script has four stages: the initial stage, the map stage, the combine stage, and the reduce stage. +All four scripts share a mutable object called `state` that is defined by you. The `state` is local to each shard during the `init`, `map`, and `combine` phases. The result is passed into the `states` array for the `reduce` phase. Therefore, each shard's `state` is independent until the shards are combined in the `reduce` step. Each script can be specified as a string containing the script source or a script object. For more information about specifying scripts, see [How to use scripts]({{site.url}}{{site.baseurl}}/scripting/using-scripts/). -* `init_script`: (OPTIONAL) Sets the initial state and executes before any collection of documents. -* `map_script`: Checks the value of the `type` field and executes the aggregation on the collected documents. -* `combine_script`: Aggregates the state returned from every shard. The aggregated value is returned to the coordinating node. -* `reduce_script`: Provides access to the variable states; this variable combines the results from the `combine_script` on each shard into an array. +## Parameters -The following example aggregates the different HTTP response types in web log data: +The `scripted_metric` aggregation takes the following parameters. + +| Parameter | Data type | Required/Optional | Description | +| ---------------- | --------- | ----------------- | -------------------------------------------------------------------------------------------------- | +| `init_script` | String or object | Optional | A script that executes once per shard before any documents are processed. Used to set up an initial `state` (for example, initialize counters or lists in a `state` object). If not provided, the `state` starts as an empty object on each shard. | +| `map_script` | String or object | Required | A script that executes for each document collected by the aggregation. This script updates the `state` based on the document's data. For example, you might check the field's value and then increment a counter or calculate a running sum in the `state`. | +| `combine_script` | String or object | Required | A script that executes once per shard after all documents on that shard have been processed by the `map_script`. This script aggregates the shard's `state` into a single result to be sent back to the coordinating node. This script is used to finalize the computation for one shard (for example, summing up counters or totals stored in the `state`). The script should return the consolidated value or structure for its shard. | +| `reduce_script` | String or object | Required | A script that executes once on the coordinating node after receiving combined results from all shards. This script receives a special variable `states`, which is an array containing each shard's output from the `combine_script`. The `reduce_script` iterates over states and produces the final aggregation output (for example, adding shard sums or merging maps of counts). The value returned by the `reduce_script` is the value reported in the aggregation results. | +| `params` | Object | Optional | User-defined parameters accessible from all four scripts. | + +## Allowed return types + +Scripts can use any valid operation and object internally. However, the data you store in `state` or return from any script must be of one of the allowed types. This restriction exists because the intermediate `state` needs to be sent between nodes. The following types are allowed: + +- Primitive types: `int`, `long`, `float`, `double`, `boolean` +- String +- Map (with keys and values of only allowed types: primitive types, string, map, or array) +- Array (containing only allowed types: primitive types, string, map, or array) + +The `state` can be a number, a string, a `map` (object) or an array (list), or a combination of these. For example, you can use a `map` to accumulate multiple counters, an array to collect values, or a single number to keep a running sum. If you need to return multiple metrics, you can store them in a `map` or array. If you return a `map` as the final value from the `reduce_script`, the aggregation result contains an object. If you return a single number or string, the result is a single value. + +## Using parameters in scripts + +You can optionally pass custom parameters to your scripts using the `params` field. This is a user-defined object whose contents are available in all four scripts as `params`. If you do not specify any `params`, the `params` object is empty. You can also define `params` on an individual script object, for example, `"reduce_script": {"source": "...", "params": {...}}`. OpenSearch merges these parameters with the top-level `params`. A parameter name can't appear in both places; if it does, the request fails. + +For example, you can supply a `threshold` or `field` name in `params` and then reference `params.threshold` or `params.field` in your scripts: ```json -GET opensearch_dashboards_sample_data_logs/_search +"scripted_metric": { + "params": { + "threshold": 100, + "field": "amount" + }, + "init_script": "...", + "map_script": "...", + "combine_script": "...", + "reduce_script": "..." +} +``` + +## Examples + +The following examples demonstrate different ways to use `scripted_metric`. + +### Calculating net profit from transactions + +The following example demonstrates the use of the `scripted_metric` aggregation to compute a custom metric that is not directly supported by built-in aggregations. The dataset represents financial transactions, in which each document is classified as either a `sale` (income) or a `cost` (expense) and includes an `amount` field. The objective is to calculate the total net profit by subtracting the total cost from the total sales across all documents. + +Create an index: + +```json +PUT transactions +{ + "mappings": { + "properties": { + "type": { "type": "keyword" }, + "amount": { "type": "double" } + } + } +} +``` +{% include copy-curl.html %} + +Index four transactions, two sales (amounts `80` and `130`), and two costs (`10` and `30`): + +```json +PUT transactions/_bulk?refresh=true +{ "index": {} } +{ "type": "sale", "amount": 80 } +{ "index": {} } +{ "type": "cost", "amount": 10 } +{ "index": {} } +{ "type": "cost", "amount": 30 } +{ "index": {} } +{ "type": "sale", "amount": 130 } +``` +{% include copy-curl.html %} + +To run a search with a `scripted_metric` aggregation to calculate the profit, use the following scripts: + +- The `init_script` creates an empty list used to store transaction values for each shard. +- The `map_script` adds each document's amount to the `state.transactions` list as a positive number if the type is `sale` or as a negative number if the type is `cost`. By the end of the `map` phase, each shard has a `state.transactions` list representing its income and expenses. +- The `combine_script` processes the `state.transactions` list and computes a single `shardProfit` value for the shard. The `shardProfit` is then returned as the shard's output. +- The `reduce_script` runs on the coordinating node, receiving the `states` array, which holds the `shardProfit` value from each shard. It checks for null entries, adds these values to compute the overall profit, and returns the final result. + +The following request contains all described scripts: + +```json +GET transactions/_search +{ + "size": 0, + "aggs": { + "total_profit": { + "scripted_metric": { + "init_script": "state.transactions = []", + "map_script": "state.transactions.add(doc['type'].value == 'sale' ? doc['amount'].value : -1 * doc['amount'].value)", + "combine_script": "double shardProfit = 0; for (t in state.transactions) { shardProfit += t; } return shardProfit;", + "reduce_script": "double totalProfit = 0; for (p in states) { if (p != null) { totalProfit += p; }} return totalProfit;" + } + } + } +} +``` +{% include copy-curl.html %} + + +The response returns the `total_profit`: + +```json +{ + ... + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "total_profit": { + "value": 170.0 + } + } +} +``` + +### Shard-by-shard walkthrough + +To see how the four phases process the data, run the net profit calculation on an index with two shards. Create the index: + +```json +PUT transactions_2shards +{ + "settings": { + "number_of_shards": 2 + }, + "mappings": { + "properties": { + "type": { "type": "keyword" }, + "amount": { "type": "double" } + } + } +} +``` +{% include copy-curl.html %} + +Index the four transactions. The `routing` values place documents 1 and 3 on shard 0 and documents 2 and 4 on shard 1: + +```json +POST transactions_2shards/_bulk?refresh +{ "index": { "_id": "1", "routing": "a" } } +{ "type": "sale", "amount": 80 } +{ "index": { "_id": "2", "routing": "b" } } +{ "type": "cost", "amount": 10 } +{ "index": { "_id": "3", "routing": "a" } } +{ "type": "cost", "amount": 30 } +{ "index": { "_id": "4", "routing": "b" } } +{ "type": "sale", "amount": 130 } +``` +{% include copy-curl.html %} + +The following table shows the result of each phase of the net profit calculation on each shard. + +| Phase | Shard 0 (documents 1 and 3) | Shard 1 (documents 2 and 4) | +| :--- | :--- | :--- | +| Before `init_script` | `{}` | `{}` | +| After `init_script` | `{"transactions": []}` | `{"transactions": []}` | +| After `map_script` | `{"transactions": [80.0, -30.0]}` | `{"transactions": [-10.0, 130.0]}` | +| After `combine_script` | `50.0` | `120.0` | + +The `reduce_script` then runs once on the coordinating node. It receives the `states` array `[50.0, 120.0]` and returns their sum, `170.0`. + +The order of the entries in `states` isn't guaranteed, so you might see `[120.0, 50.0]` instead. Write the `reduce_script` so that its result doesn't depend on the order of the shard results. +{: .note} + +To inspect the intermediate results yourself, make the later scripts return their input unchanged. For example, the following request returns each shard's `state` after the `map_script` by returning `state` from the `combine_script` and `states` from the `reduce_script`: + +```json +GET transactions_2shards/_search { "size": 0, - "aggregations": { - "responses.counts": { + "aggs": { + "profit": { "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']; + "init_script": "state.transactions = []", + "map_script": "state.transactions.add(doc['type'].value == 'sale' ? doc['amount'].value : -1 * doc['amount'].value)", + "combine_script": "return state", + "reduce_script": "return states" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains one `state` object for each shard: + +```json +{ + ... + "aggregations": { + "profit": { + "value": [ + { + "transactions": [ + 80.0, + -30.0 + ] + }, + { + "transactions": [ + -10.0, + 130.0 + ] } - return counts; + ] + } + } +} +``` + +Similarly, to see the result of the `combine_script` on each shard, keep the original `combine_script` and return `states` from the `reduce_script`: + +```json +GET transactions_2shards/_search +{ + "size": 0, + "aggs": { + "profit": { + "scripted_metric": { + "init_script": "state.transactions = []", + "map_script": "state.transactions.add(doc['type'].value == 'sale' ? doc['amount'].value : -1 * doc['amount'].value)", + "combine_script": "double p = 0; for (t in state.transactions) { p += t } return p", + "reduce_script": "return states" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the profit calculated on each shard: + +```json +{ + ... + "aggregations": { + "profit": { + "value": [ + 50.0, + 120.0 + ] + } + } +} +``` + + +### Using stored scripts + +You can store each script using the [Create or Update Stored Script API]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/) and reference it by `id`. The following requests store the four scripts from the preceding example. The `map_script` reads the name of the amount field from `params.field`: + +```json +PUT _scripts/profit_init +{ + "script": { + "lang": "painless", + "source": "state.transactions = []" + } +} +``` +{% include copy-curl.html %} + +```json +PUT _scripts/profit_map +{ + "script": { + "lang": "painless", + "source": "double v = doc[params.field].value; state.transactions.add(doc['type'].value == 'sale' ? v : -1 * v)" + } +} +``` +{% include copy-curl.html %} + +```json +PUT _scripts/profit_combine +{ + "script": { + "lang": "painless", + "source": "double p = 0; for (t in state.transactions) { p += t } return p" + } +} +``` +{% include copy-curl.html %} + +```json +PUT _scripts/profit_reduce +{ + "script": { + "lang": "painless", + "source": "double p = 0; for (s in states) { if (s != null) { p += s } } return p" + } +} +``` +{% include copy-curl.html %} + +The following request references the stored scripts by `id`. Define the parameters in the top-level `params` object so that they are available to all of the scripts: + +```json +GET transactions/_search +{ + "size": 0, + "aggs": { + "total_profit": { + "scripted_metric": { + "init_script": { "id": "profit_init" }, + "map_script": { "id": "profit_map" }, + "combine_script": { "id": "profit_combine" }, + "reduce_script": { "id": "profit_reduce" }, + "params": { + "field": "amount" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the same `total_profit` as the preceding example: + +```json +{ + ... + "aggregations": { + "total_profit": { + "value": 170.0 + } + } +} +``` + +### Categorizing HTTP response codes + +The following example demonstrates a more advanced use of the `scripted_metric` aggregation for returning multiple values within a single aggregation. The dataset consists of web server log entries, each containing an HTTP response code. The goal is to classify the responses into three categories: successful responses (2xx status codes), client or server errors (4xx or 5xx status codes), and other responses (1xx or 3xx status codes). This classification is implemented by maintaining counters within a map-based aggregation `state`. + +Create a sample index: + +```json +PUT logs +{ + "mappings": { + "properties": { + "response": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Add sample documents with a variety of response codes: + +```json +PUT logs/_bulk?refresh=true +{ "index": {} } +{ "response": "200" } +{ "index": {} } +{ "response": "201" } +{ "index": {} } +{ "response": "404" } +{ "index": {} } +{ "response": "500" } +{ "index": {} } +{ "response": "304" } +``` +{% include copy-curl.html %} + +The `state` (on each shard) is a `map` with three counters: `error`, `success`, and `other`. + +To run a scripted metric aggregation that counts the categories, use the following scripts: + +- The `init_script` initializes counters for `error`, `success`, and `other` to `0`. +- The `map_script` examines each document's response code and increments the relevant counter based on the response code. +- The `combine_script` returns the `state.responses` map for that shard. +- The `reduce_script` merges the array of maps (`states`) from all shards. Thus, it creates a new combined `map` and adds the `error`, `success`, and `other` counts from each shard's `map`. This combined `map` is returned as the final result. + +The following request contains all described scripts: + +```json +GET logs/_search +{ + "size": 0, + "aggs": { + "responses_by_type": { + "scripted_metric": { + "init_script": "state.responses = new HashMap(); state.responses.put('success', 0); state.responses.put('error', 0); state.responses.put('other', 0);", + "map_script": """ + String code = doc['response'].value; + if (code.startsWith("5") || code.startsWith("4")) { + // 4xx or 5xx -> count as error + state.responses.error += 1; + } else if (code.startsWith("2")) { + // 2xx -> count as success + state.responses.success += 1; + } else { + // anything else (e.g., 1xx, 3xx, etc.) -> count as other + state.responses.other += 1; + } + """, + "combine_script": "return state.responses;", + "reduce_script": """ + Map combined = new HashMap(); + combined.error = 0; + combined.success = 0; + combined.other = 0; + for (state in states) { + if (state != null) { + combined.error += state.error; + combined.success += state.success; + combined.other += state.other; + } + } + return combined; """ } } @@ -56,18 +447,124 @@ GET opensearch_dashboards_sample_data_logs/_search ``` {% include copy-curl.html %} -#### Example response + +The response returns three values in the `value` object, demonstrating how a scripted metric can return multiple metrics at once by using a `map` in the `state`: ```json -... -"aggregations" : { - "responses.counts" : { - "value" : { - "other" : 0, - "success" : 12832, - "error" : 1242 +{ + ... + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "responses_by_type": { + "value": { + "other": 1, + "success": 2, + "error": 2 + } } } - } } ``` + +## Managing empty buckets + +A shard that has no matching documents still runs the `init_script` and `combine_script`, so it contributes the result of the `combine_script` to the `states` array. However, some bucket aggregations create empty buckets that are not collected on any shard. For example, a `histogram` or `date_histogram` aggregation returns empty buckets between the first and last buckets that contain documents. For these buckets, the `states` array contains `null`. + +The following request groups the transactions into histogram buckets of 25 and calculates the profit in each bucket. The transactions have amounts of 10, 30, 80, and 130, so the buckets for 50 and 100 are empty. The `reduce_script` checks for `null` before adding each state: + +```json +GET transactions/_search +{ + "size": 0, + "aggs": { + "by_amount": { + "histogram": { + "field": "amount", + "interval": 25 + }, + "aggs": { + "profit": { + "scripted_metric": { + "init_script": "state.transactions = []", + "map_script": "state.transactions.add(doc['type'].value == 'sale' ? doc['amount'].value : -1 * doc['amount'].value)", + "combine_script": "double s = 0; for (t in state.transactions) { s += t } return s", + "reduce_script": "double total = 0; for (s in states) { if (s != null) { total += s } } return total" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The empty buckets report a profit of `0`: + +```json +{ + ... + "aggregations": { + "by_amount": { + "buckets": [ + { + "key": 0.0, + "doc_count": 1, + "profit": { + "value": -10.0 + } + }, + { + "key": 25.0, + "doc_count": 1, + "profit": { + "value": -30.0 + } + }, + { + "key": 50.0, + "doc_count": 0, + "profit": { + "value": 0.0 + } + }, + { + "key": 75.0, + "doc_count": 1, + "profit": { + "value": 80.0 + } + }, + { + "key": 100.0, + "doc_count": 0, + "profit": { + "value": 0.0 + } + }, + { + "key": 125.0, + "doc_count": 1, + "profit": { + "value": 130.0 + } + } + ] + } + } +} +``` + +Without the `if (s != null)` check, the `reduce_script` fails with a `null_pointer_exception` for the empty buckets. Always check for `null` entries in the `states` array. +{: .important} + +## Performance considerations + +Because scripted metrics run custom code for every document and therefore potentially accumulate a large in-memory `state`, they can be slower than built-in aggregations. The intermediate `state` from each shard must be serialized in order to send it to the coordinating node. Therefore if your `state` is very large, it can consume a lot of memory and network bandwidth. To keep your searches efficient, make your scripts as lightweight as possible and avoid accumulating unnecessary data in the `state`. Use the combine stage to shrink `state` data before sending, as demonstrated in [Calculating net profit from transactions](#calculating-net-profit-from-transactions), and only collect the values that you truly need to produce the final metric. + diff --git a/_aggregations/metric/stats.md b/_aggregations/metric/stats.md index 0a548315..2bfd941a 100644 --- a/_aggregations/metric/stats.md +++ b/_aggregations/metric/stats.md @@ -2,26 +2,58 @@ layout: default title: Stats parent: Metric aggregations -grand_parent: Aggregations nav_order: 110 redirect_from: - /query-dsl/aggregations/metric/stats/ --- -# Stats aggregations +# Stats aggregation -The `stats` metric is a multi-value metric aggregation that returns all basic metrics such as `min`, `max`, `sum`, `avg`, and `value_count` in one aggregation query. +The `stats` aggregation is a multi-value metric aggregation that computes a summary of numeric data. This aggregation is useful for quickly understanding the distribution of numeric fields. It can operate directly on a field, apply a script to derive the values, or handle documents with missing fields. The `stats` aggregation returns five values: -The following example returns the basic stats for the `taxful_total_price` field: +* `count`: The number of values collected +* `min`: The lowest value +* `max`: The highest value +* `sum`: The total of all values +* `avg`: The average of the values (sum divided by count) + +## Parameters + +The `stats` aggregation takes the following optional parameters. + +| Parameter | Data type | Description | +| --------- | --------- | ------------------------------------------------------------------------------------------ | +| `field` | String | The field to aggregate on. Must be a numeric field. | +| `script` | Object | The script used to calculate custom values for aggregation. Can be used instead of or with `field`. | +| `missing` | Number | The default value used for documents missing the target field. + +## Example + +The following example computes a `stats` aggregation for electricity usage. + +Create an index named `power_usage` and add documents containing the number of kilowatt-hours (kWh) consumed during a given hour: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +PUT /power_usage/_bulk?refresh=true +{"index": {}} +{"device_id": "A1", "kwh": 1.2} +{"index": {}} +{"device_id": "A2", "kwh": 0.7} +{"index": {}} +{"device_id": "A3", "kwh": 1.5} +``` +{% include copy-curl.html %} + +To compute statistics on the `kwh` field across all documents, use a `stats` aggregation named `consumption_stats` over the `kwh` field. Setting `size` to `0` specifies that document hits should not be returned: + +```json +GET /power_usage/_search { "size": 0, "aggs": { - "stats_taxful_total_price": { + "consumption_stats": { "stats": { - "field": "taxful_total_price" + "field": "kwh" } } } @@ -29,18 +61,206 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +The response includes `count`, `min`, `max`, `avg`, and `sum` values for the three documents in the index: ```json -... -"aggregations" : { - "stats_taxful_total_price" : { - "count" : 4675, - "min" : 6.98828125, - "max" : 2250.0, - "avg" : 75.05542864304813, - "sum" : 350884.12890625 +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "consumption_stats": { + "count": 3, + "min": 0.699999988079071, + "max": 1.5, + "avg": 1.1333333452542622, + "sum": 3.400000035762787 + } } - } } -``` \ No newline at end of file +``` + +### Running a stats aggregation per bucket + +You can compute separate statistics for each device by nesting a `stats` aggregation inside a `terms` aggregation in the `device_id` field. The `terms` aggregation groups documents into buckets based on unique `device_id` values, and the `stats` aggregation computes summary statistics within each bucket: + +```json +GET /power_usage/_search +{ + "size": 0, + "aggs": { + "per_device": { + "terms": { + "field": "device_id.keyword" + }, + "aggs": { + "device_usage_stats": { + "stats": { + "field": "kwh" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response returns one bucket per `device_id`, with computed `count`, `min`, `max`, `avg`, and `sum` fields within each bucket: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "per_device": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "A1", + "doc_count": 1, + "device_usage_stats": { + "count": 1, + "min": 1.2000000476837158, + "max": 1.2000000476837158, + "avg": 1.2000000476837158, + "sum": 1.2000000476837158 + } + }, + { + "key": "A2", + "doc_count": 1, + "device_usage_stats": { + "count": 1, + "min": 0.699999988079071, + "max": 0.699999988079071, + "avg": 0.699999988079071, + "sum": 0.699999988079071 + } + }, + { + "key": "A3", + "doc_count": 1, + "device_usage_stats": { + "count": 1, + "min": 1.5, + "max": 1.5, + "avg": 1.5, + "sum": 1.5 + } + } + ] + } + } +} +``` + +This allows you to compare usage statistics across devices with a single query. + +### Using a script to compute derived values + +You can also use a script to compute the values used in the `stats` aggregation. This is useful when the metric is derived from document fields or requires transformation. + +For example, to convert kilowatt-hours (kWh) to watt-hours (Wh) before running the `stats` aggregation, because `1 kWh` equals `1,000 Wh`, you can use a script that multiplies each value by `1,000`. The following script `doc['kwh'].value * 1000` is used to derive the input value for each document: + +```json +GET /power_usage/_search +{ + "size": 0, + "aggs": { + "usage_wh_stats": { + "stats": { + "script": { + "source": "doc['kwh'].value * 1000" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The `stats` aggregation returned in the response reflects values of `1200`, `700`, and `1500` Wh: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "usage_wh_stats": { + "count": 3, + "min": 699.999988079071, + "max": 1500, + "avg": 1133.3333452542622, + "sum": 3400.000035762787 + } + } +} +``` + +### Using a value script with a field + +When combining a field with a transformation, you can specify both `field` and `script`. This allows using the `_value` variable to reference the field's value within the script. + +The following example increases each energy reading by 5% before computing the `stats` aggregation: + +```json +GET /power_usage/_search +{ + "size": 0, + "aggs": { + "adjusted_usage": { + "stats": { + "field": "kwh", + "script": { + "source": "_value * 1.05" + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Missing values + +If some documents do not contain the target field, they are excluded by default from the aggregation. To include them using a default value, you can specify the `missing` parameter. + +The following request treats missing `kwh` values as `0.0`: + +```json +GET /power_usage/_search +{ + "size": 0, + "aggs": { + "consumption_with_default": { + "stats": { + "field": "kwh", + "missing": 0.0 + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_aggregations/metric/sum.md b/_aggregations/metric/sum.md index 0320de63..b4a6ac19 100644 --- a/_aggregations/metric/sum.md +++ b/_aggregations/metric/sum.md @@ -2,26 +2,70 @@ layout: default title: Sum parent: Metric aggregations -grand_parent: Aggregations nav_order: 120 redirect_from: - /query-dsl/aggregations/metric/sum/ --- -# Sum aggregations +# Sum aggregation -The `sum` metric is a single-value metric aggregations that returns the sum of the values of a field. +The `sum` aggregation is a single-value metric aggregation that calculates the total sum of numeric values extracted from a field across all matching documents. This aggregation is commonly used to compute totals for metrics such as revenue, quantity, or duration. -The following example calculates the total sum of the `taxful_total_price` field: +## Parameters + +The `sum` aggregation takes the following parameters. + +| Parameter | Data type | Description | +| --------- | --------- | ------------------------------------------------------------------------------------------ | +| `field` | String | The field to aggregate on. Must be a numeric field. | +| `script` | Object | The script used to calculate custom values for aggregation. Can be used instead of or with `field`. | +| `missing` | Number | The default value used for documents missing the target field. | + +## Example + +The following example demonstrates how to calculate the total weight of deliveries recorded in a logistics index. + +Create an index: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +PUT /deliveries +{ + "mappings": { + "properties": { + "shipment_id": { "type": "keyword" }, + "weight_kg": { "type": "double" } + } + } +} +``` +{% include copy-curl.html %} + +Add sample documents: + +```json +POST /deliveries/_bulk?refresh=true +{"index": {}} +{"shipment_id": "S001", "weight_kg": 12.5} +{"index": {}} +{"shipment_id": "S002", "weight_kg": 7.8} +{"index": {}} +{"shipment_id": "S003", "weight_kg": 15.0} +{"index": {}} +{"shipment_id": "S004", "weight_kg": 10.3} +``` +{% include copy-curl.html %} + + +The following request computes the total weight across all documents in the `deliveries` index, omits document hits by setting `size` to `0`, and returns the total sum of `weight_kg`: + +```json +GET /deliveries/_search { "size": 0, "aggs": { - "sum_taxful_total_price": { + "total_weight": { "sum": { - "field": "taxful_total_price" + "field": "weight_kg" } } } @@ -29,30 +73,134 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +The response contains the value `45.6`, corresponding to the sum of `12.5` + `7.8` + `15.0` + `10.3`: ```json { - "took": 16, - "timed_out": false, - "_shards": { - "total": 1, - "successful": 1, - "skipped": 0, - "failed": 0 - }, + ... "hits": { "total": { - "value": 4675, + "value": 4, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { - "sum_taxful_total_price": { - "value": 350884.12890625 + "total_weight": { + "value": 45.6 } } } ``` + +### Using a script to compute values + +Instead of specifying a field directly, you can provide a script to calculate values for the aggregation. This is useful when the value must be derived or adjusted. + +In the following example, each weight is converted from kilograms to grams before summing using a script: + +```json +GET /deliveries/_search +{ + "size": 0, + "aggs": { + "total_weight_grams": { + "sum": { + "script": { + "source": "doc['weight_kg'].value * 1000" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response includes the `total_weight_grams` of `45600`: + +```json +{ + ... + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "total_weight_grams": { + "value": 45600 + } + } +} +``` + +### Combining a field with a value script + +You can also specify both a `field` and a `script`, using the special variable `_value` to reference the field's value. This is useful when applying transformations to existing field values. + +The following example increases all weights by 10% before summing: + +```json +GET /deliveries/_search +{ + "size": 0, + "aggs": { + "adjusted_weight": { + "sum": { + "field": "weight_kg", + "script": { + "source": "Math.round(_value * 110) / 100.0" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response reflects a 10% increase applied to the original total weight: + +```json +{ + ... + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "adjusted_weight": { + "value": 50.16 + } + } +} +``` + +### Missing values + +Documents missing the target field are ignored by default. To include them using a default value, use the `missing` parameter. + +The following example assigns a default value of `0` to missing `weight_kg` fields. This ensures that the documents without this field are treated as having `weight_kg` set to `0` and included in the aggregation. + +```json +GET /deliveries/_search +{ + "size": 0, + "aggs": { + "total_weight_with_missing": { + "sum": { + "field": "weight_kg", + "missing": 0 + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_aggregations/metric/top-hits.md b/_aggregations/metric/top-hits.md index b6752300..d19be1fc 100644 --- a/_aggregations/metric/top-hits.md +++ b/_aggregations/metric/top-hits.md @@ -2,32 +2,75 @@ layout: default title: Top hits parent: Metric aggregations -grand_parent: Aggregations nav_order: 130 redirect_from: - /query-dsl/aggregations/metric/top-hits/ --- -# Top hits aggregations +# Top hits aggregation -The `top_hits` metric is a multi-value metric aggregation that ranks the matching documents based on a relevance score for the field that's being aggregated. +The `top_hits` aggregation is a multi-value metric aggregation that retrieves the highest-scoring documents within each aggregation bucket. Use it inside a bucket aggregation to return representative or top-ranked documents per group. -You can specify the following options: +When combined with a bucket aggregation, such as [`terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/), the `top_hits` aggregation groups the result set by specified properties and retrieves the highest-scoring or most recently updated documents from each group. This is useful in the following scenarios: -- `from`: The starting position of the hit. -- `size`: The maximum size of hits to return. The default value is 3. -- `sort`: How the matching hits are sorted. By default, the hits are sorted by the relevance score of the aggregation query. +- Displaying the most recent transaction in each product category. +- Showing the highest-scoring search result from each manufacturer. +- Retrieving representative documents from grouped results without returning every match. -The following example returns the top 5 products in your eCommerce data: +## Parameters + +The following table lists the parameters accepted by the `top_hits` aggregation. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `from` | Integer | The offset from the first result to fetch. Default is `0`. | +| `size` | Integer | The maximum number of top matching hits to return per bucket. Default is `3`. | +| `sort` | Object or Array | Defines how the top matching hits are sorted. By default, hits are sorted by the score of the main query. | + +## Supported per-hit features + +Because the `top_hits` aggregation returns standard search hits, the following per-hit features are supported: + +- [Highlighting]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) +- [Explain]({{site.url}}{{site.baseurl}}/api-reference/search-apis/explain/) +- [Named queries]({{site.url}}{{site.baseurl}}/query-dsl/named-queries/) +- [Source filtering]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-source-filtering) +- [Stored fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-stored-fields) +- [Script fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-scripted-fields) +- [Doc value fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-doc-value-fields) +- [Include versions]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#query-parameters) +- Include sequence numbers and primary terms + +## Example: Grouping results by category + +In the following example, orders in the e-commerce dataset are grouped by product category using a `terms` aggregation, and the `top_hits` subaggregation retrieves the most recent order from each category. Only the `order_date`, `taxful_total_price`, and `customer_full_name` fields are included in the source: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, "aggs": { - "top_hits_products": { - "top_hits": { - "size": 5 + "top_categories": { + "terms": { + "field": "category.keyword", + "size": 3 + }, + "aggs": { + "most_recent_sales": { + "top_hits": { + "sort": [ + { + "order_date": { + "order": "desc" + } + } + ], + "_source": { + "includes": ["order_date", "taxful_total_price", "customer_full_name"] + }, + "size": 1 + } + } } } } @@ -35,115 +78,824 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +
+ + Example response + + {: .text-delta} ```json -... -"aggregations" : { - "top_hits_products" : { - "hits" : { - "total" : { - "value" : 4675, - "relation" : "eq" - }, - "max_score" : 1.0, - "hits" : [ +{ + "took": 25, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "top_categories": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 2346, + "buckets": [ { - "_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 + "key": "Men's Clothing", + "doc_count": 2024, + "most_recent_sales": { + "hits": { + "total": { + "value": 2024, + "relation": "eq" }, - { - "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 + "max_score": null, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "poN5u50BpPQaFxReh8Tz", + "_score": null, + "_source": { + "customer_full_name": "Youssef Jensen", + "order_date": "2026-05-09T23:45:36+00:00", + "taxful_total_price": 78.98 + }, + "sort": [ + 1778370336000 + ] + } + ] + } + } + }, + { + "key": "Women's Clothing", + "doc_count": 1903, + "most_recent_sales": { + "hits": { + "total": { + "value": 1903, + "relation": "eq" }, - "region_name" : "Cairo Governorate", - "continent_name" : "Africa", - "city_name" : "Cairo" - }, - "event" : { - "dataset" : "sample_ecommerce" + "max_score": null, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "6IN5u50BpPQaFxRehr5T", + "_score": null, + "_source": { + "customer_full_name": "Sonya Smith", + "order_date": "2026-05-09T23:31:12+00:00", + "taxful_total_price": 42.98 + }, + "sort": [ + 1778369472000 + ] + } + ] + } + } + }, + { + "key": "Women's Shoes", + "doc_count": 1136, + "most_recent_sales": { + "hits": { + "total": { + "value": 1136, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "3IN5u50BpPQaFxReh78O", + "_score": null, + "_source": { + "customer_full_name": "Brigitte Cross", + "order_date": "2026-05-09T23:22:34+00:00", + "taxful_total_price": 91.98 + }, + "sort": [ + 1778368954000 + ] + } + ] } } - ... } ] } } - } } -``` \ No newline at end of file +``` +
+ +## Example: Field collapsing + +Field collapsing, or result grouping, organizes a result set into logical groups and returns the top documents from each group. The groups are ordered by the relevance of their highest-scoring document. + +You can implement field collapsing by wrapping a `top_hits` aggregation inside a bucket aggregation. The following example searches the e-commerce dataset for products matching `shirt` and groups the results by `manufacturer`. A `max` aggregation captures the highest score per manufacturer, and the `terms` aggregation uses that score to order the buckets by relevance: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "query": { + "match": { + "products.product_name": "shirt" + } + }, + "aggs": { + "top_manufacturers": { + "terms": { + "field": "manufacturer.keyword", + "size": 3, + "order": { + "top_score": "desc" + } + }, + "aggs": { + "top_hits_per_manufacturer": { + "top_hits": { + "_source": { + "includes": ["products.product_name", "manufacturer"] + }, + "size": 1 + } + }, + "top_score": { + "max": { + "script": { + "source": "_score" + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The `max` (or `min`) aggregation is required because the `top_hits` aggregation cannot be used directly in the `order` option of the `terms` aggregation. +{: .note} + +
+ + Example response + + {: .text-delta} + +```json +{ + "took": 38, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1160, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "top_manufacturers": { + "doc_count_error_upper_bound": -1, + "sum_other_doc_count": 953, + "buckets": [ + { + "key": "Elitelligence", + "doc_count": 503, + "top_score": { + "value": 0.9982529878616333 + }, + "top_hits_per_manufacturer": { + "hits": { + "total": { + "value": 503, + "relation": "eq" + }, + "max_score": 0.998253, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "34N5u50BpPQaFxReicgP", + "_score": 0.998253, + "_source": { + "manufacturer": [ + "Elitelligence", + "Low Tide Media" + ], + "products": [ + { + "product_name": "Shirt - white" + }, + { + "product_name": "Shirt - white" + } + ] + } + } + ] + } + } + }, + { + "key": "Low Tide Media", + "doc_count": 500, + "top_score": { + "value": 0.9982529878616333 + }, + "top_hits_per_manufacturer": { + "hits": { + "total": { + "value": 500, + "relation": "eq" + }, + "max_score": 0.998253, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "34N5u50BpPQaFxReicgP", + "_score": 0.998253, + "_source": { + "manufacturer": [ + "Elitelligence", + "Low Tide Media" + ], + "products": [ + { + "product_name": "Shirt - white" + }, + { + "product_name": "Shirt - white" + } + ] + } + } + ] + } + } + }, + { + "key": "Oceanavigations", + "doc_count": 330, + "top_score": { + "value": 0.9561269283294678 + }, + "top_hits_per_manufacturer": { + "hits": { + "total": { + "value": 330, + "relation": "eq" + }, + "max_score": 0.9561269, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "VYN5u50BpPQaFxRehbyq", + "_score": 0.9561269, + "_source": { + "manufacturer": [ + "Oceanavigations", + "Low Tide Media" + ], + "products": [ + { + "product_name": "Shirt - grey" + }, + { + "product_name": "Vibrant Patterned Shirt" + } + ] + } + } + ] + } + } + } + ] + } + } +} +``` +
+ +## Example: Using top hits aggregations with nested objects + +When the `top_hits` aggregation is wrapped in a [`nested`]({{site.url}}{{site.baseurl}}/aggregations/bucket/nested/) or `reverse_nested` aggregation, it returns nested hits. Nested hits are internally stored as separate Lucene documents that share the same document ID as their parent. The `top_hits` aggregation can surface these inner documents when used within a `nested` or `reverse_nested` aggregation context. + +Each nested hit includes a `_nested` field in the response that identifies the array field and the zero-based offset of the nested object within that array. This information is useful for locating the original nested object within the parent document source. + +First, create an index with a `nested` field type: + +```json +PUT /top-hits-products +{ + "mappings": { + "properties": { + "tags": { "type": "keyword" }, + "reviews": { + "type": "nested", + "properties": { + "reviewer": { "type": "keyword" }, + "comment": { "type": "text" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Add a document containing a nested `reviews` field: + +```json +PUT /top-hits-products/_doc/1?refresh=true +{ + "tags": ["laptop", "electronics"], + "reviews": [ + {"reviewer": "tech_guru", "comment": "This laptop has outstanding battery life"}, + {"reviewer": "casual_user", "comment": "Great laptop for everyday tasks"}, + {"reviewer": "power_user", "comment": "This laptop handles heavy workloads easily"} + ] +} +``` +{% include copy-curl.html %} + +The following request searches for products tagged `laptop`, groups the nested reviews by reviewer, and retrieves the top review per reviewer: + +```json +GET /top-hits-products/_search +{ + "query": { + "term": { "tags": "laptop" } + }, + "aggs": { + "by_product": { + "nested": { + "path": "reviews" + }, + "aggs": { + "by_reviewer": { + "terms": { + "field": "reviews.reviewer", + "size": 1 + }, + "aggs": { + "by_nested": { + "top_hits": {} + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The `_nested` field identifies the array field (`reviews`) and the zero-based position (`offset`) of the nested object within that array: + +
+ + Example response + + {: .text-delta} + +```json +{ + "took": 16, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "top-hits-products", + "_id": "1", + "_score": 1.0, + "_source": { + "tags": [ + "laptop", + "electronics" + ], + "reviews": [ + { + "reviewer": "tech_guru", + "comment": "This laptop has outstanding battery life" + }, + { + "reviewer": "casual_user", + "comment": "Great laptop for everyday tasks" + }, + { + "reviewer": "power_user", + "comment": "This laptop handles heavy workloads easily" + } + ] + } + } + ] + }, + "aggregations": { + "by_product": { + "doc_count": 3, + "by_reviewer": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 2, + "buckets": [ + { + "key": "casual_user", + "doc_count": 1, + "by_nested": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "top-hits-products", + "_id": "1", + "_nested": { + "field": "reviews", + "offset": 1 + }, + "_score": 1.0, + "_source": { + "comment": "Great laptop for everyday tasks", + "reviewer": "casual_user" + } + } + ] + } + } + } + ] + } + } + } +} +``` +
+ +When `_source` is requested for a nested hit, only the source of the nested object is returned rather than the entire parent document source. Stored fields defined on the nested object level are also accessible through `top_hits` when it resides inside a `nested` or `reverse_nested` aggregation. + +Only nested hits contain the `_nested` field. Regular (non-nested) hits do not include this field. + +The `_nested` field can also serve as a reference for locating the nested object within the original source when `_source` is disabled on the index. + +For mappings that contain multiple levels of nested object types, the `_nested` information can be hierarchical. The following snippet shows a nested hit that resides at the first position of `nested_grand_child_field`, which is itself within the second position of `nested_child_field`: + +```json +"hits": [ + { + "_index": "my-index", + "_id": "1", + "_score": 1, + "_nested": { + "field": "nested_child_field", + "offset": 1, + "_nested": { + "field": "nested_grand_child_field", + "offset": 0 + } + }, + "_source": ... + } +] +``` + +## Example: Highlighting matched terms + +The following example searches for `shirt` across product names and uses `highlight` to wrap matched terms in `` tags within each top hit: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "query": { + "match": { + "products.product_name": "shirt" + } + }, + "aggs": { + "top_categories": { + "terms": { + "field": "category.keyword", + "size": 2 + }, + "aggs": { + "top_doc": { + "top_hits": { + "size": 1, + "_source": { + "includes": ["products.product_name"] + }, + "highlight": { + "fields": { + "products.product_name": {} + } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +
+ + Example response + + {: .text-delta} + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1160, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "top_categories": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 552, + "buckets": [ + { + "key": "Men's Clothing", + "doc_count": 817, + "top_doc": { + "hits": { + "total": { + "value": 817, + "relation": "eq" + }, + "max_score": 0.998253, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "34N5u50BpPQaFxReicgP", + "_score": 0.998253, + "_source": { + "products": [ + { + "product_name": "Shirt - white" + }, + { + "product_name": "Shirt - white" + } + ] + }, + "highlight": { + "products.product_name": [ + "Shirt - white", + "Shirt - white" + ] + } + } + ] + } + } + }, + { + "key": "Women's Clothing", + "doc_count": 343, + "top_doc": { + "hits": { + "total": { + "value": 343, + "relation": "eq" + }, + "max_score": 0.91741234, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "54N5u50BpPQaFxReiccP", + "_score": 0.91741234, + "_source": { + "products": [ + { + "product_name": "Shirt - white" + }, + { + "product_name": "Shirt - light blue denim" + } + ] + }, + "highlight": { + "products.product_name": [ + "Shirt - white", + "Shirt - light blue denim" + ] + } + } + ] + } + } + } + ] + } + } +} +``` +
+ +## Example: Using script fields + +The following example retrieves the highest-priced order per category and computes a 15% discount using a `script_fields` definition: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "top_categories": { + "terms": { + "field": "category.keyword", + "size": 2 + }, + "aggs": { + "top_doc": { + "top_hits": { + "size": 1, + "sort": [ + { + "taxful_total_price": { + "order": "desc" + } + } + ], + "_source": { + "includes": ["customer_full_name", "taxful_total_price"] + }, + "script_fields": { + "price_with_tax_discount": { + "script": { + "source": "doc['taxful_total_price'].value * 0.85" + } + } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +
+ + Example response + + {: .text-delta} + +```json +{ + "took": 51, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "top_categories": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 3482, + "buckets": [ + { + "key": "Men's Clothing", + "doc_count": 2024, + "top_doc": { + "hits": { + "total": { + "value": 2024, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "LoN5u50BpPQaFxRehr9T", + "_score": null, + "_source": { + "customer_full_name": "Wagdi Shaw", + "taxful_total_price": 2249.92 + }, + "fields": { + "price_with_tax_discount": [ + 1912.5 + ] + }, + "sort": [ + 2250.0 + ] + } + ] + } + } + }, + { + "key": "Women's Clothing", + "doc_count": 1903, + "top_doc": { + "hits": { + "total": { + "value": 1903, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "z4N5u50BpPQaFxReicuj", + "_score": null, + "_source": { + "customer_full_name": "Elyssa Hart", + "taxful_total_price": 343.96 + }, + "fields": { + "price_with_tax_discount": [ + 292.4 + ] + }, + "sort": [ + 344.0 + ] + } + ] + } + } + } + ] + } + } +} +``` +
+ +## Response body fields + +The following table lists the response body fields returned within each `top_hits` aggregation result. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `hits.total.value` | Integer | The total number of documents matching the aggregation within the bucket. | +| `hits.total.relation` | String | Indicates whether the total is exact (`eq`) or a lower bound (`gte`). | +| `hits.max_score` | Float or Null | The highest relevance score among the returned hits. This is `null` when hits are sorted by a field other than `_score`. | +| `hits.hits` | Array | An array of the top matching documents for the bucket. | +| `hits.hits._index` | String | The index containing the document. | +| `hits.hits._id` | String | The unique identifier of the document. | +| `hits.hits._score` | Float or Null | The relevance score of the document. This is `null` when sorting by a field other than `_score`. | +| `hits.hits._source` | Object | The original document source. When source filtering is applied, only the requested fields are returned. | +| `hits.hits.sort` | Array | The sort values used to order this hit, present only when an explicit `sort` is specified. | +| `hits.hits._nested` | Object | Present only for nested hits. Contains `field` (the nested array field name) and `offset` (the zero-based position within the array). | diff --git a/_aggregations/metric/value-count.md b/_aggregations/metric/value-count.md index dfddaf94..a930ec66 100644 --- a/_aggregations/metric/value-count.md +++ b/_aggregations/metric/value-count.md @@ -2,23 +2,36 @@ layout: default title: Value count parent: Metric aggregations -grand_parent: Aggregations nav_order: 140 redirect_from: - /query-dsl/aggregations/metric/value-count/ --- -# Value count aggregations +# Value count aggregation -The `value_count` metric is a single-value metric aggregation that calculates the number of values that an aggregation is based on. +The `value_count` metric is a single-value metric aggregation that counts the number of values extracted from the aggregated documents. These values can be extracted from specific fields in the documents or generated by a script. This aggregation is often paired with aggregations like `avg` to determine how many values contributed to a computed result. -For example, you can use the `value_count` metric with the `avg` metric to find how many numbers the aggregation uses to calculate an average value. +The `value_count` aggregation does not deduplicate values. If a field contains duplicates or a script generates multiple identical values for a single document, each value is counted individually. + +## Parameters + +The `value_count` aggregation takes the following parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `field` | String | The field from which to count values. | +| `script` | Object | A script that generates values to count. Can be used instead of or with `field`. | +| `missing` | Number or String | The default value assigned to documents missing the target field. | + +## Example + +The following example counts the number of documents that contain a `taxful_total_price` value in the e-commerce index: ```json -GET opensearch_dashboards_sample_data_ecommerce/_search +GET /opensearch_dashboards_sample_data_ecommerce/_search { "size": 0, - "aggs": { + "aggs": { "number_of_values": { "value_count": { "field": "taxful_total_price" @@ -29,14 +42,94 @@ GET opensearch_dashboards_sample_data_ecommerce/_search ``` {% include copy-curl.html %} -#### Example response +The response shows that 4,675 documents contain values for the specified field: ```json -... - "aggregations" : { - "number_of_values" : { - "value" : 4675 +{ + ... + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "number_of_values": { + "value": 4675 } } } -``` \ No newline at end of file +``` + +The aggregation name (`number_of_values`) also serves as the key for retrieving the aggregation result from the response. + +### Using a script + +Instead of specifying a field, you can provide a script to generate values for counting. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). The following example uses an inline Painless script to count based on computed values: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "type_count": { + "value_count": { + "script": { + "source": "doc['taxful_total_price'].value" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response returns the count of script-generated values: + +```json +{ + ... + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "type_count": { + "value": 4675 + } + } +} +``` + +### Using a stored script + +To reuse a script across multiple queries, you can store it and reference it by ID. The following example uses a stored script that accepts a field name as a parameter: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "type_count": { + "value_count": { + "script": { + "id": "my_value_count_script", + "params": { + "field": "taxful_total_price" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Because `value_count` internally represents all values as byte sequences, using the `_value` script variable to access field values returns the value as a string rather than its native format. +{: .note} diff --git a/_aggregations/metric/weighted-avg.md b/_aggregations/metric/weighted-avg.md new file mode 100644 index 00000000..a4362565 --- /dev/null +++ b/_aggregations/metric/weighted-avg.md @@ -0,0 +1,224 @@ +--- +layout: default +title: Weighted average +parent: Metric aggregations +nav_order: 150 +has_math: true +--- + +# Weighted average aggregation + +The `weighted_avg` aggregation computes a weighted average of numeric values extracted from documents. Unlike a regular average where each data point contributes equally, a weighted average assigns different importance to each data point based on a corresponding weight value. + +The weighted average is calculated using the formula $$ \frac{\sum_{i=1}^n \text{value}_i \cdot \text{weight}_i}{\sum_{i=1}^n \text{weight}_i} $$. + +In a regular average, every data point contributes equally, which is equivalent to assigning a weight of `1` to all values. + +## Parameters + +The `weighted_avg` aggregation takes the following parameters. + +| Parameter | Required/Optional | Description | +|---------------|----------|-------------| +| `value` | Required | Defines how to obtain the numeric values to average. Requires a `field` or `script`. | +| `weight` | Required | Defines how to obtain the weight for each value. Requires a `field` or `script`. | +| `format` | Optional | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | +| `value_type` | Optional | A type hint for the values when using scripts or unmapped fields. | + +You can specify the following parameters within `value` or `weight`. + +| Parameter | Required/Optional | Description | +|------------|----------|-------------| +| `field` | Optional | The document field to use for the value or weight. | +| `missing` | Optional | A default value or weight to use when the field is missing. See [Missing values](#missing-values).| +| `script` | Optional | A script that provides the value or weight. Mutually exclusive with `field`. | + + +## Example + +First, create an index and add some data. Product C is missing the `rating` and `num_reviews` fields: + +```json +POST _bulk +{ "index": { "_index": "products" } } +{ "name": "Product A", "rating": 4.5, "num_reviews": 100 } +{ "index": { "_index": "products" } } +{ "name": "Product B", "rating": 3.8, "num_reviews": 50 } +{ "index": { "_index": "products" } } +{ "name": "Product C"} +``` +{% include copy-curl.html %} + +The following request calculates a weighted average product rating, where each product's rating is weighted by its `num_reviews`. Products with more reviews have a greater influence on the final average: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "field": "rating" + }, + "weight": { + "field": "num_reviews" + }, + "format": "#.##" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response contains the `weighted_rating`, calculated as `(4.5 * 100 + 3.8 * 50) / (100 + 50) = 4.27`. Only documents containing values for both `rating` and `num_reviews` are included in the calculation: + +```json +{ + "took": 21, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "weighted_rating": { + "value": 4.266666650772095, + "value_as_string": "4.27" + } + } +} +``` + +## Multi-valued fields + +The `value` field can contain multiple values per document, but the `weight` field must resolve to exactly one value. Documents with multiple weights cause an error. To handle multi-valued weight fields, use a `script` that reduces them to a single number. + +When a document contains multiple values, the single weight is applied to each value independently. The following example indexes a document where `rating` is a multi-valued field and then runs the aggregation: + +```json +POST /products/_doc?refresh=true +{ + "name": "Product D", + "rating": [1, 2, 3], + "num_reviews": 2 +} +``` +{% include copy-curl.html %} + +```json +GET /products/_search +{ + "size": 0, + "query": { + "term": { "name.keyword": "Product D" } + }, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "field": "rating" + }, + "weight": { + "field": "num_reviews" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The three values (`1`, `2`, and `3`) are each weighted by `2`, resulting in `((1*2) + (2*2) + (3*2)) / (2+2+2) = 2.0`: + +```json +{ + ... + "aggregations": { + "weighted_rating": { + "value": 2.0 + } + } +} +``` + +## Using a script + +You can supply scripts for the value, the weight, or both to compute derived quantities on the fly. The following example adds `1` to each rating and weight before computing the weighted average: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "script": "if (doc['rating'].size() == 0) return 0; return doc['rating'].value + 1" + }, + "weight": { + "script": "if (doc['num_reviews'].size() == 0) return 0; return doc['num_reviews'].value + 1" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Missing values + +Documents missing the `value` field are excluded from the calculation by default. Documents missing the `weight` field are still included with an implicit weight of `1`. + +The `missing` parameter overrides these defaults by specifying a substitute value for documents that lack the field. The following example assigns a default rating of `3.0` and a default review count of `1` to documents missing those fields: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "field": "rating", + "missing": 3.0 + }, + "weight": { + "field": "num_reviews", + "missing": 1 + }, + "format": "#.##" + } + } + } +} +``` +{% include copy-curl.html %} + +With the missing values applied, the weighted average is calculated as `(4.5 * 100 + 3.8 * 50 + 3.0 * 1) / (100 + 50 + 1) = 4.26`: + +```json +{ + ... + "aggregations": { + "weighted_rating": { + "value": 4.258278129906055, + "value_as_string": "4.26" + } + } +} +``` diff --git a/_aggregations/pipeline/avg-bucket.md b/_aggregations/pipeline/avg-bucket.md new file mode 100644 index 00000000..eb8cad0b --- /dev/null +++ b/_aggregations/pipeline/avg-bucket.md @@ -0,0 +1,112 @@ +--- +layout: default +title: Average bucket +parent: Pipeline aggregations +nav_order: 10 +--- + +# Average bucket aggregation + +The `avg_bucket` aggregation is a sibling aggregation that calculates the average of a metric in each bucket of a previous aggregation. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `avg_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#data-gaps).| +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of bytes for each month. Finally, the `avg_bucket` aggregation calculates the average number of bytes per month from these sums: + +```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" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns the average bytes from the monthly buckets: + +```json +{ + "took": 43, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "avg_monthly_bytes": { + "value": 26575229.666666668 + } + } +} +``` diff --git a/_aggregations/pipeline/bucket-script.md b/_aggregations/pipeline/bucket-script.md new file mode 100644 index 00000000..db5fee1c --- /dev/null +++ b/_aggregations/pipeline/bucket-script.md @@ -0,0 +1,161 @@ +--- +layout: default +title: Bucket script +parent: Pipeline aggregations +nav_order: 20 +--- + +# Bucket script aggregation + +The `bucket_script` aggregation is a parent pipeline aggregation that executes a script to perform per-bucket numeric computations across a set of buckets. Use the `bucket_script` aggregation to perform custom numeric computations on multiple metrics in a bucketed aggregation. For example, you can: + +- Calculate derived and composite metrics. +- Apply conditional logic using if/else statements. +- Compute business-specific KPIs, such as custom scoring metrics. + +## Parameters + +The `bucket_script` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | Object | A map of variable names to bucketed metrics that identify the metrics to be used in the script. The metrics must be numeric. See [Script variables](#script-variables). | +| `script` | Required | String or Object | The script to execute. Can be an inline script, stored script, or script file. The script has access to the variable names defined in the `buckets_path` parameter. Must return a numeric value. | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` parameter. | + +## Script variables + +The `buckets_path` parameter maps script variable names to metrics from parent aggregations. These variables can then be used in the script. + +For the `bucket_script` and `bucket_selector` aggregations, the `buckets_path` parameter is an object rather than a string because it must refer to multiple bucket metrics. See the [Pipeline aggregations]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path) page for a description of the string version of `buckets_path`. +{: .note} + +The following `buckets_path` maps the `sales_sum` metric to the `total_sales` script variable and the `item_count` metric to the `item_count` script variable: + +```json +"buckets_path": { + "total_sales": "sales_sum", + "item_count": "item_count" +} +``` + +The mapped variables can be accessed from the `params` context. For example: + +- `params.total_sales` +- `params.item_count` + +## Enabling inline scripting + +Use the `script` parameter to add your script. The script can be inline, in a file, or in an index. To enable inline scripting, the `opensearch.yml` file in the `config` folder must contain the following: + +```yml +script.inline: on +``` + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `total_sales` subaggregation sums the taxed price of all items sold for each month. The `vendor_count` aggregation counts the total number of unique vendors for each month. Finally, the `avg_vendor_spend` aggregation uses an inline script to calculate the average amount spent per vendor each month: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "month" + }, + "aggs": { + "total_sales": { + "sum": { + "field": "taxful_total_price" + } + }, + "vendor_count": { + "cardinality": { + "field": "products.manufacturer.keyword" + } + }, + "avg_vendor_spend": { + "bucket_script": { + "buckets_path": { + "sales": "total_sales", + "vendors": "vendor_count" + }, + "script": "params.sales / params.vendors", + "format": "$#,###.00" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns the formatted monthly average vendor spend: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 721, + "vendor_count": { + "value": 21 + }, + "total_sales": { + "value": 53468.1484375 + }, + "avg_vendor_spend": { + "value": 2546.1023065476193, + "value_as_string": "$2,546.10" + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 3954, + "vendor_count": { + "value": 21 + }, + "total_sales": { + "value": 297415.98046875 + }, + "avg_vendor_spend": { + "value": 14162.665736607143, + "value_as_string": "$14,162.67" + } + } + ] + } + } +} +``` + + + + diff --git a/_aggregations/pipeline/bucket-selector.md b/_aggregations/pipeline/bucket-selector.md new file mode 100644 index 00000000..a129b167 --- /dev/null +++ b/_aggregations/pipeline/bucket-selector.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Bucket selector +parent: Pipeline aggregations +nav_order: 30 +--- + +# Bucket selector aggregation + +The `bucket_selector` aggregation is a parent pipeline aggregation that evaluates a script to determine whether buckets returned by a `histogram` (or `date_histogram`) aggregation should be included in the final result. + +Unlike pipeline aggregations that create new values, the `bucket_selector` aggregation acts as a filter, keeping or removing entire buckets based on the specified criteria. Use this aggregation to filter buckets based on the computed metrics of a bucket. + +## Parameters + +The `bucket_selector` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | Object | A map of variable names to bucketed metrics that identify the metrics to be used in the script. The metrics must be numeric. See [Script variables]({{site.url}}{{site.baseurl}}/aggregations/pipeline/bucket-script#script-variables). | +| `script` | Required | String or Object | The script to execute. Can be an inline script, stored script, or script file. The script has access to the variable names defined in the `buckets_path` parameter. Must return a Boolean value. Buckets returning `false` are removed from the final output. | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | + + +## Example + +The following example creates a date histogram with a one-week interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all sales for each week. Finally, the `bucket_selector` aggregation filters the resulting weekly buckets, removing all the buckets that do not have a sum of more than $75,000: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "sales_per_week": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "weekly_sales": { + "sum": { + "field": "taxful_total_price", + "format": "$#,###.00" + } + }, + "avg_vendor_spend": { + "bucket_selector": { + "buckets_path": { + "weekly_sales": "weekly_sales" + }, + "script": "params.weekly_sales > 75000" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns the `sales_per_week` buckets that meet the scripted criterion: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_week": { + "buckets": [ + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "weekly_sales": { + "value": 79448.60546875, + "value_as_string": "$79,448.61" + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "weekly_sales": { + "value": 78208.4296875, + "value_as_string": "$78,208.43" + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "weekly_sales": { + "value": 81277.296875, + "value_as_string": "$81,277.30" + } + } + ] + } + } +} +``` + +Because it returns a Boolean rather than a numeric value, the `buckets_selector` aggregation does not take a `format` parameter. In this example, the formatted metrics are returned in the `value_as_string` result by the `sum` subaggregation. Contrast this with the [example in the `bucket_script` aggregation]({{site.url}}{{site.baseurl}}/aggregations/pipeline/bucket-script/#example). +{: .note} \ No newline at end of file diff --git a/_aggregations/pipeline/bucket-sort.md b/_aggregations/pipeline/bucket-sort.md new file mode 100644 index 00000000..ec0291e0 --- /dev/null +++ b/_aggregations/pipeline/bucket-sort.md @@ -0,0 +1,229 @@ +--- +layout: default +title: Bucket sort +parent: Pipeline aggregations +nav_order: 40 +--- + +# Bucket sort aggregation + +The `bucket_sort` aggregation is a parent aggregation that sorts or truncates the buckets produced by its parent multi-bucket aggregation. + +In `bucket_sort` aggregations, you can sort buckets by multiple fields, each with its own sort order. Buckets can be sorted by their key, document count, or values from subaggregations. You can also use the `from` and `size` parameters to truncate the results, with or without sorting. + +For information about specifying sort order, see [Sort results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/). + +## Parameters + +The `bucket_sort` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | +| `sort` | Optional | String | A list of fields by which to sort. See [Sort results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/). | +| `from` | Optional | String | The index of the first result to return. Must be a non-negative integer. Default is `0`. See [The `from` and `size` parameters]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-from-and-size-parameters). | +| `size` | Optional | String | The maximum number of results to return. Must be a positive integer. See [The `from` and `size` parameters]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-from-and-size-parameters).| + +You must supply at least one of `sort`, `from`, and `size`. +{: .note} + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the aggregation sorts the buckets in descending order by number of bytes: + +```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" } } + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation reorders the buckets in descending order by total number of bytes: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 7072, + "total_bytes": { + "value": 40124337 + } + }, + { + "key_as_string": "2025-06-01T00:00:00.000Z", + "key": 1748736000000, + "doc_count": 6056, + "total_bytes": { + "value": 34123131 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 946, + "total_bytes": { + "value": 5478221 + } + } + ] + } + } +} +``` + +## Example: Truncating the results + +To truncate the results, provide the `from` and/or `size` parameters. The following example performs the same sort but returns two buckets, starting with the second bucket: + +```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" } } + ], + "from": 1, + "size": 2 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The aggregation returns the two sorted buckets: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-06-01T00:00:00.000Z", + "key": 1748736000000, + "doc_count": 6056, + "total_bytes": { + "value": 34123131 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 946, + "total_bytes": { + "value": 5478221 + } + } + ] + } + } +} +``` + +To truncate results without sorting, omit the `sort` parameter: + +```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": { + "from": 1, + "size": 2 + } + } + } + } + } +} +``` +{% include copy-curl.html %} \ No newline at end of file diff --git a/_aggregations/pipeline/cumulative-sum.md b/_aggregations/pipeline/cumulative-sum.md new file mode 100644 index 00000000..964aafef --- /dev/null +++ b/_aggregations/pipeline/cumulative-sum.md @@ -0,0 +1,117 @@ +--- +layout: default +title: Cumulative sum +parent: Pipeline aggregations +has_children: false +nav_order: 60 +--- + +# Cumulative sum aggregation + +The `cumulative_sum` aggregation is a parent aggregation that calculates the cumulative sum across the buckets of a previous aggregation. + +A cumulative sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence `{a,b,c,…}` are `a`, `a+b`, `a+b+c`, and so on. You can use the cumulative sum to visualize the rate of change of a field over time. + +## Parameters + +The `cumulative_sum` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the `cumulative_sum` aggregation calculates the cumulative number of bytes for each month's bucket: + +```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" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "no-of-bytes": { + "value": 2804103 + }, + "cumulative_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "no-of-bytes": { + "value": 39103067 + }, + "cumulative_bytes": { + "value": 41907170 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "no-of-bytes": { + "value": 37818519 + }, + "cumulative_bytes": { + "value": 79725689 + } + } + ] + } + } +} +``` diff --git a/_aggregations/pipeline/derivative.md b/_aggregations/pipeline/derivative.md new file mode 100644 index 00000000..c26a2b9f --- /dev/null +++ b/_aggregations/pipeline/derivative.md @@ -0,0 +1,218 @@ +--- +layout: default +title: Derivative +parent: Pipeline aggregations +nav_order: 70 +--- + +# Derivative aggregation + +The `derivative` aggregation is a parent aggregation used to calculate first-order and second-order derivatives of each bucket of an aggregation. "First-order derivative" and "second-order derivative" are often shortened to "first derivative" and "second derivative," respectively. This page uses the shortened terms. + +For an ordered series of buckets, `derivative` approximates a first derivative as the difference between metric values in the current and previous buckets. + +## Parameters + +The `derivative` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index/#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + +## Example: First derivative + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the `derivative` aggregation calculates the first derivative of the `sum` subaggregation. The first derivative is estimated as the difference between the number of bytes in the current month and the previous month: + +```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" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response: First derivative + +The response shows derivatives computed for the second and third buckets: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "number_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "number_of_bytes": { + "value": 39103067 + }, + "bytes_deriv": { + "value": 36298964 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "number_of_bytes": { + "value": 37818519 + }, + "bytes_deriv": { + "value": -1284548 + } + } + ] + } + } +} +``` + +No derivative is calculated for the first bucket because no previous bucket is available for that bucket. + +## Example: Second derivative + +To calculate a second derivative, chain one derivative aggregation to another: + +```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_1st_deriv": { + "derivative": { + "buckets_path": "number_of_bytes" + } + }, + "bytes_2nd_deriv": { + "derivative": { + "buckets_path": "bytes_1st_deriv" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response: Second derivative + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "number_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "number_of_bytes": { + "value": 39103067 + }, + "bytes_1st_deriv": { + "value": 36298964 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "number_of_bytes": { + "value": 37818519 + }, + "bytes_1st_deriv": { + "value": -1284548 + }, + "bytes_2nd_deriv": { + "value": -37583512 + } + } + ] + } + } +} +``` + +No first derivative is calculated for the first bucket because no previous bucket is available for that bucket. Similarly, no second derivative is calculated for the first or second buckets. diff --git a/_aggregations/pipeline/extended-stats.md b/_aggregations/pipeline/extended-stats.md new file mode 100644 index 00000000..eeb1f66b --- /dev/null +++ b/_aggregations/pipeline/extended-stats.md @@ -0,0 +1,179 @@ +--- +layout: default +title: Extended stats bucket +parent: Pipeline aggregations +nav_order: 80 +--- + +# Extended stats bucket aggregation + +The `extended_stats_bucket` aggregation is a more comprehensive version of the [`stats_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/stats-bucket/) sibling aggregation. As well as the basic statistical measures provided by `stats_bucket`, `extended_stats_bucket` calculates the following metrics: + +- Sum of squares +- Variance +- Population variance +- Sampling variance +- Standard deviation +- Population standard deviation +- Sampling standard deviation +- Standard deviation bounds: + - Upper + - Lower + - Population upper + - Population lower + - Sampling upper + - Sampling lower + +The standard deviation and variance are population statistics; they are always equal to the population standard deviation and variance, respectively. + +The `std_deviation_bounds` object defines a range that spans the specified number of standard deviations above and below the mean (default is two standard deviations). This object is always included in the output but is meaningful only for normally distributed data. Before interpreting these values, verify that your dataset follows a normal distribution. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `extended_stats_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps).| +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `_as_string` property. | +| `sigma` | Optional | Double (non-negative) | The number of standard deviations above and below the mean used to calculate the `std_deviation_bounds` interval. Default is `2`. See [Defining bounds]({{site.url}}{{site.baseurl}}/aggregations/metric/extended-stats#defining-bounds) in `extended_stats`. | + +## Example + +The following example creates a date histogram with a one-month interval using the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the `extended_stats_bucket` aggregation returns the extended stats for these sums: + +```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": { + "extended_stats_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes", + "sigma": 3, + "format": "0.##E0" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response contains extended stats for the selected buckets. Note that the standard deviation bounds are for a three-sigma range; changing `sigma` (or letting it default to `2`) returns different results: + +
+ + Response + + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "stats_monthly_bytes": { + "count": 3, + "min": 2804103, + "max": 39103067, + "avg": 26575229.666666668, + "sum": 79725689, + "min_as_string": "2.8E6", + "max_as_string": "3.91E7", + "avg_as_string": "2.66E7", + "sum_as_string": "7.97E7", + "sum_of_squares": 2967153221794459, + "variance": 282808242095406.25, + "variance_population": 282808242095406.25, + "variance_sampling": 424212363143109.4, + "std_deviation": 16816903.46334325, + "std_deviation_population": 16816903.46334325, + "std_deviation_sampling": 20596416.2694171, + "std_deviation_bounds": { + "upper": 77025940.05669643, + "lower": -23875480.72336309, + "upper_population": 77025940.05669643, + "lower_population": -23875480.72336309, + "upper_sampling": 88364478.47491796, + "lower_sampling": -35214019.141584635 + }, + "sum_of_squares_as_string": "2.97E15", + "variance_as_string": "2.83E14", + "variance_population_as_string": "2.83E14", + "variance_sampling_as_string": "4.24E14", + "std_deviation_as_string": "1.68E7", + "std_deviation_population_as_string": "1.68E7", + "std_deviation_sampling_as_string": "2.06E7", + "std_deviation_bounds_as_string": { + "upper": "7.7E7", + "lower": "-2.39E7", + "upper_population": "7.7E7", + "lower_population": "-2.39E7", + "upper_sampling": "8.84E7", + "lower_sampling": "-3.52E7" + } + } + } +} +``` + +
diff --git a/_aggregations/pipeline/index.md b/_aggregations/pipeline/index.md new file mode 100644 index 00000000..9f797863 --- /dev/null +++ b/_aggregations/pipeline/index.md @@ -0,0 +1,250 @@ +--- +layout: default +title: Pipeline aggregations +nav_order: 5 +has_children: true +has_toc: false +redirect_from: + - /opensearch/pipeline-agg/ + - /query-dsl/aggregations/pipeline-agg/ + - /aggregations/pipeline/ + - /aggregations/pipeline-agg/ +--- + +# Pipeline aggregations + +Pipeline aggregations chain together multiple aggregations by using the output of one aggregation as the input for another. They compute complex statistical and mathematical measures like derivatives, moving averages, and cumulative sums. Some pipeline aggregations duplicate the functionality of metric and bucket aggregations but, in many cases, are more intuitive to use. + +Pipeline aggregations are executed after all other sibling aggregations. This has performance implications. For example, using the `bucket_selector` pipeline aggregation to narrow a list of buckets does not reduce the number of computations performed on omitted buckets. +{: .note} + +Pipeline aggregations cannot be sub-aggregated but can be chained to other pipeline aggregations. For example, you can calculate a second derivative by chaining two consecutive `derivative` aggregations. Keep in mind that pipeline aggregations append to existing output. For example, computing a second derivative by chaining `derivative` aggregations outputs both the first and second derivatives. + +## Pipeline aggregation types + +Pipeline aggregations are of two types: [sibling](#sibling-aggregations) and [parent](#parent-aggregations). + +### Sibling aggregations + +A _sibling_ pipeline aggregation takes the output of a nested aggregation and produces new buckets or new aggregations at the same level as the nested buckets. + +A sibling aggregation must be a multi-bucket aggregation (have multiple grouped values for a certain field), and the metric must be a numeric value. + +### Parent aggregations + +A _parent_ aggregation takes the output of an outer aggregation and produces new buckets or new aggregations at the same level as the existing buckets. Unlike sibling pipeline aggregations, which operate across all buckets and produce a single output, parent pipeline aggregations process each bucket individually and write the result back into each bucket. + +The specified metric for a parent aggregation must be a numeric value. + +We strongly recommend setting `min_doc_count` to `0` (the default for `histogram` aggregations) for parent aggregations. If `min_doc_count` is greater than `0`, then the aggregation omits buckets, which might lead to incorrect results. +{: .important} + +## Supported pipeline aggregations + +OpenSearch supports the following pipeline aggregations. + +| Name | Type | Description | +|------|------|-------------| +| [`avg_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/avg-bucket/) | Sibling | Calculates the average of a metric in each bucket of a previous aggregation. | +| [`bucket_script`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/bucket-script/) | Parent | Executes a script to perform per-bucket numeric computations across a set of buckets. | +| [`bucket_selector`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/bucket-selector/) | Parent | Evaluates a script to determine whether buckets returned by a `histogram` (or `date_histogram`) aggregation should be included in the final result. | +| [`bucket_sort`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/bucket-selector/) | Parent | Sorts or truncates the buckets produced by its parent multi-bucket aggregation. | +| [`cumulative_sum`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/cumulative-sum/) | Parent | Calculates the cumulative sum across the buckets of a previous aggregation. | +| [`derivative`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/derivative/) | Parent | Calculates first-order and second-order derivatives of each bucket of an aggregation. | +| [`extended_stats`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/extended-stats/) | Sibling | A more comprehensive version of the `stats_bucket` aggregation that provides additional metrics. | +| [`max_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/max-bucket/) | Sibling | Calculates the maximum of a metric in each bucket of a previous aggregation. | +| [`min_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/min-bucket/) | Sibling | Calculates the minimum of a metric in each bucket of a previous aggregation. | +| [`moving_avg`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/moving-avg/) *(Deprecated)* | Parent | Calculates a sequence of averages of a metric contained in windows (adjacent subsets) of an ordered dataset. | +| [`moving_fn`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/moving-function/) | Parent | Executes a script over a sliding window. | +| [`percentiles_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/percentiles-bucket/) | Sibling | Calculates the percentile placement of bucketed metrics. | +| [`serial_diff`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/serial-diff/) | Parent | Calculates the difference between metric values in the current bucket and a previous bucket. It stores the result in the current bucket. | +| [`stats_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/stats-bucket/) | Sibling | Returns a variety of stats (`count`, `min`, `max`, `avg`, and `sum`) for the buckets of a previous aggregation. | +| [`sum_bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/sum-bucket/) | Sibling | Calculates the sum of a metric in each bucket of a previous aggregation. | + + +## Buckets path + +A pipeline aggregation uses the `buckets_path` parameter to reference the output of other aggregations. +The `buckets_path` parameter has the following syntax: + +```r +buckets_path = [ > ... ][ . ] +``` + +This syntax uses the following elements. + +| Element | Description | +| :-- | :-- | +| `` | The name of the aggregation. | +| `>` | A child selector used to navigate from one aggregation (parent) to another nested aggregation (child). | +| `.` | Specifies a metric to retrieve from a multi-value aggregation. Required only if the target aggregation produces multiple metrics. | + +To visualize the buckets path, suppose you have the following aggregation structure: + +```json +"aggs": { + "parent_agg": { + "terms": { + "field": "category" + }, + "aggs": { + "child_agg": { + "stats": { + "field": "price" + } + } + } + } +} +``` + +To reference the average price from the `child_agg`, which is nested in the `parent_agg`, use `parent_agg>child_agg.avg`. + +Examples: + +- `my_sum.sum`: Refers to the sum metric from the `my_sum` aggregation. + +- `popular_tags>my_sum.sum`: Refers to the `sum` metric from the `my_sum` aggregation, which is nested under the `popular_tags` aggregation. + +For multi-value metric aggregations like `stats` or `percentiles`, you must include the metric name (for example, `.min`) in the path. For single-value metrics like `sum` or `avg`, the metric name is optional if unambiguous. +{: .tip} + + +### Buckets path example + +The following example operates on the OpenSearch Dashboards logs sample data. It creates a histogram of values in the `bytes` field, sums the `phpmemory` fields in each histogram bucket, and finally sums the buckets using the `sum_bucket` pipeline aggregation. The `buckets_path` follows the `number_of_bytes>sum_total_memory ` path from the `number_of_bytes` parent aggregation to the `sum_total_memory` subaggregation: + +```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" + } + } + } +} +``` +{% include copy-curl.html %} + +Note that the `buckets_path` contains the names of the component aggregations. Paths are directed, meaning that they cascade one way, downward from parents to children. + +The pipeline aggregation returns the total memory summed from all the buckets: + +```json +{ + ... + "aggregations": { + "number_of_bytes": { + "buckets": [ + { + "key": 0, + "doc_count": 13372, + "sum_total_memory": { + "value": 91266400 + } + }, + { + "key": 10000, + "doc_count": 702, + "sum_total_memory": { + "value": 0 + } + } + ] + }, + "sum_copies": { + "value": 91266400 + } + } +} +``` + +### Count paths + +You can direct the `buckets_path` to use a count rather than a value as its input. To do so, use the `_count` buckets path variable. + +The following example computes basic stats on a histogram of the number of bytes from the OpenSearch Dashboards logs sample data. It creates a histogram of values in the `bytes` field and then computes the stats on the counts in the histogram buckets. + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "number_of_bytes": { + "histogram": { + "field": "bytes", + "interval": 10000 + } + }, + "count_stats": { + "stats_bucket": { + "buckets_path": "number_of_bytes>_count" + } + } + } +} +``` +{% include copy-curl.html %} + +The results show stats about the *document counts* of the buckets: + +```json +{ +... + "aggregations": { + "number_of_bytes": { + "buckets": [ + { + "key": 0, + "doc_count": 13372 + }, + { + "key": 10000, + "doc_count": 702 + } + ] + }, + "count_stats": { + "count": 2, + "min": 702, + "max": 13372, + "avg": 7037, + "sum": 14074 + } + } +} +``` + +## Data gaps + +Real-world data can be missing from nested aggregations for a number of reasons, including: + +- Missing values in documents. +- Empty buckets anywhere in the chain of aggregations. +- Missing data needed to calculate a bucket value (for example, rolling functions such as `derivative` require one or more previous values to start). + +You can specify a policy to handle missing data using the `gap_policy` property: either skip the missing data or replace the missing data with zeros. + +The `gap_policy` parameter is valid for all pipeline aggregations. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + diff --git a/_aggregations/pipeline/max-bucket.md b/_aggregations/pipeline/max-bucket.md new file mode 100644 index 00000000..86908942 --- /dev/null +++ b/_aggregations/pipeline/max-bucket.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Maximum bucket +parent: Pipeline aggregations +nav_order: 100 +--- + +# Maximum bucket aggregation + +The `max_bucket` aggregation is a sibling aggregation that calculates the maximum of a metric in each bucket of a previous aggregation. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `max_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#data-gaps).| +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of bytes for each month. Finally, the `max_bucket` aggregation finds the maximum---the largest of these buckets: + +```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" + } + } + } + }, + "max_monthly_bytes": { + "max_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The `max_bucket` aggregation returns the maximum value from a specified metric across multiple buckets. In this example, it calculates the maximum number of bytes per month from the `sum_of_bytes` metric inside `visits_per_month`. The `value` field shows the maximum value found across all buckets. The `keys` array contains the keys of the buckets in which this maximum value was observed. It's an array because more than one bucket can have the same maximum value. In such cases, all matching bucket keys are included. This ensures that the result is accurate even if multiple time periods (or terms) have the same maximum value: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "max_monthly_bytes": { + "value": 39103067, + "keys": [ + "2025-04-01T00:00:00.000Z" + ] + } + } +} +``` + diff --git a/_aggregations/pipeline/min-bucket.md b/_aggregations/pipeline/min-bucket.md new file mode 100644 index 00000000..dcc72f88 --- /dev/null +++ b/_aggregations/pipeline/min-bucket.md @@ -0,0 +1,117 @@ +--- +layout: default +title: Minimum bucket +parent: Pipeline aggregations +nav_order: 110 +--- + +# Minimum bucket aggregation + +The `min_bucket` aggregation is a sibling aggregation that calculates the minimum of a metric in each bucket of a previous aggregation. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `min_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#data-gaps).| +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of bytes for each month. Finally, the `min_bucket` aggregation finds the minimum---the smallest of these buckets: + +```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" + } + } + } + }, + "min_monthly_bytes": { + "min_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The `max_bucket` aggregation returns the minimum value from a specified metric across multiple buckets. In this example, it calculates the minimum number of bytes per month from the `sum_of_bytes` metric inside `visits_per_month`. The `value` field shows the minimum value found across all buckets. The `keys` array contains the keys of the buckets in which this minimum value was observed. It's an array because more than one bucket can have the same minimum value. In such cases, all matching bucket keys are included. This ensures that the result is accurate even if multiple time periods (or terms) have the same minimum value: + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "min_monthly_bytes": { + "value": 2804103, + "keys": [ + "2025-03-01T00:00:00.000Z" + ] + } + } +} +``` + + diff --git a/_aggregations/pipeline/moving-avg.md b/_aggregations/pipeline/moving-avg.md new file mode 100644 index 00000000..e8b7d0c4 --- /dev/null +++ b/_aggregations/pipeline/moving-avg.md @@ -0,0 +1,570 @@ +--- +layout: default +title: Moving average +parent: Pipeline aggregations +nav_order: 120 +--- + +# Moving average aggregation +**Deprecated** +{: .label .label-red } + +The `moving_avg` aggregation has been deprecated in favor of the `moving_fn` aggregation. +{: .important} + +A `moving_avg` aggregation is a parent pipeline aggregation that calculates a sequence of averages of a metric contained in windows (adjacent subsets) of an ordered dataset. + +To create a `moving_avg` aggregation, you first create a `histogram` or `date_histogram` aggregation. Optionally, you then embed a metric aggregation in the histogram aggregation. Finally, you embed the `moving_avg` aggregation in the histogram and set the `buckets_path` parameter to the embedded metric that you want to track. + +A window's size is the number of sequential data values in the window. During each iteration, the algorithm calculates the average for all data points in the window and then slides forward one data value, excluding the first value of the previous window and including the first value of the next window. + +For example, given the data `[1, 5, 8, 23, 34, 28, 7, 23, 20, 19]`, a moving average with a window size of 5 is as follows: + +``` +(1 + 5 + 8 + 23 + 34) / 5 = 14.2 +(5 + 8 + 23 + 34 + 28) / 5 = 19.6 +(8 + 23 + 34 + 28 + 7) / 5 = 20 +and so on ... +``` + +The `moving_avg` aggregation is typically applied to time-series data to smooth out noise or short-term fluctuations and to identify trends. +Specify a small window size to smooth out small-scale fluctuations. Specify a larger window size to smooth out high-frequency fluctuations or random noise, making lower-frequency trends more visible. + +For more information about moving averages, see [Wikipedia](https://en.wikipedia.org/wiki/Moving_average). + +## Parameters + +The `moving_avg` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | +| `window` | Optional | Numerical | The number of data points contained in the window. Default is `5`. | +| `model` | Optional | String | The weighted moving average model to use. Options are `ewma`, `holt`, `holt_winters`, `linear`, and `simple`. Default is `simple`. See [Models](#models). | +| `settings` | Optional | Object | The parameters for adjusting the window. See [Models](#models). | +| `predict` | Optional | Numerical | The number of predicted values to append to the end of the result. Default is `0`. | + + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards logs sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the `moving_avg` aggregation calculates the moving average of bytes per month from these sums: + +```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" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns the `moving_avg` value starting from the second bucket. The first bucket does not have a moving average value because there aren't enough previous data points to calculate it: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + }, + "moving_avg_of_sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + }, + "moving_avg_of_sum_of_bytes": { + "value": 20953585 + } + } + ] + } + } +} +``` + + +## Example: Prediction + +You can use the `moving_avg` aggregation to predict future buckets. + +The following example reduces the interval of the previous example to one week and appends five predicted one-week buckets to the end of the response: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "week" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "predict": 5 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response includes the five predictions. Note that the `doc_count` for the predicted buckets is `0`: + +
+ + Response + + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "sum_of_bytes": { + "value": 9213161 + }, + "moving_avg_of_sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9188671 + }, + "moving_avg_of_sum_of_bytes": { + "value": 5372327 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9244851 + }, + "moving_avg_of_sum_of_bytes": { + "value": 6644441.666666667 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "sum_of_bytes": { + "value": 9061045 + }, + "moving_avg_of_sum_of_bytes": { + "value": 7294544 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "sum_of_bytes": { + "value": 8713507 + }, + "moving_avg_of_sum_of_bytes": { + "value": 7647844.2 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "sum_of_bytes": { + "value": 9544718 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9084247 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9155820 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9150558.4 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9025078 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9143988.2 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "sum_of_bytes": { + "value": 5047345 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9100033.6 + } + }, + { + "key_as_string": "2025-06-02T00:00:00.000Z", + "key": 1748822400000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-09T00:00:00.000Z", + "key": 1749427200000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-16T00:00:00.000Z", + "key": 1750032000000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-23T00:00:00.000Z", + "key": 1750636800000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-30T00:00:00.000Z", + "key": 1751241600000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + } + ] + } + } +} +``` +
+ +## Models + +The `moving_avg` aggregation supports five models that differ in how they weight values in the moving window. + +Use the `model` parameter to specify which model to use. + +| Model | Model keyword | Weighting | +|-------|---------------|-------------| +| Simple | `simple` | An unweighted mean of all values in the window. | +| Linear | `linear` | Uses a linear decay of weights, giving more importance to recent values. | +| Exponentially Weighted Moving Average | `ewma` | Uses exponentially decreasing weights, giving more importance to recent values. | +| Holt | `holt` | Uses a second exponential term to smooth long-term trends. | +| Holt-Winters | `holt_winters` | Uses a third exponential term to smooth periodic (seasonal) effects. | + +Use the `settings` object to set the model's properties. The following table shows the available settings for each model. + +| Model | Parameter | Allowed values | Default | Description | +| :-- | :-- | :-- | :-- | :-- | +| `simple` | None | Numeric array | None | The arithmetic mean of all values in the window. | +| `linear` | None | Numeric array | None | The weighted average of all values in the window, with more recent values weighted more heavily.| +| `ewma` | `alpha` | [0, 1] | 0.3 | The decay parameter. Higher values give more weight to recent data points. | +| `holt` | `alpha` | [0, 1] | 0.3 | The decay parameter for the level component. | +| | `beta` | [0, 1] | 0.1 | The decay parameter for the trend component.| +| `holt_winters` | `alpha` | [0, 1] | 0.3 | The decay parameter for the level component. | +| | `beta` | [0, 1] | 0.3 | The decay parameter for the trend component. | +| | `gamma` | [0, 1] | 0.3 | The decay parameter for the seasonal component. | +| | `type` | `add`, `mult` | `add` | Defines how seasonality is modeled: additive or multiplicative. | +| | `period` | Integer | 1 | The number of buckets comprising the period. | +| | `pad` | Boolean | `true` | Whether to add a small offset to `0` values for `mult` type models to avoid a divide-by-zero error. | + + +For a discussion of these models and their parameters, see [Wikipedia](https://en.wikipedia.org/wiki/Moving_average). + + +### Example: Holt model + +The `holt` model computes weights with exponential decay controlled by the `alpha` and `beta` parameters. + +The following request calculates a moving average of total weekly byte data using a Holt model with a `window` size of `6`, an `alpha` value of `0.4`, and a `beta` value of `0.2`: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "week" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "window": 6, + "model": "holt", + "settings": { "alpha": 0.4, "beta": 0.2 } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The moving average begins with the second bucket: + +
+ + Response + + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "sum_of_bytes": { + "value": 9213161 + }, + "moving_avg_of_sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9188671 + }, + "moving_avg_of_sum_of_bytes": { + "value": 4604160.2 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9244851 + }, + "moving_avg_of_sum_of_bytes": { + "value": 6806684.584000001 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "sum_of_bytes": { + "value": 9061045 + }, + "moving_avg_of_sum_of_bytes": { + "value": 8341230.127680001 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "sum_of_bytes": { + "value": 8713507 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9260724.7236736 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "sum_of_bytes": { + "value": 9544718 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9657431.903375873 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9155820 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9173999.55240704 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9025078 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9172040.511275519 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "sum_of_bytes": { + "value": 5047345 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9108804.964619776 + } + } + ] + } + } +} +``` +
diff --git a/_aggregations/pipeline/moving-function.md b/_aggregations/pipeline/moving-function.md new file mode 100644 index 00000000..b6f56244 --- /dev/null +++ b/_aggregations/pipeline/moving-function.md @@ -0,0 +1,613 @@ +--- +layout: default +title: Moving function +parent: Pipeline aggregations +nav_order: 130 +--- + +# Moving function aggregation + +The `moving_fn` aggregation is a parent pipeline aggregation that executes a script over a sliding window. The sliding window moves over a sequence of values extracted from a parent `histogram` or `date histogram` aggregation. The window shifts left to right one bucket at a time; `moving_fn` runs the script each time the window shifts. + +Use the `moving_fn` aggregation to script any numeric calculation on data within the sliding window. You can use `moving_fn` for the following purposes: + +- Trend analysis +- Outlier detection +- Custom time-series analysis +- Custom smoothing algorithms +- Digital signal processing (DSP) + + +## Parameters + +The `moving_fn` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets containing the metric values to process. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `script` | Required | String or Object | The script that calculates a value for each window of data. Can be an inline script, stored script, or script file. The script has access to the variable names defined in the `buckets_path` parameter. | +| `window` | Required | Integer | The number of buckets in the sliding window. Must be a positive integer. | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | +| `shift` | Optional | Integer | The number of buckets by which to shift the window. Can be positive (shift right toward future buckets) or negative (toward past buckets). Default is `0`, which places the window immediately to the left of the current bucket. See [Shifting the window](#shifting-the-window). | + + +## How moving function works + +The `moving_fn` aggregation operates on a sliding window over an ordered sequence of buckets. Starting at the first bucket in the parent aggregation, `moving_fn` does the following: + +1. Collects the subsequence (window) of values from the buckets specified by the `window` and `shift` parameters. +2. Passes these values as an array to the function specified by `script`. +3. Uses `script` to compute a single value from the array. +4. Returns this value as the result for the current bucket. +5. Moves forward one bucket and repeats this process. + +"Past" and "future" values imply time-series data, the most common use case for moving window functions. More generally, they refer to previous and upcoming values, respectively, in any ordered data sequence. +{: .note} + +The script applied by `moving_fn` can be a [predefined function](#predefined-functions) or a [custom script](#custom-scripts). Bucket values are provided to the script in the `values` array. The script returns a double value as the result. The result values `NaN` and `+/- Inf` are allowed, but `null` is not. + + +### Window size + +The `window` parameter specifies the number of buckets that define the size of the window. + +The array passed to the `script` function is zero-indexed. Its values are accessed within the script as `values[0]` to `values[n]`, where `n = values.length - 1`. + + +### Shifting the window + +The `shift` parameter controls where the moving window is located relative to the current bucket. Set `shift` based on whether your analysis requires historical context, current data, or future prediction. The default is `0`, which shows only past values (excluding the current bucket). + +Some commonly used values of `shift` are as follows: + +| `shift` | Window description | | +| :-- | :-- | :-- | +| `0` | Only past values. Excludes the current value. | `--[-----]x----` | +| `1` | Past values, including the current value. | `--[----x]-----` | +| `window/2` | Centers the window around the current value. | `--[--x--]-----` | +| `window` | Future values, including the current value. | `--[x----]-----` | + +When a window extends beyond available data at the beginning or end of a sequence, `window` shrinks automatically to use only the available points: + +``` +[x----]-- +-[x----]- +--[x----] +---[x---] +----[x--] +-----[x-] +------[x] +``` + + +## Predefined functions + +The `moving_fn` aggregation supports a number of predefined functions that can be used instead of a custom script. The functions are accessible from the `MovingFunctions` context. For example, you can access the `max` function as `MovingFunctions.max(values)`. + +The following table describes the predefined functions. + +| Function | Model keyword | Description | +|:-- | :-- |:-- | +| Max | `max` | The maximum value in the window. | +| Min | `min` | The minimum value in the window. | +| Sum | `sum` | The sum of values in the window. | +| Unweighted average | `unweightedAvg` | An unweighted mean of all values in the window, equal to `sum` / `window`. | +| Linear weighted average | `linearWeightedAvg` | A weighted average using a linear decay of weights, giving more importance to recent values. | +| Exponentially Weighted Moving Average | `ewma` | A weighted average using exponentially decaying weights, giving more importance to recent values. | +| Holt | `holt` | A weighted average using a second exponential term to smooth long-term trends. | +| Holt-Winters | `holt_wimnters` | A weighted average using a third exponential term to smooth periodic (seasonal) effects. | +| Standard deviation | `stdDev` | The sum of values in the window. | + +All of the predefined functions take the `values` array as their first parameter. For functions that take extra parameters, pass these parameters in order after `values`. For example, call the `stdDev` function by setting the `script` value to `MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))`. + +The following table shows the settings required for each model. + +| Function | Extra parameters | Allowed values | Default | Description | +| :-- | :-- | :-- | :-- | :-- | +| `max` | None | Numeric array | None | The maximum value of the window. | +| `min` | None | Numeric array | None | The minimum value of the window. | +| `sum` | None | Numeric array | None | The sum of all values in the window. | +| `unweightedAvg` | None | Numeric array | None | The arithmetic mean of all values in the window. | +| `linearWeightedAvg` | None | Numeric array | None | The weighted average of all values in the window, with more recent values weighted more heavily.| +| `ewma` | `alpha` | [0, 1] | 0.3 | The decay parameter. Higher values give more weight to recent data points. | +| `holt` | `alpha` | [0, 1] | 0.3 | The decay parameter for the level component. | +| | `beta` | [0, 1] | 0.1 | The decay parameter for the trend component.| +| `holt_winters` | `alpha` | [0, 1] | 0.3 | The decay parameter for the level component. | +| | `beta` | [0, 1] | 0.3 | The decay parameter for the trend component. | +| | `gamma` | [0, 1] | 0.3 | The decay parameter for the seasonal component. | +| | `type` | `add`, `mult` | `add` | Defines how seasonality is modeled: additive or multiplicative. | +| | `period` | Integer | 1 | The number of buckets comprising the period. | +| | `pad` | Boolean | true | Whether to add a small offset to `0` values for `mult` type models to avoid a divide-by-zero error. | +| `stdDev` | `avg` | Any double | None | The standard deviation of the window. To compute a meaningful standard deviation, use the mean of the sliding window array, typically, `MovingFunctions.unweightedAvg(values)`. | + +The predefined functions do not support function signatures with missing parameters. You therefore must supply the extra parameters, even if using the default values. +{: .important} + + +### Example: Predefined functions + +The following example creates a date histogram with a one-week interval from the OpenSearch Dashboards logs sample data. The `sum` subaggregation calculates the sum of all bytes logged for each week. Finally, the `moving_fn` aggregation calculates the standard deviation of the byte sum using a `window` size of `5`, the default `shift` of `0`, and unweighted means: + +```json +POST /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histo": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "week" + }, + "aggs": { + "the_sum": { + "sum": { "field": "bytes" } + }, + "the_movavg": { + "moving_fn": { + "buckets_path": "the_sum", + "window": 5, + "script": "MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response shows the standard deviation of the moving window starting with a zero value in the second bucket. The `stdDev` function returns `0` for windows that are empty or contain only invalid values (`null` or `NaN`): + +
+ + Response + + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histo": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "the_sum": { + "value": 1531493 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "the_sum": { + "value": 9213161 + }, + "the_movavg": { + "value": 0 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "the_sum": { + "value": 9188671 + }, + "the_movavg": { + "value": 3840834 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "the_sum": { + "value": 9244851 + }, + "the_movavg": { + "value": 3615414.498228507 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "the_sum": { + "value": 9061045 + }, + "the_movavg": { + "value": 3327358.65618917 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "the_sum": { + "value": 8713507 + }, + "the_movavg": { + "value": 3058812.9440705855 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "the_sum": { + "value": 9544718 + }, + "the_movavg": { + "value": 195603.33146038183 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "the_sum": { + "value": 9155820 + }, + "the_movavg": { + "value": 270085.92336040025 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "the_sum": { + "value": 9025078 + }, + "the_movavg": { + "value": 269477.75659701484 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "the_sum": { + "value": 5047345 + }, + "the_movavg": { + "value": 267356.5422566652 + } + } + ] + } + } +} +``` +
+ + +## Custom scripts + +You can supply an arbitrary custom script to calculate `moving_fn` results. Custom scripts use the Painless scripting language. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +### Example: Custom scripts + +The following example creates a date histogram with a one-week interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all taxed revenue for each week. The `moving_fn` script then returns the greater of the two values previous to the current value or `NaN` if two values are not available: + +```json +POST /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "my_date_histo": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "the_sum": { + "sum": { "field": "taxful_total_price" } + }, + "the_movavg": { + "moving_fn": { + "buckets_path": "the_sum", + "window": 2, + "script": "return (values.length < 2 ? Double.NaN : (values[0]>values[1] ? values[0] : values[1]))" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The example returns the results of the calculation starting in bucket three, where enough previous data exists to perform the calculation: + +
+ + Response + + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histo": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 582, + "the_sum": { + "value": 41455.5390625 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "the_sum": { + "value": 79448.60546875 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "the_sum": { + "value": 78208.4296875 + }, + "the_movavg": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "the_sum": { + "value": 81277.296875 + }, + "the_movavg": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 924, + "the_sum": { + "value": 70494.2578125 + }, + "the_movavg": { + "value": 81277.296875 + } + } + ] + } + } +} +``` +
+ + +## Example: Moving average + +The `moving_fn` aggregation replaces the deprecated `moving_avg` aggregation. The `moving_fn` aggregation is similar to the `moving_avg` aggregation but is more versatile since it computes arbitrary functions instead of only averages. All of the predefined `moving_avg` functions are implemented in `moving_fn` as well. + +The `holt` model is a moving average that uses exponentially decaying weights controlled by the `alpha` and `beta` parameters. The following example creates a date histogram with a one-week interval from the OpenSearch Dashboards logs sample data. The `sum` subaggregation calculates the sum of all bytes for each week. Finally, the `moving_fn` aggregation calculates a weighted average of the byte sum using a Holt model with a `window` size of `6`, the default `shift` of `0`, an `alpha` value of `0.3`, and a `beta` value of `0.1`: + +```json +POST /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "week" + }, + "aggs": { + "the_sum": { + "sum": { "field": "bytes" } + }, + "the_movavg": { + "moving_fn": { + "buckets_path": "the_sum", + "window": 6, + "script": "MovingFunctions.holt(values, 0.3, 0.1)" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The aggregation returns the moving `holt` average starting with the second bucket: + +
+ + Response + + +```json +{ + "took": 16, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "the_sum": { + "value": 1531493 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "the_sum": { + "value": 9213161 + }, + "the_movavg": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "the_sum": { + "value": 9188671 + }, + "the_movavg": { + "value": 3835993.3999999994 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "the_sum": { + "value": 9244851 + }, + "the_movavg": { + "value": 5603111.707999999 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "the_sum": { + "value": 9061045 + }, + "the_movavg": { + "value": 6964515.302359998 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "the_sum": { + "value": 8713507 + }, + "the_movavg": { + "value": 7930766.089341199 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "the_sum": { + "value": 9544718 + }, + "the_movavg": { + "value": 8536788.607547803 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "the_sum": { + "value": 9155820 + }, + "the_movavg": { + "value": 9172269.837272028 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "the_sum": { + "value": 9025078 + }, + "the_movavg": { + "value": 9166173.88436614 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "the_sum": { + "value": 5047345 + }, + "the_movavg": { + "value": 9123157.830417283 + } + } + ] + } + } +} +``` +
+ diff --git a/_aggregations/pipeline/percentiles-bucket.md b/_aggregations/pipeline/percentiles-bucket.md new file mode 100644 index 00000000..7bce8322 --- /dev/null +++ b/_aggregations/pipeline/percentiles-bucket.md @@ -0,0 +1,288 @@ +--- +layout: default +title: Percentiles bucket +parent: Pipeline aggregations +nav_order: 160 +--- + +# Percentiles bucket aggregation + +The `percentiles_bucket` aggregation is a sibling aggregation that calculates the percentile placement of bucketed metrics. + +The `percentiles_bucket` aggregation computes percentiles exactly, without approximation or interpolation. Each percentile is returned as the closest value less than or equal to the target percentile. + +The `percentiles_bucket` aggregation requires that the entire list of values be kept temporarily in memory, even for large datasets. In contrast, [the `percentiles` metric aggregation]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile/) uses less memory but approximates the percentages. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `avg_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to aggregate. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | +| `percents` | Optional | List | A list containing any number of numeric percentage values to be included in the output. Valid values are between 0.0 and 100.0, inclusive. Default is `[1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]`. | +| `keyed` | Optional | Boolean | Whether to format the output as a dictionary rather than as an array of key-value pair objects. Default is `true` (format the output as key-value pairs). | + + +## Example + +The following example creates a date histogram with a one-week interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation adds up the `taxful_total_price` for each week. Finally, the `percentiles_bucket` aggregation calculates the percentile values for each week from these sums: + +```json +POST /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "weekly_sales": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "total_price": { + "sum": { + "field": "taxful_total_price" + } + } + } + }, + "percentiles_monthly_sales": { + "percentiles_bucket": { + "buckets_path": "weekly_sales>total_price" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns the default percentile values for the weekly price totals: + +
+ + Response + + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "weekly_sales": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 582, + "total_price": { + "value": 41455.5390625 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "total_price": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "total_price": { + "value": 78208.4296875 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "total_price": { + "value": 81277.296875 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 924, + "total_price": { + "value": 70494.2578125 + } + } + ] + }, + "percentiles_monthly_sales": { + "values": { + "1.0": 41455.5390625, + "5.0": 41455.5390625, + "25.0": 70494.2578125, + "50.0": 78208.4296875, + "75.0": 79448.60546875, + "95.0": 81277.296875, + "99.0": 81277.296875 + } + } + } +} +``` +
+ +## Example: Options + +The next example computes percentiles using the same data as in the previous example but with the following differences: + +- The `percents` parameter specifies that only the 25th, 50th, and 75th percentiles be calculated. +- String-formatted outputs are appended using the `format` parameter. +- Results are displayed as key-value pair objects (with string values appended) by setting the `keyed` parameter to `false`. + +The example is as follows: + +```json +POST /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "weekly_sales": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "total_price": { + "sum": { + "field": "taxful_total_price" + } + } + } + }, + "percentiles_monthly_sales": { + "percentiles_bucket": { + "buckets_path": "weekly_sales>total_price", + "percents": [25.0, 50.0, 75.0], + "format": "$#,###.00", + "keyed": false + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response: Options + +The options modify the output of the aggregation: + + +
+ + Response + + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "weekly_sales": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 582, + "total_price": { + "value": 41455.5390625 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "total_price": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "total_price": { + "value": 78208.4296875 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "total_price": { + "value": 81277.296875 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 924, + "total_price": { + "value": 70494.2578125 + } + } + ] + }, + "percentiles_monthly_sales": { + "values": [ + { + "key": 25, + "value": 70494.2578125, + "25.0_as_string": "$70,494.26" + }, + { + "key": 50, + "value": 78208.4296875, + "50.0_as_string": "$78,208.43" + }, + { + "key": 75, + "value": 79448.60546875, + "75.0_as_string": "$79,448.61" + } + ] + } + } +} +``` +
+ diff --git a/_aggregations/pipeline/serial-diff.md b/_aggregations/pipeline/serial-diff.md new file mode 100644 index 00000000..000d2f20 --- /dev/null +++ b/_aggregations/pipeline/serial-diff.md @@ -0,0 +1,289 @@ +--- +layout: default +title: Serial differencing +parent: Pipeline aggregations +nav_order: 180 +--- + +# Serial differencing aggregation + +The `serial_diff` aggregation is a parent pipeline aggregation that calculates the difference between metric values in the current bucket and a previous bucket. It stores the result in the current bucket. + +Use the `serial_diff` aggregation to compute changes between time periods with a specified lag. The `lag` parameter (a positive integer value) specifies which previous bucket value to subtract from the current one. The default `lag` value is `1`, meaning `serial_diff` subtracts the value in the immediately previous bucket from the value in the current bucket. + +## Parameters + +The `serial_diff` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | +| `lag` | Optional | Integer | The historical bucket to subtract from the current bucket. Must be a positive integer. Default is `1`. | + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards logs sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the `serial_diff` aggregation calculates month-to-month difference in total bytes from these sums: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "monthly_bytes": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "total_bytes": { + "sum": { + "field": "bytes" + } + }, + "monthly_bytes_change": { + "serial_diff": { + "buckets_path": "total_bytes", + "lag": 1 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the month-to-month difference for the second and third months. (The first month `serial_diff` cannot be calculated because there's no previous month against which to compare it): + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "monthly_bytes": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "total_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "total_bytes": { + "value": 39103067 + }, + "monthly_bytes_change": { + "value": 36298964 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "total_bytes": { + "value": 37818519 + }, + "monthly_bytes_change": { + "value": -1284548 + } + } + ] + } + } +} +``` + +The following line chart shows the results of the `serial_diff` aggregation. The x-axis represents time, and the y-axis shows the month-over-month change in total bytes transferred. Each data point on the line reflects the difference between the total bytes in that month and the previous month. For example, a value of 5,000,000 means that the system transferred 5 million more bytes than the prior month; a negative value indicates a decrease. The first month is excluded from the line because there's no previous bucket against which to compare it (the difference is undefined). The line starts with the second month and continues across all available data. + +![Example serial difference aggregation visualization]({{site.url}}{{site.baseurl}}/images/serial-diff-agg-result.png) + +This visualization helps you quickly spot spikes, drops, or trends in data volume over time. + +## Example: Multi-period differences + +Use a larger `lag` value to compare each bucket with one that occurred further in the past. The following example computes differences in weekly byte data with a lag of 4 (meaning each bucket is compared to the one from 4 weeks earlier). This has the effect of removing any variation with a period of 4 weeks: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "monthly_bytes": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "week" + }, + "aggs": { + "total_bytes": { + "sum": { + "field": "bytes" + } + }, + "monthly_bytes_change": { + "serial_diff": { + "buckets_path": "total_bytes", + "lag": 4 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response contains a list of weekly buckets. Note that the `serial_diff` aggregation does not begin until the fifth bucket, when a bucket with a `lag` of `4` becomes available: + +
+ + Response + + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "monthly_bytes": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "total_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "total_bytes": { + "value": 9213161 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "total_bytes": { + "value": 9188671 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "total_bytes": { + "value": 9244851 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "total_bytes": { + "value": 9061045 + }, + "monthly_bytes_change": { + "value": 7529552 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "total_bytes": { + "value": 8713507 + }, + "monthly_bytes_change": { + "value": -499654 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "total_bytes": { + "value": 9544718 + }, + "monthly_bytes_change": { + "value": 356047 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "total_bytes": { + "value": 9155820 + }, + "monthly_bytes_change": { + "value": -89031 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "total_bytes": { + "value": 9025078 + }, + "monthly_bytes_change": { + "value": -35967 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "total_bytes": { + "value": 5047345 + }, + "monthly_bytes_change": { + "value": -3666162 + } + } + ] + } + } +} +``` +
diff --git a/_aggregations/pipeline/stats-bucket.md b/_aggregations/pipeline/stats-bucket.md new file mode 100644 index 00000000..ac0f9d22 --- /dev/null +++ b/_aggregations/pipeline/stats-bucket.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Stats bucket +parent: Pipeline aggregations +nav_order: 190 +--- + +# Stats bucket aggregation + +The `stats_bucket` aggregation is a sibling aggregation that returns a variety of stats (`count`, `min`, `max`, `avg`, and `sum`) for the buckets of a previous aggregation. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `stats_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/#data-gaps). | +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `_as_string` property. | + +## Example + +The following example creates a date histogram with a one-month interval using the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of all bytes for each month. Finally, the `stats_bucket` aggregation returns the `count`, `avg`, `sum`, `min`, and `max` stats from these sums: + +```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" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns all five basic statistics for the buckets: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "stats_monthly_bytes": { + "count": 3, + "min": 2804103, + "max": 39103067, + "avg": 26575229.666666668, + "sum": 79725689 + } + } +} +``` diff --git a/_aggregations/pipeline/sum-bucket.md b/_aggregations/pipeline/sum-bucket.md new file mode 100644 index 00000000..ef93f0de --- /dev/null +++ b/_aggregations/pipeline/sum-bucket.md @@ -0,0 +1,114 @@ +--- +layout: default +title: Sum bucket +parent: Pipeline aggregations +nav_order: 190 +--- + +# Sum bucket aggregation + +The `sum_bucket` aggregation is a sibling aggregation that calculates the sum of a metric in each bucket of a previous aggregation. + +The specified metric must be numeric, and the sibling aggregation must be a multi-bucket aggregation. + +## Parameters + +The `sum_bucket` aggregation takes the following parameters. + +| Parameter | Required/Optional | Data type | Description | +| :-- | :-- | :-- | :-- | +| `buckets_path` | Required | String | The path of the aggregation buckets to be aggregated. See [Buckets path]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#buckets-path). | +| `gap_policy` | Optional | String | The policy to apply to missing data. Valid values are `skip` and `insert_zeros`. Default is `skip`. See [Data gaps]({{site.url}}{{site.baseurl}}/aggregations/pipeline/index#data-gaps).| +| `format` | Optional | String | A [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) formatting string. Returns the formatted output in the aggregation's `value_as_string` property. | + +## Example + +The following example creates a date histogram with a one-month interval from the OpenSearch Dashboards e-commerce sample data. The `sum` subaggregation calculates the sum of bytes for each month. Finally, the `sum_bucket` aggregation calculates the total number of bytes per month by totaling these sums: + +```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" + } + } + } + }, + "sum_monthly_bytes": { + "sum_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The aggregation returns the sum of bytes from all the monthly buckets: + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "sum_monthly_bytes": { + "value": 79725689 + } + } +} +``` + + diff --git a/_analyzers/character-filters/html-character-filter.md b/_analyzers/character-filters/html-character-filter.md new file mode 100644 index 00000000..bd9f8858 --- /dev/null +++ b/_analyzers/character-filters/html-character-filter.md @@ -0,0 +1,178 @@ +--- +layout: default +title: HTML strip +parent: Character filters +nav_order: 100 +--- + +# HTML strip character filter + +The `html_strip` character filter removes HTML tags, such as `
`, `

`, and ``, from the input text and renders plain text. The filter can be configured to preserve certain tags or decode specific HTML entities, such as ` `, into spaces. + +## Example + +The following request applies an `html_strip` character filter to the provided text: + +```json +GET /_analyze +{ + "tokenizer": "keyword", + "char_filter": [ + "html_strip" + ], + "text": "

Commonly used calculus symbols include α, β and θ

" +} +``` +{% include copy-curl.html %} + +The response contains the token in which HTML characters have been converted to their decoded values: + +```json +{ + "tokens": [ + { + "token": """ +Commonly used calculus symbols include α, β and θ +""", + "start_offset": 0, + "end_offset": 74, + "type": "word", + "position": 0 + } + ] +} +``` + +## Parameters + +The `html_strip` character filter can be configured with the following parameter. + +| Parameter | Required/Optional | Data type | Description | +|:---|:---|:---|:---| +| `escaped_tags` | Optional | Array of strings | An array of HTML element names, specified without the enclosing angle brackets (`< >`). The filter does not remove elements in this list when stripping HTML from the text. For example, setting the array to `["b", "i"]` will prevent the `` and `` elements from being stripped.| + +## Example: Custom analyzer with lowercase filter + +The following example request creates a custom analyzer that strips HTML tags and converts the plain text to lowercase by using the `html_strip` analyzer and `lowercase` filter: + +```json +PUT /html_strip_and_lowercase_analyzer +{ + "settings": { + "analysis": { + "char_filter": { + "html_filter": { + "type": "html_strip" + } + }, + "analyzer": { + "html_strip_analyzer": { + "type": "custom", + "char_filter": ["html_filter"], + "tokenizer": "standard", + "filter": ["lowercase"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /html_strip_and_lowercase_analyzer/_analyze +{ + "analyzer": "html_strip_analyzer", + "text": "

Welcome to OpenSearch!

" +} +``` +{% include copy-curl.html %} + +In the response, the HTML tags have been removed and the plain text has been converted to lowercase: + +```json +{ + "tokens": [ + { + "token": "welcome", + "start_offset": 4, + "end_offset": 11, + "type": "", + "position": 0 + }, + { + "token": "to", + "start_offset": 12, + "end_offset": 14, + "type": "", + "position": 1 + }, + { + "token": "opensearch", + "start_offset": 23, + "end_offset": 42, + "type": "", + "position": 2 + } + ] +} +``` + +## Example: Custom analyzer that preserves HTML tags + +The following example request creates a custom analyzer that preserves HTML tags: + +```json +PUT /html_strip_preserve_analyzer +{ + "settings": { + "analysis": { + "char_filter": { + "html_filter": { + "type": "html_strip", + "escaped_tags": ["b", "i"] + } + }, + "analyzer": { + "html_strip_analyzer": { + "type": "custom", + "char_filter": ["html_filter"], + "tokenizer": "keyword" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /html_strip_preserve_analyzer/_analyze +{ + "analyzer": "html_strip_analyzer", + "text": "

This is a bold and italic text.

" +} +``` +{% include copy-curl.html %} + +In the response, the `italic` and `bold` tags have been retained, as specified in the custom analyzer request: + +```json +{ + "tokens": [ + { + "token": """ +This is a bold and italic text. +""", + "start_offset": 0, + "end_offset": 52, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/character-filters/icu-normalization.md b/_analyzers/character-filters/icu-normalization.md new file mode 100644 index 00000000..0d99d2d9 --- /dev/null +++ b/_analyzers/character-filters/icu-normalization.md @@ -0,0 +1,175 @@ +--- +layout: default +title: ICU normalization +parent: Character filters +nav_order: 110 +--- + +# ICU normalization character filter + +The `icu_normalizer` character filter converts text into a canonical Unicode form by applying one of the normalization modes defined in [Unicode Standard Annex #15](http://unicode.org/reports/tr15/). This process standardizes character representations before tokenization, ensuring that equivalent characters are treated consistently. + +## Installation + +The `icu_normalizer` character filter requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/). + +## Normalization modes + +The character filter supports the following Unicode normalization forms: + +- `nfc` (Canonical Decomposition, followed by Canonical Composition): Decomposes combined characters, then recomposes them in a standard order. This is the most common normalization form. +- `nfd` (Canonical Decomposition): Decomposes combined characters into their constituent parts. For example, `é` becomes `e` + combining acute accent. +- `nfkc` (Compatibility Decomposition, followed by Canonical Composition): Applies compatibility decompositions (converting visually similar characters to a standard form), then canonical composition. +- `nfkc_cf` (Default): Applies NFKC normalization with case folding. This mode normalizes both character representations and case. + +## Parameters + +The following table lists the parameters for the `icu_normalizer` character filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`name` | String | The Unicode normalization form to apply. Valid values are `nfc`, `nfd`, `nfkc`, and `nfkc_cf`. Default is `nfkc_cf`. +`mode` | String | The normalization mode. Valid values are `compose` (default) and `decompose`. When `decompose` is specified, `nfc` becomes `nfd` and `nfkc` becomes `nfkd`. +`unicode_set_filter` | String | A [UnicodeSet](https://unicode-org.github.io/icu/userguide/strings/unicodeset.html) expression that specifies which characters to normalize. Optional. If not specified, all characters are normalized. + +## Example: Default normalization + +The following example demonstrates using the default `nfkc_cf` normalization: + +```json +PUT /icu-norm-default +{ + "settings": { + "analysis": { + "analyzer": { + "default_icu_normalizer": { + "tokenizer": "keyword", + "char_filter": ["icu_normalizer"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the normalizer with text containing ligatures and case variations: + +```json +POST /icu-norm-default/_analyze +{ + "analyzer": "default_icu_normalizer", + "text": "financial AFFAIRS" +} +``` +{% include copy-curl.html %} + +The response shows normalization and case folding: + +```json +{ + "tokens": [ + { + "token": "financial affairs", + "start_offset": 0, + "end_offset": 16, + "type": "word", + "position": 0 + } + ] +} +``` + +## Example: NFD (decomposed) normalization + +The following example configures NFD normalization by setting `mode` to `decompose`: + +```json +PUT /icu-norm-nfd +{ + "settings": { + "analysis": { + "char_filter": { + "nfd_normalizer": { + "type": "icu_normalizer", + "name": "nfc", + "mode": "decompose" + } + }, + "analyzer": { + "nfd_analyzer": { + "tokenizer": "keyword", + "char_filter": ["nfd_normalizer"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test with accented characters: + +```json +POST /icu-norm-nfd/_analyze +{ + "analyzer": "nfd_analyzer", + "text": "café" +} +``` +{% include copy-curl.html %} + +The NFD normalization decomposes the accented character: + +```json +{ + "tokens": [ + { + "token": "café", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + } + ] +} +``` + +Note: While the visual representation appears the same, the underlying character encoding has changed from a single precomposed character to separate base and combining characters. +{: .note} + +## Example: Selective normalization with unicode_set_filter + +You can limit normalization to specific character ranges using the `unicode_set_filter` parameter: + +```json +PUT /icu-norm-selective +{ + "settings": { + "analysis": { + "char_filter": { + "latin_only_normalizer": { + "type": "icu_normalizer", + "name": "nfkc_cf", + "unicode_set_filter": "[\\u0000-\\u024F]" + } + }, + "analyzer": { + "selective_normalizer": { + "tokenizer": "keyword", + "char_filter": ["latin_only_normalizer"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +This configuration normalizes only Latin characters (Unicode range U+0000 to U+024F), leaving other scripts unchanged. + +## Related documentation + +- [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/) +- [ICU tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/icu-tokenizer/) +- [ICU folding token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/icu-folding/) \ No newline at end of file diff --git a/_analyzers/character-filters/index.md b/_analyzers/character-filters/index.md new file mode 100644 index 00000000..269115de --- /dev/null +++ b/_analyzers/character-filters/index.md @@ -0,0 +1,23 @@ +--- +layout: default +title: Character filters +nav_order: 90 +has_children: true +has_toc: false +redirect_from: + - /analyzers/character-filters/ +--- + +# Character filters + +Character filters process text before tokenization to prepare it for further analysis. + +Unlike token filters, which operate on tokens (words or terms), character filters process the raw input text before tokenization. They are especially useful for cleaning or transforming structured text containing unwanted characters, such as HTML tags or special symbols. Character filters help to strip or replace these elements so that text is properly formatted for analysis. + +Use cases for character filters include: + +- **HTML stripping**: The [`html_strip`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/html-character-filter/) character filter removes HTML tags from content so that only the plain text is indexed. +- **Pattern replacement**: The [`pattern_replace`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/pattern-replace-character-filter/) character filter replaces or removes unwanted characters or patterns in text, for example, converting hyphens to spaces. +- **Custom mappings**: The [`mapping`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/mapping-character-filter/) character filter substitutes specific characters or sequences with other values, for example, to convert currency symbols into their textual equivalents. +- **ICU normalization**: The [`icu_normalizer`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/icu-normalization/) character filter converts text into a canonical Unicode form before tokenization, ensuring that equivalent characters are treated consistently. Requires the `analysis-icu` plugin. +- **Japanese iteration marks**: The [`kuromoji_iteration_mark`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/kuromoji-iteration-mark/) character filter expands Japanese iteration marks to the character they represent, normalizing the text before tokenization. Requires the `analysis-kuromoji` plugin. diff --git a/_analyzers/character-filters/kuromoji-iteration-mark.md b/_analyzers/character-filters/kuromoji-iteration-mark.md new file mode 100644 index 00000000..064a2bd2 --- /dev/null +++ b/_analyzers/character-filters/kuromoji-iteration-mark.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Kuromoji iteration mark +parent: Character filters +nav_order: 115 +--- + +# Kuromoji iteration mark character filter + +The `kuromoji_iteration_mark` character filter normalizes Japanese horizontal iteration marks (odoriji) by replacing each mark with the character it repeats. Japanese writing uses iteration marks as shorthand for a repeated character: + +- 々 (kanji iteration mark) -- Repeats the preceding kanji character without change, so 佐々木 becomes 佐佐木. +- ゝ (hiragana iteration mark) -- Repeats the preceding hiragana character without change, so かゝ becomes かか. +- ゞ (hiragana voiced iteration mark) -- Repeats the preceding hiragana character and applies voicing (dakuten). The preceding character must be unvoiced, so みすゞ becomes みすず, in which す is voiced to ず. +- ヽ (katakana iteration mark) -- Repeats the preceding katakana character without change, so コヽア becomes ココア. +- ヾ (katakana voiced iteration mark) -- Repeats the preceding katakana character and applies voicing (dakuten). The preceding character must be unvoiced, so カヾ becomes カガ. + +Expanding these marks before tokenization ensures that the resulting tokens are consistent regardless of whether the original text used iteration marks or spelled out the repeated characters. + +## Installation + +The `kuromoji_iteration_mark` character filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `kuromoji_iteration_mark` character filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`normalize_kanji` | Boolean | When `true`, kanji iteration marks (々) are normalized. Default is `true`. +`normalize_kana` | Boolean | When `true`, kana iteration marks (ゞ, ヾ, ゝ, and ヽ) are normalized. Default is `true`. + +## Example + +The following example creates an index with a custom analyzer that uses the `kuromoji_iteration_mark` character filter: + +```json +PUT /iteration-mark-index +{ + "settings": { + "analysis": { + "char_filter": { + "iteration_mark_filter": { + "type": "kuromoji_iteration_mark", + "normalize_kanji": true, + "normalize_kana": true + } + }, + "analyzer": { + "iteration_mark_analyzer": { + "type": "custom", + "char_filter": ["iteration_mark_filter"], + "tokenizer": "kuromoji_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with text containing the kanji iteration mark. The name 佐々木 (Sasaki) uses 々 to repeat the preceding kanji 佐: + +```json +POST /iteration-mark-index/_analyze +{ + "analyzer": "iteration_mark_analyzer", + "text": "佐々木さんは元気です" +} +``` +{% include copy-curl.html %} + +The character filter expands 佐々木 to 佐佐木 before tokenization: + +```json +{ + "tokens": [ + { + "token": "佐佐木", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "さん", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 1 + }, + { + "token": "は", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "元気", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 3 + }, + { + "token": "です", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 4 + } + ] +} +``` + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) diff --git a/_analyzers/character-filters/mapping-character-filter.md b/_analyzers/character-filters/mapping-character-filter.md new file mode 100644 index 00000000..59e516e4 --- /dev/null +++ b/_analyzers/character-filters/mapping-character-filter.md @@ -0,0 +1,125 @@ +--- +layout: default +title: Mapping +parent: Character filters +nav_order: 120 +--- + +# Mapping character filter + +The `mapping` character filter accepts a map of key-value pairs for character replacement. Whenever the filter encounters a string of characters matching a key, it replaces them with the corresponding value. Replacement values can be empty strings. + +The filter applies greedy matching, meaning that the longest matching pattern is matched. + +The `mapping` character filter helps in scenarios where specific text replacements are required before tokenization. + +## Example + +The following request configures a `mapping` character filter that converts Roman numerals (such as I, II, or III) into their corresponding Arabic numerals (1, 2, and 3): + +```json +GET /_analyze +{ + "tokenizer": "keyword", + "char_filter": [ + { + "type": "mapping", + "mappings": [ + "I => 1", + "II => 2", + "III => 3", + "IV => 4", + "V => 5" + ] + } + ], + "text": "I have III apples and IV oranges" +} +``` +{% include copy-curl.html %} + +The response contains a token where Roman numerals have been replaced with Arabic numerals: + +```json +{ + "tokens": [ + { + "token": "1 have 3 apples and 4 oranges", + "start_offset": 0, + "end_offset": 32, + "type": "word", + "position": 0 + } + ] +} +``` + +## Parameters + +You can use either of the following parameters to configure the key-value map. + +| Parameter | Required/Optional | Data type | Description | +|:---|:---|:---|:---| +| `mappings` | Optional | Array | An array of key-value pairs in the format `key => value`. Each key found in the input text will be replaced with its corresponding value. | +| `mappings_path` | Optional | String | The path to a UTF-8 encoded file containing key-value mappings. Each mapping should appear on a new line in the format `key => value`. The path can be absolute or relative to the OpenSearch configuration directory. | + +### Using a custom mapping character filter + +You can create a custom mapping character filter by defining your own set of mappings. The following request creates a custom character filter that replaces common abbreviations in a text: + +```json +PUT /test-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_abbr_analyzer": { + "tokenizer": "standard", + "char_filter": [ + "custom_abbr_filter" + ] + } + }, + "char_filter": { + "custom_abbr_filter": { + "type": "mapping", + "mappings": [ + "BTW => By the way", + "IDK => I don't know", + "FYI => For your information" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /text-index/_analyze +{ + "tokenizer": "keyword", + "char_filter": [ "custom_abbr_filter" ], + "text": "FYI, updates to the workout schedule are posted. IDK when it takes effect, but we have some details. BTW, the finalized schedule will be released Monday." +} +``` +{% include copy-curl.html %} + +The response shows that the abbreviations were replaced: + +```json +{ + "tokens": [ + { + "token": "For your information, updates to the workout schedule are posted. I don't know when it takes effect, but we have some details. By the way, the finalized schedule will be released Monday.", + "start_offset": 0, + "end_offset": 153, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/character-filters/pattern-replace-character-filter.md b/_analyzers/character-filters/pattern-replace-character-filter.md new file mode 100644 index 00000000..a79158e3 --- /dev/null +++ b/_analyzers/character-filters/pattern-replace-character-filter.md @@ -0,0 +1,245 @@ +--- +layout: default +title: Pattern replace +parent: Character filters +nav_order: 130 +--- + +# Pattern replace character filter + +The `pattern_replace` character filter allows you to use regular expressions to define patterns for matching and replacing characters in the input text. It is a flexible tool for advanced text transformations, especially when dealing with complex string patterns. + +This filter replaces all instances of a pattern with a specified replacement string, allowing for easy substitutions, deletions, or complex modifications of the input text. You can use it to normalize the input before tokenization. + +## Example + +To standardize phone numbers, you'll use the regular expression `[\\s()-]+`: + +- `[ ]`: Defines a **character class**, meaning it will match **any one** of the characters inside the brackets. +- `\\s`: Matches any **white space** character, such as a space, tab, or newline. +- `()`: Matches literal **parentheses** (`(` or `)`). +- `-`: Matches a literal **hyphen** (`-`). +- `+`: Specifies that the pattern should match **one or more** occurrences of the preceding characters. + +The pattern `[\\s()-]+` will match any sequence of one or more white space characters, parentheses, or hyphens and remove it from the input text. This ensures that the phone numbers are normalized and contain only digits. + +The following request standardizes phone numbers by removing spaces, dashes, and parentheses: + +```json +GET /_analyze +{ + "tokenizer": "standard", + "char_filter": [ + { + "type": "pattern_replace", + "pattern": "[\\s()-]+", + "replacement": "" + } + ], + "text": "(555) 123-4567" +} +``` +{% include copy-curl.html %} + +The response contains the generated token: + +```json +{ + "tokens": [ + { + "token": "5551234567", + "start_offset": 1, + "end_offset": 14, + "type": "", + "position": 0 + } + ] +} +``` + +## Parameters + +The `pattern_replace` character filter supports the following parameters. + +| Parameter | Required/Optional | Data type | Description | +|:---|:---|:---|:---| +| `pattern` | Required | String | A regular expression used to match parts of the input text. The filter identifies and matches this pattern to perform replacement. | +| `replacement` | Optional | String | The string that replaces pattern matches. Use an empty string (`""`) to remove the matched text. The replacement can reference capturing groups in `pattern` as `$1`, `$2`, and so on. For an example, see [Using capturing groups](#using-capturing-groups). Default is an empty string (`""`). | +| `flags` | Optional | String | One or more [Java regular expression flags](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#field.summary) that modify how `pattern` is matched, for example, `CASE_INSENSITIVE`. To specify multiple flags, separate them with a pipe character (`\|`), for example, `"CASE_INSENSITIVE\|COMMENTS"`. | + +A poorly written regular expression can make analysis very slow and, in extreme cases, cause a `StackOverflowError` that stops the node. Avoid patterns that can match the same text in many ways, such as nested quantifiers like `(a+)+`, and test new patterns on representative text using the [Analyze API]({{site.url}}{{site.baseurl}}/api-reference/analyze-apis/). +{: .warning} + +If a replacement changes the length of the text, search results are not affected, but [highlighting]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) can be inaccurate. OpenSearch adjusts the character offsets of tokens to match the original text, but the adjustment can be imprecise for tokens next to a replacement. For example, if the filter removes parentheses and hyphens from `Call (555) 123-4567 today`, a search for `555` highlights `(555)`, including the closing parenthesis. If you need precise highlighting, test the results on your data. +{: .note} + +## Creating a custom analyzer + +The following request creates an index with a custom analyzer configured with a `pattern_replace` character filter. The filter removes currency signs and thousands separators (both European `.` and American `,`) from numbers: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "char_filter": [ + "pattern_char_filter" + ] + } + }, + "char_filter": { + "pattern_char_filter": { + "type": "pattern_replace", + "pattern": "[$€,.]", + "replacement": "" + } + } + } + } +} +``` + +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "Total: $ 1,200.50 and € 1.100,75" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Total", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "120050", + "start_offset": 9, + "end_offset": 17, + "type": "", + "position": 1 + }, + { + "token": "and", + "start_offset": 18, + "end_offset": 21, + "type": "", + "position": 2 + }, + { + "token": "110075", + "start_offset": 24, + "end_offset": 32, + "type": "", + "position": 3 + } + ] +} +``` + +## Using capturing groups + +You can use capturing groups in the `replacement` parameter. For example, the following request creates a custom analyzer that uses a `pattern_replace` character filter to replace hyphens with dots in phone numbers: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "char_filter": [ + "pattern_char_filter" + ] + } + }, + "char_filter": { + "pattern_char_filter": { + "type": "pattern_replace", + "pattern": "(\\d+)-(?=\\d)", + "replacement": "$1." + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "Call me at 555-123-4567 or 555-987-6543" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Call", + "start_offset": 0, + "end_offset": 4, + "type": "", + "position": 0 + }, + { + "token": "me", + "start_offset": 5, + "end_offset": 7, + "type": "", + "position": 1 + }, + { + "token": "at", + "start_offset": 8, + "end_offset": 10, + "type": "", + "position": 2 + }, + { + "token": "555.123.4567", + "start_offset": 11, + "end_offset": 23, + "type": "", + "position": 3 + }, + { + "token": "or", + "start_offset": 24, + "end_offset": 26, + "type": "", + "position": 4 + }, + { + "token": "555.987.6543", + "start_offset": 27, + "end_offset": 39, + "type": "", + "position": 5 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/custom-analyzer.md b/_analyzers/custom-analyzer.md new file mode 100644 index 00000000..bae41bb7 --- /dev/null +++ b/_analyzers/custom-analyzer.md @@ -0,0 +1,377 @@ +--- +layout: default +title: Creating a custom analyzer +nav_order: 40 +parent: Analyzers +--- + +# Creating a custom analyzer + +To create a custom analyzer, specify a combination of the following components: + +- Character filters (zero or more) + +- Tokenizer (one) + +- Token filters (zero or more) + +## Configuration + +The following parameters can be used to configure a custom analyzer. + +| Parameter | Required/Optional | Description | +|:--- | :--- | :--- | +| `type` | Optional | The analyzer type. Default is `custom`. You can also specify a prebuilt analyzer using this parameter. | +| `tokenizer` | Required | A tokenizer to be included in the analyzer. | +| `char_filter` | Optional | A list of character filters to be included in the analyzer. | +| `filter` | Optional | A list of token filters to be included in the analyzer. | +| `position_increment_gap` | Optional | The extra spacing applied between values when indexing text fields that have multiple values. For more information, see [Position increment gap](#position-increment-gap). Default is `100`. | + +## Examples + +The following examples demonstrate various custom analyzer configurations. + +### Custom analyzer with a character filter for HTML stripping + +The following example analyzer removes HTML tags from text before tokenization: + +```json +PUT simple_html_strip_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "html_strip_analyzer": { + "type": "custom", + "char_filter": ["html_strip"], + "tokenizer": "whitespace", + "filter": ["lowercase"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET simple_html_strip_analyzer_index/_analyze +{ + "analyzer": "html_strip_analyzer", + "text": "

OpenSearch is awesome!

" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 3, + "end_offset": 13, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 14, + "end_offset": 16, + "type": "word", + "position": 1 + }, + { + "token": "awesome!", + "start_offset": 25, + "end_offset": 42, + "type": "word", + "position": 2 + } + ] +} +``` + +### Custom analyzer with a mapping character filter for synonym replacement + +The following example analyzer replaces specific characters and patterns before applying the synonym filter: + +```json +PUT mapping_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "synonym_mapping_analyzer": { + "type": "custom", + "char_filter": ["underscore_to_space"], + "tokenizer": "standard", + "filter": ["lowercase", "stop", "synonym_filter"] + } + }, + "char_filter": { + "underscore_to_space": { + "type": "mapping", + "mappings": ["_ => ' '"] + } + }, + "filter": { + "synonym_filter": { + "type": "synonym", + "synonyms": [ + "quick, fast, speedy", + "big, large, huge" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET mapping_analyzer_index/_analyze +{ + "analyzer": "synonym_mapping_analyzer", + "text": "The slow_green_turtle is very large" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "slow","start_offset": 4,"end_offset": 8,"type": "","position": 1}, + {"token": "green","start_offset": 9,"end_offset": 14,"type": "","position": 2}, + {"token": "turtle","start_offset": 15,"end_offset": 21,"type": "","position": 3}, + {"token": "very","start_offset": 25,"end_offset": 29,"type": "","position": 5}, + {"token": "large","start_offset": 30,"end_offset": 35,"type": "","position": 6}, + {"token": "big","start_offset": 30,"end_offset": 35,"type": "SYNONYM","position": 6}, + {"token": "huge","start_offset": 30,"end_offset": 35,"type": "SYNONYM","position": 6} + ] +} +``` + +### Custom analyzer with a custom pattern-based character filter for number normalization + +The following example analyzer normalizes phone numbers by removing dashes and spaces and applies edge n-grams to the normalized text to support partial matches: + +```json +PUT advanced_pattern_replace_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "phone_number_analyzer": { + "type": "custom", + "char_filter": ["phone_normalization"], + "tokenizer": "standard", + "filter": ["lowercase", "edge_ngram"] + } + }, + "char_filter": { + "phone_normalization": { + "type": "pattern_replace", + "pattern": "[-\\s]", + "replacement": "" + } + }, + "filter": { + "edge_ngram": { + "type": "edge_ngram", + "min_gram": 3, + "max_gram": 10 + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET advanced_pattern_replace_analyzer_index/_analyze +{ + "analyzer": "phone_number_analyzer", + "text": "123-456 7890" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "123","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "1234","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "12345","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "123456","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "1234567","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "12345678","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "123456789","start_offset": 0,"end_offset": 12,"type": "","position": 0}, + {"token": "1234567890","start_offset": 0,"end_offset": 12,"type": "","position": 0} + ] +} +``` + +## Handling special characters in regex patterns + +When using custom regex patterns in your analyzer, ensure that special or non-English characters are handled correctly. By default, Java's regex considers only `[A-Za-z0-9_]` to be word characters (`\w`). This can cause unexpected behavior when using `\w` or `\b`, which match the boundary between a word and a non-word character. + +For example, the following analyzer attempts to use the pattern `(\b\p{L}+\b)` to match one or more letter characters from any language (`\p{L}`) surrounded by word boundaries: + +```json +PUT /buggy_custom_analyzer +{ + "settings": { + "analysis": { + "filter": { + "capture_words": { + "type": "pattern_capture", + "patterns": [ + "(\\b\\p{L}+\\b)" + ] + } + }, + "analyzer": { + "filter_only_analyzer": { + "type": "custom", + "tokenizer": "keyword", + "filter": [ + "capture_words" + ] + } + } + } + } +} +``` + +However, this analyzer incorrectly tokenizes `él-empezó-a-reír` as `l`, `empez`, `a`, and `reír` because `\b` does not match the boundary between accented characters and the start or end of a string. + +To handle special characters correctly, add the Unicode case flag `(?U)` to your pattern: + +```json +PUT /fixed_custom_analyzer +{ + "settings": { + "analysis": { + "filter": { + "capture_words": { + "type": "pattern_capture", + "patterns": [ + "(?U)(\\b\\p{L}+\\b)" + ] + } + }, + "analyzer": { + "filter_only_analyzer": { + "type": "custom", + "tokenizer": "keyword", + "filter": [ + "capture_words" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Position increment gap + +The `position_increment_gap` parameter sets a positional gap between terms when indexing multi-valued fields, such as arrays. This gap ensures that phrase queries don't match terms across separate values unless explicitly allowed. For example, a default gap of 100 specifies that terms in different array entries are 100 positions apart, preventing unintended matches in phrase searches. You can adjust this value or set it to `0` in order to allow phrases to span across array values. + +The following example demonstrates the effect of `position_increment_gap` using a `match_phrase` query. + +1. Index a document in a `test-index`: + + ```json + PUT test-index/_doc/1 + { + "names": [ "Slow green", "turtle swims"] + } + ``` + {% include copy-curl.html %} + +1. Query the document using a `match_phrase` query: + + ```json + GET test-index/_search + { + "query": { + "match_phrase": { + "names": { + "query": "green turtle" + } + } + } + } + ``` + {% include copy-curl.html %} + + The response returns no hits because the distance between the terms `green` and `turtle` is `100` (the default `position_increment_gap`). + +1. Now query the document using a `match_phrase` query with a `slop` parameter that is higher than the `position_increment_gap`: + + ```json + GET test-index/_search + { + "query": { + "match_phrase": { + "names": { + "query": "green turtle", + "slop": 101 + } + } + } + } + ``` + {% include copy-curl.html %} + + The response contains the matching document: + + ```json + { + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.010358453, + "hits": [ + { + "_index": "test-index", + "_id": "1", + "_score": 0.010358453, + "_source": { + "names": [ + "Slow green", + "turtle swims" + ] + } + } + ] + } + } + ``` diff --git a/_analyzers/index-analyzers.md b/_analyzers/index-analyzers.md index 72332758..23c74da0 100644 --- a/_analyzers/index-analyzers.md +++ b/_analyzers/index-analyzers.md @@ -2,11 +2,12 @@ layout: default title: Index analyzers nav_order: 20 +parent: Analyzers --- # Index analyzers -Index analyzers are specified at indexing time and are used to analyze [text]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) fields when indexing a document. +Index analyzers are specified at indexing time and are used to analyze [text]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) fields when indexing a document. ## Determining which index analyzer to use @@ -23,7 +24,7 @@ For information about verifying which analyzer is associated with which field, s ## Specifying an index analyzer for a field -When creating index mappings, you can supply the `analyzer` parameter for each [text]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) field. For example, the following request specifies the `simple` analyzer for the `text_entry` field: +When creating index mappings, you can supply the `analyzer` parameter for each [text]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) field. For example, the following request specifies the `simple` analyzer for the `text_entry` field: ```json PUT testindex diff --git a/_analyzers/index.md b/_analyzers/index.md index 95f97ec8..78ac1c55 100644 --- a/_analyzers/index.md +++ b/_analyzers/index.md @@ -45,30 +45,19 @@ An analyzer must contain exactly one tokenizer and may contain zero or more char There is also a special type of analyzer called a ***normalizer***. A normalizer is similar to an analyzer except that it does not contain a tokenizer and can only include specific types of character filters and token filters. These filters can perform only character-level operations, such as character or pattern replacement, and cannot perform operations on the token as a whole. This means that replacing a token with a synonym or stemming is not supported. See [Normalizers]({{site.url}}{{site.baseurl}}/analyzers/normalizers/) for further details. -## Built-in analyzers +## Supported analyzers -The following table lists the built-in analyzers that OpenSearch provides. The last column of the table contains the result of applying the analyzer to the string `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`. - -Analyzer | Analysis performed | Analyzer output -:--- | :--- | :--- -**Standard** (default) | - Parses strings into tokens at word boundaries
- Removes most punctuation
- Converts tokens to lowercase | [`it’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] -**Simple** | - Parses strings into tokens on any non-letter character
- Removes non-letter characters
- Converts tokens to lowercase | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] -**Whitespace** | - Parses strings into tokens on white space | [`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] -**Stop** | - Parses strings into tokens on any non-letter character
- Removes non-letter characters
- Removes stop words
- Converts tokens to lowercase | [`s`, `fun`, `contribute`, `brand`, `new`, `pr`, `opensearch`] -**Keyword** (no-op) | - Outputs the entire string unchanged | [`It’s fun to contribute a brand-new PR or 2 to OpenSearch!`] -**Pattern** | - Parses strings into tokens using regular expressions
- Supports converting strings to lowercase
- Supports removing stop words | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] -[**Language**]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/) | Performs analysis specific to a certain language (for example, `english`). | [`fun`, `contribut`, `brand`, `new`, `pr`, `2`, `opensearch`] -**Fingerprint** | - Parses strings on any non-letter character
- Normalizes characters by converting them to ASCII
- Converts tokens to lowercase
- Sorts, deduplicates, and concatenates tokens into a single token
- Supports removing stop words | [`2 a brand contribute fun it's new opensearch or pr to`]
Note that the apostrophe was converted to its ASCII counterpart. +For a list of supported analyzers, see [Analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/index/). ## Custom analyzers -If needed, you can combine tokenizers, token filters, and character filters to create a custom analyzer. +If needed, you can combine tokenizers, token filters, and character filters to create a custom analyzer. For more information, see [Creating a custom analyzer]({{site.url}}{{site.baseurl}}/analyzers/custom-analyzer/). ## Text analysis at indexing time and query time OpenSearch performs text analysis on text fields when you index a document and when you send a search request. Depending on the time of text analysis, the analyzers used for it are classified as follows: -- An _index analyzer_ performs analysis at indexing time: When you are indexing a [text]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) field, OpenSearch analyzes it before indexing it. For more information about ways to specify index analyzers, see [Index analyzers]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/). +- An _index analyzer_ performs analysis at indexing time: When you are indexing a [text]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) field, OpenSearch analyzes it before indexing it. For more information about ways to specify index analyzers, see [Index analyzers]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/). - A _search analyzer_ performs analysis at query time: OpenSearch analyzes the query string when you run a full-text query on a text field. For more information about ways to specify search analyzers, see [Search analyzers]({{site.url}}{{site.baseurl}}/analyzers/search-analyzers/). @@ -104,7 +93,7 @@ GET /_analyze The following image shows the query string. -![Query string with indices]({{site.url}}{{site.baseurl}}/images/string-indices.png) +![Query string with indexes]({{site.url}}{{site.baseurl}}/images/string-indices.png) The response contains each token and its start and end offsets that correspond to the starting index in the original string (inclusive) and the ending index (exclusive): @@ -170,6 +159,31 @@ The response provides information about the analyzers for each field: } ``` +## Normalizers + +Tokenization divides text into individual terms, but it does not address variations in token forms. Normalization resolves these issues by converting tokens into a standard format. This ensures that similar terms are matched appropriately, even if they are not identical. + +### Normalization techniques + +The following normalization techniques can help address variations in token forms: + +1. **Case normalization**: Converts all tokens to lowercase to ensure case-insensitive matching. For example, "Hello" is normalized to "hello". + +2. **Stemming**: Reduces words to their root form. For instance, "cars" is stemmed to "car" and "running" is normalized to "run". + +3. **Synonym handling:** Treats synonyms as equivalent. For example, "jogging" and "running" can be indexed under a common term, such as "run". + +### Normalization + +A search for `Hello` will match documents containing `hello` because of case normalization. + +A search for `cars` will also match documents containing `car` because of stemming. + +A query for `running` can retrieve documents containing `jogging` using synonym handling. + +Normalization ensures that searches are not limited to exact term matches, allowing for more relevant results. For instance, a search for `Cars running` can be normalized to match `car run`. + ## Next steps -- Learn more about specifying [index analyzers]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/) and [search analyzers]({{site.url}}{{site.baseurl}}/analyzers/search-analyzers/). \ No newline at end of file +- Learn more about specifying [index analyzers]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/) and [search analyzers]({{site.url}}{{site.baseurl}}/analyzers/search-analyzers/). +- See the list of [supported analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/index/). \ No newline at end of file diff --git a/_analyzers/language-analyzers/arabic.md b/_analyzers/language-analyzers/arabic.md new file mode 100644 index 00000000..8b6ea9d4 --- /dev/null +++ b/_analyzers/language-analyzers/arabic.md @@ -0,0 +1,182 @@ +--- +layout: default +title: Arabic +parent: Language analyzers +grand_parent: Analyzers +nav_order: 10 +--- + +# Arabic analyzer + +The built-in `arabic` analyzer can be applied to a text field using the following command: + +```json +PUT /arabic-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "arabic" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_arabic +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_arabic_analyzer":{ + "type":"arabic", + "stem_exclusion":["تكنولوجيا","سلطة "] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Arabic analyzer internals + +The `arabic` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - decimal_digit + - stop (Arabic) + - normalization (Arabic) + - keyword + - stemmer (Arabic) + +## Custom Arabic analyzer + +You can create a custom Arabic analyzer using the following command: + +```json +PUT /arabic-index +{ + "settings": { + "analysis": { + "filter": { + "arabic_stop": { + "type": "stop", + "stopwords": "_arabic_" + }, + "arabic_stemmer": { + "type": "stemmer", + "language": "arabic" + }, + "arabic_normalization": { + "type": "arabic_normalization" + }, + "decimal_digit": { + "type": "decimal_digit" + }, + "arabic_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "arabic_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "decimal_digit", + "arabic_stop", + "arabic_normalization", + "arabic_keywords", + "arabic_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "arabic_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /arabic-index/_analyze +{ + "field": "content", + "text": "الطلاب يدرسون في الجامعات العربية. أرقامهم ١٢٣٤٥٦." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "طلاب", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "يدرس", + "start_offset": 7, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "جامع", + "start_offset": 17, + "end_offset": 25, + "type": "", + "position": 3 + }, + { + "token": "عرب", + "start_offset": 26, + "end_offset": 33, + "type": "", + "position": 4 + }, + { + "token": "ارقامهم", + "start_offset": 35, + "end_offset": 42, + "type": "", + "position": 5 + }, + { + "token": "123456", + "start_offset": 43, + "end_offset": 49, + "type": "", + "position": 6 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/armenian.md b/_analyzers/language-analyzers/armenian.md new file mode 100644 index 00000000..9bd0549c --- /dev/null +++ b/_analyzers/language-analyzers/armenian.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Armenian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 20 +--- + +# Armenian analyzer + +The built-in `armenian` analyzer can be applied to a text field using the following command: + +```json +PUT /arabic-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "armenian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_armenian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_armenian_analyzer": { + "type": "armenian", + "stem_exclusion": ["բարև", "խաղաղություն"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Armenian analyzer internals + +The `armenian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Armenian) + - keyword + - stemmer (Armenian) + +## Custom Armenian analyzer + +You can create a custom Armenian analyzer using the following command: + +```json +PUT /armenian-index +{ + "settings": { + "analysis": { + "filter": { + "armenian_stop": { + "type": "stop", + "stopwords": "_armenian_" + }, + "armenian_stemmer": { + "type": "stemmer", + "language": "armenian" + }, + "armenian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "armenian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "armenian_stop", + "armenian_keywords", + "armenian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "armenian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET armenian-index/_analyze +{ + "analyzer": "stem_exclusion_armenian_analyzer", + "text": "բարև բոլորին, մենք խաղաղություն ենք ուզում և նոր օր ենք սկսել" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "բարև","start_offset": 0,"end_offset": 4,"type": "","position": 0}, + {"token": "բոլոր","start_offset": 5,"end_offset": 12,"type": "","position": 1}, + {"token": "խաղաղություն","start_offset": 19,"end_offset": 31,"type": "","position": 3}, + {"token": "ուզ","start_offset": 36,"end_offset": 42,"type": "","position": 5}, + {"token": "նոր","start_offset": 45,"end_offset": 48,"type": "","position": 7}, + {"token": "օր","start_offset": 49,"end_offset": 51,"type": "","position": 8}, + {"token": "սկսել","start_offset": 56,"end_offset": 61,"type": "","position": 10} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/basque.md b/_analyzers/language-analyzers/basque.md new file mode 100644 index 00000000..e73510cc --- /dev/null +++ b/_analyzers/language-analyzers/basque.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Basque +parent: Language analyzers +grand_parent: Analyzers +nav_order: 30 +--- + +# Basque analyzer + +The built-in `basque` analyzer can be applied to a text field using the following command: + +```json +PUT /basque-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "basque" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_basque_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_basque_analyzer": { + "type": "basque", + "stem_exclusion": ["autoritate", "baldintza"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Basque analyzer internals + +The `basque` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Basque) + - keyword + - stemmer (Basque) + +## Custom Basque analyzer + +You can create a custom Basque analyzer using the following command: + +```json +PUT /basque-index +{ + "settings": { + "analysis": { + "filter": { + "basque_stop": { + "type": "stop", + "stopwords": "_basque_" + }, + "basque_stemmer": { + "type": "stemmer", + "language": "basque" + }, + "basque_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "basque_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "basque_stop", + "basque_keywords", + "basque_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "basque_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /basque-index/_analyze +{ + "field": "content", + "text": "Ikasleek euskal unibertsitateetan ikasten dute. Haien zenbakiak 123456 dira." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "ikasle","start_offset": 0,"end_offset": 8,"type": "","position": 0}, + {"token": "euskal","start_offset": 9,"end_offset": 15,"type": "","position": 1}, + {"token": "unibertsi","start_offset": 16,"end_offset": 33,"type": "","position": 2}, + {"token": "ikas","start_offset": 34,"end_offset": 41,"type": "","position": 3}, + {"token": "haien","start_offset": 48,"end_offset": 53,"type": "","position": 5}, + {"token": "zenba","start_offset": 54,"end_offset": 63,"type": "","position": 6}, + {"token": "123456","start_offset": 64,"end_offset": 70,"type": "","position": 7} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/bengali.md b/_analyzers/language-analyzers/bengali.md new file mode 100644 index 00000000..864641a6 --- /dev/null +++ b/_analyzers/language-analyzers/bengali.md @@ -0,0 +1,142 @@ +--- +layout: default +title: Bengali +parent: Language analyzers +grand_parent: Analyzers +nav_order: 40 +--- + +# Bengali analyzer + +The built-in `bengali` analyzer can be applied to a text field using the following command: + +```json +PUT /bengali-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bengali" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_bengali_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_bengali_analyzer": { + "type": "bengali", + "stem_exclusion": ["কর্তৃপক্ষ", "অনুমোদন"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Bengali analyzer internals + +The `bengali` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - decimal_digit + - indic_normalization + - normalization (Bengali) + - stop (Bengali) + - keyword + - stemmer (Bengali) + +## Custom Bengali analyzer + +You can create a custom Bengali analyzer using the following command: + +```json +PUT /bengali-index +{ + "settings": { + "analysis": { + "filter": { + "bengali_stop": { + "type": "stop", + "stopwords": "_bengali_" + }, + "bengali_stemmer": { + "type": "stemmer", + "language": "bengali" + }, + "bengali_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "bengali_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "decimal_digit", + "bengali_keywords", + "indic_normalization", + "bengali_normalization", + "bengali_stop", + "bengali_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bengali_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /bengali-index/_analyze +{ + "field": "content", + "text": "ছাত্ররা বিশ্ববিদ্যালয়ে পড়াশোনা করে। তাদের নম্বরগুলি ১২৩৪৫৬।" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "ছাত্র","start_offset": 0,"end_offset": 7,"type": "","position": 0}, + {"token": "বিসসবিদালয়","start_offset": 8,"end_offset": 23,"type": "","position": 1}, + {"token": "পরাসোন","start_offset": 24,"end_offset": 32,"type": "","position": 2}, + {"token": "তা","start_offset": 38,"end_offset": 43,"type": "","position": 4}, + {"token": "নমমর","start_offset": 44,"end_offset": 53,"type": "","position": 5}, + {"token": "123456","start_offset": 54,"end_offset": 60,"type": "","position": 6} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/brazilian.md b/_analyzers/language-analyzers/brazilian.md new file mode 100644 index 00000000..67db2b92 --- /dev/null +++ b/_analyzers/language-analyzers/brazilian.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Brazilian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 50 +--- + +# Brazilian analyzer + +The built-in `brazilian` analyzer can be applied to a text field using the following command: + +```json +PUT /brazilian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "brazilian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_brazilian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_brazilian_analyzer": { + "type": "brazilian", + "stem_exclusion": ["autoridade", "aprovação"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Brazilian analyzer internals + +The `brazilian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Brazilian) + - keyword + - stemmer (Brazilian) + +## Custom Brazilian analyzer + +You can create a custom Brazilian analyzer using the following command: + +```json +PUT /brazilian-index +{ + "settings": { + "analysis": { + "filter": { + "brazilian_stop": { + "type": "stop", + "stopwords": "_brazilian_" + }, + "brazilian_stemmer": { + "type": "stemmer", + "language": "brazilian" + }, + "brazilian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "brazilian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "brazilian_stop", + "brazilian_keywords", + "brazilian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "brazilian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /brazilian-index/_analyze +{ + "field": "content", + "text": "Estudantes estudam em universidades brasileiras. Seus números são 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "estudant","start_offset": 0,"end_offset": 10,"type": "","position": 0}, + {"token": "estud","start_offset": 11,"end_offset": 18,"type": "","position": 1}, + {"token": "univers","start_offset": 22,"end_offset": 35,"type": "","position": 3}, + {"token": "brasileir","start_offset": 36,"end_offset": 47,"type": "","position": 4}, + {"token": "numer","start_offset": 54,"end_offset": 61,"type": "","position": 6}, + {"token": "sao","start_offset": 62,"end_offset": 65,"type": "","position": 7}, + {"token": "123456","start_offset": 66,"end_offset": 72,"type": "","position": 8} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/bulgarian.md b/_analyzers/language-analyzers/bulgarian.md new file mode 100644 index 00000000..42d5794e --- /dev/null +++ b/_analyzers/language-analyzers/bulgarian.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Bulgarian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 60 +--- + +# Bulgarian analyzer + +The built-in `bulgarian` analyzer can be applied to a text field using the following command: + +```json +PUT /bulgarian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bulgarian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_bulgarian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_bulgarian_analyzer": { + "type": "bulgarian", + "stem_exclusion": ["авторитет", "одобрение"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Bulgarian analyzer internals + +The `bulgarian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Bulgarian) + - keyword + - stemmer (Bulgarian) + +## Custom Bulgarian analyzer + +You can create a custom Bulgarian analyzer using the following command: + +```json +PUT /bulgarian-index +{ + "settings": { + "analysis": { + "filter": { + "bulgarian_stop": { + "type": "stop", + "stopwords": "_bulgarian_" + }, + "bulgarian_stemmer": { + "type": "stemmer", + "language": "bulgarian" + }, + "bulgarian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "bulgarian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "bulgarian_stop", + "bulgarian_keywords", + "bulgarian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bulgarian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /bulgarian-index/_analyze +{ + "field": "content", + "text": "Студентите учат в българските университети. Техните номера са 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "студент","start_offset": 0,"end_offset": 10,"type": "","position": 0}, + {"token": "учат","start_offset": 11,"end_offset": 15,"type": "","position": 1}, + {"token": "българск","start_offset": 18,"end_offset": 29,"type": "","position": 3}, + {"token": "университят","start_offset": 30,"end_offset": 42,"type": "","position": 4}, + {"token": "техн","start_offset": 44,"end_offset": 51,"type": "","position": 5}, + {"token": "номер","start_offset": 52,"end_offset": 58,"type": "","position": 6}, + {"token": "123456","start_offset": 62,"end_offset": 68,"type": "","position": 8} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/catalan.md b/_analyzers/language-analyzers/catalan.md new file mode 100644 index 00000000..89762da0 --- /dev/null +++ b/_analyzers/language-analyzers/catalan.md @@ -0,0 +1,143 @@ +--- +layout: default +title: Catalan +parent: Language analyzers +grand_parent: Analyzers +nav_order: 70 +--- + +# Catalan analyzer + +The built-in `catalan` analyzer can be applied to a text field using the following command: + +```json +PUT /catalan-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "catalan" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_catalan_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_catalan_analyzer": { + "type": "catalan", + "stem_exclusion": ["autoritat", "aprovació"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Catalan analyzer internals + +The `catalan` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - elision (Catalan) + - lowercase + - stop (Catalan) + - keyword + - stemmer (Catalan) + +## Custom Catalan analyzer + +You can create a custom Catalan analyzer using the following command: + +```json +PUT /catalan-index +{ + "settings": { + "analysis": { + "filter": { + "catalan_stop": { + "type": "stop", + "stopwords": "_catalan_" + }, + "catalan_elision": { + "type": "elision", + "articles": [ "d", "l", "m", "n", "s", "t"], + "articles_case": true + }, + "catalan_stemmer": { + "type": "stemmer", + "language": "catalan" + }, + "catalan_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "catalan_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "catalan_elision", + "lowercase", + "catalan_stop", + "catalan_keywords", + "catalan_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "catalan_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /catalan-index/_analyze +{ + "field": "content", + "text": "Els estudiants estudien a les universitats catalanes. Els seus números són 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "estud","start_offset": 4,"end_offset": 14,"type": "","position": 1}, + {"token": "estud","start_offset": 15,"end_offset": 23,"type": "","position": 2}, + {"token": "univer","start_offset": 30,"end_offset": 42,"type": "","position": 5}, + {"token": "catalan","start_offset": 43,"end_offset": 52,"type": "","position": 6}, + {"token": "numer","start_offset": 63,"end_offset": 70,"type": "","position": 9}, + {"token": "123456","start_offset": 75,"end_offset": 81,"type": "","position": 11} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/cjk.md b/_analyzers/language-analyzers/cjk.md new file mode 100644 index 00000000..32f12e8f --- /dev/null +++ b/_analyzers/language-analyzers/cjk.md @@ -0,0 +1,151 @@ +--- +layout: default +title: CJK +parent: Language analyzers +grand_parent: Analyzers +nav_order: 80 +--- + +# CJK analyzer + +The built-in `cjk` analyzer is designed for Chinese, Japanese, and Korean (CJK) text. It uses bigram tokenization to break down CJK text into overlapping two-character sequences, which is effective for languages that don't use spaces to separate words. + +You may find that the `icu_analyzer` in the ICU analysis plugin works better for CJK text than the `cjk` analyzer. Experiment with your text and queries. +{: .note} + +The `cjk` analyzer can be applied to a text field using the following command: + +```json +PUT /cjk-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "cjk" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_cjk_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_cjk_analyzer": { + "type": "cjk", + "stem_exclusion": ["example", "words"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## CJK analyzer internals + +The `cjk` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - cjk_width + - lowercase + - cjk_bigram + - stop (similar to English) + +## Custom CJK analyzer + +You can create a custom CJK analyzer using the following command: + +```json +PUT /cjk-index +{ + "settings": { + "analysis": { + "filter": { + "english_stop": { + "type": "stop", + "stopwords": [ + "a", "and", "are", "as", "at", "be", "but", "by", "for", + "if", "in", "into", "is", "it", "no", "not", "of", "on", + "or", "s", "such", "t", "that", "the", "their", "then", + "there", "these", "they", "this", "to", "was", "will", + "with", "www" + ] + } + }, + "analyzer": { + "cjk_custom_analyzer": { + "tokenizer": "standard", + "filter": [ + "cjk_width", + "lowercase", + "cjk_bigram", + "english_stop" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "cjk_custom_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /cjk-index/_analyze +{ + "field": "content", + "text": "学生们在中国、日本和韩国的大学学习。123456" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "学生","start_offset": 0,"end_offset": 2,"type": "","position": 0}, + {"token": "生们","start_offset": 1,"end_offset": 3,"type": "","position": 1}, + {"token": "们在","start_offset": 2,"end_offset": 4,"type": "","position": 2}, + {"token": "在中","start_offset": 3,"end_offset": 5,"type": "","position": 3}, + {"token": "中国","start_offset": 4,"end_offset": 6,"type": "","position": 4}, + {"token": "日本","start_offset": 7,"end_offset": 9,"type": "","position": 5}, + {"token": "本和","start_offset": 8,"end_offset": 10,"type": "","position": 6}, + {"token": "和韩","start_offset": 9,"end_offset": 11,"type": "","position": 7}, + {"token": "韩国","start_offset": 10,"end_offset": 12,"type": "","position": 8}, + {"token": "国的","start_offset": 11,"end_offset": 13,"type": "","position": 9}, + {"token": "的大","start_offset": 12,"end_offset": 14,"type": "","position": 10}, + {"token": "大学","start_offset": 13,"end_offset": 15,"type": "","position": 11}, + {"token": "学学","start_offset": 14,"end_offset": 16,"type": "","position": 12}, + {"token": "学习","start_offset": 15,"end_offset": 17,"type": "","position": 13}, + {"token": "123456","start_offset": 18,"end_offset": 24,"type": "","position": 14} + ] +} +``` + +## Related documentation + +- [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/) -- Alternative for CJK text \ No newline at end of file diff --git a/_analyzers/language-analyzers/czech.md b/_analyzers/language-analyzers/czech.md new file mode 100644 index 00000000..c1778cd0 --- /dev/null +++ b/_analyzers/language-analyzers/czech.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Czech +parent: Language analyzers +grand_parent: Analyzers +nav_order: 90 +--- + +# Czech analyzer + +The built-in `czech` analyzer can be applied to a text field using the following command: + +```json +PUT /czech-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "czech" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_czech_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_czech_analyzer": { + "type": "czech", + "stem_exclusion": ["autorita", "schválení"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Czech analyzer internals + +The `czech` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Czech) + - keyword + - stemmer (Czech) + +## Custom Czech analyzer + +You can create a custom Czech analyzer using the following command: + +```json +PUT /czech-index +{ + "settings": { + "analysis": { + "filter": { + "czech_stop": { + "type": "stop", + "stopwords": "_czech_" + }, + "czech_stemmer": { + "type": "stemmer", + "language": "czech" + }, + "czech_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "czech_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "czech_stop", + "czech_keywords", + "czech_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "czech_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /czech-index/_analyze +{ + "field": "content", + "text": "Studenti studují na českých univerzitách. Jejich čísla jsou 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + }, + { + "token": "studuj", + "start_offset": 9, + "end_offset": 16, + "type": "", + "position": 1 + }, + { + "token": "česk", + "start_offset": 20, + "end_offset": 27, + "type": "", + "position": 3 + }, + { + "token": "univerzit", + "start_offset": 28, + "end_offset": 40, + "type": "", + "position": 4 + }, + { + "token": "čísl", + "start_offset": 49, + "end_offset": 54, + "type": "", + "position": 6 + }, + { + "token": "123456", + "start_offset": 60, + "end_offset": 66, + "type": "", + "position": 8 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/danish.md b/_analyzers/language-analyzers/danish.md new file mode 100644 index 00000000..b5ee1b0e --- /dev/null +++ b/_analyzers/language-analyzers/danish.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Danish +parent: Language analyzers +grand_parent: Analyzers +nav_order: 100 +--- + +# Danish analyzer + +The built-in `danish` analyzer can be applied to a text field using the following command: + +```json +PUT /danish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "danish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_danish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_danish_analyzer": { + "type": "danish", + "stem_exclusion": ["autoritet", "godkendelse"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Danish analyzer internals + +The `danish` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Danish) + - keyword + - stemmer (Danish) + +## Custom Danish analyzer + +You can create a custom Danish analyzer using the following command: + +```json +PUT /danish-index +{ + "settings": { + "analysis": { + "filter": { + "danish_stop": { + "type": "stop", + "stopwords": "_danish_" + }, + "danish_stemmer": { + "type": "stemmer", + "language": "danish" + }, + "danish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "danish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "danish_stop", + "danish_keywords", + "danish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "danish_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /danish-index/_analyze +{ + "field": "content", + "text": "Studerende studerer på de danske universiteter. Deres numre er 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "stud", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "stud", + "start_offset": 11, + "end_offset": 19, + "type": "", + "position": 1 + }, + { + "token": "dansk", + "start_offset": 26, + "end_offset": 32, + "type": "", + "position": 4 + }, + { + "token": "universitet", + "start_offset": 33, + "end_offset": 46, + "type": "", + "position": 5 + }, + { + "token": "numr", + "start_offset": 54, + "end_offset": 59, + "type": "", + "position": 7 + }, + { + "token": "123456", + "start_offset": 63, + "end_offset": 69, + "type": "", + "position": 9 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/dutch.md b/_analyzers/language-analyzers/dutch.md new file mode 100644 index 00000000..0259707d --- /dev/null +++ b/_analyzers/language-analyzers/dutch.md @@ -0,0 +1,148 @@ +--- +layout: default +title: Dutch +parent: Language analyzers +grand_parent: Analyzers +nav_order: 110 +--- + +# Dutch analyzer + +The built-in `dutch` analyzer can be applied to a text field using the following command: + +```json +PUT /dutch-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "dutch" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_dutch_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_dutch_analyzer": { + "type": "dutch", + "stem_exclusion": ["autoriteit", "goedkeuring"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Dutch analyzer internals + +The `dutch` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Dutch) + - keyword + - stemmer_override + - stemmer (Dutch) + +## Custom Dutch analyzer + +You can create a custom Dutch analyzer using the following command: + +```json +PUT /dutch-index +{ + "settings": { + "analysis": { + "filter": { + "dutch_stop": { + "type": "stop", + "stopwords": "_dutch_" + }, + "dutch_stemmer": { + "type": "stemmer", + "language": "dutch" + }, + "dutch_keywords": { + "type": "keyword_marker", + "keywords": [] + }, + "dutch_override": { + "type": "stemmer_override", + "rules": [ + "fiets=>fiets", + "bromfiets=>bromfiets", + "ei=>eier", + "kind=>kinder" + ] + } + }, + "analyzer": { + "dutch_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "dutch_stop", + "dutch_keywords", + "dutch_override", + "dutch_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "dutch_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /dutch-index/_analyze +{ + "field": "content", + "text": "De studenten studeren in Nederland en bezoeken Amsterdam. Hun nummers zijn 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 3,"end_offset": 12,"type": "","position": 1}, + {"token": "studer","start_offset": 13,"end_offset": 21,"type": "","position": 2}, + {"token": "nederland","start_offset": 25,"end_offset": 34,"type": "","position": 4}, + {"token": "bezoek","start_offset": 38,"end_offset": 46,"type": "","position": 6}, + {"token": "amsterdam","start_offset": 47,"end_offset": 56,"type": "","position": 7}, + {"token": "nummer","start_offset": 62,"end_offset": 69,"type": "","position": 9}, + {"token": "123456","start_offset": 75,"end_offset": 81,"type": "","position": 11} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/english.md b/_analyzers/language-analyzers/english.md new file mode 100644 index 00000000..2d0b6003 --- /dev/null +++ b/_analyzers/language-analyzers/english.md @@ -0,0 +1,143 @@ +--- +layout: default +title: English +parent: Language analyzers +grand_parent: Analyzers +nav_order: 120 +--- + +# English analyzer + +The built-in `english` analyzer can be applied to a text field using the following command: + +```json +PUT /english-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "english" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_english_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_english_analyzer": { + "type": "english", + "stem_exclusion": ["authority", "authorization"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## English analyzer internals + +The `english` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - stemmer (possessive_english) + - lowercase + - stop (English) + - keyword + - stemmer (English) + +## Custom English analyzer + +You can create a custom English analyzer using the following command: + +```json +PUT /english-index +{ + "settings": { + "analysis": { + "filter": { + "english_stop": { + "type": "stop", + "stopwords": "_english_" + }, + "english_stemmer": { + "type": "stemmer", + "language": "english" + }, + "english_keywords": { + "type": "keyword_marker", + "keywords": [] + }, + "english_possessive_stemmer": { + "type": "stemmer", + "language": "possessive_english" + } + }, + "analyzer": { + "english_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "english_possessive_stemmer", + "lowercase", + "english_stop", + "english_keywords", + "english_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "english_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /english-index/_analyze +{ + "field": "content", + "text": "The students study in the USA and work at NASA. Their numbers are 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 4,"end_offset": 12,"type": "","position": 1}, + {"token": "studi","start_offset": 13,"end_offset": 18,"type": "","position": 2}, + {"token": "usa","start_offset": 26,"end_offset": 29,"type": "","position": 5}, + {"token": "work","start_offset": 34,"end_offset": 38,"type": "","position": 7}, + {"token": "nasa","start_offset": 42,"end_offset": 46,"type": "","position": 9}, + {"token": "number","start_offset": 54,"end_offset": 61,"type": "","position": 11}, + {"token": "123456","start_offset": 66,"end_offset": 72,"type": "","position": 13} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/estonian.md b/_analyzers/language-analyzers/estonian.md new file mode 100644 index 00000000..a4cb664f --- /dev/null +++ b/_analyzers/language-analyzers/estonian.md @@ -0,0 +1,139 @@ +--- +layout: default +title: Estonian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 130 +--- + +# Estonian analyzer + +The built-in `estonian` analyzer can be applied to a text field using the following command: + +```json +PUT /estonian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "estonian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_estonian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_estonian_analyzer": { + "type": "estonian", + "stem_exclusion": ["autoriteet", "kinnitus"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Estonian analyzer internals + +The `estonian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Estonian) + - keyword + - stemmer (Estonian) + +## Custom Estonian analyzer + +You can create a custom Estonian analyzer using the following command: + +```json +PUT /estonian-index +{ + "settings": { + "analysis": { + "filter": { + "estonian_stop": { + "type": "stop", + "stopwords": "_estonian_" + }, + "estonian_stemmer": { + "type": "stemmer", + "language": "estonian" + }, + "estonian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "estonian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "estonian_stop", + "estonian_keywords", + "estonian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "estonian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /estonian-index/_analyze +{ + "field": "content", + "text": "Õpilased õpivad Tallinnas ja Eesti ülikoolides. Nende numbrid on 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "õpilase","start_offset": 0,"end_offset": 8,"type": "","position": 0}, + {"token": "õpi","start_offset": 9,"end_offset": 15,"type": "","position": 1}, + {"token": "tallinna","start_offset": 16,"end_offset": 25,"type": "","position": 2}, + {"token": "eesti","start_offset": 29,"end_offset": 34,"type": "","position": 4}, + {"token": "ülikooli","start_offset": 35,"end_offset": 46,"type": "","position": 5}, + {"token": "nende","start_offset": 48,"end_offset": 53,"type": "","position": 6}, + {"token": "numbri","start_offset": 54,"end_offset": 61,"type": "","position": 7}, + {"token": "on","start_offset": 62,"end_offset": 64,"type": "","position": 8}, + {"token": "123456","start_offset": 65,"end_offset": 71,"type": "","position": 9} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/finnish.md b/_analyzers/language-analyzers/finnish.md new file mode 100644 index 00000000..6f559650 --- /dev/null +++ b/_analyzers/language-analyzers/finnish.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Finnish +parent: Language analyzers +grand_parent: Analyzers +nav_order: 140 +--- + +# Finnish analyzer + +The built-in `finnish` analyzer can be applied to a text field using the following command: + +```json +PUT /finnish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "finnish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_finnish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_finnish_analyzer": { + "type": "finnish", + "stem_exclusion": ["valta", "hyväksyntä"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Finnish analyzer internals + +The `finnish` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Finnish) + - keyword + - stemmer (Finnish) + +## Custom Finnish analyzer + +You can create a custom Finnish analyzer using the following command: + +```json +PUT /finnish-index +{ + "settings": { + "analysis": { + "filter": { + "finnish_stop": { + "type": "stop", + "stopwords": "_finnish_" + }, + "finnish_stemmer": { + "type": "stemmer", + "language": "finnish" + }, + "finnish_keywords": { + "type": "keyword_marker", + "keywords": ["Helsinki", "Suomi"] + } + }, + "analyzer": { + "finnish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "finnish_stop", + "finnish_keywords", + "finnish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "finnish_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /finnish-index/_analyze +{ + "field": "content", + "text": "Opiskelijat opiskelevat Helsingissä ja Suomen yliopistoissa. Heidän numeronsa ovat 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "opiskelij","start_offset": 0,"end_offset": 11,"type": "","position": 0}, + {"token": "opiskelev","start_offset": 12,"end_offset": 23,"type": "","position": 1}, + {"token": "helsing","start_offset": 24,"end_offset": 35,"type": "","position": 2}, + {"token": "suome","start_offset": 39,"end_offset": 45,"type": "","position": 4}, + {"token": "yliopisto","start_offset": 46,"end_offset": 59,"type": "","position": 5}, + {"token": "numero","start_offset": 68,"end_offset": 77,"type": "","position": 7}, + {"token": "123456","start_offset": 83,"end_offset": 89,"type": "","position": 9} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/french.md b/_analyzers/language-analyzers/french.md new file mode 100644 index 00000000..64e7ab54 --- /dev/null +++ b/_analyzers/language-analyzers/french.md @@ -0,0 +1,148 @@ +--- +layout: default +title: French +parent: Language analyzers +grand_parent: Analyzers +nav_order: 150 +--- + +# French analyzer + +The built-in `french` analyzer can be applied to a text field using the following command: + +```json +PUT /french-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "french" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_french_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_french_analyzer": { + "type": "french", + "stem_exclusion": ["autorité", "acceptation"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## French analyzer internals + +The `french` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - elision (French) + - lowercase + - stop (French) + - keyword + - stemmer (French) + +## Custom French analyzer + +You can create a custom French analyzer using the following command: + +```json +PUT /french-index +{ + "settings": { + "analysis": { + "filter": { + "french_stop": { + "type": "stop", + "stopwords": "_french_" + }, + "french_elision": { + "type": "elision", + "articles_case": true, + "articles": [ + "l", "m", "t", "qu", "n", "s", + "j", "d", "c", "jusqu", "quoiqu", + "lorsqu", "puisqu" + ] + }, + "french_stemmer": { + "type": "stemmer", + "language": "light_french" + }, + "french_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "french_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "french_elision", + "lowercase", + "french_stop", + "french_keywords", + "french_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "french_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /french-index/_analyze +{ + "field": "content", + "text": "Les étudiants étudient à Paris et dans les universités françaises. Leurs numéros sont 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "etudiant","start_offset": 4,"end_offset": 13,"type": "","position": 1}, + {"token": "etudient","start_offset": 14,"end_offset": 22,"type": "","position": 2}, + {"token": "pari","start_offset": 25,"end_offset": 30,"type": "","position": 4}, + {"token": "universit","start_offset": 43,"end_offset": 54,"type": "","position": 8}, + {"token": "francais","start_offset": 55,"end_offset": 65,"type": "","position": 9}, + {"token": "numero","start_offset": 73,"end_offset": 80,"type": "","position": 11}, + {"token": "123456","start_offset": 86,"end_offset": 92,"type": "","position": 13} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/galician.md b/_analyzers/language-analyzers/galician.md new file mode 100644 index 00000000..1fba1420 --- /dev/null +++ b/_analyzers/language-analyzers/galician.md @@ -0,0 +1,138 @@ +--- +layout: default +title: Galician +parent: Language analyzers +grand_parent: Analyzers +nav_order: 160 +--- + +# Galician analyzer + +The built-in `galician` analyzer can be applied to a text field using the following command: + +```json +PUT /galician-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "galician" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_galician_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_galician_analyzer": { + "type": "galician", + "stem_exclusion": ["autoridade", "aceptación"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Galician analyzer internals + +The `galician` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Galician) + - keyword + - stemmer (Galician) + +## Custom Galician analyzer + +You can create a custom Galician analyzer using the following command: + +```json +PUT /galician-index +{ + "settings": { + "analysis": { + "filter": { + "galician_stop": { + "type": "stop", + "stopwords": "_galician_" + }, + "galician_stemmer": { + "type": "stemmer", + "language": "galician" + }, + "galician_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "galician_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "galician_stop", + "galician_keywords", + "galician_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "galician_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /galician-index/_analyze +{ + "field": "content", + "text": "Os estudantes estudan en Santiago e nas universidades galegas. Os seus números son 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "estud","start_offset": 3,"end_offset": 13,"type": "","position": 1}, + {"token": "estud","start_offset": 14,"end_offset": 21,"type": "","position": 2}, + {"token": "santiag","start_offset": 25,"end_offset": 33,"type": "","position": 4}, + {"token": "univers","start_offset": 40,"end_offset": 53,"type": "","position": 7}, + {"token": "galeg","start_offset": 54,"end_offset": 61,"type": "","position": 8}, + {"token": "numer","start_offset": 71,"end_offset": 78,"type": "","position": 11}, + {"token": "son","start_offset": 79,"end_offset": 82,"type": "","position": 12}, + {"token": "123456","start_offset": 83,"end_offset": 89,"type": "","position": 13} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/german.md b/_analyzers/language-analyzers/german.md new file mode 100644 index 00000000..4071ef53 --- /dev/null +++ b/_analyzers/language-analyzers/german.md @@ -0,0 +1,174 @@ +--- +layout: default +title: German +parent: Language analyzers +grand_parent: Analyzers +nav_order: 170 +--- + +# German analyzer + +The built-in `german` analyzer can be applied to a text field using the following command: + +```json +PUT /german-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "german" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_german_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_german_analyzer": { + "type": "german", + "stem_exclusion": ["Autorität", "Genehmigung"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## German analyzer internals + +The `german` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (German) + - keyword + - normalization (German) + - stemmer (German) + +## Custom German analyzer + +You can create a custom German analyzer using the following command: + +```json +PUT /german-index +{ + "settings": { + "analysis": { + "filter": { + "german_stop": { + "type": "stop", + "stopwords": "_german_" + }, + "german_stemmer": { + "type": "stemmer", + "language": "light_german" + }, + "german_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "german_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "german_stop", + "german_keywords", + "german_normalization", + "german_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "german_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /german-index/_analyze +{ + "field": "content", + "text": "Die Studenten studieren an den deutschen Universitäten. Ihre Nummern sind 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 4, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "studi", + "start_offset": 14, + "end_offset": 23, + "type": "", + "position": 2 + }, + { + "token": "deutsch", + "start_offset": 31, + "end_offset": 40, + "type": "", + "position": 5 + }, + { + "token": "universitat", + "start_offset": 41, + "end_offset": 54, + "type": "", + "position": 6 + }, + { + "token": "numm", + "start_offset": 61, + "end_offset": 68, + "type": "", + "position": 8 + }, + { + "token": "123456", + "start_offset": 74, + "end_offset": 80, + "type": "", + "position": 10 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/greek.md b/_analyzers/language-analyzers/greek.md new file mode 100644 index 00000000..2c5aa375 --- /dev/null +++ b/_analyzers/language-analyzers/greek.md @@ -0,0 +1,190 @@ +--- +layout: default +title: Greek +parent: Language analyzers +grand_parent: Analyzers +nav_order: 180 +--- + +# Greek analyzer + +The built-in `greek` analyzer can be applied to a text field using the following command: + +```json +PUT /greek-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "greek" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_greek_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_greek_analyzer": { + "type": "greek", + "stem_exclusion": ["αρχή", "έγκριση"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Greek analyzer internals + +The `greek` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Greek) + - keyword + - stemmer (Greek) + +## Custom Greek analyzer + +You can create a custom Greek analyzer using the following command: + +```json +PUT /greek-index +{ + "settings": { + "analysis": { + "filter": { + "greek_stop": { + "type": "stop", + "stopwords": "_greek_" + }, + "greek_lowercase": { + "type": "lowercase", + "language": "greek" + }, + "greek_stemmer": { + "type": "stemmer", + "language": "greek" + }, + "greek_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "greek_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "greek_lowercase", + "greek_stop", + "greek_keywords", + "greek_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "greek_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /greek-index/_analyze +{ + "field": "content", + "text": "Οι φοιτητές σπουδάζουν στα ελληνικά πανεπιστήμια. Οι αριθμοί τους είναι 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "φοιτητ", + "start_offset": 3, + "end_offset": 11, + "type": "", + "position": 1 + }, + { + "token": "σπουδαζ", + "start_offset": 12, + "end_offset": 22, + "type": "", + "position": 2 + }, + { + "token": "στα", + "start_offset": 23, + "end_offset": 26, + "type": "", + "position": 3 + }, + { + "token": "ελλην", + "start_offset": 27, + "end_offset": 35, + "type": "", + "position": 4 + }, + { + "token": "πανεπιστημ", + "start_offset": 36, + "end_offset": 48, + "type": "", + "position": 5 + }, + { + "token": "αριθμ", + "start_offset": 53, + "end_offset": 60, + "type": "", + "position": 7 + }, + { + "token": "τ", + "start_offset": 61, + "end_offset": 65, + "type": "", + "position": 8 + }, + { + "token": "123456", + "start_offset": 72, + "end_offset": 78, + "type": "", + "position": 10 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/hindi.md b/_analyzers/language-analyzers/hindi.md new file mode 100644 index 00000000..93f2eea3 --- /dev/null +++ b/_analyzers/language-analyzers/hindi.md @@ -0,0 +1,178 @@ +--- +layout: default +title: Hindi +parent: Language analyzers +grand_parent: Analyzers +nav_order: 190 +--- + +# Hindi analyzer + +The built-in `hindi` analyzer can be applied to a text field using the following command: + +```json +PUT /hindi-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hindi" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_hindi_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_hindi_analyzer": { + "type": "hindi", + "stem_exclusion": ["अधिकार", "अनुमोदन"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Hindi analyzer internals + +The `hindi` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - decimal_digit + - keyword + - normalization (indic) + - normalization (Hindi) + - stop (Hindi) + - stemmer (Hindi) + +## Custom Hindi analyzer + +You can create a custom Hindi analyzer using the following command: + +```json +PUT /hindi-index +{ + "settings": { + "analysis": { + "filter": { + "hindi_stop": { + "type": "stop", + "stopwords": "_hindi_" + }, + "hindi_stemmer": { + "type": "stemmer", + "language": "hindi" + }, + "hindi_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "hindi_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "decimal_digit", + "hindi_keywords", + "indic_normalization", + "hindi_normalization", + "hindi_stop", + "hindi_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hindi_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /hindi-index/_analyze +{ + "field": "content", + "text": "छात्र भारतीय विश्वविद्यालयों में पढ़ते हैं। उनके नंबर १२३४५६ हैं।" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "छातर", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "भारतिय", + "start_offset": 6, + "end_offset": 12, + "type": "", + "position": 1 + }, + { + "token": "विशवविदयालय", + "start_offset": 13, + "end_offset": 28, + "type": "", + "position": 2 + }, + { + "token": "पढ", + "start_offset": 33, + "end_offset": 38, + "type": "", + "position": 4 + }, + { + "token": "नंबर", + "start_offset": 49, + "end_offset": 53, + "type": "", + "position": 7 + }, + { + "token": "123456", + "start_offset": 54, + "end_offset": 60, + "type": "", + "position": 8 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/hungarian.md b/_analyzers/language-analyzers/hungarian.md new file mode 100644 index 00000000..d115c5d2 --- /dev/null +++ b/_analyzers/language-analyzers/hungarian.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Hungarian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 200 +--- + +# Hungarian analyzer + +The built-in `hungarian` analyzer can be applied to a text field using the following command: + +```json +PUT /hungarian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hungarian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_hungarian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_hungarian_analyzer": { + "type": "hungarian", + "stem_exclusion": ["hatalom", "jóváhagyás"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Hungarian analyzer internals + +The `hungarian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Hungarian) + - keyword + - stemmer (Hungarian) + +## Custom Hungarian analyzer + +You can create a custom Hungarian analyzer using the following command: + +```json +PUT /hungarian-index +{ + "settings": { + "analysis": { + "filter": { + "hungarian_stop": { + "type": "stop", + "stopwords": "_hungarian_" + }, + "hungarian_stemmer": { + "type": "stemmer", + "language": "hungarian" + }, + "hungarian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "hungarian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "hungarian_stop", + "hungarian_keywords", + "hungarian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hungarian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /hungarian-index/_analyze +{ + "field": "content", + "text": "A diákok a magyar egyetemeken tanulnak. A számaik 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "diák", + "start_offset": 2, + "end_offset": 8, + "type": "", + "position": 1 + }, + { + "token": "magyar", + "start_offset": 11, + "end_offset": 17, + "type": "", + "position": 3 + }, + { + "token": "egyetem", + "start_offset": 18, + "end_offset": 29, + "type": "", + "position": 4 + }, + { + "token": "tanul", + "start_offset": 30, + "end_offset": 38, + "type": "", + "position": 5 + }, + { + "token": "szám", + "start_offset": 42, + "end_offset": 49, + "type": "", + "position": 7 + }, + { + "token": "123456", + "start_offset": 50, + "end_offset": 56, + "type": "", + "position": 8 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/icu.md b/_analyzers/language-analyzers/icu.md new file mode 100644 index 00000000..d237be2b --- /dev/null +++ b/_analyzers/language-analyzers/icu.md @@ -0,0 +1,281 @@ +--- +layout: default +title: ICU +parent: Language analyzers +grand_parent: Analyzers +nav_order: 205 +--- + +# ICU analyzer + +The `icu_analyzer` uses the International Components for Unicode (ICU) library to provide advanced text analysis for multilingual content. Available through the `analysis-icu` plugin, this analyzer excels at processing languages with complex writing systems, including Chinese, Japanese, Korean, Thai, Arabic, and Hebrew. + +Unlike the standard analyzer, the `icu_analyzer` applies Unicode-aware text segmentation that recognizes word boundaries in languages that don't use spaces as delimiters. The analyzer combines ICU tokenization with character normalization and case folding to produce consistent, searchable tokens across diverse language families. + +## Installing the ICU plugin + +Before using the `icu_analyzer`, you must install the `analysis-icu` plugin: + +```bash +bin/opensearch-plugin install analysis-icu +``` +{% include copy.html %} + +After installation, restart your OpenSearch cluster for the plugin to take effect. + +For more information about installing plugins, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). + +## ICU plugin components + +The `analysis-icu` plugin provides several components that can be used independently or combined in custom analyzers. The built-in `icu_analyzer` uses a combination of these components. + +### Tokenizer + +- [`icu_tokenizer`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/icu-tokenizer/): Tokenizes text using ICU Unicode text segmentation rules. More accurate than the standard tokenizer for languages without spaces between words. + +### Character filters + +- [`icu_normalizer`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/icu-normalization/): Normalizes characters to their canonical Unicode forms. Can be configured with different normalization modes (NFC, NFD, NFKC, NFKD). + +### Token filters + +- `icu_normalizer`: Normalizes tokens to canonical Unicode forms (same as character filter but operates on tokens). +- [`icu_folding`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/icu-folding/): Performs Unicode normalization and case folding, including removal of diacritics. More comprehensive than the `asciifolding` filter. +- [`icu_transform`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/icu-transform/): Applies ICU transforms for transliteration, such as converting between scripts (for example, Cyrillic to Latin). + +### Field types + +- [`icu_collation_keyword`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/icu-collation-keyword/): Provides language-specific collation for sorting and range queries. + + +## How the ICU analyzer works + +The `icu_analyzer` applies a sequence of transformations to input text: + +- **Tokenization**: Breaks text into tokens using the ICU Unicode text segmentation algorithm. This approach identifies word boundaries accurately in languages like Chinese, Japanese, Korean, and Thai, where spaces don't separate words. +- **Normalization**: Converts characters to canonical Unicode forms, resolving variations in how diacritics, ligatures, and composite characters are represented. +- **Case folding**: Applies comprehensive case transformations that handle language-specific rules, such as the Turkish İ/i distinction, more effectively than basic lowercasing. +- **Character filtering**: Standardizes equivalent Unicode representations and removes non-textual elements from the token stream. + +## When to use the ICU analyzer + +Consider using the `icu_analyzer` for the following use cases: + +- **CJK content**: Chinese, Japanese, and Korean text benefits from ICU word segmentation capabilities, which identify natural word boundaries more accurately than bigram approaches. +- **Southeast Asian languages**: Thai, Khmer, Lao, and similar languages that require dictionary-based or rule-based word boundary detection. +- **Right-to-left scripts**: Arabic, Hebrew, and other RTL writing systems where proper character normalization is essential. +- **Diacritical marks**: Content with accented characters, umlauts, or other diacritics that need consistent normalization. +- **Multilingual applications**: Search indexes containing multiple languages that require uniform text processing. +- **Unicode-heavy content**: Documents with special Unicode characters, ligatures, or combining marks. + +The `icu_analyzer` provides superior word boundary detection for CJK text compared to the `cjk` analyzer's bigram tokenization method. +{: .note} + +## Comparison with other analyzers + +The following table compares the ICU analyzer with other analyzers. + +| Analyzer | Best for | Tokenization method | +|:---------|:---------|:-------------------| +| `standard` | General-purpose, European languages | Unicode text segmentation (space-based) | +| `cjk` | Chinese, Japanese, Korean | Bigram tokenization (overlapping 2-character sequences) | +| `icu_analyzer` | Multilingual, complex scripts, CJK | ICU Unicode text segmentation (language-aware) | + +## Performance considerations + +The `icu_analyzer` uses more computational resources than basic analyzers because of its sophisticated Unicode processing and language-aware tokenization. The analyzer requires additional memory for ICU data tables and consumes more CPU cycles during text analysis compared to the `standard` or `cjk` analyzers. + +For most search applications, the accuracy improvements justify the performance overhead, particularly when handling non-Latin scripts or multilingual content. The impact is most noticeable during indexing; query-time analysis has minimal effect on search latency. + +Evaluate the `icu_analyzer` with representative data from your use case to verify that performance meets your requirements. +{: .tip} + + +## Example: Using the ICU analyzer + +You can assign the `icu_analyzer` to a text field when creating an index: + +```json +PUT /multilingual-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "icu_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example: Analyzing text with the ICU analyzer + +Use the following request to see how the `icu_analyzer` processes multilingual text: + +```json +POST /_analyze +{ + "analyzer": "icu_analyzer", + "text": "東京は日本の首都です。OpenSearch supports advanced Unicode processing with café and naïve!" +} +``` +{% include copy-curl.html %} + +The analyzer tokenizes Japanese characters at natural word boundaries and normalizes accented Latin characters. In this example, `café` becomes `cafe` and `naïve` becomes `naive` through Unicode case folding. The response demonstrates proper segmentation of both Japanese and English text: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "", + "position": 0 + }, + { + "token": "は", + "start_offset": 2, + "end_offset": 3, + "type": "", + "position": 1 + }, + { + "token": "日本", + "start_offset": 3, + "end_offset": 5, + "type": "", + "position": 2 + }, + { + "token": "の", + "start_offset": 5, + "end_offset": 6, + "type": "", + "position": 3 + }, + { + "token": "首都", + "start_offset": 6, + "end_offset": 8, + "type": "", + "position": 4 + }, + { + "token": "てす", + "start_offset": 8, + "end_offset": 10, + "type": "", + "position": 5 + }, + { + "token": "opensearch", + "start_offset": 11, + "end_offset": 21, + "type": "", + "position": 6 + }, + { + "token": "supports", + "start_offset": 22, + "end_offset": 30, + "type": "", + "position": 7 + }, + { + "token": "advanced", + "start_offset": 31, + "end_offset": 39, + "type": "", + "position": 8 + }, + { + "token": "unicode", + "start_offset": 40, + "end_offset": 47, + "type": "", + "position": 9 + }, + { + "token": "processing", + "start_offset": 48, + "end_offset": 58, + "type": "", + "position": 10 + }, + { + "token": "with", + "start_offset": 59, + "end_offset": 63, + "type": "", + "position": 11 + }, + { + "token": "cafe", + "start_offset": 64, + "end_offset": 68, + "type": "", + "position": 12 + }, + { + "token": "and", + "start_offset": 69, + "end_offset": 72, + "type": "", + "position": 13 + }, + { + "token": "naive", + "start_offset": 73, + "end_offset": 78, + "type": "", + "position": 14 + } + ] +} +``` + +## Custom ICU analyzer + +You can create a custom analyzer using ICU components with specific configuration: + +```json +PUT /custom-icu-index +{ + "settings": { + "analysis": { + "analyzer": { + "my_icu_analyzer": { + "type": "custom", + "tokenizer": "icu_tokenizer", + "filter": [ + "icu_normalizer", + "icu_folding" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_icu_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Related documentation + +- [ICU tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/icu-tokenizer/) -- Unicode text segmentation +- [ICU normalization character filter]({{site.url}}{{site.baseurl}}/analyzers/character-filters/icu-normalization/) -- Character-level Unicode normalization +- [ICU folding token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/icu-folding/) -- Case folding and diacritic removal +- [ICU transform token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/icu-transform/) -- Transliteration and text transformation +- [ICU collation keyword field]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/icu-collation-keyword/) -- Language-specific sorting +- [CJK analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/cjk/) -- Alternative for CJK text +- [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#installing-plugins) -- Plugin installation guide diff --git a/_analyzers/language-analyzers/index.md b/_analyzers/language-analyzers/index.md new file mode 100644 index 00000000..b8175b6f --- /dev/null +++ b/_analyzers/language-analyzers/index.md @@ -0,0 +1,139 @@ +--- +layout: default +title: Language analyzers +nav_order: 140 +parent: Analyzers +has_children: true +has_toc: true +redirect_from: + - /query-dsl/analyzers/language-analyzers/ + - /analyzers/language-analyzers/ +--- + +# Language analyzers + +OpenSearch supports the following language analyzers: +`arabic`, `armenian`, `basque`, `bengali`, `brazilian`, `bulgarian`, `catalan`, `czech`, `danish`, `dutch`, `english`, `estonian`, `finnish`, `french`, `galician`, `german`, `greek`, `hindi`, `hungarian`, `indonesian`, `irish`, `italian`, [`kuromoji`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) (Japanese analyzer; requires plugin), `latvian`, `lithuanian`, `norwegian`, `persian`, [`polish`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/polish/) (requires plugin), `portuguese`, `romanian`, `russian`, `sorani`, `spanish`, `swedish`, `thai`, `turkish`, and [`ukrainian`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/ukrainian/) (requires plugin). + +For multilingual text processing with advanced Unicode support, OpenSearch also provides the [`icu_analyzer`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/), which offers superior text segmentation for languages with complex scripts such as Chinese, Japanese, Korean, Thai, and Arabic (requires the `analysis-icu` plugin). + +To use an analyzer when you map an index, specify the value in your query. For example, to map your index with the French language analyzer, specify the `french` value in the analyzer field: + +```json + "analyzer": "french" +``` + +#### Example request + +The following query specifies an index `my-index` with the `content` field configured as multi-field, and a sub-field named `french` is configured with the `french` language analyzer: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "fields": { + "french": { + "type": "text", + "analyzer": "french" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The default `french` analyzer can also be configured for the entire index using the following query: + +```json +PUT my-index +{ + "settings": { + "analysis": { + "analyzer": { + "default": { + "type": "french" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text" + }, + "title": { + "type": "text" + }, + "description": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +To search documents written in several languages, you can detect the language of each document during ingestion and copy its text to a field that uses the matching language analyzer. For a complete example, see [Identifying document language for multilingual search]({{site.url}}{{site.baseurl}}/tutorials/language-identification/). + +## Stem exclusion + +You can apply stem exclusion to any language analyzer by providing a list of lowercase words that should be excluded from stemming. Internally, OpenSearch uses the `keyword_marker` token filter to mark these words as keywords, ensuring that they are not stemmed. + +## Stem exclusion example + +Use the following request to configure `stem_exclusion`: + +```json +PUT index_with_stem_exclusion_english_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_english_analyzer":{ + "type":"english", + "stem_exclusion": ["manager", "management"] + } + } + } + } +} +``` +{% include copy-curl.html %} + + +## Stem exclusion with custom analyzers + +All language analyzers consist of tokenizers and token filters specific to a particular language. If you want to implement a custom version of the language analyzer with stem exclusion, you need to configure the `keyword_marker` token filter and list the words excluded from stemming in the `keywords` parameter: + +```json +PUT index_with_keyword_marker_analyzer +{ + "settings": { + "analysis": { + "filter": { + "protected_keywords_filter": { + "type": "keyword_marker", + "keywords": ["Apple", "OpenSearch"] + } + }, + "analyzer": { + "custom_english_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "protected_keywords_filter", + "english_stemmer" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_analyzers/language-analyzers/indonesian.md b/_analyzers/language-analyzers/indonesian.md new file mode 100644 index 00000000..091eb223 --- /dev/null +++ b/_analyzers/language-analyzers/indonesian.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Indonesian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 210 +--- + +# Indonesian analyzer + +The built-in `indonesian` analyzer can be applied to a text field using the following command: + +```json +PUT /indonesian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "indonesian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_indonesian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_indonesian_analyzer": { + "type": "indonesian", + "stem_exclusion": ["otoritas", "persetujuan"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Indonesian analyzer internals + +The `indonesian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Indonesian) + - keyword + - stemmer (Indonesian) + +## Custom Indonesian analyzer + +You can create a custom Indonesian analyzer using the following command: + +```json +PUT /indonesian-index +{ + "settings": { + "analysis": { + "filter": { + "indonesian_stop": { + "type": "stop", + "stopwords": "_indonesian_" + }, + "indonesian_stemmer": { + "type": "stemmer", + "language": "indonesian" + }, + "indonesian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "indonesian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "indonesian_stop", + "indonesian_keywords", + "indonesian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "indonesian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /indonesian-index/_analyze +{ + "field": "content", + "text": "Mahasiswa belajar di universitas Indonesia. Nomor mereka adalah 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "mahasiswa", + "start_offset": 0, + "end_offset": 9, + "type": "", + "position": 0 + }, + { + "token": "ajar", + "start_offset": 10, + "end_offset": 17, + "type": "", + "position": 1 + }, + { + "token": "universitas", + "start_offset": 21, + "end_offset": 32, + "type": "", + "position": 3 + }, + { + "token": "indonesia", + "start_offset": 33, + "end_offset": 42, + "type": "", + "position": 4 + }, + { + "token": "nomor", + "start_offset": 44, + "end_offset": 49, + "type": "", + "position": 5 + }, + { + "token": "123456", + "start_offset": 64, + "end_offset": 70, + "type": "", + "position": 8 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/irish.md b/_analyzers/language-analyzers/irish.md new file mode 100644 index 00000000..3e1535d1 --- /dev/null +++ b/_analyzers/language-analyzers/irish.md @@ -0,0 +1,157 @@ +--- +layout: default +title: Irish +parent: Language analyzers +grand_parent: Analyzers +nav_order: 210 +--- + +# Irish analyzer + +The built-in `irish` analyzer can be applied to a text field using the following command: + +```json +PUT /irish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "irish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_irish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_irish_analyzer": { + "type": "irish", + "stem_exclusion": ["údarás", "faomhadh"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Irish analyzer internals + +The `irish` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - hyphenation (Irish) + - elision (Irish) + - lowercase (Irish) + - stop (Irish) + - keyword + - stemmer (Irish) + +## Custom Irish analyzer + +You can create a custom Irish analyzer using the following command: + +```json +PUT /irish-index +{ + "settings": { + "analysis": { + "filter": { + "irish_stop": { + "type": "stop", + "stopwords": "_irish_" + }, + "irish_elision": { + "type": "elision", + "articles": [ "d", "m", "b" ], + "articles_case": true + }, + "irish_hyphenation": { + "type": "stop", + "stopwords": [ "h", "n", "t" ], + "ignore_case": true + }, + "irish_lowercase": { + "type": "lowercase", + "language": "irish" + }, + "irish_stemmer": { + "type": "stemmer", + "language": "irish" + }, + "irish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "irish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "irish_hyphenation", + "irish_elision", + "irish_lowercase", + "irish_stop", + "irish_keywords", + "irish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "irish_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /irish-index/_analyze +{ + "field": "content", + "text": "Tá mic léinn ag staidéar in ollscoileanna na hÉireann. Is iad a gcuid uimhreacha ná 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "tá","start_offset": 0,"end_offset": 2,"type": "","position": 0}, + {"token": "mic","start_offset": 3,"end_offset": 6,"type": "","position": 1}, + {"token": "léinn","start_offset": 7,"end_offset": 12,"type": "","position": 2}, + {"token": "staidéar","start_offset": 16,"end_offset": 24,"type": "","position": 4}, + {"token": "ollscoileanna","start_offset": 28,"end_offset": 41,"type": "","position": 6}, + {"token": "héireann","start_offset": 45,"end_offset": 53,"type": "","position": 8}, + {"token": "cuid","start_offset": 64,"end_offset": 69,"type": "","position": 12}, + {"token": "uimhreacha","start_offset": 70,"end_offset": 80,"type": "","position": 13}, + {"token": "123456","start_offset": 84,"end_offset": 90,"type": "","position": 15} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/italian.md b/_analyzers/language-analyzers/italian.md new file mode 100644 index 00000000..190056d6 --- /dev/null +++ b/_analyzers/language-analyzers/italian.md @@ -0,0 +1,148 @@ +--- +layout: default +title: Italian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 220 +--- + +# Italian analyzer + +The built-in `italian` analyzer can be applied to a text field using the following command: + +```json +PUT /italian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "italian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_italian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_italian_analyzer": { + "type": "italian", + "stem_exclusion": ["autorità", "approvazione"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Italian analyzer internals + +The `italian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - elision (Italian) + - lowercase + - stop (Italian) + - keyword + - stemmer (Italian) + +## Custom Italian analyzer + +You can create a custom Italian analyzer using the following command: + +```json +PUT /italian-index +{ + "settings": { + "analysis": { + "filter": { + "italian_stop": { + "type": "stop", + "stopwords": "_italian_" + }, + "italian_elision": { + "type": "elision", + "articles": [ + "c", "l", "all", "dall", "dell", + "nell", "sull", "coll", "pell", + "gl", "agl", "dagl", "degl", "negl", + "sugl", "un", "m", "t", "s", "v", "d" + ], + "articles_case": true + }, + "italian_stemmer": { + "type": "stemmer", + "language": "light_italian" + }, + "italian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "italian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "italian_elision", + "lowercase", + "italian_stop", + "italian_keywords", + "italian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "italian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /italian-index/_analyze +{ + "field": "content", + "text": "Gli studenti studiano nelle università italiane. I loro numeri sono 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 4,"end_offset": 12,"type": "","position": 1}, + {"token": "studian","start_offset": 13,"end_offset": 21,"type": "","position": 2}, + {"token": "universit","start_offset": 28,"end_offset": 38,"type": "","position": 4}, + {"token": "italian","start_offset": 39,"end_offset": 47,"type": "","position": 5}, + {"token": "numer","start_offset": 56,"end_offset": 62,"type": "","position": 8}, + {"token": "123456","start_offset": 68,"end_offset": 74,"type": "","position": 10} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/kuromoji.md b/_analyzers/language-analyzers/kuromoji.md new file mode 100644 index 00000000..294f7a02 --- /dev/null +++ b/_analyzers/language-analyzers/kuromoji.md @@ -0,0 +1,386 @@ +--- +layout: default +title: Kuromoji (Japanese) +parent: Language analyzers +grand_parent: Analyzers +nav_order: 225 +--- + +# Kuromoji analyzer + +The `kuromoji` analyzer provides morphological analysis for Japanese text using the Kuromoji library backed by the IPAdic dictionary. It segments Japanese sentences into meaningful tokens, removes common stop words and grammatical particles, and returns tokens in their dictionary base form. + +To use the `kuromoji` analyzer or any Kuromoji components, you must first install the `analysis-kuromoji` plugin. + +## Installing the plugin + +Install the plugin on all nodes and then restart the cluster: + +```bash +bin/opensearch-plugin install analysis-kuromoji +``` +{% include copy.html %} + +For more information about installing plugins, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). + +## Kuromoji plugin components + +The `analysis-kuromoji` plugin provides the following components that you can use independently or combine in custom analyzers. + +### Analyzers + +| Analyzer | Description | +|:---------|:------------| +| [`kuromoji`](#analysis-pipeline) | Built-in Japanese analyzer. Segments text, removes stop words, and normalizes tokens to their base form. | +| [`kuromoji_completion`](#kuromoji-completion-analyzer) | Analyzer designed for autocomplete of Japanese text. Generates the original Japanese tokens along with their romaji reading variants. | + +### Tokenizer + +| Tokenizer | Description | +|:----------|:------------| +| [`kuromoji_tokenizer`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) | Dictionary-based Japanese tokenizer with configurable segmentation modes. | + +### Character filter + +| Character filter | Description | +|:----------------|:------------| +| [`kuromoji_iteration_mark`]({{site.url}}{{site.baseurl}}/analyzers/character-filters/kuromoji-iteration-mark/) | Normalizes Japanese iteration marks (々, ゝ, ゞ, ヽ, and ヾ) by expanding them to the character they repeat. | + +### Token filters + +| Token filter | Description | +|:------------|:------------| +| [`kuromoji_baseform`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-baseform/) | Replaces inflected tokens with their dictionary base form. | +| [`kuromoji_part_of_speech`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/) | Removes tokens whose part-of-speech tag is in a configured stop-tag list. | +| [`kuromoji_readingform`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-readingform/) | Replaces each token with its katakana or romaji reading. | +| [`kuromoji_stemmer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-stemmer/) | Removes trailing long vowel marks (ー) from katakana words. | +| [`ja_stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ja-stop/) | Removes Japanese stop words from the token stream. | +| [`kuromoji_number`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-number/) | Converts Japanese numeral expressions to standard Arabic numerals. | +| [`kuromoji_completion`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-completion/) | Generates romaji reading variants for katakana tokens to support autocomplete. | + +## Analysis pipeline + +The `kuromoji` analyzer applies the following components to input text, in order: + +1. The `cjk_width` character filter converts full-width ASCII variants to their standard ASCII equivalents and half-width katakana variants to full-width katakana before tokenization. +2. The `kuromoji_tokenizer` in `search` mode segments text using the IPAdic dictionary, splitting long compound words into their sub-tokens. +3. The `kuromoji_baseform` token filter replaces inflected verb and adjective forms with their dictionary forms (for example, 食べた becomes 食べる). +4. The `kuromoji_part_of_speech` token filter removes grammatical particles (助詞), auxiliary verbs (助動詞), punctuation (記号), and other stop tags. +5. The `ja_stop` token filter removes common Japanese stop words. +6. The `kuromoji_stemmer` token filter removes trailing long vowel marks (ー) from katakana words of four or more characters (for example, コンピューター becomes コンピュータ). +7. The `lowercase` token filter converts any Latin characters to lowercase. + +## Parameters + +The following table lists the parameters for the `kuromoji` analyzer. + +Parameter | Data type | Description +:--- | :--- | :--- +`mode` | String | Tokenization mode. Valid values are `normal`, `search` (default), and `extended`. See [Tokenization modes](#tokenization-modes) for details. +`user_dictionary` | String | Path to a custom user dictionary file (CSV format) placed in the OpenSearch config directory. Optional. +`user_dictionary_rules` | Array of strings | Inline custom dictionary rules in CSV format. Each entry is `,,,`. Optional. Cannot be used together with `user_dictionary`. +`stopwords` | String or array of strings | Stop words to use. Accepts `_japanese_` (the built-in Japanese stop set), an array of explicit stop words, or a path to a stop word file. Default is `_japanese_`. + +For the full list of stop words in the built-in stop set, see [stopwords.txt](https://github.com/apache/lucene/blob/main/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stopwords.txt) in the Lucene repository. + +## Tokenization modes + +The tokenizer mode controls how compound and unknown words are segmented. + +| Mode | Effect | +|:-----|:-------| +| `normal` | Standard dictionary-based segmentation. Compound words are kept as a single token. Unknown words are kept as a single token. | +| `search` (default) | Like `normal`, but compound words (for example, place names) are also split into their sub-components, improving recall for search queries. | +| `extended` | Like `normal`, but unknown words are split into unigrams (individual characters), ensuring that every character is indexed. | + +## Example: Basic usage + +The following example creates an index that uses the built-in `kuromoji` analyzer: + +```json +PUT /japanese-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "kuromoji" + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with a Japanese sentence meaning "I studied at the Tokyo library": + +```json +POST /_analyze +{ + "analyzer": "kuromoji", + "text": "東京の図書館で勉強しました" +} +``` +{% include copy-curl.html %} + +The analyzer returns base-form tokens with particles and auxiliary verbs removed: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "図書館", + "start_offset": 3, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "勉強", + "start_offset": 7, + "end_offset": 9, + "type": "word", + "position": 4 + } + ] +} +``` + +## Example: Custom Kuromoji analyzer + +The following example creates a custom `kuromoji` analyzer that uses `user_dictionary_rules` to register inline custom terms: + +```json +PUT /japanese-custom-index +{ + "settings": { + "analysis": { + "analyzer": { + "my_kuromoji": { + "type": "kuromoji", + "mode": "search", + "user_dictionary_rules": [ + "東京スカイツリー,東京 スカイツリー,トウキョウ スカイツリー,カスタム名詞" + ] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "my_kuromoji" + } + } + } +} +``` +{% include copy-curl.html %} + +Test the custom analyzer with a sentence containing the registered term ("I went to Tokyo Skytree"): + +```json +POST /japanese-custom-index/_analyze +{ + "analyzer": "my_kuromoji", + "text": "東京スカイツリーに行きました" +} +``` +{% include copy-curl.html %} + +The analyzer uses the custom dictionary rule to segment `東京スカイツリー` into `東京` and `スカイツリー`. The default katakana stemmer (`kuromoji_stemmer`) removes the trailing long vowel mark from `スカイツリー` to produce `スカイツリ`. The `kuromoji_part_of_speech` filter removes the particle `に` and the auxiliary verbs `まし` and `た`, and `kuromoji_baseform` normalizes `行き` to its base form `行く`: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "スカイツリ", + "start_offset": 2, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "行く", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 3 + } + ] +} +``` + +## Kuromoji completion analyzer + +The `kuromoji_completion` analyzer is designed for autocomplete use cases. It generates both the original Japanese tokens and their romaji (Latin script) reading variants, allowing users to search for Japanese content by typing in either Japanese characters or their romanized equivalents. In `query` mode, the analyzer also assembles partial input from an input method editor (IME) into a single token before romanizing it. + +The following table lists the parameters for the `kuromoji_completion` analyzer. + +Parameter | Data type | Description +:--- | :--- | :--- +`mode` | String | Controls how tokens are generated. Valid values are `index` (default) and `query`. Both modes expand katakana tokens into their original form plus all romaji variants. The `query` mode applies two additional rules for handling partial IME input: it concatenates consecutive kana tokens into a single token before romanizing, and it merges a kana token with a trailing lowercase alphabet token that represents a partially typed IME keystroke (for example, `サッ` followed by `k` becomes `サッk`). +`user_dictionary` | String | Path to a custom user dictionary file. Optional. +`user_dictionary_rules` | Array of strings | Inline custom dictionary rules. Optional. + +Use `query` mode in the search analyzer so that partial IME input typed by a user is correctly assembled before romanization. +{: .tip} + +### Example: Autocomplete using the Kuromoji completion analyzer + +The following example configures an index with different completion analyzers used at index time and search time: + +```json +PUT /autocomplete-index +{ + "settings": { + "analysis": { + "analyzer": { + "kuromoji_index_analyzer": { + "type": "kuromoji_completion", + "mode": "index" + }, + "kuromoji_search_analyzer": { + "type": "kuromoji_completion", + "mode": "query" + } + } + } + }, + "mappings": { + "properties": { + "suggest": { + "type": "text", + "analyzer": "kuromoji_index_analyzer", + "search_analyzer": "kuromoji_search_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +For more details about the completion token filter, see [Kuromoji completion token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-completion/). + +## Using the Kuromoji and ICU plugins together + +For the most thorough Japanese text analysis, combine the `analysis-kuromoji` and `analysis-icu` plugins. ICU contributes Unicode normalization of full-width and half-width characters and comprehensive character folding that the Kuromoji components alone do not provide. + +Both `analysis-kuromoji` and `analysis-icu` must be installed before creating an index that uses components from both plugins. +{: .note} + +The following example creates a custom analyzer combining both plugins. The `icu_normalizer` character filter converts full-width characters to their ASCII equivalents before tokenization (for example, `300` becomes `300`), keeping numeric sequences as single tokens. The `kuromoji_iteration_mark` character filter expands Japanese iteration marks (for example, `時々` becomes `時時`) so the tokenizer can look them up in the dictionary correctly: + +```json +PUT /japanese-icu-index +{ + "settings": { + "index": { + "analysis": { + "analyzer": { + "japanese_icu_analyzer": { + "char_filter": [ + "icu_normalizer", + "kuromoji_iteration_mark" + ], + "tokenizer": "kuromoji_tokenizer", + "filter": [ + "kuromoji_baseform", + "kuromoji_part_of_speech", + "ja_stop", + "kuromoji_stemmer", + "lowercase" + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the combined analyzer with a sentence containing full-width digits and a long vowel mark ("The computer processes 300 documents"): + +```json +POST /japanese-icu-index/_analyze +{ + "analyzer": "japanese_icu_analyzer", + "text": "コンピューターは300件の文書を処理します" +} +``` +{% include copy-curl.html %} + +The analyzer applies the following transformations: + +- `icu_normalizer` converts the full-width digits `300` to `300` before tokenization. +- `kuromoji_stemmer` removes the trailing long vowel mark, converting `コンピューター` to `コンピュータ`. +- `kuromoji_part_of_speech` removes the particles `は`, `の`, and `を`, along with the auxiliary verb `ます`. +- `ja_stop` removes `し` because it appears in the `_japanese_` stop set. +- `300` is kept as a single token, and `文書` and `処理` are returned in base form. + +The response appears as follows: + +```json +{ + "tokens": [ + { + "token": "コンピュータ", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "300", + "start_offset": 8, + "end_offset": 11, + "type": "word", + "position": 2 + }, + { + "token": "件", + "start_offset": 11, + "end_offset": 12, + "type": "word", + "position": 3 + }, + { + "token": "文書", + "start_offset": 13, + "end_offset": 15, + "type": "word", + "position": 5 + }, + { + "token": "処理", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 7 + } + ] +} +``` + +## Related documentation + +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji iteration mark character filter]({{site.url}}{{site.baseurl}}/analyzers/character-filters/kuromoji-iteration-mark/) +- [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/) +- [CJK width token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/cjk-width/) diff --git a/_analyzers/language-analyzers/latvian.md b/_analyzers/language-analyzers/latvian.md new file mode 100644 index 00000000..074e60e6 --- /dev/null +++ b/_analyzers/language-analyzers/latvian.md @@ -0,0 +1,179 @@ +--- +layout: default +title: Latvian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 230 +--- + +# Latvian analyzer + +The built-in `latvian` analyzer can be applied to a text field using the following command: + +```json +PUT /latvian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "latvian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_latvian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_latvian_analyzer": { + "type": "latvian", + "stem_exclusion": ["autoritāte", "apstiprinājums"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Latvian analyzer internals + +The `latvian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Latvian) + - keyword + - stemmer (Latvian) + +## Custom Latvian analyzer + +You can create a custom Latvian analyzer using the following command: + +```json +PUT /latvian-index +{ + "settings": { + "analysis": { + "filter": { + "latvian_stop": { + "type": "stop", + "stopwords": "_latvian_" + }, + "latvian_stemmer": { + "type": "stemmer", + "language": "latvian" + }, + "latvian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "latvian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "latvian_stop", + "latvian_keywords", + "latvian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "latvian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /latvian-index/_analyze +{ + "field": "content", + "text": "Studenti mācās Latvijas universitātēs. Viņu numuri ir 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + }, + { + "token": "māc", + "start_offset": 9, + "end_offset": 14, + "type": "", + "position": 1 + }, + { + "token": "latvij", + "start_offset": 15, + "end_offset": 23, + "type": "", + "position": 2 + }, + { + "token": "universitāt", + "start_offset": 24, + "end_offset": 37, + "type": "", + "position": 3 + }, + { + "token": "vin", + "start_offset": 39, + "end_offset": 43, + "type": "", + "position": 4 + }, + { + "token": "numur", + "start_offset": 44, + "end_offset": 50, + "type": "", + "position": 5 + }, + { + "token": "123456", + "start_offset": 54, + "end_offset": 60, + "type": "", + "position": 7 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/lithuanian.md b/_analyzers/language-analyzers/lithuanian.md new file mode 100644 index 00000000..ca5966c5 --- /dev/null +++ b/_analyzers/language-analyzers/lithuanian.md @@ -0,0 +1,136 @@ +--- +layout: default +title: Lithuanian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 230 +--- + +# Lithuanian analyzer + +The built-in `lithuanian` analyzer can be applied to a text field using the following command: + +```json +PUT /lithuanian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "lithuanian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_lithuanian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_lithuanian_analyzer": { + "type": "lithuanian", + "stem_exclusion": ["autoritetas", "patvirtinimas"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Lithuanian analyzer internals + +The `lithuanian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Lithuanian) + - keyword + - stemmer (Lithuanian) + +## Custom Lithuanian analyzer + +You can create a custom Lithuanian analyzer using the following command: + +```json +PUT /lithuanian-index +{ + "settings": { + "analysis": { + "filter": { + "lithuanian_stop": { + "type": "stop", + "stopwords": "_lithuanian_" + }, + "lithuanian_stemmer": { + "type": "stemmer", + "language": "lithuanian" + }, + "lithuanian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "lithuanian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "lithuanian_stop", + "lithuanian_keywords", + "lithuanian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "lithuanian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /lithuanian-index/_analyze +{ + "field": "content", + "text": "Studentai mokosi Lietuvos universitetuose. Jų numeriai yra 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 0,"end_offset": 9,"type": "","position": 0}, + {"token": "mok","start_offset": 10,"end_offset": 16,"type": "","position": 1}, + {"token": "lietuv","start_offset": 17,"end_offset": 25,"type": "","position": 2}, + {"token": "universitet","start_offset": 26,"end_offset": 41,"type": "","position": 3}, + {"token": "num","start_offset": 46,"end_offset": 54,"type": "","position": 5}, + {"token": "123456","start_offset": 59,"end_offset": 65,"type": "","position": 7} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/norwegian.md b/_analyzers/language-analyzers/norwegian.md new file mode 100644 index 00000000..cfb04eeb --- /dev/null +++ b/_analyzers/language-analyzers/norwegian.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Norwegian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 240 +--- + +# Norwegian analyzer + +The built-in `norwegian` analyzer can be applied to a text field using the following command: + +```json +PUT /norwegian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "norwegian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_norwegian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_norwegian_analyzer": { + "type": "norwegian", + "stem_exclusion": ["autoritet", "godkjenning"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Norwegian analyzer internals + +The `norwegian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Norwegian) + - keyword + - stemmer (Norwegian) + +## Custom Norwegian analyzer + +You can create a custom Norwegian analyzer using the following command: + +```json +PUT /norwegian-index +{ + "settings": { + "analysis": { + "filter": { + "norwegian_stop": { + "type": "stop", + "stopwords": "_norwegian_" + }, + "norwegian_stemmer": { + "type": "stemmer", + "language": "norwegian" + }, + "norwegian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "norwegian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "norwegian_stop", + "norwegian_keywords", + "norwegian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "norwegian_analyzer" + } + } + } +} + +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /norwegian-index/_analyze +{ + "field": "content", + "text": "Studentene studerer ved norske universiteter. Deres nummer er 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 0,"end_offset": 10,"type": "","position": 0}, + {"token": "studer","start_offset": 11,"end_offset": 19,"type": "","position": 1}, + {"token": "norsk","start_offset": 24,"end_offset": 30,"type": "","position": 3}, + {"token": "universitet","start_offset": 31,"end_offset": 44,"type": "","position": 4}, + {"token": "numm","start_offset": 52,"end_offset": 58,"type": "","position": 6}, + {"token": "123456","start_offset": 62,"end_offset": 68,"type": "","position": 8} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/persian.md b/_analyzers/language-analyzers/persian.md new file mode 100644 index 00000000..2e06f8d7 --- /dev/null +++ b/_analyzers/language-analyzers/persian.md @@ -0,0 +1,145 @@ +--- +layout: default +title: Persian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 250 +--- + +# Persian analyzer + +The built-in `persian` analyzer can be applied to a text field using the following command: + +```json +PUT /persian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "persian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_persian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_persian_analyzer": { + "type": "persian", + "stem_exclusion": ["حکومت", "تأیید"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Persian analyzer internals + +The `persian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Char filter: `mapping` + +- Token filters: + - lowercase + - decimal_digit + - normalization (Arabic) + - normalization (Persian) + - stop (Persian) + - keyword + +## Custom Persian analyzer + +You can create a custom Persian analyzer using the following command: + +```json +PUT /persian-index +{ + "settings": { + "analysis": { + "filter": { + "persian_stop": { + "type": "stop", + "stopwords": "_persian_" + }, + "persian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "char_filter": { + "null_width_replace_with_space": { + "type": "mapping", + "mappings": [ "\\u200C=>\\u0020"] + } + }, + "analyzer": { + "persian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "char_filter": [ "null_width_replace_with_space" ], + "filter": [ + "lowercase", + "decimal_digit", + "arabic_normalization", + "persian_normalization", + "persian_stop", + "persian_keywords" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "persian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /persian-index/_analyze +{ + "field": "content", + "text": "دانشجویان در دانشگاه‌های ایرانی تحصیل می‌کنند. شماره‌های آن‌ها ۱۲۳۴۵۶ است." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "دانشجويان","start_offset": 0,"end_offset": 9,"type": "","position": 0}, + {"token": "دانشگاه","start_offset": 13,"end_offset": 20,"type": "","position": 2}, + {"token": "ايراني","start_offset": 25,"end_offset": 31,"type": "","position": 4}, + {"token": "تحصيل","start_offset": 32,"end_offset": 37,"type": "","position": 5}, + {"token": "شماره","start_offset": 47,"end_offset": 52,"type": "","position": 8}, + {"token": "123456","start_offset": 63,"end_offset": 69,"type": "","position": 12} + ] +} +``` diff --git a/_analyzers/language-analyzers/polish.md b/_analyzers/language-analyzers/polish.md new file mode 100644 index 00000000..ead4135f --- /dev/null +++ b/_analyzers/language-analyzers/polish.md @@ -0,0 +1,130 @@ +--- +layout: default +title: Polish +nav_order: 255 +parent: Language analyzers +grand_parent: Analyzers +--- + +# Polish analyzer + +The Polish language analyzer (`polish`) provides analysis for Polish text. This analyzer is part of the `analysis-stempel` plugin, which must be installed before use. + +## Installing the plugin + +Before you can use the Polish analyzer, you must install the `analysis-stempel` plugin by running the following command: + +```bash +./bin/opensearch-plugin install analysis-stempel +``` +{% include copy.html %} + +For more information, see [Additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/): Complete list of available OpenSearch plugins. + +## Using the Polish analyzer + +To use the Polish analyzer when you map an index, specify the `polish` value in the analyzer field: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "polish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Configuring a custom Polish analyzer + +You can configure a custom Polish analyzer by creating a custom analyzer that uses the Polish stemmer token filter. The default Polish analyzer applies the following analysis chain: + +1. **Tokenizer**: `standard` +2. **Token filters**: + - `lowercase` + - `polish_stop` (removes Polish stop words) + - `polish_stem` (applies Polish stemming) + +### Example: Custom Polish analyzer + +```json +PUT my-polish-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_polish": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "polish_stop", + "polish_stem" + ] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "custom_polish" + }, + "content": { + "type": "text", + "analyzer": "polish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Polish token filters + +The `analysis-stempel` plugin provides the following token filters for Polish language processing. + + +### polish_stop token filter + + +Removes common Polish stop words from the token stream. + + +### polish_stem token filter + + +Applies Polish-specific stemming rules to reduce words to their root forms using the Stempel stemming algorithm. + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST _analyze +{ + "analyzer": "polish", + "text": "Jestem programistą w Polsce i pracuję z OpenSearch" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "jest", "start_offset": 0, "end_offset": 6, "type": "", "position": 0}, + {"token": "prograć", "start_offset": 7, "end_offset": 18, "type": "", "position": 1}, + {"token": "polsce", "start_offset": 21, "end_offset": 27, "type": "", "position": 3}, + {"token": "pracować", "start_offset": 30, "end_offset": 37, "type": "", "position": 5}, + {"token": "opensearch", "start_offset": 40, "end_offset": 50, "type": "", "position": 7} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/portuguese.md b/_analyzers/language-analyzers/portuguese.md new file mode 100644 index 00000000..166ffa00 --- /dev/null +++ b/_analyzers/language-analyzers/portuguese.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Portuguese +parent: Language analyzers +grand_parent: Analyzers +nav_order: 260 +--- + +# Portuguese analyzer + +The built-in `portuguese` analyzer can be applied to a text field using the following command: + +```json +PUT /portuguese-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "portuguese" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_portuguese_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_portuguese_analyzer": { + "type": "portuguese", + "stem_exclusion": ["autoridade", "aprovação"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Portuguese analyzer internals + +The `portuguese` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Portuguese) + - keyword + - stemmer (Portuguese) + +## Custom Portuguese analyzer + +You can create a custom Portuguese analyzer using the following command: + +```json +PUT /portuguese-index +{ + "settings": { + "analysis": { + "filter": { + "portuguese_stop": { + "type": "stop", + "stopwords": "_portuguese_" + }, + "portuguese_stemmer": { + "type": "stemmer", + "language": "light_portuguese" + }, + "portuguese_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "portuguese_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "portuguese_stop", + "portuguese_keywords", + "portuguese_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "portuguese_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /portuguese-index/_analyze +{ + "field": "content", + "text": "Os estudantes estudam nas universidades brasileiras. Seus números são 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "estudant", + "start_offset": 3, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "estudam", + "start_offset": 14, + "end_offset": 21, + "type": "", + "position": 2 + }, + { + "token": "universidad", + "start_offset": 26, + "end_offset": 39, + "type": "", + "position": 4 + }, + { + "token": "brasileir", + "start_offset": 40, + "end_offset": 51, + "type": "", + "position": 5 + }, + { + "token": "numer", + "start_offset": 58, + "end_offset": 65, + "type": "", + "position": 7 + }, + { + "token": "123456", + "start_offset": 70, + "end_offset": 76, + "type": "", + "position": 9 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/romanian.md b/_analyzers/language-analyzers/romanian.md new file mode 100644 index 00000000..cad09533 --- /dev/null +++ b/_analyzers/language-analyzers/romanian.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Romanian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 270 +--- + +# Romanian analyzer + +The built-in `romanian` analyzer can be applied to a text field using the following command: + +```json +PUT /romanian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "romanian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_romanian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_romanian_analyzer": { + "type": "romanian", + "stem_exclusion": ["autoritate", "aprobat"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Romanian analyzer internals + +The `romanian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Romanian) + - keyword + - stemmer (Romanian) + +## Custom Romanian analyzer + +You can create a custom Romanian analyzer using the following command: + +```json +PUT /romanian-index +{ + "settings": { + "analysis": { + "filter": { + "romanian_stop": { + "type": "stop", + "stopwords": "_romanian_" + }, + "romanian_stemmer": { + "type": "stemmer", + "language": "romanian" + }, + "romanian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "romanian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "romanian_stop", + "romanian_keywords", + "romanian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "romanian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /romanian-index/_analyze +{ + "field": "content", + "text": "Studenții învață la universitățile din România. Numerele lor sunt 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "studenț", + "start_offset": 0, + "end_offset": 9, + "type": "", + "position": 0 + }, + { + "token": "învaț", + "start_offset": 10, + "end_offset": 16, + "type": "", + "position": 1 + }, + { + "token": "universităț", + "start_offset": 20, + "end_offset": 34, + "type": "", + "position": 3 + }, + { + "token": "român", + "start_offset": 39, + "end_offset": 46, + "type": "", + "position": 5 + }, + { + "token": "numer", + "start_offset": 48, + "end_offset": 56, + "type": "", + "position": 6 + }, + { + "token": "123456", + "start_offset": 66, + "end_offset": 72, + "type": "", + "position": 9 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/russian.md b/_analyzers/language-analyzers/russian.md new file mode 100644 index 00000000..bd57ba0b --- /dev/null +++ b/_analyzers/language-analyzers/russian.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Russian +parent: Language analyzers +grand_parent: Analyzers +nav_order: 280 +--- + +# Russian analyzer + +The built-in `russian` analyzer can be applied to a text field using the following command: + +```json +PUT /russian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "russian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_russian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_russian_analyzer": { + "type": "russian", + "stem_exclusion": ["авторитет", "одобрение"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Russian analyzer internals + +The `russian` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Russian) + - keyword + - stemmer (Russian) + +## Custom Russian analyzer + +You can create a custom Russian analyzer using the following command: + +```json +PUT /russian-index +{ + "settings": { + "analysis": { + "filter": { + "russian_stop": { + "type": "stop", + "stopwords": "_russian_" + }, + "russian_stemmer": { + "type": "stemmer", + "language": "russian" + }, + "russian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "russian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "russian_stop", + "russian_keywords", + "russian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "russian_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /russian-index/_analyze +{ + "field": "content", + "text": "Студенты учатся в университетах России. Их номера 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "студент", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + }, + { + "token": "учат", + "start_offset": 9, + "end_offset": 15, + "type": "", + "position": 1 + }, + { + "token": "университет", + "start_offset": 18, + "end_offset": 31, + "type": "", + "position": 3 + }, + { + "token": "росс", + "start_offset": 32, + "end_offset": 38, + "type": "", + "position": 4 + }, + { + "token": "номер", + "start_offset": 43, + "end_offset": 49, + "type": "", + "position": 6 + }, + { + "token": "123456", + "start_offset": 50, + "end_offset": 56, + "type": "", + "position": 7 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/sorani.md b/_analyzers/language-analyzers/sorani.md new file mode 100644 index 00000000..6814a3a1 --- /dev/null +++ b/_analyzers/language-analyzers/sorani.md @@ -0,0 +1,169 @@ +--- +layout: default +title: Sorani +parent: Language analyzers +grand_parent: Analyzers +nav_order: 290 +--- + +# Sorani analyzer + +The built-in `sorani` analyzer can be applied to a text field using the following command: + +```json +PUT /sorani-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "sorani" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_sorani_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_sorani_analyzer": { + "type": "sorani", + "stem_exclusion": ["مؤسسه", "اجازه"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Sorani analyzer internals + +The `sorani` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - normalization (Sorani) + - lowercase + - decimal_digit + - stop (Sorani) + - keyword + - stemmer (Sorani) + +## Custom Sorani analyzer + +You can create a custom Sorani analyzer using the following command: + +```json +PUT /sorani-index +{ + "settings": { + "analysis": { + "filter": { + "sorani_stop": { + "type": "stop", + "stopwords": "_sorani_" + }, + "sorani_stemmer": { + "type": "stemmer", + "language": "sorani" + }, + "sorani_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "sorani_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "sorani_normalization", + "lowercase", + "decimal_digit", + "sorani_stop", + "sorani_keywords", + "sorani_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "sorani_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /sorani-index/_analyze +{ + "field": "content", + "text": "خوێندنی فەرمی لە هەولێرەوە. ژمارەکان ١٢٣٤٥٦." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "خوێندن", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "فەرم", + "start_offset": 8, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "هەولێر", + "start_offset": 17, + "end_offset": 26, + "type": "", + "position": 3 + }, + { + "token": "ژمار", + "start_offset": 28, + "end_offset": 36, + "type": "", + "position": 4 + }, + { + "token": "123456", + "start_offset": 37, + "end_offset": 43, + "type": "", + "position": 5 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/spanish.md b/_analyzers/language-analyzers/spanish.md new file mode 100644 index 00000000..8a0d8fad --- /dev/null +++ b/_analyzers/language-analyzers/spanish.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Spanish +parent: Language analyzers +grand_parent: Analyzers +nav_order: 300 +--- + +# Spanish analyzer + +The built-in `spanish` analyzer can be applied to a text field using the following command: + +```json +PUT /spanish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "spanish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_spanish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_spanish_analyzer": { + "type": "spanish", + "stem_exclusion": ["autoridad", "aprobación"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Spanish analyzer internals + +The `spanish` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Spanish) + - keyword + - stemmer (Spanish) + +## Custom Spanish analyzer + +You can create a custom Spanish analyzer using the following command: + +```json +PUT /spanish-index +{ + "settings": { + "analysis": { + "filter": { + "spanish_stop": { + "type": "stop", + "stopwords": "_spanish_" + }, + "spanish_stemmer": { + "type": "stemmer", + "language": "light_spanish" + }, + "spanish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "spanish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "spanish_stop", + "spanish_keywords", + "spanish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "spanish_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /spanish-index/_analyze +{ + "field": "content", + "text": "Los estudiantes estudian en universidades españolas. Sus números son 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "estudiant", + "start_offset": 4, + "end_offset": 15, + "type": "", + "position": 1 + }, + { + "token": "estudian", + "start_offset": 16, + "end_offset": 24, + "type": "", + "position": 2 + }, + { + "token": "universidad", + "start_offset": 28, + "end_offset": 41, + "type": "", + "position": 4 + }, + { + "token": "español", + "start_offset": 42, + "end_offset": 51, + "type": "", + "position": 5 + }, + { + "token": "numer", + "start_offset": 57, + "end_offset": 64, + "type": "", + "position": 7 + }, + { + "token": "123456", + "start_offset": 69, + "end_offset": 75, + "type": "", + "position": 9 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/swedish.md b/_analyzers/language-analyzers/swedish.md new file mode 100644 index 00000000..9da595f1 --- /dev/null +++ b/_analyzers/language-analyzers/swedish.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Swedish +parent: Language analyzers +grand_parent: Analyzers +nav_order: 310 +--- + +# Swedish analyzer + +The built-in `swedish` analyzer can be applied to a text field using the following command: + +```json +PUT /swedish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "swedish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_swedish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_swedish_analyzer": { + "type": "swedish", + "stem_exclusion": ["myndighet", "godkännande"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Swedish analyzer internals + +The `swedish` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - lowercase + - stop (Swedish) + - keyword + - stemmer (Swedish) + +## Custom Swedish analyzer + +You can create a custom Swedish analyzer using the following command: + +```json +PUT /swedish-index +{ + "settings": { + "analysis": { + "filter": { + "swedish_stop": { + "type": "stop", + "stopwords": "_swedish_" + }, + "swedish_stemmer": { + "type": "stemmer", + "language": "swedish" + }, + "swedish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "swedish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "swedish_stop", + "swedish_keywords", + "swedish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "swedish_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /swedish-index/_analyze +{ + "field": "content", + "text": "Studenter studerar vid svenska universitet. Deras nummer är 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 0, + "end_offset": 9, + "type": "", + "position": 0 + }, + { + "token": "studer", + "start_offset": 10, + "end_offset": 18, + "type": "", + "position": 1 + }, + { + "token": "svensk", + "start_offset": 23, + "end_offset": 30, + "type": "", + "position": 3 + }, + { + "token": "universitet", + "start_offset": 31, + "end_offset": 42, + "type": "", + "position": 4 + }, + { + "token": "numm", + "start_offset": 50, + "end_offset": 56, + "type": "", + "position": 6 + }, + { + "token": "123456", + "start_offset": 60, + "end_offset": 66, + "type": "", + "position": 8 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/thai.md b/_analyzers/language-analyzers/thai.md new file mode 100644 index 00000000..e4daa1f0 --- /dev/null +++ b/_analyzers/language-analyzers/thai.md @@ -0,0 +1,132 @@ +--- +layout: default +title: Thai +parent: Language analyzers +grand_parent: Analyzers +nav_order: 320 +--- + +# Thai analyzer + +The built-in `thai` analyzer can be applied to a text field using the following command: + +```json +PUT /thai-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "thai" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_thai_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_thai_analyzer": { + "type": "thai", + "stem_exclusion": ["อำนาจ", "การอนุมัติ"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Thai analyzer internals + +The `thai` analyzer is built using the following components: + +- Tokenizer: `thai` + +- Token filters: + - lowercase + - decimal_digit + - stop (Thai) + - keyword + +## Custom Thai analyzer + +You can create a custom Thai analyzer using the following command: + +```json +PUT /thai-index +{ + "settings": { + "analysis": { + "filter": { + "thai_stop": { + "type": "stop", + "stopwords": "_thai_" + }, + "thai_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "thai_analyzer": { + "tokenizer": "thai", + "filter": [ + "lowercase", + "decimal_digit", + "thai_stop", + "thai_keywords" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "thai_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /thai-index/_analyze +{ + "field": "content", + "text": "นักเรียนกำลังศึกษาอยู่ที่มหาวิทยาลัยไทย หมายเลข 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "นักเรียน","start_offset": 0,"end_offset": 8,"type": "word","position": 0}, + {"token": "กำลัง","start_offset": 8,"end_offset": 13,"type": "word","position": 1}, + {"token": "ศึกษา","start_offset": 13,"end_offset": 18,"type": "word","position": 2}, + {"token": "มหาวิทยาลัย","start_offset": 25,"end_offset": 36,"type": "word","position": 5}, + {"token": "ไทย","start_offset": 36,"end_offset": 39,"type": "word","position": 6}, + {"token": "หมายเลข","start_offset": 40,"end_offset": 47,"type": "word","position": 7}, + {"token": "123456","start_offset": 48,"end_offset": 54,"type": "word","position": 8} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/turkish.md b/_analyzers/language-analyzers/turkish.md new file mode 100644 index 00000000..fb36c541 --- /dev/null +++ b/_analyzers/language-analyzers/turkish.md @@ -0,0 +1,143 @@ +--- +layout: default +title: Turkish +parent: Language analyzers +grand_parent: Analyzers +nav_order: 330 +--- + +# Turkish analyzer + +The built-in `turkish` analyzer can be applied to a text field using the following command: + +```json +PUT /turkish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "turkish" + } + } + } +} +``` +{% include copy-curl.html %} + +## Stem exclusion + +You can use `stem_exclusion` with this language analyzer using the following command: + +```json +PUT index_with_stem_exclusion_turkish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_turkish_analyzer": { + "type": "turkish", + "stem_exclusion": ["otorite", "onay"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Turkish analyzer internals + +The `turkish` analyzer is built using the following components: + +- Tokenizer: `standard` + +- Token filters: + - apostrophe + - lowercase (Turkish) + - stop (Turkish) + - keyword + - stemmer (Turkish) + +## Custom Turkish analyzer + +You can create a custom Turkish analyzer using the following command: + +```json +PUT /turkish-index +{ + "settings": { + "analysis": { + "filter": { + "turkish_stop": { + "type": "stop", + "stopwords": "_turkish_" + }, + "turkish_stemmer": { + "type": "stemmer", + "language": "turkish" + }, + "turkish_lowercase": { + "type": "lowercase", + "language": "turkish" + }, + "turkish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "turkish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "apostrophe", + "turkish_lowercase", + "turkish_stop", + "turkish_keywords", + "turkish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "turkish_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /turkish-index/_analyze +{ + "field": "content", + "text": "Öğrenciler Türk üniversitelerinde öğrenim görüyor. Numara 123456." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "öğrenci","start_offset": 0,"end_offset": 10,"type": "","position": 0}, + {"token": "türk","start_offset": 11,"end_offset": 15,"type": "","position": 1}, + {"token": "üniversite","start_offset": 16,"end_offset": 33,"type": "","position": 2}, + {"token": "öğre","start_offset": 34,"end_offset": 41,"type": "","position": 3}, + {"token": "görüyor","start_offset": 42,"end_offset": 49,"type": "","position": 4}, + {"token": "numar","start_offset": 51,"end_offset": 57,"type": "","position": 5}, + {"token": "123456","start_offset": 58,"end_offset": 64,"type": "","position": 6} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/language-analyzers/ukrainian.md b/_analyzers/language-analyzers/ukrainian.md new file mode 100644 index 00000000..a3261244 --- /dev/null +++ b/_analyzers/language-analyzers/ukrainian.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Ukrainian +nav_order: 340 +parent: Language analyzers +grand_parent: Analyzers +--- + +# Ukrainian analyzer + +The Ukrainian language analyzer (`ukrainian`) provides analysis for Ukrainian text. This analyzer is part of the `analysis-ukrainian` plugin, which must be installed before use. + +## Installing the plugin + +Before you can use the Ukrainian analyzer, you must install the `analysis-ukrainian` plugin by running the following command: + +```bash +./bin/opensearch-plugin install analysis-ukrainian +``` +{% include copy.html %} + +For more information, see [Additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/): Complete list of available OpenSearch plugins. + +## Using the Ukrainian analyzer + +To use the Ukrainian analyzer when you map an index, specify the `ukrainian` value in the analyzer field: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "ukrainian" + } + } + } +} +``` +{% include copy-curl.html %} + +## Ukrainian language processing + +The Ukrainian analyzer processes text using the following approach: + +1. **Tokenization**: Splits text into individual words. +2. **Stop word removal**: Removes common Ukrainian stop words like "і", "в", "з", "для", "та", and so on. +3. **Morphological analysis**: Generates various word forms and stems for Ukrainian words. +4. **Case normalization**: Handles Ukrainian text appropriately. + +The Ukrainian analyzer uses sophisticated morphological analysis that can generate multiple forms of words to improve search recall. Unlike some other language analyzers, the Ukrainian plugin does not expose individual token filters for custom configuration. + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST _analyze +{ + "analyzer": "ukrainian", + "text": "Я програміст і працюю з OpenSearch в Україні" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "програміст", "start_offset": 2, "end_offset": 12, "type": "", "position": 1}, + {"token": "працювати", "start_offset": 15, "end_offset": 21, "type": "", "position": 3}, + {"token": "opensearch", "start_offset": 24, "end_offset": 34, "type": "", "position": 5}, + {"token": "Україна", "start_offset": 37, "end_offset": 44, "type": "", "position": 7} + ] +} +``` \ No newline at end of file diff --git a/_analyzers/normalizers.md b/_analyzers/normalizers.md index b89659f8..9e47562d 100644 --- a/_analyzers/normalizers.md +++ b/_analyzers/normalizers.md @@ -1,7 +1,7 @@ --- layout: default title: Normalizers -nav_order: 100 +nav_order: 110 --- # Normalizers @@ -91,7 +91,7 @@ This module does not require installation; it is available by default. Character filters: `pattern_replace`, `mapping` -Token filters: `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` +Token filters: `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`, `truncate`, `uppercase` ### The `analysis-icu` plugin @@ -101,11 +101,7 @@ Token filters: `icu_normalizer`, `icu_folding`, `icu_transform` ### The `analysis-kuromoji` plugin -Character filters: `normalize_kanji`, `normalize_kana` - -### The `analysis-nori` plugin - -Character filters: `normalize_kanji`, `normalize_kana` +Character filters: `kuromoji_iteration_mark` These lists of filters include only analysis components found in the [additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#additional-plugins) that are part of the core OpenSearch repository. {: .note} \ No newline at end of file diff --git a/_analyzers/search-analyzers.md b/_analyzers/search-analyzers.md index b47e739d..5c512319 100644 --- a/_analyzers/search-analyzers.md +++ b/_analyzers/search-analyzers.md @@ -2,11 +2,12 @@ layout: default title: Search analyzers nav_order: 30 +parent: Analyzers --- # Search analyzers -Search analyzers are specified at query time and are used to analyze the query string when you run a full-text query on a [text]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) field. +Search analyzers are specified at query time and are used to analyze the query string when you run a full-text query on a [text]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) field. ## Determining which search analyzer to use @@ -21,14 +22,12 @@ To determine which analyzer to use for a query string at query time, OpenSearch In most cases, specifying a search analyzer that is different from the index analyzer is not necessary and could negatively impact search result relevance or lead to unexpected search results. {: .warning} -For information about verifying which analyzer is associated with which field, see [Verifying analyzer settings]({{site.url}}{{site.baseurl}}/analyzers/index/#verifying-analyzer-settings). +## Specifying a search analyzer at query time -## Specifying a search analyzer for a query string - -Specify the name of the analyzer you want to use at query time in the `analyzer` field: +You can override the default analyzer behavior by explicitly setting the analyzer in the query. The following query uses the `english` analyzer to stem the input terms: ```json -GET shakespeare/_search +GET /shakespeare/_search { "query": { "match": { @@ -42,16 +41,16 @@ GET shakespeare/_search ``` {% include copy-curl.html %} -Valid values for [built-in analyzers]({{site.url}}{{site.baseurl}}/analyzers/index#built-in-analyzers) are `standard`, `simple`, `whitespace`, `stop`, `keyword`, `pattern`, `fingerprint`, or any supported [language analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/). +## Specifying a search analyzer in the mappings -## Specifying a search analyzer for a field +When defining mappings, you can provide both the `analyzer` (used at index time) and `search_analyzer` (used at query time) for any [`text`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) field. -When creating index mappings, you can provide the `search_analyzer` parameter for each [text]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) field. When providing the `search_analyzer`, you must also provide the `analyzer` parameter, which specifies the [index analyzer]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/) to be used at indexing time. +### Example: Different analyzers for indexing and search -For example, the following request specifies the `simple` analyzer as the index analyzer and the `whitespace` analyzer as the search analyzer for the `text_entry` field: +The following configuration allows different tokenization strategies for indexing and querying: ```json -PUT testindex +PUT /testindex { "mappings": { "properties": { @@ -66,14 +65,100 @@ PUT testindex ``` {% include copy-curl.html %} -## Specifying the default search analyzer for an index +### Example: Using the edge n-gram analyzer for indexing and the standard analyzer for search -If you want to analyze all query strings at search time with the same analyzer, you can specify the search analyzer in the `analysis.analyzer.default_search` setting. When providing the `analysis.analyzer.default_search`, you must also provide the `analysis.analyzer.default` parameter, which specifies the [index analyzer]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/) to be used at indexing time. - -For example, the following request specifies the `simple` analyzer as the index analyzer and the `whitespace` analyzer as the search analyzer for the `testindex` index: +The following configuration enables [autocomplete]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/)-like behavior, where you can type the beginning of a word and still receive relevant matches: ```json -PUT testindex +PUT /articles +{ + "settings": { + "analysis": { + "analyzer": { + "edge_ngram_analyzer": { + "tokenizer": "edge_ngram_tokenizer", + "filter": ["lowercase"] + } + }, + "tokenizer": { + "edge_ngram_tokenizer": { + "type": "edge_ngram", + "min_gram": 2, + "max_gram": 10, + "token_chars": ["letter", "digit"] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "edge_ngram_analyzer", + "search_analyzer": "standard" + } + } + } +} +``` +{% include copy-curl.html %} + +The `edge_ngram_analyzer` is applied at index time, breaking input strings into partial prefixes (n-grams), which allows the index to store fragments like "se", "sea", "sear", and so on. +Use the following request to index a document: + +```json +PUT /articles/_doc/1 +{ + "title": "Search Analyzer in Action" +} +``` +{% include copy-curl.html %} + +Use the following request to search for the partial word `sear` in the `title` field: + +```json +POST /articles/_search +{ + "query": { + "match": { + "title": "sear" + } + } +} +``` +{% include copy-curl.html %} + +The response demonstrates that the query containing "sear" matches the document "Search Analyzer in Action" because the n-gram tokens generated at index time include that prefix. This mirrors the [autocomplete functionality]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/), in which typing a prefix can retrieve full matches: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.2876821, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 0.2876821, + "_source": { + "title": "Search Analyzer in Action" + } + } + ] + } +} +``` + +## Setting a default search analyzer for an index + +Specify `analysis.analyzer.default_search` to define a search analyzer for all fields unless overridden: + +```json +PUT /testindex { "settings": { "analysis": { @@ -88,6 +173,9 @@ PUT testindex } } } - ``` {% include copy-curl.html %} + +This configuration ensures consistent behavior across multiple fields, especially when using custom analyzers. + +For more information about supported analyzers, see [Analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/index/). diff --git a/_analyzers/stemming.md b/_analyzers/stemming.md new file mode 100644 index 00000000..bd43078c --- /dev/null +++ b/_analyzers/stemming.md @@ -0,0 +1,162 @@ +--- +layout: default +title: Stemming +nav_order: 140 +--- + +# Stemming + +Stemming is the process of reducing words to their root or base form, known as the _stem_. This technique ensures that different variations of a word are matched during search operations. For example, the words "running", "runner", and "ran" can all be reduced to the stem "run", allowing searches for any of these terms to return relevant results. + +In natural language, words often appear in various forms because of conjugation, pluralization, or derivation. Stemming improves search operations in the following ways: + +- **Improves search recall**: By matching different word forms to a common stem, stemming increases the number of relevant documents retrieved. +- **Reduces index size**: Storing only the stemmed versions of words can decrease the overall size of the search index. + +Stemming is configured using token filters within [analyzers]({{site.url}}{{site.baseurl}}/analyzers/#analyzers). An analyzer comprises the following components: + +1. **Character filters**: Modify the stream of characters before tokenization. +2. **Tokenizer**: Splits text into tokens (typically, words). +3. **Token filters**: Modify tokens after tokenization, for example, by applying stemming. + +## Stemming example using built-in token filters + +To implement stemming, you can configure a built-in token filter such as a [`porter_stem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/porter-stem/) or [`kstem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kstem/) filter. + +The [Porter stemming algorithm](https://snowballstem.org/algorithms/porter/stemmer.html) is a common algorithmic stemmer used for the English language. + +### Creating an index with a custom analyzer + +The following example request creates a new index named `my_stemming_index` and configures an analyzer with the [`porter_stem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/porter-stem/) token filter: + +```json +PUT /my_stemming_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_stemmer_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "porter_stem" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +This configuration comprises the following: + +- The [`standard`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/standard/) tokenizer splits text into terms based on word boundaries. +- The [`lowercase`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/lowercase/) filter converts all tokens to lowercase. +- The [`porter_stem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/porter-stem/) filter reduces words to their root form. + +### Testing the analyzer + +To examine the stemming action, analyze a sample text using the previously configured custom analyzer: + +```json +POST /my_stemming_index/_analyze +{ + "analyzer": "my_stemmer_analyzer", + "text": "The runners are running swiftly." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "the", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "runner", + "start_offset": 4, + "end_offset": 11, + "type": "", + "position": 1 + }, + { + "token": "ar", + "start_offset": 12, + "end_offset": 15, + "type": "", + "position": 2 + }, + { + "token": "run", + "start_offset": 16, + "end_offset": 23, + "type": "", + "position": 3 + }, + { + "token": "swiftli", + "start_offset": 24, + "end_offset": 31, + "type": "", + "position": 4 + } + ] +} +``` + +## Stemmer categories + +You can configure stemmers belonging to the following two categories: + +- [Algorithmic stemmers]({{site.url}}{{site.baseurl}}/analyzers/stemming/#algorithmic-stemmers) +- [Dictionary stemmers]({{site.url}}{{site.baseurl}}/analyzers/stemming/#dictionary-stemmers) + +### Algorithmic stemmers + +Algorithmic stemmers apply predefined rules to systematically strip affixes (prefixes and suffixes) from words, reducing them to their stems. The following token filters use algorithmic stemmers: + +- [`porter_stem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/porter-stem/): Applies the Porter stemming algorithm to remove common suffixes and reduce words to their stems. For example, "running" becomes "run". + +- [`kstem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kstem/): A lightweight stemmer designed for the English language that combines algorithmic stemming with a built-in dictionary. It reduces plurals to singulars, converts verb tenses to their base forms, and removes common derivational endings. + + +- [`stemmer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stemmer/): Provides algorithmic stemming for various languages, including English, with options for different stemming algorithms like `light_english`, `minimal_english`, and `porter2`. + + +- [`snowball`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/snowball/): Applies the Snowball algorithm to provide efficient and accurate stemming for multiple languages, including English, French, German, and others. + +### Dictionary stemmers + +Dictionary stemmers rely on extensive dictionaries to map words to their root forms, effectively stemming irregular words. They look up each word in a precompiled list to find its corresponding stem. This operation is more resource intensive but often yields better results for irregular words and words that might appear to have a similar stem but are very different in their meaning. + +The most prominent example of a dictionary stemmer is the [`hunspell`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/hunspell/) token filter, which uses Hunspell---a spell checker engine used in many open-source applications. + +### Considerations +When selecting a stemmer, take note of the following considerations: + +- Algorithmic stemmers are suitable when processing speed and memory efficiency are priorities and the language has relatively regular morphological patterns. +- Dictionary stemmers are ideal when accuracy in handling irregular word forms is crucial and resources are available to support the increased memory usage and processing time. + + +### Additional stemming configuration + +Although "organize" and "organic" share a common linguistic root, leading a stemmer to produce "organ" for both, their conceptual differences are significant. In practical search scenarios, this shared root can lead to irrelevant matches being returned in search results. + +You can address these challenges by using the following methods: + +- **Explicit stemming overrides**: Rather than relying solely on algorithmic stemming, you can define specific stemming rules. Using [`stemmer_override`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stemmer-override/) allows you to ensure that "organize" remains unchanged while "organic" is reduced to "organ." This provides granular control over the final form of terms. + +- **Keyword preservation**: To maintain the integrity of important terms, you can use the [`keyword_marker`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/keyword-marker/) token filter. This filter designates specific words as keywords, preventing subsequent stemmer filters from altering them. In this example, you can mark "organize" as a keyword, ensuring that it is indexed exactly as it appears. + +- **Conditional stemming control**: The [condition]({{site.url}}{{site.baseurl}}/analyzers/token-filters/condition/) token filter enables you to establish rules that determine whether a term should be stemmed. These can be based on various criteria, such as the term's presence in a predefined list. + +- **Language-specific term exclusion**: For built-in language analyzers, the [`stem_exclusion`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/english/#stem-exclusion) parameter provides a way to specify words that should be exempt from stemming. For example, you can add "organize" to the `stem_exclusion` list, preventing the analyzer from stemming it. This can be useful for preserving the distinct meaning of specific terms within a given language. diff --git a/_analyzers/supported-analyzers/dl-model-analyzers.md b/_analyzers/supported-analyzers/dl-model-analyzers.md new file mode 100644 index 00000000..b0cb4bd1 --- /dev/null +++ b/_analyzers/supported-analyzers/dl-model-analyzers.md @@ -0,0 +1,142 @@ +--- +layout: default +title: DL model analyzers +parent: Analyzers +nav_order: 130 +--- + +# DL model analyzers + +Deep learning (DL) model analyzers are designed to work with [neural sparse search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-search/). They implement the same tokenization rules used by machine learning (ML) models, ensuring compatibility with neural sparse search. While traditional OpenSearch analyzers use standard rule-based tokenization (like white space or word boundaries), DL model analyzers use tokenization rules that match specific ML models (like the BERT WordPiece tokenization scheme). This consistent tokenization between indexed documents and search queries is essential for neural sparse search to work correctly. + +OpenSearch supports the following DL model analyzers: + +* [`bert-uncased`](#the-bert-uncased-analyzer): An analyzer based on the [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) model tokenizer. +* [`mbert-uncased`](#the-mbert-uncased-analyzer): A multilingual analyzer based on the [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased) model tokenizer. + +For Japanese text, use the [`mbert-uncased` analyzer](#the-mbert-uncased-analyzer) instead: the `bert-uncased` vocabulary is missing many kana characters, so many Japanese words, such as `パソコン`, are tokenized as `[UNK]` and match no documents. +{: .tip } + +## Usage considerations + +When using the DL model analyzers, keep the following considerations in mind: + +* These analyzers use lazy loading. The first call to these analyzers may take longer because dependencies and related resources are loaded. +* The tokenizers follow the same rules as their corresponding model tokenizers. + +## The bert-uncased analyzer + +The `bert-uncased` analyzer is based on the [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) model and tokenizes text according to the BERT WordPiece tokenization scheme. This analyzer is particularly useful for English language text. + +To analyze text with the `bert-uncased` analyzer, specify it in the `analyzer` field: + +```json +POST /_analyze +{ + "analyzer": "bert-uncased", + "text": "It's fun to contribute to OpenSearch!" +} +``` +{% include copy-curl.html %} + +## The mbert-uncased analyzer + +The `mbert-uncased` analyzer is based on the [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased) model, which supports tokenization across multiple languages. This makes it suitable for applications dealing with multilingual content. + +To analyze multilingual text, specify the `mbert-uncased` analyzer in the request: + +```json +POST /_analyze +{ + "analyzer": "mbert-uncased", + "text": "It's fun to contribute to OpenSearch!" +} +``` +{% include copy-curl.html %} + +### Half-width and full-width characters + +Like the model tokenizer, the `mbert-uncased` analyzer does not normalize half-width and full-width forms. For example, half-width `カメラ` is tokenized as `[UNK]`, so it does not match full-width `カメラ`, and full-width `ABC` does not match `abc`. The analyzer also removes Japanese voiced sound marks (dakuten and handakuten), so `パ` and `ハ` produce the same token. + +To match half-width and full-width forms, apply Unicode Normalization Form Compatibility Composition (NFKC) to both documents and queries. Normalize documents before they are encoded, for example, by using a `script` processor in the ingest pipeline: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline-sparse +{ + "processors": [ + { + "script": { + "source": "ctx.passage_text = Normalizer.normalize(ctx.passage_text, Normalizer.Form.NFKC)" + } + }, + { + "sparse_encoding": { + "model_id": "", + "field_map": { + "passage_text": "passage_embedding" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +To normalize queries, create a custom analyzer that applies the [ICU normalization character filter]({{site.url}}{{site.baseurl}}/analyzers/character-filters/icu-normalization/) before the `mbert-uncased` tokenizer. The character filter requires the [`analysis-icu` plugin]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/#installing-the-icu-plugin): + +```json +PUT /my-nlp-index +{ + "settings": { + "default_pipeline": "nlp-ingest-pipeline-sparse", + "analysis": { + "char_filter": { + "nfkc": { + "type": "icu_normalizer", + "name": "nfkc", + "mode": "compose" + } + }, + "analyzer": { + "mbert_nfkc": { + "type": "custom", + "char_filter": ["nfkc"], + "tokenizer": "mbert-uncased" + } + } + } + }, + "mappings": { + "properties": { + "passage_text": { + "type": "text" + }, + "passage_embedding": { + "type": "rank_features" + } + } + } +} +``` +{% include copy-curl.html %} + +Then specify the custom analyzer in the `neural_sparse` query: + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "カメラ", + "analyzer": "mbert_nfkc" + } + } + } +} +``` +{% include copy-curl.html %} + +## Example + +For a complete example of using DL model analyzers in neural sparse search queries, see [Generating sparse vector embeddings automatically]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-with-pipelines/). \ No newline at end of file diff --git a/_analyzers/supported-analyzers/fingerprint.md b/_analyzers/supported-analyzers/fingerprint.md new file mode 100644 index 00000000..267e16c0 --- /dev/null +++ b/_analyzers/supported-analyzers/fingerprint.md @@ -0,0 +1,115 @@ +--- +layout: default +title: Fingerprint analyzer +parent: Analyzers +nav_order: 60 +--- + +# Fingerprint analyzer + +The `fingerprint` analyzer creates a text fingerprint. The analyzer sorts and deduplicates the terms (tokens) generated from the input and then concatenates them using a separator. It is commonly used for data deduplication because it produces the same output for similar inputs containing the same words, regardless of word order. + +The `fingerprint` analyzer comprises the following components: + +- Standard tokenizer +- Lowercase token filter +- ASCII folding token filter +- Stop token filter +- Fingerprint token filter + +## Parameters + +The `fingerprint` analyzer can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`separator` | Optional | String | Specifies the character used to concatenate the terms after they have been tokenized, sorted, and deduplicated. Default is an empty space (` `). +`max_output_size` | Optional | Integer | Defines the maximum size of the output token. If the concatenated fingerprint exceeds this size, it will be truncated. Default is `255`. +`stopwords` | Optional | String or list of strings | A custom or predefined list of stopwords. Default is `_none_`. +`stopwords_path` | Optional | String | The path (absolute or relative to the config directory) to the file containing a list of stopwords. + + +## Example + +Use the following command to create an index named `my_custom_fingerprint_index` with a `fingerprint` analyzer: + +```json +PUT /my_custom_fingerprint_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_fingerprint_analyzer": { + "type": "fingerprint", + "separator": "-", + "max_output_size": 50, + "stopwords": ["to", "the", "over", "and"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_fingerprint_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_custom_fingerprint_index/_analyze +{ + "analyzer": "my_custom_fingerprint_analyzer", + "text": "The slow turtle swims over to the dog" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "dog-slow-swims-turtle", + "start_offset": 0, + "end_offset": 37, + "type": "fingerprint", + "position": 0 + } + ] +} +``` + +## Further customization + +If further customization is needed, you can define an analyzer with additional `fingerprint` analyzer components: + +```json +PUT /custom_fingerprint_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "custom_fingerprint": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "asciifolding", + "fingerprint" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_analyzers/supported-analyzers/index.md b/_analyzers/supported-analyzers/index.md new file mode 100644 index 00000000..8c4b87bb --- /dev/null +++ b/_analyzers/supported-analyzers/index.md @@ -0,0 +1,43 @@ +--- +layout: default +title: Analyzers +nav_order: 40 +has_children: true +has_toc: false +redirect_from: + - /analyzers/supported-analyzers/ +--- + +# Analyzers + +Analyzers transform text into tokens during indexing and search. OpenSearch provides built-in analyzers for common use cases and supports custom analyzers that combine character filters, tokenizers, and token filters. + +## Built-in analyzers + +The following table lists the built-in analyzers that OpenSearch provides. The last column of the table contains the result of applying the analyzer to the string `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`. + +Analyzer | Analysis performed | Analyzer output +:--- | :--- | :--- +[**Standard**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/standard/) (default) | - Parses strings into tokens at word boundaries
- Removes most punctuation
- Converts tokens to lowercase | [`it’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] +[**Simple**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/simple/) | - Parses strings into tokens on any non-letter character
- Removes non-letter characters
- Converts tokens to lowercase | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] +[**White space**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/whitespace/) | - Parses strings into tokens on white space | [`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] +[**Stop**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/stop/) | - Parses strings into tokens on any non-letter character
- Removes non-letter characters
- Removes stop words
- Converts tokens to lowercase | [`s`, `fun`, `contribute`, `brand`, `new`, `pr`, `opensearch`] +[**Keyword**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/keyword/) (no-op) | - Outputs the entire string unchanged | [`It’s fun to contribute a brand-new PR or 2 to OpenSearch!`] +[**Pattern**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/pattern/)| - Parses strings into tokens using regular expressions
- Supports converting strings to lowercase
- Supports removing stop words | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] +[**Language**]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/index/) | Performs analysis specific to a certain language (for example, `english`). | [`fun`, `contribut`, `brand`, `new`, `pr`, `2`, `opensearch`] +[**Fingerprint**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/fingerprint/) | - Parses strings on any non-letter character
- Normalizes characters by converting them to ASCII
- Converts tokens to lowercase
- Sorts, deduplicates, and concatenates tokens into a single token
- Supports removing stop words | [`2 a brand contribute fun it's new opensearch or pr to`]
Note that the apostrophe was converted to its ASCII counterpart. +[**DL model**]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/dl-model-analyzers/) | Use ML model tokenization rules for [neural sparse search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-search/). | Model-based tokens + +## Language analyzers + +OpenSearch supports multiple language analyzers. For more information, see [Language analyzers]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/index/). + +## Additional analyzers + +The following table lists the additional analyzers that OpenSearch supports. + +| Analyzer | Analysis performed | +|:---------------|:---------------------------------------------------------------------------------------------------------| +| [`phone`]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/phone-analyzers/#the-phone-analyzer) | An [index analyzer]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/) for parsing phone numbers. | +| [`phone-search`]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/phone-analyzers/#the-phone-search-analyzer) | A [search analyzer]({{site.url}}{{site.baseurl}}/analyzers/search-analyzers/) for parsing phone numbers. | + diff --git a/_analyzers/supported-analyzers/keyword.md b/_analyzers/supported-analyzers/keyword.md new file mode 100644 index 00000000..00c314d0 --- /dev/null +++ b/_analyzers/supported-analyzers/keyword.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Keyword analyzer +parent: Analyzers +nav_order: 80 +--- + +# Keyword analyzer + +The `keyword` analyzer doesn't tokenize text at all. Instead, it treats the entire input as a single token and does not break it into individual tokens. The `keyword` analyzer is often used for fields containing email addresses, URLs, or product IDs and in other cases where tokenization is not desirable. + +## Example + +Use the following command to create an index named `my_keyword_index` with a `keyword` analyzer: + +```json +PUT /my_keyword_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "keyword" + } + } + } +} +``` +{% include copy-curl.html %} + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to the `keyword` analyzer: + +```json +PUT /my_custom_keyword_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_keyword_analyzer": { + "tokenizer": "keyword" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_custom_keyword_index/_analyze +{ + "analyzer": "my_keyword_analyzer", + "text": "Just one token" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Just one token", + "start_offset": 0, + "end_offset": 14, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/supported-analyzers/pattern.md b/_analyzers/supported-analyzers/pattern.md new file mode 100644 index 00000000..bd47ddbe --- /dev/null +++ b/_analyzers/supported-analyzers/pattern.md @@ -0,0 +1,232 @@ +--- +layout: default +title: Pattern analyzer +parent: Analyzers +nav_order: 90 +--- + +# Pattern analyzer + +The `pattern` analyzer allows you to define a custom analyzer that uses a regular expression (regex) to split input text into tokens. The regex matches the separators between tokens, not the tokens themselves. It also provides options for applying regex flags, converting tokens to lowercase, and filtering out stopwords. + +The `pattern` analyzer consists of a [`pattern`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/pattern/) tokenizer followed by the [`lowercase`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/lowercase/) and [`stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/) token filters. The `stop` filter removes no tokens unless you specify `stopwords` or `stopwords_path`. + +## Parameters + +The `pattern` analyzer can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`pattern` | Optional | String | A [Java regular expression](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) used to tokenize the input. Default is `\W+`. +`flags` | Optional | String | A string containing pipe-separated [Java regex flags](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#field.summary) that modify the behavior of the regular expression. +`lowercase` | Optional | Boolean | Whether to convert tokens to lowercase. Default is `true`. +`stopwords` | Optional | String or list of strings | A string specifying a predefined list of stopwords (such as `_english_`) or an array specifying a custom list of stopwords. Default is `_none_`. +`stopwords_path` | Optional | String | The path (absolute or relative to the config directory) to the file containing a list of stopwords. + +A poorly written regular expression can make analysis very slow and, in extreme cases, cause a `StackOverflowError` that stops the node. Avoid patterns that can match the same text in many ways, such as nested quantifiers like `(a+)+`, and test new patterns on representative text using the [Analyze API]({{site.url}}{{site.baseurl}}/api-reference/analyze-apis/). +{: .warning} + +## Example + +Use the following command to create an index named `my_pattern_index` with a `pattern` analyzer: + +```json +PUT /my_pattern_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_pattern_analyzer": { + "type": "pattern", + "pattern": "\\W+", + "lowercase": true, + "stopwords": ["and", "is"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_pattern_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_pattern_index/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "OpenSearch is fast and scalable" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "fast", + "start_offset": 14, + "end_offset": 18, + "type": "word", + "position": 2 + }, + { + "token": "scalable", + "start_offset": 23, + "end_offset": 31, + "type": "word", + "position": 4 + } + ] +} +``` + +## Example: Splitting camel case identifiers + +Because the regex matches separators, it can also match the zero-width position between two characters. This lets you split identifiers in source code, such as class and method names, into separate words. The following pattern contains five alternatives that split text at runs of characters that are neither letters nor digits, between a lowercase and an uppercase letter, before the last letter of an uppercase acronym that is followed by a lowercase letter, and between letters and digits: + +```json +PUT /source-code +{ + "settings": { + "analysis": { + "analyzer": { + "camel_case_analyzer": { + "type": "pattern", + "pattern": "[^\\p{L}\\p{N}]+|(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})|(?<=\\p{L})(?=\\p{N})|(?<=\\p{N})(?=\\p{L})" + } + } + } + } +} +``` +{% include copy-curl.html %} + +In JSON, each backslash in the pattern must be escaped as `\\`. + +Use the following request to analyze a class and method name: + +```json +POST /source-code/_analyze +{ + "analyzer": "camel_case_analyzer", + "text": "XMLHttpRequest2Handler.sendJSONPayload" +} +``` +{% include copy-curl.html %} + +The response contains the individual words, converted to lowercase: + +```json +{ + "tokens": [ + { + "token": "xml", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "http", + "start_offset": 3, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "request", + "start_offset": 7, + "end_offset": 14, + "type": "word", + "position": 2 + }, + { + "token": "2", + "start_offset": 14, + "end_offset": 15, + "type": "word", + "position": 3 + }, + { + "token": "handler", + "start_offset": 15, + "end_offset": 22, + "type": "word", + "position": 4 + }, + { + "token": "send", + "start_offset": 23, + "end_offset": 27, + "type": "word", + "position": 5 + }, + { + "token": "json", + "start_offset": 27, + "end_offset": 31, + "type": "word", + "position": 6 + }, + { + "token": "payload", + "start_offset": 31, + "end_offset": 38, + "type": "word", + "position": 7 + } + ] +} +``` + +## Adding token filters to a pattern analyzer + +To apply token filters that the `pattern` analyzer does not provide, re-create it as a custom analyzer and add the filters to its `filter` array. The following request creates a custom analyzer that produces the same tokens as the default `pattern` analyzer: + +```json +PUT /custom-pattern-index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "\\W+" + } + }, + "analyzer": { + "rebuilt_pattern": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer", + "filter": [ + "lowercase" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Add more token filters after `lowercase` in the `filter` array. To remove stopwords, add a [`stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/) filter. diff --git a/_analyzers/supported-analyzers/phone-analyzers.md b/_analyzers/supported-analyzers/phone-analyzers.md new file mode 100644 index 00000000..d94bfe19 --- /dev/null +++ b/_analyzers/supported-analyzers/phone-analyzers.md @@ -0,0 +1,128 @@ +--- +layout: default +title: Phone number analyzers +parent: Analyzers +nav_order: 140 +--- + +# Phone number analyzers + +The `analysis-phonenumber` plugin provides analyzers and tokenizers for parsing phone numbers. A dedicated analyzer is required because parsing phone numbers is a non-trivial task (even though it might seem trivial at first glance). For common misconceptions regarding phone number parsing, see [Falsehoods programmers believe about phone numbers](https://github.com/google/libphonenumber/blob/master/FALSEHOODS.md). + + +OpenSearch supports the following phone number analyzers: + +* [`phone`](#the-phone-analyzer): An [index analyzer]({{site.url}}{{site.baseurl}}/analyzers/index-analyzers/) to use at indexing time. +* [`phone-search`](#the-phone-search-analyzer): A [search analyzer]({{site.url}}{{site.baseurl}}/analyzers/search-analyzers/) to use at search time. + +Internally, the plugin uses the [`libphonenumber`](https://github.com/google/libphonenumber) library and follows its parsing rules. + +The phone number analyzers are not meant to find phone numbers in larger texts. Instead, you should use them on fields that only contain phone numbers. +{: .note} + +## Installing the plugin + +Before you can use the phone number analyzers, you must install the `analysis-phonenumber` plugin by running the following command: + +```sh +./bin/opensearch-plugin install analysis-phonenumber +``` + +## Specifying a default region + +You can optionally specify a default region for parsing phone numbers by providing the `phone-region` parameter within the analyzer. Valid phone regions are represented by ISO 3166 country codes. For more information, see [List of ISO 3166 country codes](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes). + +When tokenizing phone numbers containing the international calling prefix `+`, the default region is irrelevant. However, for phone numbers that use a national prefix for international numbers (for example, `001` instead of `+1` to dial Northern America from most European countries), the region needs to be provided. You can also properly index local phone numbers with no international prefix by specifying the region. + +## Example + +The following request creates an index containing one field that ingests phone numbers for Switzerland (region code `CH`): + +```json +PUT /example-phone +{ + "settings": { + "analysis": { + "analyzer": { + "phone-ch": { + "type": "phone", + "phone-region": "CH" + }, + "phone-search-ch": { + "type": "phone-search", + "phone-region": "CH" + } + } + } + }, + "mappings": { + "properties": { + "phone_number": { + "type": "text", + "analyzer": "phone-ch", + "search_analyzer": "phone-search-ch" + } + } + } +} +``` +{% include copy-curl.html %} + +## The phone analyzer + +The `phone` analyzer generates n-grams based on the given phone number. A (fictional) Swiss phone number containing an international calling prefix can be parsed with or without the Swiss-specific phone region. Thus, the following two requests will produce the same result: + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone-ch", + "text" : "+41 60 555 12 34" +} +``` +{% include copy-curl.html %} + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone", + "text" : "+41 60 555 12 34" +} +``` +{% include copy-curl.html %} + +The response contains the generated n-grams: + +```json +["+41 60 555 12 34", "6055512", "41605551", "416055512", "6055", "41605551234", ...] +``` + +However, if you specify the phone number without the international calling prefix `+` (either by using `0041` or omitting +the international calling prefix altogether), then only the analyzer configured with the correct phone region can parse the number: + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone-ch", + "text" : "060 555 12 34" +} +``` +{% include copy-curl.html %} + +## The phone-search analyzer + +In contrast, the `phone-search` analyzer does not create n-grams and only issues some basic tokens. For example, send the following request and specify the `phone-search` analyzer: + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone-search", + "text" : "+41 60 555 12 34" +} +``` +{% include copy-curl.html %} + +The response contains the following tokens: + +```json +["+41 60 555 12 34", "41 60 555 12 34", "41605551234", "605551234", "41"] +``` diff --git a/_analyzers/supported-analyzers/simple.md b/_analyzers/supported-analyzers/simple.md new file mode 100644 index 00000000..29f8f9a5 --- /dev/null +++ b/_analyzers/supported-analyzers/simple.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Simple analyzer +parent: Analyzers +nav_order: 100 +--- + +# Simple analyzer + +The `simple` analyzer is a very basic analyzer that breaks text into terms at non-letter characters and lowercases the terms. Unlike the `standard` analyzer, the `simple` analyzer treats everything except for alphabetic characters as delimiters, meaning that it does not recognize numbers, punctuation, or special characters as part of the tokens. + +## Example + +Use the following command to create an index named `my_simple_index` with a `simple` analyzer: + +```json +PUT /my_simple_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "simple" + } + } + } +} +``` +{% include copy-curl.html %} + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to a `simple` analyzer with an added `html_strip` character filter: + +```json +PUT /my_custom_simple_index +{ + "settings": { + "analysis": { + "char_filter": { + "html_strip": { + "type": "html_strip" + } + }, + "tokenizer": { + "my_lowercase_tokenizer": { + "type": "lowercase" + } + }, + "analyzer": { + "my_custom_simple_analyzer": { + "type": "custom", + "char_filter": ["html_strip"], + "tokenizer": "my_lowercase_tokenizer", + "filter": ["lowercase"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_simple_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_custom_simple_index/_analyze +{ + "analyzer": "my_custom_simple_analyzer", + "text": "

The slow turtle swims over to dogs © 2024!

" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "the","start_offset": 3,"end_offset": 6,"type": "word","position": 0}, + {"token": "slow","start_offset": 7,"end_offset": 11,"type": "word","position": 1}, + {"token": "turtle","start_offset": 12,"end_offset": 18,"type": "word","position": 2}, + {"token": "swims","start_offset": 19,"end_offset": 24,"type": "word","position": 3}, + {"token": "over","start_offset": 25,"end_offset": 29,"type": "word","position": 4}, + {"token": "to","start_offset": 30,"end_offset": 32,"type": "word","position": 5}, + {"token": "dogs","start_offset": 33,"end_offset": 37,"type": "word","position": 6} + ] +} +``` diff --git a/_analyzers/supported-analyzers/standard.md b/_analyzers/supported-analyzers/standard.md new file mode 100644 index 00000000..ed84d6f7 --- /dev/null +++ b/_analyzers/supported-analyzers/standard.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Standard analyzer +parent: Analyzers +nav_order: 50 +--- + +# Standard analyzer + +The `standard` analyzer is the built-in default analyzer used for general-purpose full-text search in OpenSearch. It is designed to provide consistent, language-agnostic text processing by efficiently breaking down text into searchable terms. + +The `standard` analyzer performs the following operations: + +- **Tokenization**: Uses the [`standard`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/standard/) tokenizer, which splits text into words based on Unicode text segmentation rules, handling spaces, punctuation, and common delimiters. +- **Lowercasing**: Applies the [`lowercase`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/lowercase/) token filter to convert all tokens to lowercase, ensuring consistent matching regardless of input case. + +This combination makes the `standard` analyzer ideal for indexing a wide range of natural language content without needing language-specific customizations. + + +## Example: Creating an index with the standard analyzer + +You can assign the `standard` analyzer to a text field when creating an index: + +```json +PUT /my_standard_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "standard" + } + } + } +} +``` +{% include copy-curl.html %} + + +## Parameters + +The `standard` analyzer supports the following optional parameters. + +| Parameter | Data type | Default | Description | +|:----------|:-----|:--------|:------------| +| `max_token_length` | Integer | `255` | The maximum length that a token can be before it is split. | +| `stopwords` | String or list of strings | None | A list of stopwords or a [predefined stopword set for a language]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/#predefined-stopword-sets-by-language) to remove during analysis. For example, `_english_`. | +| `stopwords_path` | String | None | The path to a file containing stopwords to be used during analysis. | + +Only use one of the parameters `stopwords` or `stopwords_path`. If both are used, no error is returned but only the `stopwords` parameter is applied. +{: .note} + +## Example: Analyzer with parameters + +The following example creates a `products` index and configures the `max_token_length` and `stopwords` parameters: + +```json +PUT /animals +{ + "settings": { + "analysis": { + "analyzer": { + "my_manual_stopwords_analyzer": { + "type": "standard", + "max_token_length": 10, + "stopwords": [ + "the", "is", "and", "but", "an", "a", "it" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following `_analyze` API request to see how the `my_manual_stopwords_analyzer` processes text: + +```json +POST /animals/_analyze +{ + "analyzer": "my_manual_stopwords_analyzer", + "text": "The Turtle is Large but it is Slow" +} +``` +{% include copy-curl.html %} + +The returned tokens: + +- Have been split on spaces. +- Have been lowercased. +- Have had stopwords removed. + +```json +{ + "tokens": [ + { + "token": "turtle", + "start_offset": 4, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "large", + "start_offset": 14, + "end_offset": 19, + "type": "", + "position": 3 + }, + { + "token": "slow", + "start_offset": 30, + "end_offset": 34, + "type": "", + "position": 7 + } + ] +} +``` diff --git a/_analyzers/supported-analyzers/stop.md b/_analyzers/supported-analyzers/stop.md new file mode 100644 index 00000000..df62c7fe --- /dev/null +++ b/_analyzers/supported-analyzers/stop.md @@ -0,0 +1,177 @@ +--- +layout: default +title: Stop analyzer +parent: Analyzers +nav_order: 110 +--- + +# Stop analyzer + +The `stop` analyzer removes a predefined list of stopwords. This analyzer consists of a `lowercase` tokenizer and a `stop` token filter. + +## Parameters + +You can configure a `stop` analyzer with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`stopwords` | Optional | String or list of strings | A string specifying a predefined list of stopwords (such as `_english_`) or an array specifying a custom list of stopwords. Default is `_english_`. +`stopwords_path` | Optional | String | The path (absolute or relative to the config directory) to the file containing a list of stopwords. + +## Example + +Use the following command to create an index named `my_stop_index` with a `stop` analyzer: + +```json +PUT /my_stop_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "stop" + } + } + } +} +``` +{% include copy-curl.html %} + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to a `stop` analyzer: + +```json +PUT /my_custom_stop_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_stop_analyzer": { + "tokenizer": "lowercase", + "filter": [ + "stop" + ] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_stop_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_custom_stop_analyzer_index/_analyze +{ + "analyzer": "my_custom_stop_analyzer", + "text": "The large turtle is green and brown" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "large", + "start_offset": 4, + "end_offset": 9, + "type": "word", + "position": 1 + }, + { + "token": "turtle", + "start_offset": 10, + "end_offset": 16, + "type": "word", + "position": 2 + }, + { + "token": "green", + "start_offset": 20, + "end_offset": 25, + "type": "word", + "position": 4 + }, + { + "token": "brown", + "start_offset": 30, + "end_offset": 35, + "type": "word", + "position": 6 + } + ] +} +``` + +# Specifying stopwords + +The following example request specifies a custom list of stopwords: + +```json +PUT /my_new_custom_stop_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_stop_analyzer": { + "type": "stop", + "stopwords": ["is", "and", "was"] + } + } + } + }, + "mappings": { + "properties": { + "description": { + "type": "text", + "analyzer": "my_custom_stop_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +The following example request specifies a path to the file containing stopwords: + +```json +PUT /my_new_custom_stop_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_stop_analyzer": { + "type": "stop", + "stopwords_path": "stopwords.txt" + } + } + } + }, + "mappings": { + "properties": { + "description": { + "type": "text", + "analyzer": "my_custom_stop_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +In this example, the file is located in the config directory. You can also specify a full path to the file. \ No newline at end of file diff --git a/_analyzers/supported-analyzers/whitespace.md b/_analyzers/supported-analyzers/whitespace.md new file mode 100644 index 00000000..f1d35696 --- /dev/null +++ b/_analyzers/supported-analyzers/whitespace.md @@ -0,0 +1,87 @@ +--- +layout: default +title: White space analyzer +parent: Analyzers +nav_order: 120 +--- + +# White space analyzer + +The `whitespace` analyzer breaks text into tokens based only on white space characters (for example, spaces and tabs). It does not apply any transformations, such as lowercasing or removing stopwords, so the original case of the text is retained and punctuation is included as part of the tokens. + +## Example + +Use the following command to create an index named `my_whitespace_index` with a `whitespace` analyzer: + +```json +PUT /my_whitespace_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "whitespace" + } + } + } +} +``` +{% include copy-curl.html %} + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to a `whitespace` analyzer with an added `lowercase` character filter: + +```json +PUT /my_custom_whitespace_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_whitespace_analyzer": { + "type": "custom", + "tokenizer": "whitespace", + "filter": ["lowercase"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_whitespace_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_custom_whitespace_index/_analyze +{ + "analyzer": "my_custom_whitespace_analyzer", + "text": "The SLOW turtle swims away! 123" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "the","start_offset": 0,"end_offset": 3,"type": "word","position": 0}, + {"token": "slow","start_offset": 4,"end_offset": 8,"type": "word","position": 1}, + {"token": "turtle","start_offset": 9,"end_offset": 15,"type": "word","position": 2}, + {"token": "swims","start_offset": 16,"end_offset": 21,"type": "word","position": 3}, + {"token": "away!","start_offset": 22,"end_offset": 27,"type": "word","position": 4}, + {"token": "123","start_offset": 28,"end_offset": 31,"type": "word","position": 5} + ] +} +``` diff --git a/_analyzers/token-filters/apostrophe.md b/_analyzers/token-filters/apostrophe.md new file mode 100644 index 00000000..47d76980 --- /dev/null +++ b/_analyzers/token-filters/apostrophe.md @@ -0,0 +1,118 @@ +--- +layout: default +title: Apostrophe +parent: Token filters +nav_order: 10 +--- + +# Apostrophe token filter + +The `apostrophe` token filter's primary function is to remove possessive apostrophes and anything following them. This can be very useful in analyzing text in languages that rely heavily on apostrophes, such as Turkish, in which apostrophes separate the root word from suffixes, including possessive suffixes, case markers, and other grammatical endings. + + +## Example + +The following example request creates a new index named `custom_text_index` with a custom analyzer configured in `settings` and used in `mappings`: + +```json +PUT /custom_text_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "apostrophe" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "custom_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the created analyzer: + +```json +POST /custom_text_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "John's car is faster than Peter's bike" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "john", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "car", + "start_offset": 7, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "", + "position": 2 + }, + { + "token": "faster", + "start_offset": 14, + "end_offset": 20, + "type": "", + "position": 3 + }, + { + "token": "than", + "start_offset": 21, + "end_offset": 25, + "type": "", + "position": 4 + }, + { + "token": "peter", + "start_offset": 26, + "end_offset": 33, + "type": "", + "position": 5 + }, + { + "token": "bike", + "start_offset": 34, + "end_offset": 38, + "type": "", + "position": 6 + } + ] +} +``` + +The built-in `apostrophe` token filter is not suitable for languages such as French, in which apostrophes are used at the beginning of words. For example, `"C'est l'amour de l'école"` will result in four tokens: "C", "l", "de", and "l". +{: .note} diff --git a/_analyzers/token-filters/asciifolding.md b/_analyzers/token-filters/asciifolding.md new file mode 100644 index 00000000..d5722519 --- /dev/null +++ b/_analyzers/token-filters/asciifolding.md @@ -0,0 +1,135 @@ +--- +layout: default +title: ASCII folding +parent: Token filters +nav_order: 20 +--- + +# ASCII folding token filter + +The `asciifolding` token filter converts non-ASCII characters to their closest ASCII equivalents. For example, *é* becomes *e*, *ü* becomes *u*, and *ñ* becomes *n*. This process is known as *transliteration*. + + +The `asciifolding` token filter offers a number of benefits: + + - **Enhanced search flexibility**: Users often omit accents or special characters when entering queries. The `asciifolding` token filter ensures that such queries still return relevant results. + - **Normalization**: Standardizes the indexing process by ensuring that accented characters are consistently converted to their ASCII equivalents. + - **Internationalization**: Particularly useful for applications including multiple languages and character sets. + +While the `asciifolding` token filter can simplify searches, it may also lead to the loss of specific information, particularly if the distinction between accented and non-accented characters in the dataset is significant. +{: .warning} + +## Parameters + +You can configure the `asciifolding` token filter using the `preserve_original` parameter. Setting this parameter to `true` keeps both the original token and its ASCII-folded version in the token stream. This can be particularly useful when you want to match both the original (with accents) and the normalized (without accents) versions of a term in a search query. Default is `false`. + +## Example + +The following example request creates a new index named `example_index` and defines an analyzer with the `asciifolding` filter and `preserve_original` parameter set to `true`: + +```json +PUT /example_index +{ + "settings": { + "analysis": { + "filter": { + "custom_ascii_folding": { + "type": "asciifolding", + "preserve_original": true + } + }, + "analyzer": { + "custom_ascii_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "custom_ascii_folding" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /example_index/_analyze +{ + "analyzer": "custom_ascii_analyzer", + "text": "Résumé café naïve coördinate" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "resume", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "résumé", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "cafe", + "start_offset": 7, + "end_offset": 11, + "type": "", + "position": 1 + }, + { + "token": "café", + "start_offset": 7, + "end_offset": 11, + "type": "", + "position": 1 + }, + { + "token": "naive", + "start_offset": 12, + "end_offset": 17, + "type": "", + "position": 2 + }, + { + "token": "naïve", + "start_offset": 12, + "end_offset": 17, + "type": "", + "position": 2 + }, + { + "token": "coordinate", + "start_offset": 18, + "end_offset": 28, + "type": "", + "position": 3 + }, + { + "token": "coördinate", + "start_offset": 18, + "end_offset": 28, + "type": "", + "position": 3 + } + ] +} +``` + + diff --git a/_analyzers/token-filters/cjk-bigram.md b/_analyzers/token-filters/cjk-bigram.md new file mode 100644 index 00000000..5e5c56fd --- /dev/null +++ b/_analyzers/token-filters/cjk-bigram.md @@ -0,0 +1,160 @@ +--- +layout: default +title: CJK bigram +parent: Token filters +nav_order: 30 +--- + +# CJK bigram token filter + +The `cjk_bigram` token filter is designed specifically for processing East Asian languages, such as Chinese, Japanese, and Korean (CJK), which typically don't use spaces to separate words. A bigram is a sequence of two adjacent elements in a string of tokens, which can be characters or words. For CJK languages, bigrams help approximate word boundaries and capture significant character pairs that can convey meaning. + + +## Parameters + +The `cjk_bigram` token filter can be configured with two parameters: `ignored_scripts` and `output_unigrams`. + +### ignored_scripts + +The `cjk-bigram` token filter ignores all non-CJK scripts (writing systems like Latin or Cyrillic) and tokenizes only CJK text into bigrams. Use this option to specify CJK scripts to be ignored. This option takes the following valid values: + +- `han`: The `han` script processes Han characters. [Han characters](https://simple.wikipedia.org/wiki/Chinese_characters) are logograms used in the written languages of China, Japan, and Korea. The filter can help with text processing tasks like tokenizing, normalizing, or stemming text written in Chinese, Japanese kanji, or Korean Hanja. + +- `hangul`: The `hangul` script processes Hangul characters, which are unique to the Korean language and do not exist in other East Asian scripts. + +- `hiragana`: The `hiragana` script processes hiragana, one of the two syllabaries used in the Japanese writing system. + Hiragana is typically used for native Japanese words, grammatical elements, and certain forms of punctuation. + +- `katakana`: The `katakana` script processes katakana, the other Japanese syllabary. + Katakana is mainly used for foreign loanwords, onomatopoeia, scientific names, and certain Japanese words. + + +### output_unigrams + +This option, when set to `true`, outputs both unigrams (single characters) and bigrams. Default is `false`. + +## Example + +The following example request creates a new index named `devanagari_example_index` and defines an analyzer with the `cjk_bigram_filter` filter and `ignored_scripts` parameter set to `katakana`: + +```json +PUT /cjk_bigram_example +{ + "settings": { + "analysis": { + "analyzer": { + "cjk_bigrams_no_katakana": { + "tokenizer": "standard", + "filter": [ "cjk_bigrams_no_katakana_filter" ] + } + }, + "filter": { + "cjk_bigrams_no_katakana_filter": { + "type": "cjk_bigram", + "ignored_scripts": [ + "katakana" + ], + "output_unigrams": true + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /cjk_bigram_example/_analyze +{ + "analyzer": "cjk_bigrams_no_katakana", + "text": "東京タワーに行く" +} +``` +{% include copy-curl.html %} + +Sample text: "東京タワーに行く" + + 東京 (Kanji for "Tokyo") + タワー (Katakana for "Tower") + に行く (Hiragana and Kanji for "go to") + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "東", + "start_offset": 0, + "end_offset": 1, + "type": "", + "position": 0 + }, + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "", + "position": 0, + "positionLength": 2 + }, + { + "token": "京", + "start_offset": 1, + "end_offset": 2, + "type": "", + "position": 1 + }, + { + "token": "タワー", + "start_offset": 2, + "end_offset": 5, + "type": "", + "position": 2 + }, + { + "token": "に", + "start_offset": 5, + "end_offset": 6, + "type": "", + "position": 3 + }, + { + "token": "に行", + "start_offset": 5, + "end_offset": 7, + "type": "", + "position": 3, + "positionLength": 2 + }, + { + "token": "行", + "start_offset": 6, + "end_offset": 7, + "type": "", + "position": 4 + }, + { + "token": "行く", + "start_offset": 6, + "end_offset": 8, + "type": "", + "position": 4, + "positionLength": 2 + }, + { + "token": "く", + "start_offset": 7, + "end_offset": 8, + "type": "", + "position": 5 + } + ] +} +``` + + diff --git a/_analyzers/token-filters/cjk-width.md b/_analyzers/token-filters/cjk-width.md new file mode 100644 index 00000000..4960729c --- /dev/null +++ b/_analyzers/token-filters/cjk-width.md @@ -0,0 +1,96 @@ +--- +layout: default +title: CJK width +parent: Token filters +nav_order: 40 +--- + +# CJK width token filter + +The `cjk_width` token filter normalizes Chinese, Japanese, and Korean (CJK) tokens by converting full-width ASCII characters to their standard (half-width) ASCII equivalents and half-width katakana characters to their full-width equivalents. + +### Converting full-width ASCII characters + +In CJK texts, ASCII characters (such as letters and numbers) can appear in full-width form, occupying the space of two half-width characters. Full-width ASCII characters are typically used in East Asian typography for alignment with the width of CJK characters. However, for the purposes of indexing and searching, these full-width characters need to be normalized to their standard (half-width) ASCII equivalents. + +The following example illustrates ASCII character normalization: + +``` + Full-Width: ABCDE 12345 + Normalized (half-width): ABCDE 12345 +``` + +### Converting half-width katakana characters + +The `cjk_width` token filter converts half-width katakana characters to their full-width counterparts, which are the standard form used in Japanese text. This normalization, illustrated in the following example, is important for consistency in text processing and searching: + + +``` + Half-Width katakana: カタカナ + Normalized (full-width) katakana: カタカナ +``` + +## Example + +The following example request creates a new index named `cjk_width_example_index` and defines an analyzer with the `cjk_width` filter: + +```json +PUT /cjk_width_example_index +{ + "settings": { + "analysis": { + "analyzer": { + "cjk_width_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["cjk_width"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /cjk_width_example_index/_analyze +{ + "analyzer": "cjk_width_analyzer", + "text": "Tokyo 2024 カタカナ" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Tokyo", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "2024", + "start_offset": 6, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "カタカナ", + "start_offset": 11, + "end_offset": 15, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/classic.md b/_analyzers/token-filters/classic.md new file mode 100644 index 00000000..34db74a8 --- /dev/null +++ b/_analyzers/token-filters/classic.md @@ -0,0 +1,93 @@ +--- +layout: default +title: Classic +parent: Token filters +nav_order: 50 +--- + +# Classic token filter + +The primary function of the classic token filter is to work alongside the classic tokenizer. It processes tokens by applying the following common transformations, which aid in text analysis and search: + - Removal of possessive endings such as *'s*. For example, *John's* becomes *John*. + - Removal of periods from acronyms. For example, *D.A.R.P.A.* becomes *DARPA*. + + +## Example + +The following example request creates a new index named `custom_classic_filter` and configures an analyzer with the `classic` filter: + +```json +PUT /custom_classic_filter +{ + "settings": { + "analysis": { + "analyzer": { + "custom_classic": { + "type": "custom", + "tokenizer": "classic", + "filter": ["classic"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /custom_classic_filter/_analyze +{ + "analyzer": "custom_classic", + "text": "John's co-operate was excellent." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "John", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "co", + "start_offset": 7, + "end_offset": 9, + "type": "", + "position": 1 + }, + { + "token": "operate", + "start_offset": 10, + "end_offset": 17, + "type": "", + "position": 2 + }, + { + "token": "was", + "start_offset": 18, + "end_offset": 21, + "type": "", + "position": 3 + }, + { + "token": "excellent", + "start_offset": 22, + "end_offset": 31, + "type": "", + "position": 4 + } + ] +} +``` + diff --git a/_analyzers/token-filters/common_gram.md b/_analyzers/token-filters/common_gram.md new file mode 100644 index 00000000..58f5bbe1 --- /dev/null +++ b/_analyzers/token-filters/common_gram.md @@ -0,0 +1,94 @@ +--- +layout: default +title: Common grams +parent: Token filters +nav_order: 60 +--- + +# Common grams token filter + +The `common_grams` token filter improves search relevance by keeping commonly occurring phrases (common grams) in the text. This is useful when dealing with languages or datasets in which certain word combinations frequently occur as a unit and can impact search relevance if treated as separate tokens. If any common words are present in the input string, this token filter generates both their unigrams and bigrams. + +Using this token filter improves search relevance by keeping common phrases intact. This can help in matching queries more accurately, particularly for frequent word combinations. It also improves search precision by reducing the number of irrelevant matches. + +When using this filter, you must carefully select and maintain the `common_words` list. +{: .warning} + +## Parameters + +The `common_grams` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`common_words` | Required | List of strings | A list of words that should be treated as words that commonly appear together. These words will be used to generate common grams. If the `common_words` parameter is an empty list, the `common_grams` token filter becomes a no-op filter, meaning that it doesn't modify the input tokens at all. +`ignore_case` | Optional | Boolean | Indicates whether the filter should ignore case differences when matching common words. Default is `false`. +`query_mode` | Optional | Boolean | When set to `true`, the following rules are applied:
- Unigrams that are generated from `common_words` are not included in the output.
- Bigrams in which a non-common word is followed by a common word are retained in the output.
- Unigrams of non-common words are excluded if they are immediately followed by a common word.
- If a non-common word appears at the end of the text and is preceded by a common word, its unigram is not included in the output. + + +## Example + +The following example request creates a new index named `my_common_grams_index` and configures an analyzer with the `common_grams` filter: + +```json +PUT /my_common_grams_index +{ + "settings": { + "analysis": { + "filter": { + "my_common_grams_filter": { + "type": "common_grams", + "common_words": ["a", "in", "for"], + "ignore_case": true, + "query_mode": true + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_common_grams_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_common_grams_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "A quick black cat jumps over the lazy dog in the park" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "a_quick","start_offset": 0,"end_offset": 7,"type": "gram","position": 0}, + {"token": "quick","start_offset": 2,"end_offset": 7,"type": "","position": 1}, + {"token": "black","start_offset": 8,"end_offset": 13,"type": "","position": 2}, + {"token": "cat","start_offset": 14,"end_offset": 17,"type": "","position": 3}, + {"token": "jumps","start_offset": 18,"end_offset": 23,"type": "","position": 4}, + {"token": "over","start_offset": 24,"end_offset": 28,"type": "","position": 5}, + {"token": "the","start_offset": 29,"end_offset": 32,"type": "","position": 6}, + {"token": "lazy","start_offset": 33,"end_offset": 37,"type": "","position": 7}, + {"token": "dog_in","start_offset": 38,"end_offset": 44,"type": "gram","position": 8}, + {"token": "in_the","start_offset": 42,"end_offset": 48,"type": "gram","position": 9}, + {"token": "the","start_offset": 45,"end_offset": 48,"type": "","position": 10}, + {"token": "park","start_offset": 49,"end_offset": 53,"type": "","position": 11} + ] +} +``` + diff --git a/_analyzers/token-filters/condition.md b/_analyzers/token-filters/condition.md new file mode 100644 index 00000000..5e87c2cb --- /dev/null +++ b/_analyzers/token-filters/condition.md @@ -0,0 +1,135 @@ +--- +layout: default +title: Condition +parent: Token filters +nav_order: 70 +--- + +# Condition token filter + +The `condition` token filter is a special type of filter that allows you to apply other token filters conditionally based on certain criteria. This provides more control over when certain token filters should be applied during text analysis. +Multiple filters can be configured and only applied when they meet the conditions you define. +This token filter can be very useful for language-specific processing and handling of special characters. + + +## Parameters + +There are two parameters that must be configured in order to use the `condition` token filter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`filter` | Required | Array | Specifies which token filters should be applied to the tokens when the specified condition (defined by the `script` parameter) is met. +`script` | Required | Object | Configures an [inline script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/exec-script/) that defines the condition that needs to be met in order for the filters specified in the `filter` parameter to be applied (only inline scripts are accepted). + + +## Example + +The following example request creates a new index named `my_conditional_index` and configures an analyzer with a `condition` filter. This filter applies a `lowercase` filter to any tokens that contain the character sequence "um": + +```json +PUT /my_conditional_index +{ + "settings": { + "analysis": { + "filter": { + "my_conditional_filter": { + "type": "condition", + "filter": ["lowercase"], + "script": { + "source": "token.getTerm().toString().contains('um')" + } + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "my_conditional_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_conditional_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "THE BLACK CAT JUMPS OVER A LAZY DOG" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "THE", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "BLACK", + "start_offset": 4, + "end_offset": 9, + "type": "", + "position": 1 + }, + { + "token": "CAT", + "start_offset": 10, + "end_offset": 13, + "type": "", + "position": 2 + }, + { + "token": "jumps", + "start_offset": 14, + "end_offset": 19, + "type": "", + "position": 3 + }, + { + "token": "OVER", + "start_offset": 20, + "end_offset": 24, + "type": "", + "position": 4 + }, + { + "token": "A", + "start_offset": 25, + "end_offset": 26, + "type": "", + "position": 5 + }, + { + "token": "LAZY", + "start_offset": 27, + "end_offset": 31, + "type": "", + "position": 6 + }, + { + "token": "DOG", + "start_offset": 32, + "end_offset": 35, + "type": "", + "position": 7 + } + ] +} +``` + diff --git a/_analyzers/token-filters/decimal-digit.md b/_analyzers/token-filters/decimal-digit.md new file mode 100644 index 00000000..002375f7 --- /dev/null +++ b/_analyzers/token-filters/decimal-digit.md @@ -0,0 +1,88 @@ +--- +layout: default +title: Decimal digit +parent: Token filters +nav_order: 80 +--- + +# Decimal digit token filter + +The `decimal_digit` token filter is used to normalize decimal digit characters (0--9) into their ASCII equivalents in various scripts. This is useful when you want to ensure that all digits are treated uniformly in text analysis, regardless of the script in which they are written. + + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `decimal_digit` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_decimal_digit_filter": { + "type": "decimal_digit" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["my_decimal_digit_filter"] + } + } + } + } +} + +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "123 ١٢٣ १२३" +} +``` +{% include copy-curl.html %} + +`text` breakdown: + + - "123" (ASCII digits) + - "١٢٣" (Arabic-Indic digits) + - "१२३" (Devanagari digits) + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "123", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "123", + "start_offset": 4, + "end_offset": 7, + "type": "", + "position": 1 + }, + { + "token": "123", + "start_offset": 8, + "end_offset": 11, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/delimited-payload.md b/_analyzers/token-filters/delimited-payload.md new file mode 100644 index 00000000..f17bb1b1 --- /dev/null +++ b/_analyzers/token-filters/delimited-payload.md @@ -0,0 +1,211 @@ +--- +layout: default +title: Delimited payload +parent: Token filters +nav_order: 90 +--- + +# Delimited payload token filter + +The `delimited_payload` token filter is used to parse tokens containing payloads during the analysis process. For example, the string `red|1.5 fast|2.0 car|1.0` is parsed into the tokens `red` (with a payload of `1.5`), `fast` (with a payload of `2.0`), and `car` (with a payload of `1.0`). This is particularly useful when your tokens include additional associated data (like weights, scores, or other numeric values) that you can use for scoring or custom query logic. The filter can handle different types of payloads, including integers, floats, and strings, and attach payloads (extra metadata) to tokens. + +When analyzing text, the `delimited_payload` token filter parses each token, extracts the payload, and attaches it to the token. This payload can later be used in queries to influence scoring, boosting, or other custom behaviors. + +Payloads are stored as Base64-encoded strings. By default, payloads are not returned in the query response along with the tokens. To return the payloads, you must configure additional parameters. For more information, see [Example with a stored payload]({{site.url}}{{site.baseurl}}/analyzers/token-filters/delimited-payload/#example-without-a-stored-payload). + +## Parameters + +The `delimited_payload` token filter has two parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`encoding` | Optional | String | Specifies the data type of the payload attached to the tokens. This determines how the payload data is interpreted during analysis and querying.
Valid values are:

- `float`: The payload is interpreted as a 32-bit floating-point number using IEEE 754 format (for example, `2.5` in `car|2.5`).
- `identity`: The payload is interpreted as a sequence of characters (for example, in `user|admin`, `admin` is interpreted as a string).
- `int`: The payload is interpreted as a 32-bit integer (for example, `1` in `priority|1`).
Default is `float`. +`delimiter` | Optional | String | Specifies the character that separates the token from its payload in the input text. Default is the pipe character (`|`). + +## Example without a stored payload + +The following example request creates a new index named `my_index` and configures an analyzer with a `delimited_payload` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_payload_filter": { + "type": "delimited_payload", + "delimiter": "|", + "encoding": "float" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "whitespace", + "filter": ["my_payload_filter"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "red|1.5 fast|2.0 car|1.0" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "red", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "fast", + "start_offset": 8, + "end_offset": 16, + "type": "word", + "position": 1 + }, + { + "token": "car", + "start_offset": 17, + "end_offset": 24, + "type": "word", + "position": 2 + } + ] +} +``` + +## Example with a stored payload + +To configure the payload to be returned in the response, create an index that stores term vectors and set `term_vector` to `with_positions_payloads` or `with_positions_offsets_payloads` in the index mappings. For example, the following index is configured to store term vectors: + +```json +PUT /visible_payloads +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_payloads", + "analyzer": "custom_analyzer" + } + } + }, + "settings": { + "analysis": { + "filter": { + "my_payload_filter": { + "type": "delimited_payload", + "delimiter": "|", + "encoding": "float" + } + }, + "analyzer": { + "custom_analyzer": { + "tokenizer": "whitespace", + "filter": [ "my_payload_filter" ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +You can index a document into this index using the following request: + +```json +PUT /visible_payloads/_doc/1 +{ + "text": "red|1.5 fast|2.0 car|1.0" +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /visible_payloads/_termvectors/1 +{ + "fields": ["text"] +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens, which include payloads: + +```json +{ + "_index": "visible_payloads", + "_id": "1", + "_version": 1, + "found": true, + "took": 3, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 3, + "doc_count": 1, + "sum_ttf": 3 + }, + "terms": { + "brown": { + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 10, + "end_offset": 19, + "payload": "QEAAAA==" + } + ] + }, + "fox": { + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 20, + "end_offset": 27, + "payload": "P8AAAA==" + } + ] + }, + "quick": { + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 9, + "payload": "QCAAAA==" + } + ] + } + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_analyzers/token-filters/delimited-term-frequency.md b/_analyzers/token-filters/delimited-term-frequency.md index e2db7644..f0b26716 100644 --- a/_analyzers/token-filters/delimited-term-frequency.md +++ b/_analyzers/token-filters/delimited-term-frequency.md @@ -112,9 +112,9 @@ The response contains both the original token and the parsed version with the te "name": "keyword", "tokens": [ { - "token": "foo|100", + "token": "foo^3", "start_offset": 0, - "end_offset": 7, + "end_offset": 5, "type": "word", "position": 0, "termFrequency": 1 @@ -123,15 +123,15 @@ The response contains both the original token and the parsed version with the te }, "tokenfilters": [ { - "name": "delimited_term_freq", + "name": "my_delimited_term_freq", "tokens": [ { "token": "foo", "start_offset": 0, - "end_offset": 7, + "end_offset": 5, "type": "word", "position": 0, - "termFrequency": 100 + "termFrequency": 3 } ] } @@ -142,7 +142,7 @@ The response contains both the original token and the parsed version with the te ## Combining `delimited_token_filter` with scripts -You can write Painless scripts to calculate custom scores for the documents in the results. +You can write Painless scripts to calculate custom scores for the documents in the results. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). First, create an index and provide the following mappings and settings: diff --git a/_analyzers/token-filters/dictionary-decompounder.md b/_analyzers/token-filters/dictionary-decompounder.md new file mode 100644 index 00000000..ced6fd6f --- /dev/null +++ b/_analyzers/token-filters/dictionary-decompounder.md @@ -0,0 +1,101 @@ +--- +layout: default +title: Dictionary decompounder +parent: Token filters +nav_order: 110 +--- + +# Dictionary decompounder token filter + +The `dictionary_decompounder` token filter is used to split compound words into their constituent parts based on a predefined dictionary. This filter is particularly useful for languages like German, Dutch, or Finnish, in which compound words are common, so breaking them down can improve search relevance. The `dictionary_decompounder` token filter determines whether each token (word) can be split into smaller tokens based on a list of known words. If the token can be split into known words, the filter generates the subtokens for the token. + +## Parameters + +The `dictionary_decompounder` token filter has the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`word_list` | Required unless `word_list_path` is configured | Array of strings | The dictionary of words that the filter uses to split compound words. +`word_list_path` | Required unless `word_list` is configured | String | A file path to a text file containing the dictionary words. Accepts either an absolute path or a path relative to the `config` directory. The dictionary file must be UTF-8 encoded, and each word must be listed on a separate line. +`min_word_size` | Optional | Integer | The minimum length of the entire compound word that will be considered for splitting. If a compound word is shorter than this value, it is not split. Default is `5`. +`min_subword_size` | Optional | Integer | The minimum length for any subword. If a subword is shorter than this value, it is not included in the output. Default is `2`. +`max_subword_size` | Optional | Integer | The maximum length for any subword. If a subword is longer than this value, it is not included in the output. Default is `15`. +`only_longest_match` | Optional | Boolean | If set to `true`, only the longest matching subword will be returned. Default is `false`. + +## Example + +The following example request creates a new index named `decompound_example` and configures an analyzer with the `dictionary_decompounder` filter: + +```json +PUT /decompound_example +{ + "settings": { + "analysis": { + "filter": { + "my_dictionary_decompounder": { + "type": "dictionary_decompounder", + "word_list": ["slow", "green", "turtle"] + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "my_dictionary_decompounder"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /decompound_example/_analyze +{ + "analyzer": "my_analyzer", + "text": "slowgreenturtleswim" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slowgreenturtleswim", + "start_offset": 0, + "end_offset": 19, + "type": "", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 19, + "type": "", + "position": 0 + }, + { + "token": "green", + "start_offset": 0, + "end_offset": 19, + "type": "", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 0, + "end_offset": 19, + "type": "", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/token-filters/edge-ngram.md b/_analyzers/token-filters/edge-ngram.md new file mode 100644 index 00000000..be3eaf6f --- /dev/null +++ b/_analyzers/token-filters/edge-ngram.md @@ -0,0 +1,111 @@ +--- +layout: default +title: Edge n-gram +parent: Token filters +nav_order: 120 +--- +# Edge n-gram token filter +The `edge_ngram` token filter is very similar to the `ngram` token filter, where a particular string is split into substrings of different lengths. The `edge_ngram` token filter, however, generates n-grams (substrings) only from the beginning (edge) of a token. It's particularly useful in scenarios like autocomplete or prefix matching, where you want to match the beginning of words or phrases as the user types them. + +## Parameters + +The `edge_ngram` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`min_gram` | Optional | Integer | The minimum length of the n-grams that will be generated. Default is `1`. +`max_gram` | Optional | Integer | The maximum length of the n-grams that will be generated. Default is `1` for the `edge_ngram` filter and `2` for custom token filters. Avoid setting this parameter to a low value. If the value is set too low, only very short n-grams will be generated and the search term will not be found. For example, if `max_gram` is set to `3` and you index the word "banana", the longest generated token will be "ban". If the user searches for "banana", no matches will be returned. You can use the `truncate` token filter as a search analyzer to mitigate this risk. +`preserve_original` | Optional | Boolean | Includes the original token in the output. Default is `false` . + +## Example + +The following example request creates a new index named `edge_ngram_example` and configures an analyzer with the `edge_ngram` filter: + +```json +PUT /edge_ngram_example +{ + "settings": { + "analysis": { + "filter": { + "my_edge_ngram": { + "type": "edge_ngram", + "min_gram": 3, + "max_gram": 4 + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "my_edge_ngram"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /edge_ngram_example/_analyze +{ + "analyzer": "my_analyzer", + "text": "slow green turtle" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slo", + "start_offset": 0, + "end_offset": 4, + "type": "", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 4, + "type": "", + "position": 0 + }, + { + "token": "gre", + "start_offset": 5, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "gree", + "start_offset": 5, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "tur", + "start_offset": 11, + "end_offset": 17, + "type": "", + "position": 2 + }, + { + "token": "turt", + "start_offset": 11, + "end_offset": 17, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/elision.md b/_analyzers/token-filters/elision.md new file mode 100644 index 00000000..abc6dba6 --- /dev/null +++ b/_analyzers/token-filters/elision.md @@ -0,0 +1,124 @@ +--- +layout: default +title: Elision +parent: Token filters +nav_order: 130 +--- + +# Elision token filter + +The `elision` token filter is used to remove elided characters from words in certain languages. Elision typically occurs in languages such as French, in which words are often contracted and combined with the following word, typically by omitting a vowel and replacing it with an apostrophe. + +The `elision` token filter is already preconfigured in the following [language analyzers]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/): `catalan`, `french`, `irish`, and `italian`. +{: .note} + +## Parameters + +The custom `elision` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`articles` | Required if `articles_path` is not configured | Array of strings | Defines which articles or short words should be removed when they appear as part of an elision. +`articles_path` | Required if `articles` is not configured | String | Specifies the path to a custom list of articles that should be removed during the analysis process. +`articles_case` | Optional | Boolean | Specifies whether the filter is case sensitive when matching elisions. Default is `false`. + +## Example + +The default set of French elisions is `l'`, `m'`, `t'`, `qu'`, `n'`, `s'`, `j'`, `d'`, `c'`, `jusqu'`, `quoiqu'`, `lorsqu'`, and `puisqu'`. You can update this by configuring the `french_elision` token filter. The following example request creates a new index named `french_texts` and configures an analyzer with a `french_elision` filter: + +```json +PUT /french_texts +{ + "settings": { + "analysis": { + "filter": { + "french_elision": { + "type": "elision", + "articles": [ "l", "t", "m", "d", "n", "s", "j" ] + } + }, + "analyzer": { + "french_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "french_elision"] + } + } + } + }, + "mappings": { + "properties": { + "text": { + "type": "text", + "analyzer": "french_analyzer" + } + } + } +} + +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /french_texts/_analyze +{ + "analyzer": "french_analyzer", + "text": "L'étudiant aime l'école et le travail." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "étudiant", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "aime", + "start_offset": 11, + "end_offset": 15, + "type": "", + "position": 1 + }, + { + "token": "école", + "start_offset": 16, + "end_offset": 23, + "type": "", + "position": 2 + }, + { + "token": "et", + "start_offset": 24, + "end_offset": 26, + "type": "", + "position": 3 + }, + { + "token": "le", + "start_offset": 27, + "end_offset": 29, + "type": "", + "position": 4 + }, + { + "token": "travail", + "start_offset": 30, + "end_offset": 37, + "type": "", + "position": 5 + } + ] +} +``` diff --git a/_analyzers/token-filters/fingerprint.md b/_analyzers/token-filters/fingerprint.md new file mode 100644 index 00000000..75c66154 --- /dev/null +++ b/_analyzers/token-filters/fingerprint.md @@ -0,0 +1,86 @@ +--- +layout: default +title: Fingerprint +parent: Token filters +nav_order: 140 +--- + +# Fingerprint token filter + +The `fingerprint` token filter is used to standardize and deduplicate text. This is particularly useful when consistency in text processing is crucial. The `fingerprint` token filter achieves this by processing text using the following steps: + +1. **Lowercasing**: Converts all text to lowercase. +2. **Splitting**: Breaks the text into tokens. +3. **Sorting**: Arranges the tokens in alphabetical order. +4. **Removing duplicates**: Eliminates repeated tokens. +5. **Joining tokens**: Combines the tokens into a single string, typically joined by a space or another specified separator. + +## Parameters + +The `fingerprint` token filter can be configured with the following two parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`max_output_size` | Optional | Integer | Limits the length of the generated fingerprint string. If the concatenated string exceeds the `max_output_size`, the filter will not produce any output, resulting in an empty token. Default is `255`. +`separator` | Optional | String | Defines the character(s) used to join the tokens into a single string after they have been sorted and deduplicated. Default is space (`" "`). + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `fingerprint` token filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_fingerprint": { + "type": "fingerprint", + "max_output_size": 200, + "separator": "-" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_fingerprint" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "OpenSearch is a powerful search engine that scales easily" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "a-easily-engine-is-opensearch-powerful-scales-search-that", + "start_offset": 0, + "end_offset": 57, + "type": "fingerprint", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/token-filters/flatten-graph.md b/_analyzers/token-filters/flatten-graph.md new file mode 100644 index 00000000..8d51c574 --- /dev/null +++ b/_analyzers/token-filters/flatten-graph.md @@ -0,0 +1,109 @@ +--- +layout: default +title: Flatten graph +parent: Token filters +nav_order: 150 +--- + +# Flatten graph token filter + +The `flatten_graph` token filter is used to handle complex token relationships that occur when multiple tokens are generated at the same position in a graph structure. Some token filters, like `synonym_graph` and `word_delimiter_graph`, generate multi-position tokens---tokens that overlap or span multiple positions. These token graphs are useful for search queries but are not directly supported during indexing. The `flatten_graph` token filter resolves multi-position tokens into a linear sequence of tokens. Flattening the graph ensures compatibility with the indexing process. + +Token graph flattening is a lossy process. Whenever possible, avoid using the `flatten_graph` filter. Instead, apply graph token filters exclusively in search analyzers, removing the need for the `flatten_graph` filter. +{: .important} + +## Example + +The following example request creates a new index named `test_index` and configures an analyzer with a `flatten_graph` filter: + +```json +PUT /test_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_index_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "my_custom_filter", + "flatten_graph" + ] + } + }, + "filter": { + "my_custom_filter": { + "type": "word_delimiter_graph", + "catenate_all": true + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /test_index/_analyze +{ + "analyzer": "my_index_analyzer", + "text": "OpenSearch helped many employers" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0, + "positionLength": 2 + }, + { + "token": "Open", + "start_offset": 0, + "end_offset": 4, + "type": "", + "position": 0 + }, + { + "token": "Search", + "start_offset": 4, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "helped", + "start_offset": 11, + "end_offset": 17, + "type": "", + "position": 2 + }, + { + "token": "many", + "start_offset": 18, + "end_offset": 22, + "type": "", + "position": 3 + }, + { + "token": "employers", + "start_offset": 23, + "end_offset": 32, + "type": "", + "position": 4 + } + ] +} +``` diff --git a/_analyzers/token-filters/hunspell.md b/_analyzers/token-filters/hunspell.md new file mode 100644 index 00000000..e3d7c6e5 --- /dev/null +++ b/_analyzers/token-filters/hunspell.md @@ -0,0 +1,269 @@ +--- +layout: default +title: Hunspell +parent: Token filters +nav_order: 160 +--- + +# Hunspell token filter + +The `hunspell` token filter is used for stemming and morphological analysis of words in a specific language. This filter applies Hunspell dictionaries, which are widely used in spell checkers. It works by breaking down words into their root forms (stemming). + +If an algorithmic stemmer, such as the [`stemmer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stemmer/) or [`porter_stem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/porter-stem/) filter, is available for your language, try it before using `hunspell`. Algorithmic stemmers are faster, use less memory, and require no dictionary files, and they often produce comparable or better search results. For more information, see [Stemming]({{site.url}}{{site.baseurl}}/analyzers/stemming/). + +The Hunspell dictionary files are automatically loaded at startup from the `/hunspell/` directory. For example, the `en_GB` locale must have at least one `.aff` file and one or more `.dic` files in the `/hunspell/en_GB/` directory. + +Alternatively, you can load dictionaries from a custom directory by using the `ref_path` parameter to maintain multiple independent dictionary sets for the same locale. For more information, see [Custom dictionary loading with ref_path](#custom-dictionary-loading). + +You can also hot-reload Hunspell dictionaries at runtime without restarting the node. For more information, see [Hot-reloading Hunspell dictionaries](#hot-reloading-hunspell-dictionaries). + +You can download these files from [LibreOffice dictionaries](https://github.com/LibreOffice/dictionaries). + +## Parameters + +The `hunspell` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`language/lang/locale` | At least one of the three is required | String | Specifies the language for the Hunspell dictionary. Can contain only alphanumeric characters, hyphens, and underscores (for example, `en_US`, `de_DE`). +`ref_path` | Optional | String | Specifies a relative path used to load dictionaries from the `//hunspell//` directory instead of the default `/hunspell//` directory. When specified, the `locale` parameter is required. The `ref_path` value can contain alphanumeric characters, hyphens, underscores, and forward slashes (for nested paths such as `analyzers/my-dict`). The `locale` value can contain only alphanumeric characters, hyphens, and underscores. See [Custom dictionary loading with ref_path](#custom-dictionary-loading). **Note**: `ref_path` resolves directly under ``. In OpenSearch 3.6 and earlier, it resolved under `/analyzers/`. To preserve the previous layout, prefix your `ref_path` value with `analyzers/` (for example, `analyzers/my-dict`). +`dedup` | Optional | Boolean | Determines whether to remove multiple duplicate stemming terms for the same token. Default is `true`. +`dictionary` | Optional | Array of strings | Configures the dictionary files to be used for the Hunspell dictionary. Default is all files in the `/hunspell/` directory if `ref_path` is not specified or all files in the `//hunspell//` directory when `ref_path` is specified. See [Custom dictionary loading with ref_path](#custom-dictionary-loading). +`longest_only` | Optional | Boolean | Specifies whether only the longest stemmed version of the token should be returned. Default is `false`. +`updateable` | Optional | Boolean | When set to `true`, the filter operates in search-time analysis mode, allowing dictionaries to be hot-reloaded by using the [Refresh search analyzer]({{site.url}}{{site.baseurl}}/im-plugin/refresh-analyzer/) API without restarting the node. Default is `false`. **Introduced 3.7.** + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `hunspell` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_hunspell_filter": { + "type": "hunspell", + "lang": "en_GB", + "dedup": true, + "longest_only": true + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_hunspell_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Hunspell node settings + +The following table lists the static node settings that control how OpenSearch loads Hunspell dictionaries from the default `/hunspell/` directory. Configure them in `opensearch.yml`. + +Setting | Data type | Description +:--- | :--- | :--- +`indices.analysis.hunspell.dictionary.lazy` | Boolean | If `false`, OpenSearch loads every dictionary in the `hunspell` directory when the node starts and logs an error for any dictionary that fails to load. If `true`, OpenSearch loads each dictionary the first time a `hunspell` filter uses it, so dictionary errors appear only when an index or analysis request references the locale. Default is `false`. +`indices.analysis.hunspell.dictionary.ignore_case` | Boolean | If `true`, words are matched to dictionary entries regardless of case. For example, if the dictionary contains `Jump` with an `-ing` suffix rule, the text `jumping` is stemmed to `jump` only when `ignore_case` is `true`. This setting applies to all locales. Default is `false`. +`indices.analysis.hunspell.dictionary..ignore_case` | Boolean | Sets `ignore_case` for one locale, for example, `indices.analysis.hunspell.dictionary.en_US.ignore_case`. Overrides the global `ignore_case` setting. + +You can also set `ignore_case` for a single dictionary by adding a `settings.yml` file to the locale directory, for example, `/hunspell/en_US/settings.yml` containing `ignore_case: true`. If both the file and the locale-specific node setting specify `ignore_case`, the node setting takes precedence. + +## Custom dictionary loading + +When you specify a `ref_path` parameter, dictionaries are loaded from a custom directory instead of the default directory. This is useful when you need multiple independent dictionary sets for the same locale, for example, when different indexes require different custom dictionaries. + +The `ref_path` value is resolved relative to `` and can contain forward slashes for nested paths. In OpenSearch 3.6 and earlier, `ref_path` was resolved relative to `/analyzers/`. To preserve the previous directory layout when upgrading from 3.6 or earlier, prefix your existing `ref_path` value with `analyzers/`. +{: .note} + +Place dictionary files in the following directory structure: + +```xml +//hunspell// +├── .aff (exactly one .aff file required) +├── .dic (one or more .dic files) +└── _custom.dic +``` + +The following example loads a Hunspell dictionary from `/analyzers/my-dict/hunspell/en_US/`: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_custom_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/my-dict", + "locale": "en_US" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_custom_hunspell" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Multiple indexes can use different `ref_path` directories configured for the same locale. Each `ref_path` maintains its own independent dictionary cache: + +```json +PUT /index_medical +{ + "settings": { + "analysis": { + "filter": { + "medical_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/medical-dict", + "locale": "en_US" + } + } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /index_legal +{ + "settings": { + "analysis": { + "filter": { + "legal_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/legal-dict", + "locale": "en_US" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Hot-reloading Hunspell dictionaries +**Introduced 3.7** +{: .label .label-purple } + +You can update Hunspell dictionaries at runtime without restarting the node. To enable this, set the `updateable` parameter to `true` on the Hunspell token filter. This registers the filter in search-time analysis mode, so it can only be used at search time (for example, in a `search_analyzer`), not at index time. + +To hot-reload a Hunspell dictionary, follow these steps: + +1. Configure the Hunspell token filter with `updateable` set to `true`. The following example creates an index that uses a hot-reloadable Hunspell filter as a `search_analyzer`: + + ```json + PUT /my_index + { + "settings": { + "analysis": { + "filter": { + "my_reloadable_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/my-dict", + "locale": "en_US", + "updateable": true + } + }, + "analyzer": { + "my_search_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_reloadable_hunspell" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "standard", + "search_analyzer": "my_search_analyzer" + } + } + } + } + ``` + {% include copy-curl.html %} + +1. Replace the `.aff` and `.dic` files on disk on every node that holds a shard for the index. + +1. Call the [Refresh Search Analyzer API]({{site.url}}{{site.baseurl}}/im-plugin/refresh-analyzer/). When `reload_cached_resources` is `false` (the default), the API rebuilds analyzer factories but reuses the previously cached Hunspell dictionary. Specify `reload_cached_resources=true` to force the dictionary to be reloaded from disk: + + ```json + POST /_plugins/_refresh_search_analyzers/my_index?reload_cached_resources=true + ``` + {% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "the turtle moves slowly" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "the", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 4, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "move", + "start_offset": 11, + "end_offset": 16, + "type": "", + "position": 2 + }, + { + "token": "slow", + "start_offset": 17, + "end_offset": 23, + "type": "", + "position": 3 + } + ] +} +``` diff --git a/_analyzers/token-filters/hyphenation-decompounder.md b/_analyzers/token-filters/hyphenation-decompounder.md new file mode 100644 index 00000000..b6313f6f --- /dev/null +++ b/_analyzers/token-filters/hyphenation-decompounder.md @@ -0,0 +1,102 @@ +--- +layout: default +title: Hyphenation decompounder +parent: Token filters +nav_order: 170 +--- + +# Hyphenation decompounder token filter + +The `hyphenation_decompounder` token filter is used to break down compound words into their constituent parts. This filter is particularly useful for languages like German, Dutch, and Swedish, in which compound words are common. The filter uses hyphenation patterns (typically defined in .xml files) to identify the possible locations within a compound word where it can be split into components. These components are then checked against a provided dictionary. If there is a match, those components are treated as valid tokens. For more information about hyphenation pattern files, see [Apache Formatting Objects Processor (FOP) XML Hyphenation Patterns](https://offo.sourceforge.net/#FOP+XML+Hyphenation+Patterns). + +## Parameters + +The `hyphenation_decompounder` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`hyphenation_patterns_path` | Required | String | The path (relative to the `config` directory or absolute) to the hyphenation patterns file, which contains the language-specific rules for word splitting. The file is typically in XML format. Sample files can be downloaded from the [OFFO SourceForge project](https://sourceforge.net/projects/offo/). +`word_list` | Required if `word_list_path` is not set | Array of strings | A list of words used to validate the components generated by the hyphenation patterns. +`word_list_path` | Required if `word_list` is not set | String | The path (relative to the `config` directory or absolute) to a list of subwords. +`max_subword_size` | Optional | Integer | The maximum subword length. If the generated subword exceeds this length, it will not be added to the generated tokens. Default is `15`. +`min_subword_size` | Optional | Integer | The minimum subword length. If the generated subword is shorter than the specified length, it will not be added to the generated tokens. Default is `2`. +`min_word_size` | Optional | Integer | The minimum word character length. Word tokens shorter than this length are excluded from decomposition into subwords. Default is `5`. +`only_longest_match` | Optional | Boolean | Only includes the longest subword in the generated tokens. Default is `false`. + +## Example + +The following example request creates a new index named `test_index` and configures an analyzer with a `hyphenation_decompounder` filter: + +```json +PUT /test_index +{ + "settings": { + "analysis": { + "filter": { + "my_hyphenation_decompounder": { + "type": "hyphenation_decompounder", + "hyphenation_patterns_path": "analysis/hyphenation_patterns.xml", + "word_list": ["notebook", "note", "book"], + "min_subword_size": 3, + "min_word_size": 5, + "only_longest_match": false + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_hyphenation_decompounder" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /test_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "notebook" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "notebook", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + }, + { + "token": "note", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + }, + { + "token": "book", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/token-filters/icu-folding.md b/_analyzers/token-filters/icu-folding.md new file mode 100644 index 00000000..be44804b --- /dev/null +++ b/_analyzers/token-filters/icu-folding.md @@ -0,0 +1,182 @@ +--- +layout: default +title: ICU folding +parent: Token filters +nav_order: 172 +--- + +# ICU folding token filter + +The `icu_folding` token filter applies Unicode normalization and case folding to tokens, converting them to a form suitable for case-insensitive matching. This filter provides more comprehensive character folding than the ASCII folding filter, handling characters from all Unicode scripts. + +The filter implements case folding as defined in [Unicode Technical Report #30](https://www.unicode.org/reports/tr30/), which includes: +- Converting uppercase letters to lowercase +- Removing diacritical marks (accents) +- Converting ligatures to their component letters +- Normalizing character width (for example, full-width to half-width) +- Converting certain punctuation and symbols to ASCII equivalents + +## Installation + +The `icu_folding` token filter requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/). + +## Parameters + +The following table lists the parameters for the `icu_folding` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`unicode_set_filter` | String | A [UnicodeSet](https://unicode-org.github.io/icu/userguide/strings/unicodeset.html) expression specifying which characters to fold. Characters outside this set are passed through unchanged. Optional. If not specified, all characters are folded. + +## Example: Basic ICU folding + +The following example demonstrates the default `icu_folding` behavior: + +```json +PUT /icu-folding-index +{ + "settings": { + "analysis": { + "analyzer": { + "icu_folding_analyzer": { + "tokenizer": "icu_tokenizer", + "filter": ["icu_folding"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with text containing diacritics, ligatures, and mixed case: + +```json +POST /icu-folding-index/_analyze +{ + "analyzer": "icu_folding_analyzer", + "text": "Café RÉSUMÉ Æsop" +} +``` +{% include copy-curl.html %} + +The response shows normalization and folding: + +```json +{ + "tokens": [ + { + "token": "cafe", + "start_offset": 0, + "end_offset": 4, + "type": "", + "position": 0 + }, + { + "token": "resume", + "start_offset": 5, + "end_offset": 11, + "type": "", + "position": 1 + }, + { + "token": "aesop", + "start_offset": 12, + "end_offset": 16, + "type": "", + "position": 2 + } + ] +} +``` + +## Normalization included + +The `icu_folding` filter already performs Unicode normalization, so you don't need to add a separate normalization character filter or token filter when using `icu_folding`. +{: .note} + +## Example: Preserving specific characters + +You can preserve specific characters from folding using the `unicode_set_filter` parameter. The following example preserves German umlauts and the Eszett character: + +```json +PUT /icu-folding-german +{ + "settings": { + "analysis": { + "filter": { + "german_folding": { + "type": "icu_folding", + "unicode_set_filter": "[^äöüÄÖÜß]" + } + }, + "analyzer": { + "german_analyzer": { + "tokenizer": "icu_tokenizer", + "filter": ["german_folding", "lowercase"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +The `unicode_set_filter` value `[^äöüÄÖÜß]` means "fold all characters except these German characters." The `lowercase` filter is added afterward to handle the preserved uppercase characters. + +Test the analyzer: + +```json +POST /icu-folding-german/_analyze +{ + "analyzer": "german_analyzer", + "text": "MÜNCHEN Café Größe" +} +``` +{% include copy-curl.html %} + +The response preserves German characters while folding others: + +```json +{ + "tokens": [ + { + "token": "münchen", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "cafe", + "start_offset": 8, + "end_offset": 12, + "type": "", + "position": 1 + }, + { + "token": "größe", + "start_offset": 13, + "end_offset": 18, + "type": "", + "position": 2 + } + ] +} +``` + +## Comparison with ASCII folding + +While the `asciifolding` token filter converts non-ASCII characters to ASCII equivalents, `icu_folding` provides more sophisticated normalization: + +- **Broader character support**: Handles all Unicode scripts, not only Latin-based characters +- **Language-aware**: Applies normalization rules appropriate for different writing systems +- **Width normalization**: Converts full-width characters to half-width (important for CJK text) +- **Ligature handling**: Properly decomposes ligatures across all scripts + +## Related documentation + +- [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/) +- [ICU tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/icu-tokenizer/) +- [ICU normalization character filter]({{site.url}}{{site.baseurl}}/analyzers/character-filters/icu-normalization/) +- [ASCII folding token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/asciifolding/) diff --git a/_analyzers/token-filters/icu-transform.md b/_analyzers/token-filters/icu-transform.md new file mode 100644 index 00000000..1801f5c0 --- /dev/null +++ b/_analyzers/token-filters/icu-transform.md @@ -0,0 +1,247 @@ +--- +layout: default +title: ICU transform +parent: Token filters +nav_order: 175 +--- + +# ICU transform token filter + +The `icu_transform` token filter applies ICU text transformations to tokens, enabling operations such as transliteration, case mapping, normalization, and bidirectional text handling. This filter uses transformation rules defined by the [ICU Transform](https://unicode-org.github.io/icu/userguide/transforms/general/) framework. + +Common use cases include: +- **Transliteration**: Converting text from one script to another (for example, Cyrillic to Latin) +- **Script conversion**: Transforming between different writing systems +- **Accent removal**: Separating base characters from diacritics +- **Custom transformations**: Applying user-defined transformation rules + +## Installation + +The `icu_transform` token filter requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/). + +## Parameters + +The following table lists the parameters for the `icu_transform` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`id` | String | The ICU transform ID specifying which transformation to apply. Can be a single transform ID or a compound ID with multiple transforms separated by semicolons. Default is `Null` (no transformation). +`dir` | String | The text direction for the transformation. Valid values are `forward` (default, left-to-right) and `reverse` (right-to-left). Default is `forward`. + +## Transform IDs + +You can specify transformations using standard ICU transform IDs. Common transforms include: + +- `Any-Latin`: Transliterates text from any script to Latin characters +- `Latin-Cyrillic`: Converts Latin text to Cyrillic +- `NFD; [:Nonspacing Mark:] Remove; NFC`: Decomposes characters, removes diacritics, then recomposes +- `Lower`: Converts text to lowercase +- `Upper`: Converts text to uppercase +- `Hiragana-Katakana`: Converts Hiragana to Katakana + +You can chain multiple transforms by separating them with semicolons. + +## Example: Transliterating to Latin + +The following example demonstrates transliteration of multiple scripts to Latin characters: + +```json +PUT /icu-transform-latin +{ + "settings": { + "analysis": { + "filter": { + "latin_transform": { + "type": "icu_transform", + "id": "Any-Latin" + } + }, + "analyzer": { + "latin_analyzer": { + "tokenizer": "keyword", + "filter": ["latin_transform"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with text in different scripts: + +```json +POST /icu-transform-latin/_analyze +{ + "analyzer": "latin_analyzer", + "text": "Москва" +} +``` +{% include copy-curl.html %} + +The Cyrillic text is transliterated to Latin: + +```json +{ + "tokens": [ + { + "token": "Moskva", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0 + } + ] +} +``` + +Test with Japanese text: + +```json +POST /icu-transform-latin/_analyze +{ + "analyzer": "latin_analyzer", + "text": "東京" +} +``` +{% include copy-curl.html %} + +The Japanese characters are transliterated: + +```json +{ + "tokens": [ + { + "token": "dōng jīng", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + } + ] +} +``` + +## Example: Removing accents + +The following example removes diacritical marks from text: + +```json +PUT /icu-transform-no-accents +{ + "settings": { + "analysis": { + "filter": { + "remove_accents": { + "type": "icu_transform", + "id": "NFD; [:Nonspacing Mark:] Remove; NFC" + } + }, + "analyzer": { + "accent_removal_analyzer": { + "tokenizer": "keyword", + "filter": ["remove_accents"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer: + +```json +POST /icu-transform-no-accents/_analyze +{ + "analyzer": "accent_removal_analyzer", + "text": "Ênrique Iglesias" +} +``` +{% include copy-curl.html %} + +The accents are removed: + +```json +{ + "tokens": [ + { + "token": "Enrique Iglesias", + "start_offset": 0, + "end_offset": 16, + "type": "word", + "position": 0 + } + ] +} +``` + +## Example: Script-to-script conversion + +The following example converts Latin text to Cyrillic: + +```json +PUT /icu-transform-cyrillic +{ + "settings": { + "analysis": { + "filter": { + "to_cyrillic": { + "type": "icu_transform", + "id": "Latin-Cyrillic" + } + }, + "analyzer": { + "cyrillic_analyzer": { + "tokenizer": "keyword", + "filter": ["to_cyrillic"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test with Latin text: + +```json +POST /icu-transform-cyrillic/_analyze +{ + "analyzer": "cyrillic_analyzer", + "text": "Sankt Peterburg" +} +``` +{% include copy-curl.html %} + +The text is converted to Cyrillic script: + +```json +{ + "tokens": [ + { + "token": "Санкт Петербург", + "start_offset": 0, + "end_offset": 15, + "type": "word", + "position": 0 + } + ] +} +``` + +## Compound transformations + +You can chain multiple transformations by separating transform IDs with semicolons. The transformations are applied in order from left to right. + +For example, the compound ID `"Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC"` performs the following steps: +1. Transliterates to Latin +2. Applies canonical decomposition (NFD) +3. Removes non-spacing marks (accents) +4. Applies canonical composition (NFC) + +## Related documentation + +- [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/) +- [ICU tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/icu-tokenizer/) +- [ICU folding token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/icu-folding/) diff --git a/_analyzers/token-filters/index.md b/_analyzers/token-filters/index.md index ba09a7fa..a7857d6b 100644 --- a/_analyzers/token-filters/index.md +++ b/_analyzers/token-filters/index.md @@ -4,6 +4,8 @@ title: Token filters nav_order: 70 has_children: true has_toc: false +redirect_from: + - /analyzers/token-filters/ --- # Token filters @@ -13,52 +15,59 @@ Token filters receive the stream of tokens from the tokenizer and add, remove, o The following table lists all token filters that OpenSearch supports. Token filter | Underlying Lucene token filter| Description -`apostrophe` | [ApostropheFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/tr/ApostropheFilter.html) | In each token that contains an apostrophe, the `apostrophe` token filter removes the apostrophe itself and all characters following the apostrophe. -`asciifolding` | [ASCIIFoldingFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html) | Converts alphabetic, numeric, and symbolic characters. -`cjk_bigram` | [CJKBigramFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html) | Forms bigrams of Chinese, Japanese, and Korean (CJK) tokens. -`cjk_width` | [CJKWidthFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html) | Normalizes Chinese, Japanese, and Korean (CJK) tokens according to the following rules:
- Folds full-width ASCII character variants into the equivalent basic Latin characters.
- Folds half-width Katakana character variants into the equivalent Kana characters. -`classic` | [ClassicFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/standard/ClassicFilter.html) | Performs optional post-processing on the tokens generated by the classic tokenizer. Removes possessives (`'s`) and removes `.` from acronyms. -`common_grams` | [CommonGramsFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html) | Generates bigrams for a list of frequently occurring terms. The output contains both single terms and bigrams. -`conditional` | [ConditionalTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/ConditionalTokenFilter.html) | Applies an ordered list of token filters to tokens that match the conditions provided in a script. -`decimal_digit` | [DecimalDigitFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/DecimalDigitFilter.html) | Converts all digits in the Unicode decimal number general category to basic Latin digits (0--9). -`delimited_payload` | [DelimitedPayloadTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/payloads/DelimitedPayloadTokenFilter.html) | Separates a token stream into tokens with corresponding payloads, based on a provided delimiter. A token consists of all characters before the delimiter, and a payload consists of all characters after the delimiter. For example, if the delimiter is `|`, then for the string `foo|bar`, `foo` is the token and `bar` is the payload. -[`delimited_term_freq`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/delimited-term-frequency/) | [DelimitedTermFrequencyTokenFilter](https://lucene.apache.org/core/9_7_0/analysis/common/org/apache/lucene/analysis/miscellaneous/DelimitedTermFrequencyTokenFilter.html) | Separates a token stream into tokens with corresponding term frequencies, based on a provided delimiter. A token consists of all characters before the delimiter, and a term frequency is the integer after the delimiter. For example, if the delimiter is `|`, then for the string `foo|5`, `foo` is the token and `5` is the term frequency. -`dictionary_decompounder` | [DictionaryCompoundWordTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/compound/DictionaryCompoundWordTokenFilter.html) | Decomposes compound words found in many Germanic languages. -`edge_ngram` | [EdgeNGramTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html) | Tokenizes the given token into edge n-grams (n-grams that start at the beginning of the token) of lengths between `min_gram` and `max_gram`. Optionally, keeps the original token. -`elision` | [ElisionFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/util/ElisionFilter.html) | Removes the specified [elisions](https://en.wikipedia.org/wiki/Elision) from the beginning of tokens. For example, changes `l'avion` (the plane) to `avion` (plane). -`fingerprint` | [FingerprintFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/FingerprintFilter.html) | Sorts and deduplicates the token list and concatenates tokens into a single token. -`flatten_graph` | [FlattenGraphFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/FlattenGraphFilter.html) | Flattens a token graph produced by a graph token filter, such as `synonym_graph` or `word_delimiter_graph`, making the graph suitable for indexing. -`hunspell` | [HunspellStemFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/hunspell/HunspellStemFilter.html) | Uses [Hunspell](https://en.wikipedia.org/wiki/Hunspell) rules to stem tokens. Because Hunspell supports a word having multiple stems, this filter can emit multiple tokens for each consumed token. Requires you to configure one or more language-specific Hunspell dictionaries. -`hyphenation_decompounder` | [HyphenationCompoundWordTokenFilter](https://lucene.apache.org/core/9_8_0/analysis/common/org/apache/lucene/analysis/compound/HyphenationCompoundWordTokenFilter.html) | Uses XML-based hyphenation patterns to find potential subwords in compound words and checks the subwords against the specified word list. The token output contains only the subwords found in the word list. -`keep_types` | [TypeTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/TypeTokenFilter.html) | Keeps or removes tokens of a specific type. -`keep_word` | [KeepWordFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeepWordFilter.html) | Checks the tokens against the specified word list and keeps only those that are in the list. -`keyword_marker` | [KeywordMarkerFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordMarkerFilter.html) | Marks specified tokens as keywords, preventing them from being stemmed. -`keyword_repeat` | [KeywordRepeatFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html) | Emits each incoming token twice: once as a keyword and once as a non-keyword. -`kstem` | [KStemFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/en/KStemFilter.html) | Provides kstem-based stemming for the English language. Combines algorithmic stemming with a built-in dictionary. -`length` | [LengthFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html) | Removes tokens whose lengths are shorter or longer than the length range specified by `min` and `max`. -`limit` | [LimitTokenCountFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html) | Limits the number of output tokens. A common use case is to limit the size of document field values based on token count. -`lowercase` | [LowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html) | Converts tokens to lowercase. The default [LowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html) is for the English language. You can set the `language` parameter to `greek` (uses [GreekLowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/el/GreekLowerCaseFilter.html)), `irish` (uses [IrishLowerCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ga/IrishLowerCaseFilter.html)), or `turkish` (uses [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) | Uses the [MinHash technique](https://en.wikipedia.org/wiki/MinHash) to estimate document similarity. Performs the following operations on a token stream sequentially:
1. Hashes each token in the stream.
2. Assigns the hashes to buckets, keeping only the smallest hashes of each bucket.
3. Outputs the smallest hash from each bucket as a token stream. -`multiplexer` | N/A | Emits multiple tokens at the same position. Runs each token through each of the specified filter lists separately and outputs the results as separate tokens. -`ngram` | [NGramTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html) | Tokenizes the given token into n-grams of lengths between `min_gram` and `max_gram`. -Normalization | `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) | Normalizes the characters of one of the listed languages. -`pattern_capture` | N/A | Generates a token for every capture group in the provided regular expression. Uses [Java regular expression syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). -`pattern_replace` | N/A | Matches a pattern in the provided regular expression and replaces matching substrings. Uses [Java regular expression syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). -`phonetic` | N/A | Uses a phonetic encoder to emit a metaphone token for each token in the token stream. Requires installing the `analysis-phonetic` plugin. -`porter_stem` | [PorterStemFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/en/PorterStemFilter.html) | Uses the [Porter stemming algorithm](https://tartarus.org/martin/PorterStemmer/) to perform algorithmic stemming for the English language. -`predicate_token_filter` | N/A | Removes tokens that don’t match the specified predicate script. Supports inline Painless scripts only. -`remove_duplicates` | [RemoveDuplicatesTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html) | Removes duplicate tokens that are in the same position. -`reverse` | [ReverseStringFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html) | Reverses the string corresponding to each token in the token stream. For example, the token `dog` becomes `god`. -`shingle` | [ShingleFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/shingle/ShingleFilter.html) | Generates shingles of lengths between `min_shingle_size` and `max_shingle_size` for tokens in the token stream. Shingles are similar to n-grams but apply to words instead of letters. For example, two-word shingles added to the list of unigrams [`contribute`, `to`, `opensearch`] are [`contribute to`, `to opensearch`]. -`snowball` | N/A | Stems words using a [Snowball-generated stemmer](https://snowballstem.org/). You can use the `snowball` token filter with the following languages in the `language` field: `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 | Provides algorithmic stemming for the following languages in the `language` field: `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 | Overrides stemming algorithms by applying a custom mapping so that the provided terms are not stemmed. -`stop` | [StopFilter](https://lucene.apache.org/core/8_7_0/core/org/apache/lucene/analysis/StopFilter.html) | Removes stop words from a token stream. -`synonym` | N/A | Supplies a synonym list for the analysis process. The synonym list is provided using a configuration file. -`synonym_graph` | N/A | Supplies a synonym list, including multiword synonyms, for the analysis process. -`trim` | [TrimFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html) | Trims leading and trailing white space from each token in a stream. -`truncate` | [TruncateTokenFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html) | Truncates tokens whose length exceeds the specified character limit. -`unique` | N/A | Ensures each token is unique by removing duplicate tokens from a stream. -`uppercase` | [UpperCaseFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html) | Converts tokens to uppercase. -`word_delimiter` | [WordDelimiterFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.html) | Splits tokens at non-alphanumeric characters and performs normalization based on the specified rules. -`word_delimiter_graph` | [WordDelimiterGraphFilter](https://lucene.apache.org/core/8_7_0/analyzers-common/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.html) | Splits tokens at non-alphanumeric characters and performs normalization based on the specified rules. Assigns multi-position tokens a `positionLength` attribute. +[`apostrophe`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/apostrophe/) | [ApostropheFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/tr/ApostropheFilter.html) | In each token containing an apostrophe, the `apostrophe` token filter removes the apostrophe itself and all characters following it. +[`asciifolding`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/asciifolding/) | [ASCIIFoldingFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/ASCIIFoldingFilter.html) | Converts alphabetic, numeric, and symbolic characters. +[`cjk_bigram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/cjk-bigram/) | [CJKBigramFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/cjk/CJKBigramFilter.html) | Forms bigrams of Chinese, Japanese, and Korean (CJK) tokens. +[`cjk_width`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/cjk-width/) | [CJKWidthFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/cjk/CJKWidthFilter.html) | Normalizes Chinese, Japanese, and Korean (CJK) tokens according to the following rules:
- Folds full-width ASCII character variants into their equivalent basic Latin characters.
- Folds half-width katakana character variants into their equivalent kana characters. +[`classic`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/classic/) | [ClassicFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/classic/ClassicFilter.html) | Performs optional post-processing on the tokens generated by the classic tokenizer. Removes possessives (`'s`) and removes `.` from acronyms. +[`common_grams`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/common_gram/) | [CommonGramsFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/commongrams/CommonGramsFilter.html) | Generates bigrams for a list of frequently occurring terms. The output contains both single terms and bigrams. +[`condition`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/condition/) | [ConditionalTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/ConditionalTokenFilter.html) | Applies an ordered list of token filters to tokens that match the conditions provided in a script. +[`decimal_digit`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/decimal-digit/) | [DecimalDigitFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/DecimalDigitFilter.html) | Converts all digits in the Unicode decimal number general category to basic Latin digits (0--9). +[`delimited_payload`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/delimited-payload/) | [DelimitedPayloadTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/payloads/DelimitedPayloadTokenFilter.html) | Separates a token stream into tokens with corresponding payloads, based on a provided delimiter. A token consists of all characters preceding the delimiter, and a payload consists of all characters following the delimiter. For example, if the delimiter is `|`, then for the string `foo|bar`, `foo` is the token and `bar` is the payload. +[`delimited_term_freq`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/delimited-term-frequency/) | [DelimitedTermFrequencyTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/DelimitedTermFrequencyTokenFilter.html) | Separates a token stream into tokens with corresponding term frequencies, based on a provided delimiter. A token consists of all characters before the delimiter, and a term frequency is the integer after the delimiter. For example, if the delimiter is `|`, then for the string `foo|5`, `foo` is the token and `5` is the term frequency. +[`dictionary_decompounder`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/dictionary-decompounder/) | [DictionaryCompoundWordTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/compound/DictionaryCompoundWordTokenFilter.html) | Decomposes compound words found in many Germanic languages. +[`edge_ngram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/edge-ngram/) | [EdgeNGramTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilter.html) | Tokenizes the given token into edge n-grams (n-grams that start at the beginning of the token) of lengths between `min_gram` and `max_gram`. Optionally, keeps the original token. +[`elision`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/elision/) | [ElisionFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/util/ElisionFilter.html) | Removes the specified [elisions](https://en.wikipedia.org/wiki/Elision) from the beginning of tokens. For example, changes `l'avion` (the plane) to `avion` (plane). +[`fingerprint`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/fingerprint/) | [FingerprintFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/FingerprintFilter.html) | Sorts and deduplicates the token list and concatenates tokens into a single token. +[`flatten_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/flatten-graph/) | [FlattenGraphFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/FlattenGraphFilter.html) | Flattens a token graph produced by a graph token filter, such as `synonym_graph` or `word_delimiter_graph`, making the graph suitable for indexing. +[`hunspell`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/hunspell/) | [HunspellStemFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/hunspell/HunspellStemFilter.html) | Uses [Hunspell](https://en.wikipedia.org/wiki/Hunspell) rules to stem tokens. Because Hunspell allows a word to have multiple stems, this filter can emit multiple tokens for each consumed token. Requires the configuration of one or more language-specific Hunspell dictionaries. +[`hyphenation_decompounder`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/hyphenation-decompounder/) | [HyphenationCompoundWordTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/compound/HyphenationCompoundWordTokenFilter.html) | Uses XML-based hyphenation patterns to find potential subwords in compound words and checks the subwords against the specified word list. The token output contains only the subwords found in the word list. +[`ja_stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ja-stop/) | [StopFilter](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/analysis/StopFilter.html) when `remove_trailing` is `true`, or [SuggestStopFilter](https://lucene.apache.org/core/{{site.lucene_version}}/suggest/org/apache/lucene/search/suggest/analyzing/SuggestStopFilter.html) when `remove_trailing` is `false` | Removes Japanese stop words from the token stream. Supports the built-in `_japanese_` stop set, a custom word list, or a file. Includes a `remove_trailing` parameter for suggest and completion use cases. Requires the `analysis-kuromoji` plugin. +[`keep_types`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/keep-types/) | [TypeTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/TypeTokenFilter.html) | Keeps or removes tokens of a specific type. +[`keep_words`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/keep-words/) | [KeepWordFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/KeepWordFilter.html) | Checks the tokens against the specified word list and keeps only those that are in the list. +[`keyword_marker`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/keyword-marker/) | [KeywordMarkerFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/KeywordMarkerFilter.html) | Marks specified tokens as keywords, preventing them from being stemmed. +[`keyword_repeat`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/keyword-repeat/) | [KeywordRepeatFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.html) | Emits each incoming token twice: once as a keyword and once as a non-keyword. +[`kstem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kstem/) | [KStemFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/en/KStemFilter.html) | Provides KStem-based stemming for the English language. Combines algorithmic stemming with a built-in dictionary. +[`kuromoji_baseform`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-baseform/) | [JapaneseBaseFormFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/kuromoji/org/apache/lucene/analysis/ja/JapaneseBaseFormFilter.html) | Replaces inflected Japanese tokens with their dictionary base form. Requires the `analysis-kuromoji` plugin. +[`kuromoji_completion`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-completion/) | [JapaneseCompletionFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/kuromoji/org/apache/lucene/analysis/ja/JapaneseCompletionFilter.html) | Adds Japanese romanized terms to a token stream (in addition to the original tokens). Usually used to support autocomplete of Japanese search terms. Note that the filter has a `mode` parameter that should be set to `index` when used in an index analyzer and `query` when used in a search analyzer. Requires the `analysis-kuromoji` plugin. For information about installing the plugin, see [Additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#additional-plugins). +[`kuromoji_number`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-number/) | [JapaneseNumberFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/kuromoji/org/apache/lucene/analysis/ja/JapaneseNumberFilter.html) | Normalizes Japanese numeral expressions (kanji numerals, full-width digits) to standard Arabic numerals. Requires the `analysis-kuromoji` plugin. +[`kuromoji_part_of_speech`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/) | [JapanesePartOfSpeechStopFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/kuromoji/org/apache/lucene/analysis/ja/JapanesePartOfSpeechStopFilter.html) | Removes tokens whose IPAdic part-of-speech tag matches a configured stop-tag list. Defaults to removing particles, auxiliary verbs, punctuation, and other grammatical tokens. Requires the `analysis-kuromoji` plugin. +[`kuromoji_readingform`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-readingform/) | [JapaneseReadingFormFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/kuromoji/org/apache/lucene/analysis/ja/JapaneseReadingFormFilter.html) | Replaces each token with its katakana or romaji reading form, depending on the `use_romaji` parameter. Requires the `analysis-kuromoji` plugin. +[`kuromoji_stemmer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-stemmer/) | [JapaneseKatakanaStemFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/kuromoji/org/apache/lucene/analysis/ja/JapaneseKatakanaStemFilter.html) | Removes trailing long vowel marks (ー) from katakana words that meet a minimum length specified by the `minimum_length` parameter (default is `4`). Requires the `analysis-kuromoji` plugin. +[`length`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/length/) | [LengthFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/LengthFilter.html) | Removes tokens that are shorter or longer than the length range specified by `min` and `max`. +[`limit`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/limit/) | [LimitTokenCountFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilter.html) | Limits the number of output tokens. For example, document field value sizes can be limited based on the token count. +[`lowercase`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/lowercase/) | [LowerCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/LowerCaseFilter.html) | Converts tokens to lowercase. The default [LowerCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/LowerCaseFilter.html) processes the English language. To process other languages, set the `language` parameter to `greek` (uses [GreekLowerCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/el/GreekLowerCaseFilter.html)), `irish` (uses [IrishLowerCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ga/IrishLowerCaseFilter.html)), or `turkish` (uses [TurkishLowerCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/tr/TurkishLowerCaseFilter.html)). +[`min_hash`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/min-hash/) | [MinHashFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/minhash/MinHashFilter.html) | Uses the [MinHash technique](https://en.wikipedia.org/wiki/MinHash) to estimate document similarity. Performs the following operations on a token stream sequentially:
1. Hashes each token in the stream.
2. Assigns the hashes to buckets, keeping only the smallest hashes of each bucket.
3. Outputs the smallest hash from each bucket as a token stream. +[`multiplexer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/multiplexer/) | N/A | Emits multiple tokens at the same position. Runs each token through each of the specified filter lists separately and outputs the results as separate tokens. +[`ngram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ngram/) | [NGramTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ngram/NGramTokenFilter.html) | Tokenizes the given token into n-grams of lengths between `min_gram` and `max_gram`. +[Normalization]({{site.url}}{{site.baseurl}}/analyzers/token-filters/normalization/) | `arabic_normalization`: [ArabicNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html)
`german_normalization`: [GermanNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html)
`hindi_normalization`: [HindiNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html)
`indic_normalization`: [IndicNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html)
`sorani_normalization`: [SoraniNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html)
`persian_normalization`: [PersianNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html)
`scandinavian_normalization` : [ScandinavianNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html)
`scandinavian_folding`: [ScandinavianFoldingFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html)
`serbian_normalization`: [SerbianNormalizationFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/sr/SerbianNormalizationFilter.html) | Normalizes the characters of one of the listed languages. +[`pattern_capture`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/pattern-capture/) | N/A | Generates a token for every capture group in the provided regular expression. Uses [Java regular expression syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). +[`pattern_replace`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/pattern-replace/) | N/A | Matches a pattern in the provided regular expression and replaces matching substrings. Uses [Java regular expression syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). +[`phonetic`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/phonetic/) | N/A | Uses a phonetic encoder to emit a metaphone token for each token in the token stream. Requires installing the `analysis-phonetic` plugin. +[`porter_stem`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/porter-stem/) | [PorterStemFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/en/PorterStemFilter.html) | Uses the [Porter stemming algorithm](https://tartarus.org/martin/PorterStemmer/) to perform algorithmic stemming for the English language. +[`predicate_token_filter`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/predicate-token-filter/) | N/A | Removes tokens that do not match the specified predicate script. Supports only inline Painless scripts. +[`remove_duplicates`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/remove-duplicates/) | [RemoveDuplicatesTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/RemoveDuplicatesTokenFilter.html) | Removes duplicate tokens that are in the same position. +[`reverse`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/reverse/) | [ReverseStringFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html) | Reverses the string corresponding to each token in the token stream. For example, the token `dog` becomes `god`. +[`shingle`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/shingle/) | [ShingleFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/shingle/ShingleFilter.html) | Generates shingles of lengths between `min_shingle_size` and `max_shingle_size` for tokens in the token stream. Shingles are similar to n-grams but are generated using words instead of letters. For example, two-word shingles added to the list of unigrams [`contribute`, `to`, `opensearch`] are [`contribute to`, `to opensearch`]. +[`snowball`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/snowball/) | N/A | Stems words using a [Snowball-generated stemmer](https://snowballstem.org/). The `snowball` token filter supports using the following languages in the `language` field: `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`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stemmer/) | N/A | Provides algorithmic stemming for the following languages used in the `language` field: `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`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stemmer-override/) | N/A | Overrides stemming algorithms by applying a custom mapping so that the provided terms are not stemmed. +[`stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/) | [StopFilter](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/analysis/StopFilter.html) | Removes stop words from a token stream. +[`synonym`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym/) | N/A | Supplies a synonym list for the analysis process. The synonym list is provided using a configuration file. +[`synonym_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym-graph/) | N/A | Supplies a synonym list, including multiword synonyms, for the analysis process. +[`trim`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/trim/) | [TrimFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/TrimFilter.html) | Trims leading and trailing white space characters from each token in a stream. +[`truncate`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/truncate/) | [TruncateTokenFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/TruncateTokenFilter.html) | Truncates tokens with lengths exceeding the specified character limit. +[`unique`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/unique/) | N/A | Ensures that each token is unique by removing duplicate tokens from a stream. +[`uppercase`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/uppercase/) | [UpperCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/LowerCaseFilter.html) | Converts tokens to uppercase. +[`word_delimiter`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter/) | [WordDelimiterFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/WordDelimiterFilter.html) | Splits tokens on non-alphanumeric characters and performs normalization based on the specified rules. +[`word_delimiter_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter-graph/) | [WordDelimiterGraphFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/WordDelimiterGraphFilter.html) | Splits tokens on non-alphanumeric characters and performs normalization based on the specified rules. Assigns a `positionLength` attribute to multi-position tokens. diff --git a/_analyzers/token-filters/ja-stop.md b/_analyzers/token-filters/ja-stop.md new file mode 100644 index 00000000..f4d426fb --- /dev/null +++ b/_analyzers/token-filters/ja-stop.md @@ -0,0 +1,162 @@ +--- +layout: default +title: Japanese stop +parent: Token filters +nav_order: 178 +--- + +# Japanese stop token filter + +The `ja_stop` token filter removes Japanese stop words from a token stream. It matches tokens against a word list, either the built-in Japanese stop set or a custom list that you provide. To remove tokens by grammatical category instead, use [`kuromoji_part_of_speech`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/). + +The filter also supports a suggest-friendly mode (`remove_trailing: false`) in which trailing stop words are preserved. This is important for autocomplete use cases where a user may be in the middle of typing a phrase that ends with a stop word or particle. + +## Installation + +The `ja_stop` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `ja_stop` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`stopwords` | String or array of strings | The stop words to use. Accepts `_japanese_` for the built-in Japanese stop set, an array of explicit stop words, or a path to a file containing one stop word per line. Default is `_japanese_` (the same stop set used by the built-in `kuromoji` analyzer). +`ignore_case` | Boolean | When `true`, stop word matching is case insensitive. Default is `false`. +`remove_trailing` | Boolean | When `true` (default), a stop word at the end of the token stream is removed. When `false`, a trailing stop word is preserved, enabling prefix-match completion queries to work correctly on partially typed input. + +For the full list of stop words in the built-in stop set, see [stopwords.txt](https://github.com/apache/lucene/blob/main/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stopwords.txt) in the Lucene repository. + +## Example: Minimal usage + +The following example uses `ja_stop` in isolation to show what the filter removes on its own: + +```json +PUT /ja-stop-minimal-index +{ + "settings": { + "analysis": { + "analyzer": { + "ja_stop_minimal_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["ja_stop"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with the sentence `新聞を読んでいるばかりだ` ("I do nothing but read the newspaper"), which the tokenizer segments into `新聞`, `を`, `読ん`, `で`, `いる`, `ばかり`, and `だ`: + +```json +POST /ja-stop-minimal-index/_analyze +{ + "analyzer": "ja_stop_minimal_analyzer", + "text": "新聞を読んでいるばかりだ" +} +``` +{% include copy-curl.html %} + +The filter removes `を`, `で`, `いる`, and `だ` because they are in the `_japanese_` stop set. The inflected stem `読ん` and the adverbial particle `ばかり` are not in the stop set, so they remain unchanged alongside the content token `新聞`, because `ja_stop` does not normalize inflections or filter by grammatical category: + +```json +{ + "tokens": [ + { + "token": "新聞", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "読ん", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "ばかり", + "start_offset": 8, + "end_offset": 11, + "type": "word", + "position": 5 + } + ] +} +``` + +Compare this with the following [full pipeline example](#example-full-analysis-pipeline). Adding `kuromoji_baseform` normalizes `読ん` to its dictionary form `読む`. Adding `kuromoji_part_of_speech` removes the adverbial particle `ばかり`, which is not in the `_japanese_` stop word list and therefore cannot be removed by `ja_stop` alone. + +## Example: Full analysis pipeline + +This example uses the same sentence `新聞を読んでいるばかりだ` ("I do nothing but read the newspaper") to show how all three filters contribute distinct work when combined: + +- `kuromoji_baseform` normalizes the inflected verb stem `読ん` to its dictionary form `読む`. +- `kuromoji_part_of_speech` removes the adverbial particle `ばかり`, which `ja_stop` does not handle, and the particles `を`, `で`, and `だ`, which `ja_stop` also removes. +- `ja_stop` removes the remaining `いる`, which is listed in the built-in Japanese stop set. + +Create an index with an analyzer that chains all three filters: + +```json +PUT /ja-stop-index +{ + "settings": { + "analysis": { + "analyzer": { + "ja_stop_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_baseform", "kuromoji_part_of_speech", "ja_stop"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with the same sentence: + +```json +POST /ja-stop-index/_analyze +{ + "analyzer": "ja_stop_analyzer", + "text": "新聞を読んでいるばかりだ" +} +``` +{% include copy-curl.html %} + +The response contains only the two content tokens with the verb in its base form: + +```json +{ + "tokens": [ + { + "token": "新聞", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "読む", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + } + ] +} +``` + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji base form token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-baseform/) +- [Kuromoji part-of-speech token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/) diff --git a/_analyzers/token-filters/keep-types.md b/_analyzers/token-filters/keep-types.md new file mode 100644 index 00000000..59e617f5 --- /dev/null +++ b/_analyzers/token-filters/keep-types.md @@ -0,0 +1,115 @@ +--- +layout: default +title: Keep types +parent: Token filters +nav_order: 180 +--- + +# Keep types token filter + +The `keep_types` token filter is a type of token filter used in text analysis to control which token types are kept or discarded. Different tokenizers produce different token types, for example, ``, ``, or ``. + +The `keyword`, `simple_pattern`, and `simple_pattern_split` tokenizers do not support the `keep_types` token filter because these tokenizers do not support token type attributes. +{: .note} + +## Parameters + +The `keep_types` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`types` | Required | List of strings | List of token types to be kept or discarded (determined by the `mode`). +`mode`| Optional | String | Whether to `include` or `exclude` the token types specified in `types`. Default is `include`. + + +## Example + +The following example request creates a new index named `test_index` and configures an analyzer with a `keep_types` filter: + +```json +PUT /test_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "keep_types_filter"] + } + }, + "filter": { + "keep_types_filter": { + "type": "keep_types", + "types": [""] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /test_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Hello 2 world! This is an example." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "hello", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "world", + "start_offset": 8, + "end_offset": 13, + "type": "", + "position": 2 + }, + { + "token": "this", + "start_offset": 15, + "end_offset": 19, + "type": "", + "position": 3 + }, + { + "token": "is", + "start_offset": 20, + "end_offset": 22, + "type": "", + "position": 4 + }, + { + "token": "an", + "start_offset": 23, + "end_offset": 25, + "type": "", + "position": 5 + }, + { + "token": "example", + "start_offset": 26, + "end_offset": 33, + "type": "", + "position": 6 + } + ] +} +``` diff --git a/_analyzers/token-filters/keep-words.md b/_analyzers/token-filters/keep-words.md new file mode 100644 index 00000000..4a6b199e --- /dev/null +++ b/_analyzers/token-filters/keep-words.md @@ -0,0 +1,92 @@ +--- +layout: default +title: Keep words +parent: Token filters +nav_order: 190 +--- + +# Keep words token filter + +The `keep_words` token filter is designed to keep only certain words during the analysis process. This filter is useful if you have a large body of text but are only interested in certain keywords or terms. + +## Parameters + +The `keep_words` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`keep_words` | Required if `keep_words_path` is not configured | List of strings | The list of words to keep. +`keep_words_path` | Required if `keep_words` is not configured | String | The path to the file containing the list of words to keep. +`keep_words_case` | Optional | Boolean | Whether to lowercase all words during comparison. Default is `false`. + + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `keep_words` filter: + +```json +PUT my_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_keep_word": { + "tokenizer": "standard", + "filter": [ "keep_words_filter" ] + } + }, + "filter": { + "keep_words_filter": { + "type": "keep", + "keep_words": ["example", "world", "opensearch"], + "keep_words_case": true + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_index/_analyze +{ + "analyzer": "custom_keep_word", + "text": "Hello, world! This is an OpenSearch example." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "world", + "start_offset": 7, + "end_offset": 12, + "type": "", + "position": 1 + }, + { + "token": "OpenSearch", + "start_offset": 25, + "end_offset": 35, + "type": "", + "position": 5 + }, + { + "token": "example", + "start_offset": 36, + "end_offset": 43, + "type": "", + "position": 6 + } + ] +} +``` diff --git a/_analyzers/token-filters/keyword-marker.md b/_analyzers/token-filters/keyword-marker.md new file mode 100644 index 00000000..0ec2cb96 --- /dev/null +++ b/_analyzers/token-filters/keyword-marker.md @@ -0,0 +1,127 @@ +--- +layout: default +title: Keyword marker +parent: Token filters +nav_order: 200 +--- + +# Keyword marker token filter + +The `keyword_marker` token filter is used to prevent certain tokens from being altered by stemmers or other filters. The `keyword_marker` token filter does this by marking the specified tokens as `keywords`, which prevents any stemming or other processing. This ensures that specific words remain in their original form. + +## Parameters + +The `keyword_marker` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`ignore_case` | Optional | Boolean | Whether to ignore the letter case when matching keywords. Default is `false`. +`keywords` | Required if either `keywords_path` or `keywords_pattern` is not set | List of strings | The list of tokens to mark as keywords. +`keywords_path` | Required if either `keywords` or `keywords_pattern` is not set | String | The path (relative to the `config` directory or absolute) to the list of keywords. +`keywords_pattern` | Required if either `keywords` or `keywords_path` is not set | String | A [regular expression](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) used for matching tokens to be marked as keywords. + + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `keyword_marker` filter. The filter marks the word `example` as a keyword: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "keyword_marker_filter", "stemmer"] + } + }, + "filter": { + "keyword_marker_filter": { + "type": "keyword_marker", + "keywords": ["example"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Favorite example" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens. Note that while the word `favorite` was stemmed, the word `example` was not stemmed because it was marked as a keyword: + +```json +{ + "tokens": [ + { + "token": "favorit", + "start_offset": 0, + "end_offset": 8, + "type": "", + "position": 0 + }, + { + "token": "example", + "start_offset": 9, + "end_offset": 16, + "type": "", + "position": 1 + } + ] +} +``` + +You can further examine the impact of the `keyword_marker` token filter by adding the following parameters to the `_analyze` query: + +```json +GET /my_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "This is an OpenSearch example demonstrating keyword marker.", + "explain": true, + "attributes": "keyword" +} +``` +{% include copy-curl.html %} + +This will produce additional details in the response similar to the following: + +```json +{ + "name": "porter_stem", + "tokens": [ + ... + { + "token": "example", + "start_offset": 22, + "end_offset": 29, + "type": "", + "position": 4, + "keyword": true + }, + { + "token": "demonstr", + "start_offset": 30, + "end_offset": 43, + "type": "", + "position": 5, + "keyword": false + }, + ... + ] +} +``` diff --git a/_analyzers/token-filters/keyword-repeat.md b/_analyzers/token-filters/keyword-repeat.md new file mode 100644 index 00000000..5ba15a03 --- /dev/null +++ b/_analyzers/token-filters/keyword-repeat.md @@ -0,0 +1,160 @@ +--- +layout: default +title: Keyword repeat +parent: Token filters +nav_order: 210 +--- + +# Keyword repeat token filter + +The `keyword_repeat` token filter emits the keyword version of a token into a token stream. This filter is typically used when you want to retain both the original token and its modified version after further token transformations, such as stemming or synonym expansion. The duplicated tokens allow the original, unchanged version of the token to remain in the final analysis alongside the modified versions. + +The `keyword_repeat` token filter should be placed before stemming filters. Stemming is not applied to every token, thus you may have duplicate tokens in the same position after stemming. To remove duplicate tokens, use the `remove_duplicates` token filter after the stemmer. +{: .note} + + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `keyword_repeat` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_kstem": { + "type": "kstem" + }, + "my_lowercase": { + "type": "lowercase" + } + }, + "analyzer": { + "my_custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "my_lowercase", + "keyword_repeat", + "my_kstem" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "Stopped quickly" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "stopped", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "stop", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "quickly", + "start_offset": 8, + "end_offset": 15, + "type": "", + "position": 1 + }, + { + "token": "quick", + "start_offset": 8, + "end_offset": 15, + "type": "", + "position": 1 + } + ] +} +``` + +You can further examine the impact of the `keyword_repeat` token filter by adding the following parameters to the `_analyze` query: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "Stopped quickly", + "explain": true, + "attributes": "keyword" +} +``` +{% include copy-curl.html %} + +The response includes detailed information, such as tokenization, filtering, and the application of specific token filters: + +```json +{ + "detail": { + "custom_analyzer": true, + "charfilters": [], + "tokenizer": { + "name": "standard", + "tokens": [ + {"token": "OpenSearch","start_offset": 0,"end_offset": 10,"type": "","position": 0}, + {"token": "helped","start_offset": 11,"end_offset": 17,"type": "","position": 1}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "","position": 2}, + {"token": "employers","start_offset": 23,"end_offset": 32,"type": "","position": 3} + ] + }, + "tokenfilters": [ + { + "name": "lowercase", + "tokens": [ + {"token": "opensearch","start_offset": 0,"end_offset": 10,"type": "","position": 0}, + {"token": "helped","start_offset": 11,"end_offset": 17,"type": "","position": 1}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "","position": 2}, + {"token": "employers","start_offset": 23,"end_offset": 32,"type": "","position": 3} + ] + }, + { + "name": "keyword_marker_filter", + "tokens": [ + {"token": "opensearch","start_offset": 0,"end_offset": 10,"type": "","position": 0,"keyword": true}, + {"token": "helped","start_offset": 11,"end_offset": 17,"type": "","position": 1,"keyword": false}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "","position": 2,"keyword": false}, + {"token": "employers","start_offset": 23,"end_offset": 32,"type": "","position": 3,"keyword": false} + ] + }, + { + "name": "kstem_filter", + "tokens": [ + {"token": "opensearch","start_offset": 0,"end_offset": 10,"type": "","position": 0,"keyword": true}, + {"token": "help","start_offset": 11,"end_offset": 17,"type": "","position": 1,"keyword": false}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "","position": 2,"keyword": false}, + {"token": "employer","start_offset": 23,"end_offset": 32,"type": "","position": 3,"keyword": false} + ] + } + ] + } +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/kstem.md b/_analyzers/token-filters/kstem.md new file mode 100644 index 00000000..ed0da3b1 --- /dev/null +++ b/_analyzers/token-filters/kstem.md @@ -0,0 +1,92 @@ +--- +layout: default +title: KStem +parent: Token filters +nav_order: 220 +--- + +# KStem token filter + +The `kstem` token filter is a stemming filter used to reduce words to their root forms. The filter is a lightweight algorithmic stemmer designed for the English language that performs the following stemming operations: + +- Reduces plurals to their singular form. +- Converts different verb tenses to their base form. +- Removes common derivational endings, such as "-ing" or "-ed". + +The `kstem` token filter is equivalent to the a `stemmer` filter configured with a `light_english` language. It provides a more conservative stemming compared to other stemming filters like `porter_stem`. + +The `kstem` token filter is based on the Lucene KStemFilter. For more information, see the [Lucene documentation](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/en/KStemFilter.html). + +## Example + +The following example request creates a new index named `my_kstem_index` and configures an analyzer with a `kstem` filter: + +```json +PUT /my_kstem_index +{ + "settings": { + "analysis": { + "filter": { + "kstem_filter": { + "type": "kstem" + } + }, + "analyzer": { + "my_kstem_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "kstem_filter" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_kstem_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_kstem_index/_analyze +{ + "analyzer": "my_kstem_analyzer", + "text": "stops stopped" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "stop", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "stop", + "start_offset": 6, + "end_offset": 13, + "type": "", + "position": 1 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/kuromoji-baseform.md b/_analyzers/token-filters/kuromoji-baseform.md new file mode 100644 index 00000000..55f8fddc --- /dev/null +++ b/_analyzers/token-filters/kuromoji-baseform.md @@ -0,0 +1,199 @@ +--- +layout: default +title: Kuromoji base form +parent: Token filters +nav_order: 230 +--- + +# Kuromoji base form token filter + +The `kuromoji_baseform` token filter replaces inflected Japanese tokens with their dictionary base form, acting as a lemmatizer. + +The filter applies to tokens that carry dictionary form information from the Kuromoji tokenizer. Tokens without dictionary information (such as unknown words) are passed through unchanged. + +Note that the Kuromoji tokenizer splits some conjugated forms into multiple tokens before this filter runs. For example, the past-tense *i*-adjective 美しかった (was beautiful) is split into 美しかっ and た. The filter normalizes 美しかっ to 美しい, but た remains as a separate token. To remove auxiliary verb tokens such as た, add [`kuromoji_part_of_speech`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/) and [`ja_stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ja-stop/) to the filter chain. + +## Installation + +The `kuromoji_baseform` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The `kuromoji_baseform` token filter has no configurable parameters. + +## Example + +The following example creates an index with a custom analyzer that uses `kuromoji_baseform`: + +```json +PUT /kuromoji-baseform-index +{ + "settings": { + "analysis": { + "analyzer": { + "baseform_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_baseform"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with a sentence that includes conjugated verbs (meaning "I ate sushi and drank tea"): + +```json +POST /kuromoji-baseform-index/_analyze +{ + "analyzer": "baseform_analyzer", + "text": "寿司を食べてお茶を飲んだ" +} +``` +{% include copy-curl.html %} + +The response shows the conjugated verbs normalized to their base forms. The particles を, て, and the auxiliary verb だ are retained because this analyzer uses only `kuromoji_baseform`: + +```json +{ + "tokens": [ + { + "token": "寿司", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "を", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "食べる", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "て", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 3 + }, + { + "token": "お茶", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "を", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 5 + }, + { + "token": "飲む", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 6 + }, + { + "token": "だ", + "start_offset": 11, + "end_offset": 12, + "type": "word", + "position": 7 + } + ] +} +``` + +The te-form 食べて and past-tense form 飲んだ are replaced with their base forms 食べる and 飲む. The particles を, て, and auxiliary verb だ remain in the token stream because `kuromoji_baseform` only normalizes inflection; it does not remove grammatical tokens. + +## Example: Combining with part-of-speech and stop filters + +To also remove particles and auxiliary verbs, add `kuromoji_part_of_speech` and `ja_stop` to the filter chain. The following example creates an index with a combined analyzer: + +```json +PUT /kuromoji-baseform-full-index +{ + "settings": { + "analysis": { + "analyzer": { + "baseform_full_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_baseform", "kuromoji_part_of_speech", "ja_stop"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Run the same sentence through the combined analyzer: + +```json +POST /kuromoji-baseform-full-index/_analyze +{ + "analyzer": "baseform_full_analyzer", + "text": "寿司を食べてお茶を飲んだ" +} +``` +{% include copy-curl.html %} + +The response shows only the content words. The particles を, て, and the auxiliary verb だ are removed, and position gaps mark where they were: + +```json +{ + "tokens": [ + { + "token": "寿司", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "食べる", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "お茶", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "飲む", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 6 + } + ] +} +``` + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji part-of-speech token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/) +- [Japanese stop token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ja-stop/) diff --git a/_analyzers/token-filters/kuromoji-completion.md b/_analyzers/token-filters/kuromoji-completion.md new file mode 100644 index 00000000..8b7813eb --- /dev/null +++ b/_analyzers/token-filters/kuromoji-completion.md @@ -0,0 +1,263 @@ +--- +layout: default +title: Kuromoji completion +parent: Token filters +nav_order: 231 +--- + +# Kuromoji completion token filter + +The `kuromoji_completion` token filter generates romanized reading variants for Japanese tokens. When used in an index analyzer, it emits both the original token and one or more romanized alternatives at the same position. This allows users to search for Japanese content by typing in either Japanese characters or their phonetic equivalents. + +The filter is designed for use with the `kuromoji_completion` analyzer or in custom analyzers that power autocomplete or suggest fields. Because the filter is applied differently at index time and query time, it exposes a `mode` parameter. + +## Installation + +The `kuromoji_completion` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `kuromoji_completion` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`mode` | String | Controls how tokens are generated. Valid values are `index` (default) and `query`. Both modes expand katakana tokens into their original form plus all romaji variants. The `query` mode applies two additional rules for handling partial input from an input method editor (IME): it concatenates consecutive kana tokens into a single token before romanizing, and it merges a kana token with a trailing lowercase alphabet token that represents a partially typed IME keystroke (for example, `サッ` followed by `k` becomes `サッk`). + +Use `query` mode in the search analyzer so that partial IME input typed by a user is correctly assembled before romanization. +{: .tip} + +## Example + +The following example creates an index named `kuromoji_completion_example` with both an index-time analyzer (using `mode: index`) and a search-time analyzer (using `mode: query`), and maps the `suggest` field to use them: + +```json +PUT /kuromoji_completion_example +{ + "settings": { + "analysis": { + "filter": { + "completion_index_filter": { + "type": "kuromoji_completion", + "mode": "index" + }, + "completion_query_filter": { + "type": "kuromoji_completion", + "mode": "query" + } + }, + "analyzer": { + "completion_index_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["completion_index_filter"] + }, + "completion_query_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["completion_query_filter"] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "completion_index_analyzer", + "search_analyzer": "completion_query_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +With this configuration, a query containing either `konpyu` or `コンピュ` matches documents indexed with `コンピューター`. + +### Index-time tokens + +Use the following request to examine the tokens generated at index time using text that translates to "use a computer": + +```json +POST /kuromoji_completion_example/_analyze +{ + "analyzer": "completion_index_analyzer", + "text": "コンピューターを使う" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens. Each source token produces the original form plus one or more romaji variants at the same position. For `コンピューター` (computer), the filter emits the original katakana token and two romaji variants (`konpyuーtaー` and `konnpyuーtaー`). For the particle `を`, it emits the original and two romaji forms (`wo` and `o`). For the verb `使う` (use), it emits the original and two romaji forms (`tukau` and `tsukau`): + +```json +{ + "tokens": [ + { + "token": "コンピューター", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "konpyuーtaー", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "konnpyuーtaー", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "を", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "wo", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "o", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "使う", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 2 + }, + { + "token": "tukau", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 2 + }, + { + "token": "tsukau", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 2 + } + ] +} +``` + +### Query-time tokens + +Both modes expand katakana tokens into the original form plus all romaji variants. The key difference of `query` mode is its handling of partial IME input: when a katakana token is followed by a lowercase alphabet character that represents an in-progress IME keystroke, `query` mode concatenates them into a single token before romanizing. Without this, the partial keystroke would be processed as a separate token and the romanization would not match any indexed variant. + +The following example demonstrates this with the input `コンピュt`, which represents a user who has typed the katakana `コンピュ` and is still composing the next character `t` using an IME: + +```json +POST /kuromoji_completion_example/_analyze +{ + "analyzer": "completion_query_analyzer", + "text": "コンピュt" +} +``` +{% include copy-curl.html %} + +The `query` mode recognizes `t` as a partial IME keystroke and merges it with the preceding katakana token before romanizing, producing three tokens for the combined form `コンピュt`: the merged katakana-plus-keystroke token and its two romaji variants (`konpyut` and `konnpyut`): + +```json +{ + "tokens": [ + { + "token": "コンピュt", + "start_offset": 0, + "end_offset": 5, + "type": "word", + "position": 0 + }, + { + "token": "konpyut", + "start_offset": 0, + "end_offset": 5, + "type": "word", + "position": 0 + }, + { + "token": "konnpyut", + "start_offset": 0, + "end_offset": 5, + "type": "word", + "position": 0 + } + ] +} +``` + +With `index` mode, `コンピュ` and `t` would be emitted as two separate tokens at different positions, so the romanized form `konpyut` would never be produced and a search for `konpyut` would not match. + +### Searching with prefix queries + +Because the index stores the original katakana token and all its romaji variants, you can use a `prefix` query directly against the indexed romaji tokens to implement autocomplete. The `prefix` query bypasses the analyzer and matches any indexed token that starts with the given value. + +First, index a sample document: + +```json +POST /kuromoji_completion_example/_doc/1 +{ + "content": "コンピューターを使う" +} +``` +{% include copy-curl.html %} + +The following `prefix` query matches the document because `konnp` is a prefix of the indexed romaji token `konnpyuーtaー`: + +```json +GET /kuromoji_completion_example/_search +{ + "query": { + "prefix": { + "content": { + "value": "konnp" + } + } + } +} +``` +{% include copy-curl.html %} + +The following `prefix` query matches the document using the katakana prefix `コンピュ`, which is a prefix of the indexed katakana token `コンピューター`: + +```json +GET /kuromoji_completion_example/_search +{ + "query": { + "prefix": { + "content": { + "value": "コンピュ" + } + } + } +} +``` +{% include copy-curl.html %} + +For a higher-level approach that configures the `mode` at the analyzer level rather than the filter level, use the built-in [`kuromoji_completion` analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/#kuromoji-completion-analyzer). +{: .tip} + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji reading form token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-readingform/) +- [Japanese stop token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ja-stop/) diff --git a/_analyzers/token-filters/kuromoji-number.md b/_analyzers/token-filters/kuromoji-number.md new file mode 100644 index 00000000..47868d39 --- /dev/null +++ b/_analyzers/token-filters/kuromoji-number.md @@ -0,0 +1,108 @@ +--- +layout: default +title: Kuromoji number +parent: Token filters +nav_order: 232 +--- + +# Kuromoji number token filter + +The `kuromoji_number` token filter normalizes Japanese numeral expressions to standard Arabic numerals. Japanese text can represent numbers using kanji numerals (一, 二, 三…), full-width digits (1, 2, 3…), or a mix of both. This filter converts all such expressions to their standard integer or decimal equivalents. + +The filter makes conversions such as the following: + +- 一万二千三百四十五 becomes 12345. +- 3,〇00 becomes 3000. +- 千円 becomes 1000, with the unit 円 remaining as a separate token. + +This filter is useful for faceted search, range queries, and sorting on fields that contain prices, counts, or other quantities written in Japanese notation. + +## Installation + +The `kuromoji_number` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The `kuromoji_number` token filter has no configurable parameters. + +## Example + +The following example creates an index with a custom analyzer that uses `kuromoji_number`: + +```json +PUT /kuromoji-number-index +{ + "settings": { + "analysis": { + "analyzer": { + "number_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_number"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with text containing kanji numeral expressions (meaning "the price is 12,345 yen"): + +```json +POST /kuromoji-number-index/_analyze +{ + "analyzer": "number_analyzer", + "text": "価格は一万二千三百四十五円です" +} +``` +{% include copy-curl.html %} + +The response shows the kanji numeral converted to an Arabic integer. Note that the `12345` token spans over offsets 3–12 because the source kanji numeral `一万二千三百四十五` is 9 characters long: + +```json +{ + "tokens": [ + { + "token": "価格", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "は", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "12345", + "start_offset": 3, + "end_offset": 12, + "type": "word", + "position": 2 + }, + { + "token": "円", + "start_offset": 12, + "end_offset": 13, + "type": "word", + "position": 3 + }, + { + "token": "です", + "start_offset": 13, + "end_offset": 15, + "type": "word", + "position": 4 + } + ] +} +``` + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) diff --git a/_analyzers/token-filters/kuromoji-part-of-speech.md b/_analyzers/token-filters/kuromoji-part-of-speech.md new file mode 100644 index 00000000..0f09630a --- /dev/null +++ b/_analyzers/token-filters/kuromoji-part-of-speech.md @@ -0,0 +1,129 @@ +--- +layout: default +title: Kuromoji part of speech +parent: Token filters +nav_order: 233 +--- + +# Kuromoji part of speech token filter + +The `kuromoji_part_of_speech` token filter removes tokens whose part-of-speech (POS) tag matches an entry in a configured list of stop tags. The Kuromoji tokenizer assigns each token an IPAdic POS tag. This filter reads that tag and discards tokens that serve a grammatical function (such as particles, auxiliary verbs, and punctuation) rather than a content function. + +## Installation + +The `kuromoji_part_of_speech` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `kuromoji_part_of_speech` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`stoptags` | Array of strings | A list of IPAdic part-of-speech tags to remove. Tokens whose POS tag exactly matches an entry in this list are discarded. Default is the built-in Japanese stop tag set. + +For the full list of available stop tags, see [stoptags.txt](https://github.com/apache/lucene/blob/main/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stoptags.txt) in the Lucene repository. + +## Example: Default filter + +The following example creates an index with an analyzer that uses the default stop tag list: + +```json +PUT /kuromoji-pos-index +{ + "settings": { + "analysis": { + "analyzer": { + "pos_filter_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_part_of_speech"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with a sentence meaning "I eat sushi at the Tokyo restaurant": + +```json +POST /kuromoji-pos-index/_analyze +{ + "analyzer": "pos_filter_analyzer", + "text": "東京のレストランで寿司を食べる" +} +``` +{% include copy-curl.html %} + +The response shows the particles の (genitive), で (locative), and を (accusative) removed: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "レストラン", + "start_offset": 3, + "end_offset": 8, + "type": "word", + "position": 2 + }, + { + "token": "寿司", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 4 + }, + { + "token": "食べる", + "start_offset": 12, + "end_offset": 15, + "type": "word", + "position": 6 + } + ] +} +``` + +## Example: Custom stop tags + +The following example creates a filter that removes only auxiliary verbs (助動詞) while keeping all other grammatical tokens: + +```json +PUT /kuromoji-custom-pos-index +{ + "settings": { + "analysis": { + "filter": { + "auxiliary_verb_filter": { + "type": "kuromoji_part_of_speech", + "stoptags": ["助動詞"] + } + }, + "analyzer": { + "auxiliary_filter_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["auxiliary_verb_filter"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji base form token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-baseform/) +- [Japanese stop token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ja-stop/) diff --git a/_analyzers/token-filters/kuromoji-readingform.md b/_analyzers/token-filters/kuromoji-readingform.md new file mode 100644 index 00000000..fc44ea50 --- /dev/null +++ b/_analyzers/token-filters/kuromoji-readingform.md @@ -0,0 +1,211 @@ +--- +layout: default +title: Kuromoji reading form +parent: Token filters +nav_order: 234 +--- + +# Kuromoji reading form token filter + +The `kuromoji_readingform` token filter replaces each token with its reading form. Japanese characters (kanji) have multiple possible readings; this filter uses the reading information provided by the Kuromoji tokenizer to emit the phonetic form of each token. The filter can output readings in katakana (Japanese phonetic script) or in romaji (Latin script transliteration). + +## Installation + +The `kuromoji_readingform` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `kuromoji_readingform` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`use_romaji` | Boolean | When `false` (default), tokens are replaced with their katakana reading. When `true`, tokens are replaced with their romaji (Latin script) transliteration. + +## Example: Katakana reading (default) + +The following example creates an index with an analyzer that outputs katakana readings: + +```json +PUT /kuromoji-reading-katakana-index +{ + "settings": { + "analysis": { + "filter": { + "katakana_reading": { + "type": "kuromoji_readingform", + "use_romaji": false + } + }, + "analyzer": { + "katakana_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["katakana_reading"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with a sentence meaning "Tokyo is the capital of Japan": + +```json +POST /kuromoji-reading-katakana-index/_analyze +{ + "analyzer": "katakana_analyzer", + "text": "東京は日本の首都です" +} +``` +{% include copy-curl.html %} + +The response shows kanji tokens replaced with their katakana readings: + +```json +{ + "tokens": [ + { + "token": "トウキョウ", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "ハ", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "ニッポン", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "ノ", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 3 + }, + { + "token": "シュト", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "デス", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 5 + } + ] +} +``` + +## Example: Romaji reading + +The following example creates an analyzer that outputs romaji transliterations: + +```json +PUT /kuromoji-reading-romaji-index +{ + "settings": { + "analysis": { + "filter": { + "romaji_reading": { + "type": "kuromoji_readingform", + "use_romaji": true + } + }, + "analyzer": { + "romaji_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["romaji_reading"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test with the same sentence: + +```json +POST /kuromoji-reading-romaji-index/_analyze +{ + "analyzer": "romaji_analyzer", + "text": "東京は日本の首都です" +} +``` +{% include copy-curl.html %} + +The response shows Latin-script transliterations: + +```json +{ + "tokens": [ + { + "token": "tōkyō", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "ha", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "nippon", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "no", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 3 + }, + { + "token": "shuto", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "desu", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 5 + } + ] +} +``` + +The reading form filter replaces the entire token content. If you need both the original form and the reading, use the `kuromoji_completion` token filter instead, which adds reading variants as additional tokens at the same position. +{: .tip} + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji completion token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-completion/) diff --git a/_analyzers/token-filters/kuromoji-stemmer.md b/_analyzers/token-filters/kuromoji-stemmer.md new file mode 100644 index 00000000..131d1556 --- /dev/null +++ b/_analyzers/token-filters/kuromoji-stemmer.md @@ -0,0 +1,119 @@ +--- +layout: default +title: Kuromoji stemmer +parent: Token filters +nav_order: 235 +--- + +# Kuromoji stemmer token filter + +The `kuromoji_stemmer` token filter normalizes katakana words by removing a trailing long vowel mark (ー) from words that meet a minimum length threshold. Many foreign loanwords in Japanese are written in katakana with a trailing ー that denotes a lengthened final vowel (for example, コンピューター, プリンター). In practice, Japanese speakers often drop the trailing ー in informal or technical writing, resulting in two surface forms for the same word. This filter collapses those variants to a single canonical form. + +The filter makes conversions such as the following: + +- コンピューター (computer) becomes コンピュータ. +- プリンター (printer) becomes プリンタ. + +## Installation + +The `kuromoji_stemmer` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `kuromoji_stemmer` token filter. + +Parameter | Data type | Description +:--- | :--- | :--- +`minimum_length` | Integer | The minimum number of characters a token must have for the trailing long vowel mark to be removed. Tokens shorter than this threshold are passed through unchanged. Default is `4`. + +The default minimum length of `4` prevents short words such as カー (car, two characters) from being incorrectly stemmed to カ. +{: .note} + +## Example + +The following example creates an index with a custom analyzer that uses `kuromoji_stemmer`: + +```json +PUT /kuromoji-stemmer-index +{ + "settings": { + "analysis": { + "filter": { + "katakana_stemmer": { + "type": "kuromoji_stemmer", + "minimum_length": 4 + } + }, + "analyzer": { + "stemmer_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["katakana_stemmer"] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the analyzer with katakana loanwords (meaning "I use a computer and printer"): + +```json +POST /kuromoji-stemmer-index/_analyze +{ + "analyzer": "stemmer_analyzer", + "text": "コンピューターとプリンターを使う" +} +``` +{% include copy-curl.html %} + +The response shows the trailing long vowel marks removed from both words: + +```json +{ + "tokens": [ + { + "token": "コンピュータ", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "と", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "プリンタ", + "start_offset": 8, + "end_offset": 13, + "type": "word", + "position": 2 + }, + { + "token": "を", + "start_offset": 13, + "end_offset": 14, + "type": "word", + "position": 3 + }, + { + "token": "使う", + "start_offset": 14, + "end_offset": 16, + "type": "word", + "position": 4 + } + ] +} +``` + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/kuromoji/) +- [Kuromoji base form token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-baseform/) diff --git a/_analyzers/token-filters/length.md b/_analyzers/token-filters/length.md new file mode 100644 index 00000000..f6c5dcc7 --- /dev/null +++ b/_analyzers/token-filters/length.md @@ -0,0 +1,91 @@ +--- +layout: default +title: Length +parent: Token filters +nav_order: 240 +--- + +# Length token filter + +The `length` token filter is used to remove tokens that don't meet specified length criteria (minimum and maximum values) from the token stream. + +## Parameters + +The `length` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`min` | Optional | Integer | The minimum token length. Default is `0`. +`max` | Optional | Integer | The maximum token length. Default is `Integer.MAX_VALUE` (`2147483647`). + + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `length` filter: + +```json +PUT my_index +{ + "settings": { + "analysis": { + "analyzer": { + "only_keep_4_to_10_characters": { + "tokenizer": "whitespace", + "filter": [ "length_4_to_10" ] + } + }, + "filter": { + "length_4_to_10": { + "type": "length", + "min": 4, + "max": 10 + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_index/_analyze +{ + "analyzer": "only_keep_4_to_10_characters", + "text": "OpenSearch is a great tool!" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "great", + "start_offset": 16, + "end_offset": 21, + "type": "word", + "position": 3 + }, + { + "token": "tool!", + "start_offset": 22, + "end_offset": 27, + "type": "word", + "position": 4 + } + ] +} +``` diff --git a/_analyzers/token-filters/limit.md b/_analyzers/token-filters/limit.md new file mode 100644 index 00000000..a849f5f0 --- /dev/null +++ b/_analyzers/token-filters/limit.md @@ -0,0 +1,89 @@ +--- +layout: default +title: Limit +parent: Token filters +nav_order: 250 +--- + +# Limit token filter + +The `limit` token filter is used to limit the number of tokens passed through the analysis chain. + +## Parameters + +The `limit` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`max_token_count` | Optional | Integer | The maximum number of tokens to be generated. Default is `1`. +`consume_all_tokens` | Optional | Boolean | (Expert-level setting) Uses all tokens from the tokenizer, even if the result exceeds `max_token_count`. When this parameter is set, the output still only contains the number of tokens specified by `max_token_count`. However, all tokens generated by the tokenizer are processed. Default is `false`. + +## Example + +The following example request creates a new index named `my_index` and configures an analyzer with a `limit` filter: + +```json +PUT my_index +{ + "settings": { + "analysis": { + "analyzer": { + "three_token_limit": { + "tokenizer": "standard", + "filter": [ "custom_token_limit" ] + } + }, + "filter": { + "custom_token_limit": { + "type": "limit", + "max_token_count": 3 + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_index/_analyze +{ + "analyzer": "three_token_limit", + "text": "OpenSearch is a powerful and flexible search engine." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "a", + "start_offset": 14, + "end_offset": 15, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/lowercase.md b/_analyzers/token-filters/lowercase.md new file mode 100644 index 00000000..11956ca3 --- /dev/null +++ b/_analyzers/token-filters/lowercase.md @@ -0,0 +1,82 @@ +--- +layout: default +title: Lowercase +parent: Token filters +nav_order: 260 +--- + +# Lowercase token filter + +The `lowercase` token filter is used to convert all characters in the token stream to lowercase, making searches case insensitive. + +## Parameters + +The `lowercase` token filter can be configured with the following parameter. + +Parameter | Required/Optional | Description +:--- | :--- | :--- + `language` | Optional | Specifies a language-specific token filter. Valid values are:
- [`greek`](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/el/GreekLowerCaseFilter.html)
- [`irish`](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ga/IrishLowerCaseFilter.html)
- [`turkish`](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/tr/TurkishLowerCaseFilter.html).
Default is the [Lucene LowerCaseFilter](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/core/LowerCaseFilter.html). + +## Example + +The following example request creates a new index named `custom_lowercase_example`. It configures an analyzer with a `lowercase` filter and specifies `greek` as the `language`: + +```json +PUT /custom_lowercase_example +{ + "settings": { + "analysis": { + "analyzer": { + "greek_lowercase_example": { + "type": "custom", + "tokenizer": "standard", + "filter": ["greek_lowercase"] + } + }, + "filter": { + "greek_lowercase": { + "type": "lowercase", + "language": "greek" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /custom_lowercase_example/_analyze +{ + "analyzer": "greek_lowercase_example", + "text": "Αθήνα ΕΛΛΑΔΑ" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "αθηνα", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "ελλαδα", + "start_offset": 6, + "end_offset": 12, + "type": "", + "position": 1 + } + ] +} +``` diff --git a/_analyzers/token-filters/min-hash.md b/_analyzers/token-filters/min-hash.md new file mode 100644 index 00000000..7a923fcf --- /dev/null +++ b/_analyzers/token-filters/min-hash.md @@ -0,0 +1,157 @@ +--- +layout: default +title: Min hash +parent: Token filters +nav_order: 270 +--- + +# Min hash token filter + +The `min_hash` token filter is used to generate hashes for tokens based on a [MinHash](https://en.wikipedia.org/wiki/MinHash) approximation algorithm, which is useful for detecting similarity between documents. The `min_hash` token filter generates hashes for a set of tokens (typically from an analyzed field). + +Finding similar documents by comparing a document to every other document in an index does not scale to large indexes. Locality-sensitive hashing (LSH) reduces the number of comparisons by hashing documents so that similar documents are likely to produce the same hash values and dissimilar documents are not. MinHash is an LSH technique for [Jaccard similarity](https://en.wikipedia.org/wiki/Jaccard_index), which measures the overlap between two sets of tokens: the number of tokens the sets share divided by the number of distinct tokens in both sets. + +MinHash applies a hash function to every token in a document and keeps only the smallest result. Two documents produce the same minimum hash with a probability equal to their Jaccard similarity, so the more minimum hashes two documents share, the more similar they are likely to be. The `min_hash` filter processes a token stream as follows: + +1. Hashes each token using `hash_count` hash functions. +1. Distributes the hashes among `bucket_count` buckets. +1. Emits the `hash_set_size` smallest hashes from each bucket as tokens. + +The emitted tokens form the document's signature. If you index the signature in a field, a full-text query on that field returns the documents that share signature tokens with the query text, which are candidates for near-duplicates. + +## Parameters + +The `min_hash` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`hash_count` | Optional | Integer | The number of hash values to generate for each token. Increasing this value generally improves the accuracy of similarity estimation but increases the computational cost. Default is `1`. +`bucket_count` | Optional | Integer | The number of hash buckets to use. This affects the granularity of the hashing. A larger number of buckets provides finer granularity and reduces hash collisions but requires more memory. Default is `512`. +`hash_set_size` | Optional | Integer | The number of hashes to retain in each bucket. This can influence the hashing quality. Larger set sizes may lead to better similarity detection but consume more memory. Default is `1`. +`with_rotation` | Optional | Boolean | When set to `true`, the filter populates empty buckets with the value from the first non-empty bucket found to its circular right, provided that the `hash_set_size` is `1`. If the `bucket_count` argument exceeds `1`, this setting automatically defaults to `true`; otherwise, it defaults to `false`. + +## Tuning the min_hash filter + +Consider the following guidelines when configuring the `min_hash` filter: + +- Use word shingles, produced by the [`shingle`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/shingle/) filter, as input to the `min_hash` filter. Comparing sequences of words detects shared passages, while comparing single words only detects shared vocabulary. Choose a shingle size large enough that most shingles are rare across your documents but small enough that the possible shingles can be hashed into 128 bits with few collisions. +- Experiment with the parameter values using your own data. Increasing `bucket_count` or `hash_set_size` keeps more hashes for each document, which makes it less likely that dissimilar documents share tokens and improves precision. Increasing `hash_count` hashes each token in several ways, which produces more candidate matches and improves recall. +- Account for the increase in index size. Each token encodes a 128-bit hash. When `with_rotation` is `true` and `hash_set_size` is `1`, the filter emits `bucket_count` × `hash_count` tokens for every document, regardless of the document's length, so the default settings produce 512 tokens for each document. +- The `min_hash` filter measures whether a token is present, not how often it occurs. A document containing a word once and a document containing the same word many times produce the same hashes. + +## Example + +The following example request creates a new index named `minhash_index` and configures an analyzer with a `min_hash` filter: + +```json +PUT /minhash_index +{ + "settings": { + "analysis": { + "filter": { + "minhash_filter": { + "type": "min_hash", + "hash_count": 3, + "bucket_count": 512, + "hash_set_size": 1, + "with_rotation": false + } + }, + "analyzer": { + "minhash_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "minhash_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /minhash_index/_analyze +{ + "analyzer": "minhash_analyzer", + "text": "OpenSearch is very powerful." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens (the tokens are not human readable because they represent hashes): + +```json +{ + "tokens" : [ + { + "token" : "\u0000\u0000㳠锯ੲ걌䐩䉵", + "start_offset" : 0, + "end_offset" : 27, + "type" : "MIN_HASH", + "position" : 0 + }, + { + "token" : "\u0000\u0000㳠锯ੲ걌䐩䉵", + "start_offset" : 0, + "end_offset" : 27, + "type" : "MIN_HASH", + "position" : 0 + }, + ... +``` + +In order to demonstrate the usefulness of the `min_hash` token filter, you can use the following Python script to compare the two strings using the previously created analyzer: + +```python +from opensearchpy import OpenSearch +from requests.auth import HTTPBasicAuth + +# Initialize the OpenSearch client with authentication +host = 'https://localhost:9200' # Update if using a different host/port +auth = ('admin', 'admin') # Username and password + +# Create the OpenSearch client with SSL verification turned off +client = OpenSearch( + hosts=[host], + http_auth=auth, + use_ssl=True, + verify_certs=False, # Disable SSL certificate validation + ssl_show_warn=False # Suppress SSL warnings in the output +) + +# Analyzes text and returns the minhash tokens +def analyze_text(index, text): + response = client.indices.analyze( + index=index, + body={ + "analyzer": "minhash_analyzer", + "text": text + } + ) + return [token['token'] for token in response['tokens']] + +# Analyze two similar texts +tokens_1 = analyze_text('minhash_index', 'OpenSearch is a powerful search engine.') +tokens_2 = analyze_text('minhash_index', 'OpenSearch is a very powerful search engine.') + +# Calculate Jaccard similarity +set_1 = set(tokens_1) +set_2 = set(tokens_2) +shared_tokens = set_1.intersection(set_2) +jaccard_similarity = len(shared_tokens) / len(set_1.union(set_2)) + +print(f"Jaccard Similarity: {jaccard_similarity}") +``` + +The response should contain the Jaccard similarity score: + +```yaml +Jaccard Similarity: 0.8571428571428571 +``` \ No newline at end of file diff --git a/_analyzers/token-filters/multiplexer.md b/_analyzers/token-filters/multiplexer.md new file mode 100644 index 00000000..21597b7f --- /dev/null +++ b/_analyzers/token-filters/multiplexer.md @@ -0,0 +1,165 @@ +--- +layout: default +title: Multiplexer +parent: Token filters +nav_order: 280 +--- + +# Multiplexer token filter + +The `multiplexer` token filter allows you to create multiple versions of the same token by applying different filters. This is useful when you want to analyze the same token in multiple ways. For example, you may want to analyze a token using different stemming, synonyms, or n-gram filters and use all of the generated tokens together. This token filter works by duplicating the token stream and applying different filters to each copy. + +The `multiplexer` token filter removes duplicate tokens from the token stream. +{: .important} + +The `multiplexer` token filter does not support multiword `synonym` or `synonym_graph` token filters or `shingle` token filters because they need to analyze not only the current token but also upcoming tokens in order to determine how to transform the input correctly. +{: .important} + +## Parameters + +The `multiplexer` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`filters` | Optional | List of strings | A comma-separated list of token filters to apply to each copy of the token stream. Default is an empty list. +`preserve_original` | Optional | Boolean | Whether to keep the original token as one of the outputs. Default is `true`. + +## Example + +The following example request creates a new index named `multiplexer_index` and configures an analyzer with a `multiplexer` filter: + +```json +PUT /multiplexer_index +{ + "settings": { + "analysis": { + "filter": { + "english_stemmer": { + "type": "stemmer", + "name": "english" + }, + "synonym_filter": { + "type": "synonym", + "synonyms": [ + "quick,fast" + ] + }, + "multiplexer_filter": { + "type": "multiplexer", + "filters": ["english_stemmer", "synonym_filter"], + "preserve_original": true + } + }, + "analyzer": { + "multiplexer_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "multiplexer_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /multiplexer_index/_analyze +{ + "analyzer": "multiplexer_analyzer", + "text": "The slow turtle hides from the quick dog" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "The", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "slow", + "start_offset": 4, + "end_offset": 8, + "type": "", + "position": 1 + }, + { + "token": "turtle", + "start_offset": 9, + "end_offset": 15, + "type": "", + "position": 2 + }, + { + "token": "turtl", + "start_offset": 9, + "end_offset": 15, + "type": "", + "position": 2 + }, + { + "token": "hides", + "start_offset": 16, + "end_offset": 21, + "type": "", + "position": 3 + }, + { + "token": "hide", + "start_offset": 16, + "end_offset": 21, + "type": "", + "position": 3 + }, + { + "token": "from", + "start_offset": 22, + "end_offset": 26, + "type": "", + "position": 4 + }, + { + "token": "the", + "start_offset": 27, + "end_offset": 30, + "type": "", + "position": 5 + }, + { + "token": "quick", + "start_offset": 31, + "end_offset": 36, + "type": "", + "position": 6 + }, + { + "token": "fast", + "start_offset": 31, + "end_offset": 36, + "type": "SYNONYM", + "position": 6 + }, + { + "token": "dog", + "start_offset": 37, + "end_offset": 40, + "type": "", + "position": 7 + } + ] +} +``` diff --git a/_analyzers/token-filters/ngram.md b/_analyzers/token-filters/ngram.md new file mode 100644 index 00000000..c029eac2 --- /dev/null +++ b/_analyzers/token-filters/ngram.md @@ -0,0 +1,137 @@ +--- +layout: default +title: N-gram +parent: Token filters +nav_order: 290 +--- + +# N-gram token filter + +The `ngram` token filter is a powerful tool used to break down text into smaller components, known as _n-grams_, which can improve partial matching and fuzzy search capabilities. It works by splitting a token into smaller substrings of defined lengths. These filters are commonly used in search applications to support autocomplete, partial matches, and typo-tolerant search. For more information, see [Autocomplete functionality]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/) and [Did-you-mean]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/). + +## Parameters + +The `ngram` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`min_gram` | Optional | Integer | The minimum length of the n-grams. Default is `1`. +`max_gram` | Optional | Integer | The maximum length of the n-grams. Default is `2`. +`preserve_original` | Optional | Boolean | Whether to keep the original token as one of the outputs. Default is `false`. + +## Example + +The following example request creates a new index named `ngram_example_index` and configures an analyzer with an `ngram` filter: + +```json +PUT /ngram_example_index +{ + "settings": { + "analysis": { + "filter": { + "ngram_filter": { + "type": "ngram", + "min_gram": 2, + "max_gram": 3 + } + }, + "analyzer": { + "ngram_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "ngram_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /ngram_example_index/_analyze +{ + "analyzer": "ngram_analyzer", + "text": "Search" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "se", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "sea", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "ea", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "ear", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "ar", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "arc", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "rc", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "rch", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "ch", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/token-filters/normalization.md b/_analyzers/token-filters/normalization.md new file mode 100644 index 00000000..3ba013b7 --- /dev/null +++ b/_analyzers/token-filters/normalization.md @@ -0,0 +1,88 @@ +--- +layout: default +title: Normalization +parent: Token filters +nav_order: 300 +--- + +# Normalization token filter + +The `normalization` token filter is designed to adjust and simplify text in a way that reduces variations, particularly variations in special characters. It is primarily used to handle variations in writing by standardizing characters in specific languages. + +The following `normalization` token filters are available: + +- [arabic_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html) +- [german_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html) +- [hindi_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html) +- [indic_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html) +- [sorani_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html) +- [persian_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html) +- [scandinavian_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html) +- [scandinavian_folding](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html) +- [serbian_normalization](https://lucene.apache.org/core/{{site.lucene_version}}/analysis/common/org/apache/lucene/analysis/sr/SerbianNormalizationFilter.html) + + +## Example + +The following example request creates a new index named `german_normalizer_example` and configures an analyzer with a `german_normalization` filter: + +```json +PUT /german_normalizer_example +{ + "settings": { + "analysis": { + "filter": { + "german_normalizer": { + "type": "german_normalization" + } + }, + "analyzer": { + "german_normalizer_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "german_normalizer" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /german_normalizer_example/_analyze +{ + "text": "Straße München", + "analyzer": "german_normalizer_analyzer" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "strasse", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "munchen", + "start_offset": 7, + "end_offset": 14, + "type": "", + "position": 1 + } + ] +} +``` diff --git a/_analyzers/token-filters/pattern-capture.md b/_analyzers/token-filters/pattern-capture.md new file mode 100644 index 00000000..cff36b58 --- /dev/null +++ b/_analyzers/token-filters/pattern-capture.md @@ -0,0 +1,97 @@ +--- +layout: default +title: Pattern capture +parent: Token filters +nav_order: 310 +--- + +# Pattern capture token filter + +The `pattern_capture` token filter is a powerful filter that uses regular expressions to capture and extract parts of text according to specific patterns. This filter can be useful when you want to extract particular parts of tokens, such as email domains, hashtags, or numbers, and reuse them for further analysis or indexing. + +## Parameters + +The `pattern_capture` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`patterns` | Required | Array of strings | An array of regular expressions used to capture parts of text. +`preserve_original` | Required | Boolean| Whether to keep the original token in the output. Default is `true`. + + +## Example + +The following example request creates a new index named `email_index` and configures an analyzer with a `pattern_capture` filter to extract the local part and domain name from an email address: + +```json +PUT /email_index +{ + "settings": { + "analysis": { + "filter": { + "email_pattern_capture": { + "type": "pattern_capture", + "preserve_original": true, + "patterns": [ + "^([^@]+)", + "@(.+)$" + ] + } + }, + "analyzer": { + "email_analyzer": { + "tokenizer": "uax_url_email", + "filter": [ + "email_pattern_capture", + "lowercase" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /email_index/_analyze +{ + "text": "john.doe@example.com", + "analyzer": "email_analyzer" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "john.doe@example.com", + "start_offset": 0, + "end_offset": 20, + "type": "", + "position": 0 + }, + { + "token": "john.doe", + "start_offset": 0, + "end_offset": 20, + "type": "", + "position": 0 + }, + { + "token": "example.com", + "start_offset": 0, + "end_offset": 20, + "type": "", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/token-filters/pattern-replace.md b/_analyzers/token-filters/pattern-replace.md new file mode 100644 index 00000000..73ef7fa7 --- /dev/null +++ b/_analyzers/token-filters/pattern-replace.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Pattern replace +parent: Token filters +nav_order: 320 +--- + +# Pattern replace token filter + +The `pattern_replace` token filter allows you to modify tokens using regular expressions. This filter replaces patterns in tokens with the specified values, giving you flexibility in transforming or normalizing tokens before indexing them. It's particularly useful when you need to clean or standardize text during analysis. + +## Parameters + +The `pattern_replace` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`pattern` | Required | String | A regular expression pattern that matches the text that needs to be replaced. +`all` | Optional | Boolean | Whether to replace all pattern matches. If `false`, only the first match is replaced. Default is `true`. +`replacement` | Optional | String | A string with which to replace the matched pattern. Default is an empty string. + + +## Example + +The following example request creates a new index named `text_index` and configures an analyzer with a `pattern_replace` filter to replace tokens containing digits with the string `[NUM]`: + +```json +PUT /text_index +{ + "settings": { + "analysis": { + "filter": { + "number_replace_filter": { + "type": "pattern_replace", + "pattern": "\\d+", + "replacement": "[NUM]" + } + }, + "analyzer": { + "number_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "number_replace_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /text_index/_analyze +{ + "text": "Visit us at 98765 Example St.", + "analyzer": "number_analyzer" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "visit", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "us", + "start_offset": 6, + "end_offset": 8, + "type": "", + "position": 1 + }, + { + "token": "at", + "start_offset": 9, + "end_offset": 11, + "type": "", + "position": 2 + }, + { + "token": "[NUM]", + "start_offset": 12, + "end_offset": 17, + "type": "", + "position": 3 + }, + { + "token": "example", + "start_offset": 18, + "end_offset": 25, + "type": "", + "position": 4 + }, + { + "token": "st", + "start_offset": 26, + "end_offset": 28, + "type": "", + "position": 5 + } + ] +} +``` diff --git a/_analyzers/token-filters/phonetic.md b/_analyzers/token-filters/phonetic.md new file mode 100644 index 00000000..1188561e --- /dev/null +++ b/_analyzers/token-filters/phonetic.md @@ -0,0 +1,98 @@ +--- +layout: default +title: Phonetic +parent: Token filters +nav_order: 330 +--- + +# Phonetic token filter + +The `phonetic` token filter transforms tokens into their phonetic representations, enabling more flexible matching of words that sound similar but are spelled differently. This is particularly useful for searching names, brands, or other entities that users might spell differently but pronounce similarly. + +The `phonetic` token filter is not included in OpenSearch distributions by default. To use this token filter, you must first install the `analysis-phonetic` plugin as follows and then restart OpenSearch: + +```bash +./bin/opensearch-plugin install analysis-phonetic +``` +{% include copy.html %} + +For more information about installing plugins, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). +{: .note} + +## Parameters + +The `phonetic` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`encoder` | Optional | String | Specifies the phonetic algorithm to use.

Valid values are:
- `metaphone` (default)
- `double_metaphone`
- `soundex`
- `refined_soundex`
- `caverphone1`
- `caverphone2`
- `cologne`
- `nysiis`
- `koelnerphonetik`
- `haasephonetik`
- `beider_morse`
- `daitch_mokotoff ` +`replace` | Optional | Boolean | Whether to replace the original token. If `false`, the original token is included in the output along with the phonetic encoding. Default is `true`. + + +## Example + +The following example request creates a new index named `names_index` and configures an analyzer with a `phonetic` filter: + +```json +PUT /names_index +{ + "settings": { + "analysis": { + "filter": { + "my_phonetic_filter": { + "type": "phonetic", + "encoder": "double_metaphone", + "replace": true + } + }, + "analyzer": { + "phonetic_analyzer": { + "tokenizer": "standard", + "filter": [ + "my_phonetic_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated for the names `Stephen` and `Steven` using the analyzer: + +```json +POST /names_index/_analyze +{ + "text": "Stephen", + "analyzer": "phonetic_analyzer" +} +``` +{% include copy-curl.html %} + +```json +POST /names_index/_analyze +{ + "text": "Steven", + "analyzer": "phonetic_analyzer" +} +``` +{% include copy-curl.html %} + +In both cases, the response contains the same generated token: + +```json +{ + "tokens": [ + { + "token": "STFN", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + } + ] +} +``` diff --git a/_analyzers/token-filters/porter-stem.md b/_analyzers/token-filters/porter-stem.md new file mode 100644 index 00000000..fa2f4208 --- /dev/null +++ b/_analyzers/token-filters/porter-stem.md @@ -0,0 +1,83 @@ +--- +layout: default +title: Porter stem +parent: Token filters +nav_order: 340 +--- + +# Porter stem token filter + +The `porter_stem` token filter reduces words to their base (or _stem_) form and removes common suffixes from words, which helps in matching similar words by their root. For example, the word `running` is stemmed to `run`. This token filter is primarily used for the English language and provides stemming based on the [Porter stemming algorithm](https://snowballstem.org/algorithms/porter/stemmer.html). + + +## Example + +The following example request creates a new index named `my_stem_index` and configures an analyzer with a `porter_stem` filter: + +```json +PUT /my_stem_index +{ + "settings": { + "analysis": { + "filter": { + "my_porter_stem": { + "type": "porter_stem" + } + }, + "analyzer": { + "porter_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_porter_stem" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_stem_index/_analyze +{ + "text": "running runners ran", + "analyzer": "porter_analyzer" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "run", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "runner", + "start_offset": 8, + "end_offset": 15, + "type": "", + "position": 1 + }, + { + "token": "ran", + "start_offset": 16, + "end_offset": 19, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/predicate-token-filter.md b/_analyzers/token-filters/predicate-token-filter.md new file mode 100644 index 00000000..40f540c5 --- /dev/null +++ b/_analyzers/token-filters/predicate-token-filter.md @@ -0,0 +1,82 @@ +--- +layout: default +title: Predicate token filter +parent: Token filters +nav_order: 340 +--- + +# Predicate token filter + +The `predicate_token_filter` evaluates whether tokens should be kept or discarded, depending on the conditions defined in a custom script. The tokens are evaluated in the analysis predicate context. This filter supports only inline Painless scripts. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +## Parameters + +The `predicate_token_filter` has one required parameter: `script`. This parameter provides a condition that is used to evaluate whether the token should be kept. + +## Example + +The following example request creates a new index named `predicate_index` and configures an analyzer with a `predicate_token_filter`. The filter specifies to only output tokens if they are longer than 7 characters: + +```json +PUT /predicate_index +{ + "settings": { + "analysis": { + "filter": { + "my_predicate_filter": { + "type": "predicate_token_filter", + "script": { + "source": "token.term.length() > 7" + } + } + }, + "analyzer": { + "predicate_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_predicate_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /predicate_index/_analyze +{ + "text": "The OpenSearch community is growing rapidly", + "analyzer": "predicate_analyzer" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 4, + "end_offset": 14, + "type": "", + "position": 1 + }, + { + "token": "community", + "start_offset": 15, + "end_offset": 24, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/remove-duplicates.md b/_analyzers/token-filters/remove-duplicates.md new file mode 100644 index 00000000..b0a58988 --- /dev/null +++ b/_analyzers/token-filters/remove-duplicates.md @@ -0,0 +1,152 @@ +--- +layout: default +title: Remove duplicates +parent: Token filters +nav_order: 350 +--- + +# Remove duplicates token filter + +The `remove_duplicates` token filter is used to remove duplicate tokens that are generated in the same position during analysis. + +## Example + +The following example request creates an index with a `keyword_repeat` token filter. The filter adds a `keyword` version of each token in the same position as the token itself and then uses a `kstem` to create a stemmed version of the token: + +```json +PUT /example-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "keyword_repeat", + "kstem" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to analyze the string `Slower turtle`: + +```json +GET /example-index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Slower turtle" +} +``` +{% include copy-curl.html %} + +The response contains the token `turtle` twice in the same position: + +```json +{ + "tokens": [ + { + "token": "slower", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 7, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "turtle", + "start_offset": 7, + "end_offset": 13, + "type": "", + "position": 1 + } + ] +} +``` + +The duplicate token can be removed by adding a `remove_duplicates` token filter to the index settings: + +```json +PUT /index-remove-duplicate +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "keyword_repeat", + "kstem", + "remove_duplicates" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /index-remove-duplicate/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Slower turtle" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slower", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 7, + "end_offset": 13, + "type": "", + "position": 1 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/reverse.md b/_analyzers/token-filters/reverse.md new file mode 100644 index 00000000..dc48f07e --- /dev/null +++ b/_analyzers/token-filters/reverse.md @@ -0,0 +1,86 @@ +--- +layout: default +title: Reverse +parent: Token filters +nav_order: 360 +--- + +# Reverse token filter + +The `reverse` token filter reverses the order of the characters in each token, making suffix information accessible at the beginning of the reversed tokens during analysis. + +This is useful for suffix-based searches: + +The `reverse` token filter is useful when you need to perform suffix-based searches, such as in the following scenarios: + +- **Suffix matching**: Searching for words based on their suffixes, such as identifying words with a specific ending (for example, `-tion` or `-ing`). +- **File extension searches**: Searching for files by their extensions, such as `.txt` or `.jpg`. +- **Custom sorting or ranking**: By reversing tokens, you can implement unique sorting or ranking logic based on suffixes. +- **Autocomplete for suffixes**: Implementing autocomplete suggestions that use suffixes rather than prefixes. + + +## Example + +The following example request creates a new index named `my-reverse-index` and configures an analyzer with a `reverse` filter: + +```json +PUT /my-reverse-index +{ + "settings": { + "analysis": { + "filter": { + "reverse_filter": { + "type": "reverse" + } + }, + "analyzer": { + "my_reverse_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "reverse_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-reverse-index/_analyze +{ + "analyzer": "my_reverse_analyzer", + "text": "hello world" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "olleh", + "start_offset": 0, + "end_offset": 5, + "type": "", + "position": 0 + }, + { + "token": "dlrow", + "start_offset": 6, + "end_offset": 11, + "type": "", + "position": 1 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/shingle.md b/_analyzers/token-filters/shingle.md new file mode 100644 index 00000000..d5eec4c7 --- /dev/null +++ b/_analyzers/token-filters/shingle.md @@ -0,0 +1,123 @@ +--- +layout: default +title: Shingle +parent: Token filters +nav_order: 370 +--- + +# Shingle token filter + +The `shingle` token filter is used to generate word n-grams, or _shingles_, from input text. For example, for the string `slow green turtle`, the `shingle` filter creates the following one- and two-word shingles: `slow`, `slow green`, `green`, `green turtle`, and `turtle`. + +This token filter is often used in conjunction with other filters to enhance search accuracy by indexing phrases rather than individual tokens. For more information, see [Phrase suggester]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/#phrase-suggester). + +To accelerate phrase queries such as [`match_phrase`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/), set the [`index_phrases`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/index-phrases/) mapping parameter on the `text` field. OpenSearch then indexes two-word shingles in a separate subfield and uses them to run phrase queries, so you don't need a custom analyzer containing a `shingle` filter. +{: .tip} + +## Parameters + +The `shingle` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`min_shingle_size` | Optional | Integer | The minimum number of tokens to concatenate. Default is `2`. +`max_shingle_size` | Optional | Integer | The maximum number of tokens to concatenate. The difference between `max_shingle_size` and `min_shingle_size`, plus 1 if `output_unigrams` is `true`, cannot exceed the [`index.max_shingle_diff`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings) index setting (default `3`). With the default settings, `max_shingle_size` can therefore exceed `min_shingle_size` by at most 2. Default is `2`. +`output_unigrams` | Optional | Boolean | Whether to include unigrams (individual tokens) as output. Default is `true`. +`output_unigrams_if_no_shingles` | Optional | Boolean | Whether to output unigrams if no shingles are generated. Default is `false`. +`token_separator` | Optional | String | A separator used to concatenate tokens into a shingle. Default is a space (`" "`). +`filler_token` | Optional | String | A token inserted into empty positions or gaps between tokens. Gaps occur when a preceding filter, such as [`stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/), removes a token. The filler token appears only within shingles and is never emitted as a separate token. For example, if `on` is a stopword and `filler_token` is `+`, the text `tent on sale` produces the tokens `tent`, `tent +`, `+ sale`, and `sale`. Default is an underscore (`_`). + +If `output_unigrams` and `output_unigrams_if_no_shingles` are both set to `true`, `output_unigrams_if_no_shingles` is ignored. +{: .note} + +## Example + +The following example request creates a new index named `my-shingle-index` and configures an analyzer with a `shingle` filter: + +```json +PUT /my-shingle-index +{ + "settings": { + "analysis": { + "filter": { + "my_shingle_filter": { + "type": "shingle", + "min_shingle_size": 2, + "max_shingle_size": 2, + "output_unigrams": true + } + }, + "analyzer": { + "my_shingle_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_shingle_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-shingle-index/_analyze +{ + "analyzer": "my_shingle_analyzer", + "text": "slow green turtle" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slow", + "start_offset": 0, + "end_offset": 4, + "type": "", + "position": 0 + }, + { + "token": "slow green", + "start_offset": 0, + "end_offset": 10, + "type": "shingle", + "position": 0, + "positionLength": 2 + }, + { + "token": "green", + "start_offset": 5, + "end_offset": 10, + "type": "", + "position": 1 + }, + { + "token": "green turtle", + "start_offset": 5, + "end_offset": 17, + "type": "shingle", + "position": 1, + "positionLength": 2 + }, + { + "token": "turtle", + "start_offset": 11, + "end_offset": 17, + "type": "", + "position": 2 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/snowball.md b/_analyzers/token-filters/snowball.md new file mode 100644 index 00000000..149486e7 --- /dev/null +++ b/_analyzers/token-filters/snowball.md @@ -0,0 +1,108 @@ +--- +layout: default +title: Snowball +parent: Token filters +nav_order: 380 +--- + +# Snowball token filter + +The `snowball` token filter is a stemming filter based on the [Snowball](https://snowballstem.org/) algorithm. It supports many languages and is more efficient and accurate than the Porter stemming algorithm. + +## Parameters + +The `snowball` token filter can be configured with a `language` parameter that accepts the following values: + +- `Arabic` +- `Armenian` +- `Basque` +- `Catalan` +- `Danish` +- `Dutch` +- `English` (default) +- `Estonian` +- `Finnish` +- `French` +- `German` +- `German2` +- `Hungarian` +- `Italian` +- `Irish` +- `Kp` +- `Lithuanian` +- `Lovins` +- `Norwegian` +- `Porter` +- `Portuguese` +- `Romanian` +- `Russian` +- `Spanish` +- `Swedish` +- `Turkish` + +## Example + +The following example request creates a new index named `my-snowball-index` and configures an analyzer with a `snowball` filter: + +```json +PUT /my-snowball-index +{ + "settings": { + "analysis": { + "filter": { + "my_snowball_filter": { + "type": "snowball", + "language": "English" + } + }, + "analyzer": { + "my_snowball_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_snowball_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-snowball-index/_analyze +{ + "analyzer": "my_snowball_analyzer", + "text": "running runners" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "run", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "runner", + "start_offset": 8, + "end_offset": 15, + "type": "", + "position": 1 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/stemmer-override.md b/_analyzers/token-filters/stemmer-override.md new file mode 100644 index 00000000..c06f6737 --- /dev/null +++ b/_analyzers/token-filters/stemmer-override.md @@ -0,0 +1,139 @@ +--- +layout: default +title: Stemmer override +parent: Token filters +nav_order: 400 +--- + +# Stemmer override token filter + +The `stemmer_override` token filter allows you to define custom stemming rules that override the behavior of default stemmers like Porter or Snowball. This can be useful when you want to apply specific stemming behavior to certain words that might not be modified correctly by the standard stemming algorithms. + +## Parameters + +The `stemmer_override` token filter must be configured with exactly one of the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`rules` | String | Defines the override rules directly in the settings. +`rules_path` | String | Specifies the path to the file containing custom rules (mappings). The path can be either an absolute path or a path relative to the config directory. + +## Example + +The following example request creates a new index named `my-index` and configures an analyzer with a `stemmer_override` filter: + +```json +PUT /my-index +{ + "settings": { + "analysis": { + "filter": { + "my_stemmer_override_filter": { + "type": "stemmer_override", + "rules": [ + "running, runner => run", + "bought => buy", + "best => good" + ] + } + }, + "analyzer": { + "my_custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stemmer_override_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "I am a runner and bought the best shoes" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "i", + "start_offset": 0, + "end_offset": 1, + "type": "", + "position": 0 + }, + { + "token": "am", + "start_offset": 2, + "end_offset": 4, + "type": "", + "position": 1 + }, + { + "token": "a", + "start_offset": 5, + "end_offset": 6, + "type": "", + "position": 2 + }, + { + "token": "run", + "start_offset": 7, + "end_offset": 13, + "type": "", + "position": 3 + }, + { + "token": "and", + "start_offset": 14, + "end_offset": 17, + "type": "", + "position": 4 + }, + { + "token": "buy", + "start_offset": 18, + "end_offset": 24, + "type": "", + "position": 5 + }, + { + "token": "the", + "start_offset": 25, + "end_offset": 28, + "type": "", + "position": 6 + }, + { + "token": "good", + "start_offset": 29, + "end_offset": 33, + "type": "", + "position": 7 + }, + { + "token": "shoes", + "start_offset": 34, + "end_offset": 39, + "type": "", + "position": 8 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/stemmer.md b/_analyzers/token-filters/stemmer.md new file mode 100644 index 00000000..dd1344fc --- /dev/null +++ b/_analyzers/token-filters/stemmer.md @@ -0,0 +1,118 @@ +--- +layout: default +title: Stemmer +parent: Token filters +nav_order: 390 +--- + +# Stemmer token filter + +The `stemmer` token filter reduces words to their root or base form (also known as their _stem_). + +## Parameters + +The `stemmer` token filter can be configured with a `language` parameter that accepts the following values: + +- Arabic: `arabic` +- Armenian: `armenian` +- Basque: `basque` +- Bengali: `bengali` +- Brazilian Portuguese: `brazilian` +- Bulgarian: `bulgarian` +- Catalan: `catalan` +- Czech: `czech` +- Danish: `danish` +- Dutch: `dutch, dutch_kp` +- English: `english` (default), `light_english`, `lovins`, `minimal_english`, `porter2`, `possessive_english` +- Estonian: `estonian` +- Finnish: `finnish`, `light_finnish` +- French: `light_french`, `french`, `minimal_french` +- Galician: `galician`, `minimal_galician` (plural step only) +- German: `light_german`, `german`, `german2`, `minimal_german` +- Greek: `greek` +- Hindi: `hindi` +- Hungarian: `hungarian, light_hungarian` +- Indonesian: `indonesian` +- Irish: `irish` +- Italian: `light_italian, italian` +- Kurdish (Sorani): `sorani` +- Latvian: `latvian` +- Lithuanian: `lithuanian` +- Norwegian (Bokmål): `norwegian`, `light_norwegian`, `minimal_norwegian` +- Norwegian (Nynorsk): `light_nynorsk`, `minimal_nynorsk` +- Portuguese: `light_portuguese`, `minimal_portuguese`, `portuguese`, `portuguese_rslp` +- Romanian: `romanian` +- Russian: `russian`, `light_russian` +- Spanish: `light_spanish`, `spanish` +- Swedish: `swedish`, `light_swedish` +- Turkish: `turkish` + +You can also use the `name` parameter as an alias for the `language` parameter. If both are set, the `name` parameter is ignored. +{: .note} + +## Example + +The following example request creates a new index named `my-stemmer-index` and configures an analyzer with a `stemmer` filter: + +```json +PUT /my-stemmer-index +{ + "settings": { + "analysis": { + "filter": { + "my_english_stemmer": { + "type": "stemmer", + "language": "english" + } + }, + "analyzer": { + "my_stemmer_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_english_stemmer" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-stemmer-index/_analyze +{ + "analyzer": "my_stemmer_analyzer", + "text": "running runs" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "run", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "run", + "start_offset": 8, + "end_offset": 12, + "type": "", + "position": 1 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/token-filters/stop.md b/_analyzers/token-filters/stop.md new file mode 100644 index 00000000..25f4adac --- /dev/null +++ b/_analyzers/token-filters/stop.md @@ -0,0 +1,155 @@ +--- +layout: default +title: Stop +parent: Token filters +nav_order: 410 +--- + +# Stop token filter + +The `stop` token filter is used to remove common words (also known as _stopwords_) from a token stream during analysis. Stopwords are typically articles and prepositions, such as `a` or `for`. These words are not significantly meaningful in search queries and are often excluded to improve search efficiency and relevance. + +The default list of English stopwords includes the following words: `a`, `an`, `and`, `are`, `as`, `at`, `be`, `but`, `by`, `for`, `if`, `in`, `into`, `is`, `it`, `no`, `not`, `of`, `on`, `or`, `such`, `that`, `the`, `their`, `then`, `there`, `these`, `they`, `this`, `to`, `was`, `will`, and `with`. + +## Parameters + +The `stop` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`stopwords` | Optional | String | Specifies either a custom array of stopwords or a [predefined stopword set for a language](#predefined-stopword-sets-by-language). Default is `_english_`. +`stopwords_path` | Optional | String | Specifies the file path (absolute or relative to the config directory) of the file containing custom stopwords. +`ignore_case` | Optional | Boolean | If `true`, stopwords will be matched regardless of their case. Default is `false`. +`remove_trailing` | Optional | Boolean | If `true`, a stopword at the end of the input is removed like any other stopword. If `false`, the last token is kept if it is a stopword that is not followed by a space or other separator, while all other stopwords are removed. Set to `false` when using the filter in a [completion suggester]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/#completion-suggester) analyzer. For more information, see [Using the stop filter with completion suggesters](#using-the-stop-filter-with-completion-suggesters). Default is `true`. + +## Example + +The following example request creates a new index named `my-stopword-index` and configures an analyzer with a `stop` filter that uses the predefined stopword list for the English language: + +```json +PUT /my-stopword-index +{ + "settings": { + "analysis": { + "filter": { + "my_stop_filter": { + "type": "stop", + "stopwords": "_english_" + } + }, + "analyzer": { + "my_stop_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stop_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-stopword-index/_analyze +{ + "analyzer": "my_stop_analyzer", + "text": "A quick dog jumps over the turtle" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "quick", + "start_offset": 2, + "end_offset": 7, + "type": "", + "position": 1 + }, + { + "token": "dog", + "start_offset": 8, + "end_offset": 11, + "type": "", + "position": 2 + }, + { + "token": "jumps", + "start_offset": 12, + "end_offset": 17, + "type": "", + "position": 3 + }, + { + "token": "over", + "start_offset": 18, + "end_offset": 22, + "type": "", + "position": 4 + }, + { + "token": "turtle", + "start_offset": 27, + "end_offset": 33, + "type": "", + "position": 6 + } + ] +} +``` + +## Using the stop filter with completion suggesters + +When a user types a search query, the last word is often incomplete and can match a stopword. For example, when a user types `red on`, the `on` might be the beginning of `onion`. If the analyzer for a `completion` field removes `on`, OpenSearch searches for the prefix `red` and suggests `red cabbage`, `red onion`, and `red pepper`. If you set `remove_trailing` to `false`, the `stop` filter keeps the final `on`, so the same prefix suggests only `red onion`. After the user types a space following `on`, the filter treats `on` as a complete word and removes it. + +## Predefined stopword sets by language + +The following is a list of all available predefined stopword sets by language: + +- [`_arabic_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ar/stopwords.txt) +- [`_armenian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/hy/stopwords.txt) +- [`_basque_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/eu/stopwords.txt) +- [`_bengali_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/bn/stopwords.txt) +- [`_brazilian_` (Brazilian Portuguese)](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/br/stopwords.txt) +- [`_bulgarian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/bg/stopwords.txt) +- [`_catalan_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ca/stopwords.txt) +- [`_cjk_` (Chinese, Japanese, and Korean)](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/cjk/stopwords.txt) +- [`_czech_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/cz/stopwords.txt) +- [`_danish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/danish_stop.txt) +- [`_dutch_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/dutch_stop.txt) +- [`_english_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/java/org/apache/lucene/analysis/en/EnglishAnalyzer.java#L48) +- [`_estonian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/et/stopwords.txt) +- [`_finnish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/finnish_stop.txt) +- [`_french_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/french_stop.txt) +- [`_galician_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/gl/stopwords.txt) +- [`_german_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/german_stop.txt) +- [`_greek_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/el/stopwords.txt) +- [`_hindi_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/hi/stopwords.txt) +- [`_hungarian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/hungarian_stop.txt) +- [`_indonesian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/id/stopwords.txt) +- [`_irish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/irish_stop.txt) +- [`_italian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/italian_stop.txt) +- [`_latvian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/lv/stopwords.txt) +- [`_lithuanian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/lt/stopwords.txt) +- [`_norwegian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/norwegian_stop.txt) +- [`_persian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/fa/stopwords.txt) +- [`_portuguese_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/portuguese_stop.txt) +- [`_romanian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ro/stopwords.txt) +- [`_russian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/russian_stop.txt) +- [`_sorani_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ckb/stopwords.txt) +- [`_spanish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/spanish_stop.txt) +- [`_swedish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/swedish_stop.txt) +- [`_thai_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/th/stopwords.txt) +- [`_turkish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/tr/stopwords.txt) \ No newline at end of file diff --git a/_analyzers/token-filters/synonym-graph.md b/_analyzers/token-filters/synonym-graph.md new file mode 100644 index 00000000..a744cdf2 --- /dev/null +++ b/_analyzers/token-filters/synonym-graph.md @@ -0,0 +1,279 @@ +--- +layout: default +title: Synonym graph +parent: Token filters +nav_order: 420 +--- + +# Synonym graph token filter + +The `synonym_graph` token filter is a more advanced version of the `synonym` token filter. It supports multiword synonyms and processes synonyms across multiple tokens, making it ideal for phrases or scenarios in which relationships between tokens are important. + +Use the `synonym_graph` filter only in a [search analyzer]({{site.url}}{{site.baseurl}}/analyzers/search-analyzers/#specifying-a-search-analyzer-in-the-mappings). At index time, OpenSearch ignores the `positionLength` of each token, so a multiword synonym shifts the positions of the tokens that follow it. For example, if an index analyzer maps `ev` to `electric car`, then `charger` in the text `ev charger` is indexed at position 2, and a `match_phrase` query for `ev charger` no longer matches the document. To apply synonyms at index time, use the [`synonym`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym/) token filter. +{: .note} + +## Parameters + +The `synonym_graph` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`synonyms` | Either `synonyms` or `synonyms_path` must be specified | String | A list of synonym rules defined directly in the configuration. +`synonyms_path` | Either `synonyms` or `synonyms_path` must be specified | String | The file path to a file containing synonym rules (either an absolute path or a path relative to the config directory). +`lenient` | Optional | Boolean | Whether to ignore exceptions when loading the rule configurations. If `true`, OpenSearch skips the synonym terms that cannot be parsed and keeps the rest of the rule. For more information, see [Synonym rules containing stop words](#synonym-rules-containing-stop-words). Default is `false`. +`format` | Optional | String | Specifies the format used to determine how OpenSearch defines and interprets synonyms. Valid values are:
- `solr`
- [`wordnet`](https://wordnet.princeton.edu/).
Default is `solr`. +`expand` | Optional | Boolean | Whether to expand equivalent synonym rules. Default is `true`.

For example:
If `synonyms` are defined as `"quick, fast"` and `expand` is set to `true`, then the synonym rules are configured as follows:
- `quick => quick`
- `quick => fast`
- `fast => quick`
- `fast => fast`

If `expand` is set to `false`, the synonym rules are configured as follows:
- `quick => quick`
- `fast => quick` +`synonym_analyzer` | Optional | String | The name of the analyzer that parses the synonym rules. Specify any analyzer available to the index: a built-in analyzer (such as `standard`, `simple`, `stop`, `whitespace`, or `keyword`), a language analyzer, an analyzer registered by a plugin, or a custom analyzer defined in the same index. If the named analyzer cannot be resolved, OpenSearch parses the rules using the analysis chain in which this filter is defined and returns no error. By default, the analysis chain is used. For more information, see [Parsing synonym rules](#parsing-synonym-rules). + +## Example: Solr format + +The following example request creates a new index named `my-index` and configures an analyzer with a `synonym_graph` filter. The filter is configured with the default `solr` rule format: + +```json +PUT /my-index +{ + "settings": { + "analysis": { + "filter": { + "my_synonym_graph_filter": { + "type": "synonym_graph", + "synonyms": [ + "sports car, race car", + "fast car, speedy vehicle", + "luxury car, premium vehicle", + "electric car, EV" + ] + } + }, + "analyzer": { + "my_synonym_graph_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_synonym_graph_filter" + ] + } + } + } + } +} + +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-index/_analyze +{ + "analyzer": "my_synonym_graph_analyzer", + "text": "I just bought a sports car and it is a fast car." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "i","start_offset": 0,"end_offset": 1,"type": "","position": 0}, + {"token": "just","start_offset": 2,"end_offset": 6,"type": "","position": 1}, + {"token": "bought","start_offset": 7,"end_offset": 13,"type": "","position": 2}, + {"token": "a","start_offset": 14,"end_offset": 15,"type": "","position": 3}, + {"token": "race","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4}, + {"token": "sports","start_offset": 16,"end_offset": 22,"type": "","position": 4,"positionLength": 2}, + {"token": "car","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 5,"positionLength": 2}, + {"token": "car","start_offset": 23,"end_offset": 26,"type": "","position": 6}, + {"token": "and","start_offset": 27,"end_offset": 30,"type": "","position": 7}, + {"token": "it","start_offset": 31,"end_offset": 33,"type": "","position": 8}, + {"token": "is","start_offset": 34,"end_offset": 36,"type": "","position": 9}, + {"token": "a","start_offset": 37,"end_offset": 38,"type": "","position": 10}, + {"token": "speedy","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 11}, + {"token": "fast","start_offset": 39,"end_offset": 43,"type": "","position": 11,"positionLength": 2}, + {"token": "vehicle","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 12,"positionLength": 2}, + {"token": "car","start_offset": 44,"end_offset": 47,"type": "","position": 13} + ] +} +``` + +## Example: WordNet format + +The following example request creates a new index named `my-wordnet-index` and configures an analyzer with a `synonym_graph` filter. The filter is configured with the [`wordnet`](https://wordnet.princeton.edu/) rule format: + +```json +PUT /my-wordnet-index +{ + "settings": { + "analysis": { + "filter": { + "my_synonym_graph_filter": { + "type": "synonym_graph", + "format": "wordnet", + "synonyms": [ + "s(100000001, 1, 'sports car', n, 1, 0).", + "s(100000001, 2, 'race car', n, 1, 0).", + "s(100000001, 3, 'fast car', n, 1, 0).", + "s(100000001, 4, 'speedy vehicle', n, 1, 0)." + ] + } + }, + "analyzer": { + "my_synonym_graph_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_synonym_graph_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-wordnet-index/_analyze +{ + "analyzer": "my_synonym_graph_analyzer", + "text": "I just bought a sports car and it is a fast car." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "i","start_offset": 0,"end_offset": 1,"type": "","position": 0}, + {"token": "just","start_offset": 2,"end_offset": 6,"type": "","position": 1}, + {"token": "bought","start_offset": 7,"end_offset": 13,"type": "","position": 2}, + {"token": "a","start_offset": 14,"end_offset": 15,"type": "","position": 3}, + {"token": "race","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4}, + {"token": "fast","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4,"positionLength": 2}, + {"token": "speedy","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4,"positionLength": 3}, + {"token": "sports","start_offset": 16,"end_offset": 22,"type": "","position": 4,"positionLength": 4}, + {"token": "car","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 5,"positionLength": 4}, + {"token": "car","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 6,"positionLength": 3}, + {"token": "vehicle","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 7,"positionLength": 2}, + {"token": "car","start_offset": 23,"end_offset": 26,"type": "","position": 8}, + {"token": "and","start_offset": 27,"end_offset": 30,"type": "","position": 9}, + {"token": "it","start_offset": 31,"end_offset": 33,"type": "","position": 10}, + {"token": "is","start_offset": 34,"end_offset": 36,"type": "","position": 11}, + {"token": "a","start_offset": 37,"end_offset": 38,"type": "","position": 12}, + {"token": "sports","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 13}, + {"token": "race","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 13,"positionLength": 2}, + {"token": "speedy","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 13,"positionLength": 3}, + {"token": "fast","start_offset": 39,"end_offset": 43,"type": "","position": 13,"positionLength": 4}, + {"token": "car","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 14,"positionLength": 4}, + {"token": "car","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 15,"positionLength": 3}, + {"token": "vehicle","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 16,"positionLength": 2}, + {"token": "car","start_offset": 44,"end_offset": 47,"type": "","position": 17} + ] +} +``` + +## Parsing synonym rules + +Unless you specify a `synonym_analyzer`, OpenSearch parses synonym rules using the tokenizer and the token filters that precede `synonym_graph` in the analyzer. This applies the same processing to the rules as to the text. For example, if the `porter_stem` filter precedes `synonym_graph`, the rule `running shoes, trainers` is stored as `run shoe, trainer`. The rule then matches both `running shoes` and `run shoe`. + +A synonym rule can contain only one token at each position, so token filters that produce several tokens at the same position are handled as follows when they precede `synonym_graph`: + +- Some filters produce only one version of each token when parsing rules. For example, the [`asciifolding`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/asciifolding/) filter with `preserve_original` set to `true` produces only the folded token. Given the rule `café, coffee shop`, the text `coffee shop` produces the synonym `cafe`, not `café`. +- The [`word_delimiter_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter-graph/), [`ngram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ngram/), [`edge_ngram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/edge-ngram/), [`shingle`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/shingle/), and [`multiplexer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/multiplexer/) filters cannot parse synonym rules. If one of them precedes `synonym_graph`, OpenSearch rejects the request to create the index. + +To use one of these filters in the same analyzer as `synonym_graph`, set `synonym_analyzer` to an analyzer that does not contain the filter. OpenSearch then parses the rules using that analyzer and applies the filter only to the text. + +## Synonym rules containing stop words + +If a [`stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/) filter precedes `synonym_graph`, it also removes stop words from the synonym rules. By default, OpenSearch rejects the request to create the index if a term in a rule contains a stop word. If you set `lenient` to `true`, OpenSearch skips each term that contains a stop word and keeps the rest of the rule. + +The following example request creates an index containing a `stop` filter that removes `the` and a `synonym_graph` filter whose rule contains the term `the flask`: + +```json +PUT /drinkware +{ + "settings": { + "analysis": { + "filter": { + "my_stop_filter": { + "type": "stop", + "stopwords": ["the"] + }, + "my_synonym_graph_filter": { + "type": "synonym_graph", + "lenient": true, + "synonyms": ["flask, the flask, thermos"] + } + }, + "analyzer": { + "my_synonym_graph_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stop_filter", + "my_synonym_graph_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +OpenSearch skips `the flask` and keeps `flask` and `thermos` as synonyms. Use the following request to analyze the text `thermos`: + +```json +GET /drinkware/_analyze +{ + "analyzer": "my_synonym_graph_analyzer", + "text": "thermos" +} +``` +{% include copy-curl.html %} + +The response contains the synonym `flask`: + +```json +{ + "tokens": [ + { + "token": "flask", + "start_offset": 0, + "end_offset": 7, + "type": "SYNONYM", + "position": 0 + }, + { + "token": "thermos", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + } + ] +} +``` + +If the skipped term is the one that other terms map to, the rule adds no synonyms. The following table shows how OpenSearch handles other rules when `lenient` is `true` and `the` is a stop word. + +Rule | `expand` | Result +:--- | :--- | :--- +`flask, thermos => the flask` | `true` | No synonyms are added because the replacement term contains a stop word. +`the flask, flask, thermos` | `false` | No synonyms are added because, when `expand` is `false`, all terms map to the first term, which contains a stop word. +`flask, the flask, thermos` | `false` | `thermos` maps to `flask`. + +If a `stop` filter follows `synonym_graph`, the stop words are removed from the synonym graph after synonym matching, which breaks the graph. For example, given the rule `thermos, the flask` and a `stop` filter that follows `synonym_graph`, a `match` query for `the flask` searches only for `thermos` and does not match documents containing `flask`. Remove such words from the synonym rules, or place the `stop` filter before `synonym_graph`. +{: .warning} diff --git a/_analyzers/token-filters/synonym.md b/_analyzers/token-filters/synonym.md new file mode 100644 index 00000000..aabcdca1 --- /dev/null +++ b/_analyzers/token-filters/synonym.md @@ -0,0 +1,370 @@ +--- +layout: default +title: Synonym +parent: Token filters +nav_order: 415 +--- + +# Synonym token filter + +The `synonym` token filter allows you to map multiple terms to a single term or create equivalence groups between words, improving search flexibility. + +## Parameters + +The `synonym` token filter can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`synonyms` | Either `synonyms` or `synonyms_path` must be specified | String | A list of synonym rules defined directly in the configuration. +`synonyms_path` | Either `synonyms` or `synonyms_path` must be specified | String | The file path to a file containing synonym rules (either an absolute path or a path relative to the config directory). +`lenient` | Optional | Boolean | Whether to ignore exceptions when loading the rule configurations. If `true`, OpenSearch skips the synonym terms that cannot be parsed and keeps the rest of the rule. For more information, see [Synonym rules containing stop words](#synonym-rules-containing-stop-words). Default is `false`. +`format` | Optional | String | Specifies the format used to determine how OpenSearch defines and interprets synonyms. Valid values are:
- `solr`
- [`wordnet`](https://wordnet.princeton.edu/).
Default is `solr`. +`expand` | Optional | Boolean | Whether to expand equivalent synonym rules. Default is `true`.

For example:
If `synonyms` are defined as `"quick, fast"` and `expand` is set to `true`, then the synonym rules are configured as follows:
- `quick => quick`
- `quick => fast`
- `fast => quick`
- `fast => fast`

If `expand` is set to `false`, the synonym rules are configured as follows:
- `quick => quick`
- `fast => quick` +`synonym_analyzer` | Optional | String | The name of the analyzer that parses the synonym rules. Specify any analyzer available to the index: a built-in analyzer (such as `standard`, `simple`, `stop`, `whitespace`, or `keyword`), a language analyzer, an analyzer registered by a plugin, or a custom analyzer defined in the same index. If the named analyzer cannot be resolved, OpenSearch parses the rules using the analysis chain in which this filter is defined and returns no error. By default, the analysis chain is used. For more information, see [Parsing synonym rules](#parsing-synonym-rules). + +## Example: Solr format + +The following example request creates a new index named `my-synonym-index` and configures an analyzer with a `synonym` filter. The filter is configured with the default `solr` rule format: + +```json +PUT /my-synonym-index +{ + "settings": { + "analysis": { + "filter": { + "my_synonym_filter": { + "type": "synonym", + "synonyms": [ + "car, automobile", + "quick, fast, speedy", + "laptop => computer" + ] + } + }, + "analyzer": { + "my_synonym_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_synonym_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-synonym-index/_analyze +{ + "analyzer": "my_synonym_analyzer", + "text": "The quick dog jumps into the car with a laptop" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "the", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "quick", + "start_offset": 4, + "end_offset": 9, + "type": "", + "position": 1 + }, + { + "token": "fast", + "start_offset": 4, + "end_offset": 9, + "type": "SYNONYM", + "position": 1 + }, + { + "token": "speedy", + "start_offset": 4, + "end_offset": 9, + "type": "SYNONYM", + "position": 1 + }, + { + "token": "dog", + "start_offset": 10, + "end_offset": 13, + "type": "", + "position": 2 + }, + { + "token": "jumps", + "start_offset": 14, + "end_offset": 19, + "type": "", + "position": 3 + }, + { + "token": "into", + "start_offset": 20, + "end_offset": 24, + "type": "", + "position": 4 + }, + { + "token": "the", + "start_offset": 25, + "end_offset": 28, + "type": "", + "position": 5 + }, + { + "token": "car", + "start_offset": 29, + "end_offset": 32, + "type": "", + "position": 6 + }, + { + "token": "automobile", + "start_offset": 29, + "end_offset": 32, + "type": "SYNONYM", + "position": 6 + }, + { + "token": "with", + "start_offset": 33, + "end_offset": 37, + "type": "", + "position": 7 + }, + { + "token": "a", + "start_offset": 38, + "end_offset": 39, + "type": "", + "position": 8 + }, + { + "token": "computer", + "start_offset": 40, + "end_offset": 46, + "type": "SYNONYM", + "position": 9 + } + ] +} +``` + +## Example: WordNet format + +The following example request creates a new index named `my-wordnet-index` and configures an analyzer with a `synonym` filter. The filter is configured with the [`wordnet`](https://wordnet.princeton.edu/) rule format: + +```json +PUT /my-wordnet-index +{ + "settings": { + "analysis": { + "filter": { + "my_wordnet_synonym_filter": { + "type": "synonym", + "format": "wordnet", + "synonyms": [ + "s(100000001,1,'fast',v,1,0).", + "s(100000001,2,'quick',v,1,0).", + "s(100000001,3,'swift',v,1,0)." + ] + } + }, + "analyzer": { + "my_wordnet_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_wordnet_synonym_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-wordnet-index/_analyze +{ + "analyzer": "my_wordnet_analyzer", + "text": "I have a fast car" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "i", + "start_offset": 0, + "end_offset": 1, + "type": "", + "position": 0 + }, + { + "token": "have", + "start_offset": 2, + "end_offset": 6, + "type": "", + "position": 1 + }, + { + "token": "a", + "start_offset": 7, + "end_offset": 8, + "type": "", + "position": 2 + }, + { + "token": "fast", + "start_offset": 9, + "end_offset": 13, + "type": "", + "position": 3 + }, + { + "token": "quick", + "start_offset": 9, + "end_offset": 13, + "type": "SYNONYM", + "position": 3 + }, + { + "token": "swift", + "start_offset": 9, + "end_offset": 13, + "type": "SYNONYM", + "position": 3 + }, + { + "token": "car", + "start_offset": 14, + "end_offset": 17, + "type": "", + "position": 4 + } + ] +} +``` + +## Parsing synonym rules + +Unless you specify a `synonym_analyzer`, OpenSearch parses synonym rules using the tokenizer and the token filters that precede `synonym` in the analyzer. This applies the same processing to the rules as to the text. For example, if the `porter_stem` filter precedes `synonym`, the rule `running shoes, trainers` is stored as `run shoe, trainer`. The rule then matches both `running shoes` and `run shoe`. + +A synonym rule can contain only one token at each position, so token filters that produce several tokens at the same position are handled as follows when they precede `synonym`: + +- Some filters produce only one version of each token when parsing rules. For example, the [`asciifolding`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/asciifolding/) filter with `preserve_original` set to `true` produces only the folded token. Given the rule `café, coffee shop`, the text `coffee shop` produces the synonym `cafe`, not `café`. +- The [`word_delimiter`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter/), [`word_delimiter_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter-graph/), [`ngram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/ngram/), [`edge_ngram`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/edge-ngram/), [`shingle`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/shingle/), and [`multiplexer`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/multiplexer/) filters cannot parse synonym rules. If one of them precedes `synonym`, OpenSearch rejects the request to create the index. + +To use one of these filters in the same analyzer as `synonym`, set `synonym_analyzer` to an analyzer that does not contain the filter. OpenSearch then parses the rules using that analyzer and applies the filter only to the text. + +## Synonym rules containing stop words + +If a [`stop`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/stop/) filter precedes `synonym`, it also removes stop words from the synonym rules. By default, OpenSearch rejects the request to create the index if a term in a rule contains a stop word. If you set `lenient` to `true`, OpenSearch skips each term that contains a stop word and keeps the rest of the rule. + +The following example request creates an index containing a `stop` filter that removes `the` and a `synonym` filter whose rule contains the term `the flask`: + +```json +PUT /kitchenware +{ + "settings": { + "analysis": { + "filter": { + "my_stop_filter": { + "type": "stop", + "stopwords": ["the"] + }, + "my_synonym_filter": { + "type": "synonym", + "lenient": true, + "synonyms": ["flask, the flask, thermos"] + } + }, + "analyzer": { + "my_synonym_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stop_filter", + "my_synonym_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +OpenSearch skips `the flask` and keeps `flask` and `thermos` as synonyms. Use the following request to analyze the text `thermos`: + +```json +GET /kitchenware/_analyze +{ + "analyzer": "my_synonym_analyzer", + "text": "thermos" +} +``` +{% include copy-curl.html %} + +The response contains the synonym `flask`: + +```json +{ + "tokens": [ + { + "token": "thermos", + "start_offset": 0, + "end_offset": 7, + "type": "", + "position": 0 + }, + { + "token": "flask", + "start_offset": 0, + "end_offset": 7, + "type": "SYNONYM", + "position": 0 + } + ] +} +``` + +If the skipped term is the one that other terms map to, the rule adds no synonyms. The following table shows how OpenSearch handles other rules when `lenient` is `true` and `the` is a stop word. + +Rule | `expand` | Result +:--- | :--- | :--- +`flask, thermos => the flask` | `true` | No synonyms are added because the replacement term contains a stop word. +`the flask, flask, thermos` | `false` | No synonyms are added because, when `expand` is `false`, all terms map to the first term, which contains a stop word. +`flask, the flask, thermos` | `false` | `thermos` maps to `flask`. diff --git a/_analyzers/token-filters/trim.md b/_analyzers/token-filters/trim.md new file mode 100644 index 00000000..cdfebed5 --- /dev/null +++ b/_analyzers/token-filters/trim.md @@ -0,0 +1,93 @@ +--- +layout: default +title: Trim +parent: Token filters +nav_order: 430 +--- + +# Trim token filter + +The `trim` token filter removes leading and trailing white space characters from tokens. + +Many popular tokenizers, such as `standard`, `keyword`, and `whitespace` tokenizers, automatically strip leading and trailing white space characters during tokenization. When using these tokenizers, there is no need to configure an additional `trim` token filter. +{: .note} + + +## Example + +The following example request creates a new index named `my_pattern_trim_index` and configures an analyzer with a `trim` filter and a `pattern` tokenizer, which does not remove leading and trailing white space characters: + +```json +PUT /my_pattern_trim_index +{ + "settings": { + "analysis": { + "filter": { + "my_trim_filter": { + "type": "trim" + } + }, + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "," + } + }, + "analyzer": { + "my_pattern_trim_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer", + "filter": [ + "lowercase", + "my_trim_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my_pattern_trim_index/_analyze +{ + "analyzer": "my_pattern_trim_analyzer", + "text": " OpenSearch , is , powerful " +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 12, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 13, + "end_offset": 18, + "type": "word", + "position": 1 + }, + { + "token": "powerful", + "start_offset": 19, + "end_offset": 32, + "type": "word", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/truncate.md b/_analyzers/token-filters/truncate.md new file mode 100644 index 00000000..16d14529 --- /dev/null +++ b/_analyzers/token-filters/truncate.md @@ -0,0 +1,107 @@ +--- +layout: default +title: Truncate +parent: Token filters +nav_order: 440 +--- + +# Truncate token filter + +The `truncate` token filter is used to shorten tokens exceeding a specified length. It trims tokens to a maximum number of characters, ensuring that tokens exceeding this limit are truncated. + +## Parameters + +The `truncate` token filter can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`length` | Optional | Integer | Specifies the maximum length of the generated token. Default is `10`. + +## Example + +The following example request creates a new index named `truncate_example` and configures an analyzer with a `truncate` filter: + +```json +PUT /truncate_example +{ + "settings": { + "analysis": { + "filter": { + "truncate_filter": { + "type": "truncate", + "length": 5 + } + }, + "analyzer": { + "truncate_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "truncate_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /truncate_example/_analyze +{ + "analyzer": "truncate_analyzer", + "text": "OpenSearch is powerful and scalable" +} + +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opens", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "power", + "start_offset": 14, + "end_offset": 22, + "type": "", + "position": 2 + }, + { + "token": "and", + "start_offset": 23, + "end_offset": 26, + "type": "", + "position": 3 + }, + { + "token": "scala", + "start_offset": 27, + "end_offset": 35, + "type": "", + "position": 4 + } + ] +} +``` diff --git a/_analyzers/token-filters/unique.md b/_analyzers/token-filters/unique.md new file mode 100644 index 00000000..c4dfcbab --- /dev/null +++ b/_analyzers/token-filters/unique.md @@ -0,0 +1,106 @@ +--- +layout: default +title: Unique +parent: Token filters +nav_order: 450 +--- + +# Unique token filter + +The `unique` token filter ensures that only unique tokens are kept during the analysis process, removing duplicate tokens that appear within a single field or text block. + +## Parameters + +The `unique` token filter can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`only_on_same_position` | Optional | Boolean | If `true`, the token filter acts as a `remove_duplicates` token filter and only removes tokens that are in the same position. Default is `false`. + +## Example + +The following example request creates a new index named `unique_example` and configures an analyzer with a `unique` filter: + +```json +PUT /unique_example +{ + "settings": { + "analysis": { + "filter": { + "unique_filter": { + "type": "unique", + "only_on_same_position": false + } + }, + "analyzer": { + "unique_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "unique_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /unique_example/_analyze +{ + "analyzer": "unique_analyzer", + "text": "OpenSearch OpenSearch is powerful powerful and scalable" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "is", + "start_offset": 22, + "end_offset": 24, + "type": "", + "position": 1 + }, + { + "token": "powerful", + "start_offset": 25, + "end_offset": 33, + "type": "", + "position": 2 + }, + { + "token": "and", + "start_offset": 43, + "end_offset": 46, + "type": "", + "position": 3 + }, + { + "token": "scalable", + "start_offset": 47, + "end_offset": 55, + "type": "", + "position": 4 + } + ] +} +``` diff --git a/_analyzers/token-filters/uppercase.md b/_analyzers/token-filters/uppercase.md new file mode 100644 index 00000000..50268924 --- /dev/null +++ b/_analyzers/token-filters/uppercase.md @@ -0,0 +1,83 @@ +--- +layout: default +title: Uppercase +parent: Token filters +nav_order: 460 +--- + +# Uppercase token filter + +The `uppercase` token filter is used to convert all tokens (words) to uppercase during analysis. + +## Example + +The following example request creates a new index named `uppercase_example` and configures an analyzer with an `uppercase` filter: + +```json +PUT /uppercase_example +{ + "settings": { + "analysis": { + "filter": { + "uppercase_filter": { + "type": "uppercase" + } + }, + "analyzer": { + "uppercase_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "uppercase_filter" + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /uppercase_example/_analyze +{ + "analyzer": "uppercase_analyzer", + "text": "OpenSearch is powerful" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OPENSEARCH", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "IS", + "start_offset": 11, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "POWERFUL", + "start_offset": 14, + "end_offset": 22, + "type": "", + "position": 2 + } + ] +} +``` diff --git a/_analyzers/token-filters/word-delimiter-graph.md b/_analyzers/token-filters/word-delimiter-graph.md new file mode 100644 index 00000000..b901f5a0 --- /dev/null +++ b/_analyzers/token-filters/word-delimiter-graph.md @@ -0,0 +1,164 @@ +--- +layout: default +title: Word delimiter graph +parent: Token filters +nav_order: 480 +--- + +# Word delimiter graph token filter + +The `word_delimiter_graph` token filter is used to splits token on predefined characters and also offers optional token normalization based on customizable rules. + +The `word_delimiter_graph` filter is used to remove punctuation from complex identifiers like part numbers or product IDs. In such cases, it is best used with the `keyword` tokenizer. For hyphenated words, use the `synonym_graph` token filter instead of the `word_delimiter_graph` filter because users frequently search for these terms both with and without hyphens. +{: .note} + +By default, the filter applies the following rules. + +| Description | Input | Output | +|:---|:---|:---| +| Treats non-alphanumeric characters as delimiters. | `ultra-fast` | `ultra`, `fast` | +| Removes delimiters at the beginning or end of tokens. | `Z99++'Decoder'`| `Z99`, `Decoder` | +| Splits tokens when there is a transition between uppercase and lowercase letters. | `OpenSearch` | `Open`, `Search` | +| Splits tokens when there is a transition between letters and numbers. | `T1000` | `T`, `1000` | +| Removes the possessive ('s) from the end of tokens. | `John's` | `John` | + +It's important **not** to use tokenizers that strip punctuation, like the `standard` tokenizer, with this filter. Doing so may prevent proper token splitting and interfere with options like `catenate_all` or `preserve_original`. We recommend using this filter with a `keyword` or `whitespace` tokenizer. +{: .important} + +## Parameters + +You can configure the `word_delimiter_graph` token filter using the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`adjust_offsets` | Optional | Boolean | Determines whether the token offsets should be recalculated for split or concatenated tokens. When `true`, the filter adjusts the token offsets to accurately represent the token's position within the token stream. This adjustment ensures that the token's location in the text aligns with its modified form after processing, which is particularly useful for applications like highlighting or phrase queries. When `false`, the offsets remain unchanged, which may result in misalignment when the processed tokens are mapped back to their positions in the original text. If your analyzer uses filters like `trim` that change the token lengths without changing their offsets, we recommend setting this parameter to `false`. Default is `true`. +`catenate_all` | Optional | Boolean | Produces concatenated tokens from a sequence of alphanumeric parts. For example, `"quick-fast-200"` becomes `[ quickfast200, quick, fast, 200 ]`. Default is `false`. +`catenate_numbers` | Optional | Boolean | Concatenates numerical sequences. For example, `"10-20-30"` becomes `[ 102030, 10, 20, 30 ]`. Default is `false`. +`catenate_words` | Optional | Boolean | Concatenates alphabetic words. For example, `"high-speed-level"` becomes `[ highspeedlevel, high, speed, level ]`. Default is `false`. +`generate_number_parts` | Optional | Boolean | If `true`, numeric tokens (tokens consisting of numbers only) are included in the output. Default is `true`. +`generate_word_parts` | Optional | Boolean | If `true`, alphabetical tokens (tokens consisting of alphabetic characters only) are included in the output. Default is `true`. +`ignore_keywords` | Optional | Boolean | Whether to process tokens marked as keywords. Default is `false`. +`preserve_original` | Optional | Boolean | Keeps the original token (which may include non-alphanumeric delimiters) alongside the generated tokens in the output. For example, `"auto-drive-300"` becomes `[ auto-drive-300, auto, drive, 300 ]`. If `true`, the filter generates multi-position tokens not supported by indexing, so do not use this filter in an index analyzer or use the `flatten_graph` filter after this filter. Default is `false`. +`protected_words` | Optional | Array of strings | Specifies tokens that should not be split. +`protected_words_path` | Optional | String | Specifies a path (absolute or relative to the config directory) to a file containing tokens that should not be separated by new lines. +`split_on_case_change` | Optional | Boolean | Splits tokens where consecutive letters have different cases (one is lowercase and the other is uppercase). For example, `"OpenSearch"` becomes `[ Open, Search ]`. Default is `true`. +`split_on_numerics` | Optional | Boolean | Splits tokens where there are consecutive letters and numbers. For example `"v8engine"` will become `[ v, 8, engine ]`. Default is `true`. +`stem_english_possessive` | Optional | Boolean | Removes English possessive endings, such as `'s`. Default is `true`. +`type_table` | Optional | Array of strings | A custom map that specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For example, to treat a hyphen (`-`) as an alphanumeric character, specify `["- => ALPHA"]` so that words are not split on hyphens. Valid types are:
- `ALPHA`: alphabetical
- `ALPHANUM`: alphanumeric
- `DIGIT`: numeric
- `LOWER`: lowercase alphabetical
- `SUBWORD_DELIM`: non-alphanumeric delimiter
- `UPPER`: uppercase alphabetical +`type_table_path` | Optional | String | Specifies a path (absolute or relative to the config directory) to a file containing a custom character map. The map specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For valid types, see `type_table`. + +## Example + +The following example request creates a new index named `my-custom-index` and configures an analyzer with a `word_delimiter_graph` filter: + +```json +PUT /my-custom-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "tokenizer": "keyword", + "filter": [ "custom_word_delimiter_filter" ] + } + }, + "filter": { + "custom_word_delimiter_filter": { + "type": "word_delimiter_graph", + "split_on_case_change": true, + "split_on_numerics": true, + "stem_english_possessive": true + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-custom-index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "FastCar's Model2023" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Fast", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "Car", + "start_offset": 4, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "Model", + "start_offset": 10, + "end_offset": 15, + "type": "word", + "position": 2 + }, + { + "token": "2023", + "start_offset": 15, + "end_offset": 19, + "type": "word", + "position": 3 + } + ] +} +``` + + +## Differences between the word_delimiter_graph and word_delimiter filters + + +Both the `word_delimiter_graph` and `word_delimiter` token filters generate tokens spanning multiple positions when any of the following parameters are set to `true`: + +- `catenate_all` +- `catenate_numbers` +- `catenate_words` +- `preserve_original` + +To illustrate the differences between these filters, consider the input text `Pro-XT500`. + + +### word_delimiter_graph + + +The `word_delimiter_graph` filter assigns a `positionLength` attribute to multi-position tokens, indicating how many positions a token spans. This ensures that the filter always generates valid token graphs, making it suitable for use in advanced token graph scenarios. Although token graphs with multi-position tokens are not supported for indexing, they can still be useful in search scenarios. For example, queries like `match_phrase` can use these graphs to generate multiple subqueries from a single input string. For the example input text, the `word_delimiter_graph` filter generates the following tokens: + +- `Pro` (position 1) +- `XT500` (position 2) +- `ProXT500` (position 1, `positionLength`: 2) + +The `positionLength` attribute the production of a valid graph to be used in advanced queries. + + +### word_delimiter + + +In contrast, the `word_delimiter` filter does not assign a `positionLength` attribute to multi-position tokens, leading to invalid graphs when these tokens are present. For the example input text, the `word_delimiter` filter generates the following tokens: + +- `Pro` (position 1) +- `XT500` (position 2) +- `ProXT500` (position 1, no `positionLength`) + +The lack of a `positionLength` attribute results in a token graph that is invalid for token streams containing multi-position tokens. \ No newline at end of file diff --git a/_analyzers/token-filters/word-delimiter.md b/_analyzers/token-filters/word-delimiter.md new file mode 100644 index 00000000..77a71f28 --- /dev/null +++ b/_analyzers/token-filters/word-delimiter.md @@ -0,0 +1,128 @@ +--- +layout: default +title: Word delimiter +parent: Token filters +nav_order: 470 +--- + +# Word delimiter token filter + +The `word_delimiter` token filter is used to splits token on predefined characters and also offers optional token normalization based on customizable rules. + +We recommend using the `word_delimiter_graph` filter instead of the `word_delimiter` filter whenever possible because the `word_delimiter` filter sometimes produces invalid token graphs. For more information about the differences between the two filters, see [Differences between the `word_delimiter_graph` and `word_delimiter` filters]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter-graph/#differences-between-the-word_delimiter_graph-and-word_delimiter-filters). +{: .important} + +The `word_delimiter` filter is used to remove punctuation from complex identifiers like part numbers or product IDs. In such cases, it is best used with the `keyword` tokenizer. For hyphenated words, use the `synonym_graph` token filter instead of the `word_delimiter` filter because users frequently search for these terms both with and without hyphens. +{: .note} + +By default, the filter applies the following rules. + +| Description | Input | Output | +|:---|:---|:---| +| Treats non-alphanumeric characters as delimiters. | `ultra-fast` | `ultra`, `fast` | +| Removes delimiters at the beginning or end of tokens. | `Z99++'Decoder'`| `Z99`, `Decoder` | +| Splits tokens when there is a transition between uppercase and lowercase letters. | `OpenSearch` | `Open`, `Search` | +| Splits tokens when there is a transition between letters and numbers. | `T1000` | `T`, `1000` | +| Removes the possessive ('s) from the end of tokens. | `John's` | `John` | + +It's important **not** to use tokenizers that strip punctuation, like the `standard` tokenizer, with this filter. Doing so may prevent proper token splitting and interfere with options like `catenate_all` or `preserve_original`. We recommend using this filter with a `keyword` or `whitespace` tokenizer. +{: .important} + +## Parameters + +You can configure the `word_delimiter` token filter using the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`catenate_all` | Optional | Boolean | Produces concatenated tokens from a sequence of alphanumeric parts. For example, `"quick-fast-200"` becomes `[ quickfast200, quick, fast, 200 ]`. Default is `false`. +`catenate_numbers` | Optional | Boolean | Concatenates numerical sequences. For example, `"10-20-30"` becomes `[ 102030, 10, 20, 30 ]`. Default is `false`. +`catenate_words` | Optional | Boolean | Concatenates alphabetic words. For example, `"high-speed-level"` becomes `[ highspeedlevel, high, speed, level ]`. Default is `false`. +`generate_number_parts` | Optional | Boolean | If `true`, numeric tokens (tokens consisting of numbers only) are included in the output. Default is `true`. +`generate_word_parts` | Optional | Boolean | If `true`, alphabetical tokens (tokens consisting of alphabetic characters only) are included in the output. Default is `true`. +`preserve_original` | Optional | Boolean | Keeps the original token (which may include non-alphanumeric delimiters) alongside the generated tokens in the output. For example, `"auto-drive-300"` becomes `[ auto-drive-300, auto, drive, 300 ]`. If `true`, the filter generates multi-position tokens not supported by indexing, so do not use this filter in an index analyzer or use the `flatten_graph` filter after this filter. Default is `false`. +`protected_words` | Optional | Array of strings | Specifies tokens that should not be split. +`protected_words_path` | Optional | String | Specifies a path (absolute or relative to the config directory) to a file containing tokens that should not be separated by new lines. +`split_on_case_change` | Optional | Boolean | Splits tokens where consecutive letters have different cases (one is lowercase and the other is uppercase). For example, `"OpenSearch"` becomes `[ Open, Search ]`. Default is `true`. +`split_on_numerics` | Optional | Boolean | Splits tokens where there are consecutive letters and numbers. For example `"v8engine"` will become `[ v, 8, engine ]`. Default is `true`. +`stem_english_possessive` | Optional | Boolean | Removes English possessive endings, such as `'s`. Default is `true`. +`type_table` | Optional | Array of strings | A custom map that specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For example, to treat a hyphen (`-`) as an alphanumeric character, specify `["- => ALPHA"]` so that words are not split on hyphens. Valid types are:
- `ALPHA`: alphabetical
- `ALPHANUM`: alphanumeric
- `DIGIT`: numeric
- `LOWER`: lowercase alphabetical
- `SUBWORD_DELIM`: non-alphanumeric delimiter
- `UPPER`: uppercase alphabetical +`type_table_path` | Optional | String | Specifies a path (absolute or relative to the config directory) to a file containing a custom character map. The map specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For valid types, see `type_table`. + +## Example + +The following example request creates a new index named `my-custom-index` and configures an analyzer with a `word_delimiter` filter: + +```json +PUT /my-custom-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "tokenizer": "keyword", + "filter": [ "custom_word_delimiter_filter" ] + } + }, + "filter": { + "custom_word_delimiter_filter": { + "type": "word_delimiter", + "split_on_case_change": true, + "split_on_numerics": true, + "stem_english_possessive": true + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +GET /my-custom-index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "FastCar's Model2023" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Fast", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "Car", + "start_offset": 4, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "Model", + "start_offset": 10, + "end_offset": 15, + "type": "word", + "position": 2 + }, + { + "token": "2023", + "start_offset": 15, + "end_offset": 19, + "type": "word", + "position": 3 + } + ] +} +``` diff --git a/_analyzers/token-graph.md b/_analyzers/token-graph.md new file mode 100644 index 00000000..865a5fd1 --- /dev/null +++ b/_analyzers/token-graph.md @@ -0,0 +1,201 @@ +--- +layout: default +title: Token graphs +nav_order: 150 +--- + +# Token graphs + +Token graphs show how tokens relate to each other during text analysis, particularly when handling multi-word synonyms or compound words. They help ensure accurate query matching and phrase expansion. + +Each token is assigned the following metadata: + +- `position` – The location of the token in the text + +- `positionLength` – How many positions the token spans (used in multi-word expressions) + +Token graphs use this information to build a graph structure of token relationships, which is later used during query parsing. Graph-aware token filters, such as [`synonym_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym-graph/) and [`word_delimiter_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/word-delimiter-graph/), enable you to match phrases more accurately. + +The following diagram depicts the relationship between `position` and `positionLength` when using [`synonym_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym-graph/). The "NYC" token is assigned a `position` of `0` and a `positionLength` of `3`. + +![token graph]({{site.url}}{{site.baseurl}}/images/nyc-token-graph.png){: width="700" } + +## Using token graphs during indexing and querying + +At index time, `positionLength` is ignored and token graphs are not used. + +During query execution, various query types can leverage token graphs, with the following being the most frequently used: + +- [`match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/) +- [`match_phrase`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) + +## Example: Synonym compared to synonym graph + +To better understand the difference between graph-aware token filters and standard token filters, you can use the following steps to compare the [`synonym`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym/) token filter with the [`synonym_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym-graph/) token filter: + +1. Create an index with a [`synonym`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym/) token filter (not graph aware): + + ```json + PUT /synonym_index + { + "settings": { + "analysis": { + "filter": { + "my_synonyms": { + "type": "synonym", + "synonyms": ["ssd => solid state drive"] + } + }, + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "filter": ["lowercase", "my_synonyms"] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_analyzer" + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Create an index with a [`synonym_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym-graph/) token filter (graph aware): + + ```json + PUT /synonym_graph_index + { + "settings": { + "analysis": { + "filter": { + "my_synonyms": { + "type": "synonym_graph", + "synonyms": ["ssd => solid state drive"] + } + }, + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "filter": ["lowercase", "my_synonyms"] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_analyzer" + } + } + } + } + ``` + {% include copy-curl.html %} + +3. Create the same document in each index: + + ```json + PUT /synonym_index/_doc/1 + { "content": "ssd is critical" } + ``` + {% include copy-curl.html %} + + ```json + PUT /synonym_graph_index/_doc/1 + { "content": "ssd is critical" } + ``` + {% include copy-curl.html %} + +4. Search the non-graph-aware index: + + ```json + POST /synonym_index/_search + { + "query": { + "match_phrase": { + "content": "solid state drive is critical" + } + } + } + ``` + {% include copy-curl.html %} + + The response contains no hits: + + ```json + { + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 0, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } + } + ``` + +5. Search the graph-aware index: + + ```json + POST /synonym_graph_index/_search + { + "query": { + "match_phrase": { + "content": "solid state drive is critical" + } + } + } + ``` + {% include copy-curl.html %} + + The response contains one hit: + + ```json + { + "took": 9, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.4384103, + "hits": [ + { + "_index": "synonym_graph_index", + "_id": "1", + "_score": 1.4384103, + "_source": { + "content": "ssd is critical" + } + } + ] + } + } + ``` + +A hit occurs when using the graph-aware token filter because during the [`match_phrase`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) query, an additional subquery is generated using the token graph. The following diagram illustrates the token graph created by the graph-aware token filter. + +![token graph]({{site.url}}{{site.baseurl}}/images/ssd-token-graph.png){: width="700" } \ No newline at end of file diff --git a/_analyzers/tokenizers/character-group.md b/_analyzers/tokenizers/character-group.md new file mode 100644 index 00000000..56e52780 --- /dev/null +++ b/_analyzers/tokenizers/character-group.md @@ -0,0 +1,124 @@ +--- +layout: default +title: Character group +parent: Tokenizers +nav_order: 20 +has_children: false +has_toc: false +--- + +# Character group tokenizer + +The `char_group` tokenizer splits text into tokens using specific characters as delimiters. It is suitable for situations requiring straightforward tokenization, offering a simpler alternative to pattern-based tokenizers without the added complexity. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `char_group` tokenizer. The tokenizer splits text on white space, `-`, and `:` characters: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_char_group_tokenizer": { + "type": "char_group", + "tokenize_on_chars": [ + "whitespace", + "-", + ":" + ] + } + }, + "analyzer": { + "my_char_group_analyzer": { + "type": "custom", + "tokenizer": "my_char_group_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_char_group_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_char_group_analyzer", + "text": "Fast-driving cars: they drive fast!" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Fast", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "driving", + "start_offset": 5, + "end_offset": 12, + "type": "word", + "position": 1 + }, + { + "token": "cars", + "start_offset": 13, + "end_offset": 17, + "type": "word", + "position": 2 + }, + { + "token": "they", + "start_offset": 19, + "end_offset": 23, + "type": "word", + "position": 3 + }, + { + "token": "drive", + "start_offset": 24, + "end_offset": 29, + "type": "word", + "position": 4 + }, + { + "token": "fast!", + "start_offset": 30, + "end_offset": 35, + "type": "word", + "position": 5 + } + ] +} +``` + +## Parameters + +The `char_group` tokenizer can be configured with the following parameters. + +| **Parameter** | **Required/Optional** | **Data type** | **Description** | +| :--- | :--- | :--- | :--- | +| `tokenize_on_chars` | Required | Array | Specifies a set of characters on which the text should be tokenized. You can specify single characters (for example, `-` or `@`), including escape characters (for example, `\n`), or character classes such as `whitespace`, `letter`, `digit`, `punctuation`, or `symbol`. | +| `max_token_length` | Optional | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. | \ No newline at end of file diff --git a/_analyzers/tokenizers/classic.md b/_analyzers/tokenizers/classic.md new file mode 100644 index 00000000..c2ae4c23 --- /dev/null +++ b/_analyzers/tokenizers/classic.md @@ -0,0 +1,225 @@ +--- +layout: default +title: Classic +parent: Tokenizers +nav_order: 35 + +--- + +# Classic tokenizer + +The `classic` tokenizer parses text, applying English language grammatical rules to break the text into tokens. It includes specific logic to handle patterns such as the following: + +- Acronyms +- Email addresses +- Domain names +- Certain types of punctuation + +This tokenizer works best with the English language. It may not produce optimal results for other languages, especially those with different grammatical structures. +{: .note} + +The `classic` tokenizer parses text as follows: + +- **Punctuation**: Splits text on most punctuation marks and removes punctuation characters. Dots that aren't followed by spaces are treated as part of the token. +- **Hyphens**: Splits words at hyphens, except when a number is present. When a number is present in a token, the token is not split and is treated like a product number. +- **Email**: Recognizes email addresses and hostnames and keeps them as single tokens. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `classic` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_classic_analyzer": { + "type": "custom", + "tokenizer": "classic" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_classic_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_classic_analyzer", + "text": "For product AB3423, visit X&Y at example.com, email info@example.com, or call the operator's phone number 1-800-555-1234. P.S. 你好." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "For", + "start_offset": 0, + "end_offset": 3, + "type": "", + "position": 0 + }, + { + "token": "product", + "start_offset": 4, + "end_offset": 11, + "type": "", + "position": 1 + }, + { + "token": "AB3423", + "start_offset": 12, + "end_offset": 18, + "type": "", + "position": 2 + }, + { + "token": "visit", + "start_offset": 20, + "end_offset": 25, + "type": "", + "position": 3 + }, + { + "token": "X&Y", + "start_offset": 26, + "end_offset": 29, + "type": "", + "position": 4 + }, + { + "token": "at", + "start_offset": 30, + "end_offset": 32, + "type": "", + "position": 5 + }, + { + "token": "example.com", + "start_offset": 33, + "end_offset": 44, + "type": "", + "position": 6 + }, + { + "token": "email", + "start_offset": 46, + "end_offset": 51, + "type": "", + "position": 7 + }, + { + "token": "info@example.com", + "start_offset": 52, + "end_offset": 68, + "type": "", + "position": 8 + }, + { + "token": "or", + "start_offset": 70, + "end_offset": 72, + "type": "", + "position": 9 + }, + { + "token": "call", + "start_offset": 73, + "end_offset": 77, + "type": "", + "position": 10 + }, + { + "token": "the", + "start_offset": 78, + "end_offset": 81, + "type": "", + "position": 11 + }, + { + "token": "operator's", + "start_offset": 82, + "end_offset": 92, + "type": "", + "position": 12 + }, + { + "token": "phone", + "start_offset": 93, + "end_offset": 98, + "type": "", + "position": 13 + }, + { + "token": "number", + "start_offset": 99, + "end_offset": 105, + "type": "", + "position": 14 + }, + { + "token": "1-800-555-1234", + "start_offset": 106, + "end_offset": 120, + "type": "", + "position": 15 + }, + { + "token": "P.S.", + "start_offset": 122, + "end_offset": 126, + "type": "", + "position": 16 + }, + { + "token": "你", + "start_offset": 127, + "end_offset": 128, + "type": "", + "position": 17 + }, + { + "token": "好", + "start_offset": 128, + "end_offset": 129, + "type": "", + "position": 18 + } + ] +} +``` + +## Token types + +The `classic` tokenizer produces the following token types. + +| Token type | Description | +| :--- | :--- | +| `` | Alphanumeric tokens consisting of letters, numbers, or a combination of both. | +| ``| Tokens containing an apostrophe, commonly used in possessives or contractions (for example, `John's`). | +| `` | Acronyms or abbreviations, often identified by a trailing period (for example, `P.S.` or `U.S.A.`). | +| `` | Tokens representing company names (for example, `X&Y`). If these tokens aren't produced automatically, you may need custom configurations or filters. | +| `` | Tokens matching email addresses, containing an `@` symbol and a domain (for example,`support@widgets.co` or `info@example.com`). | +| `` | Tokens matching website or host names, often containing `www.` or a domain suffix like `.com` (for example, `www.example.com` or `example.org`). | +| `` | Tokens containing only numbers or numeric-like sequences (for example, `1-800`, `12345`, or `3.14`). | +| `` | Tokens representing Chinese or Japanese characters. | +| `` | Deprecated acronym handling (for example, acronyms with different parsing rules in older versions). Rarely used---exists primarily for backward compatibility with legacy tokenizer rules. | diff --git a/_analyzers/tokenizers/edge-n-gram.md b/_analyzers/tokenizers/edge-n-gram.md new file mode 100644 index 00000000..55e17c06 --- /dev/null +++ b/_analyzers/tokenizers/edge-n-gram.md @@ -0,0 +1,204 @@ +--- +layout: default +title: Edge n-gram +parent: Tokenizers +nav_order: 40 +--- + +# Edge n-gram tokenizer + +The `edge_ngram` tokenizer generates partial word tokens, or _n-grams_, starting from the beginning of each word. It splits the text based on specified characters and produces tokens within a defined minimum and maximum length range. This tokenizer is particularly useful for implementing search-as-you-type functionality. + +Edge n-grams are ideal for autocomplete searches where the order of the words may vary, such as when searching for product names or addresses. For more information, see [Autocomplete]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/). However, for text with a fixed order, like movie or song titles, the completion suggester may be more accurate. + +By default, the `edge n-gram` tokenizer produces tokens with a minimum length of `1` and a maximum length of `2`. For example, when analyzing the text `OpenSearch`, the default configuration will produce the `O` and `Op` n-grams. These short n-grams often match too many irrelevant terms, so configuring the tokenizer is necessary in order to adjust the n-gram lengths. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with an `edge_ngram` tokenizer. The tokenizer produces tokens 3--6 characters in length, considering both letters and symbols to be valid token characters: + +```json +PUT /edge_n_gram_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_analyzer": { + "tokenizer": "my_custom_tokenizer" + } + }, + "tokenizer": { + "my_custom_tokenizer": { + "type": "edge_ngram", + "min_gram": 3, + "max_gram": 6, + "token_chars": [ + "letter" ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /edge_n_gram_index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "Code 42 rocks!" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Cod", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "Code", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "roc", + "start_offset": 8, + "end_offset": 11, + "type": "word", + "position": 2 + }, + { + "token": "rock", + "start_offset": 8, + "end_offset": 12, + "type": "word", + "position": 3 + }, + { + "token": "rocks", + "start_offset": 8, + "end_offset": 13, + "type": "word", + "position": 4 + } + ] +} +``` + +## Parameters + +| Parameter | Required/Optional | Data type | Description | +|:-------|:--------|:------|:---| +| `min_gram` | Optional | Integer | The minimum token length. Default is `1`. | +| `max_gram` | Optional | Integer | The maximum token length. Default is `2`. | +| `custom_token_chars`| Optional | String | Defines custom characters to be treated as part of a token (for example, `+-_`). | +| `token_chars` | Optional | Array of strings | Defines character classes to include in tokens. Tokens are split on characters not included in these classes. Default includes all characters. Available classes include:
- `letter`: Alphabetic characters (for example, `a`, `ç`, or `京`)
- `digit`: Numeric characters (for example, `3` or `7`)
- `punctuation`: Punctuation symbols (for example, `!` or `?`)
- `symbol`: Other symbols (for example, `$` or `√`)
- `whitespace`: Space or newline characters
- `custom`: Allows you to specify custom characters in the `custom_token_chars` setting. | + + +## max_gram parameter limitations + + +The `max_gram` parameter sets the maximum length of tokens generated by the tokenizer. When a search query exceeds this length, it may fail to match any terms in the index. + +For example, if `max_gram` is set to `4`, the query `explore` would be tokenized as `expl` during indexing. As a result, a search for the full term `explore` will not match the indexed token `expl`. + +To address this limitation, you can apply a `truncate` token filter to shorten search terms to the maximum token length. However, this approach presents trade-offs. Truncating `explore` to `expl` might lead to matches with unrelated terms like `explosion` or `explicit`, reducing search precision. + +We recommend carefully balancing the `max_gram` value to ensure efficient tokenization while minimizing irrelevant matches. If precision is critical, consider alternative strategies, such as adjusting query analyzers or fine-tuning filters. + +## Best practices + +We recommend using the `edge_ngram` tokenizer only at indexing time in order to ensure that partial word tokens are stored. At search time, a basic analyzer should be used to match all query terms. + +## Configuring search-as-you-type functionality + +To implement search-as-you-type functionality, use the `edge_ngram` tokenizer during indexing and an analyzer that performs minimal processing at search time. The following example demonstrates this approach. + +Create an index with an `edge_ngram` tokenizer: + + +```json +PUT /my-autocomplete-index +{ + "settings": { + "analysis": { + "analyzer": { + "autocomplete": { + "tokenizer": "autocomplete", + "filter": [ + "lowercase" + ] + }, + "autocomplete_search": { + "tokenizer": "lowercase" + } + }, + "tokenizer": { + "autocomplete": { + "type": "edge_ngram", + "min_gram": 2, + "max_gram": 10, + "token_chars": [ + "letter" + ] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "autocomplete", + "search_analyzer": "autocomplete_search" + } + } + } +} +``` +{% include copy-curl.html %} + +Index a document containing a `product` field and refresh the index: + +```json +PUT my-autocomplete-index/_doc/1?refresh +{ + "title": "Laptop Pro" +} +``` +{% include copy-curl.html %} + +This configuration ensures that the `edge_ngram` tokenizer breaks terms like "Laptop" into tokens such as `La`, `Lap`, and `Lapt`, allowing partial matches during search. At search time, the `standard` tokenizer simplifies queries while ensuring that matches are case-insensitive because of the lowercase filter. + +Searches for `laptop Pr` or `lap pr` now retrieve the relevant document based on partial matches: + +```json +GET my-autocomplete-index/_search +{ + "query": { + "match": { + "title": { + "query": "lap pr", + "operator": "and" + } + } + } +} +``` +{% include copy-curl.html %} + +For more information, see [Search as you type]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/#search-as-you-type). \ No newline at end of file diff --git a/_analyzers/tokenizers/icu-tokenizer.md b/_analyzers/tokenizers/icu-tokenizer.md new file mode 100644 index 00000000..e2b435eb --- /dev/null +++ b/_analyzers/tokenizers/icu-tokenizer.md @@ -0,0 +1,162 @@ +--- +layout: default +title: ICU +parent: Tokenizers +nav_order: 45 +--- + +# ICU tokenizer + +The `icu_tokenizer` splits text into words using Unicode text segmentation rules defined in [Unicode Standard Annex #29](https://www.unicode.org/reports/tr29/). This tokenizer provides more accurate word boundary detection than the standard tokenizer, particularly for Asian languages that don't use spaces to separate words. + +The `icu_tokenizer` employs dictionary-based tokenization for Chinese, Japanese, Korean, Thai, and Lao text, and applies specialized rules for segmenting Myanmar and Khmer scripts into syllables. + +## Installation + +The `icu_tokenizer` requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/). + +## Example + +The following example demonstrates how to use the `icu_tokenizer`: + +```json +PUT /icu-tokenizer-index +{ + "settings": { + "analysis": { + "analyzer": { + "icu_analyzer_custom": { + "tokenizer": "icu_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Testing the tokenizer + +Use the following request to test the `icu_tokenizer`: + +```json +POST /icu-tokenizer-index/_analyze +{ + "tokenizer": "icu_tokenizer", + "text": "สวัสดีOpenSearchเป็นเครื่องมือค้นหา" +} +``` +{% include copy-curl.html %} + +The tokenizer correctly segments Thai text without spaces: + +```json +{ + "tokens": [ + { + "token": "สวัสดี", + "start_offset": 0, + "end_offset": 6, + "type": "", + "position": 0 + }, + { + "token": "OpenSearch", + "start_offset": 6, + "end_offset": 16, + "type": "", + "position": 1 + }, + { + "token": "เป็น", + "start_offset": 16, + "end_offset": 20, + "type": "", + "position": 2 + }, + { + "token": "เครื่อง", + "start_offset": 20, + "end_offset": 27, + "type": "", + "position": 3 + }, + { + "token": "มือ", + "start_offset": 27, + "end_offset": 30, + "type": "", + "position": 4 + }, + { + "token": "ค้นหา", + "start_offset": 30, + "end_offset": 35, + "type": "", + "position": 5 + } + ] +} +``` + +## Customizing tokenization rules + +Advanced users can customize the `icu_tokenizer` behavior by specifying per-script rule files using the Resource Bundle Break Iterator (RBBI) syntax. This feature is experimental in Lucene. + +To apply custom rules, use the `rule_files` parameter with a comma-separated list of `script:filename` pairs. Script codes follow the [ISO 15924](https://unicode.org/iso15924/iso15924-codes.html) four-letter standard. + +### Example with custom rules + +Save a custom rule file to your OpenSearch config directory (for example, `CustomRules.rbbi`): + +```text +.+ {200}; +``` + +Configure an analyzer to use this rule file: + +```json +PUT /custom-icu-rules +{ + "settings": { + "analysis": { + "tokenizer": { + "custom_icu_tokenizer": { + "type": "icu_tokenizer", + "rule_files": "Latn:CustomRules.rbbi" + } + }, + "analyzer": { + "custom_icu_analyzer": { + "tokenizer": "custom_icu_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the custom tokenizer: + +```json +POST /custom-icu-rules/_analyze +{ + "analyzer": "custom_icu_analyzer", + "text": "Custom tokenization rules" +} +``` +{% include copy-curl.html %} + +## Parameters + +The following table lists the parameters for the `icu_tokenizer`. + +Parameter | Data type | Description +:--- | :--- | :--- +`rule_files` | String | Comma-separated list of `script:rulefile` pairs that define custom tokenization rules for specific scripts. Rule files must be placed in the OpenSearch config directory. Optional. + +## Related documentation + +- [ICU analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/icu/) +- [Standard tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/standard/) diff --git a/_analyzers/tokenizers/index.md b/_analyzers/tokenizers/index.md index d401851f..fe6011f9 100644 --- a/_analyzers/tokenizers/index.md +++ b/_analyzers/tokenizers/index.md @@ -2,8 +2,10 @@ layout: default title: Tokenizers nav_order: 60 -has_children: false +has_children: true has_toc: false +redirect_from: + - /analyzers/tokenizers/ --- # Tokenizers @@ -28,13 +30,13 @@ Word tokenizers parse full text into words. Tokenizer | Description | Example :--- | :--- | :--- -`standard` | - Parses strings into tokens at word boundaries
- Removes most punctuation | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `2`, `to`, `OpenSearch`] -`letter` | - Parses strings into tokens on any non-letter character
- Removes non-letter characters | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`It`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `to`, `OpenSearch`] -`lowercase` | - Parses strings into tokens on any non-letter character
- Removes non-letter characters
- Converts terms to lowercase | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] -`whitespace` | - Parses strings into tokens at white space characters | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] -`uax_url_email` | - Similar to the standard tokenizer
- Unlike the standard tokenizer, leaves URLs and email addresses as single terms | `It’s fun to contribute a brand-new PR or 2 to OpenSearch opensearch-project@github.com!`
becomes
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `2`, `to`, `OpenSearch`, `opensearch-project@github.com`] -`classic` | - Parses strings into tokens on:
  - Punctuation characters that are followed by a white space character
  - Hyphens if the term does not contain numbers
- Removes punctuation
- Leaves URLs and email addresses as single terms | `Part number PA-35234, single-use product (128.32)`
becomes
[`Part`, `number`, `PA-35234`, `single`, `use`, `product`, `128.32`] -`thai` | - Parses Thai text into terms | `สวัสดีและยินดีต`
becomes
[`สวัสด`, `และ`, `ยินดี`, `ต`] +[`standard`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/standard/) | - Parses strings into tokens at word boundaries
- Removes most punctuation | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `2`, `to`, `OpenSearch`] +[`letter`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/letter/) | - Parses strings into tokens on any non-letter character
- Removes non-letter characters | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`It`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `to`, `OpenSearch`] +[`lowercase`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/lowercase/) | - Parses strings into tokens on any non-letter character
- Removes non-letter characters
- Converts terms to lowercase | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] +[`whitespace`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/whitespace/) | - Parses strings into tokens at white space characters | `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`
becomes
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] +[`uax_url_email`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/uax-url-email/) | - Similar to the standard tokenizer
- Unlike the standard tokenizer, leaves URLs and email addresses as single terms | `It’s fun to contribute a brand-new PR or 2 to OpenSearch opensearch-project@github.com!`
becomes
[`It’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `PR`, `or`, `2`, `to`, `OpenSearch`, `opensearch-project@github.com`] +[`classic`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/classic/) | - Parses strings into tokens on:
  - Punctuation characters that are followed by a white space character
  - Hyphens if the term does not contain numbers
- Removes punctuation
- Leaves URLs and email addresses as single terms | `Part number PA-35234, single-use product (128.32)`
becomes
[`Part`, `number`, `PA-35234`, `single`, `use`, `product`, `128.32`] +[`thai`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/thai/) | - Parses Thai text into terms | `สวัสดีและยินดีต`
becomes
[`สวัสด`, `และ`, `ยินดี`, `ต`] ### Partial word tokenizers @@ -42,8 +44,8 @@ Partial word tokenizers parse text into words and generate fragments of those wo Tokenizer | Description | Example :--- | :--- | :--- -`ngram`| - Parses strings into words on specified characters (for example, punctuation or white space characters) and generates n-grams of each word | `My repo`
becomes
[`M`, `My`, `y`, `y `,  ,  r, `r`, `re`, `e`, `ep`, `p`, `po`, `o`]
because the default n-gram length is 1--2 characters -`edge_ngram` | - Parses strings into words on specified characters (for example, punctuation or white space characters) and generates edge n-grams of each word (n-grams that start at the beginning of the word) | `My repo`
becomes
[`M`, `My`]
because the default n-gram length is 1--2 characters +[`ngram`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/ngram/)| - Generates n-grams (overlapping character sequences) from the input
- By default, treats the entire input as a single token and generates n-grams from all characters (including spaces and punctuation)
- When configured with `token_chars`, first splits on specified characters, then generates n-grams from each resulting word | `My repo`
becomes
[`M`, `My`, `y`, `y `,  ,  r, `r`, `re`, `e`, `ep`, `p`, `po`, `o`]
with default behavior (no `token_chars` configuration) and n-gram length of 1--2 characters. +[`edge_ngram`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/edge-n-gram/) | - Generates edge n-grams (n-grams that start at the beginning of each token)
- By default, treats the entire input as a single token
- When configured with `token_chars`, first splits on specified characters (for example, punctuation or white space), then generates edge n-grams from each resulting word | `My repo`
becomes
[`M`, `My`, `r`, `re`]
when configured with `token_chars: ["letter"]` and default n-gram length of 1--2 characters. ### Structured text tokenizers @@ -51,11 +53,11 @@ Structured text tokenizers parse structured text, such as identifiers, email add Tokenizer | Description | Example :--- | :--- | :--- -`keyword` | - No-op tokenizer
- Outputs the entire string unchanged
- Can be combined with token filters, like lowercase, to normalize terms | `My repo`
becomes
`My repo` -`pattern` | - Uses a regular expression pattern to parse text into terms on a word separator or to capture matching text as terms
- Uses [Java regular expressions](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) | `https://opensearch.org/forum`
becomes
[`https`, `opensearch`, `org`, `forum`] because by default the tokenizer splits terms at word boundaries (`\W+`)
Can be configured with a regex pattern -`simple_pattern` | - Uses a regular expression pattern to return matching text as terms
- Uses [Lucene regular expressions](https://lucene.apache.org/core/8_7_0/core/org/apache/lucene/util/automaton/RegExp.html)
- Faster than the `pattern` tokenizer because it uses a subset of the `pattern` tokenizer regular expressions | Returns an empty array by default
Must be configured with a pattern because the pattern defaults to an empty string -`simple_pattern_split` | - Uses a regular expression pattern to split the text at matches rather than returning the matches as terms
- Uses [Lucene regular expressions](https://lucene.apache.org/core/8_7_0/core/org/apache/lucene/util/automaton/RegExp.html)
- Faster than the `pattern` tokenizer because it uses a subset of the `pattern` tokenizer regular expressions | No-op by default
Must be configured with a pattern -`char_group` | - Parses on a set of configurable characters
- Faster than tokenizers that run regular expressions | No-op by default
Must be configured with a list of characters -`path_hierarchy` | - Parses text on the path separator (by default, `/`) and returns a full path to each component in the tree hierarchy | `one/two/three`
becomes
[`one`, `one/two`, `one/two/three`] +[`keyword`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/keyword/) | - No-op tokenizer
- Outputs the entire string unchanged
- Can be combined with token filters, like lowercase, to normalize terms | `My repo`
becomes
`My repo` +[`pattern`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/pattern/) | - Uses a regular expression pattern to parse text into terms on a word separator or to capture matching text as terms
- Uses [Java regular expressions](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) | `https://opensearch.org/forum`
becomes
[`https`, `opensearch`, `org`, `forum`] because by default the tokenizer splits terms at word boundaries (`\W+`)
Can be configured with a regex pattern +[`simple_pattern`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/simple-pattern/) | - Uses a regular expression pattern to return matching text as terms
- Uses [Lucene regular expressions](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/util/automaton/RegExp.html)
- Faster than the `pattern` tokenizer because it uses a subset of the `pattern` tokenizer regular expressions | Returns an empty array by default
Must be configured with a pattern because the pattern defaults to an empty string +[`simple_pattern_split`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/simple-pattern-split/) | - Uses a regular expression pattern to split the text on matches rather than returning the matches as terms
- Uses [Lucene regular expressions](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/util/automaton/RegExp.html)
- Faster than the `pattern` tokenizer because it uses a subset of the `pattern` tokenizer regular expressions | No-op by default
Must be configured with a pattern +[`char_group`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/character-group/) | - Parses on a set of configurable characters
- Faster than tokenizers that run regular expressions | No-op by default
Must be configured with a list of characters +[`path_hierarchy`]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/path-hierarchy/) | - Parses text on the path separator (by default, `/`) and returns a full path to each component in the tree hierarchy | `one/two/three`
becomes
[`one`, `one/two`, `one/two/three`] diff --git a/_analyzers/tokenizers/keyword.md b/_analyzers/tokenizers/keyword.md new file mode 100644 index 00000000..8b77d38c --- /dev/null +++ b/_analyzers/tokenizers/keyword.md @@ -0,0 +1,119 @@ +--- +layout: default +title: Keyword +parent: Tokenizers +nav_order: 50 +--- + +# Keyword tokenizer + +The `keyword` tokenizer ingests text and outputs it exactly as a single, unaltered token. This makes it particularly useful when you want the input to remain intact, such as when managing structured data like names, product codes, or email addresses. + +The `keyword` tokenizer can be paired with token filters to process the text, for example, to normalize it or to remove extraneous characters. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `keyword` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_keyword_analyzer": { + "type": "custom", + "tokenizer": "keyword" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_keyword_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_keyword_analyzer", + "text": "OpenSearch Example" +} +``` +{% include copy-curl.html %} + +The response contains the single token representing the original text: + +```json +{ + "tokens": [ + { + "token": "OpenSearch Example", + "start_offset": 0, + "end_offset": 18, + "type": "word", + "position": 0 + } + ] +} +``` + +## Parameters + +The `keyword` token filter can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`buffer_size`| Optional | Integer | Determines the character buffer size. Default is `256`. There is usually no need to change this setting. + +## Combining the keyword tokenizer with token filters + +To enhance the functionality of the `keyword` tokenizer, you can combine it with token filters. Token filters can transform the text, such as converting it to lowercase or removing unwanted characters. + +### Example: Using the pattern_replace filter and keyword tokenizer + +In this example, the `pattern_replace` filter uses a regular expression to replace all non-alphanumeric characters with an empty string: + +```json +POST _analyze +{ + "tokenizer": "keyword", + "filter": [ + { + "type": "pattern_replace", + "pattern": "[^a-zA-Z0-9]", + "replacement": "" + } + ], + "text": "Product#1234-XYZ" +} +``` +{% include copy-curl.html %} + +The `pattern_replace` filter removes non-alphanumeric characters and returns the following token: + +```json +{ + "tokens": [ + { + "token": "Product1234XYZ", + "start_offset": 0, + "end_offset": 16, + "type": "word", + "position": 0 + } + ] +} +``` + diff --git a/_analyzers/tokenizers/kuromoji.md b/_analyzers/tokenizers/kuromoji.md new file mode 100644 index 00000000..308f92d8 --- /dev/null +++ b/_analyzers/tokenizers/kuromoji.md @@ -0,0 +1,474 @@ +--- +layout: default +title: Kuromoji +parent: Tokenizers +nav_order: 55 +--- + +# Kuromoji tokenizer + +The `kuromoji_tokenizer` performs dictionary-based morphological analysis for Japanese text using the Kuromoji library and the IPAdic dictionary. Unlike tokenizers that split on white space or punctuation, it identifies natural word boundaries in Japanese sentences, which do not use spaces to separate words. + +## Installation + +The `kuromoji_tokenizer` requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/). + +## Parameters + +The following table lists the parameters for the `kuromoji_tokenizer`. + +Parameter | Data type | Description +:--- | :--- | :--- +`mode` | String | Tokenization mode. Valid values are `normal`, `search` (default), and `extended`. See [Tokenization modes](#tokenization-modes) for details. +`discard_punctuation` | Boolean | When `true`, punctuation tokens are discarded from the output. Default is `true`. +`discard_compound_token` | Boolean | When `true`, the compound token produced in `search` mode is discarded and only the sub-tokens are kept. Default is `false`. +`user_dictionary` | String | Path to a custom user dictionary CSV file placed in the OpenSearch config directory. Each line must follow the format `,,,`. Optional. +`user_dictionary_rules` | Array of strings | Inline custom dictionary rules in the same CSV format as `user_dictionary`. Optional. Cannot be used together with `user_dictionary`. +`nbest_cost` | Integer | When set to a value greater than `-1`, enables n-best segmentation and returns alternative tokenizations whose cost (log probability penalty) is within this value of the best segmentation. Default is `-1` (disabled). +`nbest_examples` | String | A comma-separated list of example words used to automatically calculate `nbest_cost`. When provided, the tokenizer finds the minimum additional cost needed to also produce the given examples as tokens. Optional. + +## Tokenization modes + +The tokenization mode controls how the tokenizer handles compound and unknown words. + +| Mode | Compound words | Unknown words | +|:-----|:---------------|:--------------| +| `normal` | Kept as a single token (for example, 関西国際空港 is one token). | Kept as a single token. | +| `search` (default) | Split into sub-tokens in addition to the compound form (for example, 関西国際空港 produces 関西, 国際, 空港, and 関西国際空港). Improves recall for search queries. | Kept as a single token. | +| `extended` | Kept as a single token (same as `normal`). | Split into unigrams (individual characters), ensuring every character is indexed. | + +## Example: Basic tokenization + +The following example creates an index with a custom analyzer using `kuromoji_tokenizer` in its default `search` mode: + +```json +PUT /kuromoji-tokenizer-index +{ + "settings": { + "analysis": { + "analyzer": { + "kuromoji_analyzer": { + "tokenizer": "kuromoji_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test the tokenizer with a sentence meaning "Kansai International Airport is a large airport": + +```json +POST /kuromoji-tokenizer-index/_analyze +{ + "analyzer": "kuromoji_analyzer", + "text": "関西国際空港は大きな空港です" +} +``` +{% include copy-curl.html %} + +In `search` mode, the compound place name 関西国際空港 (Kansai International Airport) is split into its components and also kept as a compound token: + +```json +{ + "tokens": [ + { + "token": "関西", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0, + "positionLength": 3 + }, + { + "token": "国際", + "start_offset": 2, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "空港", + "start_offset": 4, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "は", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 3 + }, + { + "token": "大きな", + "start_offset": 7, + "end_offset": 10, + "type": "word", + "position": 4 + }, + { + "token": "空港", + "start_offset": 10, + "end_offset": 12, + "type": "word", + "position": 5 + }, + { + "token": "です", + "start_offset": 12, + "end_offset": 14, + "type": "word", + "position": 6 + } + ] +} +``` + +## Example: Comparing tokenization modes + +The following example shows how the same text is tokenized differently depending on the mode. Create a custom tokenizer for each mode and compare the output: + +```json +PUT /kuromoji-mode-comparison +{ + "settings": { + "analysis": { + "tokenizer": { + "kuromoji_normal": { + "type": "kuromoji_tokenizer", + "mode": "normal" + }, + "kuromoji_search": { + "type": "kuromoji_tokenizer", + "mode": "search" + }, + "kuromoji_extended": { + "type": "kuromoji_tokenizer", + "mode": "extended" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Test with text that contains a known compound word (関西国際空港 meaning "Kansai International Airport") and an unknown loanword (アバクロンビー meaning "Abercrombie"): + +**`normal` mode** + +```json +POST /kuromoji-mode-comparison/_analyze +{ + "tokenizer": "kuromoji_normal", + "text": "関西国際空港とアバクロンビー" +} +``` +{% include copy-curl.html %} + +In `normal` mode, the compound 関西国際空港 is kept as a single token and the unknown loanword アバクロンビー is also kept as a single token: + +```json +{ + "tokens": [ + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0 + }, + { + "token": "と", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "アバクロンビー", + "start_offset": 7, + "end_offset": 14, + "type": "word", + "position": 2 + } + ] +} +``` + +**`search` mode** + +```json +POST /kuromoji-mode-comparison/_analyze +{ + "tokenizer": "kuromoji_search", + "text": "関西国際空港とアバクロンビー" +} +``` +{% include copy-curl.html %} + +In `search` mode, the compound 関西国際空港 is split into sub-tokens (関西, 国際, 空港) while also being retained as a compound token with `positionLength: 3`. The unknown loanword アバクロンビー is kept as a single token, the same as in `normal` mode: + +```json +{ + "tokens": [ + { + "token": "関西", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0, + "positionLength": 3 + }, + { + "token": "国際", + "start_offset": 2, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "空港", + "start_offset": 4, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "と", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 3 + }, + { + "token": "アバクロンビー", + "start_offset": 7, + "end_offset": 14, + "type": "word", + "position": 4 + } + ] +} +``` + +**`extended` mode** + +```json +POST /kuromoji-mode-comparison/_analyze +{ + "tokenizer": "kuromoji_extended", + "text": "関西国際空港とアバクロンビー" +} +``` +{% include copy-curl.html %} + +In `extended` mode, the known compound 関西国際空港 is handled the same as in `search` mode. The unknown loanword アバクロンビー is split into individual characters (unigrams), ensuring every character is indexed: + +```json +{ + "tokens": [ + { + "token": "関西", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0, + "positionLength": 3 + }, + { + "token": "国際", + "start_offset": 2, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "空港", + "start_offset": 4, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "と", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 3 + }, + { + "token": "ア", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "バ", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 5 + }, + { + "token": "ク", + "start_offset": 9, + "end_offset": 10, + "type": "word", + "position": 6 + }, + { + "token": "ロ", + "start_offset": 10, + "end_offset": 11, + "type": "word", + "position": 7 + }, + { + "token": "ン", + "start_offset": 11, + "end_offset": 12, + "type": "word", + "position": 8 + }, + { + "token": "ビ", + "start_offset": 12, + "end_offset": 13, + "type": "word", + "position": 9 + }, + { + "token": "ー", + "start_offset": 13, + "end_offset": 14, + "type": "word", + "position": 10 + } + ] +} +``` + +## Example: User dictionary + +You can add custom compound terms to the tokenizer's dictionary to control how they are split into sub-tokens. Use `user_dictionary_rules` for inline rules or `user_dictionary` for a file. + +The following example registers 東京スカイツリー (Tokyo Skytree) as a single noun: + +```json +PUT /kuromoji-user-dict-index +{ + "settings": { + "analysis": { + "tokenizer": { + "kuromoji_with_user_dict": { + "type": "kuromoji_tokenizer", + "mode": "search", + "user_dictionary_rules": [ + "東京スカイツリー,東京 スカイツリー,トウキョウ スカイツリー,カスタム名詞" + ] + } + }, + "analyzer": { + "user_dict_analyzer": { + "tokenizer": "kuromoji_with_user_dict" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Each `user_dictionary_rules` entry is a CSV string with four comma-separated fields, in the order `,,,`. The following table describes each field. + +| Field | Description | +|:---|:---| +| `` | The text as it appears in the document (for example, `東京スカイツリー`). | +| `` | Space-separated subtokens for segmentatio (for example, `東京 スカイツリー`). | +| `` | Space-separated katakana readings for each subtoken (for example, `トウキョウ スカイツリー`). | +| `` | The IPAdic part of speech tag assigned to the term (for example, `カスタム名詞`). | + +Use the analyzer to test the user dictionary entry: + +```json +POST /kuromoji-user-dict-index/_analyze +{ + "analyzer": "user_dict_analyzer", + "text": "東京スカイツリーに登る" +} +``` +{% include copy-curl.html %} + +The user dictionary controls how the text is segmented. Because the rule defines `東京 スカイツリー` as two sub-tokens, the tokenizer emits 東京 and スカイツリー as separate tokens rather than keeping 東京スカイツリー as a single token: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "スカイツリー", + "start_offset": 2, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "に", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 2 + }, + { + "token": "登る", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 3 + } + ] +} +``` + +To keep 東京スカイツリー as a single token, define it as a single sub-token in the rule: + +```json +"東京スカイツリー,東京スカイツリー,トウキョウスカイツリー,カスタム名詞" +``` + +## Related documentation + +- [Kuromoji analyzer]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/kuromoji/) +- [Kuromoji part-of-speech token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/kuromoji-part-of-speech/) diff --git a/_analyzers/tokenizers/letter.md b/_analyzers/tokenizers/letter.md new file mode 100644 index 00000000..ba67a784 --- /dev/null +++ b/_analyzers/tokenizers/letter.md @@ -0,0 +1,97 @@ +--- +layout: default +title: Letter +parent: Tokenizers +nav_order: 60 +--- + +# Letter tokenizer + +The `letter` tokenizer splits text into words on any non-letter characters. It works well with many European languages but is ineffective with some Asian languages in which words aren't separated by spaces. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `letter` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_letter_analyzer": { + "type": "custom", + "tokenizer": "letter" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_letter_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST _analyze +{ + "tokenizer": "letter", + "text": "Cats 4EVER love chasing butterflies!" +} + +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Cats", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "EVER", + "start_offset": 6, + "end_offset": 10, + "type": "word", + "position": 1 + }, + { + "token": "love", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 2 + }, + { + "token": "chasing", + "start_offset": 16, + "end_offset": 23, + "type": "word", + "position": 3 + }, + { + "token": "butterflies", + "start_offset": 24, + "end_offset": 35, + "type": "word", + "position": 4 + } + ] +} +``` diff --git a/_analyzers/tokenizers/lowercase.md b/_analyzers/tokenizers/lowercase.md new file mode 100644 index 00000000..5542ecbf --- /dev/null +++ b/_analyzers/tokenizers/lowercase.md @@ -0,0 +1,93 @@ +--- +layout: default +title: Lowercase +parent: Tokenizers +nav_order: 70 +--- + +# Lowercase tokenizer + +The `lowercase` tokenizer breaks text into terms at white space and then lowercases all the terms. Functionally, this is identical to configuring a `letter` tokenizer with a `lowercase` token filter. However, using a `lowercase` tokenizer is more efficient because the tokenizer actions are performed in a single step. + +## Example usage + +The following example request creates a new index named `my-lowercase-index` and configures an analyzer with a `lowercase` tokenizer: + +```json +PUT /my-lowercase-index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_lowercase_tokenizer": { + "type": "lowercase" + } + }, + "analyzer": { + "my_lowercase_analyzer": { + "type": "custom", + "tokenizer": "my_lowercase_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my-lowercase-index/_analyze +{ + "analyzer": "my_lowercase_analyzer", + "text": "This is a Test. OpenSearch 123!" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "this", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 5, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "a", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 2 + }, + { + "token": "test", + "start_offset": 10, + "end_offset": 14, + "type": "word", + "position": 3 + }, + { + "token": "opensearch", + "start_offset": 16, + "end_offset": 26, + "type": "word", + "position": 4 + } + ] +} +``` diff --git a/_analyzers/tokenizers/ngram.md b/_analyzers/tokenizers/ngram.md new file mode 100644 index 00000000..08ac4562 --- /dev/null +++ b/_analyzers/tokenizers/ngram.md @@ -0,0 +1,111 @@ +--- +layout: default +title: N-gram +parent: Tokenizers +nav_order: 80 +--- + +# N-gram tokenizer + +The `ngram` tokenizer splits text into overlapping n-grams (sequences of characters) of a specified length. This tokenizer is particularly useful when you want to perform partial word matching or autocomplete search functionality because it generates substrings (character n-grams) of the original input text. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with an `ngram` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_ngram_tokenizer": { + "type": "ngram", + "min_gram": 3, + "max_gram": 4, + "token_chars": ["letter", "digit"] + } + }, + "analyzer": { + "my_ngram_analyzer": { + "type": "custom", + "tokenizer": "my_ngram_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_ngram_analyzer", + "text": "OpenSearch" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "Sea","start_offset": 0,"end_offset": 3,"type": "word","position": 0}, + {"token": "Sear","start_offset": 0,"end_offset": 4,"type": "word","position": 1}, + {"token": "ear","start_offset": 1,"end_offset": 4,"type": "word","position": 2}, + {"token": "earc","start_offset": 1,"end_offset": 5,"type": "word","position": 3}, + {"token": "arc","start_offset": 2,"end_offset": 5,"type": "word","position": 4}, + {"token": "arch","start_offset": 2,"end_offset": 6,"type": "word","position": 5}, + {"token": "rch","start_offset": 3,"end_offset": 6,"type": "word","position": 6} + ] +} +``` + +## Parameters + +The `ngram` tokenizer can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`min_gram` | Optional | Integer | The minimum length of the n-grams. Default is `1`. +`max_gram` | Optional | Integer | The maximum length of the n-grams. Default is `2`. +`token_chars` | Optional | List of strings | The character classes to be included in tokenization. Valid values are:
- `letter`
- `digit`
- `whitespace`
- `punctuation`
- `symbol`
- `custom` (You must also specify the `custom_token_chars` parameter)
Default is an empty list (`[]`), which retains all the characters. +`custom_token_chars` | Optional | String | Custom characters to be included in the tokens. + +### Maximum difference between `min_gram` and `max_gram` + +The maximum difference between `min_gram` and `max_gram` is configured using the index-level `index.max_ngram_diff` setting and defaults to `1`. + +The following example request creates an index with a custom `index.max_ngram_diff` setting: + +```json +PUT /my-index +{ + "settings": { + "index.max_ngram_diff": 2, + "analysis": { + "tokenizer": { + "my_ngram_tokenizer": { + "type": "ngram", + "min_gram": 3, + "max_gram": 5, + "token_chars": ["letter", "digit"] + } + }, + "analyzer": { + "my_ngram_analyzer": { + "type": "custom", + "tokenizer": "my_ngram_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_analyzers/tokenizers/path-hierarchy.md b/_analyzers/tokenizers/path-hierarchy.md new file mode 100644 index 00000000..a6609f30 --- /dev/null +++ b/_analyzers/tokenizers/path-hierarchy.md @@ -0,0 +1,182 @@ +--- +layout: default +title: Path hierarchy +parent: Tokenizers +nav_order: 90 +--- + +# Path hierarchy tokenizer + +The `path_hierarchy` tokenizer tokenizes file-system-like paths (or similar hierarchical structures) by breaking them down into tokens at each hierarchy level. This tokenizer is particularly useful when working with hierarchical data such as file paths, URLs, or any other delimited paths. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `path_hierarchy` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_path_tokenizer": { + "type": "path_hierarchy" + } + }, + "analyzer": { + "my_path_analyzer": { + "type": "custom", + "tokenizer": "my_path_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_path_analyzer", + "text": "/users/john/documents/report.txt" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "/users", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0 + }, + { + "token": "/users/john", + "start_offset": 0, + "end_offset": 11, + "type": "word", + "position": 0 + }, + { + "token": "/users/john/documents", + "start_offset": 0, + "end_offset": 21, + "type": "word", + "position": 0 + }, + { + "token": "/users/john/documents/report.txt", + "start_offset": 0, + "end_offset": 32, + "type": "word", + "position": 0 + } + ] +} +``` + +## Parameters + +The `path_hierarchy` tokenizer can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`delimiter` | Optional | String | Specifies the character used to separate path components. Default is `/`. +`replacement` | Optional | String | Configures the character used to replace the delimiter in the tokens. Default is `/`. +`buffer_size` | Optional | Integer | Specifies the buffer size. Default is `1024`. +`reverse` | Optional | Boolean | If `true`, generates tokens in reverse order. Default is `false`. +`skip` | Optional | Integer | Specifies the number of initial tokens (levels) to skip when tokenizing. Default is `0`. + +## Example using delimiter and replacement parameters + +The following example request configures custom `delimiter` and `replacement` parameters: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_path_tokenizer": { + "type": "path_hierarchy", + "delimiter": "\\", + "replacement": "\\" + } + }, + "analyzer": { + "my_path_analyzer": { + "type": "custom", + "tokenizer": "my_path_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_path_analyzer", + "text": "C:\\users\\john\\documents\\report.txt" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "C:", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": """C:\users""", + "start_offset": 0, + "end_offset": 8, + "type": "word", + "position": 0 + }, + { + "token": """C:\users\john""", + "start_offset": 0, + "end_offset": 13, + "type": "word", + "position": 0 + }, + { + "token": """C:\users\john\documents""", + "start_offset": 0, + "end_offset": 23, + "type": "word", + "position": 0 + }, + { + "token": """C:\users\john\documents\report.txt""", + "start_offset": 0, + "end_offset": 34, + "type": "word", + "position": 0 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/tokenizers/pattern.md b/_analyzers/tokenizers/pattern.md new file mode 100644 index 00000000..036dd905 --- /dev/null +++ b/_analyzers/tokenizers/pattern.md @@ -0,0 +1,167 @@ +--- +layout: default +title: Pattern +parent: Tokenizers +nav_order: 100 +--- + +# Pattern tokenizer + +The `pattern` tokenizer is a highly flexible tokenizer that allows you to split text into tokens based on a custom Java regular expression. Unlike the `simple_pattern` and `simple_pattern_split` tokenizers, which use Lucene regular expressions, the `pattern` tokenizer can handle more complex and detailed regex patterns, offering greater control over how the text is tokenized. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `pattern` tokenizer. The tokenizer splits text on `-`, `_`, or `.` characters: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "[-_.]" + } + }, + "analyzer": { + "my_pattern_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_pattern_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "OpenSearch-2024_v1.2" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "2024", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 1 + }, + { + "token": "v1", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 2 + }, + { + "token": "2", + "start_offset": 19, + "end_offset": 20, + "type": "word", + "position": 3 + } + ] +} +``` + +## Parameters + +The `pattern` tokenizer can be configured with the following parameters. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`pattern` | Optional | String | The pattern used to split text into tokens, specified using a [Java regular expression](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). Default is `\W+`. +`flags` | Optional | String | Configures pipe-separated [flags](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#field.summary) to apply to the regular expression, for example, `"CASE_INSENSITIVE|MULTILINE|DOTALL"`. +`group` | Optional | Integer | Specifies the capture group to be used as a token. Default is `-1` (split on a match). + +## Example using a group parameter + +The following example request configures a `group` parameter that captures only the second group: + +```json +PUT /my_index_group2 +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "([a-zA-Z]+)(\\d+)", + "group": 2 + } + }, + "analyzer": { + "my_pattern_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index_group2/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "abc123def456ghi" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "123", + "start_offset": 3, + "end_offset": 6, + "type": "word", + "position": 0 + }, + { + "token": "456", + "start_offset": 9, + "end_offset": 12, + "type": "word", + "position": 1 + } + ] +} +``` \ No newline at end of file diff --git a/_analyzers/tokenizers/simple-pattern-split.md b/_analyzers/tokenizers/simple-pattern-split.md new file mode 100644 index 00000000..43c5b0e0 --- /dev/null +++ b/_analyzers/tokenizers/simple-pattern-split.md @@ -0,0 +1,105 @@ +--- +layout: default +title: Simple pattern split +parent: Tokenizers +nav_order: 120 +--- + +# Simple pattern split tokenizer + +The `simple_pattern_split` tokenizer uses a regular expression to split text into tokens. The regular expression defines the pattern used to determine where to split the text. Any matching pattern in the text is used as a delimiter, and the text between delimiters becomes a token. Use this tokenizer when you want to define delimiters and tokenize the rest of the text based on a pattern. + +The tokenizer uses the matched parts of the input text (based on the regular expression) only as delimiters or boundaries to split the text into terms. The matched portions are not included in the resulting terms. For example, if the tokenizer is configured to split text at dot characters (`.`) and the input text is `one.two.three`, then the generated terms are `one`, `two`, and `three`. The dot characters themselves are not included in the resulting terms. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `simple_pattern_split` tokenizer. The tokenizer is configured to split text on hyphens: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_split_tokenizer": { + "type": "simple_pattern_split", + "pattern": "-" + } + }, + "analyzer": { + "my_pattern_split_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_split_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_pattern_split_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_pattern_split_analyzer", + "text": "OpenSearch-2024-10-09" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "2024", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 1 + }, + { + "token": "10", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 2 + }, + { + "token": "09", + "start_offset": 19, + "end_offset": 21, + "type": "word", + "position": 3 + } + ] +} +``` + +## Parameters + +The `simple_pattern_split` tokenizer can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`pattern` | Optional | String | The pattern used to split text into tokens, specified using a [Lucene regular expression](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/util/automaton/RegExp.html). Default is an empty string, which returns the input text as one token. \ No newline at end of file diff --git a/_analyzers/tokenizers/simple-pattern.md b/_analyzers/tokenizers/simple-pattern.md new file mode 100644 index 00000000..65955985 --- /dev/null +++ b/_analyzers/tokenizers/simple-pattern.md @@ -0,0 +1,89 @@ +--- +layout: default +title: Simple pattern +parent: Tokenizers +nav_order: 110 +--- + +# Simple pattern tokenizer + +The `simple_pattern` tokenizer identifies matching sequences in text based on a regular expression and uses those sequences as tokens. It extracts terms that match the regular expression. Use this tokenizer when you want to directly extract specific patterns as terms. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `simple_pattern` tokenizer. The tokenizer extracts numeric terms from text: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "simple_pattern", + "pattern": "\\d+" + } + }, + "analyzer": { + "my_pattern_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "OpenSearch-2024-10-09" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "2024", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 0 + }, + { + "token": "10", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 1 + }, + { + "token": "09", + "start_offset": 19, + "end_offset": 21, + "type": "word", + "position": 2 + } + ] +} +``` + +## Parameters + +The `simple_pattern` tokenizer can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`pattern` | Optional | String | The pattern used to split text into tokens, specified using a [Lucene regular expression](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/util/automaton/RegExp.html). Default is an empty string, which returns the input text as one token. + diff --git a/_analyzers/tokenizers/standard.md b/_analyzers/tokenizers/standard.md new file mode 100644 index 00000000..ca00f1aa --- /dev/null +++ b/_analyzers/tokenizers/standard.md @@ -0,0 +1,130 @@ +--- +layout: default +title: Standard +parent: Tokenizers +nav_order: 130 +--- + +# Standard tokenizer + +The `standard` tokenizer is the default tokenizer in OpenSearch. It tokenizes text based on word boundaries using a grammar-based approach that recognizes letters, digits, and other characters like punctuation. It is highly versatile and suitable for many languages because it uses Unicode text segmentation rules ([UAX#29](https://unicode.org/reports/tr29/)) to break text into tokens. + +## Tokenization rules + +The `standard` tokenizer follows the word boundary rules defined in [Unicode Standard Annex #29: Unicode Text Segmentation](https://unicode.org/reports/tr29/). The following table summarizes how these rules apply to common input. + +Input | Rule | Tokens +:--- | :--- | :--- +`fast, and scalable.` | Whitespace and most punctuation, such as commas, hyphens, slashes, `+`, `#`, `%`, and `@`, split text and are removed. | `fast`, `and`, `scalable` +`can't`, `O'Neil` | An apostrophe between two letters does not split the word. | `can't`, `O'Neil` +`end. Next` | A period followed by a space splits the text. | `end`, `Next` +`hello.world`, `U.S.A.` | A period between two letters does not split the word. A trailing period is removed. | `hello.world`, `U.S.A` +`3.5`, `1,000`, `v1.2.3` | A period or comma between two digits does not split the number. | `3.5`, `1,000`, `v1.2.3` +`snake_case` | Underscores do not split words. | `snake_case` +`state-of-the-art` | Hyphens split words. | `state`, `of`, `the`, `art` +`admin@example.com` | Email addresses are split at the `@` sign. | `admin`, `example.com` +`https://opensearch.org/docs` | URLs are split at the colon and slashes. | `https`, `opensearch.org`, `docs` +`東京`, `こんにちは` | Each ideographic and hiragana character becomes a separate token. | `東`, `京`, `こ`, `ん`, `に`, `ち`, `は` + +To keep email addresses and URLs as single tokens, use the [`uax_url_email` tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/uax-url-email/). Tokens longer than `max_token_length` are split at that length. For more information, see [Parameters](#parameters). + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `standard` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_standard_analyzer": { + "type": "standard" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_standard_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_standard_analyzer", + "text": "OpenSearch is powerful, fast, and scalable." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 10, + "type": "", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "", + "position": 1 + }, + { + "token": "powerful", + "start_offset": 14, + "end_offset": 22, + "type": "", + "position": 2 + }, + { + "token": "fast", + "start_offset": 24, + "end_offset": 28, + "type": "", + "position": 3 + }, + { + "token": "and", + "start_offset": 30, + "end_offset": 33, + "type": "", + "position": 4 + }, + { + "token": "scalable", + "start_offset": 34, + "end_offset": 42, + "type": "", + "position": 5 + } + ] +} +``` + +## Parameters + +The `standard` tokenizer can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`max_token_length` | Optional | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. + diff --git a/_analyzers/tokenizers/thai.md b/_analyzers/tokenizers/thai.md new file mode 100644 index 00000000..4afb14a9 --- /dev/null +++ b/_analyzers/tokenizers/thai.md @@ -0,0 +1,108 @@ +--- +layout: default +title: Thai +parent: Tokenizers +nav_order: 140 +--- + +# Thai tokenizer + +The `thai` tokenizer tokenizes Thai language text. Because words in Thai language are not separated by spaces, the tokenizer must identify word boundaries based on language-specific rules. + +## Example usage + +The following example request creates a new index named `thai_index` and configures an analyzer with a `thai` tokenizer: + +```json +PUT /thai_index +{ + "settings": { + "analysis": { + "tokenizer": { + "thai_tokenizer": { + "type": "thai" + } + }, + "analyzer": { + "thai_analyzer": { + "type": "custom", + "tokenizer": "thai_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "thai_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /thai_index/_analyze +{ + "analyzer": "thai_analyzer", + "text": "ฉันชอบไปเที่ยวที่เชียงใหม่" +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "ฉัน", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "ชอบ", + "start_offset": 3, + "end_offset": 6, + "type": "word", + "position": 1 + }, + { + "token": "ไป", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 2 + }, + { + "token": "เที่ยว", + "start_offset": 8, + "end_offset": 14, + "type": "word", + "position": 3 + }, + { + "token": "ที่", + "start_offset": 14, + "end_offset": 17, + "type": "word", + "position": 4 + }, + { + "token": "เชียงใหม่", + "start_offset": 17, + "end_offset": 26, + "type": "word", + "position": 5 + } + ] +} +``` diff --git a/_analyzers/tokenizers/uax-url-email.md b/_analyzers/tokenizers/uax-url-email.md new file mode 100644 index 00000000..34336a4f --- /dev/null +++ b/_analyzers/tokenizers/uax-url-email.md @@ -0,0 +1,84 @@ +--- +layout: default +title: UAX URL email +parent: Tokenizers +nav_order: 150 +--- + +# UAX URL email tokenizer + +In addition to regular text, the `uax_url_email` tokenizer is designed to handle URLs, email addresses, and domain names. It is based on the Unicode Text Segmentation algorithm ([UAX #29](https://www.unicode.org/reports/tr29/)), which allows it to correctly tokenize complex text, including URLs and email addresses. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `uax_url_email` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "uax_url_email_tokenizer": { + "type": "uax_url_email" + } + }, + "analyzer": { + "my_uax_analyzer": { + "type": "custom", + "tokenizer": "uax_url_email_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_uax_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_uax_analyzer", + "text": "Contact us at support@example.com or visit https://example.com for details." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + {"token": "Contact","start_offset": 0,"end_offset": 7,"type": "","position": 0}, + {"token": "us","start_offset": 8,"end_offset": 10,"type": "","position": 1}, + {"token": "at","start_offset": 11,"end_offset": 13,"type": "","position": 2}, + {"token": "support@example.com","start_offset": 14,"end_offset": 33,"type": "","position": 3}, + {"token": "or","start_offset": 34,"end_offset": 36,"type": "","position": 4}, + {"token": "visit","start_offset": 37,"end_offset": 42,"type": "","position": 5}, + {"token": "https://example.com","start_offset": 43,"end_offset": 62,"type": "","position": 6}, + {"token": "for","start_offset": 63,"end_offset": 66,"type": "","position": 7}, + {"token": "details","start_offset": 67,"end_offset": 74,"type": "","position": 8} + ] +} +``` + +## Parameters + +The `uax_url_email` tokenizer can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`max_token_length` | Optional | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. + diff --git a/_analyzers/tokenizers/whitespace.md b/_analyzers/tokenizers/whitespace.md new file mode 100644 index 00000000..693b39f3 --- /dev/null +++ b/_analyzers/tokenizers/whitespace.md @@ -0,0 +1,110 @@ +--- +layout: default +title: White space +parent: Tokenizers +nav_order: 160 +--- + +# White space tokenizer + +The `whitespace` tokenizer splits text on white space characters, such as spaces, tabs, and new lines. It treats each word separated by white space as a token and does not perform any additional analysis or normalization like lowercasing or punctuation removal. + +## Example usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `whitespace` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "whitespace_tokenizer": { + "type": "whitespace" + } + }, + "analyzer": { + "my_whitespace_analyzer": { + "type": "custom", + "tokenizer": "whitespace_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_whitespace_analyzer" + } + } + } +} +``` +{% include copy-curl.html %} + +## Generated tokens + +Use the following request to examine the tokens generated using the analyzer: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_whitespace_analyzer", + "text": "OpenSearch is fast! Really fast." +} +``` +{% include copy-curl.html %} + +The response contains the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "word", + "position": 1 + }, + { + "token": "fast!", + "start_offset": 14, + "end_offset": 19, + "type": "word", + "position": 2 + }, + { + "token": "Really", + "start_offset": 20, + "end_offset": 26, + "type": "word", + "position": 3 + }, + { + "token": "fast.", + "start_offset": 27, + "end_offset": 32, + "type": "word", + "position": 4 + } + ] +} +``` + +## Parameters + +The `whitespace` tokenizer can be configured with the following parameter. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`max_token_length` | Optional | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. + diff --git a/_api-reference/alias/alias-exists.md b/_api-reference/alias/alias-exists.md new file mode 100644 index 00000000..871272ed --- /dev/null +++ b/_api-reference/alias/alias-exists.md @@ -0,0 +1,80 @@ +--- +layout: default +title: Alias exists +parent: Alias APIs +grand_parent: Index APIs +nav_order: 40 +--- + +# Index Alias Exists API +**Introduced 1.0** +{: .label .label-purple } + +Checks if an alias exists. + +## Endpoints + +```json +HEAD /_alias/{alias} +HEAD /{index}/_alias/{alias} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `` | String | Comma-separated list or wildcard expression of alias names to check. | +| `` | String | Comma-separated list or wildcard expression of index names used to limit the request. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `expand_wildcards` | String | Type of index that wildcard expressions can match. Supports comma-separated values. Valid values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `all`. | +| `ignore_unavailable` | Boolean | Whether to ignore unavailable indexes. Default is `false`. | +| `local` | Boolean | Whether to return information from the local node only instead of from the cluster manager node. Default is `false`. | + +## Response codes + +The API returns one of the following response codes. + +| Response code | Description | +| :--- | :--- | +| `200` | Indicates that all specified aliases exist. | +| `404` | Indicates that one or more specified aliases do not exist. | + +## Example requests + + +{% capture step1_rest %} +HEAD /_alias/2030 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.exists_alias( + name = "2030" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/aliases/get`. + +## Related documentation + +For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). \ No newline at end of file diff --git a/_api-reference/alias/aliases-api.md b/_api-reference/alias/aliases-api.md new file mode 100644 index 00000000..b9d9bf9e --- /dev/null +++ b/_api-reference/alias/aliases-api.md @@ -0,0 +1,524 @@ +--- +layout: default +title: Manage aliases +parent: Alias APIs +grand_parent: Index APIs +nav_order: 50 +redirect_from: + - /api-reference/index-apis/alias/ +--- + +# Manage Aliases API +**Introduced 1.0** +{: .label .label-purple } + +The Manage aliases API performs multiple index alias operations in a single atomic transaction. Use this API when you need to add or remove multiple aliases, switch an alias from one index to another, or delete indexes while managing their aliases simultaneously. This API accepts an array of actions, making it ideal for complex alias operations that must happen atomically. + +This API is distinct from the [Create or update alias API]({{site.url}}{{site.baseurl}}/api-reference/alias/create-alias/), which operates on a single alias at a time and uses different request parameters. Use the Manage aliases API for bulk operations and atomic transactions involving multiple aliases or indexes. + +For conceptual information about index aliases, including use cases and examples, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). + + +## Endpoints + +```json +POST _aliases +``` + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time to wait for a response from the cluster. Default is `30s`. + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description | Required +:--- | :--- | :--- | :--- +`actions` | Array | Set of actions you want to perform on the index. Valid options are: `add`, `remove`, and `remove_index`. You must have at least one action in the array. | Yes +`add` | N/A | Adds an alias to the specified index. | No +`remove` | N/A | Removes an alias from the specified index. | No +`remove_index` | N/A | Deletes an index. | No +`index` | String | Name of the index you want to associate with the alias. Supports wildcard expressions. | Yes if you don't supply an `indices` field in the body. +`indices` | Array | Array of index names you want to associate with the alias. | Yes if you don't supply an `index` field in the body. +`alias` | String | The name of the alias. | Yes if you don't supply an `aliases` field in the body. +`aliases` | Array | Array of alias names. | Yes if you don't supply an `alias` field in the body. +`filter` | Object | A filter to use with the alias, so the alias points to a filtered part of the index. | No +`is_hidden` | Boolean | Specifies whether the alias should be hidden from results that include wildcard expressions | No +`must_exist` | Boolean | Specifies whether the alias to remove must exist. | No +`is_write_index` | Boolean | Specifies whether the index should be a write index. An alias can only have one write index at a time. If a write request is submitted to a alias that links to multiple indexes, OpenSearch executes the request only on the write index. **Important**: Aliases that don't explicitly set `is_write_index: true` for an index and only reference one index will have that index behave as the write index until another index is referenced. At that point, there will be no write index and writes will be rejected. | No +`routing` | String | Used to assign a custom value to a shard for specific operations. | No +`index_routing` | String | Assigns a custom value to a shard only for index operations. | No +`search_routing` | String | Assigns a custom value to a shard only for search operations. | No + +## Example: Add an alias + +The following request creates an alias called `logs_current` that points to the `application_logs_2024` index: + + +{% capture step1_rest %} +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.update_aliases( + body = { + "actions": [ + { + "add": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Remove an alias + +The following request removes the `logs_current` alias from the `application_logs_2024` index: + + +{% capture step1_rest %} +POST /_aliases +{ + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.update_aliases( + body = { + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Rename an alias + +You can atomically rename an alias by removing it from one index and adding it to another in the same request. The following example moves the `primary_data` alias from `dataset_v1` to `dataset_v2`: + +```json +POST /_aliases +{ + "actions": [ + { + "remove": { + "index": "dataset_v1", + "alias": "primary_data" + } + }, + { + "add": { + "index": "dataset_v2", + "alias": "primary_data" + } + } + ] +} +``` +{% include copy-curl.html %} + +Alias operations are atomic, meaning there's no moment when `primary_data` points to both indexes or to neither index. +{: .important} + +## Example: Add an alias to multiple indexes + +You can associate a single alias with multiple indexes using separate `add` actions: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "products_electronics", + "alias": "all_products" + } + }, + { + "add": { + "index": "products_clothing", + "alias": "all_products" + } + }, + { + "add": { + "index": "products_books", + "alias": "all_products" + } + } + ] +} +``` +{% include copy-curl.html %} + + + +## Example: Use the indices array + + +Alternatively, you can specify multiple indexes in a single action using the `indices` array: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "indices": ["products_electronics", "products_clothing", "products_books"], + "alias": "all_products" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example: Use wildcard patterns + +You can use wildcard patterns to add multiple indexes that match a naming pattern. The following example creates an alias for all indexes that start with `sales_2024`: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "sales_2024_*", + "alias": "current_year_sales" + } + } + ] +} +``` +{% include copy-curl.html %} + +This creates a point-in-time alias that includes all indexes matching the pattern at the time of creation. It does not automatically include new indexes created later that match the pattern. +{: .note} + +It is an error to write to an alias that points to multiple indexes unless you specify a write index. +{: .important} + +## Example: Index swapping + +You can atomically replace an index with a new one without downtime. This is useful for reindexing operations: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "customer_data_new", + "alias": "customer_data" + } + }, + { + "remove_index": { + "index": "customer_data_old" + } + } + ] +} +``` +{% include copy-curl.html %} + +This operation adds the new index to the alias and deletes the old index in a single atomic operation. + +## Example: Filtered aliases + +Filtered aliases enable you to segment data within an index by applying query filters. This allows you to create focused subsets of your data accessible through separate alias names. First, ensure your index has the necessary field mappings: + +```json +PUT /user_activity +{ + "mappings": { + "properties": { + "user_type": { + "type": "keyword" + }, + "timestamp": { + "type": "date" + }, + "action": { + "type": "keyword" + } + } + } +} +``` +{% include copy-curl.html %} + +Then create filtered aliases to segment your data: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "user_activity", + "alias": "premium_users", + "filter": { + "term": { + "user_type": "premium" + } + } + } + }, + { + "add": { + "index": "user_activity", + "alias": "recent_activity", + "filter": { + "range": { + "timestamp": { + "gte": "now-7d" + } + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +These aliases apply the specified filters automatically to all search, count, and delete by query operations. + +## Example: Basic routing + +Routing allows you to direct operations to specific shards, improving performance by reducing the number of shards that need to be queried. + +The following example creates an alias with a routing value: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "customer_orders", + "alias": "region_east_orders", + "routing": "east" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example: Separate routing for index and search operations + +You can specify different routing values for indexing and searching: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "user_sessions", + "alias": "mobile_sessions", + "index_routing": "mobile", + "search_routing": "mobile,tablet" + } + } + ] +} +``` +{% include copy-curl.html %} + +In this example, all documents indexed through the alias go to the "mobile" shard, but searches can query both "mobile" and "tablet" shards. + +When you perform a search with both alias routing and a routing parameter, OpenSearch uses the intersection of both values. For example, if you search `GET /mobile_sessions/_search?routing=tablet,mobile`, only the "mobile" routing value will be used since it's the intersection of the alias routing (`mobile,tablet`) and the search parameter (`tablet,mobile`). +{: .note} + +## Example: Setting a write index + +When an alias points to multiple indexes, you must specify which index should handle write operations. + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "logs_2024_01", + "alias": "active_logs", + "is_write_index": true + } + }, + { + "add": { + "index": "logs_2024_02", + "alias": "active_logs", + "is_write_index": false + } + } + ] +} +``` +{% include copy-curl.html %} + +Now you can write to the alias, and all write operations will go to `logs_2024_01`: + +```json +POST /active_logs/_doc +{ + "timestamp": "2024-01-15T10:30:00", + "level": "INFO", + "message": "Application started successfully" +} +``` +{% include copy-curl.html %} + +## Example: Switch the write index + +You can atomically switch which index serves as the write index: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "logs_2024_01", + "alias": "active_logs", + "is_write_index": false + } + }, + { + "add": { + "index": "logs_2024_02", + "alias": "active_logs", + "is_write_index": true + } + } + ] +} +``` +{% include copy-curl.html %} + +> Keep the following important considerations in mind when working with write indexes: +> - An alias can have only one write index at a time. +> - If an alias points to multiple indexes without a designated write index, write operations will be rejected. +> - For aliases pointing to a single index, that index automatically serves as the write index. +{: .important} + +## Example: Use the must_exist parameter + +OpenSearch provides a `must_exist` parameter for remove operations that controls error handling when removing non-existent aliases: + +```json +POST /_aliases +{ + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current", + "must_exist": true + } + } + ] +} +``` +{% include copy-curl.html %} + +- `must_exist: true` - Throws an error if the alias doesn't exist +- `must_exist: false` - Silently succeeds even if the alias doesn't exist +- `must_exist: null` (default) - Throws an error only if none of the specified aliases exist + +## Example response + +All successful alias operations return the same response format: + +```json +{ + "acknowledged": true +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/aliases/get`. + +## Related documentation + +For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). \ No newline at end of file diff --git a/_api-reference/alias/create-alias.md b/_api-reference/alias/create-alias.md new file mode 100644 index 00000000..817a8320 --- /dev/null +++ b/_api-reference/alias/create-alias.md @@ -0,0 +1,325 @@ +--- +layout: default +title: Create or update alias +parent: Alias APIs +grand_parent: Index APIs +nav_order: 10 +redirect_from: + - /api-reference/index-apis/update-alias/ +--- + +# Create Or Update Index Alias API +**Introduced 1.0** +{: .label .label-purple } + +The Create or Update Alias API adds one or more indexes to an index alias or updates the settings for an existing alias. For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). + +The Create or Update Alias API is distinct from the [Manage aliases API]({{site.url}}{{site.baseurl}}/api-reference/alias/aliases-api/), which supports the addition and removal of aliases and the removal of indexes with their aliases. In contrast, the following API only supports adding or updating an alias without updating the index itself. Each API also uses different request body parameters. +{: .note} + +## Endpoints + +```json +POST /{target}/_alias/{alias-name} +PUT /{target}/_alias/{alias-name} +POST /_alias/{alias-name} +PUT /_alias/{alias-name} +POST /{target}/_aliases/{alias-name} +PUT /{target}/_aliases/{alias-name} +POST /_aliases/{alias-name} +PUT /_aliases/{alias-name} +PUT /{target}/_alias +PUT /{target}/_aliases +PUT /_alias +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Type | Description | +:--- | :--- | :--- +| `target` | String | A comma-delimited list of indexes. Wildcard expressions (`*`) are supported. To target all indexes in a cluster, use `_all` or `*`. Optional. | +| `alias-name` | String | The alias name to be created or updated. Optional. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time to wait for a response from the cluster. Default is `30s`. + +## Request body + +The following table lists the available request body fields. + +Field | Type | Description +:--- | :--- | :--- | :--- +`index` | String | A comma-delimited list of indexes that you want to associate with the alias. If this field is set, it will override the index name specified in the URL path. +`alias` | String | The name of the alias. If this field is set, it will override the alias name specified in the URL path. +`is_write_index` | Boolean | Specifies whether the index should be a write index. An alias can only have one write index at a time. If a write request is submitted to an alias that links to multiple indexes, then OpenSearch runs the request only on the write index. +`routing` | String | Assigns a custom value to a shard for specific operations. +`index_routing` | String | Assigns a custom value to a shard only for index operations. +`search_routing` | String | Assigns a custom value to a shard only for search operations. +`filter` | Object | A filter to use with the alias so that the alias points to a filtered part of the index. + +## Example request: Add a simple alias + +The following request creates a basic alias for an index: + + +{% capture step1_rest %} +PUT /products-2024/_alias/current-products +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_alias( + name = "current-products", + index = "products-2024" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Add a time-based alias + +The following request creates an alias `quarterly-2024` for the `sales-q1-2024` index: + + +{% capture step1_rest %} +PUT /sales-q1-2024/_alias/quarterly-2024 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_alias( + name = "quarterly-2024", + index = "sales-q1-2024" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Add a filtered alias with routing + +First, create an index with appropriate mappings: + + +{% capture step1_rest %} +PUT /customer-data +{ + "mappings": { + "properties": { + "customer_id": { + "type": "integer" + }, + "region": { + "type": "keyword" + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "customer-data", + body = { + "mappings": { + "properties": { + "customer_id": { + "type": "integer" + }, + "region": { + "type": "keyword" + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Then add the index alias for a specific customer with routing and filtering: + + +{% capture step1_rest %} +PUT /customer-data/_alias/customer-123 +{ + "routing": "west", + "filter": { + "term": { + "customer_id": 123 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_alias( + name = "customer-123", + index = "customer-data", + body = { + "routing": "west", + "filter": { + "term": { + "customer_id": 123 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Add an alias during index creation + +You can add an alias when creating an index using the create index API: + + +{% capture step1_rest %} +PUT /inventory-2024 +{ + "mappings": { + "properties": { + "category": { + "type": "keyword" + } + } + }, + "aliases": { + "current-inventory": {}, + "electronics": { + "filter": { + "term": { + "category": "electronics" + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "inventory-2024", + body = { + "mappings": { + "properties": { + "category": { + "type": "keyword" + } + } + }, + "aliases": { + "current-inventory": {}, + "electronics": { + "filter": { + "term": { + "category": "electronics" + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/aliases`. + +## Related documentation + +For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). diff --git a/_api-reference/alias/delete-alias.md b/_api-reference/alias/delete-alias.md new file mode 100644 index 00000000..edf641d1 --- /dev/null +++ b/_api-reference/alias/delete-alias.md @@ -0,0 +1,89 @@ +--- +layout: default +title: Delete alias +parent: Alias APIs +grand_parent: Index APIs +nav_order: 30 +--- + +# Delete Index Alias API +**Introduced 1.0** +{: .label .label-purple } + +Deletes an existing alias. + +## Endpoints + +```json +DELETE /{index}/_alias/{alias} +DELETE /{index}/_aliases/{alias} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `` | String | Comma-separated list or wildcard expression of index names used to limit the request. To include all indexes in the cluster, use `_all` or `*`. | +| `` | String | Comma-separated list or wildcard expression of alias names to delete. To delete all aliases, use `_all` or `*`. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Default is `30s`. | +| `timeout` | Time | The amount of time to wait for a response from the cluster. Default is `30s`. | + +## Example request + +The following request deletes the `alias1` alias from the `logs_20302801` index: + + +{% capture step1_rest %} +DELETE /logs_20302801/_alias/alias1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.delete_alias( + index = "logs_20302801", + name = "alias1" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | Whether the request was received. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/aliases`. + +## Related documentation + +For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). \ No newline at end of file diff --git a/_api-reference/alias/get-alias.md b/_api-reference/alias/get-alias.md new file mode 100644 index 00000000..36410eaf --- /dev/null +++ b/_api-reference/alias/get-alias.md @@ -0,0 +1,226 @@ +--- +layout: default +title: Get alias +parent: Alias APIs +grand_parent: Index APIs +nav_order: 20 +--- + +# Get Index Alias API +**Introduced 1.0** +{: .label .label-purple } + +Returns information about one or more aliases. + +## Endpoints + +```json +GET /_alias +GET /_alias/{alias} +GET /{index}/_alias/{alias} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `` | String | Comma-separated list or wildcard expression of alias names to retrieve. To retrieve information for all index aliases, use `_all` or `*`. | +| `` | String | Comma-separated list or wildcard expression of index names used to limit the request. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. | +| `expand_wildcards` | String | Type of index that wildcard expressions can match. Supports comma-separated values. Valid values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `all`. | +| `ignore_unavailable` | Boolean | Whether to ignore unavailable indexes. Default is `false`. | +| `local` | Boolean | Whether to return information from the local node only instead of from the cluster manager node. Default is `false`. | + +## Example request: Get all aliases for an index + +You can add index aliases during index creation using a create index API request. + +The following create index API request creates the `logs_20302801` index with two aliases: + +- `current_day` +- `2030`, which only returns documents in the `logs_20302801` index with a `year` field value of `2030` + + +{% capture step1_rest %} +PUT /logs_20302801 +{ + "aliases": { + "current_day": {}, + "2030": { + "filter": { + "term": { + "year": 2030 + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "logs_20302801", + body = { + "aliases": { + "current_day": {}, + "2030": { + "filter": { + "term": { + "year": 2030 + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The following get index alias API request returns all aliases for the index `logs_20302801`: + + +{% capture step1_rest %} +GET /logs_20302801/_alias/* +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_alias( + name = "*", + index = "logs_20302801" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Get a specific alias + +The following index alias API request returns the `2030` alias: + + +{% capture step1_rest %} +GET /_alias/2030 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_alias( + name = "2030" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Get aliases based on a wildcard + +The following index alias API request returns any alias that begins with `20`: + + +{% capture step1_rest %} +GET /_alias/20* +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_alias( + name = "20*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "logs_20302801" : { + "aliases" : { + "current_day" : { + }, + "2030" : { + "filter" : { + "term" : { + "year" : 2030 + } + } + } + } + } +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `` | Object | Contains aliases for the index. | +| `.aliases` | Object | Contains alias information for the index. | +| `.aliases.` | Object | Contains configuration for the alias. | +| `.aliases..filter` | Object | Query used to limit documents the alias can access. | +| `.aliases..index_routing` | String | Routing value used for indexing operations. | +| `.aliases..search_routing` | String | Routing value used for search operations. | +| `.aliases..is_write_index` | Boolean | Whether the index is the write index for the alias. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/aliases/get`. + +## Related documentation + +For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). \ No newline at end of file diff --git a/_api-reference/alias/index.md b/_api-reference/alias/index.md new file mode 100644 index 00000000..bf4f9e18 --- /dev/null +++ b/_api-reference/alias/index.md @@ -0,0 +1,35 @@ +--- +layout: default +title: Alias APIs +parent: Index APIs +nav_order: 45 +has_children: true +has_toc: false +redirect_from: + - /opensearch/rest-api/alias/ + - /api-reference/alias-api/ + - /api-reference/alias/ +--- + +# Alias APIs + +OpenSearch index alias APIs allow you to create, update, delete, and retrieve information about aliases. + +For conceptual information about index aliases, including use cases and examples, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). + +## Available APIs + +OpenSearch supports the following index alias APIs. + +| API | Description | +|-----|-------------| +| [Manage aliases]({{site.url}}{{site.baseurl}}/api-reference/alias/aliases-api/) | Adds or removes aliases. | +| [Create or update alias]({{site.url}}{{site.baseurl}}/api-reference/alias/create-alias/) | Creates or updates an alias. | +| [Get index alias]({{site.url}}{{site.baseurl}}/api-reference/alias/get-alias/) | Returns information about one or more aliases. | +| [Delete index alias]({{site.url}}{{site.baseurl}}/api-reference/alias/delete-alias/) | Deletes an existing alias. | +| [Index alias exists]({{site.url}}{{site.baseurl}}/api-reference/alias/alias-exists/) | Checks if an alias exists. | +| [CAT aliases]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-aliases/) | Lists aliases in a tabular format with routing and filtering information. | + +## Related documentation + +For more information about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). \ No newline at end of file diff --git a/_api-reference/analyze-apis.md b/_api-reference/analyze-apis.md index 7c61a6fd..4b86c472 100644 --- a/_api-reference/analyze-apis.md +++ b/_api-reference/analyze-apis.md @@ -1,66 +1,66 @@ --- layout: default title: Analyze API -has_children: true -nav_order: 7 +nav_order: 5 redirect_from: + - /api-reference/analyze-apis/perform-text-analysis/ - /opensearch/rest-api/analyze-apis/ - - /api-reference/analyze-apis/ + - /api-reference/analyze-apis/terminology/ + - /api-reference/analyze-apis/index/ --- # Analyze API **Introduced 1.0** {: .label .label-purple } -The Analyze API allows you to perform [text analysis]({{site.url}}{{site.baseurl}}/api-reference/analyze-apis/), which is the process of converting unstructured text into individual tokens (usually words) that are optimized for search. +The Analyze API allows you to perform [text analysis]({{site.url}}{{site.baseurl}}/analyzers/), which is the process of converting unstructured text into individual tokens (usually words) that are optimized for search. For more information about common analysis components such as character filters, tokenizers, token filters, and normalizers, see [Analyzers]({{site.url}}{{site.baseurl}}/analyzers/#analyzers). The Analyze API analyzes a text string and returns the resulting tokens. -If you use the Security plugin, you must have the `manage index` privilege. If you only want to analyze text, you must have the `manage cluster` privilege. -{: .note} +## Endpoints -## Path and HTTP methods - -``` +```json GET /_analyze GET /{index}/_analyze POST /_analyze POST /{index}/_analyze ``` -Although you can issue an analyze request using both `GET` and `POST` requests, the two have important distinctions. A `GET` request causes data to be cached in the index so that the next time the data is requested, it is retrieved faster. A `POST` request sends a string that does not already exist to the analyzer to be compared with data that is already in the index. `POST` requests are not cached. -{: .note} - ## Path parameter You can include the following optional path parameter in your request. Parameter | Data type | Description :--- | :--- | :--- -index | String | Index that is used to derive the analyzer. +`index` | String | Index that is used to derive the analyzer. ## Query parameters -You can include the following optional query parameters in your request. +You can include the following optional query parameter in your request. + +Parameter | Data type | Description +:--- | :--- | :--- +`index` | String | Index that is used to derive the analyzer. Use this parameter as an alternative to the `index` path parameter. + +## Request body fields + +The following table lists the available request body fields. Field | Data type | Description :--- | :--- | :--- -analyzer | String | The name of the analyzer to apply to the `text` field. The analyzer can be built in or configured in the index.

If `analyzer` is not specified, the analyze API uses the analyzer defined in the mapping of the `field` field.

If the `field` field is not specified, the analyze API uses the default analyzer for the index.

If no index is specified or the index does not have a default analyzer, the analyze API uses the standard analyzer. -attributes | Array of Strings | Array of token attributes for filtering the output of the `explain` field. -char_filter | Array of Strings | Array of character filters for preprocessing characters before the `tokenizer` field. -explain | Boolean | If true, causes the response to include token attributes and additional details. Defaults to `false`. -field | String | Field for deriving the analyzer.

If you specify `field`, you must also specify the `index` path parameter.

If you specify the `analyzer` field, it overrides the value of `field`.

If you do not specify `field`, the analyze API uses the default analyzer for the index.

If you do not specify the `index` field, or the index does not have a default analyzer, the analyze API uses the standard analyzer. -filter | Array of Strings | Array of token filters to apply after the `tokenizer` field. -normalizer | String | Normalizer for converting text into a single token. -tokenizer | String | Tokenizer for converting the `text` field into tokens. +`text` | String or Array of Strings | The text to analyze. If you provide an array of strings, the text is analyzed as a multi-value field. Required. +`analyzer` | String | The name of the analyzer to apply to the `text` field. The analyzer can be built or configured in the index.

If `analyzer` is not specified, the Analyze API uses the analyzer defined in the mapping of the `field` field.

If the `field` field is not specified, the Analyze API uses the default analyzer for the index.

If no index is specified or the index does not have a default analyzer, the Analyze API uses the [standard analyzer]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/standard/). Optional. See [Analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/index/). +`attributes` | Array of Strings | An array of token attributes to include in the `detail` output. Applies only when `explain` is `true`. +`char_filter` | Array of strings or objects | An array of character filters for preprocessing characters before the `tokenizer` field. Each array element is either the name of a character filter or an inline character filter definition. Optional. See [Character filters]({{site.url}}{{site.baseurl}}/analyzers/character-filters/index/). +`explain` | Boolean | If `true`, causes the response to include token attributes and additional details. Optional. Default is `false`. +`field` | String | The field for deriving the analyzer.

If you specify `field`, you must also specify an index in the `index` path or query parameter.

If you specify the `analyzer` field, it overrides the value of `field`.

If the field is not mapped, the Analyze API uses the default analyzer for the index. Optional. +`filter` | Array of strings or objects | Array of token filters to apply after the `tokenizer` field. Each array element is either the name of a token filter or an inline token filter definition. Optional. See [Token filters]({{site.url}}{{site.baseurl}}/analyzers/token-filters/index/). +`normalizer` | String | A normalizer for converting text into a single token. If you specify `normalizer`, you must also specify an index in the `index` path or query parameter. Optional. See [Normalizers]({{site.url}}{{site.baseurl}}/analyzers/normalizers/). +`tokenizer` | String or Object | A tokenizer for converting the `text` field into tokens. Specify either the name of a tokenizer or an inline tokenizer definition. Optional. See [Tokenizers]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/index/). -The following query parameter is required. +The `analyzer`, `normalizer`, and `field` fields cannot be combined with the `tokenizer`, `filter`, or `char_filter` fields. The `analyzer` and `normalizer` fields cannot be combined with each other. If you specify `filter` or `char_filter` without `tokenizer`, the Analyze API builds a custom normalizer from the filters, so you can only use filters that are supported in normalizers. -Field | Data type | Description -:--- | :--- | :--- -text | String or Array of Strings | Text to analyze. If you provide an array of strings, the text is analyzed as a multi-value field. - -#### Example requests +## Example requests [Analyze array of text strings](#analyze-array-of-text-strings) @@ -80,18 +80,89 @@ text | String or Array of Strings | Text to analyze. If you provide an array of [Set a token limit](#set-a-token-limit) -#### Analyze array of text strings +Some of the following examples use the `books` and `books2` indexes. To run these examples, first create the `books` index using the default settings: + +```json +PUT /books +``` +{% include copy-curl.html %} + +Then create the `books2` index. The index defines a custom analyzer named `lowercase_ascii_folding` and a custom normalizer named `to_lower_fold_ascii`, both of which convert text to lowercase and convert non-ASCII characters to ASCII. The index also maps the `name` field as a `text` field: + +```json +PUT /books2 +{ + "settings": { + "analysis": { + "analyzer": { + "lowercase_ascii_folding": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "asciifolding"] + } + }, + "normalizer": { + "to_lower_fold_ascii": { + "type": "custom", + "filter": ["lowercase", "asciifolding"] + } + } + } + }, + "mappings": { + "properties": { + "name": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +### Analyze array of text strings When you pass an array of strings to the `text` field, it is analyzed as a multi-value field. -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "analyzer": "standard", + "text": [ + "first array element", + "second array element" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "analyzer": "standard", + "text": [ + "first array element", + "second array element" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -144,20 +215,45 @@ The previous request returns the following fields: } ```` -#### Apply a built-in analyzer +### Apply a built-in analyzer -If you omit the `index` path parameter, you can apply any of the built-in analyzers to the text string. +You can apply any of the built-in analyzers to the text string without specifying an index. The following request analyzes text using the `standard` built-in analyzer: -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "analyzer": "standard", + "text": "OpenSearch text analysis" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "analyzer": "standard", + "text": "OpenSearch text analysis" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -189,22 +285,48 @@ The previous request returns the following fields: } ```` -#### Apply a custom analyzer +### Apply a custom analyzer You can create your own analyzer and specify it in an analyze request. -In this scenario, a custom analyzer `lowercase_ascii_folding` has been created and associated with the `books2` index. The analyzer converts text to lowercase and converts non-ASCII characters to ASCII. +The `books2` index defines the custom `lowercase_ascii_folding` analyzer, which converts text to lowercase and converts non-ASCII characters to ASCII. The following request applies the custom analyzer to the provided text: -````json -GET /books2/_analyze + +{% capture step1_rest %} +GET /books2/_analyze +{ + "analyzer": "lowercase_ascii_folding", + "text": "Le garçon m'a SUIVI." +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + index = "books2", + body = { + "analyzer": "lowercase_ascii_folding", + "text": "Le garçon m'a SUIVI." + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -243,21 +365,52 @@ The previous request returns the following fields: } ```` -#### Apply a custom transient analyzer +### Apply a custom transient analyzer -You can build a custom transient analyzer from tokenizers, token filters, or character filters. Use the `filter` parameter to specify token filters. +You can build a custom transient analyzer from tokenizers, token filters, or character filters. Use the `filter` parameter to specify token filters and the `char_filter` parameter to specify character filters. -The following request uses the `uppercase` character filter to convert the text to uppercase: +The following request uses the `uppercase` token filter to convert the text to uppercase: -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "tokenizer": "keyword", + "filter": [ + "uppercase" + ], + "text": "OpenSearch filter" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "tokenizer": "keyword", + "filter": [ + "uppercase" + ], + "text": "OpenSearch filter" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -276,22 +429,59 @@ The previous request returns the following fields: ````
-The following request uses the `html_strip` filter to remove HTML characters from the text: +The following request uses the `html_strip` character filter to remove HTML tags from the text: -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "tokenizer": "keyword", + "filter": [ + "lowercase" + ], + "char_filter": [ + "html_strip" + ], + "text": "Leave right now!" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "tokenizer": "keyword", + "filter": [ + "lowercase" + ], + "char_filter": [ + "html_strip" + ], + "text": "Leave right now!" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: -```` json +````json { "tokens" : [ { @@ -311,15 +501,60 @@ You can combine filters using an array. The following request combines a `lowercase` translation with a `stop` filter that removes the words in the `stopwords` array: -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "tokenizer": "whitespace", + "filter": [ + "lowercase", + { + "type": "stop", + "stopwords": [ + "to", + "in" + ] + } + ], + "text": "how to train your dog in five steps" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "tokenizer": "whitespace", + "filter": [ + "lowercase", + { + "type": "stop", + "stopwords": [ + "to", + "in" + ] + } + ], + "text": "how to train your dog in five steps" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -372,24 +607,48 @@ The previous request returns the following fields: } ```` -#### Specify an index +### Specify an index You can analyze text using an index's default analyzer, or you can specify a different analyzer. The following request analyzes the provided text using the default analyzer associated with the `books` index: -````json -GET /books/_analyze + +{% capture step1_rest %} +GET /books/_analyze +{ + "text": "OpenSearch analyze test" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + index = "books", + body = { + "text": "OpenSearch analyze test" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: ````json - +{ "tokens" : [ { "token" : "opensearch", @@ -420,14 +679,40 @@ The previous request returns the following fields: The following request analyzes the provided text using the `keyword` analyzer, which returns the entire text value as a single token: -````json -GET /books/_analyze + +{% capture step1_rest %} +GET /books/_analyze +{ + "analyzer": "keyword", + "text": "OpenSearch analyze test" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + index = "books", + body = { + "analyzer": "keyword", + "text": "OpenSearch analyze test" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -445,22 +730,48 @@ The previous request returns the following fields: } ```` -#### Derive the analyzer from an index field +### Derive the analyzer from an index field You can pass text and a field in the index. The API looks up the field's analyzer and uses it to analyze the text. -If the mapping does not exist, the API uses the standard analyzer, which converts all text to lowercase and tokenizes based on white space. +If the field is not mapped, the API uses the index's default analyzer. The following request causes the analysis to be based on the mapping for `name`: -````json -GET /books2/_analyze + +{% capture step1_rest %} +GET /books2/_analyze +{ + "field": "name", + "text": "OpenSearch analyze test" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + index = "books2", + body = { + "field": "name", + "text": "OpenSearch analyze test" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -492,22 +803,48 @@ The previous request returns the following fields: } ```` -#### Specify a normalizer +### Specify a normalizer -Instead of using a keyword field, you can use the normalizer associated with the index. A normalizer causes the analysis change to produce a single token. +You can analyze text using a normalizer defined in the index. A normalizer produces a single token from the text. -In this example, the `books2` index includes a normalizer called `to_lower_fold_ascii` that converts text to lowercase and translates non-ASCII text to ASCII. +The `books2` index defines the custom `to_lower_fold_ascii` normalizer, which converts text to lowercase and converts non-ASCII characters to ASCII. The following request applies `to_lower_fold_ascii` to the text: -````json -GET /books2/_analyze + +{% capture step1_rest %} +GET /books2/_analyze +{ + "normalizer": "to_lower_fold_ascii", + "text": "C'est le garçon qui m'a suivi." +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + index = "books2", + body = { + "normalizer": "to_lower_fold_ascii", + "text": "C'est le garçon qui m'a suivi." + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -527,18 +864,47 @@ The previous request returns the following fields:
-You can create a custom transient normalizer with token and character filters. +You can create a custom transient normalizer by specifying token filters or character filters without a tokenizer. Only filters that are supported in normalizers can be used. -The following request uses the `uppercase` character filter to convert the given text to all uppercase: +The following request uses the `uppercase` token filter to convert the given text to all uppercase: -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "filter": [ + "uppercase" + ], + "text": "That is the boy who followed me." +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "filter": [ + "uppercase" + ], + "text": "That is the boy who followed me." + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -556,23 +922,62 @@ The previous request returns the following fields: } ```` -#### Get token details +### Get token details -You can obtain additional details for all tokens by setting the `explain` attribute to `true`. +You can obtain additional details for all tokens by setting the `explain` field to `true`. To limit the token attributes in the output, specify them in the `attributes` array. -The following request provides detailed token information for the `reverse` filter used with the `standard` tokenizer: +The following request provides detailed token information for the `reverse` filter used with the `standard` tokenizer and includes only the `bytes` attribute: -````json -GET /_analyze + +{% capture step1_rest %} +GET /_analyze +{ + "tokenizer": "standard", + "filter": [ + "reverse" + ], + "text": "OpenSearch analyze test", + "explain": true, + "attributes": [ + "bytes" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.analyze( + body = { + "tokenizer": "standard", + "filter": [ + "reverse" + ], + "text": "OpenSearch analyze test", + "explain": true, + "attributes": [ + "bytes" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The previous request returns the following fields: @@ -589,21 +994,24 @@ The previous request returns the following fields: "start_offset" : 0, "end_offset" : 10, "type" : "", - "position" : 0 + "position" : 0, + "bytes" : "[4f 70 65 6e 53 65 61 72 63 68]" }, { "token" : "analyze", "start_offset" : 11, "end_offset" : 18, "type" : "", - "position" : 1 + "position" : 1, + "bytes" : "[61 6e 61 6c 79 7a 65]" }, { "token" : "test", "start_offset" : 19, "end_offset" : 23, "type" : "", - "position" : 2 + "position" : 2, + "bytes" : "[74 65 73 74]" } ] }, @@ -616,21 +1024,24 @@ The previous request returns the following fields: "start_offset" : 0, "end_offset" : 10, "type" : "", - "position" : 0 + "position" : 0, + "bytes" : "[68 63 72 61 65 53 6e 65 70 4f]" }, { "token" : "ezylana", "start_offset" : 11, "end_offset" : 18, "type" : "", - "position" : 1 + "position" : 1, + "bytes" : "[65 7a 79 6c 61 6e 61]" }, { "token" : "tset", "start_offset" : 19, "end_offset" : 23, "type" : "", - "position" : 2 + "position" : 2, + "bytes" : "[74 73 65 74]" } ] } @@ -639,52 +1050,75 @@ The previous request returns the following fields: } ```` -#### Set a token limit +### Set a token limit -You can set a limit to the number of tokens generated. Setting a lower value reduces a node's memory usage. The default value is 10000. +Use the `index.analyze.max_token_count` setting to limit the number of tokens that an analyze request can produce for an index. Default is `10000`. Requests that don't specify an index are limited to the default value. -The following request limits the tokens to four: +The following request limits the tokens produced for the `books2` index to four: -````json -PUT /books2 +```json +PUT /books2/_settings { - "settings" : { - "index.analyze.max_token_count" : 4 - } + "index.analyze.max_token_count": 4 } -```` +``` {% include copy-curl.html %} -The preceding request is an index API rather than an analyze API. See [Dynamic index-level index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-level-index-settings) for additional details. -{: .note} +The following request produces five tokens, which exceeds the limit, so OpenSearch rejects the request: -### Response fields +```json +GET /books2/_analyze +{ + "text": "how to train your dog" +} +``` +{% include copy-curl.html %} + +For more information about dynamic index settings, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). + +## Response body fields The text analysis endpoints return the following response fields. Field | Data type | Description :--- | :--- | :--- -tokens | Array | Array of tokens derived from the `text`. See [token object](#token-object). -detail | Object | Details about the analysis and each token. Included only when you request token details. See [detail object](#detail-object). +`tokens` | Array | Array of tokens derived from the `text`. Returned when `explain` is `false`. See [token object](#token-object). +`detail` | Object | Details about the analysis and each token. Returned instead of `tokens` when `explain` is `true`. See [detail object](#detail-object). #### Token object Field | Data type | Description :--- | :--- | :--- -token | String | The token's text. -start_offset | Integer | The token's starting position within the original text string. Offsets are zero-based. -end_offset | Integer | The token's ending position within the original text string. -type | String | Classification of the token: ``, ``, and so on. The tokenizer usually sets the type, but some filters define their own types. For example, the synonym filter defines the `` type. -position | Integer | The token's position within the `tokens` array. +`token` | String | The token's text. +`start_offset` | Integer | The token's starting position within the original text string. Offsets are zero-based. +`end_offset` | Integer | The token's ending position within the original text string. The end offset is exclusive. +`type` | String | Classification of the token: ``, ``, and so on. The tokenizer usually sets the type, but some filters define their own types. For example, the synonym filter defines the `SYNONYM` type. +`position` | Integer | The token's position in the token stream. Positions can skip values, for example, when a filter removes tokens. +`bytes` | String | The token's bytes in hexadecimal. Returned only when `explain` is `true`. +`positionLength` | Integer | The number of positions that the token spans. Returned only when `explain` is `true`. +`termFrequency` | Integer | The token's term frequency. Returned only when `explain` is `true`. #### Detail object Field | Data type | Description :--- | :--- | :--- -custom_analyzer | Boolean | Whether the analyzer applied to the text is custom or built in. -charfilters | Array | List of character filters applied to the text. -tokenizer | Object | Name of the tokenizer applied to the text and a list of tokens* with content before the token filters were applied. -tokenfilters | Array | List of token filters applied to the text. Each token filter includes the filter's name and a list of tokens* with content after the filters were applied. Token filters are listed in the order they are specified in the request. +`custom_analyzer` | Boolean | Whether the analyzer applied to the text is custom or built in. +`analyzer` | Object | The name of the analyzer applied to the text and a list of tokens* produced by the analyzer. Returned when `custom_analyzer` is `false`, that is, when the text is analyzed using a built-in analyzer, including the index default analyzer. +`charfilters` | Array | List of character filters applied to the text. Returned when `custom_analyzer` is `true`. +`tokenizer` | Object | Name of the tokenizer applied to the text and a list of tokens* with content before the token filters were applied. Returned when `custom_analyzer` is `true`. +`tokenfilters` | Array | List of token filters applied to the text. Each token filter includes the filter's name and a list of tokens* with content after the filters were applied. Token filters are listed in the order they are specified in the request. Returned when `custom_analyzer` is `true`. See [token object](#token-object) for token field descriptions. -{: .note} \ No newline at end of file +{: .note} + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/analyze`. + +## Related documentation + +- [Text analysis]({{site.url}}{{site.baseurl}}/analyzers/) +- [Analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/index/) +- [Tokenizers]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/index/) +- [Token filters]({{site.url}}{{site.baseurl}}/analyzers/token-filters/index/) +- [Normalizers]({{site.url}}{{site.baseurl}}/analyzers/normalizers/) diff --git a/_api-reference/cat/cat-aliases.md b/_api-reference/cat/cat-aliases.md index 9e4407dc..d2c2ab0b 100644 --- a/_api-reference/cat/cat-aliases.md +++ b/_api-reference/cat/cat-aliases.md @@ -1,7 +1,7 @@ --- layout: default title: CAT aliases -parent: CAT API +parent: CAT APIs redirect_from: - /opensearch/rest-api/cat/cat-aliases/ @@ -9,60 +9,145 @@ nav_order: 1 has_children: false --- -# CAT aliases +# CAT Aliases API **Introduced 1.0** {: .label .label-purple } The CAT aliases operation lists the mapping of aliases to indexes, plus routing and filtering information. -## Example + + +## Endpoints ```json -GET _cat/aliases?v +GET /_cat/aliases +GET /_cat/aliases/{name} ``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `expand_wildcards` | List or String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Whether to return information from the local node only instead of from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + + +## Example requests + + +{% capture step1_rest %} +GET /_cat/aliases?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To limit the information to a specific alias, add the alias name after your query: -```json -GET _cat/aliases/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/aliases/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + name = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one alias, separate the alias names with commas: -```json -GET _cat/aliases/alias1,alias2,alias3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/aliases/alias1,alias2,alias3 -## Path and HTTP methods +{% endcapture %} -``` -GET _cat/aliases/ -GET _cat/aliases -``` +{% capture step1_python %} -## URL parameters +response = client.cat.aliases( + name = "alias1,alias2,alias3" +) -All CAT aliases URL parameters are optional. +{% endcapture %} -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: +{% include code-block.html + rest=step1_rest + python=step1_python %} + -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the master node. Default is false. -expand_wildcards | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. +## Example response -## Response - -The following response shows that `alias1` refers to a `movies` index and has a configured filter: +The following response shows different types of alias configurations: ```json -alias | index | filter | routing.index | routing.search | is_write_index -alias1 | movies | * | - | - | - -.opensearch-dashboards | .opensearch-dashboards_1 | - | - | - | - +alias | index | filter | routing.index | routing.search | is_write_index +current-logs | app-logs-2024 | - | - | - | - +filtered-data | customer-data | * | - | - | - +regional-orders | orders-2024 | - | west | west | - +multi-route | products | - | 1 | 1,2 | - ``` -To learn more about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias). +This response shows: +- `current-logs`: A simple alias without filters or routing +- `filtered-data`: An alias with a configured filter (indicated by `*`) +- `regional-orders`: An alias with routing configured for both indexing and searching +- `multi-route`: An alias with different routing for indexing (1) and searching (1,2) + +To learn more about index aliases, see [Index aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias/). For alias management APIs, see [Alias APIs]({{site.url}}{{site.baseurl}}/api-reference/alias/). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/aliases/get`. diff --git a/_api-reference/cat/cat-allocation.md b/_api-reference/cat/cat-allocation.md index 9598c8f3..62e86cb9 100644 --- a/_api-reference/cat/cat-allocation.md +++ b/_api-reference/cat/cat-allocation.md @@ -1,65 +1,139 @@ --- layout: default title: CAT allocation -parent: CAT API +parent: CAT APIs redirect_from: - /opensearch/rest-api/cat/cat-allocation/ nav_order: 5 has_children: false --- -# CAT allocation +# CAT Allocation API **Introduced 1.0** {: .label .label-purple } The CAT allocation operation lists the allocation of disk space for indexes and the number of shards on each node. -## Example + + +## Endpoints ```json -GET _cat/allocation?v +GET /_cat/allocation +GET /_cat/allocation/{node_id} ``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `cluster_manager_timeout` | String | A timeout for connection to the cluster manager node. | N/A | +| `format` | String | A short version of the HTTP `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from cluster-manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + + +{% capture step1_rest %} +GET /_cat/allocation?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.allocation( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To limit the information to a specific node, add the node name after your query: -```json -GET _cat/allocation/ -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/allocation/ +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.allocation( + node_id = "" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one node, separate the node names with commas: -```json -GET _cat/allocation/node_name_1,node_name_2,node_name_3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/allocation/node_name_1,node_name_2,node_name_3 +{% endcapture %} -## Path and HTTP methods +{% capture step1_python %} -``` -GET _cat/allocation?v -GET _cat/allocation/ -``` -## URL parameters +response = client.cat.allocation( + node_id = "node_name_1,node_name_2,node_name_3" +) -All CAT allocation URL parameters are optional. +{% endcapture %} -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: +{% include code-block.html + rest=step1_rest + python=step1_python %} + -Parameter | Type | Description -:--- | :--- | :--- -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster_manager node. Default is 30 seconds. - -## Response +## Example response The following response shows that eight shards are allocated to each of the two nodes available: ```json -shards | disk.indices | disk.used | disk.avail | disk.total | disk.percent host | ip | node - 8 | 989.4kb | 25.9gb | 32.4gb | 58.4gb | 44 172.18.0.4 | 172.18.0.4 | odfe-node1 - 8 | 962.4kb | 25.9gb | 32.4gb | 58.4gb | 44 172.18.0.3 | 172.18.0.3 | odfe-node2 +shards | disk.indices | disk.used | disk.avail | disk.total | disk.percent | host | ip | node + 8 | 989.4kb | 25.9gb | 32.4gb | 58.4gb | 44 | 172.18.0.4 | 172.18.0.4 | odfe-node1 + 8 | 962.4kb | 25.9gb | 32.4gb | 58.4gb | 44 | 172.18.0.3 | 172.18.0.3 | odfe-node2 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/allocation/explain`. diff --git a/_api-reference/cat/cat-cluster_manager.md b/_api-reference/cat/cat-cluster_manager.md index abf204ce..fa9f06ea 100644 --- a/_api-reference/cat/cat-cluster_manager.md +++ b/_api-reference/cat/cat-cluster_manager.md @@ -1,45 +1,86 @@ --- layout: default title: CAT cluster manager -parent: CAT API +parent: CAT APIs redirect_from: - /opensearch/rest-api/cat/cat-master/ nav_order: 30 has_children: false --- -# CAT cluster_manager +# CAT Cluster Manager API **Introduced 1.0** {: .label .label-purple } The CAT cluster manager operation lists information that helps identify the elected cluster manager node. -## Example + +## Endpoints +```json +GET /_cat/cluster_manager ``` -GET _cat/cluster_manager?v -``` -{% include copy-curl.html %} + -## Path and HTTP methods -``` -GET _cat/cluster_manager -``` + +## Query parameters -## URL parameters +The following table lists the available query parameters. All query parameters are optional. -All CAT cluster manager URL parameters are optional. +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | A timeout for connection to the cluster manager node. | N/A | +| `format` | String | A short version of the HTTP `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: + -Parameter | Type | Description -:--- | :--- | :--- -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. -## Response +## Example request + + +{% capture step1_rest %} +GET /_cat/cluster_manager?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.cluster_manager( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```json id | host | ip | node ZaIkkUd4TEiAihqJGkp5CA | 172.18.0.3 | 172.18.0.3 | opensearch-node2 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/state`. diff --git a/_api-reference/cat/cat-count.md b/_api-reference/cat/cat-count.md index 34baa04d..b3d7fd1b 100644 --- a/_api-reference/cat/cat-count.md +++ b/_api-reference/cat/cat-count.md @@ -1,7 +1,7 @@ --- layout: default title: CAT count -parent: CAT API +parent: CAT APIs nav_order: 10 has_children: false redirect_from: @@ -9,46 +9,122 @@ redirect_from: --- -# CAT count +# CAT Count API **Introduced 1.0** {: .label .label-purple } The CAT count operation lists the number of documents in your cluster. -## Example +The count includes only live documents. Documents that you deleted are not counted, even if they have not yet been removed from disk by a segment merge. To see the number of deleted documents in each index, use the [CAT Indices API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-indices/). + + +## Endpoints ```json -GET _cat/count?v +GET /_cat/count +GET /_cat/count/{index} ``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + + +{% capture step1_rest %} +GET /_cat/count?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.count( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To see the number of documents in a specific index or alias, add the index or alias name after your query: -```json -GET _cat/count/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/count/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.count( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one index or alias, separate the index or alias names with commas: -```json -GET _cat/count/index_or_alias_1,index_or_alias_2,index_or_alias_3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/count/index_or_alias_1,index_or_alias_2,index_or_alias_3 +{% endcapture %} -## Path and HTTP methods - -``` -GET _cat/count?v -GET _cat/count/?v -``` - -## URL parameters - -All CAT count URL parameters are optional. You can specify any of the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index). +{% capture step1_python %} -## Response +response = client.cat.count( + index = "index_or_alias_1,index_or_alias_2,index_or_alias_3" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The following response shows the overall document count as 1625: @@ -56,3 +132,7 @@ The following response shows the overall document count as 1625: epoch | timestamp | count 1624237738 | 01:08:58 | 1625 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/search`. diff --git a/_api-reference/cat/cat-field-data.md b/_api-reference/cat/cat-field-data.md index 6481e5ce..eb650444 100644 --- a/_api-reference/cat/cat-field-data.md +++ b/_api-reference/cat/cat-field-data.md @@ -1,58 +1,128 @@ --- layout: default title: CAT field data -parent: CAT API +parent: CAT APIs nav_order: 15 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-field-data/ --- -# CAT fielddata +# CAT Field Data API **Introduced 1.0** {: .label .label-purple } -The CAT fielddata operation lists the memory size used by each field per node. - -## Example +The CAT Field Data operation lists the memory size used by each field per node. + +## Endpoints ```json -GET _cat/fielddata?v +GET /_cat/fielddata +GET /_cat/fielddata/{fields} ``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `fields` | List or String | A comma-separated list of fields used to limit the amount of returned information. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + + +{% capture step1_rest %} +GET /_cat/fielddata?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.fielddata( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To limit the information to a specific field, add the field name after your query: -```json -GET _cat/fielddata/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/fielddata/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.fielddata( + fields = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one field, separate the field names with commas: -```json -GET _cat/fielddata/field_name_1,field_name_2,field_name_3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/fielddata/field_name_1,field_name_2,field_name_3 +{% endcapture %} -## Path and HTTP methods +{% capture step1_python %} -``` -GET _cat/fielddata?v -GET _cat/fielddata/?v -``` -## URL parameters +response = client.cat.fielddata( + fields = "field_name_1,field_name_2,field_name_3" +) -All CAT fielddata URL parameters are optional. +{% endcapture %} -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameter: +{% include code-block.html + rest=step1_rest + python=step1_python %} + -Parameter | Type | Description -:--- | :--- | :--- -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). - -## Response +## Example response The following response shows the memory size for all fields as 284 bytes: diff --git a/_api-reference/cat/cat-health.md b/_api-reference/cat/cat-health.md index 6077c77e..0f574a1c 100644 --- a/_api-reference/cat/cat-health.md +++ b/_api-reference/cat/cat-health.md @@ -1,44 +1,92 @@ --- layout: default title: CAT health -parent: CAT API - +parent: CAT APIs nav_order: 20 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-health/ --- -# CAT health +# CAT Health API **Introduced 1.0** {: .label .label-purple } -The CAT health operation lists the status of the cluster, how long the cluster has been up, the number of nodes, and other useful information that helps you analyze the health of your cluster. +The CAT health operation lists the status of the cluster, how long the cluster has been up, the number of nodes, and other useful information that helps you analyze the health of your cluster. It returns the same information as the [Cluster Health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) in a compact, single-line format. -## Example +Each response line starts with two timestamps: `epoch`, the time in seconds since the Unix epoch, and `timestamp`, the time of day in `HH:MM:SS` format. The `epoch` value includes the date, so use it to sort or compare results collected over several days. To omit both timestamps, set `ts` to `false`. +Because each call returns one line, the CAT Health API is useful for monitoring a cluster over time, for example, while the cluster recovers after a restart. The following command checks the cluster health every 60 seconds: + +```bash +while true; do curl -s "localhost:9200/_cat/health?h=epoch,timestamp,status,init,unassign"; sleep 60; done +``` +{% include copy.html %} + +As the recovery progresses, the cluster status changes from `red` to `yellow` to `green`, and the number of unassigned shards (`unassign`) decreases. If `unassign` stays the same across several checks, use the [Cluster Allocation Explain API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-allocation/) to find out why shards are not being assigned. + + + +## Endpoints ```json -GET _cat/health?v +GET /_cat/health ``` -{% include copy-curl.html %} + -## Path and HTTP methods -``` -GET _cat/health?v -``` -{% include copy-curl.html %} + +## Query parameters -## URL parameters +The following table lists the available query parameters. All query parameters are optional. -All CAT health URL parameters are optional. +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | The unit used to display time values.
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `ts` | Boolean | When `true`, returns `HH:MM:SS` and Unix epoch timestamps. | `true` | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | -Parameter | Type | Description -:--- | :--- | :--- -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -ts | Boolean | If true, returns HH:MM:SS and Unix epoch timestamps. Default is true. + -## Response +## Example request + +The following example request give cluster health information for the past 5 days: + + +{% capture step1_rest %} +GET /_cat/health?v&time=5d +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.health( + params = { "v": "true", "time": "5d" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```json GET _cat/health?v&time=5d @@ -46,3 +94,7 @@ GET _cat/health?v&time=5d epoch | timestamp | cluster | status | node.total | node.data | shards | pri | relo | init | unassign | pending_tasks | max_task_wait_time | active_shards_percent 1624248112 | 04:01:52 | odfe-cluster | green | 2 | 2 | 16 | 8 | 0 | 0 | 0 | 0 | - | 100.0% ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/health`. diff --git a/_api-reference/cat/cat-indices.md b/_api-reference/cat/cat-indices.md index 3a21e900..423da39b 100644 --- a/_api-reference/cat/cat-indices.md +++ b/_api-reference/cat/cat-indices.md @@ -1,67 +1,312 @@ --- layout: default -title: CAT indices operation -parent: CAT API +title: CAT indices +parent: CAT APIs nav_order: 25 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-indices/ --- -# CAT indices +# CAT Indices API **Introduced 1.0** {: .label .label-purple } The CAT indices operation lists information related to indexes, that is, how much disk space they are using, how many shards they have, their health status, and so on. -## Example +The document counts in the response are sourced directly from Lucene, so they include hidden [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) documents. For example, a document containing two nested objects counts as three documents. To count only top-level documents, use the [CAT count]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-count/) or [Count]({{site.url}}{{site.baseurl}}/api-reference/search-apis/count/) API. + + +## Endpoints +```json +GET /_cat/indices +GET /_cat/indices/{index} ``` -GET _cat/indices?v -``` -{% include copy-curl.html %} + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `expand_wildcards` | List or String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | `open,closed` if `system` is `false` or omitted, `open,closed,hidden` if `system` is `true`. | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`. | N/A | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `health` | String | Limits indexes based on their health status. Supported values are `green`, `yellow`, and `red`.
Valid values are: `green`, `GREEN`, `yellow`, `YELLOW`, `red`, and `RED`. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `include_unloaded_segments` | Boolean | Whether to include information from segments not loaded into memory. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `pri` | Boolean | When `true`, returns information only from the primary shards. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `system` | Boolean | Filters indexes by their system index classification. When `true`, returns only system indexes. When `false`, returns only non-system indexes. For more information, see [System indexes](#system-indexes). | N/A | +| `time` | String | Specifies the time units.
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + +## Example requests + + +{% capture step1_rest %} +GET /_cat/indices?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.indices( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To limit the information to a specific index, add the index name after your query. -``` -GET _cat/indices/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/indices/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.indices( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one index, separate the indexes with commas: -```json -GET _cat/indices/index1,index2,index3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/indices/index1,index2,index3 +{% endcapture %} -## Path and HTTP methods - -``` -GET _cat/indices/ -GET _cat/indices -``` - -## URL parameters - -All URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index/), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -health | String | Limit indexes based on their health status. Supported values are `green`, `yellow`, and `red`. -include_unloaded_segments | Boolean | Whether to include information from segments not loaded into memory. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. -pri | Boolean | Whether to return information only from the primary shards. Default is false. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -expand_wildcards | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. +{% capture step1_python %} -## Response +response = client.cat.indices( + index = "index1,index2,index3" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json health | status | index | uuid | pri | rep | docs.count | docs.deleted | store.size | pri.store.size green | open | movies | UZbpfERBQ1-3GSH2bnM3sg | 1 | 1 | 1 | 0 | 7.7kb | 3.8kb ``` + +## Response columns + +By default, the response contains the `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, and `pri.store.size` columns. To choose the columns to display, provide a comma-separated list of column names or aliases in the `h` query parameter. The `h` parameter also accepts wildcards, for example, `h=index,search.*`. To list all available columns, send `GET /_cat/indices?help`. + +For example, the following request returns the name, health, document count, and store size of the `opensearch_dashboards_sample_data_ecommerce` index: + +```json +GET /_cat/indices/opensearch_dashboards_sample_data_ecommerce?v&h=index,health,docs.count,store.size +``` +{% include copy-curl.html %} + +The response contains only the requested columns: + +```json +index health docs.count store.size +opensearch_dashboards_sample_data_ecommerce green 4675 4mb +``` + +The following table lists the general index information columns. + +| Column | Aliases | Description | +| :--- | :--- | :--- | +| `health` | `h` | The current health status of the index. | +| `status` | `s` | Whether the index is open or closed. | +| `index` | `i`, `idx` | The index name. | +| `uuid` | `id` | The index UUID. | +| `pri` | `p`, `shards.primary`, `shardsPrimary` | The number of primary shards. | +| `rep` | `r`, `shards.replica`, `shardsReplica` | The number of replica shards. | +| `docs.count` | `dc`, `docsCount` | The number of available documents. | +| `docs.deleted` | `dd`, `docsDeleted` | The number of deleted documents. | +| `creation.date` | `cd` | The index creation date, in milliseconds since the epoch. | +| `creation.date.string` | `cds` | The index creation date, as a string. | +| `store.size` | `ss`, `storeSize` | The store size of the primary and replica shards. | +| `pri.store.size` | N/A | The store size of the primary shards. | +| `search.throttled` | `sth` | Whether search on the index is throttled. | +| `last_index_request_timestamp` | `last_index_ts`, `lastIndexRequestTimestamp` | The timestamp of the last processed index request, in milliseconds since the epoch. | +| `last_index_request_timestamp_string` | `last_index_ts_string`, `lastIndexRequestTimestampString` | The timestamp of the last processed index request, as an ISO 8601 string. | +| `system` | `sys` | Whether the index is marked as a system index in the cluster metadata. Returned when you specify the `system` query parameter. For more information, see [System indexes](#system-indexes). | +| `system.description` | `sysdesc` | The description from the matching system index descriptor, when available. Returned when you specify the `system` query parameter. For more information, see [System indexes](#system-indexes). | + +The following table lists the index statistics columns. These columns report values for both primary and replica shards. Each column has a counterpart prefixed with `pri.` that reports the value for primary shards only, for example, `pri.completion.size` or `pri.search.query_total`. The `pri.` columns have no aliases. The primary-shard counterparts of `search.startree_query_current`, `search.startree_query_time`, and `search.startree_query_total` are named `pri.search.startree.query_current`, `pri.search.startree.query_time`, and `pri.search.startree.query_total`. + +| Column | Aliases | Description | +| :--- | :--- | :--- | +| `completion.size` | `cs`, `completionSize` | The size of the completion data. | +| `fielddata.evictions` | `fe`, `fielddataEvictions` | The number of field data cache evictions. | +| `fielddata.memory_size` | `fm`, `fielddataMemory` | The memory used by the field data cache. | +| `flush.total` | `ft`, `flushTotal` | The number of flush operations. | +| `flush.total_time` | `ftt`, `flushTotalTime` | The time spent in flush operations. | +| `get.current` | `gc`, `getCurrent` | The number of current get operations. | +| `get.exists_time` | `geti`, `getExistsTime` | The time spent in successful get operations. | +| `get.exists_total` | `geto`, `getExistsTotal` | The number of successful get operations. | +| `get.missing_time` | `gmti`, `getMissingTime` | The time spent in failed get operations. | +| `get.missing_total` | `gmto`, `getMissingTotal` | The number of failed get operations. | +| `get.time` | `gti`, `getTime` | The time spent in get operations. | +| `get.total` | `gto`, `getTotal` | The number of get operations. | +| `indexing.delete_current` | `idc`, `indexingDeleteCurrent` | The number of current delete operations. | +| `indexing.delete_time` | `idti`, `indexingDeleteTime` | The time spent in delete operations. | +| `indexing.delete_total` | `idto`, `indexingDeleteTotal` | The number of delete operations. | +| `indexing.index_current` | `iic`, `indexingIndexCurrent` | The number of current indexing operations. | +| `indexing.index_failed` | `iif`, `indexingIndexFailed` | The number of failed indexing operations. | +| `indexing.index_time` | `iiti`, `indexingIndexTime` | The time spent in indexing operations. | +| `indexing.index_total` | `iito`, `indexingIndexTotal` | The number of indexing operations. | +| `memory.total` | `tm`, `memoryTotal` | The total memory used. | +| `merges.current` | `mc`, `mergesCurrent` | The number of current merge operations. | +| `merges.current_docs` | `mcd`, `mergesCurrentDocs` | The number of documents in current merge operations. | +| `merges.current_size` | `mcs`, `mergesCurrentSize` | The size of current merge operations. | +| `merges.total` | `mt`, `mergesTotal` | The number of completed merge operations. | +| `merges.total_docs` | `mtd`, `mergesTotalDocs` | The number of merged documents. | +| `merges.total_size` | `mts`, `mergesTotalSize` | The total size of merged data. | +| `merges.total_time` | `mtt`, `mergesTotalTime` | The time spent in merge operations. | +| `merges.warmer.ongoing_count` | `mswoc`, `mergedSegmentWarmerOngoingCount` | The number of merged segment warming operations currently in progress. | +| `merges.warmer.total_bytes_received` | `mswtbr`, `mergedSegmentWarmerTotalBytesReceived` | The total number of bytes received by replica shards during merged segment warming. | +| `merges.warmer.total_bytes_sent` | `mswtbs`, `mergedSegmentWarmerTotalBytesSent` | The total number of bytes sent by primary shards during merged segment warming. | +| `merges.warmer.total_failure_count` | `mswtfc`, `mergedSegmentWarmerTotalFailureCount` | The total number of merged segment warmer failures. | +| `merges.warmer.total_invocations` | `mswti`, `mergedSegmentWarmerTotalInvocations` | The total number of merged segment warmer invocations. | +| `merges.warmer.total_receive_time` | `mswtrt`, `mergedSegmentWarmerTotalReceiveTime` | The total wall-clock time replica shards spent receiving merged segments. | +| `merges.warmer.total_send_time` | `mswtst`, `mergedSegmentWarmerTotalSendTime` | The total wall-clock time primary shards spent sending merged segments. | +| `merges.warmer.total_time` | `mswtt`, `mergedSegmentWarmerTotalTime` | The total wall-clock time spent in merged segment warming operations. | +| `query_cache.evictions` | `qce`, `queryCacheEvictions` | The number of query cache evictions. | +| `query_cache.memory_size` | `qcm`, `queryCacheMemory` | The memory used by the query cache. | +| `refresh.external_time` | `rti`, `refreshTime` | The time spent in external refresh operations. | +| `refresh.external_total` | `rto`, `refreshTotal` | The total number of external refresh operations. | +| `refresh.listeners` | `rli`, `refreshListeners` | The number of pending refresh listeners. | +| `refresh.time` | N/A | The time spent in refresh operations. The help output lists the `rti` and `refreshTime` aliases for this column, but they select `refresh.external_time`. | +| `refresh.total` | N/A | The total number of refresh operations. The help output lists the `rto` and `refreshTotal` aliases for this column, but they select `refresh.external_total`. | +| `request_cache.evictions` | `rce`, `requestCacheEvictions` | The number of request cache evictions. | +| `request_cache.hit_count` | `rchc`, `requestCacheHitCount` | The number of request cache hits. | +| `request_cache.memory_size` | `rcm`, `requestCacheMemory` | The memory used by the request cache. | +| `request_cache.miss_count` | `rcmc`, `requestCacheMissCount` | The number of request cache misses. | +| `search.concurrent_avg_slice_count` | `casc`, `searchConcurrentAvgSliceCount` | The average slice count for concurrent segment search. | +| `search.concurrent_query_current` | `scqc`, `searchConcurrentQueryCurrent` | The number of current concurrent query phase operations. | +| `search.concurrent_query_time` | `scqti`, `searchConcurrentQueryTime` | The time spent in the concurrent query phase. | +| `search.concurrent_query_total` | `scqto`, `searchConcurrentQueryTotal` | The number of concurrent query phase operations. | +| `search.fetch_current` | `sfc`, `searchFetchCurrent` | The number of current fetch phase operations. | +| `search.fetch_time` | `sfti`, `searchFetchTime` | The time spent in the fetch phase. | +| `search.fetch_total` | `sfto`, `searchFetchTotal` | The number of fetch phase operations. | +| `search.open_contexts` | `so`, `searchOpenContexts` | The number of open search contexts. | +| `search.point_in_time_current` | `scc`, `searchPointInTimeCurrent` | The number of open point-in-time contexts. | +| `search.point_in_time_time` | `scti`, `searchPointInTimeTime` | The time that point-in-time contexts were held open. | +| `search.point_in_time_total` | `scto`, `searchPointInTimeTotal` | The number of completed point-in-time contexts. | +| `search.query_current` | `sqc`, `searchQueryCurrent` | The number of current query phase operations. | +| `search.query_failed` | `sqf`, `searchQueryFailed` | The number of failed query phase operations. | +| `search.query_time` | `sqti`, `searchQueryTime` | The time spent in the query phase. | +| `search.query_total` | `sqto`, `searchQueryTotal` | The number of query phase operations. | +| `search.scroll_current` | `searchScrollCurrent` | The number of open scroll contexts. | +| `search.scroll_time` | `searchScrollTime` | The time that scroll contexts were held open. | +| `search.scroll_total` | `searchScrollTotal` | The number of completed scroll contexts. | +| `search.startree_query_current` | `stqc` | The number of current star-tree query operations. | +| `search.startree_query_failed` | `stqf`, `startreeQueryFailed` | The number of failed star-tree query operations. | +| `search.startree_query_time` | `stqti`, `startreeQueryTime` | The time spent in star-tree queries. | +| `search.startree_query_total` | `stqto`, `startreeQueryCurrent` | The number of queries resolved using a star-tree index. | +| `segments.count` | `sc`, `segmentsCount` | The number of segments. | +| `segments.fixed_bitset_memory` | `sfbm`, `fixedBitsetMemory` | The memory used by fixed bit sets for nested object field types and type filters. | +| `segments.index_writer_memory` | `siwm`, `segmentsIndexWriterMemory` | The memory used by the index writer. | +| `segments.memory` | `sm`, `segmentsMemory` | The memory used by segments. | +| `segments.version_map_memory` | `svmm`, `segmentsVersionMapMemory` | The memory used by the version map. | +| `suggest.current` | `suc`, `suggestCurrent` | The number of current suggest operations. | +| `suggest.time` | `suti`, `suggestTime` | The time spent in suggest operations. | +| `suggest.total` | `suto`, `suggestTotal` | The number of suggest operations. | +| `warmer.current` | `wc`, `warmerCurrent` | The number of current warmer operations. | +| `warmer.total` | `wto`, `warmerTotal` | The number of warmer operations. | +| `warmer.total_time` | `wtt`, `warmerTotalTime` | The time spent in warmer operations. | + +## System indexes +**Introduced 3.9** +{: .label .label-purple } + +The `system` query parameter filters indexes by their system index classification: + +- `system=true` returns only system indexes. +- `system=false` returns only non-system indexes. + +Omitting `system` returns both system and non-system indexes, subject to the request's index selection and wildcard expansion. + +When `system=true` and `expand_wildcards` is omitted, wildcard expansion includes hidden indexes by default. When `system=false` or `system` is omitted, hidden indexes are not included in wildcard expansion by default. An explicit `expand_wildcards` value overrides these defaults. For example, `system=true&expand_wildcards=open` excludes hidden indexes, while `system=true&expand_wildcards=all` includes open, closed, and hidden indexes. + +An index's system classification is independent of whether the index is hidden. The `system` filter does not identify every hidden index or every index protected by the Security plugin. It does not grant access to indexes; your existing permissions still apply. For information about how the Security plugin protects system indexes, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). + +The response includes the `system` and `system.description` columns whenever you specify `system`, including `system=false`. When `system` is omitted, the default columns are unchanged. Use `h` to select the columns explicitly. Selecting either column with `h` does not change index selection or include hidden indexes in wildcard expansion. + +The description is provided independently of the `system` flag. An index without a matching descriptor has no description. If the descriptor registry and the index metadata are temporarily out of sync, an index with `system=false` can still have a description. + +For example, to list system indexes and their descriptions, including hidden indexes by default, use the following request: + +```json +GET /_cat/indices?system=true&h=index,system,system.description&format=json +``` +{% include copy-curl.html %} + +The following example response is for a cluster containing a task result index: + +```json +[ + { + "index": ".tasks", + "system": "true", + "system.description": "Task Result Index" + } +] +``` + +To display both system and non-system indexes, including open, closed, and hidden indexes, use the following request: + +```json +GET /_cat/indices?expand_wildcards=all&h=index,system,system.description&format=json +``` +{% include copy-curl.html %} + +## Limiting the response size + +To limit the number of indexes returned, configure the `cat.indices.response.limit.number_of_indices` setting. For more information, see [Cluster-level CAT response limit settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/#cluster-level-cat-response-limit-settings). + +When `system` is specified, the limit counts only indexes that match the requested system classification. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/stats` and `cluster:monitor/state`. diff --git a/_api-reference/cat/cat-nodeattrs.md b/_api-reference/cat/cat-nodeattrs.md index 95c1e50a..b22d35b1 100644 --- a/_api-reference/cat/cat-nodeattrs.md +++ b/_api-reference/cat/cat-nodeattrs.md @@ -1,47 +1,90 @@ --- layout: default -title: CAT nodeattrs -parent: CAT API +title: CAT node attributes +parent: CAT APIs nav_order: 35 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-nodeattrs/ --- -# CAT nodeattrs +# CAT Node Attributes API **Introduced 1.0** {: .label .label-purple } -The CAT nodeattrs operation lists the attributes of custom nodes. +The CAT node attributes operation lists the attributes of custom nodes. -## Example + +## Endpoints +```json +GET /_cat/nodeattrs ``` -GET _cat/nodeattrs?v -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -GET _cat/nodeattrs -``` - -## URL parameters - -All CAT nodeattrs URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. + -## Response + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example request + +The following example request returns attributes about custom nodes: + + +{% capture step1_rest %} +GET /_cat/nodeattrs?v + +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.nodeattrs( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json node | host | ip | attr | value odfe-node2 | 172.18.0.3 | 172.18.0.3 | testattr | test ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/nodes/info`. diff --git a/_api-reference/cat/cat-nodes.md b/_api-reference/cat/cat-nodes.md index 149e5905..67f507a8 100644 --- a/_api-reference/cat/cat-nodes.md +++ b/_api-reference/cat/cat-nodes.md @@ -1,14 +1,14 @@ --- layout: default title: CAT nodes -parent: CAT API +parent: CAT APIs nav_order: 40 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-nodes/ --- -# CAT nodes +# CAT Nodes API **Introduced 1.0** {: .label .label-purple } @@ -16,38 +16,77 @@ The CAT nodes operation lists node-level information, including node roles and l A few important node metrics are `pid`, `name`, `cluster_manager`, `ip`, `port`, `version`, `build`, `jdk`, along with `disk`, `heap`, `ram`, and `file_desc`. -## Example + +## Endpoints +```json +GET /_cat/nodes ``` -GET _cat/nodes?v -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -GET _cat/nodes -``` - -## URL parameters - -All CAT nodes URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -full_id | Boolean | If true, return the full node ID. If false, return the shortened node ID. Defaults to false. -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -include_unloaded_segments | Boolean | Whether to include information from segments not loaded into memory. Default is false. + -## Response + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `full_id` | Boolean or String | When `true`, returns the full node ID. When `false`, returns the shortened node ID. | `false` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example request + +The following example request lists node level information: + + +{% capture step1_rest %} +GET /_cat/nodes?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.nodes( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json ip | heap.percent | ram.percent | cpu load_1m | load_5m | load_15m | node.role | node.roles | cluster_manager | name 10.11.1.225 | 31 | 32 | 0 | 0.00 | 0.00 | di | data,ingest,ml | - | data-e5b89ad7 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/nodes/info` and `cluster:monitor/nodes/stats`. diff --git a/_api-reference/cat/cat-pending-tasks.md b/_api-reference/cat/cat-pending-tasks.md index c8e1b744..1192579a 100644 --- a/_api-reference/cat/cat-pending-tasks.md +++ b/_api-reference/cat/cat-pending-tasks.md @@ -1,48 +1,88 @@ --- layout: default title: CAT pending tasks -parent: CAT API - +parent: CAT APIs nav_order: 45 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-pending-tasks/ --- -# CAT pending tasks +# CAT Pending Tasks API **Introduced 1.0** {: .label .label-purple } The CAT pending tasks operation lists the progress of all pending tasks, including task priority and time in queue. -## Example + +## Endpoints +```json +GET /_cat/pending_tasks ``` -GET _cat/pending_tasks?v -``` -{% include copy-curl.html %} + -## Path and HTTP methods -``` -GET _cat/pending_tasks -``` + +## Query parameters -## URL parameters +The following table lists the available query parameters. All query parameters are optional. -All CAT nodes URL parameters are optional. +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: + -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). +## Example request -## Response +The following example request lists the progress of all pending node tasks: + + +{% capture step1_rest %} +GET /_cat/pending_tasks?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.pending_tasks( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```json insertOrder | timeInQueue | priority | source 1786 | 1.8s | URGENT | shard-started ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/task`. diff --git a/_api-reference/cat/cat-pit-segments.md b/_api-reference/cat/cat-pit-segments.md new file mode 100644 index 00000000..0b935764 --- /dev/null +++ b/_api-reference/cat/cat-pit-segments.md @@ -0,0 +1,137 @@ +--- +layout: default +title: CAT PIT segments +parent: CAT APIs +nav_order: 46 +--- + +# CAT Pit Segments API +**Introduced 2.4** +{: .label .label-purple } + +The CAT Point in Time (PIT) segments operation provides low-level information about the disk utilization of a PIT by describing its Lucene segments. The PIT Segments API supports listing segment information for a specific PIT by ID or for all PITs at once. + +## Endpoints + + +```json +GET /_cat/pit_segments +``` + + + +```json +GET /_cat/pit_segments/_all +``` + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Request body fields + +Field | Data type | Description +:--- | :--- | :--- +`pit_id` | [Base64-encoded binary]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/binary/) or an array of binaries | The PIT IDs of the PITs whose segments are to be listed. Required. + +## Example request: PIT segments for all PITs + + +{% capture step1_rest %} +GET /_cat/pit_segments/_all +{% endcapture %} + +{% capture step1_python %} + +response = client.cat.all_pit_segments() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If there are no segments (there is no data stored), the API does not return any information. + +## Example request: PIT segments for PITs by ID + +To list segments for one or several PITs, specify their PIT IDs in the request body: + + +{% capture step1_rest %} +GET /_cat/pit_segments +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.pit_segments( + body = { + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```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 +``` diff --git a/_api-reference/cat/cat-plugins.md b/_api-reference/cat/cat-plugins.md index 34984622..ed5a9567 100644 --- a/_api-reference/cat/cat-plugins.md +++ b/_api-reference/cat/cat-plugins.md @@ -1,66 +1,148 @@ --- layout: default title: CAT plugins -parent: CAT API - +parent: CAT APIs nav_order: 50 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-plugins/ --- -# CAT plugins +# CAT Plugins API **Introduced 1.0** {: .label .label-purple } The CAT plugins operation lists the names, components, and versions of the installed plugins. -## Example - + +## Endpoints +```json +GET /_cat/plugins ``` -GET _cat/plugins?v + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example request + +The following example request lists all installed plugins: + + +{% capture step1_rest %} +GET /_cat/plugins?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.plugins( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +name component version +opensearch-node1 analysis-icu 3.3.2 +opensearch-node1 opensearch-alerting 3.3.2.0 +opensearch-node1 opensearch-anomaly-detection 3.3.2.0 +opensearch-node1 opensearch-asynchronous-search 3.3.2.0 +opensearch-node1 opensearch-cross-cluster-replication 3.3.2.0 +opensearch-node1 opensearch-custom-codecs 3.3.2.0 +opensearch-node1 opensearch-flow-framework 3.3.2.0 +opensearch-node1 opensearch-geospatial 3.3.2.0 +opensearch-node1 opensearch-index-management 3.3.2.0 +opensearch-node1 opensearch-job-scheduler 3.3.2.0 +opensearch-node1 opensearch-knn 3.3.2.0 +opensearch-node1 opensearch-ml 3.3.2.0 +opensearch-node1 opensearch-neural-search 3.3.2.0 +opensearch-node1 opensearch-notifications 3.3.2.0 +opensearch-node1 opensearch-observability 3.3.2.0 +opensearch-node1 opensearch-security 3.3.2.0 +opensearch-node1 opensearch-sql 3.3.2.0 +``` + +## Response columns + +The following table lists all response columns. In the `h` and `s` query parameters, specify either the column name or its alias. To return this list from your cluster, send `GET /_cat/plugins?help`. + +Column | Alias | Description +:--- | :--- | :--- +`id` | - | The unique node identifier. +`name` | `n` | The node name. +`component` | `c` | The plugin component name. +`version` | `v` | The plugin version. +`description` | `d` | The plugin description and details. + +To display specific columns, use the `h` query parameter. The following example request returns only the node name, component, and version columns: + +```json +GET /_cat/plugins?v&h=name,component,version ``` {% include copy-curl.html %} -## Path and HTTP methods - -``` -GET _cat/plugins -``` - -## URL parameters - -All CAT plugins URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster_manager node. Default is 30 seconds. - -## Response +The response contains only the requested columns: ```json -name component version -odfe-node2 opendistro-alerting 1.13.1.0 -odfe-node2 opendistro-anomaly-detection 1.13.0.0 -odfe-node2 opendistro-asynchronous-search 1.13.0.1 -odfe-node2 opendistro-index-management 1.13.2.0 -odfe-node2 opendistro-job-scheduler 1.13.0.0 -odfe-node2 opendistro-knn 1.13.0.0 -odfe-node2 opendistro-performance-analyzer 1.13.0.0 -odfe-node2 opendistro-reports-scheduler 1.13.0.0 -odfe-node2 opendistro-sql 1.13.2.0 -odfe-node2 opendistro_security 1.13.1.0 -odfe-node1 opendistro-alerting 1.13.1.0 -odfe-node1 opendistro-anomaly-detection 1.13.0.0 -odfe-node1 opendistro-asynchronous-search 1.13.0.1 -odfe-node1 opendistro-index-management 1.13.2.0 -odfe-node1 opendistro-job-scheduler 1.13.0.0 -odfe-node1 opendistro-knn 1.13.0.0 -odfe-node1 opendistro-performance-analyzer 1.13.0.0 -odfe-node1 opendistro-reports-scheduler 1.13.0.0 -odfe-node1 opendistro-sql 1.13.2.0 -odfe-node1 opendistro_security 1.13.1.0 +name component version +opensearch-node1 opensearch-alerting 3.8.0.0 +opensearch-node1 opensearch-anomaly-detection 3.8.0.0 +opensearch-node1 opensearch-asynchronous-search 3.8.0.0 +... ``` + +The following example request uses column aliases to return the node ID, component, and plugin description: + +```json +GET /_cat/plugins?v&h=id,c,d +``` +{% include copy-curl.html %} + +The response contains the requested columns: + +```json +id c d +6It0uQ1AR06IDC4nMstPQw opensearch-alerting Amazon OpenSearch alerting plugin +6It0uQ1AR06IDC4nMstPQw opensearch-anomaly-detection OpenSearch anomaly detector plugin +6It0uQ1AR06IDC4nMstPQw opensearch-asynchronous-search Provides support for asynchronous search +... +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/nodes/info`. diff --git a/_api-reference/cat/cat-recovery.md b/_api-reference/cat/cat-recovery.md index 54abac6d..676c9c63 100644 --- a/_api-reference/cat/cat-recovery.md +++ b/_api-reference/cat/cat-recovery.md @@ -1,64 +1,139 @@ --- layout: default title: CAT recovery -parent: CAT API - +parent: CAT APIs nav_order: 50 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-recovery/ --- -# CAT recovery +# CAT Recovery API **Introduced 1.0** {: .label .label-purple } The CAT recovery operation lists all completed and ongoing index and shard recoveries. -## Example + +## Endpoints +```json +GET /_cat/recovery +GET /_cat/recovery/{index} ``` -GET _cat/recovery?v -``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `active_only` | Boolean | If `true`, the response only includes ongoing shard recoveries. | `false` | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `detailed` | Boolean | When `true`, includes detailed information about shard recoveries. | `false` | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `index` | List | A comma-separated list of data streams, indexes, and aliases used to limit the request. Supports wildcards (`*`). To target all data streams and indexes, omit this parameter or use `*` or `_all`. | N/A | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + + +{% capture step1_rest %} +GET /_cat/recovery?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.recovery( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To see only the recoveries of a specific index, add the index name after your query. -``` -GET _cat/recovery/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/recovery/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.recovery( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one index, separate the indexes with commas: -```json -GET _cat/recovery/index1,index2,index3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/recovery/index1,index2,index3 +{% endcapture %} -## Path and HTTP methods +{% capture step1_python %} -``` -GET _cat/recovery -``` -## URL parameters +response = client.cat.recovery( + index = "index1,index2,index3" +) -All CAT recovery URL parameters are optional. +{% endcapture %} -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: +{% include code-block.html + rest=step1_rest + python=step1_python %} + -Parameter | Type | Description -:--- | :--- | :--- -active_only | Boolean | Whether to only include ongoing shard recoveries. Default is false. -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -detailed | Boolean | Whether to include detailed information about shard recoveries. Default is false. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). - -## Response +## Example response ```json index | shard | time | type | stage | source_host | source_node | target_host | target_node | repository | snapshot | files | files_recovered | files_percent | files_total | bytes | bytes_recovered | bytes_percent | bytes_total | translog_ops | translog_ops_recovered | translog_ops_percent movies | 0 | 117ms | empty_store | done | n/a | n/a | 172.18.0.4 | odfe-node1 | n/a | n/a | 0 | 0 | 0.0% | 0 | 0 | 0 | 0.0% | 0 | 0 | 0 | 100.0% movies | 0 | 382ms | peer | done | 172.18.0.4 | odfe-node1 | 172.18.0.3 | odfe-node2 | n/a | n/a | 1 | 1 | 100.0% | 1 | 208 | 208 | 100.0% | 208 | 1 | 1 | 100.0% ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/recovery`. diff --git a/_api-reference/cat/cat-repositories.md b/_api-reference/cat/cat-repositories.md index 94f39b9d..7e00795b 100644 --- a/_api-reference/cat/cat-repositories.md +++ b/_api-reference/cat/cat-repositories.md @@ -1,49 +1,88 @@ --- layout: default title: CAT repositories -parent: CAT API - +parent: CAT APIs nav_order: 52 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-repositories/ --- -# CAT repositories +# CAT Repositories API **Introduced 1.0** {: .label .label-purple } The CAT repositories operation lists all snapshot repositories for a cluster. -## Example - + +## Endpoints +```json +GET /_cat/repositories ``` -GET _cat/repositories?v -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -GET _cat/repositories -``` - -## URL parameters - -All CAT repositories URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster_manager node. Default is 30 seconds. + -## Response + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example request + +The following example request lists all snapshot repositories in the cluster: + + +{% capture step1_rest %} +GET /_cat/repositories?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.repositories( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json id type repo1 fs repo2 s3 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/repository/get`. diff --git a/_api-reference/cat/cat-segment-replication.md b/_api-reference/cat/cat-segment-replication.md index e22012ea..63d04bba 100644 --- a/_api-reference/cat/cat-segment-replication.md +++ b/_api-reference/cat/cat-segment-replication.md @@ -1,30 +1,82 @@ --- layout: default title: CAT segment replication -parent: CAT API +parent: CAT APIs nav_order: 53 has_children: false --- -# CAT segment replication +# CAT Segment Replication API **Introduced 2.7** {: .label .label-purple } -The CAT segment replication operation returns information about active and last completed [segment replication]({{site.url}}{{site.baseurl}}/opensearch/segment-replication/index) events on each replica shard, including related shard-level metrics. These metrics provide information about how far behind the primary shard the replicas are lagging. +The CAT segment replication operation returns information about active and last completed [segment replication]({{site.url}}{{site.baseurl}}/opensearch/segment-replication/index/) events on each replica shard, including related shard-level metrics. These metrics provide information about how far behind the primary shard the replicas are lagging. Call the CAT Segment Replication API only on indexes with segment replication enabled. {: .note} -## Path and HTTP methods - + +## Endpoints ```json GET /_cat/segment_replication -GET /_cat/segment_replication/ +GET /_cat/segment_replication/{index} ``` + + ## Path parameters -The following table lists the available optional path parameter. +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | List | A comma-separated list of data streams, indexes, and aliases used to limit the request. Supports wildcards (`*`). To target all data streams and indexes, omit this parameter or use `*` or `_all`. | + + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `active_only` | Boolean | When `true`, the response only includes ongoing segment replication events. | `false` | +| `allow_no_indices` | Boolean | Whether to ignore the index if a wildcard index expression resolves to no concrete indexes. This includes the `_all` string or when no indexes have been specified. | N/A | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `completed_only` | Boolean | When `true`, the response only includes the last-completed segment replication events. | `false` | +| `detailed` | Boolean | When `true`, the response includes additional metrics for each stage of a segment replication event. | `false` | +| `expand_wildcards` | List or String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `ignore_throttled` | Boolean | Whether specified concrete, expanded, or aliased indexes should be ignored when throttled. | N/A | +| `ignore_unavailable` | Boolean | Whether the specified concrete indexes should be ignored when missing or closed. | N/A | +| `index` | List | A comma-separated list of data streams, indexes, and aliases used to limit the request. Supports wildcards (`*`). To target all data streams and indexes, omit this parameter or use `*` or `_all`. | N/A | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `shards` | List | A comma-separated list of shards to display. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `timeout` | String | The operation timeout. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Path parameters Parameter | Type | Description :--- | :--- | :--- @@ -32,33 +84,70 @@ Parameter | Type | Description ## Query parameters -The CAT segment replication API operation supports the following optional query parameters. - Parameter | Data type | Description :--- |:-----------| :--- `active_only` | Boolean | If `true`, the response only includes active segment replications. Defaults to `false`. [`detailed`](#additional-detailed-response-metrics) | String | If `true`, the response includes additional metrics for each stage of a segment replication event. Defaults to `false`. `shards` | String | A comma-separated list of shards to display. -`bytes` | Byte units | [Units]({{site.url}}{{site.baseurl}}/opensearch/units/) used to display byte size values. +`limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). +`bytes` | Byte units | [Units]({{site.url}}{{site.baseurl}}/api-reference/units/) used to display byte size values. `format` | String | A short version of the HTTP accept header. Valid values include `JSON` and `YAML`. `h` | String | A comma-separated list of column names to display. `help` | Boolean | If `true`, the response includes help information. Defaults to `false`. -`time` | Time units | [Units]({{site.url}}{{site.baseurl}}/opensearch/units/) used to display time values. +`time` | Time units | [Units]({{site.url}}{{site.baseurl}}/api-reference/units/) used to display time values. `v` | Boolean | If `true`, the response includes column headings. Defaults to `false`. `s` | String | Specifies to sort the results. For example, `s=shardId:desc` sorts by shardId in descending order. -## Example +## Example requests + +{% capture step1_rest %} +GET /_cat/segment_replication?v&s=s:desc +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segment_replication( + params = { "v": "true", "s": "s:desc" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The following examples illustrate various segment replication responses. -#### Example 1: No active segment replication events +### No active segment replication events The following query requests segment replication metrics with column headings for all indexes: -```json + +{% capture step1_rest %} GET /_cat/segment_replication?v=true -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segment_replication( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains the metrics for the preceding request: @@ -67,14 +156,32 @@ shardId target_node target_host checkpoints_behind bytes_behind current_lag last [index-1][0] runTask-1 127.0.0.1 0 0b 0s 7ms 0 ``` -#### Example 2: Shard ID specified +### Shard ID specified The following query requests segment replication metrics with column headings for shards with the ID `0` from indexes `index1` and `index2`: -```json + +{% capture step1_rest %} GET /_cat/segment_replication/index1,index2?v=true&shards=0 -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segment_replication( + index = "index1,index2", + params = { "v": "true", "shards": "0" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains the metrics for the preceding request. The column headings correspond to the metric names: @@ -84,14 +191,31 @@ shardId target_node target_host checkpoints_behind bytes_behind current_lag last [index-2][0] runTask-1 127.0.0.1 0 0b 0s 5ms 0 ``` -#### Example 3: Detailed response +### Detailed response The following query requests detailed segment replication metrics with column headings for all indexes: -```json + +{% capture step1_rest %} GET /_cat/segment_replication?v=true&detailed=true -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segment_replication( + params = { "v": "true", "detailed": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains additional metrics about the files and stages of a segment replication event: @@ -101,14 +225,31 @@ shardId target_node target_host checkpoints_behind bytes_behind current_lag last [index-2][0] runTask-1 127.0.0.1 0 0b 0s 5ms 0 done 7ms 3 100.0% 3664 100.0% 2023-03-16T13:53:33.466Z 2023-03-16T13:53:33.474Z 3 3 3.5kb 3.5kb 0s 1ms 0s 2ms 2ms ``` -#### Example 4: Sorting the results +### Sorting the results The following query requests segment replication metrics with column headings for all indexes, sorted by shard ID in descending order: -```json + +{% capture step1_rest %} GET /_cat/segment_replication?v&s=shardId:desc -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segment_replication( + params = { "v": "true", "s": "shardId:desc" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains the sorted results: @@ -118,18 +259,35 @@ shardId target_node target_host checkpoints_behind bytes_behind current_lag [test6][0] runTask-2 127.0.0.1 0 0b 0s 4ms 0 ``` -#### Example 5: Using a metric alias +### Using a metric alias In a request, you can either use a metric's full name or one of its aliases. The following query is the same as the preceding query, but it uses the alias `s` instead of `shardID` for sorting: -```json + +{% capture step1_rest %} GET /_cat/segment_replication?v&s=s:desc -``` -{% include copy-curl.html %} +{% endcapture %} -## Response metrics +{% capture step1_python %} -The following table lists the response metrics that are returned for all requests. When referring to a metric in a query parameter, you can provide either the metric's full name or any of its aliases, as shown in the previous [example](#example-5-using-a-metric-alias). + +response = client.cat.segment_replication( + params = { "v": "true", "s": "s:desc" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response metrics + +The following table lists the response metrics that are returned for all requests. When referring to a metric in a query parameter, you can provide either the metric's full name or any of its aliases, as shown in the previous [example](#using-a-metric-alias). Metric | Alias | Description :--- | :--- | :--- diff --git a/_api-reference/cat/cat-segments.md b/_api-reference/cat/cat-segments.md index b8604866..c74974c4 100644 --- a/_api-reference/cat/cat-segments.md +++ b/_api-reference/cat/cat-segments.md @@ -1,63 +1,140 @@ --- layout: default title: CAT segments -parent: CAT API - +parent: CAT APIs nav_order: 55 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-segments/ --- -# CAT segments +# CAT Segments API **Introduced 1.0** {: .label .label-purple } The cat segments operation lists Lucene segment-level information for each index. -## Example + +## Endpoints +```json +GET /_cat/segments +GET /_cat/segments/{index} ``` -GET _cat/segments?v -``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + + +{% capture step1_rest %} +GET /_cat/segments?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segments( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To see only the information about segments of a specific index, add the index name after your query. -``` -GET _cat/segments/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/segments/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.segments( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one index, separate the indexes with commas: -``` -GET _cat/segments/index1,index2,index3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/segments/index1,index2,index3 +{% endcapture %} -## Path and HTTP methods - -``` -GET _cat/segments -``` - -## URL parameters - -All CAT segments URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/).. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. +{% capture step1_python %} -## Response +response = client.cat.segments( + index = "index1,index2,index3" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```json index | shard | prirep | ip | segment | generation | docs.count | docs.deleted | size | size.memory | committed | searchable | version | compound movies | 0 | p | 172.18.0.4 | _0 | 0 | 1 | 0 | 3.5kb | 1364 | true | true | 8.7.0 | true movies | 0 | r | 172.18.0.3 | _0 | 0 | 1 | 0 | 3.5kb | 1364 | true | true | 8.7.0 | true ``` + +## Limiting the response size + +To limit the number of indexes returned, configure the `cat.segments.response.limit.number_of_indices` setting. For more information, see [Cluster-level CAT response limit settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/#cluster-level-cat-response-limit-settings). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/segments`. diff --git a/_api-reference/cat/cat-shards.md b/_api-reference/cat/cat-shards.md index e74667b5..dd4cf142 100644 --- a/_api-reference/cat/cat-shards.md +++ b/_api-reference/cat/cat-shards.md @@ -1,65 +1,144 @@ --- layout: default title: CAT shards -parent: CAT API - +parent: CAT APIs nav_order: 60 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-shards/ --- -# CAT shards +# CAT Shards API **Introduced 1.0** {: .label .label-purple } The CAT shards operation lists the state of all primary and replica shards and how they are distributed. -## Example + +## Endpoints +```json +GET /_cat/shards +GET /_cat/shards/{index} ``` -GET _cat/shards?v -``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `bytes` | String | The units used to display byte values.
Valid values are: `b`, `kb`, `k`, `mb`, `m`, `gb`, `g`, `tb`, `t`, `pb`, and `p`. | N/A | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + +The following example requests returns information about shards: + + +{% capture step1_rest %} +GET /_cat/shards?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.shards( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To see only the information about shards of a specific index, add the index name after your query. -``` -GET _cat/shards/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/shards/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.shards( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one index, separate the indexes with commas: -``` -GET _cat/shards/index1,index2,index3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/shards/index1,index2,index3 +{% endcapture %} -## Path and HTTP methods - -``` -GET _cat/shards -``` - -## URL parameters - -All cat shards URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -bytes | Byte size | Specify the units for byte size. For example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster_manager node. Default is 30 seconds. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). +{% capture step1_python %} -## Response +response = client.cat.shards( + index = "index1,index2,index3" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```json index | shard | prirep | state | docs | store | ip | | node plugins | 0 | p | STARTED | 0 | 208b | 172.18.0.4 | odfe-node1 plugins | 0 | r | STARTED | 0 | 208b | 172.18.0.3 | odfe-node2 ``` + +## Limiting the response size + +To limit the number of shards returned, configure the `cat.shards.response.limit.number_of_shards` setting. For more information, see [Cluster-level CAT response limit settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/#cluster-level-cat-response-limit-settings). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/stats` and `cluster:monitor/state`. diff --git a/_api-reference/cat/cat-snapshots.md b/_api-reference/cat/cat-snapshots.md index 82cb5c1b..54243a77 100644 --- a/_api-reference/cat/cat-snapshots.md +++ b/_api-reference/cat/cat-snapshots.md @@ -1,49 +1,92 @@ --- layout: default title: CAT snapshots -parent: CAT API - +parent: CAT APIs nav_order: 65 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-snapshots/ --- -# CAT snapshots +# CAT Snapshots API **Introduced 1.0** {: .label .label-purple } The CAT snapshots operation lists all snapshots for a repository. -## Example + +## Endpoints +```json +GET /_cat/snapshots +GET /_cat/snapshots/{repository} ``` -GET _cat/snapshots?v -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -GET _cat/snapshots -``` - -## URL parameters - -All CAT snapshots URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameter: - -Parameter | Type | Description -:--- | :--- | :--- -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). + -## Response + +## Query parameters + +The following table lists the available query parameters. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `repository` | List or String | **(Required)** A comma-separated list of snapshot repositories used to limit the request. Accepts wildcard expressions. `_all` returns all repositories. If any repository fails during the request, OpenSearch returns an error. | N/A | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `ignore_unavailable` | Boolean | When `true`, the response does not include information from unavailable snapshots. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example request + +The following example request lists all snapshots: + + +{% capture step1_rest %} +GET /_cat/snapshots?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.snapshots( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json index | shard | prirep | state | docs | store | ip | | node plugins | 0 | p | STARTED | 0 | 208b | 172.18.0.4 | odfe-node1 plugins | 0 | r | STARTED | 0 | 208b | 172.18.0.3 | odfe-node2 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/get`. diff --git a/_api-reference/cat/cat-tasks.md b/_api-reference/cat/cat-tasks.md index 4d2a06cc..153865d1 100644 --- a/_api-reference/cat/cat-tasks.md +++ b/_api-reference/cat/cat-tasks.md @@ -1,50 +1,90 @@ --- layout: default title: CAT tasks -parent: CAT API - +parent: CAT APIs nav_order: 70 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-tasks/ --- -# CAT tasks +# CAT Tasks API **Introduced 1.0** {: .label .label-purple } The CAT tasks operation lists the progress of all tasks currently running on your cluster. -## Example - + +## Endpoints +```json +GET /_cat/tasks ``` -GET _cat/tasks?v -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -GET _cat/tasks -``` - -## URL parameters - -All CAT tasks URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -nodes | List | A comma-separated list of node IDs or names to limit the returned information. Use `_local` to return information from the node you're connecting to, specify the node name to get information from specific nodes, or keep the parameter empty to get information from all nodes. -detailed | Boolean | Returns detailed task information. (Default: false) -parent_task_id | String | Returns tasks with a specified parent task ID (node_id:task_number). Keep empty or set to -1 to return all. -time | Time | Specify the units for time. For example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). + -## Response + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `actions` | List | The task action names used to limit the response. | N/A | +| `detailed` | Boolean | If `true`, the response includes detailed information about shard recoveries. | `false` | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `nodes` | List | A comma-separated list of node IDs or names used to limit the returned information. Use `_local` to return information from the node to which you're connecting, specify a specific node from which to get information, or keep the parameter empty to get information from all nodes. | N/A | +| `parent_task_id` | String | The parent task identifier, which is used to limit the response. | N/A | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `time` | String | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/).
Valid values are: `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example request + +The following example request lists all tasks in progress: + + +{% capture step1_rest %} +GET /_cat/tasks?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.tasks( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json action | task_id | parent_task_id | type | start_time | timestamp | running_time | ip | node cluster:monitor/tasks/lists | 1vo54NuxSxOrbPEYdkSF0w:168062 | - | transport | 1624337809471 | 04:56:49 | 489.5ms | 172.18.0.4 | odfe-node1 ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/tasks/list`. diff --git a/_api-reference/cat/cat-templates.md b/_api-reference/cat/cat-templates.md index d2aed7b0..0f57aef4 100644 --- a/_api-reference/cat/cat-templates.md +++ b/_api-reference/cat/cat-templates.md @@ -1,58 +1,115 @@ --- layout: default title: CAT templates -parent: CAT API - +parent: CAT APIs nav_order: 70 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-templates/ --- -# CAT templates +# CAT Templates API **Introduced 1.0** {: .label .label-purple } The CAT templates operation lists the names, patterns, order numbers, and version numbers of index templates. -## Example + +## Endpoints +```json +GET /_cat/templates +GET /_cat/templates/{name} ``` -GET _cat/templates?v -``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time allowed to establish a connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + +The following example request returns information about all templates: + + +{% capture step1_rest %} +GET /_cat/templates?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.templates( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for a specific template or pattern: -``` -GET _cat/templates/ -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/templates/ +{% endcapture %} -## Path and HTTP methods - -``` -GET _cat/templates -``` -{% include copy-curl.html %} - -## URL parameters - -All CAT templates URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the cluster manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. +{% capture step1_python %} -## Response +response = client.cat.templates( + name = "" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ``` name | index_patterns order version composed_of tenant_template | [opensearch-dashboards*] | 0 | ``` -To learn more about index templates, see [Index templates]({{site.url}}{{site.baseurl}}/opensearch/index-templates). +To learn more about index templates, see [Index templates]({{site.url}}{{site.baseurl}}/opensearch/index-templates/). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/template/get`. diff --git a/_api-reference/cat/cat-thread-pool.md b/_api-reference/cat/cat-thread-pool.md index 5d3e341b..29e9b49f 100644 --- a/_api-reference/cat/cat-thread-pool.md +++ b/_api-reference/cat/cat-thread-pool.md @@ -1,59 +1,133 @@ --- layout: default title: CAT thread pool -parent: CAT API +parent: CAT APIs nav_order: 75 has_children: false redirect_from: - /opensearch/rest-api/cat/cat-thread-pool/ --- -# CAT thread pool +# CAT Thread Pool API **Introduced 1.0** {: .label .label-purple } The CAT thread pool operation lists the active, queued, and rejected threads of different thread pools on each node. -## Example + +## Endpoints +```json +GET /_cat/thread_pool +GET /_cat/thread_pool/{thread_pool_patterns} ``` -GET _cat/thread_pool?v -``` -{% include copy-curl.html %} + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | A timeout for connection to the cluster manager node. | N/A | +| `format` | String | A short version of the `Accept` header, such as `json` or `yaml`.
Valid values are: `cbor`, `json`, `smile`, `text`, and `yaml`. | `text` | +| `h` | List | A comma-separated list of column names to display. | N/A | +| `help` | Boolean | Returns help information. | `false` | +| `limit` | Integer | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). | N/A | +| `local` | Boolean | Returns local information but does not retrieve the state from the cluster manager node. | `false` | +| `s` | List | A comma-separated list of column names or column aliases to sort by. | N/A | +| `size` | Integer | The multiplier in which to display values. | N/A | +| `v` | Boolean | Enables verbose mode, which displays column headers. | `false` | + + + +## Example requests + +The following example request gives information about thread pools on all nodes: + + +{% capture step1_rest %} +GET /_cat/thread_pool?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.thread_pool( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to get information for more than one thread pool, separate the thread pool names with commas: -``` -GET _cat/thread_pool/thread_pool_name_1,thread_pool_name_2,thread_pool_name_3 -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/thread_pool/thread_pool_name_1,thread_pool_name_2,thread_pool_name_3 +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.thread_pool( + thread_pool_patterns = "thread_pool_name_1,thread_pool_name_2,thread_pool_name_3" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to limit the information to a specific thread pool, add the thread pool name after your query: -``` -GET _cat/thread_pool/?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/thread_pool/?v +{% endcapture %} -## Path and HTTP methods - -``` -GET _cat/thread_pool -``` - -## URL parameters - -All CAT thread pool URL parameters are optional. - -In addition to the [common URL parameters]({{site.url}}{{site.baseurl}}/api-reference/cat/index), you can specify the following parameters: - -Parameter | Type | Description -:--- | :--- | :--- -local | Boolean | Whether to return information from the local node only instead of from the cluster_manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster_manager node. Default is 30 seconds. +{% capture step1_python %} -## Response +response = client.cat.thread_pool( + thread_pool_patterns = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json node_name name active queue rejected @@ -61,3 +135,7 @@ odfe-node2 ad-batch-task-threadpool 0 0 0 odfe-node2 ad-threadpool 0 0 0 odfe-node2 analyze 0 0 0s ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/nodes/info`. diff --git a/_api-reference/cat/index.md b/_api-reference/cat/index.md index 0ddaf1e0..5e8fa454 100644 --- a/_api-reference/cat/index.md +++ b/_api-reference/cat/index.md @@ -1,67 +1,142 @@ --- layout: default -title: CAT API +title: CAT APIs nav_order: 10 has_children: true +has_toc: false redirect_from: - /opensearch/catapis/ - /opensearch/rest-api/cat/index/ + - /api-reference/cat/ --- -# CAT API +# CAT APIs **Introduced 1.0** {: .label .label-purple } + You can get essential statistics about your cluster in an easy-to-understand, tabular format using the compact and aligned text (CAT) API. The CAT API is a human-readable interface that returns plain text instead of traditional JSON. -Using the CAT API, you can answer questions like which node is the elected master, what state is the cluster in, how many documents are in each index, and so on. +Using the CAT API, you can answer questions like which node is the elected cluster manager, what state the cluster is in, how many documents are in each index, and so on. ## Example To see the available operations in the CAT API, use the following command: + +{% capture step1_rest %} +GET /_cat +{% endcapture %} + +{% capture step1_python %} + +response = client.cat.help() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response is an ASCII cat (`=^.^=`) and a list of operations: + ``` -GET _cat +=^.^= +/_cat/allocation +/_cat/segment_replication +/_cat/segment_replication/{index} +/_cat/shards +/_cat/shards/{index} +/_cat/cluster_manager +/_cat/nodes +/_cat/tasks +/_cat/indices +/_cat/indices/{index} +/_cat/segments +/_cat/segments/{index} +/_cat/count +/_cat/count/{index} +/_cat/recovery +/_cat/recovery/{index} +/_cat/health +/_cat/pending_tasks +/_cat/aliases +/_cat/aliases/{alias} +/_cat/thread_pool +/_cat/thread_pool/{thread_pools} +/_cat/plugins +/_cat/fielddata +/_cat/fielddata/{fields} +/_cat/nodeattrs +/_cat/repositories +/_cat/snapshots/{repository} +/_cat/templates +/_cat/pit_segments +/_cat/pit_segments/{pit_id} ``` -{% include copy-curl.html %} ## Optional query parameters -You can use the following query parameters with any CAT API to filter your results. +The root `_cat` API does not take any parameters, but individual APIs, such as `/_cat/nodes`, accept the following query parameters. Parameter | Description :--- | :--- | -`v` | Provides verbose output by adding headers to the columns. It also adds some formatting to help align each of the columns together. All examples in this section include the `v` parameter. +`v` | Provides verbose output by adding headers to the columns. `help` | Lists the default and other available headers for a given operation. -`h` | Limits the output to specific headers. -`format` | Returns the result in JSON, YAML, or CBOR formats. -`sort` | Sorts the output by the specified columns. +`h` | Limits the output to specific headers. Accepts column names, column aliases, and wildcards (for example, `routing.*`). +`format` | The format in which to return the result. Valid values are `text` (default), `json`, `yaml`, `cbor`, and `smile`. +`s` | Sorts the output by the specified columns. Accepts column names and column aliases, each optionally followed by `:asc` or `:desc` (for example, `s=a:desc`). Each sort key must be an existing column name or alias. +`limit` | The maximum number of rows to return. Must be greater than 0. Applied after sorting (`s`). For more information, see [Limit the number of rows](#limit-the-number-of-rows). +`bytes` | The units used to display byte values. Valid values are `b`, `kb`, `mb`, `gb`, `tb`, and `pb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). +`time` | The units used to display time values. Valid values are `nanos`, `micros`, `ms`, `s`, `m`, `h`, and `d`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). +`ts` | Boolean. Whether to include timestamp columns in operations that provide them, such as `_cat/health`. Default is `true`. +`pri` | Boolean. Whether to add primary shard statistics in operations that provide them, such as `_cat/indices`. For each column specified in the `h` parameter that has a primary shard counterpart, adds a `pri.` column. For example, `h=i,ss` with `pri` returns the `i`, `ss`, and `pri.ss` columns. -### Query parameter usage examples - -You can specify a query parameter to any CAT operation to obtain more specific results. +Specify these query parameters in any CAT operation to obtain more specific results. The following examples use the CAT aliases operation. ### Get verbose output To query aliases and get verbose output that includes all column headings in the response, use the `v` query parameter. -```json -GET _cat/aliases?v -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cat/aliases?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response provides more details, such as names of each column in the response. ``` -alias index filter routing.index routing.search is_write_index -.kibana .kibana_1 - - - - -sample-alias1 sample-index-1 - - - - -``` -Without the verbose parameter, `v`, the response simply returns the alias names: - +alias index filter routing.index routing.search is_write_index +.kibana .kibana_1 - - - - +sample-alias1 sample-index-1 - - - - +sample-alias2 sample-index-2 - - - - ``` -.kibana .kibana_1 - - - - +Without the verbose parameter, `v`, the response contains the same columns without the header row: + +``` +.kibana .kibana_1 - - - - sample-alias1 sample-index-1 - - - - +sample-alias2 sample-index-2 - - - - ``` ### Get all available headers @@ -69,7 +144,42 @@ sample-alias1 sample-index-1 - - - - To see all the available headers, use the `help` parameter: ``` -GET _cat/?help +GET _cat/{operation_name}?help +``` + +For example, to see the available headers for the CAT aliases operation, send the following request: + + +{% capture step1_rest %} +GET /_cat/aliases?help +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + params = { "help": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the available headers: + +``` +alias | a | alias name +index | i,idx | index alias points to +filter | f,fi | filter +routing.index | ri,routingIndex | index routing +routing.search | rs,routingSearch | search routing +is_write_index | w,isWriteIndex | write index ``` ### Get a subset of headers @@ -77,10 +187,192 @@ GET _cat/?help To limit the output to a subset of headers, use the `h` parameter: ``` -GET _cat/?h=,&v +GET _cat/{operation_name}?h={header_name_1},{header_name_2} +``` + +For example, to limit aliases to only the alias name and index, send the following request: + + +{% capture step1_rest %} +GET /_cat/aliases?h=alias,index +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + params = { "h": "alias,index" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the requested information: + +``` +.kibana .kibana_1 +sample-alias1 sample-index-1 +sample-alias2 sample-index-2 ``` Typically, for any operation you can find out what headers are available using the `help` parameter, and then use the `h` parameter to limit the output to only the headers that you care about. +### Sort by a header + +To sort the output by a header, use the `s` parameter: + +``` +GET _cat/{operation_name}?s={header_name_1},{header_name_2} +``` + +For example, to sort aliases by index and then by alias, send the following request: + + +{% capture step1_rest %} +GET /_cat/aliases?s=i,a +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + params = { "s": "i,a" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the requested information: + +``` +.kibana .kibana_1 - - - - +sample-alias1 sample-index-1 - - - - +sample-alias2 sample-index-2 - - - - +``` + +### Limit the number of rows + +**Introduced 3.10** +{: .label .label-purple } + +To cap the number of rows returned, use the `limit` parameter: + +``` +GET _cat/{operation_name}?limit={number_of_rows} +``` + +The `limit` value must be a positive integer. A value of `0`, a negative number, or a non-numeric value causes the request to fail with a `400` error. If you omit `limit`, the API returns all rows. + +The `limit` parameter is applied after sorting (`s`), so combining the two returns the top N rows by the sort key. For example, the following request returns the five largest shards: + +``` +GET _cat/shards?s=store:desc&limit=5&v +``` + +The following request returns the 10 longest-running tasks: + +``` +GET _cat/tasks?s=running_time:desc&limit=10&v +``` + +If you do not specify `s`, the rows are returned in the default order of the operation, and `limit` returns the first N of those rows. + +The `limit` parameter has the following behavior: + +- The parameter is validated for every CAT operation but is applied only by the non-paginated CAT APIs. The paginated [List APIs]({{site.url}}{{site.baseurl}}/api-reference/list/index/) (`_list/*`) ignore `limit` and use the `size` and `next_token` parameters instead because truncating a page would skip the rows between the limit and the page boundary. +- The parameter reduces only the size of the response and the rendering work. OpenSearch still collects the data for all rows before applying the limit, so `limit` does not reduce the cost of building the table. To reduce that cost, restrict the request to specific indexes, for example, `GET _cat/shards/my-index-*`. +- The `limit` parameter truncates the response and does not return an error. To reject requests that would return too many rows, use the [cluster-level CAT response limit settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/#cluster-level-cat-response-limit-settings), which return a `429` error when the limit is exceeded. + +### Retrieve data in JSON format + +By default, CAT APIs return data in `text/plain` format. + +To retrieve data in JSON format, use the `format=json` parameter: + +``` +GET _cat/{operation_name}?format=json +``` + +For example, to retrieve aliases in JSON format, send the following request: + + +{% capture step1_rest %} +GET /_cat/aliases?format=json +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.aliases( + params = { "format": "json" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains data in JSON format: + +```json +[ + {"alias":".kibana","index":".kibana_1","filter":"-","routing.index":"-","routing.search":"-","is_write_index":"-"}, + {"alias":"sample-alias1","index":"sample-index-1","filter":"-","routing.index":"-","routing.search":"-","is_write_index":"-"}, + {"alias":"sample-alias2","index":"sample-index-2","filter":"-","routing.index":"-","routing.search":"-","is_write_index":"-"} +] +``` + +Other supported formats are [YAML](https://yaml.org/), [CBOR](https://cbor.io/), and [Smile](https://github.com/FasterXML/smile-format-specification). + +## CAT API operations + +The following CAT API operations are available. + +### Cluster and node information +- [CAT aliases]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-aliases/) +- [CAT allocation]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-allocation/) +- [CAT cluster manager]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-cluster_manager/) +- [CAT health]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-health/) +- [CAT nodes]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-nodes/) +- [CAT node attributes]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-nodeattrs/) +- [CAT pending tasks]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-pending-tasks/) +- [CAT plugins]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-plugins/) +- [CAT repositories]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-repositories/) +- [CAT tasks]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-tasks/) +- [CAT templates]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-templates/) +- [CAT thread pool]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-thread-pool/) + +### Index and document information +- [CAT count]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-count/) +- [CAT field data]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-field-data/) +- [CAT indices]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-indices/) +- [CAT PIT segments]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-pit-segments/) +- [CAT recovery]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/) +- [CAT segment replication]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-segment-replication/) +- [CAT segments]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-segments/) +- [CAT shards]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-shards/) + +### Snapshot information +- [CAT snapshots]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-snapshots/) + If you use the Security plugin, make sure you have the appropriate permissions. {: .note } diff --git a/_api-reference/cluster-api/cluster-allocation.md b/_api-reference/cluster-api/cluster-allocation.md index da6e3aab..f8503131 100644 --- a/_api-reference/cluster-api/cluster-allocation.md +++ b/_api-reference/cluster-api/cluster-allocation.md @@ -8,58 +8,105 @@ redirect_from: - /opensearch/rest-api/cluster-allocation/ --- -# Cluster allocation explain +# Cluster Allocation Explain API **Introduced 1.0** {: .label .label-purple } -The most basic cluster allocation explain request finds an unassigned shard and explains why it can't be allocated to a node. +The Cluster Allocation Explain API provides detailed explanations for shard allocations in your cluster. Use this API to troubleshoot and diagnose shard allocation issues. -If you add some options, you can instead get information on a specific shard, including why OpenSearch assigned it to its current node. +This API is particularly useful in the following scenarios: + +- Understanding why a shard remains unassigned and cannot be allocated to any node. +- Determining why a shard was allocated to a particular node instead of another. +- Understanding why a shard remains on its current node rather than being rebalanced to another node. +- Verifying that allocation settings and filters are working as expected. + +When called without a request body, the API finds the first unassigned shard and explains why it cannot be allocated. When called with specific shard information, it provides allocation details for that particular shard. -## Example - + +## Endpoints ```json -GET _cluster/allocation/explain?include_yes_decisions=true +GET /_cluster/allocation/explain +POST /_cluster/allocation/explain +``` + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `include_disk_info` | Boolean | When `true`, returns information about disk usage and shard sizes. _(Default: `false`)_ | +| `include_yes_decisions` | Boolean | When `true`, returns any `YES` decisions in the allocation explanation. `YES` decisions indicate when a particular shard allocation attempt was successful for the given node. _(Default: `false`)_ | + + + +## Request body fields + +The index, shard, and primary flag for which to generate an explanation. Leave this empty to generate an explanation for the first unassigned shard. + +The request body is optional. It is a JSON object with the following fields. + +| Property | Data type | Description | +| :--- | :--- | :--- | +| `current_node` | String | Specifies the node ID or the name of the node to only explain a shard that is currently located on the specified node. | +| `index` | String | The name of the index that contains the shard for which to generate an explanation. | +| `primary` | Boolean | When `true`, returns a routing explanation for the primary shard based on the node ID. | +| `shard` | Integer | Specifies the ID of the shard that you would like an explanation for. | + +## Example request + + +{% capture step1_rest %} +GET /_cluster/allocation/explain?include_yes_decisions=true +{ + "index": "movies", + "shard": 0, + "primary": true +} +{% endcapture %} -## Path and HTTP methods - -``` -GET _cluster/allocation/explain -POST _cluster/allocation/explain -``` +{% capture step1_python %} -## URL parameters +response = client.cluster.allocation_explain( + params = { "include_yes_decisions": "true" }, + body = { + "index": "movies", + "shard": 0, + "primary": true + } +) -All cluster allocation explain parameters are optional. +{% endcapture %} -Parameter | Type | Description -:--- | :--- | :--- -include_yes_decisions | Boolean | OpenSearch makes a series of yes or no decisions when trying to allocate a shard to a node. If this parameter is true, OpenSearch includes the (generally more numerous) "yes" decisions in its response. Default is false. -include_disk_info | Boolean | Whether to include information about disk usage in the response. Default is false. +{% include code-block.html + rest=step1_rest + python=step1_python %} + -## Request body +## Example response -All cluster allocation explain fields are optional. - -Field | Type | Description -:--- | :--- | :--- -current_node | String | If you only want an explanation if the shard happens to be on a particular node, specify that node name here. -index | String | The name of the shard's index. -primary | Boolean | Whether to provide an explanation for the primary shard (true) or its first replica (false), which share the same shard ID. -shard | Integer | The shard ID that you want an explanation for. - - -## Response +The following response shows an assigned primary shard with allocation decisions for other nodes in the cluster: ```json { @@ -147,3 +194,439 @@ shard | Integer | The shard ID that you want an explanation for. }] } ``` + +## Example: Explaining the first unassigned shard + +To get an explanation for the first unassigned shard found by OpenSearch, send an empty request body: + + +{% capture step1_rest %} +POST /_cluster/allocation/explain +{} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.allocation_explain( + body = {} +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +The following response shows an unassigned replica shard in a single-node cluster: + +```json +{ + "index" : "research_papers", + "shard" : 0, + "primary" : false, + "current_state" : "unassigned", + "unassigned_info" : { + "reason" : "CLUSTER_RECOVERED", + "at" : "2026-02-17T16:43:13.339Z", + "last_allocation_status" : "no_attempt" + }, + "can_allocate" : "no", + "allocate_explanation" : "cannot allocate because allocation is not permitted to any of the nodes", + "node_allocation_decisions" : [ + { + "node_id" : "KfEEGG7_SsKZVFqI4ko2FA", + "node_name" : "opensearch-node1", + "transport_address" : "172.18.0.2:9300", + "node_attributes" : { + "shard_indexing_pressure_enabled" : "true" + }, + "node_decision" : "no", + "deciders" : [ + { + "decider" : "same_shard", + "decision" : "NO", + "explanation" : "a copy of this shard is already allocated to this node [[research_papers][0], node[KfEEGG7_SsKZVFqI4ko2FA], [P], s[STARTED], a[id=SfxnuSLESQSI0Htcv0N3vA]]" + } + ] + } + ] +} +``` + +The response contains the following fields: +- `current_state`: The shard is `unassigned`. +- `unassigned_info.reason`: The shard became unassigned during cluster recovery (`CLUSTER_RECOVERED`). +- `can_allocate`: Set to `no` because the shard cannot be allocated to any available node. +- `node_decision`: Set to `no` for the only node in the cluster. +- `decider`: The `same_shard` allocator blocks allocation because the primary shard is already on this node. + +This is a typical situation in single-node clusters where replica shards cannot be allocated because OpenSearch does not allow a primary and its replica to coexist on the same node. + +## Example: Explaining a specific assigned shard + +To understand why an assigned shard remains on its current node, specify the shard details: + + +{% capture step1_rest %} +POST /_cluster/allocation/explain +{ + "index": "books", + "shard": 0, + "primary": true +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.allocation_explain( + body = { + "index": "books", + "shard": 0, + "primary": true + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +```json +{ + "index" : "books", + "shard" : 0, + "primary" : true, + "current_state" : "started", + "current_node" : { + "id" : "KfEEGG7_SsKZVFqI4ko2FA", + "name" : "opensearch-node1", + "transport_address" : "172.18.0.2:9300", + "attributes" : { + "shard_indexing_pressure_enabled" : "true" + }, + "weight_ranking" : 1 + }, + "can_remain_on_current_node" : "yes", + "can_rebalance_cluster" : "no", + "can_rebalance_cluster_decisions" : [ + { + "decider" : "rebalance_only_when_active", + "decision" : "NO", + "explanation" : "rebalancing is not allowed until all replicas in the cluster are active" + }, + { + "decider" : "cluster_rebalance", + "decision" : "NO", + "explanation" : "the cluster has unassigned shards and cluster setting [cluster.routing.allocation.allow_rebalance] is set to [indices_all_active]" + } + ], + "can_rebalance_to_other_node" : "no", + "rebalance_explanation" : "rebalancing is not allowed" +} +``` + +The response contains the following fields: +- `current_state`: The shard is `started` and functioning normally. +- `current_node`: Contains details about the node hosting this shard. +- `can_remain_on_current_node`: Set to `yes` because the shard is allowed to stay on its current node. +- `can_rebalance_cluster`: Set to `no` because rebalancing is disabled when the cluster has unassigned shards. +- `can_rebalance_cluster_decisions`: Lists the deciders that prevent rebalancing. + +## Example: Including disk information + +Use the `include_disk_info` parameter to get detailed disk usage statistics: + + +{% capture step1_rest %} +POST /_cluster/allocation/explain?include_disk_info=true +{ + "index": "books", + "shard": 0, + "primary": true +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.allocation_explain( + params = { "include_disk_info": "true" }, + body = { + "index": "books", + "shard": 0, + "primary": true + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +The response includes additional `cluster_info` with disk usage and shard size details: + +```json +{ + "index" : "books", + "shard" : 0, + "primary" : true, + "current_state" : "started", + "current_node" : { + "id" : "KfEEGG7_SsKZVFqI4ko2FA", + "name" : "opensearch-node1", + "transport_address" : "172.18.0.2:9300", + "attributes" : { + "shard_indexing_pressure_enabled" : "true" + }, + "weight_ranking" : 1 + }, + "cluster_info" : { + "nodes" : { + "KfEEGG7_SsKZVFqI4ko2FA" : { + "node_name" : "opensearch-node1", + "least_available" : { + "path" : "/usr/share/opensearch/data/nodes/0", + "total_bytes" : 62671097856, + "used_bytes" : 14324834304, + "free_bytes" : 48346263552, + "free_disk_percent" : 77.1, + "used_disk_percent" : 22.9 + }, + "most_available" : { + "path" : "/usr/share/opensearch/data/nodes/0", + "total_bytes" : 62671097856, + "used_bytes" : 14324834304, + "free_bytes" : 48346263552, + "free_disk_percent" : 77.1, + "used_disk_percent" : 22.9 + }, + "node_resource_usage_stats" : { + "KfEEGG7_SsKZVFqI4ko2FA" : { + "timestamp" : 1771438387501, + "cpu_utilization_percent" : "0.5", + "memory_utilization_percent" : "57.9", + "io_usage_stats" : { + "max_io_utilization_percent" : "0.0" + } + } + } + } + }, + "shard_sizes" : { + "[books][0][p]_bytes" : 5312, + "[movies][0][p]_bytes" : 4862, + "[research_papers][0][p]_bytes" : 7367 + }, + "shard_paths" : { + "[books][0], node[KfEEGG7_SsKZVFqI4ko2FA], [P], s[STARTED], a[id=Vu7arTEfRrG9lnikaClzDg]" : "/usr/share/opensearch/data/nodes/0", + "[movies][0], node[KfEEGG7_SsKZVFqI4ko2FA], [P], s[STARTED], a[id=f9QNud7NSACyM0YedYGfDg]" : "/usr/share/opensearch/data/nodes/0", + "[research_papers][0], node[KfEEGG7_SsKZVFqI4ko2FA], [P], s[STARTED], a[id=SfxnuSLESQSI0Htcv0N3vA]" : "/usr/share/opensearch/data/nodes/0" + }, + "reserved_sizes" : [ ] + }, + "can_remain_on_current_node" : "yes", + "can_rebalance_cluster" : "no", + "can_rebalance_cluster_decisions" : [ + { + "decider" : "rebalance_only_when_active", + "decision" : "NO", + "explanation" : "rebalancing is not allowed until all replicas in the cluster are active" + }, + { + "decider" : "cluster_rebalance", + "decision" : "NO", + "explanation" : "the cluster has unassigned shards and cluster setting [cluster.routing.allocation.allow_rebalance] is set to [indices_all_active]" + } + ], + "can_rebalance_to_other_node" : "no", + "rebalance_explanation" : "rebalancing is not allowed" +} +``` + +The `cluster_info` object provides: +- `nodes`: Disk usage statistics for each node, including free and used disk space percentages, and resource utilization metrics (CPU, memory, and I/O). +- `shard_sizes`: The size of each shard in the cluster in bytes (response shows a sample; actual responses include all shards). +- `shard_paths`: The file system path where each shard is stored on the node (response shows a sample; actual responses include all shards). +- `reserved_sizes`: Reserved disk space for ongoing shard operations. + +This information is useful when diagnosing disk-related allocation issues or understanding how disk space affects allocation decisions. + +## Example: Specifying a node with current_node + +Use the `current_node` parameter to get an explanation only if the shard is located on a specific node: + + +{% capture step1_rest %} +POST /_cluster/allocation/explain +{ + "index": "books", + "shard": 0, + "primary": false, + "current_node": "opensearch-node1" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.allocation_explain( + body = { + "index": "books", + "shard": 0, + "primary": false, + "current_node": "opensearch-node1" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +This query returns an explanation only if the replica shard 0 of the `books` index is currently on the `opensearch-node1` node. If the shard is on a different node or is unassigned, the API returns an error. + +## Response fields + +The API returns different fields depending on whether the shard is assigned or unassigned. + +### Common response fields + +The following table lists the common response fields. + +Field | Description +:--- | :--- +`index` | The name of the index containing the shard. +`shard` | The shard ID within the index. +`primary` | Whether this is a primary shard (`true`) or replica shard (`false`). +`current_state` | The current state of the shard: `started`, `unassigned`, `initializing`, or `relocating`. + +### Fields for assigned shards + +The following table lists the response fields for assigned shards. + +Field | Description +:--- | :--- +`current_node` | Information about the node where the shard is currently allocated, including node ID, name, transport address, and custom attributes. +`can_remain_on_current_node` | Whether the shard is allowed to remain on its current node: `yes`, `no`, or `decision_not_taken`. +`can_rebalance_cluster` | Whether rebalancing is allowed in the cluster: `yes`, `no`, or `decision_not_taken`. +`can_rebalance_to_other_node` | Whether the shard can be rebalanced to another node: `yes` or `no`. +`rebalance_explanation` | A human-readable explanation for the rebalancing decision. +`can_remain_decisions` | An array of deciders that determined whether the shard can remain on its current node. Included only when `can_remain_on_current_node` is `no`. +`can_rebalance_cluster_decisions` | An array of deciders that determined whether cluster rebalancing is allowed. Included only when `can_rebalance_cluster` is `no`. +`node_allocation_decisions` | An array of potential target nodes with allocation decisions for each node. + +### Fields for unassigned shards + +The following table lists the response fields for unassigned shards. + +Field | Description +:--- | :--- +`unassigned_info` | Information about why the shard is unassigned, including the reason, timestamp, and last allocation attempt. +`unassigned_info.reason` | The reason the shard became unassigned, such as `INDEX_CREATED`, `CLUSTER_RECOVERED`, `NODE_LEFT`, or `REPLICA_ADDED`. +`unassigned_info.at` | The timestamp (ISO 8601 format) when the shard became unassigned. +`unassigned_info.last_allocation_status` | The result of the last allocation attempt: `no_attempt`, `no`, `throttled`, or `no_valid_shard_copy`. +`unassigned_info.details` | Additional details about why the shard became unassigned. Included only when additional details are available. +`can_allocate` | Whether the shard can be allocated: `yes`, `no`, `throttled`, `no_valid_shard_copy`, or `allocation_delayed`. +`allocate_explanation` | A human-readable explanation for why the shard cannot be allocated. +`configured_delay` | The configured delay before allocating the shard. Included only when `can_allocate` is `allocation_delayed`. +`configured_delay_in_millis` | The configured delay in milliseconds. Included only when `can_allocate` is `allocation_delayed`. +`remaining_delay` | The remaining time before the shard can be allocated. Included only when `can_allocate` is `allocation_delayed`. +`remaining_delay_in_millis` | The remaining delay in milliseconds. Included only when `can_allocate` is `allocation_delayed`. +`node_allocation_decisions` | An array of nodes with allocation decisions for each node. + +### Node allocation decision fields + +The following table lists the fields in the node allocation decisions array. + +Field | Description +:--- | :--- +`node_id` | The unique identifier of the node. +`node_name` | The name of the node. +`transport_address` | The transport address of the node. +`node_attributes` | Custom attributes assigned to the node, such as Availability Zone or instance type. +`node_decision` | The allocation decision for this node: `yes`, `no`, `throttled`, `worse_balance`, or `awaiting_info`. +`weight_ranking` | The relative weight ranking for this node in allocation decisions. Lower values indicate higher preference. Included only when nodes are ranked for allocation decisions. +`deciders` | An array of allocators that made decisions about whether to allocate the shard to this node. +`store` | Information about shard data found on the node (for replica shards). Includes `matching_size` and `matching_size_in_bytes`. Included only when shard store information is available. + +### Decider fields + +Each decider in the `deciders` array contains the following fields. + +Field | Description +:--- | :--- +`decider` | The name of the allocator that made the decision. +`decision` | The decision made by the allocator: `YES`, `NO`, or `THROTTLE`. +`explanation` | A detailed explanation of why the allocator made this decision, including any relevant settings or constraints. + +## Common allocators + +The following table lists common allocators that affect shard allocation decisions. + +Allocator | Description +:--- | :--- +`same_shard` | Prevents a primary shard and its replica from being allocated to the same node. +`disk_threshold` | Checks whether the node has sufficient disk space for the shard based on low and high watermark thresholds. +`filter` | Applies allocation filters based on index settings like `index.routing.allocation.include`, `exclude`, or `require`. +`awareness` | Enforces shard allocation awareness based on node attributes, distributing shards across Availability Zones or racks. +`enable` | Checks whether shard allocation is enabled at the cluster, index, or shard level using the `cluster.routing.allocation.enable` setting. +`throttling` | Limits the number of concurrent shard recoveries based on `cluster.routing.allocation.node_concurrent_recoveries`. +`shards_limit` | Enforces the maximum number of shards per node (`cluster.routing.allocation.total_shards_per_node`) or per index. +`max_retry` | Prevents repeated allocation attempts for shards that have failed allocation multiple times. +`node_version` | Ensures that shards are allocated to nodes with compatible OpenSearch versions, preventing version downgrades. +`snapshot_in_progress` | Prevents shard allocation when a snapshot operation is in progress for that shard. +`restore_in_progress` | Controls allocation during shard restoration from a snapshot. +`rebalance_only_when_active` | Prevents rebalancing when not all shard copies (primaries and replicas) are active in the cluster. +`cluster_rebalance` | Controls when cluster rebalancing is allowed based on the `cluster.routing.allocation.allow_rebalance` setting: `always`, `indices_primaries_active`, or `indices_all_active`. +`replica_after_primary_active` | Ensures that replica shards are only allocated after their primary shard is active. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/allocation/explain`. diff --git a/_api-reference/cluster-api/cluster-awareness.md b/_api-reference/cluster-api/cluster-awareness.md index 18259b9a..642d5865 100644 --- a/_api-reference/cluster-api/cluster-awareness.md +++ b/_api-reference/cluster-api/cluster-awareness.md @@ -1,7 +1,7 @@ --- layout: default title: Cluster routing and awareness -nav_order: 20 +nav_order: 48 parent: Cluster APIs has_children: false redirect_from: @@ -9,125 +9,271 @@ redirect_from: - /opensearch/rest-api/cluster-awareness/ --- -# Cluster routing and awareness -**Introduced 1.0** +# Cluster Routing And Awareness API +**Introduced 2.4** {: .label .label-purple } -To control the distribution of search or HTTP traffic, you can use the weights per awareness attribute to control the distribution of search or HTTP traffic across zones. This is commonly used for zonal deployments, heterogeneous instances, and routing traffic away from zones during zonal failure. +To control how search traffic is routed across zones, you can assign weights to awareness attribute values. This is useful for zonal deployments, heterogeneous clusters, or routing traffic away from unhealthy zones. -## Path and HTTP methods +## Prerequisites +Before using this API, you must configure cluster awareness attributes and node attributes. This can be done either in the `opensearch.yml` file or through the Cluster Settings API. + +For example, to configure `zone` and `rack` awareness attributes using `opensearch.yml`, specify them as a comma-separated list: + +```yaml +cluster.routing.allocation.awareness.attributes: zone,rack ``` -PUT /_cluster/routing/awareness//weights -GET /_cluster/routing/awareness//weights?local -GET /_cluster/routing/awareness//weights +{% include copy.html %} + +Alternatively, you can use the Cluster Settings API to configure the awareness attributes: + + +{% capture step1_rest %} +PUT /_cluster/routing/awareness/zone/weights +{ + "weights": { + "zone_1": "1", + "zone_2": "1", + "zone_3": "0" + }, + "_version": -1 +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_weighted_routing( + attribute = "zone", + body = { + "weights": { + "zone_1": "1", + "zone_2": "1", + "zone_3": "0" + }, + "_version": -1 + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +For more information about OpenSearch settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/). + +## Endpoints + +```json +PUT /_cluster/routing/awareness/{attribute}/weights +GET /_cluster/routing/awareness/{attribute}/weights?local +GET /_cluster/routing/awareness/{attribute}/weights +DELETE /_cluster/routing/awareness/{attribute}/weights ``` ## Path parameters -Parameter | Type | Description +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description :--- | :--- | :--- -attribute | String | The name of the awareness attribute, usually `zone`. The attribute name must match the values listed in the request body when assigning weights to zones. +`attribute` | String | The name of the configured awareness attribute (for example, `zone`). The attribute specified in the path determines which awareness attribute the weights apply to. -## Request body parameters +## Query parameters -Parameter | Type | Description -:--- | :--- | :--- -weights | JSON object | Assigns weights to attributes within the request body of the PUT request. Weights can be set in any ratio, for example, 2:3:5. In a 2:3:5 ratio with 3 zones, for every 100 requests sent to the cluster, each zone would receive either 20, 30, or 50 search requests in a random order. When assigned a weight of `0`, the zone does not receive any search traffic. -_version | String | Implements optimistic concurrency control (OCC) through versioning. The parameter uses simple versioning, such as `1`, and increments upward based on each subsequent modification. This allows any servers from which a request originates to validate whether or not a zone has been modified. +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `local` | Boolean | Can be provided in a `GET` request only. If `true`, the request retrieves information from the node that receives the request instead of from the cluster manager node. Default is `false`.| + +## Request body fields + +The following table lists the available request body fields for the `PUT` and `DELETE` methods. + +| Parameter | Data type | Applicable method | Description | +| :--- | :--- | :--- | :--- | +| `weights` | Object | `PUT` | Specifies custom weights for the awareness attribute values. The weights influence how search requests are distributed across zones or other awareness attribute values. Weights are relative and can use any ratio. For example, in a `2:3:5` ratio across three zones, 20%, 30%, and 50% of requests are routed to the respective zones. A weight of `0` excludes a zone from receiving search traffic. Required for the `PUT` method. | +| `_version` | Integer | `PUT`, `DELETE` | Used for optimistic concurrency control (OCC). Ensures that changes are applied only if the current version matches, preventing conflicting updates. The version is incremented after each succesful `PUT` or `DELETE` operation. To initiate concurrency control, you must set `_version` to `-1` in the initial request. Required for the `PUT` and `DELETE` methods. | -In the following example request body, `zone_1` and `zone_2` receive 50 requests each, whereas `zone_3` is prevented from receiving requests: +## Example request: Weighted round-robin search -``` -{ - "weights": - { - "zone_1": "5", - "zone_2": "5", - "zone_3": "0" - } - "_version" : 1 +The following example request creates a round-robin shard allocation for search traffic between two zones while excluding a third zone from receiving any traffic: + + +{% capture step1_rest %} PUT /_cluster/routing/awareness/zone/weights -{ - "weights": - { - "zone_1": "1", - "zone_2": "1", - "zone_3": "0" - } - "_version" : 1 -} -``` -{% include copy-curl.html %} - -#### Response - -``` { - "acknowledged": true + "weights": { + "zone_1": "1", + "zone_2": "1", + "zone_3": "0" + }, + "_version": -1 } -``` +{% endcapture %} + +{% capture step1_python %} -## Example: Getting weights for all zones +response = client.cluster.put_weighted_routing( + attribute = "zone", + body = { + "weights": { + "zone_1": "1", + "zone_2": "1", + "zone_3": "0" + }, + "_version": -1 + } +) -The following example request gets weights for all zones. +{% endcapture %} -#### Request +{% include code-block.html + rest=step1_rest + python=step1_python %} + -```json +After this request, the `_version` increments to `0`. + +To create a shard allocation for multiple awareness attributes, send a separate request for each attribute. + +## Example request: Updating the configuration + +The `PUT` request fully replaces the existing weight configuration for the specified awareness attribute. Any values omitted in the request are removed from the configuration. For example, the following request updates the weights for zones 1 and 3 and removes zone 2: + + +{% capture step1_rest %} +PUT /_cluster/routing/awareness/zone/weights +{ + "weights": { + "zone_1": "2", + "zone_3": "1" + }, + "_version": 0 +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_weighted_routing( + attribute = "zone", + body = { + "weights": { + "zone_1": "2", + "zone_3": "1" + }, + "_version": 0 + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +After this request, the `_version` increments to `1`. + +## Example request: Viewing the configuration + +To view the current weight configuration and its version, send the following request. Use the returned version number in subsequent update or delete requests: + + +{% capture step1_rest %} GET /_cluster/routing/awareness/zone/weights -``` -{% include copy-curl.html %} +{% endcapture %} -#### Response +{% capture step1_python %} -OpenSearch responds with the weight of each zone: + +response = client.cluster.get_weighted_routing( + attribute = "zone" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```json { - "weights": - { - - "zone_1": "1.0", - "zone_2": "1.0", - "zone_3": "0.0" - }, - "_version":1 + "weights": { + "zone_1": "2.0", + "zone_3": "1.0" + }, + "_version": 1, + "discovered_cluster_manager": true } ``` -## Example: Deleting weights +## Example request: Deleting the configuration -You can remove your weight ratio for each zone using the `DELETE` method. - -#### Request +To remove a weight configuration, provide the current version in a `DELETE` request: ```json DELETE /_cluster/routing/awareness/zone/weights +{ + "_version": 1 +} ``` {% include copy-curl.html %} -#### Response - -```json -{ - "_version":1 -} -``` +After this request, the `_version` increments to `2`. ## Next steps - For more information about zone commissioning, see [Cluster decommission]({{site.url}}{{site.baseurl}}/api-reference/cluster-decommission/). -- For more information about allocation awareness, see [Cluster formation]({{site.url}}{{site.baseurl}}/opensearch/cluster/#advanced-step-6-configure-shard-allocation-awareness-or-forced-awareness). +- For more information about allocation awareness, see [Cluster formation]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#advanced-step-6-configure-shard-allocation-awareness-or-forced-awareness). diff --git a/_api-reference/cluster-api/cluster-decommission.md b/_api-reference/cluster-api/cluster-decommission.md index 867f58ed..1b08f63d 100644 --- a/_api-reference/cluster-api/cluster-decommission.md +++ b/_api-reference/cluster-api/cluster-decommission.md @@ -9,53 +9,113 @@ redirect_from: - /opensearch/rest-api/cluster-decommission/ --- -# Cluster decommission +# Cluster Decommission API **Introduced 1.0** {: .label .label-purple } The cluster decommission operation adds support decommissioning based on awareness. It greatly benefits multi-zone deployments, where awareness attributes, such as `zones`, can aid in applying new upgrades to a cluster in a controlled fashion. This is especially useful during outages, in which case, you can decommission the unhealthy zone to prevent replication requests from stalling and prevent your request backlog from becoming too large. -For more information about allocation awareness, see [Shard allocation awareness]({{site.url}}{{site.baseurl}}//opensearch/cluster/#shard-allocation-awareness). +For more information about allocation awareness, see [Shard allocation awareness]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#shard-allocation-awareness). -## HTTP and Path methods +## Endpoints -``` +```json PUT /_cluster/decommission/awareness/{awareness_attribute_name}/{awareness_attribute_value} GET /_cluster/decommission/awareness/{awareness_attribute_name}/_status DELETE /_cluster/decommission/awareness ``` -## URL parameters +## Path parameters Parameter | Type | Description :--- | :--- | :--- -awareness_attribute_name | String | The name of awareness attribute, usually `zone`. -awareness_attribute_value | String | The value of the awareness attribute. For example, if you have shards allocated in two different zones, you can give each zone a value of `zone-a` or `zoneb`. The cluster decommission operation decommissions the zone listed in the method. +`awareness_attribute_name` | String | The name of awareness attribute, usually `zone`. +`awareness_attribute_value` | String | The value of the awareness attribute. For example, if you have shards allocated in two different zones, you can give each zone a value of `zone-a` or `zoneb`. The cluster decommission operation decommissions the zone listed in the method. +## Example requests -## Example: Decommissioning and recommissioning a zone +The following examples demonstrate how to use the Cluster Decommission API. + +### Decommissioning and recommissioning a zone You can use the following example requests to decommission and recommission a zone: -#### Request The following example request decommissions `zone-a`: -```json + +{% capture step1_rest %} PUT /_cluster/decommission/awareness// -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_decommission_awareness( + awareness_attribute_name = "", + awareness_attribute_value = "" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + If you want to recommission a decommissioned zone, you can use the `DELETE` method: -```json + +{% capture step1_rest %} DELETE /_cluster/decommission/awareness -``` -{% include copy-curl.html %} +{% endcapture %} -#### Response +{% capture step1_python %} +response = client.cluster.delete_decommission_awareness() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Getting zone decommission status + +The following example requests returns the decommission status of all zones. + + +{% capture step1_rest %} +GET /_cluster/decommission/awareness/zone/_status +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.get_decommission_awareness( + awareness_attribute_name = "zone" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example responses + +The following example response shows a successful zone decommission: ```json { @@ -63,18 +123,10 @@ DELETE /_cluster/decommission/awareness } ``` -## Example: Getting zone decommission status +### Getting zone decommission status -The following example requests returns the decommission status of all zones. +The following example response returns the decommission status of all zones: -#### Request - -```json -GET /_cluster/decommission/awareness/zone/_status -``` -{% include copy-curl.html %} - -#### Response ```json { @@ -86,4 +138,4 @@ GET /_cluster/decommission/awareness/zone/_status ## Next steps - For more information about zone awareness and weight, see [Cluster awareness]({{site.url}}{{site.baseurl}}/api-reference/cluster-awareness/). -- For more information about allocation awareness, see [Cluster formation]({{site.url}}{{site.baseurl}}/opensearch/cluster/#advanced-step-6-configure-shard-allocation-awareness-or-forced-awareness). +- For more information about allocation awareness, see [Cluster formation]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#advanced-step-6-configure-shard-allocation-awareness-or-forced-awareness). diff --git a/_api-reference/cluster-api/cluster-health.md b/_api-reference/cluster-api/cluster-health.md index e9e2bb0e..e8476544 100644 --- a/_api-reference/cluster-api/cluster-health.md +++ b/_api-reference/cluster-api/cluster-health.md @@ -9,117 +9,168 @@ redirect_from: - /opensearch/rest-api/cluster-health/ --- -# Cluster health +# Cluster Health API **Introduced 1.0** {: .label .label-purple } -The most basic cluster health request returns a simple status of the health of your cluster. OpenSearch expresses cluster health in three colors: green, yellow, and red. A green status means all primary shards and their replicas are allocated to nodes. A yellow status means all primary shards are allocated to nodes, but some replicas aren't. A red status means at least one primary shard is not allocated to any node. +The cluster health API provides a quick overview of your cluster's operational status. OpenSearch expresses cluster health in three colors that represent the allocation state of shards: -To get the status of a specific index, provide the index name. +- **Green** (best): All primary shards and their replicas are allocated to nodes. The cluster is fully operational. +- **Yellow**: All primary shards are allocated, but some replica shards are unassigned. The cluster is operational, but not fully redundant. +- **Red** (worst): At least one primary shard is unassigned. Some data is unavailable, and search requests may return incomplete results. -## Example - -This request waits 50 seconds for the cluster to reach the yellow status or better: +When determining overall health, the worst status takes precedence: if you request health for multiple indexes, the overall status is determined by the worst index status. Similarly, an index's status is determined by its worst shard status. + +## Endpoints +```json +GET /_cluster/health +GET /_cluster/health/{index} ``` -GET _cluster/health?wait_for_status=yellow&timeout=50s -``` -{% include copy-curl.html %} + -If the cluster health becomes yellow or green before 50 seconds elapse, it returns a response immediately. Otherwise it returns a response as soon as it exceeds the timeout. + +## Path parameters -## Path and HTTP methods +The following table lists the available path parameters. All path parameters are optional. -``` -GET _cluster/health -GET _cluster/health/ -``` +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | List or String | A comma-separated list of data streams, indexes, and aliases used to limit the request. Supports wildcards (`*`). To target all data streams and indexes, omit this parameter or use `*` or `_all`. | + + ## Query parameters The following table lists the available query parameters. All query parameters are optional. -Parameter | Type | Description -:--- | :--- | :--- -expand_wildcards | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. -level | Enum | The level of detail for returned health information. Supported values are `cluster`, `indices`, `shards`, and `awareness_attributes`. Default is `cluster`. -awareness_attribute | String | The name of the awareness attribute, for which to return cluster health (for example, `zone`). Applicable only if `level` is set to `awareness_attributes`. -local | Boolean | Whether to return information from the local node only instead of from the cluster manager node. Default is false. -cluster_manager_timeout | Time | The amount of time to wait for a connection to the cluster manager node. Default is 30 seconds. -timeout | Time | The amount of time to wait for a response. If the timeout expires, the request fails. Default is 30 seconds. -wait_for_active_shards | String | Wait until the specified number of shards is active before returning a response. `all` for all shards. Default is `0`. -wait_for_nodes | String | Wait for N number of nodes. Use `12` for exact match, `>12` and `<12` for range. -wait_for_events | Enum | Wait until all currently queued events with the given priority are processed. Supported values are `immediate`, `urgent`, `high`, `normal`, `low`, and `languid`. -wait_for_no_relocating_shards | Boolean | Whether to wait until there are no relocating shards in the cluster. Default is false. -wait_for_no_initializing_shards | Boolean | Whether to wait until there are no initializing shards in the cluster. Default is false. -wait_for_status | Enum | Wait until the cluster health reaches the specified status or better. Supported values are `green`, `yellow`, and `red`. -weights | JSON object | Assigns weights to attributes within the request body of the PUT request. Weights can be set in any ration, for example, 2:3:5. In a 2:3:5 ratio with three zones, for every 100 requests sent to the cluster, each zone would receive either 20, 30, or 50 search requests in a random order. When assigned a weight of `0`, the zone does not receive any search traffic. +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `awareness_attribute` | String | The name of the awareness attribute for which to return the cluster health status (for example, `zone`). Applicable only if `level` is set to `awareness_attributes`. | N/A | +| `cluster_manager_timeout` | String | The amount of time to wait for a response from the cluster manager node. For more information about supported time units, see [Common parameters]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). | N/A | +| `expand_wildcards` | List or String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | `open` | +| `level` | String | Controls the amount of detail included in the cluster health response.
Valid values are: `awareness_attributes`, `cluster`, `indices`, and `shards`. | `cluster` | +| `local` | Boolean | Whether to return information from the local node only instead of from the cluster manager node. | `false` | +| `timeout` | String | The amount of time to wait for a response from the cluster manager node. For more information about supported time units, see [Common parameters]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). | N/A | +| `wait_for_active_shards` | Integer or String or NULL or String | Waits until the specified number of shards is active before returning a response. Use `all` for all shards.
Valid values are:
- `all`: Wait for all shards to be active. | `0` | +| `wait_for_events` | String | Waits until all currently queued events with the given priority are processed.
Valid values are:
- `immediate`: Highest priority, processed as soon as possible.
- `urgent`: Very high priority, processed after immediate events.
- `high`: High priority, processed after urgent events.
- `normal`: Default priority, processed after high priority events.
- `low`: Low priority, processed after normal events.
- `languid`: Lowest priority, processed after all other events. | N/A | +| `wait_for_no_initializing_shards` | Boolean | Whether to wait until there are no initializing shards in the cluster. | `false` | +| `wait_for_no_relocating_shards` | Boolean | Whether to wait until there are no relocating shards in the cluster. | `false` | +| `wait_for_nodes` | Integer or String | Waits until the specified number of nodes (`N`) is available. Accepts `>=N`, `<=N`, `>N`, and ` Valid values are: `green`, `GREEN`, `yellow`, `YELLOW`, `red`, and `RED`. | N/A | +| `weights` | JSON object | Assigns weights to attributes within the request body of the PUT request. Weights can be set in any ration, for example, 2:3:5. In a 2:3:5 ratio with three zones, for every 100 requests sent to the cluster, each zone would receive either 20, 30, or 50 search requests in a random order. When assigned a weight of `0`, the zone does not receive any search traffic. | N/A | -#### Example request + -The following example request retrieves cluster health for all indexes in the cluster: +## Example request: Retrieving cluster health for all indexes -```json -GET _cluster/health -``` -{% include copy-curl.html %} +The following request retrieves cluster health for all indexes in the cluster: -#### Example response + +{% capture step1_rest %} +GET /_cluster/health +{% endcapture %} + +{% capture step1_python %} + +response = client.cluster.health() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The response contains cluster health information: ```json { "cluster_name" : "opensearch-cluster", - "status" : "green", + "status" : "yellow", "timed_out" : false, - "number_of_nodes" : 2, - "number_of_data_nodes" : 2, + "number_of_nodes" : 1, + "number_of_data_nodes" : 1, "discovered_master" : true, - "active_primary_shards" : 6, - "active_shards" : 12, + "discovered_cluster_manager" : true, + "active_primary_shards" : 138, + "active_shards" : 138, "relocating_shards" : 0, "initializing_shards" : 0, - "unassigned_shards" : 0, + "unassigned_shards" : 110, "delayed_unassigned_shards" : 0, "number_of_pending_tasks" : 0, "number_of_in_flight_fetch" : 0, "task_max_waiting_in_queue_millis" : 0, - "active_shards_percent_as_number" : 100.0 + "active_shards_percent_as_number" : 55.64516129032258 } ``` -## Response fields +The response shows a `yellow` status because this is a single-node cluster with replica shards that cannot be allocated. The `timed_out` field is `false`, indicating the response was returned within the default timeout period. -The following table lists all response fields. +## Example request: Waiting for a specific health status -|Field |Data type |Description | -|:--- |:--- |:--- | -|cluster_name | String | The name of the cluster. | -|status | String | The cluster health status, which represents the state of shard allocation in the cluster. May be `green`, `yellow`, or `red`. | -|number_of_nodes | Integer | The number of nodes in the cluster. | -|number_of_data_nodes | Integer | The number of data nodes in the cluster. | -|discovered_cluster_manager | Boolean | Specifies whether the cluster manager is discovered. | -|active_primary_shards | Integer | The number of active primary shards. | -|active_shards | Integer | The total number of active shards, including primary and replica shards. | -|relocating_shards | Integer | The number of relocating shards. | -|initializing_shards | Integer | The number of initializing shards. | -|unassigned_shards | Integer | The number of unassigned shards. | -|delayed_unassigned_shards | Integer | The number of delayed unassigned shards. | -|number_of_pending_tasks | Integer | The number of pending tasks in the cluster. | -|number_of_in_flight_fetch | Integer | The number of unfinished fetches. | -|task_max_waiting_in_queue_millis | Integer | The maximum wait time for all tasks waiting to be performed, in milliseconds. | -|active_shards_percent_as_number | Double | The percentage of active shards in the cluster. | -|awareness_attributes | Object | Contains cluster health information for each awareness attribute. | +The following request waits 50 seconds for the cluster to reach the yellow status or better: -## Returning cluster health by awareness attribute + +{% capture step1_rest %} +GET /_cluster/health?wait_for_status=yellow&timeout=50s +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.health( + params = { "wait_for_status": "yellow", "timeout": "50s" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If the cluster health becomes yellow or green before 50 seconds elapse, the request returns a response immediately. Otherwise it returns a response as soon as it exceeds the timeout. + +## Example request: Retrieving cluster health by awareness attribute To check cluster health by awareness attribute (for example, zone or rack), specify `awareness_attributes` in the `level` query parameter: -```json -GET _cluster/health?level=awareness_attributes -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cluster/health?level=awareness_attributes +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.health( + params = { "level": "awareness_attributes" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains cluster health metrics partitioned by awareness attribute: @@ -201,16 +252,60 @@ The response contains cluster health metrics partitioned by awareness attribute: If you're interested in a particular awareness attribute, you can include the name of the awareness attribute as a query parameter: -```json -GET _cluster/health?level=awareness_attributes&awareness_attribute=zone -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_cluster/health?level=awareness_attributes&awareness_attribute=zone +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.health( + params = { "level": "awareness_attributes", "awareness_attribute": "zone" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + In response to the preceding request, OpenSearch returns cluster health information only for the `zone` awareness attribute. The unassigned shard information will be accurate only if you [enable replica count enforcement]({{site.url}}{{site.baseurl}}/opensearch/cluster#replica-count-enforcement) and [configure forced awareness]({{site.url}}{{site.baseurl}}/opensearch/cluster#forced-awareness) for the awareness attribute either before cluster start or after cluster start but before any indexing requests. If you enable replica enforcement after the cluster receives indexing requests, the unassigned shard information may be inaccurate. If you don't configure replica count enforcement and forced awareness, the `unassigned_shards` field will contain -1. {: .warning} +## Response body fields + +The following table lists all response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `cluster_name` | String | The name of the cluster. | +| `status` | String | The overall cluster health status based on the state of shard allocation.
- `green`: All primary and replica shards are allocated.
- `yellow`: All primary shards are allocated, but some replicas are not.
- `red`: At least one primary shard is unassigned.

The overall status is determined by the worst shard status across all indexes. | +| `timed_out` | Boolean | Indicates whether the request exceeded the timeout period before the desired health status was reached. `false` means the response was returned within the timeout period. `true` means the timeout expired before the desired status was achieved. | +| `number_of_nodes` | Integer | The total number of nodes in the cluster, including all node types (data, cluster manager, ingest, and so on). | +| `number_of_data_nodes` | Integer | The number of nodes designated as data nodes in the cluster. Data nodes store shards and handle data-related operations. | +| `discovered_cluster_manager` | Boolean | Indicates whether the cluster manager node has been discovered and is reachable. If `false`, the cluster may be in an unstable state. | +| `discovered_master` | Boolean | Legacy field. Use `discovered_cluster_manager` instead. Retained for backward compatibility. | +| `active_primary_shards` | Integer | The number of primary shards that are currently allocated and active in the cluster. Each document is stored in exactly one primary shard. | +| `active_shards` | Integer | The total number of active shards, including both primary and replica shards. A higher number indicates better data redundancy. | +| `relocating_shards` | Integer | The number of shards currently being moved from one node to another. Shard relocation occurs during rebalancing or when nodes join or leave the cluster. | +| `initializing_shards` | Integer | The number of shards currently being initialized. This occurs when an index is first created or when a node rejoins the cluster and needs to recover shard data. | +| `unassigned_shards` | Integer | The number of shards that exist in the cluster state but are not allocated to any node. Unassigned shards typically occur when replicas cannot be allocated (in a single-node cluster) or when a node fails and shards need to be reallocated. | +| `delayed_unassigned_shards` | Integer | The number of unassigned shards whose allocation has been intentionally delayed. OpenSearch can delay allocation to avoid unnecessary shard movements when a node briefly disconnects and is expected to return. | +| `number_of_pending_tasks` | Integer | The number of cluster-level changes (such as index creation, mapping updates, or shard allocation decisions) that are queued and awaiting execution by the cluster manager. | +| `number_of_in_flight_fetch` | Integer | The number of ongoing shard-level fetch operations currently being executed across the cluster. | +| `task_max_waiting_in_queue_millis` | Integer | The time in milliseconds that the longest-waiting task has been in the queue. High values may indicate that the cluster manager is overloaded. | +| `active_shards_percent_as_number` | Double | The percentage of shards that are active out of the total number of shards (primary and replicas) that should exist. A value of 100.0 indicates all shards are allocated. | +| `indices` | Object | Returned when `level=indices` or `level=shards`. Contains per-index health information with the same structure as the cluster-level fields. | +| `shards` | Object | Returned when `level=shards`. Contains per-shard health information, nested within the `indices` object. | +| `awareness_attributes` | Object | Returned when `level=awareness_attributes`. Contains cluster health information partitioned by awareness attributes (such as zone or rack). | + ## Required permissions If you use the Security plugin, make sure you have the appropriate permissions: diff --git a/_api-reference/cluster-api/cluster-pending-tasks.md b/_api-reference/cluster-api/cluster-pending-tasks.md new file mode 100644 index 00000000..aa4cb8db --- /dev/null +++ b/_api-reference/cluster-api/cluster-pending-tasks.md @@ -0,0 +1,98 @@ +--- +layout: default +title: Cluster pending tasks +nav_order: 46 +parent: Cluster APIs +has_children: false +--- + +# Cluster Pending Tasks API +**Introduced 1.0** +{: .label .label-purple } + +The `/_cluster/pending_tasks` API returns a list of cluster-level changes that have not yet been executed. These pending tasks are typically queued operations such as index creation, template updates, shard allocation changes, and other cluster state updates. + +This API is useful for monitoring the state of the cluster and diagnosing delays in cluster state updates, especially when tasks are backed up or stuck. + +## Endpoint + +```json +GET /_cluster/pending_tasks +``` + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------- | +| `local` | Boolean | Whether to return information from the local node only instead of the elected cluster manager node. Default is `false`. | +| `cluster_manager_timeout` | Time | Specifies the timeout for connecting to the cluster manager node. Default is `30s`. | + +## Example request + +The following request returns the list of currently pending cluster state update tasks: + + +{% capture step1_rest %} +GET /_cluster/pending_tasks +{% endcapture %} + +{% capture step1_python %} + +response = client.cluster.pending_tasks() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example response + +```json +{ + "tasks": [ + { + "insert_order": 1234, + "priority": "HIGH", + "source": "create-index [logs-2025.07.15]", + "executing": false, + "time_in_queue_millis": 28, + "time_in_queue": "28ms" + }, + { + "insert_order": 1235, + "priority": "URGENT", + "source": "shard-started shard id [logs-2025.07.15][0]", + "executing": true, + "time_in_queue_millis": 3, + "time_in_queue": "3ms" + } + ] +} +``` + +The `_cluster/pending_tasks` API typically returns an empty array because the tasks are normally processed too quickly to be included in the response. +{: .note} + +## Response fields + +The following table lists all response fields. + +| Field | Data type | Description | +| ------------------------------- | --------- | ------------------------------------------------------------------ | +| `tasks` | Array | The list of pending cluster state update tasks. | +| `tasks[n].insert_order` | Integer | The order in which the task was added to the queue. | +| `tasks[n].priority` | String | The priority level of the task (for example, `HIGH`, `URGENT`). | +| `tasks[n].source` | String | The description of the operation that submitted the task. | +| `tasks[n].executing` | Boolean | Confirmation of whether the task is currently being executed. | +| `tasks[n].time_in_queue_millis` | Integer | The amount of time the task has been waiting in the queue (in milliseconds). | +| `tasks[n].time_in_queue` | String | A human-readable version of `time_in_queue_millis`. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/task`. diff --git a/_api-reference/cluster-api/cluster-reroute.md b/_api-reference/cluster-api/cluster-reroute.md new file mode 100644 index 00000000..8c799836 --- /dev/null +++ b/_api-reference/cluster-api/cluster-reroute.md @@ -0,0 +1,392 @@ +--- +layout: default +title: Cluster reroute +nav_order: 47 +parent: Cluster APIs +has_children: false +--- + +# Cluster Reroute API +**Introduced 1.0** +{: .label .label-purple } + +The `/_cluster/reroute` API allows you to manually control the allocation of individual shards within the cluster. This includes moving, allocating, or canceling shard allocations. It's typically used for advanced scenarios, such as manual recovery or custom load balancing. + +Shard movement is subject to cluster allocation deciders. Always test reroute commands using `dry_run=true` before applying them in production environments. Use the `explain=true` parameter to obtain detailed insight into allocation decisions, which can assist in understanding why a particular reroute request may or may not be allowed. If shard allocation fails because of prior issues or cluster instability, you can reattempt allocation using the `retry_failed=true` parameter. + +For more information regarding shard distribution and cluster health, see [Cluster health]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) and [Cluster allocation explain]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-allocation/). + +## Endpoints + +```json +POST /_cluster/reroute +``` + +## Query parameters + +| Parameter | Data type | Description | +| ---------------- | --------- | -------------------------------------------------------------------------------------------------- | +| `dry_run` | Boolean | If `true`, validates and simulates the reroute request without applying it. Default is `false`. | +| `explain` | Boolean | If `true`, returns an explanation of why the command was accepted or rejected. Default is `false`. | +| `retry_failed` | Boolean | If `true`, retries allocation of shards that previously failed. Default is `false`. | +| `metric` | String | Limits the returned metadata. See [Metric options](#metric-options) for a list of available options. Default is `_all`. | +| `cluster_manager_timeout` | Time | The timeout for connection to the cluster manager node. Default is `30s`. | +| `timeout` | Time | The overall request timeout. Default is `30s`. | + +### Metric options + +The `metric` parameter filters the cluster state values returned by the Reroute API. This is useful for reducing response size or inspecting specific parts of the cluster state. This parameter supports the following values: + +- `_all` _(Default)_: Returns all available cluster state sections. +- `blocks`: Includes information about read- and write-level blocks in the cluster. +- `cluster_manager_node`: Shows which node is currently acting as the cluster manager. +- `metadata`: Returns index settings, mappings, and aliases. If specific indexes are targeted, only their metadata is returned. +- `nodes`: Includes all nodes in the cluster and their metadata. +- `routing_table`: Returns the routing information for all shards and replicas. +- `version`: Displays the cluster state version number. + +You can combine values in a comma-separated list, such as `metric=metadata,nodes,routing_table`. + +## Request body fields + +The `commands` array in the request body defines actions to apply to shard allocation. It supports the following actions. + +### Move + +The `move` command moves a started shard (primary or replica) from one node to another. This can be used to balance load or drain a node before maintenance. The shard must be in the `STARTED` state. Both primary and replica shards can be moved using this command. + +The `move` command requires the following parameters: + +* `index`: The name of the index. +* `shard`: The shard number. +* `from_node`: The name of the node to move the shard from. +* `to_node`: The name of the node to move the shard to. + +### Cancel + +The `cancel` command cancels allocation of a shard (including recovery). This command forces resynchronization by canceling existing allocations and letting the system reinitialize them. Replica shard allocations can be canceled by default, but canceling a primary shard requires `allow_primary=true` in order to prevent accidental data disruption. + +The `cancel` command requires the following parameters: + +* `index`: The name of the index. +* `shard`: The shard number. +* `node`: The name or node ID of the node to perform the action on. +* `allow_primary` _(Optional)_: If `true`, allows cancellation of primary shard allocations. Default is `false`. + +### Allocate replica + +The `allocate_replica` command assigns an unassigned replica to a specified node. This operation respects allocation deciders. Use this command to manually trigger allocation of replicas when automatic allocation fails. + +The `allocate_replica` command requires the following parameters: + +* `index`: The name of the index. +* `shard`: The shard number. +* `node`: The name or node ID of the node to perform the action on. + +### Allocate stale primary + +The `allocate_stale_primary` command force-allocates a primary shard to a node that holds a stale copy. + +This command should be used with extreme caution. It bypasses safety checks and may lead to **data loss**, especially if a more recent shard copy exists on another node that is temporarily offline. If that node rejoins the cluster later, its data will be deleted or replaced by the stale copy that was forcefully promoted. +{: .warning} + +Use this command only when no up-to-date copies are available and you have no way to restore the original data. +{: .tip} + +The `allocate_stale_primary` command requires the following parameters: + +* `index`: The name of the index. +* `shard`: The shard number. +* `node`: The name or node ID of the node to perform the action on. +* `accept_data_loss`: Must be set to `true`. + +### Allocate empty primary + +The `allocate_empty_primary` command force-allocates a new empty primary shard to a node. This operation initializes a new primary shard without any existing data. + +Any previous data for the shard will be **permanently lost**. If a node with valid data for that shard later rejoins the cluster, its copy will be erased. This command is intended for disaster recovery when **no valid shard copies exist** and recovery from backup or a snapshot is not possible. +{: .warning} + +The `allocate_empty_primary` command requires the following parameters: + +* `index`: The name of the index. +* `shard`: The shard number. +* `node` : The name or node ID of the node to perform the action on. +* `accept_data_loss`: Must be set to `true`. + +## Example + +The following are examples of using the Cluster Reroute API. + +### Moving a shard + +Create a sample index: + +```json +PUT /test-cluster-index +{ + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + } +} +``` +{% include copy-curl.html %} + +Run the following reroute command to move shard `0` of the index `test-cluster-index` from node `node1` to node `node2`: + + +{% capture step1_rest %} +POST /_cluster/reroute +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.reroute( + body = { + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Simulating a reroute + +To simulate a reroute without executing it, set `dry_run=true`: + + +{% capture step1_rest %} +POST /_cluster/reroute?dry_run=true +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.reroute( + params = { "dry_run": "true" }, + body = { + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Retrying failed allocations + +If some shards failed to allocate because of previous issues, you can reattempt allocation: + + +{% capture step1_rest %} +POST /_cluster/reroute?retry_failed=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.reroute( + params = { "retry_failed": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Explaining reroute decisions + +To understand why a reroute command is accepted or rejected, add `explain=true`: + + +{% capture step1_rest %} +POST /_cluster/reroute?explain=true +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.reroute( + params = { "explain": "true" }, + body = { + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +This returns a `decisions` array explaining the outcome: + +```json +"decisions": [ + { + "decider": "max_retry", + "decision": "YES", + "explanation": "shard has no previous failures" + }, + { + "decider": "replica_after_primary_active", + "decision": "YES", + "explanation": "shard is primary and can be allocated" + }, + ... + { + "decider": "remote_store_migration", + "decision": "YES", + "explanation": "[none migration_direction]: primary shard copy can be relocated to a non-remote node for strict compatibility mode" + } + ] +``` + +## Response body fields + +The response includes cluster state metadata and, optionally, a `decisions` array if `explain=true` was used. + +| Field | Data type | Description | +| ---------------------------- | --------- | ----------------------------------------------------------------------- | +| `acknowledged` | Boolean | States whether the reroute request was acknowledged. | +| `state.cluster_uuid` | String | The unique identifier of the cluster. | +| `state.version` | Integer | The version of the cluster state. | +| `state.state_uuid` | String | The UUID for this specific state version. | +| `state.master_node` | String | As with `cluster_manager_node`, this is maintained for backward compatibility. | +| `state.cluster_manager_node` | String | The ID of the elected cluster manager node. | +| `state.blocks` | Object | Any global or index-level cluster blocks. | +| `state.nodes` | Object | The cluster node's metadata, including its name and address. | +| `state.routing_table` | Object | The shard routing information for each index. | +| `state.routing_nodes` | Object | The shard allocation organized by node. | +| `commands` | List | A list of processed reroute commands. | +| `explanations` | List | If `explain=true`, includes detailed explanations of the outcomes. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/reroute`. diff --git a/_api-reference/cluster-api/cluster-settings.md b/_api-reference/cluster-api/cluster-settings.md index 35383390..4b433ecf 100644 --- a/_api-reference/cluster-api/cluster-settings.md +++ b/_api-reference/cluster-api/cluster-settings.md @@ -8,84 +8,558 @@ redirect_from: - /opensearch/rest-api/cluster-settings/ --- -# Cluster settings +# Cluster Settings API **Introduced 1.0** {: .label .label-purple } -The cluster settings operation lets you check the current settings for your cluster, review default settings, and change settings. When you update a setting using the API, OpenSearch applies it to all nodes in the cluster. +The Cluster Settings API retrieves or modifies cluster-wide settings that apply to all nodes in your OpenSearch cluster. Settings updated through this API take precedence over those defined in the `opensearch.yml` configuration file. -## Path and HTTP methods +Use the Cluster Settings API for the following purposes: -``` -GET _cluster/settings -PUT _cluster/settings +- Retrieving current cluster configuration to understand how your cluster is configured without accessing individual node configuration files. +- Dynamically adjusting cluster behavior without requiring a cluster restart, such as modifying shard allocation settings or recovery speeds. +- Managing settings that need to be consistent across all nodes in the cluster, ensuring uniform behavior. +- Temporarily changing settings for testing or troubleshooting purposes using transient settings that don't persist across cluster restarts. + +Using this API to manage cluster-wide settings is preferred over manually editing configuration files because it ensures consistency across all nodes and allows for dynamic updates without restarts. +{: .tip} + +When updating cluster settings, you can specify whether changes should be persistent (persist after cluster restarts) or transient (cleared after restart). For more information about persistent and transient settings, setting precedence, and resetting settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +Only dynamic settings can be updated using this API. To determine whether a setting is dynamic and to retrieve its default value and bounds, use the [Describe Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/describe-cluster-settings/). + +## Endpoints + +```json +GET /_cluster/settings +PUT /_cluster/settings ``` -## Path parameters +## Query parameters -All cluster setting parameters are optional. +The following table lists the available query parameters. All query parameters are optional. -Parameter | Data type | Description +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time to wait for a response from the cluster manager node. For more information about supported time units, see [Common parameters]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). _(Default: `30s`)_ | +| `flat_settings` | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of `"cluster": { "max_shards_per_node": 500 }` is `"cluster.max_shards_per_node": "500"`. _(Default: `false`)_ | +| `include_defaults` | Boolean | **`GET` only.** When `true`, returns default cluster settings from the local node. _(Default: `false`)_ | +| `timeout` | String | **`PUT` only.** A duration. Units can be `nanos`, `micros`, `ms` (milliseconds), `s` (seconds), `m` (minutes), `h` (hours) and `d` (days). Also accepts `0` without a unit and `-1` to indicate an unspecified value. _(Default: `30s`)_ | +| `master_timeout`
_DEPRECATED_ | String | _(Deprecated since 2.0: To promote inclusive language, use `cluster_manager_timeout` instead.)_ A duration. Units can be `nanos`, `micros`, `ms` (milliseconds), `s` (seconds), `m` (minutes), `h` (hours) and `d` (days). Also accepts `0` without a unit and `-1` to indicate an unspecified value. | + +## Request body fields + +The `GET` operation has no request body. The following table lists the request body fields for the `PUT` operation. + +Field | Data type | Description :--- | :--- | :--- -flat_settings | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of `"cluster": { "max_shards_per_node": 500 }` is `"cluster.max_shards_per_node": "500"`. -include_defaults (GET only) | Boolean | Whether to include default settings as part of the response. This parameter is useful for identifying the names and current values of settings you want to update. -cluster_manager_timeout | Time unit | The amount of time to wait for a response from the cluster manager node. Default is `30 seconds`. -timeout (PUT only) | Time unit | The amount of time to wait for a response from the cluster. Default is `30 seconds`. +`persistent` | Object | Settings that persist across full cluster restarts. These settings are written to the cluster state and remain until explicitly changed. +`transient` | Object | Settings that apply only until the next full cluster restart. Useful for temporary configuration changes during testing or troubleshooting. - -#### Example request +Within the `persistent` or `transient` objects, specify the settings you want to update as key-value pairs. For example: ```json -GET _cluster/settings?include_defaults=true -``` -{% include copy-curl.html %} - -#### Example response - -```json -PUT _cluster/settings { - "persistent":{ - "action.auto_create_index": false - } + "persistent": { + "cluster.max_shards_per_node": 500 + } } ``` -## Request fields - -The GET operation has no request body options. All cluster setting field parameters are optional. - -Not all cluster settings can be updated using the cluster settings API. You will receive the error message `"setting [cluster.some.setting], not dynamically updateable"` when trying to configure these settings through the API. +Not all cluster settings can be updated dynamically using the Cluster Settings API. When attempting to configure a static setting through the API, you will receive the error message `"setting [cluster.some.setting], not dynamically updateable"`. Static settings must be configured in the `opensearch.yml` file and require a node restart. {: .note } -For a listing of all cluster settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +For a comprehensive list of all available cluster settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). -#### Example request -For a PUT operation, the request body must contain `transient` or `persistent`, along with the setting you want to update: +## Example: Retrieving current cluster settings + +To view the current cluster settings without defaults, send a GET request: + + +{% capture step1_rest %} +GET /_cluster/settings +{% endcapture %} + +{% capture step1_python %} + +response = client.cluster.get_settings() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +The response shows any persistent and transient settings that have been explicitly configured. Empty objects indicate no settings of that type have been set: ```json -PUT _cluster/settings { - "persistent":{ - "cluster.max_shards_per_node": 500 - } + "persistent": { + "cluster": { + "routing": { + "allocation": { + "load_awareness": { + "flat_skew": "2" + } + } + }, + "max_voting_config_exclusions": "10", + "metadata": { + "key": "10s" + }, + "auto_shrink_voting_configuration": "true", + "blocks": { + "create_index": "false", + "create_index.auto_release": "true" + }, + "thread_pool": { + "generic": { + "max": "5" + } + }, + "max_shards_per_node": "500", + "remote": { + "my_remote_cluster": { + "seeds": [ + "127.0.0.1:9300" + ] + }, + "opensearch-cluster": { + "mode": "proxy" + } + }, + "no_cluster_manager_block": "write" + }, + "indices": { + "mapping": { + "max_in_flight_updates": "10" + } + }, + "plugins": { + "ml_commons": { + "only_run_on_ml_node": "false", + "mcp_server_enabled": "true", + "native_memory_threshold": "99" + } + }, + "search_backpressure": { + "mode": "monitor_only" + }, + "action": { + "auto_create_index": "true" + }, + "wlm": { + "workload_group": { + "mode": "disabled", + "duress_streak": "10" + } + }, + "admission_control": { + "cluster": { + "admin": { + "cpu_usage": { + "limit": "4" + } + } + } + }, + "script": { + "context": { + "field": { + "max_compilations_rate": "75/5m", + "cache_expire": "0ms", + "cache_max_size": "100" + }, + "search": { + "max_compilations_rate": "75/5m", + "cache_expire": "0ms", + "cache_max_size": "100" + }, + "ingest": { + "max_compilations_rate": "75/5m", + "cache_expire": "0ms", + "cache_max_size": "100" + } + } + } + }, + "transient": { + "cluster": { + "max_shards_per_node": "1000" + } + } } ``` -{% include copy-curl.html %} -For more information about transient settings, persistent settings, and precedence, see [OpenSearch configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/). +## Example: Including default settings + +To retrieve all cluster settings, including defaults, use the `include_defaults` parameter: + + +{% capture step1_rest %} +GET /_cluster/settings?include_defaults=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.get_settings( + params = { "include_defaults": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +The response includes a `defaults` object containing all default cluster settings (truncated for brevity). This is useful for identifying setting names and their default values before making changes: + +```json +{ + "persistent" : { }, + "transient" : { }, + "defaults" : { + "task_resource_tracking" : { + "enabled" : "true" + }, + "cluster" : { + "metadata" : { + "perf_analyzer" : { + "collectors" : { + "mode" : "0" + }, + "state" : "0", + "config" : { + "overrides" : "" + }, + "pa_node_stats_setting" : "1" + } + }, + "no_master_block" : "metadata_write", + "persistent_tasks" : { + "allocation" : { + "enable" : "all", + "recheck_interval" : "30s" + } + }, + "initial_cluster_manager_nodes" : [ + "opensearch-node1" + ] + } + } +} +``` + +## Example: Using flat settings format + +To return settings in a flat format, which improves readability for nested settings, use the `flat_settings` parameter: + + +{% capture step1_rest %} +GET /_cluster/settings?flat_settings=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.get_settings( + params = { "flat_settings": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + #### Example response ```json { - "acknowledged":true, - "persistent":{ - "cluster":{ - "max_shards_per_node":"500" - } - }, - "transient":{} + "persistent": { + "action.auto_create_index": "true", + "admission_control.cluster.admin.cpu_usage.limit": "4", + "cluster.auto_shrink_voting_configuration": "true", + "cluster.blocks.create_index": "false", + "cluster.blocks.create_index.auto_release": "true", + "cluster.max_shards_per_node": "500", + "cluster.max_voting_config_exclusions": "10", + "cluster.metadata.key": "10s", + "cluster.no_cluster_manager_block": "write", + "cluster.remote.my_remote_cluster.seeds": [ + "127.0.0.1:9300" + ], + "cluster.remote.opensearch-cluster.mode": "proxy", + "cluster.routing.allocation.load_awareness.flat_skew": "2", + "cluster.thread_pool.generic.max": "5", + "indices.mapping.max_in_flight_updates": "10", + "plugins.ml_commons.mcp_server_enabled": "true", + "plugins.ml_commons.native_memory_threshold": "99", + "plugins.ml_commons.only_run_on_ml_node": "false", + "script.context.field.cache_expire": "0ms", + "script.context.field.cache_max_size": "100", + "script.context.field.max_compilations_rate": "75/5m", + "script.context.ingest.cache_expire": "0ms", + "script.context.ingest.cache_max_size": "100", + "script.context.ingest.max_compilations_rate": "75/5m", + "script.context.search.cache_expire": "0ms", + "script.context.search.cache_max_size": "100", + "script.context.search.max_compilations_rate": "75/5m", + "search_backpressure.mode": "monitor_only", + "wlm.workload_group.duress_streak": "10", + "wlm.workload_group.mode": "disabled" + }, + "transient": { + "cluster.max_shards_per_node": "1000" + } } ``` + +## Example: Updating persistent settings + +To update a setting that persists across cluster restarts, include it in the `persistent` object: + + +{% capture step1_rest %} +PUT /_cluster/settings +{ + "persistent": { + "cluster.max_shards_per_node": 500 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_settings( + body = { + "persistent": { + "cluster.max_shards_per_node": 500 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +The `acknowledged` field indicates that the setting was successfully updated. The response includes the updated setting: + +```json +{ + "acknowledged" : true, + "persistent" : { + "cluster" : { + "max_shards_per_node" : "500" + } + }, + "transient" : { } +} +``` + +## Example: Updating transient settings + +To update a setting temporarily (until the next full cluster restart), include it in the `transient` object: + + +{% capture step1_rest %} +PUT /_cluster/settings +{ + "transient": { + "indices.recovery.max_bytes_per_sec": "20mb" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_settings( + body = { + "transient": { + "indices.recovery.max_bytes_per_sec": "20mb" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +The `acknowledged` field indicates that the setting was successfully updated. The response includes the updated setting: + +```json +{ + "acknowledged" : true, + "persistent" : { }, + "transient" : { + "indices" : { + "recovery" : { + "max_bytes_per_sec" : "20mb" + } + } + } +} +``` + +## Example: Resetting a setting + +To reset a setting to its default value, assign it `null`: + + +{% capture step1_rest %} +PUT /_cluster/settings +{ + "transient": { + "indices.recovery.max_bytes_per_sec": null + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_settings( + body = { + "transient": { + "indices.recovery.max_bytes_per_sec": null + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Resetting multiple settings with wildcards + +To reset multiple related settings at once, use wildcard patterns: + + +{% capture step1_rest %} +PUT /_cluster/settings +{ + "persistent": { + "indices.recovery.*": null + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_settings( + body = { + "persistent": { + "indices.recovery.*": null + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +#### Example response + +When a setting is reset, it no longer appears in the response. The setting now uses the next value in the precedence order: + +```json +{ + "acknowledged" : true, + "persistent" : { }, + "transient" : { } +} +``` + + +## Response fields + +The following table lists the response fields. + +Field | Data type | Description +:--- | :--- | :--- +`acknowledged` | Boolean | Indicates whether the settings update was successfully applied to the cluster. Only present in PUT responses. +`persistent` | Object | Contains all persistent cluster settings that have been explicitly configured. Settings in this object persist across full cluster restarts. +`transient` | Object | Contains all transient cluster settings that have been explicitly configured. Settings in this object are cleared after a full cluster restart. +`defaults` | Object | Contains all default cluster settings with their default values. Only present when the `include_defaults` parameter is set to `true` in `GET` requests. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/settings/update`. + +## Related documentation + +- [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/) +- [Describe Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/describe-cluster-settings/) diff --git a/_api-reference/cluster-api/cluster-state.md b/_api-reference/cluster-api/cluster-state.md new file mode 100644 index 00000000..5e2059c0 --- /dev/null +++ b/_api-reference/cluster-api/cluster-state.md @@ -0,0 +1,152 @@ +--- +layout: default +title: Cluster state +nav_order: 55 +parent: Cluster APIs +--- + +# Cluster State API +**Introduced 1.0** +{: .label .label-purple } + +The `/_cluster/state` API retrieves the current state of the cluster, including metadata, routing tables, nodes, and other components. This API is primarily used for monitoring, debugging, and internal purposes. It provides a snapshot of various parts of the cluster's state as maintained by the cluster manager node. + +## Endpoints + +```json +GET /_cluster/state +GET /_cluster/state/{metric} +GET /_cluster/state/{metric}/{target} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| ----------- | ----------------- | ----------- | +| `metric` | String or List | A comma-separated list of metrics to include in the response. See [Metric options](#metric-options) for a list of available options. Default is `_all`. | +| `target` | String or List | A comma-separated list of index names, data streams, and index aliases used to limit the scope of the response. | + +## Metric options + +You can limit the information returned by the API using the `metric` path parameter. The following options are available: + +- `_all` _(Default)_: Returns all metrics. +- `blocks`: Includes information about index-level and global blocks. +- `metadata`: Returns cluster metadata, including settings, index mappings, and templates. +- `nodes`: Returns information about the nodes in the cluster. +- `routing_table`: Provides the routing information for all shards. +- `cluster_manager_node`: Displays the ID of the currently elected cluster manager node. +- `version`: Displays the current cluster state version. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| ---------------- | --------- | ----------- | +| `local` | Boolean | If `true`, retrieves the state from the local node instead of the cluster manager node. Default is `false`. | +| `cluster_manager_timeout` | Time | The timeout duration for connecting to the cluster manager node. Default is `30s`. | +| `flat_settings` | Boolean | If `true`, returns settings in a flat format. Default is `false`. | +| `wait_for_metadata_version` | Integer | Waits until the metadata version is equal to or greater than this value before responding. | +| `wait_for_timeout` | Time | Specifies how long to wait when using `wait_for_metadata_version`. Default is `30s`. | +| `ignore_unavailable` | Boolean | Whether to ignore missing or closed indexes. Default is `false`. | +| `expand_wildcards` | String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes.
Default is `open`. | +| `allow_no_indices` | Boolean | Whether to fail if a wildcard expression or index alias resolves to no indexes. Default is `true`. | + + + +## Example requests + +Retrieve the full cluster state: + + +{% capture step1_rest %} +GET /_cluster/state +{% endcapture %} + +{% capture step1_python %} + +response = client.cluster.state() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Retrieve metadata and the routing table for a specific index: + + +{% capture step1_rest %} +GET /_cluster/state/metadata,routing_table/my-index +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.state( + metric = "metadata,routing_table", + index = "my-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Retrieve only the currently elected cluster manager node: + + +{% capture step1_rest %} +GET /_cluster/state/cluster_manager_node +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.state( + metric = "cluster_manager_node" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Response fields + +The following table lists all response fields. + +| Field | Data type | Description | +| ---------------------- | --------- | --------------------------------------------------------------------------------- | +| `cluster_name` | String | The name of the cluster. | +| `cluster_uuid` | String | The unique identifier for the cluster. | +| `version` | Integer | The current version of the cluster state. | +| `state_uuid` | String | The unique identifier for this version of the state. | +| `master_node` | String | As with `cluster_manager_node`, this is maintained for backward compatibility. | +| `cluster_manager_node` | String | The node ID of the elected cluster manager node. | +| `blocks` | Object | Index-level block settings. | +| `metadata` | Object | Index mappings, settings, and aliases. | +| `nodes` | Object | Details of all nodes in the cluster. | +| `routing_table` | Object | Shard-to-node allocation per index. | +| `routing_nodes` | Object | Lists of shards assigned to each node. | +| `indices` | Object | Index-specific state metadata. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/state`. diff --git a/_api-reference/cluster-api/cluster-stats.md b/_api-reference/cluster-api/cluster-stats.md index 8f8b585a..17931e0b 100644 --- a/_api-reference/cluster-api/cluster-stats.md +++ b/_api-reference/cluster-api/cluster-stats.md @@ -9,39 +9,205 @@ redirect_from: - /opensearch/rest-api/cluster-stats/ --- -# Cluster stats +# Cluster Stats API **Introduced 1.0** {: .label .label-purple } -The cluster stats API operation returns statistics about your cluster. +The Cluster Stats API returns high-level statistics about your cluster, including key index metrics such as shard counts, storage size, and memory usage. Additionally, it provides detailed information about cluster nodes, including node counts, node roles, operating systems, JVM versions, resource utilization (memory and CPU), and installed plugins. -## Example + +## Endpoints +```json +GET /_cluster/stats +GET /_cluster/stats/nodes/{node_id} +GET /_cluster/stats/{metric}/nodes/{node_id} +GET /_cluster/stats/{metric}/{index_metric}/nodes/{node_id} +``` + + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index_metric` | List | A comma-separated list of [index metric groups]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-stats/#index-metric-groups), for example, `docs,store`. | +| `metric` | List | Limit the information returned to the specified metrics. | +| `node_id` | List or String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). | + + + +Although the term `master` was deprecated in favor of `cluster_manager` subsequent to OpenSearch 2.0, the `master` field was retained for backward compatibility. If you have a node that has either a `master` role or a `cluster_manager` role, the `count` increases for both fields by 1. For an example node count increase, see the [example response](#example-response). +{: .note } + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `flat_settings` | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of `"cluster": { "max_shards_per_node": 500 }` is `"cluster.max_shards_per_node": "500"`. _(Default: `false`)_ | +| `timeout` | String | The amount of time to wait for each node to respond. If a node does not respond before its timeout expires, the response does not include its stats. However, timed out nodes are included in the response's `_nodes.failed` property. Defaults to no timeout. | + + + +### Metric groups + +The following table lists all available metric groups. + +Metric | Description +:--- |:---- +`indices` | Statistics about indexes in the cluster. +`os` | Statistics about the operating system, including load and memory. +`process` | Statistics about processes, including open file descriptors and CPU usage. +`jvm` | Statistics about the JVM, including heap usage and threads. +`fs` | Statistics about file system usage. +`plugins` | Statistics about OpenSearch plugins integrated with the nodes. +`network_types` | Statistics about the transport and HTTP networks connected to the nodes. +`discovery_type` | Statistics about the discovery methods used by the nodes to find other nodes in the cluster. +`packaging_types` | Statistics about each node's OpenSearch distribution. +`ingest` | Statistics about ingest pipelines. + +### Index metric groups + +To filter the information returned for the `indices` metric, you can use specific `index_metric` values. These values are only supported when using the following query types: ```json -GET _cluster/stats/nodes/_cluster_manager +GET _cluster/stats/_all/{index_metric}/nodes/{node_id} +GET _cluster/stats/indices/{index_metric}/nodes/{node_id} ``` -{% include copy-curl.html %} -## Path and HTTP methods +The following index metrics are supported: + +- `shards` +- `docs` +- `store` +- `fielddata` +- `query_cache` +- `completion` +- `segments` +- `mappings` +- `analysis` + +## Example request: Retrieving specific index metrics + +The following example request retrieves statistics for `docs` and `segments` index metrics for all nodes: + + +{% capture step1_rest %} +GET /_cluster/stats/indices/docs,segments/nodes/_all + +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.stats( + index_metric = "docs,segments", + metric = "indices", + node_id = "_all" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Retrieving stats for specific nodes + +The following example request returns information about the cluster manager node: + + +{% capture step1_rest %} +GET /_cluster/stats/nodes/_cluster_manager + +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.stats( + node_id = "_cluster_manager" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Using human-readable output + +The following example request includes the `human` query parameter to return byte and size values in human-readable format: + + +{% capture step1_rest %} +GET /_cluster/stats?human&pretty +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.stats( + params = { "human": "true", "pretty": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The `human` parameter adds human-readable fields to the response while preserving the original numeric values. For example, the `jvm.max_uptime_in_millis` field shows only the numeric value in the default response: ```json -GET _cluster/stats -GET _cluster/stats/nodes/ +"jvm": { + "max_uptime_in_millis": 21476787 +} ``` -## URL parameters +When you include the `human` parameter, the response includes both the human-readable `max_uptime` field and the original numeric field: -All cluster stats parameters are optional. +```json +"jvm": { + "max_uptime": "5.9h", + "max_uptime_in_millis": 21480995 +} +``` -Parameter | Type | Description -:--- | :--- | :--- -<node-filters> | List | A comma-separated list of [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters) that OpenSearch uses to filter results. +## Example response - - Although the `master` node is now called `cluster_manager` for version 2.0, we retained the `master` field for backwards compatibility. If you have a node that has either a `master` role or a `cluster_manager` role, the `count` increases for both fields by 1. To see an example node count increase, see the Response sample. - {: .note } - -## Response +
+ + Response + + {: .text-delta} ```json { @@ -88,7 +254,8 @@ Parameter | Type | Description }, "fielddata": { "memory_size_in_bytes": 664, - "evictions": 0 + "evictions": 0, + "item_count": 1 }, "query_cache": { "memory_size_in_bytes": 0, @@ -483,37 +650,102 @@ Parameter | Type | Description } } ``` +
## Response body fields -Field | Description -:--- | :--- -nodes | How many nodes returned in the response. -cluster_name | The cluster's name. -cluster_uuid | The cluster's uuid. -timestamp | The Unix epoch time of when the cluster was last refreshed. -status | The cluster's health status. -indices | Statistics about the indexes in the cluster. -indices.count | How many indexes are in the cluster. -indices.shards | Information about the cluster's shards. -indices.docs | How many documents are still in the cluster and how many documents are deleted. -indices.store | Information about the cluster's storage. -indices.fielddata | Information about the cluster's field data -indices.query_cache | Data about the cluster's query cache. -indices.completion | How many bytes in memory are used to complete operations. -indices.segments | Information about the cluster's segments, which are small Lucene indexes. -indices.mappings | Mappings within the cluster. -indices.analysis | Information about analyzers used in the cluster. -nodes | Statistics about the nodes in the cluster. -nodes.count | How many nodes were returned from the request. -nodes.versions | OpenSearch's version number. -nodes.os | Information about the operating systems used in the nodes. -nodes.process | The processes the returned nodes use. -nodes.jvm | Statistics about the Java Virtual Machines in use. -nodes.fs | The nodes' file storage. -nodes.plugins | The OpenSearch plugins integrated within the nodes. -nodes.network_types | The transport and HTTP networks within the nodes. -nodes.discovery_type | The method the nodes use to find other nodes within the cluster. -nodes.packaging_types | Information about the nodes' OpenSearch distribution. -nodes.ingest | Information about the nodes' ingest pipelines/nodes, if there are any. -total_time_spent | The total amount of download and upload time spent across all shards in the cluster when downloading or uploading from the remote store. +The following table lists the response fields. + +Field | Data type | Description +:--- | :--- | :--- +`_nodes` | Object | Provides a summary of node-level request results. +`_nodes.total` | Integer | The total number of nodes included in the request. +`_nodes.successful` | Integer | The number of nodes that successfully processed the request. +`_nodes.failed` | Integer | The number of nodes that failed to respond or rejected the request. If nonzero, failure details are included in the response. +`cluster_name` | String | The name of the cluster. +`cluster_uuid` | String | The unique identifier of the cluster. +`timestamp` | Long | The time when the cluster statistics were last updated, in milliseconds since epoch. +`status` | String | The cluster health status: `green`, `yellow`, or `red`. +`indices` | Object | Aggregated statistics for indexes with shards on the specified nodes. +`indices.count` | Integer | The total number of indexes with shards on the specified nodes. +`indices.shards` | Object | Aggregated shard statistics for the specified nodes. +`indices.shards.total` | Integer | The total number of shards on the specified nodes. +`indices.shards.primaries` | Integer | The number of primary shards on the specified nodes. +`indices.shards.replication` | Float | The ratio of replica shards to primary shards across the specified nodes. +`indices.shards.index.shards.min` | Integer | The minimum number of shards per index (considering only shards on the specified nodes). +`indices.shards.index.shards.max` | Integer | The maximum number of shards per index (considering only shards on the specified nodes). +`indices.shards.index.shards.avg` | Float | The average number of shards per index (considering only shards on the specified nodes). +`indices.shards.index.primaries.min` | Integer | The minimum number of primary shards per index (considering only shards on the specified nodes). +`indices.shards.index.primaries.max` | Integer | The maximum number of primary shards per index (considering only shards on the specified nodes). +`indices.shards.index.primaries.avg` | Float | The average number of primary shards per index (considering only shards on the specified nodes). +`indices.shards.index.replication.min` | Float | The minimum replication factor per index (considering only shards on the specified nodes). +`indices.shards.index.replication.max` | Float | The maximum replication factor per index (considering only shards on the specified nodes). +`indices.shards.index.replication.avg` | Float | The average replication factor per index (considering only shards on the specified nodes). +`indices.docs` | Object | Document statistics for the specified nodes. +`indices.docs.count` | Integer | The total number of non-deleted documents across all primary shards on the specified nodes. Includes documents in Lucene segments and may count nested documents. +`indices.docs.deleted` | Integer | The total number of deleted documents across all primary shards on the specified nodes. Disk space is reclaimed during segment merges. +`indices.store.size_in_bytes` | Long | The total storage size of all shards on the specified nodes, in bytes. +`indices.store.reserved_in_bytes` | Long | The amount of disk space reserved for ongoing operations such as segment merges, in bytes. +`indices.fielddata.memory_size_in_bytes` | Long | The total amount of memory used by the field data cache across the specified nodes, in bytes. +`indices.fielddata.evictions` | Long | The number of field data cache evictions across the specified nodes. +`indices.query_cache.memory_size_in_bytes` | Long | The total amount of memory used by the query cache across the specified nodes, in bytes. +`indices.query_cache.total_count` | Long | The total number of query cache accesses (hits and misses) across the specified nodes. +`indices.query_cache.hit_count` | Long | The number of query cache hits across the specified nodes. +`indices.query_cache.miss_count` | Long | The number of query cache misses across the specified nodes. +`indices.query_cache.cache_size` | Integer | The current number of entries in the query cache across the specified nodes. +`indices.query_cache.cache_count` | Long | The total number of entries added to the query cache, including evicted entries. +`indices.query_cache.evictions` | Long | The number of query cache evictions across the specified nodes. +`indices.completion.size_in_bytes` | Long | The total amount of memory used for completion suggesters across the specified nodes, in bytes. +`indices.segments` | Object | Segment statistics for the specified nodes. +`indices.segments.count` | Integer | The total number of segments across all shards on the specified nodes. +`indices.segments.memory_in_bytes` | Long | The total amount of memory used by segments across the specified nodes, in bytes. +`indices.segments.terms_memory_in_bytes` | Long | The amount of memory used for term dictionaries across the specified nodes, in bytes. +`indices.segments.stored_fields_memory_in_bytes` | Long | The amount of memory used for stored fields across the specified nodes, in bytes. +`indices.segments.term_vectors_memory_in_bytes` | Long | The amount of memory used for term vectors across the specified nodes, in bytes. +`indices.segments.norms_memory_in_bytes` | Long | The amount of memory used for normalization factors across the specified nodes, in bytes. +`indices.segments.points_memory_in_bytes` | Long | The amount of memory used for point values (numeric or geographic) across the specified nodes, in bytes. +`indices.segments.doc_values_memory_in_bytes` | Long | The amount of memory used for doc values across the specified nodes, in bytes. +`indices.segments.index_writer_memory_in_bytes` | Long | The amount of memory used by index writers across the specified nodes, in bytes. +`indices.segments.version_map_memory_in_bytes` | Long | The amount of memory used by version maps across the specified nodes, in bytes. +`indices.segments.fixed_bit_set_memory_in_bytes` | Long | The amount of memory used by fixed bit sets (for nested and join fields) across the specified nodes, in bytes. +`indices.segments.max_unsafe_auto_id_timestamp` | Long | The most recent timestamp of a retried indexing request, in milliseconds. +`indices.segments.file_sizes` | Object | This object is not populated by the Cluster Stats API. To get information on segment files, use the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/). +`indices.mappings.field_types` | Array | Statistics about field data types used on the specified nodes. +`indices.mappings.field_types.name` | String | The field data type. +`indices.mappings.field_types.count` | Integer | The number of fields mapped to this data type. +`indices.mappings.field_types.index_count` | Integer | The number of indexes that use this data type. +`indices.analysis` | Object | Statistics about analyzers and analysis components used on the specified nodes. +`nodes` | Object | Aggregated statistics for the specified nodes. +`nodes.count.total` | Integer | The total number of nodes. +`nodes.count.coordinating_only` | Integer | The number of nodes with no assigned roles (coordinating-only nodes). +`nodes.count.` | Integer | The number of nodes with a specific role (for example, `data`, `ingest`, `cluster_manager`). +`nodes.versions` | Array | The OpenSearch versions running on the specified nodes. +`nodes.os.available_processors` | Integer | The total number of processors available to the JVM across the specified nodes. +`nodes.os.allocated_processors` | Integer | The number of processors used for thread pool sizing across the specified nodes (capped at 32). +`nodes.os.mem.total_in_bytes` | Long | The total physical memory across the specified nodes, in bytes. +`nodes.os.mem.free_in_bytes` | Long | The amount of free physical memory across the specified nodes, in bytes. +`nodes.os.mem.used_in_bytes` | Long | The amount of used physical memory across the specified nodes, in bytes. +`nodes.os.mem.free_percent` | Integer | The percentage of free physical memory across the specified nodes. +`nodes.os.mem.used_percent` | Integer | The percentage of used physical memory across the specified nodes. +`nodes.process.cpu.percent` | Integer | The CPU usage percentage across the specified nodes. Returns `-1` if not supported. +`nodes.process.open_file_descriptors.min` | Integer | The minimum number of open file descriptors across the specified nodes. Returns `-1` if not supported. +`nodes.process.open_file_descriptors.max` | Integer | The maximum number of open file descriptors across the specified nodes. Returns `-1` if not supported. +`nodes.process.open_file_descriptors.avg` | Integer | The average number of open file descriptors across the specified nodes. Returns `-1` if not supported. +`nodes.jvm.max_uptime_in_millis` | Long | The maximum JVM uptime, in milliseconds, across the specified nodes. +`nodes.jvm.versions` | Array | Statistics about JVM versions running on the specified nodes. +`nodes.jvm.mem.heap_used_in_bytes` | Long | The heap memory currently in use across the specified nodes, in bytes. +`nodes.jvm.mem.heap_max_in_bytes` | Long | The maximum heap memory available across the specified nodes, in bytes. +`nodes.jvm.threads` | Integer | The total number of active JVM threads across the specified nodes. +`nodes.fs.total_in_bytes` | Long | The total filesystem capacity across the specified nodes, in bytes. +`nodes.fs.free_in_bytes` | Long | The total unallocated disk space across the specified nodes, in bytes. +`nodes.fs.available_in_bytes` | Long | The disk space available to the JVM across the specified nodes (may be less than free space because of operating system restrictions), in bytes. +`nodes.plugins` | Array | Information about installed plugins and modules on the specified nodes. +`nodes.network_types` | Object | Statistics about transport and HTTP network types used by the specified nodes. +`nodes.discovery_types` | Object | Statistics about discovery mechanisms used by the specified nodes. +`nodes.packaging_types` | Array | Information about the distribution types installed on the specified nodes. +`nodes.ingest.number_of_pipelines` | Integer | The total number of ingest pipelines across the specified nodes. +`nodes.ingest.processor_stats` | Object | Statistics about ingest processors used on the specified nodes. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/stats`. diff --git a/_api-reference/cluster-api/cluster-voting-configuration-exclusions.md b/_api-reference/cluster-api/cluster-voting-configuration-exclusions.md new file mode 100644 index 00000000..3a400874 --- /dev/null +++ b/_api-reference/cluster-api/cluster-voting-configuration-exclusions.md @@ -0,0 +1,132 @@ +--- +layout: default +title: Voting configuration exclusions +parent: Cluster APIs +nav_order: 75 +--- + +# Voting Configuration Exclusions API +**Introduced 1.0** +{: .label .label-purple } + +The `_cluster/voting_config_exclusions` API allows you to exclude one or more nodes from the voting configuration. This is useful when you want to safely remove cluster-manager-eligible nodes from the cluster or to change the current cluster manager. + +## Adding voting configuration exclusions + +Use the POST method to add voting configuration exclusions. + +### Endpoints +```json +POST /_cluster/voting_config_exclusions +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +|:-------------|:---------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `node_ids` | List or String | A comma-separated list of node IDs to exclude from the voting configuration. When using this setting, you cannot also specify `node_names`. Either `node_ids` or `node_names` is required in order to receive a valid response. | +| `node_names` | List or String | A comma-separated list of node names to exclude from the voting configuration. When using this setting, you cannot also specify `node_ids`. Either `node_ids` or `node_names` is required in order to receive a valid response. | +| `timeout` | String | When adding a voting configuration exclusion, the API waits for the specified nodes to be excluded from the voting configuration before returning a response. If the timeout expires before the appropriate condition is satisfied, the request fails and returns an error. | + +### Example + +Exclude a node named `opensearch-node1` from the voting configuration: + + +{% capture step1_rest %} +POST /_cluster/voting_config_exclusions?node_names=opensearch-node1 + +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.post_voting_config_exclusions( + params = { "node_names": "opensearch-node1" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Alternatively, you can specify the node IDs as a comma-separated list: + + +{% capture step1_rest %} +POST /_cluster/voting_config_exclusions?node_ids=6ITS4DmNR7OJT1G5lyW8Lw,PEEW2S7-Su2XCA4zUE9_2Q + +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.post_voting_config_exclusions( + params = { "node_ids": "6ITS4DmNR7OJT1G5lyW8Lw,PEEW2S7-Su2XCA4zUE9_2Q" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Removing voting configuration exclusions + +Use the DELETE method to clear the list of nodes that were previously excluded from the voting configuration. This is typically used after excluded nodes have been safely removed or replaced. You can optionally wait for the nodes to be removed from the cluster before clearing the exclusions. + +### Endpoints + +```json +DELETE /_cluster/voting_config_exclusions +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +|:-------------------|:----------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `wait_for_removal` | Boolean | Specifies whether to wait for all excluded nodes to be removed from the cluster before clearing the voting configuration exclusions list. When `true`, all excluded nodes are removed from the cluster before this API takes any action. When `false`, the voting configuration exclusions list is cleared even if some excluded nodes are still present in the cluster. _(Default: `true`)_ | + +### Example + +Use the following request to remove all voting configuration exclusions without waiting for nodes to be removed: + + +{% capture step1_rest %} +DELETE /_cluster/voting_config_exclusions?wait_for_removal=false + +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.delete_voting_config_exclusions( + params = { "wait_for_removal": "false" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + diff --git a/_api-reference/cluster-api/describe-cluster-settings.md b/_api-reference/cluster-api/describe-cluster-settings.md new file mode 100644 index 00000000..7a2d63c3 --- /dev/null +++ b/_api-reference/cluster-api/describe-cluster-settings.md @@ -0,0 +1,107 @@ +--- +layout: default +title: Describe cluster settings +nav_order: 52 +parent: Cluster APIs +--- + +# Describe Cluster Settings API +**Introduced 3.10** +{: .label .label-purple } + +Returns the definitions of the specified cluster settings. For each setting, the response states whether the setting is dynamic or static, its default value, and its value type and bounds. Dynamic settings can be updated on a running cluster. Static settings require a node restart to change. For more information, see [Static settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/#static-settings) and [Dynamic settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/#dynamic-settings). + +The API does not return configured values, so it does not expose values from `opensearch.yml`, the keystore, or the cluster state. + +Because the response is derived from the setting definitions and is identical on every node, any node can serve the request. The request is not routed to the elected cluster manager node. + +## Endpoints + +```json +GET /_cluster/settings/_describe +``` + +## Query parameters + +The following table lists the available query parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `settings` | String | A comma-separated list of setting names to describe. Each entry is either an exact name, such as `cluster.max_shards_per_node`, or a prefix ending in `.*`, such as `cluster.routing.allocation.*`, which describes every registered setting under that prefix at any depth. Exact names and prefixes can be mixed in one request. A prefix expands only to settings with fixed names. It does not expand to secure (keystore) settings or to settings whose names contain a variable part, such as `cluster.remote..seeds`. To describe these settings, request them by exact name, such as `cluster.remote.alpha.seeds`. Required. | + +## Example request + +The following request describes the `cluster.max_shards_per_node`, `cluster.blocks.read_only`, and `cluster.name` settings: + +```json +GET /_cluster/settings/_describe?settings=cluster.max_shards_per_node,cluster.blocks.read_only,cluster.name +``` +{% include copy-curl.html %} + +## Example response + +The `cluster.name` setting is static and declares no readable value type, so its response contains no `validation` object: + +```json +{ + "settings": { + "cluster.blocks.read_only": { + "dynamic": true, + "default": "false", + "validation": { + "type": "boolean" + } + }, + "cluster.max_shards_per_node": { + "dynamic": true, + "default": "1000", + "validation": { + "type": "integer", + "min": "1" + } + }, + "cluster.name": { + "dynamic": false, + "default": "opensearch" + } + } +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `settings` | Object | A map of setting names to their definitions. Setting names are returned in sorted order. | + +The response omits any requested setting that is unknown or filtered. Filtered settings, such as credentials, are hidden from the settings APIs. A request that contains both known and unknown names returns `200 OK` and describes only the known names. + +Each object in `settings` contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `dynamic` | Boolean | If `true`, the setting can be updated on a running cluster using the [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/). If `false`, the setting is static and can be set only in `opensearch.yml` before a node starts. This field describes the setting definition only. It does not indicate whether the calling user is permitted to update the setting. This field is always present. | +| `default` | String | The default value declared in the setting definition, in the string form that the Cluster Settings API accepts, such as `"30s"`, `"85%"`, or `"[]"` for an empty list. Omitted for secure (keystore) settings and for settings that declare an empty default. Some defaults are computed by the node that responds to the request. For example, `node.processors` defaults to that node's processor count. | +| `validation` | Object | The declared value type and bounds. Present only when the setting is defined using one of the types listed in the following table. Settings that use custom parsing, such as string, list, or enumerated settings, have no `validation` object. | +| `description` | String | The description declared in the setting definition. Omitted when the definition does not include a description. | + +The `validation` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `type` | String | The value type. Valid values are `boolean`, `integer`, `long`, `float`, `double`, `time`, `byte_size`, and `memory_size`. This field is always present in the `validation` object. | +| `min` | String | The smallest accepted value, in the same string form as `default`. Omitted when the definition places no lower bound on the value. | +| `max` | String | The largest accepted value, in the same string form as `default`. Omitted when the definition places no upper bound on the value. | + +For a `memory_size` setting, `min` and `max` describe the percentage form of the value (0--100%). These settings also accept an absolute byte size, such as `10gb`, which these bounds do not constrain. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/settings/describe`. + +## Related documentation + +- [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/) +- [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/) diff --git a/_api-reference/cluster-api/index.md b/_api-reference/cluster-api/index.md index 4432c114..97cc3d68 100644 --- a/_api-reference/cluster-api/index.md +++ b/_api-reference/cluster-api/index.md @@ -2,9 +2,11 @@ layout: default title: Cluster APIs has_children: true -nav_order: 15 +has_toc: false +nav_order: 30 redirect_from: - /opensearch/api-reference/cluster-api/ + - /api-reference/cluster-api/ --- # Cluster APIs @@ -12,3 +14,24 @@ redirect_from: {: .label .label-purple } The cluster APIs allow you to manage your cluster. You can use them to check cluster health, modify settings, retrieve statistics, and more. + +## Cluster API operations + +The following cluster API operations are available. + +### Cluster information and status +- [Cluster health]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) +- [Cluster pending tasks]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-pending-tasks/) +- [Cluster settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/) +- [Describe cluster settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/describe-cluster-settings/) +- [Cluster state]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-state/) +- [Cluster stats]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-stats/) +- [Info]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/info/) +- [Remote info]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/remote-info/) + +### Cluster management +- [Cluster allocation]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-allocation/) +- [Cluster awareness]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-awareness/) +- [Cluster decommission]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-decommission/) +- [Cluster reroute]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-reroute/) +- [Cluster voting configuration exclusions]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-voting-configuration-exclusions/) diff --git a/_api-reference/cluster-api/info.md b/_api-reference/cluster-api/info.md new file mode 100644 index 00000000..db67a76e --- /dev/null +++ b/_api-reference/cluster-api/info.md @@ -0,0 +1,73 @@ +--- +layout: default +title: Cluster information +nav_order: 45 +parent: Cluster APIs +has_children: false +--- + +# Cluster Information API +**Introduced 1.0** +{: .label .label-purple } + +The Cluster Information API (`/`) retrieves information about the running OpenSearch cluster and node, including version, build details, and cluster name. This is the simplest way to verify that a cluster is reachable and to discover the OpenSearch version. + +## Endpoints + +```json +GET / +HEAD / +``` + +- `GET /` returns a JSON body containing cluster and version details. +- `HEAD /` returns only an HTTP status (200 if reachable), useful for lightweight health checks. + +## Example request + +To get the version and build information for the cluster, send the following request: + +```json +GET / +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "name": "opensearch-node1", + "cluster_name": "opensearch-cluster", + "cluster_uuid": "sQj1b9cZQICv0b8iYc3y5A", + "version": { + "distribution": "opensearch", + "number": "3.2.0", + "build_type": "tar", + "build_hash": "abc123def456", + "build_date": "2025-06-18T12:34:56.000Z", + "build_snapshot": false, + "lucene_version": "9.10.0", + "minimum_wire_compatibility_version": "7.10.0", + "minimum_index_compatibility_version": "7.0.0" + }, + "tagline": "The OpenSearch Project: https://opensearch.org/" +} +``` + +## Response body fields + +Field | Type | Description +:--- | :--- | :--- +`name` | String | The name of the node that served the request. +`cluster_name` | String | The name of the cluster. +`cluster_uuid` | String | The universally unique identifier (UUID) of the cluster. +`tagline` | String | The tagline string. +`version` | Object | The object containing version and build metadata. +`version.distribution` | String | The distribution identifier, typically `opensearch`. +`version.number` | String | The OpenSearch version number, for example, `3.2.0`. +`version.build_type` | String | The distribution type. +`version.build_hash` | String | The commit hash the build was created from. +`version.build_date` | String | The build timestamp in ISO 8601 format. +`version.build_snapshot` | Boolean | Whether the build is a snapshot build. +`version.lucene_version` | String | The Lucene version used by this build. +`version.minimum_wire_compatibility_version` | String | The minimum compatible transport protocol version. +`version.minimum_index_compatibility_version` | String | The minimum index version that can be read. diff --git a/_api-reference/cluster-api/remote-info.md b/_api-reference/cluster-api/remote-info.md new file mode 100644 index 00000000..2e532cbb --- /dev/null +++ b/_api-reference/cluster-api/remote-info.md @@ -0,0 +1,118 @@ +--- +layout: default +title: Remote cluster information +parent: Cluster APIs +nav_order: 67 +redirect_from: + - /opensearch/rest-api/remote-info/ + - /api-reference/remote-info/ +--- + +# Remote Cluster Information API +**Introduced 1.0** +{: .label .label-purple } + +The Remote Cluster Information API retrieves connection details for all remote OpenSearch clusters configured on the local cluster. Use this API to verify connectivity status, inspect connection modes (`sniff` or `proxy`), and review timeout settings for cross-cluster search configurations. + +The response provides more detail than a call to `_cluster/settings`, which only returns the cluster alias and seed node addresses. This API additionally reports the active connection count, connection mode, and whether unavailable clusters are skipped during cross-cluster searches. + + +## Endpoints +```json +GET /_remote/info +``` + + +## Example request + +The following example retrieves information about all configured remote clusters: + + +{% capture step1_rest %} +GET /_remote/info +{% endcapture %} + +{% capture step1_python %} + +response = client.cluster.remote_info() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +When no remote clusters are configured, the response is an empty object: + +```json +{ } +``` + +When one or more remote clusters are configured in `sniff` mode, the response includes connection details keyed by the cluster alias: + +```json +{ + "opensearch-cluster2": { + "connected": true, + "mode": "sniff", + "seeds": [ + "172.28.0.2:9300" + ], + "num_nodes_connected": 1, + "max_connections_per_cluster": 3, + "initial_connect_timeout": "30s", + "skip_unavailable": false + } +} +``` + +When a remote cluster is configured in `proxy` mode, the response includes proxy-specific fields instead of seed node information: + +```json +{ + "opensearch-cluster3": { + "connected": true, + "mode": "proxy", + "proxy_address": "192.168.1.50:9443", + "num_proxy_sockets_connected": 5, + "max_proxy_socket_connections": 18, + "initial_connect_timeout": "30s", + "skip_unavailable": true + } +} +``` + +## Response body fields + +The response is a JSON object where each key is a remote cluster alias. The following table describes the fields within each cluster entry. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `connected` | Boolean | Indicates whether at least one active connection exists to the remote cluster. | +| `mode` | String | The connection mode configured for the remote cluster. Valid values are `sniff` (discovers nodes through seed addresses) and `proxy` (routes all requests through a single proxy address). | +| `initial_connect_timeout` | String | The timeout duration for establishing the initial connection to the remote cluster. | +| `skip_unavailable` | Boolean | Indicates whether the remote cluster is skipped when it is unreachable during a cross-cluster search request. When `true`, the search returns results from available clusters only. When `false`, the entire search request fails if this cluster is unavailable. | + +The following fields appear only when `mode` is `sniff`. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `seeds` | Array of strings | The initial seed transport addresses used to discover nodes in the remote cluster. | +| `num_nodes_connected` | Integer | The number of nodes in the remote cluster to which the local cluster currently has open connections. | +| `max_connections_per_cluster` | Integer | The maximum number of connections the local cluster maintains to the remote cluster. | + +The following fields appear only when `mode` is `proxy`. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `proxy_address` | String | The address (host and port) through which all connections to the remote cluster are routed. | +| `num_proxy_sockets_connected` | Integer | The number of socket connections currently open to the proxy address. | +| `max_proxy_socket_connections` | Integer | The maximum number of socket connections allowed to the proxy address. | diff --git a/_api-reference/common-parameters.md b/_api-reference/common-parameters.md index 347d38a0..6afdd75d 100644 --- a/_api-reference/common-parameters.md +++ b/_api-reference/common-parameters.md @@ -1,92 +1,267 @@ --- layout: default -title: Common REST Parameters -nav_order: 93 +title: Common REST parameters +nav_order: 150 redirect_from: - /opensearch/common-parameters/ --- # Common REST parameters -**Introduced 1.0** -{: .label .label-purple } -OpenSearch supports the following parameters for all REST operations: +OpenSearch REST APIs share the following query parameters, request body conventions, and headers. + +Boolean parameters accept only `true` and `false`. OpenSearch rejects other values, such as `yes` or `1`. Numeric parameters accept either a JSON number or a string containing a number, so `"size": 10` and `"size": "10"` are equivalent. For the units accepted by time, byte size, and distance parameters, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). ## Human-readable output -To convert output units to human-readable values (for example, `1h` for 1 hour and `1kb` for 1,024 bytes), add `?human=true` to the request URL. +Many APIs, such as the stats APIs, return values that have units, such as sizes and durations. By default, OpenSearch returns these values only in a raw form intended for programs, such as `size_in_bytes`. To also return a human-readable version of each value, add `?human=true` to the request URL. For example, the store size of an index is returned as both `"size": "4.2kb"` and `"size_in_bytes": 4356`. For a list of supported units, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). -#### Example request - -The following request requires response values to be in human-readable format: +The following request returns the index statistics using human-readable values: ```json - -GET /_search?human=true +GET /products/_stats/store?human=true ``` +{% include copy-curl.html %} ## Pretty result -To get back JSON responses in a readable format, add `?pretty=true` to the request URL. +To get back JSON responses in a readable, indented format, add `?pretty=true` to the request URL. Use this parameter only when reading responses manually because it increases the response size. -#### Example request - -The following request requires the response to be displayed in pretty JSON format: +The following request returns the cluster health in pretty JSON format: ```json - -GET /_search?pretty=true +GET /_cluster/health?pretty=true ``` +{% include copy-curl.html %} + +## YAML output + +To return the response in YAML format, add `?format=yaml` to the request URL. + +The following request returns the cluster health in YAML format: + +```json +GET /_cluster/health?format=yaml +``` +{% include copy-curl.html %} ## Content type -To specify the type of content in the request body, use the `Content-Type` key name in the request header. Most operations support JSON, YAML, and CBOR formats. - -#### Example request +To specify the type of content in the request body, use the `Content-Type` key name in the request header. Most operations support JSON, YAML, CBOR, and SMILE formats. If you send a request body in YAML, OpenSearch returns the response in YAML as well. The [Bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) and [Multi-search]({{site.url}}{{site.baseurl}}/api-reference/search-apis/multi-search/) APIs accept only newline-delimited JSON (`application/x-ndjson`), JSON, and SMILE. OpenSearch rejects requests whose `Content-Type` is not a supported format. The following request specifies JSON format for the request body: -```json - -curl -H "Content-type: application/json" -XGET localhost:9200/_scripts/ +```bash +curl -H "Content-Type: application/json" -XGET "localhost:9200/products/_search" -d '{"query": {"match_all": {}}}' ``` +{% include copy.html %} + +## Comments in request bodies + +JSON request bodies can contain comments in `/* */` or `//` format. Comments are useful in requests that you store and reuse, such as index or component template definitions. OpenSearch removes comments when it parses the request, so they are not stored and are not returned by APIs such as the Get Index Template API. + +The following request creates an index template whose body contains comments: + +```json +PUT /_index_template/comment-test +{ + /* Applies to all daily log indexes */ + "index_patterns": ["comment-logs-*"], + "template": { + "settings": { + "number_of_replicas": 0 // Single-node cluster + } + } +} +``` +{% include copy-curl.html %} + +If you send a request body containing `//` comments from a file using cURL, use the `--data-binary` option. The `-d` option removes line breaks from file input, so a `//` comment would turn the rest of the body into a comment. +{: .tip} ## Request body in query string -If the client library does not accept a request body for non-POST requests, use the `source` query string parameter to pass the request body. Also, specify the `source_content_type` parameter with a supported media type such as `application/json`. +Some HTTP clients cannot send a body with a `GET` request. In that case, put the body in the `source` query parameter and set `source_content_type` to its media type, for example, `application/json`. OpenSearch rejects a request that contains `source` without `source_content_type`. - -#### Example request - -The following request searches the documents in the `shakespeare` index for a specific field and value: +The following request searches the `orders-online` index for documents containing a `product` field: ```json - -GET shakespeare/search?source={"query":{"exists":{"field":"speaker"}}}&source_content_type=application/json +GET /orders-online/_search?source={"query":{"exists":{"field":"product"}}}&source_content_type=application/json ``` +When you send this request using cURL or another HTTP client, URL-encode the `source` value. + ## Stack traces -To include the error stack trace in the response when an exception is raised, add `error_trace=true` to the request URL. +By default, error responses do not include the Java stack trace of the exception. To include the stack trace when troubleshooting, add `error_trace=true` to the request URL. The response then contains a `stack_trace` field for the error and for each of its causes. -#### Example request - -The following request sets `error_trace` to `true` so that the response returns exception-triggered errors: +The following request searches an index that does not exist and returns the error with its stack trace: ```json - -GET /_search?error_trace=true +GET /no-such-index/_search?error_trace=true ``` +{% include copy-curl.html %} ## Filtered responses -To reduce the response size use the `filter_path` parameter to filter the fields that are returned. This parameter takes a comma-separated list of filters. It supports using wildcards to match any field or part of a field's name. You can also exclude fields with `-`. - -#### Example request - -The following request specifies filters to limit the fields returned in the response: +To reduce the response size, use the `filter_path` parameter to specify which fields are returned. Pass `filter_path` one or more dot-separated field paths, separated by commas. For example, the following request returns only the search time, the total hit count, and the index of each hit: ```json - -GET _search?filter_path=.*,- +GET /sales-*/_search?q=region:west&filter_path=took,hits.total.value,hits.hits._index ``` +{% include copy-curl.html %} + +The response contains only the requested fields: + +```json +{ + "took": 13, + "hits": { + "total": { + "value": 2 + }, + "hits": [ + { + "_index": "sales-2026-10" + }, + { + "_index": "sales-2026-09" + } + ] + } +} +``` + +Filters support the following syntax: + +- `*` matches any field name or part of a field name. For example, `metadata.indices.sales-*.state` returns the state of every index whose name starts with `sales-`. +- `**` matches any number of path levels, so you can select a field without knowing its full path. For example, in a Nodes Stats API response, `nodes.**.heap_used_percent` returns the heap usage of each node, which is nested under the node ID, `jvm`, and `mem` objects. +- A filter that starts with `-` excludes the matching fields. + +When you combine inclusive and exclusive filters, OpenSearch applies the exclusive filters first and then the inclusive filters. The following request returns the hits but removes the `_index` and `_score` fields from each one: + +```json +GET /sales-*/_search?q=region:west&filter_path=hits.hits,-hits.hits._index,-hits.hits._score +``` +{% include copy-curl.html %} + +The response contains the ID and source of each hit: + +```json +{ + "hits": { + "hits": [ + { + "_id": "4xWKNqEBmqWRVflA9hH6", + "_source": { + "region": "west", + "amount": 950 + } + }, + { + "_id": "4hWKNqEBmqWRVflA9hGr", + "_source": { + "region": "west", + "amount": 1200 + } + } + ] + } +} +``` + +The `filter_path` parameter returns `_source` as a whole and cannot select fields inside it. To return only some document fields, combine `filter_path` with [source filtering]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-source-filtering). The following request returns only the ID and the `amount` field of each hit: + +```json +GET /sales-*/_search?q=region:west&filter_path=hits.hits._id,hits.hits._source&_source_includes=amount +``` +{% include copy-curl.html %} + +The response contains the `amount` field from each document's source: + +```json +{ + "hits": { + "hits": [ + { + "_id": "4xWKNqEBmqWRVflA9hH6", + "_source": { + "amount": 950 + } + }, + { + "_id": "4hWKNqEBmqWRVflA9hGr", + "_source": { + "amount": 1200 + } + } + ] + } +} +``` + +## Flat settings + +APIs that return settings, such as the Get Settings API, return them as nested objects by default. To return each setting as a single key in dot notation, for example, `index.number_of_shards`, add `flat_settings=true` to the request URL. Flat settings are easier to search for and to copy into other requests. + +The following request returns the settings of the `orders-online` index in flat format: + +```json +GET /orders-online/_settings?flat_settings=true +``` +{% include copy-curl.html %} + +The response contains one key for each setting: + +```json +{ + "orders-online": { + "settings": { + "index.creation_date": "1791912174739", + "index.number_of_replicas": "0", + "index.number_of_shards": "1", + "index.provided_name": "orders-online", + "index.replication.type": "DOCUMENT", + "index.uuid": "-m06DdVxT72bWledrDZ8sA", + "index.version.created": "137307827" + } + } +} +``` + + +## X-Opaque-Id header + + +You can specify an opaque identifier for any request using the `X-Opaque-Id` header. OpenSearch uses this identifier to track tasks, deduplicate deprecation warnings in server-side logs, and distinguish between callers sending requests to your cluster. Do not specify a unique value per request. + +The following request adds an opaque ID to the request: + +```bash +curl -H "X-Opaque-Id: my-curl-client-1" -XGET localhost:9200/_tasks +``` +{% include copy.html %} + + +## X-Request-Id header + + +You can specify a unique identifier for a search request using the `X-Request-Id` header. This identifier is used to track individual search requests and can be referenced in logs, such as slow logs, for troubleshooting and analysis. The value must be a 32-character hexadecimal string. + +The following request adds a request ID to a search request: + +```bash +curl -X GET "http://localhost:9200/_search" \ + -H "Content-Type: application/json" \ + -H "X-Request-Id: 19d538d7c42d09240be001d1e4ff6201" \ + -d '{"query": {"match_all": {}}}' +``` +{% include copy.html %} + +## Related documentation + +- [Index name syntax]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/) +- [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/) +- [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/) +- [Date math in range queries]({{site.url}}{{site.baseurl}}/query-dsl/term/range/) +- [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/) diff --git a/_api-reference/cron-expressions.md b/_api-reference/cron-expressions.md new file mode 100644 index 00000000..bb707423 --- /dev/null +++ b/_api-reference/cron-expressions.md @@ -0,0 +1,57 @@ +--- +layout: default +title: Cron expressions +nav_order: 165 +redirect_from: + - /monitoring-plugins/alerting/cron/ + - /observing-your-data/alerting/cron/ +--- + +# Cron expressions + +Several OpenSearch features accept cron expressions for scheduling, including [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/), [alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/), and [anomaly detection]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/). OpenSearch uses the standard UNIX cron syntax. All schedule times are in UTC. + +A cron expression has the following format: + +``` + +``` + +The following table describes each field. + +| Field | Values | Special characters | +| :--- | :--- | :--- | +| Minutes | 0--59 | `, - * /` | +| Hours | 0--23 | `, - * /` | +| Day of month | 1--31 | `, - * /` | +| Month | 1--12 or JAN--DEC (case-insensitive) | `, - * /` | +| Day of week | 0--7 (0 and 7 are both Sunday) or SUN--SAT (case-insensitive) | `, - * /` | + +The following table describes the special characters. + +| Character | Description | +| :--- | :--- | +| `*` | Matches all values. For example, `*` in the month field matches every month. | +| `-` | Range. For example, `1-5` in `day_of_week` matches Monday through Friday. | +| `,` | Multiple values. For example, `1,3,5` in `day_of_week` means Monday, Wednesday, and Friday. | +| `/` | Increment. For example, `0/15` in minutes means every 15 minutes starting at minute 0. | + +Two fields specify the day: `day_of_month` and `day_of_week`. If you use a non-wildcard value in both, the schedule runs whenever either field matches the time. For example, `15 2 1,15 * 1` runs at 2:15 AM UTC on the first day of the month, on the 15th day of the month, and every Monday. To schedule a single day, set one field and leave the other as `*`. + +## Examples + +| Expression | Description | +| :--- | :--- | +| `5 9 * * *` | 9:05 AM UTC every day | +| `0/15 9 * * *` | Every 15 minutes from 9:00 to 9:45 AM UTC | +| `5 9 * * 1-5` | 9:05 AM UTC Monday through Friday | +| `5 9 * * MON-FRI` | 9:05 AM UTC Monday through Friday (using named days) | +| `45 13 1-31/2 * *` | 1:45 PM UTC every other day | +| `0/10 * * * 6-7` | Every 10 minutes on Saturday and Sunday | +| `0 0-23/3 1 1-12/2 *` | Every 3 hours on the first day of every other month | + +## Related documentation + +- [Common REST parameters]({{site.url}}{{site.baseurl}}/api-reference/common-parameters/) +- [Index name syntax]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/) +- [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/) diff --git a/_api-reference/data-stream/create-data-stream.md b/_api-reference/data-stream/create-data-stream.md new file mode 100644 index 00000000..30cc8beb --- /dev/null +++ b/_api-reference/data-stream/create-data-stream.md @@ -0,0 +1,96 @@ +--- +layout: default +title: Create data stream +parent: Data stream APIs +nav_order: 10 +--- + +# Create Data Stream API +**Introduced 1.0** +{: .label .label-purple } + +The Create Data Stream API creates a data stream. Before creating a data stream, you must create an index template that configures a set of indexes as a data stream. For more information, see [Index data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/). + + +## Endpoints +```json +PUT /_data_stream/{name} +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `name` | **Required** | String | Name of the data stream, which must meet the following criteria: Lowercase only; Cannot include `\`, `/`, `*`, `?`, `"`, `<`, `>`, `\|`, `,`, `#`, `:`, or a space character; Cannot start with `-`, `_`, `+`, or `.ds-`; Cannot be `.` or `..`; Cannot be longer than 255 bytes. Multi-byte characters count towards this limit faster. | + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | Whether to include the stack trace of returned errors. | `false` | +| `filter_path` | List or String | Used to reduce the response. This parameter takes a comma-separated list of filters. It supports using wildcards to match any field or part of a field’s name. You can also exclude fields with `-`. | N/A | +| `human` | Boolean | Whether to return human-readable values for statistics. | `false` | +| `pretty` | Boolean | Whether to pretty format the returned JSON response. | `false` | +| `source` | String | The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. | N/A | + + +## Example request + +The following example request creates the `logs-app` data stream using a matching, previously created index template: + + +{% capture step1_rest %} +PUT /_data_stream/logs-app +{} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create_data_stream( + name = "logs-app", + body = {} +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/data_stream/create`. + +## Related documentation + +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Get data streams]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-info/) +- [Delete a data stream]({{site.url}}{{site.baseurl}}/api-reference/data-stream/delete-data-stream/) diff --git a/_api-reference/data-stream/data-stream-info.md b/_api-reference/data-stream/data-stream-info.md new file mode 100644 index 00000000..edb51455 --- /dev/null +++ b/_api-reference/data-stream/data-stream-info.md @@ -0,0 +1,163 @@ +--- +layout: default +title: Get data stream +parent: Data stream APIs +nav_order: 20 +--- + +# Get Data Stream API +**Introduced 1.0** +{: .label .label-purple } + +The Get Data Stream API returns information about one or more data streams, including their backing indexes, generation, and status. + + +## Endpoints +```json +GET /_data_stream +GET /_data_stream/{name} +``` + + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `name` | List or String | A comma-separated list of data stream names used to limit the request. Wildcard (`*`) expressions are supported. If omitted, all data streams are returned. | + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | Whether to include the stack trace of returned errors. | `false` | +| `filter_path` | List or String | Used to reduce the response. This parameter takes a comma-separated list of filters. It supports using wildcards to match any field or part of a field’s name. You can also exclude fields with `-`. | N/A | +| `human` | Boolean | Whether to return human-readable values for statistics. | `false` | +| `pretty` | Boolean | Whether to pretty format the returned JSON response. | `false` | +| `source` | String | The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. | N/A | + + +## Example request + +The following example request returns information about all data streams in the cluster: + + +{% capture step1_rest %} +GET /_data_stream +{% endcapture %} + +{% capture step1_python %} + +response = client.indices.get_data_stream() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To return information about a specific data stream, provide its name as the `name` path parameter: + + +{% capture step1_rest %} +GET /_data_stream/logs-app +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_data_stream( + name = "logs-app" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "data_streams": [ + { + "name": "logs-app", + "timestamp_field": { + "name": "@timestamp" + }, + "indices": [ + { + "index_name": ".ds-logs-app-000001", + "index_uuid": "23dD0HE5Sg2kSLLAP_YtNA" + } + ], + "generation": 1, + "status": "YELLOW", + "template": "template-logs-app" + } + ] +} +``` + +## Response body fields + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `data_streams` | Array | A list of objects, one for each data stream. For object fields, see [The data stream objects](#the-data-stream-objects). | + +### The data stream objects + +Each data stream object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `name` | String | The name of the data stream. | +| `timestamp_field` | Object | The timestamp field configuration for the data stream. | +| `timestamp_field.name` | String | The name of the timestamp field, usually `@timestamp`. | +| `indices` | Array | A list of the data stream's backing indexes. The last item in the array is the current write index. For object fields, see [The backing index objects](#the-backing-index-objects). | +| `generation` | Integer | The current generation of the data stream. This number increases by one with each rollover. | +| `status` | String | The health status of the data stream, based on the health of its backing indexes. Valid values are `GREEN`, `YELLOW`, and `RED`. | +| `template` | String | The name of the index template used to create the data stream. | +| `hidden` | Boolean | Whether the data stream is hidden. | +| `system` | Boolean | Whether the data stream is managed internally by OpenSearch and cannot be modified through normal user interaction. | +| `ilm_policy` | String | The name of the associated Index State Management (ISM) policy, if one is configured. | +| `allow_custom_routing` | Boolean | Whether the data stream allows custom routing on write requests. | +| `_meta` | Object | Custom metadata attached to the data stream. | + +### The backing index objects + +Each backing index object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `index_name` | String | The name of the backing index. | +| `index_uuid` | String | The UUID of the backing index. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/data_stream/get`. + +## Related documentation + +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Get data stream stats]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-stats/) diff --git a/_api-reference/data-stream/data-stream-stats.md b/_api-reference/data-stream/data-stream-stats.md new file mode 100644 index 00000000..7f9d55f9 --- /dev/null +++ b/_api-reference/data-stream/data-stream-stats.md @@ -0,0 +1,242 @@ +--- +layout: default +title: Get data stream stats +parent: Data stream APIs +nav_order: 30 +redirect_from: + - /api-reference/index-apis/data-stream-stats/ +--- + +# Data Stream Stats API +**Introduced 1.0** +{: .label .label-purple } + +The Data Stream Stats API provides statistics about one or more data streams, including the number of backing indexes, store size, and maximum timestamp. Use this API to monitor storage and indexing activity across data streams. + + +## Endpoints +```json +GET /_data_stream/_stats +GET /_data_stream/{name}/_stats +``` + + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `name` | List or String | A comma-separated list of data streams used to limit the request. Wildcard expressions (`*`) are supported. To target all data streams in a cluster, omit this parameter or use `*`. | + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | Whether to include the stack trace of returned errors. | `false` | +| `filter_path` | List or String | Used to reduce the response. This parameter takes a comma-separated list of filters. It supports using wildcards to match any field or part of a field’s name. You can also exclude fields with `-`. | N/A | +| `human` | Boolean | Whether to return human-readable values for statistics. | `false` | +| `pretty` | Boolean | Whether to pretty format the returned JSON response. | `false` | +| `source` | String | The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. | N/A | + +## Example requests + +Create an index template with a matching pattern and data stream enabled: + + +{% capture step1_rest %} +PUT /_index_template/template-logs-app +{ + "index_patterns": [ + "logs-app*" + ], + "data_stream": {} +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_index_template( + name = "template-logs-app", + body = { + "index_patterns": [ + "logs-app*" + ], + "data_stream": {} + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Create the data stream: + + +{% capture step1_rest %} +PUT /_data_stream/logs-app +{} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create_data_stream( + name = "logs-app", + body = {} +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Index a document to generate a backing index: + + +{% capture step1_rest %} +POST /logs-app/_doc +{ + "@timestamp": "2025-06-23T10:00:00Z", + "message": "app started" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "logs-app", + body = { + "@timestamp": "2025-06-23T10:00:00Z", + "message": "app started" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Retrieve statistics for the data stream: + + +{% capture step1_rest %} +GET /_data_stream/logs-app/_stats?human=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.data_streams_stats( + name = "logs-app", + params = { "human": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "_shards": { + "total": 2, + "successful": 2, + "failed": 0 + }, + "data_stream_count": 1, + "backing_indices": 1, + "total_store_size": "16.8kb", + "total_store_size_bytes": 17304, + "data_streams": [ + { + "data_stream": "logs-app", + "backing_indices": 1, + "store_size": "16.8kb", + "store_size_bytes": 17304, + "maximum_timestamp": 1750673100000 + } + ] +} +``` + +## Response body fields + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_shards.total` | Integer | The total number of shards involved in the request. | +| `_shards.successful` | Integer | The number of successful shard fetches. | +| `_shards.failed` | Integer | The number of failed shard fetches. | +| `data_stream_count` | Integer | The total number of data streams returned in the response. | +| `backing_indices` | Integer | The total number of backing indexes across all data streams. | +| `total_store_size` | String | A human-readable total size of all data stream storage. Present only if `human=true`. | +| `total_store_size_bytes` | Integer | The total storage used by all data streams, in bytes. | +| `data_streams` | Array | A list of objects, one for each data stream. For object fields, see [The data stream objects](#the-data-stream-objects). | + +### The data stream objects + +Each data stream object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `data_stream` | String | The name of the data stream. | +| `backing_indices` | Integer | The number of backing indexes for the data stream. | +| `store_size` | String | Human-readable storage used by the data stream. Present only if `human=true`. | +| `store_size_bytes` | Integer | The total storage used by the data stream, in bytes. | +| `maximum_timestamp` | Long | The maximum timestamp across all documents in the data stream. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/data_stream/stats`. + +## Related documentation + +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Get data streams]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-info/) diff --git a/_api-reference/data-stream/delete-data-stream.md b/_api-reference/data-stream/delete-data-stream.md new file mode 100644 index 00000000..43f7cdb7 --- /dev/null +++ b/_api-reference/data-stream/delete-data-stream.md @@ -0,0 +1,91 @@ +--- +layout: default +title: Delete data stream +parent: Data stream APIs +nav_order: 50 +--- + +# Delete Data Stream API +**Introduced 1.0** +{: .label .label-purple } + +The Delete Data Stream API deletes a data stream and its backing indexes. + + +## Endpoints +```json +DELETE /_data_stream/{name} +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `name` | **Required** | List or String | A comma-separated list of data streams to delete. Wildcard (`*`) expressions are supported. | + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | Whether to include the stack trace of returned errors. | `false` | +| `filter_path` | List or String | Used to reduce the response. This parameter takes a comma-separated list of filters. It supports using wildcards to match any field or part of a field’s name. You can also exclude fields with `-`. | N/A | +| `human` | Boolean | Whether to return human-readable values for statistics. | `false` | +| `pretty` | Boolean | Whether to pretty format the returned JSON response. | `false` | +| `source` | String | The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. | N/A | + +## Example request + +The following example request deletes the `logs-app` data stream and its backing indexes: + + +{% capture step1_rest %} +DELETE /_data_stream/logs-app +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.delete_data_stream( + name = "logs-app" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/data_stream/delete`. + +## Related documentation + +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Create or update a data stream]({{site.url}}{{site.baseurl}}/api-reference/data-stream/create-data-stream/) \ No newline at end of file diff --git a/_api-reference/data-stream/index.md b/_api-reference/data-stream/index.md new file mode 100644 index 00000000..91e05e07 --- /dev/null +++ b/_api-reference/data-stream/index.md @@ -0,0 +1,29 @@ +--- +layout: default +title: Data stream APIs +nav_order: 40 +has_children: true +has_toc: false +redirect_from: + - /api-reference/data-stream/ +--- + +# Data stream APIs + +Use the data stream APIs to create and delete [data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/), modify their backing indexes, and retrieve information and statistics about them. + +## Available APIs + +OpenSearch supports the following data stream APIs. + +| API | Description | +|-----|-------------| +| [Create data stream]({{site.url}}{{site.baseurl}}/api-reference/data-stream/create-data-stream/) | Creates a data stream. | +| [Get data stream]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-info/) | Returns information about one or more data streams. | +| [Get data stream stats]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-stats/) | Returns statistics for one or more data streams. | +| [Modify data stream]({{site.url}}{{site.baseurl}}/api-reference/data-stream/modify-data-stream/) | Adds or removes the backing indexes of a data stream. | +| [Delete data stream]({{site.url}}{{site.baseurl}}/api-reference/data-stream/delete-data-stream/) | Deletes a data stream and its backing indexes. | + +## Related documentation + +- For more information about data streams, including when to use them, see [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/). diff --git a/_api-reference/data-stream/modify-data-stream.md b/_api-reference/data-stream/modify-data-stream.md new file mode 100644 index 00000000..45c434db --- /dev/null +++ b/_api-reference/data-stream/modify-data-stream.md @@ -0,0 +1,103 @@ +--- +layout: default +title: Modify data stream +parent: Data stream APIs +nav_order: 40 +redirect_from: + - /api-reference/index-apis/modify-data-stream/ +--- + +# Modify Data Stream API +**Introduced 3.8** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/8271). +{: .warning} + +The Modify Data Stream API adds or removes backing indexes of a [data stream]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/). Use this API to migrate a pre-existing regular index into a data stream or to detach a backing index without deleting its data. + +The following behaviors and restrictions apply when you add or remove backing indexes: + +- Add and remove actions change only the data stream metadata; the index and its data remain unchanged. No shards are created, deleted, restored, or relocated. +- You can include multiple add and remove actions in a request. All actions are applied atomically in a single cluster state update, and the result is independent of the action order. +- The data stream generation is derived from its backing indexes (the highest backing-index counter is the write index) and cannot be set directly. +- The write index cannot be removed, and removing the last backing index is rejected. +- An added index must map the data stream's timestamp field as a `date` or `date_nanos`. An added index is marked as hidden; a removed index is made visible again. +- An added index need not follow the `.ds--NNNNNN` naming convention, which allows you to migrate a pre-existing regular index into a data stream. +- An index cannot be a backing index of more than one data stream. + +## Endpoints + +```json +POST /_data_stream/_modify +``` + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Default is `30s`. | +| `timeout` | Time | The amount of time to wait for a response from the cluster. Default is `30s`. | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `actions` | Array | A list of actions to perform. You must provide at least one action. Required. | + +Each element in the `actions` array is a single-key object that specifies one action. The following table lists the available action fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `add_backing_index.data_stream` | String | The name of the data stream to modify. Required. | +| `add_backing_index.index` | String | The name of the index to add as a backing index. Required. | +| `remove_backing_index.data_stream` | String | The name of the data stream to modify. Required. | +| `remove_backing_index.index` | String | The name of the backing index to remove. Required. | +| `add_backing_index` | Object | Adds an existing index to the data stream as a backing index. Optional. | +| `remove_backing_index` | Object | Removes a backing index from the data stream. Optional. | + +## Example request + +The following request removes a backing index from the `logs-foo` data stream and adds the pre-existing `legacy-logs-2023` index to it in a single atomic operation: + +```json +POST /_data_stream/_modify +{ + "actions": [ + { + "remove_backing_index": { + "data_stream": "logs-foo", + "index": ".ds-logs-foo-000001" + } + }, + { + "add_backing_index": { + "data_stream": "logs-foo", + "index": "legacy-logs-2023" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "acknowledged": true +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/data_stream/modify`. + +## Related documentation + +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Data Stream Stats API]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-stats/) diff --git a/_api-reference/document-apis/bulk-streaming.md b/_api-reference/document-apis/bulk-streaming.md new file mode 100644 index 00000000..0cd7463e --- /dev/null +++ b/_api-reference/document-apis/bulk-streaming.md @@ -0,0 +1,83 @@ +--- +layout: default +title: Streaming bulk +parent: Document APIs +nav_order: 25 +redirect_from: + - /opensearch/rest-api/document-apis/bulk/streaming/ +--- + +# Streaming Bulk API +**Introduced 2.17.0** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/9065). +{: .warning} + +The streaming bulk operation lets you add, update, or delete multiple documents by streaming the request and getting the results as a streaming response. In comparison to the traditional [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/), streaming ingestion eliminates the need to estimate the batch size (which is affected by the cluster operational state at any given time) and naturally applies backpressure between many clients and the cluster. The streaming works over HTTP/2 or HTTP/1.1 (using chunked transfer encoding), depending on the capabilities of the clients and the cluster. + +The default HTTP transport method does not support streaming. You must install the [`transport-reactor-netty4`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/network-settings/#selecting-the-transport) HTTP transport plugin and use it as the default HTTP transport layer. Both the `transport-reactor-netty4` plugin and the Streaming Bulk API are experimental. +{: .note} + +## Endpoints + +```json +POST _bulk/stream +POST {index}/_bulk/stream +``` + +If you specify the index in the path, then you don't need to include it in the [request body chunks]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/#request-body). + +OpenSearch also accepts PUT requests to the `_bulk/stream` path, but we highly recommend using POST. The accepted usage of PUT---adding or replacing a single resource on a given path---doesn't make sense for streaming bulk requests. +{: .note } + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`pipeline` | String | The pipeline ID for preprocessing documents. +`refresh` | Enum | Whether to refresh the affected shards after performing the indexing operations. Default is `false`. `true` causes the changes show up in search results immediately but degrades cluster performance. `wait_for` waits for a refresh. Requests take longer to return, but cluster performance isn't degraded. +`require_alias` | Boolean | Set to `true` to require that all actions target an index alias rather than an index. Default is `false`. +`routing` | String | The default routing value for operations that don't specify their own routing. +`timeout` | Time | How long to wait for the request to return. Default is `1m`. +`wait_for_active_shards` | String | Specifies the number of active shards that must be available before OpenSearch processes the bulk request. Default is `1` (only the primary shard). Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have 2 replicas distributed across 2 additional nodes in order for the request to succeed. +`batch_interval` | Time | Specifies for how long bulk operations should be accumulated into a batch before sending the batch to data nodes. Must be greater than 0. If not specified, operations are not batched by time. +`batch_size` | Integer | Specifies how many bulk operations should be accumulated into a batch before sending the batch to data nodes. Must be greater than 0. Default is `1`. +{% comment %}_source | List | asdf +`_source_excludes` | List | asdf +`_source_includes` | List | asdf{% endcomment %} + +## Request body fields + +The Streaming Bulk API request body is fully compatible with the [Bulk API request body]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/#request-body), where each bulk operation (create/index/update/delete) is sent as a separate chunk. + +## Example request + +```json +curl -X POST "http://localhost:9200/_bulk/stream" -H "Transfer-Encoding: chunked" -H "Content-Type: application/json" -d' +{ "delete": { "_index": "movies", "_id": "tt2229499" } } +{ "index": { "_index": "movies", "_id": "tt1979320" } } +{ "title": "Rush", "year": 2013 } +{ "create": { "_index": "movies", "_id": "tt1392214" } } +{ "title": "Prisoners", "year": 2013 } +{ "update": { "_index": "movies", "_id": "tt0816711" } } +{ "doc" : { "title": "World War Z" } } +' +``` +{% include copy.html %} + +## Example response + +Depending on the batch settings, each streamed response chunk may report the results of one or many (batch) bulk operations. OpenSearch returns results for each HTTP chunk it receives, so the number of response chunks also depends on how the client splits the request stream. + +The following response assumes that the document with the ID `tt1392214` already exists in the `movies` index, so the `create` operation results in a version conflict. The documents with the IDs `tt2229499` and `tt0816711` do not exist, so the `delete` operation returns `not_found` and the `update` operation fails. For the preceding request with no batching (default), the streaming response may appear as follows: + +```json +{"took": 4, "errors": false, "items": [ { "delete": { "_index": "movies", "_id": "tt2229499", "_version": 1, "result": "not_found", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 1, "_primary_term": 1, "status": 404 } } ] } +{"took": 11, "errors": false, "items": [ { "index": { "_index": "movies", "_id": "tt1979320", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 2, "_primary_term": 1, "status": 201 } } ] } +{"took": 2, "errors": true, "items": [ { "create": { "_index": "movies", "_id": "tt1392214", "status": 409, "error": { "type": "version_conflict_engine_exception", "reason": "[tt1392214]: version conflict, document already exists (current version [1])", "index": "movies", "shard": "0", "index_uuid": "yhizhusbSWmP0G7OJnmcLg" } } } ] } +{"took": 4, "errors": true, "items": [ { "update": { "_index": "movies", "_id": "tt0816711", "status": 404, "error": { "type": "document_missing_exception", "reason": "[tt0816711]: document missing", "index": "movies", "shard": "0", "index_uuid": "yhizhusbSWmP0G7OJnmcLg" } } } ] } +``` diff --git a/_api-reference/document-apis/bulk.md b/_api-reference/document-apis/bulk.md index d0023081..30728273 100644 --- a/_api-reference/document-apis/bulk.md +++ b/_api-reference/document-apis/bulk.md @@ -7,20 +7,410 @@ redirect_from: - /opensearch/rest-api/document-apis/bulk/ --- -# Bulk +# Bulk API **Introduced 1.0** {: .label .label-purple } -The bulk operation lets you add, update, or delete multiple documents in a single request. Compared to individual OpenSearch indexing requests, the bulk operation has significant performance benefits. Whenever practical, we recommend batching indexing operations into bulk requests. +The Bulk API performs multiple indexing, update, or delete operations in a single request. This significantly reduces overhead and can greatly increase indexing speed by minimizing the number of network round trips and processing cycles required. +The Bulk API uses a newline-delimited JSON (NDJSON) structure for the request body. Each action is specified on one line, and if the action requires source data (such as for `index`, `create`, or `update` operations), the source data is provided on the following line. This format enables OpenSearch to quickly parse and process actions without reading the entire request body into memory. -Beginning in OpenSearch 2.9, when indexing documents using the bulk operation, the document `_id` must be 512 bytes or less in size. +When indexing documents using the bulk operation, the document `_id` must be 512 bytes or less in size. {: .note} -## Example +Use the Bulk API for the following purposes: + +- Indexing large datasets efficiently by grouping multiple document operations into a single request. +- Performing mixed operations (index, create, update, and delete) on multiple documents simultaneously. +- Minimizing network overhead when performing many document operations. +- Reindexing data from one index to another using client bulk helpers. + +The Bulk API processes actions independently. If one action fails, OpenSearch continues processing subsequent actions. The response indicates whether each individual action succeeded or failed. + + +## Endpoints +```json +POST /_bulk +PUT /_bulk +POST /{index}/_bulk +PUT /{index}/_bulk +``` + + +You can specify the target index in the path or include it in the [request body](#request-body). + +OpenSearch accepts `PUT` requests to the `_bulk` endpoint, but using `POST` is strongly recommended. The typical semantics of `PUT`---creating or replacing a single resource at a specific path---do not align with the behavior of bulk operations. +{: .note } + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | Name of the data stream, index, or index alias to perform bulk actions on. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `_source` | Boolean or List or String | `true` or `false` to return the `_source` field or not, or a list of fields to return. | +| `_source_excludes` | List or String | A comma-separated list of source fields to exclude from the response. | +| `_source_includes` | List or String | A comma-separated list of source fields to include in the response. | +| `index` | String | Name of the data stream, index, or index alias to perform bulk actions on. | +| `pipeline` | String | ID of the pipeline to use to preprocess incoming documents. If the index has a default ingest pipeline specified, then setting the value to `_none` disables the default ingest pipeline for this request. If a final pipeline is configured it will always run, regardless of the value of this parameter. | +| `refresh` | Boolean or String | If `true`, OpenSearch refreshes the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` do nothing with refreshes. Valid values: `true`, `false`, `wait_for`.
Valid values are:
- `false`: Do not refresh the affected shards.
- `true`: Refresh the affected shards immediately.
- `wait_for`: Wait for the changes to become visible before replying. | +| `require_alias` | Boolean | If `true`, the request's actions must target an index alias. _(Default: `false`)_ | +| `routing` | String | A custom value used to route operations to a specific shard. | +| `timeout` | String | Period each action waits for the following operations: automatic index creation, dynamic mapping updates, waiting for active shards. | +| `type` | String | Default document type for items which don't provide one. | +| `wait_for_active_shards` | Integer or String or NULL or String | The number of shard copies that must be active before proceeding with the operation. Set to all or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
Valid values are:
- `all`: Wait for all shards to be active. | + + + +## Submitting bulk requests using cURL + +When submitting bulk requests from a file using the cURL command, use the `--data-binary` flag instead of `-d` to preserve newline characters. The `-d` flag removes newlines, which breaks the NDJSON format required by the Bulk API. + +The following example demonstrates the correct approach. First, create a file containing your bulk operations: + +```bash +cat > bulk-operations.ndjson << 'EOF' +{ "index": { "_index": "movies", "_id": "curl-test1" } } +{ "title": "Curl Test Movie 1", "year": 2025 } +{ "index": { "_index": "movies", "_id": "curl-test2" } } +{ "title": "Curl Test Movie 2", "year": 2025 } +EOF +``` + +Then submit the file using `--data-binary`: + +```bash +curl -H "Content-Type: application/x-ndjson" -X POST "localhost:9200/_bulk?pretty" --data-binary "@bulk-operations.ndjson" +``` + +When making inline bulk requests with cURL, ensure that you properly escape newlines in your shell. Using single quotes and literal newlines is often clearer than using `\n` escape sequences. + +## Optimistic concurrency control + +OpenSearch uses optimistic concurrency control to prevent conflicts when multiple processes attempt to modify the same document simultaneously. The Bulk API supports two approaches for concurrency control: sequence number-based and version-based. + +### Sequence number-based concurrency control + +Sequence numbers provide the most reliable form of concurrency control. Each document operation increments the `_seq_no` field, and the `_primary_term` tracks primary shard elections. By specifying both values in your bulk operation, you ensure that the operation only succeeds if the document hasn't changed since you last read it. + +The following example demonstrates sequence number-based concurrency control: ```json -POST _bulk +{ "index": { "_index": "movies", "_id": "version-test", "if_seq_no": 13, "if_primary_term": 1 } } +{ "title": "Updated with OCC", "year": 2025 } +``` + +If another process has modified the document between your read and update operations, the `_seq_no` or `_primary_term` will have changed, and OpenSearch returns a `version_conflict_engine_exception` error. Your application can then retrieve the latest version of the document and retry the operation. + +This approach prevents lost updates without requiring explicit locking, allowing multiple processes to work concurrently while maintaining data consistency. + +### Version-based concurrency control + +OpenSearch also supports explicit version numbers for concurrency control. Every document has a `_version` field that increments with each modification. You can specify a required version in your bulk operations: + +```json +{ "index": { "_index": "movies", "_id": "doc1", "version": 5, "version_type": "internal" } } +{ "title": "Version-controlled update", "year": 2025 } +``` + +This operation only succeeds if the document's current version is 5. The `version_type` parameter supports the following values: + +- `internal` (default): Uses OpenSearch's internal version numbering. +- `external`: Allows you to maintain version numbers from an external system. The version must be greater than the current version. +- `external_gte`: Similar to `external`, but allows the version to be greater than or equal to the current version. + +## Versioning + +Document versioning in OpenSearch tracks changes to documents over time. The `_version` field automatically increments each time a document is modified through index, update, or delete operations. + +### Internal versioning + +By default, OpenSearch uses internal versioning, starting at 1 for new documents and incrementing with each modification. Internal versions are managed automatically and persist even when documents are deleted and recreated with the same ID. + +The following example creates a document with an external version number: + +```json +{ "index": { "_index": "movies", "_id": "external-version-test", "version": 100, "version_type": "external" } } +{ "title": "External Version Movie", "year": 2025 } +``` + +### External versioning + +External versioning is useful when synchronizing OpenSearch with an external data source that maintains its own version numbers. When using `version_type: external`, OpenSearch accepts your version number and only indexes the document if the provided version is greater than the stored version. This ensures that out-of-order updates don't overwrite newer data with older versions. + +### Version conflicts + +Version conflicts occur when an operation specifies a version that doesn't match the current document version. When this happens, OpenSearch returns a `version_conflict_engine_exception` error in the response for that specific operation. The bulk request continues processing other operations, allowing partial success even when some operations fail due to version conflicts. + +## Routing + +Routing determines which shard stores a particular document. By default, OpenSearch routes documents using a hash of the document ID, distributing documents evenly across shards. Custom routing allows you to override this behavior and control document placement. + +You can specify routing in two ways: at the query parameter level or in individual action metadata. + +### Query parameter routing + +Applying routing at the query parameter level affects all operations in the bulk request: + +```json +POST /_bulk?routing=user123 +{ "index": { "_index": "movies", "_id": "routed-doc" } } +{ "title": "Routed Movie", "user_id": "user123" } +``` + +### Action-level routing + +Specifying routing in the action metadata provides finer control, allowing different operations in the same bulk request to use different routing values: + +```json +POST /_bulk +{ "index": { "_index": "movies", "_id": "routed-action", "routing": "user456" } } +{ "title": "Action Routed Movie", "user_id": "user456" } +``` + +Custom routing is particularly useful for multi-tenant applications in which you want to store all documents for a specific tenant on the same shard. This improves query performance when searching within a single tenant because OpenSearch only needs to query one shard instead of all shards in the index. + +When using custom routing, you must provide the same routing value for all operations (index, get, update, delete) on a document. Otherwise, OpenSearch may not find the document because it searches the wrong shard. + +## Refresh + +The `refresh` parameter controls when changes made by bulk operations become visible to search queries. OpenSearch uses a near-real-time search model where documents are not immediately searchable after indexing. + +The `refresh` parameter accepts three values: + +- `false` (default): Documents are not refreshed immediately. They become searchable based on the index's refresh interval (typically 1 second). +- `true`: Forces an immediate refresh of all affected shards, making documents searchable immediately but with a performance cost. +- `wait_for`: Waits for the next scheduled refresh before returning, balancing visibility and performance. + +The following example uses `refresh=wait_for`: + +```json +POST /_bulk?refresh=wait_for +{ "index": { "_index": "movies", "_id": "refresh-test" } } +{ "title": "Refresh Test Movie", "year": 2025 } +``` + +Only the shards that receive documents from the bulk request are refreshed. If a bulk request contains documents routed to three shards in an index with five shards, only those three shards are refreshed. The other two shards remain unaffected. + +Using `refresh=true` can significantly impact cluster performance, especially with frequent bulk requests. For production workloads, consider using the default behavior or `refresh=wait_for`, which provides better performance characteristics while ensuring documents are available for search within a bounded time. + +## Wait for active shards + +The `wait_for_active_shards` parameter controls how many shard copies must be active before OpenSearch processes a bulk request. This setting helps ensure data durability by preventing operations from proceeding when too many shard copies are unavailable. + +By default, `wait_for_active_shards` is set to `1`, meaning only the primary shard must be active. You can set it to: + +- A positive integer: The operation waits until that number of shard copies (including the primary) are active. +- `all`: The operation waits until all shard copies (primary and all replicas) are active. + +The following example waits for the primary and one replica shard to be active: + +```json +POST /_bulk?wait_for_active_shards=2 +{ "index": { "_index": "movies", "_id": "active-shards-test" } } +{ "title": "Active Shards Test", "year": 2025 } +``` + +For an index configured with one primary and two replicas (`number_of_replicas=2`), setting `wait_for_active_shards=2` requires the primary and at least one replica to be active. This provides a balance between availability and durability. + +If the required number of active shards is not available within the timeout period (controlled by the `timeout` parameter), the bulk operation fails with a timeout error. The shards that did become active may still contain the successfully indexed documents. + +## Performance considerations + +When using the Bulk API, several factors affect performance and throughput. Understanding these considerations helps you optimize bulk operations for your specific workload. + +### Optimal batch size + +There is no universal "correct" number of operations to include in a single bulk request. The optimal batch size depends on several factors: + +- **Document size**: Larger documents require fewer operations per request to reach the ideal request size. +- **Indexing complexity**: Documents with many fields or complex mappings take longer to process. +- **Hardware resources**: Available memory and CPU capacity on your cluster nodes. +- **Network bandwidth**: The connection speed between your client and the OpenSearch cluster. + +Start with batches of 1,000 to 5,000 operations and experiment with different sizes. Monitor your cluster's performance metrics (CPU usage, memory consumption, indexing latency) to find the optimal batch size for your workload. A good bulk request size typically falls between 5 MB and 15 MB. + +### HTTP chunking + +When using the HTTP API, ensure that your client does not send HTTP chunks (`Transfer-Encoding: chunked`). HTTP chunking prevents OpenSearch from efficiently parsing the request body because it must process the data incrementally as chunks arrive rather than reading the entire request at once. + +Most HTTP clients disable chunking by default, but if you're experiencing slow bulk operations, verify that your client configuration does not enable chunked transfer encoding. + +### Client-side buffering + +The NDJSON format used by the Bulk API is designed for minimal buffering. Each action and its optional source data appears on separate lines, allowing OpenSearch to process operations as soon as they're parsed without loading the entire request into memory. + +When implementing bulk operations in your application: + +- Avoid accumulating all operations in memory before sending them. Instead, stream operations to the Bulk API as you generate them. +- Process the response incrementally rather than waiting for all operations to complete. +- Use client libraries that support efficient bulk helpers, which handle batching and error retry automatically. + +### Request parsing + +OpenSearch optimizes bulk request processing by parsing only the action metadata on the receiving node. The action metadata contains routing information that determines which shard should handle the operation. Once routing is determined, OpenSearch forwards the complete operation (metadata and source data) to the appropriate shard. + +This design minimizes processing on the coordinating node, allowing OpenSearch to efficiently distribute bulk operations across the cluster without creating a bottleneck at the entry point. + +## Request body + +The bulk request body uses a newline-delimited JSON (NDJSON) format. Each action must be specified on a single line followed by a newline character (`\n`), and source data (when required) must be on the next line followed by a newline character. + +``` +Action and metadata\n +Optional document\n +Action and metadata\n +Optional document\n +``` + +Each JSON document can include spaces for readability but must be on a single line. OpenSearch uses newline characters to parse bulk requests and requires that the request body end with a newline character. When sending requests to the Bulk API, set the `Content-Type` header to `application/x-ndjson`. + +### Action metadata fields + +All actions support the following metadata fields in the action line. The `_index` field is required unless you specify the index in the request path. + +Field | Data type | Description +:--- | :--- | :--- +`_index` | String | The name of the index. Required if not specified in the request path. +`_id` | String | The document ID. Optional. If not provided, OpenSearch generates an ID automatically. +`_require_alias` | Boolean | When `true`, requires the destination to be an index alias. Default is `false`. +`routing` | String | The custom routing value for the document operation. +`version` | Integer | The explicit version number for the document. Used for optimistic concurrency control. +`version_type` | String | The version type: `internal`, `external`, `external_gte`. Default is `internal`. +`if_seq_no` | Integer | Performs the operation only if the document has this sequence number. Used for optimistic concurrency control. +`if_primary_term` | Integer | Performs the operation only if the document has this primary term. Used for optimistic concurrency control. + +### Actions + +The Bulk API supports the following actions. + +### Create + +Creates a document if it doesn't already exist and returns an error otherwise. The next line must include a JSON document: + +```json +{ "create": { "_index": "movies", "_id": "tt1392214" } } +{ "title": "Prisoners", "year": 2013 } +``` + +### Delete + +This action deletes a document if it exists. If the document doesn't exist, OpenSearch doesn't return an error but instead returns `not_found` under `result`. Delete actions don't require documents on the next line: + +```json +{ "delete": { "_index": "movies", "_id": "tt2229499" } } +``` + +### Index + +Index actions create a document if it doesn't yet exist and replace the document if it already exists. The next line must include a JSON document: + +```json +{ "index": { "_index": "movies", "_id": "tt1979320" } } +{ "title": "Rush", "year": 2013} +``` + +### Update + +By default, this action updates existing documents and returns an error if the document doesn't exist. The next line must include a full or partial JSON document, depending on how much of the document you want to update: + +```json +{ "update": { "_index": "movies", "_id": "tt0816711" } } +{ "doc" : { "title": "World War Z" } } +``` + +The `update` action supports a `retry_on_conflict` field in the action metadata. This specifies how many times the update should be retried if a version conflict occurs: + +```json +{ "update": { "_index": "movies", "_id": "tt0816711", "retry_on_conflict": 3 } } +{ "doc" : { "title": "World War Z" } } +``` + +User-defined ingest pipelines are not executed for update operations. If you need to process documents through an ingest pipeline, use an [upsert](#upsert) operation instead. +{: .note} + +### Upsert + +To upsert a document, use one of the following options: + +1. Specify the document in the `doc` field and set `doc_as_upsert=true`. If the document exists, it is updated with the contents of the `doc` field. If the document does not exist, a new document is indexed with the parameters specified in the `doc` field: + + ```json + { "update": { "_index": "movies", "_id": "tt0816711" } } + { "doc" : { "title": "World War Z" }, "doc_as_upsert": true } + ``` +1. Specify the document to update (when it exists) in the `doc` field, the document to insert (when it doesn't exist) in the `upsert` field, and leave `doc_as_upsert` set to `false`: + + ```json + { "update": { "_index": "products", "_id": "widget-123" } } + { "doc": { "stock": 75, "updated_at": "2025-01-15T10:30:00Z" }, "upsert": { "name": "Widget", "price": 39.99, "stock": 100, "created_at": "2025-01-15T10:30:00Z" }} + ``` + +Use this option when you want to only update specific fields when a document exists but insert a complete document when it doesn't exist. + +Upsert operations trigger ingest pipelines, allowing you to preprocess documents before they are indexed or updated. +{: .note} + +### Script + +You can specify a script for more complex document updates by defining the script with the `source` or `id` from a document: + +```json +{ "update": { "_index": "movies", "_id": "tt0816711" } } +{ "script" : { "source": "ctx._source.title = \"World War Z\"" } } +``` + +### Scripted upsert + +You can use a script to update or upsert a document in the following ways: + +1. Script + upsert (`scripted_upsert=false`, default): If the document exists, the document is updated using the `script`. If the document does not exist, the document in the `upsert` field is inserted without running the script: + + ```json + POST _bulk + { "update": { "_index": "movies", "_id": "tt0816711" } } + { "script": { "source": "ctx._source.title = params.title; ctx._source.genre = params.genre;", "params": { "title": "World War Z", "genre": "Action" } }, "upsert": { "title": "World War Z", "genre": "Action", "author": "Tom Smith" } } + ``` + {% include copy-curl.html %} + +1. Script + upsert + `scripted_upsert=true`. If the document exists, the document is updated using the `script`. If the document does not exist, the script runs on the `upsert` field and the resulting document is inserted: + + ```json + POST _bulk + { "update": { "_index": "movies", "_id": "tt0816711" } } + { "script": { "source": "ctx._source.title = params.title; ctx._source.genre = params.genre;", "params": { "title": "World War Z", "genre": "Action" } }, "scripted_upsert": true } + ``` + {% include copy-curl.html %} + +## Example: Performing multiple actions + +The following example request performs multiple document operations in a single request, including delete, index, create, and update operations: + + +{% capture step1_rest %} +POST /_bulk +{ "delete": { "_index": "movies", "_id": "tt2229499" } } +{ "index": { "_index": "movies", "_id": "tt1979320" } } +{ "title": "Rush", "year": 2013 } +{ "create": { "_index": "movies", "_id": "tt1392214" } } +{ "title": "Prisoners", "year": 2013 } +{ "update": { "_index": "movies", "_id": "tt0816711" } } +{ "doc" : { "title": "World War Z" } } +{% endcapture %} -``` -{% include copy-curl.html %} +{% capture step1_python %} -## Path and HTTP methods +response = client.bulk( + body = ''' +{ "delete": { "_index": "movies", "_id": "tt2229499" } } +{ "index": { "_index": "movies", "_id": "tt1979320" } } +{ "title": "Rush", "year": 2013 } +{ "create": { "_index": "movies", "_id": "tt1392214" } } +{ "title": "Prisoners", "year": 2013 } +{ "update": { "_index": "movies", "_id": "tt0816711" } } +{ "doc" : { "title": "World War Z" } } +''' +) -``` -POST _bulk -POST /_bulk -``` +{% endcapture %} -Specifying the index in the path means you don't need to include it in the [request body]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/#request-body). +{% include code-block.html + rest=step1_rest + python=step1_python %} + -OpenSearch also accepts PUT requests to the `_bulk` path, but we highly recommend using POST. The accepted usage of PUT---adding or replacing a single resource at a given path---doesn't make sense for bulk requests. -{: .note } +## Example: Specifying the index in the path + +The following example request specifies the index in the request path, eliminating the need to include `_index` in each action line: + + +{% capture step1_rest %} +POST /movies/_bulk +{ "index": { "_id": "tt0468569" } } +{ "title": "The Dark Knight", "year": 2008, "director": "Christopher Nolan" } +{ "index": { "_id": "tt0137523" } } +{ "title": "Fight Club", "year": 1999, "director": "David Fincher" } +{% endcapture %} + +{% capture step1_python %} -## URL parameters +response = client.bulk( + index = "movies", + body = ''' +{ "index": { "_id": "tt0468569" } } +{ "title": "The Dark Knight", "year": 2008, "director": "Christopher Nolan" } +{ "index": { "_id": "tt0137523" } } +{ "title": "Fight Club", "year": 1999, "director": "David Fincher" } +''' +) -All bulk URL parameters are optional. +{% endcapture %} -Parameter | Type | Description -:--- | :--- | :--- -pipeline | String | The pipeline ID for preprocessing documents. -refresh | Enum | Whether to refresh the affected shards after performing the indexing operations. Default is `false`. `true` makes the changes show up in search results immediately, but hurts cluster performance. `wait_for` waits for a refresh. Requests take longer to return, but cluster performance doesn't suffer. -require_alias | Boolean | Set to `true` to require that all actions target an index alias rather than an index. Default is `false`. -routing | String | Routes the request to the specified shard. -timeout | Time | How long to wait for the request to return. Default `1m`. -type | String | (Deprecated) The default document type for documents that don't specify a type. Default is `_doc`. We highly recommend ignoring this parameter and using a type of `_doc` for all indexes. -wait_for_active_shards | String | Specifies the number of active shards that must be available before OpenSearch processes the bulk request. Default is 1 (only the primary shard). Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. -{% comment %}_source | List | asdf -_source_excludes | list | asdf -_source_includes | list | asdf{% endcomment %} +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Using upsert operations + +The following example request uses `doc_as_upsert` to update documents if they exist or create them if they don't: + + +{% capture step1_rest %} +POST /_bulk +{ "update": { "_index": "movies", "_id": "tt0468569" } } +{ "doc": { "rating": 9.0 }, "doc_as_upsert": true } +{ "update": { "_index": "movies", "_id": "tt9999999" } } +{ "doc": { "title": "New Movie", "year": 2024 }, "doc_as_upsert": true } +{% endcapture %} + +{% capture step1_python %} -## Request body +response = client.bulk( + body = ''' +{ "update": { "_index": "movies", "_id": "tt0468569" } } +{ "doc": { "rating": 9.0 }, "doc_as_upsert": true } +{ "update": { "_index": "movies", "_id": "tt9999999" } } +{ "doc": { "title": "New Movie", "year": 2024 }, "doc_as_upsert": true } +''' +) -The bulk request body follows this pattern: +{% endcapture %} -``` -Action and metadata\n -Optional document\n -Action and metadata\n -Optional document\n +{% include code-block.html + rest=step1_rest + python=step1_python %} + -``` +## Example: Handling version conflicts with retry_on_conflict -The optional JSON document doesn't need to be minified---spaces are fine---but it does need to be on a single line. OpenSearch uses newline characters to parse bulk requests and requires that the request body end with a newline character. +The following example request uses `retry_on_conflict` to automatically retry updates when version conflicts occur: -All actions support the same metadata: `_index`, `_id`, and `_require_alias`. If you don't provide an ID, OpenSearch generates one automatically, which can make it challenging to update the document at a later time. + +{% capture step1_rest %} +POST /_bulk +{ "update": { "_index": "movies", "_id": "tt0468569", "retry_on_conflict": 3 } } +{ "doc": { "rating": 9.5 } } +{% endcapture %} -- Create +{% capture step1_python %} - Creates a document if it doesn't already exist and returns an error otherwise. The next line must include a JSON document: - ```json - { "create": { "_index": "movies", "_id": "tt1392214" } } - { "title": "Prisoners", "year": 2013 } - ``` +response = client.bulk( + body = ''' +{ "update": { "_index": "movies", "_id": "tt0468569", "retry_on_conflict": 3 } } +{ "doc": { "rating": 9.5 } } +''' +) -- Delete +{% endcapture %} - This action deletes a document if it exists. If the document doesn't exist, OpenSearch doesn't return an error but instead returns `not_found` under `result`. Delete actions don't require documents on the next line: +{% include code-block.html + rest=step1_rest + python=step1_python %} + - ```json - { "delete": { "_index": "movies", "_id": "tt2229499" } } - ``` +## Example: Filtering response to show only errors -- Index +The following example request uses the `filter_path` query parameter to return only failed operations: - Index actions create a document if it doesn't yet exist and replace the document if it already exists. The next line must include a JSON document: + +{% capture step1_rest %} +POST /_bulk?filter_path=items.*.error +{ "update": { "_index": "movies", "_id": "missing1" } } +{ "doc": { "title": "Error" } } +{ "update": { "_index": "movies", "_id": "missing2" } } +{ "doc": { "title": "Error" } } +{ "update": { "_index": "movies", "_id": "tt0468569" } } +{ "doc": { "title": "Success" } } +{% endcapture %} - ```json - { "index": { "_index": "movies", "_id": "tt1979320" } } - { "title": "Rush", "year": 2013} - ``` +{% capture step1_python %} -- Update - By default, this action updates existing documents and returns an error if the document doesn't exist. The next line must include a full or partial JSON document, depending on how much of the document you want to update: +response = client.bulk( + params = { "filter_path": "items.*.error" }, + body = ''' +{ "update": { "_index": "movies", "_id": "missing1" } } +{ "doc": { "title": "Error" } } +{ "update": { "_index": "movies", "_id": "missing2" } } +{ "doc": { "title": "Error" } } +{ "update": { "_index": "movies", "_id": "tt0468569" } } +{ "doc": { "title": "Success" } } +''' +) - ```json - { "update": { "_index": "movies", "_id": "tt0816711" } } - { "doc" : { "title": "World War Z" } } - ``` +{% endcapture %} - To upsert a document, specify `doc_as_upsert` as `true`. If a document exists, it is updated; if it does not exist, a new document is indexed with the parameters specified in the `doc` field: +{% include code-block.html + rest=step1_rest + python=step1_python %} + - - Upsert - ```json - { "update": { "_index": "movies", "_id": "tt0816711" } } - { "doc" : { "title": "World War Z" }, "doc_as_upsert": true } - ``` +## Example response - You can specify a script for more complex document updates: +The Bulk API returns information about each operation in the request, in the same order as submitted. Pay particular attention to the top-level `errors` boolean. If `true`, one or more operations failed, and you can examine individual items for details. - - Script - ```json - { "update": { "_index": "movies", "_id": "tt0816711" } } - { "script" : { "source": "ctx._source.title = \"World War Z\"" } } - ``` +The Bulk API always returns a complete response, even when some operations fail due to shard failures or other errors. This partial response behavior ensures that you receive results for all successfully processed operations without waiting indefinitely for failed operations to complete. -## Response - -In the response, pay particular attention to the top-level `errors` boolean. If true, you can iterate over the individual actions for more detailed information. +The following example response corresponds to the first example request with multiple actions: ```json { - "took": 11, - "errors": true, + "took": 35, + "errors": false, "items": [ + { + "delete": { + "_index": "movies", + "_id": "tt2229499", + "_version": 1, + "result": "not_found", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1, + "status": 404 + } + }, { "index": { "_index": "movies", @@ -147,11 +650,11 @@ In the response, pay particular attention to the top-level `errors` boolean. If "_version": 1, "result": "created", "_shards": { - "total": 2, + "total": 1, "successful": 1, "failed": 0 }, - "_seq_no": 1, + "_seq_no": 2, "_primary_term": 1, "status": 201 } @@ -160,30 +663,119 @@ In the response, pay particular attention to the top-level `errors` boolean. If "create": { "_index": "movies", "_id": "tt1392214", - "status": 409, - "error": { - "type": "version_conflict_engine_exception", - "reason": "[tt1392214]: version conflict, document already exists (current version [1])", - "index": "movies", - "shard": "0", - "index_uuid": "yhizhusbSWmP0G7OJnmcLg" - } + "_version": 1, + "result": "created", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 3, + "_primary_term": 1, + "status": 201 } }, { "update": { "_index": "movies", "_id": "tt0816711", + "_version": 2, + "result": "updated", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 4, + "_primary_term": 1, + "status": 200 + } + } + ] +} +``` + +When operations fail, the response includes an `error` object with details about the failure: + +```json +{ + "took": 9, + "errors": true, + "items": [ + { + "update": { + "_index": "movies", + "_id": "nonexistent1", "status": 404, "error": { "type": "document_missing_exception", - "reason": "[_doc][tt0816711]: document missing", + "reason": "[nonexistent1]: document missing", "index": "movies", "shard": "0", - "index_uuid": "yhizhusbSWmP0G7OJnmcLg" + "index_uuid": "UZdzhOjDQvGihxfS-m_UFA" } } } ] } ``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`took` | Integer | The time in milliseconds it took to process the bulk request. +`errors` | Boolean | Indicates whether any operations in the bulk request failed. If `true`, examine individual items for error details. +`items` | Array of objects | Contains the result of each operation in the bulk request, in the order they were submitted. + +### The items array + +Each object in the `items` array corresponds to one operation and contains a key matching the action type (`index`, `create`, `update`, or `delete`). The value is an object containing the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`_index` | String | The name of the index associated with the operation. +`_id` | String | The document ID associated with the operation. +`_version` | Integer | The document version after the operation. Incremented each time the document is updated. Returned only for successful operations. +`result` | String | The result of the operation: `created`, `updated`, `deleted`, or `not_found`. Returned only for successful operations. +`_shards` | Object | Contains shard information for the operation. Returned only for successful operations. +`_shards.total` | Integer | The number of shards on which the operation was attempted. +`_shards.successful` | Integer | The number of shards on which the operation succeeded. +`_shards.failed` | Integer | The number of shards on which the operation failed. +`_seq_no` | Integer | The sequence number assigned to the document for the operation. Used for optimistic concurrency control. Returned only for successful operations. +`_primary_term` | Integer | The primary term assigned to the document for the operation. Used for optimistic concurrency control. Returned only for successful operations. +`status` | Integer | The HTTP status code for the operation: `200` (updated), `201` (created), `404` (not found), or `409` (version conflict). +`error` | Object | Contains information about a failed operation. Returned only for failed operations. +`error.type` | String | The error type for the failed operation, such as `document_missing_exception` or `version_conflict_engine_exception`. +`error.reason` | String | A human-readable explanation of the reason the operation failed. +`error.index` | String | The name of the index associated with the failed operation. +`error.shard` | String | The ID of the shard associated with the failed operation. +`error.index_uuid` | String | The universally unique identifier (UUID) of the index associated with the failed operation. + +## Partial responses and shard failures + +To ensure fast responses, the Bulk API returns results even when some shard operations fail. Each operation in the bulk request is processed independently, and OpenSearch includes the result of every operation in the response regardless of whether other operations succeeded or failed. + +When one or more shards fail to process an operation, OpenSearch continues processing the remaining operations and includes error information for the failed operations in the response. The top-level `errors` field indicates whether any operations encountered errors, allowing you to quickly determine if you need to examine individual operation results. + +Shard failures can occur for several reasons: + +- **Insufficient resources**: The node hosting the shard runs out of memory or disk space. +- **Network partitions**: The shard becomes temporarily unreachable due to network issues. +- **Version conflicts**: Optimistic concurrency control prevents the operation from completing. +- **Mapping errors**: The document doesn't conform to the index's mapping requirements. + +Your application should always check the `errors` field in the response and handle failed operations appropriately. Depending on your use case, you might retry failed operations, log them for later review, or alert operators to investigate the underlying cause. + +## Required permissions + +If you use the Security plugin, ensure you have the appropriate permissions to perform bulk operations. The required permissions depend on the operations in your bulk request: + +- `indices:data/write/bulk`: Required for all bulk operations. +- `indices:data/write/index`: Required for index and create operations. +- `indices:data/write/update`: Required for update operations. +- `indices:data/write/delete`: Required for delete operations. + +You also need permissions on the target indexes specified in your bulk request. When using index patterns or aliases, ensure your security role grants access to all indexes that the pattern or alias might match. diff --git a/_api-reference/document-apis/delete-by-query.md b/_api-reference/document-apis/delete-by-query.md index b205ed76..230d4617 100644 --- a/_api-reference/document-apis/delete-by-query.md +++ b/_api-reference/document-apis/delete-by-query.md @@ -2,99 +2,633 @@ layout: default title: Delete by query parent: Document APIs -nav_order: 40 +nav_order: 50 redirect_from: - /opensearch/rest-api/document-apis/delete-by-query/ --- -# Delete by query +# Delete by Query API **Introduced 1.0** {: .label .label-purple} -You can include a query as part of your delete request so OpenSearch deletes all documents that match that query. +The Delete by Query API removes all documents from an index that match a specified query. Instead of deleting documents one by one, this API allows you to delete multiple documents in a single request based on search criteria. -## Example +Use this API in the following scenarios: +- Removing outdated data from time-series indexes based on date ranges or other criteria. +- Cleaning up test data or invalid documents that match specific patterns. +- Implementing data retention policies by deleting documents that exceed a certain age. +- Deleting documents containing sensitive information. + +When you submit a delete by query request, OpenSearch creates a scroll context of the index at the start of the operation and deletes matching documents using internal versioning (sequence numbers and primary terms). The operation performs multiple search requests sequentially to find all matching documents, then executes bulk delete requests for each batch. If a document changes between when the snapshot is taken and when the delete operation processes it, a version conflict occurs and the delete fails for that document unless you set the `conflicts` parameter to `proceed`. Successfully deleted documents are not rolled back even if later operations in the batch fail. + +OpenSearch retries rejected search or bulk requests up to 10 times with exponential backoff. If the maximum retry limit is reached, the operation halts and returns all failed requests in the response. + +**Note:** OpenSearch cannot delete documents with version `0` using this API. The internal versioning system requires that version numbers are greater than 0 in order to track and process delete operations correctly. +{: .note} + + +## Endpoints ```json -POST sample-index1/_delete_by_query +POST /{index}/_delete_by_query +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | List or String | A comma-separated list of data streams, indexes, and aliases to search. Supports wildcards (`*`). To search all data streams or indexes, omit this parameter or use `*` or `_all`. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `_source` | Boolean or List or String | Set to `true` or `false` to return the `_source` field or not, or a list of fields to return. | N/A | +| `_source_excludes` | List | List of fields to exclude from the returned `_source` field. | N/A | +| `_source_includes` | List | List of fields to extract and return from the `_source` field. | N/A | +| `allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indexes. This behavior applies even if the request targets other open indexes. For example, a request targeting `foo*,bar*` returns an error if an index starts with `foo` but no index starts with `bar`. | N/A | +| `analyze_wildcard` | Boolean | If `true`, wildcard and prefix queries are analyzed. | `false` | +| `analyzer` | String | Analyzer to use for the query string. | N/A | +| `conflicts` | String | What to do if delete by query hits version conflicts: `abort` or `proceed`.
Valid values are:
- `abort`: Abort the operation on version conflicts.
- `proceed`: Proceed with the operation on version conflicts. | N/A | +| `default_operator` | String | The default operator for query string query: `AND` or `OR`.
Valid values are: `and`, `AND`, `or`, and `OR`. | N/A | +| `df` | String | Field to use as default where no field prefix is given in the query string. | N/A | +| `expand_wildcards` | List or String | Type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. Supports comma-separated values, such as `open,hidden`. Valid values are: `all`, `open`, `closed`, `hidden`, `none`.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | N/A | +| `from` | Integer | Starting offset. | `0` | +| `ignore_unavailable` | Boolean | If `false`, the request returns an error if it targets a missing or closed index. | N/A | +| `lenient` | Boolean | If `true`, format-based query failures (such as providing text to a numeric field) in the query string will be ignored. | N/A | +| `max_docs` | Integer | Maximum number of documents to process. Defaults to all documents. | N/A | +| `preference` | String | Specifies the node or shard the operation should be performed on. Random by default. | `random` | +| `q` | String | Query in the Lucene query string syntax. | N/A | +| `refresh` | Boolean or String | If `true`, OpenSearch refreshes all shards involved in the delete by query after the request completes.
Valid values are:
- `false`: Do not refresh the affected shards.
- `true`: Refresh the affected shards immediately.
- `wait_for`: Wait for the changes to become visible before replying. | N/A | +| `request_cache` | Boolean | If `true`, the request cache is used for this request. Defaults to the index-level setting. | N/A | +| `requests_per_second` | Float | The throttle for this request in sub-requests per second. | `0` | +| `routing` | List or String | A custom value used to route operations to a specific shard. | N/A | +| `scroll` | String | Period to retain the search context for scrolling. | N/A | +| `scroll_size` | Integer | Size of the scroll request that powers the operation. | `100` | +| `search_timeout` | String | Explicit timeout for each search request. Defaults to no timeout. | N/A | +| `search_type` | String | The type of the search operation. Available options: `query_then_fetch`, `dfs_query_then_fetch`.
Valid values are:
- `dfs_query_then_fetch`: Documents are scored using global term and document frequencies across all shards. This is usually slower but more accurate.
- `query_then_fetch`: Documents are scored using local term and document frequencies for the shard. This is usually faster but less accurate. | N/A | +| `size` | Integer | Deprecated, use `max_docs` instead. | N/A | +| `slices` | Integer or String | The number of slices this task should be divided into.
Valid values are:
- `auto`: Automatically determine the number of slices. | N/A | +| `sort` | List | A comma-separated list of : pairs. | N/A | +| `stats` | List | Specific `tag` of the request for logging and statistical purposes. | N/A | +| `terminate_after` | Integer | Maximum number of documents to collect for each shard. If a query reaches this limit, OpenSearch terminates the query early. OpenSearch collects documents before sorting. Use with caution. OpenSearch applies this parameter to each shard handling the request. When possible, let OpenSearch perform early termination automatically. Avoid specifying this parameter for requests that target data streams with backing indexes across multiple data tiers. | N/A | +| `timeout` | String | Period each deletion request waits for active shards. | N/A | +| `version` | Boolean | If `true`, returns the document version as part of a hit. | N/A | +| `wait_for_active_shards` | Integer or String or NULL or String | The number of shard copies that must be active before proceeding with the operation. Set to all or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
Valid values are:
- `all`: Wait for all shards to be active. | N/A | +| `wait_for_completion` | Boolean | If `true`, the request blocks until the operation is complete. | `true` | + + + + +## Request body fields + +The request body is optional but typically includes a query to specify which documents to delete. + +Field | Data type | Description +:--- | :--- | :--- +`query` | Object | The query used to select documents for deletion. If not specified, the operation deletes all documents in the target index. For more information about query types, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). +`slice` | Object | Manually specify slice ID and maximum slices for parallel processing. Contains `id` (integer, slice number) and `max` (integer, total number of slices). Optional. +`max_docs` | Integer | Maximum number of documents to process. Optional. + +## Refreshing shards + +Specifying the `refresh` parameter refreshes all shards involved in the delete by query operation after the request completes. This behavior differs from the Delete Document API's `refresh` parameter, which only refreshes the shard that received the delete request. The Delete by Query API does not support the `wait_for` value for the `refresh` parameter. + +## Running delete by query asynchronously + +To run a delete by query operation asynchronously, set the `wait_for_completion` query parameter to `false`. OpenSearch performs preflight checks, launches the request, and returns a task ID that you can use to monitor progress or cancel the operation. When running asynchronously, OpenSearch creates a record of the task as a document at `.tasks/task/${taskId}`. After the task completes, delete the task document to allow OpenSearch to reclaim the space. + +## Waiting for active shards + +The `wait_for_active_shards` parameter controls how many shard copies must be active before processing the request. The `timeout` parameter controls how long each write request waits for unavailable shards to become available. These parameters work the same way as in the Bulk API. Because Delete by Query uses scrolled searches, you can specify the `scroll` parameter to control how long the search context remains active. The default scroll time is 5 minutes. + +## Throttling delete requests + +To control the rate at which delete by query issues batches of delete operations, set `requests_per_second` to any positive decimal number. This pads each batch with a wait time to throttle the rate. Set `requests_per_second` to `-1` to disable throttling. + +Throttling uses wait time between batches so that internal scroll requests can be given a timeout that accounts for request padding. The padding time is the difference between the batch size divided by `requests_per_second` and the time spent writing. By default, the batch size is 1,000, so if `requests_per_second` is set to 500: + +``` +target_time = 1,000 / 500 per second = 2 seconds +wait_time = target_time - write_time = 2 seconds - 0.5 seconds = 1.5 seconds +``` + +Because each batch is issued as a single bulk request, large batch sizes cause OpenSearch to create many requests and then wait before starting the next batch. This creates uneven processing patterns with periods of high activity followed by idle waiting. + +## Slicing for parallel processing + +You can use slicing to run delete operations in parallel across multiple threads. This approach divides the delete operation into independent segments, improving performance for large-scale deletions. + +Setting `slices` to `auto` allows OpenSearch to choose a reasonable number for most indexes. When using automatic slicing or tuning it manually, consider these factors: + +- Optimal query performance occurs when you match the slice count to your shard count. However, for indexes with many shards (500 or more), use fewer slices to avoid performance degradation from excessive parallelization overhead. Setting slices higher than the number of shards generally does not improve efficiency and adds overhead. +- Delete performance scales linearly across available resources with the number of slices. +- Whether query or delete performance dominates runtime depends on the documents being deleted and available cluster resources. + +## Example: Deleting documents matching a query + +The following example request deletes all documents from the `movies` index where the `year` field is less than 2000: + + +{% capture step1_rest %} +POST /movies/_delete_by_query { "query": { - "match": { - "movie-length": "124" + "range": { + "year": { + "lt": 2000 + } } } } -``` +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + body = { + "query": { + "range": { + "year": { + "lt": 2000 + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Deleting with conflicts set to proceed + +The following example request deletes documents matching the query and continues processing even when version conflicts occur: + + +{% capture step1_rest %} +POST /movies/_delete_by_query?conflicts=proceed +{ + "query": { + "match": { + "status": "archived" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + params = { "conflicts": "proceed" }, + body = { + "query": { + "match": { + "status": "archived" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Deleting from multiple indexes + +The following example request deletes documents from multiple indexes that match the query: + + +{% capture step1_rest %} +POST /movies,tv-shows/_delete_by_query +{ + "query": { + "match_all": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies,tv-shows", + body = { + "query": { + "match_all": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Using routing for targeted deletion + +The following example request limits the delete operation to shards with a specific routing value: + + +{% capture step1_rest %} +POST /movies/_delete_by_query?routing=user123 +{ + "query": { + "term": { + "user_id": "user123" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + params = { "routing": "user123" }, + body = { + "query": { + "term": { + "user_id": "user123" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Using scroll_size to control batch size + +The following example request uses a custom scroll batch size of 5,000 documents: + + +{% capture step1_rest %} +POST /movies/_delete_by_query?scroll_size=5000 +{ + "query": { + "term": { + "genre": "documentary" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + params = { "scroll_size": "5000" }, + body = { + "query": { + "term": { + "genre": "documentary" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Manual slicing for parallel processing + +The following example requests manually divide the delete operation into two slices for parallel processing: + + +{% capture step1_rest %} +POST /movies/_delete_by_query +{ + "slice": { + "id": 0, + "max": 2 + }, + "query": { + "range": { + "rating": { + "lt": 5 + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + body = { + "slice": { + "id": 0, + "max": 2 + }, + "query": { + "range": { + "rating": { + "lt": 5 + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +In a separate request, process the second slice: + + +{% capture step1_rest %} +POST /movies/_delete_by_query +{ + "slice": { + "id": 1, + "max": 2 + }, + "query": { + "range": { + "rating": { + "lt": 5 + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + body = { + "slice": { + "id": 1, + "max": 2 + }, + "query": { + "range": { + "rating": { + "lt": 5 + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Automatic slicing + +The following example request uses automatic slicing to parallelize the delete operation across 5 slices: + + +{% capture step1_rest %} +POST /movies/_delete_by_query?slices=5&refresh=true +{ + "query": { + "range": { + "views": { + "lt": 100 + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + params = { "slices": "5", "refresh": "true" }, + body = { + "query": { + "range": { + "views": { + "lt": 100 + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To allow OpenSearch to automatically determine the optimal number of slices, use `slices=auto`: + + +{% capture step1_rest %} +POST /movies/_delete_by_query?slices=auto +{ + "query": { + "match": { + "category": "test" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query( + index = "movies", + params = { "slices": "auto" }, + body = { + "query": { + "match": { + "category": "test" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +The following example response shows a successful delete by query operation that deleted 8 documents: -## Response ```json { - "took": 143, + "took": 88, "timed_out": false, - "total": 1, - "deleted": 1, + "total": 8, + "deleted": 8, "batches": 1, "version_conflicts": 0, "noops": 0, @@ -109,19 +643,219 @@ To search your index for specific documents, you must include a [query]({{site.u } ``` +When using manual slicing, the response includes a `slice_id` field indicating which slice was processed: + +```json +{ + "took": 13, + "timed_out": false, + "slice_id": 0, + "total": 9, + "deleted": 9, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0, + "failures": [] +} +``` + +When using automatic slicing with a specific number of slices, the response includes a `slices` array showing the results for each slice: + +```json +{ + "took": 52, + "timed_out": false, + "total": 9, + "deleted": 9, + "batches": 4, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0, + "slices": [ + { + "slice_id": 0, + "total": 3, + "deleted": 3, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0 + }, + { + "slice_id": 1, + "total": 2, + "deleted": 2, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0 + }, + { + "slice_id": 2, + "total": 0, + "deleted": 0, + "batches": 0, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0 + }, + { + "slice_id": 3, + "total": 1, + "deleted": 1, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0 + }, + { + "slice_id": 4, + "total": 3, + "deleted": 3, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0 + } + ], + "failures": [] +} +``` + ## Response body fields -Field | Description -:--- | :--- -took | The amount of time in milliseconds OpenSearch needed to complete the operation. -timed_out | Whether any delete requests during the operation timed out. -total | Total number of documents processed. -deleted | Total number of documents deleted. -batches | Number of scroll responses the request processed. -version_conflicts | Number of conflicts the request ran into. -noops | How many delete requests OpenSearch ignored during the operation. This field always returns 0. -retries | The number of bulk and search retry requests. -throttled_millis | Number of throttled milliseconds during the request. -requests_per_second | Number of requests executed per second during the operation. -throttled_until_millis | The amount of time until OpenSearch executes the next throttled request. Always equal to 0 in a delete by query request. -failures | Any failures that occur during the request. +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`took` | Integer | The amount of time from the start to the end of the entire operation, in milliseconds. +`timed_out` | Boolean | Whether any of the requests executed during the delete by query operation timed out. When set to `true`, successfully completed deletions still stick and are not rolled back. +`total` | Integer | The total number of documents that were successfully processed. +`deleted` | Integer | The number of documents that were successfully deleted. +`batches` | Integer | The number of scroll batches processed by the delete by query operation. +`version_conflicts` | Integer | The number of version conflicts encountered by the delete by query operation. Occurs when a document changes between the time the snapshot is taken and when the delete operation is processed. +`noops` | Integer | The number of no-operation requests. This field always returns 0 for delete by query. It exists to maintain response structure consistency with Update by Query and Reindex APIs. +`retries` | Object | The number of retries attempted by the delete by query operation. Contains `bulk` (number of bulk action retries) and `search` (number of search action retries). +`throttled_millis` | Integer | The amount of time the request was throttled to conform to `requests_per_second`, in milliseconds. +`requests_per_second` | Float | The number of requests per second effectively executed during the delete by query operation. +`throttled_until_millis` | Integer | The amount of time until the next throttled request will be executed, in milliseconds. Always equals 0 in a completed delete by query response. This field has meaning only when using the Tasks API to monitor an ongoing operation, where it indicates the next time a throttled request will execute. +`slice_id` | Integer | The slice number for this response. Only present when using manual slicing. Indicates which slice of the operation this response represents. +`slices` | Array | An array of slice results when using automatic slicing with a specific number. Each element contains the same response fields as the main response, showing the results for that individual slice. +`failures` | Array | An array of failures if any unrecoverable errors occurred during the operation. If this array is not empty, the request aborted because of those failures. Delete by query is implemented using batches, and any failure causes the entire process to abort, but all failures in the current batch are collected in this array. You can use the `conflicts` parameter set to `proceed` to prevent the operation from aborting on version conflicts. + +## Managing delete by query tasks + +When you run a delete by query operation asynchronously by setting `wait_for_completion=false`, OpenSearch returns a task ID that you can use to monitor, modify, or cancel the operation. + +### Retrieving the status of a delete by query operation + +To retrieve the status of a delete by query operation, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/): + +```json +GET _tasks?detailed=true&actions=*/delete/byquery +``` +{% include copy-curl.html %} + +The response includes the status of all running delete by query operations. To retrieve the status of a specific task, use the task ID: + +```json +GET _tasks/{task_id} +``` +{% include copy-curl.html %} + +The response contains detailed information about the operation's progress: + +```json +{ + "nodes": { + "node_id": { + "tasks": { + "task_id": { + "status": { + "total": 1000, + "updated": 0, + "created": 0, + "deleted": 450, + "batches": 5, + "version_conflicts": 0, + "noops": 0, + "retries": 0, + "throttled_millis": 0 + } + } + } + } + } +} +``` + +The `total` field represents the total number of operations that the delete by query operation expects to perform. You can estimate progress by comparing the `deleted` field to the `total` field. The operation is complete when `deleted` equals `total`. + +### Changing throttling for a running operation + +To change the throttling of a running delete by query operation, use the Rethrottle Task API with the task ID: + +```json +POST _delete_by_query/{task_id}/_rethrottle?requests_per_second=100 +``` +{% include copy-curl.html %} + +Set `requests_per_second` to any positive decimal value or `-1` to disable throttling. Rethrottling that speeds up the operation takes effect immediately. Rethrottling that slows down the operation takes effect after completing the current batch to prevent scroll timeouts. + +### Canceling a delete by query operation + +To cancel a running delete by query operation, use the task cancel API: + +```json +POST _tasks/{task_id}/_cancel +``` +{% include copy-curl.html %} + +Cancellation should happen quickly but might take a few seconds. The Tasks API continues to list the delete by query task until it checks that it has been canceled and terminates itself. When you cancel a delete by query operation with slices, OpenSearch cancels each sub-request. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/write/delete/byquery`. diff --git a/_api-reference/document-apis/delete-document.md b/_api-reference/document-apis/delete-document.md index c3dea2f7..aeac983b 100644 --- a/_api-reference/document-apis/delete-document.md +++ b/_api-reference/document-apis/delete-document.md @@ -3,73 +3,266 @@ layout: default title: Delete document parent: Document APIs nav_order: 15 -redirect_from: +redirect_from: - /opensearch/rest-api/document-apis/delete-document/ --- -# Delete document +# Delete Document API **Introduced 1.0** {: .label .label-purple } -If you no longer need a document in your index, you can use the delete document API operation to delete it. - -## Example +The Delete Document API removes a document from an index. You must specify both the index name and document ID. When a document is deleted, OpenSearch increments its version number and marks it for removal during the next segment merge. + +## Endpoints +```json +DELETE /{index}/_doc/{id} ``` -DELETE /sample-index1/_doc/1 -``` -{% include copy-curl.html %} + -## Path and HTTP methods + +## Path parameters -``` -DELETE //_doc/<_id> -``` +The following table lists the available path parameters. -## URL parameters +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `id` | **Required** | String | The unique identifier for the document. | +| `index` | **Required** | String | Name of the target index. | -Parameter | Type | Description | Required -:--- | :--- | :--- | :--- -<index> | String | The index to delete from. | Yes -<_id> | String | The ID of the document to delete. | Yes -if_seq_no | Integer | Only perform the delete operation if the document's version number matches the specified number. | No -if_primary_term | Integer | Only perform the delete operation if the document has the specified primary term. | No -refresh | Enum | If true, OpenSearch refreshes shards to make the delete operation available to search results. Valid options are `true`, `false`, and `wait_for`, which tells OpenSearch to wait for a refresh before executing the operation. Default is `false`. | No -routing | String | Value used to route the operation to a specific shard. | No -timeout | Time | How long to wait for a response from the cluster. Default is `1m`. | No -version | Integer | The version of the document to delete, which must match the last updated version of the document. | No -version_type | Enum | Retrieves a specifically typed document. Available options are `external` (retrieve the document if the specified version number is greater than the document's current version) and `external_gte` (retrieve the document if the specified version number is greater than or equal to the document's current version). For example, to delete version 3 of a document, use `/_doc/1?version=3&version_type=external`. | No -wait_for_active_shards | String | The number of active shards that must be available before OpenSearch processes the delete request. Default is 1 (only the primary shard). Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the operation to succeed. | No + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `if_seq_no` | Integer | Only perform the delete operation if the document has this sequence number. See [Optimistic concurrency control](#optimistic-concurrency-control). | +| `if_primary_term` | Integer | Only perform the delete operation if the document has this primary term. See [Optimistic concurrency control](#optimistic-concurrency-control). | +| `refresh` | Boolean or String | Controls when changes made by the delete operation become visible to search. Valid values are `true` (refresh immediately), `false` (default, do not refresh), and `wait_for` (wait for a refresh before responding). See [Refresh](#refresh). | +| `routing` | String | A custom value used to route the operation to a specific shard. Required if the document was indexed with a routing value. See [Routing](#routing). | +| `timeout` | Time | How long to wait for the primary shard to become available. Default is `1m` (1 minute). See [Timeout](#timeout). | +| `version` | Integer | Explicit version number for concurrency control. The specified version must match the current version of the document for the request to succeed. See [Versioning](#versioning). | +| `version_type` | Enum | Specifies the version type: `internal` (default), `external`, or `external_gte`. With `external`, the version number must be greater than the current version. With `external_gte`, it must be greater than or equal. See [Versioning](#versioning). | +| `wait_for_active_shards` | String | The number of shard copies that must be active before proceeding with the operation. Default is `1` (only the primary shard). Set to `all` or any positive integer up to the total number of shards in the index (`number_of_replicas+1`). See [Wait for active shards](#wait-for-active-shards). | + +## Example request + +The following example request deletes a document with the ID `1` from the `products` index: + + +{% capture step1_rest %} +DELETE /products/_doc/1 +{% endcapture %} + +{% capture step1_python %} -## Response +response = client.delete( + id = "1", + index = "products" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following example response shows a successful delete operation: + ```json { - "_index": "sample-index1", - "_id": "1", - "_version": 2, - "result": "deleted", - "_shards": { - "total": 2, - "successful": 2, - "failed": 0 + "_index" : "products", + "_id" : "1", + "_version" : 9, + "result" : "deleted", + "_shards" : { + "total" : 2, + "successful" : 1, + "failed" : 0 }, - "_seq_no": 1, - "_primary_term": 15 + "_seq_no" : 45, + "_primary_term" : 1 } ``` ## Response body fields +The response body contains information about the delete operation and the affected document. + Field | Description :--- | :--- -_index | The name of the index. -_id | The document's ID. -_version | The document's version. -_result | The result of the delete operation. -_shards | Detailed information about the cluster's shards. -total | The total number of shards. -successful | The number of shards OpenSearch successfully deleted the document from. -failed | The number of shards OpenSearch failed to delete the document from. -_seq_no | The sequence number assigned when the document was indexed. -_primary_term | The primary term assigned when the document was indexed. +`_index` | The name of the index from which the document was deleted. +`_id` | The unique identifier of the deleted document. +`_version` | The new version number of the document after deletion. Each delete operation increments the version number. +`result` | The result of the delete operation. Returns `deleted` if the document was successfully deleted or `not_found` if the document did not exist. +`_shards` | Contains information about the shards involved in the delete operation. +`_shards.total` | The total number of shards (primary and replicas) that should have acknowledged the delete operation. +`_shards.successful` | The number of shards that successfully processed the delete operation. +`_shards.failed` | The number of shards that failed to process the delete operation. When this value is greater than 0, the `failures` array contains details about the failures. +`_seq_no` | The sequence number assigned to the delete operation. Sequence numbers are used for optimistic concurrency control. +`_primary_term` | The primary term at the time of the delete operation. Combined with `_seq_no`, this value is used for optimistic concurrency control. + +## Optimistic concurrency control + +Delete operations support optimistic concurrency control through the `if_seq_no` and `if_primary_term` parameters. When you specify these parameters, OpenSearch only performs the delete operation if the document's current sequence number and primary term match the provided values. If there is a mismatch, OpenSearch returns a `version_conflict_engine_exception` error with status code `409`, indicating that the document has been modified since you last retrieved it. + +The following example request deletes a document only if its sequence number is `43` and its primary term is `1`: + + +{% capture step1_rest %} +DELETE /products/_doc/3?if_seq_no=43&if_primary_term=1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete( + id = "3", + index = "products", + params = { "if_seq_no": "43", "if_primary_term": "1" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If the document's current sequence number or primary term does not match the specified values, OpenSearch returns a version conflict error with status code `409`. + +## Versioning + +Every write operation on a document, including deletions, increments the document's version number. After a document is deleted, its version number remains available for a short period to support concurrent operations. The duration for which this version information is retained is controlled by the `index.gc_deletes` index setting, which defaults to 60 seconds. This allows OpenSearch to properly handle concurrent delete requests and maintain consistency across replicas. + +## Automatic index creation + +When you use an external versioning variant (`version_type=external` or `version_type=external_gte`), the delete operation automatically creates the specified index if it does not exist. This behavior only occurs with external versioning types and does not apply to the default internal versioning. + +The following example request creates the `auto-created-index` index automatically because it uses external versioning: + + +{% capture step1_rest %} +DELETE /auto-created-index/_doc/1?version=5&version_type=external +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete( + id = "1", + index = "auto-created-index", + params = { "version": "5", "version_type": "external" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The operation returns a `not_found` result because the document does not exist, but the index is created as a side effect. Without external versioning, attempting to delete a document from a non-existent index returns an `index_not_found_exception` error. + +## Routing + +When documents are indexed with a specific routing value, OpenSearch uses that value to determine which shard stores the document. To delete a routed document, you must provide the same routing value used during indexing. If your index has a mapping that sets `_routing` to `required` and you attempt to delete a document without specifying a routing value, OpenSearch rejects the request with a `RoutingMissingException`. + +The following example request deletes a document that was indexed with the routing value `electronics`: + + +{% capture step1_rest %} +DELETE /products/_doc/2?routing=electronics +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete( + id = "2", + index = "products", + params = { "routing": "electronics" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Without the correct routing value, OpenSearch cannot locate the document on the appropriate shard and the delete operation will fail. + +## Distributed execution + +When you send a delete request, OpenSearch hashes the document ID to determine the target shard. The request is then routed to the primary shard in that shard group. After the primary shard processes the delete operation, the changes are replicated to all replica shards in the same shard group, ensuring consistency across the cluster. + +## Refresh + +By default, deleted documents become visible to search operations only after the next index refresh, which occurs every second by default. You can control this behavior using the `refresh` parameter: + +- `false` (default): The delete operation returns immediately, and the change becomes visible after the next automatic refresh. +- `true`: OpenSearch refreshes all affected shards immediately after the delete operation, making the change visible to search operations right away. This option has a performance impact and should be used sparingly. +- `wait_for`: The delete operation waits for the next automatic refresh before returning a response, ensuring that the change is visible when the API call completes. + +## Wait for active shards + +The `wait_for_active_shards` parameter controls how many shard copies must be available before OpenSearch processes a delete request. By default, this value is `1`, meaning only the primary shard must be active. You can set this to `all` to require all shard copies (primary and replicas) to be active, or specify a positive integer to require a specific number of active shards. This setting helps ensure data durability by waiting for replicas to be available before confirming the delete operation. + +## Timeout + +If the primary shard is unavailable when a delete request arrives (for example, during recovery or relocation), OpenSearch waits for the shard to become available. The `timeout` parameter specifies how long to wait before failing the request. The default timeout is 1 minute. If the primary shard does not become available within the specified timeout period, OpenSearch returns an error. + +The following example request sets a custom timeout of 30 seconds: + + +{% capture step1_rest %} +DELETE /products/_doc/4?timeout=30s +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete( + id = "4", + index = "products", + params = { "timeout": "30s" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/write/delete`. diff --git a/_api-reference/document-apis/get-documents.md b/_api-reference/document-apis/get-documents.md index d5c2e52d..7c5496b5 100644 --- a/_api-reference/document-apis/get-documents.md +++ b/_api-reference/document-apis/get-documents.md @@ -3,77 +3,570 @@ layout: default title: Get document parent: Document APIs nav_order: 5 -redirect_from: +redirect_from: - /opensearch/rest-api/document-apis/get-documents/ --- -# Get document +# Get Document API **Introduced 1.0** {: .label .label-purple } -After adding a JSON document to your index, you can use the get document API operation to retrieve the document's information and data. +The Get Document API retrieves a JSON document and its metadata from an index by document ID. You can also use HEAD requests to verify that a document or its source exists without retrieving the full content. -## Example +## Endpoints + +To retrieve a document and its metadata from an index, use the `GET` method: ```json -GET sample-index1/_doc/1 -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -GET /_doc/<_id> -HEAD /_doc/<_id> -``` -``` -GET /_source/<_id> -HEAD /_source/<_id> +GET /{index}/_doc/{id} ``` -## URL parameters +To retrieve only the document source, use the following endpoint: -All get document URL parameters are optional. +```json +GET /{index}/_source/{id} +``` -Parameter | Type | Description -:--- | :--- | :--- -preference | String | Specifies a preference of which shard to retrieve results from. Available options are `_local`, which tells the operation to retrieve results from a locally allocated shard replica, and a custom string value assigned to a specific shard replica. By default, OpenSearch executes get document operations on random shards. -realtime | Boolean | Specifies whether the operation should run in realtime. If false, the operation waits for the index to refresh to analyze the source to retrieve data, which makes the operation near-realtime. Default is true. -refresh | Boolean | If true, OpenSearch refreshes shards to make the get operation available to search results. Valid options are `true`, `false`, and `wait_for`, which tells OpenSearch to wait for a refresh before executing the operation. Default is `false`. -routing | String | A value used to route the operation to a specific shard. -stored_fields | Boolean | Whether the get operation should retrieve fields stored in the index. Default is false. -_source | String | Whether to include the `_source` field in the response body. Default is true. -_source_excludes | String | A comma-separated list of source fields to exclude in the query response. -_source_includes | String | A comma-separated list of source fields to include in the query response. -version | Integer | The version of the document to return, which must match the current version of the document. -version_type | Enum | Retrieves a specifically typed document. Available options are `external` (retrieve the document if the specified version number is greater than the document's current version) and `external_gte` (retrieve the document if the specified version number is greater than or equal to the document's current version). For example, to retrieve version 3 of a document, use `/_doc/1?version=3&version_type=external`. +To verify that a document exists, use the `HEAD` method: + +```json +HEAD /{index}/_doc/{id} +HEAD /{index}/_source/{id} +``` + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `id` | **Required** | String | The unique identifier of the document. | +| `index` | **Required** | String | The name of the index containing the document. | + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Methods | Data type | Description | Default | +| :--- | :--- | :--- | :--- | :--- | +| `_source` | `GET` | Boolean or List or String | Whether to return the `_source` field. Set to `true` to include it, `false` to exclude it, or specify a comma-separated list of field names to return. See [Source filtering](#source-filtering).| N/A | +| `_source_excludes` | `GET` | List or String | A comma-separated list of source fields to exclude from the response. See [Source filtering](#source-filtering). | N/A | +| `_source_includes` | `GET` | List or String | A comma-separated list of source fields to include in the response. See [Source filtering](#source-filtering). | N/A | +| `preference` | `GET`, `HEAD` | String | A preference for which node or shard should handle the operation. By default, OpenSearch selects a shard replica randomly. See [Preference](#preference). | `random` | +| `realtime` | `GET`, `HEAD` | Boolean | Whether the request is real time. If `true`, the request retrieves the most recent version of the document. If `false`, the request is near-real-time and retrieves the document based on the last refresh. See [Real-time behavior](#real-time-behavior). | `true` | +| `refresh` | `GET`, `HEAD` | Boolean or String | Whether to refresh the affected shards before the operation to make recent changes visible.
Valid values are:
- `false`: Do not refresh the affected shards.
- `true`: Refresh the affected shards immediately.
- `wait_for`: Wait for the changes to become visible before responding. See [Refresh](#refresh). | `false` | +| `routing` | `GET`, `HEAD` | List or String | The routing value used to target a specific primary shard. See [Routing](#routing).| N/A | +| `stored_fields` | `GET` | List or String | A comma-separated list of stored fields to return. If no fields are specified, no stored fields are included in the response. If this parameter is specified, the `_source` parameter defaults to `false`. | N/A | +| `version` | `GET`, `HEAD` | Integer | The explicit version number for concurrency control. The specified version must match the current version of the document for the request to succeed. | N/A | +| `version_type` | `GET`, `HEAD` | String | The version type for concurrency control.
Valid values are:
- `internal`: The version number is managed internally by OpenSearch.
- `external`: The version number must be greater than the current version.
- `external_gte`: The version number must be greater than or equal to the current version. | `internal` | + +## Example request + +The following example retrieves a document by its ID: + + +{% capture step1_rest %} +GET /products/_doc/1 +{% endcapture %} + +{% capture step1_python %} -## Response +response = client.get( + id = "1", + index = "products" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following example shows a response from a `GET` request: + ```json { - "_index": "sample-index1", + "_index": "products", "_id": "1", "_version": 1, "_seq_no": 0, - "_primary_term": 9, + "_primary_term": 1, "found": true, "_source": { - "text": "This is just some sample text." + "name": "Wireless Mouse", + "description": "Ergonomic wireless mouse with optical sensor", + "price": 29.99, + "category": "Electronics", + "in_stock": true, + "manufacturer": "TechCorp", + "model": "WM-2000", + "tags": [ + "wireless", + "ergonomic", + "optical" + ] } } ``` ## Response body fields -Field | Description -:--- | :--- -_index | The name of the index. -_id | The document's ID. -_version | The document's version number. Updated whenever the document changes. -_seq_no | The sequence number assigned when the document is indexed. -primary_term | The primary term assigned when the document is indexed. -found | Whether the document exists. -_routing | The shard that the document is routed to. If the document is not routed to a particular shard, this field is omitted. -_source | Contains the document's data if `found` is true. If `_source` is set to false or `stored_fields` is set to true in the URL parameters, this field is omitted. -_fields | Contains the document's data that's stored in the index. Only returned if both `stored_fields` and `found` are true. +The `GET` response contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`_index` | String | The name of the index containing the document. +`_id` | String | The document's unique identifier. +`_version` | Integer | The document's version number. Incremented each time the document is updated. +`_seq_no` | Integer | The sequence number assigned to the document for the indexing operation. Used to ensure an older version doesn't overwrite a newer version. +`_primary_term` | Integer | The primary term assigned to the document for the indexing operation. Used with `_seq_no` for optimistic concurrency control. +`found` | Boolean | Indicates whether the document exists. `true` if the document was found, `false` otherwise. +`_routing` | String | The routing value used to determine which shard stores the document. Only included if a routing value was specified when the document was indexed. +`_source` | Object | The original JSON document that was indexed. Excluded if the `_source` parameter is set to `false` or if the `stored_fields` parameter is used. +`_fields` | Object | Contains stored field values when the `stored_fields` parameter is specified. Only returned if `stored_fields` is set and `found` is `true`. Field values are always returned as arrays. See [Retrieving stored fields](#retrieving-stored-fields). + +## Source filtering + +By default, the Get Document API returns the entire contents of the `_source` field. You can control which parts of the source are returned or exclude it entirely. + +### Disabling source retrieval + +To exclude the `_source` field from the response, set the `_source` parameter to `false`. The following example retrieves document metadata without the source content: + + +{% capture step1_rest %} +GET /products/_doc/1?_source=false +{% endcapture %} + +{% capture step1_python %} + + +response = client.get( + id = "1", + index = "products", + params = { "_source": "false" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response excludes the `_source` field: + +```json +{ + "_index": "products", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true +} +``` + +### Source includes and excludes + +To retrieve only specific fields from a large document, use the `_source_includes` parameter to include specific fields or the `_source_excludes` parameter to exclude fields. This reduces network overhead by transferring only the required data. + +The following example retrieves only the `name` and `price` fields: + + +{% capture step1_rest %} +GET /products/_doc/1?_source_includes=name,price +{% endcapture %} + +{% capture step1_python %} + + +response = client.get( + id = "1", + index = "products", + params = { "_source_includes": "name,price" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The `_source` field of the response contains only the `price` and `name` fields: + +```json +{ + "_index": "products", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "price": 29.99, + "name": "Wireless Mouse" + } +} +``` + +### Shorter notation + +If you only need to include certain fields without excluding any, use the shorter notation by specifying fields directly in the `_source` parameter. The following example retrieves only the `name` and `price` fields: + + +{% capture step1_rest %} +GET /products/_doc/1?_source=name,price +{% endcapture %} + +{% capture step1_python %} + + +response = client.get( + id = "1", + index = "products", + params = { "_source": "name,price" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Retrieving the source field only + +Use the `_source` endpoint to retrieve only the document source without metadata. The following example retrieves only the source content: + + +{% capture step1_rest %} +GET /products/_source/1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.get_source( + id = "1", + index = "products" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the `_source` field only: + +```json +{ + "name": "Wireless Mouse", + "description": "Ergonomic wireless mouse with optical sensor", + "price": 29.99, + "category": "Electronics", + "in_stock": true, + "manufacturer": "TechCorp", + "model": "WM-2000", + "tags": [ + "wireless", + "ergonomic", + "optical" + ] +} +``` + +You can combine the `_source` endpoint with source filtering parameters. The following example retrieves only specific fields from the source: + + +{% capture step1_rest %} +GET /products/_source/1?_source=name,price +{% endcapture %} + +{% capture step1_python %} + + +response = client.get_source( + id = "1", + index = "products", + params = { "_source": "name,price" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains only the `price` and `name` fields: + +```json +{ + "price": 29.99, + "name": "Wireless Mouse" +} +``` + +You can use HEAD with the `_source` endpoint to check whether the document source exists: + + +{% capture step1_rest %} +HEAD /products/_source/1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.exists_source( + id = "1", + index = "products" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains only `200 - true`. + +## Routing + +When documents are indexed with a custom routing value, you must provide the same routing value when retrieving them. The routing value determines which shard stores the document. + +The following example retrieves a document that was indexed with routing value `user1`: + + +{% capture step1_rest %} +GET /products/_doc/2?routing=user1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.get( + id = "2", + index = "products", + params = { "routing": "user1" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the document with the specified routing: + +```json +{ + "_index": "products", + "_id": "2", + "_version": 1, + "_seq_no": 1, + "_primary_term": 1, + "_routing": "user1", + "found": true, + "_source": { + "name": "Mechanical Keyboard", + "description": "RGB mechanical gaming keyboard", + "price": 149.99, + "category": "Electronics", + "in_stock": true, + "manufacturer": "GameGear", + "model": "MK-500", + "tags": [ + "mechanical", + "rgb", + "gaming" + ] + } +} +``` + +If you don't specify the correct routing value, OpenSearch cannot locate the document and returns a `found: false` response. + +## Retrieving stored fields + +Use the `stored_fields` parameter to retrieve specific fields that were stored in the index at indexing time. Only fields with `store: true` in the mapping are returned. Fields without this setting are ignored. + +The following example retrieves only the `category` and `manufacturer` stored fields from a document: + + +{% capture step1_rest %} +GET /products/_doc/1?stored_fields=category,manufacturer +{% endcapture %} + +{% capture step1_python %} + + +response = client.get( + id = "1", + index = "products", + params = { "stored_fields": "category,manufacturer" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Note that field values retrieved from stored fields are always returned as arrays. Even though `category` and `manufacturer` are single-valued fields, they are returned in arrays: + +```json +{ + "_index": "products", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "fields": { + "category": [ + "Electronics" + ], + "manufacturer": [ + "TechCorp" + ] + } +} +``` + +When retrieving stored fields from a document indexed with routing, you must provide the routing value. The following example retrieves stored fields from a document with routing: + + +{% capture step1_rest %} +GET /products/_doc/2?routing=user1&stored_fields=category,manufacturer +{% endcapture %} + +{% capture step1_python %} + + +response = client.get( + id = "2", + index = "products", + params = { "routing": "user1", "stored_fields": "category,manufacturer" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Checking document existence + +You can use the HEAD method to verify whether a document exists without retrieving its content. OpenSearch returns HTTP status code `200` if the document exists or `404` if it doesn't. + +The following example checks whether a document exists: + + +{% capture step1_rest %} +HEAD /products/_doc/1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.exists( + id = "1", + index = "products" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains only `200 - true`. + +## Preference + +The `preference` parameter controls which shard replica handles the request. By default, OpenSearch randomly distributes get operations across available shard replicas. + +You can set the `preference` parameter to one of the following values: + +- `_local`: Directs the operation to a locally allocated shard replica, reducing network overhead. +- Custom string value: Routes requests with the same custom value to the same shard replicas. This ensures consistent results when shards are in different refresh states. Common custom values include session IDs or usernames. + +## Real-time behavior + +By default, the Get Document API operates in real time, retrieving the latest version of a document regardless of the index refresh rate. This means you can retrieve a document immediately after indexing it, even before the index has been refreshed to make it searchable. + +When you request stored fields (using the `stored_fields` parameter) and the document has been updated but not yet refreshed, OpenSearch parses and analyzes the document source to extract the requested stored fields. + +To disable real-time behavior and retrieve the document based on the last refreshed state of the index, set the `realtime` parameter to `false`. + +## Refresh + +The `refresh` parameter can be set to `true` to refresh the relevant shard before retrieving the document. Refreshing makes recent changes searchable but can impose significant system load and slow indexing. Carefully evaluate the trade-off between data freshness and performance before enabling this parameter. + +## Versioning + +You can use the `version` parameter to retrieve a document only if its current version matches the specified number. This ensures data consistency when working with versioned documents. + +Internally, OpenSearch marks the old document version as deleted when a document is updated and creates an entirely new document version. Although you cannot access old versions through the Get Document API, OpenSearch automatically cleans up deleted versions in the background during indexing. + +## Distributed model + +The Get Document API uses the document ID to compute a hash value that identifies the shard storing the document. OpenSearch then routes the request to one of the replicas in that shard group (including the primary shard and its replicas) and returns the result. + +Having more shard replicas improves GET operation scalability because the load is distributed across multiple replicas, increasing throughput for retrieval requests. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/get`. diff --git a/_api-reference/document-apis/index-document.md b/_api-reference/document-apis/index-document.md index ec1664bc..c131a26f 100644 --- a/_api-reference/document-apis/index-document.md +++ b/_api-reference/document-apis/index-document.md @@ -7,63 +7,145 @@ redirect_from: - /opensearch/rest-api/document-apis/index-document/ --- -# Index document +# Index Document API **Introduced 1.0** {: .label .label-purple} -Before you can search for data, you must first add documents. This operation adds a single document to your index. +The Index Document API adds a JSON document to a specified index and makes it searchable. If a document with the same ID already exists, the API updates the document and increments its version number. -## Example + +## Endpoints ```json -PUT sample-index/_doc/1 +PUT {index}/_doc/{id} +POST {index}/_doc + +PUT {index}/_create/{id} +POST {index}/_create/{id} +``` + +Use the following endpoint combinations to control how documents are indexed: + +- `PUT {index}/_doc/{id}`: Adds a new document with a specified ID or updates an existing document with the same ID. +- `POST {index}/_doc`: Adds a new document and automatically generates a unique ID. +- `PUT {index}/_create/{id}` or `POST {index}/_create/{id}`: Adds a new document with a specified ID only if a document with that ID does not already exist. If the document exists, the operation fails. + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | The name of the index. If the index does not exist, OpenSearch creates it automatically unless automatic index creation is disabled. Required. | +| `id` | String | The unique document ID. Required when using PUT. Omit this parameter when using POST to let OpenSearch automatically generate a unique ID. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `if_seq_no` | Integer | Only performs the operation if the document's current sequence number matches the specified value. Used for optimistic concurrency control. See [Optimistic concurrency control](#optimistic-concurrency-control). | +| `if_primary_term` | Integer | Only performs the operation if the document's current primary term matches the specified value. Used for optimistic concurrency control. See [Optimistic concurrency control](#optimistic-concurrency-control). | +| `op_type` | Enum | The operation type. Valid values are `create` (indexes a document only if it does not already exist) and `index` (creates a new document or updates an existing document). If a document ID is specified, the default is `index`. Otherwise, the default is `create`. | +| `pipeline` | String | The ID of the ingest pipeline to use for preprocessing the document before indexing. | +| `routing` | String | A custom routing value used to route the operation to a specific shard. See [Routing](#routing). | +| `refresh` | Enum | Whether to refresh the affected shards after the operation. Valid values are `true` (refresh immediately), `false` (do not refresh), and `wait_for` (wait for a refresh to occur before responding). Default is `false`. See [Refresh](#refresh). | +| `timeout` | Time | The amount of time to wait for the primary shard to become available if it is unavailable. Default is `1m`. See [Timeout](#timeout). | +| `version` | Integer | The explicit version number for concurrency control. The document is only indexed if its current version matches this value. See [Versioning](#versioning). | +| `version_type` | Enum | The version type for external versioning. Valid values are `external` (only indexes if the specified version is greater than the stored version) and `external_gte` (only indexes if the specified version is greater than or equal to the stored version). Default is `internal`. See [Versioning](#versioning). | +| `wait_for_active_shards` | String | The number of active shard copies required before proceeding with the operation. Valid values are `all` or a positive integer up to the total number of shards. Default is `1` (only the primary shard). See [Wait for active shards](#wait-for-active-shards). | +| `require_alias` | Boolean | Whether the target index name must be an index alias. If `true` and the target is not an alias, the request fails. Default is `false`. | + +## Example requests + +The following example requests create a sample index document for an index named `sample_index`. + + +### Example PUT request + + +{% capture step1_rest %} +PUT /sample_index/_doc/1 { - "Description": "This is just a sample document" + "name": "Example", + "price": 29.99, + "description": "To be or not to be, that is the question" } -``` +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "sample_index", + id = "1", + body = { + "name": "Example", + "price": 29.99, + "description": "To be or not to be, that is the question" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example POST request + + +{% capture step1_rest %} +POST /sample_index/_doc +{ + "name": "Another Example", + "price": 19.99, + "description": "We are such stuff as dreams are made on" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "sample_index", + body = { + "name": "Another Example", + "price": 19.99, + "description": "We are such stuff as dreams are made on" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response -## Response ```json { "_index": "sample-index", @@ -82,15 +164,180 @@ Your request body must contain the information you want to index. ## Response body fields -Field | Description -:--- | :--- -_index | The name of the index. -_id | The document's ID. -_version | The document's version. -result | The result of the index operation. -_shards | Detailed information about the cluster's shards. -total | The total number of shards. -successful | The number of shards OpenSearch successfully added the document to. -failed | The number of shards OpenSearch failed to add the document to. -_seq_no | The sequence number assigned when the document was indexed. -_primary_term | The primary term assigned when the document was indexed. +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_index` | String | The name of the index to which the document was added. | +| `_id` | String | The document's unique identifier. | +| `_version` | Integer | The document's version number. Incremented each time the document is updated. | +| `result` | String | The result of the indexing operation. Possible values are `created` (a new document was created) and `updated` (an existing document was updated). | +| `_shards` | Object | Information about the replication process. | +| `_shards.total` | Integer | The number of shard copies (primary and replicas) on which the operation should be executed. | +| `_shards.successful` | Integer | The number of shard copies on which the operation succeeded. When the operation succeeds, this value is at least 1 (the primary shard). | +| `_shards.failed` | Integer | The number of shard copies on which the operation failed. If the operation succeeds, this value is 0. | +| `_seq_no` | Integer | The sequence number assigned to the document for this indexing operation. Sequence numbers are used to ensure that an older version of a document does not overwrite a newer version. See [Optimistic concurrency control](#optimistic-concurrency-control). | +| `_primary_term` | Integer | The primary term assigned to the document for this indexing operation. See [Optimistic concurrency control](#optimistic-concurrency-control). | + + +## Automatic index creation + +By default, if the specified index does not exist, the Index Document API automatically creates it and applies any configured index templates. The API also creates a dynamic mapping for new fields if no explicit mapping exists. + +Automatic index creation is controlled by the `action.auto_create_index` setting. By default, this setting is `true`, allowing any index to be created automatically. You can modify this setting to allow or block index creation based on specific patterns or disable automatic index creation entirely. For more information, see [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). + +## Optimistic concurrency control + +You can use the `if_seq_no` and `if_primary_term` parameters to perform conditional indexing based on the document's current sequence number and primary term. This ensures that the operation only succeeds if the document has not been modified since you last retrieved it. + +For example, to update a document only if it has sequence number 3 and primary term 1, include these parameters in your request: + +```json +PUT sample-index/_doc/1?if_seq_no=3&if_primary_term=1 +{ + "name": "Updated Example", + "price": 39.99 +} +``` + +If the sequence number or primary term does not match the current values, OpenSearch returns a version conflict error (HTTP 409), allowing you to retrieve the latest version and retry the operation. + +## Automatic ID generation + +When you use the POST method without specifying a document ID, OpenSearch automatically generates a unique ID for the document. The `op_type` is automatically set to `create`, ensuring a new document is always created. + +The following example indexes a document without specifying an ID, allowing OpenSearch to generate one automatically: + +```json +POST sample-index/_doc +{ + "user": "john_doe", + "post_date": "2024-01-15T10:30:00", + "message": "Hello, OpenSearch!" +} +``` + +The response includes the automatically generated ID: + +```json +{ + "_index": "sample-index", + "_id": "W0tpsmIBdwcYyG50zbta", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + } +} +``` + +The generated ID is a Base64-encoded UUID that ensures uniqueness across your cluster. + +## Routing + +By default, OpenSearch determines which shard stores a document by computing a hash of the document's ID. You can override this behavior by providing a custom `routing` parameter value. + +The following example routes the document to a shard based on the routing value `user123`: + +```json +POST sample-index/_doc?routing=user123 +{ + "user": "john_doe", + "message": "Hello, world!" +} +``` + +When you use custom routing during indexing, you must provide the same routing value when retrieving, updating, or deleting the document. Otherwise, OpenSearch cannot locate the document. + +## Distributed model + +The index operation is directed to the primary shard based on the document's routing value (either the document ID or a custom routing value). Once the primary shard completes the operation, OpenSearch distributes the update to all applicable replica shards in the replication group. + +This distributed approach ensures that all shard copies remain synchronized. The primary shard coordinates the replication process and waits for confirmation from the required number of active shards before acknowledging success to the client. + +## Wait for active shards + +To improve write operation resiliency, you can configure the Index Document API to wait for a certain number of active shard copies before proceeding. By default, the operation waits only for the primary shard to be active (`wait_for_active_shards=1`). + +You can set `wait_for_active_shards` to `all` or any positive integer up to the total number of shard copies (`number_of_replicas + 1`). If the required number of active shards is not available, the operation waits and retries until the shards become available or a timeout occurs. + +For example, consider a cluster with three nodes (A, B, and C) and an index with `number_of_replicas` set to 3, resulting in 4 shard copies (one primary and three replicas). By default, an indexing operation proceeds as long as the primary shard is available, even if nodes B and C are down and node A hosts the primary shard copy. + +If you set `wait_for_active_shards=3` on the request, the indexing operation requires 3 active shard copies before proceeding. This requirement can be met when all 3 nodes are running, with each node containing a copy of the shard. However, if you set `wait_for_active_shards=all` (or `4`), the indexing operation does not proceed because you need all 4 copies active, but only 3 nodes exist. The operation times out unless a new node joins the cluster to host the fourth shard copy. + +The following example requires at least 2 active shard copies (the primary and one replica) before proceeding: + +```json +PUT sample-index/_doc/1?wait_for_active_shards=2 +{ + "name": "Example", + "price": 29.99 +} +``` + +This setting reduces the risk of writing to an insufficient number of shard copies but does not eliminate it entirely. The check occurs before the write operation begins. Once the operation is underway, replication can still fail on some replicas while succeeding on the primary. The `_shards` section of the response indicates how many shard copies succeeded or failed. + +## Refresh + +The `refresh` parameter controls when indexed documents become visible to search operations. For most use cases, use the default value (`false`) for optimal performance. + +Valid options are: + +- `false` (default): The document becomes visible according to the index refresh interval (by default, 1 second). +- `true`: Forces an immediate refresh after indexing, making the document immediately searchable. Use sparingly, as frequent refreshes can significantly impact performance. +- `wait_for`: Waits for the next scheduled refresh before responding. More efficient than `true` for batch operations. + +## Timeout + +If the primary shard is unavailable when you submit an index request (for example, during recovery or relocation), the operation waits for up to 1 minute by default before failing. You can adjust this behavior using the `timeout` parameter: + +```json +PUT sample-index/_doc/1?timeout=5m +{ + "name": "Example", + "price": 29.99 +} +``` + +## Versioning + +Every indexed document has a version number. By default, OpenSearch uses internal versioning, starting at 1 and incrementing with each update or delete operation. + +For external versioning (such as maintaining version numbers in a separate database), set the `version_type` parameter to control how OpenSearch handles version conflicts. The following table lists the available version types. + +| Version type | Description | +| :--- | :--- | +| `internal` | Only indexes the document if the specified version is identical to the version of the stored document. This is the default version type. | +| `external` or `external_gt` | Only indexes the document if the specified version is strictly greater than the version of the stored document or if there is no existing document. The specified version is used as the new version and stored with the document. The supplied version must be a non-negative long integer. | +| `external_gte` | Only indexes the document if the specified version is greater than or equal to the version of the stored document. If there is no existing document, the operation succeeds. The specified version is used as the new version and stored with the document. The supplied version must be a non-negative long integer. | + +The `external_gte` version type is intended for special use cases and should be used with care. If used incorrectly, it can result in data loss. + +For example, to index a document using external versioning: + +```json +PUT sample-index/_doc/1?version=5&version_type=external +{ + "name": "Example", + "price": 29.99, + "description": "Updated from external system" +} +``` + +If the provided version does not meet the requirements of the specified version type, OpenSearch returns a version conflict error. Versioning is completely real time and is not affected by the near-real-time aspects of search operations. + +## No-op updates + +When you update a document using the Index Document API, OpenSearch always creates a new version of the document, even if the document content has not changed. This behavior can be inefficient if you frequently reindex documents with the same content. + +If you need to avoid creating unnecessary document versions, use the [Update Document API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-document/) with the `detect_noop` parameter set to `true`. The Update API fetches the existing document, compares it to the new content, and only creates a new version if the content has changed. + +The Index Document API does not support no-op detection because it does not fetch the old source for comparison. Whether no-op updates are problematic depends on several factors, including how frequently your data source sends updates that do not change the document and the query load on the shard receiving the updates. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/write/index`. diff --git a/_api-reference/document-apis/index.md b/_api-reference/document-apis/index.md index 9444efa5..f642185b 100644 --- a/_api-reference/document-apis/index.md +++ b/_api-reference/document-apis/index.md @@ -2,30 +2,133 @@ layout: default title: Document APIs has_children: true -nav_order: 25 +has_toc: false +nav_order: 50 redirect_from: - /opensearch/rest-api/document-apis/index/ + - /api-reference/document-apis/ --- # Document APIs **Introduced 1.0** {: .label .label-purple } -The document APIs allow you to handle documents relative to your index, such as adding, updating, and deleting documents. +Document APIs allow you to perform create, read, update, and delete (CRUD) operations on documents stored in your indexes. Use these APIs to manage individual documents or process multiple documents efficiently in batch operations. -Document APIs are separated into two categories: single document operations and multi-document operations. Multi-document operations offer performance advantages over submitting many individual requests, so whenever practical, we recommend that you use multi-document operations. +## Operation types + +OpenSearch document APIs are organized into the following categories based on the number of documents they process. + +### Single-document operations + +Single-document operations work with one document at a time. Use these APIs when you need to perform targeted operations on specific documents or when working with individual records: + +- Use the Index Document API to add new documents or replace existing documents with the same ID. +- Use the Get Document API to fetch documents by their unique ID. +- Use the Update Document API to change specific fields in an existing document without reindexing the entire document. +- Use the Delete Document API to remove documents from an index. + +### Multi-document operations + +Multi-document operations process multiple documents in a single API request, offering significant performance advantages over submitting individual requests. When working with large datasets or batch operations, always prefer multi-document APIs because they: + +- Reduce network overhead by combining multiple operations into one request. +- Improve throughput by allowing OpenSearch to optimize batch processing. +- Minimize the number of round trips between your application and the cluster. + +Use multi-document operations for data ingestion pipelines, bulk updates, batch deletions, and any scenario where you need to process multiple documents efficiently. + +### Term vector operations + +Term vector operations retrieve information about the terms in a specific document field, including term frequencies, positions, and offsets. Use these operations for text analysis, relevance scoring, and custom similarity calculations. + +## Important considerations + +**Single-index limitation**: All document APIs operate on a single index at a time. The `index` parameter accepts only one index name or an alias that points to a single index. You cannot target multiple indexes in a single document API request. For operations across multiple indexes, you must submit separate requests for each index. + +**Document routing**: OpenSearch uses a routing algorithm to determine which shard stores each document. By default, documents are routed based on their ID, but you can specify custom routing values to control shard placement. When retrieving, updating, or deleting documents that were indexed with custom routing, you must provide the same routing value. + +## Data replication model + +OpenSearch maintains multiple copies of your data across shards to ensure fault tolerance and high availability. This replication model is based on the primary-backup pattern, where one shard copy acts as the primary and other copies serve as replicas. + +### Write operations + +When you index, update, or delete a document, OpenSearch follows this process: + +1. **Routing**: The operation is routed to the appropriate primary shard based on the document ID or custom routing value. +2. **Primary processing**: The primary shard validates and executes the operation locally. +3. **Replication**: The primary shard forwards the operation to all active replica shards in parallel. +4. **Acknowledgment**: After all in-sync replicas confirm the operation, the primary shard acknowledges success to the client. + +This process ensures that all shard copies remain synchronized and that acknowledged writes are durable across multiple nodes. + +### Read operations + +Read operations can be served by any shard copy (primary or replica), which provides several benefits: + +- **Load distribution**: Read requests are distributed across multiple shard copies, improving throughput and response times. +- **High availability**: If one shard copy becomes unavailable, OpenSearch automatically routes requests to other copies. +- **Consistency**: All shard copies contain the same data (except for in-flight operations), ensuring consistent read results. + +By default, OpenSearch uses round-robin distribution to select which shard copy handles each read request. You can influence this selection using the `preference` parameter available in many document APIs. + +## Refresh behavior + +The Index, Update, Delete, and Bulk APIs support a `refresh` parameter that controls when changes become visible to search operations. Understanding refresh behavior is important for balancing data freshness with system performance. + +### Refresh parameter values + +The `refresh` parameter accepts the following values: + +- `false` (default): No refresh-related actions are taken. Changes become visible when the index is automatically refreshed based on the `index.refresh_interval` setting (default is 1 second). +- `true`: Immediately refreshes the relevant primary and replica shards after the operation completes, making changes visible to search immediately. Use this option sparingly because it can significantly impact performance. +- `wait_for`: Waits for the changes to become visible through a refresh before responding to the client. This option does not force an immediate refresh but waits for the next scheduled refresh or for another operation to trigger one. + +### Choosing the right refresh setting + +For most use cases, use the default `refresh=false` to achieve the best performance. Consider the following guidelines: + +- **Use `false` (default)** for high-throughput indexing where near-real-time visibility (within 1 second) is acceptable. +- **Use `wait_for`** when you need confirmation that changes are searchable but do not want to force an immediate refresh. This option is more efficient than `refresh=true` for batch operations. +- **Use `true` sparingly** only when you absolutely need immediate visibility and understand the performance implications. Frequent refreshes create inefficient index segments that require more resources to search and merge. + +Excessive use of `refresh=true` can significantly degrade cluster performance by creating many small segments and increasing merge overhead. + +## Optimistic concurrency control + +OpenSearch uses optimistic concurrency control to ensure that document updates do not overwrite newer changes with older data. This mechanism is essential in distributed systems where multiple operations may occur concurrently. + +Every operation that changes a document is assigned a sequence number (`_seq_no`) and a primary term (`_primary_term`) by the coordinating primary shard: + +- **Sequence number**: A strictly increasing number assigned to each operation. Newer operations always have higher sequence numbers than older ones. +- **Primary term**: Identifies the current primary shard assignment. This value changes when a new primary shard is elected after a failure. + +Together, `_seq_no` and `_primary_term` uniquely identify each change to a document, allowing OpenSearch to detect and prevent out-of-order updates. + +### Using sequence numbers for conditional updates + +You can use the `if_seq_no` and `if_primary_term` parameters with the Index, Update, and Delete APIs to ensure that operations only succeed if the document has not changed since you retrieved it. OpenSearch returns the current `_seq_no` and `_primary_term` values in Get API responses and search results (when requested). + +This approach prevents lost updates in scenarios where multiple clients or processes modify the same document concurrently. If the sequence number or primary term does not match the current values, OpenSearch returns a version conflict error, allowing your application to retry the operation with the latest document version. ## Single document operations -- Index -- Get -- Delete -- Update +- [Index document]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index-document/) +- [Get document]({{site.url}}{{site.baseurl}}/api-reference/document-apis/get-documents/) +- [Update document]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-document/) +- [Delete document]({{site.url}}{{site.baseurl}}/api-reference/document-apis/delete-document/) ## Multi-document operations -- Bulk -- Multi get -- Delete by query -- Update by query -- Reindex +- [Bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) +- [Streaming bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk-streaming/) +- [Multi-get documents]({{site.url}}{{site.baseurl}}/api-reference/document-apis/multi-get/) +- [Update by query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-by-query/) +- [Delete by query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/delete-by-query/) +- [Reindex documents]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) + +## Term vector operations + +- [Term vector]({{site.url}}{{site.baseurl}}/api-reference/document-apis/termvector/) +- [Multi term vectors]({{site.url}}{{site.baseurl}}/api-reference/document-apis/mtermvectors/) diff --git a/_api-reference/document-apis/mtermvectors.md b/_api-reference/document-apis/mtermvectors.md new file mode 100644 index 00000000..b8df0424 --- /dev/null +++ b/_api-reference/document-apis/mtermvectors.md @@ -0,0 +1,492 @@ +--- +layout: default +title: Multi term vectors +parent: Document APIs +nav_order: 80 +--- + +# Multi Term Vectors API +**Introduced 1.0** +{: .label .label-purple } + +The `_mtermvectors` API retrieves term vector information for multiple documents in one request. Term vectors provide detailed information about the terms (words) in a document, including term frequency, positions, offsets, and payloads. This can be useful for applications such as relevance scoring, highlighting, or similarity calculations. For more information, see [Term vector parameter]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/#term-vector-parameter). + + +## Endpoints +```json +GET /_mtermvectors +POST /_mtermvectors +GET /{index}/_mtermvectors +POST /{index}/_mtermvectors +``` + + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | The name of the index that contains the document. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `field_statistics` | Boolean | If `true`, the response includes the document count, sum of document frequencies, and sum of total term frequencies. _(Default: `true`)_ | +| `fields` | List or String | A comma-separated list or a wildcard expression specifying the fields to include in the statistics. Used as the default list unless a specific field list is provided in the `completion_fields` or `fielddata_fields` parameters. | +| `ids` | List | A comma-separated list of documents IDs. You must provide either the `docs` field in the request body or specify `ids` as a query parameter or in the request body. | +| `offsets` | Boolean | If `true`, the response includes term offsets. _(Default: `true`)_ | +| `payloads` | Boolean | If `true`, the response includes term payloads. _(Default: `true`)_ | +| `positions` | Boolean | If `true`, the response includes term positions. _(Default: `true`)_ | +| `preference` | String | Specifies the node or shard on which the operation should be performed. See [preference query parameter]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#the-preference-query-parameter) for a list of available options. By default the requests are routed randomly to available shard copies (primary or replica), with no guarantee of consistency across repeated queries. | +| `realtime` | Boolean | If `true`, the request is real time as opposed to near real time. _(Default: `true`)_ | +| `routing` | List or String | A custom value used to route operations to a specific shard. | +| `term_statistics` | Boolean | If `true`, the response includes term frequency and document frequency. _(Default: `false`)_ | +| `version` | Integer | If `true`, returns the document version as part of a hit. | +| `version_type` | String | The specific version type.
Valid values are:
- `external`: The version number must be greater than the current version.
- `external_gte`: The version number must be greater than or equal to the current version.
- `internal`: The version number is managed internally by OpenSearch. | + + + +## Request body fields + +The following table lists the fields that can be specified in the request body. + +| Field | Data type | Description | +| `docs` | Array | An array of document specifications. | +| `ids` | Array of strings | A list of document IDs to retrieve. Use only when all documents share the same index specified in the request path or query. | +| `fields` | Array of strings | A list of field names for which to return term vectors. | +| `offsets` | Boolean | If `true`, the response includes character offsets for each term. *(Default: `true`)* | +| `payloads` | Boolean | If `true`, the response includes payloads for each term. *(Default: `true`)* | +| `positions` | Boolean | If `true`, the response includes token positions. *(Default: `true`)* | +| `field_statistics` | Boolean | If `true`, the response includes statistics such as document count, sum of document frequencies, and sum of total term frequencies. *(Default: `true`)* | +| `term_statistics` | Boolean | If `true`, the response includes term frequency and document frequency. *(Default: `false`)* | +| `routing` | String | A custom routing value used to identify the shard. Required if custom routing was used during indexing. | +| `version` | Integer | The specific version of the document to retrieve. | +| `version_type` | String | The type of versioning to use. Valid values: `internal`, `external`, `external_gte`. | +| `filter` | Object | Filters tokens returned in the response (for example, by frequency or position). For supported fields, see [Filtering terms]({{site.url}}{{site.baseurl}}/api-reference/document-apis/mtermvectors/#filtering-terms). | +| `per_field_analyzer` | Object | Specifies a custom analyzer to use per field. Format: `{ "field_name": "analyzer_name" }`. | + +## Filtering terms + +The `filter` object in the request body allows you to filter the tokens to include in the term vector response. The `filter` object supports the following fields. + +| Field | Data type | Description | +| `max_num_terms` | Integer | The maximum number of terms to return. | +| `min_term_freq` | Integer | The minimum term frequency in the document required for a term to be included. | +| `max_term_freq` | Integer | The maximum term frequency in the document required for a term to be included. | +| `min_doc_freq` | Integer | The minimum document frequency across the index required for a term to be included. | +| `max_doc_freq` | Integer | The maximum document frequency across the index required for a term to be included. | +| `min_word_length` | Integer | The minimum length of the term to be included. | +| `max_word_length` | Integer | The maximum length of the term to be included. | + +## Example requests + + +Create an index with term vectors enabled: + +```json +PUT /my-index +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_offsets_payloads" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the first document: + + +{% capture step1_rest %} +POST /my-index/_doc/1 +{ + "text": "OpenSearch is a search engine." +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "my-index", + id = "1", + body = { + "text": "OpenSearch is a search engine." + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Index the second document: + + +{% capture step1_rest %} +POST /my-index/_doc/2 +{ + "text": "OpenSearch provides powerful features." +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "my-index", + id = "2", + body = { + "text": "OpenSearch provides powerful features." + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request + +Get term vectors for multiple documents: + + +{% capture step1_rest %} +POST /_mtermvectors +{ + "docs": [ + { + "_index": "my-index", + "_id": "1", + "fields": [ + "text" + ] + }, + { + "_index": "my-index", + "_id": "2", + "fields": [ + "text" + ] + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mtermvectors( + body = { + "docs": [ + { + "_index": "my-index", + "_id": "1", + "fields": [ + "text" + ] + }, + { + "_index": "my-index", + "_id": "2", + "fields": [ + "text" + ] + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Alternatively, you can specify both `ids` and `fields` as query parameters: + + +{% capture step1_rest %} +GET /my-index/_mtermvectors?ids=1,2&fields=text +{% endcapture %} + +{% capture step1_python %} + + +response = client.mtermvectors( + index = "my-index", + params = { "ids": "1,2", "fields": "text" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can also provide document IDs in the `ids` array instead of specifying `docs`: + + +{% capture step1_rest %} +GET /my-index/_mtermvectors?fields=text +{ + "ids": [ + "1", + "2" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mtermvectors( + index = "my-index", + params = { "fields": "text" }, + body = { + "ids": [ + "1", + "2" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The response contains term vector information for the two documents: + +```json +{ + "docs": [ + { + "_index": "my-index", + "_id": "1", + "_version": 1, + "found": true, + "took": 10, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 9, + "doc_count": 2, + "sum_ttf": 9 + }, + "terms": { + "a": { + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 14, + "end_offset": 15 + } + ] + }, + "engine": { + "term_freq": 1, + "tokens": [ + { + "position": 4, + "start_offset": 23, + "end_offset": 29 + } + ] + }, + "is": { + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 11, + "end_offset": 13 + } + ] + }, + "opensearch": { + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 10 + } + ] + }, + "search": { + "term_freq": 1, + "tokens": [ + { + "position": 3, + "start_offset": 16, + "end_offset": 22 + } + ] + } + } + } + } + }, + { + "_index": "my-index", + "_id": "2", + "_version": 1, + "found": true, + "took": 0, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 9, + "doc_count": 2, + "sum_ttf": 9 + }, + "terms": { + "features": { + "term_freq": 1, + "tokens": [ + { + "position": 3, + "start_offset": 29, + "end_offset": 37 + } + ] + }, + "opensearch": { + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 10 + } + ] + }, + "powerful": { + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 20, + "end_offset": 28 + } + ] + }, + "provides": { + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 11, + "end_offset": 19 + } + ] + } + } + } + } + } + ] +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| -------- | --------- | ----------- | +| `docs` | Array | A list of requested documents containing term vectors. | + +Each element of the `docs` array contains the following fields. + +| Field | Data type | Description | +| -------- | --------- | ----------- | +| `term_vectors` | Object | Contains term vector data for each field. | +| `term_vectors..field_statistics` | Object | Contains statistics about the field. | +| `term_vectors..field_statistics.doc_count` | Integer | The number of documents that contain at least one term in the specified field. | +| `term_vectors..field_statistics.sum_doc_freq` | Integer | The sum of document frequencies for all terms in the field. | +| `term_vectors..field_statistics.sum_ttf` | Integer | The sum of total term frequencies for all terms in the field. | +| `term_vectors..terms` | Object | A map of terms in the field, in which each term includes its frequency (`term_freq`) and associated token information. | +| `term_vectors..terms..tokens` | Array | An array of token objects for each term, including the token's `position` in the text and its character offsets (`start_offset` and `end_offset`). | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/mtv` and `indices:data/read/mtv*`. diff --git a/_api-reference/document-apis/multi-get.md b/_api-reference/document-apis/multi-get.md index 16e9ceeb..81820e06 100644 --- a/_api-reference/document-apis/multi-get.md +++ b/_api-reference/document-apis/multi-get.md @@ -1,142 +1,706 @@ --- layout: default -title: Multi-get document +title: Multi-get documents parent: Document APIs nav_order: 30 -redirect_from: +redirect_from: - /opensearch/rest-api/document-apis/multi-get/ --- -# Multi-get documents +# Multi-get Documents API **Introduced 1.0** {: .label .label-purple } -The multi-get operation allows you to run multiple GET operations in one request, so you can get back all documents that match your criteria. +The Multi-get Documents API retrieves multiple documents from one or more indexes in a single request. This operation is more efficient than executing multiple individual GET requests because it reduces network overhead and combines the operations into a single round-trip to the cluster. -## Path and HTTP methods +Use this API when you need to retrieve specific documents by their IDs and you know which documents you want to fetch. Common scenarios include: -``` -GET _mget -GET /_mget -POST _mget -POST /_mget -``` +- Retrieving a batch of user profiles, product details, or other entities based on a list of known IDs. +- Fetching related documents from different indexes in a single operation, such as getting both an order record and its associated customer information. +- Implementing efficient data access patterns where you need to retrieve multiple documents while controlling which fields are returned for each document. -## URL parameters +## Partial responses -All multi-get URL parameters are optional. - -Parameter | Type | Description -:--- | :--- | :--- | :--- -<index> | String | Name of the index to retrieve documents from. -preference | String | Specifies the nodes or shards OpenSearch should execute the multi-get operation on. Default is random. -realtime | Boolean | Specifies whether the operation should run in realtime. If false, the operation waits for the index to refresh to analyze the source to retrieve data, which makes the operation near-realtime. Default is `true`. -refresh | Boolean | If true, OpenSearch refreshes shards to make the multi-get operation available to search results. Valid options are `true`, `false`, and `wait_for`, which tells OpenSearch to wait for a refresh before executing the operation. Default is `false`. -routing | String | Value used to route the multi-get operation to a specific shard. -stored_fields | Boolean | Specifies whether OpenSearch should retrieve documents fields from the index instead of the document's `_source`. Default is `false`. -_source | String | Whether to include the `_source` field in the query response. Default is `true`. -_source_excludes | String | A comma-separated list of source fields to exclude in the query response. -_source_includes | String | A comma-separated list of source fields to include in the query response. - -## Request body - -If you don't specify an index in your request's URL, you must specify your target indexes and the relevant document IDs in the request body. Other fields are optional. - -Field | Type | Description | Required -:--- | :--- | :--- | :--- -docs | Array | The documents you want to retrieve data from. Can contain the attributes: `_id`, `_index`, `_routing`, `_source`, and `_stored_fields`. If you specify an index in the URL, you can omit this field and add IDs of the documents to retrieve. | Yes if an index is not specified in the URL -_id | String | The ID of the document. | Yes if `docs` is specified in the request body -_index | String | Name of the index. | Yes if an index is not specified in the URL -_routing | String | The value of the shard that has the document. | Yes if a routing value was used when indexing the document -_source | Object | Specifies whether to return the `_source` field from an index (boolean), whether to return specific fields (array), or whether to include or exclude certain fields. | No -_source.includes | Array | Specifies which fields to include in the query response. For example, `"_source": { "include": ["Title"] }` retrieves `Title` from the index. | No -_source.excludes | Array | Specifies which fields to exclude in the query response. For example, `"_source": { "exclude": ["Director"] }` excludes `Director` from the query response. | No -ids | Array | IDs of the documents to retrieve. Only allowed when an index is specified in the URL. | No - - -#### Example without specifying index in URL +The Multi-get Documents API prioritizes fast responses and will return partial results if one or more shards fail during the operation. If a specific document cannot be retrieved due to a shard failure or if the document does not exist, the response includes error details for that document while still returning successfully retrieved documents. This ensures that temporary failures or missing documents do not block the entire operation. + +## Endpoints ```json -GET _mget -{ - "docs": [ - { - "_index": "sample-index1", - "_id": "1" - }, - { - "_index": "sample-index2", - "_id": "1", - "_source": { - "include": ["Length"] - } - } - ] -} +GET /_mget +POST /_mget +GET /{index}/_mget +POST /{index}/_mget ``` -{% include copy-curl.html %} + -#### Example of specifying index in URL + +## Path parameters -```json -GET sample-index1/_mget +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | The name of the index to retrieve documents from when `ids` are specified, or when a document in the `docs` array does not specify an index. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `_source` | Boolean or List or String | Set to `true` or `false` to return the `_source` field or not, or a list of fields to return. | N/A | +| `_source_excludes` | List or String | A comma-separated list of source fields to exclude from the response. You can also use this parameter to exclude fields from the subset specified in `_source_includes` query parameter. | N/A | +| `_source_includes` | List or String | A comma-separated list of source fields to include in the response. If this parameter is specified, only these source fields are returned. You can exclude fields from this subset using the `_source_excludes` query parameter. If the `_source` parameter is `false`, this parameter is ignored. | N/A | +| `preference` | String | Specifies the node or shard the operation should be performed on. Random by default. | `random` | +| `realtime` | Boolean | If `true`, the request is real time as opposed to near real time. | N/A | +| `refresh` | Boolean or String | If `true`, the request refreshes relevant shards before retrieving documents.
Valid values are:
- `false`: Do not refresh the affected shards.
- `true`: Refresh the affected shards immediately.
- `wait_for`: Wait for the changes to become visible before replying. | N/A | +| `routing` | List or String | A custom value used to route operations to a specific shard. | N/A | +| `stored_fields` | List or String | If `true`, retrieves the document fields stored in the index rather than the document `_source`. | N/A | + + + +## Request body fields + +The request body specifies which documents to retrieve. If you don't specify an index in the request path, you must include the index name for each document in the request body. The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`docs` | Array of objects | The documents to retrieve. Required if the `ids` field is not specified. Each object can include the following fields: `_index`, `_id`, `routing`, `_source`, and `stored_fields`. +`docs._index` | String | The name of the index containing the document. Required if an index is not specified in the request path. +`docs._id` | String | The document ID. Required. +`docs.routing` | String | The routing value used to route the operation to a specific shard. Required if a custom routing value was used when indexing the document. +`docs._source` | Boolean, Array, or Object | Controls which source fields are returned. If `false`, the `_source` field is excluded from the response. If an array, specifies the fields to include. If an object, can contain `includes` and `excludes` arrays to control field inclusion and exclusion. Default is `true`. +`docs._source.includes` | Array of strings | The source fields to include in the response. For example, `["title", "author"]` returns only the `title` and `author` fields. +`docs._source.excludes` | Array of strings | The source fields to exclude from the response. For example, `["internal_notes"]` excludes the `internal_notes` field. +`docs.stored_fields` | Array of strings | The stored fields to retrieve instead of the `_source` field. Only fields explicitly stored in the index mapping can be retrieved. If specified, the `_source` field is not returned unless explicitly requested. +`ids` | Array of strings | A simplified way to specify document IDs when all documents are in the same index. Can only be used when an index is specified in the request path. If provided, the `docs` field is not required. + +## Example: Retrieving documents from multiple indexes + +The following example retrieves one document from the `books` index and one document from the `articles` index: + + +{% capture step1_rest %} +GET /_mget +{ + "docs": [ + { + "_index": "books", + "_id": "1" + }, + { + "_index": "articles", + "_id": "1" + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mget( + body = { + "docs": [ + { + "_index": "books", + "_id": "1" + }, + { + "_index": "articles", + "_id": "1" + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Using the IDs array + +When retrieving multiple documents from the same index, you can simplify the request by specifying the index in the path and using the `ids` array. The following example retrieves three documents from the `books` index: + + +{% capture step1_rest %} +GET /books/_mget +{ + "ids": [ + "1", + "2", + "3" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mget( + index = "books", + body = { + "ids": [ + "1", + "2", + "3" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Filtering source fields + +You can control which fields are returned for each document by using the `_source` parameter. The following example demonstrates different source filtering options: excluding the source entirely for the first document, returning specific fields for the second document, and using includes to return selected fields for the third document: + + +{% capture step1_rest %} +GET /_mget +{ + "docs": [ + { + "_index": "books", + "_id": "1", + "_source": false + }, + { + "_index": "books", + "_id": "2", + "_source": [ + "title", + "author" + ] + }, + { + "_index": "books", + "_id": "3", + "_source": { + "includes": [ + "title", + "year" + ] + } + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mget( + body = { + "docs": [ + { + "_index": "books", + "_id": "1", + "_source": false + }, + { + "_index": "books", + "_id": "2", + "_source": [ + "title", + "author" + ] + }, + { + "_index": "books", + "_id": "3", + "_source": { + "includes": [ + "title", + "year" + ] + } + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Retrieving stored fields + +If your index mapping includes stored fields, you can retrieve them instead of the document source. The following example retrieves different stored fields from two user documents: + + +{% capture step1_rest %} +GET /_mget +{ + "docs": [ + { + "_index": "users", + "_id": "1", + "stored_fields": [ + "name", + "location" + ] + }, + { + "_index": "users", + "_id": "2", + "stored_fields": [ + "email", + "joined_date" + ] + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mget( + body = { + "docs": [ + { + "_index": "users", + "_id": "1", + "stored_fields": [ + "name", + "location" + ] + }, + { + "_index": "users", + "_id": "2", + "stored_fields": [ + "email", + "joined_date" + ] + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Specifying routing values + +If you used custom routing when indexing documents, you must provide the routing value when retrieving those documents. The following example retrieves two order documents using their routing values: the first document uses the routing value from the query parameter, and the second document specifies its own routing value: + + +{% capture step1_rest %} +GET /_mget?routing=user123 +{ + "docs": [ + { + "_index": "orders", + "_id": "1" + }, + { + "_index": "orders", + "_id": "2", + "routing": "user456" + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.mget( + params = { "routing": "user123" }, + body = { + "docs": [ + { + "_index": "orders", + "_id": "1" + }, + { + "_index": "orders", + "_id": "2", + "routing": "user456" + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The Multi-get Documents API returns a `docs` array containing the retrieved documents in the same order as they were requested. Each document includes its metadata and source data, or an error if the document could not be retrieved. + +
+ + Response for retrieving documents from multiple indexes + + {: .text-delta} -#### Example Response ```json { "docs": [ { - "_index": "sample-index1", + "_index": "books", "_id": "1", - "_version": 4, - "_seq_no": 5, - "_primary_term": 19, + "_version": 2, + "_seq_no": 2, + "_primary_term": 3, "found": true, "_source": { - "Title": "Batman Begins", - "Director": "Christopher Nolan" + "title": "The Great Gatsby", + "author": "F. Scott Fitzgerald", + "year": 1925, + "genre": "Fiction", + "pages": 180 } }, { - "_index": "sample-index2", + "_index": "articles", "_id": "1", "_version": 1, - "_seq_no": 6, - "_primary_term": 19, + "_seq_no": 0, + "_primary_term": 1, "found": true, "_source": { - "Title": "The Dark Knight", - "Director": "Christopher Nolan" + "title": "Introduction to OpenSearch", + "author": "Jane Smith", + "published": "2024-01-15", + "category": "Technology", + "views": 1500 } } ] } ``` +
+ +
+ + Response for using the IDs array + + {: .text-delta} + +```json +{ + "docs": [ + { + "_index": "books", + "_id": "1", + "_version": 2, + "_seq_no": 2, + "_primary_term": 3, + "found": true, + "_source": { + "title": "The Great Gatsby", + "author": "F. Scott Fitzgerald", + "year": 1925, + "genre": "Fiction", + "pages": 180 + } + }, + { + "_index": "books", + "_id": "2", + "_version": 2, + "_seq_no": 3, + "_primary_term": 3, + "found": true, + "_source": { + "title": "To Kill a Mockingbird", + "author": "Harper Lee", + "year": 1960, + "genre": "Fiction", + "pages": 324 + } + }, + { + "_index": "books", + "_id": "3", + "_version": 1, + "_seq_no": 4, + "_primary_term": 3, + "found": true, + "_source": { + "title": "1984", + "author": "George Orwell", + "year": 1949, + "genre": "Dystopian", + "pages": 328 + } + } + ] +} +``` +
+ +
+ + Response for filtering source fields + + {: .text-delta} + +```json +{ + "docs": [ + { + "_index": "books", + "_id": "1", + "_version": 2, + "_seq_no": 2, + "_primary_term": 3, + "found": true + }, + { + "_index": "books", + "_id": "2", + "_version": 2, + "_seq_no": 3, + "_primary_term": 3, + "found": true, + "_source": { + "author": "Harper Lee", + "title": "To Kill a Mockingbird" + } + }, + { + "_index": "books", + "_id": "3", + "_version": 1, + "_seq_no": 4, + "_primary_term": 3, + "found": true, + "_source": { + "year": 1949, + "title": "1984" + } + } + ] +} +``` +
+ +
+ + Response for retrieving stored fields + + {: .text-delta} + +```json +{ + "docs": [ + { + "_index": "users", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "fields": { + "name": [ + "Alice Johnson" + ], + "location": [ + "San Francisco" + ] + } + }, + { + "_index": "users", + "_id": "2", + "_version": 1, + "_seq_no": 1, + "_primary_term": 1, + "found": true, + "fields": { + "joined_date": [ + "2021-06-20T00:00:00.000Z" + ], + "email": [ + "bob@example.com" + ] + } + } + ] +} +``` +
+ +
+ + Response for specifying routing values + + {: .text-delta} + +```json +{ + "docs": [ + { + "_index": "orders", + "_id": "1", + "_version": 2, + "_seq_no": 3, + "_primary_term": 14, + "_routing": "user123", + "found": true, + "_source": { + "order_id": "ORD-001", + "user_id": "user123", + "product": "Laptop", + "amount": 1299.99 + } + }, + { + "_index": "orders", + "_id": "2", + "_version": 2, + "_seq_no": 4, + "_primary_term": 14, + "_routing": "user456", + "found": true, + "_source": { + "order_id": "ORD-002", + "user_id": "user456", + "product": "Smartphone", + "amount": 899.99 + } + } + ] +} +``` +
## Response body fields -Field | Description -:--- | :--- -_index | The name of the index. -_id | The document's ID. -_version | The document's version number. Updated whenever the document changes. -_seq_no | The sequence number assigned when the document is indexed. -primary_term | The primary term assigned when the document is indexed. -found | Whether the document exists. -_routing | The shard that the document is routed to. If the document is not routed to a particular shard, this field is omitted. -_source | Contains the document's data if `found` is true. If `_source` is set to false or `stored_fields` is set to true in the URL parameters, this field is omitted. -_fields | Contains the document's data that's stored in the index. Only returned if both `stored_fields` and `found` are true. +The response contains a `docs` array with one element for each requested document, returned in the same order as the request. The following table lists the response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`docs` | Array of objects | The retrieved documents. Each object represents one document and includes the fields described in this table. +`_index` | String | The name of the index containing the document. +`_id` | String | The document ID. +`_version` | Integer | The document version number. This number is incremented each time the document is updated. +`_seq_no` | Integer | The sequence number assigned to the document when it was indexed. Used for optimistic concurrency control. +`_primary_term` | Integer | The primary term assigned to the document when it was indexed. Used with `_seq_no` for optimistic concurrency control. +`found` | Boolean | Whether the document was found. If `false`, the document does not exist, and the `_source` field is not included. +`_source` | Object | The document's original JSON content. Omitted if `found` is `false`, if `_source` was set to `false` in the request, or if `stored_fields` was specified. +`fields` | Object | The stored fields for the document. Only included when `stored_fields` is specified in the request and `found` is `true`. Each field value is returned as an array. +`_routing` | String | The routing value used to direct the document to a specific shard. Only included if a custom routing value was used. +`error` | Object | Error information if the document could not be retrieved due to a failure. Contains details about the error type and reason. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/mget` and `indices:data/read/mget*`. diff --git a/_api-reference/document-apis/reindex.md b/_api-reference/document-apis/reindex.md index 766f5b28..c0333b8a 100644 --- a/_api-reference/document-apis/reindex.md +++ b/_api-reference/document-apis/reindex.md @@ -1,6 +1,6 @@ --- layout: default -title: Reindex document +title: Reindex documents parent: Document APIs nav_order: 60 redirect_from: @@ -8,16 +8,118 @@ redirect_from: - /opensearch/rest-api/document-apis/reindex/ --- -# Reindex document +# Reindex Documents API **Introduced 1.0** {: .label .label-purple} -The reindex document API operation lets you copy all or a subset of your data from a source index into a destination index. +The reindex document API operation copies all documents or a subset of documents from a source index(es), data stream, or alias into a destination index, data stream, or alias. The source and destination must be different. -## Example +The reindex operation takes a snapshot of the source index and copies documents to the destination index. For each document, copying is performed by extracting the document source ([`_source` field]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/source/)) and indexing it into the destination. + +OpenSearch natively supports cross-cluster reindexing, allowing you to copy data between different OpenSearch clusters. For more information, see [Cross-cluster reindexing](#cross-cluster-reindexing). + +Before using the Reindex API, note the following requirements and limitations: + +- The reindex operation requires the `_source` field to be enabled for all documents in the source index. If `_source` is disabled, the operation will fail. +- You must create and configure the destination index before running the reindex operation. OpenSearch does not automatically copy settings, mappings, or shard configurations from the source index. +- Configure the appropriate number of shards, replicas, and field mappings for the destination index based on your requirements. +- For large reindex operations, consider temporarily disabling replicas on the destination index by setting `number_of_replicas` to `0` and then re-enabling them after completion. + +Reindexing large datasets can be resource intensive and may impact cluster performance. Monitor cluster health during reindex operations and consider using throttling parameters for production environments. For more information, see [Performance optimization](#performance-optimization). +{: .warning } + +For a practical, tutorial-style guide to reindexing with common use cases and examples, see [Reindex data]({{site.url}}{{site.baseurl}}/im-plugin/reindex-data/). +{: .tip } + +Unlike update operations that modify documents within the same index, reindex operations work on different sources and destinations. Thus, version conflicts are unlikely. The `version_type` parameter controls how OpenSearch handles document versions during reindexing. By default, version conflicts stop the reindex process. To continue reindexing when conflicts occur, set the `conflicts` parameter to `proceed`. The response will include a count of version conflicts encountered. Other error types are unaffected by the `conflicts` parameter. + +By default, documents with the same ID are overwritten. The `op_type` parameter determines whether existing documents can be replaced or if only new documents are allowed, in which case attempting to index a document with an existing ID results in an error. For more information, see [Request body fields](#request-body-fields). + +## Endpoints ```json POST /_reindex +``` + +## Query parameters + +The following table lists the available query parameters. All parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`refresh` | Boolean | If `true`, OpenSearch refreshes shards to make the reindex operation available to search results. Valid values are `true`, `false`, and `wait_for`, which specifies to wait for a refresh before executing the operation. Default is `false`. +`timeout` | Time unit | How long to wait for a response from the cluster. Default is `30s`. +`wait_for_active_shards` | String | The number of active shards that must be available before OpenSearch processes the reindex request. Default is `1` (only the primary shard). Set to `all` or a positive integer. Values greater than `1` require replicas. For example, if you specify a value of `3`, the index must have two replicas distributed across two additional nodes for the operation to succeed. +`wait_for_completion` | Boolean | If `false`, OpenSearch runs the reindex operation asynchronously without waiting for it to complete. The request returns immediately, and the task continues in the background. You can monitor its progress using the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/). Default is `true`, which means the operation runs synchronously. See [Asynchronous operations](#asynchronous-operations). +`requests_per_second` | Integer | Specifies the request's throttling in sub-requests per second. Default is `-1`, which means no throttling. See [Controlling reindex rate](#controlling-the-reindex-rate) and [Throttling and rate control](#throttling-and-rate-control). +`require_alias` | Boolean | Whether the destination index must be an alias. Default is `false`. +`scroll` | Time unit | How long to keep the search context open. Default is `5m`. +`slices` | Integer | The number of slices for automatic slicing. OpenSearch automatically divides the reindex operation into this number of parallel subtasks. Default is `1` (no slicing). Set this parameter to `auto` for OpenSearch to automatically determine the optimal number of slices. See [Using slicing for parallel processing](#using-slicing-for-parallel-processing). +`max_docs` | Integer | The maximum number of documents that the reindex operation should process. Default is all documents. See [Extracting sample data](#extracting-sample-data). + +## Request body fields + +The following table lists all request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`source` | Object | Required | The source to copy data from. See [The `source` object](#the-source-object). +`dest` | Object | Required | The destination to copy data to. See [The `dest` object](#the-dest-object). +`conflicts` | String | Optional | Indicates to OpenSearch what should happen if the reindex operation encounters a version conflict. Valid values are `abort` and `proceed`. Default is `abort`. +`script` | Object | Optional | A script that OpenSearch uses to apply transformations to the data during the reindex operation. See [The `script` object](#the-script-object). + +### The `source` object + +The `source` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`index` | String | Required | The name of the index, data stream, or alias to copy from. You can specify multiple source indexes as a comma-separated list. +`query` | Object | Optional | The search query to use for the reindex operation. See [Filtering documents by query](#filtering-documents-by-query). +`remote` | Object | Optional | Information about a remote OpenSearch cluster to copy data from. See [Cross-cluster reindexing](#cross-cluster-reindexing). +`remote.host` | String | Required when `remote` is specified | The URL for the remote OpenSearch cluster that you want to index from. +`remote.username` | String | Optional | The username to use for authentication with the remote host. +`remote.password` | String | Optional | The password to use for authentication with the remote host. +`remote.socket_timeout` | String | Optional | The remote socket read timeout. Default is `30s`. +`remote.connect_timeout` | String | Optional | The remote connection timeout. Default is `30s`. +`size` | Integer | Optional | The number of documents to index per batch. Use this when indexing from a remote source to ensure that each batch fits within the on-heap buffer, which has a default maximum size of 100 MB. +`slice` | Object | Optional | The configuration for manual slicing. Must be an object with `id` (slice ID) and `max` (total number of slices) properties to manually specify which slice of the data to process. This enables parallel processing by running multiple reindex operations, each handling a different slice. See [Using slicing for parallel processing](#using-slicing-for-parallel-processing). +`_source` | Boolean or Array | Optional | Whether to reindex source fields. Specify a list of fields to reindex or `true` to reindex all fields. Default is `true`. See [Selecting specific fields](#selecting-specific-fields). +`sort` | Array | Optional | _Deprecated_. A comma-separated list of `:` pairs used to sort documents before reindexing. If used with `max_docs` to control which documents are reindexed, consider [filtering documents by query](#filtering-documents-by-query) to find the desired subset of data. + +### The `dest` object + +The `dest` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`index` | String | Required | The name of the index, data stream, or alias to copy to. +`version_type` | String | Optional | Controls how OpenSearch handles document versions during reindexing:
• `internal` (default): Ignores versions and overwrites any documents in the destination that have the same ID as documents from the source.
• `external`: Preserves the version from the source, creates any missing documents, and updates documents in the destination only if they have an older version than the source.
• `external_gt`: Similar to `external` but only updates documents if the source version is greater than the destination version.
• `external_gte`: Similar to `external` but updates documents if the source version is greater than or equal to the destination version. +`op_type` | String | Optional | Determines how documents are processed during reindexing:
• `index` (default): Creates new documents and updates existing ones.
• `create`: Only creates documents that don't exist in the destination. Documents with existing IDs cause version conflicts. Required when reindexing to data streams (which are append-only). +`pipeline` | String | Optional | The ingest pipeline to use during reindexing. See [Transforming documents using ingest pipelines](#transforming-documents-using-ingest-pipelines). +`routing` | String | Optional | Controls how document routing is handled during reindexing. Valid values are `keep` (preserves existing routing, default), `discard` (removes routing), or `=` (sets routing to a specific value). See [Routing](#routing). + +### The `script` object + +The `script` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`source` | String | Required | The script source code as a string. +`lang` | String | Optional | The scripting language. Valid values are `painless`, `expression`, `mustache`, and `java`. Default is `painless`. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +## How reindexing works + +The reindex operation takes a snapshot of the source index and copies documents to the destination index. This approach means that version conflicts are unlikely to occur, unlike update operations that work on the same index. + +By default, version conflicts stop the reindex process. To continue reindexing when conflicts occur, set the `conflicts` parameter to `proceed`. The response will include a count of version conflicts encountered. Other error types are unaffected by the `conflicts` parameter. + +## Example request + + +{% capture step1_rest %} POST /_reindex -``` +{ + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-destination-index" + } +} +{% endcapture %} -## URL parameters +{% capture step1_python %} -All URL parameters are optional. -Parameter | Type | Description -:--- | :--- | :--- -refresh | Boolean | If true, OpenSearch refreshes shards to make the reindex operation available to search results. Valid options are `true`, `false`, and `wait_for`, which tells OpenSearch to wait for a refresh before executing the operation. Default is `false`. -timeout | Time | How long to wait for a response from the cluster. Default is `30s`. -wait_for_active_shards | String | The number of active shards that must be available before OpenSearch processes the reindex request. Default is 1 (only the primary shard). Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the operation to succeed. -wait_for_completion | Boolean | Waits for the matching tasks to complete. Default is `false`. -requests_per_second | Integer | Specifies the request’s throttling in sub-requests per second. Default is -1, which means no throttling. -require_alias | Boolean | Whether the destination index must be an index alias. Default is false. -scroll | Time | How long to keep the search context open. Default is `5m`. -slices | Integer | Number of sub-tasks OpenSearch should divide this task into. Default is 1, which means OpenSearch should not divide this task. Setting this parameter to `auto` indicates to OpenSearch that it should automatically decide how many slices to split the task into. -max_docs | Integer | How many documents the update by query operation should process at most. Default is all documents. +response = client.reindex( + body = { + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-destination-index" + } + } +) -## Request body +{% endcapture %} -Your request body must contain the names of the source index and destination index. All other fields are optional. +{% include code-block.html + rest=step1_rest + python=step1_python %} + -Field | Description -:--- | :--- -conflicts | Indicates to OpenSearch what should happen if the delete by query operation runs into a version conflict. Valid options are `abort` and `proceed`. Default is abort. -source | Information about the source index to include. Valid fields are `index`, `max_docs`, `query`, `remote`, `size`, `slice`, and `_source`. -index | The name of the source index to copy data from. -max_docs | The maximum number of documents to reindex. -query | The search query to use for the reindex operation. -remote | Information about a remote OpenSearch cluster to copy data from. Valid fields are `host`, `username`, `password`, `socket_timeout`, and `connect_timeout`. -host | Host URL of the OpenSearch cluster to copy data from. -username | Username to authenticate with the remote cluster. -password | Password to authenticate with the remote cluster. -socket_timeout | The wait time for socket reads. Default is 30s. -connect_timeout | The wait time for remote connection timeouts. Default is 30s. -size | The number of documents to reindex. -slice | Whether to manually or automatically slice the reindex operation so it executes in parallel. Setting this field to `auto` allows OpenSearch to control the number of slices to use, which is one slice per shard, up to a maximum of 20. If there are multiple sources, the number of slices used are based on the index or backing index with the smallest number of shards. -_source | Whether to reindex source fields. Specify a list of fields to reindex or true to reindex all fields. Default is true. -id | The ID to associate with manual slicing. -max | Maximum number of slices. -dest | Information about the destination index. Valid values are `index`, `version_type`, and `op_type`. -index | Name of the destination index. -version_type | The indexing operation's version type. Valid values are `internal`, `external`, `external_gt` (retrieve the document if the specified version number is greater than the document’s current version), and `external_gte` (retrieve the document if the specified version number is greater or equal to than the document’s current version). -op_type | Whether to copy over documents that are missing in the destination index. Valid values are `create` (ignore documents with the same ID from the source index) and `index` (copy everything from the source index). -script | A script that OpenSearch uses to apply transformations to the data during the reindex operation. -source | The actual script that OpenSearch runs. -lang | The scripting language. Valid options are `painless`, `expression`, `mustache`, and `java`. +## Example response -## Response ```json { "took": 28829, @@ -106,19 +188,1172 @@ lang | The scripting language. Valid options are `painless`, `expression`, `must ## Response body fields -Field | Description -:--- | :--- -took | How long the operation took in milliseconds. -timed_out | Whether the operation timed out. -total | The total number of documents processed. -updated | The number of documents updated in the destination index. -created | The number of documents created in the destination index. -deleted | The number of documents deleted. -batches | Number of scroll responses. -version_conflicts | Number of version conflicts. -noops | How many documents OpenSearch ignored during the operation. -retries | Number of bulk and search retry requests. -throttled_millis | Number of throttled milliseconds during the request. -requests_per_second | Number of requests executed per second during the operation. -throttled_until_millis | The amount of time until OpenSearch executes the next throttled request. -failures | Any failures that occurred during the operation. +The following table lists all response body fields and provides a detailed description for each. + +Field | Data type | Description +:--- | :--- | :--- +`took` | Integer | The total time in milliseconds required to complete the entire reindex operation, including all batch processing and network overhead. +`timed_out` | Boolean | Indicates whether any part of the reindex operation exceeded the configured timeout. If `true`, the operation may have been partially completed. +`total` | Integer | The total number of documents successfully processed during the reindex operation. This includes documents that were created, updated, or resulted in no-op operations. +`updated` | Integer | The number of documents that were updated in the destination index because a document with the same ID already existed. +`created` | Integer | The number of new documents created in the destination index. These are documents that didn't previously exist in the destination. +`deleted` | Integer | The number of documents deleted from the destination index. This occurs when scripts set `ctx.op = "delete"`. +`batches` | Integer | The number of scroll batches processed during the reindex operation. Each batch contains multiple documents as configured by the `size` parameter. +`version_conflicts` | Integer | The number of version conflicts encountered. Version conflicts occur when the destination document has a higher version than the source document (when using external versioning). +`noops` | Integer | The number of documents that were skipped during processing. This happens when scripts set `ctx.op = "noop"` or when no changes are needed. +`retries` | Object | The retry statistics object containing retry counts for different operation types. Retries occur automatically when temporary failures are encountered. +`retries.bulk` | Integer | The number of bulk operation retries attempted during the reindex operation. +`retries.search` | Integer | The number of search operation retries attempted during the reindex operation. +`throttled_millis` | Integer | The total time in milliseconds that the operation was throttled to comply with the `requests_per_second` setting. Higher values indicate more throttling was applied. +`requests_per_second` | Float | The actual rate of requests executed per second during the operation. This may differ from the requested rate due to throttling adjustments and system performance. +`throttled_until_millis` | Integer | For asynchronous operations, this indicates the next time (in milliseconds since epoch) that throttled requests will be executed. Always `0` for completed operations. +`failures` | Array | An array of failure objects describing any unrecoverable errors encountered during the operation. Each failure includes details about the error type, cause, and affected document. + +## Selective reindexing + +The following examples demonstrate different ways to selectively copy data during reindexing, including filtering documents, selecting specific fields, and extracting sample datasets. + +### Filtering documents by query + +Copy only documents that match specific criteria: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "orders", + "query": { + "range": { + "order_date": { + "gte": "2024-01-01", + "lte": "2024-12-31" + } + } + } + }, + "dest": { + "index": "orders-2024" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "orders", + "query": { + "range": { + "order_date": { + "gte": "2024-01-01", + "lte": "2024-12-31" + } + } + } + }, + "dest": { + "index": "orders-2024" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Selecting specific fields + +Copy only specific fields from source documents: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "customer-data", + "_source": [ + "customer_id", + "name", + "email", + "created_date" + ] + }, + "dest": { + "index": "customers-minimal" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "customer-data", + "_source": [ + "customer_id", + "name", + "email", + "created_date" + ] + }, + "dest": { + "index": "customers-minimal" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Extracting sample data + +Create a smaller dataset for testing: + + +{% capture step1_rest %} +POST /_reindex +{ + "max_docs": 1000, + "source": { + "index": "production-logs", + "query": { + "function_score": { + "random_score": { + "seed": 42 + }, + "min_score": 0.8 + } + } + }, + "dest": { + "index": "test-sample" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "max_docs": 1000, + "source": { + "index": "production-logs", + "query": { + "function_score": { + "random_score": { + "seed": 42 + }, + "min_score": 0.8 + } + } + }, + "dest": { + "index": "test-sample" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Routing + +By default, if the reindex operation encounters a document with routing, the routing is preserved unless changed by a script. You can control routing behavior using the `routing` parameter in the `dest` section: + +- `keep`: Preserves the routing from the source document (default) +- `discard`: Removes routing from reindexed documents +- `=`: Sets routing to the specified value for all reindexed documents + +The following request sets a custom routing value for all reindexed documents: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "source" + }, + "dest": { + "index": "dest", + "routing": "=company_a" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "source" + }, + "dest": { + "index": "dest", + "routing": "=company_a" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Transforming documents using ingest pipelines + +To transform data, process documents through an ingest pipeline during reindexing. First create the pipeline, then reference it in the reindex operation: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "raw-data" + }, + "dest": { + "index": "processed-data", + "pipeline": "data-enrichment" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "raw-data" + }, + "dest": { + "index": "processed-data", + "pipeline": "data-enrichment" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Before running the reindex operation, create the ingest pipeline. This example creates a pipeline that adds a `processed_at` timestamp and converts the `status` field to uppercase: + +```json +PUT /_ingest/pipeline/data-enrichment +{ + "description": "Enriches documents during reindexing", + "processors": [ + { + "set": { + "field": "processed_at", + "value": "{{_ingest.timestamp}}" + } + }, + { + "uppercase": { + "field": "status" + } + } + ] +} +``` + +### Controlling the reindex rate + +Control the reindex rate to minimize cluster impact: + + +{% capture step1_rest %} +POST /_reindex?requests_per_second=500 +{ + "source": { + "index": "production-data" + }, + "dest": { + "index": "production-backup" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + params = { "requests_per_second": "500" }, + body = { + "source": { + "index": "production-data" + }, + "dest": { + "index": "production-backup" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Script operations + +You can transform documents during the reindex process using scripts. You can modify document content, metadata, and control which documents are processed. + +Scripts can modify the following document metadata fields: + +- `ctx._id`: Change the document ID. +- `ctx._index`: Route documents to different destination indexes. +- `ctx._version`: Control document versioning. +- `ctx._routing`: Set custom routing values. + +Set the `ctx.op` field to control what happens to each document: + +- `ctx.op = "index"`: Index the document normally (default behavior). +- `ctx.op = "create"`: Only create the document if it doesn't exist. +- `ctx.op = "noop"`: Skip the document (useful for conditional processing). +- `ctx.op = "delete"`: Delete the document from the destination index. + +### Transforming field values + +You can add or modify fields in documents during reindexing. For example, this script adds a timestamp and migration status to each document: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "source-data" + }, + "dest": { + "index": "migrated-data" + }, + "script": { + "source": "ctx._source.timestamp = System.currentTimeMillis(); ctx._source.status = 'migrated'" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "source-data" + }, + "dest": { + "index": "migrated-data" + }, + "script": { + "source": "ctx._source.timestamp = System.currentTimeMillis(); ctx._source.status = 'migrated'" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Renaming fields + +You can rename fields during reindexing using scripts. This script renames `client_name` to `customer_name` and `total_amount` to `order_total` during the reindex operation: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "legacy-data" + }, + "dest": { + "index": "updated-data" + }, + "script": { + "source": "ctx._source.customer_name = ctx._source.remove('client_name'); ctx._source.order_total = ctx._source.remove('total_amount');" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "legacy-data" + }, + "dest": { + "index": "updated-data" + }, + "script": { + "source": "ctx._source.customer_name = ctx._source.remove('client_name'); ctx._source.order_total = ctx._source.remove('total_amount');" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Processing documents conditionally + +You can skip documents based on conditions or apply different transformations. For example, this script skips archived documents and adds a migration timestamp to all others: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "mixed-data" + }, + "dest": { + "index": "processed-data" + }, + "script": { + "source": "if (ctx._source.category == 'archived') { ctx.op = 'noop' } else { ctx._source.migrated_at = new Date() }" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "mixed-data" + }, + "dest": { + "index": "processed-data" + }, + "script": { + "source": "if (ctx._source.category == 'archived') { ctx.op = 'noop' } else { ctx._source.migrated_at = new Date() }" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Routing documents to different indexes + +You can dynamically route documents to different destination indexes based on document content. For example, this script routes products to category-specific indexes: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "product-catalog" + }, + "dest": { + "index": "placeholder-will-be-overridden" + }, + "script": { + "source": "ctx._index = 'products-' + ctx._source.category.toLowerCase()" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "product-catalog" + }, + "dest": { + "index": "placeholder-will-be-overridden" + }, + "script": { + "source": "ctx._index = 'products-' + ctx._source.category.toLowerCase()" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Consolidating time-based indexes + +Use the following script to consolidate multiple time-based indexes into a single index: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": [ + "logs-2024-01-*", + "logs-2024-02-*", + "logs-2024-03-*" + ] + }, + "dest": { + "index": "logs-2024-q1" + }, + "script": { + "source": "ctx._source.quarter = 'Q1-2024'; ctx._source.consolidated_date = System.currentTimeMillis();" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": [ + "logs-2024-01-*", + "logs-2024-02-*", + "logs-2024-03-*" + ] + }, + "dest": { + "index": "logs-2024-q1" + }, + "script": { + "source": "ctx._source.quarter = 'Q1-2024'; ctx._source.consolidated_date = System.currentTimeMillis();" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +This example consolidates 3 months of daily log indexes into a quarterly index while adding metadata about the consolidation. + +## Asynchronous operations + +For large datasets, you can run reindex operations asynchronously to avoid blocking your application. When you set `wait_for_completion=false`, OpenSearch immediately returns a task ID that you can use to monitor the operation's progress: + + +{% capture step1_rest %} +POST /_reindex?wait_for_completion=false +{ + "source": { + "index": "large-source-index" + }, + "dest": { + "index": "destination-index" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + params = { "wait_for_completion": "false" }, + body = { + "source": { + "index": "large-source-index" + }, + "dest": { + "index": "destination-index" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response includes a task ID: + +```json +{ + "task": "oTUltX4IQMOUUVeiohTt8A:12345" +} +``` + +Use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) to check the status of your reindex operation: + +```json +GET /_tasks/oTUltX4IQMOUUVeiohTt8A:12345 +``` + +You can manage long-running reindex tasks using these operations: + +- Cancel a running reindex: `POST /_tasks/oTUltX4IQMOUUVeiohTt8A:12345/_cancel` +- List all reindex tasks: `GET /_tasks?actions=*reindex*` +- Task cleanup: OpenSearch automatically removes completed task documents, but you can manually delete them if needed for immediate cleanup. + +## Cross-cluster reindexing + +Copy data from a remote OpenSearch cluster: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "remote": { + "host": "https://remote-cluster.example.com:9200", + "username": "reindex-user", + "password": "secure-password" + }, + "index": "remote-index", + "size": 1000 + }, + "dest": { + "index": "local-copy" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "remote": { + "host": "https://remote-cluster.example.com:9200", + "username": "reindex-user", + "password": "secure-password" + }, + "index": "remote-index", + "size": 1000 + }, + "dest": { + "index": "local-copy" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### SSL configuration for remote reindexing + +When reindexing from remote clusters over HTTPS, configure SSL settings in `opensearch.yml`. + +#### Certificate-based authentication + +Configure SSL using individual certificate files: + +```yaml +reindex.ssl.certificate_authorities: ["/path/to/ca-cert.pem"] +reindex.ssl.certificate: "/path/to/client-cert.pem" +reindex.ssl.key: "/path/to/client-key.pem" +reindex.ssl.verification_mode: full +``` + +#### Keystore-based authentication + +Configure SSL using keystore and truststore files: + +```yaml +reindex.ssl.keystore.path: "/path/to/keystore.p12" +reindex.ssl.keystore.type: "PKCS12" +reindex.ssl.truststore.path: "/path/to/truststore.p12" +reindex.ssl.truststore.type: "PKCS12" +``` + +#### SSL configuration options + +The following table lists the available SSL configuration parameters. + +Parameter | Description | Default +:--- | :--- | :--- +`reindex.ssl.verification_mode` | The certificate verification level: `full`, `certificate`, or `none` | `full` +`reindex.ssl.certificate_authorities` | A list of CA certificate file paths | None +`reindex.ssl.truststore.path` | The path to the truststore file (JKS or PKCS12) | None +`reindex.ssl.keystore.path` | The path to the keystore file for client authentication | None +`reindex.ssl.supported_protocols` | The supported TLS protocol versions | `TLSv1.3,TLSv1.2` + +SSL settings must be configured in `opensearch.yml` and require a cluster restart. They cannot be set in the reindex request body. +{: .warning } + +#### Remote cluster allow list + +Configure allowed remote hosts in `opensearch.yml`: + +```yaml +reindex.remote.allowlist: [ + "remote-cluster.example.com:9200", + "backup-cluster.example.com:9200", + "10.0.1.*:9200" +] +``` + +The allow list supports: + +- Explicit host:port combinations. +- Wildcard patterns for IP ranges. +- Multiple cluster endpoints. + +#### Retry settings + +When a request to the remote cluster fails, OpenSearch retries it with an exponential backoff. The following cluster settings control the retries. + +Setting | Description | Default +:--- | :--- | :--- +`reindex.remote.retry.initial_backoff` | The wait time before the first retry. Each subsequent retry doubles the wait time. | `500ms` +`reindex.remote.retry.max_count` | The maximum number of retries before the reindex operation fails. | `15` + +## Performance optimization + +Use the following techniques to optimize reindexing performance. + +### Throttling and rate control + +Control the reindex operation's impact on cluster performance using throttling: + + +{% capture step1_rest %} +POST /_reindex?requests_per_second=100 +{ + "source": { + "index": "source" + }, + "dest": { + "index": "dest" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + params = { "requests_per_second": "100" }, + body = { + "source": { + "index": "source" + }, + "dest": { + "index": "dest" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can dynamically adjust throttling for running reindex operations: + +```json +POST /_reindex/task_id/_rethrottle?requests_per_second=200 +``` + +### Using slicing for parallel processing + +Slicing divides a reindex operation into multiple parallel tasks to improve performance on large datasets. + +#### Automatic slicing + +To let OpenSearch determine the optimal number of slices, set the `slices` query parameter to `auto`: + + +{% capture step1_rest %} +POST /_reindex?slices=auto +{ + "source": { + "index": "large-index" + }, + "dest": { + "index": "large-index-copy" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + params = { "slices": "auto" }, + body = { + "source": { + "index": "large-index" + }, + "dest": { + "index": "large-index-copy" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Manual slicing + +For more control over parallelization, you can manually configure slices by specifying the slice ID and total number of slices in the request body. + +OpenSearch uses the `max` parameter to partition the dataset consistently across all slice requests. OpenSearch applies a hash function to each document using the `max` value to determine which slice the document belongs to. This ensures that: + +- Documents are distributed evenly across all slices. +- Each document goes to exactly one slice (no duplicates or gaps). +- All parallel requests must use the same `max` value for consistency. + +For example, with `max: 4`, you can run four separate requests in parallel: + +- Request 1: `{"id": 0, "max": 4}` (processes slice `0`) +- Request 2: `{"id": 1, "max": 4}` (processes slice `1`) +- Request 3: `{"id": 2, "max": 4}` (processes slice `2`) +- Request 4: `{"id": 3, "max": 4}` (processes slice `3`) + +The following request processes slice `0` out of 4 total slices: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "large-index", + "slice": { + "id": 0, + "max": 4 + } + }, + "dest": { + "index": "large-index-copy" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "large-index", + "slice": { + "id": 0, + "max": 4 + } + }, + "dest": { + "index": "large-index-copy" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Run multiple requests with different slice IDs (0--3) for parallel processing. + +### Monitoring reindex operations + +Use the following methods to monitor the progress and performance of your reindex operations. + +Monitor all active reindex operations in your cluster: + +```json +GET /_tasks?actions=*reindex*&detailed=true +``` +{% include copy-curl.html %} + +Check the progress of a specific reindex task using its task ID: + +```json +GET /_tasks/oTUltX4IQMOUUVeiohTt8A:12345 +``` +{% include copy-curl.html %} + +Monitor cluster performance and disk usage during reindex operations: + +```json +GET /_cluster/health +``` +{% include copy-curl.html %} + +```json +GET /_nodes/stats/indices/store +``` +{% include copy-curl.html %} + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/write/reindex`. diff --git a/_api-reference/document-apis/termvector.md b/_api-reference/document-apis/termvector.md new file mode 100644 index 00000000..1291017d --- /dev/null +++ b/_api-reference/document-apis/termvector.md @@ -0,0 +1,324 @@ +--- +layout: default +title: Term vectors +parent: Document APIs +nav_order: 70 +--- + +# Term Vectors API +**Introduced 1.0** +{: .label .label-purple } + +The `_termvectors` API retrieves term vector information for a single document. Term vectors provide detailed information about the terms (words) in a document, including term frequency, positions, offsets, and payloads. This can be useful for applications such as relevance scoring, highlighting, or similarity calculations. For more information, see [Term vector parameter]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/#term-vector-parameter). + + +## Endpoints +```json +GET /{index}/_termvectors +POST /{index}/_termvectors +GET /{index}/_termvectors/{id} +POST /{index}/_termvectors/{id} +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the index containing the document. | +| `id` | _Optional_ | String | The unique identifier of the document. | + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `field_statistics` | Boolean | If `true`, the response includes the document count, sum of document frequencies, and sum of total term frequencies. *(Default: `true`)* | +| `fields` | List or String | A comma-separated list or a wildcard expression specifying the fields to include in the statistics. Used as the default list unless a specific field list is provided in the `completion_fields` or `fielddata_fields` parameters. | +| `offsets` | Boolean | If `true`, the response includes term offsets. *(Default: `true`)* | +| `payloads` | Boolean | If `true`, the response includes term payloads. *(Default: `true`)* | +| `positions` | Boolean | If `true`, the response includes term positions. *(Default: `true`)* | +| `preference` | String | Specifies the node or shard on which the operation should be performed. See [preference query parameter]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#the-preference-query-parameter) for a list of available options. By default the requests are routed randomly to available shard copies (primary or replica), with no guarantee of consistency across repeated queries. | +| `realtime` | Boolean | If `true`, the request is real time as opposed to near real time. *(Default: `true`)* | +| `routing` | List or String | A custom value used to route operations to a specific shard. | +| `term_statistics` | Boolean | If `true`, the response includes term frequency and document frequency. *(Default: `false`)* | +| `version` | Integer | If `true`, returns the document version as part of a hit. | +| `version_type` | String | The specific version type.
Valid values are:
- `external`: The version number must be greater than the current version.
- `external_gte`: The version number must be greater than or equal to the current version.
- `force`: The version number is forced to be the given value.
- `internal`: The version number is managed internally by OpenSearch. | + +## Request body fields + +The following table lists the fields that can be specified in the request body. + +| Field | Data type | Description | +| `doc` | Object | A document to analyze. If provided, the API does not retrieve an existing document from the index but uses the provided content. | +| `fields` | Array of strings | A list of field names for which to return term vectors. | +| `offsets` | Boolean | If `true`, the response includes character offsets for each term. *(Default: `true`)* | +| `payloads` | Boolean | If `true`, the response includes payloads for each term. *(Default: `true`)* | +| `positions` | Boolean | If `true`, the response includes token positions. *(Default: `true`)* | +| `field_statistics` | Boolean | If `true`, the response includes statistics such as document count, sum of document frequencies, and sum of total term frequencies. *(Default: `true`)* | +| `term_statistics` | Boolean | If `true`, the response includes term frequency and document frequency. *(Default: `false`)* | +| `routing` | String | A custom routing value used to identify the shard. Required if custom routing was used during indexing. | +| `version` | Integer | The specific version of the document to retrieve. | +| `version_type` | String | The type of versioning to use. Valid values: `internal`, `external`, `external_gte`, `force`. | +| `filter` | Object | Allows filtering of tokens returned in the response (for example, by frequency or position). See [Filtering terms]({{site.url}}{{site.baseurl}}/api-reference/document-apis/termvector/#filtering-terms) for available options. | +| `per_field_analyzer` | Object | Specifies a custom analyzer to use per field. Format: `{ "field_name": "analyzer_name" }`. | +| `preference` | String | Specifies shard or node routing preferences. See [preference query parameter]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#the-preference-query-parameter).| + +## Filtering terms + +The `filter` object in the request body allows you to filter the tokens to include in the term vector response. The `filter` object supports the following fields. + +| Field | Data type | Description | +| `max_num_terms` | Integer | The maximum number of terms to return. | +| `min_term_freq` | Integer | The minimum term frequency in the document required for a term to be included. | +| `max_term_freq` | Integer | The maximum term frequency in the document required for a term to be included. | +| `min_doc_freq` | Integer | The minimum document frequency across the index required for a term to be included. | +| `max_doc_freq` | Integer | The maximum document frequency across the index required for a term to be included. | +| `min_word_length` | Integer | The minimum length of the term to be included. | +| `max_word_length` | Integer | The maximum length of the term to be included. | + +## Example requests + +Create an index: + +```json +PUT /my-index +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_offsets_payloads" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the document: + + +{% capture step1_rest %} +POST /my-index/_doc/1 +{ + "text": "OpenSearch is a search engine." +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "my-index", + id = "1", + body = { + "text": "OpenSearch is a search engine." + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request + +Retrieve the term vectors: + + +{% capture step1_rest %} +GET /my-index/_termvectors/1 +{ + "fields": [ + "text" + ], + "term_statistics": true +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.termvectors( + index = "my-index", + id = "1", + body = { + "fields": [ + "text" + ], + "term_statistics": true + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Alternatively, you can provide `fields` and `term_statistics` as query parameters: + + +{% capture step1_rest %} +GET /my-index/_termvectors/1?fields=text&term_statistics=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.termvectors( + index = "my-index", + id = "1", + params = { "fields": "text", "term_statistics": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example response + +The response displays term vector information: + +```json +{ + "_index": "my-index", + "_id": "1", + "_version": 1, + "found": true, + "took": 1, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 5, + "doc_count": 1, + "sum_ttf": 5 + }, + "terms": { + "a": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 14, + "end_offset": 15 + } + ] + }, + "engine": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 4, + "start_offset": 23, + "end_offset": 29 + } + ] + }, + "is": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 11, + "end_offset": 13 + } + ] + }, + "opensearch": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 10 + } + ] + }, + "search": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 3, + "start_offset": 16, + "end_offset": 22 + } + ] + } + } + } + } +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| `term_vectors` | Object | Contains term vector data for each specified field. | +| `term_vectors.text` | Object | Contains term vector details for the `text` field. | +| `term_vectors.text.field_statistics` | Object | Contains statistics for the entire field. Present only if `field_statistics` is `true`. | +| `term_vectors.text.field_statistics.doc_count` | Integer | The number of documents that contain at least one term in the specified field. | +| `term_vectors.text.field_statistics.sum_doc_freq` | Integer | The sum of document frequencies for all terms in the field. | +| `term_vectors.text.field_statistics.sum_ttf` | Integer | The sum of total term frequencies (including repetitions) for all terms in the field. | +| `term_vectors.text.terms` | Object | A map, in which each key is a term and each value contains details about that term. | +| `term_vectors.text.terms..term_freq` | Integer | The number of times the term appears in the document. | +| `term_vectors.text.terms..doc_freq` | Integer | The number of documents containing the term. Present only if `term_statistics` is `true`. | +| `term_vectors.text.terms..ttf` | Integer | The total term frequency across all documents. Present only if `term_statistics` is `true`. | +| `term_vectors.text.terms..tokens` | Array | A list of token objects providing information about individual term instances. | +| `term_vectors.text.terms..tokens[].position` | Integer | The position of the token within the text. Present only if `positions` is `true`. | +| `term_vectors.text.terms..tokens[].start_offset` | Integer | The start character offset of the token. Present only if `offsets` is `true`. | +| `term_vectors.text.terms..tokens[].end_offset` | Integer | The end character offset of the token. Present only if `offsets` is `true`. | +| `term_vectors.text.terms..tokens[].payload` | String (Base64) | Optional payload data associated with the token. Present only if `payloads` is `true` and available. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/tv`. diff --git a/_api-reference/document-apis/update-by-query.md b/_api-reference/document-apis/update-by-query.md index b53c3193..f64a8a16 100644 --- a/_api-reference/document-apis/update-by-query.md +++ b/_api-reference/document-apis/update-by-query.md @@ -2,113 +2,899 @@ layout: default title: Update by query parent: Document APIs -nav_order: 50 +nav_order: 40 redirect_from: - /opensearch/rest-api/document-apis/update-by-query/ --- -# Update by query +# Update By Query API **Introduced 1.0** {: .label .label-purple} -You can include a query and a script as part of your update request so OpenSearch can run the script to update all of the documents that match the query. +The Update by Query API updates all documents in an index that match a specified query. You can update documents without changing their source to pick up mapping changes, or use a script to modify field values based on custom logic. -## Example +Use this API in the following scenarios: +- Applying mapping changes to existing documents after adding new fields or changing field types. +- Updating field values across multiple documents based on calculated logic or conditions. +- Incrementing counters or performing bulk calculations on documents that match specific criteria. +- Conditionally deleting documents by setting `ctx.op = "delete"` in a script. +- Performing no-operation updates by setting `ctx.op = "noop"` when conditions aren't met. + +When you submit an update by query request, OpenSearch takes a snapshot of the index at the start of the operation and updates matching documents using internal versioning. If a document changes between when the snapshot is taken and when the update operation processes it, a version conflict occurs and the update fails for that document unless you set the `conflicts` parameter to `proceed`. When a version conflict doesn't cause an abort, the document is updated and its version number is incremented. Successfully updated documents are not rolled back even if later operations in the batch fail. + +All update and query failures cause the operation to abort and are returned in the `failures` array of the response. Successful updates persist even after an abort. While the first failure triggers the abort, all failures from the rejected bulk request appear in the `failures` element, so multiple failed entities may be reported. + +OpenSearch retries rejected search or bulk requests up to 10 times with exponential backoff. If the maximum retry limit is reached, the operation halts and returns all failed requests in the response. + +**Note:** OpenSearch cannot update documents with version `0` using this API. The internal versioning system requires that version numbers are greater than 0 in order to track and process update operations correctly. +{: .note} + + + +## Endpoints ```json -POST test-index1/_update_by_query +POST /{index}/_update_by_query +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | List or String | A comma-separated list of data streams, indexes, and aliases to search. Supports wildcards (`*`). To search all data streams or indexes, omit this parameter or use `*` or `_all`. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `_source` | Boolean or List or String | Set to `true` or `false` to return the `_source` field or not, or a list of fields to return. | N/A | +| `_source_excludes` | List | List of fields to exclude from the returned `_source` field. | N/A | +| `_source_includes` | List | List of fields to extract and return from the `_source` field. | N/A | +| `allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indexes. This behavior applies even if the request targets other open indexes. For example, a request targeting `foo*,bar*` returns an error if an index starts with `foo` but no index starts with `bar`. | N/A | +| `analyze_wildcard` | Boolean | If `true`, wildcard and prefix queries are analyzed. | `false` | +| `analyzer` | String | Analyzer to use for the query string. | N/A | +| `conflicts` | String | What to do if update by query hits version conflicts: `abort` or `proceed`.
Valid values are:
- `abort`: Abort the operation on version conflicts.
- `proceed`: Proceed with the operation on version conflicts. | N/A | +| `default_operator` | String | The default operator for query string query: `AND` or `OR`.
Valid values are: `and`, `AND`, `or`, and `OR`. | N/A | +| `df` | String | Field to use as default where no field prefix is given in the query string. | N/A | +| `expand_wildcards` | List or String | Type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. Supports comma-separated values, such as `open,hidden`. Valid values are: `all`, `open`, `closed`, `hidden`, `none`.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | N/A | +| `from` | Integer | Starting offset. | `0` | +| `ignore_unavailable` | Boolean | If `false`, the request returns an error if it targets a missing or closed index. | N/A | +| `lenient` | Boolean | If `true`, format-based query failures (such as providing text to a numeric field) in the query string will be ignored. | N/A | +| `max_docs` | Integer | Maximum number of documents to process. Defaults to all documents. | N/A | +| `pipeline` | String | ID of the pipeline to use to preprocess incoming documents. If the index has a default ingest pipeline specified, then setting the value to `_none` disables the default ingest pipeline for this request. If a final pipeline is configured it will always run, regardless of the value of this parameter. | N/A | +| `preference` | String | Specifies the node or shard the operation should be performed on. Random by default. | `random` | +| `q` | String | Query in the Lucene query string syntax. | N/A | +| `refresh` | Boolean or String | If `true`, OpenSearch refreshes affected shards to make the operation visible to search.
Valid values are:
- `false`: Do not refresh the affected shards.
- `true`: Refresh the affected shards immediately.
- `wait_for`: Wait for the changes to become visible before replying. | N/A | +| `request_cache` | Boolean | If `true`, the request cache is used for this request. | N/A | +| `requests_per_second` | Float | The throttle for this request in sub-requests per second. | `0` | +| `routing` | List or String | A custom value used to route operations to a specific shard. | N/A | +| `scroll` | String | Period to retain the search context for scrolling. | N/A | +| `scroll_size` | Integer | Size of the scroll request that powers the operation. | `100` | +| `search_timeout` | String | Explicit timeout for each search request. | N/A | +| `search_type` | String | The type of the search operation. Available options: `query_then_fetch`, `dfs_query_then_fetch`.
Valid values are:
- `dfs_query_then_fetch`: Documents are scored using global term and document frequencies across all shards. This is usually slower but more accurate.
- `query_then_fetch`: Documents are scored using local term and document frequencies for the shard. This is usually faster but less accurate. | N/A | +| `size` | Integer | Deprecated, use `max_docs` instead. | N/A | +| `slices` | Integer or String | The number of slices this task should be divided into.
Valid values are:
- `auto`: Automatically determine the number of slices. | N/A | +| `sort` | List | A comma-separated list of : pairs. | N/A | +| `stats` | List | Specific `tag` of the request for logging and statistical purposes. | N/A | +| `terminate_after` | Integer | Maximum number of documents to collect for each shard. If a query reaches this limit, OpenSearch terminates the query early. OpenSearch collects documents before sorting. Use with caution. OpenSearch applies this parameter to each shard handling the request. When possible, let OpenSearch perform early termination automatically. Avoid specifying this parameter for requests that target data streams with backing indexes across multiple data tiers. | N/A | +| `timeout` | String | Period each update request waits for the following operations: dynamic mapping updates, waiting for active shards. | N/A | +| `version` | Boolean | If `true`, returns the document version as part of a hit. | N/A | +| `wait_for_active_shards` | Integer or String or NULL or String | The number of shard copies that must be active before proceeding with the operation. Set to `all` or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
Valid values are:
- `all`: Wait for all shards to be active. | N/A | +| `wait_for_completion` | Boolean | If `true`, the request blocks until the operation is complete. | `true` | + + + +**Important:** When using `_source`, `_source_includes`, or `_source_excludes` in an update by query request, these settings affect not only the response but also the fields available to the update script. If a field is excluded from `_source` and not explicitly handled in the script, it may be removed from the document during the update operation. To preserve excluded fields, ensure that the script reads and reassigns them as needed. +{: .important} + +## Request body fields + +The request body is optional but typically includes a query to specify which documents to update and a script to define the update logic. + +Field | Data type | Description +:--- | :--- | :--- +`query` | Object | The query used to select documents for update. If not specified, the operation updates all documents in the target index. For more information about query types, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). +`script` | Object | The script to run on each matching document. Contains `source` (the script code), `lang` (script language, typically `painless`), and optional `params` (parameters passed to the script). The script can access the document via `ctx._source` and control the operation by setting `ctx.op`. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). +`slice` | Object | Manually specify slice ID and maximum slices for parallel processing. Contains `id` (integer, slice number) and `max` (integer, total number of slices). Optional. +`max_docs` | Integer | Maximum number of documents to process. Optional. +`conflicts` | String | What to do when the update by query operation encounters version conflicts. Set to `proceed` to continue or `abort` to stop. Can be specified in either the request body or as a query parameter. Optional. + +## Script operations + +Within your update script, you can control what happens to each document by setting `ctx.op`: + +Operation | Description +:--- | :--- +No operation (`noop`) | Set `ctx.op = "noop"` to skip updating a document when your script determines no changes are needed. OpenSearch reports skipped documents in the `noops` counter of the response. +Delete (`delete`) | Set `ctx.op = "delete"` to delete a document based on script logic. OpenSearch reports deleted documents in the `deleted` counter of the response. + +Setting `ctx.op` to any other value causes an error. Modifying other fields in `ctx` besides `ctx._source` and `ctx.op` also causes an error. + +## Refreshing shards + +Specifying the `refresh` parameter refreshes all shards involved in the update by query operation after the request completes. This behavior differs from the Update API's `refresh` parameter, which only refreshes the shard that received the update request. The Update by Query API does not support the `wait_for` value for the `refresh` parameter. + +## Running update by query asynchronously + +To run an update by query operation asynchronously, set the `wait_for_completion` query parameter to `false`. OpenSearch performs preflight checks, launches the request, and returns a task ID that you can use to monitor progress or cancel the operation. When running asynchronously, OpenSearch creates a record of the task as a document at `.tasks/task/${taskId}`. After the task completes, delete the task document to allow OpenSearch to reclaim the space. + +## Waiting for active shards + +The `wait_for_active_shards` parameter controls how many shard copies must be active before processing the request. The `timeout` parameter controls how long each write request waits for unavailable shards to become available. These parameters work the same way as in the Bulk API. Because Update by Query uses scrolled searches, you can specify the `scroll` parameter to control how long the search context remains active. The default scroll time is 5 minutes. + +## Throttling update requests + +To control the rate at which update by query issues batches of update operations, set `requests_per_second` to any positive decimal number. This pads each batch with a wait time to throttle the rate. Set `requests_per_second` to `-1` to disable throttling. + +Throttling uses wait time between batches so that internal scroll requests can be given a timeout that accounts for request padding. The padding time is the difference between the batch size divided by `requests_per_second` and the time spent writing. By default, the batch size is 1,000, so if `requests_per_second` is set to 500: + +``` +target_time = 1,000 / 500 per second = 2 seconds +wait_time = target_time - write_time = 2 seconds - 0.5 seconds = 1.5 seconds +``` + +Because each batch is issued as a single bulk request, large batch sizes cause OpenSearch to create many requests and then wait before starting the next batch. This creates uneven processing patterns with periods of high activity followed by idle waiting. + +## Slicing for parallel processing + +You can use slicing to run update operations in parallel across multiple threads. This approach divides the update operation into independent segments, improving performance for large-scale updates. + +Setting `slices` to `auto` allows OpenSearch to choose a reasonable number for most indexes. When using automatic slicing or tuning it manually, consider these factors: + +- Optimal query performance occurs when you match the slice count to your shard count. However, for indexes with many shards (500 or more), use fewer slices to avoid performance degradation from excessive parallelization overhead. Setting slices higher than the number of shards generally does not improve efficiency and adds overhead. +- Update performance scales linearly across available resources with the number of slices. +- Whether query or update performance dominates runtime depends on the documents being updated and available cluster resources. + +## Example: Updating all documents without changing source + +The following example request updates all documents in the index without modifying their source. This is useful for picking up new mapping properties or other mapping changes: + + +{% capture step1_rest %} +POST /products/_update_by_query?conflicts=proceed +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + params = { "conflicts": "proceed" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Updating documents with a query filter + +The following example request updates only electronics products by adding a 10% discount: + + +{% capture step1_rest %} +POST /products/_update_by_query { "query": { "term": { - "oldValue": 20 + "category": "electronics" } }, - "script" : { - "source": "ctx._source.oldValue += params.newValue", + "script": { + "source": "ctx._source.discount = params.discountPercent", "lang": "painless", - "params" : { - "newValue" : 10 + "params": { + "discountPercent": 0.1 } } } -``` +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + body = { + "query": { + "term": { + "category": "electronics" + } + }, + "script": { + "source": "ctx._source.discount = params.discountPercent", + "lang": "painless", + "params": { + "discountPercent": 0.1 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Incrementing a field value + +The following example request increments the likes counter for all products from a specific user: + + +{% capture step1_rest %} +POST /products/_update_by_query +{ + "query": { + "term": { + "user_id": "user1" + } + }, + "script": { + "source": "ctx._source.likes++", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + body = { + "query": { + "term": { + "user_id": "user1" + } + }, + "script": { + "source": "ctx._source.likes++", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Conditionally deleting documents + +The following example request deletes out-of-stock products with zero likes: + + +{% capture step1_rest %} +POST /products/_update_by_query +{ + "query": { + "bool": { + "must": [ + { + "term": { + "in_stock": false + } + }, + { + "term": { + "likes": 0 + } + } + ] + } + }, + "script": { + "source": "ctx.op = 'delete'", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + body = { + "query": { + "bool": { + "must": [ + { + "term": { + "in_stock": false + } + }, + { + "term": { + "likes": 0 + } + } + ] + } + }, + "script": { + "source": "ctx.op = 'delete'", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example: Using noop for conditional updates + + +The following example request increases discount only for products priced above $100, otherwise performs no operation: + + +{% capture step1_rest %} +POST /products/_update_by_query +{ + "script": { + "source": "if (ctx._source.price > 100) { ctx._source.discount = 0.15 } else { ctx.op = 'noop' }", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + body = { + "script": { + "source": "if (ctx._source.price > 100) { ctx._source.discount = 0.15 } else { ctx.op = 'noop' }", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Updating from multiple indexes + +The following example request updates documents across multiple indexes: + + +{% capture step1_rest %} +POST /products,inventory/_update_by_query +{ + "query": { + "match_all": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products,inventory", + body = { + "query": { + "match_all": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Using routing for targeted updates + +The following example request limits the update operation to shards with a specific routing value: + + +{% capture step1_rest %} +POST /products/_update_by_query?routing=user1 +{ + "query": { + "term": { + "user_id": "user1" + } + }, + "script": { + "source": "ctx._source.likes += 5", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + params = { "routing": "user1" }, + body = { + "query": { + "term": { + "user_id": "user1" + } + }, + "script": { + "source": "ctx._source.likes += 5", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Using scroll_size to control batch size + +The following example request uses a custom scroll batch size of 100 documents: + + +{% capture step1_rest %} +POST /products/_update_by_query?scroll_size=100 +{ + "query": { + "range": { + "price": { + "gte": 50 + } + } + }, + "script": { + "source": "ctx._source.discount = 0.05", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + params = { "scroll_size": "100" }, + body = { + "query": { + "range": { + "price": { + "gte": 50 + } + } + }, + "script": { + "source": "ctx._source.discount = 0.05", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Manual slicing for parallel processing + +The following example requests manually divide the update operation into two slices for parallel processing: + + +{% capture step1_rest %} +POST /products/_update_by_query +{ + "slice": { + "id": 0, + "max": 2 + }, + "script": { + "source": "ctx._source.discount = 0.20", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + body = { + "slice": { + "id": 0, + "max": 2 + }, + "script": { + "source": "ctx._source.discount = 0.20", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +In a separate request, process the second slice: + + +{% capture step1_rest %} +POST /products/_update_by_query +{ + "slice": { + "id": 1, + "max": 2 + }, + "script": { + "source": "ctx._source.discount = 0.20", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + body = { + "slice": { + "id": 1, + "max": 2 + }, + "script": { + "source": "ctx._source.discount = 0.20", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Automatic slicing + +The following example request uses automatic slicing to parallelize the update operation across 5 slices: + + +{% capture step1_rest %} +POST /products/_update_by_query?slices=5&refresh=true +{ + "script": { + "source": "ctx._source.discount = 0.25", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + params = { "slices": "5", "refresh": "true" }, + body = { + "script": { + "source": "ctx._source.discount = 0.25", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To allow OpenSearch to automatically determine the optimal number of slices, use `slices=auto`: + + +{% capture step1_rest %} +POST /products/_update_by_query?slices=auto +{ + "query": { + "term": { + "category": "furniture" + } + }, + "script": { + "source": "ctx._source.discount = 0.30", + "lang": "painless" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query( + index = "products", + params = { "slices": "auto" }, + body = { + "query": { + "term": { + "category": "furniture" + } + }, + "script": { + "source": "ctx._source.discount = 0.30", + "lang": "painless" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following example response shows a successful update by query operation that updated 8 documents: -## Response ```json { - "took": 21, + "took": 39, "timed_out": false, - "total": 1, - "updated": 1, + "total": 8, + "updated": 8, + "deleted": 0, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0, + "failures": [] +} +``` + +When using a script with conditional `noop` operations, the response includes a `noops` count showing how many documents were skipped: + +```json +{ + "took": 55, + "timed_out": false, + "total": 8, + "updated": 4, + "deleted": 0, + "batches": 1, + "version_conflicts": 0, + "noops": 4, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0, + "failures": [] +} +``` + +When using manual slicing, the response includes a `slice_id` field indicating which slice was processed: + +```json +{ + "took": 12, + "timed_out": false, + "slice_id": 0, + "total": 4, + "updated": 4, "deleted": 0, "batches": 1, "version_conflicts": 0, @@ -126,17 +912,96 @@ To update your indexes and documents by query, you must include a [query]({{site ## Response body fields -Field | Description -:--- | :--- -took | The amount of time in milliseconds OpenSearch needed to complete the operation. -timed_out | Whether any update requests during the operation timed out. -total | Total number of documents processed. -updated | Total number of documents updated. -batches | Number of scroll responses the request processed. -version_conflicts | Number of conflicts the request ran into. -noops | How many update requests OpenSearch ignored during the operation. This field always returns 0. -retries | The number of bulk and search retry requests. -throttled_millis | Number of throttled milliseconds during the request. -requests_per_second | Number of requests executed per second during the operation. -throttled_until_millis | The amount of time until OpenSearch executes the next throttled request. Always equal to 0 in an update by query request. -failures | Any failures that occur during the request. +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`took` | Integer | The amount of time from the start to the end of the entire operation, in milliseconds. +`timed_out` | Boolean | Whether any of the requests executed during the update by query operation timed out. When set to `true`, successfully completed updates still persist and are not rolled back. +`total` | Integer | The total number of documents that were successfully processed. +`updated` | Integer | The number of documents that were successfully updated. +`deleted` | Integer | The number of documents that were deleted. This occurs when the script sets `ctx.op = "delete"`. +`batches` | Integer | The number of scroll batches processed by the update by query operation. +`version_conflicts` | Integer | The number of version conflicts encountered by the update by query operation. Occurs when a document changes between the time the snapshot is taken and when the update operation is processed. +`noops` | Integer | The number of documents that were ignored because the script set `ctx.op = "noop"`. Unlike delete by query, this field can contain non-zero values when scripts conditionally skip updates. +`retries` | Object | The number of retries attempted by the update by query operation. Contains `bulk` (number of bulk action retries) and `search` (number of search action retries). +`throttled_millis` | Integer | The amount of time the request was throttled to conform to `requests_per_second`, in milliseconds. +`requests_per_second` | Float | The number of requests per second effectively executed during the update by query operation. +`throttled_until_millis` | Integer | The amount of time until the next throttled request will be executed, in milliseconds. Always equals 0 in a completed update by query response. This field has meaning only when using the Tasks API to monitor an ongoing operation, where it indicates the next time a throttled request will execute. +`slice_id` | Integer | The slice number for this response. Only present when using manual slicing. Indicates which slice of the operation this response represents. +`slices` | Array | An array of slice results when using automatic slicing with a specific number. Each element contains the same response fields as the main response, showing the results for that individual slice. +`failures` | Array | An array of failures if any unrecoverable errors occurred during the operation. If this array is not empty, the request aborted because of those failures. Update by query is implemented using batches, and any failure causes the entire process to abort, but all failures in the current batch are collected in this array. You can use the `conflicts` parameter set to `proceed` to prevent the operation from aborting on version conflicts. + +## Managing update by query tasks + +When you run an update by query operation asynchronously by setting `wait_for_completion=false`, OpenSearch returns a task ID that you can use to monitor, modify, or cancel the operation. + +### Retrieving the status of an update by query operation + +To retrieve the status of an update by query operation, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/): + +```json +GET _tasks?detailed=true&actions=*/update/byquery +``` +{% include copy-curl.html %} + +The response includes the status of all running update by query operations. To retrieve the status of a specific task, use the task ID: + +```json +GET _tasks/ +``` +{% include copy-curl.html %} + +The response contains detailed information about the operation's progress: + +```json +{ + "nodes": { + "node_id": { + "tasks": { + "task_id": { + "status": { + "total": 1000, + "updated": 450, + "created": 0, + "deleted": 0, + "batches": 5, + "version_conflicts": 0, + "noops": 0, + "retries": 0, + "throttled_millis": 0 + } + } + } + } + } +} +``` + +The `total` field represents the total number of operations that the update by query operation expects to perform. You can estimate progress by adding the `updated`, `deleted`, and `noops` fields and comparing the sum to the `total` field. The operation is complete when their sum equals the `total` field. + +### Changing throttling for a running operation + +To change the throttling of a running update by query operation, use the Rethrottle Task API with the task ID: + +```json +POST _update_by_query//_rethrottle?requests_per_second=100 +``` +{% include copy-curl.html %} + +Set `requests_per_second` to any positive decimal value or `-1` to disable throttling. Rethrottling that speeds up the operation takes effect immediately. Rethrottling that slows down the operation takes effect after completing the current batch to prevent scroll timeouts. + +### Canceling an update by query operation + +To cancel a running update by query operation, use the task cancel API: + +```json +POST _tasks//_cancel +``` +{% include copy-curl.html %} + +Cancellation should happen quickly but might take a few seconds. The Tasks API continues to list the update by query task until it checks that it has been canceled and terminates itself. When you cancel an update by query operation with slices, OpenSearch cancels each sub-request. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/write/update/byquery`. diff --git a/_api-reference/document-apis/update-document.md b/_api-reference/document-apis/update-document.md index 365cb3aa..0d943c03 100644 --- a/_api-reference/document-apis/update-document.md +++ b/_api-reference/document-apis/update-document.md @@ -7,96 +7,262 @@ redirect_from: - /opensearch/rest-api/document-apis/update-document/ --- -# Update document +# Update Document API **Introduced 1.0** {: .label .label-purple } -If you need to update a document's fields in your index, you can use the update document API operation. You can do so by specifying the new data you want to be in your index or by including a script in your request body, which OpenSearch runs to update the document. By default, the update operation only updates a document that exists in the index. If a document does not exist, the API returns an error. To _upsert_ a document (update the document that exists or index a new one), use the [upsert](#upsert) operation. +If you need to update a document's fields in your index, you can use the update document API operation. You can do so by specifying the new data you want to be in your index or by including a script in your request body, which OpenSearch runs to update the document. By default, the update operation only updates a document that exists in the index. If a document does not exist, the API returns an error. To _upsert_ a document (update the document that exists or index a new one), use the [upsert](#using-the-upsert-operation) operation. -## Example +When you submit an update request, OpenSearch performs the following operations: +1. Fetches the current document from the shard where it is stored. +2. Applies the update using either the provided script or by merging the partial document with the existing document. +3. Reindexes the updated document and increments its version number. + +Although the document must be reindexed, using the Update Document API reduces network round trips and minimizes version conflicts compared to manually retrieving the document using the `GET` method, modifying it, and reindexing it using the Index API. + +To use the Update Document API, the `_source` field must be enabled in your index. +{: .important} + +You cannot explicitly specify an ingest pipeline when calling the Update Document API. If a `default_pipeline` or `final_pipeline` is defined in your index, the following behavior applies: + +- **Upsert operations**: When indexing a new document, the `default_pipeline` and `final_pipeline` defined in the index are executed as specified. +- **Update operations**: When updating an existing document, ingest pipeline execution is not recommended because it may produce erroneous results. Support for running ingest pipelines during update operations is deprecated and will be removed in version 3.0.0. If your index has a defined ingest pipeline, the update document operation will return the following deprecation warning: + +``` +the index [sample-index1] has a default ingest pipeline or a final ingest pipeline, the support of the ingest pipelines for update operation causes unexpected result and will be removed in 3.0.0 +``` + + +## Endpoints ```json -POST /sample-index1/_update/1 +POST /{index}/_update/{id} +``` + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `id` | **Required** | String | The document ID. | +| `index` | **Required** | String | The index name. By default, if the index doesn't exist, it is created automatically. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description | Required +:--- | :--- | :--- | :--- +`if_seq_no` | Integer | Only perform the update operation if the document has the specified sequence number. | No +`if_primary_term` | Integer | Perform the update operation if the document has the specified primary term. | No +`lang` | String | Language of the script. Default is `painless`. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). | No +`require_alias` | Boolean | Specifies whether the destination must be an index alias. Default is `false`. | No +`refresh` | Enum | If true, OpenSearch refreshes shards to make the operation visible to searching. Valid options are `true`, `false`, and `wait_for`, which tells OpenSearch to wait for a refresh before executing the operation. Default is `false`. | No +`retry_on_conflict` | Integer | The amount of times OpenSearch should retry the operation if there's a document conflict. Default is 0. | No +`routing` | String | Value to route the update operation to a specific shard. | No +`_source` | Boolean or List | Whether or not to include the `_source` field in the response body. Default is `false`. This parameter also supports a comma-separated list of source fields for including multiple source fields in the query response. | No +`_source_excludes` | List | A comma-separated list of source fields to exclude in the query response. | No +`_source_includes` | List | A comma-separated list of source fields to include in the query response. | No +`timeout` | Time | How long to wait for a response from the cluster. | No +`wait_for_active_shards` | String | The number of active shards that must be available before OpenSearch processes the update request. Default is 1 (only the primary shard). Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the operation to succeed. | No + +## Request body fields + +Your request body must contain the information with which you want to update your document. The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`doc` | Object | A partial document containing fields to merge into the existing document. Use this for simple field updates. See [Updating a document using a doc object](#updating-a-document-using-a-doc-object). +`script` | Object | A script that defines how to update the document. Use this for complex updates requiring conditional logic or computed values. If both `doc` and `script` are specified, `doc` is ignored. See [Updating a document using a script](#updating-a-document-using-a-script). +`upsert` | Object | The document to index if the target document does not exist. Used in combination with `doc` or `script` for conditional upsert operations. See [Upsert](#upsert). +`doc_as_upsert` | Boolean | If `true`, uses the `doc` content for both updates and inserts. Default is `false`. See [Doc as upsert](#doc-as-upsert). +`scripted_upsert` | Boolean | If `true`, runs the script whether or not the document exists. Default is `false`. Requires both `script` and `upsert` fields. See [Scripted upsert](#scripted-upsert). +`detect_noop` | Boolean | If `true`, OpenSearch checks whether the update changes the document. If no changes are detected, the update is skipped. Default is `true`. See [Detecting no-op updates](#detecting-no-op-updates). + +### Script context and variables + +Scripts can access and modify the document through the `ctx` map, which provides access to the following variables. + +Variable | Description +:--- | :--- +`ctx._source` | The document source. You can read and modify this object to update document fields. +`ctx._index` | The name of the index containing the document. +`ctx._id` | The document ID. +`ctx._version` | The current document version. +`ctx._routing` | The routing value used to route the document to a shard (if custom routing was used). +`ctx._now` | The current timestamp in milliseconds since the epoch. +`ctx.op` | The operation to perform. Set this to `delete` to delete the document or `none` to perform no operation (no-op). + +You can use these variables in your scripts to implement conditional logic based on the document's current state. + +## Example setup + +The following examples use test documents in a `sample-index1` index. To follow along, first create an index with sample documents: + + +{% capture step1_rest %} +PUT /sample-index1/_doc/1 +{ + "first_name": "Bruce", + "last_name": "Wayne", + "age": 35, + "gadgets": [ + "batarang" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "sample-index1", + id = "1", + body = { + "first_name": "Bruce", + "last_name": "Wayne", + "age": 35, + "gadgets": [ + "batarang" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example requests + +The following examples demonstrate how to use different request body fields to update documents. + +### Updating a document using a doc object + + +{% capture step1_rest %} +POST /sample-index1/_update/1 +{ + "doc": { + "first_name": "Bruce", + "last_name": "Wayne" + } +} +{% endcapture %} -## Script example +{% capture step1_python %} -```json -POST /test-index1/_update/1 + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "doc": { + "first_name": "Bruce", + "last_name": "Wayne" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Updating a document using a script + + +{% capture step1_rest %} +POST /sample-index1/_update/1 { - "doc": { - "first_name": "Thomas", - "last_name": "Wayne" - } -} -``` - -You can also use a script to tell OpenSearch how to update your document: - -```json -{ - "script" : { - "source": "ctx._source.oldValue += params.newValue", - "lang": "painless", - "params" : { - "newValue" : 10 - } + "script": { + "source": "ctx._source.secret_identity = \"Batman\"" } } -``` +{% endcapture %} -## Upsert +{% capture step1_python %} -Upsert is an operation that conditionally either updates an existing document or inserts a new one based on information in the object. + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "script": { + "source": "ctx._source.secret_identity = \"Batman\"" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Using the upsert operation + +Upsert is an operation that conditionally either updates an existing document or inserts a new one based on information in the request. This is useful when you're not sure if a document already exists and want to ensure the correct content is present either way. + +#### Upsert In the following example, the `upsert` operation updates the `first_name` and `last_name` fields if a document already exists. If a document does not exist, a new one is indexed using content in the `upsert` object. -```json + +{% capture step1_rest %} POST /sample-index1/_update/1 { "doc": { @@ -108,7 +274,32 @@ POST /sample-index1/_update/1 "age": "31" } } -``` +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "doc": { + "first_name": "Martha", + "last_name": "Rivera" + }, + "upsert": { + "last_name": "Oliveira", + "age": "31" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + Consider an index that contains the following document: @@ -123,6 +314,7 @@ Consider an index that contains the following document: } } ``` +{% include copy-curl.html %} After the upsert operation, the document's `first_name` and `last_name` fields are updated: @@ -137,6 +329,7 @@ After the upsert operation, the document's `first_name` and `last_name` fields a } } ``` +{% include copy-curl.html %} If the document does not exist in the index, a new document is indexed with the fields specified in the `upsert` object: @@ -151,10 +344,26 @@ If the document does not exist in the index, a new document is indexed with the } } ``` +{% include copy-curl.html %} + +#### Doc as upsert You can also add `doc_as_upsert` to the request and set it to `true` to use the information in the `doc` field for performing the upsert operation: -```json + +{% capture step1_rest %} POST /sample-index1/_update/1 { "doc": { @@ -164,7 +373,30 @@ POST /sample-index1/_update/1 }, "doc_as_upsert": true } -``` +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "doc": { + "first_name": "Martha", + "last_name": "Oliveira", + "age": "31" + }, + "doc_as_upsert": true + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + Consider an index that contains the following document: @@ -179,8 +411,9 @@ Consider an index that contains the following document: } } ``` +{% include copy-curl.html %} -After the upsert operation, the document's `first_name` and `last_name` fields are updated and an `age` field is added. If the document does not exist in the index, a new document is indexed with the fields specified in the `upsert` object. In both cases, the document is as follows: +After the upsert operation, the document's `first_name` and `last_name` fields are updated and an `age` field is added. If the document does not exist in the index, a new document is created using the fields from the `doc` object: ```json { @@ -194,8 +427,151 @@ After the upsert operation, the document's `first_name` and `last_name` fields a } } ``` +{% include copy-curl.html %} + +#### Scripted upsert + +You can also use a script to control how the document is updated. By setting the `scripted_upsert` parameter to `true`, you instruct OpenSearch to use the script even when the document doesn't exist yet. This allows you to define the entire upsert logic in the script. + +In the following example, the script sets the document to contain specific fields regardless of whether it previously existed: + + +{% capture step1_rest %} +POST /sample-index1/_update/2 +{ + "scripted_upsert": true, + "script": { + "source": "ctx._source.first_name = params.first_name; ctx._source.last_name = params.last_name; ctx._source.age = params.age;", + "params": { + "first_name": "Selina", + "last_name": "Kyle", + "age": 28 + } + }, + "upsert": {} +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "2", + index = "sample-index1", + body = { + "scripted_upsert": true, + "script": { + "source": "ctx._source.first_name = params.first_name; ctx._source.last_name = params.last_name; ctx._source.age = params.age;", + "params": { + "first_name": "Selina", + "last_name": "Kyle", + "age": 28 + } + }, + "upsert": {} + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If the document with ID `2` does not already exist, this operation creates it using the script. If the document does exist, the script updates the specified fields. In both cases, the result is: + +```json +{ + "_index": "sample-index1", + "_id": "2", + "_score": 1, + "_source": { + "first_name": "Selina", + "last_name": "Kyle", + "age": 28 + } +} +``` +{% include copy-curl.html %} + +Using `scripted_upsert` gives you full control over document creation and updates when standard `doc`-based operations are not flexible enough. + +### Detecting no-op updates + +By default, OpenSearch detects whether an update operation actually changes the document. If the update doesn't make any changes, OpenSearch skips the operation and returns `"result": "noop"` to indicate that no operation was performed. This optimization avoids unnecessary reindexing when the document already contains the values you're trying to set. + +The following example attempts to update document `1` with values it already contains: + +```json +POST /sample-index1/_update/1 +{ + "doc": { + "first_name": "Bruce", + "last_name": "Wayne", + "age": 35 + } +} +``` +{% include copy-curl.html %} + +Because the document already has these exact values, OpenSearch detects no changes and returns a no-op response: + +```json +{ + "_index": "sample-index1", + "_id": "1", + "_version": 2, + "result": "noop", + "_shards": { + "total": 0, + "successful": 0, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` +{% include copy-curl.html %} + +Note that `_shards.total` is `0` when a no-op is detected, indicating that no shard operations were performed. + +You can disable no-op detection by setting `detect_noop` to `false`. This forces OpenSearch to reindex the document even when the values haven't changed: + +```json +POST /sample-index1/_update/1 +{ + "doc": { + "first_name": "Bruce", + "last_name": "Wayne", + "age": 35 + }, + "detect_noop": false +} +``` +{% include copy-curl.html %} + +With `noop` detection disabled, OpenSearch reindexes the document and increments its version number even though the content is identical. + + +## Example response -## Response ```json { "_index": "sample-index1", @@ -214,15 +590,363 @@ After the upsert operation, the document's `first_name` and `last_name` fields a ## Response body fields +The following table lists all response body fields. + Field | Description :--- | :--- -_index | The name of the index. -_id | The document's ID. -_version | The document's version. -result | The result of the update operation. -_shards | Detailed information about the cluster's shards. -total | The total number of shards. -successful | The number of shards OpenSearch successfully updated the document in. -failed | The number of shards OpenSearch failed to update the document in. -_seq_no | The sequence number assigned when the document was indexed. -_primary_term | The primary term assigned when the document was indexed. +`_index` | The name of the index. +`_id` | The document's ID. +`_version` | The document's version. Incremented each time the document is updated. +`result` | The result of the update operation. Returns `updated` when the document was successfully updated, `created` when an upsert operation creates a new document, or `noop` when no changes were made. +`_shards` | Detailed information about the cluster's shards. +`_shards.total` | The total number of shards (primary and replicas). +`_shards.successful` | The number of shards that successfully processed the update operation. +`_shards.failed` | The number of shards that failed to process the update operation. +`_seq_no` | The sequence number assigned when the document was updated. Used for optimistic concurrency control. +`_primary_term` | The primary term assigned when the document was updated. Used with `_seq_no` for optimistic concurrency control. + +## Advanced script examples + +The following examples demonstrate advanced scripting capabilities for document updates. + +#### Adding items to an array + +You can use a script to add items to an array field. The following example adds a gadget to the `gadgets` array (the gadget is added even if it already exists in the list): + + +{% capture step1_rest %} +POST /sample-index1/_update/1 +{ + "script": { + "source": "ctx._source.gadgets.add(params.gadget)", + "lang": "painless", + "params": { + "gadget": "grappling hook" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "script": { + "source": "ctx._source.gadgets.add(params.gadget)", + "lang": "painless", + "params": { + "gadget": "grappling hook" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Removing items from an array + +You can use a script to remove items from an array. The Painless `remove` function takes the array index of the element you want to remove. To avoid a runtime error, first check that the item exists. If the list contains duplicate items, this script removes only one occurrence: + + +{% capture step1_rest %} +POST /sample-index1/_update/1 +{ + "script": { + "source": "if (ctx._source.gadgets.contains(params.gadget)) { ctx._source.gadgets.remove(ctx._source.gadgets.indexOf(params.gadget)) }", + "lang": "painless", + "params": { + "gadget": "grappling hook" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "script": { + "source": "if (ctx._source.gadgets.contains(params.gadget)) { ctx._source.gadgets.remove(ctx._source.gadgets.indexOf(params.gadget)) }", + "lang": "painless", + "params": { + "gadget": "grappling hook" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Adding and removing fields + +You can use scripts to add or remove fields from a document. The following example adds a new field: + + +{% capture step1_rest %} +POST /sample-index1/_update/1 +{ + "script": "ctx._source.bat_signal_location = 'Gotham City Hall'" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "script": "ctx._source.bat_signal_location = 'Gotham City Hall'" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The following example removes a field: + + +{% capture step1_rest %} +POST /sample-index1/_update/1 +{ + "script": "ctx._source.remove('bat_signal_location')" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "script": "ctx._source.remove('bat_signal_location')" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Changing the operation type + +You can use scripts to change the operation that is executed based on document content. The following example deletes the document if the `gadgets` field contains `kryptonite`; otherwise, it performs no operation (`noop`): + + +{% capture step1_rest %} +POST /sample-index1/_update/1 +{ + "script": { + "source": "if (ctx._source.gadgets.contains(params.gadget)) { ctx.op = 'delete' } else { ctx.op = 'none' }", + "lang": "painless", + "params": { + "gadget": "kryptonite" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.update( + id = "1", + index = "sample-index1", + body = { + "script": { + "source": "if (ctx._source.gadgets.contains(params.gadget)) { ctx.op = 'delete' } else { ctx.op = 'none' }", + "lang": "painless", + "params": { + "gadget": "kryptonite" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Error responses + +The following examples show common error responses you may encounter when using the Update Document API. + +### Document not found + +If you try to update a document that doesn't exist in the index without using the upsert operation, OpenSearch returns a 404 error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "document_missing_exception", + "reason": "[1]: document missing", + "index": "sample-index1", + "shard": "0", + "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA" + } + ], + "type": "document_missing_exception", + "reason": "[1]: document missing", + "index": "sample-index1", + "shard": "0", + "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA" + }, + "status": 404 +} +``` + +To avoid this error, use the [upsert operation](#using-the-upsert-operation) to create the document if it doesn't exist. + +### Version conflict + +If you're using optimistic concurrency control with `if_seq_no` and `if_primary_term` parameters and the document has been modified since you last read it, OpenSearch returns a 409 conflict error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "version_conflict_engine_exception", + "reason": "[1]: version conflict, required seqNo [3], primary term [1]. current document has seqNo [4] and primary term [1]", + "index": "sample-index1", + "shard": "0", + "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA" + } + ], + "type": "version_conflict_engine_exception", + "reason": "[1]: version conflict, required seqNo [3], primary term [1]. current document has seqNo [4] and primary term [1]", + "index": "sample-index1", + "shard": "0", + "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA" + }, + "status": 409 +} +``` + +To handle this error, retrieve the latest version of the document and retry the update with the correct `if_seq_no` and `if_primary_term` values, or use the `retry_on_conflict` parameter to automatically retry the operation. + +### Script compilation error + +If there's an error in your Painless script, OpenSearch returns a 400 error with details about the compilation failure: + +```json +{ + "error": { + "root_cause": [ + { + "type": "illegal_argument_exception", + "reason": "failed to execute script" + } + ], + "type": "illegal_argument_exception", + "reason": "failed to execute script", + "caused_by": { + "type": "script_exception", + "reason": "compile error", + "script_stack": [ + "ctx._source.value = params.newValue", + " ^---- HERE" + ], + "script": "ctx._source.value = params.newValue", + "lang": "painless", + "position": { + "offset": 25, + "start": 0, + "end": 34 + }, + "caused_by": { + "type": "illegal_argument_exception", + "reason": "cannot resolve symbol [params.newValue]" + } + } + }, + "status": 400 +} +``` + +Review the `script_stack` and `caused_by` fields in the error response to identify and fix the script error. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/write/update`. diff --git a/_api-reference/grpc-apis/bulk.md b/_api-reference/grpc-apis/bulk.md new file mode 100644 index 00000000..8195bb25 --- /dev/null +++ b/_api-reference/grpc-apis/bulk.md @@ -0,0 +1,604 @@ +--- +layout: default +title: Bulk (gRPC) +parent: gRPC APIs +nav_order: 20 +--- + +# Bulk API (gRPC) +**Introduced 3.0** +{: .label .label-purple } + +The gRPC Bulk API provides an efficient, binary-encoded alternative to the [HTTP Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) for performing multiple document operations—such as indexing, updating, and deleting—in a single call. This service uses protocol buffers and mirrors the REST API in terms of parameters and structure. + +## Prerequisite + +To submit gRPC requests, you must have a set of protobufs on the client side. For ways to obtain the protobufs, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). + +## gRPC service and method + +gRPC Document APIs reside in the [DocumentService](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/document_service.proto#L22). + +You can submit bulk requests by invoking the [`Bulk`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/document_service.proto#L24) gRPC method within the `DocumentService`. The method takes a [`BulkRequest`](#bulkrequest-fields) and returns a [`BulkResponse`](#bulkresponse-fields). + +## Document format + +In gRPC, documents must be provided and returned as bytes. Use Base64 encoding to provide documents in a gRPC request. +{: .note } + +For example, consider the following document in a regular Bulk API request: + +```json +"doc": "{\"title\": \"Inception\", \"year\": 2010}" +``` + +For a gRPC Bulk API request, provide the same document in Base64 encoding: + +```json +"doc": "eyJ0aXRsZSI6ICJJbmNlcHRpb24iLCAieWVhciI6IDIwMTB9" +``` + +## BulkRequest fields + +The [`BulkRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L851) message is the top-level container for a gRPC bulk operation. It accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `bulk_request_body` | `repeated `[`BulkRequestBody`](#bulkrequestbody-fields) | The list of bulk operations, each containing one of the operation types (`index`/`create`/`update`/`delete`). Required. | +| `index` | `string` | The default index for all operations unless overridden in `bulk_request_body`. Specifying the `index` in the `BulkRequest` means that you don't need to include it in the [BulkRequestBody](#bulkrequestbody-fields). Optional. | +| `x_source` | [`SourceConfigParam`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1251) | Controls whether to return the full `_source`, no `_source`, or only specific fields from `_source` in the response. Optional. | +| `x_source_excludes` | `repeated string` | Fields to exclude from `source`. Optional. | +| `x_source_includes` | `repeated string` | Fields to include from `source`. Optional. | +| `pipeline` | `string` | The preprocessing ingest pipeline ID. Optional. | +| `refresh` | [`Refresh`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3552) | Whether to refresh shards after indexing. Optional. | +| `require_alias` | `bool` | If `true`, actions must target an alias. Optional. | +| `routing` | `string` | The routing value for shard assignment. Optional. | +| `timeout` | `string` | The timeout duration (for example, `1m`). Optional. | +| `type` (Deprecated) | `string` | The document type (always `_doc`). Optional. | +| `wait_for_active_shards` | [`WaitForActiveShards`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1162) | The minimum number of active shards to wait for. Optional. | +| `global_params` | [`GlobalParams`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1150) | Global parameters for the request. Optional. | + + +## BulkRequestBody fields + +The [`BulkRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L894) message represents a single document-level operation within a `BulkRequest`. It accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `operation_container` | [`OperationContainer`](#operationcontainer-fields) | The operation to perform (`index`, `create`, `update`, or `delete`). Required. | +| `update_action` | [`UpdateAction`](#updateaction-fields) | Additional update-specific options. Optional. | +| `object` | `bytes` | The full document content used with `create` and `index` operations. Optional. | + +## OperationContainer fields + +The [`OperationContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L918) message contains exactly one operation type. It accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `index` | [`IndexOperation`](#index) | Index a document. Replaces the document if it already exists. | +| `create` | [`WriteOperation`](#create) | Create a new document. Fails if the document already exists. | +| `update` | [`UpdateOperation`](#update) | Partially update a document or use upsert/script options. | +| `delete` | [`DeleteOperation`](#delete) | Delete a document by ID. | + +## UpdateAction fields + +The [`UpdateAction`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L936) message provides additional options for update operations. It accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `detect_noop` | `bool` | If `true`, skips the update if the document content hasn't changed. Optional. Default is `true`. | +| `doc` | `bytes` | Partial or full document data for `update` operations. Optional. | +| `doc_as_upsert` | `bool` | If `true`, treats the document as the full upsert document if the target document doesn't exist. Only valid for the `update` operation. Optional. | +| `script` | [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | A script to apply to the document (used with `update`). Optional. | +| `scripted_upsert` | `bool` | If `true`, executes the script whether or not the document exists. Optional. | +| `upsert` | `bytes` | The full document to use if the target does not exist. Used with `script`. Optional. | +| `x_source` | [`SourceConfig`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1267) | Controls how the document source is fetched or filtered. Optional. | + + +### Create + +`WriteOperation` adds a new document only if it doesn't already exist. + +The document itself must be provided in the `object` field of the `BulkRequestBody` message. + +The following optional fields can also be provided. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `x_id` | `string` | The document ID. If omitted, one is auto-generated. Optional. | +| `x_index` | `string` | The target index. Required if not set globally in the `BulkRequest`. Optional. | +| `routing` | `string` | A custom routing value used to control shard placement. Optional. | +| `pipeline` | `string` | The preprocessing ingest pipeline ID. Optional. | +| `require_alias` | `bool` | If `true`, requires that all actions target an index alias rather than an index. Default is `false`. Optional. | + +#### Example request + +The following example shows a bulk request with a `create` operation. It creates a document with the ID `tt1375666` in the `movies` index. The document content, provided in Base64 encoding, represents `{"title": "Inception", "year": 2010}`: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "create": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "object": "eyJ0aXRsZSI6ICJJbmNlcHRpb24iLCAieWVhciI6IDIwMTB9" + } + ] +} +``` + +### Delete + +The `DeleteOperation` removes a document by ID. It accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `x_id` | `string` | The ID of the document to delete. Required. | +| `x_index` | `string` | The target index. Required if not set globally in the `BulkRequest`. Optional. | +| `routing` | `string` | A custom routing value used to control shard placement. Optional. | +| `if_primary_term` | `int64` | Used for concurrency control. The operation only runs if the document's primary term matches this value. Optional. | +| `if_seq_no` | `int64` | Used for concurrency control. The operation only runs if the document's sequence number matches this value. Optional. | +| `version` | `int64` | The explicit document version for concurrency control. Optional. | +| `version_type` | [`VersionType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3544) | Controls version matching behavior. Optional. | + +#### Example request + +The following example shows a bulk request with a `delete` operation. It deletes a document with the ID `tt1392214` from the `movies` index: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "delete": { + "x_index": "movies", + "x_id": "tt1392214" + } + } + } + ] +} +``` +{% include copy.html %} + +### Index + +The `IndexOperation` creates or overwrites a document. If an ID is not provided, one is generated. + +The document itself is provided in the `object` field of the `BulkRequestBody` message. + +The following optional fields can also be provided. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `x_id` | `string` | The document ID. If omitted, one is auto-generated. Optional. | +| `x_index` | `string` | The target index. Required only if not set globally in the `BulkRequest`. | +| `routing` | `string` | A custom routing value used to control shard placement. Optional. | +| `if_primary_term` | `int64` | Used for concurrency control. The operation only runs if the document's primary term matches this value. Optional. | +| `if_seq_no` | `int64` | Used for concurrency control. The operation only runs if the document's sequence number matches this value. Optional. | +| `op_type` | [`OpType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3538) | The operation type. Controls the overwriting behavior. Valid values are `index` (default) and `create`. Optional. | +| `version` | `int64` | The explicit document version for concurrency control. Optional. | +| `version_type` | [`VersionType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3544) | Controls version matching behavior. Optional. | +| `pipeline` | `string` | The preprocessing ingest pipeline ID. Optional. | +| `require_alias` | `bool` | If `true`, requires that all actions target an index alias rather than an index. Default is `false`. Optional. | + + +#### Example request + +The following example shows a bulk request with an `index` operation. It indexes a Base64-encoded document with the ID `tt0468569` into the `movies` index: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "index": { + "x_index": "movies", + "x_id": "tt0468569" + } + }, + "object": "eyJ0aXRsZSI6ICJUaGUgRGFyayBLbmlnaHQiLCAieWVhciI6IDIwMDh9" + } + ] +} +``` +{% include copy.html %} + +### Update + +The `UpdateOperation` performs partial document updates. + +The update options are provided in the `update_action` field within the `BulkRequestBody` message. + +All `UpdateOperation` fields, listed in the following table, are optional except for `x_id`. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `x_id` | `string` | The ID of the document to update. Required. | +| `x_index` | `string` | The target index. Required if not set globally in the `BulkRequest`. Optional. | +| `routing` | `string` | A custom routing value used to control shard placement. Optional. | +| `if_primary_term` | `int64` | Used for concurrency control. The operation only runs if the document's primary term matches this value. Optional. | +| `if_seq_no` | `int64` | Used for concurrency control. The operation only runs if the document's sequence number matches this value. Optional. | +| `require_alias` | `bool` | If `true`, requires that all actions target an index alias rather than an index. Default is `false`. Optional. | +| `retry_on_conflict` | `int32` | The number of times to retry the operation if a version conflict occurs. Optional. | + + +#### Example request + +The following example shows a bulk request with an `update` operation. It will update a document with the ID `tt1375666` in the `movies` index to `{"year": 2011}`: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "update": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "update_action": { + "doc": "eyJ5ZWFyIjogMjAxMX0=", + "detect_noop": true + } + } + ] +} +``` +{% include copy.html %} + +### Upsert + +The `upsert` operation updates the document if it already exists. Otherwise, it creates a new document using the provided document content. + +To upsert a document, provide an `UpdateOperation` and specify `doc_as_upsert` as `true` in the `BulkRequestBody`. The document to be upserted should be provided in the `doc` field. + +#### Example request + +The following example shows a bulk request with an `upsert` operation. It updates the `year` field of the document with ID `tt1375666` in the `movies` index to `{"year": 2012}`: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "update": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "update_action": { + "doc": "eyJ5ZWFyIjogMjAxMn0=", + "doc_as_upsert": true + } + } + ] +} +``` +{% include copy.html %} + +### Script + +Run a stored or inline script to modify a document. + +To specify a script, provide an `UpdateOperation` and a `script` field in the `BulkRequestBody`. + +#### Example request + +The following example shows a bulk request with a `script` operation. It increments the `year` field of the document with the ID `tt1375666` in the `movies` index by 1: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "update": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "update_action": { + "script": { + "inline": { + "source": "ctx._source.year += 1", + "lang": { + "builtin": "BUILTIN_SCRIPT_LANGUAGE_PAINLESS" + } + } + } + } + } + ] +} +``` +{% include copy.html %} + + +## Response fields + +The gRPC Bulk API provides the following response fields. + +### BulkResponse fields + +The [`BulkResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1059) message is returned directly from the `Bulk` gRPC method and provides a summary and per-item result of a bulk operation. It contains the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `errors` | `bool` | Indicates whether any of the operations in the bulk request failed. If any operation fails, the response's `errors` field will be `true`. You can iterate over the individual `Item` actions for more detailed information.| +| `items` | `repeated` [`Item`](#item-fields) | The result of all operations in the bulk request, in the order they were submitted. | +| `took` | `int64` | The amount of time taken to process the bulk request, in milliseconds. | +| `ingest_took` | `int64` | The amount of time taken to process documents through an ingest pipeline, in milliseconds. | + + +### Item fields + +Each `Item` in the response corresponds to a single operation in the request. For each operation, only one of the following fields is provided. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `create` | [`ResponseItem`](#responseitem-fields) | The result of the `CreateOperation`. | +| `delete` | [`ResponseItem`](#responseitem-fields) | The result of the `DeleteOperation`. | +| `index` | [`ResponseItem`](#responseitem-fields) | The result of the `IndexOperation`. | +| `update` | [`ResponseItem`](#responseitem-fields) | The result of the `UpdateOperation`. | + + +### ResponseItem fields + +Each `ResponseItem` corresponds to a single operation in the request. It contains the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `type` | `string` | The document type. | +| `id` | `string` | The document ID associated with the operation. | +| `index` | `string` | The name of the index associated with the operation. If a data stream was targeted, this is the backing index. | +| `status` | `int32` | The HTTP status code returned for the operation. *(Note: This field may be replaced with a gRPC code in the future.)* | +| `error` | [`ErrorCause`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1287) | Contains additional information about a failed operation. | +| `primary_term` | `int64` | The primary term assigned to the document. | +| `result` | `string` | The operation result. Valid values are `created`, `deleted`, and `updated`. | +| `seq_no` | `int64` | A sequence number assigned to the document to maintain version order. | +| `shards` | [`ShardInfo`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1332) | Shard information for the operation (only returned for successful actions). | +| `version` | `int64` | The document version (only returned for successful actions). | +| `forced_refresh` | `bool` | If `true`, forces the document to become visible immediately after the operation. | +| `get` | [`InlineGetDictUserDefined`](#inlinegetdictuserdefined-fields) | Contains the document `source` returned from an inline get, if requested. | + +### InlineGetDictUserDefined fields + +The [`InlineGetDictUserDefined`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1126) message contains the document source returned from an inline get operation. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `metadata_fields` | `optional` [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | The document's metadata fields. | +| `fields` | `optional` [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | The document's stored fields. | +| `found` | `bool` | Whether the document exists. | +| `x_seq_no` | `optional int64` | The document's sequence number. | +| `x_primary_term` | `optional int64` | The document's primary term. | +| `x_routing` | `optional string` | The document's routing value. | +| `x_source` | `optional bytes` | The document's source data. | + +## Example response + +```json +{ + "errors": false, + "items": [ + { + "index": { + "x_id": "2", + "x_index": "my_index", + "status": 201, + "x_primary_term": 1, + "result": "created", + "x_seq_no": 0, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 1, + "forced_refresh": true + } + }, + { + "create": { + "x_id": "1", + "x_index": "my_index", + "status": 201, + "x_primary_term": 1, + "result": "created", + "x_seq_no": 0, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 1, + "forced_refresh": true + } + }, + { + "update": { + "x_id": "2", + "x_index": "my_index", + "status": 200, + "x_primary_term": 1, + "result": "updated", + "x_seq_no": 1, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 2, + "forced_refresh": true, + "get": { + "found": true, + "x_seq_no": 1, + "x_primary_term": 1, + "x_source": "e30=" + } + } + }, + { + "delete": { + "x_id": "2", + "x_index": "my_index", + "status": 200, + "x_primary_term": 1, + "result": "deleted", + "x_seq_no": 2, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 3, + "forced_refresh": true + } + } + ], + "took": 87, + "ingest_took": 0 +} +``` +{% include copy.html %} + + +## Java gRPC client example + +The following example shows a Java client-side program that submits an example bulk gRPC request and then checks whether there were any errors in the bulk response: + +```java +import org.opensearch.protobufs.*; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import com.google.protobuf.ByteString; + +public class BulkClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + DocumentServiceGrpc.DocumentServiceBlockingStub stub = DocumentServiceGrpc.newBlockingStub(channel); + + // Create an index operation + IndexOperation indexOp = IndexOperation.newBuilder() + .setXIndex("my-index") + .setXId("1") + .build(); + + BulkRequestBody indexBody = BulkRequestBody.newBuilder() + .setOperationContainer(OperationContainer.newBuilder().setIndex(indexOp).build()) + .setObject(ByteString.copyFromUtf8("{\"field\": \"value\"}")) + .build(); + + // Create a delete operation + DeleteOperation deleteOp = DeleteOperation.newBuilder() + .setXIndex("my-index") + .setXId("2") + .build(); + + BulkRequestBody deleteBody = BulkRequestBody.newBuilder() + .setOperationContainer(OperationContainer.newBuilder().setDelete(deleteOp).build()) + .build(); + + // Build the bulk request + BulkRequest request = BulkRequest.newBuilder() + .setIndex("my-index") + .addBulkRequestBody(indexBody) + .addBulkRequestBody(deleteBody) + .build(); + + // Execute the bulk request + try { + BulkResponse response = stub.bulk(request); + + // Handle the response + System.out.println("Bulk errors: " + response.getErrors()); + System.out.println("Bulk took: " + response.getTook() + " ms"); + if (response.hasIngestTook()) { + System.out.println("Ingest took: " + response.getIngestTook() + " ms"); + } + + // Process individual items + for (Item item : response.getItemsList()) { + if (item.hasIndex()) { + System.out.println("Index operation: " + item.getIndex().getStatus()); + } else if (item.hasDelete()) { + System.out.println("Delete operation: " + item.getDelete().getStatus()); + } else if (item.hasCreate()) { + System.out.println("Create operation: " + item.getCreate().getStatus()); + } else if (item.hasUpdate()) { + System.out.println("Update operation: " + item.getUpdate().getStatus()); + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC request failed with status: " + e.getStatus()); + System.err.println("Error message: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` +{% include copy.html %} + +## Python gRPC client example + +The following example shows how to send the same request using a Python client application. + +First, install the `opensearch-protobufs` package using `pip`: + +```bash +pip install opensearch-protobufs==1.2.0 +``` +{% include copy.html %} + +Use the following code to send the request: + +```python +import grpc + +from opensearch.protobufs.schemas import * +from opensearch.protobufs.services import DocumentServiceStub + +channel = grpc.insecure_channel( + target="localhost:9400", +) + +document_stub = DocumentServiceStub(channel) + +# Add documents to a request body +requestBody = BulkRequestBody( + operation_container=OperationContainer(index=IndexOperation()) +) +requestBody.object = "{\"field\": \"value\"}".encode('utf-8') + +# Append to a bulk request +request = BulkRequest() +request.index = "my-index" +request.bulk_request_body.append(requestBody) + +# Send request and handle response +try: + response = document_stub.Bulk(request=request) + if response.items: + print("Received {} response items".format(len(response.items))) + print(response.items) +except grpc.RpcError as e: + if e.code() == StatusCode.UNAVAILABLE: + print("Failed to reach server: {}".format(e)) + elif e.code() == StatusCode.PERMISSION_DENIED: + print("Permission denied: {}".format(e)) + elif e.code() == StatusCode.INVALID_ARGUMENT: + print("Invalid argument: {}".format(e)) +finally: + channel.close() +``` +{% include copy.html %} diff --git a/_api-reference/grpc-apis/execute-agent-stream.md b/_api-reference/grpc-apis/execute-agent-stream.md new file mode 100644 index 00000000..d5d08d93 --- /dev/null +++ b/_api-reference/grpc-apis/execute-agent-stream.md @@ -0,0 +1,193 @@ +--- +layout: default +title: Execute agent stream (gRPC) +parent: gRPC APIs +nav_order: 50 +--- + +# Execute Agent Stream API (gRPC) +**Introduced 3.8** +{: .label .label-purple } + +The gRPC Execute Agent Stream API provides a binary interface for streaming the execution of an agent using protocol buffers over gRPC. The server streams response chunks to the client as the agent generates them, so the client can begin processing output before execution completes. Use streaming for conversational agents that produce token-by-token output from large language models (LLMs). + +You can stream agent execution over either REST or gRPC. Both transports return the same incrementally generated output, so choose the one that best fits your client: + +- **REST streaming** uses server-sent events (SSE) over HTTP, which browsers, standard HTTP clients, and command line tools such as cURL support directly. This is an experimental feature and is not recommended for use in a production environment. For more information, see [Execute Agent Stream API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-stream-agent/). +- **gRPC streaming** uses protocol buffers over HTTP/2. This transport provides lower serialization overhead and smaller payloads, native server streaming semantics with HTTP/2 flow control and connection multiplexing, and a strongly typed schema from which you can generate clients in any [gRPC-supported language](https://grpc.io/docs/languages/). + +Streaming agent execution is supported for agents that use the following externally hosted models: + +- [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) +- [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +## Prerequisites + +Before using the gRPC Execute Agent Stream API, ensure that you have fulfilled the following prerequisites: + +- Enable gRPC transport on the cluster. For more information, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). +- Obtain the ML Commons protobufs on the client side. For ways to obtain the protobufs, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). +- Register an agent that uses a supported streaming model. For agent and connector configuration, see [Execute Agent Stream API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-stream-agent/#step-2-register-a-compatible-externally-hosted-model). + +## gRPC service and method + +The gRPC Execute Agent Stream API resides in the [`MLService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L22) service. + +You can submit streaming agent execution requests by invoking the [`ExecuteAgentStream`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L27) method within the `MLService`. The method takes an [`MlExecuteAgentStreamRequest`](#mlexecuteagentstreamrequest-fields) and returns a stream of [`PredictResponse`](#response-fields) messages. + +`ExecuteAgentStream` is a server streaming remote procedure call (RPC): the client sends a single request, and the server returns a sequence of response messages. The final message sets `is_last` to `true`, and the server then closes the stream. +{: .note} + +## Request fields + +The gRPC Execute Agent Stream API supports the following request fields. + +### MlExecuteAgentStreamRequest fields + +The [`MlExecuteAgentStreamRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3396) message accepts the following fields. + +| Field | Protobuf type | Required | Description | +| :---- | :---- | :---- | :---- | +| `agent_id` | `string` | Required | The ID of the agent to execute. | +| `ml_execute_agent_stream_request_body` | [`MLExecuteAgentStreamRequestBody`](#mlexecuteagentstreamrequestbody-fields) | Required | The request payload containing the execution parameters. | + + +### MLExecuteAgentStreamRequestBody fields + + +The [`MLExecuteAgentStreamRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3318) message accepts the following fields. + +| Field | Protobuf type | Required | Description | +| :---- | :---- | :---- | :---- | +| `parameters` | [`Parameters`](#parameters-fields) | Required | The input parameters passed to the agent. | + +### Parameters fields + +For agent execution, the [`Parameters`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3356) message accepts the following field. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `question` | `string` | The input question sent to the agent. | + +## Response fields + +The server streams a sequence of [`PredictResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3367) messages. Each message carries one chunk of the generated output and provides the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `inference_results` | `repeated InferenceResults` | The inference results for the chunk. | +| `inference_results.output` | `repeated Output` | The output objects for each inference result. | +| `inference_results.output.name` | `string` | The name of the output field (typically, `response`). | +| `inference_results.output.result` | `string` | The values of the `memory_id` and `parent_interaction_id` fields. | +| `inference_results.output.data_as_map` | `DataAsMap` | The response content and metadata for the chunk. | +| `inference_results.output.data_as_map.content` | `string` | The text content of the chunk. Concatenate the `content` values across chunks to reconstruct the full response. | +| `inference_results.output.data_as_map.is_last` | `bool` | Whether this is the final chunk in the stream. When `true`, no further messages are sent. | + +## Example request + +The following example shows the JSON representation of the gRPC request message. Replace the `agent_id` and `question` with values that match your agent configuration: + +```json +{ + "agent_id": "your_agent_id", + "ml_execute_agent_stream_request_body": { + "parameters": { + "question": "List indices in my cluster" + } + } +} +``` +{% include copy.html %} + +The following example shows a Java gRPC client that streams the execution of a conversational agent. Replace the agent ID and question with values that match your agent configuration: + +```java +import org.opensearch.protobufs.*; +import org.opensearch.protobufs.services.MLServiceGrpc; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +import java.util.Iterator; + +public class ExecuteAgentStreamClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + // Create a gRPC stub for ML operations + MLServiceGrpc.MLServiceBlockingStub mlStub = MLServiceGrpc.newBlockingStub(channel); + + // Build the request parameters for the agent + Parameters parameters = Parameters.newBuilder() + .setQuestion("List indices in my cluster") + .build(); + + // Create the streaming agent execution request + MlExecuteAgentStreamRequest request = MlExecuteAgentStreamRequest.newBuilder() + .setAgentId("your_agent_id") + .setMlExecuteAgentStreamRequestBody(MLExecuteAgentStreamRequestBody.newBuilder() + .setParameters(parameters) + .build()) + .build(); + + // Execute the request and read the streamed response + try { + Iterator responses = mlStub.executeAgentStream(request); + while (responses.hasNext()) { + PredictResponse response = responses.next(); + for (InferenceResults results : response.getInferenceResultsList()) { + for (Output output : results.getOutputList()) { + DataAsMap chunk = output.getDataAsMap(); + System.out.print(chunk.getContent()); + if (chunk.getIsLast()) { + System.out.println("\n[stream complete]"); + } + } + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC execute agent stream request failed with status: " + e.getStatus()); + System.err.println("Error message: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` +{% include copy.html %} + +## Example response + +The server returns a sequence of `PredictResponse` messages. Each message carries a chunk of generated text in the `content` field, and the final message sets `isLast` to `true`. The following example shows the JSON representation of a streamed chunk: + +```json +{ + "inferenceResults": [ + { + "output": [ + { + "name": "memory_id", + "result": "6CMnkJ8BLGHoqtB13ipp" + }, + { + "name": "parent_interaction_id", + "result": "6SMnkJ8BLGHoqtB13irB" + }, + { + "name": "response", + "dataAsMap": { + "content": "Hello", + "isLast": false + } + } + ] + } + ] +} +``` + +## Related documentation + +- [Execute Agent Stream API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-stream-agent/) -- The REST equivalent for streaming agent execution +- [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/) -- gRPC transport configuration and client requirements diff --git a/_api-reference/grpc-apis/index.md b/_api-reference/grpc-apis/index.md new file mode 100644 index 00000000..536191b3 --- /dev/null +++ b/_api-reference/grpc-apis/index.md @@ -0,0 +1,129 @@ +--- +layout: default +title: gRPC APIs +has_children: true +has_toc: false +nav_order: 140 +description: "Reference for the OpenSearch gRPC APIs, including the bulk and k-NN search operations that use protocol buffers for high-performance communication." +redirect_from: + - /api-reference/grpc-apis/ +--- + +# gRPC APIs +**Introduced 3.0** +{: .label .label-purple } + +**Bulk and k-NN search generally available 3.2** +{: .label .label-green } + +The gRPC [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/bulk/) and [k-NN search queries]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/knn/) are generally available. These use [protobuf version 1.2.0](https://github.com/opensearch-project/opensearch-protobufs/releases/tag/1.2.0). However, expect updates to the protobuf structure as the feature matures in upcoming versions. Other gRPC search functionality remains experimental and not recommended for production use. For updates on the progress of these features or to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/16787). +{: .note} + +The OpenSearch gRPC functionality provides an alternative, high-performance transport layer using [gRPC](https://grpc.io/) for communication with OpenSearch. It uses protocol buffers over gRPC for lower overhead and faster serialization. This reduces overhead, speeds up serialization, and improves request-side latency, based on initial benchmarking results. For more information, see [Performance Benefits](#grpc-performance-benefits). + +## Supported APIs + +The following gRPC APIs are supported: +- [Bulk]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/bulk/) **Generally available 3.2** +- [k-NN]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/knn/) **Generally available 3.2** +- [Search]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/search/) (for select query types) +- [Predict Model Stream]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/predict-model-stream/) +- [Execute Agent Stream]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/execute-agent-stream/) + +## How to use gRPC APIs + +To use gRPC APIs, follow these steps: +1. Enable gRPC transport by configuring the necessary [gRPC settings](#grpc-settings). + +2. To submit gRPC requests, you must have a set of protobufs on the client side. You can obtain the protobufs in the following ways. + +| Language | Distribution method | Instructions | +| :------- | :------------------ | :----------- | +| Java | Maven Central repository | Download the `opensearch-protobufs` jar from the [Maven Central repository](https://repo1.maven.org/maven2/org/opensearch/protobufs/1.2.0). | +| Python | PyPI repository | Download the `opensearch-protobufs` package from the [PyPI repository](https://pypi.org/project/opensearch-protobufs/1.2.0). | +| Other languages | GitHub repository (raw protobufs) | Download the raw protobuf schema from the [OpenSearch Protobufs GitHub repository (v1.2.0)](https://github.com/opensearch-project/opensearch-protobufs/releases/tag/1.2.0). You can then generate client-side code using the protocol buffer compilers for the [supported languages](https://grpc.io/docs/languages/). | + + +## gRPC settings + +The `transport-grpc` module is included by default with OpenSearch installations. To enable it, add the following settings to `opensearch.yml`: + +```yaml +aux.transport.types: [transport-grpc] +aux.transport.transport-grpc.port: '9400-9500' // optional +``` +{% include copy.html %} + +Alternatively, configure a secure transport protocol using the following settings: + +```yaml +aux.transport.types: [secure-transport-grpc] +aux.transport.transport-grpc.port: '9400-9500' // optional +``` +{% include copy.html %} + +Configure additional settings if needed (see [Advanced gRPC settings](#advanced-grpc-settings)): + +```yaml +grpc.host: localhost +grpc.publish_host: 10.74.124.163 +grpc.bind_host: 0.0.0.0 +``` +{% include copy.html %} + +### Advanced gRPC settings + +OpenSearch supports the following advanced settings for gRPC communication. These settings can be configured in `opensearch.yml`. + +| Setting name | Description | Example value | Default value | +| :---- | :---- | :---- | :---- | +| `grpc.publish_port` | The external port number that this node uses to publish itself to peers for gRPC transport. | `9400` | `-1` (disabled) | +| `grpc.host` | A list of addresses the gRPC server will bind to. | `["0.0.0.0"]` | `[]` | +| `grpc.bind_host` | A list of addresses to bind the gRPC server to. Can be distinct from publish hosts. | `["0.0.0.0", "::"]` | Value of `grpc.host` | +| `grpc.publish_host` | A list of hostnames or IPs published to peers for client connections. | `["thisnode.example.com"]` | Value of `grpc.host` | +| `grpc.netty.worker_count` | The number of Netty worker threads for the gRPC server. Controls concurrency and parallelism. | `2` | Number of processors | +| `grpc.netty.executor_count` | The number of threads in the fork-join pool for processing gRPC service calls. Controls request processing parallelism. | `32` | `2 * number of processors` | +| `grpc.netty.max_concurrent_connection_calls` | The maximum number of simultaneous in-flight requests allowed per client connection. | `200` | `100` | +| `grpc.netty.max_connection_age` | The maximum age a connection can reach before being gracefully closed. Supports time units like `ms`, `s`, or `m`. See [Time units]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). | `500ms` | Not set (no limit) | +| `grpc.netty.max_connection_idle` | The maximum duration for which a connection can be idle before being closed. Supports time units like `ms`, `s`, or `m`. See [Time units]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). | `2m` | Not set (no limit) | +| `grpc.netty.keepalive_timeout` | The amount of time to wait for `keepalive` ping acknowledgment before closing the connection. Supports [time units]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). | `1s` | Not set | +| `grpc.netty.max_msg_size` | The maximum inbound message size for gRPC requests. Supports units like `b`, `kb`, `mb`, or `gb`. See [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). | `10mb` or `10485760` | `10mb` | + +### Example configuration + +The following is an example of a complete gRPC configuration in `opensearch.yml`: + +```yaml +# Basic gRPC transport configuration +aux.transport.types: [transport-grpc] +aux.transport.transport-grpc.port: '9400-9500' + +# Advanced gRPC settings +grpc.host: ["0.0.0.0"] +grpc.bind_host: ["0.0.0.0", "::"] +grpc.publish_host: ["thisnode.example.com"] +grpc.publish_port: 9400 +grpc.netty.worker_count: 4 +grpc.netty.max_concurrent_connection_calls: 200 +grpc.netty.max_connection_age: 500ms +grpc.netty.max_connection_idle: 2m +grpc.netty.keepalive_timeout: 1s +grpc.netty.max_msg_size: 10mb +``` +{% include copy.html %} + +These settings are similar to the [HTTP Network settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/network-settings/#advanced-http-settings) but specifically apply to gRPC communication. + + +## gRPC performance benefits + +Using gRPC APIs provides several advantages over HTTP APIs: + +- **Reduced latency**: Binary protocol buffers eliminate JSON parsing overhead. +- **Higher throughput**: More efficient network utilization for high-frequency queries. +- **Lower CPU usage**: Reduced serialization and deserialization costs. +- **Type safety**: Protocol buffer schemas provide compile-time validation. +- **Smaller payload sizes**: Binary encoding reduces network traffic. + +### Additional performance tip +Indexing documents as supported binary formats, such as SMILE, will usually incur lower latency than indexing/searching for them as JSON. Both indexing and searching latency should be reduced. diff --git a/_api-reference/grpc-apis/knn.md b/_api-reference/grpc-apis/knn.md new file mode 100644 index 00000000..934af453 --- /dev/null +++ b/_api-reference/grpc-apis/knn.md @@ -0,0 +1,162 @@ +--- +layout: default +title: k-NN (gRPC) +parent: gRPC APIs +nav_order: 30 +--- + +# k-NN (gRPC) API +**Introduced 3.2** +{: .label .label-purple } + + +The gRPC k-NN API is generally available. However, expect updates to the protobuf structure as the feature matures in upcoming versions. + +The gRPC k-NN API provides an efficient, binary-encoded interface for performing k-nearest neighbor searches using protocol buffers over gRPC. The k-NN plugin offers a specific search query type for vector similarity searches. This API offers superior performance compared to the traditional HTTP-based approach, making it ideal for large-scale machine learning and vector database applications. + +For information about HTTP-based k-NN queries, see [k-NN query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/k-nn/). + +## Prerequisite + +To submit gRPC requests, you must have a set of protobufs on the client side. For ways to obtain the protobufs, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). + +## gRPC service and method + +gRPC k-NN APIs reside in the [`SearchService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L22), the same service used for general search operations. + +You can submit k-NN search requests by invoking the [`Search`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L23) gRPC method within the `SearchService`, using a [`KnnQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2023) within the search request. The method takes a [`SearchRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L20) and returns a [`SearchResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L262). + +The gRPC implementation uses the same underlying k-NN functionality as the HTTP API while providing improved performance through protocol buffer serialization. + +## KnnQuery fields + +The gRPC k-NN API uses the [`KnnQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2023) message within a [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) for k-NN searches. The `KnnQuery` message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | The vector field against which to run the search query. Required. | +| `vector` | `repeated float` | A query vector. Must have the same number of dimensions as the vector field. Optional. | +| `k` | `int32` | The number of nearest neighbors to return as top hits. Optional. | +| `min_score` | `float` | The minimum similarity score required for a neighbor to be considered a hit. Optional. | +| `max_distance` | `float` | The maximum physical distance in vector space required for a neighbor to be considered a hit. Optional. | +| `filter` | [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | Filters for the k-NN search query. See [Filter limitations](#filter-limitations). Optional. | +| `boost` | `float` | A boost value used to increase or decrease relevance scores. Default is 1.0. Optional. | +| `underscore_name` | `string` | A query name for query tagging (JSON key: `_name`). Optional. | +| `method_parameters` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | Algorithm-specific parameters (for example, `ef_search` or `nprobes`). Optional. | +| `rescore` | [`KnnQueryRescore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2073) | A rescoring configuration for improved accuracy. Available in versions later than 2.17. Optional. | +| `expand_nested_docs` | `bool` | When `true`, retrieves scores for all nested field documents within each parent document. Used with nested queries. Optional. | + +## Example request + +The following example shows a gRPC search request with a k-NN query. It searches for the 10 most similar vectors to the query vector `[0.1, 0.2, 0.3, 0.4]` in the `my_vector` field of the `vector_index` index: + +```json +{ + "index": ["vector_index"], + "search_request_body": { + "query": { + "knn": { + "field": "my_vector", + "vector": [0.1, 0.2, 0.3, 0.4], + "k": 10 + } + }, + "size": 10 + } +} +``` +{% include copy.html %} + +## Java gRPC client example + +The following is a basic example of using the gRPC k-NN API (the actual implementation depends on your gRPC client setup): + +```java +import org.opensearch.protobufs.*; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +public class KnnGrpcClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + // Create a gRPC stub for search operations + SearchServiceGrpc.SearchServiceBlockingStub searchStub = + SearchServiceGrpc.newBlockingStub(channel); + + // Build a k-NN query using protocol buffers + QueryContainer knnQuery = QueryContainer.newBuilder() + .setKnn(KnnQuery.newBuilder() + .setField("my_vector") + .addAllVector(Arrays.asList(0.1f, 0.2f, 0.3f, 0.4f)) + .setK(10) + .build()) + .build(); + + // Create the search request + SearchRequest request = SearchRequest.newBuilder() + .addIndex("vector_index") + .setSearchRequestBody(SearchRequestBody.newBuilder() + .setQuery(knnQuery) + .setSize(10) + .build()) + .build(); + + // Execute the search + try { + SearchResponse response = searchStub.search(request); + + // Handle the response + System.out.println("Search took: " + response.getTook() + " ms"); + + HitsMetadata hits = response.getHits(); + if (hits.hasTotal()) { + System.out.println("Found " + hits.getTotal().getTotalHits().getValue() + " results"); + } + + // Process k-NN results with similarity scores + for (HitsMetadataHitsInner hit : hits.getHitsList()) { + System.out.println("Document ID: " + hit.getXId()); + if (hit.hasXScore()) { + System.out.println("Similarity score: " + hit.getXScore().getDouble()); + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC k-NN search request failed with status: " + e.getStatus()); + System.err.println("Error message: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` +{% include copy.html %} + +## Response fields + +k-NN search requests return the same [`SearchResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L262) structure as regular search operations. For information about response fields, see [Search (gRPC) response fields]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/search/#response-fields). + +The response includes the standard search metadata (`took`, `timed_out`, and `shards`) and a `hits` array containing the k-NN documents with their similarity scores. + +## Filter limitations + +The gRPC k-NN API has limited support for the `filter` clause compared to the HTTP API. For the current list of supported query types in gRPC, see the [Search API QueryContainer documentation]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/search/#querycontainer-fields) and [Supported queries]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/search/#supported-queries). + +For complex filtering requirements, consider using the HTTP k-NN API, simplifying your filter logic, or waiting for the next version of k-NN gRPC. + + + +## Related APIs + +- [Search (gRPC)]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/search/) - General gRPC search functionality +- [Bulk (gRPC)]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/bulk/) - Bulk operations using gRPC +- [k-NN queries]({{site.url}}{{site.baseurl}}/query-dsl/specialized/k-nn/) - HTTP-based k-NN query documentation + +## Next steps + +- Learn more about [vector search in OpenSearch]({{site.url}}{{site.baseurl}}/search-plugins/knn/index/). +- Explore [k-NN index settings]({{site.url}}{{site.baseurl}}/search-plugins/knn/knn-index/). +- Review [performance tuning for k-NN]({{site.url}}{{site.baseurl}}/search-plugins/knn/performance-tuning/). +- Read about [gRPC configuration]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#grpc-settings). diff --git a/_api-reference/grpc-apis/predict-model-stream.md b/_api-reference/grpc-apis/predict-model-stream.md new file mode 100644 index 00000000..2e3a0842 --- /dev/null +++ b/_api-reference/grpc-apis/predict-model-stream.md @@ -0,0 +1,247 @@ +--- +layout: default +title: Predict model stream (gRPC) +parent: gRPC APIs +nav_order: 40 +--- + +# Predict Model Stream API (gRPC) +**Introduced 3.8** +{: .label .label-purple } + +The gRPC Predict Model Stream API provides a binary interface for streaming predictions from remote machine learning (ML) models using protocol buffers over gRPC. The server streams response chunks to the client as the underlying model generates them, so the client can begin processing output before inference completes. Use streaming for token-by-token generation from large language models (LLMs). + +You can stream predictions over either REST or gRPC. Both transports return the same incrementally generated model output, so choose the one that best fits your client: + +- **REST streaming** uses server-sent events (SSE) over HTTP, which browsers, standard HTTP clients, and command line tools such as cURL support directly. This is an experimental feature and is not recommended for use in a production environment. For more information, see [Predict Stream API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict-stream/). +- **gRPC streaming** uses protocol buffers over HTTP/2. This transport provides lower serialization overhead and smaller payloads, native server streaming semantics with HTTP/2 flow control and connection multiplexing, and a strongly typed schema from which you can generate clients in any [gRPC-supported language](https://grpc.io/docs/languages/). + +Streaming predictions are supported for the following externally hosted models: + +- [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) +- [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +## Prerequisites + +Before using the gRPC Predict Model Stream API, ensure that you have fulfilled the following prerequisites: + +- Enable gRPC transport on the cluster. For more information, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). +- Obtain the ML Commons protobufs on the client side. For ways to obtain the protobufs, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). +- Configure an externally hosted model and streaming connector for a supported model type. For model and connector configuration, see [Predict Stream API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict-stream/#step-2-register-a-compatible-externally-hosted-model). + +## gRPC service and method + +The gRPC Predict Model Stream API resides in the [`MLService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L22) service. + +You can submit streaming prediction requests by invoking the [`PredictModelStream`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L24) method within the `MLService`. The method takes an [`MlPredictModelStreamRequest`](#mlpredictmodelstreamrequest-fields) and returns a stream of [`PredictResponse`](#response-fields) messages. + +`PredictModelStream` is a server streaming remote procedure call (RPC): the client sends a single request, and the server returns a sequence of response messages. The final message sets `is_last` to `true`, and the server then closes the stream. +{: .note} + +## Request fields + +The gRPC Predict Model Stream API supports the following request fields. + +### MlPredictModelStreamRequest fields + +The [`MlPredictModelStreamRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3406) message accepts the following fields. + +| Field | Protobuf type | Required | Description | +| :---- | :---- | :---- | :---- | +| `model_id` | `string` | Required | The ID of the model to run predictions against. The model must be a supported externally hosted model. | +| `ml_predict_model_stream_request_body` | [`MLPredictModelStreamRequestBody`](#mlpredictmodelstreamrequestbody-fields) | Required | The request payload containing the prediction parameters. | + + +### MLPredictModelStreamRequestBody fields + + +The [`MLPredictModelStreamRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3323) message accepts the following fields. + +| Field | Protobuf type | Required | Description | +| :---- | :---- | :---- | :---- | +| `parameters` | [`Parameters`](#parameters-fields) | Required | The input parameters passed to the remote model. | + +### Parameters fields + +For streaming predictions, the [`Parameters`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3356) message accepts the following fields. Provide the fields that match your model type. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `messages` | `repeated` [`Messages`](#messages-fields) | The conversation messages sent to a chat completion model, such as OpenAI Chat Completion. | +| `inputs` | `string` | The input text sent to the model, for example, when using an Amazon Bedrock Converse Stream model. | +| `x_llm_interface` | `string` | The LLM interface that corresponds to your model type. Valid values are `openai/v1/chat/completions` and `bedrock/converse/claude`. | + +### Messages fields + +The [`Messages`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3328) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `role` | `string` | The role of the message sender, for example, `system` or `user`. | +| `content` | `string` | The message content. | + +## Response fields + +The server streams a sequence of [`PredictResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3367) messages. Each message carries one chunk of the generated output and provides the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `inference_results` | `repeated InferenceResults` | The inference results for the chunk. | +| `inference_results.output` | `repeated Output` | The output objects for each inference result. | +| `inference_results.output.name` | `string` | The name of the output field (typically, `response`). | +| `inference_results.output.data_as_map` | `DataAsMap` | The response content and metadata for the chunk. | +| `inference_results.output.data_as_map.content` | `string` | The text content of the chunk. Concatenate the `content` values across chunks to reconstruct the full response. | +| `inference_results.output.data_as_map.is_last` | `bool` | Whether this is the final chunk in the stream. When `true`, no further messages are sent. | + +## Example request + +Both the field that carries the model input and the `x_llm_interface` value depend on the model type. The following examples show the JSON representation of the gRPC request message for each supported model type. In both examples, replace `model_id` with the ID of your registered model. + +For an OpenAI Chat Completion model, provide the conversation in the `messages` field and set `x_llm_interface` to `openai/v1/chat/completions`: + +```json +{ + "model_id": "your_model_id", + "ml_predict_model_stream_request_body": { + "parameters": { + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Can you summarize Prince Hamlet of William Shakespeare in around 100 words?" + } + ], + "x_llm_interface": "openai/v1/chat/completions" + } + } +} +``` +{% include copy.html %} + +For an Amazon Bedrock Converse Stream model, provide the input text in the `inputs` field and set `x_llm_interface` to `bedrock/converse/claude`: + +```json +{ + "model_id": "your_model_id", + "ml_predict_model_stream_request_body": { + "parameters": { + "inputs": "Can you summarize Prince Hamlet of William Shakespeare in around 100 words?", + "x_llm_interface": "bedrock/converse/claude" + } + } +} +``` +{% include copy.html %} + +The following example shows a Java gRPC client that streams predictions from an OpenAI Chat Completion model. Replace the model ID and messages with values that match your model configuration: + +```java +import org.opensearch.protobufs.*; +import org.opensearch.protobufs.services.MLServiceGrpc; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +import java.util.Iterator; + +public class PredictModelStreamClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + // Create a gRPC stub for ML operations + MLServiceGrpc.MLServiceBlockingStub mlStub = MLServiceGrpc.newBlockingStub(channel); + + // Build the request parameters for an OpenAI Chat Completion model + Parameters parameters = Parameters.newBuilder() + .addMessages(Messages.newBuilder() + .setRole("system") + .setContent("You are a helpful assistant.") + .build()) + .addMessages(Messages.newBuilder() + .setRole("user") + .setContent("Can you summarize Prince Hamlet of William Shakespeare in around 100 words?") + .build()) + .setXLlmInterface("openai/v1/chat/completions") + .build(); + + // Create the streaming predict request + MlPredictModelStreamRequest request = MlPredictModelStreamRequest.newBuilder() + .setModelId("your_model_id") + .setMlPredictModelStreamRequestBody(MLPredictModelStreamRequestBody.newBuilder() + .setParameters(parameters) + .build()) + .build(); + + // Execute the request and read the streamed response + try { + Iterator responses = mlStub.predictModelStream(request); + while (responses.hasNext()) { + PredictResponse response = responses.next(); + for (InferenceResults results : response.getInferenceResultsList()) { + for (Output output : results.getOutputList()) { + DataAsMap chunk = output.getDataAsMap(); + System.out.print(chunk.getContent()); + if (chunk.getIsLast()) { + System.out.println("\n[stream complete]"); + } + } + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC predict stream request failed with status: " + e.getStatus()); + System.err.println("Error message: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` +{% include copy.html %} + +For an Amazon Bedrock Converse Stream model, build the request parameters using `setInputs` instead of `addMessages`. The rest of the client code is unchanged: + +```java +Parameters parameters = Parameters.newBuilder() + .setInputs("Can you summarize Prince Hamlet of William Shakespeare in around 100 words?") + .setXLlmInterface("bedrock/converse/claude") + .build(); + +MlPredictModelStreamRequest request = MlPredictModelStreamRequest.newBuilder() + .setModelId("your_model_id") + .setMlPredictModelStreamRequestBody(MLPredictModelStreamRequestBody.newBuilder() + .setParameters(parameters) + .build()) + .build(); +``` +{% include copy.html %} + +## Example response + +The server returns a sequence of `PredictResponse` messages. Each message carries a chunk of generated text in the `content` field, and the final message sets `isLast` to `true`. The following example shows the JSON representation of a streamed chunk: + +```json +{ + "inferenceResults": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "content": "Hello", + "isLast": false + } + } + ] + } + ] +} +``` + +## Related documentation + +- [Predict Stream API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict-stream/) -- The REST equivalent for streaming predictions +- [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/) -- gRPC transport configuration and client requirements diff --git a/_api-reference/grpc-apis/search.md b/_api-reference/grpc-apis/search.md new file mode 100644 index 00000000..45a9ed0a --- /dev/null +++ b/_api-reference/grpc-apis/search.md @@ -0,0 +1,1117 @@ +--- +layout: default +title: Search (gRPC) +parent: gRPC APIs +nav_order: 10 +--- + +# Search API (gRPC) +**Introduced 3.0** +{: .label .label-purple } + + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/16787). +{: .warning} + +The gRPC Search API provides a performant, binary interface for running [queries]({{site.url}}{{site.baseurl}}/api-reference/search/) using protocol buffers over gRPC. It mirrors the capabilities of the HTTP Search API while benefiting from protobuf-typed contracts and gRPC transport. The gRPC APIs are ideal for low-latency, high-throughput applications. + +## Prerequisite + +To submit gRPC requests, you must have a set of protobufs on the client side. For ways to obtain the protobufs, see [Using gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/index/#how-to-use-grpc-apis). + +## gRPC service and method + +gRPC Document APIs reside in the [`SearchService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L22). + +You can submit search requests by invoking the [`Search`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L23) gRPC method within the `SearchService`. The method takes a [`SearchRequest`](#searchrequest-fields) and returns a [`SearchResponse`](#searchresponse-fields). + +See [Supported Queries](#supported-queries) for supported search queries. Additional query types will be supported in future versions. +{: .note} + +## Request fields + +The gRPC Search API supports the following request fields. + +### SearchRequest fields + +The [`SearchRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L20) message accepts the following fields. All fields are optional. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `index` | `repeated string` | A list of indexes to search. If not provided, defaults to all indexes. | +| `x_source` | [`SourceConfigParam`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1251) | Controls whether to return the full `_source`, no `_source`, or only specific fields from `_source` in the response. | +| `x_source_excludes` | `repeated string` | Fields to exclude from `_source`. Ignored if `source` is `false`. | +| `x_source_includes` | `repeated string` | Fields to include in `_source`. Ignored if `source` is `false`. | +| `allow_no_indices` | `bool` | Whether to ignore wildcards that match no indexes. Default is `true`. | +| `allow_partial_search_results` | `bool` | Whether to return partial results upon an error or timeout. Default is `true`. | +| `analyze_wildcard` | `bool` | Whether to analyze wildcard/prefix queries. Default is `false`. | +| `batched_reduce_size` | `int32` | The number of shards to reduce on a node. Default is `512`. | +| `cancel_after_time_interval` | `string` | The time after which the request will be canceled. Default is `-1`. | +| `ccs_minimize_roundtrips` | `bool` | Whether to minimize round trips between the node and remote clusters. Default is `true`. | +| `default_operator` | [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | The default operator for query strings. Valid values are `AND` or `OR`. Default is `OR`. | +| `df` | `string` | The default field for query strings without field prefixes. | +| `docvalue_fields` | `repeated string` | The fields to return as doc values. | +| `expand_wildcards` | `repeated` [`ExpandWildcard`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3567) | The type of index that wildcard expressions can match. Valid values are `all` (match any index), `open` (match open, non-hidden indexes), `closed` (match closed, non-hidden indexes), `hidden` (match hidden indexes), and `none` (deny wildcard expressions). Default is `open`.| +| `ignore_throttled` | `bool` | Whether to ignore frozen indexes when resolving aliases. Default is `true`. | +| `ignore_unavailable` | `bool` | Whether to ignore unavailable indexes or shards. Default is `false`. | +| `max_concurrent_shard_requests` | `int32` | The number of concurrent shard requests per node. Default is `5`. | +| `phase_took` | `bool` | Whether to return phase-level `took` values. Default is `false`. | +| `pre_filter_shard_size` | `int32` | The threshold at which to trigger prefiltering by shard size. Default is `128`. | +| `preference` | `string` | The shard or node preferences for query execution. | +| `q` | `string` | The query string in [Lucene syntax]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/#query-string-syntax). | +| `request_cache` | `bool` | Whether to use the request cache. Defaults to the index's settings. | +| `total_hits_as_int` | `bool` | Whether to return the number of total hits as an integer. Default is `false`. | +| `routing` | `repeated string` | The routing values used to direct requests to specific shards. | +| `scroll` | `string` | The amount of time to keep the search context alive for scrolling. | +| `search_type` | [`SearchType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3576) | The method for calculating relevance scores. Valid values are `QUERY_THEN_FETCH` and `DFS_QUERY_THEN_FETCH`. Default is `QUERY_THEN_FETCH`. | +| `suggest_field` | `string` | The field on which to base suggestions. | +| `suggest_mode` | [`SuggestMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3582) | The suggestion mode (for example, `always`, `missing`, `popular`). | +| `suggest_size` | `int32` | The number of suggestions to return. | +| `suggest_text` | `string` | The input text for generating suggestions. | +| `typed_keys` | `bool` | Whether to include type information in aggregation and suggestion keys. Default is `true`. | +| `search_request_body` | [`SearchRequestBody`](#searchrequestbody-fields) | The main search request payload, including the query and filters. | +| `global_params` | [`GlobalParams`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1150) | Global parameters for the request. Optional. | + +### SearchRequestBody fields + +The [`SearchRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L123) message accepts the following fields. All fields are optional. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `collapse` | [`FieldCollapse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1974) | Groups the results by a field. Returns only the top document per group. | +| `explain` | `bool` | Returns scoring explanations for matched documents. | +| `ext` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | Plugin-specific metadata, for example, for extensions like RAG. | +| `from` | `int32` | The starting index for paginated results. Default is `0`. | +| `highlight` | [`Highlight`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1728) | Highlights matched terms in the result snippets. | +| `track_total_hits` | [`TrackHits`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L252) | Whether to return the total hit count. | +| `indices_boost` | `map` | **Deprecated.** Use `indices_boost_2` instead. | +| `docvalue_fields` | `repeated` [`FieldAndFormat`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1965) | The fields to return in their `doc_values` form. You can include a format for the returned values (for example, a date format). For `knn_vector` fields, supported formats are `binary` (default, Base64-encoded) and `array` (JSON numeric arrays). For more information, see [Retrieving vector fields using `docvalue_fields`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#retrieving-vector-fields-using-docvalue_fields). | +| `min_score` | `float` | The minimum score required in order for a document to be included in the results. | +| `post_filter` | [`QueryContainer`](#querycontainer-fields) | Filters hits after aggregations are applied. | +| `profile` | `bool` | Enables profiling to analyze query performance. | +| `search_pipeline` | `string` | The name of the search pipeline to apply. | +| `verbose_pipeline` | `bool` | Enables verbose logging in the search pipeline. | +| `query` | [`QueryContainer`](#querycontainer-fields) | The query domain-specific language (DSL) for the search. | +| `rescore` | `repeated` [`Rescore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L504) | Reranks the top N hits to improve precision. | +| `script_fields` | `map` | Custom fields whose values are computed by scripts. | +| `search_after` | `repeated` [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | Cursor-based pagination using values from the previous page. | +| `size` | `int32` | The number of results to return. Default is `10`. | +| `slice` | [`SlicedScroll`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L513) | Splits scroll context into slices for parallel processing. | +| `sort` | `repeated` [`SortCombinations`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1693) | The sorting rules (for example, by field, score, or custom order). | +| `x_source` | [`SourceConfig`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1267) | Controls whether to return the full `_source`, no `_source`, or only specific fields from `_source` in the response. | +| `fields` | `repeated` [`FieldAndFormat`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1965) | Additional fields to return, with formatting options. | +| `terminate_after` | `int32` | The maximum number of matching documents (hits) to process before early termination. Default is `0`. | +| `timeout` | `string` | The maximum amount of time to wait for query execution. | +| `track_scores` | `bool` | Whether to return document scores in the results. | +| `include_named_queries_score` | `bool` | Whether to include scores for named queries. | +| `version` | `bool` | Whether to include the document version in the response. | +| `seq_no_primary_term` | `bool` | Whether to include the sequence number and primary term for each hit. | +| `stored_fields` | `repeated string` | The stored fields to return (excludes `_source` unless re-enabled). | +| `pit` | [`PointInTimeReference`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L612) | The Point in Time reference used to search a fixed snapshot. | +| `stats` | `repeated string` | The tagging or logging fields to associate with the request. | +| `derived` | `map` | Dynamically computed fields returned in the response. | +| `indices_boost_2` | `repeated` [`FloatMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3004) | The current protobuf representation for per-index boost multipliers. Each entry contains an index-to-boost mapping. | +| `aggregations` | `map` | Aggregations to compute as part of the search request. | + +### DerivedField fields + +The [`DerivedField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L228) message is used for dynamically computed fields that are calculated during search execution. It accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `name` | `string` | The name of the derived field. Required. | +| `type` | `string` | The data type of the derived field. Required. | +| `script` | [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | The script that computes the field value. Required. | +| `prefilter_field` | `string` | The field to use for prefiltering to optimize script execution. Optional. | +| `properties` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | Additional properties for the derived field. Optional. | +| `ignore_malformed` | `bool` | Whether to ignore malformed values during field computation. Optional. | +| `format` | `string` | The format to apply to the field value (for example, date formatting). Optional. | + +### QueryContainer fields + +`QueryContainer` is the entry point for all supported query types. + +**Exactly one** of the following fields must be provided in each `QueryContainer` message. + +Note that some query types are currently unsupported. See [Supported queries](#supported-queries) for the current list of implemented query types. +{: .note} + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `bool` | [`BoolQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2133) | A Boolean query that combines multiple clauses using `AND`, `OR`, or `NOT` logic. Must be the only field set. | +| `constant_score` | [`ConstantScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2171) | Wraps a filter and assigns a constant relevance score to all matching documents. Must be the only field set. | +| `function_score` | [`FunctionScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2183) | Adjusts the scores of the results using custom functions. Must be the only field set. | +| `exists` | [`ExistsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1986) | Matches documents that contain a specific field. Must be the only field set. | +| `fuzzy` | [`FuzzyQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2593) | Matches terms similar to the search term (fuzzy matching). Must be the only field set. | +| `ids` | [`IdsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2648) | Matches documents by `_id` values. Must be the only field set. | +| `prefix` | [`PrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2309) | Matches terms with a specific prefix. Must be the only field set. | +| `range` | [`RangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2460) | Matches terms within a specified range. Must be the only field set. | +| `regexp` | [`RegexpQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2391) | Matches terms using regular expressions. Must be the only field set. | +| `term` | [`TermQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2421) | Matches exact terms (no analysis). Must be the only field set. | +| `terms` | [`TermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1587) | Matches any document containing one or more specified terms in a field. Must be the only field set. | +| `terms_set` | [`TermsSetQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2370) | Matches documents containing a minimum number of exact terms in a field. Must be the only field set. | +| `wildcard` | [`WildcardQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1998) | Matches terms using a wildcard pattern. Must be the only field set. | +| `match` | [`MatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2082) | Performs a full-text match on text or exact-value fields. Must be the only field set. | +| `match_bool_prefix` | [`MatchBoolPrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2668) | Matches full words and prefixes in a Boolean-style query. Must be the only field set. | +| `match_phrase` | [`MatchPhraseQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2746) | Matches an exact phrase in order. Must be the only field set. | +| `match_phrase_prefix` | [`MatchPhrasePrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2719) | Matches a phrase in which the last term is treated as a prefix. Must be the only field set. | +| `multi_match` | [`MultiMatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2770) | Searches multiple fields using a single query string. Must be the only field set. | +| `knn` | [`KnnQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2023) | A k-NN query across vector fields. Must be the only field set. | +| `match_all` | [`MatchAllQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2659) | Matches all documents in the index. Must be the only field set. | +| `match_none` | [`MatchNoneQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2710) | Matches no documents. Must be the only field set. | +| `nested` | [`NestedQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1602) | Wraps a query targeting nested fields. Must be the only field set. | +| `geo_distance` | [`GeoDistanceQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1560) | Returns documents containing geopoints within a specified distance from a provided geopoint. Must be the only field set. | +| `geo_bounding_box` | [`GeoBoundingBoxQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1483) | Returns documents containing geopoints within a specified bounding box. Must be the only field set. | +| `script` | [`ScriptQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1471) | Filters documents based on a custom condition written in Painless scripting language. Must be the only field set. | +| `hybrid` | [`HybridQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1453) | Combines relevance scores from multiple queries into one score. Must be the only field set. | + +## Supported queries + +The gRPC Search API supports the following query types: +* Term-level: `exists`, `fuzzy`, `ids`, `prefix`, `range`, `regexp`, `term`, `terms`, `terms_set`, `wildcard` +* Full-text: `match`, `match_bool_prefix`, `match_phrase`, `match_phrase_prefix`, `multi_match` +* Match all: `match_all`, `match_none` +* Compound queries: `bool`, `constant_score`, `function_score`, `hybrid` +* Geographic: `geo_bounding_box`, `geo_distance` +* Joining queries: `nested` +* Specialized queries: `knn`, `script` + +For more information about these query types, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +### Term-level query fields + +The following sections describe the fields for each term-level query message. + +#### ExistsQuery fields + +The [`ExistsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1986) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The name of the field to search. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | + +#### FuzzyQuery fields + +The [`FuzzyQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2593) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `value` | [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | Required. The term to search for in the specified field. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `max_expansions` | `optional int32` | The maximum number of terms to which the query can expand. Default is `50`. | +| `prefix_length` | `optional int32` | The number of leading characters that are not considered in fuzziness. Default is `0`. | +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `rewrite` instead. | +| `transpositions` | `optional bool` | Specifies whether to allow transpositions of two adjacent characters as edits. Default is `true`. | +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | The number of character edits (insert, delete, or substitute) that it takes to change one word to another when determining whether a term matched a value.| +| `rewrite` | `optional string` | Determines how OpenSearch rewrites the query. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +#### IdsQuery fields + +The [`IdsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2648) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `values` | `repeated string` | The document IDs to search for. | + +#### PrefixQuery fields + +The [`PrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2309) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `value` | `string` | Required. The term to search for in the specified field. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `rewrite` instead. | +| `case_insensitive` | `optional bool` | Allows ASCII case-insensitive matching. Default is `false`. | +| `rewrite` | `optional string` | Determines how OpenSearch rewrites the query. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +#### RangeQuery fields + +The [`RangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2460) message is a `oneof` type that can contain either a [`NumberRangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2469) or a [`DateRangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2530). + +##### NumberRangeQuery fields + +The `NumberRangeQuery` message accepts the following fields. + +he `NumberRangeQuery` message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `relation` | `optional` [`RangeRelation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3589) | Indicates how the range query matches values for range fields. | +| `gt` | `optional double` | Greater than. | +| `gte` | `optional double` | Greater than or equal to. | +| `lt` | `optional double` | Less than. | +| `lte` | `optional double` | Less than or equal to. | +| `from` | `optional` [`NumberRangeQueryAllOfFrom`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2508) | The starting value for the range. | +| `to` | `optional` [`NumberRangeQueryAllOfTo`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2519) | The ending value for the range. | +| `include_lower` | `optional bool` | Whether to include the lower bound. | +| `include_upper` | `optional bool` | Whether to include the upper bound. | + +##### DateRangeQuery fields + + The `DateRangeQuery` message accepts the following fields. + +The `DateRangeQuery` message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `relation` | `optional` [`RangeRelation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3589) | Indicates how the range query matches values for range fields. | +| `gt` | `optional string` | Greater than. | +| `gte` | `optional string` | Greater than or equal to. | +| `lt` | `optional string` | Less than. | +| `lte` | `optional string` | Less than or equal to. | +| `from` | `optional` [`DateRangeQueryAllOfFrom`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2575) | The starting value for the range. | +| `to` | `optional` [`DateRangeQueryAllOfTo`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2584) | The ending value for the range. | +| `format` | `optional string` | The date format pattern. | +| `time_zone` | `optional string` | The time zone identifier. | +| `include_lower` | `optional bool` | Whether to include the lower bound. | +| `include_upper` | `optional bool` | Whether to include the upper bound. | + +#### RegexpQuery fields + +The [`RegexpQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2391) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `value` | `string` | Required. A regular expression for terms to search for in the provided field. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `case_insensitive` | `optional bool` | Allows case-insensitive matching of the regular expression. Default is `false`. | +| `flags` | `optional string` | Enables optional operators for the regular expression. | +| `max_determinized_states` | `optional int32` | The maximum number of automaton states the query requires. Default is `10000`. | +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `rewrite` instead. | +| `rewrite` | `optional string` | Determines how OpenSearch rewrites and scores multi-term queries. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +#### TermQuery fields + +The [`TermQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2421) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `value` | [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | Required. The term to search for in the provided field. Must exactly match the field value. | +| `case_insensitive` | `optional bool` | Allows ASCII case-insensitive matching. Default is `false`. | + +#### TermsQuery fields + +The [`TermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1587) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `value_type` | `optional` [`TermsQueryValueType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3612) | The types of values used for filtering. Valid values are `default` and `bitmap`. Default is `default`. | +| `terms` | `map` | A map of field names to term values or term lookups. | + +#### TermsQueryField fields + +The [`TermsQueryField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2333) message accepts one of the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `value` | [`FieldValueArray`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2365) | An explicit list of term values to match. | +| `lookup` | [`TermsLookup`](#termslookup-fields) | Fetches the term values from another document. | + +#### TermsLookup fields + +The [`TermsLookup`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2342) message accepts the following fields. Set either `id_2` or `query` to identify the lookup document. If neither is set, the deprecated `id` field is used. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `index` | `string` | The name of the index from which to fetch the terms. | +| `path` | `string` | The path to the field in the lookup document that contains the term values. | +| `id_2` | `string` | The ID of the document from which to fetch the terms. | +| `query` | [`QueryContainer`](#querycontainer-fields) | A query that selects the document or documents from which to fetch the terms. | +| `routing` | `optional string` | The routing value used to locate the lookup document. | +| `store` | `optional bool` | Whether to read the term values from the stored field instead of `_source`. | +| `id` | `string` | **Deprecated.** Use `id_2` instead. The ID of the document from which to fetch the terms. | + +#### TermsSetQuery fields + +The [`TermsSetQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2370) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `terms` | `repeated string` | Required. The array of terms to search for in the specified field. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `minimum_should_match_field` | `optional string` | The name of the numeric field that specifies the number of matching terms required. | +| `minimum_should_match_script` | `optional` [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | A script that returns the number of matching terms required. | + +#### WildcardQuery fields + +The [`WildcardQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1998) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `case_insensitive` | `optional bool` | Allows case-insensitive matching. Default is `false`. | +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `rewrite` instead. | +| `value` | `optional string` | A wildcard pattern used for matching terms in the specified field. Required when `wildcard` is not set. | +| `wildcard` | `optional string` | A wildcard pattern used for matching terms in the specified field. Required when `value` is not set. | +| `rewrite` | `optional string` | Determines how OpenSearch rewrites the query. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +### Full-text query fields + +The following sections describe the fields for each full-text query message. + +The following sections describe the fields for each full-text query message. + +#### MatchQuery fields + +The [`MatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2082) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `query` | [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | Required. The query string to use for search. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `analyzer` | `optional string` | The analyzer used to tokenize the query string text. | +| `auto_generate_synonyms_phrase_query` | `optional bool` | Specifies whether to create a match phrase query automatically for multi-term synonyms. | +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | The number of character edits (insertions, deletions, substitutions, or transpositions) that it takes to change one word to another when determining whether a term matched a value. | +| `fuzzy_rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `fuzzy_rewrite` instead. | +| `fuzzy_transpositions` | `optional bool` | Adds swaps of adjacent characters to the fuzziness operations. Default is `true`. | +| `lenient` | `optional bool` | Ignores data type mismatches between the query and the document field. Default is `false`. | +| `max_expansions` | `optional int32` | The maximum number of terms to which the query can expand. Default is `50`. | +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) | The number of terms that need to match for the document to be considered a match. | +| `operator` | `optional` [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | Whether all terms need to match (`AND`) or only one term needs to match (`OR`). Default is `OR`. | +| `prefix_length` | `optional int32` | The number of leading characters that are not considered in fuzziness. Default is `0`. | +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms. Default is `none`. | +| `fuzzy_rewrite` | `optional string` | Determines how OpenSearch rewrites the query. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +#### MatchBoolPrefixQuery fields + +The [`MatchBoolPrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2668) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `query` | `string` | Required. The terms to search for in the provided field. The last term is used in a prefix query. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `analyzer` | `optional string` | The analyzer used to tokenize the query string text. | +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | The number of character edits (insertions, deletions, substitutions, or transpositions) that it takes to change one word to another when determining whether a term matched a value. | +| `fuzzy_rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `fuzzy_rewrite` instead. | +| `fuzzy_transpositions` | `optional bool` | Adds swaps of adjacent characters to the fuzziness operations. Default is `true`. | +| `max_expansions` | `optional int32` | The maximum number of terms to which the query can expand. Default is `50`. | +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) | The number of terms that need to match for the document to be considered a match. | +| `operator` | `optional` [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | Whether all terms need to match (`AND`) or only one term needs to match (`OR`). Default is `OR`. | +| `prefix_length` | `optional int32` | The number of leading characters that are not considered in fuzziness. Default is `0`. | +| `fuzzy_rewrite` | `optional string` | Determines how OpenSearch rewrites the query. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +#### MatchPhraseQuery fields + +The [`MatchPhraseQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2746) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `query` | `string` | Required. The query string to use for search. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `analyzer` | `optional string` | The analyzer used to tokenize the query string text. | +| `slop` | `optional int32` | The number of other words permitted between words in the query phrase. Default is `0` (exact match). | +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms. Default is `none`. | + +#### MatchPhrasePrefixQuery fields + +The [`MatchPhrasePrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2719) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `field` | `string` | Required. The field against which to run a search query. | +| `query` | `string` | Required. The query string to use for search. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `analyzer` | `optional string` | The analyzer used to tokenize the query string text. | +| `max_expansions` | `optional int32` | The maximum number of terms to which the query can expand. Default is `50`. | +| `slop` | `optional int32` | The number of other words permitted between words in the query phrase. Default is `0` (exact match). | +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms. Default is `none`. | + +#### MultiMatchQuery fields + +The [`MultiMatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2770) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `query` | `string` | Required. The query string to use for search. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `analyzer` | `optional string` | The analyzer used to tokenize the query string text. | +| `auto_generate_synonyms_phrase_query` | `optional bool` | Specifies whether to create a match phrase query automatically for multi-term synonyms. Default is `true`. | +| `fields` | `repeated string` | The list of fields in which to search. | +| `fuzzy_rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated.** Use `fuzzy_rewrite` instead. | +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | The number of character edits (insertions, deletions, substitutions, or transpositions) that it takes to change one word to another when determining whether a term matched a value. | +| `fuzzy_transpositions` | `optional bool` | Adds swaps of adjacent characters to the fuzziness operations. Default is `true`. | +| `lenient` | `optional bool` | Ignores data type mismatches between the query and the document field. Default is `false`. | +| `max_expansions` | `optional int32` | The maximum number of terms to which the query can expand. Default is `50`. | +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) | The number of terms that need to match for the document to be considered a match. | +| `operator` | `optional` [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | Whether all terms need to match (`AND`) or only one term needs to match (`OR`). Default is `OR`. | +| `prefix_length` | `optional int32` | The number of leading characters that are not considered in fuzziness. Default is `0`. | +| `slop` | `optional int32` | The number of other words permitted between words in the query phrase. Supported for `phrase` and `phrase_prefix` query types. | +| `tie_breaker` | `optional float` | A factor between `0` and `1.0` used to assign more weight to documents matching multiple query clauses. | +| `type` | `optional` [`TextQueryType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3596) | The multi-match query type. Valid values are `best_fields`, `most_fields`, `cross_fields`, `phrase`, `phrase_prefix`, `bool_prefix`. Default is `best_fields`. | +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms. Default is `none`. | +| `fuzzy_rewrite` | `optional string` | Determines how OpenSearch rewrites the query. See [Rewrite parameter values](#rewrite-parameter-values). Default is `constant_score`. | + +#### MatchAllQuery fields + +The [`MatchAllQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2659) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | + +#### MatchNoneQuery fields + +The [`MatchNoneQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2710) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | + +### Compound query fields + +The following sections describe the fields for each compound query message. + +The following sections describe the fields for each compound query message. + +#### BoolQuery fields + +The [`BoolQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2133) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `filter` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2142) | The clause (query) that must appear in matching documents. The query score is ignored. | +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2145) | The minimum number of `should` clauses that must match. | +| `must` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2148) | The clause (query) must appear in matching documents and contributes to the score. | +| `must_not` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2151) | The clause (query) that must not appear in matching documents. A score of `0` is returned for all documents. | +| `should` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2154) | The clause (query) that should appear in the matching document. | +| `adjust_pure_negative` | `optional bool` | Ensures correct behavior when a query contains only `must_not` clauses. Default is `true`. | + +#### ConstantScoreQuery fields + +The [`ConstantScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2171) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `filter` | [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | Required. The filter query that a document must match to be returned in the results. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | + +#### FunctionScoreQuery fields + +The [`FunctionScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2183) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `boost_mode` | `optional` [`FunctionBoostMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3626) | Determines how the computed function score is combined with the query score. | +| `functions` | `repeated` [`FunctionScoreContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2210) | The score functions. Each entry may set `filter`, `weight`, and one of `exp`, `gauss`, `linear`, `field_value_factor`, `random_score`, or `script_score`. | +| `max_boost` | `optional float` | The maximum boost value that a function can apply to a document score. | +| `min_score` | `optional float` | Excludes documents with a score below this threshold from the results. | +| `query` | `optional` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | The query used to select documents before applying score functions. | +| `score_mode` | `optional` [`FunctionScoreMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3636) | Determines how scores from multiple functions are combined into a single score. | + +For more information, see [Function score query]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score/). + +### Joining query fields + +The following sections describe the fields for each joining query message. + +The following sections describe the fields for each joining query message. + +#### NestedQuery fields + +The [`NestedQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1602) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `path` | `string` | Required. The path to a field or an array of paths to fields in which to search. | +| `query` | [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | Required. The query to run on the nested objects within the specified path. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `ignore_unmapped` | `optional bool` | Set to `true` to ignore an unmapped field and not match any documents. Default is `false`. | +| `inner_hits` | `optional` [`InnerHits`](#innerhits-fields) | If provided, returns the underlying hits that matched the query. | +| `score_mode` | `optional` [`ChildScoreMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3800) | Defines how scores of matching inner documents influence the parent document's score. | + +### Geographic query fields + +The following sections describe the fields for each geographic query message. + +The following sections describe the fields for each geographic query message. + +#### GeoBoundingBoxQuery fields + +A geo-bounding box query returns documents whose geopoints are within the bounding box specified in the query. The [`GeoBoundingBoxQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1483) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `type` | `optional` [`GeoExecution`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3815) | The execution type for the geographic query. | +| `validation_method` | `optional` [`GeoValidationMethod`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3662) | The validation method. Valid values are `IGNORE_MALFORMED`, `COERCE`, and `STRICT`. Default is `STRICT`. | +| `ignore_unmapped` | `optional bool` | Specifies whether to ignore an unmapped field. Default is `false`. | +| `bounding_box` | `map` | A map of field names to geobounds defining the bounding box. | + +#### GeoDistanceQuery fields + +A geodistance query returns documents with geopoints that are within a specified distance from the provided geopoint. The [`GeoDistanceQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1560) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `distance` | `string` | Required. The distance within which to match the points. This distance is the radius of a circle centered at the specified point. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `distance_type` | `optional` [`GeoDistanceType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3750) | Specifies how to calculate the distance. Valid values are `arc` and `plane`. Default is `arc`. | +| `validation_method` | `optional` [`GeoValidationMethod`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3662) | The validation method. Valid values are `IGNORE_MALFORMED`, `COERCE`, and `STRICT`. Default is `STRICT`. | +| `ignore_unmapped` | `optional bool` | Set to `true` to ignore an unmapped field and not match any documents. Default is `false`. | +| `unit` | `optional` [`DistanceUnit`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3787) | The unit of distance measurement. | +| `location` | `map` | A map of field names to `geolocations` specifying the center point. | + +### Specialized query fields + +The following sections describe the fields for each specialized query message. + +For `knn` query fields, see [k-NN (gRPC)]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/knn/). + +#### ScriptQuery fields + +A script query filters documents based on a custom condition written in the Painless scripting language. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). The [`ScriptQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1471) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `script` | [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | Required. The script to execute for filtering documents. | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | + +#### HybridQuery fields + +A hybrid query combines relevance scores from multiple queries into one score for a given document. The [`HybridQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1453) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query. Default is `1.0`. | +| `x_name` | `optional string` | A query name for query tagging. | +| `queries` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | An array of one or more query clauses that are used to match documents. A document must match at least one query clause in order to be returned in the results. The documents' relevance scores from all query clauses are combined into one score by applying a search pipeline. The maximum number of query clauses is 5. | +| `pagination_depth` | `optional int32` | The pagination depth for the hybrid query. | +| `filter` | `optional` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | A filter to apply to all subqueries of the hybrid query. | + +### AggregationContainer fields + +`AggregationContainer` defines the aggregation to run. Specify exactly one of the following fields in each `AggregationContainer` message. + +The gRPC Search API supports only the following aggregation types: `max`, `min`, and `terms`. +{: .note} + +The [`AggregationContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3026) message wraps a single aggregation definition and accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `meta` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | Optional custom metadata attached to the aggregation. | +| `max` | [`MaxAggregation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3101) | A [`max`]({{site.url}}{{site.baseurl}}/aggregations/metric/maximum/) metric aggregation. Must be the only aggregation type set. | +| `min` | [`MinAggregation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3115) | A [`min`]({{site.url}}{{site.baseurl}}/aggregations/metric/minimum/) metric aggregation. Must be the only aggregation type set. | +| `terms_aggregation` | [`TermsAggregation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3179) | A [`terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/) bucket aggregation that groups documents by term values. Must be the only aggregation type set. | + +### Common message values + +The following sections describe the values used by common message types. + +#### Fuzziness + +The [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) message is a `oneof` type that accepts the following values. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `string` | `string` | `AUTO` generates an edit distance based on the length of the term. You can optionally provide `AUTO:[low],[high]`. | +| `int32` | `int32` | `0`, `1`, or `2`: The maximum allowed [Damerau–Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance). For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). | + +#### Rewrite parameter values + +Multi-term queries like `wildcard`, `prefix`, `regexp`, `fuzzy`, and `range` expand internally into sets of terms. The `rewrite` and `fuzzy_rewrite` parameters control how these term expansions are executed and scored. + +The rewrite parameter gives you control over how multi-term queries behave internally. + +| Value | Scoring | Performance | Notes | +| :---- | :---- | :---- | :---- | +| `constant_score` | Same score for all matches | Best | Default mode, ideal for filters. | +| `scoring_boolean` | TF/IDF-based | Moderate | Full relevance scoring. | +| `constant_score_boolean` | Same score with Boolean structure | Moderate | Use with `must_not` or `minimum_should_match`. | +| `top_terms_` | TF/IDF on top `` terms | Efficient | Truncates expansion to top scoring terms. | +| `top_terms_boost_` | Static boosts | Fast | Less accurate scoring. | +| `top_terms_blended_freqs_` | Blended score | Balanced | Best scoring/efficiency trade-off. | + +{: .note} + +#### MinimumShouldMatch + +The [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) message is a `oneof` type that accepts the following values. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `int32` | `int32` | An integer specifying the minimum number of terms that should match. | +| `string` | `string` | A string specifying a percentage or combination. See [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). | + +#### FieldValue + +The [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) message represents a field value and accepts the following values. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `bool` | `optional bool` | A Boolean value. | +| `general_number` | `optional` [`GeneralNumber`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3915) | A numeric value. | +| `string` | `optional string` | A string value. | +| `null_value` | `optional` [`NullValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3925) | A null value. | + +#### InnerHits fields + +The [`InnerHits`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1626) message accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `name` | `optional string` | The name to be used for the particular inner hit definition in the response. | +| `size` | `optional int32` | The maximum number of hits to return in `inner_hits`. | +| `from` | `optional int32` | The starting document offset for an inner hit. | +| `collapse` | `optional` [`FieldCollapse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1974) | Groups search results by a particular field value. | +| `docvalue_fields` | `repeated` [`FieldAndFormat`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1965) | The fields that OpenSearch should return using their `doc_values`. | +| `explain` | `optional bool` | Whether to return details about how OpenSearch computed the document's score. Default is `false`. | +| `highlight` | `optional` [`Highlight`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1728) | Highlighting emphasizes the search term(s) in the results. | +| `ignore_unmapped` | `optional bool` | Specifies how to treat an unmapped field. Default is `false`. | +| `script_fields` | `map` | Custom fields whose values are computed using scripts. | +| `seq_no_primary_term` | `optional bool` | Whether to return sequence number and primary term of the last operation of each document hit. | + + +All of the following examples show valid request payloads that can be sent to the `SearchService/Search` gRPC method. + +### Match all query + +A `match_all` query returns all documents in the index. For example, the following request returns a maximum of 50 documents from the index: + +```json +{ + "search_request_body": { + "query": { + "match_all": {} + }, + "size": 50 + } +} +``` +{% include copy.html %} + +### Term query + +A `term` query matches a single field with a specific term. For example, the following query searches for titles containing the word `Rush`: + +```json +{ + "index": "my_index", + "search_request_body": { + "query": { + "term": { + "field": "title", + "value": { + "string_value": "Rush" + }, + "case_insensitive": true + } + } + } +} +``` +{% include copy.html %} + +### Terms query + +A `terms` query matches documents in which a specific field contains any value from a list. For example, the following query searches for lines with the IDs `61809` and `61810`: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "line_id": { + "value": { + "field_value_array": [ + { "string": "61809" }, + { "string": "61810" } + ] + } + } + } + } + } + } +} +``` +{% include copy.html %} + +### Terms query with a terms lookup + +A `terms` query with a `terms` lookup is a specialized form of the `terms` query that allows you to fetch the terms for filtering from another document in your cluster rather than specifying them directly in the query. The lookup document is identified by either `id_2` (a document ID) or `query` (a query that selects the source document or documents). For example, the following request matches documents in the `students` index whose `_id` matches one of the values in the `enrolled` array of the `classes` document with the ID `class_1`: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "_id": { + "lookup": { + "index": "classes", + "id_2": "class_1", + "path": "enrolled" + } + } + } + } + } + } +} +``` +{% include copy.html %} + +To select the lookup document using a query rather than an ID, use the `query` field: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "_id": { + "lookup": { + "index": "classes", + "path": "enrolled", + "query": { + "match_all": {} + } + } + } + } + } + } + } +} +``` +{% include copy.html %} + +The deprecated `id` field is still honored for backward compatibility when neither `id_2` nor `query` is set: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "_id": { + "lookup": { + "index": "classes", + "id": "class_1", + "path": "enrolled" + } + } + } + } + } + } +} +``` +{% include copy.html %} + + +### Match none query + +A `match_none` query matches none of the documents: + +```json +{ + "search_request_body": { + "query": { + "match_none": {} + } + } +} +``` +{% include copy.html %} + +## Response fields + +The gRPC Search API returns the following response fields. + +### SearchResponse fields + +The following table lists the supported fields for the [`SearchResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L262) message. + +The source documents are returned as bytes. Use Base64 decoding to read the `_source` field in the gRPC response. +{: .note} + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `took` | `int64` | The amount of time taken to process the search request, in milliseconds. | +| `timed_out` | `bool` | Whether the search timed out. | +| `x_shards` | [`ShardStatistics`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1311) | The shard-level success/failure/total metadata. | +| `phase_took` | [`PhaseTook`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L330) | The phase-level `took` time values in the response. | +| `hits` | [`HitsMetadata`](#hitsmetadata-fields) | The main document results and metadata. | +| `processor_results` | `repeated` [`ProcessorExecutionDetail`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L306) | Processor execution details. | +| `x_clusters` | [`ClusterStatistics`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L471) | Information about the search on each cluster when searching remote clusters. | +| `fields` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | **Deprecated.** Retrieved specific fields in the search response. | +| `num_reduce_phases` | `int32` | The number of times that the coordinating node aggregates results from batches of shard responses. | +| `profile` | [`Profile`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L483) | Profiling data for query execution (debugging/performance insights). | +| `pit_id` | `string` | The Point in Time ID. | +| `x_scroll_id` | `string` | The identifier for the search and its search context. | +| `terminated_early` | `bool` | Whether the query was terminated early. | +| `aggregations` | `map` | Aggregation results returned with the search response. | + +### Aggregate fields + +The [`Aggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3009) message represents a single aggregation result and accepts the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `dterms` | [`DoubleTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3040) | A `terms` aggregation with double-valued bucket keys. | +| `lterms` | [`LongTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3066) | A `terms` aggregation with signed-long bucket keys. | +| `max` | [`SingleMetricAggregateBase`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3129) | The result of a `max` aggregation. | +| `min` | [`SingleMetricAggregateBase`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3129) | The result of a `min` aggregation. | +| `sterms` | [`StringTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3155) | A `terms` aggregation with string bucket keys. | +| `ulterms` | [`UnsignedLongTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3268) | A `terms` aggregation with unsigned-long bucket keys. | +| `umterms` | [`UnmappedTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3256) | A `terms` aggregation result for unmapped fields. | + +### HitsMetadata fields + +The `HitsMetadata` object contains information about the search results, including the total number of matching documents and an array of individual document matches. It includes the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `total` | [`HitsMetadataTotal`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L351) | Metadata about the total number of matching documents (value \+ relation). | +| `max_score` | [`HitsMetadataMaxScore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L360) | The highest relevance score of the returned hits (may be `null`). | +| `hits` | `repeated` [`HitsMetadataHitsInner`](#hitsmetadatahitsinner-fields) | The actual list of matched documents. Each hit includes core fields like `index`, `id`, `score`, and `source`, along with additional optional fields. | + +### HitsMetadataHitsInner fields + +Each `HitsMetadataHitsInner` represents a single document matched by the query and contains the following fields. + +| Field | Protobuf type | Description | +| :---- | :---- | :---- | +| `x_type` | `string` | The document type. | +| `x_index` | `string` | The name of the index containing the returned document. | +| `x_id` | `string` | The unique ID for the document within the index. | +| `x_score` | [`HitXScore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L395) | The relevance score of the hit. | +| `x_explanation` | [`Explanation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L826) | A text explanation of how the `_score` was calculated. | +| `fields` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | The document field values. | +| `highlight` | `map` | The highlighted fields and fragments per hit. | +| `inner_hits` | `map` | The matching nested documents from a different scope that contributed to the overall query result. | +| `matched_queries` | `repeated string` | **Deprecated.** A list of query names matching the document. | +| `x_nested` | [`NestedIdentity`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L838) | The path to the inner nested object from which the hit originated. | +| `x_ignored` | `repeated string` | A list of ignored fields. | +| `ignored_field_values` | `map` | Raw, unprocessed values from the document's original JSON. | +| `x_shard` | `string` | The shard ID from which the hit was retrieved. | +| `x_node` | `string` | The node ID from which the hit was retrieved. | +| `x_routing` | `string` | The routing value used for custom shard routing. | +| `x_source` | `bytes` | The Base64-encoded `_source` document. | +| `x_seq_no` | `int64` | The sequence number (used for indexing history and versioning). | +| `x_primary_term` | `int64` | The primary term number (used for optimistic concurrency control). | +| `x_version` | `int64` | The document version number. | +| `sort` | `repeated` [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | The sort values used for result sorting. | +| `meta_fields` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | The metadata values for the document. | +| `matched_queries_2` | [`HitMatchedQueries`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2851) | The current protobuf representation of matched query names for the document. | + +`source` is Base64 encoded and must be decoded to obtain the JSON document. +{: .note} + +## Example response + +```json +{ + "response_body": { + "took": 64, + "timed_out": false, + "shards": { + "successful": 1, + "total": 1 + }, + "hits": { + "total": { + "total_hits": { + "relation": "TOTAL_HITS_RELATION_EQ", + "value": 1 + } + }, + "hits": [ + { + "index": "my_index", + "id": "3", + "score": { + "float_value": 1.0 + }, + "source": "eyAidGl0bGUiOiAiUnVzaCIsICJ5ZWFyIjogMjAxM30=", + "meta_fields": {} + } + ], + "max_score": { + "float_value": 1.0 + } + } + } +} +``` +{% include copy.html %} + +## Java gRPC client example + +The following example shows a Java client-side program that submits an example search term query gRPC request and then prints the number of hits returned in the search response: + +```java +import org.opensearch.protobufs.*; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +public class SearchClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + SearchServiceGrpc.SearchServiceBlockingStub stub = SearchServiceGrpc.newBlockingStub(channel); + + // Create a term query + TermQuery termQuery = TermQuery.newBuilder() + .setField("director") + .setValue(FieldValue.newBuilder().setStringValue("Nolan").build()) + .build(); + + // Create query container + QueryContainer queryContainer = QueryContainer.newBuilder() + .setTerm(termQuery) + .build(); + + // Create search request body + SearchRequestBody requestBody = SearchRequestBody.newBuilder() + .setQuery(queryContainer) + .setSize(5) + .build(); + + // Create search request + SearchRequest request = SearchRequest.newBuilder() + .addIndex("movies") + .setSearchRequestBody(requestBody) + .build(); + + try { + SearchResponse response = stub.search(request); + + // Handle the response + System.out.println("Search took: " + response.getTook() + " ms"); + System.out.println("Timed out: " + response.getTimedOut()); + + HitsMetadata hits = response.getHits(); + if (hits.hasTotal()) { + System.out.println("Total hits: " + hits.getTotal().getTotalHits().getValue()); + } + + // Process individual hits + for (HitsMetadataHitsInner hit : hits.getHitsList()) { + System.out.println("Hit ID: " + hit.getXId()); + System.out.println("Hit Index: " + hit.getXIndex()); + if (hit.hasXScore()) { + System.out.println("Score: " + hit.getXScore().getDouble()); + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC search request failed with status: " + e.getStatus()); + System.err.println("Error message: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` +{% include copy.html %} + +## Python gRPC client example + +The following example shows how to send the same request using a Python client application. + +First, install the `opensearch-protobufs` package using `pip`: + +```bash +pip install opensearch-protobufs==1.2.0 +``` +{% include copy.html %} + +Use the following code to send the request: + +```python +import grpc + +from opensearch.protobufs.schemas import * +from opensearch.protobufs.services import SearchServiceStub + + +channel = grpc.insecure_channel( + target="localhost:9400", +) + +search_stub = SearchServiceStub(channel) + +# Create a term query +term_query = TermQuery( + field="field", + value=FieldValue(string="value") +) +query_container = QueryContainer(term=term_query) + +# Create a search request +request = SearchRequest( + search_request_body=SearchRequestBody(query=query_container), + index=["my-index"] +) + +# Send request and handle response +try: + response = search_stub.Search(request=request) + if response.hits: + print("Found {} hits".format(response.hits.total)) + print(response.hits) + elif response.timed_out or response.terminated_early: + print("Request timed out or terminated early") + elif response.x_shards.failed: + print("Some shards failed to execute the search") + print(response.x_shards.failures) +except grpc.RpcError as e: + if e.code() == StatusCode.UNAVAILABLE: + print("Failed to reach server: {}".format(e)) + elif e.code() == StatusCode.PERMISSION_DENIED: + print("Permission denied: {}".format(e)) + elif e.code() == StatusCode.INVALID_ARGUMENT: + print("Invalid argument: {}".format(e)) +finally: + channel.close() +``` diff --git a/_api-reference/index-apis/blocks.md b/_api-reference/index-apis/blocks.md new file mode 100644 index 00000000..e0f3bdc6 --- /dev/null +++ b/_api-reference/index-apis/blocks.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Blocks +parent: Index blocks and allocation +grand_parent: Index APIs +nav_order: 10 +--- + +# Blocks API +**Introduced 1.0** +{: .label .label-purple } + +Use the Blocks API to limit certain operations on a specified index. Different types of blocks allow you to restrict index write, read, or metadata operations. +For example, adding a `write` block through the API ensures that all index shards have properly accounted for the block before returning a successful response. Any in-flight write operations to the index must be complete before the `write` block takes effect. + +## Endpoints + +```json +PUT /{index}/_block/{block} +``` + +## Path parameters + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | A comma-separated list of index names. Wildcard expressions (`*`) are supported. To target all indexes in the cluster, use `_all` or `*`. Data stream names are not supported, and you cannot add a block to the write index of a data stream. Required. | +| `block` | String | The type of block to apply to the index. Required. Valid values are:
- `metadata`: Blocks both retrieving and changing index metadata. For example, you cannot close the index or get its settings.
- `read`: Blocks read operations.
- `read_only`: Blocks write operations and metadata changes.
- `write`: Blocks write operations but allows metadata changes.
- `search_only`: Blocks indexing and write operations while allowing read-only access through search replicas.
OpenSearch automatically manages this block through the Scale API as part of the reader-writer separation mechanism. Therefore, do not set this parameter manually. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `ignore_unavailable` | Boolean | When `false`, the request returns an error when it targets a missing or closed index. Default is `false`. | +| `allow_no_indices` | Boolean | When `false`, the request returns an error when a wildcard expression, index alias, or `_all` does not match any indexes. Default is `true`. | +| `expand_wildcards` | String | The type of index that wildcard expressions can match. Supports comma-separated values, such as `open,hidden`. Valid values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. | +| `cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. | +| `timeout` | Time | The amount of time to wait for the request to return. Default is `30s`. | + +## Example request + +The following example request disables any `write` operations made to the test index: + + +{% capture step1_rest %} +PUT /test-index/_block/write +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.add_block( + block = "write", + index = "test-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged" : true, + "shards_acknowledged" : true, + "indices" : [ { + "name" : "test-index", + "blocked" : true + } ] +} +``` + +## Removing a block + +The Blocks API only adds blocks. To remove a block, set the corresponding index setting to `false` using the Update Index Settings API. The setting name follows the block name: `index.blocks.read`, `index.blocks.read_only`, `index.blocks.metadata`, or `index.blocks.write`. For more information, see [Update Index Settings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/). + +The following example request removes the `write` block from the test index: + +```json +PUT /test-index/_settings +{ + "index.blocks.write": false +} +``` +{% include copy-curl.html %} + +If an index has a `read_only`, `read_only_allow_delete`, or `metadata` block, the request that removes the block must contain only that block setting. Remove the block in a separate request before updating any other settings. + +OpenSearch adds the `index.blocks.read_only_allow_delete` block to indexes that have shards on a node whose disk usage exceeds the flood-stage watermark. OpenSearch removes the block when disk usage falls below the high watermark. For more information, see [Cluster-level routing and allocation settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/#cluster-level-routing-and-allocation-settings). + +OpenSearch manages the `search_only` block through the Scale API, so do not remove it using the Update Index Settings API. To disable search-only mode, see [Scale API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/scale/). diff --git a/_api-reference/index-apis/clear-index-cache.md b/_api-reference/index-apis/clear-index-cache.md index 55a5ce85..c97dec07 100644 --- a/_api-reference/index-apis/clear-index-cache.md +++ b/_api-reference/index-apis/clear-index-cache.md @@ -1,25 +1,29 @@ --- layout: default title: Clear cache -parent: Index APIs +parent: Index operations +grand_parent: Index APIs nav_order: 10 --- -# Clear cache +# Clear Cache API **Introduced 1.0** {: .label .label-purple } The clear cache API operation clears the caches of one or more indexes. For data streams, the API clears the caches of the stream’s backing indexes. +## Endpoints -If you use the Security plugin, you must have the `manage index` privileges. -{: .note} +```json +POST /_cache/clear +POST /{target}/_cache/clear +``` ## Path parameters | Parameter | Data type | Description | :--- | :--- | :--- -| target | String | Comma-delimited list of data streams, indexes, and index aliases to which cache clearing is applied. Wildcard expressions (`*`) are supported. To target all data streams and indexes in a cluster, omit this parameter or use `_all` or `*`. Optional. | +| `target` | String | Comma-delimited list of data streams, indexes, and index aliases to which cache clearing is applied. Wildcard expressions (`*`) are supported. To target all data streams and indexes in a cluster, omit this parameter or use `_all` or `*`. Optional. | ## Query parameters @@ -28,82 +32,210 @@ All query parameters are optional. | Parameter | Data type | Description | :--- | :--- | :--- -| allow_no_indices | Boolean | Whether to ignore wildcards, index aliases, or `_all` target (`target` path parameter) values that don’t match any indexes. If `false`, the request returns an error if any wildcard expression, index alias, or `_all` target value doesn't match any indexes. This behavior also applies if the request targets include other open indexes. For example, a request where the target is `fig*,app*` returns an error if an index starts with `fig` but no index starts with `app`. Defaults to `true`. | -| expand_wildcards | String | Determines the index types that wildcard expressions can expand to. Accepts multiple values separated by a comma, such as `open,hidden`. Valid values are:

`all` -- Expand to open, closed, and hidden indexes.

`open` -- Expand only to open indexes.

`closed` -- Expand only to closed indexes

`hidden` -- Expand to include hidden indexes. Must be combined with `open`, `closed`, or `both`.

`none` -- Expansions are not accepted.

Defaults to `open`. | -| fielddata | Boolean | If `true`, clears the fields cache. Use the `fields` parameter to clear specific fields' caches. Defaults to `true`. | -| fields | String | Used in conjunction with the `fielddata` parameter. Comma-delimited list of field names that are cleared out of the cache. Does not support objects or field aliases. Defaults to all fields. | -| file | Boolean | If `true`, clears the unused entries from the file cache on nodes with the Search role. Defaults to `false`. | -| index | String | Comma-delimited list of index names that are cleared out of the cache. | -| ignore_unavailable | Boolean | If `true`, OpenSearch ignores missing or closed indexes. Defaults to `false`. | -| query | Boolean | If `true`, clears the query cache. Defaults to `true`. | -| request | Boolean | If `true`, clears the request cache. Defaults to `true`. | +| `allow_no_indices` | Boolean | Whether to ignore wildcards, index aliases, or `_all` target (`target` path parameter) values that don’t match any indexes. If `false`, the request returns an error if any wildcard expression, index alias, or `_all` target value doesn't match any indexes. This behavior also applies if the request targets include other open indexes. For example, a request where the target is `fig*,app*` returns an error if an index starts with `fig` but no index starts with `app`. Default is `true`. | +| `expand_wildcards` | String | Determines the index types that wildcard expressions can expand to. Accepts multiple values separated by a comma, such as `open,hidden`. Valid values are:

`all` -- Expand to open, closed, and hidden indexes.

`open` -- Expand only to open indexes.

`closed` -- Expand only to closed indexes

`hidden` -- Expand to include hidden indexes. Must be combined with `open` or `closed`.

`none` -- Expansions are not accepted.

Default is `open`. Caches of closed indexes cannot be cleared, so a request using `closed` or `all` fails if a wildcard expression matches a closed index, unless `ignore_unavailable` is `true`. | +| `fielddata` | Boolean | If `true`, clears the fields cache. Use the `fields` parameter to clear specific fields' caches. Default is `false`. | +| `fields` | String | Comma-delimited list of field names whose fielddata is cleared from the cache. If specified without other cache parameters, clears only the fielddata of the listed fields. Does not support objects or field aliases. Default is all fields. | +| `file` | Boolean | If `true`, clears the unused entries from the file cache on nodes with the Search role. Unless `query` or `fielddata` is also `true` or `fields` is specified, setting `file` to `true` also clears all index caches. Default is `false`. | +| `index` | String | Comma-delimited list of indexes whose caches are cleared. An alternative to the `target` path parameter for the `POST /_cache/clear` endpoint. | +| `ignore_unavailable` | Boolean | If `true`, OpenSearch ignores missing or closed indexes. Default is `false`. | +| `query` | Boolean | If `true`, clears the query cache. Default is `false`. | +| `request` | Boolean | If `true`, clears the request cache. Default is `false`. | -#### Example requests +If none of the `fielddata`, `query`, `request`, or `fields` parameters is specified, all caches are cleared. Setting `fielddata` or `query` to `true` clears only that cache. If `request` is the only cache parameter set to `true` and `fields` is not specified, all caches are cleared. + +Field data entries are removed during the next cache cleanup, which runs at the interval specified by the `indices.cache.cleanup_interval` setting (default `1m`). Until then, fielddata statistics can show the size before the cache was cleared. +{: .note} + +## Example requests The following example requests show multiple clear cache API uses. -##### Clear a specific cache +### Clear a specific cache The following request clears the fields cache only: -```json + +{% capture step1_rest %} POST /my-index/_cache/clear?fielddata=true -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.clear_cache( + index = "my-index", + params = { "fielddata": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} +
The following request clears the query cache only: -```json + +{% capture step1_rest %} POST /my-index/_cache/clear?query=true -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.clear_cache( + index = "my-index", + params = { "query": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} +
The following request clears the request cache only: -```json + +{% capture step1_rest %} POST /my-index/_cache/clear?request=true -``` -{% include copy-curl.html %} +{% endcapture %} -#### Clear the cache for specific fields +{% capture step1_python %} -The following request clears the fields caches of `fielda` and `fieldb`: -```json -POST /my-index/_cache/clear?fields=fielda,fieldb -``` -{% include copy-curl.html %} +response = client.indices.clear_cache( + index = "my-index", + params = { "request": "true" } +) -#### Clear caches for specific data streams or indexes +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Clear the cache for specific fields + +The following request clears the fields caches of `product_name` and `category`: + + +{% capture step1_rest %} +POST /my-index/_cache/clear?fields=product_name,category +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.clear_cache( + index = "my-index", + params = { "fields": "product_name,category" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Clear caches for specific data streams or indexes The following request clears the cache for two specific indexes: -```json + +{% capture step1_rest %} POST /my-index,my-index2/_cache/clear -``` -{% include copy-curl.html %} +{% endcapture %} -#### Clear caches for all data streams and indexes +{% capture step1_python %} + + +response = client.indices.clear_cache( + index = "my-index,my-index2" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Clear caches for all data streams and indexes The following request clears the cache for all data streams and indexes: -```json + +{% capture step1_rest %} POST /_cache/clear -``` -{% include copy-curl.html %} +{% endcapture %} -#### Clear unused entries from the cache on search-capable nodes +{% capture step1_python %} -```json -POST /*/_cache/clear?file=true -``` -{% include copy-curl.html %} +response = client.indices.clear_cache() +{% endcapture %} -#### Example response +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +### Clear unused entries from the cache on search-capable nodes + +The following request clears unused entries from the file cache on nodes with the Search role: + + +{% capture step1_rest %} +POST /*/_cache/clear?file=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.clear_cache( + index = "*", + params = { "file": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The `POST /books,hockey/_cache/clear` request returns the following fields: @@ -117,13 +249,22 @@ The `POST /books,hockey/_cache/clear` request returns the following fields: } ``` -## Response fields +## Response body fields The `POST /books,hockey/_cache/clear` request returns the following response fields: | Field | Data type | Description | :--- | :--- | :--- -| _shards | Object | Shard information. | -| total | Integer | Total number of shards. | -| successful | Integer | Number of index shards with caches successfully cleared. | -| failed | Integer | Number of index shards with caches that failed to clear. | +| `_shards` | Object | Shard information. | + +The `_shards` object contains the following fields. + +| Field | Data type | Description | +:--- | :--- | :--- +| `total` | Integer | Total number of shards. | +| `successful` | Integer | Number of index shards with caches successfully cleared. | +| `failed` | Integer | Number of index shards with caches that failed to clear. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/cache/clear`. diff --git a/_api-reference/index-apis/clone.md b/_api-reference/index-apis/clone.md index 60228b58..9aea7ab8 100644 --- a/_api-reference/index-apis/clone.md +++ b/_api-reference/index-apis/clone.md @@ -1,42 +1,100 @@ --- layout: default title: Clone index -parent: Index APIs -nav_order: 15 +parent: Index operations +grand_parent: Index APIs +nav_order: 20 redirect_from: - /opensearch/rest-api/index-apis/clone/ --- -# Clone index +# Clone Index API **Introduced 1.0** {: .label .label-purple } -The clone index API operation clones all data in an existing read-only index into a new index. The new index cannot already exist. +The clone index API clones an existing index into a new index, where each original primary shard is cloned into a new primary shard in the target index. -## Example +Use this API in the following scenarios: -```json -PUT /sample-index1/_clone/cloned-index1 +- Creating a backup copy of an index with the same number of shards before making destructive changes. +- Testing configuration changes on a cloned copy while preserving the original index. +- Duplicating an index for parallel processing workflows with different settings or aliases. + +The clone operation follows a three-step process to efficiently duplicate index data: + +1. OpenSearch creates a target index with the same definition as the source index, including mappings and settings. +2. The system creates hard links from the source index segments to the target index. If the file system does not support hard linking, OpenSearch copies all segments to the target index, which requires more time and disk space. +3. OpenSearch recovers the target index as if it were a closed index that has been reopened, making it available for use. + +## Prerequisites + +Before cloning an index, you must prepare the source index by marking it as read-only and ensuring the cluster is healthy: + +- The source index must have the `index.blocks.write` setting set to `true` to prevent write operations during the cloning process. Metadata changes, such as deleting the index, are still allowed. +- The cluster health status must be `green` to ensure all primary and replica shards are available. + +The following example request sets the `products` index to read-only mode so that it can be cloned: + + +{% capture step1_rest %} +PUT /products/_settings +{ + "settings": { + "index.blocks.write": true + } +} +{% endcapture %} -## Path and HTTP methods +{% capture step1_python %} + +response = client.indices.put_settings( + index = "products", + body = { + "settings": { + "index.blocks.write": true + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + + + +## Endpoints +```json +POST /{index}/_clone/{target} +PUT /{index}/_clone/{target} ``` -POST //_clone/ -PUT //_clone/ -``` + + +## Requirements + +An index can only be cloned if it meets the following requirements: + +- The target index must not already exist. +- The source index must have the same number of primary shards as the target index. +- The source index must be marked as read-only by setting `index.blocks.write` to `true`. +- The cluster health status must be `green`. +- The node handling the clone process must have sufficient free disk space to accommodate a second copy of the index if hard linking is not supported by the file system. ## Index naming restrictions @@ -48,30 +106,196 @@ OpenSearch indexes have the following naming restrictions: `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<` -## URL parameters +## Path parameters -Your request must include the source and target indexes. All other clone index parameters are optional. +The following table lists the available path parameters. -Parameter | Type | Description +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the source index to clone. | +| `target` | **Required** | String | The name of the target index to create. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | +| `task_execution_timeout` | String | The amount of time to wait for the task to complete. Only applicable when `wait_for_completion` is set to `false`. | `1h` | +| `timeout` | String | The amount of time to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. | `30s` | +| `wait_for_active_shards` | String | The number of active shard copies required for the operation to proceed. Specify `all` or any positive integer up to the total number of shards in the index (`number_of_replicas+1`). | `1` (only the primary shard) | +| `wait_for_completion` | Boolean | Specifies whether to wait for the operation to complete before returning a response. | `true` | + +## Request body fields + +The clone index API creates a new target index, so you can specify index settings and aliases to apply to the target index in the request body. The request body is optional. + +Field | Data type | Description :--- | :--- | :--- -<source-index> | String | The source index to clone. -<target-index> | String | The index to create and add cloned data to. -wait_for_active_shards | String | The number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the operation to succeed. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for the request to return. Default is `30s`. -wait_for_completion | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. Default is `true`. -task_execution_timeout | Time | The explicit task execution timeout. Only useful when wait_for_completion is set to `false`. Default is `1h`. +`settings` | Object | Configuration options for the target index. For a list of index settings, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). Optional. +`settings.index.number_of_shards` | Integer | The number of primary shards in the target index. This value must equal the number of primary shards in the source index. Optional. Default is the same as the source index. +`settings.index.number_of_replicas` | Integer | The number of replica shards for each primary shard in the target index. Optional. Default is the same as the source index. +`aliases` | Object | Index aliases to apply to the target index. Each key is an alias name, and the value is an alias configuration object. For more information, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). Optional. -## Request body +**Note**: You cannot specify mappings in the clone request. The mappings from the source index are automatically used for the target index. +{: .note} -The clone index API operation creates a new target index, so you can specify any [index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/) and [aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias/) to apply to the target index. +## Example: Cloning an index -## Response +The following example request clones the `products` index into a new index named `products-clone`: + + +{% capture step1_rest %} +POST /products/_clone/products-clone +{} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.clone( + index = "products", + target = "products-clone", + body = {} +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Cloning an index with settings and aliases + +The following example request clones the `products` index into a new index named `products-clone-configured` with custom settings and an alias: + + +{% capture step1_rest %} +POST /products/_clone/products-clone-configured +{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "aliases": { + "products-search": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.clone( + index = "products", + target = "products-clone-configured", + body = { + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "aliases": { + "products-search": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +OpenSearch returns the following response when the clone request is successful. The `index` field contains the name of the target index that was created: ```json { - "acknowledged": true, - "shards_acknowledged": true, - "index": "cloned-index1" + "acknowledged": true, + "shards_acknowledged": true, + "index": "products-clone" } ``` + +The response returns immediately once the target index has been added to the cluster state. It does not wait for the clone operation to complete. + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`acknowledged` | Boolean | Indicates whether the clone request was received by the cluster. A value of `true` means the request was received. +`shards_acknowledged` | Boolean | Indicates whether the number of shard copies specified by the `wait_for_active_shards` setting became active before the operation timed out. A value of `true` means the target number of shard copies became active. A value of `false` means that the operation timed out before the target number of shard copies became active. +`index` | String | The name of the newly created target index. + +## Monitoring the cloning process + +The clone API returns immediately after adding the target index to the cluster state, before any shards are allocated. At this point, all shards are in the `unassigned` state. If the target index cannot be allocated for any reason, its primary shards will remain `unassigned` until they can be allocated on a node. + +Once a primary shard is allocated, it transitions to the `initializing` state, and the clone operation begins. When the clone operation completes, the shard becomes `active`. OpenSearch then attempts to allocate any replicas and may relocate the primary shard to another node. + +You can monitor the cloning process using one of the following methods: + +- To view the progress of shard recovery and cloning, use the [CAT recovery API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/). +- To wait until all primary shards have been allocated, use the [Cluster health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) with the `wait_for_status` parameter set to `yellow`. + +The following example request monitors the recovery process for the cloned index: + + +{% capture step1_rest %} +GET /_cat/recovery/products-clone?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.cat.recovery( + index = "products-clone", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Wait for active shards + +Because the clone operation creates a new index, the `wait_for_active_shards` setting for index creation also applies to the clone operation. This setting determines how many shard copies must be active before the operation returns a response. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/resize`. diff --git a/_api-reference/index-apis/close-index.md b/_api-reference/index-apis/close-index.md index e8d2e3e1..14609ca0 100644 --- a/_api-reference/index-apis/close-index.md +++ b/_api-reference/index-apis/close-index.md @@ -1,47 +1,80 @@ --- layout: default title: Close index -parent: Index APIs -nav_order: 20 +parent: Core index APIs +grand_parent: Index APIs +nav_order: 60 redirect_from: - /opensearch/rest-api/index-apis/close-index/ --- -# Close index +# Close Index API **Introduced 1.0** {: .label .label-purple } The close index API operation closes an index. Once an index is closed, you cannot add data to it or search for any data within the index. -#### Example +OpenSearch blocks all read and write operations on a closed index. Requests that search or index documents in a closed index fail. Because a closed index does not serve requests, OpenSearch does not maintain the in-memory structures used for indexing and searching, which reduces the index's overhead on the cluster. To make the index available again, use the [Open Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/open-index/). + +When you close or open an index, the cluster manager restarts the index's shards, which then go through the normal recovery process. OpenSearch continues to replicate the data of closed indexes so that enough shard copies remain available. + +Closed indexes still occupy disk space. Closing an index does not free disk space. To reclaim space, delete indexes that you no longer need. To prevent users from closing indexes, set the `cluster.indices.close.enable` cluster setting to `false`. OpenSearch then rejects all requests to close an index. For more information, see [Cluster settings for indexes]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/). +{: .warning} + + +## Endpoints ```json -POST /sample-index/_close -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -POST //_close +POST /{index}/_close ``` -## URL parameters +## Path parameters + +Parameter | Type | Description +:--- | :--- | :--- +`index` | String | The index to close. Can be a comma-separated list of multiple index names. Use `_all` or `*` to close all indexes. To prevent closing indexes using `_all` or wildcard expressions, set the `action.destructive_requires_name` cluster setting to `true`. + +## Query parameters All parameters are optional. Parameter | Type | Description :--- | :--- | :--- -<index-name> | String | The index to close. Can be a comma-separated list of multiple index names. Use `_all` or * to close all indexes. -allow_no_indices | Boolean | Whether to ignore wildcards that don't match any indexes. Default is true. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions). Default is open. -ignore_unavailable | Boolean | If true, OpenSearch does not search for missing or closed indexes. Default is false. -wait_for_active_shards | String | Specifies the number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for a response from the cluster. Default is `30s`. +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. +`expand_wildcards` | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions). Default is `open`. +`ignore_unavailable` | Boolean | If true, OpenSearch does not search for missing or closed indexes. Default is `false`. +`wait_for_active_shards` | String | Specifies the number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. +`cluster_manager_timeout` | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. +`timeout` | Time | How long to wait for a response from the cluster. Default is `30s`. + +## Example requests + + +{% capture step1_rest %} +POST /sample-index/_close + +{% endcapture %} + +{% capture step1_python %} -## Response +response = client.indices.close( + index = "sample-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json { "acknowledged": true, @@ -53,3 +86,7 @@ timeout | Time | How long to wait for a response from the cluster. Default is `3 } } ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/close` and `indices:admin/close*`. diff --git a/_api-reference/index-apis/component-template.md b/_api-reference/index-apis/component-template.md new file mode 100644 index 00000000..10e05e87 --- /dev/null +++ b/_api-reference/index-apis/component-template.md @@ -0,0 +1,476 @@ +--- +layout: default +title: Component template APIs +parent: Index templates +grand_parent: Index APIs +nav_order: 60 +--- + +# Component template APIs +**Introduced 1.0** +{: .label .label-purple } + +You can use the component template APIs to create, retrieve, update, and delete component templates. A component template is a reusable building block that defines settings, mappings, and aliases and can be shared across multiple index templates. + +An index template can be constructed using multiple component templates. To incorporate a component template into an index template, you need to list it in the `composed_of` section of the index template. Component templates are only applied to newly created data streams and indexes that match the criteria specified in the index template. + +If any settings or mappings are directly defined in the index template or the index creation request, those settings will take precedence over the settings or mappings specified in a component template. + +Component templates are used solely during the process of index creation. For data streams, this includes the creation of the data stream itself and the creation of the backing indexes that support the stream. Modifications made to component templates will not affect existing indexes, including the backing indexes of a data stream. + +## Endpoints + +```json +PUT _component_template/{component-template-name} +GET _component_template/{component-template-name} +DELETE _component_template/{component-template-name} +HEAD _component_template/{component-template-name} +``` + +- `PUT`: Creates or updates a component template. Accepts both query parameters and a request body. +- `GET`: Retrieves information about an existing component template. Accepts only query parameters. +- `DELETE`: Deletes an existing component template. Accepts only query parameters. +- `HEAD`: Returns whether a component template exists. Returns only HTTP status codes. + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`component-template-name` | String | The name of the component template. Required for PUT, HEAD, and DELETE operations. Optional for GET operations. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description | Supported operations +:--- | :--- | :--- | :--- +`create` | Boolean | When true, the API cannot replace or update any existing component templates. Default is `false`. | PUT +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. | PUT, GET, DELETE + +## Create or update a component template + +Use the PUT operation to create a new component template or update an existing one. + +### Endpoints + +```json +PUT _component_template/{component-template-name} +``` + +### Request body fields + +The following table lists the available request body fields. + + +Parameter | Data type | Description +:--- | :--- | :--- +`template` | Object | The template that includes the `aliases`, `mappings`, or `settings` for the index. For more information, see [#template]. Required. +`version` | Integer | The version number used to manage index templates. Version numbers are not automatically set by OpenSearch. Optional. +`_meta` | Object | The metadata that provides details about the index template. Optional. +`allow_auto_create` | Boolean | When `true`, indexes can be automatically created with this template even if the `actions.auto_create_index` is disabled. When `false`, indexes and data streams matching the template cannot be automatically created. Optional. +`deprecated` | Boolean | When `true`, the component template is deprecated. If deprecated, OpenSearch will output a warning whenever the template is referenced. + + +### Template + +You can use the following objects with the `template` option in the request body. + +#### `alias` + +The name of the alias to associate with the template as a key. Required when the `template` option exists in the request body. This option supports multiple aliases. + +The object body contains the following optional alias parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`filter` | Query DSL object | The query that limits the number of documents that the alias can access. +`index_routing` | String | The value that routes the indexing operations to a specific shard. When specified, overwrites the `routing` value for the indexing operations. +`is_hidden` | Boolean | When `true`, the alias is hidden. Default is false. All alias indexes must have matching values for this setting. +`is_write_index` | Boolean | When `true`, the index is the write index for the alias. Default is `false`. +`routing` | String | The value used to route index and search operations to a specific shard. +`search_routing` | String | The value used to write search operations to a specific shard. When specified, this option overwrites the `routing` value for the search operations. + +#### `mappings` + +The field mappings that exist in the index. For more information, see [Mappings and field types]({{site.url}}{{site.baseurl}}/mappings/). Optional. + +#### `settings` + +Any configuration options for the index. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +### Example request: Create a component template with index aliases + +The following example request creates a component template including index aliases: + + +{% capture step1_rest %} +PUT /_component_template/alias_template +{ + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_component_template( + name = "alias_template", + body = { + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Add component versioning + +The following example adds a `version` number to a component template which simplifies template management for external systems: + + +{% capture step1_rest %} +PUT /_component_template/version_template +{ + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 3 +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_component_template( + name = "version_template", + body = { + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 3 + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Add template metadata + +The following example request uses the `_meta` parameter to add metadata to the component template. All metadata is stored in the cluster state. + + +{% capture step1_rest %} +PUT /_component_template/meta_template +{ + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.put_component_template( + name = "meta_template", + body = { + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Retrieve component template + +Use the GET operation to retrieve one or more component templates and their information. + +### Endpoints + +``` +GET /_component_template/{component-template-name} +GET /_component_template +``` + +### Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`component-template-name` | String | The name of the component template to retrieve. Supports wildcard expressions (`*`). If not specified, all component templates are returned. + +### Example request: Retrieve a component template by name + + +{% capture step1_rest %} +GET /_component_template/my_template +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.get_component_template( + name = "my_template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Retrieve component templates using a wildcard pattern + + +{% capture step1_rest %} +GET /_component_template/my_template* +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.get_component_template( + name = "my_template*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Retrieve all component templates + + +{% capture step1_rest %} +GET /_component_template +{% endcapture %} + +{% capture step1_python %} + +response = client.cluster.get_component_template() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Delete component template + +Use the DELETE operation to remove a component template from the cluster. + +**Important considerations**: +- Deleting a component template does not affect existing indexes that were created using the template. +- You cannot delete a component template that is currently referenced by an index template. +- The operation is irreversible. + +### Endpoints + +``` +DELETE _component_template/{component-template-name} +``` + +### Example request + + +{% capture step1_rest %} +DELETE /_component_template/my_template +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.delete_component_template( + name = "my_template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Check whether a component template exists + +Use the HEAD operation to check whether a component template exists without retrieving its contents. This operation returns only HTTP status codes and headers, with no response body. + +### Endpoints + +``` +HEAD _component_template/{component-template-name} +``` + +### Example request + + +{% capture step1_rest %} +HEAD /_component_template/my_template +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.exists_component_template( + name = "my_template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Response codes + +- `200`: The component template exists. +- `404`: The component template does not exist. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions. The following permissions are required for this API: + +- `cluster:admin/component_template/get`: Required for getting component templates +- `cluster:admin/component_template/put`: Required for creating or updating component templates +- `cluster:admin/component_template/delete`: Required for deleting component templates diff --git a/_api-reference/index-apis/core-index-apis.md b/_api-reference/index-apis/core-index-apis.md new file mode 100644 index 00000000..f7d29bd8 --- /dev/null +++ b/_api-reference/index-apis/core-index-apis.md @@ -0,0 +1,26 @@ +--- +layout: default +title: Core index APIs +parent: Index APIs +nav_order: 20 +has_children: true +has_toc: false +--- + +# Core index APIs + +Core index APIs provide fundamental operations for managing the lifecycle of indexes in your OpenSearch cluster. These APIs allow you to create, delete, and perform basic operations on indexes. + +## Available APIs + +OpenSearch supports the following core index APIs. + +| API | Description | +|-----|-------------| +| [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/) | Creates a new index. | +| [Delete index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-index/) | Deletes an existing index. | +| [Get index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-index/) | Returns information about one or more indexes. | +| [Index exists]({{site.url}}{{site.baseurl}}/api-reference/index-apis/exists/) | Checks if an index exists. | +| [Open index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/open-index/) | Opens a closed index. | +| [Close index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/close-index/) | Closes an open index. | +| [Resolve index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/resolve-index/) | Resolves index names and aliases to their concrete indexes. | \ No newline at end of file diff --git a/_api-reference/index-apis/create-index-template.md b/_api-reference/index-apis/create-index-template.md new file mode 100644 index 00000000..d8be4780 --- /dev/null +++ b/_api-reference/index-apis/create-index-template.md @@ -0,0 +1,457 @@ +--- +layout: default +title: Create or update index template +parent: Index templates +grand_parent: Index APIs +nav_order: 10 +--- + +# Create Or Update Index Template API +**Introduced 1.0** +{: .label .label-purple } + +Use the Create or Update Index Template API to create indexes with predefined mappings and settings as well as update existing index templates. + +## Endpoints + +```json +PUT _index_template/{template-name} +POST _index_template/{template-name} +``` + +## Path parameters + +Parameter | Data type | Description +:--- | :--- | :--- +`template-name` | String | The name of the index template. + +## Query parameters + +The following optional query parameters are supported. + +Parameter | Data type | Description +:--- | :--- | :--- +`create` | Boolean | When true, the API cannot replace or update any existing index templates. Default is `false`. +`cause` | String | The reason for creating or updating the index template. Default is `api`. +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. + +## Request body fields + +The following options can be used in the request body to customize the index template. + + +Parameter | Type | Description +:--- | :--- | :--- +`index_patterns` | String array | An array of wildcard expressions used to match the names of data streams and indexes when they are created. Required. +`composed_of` | String array | An ordered list of component template names. These templates are merged using the specified order. For more information, see [Using multiple component templates](#using-multiple-component-templates). Optional. +`data_stream` | Object | When specified, the index template becomes a data stream template, and data streams with matching names can be created using it. The data stream backing indexes are always hidden. The object can contain a `timestamp_field` object, whose `name` field specifies the timestamp field for the data stream. Default `name` is `@timestamp`. Optional. +`_meta` | Object | Optional metadata that provides details about the index template. Optional. +`priority` | Long | A number that determines which index templates take precedence during the creation of a new index or data stream. OpenSearch chooses the template with the highest priority. When no priority is given, the template is assigned a `0`, signifying the lowest priority. Must be `0` or greater. Index templates with overlapping index patterns cannot have the same priority. Optional. +`template` | Object | The template that includes the `aliases`, `mappings`, or `settings` for the index. For more information, see [Template](#template). Optional. +`version` | Long | The version number used to manage index templates. Version numbers are not automatically set by OpenSearch. Optional. +`context` | Object | (Experimental) The `context` parameter provides use-case-specific predefined templates that can be applied to an index. Among all settings and mappings declared for a template, context templates hold the highest priority. Requires the `cluster.application_templates.enabled` setting to be `true`. The object contains the `name` (String, required) of the context, the context template `version` (String, default `_latest`), and optional `params` (Object). For more information, see [Index context]({{site.url}}{{site.baseurl}}/im-plugin/index-context/). Optional. + +### Template + +You can use the following objects with the `template` option in the request body. + +#### `aliases` + +The name of the alias to associate with the template as a key. This option supports multiple aliases. The alias name can include `{index}`, which is replaced with the name of the index when the index is created. + +The object body contains the following optional alias parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`filter` | Query DSL object | The query that limits the number of documents that the alias can access. +`index_routing` | String | The value that routes indexing operations to a specific shard. When specified, overwrites the `routing` value for indexing operations. +`is_hidden` | Boolean | When `true`, the alias is hidden. Default is `false`. All alias indexes must have matching values for this setting. +`is_write_index` | Boolean | When `true`, the index is the write index for the alias. Default is `false`. +`routing` | String | The value used to route index and search operations to a specific shard. +`search_routing` | String | The value used to route search operations to a specific shard. When specified, this option overwrites the `routing` value for search operations. + +#### `mappings` + +The field mappings that exist in the index. For more information, see [Mappings and field types]({{site.url}}{{site.baseurl}}/mappings/). Optional. + +#### `settings` + +Any configuration options for the index. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +## Example requests + +The following examples show how to use the Create or Update Index Template API. + +### Index template with index aliases + +The following example request includes index aliases in the template: + + +{% capture step1_rest %} +PUT /_index_template/alias-template +{ + "index_patterns": [ + "sh*" + ], + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_index_template( + name = "alias-template", + body = { + "index_patterns": [ + "sh*" + ], + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Using multiple matching templates + +When multiple index templates match the name of a new index or data stream, the template with the highest priority is used. For example, the following two requests create index templates with different priorities. + +The first request creates a template with priority `0` that matches index names starting with `h`: + +```json +PUT /_index_template/template_one +{ + "index_patterns" : ["h*"], + "priority" : 0, + "template": { + "settings" : { + "number_of_shards" : 1, + "number_of_replicas": 0 + }, + "mappings" : { + "_source" : { "enabled" : false } + } + } +} +``` +{% include copy-curl.html %} + +The second request creates a template with priority `1` that matches the narrower set of index names starting with `ha`: + +```json +PUT /_index_template/template_two +{ + "index_patterns" : ["ha*"], + "priority" : 1, + "template": { + "settings" : { + "number_of_shards" : 2 + }, + "mappings" : { + "_source" : { "enabled" : true } + } + } +} +``` +{% include copy-curl.html %} + +For indexes that start with `ha`, the `_source` is enabled. Because only `template_two` is applied, the index will have two primary shards and one replica. + +Overlapping index patterns given the same priority are not allowed. An error will occur when attempting to create a template matching an existing index template with identical priorities. +{: .note} + +### Adding template versioning + +The following example request adds a `version` number to an index template, which simplifies template management for external systems: + + +{% capture step1_rest %} +PUT /_index_template/versioned-template +{ + "index_patterns": [ + "mac", + "cheese" + ], + "priority": 0, + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 1 +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_index_template( + name = "versioned-template", + body = { + "index_patterns": [ + "mac", + "cheese" + ], + "priority": 0, + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 1 + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +### Adding template metadata + +The following example request uses the `_meta` parameter to add metadata to the index template. All metadata is stored in the cluster state: + + +{% capture step1_rest %} +PUT /_index_template/metadata-template +{ + "index_patterns": [ + "rom", + "juliet" + ], + "template": { + "settings": { + "number_of_shards": 2 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_index_template( + name = "metadata-template", + body = { + "index_patterns": [ + "rom", + "juliet" + ], + "template": { + "settings": { + "number_of_shards": 2 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Data stream definition + +Include a `data_stream` object to use an index template for data streams, as shown in the following example request: + + +{% capture step1_rest %} +PUT /_index_template/logs-template +{ + "index_patterns": [ + "logs-*" + ], + "data_stream": {} +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_index_template( + name = "logs-template", + body = { + "index_patterns": [ + "logs-*" + ], + "data_stream": {} + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Using multiple component templates + +When using multiple component templates with the `composed_of` field, the component templates are merged in the specified order. The settings, mappings, and aliases in the index template's own `template` object are merged after the component templates and override them. Settings specified in the create index request override both. + +In the following example, an index matching `my-index-*` has two merged primary shards. If the order in the `composed_of` array were reversed, then the index would have one primary shard. + +First, create a component template that sets one primary shard: + +```json +PUT /_component_template/template_with_1_shard +{ + "template": { + "settings": { + "index.number_of_shards": 1 + } + } +} +``` +{% include copy-curl.html %} + +Next, create a component template that sets two primary shards: + +```json +PUT /_component_template/template_with_2_shards +{ + "template": { + "settings": { + "index.number_of_shards": 2 + } + } +} +``` +{% include copy-curl.html %} + +Finally, create an index template that composes both component templates in order: + +```json +PUT /_index_template/composed-template +{ + "index_patterns": ["my-index-*"], + "composed_of": ["template_with_1_shard", "template_with_2_shards"] +} +``` +{% include copy-curl.html %} + + +Recursive merging is used for mapping definition and root options such as `dynamic_templates` and `meta`, meaning that when an earlier component contains a `meta` block, new `meta` entries are added to the end of the metadata in the index. Any entries containing a preexisting key are overwritten. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/index_template/put`. diff --git a/_api-reference/index-apis/create-index.md b/_api-reference/index-apis/create-index.md index 5e0d504f..3d04460f 100644 --- a/_api-reference/index-apis/create-index.md +++ b/_api-reference/index-apis/create-index.md @@ -1,26 +1,35 @@ --- layout: default title: Create index -parent: Index APIs -nav_order: 25 +parent: Core index APIs +grand_parent: Index APIs +nav_order: 10 redirect_from: - /opensearch/rest-api/index-apis/create-index/ - /opensearch/rest-api/create-index/ --- -# Create index +# Create Index API **Introduced 1.0** {: .label .label-purple } -While you can create an index by using a document as a base, you can also create an empty index for later use. +The Create Index API creates a new index in an OpenSearch cluster. -When creating an index, you can specify its mappings, settings, and aliases. +You can use the Create Index API to specify the following index configurations: -## Path and HTTP methods +- Index settings that control the index behavior, such as the number of shards and replicas. +- Field mappings that define the data types and properties for fields in documents stored in the index. +- Index aliases that provide alternate names for querying the index. + +## Endpoints +```json +PUT /{index} ``` -PUT -``` + ## Index naming restrictions @@ -32,46 +41,445 @@ OpenSearch indexes have the following naming restrictions: `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<` + ## Path parameters -| Parameter | Description | -:--- | :--- -| index | String | The index name. Must conform to the [index naming restrictions](#index-naming-restrictions). Required. | +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the index you wish to create. | + + ## Query parameters -You can include the following query parameters in your request. All parameters are optional. +The following table lists the available query parameters. All query parameters are optional. -Parameter | Type | Description +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | +| `timeout` | String | The amount of time to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. | +| `wait_for_active_shards` | Integer or String or NULL or String | The number of shard copies that must be active before proceeding with the operation. Set to `all` or any positive integer up to the total number of shards in the index (`number_of_replicas+1`).
Valid values are:
- `all`: Wait for all shards to be active. | + +## Request body fields + +You can include the following request body fields to configure the new index. All request body fields are optional. + +Field | Data type | Description :--- | :--- | :--- -wait_for_active_shards | String | Specifies the number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for the request to return. Default is `30s`. +`settings` | Object | Index-level settings for the index. For a list of index settings, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). Optional. +`settings.index.number_of_shards` | Integer | The number of primary shards in the index. Default is `1`. Optional. +`settings.index.number_of_replicas` | Integer | The number of replica shards for each primary shard. Default is `1`. Optional. +`settings.number_of_shards` | Integer | Simplified syntax for specifying the number of primary shards without the `index` prefix. Optional. +`settings.number_of_replicas` | Integer | Simplified syntax for specifying the number of replica shards without the `index` prefix. Optional. +`mappings` | Object | Field mappings for documents in the index. Defines the data type and properties for each field. For more information, see [Mappings]({{site.url}}{{site.baseurl}}/field-types/). Optional. +`mappings.properties` | Object | Defines the fields and their data types in documents. Each key is a field name, and each value is a field definition object. Optional. +`aliases` | Object | Index aliases for the index. Each key is an alias name, and each value is an alias definition object. For more information, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). Optional. -## Request body +**Note**: You do not have to explicitly specify the `index` section inside the `settings` section. You can use the simplified syntax instead. +{: .note} -As part of your request, you can optionally specify [index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/), [mappings]({{site.url}}{{site.baseurl}}/field-types/index/), and [aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias/) for your newly created index. +## Example: Creating a basic index -#### Example request +You typically do not need to explicitly create an empty index. OpenSearch automatically creates an index when you index a document into a non-existent index. However, explicitly creating an index is useful when you want to configure specific settings, mappings, or aliases before indexing data. -```json -PUT /sample-index1 +The following example request creates an index named `sample-index` without any settings, mappings, or aliases: + + +{% capture step1_rest %} +PUT /sample-index +{} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "sample-index", + body = {} +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Creating an index with settings + +The following example request creates an index named `books` with specific settings for the number of shards and replicas: + + +{% capture step1_rest %} +PUT /books +{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "books", + body = { + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Creating an index with simplified settings + +The following example request creates an index named `books-simplified` using the simplified settings syntax without the `index` prefix: + + +{% capture step1_rest %} +PUT /books-simplified +{ + "settings": { + "number_of_shards": 2, + "number_of_replicas": 1 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "books-simplified", + body = { + "settings": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Creating an index with mappings + +The following example request creates an index named `employees` with field mappings: + + +{% capture step1_rest %} +PUT /employees +{ + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + }, + "department": { + "type": "keyword" + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "employees", + body = { + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + }, + "department": { + "type": "keyword" + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Creating an index with aliases + +The following example request creates an index named `orders` with two aliases, including a filtered alias: + + +{% capture step1_rest %} +PUT /orders +{ + "aliases": { + "current-orders": {}, + "recent-orders": { + "filter": { + "range": { + "timestamp": { + "gte": "now-7d" + } + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "orders", + body = { + "aliases": { + "current-orders": {}, + "recent-orders": { + "filter": { + "range": { + "timestamp": { + "gte": "now-7d" + } + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +OpenSearch returns the following response when the create index request is successful: + +```json +{ + "acknowledged": true, + "shards_acknowledged": true, + "index": "books" +} ``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`acknowledged` | Boolean | Indicates whether the index was successfully created in the cluster. A value of `true` means the cluster state was successfully updated with the new index. A value of `false` means the request timed out before the cluster state was updated, but the index will likely be created. +`shards_acknowledged` | Boolean | Indicates whether the number of shard copies specified by the `wait_for_active_shards` setting became active before the operation timed out. A value of `true` means the target number of shard copies became active. A value of `false` means that the operation timed out before the target number of shard copies became active, regardless of whether the cluster state was successfully updated (that is, `acknowledged` is `true`). +`index` | String | The name of the newly created index. + +## Wait for active shards + +By default, the create index operation returns a response to the client only after the primary copies of each shard have been started or the request times out. You can use the response fields to understand the result of the operation. + +The `acknowledged` field indicates whether the index was successfully created in the cluster state. The `shards_acknowledged` field indicates whether the target number of shard copies became active before the timeout. Both fields can be `false` if the operation times out, but the index creation may still succeed. + +If `acknowledged` is `false`, the cluster state update timed out, but the index will likely be created soon. If `shards_acknowledged` is `false`, the target number of shard copies did not become active before the timeout, regardless of whether the cluster state was updated successfully. + +You can change the default behavior of waiting only for primary shards to start by using one of the following methods: + +- Set the `index.write.wait_for_active_shards` index setting when creating the index. This setting also affects the `wait_for_active_shards` behavior for subsequent write operations. +- Use the `wait_for_active_shards` query parameter in the create index request. + +### Example: Using the index.write.wait_for_active_shards setting + +The following example request creates an index with the `index.write.wait_for_active_shards` setting, which waits for two shard copies to be active before returning. This setting also affects subsequent write operations on the index: + + +{% capture step1_rest %} +PUT /inventory +{ + "settings": { + "index.write.wait_for_active_shards": "2", + "number_of_shards": 1, + "number_of_replicas": 1 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "inventory", + body = { + "settings": { + "index.write.wait_for_active_shards": "2", + "number_of_shards": 1, + "number_of_replicas": 1 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example: Using the wait_for_active_shards query parameter + +The following example request creates an index and uses the `wait_for_active_shards` query parameter to wait for two shard copies (primary and one replica) to be active before returning: + + +{% capture step1_rest %} +PUT /catalog?wait_for_active_shards=2 +{ + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "catalog", + params = { "wait_for_active_shards": "2" }, + body = { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/create`. diff --git a/_api-reference/index-apis/dangling-index.md b/_api-reference/index-apis/dangling-index.md index 9d40687f..a57adf8a 100644 --- a/_api-reference/index-apis/dangling-index.md +++ b/_api-reference/index-apis/dangling-index.md @@ -2,7 +2,7 @@ layout: default title: Dangling indexes parent: Index APIs -nav_order: 30 +nav_order: 90 --- # Dangling indexes API @@ -11,24 +11,24 @@ nav_order: 30 After a node joins a cluster, dangling indexes occur if any shards exist in the node's local directory that do not already exist in the cluster. Dangling indexes can be listed, deleted, or imported. -## Path and HTTP methods +## Endpoints List dangling indexes: -``` +```json GET /_dangling ``` Import a dangling index: -``` -POST /_dangling/ +```json +POST /_dangling/{index-uuid} ``` Delete a dangling index: -``` -DELETE /_dangling/ +```json +DELETE /_dangling/{index-uuid} ``` ## Path parameters @@ -37,7 +37,7 @@ Path parameters are required. Path parameter | Description :--- | :--- -index-uuid | UUID of index. +`index-uuid` | UUID of index. ## Query parameters @@ -45,44 +45,102 @@ Query parameters are optional. Query parameter | Data type | Description :--- | :--- | :--- -accept_data_loss | Boolean | Must be set to `true` for an `import` or `delete` because OpenSearch is unaware of where the dangling index data came from. -timeout | Time units | The amount of time to wait for a response. If no response is received in the defined time period, an error is returned. Default is `30` seconds. -cluster_manager_timeout | Time units | The amount of time to wait for a connection to the cluster manager. If no response is received in the defined time period, an error is returned. Default is `30` seconds. +`accept_data_loss` | Boolean | Must be set to `true` for an `import` or `delete` because OpenSearch is unaware of where the dangling index data came from. +`timeout` | Time units | The amount of time to wait for a response. If no response is received in the defined time period, an error is returned. Default is `30` seconds. +`cluster_manager_timeout` | Time units | The amount of time to wait for a connection to the cluster manager. If no response is received in the defined time period, an error is returned. Default is `30` seconds. -## Examples +## Example request: Listing dangling indexes -The following are example requests and a example response. - -#### Sample list - -````bash + +{% capture step1_rest %} GET /_dangling -```` -{% include copy-curl.html %} +{% endcapture %} -#### Sample import +{% capture step1_python %} -````bash +response = client.dangling_indices.list_dangling_indices() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Importing a dangling index + + +{% capture step1_rest %} POST /_dangling/msdjernajxAT23RT-BupMB?accept_data_loss=true -```` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.dangling_indices.import_dangling_index( + index_uuid = "msdjernajxAT23RT-BupMB", + params = { "accept_data_loss": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + -#### Sample delete +## Example request: Deleting a dangling index -````bash + +{% capture step1_rest %} DELETE /_dangling/msdjernajxAT23RT-BupMB?accept_data_loss=true -```` +{% endcapture %} -#### Example response body +{% capture step1_python %} -````json + +response = client.dangling_indices.delete_dangling_index( + index_uuid = "msdjernajxAT23RT-BupMB", + params = { "accept_data_loss": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +A request to list dangling indexes returns the following response: + +```json { - "_nodes": { - "total": 1, - "successful": 1, - "failed": 0 - }, - "cluster_name": "opensearch-cluster", - "dangling_indices": [msdjernajxAT23RT-BupMB] + "_nodes": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "cluster_name": "opensearch-cluster", + "dangling_indices": [ + { + "index_name": "my-index", + "index_uuid": "msdjernajxAT23RT-BupMB", + "creation_date_millis": 1729699200000, + "node_ids": [ + "pVUx3kTqRmOBuFtvDwQK1A" + ] + } + ] } -```` +``` diff --git a/_api-reference/index-apis/delete-index-template.md b/_api-reference/index-apis/delete-index-template.md new file mode 100644 index 00000000..5eafb580 --- /dev/null +++ b/_api-reference/index-apis/delete-index-template.md @@ -0,0 +1,38 @@ +--- +layout: default +title: Delete index template +parent: Index templates +grand_parent: Index APIs +nav_order: 20 +--- + +# Delete Index Template API +**Introduced 1.0** +{: .label .label-purple } + +The Delete Index Template API deletes one or more index templates. + +## Endpoints + +```json +DELETE /_index_template/{template-name} +``` + +## Path parameters + +Parameter | Type | Description +:--- | :--- | :--- +`template-name` | String | The name of the index template. You can delete multiple templates in one request by separating the template names with commas. When multiple template names are used in the request, wildcards are not supported. + +## Query parameters + +The following optional query parameters are supported. + +Parameter | Type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time that the operation will wait for a response. Default is `30s`. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/index_template/delete`. diff --git a/_api-reference/index-apis/delete-index.md b/_api-reference/index-apis/delete-index.md index 5973a8cf..2f9ff946 100644 --- a/_api-reference/index-apis/delete-index.md +++ b/_api-reference/index-apis/delete-index.md @@ -1,47 +1,179 @@ --- layout: default title: Delete index -parent: Index APIs -nav_order: 35 +parent: Core index APIs +grand_parent: Index APIs +nav_order: 20 redirect_from: - /opensearch/rest-api/index-apis/delete-index/ --- -# Delete index +# Delete Index API **Introduced 1.0** {: .label .label-purple } -If you no longer need an index, you can use the delete index API operation to delete it. +The delete index API operation deletes one or more indexes from your cluster. -## Example +**Warning**: Deleting an index is a permanent operation. All data in the index is lost and cannot be recovered. Always verify that you have backups or that the data is no longer needed before deleting an index. +{: .warning} + +## Endpoints ```json +DELETE /{index} +``` + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the index to delete. You can specify a single index name, a comma-separated list of index names, or a wildcard expression. Wildcard expressions (`*`) match only open, concrete indexes. You cannot delete an index using an alias. To delete all indexes, use `_all` or `*`. To prevent accidental deletion of all indexes using `_all` or wildcard expressions, set the `action.destructive_requires_name` cluster setting to `true`. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | Specifies whether to ignore wildcards that do not match any indexes. If `false`, the request returns an error when wildcards do not match any indexes. | `true` | +| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Match all indexes, including hidden indexes.
- `open`: Match open indexes.
- `closed`: Match closed indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions. | `open` | +| `ignore_unavailable` | Boolean | Specifies whether to ignore indexes that are unavailable (missing or closed). If `true`, missing or closed indexes are not included in the response. | `false` | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | +| `timeout` | String | The amount of time to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. | `30s` | + +## Example: Deleting a single index + +The following example request deletes a single index named `sample-index`: + + +{% capture step1_rest %} DELETE /sample-index -``` -{% include copy-curl.html %} +{% endcapture %} -## Path and HTTP methods - -``` -DELETE / -``` - -## URL parameters - -All parameters are optional. - -Parameter | Type | Description -:--- | :--- | :--- -allow_no_indices | Boolean | Whether to ignore wildcards that don't match any indexes. Default is true. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions), which must be used with open, closed, or both. Default is open. -ignore_unavailable | Boolean | If true, OpenSearch does not include missing or closed indexes in the response. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for the response to return. Default is `30s`. +{% capture step1_python %} -## Response +response = client.indices.delete( + index = "sample-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Deleting multiple indexes + +The following example request deletes multiple indexes by specifying them in a comma-separated list: + + +{% capture step1_rest %} +DELETE /logs-2024-01,logs-2024-02,logs-2024-03 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.delete( + index = "logs-2024-01,logs-2024-02,logs-2024-03" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Deleting indexes using wildcard patterns + +The following example request deletes all indexes that match the pattern `logs-2024-*`: + + +{% capture step1_rest %} +DELETE /logs-2024-* +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.delete( + index = "logs-2024-*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Deleting all indexes + +**Warning**: The following operation is extremely destructive and will delete all indexes in your cluster. Use with extreme caution and only in development or testing environments. +{: .warning} + +The following example request deletes all indexes in the cluster: + + +{% capture step1_rest %} +DELETE /* +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.delete( + index = "*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To prevent accidental deletion of all indexes, you can set the `action.destructive_requires_name` cluster setting to `true`. When this setting is enabled, you must specify explicit index names and cannot use `_all` or wildcard patterns to delete all indexes. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +## Example response + +OpenSearch returns the following response when the delete operation is successful: + ```json { "acknowledged": true } ``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`acknowledged` | Boolean | Indicates whether the delete request was received by the cluster. A value of `true` means the indexes were successfully deleted. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/delete`. diff --git a/_api-reference/index-apis/delete-template-legacy.md b/_api-reference/index-apis/delete-template-legacy.md new file mode 100644 index 00000000..07e86649 --- /dev/null +++ b/_api-reference/index-apis/delete-template-legacy.md @@ -0,0 +1,74 @@ +--- + +layout: default +title: Delete template (deprecated) +parent: Index templates +grand_parent: Index APIs +nav_order: 110 +--- + +# Delete template +**Introduced 1.0** +{: .label .label-purple } + +The Delete Template API has been deprecated. Use the new [Delete Index Template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-index-template/) API. +{: .warning} + +The delete template API operation deletes an index template created using the legacy `/_template` endpoint. + + +## Endpoints + +```json +DELETE /_template/{template-name} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Type | Description | +| :----------- | :----- | :---------------------------------------------------------- | +| `index-name` | String | The name of the index to delete. Supports wildcard expressions. | + +## Query parameters + +The following table lists the available query parameters. All parameters are optional. + +| Parameter | Type | Description | +| :-------------- | :--- | :------------------------------------------------------------------------------------------- | +| `cluster_manager_timeout` | Time | Specifies how long to wait for a connection to the cluster manager node. Default is `30s`. | +| `timeout` | Time | Specifies how long to wait for the operation to complete. Default is `30s`. | + +## Example request + + +{% capture step1_rest %} +DELETE /_template/logging_template +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.delete_template( + name = "logging_template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` + diff --git a/_api-reference/index-apis/exists.md b/_api-reference/index-apis/exists.md index 6d439a96..d50eac71 100644 --- a/_api-reference/index-apis/exists.md +++ b/_api-reference/index-apis/exists.md @@ -1,45 +1,71 @@ --- layout: default title: Index exists -parent: Index APIs -nav_order: 50 +parent: Core index APIs +grand_parent: Index APIs +nav_order: 40 redirect_from: - /opensearch/rest-api/index-apis/exists/ --- -# Index exists +# Index Exists API **Introduced 1.0** {: .label .label-purple } The index exists API operation returns whether or not an index already exists. -## Example +The API returns a `200` status code if all specified indexes exist and a `404` status code if any of them does not exist. It does not distinguish between index names and [aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/), so it also returns `200` if you specify the name of an existing alias. +{: .note} + + +## Endpoints ```json -HEAD /sample-index -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -HEAD / +HEAD /{index-name} ``` -## URL parameters +## Query parameters All parameters are optional. Parameter | Type | Description :--- | :--- | :--- -allow_no_indices | Boolean | Whether to ignore wildcards that don't match any indexes. Default is true. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions). Default is open. -flat_settings | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of "index": { "creation_date": "123456789" } is "index.creation_date": "123456789". -include_defaults | Boolean | Whether to include default settings as part of the response. This parameter is useful for identifying the names and current values of settings you want to update. -ignore_unavailable | Boolean | If true, OpenSearch does not search for missing or closed indexes. Default is false. -local | Boolean | Whether to return information from only the local node instead of from the cluster manager node. Default is false. +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. +`expand_wildcards` | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions). Default is `open`. +`flat_settings` | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of "index": { "creation_date": "123456789" } is "index.creation_date": "123456789". +`include_defaults` | Boolean | Whether to include default settings as part of the response. This parameter is useful for identifying the names and current values of settings you want to update. +`ignore_unavailable` | Boolean | If true, OpenSearch does not search for missing or closed indexes. Default is `false`. +`local` | Boolean | Whether to return information from only the local node instead of from the cluster manager node. Default is `false`. -## Response +## Example request + + +{% capture step1_rest %} +HEAD /sample-index +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.exists( + index = "sample-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The index exists API operation returns only one of two possible response codes: `200` -- the index exists, and `404` -- the index does not exist. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/exists`. diff --git a/_api-reference/index-apis/flush.md b/_api-reference/index-apis/flush.md new file mode 100644 index 00000000..354dd865 --- /dev/null +++ b/_api-reference/index-apis/flush.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Flush +parent: Index operations +grand_parent: Index APIs +nav_order: 30 +--- + +# Flush API + +**Introduced 1.0** +{: .label .label-purple } + +The Flush API stores all in-memory operations to segments on disk. Operations flushed to an index segment are no longer needed in transaction logs during a cluster restart because these operations are now stored in the Lucene index. + +OpenSearch automatically performs flushes in the background based on conditions like transaction log size, which is controlled by the `index.translog.flush_threshold_size` setting. Use the Flush API sparingly, for example, for manual restarts or to free up memory. + +For more information about how flush relates to the transaction log, refresh, and merge operations, see [Flush]({{site.url}}{{site.baseurl}}/getting-started/concepts/#flush) in OpenSearch concepts. + +## Endpoints + +The Flush API supports the following paths: + +```json +GET /_flush +POST /_flush +GET /{index}/_flush +POST /{index}/_flush +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `` | String | A comma-separated list of indexes, data streams, or index aliases to which the operation is applied. Supports wildcard expressions (`*`). Use `_all` or `*` to specify all indexes and data streams in a cluster. | + +## Query parameters + +All parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `allow_no_indices` | Boolean | When `false`, the request returns an error if any wildcard expression or index alias targets any closed or missing indexes. Default is `true`. | +| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Expand to all open and closed indexes, including hidden indexes.
- `open`: Expand to open indexes.
- `closed`: Expand to closed indexes.
- `hidden`: Include hidden indexes when expanding. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions.
Default is `open`.
The Flush API cannot flush closed indexes. If a wildcard expression expands to a closed index, the request fails unless `ignore_unavailable` is `true`, in which case closed indexes are skipped. | +| `force` | Boolean | When `true`, forces a flush to occur even when no changes to the index exist in-memory. If `true`, `wait_if_ongoing` must also be `true`; otherwise, the request is rejected. Default is `false`. | +| `ignore_unavailable` | Boolean | When `true`, OpenSearch ignores missing or closed indexes. If `false`, OpenSearch returns an error if the flush operation encounters missing or closed indexes. Default is `false`. | +| `wait_if_ongoing` | Boolean | When `true`, if another flush is in progress, OpenSearch waits for it to finish and then performs the flush. When `false`, if another flush is already running on a shard, that shard skips the flush without returning an error. Default is `true`. | + +## Example request: Flushing a specific index + +The following example flushes an index named `shakespeare`: + + +{% capture step1_rest %} +POST /shakespeare/_flush + +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.flush( + index = "shakespeare" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example request: Flushing all indexes + +The following example flushes all indexes in a cluster: + + +{% capture step1_rest %} +POST /_flush + +{% endcapture %} + +{% capture step1_python %} + +response = client.indices.flush() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +OpenSearch responds with the number of shard copies targeted by the flush request (including unassigned replicas), the number of shard copies that completed the request, and the number of shard copies that failed: + +```json +{ + "_shards": { + "total": 10, + "successful": 10, + "failed": 0 + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/flush` and `indices:admin/flush*`. diff --git a/_api-reference/index-apis/force-merge.md b/_api-reference/index-apis/force-merge.md index 6ad2e7f2..115fbcf0 100644 --- a/_api-reference/index-apis/force-merge.md +++ b/_api-reference/index-apis/force-merge.md @@ -1,19 +1,27 @@ --- layout: default title: Force merge -parent: Index APIs -nav_order: 37 +parent: Index operations +grand_parent: Index APIs +nav_order: 40 --- -# Force merge +# Force Merge API **Introduced 1.0** {: .label .label-purple } -The force merge API operation forces a merge on the shards of one or more indexes. For a data stream, the API forces a merge on the shards of the stream's backing index. +The force merge API operation forces a merge on the shards of one or more indexes. For a data stream, the API forces a merge on the shards of the stream's backing indexes. + +## Endpoints + +```json +POST /_forcemerge +POST /{index}/_forcemerge +``` ## The merge operation -In OpenSearch, a shard is a Lucene index, which consists of _segments_ (or segment files). Segments store the indexed data. Periodically, smaller segments are merged into larger ones and the larger segments become immutable. Merging reduces the overall number of segments on each shard and frees up disk space. +In OpenSearch, a shard is a Lucene index, which consists of _segments_ (or segment files). Segments store the indexed data and are immutable. Periodically, OpenSearch merges smaller segments into a new, larger segment and then deletes the original segments. Merging reduces the overall number of segments on each shard and frees up disk space. OpenSearch performs background segment merges that produce segments no larger than `index.merge.policy.max_merged_segment` (the default is 5 GB). @@ -21,14 +29,18 @@ OpenSearch performs background segment merges that produce segments no larger th When a document is deleted from an OpenSearch index, it is not deleted from the Lucene segment but is rather only marked to be deleted. When the segment files are merged, deleted documents are removed (or _expunged_). Thus, merging also frees up space occupied by documents marked as deleted. +OpenSearch retains a shard's history of operations, including deleted documents, for the period specified in the `index.soft_deletes.retention_lease.period` setting (default `12h`). A force merge does not expunge deleted documents that are still retained, so the number of deleted documents might not decrease immediately after a force merge. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + ## Force Merge API -In addition to periodic merging, you can force a segment merge using the Force Merge API. +In addition to periodic merging, you can force a segment merge using the Force Merge API. By default, the merge policy determines which segments to merge, so a force merge request might not change the number of segments. To merge all segments of each shard into one segment, set `max_num_segments` to `1`. -Use the Force Merge API on an index only after all write requests sent to the index are completed. The force merge operation can produce very large segments. If write requests are still sent to the index, then the merge policy does not merge these segments until they primarily consist of deleted documents. This can increase disk space usage and lead to performance degradation. +Use the Force Merge API on an index only after all write requests sent to the index are completed. The force merge operation can produce very large segments. If write requests are still sent to the index, then the merge policy does not merge these segments until they primarily consist of deleted documents. This can increase disk space usage and lead to performance degradation. During a force merge, the shard temporarily requires additional storage to rewrite segment files. {: .warning} -When you call the Force Merge API, the call is blocked until merge completion. If during this time the connection is lost, the force merge operation continues in the background. New force merge requests sent to the same index will be blocked until the currently running merge operation is complete. +By default, the Force Merge API call does not return until the merge completes. If the connection is lost during this time, the force merge operation continues in the background. To run the operation asynchronously, set `wait_for_completion` to `false`. + +Each node runs force merge operations in its `force_merge` thread pool. Force merge requests that arrive while all threads in the pool are busy are queued until a thread becomes available. ## Force merging multiple indexes @@ -36,21 +48,25 @@ To force merge multiple indexes, you can call the Force Merge API on the followi - Multiple indexes - One or more data streams containing multiple backing indexes -- One or more index aliases pointing to multiple indexes +- One or more index aliases referencing multiple indexes - All data streams and indexes in a cluster -When you force merge multiple indexes, the merge operation is executed on each shard of a node sequentially. When the force merge operation is in progress, the storage for the shard temporarily increases so that all segments can be rewritten into a new segment. When `max_num_segments` is set to `1`, the storage for the shard temporarily doubles. +When you force merge multiple indexes, each node merges its shards using the `force_merge` thread pool. The pool size is one-eighth of the node's allocated processors, with a minimum of 1, so on most nodes shards are merged one at a time. While the force merge operation is in progress, the storage for the shard temporarily increases so that all segments can be rewritten into a new segment. When `max_num_segments` is set to `1`, the storage for the shard can temporarily double. ## Force merging data streams It can be useful to force merge data streams in order to manage a data stream's backing indexes, especially after a rollover operation. Time-based indexes receive indexing requests only during a specified time period. Once that time period has elapsed and the index receives no more write requests, you can force merge segments of all index shards into one segment. Searches on single-segment shards are more efficient because they use simpler data structures. -## Path and HTTP methods -```json -POST /_forcemerge -POST //_forcemerge/ -``` +## Upgrading segments +**Introduced 3.11** +{: .label .label-purple } + +After you upgrade OpenSearch, segments written by an older Lucene version remain in that format until they are merged. Background merge operations never select segments that have reached `index.merge.policy.max_merged_segment`, so large segments can stay in the older format indefinitely. + +To rewrite these segments using the current Lucene version, set `upgrade` to `true`. If you don't specify `max_num_segments`, each segment in an older format is rewritten as a single new segment, so the number and size of segments on each shard stay the same. If you specify `max_num_segments`, the segments in an older format are upgraded and then merged into at most `max_num_segments` segments. Segments that are already in the current format are not rewritten unless they are selected for merging. + +You cannot set `upgrade` and `only_expunge_deletes` in the same request. The `only_expunge_deletes` parameter limits merging to segments that contain more than a specified percentage of deleted documents, which conflicts with rewriting all segments in an older format. ## Path parameters @@ -58,7 +74,7 @@ The following table lists the available path parameters. All path parameters are | Parameter | Data type | Description | | :--- | :--- | :--- | -| `` | String | A comma-separated list of indexes, data streams, or index aliases to which the operation is applied. Supports wildcard expressions (`*`). Use `_all` or `*` to specify all indexes and data streams in a cluster. | +| `index` | String | A comma-separated list of indexes, data streams, or index aliases to which the operation is applied. Supports wildcard expressions (`*`). Use `_all` or `*` to specify all indexes and data streams in a cluster. | ## Query parameters @@ -66,42 +82,101 @@ The following table lists the available query parameters. All query parameters a | Parameter | Data type | Description | | :--- | :--- | :--- | -| `allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression or index alias targets any closed or missing indexes. Default is `true`. | -| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Expand to all open and closed indexes, including hidden indexes.
- `open`: Expand to open indexes.
- `closed`: Expand to closed indexes.
- `hidden`: Include hidden indexes when expanding. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions.
Default is `open`. | +| `allow_no_indices` | Boolean | If `false`, the request returns an error if a wildcard expression or index alias matches no open indexes. Default is `true`. | +| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Expand to all open and closed indexes, including hidden indexes.
- `open`: Expand to open indexes.
- `closed`: Expand to closed indexes.
- `hidden`: Include hidden indexes when expanding. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions.
Default is `open`.
Force merge cannot run on closed indexes, so requests that expand wildcards to closed indexes (`closed` or `all`) return an error unless `ignore_unavailable` is `true`. | | `flush` | Boolean | Performs a flush on the indexes after the force merge. A flush ensures that the files are persisted to disk. Default is `true`. | | `ignore_unavailable` | Boolean | If `true`, OpenSearch ignores missing or closed indexes. If `false`, OpenSearch returns an error if the force merge operation encounters missing or closed indexes. Default is `false`. | -| `max_num_segments` | Integer | The number of larger segments into which smaller segments are merged. Set this parameter to `1` to merge all segments into one segment. The default behavior is to perform the merge as necessary. | -| `only_expunge_deletes` | Boolean | If `true`, the merge operation only expunges segments containing a certain percentage of deleted documents. The percentage is 10% by default and is configurable in the `index.merge.policy.expunge_deletes_allowed` setting. Prior to OpenSearch 2.12, `only_expunge_deletes` ignored the `index.merge.policy.max_merged_segment` setting. Starting with OpenSearch 2.12, using `only_expunge_deletes` does not produce segments larger than `index.merge.policy.max_merged_segment` (by default, 5 GB). For more information, see [Deleted documents](#deleted-documents). Default is `false`. | +| `max_num_segments` | Integer | The maximum number of segments per shard after the merge. Set this parameter to `1` to merge all segments of each shard into one segment. By default, segments are merged as determined by the merge policy. | +| `only_expunge_deletes` | Boolean | If `true`, the merge operation only expunges segments containing a certain percentage of deleted documents. The percentage is 10% by default and is configurable in the `index.merge.policy.expunge_deletes_allowed` setting. Using `only_expunge_deletes` does not produce segments larger than `index.merge.policy.max_merged_segment` (by default, 5 GB). Combining `only_expunge_deletes` with `max_num_segments` is deprecated. Cannot be combined with `upgrade`. For more information, see [Deleted documents](#deleted-documents). Default is `false`. | +| `primary_only` | Boolean | If set to `true`, then the merge operation is performed only on the primary shards of an index. This can be useful when you want to take a snapshot of the index after the merge is complete. Snapshots only copy segments from the primary shards. Merging the primary shards can reduce resource consumption. Default is `false`. | +| `upgrade` | Boolean | If `true`, segments written by an older Lucene version are rewritten using the current Lucene version. When `max_num_segments` is not set, each segment in an older format is rewritten individually and no segments are merged together. When `max_num_segments` is set, segments are upgraded and then merged into at most `max_num_segments` segments. Cannot be combined with `only_expunge_deletes`. For more information, see [Upgrading segments](#upgrading-segments). Default is `false`. | +| `wait_for_completion` | Boolean | If `false`, OpenSearch runs the force merge operation asynchronously without waiting for it to complete. The request returns immediately, and the task continues in the background. You can monitor its progress using the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/). Default is `true`, which indicates that the operation runs synchronously. | -#### Example request: Force merge a specific index +## Example requests -```json +The following examples show how to use the Force Merge API. + +### Force merge a specific index + +The following example force merges a specific index: + + +{% capture step1_rest %} POST /testindex1/_forcemerge -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example request: Force merge multiple indexes +{% capture step1_python %} -```json + +response = client.indices.forcemerge( + index = "testindex1" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Force merge multiple indexes + +The following example force merges multiple indexes: + + +{% capture step1_rest %} POST /testindex1,testindex2/_forcemerge -``` -{% include copy-curl.html %} -#### Example request: Force merge all indexes +{% endcapture %} -```json +{% capture step1_python %} + + +response = client.indices.forcemerge( + index = "testindex1,testindex2" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Force merge all indexes + +The following example force merges all indexes: + + +{% capture step1_rest %} POST /_forcemerge -``` -{% include copy-curl.html %} -#### Example request: Force merge a data stream's backing indexes into one segment +{% endcapture %} -```json -POST /.testindex-logs/_forcemerge?max_num_segments=1 -``` -{% include copy-curl.html %} +{% capture step1_python %} -#### Example response +response = client.indices.forcemerge() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The `total` count includes both primary and replica shards. In the following example response, the index has one primary shard and one replica shard. The replica shard is unassigned, so the operation succeeded only on the primary shard: ```json { @@ -113,13 +188,31 @@ POST /.testindex-logs/_forcemerge?max_num_segments=1 } ``` -## Response fields +If `wait_for_completion` is `false`, the response contains the task ID, which you can use to monitor the task using the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/): + +```json +{ + "task": ":" +} +``` + +## Response body fields The following table lists all response fields. | Field | Data type | Description | | :--- | :--- | :--- | -| `shards` | Object | Contains information about the shards on which the request was executed. | -| `shards.total` | Integer | The number of shards on which the operation was executed. | -| `shards.successful` | Integer | The number of shards on which the operation was successful. | -| `shards.failed` | Integer | The number of shards on which the operation failed. | +| `_shards` | Object | Contains information about the shards on which the request was executed. Returned when `wait_for_completion` is `true`. | +| `task` | String | The ID of the force merge task. Returned when `wait_for_completion` is `false`. | + +The `_shards` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `total` | Integer | The number of shards on which the operation was executed. | +| `successful` | Integer | The number of shards on which the operation was successful. | +| `failed` | Integer | The number of shards on which the operation failed. | + +## Required permissions + +If you use the Security plugin, ensure that you have the appropriate permissions: `indices:admin/forcemerge`. diff --git a/_api-reference/index-apis/get-field-mapping.md b/_api-reference/index-apis/get-field-mapping.md new file mode 100644 index 00000000..2ee3e507 --- /dev/null +++ b/_api-reference/index-apis/get-field-mapping.md @@ -0,0 +1,80 @@ +--- +layout: default +title: Get field mapping +parent: Index settings and mappings +grand_parent: Index APIs +nav_order: 25 +--- + +# Get Field Mapping API +**Introduced 1.0** +{: .label .label-purple } + +The Get Field Mapping API retrieves mapping definitions for one or more specific fields. This is useful when you need to inspect how particular fields are configured without retrieving the full index mapping, especially for indexes with many fields. + +## Endpoints + +```json +GET /_mapping/field/{field} +GET /{index}/_mapping/field/{field} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | Optional | String | A comma-separated list of index names or wildcard expressions. Use `_all` or omit to target all indexes. | +| `field` | Required | String | A comma-separated list of field names or wildcard expressions. Use dot notation for nested fields (for example, `author.name`). | + +## Query parameters + +The following table lists the available query parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `include_defaults` | Optional | Boolean | When `true`, the response includes default mapping parameter values that are normally omitted. Default is `false`. | +| `allow_no_indices` | Optional | Boolean | When `true`, the request does not return an error if a wildcard expression or `_all` resolves to no indexes. Default is `true`. | +| `expand_wildcards` | Optional | String | Controls which index types wildcard expressions expand to. Valid values are `open`, `closed`, `hidden`, `none`, `all`. Default is `open`. | +| `ignore_unavailable` | Optional | Boolean | When `true`, missing or closed indexes are ignored rather than returning an error. Default is `false`. | + +## Example request + +The following request retrieves the mapping for the `customer_gender` field: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_mapping/field/customer_gender +``` +{% include copy-curl.html %} + +## Example response + +The response contains the field's full name and its mapping configuration: + +```json +{ + "opensearch_dashboards_sample_data_ecommerce" : { + "mappings" : { + "customer_gender" : { + "full_name" : "customer_gender", + "mapping" : { + "customer_gender" : { + "type" : "keyword" + } + } + } + } + } +} +``` + +## Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `{index}.mappings` | Object | A map of field names to their mapping details for the specified index. | +| `{field}.full_name` | String | The fully qualified field name, including any parent object path. | +| `{field}.mapping` | Object | The mapping configuration for the field, including its type and any parameters. | diff --git a/_api-reference/index-apis/get-index-template.md b/_api-reference/index-apis/get-index-template.md new file mode 100644 index 00000000..b85f1bef --- /dev/null +++ b/_api-reference/index-apis/get-index-template.md @@ -0,0 +1,196 @@ +--- +layout: default +title: Get index template +parent: Index templates +grand_parent: Index APIs +nav_order: 30 +--- + +# Get Index Template API +**Introduced 1.0** +{: .label .label-purple } + +The Get Index Template API returns information about one or more index templates. + +## Endpoints + +```json +GET /_index_template +GET /_index_template/{template-name} +HEAD /_index_template/{template-name} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`template-name` | String | The name of the index template to return. Supports wildcard expressions (`*`). Comma-separated lists of names are not supported. If omitted, all index templates are returned. + +## Query parameters + +The following optional query parameters are supported. + +Parameter | Type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`local` | Boolean | Whether to return information from the local node only instead of from the cluster manager node. Default is `false`. + +## Example requests + +The following request creates an index template named `hotels-template` for indexes whose names start with `hotels-`: + +```json +PUT /_index_template/hotels-template +{ + "index_patterns": ["hotels-*"], + "priority": 50, + "version": 1, + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "name": { "type": "text" }, + "city": { "type": "keyword" }, + "rating": { "type": "float" } + } + }, + "aliases": { + "hotels": {} + } + }, + "_meta": { + "description": "Template for hotel listing indexes" + } +} +``` +{% include copy-curl.html %} + +The following example request gets information about an index template by using a wildcard expression. If no index template matches the specified name, the API returns a `404` status code: + + +{% capture step1_rest %} +GET /_index_template/h* +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_index_template( + name = "h*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The following example request gets information about all index templates: + + +{% capture step1_rest %} +GET /_index_template +{% endcapture %} + +{% capture step1_python %} + +response = client.indices.get_index_template() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following response is returned for the `GET /_index_template/h*` request: + +```json +{ + "index_templates": [ + { + "name": "hotels-template", + "index_template": { + "index_patterns": [ + "hotels-*" + ], + "template": { + "settings": { + "index": { + "number_of_shards": "1", + "number_of_replicas": "1" + } + }, + "mappings": { + "properties": { + "city": { + "type": "keyword" + }, + "name": { + "type": "text" + }, + "rating": { + "type": "float" + } + } + }, + "aliases": { + "hotels": {} + } + }, + "composed_of": [], + "priority": 50, + "version": 1, + "_meta": { + "description": "Template for hotel listing indexes" + } + } + } + ] +} +``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`index_templates` | Array of objects | The index templates that match the request. Each object in the array contains the `name` and `index_template` fields. + +Each object in the `index_templates` array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`name` | String | The name of the index template. +`index_template` | Object | The index template definition. + +The `index_template` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`index_patterns` | Array of strings | The index name patterns to which the template applies. +`template` | Object | The settings, mappings, and aliases applied to matching indexes. Contains the `settings`, `mappings`, and `aliases` objects. Only the objects defined in the template are returned. Returned only if set. +`composed_of` | Array of strings | The names of the component templates used to compose this index template. Returned if set or if the index template contains a `template` object. In the latter case, it can be an empty array. +`priority` | Long | The priority of the template. When multiple templates match an index, the template with the highest priority is applied. Returned only if set. +`version` | Long | The version number of the template. Returned only if set. +`_meta` | Object | Custom metadata stored with the template. Returned only if set. +`data_stream` | Object | The data stream configuration, such as the `timestamp_field`. Returned only if the template creates data streams. +`context` | Object | The context used to apply additional settings to matching indexes. Returned only if set. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/index_template/get`. diff --git a/_api-reference/index-apis/get-index.md b/_api-reference/index-apis/get-index.md index 899e82e9..f3300300 100644 --- a/_api-reference/index-apis/get-index.md +++ b/_api-reference/index-apis/get-index.md @@ -1,78 +1,135 @@ --- layout: default title: Get index -parent: Index APIs -nav_order: 40 +parent: Core index APIs +grand_parent: Index APIs +nav_order: 30 redirect_from: - /opensearch/rest-api/index-apis/get-index/ --- -# Get index +# Get Index API **Introduced 1.0** {: .label .label-purple } -You can use the get index API operation to return information about an index. - -## Example +The get index API operation returns information about one or more indexes, including their settings, mappings, and aliases. + +## Endpoints ```json -GET /sample-index +GET /{index} ``` -{% include copy-curl.html %} + -## Path and HTTP methods +## Path parameters -``` -GET / -``` +The following table lists the available path parameters. -## URL parameters +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the index to retrieve. You can specify a single index, a comma-separated list of indexes, or a wildcard expression. Use `_all` or `*` to retrieve information for all indexes in the cluster. | -All parameters are optional. +## Query parameters -Parameter | Type | Description -:--- | :--- | :--- -allow_no_indices | Boolean | Whether to ignore wildcards that don't match any indexes. Default is true. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions), which must be used with open, closed, or both. Default is open. -flat_settings | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of "index": { "creation_date": "123456789" } is "index.creation_date": "123456789". -include_defaults | Boolean | Whether to include default settings as part of the response. This parameter is useful for identifying the names and current values of settings you want to update. -ignore_unavailable | Boolean | If true, OpenSearch does not include missing or closed indexes in the response. -local | Boolean | Whether to return information from only the local node instead of from the cluster manager node. Default is false. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | Specifies whether to ignore wildcards that do not match any indexes. If `false`, the request returns an error when wildcards do not match any indexes. | `true` | +| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Match all indexes, including hidden indexes.
- `open`: Match open indexes.
- `closed`: Match closed indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions. | `open` | +| `flat_settings` | Boolean | Specifies whether to return settings in flat format. When `true`, settings are returned in a flattened format (for example, `"index.creation_date": "123456789"`). When `false`, settings are returned in nested format (for example, `"index": {"creation_date": "123456789"}`). | `false` | +| `include_defaults` | Boolean | Specifies whether to include default settings in the response. When `true`, the response includes default values for all settings, which can help you identify setting names and values to update. | `false` | +| `ignore_unavailable` | Boolean | Specifies whether to ignore indexes that are unavailable (missing or closed). If `true`, missing or closed indexes are not included in the response. | `false` | +| `local` | Boolean | Specifies whether to retrieve information from the local node only instead of from the cluster manager node. | `false` | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | + +## Example request + +The following example request retrieves information for the `books` index: + + +{% capture step1_rest %} +GET /books +{% endcapture %} + +{% capture step1_python %} -## Response +response = client.indices.get( + index = "books" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +OpenSearch returns information for the requested index or indexes: + ```json { - "sample-index1": { + "books": { "aliases": {}, "mappings": {}, "settings": { "index": { - "creation_date": "1633044652108", - "number_of_shards": "2", - "number_of_replicas": "1", - "uuid": "XcXA0aZ5S0aiqx3i1Ce95w", - "version": { - "created": "135217827" + "replication": { + "type": "DOCUMENT" }, - "provided_name": "sample-index1" + "number_of_shards": "2", + "provided_name": "books", + "creation_date": "1778255937147", + "number_of_replicas": "1", + "uuid": "Onnd4TKBQMODrfvAvNXjAg", + "version": { + "created": "137277827" + } } } } } ``` +When you use the `flat_settings=true` query parameter, settings are returned in a flattened format: + +```json +{ + "books": { + "aliases": {}, + "mappings": {}, + "settings": { + "index.creation_date": "1778255937147", + "index.number_of_replicas": "1", + "index.number_of_shards": "2", + "index.provided_name": "books", + "index.replication.type": "DOCUMENT", + "index.uuid": "Onnd4TKBQMODrfvAvNXjAg", + "index.version.created": "137277827" + } + } +} +``` + ## Response body fields -Field | Description -:--- | :--- -aliases | Any aliases associated with the index. -mappings | Any mappings in the index. -settings | The index's settings -creation_date | The Unix epoch time of when the index was created. -number_of_shards | How many shards the index has. -number_of_replicas | How many replicas the index has. -uuid | The index's uuid. -created | The version of OpenSearch when the index was created. -provided_name | Name of the index. +The response contains a separate object for each index, for which the key is the index name. Each index object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`aliases` | Object | Index aliases associated with the index. Each key is an alias name, and each value is an alias configuration object. For more information, see [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/). +`mappings` | Object | Field mappings for documents in the index. Defines the data type and properties for each field. For more information, see [Mappings]({{site.url}}{{site.baseurl}}/field-types/). +`settings` | Object | Index settings that control index behavior, such as the number of shards and replicas. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/get`. diff --git a/_api-reference/index-apis/get-ingestion-state.md b/_api-reference/index-apis/get-ingestion-state.md new file mode 100644 index 00000000..a925c809 --- /dev/null +++ b/_api-reference/index-apis/get-ingestion-state.md @@ -0,0 +1,190 @@ +--- +layout: default +title: Get ingestion state +parent: Pull-based ingestion management +grand_parent: Index APIs +nav_order: 30 +--- + +# Get Ingestion State API +**Introduced 3.0** +{: .label .label-purple } + +Returns the current ingestion state for each shard in one or more indexes that use [pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/). This API supports pagination. + +## Endpoints + +```json +GET /{index}/ingestion/_state +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `index` | String | Required | The index for which to return the ingestion state. Can be a comma-separated list of multiple index names. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `size` | Integer | The number of results to return per page. | +| `next_token` | String | The token for retrieving the next page of results. Use the `next_page_token` value from the previous response. | +| `timeout` | Time units | The amount of time to wait for a response from the cluster. Default is `30s`. | + +## Example request: Retrieving the ingestion state + +To get the ingestion state of `my-index`, send the following request: + + +{% capture step1_rest %} +GET /my-index/ingestion/_state +{% endcapture %} + +{% capture step1_python %} + + +response = client.ingestion.get_state( + index = "my-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The response contains the ingestion state of each shard in `my-index`. If a shard fails to return its state, the failure is listed in `_shards.failures`: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "ingestion_state": { + "my-index": [ + { + "shard": 0, + "poller_state": "POLLING", + "error_policy": "DROP", + "poller_paused": false, + "write_block_enabled": false, + "batch_start_pointer": "KafkaOffset{offset=17735361}", + "is_primary": true, + "node": "node-a" + } + ] + } +} +``` + +## Example request: Paginating results + +To return 20 results per page, send the following request: + + +{% capture step1_rest %} +GET /my-index/ingestion/_state?size=20 +{% endcapture %} + +{% capture step1_python %} + + +response = client.ingestion.get_state( + index = "my-index", + params = { "size": "20" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If more results are available, the response contains a `next_page_token` field. To retrieve the next page, provide its value in the `next_token` query parameter: + + +{% capture step1_rest %} +GET /my-index/ingestion/_state?size=20&next_token= +{% endcapture %} + +{% capture step1_python %} + + +response = client.ingestion.get_state( + index = "my-index", + params = { "size": "20", "next_token": "" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_shards` | Object | The number of shards that returned or failed to return their ingestion state. See [Shards](#shards). | +| `ingestion_state` | Object | The ingestion state of each requested index. Each key is an index name, and its value is an array containing the state of each shard in that index. See [Shard ingestion state](#shard-ingestion-state). | +| `next_page_token` | String | The token for retrieving the next page of results. Pass this value in the `next_token` query parameter. Returned only when more results are available. | + +### Shards + +The `_shards` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `total` | Integer | The total number of shards from which the ingestion state was requested. | +| `successful` | Integer | The number of shards that returned their ingestion state. | +| `failed` | Integer | The number of shards that failed to return their ingestion state. | +| `failures` | Array of objects | A list of shard failures. Returned only when at least one shard fails. See [Shard failures](#shard-failures). | + +### Shard failures + +Each object in the `_shards.failures` array contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `shard` | Integer | The shard number. | +| `index` | String | The name of the index containing the shard. | +| `status` | String | The HTTP status of the failure, such as `INTERNAL_SERVER_ERROR`. | +| `reason` | Object | The cause of the failure, containing the error `type` (for example, `timeout_exception`) and the error message in `reason`. | + +### Shard ingestion state + +Each object in an `ingestion_state` array contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `shard` | Integer | The shard number. | +| `poller_state` | String | The current state of the shard's poller. Valid values are `NONE`, `POLLING`, `PROCESSING`, `PAUSED`, and `CLOSED`. | +| `error_policy` | String | The policy for handling failed messages: `DROP` or `BLOCK`. See [Updating the error policy]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#updating-the-error-policy). | +| `poller_paused` | Boolean | Whether ingestion for the shard is paused. | +| `write_block_enabled` | Boolean | Whether a write block is enabled for the shard. | +| `batch_start_pointer` | String | The position in the source from which the poller resumes during shard recovery, such as a Kafka offset or a Kinesis sequence number. | +| `is_primary` | Boolean | Whether the shard copy is a primary shard. | +| `node` | String | The name of the node that hosts the shard copy. | diff --git a/_api-reference/index-apis/get-mapping.md b/_api-reference/index-apis/get-mapping.md new file mode 100644 index 00000000..2f40ac63 --- /dev/null +++ b/_api-reference/index-apis/get-mapping.md @@ -0,0 +1,190 @@ +--- +layout: default +title: Get index mappings +parent: Index settings and mappings +grand_parent: Index APIs +nav_order: 20 +--- + +# Get Index Mappings API +**Introduced 1.0** +{: .label .label-purple } + +The Get Mappings API returns the mapping definitions for one or more indexes. Use this API to inspect how fields are configured in an index, verify that mapping updates were applied, or review the full schema before reindexing. + + +## Endpoints +```json +GET /_mapping +GET /{index}/_mapping +``` + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | A comma-separated list of index names to retrieve mappings for. Supports wildcard expressions. To retrieve mappings for all indexes, omit this parameter or use `_all` or `*`. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | Specifies whether to ignore wildcards that do not match any indexes. If `false`, the request returns an error when wildcards do not match any indexes. | `true` | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | +| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Match all indexes, including hidden indexes.
- `open`: Match open indexes.
- `closed`: Match closed indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions. | `open` | +| `ignore_unavailable` | Boolean | Specifies whether to ignore indexes that are missing or closed. If `true`, missing or closed indexes are not included in the response. | `false` | +| `local` | Boolean | Specifies whether to retrieve information from the local node only instead of from the cluster manager node. | `false` | + +## Example: Retrieving mappings for a single index + +The following example retrieves the mapping for the `products` index: + + +{% capture step1_rest %} +GET /products/_mapping +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_mapping( + index = "products" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Retrieving mappings for multiple indexes + +You can retrieve mappings for multiple indexes in a single request by specifying a comma-separated list: + + +{% capture step1_rest %} +GET /products,products-us/_mapping +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_mapping( + index = "products,products-us" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Retrieving all mappings + +To retrieve mappings for all indexes in the cluster, omit the index name: + + +{% capture step1_rest %} +GET /_mapping +{% endcapture %} + +{% capture step1_python %} + +response = client.indices.get_mapping() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +
+ + Response + + {: .text-delta} + +```json +{ + "products" : { + "mappings" : { + "properties" : { + "description" : { + "type" : "text" + }, + "item_id" : { + "type" : "alias", + "path" : "product_id" + }, + "manufacturer" : { + "properties" : { + "country" : { + "type" : "keyword" + }, + "name" : { + "type" : "text" + } + } + }, + "price" : { + "type" : "float" + }, + "product_id" : { + "type" : "keyword" + }, + "product_name" : { + "type" : "text", + "fields" : { + "keyword" : { + "type" : "keyword", + "ignore_above" : 256 + } + } + }, + "sku" : { + "type" : "keyword", + "ignore_above" : 50 + }, + "weight" : { + "type" : "integer" + } + } + } + } +} +``` +
+ +## Response body fields + +The response contains a JSON object where each key is an index name. The following table describes the fields within each index entry. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `mappings` | Object | The mapping definition for the index. | +| `mappings.properties` | Object | A map of field names to their mapping configurations, including type, parameters, and nested subfields. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/mappings/get`. diff --git a/_api-reference/index-apis/get-settings.md b/_api-reference/index-apis/get-settings.md index 37ac291a..4606d70d 100644 --- a/_api-reference/index-apis/get-settings.md +++ b/_api-reference/index-apis/get-settings.md @@ -1,67 +1,181 @@ --- layout: default -title: Get settings -parent: Index APIs -nav_order: 45 +title: Get index settings +parent: Index settings and mappings +grand_parent: Index APIs +nav_order: 10 redirect_from: - - /opensearch/rest-api/index-apis/get-index/ + - /opensearch/rest-api/index-apis/get-settings/ --- -# Get settings +# Get Index Settings API **Introduced 1.0** {: .label .label-purple } -The get settings API operation returns all the settings in your index. +The Get Index Settings API returns the configuration settings for one or more indexes. Use this API to retrieve index-level settings such as the number of shards and replicas, refresh intervals, analysis configurations, and other index parameters. -## Example +## Endpoints + + ```json -GET /sample-index1/_settings -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` GET /_settings -GET //_settings -GET //_settings/ +GET /{target-index}/_settings +GET /{target-index}/_settings/{setting} ``` + -## URL parameters +## Path parameters -All get settings parameters are optional. +The following table lists the available path parameters. All path parameters are optional. Parameter | Data type | Description :--- | :--- | :--- -<target-index> | String | The index to get settings from. Can be a comma-separated list to get settings from multiple indexes, or use `_all` to return settings from all indexes within the cluster. -<setting> | String | Filter to return specific settings. -allow_no_indices | Boolean | Whether to ignore wildcards that don’t match any indexes. Default is `true`. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are `all` (match all indexes), `open` (match open indexes), `closed` (match closed indexes), `hidden` (match hidden indexes), and `none` (do not accept wildcard expressions), which must be used with `open`, `closed`, or both. Default is `open`. -flat_settings | Boolean | Whether to return settings in the flat form, which can improve readability, especially for heavily nested settings. For example, the flat form of “index”: { “creation_date”: “123456789” } is “index.creation_date”: “123456789”. -include_defaults | String | Whether to include default settings, including settings used within OpenSearch plugins, in the response. Default is false. -ignore_unavailable | Boolean | If true, OpenSearch does not include missing or closed indexes in the response. -local | Boolean | Whether to return information from the local node only instead of the cluster manager node. Default is false. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. +`target-index` | String | The name of the index to retrieve settings from. You can specify a single index name, a comma-separated list of index names, or a wildcard expression. Use `_all` or `*` to retrieve settings from all indexes in the cluster. +`setting` | String | The name of a specific setting to retrieve. When specified, the response includes only the requested setting instead of all settings. -## Response +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`allow_no_indices` | Boolean | Specifies whether to ignore wildcard expressions or index patterns that don’t match any indexes. When `false`, the request returns an error if a wildcard expression doesn’t match any indexes. When `true`, the request ignores missing indexes and returns only the settings for indexes that exist. Default is `true`. +`expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are `all` (all indexes), `open` (open indexes), `closed` (closed indexes), `hidden` (hidden indexes), and `none` (wildcard expressions are not accepted). Default is `open`. +`flat_settings` | Boolean | Specifies whether to return settings in flat format. When `true`, settings are returned in a flattened format (for example, `”index.creation_date”: “123456789”`). When `false`, settings are returned in nested format (for example, `”index”: {“creation_date”: “123456789”}`). Default is `false`. +`include_defaults` | Boolean | Specifies whether to include default settings in the response. Default settings are configurations that are implicitly applied by OpenSearch when not explicitly set, including settings used by OpenSearch plugins. When `true`, the response includes both custom and default settings. When `false`, the response includes only custom settings. Default is `false`. +`ignore_unavailable` | Boolean | Specifies whether to ignore indexes that are missing or closed. When `true`, the request does not return an error if the target index is missing or closed. When `false`, the request returns an error if the target index is unavailable. Default is `false`. +`local` | Boolean | Specifies whether to retrieve settings from the local node only or from the cluster manager node. When `true`, settings are retrieved from the local node. When `false`, settings are retrieved from the cluster manager node. Default is `false`. +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. + +## Example request: Retrieving settings for a single index + +The following example retrieves all settings for the `books` index: + + +{% capture step1_rest %} +GET /books/_settings +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_settings( + index = "books" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Retrieving settings from multiple indexes + +The following example retrieves settings from multiple indexes: + +```json +GET /books,products/_settings +``` +{% include copy.html %} + +## Example request: Retrieving settings from all indexes + +The following example retrieves settings from all indexes in the cluster: + +```json +GET /_all/_settings +``` +{% include copy.html %} + +## Example request: Retrieving settings using a wildcard pattern + +The following example uses a wildcard pattern to retrieve settings from all indexes matching the pattern: + +```json +GET /logs-*/_settings +``` +{% include copy.html %} + +## Example request: Filtering settings by name + +The following example filters the response to return only settings matching the specified pattern: + +```json +GET /logs-*/_settings/index.number_* +``` +{% include copy.html %} + +{% capture default_response %} + +## Example response + +By default, settings are returned in nested format: ```json { - "sample-index1": { + "books": { "settings": { "index": { - "creation_date": "1622672553417", - "number_of_shards": "1", - "number_of_replicas": "1", - "uuid": "GMEA0_TkSaamrnJSzNLzwg", - "version": { - "created": "135217827", - "upgraded": "135238227" + "replication": { + "type": "DOCUMENT" }, - "provided_name": "sample-index1" + "number_of_shards": "2", + "provided_name": "books", + "creation_date": "1778255937147", + "number_of_replicas": "1", + "uuid": "Onnd4TKBQMODrfvAvNXjAg", + "version": { + "created": "137277827" + } } } } } ``` + +{% endcapture %} +{{ default_response }} + +{% capture flat_response %} + +## Example response: Flat format + +When you specify `flat_settings=true`, settings are returned in flattened format: + +```json +{ + "books": { + "settings": { + "index.creation_date": "1778255937147", + "index.number_of_replicas": "1", + "index.number_of_shards": "2", + "index.provided_name": "books", + "index.replication.type": "DOCUMENT", + "index.uuid": "Onnd4TKBQMODrfvAvNXjAg", + "index.version.created": "137277827" + } + } +} +``` + +{% endcapture %} +{{ flat_response }} + +## Response body fields + +The following table lists all response body fields. + +Field | Description +:--- | :--- +`settings` | An object containing all settings for the index. The specific settings returned depend on the index configuration. For information about available index settings, see [Index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/settings/get`. diff --git a/_api-reference/index-apis/get-template-legacy.md b/_api-reference/index-apis/get-template-legacy.md new file mode 100644 index 00000000..01a093b0 --- /dev/null +++ b/_api-reference/index-apis/get-template-legacy.md @@ -0,0 +1,102 @@ +--- +layout: default +title: Get template (deprecated) +parent: Index templates +grand_parent: Index APIs +nav_order: 90 +--- + +# Get template +**Introduced 1.0** +{: .label .label-purple } + +The Get Template API has been deprecated. Use the new [Get Index Template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-index-template/) API. +{: .warning} + +The get template API operation is used to retrieve one or more index templates created using the legacy `/_template` endpoint. + +## Endpoints + +```json +GET /_template +GET /_template/{template-name} +``` + +## Path parameters + +The following table lists the available path parameters. All parameters are optional. + +| Parameter | Type | Description | +| :-------------- | :----- | :------------------------------------------------------------------------------- | +| `template-name` | String | The name of the index template to retrieve. Accepts wildcard expressions. | + +## Query parameters + +The following table lists the available query parameters. All parameters are optional. + +| Parameter | Type | Description | +| :--------------- | :------ | :--------------------------------------------------------------------------------------------------- | +| `flat_settings` | Boolean | If true, returns settings in flat format. Default is `false`. | +| `local` | Boolean | If true, the request does not retrieve the state from the cluster manager node. Default is `false`. | +| `cluster_manager_timeout` | Time | Specifies how long to wait for a connection to the cluster manager node. Default is `30s`. | + +## Example request + + +{% capture step1_rest %} +GET /_template/sample-template +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.get_template( + name = "sample-template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "sample-template": { + "order": 1, + "index_patterns": [ + "sample-*" + ], + "settings": { + "number_of_shards": "1" + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + } + } + }, + "aliases": {} + } +} +``` + +## Response fields + +The response object contains the following fields. + +| Field | Type | Description | +| ---------------- | ---------------- | ------------------------------------------------------------------------------ | +| `order` | Integer | An integer that determines the priority of the template when multiple templates match an index. Templates with a higher order value have higher precedence and are applied after lower-order templates, allowing them to override conflicting settings or mappings. | +| `index_patterns` | Array of strings | The list of index name patterns to which the template applies. | +| `settings` | Object | The index-level settings defined in the template. | +| `mappings` | Object | The field mappings defined for indexes that match the pattern. | +| `aliases` | Object | The aliases to associate with matching indexes. | + diff --git a/_api-reference/index-apis/index-blocks-allocation.md b/_api-reference/index-apis/index-blocks-allocation.md new file mode 100644 index 00000000..7fcbbc58 --- /dev/null +++ b/_api-reference/index-apis/index-blocks-allocation.md @@ -0,0 +1,21 @@ +--- +layout: default +title: Index blocks and allocation +parent: Index APIs +nav_order: 70 +has_children: true +has_toc: false +--- + +# Index blocks and allocation + +Index blocks and allocation APIs provide control over index access restrictions and shard allocation policies. These APIs help you manage cluster resources and control how indexes are distributed across your cluster nodes. + +## Available APIs + +OpenSearch supports the following index blocks and allocation APIs. + +| API | Description | +|-----|-------------| +| [Blocks]({{site.url}}{{site.baseurl}}/api-reference/index-apis/blocks/) | Adds or removes index blocks that restrict operations on indexes. | +| [Shard allocation]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shard-allocation/) | Controls shard allocation and routing for indexes. | \ No newline at end of file diff --git a/_api-reference/index-apis/index-operations.md b/_api-reference/index-apis/index-operations.md new file mode 100644 index 00000000..c90a9773 --- /dev/null +++ b/_api-reference/index-apis/index-operations.md @@ -0,0 +1,32 @@ +--- +layout: default +title: Index operations +parent: Index APIs +nav_order: 30 +has_children: true +has_toc: false +--- + +# Index operations + +Index operations APIs provide advanced functionality for maintaining and optimizing indexes in your OpenSearch cluster. These operations help you manage index performance, data organization, and cluster efficiency. + +## Available APIs + +OpenSearch supports the following index operations APIs. + +| API | Description | +|-----|-------------| +| [Clear index cache]({{site.url}}{{site.baseurl}}/api-reference/index-apis/clear-index-cache/) | Clears the cache associated with one or more indexes. | +| [Clone index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/clone/) | Clones an existing index. | +| [Flush]({{site.url}}{{site.baseurl}}/api-reference/index-apis/flush/) | Flushes one or more indexes. | +| [Force merge]({{site.url}}{{site.baseurl}}/api-reference/index-apis/force-merge/) | Forces merge on one or more indexes. | +| [Index recovery]({{site.url}}{{site.baseurl}}/api-reference/index-apis/recover/) | Returns information about ongoing and completed shard recoveries. | +| [Refresh]({{site.url}}{{site.baseurl}}/api-reference/index-apis/refresh/) | Refreshes one or more indexes. | +| [Rollover]({{site.url}}{{site.baseurl}}/api-reference/index-apis/rollover/) | Rolls over an index when it meets certain conditions. | +| [Scale]({{site.url}}{{site.baseurl}}/api-reference/index-apis/scale/) | Scales the number of replicas for one or more indexes. | +| [Index segments]({{site.url}}{{site.baseurl}}/api-reference/index-apis/segment/) | Returns segment information for one or more indexes. | +| [Index shard stores]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shard-stores/) | Returns information about shard copies and their storage locations. | +| [Shrink index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shrink-index/) | Shrinks an existing index. | +| [Split]({{site.url}}{{site.baseurl}}/api-reference/index-apis/split/) | Splits an existing index. | +| [Index stats]({{site.url}}{{site.baseurl}}/api-reference/index-apis/stats/) | Returns statistics for one or more indexes. | \ No newline at end of file diff --git a/_api-reference/index-apis/index-settings-mappings.md b/_api-reference/index-apis/index-settings-mappings.md new file mode 100644 index 00000000..c446fd57 --- /dev/null +++ b/_api-reference/index-apis/index-settings-mappings.md @@ -0,0 +1,22 @@ +--- +layout: default +title: Index settings and mappings +parent: Index APIs +nav_order: 40 +has_children: true +has_toc: false +--- + +# Index settings and mappings + +Index settings and mappings APIs allow you to configure and modify the behavior and structure of your indexes. These APIs provide control over index-level settings and field mappings that determine how your data is stored and indexed. + +## Available APIs + +OpenSearch supports the following index settings and mappings APIs. + +| API | Description | +|-----|-------------| +| [Get settings]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-settings/) | Returns settings information for one or more indexes. | +| [Update settings]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/) | Updates settings for one or more indexes. | +| [Put mapping]({{site.url}}{{site.baseurl}}/api-reference/index-apis/put-mapping/) | Adds new fields or updates existing field mappings. | \ No newline at end of file diff --git a/_api-reference/index-apis/index-template-exists.md b/_api-reference/index-apis/index-template-exists.md new file mode 100644 index 00000000..43bb28af --- /dev/null +++ b/_api-reference/index-apis/index-template-exists.md @@ -0,0 +1,74 @@ +--- +layout: default +title: Index template exists +parent: Index templates +grand_parent: Index APIs +nav_order: 40 +--- + +# Index template exists +**Introduced 1.0** +{: .label .label-purple } + +The index template exists API operation is used to verify whether an index template exists. + +## Endpoints + +```json +HEAD /_index_template/{template-name} +``` + +## Path parameters + +All path parameters are required. + +| Parameter | Type | Description | +| --------------- | ------ | -------------------------------------------------- | +| `template-name` | String | The name of the index template to check for existence. | + +## Query parameters + +All parameters are optional. + +| Parameter | Type | Description | +| ------------------------- | ------- | ---------------------------------------------------------------------------------------------------- | +| `local` | Boolean | If true, the request does not retrieve the state from the cluster manager node. Default is `false`. | +| `cluster_manager_timeout` | Time | Specifies how long to wait for a connection to the cluster manager node. Default is `30s`. | + +## Example request + + +{% capture step1_rest %} +HEAD /_index_template/my-template +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.exists_index_template( + name = "my-template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example responses + +If the template exists, the response returns a success code: + +```json +200 OK +``` + +If the template does not exist, the response returns a failure code: + +```json +404 Not Found +``` diff --git a/_api-reference/index-apis/index-templates.md b/_api-reference/index-apis/index-templates.md new file mode 100644 index 00000000..7baa6b33 --- /dev/null +++ b/_api-reference/index-apis/index-templates.md @@ -0,0 +1,39 @@ +--- +layout: default +title: Index templates +parent: Index APIs +nav_order: 50 +has_children: true +has_toc: false +--- + +# Index template APIs + +Index template APIs allow you to create and manage templates that automatically apply settings, mappings, and aliases to new indexes that match specific patterns. Templates provide a powerful way to ensure consistency across your indexes. + +You can add comments to template request bodies, for example, to explain why a setting is used. For more information, see [Comments in request bodies]({{site.url}}{{site.baseurl}}/api-reference/common-parameters/#comments-in-request-bodies). + +## Available APIs + +OpenSearch supports the following index template APIs. + +| API | Description | +|-----|-------------| +| [Create index template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index-template/) | Creates or updates an index template. | +| [Delete index template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-index-template/) | Deletes an index template. | +| [Get index template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-index-template/) | Returns information about one or more index templates. | +| [Index template exists]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-template-exists/) | Checks if an index template exists. | +| [Simulate index template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/simulate-index-template/) | Simulates the application of index templates. | +| [Component template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/component-template/) | Manages component templates that can be reused across index templates. | + +## Legacy template APIs + +OpenSearch also supports the following legacy template APIs for backward compatibility. These APIs use the older template format and are deprecated in favor of the preceding index template APIs. + +| API | Description | +|-----|-------------| +| [Post template (legacy)]({{site.url}}{{site.baseurl}}/api-reference/index-apis/post-template-legacy/) | Creates or updates a legacy index template using POST. | +| [Put template (legacy)]({{site.url}}{{site.baseurl}}/api-reference/index-apis/put-template-legacy/) | Creates or updates a legacy index template using PUT. | +| [Get template (legacy)]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-template-legacy/) | Returns information about one or more legacy index templates. | +| [Template exists (legacy)]({{site.url}}{{site.baseurl}}/api-reference/index-apis/template-exists-legacy/) | Checks if a legacy index template exists. | +| [Delete template (legacy)]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-template-legacy/) | Deletes a legacy index template. | \ No newline at end of file diff --git a/_api-reference/index-apis/index.md b/_api-reference/index-apis/index.md index 4c059b3e..6beb5e02 100644 --- a/_api-reference/index-apis/index.md +++ b/_api-reference/index-apis/index.md @@ -2,9 +2,12 @@ layout: default title: Index APIs has_children: true -nav_order: 35 +has_toc: false +nav_order: 60 redirect_from: + - /opensearch/rest-api/index-apis/index/ - /opensearch/rest-api/index-apis/ + - /api-reference/index-apis/ --- # Index APIs @@ -13,5 +16,20 @@ redirect_from: The index API operations let you interact with indexes in your cluster. Using these operations, you can create, delete, close, and complete other index-related operations. +## Index API operations + +The following index API operations are available, organized by category: + +- [Alias APIs]({{site.url}}{{site.baseurl}}/api-reference/alias/) - Create, update, delete, and retrieve information about index aliases +- [Core index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/core-index-apis/) - Fundamental operations for managing the lifecycle of indexes +- [Index operations]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-operations/) - Advanced functionality for maintaining and optimizing indexes +- [Index settings and mappings]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-settings-mappings/) - Configure and modify index behavior and structure +- [Index templates]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-templates/) - Create and manage templates for automatic index configuration +- [Index blocks and allocation]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-blocks-allocation/) - Control index access restrictions and shard allocation +- [Pull-based ingestion management]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pull-based-ingestion-management/) - Pause, resume, and get the state of pull-based ingestion +- [Dangling index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/dangling-index/) - Manage indexes that exist on disk but are not part of cluster state + +To manage data streams, use the [Data stream APIs]({{site.url}}{{site.baseurl}}/api-reference/data-stream/). + If you use the Security plugin, make sure you have the appropriate permissions. {: .note } diff --git a/_api-reference/index-apis/open-index.md b/_api-reference/index-apis/open-index.md index 6ca03486..dd12f328 100644 --- a/_api-reference/index-apis/open-index.md +++ b/_api-reference/index-apis/open-index.md @@ -1,52 +1,80 @@ --- layout: default title: Open index -parent: Index APIs -nav_order: 55 +parent: Core index APIs +grand_parent: Index APIs +nav_order: 50 redirect_from: - /opensearch/rest-api/index-apis/open-index/ --- -# Open index +# Open Index API **Introduced 1.0** {: .label .label-purple } The open index API operation opens a closed index, letting you add or search for data within the index. -## Example + +## Endpoints ```json -POST /sample-index/_open -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -``` -POST //_open +POST /{index}/_open ``` -## URL parameters +## Path parameters + +Parameter | Type | Description +:--- | :--- | :--- +<index> | String | The index to open. Can be a comma-separated list of multiple index names. Use `_all` or * to open all indexes. + +## Query parameters All parameters are optional. Parameter | Type | Description :--- | :--- | :--- -<index-name> | String | The index to open. Can be a comma-separated list of multiple index names. Use `_all` or * to open all indexes. -allow_no_indices | Boolean | Whether to ignore wildcards that don't match any indexes. Default is true. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions). Default is open. -ignore_unavailable | Boolean | If true, OpenSearch does not search for missing or closed indexes. Default is false. -wait_for_active_shards | String | Specifies the number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for a response from the cluster. Default is `30s`. -wait_for_completion | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. Default is `true`. -task_execution_timeout | Time | The explicit task execution timeout. Only useful when wait_for_completion is set to `false`. Default is `1h`. +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. +`expand_wildcards` | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are all (match all indexes), open (match open indexes), closed (match closed indexes), hidden (match hidden indexes), and none (do not accept wildcard expressions). Default is `open`. +`ignore_unavailable` | Boolean | If true, OpenSearch does not search for missing or closed indexes. Default is `false`. +`wait_for_active_shards` | String | Specifies the number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. +`cluster_manager_timeout` | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. +`timeout` | Time | How long to wait for a response from the cluster. Default is `30s`. +`wait_for_completion` | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. Default is `true`. +`task_execution_timeout` | Time | The explicit task execution timeout. Only useful when wait_for_completion is set to `false`. Default is `1h`. + +## Example request + + +{% capture step1_rest %} +POST /sample-index/_open +{% endcapture %} + +{% capture step1_python %} -## Response +response = client.indices.open( + index = "sample-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response ```json { "acknowledged": true, "shards_acknowledged": true } ``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/open`. diff --git a/_api-reference/index-apis/pause-ingestion.md b/_api-reference/index-apis/pause-ingestion.md new file mode 100644 index 00000000..1d3c21a5 --- /dev/null +++ b/_api-reference/index-apis/pause-ingestion.md @@ -0,0 +1,89 @@ +--- +layout: default +title: Pause ingestion +parent: Pull-based ingestion management +grand_parent: Index APIs +nav_order: 10 +--- + +# Pause Ingestion API +**Introduced 3.0** +{: .label .label-purple } + +Pauses ingestion for one or more indexes. When paused, OpenSearch stops consuming data from the streaming source for all shards in the specified indexes. To restart ingestion, use the [Resume Ingestion API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/resume-ingestion/). + +## Endpoints + +```json +POST /{index}/ingestion/_pause +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `index` | String | Required | The index to pause. Can be a comma-separated list of multiple index names. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time units | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. | +| `timeout` | Time units | The amount of time to wait for a response from the cluster. Default is `30s`. | + +## Example request + + +{% capture step1_rest %} +POST /my-index/ingestion/_pause +{% endcapture %} + +{% capture step1_python %} + + +response = client.ingestion.pause( + index = "my-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true, + "shards_acknowledged": true +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | Whether the pause request was acknowledged. | +| `shards_acknowledged` | Boolean | Whether the pause request was acknowledged by the individual shards. | +| `failures` | Array of objects | A list of shard-level failures. See [Failures](#failures). | +| `error` | String | The request-level error message, if any. | + +### Failures + +Each object in the `failures` array contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `shard` | Integer | The shard number. | +| `error` | String | The shard-level error message. | diff --git a/_api-reference/index-apis/post-template-legacy.md b/_api-reference/index-apis/post-template-legacy.md new file mode 100644 index 00000000..69940a01 --- /dev/null +++ b/_api-reference/index-apis/post-template-legacy.md @@ -0,0 +1,142 @@ +--- +layout: default +title: Post template (deprecated) +parent: Index templates +grand_parent: Index APIs +nav_order: 70 +--- + +# Post template +**Introduced 1.0** +{: .label .label-purple } + +The Post Template API has been deprecated. Use the new [Create or Update Index Template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index-template/) API. +{: .warning} + +The post template API operation is used to create or update an index template. Templates define settings, mappings, and aliases applied automatically when a matching index is created. + +## Endpoints + +```json +POST /_template/{template-name} +``` + +## Path parameters + +All path parameters are required. + +| Parameter | Type | Description | +| :-------------- | :----- | :---------------------------------------------- | +| `template-name` | String | The name of the index template to create or update. | + +## Query parameters + +All query parameters are optional. + +| Parameter | Type | Description | +| :--------------- | :------ | :---------------------------------------------------------------------------------------------------------------- | +| `order` | Integer | The order in which to apply the template if multiple templates match. Higher values are applied last. Default is `0`. | +| `create` | Boolean | If `true`, the operation fails if a template with the same name already exists. Default is `false`. | +| `cluster_manager_timeout` | Time | Specifies how long to wait for a connection to the cluster manager node. Default is `30s`. | + +## Request body + +The request body must define one or more of the following components. + +| Field | Type | Description | +| :--------------- | :----- | :------------------------------------------------------------------- | +| `index_patterns` | Array | The list of index name patterns to which the template applies. Required. | +| `settings` | Object | The index settings to apply to matching indexes. | +| `mappings` | Object | The mappings for fields in the index. | +| `aliases` | Object | The aliases to assign to matching indexes. | +| `version` | Integer | The optional version number used to identify the template. | + +## Example request + + +{% capture step1_rest %} +POST /_template/logs_template +{ + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_template( + name = "logs_template", + body = { + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` diff --git a/_api-reference/index-apis/pull-based-ingestion-management.md b/_api-reference/index-apis/pull-based-ingestion-management.md new file mode 100644 index 00000000..d21e3b2f --- /dev/null +++ b/_api-reference/index-apis/pull-based-ingestion-management.md @@ -0,0 +1,26 @@ +--- +layout: default +title: Pull-based ingestion management +parent: Index APIs +nav_order: 80 +has_children: true +has_toc: false +redirect_from: + - /api-reference/document-apis/pull-based-ingestion-management/ +--- + +# Pull-based ingestion management +**Introduced 3.0** +{: .label .label-purple } + +Pull-based ingestion management APIs control how an index consumes data from its [pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/) source. You can stop and restart ingestion, reset the position from which shards read, and check the state of each shard's poller. + +## Available APIs + +OpenSearch supports the following pull-based ingestion management APIs. + +| API | Description | +| :--- | :--- | +| [Pause ingestion]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pause-ingestion/) | Stops consuming data from the source for all shards in one or more indexes. | +| [Resume ingestion]({{site.url}}{{site.baseurl}}/api-reference/index-apis/resume-ingestion/) | Restarts consuming data, optionally from a specific offset or timestamp. | +| [Get ingestion state]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-ingestion-state/) | Returns the current ingestion state for each shard in one or more indexes. | diff --git a/_api-reference/index-apis/put-mapping.md b/_api-reference/index-apis/put-mapping.md index 5f6be9f1..8f4fb84d 100644 --- a/_api-reference/index-apis/put-mapping.md +++ b/_api-reference/index-apis/put-mapping.md @@ -1,113 +1,806 @@ --- layout: default -title: Create or update mappings -parent: Index APIs -nav_order: 27 +title: Create or update index mappings +parent: Index settings and mappings +grand_parent: Index APIs +nav_order: 30 redirect_from: + - /opensearch/rest-api/index-apis/put-mapping/ - /opensearch/rest-api/index-apis/update-mapping/ - /opensearch/rest-api/update-mapping/ --- -# Create or update mappings +# Create or Update Index Mappings API **Introduced 1.0** {: .label .label-purple } -If you want to create or add mappings and fields to an index, you can use the put mapping API operation. For an existing mapping, this operation updates the mapping. +Use this API to introduce new fields into an existing index or modify the search settings of existing fields. This operation lets you evolve your index schema without recreating the index from scratch. -You can't use this operation to update mappings that already map to existing data in the index. You must first create a new index with your desired mappings, and then use the [reindex API operation]({{site.url}}{{site.baseurl}}/opensearch/reindex-data) to map all the documents from your old index to the new index. If you don't want any downtime while you re-index your indexes, you can use [aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias). - - -## Required path parameter - -The only required path parameter is the index with which to associate the mapping. If you don't specify an index, you will get an error. You can specify a single index, or multiple indexes separated by a comma as follows: - -``` -PUT //_mapping -PUT /,/_mapping -``` - -## Required request body field - -The request body must contain `properties`, which has all of the mappings that you want to create or update. +You cannot use this operation to change the mapping or field type of a field that already contains indexed data. Modifying an existing field's type risks making previously indexed data incompatible with the new mapping. If you need to change the type of an existing field, create a new index with the desired mappings and then use the [Reindex]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) operation to copy documents from the original index. To avoid downtime during reindexing, you can use [aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias/). For more information, see [Changing the type of an existing field](#example-changing-the-type-of-an-existing-field). + +## Endpoints ```json -{ - "properties":{ - "color":{ - "type": "text" - }, - "year":{ - "type": "integer" - } - } -} +POST /{index}/_mapping +PUT /{index}/_mapping ``` + -## Optional request body fields +## Path parameters -### dynamic +The following table lists the available path parameters. -You can make the document structure match the structure of the index mapping by setting the `dynamic` request body field to `strict`, as seen in the following example: +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the index to update. You can specify a single index name, a comma-separated list of index names, or a wildcard expression. To update the mapping of all indexes, use `_all` or `*`. | -```json -{ - "dynamic": "strict", - "properties":{ - "color":{ - "type": "text" - } - } -} -``` +## Query parameters -## Optional query parameters +The following table lists the available query parameters. All query parameters are optional. -Optionally, you can add query parameters to make a more specific request. For example, to skip any missing or closed indexes in the response, you can add the `ignore_unavailable` query parameter to your request as follows: +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | Specifies whether to ignore wildcards that do not match any indexes. If `false`, the request returns an error when wildcards do not match any indexes. | `true` | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | +| `expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are:
- `all`: Match all indexes, including hidden indexes.
- `open`: Match open indexes.
- `closed`: Match closed indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Do not accept wildcard expressions. | `open` | +| `ignore_unavailable` | Boolean | Specifies whether to ignore indexes that are missing or closed. If `true`, missing or closed indexes are not included in the response. | `false` | +| `timeout` | String | The amount of time to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. | `30s` | +| `write_index_only` | Boolean | If `true`, the mappings are applied only to the current write index for the target. | `false` | -```json -PUT /sample-index/_mapping?ignore_unavailable -``` +## Request body fields -The following table defines the put mapping query parameters: +The following table lists the available request body fields. -Parameter | Data type | Description -:--- | :--- | :--- -allow_no_indices | Boolean | Whether to ignore wildcards that don’t match any indexes. Default is `true`. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are `all` (match all indexes), `open` (match open indexes), `closed` (match closed indexes), `hidden` (match hidden indexes), and `none` (do not accept wildcard expressions), which must be used with `open`, `closed`, or both. Default is `open`. -ignore_unavailable | Boolean | If true, OpenSearch does not include missing or closed indexes in the response. -ignore_malformed | Boolean | Use this parameter with the `ip_range` data type to specify that OpenSearch should ignore malformed fields. If `true`, OpenSearch does not include entries that do not match the IP range specified in the index in the response. The default is `false`. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for the response to return. Default is `30s`. -write_index_only | Boolean | Whether OpenSearch should apply mapping updates only to the write index. +| Field | Data type | Description | +| :--- | :--- | :--- | +| `properties` | Object | Required. Defines the fields and their types for the index mapping. Each field can include a name, [field data type]({{site.url}}{{site.baseurl}}/field-types/index/), and [mapping parameters]({{site.url}}{{site.baseurl}}/field-types/mapping-parameters/). | +| `dynamic` | String | Controls whether new fields are added dynamically. Valid values are `true` (new fields are added automatically), `false` (new fields are ignored), and `strict` (requests that contain unmapped fields are rejected). Default is `true`. | -#### Sample Request +## Example: Adding fields to an index -The following request creates a new mapping for the `sample-index` index: - -```json -PUT /sample-index/_mapping +The Create or Update Mappings API requires an existing index. The following example adds `description` and `price` fields to the `products` index: + +{% capture step1_rest %} +PUT /products/_mapping +{ + "properties": { + "description": { + "type": "text" + }, + "price": { + "type": "float" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_mapping( + index = "products", + body = { + "properties": { + "description": { + "type": "text" + }, + "price": { + "type": "float" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can verify the mapping was applied by using the [Get Mappings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-mapping/): + +```json +GET /products/_mapping +``` + +## Example: Updating multiple indexes + +You can apply a mapping update to multiple indexes in a single request by specifying a comma-separated list of index names. The following example adds `currency` and `tax_rate` fields to both a US and EU regional catalog: + + +{% capture step1_rest %} +PUT /products-us,products-eu/_mapping +{ + "properties": { + "currency": { + "type": "keyword" + }, + "tax_rate": { + "type": "float" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_mapping( + index = "products-us,products-eu", + body = { + "properties": { + "currency": { + "type": "keyword" + }, + "tax_rate": { + "type": "float" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Adding properties to an existing object field + +You can add new inner fields to an existing [object]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/object/) field. Suppose the `products` index already has a `manufacturer` object with a `name` field. The following example adds a `country` keyword field to the `manufacturer` object: + + +{% capture step1_rest %} +PUT /products/_mapping +{ + "properties": { + "manufacturer": { + "properties": { + "country": { + "type": "keyword" + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_mapping( + index = "products", + body = { + "properties": { + "manufacturer": { + "properties": { + "country": { + "type": "keyword" + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can confirm the nested structure by retrieving the mapping: + +```json +GET /products/_mapping +``` + +
+ + Response + + {: .text-delta} + +```json +{ + "products" : { + "mappings" : { + "properties" : { + "description" : { + "type" : "text" + }, + "manufacturer" : { + "properties" : { + "country" : { + "type" : "keyword" + }, + "name" : { + "type" : "text" + } + } + }, + "price" : { + "type" : "float" + }, + "product_name" : { + "type" : "text" + } + } } } } ``` -{% include copy-curl.html %} +
-#### Sample Response +## Example: Adding multi-fields to an existing field -Upon success, the response returns `"acknowledged": true`. +[Multi-fields]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/fields/) allow you to index the same field in different ways. For instance, a `text` field used for full-text search can also have a `keyword` sub-field for sorting or aggregations. The following example adds a `product_name.keyword` sub-field with `ignore_above` set to `256`, enabling exact-match filtering and sorting on product names: + + +{% capture step1_rest %} +PUT /products/_mapping +{ + "properties": { + "product_name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_mapping( + index = "products", + body = { + "properties": { + "product_name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can verify the multi-field configuration: + +```json +GET /products/_mapping +``` + +
+ + Response + + {: .text-delta} ```json { - "acknowledged": true + "products" : { + "mappings" : { + "properties" : { + "description" : { + "type" : "text" + }, + "manufacturer" : { + "properties" : { + "country" : { + "type" : "keyword" + }, + "name" : { + "type" : "text" + } + } + }, + "price" : { + "type" : "float" + }, + "product_name" : { + "type" : "text", + "fields" : { + "keyword" : { + "type" : "keyword", + "ignore_above" : 256 + } + } + } + } + } + } +} +``` +
+ +## Example: Changing supported mapping parameters + +Some [mapping parameters]({{site.url}}{{site.baseurl}}/field-types/mapping-parameters/) can be updated for an existing field using the Create or Update Mappings API. For example, you can change the [`ignore_above`]({{site.url}}{{site.baseurl}}/field-types/mapping-parameters/ignore-above/) value for a keyword field. The following example increases `ignore_above` from `20` to `50` for the `sku` field, allowing longer product codes to be indexed: + + +{% capture step1_rest %} +PUT /products/_mapping +{ + "properties": { + "sku": { + "type": "keyword", + "ignore_above": 50 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_mapping( + index = "products", + body = { + "properties": { + "sku": { + "type": "keyword", + "ignore_above": 50 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can confirm the updated parameter value: + +```json +GET /products/_mapping +``` + +
+ + Response + + {: .text-delta} + +```json +{ + "products" : { + "mappings" : { + "properties" : { + "description" : { + "type" : "text" + }, + "manufacturer" : { + "properties" : { + "country" : { + "type" : "keyword" + }, + "name" : { + "type" : "text" + } + } + }, + "price" : { + "type" : "float" + }, + "product_name" : { + "type" : "text", + "fields" : { + "keyword" : { + "type" : "keyword", + "ignore_above" : 256 + } + } + }, + "sku" : { + "type" : "keyword", + "ignore_above" : 50 + } + } + } + } +} +``` +
+ +## Example: Renaming a field using an alias + +Because renaming a field makes previously stored data inaccessible under the new name, use an [`alias`]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/alias/) field type to provide an alternate way to reference the field. The following example creates an `item_id` alias that points to the existing `product_id` field, allowing queries to use either name: + + +{% capture step1_rest %} +PUT /products/_mapping +{ + "properties": { + "item_id": { + "type": "alias", + "path": "product_id" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_mapping( + index = "products", + body = { + "properties": { + "item_id": { + "type": "alias", + "path": "product_id" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can verify the alias was created: + +```json +GET /products/_mapping +``` + +
+ + Response + + {: .text-delta} + +```json +{ + "products" : { + "mappings" : { + "properties" : { + "description" : { + "type" : "text" + }, + "item_id" : { + "type" : "alias", + "path" : "product_id" + }, + "manufacturer" : { + "properties" : { + "country" : { + "type" : "keyword" + }, + "name" : { + "type" : "text" + } + } + }, + "price" : { + "type" : "float" + }, + "product_id" : { + "type" : "keyword" + }, + "product_name" : { + "type" : "text", + "fields" : { + "keyword" : { + "type" : "keyword", + "ignore_above" : 256 + } + } + }, + "sku" : { + "type" : "keyword", + "ignore_above" : 50 + } + } + } + } +} +``` +
+ +## Example: Changing the type of an existing field + +You cannot directly change the field type of a field that already contains indexed data. Instead, create a new index with the correct mapping and use the [Reindex]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) API to copy documents from the original index. + +The following example changes the `weight` field from `integer` to `float` so that fractional values (such as `0.75` kg) can be stored accurately. + +First, create the new index with the updated field type: + + +{% capture step1_rest %} +PUT /products-v2 +{ + "mappings": { + "properties": { + "product_name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "price": { + "type": "float" + }, + "weight": { + "type": "float" + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.create( + index = "products-v2", + body = { + "mappings": { + "properties": { + "product_name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "price": { + "type": "float" + }, + "weight": { + "type": "float" + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Then reindex the data from the original index into the new one: + + +{% capture step1_rest %} +POST /_reindex +{ + "source": { + "index": "products" + }, + "dest": { + "index": "products-v2" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex( + body = { + "source": { + "index": "products" + }, + "dest": { + "index": "products-v2" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +
+ + Response + + {: .text-delta} + +```json +{ + "took" : 8, + "timed_out" : false, + "total" : 2, + "updated" : 0, + "created" : 2, + "deleted" : 0, + "batches" : 1, + "version_conflicts" : 0, + "noops" : 0, + "retries" : { + "bulk" : 0, + "search" : 0 + }, + "throttled_millis" : 0, + "requests_per_second" : -1.0, + "throttled_until_millis" : 0, + "failures" : [ ] +} +``` +
+ +## Example response + +A successful mapping update returns the following response: + +```json +{ + "acknowledged": true } ``` +## Response body fields +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | Indicates whether the request was acknowledged by all relevant nodes in the cluster. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/mapping/put`. diff --git a/_api-reference/index-apis/put-template-legacy.md b/_api-reference/index-apis/put-template-legacy.md new file mode 100644 index 00000000..085a8b41 --- /dev/null +++ b/_api-reference/index-apis/put-template-legacy.md @@ -0,0 +1,142 @@ +--- +layout: default +title: Put template (deprecated) +parent: Index templates +grand_parent: Index APIs +nav_order: 80 +--- + +# Put template +**Introduced 1.0** +{: .label .label-purple } + +The Put Template API has been deprecated. Use the new [Create or Update Index Template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index-template/) API. +{: .warning} + +The put template API operation is used to create or update an index template. Templates define settings, mappings, and aliases applied automatically when a matching index is created. + +## Endpoints + +```json +PUT /_template/{template-name} +``` + +## Path parameters + +All path parameters are required. + +| Parameter | Type | Description | +| :-------------- | :----- | :---------------------------------------------- | +| `template-name` | String | The name of the index template to create or update. | + +## Query parameters + +All query parameters are optional. + +| Parameter | Type | Description | +| :--------------- | :------ | :---------------------------------------------------------------------------------------------------------------- | +| `order` | Integer | The order in which to apply the template if multiple templates match. Higher values are applied last. Default is `0`. | +| `create` | Boolean | If `true`, the operation will fail if a template with the same name already exists. Default is `false`. | +| `cluster_manager_timeout` | Time | Specifies how long to wait for a connection to the cluster manager node. Default is `30s`. | + +## Request body + +The request body must define one or more of the following components. + +| Field | Type | Description | +| :--------------- | :----- | :------------------------------------------------------------------- | +| `index_patterns` | Array | The list of index name patterns to which the template applies. Required. | +| `settings` | Object | The index settings to apply to matching indexes. | +| `mappings` | Object | The mappings for fields in the index. | +| `aliases` | Object | The aliases to assign to matching indexes. | +| `version` | Integer | The optional version number used to identify the template. | + +## Example request + + +{% capture step1_rest %} +PUT /_template/logs_template +{ + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_template( + name = "logs_template", + body = { + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true +} +``` diff --git a/_api-reference/index-apis/recover.md b/_api-reference/index-apis/recover.md new file mode 100644 index 00000000..9f37c712 --- /dev/null +++ b/_api-reference/index-apis/recover.md @@ -0,0 +1,349 @@ +--- +layout: default +title: Index recovery +parent: Index operations +grand_parent: Index APIs +nav_order: 50 +--- + +# Index Recovery API +**Introduced 1.0** +{: .label .label-purple } + +The Recovery API provides information about any completed or ongoing shard recoveries for one or more indexes. If a data stream is listed, the API returns information about that data stream's backing indexes. + +Shard recovery involves creating a shard copy to restore a primary shard from a snapshot or to synchronize a replica shard. After the shard recovery process completes, the recovered shard becomes available for use in search and index operations. + +Shard recovery occurs automatically in the following scenarios: + +- Node startup, known as a local store recovery +- Replication of a primary shard +- Relocation of a shard to a different node within the same cluster +- Restoration of a snapshot +- Clone, shrink, or split operations + +The Recovery API reports solely on completed recoveries for shard copies presently stored in the cluster. It reports only the most recent recovery for each shard copy and does not include historical information about previous recoveries or information about recoveries of shard copies that no longer exist. Consequently, if a shard copy completes a recovery and is subsequently relocated to a different node, then the information about the original recovery is not displayed in the Recovery API. + + +## Endpoints + +```json +GET /_recovery +GET /{index}/_recovery/ +``` + +## Path parameters + +Parameter | Data type | Description +:--- | :--- +`index` | String | A comma-separated list of indexes, data streams, or index aliases to which the operation is applied. Supports wildcard expressions (`*`). Use `_all` or `*` to specify all indexes and data streams in a cluster. | + + +## Query parameters + +All of the following query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`active_only` | Boolean | When `true`, the response only includes active shard recoveries. Default is `false`. +`detailed` | Boolean | When `true`, provides detailed information about shard recoveries. Default is `false`. +`index` | String | A comma-separated list or wildcard expression of index names used to limit the request. + + +## Example requests + +The following examples demonstrate how to recover information using the Recovery API. + +### Recover information from several or all indexes + +The following example request returns recovery information about several indexes in a [human-readable format]({{site.url}}{{site.baseurl}}/api-reference/common-parameters/#human-readable-output): + + +{% capture step1_rest %} +GET /index1,index2/_recovery?human +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.recovery( + index = "index1,index2", + params = { "human": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The following example request returns recovery information about all indexes in a human-readable format: + + +{% capture step1_rest %} +GET /_recovery?human +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.recovery( + params = { "human": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Recover detailed information + +The following example request returns detailed recovery information: + + +{% capture step1_rest %} +GET /_recovery?human&detailed=true +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.recovery( + params = { "human": "true", "detailed": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following response returns detailed recovery information about an index named `shakespeare`: + +```json +{ + "shakespeare": { + "shards": [ + { + "id": 0, + "type": "EXISTING_STORE", + "stage": "DONE", + "primary": true, + "start_time": "2024-07-01T18:06:47.415Z", + "start_time_in_millis": 1719857207415, + "stop_time": "2024-07-01T18:06:47.538Z", + "stop_time_in_millis": 1719857207538, + "total_time": "123ms", + "total_time_in_millis": 123, + "source": { + "bootstrap_new_history_uuid": false + }, + "target": { + "id": "uerS7REgRQCbBF3ImY8wOQ", + "host": "172.18.0.3", + "transport_address": "172.18.0.3:9300", + "ip": "172.18.0.3", + "name": "opensearch-node2" + }, + "index": { + "size": { + "total": "17.8mb", + "total_in_bytes": 18708764, + "reused": "17.8mb", + "reused_in_bytes": 18708764, + "recovered": "0b", + "recovered_in_bytes": 0, + "percent": "100.0%" + }, + "files": { + "total": 7, + "reused": 7, + "recovered": 0, + "percent": "100.0%", + "details": [ + { + "name": "_1.cfs", + "length": "9.8mb", + "length_in_bytes": 10325945, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_0.cfe", + "length": "479b", + "length_in_bytes": 479, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_0.si", + "length": "333b", + "length_in_bytes": 333, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_1.cfe", + "length": "479b", + "length_in_bytes": 479, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_1.si", + "length": "333b", + "length_in_bytes": 333, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_0.cfs", + "length": "7.9mb", + "length_in_bytes": 8380790, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "segments_3", + "length": "405b", + "length_in_bytes": 405, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + } + ] + }, + "total_time": "6ms", + "total_time_in_millis": 6, + "source_throttle_time": "-1", + "source_throttle_time_in_millis": 0, + "target_throttle_time": "-1", + "target_throttle_time_in_millis": 0 + }, + "translog": { + "recovered": 0, + "total": 0, + "percent": "100.0%", + "total_on_start": 0, + "total_time": "113ms", + "total_time_in_millis": 113 + }, + "verify_index": { + "check_index_time": "0s", + "check_index_time_in_millis": 0, + "total_time": "0s", + "total_time_in_millis": 0 + } + }, + { + "id": 0, + "type": "PEER", + "stage": "DONE", + "primary": false, + "start_time": "2024-07-01T18:06:47.693Z", + "start_time_in_millis": 1719857207693, + "stop_time": "2024-07-01T18:06:47.744Z", + "stop_time_in_millis": 1719857207744, + "total_time": "50ms", + "total_time_in_millis": 50, + "source": { + "id": "uerS7REgRQCbBF3ImY8wOQ", + "host": "172.18.0.3", + "transport_address": "172.18.0.3:9300", + "ip": "172.18.0.3", + "name": "opensearch-node2" + }, + "target": { + "id": "HFYKietmTO6Ud9COgP0k9Q", + "host": "172.18.0.2", + "transport_address": "172.18.0.2:9300", + "ip": "172.18.0.2", + "name": "opensearch-node1" + }, + "index": { + "size": { + "total": "0b", + "total_in_bytes": 0, + "reused": "0b", + "reused_in_bytes": 0, + "recovered": "0b", + "recovered_in_bytes": 0, + "percent": "0.0%" + }, + "files": { + "total": 0, + "reused": 0, + "recovered": 0, + "percent": "0.0%", + "details": [] + }, + "total_time": "1ms", + "total_time_in_millis": 1, + "source_throttle_time": "-1", + "source_throttle_time_in_millis": 0, + "target_throttle_time": "-1", + "target_throttle_time_in_millis": 0 + }, + "translog": { + "recovered": 0, + "total": 0, + "percent": "100.0%", + "total_on_start": -1, + "total_time": "42ms", + "total_time_in_millis": 42 + }, + "verify_index": { + "check_index_time": "0s", + "check_index_time_in_millis": 0, + "total_time": "0s", + "total_time_in_millis": 0 + } + } + ] + } +} +``` + +## Response body fields + +The API responds with the following information about the recovery shard. + +Parameter | Data type | Description +:--- | :--- | :--- +`id` | Integer | The ID of the shard. +`type` | String | The recovery source for the shard. Returned values include:
- `EMPTY_STORE`: An empty store. Indicates a new primary shard or the forced allocation of an empty primary shard using the Cluster Reroute API.
- `EXISTING_STORE`: The store of an existing primary shard. Indicates that the recovery is related to node startup or the allocation of an existing primary shard.
- `LOCAL_SHARDS`: Shards belonging to another index on the same node. Indicates that the recovery is related to a clone, shrink, or split operation.
- `PEER`: A primary shard on another node. Indicates that the recovery is related to shard replication.
- `SNAPSHOT`: A snapshot. Indicates that the recovery is related to a snapshot restore operation. +`STAGE` | String | The recovery stage. Returned values can include:
- `INIT`: Recovery has not started.
- `INDEX`: Reading index metadata and copying bytes from the source to the destination.
- `VERIFY_INDEX`: Verifying the integrity of the index.
- `TRANSLOG`: Replaying the transaction log.
- `FINALIZE`: Cleanup.
- `DONE`: Complete. +`primary` | Boolean | When `true`, the shard is a primary shard. +`start_time` | String | The timestamp indicating when the recovery started. +`stop_time` | String | The timestamp indicating when the recovery completed. +`total_time_in_millis` | String | The total amount of time taken to recover a shard, in milliseconds. +`source` | Object | The recovery source. This can include a description of the repository (if the recovery is from a snapshot) or a description of the source node. +`target` | Object | The destination node. +`index` | Object | Statistics about the physical index recovery. +`translog` | Object | Statistics about the translog recovery. + `start` | Object | Statistics about the amount of time taken to open and start the index. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/recovery`. diff --git a/_api-reference/index-apis/refresh.md b/_api-reference/index-apis/refresh.md new file mode 100644 index 00000000..5bb8bfd1 --- /dev/null +++ b/_api-reference/index-apis/refresh.md @@ -0,0 +1,123 @@ +--- +layout: default +title: Refresh index +parent: Index operations +grand_parent: Index APIs +nav_order: 60 +--- + +# Refresh Index API +**Introduced 1.0** +{: .label .label-purple } + +The Refresh Index API refreshes one or more indexes, making all operations performed on those indexes since the last refresh available for search. When you index a document, it is first written to a translog and added to in-memory buffers. The document is not searchable until a refresh operation converts these in-memory structures into searchable segments on disk. In the case of data streams, the Refresh Index API refreshes a stream's backing indexes. + +For a conceptual overview of how refresh operations work in OpenSearch, see [Refresh]({{site.url}}{{site.baseurl}}/getting-started/concepts/#refresh). + +## Refresh interval + +The `index.refresh_interval` setting controls how often an index refreshes automatically. OpenSearch's refresh behavior depends on whether `index.refresh_interval` is set: + +- When set, indexes are refreshed based on the `index.refresh_interval` setting (in seconds). For more information about `index.refresh_interval` settings, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). +- When not set, refreshes occur every second until the shard receives no search requests for at least the amount of time specified by the `index.search.idle.after` setting (in seconds). Default is `30s`. + +After a shard becomes idle, the indexes will not refresh until either the next search request or a Refresh Index API request is sent. The first search request on an idle shard will wait for the refresh operation to complete. + +To use the Refresh Index API, you must have write access to the indexes you want to refresh. + +## Refresh request behavior + +The Refresh Index API call is synchronous. The response is returned only after all targeted shards have been refreshed. + +## Best practices + +Refresh operations are resource intensive and can impact cluster performance. To ensure optimal cluster performance, we recommend the following best practices: + +- **Rely on automatic refreshes**: Wait for OpenSearch's periodic refresh (controlled by `index.refresh_interval`) rather than performing explicit refreshes when possible. +- **Use `refresh=wait_for` for indexing workflows**: If your application indexes documents and then immediately searches for them, use the `refresh=wait_for` query parameter on indexing operations instead of calling the Refresh API. This option ensures the indexing operation waits for a periodic refresh before returning, without forcing an immediate refresh. For more information, see [The `refresh` query parameter](#the-refresh-query-parameter). +- **Avoid `refresh=true` in production**: Using `refresh=true` on index, update, or delete operations forces an immediate refresh and creates inefficient index structures (small segments) that must later be merged, impacting both indexing and search performance. + +## Endpoints + +```json +POST /_refresh +GET /_refresh +POST /{index}/_refresh +GET /{index}/_refresh +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | A comma-separated list of index names to be refreshed. Wildcards are accepted.| + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `ignore_unavailable` | Boolean | When `false`, the request returns an error when it targets a missing or closed index. Default is `false`. +| `allow_no_indices` | Boolean | When `false`, the Refresh Index API returns an error when a wildcard expression, index alias, or `_all` targets only closed or missing indexes, even when the request is made against open indexes. Default is `true`. | +| `expand_wildcards` | String | The type of index that the wildcard patterns can match. If the request targets data streams, this argument determines whether the wildcard expressions match any hidden data streams. Supports comma-separated values, such as `open,hidden`. Valid values are `all`, `open`, `closed`, `hidden`, and `none`. + + +## Example request: Refreshing several data streams or indexes + +The following example request refreshes two indexes named `my-index-A` and `my-index-B`: + + + +{% capture step1_rest %} +POST /my-index-A,my-index-B/_refresh +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.refresh( + index = "my-index-A,my-index-B" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Refreshing all data streams and indexes + +The following request refreshes all data streams and indexes in a cluster: + +```json +POST /_refresh +``` +{% include copy-curl.html %} + +## Example request: Refreshing using the GET method + +You can also use the `GET` method to refresh indexes. The following example uses `GET` to refresh a specific index: + +```json +GET /my-index/_refresh +``` +{% include copy-curl.html %} + +The `GET` method works identically to the `POST` method and is useful in environments where `POST` requests may be restricted or when you prefer to use `GET` for read-like operations. + +## The refresh query parameter + +The document APIs such as Index, Update, Delete, and Bulk APIs support a `refresh` query parameter that controls when changes made by the request are made visible to search. This parameter provides an alternative to calling the Refresh Index API explicitly. + +For more information about the `refresh` parameter, see the [Index Document API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index-document/), [Update Document API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-document/), [Delete Document API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/delete-document/), and [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) documentation. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/refresh` and `indices:admin/refresh*`. diff --git a/_api-reference/index-apis/resolve-index.md b/_api-reference/index-apis/resolve-index.md new file mode 100644 index 00000000..e10352a1 --- /dev/null +++ b/_api-reference/index-apis/resolve-index.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Resolve index +parent: Core index APIs +grand_parent: Index APIs +nav_order: 70 +--- + +# Resolve Index API +**Introduced 1.0** +{: .label .label-purple } + +The Resolve Index API helps you understand how OpenSearch resolves aliases, data streams, and concrete indexes that match a specified name or wildcard expression. + +## Endpoints + +```json +GET /_resolve/index/{name} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `name` | String | The name, alias, data stream, or wildcard expression to resolve. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `expand_wildcards` | String | Controls how wildcard expressions expand to matching indexes. Multiple values can be combined using commas. Valid values are:
• `all` – Expand to open and closed indexes, including hidden ones.
• `open` – Expand only to open indexes.
• `closed` – Expand only to closed indexes.
• `hidden` – Include hidden indexes (must be used with `open`, `closed`, or both).
• `none` – Wildcard expressions are not accepted.
**Default**: `open`. | + +## Example requests + +The following sections provide example Resolve API requests. + + +### Resolve a concrete index + + + +{% capture step1_rest %} +GET /_resolve/index/my-index-001 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.resolve_index( + name = "my-index-001" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Resolve indexes using a wildcard + + + +{% capture step1_rest %} +GET /_resolve/index/my-index-* +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.resolve_index( + name = "my-index-*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Resolve a data stream or alias + +If an alias or data stream named `logs-app` exists, use the following request to resolve it: + + +{% capture step1_rest %} +GET /_resolve/index/logs-app +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.resolve_index( + name = "logs-app" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Resolve hidden indexes using a wildcard in a remote cluster + +The following example shows an API request using a wildcard, a remote cluster, and `expand_wildcards` configured to `hidden`: + + +{% capture step1_rest %} +GET /_resolve/index/my-index-*,remote-cluster:my-index-*?expand_wildcards=hidden +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.resolve_index( + name = "my-index-*,remote-cluster:my-index-*", + params = { "expand_wildcards": "hidden" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "indices": [ + { + "name": "my-index-001", + "attributes": [ + "open" + ] + } + ], + "aliases": [], + "data_streams": [] +} +``` + +## Response body fields + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `indices` | Array | A list of resolved concrete indexes. | +| `aliases` | Array | A list of resolved index aliases. | +| `data_streams` | Array | A list of matched data streams. | + +## Required permissions + +If you are using the Security plugin, the user running these queries needs to have at least `read` permissions for the resolved index. diff --git a/_api-reference/index-apis/resume-ingestion.md b/_api-reference/index-apis/resume-ingestion.md new file mode 100644 index 00000000..09287426 --- /dev/null +++ b/_api-reference/index-apis/resume-ingestion.md @@ -0,0 +1,165 @@ +--- +layout: default +title: Resume ingestion +parent: Pull-based ingestion management +grand_parent: Index APIs +nav_order: 20 +--- + +# Resume Ingestion API +**Introduced 3.0** +{: .label .label-purple } + +Resumes ingestion for one or more indexes that were paused using the [Pause Ingestion API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pause-ingestion/). When resumed, OpenSearch continues consuming data from the streaming source for all shards in the specified indexes. + +As part of the resume operation, you can optionally reset the stream consumer to start reading from a specific offset or timestamp. If reset settings are specified, all consumers for the selected shards are reset before the resume operation is applied to the index. Resetting a consumer also triggers an internal flush to persist the changes. + +## Endpoints + +```json +POST /{index}/ingestion/_resume +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `index` | String | Required | The index to resume ingestion for. Can be a comma-separated list of multiple index names. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time units | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. | +| `timeout` | Time units | The amount of time to wait for a response from the cluster. Default is `30s`. | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `reset_settings` | Array of objects | Optional | A list of reset settings, one for each shard to reset. If not provided, OpenSearch resumes ingestion from the current position for each shard in the specified index. See [Reset settings](#reset-settings). | + +### Reset settings + +Each object in the `reset_settings` array contains the following fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `shard` | Integer | Required | The shard to reset. | +| `mode` | String | Required | The reset mode. Valid values are `offset` (a positive integer offset) and `timestamp` (a Unix timestamp in milliseconds). | +| `value` | String | Required |  • `offset`: The Apache Kafka offset or Amazon Kinesis sequence number
 • `timestamp`: A Unix timestamp in milliseconds. | + +## Example request: Resuming ingestion from the current position + +To resume ingestion without specifying reset settings, send the following request: + + +{% capture step1_rest %} +POST /my-index/ingestion/_resume +{% endcapture %} + +{% capture step1_python %} + + +response = client.ingestion.resume( + index = "my-index" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true, + "shards_acknowledged": true +} +``` + +## Example request: Resuming ingestion from a specific offset + +To reset shard `0` to offset `1` when resuming ingestion, send the following request: + + +{% capture step1_rest %} +POST /my-index/ingestion/_resume +{ + "reset_settings": [ + { + "shard": 0, + "mode": "offset", + "value": "1" + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.ingestion.resume( + index = "my-index", + body = { + "reset_settings": [ + { + "shard": 0, + "mode": "offset", + "value": "1" + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | Whether the resume request was acknowledged. | +| `shards_acknowledged` | Boolean | Whether the resume request was acknowledged by the individual shards. | +| `failures` | Array of objects | A list of shard-level failures. See [Failures](#failures). | +| `error` | String | The request-level error message, if any. | + +### Failures + +Each object in the `failures` array contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `shard` | Integer | The shard number. | +| `error` | String | The shard-level error message. | diff --git a/_api-reference/index-apis/rollover.md b/_api-reference/index-apis/rollover.md new file mode 100644 index 00000000..4f4a4eef --- /dev/null +++ b/_api-reference/index-apis/rollover.md @@ -0,0 +1,307 @@ +--- +layout: default +title: Roll over index +parent: Index operations +grand_parent: Index APIs +nav_order: 70 +--- + +# Roll Over Index API +**Introduced 1.0** +{: .label .label-purple } + +The Roll Over Index API creates a new index for a data stream or index alias, either unconditionally or when the current write index meets the specified conditions. + +## Endpoints + +```json +POST /{rollover-target}/_rollover/ +POST /{rollover-target}/_rollover/{target-index} +``` + +## Rollover types + +You can roll over a data stream, an index alias with one index, or an index alias with a write index. + +### Data stream + +When you perform a rollover operation on a data stream, the API generates a fresh write index for that stream. Simultaneously, the stream's preceding write index transforms into a regular backing index. Additionally, the rollover process increments the generation count of the data stream. Data stream rollovers do not support the `target-index` path parameter or the `aliases`, `mappings`, and `settings` request body fields because the data stream names its backing indexes and its index template configures them. + +### Index alias with one index + +When initiating a rollover on an index alias associated with a single index, the API generates a new index and disassociates the original index from the alias. + +### Index alias with a write index + +When an index alias references multiple indexes, one index must be designated as the write index. During a rollover, the API creates a new write index with its `is_write_index` property set to `true` while updating the previous write index by setting its `is_write_index` property to `false`. + +## Incrementing index names for an alias + +During the index alias rollover process, if you don't specify a custom name and the current index's name ends with a hyphen followed by a number (for example, `my-index-000001` or `my-index-3`), then the rollover operation will automatically increment that number for the new index's name. For instance, rolling over `my-index-000001` will generate `my-index-000002`. The numeric portion is always padded with leading zeros to ensure a consistent length of six characters. + +## Using date math with index rollovers + +When using an index alias for time-series data, you can use [date math]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/) in the index name to track the rollover date. For example, you can create an alias pointing to `my-index-{now/d}-000001`. If you create an alias on June 11, 2029, then the index name would be `my-index-2029.06.11-000001`. For a rollover on June 12, 2029, the new index would be named `my-index-2029.06.12-000002`. See [Roll over an index alias with a write index](#rolling-over-an-index-alias-with-a-write-index) for a practical example. For the full date math index name syntax and the characters you must encode in request URLs, see [Date math in index names]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/#date-math-in-index-names). + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`rollover-target` | String | The name of the data stream or index alias to roll over. Required. | +`target-index` | String | The name of the index to create. Supports date math. Data streams do not support this parameter. If the name of the alias's current write index does not end with `-` and a number, such as `my-index-000001` or `my-index-2`, then the parameter is required. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`dry_run` | Boolean | If `true`, OpenSearch checks whether the current index meets the rollover conditions and returns the name of the index that would be created, but does not perform the rollover. Default is `false`. +`timeout` | Time | The amount of time to wait for a response. Default is `30s`. +`wait_for_active_shards` | String | The number of shard copies of the new index that must be active before OpenSearch returns a response. Default is `1` (only the primary shard). You can also set to `all` or a positive integer. Values greater than `1` require replicas. For example, if you specify a value of `3`, then the new index must have two replicas distributed across two additional nodes. The rollover is performed regardless of this setting. If the required shards are not active within the `cluster_manager_timeout` period, then the response contains `"shards_acknowledged": false`. + +## Request body fields + +The following request body fields are supported. + +### `aliases` + +The `aliases` parameter specifies the aliases to add to the new index. It is optional. The `aliases` object is keyed by alias name. Each alias object supports the following optional parameters. + + +Parameter | Type | Description +:--- | :--- | :--- +`filter` | Query DSL object | The query that limits the number of documents that the alias can access. +`index_routing` | String | The value that routes indexing operations to a specific shard. When specified, overwrites the `routing` value for indexing operations. +`is_hidden` | Boolean | Hides or shows the alias. When `true`, the alias is hidden. Default is `false`. Indexes for the alias must have matching values for this setting. +`is_write_index` | Boolean | Specifies the write index. When `true`, the index is the write index for the alias. Default is `false`. +`routing` | String | The value used to route index and search operations to a specific shard. +`search_routing` | String | Routes search operations to a specific shard. When specified, it overwrites `routing` for search operations. + +### `mappings` + +The `mappings` parameter specifies the index field mappings. It is optional. See [Mappings and field types]({{site.url}}{{site.baseurl}}/mappings/) for more information. + +### `conditions` + +The `conditions` parameter is an optional object defining criteria for triggering the rollover. When provided, OpenSearch only rolls over if the current index satisfies one or more specified conditions. If omitted, then the rollover occurs unconditionally without prerequisites. + +The object body supports the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`max_age` | Time units | Triggers a rollover after the maximum elapsed time since index creation is reached. Optional. | +`max_docs` | Integer | Triggers a rollover after the specified maximum number of documents, excluding documents added since the last refresh and documents in replica shards. Optional. +`max_size` | Byte units | Triggers a rollover when the index reaches a specified size, calculated as the total size of all primary shards. Replicas are not counted. Use the `_cat indices` API and check the `pri.store.size` value to see the current index size. Optional. + +### `settings` + +The `settings` parameter specifies the index configuration options. See [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) for more information. + +## Example requests + +The following examples illustrate using the Rollover Index API. A rollover occurs when one or more of the specified conditions are met: + +- The index was created 5 or more days ago. +- The index contains 500 or more documents. +- The index is 100 GB or larger. + +### Rolling over a data stream + +To create a data stream, first create an index template that enables data streams for indexes matching the `my-data-stream*` pattern: + +```json +PUT _index_template/my-data-stream-template +{ + "index_patterns": ["my-data-stream*"], + "data_stream": {} +} +``` +{% include copy-curl.html %} + +Then create the data stream: + +```json +PUT _data_stream/my-data-stream +``` +{% include copy-curl.html %} + +For more information, see [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/). + +The following request rolls over the data stream if the current write index meets any of the specified conditions: + + +{% capture step1_rest %} +POST /my-data-stream/_rollover +{ + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.rollover( + alias = "my-data-stream", + body = { + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Rolling over an index alias with a write index + +The following request creates a date-time index and sets it as the write index for `my-alias`. The index name must be URL encoded: `%3Cmy-index-%7Bnow%2Fd%7D-000001%3E` is the encoded form of ``, and `{now/d}` resolves to the current date: + +```json +PUT %3Cmy-index-%7Bnow%2Fd%7D-000001%3E +{ + "aliases": { + "my-alias": { + "is_write_index": true + } + } +} +``` +{% include copy-curl.html %} + +The next request performs a rollover using the alias: + + +{% capture step1_rest %} +POST /my-alias/_rollover +{ + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.rollover( + alias = "my-alias", + body = { + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Specifying settings during a rollover + +In most cases, you can use an index template to automatically configure the indexes created during a rollover operation. However, when rolling over an index alias, you can use the Rollover Index API to introduce additional index settings or override the settings defined in the template by sending the following request: + + +{% capture step1_rest %} +POST /my-alias/_rollover +{ + "settings": { + "index.number_of_shards": 4 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.rollover( + alias = "my-alias", + body = { + "settings": { + "index.number_of_shards": 4 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +The following example response for the data stream rollover shows that all conditions except `max_size` were met. If the write index is newly created and meets none of the conditions, then the response contains `"rolled_over": false` and OpenSearch does not create the new index: + +```json +{ + "acknowledged": true, + "shards_acknowledged": true, + "old_index": ".ds-my-data-stream-000001", + "new_index": ".ds-my-data-stream-000002", + "rolled_over": true, + "dry_run": false, + "conditions": { + "[max_age: 5d]": true, + "[max_docs: 500]": true, + "[max_size: 100gb]": false + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/rollover`. diff --git a/_api-reference/index-apis/scale.md b/_api-reference/index-apis/scale.md new file mode 100644 index 00000000..0aafa05e --- /dev/null +++ b/_api-reference/index-apis/scale.md @@ -0,0 +1,74 @@ +--- +layout: default +title: Scale +parent: Index operations +grand_parent: Index APIs +nav_order: 80 +--- + +# Scale API +**Introduced 3.0** +{: .label .label-purple } + +The Scale API allows you to enable or disable the `search_only` mode on an index. When an index is in `search_only` mode, it retains only its search replicas and scales down primary and regular replica shards. This optimization helps reduce resource consumption during periods of low write activity while maintaining search capabilities. + +This feature supports scenarios such as scale-to-zero deployments and reader/writer separation patterns, which can significantly improve resource utilization and reduce costs in production environments. + +If you are using the Security plugin, you must have the `manage index` privileges. +{: .note} + +## Endpoints + +```json +POST /{index}/_scale +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the index to scale. Wildcards are not supported. | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `search_only` | **Required** | Boolean | When `true`, enables search-only mode on the index. When `false`, disables search-only mode and restores the index to normal operations. | + +## Example request: Enabling search-only mode + +The following request enables search-only mode for an index named `my-index`: + +```json +POST /my-index/_scale +{ + "search_only": true +} +``` +{% include copy-curl.html %} + +## Example request: Disabling search-only mode + +The following request disables search-only mode and returns the index to normal operations: + +```json +POST /my-index/_scale +{ + "search_only": false +} +``` +{% include copy-curl.html %} + +## Example response + +The API returns the following response: + +```json +{ + "acknowledged": true +} +``` diff --git a/_api-reference/index-apis/segment.md b/_api-reference/index-apis/segment.md new file mode 100644 index 00000000..369b46b3 --- /dev/null +++ b/_api-reference/index-apis/segment.md @@ -0,0 +1,173 @@ +--- +layout: default +title: Index segments +parent: Index operations +grand_parent: Index APIs +nav_order: 90 +--- + +# Index Segments API +**Introduced 1.0** +{: .label .label-purple } + +The Segment API provides details about the Lucene segments within index shards as well as information about the backing indexes of data streams. + + +## Endpoints + +```json +GET /{index}/_segments +GET /_segments +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`index` | String | A comma-separated list of indexes, data streams, or index aliases to which the operation is applied. Supports wildcard expressions (`*`). Use `_all` or `*` to specify all indexes and data streams in a cluster. | + +## Query parameters + +All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. +`expand_wildcards` | String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values. Valid values are `all` (match any index), `open` (match open, non-hidden indexes), `closed` (match closed, non-hidden indexes), `hidden` (match hidden indexes), and `none` (deny wildcard expressions). Default is `open`. +`ignore_unavailable` | Boolean | When `true`, OpenSearch ignores missing or closed indexes. If `false`, OpenSearch returns an error if the force merge operation encounters missing or closed indexes. Default is `false`. +`verbose` | Boolean | When `true`, provides information about Lucene's memory usage. Default is `false`. + + +## Example requests + +The following example requests show you how to use the Segment API. + +### Specific data stream or index + + +{% capture step1_rest %} +GET /index1/_segments +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.segments( + index = "index1" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Several data streams and indexes + + +{% capture step1_rest %} +GET /index1,index2/_segments +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.segments( + index = "index1,index2" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### All data streams and indexes in a cluster + + +{% capture step1_rest %} +GET /_segments +{% endcapture %} + +{% capture step1_python %} + +response = client.indices.segments() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "_shards": ... + "indices": { + "test": { + "shards": { + "0": [ + { + "routing": { + "state": "STARTED", + "primary": true, + "node": "zDC_RorJQCao9xf9pg3Fvw" + }, + "num_committed_segments": 0, + "num_search_segments": 1, + "segments": { + "_0": { + "generation": 0, + "num_docs": 1, + "deleted_docs": 0, + "size_in_bytes": 3800, + "memory_in_bytes": 1410, + "committed": false, + "search": true, + "version": "7.0.0", + "compound": true, + "attributes": { + } + } + } + } + ] + } + } + } +} +``` + +## Response body fields + +Parameter | Data type | Description + :--- | :--- | :--- +`segment` | String | The name of the segment used to create internal file names in the shard directory. +`generation` | Integer | The generation number, such as `0`, incremented for each written segment and used to name the segment. +`num_docs` | Integer | The number of documents, obtained from Lucene. Nested documents are counted separately from their parents. Deleted documents, as well as recently indexed documents that are not yet assigned to a segment, are excluded. +`deleted_docs` | Integer | The number of deleted documents, obtained from Lucene, which may not match the actual number of delete operations performed. Recently deleted documents that are not yet assigned to a segment are excluded. Deleted documents are automatically merged when appropriate. OpenSearch will occasionally delete extra documents in order to track recent shard operations. +`size_in_bytes` | Integer | The amount of disk space used by the segment, for example, `50kb`. +`memory_in_bytes` | Integer | The amount of segment data, measured in bytes, that is kept in memory to facilitate efficient search operations, such as `1264`. A value of `-1` indicates that OpenSearch was unable to compute this number. +`committed` | Boolean | When `true`, the segments are synced to disk. Segments synced to disk can survive a hard reboot. If `false`, then uncommitted segment data is stored in the transaction log as well so that changes can be replayed at the next startup. +`search` | Boolean | When `true`, segment search is enabled. When `false`, the segment may have already been written to disk and require a refresh in order to be searchable. +`version` | String | The Lucene version used to write the segment. +`compound` | Boolean | When `true`, indicates that Lucene merged all segment files into one file in order to save any file descriptions. +`attributes` | Object | Shows if high compression was enabled. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/segments`. diff --git a/_api-reference/index-apis/shard-allocation.md b/_api-reference/index-apis/shard-allocation.md new file mode 100644 index 00000000..e25a0436 --- /dev/null +++ b/_api-reference/index-apis/shard-allocation.md @@ -0,0 +1,129 @@ +--- +layout: default +title: Shard allocation +parent: Index blocks and allocation +grand_parent: Index APIs +nav_order: 20 +--- + +# Shard allocation filtering +**Introduced 1.0** +{: .label .label-purple } + +Shard allocation filtering lets you constrain where shards for an index are placed by matching node attributes. You can use it to pin shards to certain nodes, avoid nodes, or require specific hardware or zones. Shards are only allocated to nodes that satisfy all active filters, including index-level shard allocation filtering and [cluster-level routing awareness]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-awareness/). + +## Endpoints + +```json +PUT /{index}/_settings +GET /{index}/_settings +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`index` | String | One or more comma-separated indexes from which to update or read settings. Use `_all` or `*` to target all indexes. | + +## Built-in and custom attributes + +You can filter on built‑in attributes or any custom node attribute you define. For example, custom attribute can be defined by adding `node.attr.zone: zone-a` in `opensearch.yml`. The following built‑in attributes are supported. + +Attribute | Description +:--- | :--- +`_name` | Match by node name. +`_host_ip` | Match by host IP address. +`_publish_ip` | Match by publish IP address. +`_ip` | Match either `_host_ip` or `_publish_ip`. +`_host` | Match by hostname. +`_id` | Match by node ID. +`_tier` | Match nodes by data tier role. + +## Filter types + +Use the following index settings. + +Setting | Effect +:--- | :--- +`index.routing.allocation.include.` | Allocate shards to nodes that match **any** of the provided values. +`index.routing.allocation.exclude.` | **Do not** allocate shards to nodes that match **any** of the provided values. +`index.routing.allocation.require.` | Allocate shards **only** to nodes that match **all** of the provided values. + +## Example requests + +The following examples demonstrate the different ways to use shard allocation filters. + +### Allocate an index only to a specific zone + +Use the following command to allocate an index to nodes in `zone-a`: + +```json +PUT /test-index/_settings +{ + "index.routing.allocation.require.zone": "zone-a" +} +``` +{% include copy-curl.html %} + +### Allocate to a subset of nodes by IPs + +```json +PUT /test-index/_settings +{ + "index.routing.allocation.include._ip": "10.0.0.12,10.0.0.13" +} +``` +{% include copy-curl.html %} + +### Exclude an index from the node + +The following command excludes an index from node `data-node-3`: + +```json +PUT /test-index/_settings +{ + "index.routing.allocation.exclude._name": "data-node-3" +} +``` +{% include copy-curl.html %} + +### Combine filters + +The following command configures required rack but excludes node `data-node-7`: + +```json +PUT /test-index/_settings +{ + "index": { + "routing.allocation.require.rack": "r1", + "routing.allocation.exclude._name": "data-node-7" + } +} +``` +{% include copy-curl.html %} + +### Clear a filter + +To clear a filter, set its value to `null` or an empty string `""`: + +```json +PUT /test-index/settings +{ + "persistent": { + "index.routing.allocation.exclude._host_ip": null + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "acknowledged": true +} +``` + + diff --git a/_api-reference/index-apis/shard-stores.md b/_api-reference/index-apis/shard-stores.md new file mode 100644 index 00000000..4d67eacd --- /dev/null +++ b/_api-reference/index-apis/shard-stores.md @@ -0,0 +1,175 @@ +--- +layout: default +title: Index shard stores +parent: Index operations +grand_parent: Index APIs +nav_order: 95 +redirect_from: + - /api-reference/cluster-api/shard-stores/ +--- + +# Index Shard Stores API +**Introduced 1.0** +{: .label .label-purple } + +The `_shard_stores` API provides information about the shard copies for one or more indexes. This API helps to diagnose issues with unallocated shards by indicating why shards are unassigned and providing their current states. + +## Endpoints +```json +GET /_shard_stores +GET /{index}/_shard_stores +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | List or String | List of data streams, indexes, and aliases used to limit the request. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| `allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indexes. This behavior applies even if the request targets other open indexes. | `false` | +| `expand_wildcards` | List or String | Type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with open, closed, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | `open` | +| `ignore_unavailable` | Boolean | If `true`, missing or closed indexes are not included in the response. | `false` | +| `status` | List or String | List of shard health statuses used to limit the request.
Valid values are:
- `all`: Return all shards, regardless of health status.
- `green`: The primary shard and all replica shards are assigned.
- `red`: The primary shard is unassigned.
- `yellow`: One or more replica shards are unassigned. | `yellow,red` | + +## Example requests + +Create an index with multiple primary shards on a single-node cluster: + +```json +PUT /logs-shardstore +{ + "settings": { + "number_of_shards": 2, + "number_of_replicas": 0 + }, + "mappings": { + "properties": { + "timestamp": { "type": "date" }, + "message": { "type": "text" } + } + } +} +``` +{% include copy-curl.html %} + +Index a document: + + +{% capture step1_rest %} +POST /logs-shardstore/_doc +{ + "timestamp": "2025-06-20T12:00:00Z", + "message": "Log message 1" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "logs-shardstore", + body = { + "timestamp": "2025-06-20T12:00:00Z", + "message": "Log message 1" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Get shard store status for the `logs-shardstore` index: + + +{% capture step1_rest %} +GET /logs-shardstore/_shard_stores?status=all +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.shard_stores( + index = "logs-shardstore", + params = { "status": "all" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The response lists the stores that were assigned to each shard. If a shard has no assigned stores, it is marked `unassigned`: + +```json +{ + "indices": { + "logs-shardstore": { + "shards": { + "0": { + "stores": [ + { + "UFyVYVMCSDOObiRwPxSW5w": { + "name": "opensearch-node1", + "ephemeral_id": "vkSB_-M7QVyFXvgda6oRZg", + "transport_address": "172.19.0.2:9300", + "attributes": { + "shard_indexing_pressure_enabled": "true" + } + }, + "allocation_id": "PEM5YjEWSz-jJEj-Not6Aw", + "allocation": "primary" + } + ] + }, + "1": { + "stores": [] + } + } + } + } +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description| +| `indices` | Object | Contains shard store information for each index. | +| `indices..shards` | Object | Contains store data for each shard in the index. | +| `shards..stores` | Array | A list of store entries for the shard.| +| `stores[n].` | Object | Node metadata, including name, transport address, and attributes. | +| `stores[n].allocation` | String | The shard role on this node (`primary` or `replica`). | +| `stores[n].allocation_id` | String | The unique allocation ID for this shard copy.| +| `stores[n].store_exception` | Object (optional) | Stores exceptions encountered when reading the shard store. | +| `stores[n].store_exception.type` | String | The type of exception.| +| `stores[n].store_exception.reason` | String | The reason message for the exception.| + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/shard_stores`. diff --git a/_api-reference/index-apis/shrink-index.md b/_api-reference/index-apis/shrink-index.md index 17b7c4df..c5dc4040 100644 --- a/_api-reference/index-apis/shrink-index.md +++ b/_api-reference/index-apis/shrink-index.md @@ -1,42 +1,63 @@ --- layout: default title: Shrink index -parent: Index APIs -nav_order: 65 +parent: Index operations +grand_parent: Index APIs +nav_order: 100 redirect_from: - /opensearch/rest-api/index-apis/shrink-index/ --- -# Shrink index +# Shrink Index API **Introduced 1.0** {: .label .label-purple } -The shrink index API operation moves all of your data in an existing index into a new index with fewer primary shards. +The Shrink Index API reduces the number of primary shards in an existing index by creating a new target index with fewer shards. This is useful when an index was originally over-sharded and you want to reclaim resources or improve search performance by consolidating shards. -## Example +The target index's primary shard count must be a factor of the source index's primary shard count. For example, an index with 8 primary shards can be shrunk into 4, 2, or 1 primary shard. An index with a prime number of shards (such as 7) can only be shrunk into 1 primary shard. + +## Prerequisites + +Before you can shrink an index, it must meet the following conditions: + +- The index must be read-only. To make the index read-only, set the [dynamic index setting]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings) `index.blocks.write` to `true`. +- A copy of every shard in the index (either primary or replica) must reside on the same node. You can use [shard allocation filtering]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shard-allocation/) to move shards to the same node. +- The cluster health status must be green. + +Additionally, the shrink operation enforces the following constraints: + +- The target index must not already exist. +- The source index must have more primary shards than the target index. +- The number of primary shards in the target index must be a factor of the source index's primary shard count. +- The source index must not contain more than 2,147,483,519 documents across all shards that will be merged into a single target shard, because this is the maximum number of documents a single Lucene shard can hold. +- The node handling the shrink process must have sufficient free disk space to accommodate a second copy of the existing index. + +The following request satisfies the first three conditions by routing all shards to a single node and blocking write operations: ```json -POST /my-old-index/_shrink/my-new-index +PUT /catalog-archive/_settings { "settings": { - "index.number_of_replicas": 4, - "index.number_of_shards": 3 - }, - "aliases":{ - "new-index-alias": {} + "index.routing.allocation.require._name": "opensearch-node1", + "index.blocks.write": true } } ``` {% include copy-curl.html %} -## Path and HTTP methods +Shard relocation may take time depending on index size. You can track progress using the [CAT recovery API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/) or wait for completion using the [Cluster Health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) with the `wait_for_no_relocating_shards` parameter. +{: .note} -``` -POST //_shrink/ -PUT //_shrink/ -``` +Mappings cannot be specified in the shrink request. The target index inherits all mappings from the source index. +{: .important} -When creating new indexes with this operation, remember that OpenSearch indexes have the following naming restrictions: +The shrink operation performs three steps: + +1. Creates a new target index that has the same definition as the source index but contains fewer primary shards. +1. Creates hard links from source index segments to the target index. When the file system does not support hard links, segments are physically copied into the new index, which is a much more time-consuming process. +1. Recovers the target index using the same process applied when reopening a closed index. + +When creating the target index, remember that OpenSearch index names have the following restrictions: - All letters must be lowercase. - Index names can't begin with underscores (`_`) or hyphens (`-`). @@ -44,44 +65,209 @@ When creating new indexes with this operation, remember that OpenSearch indexes `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<` -## URL parameters + +## Endpoints +```json +POST /{index}/_shrink/{target} +PUT /{index}/_shrink/{target} +``` + -The shrink index API operation requires you to specify both the source index and the target index. All other parameters are optional. +## Path parameters -Parameter | Type | description -:--- | :--- | :--- -<index-name> | String | The index to shrink. -<target-index> | String | The target index to shrink the source index into. -wait_for_active_shards | String | Specifies the number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for the request to return a response. Default is `30s`. -wait_for_completion | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. Default is `true`. -task_execution_timeout | Time | The explicit task execution timeout. Only useful when wait_for_completion is set to `false`. Default is `1h`. +The following table lists the available path parameters. -## Request body +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the source index to shrink. | +| `target` | **Required** | String | The name of the target index to create. | -You can use the request body to configure some index settings for the target index. All fields are optional. +## Query parameters -Field | Type | Description -:--- | :--- | :--- -alias | Object | Sets an alias for the target index. Can have the fields `filter`, `index_routing`, `is_hidden`, `is_write_index`, `routing`, or `search_routing`. See [Index Aliases]({{site.url}}{{site.baseurl}}/api-reference/alias/#request-body). -settings | Object | Index settings you can apply to your target index. See [Index Settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/). -[max_shard_size](#the-max_shard_size-parameter) | Bytes | Specifies the maximum size of a primary shard in the target index. Because `max_shard_size` conflicts with the `index.number_of_shards` setting, you cannot set both of them at the same time. +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `wait_for_active_shards` | String | The number of active shard copies that must be available before OpenSearch returns a response. Because the shrink operation creates a new index, the [wait for active shards]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/#wait-for-active-shards) setting on index creation applies here as well. Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. | `1` | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | +| `timeout` | String | The amount of time to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. | `30s` | +| `wait_for_completion` | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. | `true` | +| `task_execution_timeout` | String | The amount of time to wait for the task to complete. Only applicable when `wait_for_completion` is set to `false`. | `1h` | + +## Request body fields + +The following table lists the available request body fields. All fields are optional. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `settings` | Object | Index settings to apply to the target index. See [Index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/). | +| `aliases` | Object | Aliases to associate with the target index. See [Alias APIs]({{site.url}}{{site.baseurl}}/api-reference/alias/). | +| `max_shard_size` | String | The maximum size of a primary shard in the target index. OpenSearch calculates the optimal shard count based on total storage and this limit. Cannot be used together with `index.number_of_shards`. See [The `max_shard_size` parameter](#the-max_shard_size-parameter). | ### The `max_shard_size` parameter -The `max_shard_size` parameter specifies the maximum size of a primary shard in the target index. OpenSearch uses `max_shard_size` and the total storage for all primary shards in the source index to calculate the number of primary shards and their size for the target index. +The `max_shard_size` parameter specifies the maximum size of a primary shard in the target index. OpenSearch uses `max_shard_size` and the total storage for all primary shards in the source index to calculate the number of primary shards and their size for the target index. -The primary shard count of the target index is the smallest factor of the source index's primary shard count for which the shard size does not exceed `max_shard_size`. For example, if the source index has 8 primary shards, they occupy a total of 400 GB of storage, and the `max_shard_size` is equal to 150 GB, OpenSearch calculates the number of primary shards in the target index using the following algorithm: +The primary shard count of the target index is the smallest factor of the source index's primary shard count for which the shard size does not exceed `max_shard_size`. For example, if the source index has 8 primary shards that occupy a total of 400 GB of storage and `max_shard_size` is 150 GB, OpenSearch calculates the number of primary shards using the following steps: 1. Calculate the minimum number of primary shards as 400/150, rounded to the nearest whole integer. The minimum number of primary shards is 3. -1. Calculate the number of primary shards as the smallest factor of 8 that is greater than 3. The number of primary shards is 4. +1. Find the smallest factor of 8 that is greater than or equal to 3. The number of primary shards is 4. -The maximum number of primary shards for the target index is equal to the number of primary shards in the source index because the shrink operation is used to reduce the primary shard count. As an example, consider a source index with 5 primary shards that occupy a total of 600 GB of storage. If `max_shard_size` is 100 GB, the minimum number of primary shards is 600/100, which is 6. However, because the number of primary shards in the source index is smaller than 6, the number of primary shards in the target index is set to 5. +The maximum number of primary shards for the target index is equal to the number of primary shards in the source index. For example, if the source index has 5 primary shards that occupy 600 GB and `max_shard_size` is 100 GB, the minimum is 600/100 = 6. Because 6 exceeds the source shard count of 5, the target retains 5 primary shards. The minimum number of primary shards for the target index is 1. {: .note} +## Monitoring the shrink process + +The Shrink Index API returns as soon as the target index has been added to the cluster state---it does not wait for the shrink operation to complete. The shrink process proceeds through the following shard states: + +1. **Unassigned** -- All shards in the target index begin in this state immediately after the API returns. +1. **Initializing** -- Once the primary shard is allocated to the shrink node, it transitions to this state and the data consolidation begins. +1. **Active** -- When the shrink completes, the shard becomes active. OpenSearch then attempts to allocate any configured replicas and may relocate the primary shard to another node for balancing. + +You can track the progress of shard recovery using the [CAT recovery API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/), or use the [Cluster Health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) with `wait_for_status=yellow` to wait until all primary shards have been allocated. + ## Index codec considerations -For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#splits-and-shrinks). \ No newline at end of file +For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#splits-and-shrinks). + +## Example: Shrinking an index + +The following example shrinks the `catalog-archive` index from 4 primary shards into 2, clears the allocation requirement and write block copied from the source, and attaches an alias: + + +{% capture step1_rest %} +POST /catalog-archive/_shrink/catalog-archive-shrunk +{ + "settings": { + "index.number_of_shards": 2, + "index.number_of_replicas": 0, + "index.routing.allocation.require._name": null, + "index.blocks.write": null + }, + "aliases": { + "catalog-current": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.shrink( + index = "catalog-archive", + target = "catalog-archive-shrunk", + body = { + "settings": { + "index.number_of_shards": 2, + "index.number_of_replicas": 0, + "index.routing.allocation.require._name": null, + "index.blocks.write": null + }, + "aliases": { + "catalog-current": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Shrinking using `max_shard_size` + +Instead of specifying an exact shard count, you can let OpenSearch determine the optimal number of shards based on a maximum shard size. The following example shrinks the `catalog-source` index so that no primary shard exceeds 100 MB: + + +{% capture step1_rest %} +POST /catalog-source/_shrink/catalog-source-compact +{ + "max_shard_size": "100mb", + "settings": { + "index.number_of_replicas": 0, + "index.routing.allocation.require._name": null, + "index.blocks.write": null + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.shrink( + index = "catalog-source", + target = "catalog-source-compact", + body = { + "max_shard_size": "100mb", + "settings": { + "index.number_of_replicas": 0, + "index.routing.allocation.require._name": null, + "index.blocks.write": null + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged": true, + "shards_acknowledged": true, + "index": "catalog-archive-shrunk" +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | Indicates whether the request was acknowledged by all relevant nodes in the cluster. | +| `shards_acknowledged` | Boolean | Indicates whether the required number of shard copies were started before the request timed out. | +| `index` | String | The name of the target index that was created. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/resize`. diff --git a/_api-reference/index-apis/simulate-index-template.md b/_api-reference/index-apis/simulate-index-template.md new file mode 100644 index 00000000..0bb0522e --- /dev/null +++ b/_api-reference/index-apis/simulate-index-template.md @@ -0,0 +1,303 @@ +--- +layout: default +title: Simulate index templates +parent: Index templates +grand_parent: Index APIs +nav_order: 50 +--- + +# Simulate Index Templates API +**Introduced 1.0** +{: .label .label-purple } + +You can use the Simulate Index Template API to preview how index templates will be applied to an index or simulate an index template before creating it. + +## Endpoints + +```json +POST /_index_template/_simulate +POST /_index_template/_simulate/{template_name} +POST /_index_template/_simulate_index/{index_name} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `template_name` | String | The name of the index template to simulate. | +| `index_name` | String | The name of the index to use for simulating template resolution. | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `index_patterns` | Array | The index patterns to which the template applies. | +| `template` | Object | The template definition. | +| `template.settings` | Object | The index settings to apply. | +| `template.mappings` | Object | The field mappings to apply. | +| `template.aliases` | Object | The aliases to apply. | +| `priority` | Integer | The template's priority value, used to determine which template is applied when multiple templates match an index. Higher values take precedence. | +| `version` | Integer | The template version. | +| `_meta` | Object | Metadata for the template. | + +### Example request: Simulate a template + +Use the following request to simulate a template without creating it: + + +{% capture step1_rest %} +POST /_index_template/_simulate_index/logs-sim-1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.simulate_index_template( + name = "logs-sim-1" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Simulate a named template + +{% capture step1_rest %} +POST /_index_template/_simulate/template_for_simulation +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.simulate_template( + name = "template_for_simulation" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + +You can simulate a specific template by specifying the name of the template. + +First, create a template named `template_for_simulation` using the following request: + + +{% capture step1_rest %} +PUT /_index_template/template_for_simulation +{ + "index_patterns": [ + "logs-sim-*" + ], + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + }, + "message": { + "type": "text" + }, + "level": { + "type": "keyword" + } + } + } + }, + "priority": 10, + "version": 1, + "_meta": { + "description": "Template used for simulation example", + "owner": "Docs Team" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_index_template( + name = "template_for_simulation", + body = { + "index_patterns": [ + "logs-sim-*" + ], + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + }, + "message": { + "type": "text" + }, + "level": { + "type": "keyword" + } + } + } + }, + "priority": 10, + "version": 1, + "_meta": { + "description": "Template used for simulation example", + "owner": "Docs Team" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can now simulate the template named `template_for_simulation`: + + +{% capture step1_rest %} +POST /_index_template/_simulate/template_for_simulation +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.simulate_template( + name = "template_for_simulation" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Simulate a template on a specific index + +Simulating a template on a specific index name is particularly useful for resolving conflicts or debugging priority issues among templates. +The following request demonstrates how all applicable templates, with overlapping index patterns, will be applied to an index named `logs-sim-1`: + + +{% capture step1_rest %} +POST /_index_template/_simulate_index/logs-sim-1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.simulate_index_template( + name = "logs-sim-1" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "template": { + "settings": { + "index": { + "number_of_shards": "1", + "number_of_replicas": "1" + } + }, + "mappings": { + "properties": { + "level": { + "type": "keyword" + }, + "message": { + "type": "text" + }, + "timestamp": { + "type": "date" + } + } + }, + "aliases": {} + }, + "overlapping": [] +} +``` + +## Response body fields + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `template` | Object | The template applied. | +| `template.settings` | Object | The resolved index settings. | +| `template.mappings` | Object | The resolved field mappings. | +| `template.aliases` | Object | The resolved aliases. | +| `overlapping` | Array | A list of other index templates that match the same index pattern but were not applied. | + +## Required permissions + +If you are using the Security plugin, make sure you have the appropriate permissions: `indices:admin/index_template/simulate`. diff --git a/_api-reference/index-apis/split.md b/_api-reference/index-apis/split.md index 03b2f742..0d11cbb3 100644 --- a/_api-reference/index-apis/split.md +++ b/_api-reference/index-apis/split.md @@ -1,46 +1,76 @@ --- layout: default title: Split index -parent: Index APIs -nav_order: 70 +parent: Index operations +grand_parent: Index APIs +nav_order: 110 redirect_from: - /opensearch/rest-api/index-apis/split/ --- -# Split index +# Split Index API **Introduced 1.0** {: .label .label-purple } -The split index API operation splits an existing read-only index into a new index, cutting each primary shard into some amount of primary shards in the new index. +The Split Index API increases the number of primary shards in an existing index by creating a new target index where each original primary shard is divided into two or more primary shards. This is useful when an index has outgrown its original shard count and needs additional capacity to handle increased data volume or query load. -## Example +The number of primary shards in the target index must be a multiple of the source index's primary shard count. For example, an index with 2 primary shards can be split into 4, 6, 8, or any other multiple of 2. An index with a single primary shard can be split into any number of shards. + +The maximum number of splits an index supports depends on the `index.number_of_routing_shards` setting. This setting defines the total hashing space across which documents are distributed using consistent hashing. Only multiplicative factors are supported because consistent hashing requires each new shard to map to a complete, contiguous subset of the original hash space; incremental resharding (N to N+1) would require rebalancing documents across all shards, which is prohibitively expensive for search-oriented data structures. For example, an index with 2 shards and `number_of_routing_shards` set to 12 (2 x 2 x 3) supports the following split paths: + +- `2` -> `4` -> `12` (split by 2, then by 3) +- `2` -> `6` -> `12` (split by 3, then by 2) +- `2` -> `12` (split by 6) + +When not explicitly configured, `number_of_routing_shards` defaults to a value that permits repeated doubling up to a maximum of 1,024 shards. + +## Prerequisites + +Before you can split an index, it must meet the following conditions: + +- The index must be read-only. To make the index read-only, set the [dynamic index setting]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings) `index.blocks.write` to `true`. +- The cluster health status must be green. + +Additionally, the split operation enforces the following constraints: + +- The target index must not already exist. +- The source index must have fewer primary shards than the target index. +- The number of primary shards in the target index must be a multiple of the source index's primary shard count. +- The node handling the split process must have sufficient free disk space to accommodate a second copy of the existing index. + +The following request makes the `catalog-logs` index read-only to prepare it for splitting: ```json -PUT /sample-index1/_split/split-index1 +PUT /catalog-logs/_settings { "settings": { - "index": { - "number_of_shards": 4, - "number_of_replicas": 2 - } - }, - "aliases": { - "sample-alias1": {} + "index.blocks.write": true } } ``` {% include copy-curl.html %} -## Path and HTTP methods +Mappings cannot be specified in the split request. The target index inherits all mappings from the source index. +{: .important} -``` -POST //_split/ -PUT //_split/ -``` +The split operation performs the following steps: -## Index naming restrictions +1. Allocates a new target index with an identical mapping and configuration but a higher primary shard count. +1. Establishes hard links from the source segments into the target index directory. If the file system lacks hard-link support, a full byte-level copy occurs instead, which takes significantly longer. +1. Runs a rehashing pass that reassigns each document to its correct target shard based on the new routing layout and removes documents that no longer belong. +1. Initiates shard recovery on the target index, similar to the process that runs when a closed index is reopened. -OpenSearch indexes have the following naming restrictions: +## Monitoring the split process + +The split API returns as soon as the target index has been added to the cluster state; it does not wait for the split operation to complete. The split process proceeds through the following shard states: + +1. **Unassigned** -- All shards in the target index begin in this state immediately after the API returns. +1. **Initializing** -- Once the primary shard is allocated to the node, it transitions to this state and the data redistribution begins. +1. **Active** -- When the split completes, the shard becomes active. OpenSearch then attempts to allocate any configured replicas and may relocate the primary shard to another node for balancing. + +You can track the progress of shard recovery using the [CAT recovery API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/), or use the [Cluster Health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) with `wait_for_status=yellow` to wait until all primary shards have been allocated. + +When creating the target index, remember that OpenSearch index names have the following restrictions: - All letters must be lowercase. - Index names can't begin with underscores (`_`) or hyphens (`-`). @@ -48,34 +78,178 @@ OpenSearch indexes have the following naming restrictions: `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<` -## URL parameters - -Your request must include the source and target indexes. All split index parameters are optional. - -Parameter | Type | Description -:--- | :--- | :--- -<source-index> | String | The source index to split. -<target-index> | String | The index to create. -wait_for_active_shards | String | The number of active shards that must be available before OpenSearch processes the request. Default is 1 (only the primary shard). Set to all or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the operation to succeed. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -timeout | Time | How long to wait for the request to return. Default is `30s`. -wait_for_completion | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. Default is `true`. -task_execution_timeout | Time | The explicit task execution timeout. Only useful when wait_for_completion is set to `false`. Default is `1h`. - -## Request body - -The split index API operation creates a new target index, so you can specify any [index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/) and [aliases]({{site.url}}{{site.baseurl}}/opensearch/index-alias/) to apply to the target index. - -## Response - + +## Endpoints ```json -{ - "acknowledged": true, - "shards_acknowledged": true, - "index": "split-index1" -} +POST /{index}/_split/{target} +PUT /{index}/_split/{target} ``` + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `index` | **Required** | String | The name of the source index to split. | +| `target` | **Required** | String | The name of the target index to create. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `wait_for_active_shards` | String | The number of active shard copies that must be available before OpenSearch returns a response. Because the split operation creates a new index, the [wait for active shards]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/#wait-for-active-shards) setting on index creation applies here as well. Set to `all` or a positive integer. Values greater than 1 require replicas. For example, if you specify a value of 3, the index must have two replicas distributed across two additional nodes for the request to succeed. | `1` | +| `cluster_manager_timeout` | String | The amount of time to wait for a connection to the cluster manager node. | `30s` | +| `timeout` | String | The amount of time to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. | `30s` | +| `wait_for_completion` | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. | `true` | +| `task_execution_timeout` | String | The amount of time to wait for the task to complete. Only applicable when `wait_for_completion` is set to `false`. | `1h` | + +## Request body fields + +The following table lists the available request body fields. All fields are optional. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `settings` | Object | Index settings to apply to the target index. See [Index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/). | +| `aliases` | Object | Aliases to associate with the target index. See [Alias APIs]({{site.url}}{{site.baseurl}}/api-reference/alias/). | ## Index codec considerations -For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#splits-and-shrinks). \ No newline at end of file +For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#splits-and-shrinks). + +## Example: Splitting an index + +The following example splits the `catalog-logs` index from 2 primary shards into 4, removes the write block, and attaches an alias: + + +{% capture step1_rest %} +POST /catalog-logs/_split/catalog-logs-split +{ + "settings": { + "index.number_of_shards": 4, + "index.number_of_replicas": 0, + "index.blocks.write": null + }, + "aliases": { + "catalog-logs-current": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.split( + index = "catalog-logs", + target = "catalog-logs-split", + body = { + "settings": { + "index.number_of_shards": 4, + "index.number_of_replicas": 0, + "index.blocks.write": null + }, + "aliases": { + "catalog-logs-current": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Splitting a single-shard index + +An index with a single primary shard can be split into any number of shards. The following example splits the `catalog-events` index from 1 shard into 3: + + +{% capture step1_rest %} +POST /catalog-events/_split/catalog-events-expanded +{ + "settings": { + "index.number_of_shards": 3, + "index.number_of_replicas": 0, + "index.blocks.write": null + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.split( + index = "catalog-events", + target = "catalog-events-expanded", + body = { + "settings": { + "index.number_of_shards": 3, + "index.number_of_replicas": 0, + "index.blocks.write": null + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +```json +{ + "acknowledged" : true, + "shards_acknowledged" : true, + "index" : "catalog-logs-split" +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | Indicates whether the request was acknowledged by all relevant nodes in the cluster. | +| `shards_acknowledged` | Boolean | Indicates whether the required number of shard copies were started before the request timed out. | +| `index` | String | The name of the target index that was created. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/resize`. diff --git a/_api-reference/index-apis/stats.md b/_api-reference/index-apis/stats.md index d1338276..9f1ef9ac 100644 --- a/_api-reference/index-apis/stats.md +++ b/_api-reference/index-apis/stats.md @@ -1,11 +1,12 @@ --- layout: default -title: Stats -parent: Index APIs -nav_order: 72 +title: Index stats +parent: Index operations +grand_parent: Index APIs +nav_order: 120 --- -# Index Stats +# Index Stats API **Introduced 1.0** {: .label .label-purple } @@ -14,13 +15,18 @@ The Index Stats API provides index statistics. For data streams, the API provide When a shard moves to a different node, the shard-level statistics for the shard are cleared. Although the shard is no longer part of the node, the node preserves any node-level statistics to which the shard contributed. {: .note} -## Path and HTTP methods - + +## Endpoints ```json GET /_stats -GET //_stats -GET //_stats/ +GET /{index}/_stats +GET /_stats/{metric} +GET /{index}/_stats/{metric} ``` + ## Path parameters @@ -28,8 +34,8 @@ The following table lists the available path parameters. All path parameters are | Parameter | Data type | Description | | :--- | :--- | :--- | -| `` | String | A comma-separated list of indexes, data streams, or index aliases used to filter results. Supports wildcard expressions. Defaults to `_all` (`*`). -`` | String | A comma-separated list of metric groups that will be included in the response. For valid values, see [Metrics](#metrics). Defaults to all metrics. | +| `index` | String | A comma-separated list of indexes, data streams, or index aliases used to filter results. Supports wildcard expressions. To retrieve statistics for all indexes, use `_all` or `*` or omit this parameter. | +| `metric` | String | A comma-separated list of metric groups to include in the response. For valid values, see [Metrics](#metrics). Defaults to all metrics. | ### Metrics @@ -37,7 +43,7 @@ The following table lists all available metric groups. Metric | Description :--- |:---- -`_all` | Return all statistics. +`_all` | Return all statistics. Cannot be combined with other metrics. `completion` | Completion suggester statistics. `docs` | Returns the number of documents and the number of deleted documents that have not yet been merged. Index refresh operations can affect this statistic. `fielddata` | Field data statistics. @@ -46,9 +52,10 @@ Metric | Description `indexing` | Indexing statistics. `merge` | Merge statistics. `query_cache` | Query cache statistics. +`recovery` | Recovery statistics, including the number of ongoing recoveries in which the shard acts as a source (`current_as_source`) or a target (`current_as_target`) and the recovery throttle time (`throttle_time_in_millis`). `refresh` | Refresh statistics. `request_cache` | Shard request cache statistics. -`search` | Search statistics, including suggest operation statistics. Search operations can be associated with one or more groups. You can include statistics for custom groups by providing a `groups` parameter, which accepts a comma-separated list of group names. To return statistics for all groups, use `_all`. +`search` | Search statistics, including suggest operation statistics. Search operations can be associated with one or more groups. To include statistics for custom groups, provide a comma-separated list of group names in the `groups` query parameter. To return statistics for all groups, use `_all`. If `groups` is set, the `search` object contains a `groups` object with statistics for each group. `segments` | Statistics about memory use of all open segments. If the `include_segment_file_sizes` parameter is `true`, this metric includes the aggregated disk usage of each Lucene index file. `store` | Size of the index in byte units. `translog` | Translog statistics. @@ -64,57 +71,208 @@ Parameter | Data type | Description `fields` | String | A comma-separated list or a wildcard expression specifying fields to include in the statistics. Specifies the default field list if neither `completion_fields` nor `fielddata_fields` is provided. `completion_fields` | String | A comma-separated list or wildcard expression specifying fields to include in field-level `completion` statistics. `fielddata_fields` | String | A comma-separated list or wildcard expression specifying fields to include in field-level `fielddata` statistics. -`forbid_closed_indices` | Boolean | Specifies not to collect statistics for closed indexes. Default is `true`. -`groups` | String | A comma-separated list of search groups to include in the `search` statistics. +`forbid_closed_indices` | Boolean | If `true`, requests that target a closed index or expand wildcards to closed indexes return an error. Set to `false` to return statistics for closed indexes. Default is `true`. +`groups` | String | A comma-separated list of search groups to include in the `search` statistics. Search groups are custom labels assigned to search requests using the `stats` parameter of the [Search API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#search-stats-groups). Use `_all` to return statistics for all groups. `level` | String | Specifies the level used to aggregate statistics. Valid values are:
- `cluster`: Cluster-level statistics.
- `indices`: Index-level statistics.
- `shards`: Shard-level statistics.
Default is `indices`. `include_segment_file_sizes` | Boolean | Specifies whether to report the aggregated disk usage of each Lucene index file. Only applies to `segments` statistics. Default is `false`. -`include_unloaded_segments` | Boolean | Specifies whether to include information from segments that are not loaded into memory. Default is `false`. +`include_unloaded_segments` | Boolean | Specifies whether to include segment statistics for closed indexes, whose segments are not loaded into memory. Applies only if `forbid_closed_indices` is `false`. Default is `false`. +`ignore_unavailable` | Boolean | If `true`, missing or closed indexes are omitted from the response. If `false`, the request returns an error if it targets a missing or closed index. Default is `false`. +`allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value doesn't match any indexes. Default is `true`. +`timeout` | Time | The amount of time to wait for a response from each node. Default is `30s`. -#### Example request: One index +## Example requests -```json +The following example requests show how to use the Index Stats API. + +### One index + +The following example returns index stats for a single index: + + +{% capture step1_rest %} GET /testindex/_stats -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example request: Comma-separated list of indexes +{% capture step1_python %} -```json + +response = client.indices.stats( + index = "testindex" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Comma-separated list of indexes + +The following example returns stats for multiple indexes: + + +{% capture step1_rest %} GET /testindex1,testindex2/_stats -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example request: Wildcard expression +{% capture step1_python %} -```json + +response = client.indices.stats( + index = "testindex1,testindex2" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Wildcard expression + +The following example returns statistics for any index whose name starts with `testindex`: + + +{% capture step1_rest %} GET /testindex*/_stats -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example request: Specific stats +{% capture step1_python %} -```json + +response = client.indices.stats( + index = "testindex*" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Specific stats + +The following example returns index stats related to refresh and flush operations: + + +{% capture step1_rest %} GET /testindex/_stats/refresh,flush -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example request: Expand wildcards +{% capture step1_python %} -```json + +response = client.indices.stats( + metric = "refresh,flush", + index = "testindex" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Expand wildcards + +The following example returns statistics for all open indexes whose names start with `testindex`, including hidden indexes: + + +{% capture step1_rest %} GET /testindex*/_stats?expand_wildcards=open,hidden -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example request: Shard-level statistics +{% capture step1_python %} -```json + +response = client.indices.stats( + index = "testindex*", + params = { "expand_wildcards": "open,hidden" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Shard-level statistics + +The following example returns shard level stats about a test index: + + +{% capture step1_rest %} GET /testindex/_stats?level=shards -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example response +{% capture step1_python %} -By default, the returned statistics are aggregated in the `primaries` and `total` aggregations. The `primaries` aggregation contains statistics for the primary shards. The `total` aggregation contains statistics for both primary and replica shards. The following is an example Index Stats API response: + +response = client.indices.stats( + index = "testindex", + params = { "level": "shards" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Specific search groups + +The following example returns search statistics for the `group1` and `group2` search groups: + + +{% capture step1_rest %} +GET /_stats/search?groups=group1,group2 +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.stats( + metric = "search", + params = { "groups": "group1,group2" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +By default, the returned statistics are split into two groups: `primaries` and `total`. The `primaries` group contains values computed for primary shards only, while the `total` group contains accumulated values across both primary and replica shards. The following is an example Index Stats API response:
@@ -136,12 +294,12 @@ By default, the returned statistics are aggregated in the `primaries` and `total "deleted": 0 }, "store": { - "size_in_bytes": 15531, + "size_in_bytes": 5172, "reserved_in_bytes": 0 }, "indexing": { "index_total": 4, - "index_time_in_millis": 10, + "index_time_in_millis": 1, "index_current": 0, "index_failed": 0, "delete_total": 0, @@ -149,24 +307,35 @@ By default, the returned statistics are aggregated in the `primaries` and `total "delete_current": 0, "noop_update_total": 0, "is_throttled": false, - "throttle_time_in_millis": 0 + "throttle_time_in_millis": 0, + "max_last_index_request_timestamp": 1792186272652 }, "get": { - "total": 0, + "total": 2, + "getTime": "0s", "time_in_millis": 0, - "exists_total": 0, + "exists_total": 1, "exists_time_in_millis": 0, - "missing_total": 0, + "missing_total": 1, "missing_time_in_millis": 0, "current": 0 }, "search": { "open_contexts": 0, - "query_total": 12, - "query_time_in_millis": 11, + "query_total": 3, + "query_time_in_millis": 2, "query_current": 0, - "fetch_total": 12, - "fetch_time_in_millis": 5, + "query_failed": 0, + "concurrent_query_total": 0, + "concurrent_query_time_in_millis": 0, + "concurrent_query_current": 0, + "concurrent_avg_slice_count": 0.0, + "startree_query_total": 0, + "startree_query_time_in_millis": 0, + "startree_query_current": 0, + "startree_query_failed": 0, + "fetch_total": 3, + "fetch_time_in_millis": 0, "fetch_current": 0, "scroll_total": 0, "scroll_time_in_millis": 0, @@ -176,7 +345,8 @@ By default, the returned statistics are aggregated in the `primaries` and `total "point_in_time_current": 0, "suggest_total": 0, "suggest_time_in_millis": 0, - "suggest_current": 0 + "suggest_current": 0, + "search_idle_reactivate_count_total": 0 }, "merges": { "current": 0, @@ -188,23 +358,34 @@ By default, the returned statistics are aggregated in the `primaries` and `total "total_size_in_bytes": 0, "total_stopped_time_in_millis": 0, "total_throttled_time_in_millis": 0, - "total_auto_throttle_in_bytes": 20971520 + "total_auto_throttle_in_bytes": 20971520, + "unreferenced_file_cleanups_performed": 0, + "warmer": { + "total_invocations_count": 0, + "total_time_millis": 0, + "total_failure_count": 0, + "total_bytes_sent": 0, + "total_bytes_received": 0, + "total_send_time_millis": 0, + "total_receive_time_millis": 0, + "ongoing_count": 0 + } }, "refresh": { - "total": 8, - "total_time_in_millis": 58, - "external_total": 7, - "external_total_time_in_millis": 60, + "total": 3, + "total_time_in_millis": 13, + "external_total": 3, + "external_total_time_in_millis": 13, "listeners": 0 }, "flush": { - "total": 1, - "periodic": 1, - "total_time_in_millis": 21 + "total": 0, + "periodic": 0, + "total_time_in_millis": 0 }, "warmer": { "current": 0, - "total": 6, + "total": 2, "total_time_in_millis": 0 }, "query_cache": { @@ -224,7 +405,7 @@ By default, the returned statistics are aggregated in the `primaries` and `total "size_in_bytes": 0 }, "segments": { - "count": 4, + "count": 1, "memory_in_bytes": 0, "terms_memory_in_bytes": 0, "stored_fields_memory_in_bytes": 0, @@ -236,51 +417,56 @@ By default, the returned statistics are aggregated in the `primaries` and `total "version_map_memory_in_bytes": 0, "fixed_bit_set_memory_in_bytes": 0, "max_unsafe_auto_id_timestamp": -1, - "remote_store" : { - "upload" : { - "total_upload_size" : { - "started_bytes" : 152419, - "succeeded_bytes" : 152419, - "failed_bytes" : 0 + "remote_store": { + "upload": { + "total_upload_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "refresh_size_lag" : { - "total_bytes" : 0, - "max_bytes" : 0 + "refresh_size_lag": { + "total_bytes": 0, + "max_bytes": 0 }, - "max_refresh_time_lag_in_millis" : 0, - "total_time_spent_in_millis" : 516, - "pressure" : { - "total_rejections" : 0 + "max_refresh_time_lag_in_millis": 0, + "total_time_spent_in_millis": 0, + "pressure": { + "total_rejections": 0 } }, - "download" : { - "total_download_size" : { - "started_bytes" : 0, - "succeeded_bytes" : 0, - "failed_bytes" : 0 + "download": { + "total_download_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "total_time_spent_in_millis" : 0 + "total_time_spent_in_millis": 0 } }, + "segment_replication": { + "max_bytes_behind": 0, + "total_bytes_behind": 0, + "max_replication_lag": 0 + }, "file_sizes": {} }, "translog": { - "operations": 0, - "size_in_bytes": 55, - "uncommitted_operations": 0, - "uncommitted_size_in_bytes": 55, - "earliest_last_modified_age": 142622215, - "remote_store" : { - "upload" : { - "total_uploads" : { - "started" : 57, - "failed" : 0, - "succeeded" : 57 + "operations": 4, + "size_in_bytes": 363, + "uncommitted_operations": 4, + "uncommitted_size_in_bytes": 363, + "earliest_last_modified_age": 300, + "remote_store": { + "upload": { + "total_uploads": { + "started": 0, + "failed": 0, + "succeeded": 0 }, - "total_upload_size" : { - "started_bytes" : 16830, - "failed_bytes" : 0, - "succeeded_bytes" : 16830 + "total_upload_size": { + "started_bytes": 0, + "failed_bytes": 0, + "succeeded_bytes": 0 } } } @@ -303,12 +489,12 @@ By default, the returned statistics are aggregated in the `primaries` and `total "deleted": 0 }, "store": { - "size_in_bytes": 15531, + "size_in_bytes": 5172, "reserved_in_bytes": 0 }, "indexing": { "index_total": 4, - "index_time_in_millis": 10, + "index_time_in_millis": 1, "index_current": 0, "index_failed": 0, "delete_total": 0, @@ -316,24 +502,35 @@ By default, the returned statistics are aggregated in the `primaries` and `total "delete_current": 0, "noop_update_total": 0, "is_throttled": false, - "throttle_time_in_millis": 0 + "throttle_time_in_millis": 0, + "max_last_index_request_timestamp": 1792186272652 }, "get": { - "total": 0, + "total": 2, + "getTime": "0s", "time_in_millis": 0, - "exists_total": 0, + "exists_total": 1, "exists_time_in_millis": 0, - "missing_total": 0, + "missing_total": 1, "missing_time_in_millis": 0, "current": 0 }, "search": { "open_contexts": 0, - "query_total": 12, - "query_time_in_millis": 11, + "query_total": 3, + "query_time_in_millis": 2, "query_current": 0, - "fetch_total": 12, - "fetch_time_in_millis": 5, + "query_failed": 0, + "concurrent_query_total": 0, + "concurrent_query_time_in_millis": 0, + "concurrent_query_current": 0, + "concurrent_avg_slice_count": 0.0, + "startree_query_total": 0, + "startree_query_time_in_millis": 0, + "startree_query_current": 0, + "startree_query_failed": 0, + "fetch_total": 3, + "fetch_time_in_millis": 0, "fetch_current": 0, "scroll_total": 0, "scroll_time_in_millis": 0, @@ -343,7 +540,8 @@ By default, the returned statistics are aggregated in the `primaries` and `total "point_in_time_current": 0, "suggest_total": 0, "suggest_time_in_millis": 0, - "suggest_current": 0 + "suggest_current": 0, + "search_idle_reactivate_count_total": 0 }, "merges": { "current": 0, @@ -355,23 +553,34 @@ By default, the returned statistics are aggregated in the `primaries` and `total "total_size_in_bytes": 0, "total_stopped_time_in_millis": 0, "total_throttled_time_in_millis": 0, - "total_auto_throttle_in_bytes": 20971520 + "total_auto_throttle_in_bytes": 20971520, + "unreferenced_file_cleanups_performed": 0, + "warmer": { + "total_invocations_count": 0, + "total_time_millis": 0, + "total_failure_count": 0, + "total_bytes_sent": 0, + "total_bytes_received": 0, + "total_send_time_millis": 0, + "total_receive_time_millis": 0, + "ongoing_count": 0 + } }, "refresh": { - "total": 8, - "total_time_in_millis": 58, - "external_total": 7, - "external_total_time_in_millis": 60, + "total": 3, + "total_time_in_millis": 13, + "external_total": 3, + "external_total_time_in_millis": 13, "listeners": 0 }, "flush": { - "total": 1, - "periodic": 1, - "total_time_in_millis": 21 + "total": 0, + "periodic": 0, + "total_time_in_millis": 0 }, "warmer": { "current": 0, - "total": 6, + "total": 2, "total_time_in_millis": 0 }, "query_cache": { @@ -391,7 +600,7 @@ By default, the returned statistics are aggregated in the `primaries` and `total "size_in_bytes": 0 }, "segments": { - "count": 4, + "count": 1, "memory_in_bytes": 0, "terms_memory_in_bytes": 0, "stored_fields_memory_in_bytes": 0, @@ -403,51 +612,56 @@ By default, the returned statistics are aggregated in the `primaries` and `total "version_map_memory_in_bytes": 0, "fixed_bit_set_memory_in_bytes": 0, "max_unsafe_auto_id_timestamp": -1, - "remote_store" : { - "upload" : { - "total_upload_size" : { - "started_bytes" : 152419, - "succeeded_bytes" : 152419, - "failed_bytes" : 0 + "remote_store": { + "upload": { + "total_upload_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "refresh_size_lag" : { - "total_bytes" : 0, - "max_bytes" : 0 + "refresh_size_lag": { + "total_bytes": 0, + "max_bytes": 0 }, - "max_refresh_time_lag_in_millis" : 0, - "total_time_spent_in_millis" : 516, - "pressure" : { - "total_rejections" : 0 + "max_refresh_time_lag_in_millis": 0, + "total_time_spent_in_millis": 0, + "pressure": { + "total_rejections": 0 } }, - "download" : { - "total_download_size" : { - "started_bytes" : 0, - "succeeded_bytes" : 0, - "failed_bytes" : 0 + "download": { + "total_download_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "total_time_spent_in_millis" : 0 + "total_time_spent_in_millis": 0 } }, + "segment_replication": { + "max_bytes_behind": 0, + "total_bytes_behind": 0, + "max_replication_lag": 0 + }, "file_sizes": {} }, "translog": { - "operations": 0, - "size_in_bytes": 55, - "uncommitted_operations": 0, - "uncommitted_size_in_bytes": 55, - "earliest_last_modified_age": 142622215, - "remote_store" : { - "upload" : { - "total_uploads" : { - "started" : 57, - "failed" : 0, - "succeeded" : 57 + "operations": 4, + "size_in_bytes": 363, + "uncommitted_operations": 4, + "uncommitted_size_in_bytes": 363, + "earliest_last_modified_age": 300, + "remote_store": { + "upload": { + "total_uploads": { + "started": 0, + "failed": 0, + "succeeded": 0 }, - "total_upload_size" : { - "started_bytes" : 16830, - "failed_bytes" : 0, - "succeeded_bytes" : 16830 + "total_upload_size": { + "started_bytes": 0, + "failed_bytes": 0, + "succeeded_bytes": 0 } } } @@ -467,19 +681,19 @@ By default, the returned statistics are aggregated in the `primaries` and `total }, "indices": { "testindex": { - "uuid": "0SXXSpe9Rp-FpxXXWLOD8Q", + "uuid": "fnaTkGq4QIqB__mdUzGqiw", "primaries": { "docs": { "count": 4, "deleted": 0 }, "store": { - "size_in_bytes": 15531, + "size_in_bytes": 5172, "reserved_in_bytes": 0 }, "indexing": { "index_total": 4, - "index_time_in_millis": 10, + "index_time_in_millis": 1, "index_current": 0, "index_failed": 0, "delete_total": 0, @@ -487,24 +701,35 @@ By default, the returned statistics are aggregated in the `primaries` and `total "delete_current": 0, "noop_update_total": 0, "is_throttled": false, - "throttle_time_in_millis": 0 + "throttle_time_in_millis": 0, + "max_last_index_request_timestamp": 1792186272652 }, "get": { - "total": 0, + "total": 2, + "getTime": "0s", "time_in_millis": 0, - "exists_total": 0, + "exists_total": 1, "exists_time_in_millis": 0, - "missing_total": 0, + "missing_total": 1, "missing_time_in_millis": 0, "current": 0 }, "search": { "open_contexts": 0, - "query_total": 12, - "query_time_in_millis": 11, + "query_total": 3, + "query_time_in_millis": 2, "query_current": 0, - "fetch_total": 12, - "fetch_time_in_millis": 5, + "query_failed": 0, + "concurrent_query_total": 0, + "concurrent_query_time_in_millis": 0, + "concurrent_query_current": 0, + "concurrent_avg_slice_count": 0.0, + "startree_query_total": 0, + "startree_query_time_in_millis": 0, + "startree_query_current": 0, + "startree_query_failed": 0, + "fetch_total": 3, + "fetch_time_in_millis": 0, "fetch_current": 0, "scroll_total": 0, "scroll_time_in_millis": 0, @@ -514,7 +739,8 @@ By default, the returned statistics are aggregated in the `primaries` and `total "point_in_time_current": 0, "suggest_total": 0, "suggest_time_in_millis": 0, - "suggest_current": 0 + "suggest_current": 0, + "search_idle_reactivate_count_total": 0 }, "merges": { "current": 0, @@ -526,23 +752,34 @@ By default, the returned statistics are aggregated in the `primaries` and `total "total_size_in_bytes": 0, "total_stopped_time_in_millis": 0, "total_throttled_time_in_millis": 0, - "total_auto_throttle_in_bytes": 20971520 + "total_auto_throttle_in_bytes": 20971520, + "unreferenced_file_cleanups_performed": 0, + "warmer": { + "total_invocations_count": 0, + "total_time_millis": 0, + "total_failure_count": 0, + "total_bytes_sent": 0, + "total_bytes_received": 0, + "total_send_time_millis": 0, + "total_receive_time_millis": 0, + "ongoing_count": 0 + } }, "refresh": { - "total": 8, - "total_time_in_millis": 58, - "external_total": 7, - "external_total_time_in_millis": 60, + "total": 3, + "total_time_in_millis": 13, + "external_total": 3, + "external_total_time_in_millis": 13, "listeners": 0 }, "flush": { - "total": 1, - "periodic": 1, - "total_time_in_millis": 21 + "total": 0, + "periodic": 0, + "total_time_in_millis": 0 }, "warmer": { "current": 0, - "total": 6, + "total": 2, "total_time_in_millis": 0 }, "query_cache": { @@ -562,7 +799,7 @@ By default, the returned statistics are aggregated in the `primaries` and `total "size_in_bytes": 0 }, "segments": { - "count": 4, + "count": 1, "memory_in_bytes": 0, "terms_memory_in_bytes": 0, "stored_fields_memory_in_bytes": 0, @@ -574,51 +811,56 @@ By default, the returned statistics are aggregated in the `primaries` and `total "version_map_memory_in_bytes": 0, "fixed_bit_set_memory_in_bytes": 0, "max_unsafe_auto_id_timestamp": -1, - "remote_store" : { - "upload" : { - "total_upload_size" : { - "started_bytes" : 152419, - "succeeded_bytes" : 152419, - "failed_bytes" : 0 + "remote_store": { + "upload": { + "total_upload_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "refresh_size_lag" : { - "total_bytes" : 0, - "max_bytes" : 0 + "refresh_size_lag": { + "total_bytes": 0, + "max_bytes": 0 }, - "max_refresh_time_lag_in_millis" : 0, - "total_time_spent_in_millis" : 516, - "pressure" : { - "total_rejections" : 0 + "max_refresh_time_lag_in_millis": 0, + "total_time_spent_in_millis": 0, + "pressure": { + "total_rejections": 0 } }, - "download" : { - "total_download_size" : { - "started_bytes" : 0, - "succeeded_bytes" : 0, - "failed_bytes" : 0 + "download": { + "total_download_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "total_time_spent_in_millis" : 0 + "total_time_spent_in_millis": 0 } }, + "segment_replication": { + "max_bytes_behind": 0, + "total_bytes_behind": 0, + "max_replication_lag": 0 + }, "file_sizes": {} }, "translog": { - "operations": 0, - "size_in_bytes": 55, - "uncommitted_operations": 0, - "uncommitted_size_in_bytes": 55, - "earliest_last_modified_age": 142622215, - "remote_store" : { - "upload" : { - "total_uploads" : { - "started" : 57, - "failed" : 0, - "succeeded" : 57 + "operations": 4, + "size_in_bytes": 363, + "uncommitted_operations": 4, + "uncommitted_size_in_bytes": 363, + "earliest_last_modified_age": 300, + "remote_store": { + "upload": { + "total_uploads": { + "started": 0, + "failed": 0, + "succeeded": 0 }, - "total_upload_size" : { - "started_bytes" : 16830, - "failed_bytes" : 0, - "succeeded_bytes" : 16830 + "total_upload_size": { + "started_bytes": 0, + "failed_bytes": 0, + "succeeded_bytes": 0 } } } @@ -641,12 +883,12 @@ By default, the returned statistics are aggregated in the `primaries` and `total "deleted": 0 }, "store": { - "size_in_bytes": 15531, + "size_in_bytes": 5172, "reserved_in_bytes": 0 }, "indexing": { "index_total": 4, - "index_time_in_millis": 10, + "index_time_in_millis": 1, "index_current": 0, "index_failed": 0, "delete_total": 0, @@ -654,24 +896,35 @@ By default, the returned statistics are aggregated in the `primaries` and `total "delete_current": 0, "noop_update_total": 0, "is_throttled": false, - "throttle_time_in_millis": 0 + "throttle_time_in_millis": 0, + "max_last_index_request_timestamp": 1792186272652 }, "get": { - "total": 0, + "total": 2, + "getTime": "0s", "time_in_millis": 0, - "exists_total": 0, + "exists_total": 1, "exists_time_in_millis": 0, - "missing_total": 0, + "missing_total": 1, "missing_time_in_millis": 0, "current": 0 }, "search": { "open_contexts": 0, - "query_total": 12, - "query_time_in_millis": 11, + "query_total": 3, + "query_time_in_millis": 2, "query_current": 0, - "fetch_total": 12, - "fetch_time_in_millis": 5, + "query_failed": 0, + "concurrent_query_total": 0, + "concurrent_query_time_in_millis": 0, + "concurrent_query_current": 0, + "concurrent_avg_slice_count": 0.0, + "startree_query_total": 0, + "startree_query_time_in_millis": 0, + "startree_query_current": 0, + "startree_query_failed": 0, + "fetch_total": 3, + "fetch_time_in_millis": 0, "fetch_current": 0, "scroll_total": 0, "scroll_time_in_millis": 0, @@ -681,7 +934,8 @@ By default, the returned statistics are aggregated in the `primaries` and `total "point_in_time_current": 0, "suggest_total": 0, "suggest_time_in_millis": 0, - "suggest_current": 0 + "suggest_current": 0, + "search_idle_reactivate_count_total": 0 }, "merges": { "current": 0, @@ -693,23 +947,34 @@ By default, the returned statistics are aggregated in the `primaries` and `total "total_size_in_bytes": 0, "total_stopped_time_in_millis": 0, "total_throttled_time_in_millis": 0, - "total_auto_throttle_in_bytes": 20971520 + "total_auto_throttle_in_bytes": 20971520, + "unreferenced_file_cleanups_performed": 0, + "warmer": { + "total_invocations_count": 0, + "total_time_millis": 0, + "total_failure_count": 0, + "total_bytes_sent": 0, + "total_bytes_received": 0, + "total_send_time_millis": 0, + "total_receive_time_millis": 0, + "ongoing_count": 0 + } }, "refresh": { - "total": 8, - "total_time_in_millis": 58, - "external_total": 7, - "external_total_time_in_millis": 60, + "total": 3, + "total_time_in_millis": 13, + "external_total": 3, + "external_total_time_in_millis": 13, "listeners": 0 }, "flush": { - "total": 1, - "periodic": 1, - "total_time_in_millis": 21 + "total": 0, + "periodic": 0, + "total_time_in_millis": 0 }, "warmer": { "current": 0, - "total": 6, + "total": 2, "total_time_in_millis": 0 }, "query_cache": { @@ -729,7 +994,7 @@ By default, the returned statistics are aggregated in the `primaries` and `total "size_in_bytes": 0 }, "segments": { - "count": 4, + "count": 1, "memory_in_bytes": 0, "terms_memory_in_bytes": 0, "stored_fields_memory_in_bytes": 0, @@ -741,51 +1006,56 @@ By default, the returned statistics are aggregated in the `primaries` and `total "version_map_memory_in_bytes": 0, "fixed_bit_set_memory_in_bytes": 0, "max_unsafe_auto_id_timestamp": -1, - "remote_store" : { - "upload" : { - "total_upload_size" : { - "started_bytes" : 152419, - "succeeded_bytes" : 152419, - "failed_bytes" : 0 + "remote_store": { + "upload": { + "total_upload_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "refresh_size_lag" : { - "total_bytes" : 0, - "max_bytes" : 0 + "refresh_size_lag": { + "total_bytes": 0, + "max_bytes": 0 }, - "max_refresh_time_lag_in_millis" : 0, - "total_time_spent_in_millis" : 516, - "pressure" : { - "total_rejections" : 0 + "max_refresh_time_lag_in_millis": 0, + "total_time_spent_in_millis": 0, + "pressure": { + "total_rejections": 0 } }, - "download" : { - "total_download_size" : { - "started_bytes" : 0, - "succeeded_bytes" : 0, - "failed_bytes" : 0 + "download": { + "total_download_size": { + "started_bytes": 0, + "succeeded_bytes": 0, + "failed_bytes": 0 }, - "total_time_spent_in_millis" : 0 + "total_time_spent_in_millis": 0 } }, + "segment_replication": { + "max_bytes_behind": 0, + "total_bytes_behind": 0, + "max_replication_lag": 0 + }, "file_sizes": {} }, "translog": { - "operations": 0, - "size_in_bytes": 55, - "uncommitted_operations": 0, - "uncommitted_size_in_bytes": 55, - "earliest_last_modified_age": 142622215, - "remote_store" : { - "upload" : { - "total_uploads" : { - "started" : 57, - "failed" : 0, - "succeeded" : 57 + "operations": 4, + "size_in_bytes": 363, + "uncommitted_operations": 4, + "uncommitted_size_in_bytes": 363, + "earliest_last_modified_age": 300, + "remote_store": { + "upload": { + "total_uploads": { + "started": 0, + "failed": 0, + "succeeded": 0 }, - "total_upload_size" : { - "started_bytes" : 16830, - "failed_bytes" : 0, - "succeeded_bytes" : 16830 + "total_upload_size": { + "started_bytes": 0, + "failed_bytes": 0, + "succeeded_bytes": 0 } } } @@ -808,6 +1078,86 @@ By default, the returned statistics are aggregated in the `primaries` and `total ```
-## Response fields +## Response body fields -For information about response fields, see [Nodes Stats API response fields]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/#indices). +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_shards` | Object | Contains the `total`, `successful`, and `failed` shard counts for the request. | +| `_all` | Object | Statistics aggregated across all indexes that match the request. | +| `indices` | Object | Statistics for each index that matches the request, keyed by index name. Not returned if `level` is `cluster`. | + +The `_all` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `primaries` | Object | Statistics computed for primary shards only. | +| `total` | Object | Statistics accumulated across primary and replica shards. | + +Each object in `indices` contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `uuid` | String | The universally unique identifier (UUID) of the index. | +| `primaries` | Object | Statistics for the index computed for primary shards only. | +| `total` | Object | Statistics for the index accumulated across primary and replica shards. | +| `shards` | Object | Statistics for each shard of the index, keyed by shard number. Each key contains an array of shard copy objects. Returned only if `level` is `shards`. | + +Each shard copy object in `shards` contains the statistic groups for that shard copy and the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `routing` | Object | Routing information for the shard copy. | +| `commit` | Object | Information about the last Lucene commit for the shard copy. | +| `seq_no` | Object | Sequence number information for the shard copy. | +| `retention_leases` | Object | The retention leases for the shard copy. | +| `shard_path` | Object | The file system paths for the shard copy. | + +The `routing` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `state` | String | The state of the shard copy, such as `STARTED` or `RELOCATING`. | +| `primary` | Boolean | Whether the shard copy is a primary shard. | +| `node` | String | The ID of the node that holds the shard copy. | +| `relocating_node` | String | The ID of the node to which the shard copy is relocating, or `null` if the shard copy is not relocating. | + +The `commit` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `id` | String | The ID of the commit. | +| `generation` | Integer | The generation number of the commit. | +| `user_data` | Object | Metadata stored with the commit, such as the translog UUID and the local checkpoint at the time of the commit. | +| `num_docs` | Integer | The number of documents in the commit. | + +The `seq_no` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `max_seq_no` | Integer | The highest sequence number issued for the shard copy. | +| `local_checkpoint` | Integer | The highest sequence number for which the shard copy has processed all operations. | +| `global_checkpoint` | Integer | The highest sequence number that all active shard copies have processed. | + +The `retention_leases` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `primary_term` | Integer | The primary term of the shard. | +| `version` | Integer | The version of the retention lease collection. | +| `leases` | Array of objects | The retention leases. Each lease contains the `id`, `retaining_seq_no`, `timestamp`, and `source` fields. | + +The `shard_path` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `state_path` | String | The path to the node data directory that stores the shard state. | +| `data_path` | String | The path to the node data directory that stores the shard data. | +| `is_custom_data_path` | Boolean | Whether the index uses a custom data path. | + +For information about the fields in each statistic group, such as `docs`, `indexing`, and `search`, see [Nodes Stats API response fields]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/#indices). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:monitor/stats`. diff --git a/_api-reference/index-apis/template-exists-legacy.md b/_api-reference/index-apis/template-exists-legacy.md new file mode 100644 index 00000000..6b9c7bf6 --- /dev/null +++ b/_api-reference/index-apis/template-exists-legacy.md @@ -0,0 +1,69 @@ +--- +layout: default +title: Template exists (deprecated) +parent: Index templates +grand_parent: Index APIs +nav_order: 100 +--- + +# Template exists +**Introduced 1.0** +{: .label .label-purple } + +The Template Exists API has been deprecated. Use the new [Index Template Exists]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-template-exists/) API. +{: .warning} + +The template exists API operation is used to verify whether one or more index templates created using the legacy `/_template` endpoint exist. + +## Endpoints + +```json +HEAD /_template/{template-name} +``` + +## Path parameters + +The following table lists the available path parameters. All parameters are required. + +| Parameter | Type | Description | +| :-------------- | :----- | :------------------------------------------------------------------------------- | +| `template-name` | String | The name of the index template to check. Accepts wildcard expressions. | + +## Query parameters + +The following table lists the available query parameters. All parameters are optional. + +| Parameter | Type | Description | +| :------------------------- | :------ | :--------------------------------------------------------------------------------------------------- | +| `flat_settings` | Boolean | If `true`, returns settings in flat format. Default is `false`. | +| `local` | Boolean | If `true`, the request does not retrieve the state from the cluster manager node. Default is `false`. | +| `cluster_manager_timeout` | Time | Specifies how long to wait for a connection to the cluster manager node. Default is `30s`. | + +## Example request + + +{% capture step1_rest %} +HEAD /_template/logging_template +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.exists_template( + name = "logging_template" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +If the template exists, a `200 OK` status is returned with no response body. If the template does not exist, `404 Not Found` is returned. + diff --git a/_api-reference/index-apis/update-settings.md b/_api-reference/index-apis/update-settings.md index 3f38418e..7919b04d 100644 --- a/_api-reference/index-apis/update-settings.md +++ b/_api-reference/index-apis/update-settings.md @@ -1,68 +1,191 @@ --- layout: default title: Update settings -parent: Index APIs -nav_order: 75 +parent: Index settings and mappings +grand_parent: Index APIs +nav_order: 20 redirect_from: - /opensearch/rest-api/index-apis/update-settings/ --- -# Update settings +# Update Index Settings API **Introduced 1.0** {: .label .label-purple } -You can use the update settings API operation to update index-level settings. You can change dynamic index settings at any time, but static settings cannot be changed after index creation. For more information about static and dynamic index settings, see [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). +The Update Index Settings API changes index-level settings in real time. You can update dynamic index settings at any time. You can update static index settings only on a closed index, and you cannot update final static settings, such as `index.number_of_shards`, after index creation. For more information about static and dynamic index settings, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). -Aside from the static and dynamic index settings, you can also update individual plugins' settings. To get the full list of updatable settings, run `GET /_settings?include_defaults=true`. +In addition to the built-in index settings, you can also update settings for individual plugins. To retrieve a complete list of all available settings, including default values, run `GET /_settings?include_defaults=true`. -## Example +The API updates settings only on existing indexes and does not create an index. Each setting in the request body is applied whether or not it was previously set on the index. To leave settings that already have a value unchanged and apply only the settings that are not yet set, specify `preserve_existing=true`. To reset a setting to its default value, set it to `null`. For more information, see [Resetting a setting to its default value](#example-request-resetting-a-setting-to-its-default-value). +If the request contains any setting that cannot be updated, the entire request is rejected and no settings are changed. + + +## Endpoints + + ```json -PUT /sample-index1/_settings -{ - "index.plugins.index_state_management.rollover_skip": true, - "index": { - "number_of_replicas": 4 - } -} +PUT /{index}/_settings ``` -{% include copy-curl.html %} + -## Path and HTTP methods +## Path parameters -``` -PUT //_settings -``` - -## Query parameters - -All update settings parameters are optional. +The following table lists the available path parameters. All path parameters are optional. Parameter | Data type | Description :--- | :--- | :--- -allow_no_indices | Boolean | Whether to ignore wildcards that don’t match any indexes. Default is `true`. -expand_wildcards | String | Expands wildcard expressions to different indexes. Combine multiple values with commas. Available values are `all` (match all indexes), `open` (match open indexes), `closed` (match closed indexes), `hidden` (match hidden indexes), and `none` (do not accept wildcard expressions), which must be used with `open`, `closed`, or both. Default is `open`. -cluster_manager_timeout | Time | How long to wait for a connection to the cluster manager node. Default is `30s`. -preserve_existing | Boolean | Whether to preserve existing index settings. Default is false. -timeout | Time | How long to wait for a connection to return. Default is `30s`. +`index` | String | The name of the index to update. You can specify a single index name, a comma-separated list of index names, or a wildcard expression. Use `_all` or `*` to update settings for all indexes in the cluster. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`allow_no_indices` | Boolean | Specifies whether to ignore wildcard expressions or index patterns that don’t match any indexes. When `false`, the request returns an error if a wildcard expression doesn’t match any indexes. When `true`, the request ignores missing indexes and updates only the settings for indexes that exist. Default is `false`. +`expand_wildcards` | String | Specifies the types of indexes to which wildcard expressions can expand. Supports comma-separated values. Valid values are `all` (all indexes), `open` (open indexes), `closed` (closed indexes), `hidden` (hidden indexes), and `none` (wildcard expressions are not accepted). Default is `open`. +`flat_settings` | Boolean | Specifies whether to return settings in flat format. When `true`, settings are returned in a flattened format. When `false`, settings are returned in nested format. Default is `false`. +`ignore_unavailable` | Boolean | Specifies whether to ignore indexes that are missing or closed. When `true`, the request does not return an error if the target index is missing or closed. When `false`, the request returns an error if the target index is unavailable. Default is `false`. +`preserve_existing` | Boolean | Specifies whether to preserve existing index settings. When `true`, existing settings remain unchanged and only new settings are applied. When `false`, the request updates existing settings with the provided values. Default is `false`. +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time to wait for a response. Default is `30s`. ## Request body -The request body must all of the index settings that you want to update. +The request body contains the index settings you want to update. You can specify settings in either flat or nested format. + +Field | Data type | Description +:--- | :--- | :--- +`settings` | Object | An object containing the index settings to update. For a list of available index settings, see [Index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/). + +## Example request: Updating settings for a single index + +The following example updates settings for the `books` index: + + +{% capture step1_rest %} +PUT /books/_settings +{ + "index": { + "number_of_replicas": 2 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_settings( + index = "books", + body = { + "index": { + "number_of_replicas": 2 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example request: Resetting a setting to its default value + +To revert a setting to its default value, specify `null` as the value: ```json +PUT /books/_settings { - "index.plugins.index_state_management.rollover_skip": true, "index": { - "number_of_replicas": 4 + "refresh_interval": null } } ``` +{% include copy.html %} -## Response +## Example request: Updating settings for multiple indexes + +The following example updates settings for multiple indexes: + +```json +PUT /books,products/_settings +{ + "index": { + "number_of_replicas": 0 + } +} +``` +{% include copy.html %} + +## Example request: Optimizing for bulk indexing + +To optimize an index for bulk indexing operations, disable the refresh interval by setting it to `-1`. After bulk indexing is complete, reenable it by setting it back to a positive value: + +```json +PUT /books/_settings +{ + "index": { + "refresh_interval": "-1" + } +} +``` +{% include copy.html %} + +After completing bulk indexing, restore the refresh interval: + +```json +PUT /books/_settings +{ + "index": { + "refresh_interval": "1s" + } +} +``` +{% include copy.html %} + +## Example response ```json { - "acknowledged": true + "acknowledged": true } ``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`acknowledged` | Boolean | Indicates whether the update request was received. A value of `true` indicates that the request was received. This does not guarantee that the settings were applied. + +## Status codes + +The following table lists the HTTP status codes that the API returns. + +Status code | Error type | Description +:--- | :--- | :--- +`200` | None | The request succeeded. The response contains `"acknowledged": true`. +`400` | `settings_exception` | The request contains an unknown setting name or attempts to update a final setting, such as `index.number_of_shards`, on a closed index. +`400` | `illegal_argument_exception` | The request contains an invalid setting value or attempts to update a static setting on an open index. +`400` | `parse_exception` | The request body is missing. +`400` | A JSON parsing error, such as `unexpected_end_of_input_exception` | The request body is not valid JSON. +`404` | `index_not_found_exception` | A target index does not exist or a wildcard expression does not match any indexes. To ignore missing indexes, set `ignore_unavailable` to `true`. To ignore wildcard expressions that do not match any indexes, or when no target index exists, also set `allow_no_indices` to `true`. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/settings/update`. diff --git a/_api-reference/index-name-syntax.md b/_api-reference/index-name-syntax.md new file mode 100644 index 00000000..22a7f0f3 --- /dev/null +++ b/_api-reference/index-name-syntax.md @@ -0,0 +1,125 @@ +--- +layout: default +title: Index name syntax +nav_order: 155 +--- + +# Index name syntax + +Many OpenSearch REST APIs accept one or more index names in the request path. You can target several indexes in one request, select indexes by date using date math, and prevent requests from specifying indexes in the request body. + +## Targeting multiple indexes + +Most APIs that accept an index name in the path can run on several indexes at once. Specify the target indexes in one of the following ways: + +- A comma-separated list of names, for example, `app-logs-2026.10.12,app-logs-2026.10.13`. +- A wildcard pattern, for example, `app-logs-*` or `*-logs-*`. +- `_all` or `*` to target all indexes. +- An exclusion, which removes indexes from the preceding patterns. Prefix the name or pattern with `-`, for example, `app-logs-*,-app-logs-2026.10.11`. An exclusion must follow at least one inclusive name or pattern. A path containing only `-app-logs-2026.10.11` is interpreted as the literal index name `-app-logs-2026.10.11`. + +The following request counts the documents in all `app-logs-` indexes created in 2026, except `app-logs-2026.10.11`: + +```json +GET /app-logs-2026*,-app-logs-2026.10.11/_count +``` +{% include copy-curl.html %} + +APIs that operate on a single document or a single index, such as the [Index Document API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index-document/), do not accept multiple indexes. A comma-separated list in the path of these APIs is rejected as an invalid index name. + +APIs that support multiple indexes accept the following query parameters, which control how OpenSearch resolves the target indexes. The default values depend on the API. + +Parameter | Data type | Description +:--- | :--- | :--- +`ignore_unavailable` | Boolean | If `true`, OpenSearch ignores missing or closed indexes listed by name. If `false`, a request that names a missing or closed index fails. +`allow_no_indices` | Boolean | If `true`, the request succeeds when a wildcard pattern, an alias, or `_all` matches no indexes. If `false`, the request fails. For example, with the default `true`, a Count API request for `nomatch-*` returns a count of `0`. +`expand_wildcards` | String | The types of indexes that wildcard patterns can match. Accepts a comma-separated list of the following values:
- `open`: Open indexes.
- `closed`: Closed indexes.
- `hidden`: Hidden indexes, which have the [`index.hidden`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) setting enabled. Must be combined with `open`, `closed`, or both.
- `all`: All indexes, including hidden indexes.
- `none`: No indexes. Wildcard patterns are not expanded.

For most APIs, the default is `open`, so wildcard patterns do not match hidden indexes, such as indexes whose names start with `.`. Specify `expand_wildcards=open,hidden` to include them. + +## Date math in index names + +If you create one index per day or month for time-series data, you can use date math in the request path to select indexes by their date. For example, a request can target only this month's and last month's sales indexes without your client calculating their names, and OpenSearch reads only those indexes. Most APIs that accept an index name in the path support date math. For example, you can use date math to name the indexes created by a rollover. For more information, see [Using date math with index rollovers]({{site.url}}{{site.baseurl}}/api-reference/index-apis/rollover/#using-date-math-with-index-rollovers). + +A date math index name has the following format: + +``` + +``` + +The following table describes the components of a date math index name. + +Component | Description +:--- | :--- +`static_name` | The fixed part of the name, for example, `app-logs-`. +`date_math_expression` | An expression that calculates a date relative to `now`, for example, `now/d` (today rounded down to the start of the day) or `now/d-1d` (yesterday). For the expression syntax, see [Date math]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#date-math). +`date_format` | Optional. The format in which the calculated date is written into the index name. Default is `yyyy.MM.dd`. Format patterns are case sensitive: `MM` is the month and `mm` is the minute, while `HH` is the hour on a 24-hour clock and `hh` is the hour on a 12-hour clock. For more information, see [Custom formats]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#custom-formats). +`time_zone` | Optional. The time zone used to calculate the date, as an offset, such as `+12:00`, or an ID, such as `America/Los_Angeles`. Default is UTC. + +The entire expression must be enclosed in angle brackets. To use `{` or `}` in the static part of the name, escape the character using a backslash (`\`). + +The following table shows how expressions resolve if the current time is 18:00 UTC on October 13, 2026. + +Expression | Resolves to +:--- | :--- +`` | `app-logs-2026.10.13` +`` | `app-logs-2026.10.12` +`` | `app-logs-2026.10.12` (weeks start on Monday) +`` | `app-logs-2026.10.13.17` +`` | `app-logs-2026.10.14` +`` | `sales-2026-10` +`` | `app{prod}-2026.10.01` + +OpenSearch resolves date math using the Gregorian calendar, regardless of the locale. + +In a request URL, you must percent-encode the special characters in a date math expression. OpenSearch rejects a URL that contains these characters without encoding. The following table lists the encoded value of each character. + +Character | Encoded value +:--- | :--- +`<` | `%3C` +`>` | `%3E` +`/` | `%2F` +`{` | `%7B` +`}` | `%7D` +`\|` | `%7C` +`+` | `%2B` +`:` | `%3A` +`,` | `%2C` + +The following request calculates the total `west` region sales from the monthly `sales-` indexes for the current and previous months. Before encoding, the index part of the path is `,`: + +```json +GET /%3Csales-%7Bnow%2FM-1M%7Byyyy-MM%7D%7D%3E%2C%3Csales-%7Bnow%2FM%7Byyyy-MM%7D%7D%3E/_search +{ + "size": 0, + "query": { + "term": { + "region": "west" + } + }, + "aggs": { + "total_sales": { + "sum": { + "field": "amount" + } + } + } +} +``` +{% include copy-curl.html %} + +## Restricting indexes in request bodies + +The Bulk, Multi-get, and Multi-search APIs let each item in the request body specify its own target index, overriding the index in the request path. If you control access to indexes based on the request URL, for example, using a proxy, a user could bypass that control by naming a different index in the request body. + +To prevent this, set `rest.action.multi.allow_explicit_index` to `false` in `opensearch.yml` on each node. This is a static setting, so you must restart the node for it to take effect. Default is `true`. When the setting is `false`, these APIs reject any request whose body specifies an index, even if it matches the index in the path. Specify the target index in the request path: + +```json +POST /orders/_bulk +{ "index": {} } +{ "product": "Trail running shoes" } +``` +{% include copy-curl.html %} + +## Related documentation + +- [Common REST parameters]({{site.url}}{{site.baseurl}}/api-reference/common-parameters/) +- [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/) +- [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/) diff --git a/_api-reference/index.md b/_api-reference/index.md index 41d54989..8da2c1c9 100644 --- a/_api-reference/index.md +++ b/_api-reference/index.md @@ -1,66 +1,148 @@ --- layout: default -title: REST API reference +title: API reference nav_order: 1 has_toc: false has_children: true nav_exclude: true +description: "Complete OpenSearch API reference for REST APIs and gRPC APIs, including cluster, index, search, document, and other operations." permalink: /api-reference/ redirect_from: - /opensearch/rest-api/index/ - /api-reference/index/ --- -# REST API reference +# API reference + +You can use [REST APIs](#rest-apis) for every API operation in OpenSearch. You can call a subset of these operations using the experimental [gRPC APIs](#grpc-apis) instead. + +This page lists API families rather than individual operations. To find a specific operation, open the family that owns it and use the list of APIs on its page. + +The request examples on API pages omit the host and credentials, so you can paste them into Dev Tools. To learn how to send the same requests using cURL, including the host URL and authentication, see [Communicate with OpenSearch]({{site.url}}{{site.baseurl}}/getting-started/communicate/). + +OpenSearch publishes a reference generated from the OpenSearch API specification that lists REST endpoints with their parameters and schemas. The specification is not yet complete, so some APIs might not appear in the generated reference. For more information, see the [OpenSearch API specification](https://api-spec.opensearch.org/). + +## REST APIs **Introduced 1.0** {: .label .label-purple } -You can use REST APIs for most operations in OpenSearch. In this reference, we provide a description of the API, and details that include the paths and HTTP methods, supported parameters, and example requests and responses. +OpenSearch provides the following REST APIs. -This reference includes the REST APIs supported by OpenSearch. If a REST API is missing, please provide feedback or submit a pull request in GitHub. -{: .tip } +### Core REST APIs -## Related articles +The following core REST APIs are documented in this section. + +| API | Use it to | +| :--- | :--- | +| [Analyze API]({{site.url}}{{site.baseurl}}/api-reference/analyze-apis/) | Inspect the tokens that an analyzer produces from a text string. | +| [CAT APIs]({{site.url}}{{site.baseurl}}/api-reference/cat/) | Read cluster statistics as plain text aligned in columns. | +| [List APIs]({{site.url}}{{site.baseurl}}/api-reference/list/) | Read index and shard statistics as paginated plain text. | +| [Cluster APIs]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/) | Check cluster health, change cluster settings, and retrieve cluster statistics. | +| [Data stream APIs]({{site.url}}{{site.baseurl}}/api-reference/data-stream/) | Create, delete, modify, and retrieve information about data streams. | +| [Document APIs]({{site.url}}{{site.baseurl}}/api-reference/document-apis/) | Index, retrieve, update, and delete documents, individually or in bulk. | +| [Index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/) | Create, configure, maintain, and delete indexes, aliases, and index templates. | +| [Ingest APIs]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/) | Define the ingest pipelines and processors that transform documents as they are indexed. | +| [Nodes APIs]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/) | Retrieve information, statistics, and hot threads for individual nodes. | +| [Script APIs]({{site.url}}{{site.baseurl}}/api-reference/script-apis/) | Store, retrieve, and run Painless scripts. | +| [Search APIs]({{site.url}}{{site.baseurl}}/api-reference/search-apis/) | Run queries and work with search templates, scroll contexts, and search profiling. | +| [Snapshot APIs]({{site.url}}{{site.baseurl}}/api-reference/snapshots/) | Manage snapshot repositories and take and restore snapshots. | +| [Tasks APIs]({{site.url}}{{site.baseurl}}/api-reference/tasks/) | Track and cancel long-running operations. | + +The rest of the APIs listed on this page are documented in their respective sections. + +### Search feature and query language APIs + +The following APIs extend the core search APIs with additional ways to submit queries, process results, and measure relevance. + +| API | Use it to | +| :--- | :--- | +| [Asynchronous Search API]({{site.url}}{{site.baseurl}}/search-plugins/async/) | Run a search in the background and retrieve partial results while it completes. | +| [Search Pipeline APIs]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/) | Define the search pipelines and processors that transform search requests and results. | +| [Search Relevance Workbench APIs]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/) | Create the query sets, search configurations, judgments, and experiments that measure search quality. | +| [SQL and PPL API]({{site.url}}{{site.baseurl}}/sql-and-ppl/sql-and-ppl-api/) | Run SQL and Piped Processing Language queries and manage the data sources they read. | + +### Vector search and machine learning APIs + +The following APIs manage the models, agents, and workflows that support vector search and machine learning. + +| API | Use it to | +| :--- | :--- | +| [ML Commons API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/) | Register, deploy, and run machine learning models, agents, and connectors. | +| [Vector Search API]({{site.url}}{{site.baseurl}}/vector-search/api/) | Manage the models and read the statistics that support vector search. | +| [Workflow APIs]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/api/) | Create, provision, and manage the workflow templates that automate complex setup tasks. | + +### Index management APIs + +The following APIs automate the maintenance of indexes and their data. + +| API | Use it to | +| :--- | :--- | +| [Index Rollups API]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/) | Create and manage the rollup jobs that summarize historical data into smaller indexes. | +| [Index State Management API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/) | Create and manage the policies that automate index lifecycle operations. | +| [ISM Error Prevention API]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/api/) | Turn on Index State Management error prevention and read its validation results. | +| [Refresh Search Analyzer API]({{site.url}}{{site.baseurl}}/im-plugin/refresh-analyzer/) | Reload the search analyzers of an open index without closing it. | +| [Transforms API]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/transforms-apis/) | Create and manage the transform jobs that reshape data into a new index. | + +### Cluster management APIs + +The following APIs protect cluster availability and control how a cluster uses its resources. + +| API | Use it to | +| :--- | :--- | +| [Cross-Cluster Replication (CCR) API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/replication-plugin/api/) | Replicate indexes from a leader cluster to a follower cluster. | +| [Remote Store Stats API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/remote-store-stats-api/) | Read upload and download statistics for remote-backed storage. | +| [Rules API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/workload-management/rule-based-autotagging/rule-lifecycle-api/) | Create and manage the auto-tagging rules that assign incoming requests to a workload group. | +| [Shard Indexing Backpressure Stats API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/stats-api/) | Monitor shard indexing backpressure. | +| [Snapshot Management API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/sm-api/) | Take and delete snapshots on a schedule. | +| [Workload Management APIs]({{site.url}}{{site.baseurl}}/tuning-your-cluster/workload-management/workload-groups/) | Create the workload groups that limit resource usage and read their statistics. | + +### Observability and monitoring APIs + +The following APIs report the cluster state and notify you when it changes. + +| API | Use it to | +| :--- | :--- | +| [Alerting API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/) | Create and manage monitors, triggers, and alerts. | +| [Anomaly Detection API]({{site.url}}{{site.baseurl}}/observing-your-data/ad/api/) | Create and manage anomaly detectors and read the anomalies they find. | +| [Forecasting API]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/api/) | Create and manage forecasters and read the forecasts they produce. | +| [Job Scheduler APIs]({{site.url}}{{site.baseurl}}/tuning-your-cluster/scheduled-jobs/index/#monitoring-scheduled-jobs) | Monitor the scheduled jobs and locks on a cluster. | +| [Notifications API]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/api/) | Define the channels that deliver notifications and the sources that send them. | +| [Query Insights APIs]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/query-insights/) | Read top N queries, live queries, and query insights health statistics, and change query insights settings. | +| [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/) | Define reports and generate them from dashboards, visualizations, saved searches, and notebooks. Downloading the rendered content uses the OpenSearch Dashboards endpoint. | + +### Security and security analytics APIs + +The following APIs provide access control for a cluster and detect security threats in the data it contains. + +| API | Use it to | +| :--- | :--- | +| [Resource Sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) | Share plugin resources, such as models and detectors, with other users and roles. | +| [Security APIs]({{site.url}}{{site.baseurl}}/security/api/) | Manage users, roles, role mappings, action groups, and tenants, and read or replace the security configuration. | +| [Security Analytics APIs]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/index/) | Manage the detectors, rules, findings, and alerts that identify security events. | + +### OpenSearch Dashboards APIs + +The following APIs manage OpenSearch Dashboards saved objects and workspaces and read usage statistics. Unlike the preceding REST API requests that are sent to the OpenSearch REST layer on port 9200 by default, you send these requests to OpenSearch Dashboards on port 5601 by default. + +| API | Use it to | +| :--- | :--- | +| [Maps Stats API]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/maps-stats-api/) | Read usage statistics for maps and their layers. | +| [Saved Objects APIs]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects-api/) | List, create, update, export, and import saved objects such as index patterns, visualizations, and dashboards. | +| [Search Relevance Stats API]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/stats-api/) | Read usage statistics for search relevance operations. | +| [Workspace APIs]({{site.url}}{{site.baseurl}}/dashboards/workspace/apis/) | Create, update, list, and delete workspaces. | + +## gRPC APIs +**Introduced 3.0** +{: .label .label-purple } + +You can use gRPC APIs as an alternative to REST interfaces. These APIs use the gRPC protocol to provide more efficient communication with OpenSearch clusters. For more information and supported APIs, see [gRPC APIs]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/). + +## Reference + +The following pages provide additional API reference information: -- [Analyze API]({{site.url}}{{site.baseurl}}/api-reference/analyze-apis/) -- [Access control API]({{site.url}}{{site.baseurl}}/security/access-control/api/) -- [Alerting API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/) -- [Anomaly detection API]({{site.url}}{{site.baseurl}}/observing-your-data/ad/api/) -- [CAT APIs]({{site.url}}{{site.baseurl}}/api-reference/cat/index/) -- [Cluster APIs]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/index/) - [Common REST parameters]({{site.url}}{{site.baseurl}}/api-reference/common-parameters/) -- [Count]({{site.url}}{{site.baseurl}}/api-reference/count/) -- [Cross-cluster replication API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/replication-plugin/api/) -- [Document APIs]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index/) -- [Explain]({{site.url}}{{site.baseurl}}/api-reference/explain/) -- [Index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index/) -- [Index rollups API]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/) -- [Index state management API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/) -- [ISM error prevention API]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/api/) -- [Ingest APIs]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/index/) -- [k-NN plugin API]({{site.url}}{{site.baseurl}}/search-plugins/knn/api/) -- [ML Commons API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/) -- [Multi-search]({{site.url}}{{site.baseurl}}/api-reference/multi-search/) -- [Nodes APIs]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/) -- [Notifications API]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/api/) -- [Performance analyzer API]({{site.url}}{{site.baseurl}}/monitoring-your-cluster/pa/api/) -- [Point in Time API]({{site.url}}{{site.baseurl}}/search-plugins/point-in-time-api/) -- [Popular APIs]({{site.url}}{{site.baseurl}}/api-reference/popular-api/) -- [Ranking evaluation]({{site.url}}{{site.baseurl}}/api-reference/rank-eval/) -- [Refresh search analyzer]({{site.url}}{{site.baseurl}}/im-plugin/refresh-analyzer/) -- [Remove cluster information]({{site.url}}{{site.baseurl}}/api-reference/remote-info/) -- [Root cause analysis API]({{site.url}}{{site.baseurl}}/monitoring-your-cluster/pa/rca/api/) -- [Snapshot management API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/sm-api/) -- [Script APIs]({{site.url}}{{site.baseurl}}/api-reference/script-apis/index/) -- [Scroll]({{site.url}}{{site.baseurl}}/api-reference/scroll/) -- [Search]({{site.url}}{{site.baseurl}}/api-reference/search/) -- [Search relevance stats API]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/stats-api/) -- [Security analytics APIs]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/index/) -- [Snapshot APIs]({{site.url}}{{site.baseurl}}/api-reference/snapshots/index/) -- [Stats API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/stats-api/) - [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/) -- [Tasks]({{site.url}}{{site.baseurl}}/api-reference/tasks/) -- [Transforms API]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/transforms-apis/) - - - +- [Index name syntax]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/) +- [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/) +- [Popular APIs]({{site.url}}{{site.baseurl}}/api-reference/popular-api/) diff --git a/_api-reference/ingest-apis/index.md b/_api-reference/ingest-apis/index.md index 6cea0a9f..d923ee15 100644 --- a/_api-reference/ingest-apis/index.md +++ b/_api-reference/ingest-apis/index.md @@ -2,22 +2,56 @@ layout: default title: Ingest APIs has_children: false -nav_order: 40 +nav_order: 70 redirect_from: - /opensearch/rest-api/ingest-apis/index/ + - /api-reference/ingest-apis/ --- # Ingest APIs **Introduced 1.0** {: .label .label-purple } -Ingest APIs are a valuable tool for loading data into a system. Ingest APIs work together with [ingest pipelines]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/ingest-pipelines/) and [ingest processors]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/ingest-processors/) to process or transform data from a variety of sources and in a variety of formats. +Use the ingest APIs to manage [ingest pipelines]({{site.url}}{{site.baseurl}}/ingest-pipelines/), which transform documents before OpenSearch indexes them. A pipeline consists of a sequence of [ingest processors]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/), each of which performs one transformation, such as renaming a field, parsing a log line, or generating vector embeddings. -## Ingest pipeline APIs +## Pipeline APIs -Simplify, secure, and scale your OpenSearch data ingestion with the following APIs: +The following APIs create, retrieve, test, and delete ingest pipelines. -- [Create pipeline]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/create-ingest/): Use this API to create or update a pipeline configuration. -- [Get pipeline]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/get-ingest/): Use this API to retrieve a pipeline configuration. -- [Simulate pipeline]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/simulate-ingest/): Use this pipeline to test a pipeline configuration. -- [Delete pipeline]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/delete-ingest/): Use this API to delete a pipeline configuration. +API | Endpoint | Description +:--- | :--- | :--- +[Create or update pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/) | `PUT _ingest/pipeline/{pipeline-id}` | Creates a pipeline or replaces the definition of an existing pipeline. +[Get pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/get-ingest/) | `GET _ingest/pipeline/{pipeline-id}` | Returns the definition of one or more pipelines. Omit the pipeline ID to return all pipelines. +[Simulate pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/simulate-ingest/) | `POST _ingest/pipeline/{pipeline-id}/_simulate` | Runs a pipeline against sample documents without indexing them. You can simulate an existing pipeline or provide a pipeline definition in the request body. +[Delete pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/delete-ingest/) | `DELETE _ingest/pipeline/{pipeline-id}` | Deletes one or more pipelines. + +## Processor APIs + +The following API returns information about a specific processor. + +API | Endpoint | Description +:--- | :--- | :--- +[Get grok patterns]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/grok/#retrieving-built-in-patterns) | `GET _ingest/processor/grok` | Returns the built-in patterns that you can reference in `grok` processor expressions. + +## Related APIs + +The following APIs aren't ingest APIs but return information about ingest processing: + +- To list the processors installed on each node, use the [Nodes Info API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-info/): `GET _nodes/ingest?filter_path=nodes.*.ingest.processors`. +- To view statistics for each pipeline and processor, such as the number of processed and failed documents, use the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/): `GET _nodes/stats/ingest`. + +To apply a pipeline to documents, specify it in an indexing request or set it as an index's default pipeline. For more information, see [Applying a pipeline to documents]({{site.url}}{{site.baseurl}}/ingest-pipelines/#applying-a-pipeline-to-documents). + +## Required permissions + +If you use the Security plugin, you must have the following permissions to use the ingest APIs. + +Permission | Required for +:--- | :--- +`cluster:admin/ingest/pipeline/put` | Creating or updating pipelines +`cluster:admin/ingest/pipeline/get` | Retrieving pipelines +`cluster:admin/ingest/pipeline/simulate` | Simulating pipelines +`cluster:admin/ingest/pipeline/delete` | Deleting pipelines +`cluster:admin/ingest/processor/grok/get` | Retrieving grok patterns + +The `cluster_manage_pipelines` action group grants all pipeline permissions (`cluster:admin/ingest/pipeline/*`) but not the grok patterns permission. For more information, see [Default action groups]({{site.url}}{{site.baseurl}}/security/access-control/default-action-groups/). diff --git a/_api-reference/list/index.md b/_api-reference/list/index.md new file mode 100644 index 00000000..54e6168b --- /dev/null +++ b/_api-reference/list/index.md @@ -0,0 +1,297 @@ +--- +layout: default +title: List APIs +nav_order: 20 +has_children: true +redirect_from: + - /api-reference/list/ +--- + +# List APIs +**Introduced 2.18** +{: .label .label-purple } + +The List API retrieves statistics about indexes and shards in a paginated format. This streamlines the task of processing responses that include many indexes. + +The List API supports two operations: + +- [List indices]({{site.url}}{{site.baseurl}}/api-reference/list/list-indices/) +- [List shards]({{site.url}}{{site.baseurl}}/api-reference/list/list-shards/) + +## Shared query parameters + +All List API operations support the following optional query parameters. + +Parameter | Description +:--- | :--- | +`v` | Provides verbose output by adding headers to the columns. +`help` | Lists the default and other available headers for a given operation. +`h` | Limits the output to specific headers. +`format` | The format in which to return the result. Valid values are `json`, `yaml`, `cbor`, and `smile`. +`s` | Sorts the output by the specified columns. +`next_token` | The token for fetching the next page of results. Each paginated response ends with a `next_token` value. Pass this value in the next request to retrieve the next page. When `next_token` is `null`, all results have been returned. +`size` | The maximum number of entries to return on a single page. +`sort` | The order in which entries are returned, based on index creation time. Valid values are `asc` (oldest first) and `desc` (most recently created first). Default is `asc`. + +The default and allowed values of `size` differ by operation. For more information, see [List indices]({{site.url}}{{site.baseurl}}/api-reference/list/list-indices/) and [List shards]({{site.url}}{{site.baseurl}}/api-reference/list/list-shards/). + +## Examples + +The following examples show how to use the optional query parameters to customize all List API responses. + + +### Get verbose output + +To query indexes and their statistics with a verbose output that includes all column headings in the response, use the `v` query parameter, as shown in the following example. + +#### Request + + +{% capture step1_rest %} +GET /_list/indices?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Response + +```json +health status index uuid pri rep docs.count docs.deleted store.size pri.store.size +green open sample-index-1 L4tj1plyQLCjGegvdEI16A 1 0 3 0 4.7kb 4.7kb +yellow open sample-index-2 n9sq3RtJR2mMmTqJF2Xh6w 1 1 5 0 4.8kb 4.8kb +next_token null +``` + + +### Get all available headers + +To see all the available headers, use the `help` parameter with the following syntax: + +```json +GET _list/{operation_name}?help +``` +{% include copy-curl.html %} + +#### Request + +The following example list indices operation returns all the available headers: + + +{% capture step1_rest %} +GET /_list/indices?help +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + params = { "help": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Response + +The response lists each available header, followed by its aliases and a description. The following example response is truncated: + +```json +health | h | current health status +status | s | open/close status +index | i,idx | index name +uuid | id,uuid | index uuid +pri | p,shards.primary,shardsPrimary | number of primary shards +rep | r,shards.replica,shardsReplica | number of replica shards +docs.count | dc,docsCount | available docs +docs.deleted | dd,docsDeleted | deleted docs +creation.date | cd | index creation date (millisecond value) +creation.date.string | cds | index creation date (as string) +store.size | ss,storeSize | store size of primaries & replicas +pri.store.size | | store size of primaries +``` + +### Get a subset of headers + +To limit the output to a subset of headers, use the `h` parameter with the following syntax: + +```json +GET _list/{operation_name}?h={header_name_1},{header_name_2}&v +``` +{% include copy-curl.html %} + +For any operation, you can determine which headers are available by using the `help` parameter and then using the `h` parameter to limit the output to only a subset of headers. + +#### Request + +The following example limits the indexes in the response to only the index name and health status headers: + + +{% capture step1_rest %} +GET /_list/indices?h=health,index +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + params = { "h": "health,index" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Response + +```json +green sample-index-1 +yellow sample-index-2 +next_token null +``` + + +### Sort by a header + +To sort the output on a single page by a header, use the `s` parameter with the following syntax: + +```json +GET _list/{operation_name}?s={header_name_1},{header_name_2} +``` +{% include copy-curl.html %} + +#### Request + +The following example request sorts indexes by health status and then by index name and limits the output to the health status and index name headers: + + +{% capture step1_rest %} +GET /_list/indices?s=h,i&h=health,index +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + params = { "s": "h,i", "h": "health,index" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Response + +```json +green sample-index-1 +yellow sample-index-2 +next_token null +``` + +### Retrieve data in JSON format + +By default, List APIs return data in a `text/plain` format. Other supported formats are [YAML](https://yaml.org/), [CBOR](https://cbor.io/), and [Smile](https://github.com/FasterXML/smile-format-specification). + + +To retrieve data in the JSON format, use the `format=json` parameter with the following syntax: + +```json +GET _list/{operation_name}?format=json +``` +{% include copy-curl.html %} + +If you use the Security plugin, ensure you have the appropriate permissions. +{: .note } + +#### Request + + +{% capture step1_rest %} +GET /_list/indices?format=json +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + params = { "format": "json" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Response + +The response contains data in JSON format: + +```json +{ + "next_token": null, + "indices": [ + { + "health": "green", + "status": "open", + "index": "sample-index-1", + "uuid": "L4tj1plyQLCjGegvdEI16A", + "pri": "1", + "rep": "0", + "docs.count": "3", + "docs.deleted": "0", + "store.size": "4.7kb", + "pri.store.size": "4.7kb" + }, + { + "health": "yellow", + "status": "open", + "index": "sample-index-2", + "uuid": "n9sq3RtJR2mMmTqJF2Xh6w", + "pri": "1", + "rep": "1", + "docs.count": "5", + "docs.deleted": "0", + "store.size": "4.8kb", + "pri.store.size": "4.8kb" + } + ] +} +``` diff --git a/_api-reference/list/list-indices.md b/_api-reference/list/list-indices.md new file mode 100644 index 00000000..c608b65a --- /dev/null +++ b/_api-reference/list/list-indices.md @@ -0,0 +1,140 @@ +--- +layout: default +title: List indices +parent: List APIs +nav_order: 25 +has_children: false +--- + +# List Indices API +**Introduced 2.18** +{: .label .label-purple } + +The list indices operation provides the following index information in a paginated format: + +- The amount of disk space used by the index. +- The number of shards contained in the index. +- The index's health status. + +## Endpoints + +```json +GET _list/indices +GET _list/indices/{index} +``` + +## Query parameters + +Parameter | Type | Description +:--- | :--- | :--- +`bytes` | Byte size | Specifies the units for the byte size, for example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). +`health` | String | Limits indexes based on their health status. Supported values are `green`, `yellow`, and `red`. +`include_unloaded_segments` | Boolean | Whether to include information from segments not loaded into memory. Default is `false`. +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`pri` | Boolean | Whether to return information only from the primary shards. Default is `false`. +`time` | Time | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). +`expand_wildcards` | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. +`next_token` | String | Fetches the next page of indexes. When `null`, only provides the first page of indexes. Default is `null`. +`size` | Integer | The maximum number of indexes to be displayed on a single page. The number of indexes on a single page of the response is not always equal to the specified `size`. Default is `500`. Minimum is `1` and maximum value is `5000`. +`sort` | String | The order in which the indexes are displayed. If `desc`, then the most recently created indexes are displayed first. If `asc`, then the oldest indexes are displayed first. Default is `asc`. + +When using the `next_token` query parameter, use the token produced by the response to see the next page of indexes. After the API returns `null`, all indexes contained in the API have been returned. +{: .tip } + + +## Example requests + +To get information for all the indexes, send the following request: + +```json +GET /_list/indices?v +``` + +To get the next page of indexes, pass the `next_token` value from the previous response. Repeat this request until the response returns a `next_token` of `null`: + +```json +GET /_list/indices?v&next_token= +``` + +To limit the information to a specific index, add the index name after your query, as shown in the following example: + + +{% capture step1_rest %} +GET /_list/indices/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To get information about more than one index, separate the indexes with commas, as shown in the following example: + + +{% capture step1_rest %} +GET /_list/indices/index1,index2,index3?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.indices( + index = "index1,index2,index3", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +**Plain text format** + +```json +health | status | index | uuid | pri | rep | docs.count | docs.deleted | store.size | pri.store.size +green | open | movies | UZbpfERBQ1-3GSH2bnM3sg | 1 | 1 | 1 | 0 | 7.7kb | 3.8kb +next_token MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw== +``` + +**JSON format** + +```json +{ + "next_token": "MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw==", + "indices": [ + { + "health": "green", + "status": "open", + "index": "movies", + "uuid": "UZbpfERBQ1-3GSH2bnM3sg", + "pri": "1", + "rep": "1", + "docs.count": "1", + "docs.deleted": "0", + "store.size": "7.7kb", + "pri.store.size": "3.8kb" + } + ] +} +``` diff --git a/_api-reference/list/list-shards.md b/_api-reference/list/list-shards.md new file mode 100644 index 00000000..3a1ef183 --- /dev/null +++ b/_api-reference/list/list-shards.md @@ -0,0 +1,144 @@ +--- +layout: default +title: List shards +parent: List APIs +nav_order: 20 +--- + +# List Shards API +**Introduced 2.18** +{: .label .label-purple } + +The list shards operation outputs, in a paginated format, the state of all primary and replica shards and how they are distributed. + +## Endpoints + +```json +GET _list/shards +GET _list/shards/{index} +``` + +## Query parameters + +All parameters are optional. + +Parameter | Type | Description +:--- | :--- | :--- +`bytes` | Byte size | Specifies the byte size units, for example, `7kb` or `6gb`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). +`local` | Boolean | Whether to return information from the local node only instead of from the cluster manager node. Default is `false`. +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`cancel_after_time_interval` | Time | The amount of time after which the shard request is canceled. Default is `-1` (no timeout). +`time` | Time | Specifies the time units, for example, `5d` or `7h`. For more information, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). +`next_token` | String | Fetches the next page of indexes. When `null`, only provides the first page of indexes. Default is `null`. +`size` | Integer | The maximum number of indexes to be displayed on a single page. The number of indexes on a single page of the response is not always equal to the specified `size`. Default and minimum value is `2000`. Maximum value is `20000`. +`sort` | String | The order in which the indexes are displayed. If `desc`, then the most recently created indexes are displayed first. If `asc`, then the oldest indexes are displayed first. Default is `asc`. + +When using the `next_token` query parameter, use the token produced by the response to see the next page of indexes. After the API returns `null`, all indexes contained in the API have been returned. +{: .tip } + +## Example requests + +To get information for all the indexes and shards, send the following request: + +```json +GET /_list/shards?v +``` + +To get the next page of shards, pass the `next_token` value from the previous response. Repeat this request until the response returns a `next_token` of `null`: + +```json +GET /_list/shards?v&next_token= +``` + +To limit the information to a specific index, add the index name after your query, as shown in the following example: + + +{% capture step1_rest %} +GET /_list/shards/?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.shards( + index = "", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If you want to get information for more than one index, separate the indexes with commas, as shown in the following example: + + +{% capture step1_rest %} +GET /_list/shards/index1,index2,index3?v +{% endcapture %} + +{% capture step1_python %} + + +response = client.list.shards( + index = "index1,index2,index3", + params = { "v": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +**Plain text format** + +```json +index | shard | prirep | state | docs | store | ip | | node +plugins | 0 | p | STARTED | 0 | 208b | 172.18.0.4 | odfe-node1 +plugins | 0 | r | STARTED | 0 | 208b | 172.18.0.3 | odfe-node2 +.... +.... +next_token MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw== +``` + +**JSON format** + +```json +{ + "next_token": "MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw==", + "shards": [ + { + "index": "plugins", + "shard": "0", + "prirep": "p", + "state": "STARTED", + "docs": "0", + "store": "208B", + "ip": "172.18.0.4", + "node": "odfe-node1" + }, + { + "index": "plugins", + "shard": "0", + "prirep": "r", + "state": "STARTED", + "docs": "0", + "store": "208B", + "ip": "172.18.0.3", + "node": "odfe-node2" + } + ] +} +``` diff --git a/_api-reference/multi-search.md b/_api-reference/multi-search.md index 25f28c5e..545f1ede 100644 --- a/_api-reference/multi-search.md +++ b/_api-reference/multi-search.md @@ -6,16 +6,97 @@ redirect_from: - /opensearch/rest-api/multi-search/ --- -# Multi-search +# Multi-Search API **Introduced 1.0** {: .label .label-purple } As the name suggests, the multi-search operation lets you bundle multiple search requests into a single request. OpenSearch then executes the searches in parallel, so you get back the response more quickly compared to sending one request per search. OpenSearch executes each search independently, so the failure of one doesn't affect the others. -## Example + +## Endpoints +```json +GET /_msearch +POST /_msearch +GET /{index}/_msearch +POST /{index}/_msearch +``` + +Specifying an index in the path sets the default target for any searches whose metadata line does not include an `index` field. If you omit the path parameter and a search's metadata line also does not specify an `index`, the search runs against all indexes. + + +## Query parameters and metadata options + +All parameters are optional. Some can also be applied per-search as part of each metadata line. + +Parameter | Type | Description | Supported in metadata line +:--- | :--- | :--- | :--- +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. | Yes +`cancel_after_time_interval` | Time | The time after which the search request will be canceled. Supported at both parent and child request levels. The order of precedence is:
1. Child-level parameter
2. Parent-level parameter
3. [Cluster settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-settings/).
Default is -1. | Yes +`ccs_minimize_roundtrips` | Boolean | Whether OpenSearch should try to minimize the number of network round trips between the coordinating node and remote clusters (only applicable to cross-cluster search requests). Default is `true`. | No +`expand_wildcards` | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. | Yes +`ignore_unavailable` | Boolean | If an index or shard from the indexes list doesn't exist, whether to ignore it rather than fail the query. Default is `false`. | Yes +`include_named_queries_score` | Boolean | Whether to return scores for named queries. Default is `false`. | No +`max_concurrent_searches` | Integer | The maximum number of concurrent searches. The default depends on your node count and search thread pool size. Higher values can improve performance, but risk overloading the cluster. | No +`max_concurrent_shard_requests` | Integer | Maximum number of concurrent shard requests that each search executes per node. Default is 5. Higher values can improve performance, but risk overloading the cluster. | No +`pre_filter_shard_size` | Integer | A threshold that triggers a pre-filter round trip to eliminate shards that cannot match the query (for example, because a date range filter falls outside the shard's bounds). When unspecified, the pre-filter phase runs if the request targets more than 128 shards, targets a read-only index, or sorts on an indexed field. Default is `128`. | No +`rest_total_hits_as_int` | String | Whether the `hits.total` property is returned as an integer (`true`) or an object (`false`). Default is `false`. | No +`routing` | String | Comma-separated custom routing values used to route all searches in the request to specific shards. To set routing for individual searches, use the `routing` option in the metadata line instead. | No +`search_type` | String | Affects relevance score. Valid options are `query_then_fetch` and `dfs_query_then_fetch`. `query_then_fetch` scores documents using term and document frequencies for the shard (faster, less accurate), whereas `dfs_query_then_fetch` uses term and document frequencies across all shards (slower, more accurate). Default is `query_then_fetch`. | Yes +`typed_keys` | Boolean | Whether to prefix aggregation names with their internal types in the response. Default is `false`. | No + + +## Metadata-only options + +Some options can't be applied as parameters to the entire request. Instead, you can apply them per-search as part of each metadata line. All are optional. + +Option | Type | Description +:--- | :--- | :--- +`index` | String, string array | If you don't specify an index or multiple indexes as part of the URL (or want to override the URL value for an individual search), you can include it here. Examples include `"logs-*"` and `["my-store", "sample_data_ecommerce"]`. +`preference` | String | The nodes or shards that you'd like to perform the search. This setting can be useful for testing, but in most situations, the default behavior provides the best search latencies. Options include `_local`, `_only_local`, `_prefer_nodes`, `_only_nodes`, and `_shards`. These last three options accept a list of nodes or shards. Examples include `"_only_nodes:data-node1,data-node2"` and `"_shards:0,1`. +`request_cache` | Boolean | Whether to cache results, which can improve latency for repeat searches. Default is to use the `index.requests.cache.enable` setting for the index (which defaults to `true` for new indexes). +`routing` | String | Comma-separated custom routing values, for example, `"routing": "value1,value2,value3"`. Unlike `routing` at the query parameter level, which applies to all searches in the request, this option targets routing for an individual search only. + +## Request body + +The multi-search request body uses newline-delimited JSON (NDJSON) format, alternating between metadata and query lines: + +``` +Metadata\n +Query\n +Metadata\n +Query\n + +``` + +- Metadata lines include options, such as which indexes to search and the type of search. A metadata line can be empty (`{}`) if no per-search overrides are needed. +- Query lines use the [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). + +Like the [bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) operation, the JSON doesn't need to be minified---spaces are fine---but it does need to be on a single line. OpenSearch uses newline characters to parse multi-search requests and requires that the request body end with a newline character. + +When sending requests to this endpoint, set the `Content-Type` header to `application/x-ndjson`. +{: .note} + +### Query body fields + +Each query line accepts the same parameters as the [Search API]({{site.url}}{{site.baseurl}}/api-reference/search/) request body. The following table lists the most commonly used fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `query` | Object | The query DSL expression to execute. See [Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). | +| `aggregations` | Object | Aggregations to run alongside the search. See [Aggregations]({{site.url}}{{site.baseurl}}/aggregations/). | +| `from` | Integer | The starting offset for returned hits. Default is `0`. | +| `size` | Integer | The number of hits to return. Default is `10`. | +| `sort` | Array or Object | The fields and order by which to sort results. | +| `_source` | Boolean, String, or Object | Controls which fields are included in the `_source` of each hit. | +| `highlight` | Object | Highlight configuration for matched fields. | + + +## Example: Searching multiple indexes + +The following example runs queries against multiple indexes, specifying the target index in each metadata line: ```json -GET _msearch +GET /_msearch { "index": "opensearch_dashboards_sample_data_logs"} { "query": { "match_all": {} }, "from": 0, "size": 10} { "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} @@ -25,70 +106,95 @@ GET _msearch {% include copy-curl.html %} -## Path and HTTP methods +## Example: Using a default index + +When you specify an index in the URL path, that index serves as the default for any searches whose metadata line does not include an `index` field. The following example runs two queries against the `products` index without repeating the index name in each metadata line: + +```json +GET /products/_msearch +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} ``` -GET _msearch -GET /_msearch -POST _msearch -POST /_msearch -``` +{% include copy-curl.html %} +## Using search templates -## Request body +The multi-search API supports [search templates]({{site.url}}{{site.baseurl}}/search-plugins/search-template/) through the `_msearch/template` endpoint. This lets you execute parameterized searches, separating the query structure from the values passed at search time. -The multi-search request body follows this pattern: +### Example: Inline templates + +The following request uses inline templates to run two parameterized searches in a single call: + +```json +GET _msearch/template +{"index": "products"} +{"source": {"query": {"match": {"product_name": "{{search_term}}"}}}, "params": {"search_term": "wireless"}} +{"index": "products"} +{"source": {"query": {"range": {"price": {"lte": "{{max_price}}"}}}}, "params": {"max_price": "75"}} ``` -Metadata\n -Query\n -Metadata\n -Query\n +{% include copy-curl.html %} + +### Example: Stored templates + +You can also reference pre-registered templates by ID. First, create the stored templates: + +```json +POST _scripts/product_search_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "multi_match": { + "query": "{{query_text}}", + "fields": ["product_name", "description"] + } + }, + "size": "{{result_count}}" + } + } +} +``` +{% include copy-curl.html %} + +```json +POST _scripts/price_range_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "range": { + "price": { + "gte": "{{min_price}}", + "lte": "{{max_price}}" + } + } + }, + "size": "{{result_count}}" + } + } +} +``` +{% include copy-curl.html %} + +Then use the stored templates in a multi-search request: + +```json +GET _msearch/template +{"index": "products"} +{"id": "product_search_template", "params": {"query_text": "bluetooth speaker", "result_count": "5"}} +{"index": "products"} +{"id": "price_range_template", "params": {"min_price": "20", "max_price": "100", "result_count": "3"}} ``` +{% include copy-curl.html %} -- Metadata lines include options, such as which indexes to search and the type of search. -- Query lines use the [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). - -Just like the [bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) operation, the JSON doesn't need to be minified---spaces are fine---but it does need to be on a single line. OpenSearch uses newline characters to parse multi-search requests and requires that the request body end with a newline character. - - -## URL parameters and metadata options - -All multi-search URL parameters are optional. Some can also be applied per-search as part of each metadata line. - -Parameter | Type | Description | Supported in metadata line -:--- | :--- | :--- -allow_no_indices | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. | Yes -cancel_after_time_interval | Time | The time after which the search request will be canceled. Supported at both parent and child request levels. The order of precedence is:
1. Child-level parameter
2. Parent-level parameter
3. [Cluster setting]({{site.url}}{{site.baseurl}}/api-reference/cluster-settings).
Default is -1. | Yes -css_minimize_roundtrips | Boolean | Whether OpenSearch should try to minimize the number of network round trips between the coordinating node and remote clusters (only applicable to cross-cluster search requests). Default is `true`. | No -expand_wildcards | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. | Yes -ignore_unavailable | Boolean | If an index from the indexes list doesn’t exist, whether to ignore it rather than fail the query. Default is `false`. | Yes -max_concurrent_searches | Integer | The maximum number of concurrent searches. The default depends on your node count and search thread pool size. Higher values can improve performance, but risk overloading the cluster. | No -max_concurrent_shard_requests | Integer | Maximum number of concurrent shard requests that each search executes per node. Default is 5. Higher values can improve performance, but risk overloading the cluster. | No -pre_filter_shard_size | Integer | Default is 128. | No -rest_total_hits_as_int | String | Whether the `hits.total` property is returned as an integer (`true`) or an object (`false`). Default is `false`. | No -search_type | String | Affects relevance score. Valid options are `query_then_fetch` and `dfs_query_then_fetch`. `query_then_fetch` scores documents using term and document frequencies for the shard (faster, less accurate), whereas `dfs_query_then_fetch` uses term and document frequencies across all shards (slower, more accurate). Default is `query_then_fetch`. | Yes -typed_keys | Boolean | Whether to prefix aggregation names with their internal types in the response. Default is `false`. | No - -{% comment %}Regarding `pre_filter_shard_size`: The description from the REST API specification is unintelligible---to me, anyway. I wasn't able to learn anything from reading the source code, either, so I've included the default value and nothing else in the table above. - aetter - -From the REST API specification: A threshold that enforces a pre-filter round trip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on its rewrite method ie. if date filters are mandatory to match but the shard bounds and the query are disjoint.{% endcomment %} - - -## Metadata-only options - -Some options can't be applied as URL parameters to the entire request. Instead, you can apply them per-search as part of each metadata line. All are optional. - -Option | Type | Description -:--- | :--- | :--- -index | String, string array | If you don't specify an index or multiple indexes as part of the URL (or want to override the URL value for an individual search), you can include it here. Examples include `"logs-*"` and `["my-store", "sample_data_ecommerce"]`. -preference | String | The nodes or shards that you'd like to perform the search. This setting can be useful for testing, but in most situations, the default behavior provides the best search latencies. Options include `_local`, `_only_local`, `_prefer_nodes`, `_only_nodes`, and `_shards`. These last three options accept a list of nodes or shards. Examples include `"_only_nodes:data-node1,data-node2"` and `"_shards:0,1`. -request_cache | Boolean | Whether to cache results, which can improve latency for repeat searches. Default is to use the `index.requests.cache.enable` setting for the index (which defaults to `true` for new indexes). -routing | String | Comma-separated custom routing values, for example, `"routing": "value1,value2,value3"`. - - -## Response +## Example response OpenSearch returns an array with the results of each search in the same order as the multi-search request. @@ -275,3 +381,30 @@ OpenSearch returns an array with the results of each search in the same order as ] } ``` + +## Response body fields + +The following table lists the top-level response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `took` | Integer | The total time, in milliseconds, for OpenSearch to process all searches in the request. | +| `responses` | Array | An array of search response objects, returned in the same order as the corresponding searches in the request. If a particular search fails completely, the array entry for that search contains an `error` object and a `status` code instead of the normal search response. | + +The following table lists the fields within each entry of the `responses` array. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `took` | Integer | The time, in milliseconds, for OpenSearch to process the individual search. | +| `timed_out` | Boolean | Whether the search timed out before completing. | +| `_shards` | Object | Information about the number of shards involved in the search, including `total`, `successful`, `skipped`, and `failed` counts. | +| `hits` | Object | The search results, including `total` hit count, `max_score`, and an array of matching `hits`. | +| `status` | Integer | The HTTP status code for the individual search result. A value of `200` indicates success. | + +## Partial responses + +If one or more shards fail during execution, the multi-search API still returns results from the successful shards. Each individual search response in the `responses` array includes a `_shards` object that reports how many shards succeeded and how many failed, allowing you to determine whether results are complete. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/msearch`. diff --git a/_api-reference/nodes-apis/index.md b/_api-reference/nodes-apis/index.md index ac5e767e..7d3e1976 100644 --- a/_api-reference/nodes-apis/index.md +++ b/_api-reference/nodes-apis/index.md @@ -2,14 +2,17 @@ layout: default title: Nodes APIs has_children: true -nav_order: 50 +has_toc: false +nav_order: 80 +redirect_from: + - /api-reference/nodes-apis/ --- -# Nodes API +# Nodes APIs **Introduced 1.0** {: .label .label-purple } -The nodes API makes it possible to retrieve information about individual nodes within your cluster. +The Nodes API makes it possible to retrieve information about individual nodes in your cluster. ## Node filters @@ -29,7 +32,7 @@ table th:nth-of-type(3) { Parameter | Type | Description :--- |:-------| :--- -`` | String | A comma-separated list of resolution mechanisms that OpenSearch uses to identify cluster nodes. +`node-filters` | String | A comma-separated list of resolution mechanisms that OpenSearch uses to identify cluster nodes. Node filters support several node resolution mechanisms: @@ -49,17 +52,53 @@ Resolution mechanisms are applied sequentially in the order specified by the cli To get statistics from the elected cluster manager node only, use the following query : -```json + +{% capture step1_rest %} GET /_nodes/_cluster_manager/stats -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.info( + metric = "stats", + node_id = "_cluster_manager" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + To get statistics from nodes that are data-only nodes, use the following query: -```json + +{% capture step1_rest %} GET /_nodes/data:true/stats -``` -{% include copy-curl.html %} +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.info( + metric = "stats", + node_id = "data:true" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + ### Order of resolution mechanisms @@ -67,14 +106,60 @@ The order of resolution mechanisms is applied sequentially, and each can add or To get statistics from all the nodes except the cluster manager node, use the following query: -```json + +{% capture step1_rest %} GET /_nodes/_all,cluster_manager:false/stats -``` -{% include copy-curl.html %} +{% endcapture %} -However, if you switch the resolution mechanisms, the result will include all the cluster nodes, including the cluster manager node: +{% capture step1_python %} -```json + +response = client.nodes.info( + metric = "stats", + node_id = "_all,cluster_manager:false" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +However, if you switch the resolution mechanisms, the result will include all the cluster nodes, including the cluster manager node: + + +{% capture step1_rest %} GET /_nodes/cluster_manager:false,_all/stats -``` -{% include copy-curl.html %} \ No newline at end of file +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.info( + metric = "stats", + node_id = "cluster_manager:false,_all" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Nodes API operations + +The following nodes API operations are available: + +- [Nodes hot threads]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-hot-threads/) +- [Nodes info]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-info/) +- [Nodes reload secure settings]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-reload-secure/) +- [Nodes stats]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/) +- [Nodes usage]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-usage/) diff --git a/_api-reference/nodes-apis/nodes-hot-threads.md b/_api-reference/nodes-apis/nodes-hot-threads.md index 3fb6ff65..7bbdef39 100644 --- a/_api-reference/nodes-apis/nodes-hot-threads.md +++ b/_api-reference/nodes-apis/nodes-hot-threads.md @@ -5,24 +5,18 @@ parent: Nodes APIs nav_order: 30 --- -# Nodes hot threads +# Nodes Hot Threads API **Introduced 1.0** {: .label .label-purple } -The nodes hot threads endpoint provides information about busy JVM threads for selected cluster nodes. It provides a unique view of the of activity each node. +The Nodes Hot Threads endpoint provides information about busy JVM threads for selected cluster nodes. It provides a unique view of the activity on each node. -#### Example + +## Endpoints ```json GET /_nodes/hot_threads -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -```json -GET /_nodes/hot_threads -GET /_nodes//hot_threads +GET /_nodes/{node_id}/hot_threads ``` ## Path parameters @@ -31,7 +25,7 @@ You can include the following optional path parameter in your request. Parameter | Type | Description :--- | :--- | :--- -nodeId | String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. +`node_id` | String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. ## Query parameters @@ -39,21 +33,38 @@ You can include the following query parameters in your request. All query parame Parameter | Type | Description :--- | :---| :--- -snapshots | Integer | The number of samples of thread stacktraces. Defaults to `10`. -interval | Time | The interval between consecutive samples. Defaults to `500ms`. -threads | Integer | The number of the busiest threads to return information about. Defaults to `3`. -ignore_idle_threads | Boolean | Don’t show threads that are in known idle states, such as waiting on a socket select or pulling from an empty task queue. Defaults to `true`. +`snapshots` | Integer | The number of samples of thread stack traces. Defaults to `10`. +`interval` | Time | The interval between consecutive samples. Defaults to `500ms`. +`threads` | Integer | The number of the busiest threads to return information about. Defaults to `3`. +`ignore_idle_threads` | Boolean | Don’t show threads that are in known idle states, such as waiting on a socket select or pulling from an empty task queue. Defaults to `true`. type | String | Supported thread types are `cpu`, `wait`, or `block`. Defaults to `cpu`. -timeout | Time | Sets the time limit for node response. Default value is `30s`. +`timeout` | Time | Sets the time limit for node response. Default value is `30s`. -#### Example request +## Example request -```json + +{% capture step1_rest %} GET /_nodes/hot_threads -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.nodes.info( + node_id_or_metric = "hot_threads" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response ```bash ::: {opensearch}{F-ByTQzVQ3GQeYzQJArJGQ}{GxbcLdCATPWggOuQHJAoCw}{127.0.0.1}{127.0.0.1:9300}{dimr}{shard_indexing_pressure_enabled=true} @@ -65,7 +76,7 @@ GET /_nodes/hot_threads org.opensearch.performanceanalyzer.collectors.ScheduledMetricCollectorsExecutor.run(ScheduledMetricCollectorsExecutor.java:100) ``` -## Response +## Example response Unlike the majority of OpenSearch API responses, this response is in a text format. @@ -79,7 +90,7 @@ Line segment | Description `{global-eu-35}` | Node name. `{uFPbKLDOTlOmdnwUlKW8sw}` | NodeId. `{OAM8OT5CQAyasWuIDeVyUA}` | EphemeralId. -`{global-eu-35.local}` | Host name. +`{global-eu-35.local}` | Hostname. `{[gdv2:a284:2acv:5fa6:0:3a2:7260:74cf]:9300}` | Host address. `{dimr}` | Node roles (d=data, i=ingest, m=cluster manager, r=remote cluster client). `{zone=west-a2, shard_indexing_pressure_enabled=true}` | Node attributes. diff --git a/_api-reference/nodes-apis/nodes-info.md b/_api-reference/nodes-apis/nodes-info.md index d7c81041..3d3a4067 100644 --- a/_api-reference/nodes-apis/nodes-info.md +++ b/_api-reference/nodes-apis/nodes-info.md @@ -5,11 +5,11 @@ parent: Nodes APIs nav_order: 10 --- -# Nodes info +# Nodes Info API **Introduced 1.0** {: .label .label-purple } -The nodes info API represents mostly static information about your cluster's nodes, including but not limited to: +The Nodes Info API represents mostly static information about your cluster's nodes, including the following: - Host system information - JVM @@ -18,31 +18,16 @@ The nodes info API represents mostly static information about your cluster's nod - Thread pools settings - Installed plugins -## Example -To get information about all nodes in a cluster, use the following query: +## Endpoints ```json GET /_nodes -``` -{% include copy-curl.html %} - -To get thread pool information about the cluster manager node only, use the following query: - -```json -GET /_nodes/master:true/thread_pool -``` -{% include copy-curl.html %} - -## Path and HTTP methods - -```bash -GET /_nodes -GET /_nodes/ -GET /_nodes/ -GET /_nodes// +GET /_nodes/{nodeId} +GET /_nodes/{metrics} +GET /_nodes/{nodeId}/{metrics} # or full path equivalent -GET /_nodes//info/ +GET /_nodes/{nodeId}/info/{metrics} ``` ## Path parameters @@ -51,24 +36,25 @@ The following table lists the available path parameters. All path parameters are Parameter | Type | Description :--- |:-------| :--- -nodeId | String | A comma-separated list of nodeIds used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. -metrics | String | A comma-separated list of metric groups that will be included in the response. For example, `jvm,thread_pool`. Defaults to all metrics. +`node_id` | String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. +`metrics` | String | A comma-separated list of metric groups that will be included in the response. For example, `jvm,thread_pool`. Defaults to all metrics. The following table lists all available metric groups. Metric | Description :--- |:---- -settings | A node's settings. This is a combination of the default settings, custom settings from the [configuration file]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/#configuration-file), and dynamically [updated settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/#updating-cluster-settings-using-the-api). -os | Static information about the host OS, including version, processor architecture, and available/allocated processors. -process | Contains the process ID. -jvm | Detailed static information about the running JVM, including arguments. -thread_pool | Configured options for all individual thread pools. -transport | Mostly static information about the transport layer. -http | Mostly static information about the HTTP layer. -plugins | Information about installed plugins and modules. -ingest | Information about ingest pipelines and available ingest processors. -aggregations | Information about available [aggregations]({{site.url}}{{site.baseurl}}/opensearch/aggregations). -indices | Static index settings configured at the node level. +`settings` | A node's settings. This is a combination of the default settings, custom settings from the [configuration file]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/#configuration-file), and dynamically [updated settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/#updating-cluster-settings-using-the-api). +`os` | Static information about the host operating system, including version, processor architecture, and available/allocated processors. +`process` | Contains the process ID. +`jvm` | Detailed static information about the running JVM, including arguments. +`thread_pool` | Configured options for all individual thread pools. +`transport` | Mostly static information about the transport layer. +`http` | Mostly static information about the HTTP layer. +`plugins` | Information about installed plugins and modules. +`ingest` | Information about ingest pipelines and available ingest processors. +`search_pipelines` | Information about search pipelines configured on the node. +`aggregations` | Information about available [aggregations]({{site.url}}{{site.baseurl}}/opensearch/aggregations/). +`indices` | Static index settings configured at the node level. ## Query parameters @@ -76,19 +62,62 @@ You can include the following query parameters in your request. All query parame Parameter | Type | Description :--- |:-------| :--- -flat_settings| Boolean | Specifies whether to return the `settings` object of the response in flat format. Default is `false`. -timeout | Time | Sets the time limit for node response. Default value is `30s`. +`flat_settings`| Boolean | Specifies whether to return the `settings` object of the response in flat format. Default is `false`. +`timeout` | Time | Sets the time limit for node response. Default value is `30s`. -#### Example request +## Example request The following query requests the `process` and `transport` metrics from the cluster manager node: -```json + +{% capture step1_rest %} GET /_nodes/cluster_manager:true/process,transport -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.nodes.info( + metric = "process,transport", + node_id = "cluster_manager:true" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To get thread pool information about the cluster manager node only, use the following query: + + +{% capture step1_rest %} +GET /_nodes/master:true/thread_pool +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.info( + metric = "thread_pool", + node_id = "master:true" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The response contains the metric groups specified in the `` request parameter (in this case, `process` and `transport`): @@ -136,32 +165,33 @@ The response contains the metric groups specified in the `` request par } ``` -## Response fields +## Response body fields The response contains the basic node identification and build info for every node matching the `` request parameter. The following table lists the response fields. Field | Description :--- |:---- name | The node's name. -transport_address | The node's transport address. -host | The node's host address. -ip | The node's host IP address. -version | The node's OpenSearch version. -build_type | The node's build type, like `rpm`, `docker`, `tar`, etc. -build_hash | The git commit hash of the build. -total_indexing_buffer | The maximum heap size in bytes used to hold newly indexed documents. Once this heap size is exceeded, the documents are written to disk. -roles | The list of the node's roles. -attributes | The node's attributes. -os | Information about the OS, including name, version, architecture, refresh interval, and the number of available and allocated processors. -process | Information about the currently running process, including PID, refresh interval, and `mlockall`, which specifies whether the process address space has been successfully locked in memory. -jvm | Information about the JVM, including PID, version, memory information, garbage collector information, and arguments. -thread_pool | Information about the thread pool. -transport | Information about the transport address, including bound address, publish address, and profiles. -http | Information about the HTTP address, including bound address, publish address, and maximum content length, in bytes. -plugins | Information about the installed plugins, including name, version, OpenSearch version, Java version, description, class name, custom folder name, a list of extended plugins, and `has_native_controller`, which specifies whether the plugin has a native controller process. -modules | Information about the modules, including name, version, OpenSearch version, Java version, description, class name, custom folder name, a list of extended plugins, and `has_native_controller`, which specifies whether the plugin has a native controller process. Modules are different from plugins because modules are loaded into OpenSearch automatically, while plugins have to be installed manually. -ingest | Information about ingest pipelines and processors. -aggregations | Information about the available aggregation types. +`transport_address` | The node's transport address. +`host` | The node's host address. +`ip` | The node's host IP address. +`version` | The node's OpenSearch version. +`build_type` | The node's build type, such as `rpm`, `docker`, or `tar`. +`build_hash` | The git commit hash of the build. +`total_indexing_buffer` | The maximum heap size in bytes used to hold newly indexed documents. Once this heap size is exceeded, the documents are written to disk. +`roles` | The list of the node's roles. +`attributes` | The node's attributes. +`os` | Information about the operating system, including name, version, architecture, refresh interval, and the number of available and allocated processors. +`process` | Information about the currently running process, including PID, refresh interval, and `mlockall`, which specifies whether the process address space has been successfully locked in memory. +`jvm` | Information about the JVM, including PID, version, memory information, garbage collector information, and arguments. +`thread_pool` | Information about the thread pool. +`transport` | Information about the transport address, including bound address, publish address, and profiles. +`http` | Information about the HTTP address, including bound address, publish address, and maximum content length, in bytes. +`plugins` | Information about the installed plugins, including name, version, OpenSearch version, Java version, description, class name, custom folder name, a list of extended plugins, and `has_native_controller`, which specifies whether the plugin has a native controller process. +`modules` | Information about the modules, including name, version, OpenSearch version, Java version, description, class name, custom folder name, a list of extended plugins, and `has_native_controller`, which specifies whether the plugin has a native controller process. Modules are different from plugins because modules are loaded into OpenSearch automatically, while plugins have to be installed manually. +`ingest` | Information about ingest pipelines and processors. +`search_pipelines` | Information about search pipelines configured on the node. +`aggregations` | Information about the available aggregation types. ## Required permissions diff --git a/_api-reference/nodes-apis/nodes-reload-secure.md b/_api-reference/nodes-apis/nodes-reload-secure.md index 52b2ef67..23d17057 100644 --- a/_api-reference/nodes-apis/nodes-reload-secure.md +++ b/_api-reference/nodes-apis/nodes-reload-secure.md @@ -5,17 +5,17 @@ parent: Nodes APIs nav_order: 50 --- -# Nodes reload secure settings +# Nodes Reload Secure Settings API **Introduced 1.0** {: .label .label-purple } The nodes reload secure settings endpoint allows you to change secure settings on a node and reload the secure settings without restarting the node. -## Path and HTTP methods +## Endpoints -``` +```json POST _nodes/reload_secure_settings -POST _nodes//reload_secure_settings +POST _nodes/{node_id}/reload_secure_settings ``` ## Path parameter @@ -24,9 +24,9 @@ You can include the following optional path parameter in your request. Parameter | Type | Description :--- | :--- | :--- -nodeId | String | A comma-separated list of nodeIds used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. +`node_id` | String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. -## Request fields +## Request body fields The request may include an optional object containing the password for the OpenSearch keystore. @@ -36,16 +36,29 @@ The request may include an optional object containing the password for the OpenS } ``` -#### Example request +## Example request The following is an example API request: -``` -POST _nodes/reload_secure_settings -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +POST /_nodes/reload_secure_settings +{% endcapture %} -#### Example response +{% capture step1_python %} + +response = client.nodes.reload_secure_settings() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The following is an example response: diff --git a/_api-reference/nodes-apis/nodes-stats.md b/_api-reference/nodes-apis/nodes-stats.md index 4fdb5c3c..47036026 100644 --- a/_api-reference/nodes-apis/nodes-stats.md +++ b/_api-reference/nodes-apis/nodes-stats.md @@ -5,21 +5,21 @@ parent: Nodes APIs nav_order: 20 --- -# Nodes stats +# Nodes Stats API **Introduced 1.0** {: .label .label-purple } -The nodes stats API returns statistics about your cluster. +The Nodes Stats API returns statistics about your cluster. -## Path and HTTP methods +## Endpoints ```json GET /_nodes/stats -GET /_nodes//stats -GET /_nodes/stats/ -GET /_nodes//stats/ -GET /_nodes/stats// -GET /_nodes//stats// +GET /_nodes/{node_id}/stats +GET /_nodes/stats/{metric} +GET /_nodes/{node_id}/stats/{metric} +GET /_nodes/stats/{metric}/{index_metric} +GET /_nodes/{node_id}/stats/{metric}/{index_metric} ``` ## Path parameters @@ -28,31 +28,38 @@ The following table lists the available path parameters. All path parameters are Parameter | Type | Description :--- | :--- | :--- -nodeId | String | A comma-separated list of nodeIds used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. -metric | String | A comma-separated list of metric groups that are included in the response. For example, `jvm,fs`. See the following list of all index metrics. Defaults to all metrics. -index_metric | String | A comma-separated list of index metric groups that are included in the response. For example, `docs,store`. See the following list of all index metrics. Defaults to all index metrics. +`node_id` | String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. +`metric` | String | A comma-separated list of metric groups that are included in the response. For example, `jvm,fs`. See the following list of all index metrics. Defaults to all metrics. +`index_metric` | String | A comma-separated list of index metric groups that are included in the response. For example, `docs,store`. See the following list of all index metrics. Defaults to all index metrics. The following table lists all available metric groups. Metric | Description :--- |:---- -indices | Index statistics, such as size, document count, and search, index, and delete times for documents. -os | Statistics about the host OS, including load, memory, and swapping. -process | Statistics about processes, including their memory consumption, open file descriptors, and CPU usage. -jvm | Statistics about the JVM, including memory pool, buffer pool, and garbage collection, and the number of loaded classes. -fs | File system statistics, such as read/write statistics, data path, and free disk space. -transport | Transport layer statistics about send/receive in cluster communication. -http | Statistics about the HTTP layer. -breaker | Statistics about the field data circuit breakers. -script | Statistics about scripts, such as compilations and cache evictions. -discovery | Statistics about cluster states. -ingest | Statistics about ingest pipelines. -adaptive_selection | Statistics about adaptive replica selection, which selects an eligible node using shard allocation awareness. -script_cache | Statistics about script cache. -indexing_pressure | Statistics about the node's indexing pressure. -shard_indexing_pressure | Statistics about shard indexing pressure. -resource_usage_stats | Node-level resource usage statistics, such as CPU and JVM memory. -admission_control | Statistics about admission control. +`indices` | Index statistics, such as size, document count, and search, index, and delete times for documents. +`os` | Statistics about the host operating system, including load, memory, and swapping. +`process` | Statistics about processes, including their memory consumption, open file descriptors, and CPU usage. +`jvm` | Statistics about the JVM, including memory pool, buffer pool, and garbage collection, and the number of loaded classes. +`thread_pool` | Statistics about each thread pool for the node. +`fs` | File system statistics, such as read/write statistics, data path, and free disk space. +`transport` | Transport layer statistics about send/receive in cluster communication. +`http` | Statistics about the HTTP layer. +`breaker` | Statistics about the field data circuit breakers. +`script` | Statistics about scripts, such as compilations and cache evictions. +`discovery` | Statistics about cluster states. +`ingest` | Statistics about ingest pipelines. +`adaptive_selection` | Statistics about adaptive replica selection, which selects an eligible node using shard allocation awareness. +`script_cache` | Statistics about script cache. +`indexing_pressure` | Statistics about the node's indexing pressure. +`shard_indexing_pressure` | Statistics about shard indexing pressure. +`search_backpressure` | Statistics related to search backpressure. +`cluster_manager_throttling` | Statistics related to throttled tasks on the cluster manager node. +`task_cancellation` | Statistics about tasks that continue running after cancellation. +`weighted_routing` | Statistics relevant to weighted round robin requests. +`resource_usage_stats` | Node-level resource usage statistics, such as CPU and JVM memory. +`admission_control` | Statistics about admission control. +`concurrency_limiter` | Statistics about adaptive concurrency limiters. +`caches` | Statistics about caches. To filter the information returned for the `indices` metric, you can use specific `index_metric` values. You can use these only when you use the following query types: @@ -64,28 +71,76 @@ GET _nodes/stats/indices The following index metrics are supported: -- docs -- store -- indexing -- get -- search -- merge -- refresh -- flush -- warmer -- query_cache -- fielddata -- completion -- segments -- translog -- request_cache +- `docs` +- `store` +- `indexing` +- `get` +- `search` +- `merge` +- `refresh` +- `flush` +- `warmer` +- `query_cache` +- `fielddata` +- `completion` +- `segments` +- `translog` +- `request_cache` For example, the following query requests statistics for `docs` and `search`: -```json -GET _nodes/stats/indices/docs,search -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_nodes/stats/indices/docs,search +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.stats( + metric = "indices", + index_metric = "docs,search" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can also use specific `index_metric` values in the `caches` metric to specify which caches will return statistics. +The following index metrics are supported: + +- request_cache + +For example, the following query requests statistics for the `request_cache`: + + +{% capture step1_rest %} +GET /_nodes/stats/caches/request_cache +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.stats( + metric = "caches", + index_metric = "request_cache" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + ## Query parameters @@ -93,22 +148,39 @@ The following table lists the available query parameters. All query parameters a Parameter | Type | Description :--- | :--- | :--- -completion_fields | String | The fields to include in completion statistics. Supports comma-separated lists and wildcard expressions. -fielddata_fields | String | The fields to include in fielddata statistics. Supports comma-separated lists and wildcard expressions. -fields | String | The fields to include. Supports comma-separated lists and wildcard expressions. -groups | String | A comma-separated list of search groups to include in the search statistics. -level | String | Specifies whether statistics are aggregated at the cluster, index, or shard level. Valid values are `indices`, `node`, and `shard`. -timeout | Time | Sets the time limit for node response. Default is `30s`. -include_segment_file_sizes | Boolean | If segment statistics are requested, this field specifies to return the aggregated disk usage of every Lucene index file. Default is `false`. +`completion_fields` | String | The fields to include in completion statistics. Supports comma-separated lists and wildcard expressions. +`fielddata_fields` | String | The fields to include in `fielddata` statistics. Supports comma-separated lists and wildcard expressions. +`fields` | String | The fields to include. Supports comma-separated lists and wildcard expressions. +`groups` | String | A comma-separated list of search groups to include in the search statistics. +`level` | String | Specifies whether statistics for the `indices` metric are aggregated at the cluster, index, or shard level. Valid values are `indices`, `node`, and `shard`. When used for the `caches` metric, `indices`, `shard`, and `tier` are valid. The `tier` value is ignored if the [tiered spillover cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/tiered-cache/) is not in use. +`timeout` | Time | Sets the time limit for node response. Default is `30s`. +`include_segment_file_sizes` | Boolean | If segment statistics are requested, this field specifies to return the aggregated disk usage of every Lucene index file. Default is `false`. -#### Example request +## Example request -```json -GET _nodes/stats/ -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_nodes/stats +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.nodes.info( + node_id_or_metric = "stats" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response Select the arrow to view the example response. @@ -177,6 +249,7 @@ Select the arrow to view the example response. "query_total": 194, "query_time_in_millis": 467, "query_current": 0, + "query_failed": 0, "fetch_total": 194, "fetch_time_in_millis": 143, "fetch_current": 0, @@ -189,6 +262,7 @@ Select the arrow to view the example response. "suggest_total": 0, "suggest_time_in_millis": 0, "suggest_current": 0, + "search_idle_reactivate_count_total": 0, "request" : { "dfs_pre_query" : { "time_in_millis" : 0, @@ -340,6 +414,18 @@ Select the arrow to view the example response. "current_as_source" : 0, "current_as_target" : 0, "throttle_time_in_millis" : 0 + }, + "status_counter" : { + "doc_status" : { + "success" : 204, + "user_error" : 0, + "system_failure" : 0 + }, + "search_response_status" : { + "success" : 92, + "user_error" : 3, + "system_failure" : 0 + } } }, "os" : { @@ -731,7 +817,10 @@ Select the arrow to view the example response. "nxLWtMdXQmWA-ZBVWU8nwA": { "timestamp": 1698401391000, "cpu_utilization_percent": "0.1", - "memory_utilization_percent": "3.9" + "memory_utilization_percent": "3.9", + "io_usage_stats": { + "max_io_utilization_percent": "99.6" + } } }, "admission_control": { @@ -742,6 +831,24 @@ Select the arrow to view the example response. "indexing": 1 } } + }, + "global_io_usage": { + "transport": { + "rejection_count": { + "search": 3, + "indexing": 1 + } + } + } + }, + "caches" : { + "request_cache" : { + "size_in_bytes" : 1649, + "evictions" : 0, + "hit_count" : 0, + "miss_count" : 18, + "item_count" : 18, + "store_name" : "opensearch_onheap" } } } @@ -750,18 +857,18 @@ Select the arrow to view the example response. ``` -## Response fields +## Response body fields The following table lists all response fields. | Field | Data type | Description | | :--- | :--- | :--- | -| _nodes | Object | Statistics about the nodes that are returned. | -| _nodes.total | Integer | The total number of nodes for this request. | -| _nodes.successful | Integer | The number of nodes for which the request was successful. | -| _nodes.failed | Integer | The number of nodes for which the request failed. If there are nodes for which the request failed, the failure message is included. | -| cluster_name | String | The name of the cluster. | -| [nodes](#nodes) | Object | Statistics for the nodes included in this request. | +| `_nodes` | Object | Statistics about the nodes that are returned. | +| `_nodes.total` | Integer | The total number of nodes for this request. | +| `_nodes.successful` | Integer | The number of nodes for which the request was successful. | +| `_nodes.failed` | Integer | The number of nodes for which the request failed. If there are nodes for which the request failed, the failure message is included. | +| `cluster_name` | String | The name of the cluster. | +| [`nodes`](#nodes) | Object | Statistics for the nodes included in this request. | ### `nodes` @@ -769,35 +876,40 @@ The `nodes` object contains all nodes that are returned by the request, along wi Field | Data type | Description :--- | :--- | :--- -timestamp | Integer | The time the nodes statistics were collected, in milliseconds since the epoch. -name | String | The name of the node. -transport_address | IP address | The host and port of the transport layer that is used by nodes in a cluster to communicate internally. -host | IP address | The network host of the node. -ip | IP address | The IP address and port of the node. -roles | Array | The roles of the node (for example, `cluster_manager`, `data`, or `ingest`). -attributes | Object | The attributes of the node (for example, `shard_indexing_pressure_enabled`). -[indices](#indices) | Object | Index statistics for each index that has shards on the node. -[os](#os) | Object | Statistics about the OS for the node. -[process](#process) | Object | Process statistics for the node. -[jvm](#jvm) | Object | Statistics about the JVM for the node. -[thread_pool](#thread_pool)| Object | Statistics about each thread pool for the node. -[fs](#fs) | Object | Statistics about the file stores for the node. -[transport](#transport) | Object | Transport statistics for the node. -http | Object | HTTP statistics for the node. -http.current_open | Integer | The number of currently open HTTP connections for the node. -http.total_opened | Integer | The total number of HTTP connections the node has opened since it started. -[breakers](#breakers) | Object | Statistics about the circuit breakers for the node. -[script](#script-and-script_cache)| Object | Script statistics for the node. -[script_cache](#script-and-script_cache)| Object | Script cache statistics for the node. -[discovery](#discovery) | Object | Node discovery statistics for the node. -[ingest](#ingest) | Object | Ingest statistics for the node. -[search_pipeline](#search_pipeline) | Object | Statistics related to [search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/). -[adaptive_selection](#adaptive_selection) | Object | Statistics about adaptive selections for the node. -[indexing_pressure](#indexing_pressure) | Object | Statistics related to the node's indexing pressure. -[shard_indexing_pressure](#shard_indexing_pressure) | Object | Statistics related to indexing pressure at the shard level. -[search_backpressure]({{site.url}}{{site.baseurl}}/opensearch/search-backpressure#search-backpressure-stats-api) | Object | Statistics related to search backpressure. -[resource_usage_stats](#resource_usage_stats) | Object | Statistics related to resource usage for the node. -[admission_control](#admission_control) | Object | Statistics related to admission control for the node. +`timestamp` | Integer | The time the nodes statistics were collected, in milliseconds since the epoch. +`name` | String | The name of the node. +`transport_address` | IP address | The host and port of the transport layer that is used by nodes in a cluster to communicate internally. +`host` | IP address | The network host of the node. +`ip` | IP address | The IP address and port of the node. +`roles` | Array | The roles of the node (for example, `cluster_manager`, `data`, or `ingest`). +`attributes` | Object | The attributes of the node (for example, `shard_indexing_pressure_enabled`). +[`indices`](#indices) | Object | Index statistics for each index that has shards on the node. +[`os`](#os) | Object | Statistics about the operating system for the node. +[`process`](#process) | Object | Process statistics for the node. +[`jvm`](#jvm) | Object | Statistics about the JVM for the node. +[`thread_pool`](#thread_pool)| Object | Statistics about each thread pool for the node. +[`fs`](#fs) | Object | Statistics about the file stores for the node. +[`transport`](#transport) | Object | Transport statistics for the node. +`http` | Object | HTTP statistics for the node. +`http.current_open` | Integer | The number of currently open HTTP connections for the node. +`http.total_opened` | Integer | The total number of HTTP connections the node has opened since it started. +[`breakers`](#breakers) | Object | Statistics about the circuit breakers for the node. +[`script`](#script-and-script_cache)| Object | Script statistics for the node. +[`script_cache`](#script-and-script_cache)| Object | Script cache statistics for the node. +[`discovery`](#discovery) | Object | Node discovery statistics for the node. +[`ingest`](#ingest) | Object | Ingest statistics for the node. +[`search_pipeline`](#search_pipeline) | Object | Statistics related to [search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/). +[`adaptive_selection`](#adaptive_selection) | Object | Statistics about adaptive selections for the node. +[`indexing_pressure`](#indexing_pressure) | Object | Statistics related to the node's indexing pressure. +[`shard_indexing_pressure`](#shard_indexing_pressure) | Object | Statistics related to indexing pressure at the shard level. +[`search_backpressure`]({{site.url}}{{site.baseurl}}/opensearch/search-backpressure#search-backpressure-stats-api) | Object | Statistics related to search backpressure. +[`cluster_manager_throttling`](#cluster_manager_throttling) | Object | Statistics related to throttled tasks on the cluster manager node. +[`task_cancellation`](#task_cancellation) | Object | Statistics about tasks that continue running after cancellation. +[`weighted_routing`](#weighted_routing) | Object | Statistics relevant to weighted round robin requests. +[`resource_usage_stats`](#resource_usage_stats) | Object | Statistics related to resource usage for the node. +[`admission_control`](#admission_control) | Object | Statistics related to admission control for the node. +[`concurrency_limiters`](#concurrency_limiters) | Object | Statistics related to adaptive concurrency limiters for the node. Returned when you request the `concurrency_limiter` metric. +[`caches`](#caches) | Object | Statistics related to caches on the node. ### `indices` @@ -805,201 +917,219 @@ The `indices` object contains the index statistics for each index with shards on Field | Field type | Description :--- | :--- | :--- -docs | Object | Document statistics for all primary shards that exist on the node. -docs.count | Integer | The number of documents reported by Lucene. Excludes deleted documents and recently indexed documents that are not yet assigned to a segment. Nested documents are counted separately. -docs.deleted | Integer | The number of deleted documents reported by Lucene. Excludes recent deletion operations that have not yet affect the segment. -store | Object | Statistics about the shard sizes of the shards on the node. -store.size_in_bytes | Integer | Total size of all shards on the node. -store.reserved_in_bytes | Integer | The predicted number of bytes the shard store will grow to be because of activities such as restoring snapshots and peer recoveries. -indexing | Object | Statistics about indexing operations for the node. -indexing.index_total | Integer | The total number of indexing operations on the node. -indexing.index_time_in_millis | Integer | The total time for all indexing operations, in milliseconds. -indexing.index_current | Integer | The number of indexing operations that are currently running. -indexing.index_failed | Integer | The number of indexing operations that have failed. -indexing.delete_total | Integer | The total number of deletions. -indexing.delete_time_in_millis | Integer | The total time for all deletion operations, in milliseconds. -indexing.delete_current | Integer | The number of deletion operations that are currently running. -indexing.noop_update_total | Integer | The total number of noop operations. -indexing.is_throttled | Boolean | Specifies whether any operations were throttled. -indexing.throttle_time_in_millis | Integer | The total time for throttling operations, in milliseconds. -get | Object | Statistics about the get operations for the node. -get.total | Integer | The total number of get operations. -get.time_in_millis | Integer | The total time for all get operations, in milliseconds. -get.exists_total | Integer | The total number of successful get operations. -get.exists_time_in_millis | Integer | The total time for all successful get operations, in milliseconds. -get.missing_total | Integer | The number of failed get operations. -get.missing_time_in_millis | Integer | The total time for all failed get operations, in milliseconds. -get.current | Integer | The number of get operations that are currently running. -search | Object | Statistics about the search operations for the node. -search.concurrent_avg_slice_count | Integer | The average slice count of all search requests. This is computed as the total slice count divided by the total number of concurrent search requests. -search.concurrent_query_total |Integer | The total number of query operations that use concurrent segment search. -search.concurrent_query_time_in_millis | Integer | The total amount of time taken by all query operations that use concurrent segment search, in milliseconds. -search.concurrent_query_current |Integer | The number of currently running query operations that use concurrent segment search. -search.open_contexts | Integer | The number of open search contexts. -search.query_total | Integer | The total number of shard query operations. -search.query_time_in_millis | Integer | The total amount of time for all shard query operations, in milliseconds. -search.query_current | Integer | The number of shard query operations that are currently running. -search.fetch_total | Integer | The total number of shard fetch operations. -search.fetch_time_in_millis | Integer | The total amount of time for all shard fetch operations, in milliseconds. -search.fetch_current | Integer | The number of shard fetch operations that are currently running. -search.scroll_total | Integer | The total number of shard scroll operations. -search.scroll_time_in_millis | Integer | The total amount of time for all shard scroll operations, in milliseconds. -search.scroll_current | Integer | The number of shard scroll operations that are currently running. -search.point_in_time_total | Integer | The total number of shard Point in Time (PIT) contexts that have been created (completed and active) since the node last restarted. -search.point_in_time_time_in_millis | Integer | The amount of time that shard PIT contexts have been held open since the node last restarted, in milliseconds. -search.point_in_time_current | Integer | The number of shard PIT contexts currently open. -search.suggest_total | Integer | The total number of shard suggest operations. -search.suggest_time_in_millis | Integer | The total amount of time for all shard suggest operations, in milliseconds. -search.suggest_current | Integer | The number of shard suggest operations that are currently running. -search.request | Object | Statistics about coordinator search operations for the node. -search.request.dfs_pre_query.time_in_millis | Integer | The total amount of time for all coordinator depth-first search (DFS) prequery operations, in milliseconds. -search.request.dfs_pre_query.current | Integer | The number of coordinator DFS prequery operations that are currently running. -search.request.dfs_pre_query.total | Integer | The total number of coordinator DFS prequery operations. -search.request.query.time_in_millis | Integer | The total amount of time for all coordinator query operations, in milliseconds. -search.request.query.current | Integer | The number of coordinator query operations that are currently running. -search.request.query.total | Integer | The total number of coordinator query operations. -search.request.fetch.time_in_millis | Integer | The total amount of time for all coordinator fetch operations, in milliseconds. -search.request.fetch.current | Integer | The number of coordinator fetch operations that are currently running. -search.request.fetch.total | Integer | The total number of coordinator fetch operations. -search.request.dfs_query.time_in_millis | Integer | The total amount of time for all coordinator DFS prequery operations, in milliseconds. -search.request.dfs_query.current | Integer | The number of coordinator DFS prequery operations that are currently running. -search.request.dfs_query.total | Integer | The total number of coordinator DFS prequery operations. -search.request.expand.time_in_millis | Integer | The total amount of time for all coordinator expand operations, in milliseconds. -search.request.expand.current | Integer | The number of coordinator expand operations that are currently running. -search.request.expand.total | Integer | The total number of coordinator expand operations. -search.request.can_match.time_in_millis | Integer | The total amount of time for all coordinator match operations, in milliseconds. -search.request.can_match.current | Integer | The number of coordinator match operations that are currently running. -search.request.can_match.total | Integer | The total number of coordinator match operations. -merges | Object | Statistics about merge operations for the node. -merges.current | Integer | The number of merge operations that are currently running. -merges.current_docs | Integer | The number of document merges that are currently running. -merges.current_size_in_bytes | Integer | The memory size, in bytes, that is used to perform current merge operations. -merges.total | Integer | The total number of merge operations. -merges.total_time_in_millis | Integer | The total time for merges, in milliseconds. -merges.total_docs | Integer | The total number of documents that have been merged. -merges.total_size_in_bytes | Integer | The total size of all merged documents, in bytes. -merges.total_stopped_time_in_millis | Integer | The total time spent on stopping merge operations, in milliseconds. -merges.total_throttled_time_in_millis | Integer | The total time spent on throttling merge operations, in milliseconds. -merges.total_auto_throttle_in_bytes | Integer | The total size of automatically throttled merge operations, in bytes. -refresh | Object | Statistics about refresh operations for the node. -refresh.total | Integer | The total number of refresh operations. -refresh.total_time_in_millis | Integer | The total time for all refresh operations, in milliseconds. -refresh.external_total | Integer | The total number of external refresh operations. -refresh.external_total_time_in_millis | Integer | The total time for all external refresh operations, in milliseconds. -refresh.listeners | Integer | The number of refresh listeners. -flush | Object | Statistics about flush operations for the node. -flush.total | Integer | The total number of flush operations. -flush.periodic | Integer | The total number of periodic flush operations. -flush.total_time_in_millis | Integer | The total time for all flush operations, in milliseconds. -warmer | Object | Statistics about the index warming operations for the node. -warmer.current | Integer | The number of current index warming operations. -warmer.total | Integer | The total number of index warming operations. -warmer.total_time_in_millis | Integer | The total time for all index warming operations, in milliseconds. -query_cache | Statistics about query cache operations for the node. -query_cache.memory_size_in_bytes | Integer | The amount of memory used for the query cache for all shards in the node. -query_cache.total_count | Integer | The total number of hits, misses, and cached queries in the query cache. -query_cache.hit_count | Integer | The total number of hits in the query cache. -query_cache.miss_count | Integer | The total number of misses in the query cache. -query_cache.cache_size | Integer | The size of the query cache, in bytes. -query_cache.cache_count | Integer | The number of queries in the query cache. -query_cache.evictions | Integer | The number of evictions in the query cache. -fielddata | Object | Statistics about the field data cache for all shards in the node. -fielddata.memory_size_in_bytes | Integer | The total amount of memory used for the field data cache for all shards in the node. -fielddata.evictions | Integer | The number of evictions in the field data cache. -fielddata.fields | Object | Contains all field data fields. -completion | Object | Statistics about completions for all shards in the node. -completion.size_in_bytes | Integer | The total amount of memory used for completion for all shards in the node, in bytes. -completion.fields | Object | Contains completion fields. -segments | Object | Statistics about segments for all shards in the node. -segments.count | Integer | The total number of segments. -segments.memory_in_bytes | Integer | The total amount of memory, in bytes. -segments.terms_memory_in_bytes | Integer | The total amount of memory used for terms, in bytes. -segments.stored_fields_memory_in_bytes | Integer | The total amount of memory used for stored fields, in bytes. -segments.term_vectors_memory_in_bytes | Integer | The total amount of memory used for term vectors, in bytes. -segments.norms_memory_in_bytes | Integer | The total amount of memory used for normalization factors, in bytes. -segments.points_memory_in_bytes | Integer | The total amount of memory used for points, in bytes. -segments.doc_values_memory_in_bytes | Integer | The total amount of memory used for doc values, in bytes. -segments.index_writer_memory_in_bytes | Integer | The total amount of memory used by all index writers, in bytes. -segments.version_map_memory_in_bytes | Integer | The total amount of memory used by all version maps, in bytes. -segments.fixed_bit_set_memory_in_bytes | Integer | The total amount of memory used by fixed bit sets, in bytes. Fixed bit sets are used for nested objects and join fields. -segments.max_unsafe_auto_id_timestamp | Integer | The timestamp for the most recently retired indexing request, in milliseconds since the epoch. -segments.segment_replication | Object | Segment replication statistics for all primary shards when segment replication is enabled on the node. -segments.segment_replication.max_bytes_behind | long | The maximum number of bytes behind the primary replica. -segments.segment_replication.total_bytes_behind | long | The total number of bytes behind the primary replicas. -segments.segment_replication.max_replication_lag | long | The maximum amount of time, in milliseconds, taken by a replica to catch up to its primary. -segments.remote_store | Object | Statistics about remote segment store operations. -segments.remote_store.upload | Object | Statistics related to uploads to the remote segment store. -segments.remote_store.upload.total_upload_size | Object | The amount of data, in bytes, uploaded to the remote segment store. -segments.remote_store.upload.total_upload_size.started_bytes | Integer | The number of bytes to upload to the remote segment store after the upload has started. -segments.remote_store.upload.total_upload_size.succeeded_bytes | Integer | The number of bytes successfully uploaded to the remote segment store. -segments.remote_store.upload.total_upload_size.failed_bytes | Integer | The number of bytes that failed to upload to the remote segment store. -segments.remote_store.upload.refresh_size_lag | Object | The amount of lag during upload between the remote segment store and the local store. -segments.remote_store.upload.refresh_size_lag.total_bytes | Integer | The total number of bytes that lagged during the upload refresh between the remote segment store and the local store. -segments.remote_store.upload.refresh_size_lag.max_bytes | Integer | The maximum amount of lag, in bytes, during the upload refresh between the remote segment store and the local store. -segments.remote_store.upload.max_refresh_time_lag_in_millis | Integer | The maximum duration, in milliseconds, that the remote refresh is behind the local refresh. -segments.remote_store.upload.total_time_spent_in_millis | Integer | The total amount of time, in milliseconds, spent on uploads to the remote segment store. -segments.remote_store.upload.pressure | Object | Statistics related to segment store upload backpressure. -segments.remote_store.upload.pressure.total_rejections | Integer | The total number of requests rejected due to segment store upload backpressure. -segments.remote_store.download | Object | Statistics related to downloads to the remote segment store. -segments.remote_store.download.total_download_size | Object | The total amount of data download from the remote segment store. -segments.remote_store.download.total_download_size.started_bytes | Integer | The number of bytes downloaded from the remote segment store after the download starts. -segments.remote_store.download.total_download_size.succeeded_bytes | Integer | The number of bytes successfully downloaded from the remote segment store. -segments.remote_store.download.total_download_size.failed_bytes | Integer | The number of bytes that failed to download from the remote segment store. -segments.remote_store.download.total_time_spent_in_millis | Integer | The total duration, in milliseconds, spent on downloads from the remote segment store. -segments.file_sizes | Integer | Statistics about the size of the segment files. -translog | Object | Statistics about transaction log operations for the node. -translog.operations | Integer | The number of translog operations. -translog.size_in_bytes | Integer | The size of the translog, in bytes. -translog.uncommitted_operations | Integer | The number of uncommitted translog operations. -translog.uncommitted_size_in_bytes | Integer | The size of uncommitted translog operations, in bytes. -translog.earliest_last_modified_age | Integer | The earliest last modified age for the translog. -translog.remote_store | Object | Statistics related to operations from the remote translog store. -translog.remote_store.upload | Object | Statistics related to uploads to the remote translog store. -translog.remote_store.upload.total_uploads | Object | The number of syncs to the remote translog store. -translog.remote_store.upload.total_uploads.started | Integer | The number of upload syncs to the remote translog store that have started. -translog.remote_store.upload.total_uploads.failed | Integer | The number of failed upload syncs to the remote translog store. -translog.remote_store.upload.total_uploads.succeeded | Integer | The number of successful upload syncs to the remote translog store. -translog.remote_store.upload.total_upload_size | Object | The total amount of data uploaded to the remote translog store. -translog.remote_store.upload.total_upload_size.started_bytes | Integer | The number of bytes actively uploading to the remote translog store after the upload has started. -translog.remote_store.upload.total_upload_size.failed_bytes | Integer | The number of bytes that failed to upload to the remote translog store. -translog.remote_store.upload.total_upload_size.succeeded_bytes | Integer | The number of bytes successfully uploaded to the remote translog store. -request_cache | Object | Statistics about the request cache for the node. -request_cache.memory_size_in_bytes | Integer | The memory size used by the request cache, in bytes. -request_cache.evictions | Integer | The number of request cache evictions. -request_cache.hit_count | Integer | The number of request cache hits. -request_cache.miss_count | Integer | The number of request cache misses. -recovery | Object | Statistics about recovery operations for the node. -recovery.current_as_source | Integer | The number of recovery operations that have used an index shard as a source. -recovery.current_as_target | Integer | The number of recovery operations that have used an index shard as a target. -recovery.throttle_time_in_millis | Integer | The delay of recovery operations due to throttling, in milliseconds. +`docs` | `Object` | Document statistics for all primary shards that exist on the node. +`docs.count` | `Integer` | The number of documents reported by Lucene. Excludes deleted documents and recently indexed documents that are not yet assigned to a segment. Nested documents are counted separately. +`docs.deleted` | `Integer` | The number of deleted documents reported by Lucene. Excludes recent deletion operations that have not yet affect the segment. +`store` | `Object` | Statistics about the shard sizes of the shards on the node. +`store.size_in_bytes` | `Integer` | Total size of all shards on the node. +`store.reserved_in_bytes` | `Integer` | The predicted number of bytes the shard store will grow to be because of activities such as restoring snapshots and peer recoveries. +`indexing` | `Object` | Statistics about indexing operations for the node. +`indexing.index_total` | `Integer` | The total number of indexing operations on the node. +`indexing.index_time_in_millis` | `Integer` | The total time for all indexing operations, in milliseconds. +`indexing.index_current` | `Integer` | The number of indexing operations that are currently running. +`indexing.index_failed` | `Integer` | The number of indexing operations that have failed. +`indexing.delete_total` | `Integer` | The total number of deletions. +`indexing.delete_time_in_millis` | `Integer` | The total time for all deletion operations, in milliseconds. +`indexing.delete_current` | `Integer` | The number of deletion operations that are currently running. +`indexing.noop_update_total` | `Integer` | The total number of no-op operations. +`indexing.is_throttled` | `Boolean` | Specifies whether any operations were throttled. +`indexing.throttle_time_in_millis` | `Integer` | The total time for throttling operations, in milliseconds. +`get` | `Object` | Statistics about the get operations for the node. +`get.total` | `Integer` | The total number of get operations. +`get.time_in_millis` | `Integer` | The total time for all get operations, in milliseconds. +`get.exists_total` | `Integer` | The total number of successful get operations. +`get.exists_time_in_millis` | `Integer` | The total time for all successful get operations, in milliseconds. +`get.missing_total` | `Integer` | The number of failed get operations. +`get.missing_time_in_millis` | `Integer` | The total time for all failed get operations, in milliseconds. +`get.current` | `Integer` | The number of get operations that are currently running. +`search` | `Object` | Statistics about the search operations for the node. +`search.concurrent_avg_slice_count` | `Float` | The average slice count of all search requests. This is computed as the total slice count divided by the total number of concurrent search requests. +`search.concurrent_query_total` | `Integer` | The total number of query operations that use concurrent segment search. +`search.concurrent_query_time_in_millis` | `Integer` | The total amount of time taken by all query operations that use concurrent segment search, in milliseconds. +`search.concurrent_query_current` | `Integer` | The number of currently running query operations that use concurrent segment search. +`search.startree_query_total` | `Integer` | The total number of query operations that use a star tree for search. +`search.startree_query_time_in_millis` | `Integer` | The total amount of time taken by all query operations that use a star tree for search, in milliseconds. +`search.startree_query_current` | `Integer` | The number of currently running query operations that use a star tree for search. +`search.startree_query_failed` | `Integer` | The number of failed query operations that use a star tree for search. +`search.open_contexts` | `Integer` | The number of open search contexts. +`search.query_total` | `Integer` | The total number of shard query operations. +`search.query_time_in_millis` | `Integer` | The total amount of time for all shard query operations, in milliseconds. +`search.query_current` | `Integer` | The number of shard query operations that are currently running. +`search.query_failed` | `Integer` | The total number of failed shard query operations. +`search.fetch_total` | `Integer` | The total number of shard fetch operations. +`search.fetch_time_in_millis` | `Integer` | The total amount of time for all shard fetch operations, in milliseconds. +`search.fetch_current` | `Integer` | The number of shard fetch operations that are currently running. +`search.scroll_total` | `Integer` | The total number of shard scroll operations. +`search.scroll_time_in_millis` | `Integer` | The total amount of time for all shard scroll operations, in milliseconds. +`search.scroll_current` | `Integer` | The number of shard scroll operations that are currently running. +`search.point_in_time_total` | `Integer` | The total number of shard Point in Time (PIT) contexts that have been created (completed and active) since the node last restarted. +`search.point_in_time_time_in_millis` | `Integer` | The amount of time that shard PIT contexts have been held open since the node last restarted, in milliseconds. +`search.point_in_time_current` | `Integer` | The number of shard PIT contexts currently open. +`search.suggest_total` | `Integer` | The total number of shard suggest operations. +`search.suggest_time_in_millis` | `Integer` | The total amount of time for all shard suggest operations, in milliseconds. +`search.suggest_current` | `Integer` | The number of shard suggest operations that are currently running. +`search.search_idle_reactivate_count_total` | `Integer` | The total number of times that all shards have been activated from an idle state. +`search.request` | `Object` | Statistics about coordinator search operations for the node. +`search.request.took.time_in_millis` | `Integer` | The total amount of time taken for all search requests, in milliseconds. +`search.request.took.current` | `Integer` | The number of search requests that are currently running. +`search.request.took.total` | `Integer` | The total number of search requests completed. +`search.request.dfs_pre_query.time_in_millis` | `Integer` | The total amount of time for all coordinator depth-first search (DFS) pre-query operations, in milliseconds. +`search.request.dfs_pre_query.current` | `Integer` | The number of coordinator DFS pre-query operations that are currently running. +`search.request.dfs_pre_query.total` | `Integer` | The total number of coordinator DFS pre-query operations completed. +`search.request.query.time_in_millis` | `Integer` | The total amount of time for all coordinator query operations, in milliseconds. +`search.request.query.current` | `Integer` | The number of coordinator query operations that are currently running. +`search.request.query.total` | `Integer` | The total number of coordinator query operations completed. +`search.request.fetch.time_in_millis` | `Integer` | The total amount of time for all coordinator fetch operations, in milliseconds. +`search.request.fetch.current` | `Integer` | The number of coordinator fetch operations that are currently running. +`search.request.fetch.total` | `Integer` | The total number of coordinator fetch operations completed. +`search.request.dfs_query.time_in_millis` | `Integer` | The total amount of time for all coordinator DFS pre-query operations, in milliseconds. +`search.request.dfs_query.current` | `Integer` | The number of coordinator DFS pre-query operations that are currently running. +`search.request.dfs_query.total` | `Integer` | The total number of coordinator DFS pre-query operations completed. +`search.request.expand.time_in_millis` | `Integer` | The total amount of time for all coordinator expand operations, in milliseconds. +`search.request.expand.current` | `Integer` | The number of coordinator expand operations that are currently running. +`search.request.expand.total` | `Integer` | The total number of coordinator expand operations completed. +`search.request.can_match.time_in_millis` | `Integer` | The total amount of time for all coordinator match operations, in milliseconds. +`search.request.can_match.current` | `Integer` | The number of coordinator match operations that are currently running. +`search.request.can_match.total` | `Integer` | The total number of coordinator match operations completed. +`merges` | `Object` | Statistics about merge operations for the node. +`merges.current` | `Integer` | The number of merge operations that are currently running. +`merges.current_docs` | `Integer` | The number of document merges that are currently running. +`merges.current_size_in_bytes` | `Integer` | The memory size, in bytes, that is used to perform current merge operations. +`merges.total` | `Integer` | The total number of merge operations. +`merges.total_time_in_millis` | `Integer` | The total time for merges, in milliseconds. +`merges.total_docs` | `Integer` | The total number of documents that have been merged. +`merges.total_size_in_bytes` | `Integer` | The total size of all merged documents, in bytes. +`merges.total_stopped_time_in_millis` | `Integer` | The total time spent on stopping merge operations, in milliseconds. +`merges.total_throttled_time_in_millis` | `Integer` | The total time spent on throttling merge operations, in milliseconds. +`merges.total_auto_throttle_in_bytes` | `Integer` | The total size of automatically throttled merge operations, in bytes. +`refresh` | `Object` | Statistics about refresh operations for the node. +`refresh.total` | `Integer` | The total number of refresh operations. +`refresh.total_time_in_millis` | `Integer` | The total time for all refresh operations, in milliseconds. +`refresh.external_total` | `Integer` | The total number of external refresh operations. +`refresh.external_total_time_in_millis` | `Integer` | The total time for all external refresh operations, in milliseconds. +`refresh.listeners` | `Integer` | The number of refresh listeners. +`flush` | `Object` | Statistics about flush operations for the node. +`flush.total` | `Integer` | The total number of flush operations. +`flush.periodic` | `Integer` | The total number of periodic flush operations. +`flush.total_time_in_millis` | `Integer` | The total time for all flush operations, in milliseconds. +`warmer` | `Object` | Statistics about the index warming operations for the node. +`warmer.current` | `Integer` | The number of current index warming operations. +`warmer.total` | `Integer` | The total number of index warming operations. +`warmer.total_time_in_millis` | `Integer` | The total time for all index warming operations, in milliseconds. +`query_cache` | Object | Statistics about query cache operations for the node. +`query_cache.memory_size_in_bytes` | Integer | The amount of memory used for the query cache for all shards in the node. +`query_cache.total_count` | Integer | The total number of hits and misses in the query cache. +`query_cache.hit_count` | Integer | The total number of hits in the query cache. +`query_cache.miss_count` | Integer | The total number of misses in the query cache. +`query_cache.cache_size` | Integer | The number of queries currently in the query cache. +`query_cache.cache_count` | Integer | The total number of queries that have been added to the query cache, including those that have since been evicted. +`query_cache.evictions` | Integer | The number of evictions from the query cache. +`fielddata` | Object | Statistics about the field data cache for all shards in the node. +`fielddata.memory_size_in_bytes` | Integer | The total amount of memory used for the field data cache for all shards in the node. +`fielddata.evictions` | Integer | The number of evictions in the field data cache. +`fielddata.fields` | Object | Contains all field data fields. +`completion` | Object | Statistics about completions for all shards in the node. +`completion.size_in_bytes` | Integer | The total amount of memory used for completion for all shards in the node, in bytes. +`completion.fields` | Object | Contains completion fields. +`segments` | Object | Statistics about segments for all shards in the node. +`segments.count` | Integer | The total number of segments. +`segments.memory_in_bytes` | Integer | The total amount of memory, in bytes. +`segments.terms_memory_in_bytes` | Integer | The total amount of memory used for terms, in bytes. +`segments.stored_fields_memory_in_bytes` | Integer | The total amount of memory used for stored fields, in bytes. +`segments.term_vectors_memory_in_bytes` | Integer | The total amount of memory used for term vectors, in bytes. +`segments.norms_memory_in_bytes` | Integer | The total amount of memory used for normalization factors, in bytes. +`segments.points_memory_in_bytes` | Integer | The total amount of memory used for points, in bytes. +`segments.doc_values_memory_in_bytes` | Integer | The total amount of memory used for doc values, in bytes. +`segments.index_writer_memory_in_bytes` | Integer | The total amount of memory used by all index writers, in bytes. +`segments.version_map_memory_in_bytes` | Integer | The total amount of memory used by all version maps, in bytes. +`segments.fixed_bit_set_memory_in_bytes` | Integer | The total amount of memory used by fixed bit sets, in bytes. Fixed bit sets are used for nested objects and join fields. +`segments.max_unsafe_auto_id_timestamp` | Integer | The timestamp for the most recently retired indexing request, in milliseconds since the epoch. +`segments.segment_replication` | Object | Segment replication statistics for all primary shards when segment replication is enabled on the node. +`segments.segment_replication.max_bytes_behind` | long | The maximum number of bytes behind the primary replica. +`segments.segment_replication.total_bytes_behind` | long | The total number of bytes behind the primary replicas. +`segments.segment_replication.max_replication_lag` | long | The maximum amount of time, in milliseconds, taken by a replica to catch up to its primary. +`segments.remote_store` | Object | Statistics about remote segment store operations. +`segments.remote_store.upload` | Object | Statistics related to uploads to the remote segment store. +`segments.remote_store.upload.total_upload_size` | Object | The amount of data, in bytes, uploaded to the remote segment store. +`segments.remote_store.upload.total_upload_size.started_bytes` | Integer | The number of bytes to upload to the remote segment store after the upload has started. +`segments.remote_store.upload.total_upload_size.succeeded_bytes` | Integer | The number of bytes successfully uploaded to the remote segment store. +`segments.remote_store.upload.total_upload_size.failed_bytes` | Integer | The number of bytes that failed to upload to the remote segment store. +`segments.remote_store.upload.refresh_size_lag` | Object | The amount of lag during upload between the remote segment store and the local store. +`segments.remote_store.upload.refresh_size_lag.total_bytes` | Integer | The total number of bytes that lagged during the upload refresh between the remote segment store and the local store. +`segments.remote_store.upload.refresh_size_lag.max_bytes` | Integer | The maximum amount of lag, in bytes, during the upload refresh between the remote segment store and the local store. +`segments.remote_store.upload.max_refresh_time_lag_in_millis` | Integer | The maximum duration, in milliseconds, that the remote refresh is behind the local refresh. +`segments.remote_store.upload.total_time_spent_in_millis` | Integer | The total amount of time, in milliseconds, spent on uploads to the remote segment store. +`segments.remote_store.upload.pressure` | Object | Statistics related to segment store upload backpressure. +`segments.remote_store.upload.pressure.total_rejections` | Integer | The total number of requests rejected due to segment store upload backpressure. +`segments.remote_store.download` | Object | Statistics related to downloads to the remote segment store. +`segments.remote_store.download.total_download_size` | Object | The total amount of data download from the remote segment store. +`segments.remote_store.download.total_download_size.started_bytes` | Integer | The number of bytes downloaded from the remote segment store after the download starts. +`segments.remote_store.download.total_download_size.succeeded_bytes` | Integer | The number of bytes successfully downloaded from the remote segment store. +`segments.remote_store.download.total_download_size.failed_bytes` | Integer | The number of bytes that failed to download from the remote segment store. +`segments.remote_store.download.total_time_spent_in_millis` | Integer | The total duration, in milliseconds, spent on downloads from the remote segment store. +`segments.file_sizes` | Object | Statistics about the size of the segment files, keyed by Lucene file extension. Each entry contains the `size_in_bytes` and `description` fields. Empty unless `include_segment_file_sizes` is `true`. +`translog` | Object | Statistics about transaction log operations for the node. +`translog.operations` | Integer | The number of translog operations. +`translog.size_in_bytes` | Integer | The size of the translog, in bytes. +`translog.uncommitted_operations` | Integer | The number of uncommitted translog operations. +`translog.uncommitted_size_in_bytes` | Integer | The size of uncommitted translog operations, in bytes. +`translog.earliest_last_modified_age` | Integer | The earliest last modified age for the translog. +`translog.remote_store` | Object | Statistics related to operations from the remote translog store. +`translog.remote_store.upload` | Object | Statistics related to uploads to the remote translog store. +`translog.remote_store.upload.total_uploads` | Object | The number of syncs to the remote translog store. +`translog.remote_store.upload.total_uploads.started` | Integer | The number of upload syncs to the remote translog store that have started. +`translog.remote_store.upload.total_uploads.failed` | Integer | The number of failed upload syncs to the remote translog store. +`translog.remote_store.upload.total_uploads.succeeded` | Integer | The number of successful upload syncs to the remote translog store. +`translog.remote_store.upload.total_upload_size` | Object | The total amount of data uploaded to the remote translog store. +`translog.remote_store.upload.total_upload_size.started_bytes` | Integer | The number of bytes actively uploading to the remote translog store after the upload has started. +`translog.remote_store.upload.total_upload_size.failed_bytes` | Integer | The number of bytes that failed to upload to the remote translog store. +`translog.remote_store.upload.total_upload_size.succeeded_bytes` | Integer | The number of bytes successfully uploaded to the remote translog store. +`request_cache` | Object | Statistics about the request cache for the node. +`request_cache.memory_size_in_bytes` | Integer | The memory size used by the request cache, in bytes. +`request_cache.evictions` | Integer | The number of request cache evictions. +`request_cache.hit_count` | Integer | The number of request cache hits. +`request_cache.miss_count` | Integer | The number of request cache misses. +`recovery` | Object | Statistics about recovery operations for the node. +`recovery.current_as_source` | Integer | The number of recovery operations that used an index shard as the source. | +`recovery.current_as_target` | Integer | The number of recovery operations that used an index shard as the target. +`recovery.throttle_time_in_millis` | Integer | The total delay of recovery operations due to throttling, in milliseconds. +`status_counter` | Object | Counts of document write and search responses returned by requests coordinated by this node, grouped by HTTP status class. Counts are kept in memory and reset when the node restarts. +`status_counter.doc_status` | Object | Counts of document write operations (index, create, update, and delete, including bulk items), grouped by HTTP status class. +`status_counter.doc_status.success` | Integer | The number of document write operations that returned a `1xx`, `2xx`, or `3xx` status. +`status_counter.doc_status.user_error` | Integer | The number of document write operations that returned a `4xx` status. +`status_counter.doc_status.system_failure` | Integer | The number of document write operations that returned a `5xx` status. +`status_counter.search_response_status` | Object | Counts of search requests, grouped by the HTTP status class of the response. +`status_counter.search_response_status.success` | Integer | The number of search requests that returned a `1xx`, `2xx`, or `3xx` status. Includes requests that returned partial results because some shards failed. +`status_counter.search_response_status.user_error` | Integer | The number of search requests that returned a `4xx` status, such as a request for a missing index or a rejected request. +`status_counter.search_response_status.system_failure` | Integer | The number of search requests that returned a `5xx` status. ### `os` -The `os` object has the OS statistics for the node and has the following properties. +The `os` object has the operating system statistics for the node and has the following properties. Field | Field type | Description :--- | :--- | :--- -timestamp | Integer | The last refresh time for the OS statistics, in milliseconds since the epoch. -cpu | Object | Statistics about the node's CPU usage. -cpu.percent | Integer | Recent CPU usage for the system. -cpu.load_average | Object | Statistics about load averages for the system. -cpu.load_average.1m | Float | The load average for the system for the time period of one minute. -cpu.load_average.5m | Float | The load average for the system for the time period of five minutes. -cpu.load_average.15m | Float | The load average for the system for the time period of 15 minutes. -cpu.mem | Object | Statistics about memory usage for the node. -cpu.mem.total_in_bytes | Integer | The total amount of physical memory, in bytes. -cpu.mem.free_in_bytes | Integer | The total amount of free physical memory, in bytes. -cpu.mem.used_in_bytes | Integer | The total amount of used physical memory, in bytes. -cpu.mem.free_percent | Integer | The percentage of memory that is free. -cpu.mem.used_percent | Integer | The percentage of memory that is used. -cpu.swap | Object | Statistics about swap space for the node. -cpu.swap.total_in_bytes | Integer | The total amount of swap space, in bytes. -cpu.swap.free_in_bytes | Integer | The total amount of free swap space, in bytes. -cpu.swap.used_in_bytes | Integer | The total amount of used swap space, in bytes. -cpu.cgroup | Object | Contains cgroup statistics for the node. Returned for Linux only. -cpu.cgroup.cpuacct | Object | Statistics about the cpuacct control group for the node. -cpu.cgroup.cpu | Object | Statistics about the CPU control group for the node. -cpu.cgroup.memory | Object | Statistics about the memory control group for the node. +`timestamp` | `Integer` | The last refresh time for the operating system statistics, in milliseconds since the epoch. +`cpu` | `Object` | Statistics about the node's CPU usage. +`cpu.percent` | `Integer` | Recent CPU usage for the system. +`cpu.load_average` | `Object` | Statistics about load averages for the system. +`cpu.load_average.1m` | `Float` | The load average for the system for the time period of one minute. +`cpu.load_average.5m` | `Float` | The load average for the system for the time period of five minutes. +`cpu.load_average.15m` | `Float` | The load average for the system for the time period of 15 minutes. +`mem` | `Object` | Statistics about memory usage for the node. +`mem.total_in_bytes` | `Integer` | The total amount of physical memory, in bytes. +`mem.free_in_bytes` | `Integer` | The total amount of free physical memory, in bytes. +`mem.used_in_bytes` | `Integer` | The total amount of used physical memory, in bytes. +`mem.free_percent` | `Integer` | The percentage of memory that is free. +`mem.used_percent` | `Integer` | The percentage of memory that is used. +`swap` | `Object` | Statistics about swap space for the node. +`swap.total_in_bytes` | `Integer` | The total amount of swap space, in bytes. +`swap.free_in_bytes` | `Integer` | The total amount of free swap space, in bytes. +`swap.used_in_bytes` | `Integer` | The total amount of used swap space, in bytes. +`cgroup` | `Object` | Contains `cgroup` statistics for the node. Returned for Linux only. +`cgroup.cpuacct` | `Object` | Statistics about the `cpuacct` control group for the node. +`cgroup.cpu` | `Object` | Statistics about the CPU control group for the node. +`cgroup.memory` | `Object` | Statistics about the memory control group for the node. ### `process` @@ -1007,14 +1137,14 @@ The `process` object contains process statistics for the node and has the follow Field | Field type | Description :--- | :--- | :--- -timestamp | Integer | The last refresh time for the process statistics, in milliseconds since the epoch. -open_file_descriptors | Integer | The number of opened file descriptors associated with the current process. -max_file_descriptors | Integer | The maximum number of file descriptors for the system. -cpu | Object | Statistics about the CPU for the node. -cpu.percent | Integer | The percentage of CPU usage for the process. -cpu.total_in_millis | Integer | The total CPU time used by the process on which the JVM is running, in milliseconds. -mem | Object | Statistics about the memory for the node. -mem.total_virtual_in_bytes | Integer | The total amount of virtual memory that is guaranteed to be available to the process that is currently running, in bytes. +`timestamp` | `Integer` | The last refresh time for the process statistics, in milliseconds since the epoch. +`open_file_descriptors` | `Integer` | The number of opened file descriptors associated with the current process. +`max_file_descriptors` | `Integer` | The maximum number of file descriptors for the system. +`cpu` | `Object` | Statistics about the CPU for the node. +`cpu.percent` | `Integer` | The percentage of CPU usage for the process. +`cpu.total_in_millis` | `Integer` | The total CPU time used by the process on which the JVM is running, in milliseconds. +`mem` | `Object` | Statistics about the memory for the node. +`mem.total_virtual_in_bytes` | `Integer` | The total amount of virtual memory that is guaranteed to be available to the process that is currently running, in bytes. ### `jvm` @@ -1022,42 +1152,42 @@ The `jvm` object contains statistics about the JVM for the node and has the foll Field | Field type | Description :--- | :--- | :--- -timestamp | Integer | The last refresh time for the JVM statistics, in milliseconds since the epoch. -uptime_in_millis | Integer | The JVM uptime, in milliseconds. -mem | Object | Statistics for the JVM memory usage on the node. -mem.heap_used_in_bytes | Integer | The amount of memory that is currently being used, in bytes. -mem.heap_used_percent | Integer | The percentage of memory that is currently used by the heap. -mem.heap_committed_in_bytes | Integer | The amount of memory available for use by the heap, in bytes. -mem.heap_max_in_bytes | Integer | The maximum amount of memory available for use by the heap, in bytes. -mem.non_heap_used_in_bytes | Integer | The amount of non-heap memory that is currently used, in bytes. -mem.non_heap_committed_in_bytes | Integer | The maximum amount of non-heap memory available for use, in bytes. -mem.pools | Object | Statistics about heap memory usage for the node. -mem.pools.young | Object | Statistics about the young generation heap memory usage for the node. Contains the amount of memory used, the maximum amount of memory available, and the peak amount of memory used. -mem.pools.old | Object | Statistics about the old generation heap memory usage for the node. Contains the amount of memory used, the maximum amount of memory available, and the peak amount of memory used. -mem.pools.survivor | Object | Statistics about the survivor space memory usage for the node. Contains the amount of memory used, the maximum amount of memory available, and the peak amount of memory used. -threads | Object | Statistics about the JVM thread usage for the node. -threads.count | Integer | The number of threads that are currently active in the JVM. -threads.peak_count | Integer | The maximum number of threads in the JVM. -gc.collectors | Object | Statistics about the JVM garbage collectors for the node. -gc.collectors.young | Integer | Statistics about JVM garbage collectors that collect young generation objects. -gc.collectors.young.collection_count | Integer | The number of garbage collectors that collect young generation objects. -gc.collectors.young.collection_time_in_millis | Integer | The total time spent on garbage collection of young generation objects, in milliseconds. -gc.collectors.old | Integer | Statistics about JVM garbage collectors that collect old generation objects. -gc.collectors.old.collection_count | Integer | The number of garbage collectors that collect old generation objects. -gc.collectors.old.collection_time_in_millis | Integer | The total time spent on garbage collection of old generation objects, in milliseconds. -buffer_pools | Object | Statistics about the JVM buffer pools for the node. -buffer_pools.mapped | Object | Statistics about the mapped JVM buffer pools for the node. -buffer_pools.mapped.count | Integer | The number of mapped buffer pools. -buffer_pools.mapped.used_in_bytes | Integer | The amount of memory used by mapped buffer pools, in bytes. -buffer_pools.mapped.total_capacity_in_bytes | Integer | The total capacity of the mapped buffer pools, in bytes. -buffer_pools.direct | Object | Statistics about the direct JVM buffer pools for the node. -buffer_pools.direct.count | Integer | The number of direct buffer pools. -buffer_pools.direct.used_in_bytes | Integer | The amount of memory used by direct buffer pools, in bytes. -buffer_pools.direct.total_capacity_in_bytes | Integer | The total capacity of the direct buffer pools, in bytes. -classes | Object | Statistics about the classes loaded by the JVM for the node. -classes.current_loaded_count | Integer | The number of classes currently loaded by the JVM. -classes.total_loaded_count | Integer | The total number of classes loaded by the JVM since it started. -classes.total_unloaded_count | Integer | The total number of classes unloaded by the JVM since it started. +`timestamp` | `Integer` | The last refresh time for the JVM statistics, in milliseconds since the epoch. +`uptime_in_millis` | `Integer` | The JVM uptime, in milliseconds. +`mem` | `Object` | Statistics for the JVM memory usage on the node. +`mem.heap_used_in_bytes` | `Integer` | The amount of memory that is currently being used, in bytes. +`mem.heap_used_percent` | `Integer` | The percentage of memory that is currently used by the heap. +`mem.heap_committed_in_bytes` | `Integer` | The amount of memory available for use by the heap, in bytes. +`mem.heap_max_in_bytes` | `Integer` | The maximum amount of memory available for use by the heap, in bytes. +`mem.non_heap_used_in_bytes` | `Integer` | The amount of non-heap memory that is currently used, in bytes. +`mem.non_heap_committed_in_bytes` | `Integer` | The maximum amount of non-heap memory available for use, in bytes. +`mem.pools` | `Object` | Statistics about heap memory usage for the node. +`mem.pools.young` | `Object` | Statistics about the young generation heap memory usage for the node. Contains the amount of memory used, the maximum amount of memory available, and the peak amount of memory used. +`mem.pools.old` | `Object` | Statistics about the old generation heap memory usage for the node. Contains the amount of memory used, the maximum amount of memory available, and the peak amount of memory used. +`mem.pools.survivor` | `Object` | Statistics about the survivor space memory usage for the node. Contains the amount of memory used, the maximum amount of memory available, and the peak amount of memory used. +`threads` | `Object` | Statistics about the JVM thread usage for the node. +`threads.count` | `Integer` | The number of threads that are currently active in the JVM. +`threads.peak_count` | `Integer` | The maximum number of threads in the JVM. +`gc.collectors` | `Object` | Statistics about the JVM garbage collectors for the node. +`gc.collectors.young` | `Integer` | Statistics about JVM garbage collectors that collect young generation objects. +`gc.collectors.young.collection_count` | `Integer` | The number of garbage collectors that collect young generation objects. +`gc.collectors.young.collection_time_in_millis` | `Integer` | The total time spent on garbage collection of young generation objects, in milliseconds. +`gc.collectors.old` | `Integer` | Statistics about JVM garbage collectors that collect old generation objects. +`gc.collectors.old.collection_count` | `Integer` | The number of garbage collectors that collect old generation objects. +`gc.collectors.old.collection_time_in_millis` | `Integer` | The total time spent on garbage collection of old generation objects, in milliseconds. +`buffer_pools` | `Object` | Statistics about the JVM buffer pools for the node. +`buffer_pools.mapped` | `Object` | Statistics about the mapped JVM buffer pools for the node. +`buffer_pools.mapped.count` | `Integer` | The number of mapped buffer pools. +`buffer_pools.mapped.used_in_bytes` | `Integer` | The amount of memory used by mapped buffer pools, in bytes. +`buffer_pools.mapped.total_capacity_in_bytes` | `Integer` | The total capacity of the mapped buffer pools, in bytes. +`buffer_pools.direct` | `Object` | Statistics about the direct JVM buffer pools for the node. +`buffer_pools.direct.count` | `Integer` | The number of direct buffer pools. +`buffer_pools.direct.used_in_bytes` | `Integer` | The amount of memory used by direct buffer pools, in bytes. +`buffer_pools.direct.total_capacity_in_bytes` | `Integer` | The total capacity of the direct buffer pools, in bytes. +`classes` | `Object` | Statistics about the classes loaded by the JVM for the node. +`classes.current_loaded_count` | `Integer` | The number of classes currently loaded by the JVM. +`classes.total_loaded_count` | `Integer` | The total number of classes loaded by the JVM since it started. +`classes.total_unloaded_count` | `Integer` | The total number of classes unloaded by the JVM since it started. ### `thread_pool` @@ -1065,13 +1195,13 @@ The `thread_pool` object contains a list of all thread pools. Each thread pool i Field | Field type | Description :--- | :--- | :--- -threads | Integer | The number of threads in the pool. -queue | Integer | The number of threads in queue. -active | Integer | The number of active threads in the pool. -rejected | Integer | The number of tasks that have been rejected. -largest | Integer | The peak number of threads in the pool. -completed | Integer | The number of tasks completed. -total_wait_time | Integer | The total amount of time tasks spent waiting in the thread pool queue. Currently, only `search`, `search_throttled`, and `index_searcher` thread pools support this metric. +`threads` | `Integer` | The number of threads in the pool. +`queue` | `Integer` | The number of threads in queue. +`active` | `Integer` | The number of active threads in the pool. +`rejected` | `Integer` | The number of tasks that have been rejected. +`largest` | `Integer` | The peak number of threads in the pool. +`completed` | `Integer` | The number of tasks completed. +`total_wait_time_in_nanos` | `Integer` | The total amount of time that tasks spend waiting in the thread pool queue. Only the `search`, `search_throttled`, and `index_searcher` thread pools support this metric. ### `fs` @@ -1079,19 +1209,19 @@ The `fs` object represents statistics about the file stores for the node. It has Field | Field type | Description :--- | :--- | :--- -timestamp | Integer | The last refresh time for the file store statistics, in milliseconds since the epoch. -total | Object | Statistics for all file stores of the node. -total.total_in_bytes | Integer | The total memory size of all file stores, in bytes. -total.free_in_bytes | Integer | The total unallocated disk space in all file stores, in bytes. -total.available_in_bytes | Integer | The total disk space available to the JVM on all file stores. Represents the actual amount of memory, in bytes, that OpenSearch can use. -data | Array | The list of all file stores. Each file store has the following properties. -data.path | String | The path to the file store. -data.mount | String | The mount point of the file store. -data.type | String | The type of the file store (for example, overlay). -data.total_in_bytes | Integer | The total size of the file store, in bytes. -data.free_in_bytes | Integer | The total unallocated disk space in the file store, in bytes. -data.available_in_bytes | Integer | The total amount of disk space available to the JVM for the file store, in bytes. -io_stats | Object | I/O statistics for the node (Linux only). Includes devices, read and write operations, and the I/O operation time. +`timestamp` | `Integer` | The last refresh time for the file store statistics, in milliseconds since the epoch. +`total` | `Object` | Statistics for all file stores of the node. +`total.total_in_bytes` | `Integer` | The total memory size of all file stores, in bytes. +`total.free_in_bytes` | `Integer` | The total unallocated disk space in all file stores, in bytes. +`total.available_in_bytes` | `Integer` | The total disk space available to the JVM on all file stores. Represents the actual amount of memory, in bytes, that OpenSearch can use. +`data` | `Array` | The list of all file stores. Each file store has the following properties. +`data.path` | `String` | The path to the file store. +`data.mount` | `String` | The mount point of the file store. +`data.type` | `String` | The type of the file store (for example, overlay). +`data.total_in_bytes` | `Integer` | The total size of the file store, in bytes. +`data.free_in_bytes` | `Integer` | The total unallocated disk space in the file store, in bytes. +`data.available_in_bytes` | `Integer` | The total amount of disk space available to the JVM for the file store, in bytes. +`io_stats` | `Object` | I/O statistics for the node (Linux only). Includes devices, read and write operations, and the I/O operation time. ### `transport` @@ -1099,12 +1229,12 @@ The `transport` object has the following properties. Field | Field type | Description :--- | :--- | :--- -server_open | Integer | The number of open inbound TCP connections that OpenSearch nodes use for internal communication. -total_outbound_connections | Integer | The total number of outbound transport connections that the node has opened since it started. -rx_count | Integer | The total number of RX (receive) packets the node received during internal communication. -rx_size_in_bytes | Integer | The total size of RX packets the node received during internal communication, in bytes. -tx_count | Integer | The total number of TX (transmit) packets the node sent during internal communication. -tx_size_in_bytes | Integer | The total size of TX (transmit) packets the node sent during internal communication, in bytes. +`server_open` | `Integer` | The number of open inbound TCP connections that OpenSearch nodes use for internal communication. +`total_outbound_connections` | `Integer` | The total number of outbound transport connections that the node has opened since it started. +`rx_count` | `Integer` | The total number of RX (receive) packets the node received during internal communication. +`rx_size_in_bytes` | `Integer` | The total size of RX packets the node received during internal communication, in bytes. +`tx_count` | `Integer` | The total number of TX (transmit) packets the node sent during internal communication. +`tx_size_in_bytes` | `Integer` | The total size of TX (transmit) packets the node sent during internal communication, in bytes. ### `breakers` @@ -1112,12 +1242,12 @@ The `breakers` object contains statistics about the circuit breakers for the nod Field | Field type | Description :--- | :--- | :--- -limit_size_in_bytes | Integer | The memory limit for the circuit breaker, in bytes. -limit_size | Byte value | The memory limit for the circuit breaker in human-readable format (for example, `307.1mb`). -estimated_size_in_bytes | Integer | The estimated memory used for the operation, in bytes. -estimated_size | Byte value | The estimated memory used for the operation in human-readable format (for example, `356b`). -overhead | Float | A factor that all estimates are multiplied by to calculate the final estimate. -tripped | Integer | The total number of times the circuit breaker has been activated to prevent an out-of-memory error. +`limit_size_in_bytes` | `Integer` | The memory limit for the circuit breaker, in bytes. +`limit_size` | `Byte value` | The memory limit for the circuit breaker in human-readable format (for example, `307.1mb`). +`estimated_size_in_bytes` | `Integer` | The estimated memory used for the operation, in bytes. +`estimated_size` | `Byte value` | The estimated memory used for the operation in human-readable format (for example, `356b`). +`overhead` | `Float` | A factor that all estimates are multiplied by to calculate the final estimate. +`tripped` | `Integer` | The total number of times the circuit breaker has been activated to prevent an out-of-memory error. ### `script` and `script_cache` @@ -1125,15 +1255,15 @@ The `script` and `script_cache` objects have the following properties. Field | Field type | Description :--- | :--- | :--- -script | Object | Script statistics for the node. -script.compilations | Integer | The total number of script compilations for the node. -script.cache_evictions| Integer | The total number of times the script cache has purged old data. -script.compilation_limit_triggered | Integer | The total number of times script compilation was limited by a circuit breaker. -script_cache | Object | Script cache statistics for the node. -script_cache.sum.compilations | Integer | The total number of script compilations in the cache for the node. -script_cache.sum.cache_evictions| Integer | The total number of times the script cache has purged old data. -script_cache.sum.compilation_limit_triggered | Integer | The total number of times script compilation in the cache was limited by a circuit breaker. -script_cache.contexts | Array of objects | The list of contexts for the script cache. Each context contains its name, the number of compilations, the number of cache evictions, and the number of times the script was limited by a circuit breaker. +`script` | `Object` | Script statistics for the node. +`script.compilations` | `Integer` | The total number of script compilations for the node. +`script.cache_evictions` | `Integer` | The total number of times the script cache has purged old data. +`script.compilation_limit_triggered` | `Integer` | The total number of times script compilation was limited by a circuit breaker. +`script_cache` | `Object` | Script cache statistics for the node. +`script_cache.sum.compilations` | `Integer` | The total number of script compilations in the cache for the node. +`script_cache.sum.cache_evictions` | `Integer` | The total number of times the script cache has purged old data. +`script_cache.sum.compilation_limit_triggered` | `Integer` | The total number of times script compilation in the cache was limited by a circuit breaker. +`script_cache.contexts` | `Array of objects` | The list of contexts for the script cache. Each context contains its name, the number of compilations, the number of cache evictions, and the number of times the script was limited by a circuit breaker. ### `discovery` @@ -1141,24 +1271,24 @@ The `discovery` object contains the node discovery statistics and has the follow Field | Field type | Description :--- | :--- | :--- -cluster_state_queue | Object | Cluster state queue statistics for the node. -cluster_state_queue.total | Integer | The total number of cluster states in the queue. -cluster_state_queue.pending | Integer | The number of pending cluster states in the queue. -cluster_state_queue.committed | Integer | The number of committed cluster states in the queue. -published_cluster_states | Object | Statistics for the published cluster states for the node. -published_cluster_states.full_states | Integer | The number of published cluster states. -published_cluster_states.incompatible_diffs | Integer | The number of incompatible differences between published cluster states. -published_cluster_states.compatible_diffs | Integer | The number of compatible differences between published cluster states. -cluster_state_stats | Object | Cluster state update statistics published by the active leader. -cluster_state_stats.overall | Object | Overall cluster state update statistics. -cluster_state_stats.overall.update_count | Integer | The total number of successful cluster state updates. -cluster_state_stats.overall.total_time_in_millis | Integer | The total amount of time taken for all cluster state updates, in milliseconds. -cluster_state_stats.overall.failed_count | Integer | The total number of failed cluster state updates. -cluster_state_stats.remote_upload | Object | Cluster state update statistics related to remote uploads. -cluster_state_stats.remote_upload.success_count | Integer | The total number of successful cluster state updates uploaded to the remote store. -cluster_state_stats.remote_upload.failed_count | Integer | The total number of cluster state updates that failed to upload to the remote store. -cluster_state_stats.remote_upload.total_time_in_millis | Integer | The total amount of time taken for all cluster state updates uploaded to the remote store, in milliseconds. -cluster_state_stats.remote_upload.cleanup_attempt_failed_count | Integer | The total number of failures encountered while trying to clean up older cluster states from the remote store. +`cluster_state_queue` | `Object` | Cluster state queue statistics for the node. +`cluster_state_queue.total` | `Integer` | The total number of cluster states in the queue. +`cluster_state_queue.pending` | `Integer` | The number of pending cluster states in the queue. +`cluster_state_queue.committed` | `Integer` | The number of committed cluster states in the queue. +`published_cluster_states` | `Object` | Statistics for the published cluster states for the node. +`published_cluster_states.full_states` | `Integer` | The number of published cluster states. +`published_cluster_states.incompatible_diffs` | `Integer` | The number of incompatible differences between published cluster states. +`published_cluster_states.compatible_diffs` | `Integer` | The number of compatible differences between published cluster states. +`cluster_state_stats` | `Object` | Cluster state update statistics published by the active leader. +`cluster_state_stats.overall` | `Object` | Overall cluster state update statistics. +`cluster_state_stats.overall.update_count` | `Integer` | The total number of successful cluster state updates. +`cluster_state_stats.overall.total_time_in_millis` | `Integer` | The total amount of time taken for all cluster state updates, in milliseconds. +`cluster_state_stats.overall.failed_count` | `Integer` | The total number of failed cluster state updates. +`cluster_state_stats.remote_upload` | `Object` | Cluster state update statistics related to remote uploads. +`cluster_state_stats.remote_upload.success_count` | `Integer` | The total number of successful cluster state updates uploaded to the remote store. +`cluster_state_stats.remote_upload.failed_count` | `Integer` | The total number of cluster state updates that failed to upload to the remote store. +`cluster_state_stats.remote_upload.total_time_in_millis` | `Integer` | The total amount of time taken for all cluster state updates uploaded to the remote store, in milliseconds. +`cluster_state_stats.remote_upload.cleanup_attempt_failed_count` | `Integer` | The total number of failures encountered while trying to clean up older cluster states from the remote store. ### `ingest` @@ -1166,16 +1296,16 @@ The `ingest` object contains the ingest statistics and has the following propert Field | Field type | Description :--- | :--- | :--- -total | Integer | Ingest statistics for the node's lifetime. -total.count | Integer | The total number of documents ingested by the node. -total.time_in_millis | Integer | The total amount of time for preprocessing ingest documents, in milliseconds. -total.current | Integer | The total number of documents that are currently being ingested by the node. -total.failed | Integer | The total number of failed ingestions for the node. -pipelines | Object | Ingest pipeline statistics for the node. Each pipeline is a nested object that is specified by its ID and has the following properties. -pipelines._id_.count | Integer | The number of documents preprocessed by the ingest pipeline. -pipelines._id_.time_in_millis | Integer | The total amount of time for preprocessing documents in the ingest pipeline, in milliseconds. -pipelines._id_.failed | Integer | The total number of failed ingestions for the ingest pipeline. -pipelines._id_.processors | Array of objects | Statistics for the ingest processors. Includes the number of documents that are currently transformed, the total number of transformed documents, the number of failed transformations, and the time spent transforming documents. +`total` | `Integer` | Ingest statistics for the node's lifetime. +`total.count` | `Integer` | The total number of documents ingested by the node. +`total.time_in_millis` | `Integer` | The total amount of time for preprocessing ingest documents, in milliseconds. +`total.current` | `Integer` | The total number of documents that are currently being ingested by the node. +`total.failed` | `Integer` | The total number of failed ingest operations for the node. +`pipelines` | `Object` | Ingest pipeline statistics for the node. Each pipeline is a nested object that is specified by its ID and has the following properties. +`pipelines._id_.count` | `Integer` | The number of documents preprocessed by the ingest pipeline. +`pipelines._id_.time_in_millis` | `Integer` | The total amount of time for preprocessing documents in the ingest pipeline, in milliseconds. +`pipelines._id_.failed` | `Integer` | The total number of failed ingest operations for the ingest pipeline. +`pipelines._id_.processors` | `Array of objects` | Statistics for the ingest processors. Includes the number of documents that are currently transformed, the total number of transformed documents, the number of failed transformations, and the time spent transforming documents. ### `search_pipeline` @@ -1183,27 +1313,27 @@ The `search_pipeline` object contains the statistics related to [search pipeline Field | Field type | Description :--- | :--- | :--- -total_request | Object | Cumulative statistics related to all search request processors. -total_request.count | Integer | The total number of search request processor executions. -total_request.time_in_millis | Integer | The total amount of time for all search request processor executions, in milliseconds. -total_request.current | Integer | The total number of search request processor executions currently in progress. -total_request.failed | Integer | The total number of failed search request processor executions. -total_response | Object | Cumulative statistics related to all search response processors. -total_response.count | Integer | The total number of search response processor executions. -total_response.time_in_millis | Integer | The total amount of time for all search response processor executions, in milliseconds. -total_response.current | Integer | The total number of search response processor executions currently in progress. -total_response.failed | Integer | The total number of failed search response processor executions. -pipelines | Object | Search pipeline statistics. Each pipeline is a nested object specified by its ID, with the properties listed in the following rows. If a processor has a `tag`, statistics for the processor are provided in the object with the name `:` (for example, `filter_query:abc`). Statistics for all processors of the same type that do not have a `tag` are aggregated and provided in the object with the name `` (for example, `filter_query`). -pipelines._id_.request.count | Integer | The number of search request processor executions performed by the search pipeline. -pipelines._id_.request.time_in_millis | Integer | The total amount of time for search request processor executions in the search pipeline, in milliseconds. -pipelines._id_.request.current | Integer | The number of search request processor executions currently in progress for the search pipeline. -pipelines._id_.request.failed | Integer | The number of failed search request processor executions for the search pipeline. -pipelines._id_.request_processors | Array of objects | Statistics for the search request processors. Includes the total number of executions, the total amount of time of executions, the total number of executions currently in progress, and the number of failed executions. -pipelines._id_.response.count | Integer | The number of search response processor executions performed by the search pipeline. -pipelines._id_.response.time_in_millis | Integer | The total amount of time for search response processor executions in the search pipeline, in milliseconds. -pipelines._id_.response.current | Integer | The number of search response processor executions currently in progress for the search pipeline. -pipelines._id_.response.failed | Integer | The number of failed search response processor executions for the search pipeline. -pipelines._id_.response_processors | Array of objects | Statistics for the search response processors. Includes the total number of executions, the total amount of time of executions, the total number of executions currently in progress, and the number of failed executions. +`total_request` | `Object` | Cumulative statistics related to all search request processors. +`total_request.count` | `Integer` | The total number of search request processor executions. +`total_request.time_in_millis` | `Integer` | The total amount of time for all search request processor executions, in milliseconds. +`total_request.current` | `Integer` | The total number of search request processor executions currently in progress. +`total_request.failed` | `Integer` | The total number of failed search request processor executions. +`total_response` | `Object` | Cumulative statistics related to all search response processors. +`total_response.count` | `Integer` | The total number of search response processor executions. +`total_response.time_in_millis` | `Integer` | The total amount of time for all search response processor executions, in milliseconds. +`total_response.current` | `Integer` | The total number of search response processor executions currently in progress. +`total_response.failed` | `Integer` | The total number of failed search response processor executions. +`pipelines` | `Object` | Search pipeline statistics. Each pipeline is a nested object specified by its ID, with the properties listed in the following rows. If a processor has a `tag`, statistics for the processor are provided in the object with the name `:` (for example, `filter_query:abc`). Statistics for all processors of the same type that do not have a `tag` are aggregated and provided in the object with the name `` (for example, `filter_query`). +`pipelines._id_.request.count` | `Integer` | The number of search request processor executions performed by the search pipeline. +`pipelines._id_.request.time_in_millis` | `Integer` | The total amount of time for search request processor executions in the search pipeline, in milliseconds. +`pipelines._id_.request.current` | `Integer` | The number of search request processor executions currently in progress for the search pipeline. +`pipelines._id_.request.failed` | `Integer` | The number of failed search request processor executions for the search pipeline. +`pipelines._id_.request_processors` | `Array of objects` | Statistics for the search request processors. Includes the total number of executions, the total amount of time of executions, the total number of executions currently in progress, and the number of failed executions. +`pipelines._id_.response.count` | `Integer` | The number of search response processor executions performed by the search pipeline. +`pipelines._id_.response.time_in_millis` | `Integer` | The total amount of time for search response processor executions in the search pipeline, in milliseconds. +`pipelines._id_.response.current` | `Integer` | The number of search response processor executions currently in progress for the search pipeline. +`pipelines._id_.response.failed` | `Integer` | The number of failed search response processor executions for the search pipeline. +`pipelines._id_.response_processors` | `Array of objects` | Statistics for the search response processors. Includes the total number of executions, the total amount of time of executions, the total number of executions currently in progress, and the number of failed executions. ### `adaptive_selection` @@ -1211,11 +1341,11 @@ The `adaptive_selection` object contains the adaptive selection statistics. Each Field | Field type | Description :--- | :--- | :--- -outgoing_searches | Integer | The number of outgoing search requests for the node. -avg_queue_size | Integer | The rolling average queue size of search requests for the node (exponentially weighted). -avg_service_time_ns | Integer | The rolling average service time for search requests, in nanoseconds (exponentially weighted). -avg_response_time_ns | Integer | The rolling average response time for search requests, in nanoseconds (exponentially weighted). -rank | String | The node's rank that is used to select shards when routing requests. +`outgoing_searches` | `Integer` | The number of outgoing search requests for the node. +`avg_queue_size` | `Integer` | The rolling average queue size of search requests for the node (exponentially weighted). +`avg_service_time_ns` | `Integer` | The rolling average service time for search requests, in nanoseconds (exponentially weighted). +`avg_response_time_ns` | `Integer` | The rolling average response time for search requests, in nanoseconds (exponentially weighted). +`rank` | `String` | The node's rank that is used to select shards when routing requests. ### `indexing_pressure` @@ -1223,13 +1353,13 @@ The `indexing_pressure` object contains the indexing pressure statistics and has Field | Field type | Description :--- | :--- | :--- -memory | Object | Statistics related to memory consumption for the indexing load. -memory.current | Object | Statistics related to memory consumption for the current indexing load. -memory.current.combined_coordinating_and_primary_in_bytes | Integer | The total memory used by indexing requests in the coordinating or primary stages, in bytes. A node can reuse the coordinating memory if the primary stage is run locally, so the total memory does not necessarily equal the sum of the coordinating and primary stage memory usage. -memory.current.coordinating_in_bytes | The total memory consumed by indexing requests in the coordinating stage, in bytes. -memory.current.primary_in_bytes | Integer | The total memory consumed by indexing requests in the primary stage, in bytes. -memory.current.replica_in_bytes | Integer | The total memory consumed by indexing requests in the replica stage, in bytes. -memory.current.all_in_bytes | Integer | The total memory consumed by indexing requests in the coordinating, primary, or replica stages. +`memory` | `Object` | Statistics related to memory consumption for the indexing load. +`memory.current` | `Object` | Statistics related to memory consumption for the current indexing load. +`memory.current.combined_coordinating_and_primary_in_bytes` | `Integer` | The total memory used by indexing requests in the coordinating or primary stages, in bytes. A node can reuse the coordinating memory if the primary stage is run locally, so the total memory does not necessarily equal the sum of the coordinating and primary stage memory usage. +`memory.current.coordinating_in_bytes` | `Integer` | The total memory consumed by indexing requests in the coordinating stage, in bytes. +`memory.current.primary_in_bytes` | `Integer` | The total memory consumed by indexing requests in the primary stage, in bytes. +`memory.current.replica_in_bytes` | `Integer` | The total memory consumed by indexing requests in the replica stage, in bytes. +`memory.current.all_in_bytes` | `Integer` | The total memory consumed by indexing requests in the coordinating, primary, or replica stages. ### `shard_indexing_pressure` @@ -1237,13 +1367,47 @@ The `shard_indexing_pressure` object contains the [shard indexing pressure]({{si Field | Field type | Description :--- | :--- | :--- -[stats]({{site.url}}{{site.baseurl}}/opensearch/stats-api/) | Object | Statistics about shard indexing pressure. -total_rejections_breakup_shadow_mode | Object | If running in shadow mode, the `total_rejections_breakup_shadow_mode` object contains statistics about the request rejection criteria of all shards in the node. -total_rejections_breakup_shadow_mode.node_limits | Integer | The total number of rejections due to the node memory limit. When all shards reach the memory limit assigned to the node (for example, 10% of heap size), the shard is unable to take in more traffic on the node, and the indexing request is rejected. -total_rejections_breakup_shadow_mode.no_successful_request_limits | Integer | The total number of rejections when the node occupancy level is breaching its soft limit and the shard has multiple outstanding requests that are waiting to be executed. In this case, additional indexing requests are rejected until the system recovers. -total_rejections_breakup_shadow_mode.throughput_degradation_limits | Integer | The total number of rejections when the node occupancy level is breaching its soft limit and there is a constant deterioration in the request turnaround at the shard level. In this case, additional indexing requests are rejected until the system recovers. -enabled | Boolean | Specifies whether the shard indexing pressure feature is turned on for the node. -enforced | Boolean | If true, the shard indexing pressure runs in enforced mode (there are rejections). If false, the shard indexing pressure runs in shadow mode (there are no rejections, but statistics are recorded and can be retrieved in the `total_rejections_breakup_shadow_mode` object). Only applicable if shard indexing pressure is enabled. +[`stats`]({{site.url}}{{site.baseurl}}/opensearch/stats-api/) | `Object` | Statistics about shard indexing pressure. +`total_rejections_breakup_shadow_mode` | `Object` | If running in shadow mode, the `total_rejections_breakup_shadow_mode` object contains statistics about the request rejection criteria of all shards in the node. +`total_rejections_breakup_shadow_mode.node_limits` | `Integer` | The total number of rejections due to the node memory limit. When all shards reach the memory limit assigned to the node (for example, 10% of heap size), the shard is unable to take in more traffic on the node, and the indexing request is rejected. +`total_rejections_breakup_shadow_mode.no_successful_request_limits` | `Integer` | The total number of rejections when the node occupancy level is breaching its soft limit and the shard has multiple outstanding requests that are waiting to be executed. In this case, additional indexing requests are rejected until the system recovers. +`total_rejections_breakup_shadow_mode.throughput_degradation_limits` | `Integer` | The total number of rejections when the node occupancy level is breaching its soft limit and there is a constant deterioration in the request turnaround at the shard level. In this case, additional indexing requests are rejected until the system recovers. +`enabled` | `Boolean` | Specifies whether the shard indexing pressure feature is turned on for the node. +`enforced` | `Boolean` | If true, the shard indexing pressure runs in enforced mode (there are rejections). If false, the shard indexing pressure runs in shadow mode (there are no rejections, but statistics are recorded and can be retrieved in the `total_rejections_breakup_shadow_mode` object). Only applicable if shard indexing pressure is enabled. + +### `cluster_manager_throttling` + +The `cluster_manager_throttling` object contains statistics about throttled tasks on the cluster manager node. It is populated only for the node that is currently elected as the cluster manager. + +Field | Field type | Description +:--- | :--- | :--- +`stats` | `Object` | Statistics about throttled tasks on the cluster manager node. +`stats.total_throttled_tasks` | `Long` | The total number of throttled tasks. +`stats.throttled_tasks_per_task_type` | `Object` | A breakdown of statistics by individual task type, specified as key-value pairs. The keys are individual task types, and their values represent the number of requests that were throttled. + +### `task_cancellation` +Introduced 2.9 +{: .label .label-purple } + +The `task_cancellation` object contains statistics about tasks that continue running after being marked for cancellation. This helps monitor the effectiveness of task cancellation and identify tasks that don't properly respond to cancellation requests. + +Field | Field type | Description +:--- | :--- | :--- +`search_task` | `Object` | Statistics about parent search tasks that continue running after cancellation. +`search_task.current_count_post_cancel` | `Long` | The current number of search tasks that are still running after being canceled. +`search_task.total_count_post_cancel` | `Long` | The total number of search tasks that continued running after cancellation since the node last restarted. +`search_shard_task` | `Object` | Statistics about search shard tasks that continue running after cancellation. +`search_shard_task.current_count_post_cancel` | `Long` | The current number of search shard tasks that are still running after being canceled. +`search_shard_task.total_count_post_cancel` | `Long` | The total number of search shard tasks that continued running after cancellation since the node last restarted. + +### `weighted_routing` + +The `weighted_routing` object contains statistics about weighted round robin requests. Specifically, it contains a counter of times this node has server a request while it was "zoned out". + +Field | Field type | Description +:--- |:-----------| :--- +`stats` | `Object` | Statistics about weighted routing. +`fail_open_count` | `Integer` | Number of times a shard on this node has served a request while the routing weight for the node was set to zero. ### `resource_usage_stats` @@ -1251,17 +1415,63 @@ The `resource_usage_stats` object contains the resource usage statistics. Each e Field | Field type | Description :--- |:-----------| :--- -timestamp | Integer | The last refresh time for the resource usage statistics, in milliseconds since the epoch. -cpu_utilization_percent | Float | Statistics for the average CPU usage of OpenSearch process within the time period configured in the `node.resource.tracker.global_cpu_usage.window_duration` setting. -memory_utilization_percent | Float | The node JVM memory usage statistics within the time period configured in the `node.resource.tracker.global_jvmmp.window_duration` setting. +`timestamp` | `Integer` | The last refresh time for the resource usage statistics, in milliseconds since the epoch. +`cpu_utilization_percent` | `Float` | Statistics for the average CPU usage of any OpenSearch processes within the time period configured in the `node.resource.tracker.global_cpu_usage.window_duration` setting. +`memory_utilization_percent` | `Float` | The node JVM memory usage statistics within the time period configured in the `node.resource.tracker.global_jvmmp.window_duration` setting. +`max_io_utilization_percent` | `Float` | (Linux only) Statistics for the average IO usage of any OpenSearch processes within the time period configured in the `node.resource.tracker.global_io_usage.window_duration` setting. ### `admission_control` The `admission_control` object contains the rejection count of search and indexing requests based on resource consumption and has the following properties. + Field | Field type | Description :--- | :--- | :--- -admission_control.global_cpu_usage.transport.rejection_count.search | Integer | The total number of search rejections in the transport layer when the node CPU usage limit was breached. In this case, additional search requests are rejected until the system recovers. -admission_control.global_cpu_usage.transport.rejection_count.indexing | Integer | The total number of indexing rejections in the transport layer when the node CPU usage limit was breached. In this case, additional indexing requests are rejected until the system recovers. +`admission_control.global_cpu_usage.transport.rejection_count.search` | `Integer` | The total number of search rejections in the transport layer when the node CPU usage limit was met. In this case, additional search requests are rejected until the system recovers. The CPU usage limit is configured in the `admission_control.search.cpu_usage.limit` setting. +`admission_control.global_cpu_usage.transport.rejection_count.indexing` | `Integer` | The total number of indexing rejections in the transport layer when the node CPU usage limit was met. Any additional indexing requests are rejected until the system recovers. The CPU usage limit is configured in the `admission_control.indexing.cpu_usage.limit` setting. +`admission_control.global_io_usage.transport.rejection_count.search` | `Integer` | The total number of search rejections in the transport layer when the node IO usage limit was met. Any additional search requests are rejected until the system recovers. The CPU usage limit is configured in the `admission_control.search.io_usage.limit` setting (Linux only). +`admission_control.global_io_usage.transport.rejection_count.indexing` | `Integer` | The total number of indexing rejections in the transport layer when the node IO usage limit was met. Any additional indexing requests are rejected until the system recovers. The IO usage limit is configured in the `admission_control.indexing.io_usage.limit` setting (Linux only). + +### `concurrency_limiters` + +The `concurrency_limiters` object contains one entry per configured [concurrency limiter]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/concurrency-limits/), keyed by limiter name. It is returned when you request the `concurrency_limiter` metric. Each entry has the following properties. + +Field | Field type | Description +:--- | :--- | :--- +`action_name` | `String` | The transport action that the limiter applies to. +`mode` | `String` | The [mode]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/concurrency-limits/#modes) of the limiter. Valid values are `disabled`, `monitor_only`, and `enforced`. +`algorithm` | `String` | The [algorithm]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/concurrency-limits/#algorithms) used to adapt the limit. Valid values are `vegas`, `gradient2`, and `aimd`. +`current_limit` | `Integer` | The current adaptive concurrency limit, not including [burst capacity]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/concurrency-limits/#burst-capacity). +`in_flight` | `Integer` | The number of requests currently being processed. +`total_rejected` | `Integer` | The cumulative number of rejected requests. In `monitor_only` mode, this counts the requests that would have been rejected. +`last_rtt_millis` | `Integer` | The most recently observed round-trip time, in milliseconds. Omitted until the limiter has recorded a completed request. +`rtt_no_load_millis` | `Integer` | The round-trip time measured under no load, in milliseconds, used as the latency baseline. Omitted until the limiter has recorded a completed request. + +### `caches` + +Because this API supports the experimental [tiered caching feature]({{site.url}}{{site.baseurl}}/search-plugins/caching/tiered-cache/), the responses found in this section may change. If the tiered caching feature flag is not enabled, the API will return `0` for all values. +{: .warning} + +The `caches` object contains cache statistics, such as the `request_cache` statistics. The total values within each sub-metric are always returned, regardless of the value of the query parameter `level`. + +Field | Field type | Description +:--- | :--- | :--- +`request_cache` | `Object` | Statistics for the request cache. +`request_cache.size_in_bytes` | `Integer` | The total size, in bytes, of the request cache. +`request_cache.evictions` | `Integer` | The total number of evictions from the request cache. +`request_cache.hit_count` | `Integer` | The total hit count for the request cache. +`request_cache.miss_count` | `Integer` | The total miss count for the request cache. +`request_cache.item_count` | `Integer` | The total number of items in the request cache. +`request_cache.store_name` | `String` | The name of the store type used by the request cache. See [tiered cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/tiered-cache/) for more information. + +If the `level` query parameter is set to one of its valid values, `indices`, `shard`, or `tier`, additional fields will be present in `caches.request_cache` that categorize the values by these levels. +For example, if `level=indices,tier`, the tiered cache is in use, and the node has indexes named `index0` and `index1`, then the `caches` object will contain the same five metrics for each combination of level values, as shown in the following table. + +Field | Field type | Description +:--- | :--- | :--- +`request_cache.indices.index0.tier.on_heap` | `Object` | Contains the five metrics for `index0` on the heap tier. +`request_cache.indices.index0.tier.disk` | `Object` | Contains the five metrics for `index0` on the disk tier. +`request_cache.indices.index1.tier.on_heap` | `Object` | Contains the five metrics for `index1` on the heap tier. +`request_cache.indices.index1.tier.disk` | `Object` | Contains the five metrics for `index1` on the disk tier. ## Required permissions diff --git a/_api-reference/nodes-apis/nodes-usage.md b/_api-reference/nodes-apis/nodes-usage.md index 532ddb62..4a838742 100644 --- a/_api-reference/nodes-apis/nodes-usage.md +++ b/_api-reference/nodes-apis/nodes-usage.md @@ -5,19 +5,19 @@ parent: Nodes APIs nav_order: 40 --- -# Nodes usage +# Nodes Usage API **Introduced 1.0** {: .label .label-purple } The nodes usage endpoint returns low-level information about REST action usage on nodes. -## Path and HTTP methods +## Endpoints -``` +```json GET _nodes/usage -GET _nodes//usage -GET _nodes/usage/ -GET _nodes//usage/ +GET _nodes/{node_id}/usage +GET _nodes/usage/{metric} +GET _nodes/{node_id}/usage/{metric} ``` ## Path parameters @@ -26,8 +26,8 @@ You can include the following optional path parameters in your request. Parameter | Type | Description :--- | :--- | :--- -nodeId | String | A comma-separated list of nodeIds used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. -metric | String | The metrics that will be included in the response. You can set the string to either `_all` or `rest_actions`. `rest_actions` returns the total number of times an action has been called on the node. `_all` returns all stats from the node. Defaults to `_all`. +`node_id` | String | A comma-separated list of node IDs used to filter results. Supports [node filters]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters). Defaults to `_all`. +`metric` | String | The metrics that will be included in the response. You can set the string to either `_all` or `rest_actions`. `rest_actions` returns the total number of times an action has been called on the node. `_all` returns all stats from the node. Defaults to `_all`. ## Query parameters @@ -35,19 +35,36 @@ You can include the following optional query parameters in your request. Parameter | Type | Description :--- | :---| :--- -timeout | Time | Sets the time limit for a response from the node. Default is `30s`. -cluster_manager_timeout | Time | Sets the time limit for a response from the cluster manager. Default is `30s`. +`timeout` | Time | Sets the time limit for a response from the node. Default is `30s`. +`cluster_manager_timeout` | Time | Sets the time limit for a response from the cluster manager. Default is `30s`. -#### Example request +## Example request The following request returns usage details for all nodes: -``` -GET _nodes/usage -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_nodes/usage +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.nodes.info( + node_id_or_metric = "usage" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The following is an example response: diff --git a/_api-reference/popular-api.md b/_api-reference/popular-api.md index 2191b756..864e1c8c 100644 --- a/_api-reference/popular-api.md +++ b/_api-reference/popular-api.md @@ -1,7 +1,7 @@ --- layout: default title: Popular APIs -nav_order: 96 +nav_order: 170 redirect_from: - /opensearch/popular-api/ --- diff --git a/_api-reference/script-apis/create-stored-script.md b/_api-reference/script-apis/create-stored-script.md index 04a73a20..15c61223 100644 --- a/_api-reference/script-apis/create-stored-script.md +++ b/_api-reference/script-apis/create-stored-script.md @@ -1,18 +1,20 @@ --- layout: default -title: Create or Update Stored Script +title: Create or update stored script parent: Script APIs -nav_order: 1 +nav_order: 10 --- -# Create or update stored script +# Create or Update Stored Script API **Introduced 1.0** {: .label .label-purple } -Creates or updates a stored script or search template. +Creates or updates a stored script or search template in the cluster state. Stored scripts are compiled once and can be reused across multiple requests for better performance. For additional information about Painless scripting, see: +* [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + * [k-NN Painless Scripting extensions]({{site.url}}{{site.baseurl}}/search-plugins/knn/painless-functions/). * [k-NN]({{site.url}}{{site.baseurl}}/search-plugins/knn/index/). @@ -22,7 +24,7 @@ For additional information about Painless scripting, see: | Parameter | Data type | Description | :--- | :--- | :--- -| script-id | String | Stored script or search template ID. Must be unique across the cluster. Required. | +| `script-id` | String | Stored script or search template ID. Must be unique across the cluster. Required. | ## Query parameters @@ -30,40 +32,77 @@ All parameters are optional. | Parameter | Data type | Description | :--- | :--- | :--- -| context | String | Context in which the script or search template is to run. To prevent errors, the API immediately compiles the script or template in this context. | -| cluster_manager_timeout | Time | Amount of time to wait for a connection to the cluster manager. Defaults to 30 seconds. | -| timeout | Time | The period of time to wait for a response. If a response is not received before the timeout value, the request fails and returns an error. Defaults to 30 seconds.| +| `context` | String | Context in which the script or search template is to run. To prevent errors, the API immediately compiles the script or template in this context. | +| `cluster_manager_timeout` | Time | Amount of time to wait for a connection to the cluster manager. Defaults to 30 seconds. | +| `timeout` | Time | The period of time to wait for a response. If a response is not received before the timeout value, the request fails and returns an error. Defaults to 30 seconds.| -## Request fields +## Request body fields | Field | Data type | Description | :--- | :--- | :--- -| script | Object | Defines the script or search template, its parameters, and its language. See *Script object* below. | +| `script` | Object | Defines the script or search template, its parameters, and its language. See the following *Script object* section. | *Script object* | Field | Data type | Description | :--- | :--- | :--- -| lang | String | Scripting language. Required. | -| source | String or Object | Required.

For scripts, a string with the contents of the script.

For search templates, an object that defines the search template. Supports the same parameters as the [Search]({{site.url}}{{site.baseurl}}/api-reference/search) API request body. Search templates also support Mustache variables. | +| `lang` | String | Scripting language. Required. | +| `source` | String or Object | Required.

For scripts, a string with the contents of the script.

For search templates, an object that defines the search template. Supports the same parameters as the [Search]({{site.url}}{{site.baseurl}}/api-reference/search/) API request body. Search templates also support Mustache variables. | -#### Example request +## Example request -The sample uses an index called `books` with the following documents: +The following example requests uses an index called `books` with the following documents: -````json -{"index":{"_id":1}} + +{% capture step1_rest %} +POST /_bulk +{"index":{"_index":"books","_id":1}} +{"name":"book1","author":"Faustine","ratings":[4,3,5]} +{"index":{"_index":"books","_id":2}} +{"name":"book2","author":"Amit","ratings":[5,5,5]} +{"index":{"_index":"books","_id":3}} +{"name":"book3","author":"Gilroy","ratings":[2,1,5]} +{% endcapture %} + +{% capture step1_python %} + + +response = client.bulk( + body = ''' +{"index":{"_index":"books","_id":1}} +{"name":"book1","author":"Faustine","ratings":[4,3,5]} +{"index":{"_index":"books","_id":2}} +{"name":"book2","author":"Amit","ratings":[5,5,5]} +{"index":{"_index":"books","_id":3}} +{"name":"book3","author":"Gilroy","ratings":[2,1,5]} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Creating a Painless script The following request creates the Painless script `my-first-script`. It sums the ratings for each book and displays the sum in the output. -````json -PUT _scripts/my-first-script + +{% capture step1_rest %} +PUT /_scripts/my-first-script +{ + "script": { + "lang": "painless", + "source": """ + int total = 0; + for (int i = 0; i < doc['ratings'].length; ++i) { + total += doc['ratings'][i]; + } + return total; + """ + } +} +{% endcapture %} -The example above uses the syntax of the Dev Tools console in OpenSearch Dashboards. You can also use a curl request. +{% capture step1_python %} + + +response = client.put_script( + id = "my-first-script", + body = ''' +{ + "script": { + "lang": "painless", + "source": """ + int total = 0; + for (int i = 0; i < doc['ratings'].length; ++i) { + total += doc['ratings'][i]; + } + return total; + """ + } +} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The preceding example uses the syntax of the Dev Tools console in OpenSearch Dashboards. You can also use a cURL request. {: .note } -The following curl request is equivalent to the previous Dashboards console example: +The following cURL request is equivalent to the previous Dashboards console example: ````json curl -XPUT "http://opensearch:9200/_scripts/my-first-script" -H 'Content-Type: application/json' -d' @@ -96,56 +177,18 @@ curl -XPUT "http://opensearch:9200/_scripts/my-first-script" -H 'Content-Type: a {% include copy.html %} -The following request creates the Painless script `my-first-script`, which sums the ratings for each book and displays the sum in the output: - -````json -PUT _scripts/my-first-script -{ - "script": { - "lang": "painless", - "source": """ - int total = 0; - for (int i = 0; i < doc['ratings'].length; ++i) { - total += doc['ratings'][i]; - } - return total; - """ - } -} -```` -{% include copy-curl.html %} - See [Execute Painless stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/exec-stored-script/) for information about running the script. -#### Example response - -The `PUT _scripts/my-first-script` request returns the following field: - -````json -{ - "acknowledged" : true -} -```` - -To determine whether the script was successfully created, use the [Get stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-stored-script/) API, passing the script name as the `script` path parameter. -{: .note} - -### Response fields - -| Field | Data type | Description | -:--- | :--- | :--- -| acknowledged | Boolean | Whether the request was received. | - -## Creating or updating a stored script with parameters +### Creating or updating a stored script with parameters The Painless script supports `params` to pass variables to the script. -#### Example - The following request creates the Painless script `multiplier-script`. The request sums the ratings for each book, multiplies the summed value by the `multiplier` parameter, and displays the result in the output: -````json -PUT _scripts/multiplier-script + +{% capture step1_rest %} +PUT /_scripts/multiplier-script +{ + "script": { + "lang": "painless", + "source": """ + int total = 0; + for (int i = 0; i < doc['ratings'].length; ++i) { + total += doc['ratings'][i]; + } + return total * params['multiplier']; + """ + } +} +{% endcapture %} -### Example response +{% capture step1_python %} -The `PUT _scripts/multiplier-script` request returns the following field: + +response = client.put_script( + id = "multiplier-script", + body = ''' +{ + "script": { + "lang": "painless", + "source": """ + int total = 0; + for (int i = 0; i < doc['ratings'].length; ++i) { + total += doc['ratings'][i]; + } + return total * params['multiplier']; + """ + } +} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The `PUT _scripts/my-first-script` request returns the following field: ````json { "acknowledged" : true } -```` \ No newline at end of file +```` + +To determine whether the script was successfully created, use the [Get stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-stored-script/) API, passing the script name as the `script` path parameter. +{: .note} + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/script/put`. diff --git a/_api-reference/script-apis/delete-script.md b/_api-reference/script-apis/delete-script.md index 363b0152..e07372f2 100644 --- a/_api-reference/script-apis/delete-script.md +++ b/_api-reference/script-apis/delete-script.md @@ -1,15 +1,21 @@ --- layout: default -title: Delete Script +title: Delete stored script parent: Script APIs -nav_order: 4 +nav_order: 40 --- -# Delete script +# Delete Stored Script API **Introduced 1.0** {: .label .label-purple } -Deletes a stored script +Deletes a stored script from the cluster state. + +## Endpoints + +```json +DELETE _scripts/my-script +``` ## Path parameters @@ -17,25 +23,42 @@ Path parameters are optional. | Parameter | Data type | Description | :--- | :--- | :--- -| script-id | String | ID of script to delete. | +| `script-id` | String | ID of script to delete. | ## Query parameters | Parameter | Data type | Description | :--- | :--- | :--- -| cluster_manager_timeout | Time | Amount of time to wait for a connection to the cluster manager. Optional, defaults to `30s`. | -| timeout | Time | The period of time to wait for a response. If a response is not received before the timeout value, the request will be dropped. +| `cluster_manager_timeout` | Time | Amount of time to wait for a connection to the cluster manager. Optional, defaults to `30s`. | +| `timeout` | Time | The period of time to wait for a response. If a response is not received before the timeout value, the request will be dropped. -#### Example request +## Example request The following request deletes the `my-first-script` script: -````json -DELETE _scripts/my-script -```` -{% include copy-curl.html %} + +{% capture step1_rest %} +DELETE /_scripts/my-script +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.delete_script( + id = "my-script" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The `DELETE _scripts/my-first-script` request returns the following field: @@ -47,10 +70,14 @@ The `DELETE _scripts/my-first-script` request returns the following field: To determine whether the stored script was successfully deleted, use the [Get stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-stored-script/) API, passing the script name as the `script` path parameter. -## Response fields +## Response body fields The request returns the following response fields: | Field | Data type | Description | :--- | :--- | :--- -| acknowledged | Boolean | Whether the delete script request was received. | \ No newline at end of file +| `acknowledged` | Boolean | Whether the delete script request was received. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/script/delete`. diff --git a/_api-reference/script-apis/exec-script.md b/_api-reference/script-apis/exec-script.md index 4ecb6a37..351e5ddb 100644 --- a/_api-reference/script-apis/exec-script.md +++ b/_api-reference/script-apis/exec-script.md @@ -1,36 +1,50 @@ --- layout: default -title: Execute Painless script +title: Execute inline script parent: Script APIs nav_order: 7 --- -# Execute Painless script +# Execute Inline Script API **Introduced 1.0** {: .label .label-purple } -The Execute Painless script API allows you to run a script that is not stored. +The Execute Inline Script API allows you to run a script directly without storing it in the cluster state. The script is compiled and executed each time the API is called. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). -## Path and HTTP methods +## Endpoints ```json GET /_scripts/painless/_execute POST /_scripts/painless/_execute ``` -## Request fields +## Request body fields | Field | Description | :--- | :--- -| script | The script to run. Required| -| context | A context for the script. Optional. Default is `painless_test`. | -| context_setup | Specifies additional parameters for the context. Optional.| +| `script` | The inline script to run, specified in the `source` field. Stored scripts are not supported, so a script `id` is rejected. Required. | +| `context` | A context for the script. Optional. Default is `painless_test`. | +| `context_setup` | Specifies additional parameters for the context. Optional. | -#### Example request +## Example request -The following request uses the default `painless_context` for the script: +The following request uses the default `painless_test` context for the script: -```json + +{% capture step1_rest %} GET /_scripts/painless/_execute { "script": { @@ -41,10 +55,31 @@ GET /_scripts/painless/_execute } } } -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.scripts_painless_execute( + body = { + "script": { + "source": "(params.x + params.y)/ 2", + "params": { + "x": 80, + "y": 100 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The response contains the average of two script parameters: @@ -54,11 +89,11 @@ The response contains the average of two script parameters: } ``` -## Response fields +## Response body fields | Field | Description | :--- | :--- -| result | The script result.| +| `result` | The script result. | ## Script contexts @@ -71,14 +106,14 @@ The `painless_test` context is the default script context that provides only the ## Filter context -The `filter` context runs the script as if the script were inside a script query. You must provide a test document in the context. The `_source`, stored fields, and `_doc` variables will be available to the script. +The `filter` context runs the script as if the script were inside a script query. You must provide a test document in the context. The script accesses the document's field values through the `doc` variable. You can specify the following parameters for the filter context in the `context_setup`. Parameter | Description :--- | :--- -document | The document that is indexed in memory temporarily and available to the script. -index | The name of the index that contains a mapping for the document. +`document` | The document that is indexed in memory temporarily and available to the script. Required. +`index` | The name of the index that contains a mapping for the document. Must be a single index name; wildcard patterns are not supported. Required. For example, first create an index with a mapping for a test document: @@ -101,8 +136,10 @@ PUT /testindex1 Run a script to determine if a student is eligible to graduate with honors: -```json -POST /_scripts/painless/_execute + +{% capture step1_rest %} +GET /_scripts/painless/_execute +{ + "script": { + "source": "doc['grad'].value == true && doc['gpa'].value >= params.min_honors_gpa", + "params": { + "min_honors_gpa": 3.5 + } + }, + "context": "filter", + "context_setup": { + "index": "testindex1", + "document": { + "grad": true, + "gpa": 3.79 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.scripts_painless_execute( + body = { + "script": { + "source": "doc['grad'].value == true && doc['gpa'].value >= params.min_honors_gpa", + "params": { + "min_honors_gpa": 3.5 + } + }, + "context": "filter", + "context_setup": { + "index": "testindex1", + "document": { + "grad": true, + "gpa": 3.79 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains the result: @@ -138,14 +222,14 @@ You can specify the following parameters for the score context in the `context_s Parameter | Description :--- | :--- -document | The document that is indexed in memory temporarily and available to the script. -index | The name of the index that contains a mapping for the document. -query | If the script uses the `_score` parameter, the query can specify to use the `_score` field to compute the score. +`document` | The document that is indexed in memory temporarily and available to the script. Required. +`index` | The name of the index that contains a mapping for the document. Must be a single index name; wildcard patterns are not supported. Required. +`query` | A query used to compute the `_score` of the test document. If you don't specify a query, `_score` is `0`. Optional. For example, first create an index with a mapping for a test document: ```json -PUT /testindex1 +PUT /testindex2 { "mappings": { "properties": { @@ -160,8 +244,10 @@ PUT /testindex1 Run a script that converts a GPA on a 4.0 scale into a different scale that is provided as a parameter: -```json -POST /_scripts/painless/_execute + +{% capture step1_rest %} +GET /_scripts/painless/_execute +{ + "script": { + "source": "doc['gpa_4_0'].value * params.max_gpa / 4.0", + "params": { + "max_gpa": 5.0 + } + }, + "context": "score", + "context_setup": { + "index": "testindex2", + "document": { + "gpa_4_0": 3.5 + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.scripts_painless_execute( + body = { + "script": { + "source": "doc['gpa_4_0'].value * params.max_gpa / 4.0", + "params": { + "max_gpa": 5.0 + } + }, + "context": "score", + "context_setup": { + "index": "testindex2", + "document": { + "gpa_4_0": 3.5 + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The response contains the result: diff --git a/_api-reference/script-apis/exec-stored-script.md b/_api-reference/script-apis/exec-stored-script.md index 7525ec81..83441f4e 100644 --- a/_api-reference/script-apis/exec-stored-script.md +++ b/_api-reference/script-apis/exec-stored-script.md @@ -1,27 +1,109 @@ --- layout: default -title: Execute Painless stored script +title: Execute stored script parent: Script APIs -nav_order: 2 +nav_order: 20 --- -# Execute Painless stored script +# Execute Stored Script API **Introduced 1.0** {: .label .label-purple } -Runs a stored script written in the Painless language. +Runs a stored script that was previously saved to the cluster state using the Create Stored Script API. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). OpenSearch provides several ways to run a script; the following sections show how to run a script by passing script information in the request body of a `GET /_search` request. -## Request fields +## Endpoints + +```json +GET books/_search +{ + "script_fields": { + "total_ratings": { + "script": { + "id": "my-first-script" + } + } + } +} +``` + +## Request body fields | Field | Data type | Description | :--- | :--- | :--- -| query | Object | A filter that specifies documents to process. | -| script_fields | Object | Fields to include in output. | -| script | Object | ID of the script that produces a value for a field. | +| `query` | Object | A filter that specifies documents to process. | +| `script_fields` | Object | Fields to include in output. | +| `script` | Object | ID of the script that produces a value for a field. | -#### Example request +## Example request + +{% capture step1_rest %} +GET /books/_search +{ + "query": { + "match_all": {} + }, + "script_fields": { + "total_ratings": { + "script": { + "id": "multiplier-script", + "params": { + "multiplier": 2 + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "books", + body = { + "query": { + "match_all": {} + }, + "script_fields": { + "total_ratings": { + "script": { + "id": "multiplier-script", + "params": { + "multiplier": 2 + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + The following request runs the stored script that was created in [Create or update stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/). The script sums the ratings for each book and displays the sum in the `total_ratings` field in the output. @@ -31,8 +113,10 @@ The following request runs the stored script that was created in [Create or upda * The `total_ratings` field value is the result of the `my-first-script` execution. See [Create or update stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/). -````json -GET books/_search + +{% capture step1_rest %} +GET /books/_search +{ + "query": { + "match_all": {} + }, + "script_fields": { + "total_ratings": { + "script": { + "id": "my-first-script" + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "books", + body = { + "query": { + "match_all": {} + }, + "script_fields": { + "total_ratings": { + "script": { + "id": "my-first-script" + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + #### Example response @@ -104,38 +228,36 @@ The `GET books/_search` request returns the following fields: } ```` -## Response fields +## Response body fields | Field | Data type | Description | :--- | :--- | :--- -| took | Integer | How long the operation took in milliseconds. | -| timed_out | Boolean | Whether the operation timed out. | -| _shards | Object | Total number of shards processed and also the total number of successful, skipped, and not processed. | -| hits | Object | Contains high-level information about the documents processed and an array of `hits` objects. See [Hits object](#hits-object). | +| `took` | Integer | How long the operation took in milliseconds. | +| `timed_out` | Boolean | Whether the operation timed out. | +| `_shards` | Object | Total number of shards processed and also the total number of successful, skipped, and not processed. | +| `hits` | Object | Contains high-level information about the documents processed and an array of `hits` objects. See [Hits object](#hits-object). | #### Hits object | Field | Data type | Description | :--- | :--- | :--- -| total | Object | Total number of documents processed and their relationship to the `match` request field. | -| max_score | Double | Highest relevance score returned from all the hits. | -| hits | Array | Information about each document that was processed. See [Document object](#Document-object). | +| `total` | Object | Total number of documents processed and their relationship to the `match` request field. | +| `max_score` | Double | Highest relevance score returned from all the hits. | +| `hits` | Array | Information about each document that was processed. See [Document object](#Document-object). | #### Document object | Field | Data type | Description | :--- | :--- | :--- -| _index | String | Index that contains the document. | -| _id | String | Document ID. | -| _score | Float | Document's relevance score. | -| fields | Object | Fields and their value returned from the script. | +| `_index` | String | Index that contains the document. | +| `_id` | String | Document ID. | +| `_score` | Float | Document's relevance score. | +| `fields` | Object | Fields and their value returned from the script. | ## Running a Painless stored script with parameters To pass different parameters to the script each time when running a query, define `params` in `script_fields`. -#### Example - The following request runs the stored script that was created in [Create or update stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/). The script sums the ratings for each book, multiplies the summed value by the `multiplier` parameter, and displays the result in the output. * The script's target is the `books` index. @@ -146,8 +268,10 @@ The following request runs the stored script that was created in [Create or upda * `"multiplier": 2` in the `params` field is a variable passed to the stored script `multiplier-script`: -```json -GET books/_search + +{% capture step1_rest %} +GET /books/_search +{ + "query": { + "match_all": {} + }, + "script_fields": { + "total_ratings": { + "script": { + "id": "multiplier-script", + "params": { + "multiplier": 2 + } + } + } + } +} +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.search( + index = "books", + body = { + "query": { + "match_all": {} + }, + "script_fields": { + "total_ratings": { + "script": { + "id": "multiplier-script", + "params": { + "multiplier": 2 + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the matching documents: ```json { @@ -223,10 +393,9 @@ GET books/_search } ``` -**Sort results using painless stored script -You can use painless stored script to sort results.** +## Sorting results using a Painless stored script -#### Sample request +The following example uses a Painless stored script to sort results: ```json GET books/_search @@ -259,7 +428,7 @@ GET books/_search } ``` -#### Sample response +#### Example response ```json { diff --git a/_api-reference/script-apis/get-script-contexts.md b/_api-reference/script-apis/get-script-contexts.md index 40a15595..74d8baa4 100644 --- a/_api-reference/script-apis/get-script-contexts.md +++ b/_api-reference/script-apis/get-script-contexts.md @@ -1,24 +1,37 @@ --- layout: default -title: Get Stored Script Contexts +title: Get script contexts parent: Script APIs -nav_order: 5 +nav_order: 70 --- -# Get stored script contexts +# Get Script Contexts API **Introduced 1.0** {: .label .label-purple } -Retrieves all contexts for stored scripts. +Retrieves all available contexts where scripts can be used, such as search, update, or aggregation contexts. -#### Example request +## Example request -````json -GET _script_context -```` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_script_context +{% endcapture %} -#### Example response +{% capture step1_python %} + +response = client.get_script_context() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The `GET _script_context` request returns the following fields: @@ -547,32 +560,32 @@ The `GET _script_context` request returns the following fields: } ```` -## Response fields +## Response body fields The `GET _script_context` request returns the following response fields: | Field | Data type | Description | :--- | :--- | :--- -| contexts | List | A list of all contexts. See [Script object](#script-context). | +| `contexts` | List | A list of all contexts. See [Script object](#script-context). | #### Script context | Field | Data type | Description | :--- | :--- | :--- -| name | String | The context name. | -| methods | List | List of the context's allowable methods. See [Script object](#context-methods). | +| `name` | String | The context name. | +| `methods` | List | List of the context's allowable methods. See [Script object](#context-methods). | #### Context methods | Field | Data type | Description | :--- | :--- | :--- -| name | String | Method name. | -| name | String | Type that the method returns (`boolean`, `object`, `number`, and so on). | -| params | List | List of the parameters accepted by the method. See [Script object](#method-parameters). | +| `name` | String | Method name. | +| `name` | String | Type that the method returns (`boolean`, `object`, `number`, and so on). | +| `params` | List | List of the parameters accepted by the method. See [Script object](#method-parameters). | #### Method parameters | Field | Data type | Description | :--- | :--- | :--- -| type | String | Parameter data type. | -| name | String | Parameter name. | \ No newline at end of file +| `type` | String | Parameter data type. | +| `name` | String | Parameter name. | \ No newline at end of file diff --git a/_api-reference/script-apis/get-script-language.md b/_api-reference/script-apis/get-script-language.md index d53eb048..cda94027 100644 --- a/_api-reference/script-apis/get-script-language.md +++ b/_api-reference/script-apis/get-script-language.md @@ -1,24 +1,37 @@ --- layout: default -title: Get Script Language +title: Get script languages parent: Script APIs -nav_order: 6 +nav_order: 60 --- -# Get script language +# Get Script Languages API **Introduced 1.0** {: .label .label-purple } -The get script language API operation retrieves all supported script languages and their contexts. +The Get Script Languages API retrieves all supported script languages (such as Painless) and the contexts in which they can be used. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). -#### Example request +## Example request -```json -GET _script_language -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_script_language +{% endcapture %} -#### Example response +{% capture step1_python %} + +response = client.get_script_languages() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The `GET _script_language` request returns the available contexts for each language: @@ -89,13 +102,13 @@ The `GET _script_language` request returns the available contexts for each langu } ``` -## Response fields +## Response body fields The request contains the following response fields. Field | Data type | Description | :--- | :--- | :--- -types_allowed | List of strings | The types of scripts that are enabled, determined by the `script.allowed_types` setting. May contain `inline` and/or `stored`. -language_contexts | List of objects | A list of objects, each of which maps a supported language to its available contexts. -language_contexts.language | String | The name of the registered scripting language. -language_contexts.contexts | List of strings | A list of all contexts for the language, determined by the `script.allowed_contexts` setting. +`types_allowed` | List of strings | The types of scripts that are enabled, determined by the `script.allowed_types` setting. May contain `inline` and/or `stored`. +`language_contexts` | List of objects | A list of objects, each of which maps a supported language to its available contexts. +`language_contexts.language` | String | The name of the registered scripting language. +`language_contexts.contexts` | List of strings | A list of all contexts for the language, determined by the `script.allowed_contexts` setting. diff --git a/_api-reference/script-apis/get-stored-script.md b/_api-reference/script-apis/get-stored-script.md index cc681cd0..cee1e4b7 100644 --- a/_api-reference/script-apis/get-stored-script.md +++ b/_api-reference/script-apis/get-stored-script.md @@ -1,38 +1,61 @@ --- layout: default -title: Get Stored Script +title: Get stored script parent: Script APIs -nav_order: 3 +nav_order: 30 --- -# Get stored script +# Get Stored Script API **Introduced 1.0** {: .label .label-purple } -Retrieves a stored script. +Retrieves a stored script from the cluster state. + +## Endpoints + +```json +GET _scripts/my-first-script +``` ## Path parameters | Parameter | Data type | Description | :--- | :--- | :--- -| script | String | Stored script or search template name. Required.| +| `script` | String | Stored script or search template name. Required.| ## Query parameters | Parameter | Data type | Description | :--- | :--- | :--- -| cluster_manager_timeout | Time | Amount of time to wait for a connection to the cluster manager. Optional, defaults to `30s`. | +| `cluster_manager_timeout` | Time | Amount of time to wait for a connection to the cluster manager. Optional, defaults to `30s`. | -#### Example request +## Example request The following retrieves the `my-first-script` stored script. -````json -GET _scripts/my-first-script -```` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_scripts/my-first-script +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.get_script( + id = "my-first-script" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response The `GET _scripts/my-first-script` request returns the following fields: @@ -53,19 +76,23 @@ The `GET _scripts/my-first-script` request returns the following fields: } ```` -## Response fields +## Response body fields The `GET _scripts/my-first-script` request returns the following response fields: | Field | Data type | Description | :--- | :--- | :--- -| _id | String | The script's name. | -| found | Boolean | The requested script exists and was retrieved. | -| script | Object | The script definition. See [Script object](#script-object). | +| `_id` | String | The script's name. | +| `found` | Boolean | The requested script exists and was retrieved. | +| `script` | Object | The script definition. See [Script object](#script-object). | #### Script object | Field | Data type | Description | :--- | :--- | :--- -| lang | String | The script's language. | -| source | String | The script's body. | \ No newline at end of file +| `lang` | String | The script's language. | +| `source` | String | The script's body. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/script/get`. diff --git a/_api-reference/script-apis/index.md b/_api-reference/script-apis/index.md index 605faf33..b44490f5 100644 --- a/_api-reference/script-apis/index.md +++ b/_api-reference/script-apis/index.md @@ -2,13 +2,49 @@ layout: default title: Script APIs has_children: true -nav_order: 70 +has_toc: false +nav_order: 90 redirect_from: - /opensearch/rest-api/script-apis/ + - /api-reference/script-apis/ --- # Script APIs **Introduced 1.0** {: .label .label-purple } -The script APIs allow you to work with stored scripts. Stored scripts are part of the cluster state and reduce compilation time and enhance search speed. The default scripting language is Painless. +The script APIs allow you to work with both stored and inline scripts in OpenSearch. The default scripting language is Painless. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +## Types of scripts + +OpenSearch supports two types of scripts: + +- **Inline scripts**: Scripts defined directly within API requests. They are compiled each time they are executed. +- **Stored scripts**: Precompiled scripts saved in the cluster state that can be reused across multiple requests. They reduce compilation time and enhance search speed. + + +## Script API operations + +OpenSearch supports the following script API operations. + +### Inline script operations + +Execute scripts directly without saving them to the cluster state: + +- [Execute inline script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/exec-script/) + +### Stored script operations + +Manage precompiled scripts saved in the cluster state: + +- [Create or update stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/) +- [Execute stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/exec-stored-script/) +- [Get stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-stored-script/) +- [Delete stored script]({{site.url}}{{site.baseurl}}/api-reference/script-apis/delete-script/) + +### Script information + +Get information about available script contexts and languages: + +- [Get script contexts]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-script-contexts/) - List available contexts for stored scripts +- [Get script languages]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-script-language/) - List supported scripting languages diff --git a/_api-reference/search-apis/count.md b/_api-reference/search-apis/count.md new file mode 100644 index 00000000..ccf69213 --- /dev/null +++ b/_api-reference/search-apis/count.md @@ -0,0 +1,302 @@ +--- +layout: default +title: Count +parent: Search APIs +nav_order: 35 +redirect_from: + - /opensearch/rest-api/count/ + - /api-reference/count/ +--- + +# Count API +**Introduced 1.0** +{: .label .label-purple } + +The Count API returns the count of documents that match a query. You can use it to retrieve the document count of an index, a data stream, or a cluster. Common use cases include: + +- Retrieving the total number of documents in an index or data stream without retrieving the actual documents. +- Verifying that data has been indexed correctly by counting documents that match specific criteria. +- Monitoring data growth over time by tracking document counts across different time periods. +- Validating query results before running expensive search operations by first retrieving how many documents match. + +The Count API is more efficient than using the Search API with `size: 0` when you only need the document count because it is optimized specifically for counting operations. To improve performance, OpenSearch distributes the count query across all shards in parallel. Each shard processes the request using one of its available replicas, allowing horizontal scaling as the number of replicas increases. + +Alternatively, you can use the [CAT Indices API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-indices/) or the [CAT Count API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-count/) to retrieve the number of documents in each index or data stream. +{: .note } + + +## Endpoints +```json +GET /_count +POST /_count +GET /{index}/_count +POST /{index}/_count +``` + + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | List or String | A comma-separated list of data streams, indexes, and aliases to search. Supports wildcards (`*`). To search all data streams and indexes, omit this parameter or use `*` or `_all`. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indexes. This behavior applies even if the request targets other open indexes. | N/A | +| `analyze_wildcard` | Boolean | If `true`, wildcard and prefix queries are analyzed. This parameter can only be used when the `q` query string parameter is specified. | `false` | +| `analyzer` | String | Analyzer to use for the query string. This parameter can only be used when the `q` query string parameter is specified. | N/A | +| `default_operator` | String | The default operator for query string query: `AND` or `OR`. This parameter can only be used when the `q` query string parameter is specified.
Valid values are: `and`, `AND`, `or`, and `OR`. | N/A | +| `df` | String | Field to use as default where no field prefix is given in the query string. This parameter can only be used when the `q` query string parameter is specified. | N/A | +| `expand_wildcards` | List or String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes. | N/A | +| `ignore_throttled` | Boolean | If `true`, concrete, expanded or aliased indexes are ignored when frozen. | N/A | +| `ignore_unavailable` | Boolean | If `false`, the request returns an error if it targets a missing or closed index. | N/A | +| `lenient` | Boolean | If `true`, format-based query failures (such as providing text to a numeric field) in the query string will be ignored. | N/A | +| `min_score` | Float | Sets the minimum `_score` value that documents must have to be included in the result. | N/A | +| `preference` | String | Specifies the node or shard the operation should be performed on. Random by default. | `random` | +| `q` | String | Query in the Lucene query string syntax. | N/A | +| `routing` | List or String | A custom value used to route operations to a specific shard. | N/A | +| `terminate_after` | Integer | Maximum number of documents to collect for each shard. If a query reaches this limit, OpenSearch terminates the query early. OpenSearch collects documents before sorting. | N/A | + + + +## Request body fields + +The request body is optional. You can use it to restrict the results using a query defined with Query DSL. + +Field | Data type | Description +:--- | :--- | :--- +`query` | Object | The query used to filter documents. If not specified, the `match_all` query is used to count all documents in the target. For more information about OpenSearch queries, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +## Example: Counting all documents in a cluster + +The following example request returns the total count of all documents across the entire cluster: + + +{% capture step1_rest %} +GET /_count +{% endcapture %} + +{% capture step1_python %} + +response = client.count() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Counting all documents in several indexes + +The following example request returns the total count of all documents in the `movies` and `tv_shows` indexes: + + +{% capture step1_rest %} +GET /movies,tv_shows/_count +{% endcapture %} + +{% capture step1_python %} + + +response = client.count( + index = "movies,tv_shows" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Counting documents that match a query + +The following example request counts documents in the `movies` index in which the `genre` field is `drama`: + + +{% capture step1_rest %} +POST /movies/_count +{ + "query": { + "term": { + "genre": "drama" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.count( + index = "movies", + body = { + "query": { + "term": { + "genre": "drama" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Counting documents using a query string + +The following example request uses the `q` query parameter to count documents where the `genre` field is `drama`: + + +{% capture step1_rest %} +GET /movies/_count?q=genre:drama +{% endcapture %} + +{% capture step1_python %} + + +response = client.count( + index = "movies", + params = { "q": "genre:drama" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example: Counting documents with early termination + +The following example request uses the `terminate_after` parameter to stop counting after finding three matching documents: + + +{% capture step1_rest %} +POST /movies/_count?terminate_after=3 +{ + "query": { + "match_all": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.count( + index = "movies", + params = { "terminate_after": "3" }, + body = { + "query": { + "match_all": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following example response shows the document count and shard information: + +```json +{ + "count" : 7, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + } +} +``` + +When using the `terminate_after` parameter, the response includes a `terminated_early` field: + +```json +{ + "terminated_early" : true, + "count" : 7, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + } +} +``` + +## Response body fields + +The Count API response contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`count` | Integer | The total number of documents matching the query. If a query is not provided, this represents all documents in the specified target. +`_shards` | Object | Contains information about the shards involved in the count operation. +`_shards.total` | Integer | The total number of shards queried for the count operation. +`_shards.successful` | Integer | The number of shards that successfully executed the count operation. +`_shards.skipped` | Integer | The number of shards that were skipped during the count operation. Shards may be skipped if they do not contain any documents matching the query. +`_shards.failed` | Integer | The number of shards that failed to execute the count operation. If this value is greater than 0, check your cluster health and shard allocation. +`terminated_early` | Boolean | Appears only when the `terminate_after` query parameter is used. When `true`, indicates that the count operation was terminated before all matching documents were counted. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/search`. diff --git a/_api-reference/search-apis/explain.md b/_api-reference/search-apis/explain.md new file mode 100644 index 00000000..946638da --- /dev/null +++ b/_api-reference/search-apis/explain.md @@ -0,0 +1,266 @@ +--- +layout: default +title: Explain +parent: Search APIs +nav_order: 40 +redirect_from: + - /opensearch/rest-api/explain/ + - /api-reference/explain/ +--- + +# Explain API +**Introduced 1.0** +{: .label .label-purple } + +The Explain API returns detailed information about why a specific document matches or does not match a query. This API helps you understand how OpenSearch calculates the relevance score (`_score`) for each search result, making it an essential tool for debugging search relevance issues and optimizing queries. + +OpenSearch uses a probabilistic ranking framework called [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) to calculate relevance scores. Okapi BM25 is based on the original [term frequency/inverse document frequency (TF/IDF)](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/package-summary.html#scoring) framework used by Apache Lucene. + +Using the Explain API is expensive in terms of both resources and time. For production clusters, we recommend using it sparingly for the purpose of troubleshooting. +{: .warning } + +## Limitations + +The Explain API does not support the `search_pipeline` parameter. Sending a request with an inline or named search pipeline results in a `parsing_exception` error. This applies to all query types. + +To use search pipeline processors with `explain`, provide the `explain=true` query parameter to the [Search API]({{site.url}}{{site.baseurl}}/api-reference/search/). For more information about using `explain` with hybrid queries, see [Hybrid search explain]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/explain/). + + +## Endpoints +```json +GET /{index}/_explain/{id} +POST /{index}/_explain/{id} +``` + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `id` | **Required** | String | The document ID. | +| `index` | **Required** | String | The index to search. Only a single index name can be specified. | + +## Query parameters + +You must specify the index and document ID. All other parameters are optional. + +Parameter | Type | Description | Required +:--- | :--- | :--- | :--- +`analyzer` | String | The analyzer to use for the `q` query string. Only valid when `q` is used. | No +`analyze_wildcard` | Boolean | Whether to analyze wildcard and prefix queries in the `q` string. Only valid when `q` is used. Default is `false`. | No +`default_operator` | String | The default Boolean operator (`AND` or `OR`) for the `q` query string. Only valid when `q` is used. Default is `OR`. | No +`df` | String | The default field to search if no field is specified in the `q` string. Only valid when `q` is used. | No +`lenient` | Boolean | Specifies whether OpenSearch should ignore format-based query failures (for example, querying a text field for an integer). Default is `false`. | No +`preference` | String | Specifies a preference of which shard to retrieve results from. Available options are `_local`, which tells the operation to retrieve results from a locally allocated shard replica, and a custom string value assigned to a specific shard replica. By default, OpenSearch executes the explain operation on random shards. | No +`q` | String | A query string in [Lucene syntax]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/#query-string-syntax). When used, you can configure query behavior using the `analyzer`, `analyze_wildcard`, `default_operator`, `df`, and `stored_fields` parameters. | No +`stored_fields` | String | A comma-separated list of stored fields to return. If omitted, only `_source` is returned. | No +`routing` | String | A value used to route the operation to a specific shard. | No +`_source` | String | Whether to include the `_source` field in the response body. Valid values are `true` (include full `_source`), `false` (exclude `_source`), or a comma-separated list of source fields to include in the query response. By default, when not specified, the `_source` field is not returned in the Explain API response. | No +`_source_excludes` | String | A comma-separated list of source fields to exclude in the query response. | No +`_source_includes` | String | A comma-separated list of source fields to include in the query response. | No + +## Request body fields + +The request body contains the query to explain against the specified document. The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`query` | Object | The query to execute against the document. Uses the same query syntax as the [Search API]({{site.url}}{{site.baseurl}}/api-reference/search/). For more information about query types, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +## Example: Explaining a match query + +The following example explains why document `1` in the `products` index matches a query for the term "computer" in the `name` field: + + +{% capture step1_rest %} +POST /products/_explain/1 +{ + "query": { + "match": { + "name": "computer" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.explain( + id = "1", + index = "products", + body = { + "query": { + "match": { + "name": "computer" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The Explain API returns a response that includes whether the document matched the query and a detailed breakdown of the score calculation. The explanation includes the BM25 scoring formula components: term frequency (`tf`), inverse document frequency (`idf`), and field length normalization: + +
+ + Response for explaining a match query + + {: .text-delta} + +```json +{ + "_index": "products", + "_id": "1", + "matched": true, + "explanation": { + "value": 0.31506687, + "description": "weight(name:computer in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 0.31506687, + "description": "score(freq=1.0), computed as boost * idf * tf from:", + "details": [ + { + "value": 0.6931472, + "description": "idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:", + "details": [ + { + "value": 2, + "description": "n, number of documents containing term", + "details": [] + }, + { + "value": 4, + "description": "N, total number of documents with field", + "details": [] + } + ] + }, + { + "value": 0.45454544, + "description": "tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl)) from:", + "details": [ + { + "value": 1.0, + "description": "freq, occurrences of term within document", + "details": [] + }, + { + "value": 1.2, + "description": "k1, term saturation parameter", + "details": [] + }, + { + "value": 0.75, + "description": "b, length normalization parameter", + "details": [] + }, + { + "value": 2.0, + "description": "dl, length of field", + "details": [] + }, + { + "value": 2.0, + "description": "avgdl, average length of field", + "details": [] + } + ] + } + ] + } + ] + } +} +``` + +
+ +## Example: Using the query string parameter + +You can use the `q` parameter to specify a query using Lucene query string syntax instead of providing a request body. The following example explains why document `1` matches the query string "name:laptop": + + +{% capture step1_rest %} +GET /products/_explain/1?q=name:laptop +{% endcapture %} + +{% capture step1_python %} + + +response = client.explain( + id = "1", + index = "products", + params = { "q": "name:laptop" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Response body fields + +The response contains detailed information about whether the document matched the query and how the relevance score was calculated. The following table lists the response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`_index` | String | The name of the index containing the document. +`_id` | String | The document ID. +`matched` | Boolean | Whether the document matches the query. If `true`, the document is a match and has a relevance score. If `false`, the document does not match the query. +`explanation` | Object | The explanation of the score calculation. Contains the following nested fields: `value` (the calculated score or score component), `description` (a human-readable description of the calculation), and `details` (an array of sub-explanations for nested calculations). +`explanation.value` | Float | The numeric result of the score calculation. For the top-level explanation, this is the final relevance score. For nested explanations, this represents intermediate calculation values. +`explanation.description` | String | A description of the calculation being performed. For BM25 scoring, this typically describes the scoring formula components, such as term frequency (`tf`), inverse document frequency (`idf`), and normalization factors. +`explanation.details` | Array of objects | An array of nested explanation objects that break down the score calculation into component parts. Each detail object has the same structure as the explanation object (with `value`, `description`, and `details` fields). +`get` | Object | The document metadata and source data. Only included when the `_source` or `stored_fields` parameters are used. Contains fields such as `_seq_no`, `_primary_term`, `found`, and `_source`. +`get._source` | Object | The document's original JSON content. Only included when the `_source` parameter is specified. + +## BM25 scoring components + +The explanation details include the following BM25 scoring components. + +Field | Description +:--- | :--- +`idf` | The inverse document frequency. Measures how rare or common a term is across all documents in the index. Calculated as `log(1 + (N - n + 0.5) / (n + 0.5))`, where `N` is the total number of documents with the field and `n` is the number of documents containing the term. Rarer terms have higher IDF values and contribute more to the relevance score. +`tf` | The term frequency. Measures how often the term appears in the document field. Calculated as `freq / (freq + k1 * (1 - b + b * dl / avgdl))`, where `freq` is the number of times the term appears, `k1` is the term saturation parameter (default 1.2), `b` is the length normalization parameter (default 0.75), `dl` is the field length, and `avgdl` is the average field length across all documents. More frequent terms contribute more to the relevance score, but with diminishing returns. +`k1` | The term saturation parameter. Controls how quickly the score increases as term frequency increases. The default value is 1.2. Lower values cause the score to saturate more quickly, while higher values allow term frequency to have a greater impact on the score. +`b` | The length normalization parameter. Controls how much field length affects the score. The default value is 0.75. A value of 0 disables length normalization, while a value of 1 fully normalizes by field length. Shorter fields with matching terms typically receive higher scores. +`dl` | The document field length. The number of tokens in the field for this specific document. +`avgdl` | The average document field length. The average number of tokens in the field across all documents in the index. +`boost` | The query boost value. A multiplier applied to the score. The default boost is 1.0 when not explicitly specified in the query. + +The final relevance score is calculated by multiplying these components together: `score = boost * idf * tf`. The values are calculated and stored at index time when a document is added or updated and may have small inaccuracies based on shard-level statistics. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/explain`. diff --git a/_api-reference/search-apis/field-caps.md b/_api-reference/search-apis/field-caps.md new file mode 100644 index 00000000..504e151b --- /dev/null +++ b/_api-reference/search-apis/field-caps.md @@ -0,0 +1,254 @@ +--- +layout: default +title: Field capabilities +parent: Search APIs +nav_order: 45 +--- + +# Field capabilities API +**Introduced 1.0** +{: .label .label-purple } + +The `_field_caps` API provides information about the capabilities of fields across one or more indexes. It is typically used by clients to determine how fields are mapped and whether they can be used for search, sorting, and aggregations across multiple indexes. + +This API is particularly useful when indexes have varying mappings and a query needs to evaluate field compatibility across them. + +## Endpoints + +```json +GET /_field_caps +POST /_field_caps +GET /{index}/_field_caps +POST /{index}/_field_caps +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | List or String | A comma-separated list of data streams, indexes, and aliases used to limit the request. Supports wildcards (*). To target all data streams and indexes, omit this parameter or use * or `_all`. _Optional_. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `allow_no_indices` | Boolean | If `false`, the request returns an error if any wildcard expression, index alias, or `_all` value targets only missing or closed indexes. This behavior applies even if the request targets other open indexes. For example, a request targeting `foo*,bar*` returns an error if an index starts with foo but no index starts with bar. Default is `true`. | +| `expand_wildcards` | List or String | The type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. Supports comma-separated values, such as `open,hidden`.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes.
Default is `open`. | +| `fields` | List or String | A comma-separated list of fields to retrieve capabilities for. Wildcard (`*`) expressions are supported. | +| `ignore_unavailable` | Boolean | If `true`, missing or closed indexes are not included in the response. Default is `false`. | +| `include_unmapped` | Boolean | If `true`, unmapped fields are included in the response. Default is `false`. | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :------------- | :-------- | :---------------------------------------------------------------------- | +| `index_filter` | Object | A query DSL object used to filter indexes included in the request. See [Example: Using an index filter](#example-using-an-index-filter). _Optional_.| + +## Example requests + +Create two indexes with different mappings for the same field: + +```json +PUT /store-west +{ + "mappings": { + "properties": { + "product": { "type": "text" }, + "price": { "type": "float" } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /store-east +{ + "mappings": { + "properties": { + "product": { "type": "keyword" }, + "price": { "type": "float" } + } + } +} +``` +{% include copy-curl.html %} + +Query field capabilities across both indexes: + + +{% capture step1_rest %} +GET /store-west,store-east/_field_caps?fields=product,price +{% endcapture %} + +{% capture step1_python %} + + +response = client.field_caps( + index = "store-west,store-east", + params = { "fields": "product,price" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example response + +The response provides the capabilities of the available fields: + +```json +{ + "indices": [ + "store-east", + "store-west" + ], + "fields": { + "product": { + "text": { + "type": "text", + "searchable": true, + "aggregatable": false, + "indices": [ + "store-west" + ] + }, + "keyword": { + "type": "keyword", + "searchable": true, + "aggregatable": true, + "indices": [ + "store-east" + ] + } + }, + "price": { + "float": { + "type": "float", + "searchable": true, + "aggregatable": true + } + } + } +} +``` + +## Example: Using an index filter + +You can restrict the indexes considered using an `index_filter`. The `index_filter` filters out indexes based on field-level metadata, not actual document content. The following request limits the index selection to those that contain mappings containing a `product` field, even if there are no documents indexed: + + +{% capture step1_rest %} +POST /_field_caps?fields=product,price +{ + "index_filter": { + "term": { + "product": "notebook" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.field_caps( + params = { "fields": "product,price" }, + body = { + "index_filter": { + "term": { + "product": "notebook" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example response + +The response only includes the field from indexes that contain a `product` field with a value of `notebook`: + +```json +{ + "indices": [ + "store-east", + "store-west" + ], + "fields": { + "product": { + "text": { + "type": "text", + "searchable": true, + "aggregatable": false, + "indices": [ + "store-west" + ] + }, + "keyword": { + "type": "keyword", + "searchable": true, + "aggregatable": true, + "indices": [ + "store-east" + ] + } + }, + "price": { + "float": { + "type": "float", + "searchable": true, + "aggregatable": true + } + } + } +} +``` + +### Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :----------------------------------------------- | :----------- | :----------------------------------------------------------------------------------------------------------------------- | +| `indices` | List | The list of indexes included in the response. | +| `fields` | Object | A map of types to field capabilities, where each key is a field name and its value is an object. | +| `fields...type` | String | The data type of the field (for example, `float`, `text`, `keyword`). | +| `fields...searchable` | Boolean | Whether the field is searchable. In indexes that use a pluggable data format, numeric, `date`, `date_nanos`, `ip`, and `boolean` fields are not indexed, but OpenSearch can still run `range`, `term`, and `terms` queries on them using doc values. Starting with OpenSearch 3.10, `searchable` is `true` for these fields when `doc_values` is enabled. For more information, see [Pluggable data format indexes]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/index-parameter/#pluggable-data-format-indexes). | +| `fields...aggregatable` | Boolean | Whether the field can be used in aggregations like `sum` or `terms`. | +| `fields...indices` | List | A list of indexes in which this field appears with the corresponding type. | +| `fields...non_searchable_indices` | List or null | A list of indexes in which the field is *not* searchable. `null` means that the field is not searchable in any index. | +| `fields...non_aggregatable_indices` | List or null | A list of indexes in which the field is *not* aggregatable. `null` means that the field is not aggregatable in any index. | +| `fields...meta` | Object | Merged metadata values from all mappings. Keys are custom metadata keys, and values are arrays of values across indexes. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/field_caps` and `indices:data/read/field_caps*`. diff --git a/_api-reference/search-apis/index.md b/_api-reference/search-apis/index.md new file mode 100644 index 00000000..f321562c --- /dev/null +++ b/_api-reference/search-apis/index.md @@ -0,0 +1,47 @@ +--- +layout: default +title: Search APIs +nav_order: 100 +has_children: true +has_toc: false +redirect_from: + - /api-reference/search-apis/ +--- + +# Search APIs +**Introduced 1.0** +{: .label .label-purple } + +OpenSearch provides a comprehensive suite of search-related APIs that allow you to perform various search operations, test and validate your searches, and work with search templates. OpenSearch supports the following Search APIs. + +The endpoint paths listed on this page (for example, `GET /{index}/_search`) are relative to your OpenSearch host and port. The full URL format is `https://:/{index}/_search`, for which the default port is `9200`. For more information about connecting to OpenSearch, see [Communicating with OpenSearch]({{site.url}}{{site.baseurl}}/getting-started/communicate/). +{: .note} + +## Core search APIs + +These APIs form the foundation of OpenSearch's search capabilities: + +- **[Search]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/)**: Run search queries across one or more indexes. +- **[Multi-search]({{site.url}}{{site.baseurl}}/api-reference/search-apis/multi-search/)**: Run multiple search requests in a single API call. +- **[Point in Time]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/)**: Create a consistent view of the index for search operations. +- **[Scroll]({{site.url}}{{site.baseurl}}/api-reference/search-apis/scroll/)**: Retrieve large numbers of results from a search query. +- **[Count]({{site.url}}{{site.baseurl}}/api-reference/search-apis/count/)**: Get the number of documents that match a query. + +## Search testing APIs + +These APIs help you test, debug, and optimize your search operations: + +- **[Explain]({{site.url}}{{site.baseurl}}/api-reference/search-apis/explain/)**: Explain how a specific document matches (or doesn't match) a query. +- **[Field capabilities]({{site.url}}{{site.baseurl}}/api-reference/search-apis/field-caps/)**: Get the capabilities of fields across multiple indexes. +- **[Profile]({{site.url}}{{site.baseurl}}/api-reference/search-apis/profile/)**: Profile the execution of search requests. +- **[Ranking evaluation]({{site.url}}{{site.baseurl}}/api-reference/search-apis/rank-eval/)**: Evaluate the quality of search results. +- **[Search shards]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-shards/)**: Get information about the shards on which a search request would be executed. +- **[Validate]({{site.url}}{{site.baseurl}}/api-reference/search-apis/validate/)**: Validate a potentially expensive query before executing it. + +## Search template APIs + +These APIs allow you to work with search templates: + +- **[Search template]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/)**: Use search templates to run parameterized search queries. +- **[Multi-search template]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/msearch-template/)**: Execute multiple search template requests in a single API call. +- **[Render template]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/render-template/)**: Previews the final query generated from a search template by substituting parameters without executing the search. diff --git a/_api-reference/search-apis/multi-search.md b/_api-reference/search-apis/multi-search.md new file mode 100644 index 00000000..d0b56244 --- /dev/null +++ b/_api-reference/search-apis/multi-search.md @@ -0,0 +1,469 @@ +--- +layout: default +title: Multi-search +parent: Search APIs +nav_order: 20 +redirect_from: + - /opensearch/rest-api/multi-search/ + - /api-reference/multi-search/ +--- + +# Multi-Search API +**Introduced 1.0** +{: .label .label-purple } + +As the name suggests, the multi-search operation lets you bundle multiple search requests into a single request. OpenSearch then executes the searches in parallel, so you get back the response more quickly compared to sending one request per search. OpenSearch executes each search independently, so the failure of one doesn't affect the others. + + + +## Endpoints +```json +GET /_msearch +POST /_msearch +GET /{index}/_msearch +POST /{index}/_msearch +``` + + +Specifying an index in the path sets the default target for any searches whose metadata line does not include an `index` field. If you omit the path parameter and a search's metadata line also does not specify an `index`, the search runs against all indexes. + + +## Query parameters and metadata options + +All parameters are optional. Some can also be applied per-search as part of each metadata line. + +Parameter | Type | Description | Supported in metadata line +:--- | :--- | :--- | :--- +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. | Yes +`cancel_after_time_interval` | Time | The time after which the search request will be canceled. Supported at both parent and child request levels. The order of precedence is:
1. Child-level parameter
2. Parent-level parameter
3. [Cluster settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-settings/).
Default is -1. | Yes +`ccs_minimize_roundtrips` | Boolean | Whether OpenSearch should try to minimize the number of network round trips between the coordinating node and remote clusters (only applicable to cross-cluster search requests). Default is `true`. | No +`expand_wildcards` | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. | Yes +`ignore_unavailable` | Boolean | If an index or shard from the indexes list doesn't exist, whether to ignore it rather than fail the query. Default is `false`. | Yes +`include_named_queries_score` | Boolean | Whether to return scores for named queries. Default is `false`. | No +`max_concurrent_searches` | Integer | The maximum number of concurrent searches. The default depends on your node count and search thread pool size. Higher values can improve performance, but risk overloading the cluster. | No +`max_concurrent_shard_requests` | Integer | Maximum number of concurrent shard requests that each search executes per node. Default is 5. Higher values can improve performance, but risk overloading the cluster. | No +`pre_filter_shard_size` | Integer | A threshold that triggers a pre-filter round trip to eliminate shards that cannot match the query (for example, because a date range filter falls outside the shard's bounds). When unspecified, the pre-filter phase runs if the request targets more than 128 shards, targets a read-only index, or sorts on an indexed field. Default is `128`. | No +`rest_total_hits_as_int` | String | Whether the `hits.total` property is returned as an integer (`true`) or an object (`false`). Default is `false`. | No +`routing` | String | Comma-separated custom routing values used to route all searches in the request to specific shards. To set routing for individual searches, use the `routing` option in the metadata line instead. | No +`search_type` | String | Affects relevance score. Valid options are `query_then_fetch` and `dfs_query_then_fetch`. `query_then_fetch` scores documents using term and document frequencies for the shard (faster, less accurate), whereas `dfs_query_then_fetch` uses term and document frequencies across all shards (slower, more accurate). Default is `query_then_fetch`. | Yes +`typed_keys` | Boolean | Whether to prefix aggregation names with their internal types in the response. Default is `false`. | No + + +## Metadata-only options + +Some options can't be applied as parameters to the entire request. Instead, you can apply them per-search as part of each metadata line. All are optional. + +Option | Type | Description +:--- | :--- | :--- +`index` | String, string array | If you don't specify an index or multiple indexes as part of the URL (or want to override the URL value for an individual search), you can include it here. Examples include `"logs-*"` and `["my-store", "sample_data_ecommerce"]`. +`preference` | String | The nodes or shards that you'd like to perform the search. This setting can be useful for testing, but in most situations, the default behavior provides the best search latencies. Options include `_local`, `_only_local`, `_prefer_nodes`, `_only_nodes`, and `_shards`. These last three options accept a list of nodes or shards. Examples include `"_only_nodes:data-node1,data-node2"` and `"_shards:0,1`. +`request_cache` | Boolean | Whether to cache results, which can improve latency for repeat searches. Default is to use the `index.requests.cache.enable` setting for the index (which defaults to `true` for new indexes). +`routing` | String | Comma-separated custom routing values, for example, `"routing": "value1,value2,value3"`. Unlike `routing` at the query parameter level, which applies to all searches in the request, this option targets routing for an individual search only. + +## Request body + +The multi-search request body uses newline-delimited JSON (NDJSON) format, alternating between metadata and query lines: + +``` +Metadata\n +Query\n +Metadata\n +Query\n + +``` + +- Metadata lines include options, such as which indexes to search and the type of search. A metadata line can be empty (`{}`) if no per-search overrides are needed. +- Query lines use the [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). + +Like the [bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) operation, the JSON doesn't need to be minified---spaces are fine---but it does need to be on a single line. OpenSearch uses newline characters to parse multi-search requests and requires that the request body end with a newline character. + +When sending requests to this endpoint, set the `Content-Type` header to `application/x-ndjson`. +{: .note} + +### Query body fields + +Each query line accepts the same parameters as the [Search API]({{site.url}}{{site.baseurl}}/api-reference/search/) request body. The following table lists the most commonly used fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `query` | Object | The query DSL expression to execute. See [Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). | +| `aggregations` | Object | Aggregations to run alongside the search. See [Aggregations]({{site.url}}{{site.baseurl}}/aggregations/). | +| `from` | Integer | The starting offset for returned hits. Default is `0`. | +| `size` | Integer | The number of hits to return. Default is `10`. | +| `sort` | Array or Object | The fields and order by which to sort results. | +| `_source` | Boolean, String, or Object | Controls which fields are included in the `_source` of each hit. | +| `highlight` | Object | Highlight configuration for matched fields. | + + +## Example: Searching multiple indexes + +The following example runs queries against multiple indexes, specifying the target index in each metadata line: + + + +{% capture step1_rest %} +GET /_msearch +{ "index": "opensearch_dashboards_sample_data_logs"} +{ "query": { "match_all": {} }, "from": 0, "size": 10} +{ "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} +{ "query": { "match_all": {} } } +{% endcapture %} + +{% capture step1_python %} + + +response = client.msearch( + body = ''' +{ "index": "opensearch_dashboards_sample_data_logs"} +{ "query": { "match_all": {} }, "from": 0, "size": 10} +{ "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} +{ "query": { "match_all": {} } } +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example: Using a default index + +When you specify an index in the URL path, that index serves as the default for any searches whose metadata line does not include an `index` field. The following example runs two queries against the `products` index without repeating the index name in each metadata line: + + +{% capture step1_rest %} +GET /products/_msearch +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} +{% endcapture %} + +{% capture step1_python %} + + +response = client.msearch( + index = "products", + body = ''' +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Using search templates + +The multi-search API supports [search templates]({{site.url}}{{site.baseurl}}/search-plugins/search-template/) through the `_msearch/template` endpoint. This lets you execute parameterized searches, separating the query structure from the values passed at search time. + +### Example: Inline templates + +The following request uses inline templates to run two parameterized searches in a single call: + +```json +GET _msearch/template +{"index": "products"} +{"source": {"query": {"match": {"product_name": "{{search_term}}"}}}, "params": {"search_term": "wireless"}} +{"index": "products"} +{"source": {"query": {"range": {"price": {"lte": "{{max_price}}"}}}}, "params": {"max_price": "75"}} + +``` + +### Example: Stored templates + +You can also reference pre-registered templates by ID. First, create the stored templates: + +```json +POST _scripts/product_search_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "multi_match": { + "query": "{{query_text}}", + "fields": ["product_name", "description"] + } + }, + "size": "{{result_count}}" + } + } +} +``` +{% include copy-curl.html %} + +```json +POST _scripts/price_range_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "range": { + "price": { + "gte": "{{min_price}}", + "lte": "{{max_price}}" + } + } + }, + "size": "{{result_count}}" + } + } +} +``` +{% include copy-curl.html %} + +Then use the stored templates in a multi-search request: + +```json +GET _msearch/template +{"index": "products"} +{"id": "product_search_template", "params": {"query_text": "bluetooth speaker", "result_count": "5"}} +{"index": "products"} +{"id": "price_range_template", "params": {"min_price": "20", "max_price": "100", "result_count": "3"}} + +``` + +## Example response + +OpenSearch returns an array with the results of each search in the same order as the multi-search request. + +```json +{ + "took" : 2150, + "responses" : [ + { + "took" : 2149, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10000, + "relation" : "gte" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "opensearch_dashboards_sample_data_logs", + "_id" : "_fnhBXsBgv2Zxgu9dZ8Y", + "_score" : 1.0, + "_source" : { + "agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)", + "bytes" : 4657, + "clientip" : "213.116.129.196", + "extension" : "zip", + "geo" : { + "srcdest" : "CN:US", + "src" : "CN", + "dest" : "US", + "coordinates" : { + "lat" : 42.35083333, + "lon" : -86.25613889 + } + }, + "host" : "artifacts.opensearch.org", + "index" : "opensearch_dashboards_sample_data_logs", + "ip" : "213.116.129.196", + "machine" : { + "ram" : 16106127360, + "os" : "ios" + }, + "memory" : null, + "message" : "213.116.129.196 - - [2018-07-30T14:12:11.387Z] \"GET /opensearch_dashboards/opensearch_dashboards-1.0.0-windows-x86_64.zip HTTP/1.1\" 200 4657 \"-\" \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\"", + "phpmemory" : null, + "referer" : "http://twitter.com/success/ellison-onizuka", + "request" : "/opensearch_dashboards/opensearch_dashboards-1.0.0-windows-x86_64.zip", + "response" : 200, + "tags" : [ + "success", + "info" + ], + "timestamp" : "2021-08-02T14:12:11.387Z", + "url" : "https://artifacts.opensearch.org/downloads/opensearch_dashboards/opensearch_dashboards-1.0.0-windows-x86_64.zip", + "utc_time" : "2021-08-02T14:12:11.387Z", + "event" : { + "dataset" : "sample_web_logs" + } + } + }, + ... + ] + }, + "status" : 200 + }, + { + "took" : 1473, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 4675, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "opensearch_dashboards_sample_data_ecommerce", + "_id" : "efnhBXsBgv2Zxgu9ap7e", + "_score" : 1.0, + "_source" : { + "category" : [ + "Women's Clothing" + ], + "currency" : "EUR", + "customer_first_name" : "Gwen", + "customer_full_name" : "Gwen Dennis", + "customer_gender" : "FEMALE", + "customer_id" : 26, + "customer_last_name" : "Dennis", + "customer_phone" : "", + "day_of_week" : "Tuesday", + "day_of_week_i" : 1, + "email" : "gwen@dennis-family.zzz", + "manufacturer" : [ + "Tigress Enterprises", + "Gnomehouse mom" + ], + "order_date" : "2021-08-10T16:24:58+00:00", + "order_id" : 576942, + "products" : [ + { + "base_price" : 32.99, + "discount_percentage" : 0, + "quantity" : 1, + "manufacturer" : "Tigress Enterprises", + "tax_amount" : 0, + "product_id" : 22182, + "category" : "Women's Clothing", + "sku" : "ZO0036600366", + "taxless_price" : 32.99, + "unit_discount_amount" : 0, + "min_price" : 14.85, + "_id" : "sold_product_576942_22182", + "discount_amount" : 0, + "created_on" : "2016-12-20T16:24:58+00:00", + "product_name" : "Jersey dress - black/red", + "price" : 32.99, + "taxful_price" : 32.99, + "base_unit_price" : 32.99 + }, + { + "base_price" : 28.99, + "discount_percentage" : 0, + "quantity" : 1, + "manufacturer" : "Gnomehouse mom", + "tax_amount" : 0, + "product_id" : 14230, + "category" : "Women's Clothing", + "sku" : "ZO0234902349", + "taxless_price" : 28.99, + "unit_discount_amount" : 0, + "min_price" : 13.05, + "_id" : "sold_product_576942_14230", + "discount_amount" : 0, + "created_on" : "2016-12-20T16:24:58+00:00", + "product_name" : "Blouse - june bug", + "price" : 28.99, + "taxful_price" : 28.99, + "base_unit_price" : 28.99 + } + ], + "sku" : [ + "ZO0036600366", + "ZO0234902349" + ], + "taxful_total_price" : 61.98, + "taxless_total_price" : 61.98, + "total_quantity" : 2, + "total_unique_products" : 2, + "type" : "order", + "user" : "gwen", + "geoip" : { + "country_iso_code" : "US", + "location" : { + "lon" : -118.2, + "lat" : 34.1 + }, + "region_name" : "California", + "continent_name" : "North America", + "city_name" : "Los Angeles" + }, + "event" : { + "dataset" : "sample_ecommerce" + } + } + }, + ... + ] + }, + "status" : 200 + } + ] +} +``` + +## Response body fields + +The following table lists the top-level response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `took` | Integer | The total time, in milliseconds, for OpenSearch to process all searches in the request. | +| `responses` | Array | An array of search response objects, returned in the same order as the corresponding searches in the request. If a particular search fails completely, the array entry for that search contains an `error` object and a `status` code instead of the normal search response. | + +The following table lists the fields within each entry of the `responses` array. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `took` | Integer | The time, in milliseconds, for OpenSearch to process the individual search. | +| `timed_out` | Boolean | Whether the search timed out before completing. | +| `_shards` | Object | Information about the number of shards involved in the search, including `total`, `successful`, `skipped`, and `failed` counts. | +| `hits` | Object | The search results, including `total` hit count, `max_score`, and an array of matching `hits`. | +| `status` | Integer | The HTTP status code for the individual search result. A value of `200` indicates success. | + +## Partial responses + +If one or more shards fail during execution, the multi-search API still returns results from the successful shards. Each individual search response in the `responses` array includes a `_shards` object that reports how many shards succeeded and how many failed, allowing you to determine whether results are complete. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/msearch`. diff --git a/_api-reference/search-apis/point-in-time-api.md b/_api-reference/search-apis/point-in-time-api.md new file mode 100644 index 00000000..8fddabbd --- /dev/null +++ b/_api-reference/search-apis/point-in-time-api.md @@ -0,0 +1,342 @@ +--- +layout: default +title: Point in Time +nav_order: 25 +has_children: false +parent: Search APIs +redirect_from: + - /opensearch/point-in-time-api/ + - /search-plugins/point-in-time-api/ + - /search-plugins/searching-data/point-in-time-api/ +--- + +# Point in Time API + +Use the [Point in Time (PIT)]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/) APIs to manage PITs. + +--- + +#### Table of contents +- TOC +{:toc} + +--- + +## Create a PIT +**Introduced 2.4** +{: .label .label-purple } + +Creates a PIT. The `keep_alive` query parameter is required; it specifies how long to keep a PIT. + +Each node can hold a limited number of open PITs, set by the `search.max_open_pit_context` setting (default `300`). For more information, see [PIT settings]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/#pit-settings). + +### Endpoints + +```json +POST /{target_indexes}/_search/point_in_time +``` + +### Path parameters + +Parameter | Data type | Description +:--- | :--- | :--- +`target_indexes` | String | The name(s) of the target index(es) for the PIT. May contain a comma-separated list or a wildcard index pattern. + +### Query parameters + +Parameter | Data type | Description +:--- | :--- | :--- +`keep_alive` | Time | The amount of time to keep the PIT. The countdown restarts each time a search uses the PIT. If the search specifies a `keep_alive` value, the PIT's keep-alive becomes the larger of the current value and the new value, so a shorter value does not shorten it. The maximum value is set by the `point_in_time.max_keep_alive` cluster setting (default `24h`). Required. +`preference` | String | The node or shard used to perform the search. Optional. +`routing` | String | Routes the PIT to the shards for the specified routing value. Optional. By default, all shards are used. +`expand_wildcards` | String | The type of index that can match the wildcard pattern. Supports comma-separated values. Valid values are the following:
- `all`: Match any index or data stream, including hidden ones.
- `open`: Match open, non-hidden indexes or non-hidden data streams.
- `hidden`: Match hidden indexes or data streams. Must be combined with `open`.
- `none`: No wildcard patterns are accepted.
Closed indexes cannot be PIT targets, so the `closed` value is not supported. Optional. Default is `open`. +`ignore_unavailable` | Boolean | Whether to ignore missing or closed indexes when creating the PIT. If `false`, the request fails if any target index is missing or closed. Optional. Default is `false`. +`allow_partial_pit_creation` | Boolean | Specifies whether to create a PIT with partial failures. If `false`, the request fails when any shard is unavailable. Optional. Default is `true`. + +#### Example request + + +{% capture step1_rest %} +POST /my-index-1/_search/point_in_time?keep_alive=100m +{% endcapture %} + +{% capture step1_python %} + + +response = client.create_pit( + index = "my-index-1", + params = { "keep_alive": "100m" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +```json +{ + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAIWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "creation_time": 1658146050064 +} +``` + +### Response body fields + +Field | Data type | Description +:--- | :--- | :--- +`pit_id` | [Base64-encoded binary]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/binary/) | The PIT ID. +`_shards` | Object | Information about the shards on which the PIT was created. +`creation_time` | `long` | The time at which the PIT was created, in milliseconds since the epoch. + +The `_shards` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`total` | Integer | The total number of shards targeted by the PIT. +`successful` | Integer | The number of shards on which the PIT was created successfully. +`skipped` | Integer | The number of skipped shards. +`failed` | Integer | The number of shards on which the PIT could not be created. + +## Extend a PIT time + +To search using a PIT, provide the PIT ID in the `pit` object of a search request. Do not specify an index in the request path because the PIT already determines the target indexes; a search that specifies both an index and a PIT is rejected. For more information, see [Pagination with PIT and search_after]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/#pagination-with-pit-and-search_after). + +You can extend a PIT time by providing a `keep_alive` parameter in the `pit` object when you perform a search: + +```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" + ] +} +``` + +The `keep_alive` parameter in a search request is optional. Each search that uses the PIT restarts the keep-alive countdown. If you specify `keep_alive`, the PIT's keep-alive becomes the larger of the current value and the new value. +{: .note} + +## List all PITs +**Introduced 2.4** +{: .label .label-purple } + +Returns all PITs in the OpenSearch cluster. + +### Cross-cluster behavior + +The List All PITs API returns only local PITs or mixed PITs (PITs created in both local and remote clusters). It does not return fully remote PITs. + +#### Example request + + +{% capture step1_rest %} +GET /_search/point_in_time/_all +{% endcapture %} + +{% capture step1_python %} + +response = client.get_all_pits() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +```json +{ + "pits": [ + { + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAEWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "creation_time": 1658146048666, + "keep_alive": 6000000 + }, + { + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAIWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "creation_time": 1658146050064, + "keep_alive": 6000000 + } + ] +} +``` + +### Response body fields + +Field | Data type | Description +:--- | :--- | :--- +`pits` | Array of JSON objects | The list of all PITs. + +Each PIT object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`pit_id` | [Base64-encoded binary]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/binary/) | The PIT ID. +`creation_time` | `long` | The time at which the PIT was created, in milliseconds since the epoch. +`keep_alive` | `long` | The amount of time to keep the PIT, in milliseconds. + +## Delete PITs +**Introduced 2.4** +{: .label .label-purple } + +Deletes one, several, or all PITs. PITs are automatically deleted when the `keep_alive` time period elapses. However, to deallocate resources, you can delete a PIT using the Delete PIT API. The Delete PIT API supports deleting a list of PITs by ID or deleting all PITs at once. + +### Cross-cluster behavior + +The Delete PITs by ID API fully supports deleting cross-cluster PITs. + +The Delete All PITs API deletes only local PITs or mixed PITs (PITs created in both local and remote clusters). It does not delete fully remote PITs. + +#### Example request: Delete all PITs + +The Delete All PITs API deletes every PIT in the cluster, including PITs created by other users and applications. Searches that use the deleted PITs fail. +{: .warning} + + +{% capture step1_rest %} +DELETE /_search/point_in_time/_all +{% endcapture %} + +{% capture step1_python %} + +response = client.delete_all_pits() +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +If you want to delete one or several PITs, specify their PIT IDs in the request body. + +### Request body fields + +Field | Data type | Description +:--- | :--- | :--- +`pit_id` | [Base64-encoded binary]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/binary/) or an array of binaries | The PIT IDs of the PITs to be deleted. Required. + +#### Example request: Delete PITs by ID + + +{% capture step1_rest %} +DELETE /_search/point_in_time +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_pit( + body = { + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +#### Example response + +For each PIT, the response contains a JSON object with a PIT ID and a `successful` field that specifies whether the deletion was successful. Partial failures are treated as failures. + +```json +{ + "pits": [ + { + "successful": true, + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + }, + { + "successful": false, + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + } + ] +} +``` + +### Response body fields + +Field | Data type | Description +:--- | :--- | :--- +`successful` | Boolean | Whether the delete operation was successful. +`pit_id` | [Base64-encoded binary]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/binary/) | The PIT ID of the PIT to be deleted. + +## Security model + +This section describes the permissions needed to use PIT API operations if you are running OpenSearch with the Security plugin enabled. + +You can access all PIT API operations using the `point_in_time_full_access` role. If this role doesn't meet your needs, mix and match individual PIT permissions to suit your use case. Each action corresponds to an operation in the REST API. For example, the `indices:data/read/point_in_time/create` permission lets you create a PIT. The following are the possible permissions: + +- `indices:data/read/point_in_time/create` – Create API +- `indices:data/read/point_in_time/delete` – Delete API +- `indices:data/read/point_in_time/readall` – List All PITs API +- `indices:data/read/search` – Search API +- `indices:monitor/point_in_time/segments` – PIT Segments API + +For `all` API operations, such as list all and delete all, the user needs the all indexes (*) permission. For API operations such as search, create PIT, or delete list, the user only needs individual index permissions. + +The PIT IDs always contain the underlying (resolved) indexes when saved. The following sections describe the required permissions for aliases and data streams. + +### Alias permissions + +For aliases, users must have either index **or** alias permissions for any PIT operation. + +### Data stream permissions + +For data streams, users must have both the data stream **and** the data stream's backing index permissions for any PIT operation. For example, the user must have permissions for the `data-stream-11` data stream and for its backing index `.ds-my-data-stream11-000001`. + +If users have the data stream permissions only, they will be able to create a PIT, but they will not be able to use the PIT ID for other operations, such as search, without the backing index permissions. diff --git a/_api-reference/search-apis/profile.md b/_api-reference/search-apis/profile.md new file mode 100644 index 00000000..f7d48483 --- /dev/null +++ b/_api-reference/search-apis/profile.md @@ -0,0 +1,1200 @@ +--- +layout: default +title: Profile +parent: Search APIs +nav_order: 55 +redirect_from: + - /api-reference/profile/ +--- + +# Profile API +**Introduced 1.0** +{: .label .label-purple } + +The Profile API provides timing information about the execution of individual components of a search request. Using the Profile API, you can debug slow requests and understand how to improve their performance. The Profile API does not measure the following: + +- Network latency +- Amount of time a request spends in queues +- Idle time while merging shard responses on the coordinating node + +The Profile API is a resource-consuming operation that adds overhead to search operations. +{: .warning} + +## Endpoints + +```json +GET /testindex/_search +{ + "profile": true, + "query" : { + "match" : { "title" : "wind" } + } +} +``` + +## Concurrent segment search + +[Concurrent segment search]({{site.url}}{{site.baseurl}}/search-plugins/concurrent-segment-search/) allows each shard-level request to search segments in parallel during the query phase. The Profile API response contains several additional fields with statistics about _slices_. + +A slice is the unit of work that can be executed by a thread. Each query can be partitioned into multiple slices, with each slice containing one or more segments. All the slices can be executed either in parallel or in some order depending on the available threads in the pool. + +In general, the max/min/avg slice time captures statistics across all slices for a timing type. For example, when profiling aggregations, the `max_slice_time_in_nanos` field in the `aggregations` section shows the maximum time consumed by the aggregation operation and its children across all slices. + +## Example request: Non-concurrent search + +To use the Profile API, include the `profile` parameter set to `true` in the search request sent to the `_search` endpoint: + + +{% capture step1_rest %} +GET /testindex/_search +{ + "profile": true, + "query": { + "match": { + "title": "wind" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "testindex", + body = { + "profile": true, + "query": { + "match": { + "title": "wind" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To turn on human-readable format, include the `?human=true` query parameter in the request: + + +{% capture step1_rest %} +GET /testindex/_search?human=true +{ + "profile": true, + "query": { + "match": { + "title": "wind" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "testindex", + params = { "human": "true" }, + body = { + "profile": true, + "query": { + "match": { + "title": "wind" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains an additional `time` field with human-readable units, for example: + +```json +"collector": [ + { + "name": "SimpleTopScoreDocCollector", + "reason": "search_top_hits", + "time": "113.7micros", + "time_in_nanos": 113711 + } +] +``` + +The Profile API response is verbose, so if you're running the request through the `curl` command, include the `?pretty` query parameter to make the response easier to understand. +{: .tip} + +## Example request: Aggregations + +To profile aggregations, send an aggregation request and provide the `profile` parameter set to `true`. + +### Global aggregation + + +{% capture step1_rest %} +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "profile": "true", + "size": 0, + "query": { + "match": { + "manufacturer": "Elitelligence" + } + }, + "aggs": { + "all_products": { + "global": {}, + "aggs": { + "avg_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + }, + "elitelligence_products": { + "avg": { + "field": "taxful_total_price" + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "opensearch_dashboards_sample_data_ecommerce", + body = { + "profile": "true", + "size": 0, + "query": { + "match": { + "manufacturer": "Elitelligence" + } + }, + "aggs": { + "all_products": { + "global": {}, + "aggs": { + "avg_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + }, + "elitelligence_products": { + "avg": { + "field": "taxful_total_price" + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Non-global aggregation + + +{% capture step1_rest %} +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "opensearch_dashboards_sample_data_ecommerce", + body = { + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response: Non-concurrent search + +The response contains profiling information: + +
+ + Response + + {: .text-delta} + +```json +{ + "took": 21, + "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", + "description": "A 1939 American epic historical film" + } + } + ] + }, + "profile": { + "shards": [ + { + "id": "[LidyZ1HVS-u93-73Z49dQg][testindex][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "BooleanQuery", + "description": "title:wind title:rise", + "time_in_nanos": 2473919, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 5209, + "match": 0, + "next_doc_count": 2, + "score_count": 2, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 9209, + "advance_count": 2, + "score": 20751, + "build_scorer_count": 4, + "create_weight": 1404458, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 1034292 + }, + "children": [ + { + "type": "TermQuery", + "description": "title:wind", + "time_in_nanos": 813581, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 3291, + "match": 0, + "next_doc_count": 2, + "score_count": 2, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 7208, + "advance_count": 2, + "score": 18666, + "build_scorer_count": 6, + "create_weight": 616375, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 168041 + } + }, + { + "type": "TermQuery", + "description": "title:rise", + "time_in_nanos": 191083, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 0, + "match": 0, + "next_doc_count": 0, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 0, + "advance_count": 0, + "score": 0, + "build_scorer_count": 2, + "create_weight": 188625, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 2458 + } + } + ] + } + ], + "rewrite_time": 192417, + "collector": [ + { + "name": "SimpleTopScoreDocCollector", + "reason": "search_top_hits", + "time_in_nanos": 77291 + } + ] + } + ], + "aggregations": [] + } + ] + } +} +``` +
+ +### Concurrent segment search + +The following is an example response for a concurrent segment search with three segment slices: + +
+ + Response + + {: .text-delta} + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + ... + ] + }, + "aggregations": { + ... + }, + "profile": { + "shards": [ + { + "id": "[9Y7lbpaWRhyr5Y-41Zl48g][idx][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "MatchAllDocsQuery", + "description": "*:*", + "time_in_nanos": 868000, + "max_slice_time_in_nanos": 19376, + "min_slice_time_in_nanos": 12250, + "avg_slice_time_in_nanos": 16847, + "breakdown": { + "max_match": 0, + "set_min_competitive_score_count": 0, + "match_count": 0, + "avg_score_count": 1, + "shallow_advance_count": 0, + "next_doc": 29708, + "min_build_scorer": 3125, + "score_count": 5, + "compute_max_score_count": 0, + "advance": 0, + "min_set_min_competitive_score": 0, + "min_advance": 0, + "score": 29250, + "avg_set_min_competitive_score_count": 0, + "min_match_count": 0, + "avg_score": 333, + "max_next_doc_count": 3, + "max_compute_max_score_count": 0, + "avg_shallow_advance": 0, + "max_shallow_advance_count": 0, + "set_min_competitive_score": 0, + "min_build_scorer_count": 2, + "next_doc_count": 8, + "min_match": 0, + "avg_next_doc": 888, + "compute_max_score": 0, + "min_set_min_competitive_score_count": 0, + "max_build_scorer": 5791, + "avg_match_count": 0, + "avg_advance": 0, + "build_scorer_count": 6, + "avg_build_scorer_count": 2, + "min_next_doc_count": 2, + "min_shallow_advance_count": 0, + "max_score_count": 2, + "avg_match": 0, + "avg_compute_max_score": 0, + "max_advance": 0, + "avg_shallow_advance_count": 0, + "avg_set_min_competitive_score": 0, + "avg_compute_max_score_count": 0, + "avg_build_scorer": 4027, + "max_set_min_competitive_score_count": 0, + "advance_count": 0, + "max_build_scorer_count": 2, + "shallow_advance": 0, + "min_compute_max_score": 0, + "max_match_count": 0, + "create_weight_count": 1, + "build_scorer": 32459, + "max_set_min_competitive_score": 0, + "max_compute_max_score": 0, + "min_shallow_advance": 0, + "match": 0, + "max_shallow_advance": 0, + "avg_advance_count": 0, + "min_next_doc": 708, + "max_advance_count": 0, + "min_score": 291, + "max_next_doc": 999, + "create_weight": 1834, + "avg_next_doc_count": 2, + "max_score": 376, + "min_compute_max_score_count": 0, + "min_score_count": 1, + "min_advance_count": 0 + } + } + ], + "rewrite_time": 8126, + "collector": [ + { + "name": "QueryCollectorManager", + "reason": "search_multi", + "time_in_nanos": 564708, + "reduce_time_in_nanos": 1251042, + "max_slice_time_in_nanos": 121959, + "min_slice_time_in_nanos": 28958, + "avg_slice_time_in_nanos": 83208, + "slice_count": 3, + "children": [ + { + "name": "SimpleTopDocsCollectorManager", + "reason": "search_top_hits", + "time_in_nanos": 500459, + "reduce_time_in_nanos": 840125, + "max_slice_time_in_nanos": 22168, + "min_slice_time_in_nanos": 5792, + "avg_slice_time_in_nanos": 12084, + "slice_count": 3 + }, + { + "name": "NonGlobalAggCollectorManager: [histo]", + "reason": "aggregation", + "time_in_nanos": 552167, + "reduce_time_in_nanos": 311292, + "max_slice_time_in_nanos": 95333, + "min_slice_time_in_nanos": 18416, + "avg_slice_time_in_nanos": 66249, + "slice_count": 3 + } + ] + } + ] + } + ], + "aggregations": [ + { + "type": "NumericHistogramAggregator", + "description": "histo", + "time_in_nanos": 2847834, + "max_slice_time_in_nanos": 117374, + "min_slice_time_in_nanos": 20624, + "avg_slice_time_in_nanos": 75597, + "breakdown": { + "min_build_leaf_collector": 9500, + "build_aggregation_count": 3, + "post_collection": 3209, + "max_collect_count": 2, + "initialize_count": 3, + "reduce_count": 0, + "avg_collect": 17055, + "max_build_aggregation": 26000, + "avg_collect_count": 1, + "max_build_leaf_collector": 64833, + "min_build_leaf_collector_count": 1, + "build_aggregation": 41125, + "min_initialize": 583, + "max_reduce": 0, + "build_leaf_collector_count": 3, + "avg_reduce": 0, + "min_collect_count": 1, + "avg_build_leaf_collector_count": 1, + "avg_build_leaf_collector": 45000, + "max_collect": 24625, + "reduce": 0, + "avg_build_aggregation": 12013, + "min_post_collection": 292, + "max_initialize": 1333, + "max_post_collection": 750, + "collect_count": 5, + "avg_post_collection": 541, + "avg_initialize": 986, + "post_collection_count": 3, + "build_leaf_collector": 86833, + "min_collect": 6250, + "min_build_aggregation": 3541, + "initialize": 2786791, + "max_build_leaf_collector_count": 1, + "min_reduce": 0, + "collect": 29834 + }, + "debug": { + "total_buckets": 1 + } + } + ] + } + ] + } +} +``` +
+ +## Response body fields + +The response includes the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`profile` | Object | Contains profiling information. +`profile.shards` | Array of objects | A search request can be executed against one or more shards in the index, and a search may involve one or more indexes. Thus, the `profile.shards` array contains profiling information for each shard that was involved in the search. +`profile.shards.id` | String | The shard ID of the shard in the `[node-ID][index-name][shard-ID]` format. +`profile.shards.searches` | Array of objects | A search represents a query executed against the underlying Lucene index. Most search requests execute a single search against a Lucene index, but some search requests can execute more than one search. For example, including a global aggregation results in a secondary `match_all` query for the global context. The `profile.shards` array contains profiling information about each search execution. +[`profile.shards.searches.query`](#the-query-array) | Array of objects | Profiling information about the query execution. +`profile.shards.searches.rewrite_time` | Integer | All Lucene queries are rewritten. A query and its children may be rewritten more than once, until the query stops changing. The rewriting process involves performing optimizations, such as removing redundant clauses or replacing a query path with a more efficient one. After the rewriting process, the original query may change significantly. The `rewrite_time` field contains the cumulative total rewrite time for the query and all its children, in nanoseconds. +[`profile.shards.searches.collector`](#the-collector-array) | Array of objects | Profiling information about the Lucene collectors that ran the search. +[`profile.shards.aggregations`](#aggregation-responses) | Array of objects | Profiling information about the aggregation execution. + +### The `query` array + +The `query` array contains objects with the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`type` | String | The Lucene query type into which the search query was rewritten. Corresponds to the Lucene class name (which often has the same name in OpenSearch). +`description` | String | Contains a Lucene explanation of the query. Helps differentiate queries with the same type. +`time_in_nanos` | Long | The total elapsed time for this query, in nanoseconds. For concurrent segment search, `time_in_nanos` is the total time spent across all the slices (the difference between the last completed slice execution end time and the first slice execution start time). +`max_slice_time_in_nanos` | Long | The maximum amount of time taken by any slice to run a query, in nanoseconds. This field is included only if you enable concurrent segment search. +`min_slice_time_in_nanos` | Long | The minimum amount of time taken by any slice to run a query, in nanoseconds. This field is included only if you enable concurrent segment search. +`avg_slice_time_in_nanos` | Long | The average amount of time taken by any slice to run a query, in nanoseconds. This field is included only if you enable concurrent segment search. +[`breakdown`](#the-breakdown-object) | Object | Contains timing statistics about low-level Lucene execution. +`children` | Array of objects | If a query has subqueries (children), this field contains information about the subqueries. + +### The `breakdown` object + +The `breakdown` object represents the timing statistics about low-level Lucene execution, broken down by method. Timings are listed in wall-clock nanoseconds and are not normalized. The `breakdown` timings are inclusive of all child times. The `breakdown` object comprises the following fields. All fields contain integer values. + +Field | Description +:--- | :--- +`create_weight` | A `Query` object in Lucene is immutable. Yet, Lucene should be able to reuse `Query` objects in multiple `IndexSearcher` objects. Thus, `Query` objects need to keep temporary state and statistics associated with the index in which the query is executed. To achieve reuse, every `Query` object generates a `Weight` object, which keeps the temporary context (state) associated with the `` tuple. The `create_weight` field contains the amount of time spent creating the `Weight` object. +`build_scorer` | A `Scorer` iterates over matching documents and generates a score for each document. The `build_scorer` field contains the amount of time spent generating the `Scorer` object. This does not include the time spent scoring the documents. The `Scorer` initialization time depends on the optimization and complexity of a particular query. The `build_scorer` parameter also includes the amount of time associated with caching, if caching is applicable and enabled for the query. +`next_doc` | The `next_doc` Lucene method returns the document ID of the next document that matches the query. This method is a special type of the `advance` method and is equivalent to `advance(docId() + 1)`. The `next_doc` method is more convenient for many Lucene queries. The `next_doc` field contains the amount of time required to determine the next matching document, which varies depending on the query type. +`advance` | The `advance` method is a lower-level version of the `next_doc` method in Lucene. It also finds the next matching document but necessitates that the calling query perform additional tasks, such as identifying skips. Some queries, such as conjunctions (`must` clauses in Boolean queries), cannot use `next_doc`. For those queries, `advance` is timed. +`match` | For some queries, document matching is performed in two steps. First, the document is matched approximately. Second, those documents that are approximately matched are examined through a more comprehensive process. For example, a phrase query first checks whether a document contains all terms in the phrase. Next, it verifies that the terms are in order (which is a more expensive process). The `match` field is non-zero only for those queries that use the two-step verification process. +`score` | Contains the time taken for a `Scorer` to score a particular document. +`shallow_advance` | Contains the amount of time required to execute the `advanceShallow` Lucene method. +`compute_max_score` | Contains the amount of time required to execute the `getMaxScore` Lucene method. +`set_min_competitive_score` | Contains the amount of time required to execute the `setMinCompetitiveScore` Lucene method. +`_count` | Contains the number of invocations of a ``. For example, `advance_count` contains the number of invocations of the `advance` method. Different invocations of the same method occur because the method is called on different documents. You can determine the selectivity of a query by comparing counts in different query components. +`max_` | The maximum amount of time taken by any slice to run a query method. Breakdown stats for the `create_weight` method do not include profiled `max` time because the method runs at the query level rather than the slice level. This field is included only if you enable concurrent segment search. +`min_` | The minimum amount of time taken by any slice to run a query method. Breakdown stats for the `create_weight` method do not include profiled `min` time because the method runs at the query level rather than the slice level. This field is included only if you enable concurrent segment search. +`avg_` | The average amount of time taken by any slice to run a query method. Breakdown stats for the `create_weight` method do not include profiled `avg` time because the method runs at the query level rather than the slice level. This field is included only if you enable concurrent segment search. +`max__count` | The maximum number of invocations of a `` on any slice. Breakdown stats for the `create_weight` method do not include profiled `max` count because the method runs at the query level rather than the slice level. This field is included only if you enable concurrent segment search. +`min__count` | The minimum number of invocations of a `` on any slice. Breakdown stats for the `create_weight` method do not include profiled `min` count because the method runs at the query level rather than the slice level. This field is included only if you enable concurrent segment search. +`avg__count` | The average number of invocations of a `` on any slice. Breakdown stats for the `create_weight` method do not include profiled `avg` count because the method runs at the query level rather than the slice level. This field is included only if you enable concurrent segment search. + +### The `collector` array + +The `collector` array contains information about Lucene Collectors. A Collector is responsible for coordinating document traversal and scoring and collecting matching documents. Using Collectors, individual queries can record aggregation results and execute global queries or post-query filters. + +Field | Description +:--- | :--- +`name` | The collector name. In the [example response](#example-response-non-concurrent-search), the `collector` is a single `SimpleTopScoreDocCollector`---the default scoring and sorting collector. +`reason` | Contains a description of the collector. For possible field values, see [Collector reasons](#collector-reasons). +`time_in_nanos` | The total elapsed time for this collector, in nanoseconds. For concurrent segment search, `time_in_nanos` is the total amount of time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`children` | If a collector has subcollectors (children), this field contains information about the subcollectors. +`max_slice_time_in_nanos` |The maximum amount of time taken by any slice, in nanoseconds. This field is included only if you enable concurrent segment search. +`min_slice_time_in_nanos` |The minimum amount of time taken by any slice, in nanoseconds. This field is included only if you enable concurrent segment search. +`avg_slice_time_in_nanos` |The average amount of time taken by any slice, in nanoseconds. This field is included only if you enable concurrent segment search. +`slice_count` |The total slice count for this query. This field is included only if you enable concurrent segment search. +`reduce_time_in_nanos` |The amount of time taken to reduce results for all slice collectors, in nanoseconds. This field is included only if you enable concurrent segment search. + +Collector times are calculated, combined, and normalized independently, so they are independent of query times. +{: .note} + +#### Collector reasons + +The following table describes all available collector reasons. + +Reason | Description +:--- | :--- +`search_sorted` | A collector that scores and sorts documents. Present in most simple searches. +`search_count` | A collector that counts the number of matching documents but does not fetch the source. Present when `size: 0` is specified. +`search_terminate_after_count` | A collector that searches for matching documents and terminates the search when it finds a specified number of documents. Present when the `terminate_after_count` query parameter is specified. +`search_min_score` | A collector that returns matching documents that have a score greater than a minimum score. Present when the `min_score` parameter is specified. +`search_multi` | A wrapper collector for other collectors. Present when search, aggregations, global aggregations, and post filters are combined in a single search. +`search_timeout` | A collector that stops running after a specified period of time. Present when a `timeout` parameter is specified. +`aggregation` | A collector for aggregations that is run against the specified query scope. OpenSearch uses a single `aggregation` collector to collect documents for all aggregations. +`global_aggregation` | A collector that is run against the global query scope. Global scope is different from a specified query scope, so in order to collect the entire dataset, a `match_all` query must be run. + +### Aggregation responses + +The following examples show profiling responses for different aggregation types. + +#### Response: Global aggregation + +The response contains profiling information: + +
+ + Response + + {: .text-delta} + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1370, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "all_products": { + "doc_count": 4675, + "avg_price": { + "value": 75.05542864304813 + } + }, + "elitelligence_products": { + "value": 68.4430200729927 + } + }, + "profile": { + "shards": [ + { + "id": "[LidyZ1HVS-u93-73Z49dQg][opensearch_dashboards_sample_data_ecommerce][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "ConstantScoreQuery", + "description": "ConstantScore(manufacturer:elitelligence)", + "time_in_nanos": 1367487, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 634321, + "match": 0, + "next_doc_count": 1370, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 173250, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 132458, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 427458 + }, + "children": [ + { + "type": "TermQuery", + "description": "manufacturer:elitelligence", + "time_in_nanos": 1174794, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 470918, + "match": 0, + "next_doc_count": 1370, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 172084, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 114041, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 417751 + } + } + ] + } + ], + "rewrite_time": 42542, + "collector": [ + { + "name": "MultiCollector", + "reason": "search_multi", + "time_in_nanos": 778406, + "children": [ + { + "name": "EarlyTerminatingCollector", + "reason": "search_count", + "time_in_nanos": 70290 + }, + { + "name": "ProfilingAggregator: [elitelligence_products]", + "reason": "aggregation", + "time_in_nanos": 502780 + } + ] + } + ] + }, + { + "query": [ + { + "type": "ConstantScoreQuery", + "description": "ConstantScore(*:*)", + "time_in_nanos": 995345, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 930803, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 2209, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 23875, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 38458 + }, + "children": [ + { + "type": "MatchAllDocsQuery", + "description": "*:*", + "time_in_nanos": 431375, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 389875, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 1167, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 9458, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 30875 + } + } + ] + } + ], + "rewrite_time": 8792, + "collector": [ + { + "name": "ProfilingAggregator: [all_products]", + "reason": "aggregation_global", + "time_in_nanos": 1310536 + } + ] + } + ], + "aggregations": [ + { + "type": "AvgAggregator", + "description": "elitelligence_products", + "time_in_nanos": 319918, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 130709, + "build_aggregation": 2709, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 584, + "initialize": 4750, + "initialize_count": 1, + "reduce_count": 0, + "collect": 181166, + "collect_count": 1370 + } + }, + { + "type": "GlobalAggregator", + "description": "all_products", + "time_in_nanos": 1519340, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 134625, + "build_aggregation": 59291, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 5041, + "initialize": 24500, + "initialize_count": 1, + "reduce_count": 0, + "collect": 1295883, + "collect_count": 4675 + }, + "children": [ + { + "type": "AvgAggregator", + "description": "avg_price", + "time_in_nanos": 775967, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 98999, + "build_aggregation": 33083, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 2209, + "initialize": 1708, + "initialize_count": 1, + "reduce_count": 0, + "collect": 639968, + "collect_count": 4675 + } + } + ] + } + ] + } + ] + } +} +``` +
+ +#### Response: Non-global aggregation + +The response contains profiling information: + +
+ + Response + + {: .text-delta} + +```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": { + "avg_taxful_total_price": { + "value": 75.05542864304813 + } + }, + "profile": { + "shards": [ + { + "id": "[LidyZ1HVS-u93-73Z49dQg][opensearch_dashboards_sample_data_ecommerce][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "ConstantScoreQuery", + "description": "ConstantScore(*:*)", + "time_in_nanos": 1690820, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 1614112, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 2708, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 20250, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 53750 + }, + "children": [ + { + "type": "MatchAllDocsQuery", + "description": "*:*", + "time_in_nanos": 770902, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 721943, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 1042, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 5041, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 42876 + } + } + ] + } + ], + "rewrite_time": 22000, + "collector": [ + { + "name": "MultiCollector", + "reason": "search_multi", + "time_in_nanos": 3672676, + "children": [ + { + "name": "EarlyTerminatingCollector", + "reason": "search_count", + "time_in_nanos": 78626 + }, + { + "name": "ProfilingAggregator: [avg_taxful_total_price]", + "reason": "aggregation", + "time_in_nanos": 2834566 + } + ] + } + ] + } + ], + "aggregations": [ + { + "type": "AvgAggregator", + "description": "avg_taxful_total_price", + "time_in_nanos": 1973702, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 199292, + "build_aggregation": 13584, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 6125, + "initialize": 6916, + "initialize_count": 1, + "reduce_count": 0, + "collect": 1747785, + "collect_count": 4675 + } + } + ] + } + ] + } +} +``` +
+ +#### Response body fields + +The `aggregations` array contains aggregation objects with the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`type` | String | The aggregator type. In the [non-global aggregation example response](#response-non-global-aggregation), the aggregator type is `AvgAggregator`. [Global aggregation example response](#response-global-aggregation) contains a `GlobalAggregator` with an `AvgAggregator` child. +`description` | String | Contains a Lucene explanation of the aggregation. Helps differentiate aggregations with the same type. +`time_in_nanos` | Long | The total elapsed time for this aggregation, in nanoseconds. For concurrent segment search, `time_in_nanos` is the total amount of time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +[`breakdown`](#the-breakdown-object-1) | Object | Contains timing statistics about low-level Lucene execution. +`children` | Array of objects | If an aggregation has subaggregations (children), this field contains information about the subaggregations. +`debug` | Object | Some aggregations return a `debug` object that describes the details of the underlying execution. +`max_slice_time_in_nanos` |Long | The maximum amount of time taken by any slice to run an aggregation, in nanoseconds. This field is included only if you enable concurrent segment search. +`min_slice_time_in_nanos` |Long |The minimum amount of time taken by any slice to run an aggregation, in nanoseconds. This field is included only if you enable concurrent segment search. +`avg_slice_time_in_nanos` |Long |The average amount of time taken by any slice to run an aggregation, in nanoseconds. This field is included only if you enable concurrent segment search. + +#### The `breakdown` object + +The `breakdown` object represents the timing statistics about low-level Lucene execution, broken down by method. Each field in the `breakdown` object represents an internal Lucene method executed within the aggregation. Timings are listed in wall-clock nanoseconds and are not normalized. The `breakdown` timings are inclusive of all child times. The `breakdown` object is comprised of the following fields. All fields contain integer values. + +Field | Description +:--- | :--- +`initialize` | Contains the amount of time taken to execute the `preCollection()` callback method during `AggregationCollectorManager` creation. For concurrent segment search, the `initialize` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`build_leaf_collector`| Contains the time spent running the aggregation's `getLeafCollector()` method, which creates a new collector to collect the given context. For concurrent segment search, the `build_leaf_collector` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`collect`| Contains the time spent collecting the documents into buckets. For concurrent segment search, the `collect` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`post_collection`| Contains the time spent running the aggregation’s `postCollection()` callback method. For concurrent segment search, the `post_collection` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`build_aggregation`| Contains the time spent running the aggregation’s `buildAggregations()` method, which builds the results of this aggregation. For concurrent segment search, the `build_aggregation` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`reduce`| Contains the time spent in the `reduce` phase. For concurrent segment search, the `reduce` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time). +`_count` | Contains the number of invocations of a ``. For example, `build_leaf_collector_count` contains the number of invocations of the `build_leaf_collector` method. +`max_` |The maximum amount of time taken by any slice to run an aggregation method. This field is included only if you enable concurrent segment search. +`min_`|The minimum amount of time taken by any slice to run an aggregation method. This field is included only if you enable concurrent segment search. +`avg_` |The average amount of time taken by any slice to run an aggregation method. This field is included only if you enable concurrent segment search. +`_count` |The total method count across all slices. For example, for the `collect` method, it is the total number of invocations of this method needed to collect documents into buckets across all slices. +`max__count` |The maximum number of invocations of a `` on any slice. This field is included only if you enable concurrent segment search. +`min__count` |The minimum number of invocations of a `` on any slice. This field is included only if you enable concurrent segment search. +`avg__count` |The average number of invocations of a `` on any slice. This field is included only if you enable concurrent segment search. diff --git a/_api-reference/search-apis/rank-eval.md b/_api-reference/search-apis/rank-eval.md new file mode 100644 index 00000000..2ddee3e7 --- /dev/null +++ b/_api-reference/search-apis/rank-eval.md @@ -0,0 +1,234 @@ +--- +layout: default +title: Ranking evaluation +parent: Search APIs +nav_order: 60 +redirect_from: + - /api-reference/rank-eval/ +--- + +# Ranking Evaluation API +**Introduced 1.0** +{: .label .label-purple } + +The Rank Evaluation API evaluates the quality of ranked search results. + +## Endpoints + +```json +GET {index_name}/_rank_eval +POST {index_name}/_rank_eval +``` + +## Query parameters + +Query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`ignore_unavailable` | Boolean | Defaults to `false`. When set to `false` the response body will return an error if an index is closed or missing. +`allow_no_indices` | Boolean | Defaults to `true`. When set to `false` the response body will return an error if a wildcard expression points to indexes that are closed or missing. +`expand_wildcards` | String | Expand wildcard expressions for indexes that are `open`, `closed`, `hidden`, `none`, or `all`. +`search_type` | String | Set search type to either `query_then_fetch` or `dfs_query_then_fetch`. + +## Request body fields + +The request body must contain at least one parameter. + +Field type | Description +:--- | :--- +`id` | Document or template ID. +`requests` | Set multiple search requests within the request field section. +`ratings` | Document relevance score. +k | The number of documents returned per query. Default is set to 10. +`relevant_rating_threshold` | The threshold at which documents are considered relevant. Default is set to 1. +`normalize` | Discounted cumulative gain will be calculated when set to `true`. +`maximum_relevance` | Sets the maximum relevance score when using the expected reciprocal rank metric. +`ignore_unlabeled` | Defaults to `false`. Unlabeled documents are ignored when set to `true`. +`template_id` | Template ID. +`params` | Parameters used in the template. + +## Example request + + +{% capture step1_rest %} +GET /shakespeare/_rank_eval +{ + "requests": [ + { + "id": "books_query", + "request": { + "query": { + "match": { + "text": "thou" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "80", + "rating": 0 + }, + { + "_index": "shakespeare", + "_id": "115", + "rating": 1 + }, + { + "_index": "shakespeare", + "_id": "117", + "rating": 2 + } + ] + }, + { + "id": "words_query", + "request": { + "query": { + "match": { + "text": "art" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "115", + "rating": 2 + } + ] + } + ] +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.rank_eval( + index = "shakespeare", + body = { + "requests": [ + { + "id": "books_query", + "request": { + "query": { + "match": { + "text": "thou" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "80", + "rating": 0 + }, + { + "_index": "shakespeare", + "_id": "115", + "rating": 1 + }, + { + "_index": "shakespeare", + "_id": "117", + "rating": 2 + } + ] + }, + { + "id": "words_query", + "request": { + "query": { + "match": { + "text": "art" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "115", + "rating": 2 + } + ] + } + ] + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +````json +{ + "rank_eval": { + "metric_score": 0.7, + "details": { + "query_1": { + "metric_score": 0.9, + "unrated_docs": [ + { + "_index": "shakespeare", + "_id": "1234567" + }, ... + ], + "hits": [ + { + "hit": { + "_index": "shakespeare", + "_type": "page", + "_id": "1234567", + "_score": 5.123456789 + }, + "rating": 1 + }, ... + ], + "metric_details": { + "precision": { + "relevant_docs_retrieved": 3, + "docs_retrieved": 6 + } + } + }, + "query_2": { [... ] } + }, + "failures": { [... ] } + } +} +```` \ No newline at end of file diff --git a/_api-reference/search-apis/scroll.md b/_api-reference/search-apis/scroll.md new file mode 100644 index 00000000..863b15f8 --- /dev/null +++ b/_api-reference/search-apis/scroll.md @@ -0,0 +1,334 @@ +--- +layout: default +title: Scroll +parent: Search APIs +nav_order: 30 +redirect_from: + - /opensearch/rest-api/scroll/ + - /api-reference/scroll/ +--- + +# Scroll API +**Introduced 1.0** +{: .label .label-purple } + +You can use the `scroll` operation to retrieve a large number of results. For example, for machine learning jobs, you can request an unlimited number of results in batches. + +To use the `scroll` operation, add a `scroll` parameter to the request header with a search context to tell OpenSearch how long you need to keep scrolling. This search context needs to be long enough to process a single batch of results. + +Because search contexts consume a lot of memory, we suggest you don't use the `scroll` operation for frequent user queries. Instead, use the `sort` parameter with the `search_after` parameter to scroll responses for user queries. +{: .note } + +Note the following performance considerations: + +- For the most efficient scrolling when you don't need relevance scoring, sort by `_doc`. This disables scoring and returns documents in their natural index order, which is the fastest way to iterate over all documents in an index. +- Only the initial search response includes aggregation results. Subsequent scroll requests return only the next batch of hits. +- Each open scroll context prevents segment merging on the associated shards and consumes file handles and heap memory. Close scroll contexts as soon as you no longer need them. +- The maximum number of open scroll contexts is controlled by the `search.max_open_scroll_context` cluster setting, which defaults to 500. + + +## Endpoints +```json +GET /_search/scroll +POST /_search/scroll +GET /_search/scroll/{scroll_id} +POST /_search/scroll/{scroll_id} +``` + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `scroll_id` | String | The scroll ID for the search. We recommend specifying the scroll ID in the request body instead because scroll IDs can be very long. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `scroll` | String | The amount of time to extend the search context. This value overrides the duration set in the original search request's `scroll` parameter. Cannot exceed the `search.max_keep_alive` cluster setting. | None | +| `scroll_id` | String | The scroll ID for the search. We recommend specifying the scroll ID in the request body instead of as a query parameter because scroll IDs can be very long. | None | +| `rest_total_hits_as_int` | Boolean | Whether the `hits.total` property is returned as an integer (`true`) or an object (`false`). | `false` | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `scroll` | String | The amount of time to extend the search context for the next scroll request. If both the query parameter and request body field are specified, the query parameter takes precedence. | +| `scroll_id` | String | Required. The scroll ID returned by the initial search request or the previous scroll request. | + +## Example request + +The following example demonstrates the scroll workflow from initiating a scroll operation to retrieving all results. + +### Step 1: Start the scroll operation + +To begin scrolling, send an initial search query with a `scroll` parameter that specifies how long to keep the search context alive (for example, `10m` for 10 minutes). Use the `size` parameter to set how many results to return in each batch: + + +{% capture step1_rest %} +GET /shakespeare/_search?scroll=10m +{ + "size": 10000 +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "shakespeare", + params = { "scroll": "10m" }, + body = { + "size": 10000 + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +OpenSearch caches the results and returns a scroll ID to access them in batches: + +```json +"_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +``` + +### Step 2: Retrieve subsequent batches + +Pass this scroll ID to the `scroll` operation to get back the next batch of results: + + +{% capture step1_rest %} +GET /_search/scroll +{ + "scroll": "10m", + "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.scroll( + body = { + "scroll": "10m", + "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Using this scroll ID, you get results in batches of 10,000 as long as the search context is still open. Typically, the scroll ID does not change between requests, but it *can* change, so make sure to always use the latest scroll ID. If you don't send the next scroll request within the set search context, the `scroll` operation does not return any results. + +### Detecting the end of results + +When you've scrolled through all results, the final batch contains an empty `hits` array: + +```json +{ + "_scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==", + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } +} +``` + +When `hits.hits` is an empty array, you've retrieved all available results and should stop scrolling. Make sure to close the scroll context to free up resources. + +### Using sliced scroll + +If you expect billions of results, use a sliced scroll. Slicing allows you to perform multiple scroll operations for the same request, but in parallel. +Set the ID and the maximum number of slices for the scroll: + + +{% capture step1_rest %} +GET /shakespeare/_search?scroll=10m +{ + "slice": { + "id": 0, + "max": 10 + }, + "query": { + "match_all": {} + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "shakespeare", + params = { "scroll": "10m" }, + body = { + "slice": { + "id": 0, + "max": 10 + }, + "query": { + "match_all": {} + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Each slice produces its own independent scroll ID. With `"max": 10`, you initiate 10 separate scroll operations (IDs 0 through 9), each returning a distinct subset of the data. You then scroll each slice independently until all slices are exhausted. The number of slices is limited by the `index.max_slices_per_scroll` setting, which defaults to `1024`. + +### Step 3: Close the scroll context + +Close the search context when you're done scrolling because the `scroll` operation continues to consume computing resources until the timeout: + + +{% capture step1_rest %} +DELETE /_search/scroll/DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ== +{% endcapture %} + +{% capture step1_python %} + + +response = client.clear_scroll( + scroll_id = "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To close all open scroll contexts: + + +{% capture step1_rest %} +DELETE /_search/scroll/_all +{% endcapture %} + +{% capture step1_python %} + + +response = client.clear_scroll( + scroll_id = "_all" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Results from a scrolling search reflect the state of the index at the time of the initial search request. Documents indexed or modified after the scroll was initiated do not appear in scroll results, even if they match the query. +{: .important} + +## Example response + +The scroll operation returns the same response structure as the search API, including `_scroll_id`, `hits`, `_shards`, and timing information. + +The clear scroll operation returns the following response: + +```json +{ + "succeeded": true, + "num_freed": 1 +} +``` + +## Response body fields + +The following table lists the response body fields for the scroll operation. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_scroll_id` | String | The scroll ID to use for the next scroll request. This value may change between requests, so always use the most recently returned ID. | +| `took` | Integer | The time, in milliseconds, that the request took to complete. | +| `timed_out` | Boolean | Whether the request timed out before completing. | +| `_shards` | Object | Information about the shards involved, including `total`, `successful`, `skipped`, and `failed` counts. | +| `hits` | Object | The search results, including the `total` hit count and the array of matching documents. When scrolling is complete, `hits.hits` is an empty array. | + +The following table lists the response body fields for the clear scroll operation. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `succeeded` | Boolean | Whether the scroll context was successfully released. | +| `num_freed` | Integer | The number of scroll contexts that were freed. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/scroll` and `indices:data/read/scroll/clear`. + +## Related documentation + +- [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/) +- [Point in Time API]({{site.url}}{{site.baseurl}}/search-plugins/point-in-time-api/) diff --git a/_api-reference/search-apis/search-shards.md b/_api-reference/search-apis/search-shards.md new file mode 100644 index 00000000..3e3f5d8f --- /dev/null +++ b/_api-reference/search-apis/search-shards.md @@ -0,0 +1,266 @@ +--- +layout: default +title: Search shards +parent: Search APIs +nav_order: 85 +--- + +# Search shards API +**Introduced 1.0** +{: .label .label-purple } + +The `_search_shards` API provides information about which shards OpenSearch would route a search request to if the request were executed. This helps you understand how OpenSearch plans to distribute the query across shards without actually running the search. This API does not execute the search but allows you to inspect routing decisions, shard distribution, and the nodes that would handle the request. + +## Endpoints + +```json +GET /_search_shards +GET /{index}/_search_shards +POST /_search_shards +POST /{index}/_search_shards +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Date type | Description | +| --------- | ------ | ------------------------------------------------------ | +| `` | String | A comma-separated list of target index names. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| `allow_no_indices` | Boolean | If `true`, the request does not fail if a wildcard expression or index alias resolves to no concrete indexes. Default is `true`. | +| `expand_wildcards` | String | Controls how wildcard expressions are expanded. Options are: `open` (default), `closed`, `hidden`, `none`, or `all`. | +| `ignore_unavailable` | Boolean | If `true`, missing or closed indexes are ignored. Default is `false`. | +| `local` | Boolean | If `true`, the operation is performed only on the local node, without retrieving the state from the cluster manager node. Default is `false`. | +| `preference` | String | Specifies a preference in selecting which shards or nodes to target. See [The `preference` query parameter]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#the-preference-query-parameter) for more information. | +| `routing` | String | A comma-separated list of specific routing values used for shard selection. | + + +## Request body fields + +The request body can include a full search query to simulate how the request would be routed: + +```json +{ + "query": { + "term": { + "user": "alice" + } + } +} +``` + +## Example + +Create an index: + +```json +PUT /logs-demo +{ + "settings": { + "number_of_shards": 3, + "number_of_replicas": 0 + }, + "mappings": { + "properties": { + "user": { "type": "keyword" }, + "message": { "type": "text" }, + "@timestamp": { "type": "date" } + } + } +} +``` +{% include copy-curl.html %} + +Index the first document with `routing=user1`: + + +{% capture step1_rest %} +POST /logs-demo/_doc?routing=user1 +{ + "@timestamp": "2025-05-23T10:00:00Z", + "user": "user1", + "message": "User login successful" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "logs-demo", + params = { "routing": "user1" }, + body = { + "@timestamp": "2025-05-23T10:00:00Z", + "user": "user1", + "message": "User login successful" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Index the second document with `routing=user2`: + + +{% capture step1_rest %} +POST /logs-demo/_doc?routing=user2 +{ + "@timestamp": "2025-05-23T10:01:00Z", + "user": "user2", + "message": "User login failed" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.index( + index = "logs-demo", + params = { "routing": "user2" }, + body = { + "@timestamp": "2025-05-23T10:01:00Z", + "user": "user2", + "message": "User login failed" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request + +Simulate routing with `_search_shards`: + + +{% capture step1_rest %} +POST /logs-demo/_search_shards?routing=user1 +{ + "query": { + "term": { + "user": "user1" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_shards( + index = "logs-demo", + params = { "routing": "user1" }, + body = { + "query": { + "term": { + "user": "user1" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +### Example response + +The response displays the node and shard that would be searched if the search were executed: + +```json +{ + "nodes": { + "12ljrWLsQyiWHLzhFZgL9Q": { + "name": "opensearch-node3", + "ephemeral_id": "-JPvYKPMSGubd0VmSEzlbw", + "transport_address": "172.18.0.4:9300", + "attributes": { + "shard_indexing_pressure_enabled": "true" + } + } + }, + "indices": { + "logs-demo": {} + }, + "shards": [ + [ + { + "state": "STARTED", + "primary": true, + "node": "12ljrWLsQyiWHLzhFZgL9Q", + "relocating_node": null, + "shard": 1, + "index": "logs-demo", + "allocation_id": { + "id": "HwEjTdYQQJuULdQn10FRBw" + } + } + ] + ] +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Date type | Description | +| `nodes` | Object | Contains a map of node IDs to node metadata, such as name and transport address. | +| `indices` | Object | Contains a map of index names included in the request. | +| `shards` | Array of arrays | Nested arrays representing shard copies (primary/replica) for the request. | +| `shards.index` | String | The index name. | +| `shards.shard` | Integer | The shard number. | +| `shards.node` | String | The node ID of the node containing this shard. | +| `shards.primary` | Boolean | Whether this is a primary shard. | +| `shards.state` | String | The current shard state. | +| `shards.allocation_id.id` | String | A unique ID for this shard allocation. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/shards/search_shards`. diff --git a/_api-reference/search-apis/search-template/index.md b/_api-reference/search-apis/search-template/index.md new file mode 100644 index 00000000..0e5ba55b --- /dev/null +++ b/_api-reference/search-apis/search-template/index.md @@ -0,0 +1,1039 @@ +--- +layout: default +title: Search templates +parent: Search APIs +has_children: true +nav_order: 90 +redirect_from: + - /opensearch/search-template/ + - /search-plugins/search-template/ + - /api-reference/search-template/ + - /api-reference/search-apis/search-template/ +--- + +# Search Templates API + +You can convert your full-text queries into a search template to accept user input and dynamically insert it into your query. + +For example, if you use OpenSearch as a backend search engine for your application or website, you can take in user queries from a search bar or a form field and pass them as parameters into a search template. That way, the syntax to create OpenSearch queries is abstracted from your end users. + +When you're writing code to convert user input into OpenSearch queries, you can simplify your code with search templates. If you need to add fields to your search query, you can modify the template without making changes to your code. + +Search templates use the Mustache language. For a list of all syntax options, see the [Mustache manual](https://mustache.github.io/mustache.5.html). +{: .note } + +## Query parameters + +The `_search/template` endpoint accepts the same query parameters as the Search API, including `typed_keys` and `rest_total_hits_as_int`. For more information, see [Search API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/). + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`id` | String | The ID of a stored search template to run. Required if `source` is not specified. +`source` | Object or String | An inline search template. Specify the template as a string if it contains Mustache tags that make the JSON invalid. Required if `id` is not specified. +`params` | Object | The values that replace the variables in the template. +`explain` | Boolean | Whether to return details about how the score of each hit was calculated. Default is `false`. +`profile` | Boolean | Whether to return timing information about the execution of the query. Default is `false`. +`search_pipeline` | String | The name of the search pipeline to apply to the search request. + +## Create search templates + +A search template has two components: the query and the parameters. Parameters are user-inputted values that get placed into variables. Variables are represented with double braces in Mustache notation. When encountering a variable like `{% raw %}{{var}}{% endraw %}` in the query, OpenSearch goes to the `params` section, looks for a parameter called `var`, and replaces it with the specified value. + +You can code your application to ask your user what they want to search for and then plug that value into the `params` object at runtime. + +The examples on this page use the `shakespeare` index. To try them, first create the index: + +```json +PUT /shakespeare +{ + "mappings": { + "properties": { + "line_id": { "type": "integer" }, + "play_name": { "type": "keyword" }, + "speech_number": { "type": "integer" }, + "speaker": { "type": "keyword" }, + "text_entry": { "type": "text" } + } + } +} +``` +{% include copy-curl.html %} + +Then add some lines from the plays to the index: + +```json +POST /_bulk +{ "index": { "_index": "shakespeare", "_id": "1" } } +{ "line_id": 1, "play_name": "Henry IV", "speech_number": 1, "speaker": "KING HENRY IV", "text_entry": "So shaken as we are, so wan with care," } +{ "index": { "_index": "shakespeare", "_id": "2" } } +{ "line_id": 2, "play_name": "Henry IV", "speech_number": 1, "speaker": "KING HENRY IV", "text_entry": "Find we a time for frighted peace to pant," } +{ "index": { "_index": "shakespeare", "_id": "3" } } +{ "line_id": 3, "play_name": "Henry IV", "speech_number": 1, "speaker": "KING HENRY IV", "text_entry": "And breathe short-winded accents of new broils" } +{ "index": { "_index": "shakespeare", "_id": "4" } } +{ "line_id": 4, "play_name": "Othello", "speech_number": 1, "speaker": "IAGO", "text_entry": "I am not what I am." } +{ "index": { "_index": "shakespeare", "_id": "5" } } +{ "line_id": 5, "play_name": "Hamlet", "speech_number": 1, "speaker": "HAMLET", "text_entry": "To be, or not to be: that is the question:" } +{ "index": { "_index": "shakespeare", "_id": "6" } } +{ "line_id": 6, "play_name": "Romeo and Juliet", "speech_number": 1, "speaker": "ROMEO", "text_entry": "Did my heart love till now? forswear it, sight!" } +{ "index": { "_index": "shakespeare", "_id": "7" } } +{ "line_id": 7, "play_name": "As You Like It", "speech_number": 1, "speaker": "JAQUES", "text_entry": "Then a soldier, full of strange oaths," } +``` +{% include copy-curl.html %} + +This command defines a search template to find a play by its name. The `{% raw %}{{play_name}}{% endraw %}` in the query is replaced by the value `Henry IV`: + + +{% capture step1_rest %} +GET /shakespeare/_search/template +{ + "source": { + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + index = "shakespeare", + body = { + "source": { + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +This template runs the search on the `shakespeare` index. To run the search on all indexes in your cluster, omit the index name from the request: + + +{% capture step1_rest %} +GET /_search/template +{ + "source": { + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + body = { + "source": { + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +Specify the `from` and `size` parameters: + + +{% capture step1_rest %} +GET /_search/template +{ + "source": { + "from": "{% raw %}{{from}}{% endraw %}", + "size": "{% raw %}{{size}}{% endraw %}", + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV", + "from": 10, + "size": 10 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + body = { + "source": { + "from": "{% raw %}{{from}}{% endraw %}", + "size": "{% raw %}{{size}}{% endraw %}", + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV", + "from": 10, + "size": 10 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To improve the search experience, you can define defaults so the user doesn’t have to specify every possible parameter. If the parameter is not defined in the `params` section, OpenSearch uses the default value. + +The syntax for defining the default value for a variable `var` is as follows: + +``` +{% raw %}{{var}}{{^var}}default value{{/var}}{% endraw %} +``` +{% include copy.html %} + +This command sets the defaults for `from` as 10 and `size` as 10: + + +{% capture step1_rest %} +GET /_search/template +{ + "source": { + "from": "{% raw %}{{from}}{{^from}}10{{/from}}{% endraw %}", + "size": "{% raw %}{{size}}{{^size}}10{{/size}}{% endraw %}", + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + body = { + "source": { + "from": "{% raw %}{{from}}{{^from}}10{{/from}}{% endraw %}", + "size": "{% raw %}{{size}}{{^size}}10{{/size}}{% endraw %}", + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Save and execute search templates + +After the search template works the way you want it to, you can save the source of that template as a script, making it reusable for different input parameters. + +When saving the search template as a script, you need to specify the `lang` parameter as `mustache`: + +```json +POST _scripts/play_search_template +{ + "script": { + "lang": "mustache", + "source": { + "from": "{% raw %}{{from}}{{^from}}0{{/from}}{% endraw %}", + "size": "{% raw %}{{size}}{{^size}}10{{/size}}{% endraw %}", + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + } + } +} +``` + +Stored scripts don't keep default parameter values. If you include a `params` object when saving the script, OpenSearch discards it. To set default values in a stored template, use the `{% raw %}{{var}}{{^var}}default value{{/var}}{% endraw %}` syntax in the template source, as shown for `from` and `size` in the preceding request. + +Now you can reuse the template by referring to its `id` parameter. You can reuse this source template for different input values: + + +{% capture step1_rest %} +GET /shakespeare/_search/template +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV", + "from": 0, + "size": 1 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + index = "shakespeare", + body = { + "id": "play_search_template", + "params": { + "play_name": "Henry IV", + "from": 0, + "size": 1 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The response contains the first matching document: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "shakespeare", + "_id": "1", + "_score": 1.0, + "_source": { + "line_id": 1, + "play_name": "Henry IV", + "speech_number": 1, + "speaker": "KING HENRY IV", + "text_entry": "So shaken as we are, so wan with care," + } + } + ] + }, + "status": 200 +} +``` + +If you have a stored template and want to validate it, use the `render` operation: + + +{% capture step1_rest %} +POST /_render/template +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.render_search_template( + body = { + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +For more information, see [Render Template API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/render-template/). + +## Advanced parameter conversion with search templates + +You have a lot of different syntax options in Mustache to transpose the input parameters into a query. +You can specify conditions, run loops, join arrays, convert arrays to JSON, and so on. + +### Conditions + +Use the section tag in Mustache to represent conditions: + +```json +{% raw %}{{#var}}var{{/var}}{% endraw %} +``` +{% include copy.html %} + +When `var` is a Boolean value, this syntax acts as an `if` condition. The `{% raw %}{{#var}}{% endraw %}` and `{% raw %}{{/var}}{% endraw %}` tags insert the values placed between them only if `var` evaluates to `true`. + +Using section tags would make your JSON invalid, so you must write your query in a string format instead. + +This command includes the `size` parameter in the query only when the `limit` parameter is set to `true`. +In the following example, the `limit` parameter is `true`, so the rendered query includes `size` set to `2`: + + +{% capture step1_rest %} +POST /_render/template +{ + "source": "{% raw %}{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}{% endraw %}", + "params": { + "play_name": "Henry IV", + "limit": true, + "size": 2 + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.render_search_template( + body = { + "source": "{% raw %}{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}{% endraw %}", + "params": { + "play_name": "Henry IV", + "limit": true, + "size": 2 + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can also design an `if-else` condition. This command sets `size` to `2` if `limit` is `true`. Otherwise, it sets `size` to `10`: + + +{% capture step1_rest %} +GET /_search/template +{ + "source": "{% raw %}{ {{#limit}} \"size\": \"2\", {{/limit}} {{^limit}} \"size\": \"10\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}{% endraw %}", + "params": { + "play_name": "Henry IV", + "limit": true + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + body = { + "source": "{% raw %}{ {{#limit}} \"size\": \"2\", {{/limit}} {{^limit}} \"size\": \"10\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}{% endraw %}", + "params": { + "play_name": "Henry IV", + "limit": true + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Loops + +You can also use the section tag to implement a for-each loop: + +``` +{% raw %}{{#var}}{{.}}{{/var}}{% endraw %} +``` +{% include copy.html %} + +When `var` is an array, the content between the tags is repeated for each array element, and `{% raw %}{{.}}{% endraw %}` refers to the current element. A loop that writes each element followed by a comma leaves a trailing comma after the last element, which makes the query invalid JSON. To pass an array of values to a `terms` query, use the `toJson` tag, which converts the array to a JSON array: + + +{% capture step1_rest %} +GET /shakespeare/_search/template +{ + "source": "{% raw %}{\"query\":{\"terms\":{\"play_name\":{{#toJson}}play_name{{/toJson}}}}}{% endraw %}", + "params": { + "play_name": [ + "Henry IV", + "Othello" + ] + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + index = "shakespeare", + body = { + "source": "{% raw %}{\"query\":{\"terms\":{\"play_name\":{{#toJson}}play_name{{/toJson}}}}}{% endraw %}", + "params": { + "play_name": [ + "Henry IV", + "Othello" + ] + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +When you send this template to the [Render Template API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/render-template/), the response contains the following query: + +```json +{ + "template_output": { + "query": { + "terms": { + "play_name": [ + "Henry IV", + "Othello" + ] + } + } + } +} +``` + +### Join + +Use the `join` tag to concatenate the values of an array. By default, the values are separated by a comma with no space: + + +{% capture step1_rest %} +GET /shakespeare/_search/template +{ + "source": { + "query": { + "match": { + "text_entry": "{% raw %}{{#join}}text_entry{{/join}}{% endraw %}" + } + } + }, + "params": { + "text_entry": [ + "To be", + "or not to be" + ] + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + index = "shakespeare", + body = { + "source": { + "query": { + "match": { + "text_entry": "{% raw %}{{#join}}text_entry{{/join}}{% endraw %}" + } + } + }, + "params": { + "text_entry": [ + "To be", + "or not to be" + ] + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The template renders the following query: + +```json +{ + "template_output": { + "query": { + "match": { + "text_entry": "To be,or not to be" + } + } + } +} +``` + +To use a different delimiter, specify it in both the opening and closing tags. The following tag separates the values with a space and renders `To be or not to be`: + +``` +{% raw %}{{#join delimiter=' '}}text_entry{{/join delimiter=' '}}{% endraw %} +``` +{% include copy.html %} + +### Convert to JSON + +Use the `toJson` tag to convert parameters to their JSON representation. The following request passes an array of `match` queries as the `should` clauses of a `bool` query: + + +{% capture step1_rest %} +GET /shakespeare/_search/template +{ + "source": "{\"query\":{\"bool\":{\"should\":{% raw %}{{#toJson}}clauses{{/toJson}}{% endraw %}}}}", + "params": { + "clauses": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text_entry": "soldier" + } + } + ] + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search_template( + index = "shakespeare", + body = { + "source": "{\"query\":{\"bool\":{\"should\":{% raw %}{{#toJson}}clauses{{/toJson}}{% endraw %}}}}", + "params": { + "clauses": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text_entry": "soldier" + } + } + ] + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The template renders the following query: + +```json +{ + "template_output": { + "query": { + "bool": { + "should": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text_entry": "soldier" + } + } + ] + } + } + } +} +``` + +### URL encoding + +Use the `url` tag to URL-encode the content between the tags. This is useful when a template builds a URL from user input: + +```json +POST /_render/template +{ + "source": { + "query": { + "term": { + "source_url": "https://example.com/plays?name={% raw %}{{#url}}{{play_name}}{{/url}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Romeo and Juliet" + } +} +``` +{% include copy-curl.html %} + +The template renders the following query: + +```json +{ + "template_output": { + "query": { + "term": { + "source_url": "https://example.com/plays?name=Romeo+and+Juliet" + } + } + } +} +``` + +## Multiple search templates + +You can bundle multiple search templates and send them to your OpenSearch cluster in a single request using the `msearch` operation. +This saves network round trip time, so you get back the response more quickly as compared to independent requests. + +The following example runs two stored templates. First, store the conditional template from the [Conditions](#conditions) section as `if_search_template`: + +```json +POST _scripts/if_search_template +{ + "script": { + "lang": "mustache", + "source": "{% raw %}{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}{% endraw %}" + } +} +``` +{% include copy-curl.html %} + +Then run both `if_search_template` and `play_search_template` in a single request: + +```json +GET _msearch/template +{"index":"shakespeare"} +{"id":"if_search_template","params":{"play_name":"Henry IV","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} +``` + +For more information, see [Multi-search Template API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/msearch-template/). + +## Manage search templates + +To list all scripts, run the following command: + + +{% capture step1_rest %} +GET /_cluster/state/metadata?pretty&filter_path=**.stored_scripts +{% endcapture %} + +{% capture step1_python %} + + +response = client.cluster.state( + metric = "metadata", + params = { "pretty": "true", "filter_path": "**.stored_scripts" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To retrieve a specific search template, run the following command: + + +{% capture step1_rest %} +GET /_scripts/ +{% endcapture %} + +{% capture step1_python %} + + +response = client.get_script( + id = "" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +To delete a search template, run the following command: + + +{% capture step1_rest %} +DELETE /_scripts/ +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_script( + id = "" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Search template API operations + +The following search template API operations are available: + +- [Multi-search template]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/msearch-template/) +- [Render template]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/render-template/) + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/search/template`. diff --git a/_api-reference/search-apis/search-template/msearch-template.md b/_api-reference/search-apis/search-template/msearch-template.md new file mode 100644 index 00000000..9cf6ca6a --- /dev/null +++ b/_api-reference/search-apis/search-template/msearch-template.md @@ -0,0 +1,165 @@ +--- +layout: default +title: Multi-search template +parent: Search templates +grand_parent: Search APIs +nav_order: 20 +redirect_from: + - /api-reference/msearch-template/ + - /api-reference/search-apis/msearch-template/ +--- + +# Multi-search Template API + +**Introduced 1.0** +{: .label .label-purple } + +The Multi-search Template API runs multiple search template requests in a single API request. + +## Endpoints + +The Multi-search Template API uses the following paths: + +```json +GET /_msearch/template +POST /_msearch/template +GET /{index}/_msearch/template +POST /{index}/_msearch/template +``` + + +## Query parameters and metadata options + +All parameters are optional. Some can also be applied per search as part of each metadata line. + +Parameter | Type | Description | Supported in metadata +:--- | :--- | :--- | :--- +`allow_no_indices` | Boolean | Specifies whether to ignore wildcards that don't match any indexes. Default is `true`. | Yes +`cancel_after_time_interval` | Time | The interval of time after which the search request will be canceled. Supported at both parent and child request levels. The order of precedence is child-level parameter, parent-level parameter, and [cluster setting]({{site.url}}{{site.baseurl}}/api-reference/cluster-settings/). Default is `-1`. | Yes +`css_minimize_roundtrips` | Boolean | Specifies whether OpenSearch should try to minimize the number of network round trips between the coordinating node and remote clusters (only applicable to cross-cluster search requests). Default is `true`. | No +`expand_wildcards` | Enum | Expands wildcard expressions to concrete indexes. Combine multiple values with commas. Supported values are `all`, `open`, `closed`, `hidden`, and `none`. Default is `open`. | Yes +`ignore_unavailable` | Boolean | If an index or shard from the index list doesn’t exist, then this setting specifies whether to ignore the missing index or shard rather than fail the query. Default is `false`. | Yes +`max_concurrent_searches` | Integer | The maximum number of concurrent searches. The default depends on your node count and search thread pool size. Higher values can improve performance, but there may be a risk of overloading the cluster. | No +`max_concurrent_shard_requests` | Integer | The maximum number of concurrent shard requests that each search executes per node. Default is `5`. Higher values can improve performance, but there may be a risk of overloading the cluster. | No +`pre_filter_shard_size` | Integer | Default is `128`. | No +`rest_total_hits_as_int` | String | Specifies whether the `hits.total` property is returned as an integer (`true`) or an object (`false`). Default is `false`. | No +`search_type` | String | Affects the relevance score. Valid options are `query_then_fetch` and `dfs_query_then_fetch`. `query_then_fetch` scores documents using term and document frequencies for a single shard (faster, less accurate), whereas `dfs_query_then_fetch` uses term and document frequencies across all shards (slower, more accurate). Default is `query_then_fetch`. | Yes +`typed_keys` | Boolean | Specifies whether to prefix aggregation names with their internal types in the response. Default is `false`. | No + +### Metadata-only options + +Some options can't be applied as parameters to the entire request. Instead, you can apply them per search as part of each metadata line. All are optional. + +Option | Type | Description +:--- | :--- | :--- +`index` | String, string array | If you don't specify an index or multiple indexes as part of the URL (or want to override the URL value for an individual search), you can include it under this option. Examples include `"logs-*"` and `["my-store", "sample_data_ecommerce"]`. +`preference` | String | Specifies the nodes or shards on which you want to perform the search. This setting can be useful for testing, but in most situations, the default behavior provides the best search latencies. Options include `_local`, `_only_local`, `_prefer_nodes`, `_only_nodes`, and `_shards`. These last three options accept a list of nodes or shards. Examples include `"_only_nodes:data-node1,data-node2"` and `"_shards:0,1`. +`request_cache` | Boolean | Specifies whether to cache results, which can improve latency for repeated searches. Default is to use the `index.requests.cache.enable` setting for the index (which defaults to `true` for new indexes). +`routing` | String | Comma-separated custom routing values, for example, `"routing": "value1,value2,value3"`. + +## Request body + +The multi-search template request body follows this pattern, similar to the [Multi-search API]({{site.url}}{{site.baseurl}}/api-reference/multi-search/) pattern: + +``` +Metadata\n +Query\n +Metadata\n +Query\n + +``` + +- Metadata lines include options, such as which indexes to search and the type of search. +- Query lines use [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). + +Like the [bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) operation, the JSON doesn't need to be minified---spaces are fine---but it does need to be on a single line. OpenSearch uses newline characters to parse multi-search requests and requires that the request body end with a newline character. + +## Example request + +The following example `msearch/template` API request runs queries against a single index using multiple templates named `line_search_template` and `play_search_template`: + + +{% capture step1_rest %} +GET /_msearch/template +{"index":"shakespeare"} +{"id":"line_search_template","params":{"text_entry":"All the world's a stage","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} +{% endcapture %} + +{% capture step1_python %} + + +response = client.msearch_template( + body = ''' +{"index":"shakespeare"} +{"id":"line_search_template","params":{"text_entry":"All the world's a stage","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +OpenSearch returns an array with the results of each search in the same order as in the multi-search template request: + +```json +{ + "took": 5, + "responses": [ + { + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 0, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "status": 200 + }, + { + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 0, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "status": 200 + } + ] +} +``` diff --git a/_api-reference/search-apis/search-template/render-template.md b/_api-reference/search-apis/search-template/render-template.md new file mode 100644 index 00000000..8e23c5c3 --- /dev/null +++ b/_api-reference/search-apis/search-template/render-template.md @@ -0,0 +1,147 @@ +--- +layout: default +title: Render template +parent: Search templates +grand_parent: Search APIs +nav_order: 10 +redirect_from: + - /api-reference/render-template/ + - /api-reference/search-apis/render-template/ +--- + +# Render Template API +**Introduced 1.0** +{: .label .label-purple } + +The Render Template API previews the final query generated from a [search template]({{site.url}}{{site.baseurl}}/search-plugins/search-template/) by substituting parameters without executing the search. + +## Endpoints + +```json +GET /_render/template +POST /_render/template +GET /_render/template/{id} +POST /_render/template/{id} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `id` | String | The ID of the search template to render. | + +## Request body fields + +The following table lists the available request body fields. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `id` | Conditional | String | The ID of the search template to render. Is not required if the ID is provided in the path or if an inline template is specified by the `source`. | +| `params` | No | Object | A list of key-value pairs that replace Mustache variables found in the search template. The key-value pairs must exist in the documents being searched. | +| `source` | Conditional | Object | An inline search template to render if a search template is not specified. Supports the same parameters as a [Search]({{site.url}}{{site.baseurl}}/api-reference/search/) API request and [Mustache](https://mustache.github.io/mustache.5.html) variables. | + +## Example request + +Both of the following request examples use the search template with the template ID `play_search_template`: + +```json +{ + "source": { + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +``` +{% include copy.html %} + +### Render template using template ID + +The following example request validates a search template with the ID `play_search_template`: + + +{% capture step1_rest %} +POST /_render/template +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.render_search_template( + body = { + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Render template using `_source` + +If you don't want to use a saved template, or want to test a template before saving, you can test a template with the `_source` parameter using [Mustache](https://mustache.github.io/mustache.5.html) variables, as shown in the following example: + +```json +{ + "source": { + "from": "{% raw %}{{from}}{{^from}}0{{/from}}{% endraw %}", + "size": "{% raw %}{{size}}{{^size}}10{{/size}}{% endraw %}", + "query": { + "match": { + "play_name": "{% raw %}{{play_name}}{% endraw %}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +``` +{% include copy.html %} + +## Example response + +OpenSearch responds with information about the template's output: + +```json +{ + "template_output": { + "from": "0", + "size": "10", + "query": { + "match": { + "play_name": "Henry IV" + } + } + } +} +``` diff --git a/_api-reference/search-apis/search.md b/_api-reference/search-apis/search.md new file mode 100644 index 00000000..a1ad211e --- /dev/null +++ b/_api-reference/search-apis/search.md @@ -0,0 +1,581 @@ +--- +layout: default +title: Search +parent: Search APIs +nav_order: 10 +redirect_from: + - /opensearch/rest-api/search/ + - /api-reference/search/ +--- + +# Search API +**Introduced 1.0** +{: .label .label-purple } + +The search API operation lets you search your cluster for data. + +## Endpoints + +```json +GET /{index}/_search +GET /_search + +POST /{index}/_search +POST /_search +``` + +## Query parameters + +Many of the parameters apply only when you use the URL `q=` parameter or a `query_string` query. See [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) for more information. +{: .note} + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Type | Description +:--- | :--- | :--- +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. Example: `GET test-index-*/_search?allow_no_indices=true`. For more information, see [Targeting multiple indexes]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/#targeting-multiple-indexes). | +`allow_partial_search_results` | Boolean | Whether to return partial results if the request encounters an error or times out. Default is `true`. Example: `GET test-index/_search?allow_partial_search_results=false`. | +`analyzer` | String | The analyzer to use in the query string. Requires `q=` or a `query_string` body. Example: `GET test-index/_search?q=title:test&analyzer=standard`. For more information, see [Text analysis]({{site.url}}{{site.baseurl}}/analyzers/). | +`analyze_wildcard` | Boolean | Whether to analyze wildcard and prefix queries in the query string. Default is `false`. Requires `q=` or `query_string`. Example: `GET test-index/_search?q=title:te*&analyze_wildcard=true`. | +`batched_reduce_size` | Integer | The number of shard results to combine into one batch on the coordinating node before returning the final search results. Limits the number of shard results processed together, helping reduce memory usage when a search request spans many shards. Default is `512`. Example: `GET test-index/_search?batched_reduce_size=2`. | +`cancel_after_time_interval` | Time | The time after which the search request will be canceled. Request-level parameter takes precedence over the `cancel_after_time_interval` [cluster setting]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/). Default is `-1`. Example: `GET test-index/_search?cancel_after_time_interval=10ms`. | +`ccs_minimize_roundtrips` | Boolean | Whether to minimize the number of round trips between a node and remote clusters. Default is `true`. Example: `GET test-index/_search?ccs_minimize_roundtrips=true`. | +`default_operator` | String | The default operator for a string query. Valid values are `AND` and `OR`. Default is `OR`. Requires `q=` or `query_string`. Example: `GET test-index/_search?q=title:test one&default_operator=AND`. | +`df` | String | The default field used if a field prefix is not provided in the query string. Requires `q=` or `query_string`. Example: `GET test-index/_search?q=test&df=title`. | +`docvalue_fields` | String | A comma-separated list of fields whose values should be returned from their doc values representation. Doc values are an optimized, columnar format that improves performance for aggregations, sorting, and scripting. Example: `GET test-index/_search?docvalue_fields=ts,views`. For more information, see [Searching with doc value fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-doc-value-fields). | +`expand_wildcards` | String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values.
Valid values are:
- `all`: Match any index, including hidden ones.
- `closed`: Match closed, non-hidden indexes.
- `hidden`: Match hidden indexes. Must be combined with `open`, `closed`, or both.
- `none`: Wildcard expressions are not accepted.
- `open`: Match open, non-hidden indexes.
Default is `open`. Example: `GET test-index-*/_search?expand_wildcards=open`. For more information, see [Targeting multiple indexes]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/#targeting-multiple-indexes). | +`explain` | Boolean | If `true`, returns details about how OpenSearch computed each document's relevance score. Default is `false`. Only applies when `hits` are included in the search response. Example: `GET test-index/_search?explain=true&size=1&q=title:test`. For more information, see [Explain API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/explain/). | +`from` | Integer | The number of hits to skip before returning results. Use with `size` to paginate results. Default is `0`. Example: `GET test-index/_search?from=5&size=5`. For more information, see [The from and size parameters]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-from-and-size-parameters). | +`ignore_throttled` | Boolean | Whether to ignore concrete indexes, expanded indexes, or indexes with aliases if they are frozen. Default is `true`. Example: `GET test-index/_search?ignore_throttled=true`. | +`ignore_unavailable` | Boolean | If `true`, OpenSearch ignores missing or closed indexes and unavailable shards during the search. If `false`, the request returns an error when targeting missing or closed indexes. Default is `false`. Example: `GET test-index-*/_search?ignore_unavailable=true`. For more information, see [Targeting multiple indexes]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/#targeting-multiple-indexes). | +`include_named_queries_score` | Boolean | Whether to return score contributions from named queries (queries with `_name`) for each hit. Default is `false`. Requires queries named with `_name`. Example: `POST test-index/_search?include_named_queries_score=true {"size":1,"query":{"match":{"title":{"query":"test","_name":"q1"}}}}`. For more information, see [Named queries]({{site.url}}{{site.baseurl}}/query-dsl/named-queries/). | +`lenient` | Boolean | Whether OpenSearch should accept requests if queries have formatting errors (for example, querying a numeric field using text) instead of returning an error. Default is `false`. Requires `q=` or `query_string`. Example: `GET test-index/_search?q=views:abc&lenient=true`. | +`max_concurrent_shard_requests` | Integer | The maximum number of concurrent shard requests this request should execute on each node. Default is `5`. Example: `GET test-index/_search?max_concurrent_shard_requests=2`. | +`node_level_query_fanout` | Boolean | Whether to use node-level query fan-out for this search request, overriding the `search.node_level_query_fanout.enabled` cluster setting when provided. Node-level query fan-out groups shard-level `query_then_fetch` query and `can_match` requests by target data node. Default is `false`. Example: `POST index1/_search?node_level_query_fanout=true`. | +`phase_took` | Boolean | Whether to return phase-level `took` time values in the response. Default is `false`. Example: `GET test-index/_search?phase_took=true`. | +`pre_filter_shard_size` | Integer | A prefilter size threshold for triggering a prefilter operation on search shards. If the number of shards a search request expands to exceeds this value, OpenSearch performs a prefilter operation to eliminate shards that cannot match documents based on query rewriting. Default is `128`. Example: `GET test-index/_search?pre_filter_shard_size=1`. | +`preference` | String | Specifies the shards or nodes on which OpenSearch should perform the search. Example: `GET test-index/_search?preference=_local`. For valid values, see [The preference query parameter]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#the-preference-query-parameter). | +`q` | String | A Lucene query string query. Enables query-string helpers. Takes precedence over the `query` parameter in the request body. If both are specified, only documents matching this parameter are returned; the query in the request body is ignored. Example: `GET test-index/_search?q=title:test&size=5`. For more information, see [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). | +`request_cache` | Boolean | Whether OpenSearch should use caching of search results for a request if `size=0` is specified. Default is the index-level `request_cache` setting. Example: `GET test-index/_search?request_cache=true`. For more information, see [Index request cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/request-cache/). | +`rest_total_hits_as_int` | Boolean | Whether to return `hits.total` as an integer. Returns an object otherwise. Default is `false`. Use with `track_total_hits` set to `true`. Example: `GET test-index/_search?track_total_hits=true&rest_total_hits_as_int=true`. | +`routing` | String | A custom value used to route the search to a specific shard. Example: `GET test-index/_search?routing=user-42`. For more information, see [Routing]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/routing/). | +`scroll` | Time | The amount of time to keep the search context open. Requires `size` greater than `0` and a follow-up `_search/scroll`. Example: `GET test-index/_search?scroll=1m&size=2`. For more information, see [Scroll search]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#scroll-search). | +`search_type` | String | Whether OpenSearch should use global term and document frequencies when calculating relevance scores. Valid values are `query_then_fetch` and `dfs_query_then_fetch`. `query_then_fetch` scores documents using local term and document frequencies for the shard. It's usually faster but less accurate. `dfs_query_then_fetch` scores documents using global term and document frequencies across all shards. It's usually slower but more accurate. Default is `query_then_fetch`. Example: `GET test-index/_search?search_type=dfs_query_then_fetch`. | +`seq_no_primary_term` | Boolean | Whether to return the sequence number and primary term of the last operation of each document hit. Example: `GET test-index/_search?seq_no_primary_term=true&size=1&q=title:test`. | +`size` | Integer | The maximum number of results to return. Use with `from` to paginate results. Default is `10`. Example: `GET test-index/_search?size=3`. For more information, see [The from and size parameters]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-from-and-size-parameters). | +`sort` | List | A comma-separated list of `:` pairs to sort by. Use `track_scores=true` if you want scores when sorting by a non-score field. Example: `GET test-index/_search?sort=views:desc&track_scores=true&size=3`. For more information, see [Sort results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/). | +`_source` | String or Boolean | Controls the `_source` field provided in the response. Valid values are `true` (return the document source), `false` (do not return the document source) and `` (the field or fields in the source to return, provided as a list or wildcard pattern). Examples: `GET test-index/_search?_source=false&size=1`, `GET test-index/_search?_source=titl*&size=1`, `GET test-index/_search?_source=title,description&size=1`. For more information, see [Source filtering](#source-filtering). | +`_source_excludes` | List | A comma-separated list of source fields to exclude from the response. If the `_source` parameter is `false`, this parameter is ignored. Example: `GET test-index/_search?_source_excludes=title&size=1`. For more information, see [Source filtering](#source-filtering). | +`_source_includes` | List | A comma-separated list of source fields to include in the response. If the `_source` parameter is `false`, this parameter is ignored. Example: `GET test-index/_search?_source_includes=title&size=1`. For more information, see [Source filtering](#source-filtering). | +`stats` | String | A comma-separated list of [search stats groups](#search-stats-groups) to associate with the request. Example: `GET test-index/_search?stats=group1`. | +`stored_fields` | List | A comma-separated list of stored fields to return for each hit. Example: `GET test-index-stored/_search?stored_fields=note&size=1`. For more information, see [Searching with stored fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-stored-fields). | +`suggest_field` | String | The field used for term suggestions. Requires `suggest_mode` and either `suggest_text` or `q`. To configure suggestions in the request body, use the `suggest` field. For more information, see [Did-you-mean]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/). +`suggest_mode` | String | The mode to use when searching. Valid values are `always` (provide suggestions based on the terms in `suggest_text`), `popular` (provide suggestions occurring in more documents on the shard than the search term), and `missing` (provide suggestions for terms not on the shard). Required when you use `suggest_field`. +`suggest_size` | Integer | The number of suggestions to return. Requires `suggest_field` and `suggest_mode`. +`suggest_text` | String | The input text for which OpenSearch should return suggestions. Requires `suggest_field` and `suggest_mode`. If omitted, OpenSearch uses the value of `q`. +`terminate_after` | Integer | The maximum number of matching documents (hits) OpenSearch should process before terminating the request. Default is `0` (no maximum). Example: `GET test-index/_search?terminate_after=1&size=10`. | +`timeout` | Time | How long the operation should wait for a response from active shards. Default is `1m` (1 minute). Example: `GET test-index/_search?timeout=10ms`. | +`track_scores` | Boolean | Whether to return document scores. Default is `false`. Use with `sort`. Example: `GET test-index/_search?sort=views:desc&track_scores=true&size=3`. For more information, see [Tracking scores]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/#tracking-scores). | +`track_total_hits` | Boolean or Integer | How many matching documents to count. Default is `10000`. Example: `GET test-index/_search?track_total_hits=2`. For more information, see [Track total hits](#track-total-hits). | +`typed_keys` | Boolean | Whether returned aggregations and suggested terms should include their types in the response. Default is `false`. Only applicable for aggregations or suggesters. Example: `POST test-index/_search?typed_keys=true {"size":0,"aggs":{"a":{"terms":{"field":"views"}}}}`. For more information, see [Including suggester types in the response]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/#including-suggester-types-in-the-response). | +`version` | Boolean | Whether to include the document version as a match. Example: `GET test-index/_search?version=true&size=1&q=title:test`. | + +### The `preference` query parameter + +The `preference` query parameter specifies the shards or nodes on which OpenSearch should perform the search. The following are valid values: + +- `_primary`: Perform the search only on primary shards. +- `_replica`: Perform the search only on replica shards. +- `_primary_first`: Perform the search on primary shards but fail over to other available shards if primary shards are not available. +- `_replica_first`: Perform the search on replica shards but fail over to other available shards if replica shards are not available. +- `_local`: If possible, perform the search on the local node's shards. +- `_prefer_nodes:,`: If possible, perform the search on the specified nodes. Use a comma-separated list to specify multiple nodes. +- `_shards:,`: Perform the search only on the specified shards. Use a comma-separated list to specify multiple shards. When combined with other preferences, the `_shards` preference must be listed first. For example, `_shards:1,2|_replica`. +- `_only_nodes:,`: Perform the search only on the specified nodes. Use a comma-separated list to specify multiple nodes. +- ``: Specifies a custom string to use for the search. The string cannot start with an underscore character (`_`). Searches with the same custom string are routed to the same shards. + +## Request body + +The following table lists the available request body fields. All request body fields are optional. + +Field | Type | Description +:--- | :--- | :--- +`aggregations`, `aggs` | Object | In the optional `aggregations` parameter (or its short form, `aggs`), you can define any number of aggregations. Each aggregation is defined by its name and one of the types of aggregations that OpenSearch supports. For more information, see [Aggregations]({{site.url}}{{site.baseurl}}/aggregations/). +`collapse` | Object | Collapses the search results so that only the top document for each value of the specified field is returned. For more information, see [Collapse search results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/collapse-search/). +`derived` | Object | Defines derived fields, which are computed at search time by a script and can be queried, aggregated, and returned like indexed fields. For more information, see [Derived fields]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/derived/). +`docvalue_fields` | Array of objects | The fields to return in their `doc_values` form. You can include a format for the returned values (for example, a date format). For `knn_vector` fields, supported formats are `binary` (default, Base64-encoded) and `array` (JSON numeric arrays). For more information, see [Retrieving vector fields using `docvalue_fields`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#retrieving-vector-fields-using-docvalue_fields). +`explain` | Boolean | Whether to return details about how OpenSearch computed the document's score. Default is `false`. +`ext` | Object | Settings used by plugins, such as search pipeline processors. For more information, see [The ext object](#the-ext-object). +`fields` | Array | The fields to return in the `fields` object of each hit. You can use wildcard patterns and specify a format for date fields. For more information, see [Retrieve specific fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/). +`from` | Integer | The number of results to skip before returning results. Use with `size` to paginate results. Default is `0`. For more information, see [The from and size parameters]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-from-and-size-parameters). +`highlight` | Object | Returns snippets of the matching text with the search terms highlighted. For more information, see [Highlight query matches]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/). +`include_named_queries_score` | Boolean | Whether to return scores for named queries. +`indices_boost` | Array of objects | Boosts the`_score` of documents from specific indexes. Each entry specifies an index and a boost factor in the format `: `. A boost greater than `1.0` increases the score, while a boost between `0` and `1.0` decreases it. +`min_score` | Float | The minimum score that a document must have to be returned in the results. +`pit` | Object | The Point in Time (PIT) to search. When you search a PIT, do not specify an index in the request path. For more information, see [Point in Time]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/). +`post_filter` | Object | A query that filters the results after aggregations are calculated. The aggregations include all documents that match the `query`, while the results include only the documents that also match `post_filter`. For more information, see [Filter search results]({{site.url}}{{site.baseurl}}/search-plugins/filter-search/#narrowing-results-using-post-filter-while-preserving-aggregation-visibility). +`profile` | Boolean | Whether to return detailed timing information about how each part of the query was executed. Default is `false`. For more information, see [Profile API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/profile/). +`query` | Object | The [DSL query]({{site.url}}{{site.baseurl}}/query-dsl/) to use in the request. +`rescore` | Object or Array of objects | Reorders the top results returned by the `query` using a second, typically more expensive, query. For more information, see [Rescore]({{site.url}}{{site.baseurl}}/query-dsl/rescore/). +`script_fields` | Object | Fields whose values are computed by a script for each hit and returned in the `fields` object. For more information, see [Using scripted fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-scripted-fields). +`search_after` | Array | The sort values of the last hit on the previous page. Returns the results that follow it in the sort order. Requires `sort`. For more information, see [The search_after parameter]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-search_after-parameter). +`search_pipeline` | Object | A temporary search pipeline that applies only to this request. For more information, see [Search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/). +`seq_no_primary_term` | Boolean | Whether to return sequence number and primary term of the last operation of each document hit. +`size` | Integer | The maximum number of results to return. Use with `from` to paginate results. Default is `10`. For more information, see [The from and size parameters]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-from-and-size-parameters). +`slice` | Object | Splits a scroll or PIT search into slices that can be processed independently. For more information, see [Scroll search]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#scroll-search). +`sort` | Array of objects or strings | Specifies how to sort the results. Can be a field name, an object with field and sort options, or an array of these. See [Sorting results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/). +`_source` | Boolean, String, Array of strings, or Object | The document source fields to return in each hit. Default is `true` (return the full document). For more information, see [Source filtering](#source-filtering). +`stats` | Array of strings | A list of [search stats groups](#search-stats-groups) to associate with the request. +`stored_fields` | Array of strings | The stored fields to return for each hit. If you specify `stored_fields`, `_source` is not returned unless you request it. For more information, see [Searching with stored fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-stored-fields). +`suggest` | Object | Returns suggested terms or phrases that are similar to the provided text. For more information, see [Did-you-mean]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/). +`terminate_after` | Integer | The maximum number of matching documents (hits) OpenSearch should process before terminating the request. Default is 0. +`timeout` | Time | How long to wait for a response. Default is no timeout. +`track_scores` | Boolean | Whether to calculate and return document scores when sorting by a field other than `_score`. Default is `false`, in which case `_score` is `null` in sorted results. +`track_total_hits` | Boolean or Integer | How many matching documents to count accurately. Default is `10000`. For more information, see [Track total hits](#track-total-hits). +`verbose_pipeline` | Boolean | Whether to return information about each search pipeline processor that ran for the request. Default is `false`. For more information, see [Debugging a search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/debugging-search-pipeline/). +`version` | Boolean | Whether to include the document version in the response. + +### Search stats groups + +You can associate a search request with one or more stats groups by specifying group names in the `stats` field of the request body or as a query parameter. OpenSearch maintains per-group search statistics that you can retrieve using the [Index Stats API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/stats/#specific-search-groups). + +The following example associates a search request with two groups: + +```json +POST /my-index/_search +{ + "query": { + "match_all": {} + }, + "stats": ["group1", "group2"] +} +``` +{% include copy-curl.html %} + +To retrieve search statistics for specific groups, use the `groups` query parameter of the Index Stats API: + +```json +GET /my-index/_stats/search?groups=group1,group2 +``` +{% include copy-curl.html %} + +To return statistics for all groups, use `_all`: + +```json +GET /my-index/_stats/search?groups=_all +``` +{% include copy-curl.html %} + +## Example request + + +{% capture step1_rest %} +GET /movies/_search +{ + "query": { + "match": { + "director": "Christopher Nolan" + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.search( + index = "movies", + body = { + "query": { + "match": { + "director": "Christopher Nolan" + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +The following example response shows the structure of a search response: + +```json +{ + "took": 14, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.42727602, + "hits": [ + { + "_index": "movies", + "_id": "1", + "_score": 0.42727602, + "_source": { + "title": "The Dark Knight", + "director": "Christopher Nolan", + "year": 2008, + "genre": "Action" + } + }, + { + "_index": "movies", + "_id": "2", + "_score": 0.42727602, + "_source": { + "title": "Inception", + "director": "Christopher Nolan", + "year": 2010, + "genre": "Science Fiction" + } + } + ] + } +} +``` + +## Response body fields + +The following table lists the top-level response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `took` | Integer | The time, in milliseconds, that OpenSearch took to run the search. This is measured from the moment the coordinating node receives the request until it is ready to send the response, so it includes communication between the coordinating node and the data nodes, time spent queued in the `search` thread pool, and the search itself. It does not include the time spent transmitting the request or the response over the network. | +| `phase_took` | Object | The time, in milliseconds, spent in each search phase (`can_match`, `dfs_pre_query`, `query`, `dfs_query`, `fetch`, and `expand`). Returned only when the `phase_took` query parameter is `true`. | +| `timed_out` | Boolean | Whether the search timed out before completing. If `true`, the returned results may be partial or empty. | +| `terminated_early` | Boolean | Whether OpenSearch stopped the search early because it collected the number of documents specified in `terminate_after`. Returned only when `terminate_after` is set. | +| `_shards` | Object | The number of shards that the search ran on and the outcome for each group of shards. | +| `hits` | Object | The matching documents and their metadata. | +| `aggregations` | Object | The aggregation results, keyed by aggregation name. Returned only when the request body contains an `aggs` object. | +| `suggest` | Object | The suggestion results, keyed by suggester name. Returned only when the request body contains a `suggest` object. | +| `profile` | Object | Per-shard timing details for the query and fetch phases. Returned only when the request body sets `profile` to `true`. For more information, see [Profile API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/profile/). | +| `_scroll_id` | String | The scroll ID that identifies the search context. Pass this value to the [Scroll API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/scroll/) to retrieve the next batch of results. Returned only when the request includes the `scroll` query parameter. | +| `pit_id` | String | The Point in Time (PIT) ID that identifies the search context. Returned only when the request searches a PIT. For more information, see [Point in Time API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/). | +| `_clusters` | Object | The number of clusters that a cross-cluster search ran on and the outcome for each group of clusters. Returned only for cross-cluster searches. | +| `num_reduce_phases` | Integer | The number of reduce phases that OpenSearch performed in order to combine partial shard results into the final result set. Returned only when the search uses more than one reduce phase. | + +The following table lists the fields in the `_shards` object. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `total` | Integer | The number of shards that the search needed to query, including unallocated shards. | +| `successful` | Integer | The number of shards that ran the search successfully. | +| `skipped` | Integer | The number of shards that skipped the search because a preliminary check determined that no document on the shard could match. This commonly happens when the search contains a range filter and all values on the shard fall outside of that range. | +| `failed` | Integer | The number of shards that failed to run the search. Unallocated shards count as neither successful nor failed, so if `successful` and `failed` add up to less than `total`, some of the shards were unallocated. | + +The following table lists the fields in the `hits` object. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `total` | Object | The number of matching documents. Contains a `value` field with the count and a `relation` field that is `eq` when the count is exact or `gte` when the count is a lower bound. Omitted when `track_total_hits` is `false`. | +| `max_score` | Float | The highest `_score` among the matching documents. Is `null` when the search does not sort by `_score`. | +| `hits` | Array of objects | The matching documents, ordered by relevance or by the specified sort. | + +The following table lists the fields in each object in the `hits.hits` array. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_index` | String | The name of the index that contains the document. | +| `_id` | String | The document ID. This ID is unique only within the returned index. | +| `_score` | Float | The relevance score for the document. Is `null` when the search does not sort by `_score`. | +| `_source` | Object | The original JSON document provided at indexing time. To omit this field or to return only specific fields, see [Source filtering](#source-filtering). | +| `fields` | Object | The field values retrieved by `docvalue_fields` or `stored_fields`. Returned only when the request specifies either of those parameters. | +| `sort` | Array | The sort values for the document. Returned only when the request body contains a `sort` array. Pass the values from the last hit as `search_after` to retrieve the next page of results. | +| `highlight` | Object | The highlighted snippets, keyed by field name. Returned only when the request body contains a `highlight` object. | +| `matched_queries` | Array of strings | The names of the named queries that the document matched. Returned only when the search uses the `_name` parameter. | +| `inner_hits` | Object | The matching nested, child, or parent documents. Returned only when the request body contains an `inner_hits` object. | +| `_explanation` | Object | A breakdown of how OpenSearch computed the document's relevance score. Returned only when `explain` is `true`. | +| `_shard` | String | The shard that returned the document. Returned only when `explain` is `true`. | +| `_node` | String | The node that returned the document. Returned only when `explain` is `true`. | + +## Source filtering + +Each hit in the response contains a `_source` object holding the original JSON document. Returning the full document for every hit transfers more data than most applications need. Source filtering limits the fields that OpenSearch returns in `_source`. + +The following table lists the accepted values for the `_source` request body parameter. + +| Value | Description | +| :--- | :--- | +| `true` | Returns the full document. This is the default. | +| `false` | Omits the `_source` object from each hit. | +| String | A field name or a wildcard pattern, such as `details.*`. OpenSearch returns only the matching fields. | +| Array of strings | A list of field names or wildcard patterns, such as `["name", "details.*"]`. | +| Object | An object containing `includes` and `excludes` lists. A field that matches a pattern in both lists is not returned because `excludes` takes precedence. | + +To filter the source in the request URL instead of the request body, use the `_source`, `_source_includes`, and `_source_excludes` query parameters. + +For examples and limitations, see [Using source filtering]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-source-filtering). + +## Track total hits + +Counting matching documents exactly requires visiting every match, which is expensive for queries that match many documents. The `track_total_hits` parameter limits how many matches OpenSearch counts. Specify it either as a query parameter or in the request body. + +By default, OpenSearch counts matches accurately up to `10000`. When more documents match, `hits.total.value` reports `10000` and `hits.total.relation` is `gte`, indicating that the query matched at least that many documents. + +The following table lists the accepted values for `track_total_hits`. + +| Value | Description | +| :--- | :--- | +| `true` | Counts every matching document. `hits.total.relation` is always `eq`. | +| `false` | Disables hit counting. The response contains no `hits.total` object. | +| Integer | Counts matching documents accurately up to the specified number. When more documents match, `hits.total.value` reports the threshold and `hits.total.relation` is `gte`. | + +Counting every match slows down searches that match many documents. Once the count reaches the threshold, OpenSearch can skip documents that cannot enter the top results, which makes searches sorted by relevance faster. Increase the threshold only when your application requires an exact count, and set `track_total_hits` to `false` when you do not display a count at all. + +The `rest_total_hits_as_int` query parameter requires an exact count. OpenSearch rejects a request that sets `rest_total_hits_as_int` to `true` and sets `track_total_hits` to an integer. + +### Example: Default hit counting + +The following example searches a `logs` index containing 10,500 documents without specifying `track_total_hits`: + +```json +GET /logs/_search +{ + "size": 0, + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +Because `relation` is `gte`, the index contains at least 10,000 matching documents: + +```json +{ + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + } +} +``` + +### Example: Counting every matching document + +To count every match, set `track_total_hits` to `true`: + +```json +GET /logs/_search +{ + "size": 0, + "track_total_hits": true, + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +Because `relation` is `eq`, `value` is the exact number of matching documents: + +```json +{ + "hits": { + "total": { + "value": 10500, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } +} +``` + +### Example: Counting up to a custom threshold + +An integer threshold returns an exact count when fewer documents match and a lower bound otherwise. In the `logs` index, 35 documents have the `level` value `error`, and the remaining documents have the value `info`. The following request counts `error` documents up to a threshold of 50: + +```json +GET /logs/_search +{ + "size": 0, + "track_total_hits": 50, + "query": { + "term": { + "level": "error" + } + } +} +``` +{% include copy-curl.html %} + +Fewer than 50 documents match, so the count is exact: + +```json +{ + "hits": { + "total": { + "value": 35, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } +} +``` + +If you run the same request with `"level": "info"`, more than 50 documents match. OpenSearch stops counting at the threshold and returns a lower bound: + +```json +{ + "hits": { + "total": { + "value": 50, + "relation": "gte" + }, + "max_score": null, + "hits": [] + } +} +``` + +### Example: Disabling hit counting + +If your application does not display the number of matches, set `track_total_hits` to `false`: + +```json +GET /logs/_search +{ + "size": 2, + "_source": false, + "track_total_hits": false, + "query": { + "term": { + "level": "error" + } + } +} +``` +{% include copy-curl.html %} + +The `hits` object contains the matching documents but no `total` object: + +```json +{ + "hits": { + "max_score": 1.0, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1.0 + }, + { + "_index": "logs", + "_id": "301", + "_score": 1.0 + } + ] + } +} +``` + +## The `ext` object +**Introduced 2.10** +{: .label .label-purple } + +Plugin authors can add an `ext` object to both search requests and search responses. The `ext` object contains plugin-specific fields that allow plugins to pass additional parameters in requests or return additional information in responses. + +### Using `ext` in search responses + +Plugins can add an `ext` object to the search response to include plugin-specific response fields. For example, in conversational search, the result of retrieval-augmented generation (RAG) is a single "hit" (answer). Plugin authors can include this answer in the search response as part of the `ext` object so that it is separate from the search hits. In the following example response, the RAG result is in the `ext.retrieval_augmented_generation.answer` field: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 3, + "successful": 3, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 110, + "relation": "eq" + }, + "max_score": 0.55129033, + "hits": [ + { + "_index": "...", + "_id": "...", + "_score": 0.55129033, + "_source": { + "text": "...", + "title": "..." + } + }, + { + ... + } + ... + { + ... + } + ], + }, // end of hits + "ext": { + "retrieval_augmented_generation": { // a search response processor + "answer": "RAG answer" + } + } +} +``` + +### Using `ext` in search requests + +Plugins can also accept an `ext` object in search requests to provide plugin-specific parameters. The structure and content of the `ext` object in requests depends on the plugin implementation. Consult your plugin's documentation for the specific fields supported in the request `ext` object. + +The following example shows a search request that includes an `ext` object. The exact fields within `ext` depend on which plugins are installed and what parameters they accept: + +```json +POST /my-index/_search +{ + "query": { + "match": { + "field": "value" + } + }, + "ext": { + "my_plugin": { + "custom_parameter": "value" + } + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:data/read/search`. diff --git a/_api-reference/search-apis/validate.md b/_api-reference/search-apis/validate.md new file mode 100644 index 00000000..e3615f38 --- /dev/null +++ b/_api-reference/search-apis/validate.md @@ -0,0 +1,340 @@ +--- +layout: default +title: Validate query +nav_order: 87 +parent: Search APIs +redirect_from: + - /api-reference/validate/ +--- + +# Validate Query API +**Introduced 1.0** +{: .label .label-purple } + +You can use the Validate Query API to validate a query without running it. The query can be sent as a path parameter or included in the request body. + +## Endpoints + +The Validate Query API contains the following path: + +```json +GET {index}/_validate/query +``` + +## Path parameters + +All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`index` | String | The index to validate the query against. If you don't specify an index or multiple indexes as part of the URL (or want to override the URL value for an individual search), you can include it here. Examples include `"logs-*"` and `["my-store", "sample_data_ecommerce"]`. +`query` | Query object | The query using [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`all_shards` | Boolean | When `true`, validation is run against [all shards](#rewrite-and-all_shards) instead of against one shard per index. Default is `false`. +`allow_no_indices` | Boolean | Whether to ignore wildcards that don't match any indexes. Default is `true`. +`allow_partial_search_results` | Boolean | Whether to return partial results if the request encounters an error or times out. Default is `true`. +`analyzer` | String | The analyzer to use in the query string. This should only be used with the `q` option. +`analyze_wildcard` | Boolean | Specifies whether to analyze wildcard and prefix queries. Default is `false`. +`default_operator` | String | Indicates whether the default operator for a string query should be `AND` or `OR`. Default is `OR`. +`df` | String | The default field if a field prefix is not provided in the query string. +`expand_wildcards` | String | Specifies the type of index that wildcard expressions can match. Supports comma-separated values. Valid values are `all` (match any index), `open` (match open, non-hidden indexes), `closed` (match closed, non-hidden indexes), `hidden` (match hidden indexes), and `none` (deny wildcard expressions). Default is `open`. +`explain` | Boolean | Whether to return information about how OpenSearch computed the [document's score](#explain). Default is `false`. +`ignore_unavailable` | Boolean | Specifies whether to include missing or closed indexes in the response and ignores unavailable shards during the search request. Default is `false`. +`lenient` | Boolean | Specifies whether OpenSearch should ignore format-based query failures (for example, as a result of querying a text field for an integer). Default is `false`. +`rewrite` | Determines how OpenSearch [rewrites](#rewrite) and scores multi-term queries. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. Default is `constant_score`. +`q` | String | A query in the Lucene string syntax. + +## Example request + +The following example request uses an index named `Hamlet` created using a `bulk` request: + + +{% capture step1_rest %} +PUT /hamlet/_bulk?refresh +{"index":{"_id":1}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:12", "message" : "To Search or Not To Search"} +{"index":{"_id":2}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:13", "message" : "My dad says that I'm such a ham."} +{% endcapture %} + +{% capture step1_python %} + + +response = client.bulk( + index = "hamlet", + params = { "refresh": "true" }, + body = ''' +{"index":{"_id":1}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:12", "message" : "To Search or Not To Search"} +{"index":{"_id":2}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:13", "message" : "My dad says that I'm such a ham."} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +You can then use the Validate Query API to validate an index query, as shown in the following example: + + +{% capture step1_rest %} +GET /hamlet/_validate/query?q=user.id:hamlet +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.validate_query( + index = "hamlet", + params = { "q": "user.id:hamlet" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The query can also be sent as a request body, as shown in the following example: + + +{% capture step1_rest %} +GET /hamlet/_validate/query +{ + "query": { + "bool": { + "must": { + "query_string": { + "query": "*:*" + } + }, + "filter": { + "term": { + "user.id": "hamlet" + } + } + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.validate_query( + index = "hamlet", + body = { + "query": { + "bool": { + "must": { + "query_string": { + "query": "*:*" + } + }, + "filter": { + "term": { + "user.id": "hamlet" + } + } + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example responses + +If the query passes validation, then the response indicates that the query is `true`, as shown in the following example response, where the `valid` parameter is `true`: + +``` +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true +} +``` + +If the query does not pass validation, then OpenSearch responds that the query is `false`. The following example request query includes a dynamic mapping not configured in the `hamlet` index: + + +{% capture step1_rest %} +GET /hamlet/_validate/query +{ + "query": { + "query_string": { + "query": "@timestamp:foo", + "lenient": false + } + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.validate_query( + index = "hamlet", + body = { + "query": { + "query_string": { + "query": "@timestamp:foo", + "lenient": false + } + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +OpenSearch responds with the following, where the `valid` parameter is `false`: + +``` +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": false +} +``` + +Certain query parameters can also affect what is included in the response. The following examples show how the [Explain](#explain), [Rewrite](#rewrite), and [all_shards](#rewrite-and-all_shards) query options affect the response. + +### Explain + +The `explain` option returns information about the query failure in the `explanations` field, as shown in the following example response: + +``` +{ + "valid" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "failed" : 0 + }, + "explanations" : [ { + "index" : "_shakespeare", + "valid" : false, + "error" : "shakespeare/IAEc2nIXSSunQA_suI0MLw] QueryShardException[failed to create query:...failed to parse date field [foo]" + } ] +} +``` + + +### Rewrite + +When the `rewrite` option is set to `true` in the request, the `explanations` option shows the Lucene query that is executed as a string, as shown in the following response: + +``` +{ + "valid": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "explanations": [ + { + "index": "", + "valid": true, + "explanation": "((user:hamlet^4.256753 play:hamlet^6.863601 play:romeo^2.8415773 plot:puck^3.4193945 plot:othello^3.8244398 ... )~4) -ConstantScore(_id:2) #(ConstantScore(_type:_doc))^0.0" + } + ] +} +``` + + +### Rewrite and all_shards + +When both the `rewrite` and `all_shards` options are set to `true`, the Validate Query API responds with detailed information from all available shards as opposed to only one shard (the default), as shown in the following response: + +``` +{ + "valid": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "explanations": [ + { + "index": "my-index-000001", + "shard": 0, + "valid": true, + "explanation": "(user.id:hamlet)^0.6333333" + } + ] +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `indices:admin/validate/query`. diff --git a/_api-reference/snapshots/cleanup-snapshot-repository.md b/_api-reference/snapshots/cleanup-snapshot-repository.md new file mode 100644 index 00000000..54d902c6 --- /dev/null +++ b/_api-reference/snapshots/cleanup-snapshot-repository.md @@ -0,0 +1,84 @@ +--- +layout: default +title: Clean up snapshot repository +parent: Snapshot APIs +nav_order: 45 +--- + +# Clean Up Snapshot Repository API +**Introduced 1.0** +{: .label .label-purple } + +The Clean Up Snapshot Repository API clears a snapshot repository of data no longer referenced by any existing snapshot. + +## Endpoints + +```json +POST /_snapshot/{repository}/_cleanup +``` + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `repository` | String | The name of the snapshot repository. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Formerly called `master_timeout`. Optional. Default is 30 seconds. | +| `timeout` | Time | The amount of time to wait for the operation to complete. Optional.| + +## Example request + +The following request removes all stale data from the repository `my_backup`: + + +{% capture step1_rest %} +POST /_snapshot/my_backup/_cleanup +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.cleanup_repository( + repository = "my_backup" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +```json +{ + "results":{ + "deleted_bytes":40, + "deleted_blobs":8 + } +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `deleted_bytes` | Integer | The number of bytes made available in the snapshot after data deletion. | +| `deleted_blobs` | Integer | The number of binary large objects (BLOBs) cleared from the repository by the request. | + diff --git a/_api-reference/snapshots/clone-snapshot.md b/_api-reference/snapshots/clone-snapshot.md new file mode 100644 index 00000000..39e14c28 --- /dev/null +++ b/_api-reference/snapshots/clone-snapshot.md @@ -0,0 +1,111 @@ +--- +layout: default +title: Clone snapshot +parent: Snapshot APIs +nav_order: 100 +--- + +# Clone Snapshot API +**Introduced 1.0** +{: .label .label-purple } + +Creates a clone of all or part of a snapshot in the same repository as the original. + + + +## Endpoints +```json +PUT /_snapshot/{repository}/{snapshot}/_clone/{target_snapshot} +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `repository` | **Required** | String | The name of repository which will contain the snapshots clone. | +| `snapshot` | **Required** | String | The name of the original snapshot. | +| `target_snapshot` | **Required** | String | The name of the cloned snapshot. | + + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | String | The amount of time to wait for a response from the cluster manager node. For more information about supported time units, see [Common parameters]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). | + + + + +## Example request + +The following request clones indexes `index_a` and `index_b` from `my_snapshot`, a snapshot located in the snapshot repository `my-opensearch-repo`, into a new snapshot in the same repository called `my_new_snapshot`: + + +{% capture step1_rest %} +PUT /_snapshot/my-opensearch-repo/my_snapshot/_clone/my_new_snapshot +{ + “indices” : “index_a,index_b” +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.clone( + repository = "my-opensearch-repo", + snapshot = "my_snapshot", + target_snapshot = "my_new_snapshot", + body = ''' +{ + “indices” : “index_a,index_b” +} +''' +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +The successful creation of a snapshot clone returns the following response: + +```json +{ + "acknowledged" : true +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/clone`. diff --git a/_api-reference/snapshots/create-repository.md b/_api-reference/snapshots/create-repository.md index 856332b7..a5ba390d 100644 --- a/_api-reference/snapshots/create-repository.md +++ b/_api-reference/snapshots/create-repository.md @@ -1,58 +1,191 @@ --- layout: default -title: Register Snapshot Repository +title: Create or update snapshot repository parent: Snapshot APIs -nav_order: 1 +nav_order: 10 --- -# Registering or updating a snapshot repository +# Create or Update Snapshot Repository API **Introduced 1.0** {: .label .label-purple } -You can register a new repository in which to store snapshots or update information for an existing repository by using the snapshots API. +Registers a new snapshot repository or updates an existing one. -There are two types of snapshot repositories: +Snapshot repositories can be of the following types: -* File system (`fs`): For instructions on creating an `fs` repository, see [Register repository shared file system]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#shared-file-system). +* File system (`fs`): For more information about creating an `fs` repository, see [Register repository shared file system]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#shared-file-system). -* Amazon Simple Storage Service (Amazon S3) bucket (`s3`): For instructions on creating an `s3` repository, see [Register repository Amazon S3]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#amazon-s3). +* Amazon Simple Storage Service (Amazon S3) bucket (`s3`): For more information about creating an `s3` repository, see [Register repository Amazon S3]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#amazon-s3). -For instructions on creating a repository, see [Register repository]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore#register-repository). +* Hadoop Distributed File System (HDFS) (`hdfs`): For more information about creating an `hdfs` repository, see [Register an HDFS repository]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#hdfs). -## Path and HTTP methods +For more information about creating a repository, see [Register repository]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#register-repository). -``` -POST /_snapshot/my-first-repo/ -PUT /_snapshot/my-first-repo/ +To update an existing repository, send a request containing the repository's full definition. The new settings replace all existing settings, so any setting that you don't include in the request is reset to its default value. + +Because the snapshot format can change between major versions, we recommend registering a separate repository for each major version of OpenSearch. For more information, see [Sharing a repository between clusters]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#sharing-a-repository-between-clusters). + +## Endpoints + +```json +POST /_snapshot/{repository} +PUT /_snapshot/{repository} ``` ## Path parameters +The following table lists the available path parameters. + Parameter | Data type | Description :--- | :--- | :--- -repository | String | Repository name | +`repository` | String | The repository name. -## Request parameters +## Query parameters -Request parameters depend on the type of repository: `fs` or `s3`. +The following table lists the available query parameters. All query parameters are optional. -### fs repository +Parameter | Data type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time to wait for a response. Default is `30s`. +`verify` | Boolean | Whether to verify that the repository is accessible from all cluster manager and data nodes before registering it. If `false`, OpenSearch registers the repository without checking it. To verify the repository later, use the [Verify Snapshot Repository API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/verify-snapshot-repository/). Default is `true`. + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`type` | String | The repository type. Valid values are `fs`, `s3`, `hdfs`, `azure`, and `url`. The `s3`, `hdfs`, and `azure` types require the corresponding repository plugin. For information about `azure` repositories, see [Microsoft Azure]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#configuring-microsoft-azure-blob-storage). Required. +`settings` | Object | The repository settings. The valid settings depend on the repository type and are listed in the following sections. Required. + +### Common parameters + +The following table lists parameters that can be used with both the `fs` and `s3` repositories. Request field | Description :--- | :--- -`location` | The file system directory for snapshots, such as a mounted directory from a file server or a Samba share. Must be accessible by all nodes. Required. -`chunk_size` | Breaks large files into chunks during snapshot operations (e.g. `64mb`, `1gb`), which is important for cloud storage providers and far less important for shared file systems. Default is `null` (unlimited). Optional. +`prefix_mode_verification` | When enabled, adds a hashed value of a random seed to the prefix for repository verification. For remote-store-enabled clusters, you can add the `setting.prefix_mode_verification` setting to the node attributes for the supplied repository. This field works with both new and existing repositories. Optional. +`shard_path_type` | Controls the path structure of shard-level blobs. Supported values are `FIXED`, `HASHED_PREFIX`, and `HASHED_INFIX`. For more information about each value, see [shard_path_type values](#shard_path_type-values). Default is `HASHED_PREFIX`. Optional. + + +#### shard_path_type values + + +The following values are supported in the `shard_path_type` setting: + +- `FIXED`: Keeps the path structure in the existing hierarchical manner, such as `//indices//0/`. +- `HASHED_PREFIX`: Prepends a hashed prefix at the start of the path for each unique shard ID, for example, `///indices//0/`. +- `HASHED_INFIX`: Appends a hashed prefix after the base path for each unique shard ID, for example, `///indices//0/`. The hash method used is `FNV_1A_COMPOSITE_1`, which uses the `FNV1a` hash function and generates a custom-encoded 64-bit hash value that scales well with most remote store options. `FNV1a` takes the most significant 6 bits to create a URL-safe Base64 character and the next 14 bits to create a binary string. + + +### fs repository + + +The following table lists the request fields for `fs` repositories. + +Request field | Description +:--- | :--- +`location` | The file system directory for snapshots, such as a mounted directory from a file server or a Samba share. The file system must be mounted at the same path on all cluster manager and data nodes, and the location must be listed in the `path.repo` setting. A relative path is resolved against the first `path.repo` directory. Required. +`chunk_size` | Breaks large files into chunks during snapshot operations (for example, `64mb` or `1gb`), which is important for cloud storage providers and far less important for shared file systems. Default is `null` (unlimited). Optional. `compress` | Whether to compress metadata files. This setting does not affect data files, which might already be compressed, depending on your index settings. Default is `false`. Optional. -`max_restore_bytes_per_sec` | The maximum rate at which snapshots restore. Default is 40 MB per second (`40m`). Optional. -`max_snapshot_bytes_per_sec` | The maximum rate at which snapshots take. Default is 40 MB per second (`40m`). Optional. -`remote_store_index_shallow_copy` | Boolean | Determines whether the snapshot of the remote store indexes are captured as a shallow copy. Default is `false`. -`readonly` | Whether the repository is read-only. Useful when migrating from one cluster (`"readonly": false` when registering) to another cluster (`"readonly": true` when registering). Optional. +`max_restore_bytes_per_sec` | The maximum rate per node at which snapshots are restored. Default is `0` (unlimited). The restore rate is also subject to `indices.recovery.max_bytes_per_sec` (by default, `40mb`). Optional. +`max_snapshot_bytes_per_sec` | The maximum rate per node at which snapshots are taken. Default is 40 MB per second (`40mb`). Optional. +`remote_store_index_shallow_copy` | Determines whether the snapshots of the remote store indexes are captured as shallow copies. Default is `false`. +`shallow_snapshot_v2` | Determines whether the snapshots of the remote store indexes are captured as a [shallow copy v2]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/snapshot-interoperability/#shallow-snapshot-v2). Default is `false`. +`readonly` | Whether the repository is read-only. A read-only repository can list and restore snapshots but can't create them. If you register the same repository on multiple clusters, only one cluster should write to it, and all other clusters should register it with `readonly` set to `true`. For more information, see [Sharing a repository between clusters]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#sharing-a-repository-between-clusters). Default is `false`. Optional. -#### Example request + +### s3 repository + -The following example registers an `fs` repository using the local directory `/mnt/snapshots` as `location`. +The following table lists the request fields for `s3` repositories. -```json +| Request field | Description | +| :--- | :--- | +| `base_path` | The path within the bucket in which you want to store snapshots (for example, `my/snapshot/directory`). Do not include the `s3://` prefix. Optional. If not specified, snapshots are stored in the S3 bucket root. | +| `bucket` | The name of the S3 bucket, without the `s3://` prefix. Required. | +| `region` | The AWS Region in which the S3 bucket is located. Optional. If missing, values of `s3.client.default.region` from `opensearch.yml` are used. | +| `endpoint` | The S3 bucket endpoint. If not specified, the value of `s3.client.default.endpoint` from `opensearch.yml` is used. If neither is set, the endpoint is determined from the `region`. Set this field when you use an S3-compatible storage service or need a specific endpoint, for example, `https://s3.us-west-2.amazonaws.com` for `us-west-2`. Optional. | +| `buffer_size` | The threshold beyond which chunks (of `chunk_size`) should be broken into pieces (of `buffer_size`) and sent to S3 using a different API. Default is the smaller of two values: 100 MB or 5% of the Java heap. Valid values are between `5mb` and `5gb`. We don't recommend changing this option. | +| `canned_acl` | S3 has several [canned ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) that the `repository-s3` plugin can add to objects as it creates them in S3. Default is `private`. Optional. | +| `chunk_size` | Breaks files into chunks during snapshot operations (for example, `64mb`, `1gb`), which is important for cloud storage providers and far less important for shared file systems. Default is `1gb`. Optional. | +| `client` | When specifying client settings (for example, `s3.client.default.access_key`), you can use a string other than `default` (for example, `s3.client.backup-role.access_key`). If you used an alternate name, change this value to match. Default and recommended value is `default`. Optional. | +| `compress` | Whether to compress metadata files. This setting does not affect data files, which might already be compressed, depending on your index settings. Default is `false`. Optional. | +| `disable_chunked_encoding` | Disables chunked encoding for compatibility with some storage services. Default is `false`. Optional. | +| `max_restore_bytes_per_sec` | The maximum rate per node at which snapshots are restored. Default is `0` (unlimited). The restore rate is also subject to `indices.recovery.max_bytes_per_sec` (by default, `40mb`). Optional. | +| `max_snapshot_bytes_per_sec` | The maximum rate per node at which snapshots are taken. Default is 40 MB per second (`40mb`). Optional. | +| `readonly` | Whether the repository is read-only. A read-only repository can list and restore snapshots but can't create them. If you register the same repository on multiple clusters, only one cluster should write to it, and all other clusters should register it with `readonly` set to `true`. For more information, see [Sharing a repository between clusters]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#sharing-a-repository-between-clusters). Default is `false`. Optional. | +| `remote_store_index_shallow_copy` | Determines whether the snapshots of the remote store indexes are captured as shallow copies. Default is `false`. +| `s3_async_client_type` | The asynchronous HTTP client that the `repository-s3` plugin uses when it uploads data to this repository. Valid values are `crt` (the AWS Common Runtime client) and `netty` (the Netty NIO client). For more information, see [s3_async_client_type](#s3_async_client_type). Default is `crt`. Optional. | +| `shallow_snapshot_v2` | Determines whether the snapshots of the remote store indexes are captured as a [shallow copy v2]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/snapshot-interoperability/#shallow-snapshot-v2). Default is `false`. +| `storage_class` | Specifies the [S3 storage class](https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html) for the snapshot files. Default is `standard`. Do not use the `glacier` and `deep_archive` storage classes. Optional. | +| `server_side_encryption_type` | Specifies the S3 server-side encryption types. Supported values are `AES256` ([SSE-S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html)), `aws:kms` ([SSE-AWS Key Management Service (KMS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html)), and `bucket_default` ([bucket default encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-encryption.html)). Default is `bucket_default`. | +| `server_side_encryption_kms_key_id` | Specifies the AWS KMS key to be used if [S3 SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html) is selected by setting the `aws:kms` encryption type. Required if `aws:kms` is set as the `server_side_encryption_type`. | +| `server_side_encryption_bucket_key_enabled` | Specifies whether [S3 Bucket Keys](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-key.html) should be used when using [S3 SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html). Optional. | +| `server_side_encryption_encryption_context` | Specifies any additional [encryption context](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#encryption-context) that should be used when using [S3 SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html). This setting value must be formatted as a JSON object. Optional. | +| `expected_bucket_owner` | Specifies the AWS account ID of the expected S3 bucket owner. This setting can be used for [verifying bucket ownership](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-owner-condition.html). Optional. | + +The `server_side_encryption` setting was removed in OpenSearch 3.1.0. S3 applies server-side encryption as the base level of encryption for all S3 buckets. Because this encryption cannot be disabled, the repository setting had no effect. For more information, see [Protecting data with server-side encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html). +{: .note} + + +#### s3_async_client_type + + +`s3_async_client_type` applies to a single repository, so set it in the repository's `settings` block. The `repository-s3` plugin also registers `s3_async_client_type` as a node setting, so a node starts successfully with the setting in `opensearch.yml` and the [Nodes Info API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-info/) returns it, but the plugin reads the value only from the repository definition. A repository that does not set `s3_async_client_type` uses `crt`, even when `opensearch.yml` specifies `netty`. + +If the AWS Common Runtime native library is not available on the node's platform, the plugin logs a warning and uses the Netty client. + +To confirm which client a repository uses, enable `DEBUG` logging for the `org.opensearch.repositories.s3.S3AsyncService` logger and look for the `S3 Http client type` message. + + +### hdfs repository + + +The following table lists the request fields for `hdfs` repositories. + +| Request field | Description | +| :--- | :--- | +| `uri` | The HDFS URI in the `hdfs://:/` format. The URI must not contain a path. Specify the path in the `path` field. Required. | +| `path` | The path within HDFS where you want to store snapshots (for example, `/my/snapshot/directory`). Required. | +| `security.principal` | The Kerberos principal to use when connecting to HDFS. Optional. | +| `conf.` | Additional HDFS client configuration settings (for example, `core-site.xml` or `hdfs-site.xml`). Optional. | + + +### url repository + + +A `url` repository is read-only: you can list and restore snapshots from it, but you can't create snapshots in it. Use a `url` repository to give a cluster read-only access to snapshots that another cluster writes to a shared file system repository. + +The following table lists the request fields for `url` repositories. + +Request field | Description +:--- | :--- +`url` | The URL of the root of the repository. To give read-only access to a shared file system repository, the URL must point to that repository's `location`, not to a parent directory. Supported protocols are `file`, `ftp`, `http`, `https`, and `jar`. A `file` URL must point to a location listed in the `path.repo` setting on all cluster manager and data nodes. An `ftp`, `http`, or `https` URL must match an entry in the `repositories.url.allowed_urls` setting. For more information, see [Node-level repository settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#node-level-repository-settings). Required. + +## Example requests + +The following examples demonstrate how to register different repository types. + + +### fs + + +The following example registers an `fs` repository using the local directory `/mnt/snapshots` as `location`: + + +{% capture step1_rest %} PUT /_snapshot/my-fs-repository { "type": "fs", @@ -60,36 +193,47 @@ PUT /_snapshot/my-fs-repository "location": "/mnt/snapshots" } } -``` -{% include copy-curl.html %} +{% endcapture %} -#### s3 repository +{% capture step1_python %} -Request field | Description -:--- | :--- -`base_path` | The path within the bucket in which you want to store snapshots (for example, `my/snapshot/directory`). Optional. If not specified, snapshots are stored in the S3 bucket root. -`bucket` | Name of the S3 bucket. Required. -`buffer_size` | The threshold beyond which chunks (of `chunk_size`) should be broken into pieces (of `buffer_size`) and sent to S3 using a different API. Default is the smaller of two values: 100 MB or 5% of the Java heap. Valid values are between `5mb` and `5gb`. We don't recommend changing this option. -`canned_acl` | S3 has several [canned ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) that the `repository-s3` plugin can add to objects as it creates them in S3. Default is `private`. Optional. -`chunk_size` | Breaks files into chunks during snapshot operations (e.g. `64mb`, `1gb`), which is important for cloud storage providers and far less important for shared file systems. Default is `1gb`. Optional. -`client` | When specifying client settings (e.g. `s3.client.default.access_key`), you can use a string other than `default` (e.g. `s3.client.backup-role.access_key`). If you used an alternate name, change this value to match. Default and recommended value is `default`. Optional. -`compress` | Whether to compress metadata files. This setting does not affect data files, which might already be compressed, depending on your index settings. Default is `false`. Optional. -`disable_chunked_encoding` | Disables chunked encoding for compatibility with some storage services. Default is `false`. Optional. -`max_restore_bytes_per_sec` | The maximum rate at which snapshots restore. Default is 40 MB per second (`40m`). Optional. -`max_snapshot_bytes_per_sec` | The maximum rate at which snapshots take. Default is 40 MB per second (`40m`). Optional. -`readonly` | Whether the repository is read-only. Useful when migrating from one cluster (`"readonly": false` when registering) to another cluster (`"readonly": true` when registering). Optional. -`remote_store_index_shallow_copy` | Boolean | Whether the snapshot of the remote store indexes is captured as a shallow copy. Default is `false`. -`server_side_encryption` | Whether to encrypt snapshot files in the S3 bucket. This setting uses AES-256 with S3-managed keys. See [Protecting data using server-side encryption](https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html). Default is false. Optional. -`storage_class` | Specifies the [S3 storage class](https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html) for the snapshots files. Default is `standard`. Do not use the `glacier` and `deep_archive` storage classes. Optional. -For the `base_path` parameter, do not enter the `s3://` prefix when entering your S3 bucket details. Only the name of the bucket is required. -{: .note} +response = client.snapshot.create_repository( + repository = "my-fs-repository", + body = { + "type": "fs", + "settings": { + "location": "/mnt/snapshots" + } + } +) -#### Example request +{% endcapture %} -The following request registers a new S3 repository called `my-opensearch-repo` in an existing bucket called `my-open-search-bucket`. By default, all snapshots are stored in the `my/snapshot/directory`. +{% include code-block.html + rest=step1_rest + python=step1_python %} + -```json + +### s3 + + +The following request registers a new S3 repository called `my-opensearch-repo` in an existing bucket called `my-open-search-bucket`. Because the request sets `base_path`, snapshots are stored in the `my/snapshot/directory` path within the bucket: + + +{% capture step1_rest %} PUT /_snapshot/my-opensearch-repo { "type": "s3", @@ -98,10 +242,185 @@ PUT /_snapshot/my-opensearch-repo "base_path": "my/snapshot/directory" } } -``` -{% include copy-curl.html %} +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.snapshot.create_repository( + repository = "my-opensearch-repo", + body = { + "type": "s3", + "settings": { + "bucket": "my-open-search-bucket", + "base_path": "my/snapshot/directory" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The following request registers a new S3 repository called `my-opensearch-repo` in an existing bucket called `my-open-search-bucket`. Because the request sets `base_path`, snapshots are stored in the `my/snapshot/directory` path within the bucket. Additionally, this repository is configured to use [SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#encryption-context), and the expected bucket owner AWS account ID is `123456789000`: + + +{% capture step1_rest %} +PUT /_snapshot/my-opensearch-repo +{ + "type": "s3", + "settings": { + "bucket": "my-open-search-bucket", + "base_path": "my/snapshot/directory", + "server_side_encryption_type": "aws:kms", + "server_side_encryption_kms_key_id": "arn:aws:kms:us-east-1:123456789000:key/kms-key-id", + "server_side_encryption_encryption_context": "{\"additional-enc-ctx\": \"sample-context\"}", + "expected_bucket_owner": "123456789000" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.create_repository( + repository = "my-opensearch-repo", + body = { + "type": "s3", + "settings": { + "bucket": "my-open-search-bucket", + "base_path": "my/snapshot/directory", + "server_side_encryption_type": "aws:kms", + "server_side_encryption_kms_key_id": "arn:aws:kms:us-east-1:123456789000:key/kms-key-id", + "server_side_encryption_encryption_context": "{\"additional-enc-ctx\": \"sample-context\"}", + "expected_bucket_owner": "123456789000" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +### hdfs + + +The following request registers a new HDFS repository using the HDFS URI `hdfs://namenode:8020` and the HDFS file system path `/opensearch/snapshots`: + + +{% capture step1_rest %} +PUT /_snapshot/my-hdfs-repository +{ + "type": "hdfs", + "settings": { + "uri": "hdfs://namenode:8020", + "path": "/opensearch/snapshots" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.create_repository( + repository = "my-hdfs-repository", + body = { + "type": "hdfs", + "settings": { + "uri": "hdfs://namenode:8020", + "path": "/opensearch/snapshots" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +### url + + +The following request registers a read-only `url` repository for the shared file system location `/mnt/snapshots`: + + +{% capture step1_rest %} +PUT /_snapshot/my-url-repository +{ + "type": "url", + "settings": { + "url": "file:/mnt/snapshots" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.create_repository( + repository = "my-url-repository", + body = { + "type": "url", + "settings": { + "url": "file:/mnt/snapshots" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response Upon success, the following JSON object is returned: @@ -111,5 +430,9 @@ Upon success, the following JSON object is returned: } ``` -To verify that the repository was registered, use the [Get snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository) API, passing the repository name as the `repository` path parameter. -{: .note} \ No newline at end of file +To verify that the repository was registered, use the [Get Snapshot Repository API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository/), passing the repository name as the `repository` path parameter. +{: .note} + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/repository/put`. diff --git a/_api-reference/snapshots/create-snapshot.md b/_api-reference/snapshots/create-snapshot.md index 4f0a6d05..52e8a4ea 100644 --- a/_api-reference/snapshots/create-snapshot.md +++ b/_api-reference/snapshots/create-snapshot.md @@ -1,82 +1,166 @@ --- layout: default -title: Create Snapshot +title: Create snapshot parent: Snapshot APIs -nav_order: 5 +nav_order: 50 --- -# Create snapshot +# Create Snapshot API **Introduced 1.0** {: .label .label-purple } -Creates a snapshot within an existing repository. +Creates a snapshot within an existing repository. To view a list of registered repositories, use the [Get Snapshot Repository API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository/). -* To learn more about snapshots, see [Snapshots]({{site.url}}{{site.baseurl}}/opensearch/snapshots/index). +Snapshots are incremental: each snapshot copies only the index files that are not already stored in the repository by an earlier snapshot. Indexing and search requests can continue while a snapshot is in progress. The snapshot contains the data as it existed when the snapshot started, so documents indexed after that point are not included. -* To view a list of your repositories, see [Get snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository). +By default, a snapshot includes all open indexes and data streams in the cluster, including hidden indexes. Closed indexes are included only if you specify them in the `indices` field. -## Path and HTTP methods +## Endpoints ```json -PUT /_snapshot// -POST /_snapshot// +PUT /_snapshot/{repository}/{snapshot} +POST /_snapshot/{repository}/{snapshot} ``` ## Path parameters +The following table lists the available path parameters. + Parameter | Data type | Description :--- | :--- | :--- -repository | String | Repostory name to contain the snapshot. | -snapshot | String | Name of Snapshot to create. | +`repository` | String | The repository name to store the snapshot. +`snapshot` | String | The name of the snapshot to create. + +The snapshot name must be unique in the repository. To include the current date in the name, use a date math expression and URL-encode it. For an example, see [Request using date math in the snapshot name](#request-using-date-math-in-the-snapshot-name). ## Query parameters +The following table lists the available query parameters. All query parameters are optional. + Parameter | Data type | Description :--- | :--- | :--- -wait_for_completion | Boolean | Whether to wait for snapshot creation to complete before continuing. If you include this parameter, the snapshot definition is returned after completion. | +`wait_for_completion` | Boolean | Whether to wait for snapshot creation to complete before continuing. If `true`, the request returns the snapshot definition after the snapshot completes. If `false`, the request returns `{"accepted": true}` when the snapshot starts. In a large repository, the request can take some time to return even when `wait_for_completion` is `false` because OpenSearch loads information about existing snapshots when the snapshot starts. Default is `false`. +`cluster_manager_timeout` | Time | The amount of time to wait for a response from the cluster manager node. Default is `30s`. -## Request fields +## Request body fields -The request body is optional. +The request body is optional. The following table lists the available request body fields. Field | Data type | Description :--- | :--- | :--- -`indices` | String | The indices you want to include in the snapshot. You can use `,` to create a list of indices, `*` to specify an index pattern, and `-` to exclude certain indices. Don't put spaces between items. Default is all indices. -`ignore_unavailable` | Boolean | If an index from the `indices` list doesn't exist, whether to ignore it rather than fail the snapshot. Default is false. -`include_global_state` | Boolean | Whether to include cluster state in the snapshot. Default is true. -`partial` | Boolean | Whether to allow partial snapshots. Default is false, which fails the entire snapshot if one or more shards fails to stor +`indices` | String or Array of strings | The data streams and indexes you want to include in the snapshot. You can use `,` to create a list of indexes, `*` to specify an index pattern, and `-` to exclude certain indexes. Don't put spaces between items. You can also specify the indexes as an array of strings. Default is all indexes. +`ignore_unavailable` | Boolean | If an index from the `indices` list doesn't exist, whether to ignore it rather than fail the snapshot. Default is `false`. +`include_global_state` | Boolean | Whether to include cluster state in the snapshot. The cluster state includes persistent cluster settings, index templates, legacy index templates, and ingest pipelines. Transient cluster settings and registered snapshot repositories are not included. For information about restoring the cluster state, see [Restore Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/restore-snapshot/). Default is `true`. +`partial` | Boolean | Whether to allow partial snapshots. If `false`, the entire snapshot fails if any index in the snapshot does not have all primary shards available. If `true`, OpenSearch takes a snapshot of the available shards, sets the snapshot `state` to `PARTIAL`, and lists the unavailable shards in the `failures` array. Default is `false`. +`metadata` | Object | Custom information to store with the snapshot, such as the user who took the snapshot and the reason for taking it. The metadata is returned by the [Get Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot/). Must be smaller than 1,024 bytes. -#### Example requests +## Example requests -##### Request without a body +The following examples demonstrate how to create a snapshot. + +### Request without a body The following request creates a snapshot called `my-first-snapshot` in an S3 repository called `my-s3-repository`. A request body is not included because it is optional. -```json -POST _snapshot/my-s3-repository/my-first-snapshot -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +POST /_snapshot/my-s3-repository/my-first-snapshot +{% endcapture %} -##### Request with a body +{% capture step1_python %} -You can also add a request body to include or exclude certain indices or specify other settings: -```json -PUT _snapshot/my-s3-repository/2 +response = client.snapshot.create( + repository = "my-s3-repository", + snapshot = "my-first-snapshot" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Request with a body + +You can also add a request body to include or exclude certain indexes or specify other settings. The following request also stores custom information about the snapshot in the `metadata` object: + + +{% capture step1_rest %} +PUT /_snapshot/my-s3-repository/pre-upgrade +{ + "indices": "opensearch_dashboards*,my-index*,-my-index-2016", + "ignore_unavailable": true, + "include_global_state": false, + "partial": false, + "metadata": { + "taken_by": "ops-team", + "reason": "Backup before upgrading to 3.9" + } +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.create( + repository = "my-s3-repository", + snapshot = "pre-upgrade", + body = { + "indices": "opensearch_dashboards*,my-index*,-my-index-2016", + "ignore_unavailable": true, + "include_global_state": false, + "partial": false, + "metadata": { + "taken_by": "ops-team", + "reason": "Backup before upgrading to 3.9" + } + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Request using date math in the snapshot name + +The following request creates a snapshot whose name contains the current date, such as `nightly-2026.10.12`. The non-encoded snapshot name is ``. The `<`, `{`, `/`, `}`, and `>` characters must be URL-encoded in the request path: + +```json +PUT /_snapshot/my-s3-repository/%3Cnightly-%7Bnow%2Fd%7D%3E ``` {% include copy-curl.html %} -#### Example responses +For more information about date math expressions, see [Date math]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#date-math). -Upon success, the response content depends on whether you include the `wait_for_completion` query parameter. +## Example responses -##### `wait_for_completion` not included +Upon success, the response content depends on the value of the `wait_for_completion` query parameter. + + +### wait_for_completion is false + ```json { @@ -84,64 +168,75 @@ Upon success, the response content depends on whether you include the `wait_for_ } ``` -To verify that the snapshot was created, use the [Get snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot) API, passing the snapshot name as the `snapshot` path parameter. +To verify that the snapshot was created, use the [Get Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot/), passing the snapshot name as the `snapshot` path parameter. {: .note} -##### `wait_for_completion` included + +### wait_for_completion is true + -The snapshot definition is returned. +The following response is returned for the [Request with a body](#request-with-a-body) example: ```json { "snapshot" : { - "snapshot" : "5", - "uuid" : "ZRH4Zv7cSnuYev2JpLMJGw", - "version_id" : 136217927, - "version" : "2.0.1", + "snapshot" : "pre-upgrade", + "uuid" : "AsDQXjhOQViYaPzbSo8nJw", + "version_id" : 137307827, + "version" : "3.9.0", + "remote_store_index_shallow_copy" : false, "indices" : [ - ".opendistro-reports-instances", - ".opensearch-observability", - ".kibana_1", + "opensearch_dashboards_sample_data_logs", "opensearch_dashboards_sample_data_flights", - ".opensearch-notifications-config", - ".opendistro-reports-definitions", - "shakespeare" + "opensearch_dashboards_sample_data_ecommerce" ], "data_streams" : [ ], - "include_global_state" : true, + "include_global_state" : false, + "metadata" : { + "taken_by" : "ops-team", + "reason" : "Backup before upgrading to 3.9" + }, "state" : "SUCCESS", - "start_time" : "2022-08-10T16:52:15.277Z", - "start_time_in_millis" : 1660150335277, - "end_time" : "2022-08-10T16:52:18.699Z", - "end_time_in_millis" : 1660150338699, - "duration_in_millis" : 3422, + "start_time" : "2026-10-12T18:33:50.705Z", + "start_time_in_millis" : 1791830030705, + "end_time" : "2026-10-12T18:33:50.906Z", + "end_time_in_millis" : 1791830030906, + "duration_in_millis" : 201, "failures" : [ ], "shards" : { - "total" : 7, + "total" : 3, "failed" : 0, - "successful" : 7 + "successful" : 3 } } } ``` -#### Response fields +## Response body fields + +The following table lists all response body fields. | Field | Data type | Description | -| :--- | :--- | :--- | -| snapshot | string | Snapshot name. | -| uuid | string | Snapshot's universally unique identifier (UUID). | -| version_id | int | Build ID of the Open Search version that created the snapshot. | -| version | float | Open Search version that created the snapshot. | -| indices | array | Indices in the snapshot. | -| data_streams | array | Data streams in the snapshot. | -| include_global_state | boolean | Whether the current cluster state is included in the snapshot. | -| start_time | string | Date/time when the snapshot creation process began. | -| start_time_in_millis | long | Time (in milliseconds) when the snapshot creation process began. | -| end_time | string | Date/time when the snapshot creation process ended. | -| end_time_in_millis | long | Time (in milliseconds) when the snapshot creation process ended. | -| duration_in_millis | long | Total time (in milliseconds) that the snapshot creation process lasted. | -| failures | array | Failures, if any, that occured during snapshot creation. | -| shards | object | Total number of shards created along with number of successful and failed shards. | -| state | string | Snapshot status. Possible values: `IN_PROGRESS`, `SUCCESS`, `FAILED`, `PARTIAL`. | -| remote_store_index_shallow_copy | Boolean | Whether the snapshot of the remote store indexes is captured as a shallow copy. Default is `false`. | \ No newline at end of file +| :--- | :--- | :--- | +| `snapshot` | String | Snapshot name. | +| `uuid` | String | Snapshot's universally unique identifier (UUID). | +| `version_id` | Integer | Build ID of the OpenSearch version that created the snapshot. | +| `version` | String | OpenSearch version that created the snapshot. | +| `indices` | Array | Indexes in the snapshot. | +| `data_streams` | Array | Data streams in the snapshot. | +| `include_global_state` | Boolean | Whether the current cluster state is included in the snapshot. | +| `metadata` | Object | The custom information stored with the snapshot. Returned only if the request included `metadata`. | +| `start_time` | String | The date and time when the snapshot creation process began. | +| `start_time_in_millis` | Long | Time (in milliseconds) when the snapshot creation process began. | +| `end_time` | String | The date and time when the snapshot creation process ended. | +| `end_time_in_millis` | Long | Time (in milliseconds) when the snapshot creation process ended. | +| `duration_in_millis` | Long | Total time (in milliseconds) that the snapshot creation process lasted. | +| `failures` | Array | Failures, if any, that occurred during snapshot creation. | +| `shards` | Object | Total number of shards created along with number of successful and failed shards. | +| `state` | String | Snapshot status. Possible values: `IN_PROGRESS`, `SUCCESS`, `FAILED`, `PARTIAL`. | +| `remote_store_index_shallow_copy` | Boolean | Whether the snapshots of the remote store indexes are captured as shallow copies. Default is `false`. | +| `pinned_timestamp` | Long | A timestamp (in milliseconds) pinned by the snapshot for the implicit locking of remote store files referenced by the snapshot. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/create`. diff --git a/_api-reference/snapshots/delete-snapshot-repository.md b/_api-reference/snapshots/delete-snapshot-repository.md index 385205a5..1115a156 100644 --- a/_api-reference/snapshots/delete-snapshot-repository.md +++ b/_api-reference/snapshots/delete-snapshot-repository.md @@ -1,36 +1,57 @@ --- layout: default -title: Delete Snapshot Repository +title: Delete snapshot repository parent: Snapshot APIs -nav_order: 3 +nav_order: 30 --- -# Delete snapshot repository configuration +# Delete Snapshot Repository API **Introduced 1.0** {: .label .label-purple } - Deletes a snapshot repository configuration. - - A repository in OpenSearch is simply a configuration that maps a repository name to a type (file system or s3 repository) along with other information depending on the type. The configuration is backed by a file system location or an s3 bucket. When you invoke the API, the physical file system or s3 bucket itself is not deleted. Only the configuration is deleted. +Deletes a snapshot repository registration from the cluster. The storage location and the snapshots in it are not deleted. To use the snapshots again, register the repository again using the [Create or Update Snapshot Repository API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-repository/). - To learn more about repositories, see [Register or update snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-repository). +## Endpoints + +```json +DELETE _snapshot/{repository} +``` ## Path parameters +The following table lists the available path parameters. + Parameter | Data type | Description :--- | :--- | :--- -repository | String | Repository to delete. | +`repository` | String | Repository to delete. | -#### Example request +## Example request The following request deletes the `my-opensearch-repo` repository: -````json -DELETE _snapshot/my-opensearch-repo -```` -{% include copy-curl.html %} + +{% capture step1_rest %} +DELETE /_snapshot/my-opensearch-repo +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.snapshot.delete_repository( + repository = "my-opensearch-repo" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response Upon success, the response returns the following JSON object: @@ -40,5 +61,9 @@ Upon success, the response returns the following JSON object: } ```` -To verify that the repository was deleted, use the [Get snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository) API, passing the repository name as the `repository` path parameter. -{: .note} \ No newline at end of file +To verify that the repository was deleted, use the [Get snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository/) API, passing the repository name as the `repository` path parameter. +{: .note} + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/repository/delete`. diff --git a/_api-reference/snapshots/delete-snapshot.md b/_api-reference/snapshots/delete-snapshot.md index e4232c20..23cffbf9 100644 --- a/_api-reference/snapshots/delete-snapshot.md +++ b/_api-reference/snapshots/delete-snapshot.md @@ -1,39 +1,61 @@ --- layout: default -title: Delete Snapshot +title: Delete snapshot parent: Snapshot APIs -nav_order: 7 +nav_order: 70 --- -## Delete snapshot +# Delete Snapshot API **Introduced 1.0** {: .label .label-purple } -Deletes a snapshot from a repository. +Deletes a snapshot from a repository. To view a list of your repositories, use the [CAT Repositories API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-repositories/). To view a list of your snapshots, use the [CAT Snapshots API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-snapshots/). -* To learn more about snapshots, see [Snapshots]({{site.url}}{{site.baseurl}}/opensearch/snapshots/index). +Deleting a snapshot that is in progress stops the snapshot operation and deletes the partially created snapshot. -* To view a list of your repositories, see [cat repositories]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-repositories). +## Endpoints -* To view a list of your snapshots, see [cat snapshots]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-snapshots). +```json +DELETE _snapshot/{repository}/{snapshot} +``` ## Path parameters +The following table lists the available path parameters. + Parameter | Data type | Description :--- | :--- | :--- -repository | String | Repostory that contains the snapshot. | -snapshot | String | Snapshot to delete. | +`repository` | String | Repository that contains the snapshot. | +`snapshot` | String | Snapshot to delete. | -#### Example request +## Example request The following request deletes a snapshot called `my-first-snapshot` from the `my-opensearch-repo` repository: -```json -DELETE _snapshot/my-opensearch-repo/my-first-snapshot -``` -{% include copy-curl.html %} + +{% capture step1_rest %} +DELETE /_snapshot/my-opensearch-repo/my-first-snapshot +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.snapshot.delete( + repository = "my-opensearch-repo", + snapshot = "my-first-snapshot" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response Upon success, the response returns the following JSON object: @@ -43,5 +65,9 @@ Upon success, the response returns the following JSON object: } ``` -To verify that the snapshot was deleted, use the [Get snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot) API, passing the snapshot name as the `snapshot` path parameter. +To verify that the snapshot was deleted, use the [Get snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot/) API, passing the snapshot name as the `snapshot` path parameter. {: .note} + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/delete`. diff --git a/_api-reference/snapshots/get-snapshot-repository.md b/_api-reference/snapshots/get-snapshot-repository.md index e3664e11..d20962df 100644 --- a/_api-reference/snapshots/get-snapshot-repository.md +++ b/_api-reference/snapshots/get-snapshot-repository.md @@ -1,11 +1,11 @@ --- layout: default -title: Get Snapshot Repository +title: Get snapshot repository parent: Snapshot APIs -nav_order: 2 +nav_order: 20 --- -# Get snapshot repository. +# Get Snapshot Repository API **Introduced 1.0** {: .label .label-purple } @@ -16,29 +16,56 @@ To learn more about repositories, see [Register repository]({{site.url}}{{site.b You can also get details about a snapshot during and after snapshot creation. See [Get snapshot status]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-status/). {: .note} +## Endpoints + +```json +GET /_snapshot/{repository} +``` + ## Path parameters +The following table lists the available path parameters. All path parameters are optional. + | Parameter | Data type | Description | | :--- | :--- | :--- | -| repository | String | A comma-separated list of snapshot repository names to retrieve. Wildcard (`*`) expressions are supported including combining wildcards with exclude patterns starting with `-`. | +| `repository` | String | A comma-separated list of snapshot repository names to retrieve. Wildcard (`*`) expressions are supported including combining wildcards with exclude patterns starting with `-`. | ## Query parameters +The following table lists the available query parameters. All query parameters are optional. + | Parameter | Data type | Description | :--- | :--- | :--- -| local | Boolean | Whether to get information from the local node. Optional, defaults to `false`.| -| cluster_manager_timeout | Time | Amount of time to wait for a connection to the master node. Optional, defaults to 30 seconds. | +| `local` | Boolean | Whether to get information from the local node. Optional, defaults to `false`.| +| `cluster_manager_timeout` | Time | Amount of time to wait for a connection to the cluster manager node. Optional, defaults to 30 seconds. | -#### Example request +## Example request The following request retrieves information for the `my-opensearch-repo` repository: -````json + +{% capture step1_rest %} GET /_snapshot/my-opensearch-repo -```` -{% include copy-curl.html %} +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.snapshot.get_repository( + repository = "my-opensearch-repo" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response Upon success, the response returns repositry information. This sample is for an `s3` repository type. @@ -54,10 +81,16 @@ Upon success, the response returns repositry information. This sample is for an } ```` -## Response fields +## Response body fields + +The following table lists all response body fields. | Field | Data type | Description | | :--- | :--- | :--- | -| type | string | Bucket type: `fs` (file system) or `s3` (s3 bucket) | -| bucket | string | S3 bucket name. | -| base_path | string | Folder within the bucket where snapshots are stored. | \ No newline at end of file +| `type` | String | Bucket type: `fs` (file system) or `s3` (s3 bucket) | +| `bucket` | String | S3 bucket name. | +| `base_path` | String | Folder within the bucket where snapshots are stored. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/repository/get`. diff --git a/_api-reference/snapshots/get-snapshot-status.md b/_api-reference/snapshots/get-snapshot-status.md index 02aa4190..30e75a72 100644 --- a/_api-reference/snapshots/get-snapshot-status.md +++ b/_api-reference/snapshots/get-snapshot-status.md @@ -1,62 +1,101 @@ --- layout: default -title: Get Snapshot Status +title: Get snapshot status parent: Snapshot APIs -nav_order: 8 +nav_order: 80 --- -# Get snapshot status +# Get Snapshot Status API **Introduced 1.0** {: .label .label-purple } Returns details about a snapshot’s state during and after snapshot creation. -To learn about snapshot creation, see [Create snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-snapshot). +To learn about snapshot creation, see [Create snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-snapshot/). If you use the Security plugin, you must have the `monitor_snapshot`, `create_snapshot`, or `manage cluster` privileges. {: .note} +## Endpoints + +```json +GET _snapshot/{repository}/{snapshot}/_status +``` + ## Path parameters -Path parameters are optional. +The following table lists the available path parameters. All path parameters are optional. | Parameter | Data type | Description | :--- | :--- | :--- -| repository | String | Repository containing the snapshot. | -| snapshot | String | Snapshot to return. | +| `repository` | String | The repository containing the snapshot. | +| `snapshot` | List | The snapshot(s) to return. | +| `index` | List | The indexes to include in the response. | Three request variants provide flexibility: * `GET _snapshot/_status` returns the status of all currently running snapshots in all repositories. -* `GET _snapshot//_status` returns the status of only currently running snapshots in the specified repository. This is the preferred variant. +* `GET _snapshot//_status` returns all currently running snapshots in the specified repository. This is the preferred variant. -* `GET _snapshot///_status` returns the status of all snapshots in the specified repository whether they are running or not. +* `GET _snapshot///_status` returns detailed status information for a specific snapshot(s) in the specified repository, regardless of whether it's currently running. -Using the API to return state for other than currently running snapshots can be very costly for (1) machine machine resources and (2) processing time if running in the cloud. For each snapshot, each request causes file reads from all a snapshot's shards. +* `GET /_snapshot////_status` returns detailed status information only for the specified indexes in a specific snapshot in the specified repository. Note that this endpoint works only for indexes belonging to a specific snapshot. + +Snapshot API calls only work if the total number of shards across the requested resources, such as snapshots and indexes created from snapshots, is smaller than the limit specified by the following cluster setting: + +- `snapshot.max_shards_allowed_in_status_api`(Dynamic, integer): The maximum number of shards that can be included in the Snapshot Status API response. Default value is `200000`. Not applicable for [shallow snapshots v2]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/snapshot-interoperability##shallow-snapshot-v2), where the total number and sizes of files are returned as 0. + + +Using the API to return the state of snapshots that are not currently running can be very costly in terms of both machine resources and processing time when querying data in the cloud. For each snapshot, each request causes a file read of all of the snapshot's shards. {: .warning} -## Request fields +## Request body fields + +The following table lists the available request body fields. All request body fields are optional. | Field | Data type | Description | :--- | :--- | :--- -| ignore_unavailable | Boolean | How to handles requests for unavailable snapshots. If `false`, the request returns an error for unavailable snapshots. If `true`, the request ignores unavailable snapshots, such as those that are corrupted or temporarily cannot be returned. Defaults to `false`.| +| `ignore_unavailable` | Boolean | How to handle requests for unavailable snapshots and indexes. If `false`, the request returns an error for unavailable snapshots and indexes. If `true`, the request ignores unavailable snapshots and indexes, such as those that are corrupted or temporarily cannot be returned. Default is `false`.| -#### Example request +## Example request The following request returns the status of `my-first-snapshot` in the `my-opensearch-repo` repository. Unavailable snapshots are ignored. -````json -GET _snapshot/my-opensearch-repo/my-first-snapshot/_status + +{% capture step1_rest %} +GET /_snapshot/my-opensearch-repo/my-first-snapshot/_status +{ + "ignore_unavailable": true +} +{% endcapture %} -#### Example response +{% capture step1_python %} -The example that follows corresponds to the request above in the [Example request](#example-request) section. + +response = client.snapshot.status( + repository = "my-opensearch-repo", + snapshot = "my-first-snapshot" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +## Example response + +The following example corresponds to the preceding [Example request](#example-request). The `GET _snapshot/my-opensearch-repo/my-first-snapshot/_status` request returns the following fields: @@ -369,55 +408,67 @@ The `GET _snapshot/my-opensearch-repo/my-first-snapshot/_status` request returns } ```` -## Response fields +## Response body fields + +The following table lists all response body fields. | Field | Data type | Description | :--- | :--- | :--- -| repository | String | Name of repository that contains the snapshot. | -| snapshot | String | Snapshot name. | -| uuid | String | Snapshot Universally unique identifier (UUID). | -| state | String | Snapshot's current status. See [Snapshot states](#snapshot-states). | -| include_global_state | Boolean | Whether the current cluster state is included in the snapshot. | -| shards_stats | Object | Snapshot's shard counts. See [Shard stats](#shard-stats). | -| stats | Object | Details of files included in the snapshot. `file_count`: number of files. `size_in_bytes`: total of all fie sizes. See [Snapshot file stats](#snapshot-file-stats). | -| index | list of Objects | List of objects that contain information about the indices in the snapshot. See [Index objects](#index-objects).| +| `repository` | String | Name of repository that contains the snapshot. | +| `snapshot` | String | Snapshot name. | +| `uuid` | String | A snapshot's universally unique identifier (UUID). | +| `state` | String | Snapshot's current status. See [Snapshot states](#snapshot-states). | +| `include_global_state` | Boolean | Whether the current cluster state is included in the snapshot. | +| `shards_stats` | Object | Snapshot's shard counts. See [Shard stats](#shard-stats). | +| `stats` | Object | Information about files included in the snapshot. `file_count`: number of files. `size_in_bytes`: total size of all files. See [Snapshot file stats](#snapshot-file-stats). | +| `index` | List of Objects | List of objects that contain information about the indexes in the snapshot. See [Index objects](#index-objects).| -##### Snapshot states +### Snapshot states + +The following table lists the snapshot states. | State | Description | :--- | :--- | -| FAILED | The snapshot terminated in an error and no data was stored. | -| IN_PROGRESS | The snapshot is currently running. | -| PARTIAL | The global cluster state was stored, but data from at least one shard was not stored. The `failures` property of the [Create snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-snapshot) response contains additional details. | -| SUCCESS | The snapshot finished and all shards were stored successfully. | +| `FAILED` | The snapshot terminated in an error and no data was stored. | +| `IN_PROGRESS` | The snapshot is currently running. | +| `PARTIAL` | The global cluster state was stored, but data from at least one shard was not stored. The `failures` property of the [Create snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-snapshot/) response contains additional details. | +| `SUCCESS` | The snapshot finished and all shards were stored successfully. | -##### Shard stats +### Shard stats -All property values are Integers. +The following table lists the shard stats properties. All property values are integers. | Property | Description | :--- | :--- | -| initializing | Number of shards that are still initializing. | -| started | Number of shards that have started but not are not finalized. | -| finalizing | Number of shards that are finalizing but are not done. | -| done | Number of shards that initialized, started, and finalized successfully. | -| failed | Number of shards that failed to be included in the snapshot. | -| total | Total number of shards included in the snapshot. | +| `initializing` | Number of shards that are still initializing. | +| `started` | Number of shards that have started but not are not finalized. | +| `finalizing` | Number of shards that are finalizing but are not done. | +| `done` | Number of shards that initialized, started, and finalized successfully. | +| `failed` | Number of shards that failed to be included in the snapshot. | +| `total` | Total number of shards included in the snapshot. | -##### Snapshot file stats +### Snapshot file stats + +The following table lists the snapshot file stats properties. | Property | Type | Description | :--- | :--- | :--- | -| incremental | Object | Number and size of files that still need to be copied during snapshot creation. For completed snapshots, `incremental` provides the number and size of files that were not already in the repository and were copied as part of the incremental snapshot. | -| processed | Object | Number and size of files already uploaded to the snapshot. The processed `file_count` and `size_in_bytes` are incremented in stats after a file is uploaded. | -| total | Object | Total number and size of files that are referenced by the snapshot. | -| start_time_in_millis | Long | Time (in milliseconds) when snapshot creation began. | -| time_in_millis | Long | Total time (in milliseconds) that the snapshot took to complete. | +| `incremental` | Object | Number and size of files that still need to be copied during snapshot creation. For completed snapshots, `incremental` provides the number and size of files that were not already in the repository and were copied as part of the incremental snapshot. | +| `processed` | Object | Number and size of files already uploaded to the snapshot. The processed `file_count` and `size_in_bytes` are incremented in stats after a file is uploaded. | +| `total` | Object | Total number and size of files that are referenced by the snapshot. | +| `start_time_in_millis` | Long | Time (in milliseconds) when snapshot creation began. | +| `time_in_millis` | Long | Total time (in milliseconds) that the snapshot took to complete. | -##### Index objects +### Index objects + +The following table lists the index object properties. | Property | Type | Description | :--- | :--- | :--- | -| shards_stats | Object | See [Shard stats](#shard-stats). | -| stats | Object | See [Snapshot file stats](#snapshot-file-stats). | -| shards | list of Objects | List of objects containing information about the shards that include the snapshot. Properies of the shards are listed below in bold text.

**stage**: Current state of shards in the snapshot. Shard states are:

* DONE: Number of shards in the snapshot that were successfully stored in the repository.

* FAILURE: Number of shards in the snapshot that were not successfully stored in the repository.

* FINALIZE: Number of shards in the snapshot that are in the finalizing stage of being stored in the repository.

* INIT: Number of shards in the snapshot that are in the initializing stage of being stored in the repository.

* STARTED: Number of shards in the snapshot that are in the started stage of being stored in the repository.

**stats**: See [Snapshot file stats](#snapshot-file-stats).

**total**: Total number and size of files referenced by the snapshot.

**start_time_in_millis**: Time (in milliseconds) when snapshot creation began.

**time_in_millis**: Total time (in milliseconds) that the snapshot took to complete. | \ No newline at end of file +| `shards_stats` | Object | See [Shard stats](#shard-stats). | +| `stats` | Object | See [Snapshot file stats](#snapshot-file-stats). | +| `shards` | List of objects | Contains information about the shards included in the snapshot. OpenSearch returns the following properties about the shard:

**stage**: The current state of shards in the snapshot. Shard states are:

* DONE: The number of shards in the snapshot that were successfully stored in the repository.

* FAILURE: The number of shards in the snapshot that were not successfully stored in the repository.

* FINALIZE: The number of shards in the snapshot that are in the finalizing stage of being stored in the repository.

* INIT: The number of shards in the snapshot that are in the initializing stage of being stored in the repository.

* STARTED: The number of shards in the snapshot that are in the started stage of being stored in the repository.

**stats**: See [Snapshot file stats](#snapshot-file-stats).

**total**: The total number and sizes of files referenced by the snapshot.

**start_time_in_millis**: The time (in milliseconds) when snapshot creation began.

**time_in_millis**: The total amount of time (in milliseconds) that the snapshot took to complete. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/status` and `cluster:admin/snapshot/status*`. diff --git a/_api-reference/snapshots/get-snapshot.md b/_api-reference/snapshots/get-snapshot.md index da44c1f2..b2c07c42 100644 --- a/_api-reference/snapshots/get-snapshot.md +++ b/_api-reference/snapshots/get-snapshot.md @@ -1,40 +1,68 @@ --- layout: default -title: Get Snapshot +title: Get snapshot parent: Snapshot APIs -nav_order: 6 +nav_order: 60 --- -# Get snapshot. +# Get Snapshot API **Introduced 1.0** {: .label .label-purple } Retrieves information about a snapshot. +## Endpoints + +```json +GET _snapshot/{repository}/{snapshot}/ +``` + ## Path parameters +The following table lists the available path parameters. + | Parameter | Data type | Description | | :--- | :--- | :--- | -| repository | String | The repository that contains the snapshot to retrieve. | -| snapshot | String | Snapshot to retrieve. +| `repository` | String | The repository that contains the snapshot to retrieve. | +| `snapshot` | String | Snapshot to retrieve. ## Query parameters +The following table lists the available query parameters. All query parameters are optional. + | Parameter | Data type | Description | :--- | :--- | :--- -| verbose | Boolean | Whether to show all, or just basic snapshot information. If `true`, returns all information. If `false`, omits information like start/end times, failures, and shards. Optional, defaults to `true`.| -| ignore_unavailable | Boolean | How to handle snapshots that are unavailable (corrupted or otherwise temporarily can't be returned). If `true` and the snapshot is unavailable, the request does not return the snapshot. If `false` and the snapshot is unavailable, the request returns an error. Optional, defaults to `false`.| +| `verbose` | Boolean | When `true`, returns additional information about each snapshot, such as the version of OpenSearch that took the snapshot, the start and end times of the snapshot, and the number of shards contained in the snapshot. When `false`, returns only snapshot names and contained indexes. This is useful when the snapshots belong to a cloud-based repository, where each blob read is a cost or performance concern. Optional. Default is `true`.| +| `ignore_unavailable` | Boolean | How to handle snapshots that are unavailable (corrupted or otherwise temporarily can't be returned). If `true` and the snapshot is unavailable, the request does not return the snapshot. If `false` and the snapshot is unavailable, the request returns an error. Optional. Default is `false`.| -#### Example request +## Example request The following request retrieves information for the `my-first-snapshot` located in the `my-opensearch-repo` repository: -````json -GET _snapshot/my-opensearch-repo/my-first-snapshot -```` -{% include copy-curl.html %} + +{% capture step1_rest %} +GET /_snapshot/my-opensearch-repo/my-first-snapshot +{% endcapture %} -#### Example response +{% capture step1_python %} + + +response = client.snapshot.get( + repository = "my-opensearch-repo", + snapshot = "my-first-snapshot" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response Upon success, the response returns snapshot information: @@ -73,22 +101,29 @@ Upon success, the response returns snapshot information: ] } ```` -## Response fields + +## Response body fields + +The following table lists all response body fields. | Field | Data type | Description | | :--- | :--- | :--- | -| snapshot | string | Snapshot name. | -| uuid | string | Snapshot's universally unique identifier (UUID). | -| version_id | int | Build ID of the Open Search version that created the snapshot. | -| version | float | Open Search version that created the snapshot. | -| indices | array | Indices in the snapshot. | -| data_streams | array | Data streams in the snapshot. | -| include_global_state | boolean | Whether the current cluster state is included in the snapshot. | -| start_time | string | Date/time when the snapshot creation process began. | -| start_time_in_millis | long | Time (in milliseconds) when the snapshot creation process began. | -| end_time | string | Date/time when the snapshot creation process ended. | -| end_time_in_millis | long | Time (in milliseconds) when the snapshot creation process ended. | -| duration_in_millis | long | Total time (in milliseconds) that the snapshot creation process lasted. | -| failures | array | Failures, if any, that occured during snapshot creation. | -| shards | object | Total number of shards created along with number of successful and failed shards. | -| state | string | Snapshot status. Possible values: `IN_PROGRESS`, `SUCCESS`, `FAILED`, `PARTIAL`. | \ No newline at end of file +| `snapshot` | String | Snapshot name. | +| `uuid` | String | Snapshot's universally unique identifier (UUID). | +| `version_id` | Integer | Build ID of the Open Search version that created the snapshot. | +| `version` | Float | Open Search version that created the snapshot. | +| `indices` | Array | Indices in the snapshot. | +| `data_streams` | Array | Data streams in the snapshot. | +| `include_global_state` | Boolean | Whether the current cluster state is included in the snapshot. | +| `start_time` | String | Date/time when the snapshot creation process began. | +| `start_time_in_millis` | Long | Time (in milliseconds) when the snapshot creation process began. | +| `end_time` | String | Date/time when the snapshot creation process ended. | +| `end_time_in_millis` | Long | Time (in milliseconds) when the snapshot creation process ended. | +| `duration_in_millis` | Long | Total time (in milliseconds) that the snapshot creation process lasted. | +| `failures` | Array | Failures, if any, that occurred during snapshot creation. | +| `shards` | Object | Total number of shards created along with number of successful and failed shards. | +| `state` | String | Snapshot status. Possible values: `IN_PROGRESS`, `SUCCESS`, `FAILED`, `PARTIAL`. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/get`. diff --git a/_api-reference/snapshots/index.md b/_api-reference/snapshots/index.md index e341905a..55841fab 100644 --- a/_api-reference/snapshots/index.md +++ b/_api-reference/snapshots/index.md @@ -2,14 +2,34 @@ layout: default title: Snapshot APIs has_children: true -nav_order: 80 +has_toc: false +nav_order: 120 redirect_from: - - /opensearch/rest-api/document-apis/ - /opensearch/rest-api/snapshots/ + - /api-reference/snapshots/ --- # Snapshot APIs **Introduced 1.0** {: .label .label-purple } -The snapshot APIs allow you to manage snapshots and snapshot repositories. \ No newline at end of file +The snapshot APIs allow you to manage snapshots and snapshot repositories. For information about registering repositories and taking and restoring snapshots, see [Snapshots]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/index/). + +## Snapshot API operations + +The following snapshot API operations are available. + +### Repository management +- [Create repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-repository/) +- [Get snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-repository/) +- [Delete snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/delete-snapshot-repository/) +- [Verify snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/verify-snapshot-repository/) +- [Cleanup snapshot repository]({{site.url}}{{site.baseurl}}/api-reference/snapshots/cleanup-snapshot-repository/) + +### Snapshot management +- [Create snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/create-snapshot/) +- [Get snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot/) +- [Get snapshot status]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot-status/) +- [Delete snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/delete-snapshot/) +- [Clone snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/clone-snapshot/) +- [Restore snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/restore-snapshot/) diff --git a/_api-reference/snapshots/restore-snapshot.md b/_api-reference/snapshots/restore-snapshot.md index 7b82f722..086a1a51 100644 --- a/_api-reference/snapshots/restore-snapshot.md +++ b/_api-reference/snapshots/restore-snapshot.md @@ -1,120 +1,290 @@ --- layout: default -title: Restore Snapshot +title: Restore snapshot parent: Snapshot APIs - -nav_order: 9 +nav_order: 90 --- -# Restore Snapshot +# Restore Snapshot API **Introduced 1.0** {: .label .label-purple } -Restores a snapshot of a cluster or specified data streams and indices. +Restores a snapshot of a cluster or specified data streams and indexes. -* For information about indices and clusters, see [Introduction to OpenSearch]({{site.url}}{{site.baseurl}}/opensearch/index). - -* For information about data streams, see [Data streams]({{site.url}}{{site.baseurl}}/opensearch/data-streams). - -If open indexes with the same name that you want to restore already exist in the cluster, you must close, delete, or rename the indexes. See [Example request](#example-request) for information about renaming an index. See [Close index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/close-index) for information about closing an index. +If open indexes with the same name that you want to restore already exist in the cluster, you must close, delete, or rename the indexes. You can restore over a closed index only if it has the same number of shards as the index in the snapshot; the restore operation reopens the index. For information about renaming an index, see [Example requests](#example-requests). For information about closing an index, see [Close index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/close-index/). To restore a snapshot to a different cluster, see [Restoring to a different cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#restoring-a-snapshot-to-a-different-cluster). For more information about avoiding conflicts, see [Conflicts and compatibility]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#conflicts-and-compatibility). {: .note} +## Endpoints + +```json +POST _snapshot/{repository}/{snapshot}/_restore +``` + ## Path parameters +The following table lists the available path parameters. + | Parameter | Data type | Description | -:--- | :--- | :--- -repository | String | Repository containing the snapshot to restore. | -| snapshot | String | Snapshot to restore. | +| :--- | :--- | :--- | +| `repository` | String | Repository containing the snapshot to restore. | +| `snapshot` | String | Snapshot to restore. | ## Query parameters -Parameter | Data type | Description -:--- | :--- | :--- -wait_for_completion | Boolean | Whether to wait for snapshot restoration to complete before continuing. | - -### Request fields - -All request body parameters are optional. +The following table lists the available query parameters. All query parameters are optional. | Parameter | Data type | Description | -:--- | :--- | :--- -| ignore_unavailable | Boolean | How to handle data streams or indices that are missing or closed. If `false`, the request returns an error for any data stream or index that is missing or closed. If `true`, the request ignores data streams and indices in indices that are missing or closed. Defaults to `false`. | -| ignore_index_settings | Boolean | A comma-delimited list of index settings that you don't want to restore from a snapshot. | -| include_aliases | Boolean | How to handle index aliases from the original snapshot. If `true`, index aliases from the original snapshot are restored. If `false`, aliases along with associated indices are not restored. Defaults to `true`. | -| include_global_state | Boolean | Whether to restore the current cluster state1. If `false`, the cluster state is not restored. If true, the current cluster state is restored. Defaults to `false`.| -| index_settings | String | A comma-delimited list of settings to add or change in all restored indices. Use this parameter to override index settings during snapshot restoration. For data streams, these index settings are applied to the restored backing indices. | -| indices | String | A comma-delimited list of data streams and indices to restore from the snapshot. Multi-index syntax is supported. By default, a restore operation includes all data streams and indices in the snapshot. If this argument is provided, the restore operation only includes the data streams and indices that you specify. | -| partial | Boolean | How the restore operation will behave if indices in the snapshot do not have all primary shards available. If `false`, the entire restore operation fails if any indices in the snapshot do not have all primary shards available.

If `true`, allows the restoration of a partial snapshot of indices with unavailable shards. Only shards that were successfully included in the snapshot are restored. All missing shards are recreated as empty. By default, the entire restore operation fails if one or more indices included in the snapshot do not have all primary shards available. To change this behavior, set `partial` to `true`. Defaults to `false`. | -| rename_pattern | String | The pattern to apply to restored data streams and indices. Data streams and indices matching the rename pattern will be renamed according to `rename_replacement`.

The rename pattern is applied as defined by the regular expression that supports referencing the original text.

The request fails if two or more data streams or indices are renamed into the same name. If you rename a restored data stream, its backing indices are also renamed. For example, if you rename the logs data stream to `recovered-logs`, the backing index `.ds-logs-1` is renamed to `.ds-recovered-logs-1`.

If you rename a restored stream, ensure an index template matches the new stream name. If there are no matching index template names, the stream cannot roll over and new backing indices are not created.| -| rename_replacement | String | The rename replacement string. See `rename_pattern` for more information.| -| source_remote_store_repository | String | The name of the remote store repository of the source index being restored. If not provided, the Snapshot Restore API will use the repository that was registered when the snapshot was created. -| wait_for_completion | Boolean | Whether to return a response after the restore operation has completed. If `false`, the request returns a response when the restore operation initializes. If `true`, the request returns a response when the restore operation completes. Defaults to `false`. | +| :--- | :--- | :--- | +| `wait_for_completion` | Boolean | Whether to wait for the restore operation to complete before returning a response. If `false`, the request returns `{"accepted": true}` when the restore operation starts. If `true`, the request returns a response containing the restored indexes and shard counts after the restore operation completes. Default is `false`. | -1The cluster state includes: +## Request body fields + +The following table lists the available request body fields. All request body fields are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `attach_to_data_stream` (Experimental) | Boolean | Whether to attach a restored backing index to a pre-existing data stream of the same name. When `true`, a restored index whose name matches the `.ds--NNNNNN` backing index convention is attached to a pre-existing data stream of the same name as part of the restore operation, advancing the stream generation as needed. The attached index must map the data stream's timestamp field as a `date`. When `false`, the index is restored as a standalone index. Default is `false`. See [Attach a restored backing index to a data stream](#attach-a-restored-backing-index-to-a-data-stream).| +| `ignore_unavailable` | Boolean | How to handle data streams or indexes that are missing or closed. If `false`, the request returns an error for any data stream or index that is missing or closed. If `true`, the request ignores data streams and indexes that are missing or closed. Defaults to `false`. | +| `ignore_index_settings` | String or Array of strings | The index settings to exclude when restoring from a snapshot. Excluded settings are reset to their default values. Specify a comma-separated string or an array of strings. Some settings, such as `index.number_of_replicas`, can't be excluded. To change them, use `index_settings`. | +| `include_aliases` | Boolean | How to handle index aliases from the original snapshot. If `true`, index aliases from the original snapshot are restored. If `false`, the indexes are restored without their aliases. Defaults to `true`. | +| `include_global_state` | Boolean | Whether to restore the cluster state stored in the snapshot1. When `true`, items in the snapshot's cluster state replace existing items with the same names. Default is `false`.| +| `index_settings` | Object | An object containing the settings to add or change in all restored indexes, for example, `{"index.number_of_replicas": 0}`. Use this parameter to override index settings during snapshot restoration. For data streams, these index settings are applied to the restored backing indexes. Some settings, such as `index.number_of_shards`, can't be changed during a restore. | +| `indices` | String | A comma-delimited list of data streams and indexes to restore from the snapshot. Multi-index syntax is supported. By default, a restore operation includes all data streams and indexes in the snapshot. If this argument is provided, the restore operation only includes the data streams and indexes that you specify. | +| `partial` | Boolean | How the restore operation will behave if indexes in the snapshot do not have all primary shards available. If `false`, the entire restore operation fails if any indexes in the snapshot do not have all primary shards available.

If `true`, allows the restoration of a partial snapshot of indexes with unavailable shards. Only shards that were successfully included in the snapshot are restored. All missing shards are recreated as empty. Defaults to `false`. | +| `rename_pattern` | String | The pattern to apply to the restored data streams and indexes. Data streams and indexes matching the rename pattern will be renamed according to the `rename_replacement` setting.

The rename pattern is a regular expression. In `rename_replacement`, use `$1`, `$2`, and so on to reference the groups captured by the pattern, as described in the [Java `Matcher` documentation](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuilder,java.lang.String)).

The request fails if two or more data streams or indexes are renamed to the same name. If you rename a restored data stream, its backing indexes are also renamed. For example, if you rename the logs data stream to `recovered-logs`, the backing index `.ds-logs-1` is renamed to `.ds-recovered-logs-1`.

If you rename a restored stream, ensure an index template matches the new stream name. If there are no matching index template names, the stream cannot roll over, and new backing indexes are not created.| +| `rename_replacement` | String | The rename replacement string.| +| `rename_alias_pattern` | String | The pattern to apply to the restored aliases. Aliases matching the rename pattern will be renamed according to the `rename_alias_replacement` setting.

The rename pattern is a regular expression. In `rename_alias_replacement`, use `$1`, `$2`, and so on to reference the groups captured by the pattern.

If two or more aliases are renamed to the same name, these aliases will be merged into one.| +| `rename_alias_replacement` | String | The rename replacement string for aliases.| +| `source_remote_store_repository` | String | The name of the remote segment repository of the source index being restored. Required only when both source and target clusters use remote-backed storage and have different remote store repositories. The specified repository must be registered as read-only on the target cluster before restoring. If not provided, the Snapshot Restore API will use the repositories that were registered when the snapshot was created. | +| `source_remote_translog_repository` | String | The name of the remote translog repository of the source index being restored. Required only when both source and target clusters use remote-backed storage and have different remote store repositories. The specified repository must be registered as read-only on the target cluster before restoring. | +| `storage_type` | String | Where the restored index data is stored. Valid values are:
- `local`: All index data and snapshot metadata are downloaded to local storage.
- `remote_snapshot`: Snapshot metadata is downloaded to the cluster, but the remote repository remains the authoritative store of the index data. Data is downloaded and cached as necessary to service queries. At least one node in the cluster must have the [`warm` role]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/searchable_snapshot/#configuring-a-node-to-use-searchable-snapshots) in order to restore a snapshot using the type `remote_snapshot`.

Default is `local`. | + +1The cluster state includes the following items. When you restore the cluster state, these items replace existing items with the same names in the cluster: * Persistent cluster settings * Index templates * Legacy index templates * Ingest pipelines -* Index lifecycle policies -#### Example request +Index State Management (ISM) policies are stored in an index, not in the cluster state, so they are not restored with the cluster state. -The following request restores the `opendistro-reports-definitions` index from `my-first-snapshot`. The `rename_pattern` and `rename_replacement` combination causes the index to be renamed to `opendistro-reports-definitions_restored` because duplicate open index names in a cluster are not allowed. +## Example requests -````json -POST /_snapshot/my-opensearch-repo/my-first-snapshot/_restore +The following examples demonstrate different snapshot restore scenarios. + +### Basic restore + +The following request restores the `restore-test` index from `my-first-snapshot`. The `rename_pattern` and `rename_replacement` combination causes the index to be renamed to `restore-test_restored` because duplicate open index names in a cluster are not allowed. + + +{% capture step1_rest %} +POST /_snapshot/my-opensearch-repo/my-first-snapshot/_restore { - "snapshot" : { - "snapshot" : "my-first-snapshot", - "indices" : [ ], - "shards" : { - "total" : 0, - "failed" : 0, - "successful" : 0 + "indices": "restore-test", + "ignore_unavailable": true, + "include_global_state": false, + "rename_pattern": "(.+)", + "rename_replacement": "$1_restored", + "include_aliases": false +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.restore( + repository = "my-opensearch-repo", + snapshot = "my-first-snapshot", + body = { + "indices": "restore-test", + "ignore_unavailable": true, + "include_global_state": false, + "rename_pattern": "(.+)", + "rename_replacement": "$1_restored", + "include_aliases": false + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Change index settings during restore + +The following request restores the `restore-test` index under the name `restore-test-settings`, sets the number of replicas to `0`, and resets the `index.refresh_interval` setting to its default value. Reducing the number of replicas is useful when you restore a snapshot to a smaller cluster: + +```json +POST /_snapshot/my-opensearch-repo/my-first-snapshot/_restore?wait_for_completion=true +{ + "indices": "restore-test", + "rename_pattern": "(.+)", + "rename_replacement": "$1-settings", + "index_settings": { + "index.number_of_replicas": 0 + }, + "ignore_index_settings": [ + "index.refresh_interval" + ] +} +``` +{% include copy-curl.html %} + +### Cross-cluster restore with remote-backed storage + +Remote-backed storage is a feature where OpenSearch automatically backs up segments and translogs to remote repositories. When restoring snapshots between clusters that **both use remote-backed storage** with different remote store repositories, use both the `source_remote_store_repository` and `source_remote_translog_repository` parameters. + +The following example restores an index from a snapshot taken on a source cluster to a target cluster. In this example, `source-cluster-snapshots` is the snapshot repository containing the snapshot from the source cluster, `snapshot-1` is the snapshot name, `my-remote-index` is the index to restore, `source-remote-segment-repo` is the remote segment repository from the source cluster (must be registered as read-only on the target cluster), and `source-remote-translog-repo` is the remote translog repository from the source cluster (must be registered as read-only on the target cluster): + + +{% capture step1_rest %} +POST /_snapshot/source-cluster-snapshots/snapshot-1/_restore +{ + "indices": "my-remote-index", + "source_remote_store_repository": "source-remote-segment-repo", + "source_remote_translog_repository": "source-remote-translog-repo" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.snapshot.restore( + repository = "source-cluster-snapshots", + snapshot = "snapshot-1", + body = { + "indices": "my-remote-index", + "source_remote_store_repository": "source-remote-segment-repo", + "source_remote_translog_repository": "source-remote-translog-repo" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +The target cluster will restore the index and configure it to read remote segments and translogs from the source cluster's remote store repositories. + +For the complete step-by-step procedure, see [Restoring snapshots across remote-backed clusters]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#restoring-snapshots-across-remote-backed-clusters). + +### Attach a restored backing index to a data stream +**Introduced 3.8** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/8271). +{: .warning} + +To attach a restored backing index to a pre-existing data stream with the same name, set `attach_to_data_stream` to `true`. The restored index name must match the `.ds--NNNNNN` backing index convention, and the index must map the stream's timestamp field as a `date`. The following request restores the `.ds-logs-foo-000001` backing index and attaches it to the existing `logs-foo` data stream, advancing the stream generation as needed: + +```json +POST /_snapshot/my-opensearch-repo/my-first-snapshot/_restore +{ + "indices": ".ds-logs-foo-000001", + "attach_to_data_stream": true +} +``` +{% include copy-curl.html %} + +To add or remove backing indexes of a data stream without restoring an index from a snapshot, use the [Modify Data Stream API]({{site.url}}{{site.baseurl}}/api-reference/data-stream/modify-data-stream/). + +## Example response + +By default, the request returns the following response when the restore operation starts: + +```json +{ + "accepted": true +} +``` + +If you set `wait_for_completion` to `true`, the request returns a response after the restore operation completes. The following response is returned for the [Change index settings during restore](#change-index-settings-during-restore) example: + +```json +{ + "snapshot": { + "snapshot": "my-first-snapshot", + "indices": [ + "restore-test-settings" + ], + "shards": { + "total": 1, + "failed": 0, + "successful": 1 } } } -```` -Except for the snapshot name, all properties are empty or `0`. This is because any changes made to the volume after the snapshot was generated are lost. However, if you invoke the [Get snapshot]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot) API to examine the snapshot, a fully populated snapshot object is returned. +``` -## Response fields +To view the full snapshot details, such as all of the indexes it contains, use the [Get Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot/). + +To monitor the progress of a restore operation, use the [CAT Recovery API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/). Shards being restored from a snapshot have the recovery type `snapshot`: + +```json +GET _cat/recovery/restore-test-settings?v&h=index,shard,type,stage,snapshot,repository,files_percent,bytes_percent +``` +{% include copy-curl.html %} + +The response shows the snapshot and repository from which each shard is restored and the percentage of files and bytes restored so far: + +``` +index shard type stage snapshot repository files_percent bytes_percent +restore-test-settings 0 snapshot done my-first-snapshot my-opensearch-repo 100.0% 100.0% +``` + +## Response body fields + +The following table lists all response body fields. | Field | Data type | Description | -| :--- | :--- | :--- | -| snapshot | string | Snapshot name. | -| indices | array | Indices in the snapshot. | -| shards | object | Total number of shards created along with number of successful and failed shards. | +| :--- | :--- | :--- | +| `accepted` | Boolean | Returned instead of the `snapshot` object when `wait_for_completion` is `false`. Indicates that the restore operation has started. | +| `snapshot.snapshot` | String | The snapshot name. | +| `snapshot.indices` | Array | The names of the restored indexes after any renaming. | +| `snapshot.shards` | Object | The total number of restored shards and the numbers of successful and failed shards. | -If open indices in a snapshot already exist in a cluster, and you don't delete, close, or rename them, the API returns an error like the following: -{: .note} +If open indexes in a snapshot already exist in a cluster, and you don't delete, close, or rename them, the API returns an error similar to the following: -````json +```json { "error" : { "root_cause" : [ { "type" : "snapshot_restore_exception", - "reason" : "[my-opensearch-repo:my-first-snapshot/dCK4Qth-TymRQ7Tu7Iga0g] cannot restore index [.opendistro-reports-definitions] because an open index with same name already exists in the cluster. Either close or delete the existing index or restore the index under a different name by providing a rename pattern and replacement name" + "reason" : "[my-opensearch-repo:my-first-snapshot/DdQp-ksUQ66Vd4H9S2fyKw] cannot restore index [restore-test] because an open index with same name already exists in the cluster. Either close or delete the existing index or restore the index under a different name by providing a rename pattern and replacement name" } ], "type" : "snapshot_restore_exception", - "reason" : "[my-opensearch-repo:my-first-snapshot/dCK4Qth-TymRQ7Tu7Iga0g] cannot restore index [.opendistro-reports-definitions] because an open index with same name already exists in the cluster. Either close or delete the existing index or restore the index under a different name by providing a rename pattern and replacement name" + "reason" : "[my-opensearch-repo:my-first-snapshot/DdQp-ksUQ66Vd4H9S2fyKw] cannot restore index [restore-test] because an open index with same name already exists in the cluster. Either close or delete the existing index or restore the index under a different name by providing a rename pattern and replacement name" }, "status" : 500 } -```` \ No newline at end of file +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/snapshot/restore`. diff --git a/_api-reference/snapshots/verify-snapshot-repository.md b/_api-reference/snapshots/verify-snapshot-repository.md index 29299524..aeb84ea6 100644 --- a/_api-reference/snapshots/verify-snapshot-repository.md +++ b/_api-reference/snapshots/verify-snapshot-repository.md @@ -1,48 +1,74 @@ --- layout: default -title: Verify Snaphot Repository +title: Verify snaphot repository parent: Snapshot APIs - -nav_order: 4 +nav_order: 40 --- -# Verify snapshot repository +# Verify Snapshot Repository API **Introduced 1.0** {: .label .label-purple } Verifies that a snapshot repository is functional. Verifies the repository on each node in a cluster. -If verification is successful, the verify snapshot repository API returns a list of nodes connected to the snapshot repository. If verification failed, the API returns an error. +If verification is successful, the Verify Snapshot Repository API returns a list of nodes connected to the snapshot repository. If verification fails, the API returns an error. If you use the Security plugin, you must have the `manage cluster` privilege. {: .note} +## Endpoints + +```json +GET _snapshot/{repository}/ +``` + ## Path parameters -Path parameters are optional. +The following table lists the available path parameters. | Parameter | Data type | Description | :--- | :--- | :--- -| repository | String | Name of repository to verify. | +| `repository` | String | Name of repository to verify. | ## Query parameters +The following table lists the available query parameters. All query parameters are optional. + | Parameter | Data type | Description | :--- | :--- | :--- -| cluster_manager_timeout | Time | Amount of time to wait for a connection to the master node. Optional, defaults to `30s`. | -| timeout | Time | The period of time to wait for a response. If a response is not received before the timeout value, the request fails and returns an error. Defaults to `30s`. | +| `cluster_manager_timeout` | Time | Amount of time to wait for a connection to the cluster manager node. Optional, defaults to `30s`. | +| `timeout` | Time | The period of time to wait for a response. If a response is not received before the timeout value, the request fails and returns an error. Defaults to `30s`. | -#### Example request +## Example request -The following request verifies that the my-opensearch-repo is functional: +The following request verifies that the `my-opensearch-repo` is functional: -````json + +{% capture step1_rest %} POST /_snapshot/my-opensearch-repo/_verify?timeout=0s&cluster_manager_timeout=50s -```` +{% endcapture %} -#### Example response +{% capture step1_python %} -The example that follows corresponds to the request above in the [Example request](#example-request) section. + +response = client.snapshot.verify_repository( + repository = "my-opensearch-repo", + params = { "timeout": "0s", "cluster_manager_timeout": "50s" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following example corresponds to the preceding [Example request](#example-request). The `POST /_snapshot/my-opensearch-repo/_verify?timeout=0s&cluster_manager_timeout=50s` request returns the following fields: @@ -70,8 +96,14 @@ In the preceding sample, one node is connected to the snapshot repository. If mo } ```` -## Response fields +## Response body fields + +The following table lists all response body fields. | Field | Data type | Description | :--- | :--- | :--- -| nodes | Object | A list (not an array) of nodes connected to the snapshot repository. Each node itself is a property where the node ID is the key and the name has an ID (Object) and a name (String). | \ No newline at end of file +| `nodes` | Object | A list (not an array) of nodes connected to the snapshot repository. Each node itself is a property where the node ID is the key and the name has an ID (Object) and a name (String). | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/repository/verify`. diff --git a/_api-reference/tasks/cancel-tasks.md b/_api-reference/tasks/cancel-tasks.md new file mode 100644 index 00000000..af747d7a --- /dev/null +++ b/_api-reference/tasks/cancel-tasks.md @@ -0,0 +1,151 @@ +--- +layout: default +title: Cancel tasks +parent: Tasks APIs +nav_order: 40 +--- + +# Cancel Tasks API +**Introduced 1.0** +{: .label .label-purple } + +The Cancel Tasks API cancels a task, stopping it from running in the cluster. Not all tasks can be canceled. To determine whether a task is cancelable, check the `cancellable` field in the Cancel Tasks API response. + + + +## Endpoints +```json +POST /_tasks/_cancel +POST /_tasks/{task_id}/_cancel +``` + + + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `task_id` | String | The task ID. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `actions` | List or String | A comma-separated list of actions that should be returned. Keep empty to return all. | +| `nodes` | List | A comma-separated list of node IDs or names used to limit the returned information. Use `_local` to return information from the node you're connecting to, specify the node name to get information from a specific node, or keep the parameter empty to get information from all nodes. | +| `parent_task_id` | String | Returns tasks with a specified parent task ID (`node_id:task_number`). Keep empty or set to -1 to return all. | +| `wait_for_completion` | Boolean | Waits for the matching task to complete. When `true`, the request is blocked until the task has completed. _(Default: `false`)_ | + + + +## Example request + +The following request cancels any tasks currently running on `opensearch-node1` and `opensearch-node2`: + + +{% capture step1_rest %} +POST /_tasks/_cancel?nodes=opensearch-node1,opensearch-node2 +{% endcapture %} + +{% capture step1_python %} + + +response = client.tasks.cancel( + params = { "nodes": "opensearch-node1,opensearch-node2" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following response shows that a bulk write and update task were canceled without a node failure and provides additional information about the canceled tasks: + +```json +{ + "node_failures": [], + "nodes": { + "JzrCxdtFTCO_RaINw8ckNA": { + "name": "opensearch-node1", + "transport_address": "127.0.0.1:9300", + "host": "127.0.0.1", + "ip": "127.0.0.1:9300", + "roles": [ + "data", + "ingest", + "cluster_manager", + "remote_cluster_client" + ], + "attributes": {}, + "tasks": { + "JzrCxdtFTCO_RaINw8ckNA:54": { + "node": "JzrCxdtFTCO_RaINw8ckNA", + "id": 54, + "type": "transport", + "action": "indices:data/write/bulk", + "status": "cancelled", + "description": "bulk request to [test_index]", + "start_time_in_millis": 1625145678901, + "running_time_in_nanos": 2345678, + "cancellable": true, + "cancelled": true + } + } + }, + "K8iyDdtGQCO_SbJNw9dkMB": { + "name": "opensearch-node2", + "transport_address": "127.0.0.1:9301", + "host": "127.0.0.1", + "ip": "127.0.0.1:9301", + "roles": [ + "data", + "ingest", + "master", + "remote_cluster_client" + ], + "attributes": {}, + "tasks": { + "K8iyDdtGQCO_SbJNw9dkMB:78": { + "node": "K8iyDdtGQCO_SbJNw9dkMB", + "id": 78, + "type": "transport", + "action": "indices:data/write/update", + "status": "cancelled", + "description": "updating document in [another_index]", + "start_time_in_millis": 1625145679012, + "running_time_in_nanos": 1234567, + "cancellable": true, + "cancelled": true + } + } + } + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/tasks/cancel`. diff --git a/_api-reference/tasks/delete-task.md b/_api-reference/tasks/delete-task.md new file mode 100644 index 00000000..1e796bd9 --- /dev/null +++ b/_api-reference/tasks/delete-task.md @@ -0,0 +1,97 @@ +--- +layout: default +title: Delete task +parent: Tasks APIs +nav_order: 30 +--- + +# Delete Task API +**Introduced 3.9** +{: .label .label-purple } + +Use the Delete Task API to delete the stored result of a completed task. For example, when you run a supported operation and set `wait_for_completion=false`, OpenSearch stores the task result so that you can retrieve it later by using the [Get Task API]({{site.url}}{{site.baseurl}}/api-reference/tasks/get-tasks/). When you no longer need the result, delete it to free the associated storage. + +The Delete Task API does not cancel or delete a running task. To stop a running task, use the [Cancel Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/cancel-tasks/). +{: .important } + + +## Endpoints +```json +DELETE /_tasks/{task_id} +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `task_id` | **Required** | String | The ID of the stored completed task result to delete (`node_id:task_number`). | + + + +## Example request + +The following request deletes the stored result for task `JzrCxdtFTCO_RaINw8ckNA:54321`: + + +{% capture step1_rest %} +DELETE /_tasks/JzrCxdtFTCO_RaINw8ckNA:54321 +{% endcapture %} + +{% capture step1_python %} + + +response = client.tasks.delete( + task_id = "JzrCxdtFTCO_RaINw8ckNA:54321" +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +OpenSearch responds with an acknowledgment after deleting the stored result: + +```json +{ + "acknowledged": true +} +``` + +After a successful deletion, the Get Task API returns a `404 Not Found` response for the task. + +## Parent and child tasks + +You cannot delete a stored task result while it has running child tasks or stored child task results. In a hierarchy of stored task results, delete the results from the leaves toward the root. For example, delete a grandchild result before its parent result, and then delete the root result. + +OpenSearch returns a `409 Conflict` response if the task has running child tasks or stored child task results. + +## Response codes + +The following table lists common response codes. + +| HTTP status code | Description | +| :--- | :--- | +| `200 OK` | The stored completed task result was deleted. | +| `404 Not Found` | The task is not running and has no stored result. | +| `409 Conflict` | The task is still running, is not marked as completed, has running child tasks, or has stored child task results. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/tasks/delete`. diff --git a/_api-reference/tasks/get-tasks.md b/_api-reference/tasks/get-tasks.md new file mode 100644 index 00000000..a4d2d07e --- /dev/null +++ b/_api-reference/tasks/get-tasks.md @@ -0,0 +1,278 @@ +--- +layout: default +title: Get task +parent: Tasks APIs +nav_order: 20 +--- + +# Get Task API +**Introduced 1.0** +{: .label .label-purple } + +The Get Task API returns detailed information about a single general OpenSearch task (such as search, reindex, or bulk operations). + +This API is different from the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/), which tracks machine learning tasks and has a different response format. +{: .important } + + +## Endpoints +```json +GET /_tasks/{task_id} +``` + + + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Required | Data type | Description | +| :--- | :--- | :--- | :--- | +| `task_id` | **Required** | String | The task ID. | + + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `timeout` | String | The amount of time to wait for a response. | `30s` | +| `wait_for_completion` | Boolean | Waits for the matching task to complete. When `true`, the request is blocked until the task has completed. | `false` | + + + +The API returns information about tasks that are currently running. After a task finishes, the API returns its information only if the task result was stored in the `.tasks` index. OpenSearch stores task results only for operations started using `wait_for_completion=false`. For a task that has finished without storing its result, the API returns an error. + +## Example request + +To obtain a task ID, start a long-running operation, such as a reindex or update by query, using `wait_for_completion=false`. The following request starts a throttled reindex operation: + +```json +POST /_reindex?wait_for_completion=false&requests_per_second=50 +{ + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-dest-index" + } +} +``` +{% include copy-curl.html %} + +The response contains the task ID: + +```json +{ + "task": "6It0uQ1AR06IDC4nMstPQw:1822891" +} +``` + +Alternatively, find the ID of a running task using the [List Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/list-tasks/), for example, `GET /_tasks?actions=*reindex`. + +The following request returns information about the task: + +```json +GET /_tasks/ +``` +{% include copy-curl.html %} + +## Example response + +While the task is running, the response contains `"completed": false` and the current task status: + +```json +{ + "completed": false, + "task": { + "node": "6It0uQ1AR06IDC4nMstPQw", + "id": 1822891, + "type": "transport", + "action": "indices:data/write/reindex", + "status": { + "total": 2000, + "updated": 0, + "created": 1000, + "deleted": 0, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": 50.0, + "throttled_until_millis": 16963 + }, + "description": "reindex from [my-source-index] to [my-dest-index]", + "start_time_in_millis": 1792185761839, + "running_time_in_nanos": 3241833543, + "cancellable": true, + "cancelled": false, + "headers": {}, + "resource_stats": { + "average": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "total": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "min": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "max": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "thread_info": { + "thread_executions": 0, + "active_threads": 0 + } + } + } +} +``` + +After the task finishes, the response contains `"completed": true` and the stored result of the operation in the `response` object: + +
+ + Response + + {: .text-delta} + +```json +{ + "completed": true, + "task": { + "node": "6It0uQ1AR06IDC4nMstPQw", + "id": 1822891, + "type": "transport", + "action": "indices:data/write/reindex", + "status": { + "total": 2000, + "updated": 0, + "created": 2000, + "deleted": 0, + "batches": 2, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 39999, + "requests_per_second": 50.0, + "throttled_until_millis": 0 + }, + "description": "reindex from [my-source-index] to [my-dest-index]", + "start_time_in_millis": 1792185761839, + "running_time_in_nanos": 40289441643, + "cancellable": true, + "cancelled": false, + "headers": {} + }, + "response": { + "took": 40286, + "timed_out": false, + "total": 2000, + "updated": 0, + "created": 2000, + "deleted": 0, + "batches": 2, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled": "39.9s", + "throttled_millis": 39999, + "requests_per_second": 50.0, + "throttled_until": "0s", + "throttled_until_millis": 0, + "failures": [] + } +} +``` +
+ +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `completed` | Boolean | Whether the task has finished. | +| `task` | Object | Information about the task. See [The `task` object](#the-task-object). | +| `response` | Object | The result of the operation. Returned only for a task that completed or was canceled and whose result was stored. The object contents depend on the operation. For example, a reindex task returns the same fields as the [Reindex API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) response. For a canceled task, the object also contains a `canceled` field that specifies the reason for cancellation. | +| `error` | Object | The error that caused the task to fail. Returned only for a task that failed and whose result was stored. | + +### The `task` object + +The `task` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `node` | String | The ID of the node on which the task runs. | +| `id` | Integer | The task ID on the node. The full task ID has the format `:`. | +| `type` | String | The task type, such as `transport`. | +| `action` | String | The action that the task performs, such as `indices:data/write/reindex`. | +| `status` | Object | The current status of the task. The object contents depend on the action. For example, a reindex task reports the number of documents processed and throttling information. Not returned for all actions. | +| `description` | String | A description of the task, such as the source and destination indexes of a reindex operation. | +| `start_time_in_millis` | Long | The time at which the task started, in milliseconds since the epoch. | +| `running_time_in_nanos` | Long | The amount of time for which the task has run, in nanoseconds. | +| `cancellable` | Boolean | Whether the task can be canceled. | +| `cancelled` | Boolean | Whether the task has been canceled. | +| `cancellation_time_millis` | Long | The time at which the task was canceled, in milliseconds since the epoch. Returned only for canceled tasks. | +| `parent_task_id` | String | The ID of the parent task. Returned only for child tasks, such as the slices of a sliced reindex operation. | +| `headers` | Object | The tracked request headers of the request that started the task, such as `X-Opaque-Id`. Other request headers are not included. | +| `resource_stats` | Object | Resource usage statistics for the task. Returned only for running tasks that support resource tracking. See [The `resource_stats` object](#the-resource_stats-object). | + +### The `resource_stats` object + +The `resource_stats` object is only updated for tasks that support resource tracking. These statistics are computed based on scheduled thread executions, including both threads that have finished working on the task and threads currently working on the task. Because the same thread may be scheduled to work on the same task multiple times, each instance of a given thread being scheduled to work on a given task is considered to be a single thread execution. + +The `resource_stats` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `average` | Object | The average resource usage across all scheduled thread executions. | +| `total` | Object | The total resource usage across all scheduled thread executions. | +| `min` | Object | The minimum resource usage across all scheduled thread executions. | +| `max` | Object | The maximum resource usage across all scheduled thread executions. | +| `thread_info` | Object | Thread-count-related statistics. | + +Each of the `average`, `total`, `min`, and `max` objects contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `cpu_time_in_nanos` | Long | The CPU time used, in nanoseconds. | +| `memory_in_bytes` | Long | The amount of memory used, in bytes. | + +The `thread_info` object contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `thread_executions` | Integer | The number of threads that have been scheduled to work on the task. | +| `active_threads` | Integer | The number of threads currently working on the task. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/tasks/get`. diff --git a/_api-reference/tasks/list-tasks.md b/_api-reference/tasks/list-tasks.md new file mode 100644 index 00000000..0b035ae4 --- /dev/null +++ b/_api-reference/tasks/list-tasks.md @@ -0,0 +1,134 @@ +--- +layout: default +title: List tasks +parent: Tasks APIs +nav_order: 10 +--- + +# List Tasks API +**Introduced 1.0** +{: .label .label-purple } + +The List Tasks API returns a list of tasks running in the cluster. + + +## Endpoints +```json +GET /_tasks +``` + + + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | Default | +| :--- | :--- | :--- | :--- | +| `actions` | List or String | A comma-separated list of actions that should be returned. Keep empty to return all. | N/A | +| `detailed` | Boolean | When `true`, the response includes detailed information about shard recoveries. | `false` | +| `group_by` | String | Groups tasks by parent/child relationships or nodes.
Valid values are: `nodes`, `none`, and `parents`. | `nodes` | +| `nodes` | List | A comma-separated list of node IDs or names used to limit the returned information. Use `_local` to return information from the node you're connecting to, specify the node name to get information from a specific node, or keep the parameter empty to get information from all nodes. | N/A | +| `parent_task_id` | String | Returns tasks with a specified parent task ID (`node_id:task_number`). Keep empty or set to -1 to return all. | N/A | +| `timeout` | String | The amount of time to wait for a response. | N/A | +| `wait_for_completion` | Boolean | Waits for the matching task to complete. When `true`, the request is blocked until the task has completed. | `false` | + + + +## Example request + +The following request returns tasks currently running on a node named `opensearch-node1`: + + +{% capture step1_rest %} +GET /_tasks?nodes=opensearch-node1 +{% endcapture %} + +{% capture step1_python %} + + +response = client.tasks.list( + params = { "nodes": "opensearch-node1" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following response provides information about running tasks: + +```json +{ + "nodes": { + "Mgqdm0r9SEGClWxp_RbnaQ": { + "name": "opensearch-node1", + "transport_address": "sample_address", + "host": "sample_host", + "ip": "sample_ip", + "roles": [ + "data", + "ingest", + "master", + "remote_cluster_client" + ], + "tasks": { + "Mgqdm0r9SEGClWxp_RbnaQ:24578": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 24578, + "type": "transport", + "action": "cluster:monitor/tasks/lists", + "start_time_in_millis": 1611612517044, + "running_time_in_nanos": 638700, + "cancellable": false, + "headers": {} + }, + "Mgqdm0r9SEGClWxp_RbnaQ:24579": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 24579, + "type": "direct", + "action": "cluster:monitor/tasks/lists[n]", + "start_time_in_millis": 1611612517044, + "running_time_in_nanos": 222200, + "cancellable": false, + "parent_task_id": "Mgqdm0r9SEGClWxp_RbnaQ:24578", + "headers": {} + } + } + } + } +} +``` + +### The `resource_stats` object + +The `resource_stats` object is only updated for tasks that support resource tracking. These statistics are computed based on scheduled thread executions, including both threads that have finished working on the task and threads currently working on the task. Because the same thread may be scheduled to work on the same task multiple times, each instance of a given thread being scheduled to work on a given task is considered to be a single thread execution. + +The following table lists all response fields in the `resource_stats` object. + +Response field | Description | +:--- | :--- | +`average` | The average resource usage across all scheduled thread executions. | +`total` | The total resource usage across all scheduled thread executions. | +`min` | The minimum resource usage across all scheduled thread executions. | +`max` | The maximum resource usage across all scheduled thread executions. | +`thread_info` | Thread-count-related statistics.| +`thread_info.active_threads` | The number of threads currently working on the task. | +`thread_info.thread_executions` | The number of threads that have been scheduled to work on the task. | + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:monitor/tasks/list`. diff --git a/_api-reference/tasks/rethrottle.md b/_api-reference/tasks/rethrottle.md new file mode 100644 index 00000000..8089ffd0 --- /dev/null +++ b/_api-reference/tasks/rethrottle.md @@ -0,0 +1,224 @@ +--- +layout: default +title: Rethrottle task +parent: Tasks APIs +nav_order: 50 +--- + +# Rethrottle Task API +**Introduced 1.0** +{: .label .label-purple } + +You can use the following APIs to dynamically change the `requests_per_second` for [`_reindex`]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/), [`_update_by_query`]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-by-query/), or [`_delete_by_query`]({{site.url}}{{site.baseurl}}/api-reference/document-apis/delete-by-query/) operations that are already running. + +## Endpoints + +```json +POST /_delete_by_query/{task_id}/_rethrottle +POST /_reindex/{task_id}/_rethrottle +POST /_update_by_query/{task_id}/_rethrottle +``` + +## Path parameters + +Parameter | Data type | Description +:--- | :--- | :--- +`task_id` | String | The unique identifier for the running task that you want to rethrottle. + +## Query parameters + +Parameter | Data type | Description +:--- | :--- | :--- +`requests_per_second` | Float | The new throttle value to apply to the task. Use `-1` to disable throttling. Optional. + +### Example request: Rethrottle a running delete by query task + + +{% capture step1_rest %} +POST /_delete_by_query//_rethrottle?requests_per_second=10 +{% endcapture %} + +{% capture step1_python %} + + +response = client.delete_by_query_rethrottle( + task_id = "", + params = { "requests_per_second": "10" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + + +### Example request: Rethrottle a running reindex task + + +{% capture step1_rest %} +POST /_reindex//_rethrottle?requests_per_second=20 +{% endcapture %} + +{% capture step1_python %} + + +response = client.reindex_rethrottle( + task_id = "", + params = { "requests_per_second": "20" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +### Example request: Rethrottle a running update by query task + + +{% capture step1_rest %} +POST /_update_by_query//_rethrottle?requests_per_second=5 +{% endcapture %} + +{% capture step1_python %} + + +response = client.update_by_query_rethrottle( + task_id = "", + params = { "requests_per_second": "5" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} + + +## Example response + +The following response provides details regarding the active `update_by_query` task: + +``` +{ + "nodes": { + "bvv8SKpiRhOhF9_Bu8gZ7w": { + "name": "opensearch-node1", + "transport_address": "172.18.0.4:9300", + "host": "172.18.0.4", + "ip": "172.18.0.4:9300", + "roles": [ + "cluster_manager", + "data", + "ingest", + "remote_cluster_client" + ], + "attributes": { + "shard_indexing_pressure_enabled": "true" + }, + "tasks": { + "bvv8SKpiRhOhF9_Bu8gZ7w:640": { + "node": "bvv8SKpiRhOhF9_Bu8gZ7w", + "id": 640, + "type": "transport", + "action": "indices:data/write/update/byquery", + "status": { + "total": 4785, + "updated": 1000, + "created": 0, + "deleted": 0, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": 50, + "throttled_until_millis": 2146 + }, + "description": "update-by-query [test-rethrottle] updated with Script{type=inline, lang='painless', idOrCode='ctx._source.new_field = 'updated'', options={}, params={}}", + "start_time_in_millis": 1751310547697, + "running_time_in_nanos": 9567425129, + "cancellable": true, + "cancelled": false, + "headers": { + "X-Opaque-Id": "1b911516-44cd-4920-8c1e-79368ea7cdfd" + }, + "resource_stats": { + "average": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "total": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "min": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "max": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "thread_info": { + "thread_executions": 0, + "active_threads": 0 + } + } + } + } + } + } +} +``` + +## Response body fields + +The response provides detailed task- and node-level information about the rethrottled operation. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `nodes` | Object | A map of node IDs to details about the task on each node. | +| `nodes..name` | String | The name of the node on which the task is running. | +| `nodes..transport_address` | String | The transport address of the node. | +| `nodes..host` | String | The host IP address. | +| `nodes..ip` | String | The IP address and port. | +| `nodes..roles` | Array | The roles assigned to the node. | +| `nodes..attributes` | Object | Node-level attributes. | +| `nodes..tasks` | Object | A map of task IDs to detailed information about each task. | +| `nodes..tasks..type` | String | The task type, such as `transport`. | +| `nodes..tasks..action` | String | The specific action being performed (for example, `reindex`). | +| `nodes..tasks..status` | Object | The current status of the task. | +| `nodes..tasks..status.total` | Integer | The total number of documents to process. | +| `nodes..tasks..status.created` | Integer | The number of documents created. | +| `nodes..tasks..status.updated` | Integer | The number of documents updated. | +| `nodes..tasks..status.deleted` | Integer | The number of documents deleted. | +| `nodes..tasks..status.batches` | Integer | The number of batches processed. | +| `nodes..tasks..status.version_conflicts` | Integer | The number of version conflicts. | +| `nodes..tasks..status.noops` | Integer | The number of no-op updates. | +| `nodes..tasks..status.retries` | Object | Retry stats for bulk and search operations. | +| `nodes..tasks..status.requests_per_second` | Float | Current throttle rate in requests per second. | +| `nodes..tasks..status.throttled_millis` | Integer | The time, in milliseconds, that the task was throttled. | +| `nodes..tasks..status.throttled_until_millis` | Integer | The time, in milliseconds, that the task is expected to remain throttled. | +| `nodes..tasks..description` | String | A human-readable description of the task. | +| `nodes..tasks..start_time_in_millis` | Integer | The task start time in epoch milliseconds. | +| `nodes..tasks..running_time_in_nanos` | Integer | The task runtime in nanoseconds. | +| `nodes..tasks..cancellable` | Boolean | Whether the task can be canceled. | +| `nodes..tasks..cancelled` | Boolean | Whether the task has been canceled. | +| `nodes..tasks..headers` | Object | Optional HTTP headers associated with the task. | +| `nodes..tasks..resource_stats` | Object | Statistics about resource usage. | diff --git a/_api-reference/tasks/tasks.md b/_api-reference/tasks/tasks.md new file mode 100644 index 00000000..9cf1b89f --- /dev/null +++ b/_api-reference/tasks/tasks.md @@ -0,0 +1,85 @@ +--- +layout: default +title: Tasks APIs +has_children: yes +nav_order: 130 +redirect_from: + - /opensearch/rest-api/tasks/ + - /api-reference/tasks/ +--- + +# Tasks APIs +**Introduced 1.0** +{: .label .label-purple } + +A _task_ is any operation that you run in a cluster. For example, searching your data collection of books for a title or author name is a task. When you run OpenSearch, a task is automatically created to monitor your cluster's health and performance. For more information about all of the tasks currently executing in your cluster, you can use the `tasks` API operation. + +## Attaching headers to tasks + +To associate requests with tasks for better tracking, you can provide an `X-Opaque-Id:` header as part of the HTTPS request reader of your `curl` command. The API will attach the specified header in the returned result. + +The following request returns tasks with an `X-Opaque-Id` of `111111`: + +```bash +curl -i -H "X-Opaque-Id: 111111" "https://localhost:9200/_tasks" -u 'admin:' --insecure +``` +{% include copy.html %} + +The `_tasks` operation returns the following result: + +```json +HTTP/1.1 200 OK +X-Opaque-Id: 111111 +content-type: application/json; charset=UTF-8 +content-length: 768 + +{ + "nodes": { + "Mgqdm0r9SEGClWxp_RbnaQ": { + "name": "opensearch-node1", + "transport_address": "172.18.0.4:9300", + "host": "172.18.0.4", + "ip": "172.18.0.4:9300", + "roles": [ + "data", + "ingest", + "master", + "remote_cluster_client" + ], + "tasks": { + "Mgqdm0r9SEGClWxp_RbnaQ:30072": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 30072, + "type": "direct", + "action": "cluster:monitor/tasks/lists[n]", + "start_time_in_millis": 1613166701725, + "running_time_in_nanos": 245400, + "cancellable": false, + "parent_task_id": "Mgqdm0r9SEGClWxp_RbnaQ:30071", + "headers": { + "X-Opaque-Id": "111111" + } + }, + "Mgqdm0r9SEGClWxp_RbnaQ:30071": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 30071, + "type": "transport", + "action": "cluster:monitor/tasks/lists", + "start_time_in_millis": 1613166701725, + "running_time_in_nanos": 658200, + "cancellable": false, + "headers": { + "X-Opaque-Id": "111111" + } + } + } + } + } +} +``` +This operation supports the same parameters as the `tasks` operation. The following example shows you how to associate `X-Opaque-Id` with specific tasks: + +```bash +curl -i -H "X-Opaque-Id: 123456" "https://localhost:9200/_tasks?nodes=opensearch-node1" -u 'admin:' --insecure +``` +{% include copy.html %} diff --git a/_api-reference/units.md b/_api-reference/units.md index 8a0d2705..bccc2616 100644 --- a/_api-reference/units.md +++ b/_api-reference/units.md @@ -1,22 +1,72 @@ --- layout: default title: Supported units -nav_order: 90 +nav_order: 160 redirect_from: - /opensearch/units/ --- # Supported units -**Introduced 1.0** -{: .label .label-purple } -OpenSearch supports the following units for all REST operations: +OpenSearch supports the following units for all REST operations. -Unit | Description | Example -:--- | :--- | :--- -Times | The supported units for time are `d` for days, `h` for hours, `m` for minutes, `s` for seconds, `ms` for milliseconds, `micros` for microseconds, and `nanos` for nanoseconds. | `5d` or `7h` -Bytes | The supported units for byte size are `b` for bytes, `kb` for kibibytes, `mb` for mebibytes, `gb` for gibibytes, `tb` for tebibytes, and `pb` for pebibytes. Despite the base-10 abbreviations, these units are base-2; `1kb` is 1,024 bytes, `1mb` is 1,048,576 bytes, etc. | `7kb` or `6gb` -Distances | The supported units for distance are `mi` for miles, `yd` for yards, `ft` for feet, `in` for inches, `km` for kilometers, `m` for meters, `cm` for centimeters, `mm` for millimeters, and `nmi` or `NM` for nautical miles. | `5mi` or `4ft` -Quantities without units | For large values that don't have a unit, use `k` for kilo, `m` for mega, `g` for giga, `t` for tera, and `p` for peta. | `5k` for 5,000 +## Time units -To convert output units to human-readable values, see [Common REST parameters]({{site.url}}{{site.baseurl}}/opensearch/common-parameters/). +The following table lists all supported time units. + +Units | Specify as +:--- | :--- +Days | `d` +Hours | `h` +Minutes | `m` +Seconds | `s` +Milliseconds | `ms` +Microseconds | `micros` +Nanoseconds | `nanos` + +## Byte size units + +The following table lists all supported byte size units. Units are case insensitive. Byte size units are base 2, so `1kb` is equal to 1,024 bytes and `1mb` is equal to 1,048,576 bytes. + +Units | Specify as +:--- | :--- +Bytes | `b` +Kibibytes | `kb` or `k` +Mebibytes | `mb` or `m` +Gibibytes | `gb` or `g` +Tebibytes | `tb` or `t` +Pebibytes | `pb` or `p` + +## Distance units + +The following table lists all supported distance units. + +Units | Specify as +:--- | :--- +Miles | `mi` or `miles` +Yards | `yd` or `yards` +Feet | `ft` or `feet` +Inches | `in` or `inch` +Kilometers | `km` or `kilometers` +Meters | `m` or `meters` +Centimeters | `cm` or `centimeters` +Millimeters | `mm` or `millimeters` +Nautical miles | `NM`, `nmi`, or `nauticalmiles` + +## Quantities without units + +For large values that don't have a unit, such as document counts, use the following suffixes. For example, `5k` is equal to 5,000. + +Suffix | Multiplier +:--- | :--- +`k` | Kilo (1,000) +`m` | Mega (1,000,000) +`g` | Giga (1,000,000,000) +`t` | Tera (1,000,000,000,000) +`p` | Peta (1,000,000,000,000,000) + +## Related documentation + +- [Common REST parameters]({{site.url}}{{site.baseurl}}/api-reference/common-parameters/) +- [Index name syntax]({{site.url}}{{site.baseurl}}/api-reference/index-name-syntax/) +- [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/) diff --git a/_benchmark/FAQs.md b/_benchmark/FAQs.md new file mode 100644 index 00000000..70f776ae --- /dev/null +++ b/_benchmark/FAQs.md @@ -0,0 +1,28 @@ +--- +layout: default +title: FAQs +nav_order: 115 +--- + +# OpenSearch Benchmark FAQs + +This section provides answers to frequently asked questions. + + +## How can I get more information about an error that I encountered? + +Check the end of the OpenSearch Benchmark log files to view messages from the latest run. + +If you need more help, you can: +- [Post a question in the OpenSearch Benchmark Slack channel](https://opensearch.slack.com/archives/C082PLA3VPW). +- [Attend a community meeting, office hours, or issue triage session](https://www.meetup.com/opensearch/events/309982456/?eventOrigin=group_upcoming_events). + + +## Where are the OpenSearch Benchmark log files located? + +By default, the OpenSearch Benchmark log files are located in the your home directory, under `$HOME/.osb/osb.log`. + + +## I'm looking for the latest updates to OpenSearch Benchmark. Where can I find the latest incremental build of OpenSearch Benchmark? + +Incremental OpenSearch Benchmark builds are generated as Docker images when any new changes are merged into the codebase. They are available on the [OpenSearch Benchmark Docker Hub page](https://hub.docker.com/r/opensearchstaging/opensearch-benchmark/tags). diff --git a/_benchmark/anatomy-of-a-workload.md b/_benchmark/anatomy-of-a-workload.md new file mode 100644 index 00000000..ed4b2bbb --- /dev/null +++ b/_benchmark/anatomy-of-a-workload.md @@ -0,0 +1,817 @@ +--- +layout: default +title: Anatomy of a workload +nav_order: 22 +has_children: true +has_toc: false +redirect_from: + - /benchmark/user-guide/understanding-workloads/anatomy-of-a-workload/ + - /benchmark/reference/workloads/ + - /benchmark/reference/workloads/index/ + - /benchmark/workloads/ + - /benchmark/workloads/index/ + - /benchmark/user-guide/understanding-workloads/ +--- + +# Anatomy of a workload + +A workload is a specification of one or more benchmarking scenarios. All workloads contain the following files and directories: + +- [`workload.json`](#workloadjson): Contains all of the workload settings. +- [`index.json`](#indexjson): Contains the document mappings and parameters as well as index settings. +- [`files.txt`](#filestxt): Contains the data corpora file names. +- [`_test-procedures`](#_operations-and-_test-procedures): Most workloads contain only one default test procedure, which is configured in `default.json`. +- [`_operations`](#_operations-and-_test-procedures): Contains all of the operations used in test procedures. +- `workload.py`: Adds more dynamic functionality to the test. + + +## workload.json + + +A `workload.json` file usually includes the following elements: + +- [`indices`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/indices/): Defines the relevant indexes and index templates used for the workload. To create an index, specify its `name`. To add definitions to your index, use the `body` option and point it to the JSON file containing the index definitions. +- [`corpora`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/corpora/): Defines all document corpora used for the workload, including the source files that contain the documents and the number of documents in each file. +- [`operations`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/operations/): **Optional**. Lists the OpenSearch API operations performed by the workload and how they are parameterized. For example, you can list an operation named `create-index` that creates an index in the benchmark cluster to which OpenSearch Benchmark can write documents. +- [`schedule`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/schedule/): Defines operations and the order in which the operations run inline. Alternatively, you can use `operations` to group operations and the [`test_procedures`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/test-procedures/) parameter to specify the order of operations. + +The following example workload shows these elements working together. You can run this workload in your own benchmark configuration: + +```json +{ + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "iterations": 1000, + "target-throughput": 100 + } + ] +} +``` + + +## index.json + + +The `index.json` file defines the data mappings, indexing parameters, and index settings for workload documents during `create-index` operations. + +When OpenSearch Benchmark creates an index for the workload, it uses the index settings and mappings template in the `index.json` file. Mappings in the `index.json` file are based on the mappings of a single document from the workload's corpus, which is stored in the `files.txt` file. The following is an example of the `index.json` file for the `nyc_taxis` workload. You can customize the fields, such as `number_of_shards`, `number_of_replicas`, `query_cache_enabled`, and `requests_cache_enabled`. + +```json +{ + "settings": { + "index.number_of_shards": {% raw %}{{number_of_shards | default(1)}}{% endraw %}, + "index.number_of_replicas": {% raw %}{{number_of_replicas | default(0)}}{% endraw %}, + "index.queries.cache.enabled": {% raw %}{{query_cache_enabled | default(false) | tojson}}{% endraw %}, + "index.requests.cache.enable": {% raw %}{{requests_cache_enabled | default(false) | tojson}}{% endraw %} + }, + "mappings": { + "_source": { + "enabled": {% raw %}{{ source_enabled | default(true) | tojson }}{% endraw %} + }, + "properties": { + "surcharge": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "dropoff_datetime": { + "type": "date", + "format": "yyyy-MM-dd HH:mm:ss" + }, + "trip_type": { + "type": "keyword" + }, + "mta_tax": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "rate_code_id": { + "type": "keyword" + }, + "passenger_count": { + "type": "integer" + }, + "pickup_datetime": { + "type": "date", + "format": "yyyy-MM-dd HH:mm:ss" + }, + "tolls_amount": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "tip_amount": { + "type": "half_float" + }, + "payment_type": { + "type": "keyword" + }, + "extra": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "vendor_id": { + "type": "keyword" + }, + "store_and_fwd_flag": { + "type": "keyword" + }, + "improvement_surcharge": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "fare_amount": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "ehail_fee": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "cab_color": { + "type": "keyword" + }, + "dropoff_location": { + "type": "geo_point" + }, + "vendor_name": { + "type": "text" + }, + "total_amount": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "trip_distance": {% raw %}{%- if trip_distance_mapping is defined %} {{ trip_distance_mapping | tojson }} {%- else %}{% endraw %} { + "scaling_factor": 100, + "type": "scaled_float" + }{% raw %}{%- endif %}{% endraw %}, + "pickup_location": { + "type": "geo_point" + } + }, + "dynamic": "strict" + } +} +``` + + +## files.txt + + +The `files.txt` file lists the files that store the workload data, which are typically stored in a zipped JSON file. + + +## _operations and _test-procedures + + +To make the workload more human-readable, `_operations` and `_test-procedures` are separated into two directories. + +The `_operations` directory contains a `default.json` file that lists all of the supported operations that the test procedure can use. Some workloads, such as `nyc_taxis`, contain an additional `.json` file that lists feature-specific operations, such as `snapshot` operations. The following JSON example shows a list of operations from the `nyc_taxis` workload: + +```json + { + "name": "index", + "operation-type": "bulk", + "bulk-size": {% raw %}{{bulk_size | default(10000)}}{% endraw %}, + "ingest-percentage": {% raw %}{{ingest_percentage | default(100)}}{% endraw %} + }, + { + "name": "update", + "operation-type": "bulk", + "bulk-size": {% raw %}{{bulk_size | default(10000)}}, + "ingest-percentage": {{ingest_percentage | default(100)}}, + "conflicts": "{{conflicts | default('random')}}", + "on-conflict": "{{on_conflict | default('update')}}", + "conflict-probability": {{conflict_probability | default(25)}}, + "recency": {{recency | default(0)}}{% endraw %} + }, + { + "name": "wait-until-merges-finish", + "operation-type": "index-stats", + "index": "_all", + "condition": { + "path": "_all.total.merges.current", + "expected-value": 0 + }, + "retry-until-success": true, + "include-in-reporting": false + }, + { + "name": "default", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + { + "name": "range", + "operation-type": "search", + "body": { + "query": { + "range": { + "total_amount": { + "gte": 5, + "lt": 15 + } + } + } + } + }, + { + "name": "distance_amount_agg", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "bool": { + "filter": { + "range": { + "trip_distance": { + "lt": 50, + "gte": 0 + } + } + } + } + }, + "aggs": { + "distance_histo": { + "histogram": { + "field": "trip_distance", + "interval": 1 + }, + "aggs": { + "total_amount_stats": { + "stats": { + "field": "total_amount" + } + } + } + } + } + } + }, + { + "name": "autohisto_agg", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "01/01/2015", + "lte": "21/01/2015", + "format": "dd/MM/yyyy" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": 20 + } + } + } + } + }, + { + "name": "date_histogram_agg", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "01/01/2015", + "lte": "21/01/2015", + "format": "dd/MM/yyyy" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "calendar_interval": "day" + } + } + } + } + }, + { + "name": "date_histogram_calendar_interval", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "calendar_interval": "month" + } + } + } + } + }, + { + "name": "date_histogram_calendar_interval_with_tz", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "calendar_interval": "month", + "time_zone": "America/New_York" + } + } + } + } + }, + { + "name": "date_histogram_fixed_interval", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "fixed_interval": "60d" + } + } + } + } + }, + { + "name": "date_histogram_fixed_interval_with_tz", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "fixed_interval": "60d", + "time_zone": "America/New_York" + } + } + } + } + }, + { + "name": "date_histogram_fixed_interval_with_metrics", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "fixed_interval": "60d" + }, + "aggs": { + "total_amount": { "stats": { "field": "total_amount" } }, + "tip_amount": { "stats": { "field": "tip_amount" } }, + "trip_distance": { "stats": { "field": "trip_distance" } } + } + } + } + } + }, + { + "name": "auto_date_histogram", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": "12" + } + } + } + } + }, + { + "name": "auto_date_histogram_with_tz", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": "13", + "time_zone": "America/New_York" + } + } + } + } + }, + { + "name": "auto_date_histogram_with_metrics", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": "12" + }, + "aggs": { + "total_amount": { "stats": { "field": "total_amount" } }, + "tip_amount": { "stats": { "field": "tip_amount" } }, + "trip_distance": { "stats": { "field": "trip_distance" } } + } + } + } + } + }, + { + "name": "desc_sort_tip_amount", + "operation-type": "search", + "index": "nyc_taxis", + "body": { + "query": { + "match_all": {} + }, + "sort" : [ + {"tip_amount" : "desc"} + ] + } + }, + { + "name": "asc_sort_tip_amount", + "operation-type": "search", + "index": "nyc_taxis", + "body": { + "query": { + "match_all": {} + }, + "sort" : [ + {"tip_amount" : "asc"} + ] + } + } +``` + +The `_test-procedures` directory contains a `default.json` file that sets the order of operations performed by the workload. Similar to the `_operations` directory, the `_test-procedures` directory can also contain feature-specific test procedures, such as `searchable_snapshots.json` for `nyc_taxis`. The following examples show the searchable snapshots test procedures for `nyc_taxis`: + +```json + { + "name": "searchable-snapshot", + "description": "Measuring performance for Searchable Snapshot feature. Based on the default test procedure 'append-no-conflicts'.", + "schedule": [ + { + "operation": "delete-index" + }, + { + "operation": { + "operation-type": "create-index", + "settings": {% raw %}{%- if index_settings is defined %} {{ index_settings | tojson }} {%- else %}{ + "index.codec": "best_compression", + "index.refresh_interval": "30s", + "index.translog.flush_threshold_size": "4g" + }{%- endif %}{% endraw %} + } + }, + { + "name": "check-cluster-health", + "operation": { + "operation-type": "cluster-health", + "index": "nyc_taxis", + "request-params": { + "wait_for_status": {% raw %}"{{ cluster_health | default('green') }}"{% endraw %}, + "wait_for_no_relocating_shards": "true" + }, + "retry-until-success": true + } + }, + { + "operation": "index", + "warmup-time-period": 240, + "clients": {% raw %}{{ bulk_indexing_clients | default(8) }}, + "ignore-response-error-level": "{{ error_level | default('non-fatal') }}"{% endraw %} + }, + { + "name": "refresh-after-index", + "operation": "refresh" + }, + { + "operation": { + "operation-type": "force-merge", + "request-timeout": 7200 + {% raw %}{%- if force_merge_max_num_segments is defined %}{% endraw %}, + "max-num-segments": {% raw %}{{ force_merge_max_num_segments | tojson }}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + } + }, + { + "name": "refresh-after-force-merge", + "operation": "refresh" + }, + { + "operation": "wait-until-merges-finish" + }, + { + "operation": "create-snapshot-repository" + }, + { + "operation": "delete-snapshot" + }, + { + "operation": "create-snapshot" + }, + { + "operation": "wait-for-snapshot-creation" + }, + { + "operation": { + "name": "delete-local-index", + "operation-type": "delete-index" + } + }, + { + "operation": "restore-snapshot" + }, + { + "operation": "default", + "warmup-iterations": 50, + "iterations": 100 + {% raw %}{%- if not target_throughput %}{% endraw %} + ,"target-throughput": 3 + {% raw %}{%- elif target_throughput is string and target_throughput.lower() == 'none' %}{% endraw %} + {% raw %}{%- else %}{% endraw %} + ,"target-throughput": {% raw %}{{ target_throughput | tojson }}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + {% raw %}{%-if search_clients is defined and search_clients %}{% endraw %} + ,"clients": {% raw %}{{ search_clients | tojson}}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + }, + { + "operation": "range", + "warmup-iterations": 50, + "iterations": 100 + {% raw %}{%- if not target_throughput %}{% endraw %} + ,"target-throughput": 0.7 + {% raw %}{%- elif target_throughput is string and target_throughput.lower() == 'none' %}{% endraw %} + {% raw %}{%- else %}{% endraw %} + ,"target-throughput": {% raw %}{{ target_throughput | tojson }}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + {% raw %}{%-if search_clients is defined and search_clients %}{% endraw %} + ,"clients": {% raw %}{{ search_clients | tojson}}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + }, + { + "operation": "distance_amount_agg", + "warmup-iterations": 50, + "iterations": 50 + {% raw %}{%- if not target_throughput %}{% endraw %} + ,"target-throughput": 2 + {% raw %}{%- elif target_throughput is string and target_throughput.lower() == 'none' %}{% endraw %} + {% raw %}{%- else %}{% endraw %} + ,"target-throughput": {% raw %}{{ target_throughput | tojson }}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + {% raw %}{%-if search_clients is defined and search_clients %}{% endraw %} + ,"clients": {% raw %}{{ search_clients | tojson}}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + }, + { + "operation": "autohisto_agg", + "warmup-iterations": 50, + "iterations": 100 + {% raw %}{%- if not target_throughput %}{% endraw %} + ,"target-throughput": 1.5 + {% raw %}{%- elif target_throughput is string and target_throughput.lower() == 'none' %}{% endraw %} + {% raw %}{%- else %}{% endraw %} + ,"target-throughput": {% raw %}{{ target_throughput | tojson }}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + {% raw %}{%-if search_clients is defined and search_clients %}{% endraw %} + ,"clients": {% raw %}{{ search_clients | tojson}}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + }, + { + "operation": "date_histogram_agg", + "warmup-iterations": 50, + "iterations": 100 + {% raw %}{%- if not target_throughput %}{% endraw %} + ,"target-throughput": 1.5 + {% raw %}{%- elif target_throughput is string and target_throughput.lower() == 'none' %}{% endraw %} + {% raw %}{%- else %}{% endraw %} + ,"target-throughput": {% raw %}{{ target_throughput | tojson }}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + {% raw %}{%-if search_clients is defined and search_clients %}{% endraw %} + ,"clients": {% raw %}{{ search_clients | tojson}}{% endraw %} + {% raw %}{%- endif %}{% endraw %} + } + ] + } +``` + +## Workload examples + +The following examples show complete `workload.json` files that you can adapt for your own workloads. + +### Running unthrottled + +In the following example, OpenSearch Benchmark runs an unthrottled bulk index operation for 1 hour against the `movies` index: + +```json +{ + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": "bulk", + "warmup-time-period": 120, + "time-period": 3600, + "clients": 8 + } +] +} +``` + +### Workload with a single task + +The following workload runs a benchmark with a single task: a `match_all` query. Because no `clients` are indicated, only one client is used. According to the [`schedule`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/schedule/), the workload runs the `match_all` query at 10 operations per second with 1 client, uses 100 iterations to warm up, and uses the next 100 iterations to measure the benchmark: + +```json +{ + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "search", + "index": "_all", + "body": { + "query": { + "match_all": {} + } + } + }, + "warmup-iterations": 100, + "iterations": 100, + "target-throughput": 10 + } + ] +} +``` + +## Next steps + +- For the data, cluster requirements, and query types of each prepackaged workload, see [Workload types]({{site.url}}{{site.baseurl}}/benchmark/workload-types/). +- For information about creating your own workload, see [Creating custom workloads]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/). diff --git a/_benchmark/choosing-a-workload.md b/_benchmark/choosing-a-workload.md new file mode 100644 index 00000000..9e7d2370 --- /dev/null +++ b/_benchmark/choosing-a-workload.md @@ -0,0 +1,26 @@ +--- +layout: default +title: Choosing a workload +nav_order: 15 +redirect_from: + - /benchmark/user-guide/understanding-workloads/choosing-a-workload/ +--- + +# Choosing a workload + +The [`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) repository contains a list of workloads that you can use to run your benchmarks. Using a workload similar to your cluster's use cases can save you time and effort when assessing your cluster's performance. + +For example, say you're a system architect at a ride share company. As a ride share company, you collect and store data based on trip times, locations, and other data related to each ride share. Instead of building a custom workload and using your own data, which requires additional time, effort, and cost, you can use the [nyc_taxis](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/nyc_taxis) workload to benchmark your cluster because the data inside the workload is similar to the data that you collect. + +## Criteria for choosing a workload + +Consider the following criteria when deciding which workload would work best for benchmarking your cluster: + +- The cluster's use case and the size of the cluster. Small clusters usually contain 1--10 nodes and are suitable for development environments. Medium clusters usually contain 11--50 nodes and are used for testing environments that more closely resemble a production cluster. +- The data types that your cluster uses compared to the data structure of the documents contained in the workload. Each workload contains an example document so that you can compare data types, or you can view the index mappings and data types in the `index.json` file. +- The query types most commonly used inside your cluster. The `operations/default.json` file contains information about the query types and workload operations. For a list of common operations, see [Common operations]({{site.url}}{{site.baseurl}}/benchmark/common-operations/). + +## Next steps + +- For the data, cluster requirements, and query types of each prepackaged workload, see [Workload types]({{site.url}}{{site.baseurl}}/benchmark/workload-types/). +- If you can't find an official workload that suits your needs, you can create a custom workload. For more information, see [Creating custom workloads]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/). diff --git a/_benchmark/common-operations.md b/_benchmark/common-operations.md new file mode 100644 index 00000000..305e4aa5 --- /dev/null +++ b/_benchmark/common-operations.md @@ -0,0 +1,182 @@ +--- +layout: default +title: Common operations +nav_order: 25 +redirect_from: + - /benchmark/user-guide/understanding-workloads/common-operations/ +--- + +# Common operations + +[Test procedures]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/test-procedures/) use a variety of operations, found inside the `operations` directory of a workload. This page details the most common operations found inside OpenSearch Benchmark workloads. + +- [Common operations](#common-operations) + - [bulk](#bulk) + - [create-index](#create-index) + - [delete-index](#delete-index) + - [cluster-health](#cluster-health) + - [refresh](#refresh) + - [search](#search) + + +## bulk + + +The `bulk` operation type allows you to run [bulk](/api-reference/document-apis/bulk/) requests as a task. + +The following example shows a `bulk` operation type with a `bulk-size` of `5000` documents: + +```yml +{ + "name": "index-append", + "operation-type": "bulk", + "bulk-size": 5000 +} +``` + + + +## create-index + + +The `create-index` operation runs the [Create Index API](/api-reference/index-apis/create-index/). It supports the following two modes of index creation: + +- Creating all indexes specified in the workloads `indices` section +- Creating one specific index defined within the operation itself + +The following example creates all indexes defined in the `indices` section of the workload. It uses all of the index settings defined in the workload but overrides the number of shards: + +```yml +{ + "name": "create-all-indices", + "operation-type": "create-index", + "settings": { + "index.number_of_shards": 1 + }, + "request-params": { + "wait_for_active_shards": "true" + } +} +``` + +The following example creates a new index with all index settings specified in the operation body: + +```yml +{ + "name": "create-an-index", + "operation-type": "create-index", + "index": "people", + "body": { + "settings": { + "index.number_of_shards": 0 + }, + "mappings": { + "docs": { + "properties": { + "name": { + "type": "text" + } + } + } + } + } +} +``` + + + + +## delete-index + + +The `delete-index` operation runs the [Delete Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-index/). Like with the [`create-index`](#create-index) operation, you can delete all indexes found in the `indices` section of the workload or delete one or more indexes based on the string passed in the `index` setting. + +The following example deletes all indexes found in the `indices` section of the workload: + +```yml +{ + "name": "delete-all-indices", + "operation-type": "delete-index" +} +``` + +The following example deletes all `logs_*` indexes: + +```yml +{ + "name": "delete-logs", + "operation-type": "delete-index", + "index": "logs-*", + "only-if-exists": false, + "request-params": { + "expand_wildcards": "all", + "allow_no_indices": "true", + "ignore_unavailable": "true" + } +} +``` + + +## cluster-health + + +The `cluster-health` operation runs the [Cluster Health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/), which checks the cluster health status and returns the expected status according to the parameters set for `request-params`. If an unexpected cluster health status is returned, the operation reports a failure. You can use the `--on-error` option in the OpenSearch Benchmark `run` command to control how OpenSearch Benchmark behaves when the health check fails. + + +The following example creates a `cluster-health` operation that checks for a `green` health status on any `log-*` indexes: + +```yml +{ + "name": "check-cluster-green", + "operation-type": "cluster-health", + "index": "logs-*", + "request-params": { + "wait_for_status": "green", + "wait_for_no_relocating_shards": "true" + }, + "retry-until-success": true +} + +``` + + +## refresh + + +The `refresh` operation runs the Refresh API. The `operation` returns no metadata. + + +The following example refreshes all `logs-*` indexes: + +```yml +{ + "name": "refresh", + "operation-type": "refresh", + "index": "logs-*" +} +``` + + + +## search + + +The `search` operation runs the [Search API](/api-reference/search/), which you can use to run queries in OpenSearch Benchmark indexes. + +The following example runs a `match_all` query inside the `search` operation: + +```yml +{ + "name": "default", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + }, + "request-params": { + "_source_include": "some_field", + "analyze_wildcard": "false" + } +} +``` diff --git a/_benchmark/contributing-workloads.md b/_benchmark/contributing-workloads.md new file mode 100644 index 00000000..a641ba15 --- /dev/null +++ b/_benchmark/contributing-workloads.md @@ -0,0 +1,60 @@ +--- +layout: default +title: Sharing custom workloads +parent: Creating custom workloads +nav_order: 20 +redirect_from: + - /benchmark/user-guide/contributing-workloads/ + - /benchmark/user-guide/working-with-workloads/contributing-workloads/ +--- + +# Sharing custom workloads + +You can share a custom workload with other OpenSearch users by uploading it to the [workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads/) on GitHub. + +Make sure that any data included in the workload's dataset does not contain proprietary data or personally identifiable information (PII). + +To share a custom workload, follow these steps. + +## Create a README.md + +Provide a detailed `README.MD` file that includes the following: + +- The purpose of the workload. When creating a description for the workload, consider its specific use and how the that use case differs from others in the [workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads/). +- An example document from the dataset that helps users understand the data structure. +- The workload parameters that can be used to customize the workload. +- A list of default test procedures included in the workload as well as other test procedures that the workload can run. +- An output sample produced by the workload after a test is run. +- A copy of the open-source license that gives the user and OpenSearch Benchmark permission to use the dataset. + +For an example workload `README` file, go to the `http_logs` [`README`](https://github.com/opensearch-project/opensearch-benchmark-workloads/blob/main/http_logs/README.md). + +## Verify the workload's structure + +The workload must include the following files: + +- `workload.json` +- `index.json` +- `files.txt` +- `test_procedures/default.json` +- `operations/default.json` + +Both `default.json` file names can be customized to have a descriptive name. The workload can include an optional `workload.py` file to add more dynamic functionality. For more information about a file's contents, go to [Anatomy of a workload]({{site.url}}{{site.baseurl}}/benchmark/anatomy-of-a-workload/). + +## Testing the workload + +All workloads contributed to OpenSearch Benchmark must fulfill the following testing requirements: + +- All tests run to explore and produce an example from the workload must target an OpenSearch cluster. +- The workload must pass all integration tests. Follow these steps to ensure that the workload passes the integration tests: + 1. Add the workload to your forked copy of the [workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads/). Make sure that you've forked both the `opensearch-benchmark-workloads` repository and the [OpenSeach Benchmark](https://github.com/opensearch-project/opensearch-benchmark) repository. + 3. In your forked OpenSearch Benchmark repository, update the `benchmark-os-it.ini` and `benchmark-in-memory.ini` files in the `/osbenchmark/it/resources` directory to point to the forked workloads repository containing your workload. + 4. After you've modified the `.ini` files, commit your changes to a branch for testing. + 6. Run your integration tests using GitHub actions by selecting the branch for which you committed your changes. Verify that the tests have run as expected. + 7. If your integration tests run as expected, go to your forked workloads repository and merge your workload changes into branches `1` and `2`. This allows for your workload to appear in both major versions of OpenSearch Benchmark. + +## Create a PR + +After testing the workload, create a pull request (PR) from your fork to the `opensearch-project` [workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads/). Add a sample output and summary result to the PR description. The OpenSearch Benchmark maintainers will review the PR. + +Once the PR is approved, you must share the data corpora of your dataset. The OpenSearch Benchmark team can then add the dataset to a shared S3 bucket. If your data corpora is stored in an S3 bucket, you can use [AWS DataSync](https://docs.aws.amazon.com/datasync/latest/userguide/create-s3-location.html) to share the data corpora. Otherwise, you must inform the maintainers of where the data corpora resides. diff --git a/_benchmark/creating-custom-workloads.md b/_benchmark/creating-custom-workloads.md new file mode 100644 index 00000000..8171084a --- /dev/null +++ b/_benchmark/creating-custom-workloads.md @@ -0,0 +1,384 @@ +--- +layout: default +title: Creating custom workloads +nav_order: 35 +has_children: true +has_toc: false +redirect_from: + - /benchmark/user-guide/creating-custom-workloads/ + - /benchmark/user-guide/creating-osb-workloads/ + - /benchmark/user-guide/working-with-workloads/creating-custom-workloads/ +--- + +# Creating custom workloads + +OpenSearch Benchmark includes a set of [workloads](https://github.com/opensearch-project/opensearch-benchmark-workloads) that you can use to benchmark data from your cluster. You can also create a workload that is tailored to your own data by using one of the following options: + +- [Creating a workload from an existing cluster](#creating-a-workload-from-an-existing-cluster) +- [Creating a workload without an existing cluster](#creating-a-workload-without-an-existing-cluster) + +## Creating a workload from an existing cluster + +If you already have an OpenSearch cluster with indexed data, use the following steps to create a custom workload for your cluster. + +### Prerequisites + +Before creating a custom OpenSearch Benchmark workload, make sure you have the following prerequisites in place: + +- An OpenSearch cluster with an index that contains 1000 or more documents. If your cluster's index does not contain at least 1000 documents, the workload can still run tests, however, you cannot run workloads using `--test-mode`. +- You must have the correct permissions to access your OpenSearch cluster. For more information about cluster permissions, see [Permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/). + +### Customizing the workload + +To begin creating a custom OpenSearch Benchmark workload, use the `opensearch-benchmark create-workload` command. + +```bash +opensearch-benchmark create-workload \ +--workload="" \ +--target-hosts="" \ +--client-options="basic_auth_user:'',basic_auth_password:''" \ +--indices="" \ +--output-path="" +``` + +Replace the following options in the preceding example with information specific to your existing cluster: + +- `--workload`: A custom name for your custom workload. +- `--target-hosts:` A comma-separated list of host:port pairs from which the cluster extracts data. +- `--client-options`: The basic authentication client options that OpenSearch Benchmark uses to access the cluster. +- `--indices`: One or more indexes inside your OpenSearch cluster that contain data. +- `--output-path`: The directory in which OpenSearch Benchmark creates the workload and its configuration files. + +The following example response creates a workload named `movies` from a cluster with an index named `movies-info`. The `movies-info` index contains over 2,000 documents. + +```bash + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +[INFO] You did not provide an explicit timeout in the client options. Assuming default of 10 seconds. +[INFO] Connected to OpenSearch cluster [380d8fd64dd85b5f77c0ad81b0799e1e] version [1.1.0]. + +Extracting documents for index [movies] for test mode... 1000/1000 docs [100.0% done] +Extracting documents for index [movies]... 2000/2000 docs [100.0% done] + +[INFO] Workload movies has been created. Run it with: opensearch-benchmark --workload-path=/Users/hoangia/Desktop/workloads/movies + +----------------------------------- +[INFO] ✅ SUCCESS (took 2 seconds) +----------------------------------- +``` + +As part of workload creation, OpenSearch Benchmark generates the following files. You can access them in the directory specified by the `--output-path` option. + +- `workload.json`: Contains general workload specifications. +- `.json`: Contains mappings and settings for the extracted indexes. +- `-documents.json`: Contains the sources of every document from the extracted indexes. Any sources suffixed with `-1k` encompass only a fraction of the document corpus of the workload and are only used when running the workload in test mode. + +By default, OpenSearch Benchmark does not contain a reference to generate queries. Because you have the best understanding of your data, we recommend adding a query to `workload.json` that matches your index's specifications. Use the following `match_all` query as an example of a query added to your workload: + +```json +{ + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } +``` + +### Creating a workload without an existing cluster + +If you want to create a custom workload but do not have an existing OpenSearch cluster with indexed data, you can create the workload by building the workload source files directly. All you need is data that can be exported into a JSON format. + +To build a workload with source files, create a directory for your workload and perform the following steps: + +1. Build a `-documents.json` file that contains rows of documents that comprise the document corpora of the workload and houses all data to be ingested and queried into the cluster. The following example shows the first few rows of a `movies-documents.json` file that contains rows of documents about famous movies: + + ```json + {"title": "Back to the Future", "director": "Robert Zemeckis", "revenue": "$212,259,762 USD", "rating": "8.5 out of 10", "image_url": "https://imdb.com/images/32"} + {"title": "Avengers: Endgame", "director": "Anthony and Joe Russo", "revenue": "$2,800,000,000 USD", "rating": "8.4 out of 10", "image_url": "https://imdb.com/images/2"} + {"title": "The Grand Budapest Hotel", "director": "Wes Anderson", "revenue": "$173,000,000 USD", "rating": "8.1 out of 10", "image_url": "https://imdb.com/images/65"} + {"title": "The Godfather: Part II", "director": "Francis Ford Coppola", "revenue": "$48,000,000 USD", "rating": "9 out of 10", "image_url": "https://imdb.com/images/7"} + ``` + +2. In the same directory, build a `index.json` file. The workload uses this file as a reference for data mappings and index settings for the documents contained in `-documents.json`. The following example creates mappings and settings specific to the `movie-documents.json` data from the previous step: + + ```json + { + "settings": { + "index.number_of_replicas": 0 + }, + "mappings": { + "dynamic": "strict", + "properties": { + "title": { + "type": "text" + }, + "director": { + "type": "text" + }, + "revenue": { + "type": "text" + }, + "rating": { + "type": "text" + }, + "image_url": { + "type": "text" + } + } + } + } + ``` + +3. Next, build a `workload.json` file that provides a high-level overview of your workload and determines how your workload runs benchmark tests. The `workload.json` file contains the following sections: + + - `indices`: Defines the name of the index to be created in your OpenSearch cluster using the mappings from the workload's `index.json` file created in the previous step. + - `corpora`: Defines the corpora and the source file, including the: + - `document-count`: The number of documents in `-documents.json`. To get an accurate number of documents, run `wc -l -documents.json`. + - `uncompressed-bytes`: The number of bytes inside the index. To get an accurate number of bytes, run `stat -f %z -documents.json` on macOS or `stat -c %s -documents.json` on GNU/Linux. Alternatively, run `ls -lrt | grep -documents.json`. + - `schedule`: Defines the sequence of operations and available test procedures for the workload. + +The following example `workload.json` file provides the entry point for the `movies` workload. The `indices` section creates an index called `movies`. The corpora section refers to the source file created in step one, `movie-documents.json`, and provides the document count and the amount of uncompressed bytes. Lastly, the schedule section defines a few operations the workload performs when invoked, including: + +- Deleting any current index named `movies`. +- Creating an index named `movies` based on data from `movie-documents.json` and the mappings from `index.json`. +- Verifying that the cluster is in good health and can ingest the new index. +- Ingesting the data corpora from `workload.json` into the cluster. +- Querying the results. + + ```json + { + "version": 2, + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "delete-index" + } + }, + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "operation-type": "force-merge" + } + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } + ``` + +The corpora section refers to the source file created in step one, `movie-documents.json`, and provides the document count and the amount of uncompressed bytes. Lastly, the schedule section defines a few operations the workload performs when invoked, including: + +- Deleting any current index named `movies`. +- Creating an index named `movies` based on data from `movie-documents.json` and the mappings from `index.json`. + - Verifying that the cluster is in good health and can ingest the new index. + - Ingesting the data corpora from `workload.json` into the cluster. + - Querying the results. + + + +For all the workload files created, verify that the workload is functional by running a test. To verify the workload, run the following command, replacing `--workload-path` with a path to your workload directory: + +```bash +opensearch-benchmark list workloads --workload-path= +``` + +## Invoking your custom workload + +Use the `opensearch-benchmark run` command to invoke your new workload and run a benchmark test against your OpenSearch cluster, as shown in the following example. Replace `--workload-path` with the path to your custom workload, `--target-host` with the `host:port` pairs for your cluster, and `--client-options` with any authorization options required to access the cluster. + +```bash +opensearch-benchmark run \ +--pipeline="benchmark-only" \ +--workload-path="" \ +--target-host="" \ +--client-options="basic_auth_user:'',basic_auth_password:''" +``` + +Results from the test appear in the directory set by `--output-path` option in `workloads.json`. + +## Advanced options + +You can enhance your custom workload's functionality with the following advanced options. + +### Test mode + +If you want to run the test in test mode to make sure your workload operates as intended, add the `--test-mode` option to the `run` command. Test mode ingests only the first 1,000 documents from each index provided and runs query operations against them. + +To use test mode, create a `-documents-1k.json` file that contains the first 1000 documents from `-documents.json` using the following command: + +```bash +head -n 1000 -documents.json > -documents-1k.json +``` + +Then, run `opensearch-benchmark run` with the option `--test-mode`. Test mode runs a quick version of the workload test. + +```bash +opensearch-benchmark run \ +--pipeline="benchmark-only" \ +--workload-path="" \ +--target-host="" \ +--client-options"basic_auth_user:'',basic_auth_password:''" \ +--test-mode +``` + +### Adding variance to test procedures + +After using your custom workload several times, you might want to use the same workload but perform the workload's operations in a different order. Instead of creating a new workload or reorganizing the procedures directly, you can provide test procedures to vary workload operations. + +To add variance to your workload operations, go to your `workload.json` file and replace the `schedule` section with a `test_procedures` array, as shown in the following example. Each item in the array contains the following: + +- `name`: The name of the test procedure. +- `default`: When set to `true`, OpenSearch Benchmark defaults to the test procedure specified as `default` in the workload if no other test procedures are specified. +- `schedule`: All the operations the test procedure will run. + + +```json +"test_procedures": [ + { + "name": "index-and-query", + "default": true, + "schedule": [ + { + "operation": { + "operation-type": "delete-index" + } + }, + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "operation-type": "force-merge" + } + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } + ] +} +``` + +### Separate operations and test procedures + +If you want to make your `workload.json` file more readable, you can separate your operations and test procedures into different directories and reference the path to each in `workload.json`. To separate operations and procedures, perform the following steps: + +1. Add all test procedures to a single file. You can give the file any name. Because the `movies` workload in the preceding contains and index task and queries, this step names the test procedures file `index-and-query.json`. +2. Add all operations to a file named `operations.json`. +3. Reference the new files in `workloads.json` by adding the following syntax, replacing `parts` with the relative path to each file, as shown in the following example: + + ```json + "operations": [ + {% raw %}{{ benchmark.collect(parts="operations/*.json") }}{% endraw %} + ] + # Reference test procedure files in workload.json + "test_procedures": [ + {% raw %}{{ benchmark.collect(parts="test_procedures/*.json") }}{% endraw %} + ] + ``` + +## Next steps + +- To adjust your workload so that it more closely reflects your production environment, see [Fine-tuning custom workloads]({{site.url}}{{site.baseurl}}/benchmark/finetune-workloads/). +- To contribute your workload to the OpenSearch Project, see [Sharing custom workloads]({{site.url}}{{site.baseurl}}/benchmark/contributing-workloads/). +- For more information about configuring OpenSearch Benchmark, see [Configuring OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/). +- To show a list of prepackaged workloads for OpenSearch Benchmark, see the [`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) repository. diff --git a/_benchmark/distributed-load.md b/_benchmark/distributed-load.md new file mode 100644 index 00000000..85963e09 --- /dev/null +++ b/_benchmark/distributed-load.md @@ -0,0 +1,72 @@ +--- +layout: default +title: Running distributed loads +nav_order: 32 +redirect_from: + - /benchmark/user-guide/optimizing-benchmarks/distributed-load/ + - /benchmark/user-guide/distributed-load/ +--- + +# Running distributed loads + +OpenSearch Benchmark loads always run on the same machine on which the benchmark was started. However, you can use multiple load drivers to generate additional benchmark testing loads, particularly for large clusters on multiple machines. This tutorial describes how to distribute benchmark loads across multiple machines in a single cluster. + +## System architecture + +The following tutorial uses a three-node architecture; each node is generated in [Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/ec2/?nc2=h_ql_doc_ec2): + +- **Node 1**: Node 1 acts as the _coordinating node_ and enables distribution and communication between the other two nodes. +- **Node 2** and **Node 3**: The remaining nodes in the cluster are used to generate the load for the benchmark test. + +OpenSearch Benchmark must be installed on all nodes. For installation instructions, see [Installing OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/user-guide/installing-benchmark/). + +Make note of each node's IP address. This tutorial uses the following IP addresses: + +- **Node 1 -- Coordinating node**: 192.0.1.0 +- **Node 2 -- Worker node**: 198.52.100.0 +- **Node 3 -- Worker node**: 198.53.100.0 + +## Step 1: Enable node communication + +Make sure to enable communication for each node. In the AWS Management Console: + +1. Go to the EC2 host for the node. +2. Select **Security**, and then select the security group associated with the node. +3. Use **Add inbound rules** to open traffic to the node, based on the port range and traffic type of your cluster. + +## Step 2: Run daemon processes on each node + +Start OpenSearch Benchmark on each node, using `--node-ip` to initialize OpenSearch Benchmark on the node itself and then `--coordinator-ip` to connect each node to the coordinating node. + +For **Node 1**, the following command identifies the node as the coordinating node: + +``` +opensearch-benchmarkd start --node-ip=192.0.1.0 --coordinator-ip=192.0.1.0 +``` + +The following commands enable **Node 2** and **Node 3** to listen to the coordinating node for load generation instructions. + +**Node 2** + +``` +opensearch-benchmarkd start --node-ip=198.52.100.0 --coordinator-ip=192.0.1.0 +``` + +**Node 3** + +``` +opensearch-benchmarkd start --node-ip=198.53.100.0 --coordinator-ip=192.0.1.0 +``` + +With OpenSearch Benchmark running on all three nodes and the worker nodes set to listen to the coordinating node, you can now run the benchmark test. + +## Step 3: Run the benchmark test + +On **Node 1**, run a benchmark test with the `worker-ips` set to the IP addresses for your worker nodes, as shown in the following example: + +``` +opensearch-benchmark run --pipeline=benchmark-only --workload=eventdata --worker-ips=198.52.100.0,198.53.100.0 --target-hosts= --client-options= --kill-running-processes +``` + +After the test completes, the logs generated by the test appear on your worker nodes. + diff --git a/_benchmark/expand-data-corpus.md b/_benchmark/expand-data-corpus.md new file mode 100644 index 00000000..913aee39 --- /dev/null +++ b/_benchmark/expand-data-corpus.md @@ -0,0 +1,83 @@ +--- +layout: default +title: Expanding a workload's data corpus +nav_order: 55 +redirect_from: + - /benchmark/user-guide/optimizing-benchmarks/expand-data-corpus/ +--- + +# Expanding a workload's data corpus + +This tutorial shows you how to use the [`expand-data-corpus.py`](https://github.com/opensearch-project/opensearch-benchmark/blob/main/scripts/expand-data-corpus.py) script to increase the size of the data corpus for an OpenSearch Benchmark workload. This can be helpful when running the `http_logs` workload against a large OpenSearch cluster. + +This script only works with the `http_logs` workload. +{: .warning} + +## Prerequisites + +To use this tutorial, make sure you fulfill the following prerequisites: + +1. You have installed Python 3.x or later. +2. The `http_logs` workload data corpus is already stored on the load generation host running OpenSearch Benchmark. + +## Understanding the script + +The `expand-data-corpus.py` script is designed to generate a larger data corpus by duplicating and modifying existing documents from the `http_logs` workload corpus. It primarily adjusts the timestamp field while keeping other fields intact. It also generates an offset file, which enables OpenSearch Benchmark to start up faster. + +## Using `expand-data-corpus.py` + +To use `expand-data-corpus.py`, use the following syntax: + +```bash +./expand-data-corpus.py [options] +``` + +The script provides several customization options. The following are the most commonly used options: + +- `--corpus-size`: The desired corpus size in GB +- `--output-file-suffix`: The suffix for the output file name. + +## Example + +The following example script command generates a 100 GB corpus: + +```bash +./expand-data-corpus.py --corpus-size 100 --output-file-suffix 100gb +``` + +The script will start generating documents. For a 100 GB corpus, it can take up to 30 minutes to generate the full corpus. + +You can generate multiple corpora by running the script multiple times with different output suffixes. All corpora generated by the script are used by OpenSearch Benchmark sequentially during injection. + +## Verifying the documents + +After the script completes, check the following locations for new files: + +- In the OpenSearch Benchmark data directory for `http_logs`: + - `documents-100gb.json`: The generated corpus + - `documents-100gb.json.offset`: The associated offset file + +- In the `http_logs` workload directory: + - `gen-docs-100gb.json`: The metadata for the generated corpus + - `gen-idx-100gb.json`: The index specification for the generated corpus + +## Using the corpus in a test + +To use the newly generated corpus in an OpenSearch Benchmark test, use the following syntax: + +```bash +opensearch-benchmark run --workload http_logs --workload-params=generated_corpus:t [other_options] +``` + +The `generated_corpus:t` parameter tells OpenSearch Benchmark to use the expanded corpus. Any additional workload parameters can be appended using commas in the `--workload-params` option. + +## Expert-level settings + +Use `--help` to see all of the script's supported options. Be cautious when using the following expert-level settings because they may affect the corpus structure: + +- `-f`: Specifies the input file to use as a base for generating new documents +- `-n`: Sets the number of documents to generate instead of the corpus size +- `-i`: Defines the interval between consecutive timestamps +- `-t`: Sets the starting timestamp for the generated documents +- `-b`: Defines the number of documents per batch when writing to the offset file + diff --git a/_benchmark/features/index.md b/_benchmark/features/index.md new file mode 100644 index 00000000..e402d01b --- /dev/null +++ b/_benchmark/features/index.md @@ -0,0 +1,19 @@ +--- +layout: default +title: Additional features +nav_order: 80 +has_children: true +has_toc: false +redirect_from: + - /benchmark/features/ +more_cards: + - heading: "Synthetic data generation" + description: "Create synthetic datasets using index mappings or custom Python logic for comprehensive benchmarking and testing." + link: "/benchmark/features/synthetic-data-generation/" +--- + +# Additional features + +In addition to general benchmarking, OpenSearch Benchmark provides several specialized features. + +{% include cards.html cards=page.more_cards %} \ No newline at end of file diff --git a/_benchmark/features/synthetic-data-generation/custom-logic-sdg.md b/_benchmark/features/synthetic-data-generation/custom-logic-sdg.md new file mode 100644 index 00000000..c595ed6f --- /dev/null +++ b/_benchmark/features/synthetic-data-generation/custom-logic-sdg.md @@ -0,0 +1,257 @@ +--- +layout: default +title: Generating data using custom logic +nav_order: 35 +parent: Synthetic data generation +grand_parent: Additional features +--- + +# Generating data using custom logic + +You can generate synthetic data using custom logic defined in a Python module. This approach offers you the most granular control over how synthetic data is produced in OpenSearch Benchmark. This is especially useful if you understand the distribution of your data and the relationship between different fields. + +## The generate_synthetic_document function + +Every custom module provided to OpenSearch Benchmark must define the `generate_synthetic_document(providers, **custom_lists)` function. This function defines how OpenSearch Benchmark generates each synthetic document. + +### Function parameters + +| Parameter | Required/Optional | Description | +|---|---|---| +| `providers` | Required | A dictionary containing data generation tools. Available providers are `generic` (Mimesis [Generic provider](https://mimesis.name/master/api.html#generic-providers)) and `random` (Mimesis [Random class](https://mimesis.name/master/random_and_seed.html)). To add custom providers, see [Advanced configuration](#advanced-configuration). | +| `custom_lists` | Optional | Keyword arguments containing predefined lists of values that you can use in your data generation logic. These are defined in your YAML configuration file under `custom_lists` and allow you to separate data values from your Python code. For example, if you define `dog_names: [Buddy, Max, Luna]` in YAML, you can access it as `custom_lists['dog_names']` in your function. This makes it easy to modify data values without changing your Python code. | + +### Basic function template + +```python +def generate_synthetic_document(providers, **custom_lists): + # Access the available providers + generic = providers['generic'] + random_provider = providers['random'] + + # Generate a document using the providers + document = { + 'name': generic.person.full_name(), + 'age': random_provider.randint(18, 80), + 'email': generic.person.email(), + 'timestamp': generic.datetime.datetime() + } + + # Optionally, use custom lists if provided + if 'categories' in custom_lists: + document['category'] = random_provider.choice(custom_lists['categories']) + + return document +``` +{% include copy.html %} + +For more information, see the [Mimesis documentation](https://mimesis.name/master/api.html). + +## Python module example + +The following example Python module demonstrates custom logic for generating documents about dog drivers for a fictional ride-sharing company, *Pawber*, which uses OpenSearch to store and search large volumes of ride-sharing data. + +This example showcases several advanced concepts: +- **[Custom provider classes](#advanced-configuration)** (`NumericString`, `MultipleChoices`) that extend Mimesis functionality +- **[Custom lists](#advanced-configuration)** for data values like dog names, breeds, and treats (referenced as `custom_lists['dog_names']`) +- **Geographic clustering** logic for realistic location data +- **Complex document structures** with nested objects and relationships + +Save this code to a file called `pawber.py` in your desired directory (for example, `~/pawber.py`): + +```python +from mimesis.providers.base import BaseProvider +from mimesis.enums import TimestampFormat + +import random + +GEOGRAPHIC_CLUSTERS = { + 'Manhattan': { + 'center': {'lat': 40.7831, 'lon': -73.9712}, + 'radius': 0.05 # degrees + }, + 'Brooklyn': { + 'center': {'lat': 40.6782, 'lon': -73.9442}, + 'radius': 0.05 + }, + 'Austin': { + 'center': {'lat': 30.2672, 'lon': -97.7431}, + 'radius': 0.1 # Increased radius to cover more of Austin + } +} + +def generate_location(cluster): + """Generate a random location within a cluster""" + center = GEOGRAPHIC_CLUSTERS[cluster]['center'] + radius = GEOGRAPHIC_CLUSTERS[cluster]['radius'] + lat = center['lat'] + random.uniform(-radius, radius) + lon = center['lon'] + random.uniform(-radius, radius) + return {'lat': lat, 'lon': lon} + +class NumericString(BaseProvider): + class Meta: + name = "numeric_string" + + @staticmethod + def generate(length=5) -> str: + return ''.join([str(random.randint(0, 9)) for _ in range(length)]) + +class MultipleChoices(BaseProvider): + class Meta: + name = "multiple_choices" + + @staticmethod + def generate(choices, num_of_choices=5) -> str: + import logging + logger = logging.getLogger(__name__) + logger.info("Choices: %s", choices) + logger.info("Length: %s", num_of_choices) + total_choices_available = len(choices) - 1 + + return [choices[random.randint(0, total_choices_available)] for _ in range(num_of_choices)] + +def generate_synthetic_document(providers, **custom_lists): + generic = providers['generic'] + random_mimesis = providers['random'] + + first_name = generic.person.first_name() + last_name = generic.person.last_name() + city = random.choice(list(GEOGRAPHIC_CLUSTERS.keys())) + + # Driver Document + document = { + "dog_driver_id": f"DD{generic.numeric_string.generate(length=4)}", + "dog_name": random_mimesis.choice(custom_lists['dog_names']), + "dog_breed": random_mimesis.choice(custom_lists['dog_breeds']), + "license_number": f"{random_mimesis.choice(custom_lists['license_plates'])}{generic.numeric_string.generate(length=4)}", + "favorite_treats": random_mimesis.choice(custom_lists['treats']), + "preferred_tip": random_mimesis.choice(custom_lists['tips']), + "vehicle_type": random_mimesis.choice(custom_lists['vehicle_types']), + "vehicle_make": random_mimesis.choice(custom_lists['vehicle_makes']), + "vehicle_model": random_mimesis.choice(custom_lists['vehicle_models']), + "vehicle_year": random_mimesis.choice(custom_lists['vehicle_years']), + "vehicle_color": random_mimesis.choice(custom_lists['vehicle_colors']), + "license_plate": random_mimesis.choice(custom_lists['license_plates']), + "current_location": generate_location(city), + "status": random.choice(['available', 'busy', 'offline']), + "current_ride": f"R{generic.numeric_string.generate(length=6)}", + "account_status": random_mimesis.choice(custom_lists['account_status']), + "join_date": generic.datetime.formatted_date(), + "total_rides": generic.numeric.integer_number(start=1, end=200), + "rating": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "earnings": { + "today": { + "amount": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "currency": "USD" + }, + "this_week": { + "amount": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "currency": "USD" + }, + "this_month": { + "amount": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "currency": "USD" + } + }, + "last_grooming_check": "2023-12-01", + "owner": { + "first_name": first_name, + "last_name": last_name, + "email": f"{first_name}{last_name}@gmail.com" + }, + "special_skills": generic.multiple_choices.generate(custom_lists['skills'], num_of_choices=3), + "bark_volume": generic.numeric.float_number(start=1.0, end=10.0, precision=2), + "tail_wag_speed": generic.numeric.float_number(start=1.0, end=10.0, precision=1) + } + + return document +``` +{% include copy.html %} + +## Generating data + +To generate synthetic data using custom logic, use the `generate-data` subcommand and provide the required custom Python module, index name, output path, and total amount of data to generate: + +```shell +osb generate-data --custom-module ~/pawber.py --index-name pawber-data --output-path ~/Desktop/sdg_outputs/ --total-size 2 +``` +{% include copy.html %} + +For a complete list of available parameters and their descriptions, see the [`generate-data` command reference]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/generate-data/). + +## Example output + +The following is an example output when generating 100 GB of data: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + + +[NOTE] ✨ Dashboard link to monitor processes and task streams: [http://127.0.0.1:8787/status] +[NOTE] ✨ For users who are running generation on a virtual machine, consider SSH port forwarding (tunneling) to localhost to view dashboard. +[NOTE] Example of localhost command for SSH port forwarding (tunneling) from an AWS EC2 instance: +ssh -i -N -L localhost:8787:localhost:8787 ec2-user@ + +Total GB to generate: [1] +Average document size in bytes: [412] +Max file size in GB: [40] + +100%|███████████████████████████████████████████████████████████████████| 100.07G/100.07G [3:35:29<00:00, 3.98MB/s] + +Generated 24271844660 docs in 12000 seconds. Total dataset size is 100.21GB. +✅ Visit the following path to view synthetically generated data: /home/ec2-user/ + +----------------------------------- +[INFO] ✅ SUCCESS (took 272 seconds) +----------------------------------- +``` + +## Advanced configuration + +You can optionally create a YAML configuration file to store custom data and providers. The configuration file must define a `CustomGenerationValues` parameter. + +The following parameters are available in `CustomGenerationValues`. Both parameters are optional. + +| Parameter | Required/Optional | Description | +|---|---|---| +| `custom_lists` | Optional | Predefined arrays of values that you can reference in your Python module using `custom_lists['list_name']`. This allows you to separate data values from your code logic, making it easy to modify data values without changing your Python file. For example, `dog_names: [Buddy, Max, Luna]` becomes accessible as `custom_lists['dog_names']`. | +| `custom_providers` | Optional | Custom data generation classes that extend Mimesis functionality. These should be defined as classes in your Python module (like `NumericString` or `MultipleChoices` in the [example](#python-module-example)) and then listed in this parameter by name. This allows you to create specialized data generators beyond what Mimesis provides by default. | + +### Example configuration file + +Save your configuration in a YAML file: + +```yml +CustomGenerationValues: + # Generate data using a custom Python module + custom_lists: + # Custom lists to consolidate all values in this YAML file + dog_names: [Hana, Youpie, Charlie, Lucy, Cooper, Luna, Rocky, Daisy, Buddy, Molly] + dog_breeds: [Jindo, Labrador, German Shepherd, Golden Retriever, Bulldog, Poodle, Beagle, Rottweiler, Boxer, Dachshund, Chihuahua] + treats: [cookies, pup_cup, jerky] + custom_providers: + # OSB's synthetic data generator uses Mimesis; custom providers are essentially custom Python classes that adds more functionality to Mimesis + - NumericString + - MultipleChoices +``` +{% include copy.html %} + + +### Using the configuration + +To use your configuration file, add the `--custom-config` parameter to the `generate-data` command: + +```shell +osb generate-data --custom-module ~/pawber.py --index-name pawber-data --output-path ~/Desktop/sdg_outputs/ --total-size 2 --custom-config ~/Desktop/sdg-config.yml +``` +{% include copy.html %} + +## Related documentation + +- [`generate-data` command reference]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/generate-data/) +- [Generating data using index mappings]({{site.url}}{{site.baseurl}}/benchmark/features/synthetic-data-generation/mapping-sdg/) diff --git a/_benchmark/features/synthetic-data-generation/generating-vectors.md b/_benchmark/features/synthetic-data-generation/generating-vectors.md new file mode 100644 index 00000000..6dab453f --- /dev/null +++ b/_benchmark/features/synthetic-data-generation/generating-vectors.md @@ -0,0 +1,554 @@ +--- +layout: default +title: Generating vectors +nav_order: 40 +parent: Synthetic data generation +grand_parent: Additional features +--- + +# Generating vectors + +You can generate synthetic dense and sparse vectors from mappings using OpenSearch Benchmark's synthetic data generator. + +## Dense vectors + +Dense vectors (represented by the [`knn_vector`]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/knn-vector/) field type in OpenSearch) are numerical representations of data, such as text or images, in which most or all dimensions have non-zero values. These vectors typically contain floating-point numbers between -1.0 and 1.0, with each dimension contributing to the overall meaning. + +Example embedding for the word "dog": + +```json +{ + "embedding": [0.234, -0.567, 0.123, 0.891, -0.234, 0.456, ..., 0.789] +} +``` + +## Sparse vectors + +Sparse vectors (represented by the [`sparse_vector`]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/sparse-vector/) field type in OpenSearch) are vectors in which most dimensions are zero, represented as key-value pairs of non-zero token IDs and their weights. + +Example text: `Korean jindos are hunting dogs that have a reputation for being loyal, independent, and confident`. + +Sparse vector representation of example text: + +```json +{ + "5432": 0.85, // "korean" - very important (specific descriptor) + "7821": 0.78, // "jindos" - very important (breed name) + "2": 0.45, // "dog" - moderately important (general category) + "9999": 0.32, // "loyal" - somewhat important (characteristic) + "1111": 0.12 // "things" - less important (common word) +} +``` +--- + +## Basic usage + +The following examples show how to generate vectors with minimal configuration using only OpenSearch index mappings. + +### Generating dense vectors + +Generate random 128-dimensional vectors with minimal configuration. + +**1. Create a mapping file** (`simple-knn-mapping.json`): + +```json +{ + "settings": { + "index.knn": true + }, + "mappings": { + "properties": { + "title": {"type": "text"}, + "my_embedding": { + "type": "knn_vector", + "dimension": 128 + } + } + } +} +``` +{% include copy.html %} + +**2. Generate data**: + +```bash +opensearch-benchmark generate-data \ + --index-name my-vectors \ + --index-mappings simple-knn-mapping.json \ + --output-path ./output \ + --total-size 1 +``` +{% include copy.html %} + +#### Generated output + +In each of the generated documents, the `my_embedding` field might appear as follows: + +```json +{ + "title": "Sample text 42", + "my_embedding": [0.234, -0.567, 0.123, ..., 0.891] // 128 random floats [-1.0, 1.0] +} +``` + +### Generating sparse vectors + +Generate sparse vectors with the default configuration (10 tokens). + +**1. Create a mapping file** (`simple-sparse-mapping.json`): + +```json +{ + "mappings": { + "properties": { + "content": {"type": "text"}, + "sparse_embedding": { + "type": "sparse_vector" + } + } + } +} +``` +{% include copy.html %} + +**2. Generate data** (same command pattern): + +```bash +opensearch-benchmark generate-data \ + --index-name my-sparse \ + --index-mappings simple-sparse-mapping.json \ + --output-path ./output \ + --total-size 1 +``` +{% include copy.html %} + +#### Generated output + +In each of the generated documents, the `sparse_embedding` field might appear as follows: + +```json +{ + "content": "Sample text content", + "sparse_embedding": { + "1000": 0.3421, + "1100": 0.5234, + "1200": 0.7821, + "1300": 0.1523, + "1400": 0.9102, + "1500": 0.4567, + "1600": 0.2341, + "1700": 0.6789, + "1800": 0.8123, + "1900": 0.3456 + } +} +``` + +Using only an OpenSearch index mapping, OpenSearch Benchmark can generate synthetic dense and sparse vectors. However, this produces basic synthetic vectors. For more realistic distributions and clustering, we recommend configuring the parameters described in the following section. + +--- + +## Dense vector (k-NN vector) parameters + +The following are parameters that you can add to your synthetic data generation configuration file (YAML configuration) to fine-tune the generation of dense vectors. These parameters are used in the `field_overrides` section with the `generate_knn_vector` generator. For complete configuration details, see [Advanced configuration](/benchmark/features/synthetic-data-generation/mapping-sdg/#advanced-configuration). + + +#### dimension + + +This parameter specifies the number of dimensions in the vector. Optional. + +**How to specify**: The `dimension` must be defined in your OpenSearch index mapping file. You can optionally override this value in your YAML configuration using the `dimension` parameter in `field_overrides`. + +**Impact**: +- **Memory**: Higher dimensions = more storage + - 128 dimensions ≈ 0.5 KB per vector + - 768 dimensions ≈ 3 KB per vector + - 1536 dimensions ≈ 6 KB per vector +- **Performance**: More dimensions = slower indexing and search +- **Quality**: Must match your actual embedding model's output + +The following table shows common dimension values and their typical use cases. + +| Dimension | Use case | Example models | +|-----------|----------|----------------| +| 128 | Lightweight, custom models | Custom embeddings, fast search | +| 384 | General purpose | sentence-transformers/all-MiniLM-L6-v2 | +| 768 | Standard NLP | BERT-Base, DistilBERT, MPNet | +| 1,024 | High-quality NLP | BERT-Large | +| 1,536 | OpenAI standard | text-embedding-ada-002, text-embedding-3-small | +| 3,072 | OpenAI premium | text-embedding-3-large | + +**Example**: + +```yaml +field_overrides: + my_embedding: + generator: generate_knn_vector + params: + dimension: 768 # Override mapping dimension if needed +``` +{% include copy.html %} + +**Best practice**: This parameter must match your embedding model's dimension. + +--- + +#### sample_vectors + +This parameter provides base vectors to which the generator adds noise, creating realistic variations and clusters. Optional but highly recommended. + +Without sample vectors, OpenSearch Benchmark's synthetic data generator generates random uniform vectors across the entire space, which is unrealistic and offers poor search quality. Providing sample vectors allows OpenSearch Benchmark's synthetic data generator to create more realistic and natural clusters. + +After you prepare a list of sample vectors, insert them as a **list of lists**, in which each inner list is a complete vector. The following example provides sample vectors in the synthetic data generation configuration file: + +```yaml +field_overrides: + product_embedding: + generator: generate_knn_vector + params: + dimension: 768 + sample_vectors: + - [0.12, -0.34, 0.56, ..., 0.23] # Vector 1 (768 values) + - [-0.23, 0.45, -0.12, ..., -0.15] # Vector 2 (768 values) + - [0.34, 0.21, -0.45, ..., 0.42] # Vector 3 (768 values) +``` +{% include copy.html %} + +Use the following guidelines to determine the number of vectors that you provide: + +- **Minimum**: 3--5 for basic clustering +- **Recommended**: 5--10 for realistic distribution +- **Maximum**: 20+ for complex multi-cluster scenarios + +**How to obtain sample vectors**: + +**Option 1 (Recommended): Using actual embeddings from your domain**: Use actual embeddings from your domain, representing different semantic clusters. Random generation without sample vectors produces unrealistic data unsuitable for search quality testing. + +**Option 2: Using sentence-transformers** in Python: + +```python +from sentence_transformers import SentenceTransformer + +model = SentenceTransformer('all-MiniLM-L6-v2') + +# Create representative texts from different categories +texts = [ + "Electronics and gadgets", + "Clothing and fashion", + "Home and kitchen appliances", + "Books and literature", + "Sports and outdoor equipment" +] + +embeddings = model.encode(texts) +print(embeddings.tolist()) # Copy to your synthetic data generation configuration file (YAML config) +``` +{% include copy.html %} + +--- + +#### distribution_type + +This parameter specifies the type of noise distribution. Optional. Default is `gaussian`. + +**Valid values**: +- `gaussian`: Normal distribution N(0, `noise_factor`) + - Most realistic (natural variation with occasional outliers) + - Produces smooth clusters + - Some values can extend beyond expected range + +- `uniform`: Uniform distribution [-`noise_factor`, +`noise_factor`] + - Bounded variation (no extreme outliers) + - More predictable results + - Flat probability across range + +**Configuration**: +```yaml +field_overrides: + realistic_embedding: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.1 + distribution_type: gaussian # More realistic + + controlled_embedding: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.1 + distribution_type: uniform # More predictable +``` +{% include copy.html %} + +**Best practice**: Use `gaussian` for production-like benchmarks. + +--- + + +#### noise_factor + + +This parameter controls the amount of noise added to base vectors: +- For `gaussian`: Standard deviation of normal distribution +- For `uniform`: Range of uniform distribution (±`noise_factor`) + +Optional. Default is `0.1`. + +The following table shows how different `noise_factor` values impact the generated data. + +| `noise_factor` | Effect | Use case | +|--------------|--------|----------| +| 0.01--0.05 | Tight clustering, minimal variation | Duplicate detection, near-exact matches | +| 0.1--0.2 | Natural variation within topic | General semantic search, recommendations | +| 0.3--0.5 | Wide dispersion, diverse concepts | Broad topic matching, discovery | +| > 0.5 | Very scattered, overlapping clusters | Testing edge cases, stress testing | + +**Configuration**: + +```yaml +field_overrides: + tight_clustering: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.05 # Tight clusters + + diverse_results: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.2 # More variation +``` +{% include copy.html %} + +**Best practice**: Start with `0.1`, then adjust based on search recall or precision requirements. + +--- + + +#### normalize + + +This parameter normalizes vectors after noise addition, making their magnitude (length) exactly `1.0`. Optional. Default is `false`. + +The following table shows when to set `normalize` to `true` based on your index configuration. + +| `space_type` in the index mapping | `normalize` value | Explanation | +| --------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cosinesimil` | `true` | Cosine similarity depends only on vector direction. Pre-normalizing improves performance because the dot product directly represents cosine similarity. | +| `l2` | `false` | L2 distance relies on vector magnitude. Normalizing removes magnitude information and reduces accuracy. | +| `innerproduct` | `false` | Inner product incorporates vector magnitude into the similarity score, so normalization would change the intended scoring behavior. | + +**Real-world model guidance**: + +* **OpenAI embeddings**: These vectors are pre-normalized, so set `normalize` to `true`. +* **sentence-transformers**: Many models output normalized vectors. Review the model documentation; in most cases, `normalize` should be set to `true`. +* **BERT (raw output)**: Raw BERT embeddings are not normalized. Set `normalize` to `false` and rely on the index configuration to perform normalization if needed. + +**Configuration**: + +```yaml +field_overrides: + # For cosine similarity search + cosine_embedding: + generator: generate_knn_vector + params: + dimension: 384 + sample_vectors: [...] + normalize: true # Required for accurate cosine similarity + + # For L2 distance search + l2_embedding: + generator: generate_knn_vector + params: + dimension: 768 + sample_vectors: [...] + normalize: false # Keep original magnitudes +``` +{% include copy.html %} + +**Best practice**: Match your OpenSearch index's `space_type` setting. + +--- + +## Sparse vector parameters + +The following are parameters that you can add to your synthetic data generation configuration file to fine-tune how sparse vectors are generated. These parameters are used in the `field_overrides` section with the `generate_sparse_vector` generator. For complete configuration details, see [Advanced configuration](/benchmark/features/synthetic-data-generation/mapping-sdg/#advanced-configuration). + + +#### num_tokens + + +This parameter specifies the number of token-weight pairs to generate per vector. Optional. Default is `10`. + +**Impact**: +- **Low (5--10)**: Very sparse, fast search; may miss some relevant documents +- **Medium (10--25)**: Balanced performance and recall +- **High (50--100)**: Dense sparse representation; comprehensive but slower + +The following table shows typical `num_tokens` values for different models and approaches. + +| Model/Approach | Typical `num_tokens` | Use case | +|----------------|-------------------|----------| +| SPLADE v1 | 10--15 | Standard neural sparse search | +| SPLADE v2 | 15--25 | Improved recall | +| DeepImpact | 8--12 | Efficient sparse search | +| Custom/Hybrid | 20--50 | Rich representations | + +**Configuration**: + +```yaml +field_overrides: + sparse_standard: + generator: generate_sparse_vector + params: + num_tokens: 15 # Standard SPLADE-like + + sparse_rich: + generator: generate_sparse_vector + params: + num_tokens: 30 # Richer representation +``` +{% include copy.html %} + +**Best practice**: Start with `10--15`; increase if recall is insufficient. + +--- + + +#### min_weight and max_weight + + +These parameters define the range of token importance weights. Optional. Default `min_weight` is `0.01`; default `max_weight` is `1.0`. + +**Impact**: +- `min_weight`: Excludes low-importance tokens from generation. Tokens with weights below this value are not included. +- `max_weight`: Limits the upper bound of token influence to prevent any single token from dominating the vector. + +The following table shows common weight range configurations and their use cases. + +| Configuration | `min_weight` | `max_weight` | Use case | +|---------------|-----|-----|----------| +| Standard SPLADE | `0.01` | `1.0` | Default, balanced importance | +| Narrow range | `0.1` | `0.9` | More uniform importance | +| Wide range | `0.01` | `2.0` | Strong importance signals | +| High threshold | `0.05` | `1.0` | Filters low-confidence tokens | + +**Configuration**: + +```yaml +field_overrides: + sparse_balanced: + generator: generate_sparse_vector + params: + num_tokens: 15 + min_weight: 0.01 + max_weight: 1.0 + + sparse_uniform: + generator: generate_sparse_vector + params: + num_tokens: 20 + min_weight: 0.2 # Higher minimum + max_weight: 0.8 # Lower maximum +``` +{% include copy.html %} + +**Constraints**: +- `min_weight` must be > `0.0` (OpenSearch requires positive weights). +- `max_weight` must be > `min_weight`. +- Weights are rounded to `4` decimal places. + +**Best practice**: Keep `min_weight` small (`0.01--0.05`) to allow nuanced weighting. + +--- + + +#### token_id_start and token_id_step + + +These parameters define how token IDs are assigned during vector generation: + +- `token_id_start`: Sets the starting token ID in the generated sequence. Default is `1000`. + +- `token_id_step`: Specifies the increment applied between each consecutive token ID. Default is `100`. + +**Generated sequence**: `start, start+step, start+2*step, ...` + +**Example** with `start=1000`, `step=100`, `num_tokens=5`: + +```json +{ + "1000": 0.3421, // token_id_start + "1100": 0.5234, // start + 1*step + "1200": 0.7821, // start + 2*step + "1300": 0.1523, // start + 3*step + "1400": 0.9102 // start + 4*step +} +``` +{% include copy.html %} + +The following table shows different token ID configurations and their use cases. + +| Configuration | `token_id_start` | `token_id_step` | Use case | +| --------------------------- | ----------------- | --------------- | ------------------------------------------------------------------ | +| Default testing | `1000` | `100` | Helps visually distinguish generated token ranges. | +| Realistic vocabulary | `0` | `1` | Aligns token IDs with a real model's vocabulary indexes. | +| Multi-field generation | `1000`, `5000`, `10000` | `1` | Keeps token ID ranges separate across different fields. | +| Large vocabulary simulation | `0` | `1` | Supports generation scenarios with vocabularies of `50,000`+ tokens. | + +**Configuration**: + +```yaml +field_overrides: + # Default: easy debugging + sparse_debug: + generator: generate_sparse_vector + params: + num_tokens: 10 + token_id_start: 1000 + token_id_step: 100 + + # Realistic: actual vocab indices + sparse_realistic: + generator: generate_sparse_vector + params: + num_tokens: 15 + token_id_start: 0 + token_id_step: 1 + + # Multiple fields: separate ranges + sparse_field1: + generator: generate_sparse_vector + params: + token_id_start: 1000 + + sparse_field2: + generator: generate_sparse_vector + params: + token_id_start: 5000 +``` +{% include copy.html %} + +**Note**: Token IDs in the generated data is sequential. In real sparse vectors, IDs may be non-sequential based on the actual vocabulary. This difference does not impact OpenSearch indexing or search functionality. + +**Best practice**: Use a larger `token_id_step` (for example, `100`) for debugging, and set `token_id_step` to `1` for production-like data. + +--- + +## Choosing simple or complex generation approaches + +The following table outlines when to use simple generation compared to a more complex, configurable approach based on your testing goals. + +| Scenario | Recommended approach | Rationale | +| ------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------- | +| Learning or quick testing | Simple generation (no additional configuration) | Provides the fastest setup and is sufficient for basic validation. | +| Load testing | Simple generation | Prioritizes data volume and throughput over vector realism. | +| Realistic benchmarks | Complex generation (with configuration) | Requires realistic vector clustering and distributions to reflect real-world behavior. | +| Production simulation | Complex generation | Needs vector characteristics that closely match those produced by the actual embedding model. | +| Search quality testing | Complex generation | Requires meaningful vector clusters to evaluate recall and precision accurately. | + + +**Recommendation**: For search quality testing or algorithm comparisons, use a complex configuration with sample vectors to ensure realistic data distributions. diff --git a/_benchmark/features/synthetic-data-generation/index.md b/_benchmark/features/synthetic-data-generation/index.md new file mode 100644 index 00000000..e0511580 --- /dev/null +++ b/_benchmark/features/synthetic-data-generation/index.md @@ -0,0 +1,48 @@ +--- +layout: default +title: Synthetic data generation +nav_order: 5 +has_children: true +parent: Additional features +has_toc: false +redirect_from: + - /benchmark/features/synthetic-data-generation/ +cards: + - heading: "Generate data using index mappings" + description: "Create synthetic data based on your OpenSearch index mappings." + link: "/benchmark/features/synthetic-data-generation/mapping-sdg/" + - heading: "Generate data using custom logic" + description: "Build synthetic data using your own scripts or domain-specific rules." + link: "/benchmark/features/synthetic-data-generation/custom-logic-sdg/" +more_cards: + - heading: "Generating vectors" + description: "Generate synthetic dense and sparse vectors with configurable parameters for realistic AI/ML benchmarking scenarios." + link: "/benchmark/features/synthetic-data-generation/generating-vectors/" +tip_cards: + - heading: "Tips and best practices" + description: "Learn practical guidance and best practices to optimize your synthetic data generation workflows." + link: "/benchmark/features/synthetic-data-generation/tips/" +--- + +# Synthetic data generation +**Introduced 2.0** +{: .label .label-purple } + +OpenSearch Benchmark provides a built-in synthetic data generator that can create datasets for any use case at any scale. It supports two generation methods: + +* **Random data generation** produces fields with randomized values. This is useful for stress testing and evaluating system performance under load. +* **Rule-based data generation** creates data according to user-defined rules. This is helpful for testing specific scenarios, benchmarking query behavior, or simulating domain-specific patterns. + +## Data generation methods + +OpenSearch Benchmark supports the following data generation methods. + +{% include cards.html cards=page.cards %} + +For advanced synthetic data generation capabilities, explore vector generation. + +{% include cards.html cards=page.more_cards %} + +## Tips and best practices + +{% include cards.html cards=page.tip_cards %} diff --git a/_benchmark/features/synthetic-data-generation/mapping-sdg.md b/_benchmark/features/synthetic-data-generation/mapping-sdg.md new file mode 100644 index 00000000..9a333569 --- /dev/null +++ b/_benchmark/features/synthetic-data-generation/mapping-sdg.md @@ -0,0 +1,431 @@ +--- +layout: default +title: Generating data using index mappings +nav_order: 15 +parent: Synthetic data generation +grand_parent: Additional features +--- + +# Generating data using index mappings + +You can use OpenSearch index mappings to generate synthetic data. This approach offers a balance between automation and customization. + +To use this method, save your OpenSearch index mappings to a JSON file: + +```json +{ + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "standard", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "description": { + "type": "text" + }, + "price": { + "type": "float" + }, + "created_at": { + "type": "date", + "format": "strict_date_optional_time||epoch_millis" + }, + "is_available": { + "type": "boolean" + }, + "category_id": { + "type": "integer" + }, + "tags": { + "type": "keyword" + } + } + }, + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + } +} +``` + +OpenSearch Benchmark works with any valid index mappings, regardless of complexity. You can provide more complex mappings similar to the following: + +
+ + Mappings + + {: .text-delta} + +```json +{ + "mappings": { + "dynamic": "strict", + "properties": { + "user": { + "type": "object", + "properties": { + "id": { + "type": "keyword" + }, + "email": { + "type": "keyword" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + }, + "completion": { + "type": "completion" + } + }, + "analyzer": "standard" + }, + "address": { + "type": "object", + "properties": { + "street": { + "type": "text" + }, + "city": { + "type": "keyword" + }, + "state": { + "type": "keyword" + }, + "zip": { + "type": "keyword" + }, + "location": { + "type": "geo_point" + } + } + }, + "preferences": { + "type": "object", + "dynamic": true + } + } + }, + "orders": { + "type": "nested", + "properties": { + "id": { + "type": "keyword" + }, + "date": { + "type": "date", + "format": "strict_date_optional_time||epoch_millis" + }, + "amount": { + "type": "scaled_float", + "scaling_factor": 100 + }, + "status": { + "type": "keyword" + }, + "items": { + "type": "nested", + "properties": { + "product_id": { + "type": "keyword" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "quantity": { + "type": "short" + }, + "price": { + "type": "float" + }, + "categories": { + "type": "keyword" + } + } + }, + "shipping_address": { + "type": "object", + "properties": { + "street": { + "type": "text" + }, + "city": { + "type": "keyword" + }, + "state": { + "type": "keyword" + }, + "zip": { + "type": "keyword" + }, + "location": { + "type": "geo_point" + } + } + } + } + }, + "activity_log": { + "type": "nested", + "properties": { + "timestamp": { + "type": "date" + }, + "action": { + "type": "keyword" + }, + "ip_address": { + "type": "ip" + }, + "details": { + "type": "object", + "enabled": false + } + } + }, + "metadata": { + "type": "object", + "properties": { + "created_at": { + "type": "date" + }, + "updated_at": { + "type": "date" + }, + "tags": { + "type": "keyword" + }, + "source": { + "type": "keyword" + }, + "version": { + "type": "integer" + } + } + }, + "description": { + "type": "text", + "analyzer": "english", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + }, + "standard": { + "type": "text", + "analyzer": "standard" + } + } + }, + "ranking_scores": { + "type": "object", + "properties": { + "popularity": { + "type": "float" + }, + "relevance": { + "type": "float" + }, + "quality": { + "type": "float" + } + } + }, + "permissions": { + "type": "nested", + "properties": { + "user_id": { + "type": "keyword" + }, + "role": { + "type": "keyword" + }, + "granted_at": { + "type": "date" + } + } + } + } + }, + "settings": { + "number_of_shards": 3, + "number_of_replicas": 2, + "analysis": { + "analyzer": { + "email_analyzer": { + "type": "custom", + "tokenizer": "uax_url_email", + "filter": ["lowercase", "stop"] + } + } + } + } +} +``` + +
+ +## Generating data + +To generate synthetic data using index mappings, use the `generate-data` subcommand and provide the required index mappings file, index name, output path, and total amount of data to generate: + +```shell +osb generate-data --index-name --index-mappings --output-path --total-size +``` +{% include copy.html %} + +For a complete list of available parameters and their descriptions, see the [`generate-data` command reference]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/generate-data/). + +## Example output + +The following is an example output when generating 100 GB of data: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + + +[NOTE] ✨ Dashboard link to monitor processes and task streams: [http://127.0.0.1:8787/status] +[NOTE] ✨ For users who are running generation on a virtual machine, consider SSH port forwarding (tunneling) to localhost to view dashboard. +[NOTE] Example of localhost command for SSH port forwarding (tunneling) from an AWS EC2 instance: +ssh -i -N -L localhost:8787:localhost:8787 ec2-user@ + +Total GB to generate: [1] +Average document size in bytes: [412] +Max file size in GB: [40] + +100%|███████████████████████████████████████████████████████████████████| 100.07G/100.07G [3:35:29<00:00, 3.98MB/s] + +Generated 24271844660 docs in 12000 seconds. Total dataset size is 100.21GB. +✅ Visit the following path to view synthetically generated data: /home/ec2-user/ + +----------------------------------- +[INFO] ✅ SUCCESS (took 272 seconds) +----------------------------------- +``` + +## Advanced configuration + +You can control how synthetic data is generated by creating a YAML configuration file. The following is an example configuration file that defines custom rules in the `MappingGenerationValues` parameter: + +```yml +MappingGenerationValues: + # For users who want more granular control over how data is generated when providing an OpenSearch mapping + generator_overrides: + # Overrides all instances of generators with these settings. Specify type and params + integer: + min: 0 + max: 20 + long: + min: 0 + max: 1000 + float: + min: 0.0 + max: 1.0 + double: + min: 0.0 + max: 2000.0 + date: + start_date: "2020-01-01" + end_date: "2023-01-01" + format: "yyyy-mm-dd" + text: + must_include: ["lorem", "ipsum"] + keyword: + choices: ["alpha", "beta", "gamma"] + + field_overrides: + # Specify field name as key of dict. For its values, specify generator and its params. Params must adhere to existing params for each generator + # For nested fields, use dot notation: Example preferences.allergies if allergies is a subfield of preferences object + title: + generator: generate_keyword + params: + choices: ["Helly R", "Mark S", "Irving B"] + + promo_codes: + generator: generate_keyword + params: + choices: ["HOT_SUMMER", "TREATSYUM!"] + + # Nested fields, use dot notation + orders.items.product_id: + generator: generate_keyword + params: + choices: ["Python", "English"] +``` +{% include copy.html %} + +`MappingGenerationValues` supports the following parameters. + +| Parameter | Description | +|---|---| +| `generator_overrides` | Defines custom generator rules for specific OpenSearch field types. Any field that uses the corresponding type will follow these rules. See [Generator overrides parameters](#generator-overrides-parameters). | +| `field_overrides` | Defines generator rules for individual fields by field name. These apply only to the fields explicitly listed. For nested fields, use dot notation (for example, `orders.items.product_id`). See [Field overrides parameters](#field-overrides-parameters). | + +If both `generator_overrides` and `field_overrides` are present, `field_overrides` take precedence. +{: .important} + +#### Generator overrides parameters + +The following parameters are available for each OpenSearch field type in `generator_overrides`. + +| Field type | Parameters | +|---|---| +| `integer`, `long`, `short`, `byte` | `min`, `max` | +| `float`, `double` | `min`, `max`, `round` (the number of decimal places to round to) | +| `date` | `start_date`, `end_date`, `format` | +| `text` | `must_include` (array of terms to include in generated text) | +| `keyword` | `choices` (array of keywords to randomly select from) | + +#### Field overrides parameters + +The following generators and their parameters are available for use in `field_overrides`. + +| Generator | Parameters | +|---|---| +| `generate_text` | `must_include` (array of terms to include in generated text) | +| `generate_keyword` | `choices` (array of keywords to randomly select from) | +| `generate_integer` | `min`, `max` | +| `generate_long` | `min`, `max` | +| `generate_short` | `min`, `max` | +| `generate_byte` | `min`, `max` | +| `generate_float` | `min`, `max`, `round` (the number of decimal places to round to) | +| `generate_double` | `min`, `max` | +| `generate_boolean` | N/A| +| `generate_date` | `format`, `start_date`, `end_date` | +| `generate_ip` | N/A| +| `generate_geo_point` | N/A| +| `generate_knn_vector` | `dimension`, `sample_vectors`, `noise_factor`, `distribution_type`, `normalize`. See [Generating vectors](/benchmark/features/synthetic-data-generation/generating-vectors/). | +| `generate_sparse_vector` | `num_tokens`, `min_weight`, `max_weight`, `token_id_start`, `token_id_step`. See [Generating vectors](/benchmark/features/synthetic-data-generation/generating-vectors/). | + +### Using the configuration + +To use your configuration file, provide its full path in the `--custom-config` parameter: + +```shell +osb generate-data --index-name --index-mappings --output-path --total-size --custom-config ~/Desktop/sdg-config.yml +``` +{% include copy.html %} + +## Related documentation + +- [`generate-data` command reference]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/generate-data/) +- [Generating data using custom logic]({{site.url}}{{site.baseurl}}/benchmark/features/synthetic-data-generation/custom-logic-sdg/) \ No newline at end of file diff --git a/_benchmark/features/synthetic-data-generation/tips.md b/_benchmark/features/synthetic-data-generation/tips.md new file mode 100644 index 00000000..f71908c8 --- /dev/null +++ b/_benchmark/features/synthetic-data-generation/tips.md @@ -0,0 +1,23 @@ +--- +layout: default +title: Tips and best practices +nav_order: 45 +parent: Synthetic data generation +grand_parent: Additional features +--- + +# Tips and best practices + +The following tips help you efficiently generate synthetic data and monitor performance during the process. + +### Visualizing generation + +The generated URL opens a [Dask dashboard](https://docs.dask.org/en/latest/dashboard.html) that visualizes the data generation process. You can monitor CPU and memory usage for each worker and view a CPU flame graph of the generation workflow. This helps track resource usage and optimize performance, especially when using a [custom Python module]({{site.url}}{{site.baseurl}}/benchmark/features/synthetic-data-generation/custom-logic-sdg/). + +### Use default settings + +We recommend starting with the default synthetic data generation settings. These guidelines help you choose appropriate settings for efficient and reliable synthetic data generation: + +* Set the number of workers to **no more than the CPU count** on the load generation host. +* Use a **chunk size of 10,000 documents** per chunk. +* Adjust the `max_file_size_gb` setting as needed to control how much data is written to each generated file. diff --git a/_benchmark/finetune-workloads.md b/_benchmark/finetune-workloads.md new file mode 100644 index 00000000..ebf96391 --- /dev/null +++ b/_benchmark/finetune-workloads.md @@ -0,0 +1,58 @@ +--- +layout: default +title: Fine-tuning custom workloads +parent: Creating custom workloads +nav_order: 10 +redirect_from: + - /benchmark/user-guide/finetine-workloads/ + - /benchmark/user-guide/working-with-workloads/finetune-workloads/ +--- + +# Fine-tuning custom workloads + +While custom workloads can help make benchmarks more specific to your application's needs, they sometimes require additional adjustments to make sure they closely resemble a production cluster. + +You can fine-tune your custom workloads to more closely match your benchmarking needs by using the `create-workload` feature. `create-workload` can extract documents from all indexes or specific indexes selected by the user. + +## Characteristics to consider + +When beginning to use `create-workload` to fine-tune a custom workload, consider the following characteristics of the workload: + +1. **Queries** -- Consider the kinds of documents and as well as indexes targeted by the queries and the fields the queries call. +2. **Shard Size** -- Match the shard size of the workload with the shard size of your cluster, or the benchmark will not simulate the behavior of your application. Lucene operates based on shard sizes and does not have indexes. Calculate the shard size for any index that you want to include in the custom workload. +3. **Shard count** -- Choose the number of shards according to how you want to size the workload and improve query performance. Because each use case is different, you can determine the shard count in two ways: + 1. Divide the ideal index size by the shard size found in step 2. + 2. Multiply the ideal number of shards by the shard size found in step 2. +4. **Decide how many documents to extract (Recommended)** -- Now that the shard size is set and the number of shards needed in the final index decided, you can determine how many documents you want to extract. In some cases, users aren’t interested in retrieving the entire document corpus from an index because the corpus might be too big. Instead, you might want to generate a smaller corpus. However, the corpus of the generated index should be *representative* of the index in the production workload. In other words, it should contain documents from across the index and not only from a certain area, for example, the first half of the index or the last third of the index. To decide how many documents to extract: + 1. Multiply the number of shards by the shard size. Because every document is created unequally, add a buffer to the number---an arbitrary number of additional documents. The buffer provides assistance when the number of documents extracted is lower than the expected number, which will not help to retain your shard size. The shard size should be lower than the number of documents extracted. + 2. Divide the store size by the product of the previous step. The value of the multiple is used to set the number of sample documents from the reference index. +5. **Target cluster configuration** -- Factor the configuration and characteristics of the target cluster into how you generate the workload. + + +## Example + +The following example contains an index named `stocks`. The `stocks` index includes documents containing statistics on all stocks being traded on the New York Stock Exchange (NYSE). OpenSearch Dashboards provides information about the `stocks` index, as shown in the following code example: + +``` +health status index uuid pri rep docs.count docs.deleted store.size pri.store.size +green open stocks asjdkfjacklajldf 12 1 997818020 232823733 720gb 360gb +``` + +Using this information, you can start adjusting the workload to your specifications, as shown in the following steps: + +1. **Fetch queries associated with this index** -- Obtain the queries needed to make requests to the `stocks` index. +2. **Find the shard size for the index** -- To get the shard size of the index, divide the store size by the number of shards in the index: `720 / (12 + (12 * 1)) = 30`. 30 GB is the shard size. You can verify this by dividing the primary store size value by the number of primary shards. +3. **Determine the number of index shards** -- Determine the number of shards needed in the index to represent your application under a production load. For example, if you want your index to hold 300 GB of documents, but 300 GB is too much for the benchmark, determine a number that makes sense. For example, 300 GB of documents divided by the 30 GB shard size determined in the last step, or `300 / 30 = 10`, produces 10 shards. These 10 shards can either be 10 primary shards and 0 replicas, 5 primary shards and 1 replica, or 2 primary shards and 4 replicas. The shard configuration depends on your cluster's index needs. +4. **Decide how many documents to extract** -- To retain 30 GB and have 10 shards, you need to extract at least 300 GB of documents. To determine the number of documents to extract, divide the store size value by the index size value, in this example, `720 / 300 = 2.4`. Because you want to make sure you reach a value of 30 GB per shard, it is best to round down and choose 2 as the extraction multiple, which means that OpenSearch Benchmark will extract every other document. +5. **Think about the target cluster configuration** -- Assess the cluster you're planning to work on. Consider the use case, the size of the cluster, and the number of nodes. While fine-tuning the workload, this could be an iterative process where small adjustments to the cluster are made according to the results of the workload runs. + + +## Replicating metrics + +In many cases, a workload will not be able to exactly replicate the exact metrics of a production cluster. However, you can aim to get as close as possible to your ideal cluster metrics by replicating the following metrics: + +* CPU utilization +* Search request rates +* Indexing rates + + diff --git a/_benchmark/glossary.md b/_benchmark/glossary.md new file mode 100644 index 00000000..a1d2335b --- /dev/null +++ b/_benchmark/glossary.md @@ -0,0 +1,21 @@ +--- +layout: default +title: Glossary +nav_order: 100 +--- + +# OpenSearch Benchmark glossary + +The following terms are commonly used in OpenSearch Benchmark: + +- **Corpora**: A collection of documents. +- **Latency**: If `target-throughput` is disabled (has no value or a value of `0)`, then latency is equal to service time. If `target-throughput` is enabled (has a value of 1 or greater), then latency is equal to the service time plus the amount of time the request waits in the queue before being sent. +- **Metric keys**: The metrics stored by OpenSearch Benchmark, based on the configuration in the [metrics record]({{site.url}}{{site.baseurl}}/benchmark/metrics/metric-records/). +- **Operations**: In workloads, a list of API operations performed by a workload. +- **Pipeline**: A series of steps occurring both before and after running a workload that determines benchmark results. +- **Schedule**: A list of two or more operations performed in the order they appear when a workload is run. +- **Service time**: The amount of time taken for `opensearch-py`, the primary client for OpenSearch Benchmark, to send a request and receive a response from the OpenSearch cluster. It includes the amount of time taken for the server to process a request as well as for network latency, load balancer overhead, and deserialization/serialization. +- **Summary report**: A report generated at the end of a test based on the metric keys defined in the workload. +- **Test**: A single invocation of the OpenSearch Benchmark binary. +- **Throughput**: The number of operations completed in a given period of time. +- **Workload**: A collection of one or more benchmarking tests that use a specific document corpus to perform a benchmark against a cluster. The document corpus contains any indexes, data files, or operations invoked when the workload runs. \ No newline at end of file diff --git a/_benchmark/index.md b/_benchmark/index.md index 25b3738e..8b3d76e6 100644 --- a/_benchmark/index.md +++ b/_benchmark/index.md @@ -8,9 +8,38 @@ has_toc: false permalink: /benchmark/ redirect_from: - /benchmark/index/ + - /benchmark/tutorials/index/ +tutorial_cards: + - heading: "Get started with OpenSearch Benchmark" + description: "Run your first OpenSearch Benchmark workload and receive performance metrics" + link: "/benchmark/quickstart/" + - heading: "Choosing a workload" + description: "Choose a benchmark workload based on your cluster's use case" + link: "/benchmark/choosing-a-workload/" +more_cards: + - heading: "User guide" + description: "Learn how to benchmark the performance of your cluster" + link: "/benchmark/user-guide/index/" + - heading: "Reference" + description: "Learn about OpenSearch Benchmark commands and options" + link: "/benchmark/reference/index/" +items: + - heading: "Install and configure OpenSearch Benchmark" + description: "Install OpenSearch Benchmark and configure your experience" + link: "/benchmark/user-guide/install-and-configure/installing-benchmark/" + - heading: "Run a workload" + description: "Run a workload and receive performance metrics" + link: "/benchmark/running-workloads/" + - heading: "Analyze performance metrics" + description: "View your benchmark report and analyze your metrics" + link: "/benchmark/reference/summary-report/" +description: "OpenSearch Benchmark is a macrobenchmark utility provided by the OpenSearch Project. You can use OpenSearch Benchmark to gather performance metrics from an OpenSearch cluster." --- -# OpenSearch Benchmark +# ![Benchmark icon]({{site.url}}{{site.baseurl}}/images/icons/OpenSearch-PerformanceBenchmarks-Icon-1.png){: .heading-icon} OpenSearch Benchmark + +This page reflects the updated terminology in OpenSearch Benchmark `2.X`. `1.15` is the last supported version in the `1.X` series. For more information about what's changed, see the [version history page]({{site.url}}{{site.baseurl}}/benchmark/version-history/). For migration assistance, see the [migration assistance page]({{site.url}}{{site.baseurl}}/benchmark/migration-assistance/). +{: .important } OpenSearch Benchmark is a macrobenchmark utility provided by the [OpenSearch Project](https://github.com/opensearch-project). You can use OpenSearch Benchmark to gather performance metrics from an OpenSearch cluster for a variety of purposes, including: @@ -18,20 +47,14 @@ OpenSearch Benchmark is a macrobenchmark utility provided by the [OpenSearch Pro - Informing decisions about when to upgrade your cluster to a new version. - Determining how changes to your workflow---such as modifying mappings or queries---might impact your cluster. -OpenSearch Benchmark can be installed directly on a compatible host running Linux or macOS. You can also run OpenSearch Benchmark in a Docker container. See [Installing OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/installing-benchmark/) for more information. +## Get started -The following diagram visualizes how OpenSearch Benchmark works when run against a local host: - -![Benchmark workflow]({{site.url}}{{site.baseurl}}/images/benchmark/OSB-workflow.png). - -The OpenSearch Benchmark documentation is split into five sections: - -- [Quickstart]({{site.url}}{{site.baseurl}}/benchmark/quickstart/): Learn how to quickly run and install OpenSearch Benchmark. -- [User guide]({{site.url}}{{site.baseurl}}/benchmark/user-guide/index/): Dive deep into how OpenSearch Benchmark can help you track the performance of your cluster. -- [Tutorials]({{site.url}}{{site.baseurl}}/benchmark/tutorials/index/): Use step-by-step guides for more advanced benchmarking configurations and functionality. -- [Commands]({{site.url}}{{site.baseurl}}/benchmark/commands/index/): A detailed reference of commands and command options supported by OpenSearch. -- [Workloads]({{site.url}}{{site.baseurl}}/benchmark/workloads/index/): A detailed reference of options available for both default and custom workloads. +{% include list.html list_items=page.items%} +## Resources + +{% include cards.html cards=page.tutorial_cards %} +{% include cards.html cards=page.more_cards %} diff --git a/_benchmark/migration-assistance.md b/_benchmark/migration-assistance.md new file mode 100644 index 00000000..0290df60 --- /dev/null +++ b/_benchmark/migration-assistance.md @@ -0,0 +1,55 @@ +--- +layout: default +title: Migration assistance +nav_order: 110 +--- + +# Migrating from 1.X to 2.X + +For users who already have systems that integrate with OpenSearch Benchmark, we recommend performing the following steps for a smooth transition to OpenSearch Benchmark 2.0. + +## Update Benchmark.ini +OpenSearch Benchmark relies on `benchmark.ini`, which by default can be found in the `~/.benchmark` directory. This configuration file provides configurations related to where metrics are reported, how workloads are fetched, and much more. OpenSearch Benchmark 2.0 renames `[results_publishing]` to `[reporting]`. + +The configuration file should appear as follows: +```ini +[reporting] +datastore.type = in-memory +datastore.host = +datastore.port = +datastore.secure = False +datastore.ssl.verification_mode = +datastore.user = +datastore.password = +... +``` + +For information about how to configure OpenSearch Benchmark, see [Configuring OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/). + +## Update external metrics data store + +Many users use an external metrics data store to store results and metrics from previous test runs. + +OpenSearch Benchmark `1.X` stored test details in indexes with the `benchmark-test-executions-*` index pattern. However, in `2.X`, it stores them in indexes with the `benchmark-test-runs-*` index pattern. We recommend adding this new index pattern in your metrics data store as well as updating dashboards that might still be using the old index pattern. + +Old index pattern | New index pattern | +:--- | :--- | +benchmark-test-executions-* | benchmark-test-runs-* | + +## Update scripts + +Some users wrap OpenSearch Benchmark with custom scripts to run nightly performance tests. These scripts may rely on some terminology that has been deprecated in `2.X`. + +**See the following terms and adjust your scripts accordingly.** + +1.X term | 2.X term | +:--- | :--- | +execute-test, test-execution-id, TestExecution | run, test-run, TestRun | +results_publishing, results_publisher | reporting, publisher | +provision-configs, provision-config-instances | cluster-configs, cluster-config-instances +load-worker-coordinator-hosts | worker-ips | + +If you encounter any issues when migrating OpenSearch Benchmark from `1.X` to `2.X`, reach out to the OpenSearch Benchmark maintainers through any of the following ways: +- [Post a question in the OpenSearch Benchmark Slack channel](https://opensearch.slack.com/archives/C082PLA3VPW). +- [Attend the Community Meeting, Office Hours, and Issue Triage](https://www.meetup.com/opensearch/events/309982456/?eventOrigin=group_upcoming_events). +- [Create an issue in the OpenSearch Benchmark GitHub repository](https://github.com/opensearch-project/opensearch-benchmark/issues). \ No newline at end of file diff --git a/_benchmark/performance-testing-best-practices.md b/_benchmark/performance-testing-best-practices.md new file mode 100644 index 00000000..82dbc948 --- /dev/null +++ b/_benchmark/performance-testing-best-practices.md @@ -0,0 +1,267 @@ +--- +layout: default +title: Performance testing best practices +nav_order: 70 +redirect_from: + - /benchmark/user-guide/optimizing-benchmarks/performance-testing-best-practices/ + - /benchmark/user-guide/optimizing-benchmarks/ +--- + +# Performance testing best practices + +When conducting performance testing using OpenSearch Benchmark, it's crucial to follow some key best practices to ensure accurate, reliable, and meaningful results. These practices help in creating realistic test scenarios, minimizing external factors that could skew results, and generating comparable and reproducible benchmarks. By adhering to these guidelines, you can gain valuable insights into your cluster's performance, including identifying bottlenecks and making informed decisions about cluster configuration and optimization. + +## Environment setup + +Performance testing requires careful attention to the testing environment. A properly configured environment is vital to obtaining reliable and reproducible results. + +When setting up your testing environment, it's essential to use hardware that closely matches your production environment. Using development or underpowered hardware will not provide meaningful results that are translatable to production performance. Local machines often have limited hardware, and local development libraries can conflict with the workload's library, preventing the benchmark test from running effectively. + +For the best results, make sure that your load generation host or machine running OpenSearch Benchmark follows the minimum hardware requirements: + +- CPU: 8+ cores +- RAM: 32+ GB +- Storage: Solid-state drive (SSD)/NVMe +- Network: 10 Gbps + + +We recommend provisioning a test cluster and configuring its settings to reflect what you are most likely to deploy in production. + + +## Test configuration + +Proper test configuration includes setting appropriate parameters for your test scenarios and ensuring that your cluster is configured optimally. + +### Basic setup + +The following example shows a basic benchmark configuration file. This configuration includes essential parameters such as warmup time, test duration, and the number of clients: + +```json + { + "name": "my-benchmark-test-procedure", + "description": "This test procedure runs term query against a cluster. It includes a 300-second warm-up, followed by a 3600-second benchmark using 8 concurrent clients.", + "schedule": [ + { + "operation": "term", + "warmup-time=period": 300, + "time-period": 3600, + "clients": 8 + } + ] + } +``` +{% include copy.html %} + +### Index settings + +Your OpenSearch index settings should be optimized for your specific use case. Try to set the number of shards per index to match your production cluster. However, if you're a developer who wants to focus on a single shard's performance and limit the variables impacting performance, use a single primary shard, as shown in the following example `index_settings`: + +```json +{ + "index_settings": { + "number_of_shards": 1, + "number_of_replicas": 0, + "refresh_interval": "30s" + } +} +``` + +These settings offer ample storage space for your documents and test results, with 3 shards and 1 replica per index. + + +## Running tests + +Running benchmark tests involves monitoring the system during the test and ensuring consistent conditions across test runs. + +While you can run a basic test, you can also customize your test run with additional [benchmark command options]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/index/). The following example runs a `geonames` workload test that targets a specific host and outputs the test results as a `csv`, which can be used for further analysis of the benchmark's metrics: + +```bash +opensearch-benchmark run \ + --workload=geonames \ + --target-hosts=localhost:9200 \ + --pipeline=benchmark-only \ + --test-procedure=default \ + --report-format=csv \ + --report-file=benchmark-results.csv +``` +{% include copy.html %} + +### Monitoring during tests + +During a test run, it's essential to monitor various system metrics to ensure that the test is running correctly and to identify any potential bottlenecks. The following commands help you monitor different aspects of system performance: + +```bash +# Monitor system resources +vmstat 1 + +# Monitor OpenSearch metrics +curl localhost:9200/_cat/nodes?v +curl localhost:9200/_cat/indices?v + +# Monitor cluster health +curl localhost:9200/_cluster/health?pretty +``` +{% include copy.html %} + +## Collecting metrics + +Collecting and storing appropriate metrics is important for analyzing test results and making informed decisions about performance optimizations. + +### Essential metrics + +Configure your benchmark to collect comprehensive metrics. The following example configuration shows you how to set up metric collection with file storage: + +```json +{ + "metrics": { + "store_metrics": true, + "detailed": true, + "metrics_store": { + "type": "file", + "location": "/path/to/metrics" + } + } +} +``` +{% include copy.html %} + +### Sample metrics to track + +The following Python structure can be used as a template and includes a list of metrics that should be tracked during performance testing: + +```python +metrics_to_track = { + 'latency': { + 'mean': 'ms', + 'median': 'ms', + 'p95': 'ms', + 'p99': 'ms' + }, + 'throughput': { + 'ops/sec': 'count', + 'mb/sec': 'bytes' + }, + 'system': { + 'cpu_usage': '%', + 'memory_used': 'bytes', + 'disk_io': 'iops' + } +} +``` +{% include copy.html %} + +### Calculating metrics + +OpenSearch Benchmark calculates metrics differently than traditional client-server systems. For detailed information about how metrics are calculated, see [Differences between OpenSearch Benchmark and a traditional client-server system]({{site.url}}{{site.baseurl}}/benchmark/user-guide/concepts/#differences-between-opensearch-benchmark-and-a-traditional-client-server-system). + +## Integration with OpenSearch Dashboards + +To integrate OpenSearch Benchmark results with OpenSearch Dashboards, use the following steps: + +1. [Configure OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/user-guide/install-and-configure/configuring-benchmark/) to store results in OpenSearch. +2. Create index patterns in OpenSearch Dashboards for the benchmark results. +3. Create visualizations and dashboards to analyze the benchmark data. + + +## Common pitfalls + +When conducting performance tests using OpenSearch Benchmark, it's important to be aware of some common pitfalls that can lead to inaccurate or misleading results. + +### Warmup intervals + +Proper warmup is critical to accurate performance testing. Without an adequate warmup period, your test results may be skewed by initial system instabilities or caching effects. + +Don't run tests without a warmup period. + +Instead, always include an adequate warmup period in your tests. This allows the system to reach a steady state before measurements begin. In the following example, a `geonames` run is given a warmup period of `300s`: + +```python +opensearch-benchmark run --workload=geonames --workload-params="warmup_time_period:300" +``` + +The appropriate warmup period can vary depending on your specific workload and system configuration. Start with at least 5 minutes (300 seconds) and adjust as needed based on your observations. + +### Comparing results from different environments + +One of the most common mistakes in performance testing is comparing results from different environments. Results obtained from a laptop or development machine are not comparable to those from a production server due to differences in hardware, network conditions, and other environmental factors. + +Instead, ensure that all comparisons are made using the same or identical environments. If you need to compare different configurations, make sure to change only one variable at a time while keeping the environment consistent. + +### Documenting your test environment + +Proper documentation of your test environment is crucial for reproducibility and accurate analysis. Without detailed environment information, it becomes difficult to interpret results or reproduce tests in the future. + +Don't omit environment details from your test reports. + +Instead, always comprehensively document the details of your test environment. This should include hardware specifications, software versions, and any relevant configuration settings. The following example shows you how to add environment details when running OpenSearch Benchmark with a Python script: + +```python +# DO: Document environment details +def run_benchmark(): + environment = { + 'hardware': 'AWS m5.2xlarge', + 'os': 'Ubuntu 20.04', + 'kernel': '5.4.0-1018-aws', + 'opensearch': '2.0.0', + 'java': 'OpenJDK 11.0.11', + 'benchmark_version': '1.0.0' + } + results = opensearch_benchmark.run() + return {'environment': environment, 'results': results} +``` +{% include copy.html %} + +By documenting these details, you ensure that your test results can be properly interpreted and that the tests can be reproduced if necessary. + +### Troubleshooting with logs + +When encountering issues or unexpected results, OpenSearch Benchmark logs can provide valuable insights. Here's how to effectively use logs for troubleshooting: + +1. Navigate to the log file. The main log file is typically located at `~/.osb/logs/benchmark.log`. + +2. Look for error messages. Search for lines containing "ERROR" or "WARNING" to identify potential issues. + +3. Check for performance bottlenecks. Look for entries that indicate slow operations or resource constraints. + +4. Review configuration details, such as logs. Logs often include information about the test configuration, which can help verify that your intended settings were applied correctly. + +5. Pay attention to the duration of different phases of the benchmark, including warmup and measurement periods. + +By carefully reviewing these logs, you can often identify the root cause of performance issues or unexpected benchmark results. If you encounter a log error that you do not recognize, create an issue in the [OpenSearch Benchmark repository](https://github.com/opensearch-project/opensearch-benchmark). + +## Security considerations + +In most cases, a basic authentication protocol should be sufficient for testing. However, you can use SSL for secure communication during benchmark testing, as shown in the following example `opensearch.yml` configuration: + +```yaml +security: + ssl: true + verification_mode: full + certificate_authorities: + - /path/to/ca.crt + client_certificate: /path/to/client.crt + client_key: /path/to/client.key +``` +{% include copy.html %} + +## Maintenance + +Regular maintenance of your benchmark environment and tools is essential for consistent and reliable testing over time. + +Keep your benchmark tools and workloads up to date with the following commands: + +```bash +# Update OpenSearch Benchmark +pip install --upgrade opensearch-benchmark + +# Update workloads +opensearch-benchmark update-workload geonames + +# Clean old data +opensearch-benchmark clean +``` +{% include copy.html %} + +## Amazon OpenSearch Serverless considerations + +When testing using Amazon OpenSearch Serverless, be aware that not all test procedures may be supported. Always check the `README.md` file of the [workload](https://github.com/opensearch-project/opensearch-benchmark-workloads) you're using to confirm whether it's compatible with OpenSearch Serverless. If compatibility information is not provided, you may need to test the procedures individually to determine which ones are supported. diff --git a/_benchmark/quickstart.md b/_benchmark/quickstart.md index 0c23f749..495aa595 100644 --- a/_benchmark/quickstart.md +++ b/_benchmark/quickstart.md @@ -1,24 +1,24 @@ --- layout: default title: Quickstart -nav_order: 2 +nav_order: 5 --- # OpenSearch Benchmark quickstart -This tutorial outlines how to quickly install OpenSearch Benchmark and run your first OpenSearch Benchmark workload. +This page outlines how to quickly install OpenSearch Benchmark and run your first OpenSearch Benchmark workload. ## Prerequisites To perform the Quickstart steps, you'll need to fulfill the following prerequisites: -- A currently active OpenSearch cluster. For instructions on how to create an OpenSearch cluster, see [Creating a cluster]({{site.url}}{{site.baseurl}}//tuning-your-cluster/index/). +- A currently active OpenSearch cluster. For instructions on how to create an OpenSearch cluster, see [Creating a cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/). - Git 2.3 or greater. - Python 3.8 or later ## Set up an OpenSearch cluster -If you don't already have an active OpenSearch cluster, you can launch a new OpenSearch cluster to use with OpenSerch Benchmark. +If you don't already have an active OpenSearch cluster, you can launch a new OpenSearch cluster to use with OpenSearch Benchmark. - Using **Docker Compose**. For instructions on how to use Docker Compose, see [OpenSearch Quickstart]({{site.url}}{{site.baseurl}}/quickstart/). - Using **Tar**. For instructions on how to install OpenSearch with Tar, see [Installing OpenSearch > Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar#step-1-download-and-unpack-opensearch). @@ -76,7 +76,7 @@ If successful, OpenSearch returns the following response: ```bash $ opensearch-benchmark --help -usage: opensearch-benchmark [-h] [--version] {execute-test,list,info,create-workload,generate,compare,download,install,start,stop} ... +usage: opensearch-benchmark [-h] [--version] {run,list,info,create-workload,generate,compare,download,install,start,stop} ... ____ _____ __ ____ __ __ / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ @@ -92,13 +92,13 @@ optional arguments: --version show program's version number and exit subcommands: - {execute-test,list,info,create-workload,generate,compare,download,install,start,stop} - execute-test Run a benchmark + {run,list,info,create-workload,generate,compare,download,install,start,stop} + run Run a benchmark list List configuration options info Show info about a workload create-workload Create a Benchmark workload from existing data generate Generate artifacts - compare Compare two test_executions + compare Compare two test-runs download Downloads an artifact install Installs an OpenSearch node locally start Starts an OpenSearch node locally @@ -114,9 +114,9 @@ You can now run your first benchmark. The following benchmark uses the [percolat ### Understanding workload command flags -Benchmarks are run using the [`execute-test`]({{site.url}}{{site.baseurl}}/benchmark/commands/execute-test/) command with the following command flags: +Benchmarks are run using the [`run`]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/run/) command with the following command flags: -For additional `execute_test` command flags, see the [execute-test]({{site.url}}{{site.baseurl}}/benchmark/commands/execute-test/) reference. Some commonly used options are `--workload-params`, `--exclude-tasks`, and `--include-tasks`. +For additional `run` command flags, see the [run]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/run/) reference. Some commonly used options are `--workload-params`, `--exclude-tasks`, and `--include-tasks`. {: .tip} * `--pipeline=benchmark-only` : Informs OSB that users wants to provide their own OpenSearch cluster. @@ -124,19 +124,18 @@ For additional `execute_test` command flags, see the [execute-test]({{site.url}} * `--target-host=""`: Indicates the target cluster or host that will be benchmarked. Enter the endpoint of your OpenSearch cluster here. * `--client-options="basic_auth_user:'',basic_auth_password:''"`: The username and password for your OpenSearch cluster. * `--test-mode`: Allows a user to run the workload without running it for the entire duration. When this flag is present, Benchmark runs the first thousand operations of each task in the workload. This is only meant for sanity checks---the metrics produced are meaningless. - -The `--distribution-version`, which indicates which OpenSearch version Benchmark will use when provisioning. When run, the `execute-test` command will parse the correct distribution version when it connects to the OpenSearch cluster. +* `--distribution-version`: Indicates which OpenSearch version Benchmark will use when provisioning. When run, the `run` command will parse the correct distribution version when it connects to the OpenSearch cluster. ### Running the workload -To run the [percolator](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/percolator) workload with OpenSearch Benchmark, use the following `execute-test` command: +To run the [percolator](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/percolator) workload with OpenSearch Benchmark, use the following `run` command: ```bash -opensearch-benchmark execute-test --pipeline=benchmark-only --workload=percolator --target-host=https://localhost:9200 --client-options=basic_auth_user:admin,basic_auth_password:admin,verify_certs:false --test-mode +opensearch-benchmark run --pipeline=benchmark-only --workload=percolator --target-host=https://localhost:9200 --client-options=basic_auth_user:admin,basic_auth_password:admin,verify_certs:false --test-mode ``` {% include copy.html %} -When the `execute_test` command runs, all tasks and operations in the `percolator` workload run sequentially. +When the `run` command runs, all tasks and operations in the `percolator` workload run sequentially. ### Validating the test @@ -243,14 +242,14 @@ OpenSearch Benchmark returns the following response once the benchmark completes --------------------------------- -[INFO] SUCCESS (took 18 seconds) --------------------------------- +----------------------------------- +[INFO] ✅ SUCCESS (took 18 seconds) +----------------------------------- ``` -Each task run by the `percolator` workload represents a specific OpenSearch API operation---such as Bulk or Search---that was performed when the test was run. Each task in the output summary contains the following information: +Each task run by the `percolator` workload represents a specific OpenSearch API operation---such as Bulk or Search---that was performed when the test was run. Each task in the output summary contains the following information: -* **Throughput:** The number of successful OpenSearch operations per second. +* **Throughput:** The number of successful OpenSearch operations per second. * **Latency:** The amount of time, including wait time, taken for the request and the response to be sent and received by Benchmark. * **Service Time:** The amount of time, excluding wait time, taken for the request and the response to be sent and received by Benchmark. * **Error Rate:** The percentage of operations run during the task that were not successful or returned a 200 error code. @@ -260,18 +259,18 @@ For more details about how the summary report is generated, see [Summary report] ## Running OpenSearch Benchmark on your own cluster -Now that you're familiar with running OpenSearch Benchmark on a cluster, you can run OpenSearch Benchmark on your own cluster, using the same `execute-test` command, replacing the following settings. - - * Replace `https://localhost:9200` with your target cluster endpoint. This could be a URI like `https://search.mydomain.com` or a `HOST:PORT` specification. +Now that you're familiar with running OpenSearch Benchmark on a cluster, you can run OpenSearch Benchmark on your own cluster, using the same `run` command but replacing the following settings: + + * Replace `https://localhost:9200` with your target cluster endpoint. This can be a URI like `https://search.mydomain.com` or a `HOST:PORT` specification. * If the cluster is configured with basic authentication, replace the username and password in the command line with the appropriate credentials. - * Remove the `verify_certs:false` directive if you are not specifying `localhost` as your target cluster. This directive is needed only for clusters where SSL certificates are not set up. + * Remove the `verify_certs:false` directive if you are not specifying `localhost` as your target cluster. This directive is needed only for clusters where SSL certificates are not set up. * If you are using a `HOST:PORT`specification and plan to use SSL/TLS, either specify `https://`, or add the `use_ssl:true` directive to the `--client-options` string option. * Remove the `--test-mode` flag to run the full workload, rather than an abbreviated test. You can copy the following command template to use in your own terminal: ```bash -opensearch-benchmark execute-test --pipeline=benchmark-only --workload=percolator --target-host= --client-options=basic_auth_user:admin,basic_auth_password:admin +opensearch-benchmark run --pipeline=benchmark-only --workload=percolator --target-host= --client-options=basic_auth_user:admin,basic_auth_password:admin ``` {% include copy.html %} diff --git a/_benchmark/randomizing-queries.md b/_benchmark/randomizing-queries.md new file mode 100644 index 00000000..592ed504 --- /dev/null +++ b/_benchmark/randomizing-queries.md @@ -0,0 +1,143 @@ +--- +layout: default +title: Randomizing queries +nav_order: 65 +has_math: true +redirect_from: + - /benchmark/user-guide/optimizing-benchmarks/randomizing-queries/ +--- + +# Randomizing queries + +By default, OpenSearch Benchmark runs identical queries for multiple benchmark iterations. However, running the same queries repeatedly isn't ideal in every test scenario. For example, simulating real-world caching with many iterations of the same query results in one cache miss followed by many hits. OpenSearch Benchmark lets you randomize queries in a configurable way. + +For example, changing `"gte"` and `"lt"` in the following `nyc_taxis` operation creates distinct queries, resulting in unique cache entries: + +```json +{ + "name": "range", + "operation-type": "search", + "body": { + "query": { + "range": { + "total_amount": { + "gte": 5, + "lte": 15 + } + } + } + } +} +``` + +You can't completely randomize the values because the cache would not get any hits. To get cache hits, the cache must sometimes encounter the same values. To account for the same values while randomizing, OpenSearch Benchmark generates a number $$N$$ of value pairs for each randomized operation at the beginning of the benchmark. OpenSearch Benchmark stores these values in a saved list where each pair is assigned an index from $$1$$ to $$N$$. + +Every time OpenSearch sends a query, OpenSearch Benchmark decides whether to use a pair of values from this saved list in the query. It does this a configurable fraction of the time, called _repeat frequency_ (`rf`). If OpenSearch has encountered the value pair before, this might cause a cache hit. For example, if `rf` = 0.7, the cache hit ratio could be up to 70%. This ratio could cause a hit, depending on the benchmark's duration and cache size. + +OpenSearch Benchmark selects saved value pairs using the Zipf probability distribution, where the probability of selecting pair $$i$$ is proportional to $$1 \over i^\alpha$$. In this formula, $$i$$ represents the index of the saved value pair, and $$\alpha$$ controls how concentrated the distribution is. This distribution reflects usage patterns observed in real caches. Pairs with lower $$i$$ values (closer to $$1$$) are selected more frequently, while pairs with higher $$i$$ values (closer to $$N$$) are selected less often. + +The other $$1 -$$ `rf` fraction of the time, a new random pair of values is generated. Because OpenSearch Benchmark has not encountered these value pairs before, the pairs should miss the cache. + +## Usage + +To use this feature in a workload, you must make some changes to `workload.py` and supply some CLI flags when running OpenSearch Benchmark. + +### Modifying `workload.py` + +Specify how to generate the saved value pairs for each operation by registering a "standard value source" for that operation. This Python function accepts no arguments and returns a dictionary. The keys mirror those in the input query but are randomized. Finally, change the `register()` method so that it registers this function with the operation name and field name, which are randomized. + +For example, a standard value source used to randomize the `"total_amount"` field in the preceding `"range"` operation might appear similar to the following function: + +```py +def random_money_values(max_value): + gte_cents = random.randrange(0, max_value*100) + lte_cents = random.randrange(gte_cents, max_value*100) + return { + "gte":gte_cents/100, + "lte":lte_cents/100 + } + +def range_query_standard_value_source(): + return random_money_values(120.00) +``` + +Similarly, you can randomize the registration behavior using the following function: + +```py +def register(registry): + registry.register_standard_value_source("range", "total_amount", range_query_standard_value_source) +``` + +This function may already contain code. Retain it if so. If `workload.py` does not exist or lacks a `register(registry)` function, you can create them. + +#### Randomizing non-range queries + +By default, OpenSearch Benchmark assumes that the query to be randomized is a `"range"` query with values `"gte"`/`"gt"`, `"lte"`/`"lt"`, and, optionally, `"format"`. If this isn't the case, you can configure it to use a different query type name and different values. + +For example, to randomize the following workload operation: + +```json +{ + "name": "bbox", + "operation-type": "search", + "index": "nyc_taxis", + "body": { + "size": 0, + "query": { + "geo_bounding_box": { + "pickup_location": { + "top_left": [-74.27, 40.92], + "bottom_right": [-73.68, 40.49] + } + } + } + } +} +``` + +You would register the following function in `workload.py`: + +```py +registry.register_query_randomization_info("bbox", "geo_bounding_box", [["top_left"], ["bottom_right"]], []) +``` + +The first argument, `"bbox"`, is the operation's name. + +The second argument, `"geo_bounding_box"`, is the query type name. + +The third argument is a list of lists: `[[“top_left”], [“bottom_right”]]`. The outer list's entries specify parameters for randomization because there might be different versions of the same name that represent roughly the same parameters, for example, `"gte"` or `"gt"`. Here, there's only one option for each parameter name. At least one version of each parameter's name must be present in the original query in order for it to be randomized. + +The last argument is a list of optional parameters. If an optional parameter is present in the random standard value source, OpenSearch Benchmark inserts the parameter into the randomized version of the query. If it's not in the source, it's ignored. There are no optional parameters in the following example, but the typical use case would be `"format"` in a range query. + +If there is no registration, the default registration is used: `registry.register_query_randomization_info(, “range”, [[“gte”, “gt”], [“lte”, “lt”]], [“format”])`. + + +The `dict` returned by the standard value source should match the parameter names you are randomizing. For example, the following is the standard value source for the preceding example: + +```py +def bounding_box_source(): + top_longitude = random.uniform(-74.27, -73.68) + top_latitude = random.uniform(40.49, 40.92) + + bottom_longitude = random.uniform(top_longitude, -73.68) + bottom_latitude = random.uniform(40.49, top_latitude) + + return { + "top_left":[top_longitude, top_latitude], + "bottom_right":[bottom_longitude, bottom_latitude] + } +``` + + + +### CLI flags + +Use the following CLI flags to customize randomization: + +- `--randomization-enabled` turns randomization on and off. If randomization is not enabled, none of the randomization flags will be applied. + +- `--randomization-repeat-frequency` or `-rf` sets the fraction of pairs drawn from the saved value pairs generated at the start of the benchmark. The value should be between `0.0` and `1.0`. Default is `0.3`. + +- `--randomization-n` sets the number `N` of value pairs generated for each operation. Default is `5000`. + +- `--randomization-alpha` sets the `alpha` parameter, which controls the spread of the `Zipf` distribution. The value should be `>=0`. Lower values increase the spread of the distribution. Default is `1.0`. diff --git a/_benchmark/reference/commands/aggregate.md b/_benchmark/reference/commands/aggregate.md new file mode 100644 index 00000000..02e704e6 --- /dev/null +++ b/_benchmark/reference/commands/aggregate.md @@ -0,0 +1,100 @@ +--- +layout: default +title: aggregate +nav_order: 10 +parent: Command reference +grand_parent: Reference +redirect_from: + - /benchmark/commands/aggregate/ +--- + + +# aggregate command + + +The `aggregate` command combines multiple test runs into a single aggregated result, providing a more streamlined way to conduct and analyze multiple test runs. There are two methods of aggregation: + +- [Auto-aggregation](#auto-aggregation) +- [Manual aggregation](#manual-aggregation) + +## Auto-aggregation + +The auto-aggregation method runs multiple iterations of benchmark tests and automatically aggregates the results, all within a single command. You can use the flags outlined in this with the `execute` command. + +### Usage + +The following example runs the `geonames` workload and aggregates the results twice: + +```bash +opensearch-benchmark execute --test-iterations=2 --aggregate=true --workload=geonames --target-hosts=127.0.0.1:9200 +``` +{% include copy-curl.html %} + +### Auto-aggregation flags + +The following new flags can be used to customize the auto-aggregation method: + +- `--test-iterations`: Specifies the number of times to run the workload (default is `1`). +- `--aggregate`: Determines whether to aggregate the results of multiple test runs (default is `true`). +- `--sleep-timer`: Specifies the number of seconds to sleep before starting the next test run (default is `5`). +- `--cancel-on-error`: When set, stops executing tests if an error occurs in one of the test iterations (default is `false`). + +## Manual aggregation + +You can use the `aggregate` command to manually aggregate results from multiple test runs. + +### Usage + +To aggregate multiple test runs manually, specify the `test_run_ids` you would like to aggregate, as shown in the following example: + +```bash +opensearch-benchmark aggregate --test-executions=,,... +``` +{% include copy-curl.html %} + +### Response + +OpenSearch Benchmark responds with the following: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +Aggregate test run ID: aggregate_results_geonames_9aafcfb8-d3b7-4583-864e-4598b5886c4f + +---------------------------------- +[INFO] ✅ SUCCESS (took 1 seconds) +---------------------------------- +``` + +The results will be aggregated into one test run and stored under the ID shown in the output. + +### Additional options +- `--test-execution-id`: Define a unique ID for the aggregated test run. +- `--results-file`: Write the aggregated results to the provided file. +- `--workload-repository`: Define the repository from which OpenSearch Benchmark will load workloads (default is `default`). + +## Aggregated results + +Aggregated results includes the following information: + +- **Relative Standard Deviation (RSD)**: For each metric an additional `mean_rsd` value shows the spread of results across test runs. +- **Overall min/max values**: Instead of averaging minimum and maximum values, the aggregated result include `overall_min` and `overall_max` which reflect the true minimum/maximum across all test runs. +- **Storage**: Aggregated test results are stored in a separate `aggregated_results` folder alongside the `test-runs` folder. + +The following example shows aggregated results: + +```json + "throughput": { + "overall_min": 29056.890292903263, + "mean": 50115.8603858536, + "median": 50099.54349684457, + "overall_max": 72255.15946248993, + "unit": "docs/s", + "mean_rsd": 59.426059705973664 + }, +``` diff --git a/_benchmark/reference/commands/command-flags.md b/_benchmark/reference/commands/command-flags.md index ca0606f0..b95e9ba9 100644 --- a/_benchmark/reference/commands/command-flags.md +++ b/_benchmark/reference/commands/command-flags.md @@ -1,10 +1,11 @@ --- layout: default title: Command flags -nav_order: 51 +nav_order: 150 parent: Command reference -redirect_from: /benchmark/commands/command-flags/ -grand_parent: OpenSearch Benchmark Reference +redirect_from: + - /benchmark/commands/command-flags/ +grand_parent: Reference --- # Command flags @@ -38,7 +39,7 @@ This defines the repository from which OpenSearch Benchmark loads workloads. `-- ## workload-revision -Defines a specific revision from the workload source tree that OpenSearch Benchmark should use. +Defines a specific revision from the workload source tree that OpenSearch Benchmark should use. ## workload @@ -50,7 +51,7 @@ Defines the workload to use based on the workload's name. You can find a list of ## workload-params -Defines which variables to inject into the workload. Variables injected must be available in the workload. To see which parameters are valid in the official workloads, select the workload from [the workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads). +Defines the variables to inject into the workload. Injected variables must be available in the workload. You can pass parameters as a JSON file, inline JSON, or comma-separated key-value pairs. For more information, including template syntax, precedence, and common parameters for each workload, see [Workload parameters]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/parameters/). ## test-procedure @@ -70,7 +71,7 @@ Defines a unique ID for the test run. Defines a comma-separated list of test procedure tasks to run. By default, all tasks listed in a test procedure array are run. -Tests are executed in the order they are defined in `test-procedure`---not in the order they are defined in the command. +Tasks are run in the order they are defined in `test-procedure`---not in the order they are defined in the command. All task filters are case sensitive. @@ -84,13 +85,13 @@ Defines a comma-separated list of test procedure tasks not to run. ## baseline -The baseline TestExecution ID used to compare the contender TestExecution. +The baseline TestRun ID used to compare the contender TestRun. ## contender -The TestExecution ID for the contender being compared to the baseline. +The TestRun ID for the contender being compared to the baseline. ## results-format @@ -109,37 +110,37 @@ Defines the column number alignment for when the `compare` command outputs resul ## results-file -When provided a file path, writes the compare results to the file indicated in the path. +When provided a file path, writes the compare results to the file indicated in the path. ## show-in-results -Determines whether or not to include the comparison in the results file. +Determines whether or not to include the comparison in the results file. -## provision-config-repository +## cluster-config-repository -Defines the repository from which OpenSearch Benchmark loads `provision-configs` and `provision-config-instances`. +Defines the repository from which OpenSearch Benchmark loads `cluster-configs` and `cluster-config-instances`. -## provision-config-revision +## cluster-config-revision -Defines the specific Git revision in the `provision-config` that OpenSearch Benchmark should use. +Defines the specific Git revision in the `cluster-config` that OpenSearch Benchmark should use. -## provision-config-path +## cluster-config-path -Defines the path to the `--provision-config-instance` and any OpenSearch plugin configurations to use. +Defines the path to the `--cluster-config-instance` and any OpenSearch plugin configurations to use. ## distribution-version -Downloads the specified OpenSearch distribution based on version number. For a list of released OpenSearch versions, see [Version history](https://opensearch.org/docs/version-history/). +Downloads the specified OpenSearch distribution based on version number. For a list of released OpenSearch versions, see [Version history]({{site.url}}{{site.latesturl}}/version-history/). ## distribution-repository @@ -148,34 +149,34 @@ Downloads the specified OpenSearch distribution based on version number. For a l Defines the repository from which the OpenSearch distribution should be downloaded. Default is `release`. -## provision-config-instance +## cluster-config-instance -Defines the `--provision-config-instance` to use. You can view possible configuration instances by using the command `opensearch-benchmark list provision-config-instances`. +Defines the `--cluster-config-instance` to use. You can view possible configuration instances by using the command `opensearch-benchmark list cluster-config-instances`. -## provision-config-instance-params +## cluster-config-instance-params -A comma-separated list of key-value pairs injected verbatim as variables for the `provision-config-instance`. +A comma-separated list of key-value pairs injected verbatim as variables for the `cluster-config-instance`. ## target-hosts -Defines a comma-separated list of host-port pairs that should be targeted if using the pipeline `benchmark-only`. Default is `localhost:9200`. +Defines a comma-separated list of host-port pairs that should be targeted if using the pipeline `benchmark-only`. Default is `localhost:9200`. ## target-os -The target operating system (OS) for which the OpenSearch artifact should be downloaded. Default is the current OS. +The target operating system for which the OpenSearch artifact should be downloaded. Default is the current operating system. ## target-arch -The name of the CPU architecture for which an artifact should be downloaded. +The name of the CPU architecture for which an artifact should be downloaded. ## revision @@ -185,10 +186,10 @@ Defines the current source code revision to use for running a benchmark test. De This command flag can use the following options: - - `current`: Uses the source tree's current revision based on your OpenSearch distribution. - - `latest`: Fetches the latest revision from the main branch of the source tree. + - `current`: Uses the source tree's current revision based on your OpenSearch distribution. + - `latest`: Fetches the latest revision from the main branch of the source tree. -You can also use a timestamp or commit ID from the source tree. When using a timestamp, specify `@ts`, where "ts" is a valid ISO 8601 timestamp, for example, `@2013-07-27T10:37:00Z`. +You can also use a timestamp or commit ID from the source tree. When using a timestamp, specify `@ts`, where "ts" is a valid ISO 8601 timestamp, for example, `@2013-07-27T10:37:00Z`. ## opensearch-plugins @@ -206,7 +207,7 @@ Defines a comma-separated list of key-value pairs that are injected verbatim int ## runtime-jdk -The major version of JDK to use. +The major version of JDK to use. @@ -216,7 +217,7 @@ The major version of JDK to use. Defines a comma-separated list of clients to use. All options are passed to the OpenSearch Python client. Default is `timeout:60`. -## load-worker-coordinator-hosts +## worker-ips Defines a comma-separated list of hosts that coordinate loads. Default is `localhost`. @@ -243,13 +244,13 @@ Enables the provided telemetry devices when the devices are provided using a com ## telemetry-params -Enables setting parameters for telemetry devices. Accepts a list of comma-separated key-value pairs, each of which are delimited by a colon or a JSON file name. +Enables setting parameters for telemetry devices. Accepts a list of comma-separated key-value pairs, each of which are delimited by a colon or a JSON file name. ## on-error -Controls how OpenSearch Benchmark responds to errors. Default is `continue`. +Controls how OpenSearch Benchmark responds to errors. Default is `continue`. You can use the following options with this command flag: @@ -266,7 +267,7 @@ Keeps the Benchmark candidate and its index. Default is `false`. ## kill-running-processes -When set to `true`, stops any OpenSearch Benchmark processes currently running and allows Benchmark to continue to run. Default is `false`. +When set to `true`, stops any OpenSearch Benchmark processes currently running and allows Benchmark to continue to run. Default is `false`. ## chart-spec-path @@ -284,7 +285,7 @@ Generates the indicated chart type, either `time-series` or `bar`. Default is `t ## output-path -The name and path used for the chart's output. Default is `stdout`. +The name and path used for the chart's output. Default is `stdout`. ## limit @@ -296,34 +297,63 @@ Limits the number of search results for recent test runs. Default is `10`. ## latency-percentiles -Specifies a comma-separated list of latency percentiles to report after the workload runs. Accepts `ints` or `floats` with values between `0` and `100` inclusive. Does not accept `min`, `median`, `mean`, or `max`. Default is `50,90,99,99.9,99.99,100`. +Specifies a comma-separated list of latency percentiles to report after the workload runs. Accepts `ints` or `floats` with values between `0` and `100`, inclusive. Does not accept `min`, `median`, `mean`, or `max`. Default is `50,90,99,99.9,99.99,100`. ## throughput-percentiles -Specifies a list of throughput percentiles to report after the workload runs, in addition to min/median/mean/max which is always displayed. Like `--latency-percentiles`, the setting accepts `ints` or `floats` with values between `0` and `100` inclusive. Does not accept `min`, `median`, `mean`, or `max`. Default is `None`. +Specifies a list of throughput percentiles to report after the workload runs. Like `--latency-percentiles`, the setting accepts `ints` or `floats` with values between `0` and `100`, inclusive. Does not accept `min`, `median`, `mean`, or `max`. Default is `None`. ## randomization-enabled -Enables randomization of values in range queries, where the values are drawn from standard value functions registered with `register_standard_value_source` in the workload's `workload.py` file. +Enables randomization of values in `range` queries, where the values are drawn from standard value functions registered with `register_standard_value_source` in the workload's `workload.py` file. -A standard value function is a no-argument function that generates a random pair of values for a certain field, in a dict with keys `"gte"`, `"lte"`, and optionally `"format"`. +A standard value function is a no-argument function that generates a random pair of values for a certain field, in a dict with keys `"gte"`, `"lte"`, and, optionally, `"format"`. -If this argument is `True` but a search operation does not have a registered standard value function, OpenSearch Benchmark raises a `SystemSetupError`. +If this argument is `True` but a search operation does not have a registered standard value function, OpenSearch Benchmark raises a `SystemSetupError`. Default is `False`. -Default is `False`. ## randomization-repeat-frequency -Sets what fraction of randomized query values can be repeated. Takes values between `0.0` and `1.0`. Default is `0.3`. This setting does not work when `--randomization-enabled` is not used. +Sets what fraction of randomized query values can be repeated. Takes values between `0.0` and `1.0`. Default is `0.3`. This setting does not work when `--randomization-enabled` is not used. ## randomization-n -Sets how many distinct repeatable pair values are generated for each operation when randomization is used. Default is `5000`. This setting does not work when `--randomization-enabled` is not used. +Sets how many distinct repeatable pair values are generated for each operation when randomization is used. Default is `5000`. This setting does not work when `--randomization-enabled` is not used. + + +## test-iterations + + +Specifies the number of times to run the workload. Default is `1`. + + +## aggregate + + +Determines whether OpenSearch Benchmark should aggregate the results of multiple test runs. + +When set to `true`, OpenSearch Benchmark will combine the results from all iterations into a single aggregated report. When set to `false`, results from each iteration will be reported separately. + +Default is `true`. + + +## sleep-timer + + +Specifies the number of seconds to sleep before starting the next test run. Default is `5`. + + + +## cancel-on-error + + +When set, this flag instructs OpenSearch Benchmark to stop executing tests if an error occurs in one of the test iterations. Default is `false` (not set). + diff --git a/_benchmark/reference/commands/compare.md b/_benchmark/reference/commands/compare.md index dc7ed2f5..b8ec0536 100644 --- a/_benchmark/reference/commands/compare.md +++ b/_benchmark/reference/commands/compare.md @@ -1,21 +1,22 @@ --- layout: default title: compare -nav_order: 55 +nav_order: 20 parent: Command reference -grand_parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/commands/compare/ +grand_parent: Reference +redirect_from: + - /benchmark/commands/compare/ --- -# compare +# compare command -The `compare` command helps you analyze the difference between two benchmark tests. This can help you analyze the performance impact of changes made from a previous test based on a specific Git revision. +The `compare` command helps you analyze the difference between two benchmark tests. This can help you analyze the performance impact of changes made from a previous test based on a specific Git revision. ## Usage -You can compare two different workload tests using their `TestExecution IDs`. To find a list of tests run from a specific workload, use `opensearch-benchmark list test_executions`. You should receive an output similar to the following: +You can compare two different workload tests using their `TestRun IDs`. To find a list of tests run from a specific workload, use `opensearch-benchmark list test-runs`. You should receive an output similar to the following: ``` @@ -25,16 +26,18 @@ You can compare two different workload tests using their `TestExecution IDs`. To / /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< \____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| /_/ -Recent test-executions: -Recent test_executions: - -TestExecution ID TestExecution Timestamp Workload Workload Parameters TestProcedure ProvisionConfigInstance User Tags workload Revision Provision Config Revision ------------------------------------- ------------------------- ---------- --------------------- ------------------- ------------------------- ----------- ------------------- --------------------------- +Recent test-runs: +TestRun ID TestRun Timestamp Workload Workload Parameters TestProcedure ClusterConfigInstance User Tags workload Revision Cluster Config Revision +------------------------------------ ------------------- ---------- --------------------- ------------------- ----------------------- ----------- ------------------- ------------------------- 729291a0-ee87-44e5-9b75-cc6d50c89702 20230524T181718Z geonames append-no-conflicts 4gheap 30260cf f91c33d0-ec93-48e1-975e-37476a5c9fe5 20230524T170134Z geonames append-no-conflicts 4gheap 30260cf d942b7f9-6506-451d-9dcf-ef502ab3e574 20230524T144827Z geonames append-no-conflicts 4gheap 30260cf -a33845cc-c2e5-4488-a2db-b0670741ff9b 20230523T213145Z geonames append-no-conflicts +a33845cc-c2e5-4488-a2db-b0670741ff9b 20230523T213145Z geonames append-no-conflicts + +---------------------------------- +[INFO] ✅ SUCCESS (took 0 seconds) +---------------------------------- ``` @@ -55,12 +58,12 @@ You should receive the following response comparing the final benchmark metrics /_/ Comparing baseline - TestExecution ID: 729291a0-ee87-44e5-9b75-cc6d50c89702 - TestExecution timestamp: 2023-05-24 18:17:18 + TestRun ID: 729291a0-ee87-44e5-9b75-cc6d50c89702 + TestRun timestamp: 2023-05-24 18:17:18 with contender - TestExecution ID: a33845cc-c2e5-4488-a2db-b0670741ff9b - TestExecution timestamp: 2023-05-23 21:31:45 + TestRun ID: a33845cc-c2e5-4488-a2db-b0670741ff9b + TestRun timestamp: 2023-05-23 21:31:45 ------------------------------------------------------ @@ -124,13 +127,13 @@ Query latency country_agg_cached (100.0 percentile) [ms] 3.42547 2.8681 ## Options -You can use the following options to customize the results of your test comparison: +You can use the following options to customize the results of your test comparison: -- `--baseline`: The baseline TestExecution ID used to compare the contender TestExecution. -- `--contender`: The TestExecution ID for the contender being compared to the baseline. +- `--baseline`: The baseline TestRun ID used to compare the contender TestRun. +- `--contender`: The TestRun ID for the contender being compared to the baseline. - `--results-format`: Defines the output format for the command line results, either `markdown` or `csv`. Default is `markdown`. -- `--results-number-align`: Defines the column number alignment for when the `compare` command outputs results. Default is `right`. -- `--results-file`: When provided a file path, writes the compare results to the file indicated in the path. -- `--show-in-results`: Determines whether or not to include the comparison in the results file. +- `--results-numbers-align`: Defines the column number alignment for when the `compare` command outputs results. Default is `right`. +- `--results-file`: When provided a file path, writes the compare results to the file indicated in the path. +- `--show-in-results`: Determines whether or not to include the comparison in the results file. diff --git a/_benchmark/reference/commands/download.md b/_benchmark/reference/commands/download.md index 580e7ef8..e1f87563 100644 --- a/_benchmark/reference/commands/download.md +++ b/_benchmark/reference/commands/download.md @@ -1,44 +1,45 @@ --- layout: default title: download -nav_order: 60 +nav_order: 30 parent: Command reference -grand_parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/commands/download/ +grand_parent: Reference +redirect_from: + - /benchmark/commands/download/ --- -# download +# download command -Use the `download` command to select which OpenSearch distribution version to download. +Use the `download` command to select which OpenSearch distribution version to download. ## Usage The following example downloads OpenSearch version 2.7.0: ``` -opensearch-benchmark download --distribution-version=2.7.0 +opensearch-benchmark download --distribution-version=2.7.0 ``` - + Benchmark then returns the location of the OpenSearch artifact: ``` { - "opensearch": "/Users/.benchmark/benchmarks/distributions/opensearch-2.7.0.tar.gz" + "opensearch": "/Users/.benchmark/benchmarks/distributions/opensearch-2.7.0.tar.gz" } ``` ## Options - + Use the following options to customize how OpenSearch Benchmark downloads OpenSearch: -- `--provision-config-repository`: Defines the repository from which OpenSearch Benchmark loads `provision-configs` and `provision-config-instances`. -- `--provision-config-revision`: Defines a specific Git revision in the `provision-config` that OpenSearch Benchmark should use. -- `--provision-config-path`: Defines the path to the `--provision-config-instance` and any OpenSearch plugin configurations to use. -- `--distribution-version`: Downloads the specified OpenSearch distribution based on version number. For a list of released OpenSearch versions, see [Version history](https://opensearch.org/docs/version-history/). +- `--cluster-config-repository`: Defines the repository from which OpenSearch Benchmark loads `cluster-configs` and `cluster-config-instances`. +- `--cluster-config-revision`: Defines a specific Git revision in the `cluster-config` that OpenSearch Benchmark should use. +- `--cluster-config-path`: Defines the path to the `--cluster-config-instance` and any OpenSearch plugin configurations to use. +- `--distribution-version`: Downloads the specified OpenSearch distribution based on version number. For a list of released OpenSearch versions, see [Version history]({{site.url}}{{site.latesturl}}/version-history/). - `--distribution-repository`: Defines the repository from where the OpenSearch distribution should be downloaded. Default is `release`. -- `--provision-config-instance`: Defines the `--provision-config-instance` to use. You can view possible configuration instances using the command `opensearch-benchmark list provision-config-instances`. -- `--provision-config-instance-params`: A comma-separated list of key-value pairs injected verbatim as variables for the `provision-config-instance`. -- `--target-os`: The target operating system (OS) for which the OpenSearch artifact should be downloaded. Default is the current OS. -- `--target-arch`: The name of the CPU architecture for which an artifact should be downloaded. +- `--cluster-config-instance`: Defines the `--cluster-config-instance` to use. You can view possible configuration instances using the command `opensearch-benchmark list cluster-config-instances`. +- `--cluster-config-instance-params`: A comma-separated list of key-value pairs injected verbatim as variables for the `cluster-config-instance`. +- `--target-os`: The target operating system for which the OpenSearch artifact should be downloaded. Default is the current operating system. +- `--target-arch`: The name of the CPU architecture for which an artifact should be downloaded. diff --git a/_benchmark/reference/commands/generate-data.md b/_benchmark/reference/commands/generate-data.md new file mode 100644 index 00000000..9233750d --- /dev/null +++ b/_benchmark/reference/commands/generate-data.md @@ -0,0 +1,93 @@ +--- +layout: default +title: generate-data +nav_order: 50 +parent: Command reference +grand_parent: Reference +redirect_from: + - /benchmark/commands/generate-data/ +--- + + +# generate-data command + + +The `generate-data` command creates synthetic datasets for benchmarking and testing. OpenSearch Benchmark supports two methods for data generation: using OpenSearch index mappings or custom Python modules with user-defined logic. For more information, see [Synthetic data generation]({{site.url}}{{site.baseurl}}/benchmark/features/synthetic-data-generation/). + +## Usage + +```shell +osb generate-data --index-name --output-path --total-size [OPTIONS] +``` + +**Requirements**: + +- Either `--index-mappings` or `--custom-module` must be specified, but not both. +- When using `--custom-module`, your Python module must include the `generate_synthetic_document(providers, **custom_lists)` function. + +## Data generation methods + +Choose one of the following approaches: + +**Method 1: Using index mappings**: + +```shell +osb generate-data --index-name my-index --index-mappings mapping.json --output-path ./data --total-size 1 +``` + +**Method 2: Using a custom Python module**: + +```shell +osb generate-data --index-name my-index --custom-module custom.py --output-path ./data --total-size 1 +``` + +## Options + +Use the following options with the `generate-data` command. + +| Option | Required/Optional | Description | +|---|---|---| +| `--index-name` or `-n` | Required | The name of the data corpora you want to generate. | +| `--output-path` or `-p` | Required | The path where you want the data to be generated. | +| `--total-size` or `-s` | Required | The total amount of data you want to generate, in GB. | +| `--index-mappings` or `-i` | Conditional (Either `--index-mappings` or `--custom-module` must be specified)| The path to the OpenSearch index mappings you want to use. Required when using mapping-based generation. Cannot be used with `--custom-module`. | +| `--custom-module` or `-m` | Conditional (Either `--index-mappings` or `--custom-module` must be specified)| The path to the Python module that includes your custom logic. Required when using custom logic generation. Cannot be used with `--index-mappings`. The Python module must include the `generate_synthetic_document(providers, **custom_lists)` function. | +| `--custom-config` or `-c` | Optional | The path to a YAML configuration file defining rules for how you want data to be generated. | +| `--test-document` or `-t` | Optional | When this flag is present, OpenSearch Benchmark generates a single synthetic document and outputs it to the console. This provides you with a way to verify that the generated example document aligns with your expectations. When the flag is not present, the entire data corpora will be generated. | + +## Example output + +The following is an example output when generating synthetic data: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + + +[NOTE] ✨ Dashboard link to monitor processes and task streams: [http://127.0.0.1:8787/status] +[NOTE] ✨ For users who are running generation on a virtual machine, consider SSH port forwarding (tunneling) to localhost to view dashboard. +[NOTE] Example of localhost command for SSH port forwarding (tunneling) from an AWS EC2 instance: +ssh -i -N -L localhost:8787:localhost:8787 ec2-user@ + +Total GB to generate: [1] +Average document size in bytes: [412] +Max file size in GB: [40] + +100%|███████████████████████████████████████████████████████████████████| 100.07G/100.07G [3:35:29<00:00, 3.98MB/s] + +Generated 24271844660 docs in 12000 seconds. Total dataset size is 100.21GB. +✅ Visit the following path to view synthetically generated data: /home/ec2-user/ + +----------------------------------- +[INFO] ✅ SUCCESS (took 272 seconds) +----------------------------------- +``` + +## Related documentation + +- [Generating data using index mappings]({{site.url}}{{site.baseurl}}/benchmark/features/synthetic-data-generation/mapping-sdg/) +- [Generating data using custom logic]({{site.url}}{{site.baseurl}}/benchmark/features/synthetic-data-generation/custom-logic-sdg/) \ No newline at end of file diff --git a/_benchmark/reference/commands/index.md b/_benchmark/reference/commands/index.md index 12276d17..3908149a 100644 --- a/_benchmark/reference/commands/index.md +++ b/_benchmark/reference/commands/index.md @@ -3,19 +3,24 @@ layout: default title: Command reference nav_order: 50 has_children: true -parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/commands/index/ +has_toc: false +parent: Reference +redirect_from: + - /benchmark/reference/commands/ --- # OpenSearch Benchmark command reference -This section provides a list of commands supported by OpenSearch Benchmark, including commonly used commands such as `execute-test` and `list`. +OpenSearch Benchmark supports the following commands: -- [compare]({{site.url}}{{site.baseurl}}/benchmark/commands/compare/) -- [download]({{site.url}}{{site.baseurl}}/benchmark/commands/download/) -- [execute-test]({{site.url}}{{site.baseurl}}/benchmark/commands/execute-test/) -- [info]({{site.url}}{{site.baseurl}}/benchmark/commands/info/) -- [list]({{site.url}}{{site.baseurl}}/benchmark/commands/list/) +- [aggregate]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/aggregate/) +- [compare]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/compare/) +- [download]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/download/) +- [generate-data]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/generate-data/) +- [info]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/info/) +- [list]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/list/) +- [redline-test]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/redline-test/) +- [run]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/run/) ## List of common options @@ -25,3 +30,4 @@ All OpenSearch Benchmark commands support the following options: - `--quiet`: Hides as much of the results output as possible. Default is `false`. - `--offline`: Indicates whether OpenSearch Benchmark has a connection to the internet. Default is `false`. +For more information about command options, see [Command flags]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/command-flags/). \ No newline at end of file diff --git a/_benchmark/reference/commands/info.md b/_benchmark/reference/commands/info.md index c8c20ad1..6edb205b 100644 --- a/_benchmark/reference/commands/info.md +++ b/_benchmark/reference/commands/info.md @@ -1,27 +1,28 @@ --- layout: default title: info -nav_order: 75 +nav_order: 70 parent: Command reference -grand_parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/commands/info/ +grand_parent: Reference +redirect_from: + - /benchmark/commands/info/ --- -# info +# info command -The `info` command prints details about an OpenSearch Benchmark component. +The `info` command prints details about an OpenSearch Benchmark component. ## Usage -The following example returns information about a workload named `nyc_taxis`: +The following example returns information about a workload named `nyc_taxis`: ``` opensearch-benchmark info --workload=nyc_taxis ``` -OpenSearch Benchmark returns information about the workload, as shown in the following example response: +OpenSearch Benchmark returns information about the workload, as shown in the following example response: ``` ____ _____ __ ____ __ __ @@ -44,11 +45,11 @@ TestProcedure [searchable-snapshot] Measuring performance for Searchable Snapshot feature. Based on the default test procedure 'append-no-conflicts'. -Schedule: +Schedule: ---------- 1. delete-index -2. create-index +2. create-index 3. check-cluster-health 4. index (8 clients) 5. refresh-after-index @@ -61,17 +62,17 @@ Schedule: 12. wait-for-snapshot-creation 13. delete-local-index 14. restore-snapshot -15. default +15. default 16. range 17. distance_amount_agg 18. autohisto_agg 19. date_histogram_agg ==================================================== -TestProcedure [append-no-conflicts] (run by default) +TestProcedure [append-no-conflicts] (run by default) ==================================================== -Indexes the entire document corpus using a setup that will lead to a larger indexing throughput than the default settings and produce a smaller index (higher compression rate). Document IDs are unique, so all index operations are append only. After that, a couple of queries are run. +Indexes the entire document corpus using a setup that will lead to a larger indexing throughput than the default settings and produce a smaller index (higher compression rate). Document IDs are unique, so all index operations are append only. After that, a couple of queries are run. Schedule: ---------- @@ -143,20 +144,20 @@ Schedule: 8. wait-until-merges-finish -------------------------------- -[INFO] SUCCESS (took 2 seconds) -------------------------------- +---------------------------------- +[INFO] ✅ SUCCESS (took 2 seconds) +---------------------------------- ``` ## Options -You can use the following options with the `info` command: +You can use the following options with the `info` command: - `--workload-repository`: Defines the repository from where OpenSearch Benchmark loads workloads. -- `--workload-path`: Defines the path to a downloaded or custom workload. +- `--workload-path`: Defines the path to a downloaded or custom workload. - `--workload-revision`: Defines a specific revision from the workload source tree that OpenSearch Benchmark should use. -- `--workload`: Defines the workload to use based on the workload's name. You can find a list of preloaded workloads using `opensearch-benchmark list workloads`. +- `--workload`: Defines the workload to use based on the workload's name. You can find a list of preloaded workloads using `opensearch-benchmark list workloads`. - `--test-procedure`: Defines a test procedure to use. You can find a list of test procedures using `opensearch-benchmark list test_procedures`. - `--include-tasks`: Defines a comma-separated list of test procedure tasks to run. By default, all tasks listed in a test procedure array are run. -- `--exclude-tasks`: Defines a comma-separated list of test procedure tasks not to run. +- `--exclude-tasks`: Defines a comma-separated list of test procedure tasks not to run. diff --git a/_benchmark/reference/commands/list.md b/_benchmark/reference/commands/list.md index ed10f02a..265e2d9e 100644 --- a/_benchmark/reference/commands/list.md +++ b/_benchmark/reference/commands/list.md @@ -3,22 +3,23 @@ layout: default title: list nav_order: 80 parent: Command reference -grand_parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/commands/list/ +grand_parent: Reference +redirect_from: + - /benchmark/commands/list/ --- -# list +# list command The `list` command lists the following elements used by OpenSearch Benchmark: -- `telemetry`: Telemetry devices -- `workloads`: Workloads +- `telemetry`: Telemetry devices +- `workloads`: Workloads - `pipelines`: Pipelines -- `test_executions`: Single run of a workload -- `provision_config_instances`: Provisioned configuration instances -- `opensearch-plugins`: OpenSearch plugins +- `test-runs`: Single run of a workload +- `cluster-configs`: OpenSearch cluster configurations +- `opensearch-plugins`: OpenSearch plugins ## Usage @@ -26,13 +27,13 @@ The `list` command lists the following elements used by OpenSearch Benchmark: The following example lists any workload test runs and detailed information about each test: ``` -`opensearch-benchmark list test_executions +`opensearch-benchmark list test-runs ``` -OpenSearch Benchmark returns information about each test. +OpenSearch Benchmark returns information about each test. ``` -benchmark list test_executions +opensearch-benchmark list test-runs ____ _____ __ ____ __ __ / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ @@ -42,10 +43,10 @@ benchmark list test_executions /_/ -Recent test_executions: +Recent test-runs: -TestExecution ID TestExecution Timestamp Workload Workload Parameters TestProcedure ProvisionConfigInstance User Tags workload Revision Provision Config Revision ------------------------------------- ------------------------- ---------- --------------------- ------------------- ------------------------- ----------- ------------------- --------------------------- +TestRun ID TestRun Timestamp Workload Workload Parameters TestProcedure ClusterConfigInstance User Tags workload Revision Cluster Config Revision +------------------------------------ ------------------- ---------- --------------------- ------------------- ----------------------- ----------- ------------------- ------------------------- 729291a0-ee87-44e5-9b75-cc6d50c89702 20230524T181718Z geonames append-no-conflicts 4gheap 30260cf f91c33d0-ec93-48e1-975e-37476a5c9fe5 20230524T170134Z geonames append-no-conflicts 4gheap 30260cf d942b7f9-6506-451d-9dcf-ef502ab3e574 20230524T144827Z geonames append-no-conflicts 4gheap 30260cf @@ -57,18 +58,18 @@ ba643ed3-0db5-452e-a680-2b0dc0350cf2 20230522T224450Z geonames 90f066ae-3d83-41e9-bbeb-17cb0480d578 20230519T194448Z geonames append-no-conflicts external 30260cf 78602e07-0ff8-4f00-9a0e-746fb64e4129 20230519T193258Z geonames append-no-conflicts external 30260cf -------------------------------- -[INFO] SUCCESS (took 0 seconds) -------------------------------- +---------------------------------- +[INFO] ✅ SUCCESS (took 0 seconds) +---------------------------------- ``` ## Options -You can use the following options with the `test` command: +You can use the following options with the `test` command: -- `--limit`: Limits the number of search results for recent test runs. Default is `10`. +- `--limit`: Limits the number of search results for recent test runs. Default is `10`. - `--workload-repository`: Defines the repository from where OpenSearch Benchmark loads workloads. - `--workload-path`: Defines the path to a downloaded or custom workload. -- `--workload-revision`: Defines a specific revision from the workload source tree that OpenSearch Benchmark should use. +- `--workload-revision`: Defines a specific revision from the workload source tree that OpenSearch Benchmark should use. diff --git a/_benchmark/reference/commands/redline-test.md b/_benchmark/reference/commands/redline-test.md new file mode 100644 index 00000000..feab69d6 --- /dev/null +++ b/_benchmark/reference/commands/redline-test.md @@ -0,0 +1,122 @@ +--- +layout: default +title: redline-test +nav_order: 85 +parent: Command reference +grand_parent: Reference +--- + +# Redline testing + +The `--redline-test` command enables OpenSearch Benchmark to automatically determine the maximum request throughput your OpenSearch cluster can handle under increasing load. It dynamically adjusts the number of active clients based on real-time cluster performance, helping with capacity planning and identifying performance regressions. + +When the `--redline-test` flag is used, OpenSearch Benchmark performs the following steps: + +1. **Client initialization**: OpenSearch Benchmark initializes a large number of clients (default: 1,000). You can override this with the optional `--redline-max-clients=` flag. +2. **Feedback mechanism**: OpenSearch Benchmark ramps up the number of active clients. A FeedbackActor monitors real-time request failures and adjusts the client count accordingly. +3. **Shared state coordination**: OpenSearch Benchmark uses Python's multiprocessing library to manage shared dictionaries and queues for inter-process communication: + - **Workers** create and share client state maps with the WorkerCoordinatorActor. + - The **WorkerCoordinatorActor** aggregates client state and forwards it to the FeedbackActor. + - The **FeedbackActor** increases the number of clients until it detects request errors, then pauses clients, waits 30 seconds, and resumes testing. + +The following images provides a visual overview of the redline testing architecture. + +![Redline Overview]({{site.url}}{{site.baseurl}}/images/benchmark/osb-actor-system.png){: width="600" } + + +## Usage + +To perform a redline test, use the `run` command with the `--redline-test` flag and a timed test procedure. + +This test procedure defines a timed workload using the keyword-terms operation. It runs in two phases: + +- **Warmup phase**: The test begins with a warmup period (`warmup-time-period`) to stabilize performance metrics before measurement begins. This helps avoid skewing results with cold-start effects. +- **Measurement phase**: During the `time-period`, OpenSearch Benchmark sends requests at a `target-throughput` (requests per second) using a specified number of clients. The redline test logic will scale the number of active clients from this baseline to determine the cluster's maximum sustainable load. + +The following example timed test procedure is used as input to a redline test, which then dynamically adjusts the client load to find the maximum request throughput your cluster can handle without errors: + +```json +{ + "name": "timed-mode-test-procedure", + "schedule": [ + { + "operation": "keyword-terms", + "warmup-time-period": {% raw %}{{ warmup_time | default(300) | tojson }}{% endraw %}, + "time-period": {% raw %}{{ time_period | default(900) | tojson }}{% endraw %}, + "target-throughput": {% raw %}{{ target_throughput | default(20) | tojson }}{% endraw %}, + "clients": {% raw %}{{ search_clients | default(20) }}{% endraw %} + } + ] +} +``` +{% include copy.html %} + +Run the following command to start a redline test using a timed test procedure against your OpenSearch cluster: + +```bash +opensearch-benchmark run \ + --pipeline=benchmark-only \ + --target-hosts= \ + --workload= \ + --test-procedure=timed-mode-test-procedure \ + --redline-test +``` +{% include copy.html %} + +## Latency- or CPU-based feedback + +OpenSearch Benchmark supports a `timeout` value per request, which cancels a request if it exceeds the specified duration. You can set this value using the `--client-options=timeout:` flag. The default is 10 seconds. + +You can adjust this value to define the maximum request latency that OpenSearch Benchmark should tolerate during redline testing. For example, to determine the highest load your cluster can handle without exceeding 15 seconds of latency, set the timeout in client options to `15`. + +Redline testing also supports CPU-based feedback in addition to latency and request error monitoring. This helps to prevent exceeding safe utilization limits for your cluster. + +### Requirements + +To use CPU-based feedback during redline testing, your setup must meet the following requirements: + +- A metrics store must be configured. Using an in-memory store results in the following error: + + ```bash + [ERROR] Cannot run. Error in worker_coordinator (CPU-based feedback requires a metrics store. You are using an in-memory metrics store) + ``` + +- The `--redline-cpu-max-usage flag` is required. This flag sets the maximum allowed CPU usage (as a percentage) per node during testing. +- The `node-stats` telemetry device is automatically enabled when CPU-based feedback is active. + +### Behavior + +The redline CPU feedback loop operates with the following behaviors: + +- The `FeedbackActor` queries the metrics store at regular intervals to retrieve average CPU usage for each node. +- If any node exceeds the threshold set by `--redline-cpu-max-usage`, the system initiates a scale-down. +- After scaling down, the actor waits before attempting to scale up again. + + +## Results + +During a redline test, OpenSearch Benchmark provides detailed logs with scaling decisions and request failures during the test. At the end of a redline test, OpenSearch Benchmark logs the maximum number of clients that your cluster supported without request errors. + +The following example log output indicates that the redline test detected a `15%` error rate for the keyword-terms operation and determined that the cluster's maximum stable client load before errors occurred was `410`: + +``` +[WARNING] Error rate is 15.0 for operation 'keyword-terms'. Please check the logs. +Redline test finished. Maximum stable client number reached: 410 +``` + +## Configuration tips and test behavior + +Use the following optional command flags to better understand and customize a redline test run: + +- `--redline-scale-step`: Specifies the number of clients to resume in each scaling iteration. +- `--redline-scaledown-percentage`: Specifies the percentage of clients to pause when an error occurs. +- `--redline-post-scaledown-sleep`: Specifies the number of seconds the feedback actor waits before initiating a scale-up after scaling down. +- `--redline-max-clients`: Specifies the maximum number of clients allowed during redline testing. If unset, OpenSearch Benchmark defaults to the number of clients defined in the test procedure. + +### For CPU-based feedback + +Use the following additional flags to configure CPU-based feedback: + +- `--redline-cpu-max-usage`: (Required) Maximum allowed CPU load (as a percentage) per node before triggering a scale-down. +- `--redline-cpu-window-seconds`: Duration (in seconds) over which to average CPU usage per node. Default is 30 seconds. +- `--redline-cpu-check-interval`: Interval (in seconds) between CPU usage checks. Default is 30 seconds. diff --git a/_benchmark/reference/commands/run.md b/_benchmark/reference/commands/run.md new file mode 100644 index 00000000..a51325f3 --- /dev/null +++ b/_benchmark/reference/commands/run.md @@ -0,0 +1,184 @@ +--- +layout: default +title: run +nav_order: 90 +parent: Command reference +grand_parent: Reference +redirect_from: + - /benchmark/commands/execute-test/ + - /benchmark/reference/commands/execute-test/ +--- + + +# run command + + +Whether you're using the included [OpenSearch Benchmark workloads](https://github.com/opensearch-project/opensearch-benchmark-workloads) or a [custom workload]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/), use the `run` command to gather data about the performance of your OpenSearch cluster according to the selected workload. + +## Usage + +The following example runs a test using the `geonames` workload in test mode: + +``` +opensearch-benchmark run --workload=geonames --test-mode +``` + +After the test runs, OpenSearch Benchmark responds with a summary of the benchmark metrics: + +``` +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|-------------------------------:|---------------------:|----------:|-------:| +| Total indexing time | | 28.0997 | min | +| Total merge time | | 6.84378 | min | +| Total refresh time | | 3.06045 | min | +| Total flush time | | 0.106517 | min | +| Total merge throttle time | | 1.28193 | min | +| Median CPU usage | | 471.6 | % | +| Total Young Gen GC | | 16.237 | s | +| Total Old Gen GC | | 1.796 | s | +| Index size | | 2.60124 | GB | +| Total written | | 11.8144 | GB | +| Heap used for segments | | 14.7326 | MB | +| Heap used for doc values | | 0.115917 | MB | +| Heap used for terms | | 13.3203 | MB | +| Heap used for norms | | 0.0734253 | MB | +| Heap used for points | | 0.5793 | MB | +| Heap used for stored fields | | 0.643608 | MB | +| Segment count | | 97 | | +| Min Throughput | index-append | 31925.2 | docs/s | +| Median Throughput | index-append | 39137.5 | docs/s | +| Max Throughput | index-append | 39633.6 | docs/s | +| 50.0th percentile latency | index-append | 872.513 | ms | +| 90.0th percentile latency | index-append | 1457.13 | ms | +| 99.0th percentile latency | index-append | 1874.89 | ms | +| 100th percentile latency | index-append | 2711.71 | ms | +| 50.0th percentile service time | index-append | 872.513 | ms | +| 90.0th percentile service time | index-append | 1457.13 | ms | +| 99.0th percentile service time | index-append | 1874.89 | ms | +| 100th percentile service time | index-append | 2711.71 | ms | +| ... | ... | ... | ... | +| ... | ... | ... | ... | +| Min Throughput | painless_dynamic | 2.53292 | ops/s | +| Median Throughput | painless_dynamic | 2.53813 | ops/s | +| Max Throughput | painless_dynamic | 2.54401 | ops/s | +| 50.0th percentile latency | painless_dynamic | 172208 | ms | +| 90.0th percentile latency | painless_dynamic | 310401 | ms | +| 99.0th percentile latency | painless_dynamic | 341341 | ms | +| 99.9th percentile latency | painless_dynamic | 344404 | ms | +| 100th percentile latency | painless_dynamic | 344754 | ms | +| 50.0th percentile service time | painless_dynamic | 393.02 | ms | +| 90.0th percentile service time | painless_dynamic | 407.579 | ms | +| 99.0th percentile service time | painless_dynamic | 430.806 | ms | +| 99.9th percentile service time | painless_dynamic | 457.352 | ms | +| 100th percentile service time | painless_dynamic | 459.474 | ms | + +------------------------------------- +[INFO] ✅ SUCCESS (took 2634 seconds) +------------------------------------- +``` + +## Options + +Use the following options to customize the `run` command for your use case. Options in this section are categorized by their use case. + +## General settings + +The following options shape how each test runs and how results appear: + +- `--test-mode`: Runs the given workload in test mode, which is useful when checking a workload for errors. +- `--user-tag`: Defines user-specific key-value pairs to be used in metric record as meta information, for example, `intention:baseline-ticket-12345`. +- `--results-format`: Defines the output format for the command line results, either `markdown` or `csv`. Default is `markdown`. +- `--results-number-align`: Defines the column number alignment for when the `compare` command outputs results. Default is `right`. +- `--results-file`: When provided a file path, writes the compare results to the file indicated in the path. +- `--show-in-results`: Determines whether or not to include the comparison in the results file. + + +### Distributions + +The following options set which version of OpenSearch and the OpenSearch plugins the benchmark test uses: + +- `--distribution-version`: Downloads the specified OpenSearch distribution based on version number. For a list of released OpenSearch versions, see [Version history]({{site.url}}{{site.latesturl}}/version-history/). +- `--distribution-repository`: Defines the repository from where the OpenSearch distribution should be downloaded. Default is `release`. +- `--revision`: Defines the current source code revision to use for running a benchmark test. Default is `current`. + - `current`: Uses the source tree's current revision based on your OpenSearch distribution. + - `latest`: Fetches the latest revision from the main branch of the source tree. + - You can also use a timestamp or commit ID from the source tree. When using a timestamp, specify `@ts`, where "ts" is a valid ISO 8601 timestamp, for example, `@2013-07-27T10:37:00Z`. +- `--opensearch-plugins`: Defines which [OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) to install. By default, no plugins are installed. +- `--plugin-params:` Defines a comma-separated list of key:value pairs that are injected verbatim into all plugins as variables. +- `--runtime-jdk`: The major version of JDK to use. +- `--client-options`: Defines a comma-separated list of clients to use. All options are passed to the OpenSearch Python client. Default is `timeout:60`. + +### Cluster + +The following option relates to the target cluster of the benchmark. + +- `--target-hosts`: Defines a comma-separated list of host-port pairs that should be targeted if using the pipeline `benchmark-only`. Default is `localhost:9200`. + + +### Distributed workload generation + +The following options help users who want to use multiple hosts to generate load to the benchmark cluster: + +- `--worker-ips`: Defines a comma-separated list of hosts that coordinate loads. Default is `localhost`. +- `--enable-worker-coordinator-profiling`: Enables an analysis of the performance of OpenSearch Benchmark's worker coordinator. Default is `false`. + +### Provisioning + +The following options help customize how OpenSearch Benchmark provisions OpenSearch and workloads: + +- `--cluster-config-repository`: Defines the repository from which OpenSearch Benchmark loads `cluster-configs` and `cluster-config-instances`. +- `--cluster-config-path`: Defines the path to the `--cluster-config-instance` and any OpenSearch plugin configurations to use. +- `--cluster-config-revision`: Defines a specific Git revision in the `cluster-config` that OpenSearch Benchmark should use. +- `--cluster-config-instance`: Defines the `--cluster-config-instance` to use. You can see possible configuration instances using the command `opensearch-benchmark list cluster-config-instances`. +- `--cluster-config-instance-params`: A comma-separated list of key-value pairs injected verbatim as variables for the `cluster-config-instance`. + + +### Workload + +The following options determine which workload is used to run the test: + +- `--workload-repository`: Defines the repository from which OpenSearch Benchmark loads workloads. +- `--workload-path`: Defines the path to a downloaded or custom workload. +- `--workload-revision`: Defines a specific revision from the workload source tree that OpenSearch Benchmark should use. +- `--workload`: Defines the workload to use based on the workload's name. You can find a list of preloaded workloads using `opensearch-benchmark list workloads`. + +### Test procedures + +The following options define what test procedures the test uses and which operations are contained inside the procedure: + +- `--test-execution-id`: Defines a unique ID for this test run. +Defines the test procedures to use with each workload. You can find a list of test procedures that the workload supports by specifying the workload in the `info` command, for example, `opensearch-benchmark info --workload=`. To look up information on a specific test procedure, use the command `opensearch-benchmark info --workload= --test-procedure=`. +- `--include-tasks`: Defines a comma-separated list of test procedure tasks to run. By default, all tasks listed in a test procedure array are run. +- `--exclude-tasks`: Defines a comma-separated list of test procedure tasks not to run. +- `--enable-assertions`: Enables assertion checks for tasks. Default is `false`. + +### Pipelines + +The `--pipeline` option selects a pipeline to run. You can find a list of pipelines supported by OpenSearch Benchmark by running `opensearch-benchmark list pipelines`. + + +### Telemetry + +The following options enable telemetry devices on OpenSearch Benchmark: + +- `--telemetry`: Enables the provided telemetry devices when the devices are provided using a comma-separated list. You can find a list of possible telemetry devices by using `opensearch-benchmark list telemetry`. +- `--telemetry-params`: Defines a comma-separated list of key-value pairs that are injected verbatim into the telemetry devices as parameters. + + +### Errors + +The following options set how OpenSearch Benchmark handles errors when running tests: + +- `--on-error`: Controls how OpenSearch Benchmark responds to errors. Default is `continue`. + - `continue`: Continues to run the test despite the error. + - `abort`: Aborts the test when an error occurs. +- `--preserve-install`: Keeps the Benchmark candidate and its index. Default is `false`. +- `--kill-running-processes`: When set to `true`, stops any OpenSearch Benchmark processes currently running and allows OpenSearch Benchmark to continue to run. Default is `false`. diff --git a/_benchmark/reference/index.md b/_benchmark/reference/index.md index bc7a423b..6693f247 100644 --- a/_benchmark/reference/index.md +++ b/_benchmark/reference/index.md @@ -1,10 +1,13 @@ --- layout: default -title: OpenSearch Benchmark Reference -nav_order: 25 +title: Reference +nav_order: 75 has_children: true +redirect_from: + - /benchmark/reference/ --- -# OpenSearch Benchmark Reference +# OpenSearch Benchmark reference + +The following section contains reference materials for [commands]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/) and [metrics]({{site.url}}{{site.baseurl}}/benchmark/reference/metrics/) for OpenSearch Benchmark. For the elements that make up a workload, see [Anatomy of a workload]({{site.url}}{{site.baseurl}}/benchmark/anatomy-of-a-workload/). -The following section contains reference materials for commands, metrics, and workloads for OpenSearch Benchmark. \ No newline at end of file diff --git a/_benchmark/reference/metrics/index.md b/_benchmark/reference/metrics/index.md index 63e5a799..f806175c 100644 --- a/_benchmark/reference/metrics/index.md +++ b/_benchmark/reference/metrics/index.md @@ -3,24 +3,27 @@ layout: default title: Metrics reference nav_order: 25 has_children: true -parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/metrics/index/ +parent: Reference +redirect_from: + - /benchmark/metrics/ + - /benchmark/metrics/index/ + - /benchmark/reference/metrics/ --- -# Metrics +# OpenSearch Benchmark metrics -After a workload completes, OpenSearch Benchmark stores all metric records within its metrics store. These metrics can be kept in memory or in an OpenSearch cluster. +After a workload completes, OpenSearch Benchmark stores all metric records within its metrics store. These metrics can be kept in memory or in an OpenSearch cluster. ## Storing metrics -You can specify whether metrics are stored in memory or in a metrics store while running the benchmark by setting the [`datastore.type`](https://opensearch.org/docs/latest/benchmark/configuring-benchmark/#results_publishing) parameter in your `benchmark.ini` file. +You can specify whether metrics are stored in memory or in a metrics store while running the benchmark by setting the [`datastore.type`]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/#reporting) parameter in your `benchmark.ini` file. ### In memory -If you want to store metrics in memory while running the benchmark, provide the following settings in the `results_publishing` section of `benchmark.ini`: +If you want to store metrics in memory while running the benchmark, provide the following settings in the `reporting` section of `benchmark.ini`: ```ini -[results_publishing] +[reporting] datastore.type = in-memory datastore.host = datastore.port = @@ -32,10 +35,10 @@ datastore.password = ### OpenSearch -If you want to store metrics in an external OpenSearch memory store while running the benchmark, provide the following settings in the `results_publishing` section of `benchmark.ini`: +If you want to store metrics in an external OpenSearch memory store while running the benchmark, provide the following settings in the `reporting` section of `benchmark.ini`: ```ini -[results_publishing] +[reporting] datastore.type = opensearch datastore.host = datastore.port = 443 @@ -43,10 +46,10 @@ datastore.secure = true datastore.ssl.verification_mode = none datastore.user = datastore.password = -datastore.number_of_replicas = -datastore.number_of_shards = +datastore.number_of_replicas = +datastore.number_of_shards = ``` -When neither `datastore.number_of_replicas` nor `datastore.number_of_shards` is provided, OpenSearch uses the default values: `0` for the number of replicas and `1` for the number of shards. If these settings are changed after the data store cluster is created, the new replica and shard settings will only apply when new results indexes are created at the end of the month. +When neither `datastore.number_of_replicas` nor `datastore.number_of_shards` is provided, OpenSearch uses the default values: `0` for the number of replicas and `1` for the number of shards. If these settings are changed after the data store cluster is created, the new replica and shard settings will only apply when new result indexes are created at the end of the month. After you run OpenSearch Benchmark configured to use OpenSearch as a data store, OpenSearch Benchmark creates three indexes: diff --git a/_benchmark/reference/metrics/metric-keys.md b/_benchmark/reference/metrics/metric-keys.md index aa45c9d9..0931e067 100644 --- a/_benchmark/reference/metrics/metric-keys.md +++ b/_benchmark/reference/metrics/metric-keys.md @@ -3,8 +3,9 @@ layout: default title: Metric keys nav_order: 35 parent: Metrics reference -grand_parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/metrics/metric-keys/ +grand_parent: Reference +redirect_from: + - /benchmark/metrics/metric-keys/ --- # Metric keys @@ -15,9 +16,9 @@ Metric keys are the metrics that OpenSearch Benchmark stores, based on the confi - `latency`: The time period between submitting a request and receiving the complete response. This also includes wait time, such as the time the request spends waiting until it is ready to be serviced by OpenSearch Benchmark. - `service_time`: The time period between sending a request and receiving the corresponding response. This metric is similar to latency but does not include wait time. - `processing_time`: The time period between starting to process a request and receiving the complete response. Contrary to service time, this metric also includes the OpenSearch Benchmark client-side processing overhead. Large differences between service time and processing time indicate a high overhead in the client and can thus point to a potential client-side bottleneck, which requires investigation. -- `throughput`: The number of operations that OpenSearch Benchmark can perform within a certain time period, usually per second. See the [workload reference]({{site.url}}{{site.baseurl}}/benchmark/workloads/index/) for definitions of operation types. -- `disk_io_write_bytes`: The number of bytes written to disk during the benchmark. On Linux, this metric corresponds to only the bytes that have been written by OpenSearch Benchmark. On Mac OS, it includes the number of bytes written by all processes. -- `disk_io_read_bytes`: The number of bytes read from disk during the benchmark. On MacOS, this includes the number of bytes written by all processes. +- `throughput`: The number of operations that OpenSearch Benchmark can perform within a certain time period, usually per second. See [`operations`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/operations/) for definitions of operation types. +- `disk_io_write_bytes`: The number of bytes written to disk during the benchmark. On Linux, this metric corresponds to only the bytes that have been written by OpenSearch Benchmark. On macOS, it includes the number of bytes written by all processes. +- `disk_io_read_bytes`: The number of bytes read from disk during the benchmark. On macOS, this includes the number of bytes written by all processes. - `node_startup_time`: The amount of time, in seconds, from the start of the process until the node is running. - `node_total_young_gen_gc_time`: The total runtime of the young-generation garbage collector across the whole cluster, as reported by the Nodes Stats API. - `node_total_young_gen_gc_count`: The total number of young-generation garbage collections across the whole cluster, as reported by the Nodes Stats API. diff --git a/_benchmark/reference/metrics/metric-records.md b/_benchmark/reference/metrics/metric-records.md index 659f8b82..dd9846e8 100644 --- a/_benchmark/reference/metrics/metric-records.md +++ b/_benchmark/reference/metrics/metric-records.md @@ -3,8 +3,9 @@ layout: default title: Metric records nav_order: 30 parent: Metrics reference -grand_parent: OpenSearch Benchmark Reference -redirect_from: /benchmark/metrics/metric-records/ +grand_parent: Reference +redirect_from: + - /benchmark/metrics/metric-records/ --- # Metric records @@ -25,7 +26,7 @@ OpenSearch Benchmark stores metrics in the `benchmark-metrics-*` indexes. A new "environment": "local", "workload": "geonames", "test_procedure": "append-no-conflicts", - "provision-config-instance": "external", + "cluster-config-instance": "external", "name": "service_time", "value": 607.8001195564866, "unit": "ms", @@ -78,7 +79,7 @@ The timestamp of when the sample was taken since the epoch, in milliseconds. For ## relative-time-ms -The relative time since the start of the benchmark, in milliseconds. This is useful for comparing time-series graphs across multiple tests. For example, you can compare the indexing throughput over time across multiple tests. +The relative time since the start of the benchmark, in milliseconds. This is useful for comparing time-series graphs across multiple tests. For example, you can compare the indexing throughput over time across multiple tests. ## test-execution-id @@ -99,7 +100,7 @@ The timestamp of when the workload was invoked (always in UTC). The `environment` describes the origin of a metric record. This is defined when initially [configuring]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/) OpenSearch Benchmark. You can use separate environments for different benchmarks but store the metric records in the same index. -## workload, test_procedure, provision-config-instance +## workload, test_procedure, cluster-config-instance The workload, test procedures, and configuration instances for which the metrics are produced. @@ -123,11 +124,11 @@ Determines whether to configure a benchmark to run in warmup mode by setting it The meta information for each metric record, including the following: - CPU info: The number of physical and logical cores and the model name. -- OS info: The name and version of the operating system. +- Operating system info: The name and version of the operating system. - Hostname. - Node name: A unique name given to each node when OpenSearch Benchmark provisions the cluster. -- Source revision: The Git hash of the version of OpenSearch that is benchmarked. -- Distribution version: The distribution version of OpenSearch that is benchmarked. +- Source revision: The Git hash of the version of OpenSearch that is benchmarked. +- Distribution version: The distribution version of OpenSearch that is benchmarked. - Custom tags: You can define custom tags by using the command line flag `--user-tags`. The tags are prefixed by `tag_` in order to avoid accidental clashes with OpenSearch Benchmark internal tags. - Operation specific: An optional substructure of the operation. For bulk requests, this may be the number of documents; for searches, the number of hits. diff --git a/_benchmark/reference/summary-report.md b/_benchmark/reference/summary-report.md index d5396cd3..96430876 100644 --- a/_benchmark/reference/summary-report.md +++ b/_benchmark/reference/summary-report.md @@ -2,175 +2,243 @@ layout: default title: Summary report nav_order: 40 -parent: Metrics +parent: Reference +redirect_from: + - /benchmark/user-guide/understanding-results/summary-reports/ + - /benchmark/user-guide/understanding-results/ --- # Summary report -At the end of each run, OpenSearch Benchmark shows a summary report based on the metric keys defined in the workload. This page gives details on each line of the summary report and that line's associated metric key. +At the end of each test run, OpenSearch Benchmark prints a summary report of metrics such as service time, throughput, latency, and more. These metrics show how the selected workload performed on the benchmarked OpenSearch cluster. -## Cumulative indexing time of primary shards +## Example output -**Corresponding metrics key**: `indexing_total_time` +The following example shows a typical summary report: + +```bash +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 0.02655 | min | +| Min cumulative indexing time across primary shards | | 0 | min | +| Median cumulative indexing time across primary shards | | 0.00176667 | min | +| Max cumulative indexing time across primary shards | | 0.0140333 | min | +| Cumulative merge time of primary shards | | 0.0102333 | min | +| Store size | | 0.000485923 | GB | +| Segment count | | 32 | | +| Min Throughput | index | 3008.97 | docs/s | +| Mean Throughput | index | 3008.97 | docs/s | +| Median Throughput | index | 3008.97 | docs/s | +| Max Throughput | index | 3008.97 | docs/s | +| 50th percentile latency | index | 351.059 | ms | +| 100th percentile latency | index | 365.058 | ms | +| 50th percentile service time | index | 351.059 | ms | +| 100th percentile service time | index | 365.058 | ms | +| error rate | index | 0 | % | +| Min Throughput | match_all | 36.09 | ops/s | +| Mean Throughput | match_all | 36.09 | ops/s | +| Median Throughput | match_all | 36.09 | ops/s | +| Max Throughput | match_all | 36.09 | ops/s | +| 100th percentile latency | match_all | 35.9822 | ms | +| 100th percentile service time | match_all | 7.93048 | ms | +| error rate | match_all | 0 | % | +| ... | ... | ... | ... | +``` + +Metrics unique to the cluster begin at the `index` task line. For example: + +- To assess how much load your cluster can handle, the `index` task metrics show the number of documents ingested during the workload run and the ingestion error rate. +- To assess query latency and service time, the `match_all` and `term` tasks show the number of query operations performed per second, measurable query latency, and query operation error rate. + +Which values are shown in the report depends on the `--show-in-results` flag; see [Storing results](#storing-results). + +## Storing results + +Results are stored in-memory by default. When stored in-memory, they're written to `~/.benchmark/benchmarks/test-runs//`, named by the `test_run_id` of the most recent workload test. + +While [running a test]({{site.url}}{{site.baseurl}}/benchmark/reference/commands/run/#general-settings), the following flags customize how results are stored: + +- `--results-file`: File path to write the summary report to. +- `--results-format`: Output format for the summary. `markdown` or `csv`. Default is `markdown`. +- `--show-in-results`: Which values appear in the published report. `available`, `all-percentiles`, or `all`. Default is `available`. +- `--user-tag`: Key-value pairs stored with the run as metadata (for example, `intention:baseline-ticket-12345`). Useful when storing metrics in external storage. + +To store results outside the test-runs directory, configure an external metrics data store. For nightly published results, see the OpenSearch Benchmark [nightly test dashboard](https://opensearch.org/benchmarks). + +## Metric reference + +The following metrics are included in the summary report. + +### Cumulative indexing time of primary shards + +**Corresponding metric key**: `indexing_total_time` The cumulative time used for indexing as reported by the Index Stats API. Note that this is not wall-clock time, for example, if M indexing threads ran for N minutes, report M * N minutes, not N minutes. -## Cumulative indexing time across primary shards +### Cumulative indexing time across primary shards -**Corresponding metrics key:** `indexing_total_time` (property: `per-shard`) +**Corresponding metric key**: `indexing_total_time` (property: `per-shard`) The minimum, median, and maximum cumulative time used for indexing across primary shards as reported by the Index Stats API. -## Cumulative indexing throttle time of primary shards +### Cumulative indexing throttle time of primary shards -**Corresponding metrics key:** `indexing_throttle_time` +**Corresponding metric key**: `indexing_throttle_time` The cumulative time that the indexing has been throttled as reported by the Index Stats API. Note that this is not wall-clock time, for example, if M indexing threads ran for N minutes, report M * N minutes, not N minutes. -## Cumulative indexing throttle time across primary shards +### Cumulative indexing throttle time across primary shards -**Corresponding metrics key:** `indexing_throttle_time` (property: `per-shard`) +**Corresponding metric key**: `indexing_throttle_time` (property: `per-shard`) The minimum, median, and maximum cumulative time used that indexing has been throttled across primary shards as reported by the Index Stats API. -## Cumulative merge time of primary shards +### Cumulative merge time of primary shards -**Corresponding metrics key:** `merges_total_time` +**Corresponding metric key**: `merges_total_time` The cumulative runtime of merges of primary shards, as reported by the index stats API. Note that this is not wall-clock time. -## Cumulative merge count of primary shards +### Cumulative merge count of primary shards -**Corresponding metrics key:** `merges_total_count` +**Corresponding metric key**: `merges_total_count` The cumulative number of merges of primary shards, as reported by the Index Stats API under `_all/primaries`. -## Cumulative merge time across primary shards +### Cumulative merge time across primary shards -**Corresponding metrics key:** `merges_total_time` (property: `per-shard`) +**Corresponding metric key**: `merges_total_time` (property: `per-shard`) The minimum, median, and maximum cumulative time of merges across primary shards as reported by the Index Stats API. -## Cumulative refresh time of primary shards +### Cumulative refresh time of primary shards -**Corresponding metrics key**: `refresh_total_time` +**Corresponding metric key**: `refresh_total_time` The cumulative time used for index refresh of primary shards as reported by the Index Stats API. Note that this is not wall-clock time. -## Cumulative refresh count of primary shards +### Cumulative refresh count of primary shards -**Corresponding metrics key:** `refresh_total_count` +**Corresponding metric key**: `refresh_total_count` The cumulative number of refreshes of primary shards as reported by the Index Stats API under `_all/primaries`. -## Cumulative refresh time across primary shards +### Cumulative refresh time across primary shards -**Corresponding metrics key:** `refresh_total_time` (property: `per-shard`) +**Corresponding metric key**: `refresh_total_time` (property: `per-shard`) The minimum, median, and maximum cumulative time for index refresh across primary shards as reported by the Index Stats API. -## Cumulative flush time of primary shards +### Cumulative flush time of primary shards -**Corresponding metrics key:** `flush_total_time` +**Corresponding metric key**: `flush_total_time` The cumulative time used for index flush of primary shards as reported by the Index Stats API. Note that this is not wall-clock time. -## Cumulative flush count of primary shards +### Cumulative flush count of primary shards -**Corresponding metrics key**: `flush_total_count` +**Corresponding metric key**: `flush_total_count` The cumulative number of flushes of primary shards as reported by the Index Stats API under `_all/primaries`. -## Cumulative flush time across primary shards +### Cumulative flush time across primary shards -**Corresponding metrics key:** `flush_total_time` (property: `per-shard`) +**Corresponding metric key**: `flush_total_time` (property: `per-shard`) The minimum, median, and maximum time for index flush across primary shards as reported by the Index Stats API. -## Cumulative merge throttle time of primary shards +### Cumulative merge throttle time of primary shards -**Corresponding metrics key:** `merges_total_throttled_time` +**Corresponding metric key**: `merges_total_throttled_time` The cumulative time within merges that have been throttled as reported by the Index Stats API. Note that this is not wall-clock time. -## Cumulative merge throttle time across primary shards +### Cumulative merge throttle time across primary shards -Corresponding metrics key: `merges_total_throttled_time` (property: `per-shard`) +**Corresponding metric key**: `merges_total_throttled_time` (property: `per-shard`) The minimum, median, and maximum cumulative time that merges have been throttled across primary shards as reported by the Index Stats API. -## ML processing time +### ML processing time -Corresponding metrics key: `ml_processing_time` +**Corresponding metric key**: `ml_processing_time` The minimum, mean, median, and maximum time in milliseconds that a machine learning (ML) job has spent processing a single bucket. -## Total young gen GC time +### Total young gen GC time -**Corresponding metrics key**: `node_total_young_gen_gc_time` +**Corresponding metric key**: `node_total_young_gen_gc_time` The total runtime of the young generation (gen) garbage collector (GC) across the whole cluster as reported by the Node Stats API. -## Total young gen GC count +### Total young gen GC count -**Corresponding metrics key:** `node_total_young_gen_gc_count` +**Corresponding metric key**: `node_total_young_gen_gc_count` The total number of young gen GCs across the whole cluster as reported by the Node Stats API. -## Total old gen GC time +### Total old gen GC time -**Corresponding metrics key:** `node_total_old_gen_gc_time` +**Corresponding metric key**: `node_total_old_gen_gc_time` The total runtime of the old gen GC across the whole cluster as reported by the Node Stats API. -## Total old gen GC count +### Total old gen GC count -**Corresponding metrics key:** `node_total_old_gen_gc_count` +**Corresponding metric key**: `node_total_old_gen_gc_count` The total number of old gen GCs across the whole cluster as reported by the Node Stats API. -## Total ZGC cycles GC time +### Total ZGC cycles GC time -**Corresponding metrics key**: `node_total_zgc_cycles_gc_count` +**Corresponding metric key**: `node_total_zgc_cycles_gc_count` The total number of garbage collections performed by the Z garbage collector (ZGC) across the whole cluster as reported by the Node Stats API. -## Total ZGC pauses GC time +### Total ZGC pauses GC time -**Corresponding metrics key**: `node_total_zgc_pauses_gc_time` +**Corresponding metric key**: `node_total_zgc_pauses_gc_time` The total time spent in stop-the-world pauses by the ZGC across the whole cluster as reported by the Node Stats API. -## Total ZGC pauses GC count +### Total ZGC pauses GC count -**Corresponding metrics key**: `node_total_zgc_pauses_gc_count` +**Corresponding metric key**: `node_total_zgc_pauses_gc_count` The total number of stop-the-world pauses performed by the ZGC across the whole cluster as reported by the Node Stats API. -## Store size +### Store size -**Corresponding metrics key**: `store_size_in_bytes` +**Corresponding metric key**: `store_size_in_bytes` The index size in bytes (excluding the translog) as reported by the Index Stats API. -## Translog size +### Translog size -**Corresponding metrics key**: `translog_size_in_bytes` +**Corresponding metric key**: `translog_size_in_bytes` The translog size in bytes as reported by the Index Stats API. -## Heap used for X +### Heap used for X -**Corresponding metrics keys**: `segments_*_in_bytes` +**Corresponding metric keys**: `segments_*_in_bytes` The number of bytes used for the corresponding item as reported by the Index Stats API. The item may be any of the following: @@ -181,80 +249,78 @@ The number of bytes used for the corresponding item as reported by the Index Sta - Stored fields -## Segments count +### Segments count -**Corresponding metrics key**: `segments_count` +**Corresponding metric key**: `segments_count` The total number of segments as reported by the Index Stats API. -## Total ingest pipeline count +### Total ingest pipeline count -**Corresponding metrics key**: `ingest_pipeline_cluster_count` +**Corresponding metric key**: `ingest_pipeline_cluster_count` The total number of documents ingested by all nodes within the cluster over the race duration. -## Total ingest pipeline time +### Total ingest pipeline time -**Corresponding metrics key**: `ingest_pipeline_cluster_time` +**Corresponding metric key**: `ingest_pipeline_cluster_time` The total time in milliseconds spent preprocessing ingest documents by all nodes within the cluster over the race duration. -## Total ingest pipeline failed +### Total ingest pipeline failed -**Corresponding metrics key**: `ingest_pipeline_cluster_failed` +**Corresponding metric key**: `ingest_pipeline_cluster_failed` The total number of failed ingest operations by all nodes within the cluster over the race duration. -## Throughput +### Throughput -**Corresponding metrics key**: `throughput` +**Corresponding metric key**: `throughput` Reports the minimum, mean, median, and maximum throughput for each task. The number of operations that OpenSearch can perform within a certain time period per second. The report includes the minimum, mean, median, and maximum throughput for each task. -## Latency +### Latency -**Corresponding metrics key**: `latency` +**Corresponding metric key**: `latency` The time period between submission of a request and receiving the complete response. It includes the wait time the request spends waiting before it is processed by OpenSearch. OpenSearch reports several percentile numbers for each task. Which percentiles are shown depends on how many requests OpenSearch can capture during the latency period. -## Service time +### Service time -**Corresponding metrics key**: `service_time` +**Corresponding metric key**: `service_time` The time period between sending a request and receiving the corresponding response. It does not include waiting time. While many load testing tools refer to this metric as _latency_, it is not the same. OpenSearch reports several percentile numbers for each task. Which percentiles are shown depends on how many requests OpenSearch can capture during the latency period. -## Processing time +### Processing time Processing time is only reported if the setting `output.processingtime` is set to `true` in the OpenSearch Benchmark configuration file. {: note.} -**Corresponding metrics key**: `processing_time` +**Corresponding metric key**: `processing_time` The time period between start of request processing and retrieval of the complete response. Unlike `service_time`, this metric includes OpenSearch’s client-side processing overhead. The larger the difference between `service_time` and `processing_time`, the higher the overhead in the client. Depending on your processing goals, this can point to a potential client-side bottleneck that requires investigation. -## Error rate +### Error rate -Corresponding metrics key: `service_time`. Each `service_time` record has a `meta.success` flag. +**Corresponding metric key**: `service_time`. Each `service_time` record has a `meta.success` flag. The ratio of erroneous responses relative to the total number of responses. Any exception thrown by the Python OpenSearch client is considered erroneous, for example, HTTP response codes 4xx, 5xx, or network errors (network unreachable). You can investigate the root cause by inspecting OpenSearch and OpenSearch Benchmark logs and rerunning the benchmark. -## Disk usage +### Disk usage -**Corresponding metrics keys**: `disk_usage_total` +**Corresponding metric keys**: `disk_usage_total` **Metric metadata**: `index` and `field` The total number of bytes that a single field uses on disk. Recorded for each field returned by the Disk Usage API even if the total is `0`. - - diff --git a/_benchmark/reference/telemetry.md b/_benchmark/reference/telemetry.md index a5e9bbeb..a7cb766a 100644 --- a/_benchmark/reference/telemetry.md +++ b/_benchmark/reference/telemetry.md @@ -2,12 +2,24 @@ layout: default title: Telemetry devices nav_order: 45 -parent: OpenSearch Benchmark Reference +parent: Reference +redirect_from: + - /benchmark/user-guide/understanding-results/telemetry/ + - /benchmark/user-guide/telemetry/ --- # Telemetry devices -Telemetry devices give you additional insights on benchmark results. To view a list of the available telemetry devices, use the command `opensearch-benchmark list telemetry`. +Telemetry devices provide additional insights for benchmarking results. + +Telemetry results do not appear in the summary report. To visualize them, ingest the data into OpenSearch and visualize the data in OpenSearch Dashboards. + +To view a list of the available telemetry devices, use the `opensearch-benchmark list telemetry` command. After you've selected a supported telemetry device, you can activate the device when running a test by providing the `--telemetry` command flag. For example, to use the `jfr` device with the `geonames` workload, run the following command: + +```json +opensearch-benchmark workload --workload=geonames --telemetry=jfr +``` +{% include copy-curl.html %} All telemetry devices with a `--stats` can be used with clusters not provisioned by OpenSearch Benchmark. These devices are referred to as **Runtime level telemetry devices**. Alternatively, **Setup level telemetry devices** encompass devices that can only be used when OpenSearch Benchmark provisions a cluster. @@ -38,7 +50,7 @@ The `jit` telemetry device enables JIT compiler logs for the benchmark candidate ## gc -The `gc` telemetry device enables garbage collector (GC) logs for the benchmark candidate. You can use tools such as GCViewer to analyze the GC logs. +The `gc` telemetry device enables garbage collector (GC) logs for the benchmark candidate. You can use tools such as `GCViewer` to analyze the GC logs. If the runtime JDK is Java 9 or higher, you can specify the `gc-log-config` parameter. The GC logging configuration consists of a list of tags and levels, such as the default value `gc*=info,safepoint=info,age*=trace`. Run `java -Xlog:help` to view a list of available levels and tags. @@ -57,9 +69,9 @@ The `node-stats` telemetry device regularly calls the cluster [Node Stats API]({ - Index stats: `indices` - Thread pool stats: `thread_pool` - JVM buffer pool stats: `jvm.buffer_pools` -- JVM gc stats: `jvm.gc` -- OS mem stats: `os.mem` -- OS cgroup stats: `os.cgroup` +- JVM `gc` stats: `jvm.gc` +- Operating system mem stats: `os.mem` +- Operating system `cgroup` stats: `os.cgroup` - JVM mem stats: `jvm.mem` - Circuit breaker stats: `breakers` - Network-related stats: `transport` @@ -74,8 +86,8 @@ The `node-stats` device supports the following parameters: - `node-stats-include-buffer-pools`: A Boolean indicating whether buffer pool stats should be included. Default is `true`. - `node-stats-include-breakers`: A Boolean indicating whether circuit breaker stats should be included. Default is `true`. - `node-stats-include-gc`: A Boolean indicating whether JVM GC stats should be included. Default is `true`. -- `node-stats-include-mem`: A Boolean indicating whether both JVM heap and OS mem stats should be included. Default is `true`. -- `node-stats-include-cgroup`: A Boolean to include operating system cgroup stats. Memory stats are omitted since OpenSearch outputs them as string values. Use the `os_mem_*` fields instead. Default is `true`. +- `node-stats-include-mem`: A Boolean indicating whether both JVM heap and operating system mem stats should be included. Default is `true`. +- `node-stats-include-cgroup`: A Boolean to include operating system `cgroup` stats. Memory stats are omitted since OpenSearch outputs them as string values. Use the `os_mem_*` fields instead. Default is `true`. - `node-stats-include-network`: A Boolean indicating whether network-related stats should be included. Default is `true`. - `node-stats-include-process`: A Boolean indicating whether process CPU stats should be included. Default is `true`. - `node-stats-include-indexing-pressure`: A Boolean indicating whether indexing presser stats should be included. Default is `true`. @@ -86,10 +98,12 @@ The `node-stats` device supports the following parameters: The `recovery-stats` telemetry device regularly calls the [CAT Recovery API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/) and records one metrics document per shard. -This telemetry device supports the following parameters: +The `recovery-stats` telemetry device supports the following parameters. -- `searchable-snapshots-stats-indices` A string with the index pattern, or list of index patterns, that searchable snapshots stats should additionally be collected from. If unset, only cluster-level stats will be collected. Default is `None`. -- `searchable-snapshots-stats-sample-interval`: A positive number greater than zero denoting the sampling interval in seconds. Default is `1`. +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `recovery-stats-indices` | String or JSON object | Specifies the indexes from which to collect recovery statistics. Valid values are:
- A string that specifies an index pattern.
- A JSON object that maps cluster names to index patterns when `--target-hosts` is used to define multiple clusters.

If not set, recovery statistics are collected for all indexes. Default is `None`. | +| `recovery-stats-sample-interval` | Number | A positive number denoting the sampling interval, in seconds. Default is `1`. | ## shard-stats @@ -103,7 +117,7 @@ This device supports the `shard-stats-sample-interval` parameter, which defines ## data-stream-stats -The `data-stream-stats` telemetry device regularly calls the [Data Stream Stats API]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/#step-2-create-a-data-stream) and records one metrics document for cluster-level stats (`_all`) and one metrics document per data stream. +The `data-stream-stats` telemetry device regularly calls the [Get Data Stream Stats API]({{site.url}}{{site.baseurl}}/api-reference/data-stream/data-stream-stats/) and records one metrics document for cluster-level stats (`_all`) and one metrics document per data stream. The following is an example of recorded documents given two data streams in the cluster: diff --git a/_benchmark/reference/workloads/corpora.md b/_benchmark/reference/workloads/corpora.md index daa2ae65..2d54adec 100644 --- a/_benchmark/reference/workloads/corpora.md +++ b/_benchmark/reference/workloads/corpora.md @@ -1,14 +1,14 @@ --- layout: default title: corpora -parent: Workload reference -grand_parent: OpenSearch Benchmark Reference -nav_order: 70 -redirect_from: /benchmark/workloads/corpora/ +parent: Anatomy of a workload +nav_order: 20 +redirect_from: + - /benchmark/workloads/corpora/ --- -# corpora +# corpora element The `corpora` element contains all the document corpora used by the workload. You can use document corpora across workloads by copying and pasting any corpora definitions. @@ -48,7 +48,7 @@ Each entry in the `documents` array consists of the following options. Parameter | Required | Type | Description :--- | :--- | :--- | :--- `source-file` | Yes | String | The file name containing the corresponding documents for the workload. When using OpenSearch Benchmark locally, documents are contained in a JSON file. When providing a `base_url`, use a compressed file format: `.zip`, `.bz2`, `.gz`, `.tar`, `.tar.gz`, `.tgz`, or `.tar.bz2`. The compressed file must have one JSON file containing the name. -`document-count` | Yes | Integer | The number of documents in the `source-file`, which determines which client indexes correlate to which parts of the document corpus. Each N client receives an Nth of the document corpus. When using a source that contains a document with a parent-child relationship, specify the number of parent documents. +`document-count` | Yes | Integer | The number of documents in the `source-file`, which determines which client indexes correlate to which parts of the document corpus. Each N client receives an Nth of the document corpus. When using a source that contains a document with a parent/child relationship, specify the number of parent documents. `base-url` | No | String | An http(s), Amazon Simple Storage Service (Amazon S3), or Google Cloud Storage URL that points to the root path where OpenSearch Benchmark can obtain the corresponding source file. `source-format` | No | String | Defines the format OpenSearch Benchmark uses to interpret the data file specified in `source-file`. Only `bulk` is supported. `compressed-bytes` | No | Integer | The size, in bytes, of the compressed source file, indicating how much data OpenSearch Benchmark downloads. diff --git a/_benchmark/reference/workloads/indices.md b/_benchmark/reference/workloads/indices.md index daaf6101..717fc790 100644 --- a/_benchmark/reference/workloads/indices.md +++ b/_benchmark/reference/workloads/indices.md @@ -1,20 +1,22 @@ --- layout: default title: indices -parent: Workload reference -grand_parent: OpenSearch Benchmark Reference -nav_order: 65 -redirect_from: /benchmark/workloads/indices/ +parent: Anatomy of a workload +nav_order: 10 +redirect_from: + - /benchmark/workloads/indices/ --- -# indices +# indices element -The `indices` element contains a list of all indices used in the workload. +The `indices` element contains a list of all indexes used in the workload. ## Example +To create an index, specify its name. To add definitions to your index, use the `body` option and point it to the JSON file containing the index definitions: + ```json "indices": [ { diff --git a/_benchmark/reference/workloads/operations.md b/_benchmark/reference/workloads/operations.md index ed6e6b85..ecc88cbb 100644 --- a/_benchmark/reference/workloads/operations.md +++ b/_benchmark/reference/workloads/operations.md @@ -1,22 +1,21 @@ --- layout: default title: operations -parent: Workload reference -grand_parent: OpenSearch Benchmark Reference -nav_order: 100 +parent: Anatomy of a workload +nav_order: 30 --- -# operations +# operations element -The `operations` element contains a list of all available operations for specifying a schedule. +The `operations` element lists the OpenSearch API operations that the workload performs and how they are parameterized. For example, you can define an operation named `create-index` that creates an index in the benchmark cluster to which OpenSearch Benchmark can write documents. The [`schedule`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/schedule/) element then references these operations by name to specify the order in which they run. ## bulk -The `bulk` operation type allows you to run [bulk](/api-reference/document-apis/bulk/) requests as a task. +The `bulk` operation type allows you to run [bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) requests as a task. ### Usage @@ -29,6 +28,7 @@ The following example shows a `bulk` operation type with a `bulk-size` of `5000` "bulk-size": 5000 } ``` +{% include copy.html %} ### Split documents among clients @@ -54,10 +54,10 @@ Parameter | Required | Type | Description `conflicts` | No | String | Defines the type of index `conflicts` to simulate. If not specified, none are simulated. Valid values are ‘sequential’, which replaces a document ID with a sequentially increasing document ID, and ‘random’, which replaces a document ID with a random document ID. `conflict-probability` | No | Percentage | Defines how many of the documents are replaced when a conflict exists. Combining `conflicts=sequential` and `conflict-probability=0` makes OpenSearch Benchmark generate the index ID itself instead of using OpenSearch's automatic ID generation. Valid values are numbers between 0 and 100. Default is `25%`. `on-conflict` | No | String | Determines whether OpenSearch should use the action `index` or `update` index for ID conflicts. Default is `index`, which creates a new index during ID conflicts. -`recency` | No | Number | Uses a number between 0 and 1 to indicate recency. A recency closer to `1` biases conflicting IDs toward more recent IDs. A recency closer to 0 considers all IDs for ID conflicts. +`recency` | No | Number | Uses a number between 0 and 1 to indicate recency. A recency closer to `1` biases conflicting IDs toward more recent IDs. A recency closer to 0 considers all IDs for ID conflicts. `detailed-results` | No | Boolean | Records more detailed [metadata](#metadata) for bulk requests. As OpenSearch Benchmark analyzes the corresponding bulk response in more detail, additional overhead may be incurred, which can skew measurement results. This property must be set to `true` so that OpenSearch Benchmark logs individual bulk request failures. `timeout` | No | Duration | Defines the amount of time (in minutes) that OpenSearch waits per action until completing the processing of the following operations: automatic index creation, dynamic mapping updates, and waiting for active shards. Default is `1m`. -`refresh` | No | String | Controls OpenSearch refresh behavior for bulk requests that use the `refresh` bulk API query parameter. Valid values are `true`, which refreshes target shards in the background; `wait_for`, which blocks bulk requests until affected shards have been refreshed; and `false`, which uses the default refresh behavior. +`refresh` | No | String | Controls OpenSearch refresh behavior for bulk requests that use the `refresh` Bulk API query parameter. Valid values are `true`, which refreshes target shards in the background; `wait_for`, which blocks bulk requests until affected shards have been refreshed; and `false`, which uses the default refresh behavior. ### Metadata @@ -82,9 +82,9 @@ If `detailed-results` is `true`, the following metadata is returned: ## create-index -The `create-index` operation runs the [Create Index API](/api-reference/index-apis/create-index/). It supports the following two modes of index creation: +The `create-index` operation runs the [Create Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). It supports the following two index creation modes: -- Creating all indexes specified in the workloads `indices` section +- Creating all indexes specified in the workload's `indices` section - Creating one specific index defined within the operation itself ### Usage @@ -103,6 +103,7 @@ The following example creates all indexes defined in the `indices` section of th } } ``` +{% include copy.html %} The following example creates a new index with all index settings specified in the operation body: @@ -127,6 +128,7 @@ The following example creates a new index with all index settings specified in t } } ``` +{% include copy.html %} ### Configuration options @@ -135,29 +137,29 @@ Use the following options when creating all indexes from the `indices` section o Parameter | Required | Type | Description :--- | :--- | :--- | :--- `settings` | No | Array | Specifies additional index settings to be merged with the index settings specified in the `indices` section of the workload. -`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. +`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. Use the following options when creating a single index in the operation. Parameter | Required | Type | Description :--- | :--- | :--- | :--- `index` | Yes | String | The index name. -`body` | No | Request body | The request body for the Create Index API. For more information, see [Create Index API](/api-reference/index-apis/create-index/). -`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. +`body` | No | Request body | The request body for the Create Index API. For more information, see [Create Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). +`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. ### Metadata The `create-index` operation returns the following metadata: -`weight`: The number of indexes created by the operation. -`unit`: Always `ops`, indicating the number of operations inside the workload. -`success`: A Boolean indicating whether the operation has succeeded. +- `weight`: The number of indexes created by the operation. +- `unit`: Always `ops`, indicating the number of operations inside the workload. +- `success`: A Boolean indicating whether the operation has succeeded. ## delete-index -The `delete-index` operation runs the [Delete Index API](api-reference/index-apis/delete-index/). Like with the [`create-index`](#create-index) operation, you can delete all indexes found in the `indices` section of the workload or delete one or more indexes based on the string passed in the `index` setting. +The `delete-index` operation runs the [Delete Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-index/). As with the [`create-index`](#create-index) operation, you can delete all indexes found in the `indices` section of the workload or delete one or more indexes based on the string passed in the `index` setting. ### Usage @@ -169,6 +171,7 @@ The following example deletes all indexes found in the `indices` section of the "operation-type": "delete-index" } ``` +{% include copy.html %} The following example deletes all `logs_*` indexes: @@ -185,6 +188,7 @@ The following example deletes all `logs_*` indexes: } } ``` +{% include copy.html %} ### Configuration options @@ -193,29 +197,29 @@ Use the following options when deleting all indexes indicated in the `indices` s Parameter | Required | Type | Description :--- | :--- | :--- | :--- `only-if-exists` | No | Boolean | Decides whether an existing index should be deleted. Default is `true`. -`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. +`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. Use the following options if you want to delete one or more indexes based on the pattern indicated in the `index` option. Parameter | Required | Type | Description :--- | :--- | :--- | :--- -`index` | Yes | String | The index or indexes that you want to delete. +`index` | Yes | String | The index or indexes that you want to delete. `only-if-exists` | No | Boolean | Decides whether an index should be deleted when the index exists. Default is `true`. -`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. +`request-params` | No | List of settings | Contains any request parameters allowed by the Create Index API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. ### Metadata The `delete-index` operation returns the following metadata: -`weight`: The number of indexes created by the operation. -`unit`: Always `ops`, for the number of operations inside the workload. -`success`: A Boolean indicating whether the operation has succeeded. +- `weight`: The number of indexes created by the operation. +- `unit`: Always `ops`, for the number of operations inside the workload. +- `success`: A Boolean indicating whether the operation has succeeded. ## cluster-health -The `cluster-health` operation runs the [Cluster Health API](api-reference/cluster-api/cluster-health/), which checks the cluster health status and returns the expected status according to the parameters set for `request-params`. If an unexpected cluster health status is returned, the operation reports a failure. You can use the `--on-error` option in the OpenSearch Benchmark `execute-test` command to control how OpenSearch Benchmark behaves when the health check fails. +The `cluster-health` operation runs the [Cluster Health API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/), which checks the cluster health status and returns the expected status according to the parameters set for `request-params`. If an unexpected cluster health status is returned, then the operation reports a failure. You can use the `--on-error` option in the OpenSearch Benchmark `run` command to control how OpenSearch Benchmark behaves when the health check fails. ### Usage @@ -235,6 +239,7 @@ The following example creates a `cluster-health` operation that checks for a `gr } ``` +{% include copy.html %} ### Configuration options @@ -242,16 +247,16 @@ Use the following options with the `cluster-health` operation. Parameter | Required | Type | Description :--- | :--- | :--- | :--- -`index` | Yes | String | The index or indexes you want to assess. -`request-params` | No | List of settings | Contains any request parameters allowed by the Cluster Health API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. +`index` | Yes | String | The index or indexes you want to assess. +`request-params` | No | List of settings | Contains any request parameters allowed by the Cluster Health API. OpenSearch Benchmark does not attempt to serialize the parameters and passes them in their current state. ### Metadata The `cluster-health` operation returns the following metadata: -`weight`: The number of indexes the `cluster-health` operation assesses. Alwasys `1`, since the operation runs once per index. -`unit`: Always `ops`, for the number of operations inside the workload. -`success`: A Boolean indicating whether the operation has succeeded. +- `weight`: The number of indexes the `cluster-health` operation assesses. Always `1`, since the operation runs once per index. +- `unit`: Always `ops`, for the number of operations inside the workload. +- `success`: A Boolean indicating whether the operation has succeeded. - `cluster-status`: The current cluster status. - `relocating-shards`: The number of shards currently relocating to a different node. @@ -272,6 +277,7 @@ The following example refreshes all `logs-*` indexes: "index": "logs-*" } ``` +{% include copy.html %} ### Configuration options @@ -285,7 +291,7 @@ Parameter | Required | Type | Description ## search -The `search` operation runs the [Search API](/api-reference/search/), which you can use to run queries in OpenSearch Benchmark indexes. +The `search` operation runs the [Search API]({{site.url}}{{site.baseurl}}/api-reference/search/), which you can use to run queries in OpenSearch Benchmark indexes. ### Usage @@ -306,6 +312,7 @@ The following example runs a `match_all` query inside the `search` operation: } } ``` +{% include copy.html %} ### Configuration options @@ -331,8 +338,924 @@ The following metadata is always returned: If `detailed-results` is set to `true`, the following metadata is also returned: - `hits`: The total number of hits for the query. -- `hits_relation`: Whether the number of hits is accurate (eq) or a lower bound of the actual hit count (gte). +- `hits_relation`: Whether the number of hits is accurate (`eq`) or a lower bound of the actual hit count (`gte`). - `timed_out`: Whether the query has timed out. For scroll queries, this flag is `true` if the flag was `true` for any of the queries issued. - `took`: The value of the `took` property in the query response. For scroll queries, the value is the sum of all `took` values in all query responses. + +## paginated-search + +The `paginated-search` operation runs a sequence of paginated search requests using the [`search_after`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-search_after-parameter) parameter. It accepts the same options as `search` plus `pages`, which controls how many pages to retrieve. + +### Configuration options + +In addition to the options listed under [`search`](#search): + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`pages` | Yes | Integer | The maximum number of pages to retrieve. If the query returns fewer matching results than the requested number of pages, the operation terminates early. + +### Metadata + +In addition to the metadata returned by `search`: + +- `pages`: The total number of pages retrieved. + + +## scroll-search + + +The `scroll-search` operation runs a [scroll search]({{site.url}}{{site.baseurl}}/api-reference/scroll/). It accepts the same options as `search` plus `pages`, which controls how many scroll pages to fetch. + +### Configuration options + +In addition to the options listed under [`search`](#search): + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`pages` | Yes | Integer | The maximum number of scroll pages to retrieve. If the scroll exhausts before this number is reached, the operation terminates early. + +### Metadata + +In addition to the metadata returned by `search`: + +- `pages`: The total number of scroll pages retrieved. + + +## force-merge + + +The `force-merge` operation runs the [Force Merge API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/force-merge/). + +### Usage + +```yml +{ + "name": "force-merge", + "operation-type": "force-merge", + "index": "_all", + "request-params": { + "max_num_segments": 1 + } +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`index` | No | String | The index or indexes to force merge. If omitted, the call falls through to the underlying client's default behavior, which targets all indexes. +`max-num-segments` | No | Integer | The target number of segments per shard. Passed as `max_num_segments` to the Force Merge API. +`mode` | No | String | Set to `polling` to issue the force merge asynchronously and poll the Tasks API until it completes. When omitted, the call waits synchronously and may time out on large indexes. +`poll-period` | Conditional | Number | Required when `mode` is `polling`: the time in seconds between status polls. The operation raises an error if `mode: polling` is set without this value. +`request-params` | No | Object | Additional request parameters passed to the Force Merge API. + +This is an administrative operation. Metrics are not reported by default. Reporting can be forced by setting `include-in-reporting` to `true`. + + +## index-stats + + +The `index-stats` operation runs the [Index Stats API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/stats/). + +### Usage + +```yml +{ + "name": "index-stats", + "operation-type": "index-stats", + "index": "_all", + "condition": { + "path": "_all.total.merges.current", + "expected-value": 0 + }, + "retry-until-success": true +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`index` | No | String | The index or indexes to retrieve statistics for. Default is `_all`. +`condition` | No | Object | A condition to check in the response. Contains `path` (dot-notation path in the response) and `expected-value`. +`request-params` | No | Object | Request parameters passed to the Stats API. + + +## node-stats + + +The `node-stats` operation runs the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/). + +### Usage + +```yml +{ + "name": "node-stats", + "operation-type": "node-stats" +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`request-timeout` | No | Number | Client-side timeout (in seconds) for the Nodes Stats request. + + +## vector-search + + +The `vector-search` operation runs k-NN vector search queries and optionally computes recall metrics by comparing results against ground truth neighbors. + +### Usage + +```yml +{ + "name": "knn-search", + "operation-type": "vector-search", + "index": "vectors", + "k": 100, + "body": { + "query": { + "knn": { + "embedding": { + "vector": [0.1, 0.2, 0.3], + "k": 100 + } + } + } + } +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`index` | Yes | String | The target index. Required: omitting it causes the underlying `search` runner to error out. +`body` | Yes | Object | The search request body containing the k-NN query. +`k` | No | Integer | The number of nearest neighbors to retrieve. Used for recall calculation. +`detailed-results` | No | Boolean | Whether to record detailed metadata. +`calculate-recall` | No | Boolean | Whether to compute recall@k and recall@1 against ground truth neighbors. Default is `true`. +`neighbors` | No | Array | The ground truth neighbor IDs for recall calculation. Typically provided by the workload at runtime. + +### Metadata + +- `weight`: Always `1`. +- `unit`: Always `ops`. +- `success`: Whether the search succeeded. +- `recall@k`: Recall at k (if ground truth neighbors are provided). +- `recall@1`: Recall at 1 (if ground truth neighbors are provided). + + +## bulk-vector-data-set + + +The `bulk-vector-data-set` operation bulk-indexes vector data from HDF5 or BigANN dataset files. Supports individual document retry on partial failures. + +### Usage + +```yml +{ + "name": "bulk-vectors", + "operation-type": "bulk-vector-data-set", + "bulk-size": 500, + "index": "vectors" +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`bulk-size` | No | Integer | Number of documents per bulk request. +`index` | No | String | The target index. +`retries` | No | Integer | Number of retry attempts after the initial request fails. Default is `0` (no retries). Each failed document is resubmitted on retry; connection timeouts also trigger a retry. +`retry-wait-period` | No | Number | Initial wait period between retries in seconds. Default is `0.5`. +`retry-max-wait-period` | No | Number | Maximum wait period between retries in seconds (exponential backoff is capped at this value). Default is `60`. +`detailed-results` | No | Boolean | Records detailed per-document success/failure metadata. Default is `true`. +`action-metadata-present` | No | Boolean | Whether the bulk body includes action metadata lines. Default is `true`. +`unit` | No | String | Unit reported for `weight`. Default is `docs`. + + +## put-pipeline + + +The `put-pipeline` operation creates or updates an [ingest pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/). + +### Usage + +```yml +{ + "name": "define-pipeline", + "operation-type": "put-pipeline", + "id": "my-pipeline", + "body": { + "description": "My ingest pipeline", + "processors": [ + { + "set": { + "field": "ingest_time", + "value": {% raw %}"{{_ingest.timestamp}}"{% endraw %} + } + } + ] + } +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`id` | Yes | String | The pipeline ID. +`body` | Yes | Object | The pipeline definition. + +This is an administrative operation. Metrics are not reported by default. + + +## delete-pipeline + + +The `delete-pipeline` operation deletes an ingest pipeline. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`id` | Yes | String | The pipeline ID to delete. + +This is an administrative operation. Metrics are not reported by default. + + +## create-search-pipeline + + +The `create-search-pipeline` operation creates a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`id` | Yes | String | The search pipeline ID. +`body` | Yes | Object | The search pipeline definition. + +This is an administrative operation. Metrics are not reported by default. + + +## update-concurrent-segment-search-settings + + +The `update-concurrent-segment-search-settings` operation toggles the [concurrent segment search]({{site.url}}{{site.baseurl}}/search-plugins/concurrent-segment-search/) cluster setting and, optionally, the maximum slice count. It updates `search.concurrent_segment_search.enabled` (and `search.concurrent.max_slice_count` when provided) as persistent cluster settings. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`enable` | No | Boolean | Whether concurrent segment search is enabled. Default is `false`. +`max_slice_count` | No | Integer | Maximum number of slices per shard. If omitted, the setting is left unchanged. + + +## put-settings + + +The `put-settings` operation updates [cluster settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/). + +### Usage + +```yml +{ + "name": "increase-watermarks", + "operation-type": "put-settings", + "body": { + "transient": { + "cluster.routing.allocation.disk.watermark.low": "95%" + } + } +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`body` | Yes | Object | The cluster settings to apply. + +This is an administrative operation. Metrics are not reported by default. + + +## create-data-stream + + +The `create-data-stream` operation creates one or more [data streams]({{site.url}}{{site.baseurl}}/opensearch/data-streams/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`data-streams` | Yes | List | A list of data stream names to create. +`request-params` | Yes | Object | Request parameters forwarded to the Create Data Stream API. Pass an empty object (`{}`) if none are needed. + + +## delete-data-stream + + +The `delete-data-stream` operation deletes one or more data streams. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`data-streams` | Yes | List | A list of data stream names to delete. +`only-if-exists` | Yes | Boolean | If `true`, only delete data streams that exist; if `false`, attempt to delete each one and ignore HTTP 404 responses. +`request-params` | Yes | Object | Request parameters forwarded to the Delete Data Stream API. Pass an empty object (`{}`) if none are needed. + + +## create-composable-template + + +The `create-composable-template` operation creates one or more [composable index templates]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`templates` | Yes | List | A list of `[template-name, body]` pairs to create. +`request-params` | Yes | Object | Request parameters forwarded to the API. Pass an empty object (`{}`) if none are needed. + + +## delete-composable-template + + +The `delete-composable-template` operation deletes one or more composable index templates and, optionally, the indexes they match. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`templates` | Yes | List | A list of `[template-name, delete-matching-indices, index-pattern]` triples. When `delete-matching-indices` is `true` and `index-pattern` is non-empty, indexes matching the pattern are also deleted. +`only-if-exists` | Yes | Boolean | If `true`, only delete templates that exist; if `false`, attempt to delete each one and ignore HTTP 404 responses. +`request-params` | Yes | Object | Request parameters forwarded to the API. Pass an empty object (`{}`) if none are needed. + + +## create-component-template + + +The `create-component-template` operation creates one or more [component templates]({{site.url}}{{site.baseurl}}/api-reference/index-apis/component-template/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`templates` | Yes | List | A list of `[template-name, body]` pairs to create. +`request-params` | Yes | Object | Request parameters forwarded to the API. Pass an empty object (`{}`) if none are needed. + + +## delete-component-template + + +The `delete-component-template` operation deletes one or more component templates. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`templates` | Yes | List | A list of component template names to delete. +`only-if-exists` | Yes | Boolean | If `true`, only delete templates that exist; if `false`, attempt to delete each one and ignore HTTP 404 responses. +`request-params` | Yes | Object | Request parameters forwarded to the API. Pass an empty object (`{}`) if none are needed. + + +## create-index-template + + +The `create-index-template` operation creates one or more legacy index templates. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`templates` | Yes | List | A list of `[template-name, body]` pairs to create. +`request-params` | No | Object | Additional request parameters. + + +## delete-index-template + + +The `delete-index-template` operation deletes one or more legacy index templates and, optionally, the indexes they match. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`templates` | Yes | List | A list of `[template-name, delete-matching-indices, index-pattern]` triples. +`only-if-exists` | No | Boolean | If `true`, only delete templates that exist. Default is `false`. +`request-params` | No | Object | Additional request parameters. + + +## shrink-index + + +The `shrink-index` operation uses the [Shrink Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shrink-index/) to reduce the number of primary shards in an index. + +### Usage + +```yml +{ + "name": "shrink-index", + "operation-type": "shrink-index", + "source-index": "my-index", + "target-index": "my-index-shrunk", + "target-body": { + "settings": { + "index.number_of_shards": 1, + "index.codec": "best_compression" + } + } +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`source-index` | Yes | String | The source index (or wildcard pattern) to shrink. +`target-index` | Yes | String | The name for the shrunk index. When `source-index` matches multiple indexes, the matched suffix is appended to this name. +`target-body` | Yes | Object | Settings and mappings for the target index. +`shrink-node` | No | String | The node to allocate the source shards to before shrinking. If omitted, a random data node is chosen. + + +## create-snapshot-repository + + +The `create-snapshot-repository` operation creates a [snapshot repository]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`repository` | Yes | String | The repository name. +`body` | Yes | Object | The repository definition (type, settings). +`request-params` | No | Object | Additional request parameters. + + +## delete-snapshot-repository + + +The `delete-snapshot-repository` operation deletes a snapshot repository. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`repository` | Yes | String | The repository name to delete. + + +## create-snapshot + + +The `create-snapshot` operation creates a [snapshot]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`repository` | Yes | String | The repository name. +`snapshot` | Yes | String | The snapshot name. +`body` | Yes | Object | The snapshot definition. +`wait-for-completion` | No | Boolean | Whether to wait for the snapshot to complete before returning. Default is `false`. To benchmark snapshot duration accurately, leave this `false` and follow up with `wait-for-snapshot-create`. +`request-params` | No | Object | Additional request parameters. + + +## wait-for-snapshot-create + + +The `wait-for-snapshot-create` operation polls snapshot status until the snapshot reaches `SUCCESS`. If the snapshot ends in `FAILED`, the operation raises an assertion error. The reported metrics include snapshot size in bytes, throughput, and duration. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`repository` | Yes | String | The repository name. +`snapshot` | Yes | String | The snapshot name. +`completion-recheck-wait-period` | No | Number | Seconds between status polls. Default is `1`. + + +## restore-snapshot + + +The `restore-snapshot` operation restores a snapshot. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`repository` | Yes | String | The repository name. +`snapshot` | Yes | String | The snapshot name. +`body` | No | Object | The restore request body. +`wait-for-completion` | No | Boolean | Whether to wait for the restore to complete before returning. Default is `false`. Pair with `wait-for-recovery` to benchmark restore duration. +`request-params` | No | Object | Additional request parameters. + + +## wait-for-recovery + + +The `wait-for-recovery` operation waits until index recovery completes by polling the [Index Recovery API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/recover/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`index` | Yes | String | The index to monitor for recovery. +`completion-recheck-wait-period` | No | Number | Seconds between recovery polls. Default is `1`. + + +## submit-async-search + + +The `submit-async-search` operation submits an [asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/) request and stores the returned asynchronous search ID under the operation `name` so later operations in the same composite can fetch or delete it. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`name` | Yes | String | The operation name. Other operations refer to this name to look up the resulting asynchronous search ID. +`body` | Yes | Object | The search request body. +`index` | No | String | The target index. +`request-params` | No | Object | Additional request parameters forwarded to the Asynchronous Search API. + + +## get-async-search + + +The `get-async-search` operation retrieves results from one or more previously submitted asynchronous searches. The operation succeeds only when every referenced search has completed (`is_running: false`). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`retrieve-results-for` | Yes | String or List | The name of the `submit-async-search` operation (or a list of names) whose results should be retrieved. +`request-params` | No | Object | Additional request parameters forwarded to the Asynchronous Search Get API. + + +## delete-async-search + + +The `delete-async-search` operation deletes one or more asynchronous search results. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`delete-results-for` | Yes | String or List | The name of the `submit-async-search` operation (or a list of names) whose results should be deleted. + + +## create-point-in-time + + +The `create-point-in-time` operation creates a [Point in Time (PIT)]({{site.url}}{{site.baseurl}}/search-plugins/point-in-time/) for an index. The resulting PIT ID is stored under the operation `name`, so later operations in the same composite can reference it. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`name` | Yes | String | The operation name. Other operations refer to this name to reuse the resulting PIT ID. +`index` | Yes | String | The target index. +`keep-alive` | No | String | How long to keep the PIT alive (for example, `5m`). Default is `1m`. +`request-params` | No | Object | Additional request parameters forwarded to the Create PIT API. + + +## delete-point-in-time + + +The `delete-point-in-time` operation deletes one or more PITs. If `with-point-in-time-from` is set, only the PIT created by the named operation is deleted; otherwise, every PIT on the cluster is deleted. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`with-point-in-time-from` | No | String | The name of the `create-point-in-time` operation whose PIT to delete. If omitted, all PITs are deleted. +`request-params` | No | Object | Additional request parameters forwarded to the Delete PIT API. + + +## list-all-point-in-time + + +The `list-all-point-in-time` operation lists all active PITs on the cluster. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`request-params` | No | Object | Additional request parameters forwarded to the List PIT API. + + +## create-transform + + +The `create-transform` operation creates an [index transform]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`transform-id` | Yes | String | The transform ID. +`body` | Yes | Object | The transform definition. + + +## start-transform + + +The `start-transform` operation starts a previously created transform. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`transform-id` | Yes | String | The transform ID to start. +`timeout` | No | Number | Optional client-side timeout for the start request. + + +## wait-for-transform + + +The `wait-for-transform` operation polls the transform status until the transform reaches its next checkpoint (or stops, depending on options). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`transform-id` | Yes | String | The transform ID to monitor. +`force` | No | Boolean | Forcefully stop the transform when polling completes. Default is `false`. +`wait-for-checkpoint` | No | Boolean | Wait until all data has been processed through the next checkpoint. Default is `true`. +`wait-for-completion` | No | Boolean | Block until the transform has fully stopped. Default is `true`. +`transform-timeout` | No | Number | Overall transform runtime timeout in seconds. Default is `3600`. +`poll-interval` | No | Number | How often (in seconds) transform stats are polled. Default is `0.5`. + + +## delete-transform + + +The `delete-transform` operation deletes a previously created transform. Missing transforms (HTTP 404) are ignored so this operation is safe to use as a cleanup step. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`transform-id` | Yes | String | The transform ID to delete. +`force` | No | Boolean | If `true`, deletes the transform even if it is currently running. Default is `false`. + + +## train-knn-model + + +The `train-knn-model` operation trains a k-NN model using the [Train Model API]({{site.url}}{{site.baseurl}}/vector-search/api/knn/#train-a-model) and polls until training completes. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`body` | Yes | Object | The training request body. See the [Train Model API]({{site.url}}{{site.baseurl}}/vector-search/api/knn/#train-a-model) for body parameters. +`model_id` | Yes | String | The model ID to train. +`retries` | No | Integer | Maximum number of poll retries before giving up. Default is `1000`. +`poll_period` | No | Number | Seconds between status polls. Default is `0.5`. + + +## delete-knn-model + + +The `delete-knn-model` operation deletes a trained k-NN model. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`model_id` | Yes | String | The model ID to delete. +`ignore-if-model-does-not-exist` | No | Boolean | If `true`, treat a missing model (HTTP 404) as success. Default is `false`. + + +## register-ml-model + + +The `register-ml-model` operation registers a machine learning model using the [ML Commons API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/). The runner first searches for a model with a matching name; if one already exists, the existing model ID is reused. Otherwise it submits a new registration request and polls until it completes. The resulting model ID is written to `model_id.json` in the working directory so later operations can consume it. + +You can supply the request body in one of two ways: by setting `model-config-file` to a path on disk, or by setting `model-name`, `model-version`, and `model-format` and letting OpenSearch Benchmark assemble the body for you. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`model-config-file` | No | String | Path to a JSON file containing the full registration body. If set, the other body fields are ignored. +`model-name` | No | String | The model name. Used to assemble the body when `model-config-file` is not set. +`model-version` | No | String | The model version. +`model-format` | No | String | The model format (for example, `TORCH_SCRIPT`). +`timeout` | No | Number | Maximum seconds to wait for the registration task to complete. Default is `120`. + + +## deploy-ml-model + + +The `deploy-ml-model` operation deploys (loads) a previously registered ML model. The model ID is read from `model_id.json` in the working directory (typically written by an earlier `register-ml-model` operation), so this operation takes no required parameters. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`timeout` | No | Number | Maximum seconds to wait for the deploy task to complete. Default is `120`. + + +## create-ml-connector + + +The `create-ml-connector` operation creates an [ML connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/) for remote model integration. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`body` | Yes | Object | The connector definition. + + +## delete-ml-connector + + +The `delete-ml-connector` operation looks up an ML connector by name and deletes it. If no connector matches the supplied name, the operation is a no-op. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`connector_name` | Yes | String | The connector name to look up and delete. + + +## register-remote-ml-model + + +The `register-remote-ml-model` operation registers a remote ML model backed by an [ML connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). It polls the registration task until it completes, then writes the resulting model ID to `model_id.json` in the working directory so later operations can consume it. + +If `connector_id` is not set in the request body, OpenSearch Benchmark reads it from `connector_id.json` in the working directory (typically written by an earlier `create-ml-connector` operation). + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`body` | Yes | Object | The model registration request body. If `connector_id` is omitted, it is loaded from `connector_id.json`. + + +## delete-ml-model + + +The `delete-ml-model` operation looks up models by name, undeploys any that are currently deployed, and then deletes them. Multiple models with the same name (for example, across versions) are all deleted. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`model-name` | Yes | String | The model name to look up and delete. +`number-of-hits-to-return` | No | Integer | Maximum number of matching models to fetch from the search query. Default is `1000`. +`undeploy-timeout` | No | Number | Seconds to wait for each model to fully undeploy before deletion. Default is `10`. + + +## raw-request + + +The `raw-request` operation sends an arbitrary HTTP request to OpenSearch. Use this for operations not covered by a dedicated operation type. + +### Usage + +```yml +{ + "name": "check-shard-count", + "operation-type": "raw-request", + "method": "GET", + "path": "/_cat/shards?v", + "body": {} +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`method` | No | String | HTTP method (`GET`, `POST`, `PUT`, `DELETE`). Default is `GET`. +`path` | Yes | String | The URL path. Must begin with `/`. +`body` | No | Object | The request body. +`request-params` | No | Object | Query string parameters. +`headers` | No | Object | HTTP headers to include. +`ignore` | No | List | HTTP status codes to ignore (for example, `[404]`). + + +## sleep + + +The `sleep` operation pauses execution for a specified duration. + +### Usage + +```yml +{ + "name": "wait-before-search", + "operation-type": "sleep", + "duration": 30 +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`duration` | Yes | Number | Sleep duration in seconds. + + +## composite + + +The `composite` operation executes a structured group of inner operations as a single measured unit, optionally with parallel sub-streams. This is useful when several requests need to share state (for example, creating a PIT, searching with it, and deleting it) or when you want to measure end-to-end timings across a small workflow. + +Only a subset of operation types can appear inside `composite`: `create-point-in-time`, `delete-point-in-time`, `list-all-point-in-time`, `search`, `paginated-search`, `raw-request`, `sleep`, `submit-async-search`, `get-async-search`, and `delete-async-search`. Nested `stream` blocks run in parallel. + +### Usage + +```yml +{ + "name": "pit-search-workflow", + "operation-type": "composite", + "requests": [ + { "operation-type": "create-point-in-time", "name": "pit", "index": "my-index" }, + { "operation-type": "search", "body": { "query": { "match_all": {} } } }, + { "operation-type": "delete-point-in-time", "with-point-in-time-from": "pit" } + ] +} +``` +{% include copy.html %} + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`requests` | Yes | List | The list of inner operations or `stream` blocks to execute. +`max-connections` | No | Integer | Upper bound on the number of concurrent in-flight requests across the composite. Defaults to unbounded. + + +## produce-stream-message + + +The `produce-stream-message` operation publishes messages to a configured `message-producer` (for example, a Kafka producer) for streaming ingestion benchmarks. The `body` is split on newlines, and each non-metadata line is sent as an individual message. Producers are configured at the workload or cluster level---the runner itself takes only the producer reference and the message payload. + +### Configuration options + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`message-producer` | Yes | Producer | The producer instance (resolved by the workload at runtime) used to send messages. +`body` | Yes | String or Bytes | The newline-delimited message payload. Index-metadata lines (`{"index": {"_index": ...}}`) are skipped. + + +## proto-bulk + + +The `proto-bulk` operation sends bulk index requests using the gRPC transport instead of HTTP REST. Requires gRPC to be enabled on the target cluster. + +### Configuration options + +Same as `bulk`, but uses gRPC serialization (Protocol Buffers) instead of JSON over HTTP. Use `--grpc-target-hosts` to specify the gRPC endpoint. + + +## proto-search + + +The `proto-search` operation sends search requests using gRPC transport. + +### Configuration options + +Same as `search`, but uses gRPC. Use `--grpc-target-hosts` to specify the gRPC endpoint. + + +## proto-vector-search + + +The `proto-vector-search` operation sends vector search requests using gRPC transport. + +### Configuration options + +Same as `vector-search`, but uses gRPC. Use `--grpc-target-hosts` to specify the gRPC endpoint. + + +## proto-bulk-vector-data-set + + +The `proto-bulk-vector-data-set` operation bulk-indexes vector data sets using the gRPC transport. It is the gRPC counterpart to `bulk-vector-data-set`. + +### Configuration options + +Same as `bulk-vector-data-set`, but uses gRPC serialization (Protocol Buffers) instead of JSON over HTTP. Use `--grpc-target-hosts` to specify the gRPC endpoint. diff --git a/_benchmark/reference/workloads/parameters.md b/_benchmark/reference/workloads/parameters.md new file mode 100644 index 00000000..6a21754f --- /dev/null +++ b/_benchmark/reference/workloads/parameters.md @@ -0,0 +1,394 @@ +--- +layout: default +title: Workload parameters +parent: Anatomy of a workload +nav_order: 60 +--- + +# Workload parameters + +Workload parameters let you customize workload behavior without editing the workload files directly. You can control settings such as bulk size, number of shards, index name, and search configuration by passing parameters at runtime. + +OpenSearch Benchmark workloads use [Jinja2](https://jinja.palletsprojects.com/) templates. When you pass parameters using the `--workload-params` flag, OpenSearch Benchmark injects them into the workload JSON files before execution. + +For example, a workload's `index.json` might contain the following settings: + +```json +{ + "settings": { + "index.number_of_shards": {% raw %}{{ number_of_shards | default(1) }}{% endraw %}, + "index.number_of_replicas": {% raw %}{{ number_of_replicas | default(0) }}{% endraw %} + } +} +``` + +When you run a benchmark with `--workload-params='{"number_of_shards": 3}'`, OpenSearch Benchmark replaces `{% raw %}{{ number_of_shards | default(1) }}{% endraw %}` with `3`. Parameters you don't override use their default values. + +## Passing parameters + +You can pass parameters in the following ways. + +### JSON file (recommended for many parameters) + +Create a JSON file containing your parameters: + +```json +{ + "number_of_shards": 3, + "number_of_replicas": 1, + "bulk_size": 5000, + "target_index_name": "my_index" +} +``` +{% include copy.html %} + +Then reference it as follows: + +```bash +opensearch-benchmark run --workload=geonames --workload-params=my-params.json +``` +{% include copy.html %} + +### Inline JSON + +Pass parameters directly on the command line: + +```bash +opensearch-benchmark run --workload=geonames --workload-params='{"number_of_shards": 3, "bulk_size": 5000}' +``` +{% include copy.html %} + +### Comma-separated key-value pairs + +Use the following format to pass key-value pairs: + +```bash +opensearch-benchmark run --workload=geonames --workload-params="number_of_shards:3,bulk_size:5000" +``` +{% include copy.html %} + +The comma-separated format only supports string values. Use JSON file or inline JSON for numbers, Boolean values, or nested objects. +{: .note} + +## Parameter precedence + +When the same parameter is defined in multiple sources, OpenSearch Benchmark applies them in the following order (highest priority first): + +1. **`--workload-params`** (CLI flag): Overrides all other values. +1. **Workload template defaults**: Default values specified in `{% raw %}{{ var | default(value) }}{% endraw %}` expressions in the workload JSON files (for example, `{% raw %}{{ number_of_shards | default(1) }}{% endraw %}`). +1. **Undefined**: If no default is specified and the parameter is not provided, OpenSearch Benchmark raises a template rendering error. + +## Template syntax + +This section describes the most common template patterns used in workload files. + +### Variable with a default value + +Use the `default` filter to specify a fallback value when a parameter is not provided. For example, if `bulk_size` is not provided in `--workload-params`, the expression evaluates to `5000`: + +```json +{% raw %}{{ bulk_size | default(5000) }}{% endraw %} +``` +{% include copy.html %} + +### Boolean values + +Use the `tojson` filter for Boolean values to ensure correct JSON output. For example, the following expression evaluates to `false` (without quotation marks), not `"false"`: + +```json +{% raw %}{{ query_cache_enabled | default(false) | tojson }}{% endraw %} +``` +{% include copy.html %} + +### String values + +Wrap string variables in quotation marks: + +```json +{% raw %}"{{ conflicts | default('random') }}"{% endraw %} +``` +{% include copy.html %} + +### Conditional sections + +Use `{% raw %}{% if %}{% endraw %}` blocks to include or exclude sections based on whether a parameter is defined or on the parameter value. + +#### Including a field only when defined + +The following template conditionally includes the `target-throughput` field. If `target_throughput` is not provided using `--workload-params`, the entire field is omitted from the rendered output: + +```json +{% raw %}{% if target_throughput is defined %} +"target-throughput": {{ target_throughput }}, +{% endif %}{% endraw %} +``` +{% include copy.html %} + + +#### If/else for alternative values + + +Use `{% raw %}{% else %}{% endraw %}` to provide a fallback. For example, if `use_zstd` is set to `true` in `--workload-params`, the rendered output sets the `source-file` parameter to `documents.json.zst`. Otherwise, it sets the `source-file` to `documents.json.bz2`: + +```json +{% raw %}{% if use_zstd %} +"source-file": "documents.json.zst", +{% else %} +"source-file": "documents.json.bz2", +{% endif %}{% endraw %} +``` +{% include copy.html %} + +#### Conditionally adding index fields + +This pattern is commonly used to define optional fields in `vectorsearch` workload templates. The `{% raw %}{%- endif %}{% endraw %}` (with the dash) trims trailing white space and newline characters, preventing empty lines from appearing and avoiding invalid JSON formatting (such as trailing commas or misaligned structure): + +```json +"properties": { + {% raw %}{% if id_field_name is defined and id_field_name != "_id" %} + "{{ id_field_name }}": { + "type": "keyword" + }, + {%- endif %}{% endraw %} + "embedding": { + "type": "knn_vector", + "dimension": {% raw %}{{ target_index_dimension }}{% endraw %} + } +} +``` +{% include copy.html %} + +#### Version-based conditionals + +Some workloads adapt their behavior based on `distribution_version`, which OpenSearch Benchmark sets automatically according to the target cluster. This pattern allows a single workload to support multiple OpenSearch versions by conditionally including version-specific operations or settings: + +```json +{% raw %}{% if distribution_version is not defined %} + {% set distribution_version = "2.11.0" %} +{% endif %} + +{% if distribution_version.split('.') | map('int') | list >= "2.19.1".split('.') | map('int') | list %} + {# Include features available in 2.19.1+ #} +{% endif %}{% endraw %} +``` +{% include copy.html %} + +#### For loops + +Use `{% raw %}{% for %}{% endraw %}` loops to generate repeated structures: + +```json +{% raw %}{% for i in range(1, 101) %} +{ + "name": "query-{{ i }}", + "operation-type": "search", + "body": { ... } +}, +{% endfor %}{% endraw %} +``` +{% include copy.html %} + +### Integer conversion + +Use the `int` filter when a parameter must be an integer: + +```json +{% raw %}{{ target_index_dimension | default(768) | int }}{% endraw %} +``` +{% include copy.html %} + +### Including external files + +Workloads are typically organized into multiple files for readability. The `{% raw %}{{ benchmark.collect }}{% endraw %}` helper composes a single workload definition from multiple JSON files at render time. + +#### Importing the helper + +Every `workload.json` that uses `benchmark.collect` must import it at the top of the file: + +```json +{% raw %}{% import "benchmark.helpers" as benchmark with context %}{% endraw %} +``` +{% include copy.html %} + +The `with context` clause ensures that all workload parameters are available in the included files. + +#### Collecting operations and test procedures + +A typical `workload.json` delegates its operations and test procedures to separate files: + +```json +{% raw %}{% import "benchmark.helpers" as benchmark with context %}{% endraw %} +{ + "version": 2, + "description": "My workload", + "indices": [ ... ], + "corpora": [ ... ], + "operations": [ + {% raw %}{{ benchmark.collect(parts="operations/*.json") }}{% endraw %} + ], + "test_procedures": [ + {% raw %}{{ benchmark.collect(parts="test_procedures/*.json") }}{% endraw %} + ] +} +``` +{% include copy.html %} + +The `parts` argument accepts glob patterns. The pattern `operations/*.json` matches all JSON files in the `operations/` directory and includes their contents, separated by commas. This keeps the main `workload.json` concise while the operation and test procedure definitions are defined in separate files. + +#### Composing schedules from shared parts + +Test procedures can reuse common schedule fragments. For example, the `vectorsearch` workload has shared schedules under `test_procedures/common/`: + +``` +test_procedures/ + common/ + index-only-schedule.json + search-only-schedule.json + force-merge-schedule.json + vespa-search-only-schedule.json + default.json +``` +{% include copy.html %} + +A test procedure in `default.json` composes its schedule from these parts: + +```json +{ + "name": "no-train-test", + "default": true, + "schedule": [ + {% raw %}{{ benchmark.collect(parts="common/index-only-schedule.json") }}{% endraw %}, + {% raw %}{{ benchmark.collect(parts="common/force-merge-schedule.json") }}{% endraw %}, + {% raw %}{{ benchmark.collect(parts="common/search-only-schedule.json") }}{% endraw %} + ] +} +``` +{% include copy.html %} + +Each collected file contains one or more schedule entries. Parameters such as `{% raw %}{{ target_index_name }}{% endraw %}` in those files are resolved from the same `--workload-params` passed on the command line because the `with context` import propagates all parameters to the included files. + +#### Index body files + +The `body` field in an index definition references a separate JSON file for mappings and settings: + +```json +"indices": [ + { + "name": "geonames", + "body": "index.json" + } +] +``` +{% include copy.html %} + +The `index.json` file is a Jinja2 template like any other workload file, so it can use parameters: + +```json +{ + "settings": { + "index.number_of_shards": {% raw %}{{ number_of_shards | default(1) }}{% endraw %} + }, + "mappings": { ... } +} +``` +{% include copy.html %} + +## Discovering available parameters + +To view the parameters supported by a workload, use the `info` command. This command lists the workload's test procedures along with their configurable parameters and default values: + +```bash +opensearch-benchmark info --workload=geonames +``` +{% include copy.html %} + +You can also inspect the workload source directly. Parameters appear as `{% raw %}{{ variable_name | default(value) }}{% endraw %}` in workload JSON files. The main workload files are the following: + +- `workload.json` -- The top-level workload definition. +- `index.json` -- The index settings and mappings. +- `test_procedures/default.json` -- The test procedure schedules. +- `_operations/default.json` -- The operation definitions. + +## Common parameters + +The following parameters are supported by most official workloads. + +| Parameter | Description | Default | +|-----------|-------------|-----------------| +| `number_of_shards` | The primary shard count for created indexes. | `1` | +| `number_of_replicas` | The replica count for created indexes. | `0` | +| `bulk_size` | The number of documents per bulk request. | `5000` or `10000` | +| `bulk_indexing_clients` | The number of concurrent bulk indexing clients. | `8` | +| `ingest_percentage` | The percentage of the document corpus to ingest. | `100` | +| `target_throughput` | The target number of operations per second per client. | Unthrottled | +| `search_clients` | The number of concurrent search clients. | `1` | +| `cluster_health` | The required cluster health status before proceeding. | `green` | +| `source_enabled` | Whether to store the `_source` field. | `true` | + +## Vector search workload parameters + +The `vectorsearch` workload supports additional parameters for vector search benchmarking. + +| Parameter | Description | Default | +|-----------|-------------|---------| +| `target_index_name` | The vector index name. | `target_index` | +| `target_field_name` | The vector field name.| `target_field` | +| `target_index_dimension` | The number of vector dimensions. | `768` | +| `target_index_space_type` | The distance metric. Valid values are `l2`, `innerproduct`, and `cosinesimil`. | Varies | +| `target_index_body` | The path to index settings file. | `indices/faiss-index.json` | +| `target_index_bulk_size` | The number of documents per bulk request. | `500` | +| `target_index_bulk_index_data_set_format` | The corpus format. Valid values are `hdf5` and `bigann`. | `hdf5` | +| `target_index_bulk_index_data_set_corpus` | The corpus name (for example, `cohere-1m`). | Varies | +| `target_index_bulk_indexing_clients` | The number of concurrent indexing clients. | `10` | +| `target_index_max_num_segments` | The number of segments after force merge. | `1` | +| `hnsw_ef_construction` | The HNSW graph build-time exploration factor. | `256` | +| `hnsw_ef_search` | The HNSW search-time exploration factor. | `256` | +| `query_k` | The number of nearest neighbors to retrieve. | `100` | +| `query_count` | The number of queries to run. Use `-1` for all queries. | `-1` | +| `query_data_set_format` | The query vector format. Valid values are `hdf5` and `bigann`. | `hdf5` | +| `query_data_set_corpus` | The query vector corpus name. | Varies | +| `search_clients` | The number of concurrent search clients. | `1` | +| `neighbors_data_set_corpus` | The ground-truth neighbors corpus used for recall evaluation.| Varies | +| `neighbors_data_set_format` | The neighbors dataset format. | `hdf5` | + +### Example vector search parameter file + +The following example shows a complete parameter file for a `vectorsearch` workload: + +```json +{ + "target_index_name": "vector_1m", + "target_field_name": "embedding", + "target_index_body": "indices/faiss-index.json", + "target_index_primary_shards": 1, + "target_index_replica_shards": 0, + "target_index_dimension": 768, + "target_index_space_type": "innerproduct", + "target_index_bulk_size": 500, + "target_index_bulk_index_data_set_format": "hdf5", + "target_index_bulk_index_data_set_corpus": "cohere-1m", + "target_index_bulk_indexing_clients": 10, + "target_index_max_num_segments": 1, + "hnsw_ef_construction": 200, + "hnsw_ef_search": 256, + "query_k": 100, + "query_data_set_format": "hdf5", + "query_data_set_corpus": "cohere-1m", + "query_count": 10000, + "search_clients": 1, + "neighbors_data_set_corpus": "cohere-1m", + "neighbors_data_set_format": "hdf5" +} +``` +{% include copy.html %} + +To use this parameter file, save it as `params.json` and run the benchmark with the `--workload-params` flag: + +```bash +opensearch-benchmark run \ + --pipeline=benchmark-only \ + --workload-path=/path/to/vectorsearch \ + --workload-params=params.json \ + --target-hosts=localhost:9200 +``` +{% include copy.html %} \ No newline at end of file diff --git a/_benchmark/reference/workloads/schedule.md b/_benchmark/reference/workloads/schedule.md new file mode 100644 index 00000000..bce96ca4 --- /dev/null +++ b/_benchmark/reference/workloads/schedule.md @@ -0,0 +1,238 @@ +--- +layout: default +title: schedule +parent: Anatomy of a workload +nav_order: 40 +--- + + +# schedule element + + +The `schedule` element contains a list of tasks that are run in a specified order during the benchmark test. Each task is an operation supported by OpenSearch Benchmark. + +You can define `schedule` in either of the following locations: + +- At the top level of `workload.json`. Use this form when the workload defines a single benchmarking scenario. OpenSearch Benchmark treats the schedule as an implicit default test procedure. +- Inside a test procedure, in the [`test_procedures`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/test-procedures/) element. Use this form when the workload defines multiple scenarios, each with its own name, description, and schedule. + +## Example + +The following `schedule` creates an index, waits for the cluster to become healthy, indexes documents in bulk, and then runs a `match_all` query: + +```json + "schedule": [ + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "iterations": 1000, + "target-throughput": 100 + } + ] +``` + +According to this `schedule`, the actions run in the following order: + +1. The `create-index` operation creates an index. The index remains empty until the `bulk` operation adds documents with benchmarked data. +2. The `cluster-health` operation assesses the cluster's health before running the workload. In this example, the workload waits until the cluster's health status is `green`. + - The `bulk` operation runs the `bulk` API to index `5000` documents simultaneously. + - Before benchmarking, the workload waits until the specified `warmup-time-period` passes. In this example, the warmup period is `120` seconds. +3. The `clients` field defines the number of clients, in this example, eight, that run the bulk indexing operation concurrently. +4. The `search` operation runs a `match_all` query to match all documents after they have been indexed by the `bulk` API using the specified clients. + - The `iterations` field defines the number of times each client runs the `search` operation. The benchmark report automatically adjusts the percentile numbers based on this number. To generate a precise percentile, the benchmark needs to run at least 1,000 iterations. + - The `target-throughput` field defines the number of requests per second performed by each client. This setting can help reduce benchmark latency. For example, a `target-throughput` of 100 requests divided by 8 clients means that each client issues 12 requests per second. For more information about how target throughput is defined in OpenSearch Benchmark, see [Target throughput]({{site.url}}{{site.baseurl}}/benchmark/target-throughput/). + +## Defining tasks + +The `schedule` element defines tasks using the methods described in this section. + +### Using the operations element + +The following example defines a `force-merge` and `match-all` query task using the `operations` element. The `force-merge` operation does not use any parameters, so only the `name` and `operation-type` are needed. The `match-all-query` parameter requires a query `body` and `operation-type`. + +Operations defined in the `operations` element can be reused in the schedule more than once: + +```yml +{ + "operations": [ + { + "name": "force-merge", + "operation-type": "force-merge" + }, + { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + } + ], + "schedule": [ + { + "operation": "force-merge", + "clients": 1 + }, + { + "operation": "match-all-query", + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] +} +``` + +For the full list of available operation types, see [`operations`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/operations/). + +### Defining operations inline + +If you don't want to reuse an operation in the schedule, you can define operations inside the `schedule` element, as shown in the following example: + +```yml +{ + "schedule": [ + { + "operation": { + "name": "force-merge", + "operation-type": "force-merge" + }, + "clients": 1 + }, + { + "operation": { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] +} +``` + +## Task options + +Each task contains the following options. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`operation` | Yes | List | Either refers to the name of an operation, defined in the `operations` element, or includes the entire operation inline. +`name` | No | String | Specifies a unique name for the task when multiple tasks use the same operation. +`tags` | No | String | Unique identifiers that can be used to filter between `tasks.clients` or the number of clients that should execute a task concurrently. Default is 1. +`clients` | No | Integer | Specifies the number of clients that will run the task concurrently. Default is `1`. + +## Target options + +OpenSearch Benchmark requires one of the following options when running a task. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`target-throughput` | No | Integer | Defines the benchmark mode. When not defined, OpenSearch Benchmark assumes that it is a throughput benchmark and runs the task as fast as possible. This is useful for batch operations, where achieving better throughput is preferred over better latency. When defined, the target specifies the number of requests per second across all clients. For example, if you specify `target-throughput: 1000` with 8 clients, each client issues 125 (= 1000 / 8) requests per second. +`target-interval` | No | Interval | Defines an interval of 1 divided by the `target-throughput` (in seconds) when the `target-throughput` is less than 1 operation per second. Define either `target-throughput` or `target-interval` but not both, otherwise OpenSearch Benchmark raises an error. +`ignore-response-error-level` | No | Boolean | Controls whether to ignore errors encountered during the task when a benchmark is run with the `on-error=abort` command flag. + +## Iteration-based options + +Iteration-based options determine the number of times that an operation should run. They can also define the number of iterative runs when tasks are run in [parallel](#parallel-tasks). To configure an iteration-based schedule, use the following options. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`iterations` | No | Integer | Specifies the number of times that a client should execute an operation. All iterations are included in the measured results. Default is `1`. +`warmup-iterations` | No | Integer | Specifies the number of times that a client should execute an operation in order to warm up the benchmark candidate. The `warmup-iterations` do not appear in the measurement results. Default is `0`. + +## Time-based options + +Time-based options determine the duration of time, in seconds, for which operations should run. This is ideal for batch-style operations, which may require an additional warmup period. + +To configure a time-based schedule, use the following options. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`time-period` | No | Integer | Specifies the time period, in seconds, that OpenSearch Benchmark considers for measurement. This is not required for bulk indexing because OpenSearch Benchmark bulk indexes all documents and naturally measures all samples after the specified `warmup-time-period`. +`ramp-up-time-period` | No | Integer | Specifies the time period, in seconds, during which OpenSearch Benchmark gradually adds clients and reaches the total number of clients specified for the operation. +`warmup-time-period` | No | Integer | Specifies the amount of time, in seconds, to warm up the benchmark candidate. None of the response data captured during the warmup period appears in the measurement results. + +## Parallel tasks + +The `parallel` element concurrently runs tasks wrapped inside the element. + +When running tasks in parallel, each task requires the `client` option in order to ensure that clients inside your benchmark are reserved for that task. Otherwise, when the `client` option is specified inside the `parallel` element without a connection to the task, the benchmark uses that number of clients for all tasks. + +In the following example, `parallel-task-1` and `parallel-task-2` execute a `bulk` operation concurrently: + +```yml +{ + "name": "parallel-any", + "description": "Workload completed-by property", + "schedule": [ + { + "parallel": { + "tasks": [ + { + "name": "parellel-task-1", + "operation": { + "operation-type": "bulk", + "bulk-size": 1000 + }, + "clients": 8 + }, + { + "name": "parellel-task-2", + "operation": { + "operation-type": "bulk", + "bulk-size": 500 + }, + "clients": 8 + } + ] + } + } + ] +} +``` + +The `parallel` element supports all `schedule` parameters, in addition to the following options. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`tasks` | Yes | Array | Defines a list of tasks that should be executed concurrently. +`completed-by` | No | String | Allows you to define the name of one task in the task list or the value `any`. If `completed-by` is set to the name of one task in the list, the `parallel-task` structure is considered to be complete once that specific task has been completed. If `completed-by` is set to `any`, the `parallel-task` structure is considered to be complete when any one of the tasks in the list has been completed. If `completed-by` is not explicitly defined, the `parallel-task` structure is considered to be complete as soon as all of the tasks in the list have been completed. diff --git a/_benchmark/reference/workloads/test-procedures.md b/_benchmark/reference/workloads/test-procedures.md index 43099f0a..93ac3bd0 100644 --- a/_benchmark/reference/workloads/test-procedures.md +++ b/_benchmark/reference/workloads/test-procedures.md @@ -1,18 +1,17 @@ --- layout: default title: test_procedures -parent: Workload reference -grand_parent: OpenSearch Benchmark Reference -nav_order: 110 +parent: Anatomy of a workload +nav_order: 50 --- -# test_procedures +# test_procedures element -If your workload only defines one benchmarking scenario, specify the schedule at the top level. Use the `test-procedures` element to specify additional properties, such as a name or description. A test procedure is like a benchmarking scenario. If you have multiple test procedures, you can define a variety of challenges. +A test procedure is a single benchmarking scenario. Each test procedure wraps a [`schedule`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/schedule/) and adds properties such as a name and description. Use the `test_procedures` element when a workload defines multiple scenarios. When a workload defines only one scenario, specify `schedule` at the top level of `workload.json` instead and omit `test_procedures`. -The following table lists test procedures for the benchmarking scenarios in this dataset. A test procedure can reference all operations that are defined in the operations section. +A test procedure can reference all operations defined in the [`operations`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/operations/) element. Each test procedure supports the following parameters. Parameter | Required | Type | Description :--- | :--- | :--- | :--- @@ -20,175 +19,4 @@ Parameter | Required | Type | Description `description` | No | String | Describes the test procedure in a human-readable format. `user-info` | No | String | Outputs a message at the start of the test to notify you about important test-related information, for example, deprecations. `default` | No | Boolean | When set to `true`, selects the default test procedure if you did not specify a test procedure on the command line. If the workload only defines one test procedure, it is implicitly selected as the default. Otherwise, you must define `"default": true` on exactly one challenge. -[`schedule`](#Schedule) | Yes | Array | Defines the order in which workload tasks are run. - - -## schedule - - -The `schedule` element contains a list of a tasks, which are operations supported by OpenSearch Benchmark, that are run by the workload during the benchmark test. - -### Usage - -The `schedule` element defines tasks using the methods described in this section. - -#### Using the operations element - -The following example defines a `force-merge` and `match-all` query task using the `operations` element. The `force-merge` operation does not use any parameters, so only the `name` and `operation-type` are needed. The `match-all-query` parameter requires a query `body` and `operation-type`. - -Operations defined in the `operations` element can be reused in the schedule more than once: - -```yml -{ - "operations": [ - { - "name": "force-merge", - "operation-type": "force-merge" - }, - { - "name": "match-all-query", - "operation-type": "search", - "body": { - "query": { - "match_all": {} - } - } - } - ], - "schedule": [ - { - "operation": "force-merge", - "clients": 1 - }, - { - "operation": "match-all-query", - "clients": 4, - "warmup-iterations": 1000, - "iterations": 1000, - "target-throughput": 100 - } - ] -} -``` - -#### Defining operations inline - -If you don't want to reuse an operation in the schedule, you can define operations inside the `schedule` element, as shown in the following example: - -```yml -{ - "schedule": [ - { - "operation": { - "name": "force-merge", - "operation-type": "force-merge" - }, - "clients": 1 - }, - { - "operation": { - "name": "match-all-query", - "operation-type": "search", - "body": { - "query": { - "match_all": {} - } - } - }, - "clients": 4, - "warmup-iterations": 1000, - "iterations": 1000, - "target-throughput": 100 - } - ] -} -``` - -### Task options - -Each task contains the following options. - -Parameter | Required | Type | Description -:--- | :--- | :--- | :--- -`operation` | Yes | List | Either refers to the name of an operation, defined in the `operations` element, or includes the entire operation inline. -`name` | No | String | Specifies a unique name for the task when multiple tasks use the same operation. -`tags` | No | String | Unique identifiers that can be used to filter between `tasks.clients` or the number of clients that should execute a task concurrently. Default is 1. -`clients` | No | Integer | Specifies the number of clients that will run the task concurrently. Default is `1`. - -### Target options - -OpenSearch Benchmark requires one of the following options when running a task: - -`target-throughput` | No | Integer | Defines the benchmark mode. When not defined, OpenSearch Benchmark assumes that it is a throughput benchmark and runs the task as fast as possible. This is useful for batch operations, where achieving better throughput is preferred over better latency. When defined, the target specifies the number of requests per second across all clients. For example, if you specify `target-throughput: 1000` with 8 clients, each client issues 125 (= 1000 / 8) requests per second. -`target-interval` | No | Interval | Defines an interval of 1 divided by the `target-throughput` (in seconds) when the `target-throughput` is less than 1 operation per second. Define either `target-throughput` or `target-interval` but not both, otherwise OpenSearch Benchmark raises an error. -`ignore-response-error-level` | No | Boolean | Controls whether to ignore errors encountered during the task when a benchmark is run with the `on-error=abort` command flag. - -### Iteration-based options - -Iteration-based options determine the number of times that an operation should run. It can also define the number of iterative runs when tasks are run in [parallel](#parallel-tasks). To configure an iteration-based schedule, use the following options. - -Parameter | Required | Type | Description -:--- | :--- | :--- | :--- -`iterations` | No | Integer | Specifies the number of times that a client should execute an operation. All iterations are included in the measured results. Default is `1`. -`warmup-iterations` | No | Integer | Specifies the number of times that a client should execute an operation in order to warm up the benchmark candidate. The `warmup-iterations` do not appear in the measurement results. Default is `0`. - -### Parallel tasks - -The `parallel` element concurrently runs tasks wrapped inside the element. - -When running tasks in parallel, each task requires the `client` option in order to ensure that clients inside your benchmark are reserved for that task. Otherwise, when the `client` option is specified inside the `parallel` element without a connection to the task, the benchmark uses that number of clients for all tasks. - -#### Usage - -In the following example, `parallel-task-1` and `parallel-task-2` execute a `bulk` operation concurrently: - -```yml -{ - "name": "parallel-any", - "description": "Workload completed-by property", - "schedule": [ - { - "parallel": { - "tasks": [ - { - "name": "parellel-task-1", - "operation": { - "operation-type": "bulk", - "bulk-size": 1000 - }, - "clients": 8 - }, - { - "name": "parellel-task-2", - "operation": { - "operation-type": "bulk", - "bulk-size": 500 - }, - "clients": 8 - } - ] - } - } - ] -} -``` - -#### Options - -The `parallel` element supports all `schedule` parameters, in addition to the following options. - -`tasks` | Yes | Array | Defines a list of tasks that should be executed concurrently. -`completed-by` | No | String | Allows you to define the name of one task in the task list or the value `any`. If `completed-by` is set to the name of one task in the list, the `parallel-task` structure is considered to be complete once that specific task has been completed. If `completed-by` is set to `any`, the `parallel-task` structure is considered to be complete when any one of the tasks in the list has been completed. If `completed-by` is not explicitly defined, the `parallel-task` structure is considered to be complete as soon as all of the tasks in the list have been completed. - -### Time-based options - -Time-based options determine the duration of time, in seconds, for which operations should run. This is ideal for batch-style operations, which may require an additional warmup period. - -To configure a time-based schedule, use the following options. - -Parameter | Required | Type | Description -:--- | :--- | :--- | :--- -`time-period` | No | Integer | Specifies the time period, in seconds, that OpenSearch Benchmark considers for measurement. This is not required for bulk indexing because OpenSearch Benchmark bulk indexes all documents and naturally measures all samples after the specified `warmup-time-period`. -`ramp-up-time-period` | No | Integer | Specifies the time period, in seconds, during which OpenSearch Benchmark gradually adds clients and reaches the total number of clients specified for the operation. -`warmup-time-period` | No | Integer | Specifies the amount of time, in seconds, to warm up the benchmark candidate. None of the response data captured during the warmup period appears in the measurement results. - +[`schedule`]({{site.url}}{{site.baseurl}}/benchmark/reference/workloads/schedule/) | Yes | Array | Defines the order in which workload tasks are run. diff --git a/_benchmark/running-workloads.md b/_benchmark/running-workloads.md new file mode 100644 index 00000000..5682df72 --- /dev/null +++ b/_benchmark/running-workloads.md @@ -0,0 +1,200 @@ +--- +layout: default +title: Running a workload +nav_order: 30 +redirect_from: + - /benchmark/user-guide/running-workloads/ + - /benchmark/user-guide/working-with-workloads/running-workloads/ + - /benchmark/user-guide/working-with-workloads/ +--- + +# Running a workload + +Once you have a complete understanding of the various components of an OpenSearch Benchmark [workload]({{site.url}}{{site.baseurl}}/benchmark/anatomy-of-a-workload/), you can run your first workload. + +## Step 1: Find the workload name + +To learn more about the standard workloads included with OpenSearch Benchmark, use the following command: + +``` +opensearch-benchmark list workloads +``` +{% include copy.html %} + +A list of all workloads supported by OpenSearch Benchmark appears. Review the list and select the workload that's most similar to your cluster's use case. + +## Step 2: Running the test + +After you've selected the workload, you can invoke the workload using the `opensearch-benchmark run` command. Replace `--target-host` with the `host:port` pairs for your cluster and `--client-options` with any authorization options required to access the cluster. The following example runs the `nyc_taxis` workload on a localhost for testing purposes. + +If you want to run a test on an external cluster, see [Running the workload on your own cluster](#running-a-workload-on-an-external-cluster). + +```bash +opensearch-benchmark run --pipeline=benchmark-only --workload=nyc_taxis --target-host=https://localhost:9200 --client-options=basic_auth_user:admin,basic_auth_password:admin,verify_certs:false +``` +{% include copy.html %} + + +Results from the test appear in the directory set by the `--output-path` option in the `run` command. + +### Test mode + +If you want to run the test in test mode to make sure that your workload operates as intended, add the `--test-mode` option to the `run` command. Test mode ingests only the first 1,000 documents from each index provided and runs query operations against them. + +### Working with `--workload-params` + +You can customize the behavior of a workload by passing workload-specific parameters using the `--workload-params` option. This flag accepts a comma-separated list of key-value pairs that override default values defined in the workload's `workload.json` file. + +For example, some workloads let you configure the number of documents indexed, the number of clients used for query execution, or the index name. These parameters can be critical for tailoring benchmarks to your specific use case or infrastructure constraints. + +To pass workload parameters, use the following syntax: + +```bash +--workload-params="number_of_documents:100000,index_name:custom-index" +``` + +Add this option to your `run` command, as shown in the following example: + +```bash +opensearch-benchmark run \ +--pipeline=benchmark-only \ +--workload=nyc_taxis \ +--target-host=https://localhost:9200 \ +--client-options=basic_auth_user:admin,basic_auth_password:admin,verify_certs:false \ +--workload-params="bulk_size:500,index_name:nyc_custom" +``` + +Available workload parameters can be found in the `README` of each workload in the [OpenSearch Benchmark Workloads GitHub repository](https://github.com/opensearch-project/opensearch-benchmark-workloads). +{: .tip} + + + + +## Step 3: Validate the test + +After running an OpenSearch Benchmark test, take the following steps to verify that it has run properly: + +1. Note the number of documents in the OpenSearch or OpenSearch Dashboards index that you plan to run the benchmark against. +2. In the results returned by OpenSearch Benchmark, compare the `workload.json` file for your specific workload and verify that the document count matches the number of documents. For example, based on the [nyc_taxis](https://github.com/opensearch-project/opensearch-benchmark-workloads/blob/main/nyc_taxis/workload.json#L20) `workload.json` file, you should expect to see `165346692` documents in your cluster. + +## Expected results + +OSB returns the following response once the benchmark completes: + +```bash +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 0.02655 | min | +| Min cumulative indexing time across primary shards | | 0 | min | +| Median cumulative indexing time across primary shards | | 0.00176667 | min | +| Max cumulative indexing time across primary shards | | 0.0140333 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 0.0102333 | min | +| Cumulative merge count of primary shards | | 3 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0 | min | +| Max cumulative merge time across primary shards | | 0.0102333 | min | +| Cumulative merge throttle time of primary shards | | 0 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0 | min | +| Cumulative refresh time of primary shards | | 0.0709333 | min | +| Cumulative refresh count of primary shards | | 118 | | +| Min cumulative refresh time across primary shards | | 0 | min | +| Median cumulative refresh time across primary shards | | 0.00186667 | min | +| Max cumulative refresh time across primary shards | | 0.0511667 | min | +| Cumulative flush time of primary shards | | 0.00963333 | min | +| Cumulative flush count of primary shards | | 4 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0 | min | +| Max cumulative flush time across primary shards | | 0.00398333 | min | +| Total Young Gen GC time | | 0 | s | +| Total Young Gen GC count | | 0 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 0.000485923 | GB | +| Translog size | | 2.01873e-05 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 32 | | +| Min Throughput | index | 3008.97 | docs/s | +| Mean Throughput | index | 3008.97 | docs/s | +| Median Throughput | index | 3008.97 | docs/s | +| Max Throughput | index | 3008.97 | docs/s | +| 50th percentile latency | index | 351.059 | ms | +| 100th percentile latency | index | 365.058 | ms | +| 50th percentile service time | index | 351.059 | ms | +| 100th percentile service time | index | 365.058 | ms | +| error rate | index | 0 | % | +| Min Throughput | wait-until-merges-finish | 28.41 | ops/s | +| Mean Throughput | wait-until-merges-finish | 28.41 | ops/s | +| Median Throughput | wait-until-merges-finish | 28.41 | ops/s | +| Max Throughput | wait-until-merges-finish | 28.41 | ops/s | +| 100th percentile latency | wait-until-merges-finish | 34.7088 | ms | +| 100th percentile service time | wait-until-merges-finish | 34.7088 | ms | +| error rate | wait-until-merges-finish | 0 | % | +| Min Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| Mean Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| Median Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| Max Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| 100th percentile latency | percolator_with_content_president_bush | 35.9822 | ms | +| 100th percentile service time | percolator_with_content_president_bush | 7.93048 | ms | +| error rate | percolator_with_content_president_bush | 0 | % | + +[...] + +| Min Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| Mean Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| Median Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| Max Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| 100th percentile latency | percolator_with_content_ignore_me | 131.798 | ms | +| 100th percentile service time | percolator_with_content_ignore_me | 69.5237 | ms | +| error rate | percolator_with_content_ignore_me | 0 | % | +| Min Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| Mean Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| Median Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| Max Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| 100th percentile latency | percolator_no_score_with_content_ignore_me | 45.5703 | ms | +| 100th percentile service time | percolator_no_score_with_content_ignore_me | 11.316 | ms | +| error rate | percolator_no_score_with_content_ignore_me | 0 | % | + + + +----------------------------------- +[INFO] ✅ SUCCESS (took 18 seconds) +----------------------------------- +``` + + + +## Running a workload on an external cluster + +Now that you're familiar with running OpenSearch Benchmark on a local cluster, you can run it on your external cluster, as described in the following steps: + +1. Replace `https://localhost:9200` with your target cluster endpoint. This could be a Uniform Resource Identifier (URI), such as `https://search.mydomain.com`, or a `HOST:PORT` specification. +2. If the cluster is configured with basic authentication, replace the username and password in the command line with the appropriate credentials. +3. Remove the `verify_certs:false` directive if you are not specifying `localhost` as your target cluster. This directive is necessary solely for clusters without SSL certificates. +4. If you are using a `HOST:PORT`specification and plan to use SSL or TLS, either specify `https://` or add the `use_ssl:true` directive to the `--client-options` string option. +5. Remove the `--test-mode` flag to run the full workload rather than an abbreviated test. + +You can copy the following command template to use it in your own terminal: + +```bash +opensearch-benchmark run --pipeline=benchmark-only --workload=nyc_taxis --target-host= --client-options=basic_auth_user:admin,basic_auth_password:admin +``` +{% include copy.html %} diff --git a/_benchmark/target-throughput.md b/_benchmark/target-throughput.md new file mode 100644 index 00000000..b964c04b --- /dev/null +++ b/_benchmark/target-throughput.md @@ -0,0 +1,86 @@ +--- +layout: default +title: Target throughput +nav_order: 60 +redirect_from: + - /benchmark/user-guide/target-throughput/ + - /benchmark/user-guide/optimizing-benchmarks/target-throughput/ +--- + +# Target throughput + +Target throughput is key to understanding the OpenSearch Benchmark definition of *latency*. Target throughput is the rate at which OpenSearch Benchmark issues requests, assuming that responses will be returned instantaneously. `target-throughput` is a common workload parameter that can be set for each test and is measured in operations per second. + +OpenSearch Benchmark has two testing modes, both of which are related to throughput, latency, and service time: + +- [Benchmarking mode](#benchmarking-mode): Latency is measured in the same way as service time. +- [Throughput-throttled mode](#throughput-throttled-mode): Latency is measured as service time plus the time that a request spends waiting in the queue. + +## Benchmarking mode + +When `target-throughput` is set to `0`, OpenSearch Benchmark latency tests are performed in *benchmarking mode*. In this mode, the OpenSearch client sends requests to the OpenSearch cluster as fast as possible. After the cluster receives a response from the previous request, OpenSearch Benchmark immediately sends the next request to the OpenSearch client. In this testing mode, latency is identical to service time. + +OpenSearch Benchmark issues one request at a time per a single client. The number of clients is set by the `search-clients` setting in the workload parameters. + +## Throughput-throttled mode + +If the `target-throughput` is not set to `0`, then OpenSearch Benchmark issues the next request in accordance with the `target-throughput`, assuming that responses are returned instantaneously. + +**Throughput** measures the rate at which OpenSearch Benchmark issues requests, assuming that responses are returned instantaneously. To configure the request rate, you can set the `target-throughput` workload parameter to the desired number of operations per second for each test. + +When you want to simulate the type of traffic you might encounter when deploying a production cluster, set the `target-throughput` in your benchmark test to match the number of requests you estimate that the production cluster might receive. The following examples show how the `target-throughput` setting affects the latency measurement. + +### Example A + +The following diagrams illustrate how latency is calculated with an expected request response time of 200 ms and the following settings: + +- `search-clients` is set to `1`. +- `target-throughput` is set to `1` operation per second. + +![Request schedule showing expected 200 ms response times at 1 operation per second]({{site.url}}{{site.baseurl}}/images/benchmark/latency-explanation-1.png) + +When a request takes longer than 200 ms, such as when a request takes 1110 ms instead of 400 ms, OpenSearch Benchmark sends the next request that was supposed to occur at 4.00 s based on the `target-throughput` of 4.10 s. All requests subsequent to the 4.10 s request attempt to re-synchronize with the `target-throughput` setting, as shown in the following image: + +![Request schedule showing a delayed request re-synchronizing with the target throughput]({{site.url}}{{site.baseurl}}/images/benchmark/latency-explanation-2.png) + +When measuring the overall latency, OpenSearch Benchmark includes all performed requests. All requests have a latency of 200 ms, except for the following two requests: + +- The request that lasted 1100 ms. +- The subsequent request which should have started at 4.00 s. This request was delayed by 100 ms, denoted by the orange-colored area in the following diagram, and had a response time of 200 ms. When calculating the latency for this request, OpenSearch Benchmark accounts for the delayed start time and combines it with the response time. The latency for this request is **300 ms**. + +![Latency calculation showing the delayed request with combined wait time and response time]({{site.url}}{{site.baseurl}}/images/benchmark/latency-explanation-3.png) + +### Example B + +In this example, OpenSearch Benchmark assumes a latency of 200 ms and uses the following latency settings: + +- `search_clients` is set to `1`. +- `target-throughput` is set to `10` operations per second. + +The following diagram shows the schedule built by OpenSearch Benchmark with the expected response times. + +![Request schedule with target throughput of 10 operations per second and expected 200 ms response times]({{site.url}}{{site.baseurl}}/images/benchmark/b-latency-explanation-1.png) + +However, if it is assumed that all responses will have a latency of 200 ms, then 10 operations per second won't be possible. Therefore, the highest throughput that OpenSearch Benchmark can reach is 5 operations per second, as shown in the following diagram. + +![Actual throughput limited to 5 operations per second due to 200 ms response times]({{site.url}}{{site.baseurl}}/images/benchmark/b-latency-explanation-2.png) + +OpenSearch Benchmark does not account for this limitation and continues to try to achieve the `target-throughput` of 10 operations per second. Because of this, delays for each request begin to cascade, as illustrated in the following diagram. + +![Cascading delays as OpenSearch Benchmark attempts to maintain target throughput beyond capacity]({{site.url}}{{site.baseurl}}/images/benchmark/b-latency-explanation-3.png) + +By combining the service time and the delay for each operation, the following latency measurements are provided for each operation: + +- 200 ms for operation 1 +- 300 ms for operation 2 +- 400 ms for operation 3 +- 500 ms for operation 4 +- 600 ms for operation 5 + +This latency cascade continues, increasing latency by 100 ms for each subsequent request. + +### Recommendation + +As shown in the preceding examples, you should be aware of each task's average service time and should provide a `target-throughput` that accounts for the service time. OpenSearch Benchmark latency is calculated based on the `target-throughput` set by the user; therefore, *latency* could be redefined as *throughput-based latency*. + + diff --git a/_benchmark/user-guide/concepts.md b/_benchmark/user-guide/concepts.md index b353538a..8b2fafb8 100644 --- a/_benchmark/user-guide/concepts.md +++ b/_benchmark/user-guide/concepts.md @@ -3,15 +3,24 @@ layout: default title: Concepts nav_order: 3 parent: User guide +has_toc: false --- -# Concepts +# OpenSearch Benchmark concepts -Before using OpenSearch Benchmark, familiarize yourself with the following concepts. +Before you start using OpenSearch Benchmark, it's helpful to understand the following concepts, in order to effectively design, run, and analyze your benchmarks to evaluate OpenSearch performance under different scenarios. + +## Benchmark architecture + +The following diagram illustrates how OpenSearch Benchmark operates when running against a local host. + +![Benchmark workflow]({{site.url}}{{site.baseurl}}/images/benchmark/osb-workflow.jpg). ## Core concepts and definitions -- **Workload**: The description of one or more benchmarking scenarios that use a specific document corpus to perform a benchmark against your cluster. The document corpus contains any indexes, data files, and operations invoked when the workflow runs. You can list the available workloads by using `opensearch-benchmark list workloads` or view any included workloads in the [OpenSearch Benchmark Workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads/). For more information about the elements of a workload, see [Anatomy of a workload]({{site.url}}{{site.baseurl}}/benchmark/user-guide/understanding-workloads/anatomy-of-a-workload/). For information about building a custom workload, see [Creating custom workloads]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/). +- **Workload**: A collection of one or more benchmarking scenarios that use a specific document corpus to perform a benchmark against your cluster. The document corpus contains any indexes, data files, and operations invoked when the workload runs. You can list the available workloads by using `opensearch-benchmark list workloads` or view any included workloads in the [OpenSearch Benchmark Workloads repository](https://github.com/opensearch-project/opensearch-benchmark-workloads/). For more information about the elements of a workload, see [Anatomy of a workload]({{site.url}}{{site.baseurl}}/benchmark/anatomy-of-a-workload/). For information about building a custom workload, see [Creating custom workloads]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/). A workload typically includes the following components: + - One or more data streams that are ingested into indexes. + - A set of queries and operations that are invoked as part of the benchmark. - **Pipeline**: A series of steps occurring before and after a workload is run that determines benchmark results. OpenSearch Benchmark supports three pipelines: - `from-sources`: Builds and provisions OpenSearch, runs a benchmark, and then publishes the results. @@ -20,95 +29,58 @@ Before using OpenSearch Benchmark, familiarize yourself with the following conce - **Test**: A single invocation of the OpenSearch Benchmark binary. -A workload is a specification of one or more benchmarking scenarios. A workload typically includes the following: - -- One or more data streams that are ingested into indexes. -- A set of queries and operations that are invoked as part of the benchmark. - -## Throughput and latency +## Test concepts At the end of each test, OpenSearch Benchmark produces a table that summarizes the following: -- [Service time](#service-time) -- Throughput -- [Latency](#latency) -- The error rate for each completed task or OpenSearch operation. + - [Processing time](#processing-time) + - [Took time](#took-time) + - [Service time](#service-time) + - [Latency](#latency) + - [Throughput](#throughput) -While the definition for _throughput_ remains consistent with other client-server systems, the definitions for `service time` and `latency` differ from most client-server systems in the context of OpenSearch Benchmark. The following table compares the OpenSearch Benchmark definition of service time and latency versus the common definitions for a client-server system. +The following diagram illustrates how each component of the table is measured during the lifecycle of a request involving the OpenSearch cluster, the OpenSearch client, and OpenSearch Benchmark. + +![Diagram showing how service time, latency, and throughput are measured during the lifecycle of a request]({{site.url}}{{site.baseurl}}/images/benchmark/concepts-diagram.png) + +### Differences between OpenSearch Benchmark and a traditional client-server system + +While the definition for _throughput_ remains consistent with other client-server systems, the definitions for `service time` and `latency` differ from most client-server systems in the context of OpenSearch Benchmark. The following table compares the OpenSearch Benchmark definition of service time and latency compared to the common definitions for a client-server system. | Metric | Common definition | **OpenSearch Benchmark definition** | | :--- | :--- |:--- | | **Throughput** | The number of operations completed in a given period of time. | The number of operations completed in a given period of time. | -| **Service time** | The amount of time that the server takes to process a request, from the point it receives the request to the point the response is returned.

It includes the time spent waiting in server-side queues but _excludes_ network latency, load balancer overhead, and deserialization/serialization. | The amount of time that it takes for `opensearch-py` to send a request and receive a response from the OpenSearch cluster.

It includes the amount of time that it takes for the server to process a request and also _includes_ network latency, load balancer overhead, and deserialization/serialization. | -| **Latency** | The total amount of time, including the service time and the amount of time that the request waited before responding. | Based on the `target-throughput` set by the user, the total amount of time that the request waited before receiving the response, in addition to any other delays that occured before the request is sent. | +| **Service time** | The amount of time that the server takes to process a request, from the point it receives the request to the point the response is returned. It includes the time spent waiting in server-side queues but _excludes_ network latency, load balancer overhead, and deserialization/serialization. | The amount of time that it takes for `opensearch-py` to send a request and receive a response from the OpenSearch cluster. It includes the amount of time that it takes for the server to process a request and also _includes_ network latency, load balancer overhead, and deserialization/serialization. | +| **Latency** | The total amount of time, including the service time and the amount of time that the request waits before responding. | Based on the `target-throughput` set by the user, the total amount of time that the request waits before receiving the response, in addition to any other delays that occur before the request is sent. | For more information about service time and latency in OpenSearch Benchmark, see the [Service time](#service-time) and [Latency](#latency) sections. +### Processing time + +*Processing time* accounts for any extra overhead tasks that OpenSearch Benchmark performs during the lifecycle of a request, such as setting up a request context manager or calling a method to pass the request to the OpenSearch client. This is in contrast to *service time*, which only accounts for the difference between when a request is sent and when the OpenSearch client receives the response. + +### Took time + +*Took time* measures the amount of time that the cluster spends processing a request on the server side. It does not include the time taken for the request to transit from the client to the cluster or for the response to transit from the cluster to the client. + ### Service time -OpenSearch Benchmark does not have insight into how long OpenSearch takes to process a request, apart from extracting the `took` time for the request. In OpenSearch, **service time** tracks the amount of time between when OpenSearch issues a request and receives a response. -OpenSearch Benchmark makes function calls to `opensearch-py` to communicate with an OpenSearch cluster. OpenSearch Benchmark tracks the amount of time between when the `opensearch-py` client sends a request and receives a response from the OpenSearch cluster and considers this to be the service time. Unlike the traditional definition of service time, the OpenSearch Benchmark definition of service time includes overhead, such as network latency, load balancer overhead, or deserialization/serialization. The following image highlights the differences between the traditional definition of service time and the OpenSearch Benchmark definition of service time. +OpenSearch Benchmark does not have insight into how long OpenSearch takes to process a request, apart from extracting the [took time](#took-time) for the request. It makes function calls to `opensearch-py` in order to communicate with an OpenSearch cluster. - +OpenSearch Benchmark measures *service time*, which is the amount of time between when the `opensearch-py` client sends a request to and receives a response from the OpenSearch cluster. Unlike the traditional definition of service time, the OpenSearch Benchmark definition includes overhead, such as network latency, load balancer overhead, or deserialization/serialization. The following image shows the differences between the traditional definition and the OpenSearch Benchmark definition. + +![Comparison of traditional service time definition compared to OpenSearch Benchmark service time definition]({{site.url}}{{site.baseurl}}/images/benchmark/service-time.png) ### Latency -Target throughput is key to understanding the OpenSearch Benchmark definition of **latency**. Target throughput is the rate at which OpenSearch Benchmark issues requests, assuming that responses will be returned instantaneously. `target-throughput` is one of the common workload parameters that can be set for each test and is measured in operations per second. +*Latency* measures the total time that the request waits before receiving the response as well as any delays that occur prior to sending the request. In most circumstances, latency is measured in the same way as service time, unless you are testing in [throughput-throttled mode]({{site.url}}{{site.baseurl}}/benchmark/user-guide/target-throughput/). In this case, latency is measured as service time plus the time that the request spends waiting in the queue. -OpenSearch Benchmark always issues one request at a time for a single client thread, specified as `search-clients` in the workload parameters. If `target-throughput` is set to `0`, OpenSearch Benchmark issues a request immediately after it receives the response from the previous request. If the `target-throughput` is not set to `0`, OpenSearch Benchmark issues the next request to match the `target-throughput`, assuming that responses are returned instantaneously. -#### Example A +### Throughput -The following diagrams illustrate how latency is calculated with an expected request response time of 200ms and the following settings: +**Throughput** measures the rate at which OpenSearch Benchmark issues requests, assuming that responses will be returned instantaneously. -- `search-clients` is set to `1`. -- `target-throughput` is set to `1` operation per second. - - -When a request takes longer than 200ms, such as when a request takes 1110ms instead of 400ms, OpenSearch Benchmark sends the next request that was supposed to occur at 4.00s based on the `target-throughput` at 4.10s. All subsequent requests after the 4.10s request attempt to resynchronize with the `target-throughput` setting. - - - -When measuring the overall latency, OpenSearch Benchmark includes all performed requests. All requests have a latency of 200ms, except for the following two requests: - -- The request that lasted 1100ms. -- The subsquent request that was supposed to start at 4:00s. This request was delayed by 100ms, denoted by the orange area in the following diagram, and had a response time of 200ms. When calculating the latency for this request, OpenSearch Benchmark will account for the delayed start time and combine it with the response time. Thus, the latency for this request is **300ms**. - - - -#### Example B - -In this example, OpenSearch Benchmark assumes a latency of 200ms and uses the following latency settings: - -- `search_clients` is set to `1`. -- `target-throughput` is set to `10` operations per second. - -The following diagram shows the schedule built by OpenSearch Benchmark with the expected response times. - - - -However, if the assumption is that all responses will take 200ms, 10 operations per second won't be possible. Therefore, the highest throughput OpenSearch Benchmark can reach is 5 operations per second, as shown in the following diagram. - - - -OpenSearch Benchmark does not account for this and continues to try to achieve the `target-throughput` of 10 operations per second. Because of this, delays for each request begin to cascade, as illustrated in the following diagram. - - - -Combining the service time with the delay for each operation provides the following latency measurements for each operation: - -- 200 ms for operation 1 -- 300 ms for operation 2 -- 400 ms for operation 3 -- 500 ms for operation 4 -- 600 ms for operation 5 - -This latency cascade continues, increasing latency by 100ms for each subsequent request. - -### Recommendation - -As shown by the preceding examples, you should be aware of the average service time of each task and provide a `target-throughput` that accounts for the service time. The OpenSearch Benchmark latency is calculated based on the `target-throughput` set by the user, that is, the latency could be redefined as "throughput-based latency." diff --git a/_benchmark/user-guide/index.md b/_benchmark/user-guide/index.md index 35828552..a116398f 100644 --- a/_benchmark/user-guide/index.md +++ b/_benchmark/user-guide/index.md @@ -1,10 +1,40 @@ --- layout: default title: User guide -nav_order: 5 +nav_order: 10 has_children: true +has_toc: false +more_cards: + - heading: "Concepts" + description: "Learn core OpenSearch Benchmark concepts" + link: "/benchmark/user-guide/concepts/" + - heading: "Install and configure OpenSearch Benchmark" + description: "Install OpenSearch Benchmark and configure your experience" + link: "/benchmark/user-guide/install-and-configure/index/" + - heading: "Choosing a workload" + description: "Compare the prepackaged workloads and select the one that matches your cluster" + link: "/benchmark/choosing-a-workload/" + - heading: "Anatomy of a workload" + description: "Dive deep into each workload component" + link: "/benchmark/anatomy-of-a-workload/" + - heading: "Run and customize your workload" + description: "Run and customize your OpenSearch workload to get the most accurate results" + link: "/benchmark/running-workloads/" + - heading: "Understanding your results" + description: "Analyze and store your benchmark results" + link: "/benchmark/reference/summary-report/" + - heading: "Optimizing benchmarks" + description: "Optimize your benchmark experience through randomization and best practices" + link: "/benchmark/performance-testing-best-practices/" +redirect_from: + - /benchmark/user-guide/ --- -# OpenSearch Benchmark User Guide + +# OpenSearch Benchmark user guide + -The OpenSearch Benchmark User Guide includes core [concepts]({{site.url}}{{site.baseurl}}/benchmark/user-guide/concepts/), [installation]({{site.url}}{{site.baseurl}}/benchmark/installing-benchmark/) instructions, and [configuration options]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/) to help you get the most out of OpenSearch Benchmark. \ No newline at end of file +The OpenSearch Benchmark user guide includes core [concepts]({{site.url}}{{site.baseurl}}/benchmark/user-guide/concepts/), [installation instructions]({{site.url}}{{site.baseurl}}/benchmark/installing-benchmark/), and [configuration options]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/) to help you get the most out of OpenSearch Benchmark. + + +{% include cards.html cards=page.more_cards %} \ No newline at end of file diff --git a/_benchmark/user-guide/install-and-configure/configuring-benchmark.md b/_benchmark/user-guide/install-and-configure/configuring-benchmark.md new file mode 100644 index 00000000..8c8f6056 --- /dev/null +++ b/_benchmark/user-guide/install-and-configure/configuring-benchmark.md @@ -0,0 +1,318 @@ +--- +layout: default +title: Configuring +nav_order: 7 +grand_parent: User guide +parent: Install and configure OpenSearch Benchmark +redirect_from: + - /benchmark/configuring-benchmark/ + - /benchmark/user-guide/configuring-benchmark/ + - /benchmark/tutorials/sigv4/ +--- + +# Configuring OpenSearch Benchmark + +OpenSearch Benchmark configuration data is stored in `~/.benchmark/benchmark.ini`, which is automatically created the first time OpenSearch Benchmark runs. + +The file is separated into the following sections, which you can customize based on the needs of your cluster. + +## client_options + +This section explains how to customize client-level settings during benchmark execution using the `--client-options` command line flag. + +You can pass client-specific parameters to OpenSearch Benchmark using the `--client-options` flag. These parameters let you control low-level client behavior such as timeouts, authentication methods, and SSL settings. + +The `--client-options` flag accepts a comma-separated list of key-value pairs, as shown in the following example: + +```bash +--client-options=timeout:120,verify_certs:false +``` + +You can customize `--client-options` with the following settings. + +| Option | Type | Description | +| :---- | :---- | :---- | +| `timeout` | Integer | Sets the request timeout value in seconds. | +| `verify_certs` | Boolean | Determines whether to verify SSL certificates when connecting to the OpenSearch cluster. | +| `basic_auth_user` | String | The username used to authenticate with the OpenSearch cluster (if authentication is enabled). | +| `basic_auth_password` | String | The password used to authenticate with the OpenSearch cluster (if authentication is enabled). | + +This example runs a benchmark with a 2-minute timeout and disabled certificate verification: + +```bash +opensearch-benchmark run \ +--target-hosts=https://localhost:9200 \ +--pipeline=benchmark-only \ +--workload=geonames \ +--client-options=timeout:120,verify_certs:false +``` + + +## meta + + +This section contains meta information about the configuration file. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `config.version` | Integer | The version of the configuration file format. This property is managed by OpenSearch Benchmark and should not be changed. | + + +## system + + +This section contains global information for the current benchmark environment. This information should be identical on all machines on which OpenSearch Benchmark is installed. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `env.name` | String | The name of the benchmark environment used as metadata in metrics documents when an OpenSearch metrics store is configured. Only alphanumeric characters are allowed. Default is `local`. | +| `available.cores` | Integer | Determines the number of available CPU cores. OpenSearch Benchmark aims to create one `asyncio` event loop per core and distributes it to clients evenly across event loops. Defaults to the number of logical CPU cores for your cluster. | +| `async.debug` | Boolean | Enables debug mode on OpenSearch Benchmark's `asyncio` event loop. Default is `false`. | +| `passenv` | String | A comma-separated list of environment variable names that should be passed to OpenSearch for processing. | + + +## node + + +This section contains node-specific information that can be customized according to the needs of your cluster. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `root.dir` | String | The directory that stores all OpenSearch Benchmark data. OpenSearch Benchmark assumes control over this directory and all its subdirectories. | +| `src.root.dir` | String | The directory from which the OpenSearch source code and any OpenSearch plugins are called. Only relevant for benchmarks from [sources](#source). | + + +## source + + +This section contains more details about the OpenSearch source tree. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `remote.repo.url` | URL | The URL from which to check out OpenSearch. Default is `https://github.com/opensearch-project/OpenSearch.git`. +| `opensearch.src.subdir` | String | The local path relative to the `src.root.dir` of the OpenSearch search tree. Default is `OpenSearch`. +| `cache` | Boolean | Enables OpenSearch's internal source artifact cache, `opensearch*.tar.gz`, and any plugin zip files. Artifacts are cached based on their Git revision. Default is `true`. | +| `cache.days` | Integer | The number of days that an artifact should be kept in the source artifact cache. Default is `7`. | + + +## benchmarks + + +This section contains the settings that can be customized in the OpenSearch Benchmark data directory. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `local.dataset.cache` | String | The directory in which benchmark datasets are stored. Depending on the benchmarks that are run, this directory may contain hundreds of GB of data. Default path is `$HOME/.benchmark/benchmarks/data`. | + + +## reporting + + +This section defines how benchmark metrics are stored. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `datastore.type` | String | If set to `in-memory` all metrics are kept in memory while running the benchmark. If set to `opensearch` all metrics are instead written to a persistent metrics store and the data is made available for further analysis. Default is `in-memory`. | +| `sample.queue.size` | Function | The number of metric samples that can be stored in OpenSearch Benchmark's in-memory queue. Default is `2^20`. | +| metrics.request.downsample.factor | Integer| (default: 1): Determines how many service time and latency samples are saved in the metrics store. By default, all values are saved. If you want to, for example. keep only every 100th sample, specify `100`. This is useful to avoid overwhelming the metrics store in benchmarks with many clients. Default is `1`. | +| `output.processingtime` | Boolean | If set to `true`, OpenSearch shows the additional metric processing time in the command line report. Default is `false`. | + + +### `datastore.type` parameters + + +When `datastore.type` is set to `opensearch`, the following reporting settings can be customized. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `datastore.host` | IP address | The hostname of the metrics store, for example, `124.340.200.22`. | +| `datastore.port`| Port | The port number of the metrics store, for example, `9200`. | +| `datastore.secure` | Boolean | If set to `false`, OpenSearch assumes an HTTP connection. If set to true, it assumes an HTTPS connection. | +| `datastore.ssl.verification_mode` | String | When set to the default `full`, the metrics store’s SSL certificate is checked. To disable certificate verification, set this value to `none`. | +| `datastore.ssl.certificate_authorities` | String | Determines the local file system path to the certificate authority’s signing certificate. +| `datastore.user` | Username | Sets the username for the metrics store | +| `datastore.password` | String | Sets the password for the metrics store. Alternatively, this password can be configured using the `OSB_DATASTORE_PASSWORD` environment variable, which avoids storing credentials in a plain text file. The environment variable takes precedence over the config file if both define a password. | +| `datastore.probe.cluster_version` | String | Enables automatic detection of the metrics store’s version. Default is `true`. | +| `datastore.number_of_shards` | Integer | The number of primary shards that the `opensearch-*` indexes should have. Any updates to this setting after initial index creation will only be applied to new `opensearch-*` indexes. Default is the [OpenSearch static index value]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#static-index-settings). | +| `datastore.number_of_replicas` | Integer | The number of replicas each primary shard in the datastore contains. Any updates to this setting after initial index creation will only be applied to new `opensearch-* `indexes. Default is the [OpenSearch static index value]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#static-index-settings). | + +### Examples + +You can use the following examples to set reporting values in your cluster. + +This example defines an unprotected metrics store in the local network: + +``` +[reporting] +datastore.type = opensearch +datastore.host = 192.168.10.17 +datastore.port = 9200 +datastore.secure = false +datastore.user = +datastore.password = +``` + +This example defines a secure connection to a metrics store in the local network with a self-signed certificate: + +``` +[reporting] +datastore.type = opensearch +datastore.host = 192.168.10.22 +datastore.port = 9200 +datastore.secure = true +datastore.ssl.verification_mode = none +datastore.user = user-name +datastore.password = the-password-to-your-cluster +``` + + +## workloads + + +This section defines how workloads are retrieved. All keys are read by OpenSearch using the syntax `<>.url`, which you can select using the OpenSearch Benchmark CLI `--workload-repository=workload-repository-name"` option. By default, OpenSearch chooses the workload repository using the `default.url` `https://github.com/opensearch-project/opensearch-benchmark-workloads`. + + +## defaults + + +This section defines the default values of certain OpenSearch Benchmark CLI parameters. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `preserve_benchmark_candidate` | Boolean | Determines whether OpenSearch installations are preserved or wiped by default after a benchmark. To preserve an installation for a single benchmark, use the command line flag `--preserve-install`. Default is `false`. + + +## distributions + + +This section defines how OpenSearch versions are distributed. + +| Parameter | Type | Description | +| :---- | :---- | :---- | +| `release.cache` | Boolean | Determines whether newly released OpenSearch versions should be cached locally. | + +## Running OpenSearch Benchmark with AWS Signature Version 4 + +OpenSearch Benchmark supports AWS Signature Version 4 authentication. To run OpenSearch Benchmark with AWS Signature Version 4, you need to set up an [AWS Identity and Access Management (IAM) user or role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html) and provide it access to the OpenSearch cluster using AWS Signature Version 4 authentication. + +Whether to use an IAM role or user depends on your test cluster's access management requirements. For more information about whether to use an IAM role or user, see [When to create an IAM user (instead of a role)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html#id_which-to-choose). + +### OpenSearch Benchmark version 1.15.0 and later + +Starting with OpenSearch Benchmark version 1.15.0, you can use session-based authentication that automatically handles temporary credential generation and refresh. This method eliminates the need to manually export AWS credentials: + +1. Create an IAM role or user in the AWS Management Console that has the necessary permissions to access your OpenSearch cluster. Ensure that the role or user has the required policies attached for OpenSearch access. + +2. Run the following `execute-test` command with the `--client-options=amazon_aws_log_in:session` flag. OpenSearch Benchmark will automatically generate temporary credentials and handle auto-refresh: + + ```bash + opensearch-benchmark execute-test \ + --target-hosts= \ + --pipeline=benchmark-only \ + --workload=geonames \ + --client-options=timeout:120,amazon_aws_log_in:session,region:,service: + ``` + {% include copy.html %} + +### OpenSearch Benchmark version 1.14.0 and earlier + +For OpenSearch Benchmark versions prior to 1.15.0, use the environment variable method: + +1. Create an IAM role or user in the AWS Management Console. + +2. Set up your environment variables. If you're testing using Amazon OpenSearch Serverless, set `OSB_SERVICE` to `aoss`. + + - For an IAM user, configure the following environment variables: + + ```bash + export OSB_AWS_ACCESS_KEY_ID= + export OSB_AWS_SECRET_ACCESS_KEY= + export OSB_REGION= + export OSB_SERVICE=es + ``` + {% include copy.html %} + + - For an IAM role, configure the following environment variables: + + ```bash + export OSB_AWS_ACCESS_KEY_ID= + export OSB_AWS_SECRET_ACCESS_KEY= + export OSB_AWS_SESSION_TOKEN= + export OSB_REGION= + export OSB_SERVICE=es + ``` + {% include copy.html %} + + +3. Customize and run the following `run` command with the `--client-options=amazon_aws_log_in:environment` flag. This flag provides the location of your exported credentials to OpenSearch Benchmark. + + ```bash + opensearch-benchmark run \ + --target-hosts= \ + --pipeline=benchmark-only \ + --workload=geonames \ + --client-options=timeout:120,amazon_aws_log_in:environment + ``` + {% include copy.html %} + + +## Proxy configurations + +OpenSearch automatically downloads all the necessary proxy data for you, including: + +- OpenSearch distributions, when you specify `--distribution-version=`. +- OpenSearch source code, when you specify a Git revision number, for example, `--revision=1e04b2w`. +- Any metadata tracked from the [OpenSearch GitHub repository](https://github.com/opensearch-project/OpenSearch). + +As of OpenSearch Benchmark 0.5.0, only `http_proxy` is supported. +{: .warning} + +You can use an `http_proxy` to connect OpenSearch Benchmark to a specific proxy and connect the proxy to a benchmark workload. To add the proxy: + + +1. Add your proxy URL to your shell profile: + + ``` + export http_proxy=http://proxy.proxy.org:4444/ + ``` + +2. Source your shell profile and verify that the proxy URL is set correctly: + + ``` + source ~/.bash_profile ; echo $http_proxy + ``` + +3. Configure Git to connect to your proxy by using the following command. For more information, see the [Git documentation](https://git-scm.com/docs/git-config). + + ``` + git config --global http_proxy $http_proxy + ``` + +4. Use `git clone` to clone the workloads repository by using the following command. If the proxy configured correctly, the clone is successful. + + ``` + git clone http://github.com/opensearch-project/opensearch-benchmark-workloads.git + ``` + +5. Lastly, verify that OpenSearch Benchmark can connect to the proxy server by checking the `/.benchmark/logs/benchmark.log` log. When OpenSearch Benchmark starts, you should see the following at the top of the log: + + ``` + Connecting via proxy URL [http://proxy.proxy.org:4444/] to the Internet (picked up from the environment variable [http_proxy]). + ``` + +## Logging + +Logs from OpenSearch Benchmark can be configured in the `~/.benchmark/logging.json` file. For more information about how to format the log file, see the following Python documentation: + +- For general tips and tricks, use the [Python Logging Cookbook](https://docs.python.org/3/howto/logging-cookbook.html). +- For the file format, see the Python [logging configuration schema](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema). +- For instructions on how to customize where the log output is written, see the [logging handlers documentation](https://docs.python.org/3/library/logging.handlers.html). + +By default, OpenSearch Benchmark logs all output to `~/.benchmark/logs/benchmark.log`. + + + + + + + diff --git a/_benchmark/user-guide/install-and-configure/index.md b/_benchmark/user-guide/install-and-configure/index.md new file mode 100644 index 00000000..f8e11ac7 --- /dev/null +++ b/_benchmark/user-guide/install-and-configure/index.md @@ -0,0 +1,14 @@ +--- +layout: default +title: Install and configure OpenSearch Benchmark +nav_order: 5 +parent: User guide +has_children: true +redirect_from: + - /benchmark/user-guide/install-and-configure/ +--- + +# Installing and configuring OpenSearch Benchmark + +OpenSearch Benchmark can be installed using `pip`. After installation, you can configure connections to your OpenSearch cluster and customize benchmarking behavior. + diff --git a/_benchmark/user-guide/install-and-configure/installing-benchmark.md b/_benchmark/user-guide/install-and-configure/installing-benchmark.md new file mode 100644 index 00000000..a4efeb44 --- /dev/null +++ b/_benchmark/user-guide/install-and-configure/installing-benchmark.md @@ -0,0 +1,224 @@ +--- +layout: default +title: Installing +nav_order: 5 +grand_parent: User guide +parent: Install and configure OpenSearch Benchmark +redirect_from: + - /benchmark/installing-benchmark/ + - /benchmark/user-guide/installing-benchmark/ +--- + +# Installing OpenSearch Benchmark + +You can install OpenSearch Benchmark directly on a host running Linux or macOS, or you can run OpenSearch Benchmark in a Docker container on any compatible host. This page provides general considerations for your OpenSearch Benchmark host as well as instructions for installing OpenSearch Benchmark. + + +## Choosing appropriate hardware + +OpenSearch Benchmark can be used to provision OpenSearch nodes for testing. If you intend to use OpenSearch Benchmark to provision nodes in your environment, then install OpenSearch Benchmark directly on each host in the cluster. Additionally, you must configure each host in the cluster for OpenSearch. See [Installing OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/) for guidance on important host settings. + +Remember that OpenSearch Benchmark cannot be used to provision OpenSearch nodes when you run OpenSearch Benchmark in a Docker container. If you want to use OpenSearch Benchmark to provision nodes, or if you want to distribute the benchmark workload with the OpenSearch Benchmark daemon, then you must install OpenSearch Benchmark directly on each host using Python and pip. +{: .important} + +When you select a host, you should also think about which workloads you want to run. To see a list of default benchmark workloads, visit the [`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) repository on GitHub. As a general rule, make sure that the OpenSearch Benchmark host has enough free storage space to store the compressed data and the fully decompressed data corpus once OpenSearch Benchmark is installed. + +If you want to benchmark with a default workload, then use the following table to determine the approximate minimum amount of required free space needed by adding the compressed size with the uncompressed size. + +| Workload name | Document count | Compressed size | Uncompressed size | +| :----: | :----: | :----: | :----: | +| `eventdata` | 20,000,000 | 756.0 MB | 15.3 GB | +| `geonames` | 11,396,503 | 252.9 MB | 3.3 GB | +| `geopoint` | 60,844,404 | 482.1 MB | 2.3 GB | +| `geopointshape` | 60,844,404 | 470.8 MB | 2.6 GB | +| `geoshape` | 60,523,283 | 13.4 GB | 45.4 GB | +| `http_logs` | 247,249,096 | 1.2 GB | 31.1 GB | +| `nested` | 11,203,029 | 663.3 MB | 3.4 GB | +| `noaa` | 33,659,481 | 949.4 MB | 9.0 GB | +| `nyc_taxis` | 165,346,692 | 4.5 GB | 74.3 GB | +| `percolator` | 2,000,000 | 121.1 kB | 104.9 MB | +| `pmc` | 574,199 | 5.5 GB | 21.7 GB | +| `so` | 36,062,278 | 8.9 GB | 33.1 GB | + +Your OpenSearch Benchmark host should use solid-state drives (SSDs) for storage because they perform read and write operations significantly faster than traditional spinning-disk hard drives. Spinning-disk hard drives can introduce performance bottlenecks, which can make benchmark results unreliable and inconsistent. +{: .tip} + +## Installing on Linux and macOS + +If you want to run OpenSearch Benchmark in a Docker container, see [Installing with Docker](#installing-with-docker). The OpenSearch Benchmark Docker image includes all of the required software, so there are no additional steps required. +{: .important} + +To install OpenSearch Benchmark directly on a UNIX host, such as Linux or macOS, make sure you have **Python 3.8 or later** installed. + +If you need help installing Python, refer to the official [Python Setup and Usage](https://docs.python.org/3/using/index.html) documentation. + +### Checking software dependencies + +Before you begin installing OpenSearch Benchmark, check the following software dependencies. + +Use [`pyenv`](https://github.com/pyenv/pyenv) to manage multiple versions of Python on your host. This is especially useful if your "system" version of Python is earlier than version 3.8. +{: .tip} + +- Check that Python 3.8 or later is installed: + + ```bash + python3 --version + ``` + {% include copy.html %} + +- Check that `pip` is installed and functional: + + ```bash + pip --version + ``` + {% include copy.html %} + +- _Optional_: Check that your installed version of `git` is **Git 1.9 or later** using the following command. `git` is not required for OpenSearch Benchmark installation, but it is required in order to fetch benchmark workload resources from a repository when you want to perform tests. See the official Git [documentation](https://git-scm.com/doc) for help installing Git. + + ```bash + git --version + ``` + {% include copy.html %} + +### Completing the installation + +After the required software is installed, you can install OpenSearch Benchmark using the following command: + +```bash +pip install opensearch-benchmark +``` +{% include copy.html %} + +After the installation completes, you can use the following command to display help information: + +```bash +opensearch-benchmark -h +``` +{% include copy.html %} + + +Now that OpenSearch Benchmark is installed on your host, you can learn about [Configuring OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/). + +## Installing with Docker + +You can find the official Docker images for OpenSearch Benchmark on [Docker Hub](https://hub.docker.com/r/opensearchproject/opensearch-benchmark) or on the [Amazon ECR Public Gallery](https://gallery.ecr.aws/opensearchproject/opensearch-benchmark). + + +### Docker limitations + +Some OpenSearch Benchmark functionality is unavailable when you run OpenSearch Benchmark in a Docker container. Specifically, the following restrictions apply: + +- OpenSearch Benchmark cannot distribute load from multiple hosts, such as load worker coordinator hosts. +- OpenSearch Benchmark cannot provision OpenSearch nodes and can only run tests on previously existing clusters. You can only invoke OpenSearch Benchmark commands using the `benchmark-only` pipeline. + +### Pulling the Docker images + +To pull the image from Docker Hub, run the following command: + +```bash +docker pull opensearchproject/opensearch-benchmark:latest +``` +{% include copy.html %} + +To pull the image from Amazon Elastic Container Registry (Amazon ECR): + +```bash +docker pull public.ecr.aws/opensearchproject/opensearch-benchmark:latest +``` +{% include copy.html %} + +### Running OpenSearch Benchmark with Docker + +To run OpenSearch Benchmark, use `docker run` to launch a container. OpenSearch Benchmark subcommands are passed as arguments when you start the container. OpenSearch Benchmark then processes the command and stops the container after the requested operation completes. + +For example, the following command prints the help text for OpenSearch Benchmark to the command line and then stops the container: + +```bash +docker run opensearchproject/opensearch-benchmark -h +``` +{% include copy.html %} + +### Establishing volume persistence in a Docker container + +To ensure that your benchmark data and logs persist after your Docker container stops, you must mount a local directory as a volume when running OpenSearch Benchmark in Docker. + +Use the `-v` option to specify a local directory to mount and a directory in the container where the volume is attached. + +The following example mounts a volume from the user's home directory to the OpenSearch Benchmark container's default benchmark data path at `/opensearch-benchmark/.benchmark` and then runs a test benchmark using the `geonames` workload: + +```bash +docker run -v $HOME/benchmarks:/opensearch-benchmark/.benchmark opensearchproject/opensearch-benchmark run --target-hosts https://198.51.100.25:9200 --pipeline benchmark-only --workload geonames --client-options basic_auth_user:admin,basic_auth_password:admin,verify_certs:false --test-mode +``` +{% include copy.html %} + +By default, the OpenSearch Benchmark container runs as the `benchmark` user with a home directory of `/opensearch-benchmark`, so `$HOME/.benchmark` resolves to `/opensearch-benchmark/.benchmark`. +{: .note} + +#### Running OpenSearch Benchmark as the root user + +If you run the container as the `root` user, then the effective home directory becomes `/root`, and the benchmark path becomes `/root/.benchmark`. In this case, specify the volume mount accordingly: + +```bash +docker run -v $HOME/benchmarks:/root/.benchmark opensearchproject/opensearch-benchmark run --target-hosts https://198.51.100.25:9200 --pipeline benchmark-only --workload geonames --client-options basic_auth_user:admin,basic_auth_password:admin,verify_certs:false --test-mode +``` +{% include copy.html %} + +To learn more about the files and subdirectories located in `/opensearch-benchmark/.benchmark`, see [Configuring OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/). + +## Provisioning an OpenSearch cluster with a test + +OpenSearch Benchmark is compatible with JDK versions 17, 16, 15, 14, 13, 12, 11, and 8. +{: .note} + +If you installed OpenSearch with PyPi, you can also provision a new OpenSearch cluster by specifying a `distribution-version` in the `run` command. + +If you plan on having Benchmark provision a cluster, you'll need to inform Benchmark of the location of the `JAVA_HOME` path for the Benchmark cluster. To set the `JAVA_HOME` path and provision a cluster: + +1. Find the `JAVA_HOME` path you're currently using. Open a terminal and enter `/usr/libexec/java_home`. + +2. Set your corresponding JDK version environment variable by entering the path from the previous step. Enter `export JAVA17_HOME=`. + +3. Run the `run` command and indicate the distribution version of OpenSearch you want to use: + + ```bash + opensearch-benchmark run --distribution-version=2.3.0 --workload=geonames --test-mode + ``` + +## Directory structure + +After running OpenSearch Benchmark for the first time, you can search through all related files, including configuration files, in the `~/.benchmark` directory. The directory includes the following file tree: + +``` +# ~/.benchmark Tree +. +├── benchmark.ini +├── benchmarks +│ ├── data +│ │ └── geonames +│ ├── distributions +│ │ ├── opensearch-1.0.0-linux-x64.tar.gz +│ │ └── opensearch-2.3.0-linux-x64.tar.gz +│ ├── test-runs +│ │ ├── 0279b13b-1e54-49c7-b1a7-cde0b303a797 +│ │ └── 0279c542-a856-4e88-9cc8-04306378cd38 +│ └── workloads +│ └── default +│ └── geonames +├── logging.json +├── logs +│ └── benchmark.log +``` + +* `benchmark.ini`: Contains any adjustable configurations for tests. For information about how to configure OpenSearch Benchmark, see [Configuring OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/). +* `data`: Contains all the data corpora and documents related to OpenSearch Benchmark's [official workloads](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/geonames). +* `distributions`: Contains all the OpenSearch distributions downloaded from [OpenSearch.org](http://opensearch.org/) and used to provision clusters. +* `test-runs`: Contains every test `execution_id` from previous runs of OpenSearch Benchmark. +* `workloads`: Contains all files related to workloads, except for the data corpora. +* `logging.json`: Contains all of the configuration options related to how logging is performed within OpenSearch Benchmark. +* `logs`: Contains all the logs from OpenSearch Benchmark runs. This can be helpful when you've encountered errors during runs. + + +## Next steps + +- [Configuring OpenSearch Benchmark]({{site.url}}{{site.baseurl}}/benchmark/configuring-benchmark/) +- [Creating custom workloads]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/) diff --git a/_benchmark/version-history.md b/_benchmark/version-history.md new file mode 100644 index 00000000..9fe5310f --- /dev/null +++ b/_benchmark/version-history.md @@ -0,0 +1,27 @@ +--- +layout: default +title: Version history +nav_order: 105 +--- + +# OpenSearch Benchmark version history + +This page details high-level changes across OpenSearch Benchmark versions. + +## Updated terminology in OpenSearch Benchmark 2.0 + +OpenSearch Benchmark 2.0 introduces updated terminology to enhance the user experience and provide more intuitive benchmarking workflows. + +1.X term | 2.X term | +:--- | :--- | +execute-test, test-execution-id, TestExecution | run, test-run, TestRun | +results_publishing, results_publisher | reporting, publisher | +provision-configs, provision-config-instances | cluster-configs, cluster-config-instances +load-worker-coordinator-hosts | worker-ips | + +## Version history + +OpenSearch Benchmark version | Release highlights | Release date +:--- | :--- | :--- +[2.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.1.0.md) | Introduces new mechanisms to enhance user experience and intuitive benchmarking workflows. Adds new features such as synthetic data generation, data streaming, and visualizations. | 21 August 2025 +[1.15.0](https://github.com/opensearch-project/opensearch-benchmark/releases/tag/1.15.0) | Enables users to use session-based authentication that automatically handles temporary credential generation and refresh, which eliminates the need to manually export AWS credentials. Adds percent diff to compare command. Addresses bugs with execute-test | 7 August 2025 diff --git a/_benchmark/workload-types.md b/_benchmark/workload-types.md new file mode 100644 index 00000000..10fa03d1 --- /dev/null +++ b/_benchmark/workload-types.md @@ -0,0 +1,87 @@ +--- +layout: default +title: Workload types +nav_order: 20 +has_children: true +has_toc: false +--- + +# Workload types + +The [`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) repository contains prepackaged workloads that you can run against your cluster. This page describes the data, cluster requirements, and query types for each workload. To determine which one fits your cluster, see [Choosing a workload]({{site.url}}{{site.baseurl}}/benchmark/choosing-a-workload/). + +## General search use cases: `nyc_taxis` + +For benchmarking clusters built for general search use cases, start with the [nyc_taxis](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/nyc_taxis) workload. It contains the following: + +- **Data type**: Ride data from yellow taxis in New York City in 2015. +- **Cluster requirements**: Suitable for small- to medium-sized clusters. + +This workload tests the following queries and search functions: + +- Range queries +- Term queries on various fields +- Geodistance queries +- Aggregations + +## Vector data: `vectorsearch` + +The [`vectorsearch`](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/vectorsearch) workload is designed to benchmark vector search capabilities, including performance and accuracy. It contains the following: + +- **Data type**: High-dimensional vector data, often representing embeddings of text or images. +- **Cluster requirements**: Requires a cluster with [vector search capabilities]({{site.url}}{{site.baseurl}}/vector-search/) enabled. + +This workload tests the following queries and search functions: + +- k-NN vector searches +- Hybrid searches combining vector similarity with metadata filtering +- Indexing performance for high-dimensional vector data + +For the supported parameters, test procedures, and sample results, see [Vector search workload]({{site.url}}{{site.baseurl}}/benchmark/workloads/vectorsearch/). + +## Comprehensive search solutions: `big5` + +The [big5](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/big5) workload is a comprehensive benchmark suite for testing various aspects of search engine performance, including overall search engine performance across multiple use cases. It contains the following: + +- **Data type**: A mix of different data types, including text, numeric, and structured data. +- **Cluster requirements**: Suitable for medium to large clusters because it's designed to stress test various components. + +This workload tests the following queries and search functions: + +- Full-text search performance +- Aggregation performance +- Complex Boolean queries +- Sorting and pagination +- Indexing performance for various data types + +## Percolator queries: `percolator` + +The [percolator](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/percolator) workload is designed to test the performance of the `percolator` query type. It contains the following: + +- **Data type**: A set of stored queries and documents to be matched against those queries. +- **Cluster requirements**: Suitable for clusters that make heavy use of the [percolator]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/percolator/) feature. + +This workload tests the following queries and search functions: + +- Indexing performance for storing queries +- Matching performance for percolator queries +- Scalability with increasing numbers of stored queries + +## Log data: `http_logs` + +For benchmarking clusters built for indexing and search using log data, use the [http_logs](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/http_logs) workload. It contains the following: + +- **Data type**: HTTP access logs from the 1998 World Cup website. +- **Cluster requirements**: Suitable for clusters optimized for time-series data and log analytics. + +This workload tests the following queries and search functions: + +- Time range queries +- Term queries on fields like `status-code` or `user-agent` +- Aggregations for metrics like request count and average response size +- Cardinality aggregations on fields like `ip-address`. + +## Next steps + +- To compare these workloads against your cluster's use case, see [Choosing a workload]({{site.url}}{{site.baseurl}}/benchmark/choosing-a-workload/). +- To build a workload for data that no prepackaged workload matches, see [Creating custom workloads]({{site.url}}{{site.baseurl}}/benchmark/creating-custom-workloads/). diff --git a/_benchmark/workloads/vectorsearch.md b/_benchmark/workloads/vectorsearch.md new file mode 100644 index 00000000..40e3e4b9 --- /dev/null +++ b/_benchmark/workloads/vectorsearch.md @@ -0,0 +1,573 @@ +--- +layout: default +title: Vector search +parent: Workload types +nav_order: 10 +--- + +# Vector search workload + +The vector search workload benchmarks OpenSearch's vector engine capabilities for both indexing and search operations. It tests various vector search algorithms, quantization methods, and index configurations to measure performance metrics like throughput, latency, and recall accuracy. The workload supports different datasets and can evaluate both trained and untrained vector search methods. + +This workload supports datasets in either the `HDF5` or `BIG-ANN` formats. To download the datasets, use [this link](http://corpus-texmex.irisa.fr/). + +## Supported workload parameters + +The following workload parameters are supported by the vector search workload. + +| Name | Description | +| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `target_index_name` | The name of index to which to add vectors. | +| `target_field_name` | The name of the field to which to add vectors. Use "." to indicate a nested field. | +| `target_index_body` | The path to the target index definition. | +| `target_index_primary_shards` | The target index's primary shards. | +| `target_index_replica_shards` | The target index's replica shards. | +| `target_index_dimension` | The dimension of the target index. | +| `target_index_space_type` | The target index space type. | +| `target_index_bulk_size` | The target index bulk size. | +| `target_index_bulk_index_data_set_format` | The format of the vector dataset. | +| `target_index_bulk_index_data_set_path` | The path to the vector dataset in the index. | +| `target_index_bulk_index_data_set_corpus` | The corpus name of the vector dataset. | +| `target_index_bulk_index_clients` | The clients to be used for bulk ingestion. Must be a divisor of dataset size. | +| `target_index_max_num_segments` | The number of segments to merge into the target index before beginning to search. | +| `target_index_force_merge_timeout` | The amount of time (in seconds) to wait before force merging requests. | +| `hnsw_ef_search ` | THE `HNSW ef` search parameter. | +| `hnsw_ef_construction` | The `HNSW ef` construction parameter. | +| `id_field_name` | The name of the field that will be used to identify documents in an index. | +| `hnsw_m ` | The `HNSW m` parameter. | +| `query_k` | The number of neighbors to return for the search. Only one of `query_k`, `query_max_distance`, or `query_min_score` can be provided. | +| `query_max_distance ` | The maximum distance to be returned for the vector search. Only one of `query_k`, `query_max_distance`, or `query_min_score` can be provided. | +| `query_min_score` | The minimum score to be returned for the vector search. Only one of `query_k`, `query_max_distance`, or `query_min_score` can be provided. | +| `query_data_set_format` | The format of the vector dataset used for queries. Only one of `query_k`, `query_max_distance`, or `query_min_score` can be provided. | +| `query_data_set_path` | The path to the vector dataset used for queries. | +| `query_count` | The number of queries used for the search operation. | +| `query_body` | The JSON properties that will be merged with the search body. | +| `search_clients` | The number of clients used to run queries. | +| `repetitions` | The number of repetitions completed until the dataset is exhausted. Default is `1`. | +| `target_throughput` | The target throughput for each query operation, in requests per second. Default is `10`. | +| `time_period` | The period of time dedicated to running the benchmark test, in seconds. Default is `900`. | + + + +## Test procedures + +The vector search workload supports the following test procedures. + +### No-train test procedure + +The no-train test procedure tests vector search indexes that require no training. You can define the underlying configuration of the vector search algorithm (such as specifying a specific engine or space type) as method definitions. + +### No-train test (index only) procedure + +The no-train test (index only) procedure is used to index vector search indexes that require no training. This can be particularly useful when you want to benchmark only the indexing operation. + +### No-train test (Amazon OpenSearch Serverless) + +The no-train test procedure for Amazon OpenSearch Serverless is used specifically for OpenSearch Serverless vector search collections. This procedure doesn't include operations like **refresh** and **warmup** because they aren't supported by vector search collections. + +### Force merge index procedure + +The force merge index procedure optimizes vector search indexes by performing force merge operations up to a given maximum number of segments. For large datasets, force merging is a costly operation. Therefore, we recommend using a separate procedure to occasionally trigger force merge operations based on user requirements. + +### Train test procedure + +The train test procedure benchmarks approximate k-NN search algorithms that require a training step. For example, the Faiss Inverted File Indexing (IVF) technique requires a training step in order to retrieve cluster vectors. After the step is performed, the benchmark can search a smaller number of cluster centroids instead of the entire dataset. + +### Search procedure + +The search procedure benchmarks previously indexed vector search indexes. This can be useful when you want to benchmark large vector search indexes without reindexing each time because load time can be substantial for large datasets. This procedure includes warmup operations intended to avoid cold start problems during vector search. + +## Custom runners + +Only one custom runner, `warmup-knn-indices`, is supported by the vector search workload. This runner will warm up k-NN indexes and retry the warmup until it succeeds. + +## Running the workload + +To run the vector search workload, use the following command: + +```bash +export ENDPOINT= +export PARAMS_FILE= + +opensearch-benchmark run \ + --target-hosts $ENDPOINT \ + --workload vectorsearch \ + --workload-params ${PARAMS_FILE} \ + --pipeline benchmark-only \ + --kill-running-processes +``` +{% include copy.html %} + +## Sample results + +When using the vector search workload, you can expect results similar to the following. + +### Train test procedure + +The following example provides results from the train test procedure: + + +``` +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 0.00946667 | min | +| Min cumulative indexing time across primary shards | | 0 | min | +| Median cumulative indexing time across primary shards | | 0.00298333 | min | +| Max cumulative indexing time across primary shards | | 0.00336667 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 0 | min | +| Cumulative merge count of primary shards | | 0 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0 | min | +| Max cumulative merge time across primary shards | | 0 | min | +| Cumulative merge throttle time of primary shards | | 0 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0 | min | +| Cumulative refresh time of primary shards | | 0.00861667 | min | +| Cumulative refresh count of primary shards | | 33 | | +| Min cumulative refresh time across primary shards | | 0 | min | +| Median cumulative refresh time across primary shards | | 0.00268333 | min | +| Max cumulative refresh time across primary shards | | 0.00291667 | min | +| Cumulative flush time of primary shards | | 0.000183333 | min | +| Cumulative flush count of primary shards | | 2 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0 | min | +| Max cumulative flush time across primary shards | | 0.000183333 | min | +| Total Young Gen GC time | | 0.075 | s | +| Total Young Gen GC count | | 17 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 0.00869293 | GB | +| Translog size | | 2.56114e-07 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 9 | | +| Min Throughput | custom-vector-bulk | 25527 | docs/s | +| Mean Throughput | custom-vector-bulk | 25527 | docs/s | +| Median Throughput | custom-vector-bulk | 25527 | docs/s | +| Max Throughput | custom-vector-bulk | 25527 | docs/s | +| 50th percentile latency | custom-vector-bulk | 36.3095 | ms | +| 90th percentile latency | custom-vector-bulk | 52.2662 | ms | +| 100th percentile latency | custom-vector-bulk | 68.6513 | ms | +| 50th percentile service time | custom-vector-bulk | 36.3095 | ms | +| 90th percentile service time | custom-vector-bulk | 52.2662 | ms | +| 100th percentile service time | custom-vector-bulk | 68.6513 | ms | +| error rate | custom-vector-bulk | 0 | % | +| Min Throughput | prod-queries | 211.26 | ops/s | +| Mean Throughput | prod-queries | 213.85 | ops/s | +| Median Throughput | prod-queries | 213.48 | ops/s | +| Max Throughput | prod-queries | 216.49 | ops/s | +| 50th percentile latency | prod-queries | 3.43393 | ms | +| 90th percentile latency | prod-queries | 4.01881 | ms | +| 99th percentile latency | prod-queries | 5.56238 | ms | +| 99.9th percentile latency | prod-queries | 9.95666 | ms | +| 99.99th percentile latency | prod-queries | 39.7922 | ms | +| 100th percentile latency | prod-queries | 62.415 | ms | +| 50th percentile service time | prod-queries | 3.43405 | ms | +| 90th percentile service time | prod-queries | 4.0191 | ms | +| 99th percentile service time | prod-queries | 5.56316 | ms | +| 99.9th percentile service time | prod-queries | 9.95666 | ms | +| 99.99th percentile service time | prod-queries | 39.7922 | ms | +| 100th percentile service time | prod-queries | 62.415 | ms | +| error rate | prod-queries | 0 | % | + + +------------------------------------ +[INFO] ✅ SUCCESS (took 119 seconds) +------------------------------------ +``` + +### Faiss results + +The following sample outputs were generated using the Faiss IVF benchmarking procedure. For brevity, the test used 100 search queries instead of the 10,000 specified in the parameter files. All other parameters remain the same as those in the `params/train` folder. The first run demonstrates results without quantization, the second run demonstrates scalar quantization, and the third run demonstrates product quantization. Note that quantization may cause search recall to drop. + +#### Faiss IVF with no quantization/flat encoding + + +``` +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 11.7662 | min | +| Min cumulative indexing time across primary shards | | 0.000266667 | min | +| Median cumulative indexing time across primary shards | | 0.1423 | min | +| Max cumulative indexing time across primary shards | | 11.6236 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 1.09872 | min | +| Cumulative merge count of primary shards | | 21 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0.00045 | min | +| Max cumulative merge time across primary shards | | 1.09827 | min | +| Cumulative merge throttle time of primary shards | | 0.872417 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0.872417 | min | +| Cumulative refresh time of primary shards | | 0.113733 | min | +| Cumulative refresh count of primary shards | | 59 | | +| Min cumulative refresh time across primary shards | | 0.00235 | min | +| Median cumulative refresh time across primary shards | | 0.00516667 | min | +| Max cumulative refresh time across primary shards | | 0.106217 | min | +| Cumulative flush time of primary shards | | 0.01685 | min | +| Cumulative flush count of primary shards | | 8 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0.00791667 | min | +| Max cumulative flush time across primary shards | | 0.00893333 | min | +| Total Young Gen GC time | | 5.442 | s | +| Total Young Gen GC count | | 3739 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 1.3545 | GB | +| Translog size | | 0.0304573 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 14 | | +| Min Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| Mean Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| Median Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| Max Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| 50th percentile latency | custom-vector-bulk-train | 26.5199 | ms | +| 90th percentile latency | custom-vector-bulk-train | 34.9823 | ms | +| 99th percentile latency | custom-vector-bulk-train | 196.712 | ms | +| 100th percentile latency | custom-vector-bulk-train | 230.342 | ms | +| 50th percentile service time | custom-vector-bulk-train | 26.5158 | ms | +| 90th percentile service time | custom-vector-bulk-train | 34.9823 | ms | +| 99th percentile service time | custom-vector-bulk-train | 196.712 | ms | +| 100th percentile service time | custom-vector-bulk-train | 230.342 | ms | +| error rate | custom-vector-bulk-train | 0 | % | +| Min Throughput | delete-model | 10.58 | ops/s | +| Mean Throughput | delete-model | 10.58 | ops/s | +| Median Throughput | delete-model | 10.58 | ops/s | +| Max Throughput | delete-model | 10.58 | ops/s | +| 100th percentile latency | delete-model | 93.6958 | ms | +| 100th percentile service time | delete-model | 93.6958 | ms | +| error rate | delete-model | 0 | % | +| Min Throughput | train-knn-model | 0.63 | ops/s | +| Mean Throughput | train-knn-model | 0.63 | ops/s | +| Median Throughput | train-knn-model | 0.63 | ops/s | +| Max Throughput | train-knn-model | 0.63 | ops/s | +| 100th percentile latency | train-knn-model | 1577.49 | ms | +| 100th percentile service time | train-knn-model | 1577.49 | ms | +| error rate | train-knn-model | 0 | % | +| Min Throughput | custom-vector-bulk | 11055 | docs/s | +| Mean Throughput | custom-vector-bulk | 14163.8 | docs/s | +| Median Throughput | custom-vector-bulk | 12878.9 | docs/s | +| Max Throughput | custom-vector-bulk | 33841.3 | docs/s | +| 50th percentile latency | custom-vector-bulk | 81.6677 | ms | +| 90th percentile latency | custom-vector-bulk | 117.848 | ms | +| 99th percentile latency | custom-vector-bulk | 202.484 | ms | +| 99.9th percentile latency | custom-vector-bulk | 406.209 | ms | +| 99.99th percentile latency | custom-vector-bulk | 458.823 | ms | +| 100th percentile latency | custom-vector-bulk | 459.417 | ms | +| 50th percentile service time | custom-vector-bulk | 81.6621 | ms | +| 90th percentile service time | custom-vector-bulk | 117.843 | ms | +| 99th percentile service time | custom-vector-bulk | 202.294 | ms | +| 99.9th percentile service time | custom-vector-bulk | 406.209 | ms | +| 99.99th percentile service time | custom-vector-bulk | 458.823 | ms | +| 100th percentile service time | custom-vector-bulk | 459.417 | ms | +| error rate | custom-vector-bulk | 0 | % | +| Min Throughput | force-merge-segments | 0.1 | ops/s | +| Mean Throughput | force-merge-segments | 0.1 | ops/s | +| Median Throughput | force-merge-segments | 0.1 | ops/s | +| Max Throughput | force-merge-segments | 0.1 | ops/s | +| 100th percentile latency | force-merge-segments | 10017.4 | ms | +| 100th percentile service time | force-merge-segments | 10017.4 | ms | +| error rate | force-merge-segments | 0 | % | +| Min Throughput | warmup-indices | 9.63 | ops/s | +| Mean Throughput | warmup-indices | 9.63 | ops/s | +| Median Throughput | warmup-indices | 9.63 | ops/s | +| Max Throughput | warmup-indices | 9.63 | ops/s | +| 100th percentile latency | warmup-indices | 103.228 | ms | +| 100th percentile service time | warmup-indices | 103.228 | ms | +| error rate | warmup-indices | 0 | % | +| Min Throughput | prod-queries | 120.06 | ops/s | +| Mean Throughput | prod-queries | 120.06 | ops/s | +| Median Throughput | prod-queries | 120.06 | ops/s | +| Max Throughput | prod-queries | 120.06 | ops/s | +| 50th percentile latency | prod-queries | 1.75219 | ms | +| 90th percentile latency | prod-queries | 2.29527 | ms | +| 99th percentile latency | prod-queries | 50.4419 | ms | +| 100th percentile latency | prod-queries | 97.9905 | ms | +| 50th percentile service time | prod-queries | 1.75219 | ms | +| 90th percentile service time | prod-queries | 2.29527 | ms | +| 99th percentile service time | prod-queries | 50.4419 | ms | +| 100th percentile service time | prod-queries | 97.9905 | ms | +| error rate | prod-queries | 0 | % | +| Mean recall@k | prod-queries | 0.96 | | +| Mean recall@1 | prod-queries | 0.99 | | + + +------------------------------------ +[INFO] ✅ SUCCESS (took 218 seconds) +------------------------------------ +``` + +#### Faiss IVF with scalar quantization (100 search queries) + +``` +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 11.5 | min | +| Min cumulative indexing time across primary shards | | 0.000283333 | min | +| Median cumulative indexing time across primary shards | | 0.10915 | min | +| Max cumulative indexing time across primary shards | | 11.3905 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 1.03638 | min | +| Cumulative merge count of primary shards | | 22 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0.000266667 | min | +| Max cumulative merge time across primary shards | | 1.03612 | min | +| Cumulative merge throttle time of primary shards | | 0.798767 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0.798767 | min | +| Cumulative refresh time of primary shards | | 0.107117 | min | +| Cumulative refresh count of primary shards | | 61 | | +| Min cumulative refresh time across primary shards | | 0.00236667 | min | +| Median cumulative refresh time across primary shards | | 0.00543333 | min | +| Max cumulative refresh time across primary shards | | 0.0993167 | min | +| Cumulative flush time of primary shards | | 0.0193167 | min | +| Cumulative flush count of primary shards | | 9 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0.00871667 | min | +| Max cumulative flush time across primary shards | | 0.0106 | min | +| Total Young Gen GC time | | 5.267 | s | +| Total Young Gen GC count | | 3688 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 1.11609 | GB | +| Translog size | | 0.0304573 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 18 | | +| Min Throughput | custom-vector-bulk-train | 35950.5 | docs/s | +| Mean Throughput | custom-vector-bulk-train | 35950.5 | docs/s | +| Median Throughput | custom-vector-bulk-train | 35950.5 | docs/s | +| Max Throughput | custom-vector-bulk-train | 35950.5 | docs/s | +| 50th percentile latency | custom-vector-bulk-train | 22.8328 | ms | +| 90th percentile latency | custom-vector-bulk-train | 34.864 | ms | +| 99th percentile latency | custom-vector-bulk-train | 99.471 | ms | +| 100th percentile latency | custom-vector-bulk-train | 210.424 | ms | +| 50th percentile service time | custom-vector-bulk-train | 22.823 | ms | +| 90th percentile service time | custom-vector-bulk-train | 34.864 | ms | +| 99th percentile service time | custom-vector-bulk-train | 99.471 | ms | +| 100th percentile service time | custom-vector-bulk-train | 210.424 | ms | +| error rate | custom-vector-bulk-train | 0 | % | +| Min Throughput | delete-model | 8.39 | ops/s | +| Mean Throughput | delete-model | 8.39 | ops/s | +| Median Throughput | delete-model | 8.39 | ops/s | +| Max Throughput | delete-model | 8.39 | ops/s | +| 100th percentile latency | delete-model | 118.241 | ms | +| 100th percentile service time | delete-model | 118.241 | ms | +| error rate | delete-model | 0 | % | +| Min Throughput | train-knn-model | 0.64 | ops/s | +| Mean Throughput | train-knn-model | 0.64 | ops/s | +| Median Throughput | train-knn-model | 0.64 | ops/s | +| Max Throughput | train-knn-model | 0.64 | ops/s | +| 100th percentile latency | train-knn-model | 1564.44 | ms | +| 100th percentile service time | train-knn-model | 1564.44 | ms | +| error rate | train-knn-model | 0 | % | +| Min Throughput | custom-vector-bulk | 11313.1 | docs/s | +| Mean Throughput | custom-vector-bulk | 14065.7 | docs/s | +| Median Throughput | custom-vector-bulk | 12894.8 | docs/s | +| Max Throughput | custom-vector-bulk | 30050.8 | docs/s | +| 50th percentile latency | custom-vector-bulk | 81.4293 | ms | +| 90th percentile latency | custom-vector-bulk | 111.812 | ms | +| 99th percentile latency | custom-vector-bulk | 196.45 | ms | +| 99.9th percentile latency | custom-vector-bulk | 370.543 | ms | +| 99.99th percentile latency | custom-vector-bulk | 474.156 | ms | +| 100th percentile latency | custom-vector-bulk | 499.048 | ms | +| 50th percentile service time | custom-vector-bulk | 81.4235 | ms | +| 90th percentile service time | custom-vector-bulk | 111.833 | ms | +| 99th percentile service time | custom-vector-bulk | 197.125 | ms | +| 99.9th percentile service time | custom-vector-bulk | 370.543 | ms | +| 99.99th percentile service time | custom-vector-bulk | 474.156 | ms | +| 100th percentile service time | custom-vector-bulk | 499.048 | ms | +| error rate | custom-vector-bulk | 0 | % | +| Min Throughput | force-merge-segments | 0.1 | ops/s | +| Mean Throughput | force-merge-segments | 0.1 | ops/s | +| Median Throughput | force-merge-segments | 0.1 | ops/s | +| Max Throughput | force-merge-segments | 0.1 | ops/s | +| 100th percentile latency | force-merge-segments | 10015.2 | ms | +| 100th percentile service time | force-merge-segments | 10015.2 | ms | +| error rate | force-merge-segments | 0 | % | +| Min Throughput | warmup-indices | 19 | ops/s | +| Mean Throughput | warmup-indices | 19 | ops/s | +| Median Throughput | warmup-indices | 19 | ops/s | +| Max Throughput | warmup-indices | 19 | ops/s | +| 100th percentile latency | warmup-indices | 52.1685 | ms | +| 100th percentile service time | warmup-indices | 52.1685 | ms | +| error rate | warmup-indices | 0 | % | +| Min Throughput | prod-queries | 159.49 | ops/s | +| Mean Throughput | prod-queries | 159.49 | ops/s | +| Median Throughput | prod-queries | 159.49 | ops/s | +| Max Throughput | prod-queries | 159.49 | ops/s | +| 50th percentile latency | prod-queries | 1.92377 | ms | +| 90th percentile latency | prod-queries | 2.63867 | ms | +| 99th percentile latency | prod-queries | 48.513 | ms | +| 100th percentile latency | prod-queries | 90.543 | ms | +| 50th percentile service time | prod-queries | 1.92377 | ms | +| 90th percentile service time | prod-queries | 2.63867 | ms | +| 99th percentile service time | prod-queries | 48.513 | ms | +| 100th percentile service time | prod-queries | 90.543 | ms | +| error rate | prod-queries | 0 | % | +| Mean recall@k | prod-queries | 0.96 | | +| Mean recall@1 | prod-queries | 0.98 | | + + +------------------------------------ +[INFO] ✅ SUCCESS (took 218 seconds) +------------------------------------ +``` + +#### Faiss IVF with product quantization (100 search queries) + +``` +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 11.3862 | min | +| Min cumulative indexing time across primary shards | | 0.0003 | min | +| Median cumulative indexing time across primary shards | | 0.12735 | min | +| Max cumulative indexing time across primary shards | | 11.2586 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 1.50842 | min | +| Cumulative merge count of primary shards | | 19 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0.000233333 | min | +| Max cumulative merge time across primary shards | | 1.50818 | min | +| Cumulative merge throttle time of primary shards | | 0.58095 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0.58095 | min | +| Cumulative refresh time of primary shards | | 0.2059 | min | +| Cumulative refresh count of primary shards | | 61 | | +| Min cumulative refresh time across primary shards | | 0.00238333 | min | +| Median cumulative refresh time across primary shards | | 0.00526667 | min | +| Max cumulative refresh time across primary shards | | 0.19825 | min | +| Cumulative flush time of primary shards | | 0.0254667 | min | +| Cumulative flush count of primary shards | | 10 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0.0118333 | min | +| Max cumulative flush time across primary shards | | 0.0136333 | min | +| Total Young Gen GC time | | 6.477 | s | +| Total Young Gen GC count | | 3565 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 0.892541 | GB | +| Translog size | | 0.0304573 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 21 | | +| Min Throughput | custom-vector-bulk-train | 31931 | docs/s | +| Mean Throughput | custom-vector-bulk-train | 31931 | docs/s | +| Median Throughput | custom-vector-bulk-train | 31931 | docs/s | +| Max Throughput | custom-vector-bulk-train | 31931 | docs/s | +| 50th percentile latency | custom-vector-bulk-train | 25.3297 | ms | +| 90th percentile latency | custom-vector-bulk-train | 35.3864 | ms | +| 99th percentile latency | custom-vector-bulk-train | 144.372 | ms | +| 100th percentile latency | custom-vector-bulk-train | 209.37 | ms | +| 50th percentile service time | custom-vector-bulk-train | 25.3226 | ms | +| 90th percentile service time | custom-vector-bulk-train | 35.3864 | ms | +| 99th percentile service time | custom-vector-bulk-train | 144.372 | ms | +| 100th percentile service time | custom-vector-bulk-train | 209.37 | ms | +| error rate | custom-vector-bulk-train | 0 | % | +| Min Throughput | delete-model | 8.65 | ops/s | +| Mean Throughput | delete-model | 8.65 | ops/s | +| Median Throughput | delete-model | 8.65 | ops/s | +| Max Throughput | delete-model | 8.65 | ops/s | +| 100th percentile latency | delete-model | 114.725 | ms | +| 100th percentile service time | delete-model | 114.725 | ms | +| error rate | delete-model | 0 | % | +| Min Throughput | train-knn-model | 0.03 | ops/s | +| Mean Throughput | train-knn-model | 0.03 | ops/s | +| Median Throughput | train-knn-model | 0.03 | ops/s | +| Max Throughput | train-knn-model | 0.03 | ops/s | +| 100th percentile latency | train-knn-model | 37222.2 | ms | +| 100th percentile service time | train-knn-model | 37222.2 | ms | +| error rate | train-knn-model | 0 | % | +| Min Throughput | custom-vector-bulk | 10669.3 | docs/s | +| Mean Throughput | custom-vector-bulk | 14468.6 | docs/s | +| Median Throughput | custom-vector-bulk | 12496.1 | docs/s | +| Max Throughput | custom-vector-bulk | 35027.8 | docs/s | +| 50th percentile latency | custom-vector-bulk | 74.2584 | ms | +| 90th percentile latency | custom-vector-bulk | 113.426 | ms | +| 99th percentile latency | custom-vector-bulk | 293.075 | ms | +| 99.9th percentile latency | custom-vector-bulk | 1774.41 | ms | +| 99.99th percentile latency | custom-vector-bulk | 1969.99 | ms | +| 100th percentile latency | custom-vector-bulk | 1971.29 | ms | +| 50th percentile service time | custom-vector-bulk | 74.2577 | ms | +| 90th percentile service time | custom-vector-bulk | 113.477 | ms | +| 99th percentile service time | custom-vector-bulk | 292.481 | ms | +| 99.9th percentile service time | custom-vector-bulk | 1774.41 | ms | +| 99.99th percentile service time | custom-vector-bulk | 1969.99 | ms | +| 100th percentile service time | custom-vector-bulk | 1971.29 | ms | +| error rate | custom-vector-bulk | 0 | % | +| Min Throughput | force-merge-segments | 0.05 | ops/s | +| Mean Throughput | force-merge-segments | 0.05 | ops/s | +| Median Throughput | force-merge-segments | 0.05 | ops/s | +| Max Throughput | force-merge-segments | 0.05 | ops/s | +| 100th percentile latency | force-merge-segments | 20015.2 | ms | +| 100th percentile service time | force-merge-segments | 20015.2 | ms | +| error rate | force-merge-segments | 0 | % | +| Min Throughput | warmup-indices | 47.06 | ops/s | +| Mean Throughput | warmup-indices | 47.06 | ops/s | +| Median Throughput | warmup-indices | 47.06 | ops/s | +| Max Throughput | warmup-indices | 47.06 | ops/s | +| 100th percentile latency | warmup-indices | 20.6798 | ms | +| 100th percentile service time | warmup-indices | 20.6798 | ms | +| error rate | warmup-indices | 0 | % | +| Min Throughput | prod-queries | 87.76 | ops/s | +| Mean Throughput | prod-queries | 87.76 | ops/s | +| Median Throughput | prod-queries | 87.76 | ops/s | +| Max Throughput | prod-queries | 87.76 | ops/s | +| 50th percentile latency | prod-queries | 1.81677 | ms | +| 90th percentile latency | prod-queries | 2.80454 | ms | +| 99th percentile latency | prod-queries | 51.2039 | ms | +| 100th percentile latency | prod-queries | 98.2032 | ms | +| 50th percentile service time | prod-queries | 1.81677 | ms | +| 90th percentile service time | prod-queries | 2.80454 | ms | +| 99th percentile service time | prod-queries | 51.2039 | ms | +| 100th percentile service time | prod-queries | 98.2032 | ms | +| error rate | prod-queries | 0 | % | +| Mean recall@k | prod-queries | 0.62 | | +| Mean recall@1 | prod-queries | 0.52 | | + +------------------------------------ +[INFO] ✅ SUCCESS (took 413 seconds) +------------------------------------ +``` diff --git a/_clients/OSC-dot-net.md b/_clients/OSC-dot-net.md index 9af9d428..595e4a25 100644 --- a/_clients/OSC-dot-net.md +++ b/_clients/OSC-dot-net.md @@ -11,42 +11,58 @@ parent: .NET clients OpenSearch.Client is a high-level .NET client. It provides strongly typed requests and responses as well as Query DSL. It frees you from constructing raw JSON requests and parsing raw JSON responses by providing models that parse and serialize/deserialize requests and responses automatically. OpenSearch.Client also exposes the OpenSearch.Net low-level client if you need it. For the client's complete API documentation, see the [OpenSearch.Client API documentation](https://opensearch-project.github.io/opensearch-net/api/OpenSearch.Client.html). -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-net repo](https://github.com/opensearch-project/opensearch-net). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-net` repo](https://github.com/opensearch-project/opensearch-net). ## Installing OpenSearch.Client -To install OpenSearch.Client, download the [OpenSearch.Client NuGet package](https://www.nuget.org/packages/OpenSearch.Client/) and add it to your project in an IDE of your choice. In Microsoft Visual Studio, follow the steps below: +To install OpenSearch.Client, download the [OpenSearch.Client NuGet package](https://www.nuget.org/packages/OpenSearch.Client/) and add it to your project in an IDE of your choice. In Microsoft Visual Studio, follow the following steps: - In the **Solution Explorer** panel, right-click on your solution or project and select **Manage NuGet Packages for Solution**. - Search for the OpenSearch.Client NuGet package, and select **Install**. -Alternatively, you can add OpenSearch.Client to your .csproj file: +Alternatively, add OpenSearch.Client to your project using the .NET CLI: + +```bash +dotnet add package OpenSearch.Client --version 2.2.0 +``` +{% include copy.html %} + +You can also add OpenSearch.Client to your .csproj file: + ```xml ... - + ``` {% include copy.html %} -## Example +OpenSearch.Client depends on OpenSearch.Net, so installing OpenSearch.Client also installs the low-level client. For information about supported OpenSearch versions and target frameworks, see [Compatibility]({{site.url}}{{site.baseurl}}/clients/dot-net/#compatibility). -The following example illustrates connecting to OpenSearch, indexing documents, and sending queries on the data. It uses the Student class to represent one student, which is equivalent to one document in the index. +## Sample data + +The examples on this page use the following `Student` class to represent one student, which is equivalent to one document in the index. The `ToString` method formats a `Student` for console output: ```cs +using System.Globalization; + public class Student { - public int Id { get; init; } - public string FirstName { get; init; } - public string LastName { get; init; } - public int GradYear { get; init; } - public double Gpa { get; init; } + public string FirstName { get; set; } = string.Empty; + public string LastName { get; set; } = string.Empty; + public double Gpa { get; set; } + public string GradDate { get; set; } = string.Empty; + + public override string ToString() => + string.Format(CultureInfo.InvariantCulture, + "{% raw %}Student{{firstName='{0}', lastName='{1}', gpa={2}, gradDate={3}}}{% endraw %}", + FirstName, LastName, Gpa, GradDate); } ``` {% include copy.html %} -By default, OpenSearch.Client uses camel case to convert property names to field names. +By default, OpenSearch.Client uses camel case to convert property names to field names, so a `Student` is indexed as a document containing the `firstName`, `lastName`, `gpa`, and `gradDate` fields. {: .note} ## Connecting to OpenSearch @@ -82,9 +98,10 @@ var client = new OpenSearchClient(settings); ``` {% include copy.html %} -## Using ConnectionSettings +### Using ConnectionSettings + +`ConnectionConfiguration` is used to pass configuration options to the low-level OpenSearch.Net client. `ConnectionSettings` inherits from `ConnectionConfiguration` and provides additional configuration options for the high-level client, such as a default index name for requests and the mapping of property names to field names. `ConnectionSettings` is part of the OpenSearch.Client package. -`ConnectionConfiguration` is used to pass configuration options to the low-level OpenSearch.Net client. `ConnectionSettings` inherits from `ConnectionConfiguration` and provides additional configuration options. To set the address of the node and the default index name for requests that don't specify the index name, create a `ConnectionSettings` object: ```cs @@ -94,70 +111,105 @@ var client = new OpenSearchClient(config); ``` {% include copy.html %} +## Creating an index + +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: + +```cs +var index = "students"; +var createIndexResponse = client.Indices.Create(index, c => c + .Settings(s => s + .NumberOfShards(1) + .NumberOfReplicas(1)) + .Map(m => m + .Properties(p => p + .Date(d => d.Name(f => f.GradDate).Format("yyyy-MM-dd"))))); +``` +{% include copy.html %} + ## Indexing one document -Create one instance of Student: +Create one instance of `Student`: ```cs -var student = new Student { Id = 100, FirstName = "Paulo", LastName = "Santos", Gpa = 3.93, GradYear = 2021 }; +var student = new Student { FirstName = "John", LastName = "Doe", Gpa = 3.89, GradDate = "2022-05-15" }; ``` {% include copy.html %} -To index one document, you can use either fluent lambda syntax or object initializer syntax. +To index one document, you can use either fluent lambda syntax or object initializer syntax. The following examples set `Refresh` to `Refresh.True` so that the document is immediately available for search. -Index this Student into the `students` index using fluent lambda syntax: +Index this `Student` into the `students` index with the ID `1` using fluent lambda syntax: ```cs -var response = client.Index(student, i => i.Index("students")); +var indexResponse = client.Index(student, i => i + .Index(index) + .Id("1") + .Refresh(Refresh.True)); ``` {% include copy.html %} -Index this Student into the `students` index using object initializer syntax: +Index this `Student` into the `students` index with the ID `1` using object initializer syntax: ```cs -var response = client.Index(new IndexRequest(student, "students")); +var indexResponse = client.Index(new IndexRequest(student, index, "1") +{ + Refresh = Refresh.True +}); ``` {% include copy.html %} ## Indexing many documents -You can index many documents from a collection at the same time by using the OpenSearch.Client's `IndexMany` method: +Index multiple documents in a single request using the Bulk API: ```cs -var studentArray = new Student[] -{ - new() {Id = 200, FirstName = "Shirley", LastName = "Rodriguez", Gpa = 3.91, GradYear = 2019}, - new() {Id = 300, FirstName = "Nikki", LastName = "Wolf", Gpa = 3.87, GradYear = 2020} -}; - -var manyResponse = client.IndexMany(studentArray, "students"); +var bulkResponse = client.Bulk(b => b + .Index(index) + .Refresh(Refresh.True) + .Index(op => op + .Id("2") + .Document(new Student { FirstName = "Paulo", LastName = "Santos", Gpa = 3.93, GradDate = "2021-05-20" })) + .Index(op => op + .Id("3") + .Document(new Student { FirstName = "Shirley", LastName = "Rodriguez", Gpa = 3.91, GradDate = "2019-05-10" }))); ``` {% include copy.html %} -## Searching for a document +## Searching for documents -To search for a student indexed above, you want to construct a query that is analogous to the following Query DSL query: +Search for all documents in an index using the following code: -```json -GET students/_search +```cs +var searchResponse = client.Search(s => s + .Index(index) + .Query(q => q.MatchAll())); +foreach (var doc in searchResponse.Documents) { - "query" : { - "match": { - "lastName": "Santos" - } - } + Console.WriteLine(doc); } ``` +{% include copy.html %} -The query above is a shorthand version of the following explicit query: +Each item in `searchResponse.Documents` is a `Student` object, and its fields are available as properties. To also get the ID of each document, iterate over `searchResponse.Hits`. Each hit contains the document ID in the `Id` property and the `Student` object in the `Source` property: + +```cs +foreach (var hit in searchResponse.Hits) +{ + Console.WriteLine($"ID: {hit.Id}, name: {hit.Source.FirstName} {hit.Source.LastName}, GPA: {hit.Source.Gpa}, graduation date: {hit.Source.GradDate}"); +} +``` +{% include copy.html %} + +To search for students who graduated in 2019, use a range query. The following Query DSL range query searches for documents whose `gradDate` falls within 2019: ```json GET students/_search { - "query" : { - "match": { - "lastName": { - "query": "Santos" + "query": { + "range": { + "gradDate": { + "gte": "2019-01-01", + "lte": "2019-12-31" } } } @@ -168,30 +220,80 @@ In OpenSearch.Client, this query looks like this: ```cs var searchResponse = client.Search(s => s - .Index("students") - .Query(q => q - .Match(m => m - .Field(fld => fld.LastName) - .Query("Santos")))); -``` -{% include copy.html %} - -You can print out the results by accessing the documents in the response: - -```cs -if (searchResponse.IsValid) -{ - foreach (var s in searchResponse.Documents) - { - Console.WriteLine($"{s.Id} {s.LastName} {s.FirstName} {s.Gpa} {s.GradYear}"); - } -} + .Index(index) + .Query(q => q + .DateRange(r => r + .Field(f => f.GradDate) + .GreaterThanOrEquals("2019-01-01") + .LessThanOrEquals("2019-12-31")))); ``` {% include copy.html %} The response contains one document, which corresponds to the correct student: -`100 Santos Paulo 3.93 2021` +```text +Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} +``` + +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```cs +var firstPageResponse = client.Search(s => s + .Index(index) + .Sort(so => so.Ascending(f => f.GradDate)) + .From(0) + .Size(2)); +foreach (var doc in firstPageResponse.Documents) +{ + Console.WriteLine(doc); +} + +var nextPageResponse = client.Search(s => s + .Index(index) + .Sort(so => so.Ascending(f => f.GradDate)) + .From(2) + .Size(2)); +foreach (var doc in nextPageResponse.Documents) +{ + Console.WriteLine(doc); +} +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +## Updating a document + +Update a document using a partial document. Only the fields in the partial document are updated: + +```cs +var updateResponse = client.Update("1", u => u + .Index(index) + .Doc(new { gpa = 3.92 })); +``` +{% include copy.html %} + +## Deleting a document + +Delete a document using the following code: + +```cs +var deleteResponse = client.Delete("3", d => d + .Index(index) + .Refresh(Refresh.True)); +``` +{% include copy.html %} + +## Deleting an index + +Delete an index using the following code: + +```cs +var deleteIndexResponse = client.Indices.Delete(index); +``` +{% include copy.html %} ## Using OpenSearch.Client methods asynchronously @@ -199,30 +301,32 @@ For applications that require asynchronous code, all method calls in OpenSearch. ```cs // synchronous method -var response = client.Index(student, i => i.Index("students")); +var response = client.Index(student, i => i.Index(index).Id("1")); // asynchronous method -var response = await client.IndexAsync(student, i => i.Index("students")); +var asyncResponse = await client.IndexAsync(student, i => i.Index(index).Id("1")); ``` +{% include copy.html %} ## Falling back on the low-level OpenSearch.Net client -OpenSearch.Client exposes the low-level the OpenSearch.Net client you can use if anything is missing: +OpenSearch.Client exposes the low-level OpenSearch.Net client through the `LowLevel` property. Use the low-level client to call an API for which OpenSearch.Client does not provide a method or to construct the request body yourself instead of using the OpenSearch.Client query methods. The following example sends a range query as an anonymous object and deserializes the response into a `SearchResponse`: ```cs var lowLevelClient = client.LowLevel; -var searchResponseLow = lowLevelClient.Search>("students", +var searchResponseLow = lowLevelClient.Search>(index, PostData.Serializable( new { query = new { - match = new + range = new { - lastName = new + gradDate = new { - query = "Santos" + gte = "2019-01-01", + lte = "2019-12-31" } } } @@ -230,9 +334,9 @@ var searchResponseLow = lowLevelClient.Search>("students if (searchResponseLow.IsValid) { - foreach (var s in searchResponseLow.Documents) + foreach (var doc in searchResponseLow.Documents) { - Console.WriteLine($"{s.Id} {s.LastName} {s.FirstName} {s.Gpa} {s.GradYear}"); + Console.WriteLine(doc); } } ``` @@ -240,7 +344,12 @@ if (searchResponseLow.IsValid) ## Sample program -The following is a complete sample program that illustrates all of the concepts described above. It uses the Student class defined above. +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. Before running the sample program, make sure that you have the `Student` class defined in your project. + +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```cs using OpenSearch.Client; @@ -250,108 +359,157 @@ namespace NetClientProgram; internal class Program { - private static IOpenSearchClient osClient = new OpenSearchClient(); - public static void Main(string[] args) - { - Console.WriteLine("Indexing one student......"); - var student = new Student { Id = 100, - FirstName = "Paulo", - LastName = "Santos", - Gpa = 3.93, - GradYear = 2021 }; - var response = osClient.Index(student, i => i.Index("students")); - Console.WriteLine(response.IsValid ? "Response received" : "Error"); + { + var settings = new ConnectionSettings(new Uri("https://localhost:9200")); // Without security, use http://localhost:9200 + settings.BasicAuthentication("admin", ""); // Without security, remove this line + settings.ServerCertificateValidationCallback(CertificateValidations.AllowAll); // Without security, remove this line + var client = new OpenSearchClient(settings); - Console.WriteLine("Searching for one student......"); - SearchForOneStudent(); + // Create the index + var index = "students"; + Console.WriteLine("Creating index......"); + var createIndexResponse = client.Indices.Create(index, c => c + .Settings(s => s + .NumberOfShards(1) + .NumberOfReplicas(1)) + .Map(m => m + .Properties(p => p + .Date(d => d.Name(f => f.GradDate).Format("yyyy-MM-dd"))))); + Console.WriteLine("Index created: " + createIndexResponse.Index); - Console.WriteLine("Searching using low-level client......"); - SearchLowLevel(); + // Index a document + Console.WriteLine("\nIndexing one student......"); + var student = new Student { FirstName = "John", LastName = "Doe", Gpa = 3.89, GradDate = "2022-05-15" }; + var indexResponse = client.Index(student, i => i + .Index(index) + .Id("1") + .Refresh(Refresh.True)); + Console.WriteLine($"Result: {indexResponse.Result.ToString().ToLowerInvariant()}, id: {indexResponse.Id}, version: {indexResponse.Version}"); - Console.WriteLine("Indexing an array of Student objects......"); - var studentArray = new Student[] + // Bulk index documents + Console.WriteLine("\nIndexing many students......"); + var bulkResponse = client.Bulk(b => b + .Index(index) + .Refresh(Refresh.True) + .Index(op => op + .Id("2") + .Document(new Student { FirstName = "Paulo", LastName = "Santos", Gpa = 3.93, GradDate = "2021-05-20" })) + .Index(op => op + .Id("3") + .Document(new Student { FirstName = "Shirley", LastName = "Rodriguez", Gpa = 3.91, GradDate = "2019-05-10" }))); + Console.WriteLine("Errors: " + bulkResponse.Errors.ToString().ToLowerInvariant()); + foreach (var item in bulkResponse.Items) { - new() { Id = 200, - FirstName = "Shirley", - LastName = "Rodriguez", - Gpa = 3.91, - GradYear = 2019}, - new() { Id = 300, - FirstName = "Nikki", - LastName = "Wolf", - Gpa = 3.87, - GradYear = 2020} - }; - var manyResponse = osClient.IndexMany(studentArray, "students"); - Console.WriteLine(manyResponse.IsValid ? "Response received" : "Error"); - } - - private static void SearchForOneStudent() - { - var searchResponse = osClient.Search(s => s - .Index("students") - .Query(q => q - .Match(m => m - .Field(fld => fld.LastName) - .Query("Santos")))); - - PrintResponse(searchResponse); - } - - private static void SearchForAllStudentsWithANonEmptyLastName() - { - var searchResponse = osClient.Search(s => s - .Index("students") - .Query(q => q - .Bool(b => b - .Must(m => m.Exists(fld => fld.LastName)) - .MustNot(m => m.Term(t => t.Verbatim().Field(fld => fld.LastName).Value(string.Empty))) - ))); - - PrintResponse(searchResponse); - } - - private static void SearchLowLevel() - { - // Search for the student using the low-level client - var lowLevelClient = osClient.LowLevel; - - var searchResponseLow = lowLevelClient.Search> - ("students", - PostData.Serializable( - new - { - query = new - { - match = new - { - lastName = new - { - query = "Santos" - } - } - } - })); - - PrintResponse(searchResponseLow); - } - - private static void PrintResponse(ISearchResponse response) - { - if (response.IsValid) - { - foreach (var s in response.Documents) - { - Console.WriteLine($"{s.Id} {s.LastName} " + - $"{s.FirstName} {s.Gpa} {s.GradYear}"); - } + Console.WriteLine($" {item.Result} id: {item.Id}"); } - else + + // Search for all students + Console.WriteLine("\nSearching for all students......"); + var searchResponse = client.Search(s => s + .Index(index) + .Sort(so => so.Ascending(f => f.GradDate)) + .From(0) + .Size(2)); + Console.WriteLine("Total hits: " + searchResponse.Total); + Console.WriteLine("Page 1:"); + foreach (var doc in searchResponse.Documents) { - Console.WriteLine("Student not found."); + Console.WriteLine(" " + doc); } + + var nextPageResponse = client.Search(s => s + .Index(index) + .Sort(so => so.Ascending(f => f.GradDate)) + .From(2) + .Size(2)); + Console.WriteLine("Page 2:"); + foreach (var doc in nextPageResponse.Documents) + { + Console.WriteLine(" " + doc); + } + + // Search for students who graduated in 2019 + Console.WriteLine("\nSearching for students who graduated in 2019......"); + var searchResponse2 = client.Search(s => s + .Index(index) + .Query(q => q + .DateRange(r => r + .Field(f => f.GradDate) + .GreaterThanOrEquals("2019-01-01") + .LessThanOrEquals("2019-12-31")))); + Console.WriteLine("Total hits: " + searchResponse2.Total); + foreach (var doc in searchResponse2.Documents) + { + Console.WriteLine(" " + doc); + } + + // Update a document + Console.WriteLine("\nUpdating a student's GPA......"); + var updateResponse = client.Update("1", u => u + .Index(index) + .Doc(new { gpa = 3.92 })); + Console.WriteLine($"Result: {updateResponse.Result.ToString().ToLowerInvariant()}, version: {updateResponse.Version}"); + + // Get the updated document + var getResponse = client.Get("1", g => g.Index(index)); + Console.WriteLine("Updated document: " + getResponse.Source); + + // Delete a document + Console.WriteLine("\nDeleting a student......"); + var deleteResponse = client.Delete("3", d => d + .Index(index) + .Refresh(Refresh.True)); + Console.WriteLine("Result: " + deleteResponse.Result.ToString().ToLowerInvariant()); + + // Delete the index + Console.WriteLine("\nDeleting the index......"); + var deleteIndexResponse = client.Indices.Delete(index); + Console.WriteLine("Acknowledged: " + deleteIndexResponse.Acknowledged.ToString().ToLowerInvariant()); } } ``` {% include copy.html %} + +The sample program produces the following output: + +```text +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} + Student{firstName='Paulo', lastName='Santos', gpa=3.93, gradDate=2021-05-20} +Page 2: + Student{firstName='John', lastName='Doe', gpa=3.89, gradDate=2022-05-15} + +Searching for students who graduated in 2019...... +Total hits: 1 + Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: Student{firstName='John', lastName='Doe', gpa=3.92, gradDate=2022-05-15} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- For more examples of using the client, see the [`opensearch-net` user guide](https://github.com/opensearch-project/opensearch-net/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-net` guides](https://github.com/opensearch-project/opensearch-net/tree/main/guides). +- For complete sample applications, see the [`opensearch-net` samples](https://github.com/opensearch-project/opensearch-net/tree/main/samples). diff --git a/_clients/OSC-example.md b/_clients/OSC-example.md index 4511e2b4..3ed2002a 100644 --- a/_clients/OSC-example.md +++ b/_clients/OSC-example.md @@ -8,16 +8,22 @@ parent: .NET clients # More advanced features of the high-level .NET client (OpenSearch.Client) -The following example illustrates more advanced features of OpenSearch.Client. For a simple example, see the [Getting started guide]({{site.url}}{{site.baseurl}}/clients/OSC-dot-net/). This example uses the following Student class. +The following example illustrates more advanced features of OpenSearch.Client. For a simple example, see the [Getting started guide]({{site.url}}{{site.baseurl}}/clients/OSC-dot-net/). This example uses the following `Student` class, which is the same class used in the [Getting started guide]({{site.url}}{{site.baseurl}}/clients/OSC-dot-net/). OpenSearch.Client converts its property names to the `firstName`, `lastName`, `gpa`, and `gradDate` field names. The `ToString` method formats a `Student` for console output: ```cs +using System.Globalization; + public class Student { - public int Id { get; init; } - public string FirstName { get; init; } - public string LastName { get; init; } - public int GradYear { get; init; } - public double Gpa { get; init; } + public string FirstName { get; set; } = string.Empty; + public string LastName { get; set; } = string.Empty; + public double Gpa { get; set; } + public string GradDate { get; set; } = string.Empty; + + public override string ToString() => + string.Format(CultureInfo.InvariantCulture, + "{% raw %}Student{{firstName='{0}', lastName='{1}', gpa={2}, gradDate={3}}}{% endraw %}", + FirstName, LastName, Gpa, GradDate); } ``` {% include copy.html %} @@ -34,7 +40,7 @@ var createResponse = await osClient.Indices.CreateAsync("students", ``` {% include copy.html %} -If you use auto mapping, Id and GradYear are mapped as integers, Gpa is mapped as a double, and FirstName and LastName are mapped as text with a keyword subfield. If you want to search for FirstName and LastName and allow only case-sensitive full matches, you can suppress analyzing by mapping these fields as keyword only. In Query DSL, you can accomplish this using the following query: +If you use auto mapping, `Gpa` is mapped as a double, and `FirstName`, `LastName`, and `GradDate` are string properties, so they are mapped as text with a keyword subfield. To search date ranges on `GradDate`, map it as a `date` in the `yyyy-MM-dd` format. If you want to search for `FirstName` and `LastName` and allow only case-sensitive full matches, you can suppress analyzing by mapping these fields as keyword only. In Query DSL, you can accomplish this using the following query: ```json PUT students @@ -46,20 +52,25 @@ PUT students }, "lastName" : { "type" : "keyword" + }, + "gradDate" : { + "type" : "date", + "format" : "yyyy-MM-dd" } } } } ``` -In OpenSearch.Client, you can use fluid lambda syntax to mark these fields as keywords: +In OpenSearch.Client, you can use fluid lambda syntax to map these fields: ```cs var createResponse = await osClient.Indices.CreateAsync(index, c => c.Map(m => m.AutoMap() .Properties(p => p .Keyword(k => k.Name(f => f.FirstName)) - .Keyword(k => k.Name(f => f.LastName))))); + .Keyword(k => k.Name(f => f.LastName)) + .Date(d => d.Name(f => f.GradDate).Format("yyyy-MM-dd"))))); ``` {% include copy.html %} @@ -77,6 +88,10 @@ PUT students }, "lastName" : { "type" : "keyword" + }, + "gradDate" : { + "type" : "date", + "format" : "yyyy-MM-dd" } } }, @@ -87,14 +102,15 @@ PUT students } ``` -In OpenSearch.Client, the equivalent of the above query is the following: +In OpenSearch.Client, the equivalent of the preceding query is the following: ```cs var createResponse = await osClient.Indices.CreateAsync(index, c => c.Map(m => m.AutoMap() .Properties(p => p .Keyword(k => k.Name(f => f.FirstName)) - .Keyword(k => k.Name(f => f.LastName)))) + .Keyword(k => k.Name(f => f.LastName)) + .Date(d => d.Name(f => f.GradDate).Format("yyyy-MM-dd")))) .Settings(s => s.NumberOfShards(1).NumberOfReplicas(2))); ``` {% include copy.html %} @@ -122,7 +138,7 @@ var bulkAll = osClient.BulkAll(ReadData(), r => r ## Searching with Boolean query -OpenSearch.Client exposes full OpenSearch query capability. In addition to simple searches that use the match query, you can create a more complex Boolean query to search for students who graduated in 2022 and sort them by last name. In the example below, search is limited to 10 documents, and the scroll API is used to control the pagination of results. +OpenSearch.Client exposes full OpenSearch query capability. In addition to simple searches that use the match query, you can create a more complex Boolean query that filters on a `gradDate` range to search for students who graduated in 2022 and sort them by last name. In the following example, search is limited to 10 documents, and the scroll API is used to control the pagination of results. ```cs var gradResponse = await osClient.SearchAsync(s => s @@ -133,7 +149,10 @@ var gradResponse = await osClient.SearchAsync(s => s .Query(q => q .Bool(b => b .Filter(f => f - .Term(t => t.Field(fld => fld.GradYear).Value(2022))))) + .DateRange(r => r + .Field(fld => fld.GradDate) + .GreaterThanOrEquals("2022-01-01") + .LessThanOrEquals("2022-12-31"))))) .Sort(srt => srt.Ascending(f => f.LastName))); ``` {% include copy.html %} @@ -159,9 +178,19 @@ var aggResponse = await osClient.SearchAsync(s => s ## Sample program for creating an index and indexing data -The following program creates an index, reads a stream of student records from a comma-separated file and indexes this data into OpenSearch. +The sample program in this section reads student records from a `students.csv` file located in the directory from which you run the program. Create the file with one student record per line in the `FirstName,LastName,Gpa,GradDate` format, specifying the graduation date in the `yyyy-MM-dd` format. Do not include a header row. For example: + +```text +John,Doe,3.89,2022-05-15 +Wei,Zhang,3.65,2022-05-15 +Zhang,Li,3.72,2022-06-10 +``` +{% include copy.html %} + +The following program deletes the `students` index if it exists, creates the index, reads the student records from the file, and indexes them into OpenSearch: ```cs +using System.Globalization; using OpenSearch.Client; namespace NetClientProgram; @@ -174,50 +203,58 @@ internal class Program public static async Task Main(string[] args) { - // Check if the index with the name "students" exists + // Delete the "students" index if it exists so that the index is created with the following mappings var existResponse = await osClient.Indices.ExistsAsync(index); - if (!existResponse.Exists) // There is no index with this name + if (existResponse.Exists) { - // Create an index "students" - // Map FirstName and LastName as keyword - var createResponse = await osClient.Indices.CreateAsync(index, - c => c.Map(m => m.AutoMap() - .Properties(p => p - .Keyword(k => k.Name(f => f.FirstName)) - .Keyword(k => k.Name(f => f.LastName)))) - .Settings(s => s.NumberOfShards(1).NumberOfReplicas(1))); - - if (!createResponse.IsValid && !createResponse.Acknowledged) - { - throw new Exception("Create response is invalid."); - } - - // Take a stream of data and send it to OpenSearch - var bulkAll = osClient.BulkAll(ReadData(), r => r - .Index(index) - .BackOffRetries(2) - .BackOffTime("20s") - .MaxDegreeOfParallelism(4) - .Size(10)); - - // Wait until the data upload is complete. - // FromMinutes specifies a timeout. - // r is a response object that is returned as the data is indexed. - bulkAll.Wait(TimeSpan.FromMinutes(10), r => - Console.WriteLine("Data chunk indexed")); + await osClient.Indices.DeleteAsync(index); } + + // Create an index "students" + // Map FirstName and LastName as keyword and GradDate as date + var createResponse = await osClient.Indices.CreateAsync(index, + c => c.Map(m => m.AutoMap() + .Properties(p => p + .Keyword(k => k.Name(f => f.FirstName)) + .Keyword(k => k.Name(f => f.LastName)) + .Date(d => d.Name(f => f.GradDate).Format("yyyy-MM-dd")))) + .Settings(s => s.NumberOfShards(1).NumberOfReplicas(1))); + + if (!createResponse.IsValid || !createResponse.Acknowledged) + { + throw new Exception("Create response is invalid."); + } + + // Take a stream of data and send it to OpenSearch + var bulkAll = osClient.BulkAll(ReadData(), r => r + .Index(index) + .BackOffRetries(2) + .BackOffTime("20s") + .MaxDegreeOfParallelism(4) + .Size(10) + .RefreshOnCompleted()); + + // Wait until the data upload is complete. + // FromMinutes specifies a timeout. + // r is a response object that is returned as the data is indexed. + bulkAll.Wait(TimeSpan.FromMinutes(10), r => + Console.WriteLine("Data chunk indexed")); } - // Reads student data in the form "Id,FirsName,LastName,GradYear,Gpa" + // Reads student data in the form "FirstName,LastName,Gpa,GradDate" public static IEnumerable ReadData() { - var file = new StreamReader("C:\\search\\students.csv"); - - string s; - while ((s = file.ReadLine()) is not null) + foreach (var line in File.ReadLines("students.csv")) { - yield return new Student(s); + var fields = line.Split(','); + yield return new Student + { + FirstName = fields[0], + LastName = fields[1], + Gpa = double.Parse(fields[2], CultureInfo.InvariantCulture), + GradDate = fields[3] + }; } } } @@ -226,7 +263,7 @@ internal class Program ## Sample program for search -The following program searches students by name and graduation date and calculates the average GPA. +The following program searches students by name and graduation date, calculates the average GPA, and then deletes the index. ```cs using OpenSearch.Client; @@ -246,6 +283,11 @@ internal class Program await SearchByGradDate(); await CalculateAverageGpa(); + + // Delete the index + Console.WriteLine("Deleting the index......"); + var deleteIndexResponse = await osClient.Indices.DeleteAsync(index); + Console.WriteLine("Acknowledged: " + deleteIndexResponse.Acknowledged.ToString().ToLowerInvariant()); } private static async Task SearchByName() @@ -261,13 +303,12 @@ internal class Program if (!nameResponse.IsValid) { - throw new Exception("Aggregation query response is not valid."); + throw new Exception("Name query response is not valid."); } foreach (var s in nameResponse.Documents) { - Console.WriteLine($"{s.Id} {s.LastName} " + - $"{s.FirstName} {s.Gpa} {s.GradYear}"); + Console.WriteLine(" " + s); } } @@ -279,14 +320,16 @@ internal class Program var gradResponse = await osClient.SearchAsync(s => s .Index(index) .From(0) - .Size(2) + .Size(10) .Scroll("1m") .Query(q => q .Bool(b => b .Filter(f => f - .Term(t => t.Field(fld => fld.GradYear).Value(2022))))) - .Sort(srt => srt.Ascending(f => f.LastName)) - .Size(10)); + .DateRange(r => r + .Field(fld => fld.GradDate) + .GreaterThanOrEquals("2022-01-01") + .LessThanOrEquals("2022-12-31"))))) + .Sort(srt => srt.Ascending(f => f.LastName))); if (!gradResponse.IsValid) @@ -298,11 +341,13 @@ internal class Program { foreach (var data in gradResponse.Documents) { - Console.WriteLine($"{data.Id} {data.LastName} {data.FirstName} " + - $"{data.Gpa} {data.GradYear}"); + Console.WriteLine(" " + data); } - gradResponse = osClient.Scroll("1m", gradResponse.ScrollId); + gradResponse = await osClient.ScrollAsync("1m", gradResponse.ScrollId); } + + // Release the resources held by the scroll context + await osClient.ClearScrollAsync(c => c.ScrollId(gradResponse.ScrollId)); } public static async Task CalculateAverageGpa() @@ -315,9 +360,9 @@ internal class Program .Index(index) .Size(0) .Aggregations(a => a - .Average("average gpa", + .Average("average gpa", avg => avg.Field(fld => fld.Gpa)))); - + if (!aggResponse.IsValid) throw new Exception("Aggregation response not valid"); var avg = aggResponse.Aggregations.Average("average gpa").Value; @@ -325,4 +370,10 @@ internal class Program } } ``` -{% include copy.html %} \ No newline at end of file +{% include copy.html %} + +## Related documentation + +- For more examples of using the client, see the [`opensearch-net` user guide](https://github.com/opensearch-project/opensearch-net/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-net` guides](https://github.com/opensearch-project/opensearch-net/tree/main/guides). +- For complete sample applications, see the [`opensearch-net` samples](https://github.com/opensearch-project/opensearch-net/tree/main/samples). diff --git a/_clients/OpenSearch-dot-net.md b/_clients/OpenSearch-dot-net.md index 86488928..954cb743 100644 --- a/_clients/OpenSearch-dot-net.md +++ b/_clients/OpenSearch-dot-net.md @@ -10,46 +10,70 @@ parent: .NET clients OpenSearch.Net is a low-level .NET client that provides the foundational layer of communication with OpenSearch. It is dependency free, and it can handle round-robin load balancing, transport, and the basic request/response cycle. OpenSearch.Net contains all OpenSearch API endpoints as methods. When using OpenSearch.Net, you need to construct the queries yourself. -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-net repo](https://github.com/opensearch-project/opensearch-net). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-net` repo](https://github.com/opensearch-project/opensearch-net). -## Stable Release +## Stable release -This documentation reflects the latest updates available in the [GitHub repository](https://github.com/opensearch-project/opensearch-net) and may include changes unavailable in the current stable release. The current stable release in NuGet is [1.2.0](https://www.nuget.org/packages/OpenSearch.Net.Auth.AwsSigV4/1.2.0). +This documentation reflects the latest updates available in the [GitHub repository](https://github.com/opensearch-project/opensearch-net) and may include changes unavailable in the current stable release. The current stable release in NuGet is [2.2.0](https://www.nuget.org/packages/OpenSearch.Net/2.2.0). For information about supported OpenSearch versions and target frameworks, see [Compatibility]({{site.url}}{{site.baseurl}}/clients/dot-net/#compatibility). -## Example +## Installing the OpenSearch.Net client -The following example illustrates connecting to OpenSearch, indexing documents, and sending queries on the data. It uses the Student class to represent one student, which is equivalent to one document in the index. - -```cs -public class Student -{ - public int Id { get; init; } - public string FirstName { get; init; } - public string LastName { get; init; } - public int GradYear { get; init; } - public double Gpa { get; init; } -} -``` -{% include copy.html %} - -## Installing the Opensearch.Net client - -To install Opensearch.Net, download the [Opensearch.Net NuGet package](https://www.nuget.org/packages/OpenSearch.Net) and add it to your project in an IDE of your choice. In Microsoft Visual Studio, follow the steps below: +To install OpenSearch.Net, download the [OpenSearch.Net NuGet package](https://www.nuget.org/packages/OpenSearch.Net) and add it to your project in an IDE of your choice. In Microsoft Visual Studio, use the following steps: - In the **Solution Explorer** panel, right-click on your solution or project and select **Manage NuGet Packages for Solution**. - Search for the OpenSearch.Net NuGet package, and select **Install**. -Alternatively, you can add OpenSearch.Net to your .csproj file: +Alternatively, add OpenSearch.Net to your project using the .NET CLI: + +```bash +dotnet add package OpenSearch.Net --version 2.2.0 +``` +{% include copy.html %} + +You can also add OpenSearch.Net to your .csproj file: ```xml ... - + ``` {% include copy.html %} +## Sample data + +The examples on this page use the following `Student` class to represent one student, which is equivalent to one document in the index. The `ToString` method formats a `Student` for console output: + +```cs +using System.Globalization; +using System.Runtime.Serialization; + +public class Student +{ + [DataMember(Name = "firstName")] + public string FirstName { get; set; } = string.Empty; + + [DataMember(Name = "lastName")] + public string LastName { get; set; } = string.Empty; + + [DataMember(Name = "gpa")] + public double Gpa { get; set; } + + [DataMember(Name = "gradDate")] + public string GradDate { get; set; } = string.Empty; + + public override string ToString() => + string.Format(CultureInfo.InvariantCulture, + "{% raw %}Student{{firstName='{0}', lastName='{1}', gpa={2}, gradDate={3}}}{% endraw %}", + FirstName, LastName, Gpa, GradDate); +} +``` +{% include copy.html %} + +By default, OpenSearch.Net serializes property names exactly as they are declared. The `DataMember` attributes specify the field names, so a `Student` is indexed as a document containing the `firstName`, `lastName`, `gpa`, and `gradDate` fields. +{: .note} + ## Connecting to OpenSearch Use the default constructor when creating an OpenSearchLowLevelClient object to connect to the default OpenSearch host (`http://localhost:9200`). @@ -95,10 +119,22 @@ var client = new OpenSearchLowLevelClient(settings); ## Connecting to Amazon OpenSearch Service +To sign requests to Amazon OpenSearch Service using AWS Signature Version 4, install the OpenSearch.Net.Auth.AwsSigV4 package. This package depends on OpenSearch.Net, so it also installs OpenSearch.Net: + +```bash +dotnet add package OpenSearch.Net.Auth.AwsSigV4 --version 2.2.0 +``` +{% include copy.html %} + +`AwsSigV4HttpConnection` signs requests using credentials from the default AWS credential provider chain. The Region that you pass to `AwsSigV4HttpConnection` must match the Region of your domain or collection. The following examples use the `us-east-1` Region. + +In the following example, replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console. + The following example illustrates connecting to Amazon OpenSearch Service: ```cs -using OpenSearch.Client; +using Amazon; +using OpenSearch.Net; using OpenSearch.Net.Auth.AwsSigV4; namespace Application @@ -107,12 +143,12 @@ namespace Application { static void Main(string[] args) { - var endpoint = new Uri("https://search-xxx.region.es.amazonaws.com"); - var connection = new AwsSigV4HttpConnection(RegionEndpoint.APSoutheast2, service: AwsSigV4HttpConnection.OpenSearchService); - var config = new ConnectionSettings(endpoint, connection); - var client = new OpenSearchClient(config); + var endpoint = new Uri("https://search--.us-east-1.es.amazonaws.com"); + var connection = new AwsSigV4HttpConnection(RegionEndpoint.USEast1, service: AwsSigV4HttpConnection.OpenSearchService); + var config = new ConnectionConfiguration(endpoint, connection); + var client = new OpenSearchLowLevelClient(config); - Console.WriteLine($"{client.RootNodeInfo().Version.Distribution}: {client.RootNodeInfo().Version.Number}"); + Console.WriteLine(client.RootNodeInfo().Body); } } } @@ -121,10 +157,11 @@ namespace Application ## Connecting to Amazon OpenSearch Serverless -The following example illustrates connecting to Amazon OpenSearch Serverless Service: +The following example illustrates connecting to Amazon OpenSearch Serverless. Replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console: ```cs -using OpenSearch.Client; +using Amazon; +using OpenSearch.Net; using OpenSearch.Net.Auth.AwsSigV4; namespace Application @@ -133,176 +170,239 @@ namespace Application { static void Main(string[] args) { - var endpoint = new Uri("https://search-xxx.region.aoss.amazonaws.com"); - var connection = new AwsSigV4HttpConnection(RegionEndpoint.APSoutheast2, service: AwsSigV4HttpConnection.OpenSearchServerlessService); - var config = new ConnectionSettings(endpoint, connection); - var client = new OpenSearchClient(config); + var endpoint = new Uri("https://.us-east-1.aoss.amazonaws.com"); + var connection = new AwsSigV4HttpConnection(RegionEndpoint.USEast1, service: AwsSigV4HttpConnection.OpenSearchServerlessService); + var config = new ConnectionConfiguration(endpoint, connection); + var client = new OpenSearchLowLevelClient(config); - Console.WriteLine($"{client.RootNodeInfo().Version.Distribution}: {client.RootNodeInfo().Version.Number}"); + Console.WriteLine(client.Cat.Indices().Body); } } } ``` {% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} -## Using ConnectionSettings +## Using ConnectionConfiguration + +Use `ConnectionConfiguration` to pass configuration options to the OpenSearch.Net client. The following example uses `ConnectionConfiguration` to: -`ConnectionConfiguration` is used to pass configuration options to the OpenSearch.Net client. `ConnectionSettings` inherits from `ConnectionConfiguration` and provides additional configuration options. -The following example uses `ConnectionSettings` to: -- Set the default index name for requests that don't specify the index name. - Enable gzip-compressed requests and responses. -- Signal to OpenSearch to return formatted JSON. -- Make field names lowercase. +- Signal to OpenSearch to return formatted JSON. ```cs var uri = new Uri("http://localhost:9200"); var connectionPool = new SingleNodeConnectionPool(uri); -var settings = new ConnectionSettings(connectionPool) - .DefaultIndex("students") +var settings = new ConnectionConfiguration(connectionPool) .EnableHttpCompression() - .PrettyJson() - .DefaultFieldNameInferrer(f => f.ToLower()); + .PrettyJson(); var client = new OpenSearchLowLevelClient(settings); ``` {% include copy.html %} +## Creating an index + +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: + +```cs +var index = "students"; +var createIndexResponse = client.Indices.Create(index, + PostData.Serializable(new + { + settings = new + { + index = new + { + number_of_shards = 1, + number_of_replicas = 1 + } + }, + mappings = new + { + properties = new + { + gradDate = new { type = "date", format = "yyyy-MM-dd" } + } + } + })); +``` +{% include copy.html %} + +The generic type parameter of each method specifies the response type. `DynamicResponse` lets you read values from the response body by path, for example, `createIndexResponse.Get("index")`. `StringResponse` returns the response body as a string. + ## Indexing one document -To index a document, you first need to create an instance of the Student class: +To index a document, first create an instance of the `Student` class: ```cs -var student = new Student { - Id = 100, - FirstName = "Paulo", - LastName = "Santos", - Gpa = 3.93, - GradYear = 2021 -}; +var student = new Student { FirstName = "John", LastName = "Doe", Gpa = 3.89, GradDate = "2022-05-15" }; ``` {% include copy.html %} -Alternatively, you can create an instance of Student using an anonymous type: +Alternatively, you can create a student using an anonymous type. In this case, the property names are the field names: ```cs -var student = new { - Id = 100, - FirstName = "Paulo", - LastName = "Santos", - Gpa = 3.93, - GradYear = 2021 -}; +var student = new { firstName = "John", lastName = "Doe", gpa = 3.89, gradDate = "2022-05-15" }; ``` {% include copy.html %} -Next, upload this Student into the `students` index using the `Index` method: +Next, upload this student into the `students` index with the ID `1` using the `Index` method. Setting `Refresh` to `Refresh.True` makes the document immediately available for search: ```cs -var response = client.Index("students", "100", - PostData.Serializable(student)); -Console.WriteLine(response.Body); +var indexResponse = client.Index(index, "1", + PostData.Serializable(student), + new IndexRequestParameters { Refresh = Refresh.True }); ``` {% include copy.html %} -The generic type parameter of the `Index` method specifies the response body type. In the example above, the response is a string. - ## Indexing many documents using the Bulk API To index many documents, use the Bulk API to bundle many operations into one request: ```cs -var studentArray = new object[] +var bulkBody = new object[] { - new {index = new { _index = "students", _type = "_doc", _id = "200"}}, - new { Id = 200, - FirstName = "Shirley", - LastName = "Rodriguez", - Gpa = 3.91, - GradYear = 2019 - }, - new {index = new { _index = "students", _type = "_doc", _id = "300"}}, - new { Id = 300, - FirstName = "Nikki", - LastName = "Wolf", - Gpa = 3.87, - GradYear = 2020 - } + new { index = new { _index = index, _id = "2" } }, + new Student { FirstName = "Paulo", LastName = "Santos", Gpa = 3.93, GradDate = "2021-05-20" }, + new { index = new { _index = index, _id = "3" } }, + new Student { FirstName = "Shirley", LastName = "Rodriguez", Gpa = 3.91, GradDate = "2019-05-10" } }; - -var manyResponse = client.Bulk(PostData.MultiJson(studentArray)); +var bulkResponse = client.Bulk(PostData.MultiJson(bulkBody), + new BulkRequestParameters { Refresh = Refresh.True }); ``` {% include copy.html %} -You can send the request body as an anonymous object, string, byte array, or stream in APIs that take a body. For APIs that take multiline JSON, you can send the body as a list of bytes or a list of objects, like in the example above. The `PostData` class has static methods to send the body in all of these forms. +You can send the request body as an anonymous object, string, byte array, or stream in APIs that take a body. For APIs that take multiline JSON, you can send the body as a list of bytes or a list of objects, like in the preceding example. The `PostData` class has static methods to send the body in all of these forms. -## Searching for a document +## Searching for documents -To construct a Query DSL query, use anonymous types within the request body. The following query searches for all students who graduated in 2021: +To construct a Query DSL query, use anonymous types within the request body. The following query searches for all students: ```cs -var searchResponseLow = client.Search("students", - PostData.Serializable( - new - { - from = 0, - size = 20, +var searchResponse = client.Search(index, + PostData.Serializable(new { query = new { match_all = new { } } })); +Console.WriteLine(searchResponse.Body); +``` +{% include copy.html %} +The following range query searches for students who graduated in 2019: + +```cs +var searchResponse = client.Search(index, + PostData.Serializable(new + { query = new { - term = new + range = new { - gradYear = new - { - value = 2019 - } + gradDate = new { gte = "2019-01-01", lte = "2019-12-31" } } } - })); - -Console.WriteLine(searchResponseLow.Body); + })); +Console.WriteLine(searchResponse.Body); ``` {% include copy.html %} Alternatively, you can use strings to construct the request. When using strings, you have to escape the `"` character: ```cs -var searchResponse = client.Search("students", +var searchResponse = client.Search(index, @" { ""query"": { - ""match"": + ""range"": { - ""lastName"": + ""gradDate"": { - ""query"": ""Santos"" + ""gte"": ""2019-01-01"", + ""lte"": ""2019-12-31"" } } } }"); - Console.WriteLine(searchResponse.Body); ``` {% include copy.html %} +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```cs +var firstPageResponse = client.Search(index, + PostData.Serializable(new + { + from = 0, + size = 2, + sort = new[] { new { gradDate = "asc" } }, + query = new { match_all = new { } } + })); +Console.WriteLine(firstPageResponse.Body); + +var nextPageResponse = client.Search(index, + PostData.Serializable(new + { + from = 2, + size = 2, + sort = new[] { new { gradDate = "asc" } }, + query = new { match_all = new { } } + })); +Console.WriteLine(nextPageResponse.Body); +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +## Updating a document + +Update a document by sending a partial document in the `doc` field. Only the fields in the partial document are updated: + +```cs +var updateResponse = client.Update(index, "1", + PostData.Serializable(new { doc = new { gpa = 3.92 } })); +``` +{% include copy.html %} + +## Deleting a document + +Delete a document using the following code: + +```cs +var deleteResponse = client.Delete(index, "3", + new DeleteRequestParameters { Refresh = Refresh.True }); +``` +{% include copy.html %} + +## Deleting an index + +Delete an index using the following code: + +```cs +var deleteIndexResponse = client.Indices.Delete(index); +``` +{% include copy.html %} + ## Using OpenSearch.Net methods asynchronously -For applications that require asynchronous code, all method calls in OpenSearch.Client have asynchronous counterparts: +For applications that require asynchronous code, all method calls in OpenSearch.Net have asynchronous counterparts: ```cs // synchronous method -var response = client.Index("students", "100", +var response = client.Index(index, "1", PostData.Serializable(student)); // asynchronous method -var response = client.IndexAsync("students", "100", +var asyncResponse = await client.IndexAsync(index, "1", PostData.Serializable(student)); ``` {% include copy.html %} ## Handling exceptions -By default, OpenSearch.Net does not throw exceptions when an operation is unsuccessful. In particular, OpenSearch.Net does not throw exceptions if the response status code has one of the expected values for this request. For example, the following query searches for a document in an index that does not exist: +By default, OpenSearch.Net does not throw exceptions when an operation is unsuccessful. For example, the following query searches for a document in an index that does not exist: ```cs var searchResponse = client.Search("students1", @@ -323,7 +423,7 @@ Console.WriteLine(searchResponse.Body); ``` {% include copy.html %} -The response contains an error status code 404, which is one of the expected error codes for search requests, so no exception is thrown. You can see the status code in the `status` field: +The response contains the 404 error status code, but no exception is thrown. You can see the status code in the `status` field: ```json { @@ -360,25 +460,31 @@ var client = new OpenSearchLowLevelClient(settings); ``` {% include copy.html %} -You can use the following properties of the response object to determine response success: +To determine whether a request succeeded, use the following properties of the response object: ```cs Console.WriteLine("Success: " + searchResponse.Success); Console.WriteLine("SuccessOrKnownError: " + searchResponse.SuccessOrKnownError); Console.WriteLine("Original Exception: " + searchResponse.OriginalException); ``` +{% include copy.html %} - `Success` returns true if the response code is in the 2xx range or the response code has one of the expected values for this request. - `SuccessOrKnownError` returns true if the response is successful or the response code is in the 400–501 or 505–599 ranges. If SuccessOrKnownError is true, the request is not retried. - `OriginalException` holds the original exception for the unsuccessful responses. -## Sample program +## Sample program -The following program creates an index, indexes data, and searches for documents. +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. Before running the sample program, make sure that you have the `Student` class defined in your project. To print the returned documents, the sample program uses `System.Text.Json` to deserialize the `_source` of each document into a `Student`. + +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```cs +using System.Text.Json; using OpenSearch.Net; -using OpenSearch.Client; namespace NetClientProgram; @@ -386,89 +492,199 @@ internal class Program { public static void Main(string[] args) { - // Create a client with custom settings - var uri = new Uri("http://localhost:9200"); - var connectionPool = new SingleNodeConnectionPool(uri); - var settings = new ConnectionSettings(connectionPool) - .PrettyJson(); - var client = new OpenSearchLowLevelClient(settings); + var config = new ConnectionConfiguration(new Uri("https://localhost:9200")); // Without security, use http://localhost:9200 + config.BasicAuthentication("admin", ""); // Without security, remove this line + config.ServerCertificateValidationCallback(CertificateValidations.AllowAll); // Without security, remove this line + var client = new OpenSearchLowLevelClient(config); - - Console.WriteLine("Indexing one student......"); - var student = new Student { - Id = 100, - FirstName = "Paulo", - LastName = "Santos", - Gpa = 3.93, - GradYear = 2021 }; - var response = client.Index("students", "100", - PostData.Serializable(student)); - Console.WriteLine(response.Body); - - Console.WriteLine("Indexing many students......"); - var studentArray = new object[] - { - new { index = new { _index = "students", _type = "_doc", _id = "200"}}, - new { - Id = 200, - FirstName = "Shirley", - LastName = "Rodriguez", - Gpa = 3.91, - GradYear = 2019}, - new { index = new { _index = "students", _type = "_doc", _id = "300"}}, - new { - Id = 300, - FirstName = "Nikki", - LastName = "Wolf", - Gpa = 3.87, - GradYear = 2020} - }; - - var manyResponse = client.Bulk(PostData.MultiJson(studentArray)); - - Console.WriteLine(manyResponse.Body); - - - Console.WriteLine("Searching for students who graduated in 2019......"); - var searchResponseLow = client.Search("students", - PostData.Serializable( - new + // Create the index + var index = "students"; + Console.WriteLine("Creating index......"); + var createIndexResponse = client.Indices.Create(index, + PostData.Serializable(new { - from = 0, - size = 20, - - query = new + settings = new { - term = new + index = new { - gradYear = new - { - value = 2019 - } + number_of_shards = 1, + number_of_replicas = 1 + } + }, + mappings = new + { + properties = new + { + gradDate = new { type = "date", format = "yyyy-MM-dd" } } } })); + Console.WriteLine("Index created: " + createIndexResponse.Get("index")); - Console.WriteLine(searchResponseLow.Body); + // Index a document + Console.WriteLine("\nIndexing one student......"); + var student = new Student { FirstName = "John", LastName = "Doe", Gpa = 3.89, GradDate = "2022-05-15" }; + var indexResponse = client.Index(index, "1", + PostData.Serializable(student), + new IndexRequestParameters { Refresh = Refresh.True }); + Console.WriteLine($"Result: {indexResponse.Get("result")}, id: {indexResponse.Get("_id")}, version: {indexResponse.Get("_version")}"); - Console.WriteLine("Searching for a student with the last name Santos......"); + // Bulk index documents + Console.WriteLine("\nIndexing many students......"); + var bulkBody = new object[] + { + new { index = new { _index = index, _id = "2" } }, + new Student { FirstName = "Paulo", LastName = "Santos", Gpa = 3.93, GradDate = "2021-05-20" }, + new { index = new { _index = index, _id = "3" } }, + new Student { FirstName = "Shirley", LastName = "Rodriguez", Gpa = 3.91, GradDate = "2019-05-10" } + }; + var bulkResponse = client.Bulk(PostData.MultiJson(bulkBody), + new BulkRequestParameters { Refresh = Refresh.True }); + using (var bulkJson = JsonDocument.Parse(bulkResponse.Body)) + { + Console.WriteLine("Errors: " + bulkJson.RootElement.GetProperty("errors").GetRawText()); + foreach (var item in bulkJson.RootElement.GetProperty("items").EnumerateArray()) + { + var operation = item.GetProperty("index"); + Console.WriteLine($" {operation.GetProperty("result")} id: {operation.GetProperty("_id")}"); + } + } - var searchResponse = client.Search("students", - @" { - ""query"": + // Search for all students + Console.WriteLine("\nSearching for all students......"); + var searchResponse = client.Search(index, + PostData.Serializable(new + { + from = 0, + size = 2, + sort = new[] { new { gradDate = "asc" } }, + query = new { match_all = new { } } + })); + PrintTotal(searchResponse); + Console.WriteLine("Page 1:"); + PrintStudents(searchResponse); + + var nextPageResponse = client.Search(index, + PostData.Serializable(new + { + from = 2, + size = 2, + sort = new[] { new { gradDate = "asc" } }, + query = new { match_all = new { } } + })); + Console.WriteLine("Page 2:"); + PrintStudents(nextPageResponse); + + // Search for students who graduated in 2019 + Console.WriteLine("\nSearching for students who graduated in 2019......"); + var searchResponse2 = client.Search(index, + PostData.Serializable(new + { + query = new { - ""match"": + range = new { - ""lastName"": - { - ""query"": ""Santos"" - } + gradDate = new { gte = "2019-01-01", lte = "2019-12-31" } } } - }"); + })); + PrintTotal(searchResponse2); + PrintStudents(searchResponse2); - Console.WriteLine(searchResponse.Body); + // Update a document + Console.WriteLine("\nUpdating a student's GPA......"); + var updateResponse = client.Update(index, "1", + PostData.Serializable(new { doc = new { gpa = 3.92 } })); + Console.WriteLine($"Result: {updateResponse.Get("result")}, version: {updateResponse.Get("_version")}"); + + // Get the updated document + var getResponse = client.Get(index, "1"); + using (var getJson = JsonDocument.Parse(getResponse.Body)) + { + var updatedStudent = getJson.RootElement.GetProperty("_source").Deserialize(JsonOptions); + Console.WriteLine("Updated document: " + updatedStudent); + } + + // Delete a document + Console.WriteLine("\nDeleting a student......"); + var deleteResponse = client.Delete(index, "3", + new DeleteRequestParameters { Refresh = Refresh.True }); + Console.WriteLine("Result: " + deleteResponse.Get("result")); + + // Delete the index + Console.WriteLine("\nDeleting the index......"); + var deleteIndexResponse = client.Indices.Delete(index); + using (var deleteIndexJson = JsonDocument.Parse(deleteIndexResponse.Body)) + { + Console.WriteLine("Acknowledged: " + deleteIndexJson.RootElement.GetProperty("acknowledged").GetRawText()); + } + } + + // Deserializes camelCase JSON field names into Student properties + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + // Prints the total number of hits + private static void PrintTotal(StringResponse searchResponse) + { + using var json = JsonDocument.Parse(searchResponse.Body); + var hits = json.RootElement.GetProperty("hits"); + Console.WriteLine("Total hits: " + hits.GetProperty("total").GetProperty("value")); + } + + // Prints the student in each hit + private static void PrintStudents(StringResponse searchResponse) + { + using var json = JsonDocument.Parse(searchResponse.Body); + var hits = json.RootElement.GetProperty("hits"); + foreach (var hit in hits.GetProperty("hits").EnumerateArray()) + { + var student = hit.GetProperty("_source").Deserialize(JsonOptions); + Console.WriteLine(" " + student); + } } } ``` {% include copy.html %} + +The sample program produces the following output: + +```text +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} + Student{firstName='Paulo', lastName='Santos', gpa=3.93, gradDate=2021-05-20} +Page 2: + Student{firstName='John', lastName='Doe', gpa=3.89, gradDate=2022-05-15} + +Searching for students who graduated in 2019...... +Total hits: 1 + Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: Student{firstName='John', lastName='Doe', gpa=3.92, gradDate=2022-05-15} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- For more examples of using the client, see the [`opensearch-net` user guide](https://github.com/opensearch-project/opensearch-net/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-net` guides](https://github.com/opensearch-project/opensearch-net/tree/main/guides). +- For complete sample applications, see the [`opensearch-net` samples](https://github.com/opensearch-project/opensearch-net/tree/main/samples). diff --git a/_clients/dot-net-conventions.md b/_clients/dot-net-conventions.md index a0ee0295..ecb0f181 100644 --- a/_clients/dot-net-conventions.md +++ b/_clients/dot-net-conventions.md @@ -32,8 +32,8 @@ var node = new Node(uri); ``` {% include copy.html %} -When first created, a node is master eligible, and its `HoldsData` property is set to true. -The `AbsolutePath` property of the node created above is `"/opensearch/"`: A trailing forward slash is appended so that the paths can be easily combined. If not specified, the default `Port` is 80. +When first created, a node is cluster-manager-eligible, and its `HoldsData` property is set to true. +The `AbsolutePath` property of the node created previously is `"/opensearch/"`: A trailing forward slash is appended so that the paths can be easily combined. If not specified, the default `Port` is 80. Nodes are considered equal if they have the same endpoint. Metadata is not taken into account when checking nodes for equality. {: .note} @@ -79,7 +79,7 @@ var settings = new ConnectionSettings(connectionPool).MaximumRetries(5); ``` {% include copy.html %} -You can also set a `RequestTimeout` that specifies a timeout for a single request and a `MaxRetryTimeout` that specifies the time limit for all retry attempts. In the example below, `RequestTimeout` is set to 4 seconds, and `MaxRetryTimeout` is set to 12 seconds, so the maximum number of attempts for a query is 3. +You can also set a `RequestTimeout` that specifies a timeout for a single request and a `MaxRetryTimeout` that specifies the time limit for all retry attempts. In the following example, `RequestTimeout` is set to 4 seconds, and `MaxRetryTimeout` is set to 12 seconds, so the maximum number of attempts for a query is 3. ```cs var settings = new ConnectionSettings(connectionPool) diff --git a/_clients/dot-net.md b/_clients/dot-net.md index 8e212e0e..23cc4d28 100644 --- a/_clients/dot-net.md +++ b/_clients/dot-net.md @@ -18,6 +18,20 @@ OpenSearch has two .NET clients: a low-level [OpenSearch.Net]({{site.url}}{{site - Operator overloading in queries. - Type and index inference. -You can use both .NET clients in a console program, a .NET core, an ASP.NET core, or in worker services. +You can use both .NET clients in a console program, a .NET Core application, an ASP.NET Core application, or a worker service. -To get started with OpenSearch.Client, follow the instructions in [Getting started with the high-level .NET client]({{site.url}}{{site.baseurl}}/clients/OSC-dot-net#installing-opensearchclient) or in [More advanced features of the high-level .NET client]({{site.url}}{{site.baseurl}}/clients/OSC-example), a slightly more advanced walkthrough. \ No newline at end of file +To get started with OpenSearch.Client, follow the instructions in [Getting started with the high-level .NET client]({{site.url}}{{site.baseurl}}/clients/OSC-dot-net#installing-opensearchclient) or in [More advanced features of the high-level .NET client]({{site.url}}{{site.baseurl}}/clients/OSC-example/), a slightly more advanced walkthrough. + +## Compatibility + +The following table lists the OpenSearch.Client and OpenSearch.Net versions that are compatible with each OpenSearch version. + +| OpenSearch version | Client version | +|:---|:---| +| 1.x | 1.0.0, 1.1.0 | +| 2.x | 1.1.0 or later | +| 3.x | 2.0.0 or later | + +The 2.x clients support .NET 8 or later and .NET Framework 4.7.2 or later. Both clients target .NET Standard 2.0 and .NET Standard 2.1. OpenSearch.Net and OpenSearch.Net.Auth.AwsSigV4 also target .NET 8 and .NET 10. + +For the latest compatibility information, see the [`COMPATIBILITY.md`](https://github.com/opensearch-project/opensearch-net/blob/main/COMPATIBILITY.md) file in the client repository. For information about breaking changes between client versions, see the [upgrading guide](https://github.com/opensearch-project/opensearch-net/blob/main/UPGRADING.md). diff --git a/_clients/go.md b/_clients/go.md index 4e7de566..bf036f9a 100644 --- a/_clients/go.md +++ b/_clients/go.md @@ -6,57 +6,82 @@ nav_order: 50 # Go client -The OpenSearch Go client lets you connect your Go application with the data in your OpenSearch cluster. This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client's complete API documentation and additional examples, see the [Go client API documentation](https://pkg.go.dev/github.com/opensearch-project/opensearch-go/v2). +The OpenSearch Go client lets you connect your Go application with the data in your OpenSearch cluster. This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client's complete API documentation and additional examples, see the [Go client API documentation](https://pkg.go.dev/github.com/opensearch-project/opensearch-go/v5). -For the client source code, see the [opensearch-go repo](https://github.com/opensearch-project/opensearch-go). +For the client source code, see the [`opensearch-go` repo](https://github.com/opensearch-project/opensearch-go). -## Setup +## Installing the Go client + +The Go client requires Go 1.26 or later. If you're starting a new project, create a new module by running the following command: -```go +```bash go mod init ``` {% include copy.html %} -To add the Go client to your project, import it like any other module: +To add the Go client to your project, run the following command: -```go -go get github.com/opensearch-project/opensearch-go +```bash +go get github.com/opensearch-project/opensearch-go/v5 ``` {% include copy.html %} +Version 5 of the client is not compatible with code written for version 4. For migration instructions, see the [v5 upgrade guide](https://github.com/opensearch-project/opensearch-go/blob/main/UPGRADING_V5.md). + ## Connecting to OpenSearch -To connect to the default OpenSearch host, create a client object with the address `https://localhost:9200` if you are using the Security plugin: +The examples on this page use the following imports: ```go -client, err := opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - Addresses: []string{"https://localhost:9200"}, - Username: "admin", // For testing only. Don't store credentials in code. - Password: "admin", - }) +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/opensearch-project/opensearch-go/v5" + "github.com/opensearch-project/opensearch-go/v5/opensearchapi" + "github.com/opensearch-project/opensearch-go/v5/opensearchutil" +) +``` +{% include copy.html %} + +To connect to the default OpenSearch host, create a client object with the address `https://localhost:9200` if you are using the Security plugin: + +```go +client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{"https://localhost:9200"}, + InsecureSkipVerify: true, // For testing only. Use certificate for validation. + Username: "admin", // For testing only. Don't store credentials in code. + Password: "", + DiscoverNodesOnStart: new(false), + }, +}) ``` {% include copy.html %} If you are not using the Security plugin, create a client object with the address `http://localhost:9200`: ```go -client, err := opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - Addresses: []string{"http://localhost:9200"}, - }) +client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{"http://localhost:9200"}, + DiscoverNodesOnStart: new(false), + }, +}) ``` {% include copy.html %} +By default, the client discovers the nodes in the cluster when it starts and then sends requests to the nodes' publish addresses. If these addresses are not reachable from your application---for example, when OpenSearch runs in Docker---requests time out. Setting `DiscoverNodesOnStart` to `false` makes the client send requests only to the addresses that you specify in `Addresses`. + ## Connecting to Amazon OpenSearch Service +In the following example, replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console. + The following example illustrates connecting to Amazon OpenSearch Service: ```go @@ -68,40 +93,46 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" - opensearch "github.com/opensearch-project/opensearch-go/v2" - opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/awsv2" + "github.com/opensearch-project/opensearch-go/v5" + "github.com/opensearch-project/opensearch-go/v5/opensearchapi" + requestsigner "github.com/opensearch-project/opensearch-go/v5/signer/awsv2" ) -const endpoint = "" // e.g. https://opensearch-domain.region.com or Amazon OpenSearch Serverless endpoint +const endpoint = "https://search--.us-east-1.es.amazonaws.com" // OpenSearch domain endpoint func main() { ctx := context.Background() awsCfg, err := config.LoadDefaultConfig(ctx, - config.WithRegion(""), + config.WithRegion("us-east-1"), config.WithCredentialsProvider( getCredentialProvider("", "", ""), ), ) if err != nil { - log.Fatal(err) // Do not log.fatal in a production ready app. + log.Fatal(err) // Do not log.Fatal in a production-ready app. } - // Create an AWS request Signer and load AWS configuration using default config folder or env vars. + // Create an AWS request signer for Amazon OpenSearch Service. signer, err := requestsigner.NewSignerWithService(awsCfg, "es") if err != nil { - log.Fatal(err) // Do not log.fatal in a production ready app. + log.Fatal(err) // Do not log.Fatal in a production-ready app. } - // Create an opensearch client and use the request-signer - client, err := opensearch.NewClient(opensearch.Config{ - Addresses: []string{endpoint}, - Signer: signer, + // Create an OpenSearch client that uses the request signer. + client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{endpoint}, + Signer: signer, + DiscoverNodesOnStart: new(false), + }, }) if err != nil { log.Fatal("client creation err", err) } + + _ = client + // Your code here } func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc { @@ -117,9 +148,13 @@ func getCredentialProvider(accessKey, secretAccessKey, token string) aws.Credent ``` {% include copy.html %} +To use the default AWS credential chain in this or the Amazon OpenSearch Serverless example, omit the `config.WithCredentialsProvider` option. + ## Connecting to Amazon OpenSearch Serverless -The following example illustrates connecting to Amazon OpenSearch Serverless Service: +In the following example, replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console. + +The following example illustrates connecting to Amazon OpenSearch Serverless: ```go package main @@ -130,40 +165,46 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" - opensearch "github.com/opensearch-project/opensearch-go/v2" - opensearchapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi" - requestsigner "github.com/opensearch-project/opensearch-go/v2/signer/awsv2" + "github.com/opensearch-project/opensearch-go/v5" + "github.com/opensearch-project/opensearch-go/v5/opensearchapi" + requestsigner "github.com/opensearch-project/opensearch-go/v5/signer/awsv2" ) -const endpoint = "" // e.g. https://opensearch-domain.region.com or Amazon OpenSearch Serverless endpoint +const endpoint = "https://.us-east-1.aoss.amazonaws.com" // OpenSearch Serverless collection endpoint func main() { ctx := context.Background() awsCfg, err := config.LoadDefaultConfig(ctx, - config.WithRegion(""), + config.WithRegion("us-east-1"), config.WithCredentialsProvider( getCredentialProvider("", "", ""), ), ) if err != nil { - log.Fatal(err) // Do not log.fatal in a production ready app. + log.Fatal(err) // Do not log.Fatal in a production-ready app. } - // Create an AWS request Signer and load AWS configuration using default config folder or env vars. + // Create an AWS request signer for Amazon OpenSearch Serverless. signer, err := requestsigner.NewSignerWithService(awsCfg, "aoss") if err != nil { - log.Fatal(err) // Do not log.fatal in a production ready app. + log.Fatal(err) // Do not log.Fatal in a production-ready app. } - // Create an opensearch client and use the request-signer - client, err := opensearch.NewClient(opensearch.Config{ - Addresses: []string{endpoint}, - Signer: signer, + // Create an OpenSearch client that uses the request signer. + client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{endpoint}, + Signer: signer, + DiscoverNodesOnStart: new(false), + }, }) if err != nil { log.Fatal("client creation err", err) } + + _ = client + // Your code here } func getCredentialProvider(accessKey, secretAccessKey, token string) aws.CredentialsProviderFunc { @@ -179,296 +220,527 @@ func getCredentialProvider(accessKey, secretAccessKey, token string) aws.Credent ``` {% include copy.html %} -The Go client constructor takes an `opensearch.Config{}` type, which can be customized using options such as a list of OpenSearch node addresses or a username and password combination. +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} + +The `opensearchapi.NewClient` constructor takes an `opensearchapi.Config{}` type. Its `Client` field contains an `opensearch.Config{}` type, which can be customized using options such as a list of OpenSearch node addresses or a username and password combination. To connect to multiple OpenSearch nodes, specify them in the `Addresses` parameter: ```go var ( - urls = []string{"http://localhost:9200", "http://localhost:9201", "http://localhost:9202"} + urls = []string{"http://localhost:9200", "http://localhost:9201", "http://localhost:9202"} ) -client, err := opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - Addresses: urls, +client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: urls, + DiscoverNodesOnStart: new(false), + }, }) ``` {% include copy.html %} -The Go client retries requests for a maximum of three times by default. To customize the number of retries, set the `MaxRetries` parameter. Additionally, you can change the list of response codes for which a request is retried by setting the `RetryOnStatus` parameter. The following code snippet creates a new Go client with custom `MaxRetries` and `RetryOnStatus` values: +The Go client retries requests for a maximum of three times by default. To customize the number of retries, set the `MaxRetries` parameter. Additionally, you can change the list of response codes for which a request is retried by setting the `RetryOnStatus` parameter. The following code snippet creates a new Go client with custom `MaxRetries` and `RetryOnStatus` values: ```go -client, err := opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - Addresses: []string{"http://localhost:9200"}, - MaxRetries: 5, - RetryOnStatus: []int{502, 503, 504}, - }) +client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + Addresses: []string{"http://localhost:9200"}, + DiscoverNodesOnStart: new(false), + MaxRetries: 5, + RetryOnStatus: []int{502, 503, 504}, + }, +}) +``` +{% include copy.html %} + +## Sample data + +The examples on this page use a `Student` struct to represent documents. The JSON tags determine the field names in the indexed documents: + +```go +type Student struct { + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + GPA float64 `json:"gpa"` + GradDate string `json:"gradDate"` +} ``` {% include copy.html %} ## Creating an index -To create an OpenSearch index, use the `IndicesCreateRequest` method. You can use the following code to construct a JSON object with custom settings : +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```go -settings := strings.NewReader(`{ - 'settings': { - 'index': { - 'number_of_shards': 1, - 'number_of_replicas': 0 - } - } - }`) - -res := opensearchapi.IndicesCreateRequest{ - Index: "go-test-index1", - Body: settings, -} +ctx := context.Background() +index := "students" +body := `{ + "settings": { + "index": { + "number_of_shards": 1, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "gradDate": { "type": "date", "format": "yyyy-MM-dd" } + } + } +}` +createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{ + Index: index, + BodyReader: strings.NewReader(body), +}) ``` {% include copy.html %} ## Indexing a document -You can index a document into OpenSearch using the `IndexRequest` method: +Index a document using the following code. Setting the `Refresh` parameter to `true` makes the document immediately available for search: ```go -document := strings.NewReader(`{ - "title": "Moneyball", - "director": "Bennett Miller", - "year": "2011" -}`) +student := Student{FirstName: "John", LastName: "Doe", GPA: 3.89, GradDate: "2022-05-15"} +indexResp, err := client.Doc.Index(ctx, opensearchapi.IndexReq{ + Index: index, + ID: "1", + Body: opensearchutil.NewJSONReader(student), + Params: &opensearchapi.IndexParams{Refresh: "true"}, +}) +``` +{% include copy.html %} -docId := "1" -req := opensearchapi.IndexRequest{ - Index: "go-test-index1", - DocumentID: docId, - Body: document, +## Bulk indexing + +Index multiple documents in a single request using the following code. The request body contains an action line followed by a document line for each document, and each line must end with a newline character: + +```go +students := []struct { + id string + student Student +}{ + {"2", Student{FirstName: "Paulo", LastName: "Santos", GPA: 3.93, GradDate: "2021-05-20"}}, + {"3", Student{FirstName: "Shirley", LastName: "Rodriguez", GPA: 3.91, GradDate: "2019-05-10"}}, } -insertResponse, err := req.Do(context.Background(), client) +var bulkBody strings.Builder +for _, s := range students { + doc, err := json.Marshal(s.student) + if err != nil { + return err + } + fmt.Fprintf(&bulkBody, "{\"index\":{\"_id\":%q}}\n%s\n", s.id, doc) +} +bulkResp, err := client.Doc.Bulk(ctx, opensearchapi.BulkReq{ + Index: index, + Body: strings.NewReader(bulkBody.String()), + Params: &opensearchapi.BulkParams{Refresh: "true"}, +}) ``` {% include copy.html %} -## Performing bulk operations - -You can perform several operations at the same time by using the `Bulk` method of the client. The operations may be of the same type or of different types. - -```go -blk, err := client.Bulk( - strings.NewReader(` - { "index" : { "_index" : "go-test-index1", "_id" : "2" } } - { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} - { "create" : { "_index" : "go-test-index1", "_id" : "3" } } - { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} - { "update" : {"_id" : "3", "_index" : "go-test-index1" } } - { "doc" : {"year" : "2016"} } -`), - ) -``` -{% include copy.html %} +If any of the operations fail, the method returns an `*opensearchapi.PartialBulkError` error together with the response. To check the result of each operation, examine the `bulkResp.Items` field. ## Searching for documents -The easiest way to search for documents is to construct a query string. The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" appears in the title field: +Search for all documents in an index using the following code: ```go -content := strings.NewReader(`{ - "size": 5, - "query": { - "multi_match": { - "query": "miller", - "fields": ["title^2", "director"] - } - } -}`) - -search := opensearchapi.SearchRequest{ - Index: []string{"go-test-index1"}, - Body: content, +searchResp, err := client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, +}) +if err != nil { + return err } +for _, hit := range searchResp.Hits.Hits { + var s Student + if err := json.Unmarshal(hit.Source, &s); err != nil { + return err + } + out, err := json.Marshal(s) + if err != nil { + return err + } + fmt.Println(string(out)) +} +``` +{% include copy.html %} -searchResponse, err := search.Do(context.Background(), client) +In each item in `searchResp.Hits.Hits`, the `ID` field contains a pointer to the document ID, and the `Source` field contains the document as raw JSON. To access the document fields, unmarshal `Source` into a `Student` struct: + +```go +for _, hit := range searchResp.Hits.Hits { + var s Student + if err := json.Unmarshal(hit.Source, &s); err != nil { + return err + } + fmt.Printf("ID: %s, name: %s %s, GPA: %v, graduation date: %s\n", *hit.ID, s.FirstName, s.LastName, s.GPA, s.GradDate) +} +``` +{% include copy.html %} + +Search using a range query: + +```go +searchResp, err := client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, + BodyReader: strings.NewReader(`{"query": {"range": {"gradDate": {"gte": "2019-01-01", "lte": "2019-12-31"}}}}`), +}) +``` +{% include copy.html %} + +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```go +searchResp, err := client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, + Params: &opensearchapi.SearchParams{From: 0, Size: new(2), Sort: []string{"gradDate:asc"}}, +}) +if err != nil { + return err +} +nextResp, err := client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, + Params: &opensearchapi.SearchParams{From: 2, Size: new(2), Sort: []string{"gradDate:asc"}}, +}) +if err != nil { + return err +} +for i, resp := range []*opensearchapi.SearchResp{searchResp, nextResp} { + fmt.Printf("Page %d:\n", i+1) + for _, hit := range resp.Hits.Hits { + var s Student + if err := json.Unmarshal(hit.Source, &s); err != nil { + return err + } + out, err := json.Marshal(s) + if err != nil { + return err + } + fmt.Println(" " + string(out)) + } +} +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +## Updating a document + +Update specific fields of a document using a partial document in the `doc` field. Only the specified fields are updated: + +```go +updateResp, err := client.Doc.Update(ctx, opensearchapi.UpdateReq{ + Index: index, + ID: "1", + BodyReader: strings.NewReader(`{"doc": {"gpa": 3.92}}`), +}) ``` {% include copy.html %} ## Deleting a document -You can delete a document using the `DeleteRequest` method: +Delete a document using the following code: ```go -delete := opensearchapi.DeleteRequest{ - Index: "go-test-index1", - DocumentID: "1", -} - -deleteResponse, err := delete.Do(context.Background(), client) +deleteResp, err := client.Doc.Delete(ctx, opensearchapi.DeleteReq{ + Index: index, + ID: "3", + Params: &opensearchapi.DeleteParams{Refresh: "true"}, +}) ``` {% include copy.html %} ## Deleting an index -You can delete an index using the `IndicesDeleteRequest` method: +Delete an index using the following code: ```go -deleteIndex := opensearchapi.IndicesDeleteRequest{ - Index: []string{"go-test-index1"}, -} - -deleteIndexResponse, err := deleteIndex.Do(context.Background(), client) +deleteIndexResp, err := client.Indices.Delete(ctx, &opensearchapi.IndicesDeleteReq{Indices: []string{index}}) ``` {% include copy.html %} ## Sample program -The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index: +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. + +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```go package main + import ( - "os" - "context" - "crypto/tls" - "fmt" - opensearch "github.com/opensearch-project/opensearch-go" - opensearchapi "github.com/opensearch-project/opensearch-go/opensearchapi" - "net/http" - "strings" + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/opensearch-project/opensearch-go/v5" + "github.com/opensearch-project/opensearch-go/v5/opensearchapi" + "github.com/opensearch-project/opensearch-go/v5/opensearchutil" ) -const IndexName = "go-test-index1" + +type Student struct { + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + GPA float64 `json:"gpa"` + GradDate string `json:"gradDate"` +} + func main() { - // Initialize the client with SSL/TLS enabled. - client, err := opensearch.NewClient(opensearch.Config{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - Addresses: []string{"https://localhost:9200"}, - Username: "admin", // For testing only. Don't store credentials in code. - Password: "admin", - }) - if err != nil { - fmt.Println("cannot initialize", err) - os.Exit(1) - } + if err := run(); err != nil { + fmt.Println("Error:", err) + os.Exit(1) + } +} - // Print OpenSearch version information on console. - fmt.Println(client.Info()) +func run() error { + ctx := context.Background() - // Define index settings. - settings := strings.NewReader(`{ - 'settings': { - 'index': { - 'number_of_shards': 1, - 'number_of_replicas': 2 - } - } - }`) + client, err := opensearchapi.NewClient(opensearchapi.Config{ + Client: opensearch.Config{ + // Without security, use http://localhost:9200 + Addresses: []string{"https://localhost:9200"}, + // Without security, remove this line + InsecureSkipVerify: true, + // Without security, remove this line + Username: "admin", + // Without security, remove this line + Password: "", + DiscoverNodesOnStart: new(false), + }, + }) + if err != nil { + return err + } - // Create an index with non-default settings. - res := opensearchapi.IndicesCreateRequest{ - Index: IndexName, - Body: settings, - } - fmt.Println("Creating index") - fmt.Println(res) + // Create the index + index := "students" + fmt.Println("Creating index......") + body := `{ + "settings": { + "index": { + "number_of_shards": 1, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "gradDate": { "type": "date", "format": "yyyy-MM-dd" } + } + } + }` + createResp, err := client.Indices.Create(ctx, opensearchapi.IndicesCreateReq{ + Index: index, + BodyReader: strings.NewReader(body), + }) + if err != nil { + return err + } + fmt.Println("Index created:", createResp.Index) - // Add a document to the index. - document := strings.NewReader(`{ - "title": "Moneyball", - "director": "Bennett Miller", - "year": "2011" - }`) + // Index a document + fmt.Println("\nIndexing one student......") + student := Student{FirstName: "John", LastName: "Doe", GPA: 3.89, GradDate: "2022-05-15"} + indexResp, err := client.Doc.Index(ctx, opensearchapi.IndexReq{ + Index: index, + ID: "1", + Body: opensearchutil.NewJSONReader(student), + Params: &opensearchapi.IndexParams{Refresh: "true"}, + }) + if err != nil { + return err + } + fmt.Printf("Result: %s, id: %s, version: %d\n", indexResp.Result, indexResp.ID, indexResp.Version) - docId := "1" - req := opensearchapi.IndexRequest{ - Index: IndexName, - DocumentID: docId, - Body: document, - } - insertResponse, err := req.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to insert document ", err) - os.Exit(1) - } - fmt.Println("Inserting a document") - fmt.Println(insertResponse) - defer insertResponse.Body.Close() - - // Perform bulk operations. - blk, err := client.Bulk( - strings.NewReader(` - { "index" : { "_index" : "go-test-index1", "_id" : "2" } } - { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} - { "create" : { "_index" : "go-test-index1", "_id" : "3" } } - { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} - { "update" : {"_id" : "3", "_index" : "go-test-index1" } } - { "doc" : {"year" : "2016"} } -`), - ) + // Bulk index documents + fmt.Println("\nIndexing many students......") + students := []struct { + id string + student Student + }{ + {"2", Student{FirstName: "Paulo", LastName: "Santos", GPA: 3.93, GradDate: "2021-05-20"}}, + {"3", Student{FirstName: "Shirley", LastName: "Rodriguez", GPA: 3.91, GradDate: "2019-05-10"}}, + } + var bulkBody strings.Builder + for _, s := range students { + doc, err := json.Marshal(s.student) + if err != nil { + return err + } + fmt.Fprintf(&bulkBody, "{\"index\":{\"_id\":%q}}\n%s\n", s.id, doc) + } + bulkResp, err := client.Doc.Bulk(ctx, opensearchapi.BulkReq{ + Index: index, + Body: strings.NewReader(bulkBody.String()), + Params: &opensearchapi.BulkParams{Refresh: "true"}, + }) + if err != nil { + return err + } + fmt.Println("Errors:", bulkResp.Errors) + for _, item := range bulkResp.Items { + fmt.Printf(" %s id: %s\n", *item.Index.Result, *item.Index.ID) + } - if err != nil { - fmt.Println("failed to perform bulk operations", err) - os.Exit(1) - } - fmt.Println("Performing bulk operations") - fmt.Println(blk) + // Search for all students + fmt.Println("\nSearching for all students......") + searchResp, err := client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, + Params: &opensearchapi.SearchParams{From: 0, Size: new(2), Sort: []string{"gradDate:asc"}}, + }) + if err != nil { + return err + } + total, err := searchResp.Hits.Total.TotalHits() + if err != nil { + return err + } + fmt.Println("Total hits:", total.Value) + nextResp, err := client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, + Params: &opensearchapi.SearchParams{From: 2, Size: new(2), Sort: []string{"gradDate:asc"}}, + }) + if err != nil { + return err + } + for i, resp := range []*opensearchapi.SearchResp{searchResp, nextResp} { + fmt.Printf("Page %d:\n", i+1) + for _, hit := range resp.Hits.Hits { + var s Student + if err := json.Unmarshal(hit.Source, &s); err != nil { + return err + } + out, err := json.Marshal(s) + if err != nil { + return err + } + fmt.Println(" " + string(out)) + } + } - // Search for the document. - content := strings.NewReader(`{ - "size": 5, - "query": { - "multi_match": { - "query": "miller", - "fields": ["title^2", "director"] - } - } - }`) + // Search for students who graduated in 2019 + fmt.Println("\nSearching for students who graduated in 2019......") + searchResp, err = client.Search(ctx, &opensearchapi.SearchReq{ + Indices: []string{index}, + BodyReader: strings.NewReader(`{"query": {"range": {"gradDate": {"gte": "2019-01-01", "lte": "2019-12-31"}}}}`), + }) + if err != nil { + return err + } + total, err = searchResp.Hits.Total.TotalHits() + if err != nil { + return err + } + fmt.Println("Total hits:", total.Value) + for _, hit := range searchResp.Hits.Hits { + var s Student + if err := json.Unmarshal(hit.Source, &s); err != nil { + return err + } + out, err := json.Marshal(s) + if err != nil { + return err + } + fmt.Println(" " + string(out)) + } - search := opensearchapi.SearchRequest{ - Index: []string{IndexName}, - Body: content, - } + // Update a document + fmt.Println("\nUpdating a student's GPA......") + updateResp, err := client.Doc.Update(ctx, opensearchapi.UpdateReq{ + Index: index, + ID: "1", + BodyReader: strings.NewReader(`{"doc": {"gpa": 3.92}}`), + }) + if err != nil { + return err + } + fmt.Printf("Result: %s, version: %d\n", updateResp.Result, updateResp.Version) - searchResponse, err := search.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to search document ", err) - os.Exit(1) - } - fmt.Println("Searching for a document") - fmt.Println(searchResponse) - defer searchResponse.Body.Close() + // Get the updated document + getResp, err := client.Doc.Get(ctx, opensearchapi.GetReq{Index: index, ID: "1"}) + if err != nil { + return err + } + var updated Student + if err := json.Unmarshal(getResp.Source, &updated); err != nil { + return err + } + out, err := json.Marshal(updated) + if err != nil { + return err + } + fmt.Println("Updated document: " + string(out)) - // Delete the document. - delete := opensearchapi.DeleteRequest{ - Index: IndexName, - DocumentID: docId, - } + // Delete a document + fmt.Println("\nDeleting a student......") + deleteResp, err := client.Doc.Delete(ctx, opensearchapi.DeleteReq{ + Index: index, + ID: "3", + Params: &opensearchapi.DeleteParams{Refresh: "true"}, + }) + if err != nil { + return err + } + fmt.Println("Result:", deleteResp.Result) - deleteResponse, err := delete.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to delete document ", err) - os.Exit(1) - } - fmt.Println("Deleting a document") - fmt.Println(deleteResponse) - defer deleteResponse.Body.Close() + // Delete the index + fmt.Println("\nDeleting the index......") + deleteIndexResp, err := client.Indices.Delete(ctx, &opensearchapi.IndicesDeleteReq{Indices: []string{index}}) + if err != nil { + return err + } + fmt.Println("Acknowledged:", deleteIndexResp.Acknowledged) - // Delete the previously created index. - deleteIndex := opensearchapi.IndicesDeleteRequest{ - Index: []string{IndexName}, - } - - deleteIndexResponse, err := deleteIndex.Do(context.Background(), client) - if err != nil { - fmt.Println("failed to delete index ", err) - os.Exit(1) - } - fmt.Println("Deleting the index") - fmt.Println(deleteIndexResponse) - defer deleteIndexResponse.Body.Close() + return nil } ``` -{% include copy.html %} \ No newline at end of file +{% include copy.html %} + +The program produces the following output: + +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + {"firstName":"Paulo","lastName":"Santos","gpa":3.93,"gradDate":"2021-05-20"} +Page 2: + {"firstName":"John","lastName":"Doe","gpa":3.89,"gradDate":"2022-05-15"} + +Searching for students who graduated in 2019...... +Total hits: 1 + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: {"firstName":"John","lastName":"Doe","gpa":3.92,"gradDate":"2022-05-15"} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- For more examples of using the client, see the [`opensearch-go` user guide](https://github.com/opensearch-project/opensearch-go/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-go` guides](https://github.com/opensearch-project/opensearch-go/tree/main/guides). diff --git a/_clients/hadoop.md b/_clients/hadoop.md new file mode 100644 index 00000000..4114d2fc --- /dev/null +++ b/_clients/hadoop.md @@ -0,0 +1,404 @@ +--- +layout: default +title: Hadoop connector +nav_order: 110 +--- + +# Hadoop connector + +The OpenSearch Hadoop connector lets you read and write data between [Apache Spark](http://spark.apache.org), [Apache Hive](http://hive.apache.org), Hadoop MapReduce, and OpenSearch. It enables Spark jobs to directly index data into OpenSearch and run queries against it, with parallel reads and writes across Spark partitions and OpenSearch shards for efficient distributed processing. + +For the source code, see the [OpenSearch Hadoop](https://github.com/opensearch-project/opensearch-hadoop) repository. + +## Setup + +Add the connector to your Spark application using `--packages`: + +- For Spark 3.4.x, run the following command: + +```bash +pyspark --packages org.opensearch.client:opensearch-spark-30_2.12:2.0.0 +``` +{% include copy.html %} + +- For Spark 3.5.x, run the following command: + +```bash +pyspark --packages org.opensearch.client:opensearch-spark-35_2.12:2.0.0 +``` +{% include copy.html %} + +- For Spark 4.x, run the following command: + +```bash +pyspark --packages org.opensearch.client:opensearch-spark-40_2.13:2.0.0 +``` +{% include copy.html %} + +Alternatively, add Spark as a dependency in your build file: + +```xml + + org.opensearch.client + opensearch-spark-30_2.12 + 2.0.0 + +``` +{% include copy.html %} + +Choose the artifact that matches your Spark and Scala version listed in the following table. + +Spark version | Scala version | Artifact +:--- | :--- | :--- +3.4.x | 2.12 | `org.opensearch.client:opensearch-spark-30_2.12:2.0.0` +3.4.x | 2.13 | `org.opensearch.client:opensearch-spark-30_2.13:2.0.0` +3.5.x | 2.12 | `org.opensearch.client:opensearch-spark-35_2.12:2.0.0` +3.5.x | 2.13 | `org.opensearch.client:opensearch-spark-35_2.13:2.0.0` +4.x | 2.13 | `org.opensearch.client:opensearch-spark-40_2.13:2.0.0` + +## Basic usage + +The following examples demonstrate basic read and write operations using the connector with different Spark APIs. + +### PySpark + +No additional Python package is needed. The Java connector is loaded using `--packages` or `spark.jars`: + +```python +# Write (index documents into OpenSearch) +df = spark.createDataFrame([("John", 30), ("Jane", 25)], ["name", "age"]) +df.write.format("opensearch").save("people") + +# Read (query documents from OpenSearch) +df = spark.read.format("opensearch").load("people") +df.show() + +# Read with a query (only matching documents are transferred to Spark) +filtered = spark.read \ + .format("opensearch") \ + .option("opensearch.query", '{"query":{"match":{"name":"John"}}}') \ + .load("people") +``` +{% include copy.html %} + +### Scala + +Use the Scala API to access helper methods like `saveToOpenSearch` for cleaner syntax: + +```scala +import org.opensearch.spark.sql._ + +// Write (index documents into OpenSearch) +val df = spark.createDataFrame(Seq(("John", 30), ("Jane", 25))).toDF("name", "age") +df.saveToOpenSearch("people") + +// Read (query documents from OpenSearch) +val result = spark.read.format("opensearch").load("people") +result.show() + +// Read with a query +val filtered = spark.read + .format("opensearch") + .option("opensearch.query", """{"query":{"match":{"name":"John"}}}""") + .load("people") +``` +{% include copy.html %} + +### Java + +Use the `JavaOpenSearchSparkSQL` wrapper for Java applications: + +```java +import org.opensearch.spark.sql.api.java.JavaOpenSearchSparkSQL; + +// Write +Dataset df = spark.createDataFrame(data, schema); +JavaOpenSearchSparkSQL.saveToOpenSearch(df, "people"); + +// Read +Dataset result = spark.read().format("opensearch").load("people"); +result.show(); +``` +{% include copy.html %} + +### Spark SQL + +You can register an OpenSearch index as a temporary view and query it using SQL: + +```python +spark.sql(""" + CREATE TEMPORARY VIEW people + USING opensearch + OPTIONS (resource 'people') +""") + +spark.sql("SELECT * FROM people WHERE age > 25").show() +``` +{% include copy.html %} + +## Write operations + +Configure how documents are written to OpenSearch indexes, including document IDs, write modes, and routing strategies. + +### Specifying a document ID + +Use `opensearch.mapping.id` to control the `_id` of each document: + +```python +df.write.format("opensearch") \ + .option("opensearch.mapping.id", "id") \ + .save("my-index") +``` +{% include copy.html %} + +### Write modes + +Control how data is written to OpenSearch using Spark's write modes: + +```python +# Append (default): add documents to the index +df.write.format("opensearch").mode("append").save("my-index") + +# Overwrite: delete the index and recreate it with the new data +df.write.format("opensearch").mode("overwrite").save("my-index") +``` +{% include copy.html %} + +### Upsert + +Update documents if they exist or insert them as new documents if they don't. This operation requires specifying a document ID field: + +```python +df.write.format("opensearch") \ + .option("opensearch.mapping.id", "id") \ + .option("opensearch.write.operation", "upsert") \ + .save("my-index") +``` +{% include copy.html %} + +### Dynamic index routing + +Use placeholders in the index name to route documents to different indexes based on field values. This feature requires the Scala `saveToOpenSearch` method: + +```scala +import org.opensearch.spark.sql._ + +// Route by field value: {"category": "electronics", "name": "TV"} -> index "electronics" +df.saveToOpenSearch("{category}") + +// Prefix + field value: {"env": "prod", "msg": "ok"} -> index "logs-prod" +df.saveToOpenSearch("logs-{env}") + +// Date formatting: {"timestamp": "2026-02-16T10:30:00.000Z", "msg": "ok"} -> index "logs-2026.02.16" +df.saveToOpenSearch("logs-{timestamp|yyyy.MM.dd}") +``` +{% include copy.html %} + +## Read operations + +Optimize data retrieval from OpenSearch by filtering queries and selecting specific fields to reduce data transfer. + +### Reading with a query + +Filter data at the OpenSearch level so only matching documents are loaded into Spark: + +```python +# Query DSL +df = spark.read.format("opensearch") \ + .option("opensearch.query", '{"query":{"range":{"age":{"gte":25}}}}') \ + .load("my-index") + +# URI query +df = spark.read.format("opensearch") \ + .option("opensearch.query", "?q=name:John") \ + .load("my-index") +``` +{% include copy.html %} + +### Selecting fields + +Load only specific fields to reduce data transfer: + +```python +df = spark.read.format("opensearch") \ + .option("opensearch.read.field.include", "name,age") \ + .load("my-index") +``` +{% include copy.html %} + +## Security + +Secure connections to OpenSearch clusters using authentication and encryption. + +### Basic authentication + +Provide credentials for OpenSearch clusters with authentication enabled: + +```python +df.write.format("opensearch") \ + .option("opensearch.net.http.auth.user", "") \ + .option("opensearch.net.http.auth.pass", "") \ + .save("my-index") +``` +{% include copy.html %} + +### HTTPS + +Enable SSL/TLS encryption for secure connections: + +```python +df.write.format("opensearch") \ + .option("opensearch.net.ssl", "true") \ + .save("my-index") +``` +{% include copy.html %} + +## Advanced Spark features + +Access low-level Spark APIs and streaming capabilities for specialized use cases. + +### Spark resilient distributed dataset + +For low-level access, the connector provides resilient distributed dataset (RDD)-based read and write methods: + +```scala +import org.opensearch.spark._ + +// Write +val data = sc.makeRDD(Seq( + Map("name" -> "John", "age" -> 30), + Map("name" -> "Jane", "age" -> 25) +)) +data.saveToOpenSearch("people") + +// Read +val rdd = sc.opensearchRDD("people") +rdd.collect().foreach(println) + +// Read with query +val filtered = sc.opensearchRDD("people", "?q=name:John") +``` +{% include copy.html %} + +### Spark Structured Streaming + +The connector supports Spark Structured Streaming as a sink: + +```scala +val query = streamingDF.writeStream + .format("opensearch") + .option("checkpointLocation", "/tmp/checkpoint") + .start("streaming-index") +``` +{% include copy.html %} + +## Alternative interfaces + +Use the connector with Hadoop MapReduce and Apache Hive for alternative workflows. + +### Hadoop MapReduce + +For Hadoop MapReduce jobs, the connector provides `OpenSearchInputFormat` and `OpenSearchOutputFormat`. Add `opensearch-hadoop-mr-2.0.0.jar` to your job `classpath`. + +```java +// Writing +Configuration conf = new Configuration(); +conf.set("opensearch.resource", "my-index"); +Job job = new Job(conf); +job.setOutputFormatClass(OpenSearchOutputFormat.class); +job.waitForCompletion(true); + +// Reading +Configuration conf = new Configuration(); +conf.set("opensearch.resource", "my-index"); +Job job = new Job(conf); +job.setInputFormatClass(OpenSearchInputFormat.class); +job.waitForCompletion(true); +``` +{% include copy.html %} + +### Apache Hive + +The connector provides an Apache Hive storage handler. Add `opensearch-hadoop-hive-2.0.0.jar` to your Hive classpath: + +```sql +ADD JAR /path/opensearch-hadoop-hive-2.0.0.jar; + +CREATE EXTERNAL TABLE people ( + name STRING, + age INT) +STORED BY 'org.opensearch.hadoop.hive.OpenSearchStorageHandler' +TBLPROPERTIES('opensearch.resource' = 'people'); + +SELECT * FROM people; +``` +{% include copy.html %} + +## Connecting to Amazon OpenSearch Service + +To connect to Amazon OpenSearch Service with IAM authentication, enable AWS Signature Version 4 signing and HTTPS: + +```python +df.write.format("opensearch") \ + .option("opensearch.nodes", "https://search-xxx.us-east-1.es.amazonaws.com") \ + .option("opensearch.port", "443") \ + .option("opensearch.net.ssl", "true") \ + .option("opensearch.nodes.wan.only", "true") \ + .option("opensearch.aws.sigv4.enabled", "true") \ + .option("opensearch.aws.sigv4.region", "us-east-1") \ + .save("my-index") +``` +{% include copy.html %} + +The following AWS SDK v2 dependencies are required on the `classpath`: +- `software.amazon.awssdk:auth:2.31.59` (or later) +- `software.amazon.awssdk:regions:2.31.59` (or later) +- `software.amazon.awssdk:http-client-spi:2.31.59` (or later) +- `software.amazon.awssdk:identity-spi:2.31.59` (or later) +- `software.amazon.awssdk:sdk-core:2.31.59` (or later) +- `software.amazon.awssdk:utils:2.31.59` (or later) + +## Connecting to Amazon OpenSearch Serverless + +To connect to Amazon OpenSearch Serverless, add `opensearch.serverless` and set the Signature Version 4 service name to `aoss`: + +```python +df.write.format("opensearch") \ + .option("opensearch.nodes", "https://xxx.us-east-1.aoss.amazonaws.com") \ + .option("opensearch.port", "443") \ + .option("opensearch.net.ssl", "true") \ + .option("opensearch.nodes.wan.only", "true") \ + .option("opensearch.aws.sigv4.enabled", "true") \ + .option("opensearch.aws.sigv4.region", "us-east-1") \ + .option("opensearch.aws.sigv4.service.name", "aoss") \ + .option("opensearch.serverless", "true") \ + .save("my-index") +``` +{% include copy.html %} + +## Configuration properties + +All configuration properties start with the `opensearch` prefix. Properties can be set using Spark configuration (`--conf`), as options of the `DataFrame` reader/writer, or in the Hadoop configuration. + +Property | Default | Description +:--- | :--- | :--- +`opensearch.resource` | (none) | The OpenSearch index name. Can also be specified as the argument to `saveToOpenSearch()` or `load()`. +`opensearch.nodes` | `localhost` | The OpenSearch host address. +`opensearch.port` | `9200` | The OpenSearch REST port. +`opensearch.nodes.wan.only` | `false` | Set to `true` when connecting through a load balancer or proxy. +`opensearch.query` | match all | A query DSL or Uniform Resource Identifier (URI) query for reading. +`opensearch.net.ssl` | `false` | Enables HTTPS. +`opensearch.mapping.id` | (none) | The document field to use as the `_id`. +`opensearch.write.operation` | `index` | The write operation: `index`, `create`, `update`, or `upsert`. +`opensearch.scroll.size` | `1000` | The number of documents fetched per batch when reading. +`opensearch.read.field.include` | (none) | A comma-separated list of fields to read. + +## Compatibility + +The following table lists the connector versions and their compatible runtime versions. + +Client version | Minimum Java runtime version | OpenSearch version | Spark version +:--- | :--- | :--- | :--- +1.0.0--1.3.0 | Java 8 | 1.x, 2.x | 3.4.x +2.0.0 | Java 11 | 1.x, 2.x, 3.x | 3.4.x, 3.5.x, 4.x + diff --git a/_clients/index.md b/_clients/index.md index 7ce0acc2..87b67c0a 100644 --- a/_clients/index.md +++ b/_clients/index.md @@ -9,22 +9,21 @@ redirect_from: - /clients/index/ --- -# OpenSearch language clients +# ![Clients icon]({{site.url}}{{site.baseurl}}/images/icons/OpenSearch-Clients-Icon.avif){: .heading-icon} OpenSearch language clients -OpenSearch provides clients in JavaScript, Python, Ruby, Java, PHP, .NET, Go and Rust. +OpenSearch clients let you work with OpenSearch from your application code. A client connects to your cluster, sends requests, and returns the responses as objects in your programming language, so you can create indexes, add documents, and search without building HTTP requests and parsing JSON yourself. ## OpenSearch clients OpenSearch provides clients for the following programming languages and platforms: * **Python** - * [OpenSearch high-level Python client]({{site.url}}{{site.baseurl}}/clients/python-high-level/) - * [OpenSearch low-level Python client]({{site.url}}{{site.baseurl}}/clients/python-low-level/) - * [`opensearch-py-ml` client]({{site.url}}{{site.baseurl}}/clients/opensearch-py-ml/) + * [OpenSearch Python client]({{site.url}}{{site.baseurl}}/clients/python-low-level/) + * [OpenSearch Python ML client]({{site.url}}{{site.baseurl}}/clients/opensearch-py-ml/): Analyze data in OpenSearch indexes using DataFrames and upload machine learning (ML) models to OpenSearch. * **Java** * [OpenSearch Java client]({{site.url}}{{site.baseurl}}/clients/java/) * **JavaScript** - * [OpenSearch JavaScript (Node.js) client]({{site.url}}{{site.baseurl}}/clients/javascript/index) + * [OpenSearch JavaScript (Node.js) client]({{site.url}}{{site.baseurl}}/clients/javascript/index/) * **Go** * [OpenSearch Go client]({{site.url}}{{site.baseurl}}/clients/go/) * **Ruby** @@ -36,89 +35,31 @@ OpenSearch provides clients for the following programming languages and platform * **Rust** * [OpenSearch Rust client]({{site.url}}{{site.baseurl}}/clients/rust/) * **Hadoop** - * [OpenSearch Hadoop client](https://github.com/opensearch-project/opensearch-hadoop) + * [Hadoop connector (Apache Spark, Apache Hive, and Hadoop MapReduce)]({{site.url}}{{site.baseurl}}/clients/hadoop/) +## Deprecated clients -For a client compatibility matrix, see the COMPATIBILITY.md file in the client's repository. -{: .note} +The following clients have been deprecated: + +* [OpenSearch high-level Python client]({{site.url}}{{site.baseurl}}/clients/python-high-level/): Use the [OpenSearch Python client]({{site.url}}{{site.baseurl}}/clients/python-low-level/) instead. +* [OpenSearch Java high-level REST client]({{site.url}}{{site.baseurl}}/clients/java-rest-high-level/): Use the [OpenSearch Java client]({{site.url}}{{site.baseurl}}/clients/java/) instead. -The OpenSearch Java high-level REST client will be deprecated starting with OpenSearch version 3.0.0 and will be removed in a future release. We recommend switching to the [Java client]({{site.url}}{{site.baseurl}}/clients/java/) instead. -{: .warning} ## Legacy clients -Most clients that work with Elasticsearch OSS 7.10.2 *should* work with OpenSearch, but the latest versions of those clients might include license or version checks that artificially break compatibility. This page includes recommendations around which versions of those clients to use for best compatibility with OpenSearch. +Clients that work with Elasticsearch OSS 7.10.2 should work with OpenSearch 1.x. The latest versions of those clients, however, might include license or version checks that artificially break compatibility. The following table provides recommendations for which client versions to use for best compatibility with OpenSearch 1.x. For OpenSearch 2.0 and later, no Elasticsearch clients are fully compatible with OpenSearch. -For a client compatibility matrix, see the COMPATIBILITY.md file in the client's repository. -{: .note} +While OpenSearch and Elasticsearch share several core features, mixing and matching the client and server has a high risk of errors and unexpected results. As OpenSearch and Elasticsearch continue to diverge, such risks may increase. Although your Elasticsearch client may continue working with your OpenSearch cluster, using OpenSearch clients for OpenSearch clusters is recommended. +{: .warning} + +To view the compatibility matrix for a specific client, see the `COMPATIBILITY.md` file in the client's repository. Client | Recommended version :--- | :--- -[Elasticsearch Java low-level REST client](https://search.maven.org/artifact/org.elasticsearch.client/elasticsearch-rest-client/7.13.4/jar) | 7.13.4 -[Elasticsearch Java high-level REST client](https://search.maven.org/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client/7.13.4/jar) | 7.13.4 +[Elasticsearch Java low-level REST client](https://central.sonatype.com/artifact/org.elasticsearch.client/elasticsearch-rest-client/7.13.4) | 7.13.4 +[Elasticsearch Java high-level REST client](https://central.sonatype.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client/7.13.4) | 7.13.4 [Elasticsearch Python client](https://pypi.org/project/elasticsearch/7.13.4/) | 7.13.4 [Elasticsearch Node.js client](https://www.npmjs.com/package/@elastic/elasticsearch/v/7.13.0) | 7.13.0 [Elasticsearch Ruby client](https://rubygems.org/gems/elasticsearch/versions/7.13.0) | 7.13.0 -If you test a legacy client and verify that it works, please [submit a PR](https://github.com/opensearch-project/documentation-website/pulls) and add it to this table. - - -{% comment %} -## Python 3 test code - -This code indexes a single document and is equivalent to `PUT /python-test-index1/_doc/1`. - -```python -from elasticsearch import Elasticsearch - -host = 'localhost' -port = 9200 -# For testing only. Do not store credentials in code. -auth = ('admin', 'admin') - -es = Elasticsearch( - hosts = [{'host': host, 'port': port}], - http_auth = auth, - use_ssl = True, - verify_certs = False -) - -document = { - "title": "Moneyball", - "director": "Bennett Miller", - "year": "2011" -} - -response = es.index(index='python-test-index1', id='1', body=document, refresh=True) - -print(response) -``` - - -## Node.js test code - -This code is equivalent to `GET /`. - -```js -const { Client } = require('@elastic/elasticsearch') -const client = new Client({ - node: 'https://localhost:9200', - auth: { - // For testing only. Don't store credentials in code. - username: 'admin', - password: 'admin' - }, - ssl: { - // ca: fs.readFileSync('./cacert.pem'), - rejectUnauthorized: false - } -}) - -async function run () { - const { body } = await client.info(); - console.log(body); -} - -run().catch(console.log) -``` -{% endcomment %} +If you test a legacy client and verify that it works, [submit a PR](https://github.com/opensearch-project/documentation-website/pulls) and add it to this table. diff --git a/_clients/java-rest-high-level.md b/_clients/java-rest-high-level.md index e4364994..dc99bae3 100644 --- a/_clients/java-rest-high-level.md +++ b/_clients/java-rest-high-level.md @@ -1,12 +1,12 @@ --- layout: default -title: Java high-level REST client -nav_order: 20 +title: Java high-level REST client (deprecated) +nav_order: 190 --- # Java high-level REST client -The OpenSearch Java high-level REST client is deprecated. Support will be removed in OpenSearch version 3.0.0. We recommend switching to the [Java client]({{site.url}}{{site.baseurl}}/clients/java/) instead. +The OpenSearch Java high-level REST client is deprecated. Support will be removed in a future version. We recommend switching to the [Java client]({{site.url}}{{site.baseurl}}/clients/java/) instead. {: .warning} The OpenSearch Java high-level REST client lets you interact with your OpenSearch clusters and indexes through Java methods and data structures rather than HTTP methods and JSON. @@ -23,7 +23,7 @@ To start using the OpenSearch Java high-level REST client, ensure that you have ``` -You can now start your OpenSearch cluster. The OpenSearch 1.x high-level REST client works with the 1.x versions of OpenSearch. +You can now start your OpenSearch cluster. Use the version of the high-level REST client that matches your OpenSearch version. ## Security @@ -32,24 +32,23 @@ Before using the REST client in your Java application, you must configure the ap If you're using certificates from a trusted Certificate Authority (CA), you don't need to configure the truststore. ```bash -keytool -import -alias -keystore +keytool -importcert -file -alias -keystore ``` -You can now point your Java client to the truststore and set basic authentication credentials that can access a secure cluster (refer to the sample code below on how to do so). +You can now point your Java client to the truststore and set basic authentication credentials that can access a secure cluster (refer to the sample following code on how to do so). -If you run into issues when configuring security, see [common issues]({{site.url}}{{site.baseurl}}/troubleshoot/index) and [troubleshoot TLS]({{site.url}}{{site.baseurl}}/troubleshoot/tls). +If you run into issues when configuring security, see [Troubleshooting TLS]({{site.url}}{{site.baseurl}}/security/configuration/troubleshoot-tls/). ## Sample program -This code example uses basic credentials that come with the default OpenSearch configuration. If you’re using the OpenSearch Java high-level REST client with your own OpenSearch cluster, be sure to change the code to use your own credentials. +This code example uses the `admin` user. Replace `` with the admin password that you set when you installed OpenSearch. Replace `/full/path/to/keystore` with the path to your truststore and `password-to-keystore` with the truststore password. ```java -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; +import org.apache.hc.core5.http.HttpHost; import org.opensearch.action.admin.indices.delete.DeleteIndexRequest; import org.opensearch.action.delete.DeleteRequest; import org.opensearch.action.delete.DeleteResponse; @@ -57,7 +56,7 @@ import org.opensearch.action.get.GetRequest; import org.opensearch.action.get.GetResponse; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.index.IndexResponse; -import org.opensearch.action.support.master.AcknowledgedResponse; +import org.opensearch.action.support.clustermanager.AcknowledgedResponse; import org.opensearch.client.RequestOptions; import org.opensearch.client.RestClient; import org.opensearch.client.RestClientBuilder; @@ -79,13 +78,14 @@ public class RESTClientSample { //Establish credentials to use basic authentication. //Only for demo purposes. Don't specify your credentials in code. - final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + final HttpHost host = new HttpHost("https", "localhost", 9200); + final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(AuthScope.ANY, - new UsernamePasswordCredentials("admin", "admin")); + credentialsProvider.setCredentials(new AuthScope(host), + new UsernamePasswordCredentials("admin", "".toCharArray())); //Create a client. - RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "https")) + RestClientBuilder builder = RestClient.builder(host) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { diff --git a/_clients/java.md b/_clients/java.md index 4c1e06a4..b073cc0e 100644 --- a/_clients/java.md +++ b/_clients/java.md @@ -8,9 +8,13 @@ nav_order: 30 The OpenSearch Java client allows you to interact with your OpenSearch clusters through Java methods and data structures rather than HTTP methods and raw JSON. For example, you can submit requests to your cluster using objects to create indexes, add data to documents, or complete some other operation using the client's built-in methods. For the client's complete API documentation and additional examples, see the [javadoc](https://www.javadoc.io/doc/org.opensearch.client/opensearch-java/latest/index.html). -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-java repo](https://github.com/opensearch-project/opensearch-java). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-java` repo](https://github.com/opensearch-project/opensearch-java). -## Installing the client using Apache HttpClient 5 Transport +## Installing the Java client + +The Java client requires a transport in order to communicate with your cluster. `ApacheHttpClient5Transport` is the default transport and the recommended choice for new applications. The `RestClient` transport is deprecated and will be removed in a future release. + +### Installing the client using Apache HttpClient 5 Transport To start using the OpenSearch Java client, you need to provide a transport. The default `ApacheHttpClient5TransportBuilder` transport comes with the Java client. To use the OpenSearch Java client with the default transport, add it to your `pom.xml` file as a dependency: @@ -18,30 +22,26 @@ To start using the OpenSearch Java client, you need to provide a transport. The org.opensearch.client opensearch-java - 2.8.1 - - - - org.apache.httpcomponents.client5 - httpclient5 - 5.2.1 + 3.10.0 ``` {% include copy.html %} If you're using Gradle, add the following dependencies to your project: -``` +```groovy dependencies { - implementation 'org.opensearch.client:opensearch-java:2.8.1' - implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1' + implementation 'org.opensearch.client:opensearch-java:3.10.0' } ``` {% include copy.html %} You can now start your OpenSearch cluster. -## Installing the client using RestClient Transport +### Installing the client using RestClient Transport (deprecated) + +The `RestClientTransport` transport and the `org.opensearch.client.RestClient` class that it wraps are deprecated and will be removed in a future release. Use [Apache HttpClient 5 Transport](#installing-the-client-using-apache-httpclient-5-transport) instead. +{: .warning} Alternatively, you can create a Java client by using the `RestClient`-based transport. In this case, make sure that you have the following dependencies in your project's `pom.xml` file: @@ -55,88 +55,74 @@ Alternatively, you can create a Java client by using the `RestClient`-based tran org.opensearch.client opensearch-java - 2.6.0 + 3.10.0 ``` {% include copy.html %} -If you're using Gradle, add the following dependencies to your project" +If you're using Gradle, add the following dependencies to your project: -``` +```groovy dependencies { implementation 'org.opensearch.client:opensearch-rest-client:{{site.opensearch_version}}' - implementation 'org.opensearch.client:opensearch-java:2.6.0' + implementation 'org.opensearch.client:opensearch-java:3.10.0' } ``` {% include copy.html %} You can now start your OpenSearch cluster. -## Security - -Before using the REST client in your Java application, you must configure the application's truststore to connect to the Security plugin. If you are using self-signed certificates or demo configurations, you can use the following command to create a custom truststore and add in root authority certificates. - -If you're using certificates from a trusted Certificate Authority (CA), you don't need to configure the truststore. - -```bash -keytool -import -alias -keystore -``` -{% include copy.html %} - -You can now point your Java client to the truststore and set basic authentication credentials that can access a secure cluster (refer to the sample code below on how to do so). - -If you run into issues when configuring security, see [common issues]({{site.url}}{{site.baseurl}}/troubleshoot/index) and [troubleshoot TLS]({{site.url}}{{site.baseurl}}/troubleshoot/tls). - ## Sample data -This section uses a class called `IndexData`, which is a simple Java class that stores basic data and methods. For your own OpenSearch cluster, you might find that you need a more robust class to store your data. - -### IndexData class +The sample programs in the following sections use a `Student` class to represent documents. Use the following wrapper class, which declares `gpa` as a boxed `Double` so that partial updates serialize correctly: ```java -static class IndexData { +public class Student { private String firstName; private String lastName; + private Double gpa; + private String gradDate; - public IndexData(String firstName, String lastName) { + public Student() {} + + public Student(String firstName, String lastName, double gpa, String gradDate) { this.firstName = firstName; this.lastName = lastName; + this.gpa = gpa; + this.gradDate = gradDate; } - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } + public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + public Double getGpa() { return gpa; } + public void setGpa(Double gpa) { this.gpa = gpa; } + public String getGradDate() { return gradDate; } + public void setGradDate(String gradDate) { this.gradDate = gradDate; } @Override public String toString() { - return String.format("IndexData{first name='%s', last name='%s'}", firstName, lastName); + return String.format("Student{firstName='%s', lastName='%s', gpa=%s, gradDate=%s}", + firstName, lastName, gpa, gradDate); } } ``` {% include copy.html %} -## Initializing the client with SSL and TLS enabled using Apache HttpClient 5 Transport +## Connecting to OpenSearch -This code example uses basic credentials that come with the default OpenSearch configuration. If you’re using the Java client with your own OpenSearch cluster, be sure to change the code so that it uses your own credentials. +The following examples connect to a cluster that has the Security plugin enabled using either the Apache HttpClient 5 transport or the deprecated RestClient transport. + +### Using Apache HttpClient 5 Transport + +This code example uses the `admin` user. Replace `` with the admin password that you set when you installed OpenSearch. The following sample code initializes a client with SSL and TLS enabled: ```java import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; import org.apache.hc.client5.http.auth.AuthScope; import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; @@ -144,10 +130,8 @@ import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; -import org.apache.hc.core5.function.Factory; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.nio.ssl.TlsStrategy; -import org.apache.hc.core5.reactor.ssl.TlsDetails; import org.apache.hc.core5.ssl.SSLContextBuilder; import org.opensearch.client.opensearch.OpenSearchClient; import org.opensearch.client.transport.OpenSearchTransport; @@ -155,14 +139,12 @@ import org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBui public class OpenSearchClientExample { public static void main(String[] args) throws Exception { - System.setProperty("javax.net.ssl.trustStore", "/full/path/to/keystore"); - System.setProperty("javax.net.ssl.trustStorePassword", "password-to-keystore"); - final HttpHost host = new HttpHost("https", "localhost", 9200); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Only for demo purposes. Don't specify your credentials in code. - credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "admin".toCharArray())); + credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "".toCharArray())); + // Trusts all certificates, including self-signed certificates. For testing only. Don't use in production. final SSLContext sslcontext = SSLContextBuilder .create() .loadTrustMaterial(null, (chains, authType) -> true) @@ -172,13 +154,6 @@ public class OpenSearchClientExample { builder.setHttpClientConfigCallback(httpClientBuilder -> { final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create() .setSslContext(sslcontext) - // See https://issues.apache.org/jira/browse/HTTPCLIENT-2219 - .setTlsDetailsFactory(new Factory() { - @Override - public TlsDetails create(final SSLEngine sslEngine) { - return new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol()); - } - }) .build(); final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder @@ -195,21 +170,35 @@ public class OpenSearchClientExample { OpenSearchClient client = new OpenSearchClient(transport); } } - ``` +{% include copy.html %} -## Initializing the client with SSL and TLS enabled using RestClient Transport +If you run into issues when configuring security, see [Troubleshooting TLS]({{site.url}}{{site.baseurl}}/security/configuration/troubleshoot-tls/). -This code example uses basic credentials that come with the default OpenSearch configuration. If you’re using the Java client with your own OpenSearch cluster, be sure to change the code so that it uses your own credentials. +### Using RestClient Transport (deprecated) -The following sample code initializes a client with SSL and TLS enabled: +The `RestClientTransport` transport and the `org.opensearch.client.RestClient` class that it wraps are deprecated and will be removed in a future release. Use [Apache HttpClient 5 Transport](#using-apache-httpclient-5-transport) instead. +{: .warning} + +This code example uses the `admin` user. Replace `` with the admin password that you set when you installed OpenSearch. + +The RestClient transport uses the Java truststore to validate the cluster's certificate. If you are using self-signed certificates or demo certificates, create a truststore that contains the root certificate authority (CA) certificate using the following command. When prompted, enter a password for the truststore: + +```bash +keytool -importcert -file -alias -keystore +``` +{% include copy.html %} + +If you're using certificates from a trusted CA, you don't need to configure the truststore. + +In the following code, replace `/full/path/to/keystore` with the path to your truststore and `password-to-keystore` with the truststore password. The following sample code initializes a client with SSL and TLS enabled: ```java -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; -import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; import org.opensearch.client.RestClient; import org.opensearch.client.RestClientBuilder; import org.opensearch.client.json.jackson.JacksonJsonpMapper; @@ -225,7 +214,7 @@ public class OpenSearchClientExample { final HttpHost host = new HttpHost("https", "localhost", 9200); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); //Only for demo purposes. Don't specify your credentials in code. - credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "admin".toCharArray())); + credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "".toCharArray())); //Initialize the client with SSL and TLS enabled final RestClient restClient = RestClient.builder(host). @@ -245,17 +234,57 @@ public class OpenSearchClientExample { ## Connecting to Amazon OpenSearch Service -The following example illustrates connecting to Amazon OpenSearch Service: +To connect to Amazon OpenSearch Service or Amazon OpenSearch Serverless, use `AwsSdk2Transport`, which signs requests using the AWS SDK for Java 2.x. Add the AWS SDK HTTP client and authentication modules to your `pom.xml` file in addition to `opensearch-java`: + +```xml + + software.amazon.awssdk + aws-crt-client + 2.55.9 + + + + software.amazon.awssdk + auth + 2.55.9 + +``` +{% include copy.html %} + +If you're using Gradle, add the following dependencies to your project: + +```groovy +dependencies { + implementation 'software.amazon.awssdk:aws-crt-client:2.55.9' + implementation 'software.amazon.awssdk:auth:2.55.9' +} +``` +{% include copy.html %} + +The examples use `AwsCrtHttpClient`. Avoid `ApacheHttpClient` from the AWS SDK because it does not support request bodies in `GET` or `DELETE` requests, so `AwsSdk2Transport` throws a `TransportException` for operations such as `clearScroll()` and `deletePit()`. +{: .note} + +In the following example, replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console. + +`AwsSdk2Transport` obtains AWS credentials from the AWS SDK default credentials provider chain. The following example illustrates connecting to Amazon OpenSearch Service: ```java -SdkHttpClient httpClient = ApacheHttpClient.builder().build(); +import org.opensearch.client.opensearch.OpenSearchClient; +import org.opensearch.client.opensearch.core.InfoResponse; +import org.opensearch.client.transport.aws.AwsSdk2Transport; +import org.opensearch.client.transport.aws.AwsSdk2TransportOptions; +import software.amazon.awssdk.http.SdkHttpClient; +import software.amazon.awssdk.http.crt.AwsCrtHttpClient; +import software.amazon.awssdk.regions.Region; + +SdkHttpClient httpClient = AwsCrtHttpClient.builder().build(); OpenSearchClient client = new OpenSearchClient( new AwsSdk2Transport( httpClient, - "search-...us-west-2.es.amazonaws.com", // OpenSearch endpoint, without https:// + "search--.us-east-1.es.amazonaws.com", // OpenSearch endpoint, without https:// "es", - Region.US_WEST_2, // signing service region + Region.US_EAST_1, // signing service region AwsSdk2TransportOptions.builder().build() ) ); @@ -269,79 +298,182 @@ httpClient.close(); ## Connecting to Amazon OpenSearch Serverless -The following example illustrates connecting to Amazon OpenSearch Serverless Service: +In the following example, replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console. + +The following example illustrates connecting to Amazon OpenSearch Serverless. Because Amazon OpenSearch Serverless does not support the root endpoint, the example checks whether an index exists: ```java -SdkHttpClient httpClient = ApacheHttpClient.builder().build(); +import org.opensearch.client.opensearch.OpenSearchClient; +import org.opensearch.client.transport.aws.AwsSdk2Transport; +import org.opensearch.client.transport.aws.AwsSdk2TransportOptions; +import software.amazon.awssdk.http.SdkHttpClient; +import software.amazon.awssdk.http.crt.AwsCrtHttpClient; +import software.amazon.awssdk.regions.Region; + +SdkHttpClient httpClient = AwsCrtHttpClient.builder().build(); OpenSearchClient client = new OpenSearchClient( new AwsSdk2Transport( httpClient, - "search-...us-west-2.aoss.amazonaws.com", // OpenSearch endpoint, without https:// - "aoss" - Region.US_WEST_2, // signing service region + ".us-east-1.aoss.amazonaws.com", // OpenSearch Serverless collection endpoint, without https:// + "aoss", + Region.US_EAST_1, // signing service region AwsSdk2TransportOptions.builder().build() ) ); -InfoResponse info = client.info(); -System.out.println(info.version().distribution() + ": " + info.version().number()); +boolean exists = client.indices().exists(e -> e.index("students")).value(); +System.out.println("Index exists: " + exists); httpClient.close(); ``` {% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} -## Creating an index +## Creating an index -You can create an index with non-default settings using the following code: +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```java -String index = "sample-index"; -CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).build(); +String index = "students"; +CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder() + .index(index) + .settings(s -> s + .numberOfShards(1) + .numberOfReplicas(1)) + .mappings(m -> m + .properties("gradDate", p -> p.date(d -> d.format("yyyy-MM-dd")))) + .build(); client.indices().create(createIndexRequest); - -IndexSettings indexSettings = new IndexSettings.Builder().autoExpandReplicas("0-all").build(); -PutIndicesSettingsRequest putIndicesSettingsRequest = new PutIndicesSettingsRequest.Builder().index(index).value(indexSettings).build(); -client.indices().putSettings(putIndicesSettingsRequest); ``` {% include copy.html %} -## Indexing data +## Indexing a document -You can index data into OpenSearch using the following code: +Index a document using the following code: ```java -IndexData indexData = new IndexData("first_name", "Bruce"); -IndexRequest indexRequest = new IndexRequest.Builder().index(index).id("1").document(indexData).build(); -client.index(indexRequest); +Student student = new Student("John", "Doe", 3.89, "2022-05-15"); +IndexRequest indexRequest = new IndexRequest.Builder() + .index(index).id("1").document(student).refresh(Refresh.True).build(); +IndexResponse indexResponse = client.index(indexRequest); +``` +{% include copy.html %} + +## Bulk indexing + +Index multiple documents in a single request using the following code: + +```java +List operations = new ArrayList<>(); +operations.add(new BulkOperation.Builder().index( + new IndexOperation.Builder() + .index(index).id("2") + .document(new Student("Paulo", "Santos", 3.93, "2021-05-20")).build() +).build()); +operations.add(new BulkOperation.Builder().index( + new IndexOperation.Builder() + .index(index).id("3") + .document(new Student("Shirley", "Rodriguez", 3.91, "2019-05-10")).build() +).build()); +BulkRequest bulkRequest = new BulkRequest.Builder() + .index(index).operations(operations).refresh(Refresh.True).build(); +BulkResponse bulkResponse = client.bulk(bulkRequest); ``` {% include copy.html %} ## Searching for documents -You can search for a document using the following code: +Search for all documents in an index using the following code: ```java -SearchResponse searchResponse = client.search(s -> s.index(index), IndexData.class); -for (int i = 0; i< searchResponse.hits().hits().size(); i++) { +SearchResponse searchResponse = client.search(s -> s.index(index), Student.class); +for (int i = 0; i < searchResponse.hits().hits().size(); i++) { System.out.println(searchResponse.hits().hits().get(i).source()); } ``` {% include copy.html %} -## Deleting a document - -The following sample code deletes a document whose ID is 1: +Each hit in `searchResponse.hits().hits()` is a `Hit` object that contains the document ID in `hit.id()` and the `Student` object in `hit.source()`, whose fields are available through getters. To use the `Hit` class, import `org.opensearch.client.opensearch.core.search.Hit`: ```java -client.delete(b -> b.index(index).id("1")); +for (Hit hit : searchResponse.hits().hits()) { + Student student = hit.source(); + System.out.println("ID: " + hit.id() + ", name: " + student.getFirstName() + " " + student.getLastName() + + ", GPA: " + student.getGpa() + ", graduation date: " + student.getGradDate()); +} ``` {% include copy.html %} -### Deleting an index +Search using a range query. The `gte` and `lte` bounds take `JsonData` values, so import `org.opensearch.client.json.JsonData`: -The following sample code deletes an index: +```java +SearchResponse searchResponse = client.search(s -> s + .index(index) + .query(q -> q.range(r -> r + .field("gradDate") + .gte(JsonData.of("2019-01-01")) + .lte(JsonData.of("2019-12-31")))), + Student.class); +``` +{% include copy.html %} + +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page. To use the `SortOrder` enum, import `org.opensearch.client.opensearch._types.SortOrder`: + +```java +SearchResponse firstPageResponse = client.search(s -> s + .index(index) + .from(0) + .size(2) + .sort(so -> so.field(f -> f.field("gradDate").order(SortOrder.Asc))), + Student.class); +for (int i = 0; i < firstPageResponse.hits().hits().size(); i++) { + System.out.println(firstPageResponse.hits().hits().get(i).source()); +} + +SearchResponse nextPageResponse = client.search(s -> s + .index(index) + .from(2) + .size(2) + .sort(so -> so.field(f -> f.field("gradDate").order(SortOrder.Asc))), + Student.class); +for (int i = 0; i < nextPageResponse.hits().hits().size(); i++) { + System.out.println(nextPageResponse.hits().hits().get(i).source()); +} +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +## Updating a document + +Update a document using a partial document object. Fields set to `null` are not sent, so only the specified fields are updated: + +```java +Student updatedFields = new Student(); +updatedFields.setGpa(3.92); +UpdateRequest updateRequest = new UpdateRequest.Builder() + .index(index).id("1").doc(updatedFields).build(); +UpdateResponse updateResponse = client.update(updateRequest, Student.class); +``` +{% include copy.html %} + +## Deleting a document + +Delete a document using the following code: + +```java +client.delete(b -> b.index(index).id("3").refresh(Refresh.True)); +``` +{% include copy.html %} + +## Deleting an index + +Delete an index using the following code: ```java DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(index).build(); @@ -351,92 +483,230 @@ DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexReq ## Sample program -The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index: +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. Before running the sample program, make sure that you have the `Student` class defined in your project. Make sure to change the credentials to match your cluster configuration. + +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```java -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; -import org.opensearch.client.RestClient; -import org.opensearch.client.RestClientBuilder; -import org.opensearch.client.base.RestClientTransport; -import org.opensearch.client.base.Transport; -import org.opensearch.client.json.jackson.JacksonJsonpMapper; +import javax.net.ssl.SSLContext; + +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.nio.ssl.TlsStrategy; +import org.apache.hc.core5.ssl.SSLContextBuilder; +import org.opensearch.client.json.JsonData; import org.opensearch.client.opensearch.OpenSearchClient; -import org.opensearch.client.opensearch._global.IndexRequest; -import org.opensearch.client.opensearch._global.IndexResponse; -import org.opensearch.client.opensearch._global.SearchResponse; +import org.opensearch.client.opensearch._types.Refresh; +import org.opensearch.client.opensearch._types.SortOrder; +import org.opensearch.client.opensearch.core.IndexRequest; +import org.opensearch.client.opensearch.core.IndexResponse; +import org.opensearch.client.opensearch.core.SearchResponse; +import org.opensearch.client.opensearch.core.UpdateRequest; +import org.opensearch.client.opensearch.core.UpdateResponse; +import org.opensearch.client.opensearch.core.GetResponse; +import org.opensearch.client.opensearch.core.BulkRequest; +import org.opensearch.client.opensearch.core.BulkResponse; +import org.opensearch.client.opensearch.core.DeleteResponse; +import org.opensearch.client.opensearch.core.bulk.BulkOperation; +import org.opensearch.client.opensearch.core.bulk.IndexOperation; import org.opensearch.client.opensearch.indices.*; -import org.opensearch.client.opensearch.indices.put_settings.IndexSettingsBody; +import org.opensearch.client.transport.OpenSearchTransport; +import org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBuilder; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class OpenSearchClientExample { - public static void main(String[] args) { - RestClient restClient = null; - try{ - System.setProperty("javax.net.ssl.trustStore", "/full/path/to/keystore"); - System.setProperty("javax.net.ssl.trustStorePassword", "password-to-keystore"); + public static void main(String[] args) throws Exception { + final HttpHost host = new HttpHost("https", "localhost", 9200); // Without security, use new HttpHost("http", "localhost", 9200) + final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Without security, remove this line + // Without security, remove this line + credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "".toCharArray())); - //Only for demo purposes. Don't specify your credentials in code. - final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(AuthScope.ANY, - new UsernamePasswordCredentials("admin", "admin")); + final SSLContext sslcontext = SSLContextBuilder.create() + .loadTrustMaterial(null, (chains, authType) -> true) + .build(); - //Initialize the client with SSL and TLS enabled - restClient = RestClient.builder(new HttpHost("localhost", 9200, "https")). - setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { - @Override - public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { - return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); - } - }).build(); - Transport transport = new RestClientTransport(restClient, new JacksonJsonpMapper()); - OpenSearchClient client = new OpenSearchClient(transport); + final ApacheHttpClient5TransportBuilder builder = ApacheHttpClient5TransportBuilder.builder(host); + builder.setHttpClientConfigCallback(httpClientBuilder -> { + final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create() + .setSslContext(sslcontext) + .build(); - //Create the index - String index = "sample-index"; - CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).build(); - client.indices().create(createIndexRequest); + final PoolingAsyncClientConnectionManager connectionManager = + PoolingAsyncClientConnectionManagerBuilder.create() + .setTlsStrategy(tlsStrategy) + .build(); - //Add some settings to the index - IndexSettings indexSettings = new IndexSettings.Builder().autoExpandReplicas("0-all").build(); - IndexSettingsBody settingsBody = new IndexSettingsBody.Builder().settings(indexSettings).build(); - PutSettingsRequest putSettingsRequest = new PutSettingsRequest.Builder().index(index).value(settingsBody).build(); - client.indices().putSettings(putSettingsRequest); + return httpClientBuilder + .setDefaultCredentialsProvider(credentialsProvider) // Without security, remove this line + .setConnectionManager(connectionManager); + }); - //Index some data - IndexData indexData = new IndexData("first_name", "Bruce"); - IndexRequest indexRequest = new IndexRequest.Builder().index(index).id("1").document(indexData).build(); - client.index(indexRequest); + final OpenSearchTransport transport = builder.build(); + final OpenSearchClient client = new OpenSearchClient(transport); - //Search for the document - SearchResponse searchResponse = client.search(s -> s.index(index), IndexData.class); - for (int i = 0; i< searchResponse.hits().hits().size(); i++) { - System.out.println(searchResponse.hits().hits().get(i).source()); + try { + // Create the index + String index = "students"; + System.out.println("Creating index......"); + CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder() + .index(index) + .settings(s -> s + .numberOfShards(1) + .numberOfReplicas(1)) + .mappings(m -> m + .properties("gradDate", p -> p.date(d -> d.format("yyyy-MM-dd")))) + .build(); + CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest); + System.out.println("Index created: " + createIndexResponse.index()); + + // Index a document + System.out.println("\nIndexing one student......"); + Student student = new Student("John", "Doe", 3.89, "2022-05-15"); + IndexRequest indexRequest = new IndexRequest.Builder() + .index(index).id("1").document(student).refresh(Refresh.True).build(); + IndexResponse indexResponse = client.index(indexRequest); + System.out.println("Result: " + indexResponse.result().jsonValue() + ", id: " + indexResponse.id() + ", version: " + indexResponse.version()); + + // Bulk index documents + System.out.println("\nIndexing many students......"); + List operations = new ArrayList<>(); + operations.add(new BulkOperation.Builder().index( + new IndexOperation.Builder() + .index(index).id("2") + .document(new Student("Paulo", "Santos", 3.93, "2021-05-20")).build() + ).build()); + operations.add(new BulkOperation.Builder().index( + new IndexOperation.Builder() + .index(index).id("3") + .document(new Student("Shirley", "Rodriguez", 3.91, "2019-05-10")).build() + ).build()); + BulkRequest bulkRequest = new BulkRequest.Builder() + .index(index).operations(operations).refresh(Refresh.True).build(); + BulkResponse bulkResponse = client.bulk(bulkRequest); + System.out.println("Errors: " + bulkResponse.errors()); + bulkResponse.items().forEach(item -> + System.out.println(" " + item.result() + " id: " + item.id())); + + // Search for all students + System.out.println("\nSearching for all students......"); + SearchResponse searchResponse = client.search(s -> s + .index(index) + .from(0) + .size(2) + .sort(so -> so.field(f -> f.field("gradDate").order(SortOrder.Asc))), + Student.class); + System.out.println("Total hits: " + searchResponse.hits().total().value()); + System.out.println("Page 1:"); + for (int i = 0; i < searchResponse.hits().hits().size(); i++) { + System.out.println(" " + searchResponse.hits().hits().get(i).source()); + } + SearchResponse nextPageResponse = client.search(s -> s + .index(index) + .from(2) + .size(2) + .sort(so -> so.field(f -> f.field("gradDate").order(SortOrder.Asc))), + Student.class); + System.out.println("Page 2:"); + for (int i = 0; i < nextPageResponse.hits().hits().size(); i++) { + System.out.println(" " + nextPageResponse.hits().hits().get(i).source()); } - //Delete the document - client.delete(b -> b.index(index).id("1")); + // Search for students who graduated in 2019 + System.out.println("\nSearching for students who graduated in 2019......"); + SearchResponse searchResponse2 = client.search(s -> s + .index(index) + .query(q -> q.range(r -> r + .field("gradDate") + .gte(JsonData.of("2019-01-01")) + .lte(JsonData.of("2019-12-31")))), + Student.class); + System.out.println("Total hits: " + searchResponse2.hits().total().value()); + for (int i = 0; i < searchResponse2.hits().hits().size(); i++) { + System.out.println(" " + searchResponse2.hits().hits().get(i).source()); + } + + // Update a document + System.out.println("\nUpdating a student's GPA......"); + Student updatedFields = new Student(); + updatedFields.setGpa(3.92); + UpdateRequest updateRequest = new UpdateRequest.Builder() + .index(index).id("1").doc(updatedFields).build(); + UpdateResponse updateResponse = client.update(updateRequest, Student.class); + System.out.println("Result: " + updateResponse.result().jsonValue() + ", version: " + updateResponse.version()); + + // Get the updated document + GetResponse getResponse = client.get(g -> g.index(index).id("1"), Student.class); + System.out.println("Updated document: " + getResponse.source()); + + // Delete a document + System.out.println("\nDeleting a student......"); + DeleteResponse deleteResponse = client.delete(b -> b.index(index).id("3").refresh(Refresh.True)); + System.out.println("Result: " + deleteResponse.result().jsonValue()); // Delete the index - DeleteIndexRequest deleteIndexRequest = new DeleteRequest.Builder().index(index).build(); + System.out.println("\nDeleting the index......"); + DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(index).build(); DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest); - } catch (IOException e){ - System.out.println(e.toString()); + System.out.println("Acknowledged: " + deleteIndexResponse.acknowledged()); + } finally { - try { - if (restClient != null) { - restClient.close(); - } - } catch (IOException e) { - System.out.println(e.toString()); - } + transport.close(); } } } ``` {% include copy.html %} + +The program produces the following output: + +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} + Student{firstName='Paulo', lastName='Santos', gpa=3.93, gradDate=2021-05-20} +Page 2: + Student{firstName='John', lastName='Doe', gpa=3.89, gradDate=2022-05-15} + +Searching for students who graduated in 2019...... +Total hits: 1 + Student{firstName='Shirley', lastName='Rodriguez', gpa=3.91, gradDate=2019-05-10} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: Student{firstName='John', lastName='Doe', gpa=3.92, gradDate=2022-05-15} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- For more examples of using the client, see the [`opensearch-java` user guide](https://github.com/opensearch-project/opensearch-java/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-java` guides](https://github.com/opensearch-project/opensearch-java/tree/main/guides). +- For complete sample applications, see the [`opensearch-java` samples](https://github.com/opensearch-project/opensearch-java/tree/main/samples). diff --git a/_clients/javascript/helpers.md b/_clients/javascript/helpers.md index f88efd8e..85738515 100644 --- a/_clients/javascript/helpers.md +++ b/_clients/javascript/helpers.md @@ -5,13 +5,13 @@ parent: JavaScript client nav_order: 2 --- -# Helper methods +# JavaScript helper methods -Helper methods simplify the use of complicated API tasks. For the client's complete API documentation and additional examples, see the [JS client API documentation](https://opensearch-project.github.io/opensearch-js/2.2/index.html). +JavaScript helper methods simplify the use of complicated API tasks. For complete helper documentation, see the [`opensearch-js` guides](https://github.com/opensearch-project/opensearch-js/tree/main/guides). ## Bulk helper -The bulk helper simplifies making complex bulk API requests. The bulk helper supports operations of the same kind. Alternatively, you can use the `client.bulk` method to perform multiple types of bulk operations. For example, you can send `delete` and `index` operations in one bulk request. For more information, see the [Bulk guide](https://github.com/opensearch-project/opensearch-js/blob/main/guides/bulk.md). +The bulk helper simplifies making complex bulk API requests. It splits the documents in the data source into batches, sends each batch to the Bulk API, and retries failed operations. Because the `onDocument` function returns the operation for each document, one call can combine `index`, `create`, `update`, and `delete` operations. To send a bulk request body that you construct yourself, use the `client.bulk` method. For more information, see the [Bulk guide](https://github.com/opensearch-project/opensearch-js/blob/main/guides/bulk.md). ### Usage @@ -44,25 +44,26 @@ Bulk helper operations return an object with the following fields: failed: number, retry: number, successful: number, + noop: number, time: number, bytes: number, aborted: boolean } ``` -#### Bulk helper configuration options +### Bulk helper configuration options When creating a new bulk helper instance, you can use the following configuration options. | Option | Data type | Required/Default | Description | :--- | :--- | :--- | :--- -| `datasource` | An array, async generator or a readable stream of strings or objects | Required | Represents the documents you need to create, delete, index, or update. +| `datasource` | An array, asynchronous generator, or a readable stream of strings or objects | Required | Represents the documents you need to create, delete, index, or update. | `onDocument` | Function | Required | A function to be invoked with each document in the given `datasource`. It returns the operation to be executed for this document. Optionally, the document can be manipulated for `create` and `index` operations by returning a new document as part of the function's result. | `concurrency` | Integer | Optional. Default is 5. | The number of requests to be executed in parallel. | `flushBytes` | Integer | Optional. Default is 5,000,000. | Maximum bulk body size to send in bytes. | `flushInterval` | Integer | Optional. Default is 30,000. | Time in milliseconds to wait before flushing the body after the last document has been read. | `onDrop` | Function | Optional. Default is `noop`. | A function to be invoked for every document that can’t be indexed after reaching the maximum number of retries. -| `refreshOnCompletion` | Boolean | Optional. Default is false. | Whether or not a refresh should be run on all affected indexes at the end of the bulk operation. +| `refreshOnCompletion` | Boolean or string | Optional. Default is `false`. | Whether a refresh should be run at the end of the bulk operation. Set to `true` to refresh all indexes or to an index name to refresh only that index. | `retries` | Integer | Optional. Defaults to the client's `maxRetries` value. | The number of times an operation is retried before `onDrop` is called for that document. | `wait` | Integer | Optional. Default is 5,000. | Time in milliseconds to wait before retrying an operation. @@ -144,7 +145,7 @@ client.helpers.bulk({ The update operation updates the document with the fields being sent. The document must already exist in the index. -The following bulk operation updates documents in the `arrayOfDocuments`: +The following bulk operation updates documents in `example-index`: ```javascript client.helpers.bulk({ @@ -163,7 +164,7 @@ client.helpers.bulk({ ``` {% include copy.html %} -The following bulk operation updates documents in the `arrayOfDocuments` with document overwrite: +The following bulk operation updates documents in `example-index` with document overwrite: ```javascript client.helpers.bulk({ @@ -201,5 +202,7 @@ client.helpers.bulk({ ``` {% include copy.html %} -## Related articles -https://github.com/opensearch-project/opensearch-js/tree/main/guides +## Related documentation + +- For more helper documentation, such as that for indexing and multi-search, see the [`opensearch-js` guides](https://github.com/opensearch-project/opensearch-js/tree/main/guides). +- For complete sample applications, see the [`opensearch-js` samples](https://github.com/opensearch-project/opensearch-js/tree/main/samples). diff --git a/_clients/javascript/index.md b/_clients/javascript/index.md index 58e9f190..2f9a1681 100644 --- a/_clients/javascript/index.md +++ b/_clients/javascript/index.md @@ -2,6 +2,7 @@ layout: default title: JavaScript client has_children: true +has_toc: false nav_order: 40 redirect_from: - /clients/javascript/ @@ -9,13 +10,15 @@ redirect_from: # JavaScript client -The OpenSearch JavaScript (JS) client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from the browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster. For the client's complete API documentation and additional examples, see the [JS client API documentation](https://opensearch-project.github.io/opensearch-js/2.2/index.html). +The OpenSearch JavaScript (JS) client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from the browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster. For the client's complete API documentation and additional examples, see the [JS client API documentation](https://opensearch-project.github.io/opensearch-js/3.6/index.html). The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body. The example here demonstrates some basic operations like creating an index, adding documents, and searching your data. You can use helper methods to simplify the use of complicated API tasks. For more information, see [Helper methods]({{site.url}}{{site.baseurl}}/clients/javascript/helpers/). For more advanced index actions, see the [`opensearch-js` guides](https://github.com/opensearch-project/opensearch-js/tree/main/guides) in GitHub. -## Setup +## Installing the JavaScript client + +The client requires Node.js 14 or later. To add the client to your project, install it from [`npm`](https://www.npmjs.com): @@ -24,7 +27,7 @@ npm install @opensearch-project/opensearch ``` {% include copy.html %} -To install a specific major version of the client, run the following command: +To install a specific version of the client, run the following command: ```bash npm install @opensearch-project/opensearch@ @@ -88,6 +91,25 @@ var client = new Client({ ## Authenticating with Amazon OpenSearch Service: AWS Signature Version 4 +To sign requests using the AWS SDK for JavaScript V3, install the V3 credential provider package: + +```bash +npm install @aws-sdk/credential-provider-node +``` +{% include copy.html %} + +To sign requests using the AWS SDK for JavaScript V2, install the V2 SDK: + +```bash +npm install aws-sdk +``` +{% include copy.html %} + +The AWS SDK for JavaScript V2 reached end of support on September 8, 2025. For new applications, use the AWS SDK for JavaScript V3 examples in this section. +{: .note} + +In the following examples, replace the endpoint with your domain or collection endpoint, which is listed on the domain's or collection's details page in the Amazon OpenSearch Service console. + Use the following code to authenticate with AWS V2 SDK: ```javascript @@ -97,13 +119,13 @@ const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); const client = new Client({ ...AwsSigv4Signer({ - region: 'us-west-2', + region: 'us-east-1', service: 'es', - // Must return a Promise that resolve to an AWS.Credentials object. - // This function is used to acquire the credentials when the client start and - // when the credentials are expired. - // The Client will refresh the Credentials only when they are expired. - // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials. + // Must return a Promise that resolves to an AWS.Credentials object. + // This function acquires the credentials when the client starts and + // when the credentials expire. + // The client refreshes the credentials only when they expire, using + // Credentials.refreshPromise when it is available. // Example with AWS SDK V2: getCredentials: () => @@ -118,7 +140,7 @@ const client = new Client({ }); }), }), - node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL + node: 'https://search--.us-east-1.es.amazonaws.com', // OpenSearch domain endpoint }); ``` {% include copy.html %} @@ -132,13 +154,13 @@ const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); const client = new Client({ ...AwsSigv4Signer({ - region: 'us-west-2', + region: 'us-east-1', service: 'aoss', - // Must return a Promise that resolve to an AWS.Credentials object. - // This function is used to acquire the credentials when the client start and - // when the credentials are expired. - // The Client will refresh the Credentials only when they are expired. - // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials. + // Must return a Promise that resolves to an AWS.Credentials object. + // This function acquires the credentials when the client starts and + // when the credentials expire. + // The client refreshes the credentials only when they expire, using + // Credentials.refreshPromise when it is available. // Example with AWS SDK V2: getCredentials: () => @@ -153,7 +175,7 @@ const client = new Client({ }); }), }), - node: "https://xxx.region.aoss.amazonaws.com" // OpenSearch domain URL + node: 'https://.us-east-1.aoss.amazonaws.com', // OpenSearch Serverless collection endpoint }); ``` {% include copy.html %} @@ -163,27 +185,30 @@ Use the following code to authenticate with AWS V3 SDK: ```javascript const { defaultProvider } = require('@aws-sdk/credential-provider-node'); // V3 SDK. const { Client } = require('@opensearch-project/opensearch'); -const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); +// Use the aws-v3 import path with the AWS SDK for JavaScript V3. It lazy loads +// only the V3 credential providers. +const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws-v3'); const client = new Client({ ...AwsSigv4Signer({ region: 'us-east-1', service: 'es', // 'aoss' for OpenSearch Serverless - // Must return a Promise that resolve to an AWS.Credentials object. - // This function is used to acquire the credentials when the client start and - // when the credentials are expired. - // The Client will refresh the Credentials only when they are expired. - // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials. + // Must return a Promise that resolves to a credentials object containing + // accessKeyId, secretAccessKey, and, optionally, sessionToken and expiration. + // This function acquires the credentials when the client starts and + // when the credentials expire. + // The client treats the credentials as expired if they are within + // requestTimeout milliseconds of expiration (the default is 30,000). // Example with AWS SDK V3: getCredentials: () => { - // Any other method to acquire a new Credentials object can be used. + // Any other credential provider that returns such a Promise can be used. const credentialsProvider = defaultProvider(); return credentialsProvider(); }, }), - node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL - // node: "https://xxx.region.aoss.amazonaws.com" for OpenSearch Serverless + node: 'https://search--.us-east-1.es.amazonaws.com', // OpenSearch domain endpoint + // node: 'https://.us-east-1.aoss.amazonaws.com' for an OpenSearch Serverless collection endpoint }); ``` {% include copy.html %} @@ -193,30 +218,36 @@ Use the following code to authenticate with the AWS V3 SDK for Amazon OpenSearch ```javascript const { defaultProvider } = require('@aws-sdk/credential-provider-node'); // V3 SDK. const { Client } = require('@opensearch-project/opensearch'); -const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); +// Use the aws-v3 import path with the AWS SDK for JavaScript V3. It lazy loads +// only the V3 credential providers. +const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws-v3'); const client = new Client({ ...AwsSigv4Signer({ region: 'us-east-1', service: 'aoss', - // Must return a Promise that resolve to an AWS.Credentials object. - // This function is used to acquire the credentials when the client start and - // when the credentials are expired. - // The Client will refresh the Credentials only when they are expired. - // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials. + // Must return a Promise that resolves to a credentials object containing + // accessKeyId, secretAccessKey, and, optionally, sessionToken and expiration. + // This function acquires the credentials when the client starts and + // when the credentials expire. + // The client treats the credentials as expired if they are within + // requestTimeout milliseconds of expiration (the default is 30,000). // Example with AWS SDK V3: getCredentials: () => { - // Any other method to acquire a new Credentials object can be used. + // Any other credential provider that returns such a Promise can be used. const credentialsProvider = defaultProvider(); return credentialsProvider(); }, }), - node: "https://xxx.region.aoss.amazonaws.com" // OpenSearch domain URL + node: 'https://.us-east-1.aoss.amazonaws.com', // OpenSearch Serverless collection endpoint }); ``` {% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} + ### Authenticating from within an AWS Lambda function Within an AWS Lambda function, objects declared outside the handler function retain their initialization. For more information, see [Lambda Execution Environment](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html). Thus, you must initialize the OpenSearch client outside of the handler function to ensure the reuse of the original connection in subsequent invocations. This promotes efficiency and eliminates the need to create a new connection each time. @@ -228,172 +259,211 @@ The following example AWS Lambda function code demonstrates the correct initiali ```javascript const { defaultProvider } = require('@aws-sdk/credential-provider-node'); // V3 SDK. const { Client } = require('@opensearch-project/opensearch'); -const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws'); +// Use the aws-v3 import path with the AWS SDK for JavaScript V3. It lazy loads +// only the V3 credential providers. +const { AwsSigv4Signer } = require('@opensearch-project/opensearch/aws-v3'); const client = new Client({ ...AwsSigv4Signer({ region: 'us-east-1', service: 'es', // 'aoss' for OpenSearch Serverless - // Must return a Promise that resolve to an AWS.Credentials object. - // This function is used to acquire the credentials when the client start and - // when the credentials are expired. - // The Client will refresh the Credentials only when they are expired. - // With AWS SDK V2, Credentials.refreshPromise is used when available to refresh the credentials. + // Must return a Promise that resolves to a credentials object containing + // accessKeyId, secretAccessKey, and, optionally, sessionToken and expiration. + // This function acquires the credentials when the client starts and + // when the credentials expire. + // The client treats the credentials as expired if they are within + // requestTimeout milliseconds of expiration (the default is 30,000). // Example with AWS SDK V3: getCredentials: () => { - // Any other method to acquire a new Credentials object can be used. + // Any other credential provider that returns such a Promise can be used. const credentialsProvider = defaultProvider(); return credentialsProvider(); }, }), - node: 'https://search-xxx.region.es.amazonaws.com', // OpenSearch domain URL - // node: "https://xxx.region.aoss.amazonaws.com" for OpenSearch Serverless + node: 'https://search--.us-east-1.es.amazonaws.com', // OpenSearch domain endpoint + // node: 'https://.us-east-1.aoss.amazonaws.com' for an OpenSearch Serverless collection endpoint }); -export const handler = async (event, context) => { - const indexName = "books"; - - const settings = { - settings: { - index: { - number_of_shards: 4, - number_of_replicas: 3, - }, - }, - }; - +exports.handler = async (event, context) => { // Use the already initialized client const response = await client.indices.create({ - index: indexName, - body: settings, + index: "students", }); + return response.body; }; ``` {% include copy.html %} - ## Creating an index -To create an OpenSearch index, use the `indices.create()` method. You can use the following code to construct a JSON object with custom settings: +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```javascript -var index_name = "books"; - -var settings = { - settings: { - index: { - number_of_shards: 4, - number_of_replicas: 3, - }, - }, -}; +var index_name = "students"; var response = await client.indices.create({ index: index_name, - body: settings, + body: { + settings: { + index: { + number_of_shards: 1, + number_of_replicas: 1, + }, + }, + mappings: { + properties: { + gradDate: { type: "date", format: "yyyy-MM-dd" }, + }, + }, + }, }); ``` {% include copy.html %} ## Indexing a document -You can index a document into OpenSearch using the client's `index` method: +Index a document into OpenSearch using the client's `index` method: ```javascript -var document = { - title: "The Outsider", - author: "Stephen King", - year: "2018", - genre: "Crime fiction", -}; - -var id = "1"; +var student = { firstName: "John", lastName: "Doe", gpa: 3.89, gradDate: "2022-05-15" }; var response = await client.index({ - id: id, index: index_name, - body: document, + id: "1", + body: student, refresh: true, }); ``` {% include copy.html %} -## Searching for documents +## Bulk indexing -The easiest way to search for documents is to construct a query string. The following code uses a `match` query to search for "The Outsider" in the title field: +Index multiple documents in one request using the client's `bulk` method. The request body is an array in which each action is followed by the document that it applies to: ```javascript -var query = { - query: { - match: { - title: { - query: "The Outsider", +var response = await client.bulk({ + body: [ + { index: { _index: index_name, _id: "2" } }, + { firstName: "Paulo", lastName: "Santos", gpa: 3.93, gradDate: "2021-05-20" }, + { index: { _index: index_name, _id: "3" } }, + { firstName: "Shirley", lastName: "Rodriguez", gpa: 3.91, gradDate: "2019-05-10" }, + ], + refresh: true, +}); +``` +{% include copy.html %} + +To build the request body from an array, a stream, or an async generator, use the [bulk helper]({{site.url}}{{site.baseurl}}/clients/javascript/helpers/#bulk-helper). + +## Searching for documents + +Search for all documents in an index using the client's `search` method: + +```javascript +var response = await client.search({ + index: index_name, + body: { + query: { + match_all: {}, + }, + }, +}); +response.body.hits.hits.forEach((hit) => console.log(hit._source)); +``` +{% include copy.html %} + +Each item in `response.body.hits.hits` is a plain JavaScript object. The document ID is in the `_id` property, and the document fields are properties of the `_source` object: + +```javascript +response.body.hits.hits.forEach((hit) => { + console.log( + `ID: ${hit._id}, name: ${hit._source.firstName} ${hit._source.lastName}, GPA: ${hit._source.gpa}, graduation date: ${hit._source.gradDate}` + ); +}); +``` +{% include copy.html %} + +Search using a `range` query: + +```javascript +var response = await client.search({ + index: index_name, + body: { + query: { + range: { + gradDate: { + gte: "2019-01-01", + lte: "2019-12-31", + }, }, }, }, -}; - -var response = await client.search({ - index: index_name, - body: query, }); ``` {% include copy.html %} +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```javascript +var response = await client.search({ + index: index_name, + body: { + from: 0, + size: 2, + sort: [{ gradDate: "asc" }], + }, +}); +response.body.hits.hits.forEach((hit) => console.log(hit._source)); + +var nextPage = await client.search({ + index: index_name, + body: { + from: 2, + size: 2, + sort: [{ gradDate: "asc" }], + }, +}); +nextPage.body.hits.hits.forEach((hit) => console.log(hit._source)); +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + ## Updating a document -You can update a document using the client's `update` method: +Update a document using the client's `update` method. The `doc` object contains only the fields to update: ```javascript var response = await client.update({ index: index_name, - id: id, + id: "1", body: { - doc: { - // Specify the fields and their updated values here - field1: "new_value1", - field2: "new_value2", - // Add more fields as needed - } - } + doc: { gpa: 3.92 }, + }, }); ``` {% include copy.html %} -For example, the following code updates the `genre` field and adds a `tv_adapted` field to the document specified by `id`: - -```javascript -var response = await client.update({ - index: index_name, - id: id, - body: { - doc: { - genre: "Detective fiction", - tv_adapted: true - } - }, - refresh: true - }); -``` -{% include copy.html %} - ## Deleting a document -You can delete a document using the client's `delete` method: +Delete a document using the client's `delete` method: ```javascript var response = await client.delete({ index: index_name, - id: id, + id: "3", + refresh: true, }); ``` {% include copy.html %} ## Deleting an index -You can delete an index using the `indices.delete()` method: +Delete an index using the `indices.delete()` method: ```javascript var response = await client.indices.delete({ @@ -404,16 +474,22 @@ var response = await client.indices.delete({ ## Sample program -The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index: +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. + +This sample program is for testing only. It specifies credentials in code. In production, load credentials from a secure location. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```javascript "use strict"; var host = "localhost"; -var protocol = "https"; +var protocol = "https"; // Without security, use "http" var port = 9200; -var auth = "admin:"; // For testing only. Don't store credentials in code. -var ca_certs_path = "/full/path/to/root-ca.pem"; +// Without security, remove the following line +var auth = "admin:"; +var ca_certs_path = "/full/path/to/root-ca.pem"; // Without security, remove this line // Optional client certificates if you don't want to use HTTP basic authentication // var client_cert_path = '/full/path/to/client.pem' @@ -421,132 +497,185 @@ var ca_certs_path = "/full/path/to/root-ca.pem"; // Create a client with SSL/TLS enabled var { Client } = require("@opensearch-project/opensearch"); -var fs = require("fs"); +var fs = require("fs"); // Without security, remove this line var client = new Client({ + // Without security, use node: protocol + "://" + host + ":" + port, node: protocol + "://" + auth + "@" + host + ":" + port, - ssl: { + ssl: { // Without security, remove the ssl block ca: fs.readFileSync(ca_certs_path), - // You can turn off certificate verification (rejectUnauthorized: false) if you're using + // You can turn off certificate verification (rejectUnauthorized: false) if you're using // self-signed certificates with a hostname mismatch. // cert: fs.readFileSync(client_cert_path), // key: fs.readFileSync(client_key_path) }, }); -async function search() { - // Create an index with non-default settings - var index_name = "books"; - - var settings = { - settings: { - index: { - number_of_shards: 4, - number_of_replicas: 3, - }, - }, - }; - +async function main() { + // Create the index + var index_name = "students"; + console.log("Creating index......"); var response = await client.indices.create({ index: index_name, - body: settings, + body: { + settings: { + index: { + number_of_shards: 1, + number_of_replicas: 1, + }, + }, + mappings: { + properties: { + gradDate: { type: "date", format: "yyyy-MM-dd" }, + }, + }, + }, }); + console.log("Index created: " + response.body.index); - console.log("Creating index:"); - console.log(response.body); - - // Add a document to the index - var document = { - title: "The Outsider", - author: "Stephen King", - year: "2018", - genre: "Crime fiction", - }; - - var id = "1"; - - var response = await client.index({ - id: id, + // Index a document + console.log("\nIndexing one student......"); + var student = { firstName: "John", lastName: "Doe", gpa: 3.89, gradDate: "2022-05-15" }; + response = await client.index({ index: index_name, - body: document, + id: "1", + body: student, refresh: true, }); + console.log("Result: " + response.body.result + ", id: " + response.body._id + ", version: " + response.body._version); - console.log("Adding document:"); - console.log(response.body); + // Bulk index documents + console.log("\nIndexing many students......"); + response = await client.bulk({ + body: [ + { index: { _index: index_name, _id: "2" } }, + { firstName: "Paulo", lastName: "Santos", gpa: 3.93, gradDate: "2021-05-20" }, + { index: { _index: index_name, _id: "3" } }, + { firstName: "Shirley", lastName: "Rodriguez", gpa: 3.91, gradDate: "2019-05-10" }, + ], + refresh: true, + }); + console.log("Errors: " + response.body.errors); + response.body.items.forEach((item) => + console.log(" " + item.index.result + " id: " + item.index._id)); - // Search for the document - var query = { - query: { - match: { - title: { - query: "The Outsider", + // Search for all students + console.log("\nSearching for all students......"); + response = await client.search({ + index: index_name, + body: { + from: 0, + size: 2, + sort: [{ gradDate: "asc" }], + }, + }); + console.log("Total hits: " + response.body.hits.total.value); + console.log("Page 1:"); + response.body.hits.hits.forEach((hit) => console.log(" " + JSON.stringify(hit._source))); + response = await client.search({ + index: index_name, + body: { + from: 2, + size: 2, + sort: [{ gradDate: "asc" }], + }, + }); + console.log("Page 2:"); + response.body.hits.hits.forEach((hit) => console.log(" " + JSON.stringify(hit._source))); + + // Search for students who graduated in 2019 + console.log("\nSearching for students who graduated in 2019......"); + response = await client.search({ + index: index_name, + body: { + query: { + range: { + gradDate: { + gte: "2019-01-01", + lte: "2019-12-31", + }, }, }, }, - }; - - var response = await client.search({ - index: index_name, - body: query, }); - - console.log("Search results:"); - console.log(JSON.stringify(response.body.hits, null, " ")); + console.log("Total hits: " + response.body.hits.total.value); + response.body.hits.hits.forEach((hit) => console.log(" " + JSON.stringify(hit._source))); // Update a document - var response = await client.update({ + console.log("\nUpdating a student's GPA......"); + response = await client.update({ index: index_name, - id: id, + id: "1", body: { - doc: { - genre: "Detective fiction", - tv_adapted: true - } + doc: { gpa: 3.92 }, }, - refresh: true }); + console.log("Result: " + response.body.result + ", version: " + response.body._version); - // Search for the updated document - var query = { - query: { - match: { - title: { - query: "The Outsider", - }, - }, - }, - }; - - var response = await client.search({ + // Get the updated document + response = await client.get({ index: index_name, - body: query, + id: "1", }); + console.log("Updated document: " + JSON.stringify(response.body._source)); - console.log("Search results:"); - console.log(JSON.stringify(response.body.hits, null, " ")); - - // Delete the document - var response = await client.delete({ + // Delete a document + console.log("\nDeleting a student......"); + response = await client.delete({ index: index_name, - id: id, + id: "3", + refresh: true, }); - - console.log("Deleting document:"); - console.log(response.body); + console.log("Result: " + response.body.result); // Delete the index - var response = await client.indices.delete({ + console.log("\nDeleting the index......"); + response = await client.indices.delete({ index: index_name, }); - - console.log("Deleting index:"); - console.log(response.body); + console.log("Acknowledged: " + response.body.acknowledged); } -search().catch(console.log); +main().catch(console.log); ``` {% include copy.html %} +The program produces the following output: + +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + {"firstName":"Paulo","lastName":"Santos","gpa":3.93,"gradDate":"2021-05-20"} +Page 2: + {"firstName":"John","lastName":"Doe","gpa":3.89,"gradDate":"2022-05-15"} + +Searching for students who graduated in 2019...... +Total hits: 1 + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: {"firstName":"John","lastName":"Doe","gpa":3.92,"gradDate":"2022-05-15"} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + ## Circuit breaker The `memoryCircuitBreaker` option can be used to prevent errors caused by a response payload being too large to fit into the heap memory available to the client. @@ -567,3 +696,10 @@ var client = new Client({ }); ``` {% include copy.html %} + +## Related documentation + +- To index, update, and delete documents in bulk using the client's helper method, see [Helper methods]({{site.url}}{{site.baseurl}}/clients/javascript/helpers/). +- For more examples of using the client, see the [`opensearch-js` user guide](https://github.com/opensearch-project/opensearch-js/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-js` guides](https://github.com/opensearch-project/opensearch-js/tree/main/guides). +- For complete sample applications, see the [`opensearch-js` samples](https://github.com/opensearch-project/opensearch-js/tree/main/samples). diff --git a/_clients/opensearch-py-ml.md b/_clients/opensearch-py-ml.md index de3704b9..488e69b7 100644 --- a/_clients/opensearch-py-ml.md +++ b/_clients/opensearch-py-ml.md @@ -1,44 +1,236 @@ --- layout: default -title: Opensearch-py-ml -nav_order: 11 +title: Python ML client +parent: Python client +nav_order: 10 --- -# opensearch-py-ml +# Python machine learning client -`opensearch-py-ml` is a Python client that provides a suite of data analytics and natural language processing (NLP) support tools for OpenSearch. It provides data analysts with the ability to: +The Python machine learning (ML) client (`opensearch-py-ml`) is a Python library that you use together with the [Python client]({{site.url}}{{site.baseurl}}/clients/python-low-level/) (`opensearch-py`). It provides the following tools: -- Call OpenSearch indexes and manipulate them using the opensearch-py-ml [DataFrame](https://opensearch-project.github.io/opensearch-py-ml/reference/dataframe.html) APIs. The opensearch-py-ml DataFrame wraps an OpenSearch index into an API similar to [pandas](https://pandas.pydata.org/), giving you the ability to process large amounts of data from OpenSearch inside a Jupyter Notebook. -- Upload NLP [SentenceTransformer](https://www.sbert.net/) models into OpenSearch using the [ML Commons plugin]({{site.url}}{{site.baseurl}}/ml-commons-plugin/index/). -- Train and tune SentenceTransformer models with synthetic queries. +- DataFrames that represent OpenSearch indexes and support pandas-like operations, so that you can analyze data stored in OpenSearch. +- Methods for uploading ML models to the ML Commons plugin and managing them. -## Prerequisites +## Installing the Python ML client -To use `opensearch-py-ml`, install the [OpenSearch Python client]({{site.url}}{{site.baseurl}}/clients/python-low-level#setup). The Python client allows OpenSearch to use the Python syntax required to run DataFrames in `opensearch-py-ml`. - -## Install `opensearch-py-ml` - -To add the client to your project, install it using [pip](https://pip.pypa.io/): +The latest version of the client, `opensearch-py-ml` 1.3.0, requires Python 3.11 or later. To add the client to your project, install it using [pip](https://pip.pypa.io/): ```bash pip install opensearch-py-ml ``` {% include copy.html %} -Then import the client into OpenSearch like any other module: +Installing `opensearch-py-ml` also installs the Python client (`opensearch-py`), which you use to connect to OpenSearch. + +## Connecting to OpenSearch + +To connect to OpenSearch, create a Python client object and import `opensearch_py_ml`. If you are using the Security plugin, create the client object with SSL enabled. Replace `` with the admin password that you set when installing OpenSearch: ```python from opensearchpy import OpenSearch import opensearch_py_ml as oml + +host = 'localhost' +port = 9200 +auth = ('admin', '') # For testing only. Don't store credentials in code. +ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA. + +# Create the client with SSL/TLS enabled, but hostname verification disabled. +client = OpenSearch( + hosts = [{'host': host, 'port': port}], + http_compress = True, # enables gzip compression for request bodies + http_auth = auth, + use_ssl = True, + verify_certs = True, + ssl_assert_hostname = False, + ssl_show_warn = False, + ca_certs = ca_certs_path +) ``` {% include copy.html %} -## API reference +If you are not using the Security plugin, create the client object with SSL disabled: -For information on all opensearch-py-ml objects, functions, and methods, see the [opensearch-py-ml API reference](https://opensearch-project.github.io/opensearch-py-ml/reference/index.html). +```python +from opensearchpy import OpenSearch +import opensearch_py_ml as oml -## Next steps +host = 'localhost' +port = 9200 -If you want to track or contribute to the development of the `opensearch-py-ml` client, see the [opensearch-py-ml GitHub repository](https://github.com/opensearch-project/opensearch-py-ml). +# Create the client with SSL/TLS and hostname verification disabled. +client = OpenSearch( + hosts = [{'host': host, 'port': port}], + http_compress = True, # enables gzip compression for request bodies + use_ssl = False, + verify_certs = False, + ssl_assert_hostname = False, + ssl_show_warn = False +) +``` +{% include copy.html %} -For example Python notebooks to use with the client, see [Examples](https://opensearch-project.github.io/opensearch-py-ml/examples/index.html). +For more connection options, including connecting to Amazon OpenSearch Service, see [Python client]({{site.url}}{{site.baseurl}}/clients/python-low-level/). + +## Analyzing data with DataFrames + +An `opensearch-py-ml` DataFrame represents an OpenSearch index. When you select, filter, or aggregate data in a DataFrame, the client translates the operation into an OpenSearch request, so the data stays in the index until you need the results. + +First, use the Python client to index sample documents into a `students` index: + +```python +docs = [ + {"firstName": "John", "lastName": "Doe", "gpa": 3.89, "gradDate": "2022-05-15"}, + {"firstName": "Paulo", "lastName": "Santos", "gpa": 3.93, "gradDate": "2021-05-20"}, + {"firstName": "Shirley", "lastName": "Rodriguez", "gpa": 3.91, "gradDate": "2019-05-10"}, +] + +for doc_id, doc in enumerate(docs, start=1): + client.index(index="students", id=doc_id, body=doc, refresh=True) +``` +{% include copy.html %} + +Then create a DataFrame for the `students` index and display its first rows: + +```python +df = oml.DataFrame(client, "students") +print(df.head()) +``` +{% include copy.html %} + +The output contains one row for each document, indexed by document ID: + +``` + firstName gpa gradDate lastName +1 John 3.89 2022-05-15 Doe +2 Paulo 3.93 2021-05-20 Santos +3 Shirley 3.91 2019-05-10 Rodriguez + +[3 rows x 4 columns] +``` + +To calculate summary statistics for the numeric fields, use the `describe` method: + +```python +print(df.describe()) +``` +{% include copy.html %} + +The output contains statistics for the `gpa` field: + +``` + gpa +count 3.000000 +mean 3.910000 +std 0.024495 +min 3.890000 +25% 3.890000 +50% 3.910000 +75% 3.930000 +max 3.930000 +``` + +To filter documents and select columns, use pandas syntax. The following example returns the names and GPAs of students whose GPA is greater than 3.9: + +```python +print(df[df["gpa"] > 3.9][["firstName", "lastName", "gpa"]]) +``` +{% include copy.html %} + +The output contains the two matching students: + +``` + firstName lastName gpa +2 Paulo Santos 3.93 +3 Shirley Rodriguez 3.91 + +[2 rows x 3 columns] +``` + +To convert a DataFrame to a pandas DataFrame, use the `to_pandas` method. This method retrieves all matching documents from OpenSearch. + +For all DataFrame methods, see the [`opensearch-py-ml` DataFrame reference](https://opensearch-project.github.io/opensearch-py-ml/reference/dataframe.html). + +## Uploading a pretrained model + +Use the `MLCommonClient` class to register and deploy one of the [pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/) that OpenSearch provides. + +By default, ML Commons runs models only on dedicated ML nodes. If your cluster doesn't have dedicated ML nodes, allow models to run on data nodes: + +```python +client.cluster.put_settings(body={ + "persistent": { + "plugins.ml_commons.only_run_on_ml_node": "false" + } +}) +``` +{% include copy.html %} + +For more information, see [ML Commons cluster settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/). + +The following example registers and deploys the `huggingface/sentence-transformers/all-MiniLM-L6-v2` model. The method waits until the model is deployed and returns the model ID: + +```python +from opensearch_py_ml.ml_commons import MLCommonClient + +ml_client = MLCommonClient(client) + +model_id = ml_client.register_pretrained_model( + model_name="huggingface/sentence-transformers/all-MiniLM-L6-v2", + model_version="1.0.2", + model_format="TORCH_SCRIPT", + deploy_model=True, + wait_until_deployed=True +) +``` +{% include copy.html %} + +The method prints the model ID and the deployment task ID: + +``` +Model was registered successfully. Model Id: oVMj-aABo6RnaVqceH5b +oVMj-aABo6RnaVqceH5b +Task ID: olMj-aABo6RnaVqcuX7E +Model deployed successfully +``` + +Because the example doesn't specify a model group, ML Commons creates a model group for the model. To register the model in an existing model group, pass the model group ID in the `model_group_id` parameter. + +To generate an embedding using the deployed model, send the text to the model: + +```python +response = ml_client.generate_model_inference( + model_id, + {"text_docs": ["Paulo Santos graduated in 2021."], "target_response": ["sentence_embedding"]} +) +embedding = response["inference_results"][0]["output"][0] +print(embedding["shape"]) +print(embedding["data"][:3]) +``` +{% include copy.html %} + +The model returns a 384-dimensional embedding. The output contains the embedding dimensions and the first three values: + +``` +[384] +[-0.0007759315, 0.018069174, 0.014426488] +``` + +When you no longer need the model, undeploy it and delete it, along with its model group: + +```python +model_group_id = ml_client.get_model_info(model_id)["model_group_id"] +ml_client.undeploy_model(model_id) +ml_client.delete_model(model_id) +ml_client.model_access_control.delete_model_group(model_group_id) +``` +{% include copy.html %} + +## Related documentation + +- For the complete client documentation, see the [`opensearch-py-ml` documentation](https://opensearch-project.github.io/opensearch-py-ml/index.html). +- For the client API reference, see the [`opensearch-py-ml` API reference](https://opensearch-project.github.io/opensearch-py-ml/reference/index.html). +- For example Jupyter notebooks, see the [`opensearch-py-ml` examples](https://opensearch-project.github.io/opensearch-py-ml/examples/index.html). +- For the client source code, see the [`opensearch-py-ml` GitHub repository](https://github.com/opensearch-project/opensearch-py-ml). +- For more information about pretrained models, see [Pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/). diff --git a/_clients/php.md b/_clients/php.md index 785614c2..7aa14306 100644 --- a/_clients/php.md +++ b/_clients/php.md @@ -8,25 +8,39 @@ nav_order: 70 The OpenSearch PHP client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from a browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster. The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body. -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-php repo](https://github.com/opensearch-project/opensearch-php). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-php` repo](https://github.com/opensearch-project/opensearch-php). -## Setup +## Installing the PHP client -To add the client to your project, install it using [composer](https://getcomposer.org/): +The client requires PHP 8.2 or later. To add the client to your project, install it using [Composer](https://getcomposer.org/): ```bash composer require opensearch-project/opensearch-php ``` {% include copy.html %} -To install a specific major version of the client, run the following command: +To install a specific version of the client, run the following command: ```bash composer require opensearch-project/opensearch-php: ``` {% include copy.html %} -Then require the autload file from composer in your code: +The client sends requests through any HTTP client that implements [PSR-18](https://www.php-fig.org/psr/psr-18/), so you must also install one. To use [Guzzle](https://docs.guzzlephp.org/en/stable/), run the following command: + +```bash +composer require guzzlehttp/guzzle +``` +{% include copy.html %} + +To use the [Symfony HTTP client](https://symfony.com/doc/current/http_client.html), run the following command: + +```bash +composer require symfony/http-client +``` +{% include copy.html %} + +Then require the `autoload` file from `composer` in your code: ```php require __DIR__ . '/vendor/autoload.php'; @@ -35,217 +49,546 @@ require __DIR__ . '/vendor/autoload.php'; ## Connecting to OpenSearch -To connect to the default OpenSearch host, create a client object with the address `https://localhost:9200` if you are using the Security plugin: +Create a client using `GuzzleClientFactory` or `SymfonyClientFactory`. The `base_uri` option is required. The factory passes all other options to the underlying HTTP client. The following code connects to a cluster that does not have the Security plugin enabled: ```php -$client = (new \OpenSearch\ClientBuilder()) - ->setHosts(['https://localhost:9200']) - ->setBasicAuthentication('admin', 'admin') // For testing only. Don't store credentials in code. - ->setSSLVerification(false) // For testing only. Use certificate for validation - ->build(); +$client = (new \OpenSearch\GuzzleClientFactory())->create([ + 'base_uri' => 'http://localhost:9200', +]); ``` -{% include copy.html %} +{% include copy.html %} + +To connect to a cluster that has the Security plugin enabled, provide credentials and TLS options: + +```php +$client = (new \OpenSearch\GuzzleClientFactory())->create([ + 'base_uri' => 'https://localhost:9200', + // Only for demo purposes. Don't specify your credentials in code. + 'auth' => ['admin', ''], + 'verify' => false, // Disables TLS certificate verification. Use only for local development. +]); +``` +{% include copy.html %} + +The Symfony HTTP client accepts equivalent options: + +```php +$client = (new \OpenSearch\SymfonyClientFactory())->create([ + 'base_uri' => 'https://localhost:9200', + // Only for demo purposes. Don't specify your credentials in code. + 'auth_basic' => ['admin', ''], + 'verify_peer' => false, // Disables TLS certificate verification. Use only for local development. +]); +``` +{% include copy.html %} + +For more information about the supported PSR clients, see [Client factories](https://github.com/opensearch-project/opensearch-php/blob/main/USER_GUIDE.md#client-factories). For more information about basic authentication, see [Basic authentication using a PSR client](https://github.com/opensearch-project/opensearch-php/blob/main/guides/auth.md#using-a-psr-client). ## Connecting to Amazon OpenSearch Service -The following example illustrates connecting to Amazon OpenSearch Service: +To sign requests using AWS Identity and Access Management (IAM) credentials, install the AWS SDK for PHP: + +```bash +composer require aws/aws-sdk-php +``` +{% include copy.html %} + +In the following example, replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console. + +Then pass the `auth_aws` option when you create the client: ```php -$client = (new \OpenSearch\ClientBuilder()) - ->setSigV4Region('us-east-2') - - ->setSigV4Service('es') - - // Default credential provider. - ->setSigV4CredentialProvider(true) - - // Using a custom access key and secret - ->setSigV4CredentialProvider([ - 'key' => 'awskeyid', - 'secret' => 'awssecretkey', - ]) - - ->build(); +$client = (new \OpenSearch\GuzzleClientFactory())->create([ + 'base_uri' => 'https://search--.us-east-1.es.amazonaws.com', + 'auth_aws' => [ + 'region' => 'us-east-1', + 'service' => 'es', + ], +]); ``` -{% include copy.html %} +{% include copy.html %} + +Because the example does not specify `credentials`, the AWS SDK for PHP resolves credentials using the default credential provider chain. The chain checks environment variables, the shared AWS config and credentials files, and the IAM role of the Amazon EC2 instance or container in which the code runs. + +To pass credentials explicitly, add the `credentials` option. Specify `session_token` only when you use temporary credentials: + +```php +$client = (new \OpenSearch\GuzzleClientFactory())->create([ + 'base_uri' => 'https://search--.us-east-1.es.amazonaws.com', + 'auth_aws' => [ + 'region' => 'us-east-1', + 'service' => 'es', + 'credentials' => [ + 'access_key' => getenv('AWS_ACCESS_KEY_ID'), + 'secret_key' => getenv('AWS_SECRET_ACCESS_KEY'), + 'session_token' => getenv('AWS_SESSION_TOKEN'), + ], + ], +]); +``` +{% include copy.html %} + +For more information, see [IAM authentication using a PSR client](https://github.com/opensearch-project/opensearch-php/blob/main/guides/auth.md#using-a-psr-client-1). ## Connecting to Amazon OpenSearch Serverless -The following example illustrates connecting to Amazon OpenSearch Serverless Service: +In the following example, replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console. + +To connect to Amazon OpenSearch Serverless, set `service` to `aoss` and specify your collection endpoint. The following example checks whether an index exists: ```php -$client = (new \OpenSearch\ClientBuilder()) - ->setSigV4Region('us-east-2') +$client = (new \OpenSearch\GuzzleClientFactory())->create([ + 'base_uri' => 'https://.us-east-1.aoss.amazonaws.com', + 'auth_aws' => [ + 'region' => 'us-east-1', + 'service' => 'aoss', + ], +]); - ->setSigV4Service('aoss') - - // Default credential provider. - ->setSigV4CredentialProvider(true) - - // Using a custom access key and secret - ->setSigV4CredentialProvider([ - 'key' => 'awskeyid', - 'secret' => 'awssecretkey', - ]) - - ->build(); +$exists = $client->indices()->exists(['index' => 'students']); +echo $exists ? 'Index exists' : 'Index does not exist', PHP_EOL; ``` -{% include copy.html %} +{% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} ## Creating an index -To create an OpenSearch index with custom settings, use the following code: +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```php -$indexName = 'test-index-name'; +$index = 'students'; -// Create an index with non-default settings. $client->indices()->create([ - 'index' => $indexName, + 'index' => $index, 'body' => [ 'settings' => [ 'index' => [ - 'number_of_shards' => 4 - ] - ] - ] + 'number_of_shards' => 1, + 'number_of_replicas' => 1, + ], + ], + 'mappings' => [ + 'properties' => [ + 'gradDate' => ['type' => 'date', 'format' => 'yyyy-MM-dd'], + ], + ], + ], ]); ``` {% include copy.html %} ## Indexing a document -You can index a document into OpenSearch using the following code: +Index a document using the following code. Set `refresh` to `true` to make the document available for search immediately: ```php -$client->create([ - 'index' => $indexName, - 'id' => 1, +$response = $client->index([ + 'index' => $index, + 'id' => '1', 'body' => [ - 'title' => 'Moneyball', - 'director' => 'Bennett Miller', - 'year' => 2011 - ] + 'firstName' => 'John', + 'lastName' => 'Doe', + 'gpa' => 3.89, + 'gradDate' => '2022-05-15', + ], + 'refresh' => true, ]); ``` {% include copy.html %} -## Searching for documents +To create a document only if its ID does not already exist, use `create()` instead of `index()`. A `create()` request for an existing ID returns a `409` response. -The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" appears in the title field: +## Bulk indexing + +Index multiple documents in a single request using the following code. The request body alternates between an action line and the document to which the action applies: ```php -var_dump( - $client->search([ - 'index' => $indexName, +$response = $client->bulk([ + 'body' => [ + ['index' => ['_index' => $index, '_id' => '2']], + ['firstName' => 'Paulo', 'lastName' => 'Santos', 'gpa' => 3.93, 'gradDate' => '2021-05-20'], + ['index' => ['_index' => $index, '_id' => '3']], + ['firstName' => 'Shirley', 'lastName' => 'Rodriguez', 'gpa' => 3.91, 'gradDate' => '2019-05-10'], + ], + 'refresh' => true, +]); +``` +{% include copy.html %} + +A bulk request does not throw an exception when an individual action fails, so check the `errors` field of the response and the `items` array for per-action results. + +## Searching for documents + +Search for all documents in an index using the following code: + +```php +$response = $client->search([ + 'index' => $index, +]); + +foreach ($response['hits']['hits'] as $hit) { + echo json_encode($hit['_source']) . "\n"; +} +``` +{% include copy.html %} + +Search using a range query: + +```php +$response = $client->search([ + 'index' => $index, + 'body' => [ + 'query' => [ + 'range' => [ + 'gradDate' => [ + 'gte' => '2019-01-01', + 'lte' => '2019-12-31', + ], + ], + ], + ], +]); +``` +{% include copy.html %} + +To write the query in SQL, use the `sql()` namespace. The response contains a `schema` array describing the columns and a `datarows` array containing the matching rows: + +```php +$response = $client->sql()->query([ + 'body' => [ + 'query' => "SELECT firstName, lastName, gpa FROM $index WHERE gradDate BETWEEN '2019-01-01' AND '2019-12-31'", + ], +]); +``` +{% include copy.html %} + +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```php +foreach ([0, 2] as $from) { + $response = $client->search([ + 'index' => $index, 'body' => [ - 'size' => 5, - 'query' => [ - 'multi_match' => [ - 'query' => 'miller', - 'fields' => ['title^2', 'director'] - ] - ] - ] - ]) -); + 'from' => $from, + 'size' => 2, + 'sort' => [['gradDate' => 'asc']], + ], + ]); + + foreach ($response['hits']['hits'] as $hit) { + echo json_encode($hit['_source']) . "\n"; + } +} +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`, as described in [Paginating using a point in time](#paginating-using-a-point-in-time). + +### Paginating using a point in time + +To paginate through a large number of results or to page through a fixed view of the index, use a point in time (PIT) with `search_after`. Create a PIT, pass its ID in the search body, and use the `sort` values of the last hit as the `search_after` value for the next page: + +```php +$response = $client->createPit([ + 'index' => $index, + 'keep_alive' => '10m', +]); +$pitId = $response['pit_id']; + +// Get the first page of results. +$response = $client->search([ + 'body' => [ + 'pit' => ['id' => $pitId, 'keep_alive' => '10m'], + 'size' => 2, + 'sort' => [['gradDate' => 'asc']], + ], +]); +$last = end($response['hits']['hits']); + +// Get the next page of results. +$response = $client->search([ + 'body' => [ + 'pit' => ['id' => $pitId, 'keep_alive' => '10m'], + 'search_after' => $last['sort'], + 'size' => 2, + 'sort' => [['gradDate' => 'asc']], + ], +]); + +// Delete the point in time. +$client->deletePit([ + 'body' => ['pit_id' => [$pitId]], +]); +``` +{% include copy.html %} + +## Updating a document + +Update a document by wrapping the changed fields in a `doc` object: + +```php +$response = $client->update([ + 'index' => $index, + 'id' => '1', + 'body' => [ + 'doc' => [ + 'gpa' => 3.92, + ], + ], +]); ``` {% include copy.html %} ## Deleting a document -You can delete a document using the following code: +Delete a document using the following code: ```php -$client->delete([ - 'index' => $indexName, - 'id' => 1, +$response = $client->delete([ + 'index' => $index, + 'id' => '3', + 'refresh' => true, +]); +``` +{% include copy.html %} + +To delete all documents that match a query, use `deleteByQuery()`: + +```php +$response = $client->deleteByQuery([ + 'index' => $index, + 'body' => [ + 'query' => [ + 'range' => [ + 'gradDate' => [ + 'gte' => '2021-01-01', + 'lte' => '2021-12-31', + ], + ], + ], + ], ]); ``` {% include copy.html %} ## Deleting an index -You can delete an index using the following code: +Delete an index using the following code: ```php -$client->indices()->delete([ - 'index' => $indexName +$response = $client->indices()->delete([ + 'index' => $index, ]); ``` {% include copy.html %} ## Sample program -The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index: +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. + +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```php setHosts(['https://localhost:9200']) - ->setBasicAuthentication('admin', 'admin') // For testing only. Don't store credentials in code. - ->setSSLVerification(false) // For testing only. Use certificate for validation - ->build(); - -$indexName = 'test-index-name'; - -// Print OpenSearch version information on console. -var_dump($client->info()); - -// Create an index with non-default settings. -$client->indices()->create([ - 'index' => $indexName, - 'body' => [ - 'settings' => [ - 'index' => [ - 'number_of_shards' => 4 - ] - ] - ] +$client = (new \OpenSearch\GuzzleClientFactory())->create([ + 'base_uri' => 'https://localhost:9200', // Without security, use http://localhost:9200 + 'auth' => ['admin', ''], // Without security, remove this line + 'verify' => false, // Without security, remove this line ]); -$client->create([ - 'index' => $indexName, - 'id' => 1, - 'body' => [ - 'title' => 'Moneyball', - 'director' => 'Bennett Miller', - 'year' => 2011 - ] -]); - -// Search for it -var_dump( - $client->search([ - 'index' => $indexName, +try { + // Create the index + $index = 'students'; + echo "Creating index......\n"; + $response = $client->indices()->create([ + 'index' => $index, + 'body' => [ + 'settings' => [ + 'index' => [ + 'number_of_shards' => 1, + 'number_of_replicas' => 1, + ], + ], + 'mappings' => [ + 'properties' => [ + 'gradDate' => ['type' => 'date', 'format' => 'yyyy-MM-dd'], + ], + ], + ], + ]); + echo "Index created: {$response['index']}\n"; + + // Index a document + echo "\nIndexing one student......\n"; + $response = $client->index([ + 'index' => $index, + 'id' => '1', + 'body' => [ + 'firstName' => 'John', + 'lastName' => 'Doe', + 'gpa' => 3.89, + 'gradDate' => '2022-05-15', + ], + 'refresh' => true, + ]); + echo "Result: {$response['result']}, id: {$response['_id']}, version: {$response['_version']}\n"; + + // Bulk index documents + echo "\nIndexing many students......\n"; + $response = $client->bulk([ + 'body' => [ + ['index' => ['_index' => $index, '_id' => '2']], + ['firstName' => 'Paulo', 'lastName' => 'Santos', 'gpa' => 3.93, 'gradDate' => '2021-05-20'], + ['index' => ['_index' => $index, '_id' => '3']], + ['firstName' => 'Shirley', 'lastName' => 'Rodriguez', 'gpa' => 3.91, 'gradDate' => '2019-05-10'], + ], + 'refresh' => true, + ]); + echo 'Errors: ' . var_export($response['errors'], true) . "\n"; + foreach ($response['items'] as $item) { + $action = array_key_first($item); + echo " {$item[$action]['result']} id: {$item[$action]['_id']}\n"; + } + + // Search for all students + echo "\nSearching for all students......\n"; + $response = $client->search([ + 'index' => $index, + 'body' => [ + 'from' => 0, + 'size' => 2, + 'sort' => [['gradDate' => 'asc']], + ], + ]); + echo "Total hits: {$response['hits']['total']['value']}\n"; + echo "Page 1:\n"; + foreach ($response['hits']['hits'] as $hit) { + echo ' ' . json_encode($hit['_source']) . "\n"; + } + + $response = $client->search([ + 'index' => $index, + 'body' => [ + 'from' => 2, + 'size' => 2, + 'sort' => [['gradDate' => 'asc']], + ], + ]); + echo "Page 2:\n"; + foreach ($response['hits']['hits'] as $hit) { + echo ' ' . json_encode($hit['_source']) . "\n"; + } + + // Search for students who graduated in 2019 + echo "\nSearching for students who graduated in 2019......\n"; + $response = $client->search([ + 'index' => $index, 'body' => [ - 'size' => 5, 'query' => [ - 'multi_match' => [ - 'query' => 'miller', - 'fields' => ['title^2', 'director'] - ] - ] - ] - ]) -); + 'range' => [ + 'gradDate' => [ + 'gte' => '2019-01-01', + 'lte' => '2019-12-31', + ], + ], + ], + ], + ]); + echo "Total hits: {$response['hits']['total']['value']}\n"; + foreach ($response['hits']['hits'] as $hit) { + echo ' ' . json_encode($hit['_source']) . "\n"; + } -// Delete a single document -$client->delete([ - 'index' => $indexName, - 'id' => 1, -]); + // Update a document + echo "\nUpdating a student's GPA......\n"; + $response = $client->update([ + 'index' => $index, + 'id' => '1', + 'body' => [ + 'doc' => [ + 'gpa' => 3.92, + ], + ], + ]); + echo "Result: {$response['result']}, version: {$response['_version']}\n"; + // Get the updated document + $response = $client->get([ + 'index' => $index, + 'id' => '1', + ]); + echo 'Updated document: ' . json_encode($response['_source']) . "\n"; -// Delete index -$client->indices()->delete([ - 'index' => $indexName -]); + // Delete a document + echo "\nDeleting a student......\n"; + $response = $client->delete([ + 'index' => $index, + 'id' => '3', + 'refresh' => true, + ]); + echo "Result: {$response['result']}\n"; -?> + // Delete the index + echo "\nDeleting the index......\n"; + $response = $client->indices()->delete([ + 'index' => $index, + ]); + echo 'Acknowledged: ' . var_export($response['acknowledged'], true) . "\n"; +} catch (\OpenSearch\Exception\HttpExceptionInterface $e) { + echo 'OpenSearch returned an error: ' . $e->getMessage() . "\n"; +} ``` -{% include copy.html %} \ No newline at end of file +{% include copy.html %} + +The program produces the following output: + +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + {"firstName":"Paulo","lastName":"Santos","gpa":3.93,"gradDate":"2021-05-20"} +Page 2: + {"firstName":"John","lastName":"Doe","gpa":3.89,"gradDate":"2022-05-15"} + +Searching for students who graduated in 2019...... +Total hits: 1 + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: {"firstName":"John","lastName":"Doe","gpa":3.92,"gradDate":"2022-05-15"} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- For more examples of using the client, see the [`opensearch-php` user guide](https://github.com/opensearch-project/opensearch-php/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as authentication and sending raw requests, see the [`opensearch-php` guides](https://github.com/opensearch-project/opensearch-php/tree/main/guides). +- For complete sample applications, see the [`opensearch-php` samples](https://github.com/opensearch-project/opensearch-php/tree/main/samples). diff --git a/_clients/python-high-level.md b/_clients/python-high-level.md index ff529eb0..505569c9 100644 --- a/_clients/python-high-level.md +++ b/_clients/python-high-level.md @@ -1,17 +1,17 @@ --- layout: default -title: High-level Python client -nav_order: 5 +title: High-level Python client (deprecated) +nav_order: 200 --- -The OpenSearch high-level Python client (`opensearch-dsl-py`) will be deprecated after version 2.1.0. We recommend switching to the [Python client (`opensearch-py`)]({{site.url}}{{site.baseurl}}/clients/python-low-level/), which now includes the functionality of `opensearch-dsl-py`. -{: .warning} - # High-level Python client +The OpenSearch high-level Python client (`opensearch-dsl-py`) is deprecated, and its repository is archived. We recommend switching to the [Python client (`opensearch-py`)]({{site.url}}{{site.baseurl}}/clients/python-low-level/), which now includes the functionality of `opensearch-dsl-py`. +{: .warning} + The OpenSearch high-level Python client (`opensearch-dsl-py`) provides wrapper classes for common OpenSearch entities, like documents, so you can work with them as Python objects. Additionally, the high-level client simplifies writing queries and supplies convenient Python methods for common OpenSearch operations. The high-level Python client supports creating and indexing documents, searching with and without filters, and updating documents using queries. -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-dsl-py repo](https://github.com/opensearch-project/opensearch-dsl-py). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-dsl-py` repo](https://github.com/opensearch-project/opensearch-dsl-py). ## Setup @@ -26,18 +26,18 @@ After installing the client, you can import it like any other module: ```python from opensearchpy import OpenSearch -from opensearch_dsl import Search +from opensearch_dsl import Search, Document, Text, Keyword ``` {% include copy.html %} ## Connecting to OpenSearch -To connect to the default OpenSearch host, create a client object with SSL enabled if you are using the Security plugin. You can use the default credentials for testing purposes: +To connect to the default OpenSearch host, create a client object with SSL enabled if you are using the Security plugin. Replace `` with the admin password that you set when you installed OpenSearch: ```python host = 'localhost' port = 9200 -auth = ('admin', 'admin') # For testing only. Don't store credentials in code. +auth = ('admin', '') # For testing only. Don't store credentials in code. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA. # Create the client with SSL/TLS enabled, but hostname verification disabled. @@ -59,7 +59,7 @@ If you have your own client certificates, specify them in the `client_cert_path` ```python host = 'localhost' port = 9200 -auth = ('admin', 'admin') # For testing only. Don't store credentials in code. +auth = ('admin', '') # For testing only. Don't store credentials in code. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA. # Optional client certificates if you don't want to use HTTP basic authentication. @@ -114,7 +114,7 @@ index_body = { } } -response = client.indices.create(index_name, body=index_body) +response = client.indices.create(index=index_name, body=index_body) ``` {% include copy.html %} @@ -153,7 +153,7 @@ You can perform several operations at the same time by using the `bulk()` method ```python movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }' -client.bulk(movies) +client.bulk(body=movies) ``` {% include copy.html %} @@ -226,7 +226,7 @@ from opensearch_dsl import Search, Document, Text, Keyword host = 'localhost' port = 9200 -auth = ('admin', 'admin') # For testing only. Don't store credentials in code. +auth = ('admin', '') # For testing only. Don't store credentials in code. ca_certs_path = 'root-ca.pem' # Create the client with SSL/TLS enabled, but hostname verification disabled. @@ -250,7 +250,7 @@ index_body = { } } -response = client.indices.create(index_name, index_body) +response = client.indices.create(index=index_name, body=index_body) print('\nCreating index:') print(response) @@ -278,7 +278,7 @@ print(response) movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }' -client.bulk(movies) +client.bulk(body=movies) # Search for the document. s = Search(using=client, index=index_name) \ @@ -292,6 +292,11 @@ for hit in response: print(hit.meta.score, hit.title) # Delete the document. +response = client.delete( + index = index_name, + id = 1 +) + print('\nDeleting document:') print(response) diff --git a/_clients/python-low-level.md b/_clients/python-low-level.md index 894bef0e..d5ba33a1 100644 --- a/_clients/python-low-level.md +++ b/_clients/python-low-level.md @@ -1,20 +1,28 @@ --- layout: default -title: Low-level Python client +title: Python client nav_order: 10 +has_children: true +has_toc: false redirect_from: - /clients/python/ --- -# Low-level Python client +# Python client -The OpenSearch low-level Python client (`opensearch-py`) provides wrapper methods for the OpenSearch REST API so that you can interact with your cluster more naturally in Python. Rather than sending raw HTTP requests to a given URL, you can create an OpenSearch client for your cluster and call the client's built-in functions. For the client's complete API documentation and additional examples, see the [`opensearch-py` API documentation](https://opensearch-project.github.io/opensearch-py/). +The OpenSearch low-level Python client (`opensearch-py`) provides wrapper methods for the OpenSearch REST API so that you can interact with your cluster more naturally in Python. Rather than sending raw HTTP requests to a given URL, you can create an OpenSearch client for your cluster and call the client's built-in functions. -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-py` repo](https://github.com/opensearch-project/opensearch-py). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For additional information, see the following resources: +- [OpenSearch Python repo](https://github.com/opensearch-project/opensearch-py) +- [API reference](https://opensearch-project.github.io/opensearch-py/api-ref.html) +- [User guides](https://github.com/opensearch-project/opensearch-py/tree/main/guides) +- [Samples](https://github.com/opensearch-project/opensearch-py/tree/main/samples) -## Setup +If you have any questions or would like to contribute, you can [create an issue](https://github.com/opensearch-project/opensearch-py/issues) to interact with the OpenSearch Python team directly. -To add the client to your project, install it using [pip](https://pip.pypa.io/): +## Installing the Python client + +The latest version of the client, `opensearch-py` 3.2.0, requires Python 3.10 or later. To add the client to your project, install it using [pip](https://pip.pypa.io/): ```bash pip install opensearch-py @@ -28,14 +36,23 @@ from opensearchpy import OpenSearch ``` {% include copy.html %} +## Sample data + +The examples on this page use student documents. Each document is a Python dictionary that contains the `firstName`, `lastName`, `gpa`, and `gradDate` fields. For example, the following dictionary represents one student: + +```python +document = {'firstName': 'John', 'lastName': 'Doe', 'gpa': 3.89, 'gradDate': '2022-05-15'} +``` +{% include copy.html %} + ## Connecting to OpenSearch -To connect to the default OpenSearch host, create a client object with SSL enabled if you are using the Security plugin. You can use the default credentials for testing purposes: +To connect to the default OpenSearch host, create a client object with SSL enabled if you are using the Security plugin. Replace `` with the admin password that you set when installing OpenSearch: ```python host = 'localhost' port = 9200 -auth = ('admin', 'admin') # For testing only. Don't store credentials in code. +auth = ('admin', '') # For testing only. Don't store credentials in code. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA. # Create the client with SSL/TLS enabled, but hostname verification disabled. @@ -57,7 +74,7 @@ If you have your own client certificates, specify them in the `client_cert_path` ```python host = 'localhost' port = 9200 -auth = ('admin', 'admin') # For testing only. Don't store credentials in code. +auth = ('admin', '') # For testing only. Don't store credentials in code. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA. # Optional client certificates if you don't want to use HTTP basic authentication. @@ -100,17 +117,26 @@ client = OpenSearch( ## Connecting to Amazon OpenSearch Service -The following example illustrates connecting to Amazon OpenSearch Service: +To sign requests to Amazon OpenSearch Service or Amazon OpenSearch Serverless using IAM credentials, install the AWS SDK for Python (Boto3): + +```bash +pip install boto3 +``` +{% include copy.html %} + +In the following example, replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console. + +The following example illustrates connecting to Amazon OpenSearch Service using IAM credentials: ```python -from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth +from opensearchpy import OpenSearch, RequestsHttpConnection, RequestsAWSV4SignerAuth import boto3 -host = '' # cluster endpoint, for example: my-test-domain.us-east-1.es.amazonaws.com -region = 'us-west-2' +host = 'search--.us-east-1.es.amazonaws.com' # Domain endpoint without https:// +region = 'us-east-1' service = 'es' credentials = boto3.Session().get_credentials() -auth = AWSV4SignerAuth(credentials, region, service) +auth = RequestsAWSV4SignerAuth(credentials, region, service) client = OpenSearch( hosts = [{'host': host, 'port': 443}], @@ -123,19 +149,41 @@ client = OpenSearch( ``` {% include copy.html %} +To connect to Amazon OpenSearch Service through HTTP with a username and password, use the following code: + +```python +from opensearchpy import OpenSearch + +host = 'search--.us-east-1.es.amazonaws.com' # Domain endpoint without https:// +auth = ('admin', '') # For testing only. Don't store credentials in code. + +client = OpenSearch( + hosts=[{"host": host, "port": 443}], + http_auth=auth, + http_compress=True, # enables gzip compression for request bodies + use_ssl=True, + verify_certs=True, + ssl_assert_hostname=False, + ssl_show_warn=False, +) +``` +{% include copy.html %} + ## Connecting to Amazon OpenSearch Serverless -The following example illustrates connecting to Amazon OpenSearch Serverless Service: +In the following example, replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console. + +The following example illustrates connecting to Amazon OpenSearch Serverless: ```python -from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth +from opensearchpy import OpenSearch, RequestsHttpConnection, RequestsAWSV4SignerAuth import boto3 -host = '' # cluster endpoint, for example: my-test-domain.us-east-1.aoss.amazonaws.com -region = 'us-west-2' +host = '.us-east-1.aoss.amazonaws.com' # Collection endpoint without https:// +region = 'us-east-1' service = 'aoss' credentials = boto3.Session().get_credentials() -auth = AWSV4SignerAuth(credentials, region, service) +auth = RequestsAWSV4SignerAuth(credentials, region, service) client = OpenSearch( hosts = [{'host': host, 'port': 443}], @@ -148,76 +196,103 @@ client = OpenSearch( ``` {% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} ## Creating an index -To create an OpenSearch index, use the `client.indices.create()` method. You can use the following code to construct a JSON object with custom settings: +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```python -index_name = 'python-test-index' +index_name = 'students' index_body = { - 'settings': { - 'index': { - 'number_of_shards': 4 + 'settings': { + 'index': { + 'number_of_shards': 1, + 'number_of_replicas': 1 + } + }, + 'mappings': { + 'properties': { + 'gradDate': {'type': 'date', 'format': 'yyyy-MM-dd'} + } } - } } - -response = client.indices.create(index_name, body=index_body) +response = client.indices.create(index=index_name, body=index_body) ``` {% include copy.html %} ## Indexing a document -You can index a document using the `client.index()` method: +To index the `document` dictionary from [Sample data](#sample-data), use the `client.index()` method: ```python -document = { - 'title': 'Moneyball', - 'director': 'Bennett Miller', - 'year': '2011' -} - -response = client.index( - index = 'python-test-index', - body = document, - id = '1', - refresh = True -) +response = client.index(index=index_name, id='1', body=document, refresh=True) ``` {% include copy.html %} ## Performing bulk operations -You can perform several operations at the same time by using the `bulk()` method of the client. The operations may be of the same type or of different types. Note that the operations must be separated by a `\n` and the entire string must be a single line: +You can perform several operations at the same time by using the `bulk()` method of the client. The operations may be of the same type or of different types. Provide the operations as a list in which each action is followed by its document: ```python -movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }' - -client.bulk(movies) +operations = [ + {'index': {'_index': index_name, '_id': '2'}}, + {'firstName': 'Paulo', 'lastName': 'Santos', 'gpa': 3.93, 'gradDate': '2021-05-20'}, + {'index': {'_index': index_name, '_id': '3'}}, + {'firstName': 'Shirley', 'lastName': 'Rodriguez', 'gpa': 3.91, 'gradDate': '2019-05-10'} +] +response = client.bulk(body=operations, refresh=True) ``` {% include copy.html %} ## Searching for documents -The easiest way to search for documents is to construct a query string. The following code uses a multi-match query to search for “miller” in the title and director fields. It boosts the documents that have “miller” in the title field: +To search for all documents in an index, use the `client.search()` method without a query: ```python -q = 'miller' -query = { - 'size': 5, - 'query': { - 'multi_match': { - 'query': q, - 'fields': ['title^2', 'director'] - } - } -} +response = client.search(index=index_name) +``` +{% include copy.html %} -response = client.search( - body = query, - index = 'python-test-index' -) +The response is a dictionary, and each item in `response['hits']['hits']` is a dictionary that contains the document ID in the `_id` key and the document fields in the `_source` key: + +```python +for hit in response['hits']['hits']: + source = hit['_source'] + print(f"ID: {hit['_id']}, name: {source['firstName']} {source['lastName']}, GPA: {source['gpa']}, graduation date: {source['gradDate']}") +``` +{% include copy.html %} + +To search using a query, provide the query in the request body. The following code uses a range query to search for students who graduated in 2019: + +```python +query = {'query': {'range': {'gradDate': {'gte': '2019-01-01', 'lte': '2019-12-31'}}}} +response = client.search(index=index_name, body=query) +``` +{% include copy.html %} + +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```python +response = client.search(index=index_name, body={'from': 0, 'size': 2, 'sort': [{'gradDate': 'asc'}]}) +next_response = client.search(index=index_name, body={'from': 2, 'size': 2, 'sort': [{'gradDate': 'asc'}]}) +for page in [response, next_response]: + for hit in page['hits']['hits']: + print(hit['_source']) +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +## Updating a document + +You can update a document using the `client.update()` method. The fields in the `doc` object are merged into the existing document: + +```python +response = client.update(index=index_name, id='1', body={'doc': {'gpa': 3.92}}) ``` {% include copy.html %} @@ -226,10 +301,7 @@ response = client.search( You can delete a document using the `client.delete()` method: ```python -response = client.delete( - index = 'python-test-index', - id = '1' -) +response = client.delete(index=index_name, id='3', refresh=True) ``` {% include copy.html %} @@ -238,119 +310,160 @@ response = client.delete( You can delete an index using the `client.indices.delete()` method: ```python -response = client.indices.delete( - index = 'python-test-index' -) +response = client.indices.delete(index=index_name) ``` {% include copy.html %} ## Sample program -The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index: +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `# Without security` comments. + +This sample program is for testing only. It specifies credentials in code. In production, load credentials from a secure location. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```python +import json from opensearchpy import OpenSearch host = 'localhost' port = 9200 -auth = ('admin', 'admin') # For testing only. Don't store credentials in code. +# Without security, remove this line +auth = ('admin', '') +# Without security, remove this line ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA. -# Optional client certificates if you don't want to use HTTP basic authentication. -# client_cert_path = '/full/path/to/client.pem' -# client_key_path = '/full/path/to/client-key.pem' - # Create the client with SSL/TLS enabled, but hostname verification disabled. client = OpenSearch( hosts = [{'host': host, 'port': port}], http_compress = True, # enables gzip compression for request bodies - http_auth = auth, - # client_cert = client_cert_path, - # client_key = client_key_path, - use_ssl = True, - verify_certs = True, + http_auth = auth, # Without security, remove this line + use_ssl = True, # Without security, use use_ssl = False + verify_certs = True, # Without security, use verify_certs = False ssl_assert_hostname = False, ssl_show_warn = False, - ca_certs = ca_certs_path + ca_certs = ca_certs_path # Without security, remove this line ) -# Create an index with non-default settings. -index_name = 'python-test-index' +# Create the index. +index_name = 'students' index_body = { - 'settings': { - 'index': { - 'number_of_shards': 4 + 'settings': { + 'index': { + 'number_of_shards': 1, + 'number_of_replicas': 1 + } + }, + 'mappings': { + 'properties': { + 'gradDate': {'type': 'date', 'format': 'yyyy-MM-dd'} + } } - } } +print('Creating index......') +response = client.indices.create(index=index_name, body=index_body) +print(f"Index created: {response['index']}") -response = client.indices.create(index_name, body=index_body) -print('\nCreating index:') -print(response) +# Index a document. +print('\nIndexing one student......') +document = {'firstName': 'John', 'lastName': 'Doe', 'gpa': 3.89, 'gradDate': '2022-05-15'} +response = client.index(index=index_name, id='1', body=document, refresh=True) +print(f"Result: {response['result']}, id: {response['_id']}, version: {response['_version']}") -# Add a document to the index. -document = { - 'title': 'Moneyball', - 'director': 'Bennett Miller', - 'year': '2011' -} -id = '1' +# Bulk index documents. +print('\nIndexing many students......') +operations = [ + {'index': {'_index': index_name, '_id': '2'}}, + {'firstName': 'Paulo', 'lastName': 'Santos', 'gpa': 3.93, 'gradDate': '2021-05-20'}, + {'index': {'_index': index_name, '_id': '3'}}, + {'firstName': 'Shirley', 'lastName': 'Rodriguez', 'gpa': 3.91, 'gradDate': '2019-05-10'} +] +response = client.bulk(body=operations, refresh=True) +print(f"Errors: {str(response['errors']).lower()}") +for item in response['items']: + print(f" {item['index']['result']} id: {item['index']['_id']}") -response = client.index( - index = index_name, - body = document, - id = id, - refresh = True -) +# Search for all students. +print('\nSearching for all students......') +for page, start in enumerate([0, 2], start=1): + response = client.search(index=index_name, body={'from': start, 'size': 2, 'sort': [{'gradDate': 'asc'}]}) + if page == 1: + print(f"Total hits: {response['hits']['total']['value']}") + print(f"Page {page}:") + for hit in response['hits']['hits']: + print(f" {json.dumps(hit['_source'], separators=(',', ':'))}") -print('\nAdding document:') -print(response) +# Search for students who graduated in 2019. +print('\nSearching for students who graduated in 2019......') +query = {'query': {'range': {'gradDate': {'gte': '2019-01-01', 'lte': '2019-12-31'}}}} +response = client.search(index=index_name, body=query) +print(f"Total hits: {response['hits']['total']['value']}") +for hit in response['hits']['hits']: + print(f" {json.dumps(hit['_source'], separators=(',', ':'))}") -# Perform bulk operations +# Update a document. +print("\nUpdating a student's GPA......") +response = client.update(index=index_name, id='1', body={'doc': {'gpa': 3.92}}) +print(f"Result: {response['result']}, version: {response['_version']}") -movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }' +# Get the updated document. +response = client.get(index=index_name, id='1') +print(f"Updated document: {json.dumps(response['_source'], separators=(',', ':'))}") -client.bulk(movies) - -# Search for the document. -q = 'miller' -query = { - 'size': 5, - 'query': { - 'multi_match': { - 'query': q, - 'fields': ['title^2', 'director'] - } - } -} - -response = client.search( - body = query, - index = index_name -) -print('\nSearch results:') -print(response) - -# Delete the document. -response = client.delete( - index = index_name, - id = id -) - -print('\nDeleting document:') -print(response) +# Delete a document. +print('\nDeleting a student......') +response = client.delete(index=index_name, id='3', refresh=True) +print(f"Result: {response['result']}") # Delete the index. -response = client.indices.delete( - index = index_name -) - -print('\nDeleting index:') -print(response) +print('\nDeleting the index......') +response = client.indices.delete(index=index_name) +print(f"Acknowledged: {str(response['acknowledged']).lower()}") ``` {% include copy.html %} -## Next steps +The program produces the following output: -- For Python client API, see the [`opensearch-py` API documentation](https://opensearch-project.github.io/opensearch-py/). -- For Python code samples, see [Samples](https://github.com/opensearch-project/opensearch-py/tree/main/samples). \ No newline at end of file +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + {"firstName":"Paulo","lastName":"Santos","gpa":3.93,"gradDate":"2021-05-20"} +Page 2: + {"firstName":"John","lastName":"Doe","gpa":3.89,"gradDate":"2022-05-15"} + +Searching for students who graduated in 2019...... +Total hits: 1 + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: {"firstName":"John","lastName":"Doe","gpa":3.92,"gradDate":"2022-05-15"} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- To analyze data and upload ML models from Python, see [Python ML client]({{site.url}}{{site.baseurl}}/clients/opensearch-py-ml/). +- For the client API reference, see the [`opensearch-py` API documentation](https://opensearch-project.github.io/opensearch-py/). +- For more examples of using the client, see the [`opensearch-py` user guide](https://github.com/opensearch-project/opensearch-py/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-py` guides](https://github.com/opensearch-project/opensearch-py/tree/main/guides). +- For complete sample applications, see the [`opensearch-py` samples](https://github.com/opensearch-project/opensearch-py/tree/main/samples). diff --git a/_clients/ruby.md b/_clients/ruby.md index 7d582927..b4de95c8 100644 --- a/_clients/ruby.md +++ b/_clients/ruby.md @@ -7,9 +7,9 @@ has_children: false # Ruby client -The OpenSearch Ruby client allows you to interact with your OpenSearch clusters through Ruby methods rather than HTTP methods and raw JSON. For the client's complete API documentation and additional examples, see the [`opensearch-transport`](https://rubydoc.info/gems/opensearch-transport), [`opensearch-api`](https://rubydoc.info/gems/opensearch-api), [`opensearch-dsl`](https://rubydoc.info/gems/opensearch-dsl), and [`opensearch-ruby`](https://rubydoc.info/gems/opensearch-ruby/) gem documentation. +The OpenSearch Ruby client allows you to interact with your OpenSearch clusters through Ruby methods rather than HTTP methods and raw JSON. For the client's complete API documentation, see the [`opensearch-ruby` repository](https://github.com/opensearch-project/opensearch-ruby) documentation. For additional examples, see [`opensearch-transport`](https://rubygems.org/gems/opensearch-transport/), [`opensearch-api`](https://rubygems.org/gems/opensearch-api/), [`opensearch-dsl`](https://rubygems.org/gems/opensearch-dsl/), and [`opensearch-ruby`](https://rubygems.org/gems/opensearch-ruby/) gem documentation. -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-ruby repo](https://github.com/opensearch-project/opensearch-ruby). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-ruby` repo](https://github.com/opensearch-project/opensearch-ruby). ## Installing the Ruby client @@ -20,6 +20,13 @@ gem install opensearch-ruby ``` {% include copy.html %} +Alternatively, add the gem to your `Gemfile` and run `bundle install`. The following example requires client version 3.4.0 or a later 3.x release: + +```ruby +gem 'opensearch-ruby', '~> 3.4' +``` +{% include copy.html %} + To use the client, import it as a module: ```ruby @@ -53,29 +60,41 @@ client.cluster.health The output is as follows: ```bash -2022-08-25 14:24:52 -0400: GET http://localhost:9200/ [status:200, request:0.048s, query:n/a] -2022-08-25 14:24:52 -0400: < { - "name" : "opensearch", - "cluster_name" : "docker-cluster", - "cluster_uuid" : "Aw0F5Pt9QF6XO9vXQHIs_w", +2026-09-30 12:29:58 -0400: GET http://localhost:9200/ [status:200, request:0.009s, query:n/a] +2026-09-30 12:29:58 -0400: < { + "name" : "opensearch-node1", + "cluster_name" : "opensearch-cluster", + "cluster_uuid" : "uwutrwdfTVeh8rroYbZh4g", "version" : { "distribution" : "opensearch", - "number" : "2.2.0", + "number" : "3.8.0", "build_type" : "tar", - "build_hash" : "b1017fa3b9a1c781d4f34ecee411e0cdf930a515", - "build_date" : "2022-08-09T02:27:25.256769336Z", + "build_hash" : "e5a3c5691be87af6c12dbe3e158c59c04ee72973", + "build_date" : "2026-08-03T21:07:36.443334696Z", "build_snapshot" : false, - "lucene_version" : "9.3.0", - "minimum_wire_compatibility_version" : "7.10.0", - "minimum_index_compatibility_version" : "7.0.0" + "lucene_version" : "10.5.0", + "minimum_wire_compatibility_version" : "2.19.0", + "minimum_index_compatibility_version" : "2.0.0" }, "tagline" : "The OpenSearch Project: https://opensearch.org/" } -2022-08-25 14:24:52 -0400: GET http://localhost:9200/_cluster/health [status:200, request:0.018s, query:n/a] -2022-08-25 14:24:52 -0400: < {"cluster_name":"docker-cluster","status":"yellow","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"discovered_master":true,"discovered_cluster_manager":true,"active_primary_shards":10,"active_shards":10,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":8,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":55.55555555555556} +2026-09-30 12:29:58 -0400: GET http://localhost:9200/_cluster/health [status:200, request:0.007s, query:n/a] +2026-09-30 12:29:58 -0400: < {"cluster_name":"opensearch-cluster","status":"yellow","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"discovered_master":true,"discovered_cluster_manager":true,"active_primary_shards":57,"active_shards":57,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":28,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":67.05882352941175} ``` +To connect to a cluster that has the Security plugin enabled, use HTTPS and provide the user credentials: + +```ruby +client = OpenSearch::Client.new( + host: 'https://localhost:9200', + user: 'admin', # Only for demo purposes. Don't specify your credentials in code. + password: '', + transport_options: { ssl: { verify: false } } # For testing only. Use a certificate for validation. +) +``` +{% include copy.html %} + ## Connecting to Amazon OpenSearch Service To connect to Amazon OpenSearch Service, first install the `opensearch-aws-sigv4` gem: @@ -83,30 +102,36 @@ To connect to Amazon OpenSearch Service, first install the `opensearch-aws-sigv4 ```bash gem install opensearch-aws-sigv4 ``` +{% include copy.html %} + +Then create a client. Replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console: ```ruby require 'opensearch-aws-sigv4' require 'aws-sigv4' signer = Aws::Sigv4::Signer.new(service: 'es', - region: 'us-west-2', # signing service region + region: 'us-east-1', # must match the Region in the endpoint access_key_id: 'key_id', - secret_access_key: 'secret') + secret_access_key: 'secret', + session_token: 'session_token') # required for temporary credentials, such as IAM roles or SSO client = OpenSearch::Aws::Sigv4Client.new({ - host: 'https://your.amz-managed-opensearch.domain', + host: 'https://search--.us-east-1.es.amazonaws.com', log: true }, signer) # create an index and document -index = 'prime' +index = 'students' client.indices.create(index: index) -client.index(index: index, id: '1', body: { name: 'Amazon Echo', - msrp: '5999', - year: 2011 }) +client.index(index: index, id: '1', body: { firstName: 'John', + lastName: 'Doe', + gpa: 3.89, + gradDate: '2022-05-15' }, + refresh: true) # search for the document -client.search(body: { query: { match: { name: 'Echo' } } }) +client.search(index: index, body: { query: { match: { firstName: 'John' } } }) # delete the document client.delete(index: index, id: '1') @@ -118,165 +143,265 @@ client.indices.delete(index: index) ## Connecting to Amazon OpenSearch Serverless -To connect to Amazon OpenSearch Serverless Service, first install the `opensearch-aws-sigv4` gem: +To connect to Amazon OpenSearch Serverless, first install the `opensearch-aws-sigv4` gem: ```bash gem install opensearch-aws-sigv4 ``` +{% include copy.html %} + +Then create a client. Replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console: ```ruby require 'opensearch-aws-sigv4' require 'aws-sigv4' signer = Aws::Sigv4::Signer.new(service: 'aoss', - region: 'us-west-2', # signing service region + region: 'us-east-1', # must match the Region in the endpoint access_key_id: 'key_id', - secret_access_key: 'secret') + secret_access_key: 'secret', + session_token: 'session_token') # required for temporary credentials, such as IAM roles or SSO client = OpenSearch::Aws::Sigv4Client.new({ - host: 'https://your.amz-managed-opensearch.domain', # serverless endpoint for OpenSearch Serverless + host: 'https://.us-east-1.aoss.amazonaws.com', # Amazon OpenSearch Serverless collection endpoint log: true }, signer) -# create an index and document -index = 'prime' -client.indices.create(index: index) -client.index(index: index, id: '1', body: { name: 'Amazon Echo', - msrp: '5999', - year: 2011 }) - -# search for the document -client.search(body: { query: { match: { name: 'Echo' } } }) - -# delete the document -client.delete(index: index, id: '1') - -# delete the index -client.indices.delete(index: index) +# check whether an index exists +puts client.indices.exists?(index: 'students') ``` {% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} -## Creating an index +## Creating an index -You don't need to create an index explicitly in OpenSearch. Once you upload a document into an index that does not exist, OpenSearch creates the index automatically. Alternatively, you can create an index explicitly to specify settings like the number of primary and replica shards. To create an index with non-default settings, create an index body hash with those settings: +You don't need to create an index explicitly in OpenSearch. Once you upload a document into an index that does not exist, OpenSearch creates the index automatically. To create an index explicitly, use the `indices.create` method and pass the index settings and mappings in the `body` parameter. + +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```ruby index_body = { - 'settings': { - 'index': { - 'number_of_shards': 1, - 'number_of_replicas': 2 - } + settings: { + index: { + number_of_shards: 1, + number_of_replicas: 1 } -} - -client.indices.create( - index: 'students', - body: index_body -) + }, + mappings: { + properties: { + gradDate: { type: 'date', format: 'yyyy-MM-dd' } + } + } +} +client.indices.create(index: 'students', body: index_body) ``` {% include copy.html %} ## Mappings -OpenSearch uses dynamic mapping to infer field types of the documents that are indexed. However, to have more control over the schema of your document, you can pass an explicit mapping to OpenSearch. You can define data types for some or all fields of your document in this mapping. To create a mapping for an index, use the `put_mapping` method: +OpenSearch uses dynamic mapping to infer field types of the documents that are indexed. However, to have more control over the schema of your document, you can pass an explicit mapping to OpenSearch, as shown in [Creating an index](#creating-an-index). By default, string fields are mapped as `text`. Mapping a field as `keyword` instead signals to OpenSearch that the field should not be analyzed and should support only full case-sensitive matches. -```ruby -client.indices.put_mapping( - index: 'students', - body: { - properties: { - first_name: { type: 'keyword' }, - last_name: { type: 'keyword' } - } - } -) -``` -{% include copy.html %} - -By default, string fields are mapped as `text`, but in the mapping above, the `first_name` and `last_name` fields are mapped as `keyword`. This mapping signals to OpenSearch that these fields should not be analyzed and should support only full case-sensitive matches. - -You can verify the index's mappings using the `get_mapping` method: +To verify an index's mappings, use the `get_mapping` method: ```ruby response = client.indices.get_mapping(index: 'students') ``` {% include copy.html %} -If you know the mapping of your documents in advance and want to avoid mapping errors (for example, misspellings of a field name), you can set the `dynamic` parameter to `strict`: +If you know the mapping of your documents in advance and want to avoid mapping errors (for example, misspellings of a field name), use the `put_mapping` method to map the remaining fields and set the `dynamic` parameter to `strict`: ```ruby client.indices.put_mapping( - index: 'students', - body: { - dynamic: 'strict', - properties: { - first_name: { type: 'keyword' }, - last_name: { type: 'keyword' }, - gpa: { type: 'float'}, - grad_year: { type: 'integer'} - } + index: 'students', + body: { + dynamic: 'strict', + properties: { + firstName: { type: 'keyword' }, + lastName: { type: 'keyword' }, + gpa: { type: 'float' }, + gradDate: { type: 'date', format: 'yyyy-MM-dd' } } + } ) ``` {% include copy.html %} -With strict mapping, you can index a document with a missing field, but you cannot index a document with a new field. For example, indexing the following document with a misspelled `grad_yea` field fails: +With strict mapping, you can index a document with a missing field, but you cannot index a document with a new field. For example, indexing the following document with a misspelled `gradDat` field fails: ```ruby -document = { - first_name: 'Connor', - last_name: 'James', - gpa: 3.93, - grad_yea: 2021 -} - -client.index( - index: 'students', - body: document, - id: 100, - refresh: true -) +student = { firstName: 'John', lastName: 'Doe', gpa: 3.89, gradDat: '2022-05-15' } +client.index(index: 'students', id: '1', body: student, refresh: true) ``` {% include copy.html %} -OpenSearch returns a mapping error: +OpenSearch returns a mapping error, and the client raises an `OpenSearch::Transport::Transport::Errors::BadRequest` exception containing the following message: ```bash -{"error":{"root_cause":[{"type":"strict_dynamic_mapping_exception","reason":"mapping set to strict, dynamic introduction of [grad_yea] within [_doc] is not allowed"}],"type":"strict_dynamic_mapping_exception","reason":"mapping set to strict, dynamic introduction of [grad_yea] within [_doc] is not allowed"},"status":400} +[400] {"error":{"root_cause":[{"type":"strict_dynamic_mapping_exception","reason":"mapping set to strict, dynamic introduction of [gradDat] within [_doc] is not allowed"}],"type":"strict_dynamic_mapping_exception","reason":"mapping set to strict, dynamic introduction of [gradDat] within [_doc] is not allowed"},"status":400} ``` -## Indexing one document +## Indexing a document -To index one document, use the `index` method: +To index a document, use the `index` method: ```ruby -document = { - first_name: 'Connor', - last_name: 'James', - gpa: 3.93, - grad_year: 2021 -} - -client.index( - index: 'students', - body: document, - id: 100, - refresh: true -) +student = { firstName: 'John', lastName: 'Doe', gpa: 3.89, gradDate: '2022-05-15' } +response = client.index(index: 'students', id: '1', body: student, refresh: true) ``` {% include copy.html %} +## Bulk operations + +You can perform several operations at the same time by using the `bulk` method. The operations may be of the same type or of different types. + +To index multiple documents, pass each action header followed by its document: + +```ruby +actions = [ + { index: { _index: 'students', _id: '2' } }, + { firstName: 'Paulo', lastName: 'Santos', gpa: 3.93, gradDate: '2021-05-20' }, + { index: { _index: 'students', _id: '3' } }, + { firstName: 'Shirley', lastName: 'Rodriguez', gpa: 3.91, gradDate: '2019-05-10' } +] +response = client.bulk(body: actions, refresh: true) +``` +{% include copy.html %} + +Alternatively, you can pass the header and the data together by denoting the data with the `data:` key. The following request indexes the same two documents: + +```ruby +actions = [ + { index: { _index: 'students', _id: '2', data: { firstName: 'Paulo', lastName: 'Santos', gpa: 3.93, gradDate: '2021-05-20' } } }, + { index: { _index: 'students', _id: '3', data: { firstName: 'Shirley', lastName: 'Rodriguez', gpa: 3.91, gradDate: '2019-05-10' } } } +] +response = client.bulk(body: actions, refresh: true) +``` +{% include copy.html %} + +## Searching for documents + +To search for documents, use the `search` method. If you omit the request body, your query becomes a `match_all` query and returns all documents in the index: + +```ruby +require 'json' + +response = client.search(index: 'students') +response['hits']['hits'].each { |hit| puts JSON.generate(hit['_source']) } +``` +{% include copy.html %} + +The following example uses a `range` query to search for students who graduated in 2019: + +```ruby +query = { query: { range: { gradDate: { gte: '2019-01-01', lte: '2019-12-31' } } } } +response = client.search(index: 'students', body: query) +``` +{% include copy.html %} + +The following example searches for a student whose first or last name is "Santos." It uses a `multi_match` query to search for two fields (`firstName` and `lastName`), and it is boosting the `lastName` field in relevance with a caret notation (`lastName^2`): + +```ruby +query = { + size: 5, + query: { + multi_match: { + query: 'Santos', + fields: ['firstName', 'lastName^2'] + } + } +} +response = client.search(index: 'students', body: query) +``` +{% include copy.html %} + +## Boolean query + +The Ruby client exposes full OpenSearch query capability. In addition to simple searches that use the match query, you can create a more complex Boolean query to search for students who graduated in 2021 or later and sort them by GPA in descending order. In the following example, search is limited to 10 documents: + +```ruby +query = { + query: { + bool: { + filter: { + range: { + gradDate: { gte: '2021-01-01' } + } + } + } + }, + sort: { + gpa: { order: 'desc' } + } +} +response = client.search(index: 'students', from: 0, size: 10, body: query) +``` +{% include copy.html %} + +## Multi-search + +You can bulk several queries together and perform a multi-search using the `msearch` method. The following code searches for students whose GPAs are greater than 3.9 and for students whose GPAs are less than 3.9: + +```ruby +actions = [ + {}, + { query: { range: { gpa: { gt: 3.9 } } } }, + {}, + { query: { range: { gpa: { lt: 3.9 } } } } +] +response = client.msearch(index: 'students', body: actions) +``` +{% include copy.html %} + +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: + +```ruby +require 'json' + +query = { sort: [{ gradDate: 'asc' }] } +response = client.search(index: 'students', from: 0, size: 2, body: query) +response['hits']['hits'].each { |hit| puts JSON.generate(hit['_source']) } + +response = client.search(index: 'students', from: 2, size: 2, body: query) +response['hits']['hits'].each { |hit| puts JSON.generate(hit['_source']) } +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To process a large number of results in a batch, use scroll, as described in [Paginating using scroll](#paginating-using-scroll). + +### Paginating using scroll + +Use the Scroll API to paginate search results. Scroll keeps a search context open on the cluster and is suited to processing all results in a batch job rather than to user-facing requests. For other use cases, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +The following example retrieves all students two at a time: + +```ruby +response = client.search(index: 'students', scroll: '2m', size: 2) + +while response['hits']['hits'].size.positive? + scroll_id = response['_scroll_id'] + puts(response['hits']['hits'].map { |hit| "#{hit['_source']['firstName']} #{hit['_source']['lastName']}" }) + response = client.scroll(scroll: '1m', body: { scroll_id: scroll_id }) +end + +client.clear_scroll(body: { scroll_id: response['_scroll_id'] }) +``` +{% include copy.html %} + +First, you issue a search query, specifying the `scroll` and `size` parameters. The `scroll` parameter tells OpenSearch how long to keep the search context. In this case, it is set to two minutes. The `size` parameter specifies how many documents you want to return in each request. + +The response to the initial search query contains a `_scroll_id` that you can use to get the next set of documents. To do this, you use the `scroll` method, again specifying the `scroll` parameter and passing the `_scroll_id` in the body. You don't need to specify the query or index to the `scroll` method. The `scroll` method returns the next set of documents and the `_scroll_id`. It's important to use the latest `_scroll_id` when requesting the next batch of documents because `_scroll_id` can change between requests. When you have retrieved all documents, use the `clear_scroll` method to release the search context. + ## Updating a document -To update a document, use the `update` method: +To update a document, use the `update` method and pass the fields to change in the `doc` object. Then retrieve the updated document using the `get` method: ```ruby -client.update(index: 'students', - id: 100, - body: { doc: { gpa: 3.25 } }, - refresh: true) +response = client.update(index: 'students', id: '1', body: { doc: { gpa: 3.92 } }) +response = client.get(index: 'students', id: '1') ``` {% include copy.html %} @@ -285,372 +410,191 @@ client.update(index: 'students', To delete a document, use the `delete` method: ```ruby -client.delete( - index: 'students', - id: 100, - refresh: true -) +response = client.delete(index: 'students', id: '3', refresh: true) ``` {% include copy.html %} -## Bulk operations - -You can perform several operations at the same time by using the `bulk` method. The operations may be of the same type or of different types. - -You can index multiple documents using the `bulk` method: +To delete multiple documents in one request, use the `bulk` method: ```ruby actions = [ - { index: { _index: 'students', _id: '200' } }, - { first_name: 'James', last_name: 'Rodriguez', gpa: 3.91, grad_year: 2019 }, - { index: { _index: 'students', _id: '300' } }, - { first_name: 'Nikki', last_name: 'Wolf', gpa: 3.87, grad_year: 2020 } + { delete: { _index: 'students', _id: '1' } }, + { delete: { _index: 'students', _id: '2' } } ] -client.bulk(body: actions, refresh: true) +response = client.bulk(body: actions, refresh: true) ``` {% include copy.html %} -You can delete multiple documents as follows: - -```ruby -# Deleting multiple documents. -actions = [ - { delete: { _index: 'students', _id: 200 } }, - { delete: { _index: 'students', _id: 300 } } -] -client.bulk(body: actions, refresh: true) -``` -{% include copy.html %} - -You can perform different operations when using `bulk` as follows: - -```ruby -actions = [ - { index: { _index: 'students', _id: 100, data: { first_name: 'Paulo', last_name: 'Santos', gpa: 3.29, grad_year: 2022 } } }, - { index: { _index: 'students', _id: 200, data: { first_name: 'Shirley', last_name: 'Rodriguez', gpa: 3.92, grad_year: 2020 } } }, - { index: { _index: 'students', _id: 300, data: { first_name: 'Akua', last_name: 'Mansa', gpa: 3.95, grad_year: 2022 } } }, - { index: { _index: 'students', _id: 400, data: { first_name: 'John', last_name: 'Stiles', gpa: 3.72, grad_year: 2019 } } }, - { index: { _index: 'students', _id: 500, data: { first_name: 'Li', last_name: 'Juan', gpa: 3.94, grad_year: 2022 } } }, - { index: { _index: 'students', _id: 600, data: { first_name: 'Richard', last_name: 'Roe', gpa: 3.04, grad_year: 2020 } } }, - { update: { _index: 'students', _id: 100, data: { doc: { gpa: 3.73 } } } }, - { delete: { _index: 'students', _id: 200 } } -] -client.bulk(body: actions, refresh: true) -``` -{% include copy.html %} - -In the above example, you pass the data and the header together and you denote the data with the `data:` key. - -## Searching for a document - -To search for a document, use the `search` method. The following example searches for a student whose first or last name is "James." It uses a `multi_match` query to search for two fields (`first_name` and `last_name`), and it is boosting the `last_name` field in relevance with a caret notation (`last_name^2`). - -```ruby -q = 'James' -query = { - 'size': 5, - 'query': { - 'multi_match': { - 'query': q, - 'fields': ['first_name', 'last_name^2'] - } - } -} - -response = client.search( - body: query, - index: 'students' -) -``` -{% include copy.html %} - -If you omit the request body in the `search` method, your query becomes a `match_all` query and returns all documents in the index: - -```ruby -client.search(index: 'students') -``` -{% include copy.html %} - -## Boolean query - -The Ruby client exposes full OpenSearch query capability. In addition to simple searches that use the match query, you can create a more complex Boolean query to search for students who graduated in 2022 and sort them by last name. In the example below, search is limited to 10 documents. - -```ruby -query = { - 'query': { - 'bool': { - 'filter': { - 'term': { - 'grad_year': 2022 - - } - } - } - }, - 'sort': { - 'last_name': { - 'order': 'asc' - } - } -} - -response = client.search(index: 'students', from: 0, size: 10, body: query) -``` -{% include copy.html %} - -## Multi-search - -You can bulk several queries together and perform a multi-search using the `msearch` method. The following code searches for students whose GPAs are outside the 3.1–3.9 range: - -```ruby -actions = [ - {}, - {query: {range: {gpa: {gt: 3.9}}}}, - {}, - {query: {range: {gpa: {lt: 3.1}}}} -] -response = client.msearch(index: 'students', body: actions) -``` -{% include copy.html %} - -## Scroll - -You can paginate your search results using the Scroll API: - -```ruby -response = client.search(index: index_name, scroll: '2m', size: 2) - -while response['hits']['hits'].size.positive? - scroll_id = response['_scroll_id'] - puts(response['hits']['hits'].map { |doc| [doc['_source']['first_name'] + ' ' + doc['_source']['last_name']] }) - response = client.scroll(scroll: '1m', body: { scroll_id: scroll_id }) -end -``` -{% include copy.html %} - -First, you issue a search query, specifying the `scroll` and `size` parameters. The `scroll` parameter tells OpenSearch how long to keep the search context. In this case, it is set to two minutes. The `size` parameter specifies how many documents you want to return in each request. - -The response to the initial search query contains a `_scroll_id` that you can use to get the next set of documents. To do this, you use the `scroll` method, again specifying the `scroll` parameter and passing the `_scroll_id` in the body. You don't need to specify the query or index to the `scroll` method. The `scroll` method returns the next set of documents and the `_scroll_id`. It's important to use the latest `_scroll_id` when requesting the next batch of documents because `_scroll_id` can change between requests. - ## Deleting an index -You can delete the index using the `delete` method: +To delete an index, use the `indices.delete` method: ```ruby -response = client.indices.delete(index: index_name) +response = client.indices.delete(index: 'students') ``` {% include copy.html %} ## Sample program -The following is a complete sample program that illustrates all of the concepts described in the preceding sections. The Ruby client's methods return responses as Ruby hashes, which are hard to read. To display JSON responses in a pretty format, the sample program uses the `MultiJson.dump` method. +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `# Without security` comments. + +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```ruby require 'opensearch' +require 'json' -client = OpenSearch::Client.new(host: 'http://localhost:9200') +client = OpenSearch::Client.new( + host: 'https://localhost:9200', # Without security, use http://localhost:9200 + user: 'admin', # Without security, remove this line + password: '', # Without security, remove this line + transport_options: { ssl: { verify: false } } # Without security, remove this line +) -# Create an index with non-default settings -index_name = 'students' +# Create the index +index = 'students' +puts 'Creating index......' index_body = { - 'settings': { - 'index': { - 'number_of_shards': 1, - 'number_of_replicas': 2 - } + settings: { + index: { + number_of_shards: 1, + number_of_replicas: 1 } - } - -client.indices.create( - index: index_name, - body: index_body -) - -# Create a mapping -client.indices.put_mapping( - index: index_name, - body: { - properties: { - first_name: { type: 'keyword' }, - last_name: { type: 'keyword' } - } - } -) - -# Get mappings -response = client.indices.get_mapping(index: index_name) -puts 'Mappings for the students index:' -puts MultiJson.dump(response, pretty: "true") - -# Add one document to the index -puts 'Adding one document:' -document = { - first_name: 'Connor', - last_name: 'James', - gpa: 3.93, - grad_year: 2021 -} -id = 100 - -client.index( - index: index_name, - body: document, - id: id, - refresh: true -) - -response = client.search(index: index_name) -puts MultiJson.dump(response, pretty: "true") - -# Update a document -puts 'Updating a document:' -client.update(index: index_name, id: id, body: { doc: { gpa: 3.25 } }, refresh: true) -response = client.search(index: index_name) -puts MultiJson.dump(response, pretty: "true") -print 'The updated gpa is ' -puts response['hits']['hits'].map { |doc| doc['_source']['gpa'] } - -# Add many documents in bulk -documents = [ -{ index: { _index: index_name, _id: '200' } }, -{ first_name: 'James', last_name: 'Rodriguez', gpa: 3.91, grad_year: 2019}, -{ index: { _index: index_name, _id: '300' } }, -{ first_name: 'Nikki', last_name: 'Wolf', gpa: 3.87, grad_year: 2020} -] -client.bulk(body: documents, refresh: true) - -# Get all documents in the index -response = client.search(index: index_name) -puts 'All documents in the index after bulk upload:' -puts MultiJson.dump(response, pretty: "true") - -# Search for a document using a multi_match query -puts 'Searching for documents that match "James":' -q = 'James' -query = { - 'size': 5, - 'query': { - 'multi_match': { - 'query': q, - 'fields': ['first_name', 'last_name^2'] + }, + mappings: { + properties: { + gradDate: { type: 'date', format: 'yyyy-MM-dd' } } } } +response = client.indices.create(index: index, body: index_body) +puts "Index created: #{response['index']}" -response = client.search( - body: query, - index: index_name -) -puts MultiJson.dump(response, pretty: "true") +# Index a document +puts "\nIndexing one student......" +student = { firstName: 'John', lastName: 'Doe', gpa: 3.89, gradDate: '2022-05-15' } +response = client.index(index: index, id: '1', body: student, refresh: true) +puts "Result: #{response['result']}, id: #{response['_id']}, version: #{response['_version']}" -# Delete the document -response = client.delete( -index: index_name, -id: id, -refresh: true -) - -response = client.search(index: index_name) -puts 'Documents in the index after one document was deleted:' -puts MultiJson.dump(response, pretty: "true") - -# Delete multiple documents +# Bulk index documents +puts "\nIndexing many students......" actions = [ - { delete: { _index: index_name, _id: 200 } }, - { delete: { _index: index_name, _id: 300 } } + { index: { _index: index, _id: '2' } }, + { firstName: 'Paulo', lastName: 'Santos', gpa: 3.93, gradDate: '2021-05-20' }, + { index: { _index: index, _id: '3' } }, + { firstName: 'Shirley', lastName: 'Rodriguez', gpa: 3.91, gradDate: '2019-05-10' } ] -client.bulk(body: actions, refresh: true) - -response = client.search(index: index_name) - -puts 'Documents in the index after all documents were deleted:' -puts MultiJson.dump(response, pretty: "true") - -# Bulk several operations together -actions = [ - { index: { _index: index_name, _id: 100, data: { first_name: 'Paulo', last_name: 'Santos', gpa: 3.29, grad_year: 2022 } } }, - { index: { _index: index_name, _id: 200, data: { first_name: 'Shirley', last_name: 'Rodriguez', gpa: 3.92, grad_year: 2020 } } }, - { index: { _index: index_name, _id: 300, data: { first_name: 'Akua', last_name: 'Mansa', gpa: 3.95, grad_year: 2022 } } }, - { index: { _index: index_name, _id: 400, data: { first_name: 'John', last_name: 'Stiles', gpa: 3.72, grad_year: 2019 } } }, - { index: { _index: index_name, _id: 500, data: { first_name: 'Li', last_name: 'Juan', gpa: 3.94, grad_year: 2022 } } }, - { index: { _index: index_name, _id: 600, data: { first_name: 'Richard', last_name: 'Roe', gpa: 3.04, grad_year: 2020 } } }, - { update: { _index: index_name, _id: 100, data: { doc: { gpa: 3.73 } } } }, - { delete: { _index: index_name, _id: 200 } } -] -client.bulk(body: actions, refresh: true) - -puts 'All documents in the index after bulk operations with scrolling:' -response = client.search(index: index_name, scroll: '2m', size: 2) - -while response['hits']['hits'].size.positive? - scroll_id = response['_scroll_id'] - puts(response['hits']['hits'].map { |doc| [doc['_source']['first_name'] + ' ' + doc['_source']['last_name']] }) - response = client.scroll(scroll: '1m', body: { scroll_id: scroll_id }) +response = client.bulk(body: actions, refresh: true) +puts "Errors: #{response['errors']}" +response['items'].each do |item| + puts " #{item['index']['result']} id: #{item['index']['_id']}" end -# Multi search -actions = [ - {}, - {query: {range: {gpa: {gt: 3.9}}}}, - {}, - {query: {range: {gpa: {lt: 3.1}}}} -] -response = client.msearch(index: index_name, body: actions) +# Search for all students +puts "\nSearching for all students......" +query = { sort: [{ gradDate: 'asc' }] } +[0, 2].each_with_index do |from, page| + response = client.search(index: index, from: from, size: 2, body: query) + puts "Total hits: #{response['hits']['total']['value']}" if page.zero? + puts "Page #{page + 1}:" + response['hits']['hits'].each { |hit| puts " #{JSON.generate(hit['_source'])}" } +end -puts 'Multi search results:' -puts MultiJson.dump(response, pretty: "true") +# Search for students who graduated in 2019 +puts "\nSearching for students who graduated in 2019......" +query = { query: { range: { gradDate: { gte: '2019-01-01', lte: '2019-12-31' } } } } +response = client.search(index: index, body: query) +puts "Total hits: #{response['hits']['total']['value']}" +response['hits']['hits'].each { |hit| puts " #{JSON.generate(hit['_source'])}" } -# Boolean query -query = { - 'query': { - 'bool': { - 'filter': { - 'term': { - 'grad_year': 2022 - - } - } - } - }, - 'sort': { - 'last_name': { - 'order': 'asc' - } - } -} +# Update a document +puts "\nUpdating a student's GPA......" +response = client.update(index: index, id: '1', body: { doc: { gpa: 3.92 } }) +puts "Result: #{response['result']}, version: #{response['_version']}" -response = client.search(index: index_name, from: 0, size: 10, body: query) +# Get the updated document +response = client.get(index: index, id: '1') +puts "Updated document: #{JSON.generate(response['_source'])}" -puts 'Boolean query search results:' -puts MultiJson.dump(response, pretty: "true") +# Delete a document +puts "\nDeleting a student......" +response = client.delete(index: index, id: '3', refresh: true) +puts "Result: #{response['result']}" # Delete the index -puts 'Deleting the index:' -response = client.indices.delete(index: index_name) - -puts MultiJson.dump(response, pretty: "true") +puts "\nDeleting the index......" +response = client.indices.delete(index: index) +puts "Acknowledged: #{response['acknowledged']}" ``` {% include copy.html %} -# Ruby AWS Sigv4 Client +The program produces the following output: -The [opensearch-aws-sigv4](https://github.com/opensearch-project/opensearch-ruby-aws-sigv4) gem provides the `OpenSearch::Aws::Sigv4Client` class, which has all features of `OpenSearch::Client`. The only difference between these two clients is that `OpenSearch::Aws::Sigv4Client` requires an instance of `Aws::Sigv4::Signer` during instantiation to authenticate with AWS: +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + {"firstName":"Paulo","lastName":"Santos","gpa":3.93,"gradDate":"2021-05-20"} +Page 2: + {"firstName":"John","lastName":"Doe","gpa":3.89,"gradDate":"2022-05-15"} + +Searching for students who graduated in 2019...... +Total hits: 1 + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: {"firstName":"John","lastName":"Doe","gpa":3.92,"gradDate":"2022-05-15"} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +# Ruby AWS Signature Version 4 client + +The [`opensearch-aws-sigv4`](https://github.com/opensearch-project/opensearch-ruby-aws-sigv4) gem provides the `OpenSearch::Aws::Sigv4Client` class, which has all features of `OpenSearch::Client`. The only difference between these two clients is that `OpenSearch::Aws::Sigv4Client` requires an instance of `Aws::Sigv4::Signer` during instantiation to authenticate with AWS: ```ruby require 'opensearch-aws-sigv4' require 'aws-sigv4' signer = Aws::Sigv4::Signer.new(service: 'es', - region: 'us-west-2', + region: 'us-east-1', access_key_id: 'key_id', - secret_access_key: 'secret') + secret_access_key: 'secret', + session_token: 'session_token') # required for temporary credentials, such as IAM roles or SSO -client = OpenSearch::Aws::Sigv4Client.new({ log: true }, signer) +client = OpenSearch::Aws::Sigv4Client.new({ + host: 'https://search--.us-east-1.es.amazonaws.com', + log: true +}, signer) client.cluster.health -client.transport.reload_connections! - -client.search q: 'test' +client.search(index: 'students', q: 'firstName:John') ``` -{% include copy.html %} \ No newline at end of file +{% include copy.html %} + +## Related documentation + +- For more examples of using the client, see the [`opensearch-ruby` user guide](https://github.com/opensearch-project/opensearch-ruby/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-ruby` guides](https://github.com/opensearch-project/opensearch-ruby/tree/main/guides). +- For complete sample applications, see the [`opensearch-ruby` samples](https://github.com/opensearch-project/opensearch-ruby/tree/main/samples). diff --git a/_clients/rust.md b/_clients/rust.md index 36d1d24d..83613a77 100644 --- a/_clients/rust.md +++ b/_clients/rust.md @@ -8,30 +8,30 @@ nav_order: 100 The OpenSearch Rust client lets you connect your Rust application with the data in your OpenSearch cluster. For the client's complete API documentation and additional examples, see the [OpenSearch docs.rs documentation](https://docs.rs/opensearch/). -This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [opensearch-rs repo](https://github.com/opensearch-project/opensearch-rs). +This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the [`opensearch-rs` repo](https://github.com/opensearch-project/opensearch-rs). For the OpenSearch versions that each client version supports, see the client's [compatibility matrix](https://github.com/opensearch-project/opensearch-rs/blob/main/COMPATIBILITY.md). -## Setup +## Installing the Rust client If you're starting a new project, add the `opensearch` crate to Cargo.toml: -```rust +```toml [dependencies] -opensearch = "1.0.0" +opensearch = "2.4.0" ``` {% include copy.html %} -Additionally, you may want to add the following `serde` dependencies that help serialize types to JSON and deserialize JSON responses: +Additionally, you may want to add the following `serde` dependencies that help serialize types to JSON and deserialize JSON responses. The `derive` feature lets you derive `Serialize` and `Deserialize` for your own structs: -```rust -serde = "~1" +```toml +serde = { version = "~1", features = ["derive"] } serde_json = "~1" ``` {% include copy.html %} -The Rust client uses the higher-level [`reqwest`](https://crates.io/crates/reqwest) HTTP client library for HTTP requests, and reqwest uses the [`tokio`](https://crates.io/crates/tokio) platform to support asynchronous requests. If you are planning to use asynchronous functions, you need to add the `tokio` dependency to Cargo.toml: +The Rust client uses the higher-level [`reqwest`](https://crates.io/crates/reqwest) HTTP client library for HTTP requests, and `reqwest` uses the [`tokio`](https://crates.io/crates/tokio) platform to support asynchronous requests. If you are planning to use asynchronous functions, you need to add the `tokio` dependency to Cargo.toml: -```rust -tokio = { version = "*", features = ["full"] } +```toml +tokio = { version = "1", features = ["full"] } ``` {% include copy.html %} @@ -44,6 +44,35 @@ use opensearch::OpenSearch; ``` {% include copy.html %} +## Sample data + +The examples on this page use a `Student` struct to represent documents. The `#[serde(rename_all = "camelCase")]` attribute serializes the struct fields to the `firstName`, `lastName`, `gpa`, and `gradDate` JSON fields: + +```rust +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Student { + first_name: String, + last_name: String, + gpa: f64, + grad_date: String, +} + +impl Student { + fn new(first_name: &str, last_name: &str, gpa: f64, grad_date: &str) -> Self { + Student { + first_name: first_name.to_string(), + last_name: last_name.to_string(), + gpa, + grad_date: grad_date.to_string(), + } + } +} +``` +{% include copy.html %} + ## Connecting to OpenSearch To connect to the default OpenSearch host, create a default client object that connects to OpenSearch at the address `http://localhost:9200`: @@ -53,6 +82,17 @@ let client = OpenSearch::default(); ``` {% include copy.html %} +The remaining connection examples on this page require the following imports: + +```rust +use opensearch::{ + http::transport::{SingleNodeConnectionPool, Transport, TransportBuilder}, + http::Url, + OpenSearch, +}; +``` +{% include copy.html %} + To connect to an OpenSearch host that is running at a different address, create a client with the specified address: ```rust @@ -71,18 +111,56 @@ let client = OpenSearch::new(transport); ``` {% include copy.html %} +To connect to a cluster that has the Security plugin enabled, use HTTPS and provide basic authentication credentials. The following example also disables certificate validation so that the client accepts the self-signed demo certificates. Import `Credentials` from `opensearch::auth` and `CertificateValidation` from `opensearch::cert`: + +```rust +let url = Url::parse("https://localhost:9200")?; +let conn_pool = SingleNodeConnectionPool::new(url); +let transport = TransportBuilder::new(conn_pool) + // Only for demo purposes. Don't specify your credentials in code. + .auth(Credentials::Basic( + "admin".to_string(), + "".to_string(), + )) + // Only for demo purposes. Disables certificate validation for self-signed certificates. + .cert_validation(CertificateValidation::None) + .build()?; +let client = OpenSearch::new(transport); +``` +{% include copy.html %} + ## Connecting to Amazon OpenSearch Service +To sign requests using AWS Signature Version 4, enable the `aws-auth` feature of the `opensearch` crate and add the `aws-config` dependency to Cargo.toml: + +```toml +opensearch = { version = "2.4.0", features = ["aws-auth"] } +aws-config = "1" +``` +{% include copy.html %} + +Then import the AWS configuration types: + +```rust +use aws_config::{meta::region::RegionProviderChain, BehaviorVersion}; +``` +{% include copy.html %} + +In the following example, replace the endpoint with your domain endpoint, which is listed on the domain's details page in the Amazon OpenSearch Service console. + The following example illustrates connecting to Amazon OpenSearch Service: ```rust -let url = Url::parse("https://..."); +let url = Url::parse("https://search--.us-east-1.es.amazonaws.com")?; let service_name = "es"; -let conn_pool = SingleNodeConnectionPool::new(url?); +let conn_pool = SingleNodeConnectionPool::new(url); let region_provider = RegionProviderChain::default_provider().or_else("us-east-1"); -let aws_config = aws_config::from_env().region(region_provider).load().await.clone(); +let aws_config = aws_config::defaults(BehaviorVersion::latest()) + .region(region_provider) + .load() + .await; let transport = TransportBuilder::new(conn_pool) - .auth(aws_config.clone().try_into()?) + .auth(aws_config.try_into()?) .service_name(service_name) .build()?; let client = OpenSearch::new(transport); @@ -91,35 +169,49 @@ let client = OpenSearch::new(transport); ## Connecting to Amazon OpenSearch Serverless -The following example illustrates connecting to Amazon OpenSearch Serverless Service: +In the following example, replace the endpoint with your collection endpoint, which is listed on the collection's details page in the Amazon OpenSearch Service console. + +Connecting to Amazon OpenSearch Serverless requires the same `aws-auth` feature, `aws-config` dependency, and imports as [connecting to Amazon OpenSearch Service](#connecting-to-amazon-opensearch-service). The following example illustrates connecting to Amazon OpenSearch Serverless: ```rust -let url = Url::parse("https://..."); +let url = Url::parse("https://.us-east-1.aoss.amazonaws.com")?; let service_name = "aoss"; -let conn_pool = SingleNodeConnectionPool::new(url?); +let conn_pool = SingleNodeConnectionPool::new(url); let region_provider = RegionProviderChain::default_provider().or_else("us-east-1"); -let aws_config = aws_config::from_env().region(region_provider).load().await.clone(); +let aws_config = aws_config::defaults(BehaviorVersion::latest()) + .region(region_provider) + .load() + .await; let transport = TransportBuilder::new(conn_pool) - .auth(aws_config.clone().try_into()?) + .auth(aws_config.try_into()?) .service_name(service_name) .build()?; let client = OpenSearch::new(transport); ``` {% include copy.html %} +Amazon OpenSearch Serverless supports a subset of OpenSearch API operations and does not support the `refresh` parameter used in the examples on this page. For more information, see [Supported operations and plugins in Amazon OpenSearch Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-genref.html). +{: .note} ## Creating an index -To create an OpenSearch index, use the `create` function of the `opensearch::indices::Indices` struct. You can use the following code to construct a JSON object with custom mappings: +The following example creates an index with one primary shard and one replica. It explicitly maps the `gradDate` field as a `date` in the `yyyy-MM-dd` format. OpenSearch maps the other document fields dynamically when you index documents: ```rust +let index = "students"; let response = client .indices() - .create(IndicesCreateParts::Index("movies")) + .create(IndicesCreateParts::Index(index)) .body(json!({ - "mappings" : { - "properties" : { - "title" : { "type" : "text" } + "settings": { + "index": { + "number_of_shards": 1, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "gradDate": { "type": "date", "format": "yyyy-MM-dd" } } } })) @@ -130,17 +222,14 @@ let response = client ## Indexing a document -You can index a document into OpenSearch using the client's `index` function: +You can index a document into OpenSearch using the client's `index` function. The `refresh(Refresh::True)` call makes the document immediately available for search. `Refresh` is defined in the `opensearch::params` module: ```rust +let student = Student::new("John", "Doe", 3.89, "2022-05-15"); let response = client - .index(IndexParts::IndexId("movies", "1")) - .body(json!({ - "id": 1, - "title": "Moneyball", - "director": "Bennett Miller", - "year": "2011" - })) + .index(IndexParts::IndexId(index, "1")) + .body(student) + .refresh(Refresh::True) .send() .await?; ``` @@ -151,29 +240,16 @@ let response = client You can perform several operations at the same time by using the client's `bulk` function. First, create the JSON body of a Bulk API call, and then pass it to the `bulk` function: ```rust -let mut body: Vec> = Vec::with_capacity(4); - -// add the first operation and document -body.push(json!({"index": {"_id": "2"}}).into()); -body.push(json!({ - "id": 2, - "title": "Interstellar", - "director": "Christopher Nolan", - "year": "2014" -}).into()); - -// add the second operation and document -body.push(json!({"index": {"_id": "3"}}).into()); -body.push(json!({ - "id": 3, - "title": "Star Trek Beyond", - "director": "Justin Lin", - "year": "2015" -}).into()); - +let body: Vec> = vec![ + json!({"index": {"_id": "2"}}).into(), + serde_json::to_value(Student::new("Paulo", "Santos", 3.93, "2021-05-20"))?.into(), + json!({"index": {"_id": "3"}}).into(), + serde_json::to_value(Student::new("Shirley", "Rodriguez", 3.91, "2019-05-10"))?.into(), +]; let response = client - .bulk(BulkParts::Index("movies")) + .bulk(BulkParts::Index(index)) .body(body) + .refresh(Refresh::True) .send() .await?; ``` @@ -181,19 +257,55 @@ let response = client ## Searching for documents -The easiest way to search for documents is to construct a query string. The following code uses a `multi_match` query to search for "miller" in the title and director fields. It boosts the documents where "miller" appears in the title field: +To search for all documents in an index, send a search request without a query: ```rust -response = client - .search(SearchParts::Index(&["movies"])) - .from(0) - .size(10) +let response = client + .search(SearchParts::Index(&[index])) + .send() + .await?; +``` +{% include copy.html %} + +You can then read the response body as JSON and iterate over the `hits` array to deserialize each `_source` document into a `Student`: + +```rust +let response_body = response.json::().await?; +println!("Total hits: {}", response_body["hits"]["total"]["value"]); +for hit in response_body["hits"]["hits"].as_array().unwrap_or(&vec![]) { + let student: Student = serde_json::from_value(hit["_source"].clone())?; + println!(" {}", serde_json::to_string(&student)?); +} +``` +{% include copy.html %} + +Each `_source` document deserializes into a `Student` struct, so the document fields are available as struct fields, such as `student.first_name`. Each hit contains the document ID in `hit["_id"]` and the document in `hit["_source"]`. To print the ID and fields of each document, use the following code: + +```rust +for hit in response_body["hits"]["hits"].as_array().unwrap_or(&vec![]) { + let id = hit["_id"].as_str().unwrap_or_default(); + let student: Student = serde_json::from_value(hit["_source"].clone())?; + println!( + "ID: {}, name: {} {}, GPA: {}, graduation date: {}", + id, student.first_name, student.last_name, student.gpa, student.grad_date + ); +} +``` +{% include copy.html %} + +To search for students who graduated in 2019, use a `range` query on the `gradDate` field: + +```rust +let response = client + .search(SearchParts::Index(&[index])) .body(json!({ "query": { - "multi_match": { - "query": "miller", - "fields": ["title^2", "director"] - } + "range": { + "gradDate": { + "gte": "2019-01-01", + "lte": "2019-12-31" + } + } } })) .send() @@ -201,14 +313,55 @@ response = client ``` {% include copy.html %} -You can then read the response body as JSON and iterate over the `hits` array to read all the `_source` documents: +## Paginating results + +To paginate results, use the `from` and `size` parameters. The following example sorts students by graduation date and retrieves the results two at a time. The first request returns the first page of results, and the second request returns the next page: ```rust -let response_body = response.json::().await?; -for hit in response_body["hits"]["hits"].as_array().unwrap() { - // print the source document - println!("{}", serde_json::to_string_pretty(&hit["_source"]).unwrap()); -} +let response = client + .search(SearchParts::Index(&[index])) + .from(0) + .size(2) + .sort(&["gradDate:asc"]) + .send() + .await?; + +let next_page = client + .search(SearchParts::Index(&[index])) + .from(2) + .size(2) + .sort(&["gradDate:asc"]) + .send() + .await?; +``` +{% include copy.html %} + +The `from` and `size` parameters work well for the first pages of results. To paginate through a large number of results, use point in time with `search_after`. For more information, see [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/). + +## Updating a document + +You can update a document using the client's `update` function. The following example sets the `gpa` field of the document with the ID `1` to `3.92`: + +```rust +let response = client + .update(UpdateParts::IndexId(index, "1")) + .body(json!({ + "doc": { + "gpa": 3.92 + } + })) + .send() + .await?; +``` +{% include copy.html %} + +To retrieve the updated document, use the client's `get` function: + +```rust +let response = client + .get(GetParts::IndexId(index, "1")) + .send() + .await?; ``` {% include copy.html %} @@ -218,7 +371,8 @@ You can delete a document using the client's `delete` function: ```rust let response = client - .delete(DeleteParts::IndexId("movies", "2")) + .delete(DeleteParts::IndexId(index, "3")) + .refresh(Refresh::True) .send() .await?; ``` @@ -231,7 +385,7 @@ You can delete an index using the `delete` function of the `opensearch::indices: ```rust let response = client .indices() - .delete(IndicesDeleteParts::Index(&["movies"])) + .delete(IndicesDeleteParts::Index(&[index])) .send() .await?; ``` @@ -239,9 +393,11 @@ let response = client ## Sample program -The sample program uses the following Cargo.toml file with all dependencies described in the [Setup](#setup) section: +This sample program combines the code from the preceding sections. It connects to a cluster that has the Security plugin enabled. To connect to a cluster without the Security plugin, change the lines marked with `// Without security` comments. -```rust +The sample program uses the following Cargo.toml file with all dependencies described in the [Installing the Rust client](#installing-the-rust-client) section: + +```toml [package] name = "os_rust_project" version = "0.1.0" @@ -250,167 +406,277 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -opensearch = "1.0.0" -tokio = { version = "*", features = ["full"] } -serde = "~1" +opensearch = "2.4.0" +tokio = { version = "1", features = ["full"] } +serde = { version = "~1", features = ["derive"] } serde_json = "~1" ``` {% include copy.html %} -The following sample program creates a client, adds an index with non-default mappings, inserts a document, performs bulk operations, searches for the document, deletes the document, and then deletes the index: +This sample program is for testing only. It specifies credentials in code and disables certificate validation so that it can connect to a cluster that uses self-signed certificates. In production, load credentials from a secure location and validate the cluster's certificate. +{: .warning} + +The following sample program creates a client, creates an index, indexes documents individually and in bulk, searches for documents, updates a document, deletes a document, and then deletes the index: ```rust -use opensearch::{DeleteParts, OpenSearch, IndexParts, http::request::JsonBody, BulkParts, SearchParts}; -use opensearch::{indices::{IndicesDeleteParts, IndicesCreateParts}}; +use opensearch::{ + auth::Credentials, // Without security, remove this line + cert::CertificateValidation, // Without security, remove this line + http::request::JsonBody, + http::transport::{SingleNodeConnectionPool, TransportBuilder}, + http::Url, + indices::{IndicesCreateParts, IndicesDeleteParts}, + params::Refresh, + BulkParts, DeleteParts, GetParts, IndexParts, OpenSearch, SearchParts, UpdateParts, +}; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Student { + first_name: String, + last_name: String, + gpa: f64, + grad_date: String, +} + +impl Student { + fn new(first_name: &str, last_name: &str, gpa: f64, grad_date: &str) -> Self { + Student { + first_name: first_name.to_string(), + last_name: last_name.to_string(), + gpa, + grad_date: grad_date.to_string(), + } + } +} + +fn print_students(response_body: &Value) -> Result<(), Box> { + for hit in response_body["hits"]["hits"].as_array().unwrap_or(&vec![]) { + let student: Student = serde_json::from_value(hit["_source"].clone())?; + println!(" {}", serde_json::to_string(&student)?); + } + Ok(()) +} + +fn print_hits(response_body: &Value) -> Result<(), Box> { + println!("Total hits: {}", response_body["hits"]["total"]["value"]); + print_students(response_body) +} + #[tokio::main] async fn main() -> Result<(), Box> { - let client = OpenSearch::default(); + let url = Url::parse("https://localhost:9200")?; // Without security, use http://localhost:9200 + let conn_pool = SingleNodeConnectionPool::new(url); + let transport = TransportBuilder::new(conn_pool) + // Without security, remove this line + .auth(Credentials::Basic("admin".to_string(), "".to_string())) + .cert_validation(CertificateValidation::None) // Without security, remove this line + .build()?; + let client = OpenSearch::new(transport); - // Create an index - let mut response = client - .indices() - .create(IndicesCreateParts::Index("movies")) - .body(json!({ - "mappings" : { - "properties" : { - "title" : { "type" : "text" } + // Create the index + let index = "students"; + println!("Creating index......"); + let response_body = client + .indices() + .create(IndicesCreateParts::Index(index)) + .body(json!({ + "settings": { + "index": { + "number_of_shards": 1, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "gradDate": { "type": "date", "format": "yyyy-MM-dd" } + } } - } - })) - .send() - .await?; - - let mut successful = response.status_code().is_success(); - - if successful { - println!("Successfully created an index"); - } - else { - println!("Could not create an index"); - } - - // Index a single document - println!("Indexing a single document..."); - response = client - .index(IndexParts::IndexId("movies", "1")) - .body(json!({ - "id": 1, - "title": "Moneyball", - "director": "Bennett Miller", - "year": "2011" - })) - .send() - .await?; - - successful = response.status_code().is_success(); - - if successful { - println!("Successfully indexed a document"); - } - else { - println!("Could not index document"); - } - - // Index multiple documents using the bulk operation - - println!("Indexing multiple documents..."); - - let mut body: Vec> = Vec::with_capacity(4); - - // add the first operation and document - body.push(json!({"index": {"_id": "2"}}).into()); - body.push(json!({ - "id": 2, - "title": "Interstellar", - "director": "Christopher Nolan", - "year": "2014" - }).into()); - - // add the second operation and document - body.push(json!({"index": {"_id": "3"}}).into()); - body.push(json!({ - "id": 3, - "title": "Star Trek Beyond", - "director": "Justin Lin", - "year": "2015" - }).into()); - - response = client - .bulk(BulkParts::Index("movies")) - .body(body) + })) .send() + .await? + .json::() .await?; + println!("Index created: {}", response_body["index"].as_str().unwrap_or_default()); - let mut response_body = response.json::().await?; - successful = response_body["errors"].as_bool().unwrap() == false; + // Index a document + println!("\nIndexing one student......"); + let student = Student::new("John", "Doe", 3.89, "2022-05-15"); + let response_body = client + .index(IndexParts::IndexId(index, "1")) + .body(student) + .refresh(Refresh::True) + .send() + .await? + .json::() + .await?; + println!( + "Result: {}, id: {}, version: {}", + response_body["result"].as_str().unwrap_or_default(), + response_body["_id"].as_str().unwrap_or_default(), + response_body["_version"] + ); - if successful { - println!("Successfully performed bulk operations"); - } - else { - println!("Could not perform bulk operations"); + // Bulk index documents + println!("\nIndexing many students......"); + let body: Vec> = vec![ + json!({"index": {"_id": "2"}}).into(), + serde_json::to_value(Student::new("Paulo", "Santos", 3.93, "2021-05-20"))?.into(), + json!({"index": {"_id": "3"}}).into(), + serde_json::to_value(Student::new("Shirley", "Rodriguez", 3.91, "2019-05-10"))?.into(), + ]; + let response_body = client + .bulk(BulkParts::Index(index)) + .body(body) + .refresh(Refresh::True) + .send() + .await? + .json::() + .await?; + println!("Errors: {}", response_body["errors"]); + for item in response_body["items"].as_array().unwrap_or(&vec![]) { + println!( + " {} id: {}", + item["index"]["result"].as_str().unwrap_or_default(), + item["index"]["_id"].as_str().unwrap_or_default() + ); } - // Search for a document - - println!("Searching for a document..."); - response = client - .search(SearchParts::Index(&["movies"])) - .from(0) - .size(10) - .body(json!({ - "query": { - "multi_match": { - "query": "miller", - "fields": ["title^2", "director"] - } + // Search for all students, two at a time, sorted by graduation date + println!("\nSearching for all students......"); + for (page, from) in [(1, 0), (2, 2)] { + let response_body = client + .search(SearchParts::Index(&[index])) + .from(from) + .size(2) + .sort(&["gradDate:asc"]) + .send() + .await? + .json::() + .await?; + if page == 1 { + println!("Total hits: {}", response_body["hits"]["total"]["value"]); } - })) - .send() - .await?; - - response_body = response.json::().await?; - for hit in response_body["hits"]["hits"].as_array().unwrap() { - // print the source document - println!("{}", serde_json::to_string_pretty(&hit["_source"]).unwrap()); + println!("Page {}:", page); + print_students(&response_body)?; } + // Search for students who graduated in 2019 + println!("\nSearching for students who graduated in 2019......"); + let response_body = client + .search(SearchParts::Index(&[index])) + .body(json!({ + "query": { + "range": { + "gradDate": { + "gte": "2019-01-01", + "lte": "2019-12-31" + } + } + } + })) + .send() + .await? + .json::() + .await?; + print_hits(&response_body)?; + + // Update a document + println!("\nUpdating a student's GPA......"); + let response_body = client + .update(UpdateParts::IndexId(index, "1")) + .body(json!({ + "doc": { + "gpa": 3.92 + } + })) + .send() + .await? + .json::() + .await?; + println!( + "Result: {}, version: {}", + response_body["result"].as_str().unwrap_or_default(), + response_body["_version"] + ); + + // Get the updated document + let response_body = client + .get(GetParts::IndexId(index, "1")) + .send() + .await? + .json::() + .await?; + let student: Student = serde_json::from_value(response_body["_source"].clone())?; + println!("Updated document: {}", serde_json::to_string(&student)?); + // Delete a document - - response = client - .delete(DeleteParts::IndexId("movies", "2")) - .send() - .await?; - - successful = response.status_code().is_success(); - - if successful { - println!("Successfully deleted a document"); - } - else { - println!("Could not delete document"); - } + println!("\nDeleting a student......"); + let response_body = client + .delete(DeleteParts::IndexId(index, "3")) + .refresh(Refresh::True) + .send() + .await? + .json::() + .await?; + println!("Result: {}", response_body["result"].as_str().unwrap_or_default()); // Delete the index + println!("\nDeleting the index......"); + let response_body = client + .indices() + .delete(IndicesDeleteParts::Index(&[index])) + .send() + .await? + .json::() + .await?; + println!("Acknowledged: {}", response_body["acknowledged"]); - response = client - .indices() - .delete(IndicesDeleteParts::Index(&["movies"])) - .send() - .await?; - - successful = response.status_code().is_success(); - - if successful { - println!("Successfully deleted the index"); - } - else { - println!("Could not delete the index"); - } - Ok(()) } ``` -{% include copy.html %} \ No newline at end of file +{% include copy.html %} + +The program produces the following output: + +``` +Creating index...... +Index created: students + +Indexing one student...... +Result: created, id: 1, version: 1 + +Indexing many students...... +Errors: false + created id: 2 + created id: 3 + +Searching for all students...... +Total hits: 3 +Page 1: + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + {"firstName":"Paulo","lastName":"Santos","gpa":3.93,"gradDate":"2021-05-20"} +Page 2: + {"firstName":"John","lastName":"Doe","gpa":3.89,"gradDate":"2022-05-15"} + +Searching for students who graduated in 2019...... +Total hits: 1 + {"firstName":"Shirley","lastName":"Rodriguez","gpa":3.91,"gradDate":"2019-05-10"} + +Updating a student's GPA...... +Result: updated, version: 2 +Updated document: {"firstName":"John","lastName":"Doe","gpa":3.92,"gradDate":"2022-05-15"} + +Deleting a student...... +Result: deleted + +Deleting the index...... +Acknowledged: true +``` + +## Related documentation + +- For more examples of using the client, see the [`opensearch-rs` user guide](https://github.com/opensearch-project/opensearch-rs/blob/main/USER_GUIDE.md). +- For guides to specific tasks, such as bulk indexing and searching, see the [`opensearch-rs` guides](https://github.com/opensearch-project/opensearch-rs/tree/main/guides). diff --git a/_dashboards/branding.md b/_dashboards/branding.md index f4e4c1f4..069fd603 100644 --- a/_dashboards/branding.md +++ b/_dashboards/branding.md @@ -1,14 +1,15 @@ --- layout: default title: Custom branding -nav_order: 130 +parent: Settings and administration +nav_order: 40 --- # Custom branding Introduced 1.2 {: .label .label-purple } -By default, OpenSearch Dashboards uses the OpenSearch logo, but if you want to use custom branding elements such as the favicon or main Dashboards logo, you can do so by editing `opensearch_dashboards.yml` or by including a custom `opensearch_dashboards.yml` file when you start your OpenSearch cluster. +By default, OpenSearch Dashboards uses the OpenSearch logo, but if you want to use custom branding elements such as the `favicon` or main Dashboards logo, you can do so by editing `opensearch_dashboards.yml` or by including a custom `opensearch_dashboards.yml` file when you start your OpenSearch cluster. For example, if you're using Docker to start your OpenSearch cluster, include the following lines in the `opensearch-dashboards` section of your `docker-compose.yml` file: @@ -17,7 +18,7 @@ volumes: - ./opensearch_dashboards.yml:/usr/share/opensearch-dashboards/config/opensearch_dashboards.yml ``` -Doing so replaces the Docker image's default `opensearch_dashboards.yml` with your custom `opensearch_dashboards.yml` file, so be sure to include your desired settings as well. For example, if you want to configure TLS for OpenSearch Dashboards, see [Configure TLS for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/install/tls). +Doing so replaces the Docker image's default `opensearch_dashboards.yml` with your custom `opensearch_dashboards.yml` file, so be sure to include your desired settings as well. For example, if you want to configure TLS for OpenSearch Dashboards, see [Configure TLS for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/install/tls/). Re-launch OpenSearch Dashboards, and OpenSearch Dashboards now uses your custom elements. @@ -29,11 +30,11 @@ The following elements in OpenSearch Dashboards are customizable: Setting | Corresponding branding element :--- | :--- -logo | Header logo. See #1 in the image. -mark | OpenSearch Dashboards mark. See #2 in the image. -loadingLogo | Loading logo used when OpenSearch Dashboards is starting. See #3 in the image. -faviconUrl | Website icon. Loads next to the application title. See #4 in the image. -applicationTitle | The application's title. See #5 in the image. +`logo` | Header logo. See #1 in the image. +`mark` | OpenSearch Dashboards mark. See #2 in the image. +`loadingLogo` | Loading logo used when OpenSearch Dashboards is starting. See #3 in the image. +`faviconUrl` | Website icon. Loads next to the application title. See #4 in the image. +`applicationTitle` | The application's title. See #5 in the image. To consolidate navigation controls and reduce the space the header takes up on the page, see [Condensed header](#condensed-header). {: .note} @@ -118,7 +119,7 @@ The current default view remains close in appearance to the two-bar header offer In a future release, default behavior will become `useExpandedHeader: false`. If you want to retain the default view in subsequent releases, you can explicitly set the property to `true` in advance. Alternatively, you can also do this when upgrading. {: .note } -The condensed view header appears as in the example below. +The condensed view header appears as in the following example. ![Condensed header]({{site.url}}{{site.baseurl}}/images/DBs-Condensed.jpeg) @@ -137,9 +138,9 @@ Home button | See #1. Returns to the home page and provides an indication when a Header label | See #2. The label also functions as a home button. Navigation controls | See #3. Additional navigation controls on right-side insertion points. -#### Preserving nagivation elements in the default view +#### Preserving navigation elements in the default view -You can continue using the top header bar in the default view for custom navigation links (such as menu items and plugins). Follow the steps below to keep these elements in the top header in the default view. +You can continue using the top header bar in the default view for custom navigation links (such as menu items and plugins). Follow the following steps to keep these elements in the top header in the default view. 1. Replace the property `coreStart.chrome.navControls.registerRight(...)` with `coreStart.chrome.navControls.registerExpandedRight(...)` and then replace the property `coreStart.chrome.navControls.registerCenter(...)` with `coreStart.chrome.navControls.registerExpandedCenter(...)` 2. Make sure the configuration property `useExpandedHeader` is explicitly set to `true`. diff --git a/_dashboards/compression.md b/_dashboards/compression.md new file mode 100644 index 00000000..4d7092ac --- /dev/null +++ b/_dashboards/compression.md @@ -0,0 +1,182 @@ +--- +layout: default +title: Network compression +parent: Settings and administration +nav_order: 50 +--- + +# Network compression +**Introduced 1.0** +{: .label .label-purple } + +OpenSearch Dashboards supports automatic compression of JavaScript and CSS bundles to reduce network transfer sizes. This feature is especially useful when deploying OpenSearch Dashboards behind a proxy, gateway, or load balancer that has response size limitations. + +## Compression methods + +OpenSearch Dashboards generates pre-compressed versions of all plugin bundles using the following compression algorithms: + +- **Brotli (`br`)**: Modern compression algorithm providing the best compression ratio +- **gzip (`gz`)**: Widely supported compression algorithm with good compatibility + +When a client requests a bundle file, OpenSearch Dashboards automatically serves the compressed version if the client sends the appropriate `Accept-Encoding` header. If no compression encoding is specified, OpenSearch Dashboards serves the uncompressed file. + +## Compression effectiveness + +The following table shows typical compression ratios for large plugin bundles, using the Observability plugin as an example: + +| Compression method | File size | Compression ratio | +|:---|:---|:---| +| Brotli (`br`) | ~1.8 MB | ~86% reduction | +| gzip (`gz`) | ~2.5 MB | ~80% reduction | +| Uncompressed | ~12.6 MB | Baseline | + +The actual compression ratio varies depending on the plugin and its dependencies. + +## Configuration + +Compression is enabled by default. You can control compression behavior using the following settings in `opensearch_dashboards.yml`. + +### `server.compression.enabled` + +Enables or disables HTTP compression for all responses. When set to `false`, OpenSearch Dashboards serves only uncompressed content, regardless of client headers. + +- **Type**: Boolean +- **Default**: `true` +- **Example**: + + ```yaml + server: + compression: + enabled: true + ``` + {% include copy.html %} + +### `server.compression.referrerWhitelist` + +Limits compression to requests from specific referrer hostnames. When this setting is configured, OpenSearch Dashboards only compresses responses for requests that come from the specified referrers. This setting is only valid when `server.compression.enabled` is `true`. + +- **Type**: Array of strings +- **Default**: Not set (compression enabled for all referrers) +- **Example**: + + ```yaml + server: + compression: + enabled: true + referrerWhitelist: + - trusted-proxy.example.com + - api-gateway.example.com + ``` + {% include copy.html %} + +## Using compression with proxies + +When deploying OpenSearch Dashboards behind a proxy, gateway, or load balancer, configure your proxy to request compressed content by including the `Accept-Encoding` header in upstream requests. + +### Example: Requesting Brotli compression + +```bash +curl -H 'Accept-Encoding: br' \ + https://your-dashboards-host/bundles/plugin/observabilityDashboards/observabilityDashboards.plugin.js +``` +{% include copy.html %} + +The response includes the `Content-Encoding: br` header, indicating that Brotli compression was applied: + +```bash +HTTP/1.1 200 OK +content-type: application/javascript; charset=utf-8 +cache-control: max-age=31536000 +content-encoding: br +osd-name: dashboards-opensearch-dashboards-55cf49965-9bcwz +vary: accept-encoding +Date: Wed, 08 May 2024 00:01:14 GMT +Connection: keep-alive +Keep-Alive: timeout=120 +Transfer-Encoding: chunked +``` + +### Example: Requesting zip compression + +```bash +curl -H 'Accept-Encoding: gzip' \ + https://your-dashboards-host/bundles/plugin/observabilityDashboards/observabilityDashboards.plugin.js +``` +{% include copy.html %} + +The response includes the `Content-Encoding: gzip` header: + +```bash +HTTP/1.1 200 OK +content-type: application/javascript; charset=utf-8 +cache-control: max-age=31536000 +content-encoding: gzip +osd-name: dashboards-opensearch-dashboards-55cf49965-9bcwz +vary: accept-encoding +Date: Wed, 08 May 2024 00:01:14 GMT +Connection: keep-alive +Keep-Alive: timeout=120 +Transfer-Encoding: chunked +``` + +### Example: No compression + +If you don't specify an `Accept-Encoding` header (or if compression is disabled), OpenSearch Dashboards serves the uncompressed file: + +```bash +curl https://your-dashboards-host/bundles/plugin/observabilityDashboards/observabilityDashboards.plugin.js +``` +{% include copy.html %} + +### Proxy configuration examples + +The following examples show how to configure different proxy servers to request compressed content. + +#### NGINX + +Configure NGINX to request compressed content from OpenSearch Dashboards: + +```json +location / { + proxy_pass http://opensearch-dashboards:5601; + proxy_set_header Accept-Encoding "br, gzip"; + proxy_set_header Host $host; +} +``` +{% include copy.html %} + +#### Apache + +Configure Apache to request compressed content from OpenSearch Dashboards: + +```xml + + ProxyPass http://opensearch-dashboards:5601/ + ProxyPassReverse http://opensearch-dashboards:5601/ + RequestHeader set Accept-Encoding "br, gzip" + +``` +{% include copy.html %} + +## Proxy response size limits + +If your proxy or gateway has response size limits (for example, 10 MB), follow these steps to address them: + +1. Configure your proxy to request Brotli compression first (best compression ratio): + ``` + Accept-Encoding: br, gzip + ``` + {% include copy.html %} + +2. Verify that the compressed bundle size is within your proxy's limits. Most OpenSearch Dashboards plugin bundles compress to less than 3 MB with Brotli. + +3. If issues persist, consider increasing your proxy's response size limit or breaking large plugins into smaller components. + +## Browser support + +All modern browsers automatically include the `Accept-Encoding` header in their requests and transparently decompress responses. Compression is handled automatically without any configuration required on the browser side. + +Browser support for compression methods: + +- **Brotli**: Supported in all modern browsers (Chrome, Firefox, Safari, Edge) +- **gzip**: Universally supported by all browsers diff --git a/_dashboards/csp/csp-dynamic-configuration.md b/_dashboards/csp/csp-dynamic-configuration.md new file mode 100644 index 00000000..1365a6cf --- /dev/null +++ b/_dashboards/csp/csp-dynamic-configuration.md @@ -0,0 +1,82 @@ +--- +layout: default +title: CSP rules +parent: Settings and administration +nav_order: 60 +has_children: false +--- + +# CSP rules +Introduced 2.13 +{: .label .label-purple } + +Content Security Policy (CSP) is a security standard intended to prevent cross-site scripting (XSS), clickjacking, and other code injection attacks. OpenSearch Dashboards enforces CSP by sending a `Content-Security-Policy` response header on every page load. + + +## Configuration + +To configure CSP, add the following keys to `opensearch_dashboards.yml`. All `allowed*Sources` values are appended to the strict policy defaults for that directive: + +```yaml +# Enable strict CSP enforcement. +csp.enable: true + +# Append trusted origins to frame-ancestors (controls iframe embedding). +csp.allowedFrameAncestorSources: ["https://portal.example.com"] + +# Append trusted origins to connect-src (fetch/XHR calls from the browser). +csp.allowedConnectSources: ["https://api.example.com"] + +# Append trusted origins to img-src. +csp.allowedImgSources: ["https://cdn.example.com"] + +# Relax specific directives back to their non-strict defaults +# while keeping the rest of the policy strict. +csp.loosenCspDirectives: ["style-src"] +``` +{% include copy.html %} + +Then restart OpenSearch for the changes to take effect. + +## CSP settings + +The following table describes the available CSP settings. + +Setting | Type | Description +:--- | :--- | :--- +`csp.enable` | Boolean | Enables strict CSP enforcement. Default is `true`. +`csp.allowedFrameAncestorSources` | Array of strings | Origins appended to the `frame-ancestors` directive. Use to allow embedding Dashboards in an iframe. +`csp.allowedConnectSources` | Array of strings | Origins appended to `connect-src`. Use to allow browser-initiated requests to external endpoints (fetch, XHR, or WebSocket). +`csp.allowedImgSources` | Array of strings | Origins appended to `img-src`. Use to allow images from external CDNs or tile servers. +`csp.loosenCspDirectives` | Array of strings | Directive names to relax back to their non-strict default values. + +## Enabling site embedding + +To embed OpenSearch Dashboards in an iframe on another site, add that site to `csp.allowedFrameAncestorSources`: + +```yaml +csp.allowedFrameAncestorSources: ["https://portal.example.com"] +``` +{% include copy.html %} + +This produces the following `frame-ancestors` directive in the response header: + +``` +frame-ancestors 'self' https://portal.example.com +``` + +## Report-only mode + +To audit a new CSP policy without enforcing it, enable the `Content-Security-Policy-Report-Only` header. Violations are reported but no content is blocked: + +```yaml +csp-report-only.isEmitting: true +csp-report-only.allowedFrameAncestorSources: ["https://portal.example.com"] +csp-report-only.allowedConnectSources: ["https://api.example.com"] +csp-report-only.allowedImgSources: ["https://cdn.example.com"] +``` +{% include copy.html %} + +## Configuring CSP rules using applicationConfig (deprecated) + +**Deprecated.** In OpenSearch Dashboards 2.13--2.16, you could set the `frame-ancestors` directive dynamically through a REST API by using the `applicationConfig` and `cspHandler` plugins. This approach is no longer functional. Use the `csp.*` settings instead. diff --git a/_dashboards/dashboard/adding-a-viz.md b/_dashboards/dashboard/adding-a-viz.md new file mode 100644 index 00000000..b5a794c2 --- /dev/null +++ b/_dashboards/dashboard/adding-a-viz.md @@ -0,0 +1,77 @@ +--- +layout: default +title: Adding a visualization to a dashboard +parent: Creating dashboards +nav_order: 20 +has_children: false +--- + +# Adding a visualization to a dashboard + +You can add an existing panel to a dashboard or create a new visualization directly in a dashboard. + +## Prerequisites + +You can add a visualization to a dashboard only when you have the dashboard open for editing. See [Opening a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/opening-a-dashboard/). + + +## Creating a new visualization in a dashboard + +You can create a new visualization, but not a new search, in a dashboard. + +To add a search to a dashboard, you must create it in the Discover application, then add it. See [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). +{: .note} + +To create a new visualization in a dashboard, follow these steps: + +1. From the application toolbar, choose **Create new**. + +1. From the **New Visualization** window, choose a visualization type. + +1. In the **New _\_/Choose a source** dialog, select an index pattern. + + Rather than a source selection dialog at this point, advanced visualization tools like Maps and VisBuilder have source selection built into the tool. + {: .note} + +1. The Dashboards application opens the Visualize editor and displays the default (count) visualization. + + + +1. Save the visualization. + + + + Make sure the **Add to dashboard after saving** toggle in the **Save visualization** dialog is selected. + + When you add a visualization by creating it in a dashboard, the **Save** button in the **Save visualization** dialog says **Save and return**. + {: .note} + +## Adding a panel to a dashboard + +To add a visualization or search to a dashboard, follow these steps: + +1. In the application menu, select **Add**. + + The application displays the **Add panels** dialog. + +1. (Optional) In the **Search** box, enter a term to filter the list of panels. + + Search is _not_ case-sensitive. Special characters are not allowed, even though they are allowed in a panel name. + +1. (Optional) In the Sort drop-down, choose Ascending or Descending to select alphabetical or reverse alphabetical sorting. + + Sorting _is_ case-sensitive. Special characters are included in the sort. For example, searching on `ecommerce` would include all of these visualizations in the filtered list: `[eCommerce] Markdown`, `[Ecommerce] Order Count`, and `eCommerce Orders`. + +1. (Optional) In the **Types** drop-down, select one or more panel types. The drop-down includes visualizations, searches, and special visualization types such as **Maps** and **VisBuilder** panels. If no items are selected, the filter includes all types by default. + +1. (Optional) In the Rows per page drop-down, select the number of panels to list per dialog page. Default is 10. + +1. (Optional) Select a page number to jump to from the page number list, or scroll through the pages with the {::nomarkdown}right icon{:/} (right) and {::nomarkdown}left icon{:/} (left) icons. + +1. Select one or more panels from the list. + + The dialog remains active so that you can choose more than one panel to add to the dashboard. + {: .note} + +1. Choose the {::nomarkdown}cross icon{:/} (cross) icon to close the dialog. + diff --git a/_dashboards/dashboard/customizing-a-dash.md b/_dashboards/dashboard/customizing-a-dash.md new file mode 100644 index 00000000..413a9827 --- /dev/null +++ b/_dashboards/dashboard/customizing-a-dash.md @@ -0,0 +1,126 @@ +--- +layout: default +title: Customizing a dashboard +parent: Creating dashboards +nav_order: 30 +has_children: false +--- + +# Customizing a dashboard + +You can customize a dashboard in the following ways: + +- [Resize panels](#resizing-a-panel). +- [Move panels](#moving-a-panel). +- [View a panel in full screen mode](#using-full-screen-mode) +- [Customize](#customizing-a-visualization-panel) the title, legend, or colors in a visualization. + + +## Prerequisites + +You can customize a dashboard only when you have the dashboard open for editing. See [Opening a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/opening-a-dashboard/). + + +### Resizing a panel + +To resize a panel, follow these steps: + +1. Select and hold the {::nomarkdown}resize icon{:/} (resize) icon in the panel's lower-right corner. + +1. Drag to the new dimensions. + + Other panels move out of the way to accommodate the new panel size. + + +### Moving a panel + +To move a panel, follow these steps: + +1. Select and hold the panel title or the top of the panel as shown in the following image. + +![Dragging a panel in Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/dash-panel-grab.png){: width="50%" } + +1. Drag the panel to the new location. + + Other panels move out of the way to accommodate the new panel location. + +## Using full screen mode + +You can view a single visualization panel in full screen mode and then return to dashboard mode. + + +### Viewing a panel in full screen mode + +To view a panel in full screen mode, follow these steps: + +1. Choose the {::nomarkdown}ellipses icon{:/} (ellipses) icon at the upper right of the panel. + + The {::nomarkdown}ellipses icon{:/} (ellipses) icon is visible only when you point to the visualization panel. + {: .note} + +1. In the **Options** drop-down, select {::nomarkdown}maximize icon{:/} (maximize) **Maximize panel**. + + +### Reducing a panel from full screen mode + +To reduce a panel from full screen mode, follow these steps: + +1. Choose the {::nomarkdown}ellipses icon{:/} (ellipses) icon at the upper right of the panel. + + The {::nomarkdown}ellipses icon{:/} (ellipses) icon is visible only when you point to the visualization panel. + {: .note} + +1. Select {::nomarkdown}minimize icon{:/} (minimize) **Minimize**. + + +## Customizing a visualization panel + +You can customize the following aspects of a visualization panel in a dashboard: + +- [Hide or display the legend](#hiding-and-displaying-the-legend). +- [Change colors in the visualization](#changing-a-color). +- [Change or hide the panel title](#changing-or-hiding-the-panel-title). + +### Hiding and displaying the legend + +To display or hide the panel legend: + +- Choose the {::nomarkdown}list icon{:/} (list) icon in the panel's lower left corner. + +### Changing a color + +To change a color in the visualization, follow these steps: + +1. From the visualization legend, select a category. + +1. From the flyout, select a color. + + The visualization graphic updates with your change. + + The color change is only saved for the current panel and dashboard. It does not affect the saved visualization. + + + +### Changing or hiding the panel title + +To display, hide, or customize the panel title, follow these steps: + +1. Choose the {::nomarkdown}gear icon{:/} (gear) icon. + +1. From the **Options** window, select **Edit panel title**. + +1. From the **Customize panel** dialog, enter a title under **Panel title**. + +1. (Optional) Toggle the **Show panel title** to hide the title. + +1. Choose **Save**. + + Changing a panel title only affects the panel on the current dashboard. The change does not affect the visualization on any other dashboard nor any other panel containing that visualization. + {: .note} + + +## Next steps + +If you have made changes to the dashboard that you want to keep, save the dashboard. See [Saving a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/managing-a-dash/#saving-a-dashboard). \ No newline at end of file diff --git a/_dashboards/dashboard/dash-tutorial.md b/_dashboards/dashboard/dash-tutorial.md new file mode 100644 index 00000000..c06f23ae --- /dev/null +++ b/_dashboards/dashboard/dash-tutorial.md @@ -0,0 +1,138 @@ +--- +layout: default +title: Dashboard tutorial +parent: Creating dashboards +nav_order: 5 +has_children: false +--- + +# Tutorial: Creating a dashboard + +You can use the **Dashboards** application in OpenSearch Dashboards to build a page containing multiple visual representations of your data. + +Use the following tutorial to learn to create a dashboard using the **Dashboards** application and the OpenSearch sample data. The sample datasets have existing sample visualizations that you can use for the dashboard, or you can create your own visualizations. The tutorials demonstrate how to do both. + +For an overview of the Dashboards UI, see [Navigating the Dashboards application UI]({{site.url}}{{site.baseurl}}/dashboards/dashboard/#navigating-the-dashboards-application-ui). + +## Prerequisites + +The tutorials on this page use the [**Sample eCommerce data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). + +If you're using a local installation of OpenSearch Dashboards and haven't added sample data yet, see [Prepare your data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +The following tutorials assume you're either using your existing installation of OpenSearch Dashboards or using the [OpenSearch Playground](https://playground.opensearch.org/app/home#/). Depending on which one you use, certain capabilities may not be available. For example, sample datasets may not be included in your existing installation, and saving a dashboard isn't an option in the OpenSearch Playground. +{: .note} + +## Creating a dashboard + +To create a new dashboard, follow these steps: + +1. | In classic navigation | In workspaces navigation | + | :-- | :-- | + | - Select **OpenSearch Dashboards** > **Dashboards**.
- Select **Dashboards**. | Select **Dashboards**. | + +1. | In classic navigation | In workspaces navigation | + | :-- | :-- | + | - In the Dashboards panel, select **Create**.
- From the drop-down, select **Dashboard**. | From the application menu, select **Create Dashboard**. | + +## Adding an existing visualization + +To add a saved visualization to the dashboard, follow these steps: + +1. From the application panel, choose **Add an existing**. + +1. In the **Add panels** dialog, type `ecommerce` in the **Search** box to filter the list of available visualizations. + +1. From the **Add panels** dialog, choose **[eCommerce] Sales by Category**. + +1. Choose the {::nomarkdown}cross icon{:/} (cross) icon to close the dialog. + +1. Use the [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) to select `Last 2 years` as the time window as shown in the following image. + +![Time filter set to Last 2 years]({{site.url}}{{site.baseurl}}/images/dashboards/dash-tut-time-2-years.png){: width="40%" } + +1. Drag-select the narrow band of data from the area chart as shown in the following image. + + ![Visualization showing drag-select]({{site.url}}{{site.baseurl}}/images/dashboards/dash-tut-sales-drag.png){: width="60%" } + + The data adjusts to span the width of the data display and the scale adjusts automatically, as shown in the following image. + + ![Sales by category area visualization]({{site.url}}{{site.baseurl}}/images/dashboards/dash-tut-sales-area.png){: width="60%" } + + Selecting a date range interactively results in an absolute time interval. + {: .note} + +You've created a dashboard with a single panel, which you'll continue to modify in this tutorial. Save the dashboard as described in the following section. + + +## Saving a dashboard + +To save a new dashboard, follow these steps: + +1. In the **Dashboards** toolbar, choose **Save**. + +1. In the **Save dashboard** dialog, enter `[Ecommerce] tutorial dashboard` in the **Title** box. + +1. Save the time filter with the dashboard by selecting **Store time with dashboard**. + +1. Choose **Save**. + +1. Choose **Edit** from the application menu to continue editing the dashboard. + + +## Creating a visualization + +To create a new visualization in **Dashboards**, follow these steps: + +1. From the application toolbar, choose **Create new**. + +1. From the **New Visualization** window, choose **Metric**. + +1. In the **New Metric/Choose a source** dialog, select the index pattern **opensearch_dashboards_sample_data_ecommerce**. + +1. From the toolbar, choose **Save**. + +1. In the **Save visualization** dialog, enter a title for the visualization. For this tutorial, enter `[eCommerce] Order Count`. + +1. Choose **Save and return**. + + The **Dashboards** application saves the metric visualization and adds it to the dashboard as shown in the following image. + + ![Dashboard with Sales by Category and Order Count metric panels]({{site.url}}{{site.baseurl}}/images/dashboards/dash-tut-combined.png) + + +## Adding subsequent panels + +Add a Markdown visualization to the dashboard. Follow these steps: + +1. From the dashboard toolbar, choose **Add**. + +1. From the **Add panels** dialog, choose **[eCommerce] Markdown**. + +1. Choose the {::nomarkdown}cross icon{:/} (cross) icon to close the dialog. + + The **Dashboards** application adds the Markdown panel to the dashboard as shown in the following image. + + ![Example dashboard]({{site.url}}{{site.baseurl}}/images/dashboards/dash-tut-three-panel.png) + + +## Organizing a dashboard + +You can organize a dashboard by resizing and rearranging panels. Move and resize the Markdown panel to serve as a title and description for the dashboard. Follow these steps: + +1. Select and hold the top of the panel anywhere to the left of the {::nomarkdown}options icon{:/} (options) icon. + +1. Drag the panel to the top of the application panel. + + The Sales by Category panel automatically swaps places with the Markdown panel as you move it up. +1. Select and hold the {::nomarkdown}resize icon{:/} (resize) icon in the panel's lower-right corner. + +1. Drag to make the panel longer and narrower so that it serves as a banner across the entire upper part of the dashboard. + + The metric panel automatically moves down to allow room for the resized Markdown panel. + + The resulting dashboard should look like the following image. + + ![Example dashboard]({{site.url}}{{site.baseurl}}/images/dashboards/dash-tut-banner.png) + +1. Save your dashboard. See [Saving a dashboard](#saving-a-dashboard). \ No newline at end of file diff --git a/_dashboards/dashboard/dashboard-sections.md b/_dashboards/dashboard/dashboard-sections.md new file mode 100644 index 00000000..831b6a99 --- /dev/null +++ b/_dashboards/dashboard/dashboard-sections.md @@ -0,0 +1,176 @@ +--- +layout: default +title: Dashboard sections +parent: Creating dashboards +nav_order: 35 +has_children: false +--- + +# Dashboard sections +**Introduced 3.9** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +Dashboard sections are collapsible containers that group visualization panels into named categories within a dashboard. Use sections to organize a dashboard that contains many panels and to reduce its initial load time by saving it with rarely used sections collapsed. + +The following image shows a dashboard containing a section of visualizations. + +![Dashboard with a section containing four visualization panels]({{site.url}}{{site.baseurl}}/images/dashboard-sections/dashboard-with-sections.png) + +## Enabling dashboard sections + +To enable dashboard sections, add the following settings to your `opensearch_dashboards.yml` file: + +```yaml +uiSettings.overrides.home:useNewHomePage: true +dashboard.allowDashboardSections: true +``` +{% include copy.html %} + +Then restart OpenSearch Dashboards for the changes to take effect. + +## Creating and managing sections + +All section actions except collapsing and expanding require [edit mode]({{site.url}}{{site.baseurl}}/dashboards/dashboard/opening-a-dashboard/). In edit mode, select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on a section header to open the section context menu, or the {::nomarkdown}gear icon{:/} (gear) icon on a panel to open the panel context menu. + +Within a section, panels have their own grid layout, so you can drag and resize them as you would on a dashboard without sections. The section adjusts its height to fit its contents. + +### Creating a section + +When you create the first section on a dashboard, all existing panels are grouped into that section so that the current layout is preserved. Later sections start empty. + +To create a section, follow these steps: + +1. Open a dashboard in edit mode. +2. In the toolbar, select **Add**. +3. Select **Section**. + +A section is added to the dashboard. + +### Renaming a section + +To rename a section, follow these steps: + +1. Select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on the section header. +2. Select **Rename**. +3. In the **Rename section** dialog, enter a name for the section. +4. Select **Save**. + +Section names do not need to be unique, but distinct names make it easier to move panels between sections. +{: .tip} + +### Collapsing and expanding sections + +To collapse a section, select the arrow to the left of the section title. The section header remains visible, and the panels are hidden. To expand a collapsed section, select the arrow again. + +### Reordering sections + +To reorder sections, follow these steps: + +1. Select and hold the section header, which acts as the drag handle. +2. Drag the section to a new position. +3. Release the section to drop it into place. + +### Moving a panel to another section + +You can move a panel from one section to another or from the **Ungrouped** area into a section. + +To move a panel, follow these steps: + +1. Select the {::nomarkdown}gear icon{:/} (gear) icon in the panel's upper-right corner. +2. Select **Move to section**. +3. In the **Move to section** dialog, select the target section. +4. Select **Move**. + +The panel is removed from its current section and added to the target section. + +### Adding a new visualization to a section + +To create a visualization and add it to a section, follow these steps: + +1. Select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on the section header. +2. Select **Create new visualization**. +3. Build the visualization in the visualization editor. +4. Select **Save and return**. + +The visualization is added to the section as a panel. + +### Adding a saved visualization to a section + +To add an existing visualization from the library, follow these steps: + +1. Select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on the section header. +2. Select **Add from library**. +3. Search for and select a saved visualization. + +The visualization is added to the section. + +### Deleting a section + +To delete a section, follow these steps: + +1. Select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on the section header. +2. Select **Delete section**. +3. In the confirmation dialog, confirm the deletion. + +Deleting a section permanently removes all panels in it. You cannot undo this after you save the dashboard. To keep the panels, move them to another section first. +{: .warning} + +### Removing all sections + +You can return all panels to a single grid and remove the section structure from the dashboard. + +To remove all sections, follow these steps: + +1. Select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on any section header. +2. Select **Ungroup all sections**. +3. In the confirmation dialog, confirm the action. + +All panels are returned to a single grid, and the sections are removed. + +## Ungrouped panels + +Panels that are not assigned to a section appear in an **Ungrouped** area at the bottom of the dashboard. To move an ungrouped panel into a section, use **Move to section** in the panel context menu. You cannot move a panel back into the **Ungrouped** area. + +## Collapsed sections and data loading + +Collapsing a section hides its panels but does not remove them. A panel that has not yet been displayed requests no data while its section is collapsed; it fetches data when you expand the section and scroll the panel into view. A panel that has already been displayed continues to refresh with the rest of the dashboard even while the section is collapsed. + +On a dashboard with many visualizations, saving the dashboard with rarely used sections already collapsed reduces both the initial page load time and the load on your OpenSearch cluster. +{: .tip} + +## Example: Organizing a dashboard into sections + +To follow along, go to the OpenSearch Dashboards home page, select **Add sample data**, and then select **Add data** for **Sample eCommerce orders**. + +The following steps organize the sample e-commerce dashboard into two sections: + +1. On the top menu, select **Dashboards**, and then select **[eCommerce] Revenue Dashboard**. +2. Select the **Edit** toggle in the toolbar to enter edit mode. +3. In the toolbar, select **Add** > **Section**. All existing panels are grouped into a section named **Section 1**. +4. Select the {::nomarkdown}vertical ellipsis icon{:/} (vertical ellipsis) icon on the **Section 1** header, select **Rename**, enter `Revenue and trends`, and then select **Save**. +5. In the toolbar, select **Add** > **Section** again. An empty section appears below the first one, also named **Section 1** because the first section was renamed. Rename this section `Customer breakdown`. +6. On the **[eCommerce] Sales by Gender** panel, select the {::nomarkdown}gear icon{:/} (gear) icon, and then select **Move to section**, as shown in the following image. + ![Panel Options menu with the Move to section action highlighted]({{site.url}}{{site.baseurl}}/images/dashboard-sections/panel-context-menu.png) +7. In the **Move to section** dialog, select **Customer breakdown**, and then select **Move**. +8. Repeat the previous two steps for the **[eCommerce] Sales Count Map** and **[eCommerce] Top Selling Products** panels. +9. Select the arrow to the left of the **Customer breakdown** title to collapse the section. +10. Select **Save**. + +The dashboard now contains two sections that you can collapse, expand, and reorder independently, and the collapsed **Customer breakdown** section loads no data until you expand it. + +## Limitations + +Dashboard sections have the following limitations: + +- Dragging a panel from one section to another is not supported. To move a panel, use **Move to section** in the panel context menu. +- Section-scoped filters and variables are not supported. All filters apply to the entire dashboard. +- Adding, renaming, reordering, and deleting sections require edit mode. In view mode, you can only collapse and expand sections. + +## Related documentation + +- [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/) +- [Customizing a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/customizing-a-dash/) +- [Adding a visualization to a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/adding-a-viz/) diff --git a/_dashboards/dashboard/index.md b/_dashboards/dashboard/index.md index 37878bd2..2330288e 100644 --- a/_dashboards/dashboard/index.md +++ b/_dashboards/dashboard/index.md @@ -1,142 +1,72 @@ --- layout: default title: Creating dashboards -nav_order: 30 -has_children: false +nav_order: 70 +has_children: true +redirect_from: + - /dashboards/dashboard/ --- # Creating dashboards -The **Dashboard** application in OpenSearch Dashboards lets you visually represent your analytical, operational, and strategic data to help you quickly understand the trends in your data, giving you a high-level view of key metrics, simplifying data exploration, and delivering insights when and where you need them. +You can use the **Dashboards** application in OpenSearch Dashboards to build a dashboard, a page containing multiple panels showing different views of your data. -In this tutorial you'll learn the basics of creating a dashboard using the **Dashboard** application and OpenSearch sample data. The sample dataset has existing sample visualizations, and you can use those visualizations or create new visualizations for the dashboard. In this tutorial, you'll do both. Once you've completed this tutorial, you'll have learned the foundations of creating a new dashboard with multiple panels in OpenSearch Dashboards. +If you're new to the Dashboards application, see [Explore the Dashboards application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dashboards/) for a hands-on introduction using sample data. +{: .tip} -This OpenSearch Playground [dashboard example](https://playground.opensearch.org/app/dashboards#/view/722b74f0-b882-11e8-a6d9-e546fe2bba5f?_g=(filters:!(),refreshInterval:(pause:!f,value:900000),time:(from:now-7d,to:now))&_a=(description:'Analyze%20mock%20eCommerce%20orders%20and%20revenue',filters:!(),fullScreenMode:!f,options:(hidePanelTitles:!f,useMargins:!t),query:(language:kuery,query:''),timeRestore:!t,title:'%5BeCommerce%5D%20Revenue%20Dashboard',viewMode:view)) shows you what's possible with OpenSearch Dashboards. +>This documentation uses the following terms: +>- _OpenSearch Dashboards_: The web UI for OpenSearch. +>- **Dashboards** application: The application within OpenSearch Dashboards for creating dashboards. +>- _dashboard_ (lowercase): An individual collection of data visualizations created in the **Dashboards** application. {: .note} -## Getting familiar with the UI +Dashboards typically contain visualizations, but can also contain searches. -Before getting started, let's get familiar with the **Dashboard** UI. The UI comprises the following main components: +A dashboard shows one or more panels, usually arranged to support a business goal such as operations, decision support, or observability. A dashboard can contain any number of panels, subject only to display and legibility constraints. -![Dashboard user interface]({{site.url}}{{site.baseurl}}/images/dashboards/dashboard-UI.png) +## Prerequisites -- The **navigation panel** (A) on the left contains the OpenSearch Dashboards applications. -- The **search** bar (B) lets you search for documents and other objects and add filters. -- The **filter** (C) lets you narrow a dashboard's results. -- The **toolbar** (D) contains frequently used commands and shortcuts. -- The **time filter** (E) lets you customize the time and date. -- The **panel** (F) allows you to add existing visualizations to the dashboard or create new ones for the dashboard. +The tutorials on this page use the [**Sample eCommerce data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). -## Defining terminology +If you've installed a local OpenSearch Dashboards instance, add the sample data by following these steps: -The following is some useful terminology for working with OpenSearch Dashboards and the **Dashboard** application: +1. On the OpenSearch Dashboards home page, select **Add sample data**. +2. In the **Sample eCommerce data** panel, select **Add data**. -- _Dashboards_ is the abbreviated name for OpenSearch Dashboards. OpenSearch Dashboards is an open-source visualization tool designed to work with OpenSearch. -- _Dashboard_ is the OpenSearch Dashboards application used to track, analyze, and display data. -- _dashboard_ or _dashboards_ are common names for a tool used to visually display data. -- _Panel_ is a term used to refer to a visualization displayed on a dashboard. The terms _panel_ and _visualization_ may be used interchangeably throughout this and other Dashboards documentation. +For more information, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). -The following tutorial assumes you're either using your existing installation of OpenSearch Dashboards or using the [OpenSearch Playground](https://playground.opensearch.org/app/home#/). Depending on which one you use, certain capabilities may not be available. For example, sample datasets may not be included in your existing installation, and saving a dashboard isn't an option in the OpenSearch Playground. -{: .note} +## Navigating the Dashboards application UI + +The following image shows the main components of the **Dashboards** application. + +![Dashboards app default page]({{site.url}}{{site.baseurl}}/images/dashboards/dashboard-UI-blank-callouts.png) + +- The _application menu_ (A) contains application options. This menu is context-sensitive and is different for other applications. +- The _search_ bar (B) enables selection of data using a query language search. +- The _time filter_ (C) enables selection of data based on a time and date range. +- The _filter_ (D) provides a graphical interface for selecting data values and ranges. +- The _application panel_ (E) displays the dashboard, which contains visualization and search panels. ## Creating a dashboard and adding an existing visualization -To create a dashboard and add a sample visualization: +The procedure for creating a dashboard is as follows: -1. Connect to `https://localhost:5601`. The username and password are `admin`. Alternatively, go to the [OpenSearch Playground](https://playground.opensearch.org/app/home#/). -1. On the top menu, go to **OpenSearch Dashboards > Dashboard**. -1. From the **Dashboards** panel, choose **Create Dashboard**. -1. Choose the calendar icon and set the time filter to **Last 30 days**. -1. From the panel, choose **Add an existing**. -1. From the **Add panels** window, choose **[eCommerce] Promotion Tracking**, and then choose `x` to close the panel. +1. Open a dashboard. You can start with a new (empty) dashboard, modify an existing dashboard, or clone an existing dashboard as a starting point for a similar dashboard. See [Opening a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/opening-a-dashboard/). -You've now created the following basic dashboard with a single panel, which you'll continue using throughout this tutorial. +1. Ensure that the data filters include the data you want to work on. This typically, but not always, means setting the time filter to include a range of timestamps. See [Selecting a time range]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/#selecting-a-time-range). -![Basic dashboard with single panel]({{site.url}}{{site.baseurl}}/images/dashboards/dashboard-basic.png) + OpenSearch applications, including Dashboards, Visualize, and Discover, apply filters to all data in the application. The filter is applied to all index patterns used in the dashboard. For example, a time filter applied to a log monitoring dashboard selects the documents from all log visualizations on that dashboard, even if they include documents from different index patterns. See [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). + {: .note} -## Creating visualizations +1. Add panels to the dashboard. You can select saved panels or create new visualization within the **Dashboards** application. See [Adding a visualization to a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/adding-a-viz/). -Continuing with the dashboard you created in the preceding steps, you'll create a new visualization and save it to the dashboard: +1. Arrange and resize panels on the dashboard. See [Customizing a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/customizing-a-dash/). -1. From the dashboard toolbar, choose **Create new**. -1. From the **New Visualization** window, choose **Gauge** and then select the index pattern **opensearch_dashboards_sample_data_ecommerce**. -1. From the toolbar, choose **Save**. -1. In the **Save visualization** window, enter a title for the visualization. For example, the title for the gauge chart panel is [eCommerce] Orders. -1. Choose **Save and return**. +1. Save the completed (or work-in-progress) dashboard. See [Saving a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/managing-a-dash/#saving-a-dashboard). -The gauge chart visualization is now saved and you are taken back to the dashboard. You'll see two visualizations on the dashboard, like the following. -![Dashboard showing visualizations combined in a single view]({{site.url}}{{site.baseurl}}/images/dashboards/dashboard-combined.png) +## Next steps -## Adding subsequent panels +- For a quick introduction to viewing and filtering dashboards, see [Explore the Dashboards application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dashboards/). -Continuing with the dashboard you created in the preceding steps, you'll add an existing visualization to the dashboard: - -1. From the dashboard toolbar, choose **Add**. -1. From the **Add panels** window, choose **[eCommerce] Sales by Category**. -1. Choose `x` to close the **Add panels** window. - -You'll see an area chart visualization display on the dashboard, as shown in the following image. - -![Adding another panel to the dashboard]({{site.url}}{{site.baseurl}}/images/dashboards/dashboard-adding-panels.png) - -## Saving dashboards - -When you've finalized your dashboard, save it. If you're saving a new dashboard: - -1. In the toolbar, choose **Save**. -2. In the **Save dashboard** window, enter the **Title**. The **Description** is optional. -3. To save the time filter to the dashboard, select **Store time with dashboard**. -4. Choose **Save**. - -## Customizing the look of a panel - -To customize the panels, you'll need to be in edit mode: - -- Choose **Edit** at the top right of the toolbar. - -If you see **Create new** at the top right of the toolbar, you're already in edit mode. -{: .note} - -Displaying a legend can give readers more information, while hiding a legend can give the panel a cleaner look. If you want to display or hide the panel legend: - -- Choose the list icon in the panel's lower left corner. - -If you want to change the color of the panel legend: - -- From the visualization legend, select a category and then select a color from the flyout. The area chart updates with your change. - -This color change is only saved for the current panel and dashboard and doesn't affect the saved visualization. -{: .note} - -If you want to change the color of the panel legend in the visualization: - -1. Choose the gear icon on the area chart panel. -2. From the **Options** window, select **Edit visualization**. -3. From the visualization legend, select a category and then select a color from the flyout. The area chart updates with your change. -4. Choose **Save and return**. - -This color change affects the saved visualization and any dashboard that links to the visualization. -{: .note} - -If you want to display, hide, or customize the panel title: - -1. Choose the gear icon on the panel. -2. From the **Options** window, select **Edit panel title**. -3. From the **Customize panel**, enter a title under **Panel title** or toggle the **Show panel title** to hide the title. -4. Choose **Save**. - -Changing panel titles only affects the particular panel on the particular dashboard and won't affect any other panel containing that same visualization or any other dashboard. -{: .note} - -## Arranging panels - -To organize panels, arrange them side by side, or resize them, you can use these options: - -- To move a panel, select and hold the panel title or the top of the panel and drag to the new location. -- To resize a panel, choose the resize icon in the panel's lower-right corner and drag to the new dimensions. -- To view a panel in full screen mode, choose the gear icon (edit mode) or vertical ellipsis (⋮) at the top right of the panel and select **Maximize panel**. To minimize the full screen mode, choose the gear icon or vertical ellipsis and select **Minimize**. - -The following is an example of a customized dashboard created by using this tutorial. - -![Customized dashboard with panels arranged side by side and without legends]({{site.url}}{{site.baseurl}}/images/dashboards/dashboard-customized.png) +- For a comprehensive end-to-end tutorial, see [Tutorial: Creating a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/dash-tutorial/). diff --git a/_dashboards/dashboard/managing-a-dash.md b/_dashboards/dashboard/managing-a-dash.md new file mode 100644 index 00000000..ed63fa5e --- /dev/null +++ b/_dashboards/dashboard/managing-a-dash.md @@ -0,0 +1,94 @@ +--- +layout: default +title: Managing dashboards +parent: Creating dashboards +nav_order: 40 +has_children: false +--- + +# Managing dashboards + +Manage dashboards in OpenSearch Dashboards from the **Dashboards** application main page, shown in the following image. + +![Dashboards landing page]({{site.url}}{{site.baseurl}}/images/dashboards/dash-landing-page.png) + +You can do the following: + +- [Save a dashboard](#saving-a-dashboard). +- Create and edit a dashboard. See [Opening a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/opening-a-dashboard/). +- [Export a dashboard to a file](#exporting-a-dashboard). +- [Delete dashboards](#deleting-dashboards). + +## Saving a dashboard + +You can save a newly created dashboard or save changes to an existing dashboard. + +### Saving a new dashboard + +To save a new dashboard, follow these steps: + +1. In the application menu, select **Save**. + + The application displays the **Save dashboard** dialog. + +1. Enter a title for the dashboard in the **Title** box. + +1. (Optional) Enter a **Description**. + +1. (Optional) To save the current time filter so it's applied when you reopen the dashboard, select **Store time with dashboard**. + +1. Select **Save**. + +### Saving an existing dashboard + +You can save a dashboard at any time. + +To save an existing dashboard: + +1. Select **Save** in the upper right of the **Create** panel. + + The application displays the **Save dashboard** dialog. If you have previously saved the dashboard, the **Title** box contains the dashboard title. + +1. (Optional) To change the dashboard name, enter a new title for the dashboard in the **Title** box. + + Saving an existing dashboard without selecting **Save as new dashboard** overwrites the previous state of the dashboard, even if you've renamed the dashboard. + {: .warning} + +1. (Optional) Update the **Description**. + +1. (Optional) To leave the saved dashboard in its current state and save the changes as a new dashboard, select **Save as new dashboard**. You can select **Copy panels** so that edits to the panels in the new dashboard do not affect the original dashboard. For more information, see [Copying panels]({{site.url}}{{site.baseurl}}/dashboards/dashboard/opening-a-dashboard/#copying-panels). + +1. (Optional) To save the current time filter so it's applied when you reopen the dashboard, select **Store time with dashboard**. + +1. Select the **Save** button. + + +## Exporting a dashboard + +You can export a dashboard to a PDF file or PNG image file. + +Exporting a dashboard is a Reporting feature. You must have the Reporting plugin active to export a file. +{: .note} + +This feature requires the Reporting plugin. See [Reporting using OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-dashboard-index/) for more information about reporting. + +1. Select **Reporting** from the application menu. + +1. From the drop-down menu, select **Download PDF** or **Download PNG**. + + The application displays the **Generating report** dialog. The report can take several seconds to generate. + +1. The report opens in your browser or downloads, depending on your browser preference. + + +## Deleting dashboards + +To delete one or more dashboards, follow these steps: + +1. In the [navigation panel]({{site.url}}{{site.baseurl}}/dashboards/navigating-ui/#the-left-navigation-panel), select **OpenSearch Dashboards** > **Dashboards**. + +1. From the list in the **Dashboards** table, select the checkbox next to all the dashboards you want to delete. + +1. Choose the **Delete N Dashboards** button (where **N** is the number of checked boxes) to the left of the **Search** box in the **Dashboards** panel. + +1. In the confirmation dialog, choose **Delete**. diff --git a/_dashboards/dashboard/opening-a-dashboard.md b/_dashboards/dashboard/opening-a-dashboard.md new file mode 100644 index 00000000..ed269511 --- /dev/null +++ b/_dashboards/dashboard/opening-a-dashboard.md @@ -0,0 +1,74 @@ +--- +layout: default +title: Opening a dashboard +parent: Creating dashboards +nav_order: 10 +has_children: false +--- + +# Opening a dashboard + +To open a dashboard for editing, you can do one of the following: + +- [Create a new empty dashboard](#creating-a-new-dashboard). +- [Copy an existing dashboard](#copying-a-dashboard). +- [Edit an existing dashboard](#editing-an-existing-dashboard). + + +## Creating a new dashboard + +To create a new dashboard, follow these steps: + +1. In the [navigation panel]({{site.url}}{{site.baseurl}}/dashboards/navigating-ui/#the-left-navigation-panel), select **OpenSearch Dashboards** > **Dashboards**. + +1. From the **Dashboards** application panel, choose **Create**. + +1. From the drop-down, select **Dashboard**. + + The Dashboards application opens an empty dashboard in edit mode, as shown in the following image. + + +## Copying a dashboard + +To copy a dashboard, follow these steps: + +1. In the [navigation panel]({{site.url}}{{site.baseurl}}/dashboards/navigating-ui/#the-left-navigation-panel), select **OpenSearch Dashboards** > **Dashboards**. + +1. From the list in the **Dashboards** table, select a dashboard by choosing its title from the table. + +1. From the menu in the toolbar, select **Clone**. + +1. In the **Clone dashboard** dialog, enter a name for the copied dashboard. + +1. (Optional) To copy the panels from the original to the copied dashboard, select **Copy panels**. For more information, see [Copying panels](#copying-panels). + +1. Select **Confirm Clone**. + +### Copying panels +**Introduced 3.11** +{: .label .label-purple } + +By default, a copied dashboard shares its panels with the original dashboard. Both dashboards reference the same saved visualizations and saved searches, so editing a panel in the copy also changes it in the original dashboard. + +To copy the panels to the new dashboard, follow these steps: + +1. Select **Copy panels** in the **Clone dashboard** or **Save dashboard** dialog. + +1. (Optional) In the **Copied panel title** box, customize the title template for the copied panels. Because multiple panels are copied at once, each panel title is generated from the template when it is copied. The template must include {% raw %}`{{panelTitle}}`{% endraw %}, which is replaced with the original panel title. You can also include {% raw %}`{{dashboardTitle}}`{% endraw %}, which is replaced with the new dashboard title. For example, if you copy a panel named `Errors by host` from a dashboard named `Logs` to a new dashboard named `Logs archive` using the template {% raw %}`{{panelTitle}} ({{dashboardTitle}})`{% endraw %}, the panel is copied as `Errors by host (Logs archive)`. + +Only the panels are copied. Shared data, such as index patterns and data sources, stays shared. + +If a panel can't be copied, for example, because its visualization was deleted, the new dashboard is still saved. That panel continues to use the original object, and a warning lists the panels that weren't copied. +{: .note} + + +## Editing an existing dashboard + +To edit an existing dashboard, follow these steps: + +1. In the [navigation panel]({{site.url}}{{site.baseurl}}/dashboards/navigating-ui/#the-left-navigation-panel), select **OpenSearch Dashboards** > **Dashboards**. + +1. From the list in the **Dashboards** table, select a dashboard by choosing its title from the table. + +1. From the menu in the toolbar, select **Edit**. + diff --git a/_dashboards/dashboard/plugins-dashboards.md b/_dashboards/dashboard/plugins-dashboards.md index a4a0f6eb..380de1cc 100644 --- a/_dashboards/dashboard/plugins-dashboards.md +++ b/_dashboards/dashboard/plugins-dashboards.md @@ -9,34 +9,34 @@ nav_order: 5 Observability is a collection of plugins and applications that let you visualize data-driven events by using [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) to explore, discover, and query data stored in OpenSearch. Observability provides a unified experience for collecting and monitoring metrics, logs, and traces from common data sources. With data collection and monitoring in one place, you have full-stack, end-to-end observability of your entire infrastructure. -As of OpenSearch 2.7, you can manage your observability plugins with **Observability Dashboards** or **Dashboard** instead of the plugins page. This feature provides you: +You can manage your observability plugins with **Observability Dashboards** or **Dashboard** instead of the plugins page. This feature provides you: - **Instant access to installed plugins:** The dashboard displays all installed plugins in one place. -- **Improved efficiency:** With a list of plugins readily available from a dashboard, you can enable, disable, update, or remove plugins in the OpenSearch Dashboards UI. +- **Improved efficiency:** With a list of plugins readily available from a dashboard, you can enable, disable, update, or remove plugins in OpenSearch Dashboards. - **Better troubleshooting:** Viewing a list of plugins from a dashboard can help you quickly identify which plugins may be causing a problem. - **Enhanced security:** With a list of plugins readily available from a dashboard, you can easily see if any outdated or vulnerable plugins are present and then quickly remove or update them, minimizing or avoiding security risks. - **Improved website performance:** Viewing a list of plugins from a dashboard can help you identify any plugins that may be slowing down your website or causing performance issues. -Get familiar with the basics of managing plugins from the Dashboard app in less than 20 seconds in the following video. +Learn the basics of managing plugins from the Dashboards app in less than 20 seconds in the following video. -![Demo of using Dashboard to view a list of observability plugins](https://user-images.githubusercontent.com/105296784/234345611-50beb9a6-6118-449a-b015-b9f9e90b525e.gif) +![Demo of using Dashboards to view a list of observability plugins](https://user-images.githubusercontent.com/105296784/234345611-50beb9a6-6118-449a-b015-b9f9e90b525e.gif) ## Viewing a list of installed plugins -To view a list of installed plugins from the Dashboard app, follow these steps: +To view a list of installed plugins from the Dashboards app, follow these steps: -1. From the OpenSearch Dashboards main menu, select **Dashboard**. -2. View the list of items and select your plugin. Plugins are categorized automatically as the Observability Dashboard data type, which you can filter in order to concentrate on just what you want to see. +1. From the OpenSearch Dashboards main menu, select **Dashboards**. +2. View the list of items and select your plugin. Plugins are categorized automatically as the Observability Dashboard data type, which you can filter to focus on specific items. ## Adding and removing plugins -To add a plugin from the Dashboard app, follow these steps: +To add a plugin from the Dashboards app, follow these steps: -1. From the OpenSearch Dashboards main menu, select **Dashboard**. +1. From the OpenSearch Dashboards main menu, select **Dashboards**. 2. In the **Dashboards** window, select **Create** > **Dashboard**. -3. In the **Create operational panel** window, enter a name in the **Name** field and then select **Create**. The plugin is added to both the Observability app and the Dashboard app. +3. In the **Create operational panel** window, enter a name in the **Name** field and then select **Create**. The plugin is added to both the Observability app and the Dashboards app. -You can remove a plugin from the Dashboard app by selecting the edit icon under the **Actions** column and then selecting **Delete**. +You can remove a plugin from the Dashboards app by selecting the edit icon under the **Actions** column and then selecting **Delete**. ## Staying updated about OpenSearch Dashboards plugins diff --git a/_dashboards/dashboards-assistant/alert-insight.md b/_dashboards/dashboards-assistant/alert-insight.md new file mode 100644 index 00000000..24fe57da --- /dev/null +++ b/_dashboards/dashboards-assistant/alert-insight.md @@ -0,0 +1,321 @@ +--- +layout: default +title: Alert insights +parent: OpenSearch Assistant for OpenSearch Dashboards +nav_order: 10 +has_children: false +--- + +# Alert insights + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress the feature or if you want to leave feedback, join the discussion in the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The OpenSearch Dashboards Assistant alert insights help generate alert summaries and provide log patterns based on the logs that triggered the alert. + +## Configuring alert insights + +To configure alert insights, use the following steps. + +### Prerequisite + +Before using alert insights, you must have the `alerting` and `alerting-dashboards` plugins installed on your cluster. By default, these plugins are installed as part of standard OpenSearch distributions. For more information, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). + +### Step 1: Enable alert insights + +To enable alert insights, configure the following `opensearch_dashboards.yml` setting: + +```yaml +assistant.alertInsight.enabled: true +``` +{% include copy.html %} + +### Step 2: Create the agents + +To orchestrate alert insights, you'll need to create the necessary [agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). Create a workflow template for creating all necessary agents by sending the following request: + +
+ + Request + + {: .text-delta} + +```json +POST /_plugins/_flow_framework/workflow?provision=true +{ + "name": "Alert Summary Agent", + "description": "Create Alert Summary Agent using Claude on BedRock", + "use_case": "REGISTER_AGENT", + "version": { + "template": "1.0.0", + "compatibility": ["2.17.0", "3.0.0"] + }, + "workflows": { + "provision": { + "user_params": {}, + "nodes": [ + { + "id": "create_claude_connector", + "type": "create_connector", + "previous_node_inputs": {}, + "user_inputs": { + "version": "1", + "name": "Claude Sonnet 4.6 runtime Connector", + "protocol": "aws_sigv4", + "description": "The connector to BedRock service for Claude model", + "actions": [ + { + "headers": { + "x-amz-content-sha256": "required", + "content-type": "application/json" + }, + "method": "POST", + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.prompt}\"}]}],\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens},\"temperature\":${parameters.temperature}}", + "action_type": "predict", + "url": "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" + } + ], + "credential": { + "access_key": "", + "secret_key": "", + "session_token": "" + }, + "parameters": { + "region": "us-west-2", + "endpoint": "bedrock-runtime.us-west-2.amazonaws.com", + "content_type": "application/json", + "auth": "Sig_V4", + "max_tokens": "8000", + "service_name": "bedrock", + "temperature": "0.0001", + "response_filter": "$.content[0].text", + "anthropic_version": "bedrock-2023-05-31" + } + } + }, + { + "id": "register_claude_model", + "type": "register_remote_model", + "previous_node_inputs": { + "create_claude_connector": "connector_id" + }, + "user_inputs": { + "description": "Claude model", + "deploy": true, + "name": "claude-sonnet-4-6" + } + }, + { + "id": "create_alert_summary_ml_model_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You are an OpenSearch Alert Assistant to help summarize the alerts.\n Here is the detail of alert: ${parameters.context};\n The question is: ${parameters.question}." + }, + "name": "MLModelTool", + "type": "MLModelTool" + } + }, + { + "id": "create_alert_summary_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_alert_summary_ml_model_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "Alert Summary Agent", + "description": "this is an alert summary agent" + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +
+ +For sample agent templates, see [Flow Framework sample templates](https://github.com/opensearch-project/flow-framework/tree/2.x/sample-templates). Note the agent ID; you'll use it in the following step. + +For this example, use the templates to create the following agents: +- An alert insights agent, see [flow template](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/create-knowledge-base-alert-agent.json) +- Two summary agents: + - A basic alert summary agent, see [flow template](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/alert-summary-agent-claude-tested.json) + - An agent for an alert summary that includes log patterns, see [flow template](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/alert-summary-log-pattern-agent.json) + + These agents require different prompts. The prompt for the log patterns summary must include a placeholder `${parameters.topNLogPatternData}` and additional instructions to guide the LLM on using this information effectively. Note that log patterns are available only for query monitors created using OpenSearch Dashboards. + +### Step 3: Create the root agents + +Next, create [root agents]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/workflow-tutorial/#root_agent) for agents created in the previous step. + +Create a root agent for the alert summary agent: + +```json +POST /.plugins-ml-config/_doc/os_summary +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "" + } +} +``` +{% include copy-curl.html %} + +Create a root agent for the alert summary with log patterns agent: + +```json +POST /.plugins-ml-config/_doc/os_summary_with_log_pattern +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "" + } +} +``` +{% include copy-curl.html %} + +Create a root agent for the alert insights agent: + +```json +POST /.plugins-ml-config/_doc/os_insight +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "" + } +} +``` +{% include copy-curl.html %} + +The created `os_insight` agent provides alert insights related to OpenSearch cluster metrics. For insights about alerts unrelated to OpenSearch cluster metrics, you need to register an agent with [this template](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/create-knowledge-base-alert-agent.json) and change the agent name to `KB_For_Alert_Insight`. +{: .note} + +This example demonstrates a system index. In security-enabled domains, only superadmins have permissions to execute this code. For information about making superadmin calls, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). For access permissions, contact your system administrator. +{: .warning} + +### Step 4: Test the agents + +You can verify that the agents were created successfully by calling the agents with an example payload. + +To test the alert summary agent, send the following request: + +```json +POST /_plugins/_ml/agents/{SUMMARY_AGENT_ID}/_execute +{ + "parameters": { + "question": "Please summarize this alert, do not use any tool.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n" + } +} +``` +{% include copy-curl.html %} + +To test the alert summary with log patterns agent, send the following request: + +```json +POST /_plugins/_ml/agents/{SUMMARY_WITH_LOG_PATTERNS_AGENT_ID}/_execute +{ + "parameters": { + "question": "Please summarize this alert, do not use any tool.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "topNLogPatternData": "[[539,["[Sun Dec 04 07:12:44 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 06:19:18 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:59:47 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:11:22 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:31:12 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 05:04:04 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 20:24:49 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 06:16:23 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 20:47:17 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:30:43 2005] [error] mod_jk child workerEnv in error state 6","[Mon Dec 05 06:35:27 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:07:30 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 16:32:56 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 8"],"[ :: ] [] _ "],[32,["[Sun Dec 04 14:29:00 2005] [error] [client 4.245.93.87] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 08:54:17 2005] [error] [client 147.31.138.75] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:34:57 2005] [error] [client 61.138.216.82] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 07:45:45 2005] [error] [client 63.13.186.196] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 10:53:30 2005] [error] [client 218.76.139.20] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:48:48 2005] [error] [client 67.166.248.235] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:18:36 2005] [error] [client 67.154.58.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 01:30:32 2005] [error] [client 211.62.201.48] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 16:45:04 2005] [error] [client 216.216.185.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 17:31:39 2005] [error] [client 218.75.106.250] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:00:56 2005] [error] [client 68.228.3.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:14:09 2005] [error] [client 61.220.139.68] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 09:35:12 2005] [error] [client 207.203.80.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:28:44 2005] [error] [client 198.232.168.9] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 16:24:05 2005] [error] [client 58.225.62.140] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:53:43 2005] [error] [client 218.39.132.175] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 12:33:13 2005] [error] [client 208.51.151.210] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:59:01 2005] [error] [client 24.83.37.136] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 11:42:43 2005] [error] [client 216.127.124.16] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 05:15:09 2005] [error] [client 222.166.160.184] Directory index forbidden by rule: /var/www/html/"],"[ :: ] [] [ ...] : ////"],[12,["[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:16 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2"],"[ :: ] [] _ -"]]" + } +} +``` +{% include copy-curl.html %} + +To test the alert insights agent, send the following request: + +```json +POST /_plugins/_ml/agents/{ALERT_INSIGHTS_AGENT_ID}/_execute +{ + "parameters": { + "question": "Please provide your insight on this alerts.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "summary": "" + } +} +``` +{% include copy-curl.html %} + +## Generating an alert summary + +You can generate an alert summary by calling the `/api/assistant/summary` API endpoint. To generate an alert summary, the fields `index`, `dsl`, and `topNLogPatternData` are optional. If all three fields are provided, the agent will provide a summary with log pattern analysis; otherwise, it will provide a general summary: + +```json +POST /api/assistant/summary +{ + "summaryType": "alerts", + "question": "Please summarize this alert, do not use any tool.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "index": "loghub-apache-new", + "dsl": "{\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}", + "topNLogPatternData": "[[539,["[Sun Dec 04 07:12:44 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 06:19:18 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:59:47 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:11:22 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:31:12 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 05:04:04 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 20:24:49 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 06:16:23 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 20:47:17 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:30:43 2005] [error] mod_jk child workerEnv in error state 6","[Mon Dec 05 06:35:27 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:07:30 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 16:32:56 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 8"],"[ :: ] [] _ "],[32,["[Sun Dec 04 14:29:00 2005] [error] [client 4.245.93.87] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 08:54:17 2005] [error] [client 147.31.138.75] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:34:57 2005] [error] [client 61.138.216.82] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 07:45:45 2005] [error] [client 63.13.186.196] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 10:53:30 2005] [error] [client 218.76.139.20] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:48:48 2005] [error] [client 67.166.248.235] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:18:36 2005] [error] [client 67.154.58.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 01:30:32 2005] [error] [client 211.62.201.48] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 16:45:04 2005] [error] [client 216.216.185.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 17:31:39 2005] [error] [client 218.75.106.250] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:00:56 2005] [error] [client 68.228.3.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:14:09 2005] [error] [client 61.220.139.68] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 09:35:12 2005] [error] [client 207.203.80.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:28:44 2005] [error] [client 198.232.168.9] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 16:24:05 2005] [error] [client 58.225.62.140] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:53:43 2005] [error] [client 218.39.132.175] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 12:33:13 2005] [error] [client 208.51.151.210] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:59:01 2005] [error] [client 24.83.37.136] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 11:42:43 2005] [error] [client 216.127.124.16] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 05:15:09 2005] [error] [client 222.166.160.184] Directory index forbidden by rule: /var/www/html/"],"[ :: ] [] [ ...] : ////"],[12,["[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:16 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2"],"[ :: ] [] _ -"]]" +} +``` +{% include copy-curl.html %} + +The following table describes the Assistant Summary API parameters. + +Parameter | Required/Optional | Description +:--- | :--- | :--- +`summaryType` | Required | Specifies the type of application calling this API. Use `alerts` for alert insights. +`question` | Required | Specifies the user's question regarding alert insights. Default is `Please summarize this alert, do not use any tool.` +`context` | Required | Provides context for the alert, including the alert monitor definition, active alerts, and trigger values. +`index` | Optional | The index that the alert monitors. If this parameter is not provided, log pattern analysis is not returned. +`dsl` | Optional | The DSL query for alert monitoring. If this parameter is not provided, log pattern analysis is not returned. +`topNLogPatternData` | Optional | Log patterns for the alert trigger data. If this parameter is not provided, log pattern analysis is not returned. + +## Generating alert insights + +You can generate alert insights by calling the `/api/assistant/insight` API endpoint. To generate alert insights, all of the following parameters are required: + +```json +POST /api/assistant/insight +{ + "summaryType": "alerts", + "insightType": "user_insight" + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "question": "Please provide your insight on this alerts.", + "summary": +} +``` +{% include copy-curl.html %} + +The following table describes the Assistant Insight API parameters. + +Parameter | Required/Optional | Description +:--- | :--- | :--- +`summaryType` | Required | Specifies the type of application calling this API. Use `alerts` for alert insights. +`insightType` | Required | Defines the alert type. Use `os_insight` for cluster metrics alerts and `user_insight` for other alert types. +`question` | Required | Specifies the user's question regarding alert insights. Default is `Please provide your insight on this alerts.` +`context` | Required | Provides context for the alert, including the alert monitor definition, active alerts, and trigger values. +`summary` | Required | The result returned by the alert summary agent. + + +## Viewing alert insights in OpenSearch Dashboards + +Before viewing alert insights, you must configure alerts in OpenSearch Dashboards. For more information, see [Alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/). + +To view alert insights in OpenSearch Dashboards, use the following steps: + +1. On the top menu bar, go to **OpenSearch Plugins > Alerting**. All alerts are displayed. + +1. Hover over the alerts for your desired monitor. If you configured alert insights, you will see a sparkle icon ({::nomarkdown}sparkle icon{:/}) next to the alerts in the **Alerts** column, as shown in the following image. + + ![Alerting page with sparkle icon]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/alert-insight-start.png) + +1. Select the alerts label or the sparkle icon. You will see the generated summary, as shown in the following image. + + ![Alert summary]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/alert-insight-summary.png) + +1. Select the information icon ({::nomarkdown}info icon{:/}) to view alert insights. You will see the generated alert insights, as shown in the following image. + + ![Alert insights]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/alert-insight-insight.png) \ No newline at end of file diff --git a/_dashboards/dashboards-assistant/data-summary.md b/_dashboards/dashboards-assistant/data-summary.md new file mode 100644 index 00000000..399a0942 --- /dev/null +++ b/_dashboards/dashboards-assistant/data-summary.md @@ -0,0 +1,219 @@ +--- +layout: default +title: Data summary +parent: OpenSearch Assistant for OpenSearch Dashboards +nav_order: 30 +has_children: false +--- + +# Data summary + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The OpenSearch Dashboards Assistant data summary feature uses large language models (LLMs) to help you generate summaries for data stored in OpenSearch indexes. This tool provides an efficient way to gain insights from large datasets, making it easier to understand and act on the information contained in your OpenSearch indexes. + +## Configuration + +To configure the data summary feature, use the following steps. + +### Prerequisite + +Before using the data summary feature, enable query enhancements in OpenSearch Dashboards as follows: + +1. On the top menu bar, go to **Management > Dashboards Management**. +1. In the left navigation pane, select **Advanced settings**. +1. On the settings page, toggle **Enable query enhancements** to **On**. + +### Step 1: Enable the data summary feature + +To enable the data summary feature, configure the following `opensearch_dashboards.yml` setting: + +```yaml +queryEnhancements.queryAssist.summary.enabled: true +``` +{% include copy.html %} + +### Step 2: Create a data summary agent + +To orchestrate data summarization, create a data summary [agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). To create an agent, send a `POST /_plugins/_flow_framework/workflow?provision=true` request and provide the agent template as a payload: + +
+ + Request + + {: .text-delta} + +```json +POST /_plugins/_flow_framework/workflow?provision=true +{ + "name": "Query Assist Agent", + "description": "Create a Query Assist Agent using Claude on BedRock", + "use_case": "REGISTER_AGENT", + "version": { + "template": "1.0.0", + "compatibility": ["2.13.0", "3.0.0"] + }, + "workflows": { + "provision": { + "user_params": {}, + "nodes": [ + { + "id": "create_claude_connector", + "type": "create_connector", + "previous_node_inputs": {}, + "user_inputs": { + "version": "1", + "name": "Claude Sonnet 4.6 runtime Connector", + "protocol": "aws_sigv4", + "description": "The connector to BedRock service for Claude model", + "actions": [ + { + "headers": { + "x-amz-content-sha256": "required", + "content-type": "application/json" + }, + "method": "POST", + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.prompt}\"}]}],\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens},\"temperature\":${parameters.temperature}}", + "action_type": "predict", + "url": "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" + } + ], + "credential": { + "access_key": "", + "secret_key": "", + "session_token": "" + }, + "parameters": { + "region": "us-west-2", + "endpoint": "bedrock-runtime.us-west-2.amazonaws.com", + "content_type": "application/json", + "auth": "Sig_V4", + "max_tokens": "8000", + "service_name": "bedrock", + "temperature": "0.0001", + "response_filter": "$.content[0].text", + "anthropic_version": "bedrock-2023-05-31" + } + } + }, + { + "id": "register_claude_model", + "type": "register_remote_model", + "previous_node_inputs": { + "create_claude_connector": "connector_id" + }, + "user_inputs": { + "description": "Claude model", + "deploy": true, + "name": "claude-sonnet-4-6" + } + }, + { + "id": "create_query_assist_data_summary_ml_model_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You are an assistant that helps to summarize the data and provide data insights.\nThe data are queried from OpenSearch index through user's question which was translated into PPL query.\nHere is a sample PPL query: `source= | where = `.\nNow you are given ${parameters.sample_count} sample data out of ${parameters.total_count} total data.\nThe user's question is `${parameters.question}`, the translated PPL query is `${parameters.ppl}` and sample data are:\n```\n${parameters.sample_data}\n```\nCould you help provide a summary of the sample data and provide some useful insights with precise wording and in plain text format, do not use markdown format.\nYou don't need to echo my requirements in response." + }, + "name": "MLModelTool", + "type": "MLModelTool" + } + }, + { + "id": "create_query_assist_data_summary_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_query_assist_data_summary_ml_model_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "Query Assist Data Summary Agent", + "description": "this is an query assist data summary agent" + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +
+ +For sample agent templates, see [Flow Framework sample templates](https://github.com/opensearch-project/flow-framework/tree/2.x/sample-templates). Note the agent ID; you'll use it in the following step. + +### Step 3: Create a root agent + +Next, create a [root agent]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/workflow-tutorial/#root_agent) for the data summary agent created in the previous step: + +```json +POST /.plugins-ml-config/_doc/os_data2summary +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "" + } +} +``` +{% include copy-curl.html %} + +This example demonstrates a system index. In security-enabled domains, only superadmins have permissions to execute this code. For information about making superadmin calls, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). For access permissions, contact your system administrator. +{: .warning} + +### Step 4: Test the agent + +You can verify that the data summary agent was created successfully by calling the agent with an example payload: + +```json +POST /_plugins/_ml/agents/{DATA_SUMMARY_AGENT_ID}/_execute +{ + "parameters": { + "sample_data":"'[{\"_index\":\"90943e30-9a47-11e8-b64d-95841ca0b247\",\"_source\":{\"referer\":\"http://twitter.com/success/gemini-9a\",\"request\":\"/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\",\"extension\":\"deb\",\"memory\":null,\"ip\":\"239.67.210.53\",\"index\":\"opensearch_dashboards_sample_data_logs\",\"message\":\"239.67.210.53 - - [2018-08-30T15:29:01.686Z] \\\"GET /beats/metricbeat/metricbeat-6.3.2-amd64.deb HTTP/1.1\\\" 404 2633 \\\"-\\\" \\\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\\\"\",\"url\":\"https://artifacts.opensearch.org/downloads/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"tags\":\"success\",\"geo\":{\"srcdest\":\"CN:PL\",\"src\":\"CN\",\"coordinates\":{\"lat\":44.91167028,\"lon\":-108.4455092},\"dest\":\"PL\"},\"utc_time\":\"2024-09-05 15:29:01.686\",\"bytes\":2633,\"machine\":{\"os\":\"win xp\",\"ram\":21474836480},\"response\":\"404\",\"clientip\":\"239.67.210.53\",\"host\":\"artifacts.opensearch.org\",\"event\":{\"dataset\":\"sample_web_logs\"},\"phpmemory\":null,\"timestamp\":\"2024-09-05 15:29:01.686\"}}]'", + "sample_count":1, + "total_count":383, + "question":"Are there any errors in my logs?", + "ppl":"source=opensearch_dashboards_sample_data_logs| where QUERY_STRING(['response'], '4* OR 5*')"} +} +``` +{% include copy-curl.html %} + +## Generating a data summary + +You can generate a data summary by calling the `/api/assistant/data2summary` API endpoint. The `sample_count`, `total_count`, `question`, and `ppl` parameters are optional: + +```json +POST /api/assistant/data2summary +{ + "sample_data":"'[{\"_index\":\"90943e30-9a47-11e8-b64d-95841ca0b247\",\"_source\":{\"referer\":\"http://twitter.com/success/gemini-9a\",\"request\":\"/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\",\"extension\":\"deb\",\"memory\":null,\"ip\":\"239.67.210.53\",\"index\":\"opensearch_dashboards_sample_data_logs\",\"message\":\"239.67.210.53 - - [2018-08-30T15:29:01.686Z] \\\"GET /beats/metricbeat/metricbeat-6.3.2-amd64.deb HTTP/1.1\\\" 404 2633 \\\"-\\\" \\\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\\\"\",\"url\":\"https://artifacts.opensearch.org/downloads/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"tags\":\"success\",\"geo\":{\"srcdest\":\"CN:PL\",\"src\":\"CN\",\"coordinates\":{\"lat\":44.91167028,\"lon\":-108.4455092},\"dest\":\"PL\"},\"utc_time\":\"2024-09-05 15:29:01.686\",\"bytes\":2633,\"machine\":{\"os\":\"win xp\",\"ram\":21474836480},\"response\":\"404\",\"clientip\":\"239.67.210.53\",\"host\":\"artifacts.opensearch.org\",\"event\":{\"dataset\":\"sample_web_logs\"},\"phpmemory\":null,\"timestamp\":\"2024-09-05 15:29:01.686\"}}]'", + "sample_count":1, + "total_count":383, + "question":"Are there any errors in my logs?", + "ppl":"source=opensearch_dashboards_sample_data_logs| where QUERY_STRING(['response'], '4* OR 5*')" +} +``` +{% include copy-curl.html %} + +The following table describes the Assistant Data Summary API parameters. + +Parameter | Required/Optional | Description +:--- | :--- | :--- +`sample_data` | Required | A sample of data returned by the specified query and used as input for summarization. +`question` | Optional | The user's natural language question about the data, which guides the summary generation. +`ppl` | Optional | The Piped Processing Language (PPL) query used to retrieve data; in query assistance, this is generated by the LLM using the user's natural language question. +`sample_count` | Optional | The number of entries included in sample_data. +`total_count` | Optional | The total number of entries in the full query result set. + +## Viewing data summaries in OpenSearch Dashboards + +To view alert insights in OpenSearch Dashboards, use the following steps: + +1. On the top menu bar, go to **OpenSearch Dashboards > Discover**. + +1. From the query language dropdown list, select **PPL**. You will see the generated data summary after the query text, as shown in the following image. + + ![data summary]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/data-summary.png) diff --git a/_dashboards/dashboards-assistant/index.md b/_dashboards/dashboards-assistant/index.md index dd62347c..02d713e3 100644 --- a/_dashboards/dashboards-assistant/index.md +++ b/_dashboards/dashboards-assistant/index.md @@ -1,19 +1,18 @@ --- layout: default title: OpenSearch Assistant for OpenSearch Dashboards -nav_order: 3 -has_children: false +nav_order: 110 +has_children: true has_toc: false +redirect_from: + - /dashboards/dashboards-assistant/ --- -This is an experimental feature and is not recommended for use in a production environment. For updates on the feature's progress or to leave feedback, go to the [`dashboards-assistant` repository](https://github.com/opensearch-project/dashboards-assistant) on GitHub or the associated [OpenSearch forum thread](https://forum.opensearch.org/t/feedback-opensearch-assistant/16741). -{: .warning} - Note that machine learning models are probabilistic and that some may perform better than others, so the OpenSearch Assistant may occasionally produce inaccurate information. We recommend evaluating outputs for accuracy as appropriate to your use case, including reviewing the output or combining it with other verification factors. {: .important} # OpenSearch Assistant for OpenSearch Dashboards -Introduced 2.12 +**Introduced 2.13** {: .label .label-purple } The OpenSearch Assistant toolkit helps you create AI-powered assistants for OpenSearch Dashboards without requiring you to have specialized query tools or skills. @@ -22,14 +21,14 @@ The OpenSearch Assistant toolkit helps you create AI-powered assistants for Open To enable **OpenSearch Assistant** in OpenSearch Dashboards, locate your copy of the `opensearch_dashboards.yml` file and set the following option: -``` +```yaml assistant.chat.enabled: true ``` -{% include copy-curl.html %} +{% include copy.html %} Then configure the root `agent_id` through the following API: -``` +```json PUT .plugins-ml-config/_doc/os_chat { "type":"os_chat_root_agent", @@ -40,6 +39,8 @@ PUT .plugins-ml-config/_doc/os_chat ``` {% include copy-curl.html %} +For more information about configuring the root agent, see [Build your own chatbot]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/chatbots/build-chatbot/#step-5-configure-a-root-chatbot-agent-in-opensearch-dashboards). + This example shows a system index. In security-enabled domains, only super admins have permission to execute this code. For information about making super admin calls, see the [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/) guide. For access permission, contact your IT administrator. {: .warning} @@ -47,10 +48,7 @@ Next, restart the OpenSearch Dashboards server. Following a successful restart, A screenshot of the interface is shown in the following image. -OpenSearch Assistant interface - -For more information about ways to enable experimental features, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). -{: .note} +![OpenSearch Assistant interface]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-full-frame.png){: width="700" } ## Configuring OpenSearch Assistant @@ -60,7 +58,7 @@ For information about configuring OpenSearch Assistant through the REST API, see ## Using OpenSearch Assistant in OpenSearch Dashboards -The following tutorials guide you through using OpenSearch Assistant in OpenSearch Dashboards. OpenSearch Assistant can be viewed full frame or in the right sidebar. The default is sidebar. To view full frame, select the frame icon {::nomarkdown}frame icon{:/} in the toolbar. +The following tutorials guide you through using OpenSearch Assistant in OpenSearch Dashboards. OpenSearch Assistant can be viewed in full frame or in the sidebar. The default view is in the right sidebar. To view the assistant in the left sidebar or in full frame, select the {::nomarkdown}frame icon{:/} (frame) icon in the toolbar and choose the preferred option. ### Start a conversation @@ -68,19 +66,19 @@ Start a conversation by entering a prompt in the **Ask a question** search box o The following screenshot shows an example prompt and response. -Prompt and response using OpenSearch Assistant in OpenSearch Dashboards +![Prompt and response using OpenSearch Assistant in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-QandA.png){: width="700" } ### Regenerate a response Beneath the response, select the regenerate icon to generate an alternative answer to your original question. The new answer will replace the previous one, appearing in both the interface and the chat history. A regenerated example is shown in the following image. -Regenerated response +![Regenerated response]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-regenerate.png){: width="700" } ### Suggested prompts OpenSearch Assistant suggests prompts to help you get started, build upon your existing prompts, or explore other queries you may not have considered, among other reasons. Select a suggested prompt listed beneath the response field. A screenshot is shown in the following image. -Suggested prompts +![Suggested prompts]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-suggestions.png){: width="700" } ### Rate a response @@ -90,27 +88,27 @@ To rate a response, select the thumbs up or thumbs down icon. A screenshot of th Learn how a response is generated by selecting the **How was this generated?** option. This option is included within the available suggestions to help you understand which tools were involved in creating the response. If multiple tools were involved, each step will display the tool name and its input and output. This feature can be useful for troubleshooting. A screenshot is shown in the following image. -Response generation details +![Response generation details]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-how-generated.png){: width="700" } ### Resume previous conversations To view a previous conversation, select the clock icon to open the conversation history panel and display the chat history. The conversation history can also be searched by conversation name. A screenshot is shown in the following image. -Conversation history +![Conversation history]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-conversation-history.png){: width="400" } #### Edit and delete previous conversations Select the pencil icon to edit a conversation name and rename it. Select the **Confirm name** button to save the new name. A screenshot is shown in the following image. -Editing a conversation name +![Editing a conversation name]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-edit-convo.png){: width="300" } Select the trash can icon to delete a conversation. Once the confirmation dialog appears, select **Delete conversation**. The conversation is now deleted from your chat history. A screenshot is shown in the following image. -Deleting a conversation +![Deleting a conversation]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-delete-convo.png){: width="300" } ### Share a conversation through Notebooks -You can use [Notebooks]({{site.url}}{{site.baseurl}}/observing-your-data/notebooks/) to save your conversations. To use this option, select **Save to notebook** from the dropdown menu to the right of **OpenSearch Assistant**. Enter a name for the notebook, then select **Save**. A pop-up message in the lower-right corner confirms the conversation has been saved. +You can use [Notebooks]({{site.url}}{{site.baseurl}}/dashboards/notebooks/) to save your conversations. To use this option, select **Save to notebook** from the dropdown menu to the right of **OpenSearch Assistant**. Enter a name for the notebook, then select **Save**. A pop-up message in the lower-right corner confirms the conversation has been saved. All conversations (prompts and responses/questions and answers) between you and the large language model (LLM) will be saved to this notebook. @@ -118,13 +116,34 @@ To open the saved notebook or view a list of other notebooks, select **Observabi A screenshot of the Notebooks interface with a list of saved conversations is shown in the following image. -Notebooks interface with saved OpenSearch Assistant conversations +![Notebooks interface with saved OpenSearch Assistant conversations]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-notebooks.png){: width="700" } The following screenshot shows a saved conversation, along with actions you can take for the saved conversation. -Notebooks interface with saved OpenSearch Assistant conversations +![Notebooks interface with saved OpenSearch Assistant conversations]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-assistant-save-notebook.png){: width="700" } -## Related articles +## Enabling Dashboards Assistant experimental features +**Introduced 2.16** +{: .label .label-purple } + +To enable experimental assistant features, such as text to visualization, locate your copy of the `opensearch_dashboards.yml` file and set the following option: + +```yaml +assistant.next.enabled: true +``` +{% include copy-curl.html %} + +## Additional Dashboards Assistant capabilities + +For information about additional Dashboards Assistant capabilities, see the following pages: + +- [Generating alert insights]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/alert-insight/) +- [Generating data summaries]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/data-summary/) +- [Generating anomaly detector suggestions]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/suggest-anomaly-detector/) +- [Generating visualizations from text]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/text-to-visualization/) + +## Related documentation - [Getting started guide for OpenSearch Assistant in OpenSearch Dashboards](https://github.com/opensearch-project/dashboards-assistant/blob/main/GETTING_STARTED_GUIDE.md) - [OpenSearch Assistant configuration through the REST API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/opensearch-assistant/) +- [Build your own chatbot]({{site.url}}{{site.baseurl}}/ml-commons-plugin/tutorials/build-chatbot/) diff --git a/_dashboards/dashboards-assistant/suggest-anomaly-detector.md b/_dashboards/dashboards-assistant/suggest-anomaly-detector.md new file mode 100644 index 00000000..fb3e41ba --- /dev/null +++ b/_dashboards/dashboards-assistant/suggest-anomaly-detector.md @@ -0,0 +1,89 @@ +--- +layout: default +title: Anomaly detector suggestions +parent: OpenSearch Assistant for OpenSearch Dashboards +nav_order: 20 +has_children: false +--- + +# Anomaly detector suggestions + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The OpenSearch Dashboards Assistant can use a large language model (LLM) to suggest the creation of an anomaly detector. The LLM analyzes data patterns in your OpenSearch indexes and recommends configuration settings for the anomaly detector, making it easier to identify unusual activity or trends in your data. + +## Configuration + +To configure anomaly detector suggestions, use the following steps. + +### Prerequisite + +Before using anomaly detector suggestions, enable query enhancements in OpenSearch Dashboards as follows: + +1. On the top menu bar, go to **Management > Dashboards Management**. +1. In the left navigation pane, select **Advanced settings**. +1. On the settings page, toggle **Enable query enhancements** to **On**. + +### Step 1: Enable anomaly detector suggestions + +To enable anomaly detector suggestions, configure the following `opensearch_dashboards.yml` setting: + +```yaml +assistant.smartAnomalyDetector.enabled: true +``` +{% include copy.html %} + +### Step 2: Create an anomaly detector suggestion agent + +To orchestrate anomaly detector suggestions, create an anomaly detector suggestion [agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). To create an agent, send a `POST /_plugins/_flow_framework/workflow?provision=true` request and provide the agent template as a payload. For more information, see [Configuring OpenSearch Assistant]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/index/#configuring-opensearch-assistant). + +For sample agent templates, see [Flow Framework sample templates](https://github.com/opensearch-project/flow-framework/tree/2.x/sample-templates). Note the agent ID; you'll use it in the following step. + +### Step 3: Configure the agent + +Next, configure the anomaly detector suggestion agent created in the previous step: + +```json +POST /.plugins-ml-config/_doc/os_suggest_ad +{ + "type": "suggest_anomaly_detector_agent", + "configuration": { + "agent_id": "" + } +} +``` +{% include copy-curl.html %} + +This example demonstrates a system index. In security-enabled domains, only superadmins have permissions to execute this code. For information about making superadmin calls, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). For access permissions, contact your system administrator. +{: .warning} + +### Step 4: Test the agent + +You can verify that the agent was created successfully by calling the agent with an example payload: + +```json +POST /_plugins/_ml/agents/{SUGGEST_ANOMALY_DETECTOR_AGENT_ID}/_execute +{ + "parameters": { + "index":"sample_weblogs_test" + } +} +``` +{% include copy-curl.html %} + +## Viewing anomaly detector suggestions in OpenSearch Dashboards + +To view anomaly detector suggestions in OpenSearch Dashboards, use the following steps: + +1. On the top menu bar, go to **OpenSearch Dashboards > Discover**. + +1. From the index pattern dropdown list, select an index pattern. + +1. Select the **AI assistant** dropdown list and then select **Suggest anomaly detector**, as shown in the following image. + + ![Click the Suggest anomaly detector action]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/suggestAD-button.png){: width="420px" } + +1. Wait for the LLM to populate the **Suggest anomaly detector** fields that will be used to create an anomaly detector for the index pattern. Then select the **Create detector** button to create an anomaly detector, as shown in the following image. + + ![Suggested anomaly detector]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/suggestAD-UI.png){: width="800px" } diff --git a/_dashboards/dashboards-assistant/text-to-visualization.md b/_dashboards/dashboards-assistant/text-to-visualization.md new file mode 100644 index 00000000..2d5158c9 --- /dev/null +++ b/_dashboards/dashboards-assistant/text-to-visualization.md @@ -0,0 +1,286 @@ +--- +layout: default +title: Text to visualization +parent: OpenSearch Assistant for OpenSearch Dashboards +nav_order: 40 +has_children: false +--- + +# Text to visualization + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The OpenSearch Dashboards Assistant can create visualizations using natural language instructions. + +## Configuration + +To configure text to visualization, use the following steps. + +### Step 1: Enable text to visualization + +To enable text to visualization, configure the following `opensearch_dashboards.yml` setting: + +```yaml +assistant.text2viz.enabled: true +``` +{% include copy.html %} + +### Step 2: Create the agents + +To orchestrate text to visualization, you'll need to create the necessary [agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). Create a workflow template for creating all necessary text-to-visualization agents by sending the following request: + +
+ + Request + + {: .text-delta} + +```json +POST /_plugins/_flow_framework/workflow +{ + "name": "Text to visualization agents", + "description": "This template is to create all Agents required for text to visualization", + "use_case": "REGISTER_AGENTS", + "version": { + "template": "1.0.0", + "compatibility": [ + "2.18.0", + "3.0.0" + ] + }, + "workflows": { + "provision": { + "user_params": {}, + "nodes": [ + { + "id": "create_claude_connector", + "type": "create_connector", + "previous_node_inputs": {}, + "user_inputs": { + "credential": { + "access_key": "", + "secret_key": "", + "session_token": "" + }, + "parameters": { + "endpoint": "bedrock-runtime.us-east-1.amazonaws.com", + "content_type": "application/json", + "auth": "Sig_V4", + "max_tokens_to_sample": "8000", + "service_name": "bedrock", + "temperature": "0.0000", + "response_filter": "$.content[0].text", + "region": "us-east-1", + "anthropic_version": "bedrock-2023-05-31" + }, + "version": "1", + "name": "Claude Sonnet 4.6 runtime Connector", + "protocol": "aws_sigv4", + "description": "The connector to BedRock service for claude model", + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.prompt}\"}]}],\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens_to_sample}}" + } + ] + } + }, + { + "id": "register_claude_model", + "type": "register_remote_model", + "previous_node_inputs": { + "create_claude_connector": "connector_id" + }, + "user_inputs": { + "name": "claude-sonnet-4-6", + "description": "Claude model", + "deploy": true + } + }, + { + "id": "create_t2vega_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You're an expert at creating vega-lite visualization. No matter what the user asks, you should reply with a valid vega-lite specification in json.\nYour task is to generate Vega-Lite specification in json based on the given sample data, the schema of the data, the PPL query to get the data and the user's input.\nLet's start from dimension and metric/date. Now I have a question, I already transfer it to PPL and query my Opensearch cluster. \nThen I get data. For the PPL, it will do aggregation like \"stats AVG(field_1) as avg, COUNT(field_2) by field_3, field_4, field_5\". \nIn this aggregation, the metric is [avg, COUNT(field_2)] , and then we judge the type of field_3,4,5. If only field_5 is type related to date, the dimension is [field_3, field_4], and date is [field_5]\nFor example, stats SUM(bytes) by span(timestamp, 1w), machine.os, response, then SUM(bytes) is metric and span(timestamp, 1w) is date, while machine.os, response are dimensions.\nNotice: Some fields like 'span()....' will be the date, but not metric and dimension. \nAnd one field will only count once in dimension count. You should always pick field name from schema\nTo summarize,\nA dimension is a categorical variable that is used to group, segment, or categorize data. It is typically a qualitative attribute that provides context for metrics and is used to slice and dice data to see how different categories perform in relation to each other.\nThe dimension is not date related fields. The dimension and date are very closed. The only difference is date is related to datetime, while dimension is not.\nA metric is a quantitative measure used to quantify or calculate some aspect of the data. Metrics are numerical and typically represent aggregated values like sums, averages, counts, or other statistical calculations.\n\nIf a ppl doesn't have aggregation using 'stats', then each field in output is dimension.\nOtherwise, if a ppl use aggregation using 'stats' but doesn't group by using 'by', then each field in output is metric.\n\nThen for each given PPL, you could give the metric and dimension and date. One field will in only one of the metric, dimension or date.\n\nThen according to the metric number and dimension number of PPL result, you should first format the entrance code by metric_number, dimension_number, and date_number. For example, if metric_number = 1, dimension_number = 2, date_number=1, then the entrance code is 121.\nI define several use case categories here according to the entrance code.\nFor each category, I will define the entrance condition (number of metric and dimension)\nI will also give some defined attribute of generated vega-lite. Please refer to it to generate vega-lite.\n\nType 1:\nEntrance code: <1, 1, 0>\nDefined Attributes:\n {\n \"title\": \"\",\n \"description\": \"<description>\",\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<metric name>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<dimension name>\",\n \"type\": \"nominal\"\n }\n },\n }\n\nType 2:\nEntrance code: <1, 2, 0>\nDefined Attributes:\n{\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n },\n \"color\": {\n \"field\": \"<dimension 2>\",\n \"type\": \"nominal\"\n }\n }\n }\n\n\nType 3\nEntrance code: <3, 1, 0>\nDefined Attributes:\n{\n \"mark\": \"point\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<metric 2>\",\n \"type\": \"quantitative\"\n },\n \"size\": {\n \"field\": \"<metric 3>\",\n \"type\": \"quantitative\"\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n}\n\nType 4\nEntrance code: <2, 1, 0>\nDefined Attributes:\n{\n \"mark\": \"point\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<mtric 1>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<metric 2>\",\n \"type\": \"quantitative\"\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n}\n\nType 5:\nEntrance code: <2, 1, 1>\nDefined Attributes:\n{\n \"layer\": [\n {\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 1 name>\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n },\n {\n \"mark\": {\n \"type\": \"line\",\n \"color\": \"red\"\n },\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"<metric 2>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 2 name>\",\n \"orient\": \"right\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n }\n ],\n \"resolve\": {\n \"scale\": {\n \"y\": \"independent\"\n }\n }\n }\n\nType 6:\nEntrance code: <2, 0, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"layer\": [\n {\n \"mark\": \"area\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 1 name>\"\n }\n }\n }\n },\n {\n \"mark\": {\n \"type\": \"line\",\n \"color\": \"black\"\n },\n \"encoding\": {\n \"x\": {\n \"field\": \"date\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"metric 2\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 2 name>\",\n \"orient\": \"right\"\n }\n }\n }\n }\n ],\n \"resolve\": {\n \"scale\": {\n \"y\": \"independent\"\n }\n }\n }\n \nType 7:\nEntrance code: <1, 0, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"line\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\",\n \"axis\": {\n \"title\": \"<date name>\"\n }\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric name>\"\n }\n }\n }\n }\n\nType 8:\nEntrance code: <1, 1, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"line\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\",\n \"axis\": {\n \"title\": \"<date name>\"\n }\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric name>\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\",\n \"legend\": {\n \"title\": \"<dimension name>\"\n }\n }\n }\n }\n\nType 9:\nEntrance code: <1, 2, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"line\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\",\n \"axis\": {\n \"title\": \"<date name>\"\n }\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 1>\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\",\n \"legend\": {\n \"title\": \"<dimension 1>\"\n }\n },\n \"facet\": {\n \"field\": \"<dimension 2>\",\n \"type\": \"nominal\",\n \"columns\": 2\n }\n }\n }\n\nType 10:\nEntrance code: all other code\nAll others type.\nUse a table to show the result\n\n\nBesides, here are some requirements:\n1. Do not contain the key called 'data' in vega-lite specification.\n2. If mark.type = point and shape.field is a field of the data, the definition of the shape should be inside the root \"encoding\" object, NOT in the \"mark\" object, for example, {\"encoding\": {\"shape\": {\"field\": \"field_name\"}}}\n3. Please also generate title and description\n\nThe sample data in json format:\n${parameters.sampleData}\n\nThis is the schema of the data:\n${parameters.dataSchema}\n\nThe user used this PPL query to get the data: ${parameters.ppl}\n\nThe user's question is: ${parameters.input_question}\n\nNotice: Some fields like 'span()....' will be the date, but not metric and dimension. \nAnd one field will only count once in dimension count. You should always pick field name from schema.\n And when you code is <2, 1, 0>, it belongs type 4.\n And when you code is <1, 2, 0>, it belongs type 9.\n\n\nNow please reply a valid vega-lite specification in json based on above instructions.\nPlease return the number of dimension, metric and date. Then choose the type. \nPlease also return the type.\nFinally return the vega-lite specification according to the type.\nPlease make sure all the key in the schema matches the word I given. \nYour answer format should be:\nNumber of metrics:[list the metric name here, Don't use duplicate name] <number of metrics {a}> \nNumber of dimensions:[list the dimension name here] <number of dimension {b}> \nNumber of dates:[list the date name here] <number of dates {c}> \nThen format the entrance code by: <Number of metrics, Number of dimensions, Number of dates>\nType and its entrance code: <type number>: <its entrance code>\nThen apply the vega-lite requirements of the type.\n<vega-lite> {here is the vega-lite json} </vega-lite>\n\nAnd don't use 'transformer' in your vega-lite and wrap your vega-lite json in <vega-lite> </vega-lite> tags\n" + }, + "name": "Text2Vega", + "type": "MLModelTool" + } + }, + { + "id": "create_instruction_based_t2vega_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You're an expert at creating vega-lite visualization. No matter what the user asks, you should reply with a valid vega-lite specification in json.\nYour task is to generate Vega-Lite specification in json based on the given sample data, the schema of the data, the PPL query to get the data and the user's input.\n\nBesides, here are some requirements:\n1. Do not contain the key called 'data' in vega-lite specification.\n2. If mark.type = point and shape.field is a field of the data, the definition of the shape should be inside the root \"encoding\" object, NOT in the \"mark\" object, for example, {\"encoding\": {\"shape\": {\"field\": \"field_name\"}}}\n3. Please also generate title and description\n\nThe sample data in json format:\n${parameters.sampleData}\n\nThis is the schema of the data:\n${parameters.dataSchema}\n\nThe user used this PPL query to get the data: ${parameters.ppl}\n\nThe user's input question is: ${parameters.input_question}\nThe user's instruction on the visualization is: ${parameters.input_instruction}\n\nNow please reply a valid vega-lite specification in json based on above instructions.\nPlease only contain vega-lite in your response.\n" + }, + "name": "Text2Vega", + "type": "MLModelTool" + } + }, + { + "id": "t2vega_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_t2vega_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "t2vega agent", + "description": "this is the t2vega agent that has a set of rules to generate the visualizations" + } + }, + { + "id": "t2vega_instruction_based_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_instruction_based_t2vega_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "t2vega instruction based agent", + "description": "this is the t2vega agent that supports instructions" + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +</details> + +Use the workflow ID returned in the response to provision the resources: + +```json +POST /_plugins/_flow_framework/workflow/{workflow_id}/_provision +``` +{% include copy-curl.html %} + +To view the status of the workflow and all created resources, send the following request: + +```json +GET /_plugins/_flow_framework/workflow/{workflow_id}/_status +``` +{% include copy-curl.html %} + +### Step 3: Configure the root agent + +Next, configure a root agent for text to visualization: + +```json +POST /.plugins-ml-config/_doc/os_text2vega +{ + "type": "os_chat_root_agent", + "configuration": { + "agent_id": "<ROOT_AGENT_ID>" + } +} +``` +{% include copy-curl.html %} + +Configure the agent to receive user instructions for creating visualizations: + +```json +POST /.plugins-ml-config/_doc/os_text2vega_with_instructions +{ + "type": "os_chat_root_agent", + "configuration": { + "agent_id": "<ROOT_AGENT_ID>" + } +} +``` +{% include copy-curl.html %} + +This example demonstrates a system index. In security-enabled domains, only superadmins have permissions to execute this code. For information about making superadmin calls, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). For access permissions, contact your system administrator. +{: .warning} + +### Step 4: Test the agent + +You can verify that the agent was created successfully by calling the agent with an example payload: + +```json +POST /_plugins/_ml/agents/{ROOT_AGENT_ID}/_execute +{ + "parameters": { + "input_question": "find unique visitors and average bytes every 3 hours", + "input_instruction": "display with different layers, use independent scale for different layers, display unique visitors with light blue bar chart", + "ppl": "source=opensearch_dashboards_sample_data_ecommerce| stats DISTINCT_COUNT(user) as unique_visitors, AVG(taxful_total_price) as avg_bytes by span(order_date, 3h)", + "sampleData": """[{\"unique_visitors\":15,\"avg_bytes\":90.98684210526316,\"span(order_date,3h)\":\"2024-04-25 00:00:00\"},{\"unique_visitors\":14,\"avg_bytes\":72.72083333333333,\"span(order_date,3h)\":\"2024-04-25 03:00:00\"}]""", + "dataSchema": """[{\"name\":\"unique_visitors\",\"type\":\"integer\"},{\"name\":\"avg_bytes\",\"type\":\"double\"},{\"name\":\"span(order_date,3h)\",\"type\":\"timestamp\"}]""" + } +} +``` +{% include copy-curl.html %} + +## Generating a visualization from text + +You can generate a visualization from text by calling the `/api/assistant/text2vega` API endpoint. The `input_instruction` parameter is optional: + +```json +POST /api/assistant/text2vega +{ + "input_instruction": "<input_instruction>", + "input_question": "<input_question>", + "ppl": "<ppl_query>", + "dataSchema": "<data_schema_of_ppl_response>", + "sampleData": "<sample_data_of_ppl_response>" +} +``` +{% include copy-curl.html %} + +The following table describes the Text to Visualization API parameters. + +Parameter | Required/Optional | Description +:--- | :--- | :--- +`input_question` | Required | The user's original question used to generate the corresponding Piped Processing Language (PPL) query. +`ppl` | Required | The generated PPL query that retrieves the data required for the visualization. +`dataSchema` | Required | Describes the structure and types of the data fields in the visualization output, based on the PPL response. +`sampleData` | Required | Provides sample entries from the data that will populate the visualization. +`input_instruction` | Optional | Specifies the styling instructions, such as colors, for the visualization. + +## Generating visualizations from text in OpenSearch Dashboards + +To generate visualizations from text in OpenSearch Dashboards, use the following steps: + +1. On the top menu bar, go to **OpenSearch Dashboards > Visualize** and then select **Create visualization**. + +1. In the **New Visualization** dialog, select **Natural language**, as shown in the following image. + + ![Create a visualization by selecting natural language]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/t2viz-start.png){: width="800px" } + +1. From the data sources dropdown list, select a data source, as shown in the following image. + + ![Create a visualization by selecting natural language]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/t2viz-select-data-source.png) + +1. In the text box on the upper right, enter a question using natural language. A new visualization is generated, as shown in the following image. + + ![Create a visualization by selecting natural language]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/t2viz-ask-question.png) + +1. To modify the generated visualization, select **Edit visual**. In the **Edit visual** dialog, enter the desired modifications and then select **Apply**, as shown in the following image. + + ![Create a visualization by selecting natural language]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/t2viz-edit-visual.png) + + The visualization is updated, as shown in the following image. + + ![Create a visualization by selecting natural language]({{site.url}}{{site.baseurl}}/images/dashboards-assistant/t2viz-edit-visual-response.png) + + + diff --git a/_dashboards/dev-tools/console.md b/_dashboards/dev-tools/console.md new file mode 100644 index 00000000..fb04f8c8 --- /dev/null +++ b/_dashboards/dev-tools/console.md @@ -0,0 +1,195 @@ +--- +layout: default +title: Console +parent: Using Dev Tools +grand_parent: Exploring data +nav_order: 10 +--- + +# Dev Tools console + +Use the **Console** tab in **Dev Tools** to send REST API requests to OpenSearch, including [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) search queries, index management operations, and cluster administration commands. + +The console supports all OpenSearch REST APIs. For example, you can use the console to perform the following common operations: + +- Search for documents using [`match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/), [`term`]({{site.url}}{{site.baseurl}}/query-dsl/term/term/), [`range`]({{site.url}}{{site.baseurl}}/query-dsl/term/range/), and other query types. +- Retrieve all documents from an index using [`match_all`]({{site.url}}{{site.baseurl}}/query-dsl/match-all/) queries. +- Count matching documents without retrieving them using the [`_count`]({{site.url}}{{site.baseurl}}/api-reference/search-apis/count/) endpoint. +- Compute metrics, statistics, and summaries of your data using [aggregations]({{site.url}}{{site.baseurl}}/aggregations/). +- Narrow down search results by [combining queries with filters]({{site.url}}{{site.baseurl}}/query-dsl/query-filter-context/). + +## Writing and sending requests + +Write your queries in the editor pane on the left side of the console. For example, enter the following request, which indexes one document into a `students` index: + +```json +PUT students/_doc/1 +{ + "name": "John Doe", + "gpa": 3.89, + "grad_year": 2022 +} +``` +{% include copy-curl.html %} + +For long queries, you can collapse and expand parts of your query by selecting the small triangles next to the line numbers. +{: .tip} + +To send a query to OpenSearch, select the query by placing the cursor anywhere in the query text. Then choose the play icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dev-tools/play-icon.png" class="inline-icon" alt="play icon"/>{:/}) on the upper right of the request or press `Ctrl/Cmd+Enter`, as shown in the following image. + +![Send request]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-send.png) + +OpenSearch displays the response in the response pane on the right side of the console. For the indexing request, the response confirms that the document was created, as shown in the following image. + +![Response pane]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-response.png) + +To search for the document that you indexed, enter the following request: + +```json +GET students/_search +{ + "query": { + "match": { + "name": "John Doe" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document in the `hits` array, as shown in the following image. + +![Search response]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-search-response.png) + +### Working in the cURL and console formats + +The console uses an easier syntax to format REST requests than the `curl` command. + +For example, the following `curl` command runs a search query: + +```bash +curl -XGET http://localhost:9200/students/_search?pretty -H 'Content-Type: application/json' -d' +{ + "query": { + "match": { + "name": "John Doe" + } + } +}' +``` +{% include copy.html %} + +The same query has a simpler syntax in the console format: + +```json +GET students/_search +{ + "query": { + "match": { + "name": "John Doe" + } + } +} +``` +{% include copy-curl.html %} + +If you paste a `curl` command directly into the console, the command is automatically converted into the format the console uses. To convert a query in the console into cURL format, see [Copying a query as cURL](#copying-a-query-as-curl). + +### Using triple quotation marks in queries + +When writing queries containing quotation marks (`"`) and backslash (`\`) characters, you can use triple quotation marks (`"""`) to avoid escaping the characters. This format improves readability and helps avoid escape characters when writing large or complex strings, especially when working with deeply nested JSON strings. + +You can index a document containing special characters by escaping each special character with a backslash: + +```json +PUT /testindex/_doc/1 +{ + "test_query": "{ \"query\": { \"query_string\": { \"query\": \"host:\\\"127.0.0.1\\\"\" } } }" +} +``` +{% include copy-curl.html %} + +Alternatively, you can use triple quotation marks for a simpler format: + +```json +PUT /testindex/_doc/1 +{ + "test_query": """{ "query": { "query_string": { "query": "host:\"127.0.0.1\"" } } }""" +} +``` +{% include copy-curl.html %} + +Triple quotation marks are only supported in the console---not in `curl` or other HTTP clients. To convert a query containing triple quotation marks into a format that other clients accept, use **Copy as cURL**. +{: .tip} + +If a response contains the `\n`, `\t`, `\`, or `"` special characters, the console formats the response using triple quotation marks. To turn off this behavior, select **Settings** from the top menu and toggle **JSON syntax**. +{: .tip} + +### Submitting long-running operations + +When submitting long-running operations (such as reindexing or snapshot creation) to OpenSearch, you can make the request asynchronous by providing the `wait_for_completion=false` query parameter. If this parameter is not specified, the request runs synchronously. In that case, if the operation exceeds the OpenSearch request timeout value, the client might send a new request, which can lead to unexpected behavior. If the API does not support asynchronous execution through query parameters, consider using cURL to run the request directly. + +## Using the request options menu + +To open the request options menu, select the wrench icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dev-tools/wrench-icon.png" class="inline-icon" alt="wrench icon"/>{:/}) on the upper right of a request, as shown in the following image. + +![Console tools]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-tools.png){: width="640" } + +### Copying a query as cURL + +To copy a query in cURL format, select the query and choose **Copy as cURL** from the request options menu. You can then run the copied command in a terminal or paste it into another HTTP client. + +### Viewing documentation + +To view the OpenSearch documentation for the selected request, choose **Open documentation** from the request options menu. + +### Auto indenting + +To use auto indent, select the queries that you want to format and choose **Auto indent** from the request options menu. + +Auto indenting a collapsed query expands it. + +Auto indenting a well-formatted query puts the request body on a single line. This is useful for working with [bulk APIs]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/). +{: .tip} + +## Using the top menu + +The top menu provides options for reusing queries, configuring the editor, and viewing keyboard shortcuts. + +### Viewing your request history + +You can view up to the 500 most recent requests that OpenSearch ran successfully. To view request history, select **History** from the top menu. If you select the request you want to view from the left pane, the query is shown in the right pane. + +To copy the query into the editor pane, select the query text and then select **Apply**. + +To clear the history, select **Clear**. + +### Exporting and importing queries + +To save the queries in the editor pane to a file, select **Export** from the top menu. The console downloads the queries as a `sense.json` file. + +To load queries from a file, select **Import** from the top menu, select the file, and then choose one of the following import options: + +- **Merge with existing queries**: Adds the imported queries to the queries already in the editor pane. +- **Overwrite existing queries**: Replaces the contents of the editor pane with the imported queries. + +Select **Import** to complete the import. + +### Updating the console settings + +To update your preferences, select **Settings** from the top menu. You can configure the following settings: + +- **Font Size**: Sets the editor font size. +- **Wrap long lines**: Wraps lines that exceed the editor width. +- **JSON syntax**: Uses triple quotation marks in the response pane for responses containing special characters. +- **Autocomplete**: Turns autocomplete suggestions on or off for **Fields**, **Indices & Aliases**, and **Templates**. +- **Automatically refresh autocomplete suggestions**: Refreshes autocomplete suggestions by querying OpenSearch. Automatic refreshes may be an issue if you have a large cluster or network limitations. To refresh suggestions manually, select **Refresh autocomplete suggestions**. + +### Using keyboard shortcuts + +To view all available keyboard shortcuts, select **Help** from the top menu. + +## Next steps + +- To try running additional queries in the console, see [Ingest data]({{site.url}}{{site.baseurl}}/getting-started/ingest-data/) and [Search your data]({{site.url}}{{site.baseurl}}/getting-started/search-data/). +- For information about writing queries, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). diff --git a/_dashboards/dev-tools/grok-debugger.md b/_dashboards/dev-tools/grok-debugger.md new file mode 100644 index 00000000..fd3a9e6a --- /dev/null +++ b/_dashboards/dev-tools/grok-debugger.md @@ -0,0 +1,52 @@ +--- +layout: default +title: Grok Debugger +parent: Using Dev Tools +grand_parent: Exploring data +nav_order: 20 +--- + +# Grok Debugger + +Use the **Grok Debugger** tab in Dev Tools to build and test [Grok patterns]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/grok/) before using them in ingest pipelines. Grok patterns parse unstructured log data into structured fields. The Grok Debugger tests patterns against sample text you provide, so it doesn't require any indexed data. + +## Testing a Grok pattern + +To test a Grok pattern, follow these steps: + +1. Navigate to **Dev Tools** and select **Grok Debugger** at the top of the page. +1. In the **Sample Log** field, enter a sample log message. For example, enter the following Apache access log entry: + + ``` + 127.0.0.1 - alice [15/Mar/2026:10:32:41 -0700] "GET /products/1234 HTTP/1.1" 200 2326 + ``` + {% include copy.html %} + +1. In the **Grok Pattern** field, enter the pattern to test against the sample log: + + ``` + %{IPORHOST:client_ip} - %{USER:user} \[%{HTTPDATE:timestamp}\] "%{WORD:method} %{URIPATHPARAM:request} HTTP/%{NUMBER:http_version}" %{NUMBER:status} %{NUMBER:bytes} + ``` + {% include copy.html %} + +1. Select **Simulate**. + +The **Results** pane displays **Pattern matched** and lists the extracted fields and their values, as shown in the following image. + +![Grok Debugger]({{site.url}}{{site.baseurl}}/images/dev-tools/grok-debugger.png) + +To clear both fields and the results, select **Clear**. + +To open the Grok processor documentation, select **Grok documentation**. + +## Configuring advanced settings + +To define your own patterns or return every match, select **Advanced settings**. You can configure the following settings: + +- **Custom pattern definitions**: Defines patterns that aren't included in the built-in pattern set. Enter one pattern per line in the format `PATTERN_NAME pattern_regex`. After you define a custom pattern, you can reference it in the **Grok Pattern** field using the `%{PATTERN_NAME:field_name}` syntax. +- **Capture all matches**: Returns all matches for a pattern instead of only the first match. + +## Next steps + +- For information about the Grok processor and the available built-in patterns, see [Grok processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/grok/). +- For information about creating ingest pipelines, see [Ingest pipelines]({{site.url}}{{site.baseurl}}/ingest-pipelines/). diff --git a/_dashboards/dev-tools/index.md b/_dashboards/dev-tools/index.md new file mode 100644 index 00000000..0361ddd0 --- /dev/null +++ b/_dashboards/dev-tools/index.md @@ -0,0 +1,46 @@ +--- +layout: default +title: Using Dev Tools +parent: Exploring data +nav_order: 20 +has_children: true +has_toc: false +redirect_from: + - /dashboards/run-queries/ + - /dashboards/dev-tools/run-queries/ + - /dashboards/dev-tools/index-dev/ + - /dashboards/visualize/run-queries/ + - /dashboards/discover/run-queries/ + - /dashboards/dev-tools/ +--- + +# Using Dev Tools + +The **Dev Tools** application in OpenSearch Dashboards provides tools for querying your cluster and testing queries and ingest patterns. + +If you're new to the Dev Tools application, see [Run queries in the Dev Tools console]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dev-tools/) for a hands-on introduction. +{: .tip} + +## Navigating to Dev Tools + +To open Dev Tools, select **Dev Tools** on the main OpenSearch Dashboards page, as shown in the following image. + +![Dev Tools console from main page]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-main.png) + +You can open Dev Tools from any other page by navigating to the main menu and selecting **Management** > **Dev Tools**, as shown in the following image. + +![Dev Tools console from all pages]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-left.png){: width="200" } + +In installations with workspaces enabled, select the code icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/code-icon.png" class="inline-icon" alt="code icon"/>{:/}) in the lower-left corner of the navigation panel. + +## Using Dev Tools + +The **Dev Tools** application is shown in the following image. + +![Dev Tools Console application]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-console.png) + +Dev Tools contains the following applications: + +- [**Console**]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/console/) sends [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) queries and other REST API requests to OpenSearch and displays the responses. +- [**Grok Debugger**]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/grok-debugger/) builds and tests [Grok patterns]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/grok/) against sample log data before you use them in ingest pipelines. +- [**Query Profiler**]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/query-profiler/) measures how long each part of a search query takes to run so that you can identify slow components. diff --git a/_dashboards/dev-tools/query-profiler.md b/_dashboards/dev-tools/query-profiler.md new file mode 100644 index 00000000..23e04a0b --- /dev/null +++ b/_dashboards/dev-tools/query-profiler.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Query Profiler +parent: Using Dev Tools +grand_parent: Exploring data +nav_order: 30 +--- + +# Query Profiler + +Use the **Query Profiler** tab in Dev Tools to measure how long each component of a search query takes to run. The Query Profiler runs your query with the [Profile API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/profile/) and presents the results as a visualization, so you can identify the queries and aggregations that consume the most time. + +When you open the Query Profiler, the editor contains the following default query, which includes the `profile` parameter, as shown in the following image. + +![Query Profiler default query]({{site.url}}{{site.baseurl}}/images/dev-tools/query-profiler-default.png) + +When you select **Visualize profile**, the Query Profiler collects profiling data even if your query doesn't contain the `profile` parameter. To include the profiling data in the response pane, keep `"profile": true` in the query. +{: .note} + +## Prerequisites + +The examples on this page use the **Sample eCommerce orders** dataset. If you're using a local installation of OpenSearch Dashboards and haven't added sample data yet, see [Add sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Profiling a query + +To profile a query, follow these steps: + +1. Navigate to **Dev Tools** and select **Query Profiler** at the top of the page. +1. Replace the default query in the editor pane with the query you want to profile. For example, enter the following query, which searches the sample e-commerce data and computes an average order total and a breakdown by customer gender: + + ```json + GET opensearch_dashboards_sample_data_ecommerce/_search + { + "profile": true, + "query": { + "bool": { + "must": [ + { "match": { "category": "Clothing" } }, + { "match": { "manufacturer": "Elitelligence" } } + ], + "filter": [ + { "range": { "taxful_total_price": { "gte": 50 } } } + ] + } + }, + "aggs": { + "avg_price": { + "avg": { "field": "taxful_total_price" } + }, + "by_gender": { + "terms": { "field": "customer_gender" } + } + } + } + ``` + {% include copy-curl.html %} + +1. Select the play icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dev-tools/play-icon.png" class="inline-icon" alt="play icon"/>{:/}) or press `Ctrl/Cmd+Enter` to run the query. OpenSearch displays the response in the right pane. +1. Select **Visualize profile**. + +To restore the default query and clear the results, select the reset icon next to the play icon. + +## Reviewing shard timings + +The **Profile Results** section lists the shards that processed the query, with the **Search time** and **Aggregation time** for each shard, as shown in the following image. + +![Query Profiler shard results]({{site.url}}{{site.baseurl}}/images/dev-tools/query-profiler-results.png) + +The bar colors indicate how much of the maximum time each shard consumed: + +- Green: 50% or less (low) +- Orange: 51--80% (medium) +- Red: More than 80% (high) + +To change these percentages, select the gear icon next to the legend and update the **Red (>80%)** and **Orange (>50%)** thresholds. To restore the default values, select **Reset to defaults**. + +You can also perform the following actions in this section: + +- To find a specific shard, enter its name in the **Search shard** field. +- To order the list by aggregation time instead of search time, select **Sort by: Search time** and then choose **Sort by: Aggregation time**. +- To change the number of shards displayed, select **Rows per page**. + +## Reviewing query timings + +Select a shard to display its query breakdown. The left pane contains a **Search** tab and an **Aggregation** tab, each listing the components that ran on that shard and the time each one took. Select the arrow next to a component to expand its subqueries. + +Select a component to display its details, as shown in the following image. + +![Query Profiler operation breakdown]({{site.url}}{{site.baseurl}}/images/dev-tools/query-profiler-breakdown.png) + +The details pane contains the following information: + +- The component name, the Lucene query it rewrote to, and the **Total time**. +- **Query Hierarchy**: The hierarchical structure of the query and its subqueries, with the percentage of total time for each. +- **Operation Breakdown**: The low-level Lucene operations that the component performed, such as `Create Weight`, `Build Scorer`, and `Next Doc`, with the time in nanoseconds and the number of times each operation ran. + +To switch between the chart and table views of the operation breakdown, select the **Visual breakdown** or **Raw data** icon on the right side of the **Operation Breakdown** heading. + +## Importing and exporting profile results + +To save the profile results, select **Export JSON** from the top menu. The Query Profiler downloads the results as a `profile.json` file. + +To load a query or a previously saved profile, select **Import** from the top menu, choose one of the following options in **Import to**, select the file, and then select **Import**: + +- **Search query**: Loads a search query into the editor pane. +- **Profile JSON**: Loads profile results and displays the visualization without running a query. + +## Updating the Query Profiler settings + +To update your preferences, select **Settings** from the top menu. You can configure the following settings: + +- **Font Size**: Sets the editor font size. +- **Wrap long lines**: Wraps lines that exceed the editor width. + +To view help for the Query Profiler, select **Help** from the top menu. + +## Next steps + +- For information about the API that the Query Profiler uses, see [Profile API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/profile/). +- For information about writing queries, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). diff --git a/_dashboards/discover/field-select.md b/_dashboards/discover/field-select.md new file mode 100644 index 00000000..47644821 --- /dev/null +++ b/_dashboards/discover/field-select.md @@ -0,0 +1,117 @@ +--- +layout: default +title: Field select tool +parent: Exploring data with Discover +grand_parent: Exploring data +nav_order: 40 +--- + +# Using the field select tool + +By default, the Discover application's **Results** table displays all fields for every document in the table. In the field select tool, you can select which data fields appear in the **Results** table. + +The field select tool is in the vertical panel to the immediate left of the [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) application pane. It is available only in the **Discover** application. + + +## Navigating the field select tool + +![Field select tool]({{site.url}}{{site.baseurl}}/images/dashboards/field-select-collapsed-callouts.png){: width="44%" } + +The following components make up the field select tool. + +- The **Index patterns** dropdown (A) presents all available index patterns. The selected index pattern determines what data is loaded and therefore which fields are available in the field select tool. +- The **Search field names** (B) box narrows the fields available in the select tool by matching field names to your search string. +- The **Filter by type** dropdown (C) narrows the fields available based on data properties such as data type and searchability. +- The **Selected fields** list (D) is a collapsible list of all selected fields. +- The **Popular fields** list (E) is a collapsible list of recently selected fields. +- The **Available fields** list (F) is a collapsible list of all fields that have not been selected. + +The **Selected fields**, **Popular fields**, and **Available fields** lists are mutually exclusive. A field appears in only one of these collapsible lists. +{: .important} + + +## Selecting an index pattern + +Before exploring and visualizing data, you must select an index pattern. + +An index pattern is equivalent to a table view in a traditional relational database system. It defines the dataset that you are interested in exploring and visualizing. For information about creating index patterns, see [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). + +To select an index pattern, follow these steps: + +1. In the field select tool, select an index pattern from the **Index patterns** dropdown. + + +## Selecting fields to display + +To select a field for display in the **Results** table, follow these steps: + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/arrow-right-icon.png" class="inline-icon" alt="expand icon"/>{:/} (expand) **Available fields** to expand the **Available fields**. + + If the field has been used recently, it might be in the **Popular fields** list instead of **Available fields**. + {: .note} + +1. (Optional) [Use the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="funnel icon"/>{:/} **Filter by type**](#filtering-fields-by-type ) popover to narrow the available fields by type. + +1. (Optional) Enter text in the **Search field names** box to narrow the list of available fields. + +1. Select a field in the **Available fields** or **Popular fields** list. + +1. Choose the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/green-plus-icon.png" class="inline-icon" alt="green plus icon"/>{:/} (add) icon of the selected field. + + The field is added as a column in the **Results** table in the **Discover** application pane. + +## Removing fields + +To remove a field from display in the **Results** table, follow these steps: + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/arrow-right-icon.png" class="inline-icon" alt="expand icon"/>{:/} (expand) **Selected fields** to expand the **Selected fields**. + +1. Choose a field in the **Selected fields** list. + +1. Choose the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/red-cross-icon.png" class="inline-icon" alt="red cross icon"/>{:/} (remove) icon of the selected field. + + The field is removed from the **Results** table in the **Discover** application pane. + + If the removed field was the last selected field, the **Results** table defaults back to displaying all fields. + {: .note} + + +## Filtering fields by type + +Often the list of available fields is long. To avoid scrolling through the list, filter fields in the field select tool by data type and by whether they are aggregatable or searchable. + +The number to the right of {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="funnel icon"/>{:/} **Filter by type** indicates the number of active type filters. +{: .tip} + +### Filtering fields by data type + +To narrow the fields in the field select tool by data type, follow these steps: + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="funnel icon"/>{:/} **Filter by type**. + +1. In the **Filter by type** popover, select a data type from the **Type** dropdown. + + The fields are restricted to the selected type. + + Fields are restricted in all the lists: **Selected fields**, **Popular fields**, and **Available fields**. + {: .note} + +### Filtering fields by property + +To filter fields by property, follow these steps: + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="funnel icon"/>{:/} **Filter by type**. + +1. In the **Filter by type** popover, select an **Aggregatable** option. For example, selecting **yes** filters out all non-aggregatable fields. + +1. In the **Filter by type** popover, select a **Searchable** option. For example, selecting **yes** filters out all non-searchable fields. + + Searchable fields are fields that are included in the inverted index and are available for search. For more information, see [Index]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/index-parameter/). + +### Filtering missing fields + +To filter out fields with missing data, follow these steps: + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="funnel icon"/>{:/} **Filter by type**. + +1. In the **Filter by type** popover, activate the **Hide missing fields** toggle. \ No newline at end of file diff --git a/_dashboards/discover/filter-tool.md b/_dashboards/discover/filter-tool.md new file mode 100644 index 00000000..fcd526e8 --- /dev/null +++ b/_dashboards/discover/filter-tool.md @@ -0,0 +1,166 @@ +--- +layout: default +title: Filter tool +parent: Exploring data with Discover +grand_parent: Exploring data +nav_order: 30 +--- + +# Using the filter tool + +The filter tool is at the top of the [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) and [Dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/) and [Visualize]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/) applications, directly below the **[Search]({{site.url}}{{site.baseurl}}/dashboards/discover/search-bar/)** bar. Use it to add and remove discrete filters to the data displayed in those applications. + + You can create any number of filters. Filters are listed in the filter display between the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon and the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/add-filter-icon.png" class="inline-icon" alt="add filter icon"/>{:/} (circle-plus) **Add filter** control. + + +## Navigating the filter tool + +![Filter tool]({{site.url}}{{site.baseurl}}/images/dashboards/filter-tool-callouts.png){: width="75%" } + +The following components make up the filter tool. + +- The {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon (A) provides a drop-down menu of filter options. +- The filter list (B) shows the currently defined filters. +- {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/add-filter-icon.png" class="inline-icon" alt="add filter icon"/>{:/} (circle-plus) **Add filter** (C) provides a popover menu for adding data filters. + +## Adding a filter + +To add a filter using the **Add filter** tool, follow these steps: + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/add-filter-icon.png" class="inline-icon" alt="add filter icon"/>{:/} (add) **Add filter**. + +1. In the **Edit filter** popover, choose a data field. + +![Edit filter popover]({{site.url}}{{site.baseurl}}/images/dashboards/edit-filter-popover-filled.png){: width="79%" } + +1. In the **Operator** field, choose an operator. + + The **Operator** dropdown choices are determined by the chosen data field's type. + {: .note} + + The Value field appears if needed. + +1. If required, in the **Value** field, enter or select a value. + + The **Value** entry mode and choices are determined by the chosen operator and data field type. + {: .note} + +1. (Optional) Choose **Create custom label?**. + + The custom label replaces the default label composed of the data field name and operator. + +1. Select **Save**. + +## Editing a filter + +To change an existing filter, follow these steps: + +1. Select the filter in the filter list. + +1. In the filter dropdown, select **Edit filter>**. + +1. In the **Edit filter** popover, change the **Field**, **Operator**, or **Values** as needed. + +1. (Optional) Add or change the **Custom label**. + +1. Select **Save**. + + +## Removing a filter + +To remove a filter, choose the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>{:/} (cross) icon to the right of the filter name. + +## Disabling a filter + +You can disable a filter temporarily without removing it from the filter list. To disable a filter, follow these steps: + +1. Select the filter in the filter list. + +1. In the filter dropdown, select **Temporarily disable**. + + Disabled filter names are shown in ~~strikethrough~~ text. + {: .note} + +## Re-enabling a filter + +To enable a disabled filter, follow these steps: + +1. Select a ~~disabled~~ filter in the filter list. + +1. In the filter dropdown, select **Re-enable**. + + +## Pinning a filter + +You can pin a filter so that it applies to all the applications in OpenSearch Dashboards (Discover, Dashboards, and Visualize). To pin a filter, follow these steps: + +1. Select the filter in the filter list. + +1. In the filter dropdown, select **Pin across all apps**. + + +## Unpinning a filter + +To unpin a filter that has been pinned to all apps, follow these steps: + +1. Select the filter in the filter list. + +1. In the filter dropdown, select **Unpin**. + + +## Modifying all filters as a group + +You can use the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) **Filters** dropdown list to change all the filters at once in several ways. + +Modifications made with the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) **Filters** dropdown list apply only to the filters in the filter list, not to the query in the **Search** bar or to the time filter. +{: .note} + +### Enabling or disabling all the filters + +To enable or disable all filters, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon. + +1. In the **Filters** dropdown list, select **Enable all** or **Disable all**. + + +### Inverting which filters are enabled + +To exclude all included filters and include all excluded filters, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon. + +1. In the **Filters** dropdown list, select **Invert enabled/disabled**. + + +### Inverting the sense of inclusion for all filters + +To negate all filter expressions so that all included documents are excluded and all excluded documents are included, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon. + +1. In the **Filters** dropdown list, select **Invert inclusion**. + + Exclusion filters have **NOT** appended to their title, as shown following. Inverting inclusion a second time removes the **NOT** modifier. + + ![Exclusion filter]({{site.url}}{{site.baseurl}}/images/dashboards/excluded-filter.png){: width="36%" } + + Disabled filters are inverted, but remain disabled. + {: .note} + +### Pinning or unpinning all filters + +To pin or unpin all filters in all OpenSearch Dashboards applications (Discover, Dashboards, and Visualize), follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon. + +1. In the **Filters** dropdown list, select **Pin all** or **Unpin all**. + + +### Removing all filters + +To remove all filters from the filter list, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/funnel-icon.png" class="inline-icon" alt="filter menu icon"/>{:/} (funnel) icon. + +1. In the **Filters** dropdown list, select **Remove all**. diff --git a/_dashboards/discover/index-discover.md b/_dashboards/discover/index-discover.md index 4e32c4f1..fa1ce01f 100644 --- a/_dashboards/discover/index-discover.md +++ b/_dashboards/discover/index-discover.md @@ -1,113 +1,222 @@ --- layout: default -title: Analyzing data -nav_order: 20 +title: Exploring data with Discover +parent: Exploring data +nav_order: 10 has_children: true -redirect_from: - - /dashboards/discover/index-discover/ +has_toc: false --- -# Analyzing data +# Exploring data with Discover -To analyze your data in OpenSearch and visualize key metrics, you can use the **Discover** application in OpenSearch Dashboards. An example of data analysis in **Discover** is shown in the following image. +You can use the **Discover** application in **OpenSearch Dashboards** to explore and visualize your data in OpenSearch. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/discover.png" alt="A Discover default page" width="700"> +If you're new to the Discover application, see [Explore the Discover application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-discover/) for a hands-on introduction using sample data. +{: .tip} -## Getting started +## Prerequisites -In this tutorial, you'll learn about using **Discover** to: +The examples on this page use the [**Sample flight data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). -- Add data. -- Interpret and visualize data. -- Share data findings. -- Set alerts. +If you've installed a local OpenSearch Dashboards instance, add the sample data by following these steps: -Before getting started, make sure you: +1. On the OpenSearch Dashboards home page, select **Add sample data**. +2. In the **Sample flight data** panel, select **Add data**. -- Install [OpenSearch Dashboards](https://opensearch.org/downloads.html). -- Add sample data or import your own data into OpenSearch. Go to the [OpenSearch Dashboards quickstart guide]({{site.url}}{{site.baseurl}}/dashboards/quickstart/) to learn about adding sample datasets. Go to [Managing indexes]({{site.url}}{{site.baseurl}}/im-plugin/index/) to learn about importing your own data. -- Have a foundational understanding of [OpenSearch documents and indexes]({{site.url}}{{site.baseurl}}/im-plugin/index/). - -## Defining the search +For more information, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). -To define a search, follow these steps: +## Navigating the Discover application UI -1. On the OpenSearch Dashboards navigation menu, select **Discover**. -2. Choose the data you want to work with. In this case, choose `opensearch_dashboards_sample_data_flights` from the upper-left dropdown menu. -3. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-oui.png" class="inline-icon" alt="calendar icon"/>{:/} icon to change the time range of your search and then select **Refresh**. +The following image shows the main components of the **Discover** application. -The resulting view is shown in the following image. +![Discover app default page]({{site.url}}{{site.baseurl}}/images/dashboards/discover-app-panel-callouts.png) -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/define-search.png" alt="Discover interface showing search of flight sample data for Last 7 days" width="700"> +- The _application menu_ (A) provides options for creating and saving Discover filters settings. +- The _field select_ tool (B) determines which fields display in the **Discover** application panel. See [Using the field select tool]({{site.url}}{{site.baseurl}}/dashboards/discover/field-select/). +- The _time filter_ (C) provides a graphical interface for selecting data values and ranges. See [Using the time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/). +- The _search_ bar (D) enables selection of data using a query language search. See [Using the search bar]({{site.url}}{{site.baseurl}}/dashboards/discover/search-bar/). +- The _filter_ tool (E) contains frequently used commands and shortcuts. See [Using the filter tool]({{site.url}}{{site.baseurl}}/dashboards/discover/filter-tool/). +- The **Discover** _application panel_ displays the following elements: + - The _date range display_ (F) specifies and selects a date-time range and determines the scale of the timeline visualization. + - The _timestamp histogram_ (G) displays the count of documents per time interval. + - The **Results** table (H) displays summaries of the selected documents. You can expand each document and view it in tabular or JSON form. -## Analyzing document tables + If there is no data selected, the application panel displays a **</> No Results** message. This often happens, especially with the OpenSearch Dashboards sample data, because all data falls outside the time filter interval. + {: .note} -In OpenSearch, a document table stores unstructured data. In a document table, each row represents a single document, and each column contains document attributes. + The time filter interval defaults to **Last 15 minutes**. To change the time filter interval, [Expand the time range]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/#selecting-a-time-range) to include data. + {: .note} -To examine document attributes, follow these steps: +## Viewing the Results table -1. From the data table's left column, choose the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/inspect-icon.png" class="inline-icon" alt="inspect icon"/>{:/} icon to open the **Document Details** window. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/minimize-icon.png" class="inline-icon" alt="minimize icon"/>{:/} icon to close the **Document Details** window. -2. Examine the metadata. You can switch between the **Table** and **JSON** tabs to view the data in your preferred format. -3. Select **View surrounding documents** to view data for other log entries either preceding or following your current document or select **View single document** to view a particular log entry. +The **Results** table displays the selected data. Each row represents a single document, and each column contains document attributes. -The resulting view is shown in the following image. +By default, the table shows all attributes for all selected documents. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/doc-details.png" alt="Document attributes" width="700"> +To display documents in the **Discover** application, follow these steps: -To add or delete fields in a document table, follow these steps: +1. In the navigation panel, select **OpenSearch Dashboards** > **Discover**. -1. View the data fields listed under **Available fields** and select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/plus-icon.png" class="inline-icon" alt="plus icon"/>{:/} icon to add the desired fields to the document table. The field will be automatically added to both **Selected fields** and the document table. For this example, choose the fields `Carrier`, `AvgTicketPrice`, and `Dest`. -2. Select **Sort fields** > **Pick fields to sort by**. Drag and drop the chosen fields in the desired sort order. +1. Choose the data you want to work with from the **Index patterns** dropdown in the field select tool. See [Selecting an index pattern]({{site.url}}{{site.baseurl}}/dashboards/discover/field-select/#selecting-an-index-pattern). -The resulting view is shown in the following image. + For the following example, choose `opensearch_dashboards_sample_data_flights`. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/add-data-fields.png" alt="Adding and deleting data fields" width="700"> +1. Use the time filter to select the time interval of interest. See [Selecting a time range]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/#selecting-a-time-range). -## Searching data + For the example, select **Last 12 months**. -You can use the search toolbar to enter a [DQL]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/) or [query string]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) query. The search toolbar is best for basic queries; for full query and filter capability, use [query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/index/) in the [Dev Tools console]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index-dev/). + The following image shows the resulting display in the Discover app. -For more information, see [Discover and Dashboard search toolbar]({{site.url}}{{site.baseurl}}/dashboards/index/#discover-and-dashboard-search-bar). + ![Discover interface showing search of flight sample data for last 90 days]({{site.url}}{{site.baseurl}}/images/dashboards/discover-display-flight-data-3-mo.png){: width="95%" } -## Filtering data +1. Drag-select the narrow band of data from the timestamp histogram as shown in the following image. -Filters allow you to narrow the results of a query by specifying certain criteria. You can filter by field, value, or range. The **Add filter** pop-up suggests the available fields and operators. + ![Discover interface showing drag-select]({{site.url}}{{site.baseurl}}/images/dashboards/discover-drag-select.png){: width="95%" } -To filter your data, follow these steps: + The data adjusts to span the width of the data display, and the scale adjusts automatically. -1. Under the DQL search bar, choose **Add filter**. -2. Select the desired options from the **Field**, **Operator**, and **Value** dropdown lists. For example, select `Cancelled`, `is`, and `true`. -3. Choose **Save**. -4. To remove a filter, choose the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>{:/} icon to the right of the filter name. + Selecting a date range interactively results in an absolute time interval. + {: .note} -The resulting view is shown in the following image. +1. Select **Auto** from the date range display drop-down. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/discover-filter.png" alt="Visualize data findings interface" width="700"/> + The resulting view should look like the following image. -## Saving a search + ![Discover interface showing flight sample data scaled to display width]({{site.url}}{{site.baseurl}}/images/dashboards/discover-display-flight-data-adjusted.png){: width="95%" } -To save your search, including the query text, filters, and current data view, follow these steps: -1. Select **Save** on the upper-right toolbar. -2. Add a title, and then choose **Save**. -3. Select **Open** on the upper-right toolbar to access your saved searches. +## Filtering documents -## Visualizing data findings +You can filter documents out of the selected index pattern in several ways: -To visualize your data findings, follow these steps: +- By further refining the time interval +- By entering a query language query +- By selecting attribute values in a menu-based filter tool -1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/inspect-icon.png" class="inline-icon" alt="inspect icon"/>{:/} icon to the right of the field you want to visualize. +You can save any combination of these filters and re-apply them later to the same or a different index pattern. See [Saving a query]({{site.url}}{{site.baseurl}}/dashboards/discover/search-bar/#saving-a-query). - The resulting view is shown in the following image. + +### Refining the time interval + +The **Discover** application displays only the documents that are included in the time filter's time interval. The time interval can be _relative_ (a fixed window of time relative to _now_), or _absolute_ (between two fixed times). + +Some tools for changing the time interval are demonstrated in the previous example. To learn about others, see [Using the time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/). + + +### Entering a query + +You can filter documents by entering a query string in the search bar using one of two query languages. + +- [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/) is the default query language in the search bar and is available only in **Dashboards**. +- [Query string query language (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) is based on the [Apache Lucene](https://lucene.apache.org/core/{{site.lucene_version}}/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description) query language. + +To filter documents using the search bar, see [Using the search bar]({{site.url}}{{site.baseurl}}/dashboards/discover/search-bar/). + +For example, using the _flights_ sample data, enter the following DQL search: + +``` +Carrier: "OpenSearch-Air" +``` + +### Selecting attribute values + +You can use the filter tool to add any number of discrete filters based on attribute values. + +You can turn filters on or off individually or all at once; reverse the inclusion-exclusion status of any filter; and pin the filters as a group so that they apply to the **Dashboards** and **Visualization** applications. + +To use the filter tool, see [Using the filter tool]({{site.url}}{{site.baseurl}}/dashboards/discover/filter-tool/). + +For example, using the _flights_ sample data, use the filter tool to enter the following filter: + +![A data filter]({{site.url}}{{site.baseurl}}/images/dashboards/filter-cancelled-true.png){: width="100" } + + +## Choosing data fields + +By default, the **Discover** application displays all the fields in a document. You can choose to display one, more, or all fields in the **Results** table. + +To choose the fields to display in the **Results** table, see [Using the field select tool]({{site.url}}{{site.baseurl}}/dashboards/discover/field-select/). + +For example, select **Dest**, **FlightDelayMin**, and **FlightDelayType** in the field select tool. The **Results** table now displays only those fields (in addition to the **Time**). + + +## Examining a document + +To expand a single document and see a detailed view in the **Results** table, follow these steps: + +1. From a row in the **Results** table's left column, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/arrow-right-icon.png" class="inline-icon" alt="expand icon"/>{:/} (expand) icon. The expanded document is displayed below the row in the **Expanded document** area. + +1. (Optional) To display the document in JSON format, select the **JSON** tab. + +1. To return to the (default) tabular view, select the **Table** tab. + +1. (Optional) To view documents preceding or following the current document, select **View surrounding documents**. + + The document, along with the five documents before and after by default, is displayed in a new browser tab or window. + + The number of surrounding documents is fewer if there are fewer documents immediately before or after. + {: .note} + +1. (Optional) To view the expanded document in isolation, select **View single document**. + + The expanded document is displayed in a new browser tab or window. + +1. To collapse the expanded document, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/arrow-down-icon.png" class="inline-icon" alt="collapse icon"/>{:/} (down arrow) icon. + + +## Visualizing data fields + +To visualize a data field, follow these steps: + +1. In the field select list, mouse over the field you want to visualize. + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/inspect-icon.png" class="inline-icon" alt="inspect icon"/>{:/} (inspect) icon to the right of the field name. + + The **Top 5 views popover** displays as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/visualize-discover.png" alt="Visualize data findings interface" width="700"/> + ![top 5 values popover]({{site.url}}{{site.baseurl}}/images/dashboards/top-5-values.png){: width="51%" } -2. Select the **Visualize** button. When the **Visualize** application is launched, a visualization appears. +1. From the **Top 5 values** popover, select the **Visualize** button. The display changes to the **Visualize** application, showing a default visualization of the selected field. - The resulting view is shown in the following image. + See [Building data visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/) to learn how to edit the visualization display. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/visualization-flight.png" alt="Data visualization of flight sample data field destination" width="700"/> + +## Exporting data + +You can export data from the **Results** table to a CSV file or copy a JSON object representing a single document. To export the same data on a schedule or from a script instead of from the interface, save your query as a saved search and generate a CSV report from it. For more information, see [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/). + +### Downloading data to a CSV file + +To download a CSV-formatted file of data from the **Results** table: + +1. Filter the data to the documents you want to export as described in [Filtering documents](#filtering-documents). + +1. Choose the data fields you want to export as described in [Choosing data fields](#choosing-data-fields). + +1. Select **Download as CSV**. + +1. In the **DOWNLOAD AS CSV** popover, choose whether you want to download only the documents **Visible** on the page, or the **Max available** (all selected documents, limited to 10,000 documents). + +1. Select the **Download CSV** button. + + The data is written to a CSV file at the file system's default location. + + If the selected fields include objects or arrays, the CSV documents will download as JSON objects. To download as discrete CSV values, select only single-value fields. + {: .tip} + +### Copying a JSON representation of a document + +To copy a JSON representation of a document, follow these steps: + +1. Select the individual document in the **Results** table. See [Examining a document](#examining-a-document). + +1. Select the JSON tab to view the document in JSON form. + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/copy-icon.png" class="inline-icon" alt="copy icon"/>{:/} (copy) icon in the upper right of the JSON display area. ## Setting alerts -Set alerts to notify you when your data exceeds your specified thresholds. Go to [Alerting dashboards and visualizations]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/dashboards-alerting/) to learn about creating and managing alerts. +You can set thresholds for data values and then set alerts to notify you when your data exceeds your thresholds. + +To learn about creating and managing alerts, see [Alerting dashboards and visualizations]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/dashboards-alerting/). + diff --git a/_dashboards/discover/index.md b/_dashboards/discover/index.md new file mode 100644 index 00000000..1a00a154 --- /dev/null +++ b/_dashboards/discover/index.md @@ -0,0 +1,24 @@ +--- +layout: default +title: Exploring data +nav_order: 40 +has_children: true +redirect_from: + - /dashboards/discover/ +--- + +# Exploring data + +OpenSearch Dashboards provides several tools for exploring data, enabling everything from basic one-time queries to savable API-equivalent queries. You can do the following: + +- Explore data in the **Discover** or **Dashboards** search bar using Dashboards Query Language (DQL), a Dashboards-specific language for basic queries, or Query String Query Language, based on Apache Lucene. +- Use the **Query Workbench** tool to execute queries in SQL or Piped Processing Language (PPL). +- Use the **Dev Tools** console to run queries in Query Domain-specific Language (Query DSL). With Query DSL you can run any query as if from the API. +- Display and save visuals of queried data in the **Discover** and **Visualize** tools. + + +To learn more about | Go to | Query languages used +:------------------- | :----- | :----- +Exploring data quickly | [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) | [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/dql/)<br/>or<br/>[Query String Query Language (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) +Querying data using the API |[Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index/) | [Query Domain-specific Language (Query DSL)]({{site.url}}{{site.baseurl}}/query-dsl/) +Querying data | [Using Query Workbench]({{site.url}}{{site.baseurl}}/dashboards/query-workbench/) | [Structured Query Language (SQL)]({{site.url}}{{site.baseurl}}/sql-and-ppl/sql/)<br/>or<br/>[Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/) \ No newline at end of file diff --git a/_dashboards/discover/search-bar.md b/_dashboards/discover/search-bar.md new file mode 100644 index 00000000..74021517 --- /dev/null +++ b/_dashboards/discover/search-bar.md @@ -0,0 +1,150 @@ +--- +layout: default +title: Search bar +parent: Exploring data with Discover +grand_parent: Exploring data +nav_order: 20 +redirect_from: + - /dashboards/#discover-and-dashboard-search-bar +--- + +# Using the search bar + +The same search bar is at the top of the [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/), [Dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/), and [Visualize]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/) applications. Use it to filter the data displayed in those applications. + +In the search bar, you do text-based searches using either of two languages: + +- [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/): A basic query language with nested field queries. + +- [Query string query language (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/): A query language based on the [Apache Lucene](https://lucene.apache.org/core/{{site.lucene_version}}/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description) query language. + +The terms _Query string query language_ and _Lucene_ are used interchangeably in the documentation and UI. +{: .note} + +Query string query language and DQL support different features. For example, DQL has nested expressions; Lucene has fuzzy searches and regular expressions. For a full comparison, see [DQL and query string query quick reference]({{site.url}}{{site.baseurl}}/dashboards/dql/#dql-and-query-string-query-quick-reference). + + +## Navigating the search bar + + ![Search bar interface]({{site.url}}{{site.baseurl}}/images/dashboards/search-bar-callouts.png) + +The following components make up the search bar. + +- The {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/save-icon.png" class="inline-icon" alt="save icon"/>{:/} (save) icon (A) saves the current query. +- The **Search** box (B) accepts a query in the currently selected query language. +- The query language selector (C) opens the **Syntax options** popover for selecting the query language. + +## Changing the query language + +The current query language, OpenSearch Dashboards Query Language (DQL) or Query String Query Language (Lucene), is displayed at the right side of the **Search** box. + +To switch between DQL and query string query language, follow these steps: + +1. Choose the query language selector (displaying the current query language). + +1. In the **Syntax options** dialog, toggle **OpenSearch Dashboards Query Language** on or off. + + If **OpenSearch Dashboard Query Language** (DQL) is turned **off**, the query language is set to OpenSearch Dashboards Query Language, and the query language selector displays **Lucene**. + {: .note} + + ![Using query string syntax in OpenSearch Dashboards Discover]({{site.url}}{{site.baseurl}}/images/dashboards/discover-lucene-syntax.png){: width="97%" } + + +## Filtering based on a query + +To filter using the **Search** box, follow these steps: + +1. Enter a filter criterion in the **Search** box. For example, using DQL against the OpenSearch e-commerce sample data, enter `category: "Men's Clothing"`. + + For information about querying in DQL, see [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/). + + For information about querying in Lucene, see [Query string query language (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). + +1. Select **Refresh**. + + ![Refresh button]({{site.url}}{{site.baseurl}}/images/dashboards/refresh-button.png){: width="100" } + + The **Results** table is updated to reflect filtering by the query. + +## Editing a filter query + +To change the query, follow these steps: + +1. Edit the filter criterion in the **Search** box. For example, to change the DQL query in the previous example, change the query to `sales_by_category is "Women's Clothing"`. + +1. Select **Refresh**. + + ![Refresh button]({{site.url}}{{site.baseurl}}/images/dashboards/refresh-button.png){: width="100" } + + The **Results** table is updated to reflect the altered query. + +## Saving a query + +Use this procedure to save any combination of: + +- The DQL or Lucene query. +- The filters. +- The time filter. + +To save a query, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/save-icon.png" class="inline-icon" alt="save icon"/>{:/} (save) icon. + +There does not have to be a query in the **Search** box. You can use this procedure to save the filters and/or the time filter without saving a query. +{: .note} + +1. From the **Save** popover, select **Save current query** or **Save as new**. + +1. In the **Save query** dialog, enter a **Name** for the query. + +1. (Optional) In the **Description** box, enter a description of the query. + +1. (Optional) Activate the **Include filters** toggle to also save the filters in the [filter list]({{site.url}}{{site.baseurl}}/dashboards/discover/filter-tool/). + +1. (Optional) Activate the **Include time filter** toggle to also save the currently active [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/). + +1. Select **Save**. + + +## Loading a saved search + +To load a saved search, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/save-icon.png" class="inline-icon" alt="save icon"/>{:/} (save) icon. + +1. Select the search you want to load. + + The filter loads and the data displayed in the **Discover** application is updated. + + +## Editing a query + +To change an existing query, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/save-icon.png" class="inline-icon" alt="save icon"/>{:/} (save) icon. + +1. Select the query you want to edit. + +1. Filter the data using the search query, filters, and time filter you want to update a query to. + +1. Again select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/save-icon.png" class="inline-icon" alt="save icon"/>{:/} (save) icon. The current saved query is checked in the list. + +1. Select **Save changes**. + +1. (Optional) In the **Save query** dialog, enter or change the **Description**. + +1. Select **Save**. + + +## Deleting a query + +To delete a query, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/save-icon.png" class="inline-icon" alt="save icon"/>{:/} (save) icon. + +1. Hover over the query you want to delete. + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/trash-icon.png" class="inline-icon" alt="trash icon"/>{:/} (trash) icon. + +1. In the delete confirmation dialog, select **Delete**. + diff --git a/_dashboards/discover/time-filter.md b/_dashboards/discover/time-filter.md index 288138d0..ef97b83c 100644 --- a/_dashboards/discover/time-filter.md +++ b/_dashboards/discover/time-filter.md @@ -1,36 +1,186 @@ --- layout: default title: Time filter -parent: Analyzing data -nav_order: 20 +parent: Exploring data with Discover +grand_parent: Exploring data +nav_order: 10 redirect_from: - /dashboards/get-started/time-filter/ - - /dashboards/discover/time-filter/ --- -# Time filter +# Using the time filter -The time filter is used to set the time range, including minutes, hours, days, weeks, months, or years, that is displayed on your dashboard. +The time filter is located at the top of the **Dashboard**, **Discover**, and **Visualize** applications. -The default time range is **Last 15 minutes**. You can change the time range at the dashboard level or under **Dashboards Management** > **Advanced Settings** > **Time filter defaults**. +Use the time filter to select the time interval for the data that is displayed in the applications. The filter supports intervals in seconds, minutes, hours, days, weeks, months, or years. + +This page uses the terms _time range_ and _time interval_ interchangeably to refer generically to a filter interval, no matter what the magnitude, from seconds to years. _Time_ or _time value_ refers to the endpoint of a relative time interval in seconds, minutes, or hours, as distinct from date values in days, weeks, months, or years. {: .note} -To change the time range at the dashboard level, follow these steps: +You can select a _relative_ time interval (a fixed window of time relative to _now_), or an _absolute_ time interval (between two fixed times). A _refresh interval_ determines how often a relative time interval refreshes. The refresh interval is configurable, and defaults to one second (1 s). Absolute time intervals are unaffected by the refresh interval. -1. From an OpenSearch Dashboards application (Discover, Dashboards, or Visualize), select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>{:/} icon on the right of the search bar. -2. Select one of the time filter options, as shown in the following image: - - **Quick select:** Choose a time based on the last or next number of seconds, minutes, hours, days, or another time unit. - - **Commonly used:** Choose a common time range like **Today**, **Last 7 days**, or **Last 30 days**. - - **Recently used date ranges:** Select a previously used time range. - - **Refresh every:** Set an automatic refresh period. +While most applications (data logs, for example), deal with past dates and times, relative and absolute time intervals can encompass both past and future dates and times. For example, a relative time interval could be set to span _now_ to 24 hours in the future. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/time-range.png" alt="Time range interface" width="400"/> +The default time range is a relative interval of **Last 15 minutes**. You can change the default at [**Dashboards Management** > **Advanced Settings** > **Time filter defaults**]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/#general-settings), or select a time range at the application level as described in [Selecting a time range](#selecting-a-time-range). +{: .note} -3. Choose **Show dates** to set start and end times, and then select anywhere inside the toolbar to access the time filter pop-up window, as shown in the following image. +## Time field used by the time filter - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/time-filter-popup.png" alt="Time filter pop-up window" width="400"/> +The time filter applies to one date field: the time field that you select when you [create the index pattern]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/#step-2-configure-the-settings), for example, `@timestamp`. If your documents contain several date fields, the time filter uses only the time field and ignores the other date fields. On the index pattern's page in **Dashboards Management** > **Index patterns**, the time field is marked with a clock icon. -4. Select **Absolute**, **Relative**, or **Now** and specify ranges. -5. Choose **Update** to apply changes, as shown in the following image. +Visualizations and dashboard panels use the time field of the index pattern that they are built on. A dashboard can contain panels built on different index patterns, and each panel applies the time range to its own index pattern's time field. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/start-end-time.png" alt="Start and end times interface" width="400"/> +If you create an index pattern without a time field (by selecting **I don't want to use the time filter**), the data is not filtered by time. **Discover** doesn't display the time filter for that index pattern, and **Visualize** displays only the refresh interval control. On a dashboard, panels that use such an index pattern ignore the time range. + +You can't change the time field of an existing index pattern. To filter by a different date field, or to add time filtering to an index pattern created without a time field, create a new index pattern and select the field in the **Time field** list. + +## Navigating the time filter + +![Time filter interface]({{site.url}}{{site.baseurl}}/images/dashboards/time-filter-callouts.png) + +The following components make up the time filter. + +- The _shortcut selector_ (A) opens a dialog from which you can select a relative time interval or a recently used time interval, and set the time refresh interval. +- The _time range display_ (B) shows the selected time range in absolute (for example, _Mar 22, 2024 @12:00:01.000 → now_) or relative (for example, _Last 2 years_) terms. +- The **Show dates** link (C) forces the _time range display_ to show the time interval in _from → to_ format. +- The **Refresh** button (D) updates the data displayed in the application based on new filter or query values. **Refresh** updates query and data filters as well as the time filter. + + +## Selecting a time range + +You can select a [relative](#selecting-a-relative-time-interval) or [absolute](#selecting-an-absolute-time-interval) interval as the time range at the application level. Or, you can select a relative or absolute interval using the [shortcut selector](#using-the-time-interval-shortcuts). + + +### Selecting an absolute time interval + +To select an absolute time interval, follow these steps: + +1. If necessary to display the interval in **from → to** form, select **Show dates**. + +1. Select the displayed start time. + +1. In the time selection popover, choose the **Absolute** tab as shown in the following image. + + ![Absolute time filter]({{site.url}}{{site.baseurl}}/images/dashboards/absolute-time-filter.png){: width="56%" } + +1. Use the calendar and time scroll tools to choose a start time, or edit the start time in the **Start date** text box. + +1. Select the displayed end time. + +1. In the time selection popover, choose the **Absolute** tab. + +1. Use the calendar and time scroll tools to choose an end date and time, or edit the end date and time in the **End date** text box. + +1. Choose the **Update** button to apply changes. + + The data tables and visualizations displayed in the application automatically updates to reflect the new time interval filter. + + +### Selecting a relative time interval + +To select a relative time interval, follow these steps: + +1. If necessary to display the interval in **from → to** form, select **Show dates**. + +1. Select the displayed start time. + +1. In the time selection popover, choose the **Relative** tab as shown in the following image. + + ![Relative time filter]({{site.url}}{{site.baseurl}}/images/dashboards/relative-time-filter.png){: width="56%" } + +1. In the number combo box, select or enter the interval quantity. + +1. In the interval dropdown, select the past (**ago**) or future (**from now**) start of the relative interval. + + You can choose **Now** as the start time. In this case, the relative end time must be in the future (**from now**). + {: .note} + +1. (Optional) Activate the **Round to** toggle. This rounds the start time to the beginning of the specified interval rather than calculating it as an offset from the exact time on the system clock. + +1. Select the displayed end time. + +1. Do one of the following: + + Many, perhaps most, applications require a relative interval ending at the present. In this case, do the immediately following instructions. + + 1. Select the **Now** tab. + + 1. In the **Now** popover, select **Set end date and time to now**. + + If your application requires a relative end time that is not **now**, do the following: + + 1. In the time selection popover, choose the **Relative** tab. + + 1. In the number combo box, select or enter the interval quantity. + + 1. In the interval dropdown, select the past (**ago**) or future (**from now**) start of the relative interval. + + The end time must be after the start time. The interval displays in red if the interval is illegal. + {: .note} + + 1. (Optional) Activate the **Round to ...** toggle. This rounds the start time to the beginning of the specified interval rather than calculating it from the exact time on the system clock. + +1. Choose the **Update** button to apply changes. + + The application updates the data in data tables and visualizations to reflect the new time interval filter. + + +### Using the time interval shortcuts + +To select a time interval from common or previous interval values, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>{:/} (calendar) or {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/clock-icon.png" class="inline-icon" alt="clock icon"/>{:/} (clock) icon on the right of the search bar. + +1. From the shortcut popover, select one of the time filter options, as shown in the following image. + + ![Time range interface]({{site.url}}{{site.baseurl}}/images/dashboards/time-range.png){: width="59%" } + + - **Quick select**: Choose an interval spanning _now_ to a past (**Last**) or future (**Next**) time. + + 1. In the **Last/Next** dropdown, select **Last** (past) or **Next** (future). + + 1. In the number combo box, select or enter the interval quantity. + + 1. In the interval dropdown, select the units for the relative interval. + + 1. Choose **Apply**. + + - **Commonly used**: Choose a common time range, for example **Today**, **Last 7 days**, or **Last 30 days**. + + - **Recently used date ranges**: Select a previously used time range. The time range can be relative or absolute. + +- (Optional) Change the refresh interval: + + 1. In the **Refresh every** panel, select or enter the interval quantity in the number combo box. + + 1. In the interval dropdown, select the interval unit (**seconds**, **minutes**, or **hours**). + + 1. Select **Refresh**. + +## Starting and stopping data refresh + +To start or stop the time interval refresh, follow these steps: + +1. From an OpenSearch Dashboards application (**Discover**, **Dashboards**, or **Visualize**), select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>{:/} (calendar) or {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/clock-icon.png" class="inline-icon" alt="clock icon"/>{:/} (clock) icon on the right of the search bar. + +1. In the **Refresh every** panel, select **Start** or **Stop**. + + - If the time interval is relative: + + - Starting data refresh causes the data selection to be updated approximately every _refresh interval_. + - Stopping data refresh "freezes" the selection interval until data refresh is restarted. + + - If the time interval is absolute, then starting or stopping data refresh has no effect on the data selection. + +1. Select **Refresh**. + + The shortcut selector shows the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>{:/} (calendar) icon if the time interval refresh is stopped, or the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/clock-icon.png" class="inline-icon" alt="clock icon"/>{:/} (clock) icon if the time interval refresh is running. + {: .note} + +## Configuring the time zone + +By default, the time filter uses the time zone detected by your browser. To change the time zone, go to **Dashboards Management** > **Advanced settings** and update the **Timezone for date formatting** (**dateFormat:tz**) setting. For more information, see [Advanced settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/). + +## Related documentation + +- [Advanced settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/) \ No newline at end of file diff --git a/_dashboards/dql.md b/_dashboards/dql.md index 7ddcbc6d..4494163c 100644 --- a/_dashboards/dql.md +++ b/_dashboards/dql.md @@ -1,20 +1,28 @@ --- layout: default title: Dashboards Query Language (DQL) -nav_order: 130 +nav_order: 50 redirect_from: - - /dashboards/dql/ - /dashboards/discover/dql/ --- +<!-- vale off --> # Dashboards Query Language (DQL) +<!-- vale on --> -Dashboards Query Language (DQL) is a simple text-based query language used to filter data in OpenSearch Dashboards. For example, to display your site visitor data for a host in the United States, you would enter `geo.dest:US` in the search field, as shown in the following image. +Dashboards Query Language (DQL) is a simple text-based language for filtering documents in OpenSearch Dashboards. DQL is available in the Discover and Dashboards applications. Each DQL query compares field values with the values that you specify and returns the matching documents. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/dql-interface.png" alt="Search term using DQL toolbar in Dashboard" width="500"> +DQL and [query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) (Lucene) language are the two search bar language options in Discover and Dashboards. This page provides a reference for the DQL syntax. For the Lucene syntax, see [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). For a syntax comparison, see the [Command quick reference](#dql-and-query-string-query-quick-reference). -DQL and query string query (Lucene) language are the two search bar language options in Discover and Dashboards. To compare these language options, see [Discover and Dashboard search bar]({{site.url}}{{site.baseurl}}/dashboards/index/#discover-and-dashboard-search-bar). -{: .tip} +By default, OpenSearch Dashboards uses DQL syntax. To switch to query string query (Lucene), select the **DQL** button next to the search box and then toggle the **On** switch, as shown in the following image. + +![Search term using DQL toolbar in Dashboard]({{site.url}}{{site.baseurl}}/images/dashboards/dql-interface.png) + +The syntax changes to **Lucene**. To switch back to DQL, select the **Lucene** button and toggle the **Off** switch. + +## Queries on analyzed text + +When running queries, understanding whether your fields are analyzed ([`text`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) type) or non-analyzed ([`keyword`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/keyword/) type) is crucial because it significantly impacts search behavior. In analyzed fields, text undergoes tokenization and filtering, while non-analyzed fields store exact values. For simple field queries like `wind`, searches against analyzed fields match documents containing `wind` regardless of case, while the same query on keyword fields requires exact matching of the full string. For more information about analyzed fields, see [Text analysis]({{site.url}}{{site.baseurl}}/analyzers/). ## Setup @@ -81,7 +89,8 @@ PUT /testindex/_doc/3 "title": "Chicago: the historical windy city", "media_type": "article", "date": "2023-07-29", - "page_views": 300 + "page_views": 300, + "author": "Lena Ruiz-Ortega" } ``` {% include copy-curl.html %} @@ -91,7 +100,8 @@ PUT /testindex/_doc/4 { "article title": "Wind turbines", "media_type": "article", - "format": "2*3" + "format": "2*3", + "author": "" } ``` {% include copy-curl.html %} @@ -116,6 +126,39 @@ The [Object fields](#object-fields) and [Nested fields](#nested-fields) sections {: .note} </details> +## DQL and query string query quick reference + +The following table provides a quick reference for both query language commands. + +| Feature | DQL | Query string query (Lucene)| +|:---|:---|:---| +| Basic term search | `wind` | `wind` | +| Multiple terms | `wind gone` (finds documents containing `wind` or `gone`) | `wind gone` (finds documents containing `wind` or `gone`) | +| Exact phrase search | `"wind rises"` | `"wind rises"` | +| Field-specific search | `title: wind` | `title:wind` | +| Existence of a field | `description:*` | `_exists_:description` | +| Missing field | `not description:*` | `NOT _exists_:description` | +| Empty string | `author.keyword: ""` | `author.keyword:""` | +| Term containing a hyphen | `author: "Ruiz-Ortega"` | `author:"Ruiz-Ortega"` | +| Multiple terms in field | `title: (wind OR rises)` <br><br> | `title:(wind OR rises)` | +| Field containing spaces | `article*title: wind` | `article\ title:wind` | +| Escaping special characters | `format: 2\*3` | `format:2\*3` | +| Multiple field search | `title: wind OR description: film` | `title:wind OR description:film` | +| Nested field search | See [Nested fields](#nested-fields) | Not supported | +| Numeric range | `page_views >= 100 and page_views <= 300` <br><br> `not page_views: 100` (results include documents that don't contain a `page_views` field) <br><br> See [Ranges](#ranges)| `page_views:[100 TO 300]` <br><br> `page_views:(>=100 AND <=300)` <br><br> `page_views:(+>=100 +<=300)` <br><br> `page_views:[100 TO *]` <br><br> `page_views:>=100` <br><br> `NOT page_views:100` (results include documents that don't contain a `page_views` field) <br><br> See [Ranges]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/#ranges)| +| Date range | `date >= "1939-01-01" and date <= "2013-12-31"` <br><br> `not date: "1939-09-08"` | `date:[1939-01-01 TO 2013-12-31]` <br><br> `NOT date:1939-09-08` <br><br> Supports all numeric range syntax constructs| +| Exclusive range | Not supported | `page_views: {100 TO 300}` (returns documents whose `page_views` are between `100` and `300`, excluding `100` and `300`) | +| Boolean `AND` | `media_type: film AND page_views: 100` <br><br> `media_type: film and page_views: 100`| `media_type:film AND page_views:100` <br><br> `+media_type:film +page_views:100`| +| Boolean `NOT` | `NOT media_type: article` <br><br> `not media_type: article` | `NOT media_type:article` <br><br> `-media_type:article` | +| Boolean `OR` | `title: wind OR description: film` <br><br> `title: wind or description: film` | `title: wind OR description: film` | +| Required/Prohibited operators | Not supported | Supports both `+` (required operator) and `-` (prohibited operator) <br><br> `+title:wind -media_type:article` (returns documents in which `title` contains `wind` but `media_type` does not contain `article`) | +| Wildcards | `title: wind*`<br><br> `titl*: wind` <br><br> Does not support wildcards in phrase searches (within quotation marks) <br><br> Only supports `*` (multiple characters) | `title:wind*` or `title:w?nd` <br><br> Does not support wildcards in field names <br><br> Does not support wildcards in phrase searches (within quotation marks) <br><br> Supports `*` (multiple characters) and `?` (single character) | +| Regular expressions | Not supported | `title:/w[a-z]nd/` | +| Fuzzy search | Not supported | `title:wind~2` | +| Proximity search | Not supported | `"wind rises"~2` | +| Boosting terms | Not supported | `title:wind^2` | +| Reserved characters | `\ ( ) : < > " * { }` | `+ - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ /` | + ## Search for terms By default, DQL searches in the field set as the default field on the index. If the default field is not set, DQL searches all fields. For example, the following query searches for documents containing the words `rises` or `wind` in any of their fields: @@ -134,14 +177,20 @@ To search for a phrase (an ordered sequence of words), surround your text with q ``` {% include copy.html %} -Hyphens are reserved characters in Lucene, so if your search term contains hyphens, DQL might prompt you to switch to Lucene syntax. To avoid this, surround your search term with quotation marks in a phrase search or omit the hyphen in a regular search. -{: .tip} +To search for a term that contains a hyphen, such as `Ruiz-Ortega`, surround the term with quotation marks: + +```python +author: "Ruiz-Ortega" +``` +{% include copy.html %} + +Without quotation marks, the query returns the same results, but Dashboards displays a warning that the query looks like Lucene syntax, because the hyphen is a reserved character in Lucene. ## Reserved characters The following is a list of reserved characters in DQL: -`\`, `(`, `)`, `:`, `<`, `>`, `"`, `*` +`\`, `(`, `)`, `:`, `<`, `>`, `"`, `*`, `{`, `}` Use a backslash (`\`) to escape reserved characters. For example, to search for an expression `2*3`, specify the query as `2\*3`: @@ -150,6 +199,20 @@ Use a backslash (`\`) to escape reserved characters. For example, to search for ``` {% include copy.html %} +The words `or`, `and`, and `not` are Boolean operators. To search for one of these words as a term, escape it with a backslash. For example, the following query searches for the word `and` in the `title` field: + +```plaintext +title: \and +``` +{% include copy.html %} + +Inside a quoted phrase, only the quotation mark (`"`) and the backslash (`\`) need to be escaped. Other reserved characters are treated as regular characters. For example, the following query searches for the phrase `2*3 (approx.)`: + +```plaintext +"2*3 (approx.)" +``` +{% include copy.html %} + ## Search in a field To search for text in a particular field, specify the field name before the colon: @@ -181,6 +244,29 @@ Query | Criterion for a document to match | Matching documents from the `testind `article*title: wind` | The field that starts with `article` and ends with `title` contains the word `wind`. Matches the field `article title`. | 4 `description:*` | Documents in which the field `description` exists. | 1, 2 +## Missing and empty values + +To find documents in which a field is missing, negate the [field existence query](#field-names). The following query returns documents 3 and 4, which don't contain a `description` field: + +```python +not description:* +``` +{% include copy.html %} + +A field that contains an empty string (`""`) exists, so the preceding query doesn't return it. To find documents in which a field contains an empty string, search the field's `keyword` subfield for `""`. A `text` field doesn't index any tokens for an empty string, so `author: ""` matches no documents. The following query returns document 4: + +```python +author.keyword: "" +``` +{% include copy.html %} + +To find documents in which a field exists and isn't empty, combine both conditions. The following query returns document 3: + +```python +author:* and not author.keyword: "" +``` +{% include copy.html %} + ## Wildcards DQL supports wildcards (`*` only) in both search terms and field names, for example: @@ -206,6 +292,13 @@ date >= "2013-01-01" and date < "2024-01-01" ``` {% include copy.html %} +Specify dates in the format defined in the field mapping. In `testindex`, the `date` field uses the `yyyy-MM-dd` format, so `date >= "1939"` returns a search error. You can also specify relative dates using [date math]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#date-math). For example, the following query searches for documents dated within the last 20 years: + +```python +date > "now-20y" +``` +{% include copy.html %} + You can query for "not equal to" by using `not` and the field name, for example: ```python @@ -277,7 +370,7 @@ title: ((wind or windy) and not rises) To refer to an object's inner field, list the dot path of the field. -To index a document containing an object, follow the steps in the [object field type example]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/object/#example). To search the `name` field of the `patient` object, use the following syntax: +To index a document containing an object, follow the steps in the [object field type example]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/object/#example). To search the `name` field of the `patient` object, use the following syntax: ```python patient.name: john @@ -288,7 +381,7 @@ patient.name: john To refer to a nested object, list the JSON path of the field. -To index a document containing an object, follow the steps in the [nested field type example]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/nested/#nested-field-type-1). +To index a document containing an object, follow the steps in the [nested field type example]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/#mapping-objects-as-nested). To search the `name` field of the `patients` object, use the following syntax: @@ -366,4 +459,33 @@ To search the `name` field of the `patients` object, use the following syntax: ```python patients.names: {name: john} ``` -{% include copy.html %} \ No newline at end of file +{% include copy.html %} + +## Comparing two fields + +DQL compares each field with a value that you specify, so it can't compare two fields in the same document. To compare fields in Discover, add a filter that contains a [script query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/script/): + +1. Below the search bar, select **Add filter**. +1. Select **Edit as Query DSL**. +1. Enter a script query. For example, the following query matches documents in which the `likes` field is greater than the `page_views` field: + + ```json + { + "script": { + "script": { + "source": "doc['likes'].value > doc['page_views'].value" + } + } + } + ``` + {% include copy.html %} + +1. Select **Save**. + +You can also compare fields using the PPL [`where`]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/commands/where/) command, for example, `source=my-index | where likes > page_views`. + +## Related documentation + +- To use regular expressions, fuzzy matching, proximity searches, or boosting, see [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). +- To filter and explore data in Discover, see [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). +- To group or summarize matching documents, see [Building data visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/index/) or [PPL]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/index/). diff --git a/_dashboards/exporting-data.md b/_dashboards/exporting-data.md new file mode 100644 index 00000000..6de3fd45 --- /dev/null +++ b/_dashboards/exporting-data.md @@ -0,0 +1,49 @@ +--- +layout: default +title: Exporting data +nav_order: 72 +--- + +# Exporting data + +OpenSearch Dashboards provides several ways to download content. The method depends on what you want to export: the documents themselves, the data behind a visualization, a rendered copy of a dashboard, or the definitions of the objects that you created. + +The following table lists the export methods. + +| What you want to export | Method | Format | +| :--- | :--- | :--- | +| Documents returned by a search | [Download the search results from Discover](#exporting-search-results) | CSV | +| A single document | [Copy the document from Discover](#exporting-search-results) | JSON | +| The data that a visualization displays | [Download the data from the Inspect panel](#exporting-visualization-data) | CSV | +| A dashboard, visualization, saved search, or notebook as a file to share, on demand or on a schedule | [Generate a report](#generating-reports) | PDF, PNG, CSV, or XLSX | +| Dashboards, visualizations, index patterns, and other saved objects, to back them up or copy them to another instance | [Export saved objects](#exporting-saved-objects) | NDJSON | + +## Exporting search results + +In **Discover**, filter the documents and choose the fields that you want to export, and then select **Download as CSV**. You can download either the documents visible on the page or all matching documents, up to 10,000. To copy a single document instead, expand the document and copy its JSON representation. + +For more information, see [Exporting data in Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/#exporting-data). + +## Exporting visualization data + +To download the data that a visualization displays, follow these steps: + +1. Open the visualization: + - In the **Visualize** application, open the visualization and select **Inspect** on the top menu. + - On a dashboard, open the panel menu of the visualization and select **Inspect**. +1. Select **Download CSV**. +1. Select one of the following options: + - **Formatted CSV**: Downloads the data as it appears in the table, using the field formats of the index pattern. + - **Raw CSV**: Downloads the data as it is stored. For example, dates are downloaded as timestamps. + +## Generating reports + +A report captures a dashboard, visualization, or notebook as a PDF or PNG file, or the results of a saved search as a CSV or XLSX file. Generate a report once or create a report definition that generates reports on a schedule. To export search results on a schedule or from a script, save the search in **Discover** and generate a CSV or XLSX report from the saved search. + +For more information, see [Reporting]({{site.url}}{{site.baseurl}}/dashboards/reporting/). + +## Exporting saved objects + +Saved objects are the definitions of the dashboards, visualizations, saved searches, index patterns, and other resources that you create in OpenSearch Dashboards. Exporting saved objects downloads these definitions, not the data that they display. Use this method to back up your objects or to import them into another OpenSearch Dashboards instance. + +For more information, see [Saved objects]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects/). diff --git a/_dashboards/getting-started/access.md b/_dashboards/getting-started/access.md new file mode 100644 index 00000000..eb7cae8d --- /dev/null +++ b/_dashboards/getting-started/access.md @@ -0,0 +1,54 @@ +--- +layout: default +title: Access OpenSearch Dashboards +parent: Getting started +nav_order: 15 +--- + +# Access OpenSearch Dashboards + +Once OpenSearch and OpenSearch Dashboards are running, open your browser and navigate to the following URL: + +- `http://localhost:5601` or `https://localhost:5601` for a local installation. +- [https://playground.opensearch.org/app/home#/](https://playground.opensearch.org/app/home#/) for the OpenSearch Playground. + +If your cluster uses the Security plugin, OpenSearch Dashboards opens a sign-in page. Sign in as the `admin` user with the password that you set in `OPENSEARCH_INITIAL_ADMIN_PASSWORD` when you installed OpenSearch. For more information, see [Setting the initial admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password). + +>- _OpenSearch Dashboards_ refers to the web UI for OpenSearch---the application you're looking at in your browser. +>- The **Dashboards** application is the tool within OpenSearch Dashboards for assembling visualizations into a single page. +>- A _dashboard_ (lowercase) is an individual page of visualizations created in the **Dashboards** application. +{: .note} + +## Accessing applications used in this section + +The Getting started tutorials use the Discover, Visualize, and Dashboards applications and the Dev Tools console. Use the _left navigation panel_ on the left side of the UI to select any application or settings page that you want to use. To open the navigation panel, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/menu-icon.png" class="inline-icon" alt="menu icon"/>{:/} (menu) icon in the header bar at the top of the page. For more information about the home page and the left navigation panel, see [Navigating OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/navigating-ui/). + +### Classic navigation + +In installations in which workspaces are not enabled, the left navigation panel lists all applications directly. The following image highlights the applications used in the tutorials. + +![OpenSearch Dashboards home page with classic navigation]({{site.url}}{{site.baseurl}}/images/dashboards/getting-started-classic-nav.png) + +1. Prepare your data. +1. Explore the Discover application. +1. Explore the Dashboards application. +1. Explore the Visualize application. +1. Run queries in OpenSearch Dashboards. + +The examples in this documentation use classic navigation. If you have workspaces enabled, the menu structure is different but the same applications are available within your workspace. + +### Workspaces navigation + +If workspaces are enabled, first create and select a workspace. For more information, see [Workspaces navigation]({{site.url}}{{site.baseurl}}/dashboards/navigating-ui/#workspaces-navigation). The following image shows the left navigation within an example Analytics workspace, including the applications used in the tutorials. + +![Left navigation within an Analytics workspace]({{site.url}}{{site.baseurl}}/images/dashboards/getting-started-workspace-interior-nav.png) + +1. Prepare your data. +1. Explore the Discover application. +1. Explore the Dashboards application. +1. Explore the Visualize application. +1. Run queries in OpenSearch Dashboards. + +## Next steps + +- To learn what each application does, see [Learn about main applications]({{site.url}}{{site.baseurl}}/dashboards/getting-started/learn-dashboards/). diff --git a/_dashboards/getting-started/concepts.md b/_dashboards/getting-started/concepts.md new file mode 100644 index 00000000..3c01cf7b --- /dev/null +++ b/_dashboards/getting-started/concepts.md @@ -0,0 +1,51 @@ +--- +layout: default +title: Concepts +parent: Getting started +nav_order: 60 +--- + +# OpenSearch Dashboards concepts + +This page defines key terms used throughout the OpenSearch Dashboards documentation. + +## OpenSearch Dashboards terminology + +- **_OpenSearch Dashboards_**: The web UI for OpenSearch. This is the application you access in your browser. +- **Dashboards** application: The application within OpenSearch Dashboards for assembling visualizations into a single page. See [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). +- _dashboard_ (lowercase): An individual page of data visualizations created in the **Dashboards** application. +- **Visualize** application: The application within OpenSearch Dashboards for creating individual charts, maps, and tables. See [Creating visualizations in the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/). +- _visualization_: A single panel containing a graph, chart, map, or other visual representation of data. +- **Discover** application: The application within OpenSearch Dashboards for searching, filtering, and examining data. See [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). +- [**OpenSearch Playground**](https://playground.opensearch.org/app/home#/): A read-only, web-based OpenSearch Dashboards instance with preloaded sample data. Use it to explore OpenSearch Dashboards without installing anything. + +## Data concepts + +- _index_: A collection of related documents stored in OpenSearch. See [Indexes]({{site.url}}{{site.baseurl}}/getting-started/intro/#index). +- _document_: The basic unit of information in OpenSearch, stored as a JSON object. See [Documents]({{site.url}}{{site.baseurl}}/getting-started/intro/#document). +- _index pattern_: A view into one or more indexes that you use as a data source in OpenSearch Dashboards. Also called a _data source_ in some contexts. See [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). +- _field_: A single named value within a document, equivalent to a column in a relational database table. +- _bucket_: A grouping of field values based on an aggregation. Buckets can be categorical (based on text values), range-based (user-defined numeric ranges), histogram-based (automatically sized numeric intervals), or time-based (segments of a timestamp field). +- _aggregation_: A computation that summarizes data across documents, such as calculating counts, averages, sums, or grouping documents into buckets. See [Aggregations]({{site.url}}{{site.baseurl}}/aggregations/). +- _saved object_: Any item you save in OpenSearch Dashboards, including visualizations, dashboards, index patterns, and saved searches. + +## Workspaces + +A _workspace_ is an isolated environment in OpenSearch Dashboards that organizes applications and saved objects by use case (for example, Analytics or Observability). See [Workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/). + +## Query languages + +OpenSearch Dashboards supports several query languages: + +- [**Dashboards Query Language (DQL)**]({{site.url}}{{site.baseurl}}/dashboards/dql/): A simple text-based language for filtering data in the Discover and Dashboards search bars. +- [**Piped Processing Language (PPL)**]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/): A pipe-based language for data processing and analysis. Used in the Query Workbench and the visualization editor. +- [**Query DSL**]({{site.url}}{{site.baseurl}}/query-dsl/): The full OpenSearch query language, used in the Dev Tools console and API requests. +- [**SQL**]({{site.url}}{{site.baseurl}}/sql-and-ppl/sql/): Standard SQL syntax for querying OpenSearch data. Used in the Query Workbench. + +## Next steps + +Explore the full documentation for each application: + +- [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) +- [Building data visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/) +- [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/) diff --git a/_dashboards/getting-started/data-setup.md b/_dashboards/getting-started/data-setup.md new file mode 100644 index 00000000..60e50a45 --- /dev/null +++ b/_dashboards/getting-started/data-setup.md @@ -0,0 +1,69 @@ +--- +layout: default +title: Prepare your data +parent: Getting started +nav_order: 20 +--- + +# Prepare your data + +Before you can explore, visualize, or dashboard your data in OpenSearch Dashboards, you need data in OpenSearch and an index pattern that points to it. + +## Step 1: Add data to OpenSearch + +Choose one of the following options to add data to OpenSearch. We recommend getting started by adding sample data. + +### Add sample data + +Sample datasets come with prebuilt index patterns, visualizations, and dashboards. The [**Sample flight data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). + +If you've installed a local OpenSearch Dashboards instance, add one or more sample datasets by following these steps: + +**Classic navigation:** + +1. On the OpenSearch Dashboards home page, select **Add sample data**. +1. On the **Add sample data** page, select the **Add data** button in the **Sample flight data** tile and any others that you want to add. + +**Workspaces navigation:** + +1. In the left navigation panel, expand **Manage workspace** and select **Sample data**. +1. Select the **Add data** button in the **Sample flight data** tile and any others that you want to add. + +The following image shows the available sample datasets. + +![Adding sample data window]({{site.url}}{{site.baseurl}}/images/dashboards/add-sample.png) + +If you installed sample data, the index patterns are created automatically and you're ready to [explore the Discover application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-discover/). +{: .note} + +### Ingest your own data + +OpenSearch Dashboards reads data from OpenSearch, so you add your own data to OpenSearch. Load your data into OpenSearch using the Bulk API, Data Prepper, or other ingestion tools. For more information, see [Ingest data]({{site.url}}{{site.baseurl}}/getting-started/ingest-data/). + +To send API requests, such as Bulk API requests, from OpenSearch Dashboards, use the Dev Tools console. For more information, see [Run queries in the Dev Tools console]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dev-tools/). + +After you ingest your data, create an index pattern for it as described in [Step 2](#step-2-create-an-index-pattern). + +## Step 2: Create an index pattern + +An index pattern tells OpenSearch Dashboards which indexes to query. You need at least one index pattern before you can use Discover, Visualize, or Dashboards with your own data. + +To create an index pattern, follow these steps: + +1. In the left navigation menu, go to **Management** > **Index patterns**. +2. Select **Create index pattern**. +3. Enter an index name or pattern (for example, `my-index-*` to match multiple indexes). +4. Select **Next step**. +5. If your index contains a timestamp field, select it from the **Time field** dropdown. For the examples in this section, select `timestamp`. This enables time-based filtering in Discover and visualizations. +6. Select **Create index pattern**. + +For more information, see [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). + +## Further reading + +- For more information about index patterns, see [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). +- [Connecting data sources]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/). + +## Next steps + +- Learn about each application in [Learn about main applications]({{site.url}}{{site.baseurl}}/dashboards/getting-started/learn-dashboards/). \ No newline at end of file diff --git a/_dashboards/getting-started/explore-dashboards.md b/_dashboards/getting-started/explore-dashboards.md new file mode 100644 index 00000000..fb8aaed0 --- /dev/null +++ b/_dashboards/getting-started/explore-dashboards.md @@ -0,0 +1,93 @@ +--- +layout: default +title: Explore the Dashboards application +parent: Getting started +nav_order: 40 +--- + +# Explore the Dashboards application + +The **Dashboards** application lets you combine multiple visualizations into a single page for monitoring and analysis. + +With **Dashboards**, you can: + +- Display multiple data visualizations in a single view. +- Build dynamic dashboards. +- Create and share reports. +- Embed analytics to differentiate your applications. + +## Prerequisites + +The examples on this page use the [**Sample flight data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). + +If you're using a local installation of OpenSearch Dashboards and haven't added sample data yet, see [Prepare your data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Try it: Explore a prebuilt dashboard + +1. From the navigation panel, select **OpenSearch Dashboards** > **Dashboards**. The panel displays a list of existing dashboards. + +1. In the search toolbar, search for and select **[Flights] Global Flight Dashboard**. + + The panel displays a dashboard preloaded with visualizations, including charts, maps, and data tables. + +1. To add other panels to the dashboard, select the **Edit** button and choose **Add** from the toolbar. + +1. In the search toolbar in the **Add panels** window, enter `flights`. + +1. From the narrowed list, select **[Flights] Delay Buckets**. + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>{:/} (cross) to exit the confirmation dialog. + +1. Select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>{:/} (cross) to exit the **Add panels** window. + +1. Scroll down to confirm that the newly added panel is now displayed as the last panel on the dashboard. + + The resulting view is shown in the following image. + + ![Add panel view]({{site.url}}{{site.baseurl}}/images/dashboards/add-dash-panel.png) + +### Adding your own visualization + +If you're using a local installation and saved the `Flight count over time` visualization in [Explore the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-visualize/), you can add it to this dashboard. Saving visualizations is not available in the OpenSearch Playground because it is read-only. + +To add the visualization, follow these steps: + +1. Select **Add** from the toolbar. +1. In the search toolbar, enter `Flight count over time`. +1. Select the visualization from the list. + + The visualization is added as the last panel on the dashboard, as shown in the following image. + + ![Flight count over time panel added to the end of the dashboard]({{site.url}}{{site.baseurl}}/images/dashboards/add-flight-count-panel.png) + +## Filtering data in the Dashboards application + +You can interact with visualizations to filter data. + +Using the **[Flights] Global Flight Dashboard** dashboard, follow these steps to filter the sample flight data: + +1. On the **[Flights] Airline Carrier** panel, select the **Toggle legend** icon in the lower-left corner. Then select **OpenSearch-Air** and then select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/plus-icon.png" class="inline-icon" alt="plus icon"/>{:/} (plus) icon. + + The dashboard updates automatically, adding the filter `Carrier: OpenSearch-Air` to the upper-left filter bar, as shown in the following image. + + ![Dashboard filtered by the OpenSearch-Air carrier]({{site.url}}{{site.baseurl}}/images/dashboards/airline-carrier-filter.png) + +1. Select **Save** to save the dashboard. + +Alternatively, you can use the dashboard toolbar to apply filters: + +1. If you've added a filter using the preceding instructions, first select {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>{:/} (cross) in the `Carrier: OpenSearch-Air` filter in the filter bar to remove the filter. + +1. In the dashboard toolbar, select **+ Add filter**. + +1. From the **Field**, **Operator**, and **Value** dropdown lists, select **Carrier**, **is**, and **OpenSearch-Air**, respectively. + +1. Select **Save**. + +## Further reading + +- For the full Dashboards reference, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). + +## Next steps + +- Learn how to run API queries in [Run queries in the Dev Tools console]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dev-tools/). diff --git a/_dashboards/getting-started/explore-dev-tools.md b/_dashboards/getting-started/explore-dev-tools.md new file mode 100644 index 00000000..5d200e3d --- /dev/null +++ b/_dashboards/getting-started/explore-dev-tools.md @@ -0,0 +1,50 @@ +--- +layout: default +title: Run queries in the Dev Tools console +parent: Getting started +nav_order: 50 +--- + +# Run queries in the Dev Tools console + +The Dev Tools console lets you send [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) queries to OpenSearch instead of using cURL in your terminal. + +## Try it: Write and run a query + +1. To open the Dev Tools console, select **Dev Tools** on the main OpenSearch Dashboards page or select **Management** > **Dev Tools** from the left navigation menu. In installations with workspaces enabled, select the code icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/code-icon.png" class="inline-icon" alt="code icon"/>{:/}) in the lower-left corner of the navigation panel. + +2. Write a query in the editor pane on the left side of the console. For example, enter the following query to index some documents: + + ```json + POST _bulk + { "create": { "_index": "students", "_id": "2" } } + { "name": "Jonathan Powers", "gpa": 3.85, "grad_year": 2025 } + { "create": { "_index": "students", "_id": "3" } } + { "name": "Jane Doe", "gpa": 3.52, "grad_year": 2024 } + ``` + {% include copy.html %} + +3. To send the query, place the cursor anywhere in the query text and select the play icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dev-tools/play-icon.png" class="inline-icon" alt="play icon"/>{:/}) on the upper right of the request, or press `Ctrl/Cmd+Enter`. + + OpenSearch displays the response in the pane on the right side of the console. + + ![Example query]({{site.url}}{{site.baseurl}}/images/dashboards/dev-tools-example.png) + +4. Try a search query. Enter the following request to retrieve all documents from the `students` index: + + ```json + GET students/_search + { + "query": { + "match_all": {} + } + } + ``` + {% include copy.html %} + +5. Select the play icon to send the request and view the results. + +## Next steps + +- For the full Dev Tools reference, see [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index/). +- For the full query language reference, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). \ No newline at end of file diff --git a/_dashboards/getting-started/explore-discover.md b/_dashboards/getting-started/explore-discover.md new file mode 100644 index 00000000..f98c96dd --- /dev/null +++ b/_dashboards/getting-started/explore-discover.md @@ -0,0 +1,62 @@ +--- +layout: default +title: Explore the Discover application +parent: Getting started +nav_order: 30 +--- + +# Explore the Discover application + +The **Discover** application lets you search, filter, and examine your data interactively. Use it to understand what fields are available, how data is distributed over time, and what patterns exist. + +With **Discover**, you can: + +- Choose data for analysis, set a time range for that data, search the data, and filter the results. +- Analyze your data: query and filter data, view results in a table, and examine documents. +- Create histograms to display the distribution of your data. + +In the search bar of the Discover and Dashboards applications, you can write queries in [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/dql/)---a simple text-based language for filtering data using field names and values. You can also switch to [query string (Lucene) syntax]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). + +## Prerequisites + +The examples on this page use the [**Sample flight data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). + +If you're using a local installation of OpenSearch Dashboards and haven't added sample data yet, see [Prepare your data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Try it: Search and filter flight data + +Follow these steps to use the **Discover** application: + +1. From the navigation panel, select **OpenSearch Dashboards** > **Discover**. + +1. On the **Discover** page, select the index pattern `opensearch_dashboards_sample_data_flights` from the dropdown menu on the upper left. + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>{:/} (calendar) icon to change the [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) from the default of **Last 15 minutes** to **Last 7 days**. + +1. In the DQL search bar, enter the following query: + + ```sql + FlightDelay:true AND DestCountry: US AND FlightDelayMin >= 60 + ``` + {% include copy.html %} + +1. Select **Update**. + + Results are shown for US-bound flights delayed by 60 minutes or more. + +1. Filter data by selecting {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/plus-icon.png" class="inline-icon" alt="plus icon"/>{:/} (plus) **Add filter** from the DQL **search bar** and then selecting a **Field**, **Operator**, and **Value** from the dropdown lists in the **Edit Filter** popover. For example, select `FlightDelayType`, **is**, and **Weather Delay**. + +1. Select **Save**. + + The resulting view is shown in the following image. + + ![Discover output showing filtered flight data]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-dashboards-discover.png) + +## Further reading + +- For the full Discover reference, see [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). +- For a DQL reference, see [Dashboards Query Language]({{site.url}}{{site.baseurl}}/dashboards/dql/). + +## Next steps + +- Create a visualization from your data using [Explore the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-visualize/). \ No newline at end of file diff --git a/_dashboards/getting-started/explore-visualize.md b/_dashboards/getting-started/explore-visualize.md new file mode 100644 index 00000000..9ef8f5b3 --- /dev/null +++ b/_dashboards/getting-started/explore-visualize.md @@ -0,0 +1,50 @@ +--- +layout: default +title: Explore the Visualize application +parent: Getting started +nav_order: 35 +--- + +# Explore the Visualize application + +The **Visualize** application lets you create charts, maps, tables, and other visual representations of your data using a point-and-click interface. + +## Prerequisites + +The example on this page uses the [**Sample flight data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). + +If you're using a local installation of OpenSearch Dashboards and haven't added sample data yet, see [Prepare your data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Try it: Create a line chart with sample data + +Follow these steps to use the **Visualize** application to create a line chart that shows flight count over time: + +1. In the left navigation menu, select **OpenSearch Dashboards** > **Visualize**. +2. Select **Create visualization**. +3. In the **New Visualization** dialog, select **Line**. +4. In the **Choose a source** dialog, select **opensearch_dashboards_sample_data_flights**. +5. Set the time filter to **Last 7 days**. +6. Under **Buckets**, select **Add** > **X-axis**. +7. Set **Aggregation** to **Date Histogram** and **Field** to **timestamp**. +8. Select **Update**. The chart displays flight count per time interval, as shown in the following image. + + ![Line chart showing flight count over time]({{site.url}}{{site.baseurl}}/images/dashboards/visualize-app-line-chart-example.png) + +9. From the toolbar, select **Save** (the disk icon). + + Saving is not available in the OpenSearch Playground because it is read-only. + {: .note} +10. In the **Save visualization** dialog, enter `Flight count over time` as the title. +11. Select **Save**. + + +The visualization is saved and appears in the **Visualizations** list. + +## Further reading + +- For the full Visualize reference, see [Creating visualizations in the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/). +- For a hands-on tutorial, see [Creating aggregation-based visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/aggregation-based-viz/). + +## Next steps + +- Assemble visualizations into a dashboard using [Explore the Dashboards application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dashboards/). \ No newline at end of file diff --git a/_dashboards/getting-started/index.md b/_dashboards/getting-started/index.md new file mode 100644 index 00000000..91616ac6 --- /dev/null +++ b/_dashboards/getting-started/index.md @@ -0,0 +1,77 @@ +--- +layout: default +title: Getting started +nav_order: 10 +has_children: true +has_toc: false +redirect_from: + - /dashboards/getting-started/ + - /dashboards/get-started/quickstart-dashboards/ + - /dashboards/quickstart-dashboards/ + - /dashboards/browser-compatibility/ + - /dashboards/quickstart/ +install_items: + - heading: "Install OpenSearch Dashboards" + link: "/dashboards/getting-started/install/" + - heading: "Access OpenSearch Dashboards" + link: "/dashboards/getting-started/access/" + - heading: "Prepare your data" + link: "/dashboards/getting-started/data-setup/" +learn_items: + - heading: "Learn about the main applications" + description: "Explore what each application does and when to use it." + link: "/dashboards/getting-started/learn-dashboards/" + - heading: "Explore the Discover application" + description: "Search and filter data." + link: "/dashboards/getting-started/explore-discover/" + - heading: "Explore the Visualize application" + description: "Create a visualization." + link: "/dashboards/getting-started/explore-visualize/" + - heading: "Explore the Dashboards application" + description: "View and filter a dashboard." + link: "/dashboards/getting-started/explore-dashboards/" + - heading: "Run queries in the Dev Tools console" + description: "Send OpenSearch API requests using Query DSL." + link: "/dashboards/getting-started/explore-dev-tools/" +workflow_items: + - heading: "Explore data with Discover" + description: "Search, filter, and examine your data interactively. Understand what fields are available, how data is distributed over time, and what patterns exist." + link: "/dashboards/discover/index-discover/" + - heading: "Build visualizations" + description: "Learn about ways to create charts, maps, tables, and other visual representations of your data." + link: "/dashboards/visualize/" + - heading: "Assemble dashboards" + description: "Combine multiple visualizations into a single page for monitoring and analysis." + link: "/dashboards/dashboard/" +--- + +# Getting started with OpenSearch Dashboards + +OpenSearch Dashboards is the web interface for OpenSearch. Use it to explore your data, build visualizations, assemble dashboards, and run queries. + +Before you begin, ensure that you're familiar with basic OpenSearch concepts like documents and indexes. For more information, see [Introduction to OpenSearch]({{site.url}}{{site.baseurl}}/getting-started/intro/). +{: .note} + +## Step 1: Set up OpenSearch Dashboards + +Choose one of the following options. + +### Option 1: Use the OpenSearch Playground + +Open the [OpenSearch Playground](https://playground.opensearch.org/app/home#/) in your browser. The Playground is read only and already includes the sample flight data, so you can start learning about the OpenSearch Dashboards applications in [Step 2](#step-2-explore-opensearch-dashboards-applications). + +### Option 2: Use your own installation + +To install OpenSearch Dashboards and add the sample data, follow these steps: + +{% include list.html list_items=page.install_items %} + +## Step 2: Explore OpenSearch Dashboards applications + +{% include list.html list_items=page.learn_items %} + +## Next steps + +Once you're familiar with the applications, the standard approach to building dashboards follows three steps: explore your data, build individual visualizations, then assemble those visualizations into a dashboard. To learn about each step in detail, use the following links to explore the full documentation. + +{% include list.html list_items=page.workflow_items %} diff --git a/_dashboards/getting-started/install.md b/_dashboards/getting-started/install.md new file mode 100644 index 00000000..2d361872 --- /dev/null +++ b/_dashboards/getting-started/install.md @@ -0,0 +1,30 @@ +--- +layout: default +title: Install OpenSearch Dashboards +parent: Getting started +nav_order: 10 +--- + +# Install OpenSearch Dashboards + +OpenSearch Dashboards is the user interface for OpenSearch. To follow the tutorials using your own instance, install OpenSearch and OpenSearch Dashboards by following these steps. + +## Step 1: Install OpenSearch and OpenSearch Dashboards + +Choose one of the following options: + +- To try OpenSearch and OpenSearch Dashboards using Docker, follow the [Installation quickstart]({{site.url}}{{site.baseurl}}/getting-started/quickstart/). + +- To install OpenSearch Dashboards for production, first install OpenSearch using one of the methods in [Installing OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/), and then install OpenSearch Dashboards using one of the methods in [Installing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/). + +## Step 2 (Optional): Configure OpenSearch Dashboards + +You can configure OpenSearch Dashboards settings in the `opensearch_dashboards.yml` file. This file controls server options, authentication, plugin settings, and features like [workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/). After changing the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +For a full list of settings, see [Configuring OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-dashboards/). + +Some settings can also be changed in OpenSearch Dashboards without editing `opensearch_dashboards.yml`. For more information, see [Advanced settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/). + +## Next steps + +- Learn how to navigate the interface in [Access OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/getting-started/access/). diff --git a/_dashboards/getting-started/learn-dashboards.md b/_dashboards/getting-started/learn-dashboards.md new file mode 100644 index 00000000..8705426a --- /dev/null +++ b/_dashboards/getting-started/learn-dashboards.md @@ -0,0 +1,45 @@ +--- +layout: default +title: Learn about main applications +parent: Getting started +nav_order: 25 +has_children: false +--- + +# Learn about main applications + +OpenSearch Dashboards provides several applications for working with your data. The standard workflow is to explore your data, build individual visualizations, and then assemble those visualizations into a dashboard. + +## The Discover application + +The **Discover** application lets you search, filter, and examine your data interactively. Use it to understand what fields are available, how data is distributed over time, and what patterns exist. + +![The Discover application showing flight data filtered by delay]({{site.url}}{{site.baseurl}}/images/dashboards/opensearch-dashboards-discover.png) + +## The Visualize application + +The **Visualize** application lets you create charts, maps, tables, and other visual representations of your data using a point-and-click interface. You select a visualization type, configure metrics and buckets, and adjust display settings. + +![A line chart created in the Visualize application]({{site.url}}{{site.baseurl}}/images/dashboards/visualize-app-line-chart-example.png) + +## The Dashboards application + +The **Dashboards** application lets you combine multiple visualizations into a single page for monitoring and analysis. You can add existing visualizations, create new ones, resize and reposition panels, and apply filters that affect all panels simultaneously. + +![A dashboard with multiple visualization panels]({{site.url}}{{site.baseurl}}/images/dashboards/add-dash-panel.png) + +## Dev Tools + +The **Dev Tools** console lets you run OpenSearch API queries directly using [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). Use it to test queries, manage indexes, and perform cluster operations without leaving the browser. + +![The Dev Tools console showing a query and response]({{site.url}}{{site.baseurl}}/images/dev-tools/dev-tools-response.png) + + +## Next steps + +To try each application, follow these pages in order or go directly to the application that you want to learn about: + +1. [Explore the Discover application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-discover/) +1. [Explore the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-visualize/) +1. [Explore the Dashboards application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dashboards/) +1. [Run queries in the Dev Tools console]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-dev-tools/) diff --git a/_dashboards/im-dashboards/index.md b/_dashboards/im-dashboards/index.md index 9ad94f5f..e200f1c2 100644 --- a/_dashboards/im-dashboards/index.md +++ b/_dashboards/im-dashboards/index.md @@ -1,52 +1,41 @@ --- layout: default -title: Index Management +title: Index management nav_order: 80 -has_children: true +has_children: false redirect_from: + - /dashboards/im-dashboards/ - /dashboards/admin-ui-index/ --- -# Index Management -Introduced 2.5 -{: .label .label-purple } +# Index Management in OpenSearch Dashboards -The Index Management interface in OpenSearch Dashboards provides a unified solution for managing common indexing and data stream operations. The interface allows you to perform create, read, update, and delete (CRUD) and mapping operations for indexes, index templates, and aliases instead of using REST APIs or YAML configurations for basic administrative operations and interventions, along with other operations such as open, close, reindex, shrink, and split indexes. The interface also provides you with the capabilities to run index status and data validation before submitting requests and compare changes with previously saved settings before making updates. +The **Index Management** page in OpenSearch Dashboards provides an interface for the index operations that you can otherwise perform using the [Index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index/): creating indexes and defining their mappings, opening and closing indexes, merging and splitting them, and automating those operations with state management policies. -An example of the interface is shown in the following image. +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. The following image shows the **Index Management** page. -![Index Management user interface]({{site.url}}{{site.baseurl}}/images/dashboards/index-management-UI.png) +![Index Management page]({{site.url}}{{site.baseurl}}/images/dashboards/index-management-UI.png) -## Get started with Index Management using Dashboards +Index management does not include operations on the documents in an index. To add data to an index, see [Ingest your data into OpenSearch]({{site.url}}{{site.baseurl}}/getting-started/ingest-data/). To query it, see [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/). -**Step 1: Open Index Management** +## Index Management pages -- Once you're in OpenSearch Dashboards, select **Index Management** from the **OpenSearch Plugins** main menu. Then select **Indices**. +The left panel of the **Index Management** page contains the following pages. -**Step 2: View indexes** +| Page | Description | Documentation | +| :--- | :--- | :--- | +| **State management policies** | Create, edit, and delete the policies that manage indexes automatically. | [Policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/#policies-in-opensearch-dashboards) | +| **Policy managed indexes** | View the state of each index that a policy manages, change its policy, or stop managing it. | [Managed indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/#managed-indexes-in-opensearch-dashboards) | +| **Indexes** | Create indexes and view their settings, mappings, and statistics. Open, close, reindex, and delete them, apply a policy to them, and maintain them by refreshing, flushing, force merging, shrinking, splitting, and rolling them over. | [Index operations]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#index-operations-in-opensearch-dashboards), [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#index-maintenance-in-opensearch-dashboards) | +| **Data streams** | Create data streams, view their backing indexes, and roll them over. | [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/#data-streams-in-opensearch-dashboards) | +| **Templates** | Create index templates and component templates that configure new indexes and data streams. | [Index templates]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/#index-templates-in-opensearch-dashboards) | +| **Aliases** | Create aliases, add indexes to them, and set the write index. | [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/#index-aliases-in-opensearch-dashboards) | +| **Rollup jobs** | Create jobs that summarize old data into smaller indexes. | [Index rollups]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/#index-rollups-in-opensearch-dashboards) | +| **Transform jobs** | Create jobs that write a summarized view of an index to a second index. | [Index transforms]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/index/#index-transforms-in-opensearch-dashboards) | +| **Notification settings** | Choose the index operations that send a notification when they finish or fail, and the channels that receive it. | [Long-running operation notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/#notifications-in-opensearch-dashboards) | -- In the **Indices** interface you will see a list of existing indexes in your OpenSearch cluster. The list provides information such as index name, health state, document count, index size, and other relevant details. +## Related documentation -**Step 3: Create an index** - -- To create a new index, select the **Create index** button in the upper-right corner. You will be prompted to enter the index name and configure the index settings, such as number of shards and replicas. Fill in the required information and select **Create** to create the index. - -**Step 4: Delete an index** - -- To delete an index, locate the index and select the checkbox next to it. Then select the **Actions** button and choose **Delete** from the dropdown list. Use caution when deleting indexes because this action is irreversible. - -**Step 5: Modify an index** - -- To modify the settings of an existing index, locate the index in the list and select its name. This takes you to the index details page. Here you can update settings such as the numbers of shards, replicas, and other advanced configurations. After making the desired changes, select **Save**. - -**Step 7: Refresh indexes** - -- To refresh an index, locate the index and select the checkbox next to it. Then select the **Actions** button and choose **Refresh** from the dropdown list. - -**Step 8: Filter and search indexes** - -- If you have a large number of indexes and want to filter or search for specific indexes, you can use the search bar located above the list of indexes. Enter the relevant keywords or filters to narrow the list of indexes. - -**Step 9: Additional operations** - -- Index Management provides additional functionalities such as creating index patterns, managing lifecycle policies, and configuring index templates. These options are available in their respective sections of the Index Management interface. +- [Managing indexes]({{site.url}}{{site.baseurl}}/im-plugin/) +- [Index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index/) +- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) diff --git a/_dashboards/index.md b/_dashboards/index.md index 8284d173..0b2b8a91 100644 --- a/_dashboards/index.md +++ b/_dashboards/index.md @@ -7,65 +7,81 @@ nav_exclude: true permalink: /dashboards/ redirect_from: - /dashboards/index/ +start_cards: + - heading: "Install OpenSearch Dashboards" + description: "Install OpenSearch Dashboards using Docker, Helm, a package manager, a tarball, or on Windows" + link: "/install-and-configure/install-dashboards/index/" + - heading: "Try it in the Playground" + description: "Explore OpenSearch Dashboards in your browser without installing anything" + link: "https://playground.opensearch.org/app/home#/" +getting_started_cards: + - heading: "Getting started" + description: "Learn the main applications step by step using sample data" + link: "/dashboards/getting-started/" + - heading: "Navigating OpenSearch Dashboards" + description: "Learn the layout of the home page and the left navigation panel" + link: "/dashboards/navigating-ui/" --- # OpenSearch Dashboards -OpenSearch Dashboards is the user interface that lets you visualize your OpenSearch data and run and scale your OpenSearch clusters. +OpenSearch Dashboards is the web UI for OpenSearch. Use it to search and explore your data, build visualizations and dashboards, and manage your cluster without writing API requests. + +{% include cards.html cards=page.start_cards %} ## Getting started -| Concept | Description | -|---------|-------------| -| [OpenSearch Dashboards Quickstart]({{site.url}}{{site.baseurl}}/dashboards/quickstart-dashboards/) | Learn about the basic concepts and features of OpenSearch Dashboards. | -| [OpenSearch Playground](https://playground.opensearch.org/app/home#/) | Explore features in OpenSearch Dashboards without downloading or installing anything. | -| [Install and configure OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) | Get started with OpenSearch Dashboards. | -| [Create visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/viz-index/) | Learn about visualizing data in OpenSearch Dashboards. | -| [Explore and query data]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) | Learn how to explore and query data in OpenSearch. | +{% include cards.html cards=page.getting_started_cards %} -## Query languages +## Adding data -Query language | Where you can use it | Description -:--- | :--- | :--- -[Query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/index/) | [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index-dev/) | The primary OpenSearch query language that supports creating complex, fully customizable queries. -[Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/) | [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) and [Dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/) search bar | A simple text-based query language used to filter data in OpenSearch Dashboards. -[Query string query language]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) and [Dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/) search bar | A scaled-down query language whose syntax is based on the Apache Lucene query syntax. -[SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/sql/index/) | [Query Workbench]({{site.url}}{{site.baseurl}}/dashboards/query-workbench/) | A traditional query language that bridges the gap between relational database concepts and the flexibility of OpenSearch’s document-oriented data storage. -[Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) | [Query Workbench]({{site.url}}{{site.baseurl}}/dashboards/query-workbench/) | The primary language used with observability in OpenSearch. PPL uses a pipe syntax that chains commands into a query. +To work with data in OpenSearch Dashboards, either add it to OpenSearch or connect to where it's stored: -### Discover and Dashboard search bar +- [Ingest data]({{site.url}}{{site.baseurl}}/getting-started/ingest-data/) into OpenSearch indexes. +- [Connect data sources]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/), such as other OpenSearch clusters, Amazon S3, or Prometheus, to query data without ingesting it. -Using the search bar in the [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) and [Dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/) apps, you can search data with the following two languages: +## Exploring and visualizing data -- [DQL]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/) +Use the following applications to search your data and present it visually. The table lists the query language that you use in each application. -- [Query string query (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) +| Application | Use it to | Query language | +| :--- | :--- | :--- | +| [Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) | Search, filter, and examine your data. | [DQL]({{site.url}}{{site.baseurl}}/dashboards/dql/) or [query string (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | +| [Visualize]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/) | Create charts, maps, tables, and other visualizations using a point-and-click interface. | [DQL]({{site.url}}{{site.baseurl}}/dashboards/dql/) or [query string (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | +| [Dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/) | Combine multiple visualizations into a single page and filter all of them at once. | [DQL]({{site.url}}{{site.baseurl}}/dashboards/dql/) or [query string (Lucene)]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | +| [Query Workbench]({{site.url}}{{site.baseurl}}/dashboards/query-workbench/) | Run on-demand SQL and PPL queries. | [SQL]({{site.url}}{{site.baseurl}}/sql-and-ppl/sql/) or [PPL]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/) | +| [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index/) | Send OpenSearch API requests from the browser. | [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) | -The following table compares DQL and query string query language features. +If [workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/) are enabled, you can also create visualizations by writing PPL or PromQL queries. For more information, see [Creating visualizations using queries]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/). -DQL and query string query language | DQL | Query string query language -:--- | :--- | :--- -- Wildcard expressions (DQL supports `*` only)<br> - Ranges<br> - Boolean operations<br> | - Querying nested fields | - Regular expressions<br> - Fuzziness<br> - Proximity queries<br> - Boosting +## Exporting data and generating reports -By default, the query language in the Discover search toolbar is DQL. To switch to query string syntax, select **DQL** and then turn off **OpenSearch Dashboards Query Language**. The query language changes to `Lucene`, as shown in the following image. +Download search results or visualization data as CSV files, or export your dashboards and visualizations as saved objects to back them up or copy them to another instance. For more information, see [Exporting data]({{site.url}}{{site.baseurl}}/dashboards/exporting-data/). -![Using query string syntax in OpenSearch Dashboards Discover]({{site.url}}{{site.baseurl}}/images/discover-lucene-syntax.png) +To share a dashboard, visualization, or saved search as a PDF, PNG, CSV, or XLSX file, either once or on a schedule, see [Reporting]({{site.url}}{{site.baseurl}}/dashboards/reporting/). + +## Managing indexes and snapshots + +Use the following applications to manage indexes and snapshots. + +| Application | Use it to | +| :--- | :--- | +| [Index Management]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/index/) | Manage indexes, data streams, aliases, templates, and Index State Management policies. | +| [Snapshot Management]({{site.url}}{{site.baseurl}}/dashboards/sm-dashboards/) | Back up and restore your cluster's indexes and state. | ## Observability -| Concept | Description | -|---------|-------------| -| [Observability in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}//observing-your-data/index/) | Observe, monitor, and secure data and improve performance across tools and workflows. | +To monitor logs, traces, and metrics in OpenSearch Dashboards, see [Observability]({{site.url}}{{site.baseurl}}/observing-your-data/index/). To set up prebuilt dashboards and visualizations for common data sources, such as NGINX logs, see [Integrations]({{site.url}}{{site.baseurl}}/dashboards/integrations/index/). +## Using AI assistance -## Dashboards Management +The [OpenSearch Assistant]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/index/) adds AI-powered assistance to OpenSearch Dashboards. -| Concept | Description | -|---------|-------------| -| [Dashboards Management]({{site.url}}{{site.baseurl}}/dashboards/management/management-index/) | Learn about the command center for customizing your OpenSearch Dashboards behavior, creating index patterns, and configuring data sources. | +## Configuring and administering OpenSearch Dashboards -## Dev Tools +You can configure OpenSearch Dashboards in two places, depending on your role. -| Concept | Description | -|---------|-------------| -| [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index-dev/) | Learn how to run OpenSearch queries in an integrated console. | +| Where | Who uses it | What you can configure | +| :--- | :--- | :--- | +| [Dashboards Management]({{site.url}}{{site.baseurl}}/dashboards/management/management-index/), an application in the UI | Users who have the required permissions | [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/), [data sources]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/), [saved objects]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects/), and [advanced settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/) | +| The `opensearch_dashboards.yml` configuration file | Administrators who deploy OpenSearch Dashboards and have access to the host | Deployment-level settings, such as [custom branding]({{site.url}}{{site.baseurl}}/dashboards/branding/), [network compression]({{site.url}}{{site.baseurl}}/dashboards/compression/), and [workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/). For more information, see [Settings and administration]({{site.url}}{{site.baseurl}}/dashboards/settings-and-administration/) and [Configuring OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-dashboards/). | diff --git a/_dashboards/integrations/index.md b/_dashboards/integrations/index.md new file mode 100644 index 00000000..2e16918f --- /dev/null +++ b/_dashboards/integrations/index.md @@ -0,0 +1,106 @@ +--- +layout: default +title: Integrations +nav_order: 100 +has_children: false +redirect_from: + - /integrations/ + - /integrations/index/ + - /dashboards/integrations/ +--- + +# OpenSearch Dashboards integrations +**Introduced 2.9** +{: .label .label-purple } + +The **Integrations** application in OpenSearch Dashboards provides a user-friendly platform for data visualization, querying, and projection of your resource data, such as flow logs. An _integration asset_, such NGINX or Amazon Virtual Private Cloud (VPC), contains a bundle of metadata, data mappings, and visualizations, streamlining the monitoring of resource data without redundant configuration steps. + +Available OpenSearch Dashboards integration assets are shown in the following image. + +![Integrations assets available in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/integrations-assets.png) + + + +## Use cases + +**Integrations** considers established data schemas across multiple domains to give you seamless data mapping and integration for various use cases, such as e-commerce product search, observability monitoring (for example, trace and metrics analytics), and security monitoring and threat analysis. + +## OpenTelemetry protocol for observability + +A consistent telemetry data schema is crucial for effective observability, enabling data correlation and analysis across applications, services, and infrastructure components to provide a holistic view of system behavior and performance. + +OpenSearch adopted the [OpenTelemetry (OTel)](https://opentelemetry.io/) protocol as the foundation for its observability solution. OTel is a community-driven standard that defines a consistent schema and data collection approach for metrics, logs, and traces. It is widely supported by APIs, SDKs, and telemetry collectors, enabling features like auto-instrumentation for seamless observability integration. + +This shared schema allows cross-correlation and analysis across different data sources. To this end, OpenSearch derived the [Simple Schema for Observability](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/schema/observability), which encodes the OTel standard as OpenSearch mappings. OpenSearch also supports the [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/), which is designed for high-dimensionality querying in observability use cases. + + + +## Ingesting data + +Data ingested into OpenSearch must conform to the supported schemas for data integrations and their associated dashboards. Compatible data pipelines are required, such as the following: + +- [Data Prepper](https://github.com/opensearch-project/data-prepper) +- [OpenTelemetry Collector](https://github.com/open-telemetry/opentelemetry-collector) +- [Fluent Bit for OpenSearch](https://docs.fluentbit.io/manual/pipeline/outputs/opensearch) + +These pipelines use the OTel schema (or a simple schema) to index signal documents into the correct index representing the observed resource signals. See [Naming Convention](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/schema/observability/Naming-convention.md) for index naming conventions. + +### Ingestion structure + +Each integration asset contains the following metadata and assets: + +* Name and description +* Source URL and license +* Schema specification, for example, mapping or component mapping +* Sample data for testing the feature +* Assets such as dashboards, index patterns, queries, or alerts + + + +## Installing an integration asset + +Integration assets can be installed directly from the [default catalog](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/integrations/Release.md) shipped with every OpenSearch release. + +To install an asset, follow these steps: + +1. Go to **Integrations** > **Available** to view the available options. +2. Select a tool, such as **NGINX** or **Amazon VPC**. You can choose **Add** to add or configure a new data integration using a prepackaged integration asset. You can choose **Try it** to test or explore the integration before fully adding it. +3. On the **Available** page, select the **Categories** dropdown menu to filter the list of integrations. + +### Try it demo + +To try a prepackaged integration asset, follow these steps: + +1. On the **Integrations** page, select **NGINX**. +2. Select the **Try it** button. The **Try it** option automatically creates a sample index template, adds sample data to the template, and then creates the integration based on that data. +3. Select an asset from the **Asset List**. Assets include dashboards, index patterns, and visualizations. +4. Preview the data visualizations and sample data details. An example is shown in the following image. + + ![Integrations dashboard with visualizations]({{site.url}}{{site.baseurl}}/images/integrations/nginx-integration-dashboard.png) + +## Loading custom integration assets + +To load a custom integration asset, follow these steps: + +1. Download an integration artifact from the [catalog repository](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/integrations/Release.md). +2. Go to **Dashboards Management** > **Saved objects**. +3. Select **Import** on the upper-right toolbar menu, navigate to the folder where you saved the integration artifact, and then choose the file (a file with an .ndjson extension). An example of this step is shown in the following image. + ![Import folder window]({{site.url}}{{site.baseurl}}/images/integrations/integration-import-file.png) +4. Select the saved object you uploaded to confirm that it was uploaded to **Saved objects**. An example of this step is shown in the following image. + ![List of integrations saved objects]({{site.url}}{{site.baseurl}}/images/integrations/select-uploaded-integration.png) + + + +## Developer resources + +See the following developer resources for sample code, articles, tutorials, and an API reference: + +- [OpenSearch Integrations repository](https://github.com/opensearch-project/opensearch-catalog) +- [OpenSearch Integrations reference documentation](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/integrations) +- [OpenSearch Observability Catalog](https://htmlpreview.github.io/?https://github.com/opensearch-project/opensearch-catalog/blob/main/integrations/observability/catalog.html) +- [OpenSearch Observability Catalog release page](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/integrations/Release.md) +- [Simple Schema for Observability](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/schema/observability) + +## Next steps + +- To request an integration that isn't available in the catalog, submit an [integration request](https://github.com/opensearch-project/dashboards-observability/issues/new?assignees=&labels=integration%2C+untriaged&projects=&template=integration_request.md&title=%5BIntegration%5D). diff --git a/_dashboards/management/S3-data-source.md b/_dashboards/management/S3-data-source.md index 585edeac..7742814a 100644 --- a/_dashboards/management/S3-data-source.md +++ b/_dashboards/management/S3-data-source.md @@ -1,8 +1,8 @@ --- layout: default title: Connecting Amazon S3 to OpenSearch -parent: Data sources -nav_order: 15 +parent: Connecting data sources +nav_order: 30 has_children: true --- @@ -10,51 +10,41 @@ has_children: true Introduced 2.11 {: .label .label-purple } -Starting with OpenSearch 2.11, you can connect OpenSearch to your Amazon Simple Storage Service (Amazon S3) data source using the OpenSearch Dashboards UI. You can then query that data, optimize query performance, define tables, and integrate your S3 data within a single UI. +You can connect OpenSearch to your Amazon Simple Storage Service (Amazon S3) data source using the OpenSearch Dashboards interface and then query that data, optimize query performance, define tables, and integrate your S3 data. ## Prerequisites -To connect data from Amazon S3 to OpenSearch using OpenSearch Dashboards, you must have: +Before connecting a data source, verify that the following requirements are met: -- Access to Amazon S3 and the [AWS Glue Data Catalog](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/connectors/s3glue_connector.rst#id2). -- Access to OpenSearch and OpenSearch Dashboards. -- An understanding of OpenSearch data source and connector concepts. See the [developer documentation](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/datasources.rst#introduction) for information about these concepts. +- You have access to Amazon S3 and the [AWS Glue Data Catalog](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/connectors/s3glue_connector.md). +- You have access to OpenSearch and OpenSearch Dashboards. +- You have an understanding of OpenSearch data source and connector concepts. See the [developer documentation](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/datasources.md) for more information. -## Connect your Amazon S3 data source +## Connect your data source -To connect your Amazon S3 data source, follow these steps: +To connect your data source, follow these steps: -1. From the OpenSearch Dashboards main menu, select **Management** > **Data sources**. -2. On the **Data sources** page, select **New data source** > **S3**. An example UI is shown in the following image. +1. From the OpenSearch Dashboards main menu, go to **Management** > **Dashboards Management** > **Data sources**. +2. On the **Data sources** page, select **Create data source connection** > **Amazon S3**. +3. On the **Configure Amazon S3 data source** page, enter the data source, authentication details, and permissions. +4. Select the **Review Configuration** button to verify the connection details. +5. Select the **Connect to Amazon S3** button to establish a connection. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/data-sources-UI.png" alt="Amazon S3 data sources UI" width="700"/> +## Manage your data source -3. On the **Configure Amazon S3 data source** page, enter the required **Data source details**, **AWS Glue authentication details**, **AWS Glue index store details**, and **Query permissions**. An example UI is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/S3-config-UI.png" alt="Amazon S3 configuration UI" width="700"/> - -4. Select the **Review Configuration** button and verify the details. -5. Select the **Connect to Amazon S3** button. - -## Manage your Amazon S3 data source - -Once you've connected your Amazon S3 data source, you can explore your data through the **Manage data sources** tab. The following steps guide you through using this functionality: +To manage your data source, follow these steps: 1. On the **Manage data sources** tab, choose a date source from the list. -2. On that data source's page, you can manage the data source, choose a use case, and manage access controls and configurations. An example UI is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/manage-data-source-UI.png" alt="Manage data sources UI" width="700"/> - -3. (Optional) Explore the Amazon S3 use cases, including querying your data and optimizing query performance. Go to **Next steps** to learn more about each use case. +2. On the page for the data source, you can manage the data source, choose a use case, and configure access controls. +3. (Optional) Explore the Amazon S3 use cases, including querying your data and optimizing query performance. Refer to the [**Next steps**](#next-steps) section to learn more about each use case. ## Limitations -This feature is still under development, including the data integration functionality. For real-time updates, see the [developer documentation on GitHub](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#limitations). +This feature is currently under development, including the data integration functionality. For up-to-date information, refer to the [developer documentation on GitHub](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#limitations). ## Next steps - Learn about [querying your data in Data Explorer]({{site.url}}{{site.baseurl}}/dashboards/management/query-data-source/) through OpenSearch Dashboards. -- Learn about ways to [optimize the query performance of your external data sources]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/), such as Amazon S3, through Query Workbench. -- Learn about [Amazon S3 and AWS Glue Data Catalog](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/connectors/s3glue_connector.rst) and the APIS used with Amazon S3 data sources, including configuration settings and query examples. +- Learn about [optimizing the query performance of your external data sources]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/), such as Amazon S3, through Query Workbench. +- Learn about [Amazon S3 and AWS Glue Data Catalog](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/connectors/s3glue_connector.md) and the APIs used with Amazon S3 data sources, including configuration settings and query examples. - Learn about [managing your indexes]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/index/) through OpenSearch Dashboards. - diff --git a/_dashboards/management/accelerate-external-data.md b/_dashboards/management/accelerate-external-data.md index 00e4600f..b946cb89 100644 --- a/_dashboards/management/accelerate-external-data.md +++ b/_dashboards/management/accelerate-external-data.md @@ -1,65 +1,181 @@ --- layout: default -title: Optimize query performance using OpenSearch indexing -parent: Connecting Amazon S3 to OpenSearch -grand_parent: Data sources -nav_order: 15 -has_children: false +title: Optimizing query performance using OpenSearch indexing +parent: Connecting data sources +nav_order: 40 --- -# Optimize query performance using OpenSearch indexing +# Optimizing query performance using OpenSearch indexing Introduced 2.11 {: .label .label-purple } -Query performance can be slow when using external data sources for reasons such as network latency, data transformation, and data volume. You can optimize your query performance by using OpenSearch indexes, such as a skipping index or a covering index. A _skipping index_ uses skip acceleration methods, such as partition, minimum and maximum values, and value sets, to ingest and create compact aggregate data structures. This makes them an economical option for direct querying scenarios. A _covering index_ ingests all or some of the data from the source into OpenSearch and makes it possible to use all OpenSearch Dashboards and plugin functionality. See the [Flint Index Reference Manual](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md) for comprehensive guidance on this feature's indexing process. +Query performance can be slow when using external data sources for reasons such as network latency, data transformation, and data volume. You can optimize your query performance by using OpenSearch indexes, such as a skipping index or a covering index. + +- A _skipping index_ uses skip acceleration methods, such as partition, minimum and maximum values, and value sets, to ingest and create compact aggregate data structures. This makes them an economical option for direct querying scenarios. For more information, see [Skipping indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#skipping-indexes). +- A _covering index_ ingests all or some of the data from the source into OpenSearch and makes it possible to use all OpenSearch Dashboards and plugin functionality. For more information, see [Covering indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#covering-indexes). +- A _materialized view_ enhances query performance by storing precomputed and aggregated data from the source data. For more information, see [Materialized views]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#materialized-views). + +For comprehensive guidance on each indexing process, see the [Flint Index Reference Manual](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md). ## Data sources use case: Accelerate performance -To get started with the **Accelerate performance** use case available in **Data sources**, follow these steps: +To get started with accelerating query performance, perform the following steps: -1. Go to **OpenSearch Dashboards** > **Query Workbench** and select your Amazon S3 data source from the **Data sources** dropdown menu in the upper-left corner. -2. From the left-side navigation menu, select a database. An example using the `http_logs` database is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-workbench-accelerate-data.png" alt="Query Workbench accelerate data UI" width="700"/> - -3. View the results in the table and confirm that you have the desired data. +1. Go to **OpenSearch Plugins** > **Query Workbench** and select your data source from the **Data sources** dropdown menu. +2. From the navigation menu, select a database. +3. View the results in the table and confirm that you have the correct data. 4. Create an OpenSearch index by following these steps: - 1. Select the **Accelerate data** button. A pop-up window appears. An example is shown in the following image. + 1. Select **Accelerate data**. A pop-up window appears. + 2. Enter your database and table details under **Select data fields**. +5. For **Acceleration type**, select the type of acceleration according to your use case. Then, enter the information for your acceleration type. For more information, see the following sections: + - [Skipping indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#skipping-indexes) + - [Covering indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#covering-indexes) + - [Materialized views]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#materialized-views) - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/accelerate-data-popup.png" alt="Accelerate data pop-up window" width="700"/> +## Skipping indexes - 2. Enter your details in **Select data fields**. In the **Database** field, select the desired acceleration index: **Skipping index** or **Covering index**. A _skipping index_ uses skip acceleration methods, such as partition, min/max, and value sets, to ingest data using compact aggregate data structures. This makes them an economical option for direct querying scenarios. A _covering index_ ingests all or some of the data from the source into OpenSearch and makes it possible to use all OpenSearch Dashboards and plugin functionality. - -5. Under **Index settings**, enter the information for your acceleration index. For information about naming, select **Help**. Note that an Amazon S3 table can only have one skipping index at a time. An example is shown in the following image. +A _skipping index_ uses skip acceleration methods, such as partition, min/max, and value sets, to ingest data using compact aggregate data structures. This makes them an economical option for direct querying scenarios. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/skipping-index-settings.png" alt="Skipping index settings" width="700"/> +With a skipping index, you can index only the metadata of the data stored in Amazon S3. When you query a table with a skipping index, the query planner references the index and rewrites the query to efficiently locate the data, instead of scanning all partitions and files. This allows the skipping index to quickly narrow down the specific location of the stored data. ### Define skipping index settings -1. Under **Skipping index definition**, select the **Add fields** button to define the skipping index acceleration method and choose the fields you want to add. An example is shown in the following image. +1. Under **Skipping index definition**, select **Generate** to automatically generate a skipping index. Alternately, to manually choose the fields you want to add, select **Add fields**. Choose from the following types: + - `Partition`: Uses data partition details to locate data. This type is best for partitioning-based columns such as year, month, day, hour. + - `MinMax`: Uses lower and upper bound of the indexed column to locate data. This type is best for numeric columns. + - `ValueSet`: Uses a unique value set to locate data. This type is best for columns with low to moderate cardinality that require exact matching. + - `BloomFilter`: Uses the bloom filter algorithm to locate data. This type is best for columns with high cardinality that do not require exact matching. +2. Select **Create acceleration** to apply your skipping index settings. +3. View the skipping index query details and then click **Run**. OpenSearch adds your index to the left navigation pane. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/add-fields-skipping-index.png" alt="Skipping index add fields" width="700"/> +Alternately, you can manually create a skipping index using Query Workbench. Select your data source from the dropdown and run a query like the following: -2. Select the **Copy Query to Editor** button to apply your skipping index settings. -3. View the skipping index query details in the table pane and then select the **Run** button. Your index is added to the left-side navigation menu containing the list of your databases. An example is shown in the following image. +```sql +CREATE SKIPPING INDEX +ON datasourcename.gluedatabasename.vpclogstable( + `srcaddr` BLOOM_FILTER, + `dstaddr` BLOOM_FILTER, + `day` PARTITION, + `account_id`BLOOM_FILTER + ) WITH ( +index_settings = '{"number_of_shards":5,"number_of_replicas":1}', +auto_refresh = true, +checkpoint_location = 's3://accountnum-vpcflow/AWSLogs/checkpoint' +) +``` - <img src="{{site.url}}{{site.baseurl}}/query-workbench-S3.png" alt="Run a skippping or covering index UI" width="700"/> +## Covering indexes + +A _covering index_ ingests all or some of the data from the source into OpenSearch and makes it possible to use all OpenSearch Dashboards and plugin functionality. + +With a covering index, you can ingest data from a specified column in a table. This is the most performant of the three indexing types. Because OpenSearch ingests all data from your desired column, you get better performance and can perform advanced analytics. + +OpenSearch creates a new index from the covering index data. You can use this new index to create visualizations, or for anomaly detection and geospatial capabilities. You can manage the covering view index with Index State Management. For more information, see [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/). ### Define covering index settings -1. Under **Index settings**, enter a valid index name. Note that each Amazon S3 table can have multiple covering indexes. An example is shown in the following image. +1. For **Index name**, enter a valid index name. Note that each table can have multiple covering indexes. +2. Choose a **Refresh type**. By default, OpenSearch automatically refreshes the index. Otherwise, you must manually trigger a refresh using a REFRESH statement. +3. Enter a **Checkpoint location**, which is a path for refresh job checkpoints. The location must be a path in a file system compatible with the Hadoop Distributed File System (HDFS). For more information, see [Starting streaming queries](https://spark.apache.org/docs/latest/streaming/apis-on-dataframes-and-datasets.html#starting-streaming-queries). +4. Define the covering index fields by selecting **(add fields here)** under **Covering index definition**. +5. Select **Create acceleration** to apply your covering index settings. +6. View the covering index query details and then click **Run**. OpenSearch adds your index to the left navigation pane. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/covering-index-naming.png" alt="Covering index settings" width="700"/> +Alternately, you can manually create a covering index on your table using Query Workbench. Select your data source from the dropdown and run a query like the following: -2. Once you have added the index name, define the covering index fields by selecting `(add fields here)` under **Covering index definition**. An example is shown in the following image. +```sql +CREATE INDEX vpc_covering_index +ON datasourcename.gluedatabasename.vpclogstable (version, account_id, interface_id, +srcaddr, dstaddr, srcport, dstport, protocol, packets, +bytes, start, action, log_status STRING, +`aws-account-id`, `aws-service`, `aws-region`, year, +month, day, hour ) +WITH ( + auto_refresh = true, + refresh_interval = '15 minute', + checkpoint_location = 's3://accountnum-vpcflow/AWSLogs/checkpoint' +) +``` - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/covering-index-fields.png" alt="Covering index field naming" width="700"/> +## Materialized views -3. Select the **Copy Query to Editor** button to apply your covering index settings. -4. View the covering index query details in the table pane and then select the **Run** button. Your index is added to the left-side navigation menu containing the list of your databases. An example UI is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/run-index-query-workbench.png" alt="Run index in Query Workbench" width="700"/> +With _materialized views_, you can use complex queries, such as aggregations, to power Dashboards visualizations. Materialized views ingest a small amount of your data, depending on the query, into OpenSearch. OpenSearch then forms an index from the ingested data that you can use for visualizations. You can manage the materialized view index with Index State Management. For more information, see [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/). + +### Define materialized view settings + +1. For **Index name**, enter a valid index name. Note that each table can have multiple covering indexes. +2. Choose a **Refresh type**. By default, OpenSearch automatically refreshes the index. Otherwise, you must manually trigger a refresh using a `REFRESH` statement. +3. Enter a **Checkpoint location**, which is a path for refresh job checkpoints. The location must be a path in an HDFS compatible file system. +4. Enter a **Watermark delay**, which defines how late data can come and still be processed, such as 1 minute or 10 seconds. +5. Define the covering index fields under **Materialized view definition**. +6. Select **Create acceleration** to apply your materialized view index settings. +7. View the materialized view query details and then click **Run**. OpenSearch adds your index to the left navigation pane. + +Alternately, you can manually create a materialized view index on your table using Query Workbench. Select your data source from the dropdown and run a query like the following: + +```sql +CREATE MATERIALIZED VIEW {table_name}__week_live_mview AS + SELECT + cloud.account_uid AS `aws.vpc.cloud_account_uid`, + cloud.region AS `aws.vpc.cloud_region`, + cloud.zone AS `aws.vpc.cloud_zone`, + cloud.provider AS `aws.vpc.cloud_provider`, + + CAST(IFNULL(src_endpoint.port, 0) AS LONG) AS `aws.vpc.srcport`, + CAST(IFNULL(src_endpoint.svc_name, 'Unknown') AS STRING) AS `aws.vpc.pkt-src-aws-service`, + CAST(IFNULL(src_endpoint.ip, '0.0.0.0') AS STRING) AS `aws.vpc.srcaddr`, + CAST(IFNULL(src_endpoint.interface_uid, 'Unknown') AS STRING) AS `aws.vpc.src-interface_uid`, + CAST(IFNULL(src_endpoint.vpc_uid, 'Unknown') AS STRING) AS `aws.vpc.src-vpc_uid`, + CAST(IFNULL(src_endpoint.instance_uid, 'Unknown') AS STRING) AS `aws.vpc.src-instance_uid`, + CAST(IFNULL(src_endpoint.subnet_uid, 'Unknown') AS STRING) AS `aws.vpc.src-subnet_uid`, + + CAST(IFNULL(dst_endpoint.port, 0) AS LONG) AS `aws.vpc.dstport`, + CAST(IFNULL(dst_endpoint.svc_name, 'Unknown') AS STRING) AS `aws.vpc.pkt-dst-aws-service`, + CAST(IFNULL(dst_endpoint.ip, '0.0.0.0') AS STRING) AS `aws.vpc.dstaddr`, + CAST(IFNULL(dst_endpoint.interface_uid, 'Unknown') AS STRING) AS `aws.vpc.dst-interface_uid`, + CAST(IFNULL(dst_endpoint.vpc_uid, 'Unknown') AS STRING) AS `aws.vpc.dst-vpc_uid`, + CAST(IFNULL(dst_endpoint.instance_uid, 'Unknown') AS STRING) AS `aws.vpc.dst-instance_uid`, + CAST(IFNULL(dst_endpoint.subnet_uid, 'Unknown') AS STRING) AS `aws.vpc.dst-subnet_uid`, + CASE + WHEN regexp(dst_endpoint.ip, '(10\\..*)|(192\\.168\\..*)|(172\\.1[6-9]\\..*)|(172\\.2[0-9]\\..*)|(172\\.3[0-1]\\.*)') + THEN 'ingress' + ELSE 'egress' + END AS `aws.vpc.flow-direction`, + + CAST(IFNULL(connection_info['protocol_num'], 0) AS INT) AS `aws.vpc.connection.protocol_num`, + CAST(IFNULL(connection_info['tcp_flags'], '0') AS STRING) AS `aws.vpc.connection.tcp_flags`, + CAST(IFNULL(connection_info['protocol_ver'], '0') AS STRING) AS `aws.vpc.connection.protocol_ver`, + CAST(IFNULL(connection_info['boundary'], 'Unknown') AS STRING) AS `aws.vpc.connection.boundary`, + CAST(IFNULL(connection_info['direction'], 'Unknown') AS STRING) AS `aws.vpc.connection.direction`, + + CAST(IFNULL(traffic.packets, 0) AS LONG) AS `aws.vpc.packets`, + CAST(IFNULL(traffic.bytes, 0) AS LONG) AS `aws.vpc.bytes`, + + CAST(FROM_UNIXTIME(time / 1000) AS TIMESTAMP) AS `@timestamp`, + CAST(FROM_UNIXTIME(start_time / 1000) AS TIMESTAMP) AS `start_time`, + CAST(FROM_UNIXTIME(start_time / 1000) AS TIMESTAMP) AS `interval_start_time`, + CAST(FROM_UNIXTIME(end_time / 1000) AS TIMESTAMP) AS `end_time`, + status_code AS `aws.vpc.status_code`, + + severity AS `aws.vpc.severity`, + class_name AS `aws.vpc.class_name`, + category_name AS `aws.vpc.category_name`, + activity_name AS `aws.vpc.activity_name`, + disposition AS `aws.vpc.disposition`, + type_name AS `aws.vpc.type_name`, + + region AS `aws.vpc.region`, + accountid AS `aws.vpc.account-id` + FROM + datasourcename.gluedatabasename.vpclogstable +WITH ( + auto_refresh = true, + refresh_interval = '15 Minute', + checkpoint_location = 's3://accountnum-vpcflow/AWSLogs/checkpoint', + watermark_delay = '1 Minute', +) +``` ## Limitations diff --git a/_dashboards/management/acl.md b/_dashboards/management/acl.md new file mode 100644 index 00000000..e7403fda --- /dev/null +++ b/_dashboards/management/acl.md @@ -0,0 +1,79 @@ +--- +layout: default +title: Access control lists for saved objects +parent: Saved objects +grand_parent: Dashboards management +nav_order: 20 +--- + +# Access control lists for saved objects +Introduced 2.18 +{: .label .label-purple } + +You can use access control lists (ACLs) to manage permissions for your saved objects, providing authorization (AuthZ) capabilities without requiring backend plugin integration. + +## Understanding ACL types + +ACLs are applied at two levels: + +1. **Workspace ACL:** Workspace objects inherit permissions from their parent workspace. See [Workspace ACL]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/) for more information. +2. **Objects ACL:** Each individual object can have its own ACL policy. All operations on these objects must pass ACL policy validation. + +## Enabling the ACL feature + +The ACL feature must be enabled before you can define any access controls. Enable it by: + +1. Opening your `opensearch_dashboards.yml` file. +2. Enabling permissions with `savedObjects.permission.enabled: true`. + +## Defining ACL permissions + +ACL permissions are defined using the following schema: + +```json +{ + "permissions": { + "<permission_type_1>": { + "users": ["<principal_1>", "<principal_2>"], + "groups": ["<principal_3>", "<principal_4>"] + } + } +} +``` +{% include copy-curl.html %} + +### Granting permissions to authenticated users + +The wildcard character (`*`) grants permissions to all authenticated users. In the following example, the ACL grants workspace management permissions to the `finance_manager` group and dashboard creation permissions to the `finance_analyst` group: + +```json +{ + "permissions": { + "write": { + "groups": ["finance_manager"] + }, + "library_write": { + "groups": ["finance_analyst"] + } + } +} +``` +{% include copy-curl.html %} + +### Configuring mixed-level permissions + +To allow one user, `user-1` for example, to modify an object while giving read-only access to others, you can configure the ACL policy as follows: + +```json +{ + "permissions": { + "read": { + "users": ["*"] + }, + "write": { + "users": ["user-1"] + }, + } +} +``` +{% include copy-curl.html %} diff --git a/_dashboards/management/advanced-settings.md b/_dashboards/management/advanced-settings.md index 8602baea..c27cc86f 100644 --- a/_dashboards/management/advanced-settings.md +++ b/_dashboards/management/advanced-settings.md @@ -1,23 +1,156 @@ --- layout: default title: Advanced settings -parent: Dashboards Management -nav_order: 40 +parent: Dashboards management +nav_order: 10 --- -# Advanced settings -Updated 2.10 -{: .label .label-purple } +# Advanced settings in OpenSearch Dashboards Use the **Advanced settings** page to modify settings that govern OpenSearch Dashboards behavior. These settings can be used to customize the look and feel of the application, change the behavior of certain features, and more. A view of the interface is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/advanced-settings-ui.png" alt="Advanced settings interface" width="700"/> +![Advanced settings interface in OpenSearch 2.14]({{site.url}}{{site.baseurl}}/images/dashboards/advanced-settings.png){: width="700" } -To access **Advanced settings**, go to **Dashboards Management** and select **Advanced settings**. The page is divided into several sections, each containing a set of related settings. You can modify these settings by editing their fields. Once you've made the changes, select **Save** to apply them. +To access **Advanced settings**, go to **Dashboards Management** and select **Advanced settings**. The page is divided into the following sections: [General](#general-settings), [Appearance](#appearance-settings), [Discover](#discover-settings), [Notifications](#notifications-settings), [Search](#search-settings), [Timeline](#timeline-settings), and [Visualization](#visualization-settings). Each section contains a set of its respective settings. You can modify these settings by editing their fields. Once you've made the changes, select **Save** to apply them. -{::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/alert-icon.png" class="inline-icon" alt="alert icon"/>{:/} **Note**<br>Certain settings require you to modify [the `opensearch_dashboards.yml` file](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml) and restart OpenSearch Dashboards. +{::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/alert-icon.png" class="inline-icon" alt="alert icon"/>{:/} **Note**<br>Certain settings require you to modify the `opensearch_dashboards.yml` file and restart OpenSearch Dashboards. For more information, see [Configuring OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-dashboards/). {: .note} ## Required permissions -To modify settings, you must have permission to make changes. See [Multi-tenancy configuration](https://opensearch.org/docs/latest/security/multi-tenancy/multi-tenancy-config/#give-roles-access-to-tenants) for guidance about assigning role access to tenants. +To modify settings, you must have permission to make changes. See [Multi-tenancy configuration]({{site.url}}{{site.baseurl}}/security/multi-tenancy/multi-tenancy-config/#give-roles-access-to-tenants) for guidance about assigning role access to tenants. + +## Advanced settings descriptions + +The following tables describe the core advanced settings. + +### General settings + +The following table describes the **General** settings. + +Setting | Description +:--- | :--- +`csv:quoteValues` | Defines whether to enclose values containing special characters or multiline values within double quotation marks `"`. Default is `On`. | +`csv:separator` | Defines whether to use a specific character or string to delimit exported values. Default is `,`. | +`dateFormat` | Defines the format for displaying dates. Default is `MMM D, YYYY @ HH:mm:ss.SSS`. | +`dateFormat:dow` | Defines the day on which to start the week. Default is `Sunday`. | +`dateFormat:scaled` | Defines the format for timestamps. The timestamp format changes depending on the amount of time between measurements (hour, minutes, seconds, and milliseconds). The keys are time periods in [ISO8601](https://www.iso.org/iso-8601-date-and-time-format.html) format: `YYYY-MM-DD`. | +`dateFormat:tz` | Defines the time zone for OpenSearch Dashboards. Default is the time zone detected by your browser. | +`dateNanosFormat` | Defines the format for representing dates with nanoseconds. Default is `MMM D, YYYY @ HH:mm:ss.SSSSSSSSS`. | +`defaultIndex` | Defines the default index for all indexes in an OpenSearch cluster. If no indexes are added, `defaultIndex` is set to `null`. However, if one or more indexes are added, `defaultIndex` is assigned the value of the first index in the list. Default is `null`. | +`defaultRoute` | Defines the gateway point. Use this setting to change the landing page for OpenSearch Dashboards. The setting must be a relative URL. Default is `/app/home`. | +`fields:popularLimit` | Defines the number of N fields to be displayed. Default is `10`. | +`filterEditor:suggestValues` | Defines whether the filter editor suggests field values. Default is `Off`. | +`filters:pinnedByDefault` | Defines whether filters are automatically pinned. To keep a filter visible across all applications, you can select the filter and then the **Pin across all apps** option. Default is `Off.` | +`format:bytes:defaultPattern` | Defines the default numeral format for the bytes format. Default is `0,0.[0]b`. | +`format:currency:defaultPattern` | Defines the default numeral format for the currency format. Default is `($0,0.[00])`. | +`format:defaultTypeMap` | Defines the default format name for each field type using a mapping. If the field type isn't specified, then `_default_` is used. | +`format:number:defaultLocale` | Defines the language locale for numerals. Default is `en`. To change the language of the OpenSearch Dashboards interface, set `i18n.locale` in `opensearch_dashboards.yml`. For more information, see [Language settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-dashboards/#language-settings). | +`format:number:defaultPattern` | Defines the default numeral format for the number format. Default is `0,0.[000]`. | +`format:percent:defaultPattern` | Defines the default numeral format for the percent format. Default is `0,0.[000]%`. | +`histogram:barTarget` | Defines a specified number of bars for date histograms that use the `auto` interval. Default is `50`. | +`histogram:maxBars` | Defines the maximum number of bars to show in date histograms. Default is `100`. | +`history:limit` | Defines how many of the most recent values to store in the history. Default is `10`. | +`indexPattern:placeholder` | Defines the placeholder value to use when creating index patterns. | +`metaFields` | Enables fields that are not part of the `_source` field to be merged into the document. Default is `_source`, `_id`, `_type`, `_index`, and `_score`. | +`metrics:max_buckets` | Defines the maximum number of buckets that a single data source can return. Default is `2000`. | +`query:allowLeadingWildcards` | Defines whether `*` is allowed as the first character in a query clause. Default is `On`. | +`query:queryString:options` | Defines the options for the Lucene query string parser. Default is `{ "analyze_wildcard": true }`. | +`reporting:useFOR` | Enables or disables `ForeignObject` rendering for embedding of external content into reports. The `reporting:useFOR` and `reporting:useOcr` options are visible only after installing the reporting plugin. Default is `On`. | +`reporting:useOcr` | Enables or disables optical character recognition (OCR) on PDF reports. The `reporting:useFOR` and `reporting:useOcr` options are visible only after installing the reporting plugin. Default is `Off`. | +`savedObjects:listingLimit` | Defines the number of objects to fetch when viewing a listing page. Default is `1000`. | +`savedObjects:perPage` | Defines the number of objects to display on each page of the load dialog. Default is `20`. | +`search:queryLanguage` | Defines the query language for OpenSearch Dashboards. Default is `DQL`. | +`shortDots:enable` | Enables or disables the shortening of long fields. Default is `Off`. | +`sort:options` | Defines the options for the sort parameter. Default is `boolean`. | +`state:storeInSessionStorage` | Enables or disables URL session storage. Default is `Off`. | +`timepicker:quickRanges` | Defines the quick-select time ranges to display in the time filter. | +`timepicker:refreshIntervalDefaults` | Defines the time filter's default refresh interval, in milliseconds. Default is `0`. | +`timepicker:timeDefaults` | Defines the default time period for data analysis. Default is `Last 15 minutes`. | +`truncate:maxHeight` | Defines the maximum height of a table cell. Default is `115` pixels. + +## Appearance settings + +The following table describes the **Appearance** settings. + +Setting | Description +:--- | :--- +`accessibility:disableAnimations` | Enables or disables animations. Default is `Off`. | +`pageNavigation` | Defines the navigation pane style. Default is `Modern`. | +`theme:darkMode` | Enables or disables dark mode. Default is `Off`. Dark mode is available only in OpenSearch Dashboards versions 2.10 and later. | +`theme:version` | Defines the theme to use for the current and subsequent versions of OpenSearch Dashboards. Default is `v7`. | + +## Discover settings + +The following table describes the **Discover** settings. + +Setting | Description +:--- | :--- +`context:defaultSize` | Defines the number of surrounding entries to show in the context view. Default is `5`. | +`context:step` | Defines the number by which to increment or decrement the context size. Default is `5`. | +`context:tieBreakerFields` | Defines the fields that are used to break a tie between documents that have the same timestamp value. The first field that is present and sortable in the current index pattern is used. Default is `_doc`. | +`defaultColumns` | Defines the columns that appear by default on the **Discover** page. Default is `_source`. | +`discover:aggs:terms:size` | Defines the number of terms that are visualized when selecting the **Visualize** button in the field dropdown. Default is `20`. | +`discover:modifyColumnsOnSwitch` | Defines whether unavailable columns are removed from a new index pattern. Default is `On`. | +`discover:sampleSize` | Defines the number of rows to show in a table. Default is `20`. | +`discover:searchOnPageLoad` | Defines whether a search is run when **Discover** first loads. The setting does not affect the loading of saved searches. Default is `On`. | +`discover:sort:defaultOrder` | Defines how to sort time-based index patterns. Default is `Descending`. | +`doc_table:hideTimeColumn` | Defines whether to hide the `Time` column in the **Discover** application and in all saved dashboard searches. Default is `Off`. | +`doc_table:highlight` | Defines whether to highlight results in the **Discover** application and saved searches on dashboards. Highlighting can make it easier to find and identify results, but it can also slow down requests when working with big documents. | + +## Notifications settings + +The following table describes the **Notifications** settings. + +Setting | Description +:--- | :--- +`notifications:banner` | Defines the custom banner for temporary user notifications. Supports [Markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax). | +`notifications:lifetime:banner` | Defines the display duration for banner notifications. Default is `3000000` milliseconds. Set field to `Infinity` to disable notifications. | +`notifications:lifetime:error` | Defines the display duration for error notifications. Default is `300000` milliseconds. Set field to `Infinity` to disable notifications. | +`notifications:lifetime:info` | Defines the display duration for information notifications. Default is `5000` milliseconds. Set field to `Infinity` to disable notifications. | +`notifications:lifetime:warning` | Defines the display duration for warning notifications. Default is `10000` milliseconds. Set field to `Infinity` to disable notifications. + +## Search settings + +The following table describes the **Search** settings. + +Setting | Description +:--- | :--- +`courier:batchSearches` | Enables or disables how dashboard panels load. When disabled, panels load individually, and search requests end when the user navigates away or updates the query. When enabled, all panels load together when all data is loaded, and searches do not end. Default is `Off`. | +`courier:customRequestPreference` | Specifies whether to use the [request preference]({{site.url}}{{site.baseurl}}/api-reference/popular-api/) with the `custom` setting. Default is `_local`. | +`courier:ignoreFilterIfFieldNotInIndex` | Enables or disables support for dashboards that contain visualizations using different indexes. When disabled, all filters are applied to all visualizations. When enabled, visualization filters are ignored if the visualization's index does not contain the field being filtered. Default is `Off`. | +`courier:maxConcurrentShardRequests` | Defines the maximum number of concurrent shard requests that OpenSearch Dashboards can initiate for `_msearch` requests. Set to `0` to disable the setting and to use the default value set by OpenSearch. Default is `0`. | +`courier:setRequestPreference` | Defines which shards handle your search requests. Options include **Session ID**, **Custom**, and **None**. **Session ID** restricts operations so that all search requests run on the same shard and reuses shard caches across requests, which can improve performance. **Custom** is used to define your own preference. Use `courier:customRequestPreference` to customize your preference value. **None** means that no preference is set. This option can provide better performance because requests can be spread across all shard copies. However, results might be inconsistent because different shards might be in different refresh states. Default is `Session ID`. | +`search:includeFrozen` | Specifies whether to include frozen indexes in search results. If enabled, frozen indexes are included in search results. Searching through frozen indexes can increase the search time. Default is `Off`. | + +## Timeline settings + +The following table describes the **Timeline** settings. + +Setting | Description +:--- | :--- +`timeline:es.default_index` | Defines the default OpenSearch index to be searched with the `.opensearch()` function. If not set, then the `.opensearch()` function will search all indexes. Default is `_all`. | +`timeline:es.timefield` | Defines the default timestamp field when using the `.opensearch()` function. If not set, then the `.opensearch()` function is used in the `@timestmap` field. Default is `@timestmap`. | +`timeline:graphite.url` | (Experimental) Defines the graphite host URL. | +`timeline:max_buckets` | Defines the maximum number of buckets that a single data source can return. Default is `2000`. | +`timeline:min_interval` | Defines the minimum interval to calculate when using the `auto` interval. Default is `1ms`. | +`timeline:quandl.key` | (Experimental) Defines your unique identifier (API key) that allows you to access Quandl's data. | +`timeline:target_buckets` | Defines the number of buckets that OpenSearch Dashboards attempts to use when calculating automatic intervals in visualizations. Default is `200`. | + +## Visualization settings + +The following table describes the **Visualization** settings. + +Setting | Description +:--- | :--- +`visualization:colorMapping` | Assigns colors to values within visualizations. Default is `#00A69B`. | +`visualization:dimmingOpacity` | Defines the opacity of chart items that are dimmed when another chart element is highlighted. The lower the value, the more the highlighted element will stand out. The value must be between `0` and `1`. Default is `0.5`. | +`visualization:enablePluginAugmentation` | Enables or disables access to plugin functionality through line chart visualizations. Default is `On`. | +` line chart visualizations` | Defines the maximum number of associated augmentations per visualization. Default is `10`. Associating more than 10 plugin resources per visualization can cause performance issues. | +`visualization:heatmap:maxBuckets` | Defines the maximum number of buckets that a single data source can return in a heat map visualization. A higher number of buckets can negatively impact browser rendering performance. Default is `50`. | +`visualization:regionmap:customVectorMapMaxSize` | Defines the maximum number of features that can be loaded from a custom vector map. Default is `1000`. | +`visualization:regionmap:showWarnings` | Specifies whether a warning is shown when terms cannot be joined to a shape on a region map. Default is `On`. | +`visualization:tileMap:WMSdefaults` | Defines the default [properties](https://leafletjs.com/reference.html#tilelayer-wms) for the Web Map Service (WMS) map server in coordinate maps. Default is `enabled: false`. | +`visualization:tileMap:maxPrecision` | Defines the maximum geohash precision that can be displayed on maps, with 7 being high, 10 being very high, and 12 being the maximum. Default is `7`. | +`visualize:disableBucketAgg` | Deactivates specific bucket aggregations in visualizations. The setting takes a comma-separated list of bucket aggregation names, such as `significant_terms` and `terms`. | +`visualize:enableLabs` | Enables or disables experimental visualizations. When enabled, you can create, view, and edit experimental visualizations. When disabled, you can only use production-ready visualizations. Default is `On`. | diff --git a/_dashboards/management/connect-prometheus.md b/_dashboards/management/connect-prometheus.md new file mode 100644 index 00000000..982d4278 --- /dev/null +++ b/_dashboards/management/connect-prometheus.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Connecting Prometheus to OpenSearch +parent: Connecting data sources +nav_order: 60 +--- + +# Connecting Prometheus to OpenSearch +Introduced 2.16 +{: .label .label-purple } + +You can connect OpenSearch to a Prometheus server and query its metrics in OpenSearch Dashboards. OpenSearch doesn't copy the metrics. Instead, the SQL plugin sends each query to Prometheus when you run it, so the Prometheus URI must be reachable from the OpenSearch nodes. + +## Prerequisites + +Before you create a connection, make sure that you have completed the following prerequisites: + +- Set the `plugins.query.datasources.encryption.masterkey` setting on all OpenSearch nodes. OpenSearch uses this key to encrypt the stored connection credentials and rejects requests to create or update a connection if the key is not set. For more information, see [Prerequisites]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/#prerequisites). +- Confirm that you have the required [Permissions]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/#permissions). + +## Creating a Prometheus connection + +To create a Prometheus connection, follow these steps: + +1. On the main menu, go to **Management** > **Dashboards Management** > **Data sources**. +1. Select **Create direct query connection** > **Prometheus**. +1. In the **Data source details** section, enter a **Data source name** and, optionally, a description. You use this name to refer to the connection in queries, for example, `source = my_prometheus.prometheus_http_requests_total`. +1. In the **Prometheus data location** section, enter the **Prometheus URI**, for example, `http://prometheus.example.com:9090`. +1. In the **Authentication details** section, select an **Authentication method**: + - **No authentication**: OpenSearch connects to Prometheus without credentials. + - **Basic authentication**: Enter a **Username** and **Password**. + - **AWS Signature Version 4**: Enter the **Auth Region**, **Access Key**, and **Secret Key**. Use this method for Amazon Managed Service for Prometheus. +1. In the **Query permissions** section, select a **Query access level**: + - **Admin only**: Only the admin user can query the connection. This is the default. + - **Restricted**: Users with the OpenSearch roles that you select can query the connection. This option is available only when the Security plugin is installed. +1. Select **Connect to Prometheus**. + +The new connection appears in the list of data sources. + +You can also create a connection using the `_plugins/_query/_datasources` API. For an example, see [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/#configuring-a-prometheus-connection-using-the-api). + +## Querying Prometheus metrics + +To query the metrics, select the connection on the **Data sources** page and then select **Query data**. The **Metrics** page in Observability opens, where you can visualize Prometheus metrics. You can also query them using Piped Processing Language (PPL). For more information, see [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/). + +## Changing access to a connection + +To change which users can query a connection, select the connection on the **Data sources** page. On the **Access control** tab, select **Edit**, update the **Query access level**, and save your changes. + +## Updating a connection + +OpenSearch Dashboards doesn't support editing the Prometheus URI or the credentials of an existing connection. To update them, send a request to the `_plugins/_query/_datasources` API. The following request changes the Prometheus URI of the `my_prometheus` connection: + +```json +PATCH _plugins/_query/_datasources +{ + "name": "my_prometheus", + "properties": { + "prometheus.uri": "http://prometheus.example.com:9090" + } +} +``` +{% include copy-curl.html %} + +## Deleting a connection + +If [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/) are enabled in OpenSearch Dashboards, you can delete a connection on the **Data sources** page. On the **Direct query connections** tab, select the connection, select **Delete 1 connection**, and then confirm the deletion. This tab lists only connections created in OpenSearch Dashboards. + +Otherwise, delete the connection using the API: + +```json +DELETE _plugins/_query/_datasources/my_prometheus +``` +{% include copy-curl.html %} + +## Related documentation + +- [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/) diff --git a/_dashboards/management/data-sources.md b/_dashboards/management/data-sources.md index 615a6ae5..b2613cd6 100644 --- a/_dashboards/management/data-sources.md +++ b/_dashboards/management/data-sources.md @@ -1,73 +1,49 @@ --- layout: default -title: Data sources -nav_order: 110 +title: Connecting data sources +nav_order: 30 has_children: true --- # Data sources -OpenSearch data sources are the applications that OpenSearch can connect to and ingest data from. Once your data sources have been connected and your data has been ingested, it can be indexed, searched, and analyzed using [REST APIs]({{site.url}}{{site.baseurl}}/api-reference/index/) or the OpenSearch Dashboards UI. +OpenSearch data sources are the applications that OpenSearch can connect to and ingest data from. Once your data sources have been connected and your data has been ingested, it can be indexed, searched, and analyzed using [REST APIs]({{site.url}}{{site.baseurl}}/api-reference/index/) or [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/). -This documentation focuses on using the OpenSeach Dashboards interface to connect and manage your data sources. For information about using an API to connect data sources, see the developer resources linked under [Next steps](#next-steps). +This documentation focuses on using the OpenSearch Dashboards web-based interface to connect and manage your data sources. For information about using an API to connect data sources, see the developer resources linked under [Next steps](#next-steps). ## Prerequisites -The first step in connecting your data sources to OpenSearch is to install OpenSearch and OpenSearch Dashboards on your system. You can follow the installation instructions in the [OpenSearch documentation]({{site.url}}{{site.baseurl}}/install-and-configure/index/) to install these tools. +The first step in connecting your data sources to OpenSearch is to install OpenSearch and OpenSearch Dashboards on your system. Refer to the [installation instructions]({{site.url}}{{site.baseurl}}/install-and-configure/index/) for information. Once you have installed OpenSearch and OpenSearch Dashboards, you can use Dashboards to connect your data sources to OpenSearch and then use Dashboards to manage data sources, create index patterns based on those data sources, run queries against a specific data source, and combine visualizations in one dashboard. Configuration of the [YAML files]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/#configuration-file) and installation of the `dashboards-observability` and `opensearch-sql` plugins is necessary. For more information, see [OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). -## Create a data source connection +To securely store and encrypt data source connections in OpenSearch, you must add the following configuration to the `opensearch.yml` file on all the nodes: -A data source connection specifies the parameters needed to connect to a data source. These parameters form a connection string for the data source. Using Dashboards, you can add new data source connections or manage existing ones. +`plugins.query.datasources.encryption.masterkey: "YOUR_GENERATED_MASTER_KEY_HERE"` -The following steps guide you through the basics of creating a data source connection: +The key must be 16, 24, or 32 characters. You can use the following command to generate a 24-character key: -1. From the OpenSearch Dashboards main menu, select **Dashboards Management** > **Data sources** > **Create data source connection**. The UI is shown in the following image. +`openssl rand -hex 12` - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/data-source-UI.png" alt="Connecting a data source UI" width="700"/> +Generating 12 bytes results in a hexadecimal string that is 12 * 2 = 24 characters. +{: .note} -2. Create the data source connection by entering the appropriate information into the **Connection Details** and **Authentication Method** fields. - - - Under **Connection Details**, enter a title and endpoint URL. For this tutorial, use the URL `http://localhost:5601/app/management/opensearch-dashboards/dataSources`. Entering a description is optional. +## Permissions - - Under **Authentication Method**, select an authentication method from the dropdown list. Once an authentication method is selected, the applicable fields for that method appear. You can then enter the required details. The authentication method options are: - - **No authentication**: No authentication is used to connect to the data source. - - **Username & Password**: A basic username and password are used to connect to the data source. - - **AWS SigV4**: An AWS Signature Version 4 authenticating request is used to connect to the data source. AWS Signature Version 4 requires an access key and a secret key. - - For AWS Signature Version 4 authentication, first specify the **Region**. Next, select the OpenSearch service in the **Service Name** list. The options are **Amazon OpenSearch Service** and **Amazon OpenSearch Serverless**. Lastly, enter the **Access Key** and **Secret Key** for authorization. +To work with data sources in OpenSearch Dashboards, you must be assigned the correct cluster-level [data source permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions#data-source-permissions). - After you have populated the required fields, the **Test connection** and **Create data source** buttons become active. You can select **Test connection** to confirm that the connection is valid. +## Types of data streams -3. Select **Create data source** to save your settings. The connection is created. The active window returns to the **Data sources** main page, and the new connection appears in the list of data sources. +To configure data sources through OpenSearch Dashboards, go to **Management** > **Dashboards Management** > **Data sources**. This flow can be used for OpenSearch data stream connections. See [Configuring and using multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/). -4. To delete a data source connection, select the checkbox to the left of the data source **Title** and then select the **Delete 1 connection** button. Selecting multiple checkboxes for multiple connections is supported. An example UI is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/delete-data-source.png" alt="Deleting a data source UI" width="700"/> - -### Modify a data source connection - -To make changes to a data source connection, select a connection in the list on the **Data sources** main page. The **Connection Details** window opens. - -To make changes to **Connection Details**, edit one or both of the **Title** and **Description** fields and select **Save changes** in the lower-right corner of the screen. You can also cancel changes here. To change the **Authentication Method**, choose a different authentication method, enter your credentials (if applicable), and then select **Save changes** in the lower-right corner of the screen. The changes are saved. - -When **Username & Password** is the selected authentication method, you can update the password by choosing **Update stored password** next to the **Password** field. In the pop-up window, enter a new password in the first field and then enter it again in the second field to confirm. Select **Update stored password** in the pop-up window. The new password is saved. Select **Test connection** to confirm that the connection is valid. - -When **AWS SigV4** is the selected authentication method, you can update the credentials by selecting **Update stored AWS credential**. In the pop-up window, enter a new access key in the first field and a new secret key in the second field. Select **Update stored AWS credential** in the pop-up window. The new credentials are saved. Select **Test connection** in the upper-right corner of the screen to confirm that the connection is valid. - -To delete the data source connection, select the delete icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/trash-can-icon.png" class="inline-icon" alt="delete icon"/>{:/}). - -## Create an index pattern - -Once you've created a data source connection, you can create an index pattern for the data source. An _index pattern_ is a template that OpenSearch uses to create indexes for data from the data source. See [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) for more information and a tutorial. +Alternatively, if you are running OpenSearch Dashboards 2.16 or later, go to **Management** > **Data sources**. This flow can be used to connect Amazon Simple Storage Service (Amazon S3) and Prometheus. See [Connecting Amazon S3 to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/S3-data-source/) and [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/) for more information. ## Next steps - Learn about [managing index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) through OpenSearch Dashboards. - Learn about [indexing data using Index Management]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/index/) through OpenSearch Dashboards. - Learn about how to connect [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/). -- Learn about how to [connect OpenSearch and Amazon S3 through OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/management/S3-data-source/). -- Learn about the [Integrations]({{site.url}}{{site.baseurl}}/integrations/index/) tool, which gives you the flexibility to use various data ingestion methods and connect data from the Dashboards UI. - +- Learn about how to connect [OpenSearch and Amazon S3]({{site.url}}{{site.baseurl}}/dashboards/management/S3-data-source/) and [OpenSearch and Prometheus]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/) using the OpenSearch Dashboards interface. +- Learn about the [Integrations]({{site.url}}{{site.baseurl}}/integrations/index/) plugin, which gives you the flexibility to use various data ingestion methods and connect data to OpenSearch Dashboards. diff --git a/_dashboards/management/index-patterns.md b/_dashboards/management/index-patterns.md index 590a9675..79b1c048 100644 --- a/_dashboards/management/index-patterns.md +++ b/_dashboards/management/index-patterns.md @@ -1,7 +1,7 @@ --- layout: default title: Index patterns -parent: Dashboards Management +parent: Connecting data sources nav_order: 10 --- @@ -11,25 +11,19 @@ Index patterns are essential for accessing OpenSearch data. An _index pattern_ r If you store data in multiple indexes, creating an index pattern enables your visualizations to retrieve data from all indexes that match the index pattern. You need to create index patterns to define how data is retrieved and fields are formatted so that you can query, search, and display data. -## Get started -In this tutorial, you'll learn to create index patterns. - -{::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/alert-icon.png" class="inline-icon" alt="alert icon" size="m"/>{:/}**Note**<br> -To create or modify index patterns, you must have create, manage, and delete permissions. Contact your administrator for support. For more information, refer to [Multi-tenancy configuration]({{site.url}}{{site.baseurl}}/security/multi-tenancy/multi-tenancy-config/#give-roles-access-to-tenants). -{: .note} ## Prerequisites Before you can create an index pattern, your data must be indexed. To learn about indexing your data in OpenSearch, see [Managing indexes]({{site.url}}{{site.baseurl}}/im-plugin/index/). -## Best practices - -Consider the following best practices when creating index patterns: - -- **Make your index patterns specific.** Instead of creating an index pattern that matches all indexes, create an index pattern that matches all indexes starting with a certain prefix, for example, `my-index-`. The more specific your index patterns, the better it will be to query and analyze your data. -- **Use wildcards sparingly.** Wildcards can be useful for matching multiple indexes, but they can also make it more difficult to manage your index patterns. Try to use wildcards as specifically as possible. -- **Test your index patterns.** Make sure to test your index patterns to ensure that they match the correct indexes. +> To create or modify index patterns, your role must have the following permissions: +> - The `kibana_user` role (or equivalent), which grants access to OpenSearch Dashboards. +> - The `kibana_all_write` tenant permission for the tenant in which you want to create the index pattern. With `kibana_all_read`, you can view existing index patterns but cannot create or modify them. +> - Read access to the indexes that the index pattern will match. +> +> Contact your administrator for support. For more information about tenant permissions, see [Multi-tenancy configuration]({{site.url}}{{site.baseurl}}/security/multi-tenancy/multi-tenancy-config/#give-roles-access-to-tenants). For more information about roles, see [Predefined roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/#predefined-roles). +{: .note} ## Creating an index pattern @@ -44,21 +38,29 @@ If you added sample data, you have index patterns that you can use to analyze th An example of step 1 is shown in the following image. Note that the index pattern `security*` matches three indexes. By defining the pattern with a wildcard `*`, you can query and visualize all the data in your indexes. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/index-patterns-step1.png" alt="Index pattern step 1 UI " width="700"/> +![Index pattern step 1 UI ]({{site.url}}{{site.baseurl}}/images/dashboards/index-patterns-step1.png){: width="700" } ### Step 2: Configure the settings -1. Select `@timestamp` from the dropdown menu to specify the time field for OpenSearch to use when filtering documents based on time. Selecting this time filter determines which field the time filter is applied to. It can be the timestamp of a request or any relevant timestamp field. If you don't want to use a time filter, select that option from the dropdown menu. If you select this option, OpenSearch returns all of the data in the indexes that match the pattern. +1. In the **Time field** list, select the date field to use for time filtering, for example, `@timestamp`. The list contains the date fields in the matching indexes, so if your indexes don't have an `@timestamp` field, select another date field, such as the time an event or order occurred. The [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) applies only to this field. If your indexes don't contain a date field, or you don't want to filter by time, select **I don't want to use the time filter**. In this case, data is not filtered by time, so all data in the matching indexes is returned. You can't change the time field after you create the index pattern. 2. Select **Create index pattern.** An example is shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/index-pattern-step2.png" alt="Index pattern step 2 UI " width="700"/> + ![Index pattern step 2 UI ]({{site.url}}{{site.baseurl}}/images/dashboards/index-pattern-step2.png){: width="700" } Once the index pattern has been created, you can view the mapping of the matching indexes. Within the table, you can see the list of fields, along with their data type and properties. An example is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}//images/dashboards/index-pattern-table.png" alt="Index pattern table UI " width="700"/> +![Index pattern table UI ]({{site.url}}{{site.baseurl}}/images/dashboards/index-pattern-table.png){: width="700" } + +## Best practices + +Consider the following best practices when creating index patterns: + +- **Make your index patterns specific**: Instead of creating an index pattern that matches all indexes, create an index pattern that matches all indexes starting with a certain prefix, for example, `my-index-`. The more specific your index patterns, the better it will be to query and analyze your data. +- **Use wildcards sparingly**: Wildcards can be useful for matching multiple indexes, but they can also make it more difficult to manage your index patterns. Try to use wildcards as specifically as possible. +- **Test your index patterns**: Make sure to test your index patterns to ensure that they match the correct indexes. ## Next steps -- [Understand your data through visuals]({{site.url}}{{site.baseurl}}/dashboards/visualize/viz-index/). +- [Understand your data through visuals]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/). - [Dig into your data]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). diff --git a/_dashboards/management/management-index.md b/_dashboards/management/management-index.md index 7edc4d06..bb8b50ef 100644 --- a/_dashboards/management/management-index.md +++ b/_dashboards/management/management-index.md @@ -1,26 +1,32 @@ --- layout: default -title: Dashboards Management -nav_order: 100 +title: Dashboards management +nav_order: 130 has_children: true +has_toc: false --- -# Dashboards Management +# Dashboards management Introduced 2.10 {: .label .label-purple } -**Dashboards Management** serves as the command center for customizing OpenSearch Dashboards to your needs. A view of the interface is shown in the following image. +**Dashboards Management** is the central hub for managing and customizing OpenSearch data directly within OpenSearch Dashboards. Unlike deployment-level settings that administrators configure, **Dashboards Management** is an in-product application that you access from OpenSearch Dashboards. Use it to configure data access, such as index patterns, data sources, saved objects, and advanced settings, without editing configuration files or accessing the host. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/dashboards-management-ui.png" alt="Dashboards Management interface" width="700"/> - -{::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/alert-icon.png" class="inline-icon" alt="alert icon"/>{:/} **Note**<br>OpenSearch and OpenSearch Dashboards privileges govern access to individual features. If you do not have the appropriate access, consult your administrator. -{: .note} +OpenSearch and OpenSearch Dashboards permissions govern access to individual features. If you do not have the appropriate access permissions, consult your administrator. +{: .warning} ## Applications -The following applications are available in **Dashboards Management**: +To open **Dashboards Management**, in classic navigation, select **Management** > **Dashboards Management**. In workspaces navigation, the applications are available in the **Settings and setup** menu. -- **[Index Patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/):** To access OpenSearch data, you need to create an index pattern so that you can select the data you want to use and define the properties of the fields. The Index Pattern tool gives you the ability to create an index pattern from within the UI. Index patterns point to one or more indexes, data streams, or index aliases. -- **[Data Sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/):** The Data Sources tool is used to configure and manage the data sources that OpenSearch uses to collect and analyze data. You can use the tool to specify the source configuration in your copy of the [OpenSearch Dashboards configuration file]({{site.url}}{{site.baseurl}}https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml). -- **[Saved Objects](https://opensearch.org/blog/enhancement-multiple-data-source-import-saved-object/):** The Saved Objects tool helps you organize and manage your saved objects. Saved objects are files that store data, such as dashboards, visualizations, and maps, for later use. -- **[Advanced Settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/):** The Advanced Settings tool gives you the flexibility to personalize the behavior of OpenSearch Dashboards. The tool is divided into settings sections, such as General, Accessibility, and Notifications, and you can use it to customize and optimize many of your Dashboards settings. +You can access the following applications in **Dashboards Management**: + +- **[Index Patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/)**: To access OpenSearch data, you need to create an index pattern so that you can select the data you want to use and define the properties of the fields. The **Index Pattern** tool gives you the ability to create an index pattern from within the UI. Index patterns point to one or more indexes, data streams, or index aliases. +- **[Data Sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/)**: The **Data Sources** tool is used to configure and manage the data sources that OpenSearch uses to collect and analyze data. You can use the tool to specify the source configuration in your copy of the [OpenSearch Dashboards configuration file](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml). +- **[Saved Objects]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects/)**: The **Saved Objects** tool helps you organize and manage your saved objects. Saved objects are files that store data, such as dashboards, visualizations, and maps, for later use. Use the tool to [export and import them]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects/), for example to copy a dashboard to another cluster, or to do the same programmatically with the [Saved Objects APIs]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects-api/). +- **[Advanced Settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/)**: The **Advanced Settings** tool gives you the flexibility to personalize the behavior of OpenSearch Dashboards. The tool is divided into settings sections, such as General, Accessibility, and Notifications, and you can use it to customize and optimize many of your Dashboards settings. +- **[Resource Access Management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/)** (if resource sharing is enabled): The **Resource Access Management** tool provides fine-grained access control for plugin-defined resources such as machine learning (ML) model groups, anomaly detectors, and report definitions. You can share resources with specific users, roles, or backend roles and control their access levels. + +## Related documentation + +- To configure deployment-level settings, such as branding and network compression, by editing the `opensearch_dashboards.yml` file, see [Settings and administration]({{site.url}}{{site.baseurl}}/dashboards/settings-and-administration/). \ No newline at end of file diff --git a/_dashboards/management/multi-data-sources.md b/_dashboards/management/multi-data-sources.md index 04473486..18d3a3e9 100644 --- a/_dashboards/management/multi-data-sources.md +++ b/_dashboards/management/multi-data-sources.md @@ -1,33 +1,35 @@ --- layout: default title: Configuring and using multiple data sources -parent: Data sources -nav_order: 10 -redirect_from: +parent: Connecting data sources +nav_order: 20 +redirect_from: - /dashboards/discover/multi-data-sources/ --- -# Configuring and using multiple data sources +# Configuring and using multiple data sources in OpenSearch Dashboards -You can ingest, process, and analyze data from multiple data sources in OpenSearch Dashboards. You configure the data sources in the **Dashboards Management** > **Data sources** app, as shown in the following image. +You can ingest, process, and analyze data from multiple data sources in OpenSearch Dashboards. You configure the data sources under **Dashboards Management** > **Data sources**. This interface is shown in the following image. - -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/data-sources-management.png" alt="Dashboards Management Data sources main screen" width="700"> +![Dashboards Management data sources main screen]({{site.url}}{{site.baseurl}}/images/dashboards/data_sources_management.png){: width="700" } ## Getting started -The following tutorial guides you through configuring and using multiple data sources. +The following tutorial guides you through configuring and using multiple data sources in OpenSearch Dashboards. + +The following features are not supported when using multiple data sources: timeline visualization types. +{: .note} ### Step 1: Modify the YAML file settings To use multiple data sources, you must enable the `data_source.enabled` setting. It is disabled by default. To enable multiple data sources: 1. Open your local copy of the OpenSearch Dashboards configuration file, `opensearch_dashboards.yml`. If you don't have a copy, [`opensearch_dashboards.yml`](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml) is available on GitHub. -2. Set `data_source.enabled:` to `true` and save the YAML file. +2. Set `data_source.enabled:` to `true` and save the YAML file. 3. Restart the OpenSearch Dashboards container. 4. Verify that the configuration settings were configured properly by connecting to OpenSearch Dashboards and viewing the **Dashboards Management** navigation menu. **Data sources** appears in the sidebar. You'll see a view similar to the following image. - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/multidatasources.png" alt="Data sources in sidebar within Dashboards Management" width="700"> +![Data sources in sidebar within Dashboards Management]({{site.url}}{{site.baseurl}}/images/dashboards/data_sources_management.png){: width="700" } ### Step 2: Create a new data source connection @@ -36,50 +38,52 @@ A data source connection specifies the parameters needed to connect to a data so To create a new data source connection: 1. From the OpenSearch Dashboards main menu, select **Dashboards Management** > **Data sources** > **Create data source connection**. -2. Add the required information to each field to configure **Connection Details** and **Authentication Method**. - - - Under **Connection Details**, enter a title and endpoint URL. For this tutorial, use the URL `http://localhost:5601/app/management/opensearch-dashboards/dataSources`. Entering a description is optional. + +2. Add the required information to each field to configure the **Connection Details** and **Authentication Method**. + + - Under **Connection Details**, enter a title and endpoint URL. For this tutorial, use the URL `https://localhost:9200/`. Entering a description is optional. - Under **Authentication Method**, select an authentication method from the dropdown list. Once an authentication method is selected, the applicable fields for that method appear. You can then enter the required details. The authentication method options are: - - **No authentication**: No authentication is used to connect to the data source. - - **Username & Password**: A basic username and password are used to connect to the data source. - - **AWS SigV4**: An AWS Signature Version 4 authenticating request is used to connect to the data source. AWS Signature Version 4 requires an access key and a secret key. - - For AWS Signature Version 4 authentication, first specify the **Region**. Next, select the OpenSearch service in the **Service Name** list. The options are **Amazon OpenSearch Service** and **Amazon OpenSearch Serverless**. Last, enter the **Access Key** and **Secret Key** for authorization. - + - **No authentication**: No authentication is used to connect to the data source. + - **Username & Password**: A basic username and password are used to connect to the data source. + - **AWS SigV4**: An AWS Signature Version 4 authenticating request is used to connect to the data source. AWS Signature Version 4 requires an access key and a secret key. + - For AWS Signature Version 4 authentication, first specify the **Region**. Next, select the OpenSearch service from the **Service Name** list. The options are **Amazon OpenSearch Service** and **Amazon OpenSearch Serverless**. Last, enter the **Access Key** and **Secret Key** for authorization. + For information about available AWS Regions for AWS accounts, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions). For more information about AWS Signature Version 4 authentication requests, see [Authenticating Requests (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html). {: .note} - After you have entered the appropriate details in all of the required fields, the **Test connection** and **Create data source** buttons become active. You can select **Test connection** to confirm that the connection is valid. -3. Select **Create data source** to save your settings. The connection is created. The active window returns to the **Data Sources** main page, and the new connection appears in the list of data sources. +3. Select **Create data source** to save your settings. The connection is created, and the new data source appears in the list on the **Data Sources** main page. The first data source you create is marked as your default. 4. Edit or update a data source connection. - - To make changes to the data source connection, select a connection in the list on the **Data Sources** main page. The **Connection Details** window opens. + - On the **Data Sources** main page, select the connection you want to modify. The **Connection Details** window opens. + + - To mark the selected data source as the default, select the **Set as default** option. - To make changes to **Connection Details**, edit one or both of the **Title** and **Description** fields and select **Save changes** in the lower-right corner of the screen. You can also cancel changes here. To change the **Authentication Method**, choose a different authentication method, enter your credentials (if applicable), and then select **Save changes** in the lower-right corner of the screen. The changes are saved. - When **Username & Password** is the selected authentication method, you can update the password by choosing **Update stored password** next to the **Password** field. In the pop-up window, enter a new password in the first field and then enter it again in the second field to confirm. Select **Update stored password** in the pop-up window. The new password is saved. Select **Test connection** to confirm that the connection is valid. - - When **AWS SigV4** is the selected authentication method, you can update the credentials by selecting **Update stored AWS credential**. In the pop-up window, enter a new access key in the first field and a new secret key in the second field. Select **Update stored AWS credential** in the pop-up window. The new credentials are saved. Select **Test connection** in the upper-right corner of the screen to confirm that the connection is valid. -5. Delete the data source connection by selecting the check box to the left of the title and then choosing **Delete 1 connection**. Selecting multiple check boxes for multiple connections is supported. Alternatively, select the trash can icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/}). +5. Delete the data source connection by selecting the check box to the left of the title and then choosing **Delete 1 connection**. Selecting multiple check boxes for multiple connections is supported. Alternatively, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/} (trash can) icon. -An example data source connection screen is shown in the following image. +A data source connection interface is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/data-source-connection.png" alt="Data source connection screen" width="700"> +![Data source connection screen]({{site.url}}{{site.baseurl}}/images/dashboards/data_source_connection.png){: width="700" } ### Selecting multiple data sources through the Dev Tools console -Alternatively, you can select multiple data sources through the [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index-dev/) console. This option provides for working with a broader range of data and gaining deeper insight into your code and applications. +Alternatively, you can select multiple data sources through the [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index/) console. This option allows you to work with a broader range of data and gaining a deeper understanding of your code and applications. Watch the following 10-second video to see it in action. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/multidata-dev-tools.gif" alt="Multiple data sources in Dev Tools demo">{: .img-fluid} +![Multiple data sources in Dev Tools demo]({{site.url}}{{site.baseurl}}/images/dashboards/multidata-dev-tools.gif) To select a data source through the Dev Tools console, follow these steps: -1. Locate your copy of `opensearch_dashboards.yml` and open it in the editor of your choice. +1. Locate your copy of `opensearch_dashboards.yml` and open it in the editor of your choice. 2. Set `data_source.enabled` to `true`. 3. Connect to OpenSearch Dashboards and select **Dev Tools** in the menu. 4. Enter the following query in the editor pane of the **Console** and then select the play button: @@ -92,33 +96,251 @@ To select a data source through the Dev Tools console, follow these steps: 5. From the **Data source** dropdown menu, select a data source and then query the source. 6. Repeat the preceding steps for each data source you want to select. -### Upload saved objects to a dashboard from connected data sources -To upload saved objects from connected data sources to a dashboard with multiple data sources, export them as an NDJSON file from the data source's **Saved object management** page. Then upload the file to the dashboard's **Saved object management** page. This method can make it easier to transfer saved objects between dashboards. The following 20-second video shows this feature in action. +--- +## Uploading saved objects to a dashboard from connected data sources -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/import_saved_objects_with_file_upload.gif" alt="Multiple data sources in Saved object management">{: .img-fluid} +To upload saved objects from connected data sources to a dashboard with multiple data sources, export them as an NDJSON file from the data source's **Saved object management** page. Then upload the file to the dashboard's **Saved object management** page. This method can simplify the transfer of saved objects between dashboards. The following 20-second video shows this feature in action. + +![Multiple data sources in Saved object management]({{site.url}}{{site.baseurl}}/images/dashboards/import_saved_objects_with_file_upload.gif) + +### Importing saved objects from a connected data source Follow these steps to import saved objects from a connected data source: -1. Locate your `opensearch_dashboards.yml` file and open it in your preferred text editor. +1. Locate your `opensearch_dashboards.yml` file and open it in your preferred text editor. 2. Set `data_source.enabled` to `true`. 3. Connect to OpenSearch Dashboards and go to **Dashboards Management** > **Saved objects**. 4. Select **Import** > **Select file** and upload the file acquired from the connected data source. 5. Choose the appropriate **Data source** from the dropdown menu, set your **Conflict management** option, and then select the **Import** button. -## Next steps +--- -Once you've configured your multiple data sources, you can start exploring that data. See the following resources to learn more: +## Showing or hiding authentication methods +Introduced 2.13 +{: .label .label-purple } -- Learn about [managing index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) through OpenSearch Dashboards. -- Learn about [indexing data using Index Management]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/index/) through OpenSearch Dashboards. -- Learn about how to [connect OpenSearch and Amazon S3 through OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/management/S3-data-source/). -- Learn about the [Integrations tool]({{site.url}}{{site.baseurl}}/integrations/index/), which gives you the flexibility to use various data ingestion methods and connect data from the Dashboards UI. +A feature flag in your `opensearch_dashboards.yml` file allows you to show or hide authentication methods within the `data_source` plugin. The following setting hides the authentication method for `AWSSigV4`. -## Limitations +```` +# Set enabled to false to hide the authentication method from multiple data source in OpenSearch Dashboards. +# If this setting is commented out, then all three options will be available in OpenSearch Dashboards. +# The default value will be considered as true. +data_source.authTypes: + NoAuthentication: + enabled: true + UsernamePassword: + enabled: true + AWSSigV4: + enabled: false +```` -This feature has some limitations: +The following demo shows this process. -* The multiple data sources feature is supported for index-pattern-based visualizations only. -* The visualization types Time Series Visual Builder (TSVB), Vega and Vega-Lite, and timeline are not supported. -* External plugins, such as Gantt chart, and non-visualization plugins, such as the developer console, are not supported. +![Multiple data sources hide and show authentication]({{site.url}}{{site.baseurl}}/images/dashboards/multidata-hide-show-auth.gif) + +## Showing or hiding the local cluster +Introduced 2.13 +{: .label .label-purple } + +A feature flag in your `opensearch_dashboards.yml` file allows you to hide the local cluster option within the `data_source` plugin. This option hides the local cluster from the data source dropdown menu and index creation page, which is ideal for environments with or without a local OpenSearch cluster. The following example setting, shown in a 20-second demo, hides the local cluster: + +```` +# hide local cluster in the data source dropdown and index pattern creation page. +data_source.hideLocalCluster: true +```` + +The following demo shows this process. + +![Multiple data sources hide local cluster]({{site.url}}{{site.baseurl}}/images/dashboards/multidata-hide-localcluster.gif) + +--- + +## Using multiple data sources with external dashboards plugins +Introduced 2.14 +{: .label .label-purple} + +The following plugins now support multiple data sources. + +### Index management + +When you set `data_source.enabled:true`, you can view and select data sources and their associated indexes directly from the interface: + +1. Navigate to **Management** > **Index Management** under the main menu. +2. Select **Indexes** from the sidebar menu and then select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} (database) icon on the upper-right menu bar. +3. Choose the appropriate data source from the dropdown menu and then choose the appropriate index from the list. By default, the indexes from your default data source are displayed. You can choose any connected data source to view its corresponding indexes. + +The following GIF illustrates these steps. + +![Multiple data sources in ISM list page]({{site.url}}{{site.baseurl}}/images/dashboards/ism_mds1.gif) + +To perform operations on a specific index within a data source, select the individual index from the list. To create a new index, select the **Create Index** button, which opens a form. Enter the required information and select the **Create** button. The index is created within the selected data source. The following GIF illustrates these steps. + +![Multiple data sources in ISM create page]({{site.url}}{{site.baseurl}}/images/dashboards/ism_mds2.gif) + +### Anomaly detection + +When you set `data_source.enabled:true`, you can create or view detectors associated with a data source: + +1. Navigate to **OpenSearch Plugins** > **Anomaly Detection** under the main menu. +2. Select the database icon on the upper-right menu bar to view a list of connected data sources. +3. Select a data source to view a list of associated detectors. If the selected data source does not have detectors, then the **Create detector** button appears under the upper-right menu bar. See [Creating anomaly detectors]({{site.url}}{{site.baseurl}}/observing-your-data/ad/dashboards-anomaly-detection/#creating-anomaly-detectors) for instructions on creating detectors through the interface. + +The following GIF illustrates these steps. + +![Multiple data sources in Anomaly Detection dashboard page]({{site.url}}{{site.baseurl}}/images/dashboards/ad_mds1.gif) + +You can edit the data source's associated detectors on the **Detectors** tab under the left side bar. + +1. Select **Detectors** and then select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} (database) icon on the upper-right menu bar. +2. From the dropdown menu, select the appropriate data source. A list of associated detectors appears. +3. Choose a detector from the list, select **Actions**, and then choose the appropriate edit option from the dropdown menu. +4. Enter the applicable settings and configuration details. + +The following GIF illustrates these steps. + +![Multiple data sources in Anomaly Detection detector page]({{site.url}}{{site.baseurl}}/images/dashboards/ad_mds2.gif) + +### Security + +When you set `data_source.enabled:true`, you can view and manage roles for each connected data source: + +1. Navigate to **Management** > **Security** under the main menu. +2. Select **Roles** from the left sidebar menu and then select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} (database) icon on the upper-right menu bar. +3. From the dropdown menu, select the appropriate data source and then select the **Create role** button to add a new role. +4. Enter the required configuration information and select the **Create** button to save. + +The following GIF illustrates these steps. + +![Multiple data sources in Security plugin]({{site.url}}{{site.baseurl}}/images/dashboards/security_mds1.gif) + +### Maps + +When you set `data_source.enabled:true`, you can view all available data sources, including the ones currently used as layers, in a map: + +1. Navigate to **OpenSearch Plugins** > **Maps** under the main menu. +2. From the dropdown menu, select the appropriate data source to edit or create an associated map layer: + - Edit a map layer by selecting one from the **Layers** dropdown menu. In the pop-up window, view the settings and edit them as needed. + - Add a new layer by selecting the **Add layer** button from the dropdown menu and then selecting **Documents** in the pop-up window. Another pop-up window appears on the right. Enter the required information on the **Data** tab. Note that the data source name is prefixed to the index pattern name. The **Style** and **Settings** tabs include optional information. + - Select **Update** to save the settings. +3. Select the **Save** button on the menu bar to save the edited or new layer. +4. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon on the upper-right menu bar to verify that the new data source is listed in the dropdown menu. + +The following GIF illustrates these steps. + +![Multiple data sources in Maps plugin]({{site.url}}{{site.baseurl}}/images/dashboards/maps_mds1.gif) + +### Machine learning + +When you set `data_source.enabled:true`, you can view and manage machine learning models from different connected data sources: + +1. Navigate to **OpenSearch Plugins** > **Machine Learning** under the main menu. +2. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon and choose a data source from the dropdown menu. A list of models associated with the selected data source is displayed. +3. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/inspect-icon.png" class="inline-icon" alt="inspect icon"/>{:/} icon to the right of a listed model to view the model's configuration details for the selected data source. + +The following GIF illustrates these steps. + +![Multiple data sources in Machine Learning Plugin]({{site.url}}{{site.baseurl}}/images/dashboards/ml_mds1.gif) + +### Notifications + +When you set `data_source.enabled:true`, you can view and manage notification channels for different data sources: + +1. Navigate to **Management** > **Notifications** under the main menu. +2. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon and choose a data source from the dropdown menu. A list of channels associated with the selected data source is displayed. +3. Choose a channel from the list to view or manage its settings. + - Edit the channel's settings by selecting the **Actions** button and choosing the **Edit** option. Enter the required information in the **Edit channel** panel and then choose **Save**. + - Send a test message to the channel by selecting the **Send test message** button in the **Edit channel** window. Alternatively, you can select the **Actions** button in the channel details window and then choose the **Send test message** option from the dropdown menu. + +The following GIF illustrates these steps. + +![Multiple data sources in Notification plugin]({{site.url}}{{site.baseurl}}/images/dashboards/notification_mds1.gif) + +### Search relevance + +When you set `data_source.enabled:true`, you can compare search results across indexes from different data sources: + +1. Navigate to **OpenSearch Plugins** > **Search Relevance** under the main menu. +2. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon and choose a data source from the dropdown menu. A list of available data sources is displayed. +3. Under both **Query 1** and **Query 2**, select a data source and an index. +4. Select the **Search** button to run the queries. The query results are displayed in their respective results panels. + +The following GIF illustrates these steps. + +![Multiple data sources in Search Relevance plugin]({{site.url}}{{site.baseurl}}/images/dashboards/searchrelevance_mds1.gif) + +### Security Analytics +Introduced 2.15 +{: .label .label-purple} + +When you set `data_source.enabled:true`, you can view and manage Security Analytics resources, such as detection rules, across multiple connected data sources: + +1. Navigate to **OpenSearch Plugins** > **Security Analytics** under the main menu. +2. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon and choose a data source from the dropdown menu. +3. Select **Detectors** > **Detection rules** from the navigation menu on the left. A list of detection rules is displayed. +4. Select a rule to open a pop-up window containing more information about that rule. + +The following GIF illustrates these steps. + +![Multiple data sources in Security Analytics list page]({{site.url}}{{site.baseurl}}/images/dashboards/mds_sa_detection_rules_view.gif) + +1. Navigate to **OpenSearch Plugins** > **Security analytics** under the main menu. +2. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon and choose a data source from the dropdown menu. +3. Select **Detectors** > **Detection rules** from the navigation menu on the left. +4. Select the **Create detection rule** button on the upper right and then enter the required configuration details in the **Create detection rule** window. +5. Select the **Create detection rule** button on the lower right to save the rule. The rule is now associated with the data source. + +The following GIF illustrates these steps. + +![Multiple data sources in Security Analytics create page]({{site.url}}{{site.baseurl}}/images/dashboards/mds_sa_detection_rules_create.gif) + +### Alerting +Introduced 2.15 +{: .label .label-purple } + +When you set `data_source.enabled:true`, you can you can view and manage alerting monitors across multiple connected data sources: + +1. Navigate to **OpenSearch Plugins** > **Alerting** under the main menu. +2. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/database-icon.png" class="inline-icon" alt="database icon"/>{:/} icon and choose a data source from the dropdown menu. A list of associated monitors is displayed. +3. Select a monitor to view its details. + +The following GIF illustrates these steps. + +![Multiple data sources in Alerting list page]({{site.url}}{{site.baseurl}}/images/dashboards/mds_monitor_view.gif) + +To create a new monitor, select **Create monitor**. Fill out the form and select **Create**. The monitor is created within the selected data source. + +#### Managing alerting monitors from within the Dashboards application + +To manage data source monitors from within **Dashboards**: + +1. Navigate to the **Dashboards** application under the main menu and then select a dashboard from the list. +2. From the dashboard, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/} (ellipsis) icon to open the **Options** dropdown menu and then choose **Alerting**. +4. From the **Alerting** dropdown menu, choose **Associated monitors** to open the configuration window. +5. Select a monitor from the list to view or edit its details. + +The following GIF illustrates these steps. + +![Multiple data sources with Feature anywhere associated monitor]({{site.url}}{{site.baseurl}}/images/dashboards/mds_feature_anywhere_view_alerting.gif) + +To associate a monitor with a data source: + +1. Navigate to the **Dashboards** application under the main menu and then select a dashboard from the list. +2. From the dashboard, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/} (ellipsis) icon to open the **Options** dropdown menu and then choose **Alerting**. +3. From the **Alerting** dropdown menu, choose **Add alerting monitor** to open the configuration window. +4. Enter the configuration information and then select the **Create monitor** button. The monitor is now associated with the data source. + +The following GIF illustrates these steps. + +![Multiple data sources with Feature anywhere add associated monitor]({{site.url}}{{site.baseurl}}/images/dashboards/mds_feature_anywhere_create_alerting.gif) + +--- + +## Next steps + +After configuring multiple data sources, you can analyze the data from each source. See the following resources for more information: + +- [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) +- [Index Management]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/index/) +- [Connecting OpenSearch and Amazon S3 through OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/management/S3-data-source/) +- [OpenSearch Integrations]({{site.url}}{{site.baseurl}}/integrations/index/) diff --git a/_dashboards/management/query-data-source.md b/_dashboards/management/query-data-source.md index f1496b3e..4840c7db 100644 --- a/_dashboards/management/query-data-source.md +++ b/_dashboards/management/query-data-source.md @@ -2,7 +2,7 @@ layout: default title: Query and visualize Amazon S3 data parent: Connecting Amazon S3 to OpenSearch -grand_parent: Data sources +grand_parent: Connecting data sources nav_order: 10 has_children: false --- @@ -11,7 +11,7 @@ has_children: false Introduced 2.11 {: .label .label-purple } -This tutorial guides you through using the **Query data** use case for querying and visualizing your Amazon Simple Storage Service (Amazon S3) data using OpenSearch Dashboards. +This tutorial guides you through using the **Query data** use case for querying and visualizing your Amazon Simple Storage Service (Amazon S3) data using OpenSearch Dashboards. ## Prerequisites @@ -22,15 +22,9 @@ You must be using the `opensearch-security` plugin and have the appropriate role To get started, follow these steps: 1. On the **Manage data sources** page, select your data source from the list. -2. On the data source's detail page, select the **Query data** card. This option takes you to the **Observability** > **Logs** page, which is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/observability-logs-UI.png" alt="Observability Logs UI" width="700"> - +2. On the data source's detail page, select the **Query data** card. This option takes you to the **Observability** > **Logs** page. 3. Select the **Event Explorer** button. This option creates and saves frequently searched queries and visualizations using [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) or [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/index/), which connects to Spark SQL. -4. Select the Amazon S3 data source from the dropdown menu in the upper-left corner. An example is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-data-sources-UI-2.png" alt="Observability Logs Amazon S3 dropdown menu" width="700"> - +4. Select the Amazon S3 data source from the dropdown menu in the upper-left corner. 5. Enter the query in the **Enter PPL query** field. Note that the default language is SQL. To change the language, select PPL from the dropdown menu. 6. Select the **Search** button. The **Query Processing** message is shown, confirming that your query is being processed. 7. View the results, which are listed in a table on the **Events** tab. On this page, details such as available fields, source, and time are shown in a table format. @@ -40,11 +34,8 @@ To get started, follow these steps: To create visualizations, follow these steps: -1. On the **Explorer** page, select the **Visualizations** tab. An example is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/explorer-S3viz-UI.png" alt="Explorer Amazon S3 visualizations UI" width="700"> - -2. Select **Index data to visualize**. This option currently only creates [acceleration indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/), which give you views of the data visualizations from the **Visualizations** tab. To create a visualization of your Amazon S3 data, go to **Discover**. See the [Discover documentation]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) for information and a tutorial. +1. On the **Explorer** page, select the **Visualizations** tab. +2. Select **Index data to visualize**. This option creates an [acceleration index]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/) that stores your Amazon S3 data in OpenSearch. After the acceleration index is created, visualize its data on the **Visualizations** tab. ## Use Query Workbench with your Amazon S3 data source @@ -53,14 +44,12 @@ To create visualizations, follow these steps: To use Query Workbench with your Amazon S3 data, follow these steps: 1. From the OpenSearch Dashboards main menu, select **OpenSearch Plugins** > **Query Workbench**. -2. From the **Data Sources** dropdown menu in the upper-left corner, choose your Amazon S3 data source. Your data begins loading the databases that are part of your data source. An example is shown in the following image. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-workbench-S3.png" alt="Query Workbench Amazon S3 data loading UI" width="700"> - +2. From the **Data Sources** dropdown menu in the upper-left corner, choose your Amazon S3 data source. Your data begins loading the databases that are part of your data source. 3. View the databases listed in the left-side navigation menu and select a database to view its details. Any information about acceleration indexes is listed under **Acceleration index destination**. 4. Choose the **Describe Index** button to learn more about how data is stored in that particular index. 5. Choose the **Drop index** button to delete and clear both the OpenSearch index and the Amazon S3 Spark job that refreshes the data. -6. Enter your SQL query and select **Run**. +6. Enter your SQL query and select **Run**. + ## Next steps - Learn about [accelerating the query performance of your external data sources]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/). diff --git a/_dashboards/management/resource-sharing.md b/_dashboards/management/resource-sharing.md new file mode 100644 index 00000000..7784f66f --- /dev/null +++ b/_dashboards/management/resource-sharing.md @@ -0,0 +1,155 @@ +--- +layout: default +title: Resource access management +parent: Dashboards management +nav_order: 30 +--- + +# Resource access management +**Introduced 3.3** +{: .label .label-purple } + +Resource sharing in OpenSearch Dashboards provides fine-grained, document-level access control for individual resources that plugins define. This feature extends OpenSearch's role-based access control by allowing resource owners to specify who can access a resource and what level of access they have, including read-only or read-write permissions. Use OpenSearch Dashboards for everyday access management and the **Dev Tools** console for automation and batch operations. + +If resource sharing features are not visible in OpenSearch Dashboards, contact your OpenSearch administrator to enable the capability and assign appropriate permissions. +{: .note} + +A **resource** is a document that a plugin creates and stores in a protected system index, such as a machine learning (ML) model group, an anomaly detector, a report definition, or a Flow Framework workflow. + +The following table lists the default resource access, which is determined by the user's role and relationship to the resource. + +| User | Access | +|---|---| +| Resource creator | Full access (view, edit, delete, and share) | +| Superadmin | Full access | +| Other users | No access unless the resource is shared with them | + +After you share a resource with specific users, roles, or backend roles, it becomes visible to those users in OpenSearch Dashboards, which filters resource lists based on each user's identity, permissions, and the resource sharing configuration. + +## Prerequisites + +To use resource sharing in OpenSearch Dashboards, you must meet the following prerequisites: + +* An administrator has granted you the cluster permissions for the resource's plugin. You need these permissions to create resources. +* You own the resource, you are a superadmin, or the owner has shared the resource with you. +* An administrator has enabled the following settings: + ```yaml + plugins.security.resource_sharing.enabled: true + plugins.security.resource_sharing.protected_types: ["<resource-type>"] + plugins.security.system_indices.enabled: true + ``` + {% include copy.html %} + + For more information about these settings, see [Configuring resource sharing]({{site.url}}{{site.baseurl}}/security/access-control/resources/#configuring-resource-sharing). + +## Managing access for all resource types + +The **Resource Access Management** page lists the resources of any protected type that you can access and lets you manage sharing for them in one place. Follow these steps to view and manage access for a resource: + +1. On the top menu, go to **Management** > **Resource Access Management**. + +1. In the **Resources** panel, in the upper-right corner, select a resource type from the dropdown list. The table lists the resources of that type that you can access and shows the owner of each resource in the **Owner** column. The **Shared With** column lists the users, roles, and backend roles that the resource is shared with, along with their access levels, or **Not shared** if the resource is private. If no resources appear, create a resource or ask an administrator or the resource owner to share one with you. + + The following image shows the **Resources** panel for the anomaly detector resource type. + + ![Resources panel listing anomaly detectors with their resource IDs, owners, and the users and roles that each detector is shared with]({{site.url}}{{site.baseurl}}/images/resource-sharing/4-after-selecting-resource.png) + +1. In the **Actions** column, select **Share** for a private resource or **Update Access** for a resource that is already shared. These options appear only for resources that you own or that the owner granted you share permission for. Superadmins can share any resource. + +1. In the **Share Resource** or **Update Access** dialog, from the **Access-level** dropdown list, select an access level. In the **Share Resource** dialog, first select **Add access-level** to display the fields. + +1. Enter the users, roles, and backend roles that you want to grant this level of access to in the **Users**, **Roles**, and **Backend roles** fields. To grant access to all users, enter an asterisk (`*`) in the **Users** field. + +1. To grant a different level of access to another set of users, select **Add access-level** and repeat the preceding two steps. To delete an access level, select **Remove**. + +1. Select **Share** or **Update Access** to apply the changes. Removing access immediately hides the resource from the affected users. + +## Managing access from a plugin page +**Introduced 3.9** +{: .label .label-purple } + +You can manage access to a resource directly from the plugin's resource list when resource sharing is enabled for the resource type. + +The following table lists the resources that support access management from their plugin's resource list and links to the access levels available for each one. + +| Plugin | Resources | +|---|---| +| Alerting | [Monitors and workflows]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/alerting-access-control/) | +| Anomaly Detection | [Detectors]({{site.url}}{{site.baseurl}}/observing-your-data/ad/detector-access-control/) and [forecasters]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/forecaster-access-control/) | +| Flow Framework | [Workflows]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/workflow-access-control/) | +| ML Commons | [Model groups]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-sharing-access-control/) | +| Notifications | [Channels]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/notification-access-control/) | +| Reporting | [Report definitions]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-definition-access-control/) and [reports]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-instance-access-control/) | +| Security Analytics | [Detectors and correlation rules]({{site.url}}{{site.baseurl}}/security-analytics/resource-access-control/) | + +You can share a resource only if you are its owner, a superadmin, or a user to whom the owner granted share permission. +{: .note} + +### Sharing a resource + +To share a resource from a plugin page, follow these steps: + +1. Open the resource list for a supported plugin. For example, on the top menu, go to **OpenSearch Plugins** > **Anomaly Detection**, and then select **Detectors**. + +1. In the **Access** column, review the sharing status for each resource. Each resource displays a status of **Private** or **Shared**. Resources that you have permission to share also display a share icon, as shown in the following image. + + ![Detectors list showing the Access column with Private and Shared statuses and share icons]({{site.url}}{{site.baseurl}}/images/resource-sharing/share-button-access-column.png) + +1. Select the share icon for the resource that you want to manage. + +1. In the **Manage access** dialog, configure the following values: + + 1. From the **Access level** dropdown list, select an access level. The available levels vary by resource type. + + 1. In the **Users** field, enter a username and press Enter. To share the resource with all users at the selected access level, enter an asterisk (`*`). + + 1. To share the resource with roles or backend roles, expand **Advanced access options** and enter the role names in the **Roles** or **Backend roles** field. + + 1. To share the resource at more than one access level, select **Add access level** and repeat the preceding steps. Each level maintains its own users, roles, and backend roles. To delete a level, select **Remove level**. + + 1. Select **Save changes**. + +### Making a resource private + +To stop sharing a resource, follow these steps: + +1. In the **Access** column, select the share icon for the resource. + +1. In the **Remove all sharing** section of the **Manage access** dialog, select **Remove access**. + +The resource status returns to **Private**, and the users, roles, and backend roles that it was shared with can no longer access it. + +## Listing resources shared with you + +OpenSearch Dashboards shows only the resources that you can access, so no additional actions are required. A resource appears in your resource lists in any of the following cases: + +* You own the resource. +* The owner has explicitly shared the resource with you. +* The owner has shared the resource with one of your roles or backend roles. +* The resource is shared with all users. + +In all cases, listing a resource also requires the cluster permissions for the resource's plugin. + +## Managing resource sharing using APIs + +You can manage resource sharing programmatically using REST APIs. These operations can only be performed if you are the owner, a superadmin, or have sharing access to the resource. You can use the command line or the **Dev Tools** console to send API requests. + +For complete API documentation, including endpoints, parameters, and examples, see [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/). + +## Troubleshooting + +Use the following table to troubleshoot common issues. + +| Issue | Possible cause | Fix | +|---|---|---| +| The **Resource Access Management** page is not visible. | The feature is disabled. | Ask an administrator to enable `plugins.security.resource_sharing.enabled`. | +| You can't create a resource. | You don't have the cluster permissions for the resource's plugin. | Ask an administrator to map you to a role that grants those permissions. | +| You can't access a resource. | The resource is not shared with you. | Ask the owner to share the resource with you at the appropriate access level. | +| An API request returns a `403` error. | The resource is not shared with you. | Ask the owner to share the resource with you at the appropriate access level. | +| A resource is not listed in OpenSearch Dashboards. | The resource type is not marked as protected. | Ask an administrator to add the resource type to `plugins.security.resource_sharing.protected_types`. | +| Updating access has no effect. | The access level is not valid for the resource type. | Verify the access level against the documentation for the resource's plugin. | + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management \ No newline at end of file diff --git a/_dashboards/management/saved-objects-api.md b/_dashboards/management/saved-objects-api.md new file mode 100644 index 00000000..ffe54276 --- /dev/null +++ b/_dashboards/management/saved-objects-api.md @@ -0,0 +1,619 @@ +--- +layout: default +title: Saved Objects APIs +parent: Saved objects +grand_parent: Dashboards management +nav_order: 15 +--- + +# Saved Objects APIs + +Use the Saved Objects APIs to list, retrieve, create, update, export, and import saved objects, for example to copy a set of visualizations between clusters or to inventory the visualizations that a cluster contains. + +These endpoints are served by OpenSearch Dashboards rather than by OpenSearch, so send them to the OpenSearch Dashboards host and port (`5601` by default) instead of the OpenSearch REST port. Requests that use `POST`, `PUT`, or `DELETE` require the `osd-xsrf: true` header. Scripts written for Kibana OSS send the `kbn-xsrf: true` header instead, and OpenSearch Dashboards rejects these requests with the error `Request must contain a osd-xsrf header`. To fix this error, replace `kbn-xsrf` with `osd-xsrf` in your scripts. + +Send these requests using `curl`, as shown in the examples on this page. To run a `GET` endpoint without `curl`, enter its full URL in the address bar of a browser in which you are signed in to OpenSearch Dashboards. + +The Dev Tools console cannot call these endpoints because it forwards every request to the OpenSearch REST port, where the saved objects paths do not exist. +{: .note} + +If the Security plugin is enabled, pass credentials using the `-u` option and add `-k` if the cluster uses a self-signed certificate: + +```bash +curl -k -u admin:<password> "https://localhost:5601/api/saved_objects/_find?type=visualization" +``` +{% include copy.html %} + +If OpenSearch Dashboards is served from a base path, such as when it runs behind a proxy or on a managed service, include that base path in the request, for example, `https://<host>/_dashboards/api/saved_objects/_find`. + +These APIs return the definition of a visualization, such as its aggregations and its index pattern reference. They do not run the visualization or return the data it displays. To export the underlying rows of a saved search as a CSV or Excel file, see [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/). +{: .note} + +To export and import the same objects from OpenSearch Dashboards instead, see [Exporting and importing saved objects]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects/). + +## Selecting a tenant + +When multi-tenancy is enabled, each tenant has its own set of saved objects. Send the tenant name in the `securitytenant` header to work with the saved objects of a specific tenant: + +```bash +curl -k -u admin:<password> -H 'securitytenant: global' "https://localhost:5601/api/saved_objects/_find?type=dashboard&fields=title" +``` +{% include copy.html %} + +Use `global` for the global tenant and `__user__` for the requesting user's private tenant. + +A request that omits the header is served by the first of the following tenants that applies: + +1. The tenant recorded in the request's session cookie. +2. The default tenant configured for the cluster. +3. The first tenant in the preferred tenant list that the user can access. +4. The global tenant. +5. The requesting user's private tenant. + +A `curl` request carries no session cookie, so under the default configuration it is served by the global tenant. + +Passing the tenant as a query parameter does not work, because the saved objects endpoints do not define one: a `securitytenant` or `security_tenant` query parameter is rejected with a `400` error. For more information about tenants, see [OpenSearch Dashboards multi-tenancy]({{site.url}}{{site.baseurl}}/security/multi-tenancy/tenant-index/). + +## Find saved objects + +The Find Saved Objects API searches for saved objects of one or more types. + +### Endpoint + +```json +GET {osd_host}:{port}/api/saved_objects/_find +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters except `type` are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `type` | String | The type of saved object to search for, such as `visualization`, `dashboard`, `search`, or `index-pattern`. Repeat the parameter to search multiple types. Required. | +| `search` | String | A query string used to filter results, such as `Sales*`. | +| `search_fields` | String | The fields to match the `search` value against, such as `title`. | +| `fields` | String | The object attributes to include in the response. Repeat the parameter to return multiple attributes. Returning only `title` keeps the response small. | +| `per_page` | Integer | The number of results per page. Default is `20`. | +| `page` | Integer | The page of results to return. Default is `1`. | +| `sort_field` | String | The field to sort results by, such as `updated_at`. | + +### Example request + +The following request lists the visualizations in the cluster and returns only their titles: + +```bash +curl "http://localhost:5601/api/saved_objects/_find?type=visualization&fields=title&per_page=5" +``` +{% include copy.html %} + +### Example response + +```json +{ + "page": 1, + "per_page": 5, + "total": 1, + "saved_objects": [ + { + "type": "visualization", + "id": "test-viz", + "attributes": { + "title": "Sales by customer" + }, + "references": [ + { + "name": "kibanaSavedObjectMeta.searchSourceJSON.index", + "id": "ecommerce-test-pattern", + "type": "index-pattern" + } + ], + "migrationVersion": { + "visualization": "7.10.0" + }, + "updated_at": "2026-09-02T19:35:47.635Z", + "version": "WzI5LDdd", + "namespaces": ["default"], + "score": null + } + ] +} +``` + +### Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `total` | Integer | The number of saved objects that matched the search. | +| `saved_objects` | Array | The matching saved objects. | +| `saved_objects.id` | String | The ID of the saved object. Use this ID as the report source ID when you create a report definition. | +| `saved_objects.type` | String | The type of the saved object. | +| `saved_objects.attributes` | Object | The definition of the saved object, filtered by the `fields` parameter. | +| `saved_objects.references` | Array | The other saved objects that this object depends on, such as its index pattern. | +| `saved_objects.updated_at` | String | The time at which the saved object was last updated. | + +## Get saved object + +The Get Saved Object API retrieves a single saved object by type and ID. + +### Endpoint + +```json +GET {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### Example request + +```bash +curl "http://localhost:5601/api/saved_objects/visualization/test-viz" +``` +{% include copy.html %} + +To retrieve several saved objects in one request, send their types and IDs to the `_bulk_get` endpoint: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_bulk_get" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '[{"type": "visualization", "id": "test-viz", "fields": ["title"]}]' +``` +{% include copy.html %} + +## Create saved object + +The Create Saved Object API creates a saved object. Provide an ID to control the object's ID, or omit it to have one generated. + +Creating an object with this API requires the same attributes that the application that owns the type expects, and those attributes are not part of a public contract. Export objects from a working instance and import them elsewhere rather than composing visualizations or dashboards by hand. +{: .note} + +### Endpoints + +```json +POST {osd_host}:{port}/api/saved_objects/{type} +POST {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `overwrite` | Boolean | Whether to replace an object that already has the specified ID. Default is `false`, which returns a `409` error when the ID is in use. | + +### Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `attributes` | Object | The definition of the object, in the format that the object's type expects. Required. | +| `references` | Array | The other saved objects that this object depends on, each with a `name`, a `type`, and an `id`. Optional. | + +### Example request + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/visualization/sales-by-region" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{ + "attributes": { + "title": "Sales by region", + "visState": "{\"type\":\"pie\"}", + "kibanaSavedObjectMeta": {"searchSourceJSON": "{}"} + }, + "references": [ + { + "name": "kibanaSavedObjectMeta.searchSourceJSON.index", + "type": "index-pattern", + "id": "ecommerce-test-pattern" + } + ] + }' +``` +{% include copy.html %} + +### Example response + +```json +{ + "type": "visualization", + "id": "sales-by-region", + "attributes": { + "title": "Sales by region", + "visState": "{\"type\":\"pie\"}", + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{}" + } + }, + "references": [ + { + "name": "kibanaSavedObjectMeta.searchSourceJSON.index", + "type": "index-pattern", + "id": "ecommerce-test-pattern" + } + ], + "migrationVersion": { + "visualization": "7.10.0" + }, + "updated_at": "2026-09-08T20:30:46.728Z", + "version": "WzcxLDhd", + "namespaces": ["default"] +} +``` + +To create several objects in one request, send them to the `_bulk_create` endpoint, which accepts the same `overwrite` parameter: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_bulk_create" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '[{"type": "visualization", "id": "sales-by-day", "attributes": {"title": "Sales by day", "visState": "{}", "kibanaSavedObjectMeta": {"searchSourceJSON": "{}"}}}]' +``` +{% include copy.html %} + +The response contains the created objects in a `saved_objects` array. + +## Update saved object + +The Update Saved Object API updates the attributes of an existing saved object. The fields that you send replace the corresponding fields of the object, and the fields that you omit are left unchanged. + +### Endpoint + +```json +PUT {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `attributes` | Object | The fields of the object to update. Required. | +| `references` | Array | The references to replace. Sending this field replaces the object's entire reference list. Optional. | + +### Example request + +```bash +curl -X PUT "http://localhost:5601/api/saved_objects/visualization/sales-by-region" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{"attributes": {"title": "Sales by region and month"}}' +``` +{% include copy.html %} + +### Example response + +The response contains the updated fields rather than the full object: + +```json +{ + "id": "sales-by-region", + "type": "visualization", + "updated_at": "2026-09-08T20:30:47.950Z", + "version": "WzczLDhd", + "namespaces": ["default"], + "attributes": { + "title": "Sales by region and month" + } +} +``` + +## Delete saved object + +The Delete Saved Object API deletes a saved object. Deleting an object that others reference, such as an index pattern used by a visualization, leaves those objects with a missing reference. Use the **Relationships** action in **Dashboards Management** > **Saved objects**, or the `references` field returned by the [Find Saved Objects API](#find-saved-objects), to check what depends on an object before you delete it. + +### Endpoint + +```json +DELETE {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### Example request + +```bash +curl -X DELETE "http://localhost:5601/api/saved_objects/visualization/sales-by-day" \ + -H 'osd-xsrf: true' +``` +{% include copy.html %} + +### Example response + +```json +{} +``` + +## Export saved objects + +The Export Saved Objects API exports saved objects as newline-delimited JSON (NDJSON). Each line is one saved object, and the final line summarizes the export. + +An export contains only the objects of the tenant that serves the request, so a backup of every tenant requires one request per tenant. For more information, see [Selecting a tenant](#selecting-a-tenant). + +### Endpoint + +```json +POST {osd_host}:{port}/api/saved_objects/_export +``` + +### Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `type` | String or Array | The types of saved object to export, such as `visualization`. Provide either `type` or `objects`. | +| `objects` | Array | The specific saved objects to export, each with a `type` and an `id`. Provide either `type` or `objects`. | +| `includeReferencesDeep` | Boolean | Whether to also export the objects that the exported objects depend on, such as their index patterns. Set to `true` so that the export can be imported into a cluster that does not already contain those references. Optional. Default is `false`. | +| `search` | String | A query string that limits the export to matching objects, such as `Sales*`. Use with `type`. Optional. | +| `excludeExportDetails` | Boolean | Whether to omit the summary line at the end of the output. Optional. Default is `false`. | +| `workspaces` | Array | The workspaces to export objects from. Use with `type`. Optional. | + +A request sent to a workspace path is limited to that workspace even when the request body omits `workspaces`: + +```json +POST {osd_host}:{port}/w/{workspace_id}/api/saved_objects/_export +``` +{% include copy.html %} + +The same path prefix associates imported objects with a workspace, so you can use it in place of the `workspaces` query parameter of the [Import Saved Objects API](#import-saved-objects). + +A request sent to a workspace path can export the objects of that workspace and objects that belong to no workspace. Requesting an object of a different workspace in `objects` returns the following error: + +```json +{"statusCode": 400, "error": "Bad Request", "message": "Bad Request", "attributes": {"objects": [{"id": "test-viz", "type": "visualization", "attributes": {}, "references": [], "error": {"statusCode": 403, "error": "Forbidden", "message": "Saved object does not belong to the workspace"}}]}} +``` + +### Example request + +The following request exports one visualization along with the index pattern it references: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_export" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{"objects": [{"type": "visualization", "id": "test-viz"}], "includeReferencesDeep": true}' \ + -o export.ndjson +``` +{% include copy.html %} + +To export every visualization instead of a specific one, replace `objects` with `"type": "visualization"`. + +### Example response + +The last line of the NDJSON output summarizes the export: + +```json +{"exportedCount": 2, "missingRefCount": 0, "missingReferences": []} +``` + +### Exporting all saved objects + +To back up an entire OpenSearch Dashboards instance, list the types to export: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_export" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{"type": ["config", "index-pattern", "search", "visualization", "dashboard", "url", "query"], "includeReferencesDeep": true}' \ + -o backup.ndjson +``` +{% include copy.html %} + +When multi-tenancy is enabled, repeat the request for each tenant, as described in [Selecting a tenant](#selecting-a-tenant). + +Installed plugins register additional types, so the types available in one instance can differ from those in another. To see the types that an instance contains, review the **Type** filter in **Dashboards Management** > **Saved objects**. Requesting a type that cannot be exported returns the following error: + +```json +{"statusCode": 400, "error": "Bad Request", "message": "Trying to export non-exportable type(s): bogus-type"} +``` + +## Import saved objects + +The Import Saved Objects API imports saved objects from an NDJSON file produced by the [Export Saved Objects API](#export-saved-objects) or by an export from **Dashboards Management** > **Saved objects**. Send the file as multipart form data in a `file` field. The file must use the `.ndjson` extension. + +### Endpoint + +```json +POST {osd_host}:{port}/api/saved_objects/_import +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `overwrite` | Boolean | Whether to replace saved objects that already exist. Default is `false`, which causes conflicting objects to be reported as errors instead of imported. Cannot be combined with `createNewCopies`. | +| `createNewCopies` | Boolean | Whether to import the objects under new IDs, preserving the existing objects. Cannot be combined with `overwrite`. | +| `dataSourceId` | String | The ID of the data source to attach the imported objects to when multiple data sources are enabled. | +| `workspaces` | String or Array | The workspaces to import the objects into. | + +### Example request + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_import?overwrite=true" \ + -H 'osd-xsrf: true' \ + --form file=@export.ndjson +``` +{% include copy.html %} + +### Example response + +```json +{ + "successCount": 2, + "success": true, + "successResults": [ + { + "type": "index-pattern", + "id": "ecommerce-test-pattern", + "meta": { + "title": "ecommerce-test", + "icon": "indexPatternApp" + }, + "overwrite": true + }, + { + "type": "visualization", + "id": "test-viz", + "meta": { + "title": "Sales by customer", + "icon": "visualizeApp" + }, + "overwrite": true + } + ] +} +``` + +### Import errors + +An import can fail for some objects and succeed for others. When any object fails, `success` is `false` and each failure appears in `errors` with an `error.type` field that identifies the cause: + +```json +{ + "successCount": 0, + "success": false, + "errors": [ + { + "id": "orphan-viz", + "type": "visualization", + "title": "Orphan", + "meta": { + "title": "Orphan", + "icon": "visualizeApp" + }, + "error": { + "type": "missing_references", + "references": [ + { + "type": "index-pattern", + "id": "does-not-exist" + } + ] + } + } + ] +} +``` + +The following table lists the most common error types. + +| Error type | Cause | Resolution | +| :--- | :--- | :--- | +| `missing_references` | The object refers to an object that the import does not contain and the target instance does not have, such as an index pattern. | Export the source objects again with `includeReferencesDeep` set to `true`, create the missing object, or ignore the reference using the [Resolve Import Errors API](#resolve-import-errors). | +| `conflict` | An object with the same type and ID already exists. | Retry with `overwrite=true` or `createNewCopies=true`. | +| `unsupported_type` | No installed plugin registers the object's type. | Install the plugin that provides the type or remove the object from the file. | + +Because the response returns a `200` status code even when objects fail to import, check the `success` field rather than the status code when you script an import. +{: .note} + +## Resolve import errors + +The Resolve Import Errors API retries a failed import with per-object instructions, such as overwriting a specific object or ignoring a missing reference. Send the same NDJSON file that the import used, along with a `retries` field that lists the objects to retry. + +### Endpoint + +```json +POST {osd_host}:{port}/api/saved_objects/_resolve_import_errors +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `createNewCopies` | Boolean | Whether to import the retried objects under new IDs. Default is `false`. | +| `dataSourceId` | String | The ID of the data source to attach the imported objects to. | +| `workspaces` | String or Array | The workspaces to import the objects into. | + +### Request body fields + +Send the following fields as multipart form data. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `file` | File | The NDJSON file that the failed import used. Required. | +| `retries` | Array | The objects to retry. Required. | +| `retries.type` | String | The type of the object to retry. Required. | +| `retries.id` | String | The ID of the object to retry. Required. | +| `retries.overwrite` | Boolean | Whether to replace the existing object. Default is `false`. | +| `retries.destinationId` | String | The ID to assign to the imported object. | +| `retries.replaceReferences` | Array | The references to repoint, each with a `type`, a `from` ID, and a `to` ID. | +| `retries.ignoreMissingReferences` | Boolean | Whether to import the object even though a reference is missing. | + +### Example request + +The following request retries a visualization whose index pattern is missing, importing it without the reference: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_resolve_import_errors" \ + -H 'osd-xsrf: true' \ + --form file=@export.ndjson \ + --form 'retries=[{"type": "visualization", "id": "orphan-viz", "ignoreMissingReferences": true}]' +``` +{% include copy.html %} + +### Example response + +```json +{ + "successCount": 1, + "success": true, + "successResults": [ + { + "type": "visualization", + "id": "orphan-viz", + "meta": { + "title": "Orphan", + "icon": "visualizeApp" + } + } + ] +} +``` + +## Limitations + +The following limits and caveats apply to the Saved Objects APIs. + +### File format + +The import endpoints accept only files with the `.ndjson` extension. A file with any other extension returns `{"statusCode": 400, "error": "Bad Request", "message": "Invalid file extension .json"}`. The legacy `/api/opensearch-dashboards/dashboards/export` endpoint produces a single JSON document instead of NDJSON, so its output cannot be imported with `_import`. Export the objects with `_export`, or from **Dashboards Management** > **Saved objects**, and import the resulting NDJSON file. + +### Request size + +The import endpoints are bounded by the `savedObjects.maxImportPayloadBytes` setting, which is `26214400` (25 MB) by default. The `server.maxPayloadBytes` setting, which is `1048576` (1 MB) by default, applies to other OpenSearch Dashboards routes and does not raise or lower the import limit. + +A `413 Request Entity Too Large` response for a file smaller than 25 MB usually comes from a proxy in front of OpenSearch Dashboards rather than from OpenSearch Dashboards itself. Raise the body size limit of the proxy, such as `client_max_body_size` in NGINX or `proxy-body-size` in an NGINX Ingress controller. + +### Object count + +A single export or import is limited to `10000` objects by the `savedObjects.maxImportExportSize` setting. Split larger transfers by type or by search term. + +### Conflicting parameters + +The `overwrite` and `createNewCopies` parameters cannot be used together. Sending both returns the following error: + +```json +{"statusCode": 400, "error": "Bad Request", "message": "[request query]: cannot use [overwrite] with [createNewCopies]"} +``` + +### Version compatibility + +Import an NDJSON file into an instance running the same version of OpenSearch Dashboards as the instance that exported it, or a later one. Objects are migrated forward as they are imported, but they cannot be migrated backward. An object exported from a later version fails with an error similar to the following: + +``` +Document "test-viz" has property "visualization" which belongs to a more recent version of OpenSearch Dashboards [7.10.0]. The last known version is [7.9.3] +``` + +## Related documentation + +- [Exporting and importing saved objects]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects/) +- [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/) +- [Access control lists for saved objects]({{site.url}}{{site.baseurl}}/dashboards/management/acl/) +- [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) diff --git a/_dashboards/management/saved-objects.md b/_dashboards/management/saved-objects.md new file mode 100644 index 00000000..72ff0f8c --- /dev/null +++ b/_dashboards/management/saved-objects.md @@ -0,0 +1,72 @@ +--- +layout: default +title: Saved objects +parent: Dashboards management +has_children: true +nav_order: 12 +--- + +# Saved objects + +_Saved objects_ are the OpenSearch Dashboards resources that you create and reuse, including visualizations, dashboards, saved searches, index patterns, and maps. Export them to a file and import that file into another instance to copy a dashboard from a development cluster to a production one, to move objects between tenants or workspaces, or to keep a backup of your visualizations. + +Objects depend on each other: a dashboard references its visualizations, and a visualization references its index pattern. Export an object together with the objects it references so that the export can be imported into an instance that does not already contain them. + +To perform these tasks programmatically, for example as part of a CI/CD pipeline, see [Saved Objects APIs]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects-api/). + +## Exporting saved objects + +To export specific objects, such as one dashboard and everything it displays, follow these steps: + +1. On the top menu, go to **Management** > **Dashboards Management** > **Saved objects**. +1. Select the checkbox for each object to export. To narrow the list, enter a title in the search box or filter by **Type**. +1. Select **Export**. +1. Keep **Include related objects** selected so that the export also contains the objects that the selected objects reference. +1. Select **Export** to download the file. + +To export the full contents of an instance, select **Export all objects**, choose the types to include, and then select **Export**. + +The downloaded file uses the NDJSON format, with one object per line and a summary on the final line. This is the same format that the [Export Saved Objects API]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects-api/#export-saved-objects) produces, so a file exported from OpenSearch Dashboards can be imported using the API and a file exported using the API can be imported from OpenSearch Dashboards. + +To review what an object references before you export it, select the **Relationships** action for that object. + +When multi-tenancy is enabled, each tenant has its own set of saved objects, and an export contains only the objects of the tenant that you are currently using. This applies to **Export all objects**, so to capture every object in an instance, switch to each tenant and export it separately. When the aggregate view is enabled, the list can show the objects of several tenants at once, but filtering the list by tenant does not change what an export contains. For more information, see [OpenSearch Dashboards multi-tenancy aggregate view for saved objects]({{site.url}}{{site.baseurl}}/security/multi-tenancy/mt-agg-view/). + +When workspaces are enabled, an export that you start from within a workspace contains only the objects associated with that workspace. An export that you start from **Saved objects** outside any workspace covers every workspace: the list includes the objects of all workspaces that you can access, marks each one in the **Workspace** column, and **Export all objects** writes all of them to the file. + +To copy objects to another workspace in the same instance rather than export them, select the objects, select **Copy to**, and choose the target workspace. To copy every object in the current workspace, select **Copy all objects to**. To perform the same task programmatically, see [Duplicate saved objects]({{site.url}}{{site.baseurl}}/dashboards/workspace/apis/#duplicate-saved-objects). + +## Importing saved objects + +To import saved objects, follow these steps: + +1. On the top menu, go to **Management** > **Dashboards Management** > **Saved objects**. +1. Select **Import**. +1. Select **Select file** and choose the NDJSON file to import. +1. In **Import options**, choose how to handle objects that already exist: + - **Create new objects with unique IDs** imports the objects as copies and leaves the existing objects unchanged. + - **Check for existing objects** compares the incoming objects with the objects already in the instance. Combine it with **Automatically overwrite conflicts** to replace existing objects, or with **Request action on conflict** to decide for each conflict. +1. Select **Import**, and then select **Done**. + +If an object refers to an index pattern that the target instance does not have, OpenSearch Dashboards lists the affected objects and prompts you to select a different index pattern or create one. + +When multi-tenancy is enabled, the objects are imported into the tenant that you are currently using, so switch to the target tenant before you import. + +When workspaces are enabled, **Import** appears only within a workspace, and the imported objects are associated with that workspace. Open the target workspace before you import. + +## Copying a dashboard to another instance + +To move a dashboard between two instances that index the same data, follow these steps: + +1. In the source instance, go to **Management** > **Dashboards Management** > **Saved objects** and select the checkbox for the dashboard. +1. Select **Export**, keep **Include related objects** selected, and then select **Export**. The file contains the dashboard, its visualizations and saved searches, and their index patterns. +1. In the target instance, go to **Management** > **Dashboards Management** > **Saved objects** and select **Import**. +1. Select the downloaded file, choose an import option, and then select **Import**. + +Tenants and workspaces determine which objects each step covers. Select the source tenant or workspace before you export and the target tenant or workspace before you import. For more information, see [Exporting saved objects](#exporting-saved-objects) and [Importing saved objects](#importing-saved-objects). + +## Limitations + +An import from OpenSearch Dashboards accepts an `.ndjson` file, and it also accepts a legacy `.json` file exported by a version of OpenSearch Dashboards or Kibana that predates NDJSON. Support for `.json` files is deprecated, and the Saved Objects APIs accept only `.ndjson`. Re-export legacy files before you use them with the API. + +A single export or import is limited to 10,000 objects and to a request size of 25 MB. For the settings that control these limits, and for other caveats that apply to both OpenSearch Dashboards and the API, see [Limitations]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects-api/#limitations). diff --git a/_dashboards/management/scheduled-query-acceleration.md b/_dashboards/management/scheduled-query-acceleration.md new file mode 100644 index 00000000..356f209f --- /dev/null +++ b/_dashboards/management/scheduled-query-acceleration.md @@ -0,0 +1,208 @@ +--- +layout: default +title: Scheduled Query Acceleration +parent: Connecting data sources +nav_order: 50 +has_children: false +--- + +# Scheduled Query Acceleration +Introduced 2.17 +{: .label .label-purple } + +Scheduled Query Acceleration (SQA) is designed to optimize queries sent directly from OpenSearch to external data sources, such as Amazon Simple Storage Service (Amazon S3). It uses automation to address issues commonly encountered when managing and refreshing indexes, views, and data. + +Query acceleration is facilitated by secondary indexes like [skipping indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#skipping-indexes), [covering indexes]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#covering-indexes), or [materialized views]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/#materialized-views). When queries run, they use these indexes instead of directly querying Amazon S3. + +The secondary indexes need to be refreshed periodically in order to remain current with the Amazon S3 data. This refresh operation can be scheduled using either an internal scheduler (within Spark) or an external scheduler. + +SQA provides the following benefits: + +- **Cost reduction through optimized resource usage**: SQA reduces the operational load on driver nodes, lowering the costs associated with maintaining auto-refresh for indexes and views. + +- **Improved observability of refresh operations**: SQA provides visibility into index states and refresh timing, offering insights into data processing and the current system state. + +- **Better control over refresh scheduling**: SQA allows flexible scheduling of refresh intervals, helping you to manage resource usage and refresh frequency according to specific requirements. + +- **Simplified index management**: SQA enables updates to index settings, such as refresh intervals, in a single query, which simplifies workflows. + +## Concepts + +Before configuring SQA, familiarize yourself with the following topics: + +- [Optimizing query performance using OpenSearch indexing]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/) +- [Flint index refresh](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#flint-index-refresh) +- [Index State Management](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#index-state-transition-1) + +## Prerequisites + +Before configuring SQA, verify that the following requirements are met: + +- Ensure you're running OpenSearch version 2.17 or later. +- Ensure you have the SQL plugin installed. The SQL plugin is included in most OpenSearch distributions. For more information, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). +- Ensure you have configured a data source (in this example, Amazon S3): Configure a skipping index, covering index, or materialized view. These secondary data sources are additional data structures that improve query performance by optimizing queries sent to external data sources, such as Amazon S3. For more information, see [Optimizing query performance using OpenSearch indexing]({{site.url}}{{site.baseurl}}/dashboards/management/accelerate-external-data/). +- Configure Amazon EMR Serverless (needed for access to Apache Spark). + +## Configuring SQA settings + +If you want to override default configuration values, change the following cluster settings: + +- **Enable asynchronous query execution**: Set `plugins.query.executionengine.async_query.enabled` to `true` (default value): + ```json + PUT /_cluster/settings + { + "transient": { + "plugins.query.executionengine.async_query.enabled": "true" + } + } + ``` + {% include copy-curl.html %} + + For more information, see [Settings](https://github.com/opensearch-project/sql/blob/main/docs/user/admin/settings.rst#pluginsqueryexecutionengineasync_queryenabled). + +- **Configure the external scheduler interval for asynchronous queries**: This setting defines how often the external scheduler checks for tasks, allowing customization of refresh frequency. There is no default value for this setting: if this value is empty, the default comes from `opensearch-spark` and is `5 minutes`. Adjusting the interval based on workload volume can help you to optimize resources and manage costs: + ```json + PUT /_cluster/settings + { + "transient": { + "plugins.query.executionengine.async_query.external_scheduler.interval": "10 minutes" + } + } + ``` + {% include copy-curl.html %} + + For more information, see [Settings](https://github.com/opensearch-project/sql/blob/main/docs/user/admin/settings.rst#pluginsqueryexecutionengineasync_queryexternal_schedulerinterval). + +## Running an accelerated query + +You can run accelerated queries in [Query Workbench]({{site.url}}{{site.baseurl}}/dashboards/query-workbench/). To run an accelerated query, use the following syntax: + +```sql +CREATE SKIPPING INDEX example_index +WITH ( + auto_refresh = true, + refresh_interval = '15 minutes' +); +``` +{% include copy.html %} + +By default, the query uses an external scheduler. To use an internal scheduler, set `scheduler_mode` to `internal`: + +```sql +CREATE SKIPPING INDEX example_index +WITH ( + auto_refresh = true, + refresh_interval = '15 minutes', + scheduler_mode = 'internal' +); +``` +{% include copy.html %} + +## Parameters + +When creating indexes using an accelerated query, you can specify the following parameters in the `WITH` clause to control refresh behavior, scheduling, and timing. + +| Parameter | Description | +|:--- | :--- | +| `auto_refresh` | Enables automatic refresh for the index. If `true`, the index refreshes automatically at the specified interval. If `false`, the refresh operation must be triggered manually using the `REFRESH` statement. Default is `false`. | +| `refresh_interval` | Defines the amount of time between index refresh operations for the index, which determines how frequently new data is ingested into the index. This is applicable only when `auto_refresh` is enabled. The interval determines how frequently new data is integrated and can be specified in formats like `1 minute` or `10 seconds`. For valid time units, see [Time units](#time-units).| +| `scheduler_mode` | Specifies the scheduling mode for auto-refresh (internal or external scheduling). The external scheduler requires a `checkpoint_location` (a path for refresh job checkpoints) for state management. For more information, see [Starting streaming queries](https://spark.apache.org/docs/latest/streaming/apis-on-dataframes-and-datasets.html#starting-streaming-queries). Valid values are `internal` and `external`.| + +For more information and additional available parameters, see [Flint index refresh](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#flint-index-refresh). + +## Time units + +You can specify the following time units when defining time intervals: + +- Milliseconds: `ms`, `millisecond`, or `milliseconds` +- Seconds: `s`, `second`, or `seconds` +- Minutes: `m`, `minute`, or `minutes` +- Hours: `h`, `hour`, or `hours` +- Days: `d`, `day`, or `days` + +## Monitoring index status + +To monitor the status of an index, use the following statement: + +```sql +SHOW FLINT INDEXES IN spark_catalog.default; +``` +{% include copy.html %} + +## Managing scheduled jobs + +Use the following commands to manage scheduled jobs. + +### Enabling jobs + +To disable auto-refresh using an internal or external scheduler, set `auto_refresh` to `false`: + +```sql +ALTER MATERIALIZED VIEW myglue_test.default.count_by_status_v9 WITH (auto_refresh = false); +``` +{% include copy.html %} + +### Updating schedules + +To update the schedule and modify the refresh settings, specify the `refresh_interval` in the `WITH` clause: + +```sql +ALTER INDEX example_index +WITH (refresh_interval = '30 minutes'); +``` +{% include copy.html %} + +### Switching the scheduler mode + +To switch the scheduler mode, specify the `scheduler_mode` in the `WITH` clause: + +```sql +ALTER MATERIALIZED VIEW myglue_test.default.count_by_status_v9 WITH (scheduler_mode = 'internal'); +``` +{% include copy.html %} + +### Inspecting scheduler metadata + +To inspect scheduler metadata, use the following request: + +```json +GET /.async-query-scheduler/_search +``` +{% include copy-curl.html %} + +## Best practices + +We recommend the following best practices when using SQA. + +### Performance optimization + +- **Recommended refresh intervals**: Choosing the right refresh interval is crucial for balancing resource usage and system performance. Consider your workload requirements and the freshness of the data you need when setting intervals. + +- **Concurrent job limits**: Limit the number of concurrent running jobs to avoid overloading system resources. Monitor system capacity and adjust job limits accordingly to ensure optimal performance. + +- **Resource usage**: Efficient resource allocation is key to maximizing performance. Properly allocate memory, CPU, and I/O based on the workload and the type of queries you're running. + +### Cost management + +- **Use an external scheduler**: An external scheduler offloads refresh operations, reducing demand on core driver nodes. + +- **Configure a refresh interval for your use case**: Longer refresh intervals lead to reduced costs but may impact data freshness. + +- **Optimize the refresh schedule**: Adjust refresh intervals based on workload patterns to reduce unnecessary refresh operations. + +- **Monitor costs**: Regularly monitor costs related to scheduled queries and refresh operations. Using observability tools can help you gain insights into resource usage and costs over time. + +## Validating settings + +You can validate your settings by running a test query and verifying the scheduler configuration: + +```sql +SHOW FLINT INDEXES EXTENDED +``` +{% include copy.html %} + +For more information, see the [OpenSearch Spark documentation](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#all-indexes). + +## Troubleshooting + +If the refresh operation is not triggering as expected, ensure that the `auto_refresh` setting is enabled and the refresh interval is properly configured. diff --git a/_dashboards/navigating-ui.md b/_dashboards/navigating-ui.md new file mode 100644 index 00000000..d89ed868 --- /dev/null +++ b/_dashboards/navigating-ui.md @@ -0,0 +1,63 @@ +--- +layout: default +title: Navigating OpenSearch Dashboards +nav_order: 20 +has_children: false +--- + +# Navigating OpenSearch Dashboards + +You can navigate OpenSearch Dashboards from the [home page](#the-opensearch-dashboards-home-page) and the [left navigation panel](#the-left-navigation-panel), which provides access to all OpenSearch Dashboards applications. + +## The OpenSearch Dashboards home page + +The OpenSearch Dashboards home page has two variants: the classic home page and the workspaces home page. + +### The classic home page + +The following image shows the home page in classic navigation, with the navigation panel open. + +![OpenSearch Dashboards home page]({{site.url}}{{site.baseurl}}/images/dashboards/osd-homepage.png) + +- The _header bar_ (A) contains the following elements from left to right: + - {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/menu-icon.png" class="inline-icon" alt="menu icon"/>{:/} (menu) The menu icon. + - {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/home-icon.png" class="inline-icon" alt="home icon"/>{:/} (home) The home icon. + - The breadcrumb display. It contains only one label, "Home", on the home page. + - The menu area (B). This area, the right portion of the header bar, contains a context-sensitive _application menu_ when an application is active in the main panel. + - {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/help-icon.png" class="inline-icon" alt="help icon"/>{:/} (help) The help icon. +- The navigation panel (C) is the primary means of navigating OpenSearch Dashboards. It contains collapsible menus grouped by function (**Recently viewed**, **OpenSearch Dashboards** apps, **Observability**, and so on). See [The left navigation panel](#the-left-navigation-panel). +- The _panel_ or _main panel_ (D) contains the current application or UI page. + +### Workspaces navigation +**Introduced 2.18.0** +{: .label .label-purple } + +OpenSearch Dashboards offers an alternative navigation mode called workspaces navigation. Workspaces group applications into focused environments, for example, Analytics, Observability, or Security Analytics. In workspaces navigation, the home page lists your workspaces, as shown in the following image, and you must first select a workspace to access applications. + +![OpenSearch Dashboards home page with workspaces enabled]({{site.url}}{{site.baseurl}}/images/dashboards/getting-started-workspaces-nav.png) + +After you select a workspace, the left navigation panel provides access to the applications for that workspace, similarly to classic navigation, as shown in the following image. Some features, such as [creating visualizations using queries]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/), are only available within workspaces. + +![Overview page and left navigation panel within a workspace]({{site.url}}{{site.baseurl}}/images/dashboards/workspace-overview-nav.png) + +Workspaces are enabled by an OpenSearch Dashboards administrator. For more information, see [Workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/). + +## The left navigation panel + +Use the _left navigation panel_ on the left side of the UI to select any application or settings page that you want to use. To open the navigation panel, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/menu-icon.png" class="inline-icon" alt="menu icon"/>{:/} (menu) icon at the top of the page. + +The following images show the most-used features in classic and workspaces navigation. + +Classic navigation panel | Workspaces navigation panel +:--: | :--: +![Classic navigation panel]({{site.url}}{{site.baseurl}}/images/dashboards/os-nav-panel.png){: width="60%" } | ![Workspaces navigation panel]({{site.url}}{{site.baseurl}}/images/dashboards/os-new-nav-panel.png){: width="57%" } + +- The _menu icon_ (A) opens and closes the navigation panel. +- **Discover** (B) opens the Discover application in the main panel. See [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). +- **Dashboards** (C) opens the Dashboards application in the main panel. See [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). +- **Visualize** (D) opens the Visualize application in the main panel. See [Building data visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/). +- **Observability** (E) opens the Observability menu in the navigation panel. See [Observability]({{site.url}}{{site.baseurl}}/observing-your-data/). + +## Related documentation + +- [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/getting-started/access/) \ No newline at end of file diff --git a/_dashboards/notebooks.md b/_dashboards/notebooks.md new file mode 100644 index 00000000..34b012de --- /dev/null +++ b/_dashboards/notebooks.md @@ -0,0 +1,126 @@ +--- +layout: default +title: Notebooks +nav_order: 74 +redirect_from: + - /observability-plugin/notebooks/ + - /observing-your-data/notebooks/ +has_children: false +--- + +# Notebooks + +An OpenSearch Dashboards notebook is an interface that lets you easily combine code snippets, live visualizations, and narrative text in a single notebook interface. + +Notebooks let you interactively explore data by running different visualizations that you can share with team members to collaborate on a project. + +A notebook is a document composed of two elements: code blocks (Markdown/SQL/Piped Processing Language (PPL)) and visualizations. Choose multiple timelines to compare and contrast visualizations. + +You can also generate [reports]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-dashboard-index/) directly from your notebooks. + +Common use cases include creating postmortem reports, designing runbooks, building live infrastructure reports, and writing documentation. + +Tenants in OpenSearch Dashboards are spaces for saving notebooks and other OpenSearch Dashboards objects. For more information, see [OpenSearch Dashboards multi-tenancy]({{site.url}}{{site.baseurl}}/security/multi-tenancy/tenant-index/). +{: .note } + + +## Get started with notebooks + +To open notebooks, on the top menu, go to **Observability** > **Notebooks**. In a workspace, Notebooks is in the **Visualize and report** menu category. In an Observability workspace that uses the icon side navigation, Notebooks is in the **More** menu. + + +### Step 1: Create a notebook + +A notebook is an interface for creating reports. + +1. Choose **Create notebook** and enter a descriptive name. +1. Choose **Create**. + +Choose **Actions** to rename, duplicate, or delete a notebook. + +![Create notebook]({{site.url}}{{site.baseurl}}/images/create_notebook.gif) + +### Step 2: Add a paragraph + +Paragraphs combine code blocks and visualizations for describing data. + +#### Add a code block + +Code blocks support Markdown, SQL, and PPL languages. + +Specify the input language on the first line using `%[language type]` syntax. +For example, type `%md` for Markdown, `%sql` for SQL, and `%ppl` for PPL. + +##### Sample Markdown block + +``` +%md +Add in text formatted in Markdown. +``` + +![Markdown paragraph]({{site.url}}{{site.baseurl}}/images/markdown_notebooks.gif) + +##### Sample SQL block + +```sql +%sql +Select * from opensearch_dashboards_sample_data_flights limit 20; +``` + +![SQL paragraph]({{site.url}}{{site.baseurl}}/images/sql_notebooks.gif) + +##### Sample PPL block + +``` +%ppl +source=opensearch_dashboards_sample_data_logs | head 20 +``` + +![PPL paragraph]({{site.url}}{{site.baseurl}}/images/ppl_notebooks.gif) + + +#### Add a visualization + +1. To add a visualization, choose **Add paragraph** and select **Visualization**. +1. In **Title**, select your visualization and choose a date range. You can choose multiple timelines to compare and contrast visualizations. +1. To run and save a paragraph, choose **Run**. + +![Visualization paragraph]({{site.url}}{{site.baseurl}}/images/visualization_notebooks.gif) + +## Paragraph actions + +You can perform the following actions on paragraphs: + +- Add a new paragraph to the top of a report. +- Add a new paragraph to the bottom of a report. +- Run all the paragraphs at the same time. +- Clear the outputs of all paragraphs. +- Delete all the paragraphs. + +![Sample notebooks]({{site.url}}{{site.baseurl}}/images/paragraphs_notebooks.gif) + +## Sample notebooks + +We prepared the following sample notebooks that showcase a variety of use cases: + +- Using SQL to query the OpenSearch Dashboards sample flight data. +- Using PPL to query the OpenSearch Dashboards sample web logs data. +- Using PPL and visualizations to perform sample root cause event analysis on the OpenSearch Dashboards sample web logs data. + +To add a sample notebook, choose **Actions** and select **Add sample notebooks**. + +![Sample notebooks]({{site.url}}{{site.baseurl}}/images/sample_notebooks.gif) + +## Create a report + +You can use notebooks to create PNG and PDF reports: + +1. From the top menu bar, choose **Reporting actions**. +1. You can choose to **Download PDF** or **Download PNG**. + + Reports generate asynchronously in the background and might take a few minutes, depending on the size of the report. A notification appears when your report is ready to download. + +1. To create a schedule-based report, choose **Create report definition**. For steps to create a report definition, see [Creating reports using a definition]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-dashboard-index/#creating-reports-using-a-definition). +1. To see all your reports, choose **View all reports**. + +![Report notebooks]({{site.url}}{{site.baseurl}}/images/report_notebooks.gif) diff --git a/_dashboards/query-workbench.md b/_dashboards/query-workbench.md index 8fe41afc..c30a1c02 100644 --- a/_dashboards/query-workbench.md +++ b/_dashboards/query-workbench.md @@ -1,26 +1,22 @@ --- layout: default -title: Query Workbench -nav_order: 125 +title: Using Query Workbench +parent: Exploring data +nav_order: 30 redirect_from: - /search-plugins/sql/workbench/ --- -# Query Workbench +# Using Query Workbench -Query Workbench is a tool within OpenSearch Dashboards. You can use Query Workbench to run on-demand [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/sql/index/) and [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) queries, translate queries into their equivalent REST API calls, and view and save results in different [response formats]({{site.url}}{{site.baseurl}}/search-plugins/sql/response-formats/). +You can use Query Workbench in OpenSearch Dashboards to run on-demand [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/sql/index/) and [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) queries, translate queries into their equivalent REST API calls, and view and save results in different [response formats]({{site.url}}{{site.baseurl}}/search-plugins/sql/response-formats/). -A view of the Query Workbench interface within OpenSearch Dashboards is shown in the following image. +Query Workbench does not support delete or update operations through SQL or PPL. Access to data is read-only. +{: .important} -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-workbench-ui.png" alt="Query Workbench interface within OpenSearch Dashboards" width="700"> +## Prerequisites -## Prerequisites - -Before getting started, make sure you have [indexed your data]({{site.url}}{{site.baseurl}}/im-plugin/index/). - -For this tutorial, you can index the following sample documents. Alternatively, you can use the [OpenSearch Playground](https://playground.opensearch.org/app/opensearch-query-workbench#/), which has preloaded indexes that you can use to try out Query Workbench. - -To index sample documents, send the following [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) request: +Before getting started with this tutorial, index the sample documents by sending the following [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) request: ```json PUT accounts/_bulk?refresh @@ -35,9 +31,11 @@ PUT accounts/_bulk?refresh ``` {% include copy-curl.html %} -## Running SQL queries within Query Workbench +See [Managing indexes]({{site.url}}{{site.baseurl}}/im-plugin/index/) to learn about indexing your own data. -Follow these steps to learn how to run SQL queries against your OpenSearch data using Query Workbench: +## Running SQL queries within Query Workbench + + The following steps guide you through running SQL queries against OpenSearch data: 1. Access Query Workbench. - To access Query Workbench, go to OpenSearch Dashboards and choose **OpenSearch Plugins** > **Query Workbench** from the main menu. @@ -64,23 +62,15 @@ Follow these steps to learn how to run SQL queries against your OpenSearch data 3. View the results. - View the results in the **Results** pane, which presents the query output in tabular format. You can filter and download the results as needed. - The following image shows the query editor pane and results pane for the preceding SQL query: - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-workbench-query-step2.png" alt="Query Workbench SQL query input and results output panes" width="800"> - 4. Clear the query editor. - Select the **Clear** button to clear the query editor and run a new query. 5. Examine how the query is processed. - - Select the **Explain** button to examine how OpenSearch processes the query, including the steps involved and order of operations. - - The following image shows the explanation of the SQL query that was run in step 2. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-explain.png" alt="Query Workbench SQL query explanation pane" width="500"> + - Select the **Explain** button to examine how OpenSearch processes the query, including the steps involved and order of operations. ## Running PPL queries within Query Workbench -Follow these steps to learn how to run PPL queries against your OpenSearch data using Query Workbench: +Follow these steps to learn how to run PPL queries against OpenSearch data: 1. Access Query Workbench. - To access Query Workbench, go to OpenSearch Dashboards and choose **OpenSearch Plugins** > **Query Workbench** from the main menu. @@ -100,19 +90,8 @@ Follow these steps to learn how to run PPL queries against your OpenSearch data 3. View the results. - View the results in the **Results** pane, which presents the query output in tabular format. - The following image shows the query editor pane and results pane for the PPL query that was run in step 2: - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-workbench-ppl.png" alt="Query Workbench PPL query input and results output panes"> - 4. Clear the query editor. - Select the **Clear** button to clear the query editor and run a new query. 5. Examine how the query is processed. - - Select the **Explain** button to examine how OpenSearch processes the query, including the steps involved and order of operations. - - The following image shows the explanation of the PPL query that was run in step 2. - - <img src="{{site.url}}{{site.baseurl}}/images/dashboards/query-PPL-explain.png" alt="Query Workbench PPL query explanation pane" width="500"> - -Query Workbench does not support delete or update operations through SQL or PPL. Access to data is read-only. -{: .important} \ No newline at end of file + - Select the **Explain** button to examine how OpenSearch processes the query, including the steps involved and order of operations. diff --git a/_dashboards/reporting/api.md b/_dashboards/reporting/api.md new file mode 100644 index 00000000..cee79e2d --- /dev/null +++ b/_dashboards/reporting/api.md @@ -0,0 +1,540 @@ +--- +layout: default +title: Reporting API +nav_order: 30 +parent: Reporting +redirect_from: + - /reporting/api/ +--- + +# Reporting API + +Use the Reporting API to create and manage report definitions and to generate reports from dashboards, visualizations, saved searches, and notebooks. A report definition specifies the source object to capture, the file format, the time range, and an optional schedule. Generating a report from a definition produces a report instance. + +Report definitions and report instances are managed through OpenSearch, but the file itself is rendered by OpenSearch Dashboards. Creating a definition and listing instances use the OpenSearch endpoint on port 9200, and downloading the report content uses the OpenSearch Dashboards endpoint on port 5601. For more information, see [Downloading report content](#downloading-report-content). + +For the OpenSearch Dashboards interface equivalent of these operations, see [Reporting using OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-dashboard-index/). + +## Report source types and file formats + +The `Csv` and `Xlsx` file formats export the underlying rows of a saved search. They are not supported for the `Visualization`, `Dashboard`, or `Notebook` source types, which are captured as rendered images. To export the data behind a visualization as CSV, save the equivalent query as a saved search in **Discover** and use that saved search as the report source. + +The following table lists the file formats supported for each report source type. + +| Source type | Supported file formats | +| :--- | :--- | +| `SavedSearch` | `Csv`, `Xlsx` | +| `Visualization` | `Pdf`, `Png` | +| `Dashboard` | `Pdf`, `Png` | +| `Notebook` | `Pdf`, `Png` | + +OpenSearch accepts a report definition that pairs a source type with an unsupported file format, such as `Visualization` with `Csv`, but the report cannot be rendered. A definition with an unsupported pairing also causes the **Reporting** page in OpenSearch Dashboards to fail to load its list of report definitions until you delete the definition. +{: .warning} + +## Create report definition API + +Creates a report definition. + +### Endpoint + +```json +POST _plugins/_reports/definition +``` + +### Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `reportDefinition` | Object | The report definition. Required. | +| `reportDefinition.name` | String | The name of the report definition. Required. | +| `reportDefinition.isEnabled` | Boolean | Whether the definition's schedule is active. Required. | +| `reportDefinition.source` | Object | The object to capture. Required. | +| `reportDefinition.source.type` | String | The type of source object. Valid values are `Dashboard`, `Visualization`, `SavedSearch`, and `Notebook`. Required. | +| `reportDefinition.source.id` | String | The saved object ID of the source object. Required. | +| `reportDefinition.source.origin` | String | The base URL of the OpenSearch Dashboards instance that renders the report, such as `http://localhost:5601`. Required. | +| `reportDefinition.source.description` | String | A description of the source object. Optional. | +| `reportDefinition.format` | Object | The output format. Required. | +| `reportDefinition.format.fileFormat` | String | The file format of the generated report. Valid values are `Pdf`, `Png`, `Csv`, and `Xlsx`. Required. | +| `reportDefinition.format.duration` | String | The time range to capture, ending at the time the report is generated, as an ISO 8601 duration such as `PT30M` or `P60D`. Required. | +| `reportDefinition.format.limit` | Integer | The maximum number of rows to include in a `Csv` or `Xlsx` report. Optional. | +| `reportDefinition.format.header` | String | A header to add to the report. Optional. | +| `reportDefinition.trigger` | Object | Specifies when the report is generated. Required. | +| `reportDefinition.trigger.triggerType` | String | Valid values are `OnDemand`, `Download`, `CronSchedule`, and `IntervalSchedule`. Required. | +| `reportDefinition.trigger.schedule` | Object | The schedule on which to generate the report. Required when `triggerType` is `CronSchedule` or `IntervalSchedule`. | +| `reportDefinition.delivery` | Object | Notification settings for the generated report. Optional. | + +### Example request + +The following request creates an on-demand definition that exports the last 60 days of a saved search as CSV: + +```json +POST _plugins/_reports/definition +{ + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "<saved_search_id>" + }, + "format": { + "duration": "P60D", + "fileFormat": "Csv", + "limit": 1000, + "header": "" + }, + "trigger": { + "triggerType": "OnDemand" + }, + "delivery": { + "configIds": [], + "title": "", + "textDescription": "", + "htmlDescription": "" + }, + "status": "ACTIVE" + } +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "reportDefinitionId": "7f6fY6ABLgrkzSeVjlGr" +} +``` + +### Example request: Scheduled report + +To generate a report on a recurring schedule, set `triggerType` to `CronSchedule` and provide a `schedule` object. The following request generates the same CSV report every day at 6:00 AM: + +```json +POST _plugins/_reports/definition +{ + "reportDefinition": { + "name": "Daily orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "<saved_search_id>" + }, + "format": { + "duration": "P1D", + "fileFormat": "Csv", + "limit": 10000, + "header": "" + }, + "trigger": { + "triggerType": "CronSchedule", + "schedule": { + "cron": { + "expression": "0 6 * * *", + "timezone": "America/Los_Angeles" + } + } + }, + "status": "ACTIVE" + } +} +``` +{% include copy-curl.html %} + +For more information about cron expressions, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). + +## List report definitions API + +Retrieves all report definitions. + +### Endpoint + +```json +GET _plugins/_reports/definitions +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `fromIndex` | Integer | The index of the first definition to return. Default is `0`. | +| `maxItems` | Integer | The maximum number of definitions to return. | + +### Example request + +```json +GET _plugins/_reports/definitions +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "startIndex": 0, + "totalHits": 1, + "totalHitRelation": "eq", + "reportDefinitionDetailsList": [ + { + "id": "7f6fY6ABLgrkzSeVjlGr", + "lastUpdatedTimeMs": 1788377796262, + "createdTimeMs": 1788377796262, + "tenant": "", + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "test-search" + }, + "format": { + "duration": "PT1440H", + "fileFormat": "Csv", + "limit": 1000, + "header": "", + "timeFrom": null, + "timeTo": null + }, + "trigger": { + "triggerType": "OnDemand" + }, + "delivery": { + "title": "", + "textDescription": "", + "htmlDescription": "", + "configIds": [] + } + } + } + ] +} +``` + +## Get report definition API + +Retrieves a single report definition. + +### Endpoint + +```json +GET _plugins/_reports/definition/{report_definition_id} +``` + +### Example request + +```json +GET _plugins/_reports/definition/7f6fY6ABLgrkzSeVjlGr +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "reportDefinitionDetails": { + "id": "7f6fY6ABLgrkzSeVjlGr", + "lastUpdatedTimeMs": 1788377796434, + "createdTimeMs": 1788377796262, + "tenant": "", + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "test-search" + }, + "format": { + "duration": "PT1440H", + "fileFormat": "Csv", + "limit": 1000, + "header": "", + "timeFrom": null, + "timeTo": null + }, + "trigger": { + "triggerType": "OnDemand" + }, + "delivery": { + "title": "", + "textDescription": "", + "htmlDescription": "", + "configIds": [] + } + } + } +} +``` + +## Update report definition API + +Replaces an existing report definition. Provide the complete definition, because fields you omit are not preserved. + +### Endpoint + +```json +PUT _plugins/_reports/definition/{report_definition_id} +``` + +### Example request + +```json +PUT _plugins/_reports/definition/7f6fY6ABLgrkzSeVjlGr +{ + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "<saved_search_id>" + }, + "format": { + "duration": "P90D", + "fileFormat": "Csv", + "limit": 5000, + "header": "" + }, + "trigger": { + "triggerType": "OnDemand" + }, + "status": "ACTIVE" + } +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "reportDefinitionId": "7f6fY6ABLgrkzSeVjlGr" +} +``` + +## Delete report definition API + +Deletes a report definition. Deleting a definition does not delete reports that were already generated from it. + +### Endpoint + +```json +DELETE _plugins/_reports/definition/{report_definition_id} +``` + +### Example request + +```json +DELETE _plugins/_reports/definition/7f6fY6ABLgrkzSeVjlGr +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "reportDefinitionId": "7f6fY6ABLgrkzSeVjlGr" +} +``` + +## Generate on-demand report API + +Creates a report instance from an existing report definition. The response records the definition used and the time range captured. To retrieve the file content, see [Downloading report content](#downloading-report-content). + +### Endpoint + +```json +POST _plugins/_reports/on_demand/{report_definition_id} +``` + +### Example request + +```json +POST _plugins/_reports/on_demand/7f6fY6ABLgrkzSeVjlGr +{} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "reportInstance": { + "id": "7v6fY6ABLgrkzSeVpVGM", + "lastUpdatedTimeMs": 1788377802121, + "createdTimeMs": 1788377802121, + "beginTimeMs": 1780601802121, + "endTimeMs": 1788377802121, + "tenant": "", + "reportDefinitionDetails": { + "id": "7f6fY6ABLgrkzSeVjlGr", + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "test-search" + }, + "format": { + "duration": "PT1440H", + "fileFormat": "Csv", + "limit": 5000, + "header": "", + "timeFrom": null, + "timeTo": null + }, + "trigger": { + "triggerType": "OnDemand" + } + } + }, + "status": "Success" + } +} +``` + +### Response body fields + +The following table lists the response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `reportInstance.id` | String | The ID of the report instance. | +| `reportInstance.beginTimeMs` | Integer | The start of the captured time range, in milliseconds since the epoch. | +| `reportInstance.endTimeMs` | Integer | The end of the captured time range, in milliseconds since the epoch. | +| `reportInstance.reportDefinitionDetails` | Object | The report definition used to generate the instance. | +| `reportInstance.status` | String | The status of the report instance, such as `Success`. | + +## List report instances API + +Retrieves the report instances that were generated in the cluster. + +### Endpoint + +```json +GET _plugins/_reports/instances +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `fromIndex` | Integer | The index of the first instance to return. Default is `0`. | +| `maxItems` | Integer | The maximum number of instances to return. | + +### Example request + +```json +GET _plugins/_reports/instances?fromIndex=0&maxItems=2 +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "startIndex": 0, + "totalHits": 5, + "totalHitRelation": "eq", + "reportInstanceList": [ + { + "id": "7v6fY6ABLgrkzSeVpVGM", + "lastUpdatedTimeMs": 1788377802121, + "createdTimeMs": 1788377802121, + "beginTimeMs": 1780601802121, + "endTimeMs": 1788377802121, + "tenant": "", + "status": "Success" + } + ] +} +``` + +## Get report instance API + +Retrieves a single report instance. + +### Endpoint + +```json +GET _plugins/_reports/instance/{report_instance_id} +``` + +### Example request + +```json +GET _plugins/_reports/instance/7v6fY6ABLgrkzSeVpVGM +``` +{% include copy-curl.html %} + +## Downloading report content + +The OpenSearch endpoints manage report metadata and do not return the report file. To retrieve the content, call the OpenSearch Dashboards reporting endpoint with the ID of a report definition: + +```json +POST {osd_host}:{port}/api/reporting/generateReport/{report_definition_id} +``` + +This endpoint requires the `osd-xsrf: true` header and the following query parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `timezone` | String | The time zone used to interpret the report time range, such as `UTC`. Required. | +| `dateFormat` | String | The format applied to date fields in the output, such as `MMM D, YYYY @ HH:mm:ss.SSS`. Required. | +| `csvSeparator` | String | The character used to delimit values in `Csv` output. Required. | +| `allowLeadingWildcards` | Boolean | Whether the saved search query can begin with a wildcard. Required. | + +### Example request + +The following request downloads the CSV content of a report definition: + +```bash +curl -X POST \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + 'http://localhost:5601/api/reporting/generateReport/7f6fY6ABLgrkzSeVjlGr?timezone=UTC&dateFormat=MMM%20D,%20YYYY%20@%20HH:mm:ss.SSS&csvSeparator=,&allowLeadingWildcards=true' \ + -d '{}' +``` +{% include copy.html %} + +### Example response + +For `Csv` reports, the `data` field contains the file content as text: + +```json +{ + "data": "order_date,customer_name,price\n\"Aug 1, 2026 @ 10:00:00.000\",Alice,24.99\n\"Aug 2, 2026 @ 11:00:00.000\",Bob,13.5\n\"Aug 3, 2026 @ 12:00:00.000\",Carla,99", + "filename": "Orders CSV_2026-09-02T19:34:25.546Z_4e4bc6a0-a705-11f1-b9f2-73596a0bfb5c.csv" +} +``` + +For `Xlsx` reports, the `data` field contains a Base64-encoded data URL instead of text. + +If `data` is an empty string, the report definition's `duration` did not overlap any documents. Increase `duration` so that the time range ending at the current time includes your data. +{: .tip} + +CSV reports have a non-configurable 10,000-row limit in OpenSearch version 2.16 and earlier. As of version 2.17, set the limit using the `limit` field in the report definition. +{: .note} + +## Related documentation + +- [Reporting using OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-dashboard-index/) +- [Saved Objects APIs]({{site.url}}{{site.baseurl}}/dashboards/management/saved-objects-api/) +- [Report definition access control]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-definition-access-control/) +- [Report instance access control]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-instance-access-control/) diff --git a/_dashboards/reporting/index.md b/_dashboards/reporting/index.md new file mode 100644 index 00000000..d5abce09 --- /dev/null +++ b/_dashboards/reporting/index.md @@ -0,0 +1,58 @@ +--- +layout: default +title: Reporting +nav_order: 75 +has_children: true +has_toc: false +redirect_from: + - /dashboards/reporting/ + - /reporting/ + - /reporting/index/ +--- + +# Reporting + +Use reporting to generate PDF, PNG, CSV, and XLSX reports from dashboards, visualizations, saved searches, and notebooks, either on demand or on a schedule. OpenSearch Dashboards renders every report, so reporting requires a running OpenSearch Dashboards instance even when you generate reports using the API or the CLI. + +To download search results or saved objects without creating a report, see [Exporting data]({{site.url}}{{site.baseurl}}/dashboards/exporting-data/). + +## Report definitions and reports + +Reporting uses two concepts: + +- A **report definition** is a saved configuration that specifies which dashboard, visualization, saved search, or notebook to capture, the file format, the time range, and an optional schedule. You can reuse a report definition to generate reports on demand or on a recurring schedule. +- A **report** is the generated file produced from a report definition or a one-time download. + +Deleting a report definition does not delete the reports generated from it. + +## Report sources and file formats + +The available file formats depend on the report source. Dashboards, visualizations, and notebooks are captured as rendered images. Saved searches are exported as the rows returned by the query. + +| Report source | File formats | +| :--- | :--- | +| Dashboard | PDF, PNG | +| Visualization | PDF, PNG | +| Notebook | PDF, PNG | +| Saved search | CSV, XLSX | + +To download the data behind a visualization, see [Exporting visualization data]({{site.url}}{{site.baseurl}}/dashboards/exporting-data/#exporting-visualization-data). + +CSV and XLSX reports contain up to 10,000 rows by default. To change this limit, set the record limit when you create a report definition. Reports have no explicit size limit, but extremely large documents can cause report generation to fail with an out-of-memory error from the V8 JavaScript engine. +{: .tip } + +## Choosing a method + +The following table lists the ways to generate reports. + +| Method | Use it to | Requires the Reporting plugin | +| :--- | :--- | :--- | +| [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-dashboard-index/) | Generate reports from the page that you are viewing, and create and manage report definitions. | Yes | +| [Reporting CLI]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-index/) | Generate reports from scripts, cron jobs, or AWS Lambda functions, and send them by email using Amazon SES or SMTP. | Only for CSV reports | +| [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/) | Create report definitions and generate reports programmatically. | Yes | + +## Access control + +To create reports, you must have the correct permissions. For a summary of the predefined roles and the permissions they grant, see [Predefined roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/#predefined-roles). + +When resource sharing is enabled for reporting, owners of report definitions and reports, and users with sharing permissions, can grant access to specific users, roles, and backend roles. For more information, see [Report definition access control]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-definition-access-control/) and [Report instance access control]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-instance-access-control/). diff --git a/_dashboards/reporting/rep-cli-create.md b/_dashboards/reporting/rep-cli-create.md new file mode 100644 index 00000000..d25f94d1 --- /dev/null +++ b/_dashboards/reporting/rep-cli-create.md @@ -0,0 +1,103 @@ +--- +layout: default +title: Create and request visualization reports +nav_order: 15 +parent: Reporting using the CLI +grand_parent: Reporting +redirect_from: + - /reporting/rep-cli-create/ + - /dashboards/reporting-cli/rep-cli-create/ +--- + +# Create and request visualization reports + +To generate a report, provide the Reporting CLI with the OpenSearch Dashboards URL of the dashboard, visualization, notebook, or saved search that you want to capture. + +## Getting the URL + +To get the URL, follow these steps: + +1. In OpenSearch Dashboards, open the dashboard, visualization, notebook, or saved search. +1. On the top menu, select **Share** > **Permalinks**. +1. In **Generate the link as**, select **Saved object**. +1. Select **Copy link**. + + ![Copy link]({{site.url}}{{site.baseurl}}/images/dashboards/dash-url.png) + +A **Saved object** link is percent-encoded and contains the time range of the page. A **Snapshot** link also contains the current filters and query, but it can include characters, such as `'` and `!`, that the shell interprets. Enclose the URL in single quotes when you pass it to the `-u` option. To use a Snapshot link that contains a single quote, save the URL in the `OPENSEARCH_URL` variable of a `.env` file. For more information, see [Use environment variables with the Reporting CLI]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-env-var/). + +Don't use a link generated with the **Short URL** option. The Reporting CLI uses the URL path to determine the report source, so for a short URL, the report includes the OpenSearch Dashboards header and buttons. +{: .note} + +If the URL does not include a time range, the report uses the default time range of OpenSearch Dashboards. + +## Example: Downloading a PDF report + +The following command downloads a PDF report of a dashboard to the current directory: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' +``` +{% include copy.html %} + +PDF is the default format. If you don't specify a file name, the report is saved as `opensearch-report-<timestamp>.pdf`. The following image shows an example PDF report. + +![PDF example]({{site.url}}{{site.baseurl}}/images/dashboards/cli-pdf-report.png) + +## Example: Downloading a PNG report of a long dashboard + +OpenSearch Dashboards loads dashboard panels only when they are visible in the browser window. By default, the window is 600 pixels tall, so panels in the lower part of a long dashboard can appear empty in the report. To capture all panels, set the `-l` option to a height that fits the entire dashboard: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -f png -l 2200 -n web-traffic +``` +{% include copy.html %} + +The report is saved as `web-traffic.png`. If a file with the same name already exists in the current directory, the Reporting CLI does not overwrite it and the command fails. + +## Example: Downloading a CSV report of a saved search + +CSV reports are supported only for saved searches. To download a CSV report, provide the URL of a saved search and set the window width to `800`: + +```bash +opensearch-reporting-cli -u '<saved-search-url>' -f csv -w 800 -n orders +``` +{% include copy.html %} + +The Reporting CLI generates the CSV report by selecting **Reporting** > **Generate CSV** in **Discover**. When the window is resized to any other width after the page loads, the **Reporting** menu is not displayed, and the command fails with the error `No element found for selector: button[id="downloadReport"]`. +{: .note} + +## Example: Requesting a report using basic authentication + +If the Security plugin is enabled, provide the authentication type and credentials. The following command uses basic authentication to request a PDF report: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -a basic -c '<username>:<password>' +``` +{% include copy.html %} + +To avoid passing the password on the command line, set the `OPENSEARCH_USERNAME` and `OPENSEARCH_PASSWORD` environment variables instead of the `-c` option. + +## Example: Sending a report by email using SMTP + +The following command generates a PDF report and sends it as an attachment to the specified recipient using an SMTP server: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -e smtp --smtphost <smtp-host> --smtpport <smtp-port> --smtpusername <smtp-username> --smtppassword <smtp-password> -s <sender-email> -r <recipient-email> +``` +{% include copy.html %} + +The email contains an image of the page, a link to the page in OpenSearch Dashboards, and the report as an attachment. The report is also saved to the current directory. To send the email to multiple recipients, separate the addresses with commas. To change the email subject and body, use the `--subject` and `--note` options. The `--note` option accepts either a string or the path to a text file. + +## Example: Sending a report by email using Amazon SES + +The following command generates a PNG report and sends it using Amazon SES: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -f png -e ses -s <sender-email> -r <recipient-email> +``` +{% include copy.html %} + +Amazon SES requires AWS credentials and a verified sender address. For more information, see [Using Amazon SES to request an email with a report attachment]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-env-var/#using-amazon-ses-to-request-an-email-with-a-report-attachment). + +For all available options, see [Reporting CLI options]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-options/). diff --git a/_dashboards/reporting/rep-cli-cron.md b/_dashboards/reporting/rep-cli-cron.md new file mode 100644 index 00000000..545bfe4a --- /dev/null +++ b/_dashboards/reporting/rep-cli-cron.md @@ -0,0 +1,79 @@ +--- +layout: default +title: Schedule reports with the cron utility +nav_order: 20 +parent: Reporting using the CLI +grand_parent: Reporting +redirect_from: + - /reporting/rep-cli-cron/ + - /dashboards/reporting-cli/rep-cli-cron/ +--- + +# Schedule reports with the cron utility + +Use the cron command-line utility to run the Reporting CLI on a schedule. Each cron entry consists of a cron expression that specifies when to run, followed by the command to run. + +To learn about the cron expression syntax, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). To get help with cron, open the man page by running the following command: + +```bash +man crontab +``` +{% include copy.html %} + +## Prerequisites + +- A machine with cron installed. +- The Reporting CLI. For instructions, see [Download and install the Reporting CLI tool]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-install/). + +## Specifying the schedule + +Cron runs commands with a minimal `PATH` that usually contains only `/usr/bin` and `/bin`, so cron cannot find the `node` and `opensearch-reporting-cli` commands unless you set `PATH` in the crontab. To find the directories that contain these commands, run the following command: + +```bash +dirname "$(command -v node)" "$(command -v opensearch-reporting-cli)" +``` +{% include copy.html %} + +Open the crontab editor by running the following command: + +```bash +crontab -e +``` +{% include copy.html %} + +In the crontab editor, set `PATH` to include the directories returned by the preceding command, and then add the report request. The following example generates a report every day at 8:00 AM and sends it by email using Amazon SES: + +``` +PATH=/usr/local/bin:/usr/bin:/bin +0 8 * * * opensearch-reporting-cli -u '<dashboards-url>' -e ses -s <sender-email> -r <recipient-email> +``` + +Cron converts every `%` character in a command into a new line, and OpenSearch Dashboards URLs usually contain `%` characters. Enclose the URL in single quotes and escape each `%` character in the URL as `\%`. Alternatively, store the URL in a `.env` file as described in the following section. +{: .important} + +If you specify a file name using the `-n` option, the Reporting CLI fails on the second run because a file with the same name already exists. Omit the file name to save each report with a timestamped file name, or delete the previous report before the next run. +{: .note} + +## Storing report settings in a .env file + +Instead of providing the URL and other options in the cron command, store them in a `.env` file. Values in a `.env` file do not need escaping. Cron runs commands from your home directory, so change to the directory that contains the `.env` file before running the Reporting CLI. + +For example, create a `/home/<user>/reports/.env` file containing the following variables: + +``` +OPENSEARCH_URL="<dashboards-url>" +OPENSEARCH_TRANSPORT=smtp +OPENSEARCH_SMTP_HOST=<smtp-host> +OPENSEARCH_SMTP_PORT=<smtp-port> +OPENSEARCH_FROM=<sender-email> +OPENSEARCH_TO=<recipient-email> +``` + +Then add the following entry to the crontab: + +``` +PATH=/usr/local/bin:/usr/bin:/bin +0 8 * * * cd /home/<user>/reports && opensearch-reporting-cli +``` + +For more information, see [Use environment variables with the Reporting CLI]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-env-var/). diff --git a/_dashboards/reporting/rep-cli-env-var.md b/_dashboards/reporting/rep-cli-env-var.md new file mode 100644 index 00000000..317cde29 --- /dev/null +++ b/_dashboards/reporting/rep-cli-env-var.md @@ -0,0 +1,115 @@ +--- +layout: default +title: Use environment variables with the Reporting CLI +nav_order: 35 +parent: Reporting using the CLI +grand_parent: Reporting +redirect_from: + - /reporting/rep-cli-env-var/ + - /dashboards/reporting-cli/rep-cli-env-var/ +--- + +# Use environment variables with the Reporting CLI + +Instead of providing values on the command line, you can set them as environment variables. For a list of the options that have a corresponding environment variable, see [Reporting CLI options]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-options/). + +Set environment variables in either of the following ways: + +- Export them in your shell, for example, `export OPENSEARCH_FROM=reports@example.com`. +- Save them in a file named `.env` in the directory from which you run the Reporting CLI. The Reporting CLI reads the `.env` file only from the current directory. + +In a `.env` file, use the `NAME=VALUE` format, one variable per line. Lines that start with `#` are comments. To include characters such as `#`, `'`, or `!` in a value, enclose the value in double quotation marks. The quotation marks are not included in the value. + +When the same value is set in more than one place, the Reporting CLI uses the following order of precedence: + +1. Command line options +1. Environment variables exported in the shell +1. Variables in the `.env` file + +For example, if the `.env` file sets `OPENSEARCH_FILENAME=test` and you run the command with the `--filename report` option, the report is saved as `report.pdf`. + +## Example: Requesting a report using a .env file + +The following `.env` file specifies the URL, the report file name, and the credentials: + +``` +OPENSEARCH_URL="<dashboards-url>" +OPENSEARCH_FILENAME=daily-traffic +OPENSEARCH_USERNAME=<username> +OPENSEARCH_PASSWORD=<password> +``` + +To request a PNG report using the values in the `.env` file, run the following command from the directory that contains the file: + +```bash +opensearch-reporting-cli --format png --auth basic +``` +{% include copy.html %} + +The report is saved to the current directory as `daily-traffic.png`. + +## Sending a report by email using SMTP + +To send a report by email using SMTP, set the following variables in your `.env` file: + +``` +OPENSEARCH_TRANSPORT=smtp +OPENSEARCH_SMTP_HOST=<smtp-host> +OPENSEARCH_SMTP_PORT=<smtp-port> +OPENSEARCH_SMTP_SECURE=true +OPENSEARCH_SMTP_USERNAME=<smtp-username> +OPENSEARCH_SMTP_PASSWORD=<smtp-password> +OPENSEARCH_FROM=<sender-email> +OPENSEARCH_TO=<recipient-email> +``` + +Then run the following command: + +```bash +opensearch-reporting-cli --url '<dashboards-url>' +``` +{% include copy.html %} + +If your SMTP server does not require authentication, omit `OPENSEARCH_SMTP_USERNAME` and `OPENSEARCH_SMTP_PASSWORD`. + +## Using Amazon SES to request an email with a report attachment + +To use Amazon SES as the email transport, the following prerequisites apply: + +- The sender's email address must be verified by [Amazon SES](https://aws.amazon.com/ses/). +- The Reporting CLI reads AWS credentials and the AWS Region from your AWS configuration. To configure them using the [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html), see [Quick configuration with `aws configure`](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config) in the AWS Command Line Interface user guide. +- The AWS credentials must grant the `ses:SendRawEmail` permission: + + ```json + { + "Statement": [ + { + "Effect": "Allow", + "Action": "ses:SendRawEmail", + "Resource": "*" + } + ] + } + ``` + +The following command requests an email with the report attached: + +```bash +opensearch-reporting-cli --url '<dashboards-url>' --transport ses --from <sender-email> --to <recipient-email> +``` +{% include copy.html %} + +Alternatively, set `OPENSEARCH_TRANSPORT`, `OPENSEARCH_FROM`, and `OPENSEARCH_TO` in your `.env` file and provide only the URL: + +```bash +opensearch-reporting-cli --url '<dashboards-url>' +``` +{% include copy.html %} + +## Customizing the email + +To change the email subject and body, use the `--subject` and `--note` options or the `OPENSEARCH_EMAIL_SUBJECT` and `OPENSEARCH_EMAIL_NOTE` variables. To change the email layout, edit the `src/views/index.hbs` template in the Reporting CLI installation directory. + +## Troubleshooting + +To resolve **MessageRejected: Email address is not verified**, see [Why am I getting a 400 "message rejected" error with the message "Email address is not verified" from Amazon SES?](https://repost.aws/knowledge-center/ses-554-400-message-rejected-error) in the AWS Knowledge Center. diff --git a/_dashboards/reporting/rep-cli-index.md b/_dashboards/reporting/rep-cli-index.md new file mode 100644 index 00000000..11c3fa7a --- /dev/null +++ b/_dashboards/reporting/rep-cli-index.md @@ -0,0 +1,30 @@ +--- +layout: default +title: Reporting using the CLI +nav_order: 20 +parent: Reporting +has_children: true +redirect_from: + - /reporting/rep-cli-index/ + - /dashboards/reporting-cli/rep-cli-index/ +--- + +# Reporting using the CLI + +Use the Reporting CLI to generate reports from a script or a scheduler without opening OpenSearch Dashboards in a browser. The Reporting CLI opens the URL of a dashboard, visualization, notebook, or saved search in a headless Chromium browser, captures the page, and either saves the report to the current directory or sends it as an email attachment using Amazon Simple Email Service (Amazon SES) or SMTP. + +The Reporting CLI loads the page from a running OpenSearch Dashboards instance, so the instance must be reachable from the machine on which the Reporting CLI runs. + +The Reporting CLI supports the following report formats: + +- PDF and PNG reports of dashboards, visualizations, and notebooks. These reports do not require the Reporting plugin. +- CSV reports of saved searches. The Reporting CLI generates CSV reports using the **Reporting** menu in **Discover**, so CSV reports require the Reporting plugin to be installed in OpenSearch Dashboards. + +To connect to OpenSearch Dashboards, the Reporting CLI supports the following authentication types: + +- Basic HTTP authentication: Specify `-a basic` and provide credentials. +- Amazon Cognito authentication: Specify `-a cognito` and provide credentials. To learn more about Amazon Cognito, see [What is Amazon Cognito?](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html). +- SAML authentication using Okta as the identity provider: Specify `-a saml` and provide credentials. +- No authentication: Omit the `-a` option. + +To get started, see [Download and install the Reporting CLI tool]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-install/). diff --git a/_dashboards/reporting/rep-cli-install.md b/_dashboards/reporting/rep-cli-install.md new file mode 100644 index 00000000..f7652bba --- /dev/null +++ b/_dashboards/reporting/rep-cli-install.md @@ -0,0 +1,63 @@ +--- +layout: default +title: Download and install the Reporting CLI tool +nav_order: 10 +parent: Reporting using the CLI +grand_parent: Reporting +redirect_from: + - /reporting/rep-cli-install/ + - /dashboards/reporting-cli/rep-cli-install/ +--- + +# Download and install the Reporting CLI tool + +Install the Reporting CLI tool from either the `npm` software registry or an archive downloaded from OpenSearch.org. The Reporting CLI requires Node.js. + +To learn more about the `npm` software registry, see the [`npm`](https://docs.npmjs.com/about-npm) documentation. + +## Installing the Reporting CLI from npm + +To install the Reporting CLI from `npm`, run the following command: + +```bash +npm install -g @opensearch-project/reporting-cli +``` +{% include copy.html %} + +The `-g` option installs the Reporting CLI globally so that the `opensearch-reporting-cli` command is available in every directory. If you install the package without `-g`, run the command from the installation directory using `npx opensearch-reporting-cli`. + +## Installing the Reporting CLI from an archive + +Download the [Reporting CLI archive](https://artifacts.opensearch.org/reporting-cli/opensearch-reporting-cli-1.1.0.tgz), and then install the archive by running the following command: + +```bash +npm install -g opensearch-reporting-cli-1.1.0.tgz +``` +{% include copy.html %} + +To confirm that the archive was published by the OpenSearch Project and has not been modified, verify its signature using the [Reporting CLI signature file](https://artifacts.opensearch.org/reporting-cli/opensearch-reporting-cli-1.1.0.tgz.sig). +{: .important } + +To learn more about verifying signatures, see [How to verify signatures for downloadable artifacts](https://opensearch.org/verify-signatures/). + +## Verifying the installation + +To verify the installation and list all available options, run the following command: + +```bash +opensearch-reporting-cli -h +``` +{% include copy.html %} + +## Chromium + +The Reporting CLI renders reports using Chromium, which `npm` downloads when it runs the Puppeteer installation script during installation. If your `npm` configuration skips installation scripts, Chromium is not downloaded. + +The downloaded Chromium is an x86-64 binary on all macOS computers. On a Mac with Apple silicon, the Reporting CLI fails with the error `spawn Unknown system error -86` unless Rosetta 2 is installed. + +To use a different Chromium or Chrome binary, for example, an Arm64 build or a browser installed by your package manager, set the `CHROMIUM_PATH` environment variable to the path of the browser executable: + +```bash +export CHROMIUM_PATH=<path-to-chromium-executable> +``` +{% include copy.html %} diff --git a/_dashboards/reporting/rep-cli-lambda.md b/_dashboards/reporting/rep-cli-lambda.md new file mode 100644 index 00000000..30dbd6d5 --- /dev/null +++ b/_dashboards/reporting/rep-cli-lambda.md @@ -0,0 +1,178 @@ +--- +layout: default +title: Schedule reports with AWS Lambda +nav_order: 30 +parent: Reporting using the CLI +grand_parent: Reporting +redirect_from: + - /reporting/rep-cli-lambda/ + - /dashboards/reporting-cli/rep-cli-lambda/ +--- + +<!-- vale off --> +# Scheduling reports with AWS Lambda +<!-- vale on --> + +Use AWS Lambda to run the Reporting CLI in response to a trigger, such as a schedule. The Lambda function runs the Reporting CLI from a container image, so the OpenSearch Dashboards URL that you report on must be reachable from the Lambda function. + +The container image installs Google Chrome dependencies that are available only for the x86-64 architecture. To build the image, you need Docker. On a computer with a different architecture, such as a Mac with Apple silicon, build the image using the `--platform linux/amd64` option. + +### Prerequisites + +To use the Reporting CLI with AWS Lambda, you need to do the following preliminary steps. + +- Get an AWS account. For instructions, see [Creating an AWS account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html) in the AWS Account Management reference guide. +- Set up an Amazon Elastic Container Registry (Amazon ECR). For instructions, see [Getting started with Amazon ECR using the AWS Management Console](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-console.html). + +## Step 1: Create a container image with a Dockerfile + +You need to assemble the container image by running a Dockerfile. When you run the Dockerfile, it downloads the OpenSearch artifact required to use the Reporting CLI. To learn more about Dockerfiles, see [Dockerfile reference](https://docs.docker.com/engine/reference/builder/). + +Copy the following sample configurations into a Dockerfile: + +```dockerfile +# Define function directory +ARG FUNCTION_DIR="/function" + +# Base image of the docker container +FROM node:lts-slim AS build-image + +# Include global arg in this stage of the build +ARG FUNCTION_DIR + +# AWS Lambda runtime dependencies +RUN apt-get update && \ + apt-get install -y \ + g++ \ + make \ + unzip \ + libcurl4-openssl-dev \ + autoconf \ + automake \ + libtool \ + cmake \ + python3 \ + libkrb5-dev \ + curl + +# Copy function code +WORKDIR ${FUNCTION_DIR} +RUN npm install @opensearch-project/reporting-cli && npm install aws-lambda-ric + +# Build Stage 2: Copy Build Stage 1 files in to Stage 2. Install chrome, then remove chrome to keep the dependencies. +FROM node:lts-slim +# Include global arg in this stage of the build +ARG FUNCTION_DIR +# Set working directory to function root directory +WORKDIR ${FUNCTION_DIR} +# Copy in the build image dependencies +COPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR} + +# Install latest chrome dev package and fonts to support major char sets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others) +# Note: this installs the necessary libs to make the bundled version of Chromium that Puppeteer installs, work. +RUN apt-get update \ + && apt-get install -y wget gnupg \ + && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ + && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \ + && apt-get update \ + && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \ + --no-install-recommends \ + && apt-get remove -y google-chrome-stable \ + && rm -rf /var/lib/apt/lists/* + +ENTRYPOINT ["/usr/local/bin/npx", "aws-lambda-ric"] + +ENV HOME="/tmp" +CMD [ "/function/node_modules/@opensearch-project/reporting-cli/src/index.handler" ] + +``` + +Next, run the following build command within the same directory that contains the Dockerfile: + +```bash +docker build --platform linux/amd64 -t opensearch-reporting-cli . +``` +{% include copy.html %} + +## Step 2: Create a private repository with Amazon ECR + +You need to follow the instructions to create an image repository, see [Getting started with Amazon ECR using the AWS Management Console](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-console.html). + +Give your repository the name `opensearch-reporting-cli`. + +In addition to the Amazon ECR instructions, you need to make several adjustments for the Reporting CLI to function properly as described in the following steps in this procedure. + +## Step 3: Push the image to the private repository + +You need to get several commands from the AWS ECR Console to run within the Dockerfile directory. + +1. After you create your repository, select it from **Private repositories**. +1. Choose **view push commands**. +1. Copy and run each command shown in **Push commands for `opensearch-reporting-cli`** sequentially in the Dockerfile directory. + +For more details about Docker push commands, see [Pushing a Docker image](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html) in the Amazon ECR user guide. + +## Step 4: Create a Lambda function with the container image + +Now that you have a container image created for the Reporting CLI, you need to create a function defined as the container image. + +1. Open the AWS Lambda console and choose [Functions](https://us-west-2.console.aws.amazon.com/lambda/home?region=us-west-2#/functions). +1. Choose **Create function**, then choose **Container image** and fill in a name for the function. +1. In **Container image URI**, choose **Browse images** and select `opensearch-reporting-cli` for the image repository. +1. In **Images** select the image, and choose **Select image**. +1. In **Architecture**, choose **x86_64**. +1. Choose **Create function**. +1. Go to **Lambda** > **functions** and choose the function you created. +1. Choose **Configuration > General configuration > Edit timeout** and set the timeout in Lambda to 5 minutes to allow the Reporting CLI to generate the report. +1. Change the **Ephemeral storage** setting to at least 1024 MB. The default setting is not a sufficient storage amount to support report generation. +1. Test the function by providing values either in a JSON test event or as Lambda environment variables. + +To provide values that are the same for every run, such as the email addresses, set the corresponding environment variables, such as `OPENSEARCH_FROM` and `OPENSEARCH_TO`, in the Lambda function configuration. To provide values in the test event or trigger payload, use the long option names without the leading dashes as JSON keys, for example, `url`, `format`, `transport`, `from`, and `to`. For the `credentials` key, specify the value in the `<username>:<password>` format. For a list of options and environment variables, see [Reporting CLI options]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-options/). + +The following example event specifies the URL, the email transport, the sender and recipient email addresses, and the email subject: + +```json +{ + "url": "https://playground.opensearch.org/app/dashboards#/view/084aed50-6f48-11ed-a3d5-1ddbf0afc873", + "transport": "ses", + "from": "sender@example.com", + "to": "recipient@example.com", + "subject": "Test lambda docker image" +} +``` + +The Lambda function saves the report in the `/tmp` directory of the function, so specify an email transport to receive the report. + +To learn more about AWS Lambda functions, see [Deploying Lambda functions as container images](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-images.html) in the AWS Lambda documentation. + +## Step 5: Add the trigger to start the AWS Lambda function + +Set the trigger that starts the report. AWS Lambda can use other AWS services as triggers, such as Amazon Simple Notification Service (Amazon SNS), Amazon S3, or Amazon EventBridge. + +1. In the **Triggers** section, choose **Add trigger**. +1. Select a trigger from the list. To generate reports on a schedule, use an Amazon EventBridge schedule. For more information, see [Invoke a Lambda function on a schedule](https://docs.aws.amazon.com/lambda/latest/dg/with-eventbridge-scheduler.html) in the AWS Lambda documentation. +1. Choose **Test** to initiate the function. + +## (Optional) Step 6: Add the role permission for Amazon SES + +If you want to use Amazon SES for the email transport, you need to set up permissions. + +1. Select **Configuration** and choose **Execution role**. +1. In **Summary**, choose **Permissions**. +1. Select **{}JSON** to open the JSON policy editor. +1. Add the permissions for the Amazon SES resource that you want to use. + +The following example provides the resource ARN for the send email action: + +```json +{ +"Effect": "Allow", +"Action": [ + "ses:SendEmail", + "ses:SendRawEmail" + ], +"Resource": "arn:aws:ses:us-west-2:555555511111:identity/sender@example.com" +} +``` + +To learn more about setting role permissions, see [Permissions](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-images.html#gettingstarted-images-permissions) in the AWS Lambda user guide. \ No newline at end of file diff --git a/_dashboards/reporting/rep-cli-options.md b/_dashboards/reporting/rep-cli-options.md new file mode 100644 index 00000000..4ed4bb93 --- /dev/null +++ b/_dashboards/reporting/rep-cli-options.md @@ -0,0 +1,48 @@ +--- +layout: default +title: Reporting CLI options +nav_order: 30 +parent: Reporting using the CLI +grand_parent: Reporting +redirect_from: + - /reporting/rep-cli-options/ + - /dashboards/reporting-cli/rep-cli-options/ +--- + +# Reporting CLI options + +The `opensearch-reporting-cli` tool supports the following options. Option values are case sensitive and must be lowercase. Options provided on the command line take precedence over environment variables. For more information, see [Use environment variables with the Reporting CLI]({{site.url}}{{site.baseurl}}/dashboards/reporting/rep-cli-env-var/). + +| Option | Description | Environment variable | +| :--- | :--- | :--- | +| `-u`, `--url` | The OpenSearch Dashboards URL of the dashboard, visualization, notebook, or saved search. To get the URL, select **Share** > **Permalinks** > **Copy link**. Required. | `OPENSEARCH_URL` | +| `-a`, `--auth` | The authentication type. Valid values are `basic`, `cognito`, and `saml`. Requires credentials. To connect without authentication, omit this option. | N/A | +| `-c`, `--credentials` | The OpenSearch Dashboards login credentials in the `<username>:<password>` format. | `OPENSEARCH_USERNAME` and `OPENSEARCH_PASSWORD` | +| `-t`, `--tenant` | The tenant to select after login when multi-tenancy is enabled. Valid values are `private`, `global`, or the name of a custom tenant. A tenant specified in the URL takes precedence over this option. Default is `private`. | N/A | +| `--multitenancy` | Whether to select a tenant after login. Valid values are `true` and `false`. Default is `true`. | N/A | +| `-f`, `--format` | The file format of the report. Valid values are `pdf`, `png`, and `csv`. The `csv` format is supported only for saved searches. Default is `pdf`. | N/A | +| `-w`, `--width` | The browser window width, in pixels. Default is `1680`. | N/A | +| `-l`, `--height` | The minimum browser window height, in pixels. Default is `600`. | N/A | +| `-n`, `--filename` | The file name of the report, without the extension. Default is `opensearch-report-<timestamp>`. | `OPENSEARCH_FILENAME` | +| `-e`, `--transport` | The email transport. Valid values are `ses` (Amazon SES) and `smtp`. If not specified, the report is not sent by email. | `OPENSEARCH_TRANSPORT` | +| `-s`, `--from` | The sender email address. | `OPENSEARCH_FROM` | +| `-r`, `--to` | The recipient email address. To specify multiple recipients, separate the addresses with commas. | `OPENSEARCH_TO` | +| `--smtphost` | The host name of the SMTP server. | `OPENSEARCH_SMTP_HOST` | +| `--smtpport` | The port of the SMTP server. | `OPENSEARCH_SMTP_PORT` | +| `--smtpsecure` | Specify `true` to use TLS when connecting to the SMTP server. Any value enables TLS, including `false`, so to connect without TLS, omit this option. | `OPENSEARCH_SMTP_SECURE` | +| `--smtpusername` | The SMTP username. | `OPENSEARCH_SMTP_USERNAME` | +| `--smtppassword` | The SMTP password. | `OPENSEARCH_SMTP_PASSWORD` | +| `--selfsignedcerts` | Whether to accept a self-signed certificate from the SMTP server. Valid values are `true` and `false`. Default is `false`. | N/A | +| `--subject` | The email subject. Default is `This is an email containing your opensearch dashboard report`. | `OPENSEARCH_EMAIL_SUBJECT` | +| `--note` | The email body, either a string or the path to a text file. Default is `Hi,\nHere is the latest report!`. | `OPENSEARCH_EMAIL_NOTE` | +| `--timeout` | The maximum amount of time to wait for the page to load, in milliseconds. Default is `300000` (5 minutes). | `OPENSEARCH_TIMEOUT` | +| `-h`, `--help` | Displays the list of options. | N/A | + +## Getting help + +To get a list of all available options, run the following command: + +```bash +opensearch-reporting-cli -h +``` +{% include copy.html %} diff --git a/_dashboards/reporting/report-dashboard-index.md b/_dashboards/reporting/report-dashboard-index.md new file mode 100644 index 00000000..a4c18f9f --- /dev/null +++ b/_dashboards/reporting/report-dashboard-index.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Reporting using OpenSearch Dashboards +nav_order: 10 +parent: Reporting +redirect_from: + - /reporting/report-dashboard-index/ +--- + +# Reporting using OpenSearch Dashboards + +Use OpenSearch Dashboards to generate reports from the page that you are viewing and to create, manage, and delete report definitions. For information about report definitions, the file formats available for each report source, and the permissions required, see [Reporting]({{site.url}}{{site.baseurl}}/dashboards/reporting/). To perform these operations programmatically, see [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/). + +## Generating reports + +To generate a report from the interface, follow these steps: + +1. Open the dashboard, visualization, notebook, or saved search that you want to report on. +1. On the top menu, select **Reporting**. +1. Select the format: + - For dashboards, visualizations, and notebooks, select **Download PDF** or **Download PNG**. + - For saved searches in **Discover**, select **Generate CSV** or **Generate XLSX**. + + Reports are generated asynchronously in the background and might take a few minutes, depending on the size of the report. A notification appears when your report is ready, and the file is downloaded. + +To generate reports on a schedule, select **Create report definition** in the **Reporting** menu, and then proceed to [Creating reports using a definition](#creating-reports-using-a-definition). This option fills in many of the fields based on the page you were viewing. + +To view the reports that you generated, select **View reports** in the **Reporting** menu. + +## Creating reports using a definition + +Definitions let you generate reports on a periodic schedule. + +1. On the top menu, go to **OpenSearch Plugins** > **Reporting**. +1. In the **Report definitions** section, select **Create**. +1. In **Report settings**, enter a name and optional description for your report. +1. Choose the **Report source**: **Dashboard**, **Visualization**, **Saved search**, or **Notebook**. +1. Select your dashboard, visualization, saved search, or notebook. Then choose a time range for the report. +1. Choose a file format for the report. For a saved search, you can also set the **Record limit**. +1. (Optional) Add a header or footer to the report. Headers and footers are only available for dashboard, visualization, and notebook reports. +1. In **Report trigger**, choose either **On demand** or **Schedule**. + + For scheduled reports, select either **Recurring** or **Cron based**. Recurring reports run daily or at a specified interval. Cron expressions give you more flexibility. For more information, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). + +1. Select **Create**. + +## Deleting report definitions + +You can delete report definitions from OpenSearch Dashboards or by using the API. Deleting a report definition does not delete previously generated reports. + +Generated reports cannot be deleted individually. +{: .note} + +### Deleting from OpenSearch Dashboards + +To delete a report definition, follow these steps: + +1. On the top menu, go to **OpenSearch Plugins** > **Reporting**. +1. In the **Report definitions** section, select the name of the report definition you want to delete. +1. On the report definition details page, choose **Delete**. +1. In the confirmation dialog, choose **Delete**. + +### Deleting using the API + +To delete a report definition, send the following request: + +```json +DELETE _plugins/_reports/definition/{report_definition_id} +``` +{% include copy-curl.html %} + +To find the report definition ID, list all definitions: + +```json +GET _plugins/_reports/definitions +``` +{% include copy-curl.html %} + +For the full set of reporting endpoints, see [Reporting API]({{site.url}}{{site.baseurl}}/dashboards/reporting/api/). + +## Troubleshooting + +You can use the following topics to troubleshoot and resolve issues with reporting. + +### Chromium fails to launch with OpenSearch Dashboards + +While creating a report for dashboards or visualizations, you might see the following error: + +![OpenSearch Dashboards reporting pop-up error message]({{site.url}}{{site.baseurl}}/images/reporting-error.png) + +This problem can occur for two reasons: + +- You don't have the correct version of `headless-chrome` to match the operating system on which OpenSearch Dashboards is running. Download the [correct version](https://github.com/opensearch-project/reporting/releases/tag/chromium-1.12.0.0). + +- You're missing additional dependencies. Install the required dependencies for your operating system from the [additional libraries](https://github.com/opensearch-project/dashboards-reports/blob/1.x/dashboards-reports/rendering-engine/headless-chrome/README.md#additional-libaries) section. + +### Characters not loading in reports + +You might encounter an issue where UTF-8 encoded characters look fine in your browser, but they don't load in your generated reports because you're missing the required font dependencies. Install the [font dependencies](https://github.com/opensearch-project/dashboards-reports#missing-font-dependencies), and then generate your reports again. diff --git a/_dashboards/reporting/report-definition-access-control.md b/_dashboards/reporting/report-definition-access-control.md new file mode 100644 index 00000000..84eece6d --- /dev/null +++ b/_dashboards/reporting/report-definition-access-control.md @@ -0,0 +1,140 @@ +--- +layout: default +title: Report definition access control +nav_order: 40 +parent: Reporting +redirect_from: + - /reporting/report-definition-access-control/ +--- + +# Report definition access control + +The Reporting plugin integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for report definition records. This replaces the legacy `plugins.alerting.filter_by_backend_roles` setting with a more flexible sharing system that allows resource owners to grant specific access levels to users, roles, or backend roles. + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +The following table describes the report definition resource configuration. + +| Field | Value | +| :--- |:----------------------------------| +| Resource type | `report-definition` | +| System index | `.opendistro-reports-definitions` | +| Onboarded version | OpenSearch 3.5 | + +When resource-level authorization is enabled for report definitions, each report definition's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +## Enable report definition resource sharing + +To enable resource sharing for report definitions, you must add the report definition resource type to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for report definitions: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "report-definition" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["report-definition"] + } +} +``` +{% include copy-curl.html %} + +When adding the report definition resource type to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Report definition access levels + +Reporting provides the following predefined access levels for report definition documents. These access levels determine the specific permissions granted to users who have been granted access to a report definition resource. + +### rd_read_only + +The `rd_read_only` read-only access level grants users the ability to view and search shared report definitions but not modify them. This access level includes the following permissions: + +```yaml +- "cluster:admin/opendistro/reports/definition/get" +- "cluster:admin/opendistro/reports/definition/list" +- "cluster:admin/opendistro/reports/instance/get" +- "cluster:admin/opendistro/reports/instance/list" +- "cluster:admin/opendistro/reports/menu/download" +``` +{% include copy.html %} + +### rd_read_write + +The `rd_read_write` read-write access level grants users full access to report definition operations except for sharing capabilities. This access level includes all read permissions plus write operations: + +```yaml +- "cluster:admin/opendistro/reports/definition/*" +- "cluster:admin/opendistro/reports/instance/*" +- "cluster:admin/opendistro/reports/menu/download" +``` +{% include copy.html %} + +### rd_full_access + +The `rd_full_access` full access level grants users complete control over a report definition, including owner-like permissions such as sharing the resource with other users. This access level includes all report definition operations plus resource sharing permissions: + +```yaml +- "cluster:admin/opendistro/reports/definition/*" +- "cluster:admin/opendistro/reports/instance/get" +- "cluster:admin/opendistro/reports/instance/list" +- "cluster:admin/opendistro/reports/menu/download" +- "cluster:admin/security/resource/share" +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Reporting GitHub repository](https://github.com/opensearch-project/reporting/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking report definitions as a protected resource type, cluster administrators must run the Migrate API to transfer existing report definition sharing information from the legacy framework to the new resource sharing system. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Use the following API call to migrate legacy report definition sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-reports-definitions", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "report-definition": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own report definitions without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available report definition access levels: `rd_read_only`, `rd_read_write`, or `rd_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance +- [Report instance access control]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-instance-access-control/) -- Access control for report instances \ No newline at end of file diff --git a/_dashboards/reporting/report-instance-access-control.md b/_dashboards/reporting/report-instance-access-control.md new file mode 100644 index 00000000..511732af --- /dev/null +++ b/_dashboards/reporting/report-instance-access-control.md @@ -0,0 +1,135 @@ +--- +layout: default +title: Report instance access control +nav_order: 50 +parent: Reporting +redirect_from: + - /reporting/report-instance-access-control/ +--- + +# Report instance access control + +The Reporting plugin integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for report instance records. This replaces the legacy `plugins.alerting.filter_by_backend_roles` setting with a more flexible sharing system that allows resource owners to grant specific access levels to users, roles, or backend roles. + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +The following table describes the report instance resource configuration. + +| Field | Value | +| :--- |:----------------------------------| +| Resource type | `report-instance` | +| System index | `.opendistro-reports-instances` | +| Onboarded version | OpenSearch 3.5 | + +When resource-level authorization is enabled for report instances, each report instance's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +## Enable report instance resource sharing + +To enable resource sharing for report instances, you must add the report instance resource type to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for report instances: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "report-instance" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["report-instance"] + } +} +``` +{% include copy-curl.html %} + +When adding the report instance resource type to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Report instance access levels + +Reporting provides the following predefined access levels for report instance documents. These access levels determine the specific permissions granted to users who have been granted access to a report instance resource. + +### ri_read_only + +The `ri_read_only` read-only access level grants users the ability to view and search shared report instances but not modify them. This access level includes the following permissions: + +```yaml +- "cluster:admin/opendistro/reports/instance/get" +- "cluster:admin/opendistro/reports/instance/list" +- "cluster:admin/opendistro/reports/menu/download" +``` +{% include copy.html %} + +### ri_read_write + +The `ri_read_write` read-write access level grants users full access to report instance operations except for sharing capabilities. This access level includes all read permissions plus write operations: + +```yaml +- "cluster:admin/opendistro/reports/instance/*" +- "cluster:admin/opendistro/reports/menu/download" +``` +{% include copy.html %} + +### ri_full_access + +The `ri_full_access` full access level grants users complete control over a report instance, including owner-like permissions such as sharing the resource with other users. This access level includes all report instance operations plus resource sharing permissions: + +```yaml +- "cluster:admin/opendistro/reports/instance/*" +- "cluster:admin/opendistro/reports/menu/download" +- "cluster:admin/security/resource/share" +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Reporting GitHub repository](https://github.com/opensearch-project/reporting/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking report instances as a protected resource type, cluster administrators must run the Migrate API to transfer existing report instance sharing information from the legacy framework to the new resource sharing system. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Use the following API call to migrate legacy report instance sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-reports-instances", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "report-instance": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own report instances without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available report instance access levels: `ri_read_only`, `ri_read_write`, or `ri_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance +- [Report definition access control]({{site.url}}{{site.baseurl}}/dashboards/reporting/report-definition-access-control/) -- Access control for report definitions \ No newline at end of file diff --git a/_dashboards/search-telemetry.md b/_dashboards/search-telemetry.md index 3b9af82b..712a3e63 100644 --- a/_dashboards/search-telemetry.md +++ b/_dashboards/search-telemetry.md @@ -1,7 +1,8 @@ --- layout: default title: Search telemetry -nav_order: 140 +parent: Settings and administration +nav_order: 70 --- diff --git a/_dashboards/settings-and-administration.md b/_dashboards/settings-and-administration.md new file mode 100644 index 00000000..4ac0b970 --- /dev/null +++ b/_dashboards/settings-and-administration.md @@ -0,0 +1,20 @@ +--- +layout: default +title: Settings and administration +nav_order: 140 +has_children: true +has_toc: false +--- + +# Settings and administration + +Configure and administer OpenSearch Dashboards at the deployment level by editing the `opensearch_dashboards.yml` configuration file. This documentation is intended for OpenSearch Dashboards administrators. The following settings are available: + +- [Custom branding]({{site.url}}{{site.baseurl}}/dashboards/branding/): Replace the default OpenSearch logo and other branding elements with your own. +- [Network compression]({{site.url}}{{site.baseurl}}/dashboards/compression/): Compress JavaScript and CSS bundles to reduce network transfer sizes. +- [Configuring CSP rules]({{site.url}}{{site.baseurl}}/dashboards/csp/csp-dynamic-configuration/): Enforce Content Security Policy (CSP) rules to protect against cross-site scripting and other code injection attacks. +- [Search telemetry]({{site.url}}{{site.baseurl}}/dashboards/search-telemetry/): Analyze search request performance in OpenSearch Dashboards. + +## Related documentation + +- To configure data access, index patterns, saved objects, and other settings from within the Dashboards UI, see [Dashboards management]({{site.url}}{{site.baseurl}}/dashboards/management/management-index/). diff --git a/_dashboards/sm-dashboards.md b/_dashboards/sm-dashboards.md index 3f6cd11d..b43e2168 100644 --- a/_dashboards/sm-dashboards.md +++ b/_dashboards/sm-dashboards.md @@ -1,12 +1,12 @@ --- layout: default -title: Snapshot Management +title: Snapshot management nav_order: 90 redirect_from: - /dashboards/admin-ui-index/sm-dashboards/ --- -# Snapshot Management +# Snapshot management in OpenSearch Dashboards [Snapshots]({{site.url}}{{site.baseurl}}/opensearch/snapshots/index/) are backups of a cluster’s indexes and state. The state includes cluster settings, node information, index metadata (mappings, settings, templates), and shard allocation. The Snapshot Management (SM) interface in OpenSearch Dashboards provides a unified solution for taking and restoring snapshots. @@ -132,7 +132,7 @@ The **Delete** button [deletes]({{site.url}}{{site.baseurl}}/api-reference/snaps 1. From the OpenSearch Dashboards main menu, select **Management** > **Snapshot Management**. 1. In the left panel, under **Snapshot Management**, select **Snapshots**. The **Snapshots** tab is selected by default. 1. Select the checkbox next to the snapshot you want to restore. An example is shown in the following image: - <img src="{{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-main.png" alt="Snapshots">{: .img-fluid} + ![Snapshots]({{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-main.png) {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/star-icon.png" class="inline-icon" alt="star icon"/>{:/} **Note:** You can only restore snapshots with the status of `Success` or `Partial`. The status of the snapshot is displayed in the **Snapshot status** column. {: .note purple} @@ -140,7 +140,7 @@ The **Delete** button [deletes]({{site.url}}{{site.baseurl}}/api-reference/snaps The **Restore snapshot** flyout lists the snapshot name and status. To view the list of indexes in the snapshot, select the number under **Indices** (for example, `27` in the following image). This number represents the number of indexes in the snapshot. - <img src="{{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot.png" alt="Restore Snapshot" width="450"> + ![Restore Snapshot]({{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot.png){: width="450" } For more information about the options in the **Restore snapshot** flyout, see [Restore snapshots]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore#restore-snapshots). @@ -156,7 +156,7 @@ The **Delete** button [deletes]({{site.url}}{{site.baseurl}}/api-reference/snaps The examples in the following image set `index.number_of_replicas` to `0`, `index.auto_expand_replicas` to `true`, and `index.refresh_interval` and `index.max_script_fields` to the cluster default values for all newly restored indexes. - <img src="{{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-custom.png" alt="Custom settings" width="450"> + ![Custom settings]({{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-custom.png){: width="450" } For more information about index settings, see [Index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/). @@ -165,7 +165,7 @@ The **Delete** button [deletes]({{site.url}}{{site.baseurl}}/api-reference/snaps After choosing the options, select the **Restore snapshot** button. 1. (Optional) To monitor the restore progress, select **View restore activities** in the confirmation dialog. You can also monitor the restore progress at any time by selecting the **Restore activities in progress** tab, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-activities.png" alt="Restore Activities">{: .img-fluid} + ![Restore Activities]({{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-activities.png) You can view the percentage of the job that has been completed in the **Status** column. Once the snapshot restore is complete, the **Status** changes to `Completed (100%)`. @@ -173,8 +173,8 @@ The **Delete** button [deletes]({{site.url}}{{site.baseurl}}/api-reference/snaps {: .note purple} To view the status of each index being restored, select the link in the **Indices being restored** column (in the preceding image, the `27 Indices` link). The **Indices being restored** flyout (shown in the following image) displays each index and its restore status. - <img src="{{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-indices.png" alt="Restore Indices">{: .img-fluid} + ![Restore Indices]({{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-indices.png) After the restore operation is complete, the restored indexes are listed in the **Indices** panel. To view the indexes, in the left panel, under **Index Management**, choose **Indices**. -<img src="{{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-indices-panel.png" alt="View Indices">{: .img-fluid} +![View Indices]({{site.url}}{{site.baseurl}}/images/restore-snapshot/restore-snapshot-indices-panel.png) diff --git a/_dashboards/visualize/index.md b/_dashboards/visualize/index.md new file mode 100644 index 00000000..8ff46d4d --- /dev/null +++ b/_dashboards/visualize/index.md @@ -0,0 +1,53 @@ +--- +layout: default +title: Building data visualizations +nav_order: 60 +has_children: true +has_toc: false +redirect_from: + - /dashboards/visualize/ + - /dashboards/visualize/gantt/ +--- + +# Building data visualizations + +OpenSearch Dashboards provides two approaches for creating data visualizations: building visualizations visually and building visualizations using queries. Both produce charts that you can save and add to dashboards. + +## Choosing a visualization approach + +When you select **Create new** in a dashboard (or **Create new visualization** in the **Visualize** app), a dialog presents the available visualization types. The first option, **Add visualization**, opens the query-based visualization editor. All other options (such as **Area**, **Line**, or **Pie**) open the visual point-and-click tool. + +The following table compares the two approaches. *Italicized* visualization types are unique to that approach. + +If you're getting started, use the **Visualize** application to build visualizations visually---it's available by default in all installations. Building visualizations using queries requires additional configuration and PPL or PromQL knowledge. +{: .tip} + +| | Creating visualizations in the Visualize application | Creating visualizations using queries | +| :--- | :--- | :--- | +| **Entry point** | In the **Create new** dialog, select a chart type (Area, Line, Pie, and others) | In the **Create new** dialog, select **Add visualization** | +| **Configuration** | Configure metrics and buckets using point-and-click panels. Use DQL in the search bar to filter data. | Write Piped Processing Language (PPL) or Prometheus Query Language (PromQL) queries to define the data. The editor automatically suggests a chart type. | +| **Visualization types** | - Area<br>- Bar<br>- *Coordinate map*<br>- *Data table*<br>- Gauge<br>- Heatmap<br>- Line<br>- *Metric*<br>- Pie<br>- *Region map*<br>- *Tag cloud*<br>- *Timeline*<br>- *TSVB*<br>- *Vega*<br>- *VisBuilder* | - Area<br>- Bar<br>- *Bar gauge*<br>- Gauge<br>- Heatmap<br>- Line<br>- Pie<br>- *Scatter*<br>- *State timeline* | +| **Prerequisites** | None (available by default in all installations) | Requires `workspace.enabled: true` and `explore.enabled: true` in `opensearch_dashboards.yml`. If these settings are not enabled by your administrator, the visualization editor is not available. | +| **Best for** | Aggregation-based analysis without writing queries | Query-driven exploration where you need precise control over data shaping | +| **Application** | [**Visualize** application]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/) | [Visualization editor]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/) | + +## Creating visualizations in the Visualize application + +The **Visualize** application uses a point-and-click interface to build visualizations from aggregations. Select a chart type, choose an index pattern, configure metrics and buckets, and render the result, as shown in the following image. Use the [DQL]({{site.url}}{{site.baseurl}}/dashboards/dql/) search bar to filter the underlying data. + +![Visualize application showing a line chart with point-and-click configuration panels]({{site.url}}{{site.baseurl}}/images/dashboards/visualize-app-example.png) + +For more information, see [Creating visualizations in the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/). + +## Creating visualizations using queries + +The visualization editor lets you write PPL or PromQL queries and map query results directly to chart fields. The editor automatically suggests a chart type based on the shape of your query results and maps fields to axes, as shown in the following image. This approach supports [dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/) for interactive filtering. + +![Visualization editor showing a multi-line chart built from a PPL query with dashboard variables]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/visualization-editor-example.png) + +For more information, see [Creating visualizations using queries]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/). + +## Related documentation + +- [Exploring data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/) +- [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/) diff --git a/_dashboards/visualize/visualization-editor/area-chart.md b/_dashboards/visualize/visualization-editor/area-chart.md new file mode 100644 index 00000000..00bf5ed4 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/area-chart.md @@ -0,0 +1,103 @@ +--- +layout: default +title: Area chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 10 +--- + +# Area charts in the visualization editor + +An area chart plots data points connected by lines and fills the region below each line. Use an area chart to show volume and composition over time. Stack multiple series to see how each category contributes to the total. + +## Creating an area chart + +The following examples build on each other, starting with a basic chart and adding complexity. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic area chart + +Start with an aggregation query that counts events over time: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1d) +``` +{% include copy.html %} + +After running this query, the visualization editor automatically maps the fields: + +- The **X-Axis** displays the `SPAN(@timestamp, 1d)` field. +- The **Y-Axis** displays the `count()` field. + +The result is a single filled area showing the event count per day, as shown in the following image. + +![Basic area chart showing count over time]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/area-chart-basic-result.png){: width="100%" } + +### Stacked area chart + +Add a third dimension to your query to split the data into multiple stacked series by category: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1d), response +``` +{% include copy.html %} + +This query groups the count by both time and the `response` field (HTTP status codes). Select `response` as the **Color** field to render a separate stacked area for each status code value (for example, 200, 404, 503). + +The result is a stacked area chart that displays each HTTP response code in a distinct color. The chart stacks the areas on top of each other, showing both individual category volumes and the total across all categories, as shown in the following image. + +![Stacked area chart showing counts by HTTP response code]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/area-chart-stacked-result.png){: width="100%" } + +## Configuring an area chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a date or numeric field for the horizontal axis that defines the buckets along which data is plotted (for example, `SPAN(@timestamp, 1d)`). | +| **Y-Axis** | Select one or more numeric fields to plot as separate areas. When multiple fields are selected, each renders as its own area layer. | +| **Color** | Select a categorical field to split the data into multiple stacked series, each rendered in a different color. For example, use a `response` status code field to display separate stacked areas for each HTTP status code. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Area + +The following settings control the area fill, line style, and value display. + +| Setting | Description | +| --- | --- | +| **Stack** | Controls how multiple series are displayed. **None** overlays the series without stacking. **Stack** adds series values together. **Percentage** stacks series as percentages of the total. | +| **Fill opacity** | Sets the opacity of the filled area below the line. | +| **Gradient mode** | Controls the fill gradient. **None** uses a solid fill. **Opacity** fades the fill toward the baseline. **Hue** uses a lighter color toward the baseline. | +| **Line style** | Controls whether the chart displays lines with points (**Default**), lines only (**Line only**), or points only (**Dots only**). | +| **Line dash style** | Sets the line pattern to **Solid**, **Dashed**, or **Dotted**. | +| **Interpolation** | Determines how points are connected. **Straight** draws direct lines between points. **Smooth** applies a curve. **Stepped** creates a staircase pattern. | +| **Line width** | Sets the thickness of the line in pixels. Supports values in the 1–10 range. | +| **Show values** | Shows value labels on the chart. | +| **Show current time marker** | Shows a vertical marker for the current time. This setting is available only when the X-axis uses a date field. | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### Legend + +For information about configuring the legend, see [Legend]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#legend). + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/bar-chart.md b/_dashboards/visualize/visualization-editor/bar-chart.md new file mode 100644 index 00000000..ab067328 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/bar-chart.md @@ -0,0 +1,130 @@ +--- +layout: default +title: Bar chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 15 +--- + +# Bar charts in the visualization editor + +A bar chart displays data as vertical or horizontal bars. Use a bar chart to compare discrete categories. Select a **Color** field to split categories into subgroups, and add threshold lines to flag values higher or lower than a target. + +## Creating a bar chart + +The following examples build on each other, starting with a basic chart and adding complexity. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic bar chart + +Start with an aggregation query that counts events by category: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by Carrier +``` +{% include copy.html %} + +After running this query, the visualization editor automatically selects a **Bar** chart and maps the fields: + +- The **X-Axis** displays the `Carrier` field. +- The **Y-Axis** displays the `count()` field. + +The result is a bar chart comparing the event count for each carrier, as shown in the following image. + +![Basic bar chart showing count by carrier]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-chart-basic-result.png){: width="100%" } + +### Grouped bar chart + +Add a second dimension to your query to split each category into sub-groups: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by Carrier, Cancelled +``` +{% include copy.html %} + +This query groups the count by both carrier and the `Cancelled` field. Select `Cancelled` as the **Color** field to render a separate bar for each cancellation status within each carrier. + +The result is a grouped bar chart in which each carrier has two bars side by side---one for non-canceled flights and one for canceled flights---making it easy to compare the flight counts for each cancellation status, as shown in the following image. + +![Grouped bar chart showing count by carrier and cancellation status]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-chart-grouped-result.png){: width="100%" } + +### Adding thresholds + +Use thresholds to add reference lines and color-code bars based on a target value. + +Using the same grouped bar chart from the previous example, configure the settings panel: + +1. In the **Bar** section, enable **Use threshold colors**. +1. In the **Thresholds** section, select **+ Add threshold**. +1. Set the base color to green (`#00BD6B`) and add a threshold at value `200` with a red color (`#F13939`). +1. Set **Threshold lines mode** to **Dashed lines**, as shown in the following image. + +![Bar chart settings with threshold configured at 200]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-chart-threshold-settings.png){: width="400" } + +The result shows bars colored according to the threshold rules: bars below 200 appear green, while bars above 200 appear red. A dashed reference line at 200 provides a clear visual anchor, as shown in the following image. + +![Bar chart with threshold coloring and dashed reference line at 200]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-chart-threshold-result.png){: width="100%" } + +## Configuring a bar chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a categorical or date field that defines the groups along the horizontal axis (for example, `Carrier`). | +| **Y-Axis** | Select one or more numeric fields that determine the height of the bars. When multiple fields are selected, each renders as a separate bar within each category group. | +| **Color** | Select a categorical field to split each category into grouped bars, each rendered in a different color. For example, use a `Cancelled` field to show separate bars for canceled and non-canceled flights within each carrier. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + + +### Bar + +The following settings control the display style and sizing of bars. + +| Setting | Description | +| --- | --- | +| **Stack** | Controls how multiple series are displayed. **None** overlays the series without stacking. **Stack** adds series values together. **Percentage** stacks series as percentages of the total. | +| **Fill opacity** | Sets the opacity of the bars. | +| **Size** | Controls bar width. **Auto** sizes bars automatically. **Manual** sets a specific width percentage (1–100). | +| **Radius** | Sets the corner rounding of each bar in pixels. | +| **Show values** | Shows value labels on the chart. | +| **Use threshold colors** | When enabled, the chart colors bars based on the threshold rules defined in the **Thresholds** section. | +| **Show border** | When enabled, adds a border around each bar. | +| **Border width** | Sets the border thickness in pixels. This setting is available when **Show border** is enabled. | +| **Border color** | Sets the border color. This setting is available when **Show border** is enabled. | + +### Bucket + +The following settings control how data is aggregated within each bar. + +| Setting | Description | +| --- | --- | +| **Type** | The aggregation type used to calculate the value for each bucket. Supported values: **Sum**, **Average**, **Min**, **Max**, **Count**. | +| **Interval** | The time interval for grouping data into buckets. Supported values: **Auto**, **Month**, **Day**, **Hour**, **Minute**, **Second**. | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### Legend + +For information about configuring the legend, see [Legend]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#legend). + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/bar-gauge-chart.md b/_dashboards/visualize/visualization-editor/bar-gauge-chart.md new file mode 100644 index 00000000..62e1ca60 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/bar-gauge-chart.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Bar gauge chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 20 +--- + +# Bar gauge charts in the visualization editor + +A bar gauge chart displays numeric values as horizontal or vertical bars against a scale, reducing each field to a single value. Unlike a bar chart, a bar gauge chart is designed for comparing values against defined thresholds. + +## Creating a bar gauge chart + +The following examples build on each other, starting with a basic chart and adding complexity. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic bar gauge chart + +Start with a query that groups a numeric metric by a categorical field: + +```sql +source = opensearch_dashboards_sample_data_logs | stats avg(bytes) by machine.os +``` +{% include copy.html %} + +After running this query, select **Bar Gauge** as the chart type. The fields are mapped as follows: + +- The **X-Axis** displays the `machine.os` field (categorical). +- The **Y-Axis** displays the `avg(bytes)` field (numerical). + +The result is a set of vertical bars, one for each operating system, showing the average bytes for each. The **Show unfilled area** toggle is enabled by default, displaying a grey background behind each bar to indicate the remaining distance to the maximum, as shown in the following image. + +![Basic bar gauge showing average bytes by operating system]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-gauge/bar-gauge-initial.png){: width="100%" } + +### Adding thresholds and display styles + +Open the **Thresholds** section and define breakpoints to color-code the bars. For example: + +- Base color: green (values below 3000) +- Threshold at 3000: orange (moderate range) +- Threshold at 5000: red (high range) + +Then in the **Bar Gauge** section, switch the **Display style** to see different visual treatments: + +**Gradient**---Each bar fills with a smooth color transition through the thresholds it passes, as shown in the following image. + +![Bar gauge with gradient display style]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-gauge/bar-gauge-gradient.png){: width="100%" } + +**Stack**---Each bar is divided into distinct colored segments at threshold boundaries, as shown in the following image. + +![Bar gauge with stack display style]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-gauge/bar-gauge-stack.png){: width="100%" } + +**Basic**---Each bar uses a single solid color based on the highest threshold the value reaches, as shown in the following image. + +![Bar gauge with basic display style]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-gauge/bar-gauge-basic.png){: width="100%" } + +## Configuring a bar gauge chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a categorical field (for category labels) or a numerical field (for bar values). | +| **Y-Axis** | Select the complementary field. If X-Axis is categorical, select a numeric field for Y-Axis (and the other way around). | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Value options + +| Setting | Description | +| --- | --- | +| **Calculation** | Determines how multiple data points for the same category are reduced to a single value. Supported values: **Last \***, **Last**, **First \***, **First**, **Min**, **Max**, **Mean**, **Median**, **Variance**, **Count**, **Distinct count**, **Total**. For more information, see [Value calculations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations/). | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Bar gauge + +| Setting | Description | +| --- | --- | +| **Display style** | Controls how the bar fill is rendered. **Gradient** fills the bar with a smooth color gradient generated from thresholds. **Stack** shows distinct colored segments for each threshold range. **Basic** fills the bar with a single solid color from the matching threshold. | +| **Value display** | Controls how the numeric value label is colored. **Value Color** colors the text with the mapped threshold. **Text Color** uses the default text color. **Hidden** hides the value entirely. | +| **Show unfilled area** | When enabled, displays a grey background behind the filled portion of each bar, making it easier to see the remaining distance to the maximum. | + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/configuring-visualizations/index.md b/_dashboards/visualize/visualization-editor/configuring-visualizations/index.md new file mode 100644 index 00000000..84cc30c3 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/configuring-visualizations/index.md @@ -0,0 +1,98 @@ +--- +layout: default +title: Configuring visualizations +parent: Creating visualizations using queries +grand_parent: Building data visualizations +nav_order: 90 +has_children: true +has_toc: false +redirect_from: + - /dashboards/visualize/visualization-editor/configuring-visualizations/ +--- + +# Configuring visualizations in the visualization editor + +The visualization editor provides shared configuration options that apply across multiple visualization types. Each visualization type page documents its specific options. The following configurations are common to most visualizations. + +## Fields + +The **Fields** panel maps query result columns to chart axes. Select which fields to use for the X-axis, Y-axis, and optional dimensions like color or size. Available field mappings depend on the chart type. + +## Split + +Use the **Split** option when your data has more dimensions than a single chart can display. For example, if your query returns three dimensions but a line chart can only show two (X-axis and Y-axis), use Split to create multiple charts by splitting the data along the third dimension. Each resulting chart shows the same axes but filtered to a different value of the split field. + +To create a split visualization, follow these steps: + +1. In the dashboard, select **Create new** > **Add visualization**. +1. Select `opensearch_dashboards_sample_data_logs` as the dataset. +1. In the query editor, enter the following query and select **Update**: + + ```sql + | stats count() by span(`@timestamp`, 1h), extension, `machine.os` + ``` + {% include copy.html %} + +1. In the time filter, select **Last 15 days**. +1. Set **Visualization type** to **Line**. +1. In **Fields**, configure the following settings: + - **X-Axis**: Select `span(@timestamp,1h)`. + - **Y-Axis**: Select `count()`. +1. In **Split**, configure the following settings: + - **Split by**: Select `machine.os`. + - Toggle **Show labels** to on. + +The visualization displays a separate line chart for each `machine.os` value (for example, `win xp`, `osx`, `win 7`, `win 8`, `ios`), each showing the event count over time, as shown in the following image. + +![Split visualization showing separate line charts for each machine.os value]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/split-example.png) + +## Axes + +The X-axis and Y-axis share the same configuration options. Each axis can be independently customized. + +| Setting | Description | +| --- | --- | +| **Show axis** | Shows or hides the axis. | +| **Title** | A custom label for the axis. | +| **Position** | Controls the placement of the axis relative to the chart. Supported values: X-axis: **Top**, **Bottom**. Y-axis: **Left**, **Right**. | +| **Show grid lines** | When enabled, shows grid lines extending from the axis into the chart area. | +| **Show labels** | When enabled, shows category labels along the axis. | +| **Alignment** | Controls the rotation of axis labels: **Horizontal** (0°), **Vertical** (90°), or **Angled** (45°). | +| **Truncate after** | Sets the maximum character length for axis labels before truncation. | + +Axes are available in area, bar, heatmap, histogram, line, scatter, and state timeline charts. + +## Tooltip + +The **Tooltip** panel controls what information appears when you hover over a data point. Options include showing all series values or only the hovered series. + +Tooltips are available in area, bar, bar gauge, heatmap, histogram, line, pie, scatter, and state timeline charts. + +## Legend + +The **Legend** panel controls the display and position of the chart legend. Options include showing or hiding the legend and selecting its position (top, bottom, left, or right). + +Legends are available in heatmap, pie, scatter, and state timeline charts. + +## Standard options + +Standard options control how numeric values are formatted in the visualization. For details, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +## Value options + +Value options control how values are calculated and displayed for single-value visualizations. + +| Setting | Description | +| --- | --- | +| **Calculation** | The function used to reduce a series to a single value (for example, Last, Mean, Max, Min). For details, see [Value calculations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations/). | +| **Show** | Controls whether to display the calculated value, the value name, or both. | + +Value options are available in bar gauge, gauge, and metric charts. + +## Thresholds + +Thresholds define color-coded boundaries that indicate when values cross important limits. For details, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +## Value calculations + +Value calculations determine how a series of values is reduced to a single number for display (for example, Last, Mean, Sum, Min, Max). For details, see [Value calculations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations/). diff --git a/_dashboards/visualize/visualization-editor/configuring-visualizations/standard-options.md b/_dashboards/visualize/visualization-editor/configuring-visualizations/standard-options.md new file mode 100644 index 00000000..4181a733 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/configuring-visualizations/standard-options.md @@ -0,0 +1,91 @@ +--- +layout: default +title: Standard options +parent: Configuring visualizations +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 30 +--- + +# Standard options + +Standard options control how numeric values are formatted in a visualization. Use them to set units, custom suffixes, decimal precision, and, for charts with a scale, minimum and maximum values. + +## Supported chart types + +The following table lists the standard options supported by each visualization type. + +| Visualization type | Minimum and maximum | Units | Unit suffix | Decimals | +| --- | --- | --- | --- | --- | +| [Area chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/area-chart/) | Yes | Yes | Yes | Yes | +| [Bar chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/bar-chart/) | Yes | Yes | Yes | Yes | +| [Bar gauge chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/bar-gauge-chart/) | Yes | Yes | Yes | Yes | +| [Gauge chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/gauge-chart/) | Yes | Yes | Yes | Yes | +| [Heatmap]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/heatmap-chart/) | No | Yes | Yes | Yes | +| [Histogram]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/histogram-chart/) | Yes | Yes | Yes | Yes | +| [Line chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/line-chart/) | Yes | Yes | Yes | Yes | +| [Metric chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/metric-chart/) | No | Yes | Yes | Yes | +| [Pie chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/pie-chart/) | No | Yes | Yes | Yes | +| [Scatter plot]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/scatter-chart/) | Yes | Yes | Yes | Yes | +| [State timeline]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/state-timeline-chart/) | No | No | No | No | +| [Table]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/table-chart/) | No | No | No | No | + +## Options + +The following table describes the available standard options. + +| Setting | Description | +| --- | --- | +| **Min** | The lower bound of the value scale. For Cartesian charts, this sets the value-axis minimum. For gauge and bar gauge charts, this sets the scale minimum. | +| **Max** | The upper bound of the value scale. For Cartesian charts, this sets the value-axis maximum. For gauge and bar gauge charts, this sets the scale maximum. | +| **Units** | The unit displayed with the value. Some units, such as currency symbols, appear before the value. Other units appear after the value or scale the value automatically. | +| **Unit suffix** | Custom text appended after the unit or value, for example, `/sec`. Use this setting to show custom units or rates. | +| **Decimals** | The number of decimal places to display. Leave this setting empty to use automatic precision. | + +## Units + +The **Units** menu groups common formats such as numbers, percentages, currencies, data units, time units, mass units, and length units. + +For unit groups that support scaling, the selected unit acts as the input unit, and the visualization converts the value to the most readable unit in the same group. For example, if **Units** is set to `bytes(B)`, a value of `1000` is displayed as `1 KB`. + +Some units only change the displayed label or symbol. For example, a currency unit can display a symbol before the value, while a percentage unit appends `%`. + +The following metric chart displays an underlying value of `7911` with **Units** set to `bytes(B)`. + +![Metric chart displaying 7.91 KB for an underlying value of 7911 with the unit set to bytes]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/metric-chart-unit-byte.png) + +## Unit suffix + +Use **Unit suffix** to append custom text after the formatted value. This is useful for rates or custom units. + +For example, to display byte rates in a metric chart, set **Units** to `bytes(B)` and set **Unit suffix** to `/sec`. With **Decimals** set to automatic precision, an underlying value of `14074` total bytes is displayed as `14.07 KB/sec`. + +![Metric chart displaying 14.07 KB/sec for an underlying value of 14074 with the unit set to bytes and a unit suffix of /sec]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/metric-chart-unit-byte-suffix.png) + +## Decimals + +Use **Decimals** to control numeric precision. For example, enter `2` to display two decimal places. Leave this setting empty to let the visualization choose the precision automatically. + +The following bar chart has **Units** set to `bits(b)` and **Decimals** set to `1`. For Cartesian charts, unit formatting also applies to axis labels. + +![Bar chart with the unit set to bits and decimals set to 1]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-chart-unit-bit-decimal-1.png) + +## Minimum and maximum + +Use **Min** and **Max** to define the displayed value range. + +For Cartesian charts, such as area, bar, histogram, line, and scatter charts, **Min** and **Max** set the value-axis range. + +The following bar chart has **Min** set to `100` and **Max** set to `300`. The bar baseline starts at `100`, so values below this range are clipped, and the value axis extends to `300`. + +![Bar chart with the minimum set to 100 and the maximum set to 300]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-chart-min-100-max-300.png) + +For gauge and bar gauge charts, **Min** and **Max** define the scale boundaries. Thresholds and filled ranges are calculated within this range. When left empty, the visualization calculates the range automatically. + +The following image shows a threshold configuration with a base color and steps at `1000`, `1100`, `1700`, `1800`, `1900`, and `2100`. + +![Threshold configuration with a base color and steps at 1000, 1100, 1700, 1800, 1900, and 2100]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/standard-options-threshold-config.png){: width="40%" } + +The following gauge chart uses that threshold configuration with a value of `2000`, **Min** set to `1200`, and **Max** set to `2200`. The gauge scale uses this range to position the threshold segments. + +![Gauge chart displaying a value of 2000 with the minimum set to 1200 and the maximum set to 2200]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/gauge-min-1200-max-2200.png) diff --git a/_dashboards/visualize/visualization-editor/configuring-visualizations/thresholds.md b/_dashboards/visualize/visualization-editor/configuring-visualizations/thresholds.md new file mode 100644 index 00000000..5df69b7c --- /dev/null +++ b/_dashboards/visualize/visualization-editor/configuring-visualizations/thresholds.md @@ -0,0 +1,258 @@ +--- +layout: default +title: Thresholds +parent: Configuring visualizations +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 10 +--- + +# Thresholds in the visualization editor + +A threshold is a boundary value that, when reached or exceeded by a data point, triggers a visual change in color. Use thresholds to define meaningful ranges so that you can immediately understand whether values are within normal, warning, or critical zones. + +Each threshold defines a value range. The base threshold applies to all values lower than the first threshold, and each additional threshold starts at its configured value and applies until the next threshold begins. For example, if the base color is green, a threshold at `50` is yellow, and a threshold at `80` is red, then values lower than 50 are green, values from 50 to less than 80 are yellow, and values of 80 or greater are red. + +## Supported chart types + +Thresholds are available in the following chart types: + +- [Area chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/area-chart/) +- [Bar chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/bar-chart/) +- [Bar gauge chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/bar-gauge-chart/) +- [Gauge chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/gauge-chart/) +- [Heatmap]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/heatmap-chart/) +- [Histogram]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/histogram-chart/) +- [Line chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/line-chart/) +- [Metric chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/metric-chart/) +- [Scatter plot]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/scatter-chart/) +- [State timeline]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/state-timeline-chart/) +- [Table]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/table-chart/) + +## Configuring thresholds + +To add a threshold, open the **Thresholds** section in the configuration panel and select **+ Add threshold**. For each threshold, configure the following settings. + +| Setting | Description | +| :--- | :--- | +| **Color** | Select a color to apply to values that fall within this threshold's range. Select a preset color or a custom color. | +| **Value** | Enter the numeric boundary at which this threshold begins. Values equal to or greater than this number (and lower than the next threshold) are displayed in this color. | + +OpenSearch Dashboards automatically sorts thresholds by value. The base threshold is always present and represents the starting color for all values lower than the other thresholds. You can change the base color, but you cannot delete the base threshold or set a value for it. To delete any other threshold, select the trash icon next to it. + +## Threshold effects by chart type + +Thresholds are applied differently depending on the chart type. Some visualizations use thresholds to color chart marks, some use thresholds as reference lines, and some require an additional chart-specific setting, such as **Use threshold colors** or **Cell style**. The following table describes how thresholds are applied in each chart type. + +| Chart type | Threshold effect | Additional setting | +| :--- | :--- | :--- | +| Gauge | Colors the gauge arc by threshold range. When **Use threshold colors** is turned on, the displayed value also uses the matching threshold color. | Turn on **Use threshold colors**. | +| Bar gauge | Colors the bar gauge by threshold range. The visual result also depends on the selected display style, such as gradient, stack, or basic. | None. | +| Metric | Colors the metric value or background according to the metric value and the selected color mode. | Set **Color mode** and then turn on **Use threshold colors**. | +| Line and area | Displays threshold values as horizontal reference lines. The line or area mark itself does not change color. | Set **Threshold lines mode** to **Solid lines**, **Dashed lines**, or **Dotted lines**. | +| Bar and histogram | Colors bars by value range when threshold colors are turned on. You can also display threshold reference lines. | Turn on **Use threshold colors** to color bars. Set **Threshold lines mode** to display reference lines. | +| Heatmap | Colors cells by value range, overriding the selected color schema. | Turn on **Use threshold colors**. | +| Scatter | Colors points by value range when threshold colors are turned on. You can also display threshold reference lines. | Turn on **Use threshold colors** to color points. Set **Threshold lines mode** to display reference lines. | +| State timeline | Colors state regions by value range, overriding the value mapping colors. | Turn on **Use threshold color**. | +| Table | Colors numeric table cells by value range. | In **Cell style**, select a numeric field and then select **Colored Text** or **Colored Background**. | + +State timeline charts also include settings for disconnecting values and connecting null values by a time threshold. Those settings control gaps in the timeline and do not affect the color thresholds described on this page. +{: .note} + +## Threshold examples + +The following examples show how to apply thresholds to each supported chart type using the OpenSearch Dashboards sample data. + +### Gauge chart + +In gauge charts, thresholds color the arc directly. The **Min** and **Max** controls under **Standard options** define the scale range, and thresholds divide that scale into colored segments. To apply thresholds to a gauge chart, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m) + ``` + {% include copy.html %} + +1. Select **Gauge** as the visualization type. +1. In the **Gauge** section, turn on **Use threshold colors**. +1. Open the **Thresholds** section and select **+ Add threshold**. +1. Set the base color to green and add thresholds at `6000`, `8000`, and `10000`. + +The arc uses the threshold color for each range, and the displayed value uses the matching threshold color, as shown in the following image. + +![Gauge chart with a threshold-colored arc and a value displayed in the matching threshold color]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/gauge-chart-threshold-result.png){: width="100%" } + +### Bar gauge chart + +In bar gauge charts, thresholds define the colored ranges of each bar. The result depends on the selected display style: + +- **Gradient** shows a smooth transition across threshold colors. +- **Stack** divides the bar into distinct threshold segments. +- **Basic** colors the bar using the threshold range that contains the value. + +To apply thresholds to a bar gauge chart, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m), extension + ``` + {% include copy.html %} + +1. Select **Bar Gauge** as the visualization type. +1. In the **Fields** section, set **X-Axis** to `extension` and **Y-Axis** to `AVG(bytes)`. +1. In the **Thresholds** section, set thresholds at `3000`, `5000`, and `8000`. +1. In the **Bar Gauge** section, select a **Display style**. + +Each bar is colored by the threshold range that contains its value, as shown in the following image. + +![Bar gauge chart with each bar colored by its threshold range]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-gauge/bar-gauge-threshold-result.png){: width="100%" } + +### Metric chart + +In metric charts, thresholds color the displayed value or its background according to the selected **Color mode**. To apply thresholds to a metric chart, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m), extension + ``` + {% include copy.html %} + +1. Select **Metric** as the visualization type. +1. In the **Metric** section, set **Color mode** to **Background gradient** and turn on **Use threshold colors**. +1. In the **Thresholds** section, set thresholds at `4000`, `6000`, and `8000`. + +The background of each metric uses the color of the threshold range that contains the metric value, as shown in the following image. + +![Metric chart with threshold colors applied to the background of each metric]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/metric-chart-threshold-result.png){: width="100%" } + +### Line and area charts + +In line and area charts, thresholds are displayed as horizontal reference lines across the chart. The line or area mark itself does not change color. To add threshold lines to a line or area chart, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m) + ``` + {% include copy.html %} + +1. Select **Line** as the visualization type. +1. Open the **Thresholds** section and select **+ Add threshold**. +1. Set thresholds at `5000` and `8000`. +1. Set **Threshold lines mode** to **Dashed lines**. + +A dashed horizontal line appears at each threshold value, as shown in the following image. + +![Line chart with dashed horizontal reference lines at each threshold value]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/line-area-threshold-lines.png){: width="100%" } + +Use the **Threshold lines mode** setting to control the line appearance: + +- **Off**: Displays no threshold lines. +- **Solid lines**: Draws solid horizontal lines at each threshold value. +- **Dashed lines**: Draws dashed horizontal lines at each threshold value. +- **Dotted lines**: Draws dotted horizontal lines at each threshold value. + +### Bar and histogram charts + +In bar and histogram charts, thresholds can color bars based on each bar's value. These chart types can also display threshold reference lines. To apply threshold colors to a bar chart, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | stats avg(bytes) by extension + ``` + {% include copy.html %} + +1. Select **Bar** as the visualization type. +1. In the **Fields** section, set **X-Axis** to `extension` and **Y-Axis** to `AVG(bytes)`. +1. In the **Bar** section, turn on **Use threshold colors**. +1. In the **Thresholds** section, set thresholds at `2000`, `4000`, and `6000`. +1. Set **Threshold lines mode** to **Off**. + +Each bar is colored by the threshold range that contains its value, as shown in the following image. + +![Bar chart with each bar colored by its threshold range]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/bar-histogram-threshold-result.png){: width="100%" } + +### Heatmap + +In heatmaps, thresholds color cells by value range, overriding the selected color schema. To apply thresholds to a heatmap, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | stats avg(bytes) by extension, `machine.os` + ``` + {% include copy.html %} + +1. Select **Heatmap** as the visualization type. +1. In the **Fields** section, set **X-Axis** to `extension`, **Y-Axis** to `machine.os`, and **Value** to `AVG(bytes)`. +1. In the **Heatmap** section, turn on **Use threshold colors**. +1. In the **Thresholds** section, set thresholds at `4000`, `6000`, and `8000`. + +Each cell is colored by the threshold range that contains its value, as shown in the following image. + +![Heatmap with each cell colored by its threshold range]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/heatmap/heatmap-threshold-colors.png){: width="100%" } + +### Scatter plot + +In scatter plots, thresholds can color points based on each point's value. Scatter plots can also display threshold reference lines. To apply thresholds to a scatter plot, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_flights` dataset and select **Update**. +1. Select **Scatter** as the visualization type. +1. In the **Fields** section, set **X-Axis** to `DistanceMiles` and **Y-Axis** to `AvgTicketPrice`. +1. Open the **Thresholds** section and select **+ Add threshold**. +1. Set thresholds at `400`, `600`, and `800`. + +Each point is colored by the threshold range that contains its ticket price, as shown in the following image. + +![Scatter plot with each point colored by the threshold range of its ticket price]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/scatter-threshold-result.png){: width="100%" } + +### State timeline + +In state timelines, thresholds color state regions by numeric value range. Use thresholds when the color represents a range, such as successful, warning, and error response codes, rather than an individual value. To apply thresholds to a state timeline, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_logs` dataset. +1. Enter the following query and select **Update**: + + ```sql + | FIELDS @timestamp, response + ``` + {% include copy.html %} + +1. Select **State Timeline** as the visualization type. +1. In the **Fields** section, set **X-Axis** to `@timestamp` and **Color** to `response`. Because the `response` field is numeric, OpenSearch Dashboards can divide it into threshold ranges. +1. In the **Thresholds** section, keep the base color green and set thresholds at `400` and `500`. +1. In the **State Timeline** section, turn on **Use threshold color**. To display only the threshold-colored regions, keep **Show display text** turned off. + +The timeline regions are colored by response code range: values from `0` to less than `400`, values from `400` to less than `500`, and values of `500` or greater, as shown in the following image. + +![State timeline with regions colored by response code range]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/state-timeline/state-timeline-threshold-colors.png){: width="100%" } + +### Table + +In tables, thresholds color numeric cells. To apply thresholds to a table, follow these steps: + +1. Select the `opensearch_dashboards_sample_data_flights` dataset. +1. Enter the following query and select **Update**: + + ```sql + | FIELDS AvgTicketPrice, Carrier, Dest, Origin + ``` + {% include copy.html %} + +1. Select **Table** as the visualization type. +1. In the **Table** section, set **Cell style** to `AvgTicketPrice` and select **Colored Background**. +1. In the **Threshold** section, set thresholds at `400`, `600`, and `1000`. + +Each `AvgTicketPrice` cell background is colored by the threshold range that contains its value, as shown in the following image. + +![Table with numeric cell backgrounds colored by threshold range]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/table-threshold-cells.png){: width="100%" } diff --git a/_dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations.md b/_dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations.md new file mode 100644 index 00000000..d08364cd --- /dev/null +++ b/_dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations.md @@ -0,0 +1,44 @@ +--- +layout: default +title: Value calculations +parent: Configuring visualizations +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 20 +--- + +# Value calculations + +When a visualization receives a numeric field, the data often contains a series of values rather than a single number. Use the **Calculation** setting to select a reducer function that aggregates the series into one representative value for display. + +## Supported chart types + +The value calculation setting is available in the following chart types. These are the only chart types that display a single aggregated value per series. + +- Bar gauge +- Gauge +- Metric + +## Missing values + +A data series may contain `NaN` or `null` entries. Calculation methods marked with an asterisk (\*) skip these invalid entries and operate only on valid numeric values. Methods without an asterisk use raw positional values regardless of whether they are valid numbers. + +## Available calculations + +The following table lists all available calculation methods. + +| Calculation | Description | Requires valid values | +| --- | --- | --- | +| **First** | The first value in the field. | No | +| **First \*** | The first valid (non-`null`, non-`NaN`) value in the field. | Yes | +| **Last** | The last value in the field. | No | +| **Last \*** | The last valid (non-`null`, non-`NaN`) value in the field. | Yes | +| **Min** | The minimum value among all valid values. | Yes | +| **Max** | The maximum value among all valid values. | Yes | +| **Mean** | The arithmetic average of all valid values. | Yes | +| **Median** | The middle value when all valid values are sorted. | Yes | +| **Total** | The sum of all valid values. | Yes | +| **Count** | The total number of values in the field (including `null`/`NaN`). | No | +| **Distinct count** | The number of unique values in the field (including `null`/`NaN`). | No | +| **Variance** | The statistical variance of all valid values. | Yes | + diff --git a/_dashboards/visualize/visualization-editor/dashboard-variables/index.md b/_dashboards/visualize/visualization-editor/dashboard-variables/index.md new file mode 100644 index 00000000..5b2817e5 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/dashboard-variables/index.md @@ -0,0 +1,168 @@ +--- +layout: default +title: Dashboard variables +has_children: true +has_toc: false +nav_order: 100 +parent: Creating visualizations using queries +grand_parent: Building data visualizations +redirect_from: + - /dashboards/visualize/visualization-editor/dashboard-variables/ +--- + +# Dashboard variables +**Introduced 3.7** +{: .label .label-purple } + +Dashboard variables are reusable values that you can reference in [visualization editor]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/) queries. Use variables for filters, metrics, dimensions, intervals, fields, aggregations, and any other query parameter, eliminating the need to manually edit PPL or PromQL queries when switching between data views. + +Dashboard variables are available in **Observability** workspaces only. To use dashboard variables, create an Observability workspace if you don't already have one. For more information, see [Workspace for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/workspace/). +{: .note} + +Use dashboard variables to: + +- Change query parameters without editing visualizations. +- Define values once and reference them across multiple visualizations. +- Automatically update visualizations when variable values change. +- Create cascading filters with dependent variables. +- Dynamically control grouping, aggregation, and time intervals. + +## Variable types + +OpenSearch Dashboards supports the following variable types: + +- **Query variables**: Options are dynamically fetched from a data source using a Piped Processing Language (PPL) or Prometheus Query Language (PromQL) query. Use query variables when values change over time or depend on underlying data, such as service names from logs or available regions from metrics. For a Prometheus data connection, you can build the query from PromQL query types (label names, label values, metrics, or series) instead of writing a raw query. For more information, see [Using a PromQL query variable]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables/#using-a-promql-query-variable). + +- **Custom variables**: Options are manually defined as a static list. Use custom variables for predefined categories like environment types (`dev`, `staging`, `prod`) or fixed status codes. + +- **Text variables**: A single value that you type in the variables bar. Use text variables for values that you can't list in advance, such as a search term or a threshold. + +## Variable syntax + +You can reference variables in queries using `$variableName` or `${variableName}` syntax: + +```sql +source=logs | where service='${service}' | stats count() by region +``` +{% include copy.html %} + +When you change a variable's value in a dashboard, all visualizations referencing that variable automatically refresh using the new value. + +## Enabling dashboard variables + +In addition to [enabling workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace/#enabling-workspaces), add the following setting to your `opensearch_dashboards.yml` file: + +```yaml +explore.enabled: true +``` +{% include copy.html %} + +Restart OpenSearch Dashboards for the changes to take effect. + +## Creating and using dashboard variables + +The following tutorial uses the OpenSearch Dashboards sample web logs dataset to create a variable and use it in a visualization. + +### Step 1: Create a workspace + +1. Navigate to the OpenSearch Dashboards home page. +1. Select **Create workspace**. +1. Enter a workspace name (for example, `My Observability`). +1. In the **Use case and features** section, keep **Observability** selected. +1. Select **Create workspace**. + +For more information, see [Create a workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/create-workspace/). + +### Step 2: Set up sample data + +In the workspace, navigate to **Manage workspace** > **Sample data** and select **Add data** for the web logs dataset. Adding the sample data also creates the `opensearch_dashboards_sample_data_logs` index pattern. + +### Step 3: Create a variable + +1. Select **Dashboards** in the left navigation. +1. Select **Create Dashboard**. +1. Save the dashboard by entering a title (for example, `Log Analysis`) and selecting **Save**. Saving switches the dashboard to view mode. +1. Turn on the **Edit** toggle. +1. At the top of the dashboard, select **Add variable**. +1. In the **Name** field, enter `extension`. +1. In the **Type** dropdown, keep **Query** selected. +1. In the **Query options** section, select **Open variable editor**. +1. Keep the query language set to **PPL**. Verify that the selected dataset is `opensearch_dashboards_sample_data_logs`. To choose a different dataset, select the dataset name. +1. Enter the following query: + + ```sql + source=opensearch_dashboards_sample_data_logs | stats count() by extension | fields extension + ``` + {% include copy.html %} + +1. To verify the results, select **Preview**. The preview displays `css`, `deb`, `gz`, `rpm`, `zip`, and an empty value for documents that have no file extension. +1. In the **Value field** dropdown, verify that `extension` is selected. The preview fills in this field automatically. +1. Select **Apply** to save the query and close the editor. +1. Select **Add variable** to save. + +The `extension` variable now appears at the top of the dashboard with a dropdown. + +For more information, see [Managing dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables/). + +### Step 4: Use the variable in a visualization + +1. In the dashboard, select **Create new**. +1. Select **Add visualization** to open the visualization editor. +1. In the query editor, enter the following PPL query that references the `$extension` variable: + + ```sql + | where extension='$extension' | stats count() by response + ``` + {% include copy.html %} + +1. In the `extension` dropdown at the top of the editor, select a value (for example, `css`). +1. Select **Update** to run the query. + +The visualization displays the response code distribution filtered by the selected extension, as shown in the following image. + +![Visualization editor showing a bar chart of response codes filtered by the selected extension value]({{site.url}}{{site.baseurl}}/images/dashboard-variables/variable-visualization-result.png) + +When you change the `extension` value in the dropdown, the visualization automatically updates to reflect the new selection. + +If no results appear, expand the time range (for example, **Last 90 days**) using the [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) in the upper-right corner. +{: .tip} + +For more information, see [Using dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/using-variables/). + +## Variable storage + +Variables are stored as part of the dashboard saved object in OpenSearch. Each dashboard maintains its own set of variables independently. + +The `variablesJSON` attribute in the dashboard saved object contains the variable configurations: + +```typescript +{ + type: "dashboard", + id: "dashboard-id", + attributes: { + title: "My Dashboard", + variablesJSON: "{\"variables\":[...]}" + } +} +``` +{% include copy.html %} + +Variable configurations include the following components: + +- Metadata (name, label, description, type). +- Options (query definition for query type or custom values for custom type). +- Settings (multi-select, "All" option, sort order, visibility). +- Current values (selected values for each variable). + +Current variable values are also synchronized to the dashboard URL so that you can: + +- Share dashboards with specific filter values preselected. +- Bookmark dashboards with desired variable states. +- Persist variable selections across page refreshes. + +## Related documentation + +- [Managing dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables/) +- [Using dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/using-variables/) +- [Creating visualizations using queries]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/) +- [Workspace for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/workspace/) \ No newline at end of file diff --git a/_dashboards/visualize/visualization-editor/dashboard-variables/managing-variables.md b/_dashboards/visualize/visualization-editor/dashboard-variables/managing-variables.md new file mode 100644 index 00000000..05815058 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/dashboard-variables/managing-variables.md @@ -0,0 +1,292 @@ +--- +layout: default +title: Managing dashboard variables +parent: Dashboard variables +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 10 +--- + +# Managing dashboard variables + +You can create, edit, delete, organize, and view dashboard variables from within a dashboard. + +## Prerequisites + +Before you start, ensure that you have met the following prerequisites: + +- Dashboard variables are [enabled]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/#enabling-dashboard-variables) in your `opensearch_dashboards.yml` file. +- You have an [Observability workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/create-workspace/) set up. + +For the complete setup, see [Creating and using dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/#creating-and-using-dashboard-variables). + +## Creating a query variable + +Use a query variable when the list of available values is retrieved from a data source. For example, you can create an `extension` variable from the sample web logs data and use it to filter multiple visualizations by file extension. + +The following example uses the OpenSearch Dashboards sample web logs data. If you use a different dataset, select the dataset and fields that match your data. +{: .note} + +To create a query variable, follow these steps: + +1. In your Observability workspace, select **Dashboards** in the left navigation. +1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If you create a new dashboard, save it first by entering a title and selecting **Save**. +1. If the dashboard is in view mode, turn on the **Edit** toggle. +1. At the top of the dashboard, select **Add variable**. +1. Configure the following general settings: + - **Name**: Enter `extension`. This is the identifier used to reference the variable in queries, for example, `$extension` or `${extension}`. + - **Label**: Enter `Extension`. This is the display name shown at the top of the dashboard. + - **Description**: Optionally, enter a description, such as `Filters visualizations by file extension`. + - **Type**: Keep **Query** selected. +1. In the **Query options** section, select **Open variable editor**. The query editor opens in a modal with a pinned **Preview of values** panel. +1. Keep the query language set to **PPL**. To build the query from Prometheus metadata instead, see [Using a PromQL query variable](#using-a-promql-query-variable). +1. Verify that the selected dataset is `opensearch_dashboards_sample_data_logs`. To choose a different dataset, select the dataset name. +1. Enter the following query: + + ```sql + source = opensearch_dashboards_sample_data_logs | stats count() by extension | fields extension + ``` + {% include copy.html %} + +1. Select **Preview**. The preview runs the query and displays the first 100 variable options in the **Preview of values** panel. You must successfully preview a query variable before you can apply it. +1. In the **Value field** dropdown, verify that `extension` is selected. The preview fills in this field automatically. The value field provides the value inserted into queries when you use `$extension` or `${extension}`. +1. In the **Label field** dropdown, keep **None**. Select a label field only when the query returns a separate field to display in the dropdown list in place of the stored value. +1. Optional: In **Regex**, enter a regular expression to filter the available options or to extract values and labels from the query results. For example, `^(css|gz|zip)$` displays only the `css`, `gz`, and `zip` options. The preview updates to show the filtered options. For more information, see [Filtering and extracting options with a regular expression](#filtering-and-extracting-options-with-a-regular-expression). +1. Select **Apply** to save the query and close the editor. +1. Back in the variable editor, in the **Query options** section, select a **Refresh** option to choose when OpenSearch Dashboards updates the variable options: + - **On dashboard load** (default): Refreshes options when the dashboard loads. + - **On time range change**: Refreshes options when the dashboard time range changes. Use this option when the available values depend on the selected time range. +1. Configure the settings in the **Selection options** section. For more information, see [Configuring variable option settings](#configuring-variable-option-settings). +1. Select **Add variable**. + +The variable appears at the top of the dashboard. The following image shows the query editor for an `extension` query variable configured using the sample web logs data. + +![Query editor configured for an extension PPL query variable using sample web logs data]({{site.url}}{{site.baseurl}}/images/dashboard-variables/query-variable-config.png){: width="700" } + +### Mapping query result fields + +A query variable can use one field as the stored value and another field as the display label: + +- **Value field**: The field used as the variable value. OpenSearch Dashboards inserts this value into queries when you reference the variable. +- **Label field**: An optional field used as the display label in the variable dropdown list. The label does not change the value inserted into queries. + +For example, if your query returns `service_id` and `service_name`, set **Value field** to `service_id` and **Label field** to `service_name`. The dropdown list displays the service name, and queries receive the service ID. + +If you do not select a value field, OpenSearch Dashboards uses the first field returned by the query. To avoid unexpected values, preview the query and explicitly select the field to use as the variable value. +{: .tip} + +### Using a PromQL query variable + +When a query variable uses a dataset backed by a Prometheus data connection, you can set the query language to **PromQL**. Instead of writing a raw query, you build the variable from one of the following PromQL query types: + +- **Label names**: Lists the label names in the data. You can optionally scope the result to a metric. +- **Label values**: Lists the values of a label that you choose. You can narrow the result with label matchers (`=`, `!=`, `=~`, and `!~`) and select a metric from the Metrics Explorer. +- **Metrics**: Lists the metric names. You can optionally filter the result with a regular expression on the metric name. +- **Series query**: Lists the full time series (label sets) that match a series selector. +- **Query result**: Evaluates a raw PromQL expression, the same as the free-text path used for PPL. + +To create a PromQL query variable, follow these steps: + +1. At the top of the dashboard, select **Add variable**, and set **Type** to **Query**. +1. In the **Query options** section, select **Open variable editor**. +1. Set the query language to **PromQL**. +1. Select the dataset name and choose a dataset backed by a Prometheus data connection. +1. In **Query type**, select a query type (for example, **Label values**) and complete its fields. For **Label values**, select the label and, optionally, a metric and one or more label matchers. +1. Select **Preview** to load the options, then select **Apply** to save the query and close the editor. +1. Configure refresh behavior, and then select **Add variable**. + +The following image shows a PromQL query variable configured with the **Label values** query type. + +![Variable editor panel configured for a PromQL label values query variable]({{site.url}}{{site.baseurl}}/images/dashboard-variables/promql-query-variable-config.png){: width="700" } + +A PromQL query variable requires a dataset backed by a Prometheus data connection in your Observability workspace. +{: .note} + +### Filtering and extracting options with a regular expression + +The **Regex** field in a query variable supports two behaviors. You can enter the expression as a bare pattern (for example, `^win`) or in `/pattern/flags` form (for example, `/^win/i`). + +The following examples use a query variable created from the sample web logs `machine.os` field: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by `machine.os` | fields `machine.os` +``` +{% include copy.html %} + +Previewing this query returns the options `ios`, `osx`, `win 7`, `win 8`, and `win xp`. You can then apply a regular expression to those results: + +- **Filtering**: When the regular expression has no `value` or `label` capture group, OpenSearch Dashboards keeps only the options that match and leaves them unchanged. For example, `^win` keeps only `win 7`, `win 8`, and `win xp`. +- **Extracting**: When the regular expression includes a named `(?<value>...)` capture group, OpenSearch Dashboards replaces each option's value with the captured text. An optional named `(?<label>...)` group sets the display label. Options that resolve to the same value are deduplicated automatically. For example, `^(?<value>ios|osx|win)` extracts the operating system family, so `win 7`, `win 8`, and `win xp` collapse into a single `win` option, leaving `ios`, `osx`, and `win`. + +To set a separate display label, add a `(?<label>...)` group. For example, if a query returns compound values such as `env=dev,label=Development`, the pattern `^env=(?<value>[^,]+),label=(?<label>.+)$` stores `dev` as the value and shows `Development` in the dropdown. + +![Regex field extracting the operating system family from the sample web logs machine.os field]({{site.url}}{{site.baseurl}}/images/dashboard-variables/regex-capture-groups.png){: width="700" } + +When you edit an existing variable, the query preview runs automatically so that you can see the extracted options right away. +{: .tip} + +## Creating a custom variable + +Use a custom variable when the list of available values is fixed and does not need to be fetched from a data source. For example, you can create an `environment` variable containing the `dev`, `staging`, and `prod` options. + +To create a custom variable, follow these steps: + +1. In your Observability workspace, select **Dashboards** in the left navigation. +1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If you create a new dashboard, save it first by entering a title and selecting **Save**. +1. If the dashboard is in view mode, turn on the **Edit** toggle. +1. At the top of the dashboard, select **Add variable**. +1. Configure the following general settings: + - **Name**: Enter `environment`. This is the identifier used to reference the variable in queries, for example, `$environment` or `${environment}`. + - **Label**: Enter `Environment`. + - **Description**: Optionally, enter a description, such as `Filters visualizations by deployment environment`. + - **Type**: Select **Custom**. +1. In **Custom options**, select **Add option**. +1. In the first option row, enter `dev` in **Value** and `Development` in **Label**. OpenSearch Dashboards inserts the value into queries when you reference the variable and uses the optional label as the display text in the dropdown list. +1. Select **Add option** again and enter `staging` in **Value** and `Staging` in **Label**. +1. Select **Add option** again and enter `prod` in **Value** and `Production` in **Label**. +1. Configure the shared option settings. For more information, see [Configuring variable option settings](#configuring-variable-option-settings). +1. Select **Add variable**. + +Custom option values must be unique and cannot be empty. OpenSearch Dashboards displays a maximum of 100 options in the dropdown list. +{: .note} + +The following image shows an `environment` custom variable configured with value and label pairs. + +![Variable editor panel configured for an environment custom variable with value and label option rows]({{site.url}}{{site.baseurl}}/images/dashboard-variables/custom-variable-config.png){: width="500" } + +## Creating a text variable + +Use a text variable when you want to type a single free-form value directly, without an option list. For example, you can create a `search_term` variable and change its value from the variables bar without opening the editor. + +To create a text variable, follow these steps: + +1. In your Observability workspace, select **Dashboards** in the left navigation. +1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If you create a new dashboard, save it first by entering a title and selecting **Save**. +1. If the dashboard is in view mode, turn on the **Edit** toggle. +1. At the top of the dashboard, select **Add variable**. +1. Configure the following general settings: + - **Name**: Enter `search_term`. This is the identifier used to reference the variable in queries, for example, `$search_term` or `${search_term}`. + - **Label**: Enter `Search term`. + - **Description**: Optionally, enter a description. + - **Type**: Select **Text**. +1. In **Value**, enter an initial value. +1. Select **Add variable**. + +The text variable appears at the top of the dashboard as an input box. Enter a value and press **Enter**, or select outside the box, to apply it. The value is applied when you finish editing, not on every keystroke, so visualizations that reference the variable do not re-run while you type. + +![Variable editor panel configured for a text variable with a free-form value]({{site.url}}{{site.baseurl}}/images/dashboard-variables/text-variable-config.png){: width="500" } + +A text variable has no option list, so the **Sort**, **Allow multiple selections**, **Include All option**, and **Allow custom values** settings do not apply and are hidden for this type. +{: .note} + +## Configuring variable option settings + +Query variables and custom variables share the following option settings: + +- **Sort**: Controls how options are sorted in the dropdown list. Select **Disabled**, **Alphabetical** ascending or descending, or **Numerical** ascending or descending. +- **Allow multiple selections**: Allows you to select more than one value from the variable dropdown list. +- **Include All option**: Adds an **All** option to the dropdown list. This setting is available only when **Allow multiple selections** is turned on. +- **Allow custom values**: Lets you commit a value that is not in the generated or static option list. When this setting is turned on, typing in the variable dropdown's search box offers the typed value as the first row, labeled **Hit enter to add**. Press **Enter** or select the row to add it. In a multiple-selection variable, the custom value is appended to the current selection; in a single-selection variable, it replaces the current value. A custom value is stored as the variable's selected value only; it is not added to the variable definition. + +## Managing existing variables + +The **Manage variables** panel lists all existing variables, including their type, name, and configuration options. To access this panel, follow these steps: + +1. Navigate to your workspace. +1. From **Dashboards**, select the dashboard to update. +1. On the top, toggle the **Edit** selector to enter edit mode. +1. In the upper-left corner, select the **Manage variables** icon, as shown in the following image. + +![Manage variables panel displaying variable names, types, and action icons]({{site.url}}{{site.baseurl}}/images/dashboard-variables/manage_panel.png) + +The **Manage variables** icon only appears when variables have been created in the dashboard. If no variables exist, create one first before accessing the management interface. +{: .note} + +## Editing a variable + +To edit an existing variable, follow these steps: + +1. Open the **Manage variables** panel. +1. Select the **Edit** icon for the variable you want to modify. +1. Make your changes. +1. Select **Update variable** to save. + +Changing the variable name causes any queries that reference the old name to fail. +{: .note} + +## Deleting a variable + +To delete a variable, follow these steps: + +1. Open the **Manage variables** panel. +1. Select the **Delete** icon for the variable you want to remove. +1. Confirm the deletion in the dialog. + +Variables that are referenced by other variables or visualization editors display an indicator in the management panel. Deleting a referenced variable causes any queries that use it to fail. +{: .note} + +## Organizing variables + +Variables are displayed at the top of the dashboard in the order they appear in the management panel. + +To reorder variables, follow these steps: + +1. Open the **Manage variables** panel. +1. Drag the reorder handle on the left side of a variable. +1. Drop it in the desired position. +1. Save the dashboard to apply the new order. + +## Hiding variables + +You can hide variables from the top of the dashboard while keeping them available for use in queries. + +To hide or show a variable, follow these steps: + +1. Open the **Manage variables** panel. +1. Select the **Hide/Show** icon for the variable. +1. Save the dashboard to apply the change. + +Hidden variables are marked with a **Hidden** badge in the management panel and do not appear in the dashboard. +{: .note} + +## Variable status indicators + +Each variable displays a status indicator at the top of the dashboard: + +- **Loading**: A spinner appears while the system fetches options. +- **Error**: An error icon appears with a tooltip showing the error message. The dropdown is disabled. +- **No options**: If a variable query returns no results, "No options" is displayed in the dropdown. + +## URL synchronization + +Variable values are automatically synchronized to the dashboard URL using the `variableValues` query parameter: + +```js +?variableValues=(service:(api),region:(us-east,us-west)) +``` + +URL synchronization enables the following functionality: + +- Send a link to a dashboard with specific variable values preselected. +- Save a dashboard view with your preferred variable settings. +- Preserve variable selections across page refreshes. + +## Variable dependencies + +Query type variables can reference other variables in their queries. The following example shows a query variable that references another variable: + +```sql +source=logs | where region=$region | dedup service | fields service +``` +{% include copy.html %} + +In this example, the `service` variable depends on the `region` variable. When the `region` variable changes, the `service` variable automatically refreshes its options. + +Keep the following considerations in mind: + +- Avoid circular dependencies where Variable A references Variable B, and Variable B references Variable A. +- Variables are evaluated in the order they appear in the management panel. Place dependent variables after the variables they reference. + +## Next steps + +- [Using dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/using-variables/) diff --git a/_dashboards/visualize/visualization-editor/dashboard-variables/using-variables.md b/_dashboards/visualize/visualization-editor/dashboard-variables/using-variables.md new file mode 100644 index 00000000..4c583432 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/dashboard-variables/using-variables.md @@ -0,0 +1,342 @@ +--- +layout: default +title: Using dashboard variables +parent: Dashboard variables +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 20 +--- + +# Using dashboard variables + +You can reference dashboard variables in queries in the visualization editor to create dynamic, interactive dashboards. + +## Variable syntax + +Dashboard variables can be referenced in queries using the following syntax options. + +### Basic syntax + +Use `$variableName` for most cases: + +```sql +source=logs | where service='$service' | stats count() by region +``` +{% include copy.html %} + +### Braced syntax + +Use `${variableName}` when the variable name is followed by other characters without white space: + +```sql +source = logs | where ${env}_level = "error" +``` +{% include copy.html %} + +Braced syntax ensures that the variable name is properly delimited. Without braces, `$env_level` is interpreted as a variable named `env_level` instead of `env`. + +## Using variables in queries + +Dashboard variables support Piped Processing Language (PPL) and Prometheus Query Language (PromQL). The following examples use PPL. + +#### Single-value variable for filtering + +The following query filters logs by a single-value variable: + +```sql +source=logs | where service='$service' | stats count() by status_code +``` +{% include copy.html %} + +When `service` is set to `api`, the query resolves to: + +```sql +source=logs | where service='api' | stats count() by status_code +``` + +#### Multi-value variable for filtering + +The following query filters logs by a multi-value variable: + +```sql +source=logs | where region IN $region | stats count() by service +``` +{% include copy.html %} + +When `region` has multiple values selected (`us-east`, `us-west`), the query resolves to: + +```sql +source=logs | where region IN ('us-east', 'us-west') | stats count() by service +``` + +#### Multi-value with numbers + +When a query variable's options are detected as numeric or Boolean values, multi-values are formatted without quotes: + +```sql +source=logs | where status_code IN $status | stats count() +``` +{% include copy.html %} + +When `status` has multiple numeric values selected, the query resolves to: + +```sql +source=logs | where status_code IN (200, 404, 500) | stats count() +``` + +#### Variable for grouping dimension + +The following query uses a variable to control the grouping dimension: + +```sql +source=logs | stats count() by `$group_by` +``` +{% include copy.html %} + +When `group_by` is set to `region`, the query resolves to: + +```sql +source=logs | stats count() by region +``` + +#### Variable for time interval + +The following query uses a variable to control the time interval: + +```sql +source=logs | stats count() by span(timestamp, $interval) +``` +{% include copy.html %} + +When `interval` is set to `5m`, the query resolves to: + +```sql +source=logs | stats count() by span(timestamp, 5m) +``` + +#### Variable for metric calculation + +The following query uses a variable to control which metric is calculated: + +```sql +source=metrics | stats avg($metric) by service +``` +{% include copy.html %} + +When `metric` is set to `response_time`, the query resolves to: + +```sql +source=metrics | stats avg(response_time) by service +``` + +### Multi-value variable formatting + +When a variable allows multiple selections, values are automatically formatted based on the query language. + +<table> + <thead> + <tr> + <th>Query language</th> + <th>String values</th> + <th>Numeric or Boolean values</th> + </tr> + </thead> + <tbody> + <tr> + <td>PPL</td> + <td><code>('value1', 'value2')</code></td> + <td><code>(123, 456)</code></td> + </tr> + <tr> + <td>PromQL</td> + <td><code>(value1|value2)</code></td> + <td><code>(value1|value2)</code></td> + </tr> + <tr> + <td>Other</td> + <td><code>value1, value2</code></td> + <td><code>value1, value2</code></td> + </tr> + </tbody> +</table> + +### Autocomplete suggestions + +Query editors in OpenSearch Dashboards provide autocomplete suggestions for dashboard variables. + +1. In the query editor, type `$`. A dropdown appears showing all available dashboard variables. +1. Select a variable from the list or continue typing to filter, as shown in the following image. + + ![Query editor showing autocomplete dropdown with available dashboard variables]({{site.url}}{{site.baseurl}}/images/dashboard-variables/variable_autocomplete.png) +1. Press Enter or Tab to insert the variable. + +## Using variables in visualizations + +Dashboard variables integrate with the OpenSearch Dashboards visualization editor, which provides full support for dashboard variables when editing visualizations from a dashboard. + +### Filtering by a variable value + +Variables can serve as filtering conditions within your visualizations. Instead of applying filters to entire dashboards, embed variables directly into PPL queries to create targeted filtering for specific panels. + +To filter a visualization by a variable value, follow these steps: + +1. Create a `machine_os` variable: + 1. In your Observability workspace, select **Dashboards** in the left navigation. + 1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If creating a new dashboard, save it first by entering a title and selecting **Save**. + 1. If the dashboard is in view mode, turn on the **Edit** toggle. + 1. At the top of the dashboard, select **Add variable**. + 1. In the **Name** field, enter `machine_os`, and keep **Type** set to **Query**. In the **Query options** section, select **Open variable editor**. Keep the language set to **PPL**, verify that the selected dataset is `opensearch_dashboards_sample_data_logs`, and enter the following query: + + ```sql + | FIELDS `machine.os` + ``` + {% include copy.html %} + 1. Select **Preview** and make sure that you see values such as `win 8`, `ios`, and `win xp` in the **Preview of values**. Select **Apply** to save the query, and then select **Add variable** to save. + + +1. Filter by a variable value: + 1. Open a new visualization editor by selecting **Create new** in the dashboard and then selecting **Add visualization**. + 1. In the time filter, select **Last 30 days**. + 1. In the query box, enter the following query: + + ```sql + | WHERE `machine.os` = '${machine_os}' | STATS avg(memory) BY span(`@timestamp`, 1d) + ``` + {% include copy.html %} + + To filter the visualization by `machine_os` values, select the value in the `machine_os` dropdown list (for example, select `win 8`), as shown in the following image. + + ![Visualization editor showing average memory over time filtered by machine_os set to win 8]({{site.url}}{{site.baseurl}}/images/dashboard-variables/filter_case_variable.png) + +### Selecting a metric dynamically + +Use a variable to control which field is used in an aggregation. This lets you switch between metrics (for example, `memory` and `bytes`) without editing the query. + +To select a metric dynamically, follow these steps: + +1. Create a `log_metric` variable: + 1. In your Observability workspace, select **Dashboards** in the left navigation. + 1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If creating a new dashboard, save it first by entering a title and selecting **Save**. + 1. If the dashboard is in view mode, turn on the **Edit** toggle. + 1. At the top of the dashboard, select **Add variable**. + 1. In the **Name**, enter `log_metric`. In the **Type**, select **Custom**. In the **Custom options**, enter `memory` and press **Enter** to add. Then enter `bytes` and press **Enter** to add. + 1. Select **Add variable** to save. + +1. Use the variable in a visualization: + 1. Open a new visualization editor by selecting **Create new** in the dashboard and then selecting **Add visualization**. + 1. In the time filter, select **Last 30 days**. + 1. In the query box, enter the following query: + + ```sql + source=opensearch_dashboards_sample_data_logs + | stats avg($log_metric) as avg_${log_metric} by span(`timestamp`, 1h) as timestamp, response + ``` + {% include copy.html %} + + To switch between metrics, select a value in the `log_metric` dropdown list (for example, select `memory` or `bytes`). + + ![Visualization editor showing average memory over time with the log_metric variable set to memory]({{site.url}}{{site.baseurl}}/images/dashboard-variables/metrics_case_variable.png) + +### Changing time intervals dynamically + +Use a variable to let dashboard viewers switch between time aggregation intervals (for example, `1h`, `6h`, or `1d`) without editing the query. + +To change time intervals dynamically, follow these steps: + +1. Create an `interval` variable: + 1. In your Observability workspace, select **Dashboards** in the left navigation. + 1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If creating a new dashboard, save it first by entering a title and selecting **Save**. + 1. If the dashboard is in view mode, turn on the **Edit** toggle. + 1. At the top of the dashboard, select **Add variable**. + 1. In the **Name**, enter `interval`. In the **Type**, select **Custom**. In the **Custom options**, enter `1d` and press **Enter** to add. Repeat for `12h`, `6h`, and `1h`. + 1. Select **Add variable** to save. + +1. Use the variable in a visualization: + 1. Open a new visualization editor by selecting **Create new** in the dashboard and then selecting **Add visualization**. + 1. In the time filter, select **Last 30 days**. + 1. In the query box, enter the following query: + + ```sql + source=opensearch_dashboards_sample_data_logs | stats AVG(`bytes`) as avg_bytes, MAX(`bytes`) as max_bytes by span(`timestamp`, $interval) + ``` + {% include copy.html %} + + To switch between intervals, select a value in the `interval` dropdown list (for example, select `6h`) and select **Update**. The visualization reflects the selected time bucketing, as shown in the following image. + + ![Visualization editor showing avg_bytes and max_bytes over time with the interval variable set to 1d]({{site.url}}{{site.baseurl}}/images/dashboard-variables/interval_case_variable.png) + +### Changing aggregation functions dynamically + +Use a variable to let dashboard viewers switch between aggregation functions (for example, `avg`, `max`, or `min`) without editing the query. + +To change aggregation functions dynamically, follow these steps: + +1. Create a `function` variable: + 1. In your Observability workspace, select **Dashboards** in the left navigation. + 1. Open an existing dashboard or select **Create Dashboard** to create a new dashboard. If creating a new dashboard, save it first by entering a title and selecting **Save**. + 1. If the dashboard is in view mode, turn on the **Edit** toggle. + 1. At the top of the dashboard, select **Add variable**. + 1. In the **Name**, enter `function`. In the **Type**, select **Custom**. In the **Custom options**, enter `avg` and press **Enter** to add. Repeat for `max` and `min`. + 1. Select **Add variable** to save. + +1. Use the variable in a visualization: + 1. Open a new visualization editor by selecting **Create new** in the dashboard and then selecting **Add visualization**. + 1. In the time filter, select **Last 30 days**. + 1. In the query box, enter the following query: + + ```sql + | STATS ${function}(memory) BY span(`@timestamp`, 1d) + ``` + {% include copy.html %} + + To switch between functions, select a value in the `function` dropdown list (for example, select `max`) and select **Update**. The visualization reflects the selected aggregation function, as shown in the following image. + + ![Visualization editor showing average memory over time with the function variable set to avg]({{site.url}}{{site.baseurl}}/images/dashboard-variables/function_case_variable.png) + +## Cascading and cross-panel variables + +The following sections describe advanced variable use cases. + +### Cascading variables + +Create dependent variables for which one variable filters the options of another. For example, select a region first, then select from services available in that region. + +Create a `region` variable: + +```sql +source=logs | dedup region | fields region +``` +{% include copy.html %} + +Create a `service` variable that references `region`: + +```sql +source=logs | where region='$region' | dedup service | fields service +``` +{% include copy.html %} + +When the `region` value changes, the `service` variable automatically refreshes its options to show only services in the selected region. + +### Cross-panel filtering + +Use a single variable to filter multiple visualizations simultaneously. For example, create a `service` variable and reference it in multiple visualization editors. + +Visualization editor 1 (request count by service): + +```sql +source=logs | where service='$service' | stats count() by status_code +``` +{% include copy.html %} + +Visualization editor 2 (response time by service): + +```sql +source=metrics | where service='$service' | stats avg(response_time) +``` +{% include copy.html %} + +Changing the `service` variable value updates both visualization editors at once. + +## Next steps + +- [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/) diff --git a/_dashboards/visualize/visualization-editor/data-transformation/index.md b/_dashboards/visualize/visualization-editor/data-transformation/index.md new file mode 100644 index 00000000..635edc1f --- /dev/null +++ b/_dashboards/visualize/visualization-editor/data-transformation/index.md @@ -0,0 +1,299 @@ +--- +layout: default +title: Data transformations +parent: Creating visualizations using queries +grand_parent: Building data visualizations +nav_order: 95 +redirect_from: + - /dashboards/visualize/visualization-editor/data-transformation/ +--- + +# Data transformations + +Data transformations modify query results before a visualization is rendered. Use transformations to reshape, filter, sort, calculate, or summarize data without changing the original query. + +Transformations are applied as a pipeline. Each transformation receives the output of the previous transformation as its input, so the order of transformations can change the final result. + +Use transformations when you need to: + +- Filter rows after a query returns results. +- Keep or remove specific fields from the result table. +- Sort rows before visualizing them. +- Limit the number of rows shown in a visualization. +- Convert field values to another type, such as number, string, Boolean, or date. +- Extract fields from an object or JSON string into top-level columns. +- Add a calculated field from existing numeric fields. +- Group rows by a field and aggregate the remaining fields. + +Transformations are useful when the query returns the right data but not in the exact shape required by the visualization. If the data can be filtered or aggregated more efficiently in the query, update the query first. + +## Supported transformations + +The following table lists the available transformations. + +| Transformation | Description | +| --- | --- | +| **Limit** | Keeps only the specified number of rows. | +| **Sort by** | Sorts rows by one field in ascending or descending order. | +| **Filter** | Keeps rows that match a field, operator, and value condition. | +| **Filter fields** | Includes or excludes selected fields. | +| **Convert field type** | Converts field values to string, number, Boolean, or date. | +| **Group by** | Groups rows by one field and aggregates the remaining fields. | +| **Extract fields** | Extracts nested object or JSON string fields into top-level fields. | +| **Add field** | Creates a calculated numeric field from existing numeric fields or constants. | + +## Adding and managing transformations + +To add a transformation, go to the **Transform** tab, select **Add**, and then choose a transformation in the **Add transformation** flyout. A transformation card is added to the pipeline. + +The following image shows the **Add transformation** flyout listing the available transformations. + +![Add transformation flyout listing the available transformations next to the Transform tab]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/data-transformation/open-transformation-table.png){: width="100%" } + +You can manage transformations in the pipeline as follows: + +- Update the controls in a transformation card to edit it. +- Select the eye icon to hide or show a transformation. Hidden transformations remain in the pipeline but are skipped. +- Select the delete icon to remove a transformation. +- Drag transformation cards to change the pipeline order. + +## Transformation order + +Transformation order matters. The pipeline runs from top to bottom, and each step uses the result produced by the previous step. Fields created or removed by one transformation affect the fields available to later transformations. + +For example, the following pipeline filters successful requests, sorts them by byte count, and keeps only the largest result: + +1. **Filter**: `response` equals `200`. +1. **Sort by**: `bytes`, descending. +1. **Limit**: `1`. + +The following table shows the input data. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +The following table shows the result. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | + +## Example data + +The following examples use a small result table based on the `opensearch_dashboards_sample_data_logs` sample index. + +| `@timestamp` | `extension` | `response` | `bytes` | `machine.os` | `geo` | +| --- | --- | --- | --- | --- | --- | +| `2026-09-20T10:00:00Z` | `css` | `200` | `14074` | `win 8` | `{"src":"US","dest":"CN"}` | +| `2026-09-20T10:01:00Z` | `png` | `404` | `7911` | `osx` | `{"src":"IN","dest":"US"}` | +| `2026-09-20T10:02:00Z` | `js` | `200` | `1024` | `win xp` | `{"src":"US","dest":"GB"}` | +| `2026-09-20T10:03:00Z` | `css` | `503` | `2048` | `ios` | `{"src":"CN","dest":"US"}` | + +## Transformation types + +The following sections describe each transformation and show the result of applying it to the example data. + +### Limit + +Use **Limit** to keep only the specified number of rows from the beginning of the result. + +The transformation uses the following configuration: + +- **Number of rows**: `2` + +The following table shows the input data. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +The following table shows the result. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | + +### Sort by + +Use **Sort by** to sort rows by a selected field. + +The transformation uses the following configuration: + +- **Field**: `bytes` +- **Order**: **Descending** + +The following table shows the input data. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +The following table shows the result. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `css` | `503` | `2048` | +| `js` | `200` | `1024` | + +### Filter + +Use **Filter** to keep rows that match a condition. Available operators depend on the selected field type. + +The transformation uses the following configuration: + +- **Field**: `response` +- **Operator**: **Equals** +- **Value**: `200` + +The following table shows the input data. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +The following table shows the result. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `js` | `200` | `1024` | + +### Filter fields + +Use **Filter fields** to include or exclude selected fields. + +The transformation uses the following configuration: + +- **Mode**: **Include** +- **Fields**: `extension`, `response`, `bytes` + +The following table shows the input data. + +| `@timestamp` | `extension` | `response` | `bytes` | `machine.os` | +| --- | --- | --- | --- | --- | +| `2026-09-20T10:00:00Z` | `css` | `200` | `14074` | `win 8` | +| `2026-09-20T10:01:00Z` | `png` | `404` | `7911` | `osx` | + +The following table shows the result. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | + +### Convert field type + +Use **Convert field type** to cast selected field values to another type. Supported target types are string, number, Boolean, and date. + +The transformation uses the following configuration: + +- **Field**: `response` +- **Target type**: **Number** + +The following table shows the input data. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `"200"` | `14074` | +| `png` | `"404"` | `7911` | + +The following table shows the result. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | + +### Group by + +Use **Group by** to group rows by a field value and aggregate other fields for each group. + +The transformation uses the following configuration: + +- **Field**: `extension` +- **Aggregations**: `bytes` as **Total** and `response` as **Count** + +The following table shows the input data. + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +The following table shows the result. + +| `extension` | `total_bytes` | `count_response` | +| --- | --- | --- | +| `css` | `16122` | `2` | +| `png` | `7911` | `1` | +| `js` | `1024` | `1` | + +### Extract fields + +Use **Extract fields** to flatten a nested object or JSON string field into top-level fields. + +The transformation uses the following configuration: + +- **Field**: `geo` +- **Format**: **Object** +- **Column prefix**: `geo_` + +The following table shows the input data. + +| `extension` | `geo` | +| --- | --- | +| `css` | `{"src":"US","dest":"CN"}` | +| `png` | `{"src":"IN","dest":"US"}` | + +The following table shows the result. + +| `extension` | `geo` | `geo_src` | `geo_dest` | +| --- | --- | --- | --- | +| `css` | `{"src":"US","dest":"CN"}` | `US` | `CN` | +| `png` | `{"src":"IN","dest":"US"}` | `IN` | `US` | + +### Add field + +Use **Add field** to create a calculated numeric field. **Add field** supports binary calculations, unary calculations, and cross-field calculations. + +The transformation uses the following configuration: + +- **Mode**: **Binary** +- **Field 1**: `bytes` +- **Operator**: `+` +- **Field 2**: custom value `100` +- **Alias**: `bytes_with_overhead` + +The following table shows the input data. + +| `extension` | `bytes` | +| --- | --- | +| `css` | `14074` | +| `png` | `7911` | +| `js` | `1024` | + +The following table shows the result. + +| `extension` | `bytes` | `bytes_with_overhead` | +| --- | --- | --- | +| `css` | `14074` | `14174` | +| `png` | `7911` | `8011` | +| `js` | `1024` | `1124` | diff --git a/_dashboards/visualize/visualization-editor/gauge-chart.md b/_dashboards/visualize/visualization-editor/gauge-chart.md new file mode 100644 index 00000000..6331f432 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/gauge-chart.md @@ -0,0 +1,96 @@ +--- +layout: default +title: Gauge chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 25 +--- + +# Gauge charts in the visualization editor + +A gauge chart displays a single numeric value on a semicircular arc. Use a gauge chart to show how a metric compares against defined thresholds or a target range. + +## Creating a gauge chart + +The following examples build on each other, starting with a basic gauge and adding complexity. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic gauge chart + +Start with a query that returns a single numeric aggregation: + +```sql +source = opensearch_dashboards_sample_data_flights | FIELDS AvgTicketPrice +``` +{% include copy.html %} + +After running this query, select **Gauge** as the chart type. The visualization automatically applies the **Last** calculation to reduce the series to a single value for display. The editor maps the field as follows: + +- The **Value** field displays the `AvgTicketPrice` field (using the **Last** calculation by default). + +The result is a gauge displaying the last ticket price value with the default green arc, as shown in the following image. + +![Initial gauge chart showing the last average ticket price]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/gauge/gauge-initial-look.png){: width="100%" } + +### Adding thresholds + +Define threshold breakpoints to segment the gauge arc into colored ranges that indicate value health. + +Using the same query as the previous example, open the **Thresholds** section in the settings panel and add thresholds. For example: + +- Base color: green (values below 500) +- Threshold at 500: yellow (moderate price range) +- Threshold at 800: red (high price range) + +The arc now shows colored bands---green up to 500, yellow from 500 to 800, and red above 800. Enable **Use threshold colors** to apply the matching threshold color to the displayed value text and the arc, as shown in the following image. + +![Gauge chart with color-coded threshold bands]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/gauge/gauge-with-thresholds.png){: width="100%" } + +### Customizing the gauge scale + +To monitor ticket prices against a fixed scale that represents the full expected range, open the **Standard options** section and set: + +- **Min**: `500` +- **Max**: `1200` + +The gauge now always spans from 500 to 1200, making it easier to compare across split panels, as shown in the following image. + +![Gauge chart with custom min/max scale]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/gauge/gauge-custom-scale.png){: width="100%" } + +## Configuring a gauge chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the data fields. + +| Field | Description | +| --- | --- | +| **Value** | Select a numeric field whose values are reduced to a single number using the configured calculation method. The result is displayed as the gauge's current value. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Gauge + +| Setting | Description | +| --- | --- | +| **Use threshold colors** | When enabled, the central numeric value adopts the color of the threshold range that the current value falls within. | +| **Show title** | Displays a label below the numeric value. Defaults to the field name, but you can override it with custom text. | +| **Title** | Custom title text displayed below the value when **Show title** is enabled. If left blank, the field name is used. | + +### Value options + +| Setting | Description | +| --- | --- | +| **Calculation** | Determines how multiple data points are reduced to the single value shown on the gauge. Supported values: **Last \***, **Last**, **First \***, **First**, **Min**, **Max**, **Mean**, **Median**, **Variance**, **Count**, **Distinct count**, **Total**. For more information, see [Value calculations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations/). | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). diff --git a/_dashboards/visualize/visualization-editor/heatmap-chart.md b/_dashboards/visualize/visualization-editor/heatmap-chart.md new file mode 100644 index 00000000..40953cfc --- /dev/null +++ b/_dashboards/visualize/visualization-editor/heatmap-chart.md @@ -0,0 +1,118 @@ +--- +layout: default +title: Heatmap +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 30 +--- + +# Heatmaps in the visualization editor + +A heatmap uses color to represent the magnitude of values in a dataset. Each cell in the map corresponds to a combination of two dimensions, with the cell's color intensity reflecting the value associated with that combination. + +## Creating a heatmap + +The following examples build on each other, starting with a basic heatmap and adding complexity. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic heatmap + +Start with a query that aggregates a numeric metric by two categorical fields: + +```sql +source = opensearch_dashboards_sample_data_flights | where FlightDelay = true | stats avg(FlightDelayMin) as avg_delay by OriginWeather, DestWeather +``` +{% include copy.html %} + +After running this query, select **Heatmap** as the chart type. The fields are mapped as follows: + +- The **X-Axis** displays the `OriginWeather` field. +- The **Y-Axis** displays the `DestWeather` field. +- The **Value** displays the `avg_delay` field. + +The result is a grid of colored cells where each cell represents the average flight delay minutes for a specific origin-destination weather combination. Darker cells indicate higher values, as shown in the following image. + +![Basic heatmap showing average flight delay minutes by weather conditions]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/heatmap/heatmap-initial.png){: width="100%" } + +### Customizing the color schema and scale + +To better distinguish between values, change the color settings: + +1. In the **Heatmap** section, change **Color schema** to a different palette (for example, **Yellow to Orange**) to improve contrast. +2. Enable **Scale to data bounds** to map the color range to the actual min and max of your data rather than calculated bounds. +3. Change **Max number of colors** to increase or decrease the granularity of color bins, as shown in the following image. + +![Heatmap with customized color schema and scale]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/heatmap/heatmap-custom-colors.png){: width="100%" } + +### Enabling labels + +To display the numeric value inside each cell, enable **Show labels**. If cells are narrow, enable **Rotate** to angle the labels for better readability, as shown in the following image. + +![Heatmap with value labels displayed in cells]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/heatmap/heatmap-with-labels.png){: width="100%" } + +## Configuring a heatmap + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a categorical field to display along the horizontal axis. Each unique value becomes a column in the heatmap grid. | +| **Y-Axis** | Select a categorical field to display along the vertical axis. Each unique value becomes a row in the heatmap grid. | +| **Value** | Select a numeric field whose magnitude determines the color intensity of each cell. Each cell represents the intersection of one X-Axis category and one Y-Axis category. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + + +### Heatmap + +Use the following settings to customize the appearance of the heatmap. + +| Setting | Description | +| --- | --- | +| **Use threshold colors** | When enabled, cell colors are determined by threshold ranges rather than the selected color schema. | +| **Color schema** | Controls the color theme used to represent values across cells. Supported values: **Greens**, **Blues**, **Reds**, **Greys**, **Green to Blue**, **Yellow to Orange**. | +| **Reverse schema** | When enabled, the color mapping is inverted: higher values are represented with lighter colors, and lower values with darker colors. | +| **Color scale** | Defines how data values are mapped to colors. Supported values: **Linear**, **Log**, **Sqrt**. | +| **Scale to data bounds** | When enabled, calculates the minimum and maximum values from the dataset and maps the color scale accordingly. | +| **Percentage mode** | When enabled, values are converted to percentages and the color scale is normalized between 0 and 1. | +| **Max number of colors** | Controls the maximum number of discrete color bins used in the color scale. | +| **Show labels** | When enabled, displays the numeric value as a label inside each cell. | + +The following settings are available when **Show labels** is enabled. + +| Setting | Description | +| --- | --- | +| **Rotate** | When enabled, rotates the value labels by 45 degrees for better readability in narrow cells. | +| **Overwrite automatic color** | When enabled, sets a custom label color. | +| **Color** | Sets the custom label color when **Overwrite automatic color** is enabled. | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, and decimal precision, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### Legend + +The legend summarizes the visual color encodings used in the chart. + +| Setting | Description | +| --- | --- | +| **Show legend** | Shows or hides the legend. | +| **Position** | Controls where the legend appears relative to the chart. Supported values: **Left**, **Right**, **Top**, **Bottom**. | + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/histogram-chart.md b/_dashboards/visualize/visualization-editor/histogram-chart.md new file mode 100644 index 00000000..bfdcf17c --- /dev/null +++ b/_dashboards/visualize/visualization-editor/histogram-chart.md @@ -0,0 +1,84 @@ +--- +layout: default +title: Histogram +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 35 +--- + +# Histograms in the visualization editor + +A histogram displays the distribution of a numeric field by grouping values into bins (buckets) and showing the count of values in each bin as vertical bars. + +## Creating a histogram + +The following example demonstrates a basic histogram visualization. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic histogram + +Start with a query that counts values grouped by a numeric field: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by AvgTicketPrice +``` +{% include copy.html %} + +After running this query, select **Histogram** as the chart type. The editor maps the field as follows: + +- The **X-Axis** displays the `AvgTicketPrice` field. + +The result is a histogram showing the distribution of ticket prices, as shown in the following image. + +![Histogram showing distribution of average ticket prices]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/histogram-chart-basic-result.png){: width="100%" } + +## Configuring a histogram + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a numeric field to distribute into buckets along the horizontal axis. | +| **Y-Axis** | Select a numeric field for the vertical axis. If left blank, the chart displays the count of values in each bucket. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Bucket + +The following settings control how data is grouped into bins. + +| Setting | Description | +| --- | --- | +| **Bucket Size** | Sets the width of each bin. Enter a numeric value or leave as **auto** to let the editor calculate an appropriate size. | +| **Bucket count** | Sets the maximum number of bins to display. | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### Histogram + +Use the following settings to customize the appearance of the histogram. + +| Setting | Description | +| --- | --- | +| **Use threshold colors** | When enabled, colors bars based on threshold ranges. | +| **Show border** | When enabled, adds a border around each bar. | + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/index.md b/_dashboards/visualize/visualization-editor/index.md new file mode 100644 index 00000000..e80ddd42 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/index.md @@ -0,0 +1,163 @@ +--- +layout: default +title: Creating visualizations using queries +nav_order: 50 +parent: Building data visualizations +grand_parent: OpenSearch Dashboards +has_children: true +has_toc: false +redirect_from: + - /dashboards/visualize/visualization-editor/ +--- + +# Creating visualizations using queries + +The _visualization editor_ lets you create visualizations by writing [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/) or Prometheus Query Language (PromQL) queries. The editor automatically maps query result fields to chart axes and suggests a chart type based on the shape of your data. To open the visualization editor from a dashboard, select **Create new** > **Add visualization**. + +## Prerequisites + +Before using the visualization editor, an OpenSearch Dashboards administrator must complete the following setup steps. + +### Step 1: Enable required settings + +In addition to [enabling workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace/#enabling-workspaces), add the following setting to your `opensearch_dashboards.yml` file: + +```yaml +explore.enabled: true +``` +{% include copy.html %} + +After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +### Step 2: Create a workspace + +The visualization editor requires a workspace. If saved object permissions are enabled, only dashboard administrators can create workspaces, and other users must be added to an existing workspace by its owner. For more information, see [Configuring dashboard administrators]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators). + +To create a workspace, follow these steps: + +1. Navigate to the OpenSearch Dashboards home page. +1. Select **Create workspace**. +1. Enter a workspace name. +1. Select the **Analytics (all features)** use case. +1. Select **Create workspace**. + +For more information, see [Create a workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/create-workspace/). + +### Step 3: Configure a data source + +The visualization editor requires a dataset associated with your workspace: + +- For PPL, configure an index pattern: + 1. Inside your workspace, go to **Index patterns** (in **Management**). + 1. Select **Create index pattern**. + 1. Enter the index name (for example, `opensearch_dashboards_sample_data_logs`). + 1. Select **Next step**. + 1. Select a time field (for example, `@timestamp`). + 1. Select **Create index pattern**. + + For more information, see [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). + +- For PromQL (Prometheus data source), configure a Prometheus data source connection for your workspace. For more information, see [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/). + +### Step 4 (Optional): Install sample data + +The examples in this documentation use the OpenSearch Dashboards sample datasets. To install the sample datasets, follow these steps: + +1. In the left navigation, expand **Manage workspace** and select **Sample data**. +1. Select the **Add data** button in the **Sample log data** tile and any others that you want to add. The examples in this section use the sample log data. + +For more information, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Navigating the visualization editor UI + +The following image shows the main components of the visualization editor. + +![Visualization editor interface with callouts]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/visualization-editor-overview.png){: width="100%" } + +- The _time filter_ (A) selects the time range for query results. +- The _Update button_ (B) runs or refreshes the query. +- The _query editor_ (C) contains the query text or, for PromQL, the query builder. +- The _Saved queries_ dropdown (D) saves and loads reusable queries. +- The _configuration panel_ (E) contains the chart type selector, field mappings, and style settings. + +## Creating a visualization + +To open the visualization editor, use one of the following methods: + +- From the left navigation, select **Explorer** > **Logs**, then select the **Visualization** tab. +- From a dashboard, select the add panel icon, then select **Add visualization**. + +To create a visualization, follow these steps: + +1. Select a dataset from the dataset selector in the query bar (for example, **opensearch_dashboards_sample_data_logs**). +1. Write a PPL query in the query editor. If you selected a dataset, start the query with a pipe character (`|`). Otherwise, specify the source explicitly using `source =`. For example, the following query counts log events per hour: + + ```sql + source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1h) + ``` + {% include copy.html %} + + If `opensearch_dashboards_sample_data_logs` is already selected as the dataset, you can omit the `source`: + + ```sql + | stats count() by SPAN(@timestamp, 1h) + ``` + {% include copy.html %} + +1. Select **Update** or press **Enter** to run the query. +1. The editor automatically selects a chart type and maps fields to axes based on your query results. To change the chart type, use the **Visualization type** dropdown. +1. To customize the field mapping, use the **Fields** panel. + +## Using dashboard variables + +You can use dashboard variables to create dynamic, interactive visualizations. Variables let you switch between filter values, metrics, time intervals, and aggregation functions without editing the query. Reference variables in your PPL or PromQL queries using `$variableName` or `${variableName}` syntax. + +For more information, see [Dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/). + +## Saving a visualization + +To save a visualization, select **Save** (or **Save and back** if you opened the editor from a dashboard). Enter a name for the visualization and select **Save**. + +If you opened the visualization editor from a dashboard, the visualization is automatically added to that dashboard after saving. If you created the visualization from **Explorer** > **Logs**, save it first, then add it to a dashboard manually. + +## Saving and reusing queries + +To save a PPL query for reuse, select **Saved queries** > **Save query**. In the dialog, configure the following options. + +| Option | Description | +| --- | --- | +| **Save as new query** | When selected, saves the query as a new entry rather than overwriting an existing one. | +| **Name** | A name for the saved query. | +| **Description** | An optional description of the query. | +| **Include filters** | When enabled, saves the currently applied filters along with the query. | +| **Include time filter** | When enabled, saves the current time range along with the query. | + +Select **Save changes** to save the query. + +To load a previously saved query, select **Saved queries** > **Open query**, then select a query from the list and select the **Open query** button. The saved query is loaded into the query editor. + +## Visualization types + +For a list of supported chart types and their expected data shapes, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/viz-types/). + +## Configuring visualizations + +Shared configuration options (fields, split, axes, tooltip, legend, thresholds, and more) apply across multiple visualization types. For details, see [Configuring visualizations in the visualization editor]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/). + +## Query panel + +Use the query panel to choose a query language and dataset, write or build a query, and run it to generate a visualization. The query panel supports PPL, PromQL, and, when enabled, SQL. For PromQL, the query panel also provides **Builder** and **Code** modes, multiple query rows, and per-query and shared query options. + +For details, see [Query panel]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/query-panel/). + +## Data transformations + +Data transformations modify query results before the visualization is rendered. Use transformations to reshape, filter, sort, calculate, or summarize data without changing the original query. For details, see [Data transformations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/data-transformation/). + +## Related documentation + +- [PPL]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/) +- [Dashboard variables]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/dashboard-variables/) +- [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/) +- [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) +- [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/) diff --git a/_dashboards/visualize/visualization-editor/line-chart.md b/_dashboards/visualize/visualization-editor/line-chart.md new file mode 100644 index 00000000..7f5cf704 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/line-chart.md @@ -0,0 +1,135 @@ +--- +layout: default +title: Line chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 40 +--- + +# Line charts in the visualization editor + +A line chart plots data points connected by lines. Use a line chart to show trends and changes over time. Compare multiple series on the same time axis, and use a secondary y-axis to correlate metrics that have different scales. + +## Creating a line chart + +The following examples build on each other, starting with a basic chart and adding complexity. They use the sample web log dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic line chart + +Start with an aggregation query that counts events over time: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1h) +``` +{% include copy.html %} + +After running this query, the visualization editor automatically selects a **Line** chart and maps the fields: + +- The **X-Axis** displays the `SPAN(@timestamp, 1h)` field. +- The **Y-Axis** displays the `count()` field. + +The result is a single line showing the event count per hour, as shown in the following image. + +![Basic line chart showing event count per hour]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/line-chart-basic-result.png){: width="100%" } + +### Multi-series line chart + +Add a third dimension to your query to split the data into multiple series by category: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1h), response +``` +{% include copy.html %} + +This query groups the count by both time and the `response` field (HTTP status codes). Select `response` as the **Color** field to render a separate line for each status code value (for example, 200, 404, 503). + +The result is a multi-series line chart where each HTTP response code is displayed in a distinct color, as shown in the following image. + +![Multi-series line chart showing counts by HTTP response code]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/line-chart-multi-series.png){: width="100%" } + +### Multiple y-axis fields + +When your query computes multiple metrics, you can plot them all on the same chart: + +```sql +source = opensearch_dashboards_sample_data_logs | stats avg(bytes), max(bytes) by SPAN(@timestamp, 1h) +``` +{% include copy.html %} + +This query returns two numeric fields: `avg(bytes)` and `max(bytes)`. Select `avg(bytes)` and `max(bytes)` in the **Y-Axis** field list to plot them as separate lines on the same scale. + +The result shows both the average and maximum byte values over time, as shown in the following image. + +![Line chart with two y-axis metrics plotted together]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/line-chart-multiple-y-result.png){: width="100%" } + +### Secondary y-axis (dual axis) + +When two metrics have significantly different scales, plotting them on the same axis can make one appear flat. Use the **Y-Axis (2nd)** field to give the second metric its own scale on the right side of the chart. + +Using the same query as the previous example: + +```sql +source = opensearch_dashboards_sample_data_logs | stats avg(bytes), max(bytes) by SPAN(@timestamp, 1h) +``` +{% include copy.html %} + +This time, assign `avg(bytes)` to the **Y-Axis** and `max(bytes)` to the **Y-Axis (2nd)**. + +The result is a dual-axis chart. The left axis scales to `avg(bytes)` and the right axis scales to `max(bytes)`, as shown in the following image. + +![Dual-axis chart with avg(bytes) as line and max(bytes) as bars]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/line-chart-dual-axis-result.png){: width="100%" } + +## Configuring a line chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a date or numeric field for the horizontal axis. This field defines the buckets along which data is plotted (for example, `SPAN(@timestamp, 1h)`). | +| **Y-Axis** | Select one or more numeric fields to plot as separate lines. When multiple fields are selected, each renders as its own line on the same scale. | +| **Y-Axis (2nd)** | Select a numeric field to overlay on a secondary axis with its own scale. Use this when two metrics have different units or magnitudes. | +| **Color** | Select a categorical field to split the data into multiple series, each rendered in a different color. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + + +### Line + +The following table describes the line style settings. + +| Setting | Description | +| --- | --- | +| **Line style** | Controls whether the chart displays lines with points (**Default**), lines only (**Line only**), or points only (**Dots only**). | +| **Line dash style** | Sets the line pattern to **Solid**, **Dashed**, or **Dotted**. | +| **Interpolation** | Determines how points are connected. **Straight** draws direct lines between points. **Smooth** applies a curve. **Stepped** creates a staircase pattern, useful for data that changes at discrete intervals. | +| **Line width** | Sets the thickness of the lines in pixels. Supports values in the 1–10 range. | +| **Point size** | Sets the size of data points. This setting is available when points are shown. | +| **Show values** | Shows value labels on the chart. | +| **Show current time marker** | Shows a vertical marker for the current time. This setting is available only when the X-axis uses a date field. | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### Legend + +For information about configuring the legend, see [Legend]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#legend). + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/metric-chart.md b/_dashboards/visualize/visualization-editor/metric-chart.md new file mode 100644 index 00000000..24a57100 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/metric-chart.md @@ -0,0 +1,80 @@ +--- +layout: default +title: Metric chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 45 +--- + +# Metric charts in the visualization editor + +A metric chart displays a single numeric value prominently. Use a metric chart to show key performance indicators (KPIs) or summary statistics. + +## Creating a metric chart + +The following example demonstrates a basic metric visualization. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic metric chart + +Start with a query that returns a numeric field: + +```sql +source = opensearch_dashboards_sample_data_flights | FIELDS AvgTicketPrice +``` +{% include copy.html %} + +After running this query, select **Metric** as the chart type. The editor maps the field as follows: + +- The **Value** field displays the `AvgTicketPrice` field (using the **Last** calculation by default). + +The result is a single large number displaying the last ticket price value, as shown in the following image. + +![Metric chart displaying the last average ticket price]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/metric-chart-basic-result.png){: width="100%" } + +## Configuring a metric chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the data fields. + +| Field | Description | +| --- | --- | +| **Value** | Select a numeric field to display as the metric value. The field is reduced to a single number using the configured calculation method. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Metric + +| Setting | Description | +| --- | --- | +| **Text display** | Controls what text is shown alongside the value. Supported values: **Value only**, **Name only**, **Value and Name**, **None**. | +| **Color mode** | Controls how threshold colors are applied to the metric. Supported values: **None** (no color), **Value** (colors the value text), **Background gradient** (applies a gradient background), **Background solid** (applies a solid background color). | +| **Show percentage** | When enabled, displays the value as a percentage of the maximum value. | +| **Use threshold colors** | When enabled, applies threshold colors to the metric based on the current value. | + +### Value options + +| Setting | Description | +| --- | --- | +| **Calculation** | Determines how multiple data points are reduced to a single value. Supported values: **Last \***, **Last**, **First \***, **First**, **Min**, **Max**, **Median**, **Variance**, **Distinct count**, **Count**, **Total**. For more information, see [Value calculations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations/). | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, and decimal precision, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Text size + +| Setting | Description | +| --- | --- | +| **Value size** | Controls the font size of the displayed value. | +| **Title size** | Controls the font size of the metric title. | +| **Percentage size** | Controls the font size of the percentage display (when **Show percentage** is enabled). | diff --git a/_dashboards/visualize/visualization-editor/pie-chart.md b/_dashboards/visualize/visualization-editor/pie-chart.md new file mode 100644 index 00000000..78a3afea --- /dev/null +++ b/_dashboards/visualize/visualization-editor/pie-chart.md @@ -0,0 +1,95 @@ +--- +layout: default +title: Pie chart +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 50 +--- + +# Pie charts in the visualization editor + +A pie chart displays data as proportional slices of a circle. Use a pie chart to show part-to-whole relationships. + +## Creating a pie chart + +The following examples build on each other, starting with a basic chart and adding customization. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic pie chart + +Start with an aggregation query that counts events by category: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by Carrier +``` +{% include copy.html %} + +After running this query, the visualization editor maps the fields automatically: + +- The **Size** displays the `count()` field. +- The **Color** displays the `Carrier` field. + +The default rendering is a **Donut** chart. Each airline carrier appears as a colored slice proportional to its event count, as shown in the following image. + +![Donut chart showing count by carrier]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/pie-chart-donut-result.png){: width="100%" } + +### Customizing the pie chart + +Open the **Pie** settings panel and configure the following options: + +1. Change **Show as** from **Donut** to **Pie** to render a full circle without a center hole. +1. Enable **Show values** to display the count on each slice. +1. Enable **Show labels** to display the carrier name alongside each slice. +1. Set **Truncate after** to `300` for longer label text, as shown in the following image. + +![Pie chart settings with Pie mode, show values, and show labels enabled]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/pie-chart-settings-custom.png){: width="400" } + +The result is a full pie chart with both category labels and numeric values displayed on each slice, as shown in the following image. + +![Pie chart with labels and values shown]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/pie-chart-labels-result.png){: width="100%" } + +## Configuring a pie chart + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the data fields. + +| Field | Description | +| --- | --- | +| **Size** | Select a numeric field that determines the size of each slice. For example, `count()` makes each slice proportional to the number of events in that category. | +| **Color** | Select a categorical field that splits the data into individual slices, each rendered in a different color. For example, use a `Carrier` field to display a slice for each airline. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + + +### Pie + +The following table describes the pie chart settings. + +| Setting | Description | +| --- | --- | +| **Show as** | Controls whether the chart renders as a full pie or a **Donut** (ring) shape. **Donut** is the default. | +| **Show values** | When enabled, shows the numeric value for each slice on the chart. | +| **Show labels** | When enabled, shows the category label for each slice on the chart. | +| **Truncate after** | Sets the maximum width in pixels for labels before truncation. Only visible when **Show labels** is enabled. | + +### Standard options + +For information about configuring units, unit suffixes, and decimal precision, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Legend + +The legend summarizes the visual color encodings used in the chart. + +| Setting | Description | +| --- | --- | +| **Show legend** | Shows or hides the legend. | +| **Position** | Controls where the legend appears relative to the chart. Supported values: **Left**, **Right**, **Top**, **Bottom**. | + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/query-panel.md b/_dashboards/visualize/visualization-editor/query-panel.md new file mode 100644 index 00000000..a1dfa8bf --- /dev/null +++ b/_dashboards/visualize/visualization-editor/query-panel.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Query panel +parent: Creating visualizations using queries +grand_parent: Building data visualizations +nav_order: 91 +--- + +# Query panel + +Use the query panel to choose a query language and dataset, write or build a query, and run it to generate data for a visualization. + +The query panel supports Piped Processing Language (PPL), Prometheus Query Language (PromQL), and, when enabled, SQL. To enable SQL, add the following setting to your `opensearch_dashboards.yml` file: + +```yaml +explore.sqlSupport.enabled: true +``` +{% include copy.html %} + +AI query generation is available when prompt mode is enabled for the selected dataset. + +## Query panel controls + +The query panel includes the following controls. + +| Control | Description | +| --- | --- | +| **Language toggle** | Switches the editor between PPL, PromQL, SQL, and AI when those options are available. | +| **Dataset selector** | Selects the dataset or data source queried by the editor. Available datasets depend on the selected language. | +| **Saved queries** | Saves the current query or loads a previously saved query. | +| **Query editor** | Provides the text editor, or the PromQL editor or builder when PromQL is selected. | + +The following image shows the query panel with the language toggle, dataset selector, saved queries menu, and query editor. + +![Query panel showing the language toggle, dataset selector, saved queries menu, and query editor]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/query-panel.png){: width="100%" } + +## Selecting a query language + +Use the language toggle to select the query language. The selected language determines which datasets are available and which editor features are shown. + +| Language | Description | +| --- | --- | +| **PPL** | Queries OpenSearch datasets using Piped Processing Language. | +| **PromQL** | Queries Prometheus data sources and displays the PromQL multi-query editor. | +| **SQL** | Queries OpenSearch datasets using SQL. This option appears only when `explore.sqlSupport.enabled` is set to `true`. | +| **AI** | Generates a query from a natural language prompt. This option appears only when prompt mode is available. | + +## Selecting a dataset + +Use the dataset selector to choose the data queried by the visualization editor. Dataset availability depends on the selected query language: + +- **PPL** and **SQL** use OpenSearch datasets, such as indexes and index patterns. +- **PromQL** uses Prometheus datasets. + +## Writing PPL queries + +After you select a dataset, you can write a PPL query. The visualization editor uses the selected dataset as the query source. + +For example, if `opensearch_dashboards_sample_data_logs` is selected, you can enter the following query: + +```sql +| stats count() by response +``` +{% include copy.html %} + +You can also include the source explicitly: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by response +``` +{% include copy.html %} + +## Writing PromQL queries + +When **PromQL** is selected, the editor displays a multi-query editor. Each query row can be written in **Builder** mode or **Code** mode. + +The following image shows the PromQL multi-query editor. + +![PromQL multi-query editor with one query row in Builder mode]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/promql-panel.png) + +Use **Builder** mode to build a PromQL query from metric names, label filters, and operations. Use **Code** mode to write PromQL directly. Some code queries cannot be represented in **Builder** mode, so switching back to **Builder** mode may not be available for complex queries. + +The following example uses **Builder** mode to write a PromQL query: + +```prometheus +sum(rate(go_gc_heap_allocs_bytes_total[50060s])) +``` +{% include copy.html %} + +The following image shows the same query built in **Builder** mode from a `sum` aggregation, a `rate` function with a `50060s` window, and the `go_gc_heap_allocs_bytes_total` metric. + +![PromQL query built in Builder mode from a sum aggregation, a rate function, and a metric name, with the generated query shown below the controls]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/promql-builder-case.png){: width="100%" } + +You can manage PromQL query rows as follows: + +- Select **Add query** to add another PromQL query row. +- Select the remove icon to delete a query row. +- Drag query rows to reorder them. +- Select **Update** to run the query. In **Code** mode, you can also press Command+Enter (macOS) or Ctrl+Enter (Windows and Linux). + +## PromQL query options + +PromQL provides per-query options for each query row and shared options for all rows. To configure the options for a single query row, select the gear icon at the end of the row. To configure the options shared by all rows, select **Query options**. + +The following image shows the per-query options for a PromQL query row. + +![Per-query options for a PromQL query row, including Series name and Min step, with the estimated step and rate window]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/per-query-option.png){: width="100%" } + +### Series name + +Use **Series name** to customize the displayed series name. You can reference metric labels using double curly braces. + +For example, enter {% raw %}`{{job}}`{% endraw %} to name each series by its job label, or enter {% raw %}`{{job}}-{{instance}}`{% endraw %} to combine multiple labels. + +The following bar chart sets **Series name** to {% raw %}`{{operation}}`{% endraw %}, so the legend names each series by its operation label, `Read` and `Write`. + +![Bar chart whose legend names each series by its operation label, Read and Write, with the Series name option set in the query row]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/series-name-operation.png) + +### Minimum step + +Use **Min step** to set the lower bound for the PromQL query step. Enter a duration with a unit, such as `15s`, `1m`, or `2h`. Match this value to your Prometheus scrape interval. The options panel shows the resulting step (`$__interval`) and rate window (`$__rate_interval`) as estimates; run the query to confirm the values. + +### Maximum number of data points + +Use **Max data points** to set the maximum number of points returned per series. This option is shared by all PromQL query rows. Leave this setting empty to use the automatic value. + +The following image shows **Max data points** in the shared **Query options** panel, with the automatic value of `1440`. + +![Max data points set to the automatic value of 1440 in the shared Query options panel]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/max-point.png) + +## Saving and reusing queries + +To save a query for reuse, select **Saved queries** > **Save query**. To load a saved query, select **Saved queries** > **Open query**, and then choose the query to load. + +The following image shows the **Saved queries** menu with the **Save query** and **Open query** options. + +![Saved queries menu expanded to show the Save query and Open query options]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/query-panel/open-saved-query.png){: width="60%" } diff --git a/_dashboards/visualize/visualization-editor/scatter-chart.md b/_dashboards/visualize/visualization-editor/scatter-chart.md new file mode 100644 index 00000000..e6a5ef82 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/scatter-chart.md @@ -0,0 +1,126 @@ +--- +layout: default +title: Scatter plot +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 55 +--- + +# Scatter plots in the visualization editor + +A scatter plot visualizes relationships between two numerical variables. Each point on the chart represents an observation from the dataset, with its position determined by the values of the two variables. You can split data by a categorical field to compare how different groups distribute across the same dimensions. + +## Creating a scatter plot + +The following examples build on each other, starting with a basic two-variable scatter and adding dimensions. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic scatter plot + +Start with a query that returns two numeric fields: + +```sql +source = opensearch_dashboards_sample_data_flights | fields AvgTicketPrice, DistanceMiles +``` +{% include copy.html %} + +After running this query, select **Scatter** as the chart type. The fields are mapped as follows: + +- The **X-Axis** displays the `AvgTicketPrice` field. +- The **Y-Axis** displays the `DistanceMiles` field. + +The result is a scatter plot showing the relationship between ticket price and flight distance. Each point represents a single flight, as shown in the following image. + +![Basic scatter plot showing average flight price compared to distance]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/scatter/scatter-two-num-fields.png){: width="100%" } + +### Using thresholds + +To apply thresholds, enable **Use threshold colors** in the **Scatter** section. Then open the **Thresholds** section and add a threshold of `6000` to highlight long-distance flights, as shown in the following image. + +![Scatter plot with threshold at 6000 highlighting long-distance flights]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/scatter/scatter-with-threshold.png){: width="100%" } + +For more information, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Adding a color dimension + +Add a categorical field to split the data points into color-coded groups: + +```sql +source = opensearch_dashboards_sample_data_flights | fields AvgTicketPrice, DistanceMiles, DestWeather +``` +{% include copy.html %} + +This query returns two numeric fields: `AvgTicketPrice` and `DistanceMiles`. Select `DestWeather` as the **Color** field. + +The result is a scatter plot with points split into color-coded groups---each weather condition is rendered in a distinct color, as shown in the following image. + +![Scatter plot with color-coded weather categories]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/scatter/scatter-two-numerical-one-cate-fields.png){: width="100%" } + +### Adding a size dimension + +Add a third numeric field to control point size, creating a bubble chart: + +```sql +source = opensearch_dashboards_sample_data_flights | fields AvgTicketPrice, DistanceMiles, DestWeather, FlightDelayMin +``` +{% include copy.html %} + +This query returns three numeric fields: `AvgTicketPrice`, `DistanceMiles`, and `FlightDelayMin`. Select `DestWeather` as the **Color** field and map `FlightDelayMin` to the **Size** field. + +Points now vary in size---larger bubbles represent longer delays. Each color still represents a weather condition, making it possible to identify whether certain weather types correlate with both higher prices and longer delays, as shown in the following image. + +![Scatter plot with size representing flight delay minutes]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/scatter/scatter-two-numerical-one-cate-fields-one-size.png){: width="100%" } + +## Configuring a scatter plot + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Configuration | Fields | Description | +| :---| :---| :---| +| **Two numerical** | X-Axis (numeric), Y-Axis (numeric) | Select two numeric fields to display data points showing the relationship between two numerical variables. | +| **Two numerical + one categorical** | X-Axis (numeric), Y-Axis (numeric), Color (categorical) | Select two numeric fields and a categorical Color field to display data points split into color-coded groups. | +| **Three numerical + one categorical** | X-Axis (numeric), Y-Axis (numeric), Size (numeric), Color (categorical) | Select three numeric fields and a categorical Color field to display data points with colors indicating categories and the third numeric field controlling the size of the points. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Scatter + +Use the following settings to customize the appearance of the scatter plot. + +| Setting | Description | +| :---| :---| +| **Point size** | Controls the default size of data points when no Size field is mapped. | +| **Shape** | Controls the shape of each data point. Supported values: **Circle**, **Square**, **Diamond**, **Cross**. | +| **Filled** | When enabled, data points are filled with color. When disabled, only the outline is rendered. | +| **Angle** | Controls the display angle of each data point in degrees. Supports values in the 0–360 range. | + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Standard options + +For information about configuring units, unit suffixes, decimal precision, and minimum and maximum values, see [Standard options]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### Legend + +The legend summarizes the visual color encodings used in the chart. + +| Setting | Description | +| :---| :---| +| **Show legend** | Shows or hides the legend. | +| **Position** | Controls where the legend appears relative to the chart. Supported values: **Left**, **Right**, **Top**, **Bottom**. | + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/state-timeline-chart.md b/_dashboards/visualize/visualization-editor/state-timeline-chart.md new file mode 100644 index 00000000..704bd10d --- /dev/null +++ b/_dashboards/visualize/visualization-editor/state-timeline-chart.md @@ -0,0 +1,153 @@ +--- +layout: default +title: State timeline +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 60 +--- + +# State timelines in the visualization editor + +A state timeline displays a series of horizontal bars that represent state changes over time. Each bar, known as a state region, represents a specific state, and its length indicates the duration of that state. + +## Creating a state timeline + +The following examples build on each other, starting with a basic timeline and adding complexity. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Single-category state timeline + +Start with a query that returns a time field and a state field: + +```sql +source = opensearch_dashboards_sample_data_logs | fields timestamp, response +``` +{% include copy.html %} + +After running this query, select **State Timeline** as the chart type. The fields are mapped as follows: + +- The **X-Axis** displays the `timestamp` field. +- The **Color** displays the `response` field. + +The result is a single row of colored segments, where each segment represents a time period during which a particular response status code was recorded, as shown in the following image. + +![Basic state timeline showing request changes over time]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/state-timeline/state-timeline-single-cate-field.png){: width="100%" } + +### Applying value mappings + +Use value mappings to assign custom labels and colors to specific state values. For example, to categorize HTTP response codes into meaningful groups: + +1. In the **Value mappings** section, select **Edit value mappings**. +1. Select **Add new mapping** and select **Value** as the mapping type. +1. In the **Value** field, enter `200`. In the **Display text** field, enter `Successful`. Select the color green. +1. Repeat for `404` with the label `Error` and the color orange. +1. Repeat for `503` with the label `Error` and the color red, as shown in the following image, and then select **Save**. + +Alternatively, select **Range** as the mapping type to group continuous values into bands. For example, map all status codes in the range [400, 600) to display as "Error" in red. + +![Value mappings options]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/state-timeline/value-mapping-for-reponse.png){: width="400" } + +The timeline now displays user-configured labels for each data value and uses consistent colors---green for successful responses and red for errors, as shown in the following image. + +![State timeline with value mappings applied]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/state-timeline/state-timeline-value-mapping.png){: width="100%" } + +### Handling data gaps + +In a state timeline, each data point's `timestamp` serves as the start time of a state region, and the next data point's `timestamp` marks its end. When data has gaps (missing data points between timestamps), use the **Disconnect values** or **Connect null values** settings to control how these gaps are visualized. + +You can apply only one of **Disconnect values** and **Connect null values** at a time. +{: .note} + +The following example shows the effect of setting the **Disconnect values** threshold: + +![State timeline with disconnect threshold settings]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/state-timeline/disconnect-threshold.gif){: width="100%" } + +### Multi-category state timeline + +Add a categorical grouping field to display multiple rows of state timelines: + +```sql +source = opensearch_dashboards_sample_data_logs | fields timestamp, request, response +``` +{% include copy.html %} + +After running this query, select **State Timeline** as the chart type. The fields are mapped as follows: + +- The **X-Axis** displays the `timestamp` field. +- The **Y-Axis** displays the `request` field. +- The **Color** field displays the `response` field. + +The result shows each request path's response status over time, making it easy to identify which endpoints experience frequent instability, as shown in the following image. + +![State timeline grouped by request]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/state-timeline/state-timeline-grouped.png){: width="100%" } + +## Configuring a state timeline + +You can configure the following settings in the configuration panel. + +### Fields + +In the **Fields** section, configure the fields displayed on each axis. + +| Field | Description | +| --- | --- | +| **X-Axis** | Select a date field for the horizontal axis. Each data point's timestamp serves as the start time of a state region. | +| **Y-Axis** | Select a categorical field to group state timelines into separate rows. Each unique value is rendered as its own row. Optional for single-category timelines. | +| **Color** | Select a categorical or numeric field to define the state at each time point. Categorical fields represent discrete states (such as `running`, `stopped`, or `degraded`). Numerical fields can represent states when each value corresponds to a distinct state (for example, HTTP status codes 200, 404, 503). For continuous numerical values, use [value mappings](#value-mappings) to define ranges as named states. | + +### Split + +In the **Split by** dropdown list, select a field to split the chart into separate elements by value. For more information, see [Split]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#split). + +### Value mappings + +Value mappings replace raw data values with custom labels and colors. The following mapping types are available. + +**Value mapping**: Maps a specific value (numerical or categorical) to a custom display text and color. For example, map the HTTP status code `200` to display as "Success" in green, and `503` to display as "Error" in red. + +**Range mapping**: Maps a numerical range to a custom display text and color. For example, map the range [0, 300) to display as "Low" and [300, 800) to display as "Medium". + +Each mapping entry has the following options. + +| Setting | Description | +| --- | --- | +| **Value/Range** | The target value or numeric range to match. For value mappings, enter a specific value. For range mappings, define a start and end value (start-inclusive, end-exclusive). | +| **Display text** | The label to show in place of the original value. If left blank, the original value is displayed. | +| **Color** | A custom color for the mapped value. If left undefined, a color is automatically assigned. | + +For a complete example, see [Applying value mappings](#applying-value-mappings). + +### Thresholds + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Axes + +The X-axis and Y-axis share the same configuration options. For more information, see [Axes]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/#axes). + +### State timeline + +Use the following settings to customize the appearance and behavior of the state timeline. + +| Setting | Description | +| --- | --- | +| **Use threshold color** | When enabled, state region colors are determined by threshold ranges rather than the default or mapped colors. | +| **Show display text** | When enabled and a value mapping with display text is configured, the mapped text is shown inside each state region. When disabled, no text is displayed. | +| **Row height** | Controls the height of each state bar. A value of 0 produces the minimum bar width, and 1 produces the maximum bar width. | +| **Disconnect values** | Controls whether state regions are visually disconnected when gaps exceed a specified duration. **Never** keeps all regions connected. **Threshold** disconnects regions when the gap between data points exceeds the configured threshold. | +| **Threshold (disconnect)** | Sets the duration threshold for disconnecting values. If a gap between consecutive data points exceeds this threshold, the bars are rendered as separate disconnected regions. Specify as a duration (for example, `1h` or `30m`). | +| **Connect null values** | Controls how null values (gaps in the data) appear on the chart. **Never** leaves gaps visible. **Threshold** connects gaps only when they fall within the configured threshold. | +| **Threshold (connect)** | Sets the duration threshold for connecting null values. If a gap between data points falls within this threshold, the points are connected, bridging the gap. Specify as a duration (for example, `1h` or `30m`). | + +### Legend + +The legend summarizes the visual color encodings used in the chart. + +| Setting | Description | +| --- | --- | +| **Show legend** | Shows or hides the legend. | +| **Position** | Controls where the legend appears relative to the chart. Supported values: **Left**, **Right**, **Top**, **Bottom**. | + +### Tooltip + +Toggle the **Show tooltip** selector to enable or disable tooltips. diff --git a/_dashboards/visualize/visualization-editor/table-chart.md b/_dashboards/visualize/visualization-editor/table-chart.md new file mode 100644 index 00000000..d94c77e2 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/table-chart.md @@ -0,0 +1,56 @@ +--- +layout: default +title: Table +parent: Visualization types +grand_parent: Creating visualizations using queries +great_grand_parent: Building data visualizations +nav_order: 65 +--- + +# Tables in the visualization editor + +A table displays query results in rows and columns. Use a table to view raw data or summary statistics. + +## Creating a table + +The following example demonstrates a basic table visualization. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/#prerequisites). + +### Basic table + +Start with a query that returns multiple fields: + +```sql +source = opensearch_dashboards_sample_data_flights | fields Carrier, AvgTicketPrice, DistanceMiles, FlightDelayMin | head 20 +``` +{% include copy.html %} + +After running this query, select **Table** as the chart type. The result is a table displaying the selected fields as columns, as shown in the following image. + +![A table displaying flight data]({{site.url}}{{site.baseurl}}/images/dashboards/visualization-editor/table-chart-basic-result.png){: width="100%" } + +## Configuring a table + +You can configure the following settings in the configuration panel. + +### Table + +| Setting | Description | +| --- | --- | +| **Max rows per page** | Sets the maximum number of rows displayed per page. | +| **Cell alignment** | Controls the text alignment within cells. Supported values: **Auto**, **Left**, **Center**, **Right**. | +| **Cell style** | Select **Add new cell type** to apply custom styling to specific columns. | +| **Column filters** | When enabled, displays filter controls in column headers for interactive filtering. | + +### Threshold + +For information about configuring thresholds, see [Thresholds]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds/). + +### Table footer + +| Setting | Description | +| --- | --- | +| **Show footer** | When enabled, displays a footer row with summary calculations for each column. | + +### Data links + +Select **Add link** to create clickable links within table cells. Use data links to navigate to external URLs or other dashboards based on cell values. diff --git a/_dashboards/visualize/visualization-editor/viz-types.md b/_dashboards/visualize/visualization-editor/viz-types.md new file mode 100644 index 00000000..e5f76e66 --- /dev/null +++ b/_dashboards/visualize/visualization-editor/viz-types.md @@ -0,0 +1,28 @@ +--- +layout: default +title: Visualization types +parent: Creating visualizations using queries +grand_parent: Building data visualizations +nav_order: 50 +has_children: true +has_toc: false +--- + +# Query-based visualization types + +The following table lists the visualization types supported by the visualization editor and their expected data shapes. + +| Chart type | Data shape | +| :--- | :--- | +| [Area chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/area-chart/) | One date field + one or more numeric fields (supports stacking) | +| [Bar chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/bar-chart/) | One or more categorical or date fields + one or more numeric fields | +| [Bar gauge chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/bar-gauge-chart/) | One or more numeric fields (single values) | +| [Gauge chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/gauge-chart/) | One numeric field (single value) | +| [Heatmap]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/heatmap-chart/) | Two categorical or date fields + one numeric field | +| [Histogram]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/histogram-chart/) | One numeric field (distribution) | +| [Line chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/line-chart/) | One date field + one or more numeric fields | +| [Metric chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/metric-chart/) | One numeric field (single value) | +| [Pie chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/pie-chart/) | One categorical field + one numeric field | +| [Scatter plot]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/scatter-chart/) | Two or more numeric fields | +| [State timeline]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/state-timeline-chart/) | One date field + one categorical field (state values) | +| [Table]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/table-chart/) | Any combination of fields (displays raw data) | diff --git a/_dashboards/visualize/visualize-app/aggregation-based-viz.md b/_dashboards/visualize/visualize-app/aggregation-based-viz.md new file mode 100644 index 00000000..595200d8 --- /dev/null +++ b/_dashboards/visualize/visualize-app/aggregation-based-viz.md @@ -0,0 +1,131 @@ +--- +layout: default +title: Creating aggregation-based visualizations +parent: Creating visualizations in the Visualize application +grand_parent: Building data visualizations +nav_order: 10 +--- + +# Creating aggregation-based visualizations + +[Aggregations]({{site.url}}{{site.baseurl}}/aggregations/) are the analytics engine behind most visualizations in OpenSearch Dashboards. They calculate statistics (metrics) and group data into categories (buckets) so that results can be displayed as charts, tables, and maps. When you configure a visualization in the **Visualize** application, OpenSearch Dashboards translates your selections into aggregation queries automatically. + +The following visualization types use aggregations: **Area**, **Horizontal Bar**, **Vertical Bar**, **Coordinate Map**, **Data Table**, **Gauge**, **Goal**, **Heat Map**, **Line**, **Metric**, **Pie**, **Region Map**, and **Tag Cloud**. + +For a complete list of available metrics and buckets, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/#data-tab). + +In this tutorial, you'll create a Vertical Bar visualization using the sample flight data and learn how to use metric aggregations, bucket aggregations, split series, percentiles, pipeline aggregations, and top hits. + +## Prerequisites + +The examples on this page use the **Sample flight data** dataset. If you haven't added sample data yet, see [Prepare your data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Example 1: Flight count over time + +This example uses the default **Count** metric with a **Date Histogram** bucket to show the number of flights per time interval. + +To create a flight count visualization, follow these steps: + +1. In the left navigation menu, select **OpenSearch Dashboards** > **Visualize**. +1. Select **Create visualization**. +1. Select **Vertical Bar**, then select **opensearch_dashboards_sample_data_flights** as the source. +1. Set the time filter to **Last 7 days**. +1. In the **Buckets** panel, select **Add** > **X-axis**. +1. From the **Aggregation** dropdown list, select **Date Histogram**. +1. Verify that the **Field** is set to **timestamp**. +1. Select **Update**. + +The chart displays the number of flights per 3-hour interval. The Y-axis shows **Count**---the number of documents (flights) in each time bucket. Because **Count** is the default metric, no field selection is required. + +![Flight count over time using Count metric and Date Histogram bucket]({{site.url}}{{site.baseurl}}/images/dashboards/aggregation-viz-count-date-histogram.png) + +## Example 2: Average ticket price over time + +This example replaces Count with the **Average** metric to show how ticket prices change over time. + +To change the metric to **Average**, follow these steps: + +1. In the **Metrics** panel, select the **Y-axis** section. +1. From the **Aggregation** dropdown list, select **Average**. +1. From the **Field** dropdown list, select **AvgTicketPrice**. +1. Select **Update**. + +The Y-axis now shows dollar values instead of document counts. Each bar represents the average ticket price across all flights in that time interval. + +![Average ticket price over time]({{site.url}}{{site.baseurl}}/images/dashboards/aggregation-viz-avg-ticket-price.png) + +## Example 3: Flight count by carrier + +This example adds a **Split series** bucket to break down the **Count** metric by airline carrier. + +To split the series by carrier, follow these steps: + +1. In the **Metrics** panel, change the **Aggregation** back to **Count**. +1. In the **Buckets** panel, select **Add** > **Split series**. +1. From the **Aggregation** dropdown list, select **Terms**. +1. From the **Field** dropdown list, select **Carrier**. +1. Select **Update**. + +The chart now displays stacked bars, with each color representing a different airline. The legend identifies each carrier. This configuration creates a nested aggregation: the **Date Histogram** groups flights into time buckets, and the **Terms** aggregation subdivides each bucket by carrier. + +![Flight count split by carrier]({{site.url}}{{site.baseurl}}/images/dashboards/aggregation-viz-split-series-carrier.png) + +## Example 4: Ticket price percentiles over time + +This example uses the **Percentiles** metric to show the distribution of ticket prices across time intervals. Unlike **Average** (which returns a single value), **Percentiles** returns multiple values---one for each percentile you configure. + +To create a **Percentiles** visualization, follow these steps: + +1. In the **Metrics** panel, select the **Y-axis** section. +1. From the **Aggregation** dropdown list, select **Percentiles**. +1. From the **Field** dropdown list, select **AvgTicketPrice**. +1. In the **Percents** section, remove the default values and enter `25`, `50`, and `75` (the interquartile range). Use the delete icon next to each value to remove it, and select **Add percent** to add new ones. +1. In the **Buckets** panel, verify that the **X-axis** is set to **Date Histogram** on the **timestamp** field. +1. Select **Update**. + +The chart displays three stacked series---one for each percentile. The 50th percentile (median) shows the middle value, while the gap between the 25th and 75th percentiles shows the spread of ticket prices in each time bucket. + +![Ticket price percentiles over time]({{site.url}}{{site.baseurl}}/images/dashboards/aggregation-viz-percentiles.png) + +## Example 5: Cumulative flight count + +This example uses the **Cumulative Sum** pipeline aggregation to show a running total of flights. Pipeline aggregations operate on the output of another metric rather than directly on document fields. + +To add a cumulative sum to your visualization, follow these steps: + +1. In the **Metrics** panel, verify that the first Y-axis is set to **Count**. +1. Select **Add** to create a second metric. +1. From the **Aggregation** dropdown list, scroll down to **Parent Pipeline Aggregations** and select **Cumulative Sum**. +1. In the **Metric** dropdown list, select **Custom metric**. +1. In the nested **Aggregation** dropdown list that appears, select **Count**. +1. In the **Buckets** panel, verify that the **X-axis** is set to **Date Histogram** on the **timestamp** field. +1. Select **Update**. + +The chart displays the per-interval **Count** as bars along the bottom and the **Cumulative Sum** as a rising line. The line shows the total number of flights accumulated over time. + +![Cumulative flight count]({{site.url}}{{site.baseurl}}/images/dashboards/aggregation-viz-cumulative-sum.png) + +## Example 6: Most recent ticket price over time + +This example uses the **Top Hit** metric to display the most recent ticket price in each time bucket. **Top Hit** has the most configuration options of any metric: it lets you control which document values are returned, how many, and in what order. + +To create a **Top Hit** visualization, follow these steps: + +1. In the **Metrics** panel, select the **Y-axis** section. +1. From the **Aggregation** dropdown list, select **Top Hit**. +1. From the **Field** dropdown list, select **AvgTicketPrice**. +1. From the **Aggregate with** dropdown list, select **Max** (this determines how multiple values within the same bucket are combined). +1. Set **Size** to `1` (return one value per bucket). +1. From the **Sort on** dropdown list, select **timestamp**. +1. From the **Order** dropdown list, select **Descending** (most recent first). +1. In the **Buckets** panel, verify that the **X-axis** is set to **Date Histogram** on the **timestamp** field. +1. Select **Update**. + +The chart displays the most recent (highest-timestamp) ticket price in each 3-hour interval. Unlike **Average**, which smooths all values together, **Top Hit** shows a single document's actual value, which is useful for tracking the latest state per time window. + +![Most recent ticket price over time using Top Hit]({{site.url}}{{site.baseurl}}/images/dashboards/aggregation-viz-top-hit.png) + +## Next steps + +- To learn about all available metric and bucket aggregations, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/#data-tab). +- To understand how aggregations work in the API, see [Aggregations]({{site.url}}{{site.baseurl}}/aggregations/). diff --git a/_dashboards/visualize/visualize-app/area.md b/_dashboards/visualize/visualize-app/area.md new file mode 100644 index 00000000..4b43822b --- /dev/null +++ b/_dashboards/visualize/visualize-app/area.md @@ -0,0 +1,179 @@ +--- +layout: default +title: Area chart +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 30 +redirect_from: + - /dashboards/visualize/area/ +--- + +# Area chart + +An area chart is a line chart with the area below the line shaded with a color. You can stack multiple buckets to show relative proportions of a running absolute value of the variable, or superimpose buckets or different variables to compare within x-axis buckets or time values. + +## When to use area charts + +Use area charts to show both trend patterns and proportional relationships simultaneously. They reveal contribution patterns, showing which components drive overall totals and when those patterns change. + +## Creating an area chart + +The examples on this page use the **Sample flight data** dataset and build on each other. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create an area chart that shows flight count over time, follow these steps: + +1. In the **New Visualization** dialog, select **Area**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). +2. Under **Metrics**, expand **Y-axis Count** and set **Aggregation** to **Count**. + + For the `Count` metric there is no Field selection because `Count` denotes the number of documents, not a field value. + +3. Under **Buckets**, select **Add** > **X-axis**. +4. Set **Aggregation** to **Date Histogram** and **Field** to **timestamp**. + + The timestamp field is the only date-time field available in the sample flight data. + {: .note} + +5. Select **Update**. + + The chart generates a jagged time-series plot of the document count for an automatically determined bucket size (for example, one day). + +6. Drag-select the portion of the chart containing the data. Leave a margin on either side of the data so as not to cut any data off. + + The data expands to fill the entire width of the graph. Since there's more room, the auto-calculated bucket size decreases to 12 hours. + +7. Under **Buckets**, select **Add** > **Split series**. +8. Set **Sub aggregation** to **Terms** and **Field** to **Cancelled**. +9. Select **Update**. + + The chart shows the counts of cancelled and uncancelled flights superimposed on the timeline, as shown in the following image. + + ![Area chart with flight cancellation status overlaid]({{site.url}}{{site.baseurl}}/images/dashboards/example-area-normal-count.png) + + Note the following: + - The count of cancelled (`Cancelled = true`) and uncancelled flights are superimposed on the graph. The cancelled flight count seems to average about 10% of the uncancelled flights. + - The flight count is cyclic over time, with a one-day dip every week. + +### Stacked area chart + +By default, split series are overlaid (Normal mode). To stack the areas on top of each other so they show the total volume: + +1. Select the **Metrics & axes** tab. +2. Under **Metrics**, expand the **Count** series. +3. Change **Mode** from **Normal** to **Stacked**. +4. Select **Update**. + +The areas are now stacked, showing both individual category volumes and the combined total, as shown in the following image. + +![Stacked area chart showing flight cancellation status]({{site.url}}{{site.baseurl}}/images/dashboards/example-area-stacked-count.png) + +### Multiple metrics + +Add a second Y-axis metric to compare different measurements on the same chart: + +1. Under **Metrics**, select **Add**. +2. Set **Aggregation** to **Average** and **Field** to **AvgTicketPrice**. +3. Select **Update**. + +The chart now overlays the average ticket price on top of the count. To give the second metric its own scale, go to the **Metrics & axes** tab, expand the new metric, and assign it to a new value axis. + +## Configuring an area chart + +The area chart editor has three configuration tabs. + +### Data tab + +The **Data** tab defines what data is displayed. + +#### Metrics + +Metrics define the Y-axis values. Each metric computes an aggregation over the documents in each bucket. + +| Setting | Description | +| :--- | :--- | +| **Aggregation** | The aggregation function. Supported values: **Count**, **Average**, **Sum**, **Min**, **Max**, **Unique Count**, **Median**, **Percentiles**, **Percentile Ranks**, **Top Hit**, **Standard Deviation**. | +| **Field** | The numeric field to aggregate (not required for **Count**). | + +Select **Add** to plot multiple metrics on the same chart. + +#### Buckets + +Buckets define how data is grouped. + +| Bucket type | Description | +| :--- | :--- | +| **X-axis** | Groups data along the horizontal axis. Typically uses a **Date Histogram** for time-based data or a **Histogram** for numeric ranges. | +| **Split series** | Splits the data into multiple stacked (or overlaid) areas by the values of a field. Uses **Terms**, **Filters**, or other bucket aggregations. | +| **Split chart** | Creates separate chart panels for each bucket value (small multiples). Can split in rows or columns. | + +### Metrics & axes tab + +The **Metrics & axes** tab controls how each metric is rendered and how the axes are configured. + +#### Series settings + +Each metric series has the following options. + +| Setting | Description | +| :--- | :--- | +| **Value axis** | The Y-axis this series is plotted against. Select **New axis** to create a secondary Y-axis. | +| **Chart type** | Overrides the chart type for this series. Supported values: **Line**, **Area**, **Bar**. | +| **Mode** | Controls stacking behavior. **Stacked** layers areas on top of each other. **Normal** overlaps areas. | +| **Line mode** | Controls line interpolation. **Straight** draws direct segments. **Smoothed** applies a curve. **Stepped** creates a staircase pattern. | + +#### Y-axes + +Each Y-axis has the following options. + +| Setting | Description | +| :--- | :--- | +| **Position** | Where the axis appears. Supported values: **Left**, **Right**. | +| **Mode** | Controls the Y-axis scale mode. **Normal** displays raw values. **Percentage** normalizes stacked areas to 100%. **Wiggle** and **Silhouette** are stream graph layout variants. | +| **Scale type** | Determines the scale. Supported values: **Linear**, **Log**, **Square root**. | +| **Show** | Shows or hides the axis line and labels. | +| **Labels** | Controls label rotation. Supported values: **Horizontal**, **Vertical**, **Angled**. | + +#### X-axis + +| Setting | Description | +| :--- | :--- | +| **Position** | Where the axis appears. Supported values: **Top**, **Bottom**. | +| **Show** | Shows or hides the axis line and labels. | +| **Filter labels** | When enabled, overlapping labels are automatically hidden. | +| **Align** | Controls label rotation. Supported values: **Horizontal**, **Vertical**, **Angled**. | +| **Truncate** | Sets the maximum pixel width for labels before truncation. | + +### Panel settings tab + +The **Panel settings** tab controls the overall chart appearance. + +#### Settings + +| Setting | Description | +| :--- | :--- | +| **Legend position** | Where the legend appears. Supported values: **Top**, **Left**, **Right**, **Bottom**. | +| **Show tooltip** | When enabled, displays values on hover. | +| **Order buckets by sum** | When enabled, orders split series by their total value rather than alphabetically. | + +#### Grid + +| Setting | Description | +| :--- | :--- | +| **Show X-axis lines** | When enabled, displays vertical grid lines at each X-axis tick. | +| **Y-axis lines** | Select a Y-axis to display horizontal grid lines, or **Don't show** to hide them. | + +#### Threshold line + +| Setting | Description | +| :--- | :--- | +| **Show threshold line** | When enabled, draws a horizontal reference line at a specified value. | +| **Threshold value** | The Y-axis value at which the line is drawn. | +| **Line width** | The thickness of the threshold line in pixels. | +| **Line style** | The line style. Supported values: **Full** (solid), **Dashed**, **Dot-dashed**. | +| **Line color** | The color of the threshold line. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/bar-charts.md b/_dashboards/visualize/visualize-app/bar-charts.md new file mode 100644 index 00000000..682d54f2 --- /dev/null +++ b/_dashboards/visualize/visualize-app/bar-charts.md @@ -0,0 +1,85 @@ +--- +layout: default +title: Bar chart +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 40 +redirect_from: + - /dashboards/visualize/bar-charts/ +--- + +# Bar chart + +A bar chart compares values across categories by representing values as proportional bar lengths. Use vertical bars for time-series data or category comparisons, and horizontal bars when category labels are long or when comparing many categories. + +## When to use bar charts + +Use bar charts to reveal variation over an independent variable, comparative performance across categories, and trends over time. Bar charts can show performance gaps, outliers, seasonal patterns, and comparative advantages across categories. You can select bars to filter other visualizations on the same dashboard. + +## Creating a bar chart + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a bar chart, follow these steps: + +1. In the **New Visualization** dialog, select **Vertical Bar** (or **Horizontal Bar**), then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). +2. Under **Metrics**, expand **Y-axis Count**. +3. Set **Aggregation** to **Average** and **Field** to **FlightDelayMin**. +4. (Optional) Enter a **Custom label**, for example `Flight delay in minutes`. +5. Select **Update**. + + The chart displays a single bar with height of about `47`, the average flight delay for every document in the flight database. + + If your visualization displays a different value, make sure that your time filter window is large enough to encompass all the sample flight data. + {: .note} + +6. Under **Buckets**, select **Add** > **X-axis**. +7. Set **Aggregation** to **Terms** and **Field** to **OriginWeather**. +8. Set **Order by** to `Metric: FlightDelayMin`, **Order** to **Descending**, and **Size** to `8`. + + Any number eight or higher displays all of the available `OriginWeather` terms. + {: .note} + +9. Select **Update**. + + The chart shows the average delay for each weather type at the flight origin. The greatest average delay was for `Damaging Wind`, as shown in the following image. + + ![Bar chart showing average flight delay by origin weather]({{site.url}}{{site.baseurl}}/images/dashboards/example-bar-chart-flight-delay.png) + +## Configuring a bar chart + +Bar charts share the same configuration tabs as other aggregation-based visualizations. For information about each tab, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Data tab + +| Setting | Description | +| :--- | :--- | +| **Metrics** | Defines the Y-axis values. Supports all standard aggregations (Count, Average, Sum, Min, Max, Unique Count, Median, Percentiles, and others). | +| **Buckets > X-axis** | Groups bars along the horizontal axis. Use **Terms** for categorical data, **Date Histogram** for time-based data, or **Histogram** for numeric ranges. | +| **Buckets > Split series** | Splits each bar into grouped or stacked sub-bars by the values of a field. | +| **Buckets > Split chart** | Creates separate chart panels (small multiples) for each bucket value. | + +### Metrics & axes tab + +| Setting | Description | +| :--- | :--- | +| **Chart type** | Override per series. Supports **Line**, **Area**, **Bar**. | +| **Mode** | **Stacked** layers bars on top of each other. **Normal** groups bars side by side. | +| **Y-axis position** | **Left** or **Right**. | +| **Y-axis scale** | **Linear**, **Log**, or **Square root**. | + +### Panel settings tab + +| Setting | Description | +| :--- | :--- | +| **Legend position** | **Top**, **Left**, **Right**, **Bottom**. | +| **Show tooltip** | Displays values on hover. | +| **Order buckets by sum** | Orders split series by total value. | +| **Show threshold line** | Draws a horizontal reference line at a specified value. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/configuring-maps.md b/_dashboards/visualize/visualize-app/configuring-maps.md new file mode 100644 index 00000000..76ab22d0 --- /dev/null +++ b/_dashboards/visualize/visualize-app/configuring-maps.md @@ -0,0 +1,18 @@ +--- +layout: default +title: Configuring maps +parent: Creating visualizations in the Visualize application +grand_parent: Building data visualizations +has_children: true +has_toc: false +nav_order: 210 +--- + +# Configuring maps + +You can configure map tile servers used by [coordinate maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/coordinate-maps/) and the [Maps application]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/). These settings do not apply to [region maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/region-maps/), which use vector boundaries (GeoJSON files) rather than raster tiles. + +## Related documentation + +- [Configuring a Web Map Service (WMS)]({{site.url}}{{site.baseurl}}/dashboards/visualize/maptiles/) -- Configure a WMS tile server for custom basemaps. +- [Using self-hosted map servers]({{site.url}}{{site.baseurl}}/dashboards/visualize/selfhost-maps-server/) -- Host map tiles locally for air-gapped environments. diff --git a/_dashboards/visualize/visualize-app/configuring-viz.md b/_dashboards/visualize/visualize-app/configuring-viz.md new file mode 100644 index 00000000..8f403316 --- /dev/null +++ b/_dashboards/visualize/visualize-app/configuring-viz.md @@ -0,0 +1,177 @@ +--- +layout: default +title: Configuring visualizations +parent: Creating visualizations in the Visualize application +grand_parent: Building data visualizations +nav_order: 200 +redirect_from: + - /dashboards/visualize/viz-tool-ref/ +--- + +# Configuring visualizations + +The configuration panel is on the right side of the **Visualize** application. It contains two or more tabs depending on the type of visualization being edited. For terminology definitions, see [Concepts]({{site.url}}{{site.baseurl}}/dashboards/getting-started/concepts/). + +The configuration panel contains the following tabs: + +- The **Data** tab enables the addition of metrics and data buckets to the visualization. +- The **Metrics and axes** tab controls display options such as how to display axes, labels, and scales; text display and alignment, and visualization-specific options. This tab is labeled **Options** for some visualization types. +- The **Panel settings** tab contains options for panel-wide settings such as the legend, tooltips, and grid lines. + +## Data tab + +The **Data** tab uses [aggregations]({{site.url}}{{site.baseurl}}/aggregations/) to determine what data is displayed and how it is grouped. When you configure a visualization, OpenSearch Dashboards automatically generates aggregation queries based on your selections. For a hands-on walkthrough, see [Creating aggregation-based visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/aggregation-based-viz/). + +The following visualization types use the **Data** tab with aggregations: **Area**, **Horizontal Bar**, **Vertical Bar**, **Coordinate Map**, **Data Table**, **Gauge**, **Goal**, **Heat Map**, **Line**, **Metric**, **Pie**, **Region Map**, and **Tag Cloud**. +{: .note} + +A typical **Data** tab is shown in the following image. + +![Visualization tools Data settings]({{site.url}}{{site.baseurl}}/images/dashboards/viz-tools-data.png){: width="600" } + +The **Data** tab generally contains two types of panels for adding elements to the visualization: + +- **Y-axis**, **Data** or **Metrics** panels for choosing the field or fields to be displayed +- **X-axis** or **Buckets** panels for choosing how to segment the data for display + +**Metrics** and **Buckets** panels both use _progressive disclosure_, meaning that subsequent options available to you are based on your last choice in the panel. A typical sequence for choosing a metric or bucket is as follows: + +1. You select an aggregation type, such as average, count, max, or min, from a dropdown list of available choices. + +1. You select a field from a dropdown list. The field selection is limited to data types to which your selected aggregation can be applied. For example, the **Count** aggregation applies to documents as a whole, so no field selection is presented. The **Date Histogram** aggregation applies only to timestamp fields. + +1. You optionally select other options such as range intervals or a custom name to label the field in the visualization. + +1. You optionally add more fields or buckets. For example, after choosing an _X-axis_ bucket type of histogram to display a cost variable across product category in a bar chart, you might add a _split chart_ bucket to display a separate bar chart for each customer gender. + +### Metric aggregations + +Metric aggregations appear in the **Metrics** panel and become Y-axis values in charts. The following table lists the available metric aggregations. + +| Metric | Description | Requires field | +| :--- | :--- | :--- | +| `Count` | Counts the number of documents in each bucket. This is the default metric for new visualizations and does not require a field selection. In the aggregation API, every [bucket aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/) response includes a `doc_count` field, which contains the number of documents that are in that bucket---and `Count` displays this value. | No | +| [`Average`]({{site.url}}{{site.baseurl}}/aggregations/metric/average/) | Calculates the average value of a numeric field. | Yes | +| [`Max`]({{site.url}}{{site.baseurl}}/aggregations/metric/maximum/) | Returns the maximum value of a numeric field. | Yes | +| [`Median`]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile/) | Returns the 50th percentile value of a numeric field. In the aggregation API, this uses the `percentiles` aggregation at the 50th rank. | Yes | +| [`Min`]({{site.url}}{{site.baseurl}}/aggregations/metric/minimum/) | Returns the minimum value of a numeric field. | Yes | +| [`Percentile Ranks`]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile-ranks/) | Returns the percentile rank of specified values within a numeric field. After selecting, enter threshold values in the **Values** list to define the points at which to calculate ranks. | Yes | +| [`Percentiles`]({{site.url}}{{site.baseurl}}/aggregations/metric/percentile/) | Returns values at specified percentile ranks of a numeric field. After selecting, configure the **Percents** list to define which percentiles to calculate. The defaults are 1, 5, 25, 50, 75, 95, and 99. Each percentile appears as a separate series in the visualization. | Yes | +| [`Standard Deviation`]({{site.url}}{{site.baseurl}}/aggregations/metric/extended-stats/) | Calculates the standard deviation of a numeric field. In the aggregation API, this uses the `extended_stats` aggregation. | Yes | +| [`Sum`]({{site.url}}{{site.baseurl}}/aggregations/metric/sum/) | Calculates the total sum of a numeric field. | Yes | +| [`Top Hit`]({{site.url}}{{site.baseurl}}/aggregations/metric/top-hits/) | Returns one or more of the top values from a field, sorted by a specified metric. After selecting, configure **Aggregate with** (how to combine multiple values: `Concat`, `Min`, `Max`, `Sum`, or Average), **Size** (number of top values to return), **Sort on** (field to sort by), and **Order** (ascending or descending). | Yes | +| [`Unique Count`]({{site.url}}{{site.baseurl}}/aggregations/metric/cardinality/) | Counts the number of distinct values in a field. In the aggregation API, this corresponds to the `cardinality` aggregation. | Yes | + +### Parent pipeline aggregations + +Parent pipeline aggregations compute values based on the output of another metric within the same bucket. They appear in the **Metrics** panel below the basic metric aggregations. + +After selecting a parent pipeline aggregation, use the **Metric** dropdown to choose which metric to operate on. Select an existing metric from the Y-axis, or select **Custom metric** to define a new metric inline (this reveals a nested aggregation selector where you can configure any of the basic metric aggregations). + +| Metric | Description | +| :--- | :--- | +| [`Cumulative Sum`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/cumulative-sum/) | Calculates the cumulative sum of a metric across ordered buckets. | +| [`Derivative`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/derivative/) | Calculates the rate of change of a metric between consecutive buckets. | +| [`Moving Avg`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/moving-avg/) | Calculates a moving average of a metric over a sliding window of buckets. | +| [`Serial Diff`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/serial-diff/) | Calculates the difference between a metric value and an earlier value in the series. | + +### Sibling pipeline aggregations + +Sibling pipeline aggregations compute a single value from all buckets in a sibling aggregation and display it alongside the other metrics. They appear in the **Metrics** panel below the parent pipeline aggregations. + +Like parent pipeline aggregations, sibling pipeline aggregations use the **Metric** dropdown to select which metric to operate on. Select an existing metric or **Custom metric** to define one inline. + +| Metric | Description | +| :--- | :--- | +| [`Average Bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/avg-bucket/) | Calculates the average of a metric across all buckets. | +| [`Max Bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/max-bucket/) | Returns the maximum value of a metric across all buckets. | +| [`Min Bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/min-bucket/) | Returns the minimum value of a metric across all buckets. | +| [`Sum Bucket`]({{site.url}}{{site.baseurl}}/aggregations/pipeline/sum-bucket/) | Calculates the sum of a metric across all buckets. | + +### Bucket aggregations + +Bucket aggregations appear in the **Buckets** panel and determine how data is grouped. When you select **Add** in the **Buckets** panel, you first choose a bucket type: + +| Bucket type | Description | +| :--- | :--- | +| X-axis | Groups data along the horizontal axis of the chart. | +| Split series | Creates multiple series (lines, bars, or areas) within the same chart, each representing a different group. | +| Split chart | Creates separate charts for each group, displayed in a row or column layout. | + +After you choose a bucket type, you select a bucket aggregation to define how the data is grouped. The following table lists the available bucket aggregations. + +| Aggregation | Description | +| :--- | :--- | +| [`Date Histogram`]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-histogram/) | Groups documents into time intervals (for example, hourly, daily, or weekly). Requires a date field. | +| [`Date Range`]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-range/) | Groups documents into custom date ranges that you define. Requires a date field. | +| [`Filters`]({{site.url}}{{site.baseurl}}/aggregations/bucket/filters/) | Groups documents by custom query filters that you define. Each filter creates a bucket. | +| [`Histogram`]({{site.url}}{{site.baseurl}}/aggregations/bucket/histogram/) | Groups numeric values into fixed-size intervals. Requires a numeric field. | +| [`IPv4 Range`]({{site.url}}{{site.baseurl}}/aggregations/bucket/ip-range/) | Groups documents into custom IP address ranges. Requires an IP field. | +| [`Range`]({{site.url}}{{site.baseurl}}/aggregations/bucket/range/) | Groups numeric values into custom ranges that you define. Requires a numeric field. | +| [`Significant Terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/significant-terms/) | Identifies terms that appear more frequently in the selected dataset than in the overall index. Requires a keyword or text field. | +| [`Terms`]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/) | Groups documents by the unique values of a field. Requires a keyword, numeric, IP, or Boolean field. | + +For more information about bucket aggregation types, see [Bucket aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/). + + +## Metrics and axes tab + +A typical **Metrics** tab is shown in the following image. + +![Visualization tools Metrics and axes settings]({{site.url}}{{site.baseurl}}/images/dashboards/viz-tools-metrics.png){: width="600" } + +Like the **Data** tab, contents of the **Metrics and axes** (or **Options**) tab depend on the visualization type as well as the specifics of the data that you've selected. Options vary widely, but generally fall into the following categories. This is not an exhaustive list: + + +### Metrics options + +Metrics or display options include: + +- The form factor of the graphic, such as Circle or Arc for gauges; or Line/Bar/Area chart types +- Visualization-specific options, such as Stacked or Normal (superimposed) area charts +- Whether to display lines and dots in line graphs, line width, and line style (such as straight or smoothed) +- Range widths +- Color schemas (for heat maps, for example) + + +### Axis options + +X- and Y-axis options include: + +- Position of the axes +- Mode, such as normal or percentage scale +- Whether to display or truncate labels and their alignment +- Custom titles for axes +- Whether to display axis lines and tick marks + + +## Panel settings + +A typical **Panel settings** tab is shown in the following image. + +![Visualization tools Panel settings]({{site.url}}{{site.baseurl}}/images/dashboards/viz-tools-panel.png){: width="600" } + +The **Panel settings** tab controls panel-wide display options such as the following: + +- Change the position of the legend +- Show a threshold line +- Highlight the current time on a timeline +- Show or hide vertical or horizontal grid lines +- Label values on charts + + +## Legend colors + +The legend shows the color key in charts where range, categorical, or text variables are represented by colors. + +Use the legend to change the colors of a graphical element. To change a color, follow these steps: + +1. Select an entry in the legend. + +2. Choose a color from the palette that appears. + +![Visualize legend]({{site.url}}{{site.baseurl}}/images/dashboards/legend-colors.png){: width="300" } + +## Next steps + +- For a hands-on tutorial, see [Creating aggregation-based visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/aggregation-based-viz/). \ No newline at end of file diff --git a/_dashboards/visualize/visualize-app/controls.md b/_dashboards/visualize/visualize-app/controls.md new file mode 100644 index 00000000..3d8b8666 --- /dev/null +++ b/_dashboards/visualize/visualize-app/controls.md @@ -0,0 +1,74 @@ +--- +layout: default +title: Controls +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 50 +redirect_from: + - /dashboards/visualize/controls/ +--- + +# Controls visualization +**Experimental** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +A controls visualization adds interactive filter panels to a dashboard. Controls let you filter data without modifying the dashboard itself. + +Controls do not require a data source. You configure the data source within each individual control. + +## When to use controls + +Use controls to filter data within a dashboard. Many visualizations have data selection filtering built in. Use controls with visualizations that don't already offer data selection or to enhance the data selection capability of an existing visualization. + +## Control types + +Two types of controls are available: + +- **Range slider**: Defines minimum and maximum values for a numeric field. +- **Options list**: Provides a dropdown to select values from a field. + +## Creating a controls visualization + +To create a controls visualization, follow these steps: + +1. In the **New Visualization** dialog, select **Controls**. +2. Select the **Controls** tab. +3. From the **Type** dropdown, select **Range slider** or **Options list**. +4. Select **Add**. + +The following image shows a controls visualization with two Options list controls (Origin City and Destination City) and one Range slider control (Average Ticket Price). + +![Controls visualization with dropdown and range slider]({{site.url}}{{site.baseurl}}/images/dashboards/controls-example.png) + +### Configuring a range slider + +1. In **Control Label**, enter the label that appears on the control. +2. From **Index Pattern**, select the data source. +3. From **Field**, select a numeric field. +4. (Optional) Set a **Step Size** (minimum increment) and **Decimal Places**. +5. Select **Update**. + +### Configuring an options list + +1. In **Control Label**, enter the label that appears on the control. +2. From **Index Pattern**, select the data source. +3. From **Field**, select the field to filter by. +4. (Optional) Enable **Multi-select** to allow selecting multiple values. +5. (Optional) Enable **Dynamic Options** to automatically scale the dropdown items (text fields only). +6. If **Dynamic Options** is disabled, set the **Size** (number of items shown). + + The control displays only the top **Size** values, as determined by the data field's sorting method. + {: .note} + +7. Select **Update**. + +You can add multiple controls to a single visualization by repeating the steps. + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/coordinate-maps.md b/_dashboards/visualize/visualize-app/coordinate-maps.md new file mode 100644 index 00000000..48372003 --- /dev/null +++ b/_dashboards/visualize/visualize-app/coordinate-maps.md @@ -0,0 +1,64 @@ +--- +layout: default +title: Coordinate map +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 55 +redirect_from: + - /dashboards/visualize/coordinate-maps/ +--- + +# Coordinate map + +A coordinate map plots geographic data points on a map using latitude and longitude coordinates. Each marker represents a document with a geo_point field, and marker size indicates the aggregated value at that location. + +## When to use coordinate maps + +Use coordinate maps to reveal distribution patterns and spatial correlations over locations, such as customer locations, service coverage areas, incident distributions, or events with geographic coordinates. You can select geographic regions to filter other visualizations on the same dashboard. For multi-layer geographic visualizations, use the [Maps application]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/). + +## Creating a coordinate map + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a coordinate map, follow these steps: + +1. In the **New Visualization** dialog, select **Coordinate Map**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). +2. Set the time filter to **Last 7 days**. +3. Under **Buckets**, select **Add** > **Geo coordinates**. +4. Set **Aggregation** to **Geohash** and **Field** to **OriginLocation**. +5. Select **Update**. + +The map displays markers at flight origin locations, with marker size proportional to the document count at each location, as shown in the following image. + +![Coordinate map showing flight origins]({{site.url}}{{site.baseurl}}/images/dashboards/coordinate-map-example.png) + +### Customizing the map display + +1. Select the **Options** tab. +2. Under **Map type**, select a marker style: **Scaled Circle Markers**, **Shaded Circle Markers**, **Shaded Geohash Grid**, or **Heatmap**. +3. Adjust **Precision** to control the geohash bucket size (higher precision = smaller, more numerous buckets). +4. Select **Update**. + +## Configuring a coordinate map + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Map type** | The marker style. Supported values: **Scaled Circle Markers** (sized by value), **Shaded Circle Markers** (colored by value), **Shaded Geohash Grid** (rectangular cells colored by value), **Heatmap** (continuous color gradient). | +| **Precision** | Controls the geohash grid resolution. Higher values produce smaller, more numerous buckets. | +| **Show tooltips** | When enabled, displays aggregation values on hover. | +| **WMS compliant map server** | When enabled, uses a WMS server for the basemap. For more information, see [Configuring a Web Map Service]({{site.url}}{{site.baseurl}}/dashboards/visualize/maptiles/). | + +## Related documentation + +- [Configuring maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-maps/) + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/data-table.md b/_dashboards/visualize/visualize-app/data-table.md new file mode 100644 index 00000000..be96dfd1 --- /dev/null +++ b/_dashboards/visualize/visualize-app/data-table.md @@ -0,0 +1,117 @@ +--- +layout: default +title: Data table +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 60 +redirect_from: + - /dashboards/visualize/data-table/ +--- + +# Data table + +A data table displays selected fields in row-column form. You can display one or more metrics as columns, bucketed into rows, and subdivide bucket data into separate tables. + +## When to use data tables + +Use data tables to examine individual documents, verify data quality, or investigate details behind aggregate visualizations. You can sort, filter, and examine correlations between fields that might not be apparent in more abstract visualizations. Use data tables as drill-down targets to move from high-level visual summaries to specific record-level details. + +## Creating a data table + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a data table, follow these steps: + +1. In the **New Visualization** dialog, select **Data Table**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). + + By default, the visualization selects `Count` as the only metric to display. Since the data is not bucketed, it displays the total document count. + + For this dataset the count is `13,059` if none of the data has been filtered out. If your visualization displays a different value, make sure that your time filter window is large enough to encompass all the sample flight data. See [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/). + {: .note} + +2. In the **Metrics** panel, expand **Metric Count**. +3. Set **Aggregation** to **Average** and **Field** to **FlightDelayMin**. +4. (Optional) Enter a **Custom label**, for example `Flight delay in minutes`. +5. Select **Update**. + + The table displays a single value for all the data, `47.335`. This is the average flight delay for every document in the flight database, including zero-minute delays. + +6. In the **Buckets** panel, select **Add** > **Split rows**. +7. Set **Aggregation** to **Terms** and **Field** to **FlightDelay**. +8. Select **Update**. + + The table shows that non-delayed flights averaged zero minutes of delay time. The nonzero flight delay bucket is considerably higher than the overall value because the zero delays are no longer part of that average. + {: .note} + +9. Change the row buckets by choosing **Range** from the **Aggregation** dropdown and **DistanceMiles** from the **Field** dropdown. +10. Configure the following ranges (select **Add range** for the third row): + + | From | To | + | :--- | :--- | + | 0 | 4000 | + | 4000 | 8000 | + | 8000 | Infinity | + +11. In the **Metrics** panel, select **Add** > **Metric** and set **Aggregation** to **Count**. + + Select **Add** in the **Metrics** panel, not the **Buckets** panel. + {: .tip} + +12. Select **Update**. + + The table shows the average flight delay and count for each distance range, as shown in the following image. + + ![Data table showing flight delay by distance range]({{site.url}}{{site.baseurl}}/images/dashboards/example-table-flightdelay.png) + +## Displaying multiple columns + +A data table always includes at least one metric. When the **Metrics** panel contains a single metric, the panel provides no option to remove or disable it, so an aggregation-based data table cannot be built without a metric column. To display several columns, add a bucket or a **Top Hit** metric for each field. + +### Adding a column for each field you group by + +Each **Split rows** bucket adds a column to the table. + +This example starts from a new data table that uses the default **Count** metric. If you continue from the previous procedure, the table retains the **DistanceMiles** bucket and both metrics, so it displays additional columns. +{: .note} + +To group flights by carrier and destination country, follow these steps: + +1. In the **Buckets** panel, select **Add** > **Split rows**. +1. Set **Aggregation** to **Terms** and **Field** to **Carrier**. +1. Select **Add** > **Split rows** a second time. +1. Set **Aggregation** to **Terms** and **Field** to **DestCountry**. +1. Select **Update**. + +The table displays three columns: **Carrier: Descending**, **DestCountry: Descending**, and the metric column. A bucket column is labeled with the field name and the sort order of the bucket. The buckets are nested, so each row pairs one carrier with one of the destination countries that appears in its documents. + +### Adding a column of field values + +The **Top Hit** metric returns a value taken directly from a document, and in a data table it accepts string fields as well as numeric ones. Each **Top Hit** metric becomes a column of field values. To add the destination city of each group's most recent flight, follow these steps: + +1. In the **Metrics** panel, select **Add** > **Metric**. +1. From the **Aggregation** dropdown list, select **Top Hit**. +1. From the **Field** dropdown list, select **DestCityName**. +1. Verify that **Size** is set to `1`, **Sort on** is set to **timestamp**, and **Order** is set to **Descending**. +1. Select **Update**. + +The table now displays four columns: **Carrier: Descending**, **DestCountry: Descending**, **Count**, and **Last DestCityName**. Each row reports how many flights the carrier operated to that country and the city where its most recent flight landed, such as `Rome` or `San Antonio`. To add a column for each additional field, repeat these steps and select a different field. + +**Top Hit** returns values from the documents in each row's bucket, so the table still groups documents. Raising **Size** returns that many values in one cell, but the documents in a bucket often repeat the same value, so the cell lists one city many times. To give each document its own row, see [Listing individual documents](#listing-individual-documents). +{: .note} + +## Listing individual documents + +To build a table in which each row is a single document and each column is a field, save a search in the **Discover** application instead of creating a data table. Discover returns documents without aggregating them, and a saved search can be added to a dashboard in the same **Add panels** dialog as a visualization. + +To choose which fields appear as columns, see [Using the field select tool]({{site.url}}{{site.baseurl}}/dashboards/discover/field-select/). To place the saved search on a dashboard, see [Adding a visualization to a dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/adding-a-viz/#adding-a-panel-to-a-dashboard). + +## Configuring a data table + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/gauge.md b/_dashboards/visualize/visualize-app/gauge.md new file mode 100644 index 00000000..ad692f76 --- /dev/null +++ b/_dashboards/visualize/visualize-app/gauge.md @@ -0,0 +1,80 @@ +--- +layout: default +title: Gauge visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 70 +redirect_from: + - /dashboards/visualize/gauge/ +--- + +# Gauge visualization + +A gauge visualization displays a data field in a simulated analog instrument like a speedometer. The gauge value can be instantly compared with marked ranges or thresholds. The visualization can show a single value or multiple bucketed values. + +## When to use gauge visualizations + +Use gauge visualizations to monitor a key indicator against an acceptable range in a dashboard. + +## Creating a gauge visualization + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a gauge visualization, follow these steps: + +1. In the **New Visualization** dialog, select **Gauge**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). + + The visualization displays a gauge showing a count of the documents in the index pattern. For the `opensearch_dashboards_sample_data_flights` data, this is `13059` if the date range contains all the documents. + {: .note} + +2. Under **Metrics**, expand **Metric count**. +3. Set **Aggregation** to **Median** and **Field** to **FlightTimeMin**. +4. Select **Update**. + + The gauge displays `502.775`, presented as the full range of gauge. + + If your visualization displays a different value, make sure that your [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) window is large enough to encompass all the sample flight data. + {: .note} + +5. Now that you have some idea of the magnitude of the data, change the display range so that the displayed value falls within it. + + 1. Select the **Options** tab. + 2. In the **Ranges** panel, edit the three default ranges as follows: + + | From | To | + | :--- | :--- | + | 0 | 250 | + | 250 | 500 | + | 500 | 750 | + + 3. Select **Update**. + +6. To compare two different conditions in one visualization, bucket the data. + + 1. Under **Buckets**, select **Add** > **Split group**. + 2. Set **Aggregation** to **Terms** and **Field** to **FlightDelay**. + 3. Select **Update**. + + The visualization displays two gauges, with median flight times for delayed and non-delayed flights, as shown in the following image. + + ![Gauge showing median flight time split by delay status]({{site.url}}{{site.baseurl}}/images/dashboards/example-gauge-flight-time.png) + +## Configuring a gauge visualization + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Ranges** | Defines the color-coded segments of the gauge arc. Each range has a start and end value. | +| **Percentage mode** | When enabled, displays the value as a percentage of the maximum range value. | +| **Show scale** | When enabled, displays tick marks on the gauge. | +| **Color options** | Controls the colors assigned to each range segment. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/goal.md b/_dashboards/visualize/visualize-app/goal.md new file mode 100644 index 00000000..212c77b7 --- /dev/null +++ b/_dashboards/visualize/visualize-app/goal.md @@ -0,0 +1,67 @@ +--- +layout: default +title: Goal visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 80 +redirect_from: + - /dashboards/visualize/goal/ +--- + +# Goal visualization + +A goal visualization displays a value in a speedometer-like gauge. It shows the value as a proportion of a predefined goal. The visualization also displays the metric, either as an absolute value or as a percentage of the goal. The visualization can show a single value or multiple bucketed values. If bucketed, the goal is the same for all buckets. + +## When to use goal visualizations + +Use goal visualizations to monitor a key indicator against a goal value. + +## Creating a goal visualization + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a goal visualization, follow these steps: + +1. In the **New Visualization** dialog, select **Goal**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). + + The visualization displays a gauge showing the document count as a percentage of a default goal of `10,000`. For the `opensearch_dashboards_sample_data_flights` data, this is `130.59%` if the date range contains all the documents. + {: .note} + +2. Under **Metrics**, expand **Metric count**. +3. Set **Aggregation** to **Sum** and **Field** to **DistanceKilometers**. +4. To see how close the dataset is to recording a total of a hundred million kilometers, set 100,000,000 as the goal: + + 1. Select the **Options** tab. + 2. In the **Ranges** boxes, enter `1e8` as the top of the range. + + Numerical entries cannot take group separators. Use exponential notation for large numbers. + {: .note} + + 3. Deselect **Percentage mode**. + 4. Select **Update**. + + The visualization displays `92,616,288.34`, the sum of all flight distances in kilometers. This value shows as about 93% of the gauge maximum, which is calibrated to the goal, as shown in the following image. + + ![Goal showing total flight distance toward 100M km target]({{site.url}}{{site.baseurl}}/images/dashboards/example-goal-total-km.png) + +5. (Optional) Combine gauge and goal displays by adding a scale as described in [Gauge visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/gauge/). + +## Configuring a goal visualization + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Ranges** | Defines the target range. The maximum value represents the goal. | +| **Percentage mode** | When enabled, displays the value as a percentage of the goal. | +| **Show scale** | When enabled, displays tick marks on the progress bar. | +| **Color options** | Controls the colors assigned to each range segment. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/heat-map.md b/_dashboards/visualize/visualize-app/heat-map.md new file mode 100644 index 00000000..d7a85f43 --- /dev/null +++ b/_dashboards/visualize/visualize-app/heat-map.md @@ -0,0 +1,88 @@ +--- +layout: default +title: Heat map +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 90 +redirect_from: + - /dashboards/visualize/heat-map/ +--- + +# Heat map + +A heat map displays values represented as a color or saturation gradient on a two-dimensional grid, effectively rendering a three-dimensional data display. The X and Y dimensions can be the same, as in a spatial heat map, or different---for example, months against years in a record of average temperature at a location (thus separating the cyclic and trend data for the site). + +## When to use heat maps + +Use heat maps to reveal clusters, correlation strengths, and anomalies within multidimensional datasets. They make patterns visible that would be difficult to see in tabular format or in multiple two-dimensional plots. + +## Creating a heat map + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a heat map, follow these steps: + +1. In the **New Visualization** dialog, select **Heat Map**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). +2. Under **Metrics**, expand **Value Count** and set **Aggregation** to **Count**. +3. Under **Buckets**, select **Add** > **X-axis**. +4. Set **Aggregation** to **Terms**, **Field** to **OriginWeather**, and **Size** to `8`. +5. Select **Update**. +6. Under **Buckets**, select **Add** > **Y-axis**. +7. Set **Sub aggregation** to **Terms**, **Field** to **DestWeather**, and **Size** to `8`. +8. Select **Update**. + +### Customizing the display + +1. Select the **Options** tab. +2. In **Heatmap settings**, set **Color schema** to **Greys** and **Number of colors** to `8`. +3. In **Labels**, enable **Show labels**. +4. Select **Update**. + + The heat map shows average flight delay mapped to origin and destination weather combinations, as shown in the following image. + + ![Heat map showing flight delay by weather conditions]({{site.url}}{{site.baseurl}}/images/dashboards/example-heatmap-flight-delay.png) + + Note the following: + - The heat map data is organized into four quadrants, corresponding to the four combinations of "good" (Cloudy, Rain, Clear, Sunny) and "bad" (Hail, Heavy Fog, Damaging Wind, Thunder & Lightning) weather conditions at the destination and origin. + - The longest delays occurred when the weather was good at both the origin and destination. The shortest delays occurred when the weather was bad at both locations. + +### Filtering with split chart + +You can filter the data using the [filter tool]({{site.url}}{{site.baseurl}}/dashboards/discover/filter-tool/), but if the visualization is in a dashboard this filters the data for other visualizations as well. The following procedure limits the data only for this visualization. +{: .note} + +To limit the heat map to specific conditions (for example, only cancelled flights): + +1. Under **Buckets**, select **Add** > **Split chart** > **Rows**. +2. Set **Sub aggregation** to **Filters**. +3. In the **Filter 1** box, enter `Cancelled: true`. + + The filter terms are case-sensitive. + {: .tip} + +4. Select **Update**. + + The heat map now shows only cancelled flights. It shows that no cancellations occurred when the weather was good at both ends of the flight, as shown in the following image. + + ![Heat map showing cancelled flights by weather conditions]({{site.url}}{{site.baseurl}}/images/dashboards/example-heatmap-cancellation.png) + +## Configuring a heat map + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Color schema** | The color palette for the heat map (for example, **Greens**, **Blues**, **Greys**, **Yellow to Orange**). | +| **Reverse schema** | Inverts the color mapping. | +| **Number of colors** | The number of discrete color bins. | +| **Show labels** | Displays values inside each cell. | +| **Percentage mode** | Normalizes values between 0 and 1. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/index.md b/_dashboards/visualize/visualize-app/index.md new file mode 100644 index 00000000..3a435a9f --- /dev/null +++ b/_dashboards/visualize/visualize-app/index.md @@ -0,0 +1,150 @@ +--- +layout: default +title: Creating visualizations in the Visualize application +nav_order: 40 +parent: Building data visualizations +grand_parent: OpenSearch Dashboards +has_children: true +has_toc: false +redirect_from: + - /dashboards/visualize/visualize-app/ + - /dashboards/visualize/viz-index/ +--- + +# Creating visualizations in the Visualize application + +The **Visualize** application uses a point-and-click interface to create data visualizations from aggregations. You select a visualization type, configure metrics and buckets, and adjust display settings to build charts, tables, maps, and other visual representations of your data. + +If you're new to the Visualize application, see [Explore the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-visualize/) for a hands-on introduction using sample data. +{: .tip} + +## Prerequisites + +The examples on this page use the [**Sample flight data**](https://playground.opensearch.org/app/home#/tutorial_directory) dataset that is already installed in [OpenSearch Playground](https://playground.opensearch.org/app/home#/). + +If you've installed a local OpenSearch Dashboards instance, add the sample data by following these steps: + +1. On the OpenSearch Dashboards home page, select **Add sample data**. +2. In the **Sample flight data** panel, select **Add data**. + +For more information, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +To use your own data, you need an index pattern. See [Setting up your data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/). + +## Navigating the Visualize application UI + +The following image shows the main components of the **Visualize** application. + +![Visualize application interface]({{site.url}}{{site.baseurl}}/images/dashboards/viz-app-panel-callouts.png) + +- The _search bar_ (A) enables selection of data using a query language search. See [Using the search bar]({{site.url}}{{site.baseurl}}/dashboards/discover/search-bar/). +- The _time filter_ (B) provides a graphical interface for selecting data values and ranges. See [Using the time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/). +- The _filter tool_ (C) contains frequently used commands and shortcuts. See [Using the filter tool]({{site.url}}{{site.baseurl}}/dashboards/discover/filter-tool/). +- The _visualization panel_ (D) displays the visualization. +- The _configuration panel_ (E) contains all the controls to select and configure the visualization. Its contents depend on the visualization type. See [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +## Creating a visualization + +To create a visualization, follow these steps: + +1. In the left navigation menu, select **OpenSearch Dashboards** > **Visualize**. + + The application displays the **Visualizations** list, a table of saved visualizations. + +1. In the upper-right corner, select **Create visualization**. + + The application displays the **New Visualization** dialog, as shown in the following image. + + ![New visualization dialog]({{site.url}}{{site.baseurl}}/images/dashboards/new-viz-dialog.png){: width=500 } + +1. Select a visualization type by choosing its icon. For help choosing a type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). + +1. If prompted, select an index pattern in the **Choose a source** dialog. Not all visualization types display this dialog. For examples of creating each visualization type, see the individual visualization type pages. + + The default visualization shows a single value, the document count, for the current dataset. + + If the visualization shows no data, or a count different than expected, verify that the [search bar]({{site.url}}{{site.baseurl}}/dashboards/discover/search-bar/), [filter tool]({{site.url}}{{site.baseurl}}/dashboards/discover/filter-tool/), and especially the [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) are not filtering out the missing documents. + {: .tip} + +1. Configure the visualization. For more information, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/) or the individual visualization type pages. For a complete example, see [Explore the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-visualize/). + +## Other ways to start creating a visualization + +In addition to the **Visualize** application, you can start creating a new visualization from the following locations: + +- To create a visualization from a [workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/) (if workspaces are enabled), follow these steps: + + 1. On the home page, select or create a [workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/). + 1. In the left navigation menu, expand **Visualize and report** and select **Visualizations**. + 1. Select **Create new visualization**. + +- To create a visualization from a dashboard, follow these steps: + + 1. In the left navigation menu, select **OpenSearch Dashboards** > **Dashboards**. + 1. Open an existing dashboard or create a new one. + 1. Select **Edit**. + 1. Select **Create new** in the toolbar, or select **Add** (or the plus icon) and then select **Create new** in the **Add panels** dialog. + + When you create a visualization from a dashboard, it is automatically added to that dashboard when you save. + {: .note} + +## Saving a visualization + +Your visualization remains in the **Visualize** application if you leave the application. However, if you select the **Visualize** application again without saving the visualization, changes to the visualization are lost. We recommend always saving your visualization before you leave the **Visualize** application. +{: .warning} + +### Saving a new visualization + +To save a new visualization, follow these steps: + +1. Select **Save** in the upper right of the **Create** panel. + + The application displays the **Save visualization** dialog. + +1. Enter a title for the visualization in the **Title** box. + +1. (Optional) Enter a **Description**. + +1. Select **Save**. + +### Saving an existing visualization + +You can save a visualization at any time, as often as you like. + +To save an existing visualization, follow these steps: + +1. Select **Save** in the upper right of the **Create** panel. + + If you have previously saved the visualization, the **Save visualization** **Title** box contains the visualization title. + +1. (Optional) To change the visualization name, enter a new title for the visualization in the **Title** box. + +1. (Optional) Update the **Description**. + +1. (Optional) To leave the saved visualization in its current state and save the changes as a new visualization, select **Save as new visualization**. + + Saving an existing visualization without selecting **Save as new visualization** overwrites the previous state of the visualization, even if you've renamed the visualization. + {: .warning} + +1. To save the current changes, select the **Save** button. + +## Adding a visualization to a dashboard + +To add a saved visualization to a dashboard, follow these steps: + +1. Open a [dashboard]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). +1. Select **Edit**. +1. Select **Add** or the plus icon in the toolbar. If prompted, select **From library**. +1. Select the saved visualization from the list. + +The visualization appears as a panel on the dashboard. You can resize, reposition, and configure it alongside other panels. + +## Try it + +For a hands-on walkthrough of creating a line chart with sample data, see [Explore the Visualize application]({{site.url}}{{site.baseurl}}/dashboards/getting-started/explore-visualize/). + +## Next steps + +- To learn how to create various visualizations using sample data, see [Creating aggregation-based visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/aggregation-based-viz/). +- For help choosing a visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To learn about adding visualizations to dashboards, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/line-charts.md b/_dashboards/visualize/visualize-app/line-charts.md new file mode 100644 index 00000000..22683cd2 --- /dev/null +++ b/_dashboards/visualize/visualize-app/line-charts.md @@ -0,0 +1,70 @@ +--- +layout: default +title: Line chart +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 100 +redirect_from: + - /dashboards/visualize/line-charts/ +--- + +# Line chart + +A line chart shows one or more series of numerical data points on the Y-axis plotted against a numerical field on the X-axis. The points can be connected by a line. The X-axis value can be a timeline or any other continuous or discrete number series. + +## When to use line charts + +Use line charts to reveal trends, cyclical behaviors, rate-of-change information, and inflection points across time or any continuous numerical quantity. Use multiple lines to show correlation between metrics. + +## Creating a line chart + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a line chart, follow these steps: + +1. In the **New Visualization** dialog, select **Line**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). +2. Under **Metrics**, expand **Y-axis Count**. +3. Set **Aggregation** to **Average** and **Field** to **AvgTicketPrice**. +4. (Optional) Enter a **Custom label**, for example `Average Ticket Price`. +5. Select **Update**. + + The chart displays a single bar with height of a little over `$600`, the average ticket price for every document in the flight database. + + If your visualization displays a different value, make sure that your time filter window is large enough to encompass all the sample flight data. + {: .note} + +6. Under **Buckets**, select **Add** > **X-axis**. +7. Set **Aggregation** to **Histogram** and **Field** to **DistanceKilometers**. +8. Select **Update**. + + The chart shows average ticket price as a function of bucketed flight distance. + +### Adding a split series + +1. Under **Buckets**, select **Add** > **Split series**. +2. Set **Sub aggregation** to **Terms**, **Field** to **dayOfWeek**, **Order by** to **Alphabetical**, and **Size** to `7`. +3. Select **Update**. + + The average ticket price is displayed per weekday value in seven different lines, as shown in the following image. The average ticket price for weekday value keys 5 and 6 are significantly higher across most flight distances. + + ![Line chart showing average ticket price compared to distance by day of week]({{site.url}}{{site.baseurl}}/images/dashboards/example-line-cost-vs-distance.png) + +## Configuring a line chart + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Metrics & axes tab + +| Setting | Description | +| :--- | :--- | +| **Chart type** | Override per series. Supports **Line**, **Area**, **Bar**. | +| **Mode** | **Normal** overlaps lines. **Stacked** is available when combining with area/bar types. | +| **Line mode** | **Straight**, **Smoothed**, or **Stepped**. | +| **Y-axis scale** | **Linear**, **Log**, or **Square root**. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/maps-stats-api.md b/_dashboards/visualize/visualize-app/maps-stats-api.md new file mode 100644 index 00000000..439a935d --- /dev/null +++ b/_dashboards/visualize/visualize-app/maps-stats-api.md @@ -0,0 +1,139 @@ +--- +layout: default +title: Maps Stats API +nav_order: 20 +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +parent: Maps application +has_children: false +redirect_from: + - /dashboards/visualize/maps-stats-api/ +--- + +# Maps Stats API +Introduced 2.7 +{: .label .label-purple } + +When you create and save a [map]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/) in OpenSearch Dashboards, the map becomes a saved object of type `map`. The Maps Stats API provides information about such saved objects in OpenSearch Dashboards. + +#### Example request + +You can access the Maps Stats API by providing its URL address in the following format: + +``` +{opensearch-dashboards-endpoint-address}/api/maps-dashboards/stats +``` + +The OpenSearch Dashboards endpoint address may contain a port number if it is specified in the OpenSearch configuration file. The specific URL format depends on the type of OpenSearch deployment and the network environment in which it is hosted. +{: .note} + +You can query the endpoint in two ways: + + - By accessing the endpoint address (for example, `http://localhost:5601/api/maps-dashboards/stats`) in a browser + + - By using the `curl` command in the terminal: + ```bash + curl -X GET http://localhost:5601/api/maps-dashboards/stats + ``` + {% include copy.html %} + +#### Example response + +The following is the response for the preceding request: + +```json +{ + "maps_total":4, + "layers_filters_total":4, + "layers_total":{ + "opensearch_vector_tile_map":2, + "documents":7, + "wms":1, + "tms":2 + }, + "maps_list":[ + { + "id":"88a24e6c-0216-4f76-8bc7-c8db6c8705da", + "layers_filters_total":4, + "layers_total":{ + "opensearch_vector_tile_map":1, + "documents":3, + "wms":0, + "tms":0 + } + }, + { + "id":"4ce3fe50-d309-11ed-a958-770756e00bcd", + "layers_filters_total":0, + "layers_total":{ + "opensearch_vector_tile_map":0, + "documents":2, + "wms":0, + "tms":1 + } + }, + { + "id":"af5d3b90-d30a-11ed-a605-f7ad7bc98642", + "layers_filters_total":0, + "layers_total":{ + "opensearch_vector_tile_map":1, + "documents":1, + "wms":0, + "tms":1 + } + }, + { + "id":"5ca1ec10-d30b-11ed-a042-93d8ff0f09ee", + "layers_filters_total":0, + "layers_total":{ + "opensearch_vector_tile_map":0, + "documents":1, + "wms":1, + "tms":0 + } + } + ] +} +``` + +## Response body fields + +The response contains statistics for the following layer types: + +- Basemaps: Either a default OpenSearch map or custom base layer maps. + +- WMS layers: Custom WMS base layer maps. + +- TMS layers: Custom TMS base layer maps. + +- Document layers: The map's data layers. + +For more information about the layer types, see [Adding layers]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/#adding-layers). + +The following table lists all response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `maps_total` | Integer | The total number of maps registered as saved objects with the Maps plugin. | +| `layers_filters_total` | Integer | The total number of filters for all layers in all maps. This includes [layer-level filters]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/#filtering-data-at-the-layer-level) but excludes global filters like [shape filters]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/#drawing-shapes-to-filter-data). | +| `layers_total` | Object | Totals statistics for all layers in all maps. | +| `layers_total.opensearch_vector_tile_map` | Integer | The total number of OpenSearch basemaps in all maps. | +| `layers_total.documents` | Integer | The total number of document layers in all maps. | +| `layers_total.wms` | Integer | The total number of WMS layers in all maps. | +| `layers_total.tms` | Integer | The total number of TMS layers in all maps. | +| `maps_list` | Array | A list of all maps saved in OpenSearch Dashboards. | + +Each map in the `map_list` contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `id` | String | The map's saved object ID. | +| `layers_filters_total` | Integer | The total number of filters for all layers in the map. This includes [layer-level filters]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/#filtering-data-at-the-layer-level) but excludes global filters like [shape filters]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/#drawing-shapes-to-filter-data) . | +| `layers_total` | Object | Totals statistics for all layers in the map. | +| `layers_total.opensearch_vector_tile_map` | Integer | The total number of OpenSearch basemaps in the map. | +| `layers_total.documents` | Integer | The total number of document layers in the map. | +| `layers_total.wms` | Integer | The total number of WMS layers in the map. | +| `layers_total.tms` | Integer | The total number of TMS layers in the map. | + +The saved object ID helps you navigate to a particular map because the ID is the last part of the map's URL. For example, in OpenSearch Playground, the address of the `[Flights] Flights Status on Maps Destination Location` map is `https://playground.opensearch.org/app/maps-dashboards/88a24e6c-0216-4f76-8bc7-c8db6c8705da`, where `88a24e6c-0216-4f76-8bc7-c8db6c8705da` is the saved object ID for this map. +{: .tip} diff --git a/_dashboards/visualize/visualize-app/maps.md b/_dashboards/visualize/visualize-app/maps.md new file mode 100644 index 00000000..457331c6 --- /dev/null +++ b/_dashboards/visualize/visualize-app/maps.md @@ -0,0 +1,277 @@ +--- +layout: default +title: Maps application +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +has_children: true +has_toc: false +nav_order: 105 +redirect_from: + - /dashboards/visualize/maps/ + - /dashboards/maps-plugin/ + - /dashboards/maps/ +--- + +# Maps application + +The **Maps** application creates map visualizations with multiple layers, combining data across different indexes. You can build each layer from a different index pattern and configure maps to show specific data at different zoom levels. OpenSearch maps are powered by the OpenSearch maps service, which uses vector tiles to render maps. + +## When to use the Maps application + +Use the Maps application when you need multi-layer geographic visualizations that combine data from different indexes, filtering by geographic shapes, custom basemaps, tooltips, or labels. For simpler single-layer geographic visualizations, consider [coordinate maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/coordinate-maps/) or [region maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/region-maps/). + +## Creating a new map + +You can create a new map from the **Maps** or **Visualize** workflows by performing the following steps: + +- To create a new map from the **Maps** workflow, perform the following steps: + + 1. On the top menu bar, go to **OpenSearch Plugins > Maps**. + 1. Choose the **Create map** button. + +- To create a new map from the **Visualize** workflow, perform the following steps: + + 1. On the top menu bar, go to **OpenSearch Dashboards > Visualize**. + 1. Choose the **Create visualization** button. + 1. In the **New Visualization** dialog, choose **Maps**. + +You can now see the default OpenSearch basemap. + +To examine the **Default map** layer configuration, in the **Layers** panel on the upper left of the map, select **Default map**, as shown in the following image. + +![Default map]({{site.url}}{{site.baseurl}}/images/maps/maps-default.png){: width="900" } + +To hide the **Layers** panel, select the collapse (arrow) icon in the panel's upper-right corner. +{: .tip} + +## Layer settings + +To change the default map settings, select **Default map** in the **Layers** panel. Under **Layer settings**, you can change the layer name and description and configure zoom levels and opacity for your layer: + +- **Zoom levels**: By default, a layer is visible at all zoom levels. If you want to make a layer visible only for a certain range of zoom levels, you can specify the zoom levels either by entering them in the text boxes or by sliding the range slider to the desired values. + +- **Opacity**: If your map contains multiple layers, one layer can obscure another one. In this case, you may want to reduce the opacity of the top layer so you can see both layers at the same time. + +## Adding layers + +To add a layer to the map, in the **Layers** panel, select the **Add layer** button. The **Add layer** dialog is shown in the following image. + +![Add layer]({{site.url}}{{site.baseurl}}/images/maps/add-layer.png){: width="450" } + +You can add **base layers** or **data layers** to the map: + +- A **base layer** serves as a basemap. To use your own or a third-party map as a base layer, [add it as a **Custom map**](#adding-a-custom-map). + +- **Data layers** let you visualize data from various data sources. + +## Adding a custom map + +OpenSearch supports Web Map Service (WMS) or Tile Map Service (TMS) custom maps. To add a TMS custom map, perform the following steps: + +1. In the **Layers** panel, select the **Add layer** button. +1. From the **Add layer** dialog, select **Base layer > Custom map**. + Follow the next steps in the **New layer** dialog, which is shown in the following image. + + ![Add custom map]({{site.url}}{{site.baseurl}}/images/maps/custom-map.png) + +1. In the **Custom type** dropdown list, select **Tile Map Service (TMS)**. +1. Enter the TMS URL. +1. (Optional) In **TMS attribution**, enter a TMS attribution for the basemap. For example, if you're using a custom basemap, enter the custom map name. This name is displayed in the lower-right corner of the map. +1. Select the **Settings** tab to edit the layer settings. +1. Enter the layer name in **Name**. +1. (Optional) Enter the layer description in **Description**. +1. (Optional) Select the zoom levels and opacity for this layer. +1. Select the **Update** button. + +## Adding a document layer + +Adding document layers lets you visualize your data. You can add one index pattern per document layer. To view multiple index patterns, create multiple layers. + +Document layers can display geopoint and geoshape document fields. +{: .note} + +The following example assumes that you have the `opensearch_dashboards_sample_data_flights` dataset installed. If you don't have this dataset installed, perform the following steps: + +1. In the upper left, select the home icon. +1. Select **Add sample data**. +1. In the **Sample flight data** panel, select the **Add data** button. + +Add a document layer as follows: + +1. In the **Layers** panel, select the **Add layer** button. +1. From the **Add layer** dialog, select **Data layer > Documents**. +1. In **Data source**, select `opensearch_dashboards_sample_data_flights`. Alternatively, you can enter another index pattern to visualize. +1. In **Geospatial field**, select a geospatial field (geopoint or geoshape) to be displayed in the visualization. In this example, select `DestLocation`. +1. (Optional) Select the **Style** tab to change the fill color, border color, border thickness, or marker size. +1. Select the **Settings** tab to edit layer settings. +1. Enter `Flight destination` in **Name**. +1. Select the **Update** button. +1. To see more data, in the upper-right corner select the calendar icon dropdown list, then under **Quick select**, choose **Last 15 days** and select the **Apply** button. + +You should see the flight destination data, as in the following image. + +![Flight destination map]({{site.url}}{{site.baseurl}}/images/maps/new-layer.png) + +## Filtering data + +To show a subset of the data in the index, filter the data. You can either filter data at the layer level or draw shapes on the map to filter all layer data globally. + +### Filtering data at the layer level + +To filter data at the layer level, select the layer and add a filter to it. + +The following example shows how to filter the flight destination data to display only United States destinations: + +1. In the **Layers** panel, select **Flight destination**. +1. Select **Filters**. +1. Select **Add filter**. +1. In **Edit filter**, select **DestCountry** in **Field**. +1. In **Operator**, select **is**. +1. In **Value**, select **US**. +1. Select the **Save** button. +1. Select the **Update** button. + +For large datasets, you may want to avoid loading data for the full map. To load data only for a specific geographic area, select **Only request data around map extent**. +{: .tip} + +### Drawing shapes to filter data + +You can filter your data globally by drawing [shapes]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape/) on the map. To draw a rectangle or polygon on the map, perform the following steps: + +1. Select the **Rectangle** or **Polygon** icon on the right side of the map. +1. In the **Filter label** field, enter a name for the filter. +1. Choose a spatial relation type. By default, **Intersects** is selected. See [Spatial relations]({{site.url}}{{site.baseurl}}/query-dsl/geo-and-xy/xy#spatial-relations) for more information about spatial relationship types. +1. Select the **Draw Rectangle** or **Draw Polygon** button. +1. Draw the shape over the map area that you want to select: + - For a rectangle, select any starting point on the map (this point becomes a rectangle vertex). Then hover (do not drag) to another point on the map and select it (this point becomes the opposite vertex). + - For a polygon, select any starting point on the map (this point becomes a polygon vertex) and hover (do not drag) to each subsequent vertex and select that point. Finally, make sure to select the starting point again to close the polygon, as shown in the following image. + +![Drawing a polygon on a map]({{site.url}}{{site.baseurl}}/images/maps/draw-shape.png) + +### Disabling the shape filter for a map layer + +By default, the shape filter is applied globally to all layers on the map. If you want to disable your shape filter for a map layer, perform the following steps: +1. Select the layer from the **Layers** panel. +1. In the **Filters** section, deselect **Apply global filters**. +1. Select the **Update** button. + +### Modifying an existing shape filter + +To modify an existing shape filter, select your filter on the upper left above the map. You can perform the following operations on an existing filter: + +- **Edit filter**: Change the filter name or modify the shape's coordinates. +- **Exclude results**: Negate the filter, that is, show all data points _except_ those to which the filter applies. +- **Temporarily disable**: Disable the filter until you select **Re-enable**. +- **Delete**: Remove your filter completely. + +## Using tooltips to visualize additional data + +Document layers show geopoint and geoshape document fields as locations on the map. To add more information to the locations, you can use tooltips. For example, you may want to show flight delay, destination weather, and destination country information in the **Flight destination** layer. Perform the following steps to configure tooltips to show additional data: + +1. In the **Layers** panel, select **Flight destination**. +1. Select **Tooltips**. +1. Select the **Show tooltips** checkbox. +1. In the **Tooltip fields** dropdown list, select the fields that you'd like to display. In this example, select `FlightDelay`, `DestWeather`, and `DestCountry`. +1. Select the **Update** button. + +To view tooltips, hover over the geographical point you're interested in. One tooltip can display many data points. For example, in the **Flight destination** layer there are multiple flights for a single destination city. To paginate over the flights, select the city you're interested in and use the arrows in the tooltip, as shown in the following image. + +![Flight destination tooltip]({{site.url}}{{site.baseurl}}/images/maps/tooltip.png){: width="450" } + +If a point on the map contains data from multiple layers, one tooltip can display data from multiple layers. To see all layers, select **All layers**. To choose a particular layer, select the layer name in the tooltip layer selection panel, as shown in the following image. + +![Tooltip with a layer selection panel]({{site.url}}{{site.baseurl}}/images/maps/layer-selection-panel.png){: width="450" } + +## Adding labels to layers + +Adding a label to a layer lets you visualize additional data on the map. For example, you may want to see the origin weather in the **Flight destination** layer. Perform the following steps to add a label to the **Flight destination** layer: + +1. In the **Layers** panel, select **Flight destination**. +1. In the **Style** tab, select the **Add label** checkbox. +1. You can choose to add a label based on fixed text to all data points in the layer or to use a field value as the label text. + - To add a fixed-text label, under **Label text**, select **Fixed** and enter your desired label text. + - To add a label based on a field value, under **Label text**, select **Field value** and select the field name. In this example, select `OriginWeather`. +1. (Optional) Change the label size, color, border color, or border width. +1. Select the **Update** button. + +The label with the origin weather is visible on the map and also added to the tooltips, as shown in the following image. + +![Label based on field type added to map and tooltips]({{site.url}}{{site.baseurl}}/images/maps/label.png){: width="450" } + +## Reordering, hiding, and deleting layers + +The **Layers** panel lets you reorder, hide, and delete layers: + +- Layers on a map are stacked on top of each other. To reorder layers, use the handlebar (two horizontal lines) icon next to the layer name to drag the layer to the desired position. + +- If you'd like to hide a layer, select the show/hide (eye) icon next to the layer name. Toggle the show/hide icon to show the layer again. + +- To delete a layer, select the delete (trash can) icon next to the layer name. + +## Refreshing data for a real-time dataset + +If you want to visualize a real-time dataset, after adding layers to the map, perform the following steps to set the refresh interval: + +1. Select the calendar icon in the upper-right corner. +1. Under **Refresh every**, select or enter the refresh interval (for example, 1 second). +1. Select the **Start** button. + +![Refreshing a map]({{site.url}}{{site.baseurl}}/images/maps/refresh.png){: width="450" } + +## Saving a map + +To save a map with all the layers that you set up, perform the following steps: + +1. Select the **Save** button in the upper-right corner. +1. In the **Save map** dialog, enter the map name in the **Title** text box. +1. (Optional) In the **Description** text box, enter the map description. +1. Select the **Save** button. + +To open your saved map, choose **Maps** in the upper-left corner. The list of saved maps is displayed. + +## Adding a map to a dashboard + +You can add a new or existing map to a new or existing dashboard by performing the following steps: + +- To add a map to a new dashboard, first create the dashboard as follows: + + 1. On the top menu bar, go to **OpenSearch Dashboards > Dashboard**. + 1. Choose the **Create dashboard** button. + 1. Choose the **Create new** button. + +- To add a map to an existing dashboard, first open the dashboard as follows: + 1. On the top menu bar, go to **OpenSearch Dashboards > Dashboard**. + 1. Select the dashboard you want to open from the list. + 1. In the upper-right corner, choose **Edit**. + +Once you've opened a dashboard, you can add a new or existing map to it. + +### Adding an existing map + +1. From the top menu, choose **Add**. +1. In the **Types** dropdown list, select **Maps**. +1. Select the map you want to add from the list. + +### Adding a new map + +1. From the top menu, choose the **Create new** button. +1. In the **New Visualization** dialog, choose **Maps**. +1. Edit the default map by adding a basemap, layers, or tooltips. +1. In the upper-right corner, choose the **Save** button. +1. In the **Save map** dialog, enter the **Title** and optional **Description** of the map. +1. Select **Add to Dashboard after saving** (this option is selected by default). +1. Choose the **Save and return** button. + +## Editing a map from a dashboard + +1. In the dashboard, choose the gear icon in the upper-right corner of the map you want to edit. +1. Choose **Edit maps**. +1. Edit the map. +1. In the upper-right corner, choose the **Save** button. +1. In the **Save map** dialog, choose the **Save and return** button. + +## Related documentation + +- [Maps Stats API]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps-stats-api/) +- [Configuring maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-maps/) \ No newline at end of file diff --git a/_dashboards/visualize/visualize-app/maptiles.md b/_dashboards/visualize/visualize-app/maptiles.md new file mode 100644 index 00000000..e4d54644 --- /dev/null +++ b/_dashboards/visualize/visualize-app/maptiles.md @@ -0,0 +1,36 @@ +--- +layout: default +title: Configuring a Web Map Service (WMS) +parent: Configuring maps +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 30 +redirect_from: + - /dashboards/visualize/maptiles/ + - /dashboards/maptiles/ +--- + +{%- comment -%}The `/docs/opensearch-dashboards/maptiles/` redirect is specifically to support the UI links in OpenSearch Dashboards 1.0.0.{%- endcomment -%} + +# Configuring a Web Map Service + +The Open Geospatial Consortium (OGC) Web Map Service (WMS) specification is an international specification for requesting dynamic maps on the web. OpenSearch Dashboards includes default map tiles. For specialized maps, you can configure a WMS on OpenSearch Dashboards following these steps: + +1. Log in to OpenSearch Dashboards at `https://<host>:<port>`. For example, you can connect to OpenSearch Dashboards by connecting to [https://localhost:5601](https://localhost:5601). The default username and password are `admin`. +2. Choose **Management** > **Advanced Settings**. +3. Locate `visualization:tileMap:WMSdefaults`. +4. Change `enabled` to `true` and add the URL of a valid WMS server, as shown in the following example: + + ```json + { + "enabled": true, + "url": "{wms-map-server-url}", + "options": { + "format": "image/png", + "transparent": true + } + } + ``` + +Web map services may have licensing fees or restrictions, and you are responsible for complying with any such fees or restrictions. +{: .note } diff --git a/_dashboards/visualize/visualize-app/markdown.md b/_dashboards/visualize/visualize-app/markdown.md new file mode 100644 index 00000000..1c20cf2f --- /dev/null +++ b/_dashboards/visualize/visualize-app/markdown.md @@ -0,0 +1,52 @@ +--- +layout: default +title: Markdown visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 110 +redirect_from: + - /dashboards/visualize/markdown/ +--- + +# Markdown visualization + +A Markdown visualization renders formatted text within a dashboard panel. Use Markdown to provide titles, instructions, metric definitions, and explanatory context alongside data visualizations. Markdown supports headings, lists, bold and italic text, links, blockquotes, and code blocks (GitHub-flavored Markdown). + +Markdown visualizations do not require a data source. + +## When to use Markdown visualizations + +Use Markdown visualizations to add context that helps you interpret the data on a dashboard. Common use cases include: + +- Dashboard titles and section headers +- Instructions for interacting with filters and controls +- Definitions of key metrics shown in other panels +- Links to related dashboards or external documentation +- Status notes such as data refresh intervals or maintenance schedules + +## Creating a Markdown visualization + +1. In the **New Visualization** dialog, select **Markdown**. +2. In the **Markdown** text box on the **Data** tab, enter your Markdown content. +3. Select **Update** to preview the rendered output, as shown in the following image. + +![Markdown visualization showing a dashboard guide]({{site.url}}{{site.baseurl}}/images/dashboards/markdown-example.png) + +4. (Optional) Select the **Options** tab to adjust the base font size or enable **Open links in new tab**. + +## Configuring a Markdown visualization + +The following settings are available on the **Options** tab. + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Font size** | Controls the base font size of the rendered text. | +| **Open links in new tab** | When enabled, links in the Markdown open in a new browser tab. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/metric.md b/_dashboards/visualize/visualize-app/metric.md new file mode 100644 index 00000000..26fc5bad --- /dev/null +++ b/_dashboards/visualize/visualize-app/metric.md @@ -0,0 +1,50 @@ +--- +layout: default +title: Metric visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 120 +redirect_from: + - /dashboards/visualize/metric/ +--- + +# Metric visualization + +A metric visualization displays a single data field. The visualization can show a single value or multiple bucketed values. Use metric visualizations for key indicators on dashboards, especially values that update frequently. + +## When to use metric visualizations + +Use metric visualizations to communicate key business or operational values at a glance, especially real-time or frequently updated values that require constant monitoring, such as system health, business performance, or operational status. + +## Creating a metric visualization + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a metric visualization, follow these steps: + +1. In the **New Visualization** dialog, select **Metric**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). + + The visualization displays a count of the documents in the index pattern. For the `opensearch_dashboards_sample_data_flights` data, this is `13059` if the date range contains all the documents. + {: .note} + +2. Under **Metrics**, expand **Metric Count**. +3. Set **Aggregation** to **Average** and **Field** to **DistanceKilometers**. +4. Select **Update**. + + The visualization displays `7092.142`, the average distance in kilometers for every document in the flight database. + + If your visualization displays a different value, make sure that your [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) window is large enough to encompass all the sample flight data. + {: .note} + + ![Metric visualization showing average flight distance]({{site.url}}{{site.baseurl}}/images/dashboards/metric-example.png) + +## Configuring a metric visualization + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/pie-charts.md b/_dashboards/visualize/visualize-app/pie-charts.md new file mode 100644 index 00000000..9922e205 --- /dev/null +++ b/_dashboards/visualize/visualize-app/pie-charts.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Pie chart +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 130 +redirect_from: + - /dashboards/visualize/pie-charts/ +--- + +# Pie chart + +A pie chart displays what percent of each condition makes up the entire count of a data field. The visualization can show a single value or multiple bucketed values. + +## When to use pie charts + +Use pie charts to compare the relative share of each condition making up a metric. You can select pie segments to filter other visualizations on the same dashboard. + +## Creating a pie chart + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a pie chart, follow these steps: + +1. In the **New Visualization** dialog, select **Pie**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). + + The visualization displays an annular (ring) style pie chart showing only one value. The tooltip reveals the value, a count of the documents in the index pattern. For the `opensearch_dashboards_sample_data_flights` data, this is `13059` if the date range contains all the documents. + {: .note} + + If your visualization displays a different value, make sure that your [time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/) window is large enough to encompass all the sample flight data. + {: .note} + +2. Under **Metrics**, expand **Slice size count**. +3. Set **Aggregation** to **Unique Count** and **Field** to **FlightNum**. + + For a pie chart, bucketed values of the metric must add to 100%. Only those aggregations with this property are displayed. + +4. Select **Update**. + + The pie chart displays `12,932`, presented as a single-value annular pie chart. + +5. To visualize the composition of the field by different conditions, bucket the data: + + 1. Under **Buckets**, select **Add** > **Split slices**. + 2. Set **Aggregation** to **Terms**, **Field** to **OriginCountry**, and **Size** to `5`. + 3. Select **Group other values in separate bucket** so that the total number of unique flights is accurately represented. + 4. Select **Update**. + + The visualization shows that Italy and the U.S. originate the most flights. The top five countries account for almost half of unique flight numbers. + +6. (Optional) Display the visualization as a traditional rather than annular pie chart: + + 1. Select the **Options** tab. + 2. In the Pie settings panel, deselect **Donut**. + 3. Select **Update**. + + The visualization shows a wedge pie chart of the top five countries with all others grouped, as shown in the following image. + + ![Pie chart showing unique flights by origin country]({{site.url}}{{site.baseurl}}/images/dashboards/example-pie-unique-flights.png) + +## Configuring a pie chart + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Donut** | When enabled, renders the chart as a ring (donut) rather than a filled circle. | +| **Show labels** | Displays category labels on each slice. | +| **Show top level only** | When nested buckets exist, shows only the outermost ring. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/ppl.md b/_dashboards/visualize/visualize-app/ppl.md new file mode 100644 index 00000000..c0eb981f --- /dev/null +++ b/_dashboards/visualize/visualize-app/ppl.md @@ -0,0 +1,52 @@ +--- +layout: default +title: PPL visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 140 +redirect_from: + - /dashboards/visualize/ppl/ +--- + +# PPL visualization + +Piped Processing Language (PPL) visualizations enable data processing and visualization using PPL queries. Selecting **PPL** from the **New Visualization** dialog opens the Observability Logs Explorer, where you write a PPL query and map the results to a chart. + +## When to use PPL visualizations + +Use PPL visualizations when you want to write queries directly using the PPL pipeline syntax rather than configuring aggregations through the point-and-click interface. For more information, see [Observability]({{site.url}}{{site.baseurl}}/observing-your-data/) and [Exploring data]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/index/). + +## Creating a PPL visualization + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a PPL visualization, follow these steps: + +1. In the **New Visualization** dialog, select **PPL**. The Observability Logs Explorer opens. +2. In the PPL query bar, enter a query. For example: + + ```sql + source = opensearch_dashboards_sample_data_flights | stats count() by Carrier + ``` + {% include copy.html %} + +3. Set the time filter to a range that contains data (for example, select **Last 7 days**). +4. Select **Run**. +5. Select the **Visualizations** tab to view the chart. +6. (Optional) Use the chart type selector on the right to change the chart type (for example, **Pie**). + +The explorer automatically maps query result fields to the chart. The **Configuration** panel shows **Series** (the metric) and **Dimensions** (the grouping field), as shown in the following image. + +![PPL visualization showing flight count by carrier as a pie chart]({{site.url}}{{site.baseurl}}/images/dashboards/ppl-example.png) + + +## Related documentation + +- [Creating visualizations using queries]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualization-editor/) + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). \ No newline at end of file diff --git a/_dashboards/visualize/visualize-app/region-maps.md b/_dashboards/visualize/visualize-app/region-maps.md new file mode 100644 index 00000000..ac72c6b9 --- /dev/null +++ b/_dashboards/visualize/visualize-app/region-maps.md @@ -0,0 +1,124 @@ +--- +layout: default +title: Region map +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 145 +redirect_from: + - /dashboards/visualize/region-maps/ + - /dashboards/visualize/geojson-regionmaps/ + - /dashboards/geojson-regionmaps/ +--- + +# Region map + +A region map colors geographic regions (countries, states, or counties) based on an aggregated value, using color intensity to show how a metric varies across regions. + +## When to use region maps + +Use region maps to compare data values aggregated by geographic boundaries, such as sales by country, population by state, or incidents by county. For multi-layer geographic visualizations, use the [Maps application]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/). + +## Creating a region map + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a region map, follow these steps: + +1. In the **New Visualization** dialog, select **Region Map**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). +2. Set the time filter to **Last 7 days**. +3. Under **Buckets**, select **Add** > **Shape field**. +4. Set **Aggregation** to **Terms** and **Field** to **OriginCountry**. +5. Select **Update**. + +The map colors each country by its flight count, as shown in the following image. + +![Region map showing flight count by origin country]({{site.url}}{{site.baseurl}}/images/dashboards/region-map-example.png) + +### Customizing the map display + +1. Select the **Options** tab. +2. Under **Layer settings**, select a vector map (for example, **World Countries**). +3. In **Join field**, select the field in the vector map that matches your data (for example, `ISO 3166-1 alpha-2`). +4. Under **Style settings**, adjust the color schema. +5. Select **Update**. + +## Using custom vector maps with GeoJSON + +If the built-in vector maps do not include the regions you need (for example, US counties or ZIP codes), you can upload a custom GeoJSON file. + +To use a custom vector map with GeoJSON, install the following plugins: +- OpenSearch Dashboards Maps [`dashboards-maps`](https://github.com/opensearch-project/dashboards-maps) front-end plugin +- OpenSearch [`geospatial`](https://github.com/opensearch-project/geospatial) backend plugin +{: .note} + +### Uploading a custom GeoJSON file + +1. Prepare a JSON file with either a `.geojson` or `.json` extension. +2. In the **Region Map** editor, in the right panel, select **Import Vector Map**. +3. In **Upload map**, select or drag and drop your JSON file. +4. Enter a **Map name prefix** (for example, `usa-counties`). The map name becomes `<prefix>-map`. +5. Select **Import file**, then select **Refresh** in the confirmation popup. + +### Selecting the custom vector map + +1. In **Layer Options** > **Layer settings**, select **Custom vector map**. +2. Under **Vector map**, select the map you uploaded. +3. (Optional) Under **Style settings**, increase **Border thickness** for visibility. +4. Select **Update**. + +### Example GeoJSON file + +The following GeoJSON file defines two US counties: + +```json +{ + "type": "FeatureCollection", + "name": "usa counties", + "features": [ + { + "type": "Feature", + "properties": { "iso2": "US", "iso3": "LA-CA", "name": "Los Angeles County", "country": "US", "county": "LA" }, + "geometry": { "type": "Polygon", "coordinates": [[[-118.718, 34.071], [-118.696, 34.034], [-118.570, 34.030], [-118.488, 33.957], [-118.372, 33.861], [-118.455, 33.756], [-118.339, 33.715], [-118.229, 33.756], [-118.141, 33.679], [-117.911, 33.578], [-117.751, 33.496], [-117.559, 33.555], [-117.307, 33.596], [-117.070, 33.674], [-116.697, 34.062], [-116.944, 34.284], [-117.180, 34.430], [-117.378, 34.543], [-117.625, 34.570], [-118.048, 34.615], [-118.449, 34.543], [-118.619, 34.389], [-118.740, 34.212], [-118.718, 34.071]]] } + }, + { + "type": "Feature", + "properties": { "iso2": "US", "iso3": "SD-CA", "name": "San Diego County", "country": "US", "county": "SD" }, + "geometry": { "type": "Polygon", "coordinates": [[[-117.235, 32.861], [-117.241, 32.755], [-117.164, 32.681], [-117.142, 32.584], [-117.092, 32.463], [-117.054, 32.292], [-116.960, 32.194], [-116.856, 32.166], [-116.675, 32.204], [-116.367, 32.320], [-116.147, 32.551], [-116.164, 32.806], [-116.411, 33.073], [-116.730, 33.082], [-117.092, 32.995], [-117.252, 32.963], [-117.235, 32.861]]] } + } + ] +} +``` + +## Configuring GeoJSON complexity + +The complexity of uploaded GeoJSON files is configured using the following cluster settings: + +| Setting | Default | Description | +| :--- | :--- | :--- | +| `plugins.geospatial.geojson.max_coordinates_per_geo` | `10000` | Maximum number of coordinates allowed per geometry. | +| `plugins.geospatial.geojson.max_holes_per_polygon` | `1000` | Maximum number of holes allowed per polygon. | +| `plugins.geospatial.geojson.max_multi_geometries` | `100` | Maximum number of geometries in a multi-geometry object. | +| `plugins.geospatial.geojson.max_geometry_collection_nested_depth` | `5` | Maximum nested depth for geometry collections. | + +For more information about updating dynamic settings, see [Dynamic settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/#dynamic-settings). + +## Configuring a region map + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +### Options tab + +| Setting | Description | +| :--- | :--- | +| **Vector map** | The basemap containing geographic boundaries. Select a built-in map or a custom uploaded map. | +| **Join field** | The field in the vector map used to match your data values. | +| **Color schema** | The color gradient used to represent values. | +| **Show tooltips** | When enabled, displays region values on hover. | + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). + diff --git a/_dashboards/visualize/visualize-app/selfhost-maps-server.md b/_dashboards/visualize/visualize-app/selfhost-maps-server.md new file mode 100644 index 00000000..bef1ff37 --- /dev/null +++ b/_dashboards/visualize/visualize-app/selfhost-maps-server.md @@ -0,0 +1,110 @@ +--- +layout: default +title: Using self-hosted map servers +parent: Configuring maps +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 40 +redirect_from: + - /dashboards/visualize/selfhost-maps-server/ + - /dashboards/selfhost-maps-server/ +--- + +# Using self-hosted map servers + +The self-host maps server for OpenSearch Dashboards provides access to the default maps service in air-gapped environments. OpenSearch-compatible map URLs include a map manifest with map tiles and vectors, the map tiles, and the map vectors. + +The following sections provide steps for setting up and using the self-host maps server with OpenSearch Dashboards. + +You can access the `maps-server` image from the official OpenSearch [Docker Hub repository](https://hub.docker.com/u/opensearchproject). +{: .note} + +## Pulling the Docker image + +Open your terminal and run the following command: + +`docker pull opensearchproject/opensearch-maps-server:1.0.0` + +## Setting up the server + +You must set up the map tiles before running the server. You have two setup options: Use the OpenSearch-provided maps service tiles set, or generate the raster tiles set. + +### Option 1: Use the OpenSearch-provided maps service tiles set + +Create a Docker volume to hold the tiles set: + +`docker volume create tiles-data` + +Download the tiles set from the OpenSearch maps service. Two planet tiles sets are available based on the desired zoom level: + +- Zoom level 8 (https://maps.opensearch.org/offline/planet-osm-default-z0-z8.tar.gz) +- Zoom level 10 (https://maps.opensearch.org/offline/planet-osm-default-z0-z10.tar.gz) + +The planet tiles set for zoom level 10 (2 GB compressed/6.8 GB uncompressed) is approximately 10 times larger than the set for zoom level 8 (225 MB compressed/519 MB uncompressed). +{: .note} + +``` +docker run \ + -e DOWNLOAD_TILES=https://maps.opensearch.org/offline/planet-osm-default-z0-z8.tar.gz \ + -v tiles-data:/usr/src/app/public/tiles/data/ \ + opensearch/opensearch-maps-server \ + import +``` + +### Option 2: Generate the raster tiles set + +To generate the raster tiles set, use the [raster tile generation pipeline](https://github.com/opensearch-project/maps/tree/main/tiles-generation/cdk) and then use the tiles set absolute path to create a volume to start the server. + +## Starting the server + +Use the following command to start the server using the Docker volume `tiles-data`. The following command is an example using host URL "localhost" and port "8080": + +``` +docker run \ + -v tiles-data:/usr/src/app/public/tiles/data/ \ + -e HOST_URL='http://localhost' \ + -p 8080:8080 \ + opensearch/opensearch-maps-server \ + run +``` + +Or, if you generated the raster tiles set, run the server using that tiles set: + +``` +docker run \ + -v /absolute/path/to/tiles/:/usr/src/app/dist/public/tiles/data/ \ + -p 8080:8080 \ + opensearch/opensearch-maps-server \ + run +``` +Confirm the server is running by opening each of the following links in a browser on your host or with a `curl` command (for example, `curl http://localhost:8080/manifest.json`). + +* Map manifest URL: `http://localhost:8080/manifest.json` +* Map tiles URL: `http://localhost:8080/tiles/data/{z}/{x}/{y}.png` +* Map tiles demo URL: `http://localhost:8080/` + +## Using the self-host maps server with OpenSearch Dashboards + +You can use the self-host maps server with OpenSearch Dashboards by either adding the parameter to `opensearch_dashboards.yml` or configuring the default WMS properties in OpenSearch Dashboards. + +### Option 1: Configure opensearch_dashboards.yml + +Configure the manifest URL in `opensearch_dashboards.yml`: + +`map.opensearchManifestServiceUrl: "http://localhost:8080/manifest.json"` + +### Option 2: Configure Default WMS properties in OpenSearch Dashboards + +1. On the OpenSearch Dashboards console, select **Dashboards Management** > **Advanced Settings**. +2. Locate `visualization:tileMap:WMSdefaults` under **Default WMS properties**. +3. Change `"enabled": false` to `"enabled": true` and add the URL for the valid map server. + +## Licenses + +Tiles are generated per [Terms of Use for Natural Earth vector map data](https://www.naturalearthdata.com/about/terms-of-use/) and [Copyright and License for OpenStreetMap](https://www.openstreetmap.org/copyright). + +## Related documentation + +* [Configuring a Web Map Service (WMS)]({{site.url}}{{site.baseurl}}/dashboards/visualize/maptiles/) +* [Coordinate maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/coordinate-maps/) +* [Region maps]({{site.url}}{{site.baseurl}}/dashboards/visualize/region-maps/) diff --git a/_dashboards/visualize/visualize-app/tag-cloud.md b/_dashboards/visualize/visualize-app/tag-cloud.md new file mode 100644 index 00000000..c309d091 --- /dev/null +++ b/_dashboards/visualize/visualize-app/tag-cloud.md @@ -0,0 +1,56 @@ +--- +layout: default +title: Tag cloud +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 150 +redirect_from: + - /dashboards/visualize/tag-cloud/ +--- + +# Tag cloud + +A tag cloud displays a group of text fields (bucket labels, called _tags_ in the visualization) from the data. The font size of each tag corresponds to the magnitude of the bucket in the data. For example, if the visualization specifies `Average`, the font size of the tag in the tag cloud is proportional to the bucketed field's average value. + +You can think of a tag cloud as a kind of reverse display that maps bucketed values by displaying the values as the size of the bucket label rather than a graphed quantity such as the length of a bar. + +## When to use tag clouds + +Use tag clouds to provide a dramatic comparison of magnitudes of different text-labeled buckets. + +## Creating a tag cloud + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a tag cloud, follow these steps: + +1. In the **New Visualization** dialog, select **Tag Cloud**, then select your index pattern (for example, **opensearch_dashboards_sample_data_flights**). + + Since the data is not bucketed, the visualization pane displays `all` in large letters. By default the tag size is proportional to the document count, but there are no other terms to compare its size against. + {: .note} + +2. Under **Metrics**, expand **Tag size count**. +3. Set **Aggregation** to **Unique Count** and **Field** to **DestLocation**. +4. (Optional) Enter a **Custom label**, for example `Destinations Served`. +5. Select **Update**. + + The visualization does not change. The tag cloud still has only one entry, `all`, because the data has not been bucketed. + +6. Under **Buckets**, select **Add** > **Tags**. +7. Set **Aggregation** to **Terms** and **Field** to **Carrier**. +8. Select **Update**. + + The tag cloud displays each carrier sized by the number of unique destinations, as shown in the following image. + + ![Tag cloud showing carriers sized by unique destinations]({{site.url}}{{site.baseurl}}/images/dashboards/example-tagcloud-carrier-destinations.png) + +## Configuring a tag cloud + +For information about general visualization configuration, see [Configuring visualizations]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/configuring-viz/). + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/timeline.md b/_dashboards/visualize/visualize-app/timeline.md new file mode 100644 index 00000000..c4991279 --- /dev/null +++ b/_dashboards/visualize/visualize-app/timeline.md @@ -0,0 +1,577 @@ +--- +layout: default +title: Timeline visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 160 +redirect_from: + - /dashboards/visualize/timeline/ +--- + +# Timeline visualization + +**Timeline** is an expression-based data visualization tool in OpenSearch Dashboards that you can use to create time-series visualizations using a simple expression language. Unlike other visualization types that use a graphical interface, **Timeline** uses a text-based expression syntax to define data sources, transformations, and display options. With this syntax, you can compare multiple time series, apply mathematical functions, and overlay data from different time periods. + +## When to use timeline visualizations + +Use **Timeline** for exclusively time-based data analysis, particularly for revealing temporal patterns and event sequences using its expression syntax. + +**Timeline** is a legacy visualization tool. For new time-based visualizations, consider using [TSVB]({{site.url}}{{site.baseurl}}/dashboards/visualize/tsvb/) or [Vega]({{site.url}}{{site.baseurl}}/dashboards/visualize/vega/). +{: .note} + +**Timeline** is best suited for scenarios where you need expression-based control over your visualizations, such as comparing data across time periods using offsets, applying mathematical transformations to series, or combining multiple data sources on a single chart. +{: .tip} + +## Prerequisites + +Before creating a timeline visualization, ensure that you have the following: + +- An OpenSearch Dashboards instance running and accessible. +- Sample data loaded or a time-series index available. The examples in this document use the e-commerce sample dataset. To learn about adding sample datasets, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +## Creating a timeline visualization + +To create a timeline visualization, follow these steps: + +1. From the top menu, select **OpenSearch Dashboards > Visualize**. +1. Select **Create visualization**. +1. Select **Timeline**. + +The timeline editor consists of the following components: + +- **Chart area**: Displays the rendered visualization. +- **Interval**: Sets the time bucket size for data aggregation (for example, `1d`, `1h`, or `auto`). +- **Timeline expression**: The text editor where you write timeline expressions to define the data and appearance of your visualization. +- **Update and Discard buttons**: Apply or revert changes to the expression. + +The following image shows the timeline editor containing a basic expression that queries e-commerce data. + +![The timeline editor showing a basic OpenSearch expression with order count over time]({{site.url}}{{site.baseurl}}/images/dashboards/timeline-basic-expression.png){: width="700" } + +## Timeline expression syntax + +A timeline expression consists of one or more function chains separated by commas. Each chain starts with a data source function and is followed by additional functions chained using dot notation. Multiple chains are separated by commas and produce multiple series on the same chart. + +The basic syntax is as follows: + +```js +.function1(arg1=value1, arg2=value2).function2(arg1=value1) +``` +{% include copy.html %} + +To display multiple series on the same chart, separate the expressions with commas: + +```js +.opensearch(index=my-index).label("Series 1"), .opensearch(index=my-index, metric=avg:price).label("Series 2") +``` +{% include copy.html %} + +## Data source functions + +The `.opensearch()` function is the primary data source for timeline expressions. It pulls time-series data from an OpenSearch index. + +<!-- vale off --> +### .opensearch() parameters +<!-- vale on --> + +The following table lists the `.opensearch()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `q` | String | A query in Apache Lucene [query string]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) syntax. Default is `*` (match all). | +| `metric` | String | An OpenSearch metric aggregation: `avg`, `sum`, `min`, `max`, `percentiles`, or `cardinality`, followed by a field name. For example, `sum:bytes` or `percentiles:bytes:95,99,99.9`. Default is `count`. | +| `split` | String | A field on which to split the series and a limit. For example, `hostname:10` retrieves the top 10 hostnames. | +| `index` | String | The index to query. Wildcards are accepted. Provide an index pattern name for scripted fields and field name suggestions. | +| `timefield` | String | A field of type `date` to use for the x-axis. | +| `offset` | String | Offsets the series retrieval by a date expression, for example, `-1M` to make events from one month ago appear as if they are happening now. Use `timerange:-2` to offset by twice the overall chart time range to the past. | +| `opensearchDashboards` | Boolean | When set to `true`, respects filters applied on OpenSearch Dashboards dashboards. Only has an effect when used on dashboards. | +| `data_source_name` | String | The data source to query from. Only works when multiple data sources are enabled. | +| `fit` | String | The algorithm to use for fitting series to the target time span and interval. One of `average`, `carry`, `nearest`, `none`, or `scale`. | + +### Basic query example + +The following expression retrieves a count of documents from the e-commerce sample data index over time: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date) +``` +{% include copy.html %} + +### Metric aggregation example + +The following expression calculates the average value of the `taxful_total_price` field: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=avg:taxful_total_price) +``` +{% include copy.html %} + +### Query filter example + +The following expression uses the `q` parameter to filter data using Lucene query syntax: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, q="customer_gender:MALE").label("Male Orders"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, q="customer_gender:FEMALE").label("Female Orders") +``` +{% include copy.html %} + +### Split example + +The following expression splits the data by the `customer_gender` field, returning the top 2 values: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, split=customer_gender:2) +``` +{% include copy.html %} + +### Offset example + +The following expression overlays the current time range with data from one week ago for comparison: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("This Week"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, offset=-1w).label("Previous Week") +``` +{% include copy.html %} + +The following image shows the current week compared to the previous week using offset. + +![A timeline visualization comparing the current period with the previous week using offset]({{site.url}}{{site.baseurl}}/images/dashboards/timeline-offset.png){: width="700" } + +## Display functions + +Display functions control the chart type used to render series (lines, bars, or points). + +<!-- vale off --> +### .lines() +<!-- vale on --> + +Renders the series as lines. The following table lists the `.lines()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `width` | Number | The line thickness, in pixels. | +| `fill` | Number | A number between 0 and 10 that controls the fill opacity. Use for creating area charts. | +| `stack` | Boolean | When set to `true`, stacks lines. | +| `show` | Boolean | Shows or hides lines. | +| `steps` | Boolean | When set to `true`, renders lines as steps instead of interpolating between points. | + +#### Example + +The following expression renders a line chart with a custom width and fill: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).lines(width=2, fill=1) +``` +{% include copy.html %} + +<!-- vale off --> +### .bars() +<!-- vale on --> + +Renders the series as bars. The following table lists the `.bars()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `width` | Number | The bar width, in pixels. | +| `stack` | Boolean | When set to `true`, stacks bars. Default is `true`. | + +#### Example + +The following expression renders a bar chart of total revenue: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).bars(width=2) +``` +{% include copy.html %} + +<!-- vale off --> +### .points() +<!-- vale on --> + +Renders the series as points. The following table lists the `.points()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `radius` | Number | The point size. | +| `weight` | Number | The thickness of the line around the point. | +| `fill` | Number | A number between 0 and 10 representing the fill opacity. | +| `fillColor` | String | The color with which to fill the point. | +| `symbol` | String | The point symbol. One of `triangle`, `cross`, `square`, `diamond`, or `circle`. | +| `show` | Boolean | Shows or hides points. | + +#### Example + +The following expression renders data as cross-shaped points: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=max:taxful_total_price).points(symbol=cross, radius=3) +``` +{% include copy.html %} + +## Styling functions + +Styling functions control the labeling, color, and legend of series without changing the chart type. + +<!-- vale off --> +### .label() +<!-- vale on --> + +Changes the label of the series displayed in the legend. Use `$1`, `$2`, and so on to reference regex capture groups. The following table lists the `.label()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `label` | String | The legend value for the series. Use `$1`, `$2`, and so on to reference regex capture groups. | +| `regex` | String | A regex with capture group support. | + +#### Example + +The following expression sets a custom label for the series: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("Daily Order Count") +``` +{% include copy.html %} + +<!-- vale off --> +### .color() +<!-- vale on --> + +Changes the color of the series. Accepts hex color values. To create a gradient across multiple series, specify multiple colors separated by colons. + +#### Example + +The following expression sets the series color to blue: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).color(#1E88E5) +``` +{% include copy.html %} + +<!-- vale off --> +### .legend() +<!-- vale on --> + +Sets the position and style of the legend. The following table lists the `.legend()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `position` | String or Boolean | The corner to place the legend in: `nw`, `ne`, `se`, or `sw`. Set to `false` to disable the legend. | +| `columns` | Number | The number of columns to divide the legend into. | +| `showTime` | Boolean | When set to `true`, shows the time value in the legend when hovering over the graph. Default is `true`. | +| `timeFormat` | String | A moment.js format pattern. Default is `MMMM Do YYYY, HH:mm:ss.SSS`. | + +<!-- vale off --> +### .title() +<!-- vale on --> + +Adds a title to the top of the plot. If called on more than one series, the last call is used. The following table lists the `.title()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `title` | String | The title for the plot. | + +<!-- vale off --> +### .hide() +<!-- vale on --> + +Hides the series by default. The series is still available in the legend and can be toggled on. The following table lists the `.hide()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `hide` | Boolean | When set to `true`, hides the series. Default is `true`. | + +## Y-axis configuration + +You can configure one or more y-axes to control scale, positioning, and formatting. + +<!-- vale off --> +### .yaxis() +<!-- vale on --> + +Configures y-axis options. Use `.yaxis(2)` to plot a series on a secondary y-axis. The following table lists the `.yaxis()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `yaxis` | Number | The numbered y-axis to plot this series on. For example, `2` for a secondary y-axis. | +| `min` | Number | The minimum value. | +| `max` | Number | The maximum value. | +| `position` | String | The axis position: `left` or `right`. | +| `label` | String | The label for the axis. | +| `color` | String | The color of the axis label. | +| `units` | String | The formatting for y-axis labels. One of `bits`, `bits/s`, `bytes`, `bytes/s`, `currency(:ISO 4217 code)`, `percent`, or `custom(:prefix:suffix)`. | +| `tickDecimals` | Number | The number of decimal places for y-axis tick labels. | + +#### Example + +The following expression displays revenue as bars on the left y-axis and order count as a line on the right y-axis: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).label("Total Revenue").bars(width=2), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("Order Count").lines(fill=1, width=1).yaxis(2) +``` +{% include copy.html %} + +The following image shows the dual y-axis visualization with revenue as bars and order count as a line. + +![A timeline visualization with dual y-axis showing total revenue as bars and order count as a line]({{site.url}}{{site.baseurl}}/images/dashboards/timeline-multi-series.png){: width="700" } + +## Data transformation functions + +Data transformation functions modify, smooth, or analyze series data. + +<!-- vale off --> +### .movingaverage() +<!-- vale on --> + +Calculates the moving average over a given window. Use this function to smooth noisy series. Aliases: `.mvavg()`. The following table lists the `.movingaverage()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `window` | Number or String | The number of points, or a date math expression (for example, `1d` or `1M`) to average over. | +| `position` | String | The position of the averaged points relative to the result time. One of `left`, `right`, or `center`. | + +#### Example + +The following expression overlays daily revenue with a 7-day moving average: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).label("Daily Revenue"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).movingaverage(window=7).label("7-Day Moving Average").color(#F04E37).lines(width=3) +``` +{% include copy.html %} + +The following image shows daily revenue with a 7-day moving average overlay. + +![A timeline visualization showing daily revenue with a 7-day moving average overlay]({{site.url}}{{site.baseurl}}/images/dashboards/timeline-moving-average.png){: width="700" } + +<!-- vale off --> +### .movingstd() +<!-- vale on --> + +Calculates the moving standard deviation over a given window. Aliases: `.mvstd()`. The following table lists the `.movingstd()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `window` | Number | The number of points to compute the standard deviation over. | +| `position` | String | The position of the window slice relative to the result time. One of `left`, `right`, or `center`. Default is `left`. | + +#### Example + +The following expression calculates the 5-point moving standard deviation: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).movingstd(window=5).label("5-Point Std Dev") +``` +{% include copy.html %} + +<!-- vale off --> +### .derivative() +<!-- vale on --> + +Plots the change in values over time. + +#### Example + +The following expression plots the change in order count over time: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).derivative().label("Change in Order Count") +``` +{% include copy.html %} + +<!-- vale off --> +### .trend() +<!-- vale on --> + +Draws a trend line using a specified regression algorithm. The following table lists the `.trend()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `mode` | String | The algorithm to use. One of `linear` or `log`. | +| `start` | Number | Where to start calculating. Negative values count from the end. Default is `0`. | +| `end` | Number | Where to stop calculating. Negative values count from the end. Default is `0`. | + +#### Example + +The following expression overlays a linear trend line on the order count: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("Order Count"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).trend(mode=linear).label("Trend").color(#E53935) +``` +{% include copy.html %} + +<!-- vale off --> +### .cusum() +<!-- vale on --> + +Returns the cumulative sum of a series, starting at a base value. The following table lists the `.cusum()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `base` | Number | The number to start at. This value is added to the beginning of the series. | + +<!-- vale off --> +### .fit() +<!-- vale on --> + +Fills null values using a defined fit function. The following table lists the `.fit()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `mode` | String | The algorithm to use. One of `average`, `carry`, `nearest`, `none`, or `scale`. | + +<!-- vale off --> +### .trim() +<!-- vale on --> + +Sets N buckets at the start or end of a series to null. Use this function to address the partial bucket issue. The following table lists the `.trim()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `start` | Number | The number of buckets to trim from the beginning. Default is `1`. | +| `end` | Number | The number of buckets to trim from the end. Default is `1`. | + +## Mathematical functions + +Timeline supports the following mathematical functions for combining or transforming series. Mathematical functions accept either a number or another series as an argument. + +| Function | Description | +| :--- | :--- | +| `.add()` (aliases: `.plus()`, `.sum()`) | Adds the values of one or more series to each position in the input series. | +| `.subtract()` | Subtracts the values of one or more series from each position in the input series. | +| `.multiply()` | Multiplies the values of one or more series at each position in the input series. | +| `.divide()` | Divides the values of one or more series at each position in the input series. | +| `.abs()` | Returns the absolute value of each value in the series. | +| `.log()` | Returns the logarithm of each value (default base: 10). | +| `.min()` | Returns the minimum value between the current and the provided series or number at each position. | +| `.max()` | Returns the maximum value between the current and the provided series or number at each position. | +| `.precision()` | Truncates the decimal portion of values to the specified number of digits. | +| `.scale_interval()` | Scales a value (usually a sum or a count) to a new interval, for example, a per-second rate. | +| `.range()` | Changes the maximum and minimum of a series while keeping the same shape. | + +#### Example + +The following expression calculates revenue per order by dividing the total revenue by the order count: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).divide(value=.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date)).label("Revenue per Order") +``` +{% include copy.html %} + +## Conditional function + +Use the conditional function to set values based on comparison logic. + +<!-- vale off --> +### .condition() +<!-- vale on --> + +Compares each point to a number or the same point in another series using an operator, then sets its value to the result if the condition proves true. If `else` is omitted, points that do not meet the condition retain their original value. Aliases: `.if()`. The following table lists the `.condition()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `operator` | String | The comparison operator: `eq`, `ne`, `lt`, `lte`, `gt`, or `gte`. | +| `if` | Number or SeriesList | The value to compare each point against. | +| `then` | Number or SeriesList | The value to set if the comparison is true. | +| `else` | Number or SeriesList | The value to set if the comparison is false. | + +#### Example + +The following expression caps values at 150 and sets lower values to 0: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).condition(operator=gte, if=150, then=150, else=0).label("Days Meeting Target") +``` +{% include copy.html %} + +## Static values + +Use static values to draw reference lines, such as targets or thresholds, on your chart. + +<!-- vale off --> +### .static() +<!-- vale on --> + +Draws a single value as a horizontal line across the chart. Aliases: `.value()`. The following table lists the `.static()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `value` | Number or String | The single value to display. You can pass several values to interpolate them evenly across the time range. | +| `label` | String | The label for the series. | +| `offset` | String | Offsets the series retrieval by a date expression. | +| `fit` | String | The algorithm to use for fitting. One of `average`, `carry`, `nearest`, `none`, or `scale`. | + +#### Example + +The following expression adds a target line at 150 orders: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("Order Count").lines(fill=2, width=1), +.static(value=150, label="Target").color(#E53935).lines(width=2) +``` +{% include copy.html %} + +The following image shows the order count with a static target line at 150 orders. + +![A timeline visualization with a static target line at 150 orders]({{site.url}}{{site.baseurl}}/images/dashboards/timeline-static-line.png){: width="700" } + +## Aggregation function + +Use the aggregation function to reduce a series to a single value and display it as a horizontal line. + +<!-- vale off --> +### .aggregate() +<!-- vale on --> + +Creates a static line based on the result of processing all points in the series. The following table lists the `.aggregate()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `function` | String | One of `avg`, `cardinality`, `min`, `max`, `last`, `first`, or `sum`. | + +#### Example + +The following expression displays the order count with its average as a horizontal line: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("Order Count"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).aggregate(function=avg).label("Average").color(#E53935) +``` +{% include copy.html %} + +## Forecasting function + +Use the forecasting function to predict future values based on historical patterns in your series. + +<!-- vale off --> +### .holt() +<!-- vale on --> + +Samples the beginning of a series and uses it to forecast future values using Holt-Winters triple exponential smoothing. Use this function for anomaly detection. Null values are filled with forecasted values. The following table lists the `.holt()` function parameters. + +| Parameter | Type | Description | +| :--- | :--- | :--- | +| `alpha` | Number | The smoothing weight from 0 to 1. Higher values make the series follow the original more closely. | +| `beta` | Number | The trending weight from 0 to 1. Higher values make rising or falling lines continue longer. | +| `gamma` | Number | The seasonal weight from 0 to 1. Higher values give recent seasons more importance. | +| `season` | String | The season length, for example, `1w` for weekly patterns. Only useful with `gamma`. | +| `sample` | Number | The number of seasons to sample before predicting. Only useful with `gamma`. Default is all. | + +#### Example + +The following expression forecasts order count using Holt-Winters smoothing: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("Actual"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).holt(alpha=0.5, beta=0.5).label("Forecast").color(#E53935) +``` +{% include copy.html %} + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/tsvb.md b/_dashboards/visualize/visualize-app/tsvb.md new file mode 100644 index 00000000..80128749 --- /dev/null +++ b/_dashboards/visualize/visualize-app/tsvb.md @@ -0,0 +1,83 @@ +--- +layout: default +title: TSVB visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 170 +redirect_from: + - /dashboards/visualize/tsvb/ +--- + +# TSVB visualization + +The Time-Series Visual Builder (TSVB) is a data visualization tool in OpenSearch Dashboards for creating detailed time-series visualizations. TSVB supports adding annotations or markers at specific time points based on index data, making connections between multiple indexes, and building visualizations that display data over time. TSVB supports the following visualization types: Area, Line, Metric, Gauge, Markdown, and Data Table. + +## When to use TSVB visualizations + +Use TSVB visualizations for time-series analysis that goes beyond basic chart capabilities, including advanced mathematical functions, multiple metric comparisons, and sophisticated temporal analysis. + +## Creating TSVB visualizations from multiple data sources +Introduced 2.14 +{: .label .label-purple } + +Before proceeding, ensure that the following configuration settings are enabled in the `config/opensearch_dashboards.yaml` file: + +```yaml +data_source.enabled: true +vis_type_timeseries.enabled: true +``` +{% include copy.html %} + +Once you have configured [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/) in OpenSearch Dashboards, you can use TSVB to query those data sources. The following GIF shows the process of creating TSVB visualizations in OpenSearch Dashboards. + +![Process of creating TSVB visualizations in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/configure-tsvb.gif) + +**Step 1: Set up and connect data sources** + +Open OpenSearch Dashboards and follow these steps: + +1. Select **Dashboards Management** from the main menu on the left. +2. Select **Data sources** and then select the **Create data source** button. +3. On the **Create data source** page, enter the connection details and endpoint URL. +4. On the home page, select **Add sample data** and then select the **Add data** button for the **Sample web logs** dataset. + +The following GIF shows the steps required to set up and connect a data source. + +![Create data source]({{site.url}}{{site.baseurl}}/images/dashboards/create-datasource.gif) + +**Step 2: Create the visualization** + +Follow these steps to create the visualization: + +1. From the menu on the left, select **Visualize**. +2. On the **Visualizations** page, select **Create Visualization** and then select **TSVB** in the pop-up window. + +**Step 3: Specify data sources** + +After creating a TSVB visualization, data may appear based on your default index pattern. To change the index pattern or configure additional settings, follow these steps: + +1. In the **Create** window, select **Panel options**. +2. Under **Data source**, select the OpenSearch cluster from which to pull data. In this case, choose your newly created data source. +3. Under **Index name**, enter `opensearch_dashboards_sample_data_logs`. +4. Under **Time field**, select `@timestamp`. This setting specifies the time range for rendering the visualization. + +**(Optional) Step 4: Add annotations** + +Annotations are markers that can be added to time-series visualizations. Follow these steps to add annotations: + +1. On the upper-left corner of the page, select **Time Series**. +2. Select the **Annotations** tab and then **Add data source**. +3. In the **Index** name field, specify the appropriate index. In this case, continue using the same index from the previous steps, that is, `opensearch_dashboards_sample_data_logs`. +4. From **Time** field, select `@timestamp`. +5. In the **Fields** field, enter `timestamp`. +6. In the **Row template** field, enter `timestamp`. + +The visualization automatically updates to display your annotations, as shown in the following image. + + ![TSVB visualization with annotations]({{site.url}}{{site.baseurl}}/images/dashboards/tsvb-with-annotations.png){: width="700" } + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/vega.md b/_dashboards/visualize/visualize-app/vega.md new file mode 100644 index 00000000..b12b7ced --- /dev/null +++ b/_dashboards/visualize/visualize-app/vega.md @@ -0,0 +1,394 @@ +--- +layout: default +title: Vega visualization +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 180 +redirect_from: + - /dashboards/visualize/vega/ +--- + +# Vega visualization + +[Vega](https://vega.github.io/vega/) and [Vega-Lite](https://vega.github.io/vega-lite/) are open-source, declarative language visualization tools that you can use to create custom data visualizations with your OpenSearch data and [Vega data](https://vega.github.io/vega/docs/data/). These tools are ideal for advanced users comfortable with writing OpenSearch queries directly. You define data sources inline within your Vega specification. + +## When to use Vega visualizations + +Use Vega visualizations when you need visualization types or analytical capabilities not available in standard OpenSearch visualization types, including advanced statistical analysis, custom interactive behaviors, and specialized analytical techniques. + +## Enabling Vega visualizations + +Vega visualizations are enabled by default. Write your [Vega specifications](https://vega.github.io/vega/docs/specification/) in JSON or [Hjson](https://hjson.github.io/) format. You can specify one or more OpenSearch queries within a specification. + +To disable Vega visualizations, set `vis_type_vega.enabled` to `false` in your `opensearch_dashboards.yml` file. + +## Creating a Vega visualization + +The examples on this page use the **Sample e-commerce data** dataset. To learn about adding sample datasets, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). +{: .note} + +The following example creates a network graph that visualizes relationships between product manufacturers in the sample e-commerce dataset. It uses the [`adjacency_matrix` aggregation]({{site.url}}{{site.baseurl}}/aggregations/bucket/adjacency-matrix/) to determine how frequently products from different manufacturers appear together in the same orders. + +To create a Vega visualization for this aggregation, follow these steps: + +1. From the menu on the left, select **Visualize**. +2. Select **Create Visualization** and then select **Vega**. +3. Replace the default spec with the following and then select **Update**: + +```json +{ + "$schema": "https://vega.github.io/schema/vega/v5.json", + "description": "Network graph from adjacency matrix aggregation", + "autosize": "none", + "width": 500, + "height": 400, + "padding": 50, + + "data": [ + { + "name": "raw", + "url": { + "index": "opensearch_dashboards_sample_data_ecommerce", + "body": { + "size": 0, + "aggs": { + "interactions": { + "adjacency_matrix": { + "filters": { + "Low Tide Media": {"match": {"manufacturer.keyword": "Low Tide Media"}}, + "Elitelligence": {"match": {"manufacturer.keyword": "Elitelligence"}}, + "Oceanavigations": {"match": {"manufacturer.keyword": "Oceanavigations"}} + } + } + } + } + } + }, + "format": {"property": "aggregations.interactions.buckets"} + }, + { + "name": "nodes", + "source": "raw", + "transform": [ + {"type": "filter", "expr": "indexof(datum.key, '&') === -1"}, + {"type": "window", "ops": ["row_number"], "as": ["index"]}, + {"type": "formula", "as": "x", "expr": "250 + 150 * cos(2 * PI * (datum.index - 1) / 3)"}, + {"type": "formula", "as": "y", "expr": "200 + 150 * sin(2 * PI * (datum.index - 1) / 3)"} + ] + }, + { + "name": "edges", + "source": "raw", + "transform": [ + {"type": "filter", "expr": "indexof(datum.key, '&') !== -1"}, + {"type": "formula", "as": "source", "expr": "split(datum.key, '&')[0]"}, + {"type": "formula", "as": "target", "expr": "split(datum.key, '&')[1]"}, + {"type": "lookup", "from": "nodes", "key": "key", "fields": ["source"], "as": ["sourceNode"]}, + {"type": "lookup", "from": "nodes", "key": "key", "fields": ["target"], "as": ["targetNode"]} + ] + } + ], + + "scales": [ + { + "name": "nodeSize", + "type": "linear", + "domain": {"data": "nodes", "field": "doc_count"}, + "range": [400, 2000] + }, + { + "name": "linkWidth", + "type": "linear", + "domain": {"data": "edges", "field": "doc_count"}, + "range": [2, 8] + } + ], + + "marks": [ + { + "type": "rule", + "from": {"data": "edges"}, + "encode": { + "enter": { + "x": {"field": "sourceNode.x"}, + "y": {"field": "sourceNode.y"}, + "x2": {"field": "targetNode.x"}, + "y2": {"field": "targetNode.y"}, + "stroke": {"value": "#888"}, + "strokeWidth": {"scale": "linkWidth", "field": "doc_count"}, + "strokeOpacity": {"value": 0.6} + } + } + }, + { + "type": "text", + "from": {"data": "edges"}, + "encode": { + "enter": { + "x": {"signal": "(datum.sourceNode.x + datum.targetNode.x) / 2"}, + "y": {"signal": "(datum.sourceNode.y + datum.targetNode.y) / 2"}, + "text": {"signal": "datum.doc_count"}, + "align": {"value": "center"}, + "baseline": {"value": "middle"}, + "fontSize": {"value": 11}, + "fill": {"value": "#555"} + } + } + }, + { + "type": "symbol", + "from": {"data": "nodes"}, + "encode": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "size": {"scale": "nodeSize", "field": "doc_count"}, + "fill": {"value": "#4C78A8"}, + "stroke": {"value": "#fff"}, + "strokeWidth": {"value": 2}, + "tooltip": {"signal": "datum.key + ': ' + datum.doc_count + ' docs'"} + } + } + }, + { + "type": "text", + "from": {"data": "nodes"}, + "encode": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "dy": {"value": -30}, + "text": {"field": "key"}, + "align": {"value": "center"}, + "fontSize": {"value": 12}, + "fontWeight": {"value": "bold"} + } + } + } + ] +} +``` +{% include copy.html %} + +The following image shows the resulting network graph. Node size represents the document count for each manufacturer, and edge thickness represents the number of orders containing products from both manufacturers. + +![Adjacency matrix network graph visualization in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/adjacency-graph.png) + +## Creating Vega visualizations from multiple data sources +Introduced 2.13 +{: .label .label-purple } + +Before proceeding, ensure that the following configuration settings are enabled in the `config/opensearch_dashboards.yaml` file. For configuration details, refer to the `vis_type_vega` [`README`](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/src/plugins/vis_type_vega/README.md). + +``` +data_source.enabled: true +vis_type_vega.enabled: true +``` + +After you have configured [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/) in OpenSearch Dashboards, you can use Vega to query those data sources. The following GIF shows the process of creating Vega visualizations in OpenSearch Dashboards. + +![Process of creating Vega visualizations in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/configure-vega.gif) + +### Step 1: Set up and connect data sources + +Open OpenSearch Dashboards and follow these steps: + +1. Select **Dashboards Management** from the menu on the left. +2. Select **Data sources** and then select the **Create data source** button. +3. On the **Create data source** page, enter the connection details and endpoint URL, as shown in the following GIF. +4. On the **Home page**, select **Add sample data**. Under **Data source**, select your newly created data source, and then select the **Add data button** for the **Sample web logs** dataset. + +The following GIF shows the steps required for setting up and connecting a data source. + +![Setting up and connecting data sources with OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/images/dashboards/Add_datasource.gif) + +### Step 2: Create the visualization + +1. From the menu on the left, select **Visualize**. +2. On the **Visualizations** page, select **Create Visualization** and then select **Vega** in the pop-up window. + +### Step 3: Add the Vega specification + +By default, queries use data from the local cluster. You can assign individual `data_source_name` values to each OpenSearch query in your Vega specification. This allows you to query multiple indexes across different data sources in a single visualization. + +1. Verify that the data source you created is specified under `data_source_name`. Alternatively, in your Vega specification, add the `data_source_name` field under the `url` property to target a specific data source by name. +2. Copy the following Vega specification and then select the **Update** button in the lower-right corner. The visualization should appear. + +```json +{ + $schema: https://vega.github.io/schema/vega-lite/v5.json + data: { + url: { + %context%: true + %timefield%: @timestamp + index: opensearch_dashboards_sample_data_logs + data_source_name: YOUR_DATA_SOURCE_TITLE + body: { + aggs: { + 1: { + date_histogram: { + field: @timestamp + fixed_interval: 3h + time_zone: America/Los_Angeles + min_doc_count: 1 + } + aggs: { + 2: { + avg: { + field: bytes + } + } + } + } + } + size: 0 + } + } + format: { + property: aggregations.1.buckets + } + } + transform: [ + { + calculate: datum.key + as: timestamp + } + { + calculate: datum[2].value + as: bytes + } + ] + layer: [ + { + mark: { + type: line + } + } + { + mark: { + type: circle + tooltip: true + } + } + ] + encoding: { + x: { + field: timestamp + type: temporal + axis: { + title: @timestamp + } + } + y: { + field: bytes + type: quantitative + axis: { + title: Average bytes + } + } + color: { + datum: Average bytes + type: nominal + } + } +} +``` +{% include copy.html %} + +## Querying Prometheus data using PromQL +Introduced 3.10 +{: .label .label-purple } + +You can use a Vega or Vega-Lite specification to query a Prometheus data connection using [Prometheus Query Language (PromQL)](https://prometheus.io/docs/prometheus/latest/querying/basics/). OpenSearch Dashboards runs the query on the server and inserts the results into the specification as inline `values`, so the browser makes no external HTTP calls. + +Before proceeding, ensure that you have configured a Prometheus data connection in OpenSearch Dashboards. For more information, see [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/). +{: .note} + +### Specification fields + +Add a `data.url` object and set `%type%` to `prometheus`. The `data.url` object supports the following fields. + +| Field | Required | Description | +|-------|----------|-------------| +| `%type%` | Yes | Must be set to `prometheus`. | +| `%datasource%` | Yes | The name of the Prometheus data connection as configured in OpenSearch Dashboards. | +| `%context%` | Yes | Must be set to `true`. Applies the dashboard time range to the PromQL query. | +| `body.query` | Yes | The PromQL expression to evaluate, for example, `rate(http_requests_total[5m])`. To run multiple expressions in one request, separate them with a semicolon (`;`). | +| `%maxdatapoints%` | No | The maximum number of data points per series. OpenSearch Dashboards calculates a step interval that keeps each series within this limit. Use this field to keep charts responsive over long time ranges. | +| `%step%` | No | The step interval, in seconds, for example, `60`. Takes precedence over `%maxdatapoints%` when both are provided. | + +### Response fields + +OpenSearch Dashboards returns one record per data point. Each record contains the following fields, which you can reference in Vega encodings. + +| Field | Type | Description | +|-------|------|-------------| +| `Time` | Number | The timestamp of the data point, in milliseconds since the Unix epoch. | +| `Series` | String | The full label set of the time series, formatted as a Prometheus metric string, for example, `up{job="node"}`. When `body.query` contains multiple expressions, each `Series` value starts with a letter that identifies its expression. For example, a `Series` value for the first expression is `A: up{job="node"}`. | +| `Labels` | Object | The individual labels of the series as key-value pairs, for example, `{"job": "node", "instance": "localhost:9100"}`. | +| `Value` | Number | The sample value at this timestamp. | + +### Example + +The following Vega-Lite specification creates a line chart that plots the per-second rate of HTTP requests over the dashboard time range: + +```json +{ + "$schema": "https://vega.github.io/schema/vega-lite/v5.json", + "data": { + "url": { + "%type%": "prometheus", + "%datasource%": "my_prometheus_connection", + "%context%": true, + "%maxdatapoints%": 500, + "body": { + "query": "rate(http_requests_total[5m])" + } + } + }, + "mark": "line", + "encoding": { + "x": { + "field": "Time", + "type": "temporal", + "axis": { "title": "Time" } + }, + "y": { + "field": "Value", + "type": "quantitative", + "axis": { "title": "Requests / second" } + }, + "color": { + "field": "Series", + "type": "nominal" + }, + "tooltip": [ + { "field": "Time", "type": "temporal" }, + { "field": "Series", "type": "nominal" }, + { "field": "Value", "type": "quantitative" } + ] + } +} +``` +{% include copy.html %} + +Replace `my_prometheus_connection` with the name of your configured Prometheus data connection. +{: .note} + +### Limitations + +- Vega PromQL queries support only Prometheus data connections on the local cluster. Data connections on remote clusters added through [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/) are not supported. +- If a query returns more than 2,000 series, OpenSearch Dashboards displays a warning and truncates the result. Narrow the PromQL query to reduce the number of series returned. +- If a PromQL result exceeds 30,000 data points, OpenSearch Dashboards displays a warning and truncates the result at a series boundary. Use `%maxdatapoints%` or `%step%` to reduce the number of data points returned. + +## Additional resources + +The following resources provide additional information about Vega visualizations in OpenSearch Dashboards: + +- [Improving ease of use in OpenSearch Dashboards with Vega visualizations](https://opensearch.org/blog/Improving-Dashboards-usability-with-Vega/) + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/visbuilder.md b/_dashboards/visualize/visualize-app/visbuilder.md new file mode 100644 index 00000000..a3bef3eb --- /dev/null +++ b/_dashboards/visualize/visualize-app/visbuilder.md @@ -0,0 +1,48 @@ +--- +layout: default +title: VisBuilder +parent: Visualization types +grand_parent: Creating visualizations in the Visualize application +great_grand_parent: Building data visualizations +nav_order: 190 +redirect_from: + - /dashboards/visualize/visbuilder/ + - /dashboards/drag-drop-wizard/ +--- + +# VisBuilder + +VisBuilder provides drag-and-drop visualization creation in OpenSearch Dashboards. With VisBuilder you have: + +* An immediate view of your data without the need to preselect the visualization output. +* The flexibility to change visualization types and index patterns quickly. +* The ability to easily navigate between multiple screens. + +## When to use VisBuilder + +Use VisBuilder for rapid exploration of data relationships through an intuitive drag-and-drop interface, reducing the time required to test hypotheses and explore data patterns without needing query language knowledge. + +## Creating a visualization using VisBuilder + +The examples on this page use the **Sample flight data** dataset. Before you begin, complete the [prerequisites]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/#prerequisites). +{: .note} + +To create a visualization using VisBuilder, follow these steps: + +1. In the **New Visualization** dialog, select **VisBuilder**, as shown in the following image. + + ![VisBuilder new visualization start page]({{site.url}}{{site.baseurl}}/images/dashboards/vis-builder-2.png) +2. From the **Data Source** dropdown, select **opensearch_dashboards_sample_data_flights**. +3. In the **Configuration** panel, add fields to the chart by dragging them from the field list on the left or by selecting the **+** icon in each section: + - **Y-axis**: Select the **+** icon, set **Aggregation** to **Average**, and set **Field** to **AvgTicketPrice**. + - **X-axis**: Select the **+** icon, set **Aggregation** to **Terms**, set **Field** to **Carrier**, and set **Order** to **Descending**. + - **Split series**: Select the **+** icon, set **Aggregation** to **Terms**, and set **Field** to **FlightDelay**. + +The chart updates automatically as you add fields. The **Split series** field divides each bar into color-coded subgroups. In this example, `FlightDelay` has two values (`true` and `false`), so each carrier shows two bars---one for delayed flights and one for non-delayed flights---in different colors, as shown in the following image. + +![VisBuilder bar chart showing average ticket price by carrier split by flight delay]({{site.url}}{{site.baseurl}}/images/dashboards/visbuilder-example.png) + +## Next steps + +- To choose a different visualization type, see [Visualization types]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/viz-types/). +- To add this visualization to a dashboard, see [Creating dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/). diff --git a/_dashboards/visualize/visualize-app/viz-types.md b/_dashboards/visualize/visualize-app/viz-types.md new file mode 100644 index 00000000..a8149ff9 --- /dev/null +++ b/_dashboards/visualize/visualize-app/viz-types.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Visualization types +parent: Creating visualizations in the Visualize application +grand_parent: Building data visualizations +nav_order: 5 +has_children: true +has_toc: false +description: "The recommended visualization types for creating data visualizations in OpenSearch Dashboards using the Visualize application, including charts, tables, and maps." +redirect_from: + - /dashboards/visualize/viz-types/ +--- + +# Visualization types + +The **Visualize** application supports the following visualization types, grouped by category. Each description includes guidance describing when the visualization type is most effective. For more information, see the individual visualization type pages. + +## Text visualizations + +Text visualizations display data using words and numbers rather than graphical elements. These provide detail and help key data stand out on a dashboard. + +| Visualization type | Description | +| :--- | :--- | +| [**Metric visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/metric/) <br><br> ![Metric]({{site.url}}{{site.baseurl}}/images/dashboards/metric-chart-1.png){: width="400" } | Displays a single numeric value prominently. Use for KPIs and summary statistics. | +| [**Tag clouds**]({{site.url}}{{site.baseurl}}/dashboards/visualize/tag-cloud/) <br><br> ![Tag cloud]({{site.url}}{{site.baseurl}}/images/dashboards/word-cloud-1.png){: width="400" } | Displays words sized by frequency or another metric. | +| [**Data tables**]({{site.url}}{{site.baseurl}}/dashboards/visualize/data-table/) <br><br> ![Data table]({{site.url}}{{site.baseurl}}/images/data-table-1.png){: width="400" } | Displays raw or aggregated data in tabular form. | + +## One-dimensional visualizations + +One-dimensional visualizations display a single bucketed data field, comparing values across categories or showing proportions. + +| Visualization type | Description | +| :--- | :--- | +| [**Gauge visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/gauge/) <br><br> ![Gauge]({{site.url}}{{site.baseurl}}/images/dashboards/gauge-1.png){: width="400" } | Displays a single value on a dial relative to defined ranges or thresholds. | +| [**Goal visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/goal/) <br><br> ![Goal]({{site.url}}{{site.baseurl}}/images/dashboards/example-goal-total-km.png){: width="400" } | Displays a single value on a progress bar relative to a target. | +| [**Pie charts**]({{site.url}}{{site.baseurl}}/dashboards/visualize/pie-charts/) <br><br> ![Pie chart]({{site.url}}{{site.baseurl}}/images/dashboards/pie-1.png){: width="400" } | Displays proportional data as slices of a circle. Use for part-to-whole comparisons. | + +## Multidimensional visualizations + +Multidimensional visualizations display one or more data fields as a function of another data field. The aggregations that bucket the data use numerical rather than categorical values. + +| Visualization type | Description | +| :--- | :--- | +| [**Bar charts**]({{site.url}}{{site.baseurl}}/dashboards/visualize/bar-charts/) <br><br> ![Vertical bar chart]({{site.url}}{{site.baseurl}}/images/dashboards/bar-chart-1.png){: width="400" } | Compare categorical data as vertical or horizontal bars. Use for ranking or comparing values across categories. | +| [**Area charts**]({{site.url}}{{site.baseurl}}/dashboards/visualize/area/) <br><br> ![Area chart]({{site.url}}{{site.baseurl}}/images/dashboards/area-chart-1.png){: width="400" } | Displays data as a filled region between a line and the axis. Use for showing volume over time or comparing stacked categories. | +| [**Heat maps**]({{site.url}}{{site.baseurl}}/dashboards/visualize/heat-map/) <br><br> ![Heat map]({{site.url}}{{site.baseurl}}/images/dashboards/heat-map-1.png){: width="400" } | Uses color intensity to represent values across two categorical dimensions. | +| [**Line charts**]({{site.url}}{{site.baseurl}}/dashboards/visualize/line-charts/) <br><br> ![Line chart]({{site.url}}{{site.baseurl}}/images/dashboards/line-1.png){: width="400" } | Plots data points connected by lines. Use for visualizing trends and changes over time. | + +## Map visualizations + +Map visualizations plot data based on geographic region or coordinate. + +| Visualization type | Description | +| :--- | :--- | +| [**Coordinate maps**]({{site.url}}{{site.baseurl}}/dashboards/visualize/coordinate-maps/) <br><br> ![Coordinate map]({{site.url}}{{site.baseurl}}/images/dashboards/coordinate-map-example.png){: width="400" } | Plots geographic data points on a map using latitude and longitude coordinates. | +| [**Region maps**]({{site.url}}{{site.baseurl}}/dashboards/visualize/region-maps/) <br><br> ![Region map]({{site.url}}{{site.baseurl}}/images/dashboards/map-1.png){: width="400" } | Colors geographic regions by aggregated value. Supports custom GeoJSON vector maps. | +| [**Maps application**]({{site.url}}{{site.baseurl}}/dashboards/visualize/maps/) <br><br> ![Maps]({{site.url}}{{site.baseurl}}/images/dashboards/coordinate-1.png){: width="400" } | A standalone mapping tool with multiple layer types, tooltips, filters, and labels. | + +## Utility visualizations + +Utility visualizations don't display data directly but support other visualizations in the context of a dashboard. + +| Visualization type | Description | +| :--- | :--- | +| [**Markdown visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/markdown/) <br><br> ![Markdown]({{site.url}}{{site.baseurl}}/images/dashboards/markdown.png){: width="400" } | Renders Markdown text alongside data visualizations for context and instructions. | +| [**Controls**]({{site.url}}{{site.baseurl}}/dashboards/visualize/controls/) <br><br> ![Controls]({{site.url}}{{site.baseurl}}/images/dashboards/controls-1.png){: width="400" } | Adds interactive filter panels (dropdown lists or range sliders) to a dashboard. | + +## Other tools + +The following visualization tools use specialized interfaces rather than the standard aggregation-based editor. + +| Visualization type | Description | +| :--- | :--- | +| [**PPL visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/ppl/) <br><br> ![PPL]({{site.url}}{{site.baseurl}}/images/dashboards/ppl-example.png){: width="400" } | Creates visualizations by entering PPL queries directly. | +| [**TSVB visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/tsvb/) <br><br> ![TSVB]({{site.url}}{{site.baseurl}}/images/dashboards/TSVB-1.png){: width="400" } | Creates detailed time-series visualizations with support for Area, Line, Metric, Gauge, Markdown, and Data Table types. | +| [**Vega visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/vega/) <br><br> ![Vega]({{site.url}}{{site.baseurl}}/images/dashboards/vega-1.png){: width="400" } | Uses the Vega and Vega-Lite declarative grammars for custom visualizations. | +| [**VisBuilder**]({{site.url}}{{site.baseurl}}/dashboards/visualize/visbuilder/) <br><br> ![VisBuilder]({{site.url}}{{site.baseurl}}/images/dashboards/vis-builder-2.png){: width="400" } | A drag-and-drop tool for creating visualizations without selecting a chart type in advance. | +| [**Timeline visualizations**]({{site.url}}{{site.baseurl}}/dashboards/visualize/timeline/) <br><br> ![Timeline]({{site.url}}{{site.baseurl}}/images/dashboards/timeline-1.png){: width="400" } | Uses a text-based expression syntax to create time-series visualizations. | diff --git a/_dashboards/workspace/apis.md b/_dashboards/workspace/apis.md new file mode 100644 index 00000000..1bd5de50 --- /dev/null +++ b/_dashboards/workspace/apis.md @@ -0,0 +1,420 @@ +--- +layout: default +title: Workspace APIs +parent: Workspaces +nav_order: 10 +--- + +# Workspace APIs +**Introduced 2.18** +{: .label .label-purple } + +Use the Workspace APIs to manage workspaces in OpenSearch Dashboards. + +These endpoints are served by OpenSearch Dashboards, so send requests to the OpenSearch Dashboards host and port (`5601` by default). Requests that use `POST`, `PUT`, or `DELETE` require the `osd-xsrf: true` header. Scripts written for Kibana OSS send the `kbn-xsrf: true` header instead, and OpenSearch Dashboards rejects these requests with the error `Request must contain a osd-xsrf header`. To fix this error, replace `kbn-xsrf` with `osd-xsrf` in your scripts. + +## List workspaces + +You can use the following endpoint to retrieve a list of workspaces: + +```json +POST {osd_host}:{port}/api/workspaces/_list +``` +{% include copy.html %} + +The following table lists the available path parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `search` | String | Optional | A query string used to filter workspaces with simple query syntax, for example, `simple_query_string`. | +| `searchFields` | Array | Optional | Specifies which fields to perform the search query against. | +| `sortField` | String | Optional | The field name to use for sorting results. | +| `sortOrder` | String | Optional | Specifies ascending or descending sort order. | +| `perPage` | Number | Optional | The number of workspace results per page. | +| `page` | Number | Optional | The number of pages of results to retrieve. | +| `permissionModes` | Array | Optional | A list of permissions to filter by. | + +#### Example request + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_list' \ + -d '{}' +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": { + "page": 1, + "per_page": 20, + "total": 1, + "workspaces": [ + { + "name": "test4", + "description": "test4", + "features": [ + "use-case-all" + ], + "lastUpdatedTime": "2025-09-10T14:47:04.741Z", + "id": "B9Le1w", + "permissionMode": "read" + } + ] + } +} +``` + +## Get a workspace + +You can use the following endpoint to retrieve a single workspace: + +```json +GET {osd_host}:{port}/api/workspaces/{id} +``` +{% include copy.html %} + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `<id>` | String | Required | Identifies the unique workspace to be retrieved. | + +#### Example request + +```json +curl -k -u admin:admin -X GET 'https://localhost:5601/api/workspaces/B9Le1w' +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": { + "name": "test4", + "description": "test4", + "features": [ + "use-case-all" + ], + "lastUpdatedTime": "2025-09-10T14:47:04.741Z", + "id": "B9Le1w" + } +} +``` + +## Create a workspace + +You can use the following endpoint to create a workspace: + +```json +POST {osd_host}:{port}/api/workspaces +``` +{% include copy.html %} + +The following table lists the available path parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `attributes` | Object | Required | Defines the workspace attributes. | +| `attributes.id` | String | Optional | The ID of the workspace. | +| `permissions` | Object | Optional | Specifies the permissions for the workspace. | +| `settings` | Object | Optional | Specifies the settings for the workspace. | + +#### Example request + +```json +curl -k -XPOST "https://localhost:5601/api/workspaces" \ + -H "Content-Type: application/json" \ + -H "osd-xsrf: true" \ + -d '{ + "attributes": { + "id": "my_workspace", + "name": "test4", + "description": "test4", + "features": ["use-case-all"] + } + }' -u admin:admin +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": { + "id": "B9Le1w" + } +} +``` + +## Update a workspace + +You can use the following endpoint to update the attributes and permissions for a workspace: + +```json +PUT {osd_host}:{port}/api/workspaces/{id} +``` +{% include copy.html %} + +The following table lists the available path parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `<id>` | String | Required | Identifies the unique workspace to be retrieved. | +| `attributes` | Object | Required | Defines the workspace attributes. | +| `permissions` | Object | Optional | Specifies the permissions for the workspace. | + +#### Example request without permissions object + +```json +curl -k -XPUT "https://localhost:5601/api/workspaces/B9Le1w" \ + -H "Content-Type: application/json" \ + -H "osd-xsrf: true" \ + -d '{ + "attributes": { + "name": "test5", + "description": "Updated description" + } + }' -u admin:admin +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": true +} +``` + +#### Example request with permissions object + +When a request includes a `permissions` object, each user or group must be assigned the set of permission modes required for the desired access level. For example, read-only access requires both the `library_read` and `read` permission modes: + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X PUT 'https://localhost:5601/api/workspaces/B9Le1w' \ + -d '{ + "attributes": {}, + "settings": { + "permissions": { + "library_write": { "users": ["obs-admin-user"] }, + "write": { "users": ["obs-admin-user"] }, + "library_read": { "groups": ["obs-read-users"] }, + "read": { "groups": ["obs-read-users"] } + } + } + }' +``` +{% include copy.html %} + +For a complete list of permission modes and the access levels they provide, see [Defining workspace collaborators]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#defining-workspace-collaborators). + +## Delete a workspace + +You can use the following endpoint to delete a workspace: + +```json +DELETE {osd_host}:{port}/api/workspaces/{id} +``` +{% include copy.html %} + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `<id>` | String | Required | Identifies the unique workspace to be retrieved. | + +#### Example request + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -X DELETE 'https://localhost:5601/api/workspaces/B9Le1w' +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": true +} +``` + +## Duplicate saved objects + +You can use the following endpoint to copy saved objects between workspaces: + +```json +POST {osd_host}:{port}/api/workspaces/_duplicate_saved_objects +``` +{% include copy.html %} + +The following table lists the available path parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `objects` | Array | Required | Specifies the saved objects to be duplicated. | +| `targetWorkspace` | String | Required | Identifies the destination workspace for copying. | +| `includeReferencesDeep` | Boolean | Optional | Determines whether to copy all referenced objects to the target workspace. Default is `true`. | + +The following table lists the attributes of the object in the `objects` parameter. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `type` | String | Required | Defines the saved object classification, such as `index-pattern`, `config`, or `dashboard`. | +| `id` | String | Required | The ID of the saved object. | + +#### Example request + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_duplicate_saved_objects' \ + -d '{ + "objects": [ + { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" } + ], + "targetWorkspace": "9gt4lB" + }' +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "successCount": 1, + "success": true, + "successResults": [ + { + "type": "index-pattern", + "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", + "meta": { + "title": "test*", + "icon": "indexPatternApp" + }, + "destinationId": "f4b724fd-9647-4bbf-bf59-610b43a62c75" + } + ] +} +``` + +## Associate saved objects + +You can use the following endpoint to associate saved objects with a workspace: + +```json +POST {osd_host}:{port}/api/workspaces/_associate +``` +{% include copy.html %} + +The following table lists the available path parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `workspaceId` | String | Required | Identifies the target workspace for object association. | +| `savedObjects` | Array | Required | Specifies the list of saved objects to be copied. | + +The following table lists the attributes of the object in the `savedObjects` parameter. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `type` | String | Required | Defines the saved object classification, such as `index-pattern`, `config`, or `dashboard`. | +| `id` | String | Required | The ID of the saved object. | + +#### Example request + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_associate' \ + -d '{ + "savedObjects": [ + { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" } + ], + "workspaceId": "9gt4lB" + }' +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": [ + { + "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", + } + ] +} +``` + +## Dissociate saved objects + +You can use the following endpoint to dissociate saved objects from a workspace: + +```json +POST {osd_host}:{port}/api/workspaces/_dissociate +``` +{% include copy.html %} + +The following table lists the available path parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `workspaceId` | String | Required | The target workspace with which to associate the objects. | +| `savedObjects` | Array | Required | A list of saved objects to copy. | + +The following table lists the attributes of the `savedObjects` parameter. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `type` | String | Required | The type of the saved object, such as `index-pattern`, `config`, or `dashboard`. | +| `id` | String | Required | The ID of the saved object. | + +#### Example request + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_dissociate' \ + -d '{ + "savedObjects": [ + { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" } + ], + "workspaceId": "9gt4lB" + }' + +``` +{% include copy.html %} + +The following example response shows a successful API call: + +```json +{ + "success": true, + "result": [ + { + "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", + } + ] +} +``` diff --git a/_dashboards/workspace/create-workspace.md b/_dashboards/workspace/create-workspace.md new file mode 100644 index 00000000..94968520 --- /dev/null +++ b/_dashboards/workspace/create-workspace.md @@ -0,0 +1,53 @@ +--- +layout: default +title: Create a workspace +parent: Workspaces +nav_order: 1 +--- + +# Create a workspace +**Introduced 2.18** +{: .label .label-purple } + +Before getting started with this tutorial, you must enable the workspace feature flag. See [Enabling workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace/#enabling-workspaces) for more information. + +When the saved objects permission is enabled, only users with admin status can create workspaces. See [Configuring the dashboard admin]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators) for more information. + +To create a workspace, follow these steps: + +1. Open OpenSearch Dashboards. +2. From the main page, choose the appropriate card for your use case, for example, **Observability**, **Security Analytics**, **Search**, **Essentials**, or **Analytics**. Alternatively, you can select the **Create workspace** button and choose the appropriate use case from the dropdown menu. +3. Enter the required information in the **Workspace details** window. + - **Workspace name** is required. Valid characters are `a-z`, `A-Z`, `0-9`, parentheses (`()`), brackets (`[]`), underscore (`_`), hyphen (`-`), and spaces. Choose a unique workspace name within the character limit (40 characters). The **Create workspace** button is disabled when the workspace name already exists or exceeds the character limit, and an error message appears. + - **Use case and features** is required. Choose the use case that best fits your needs. If you are using Amazon OpenSearch Serverless and have enabled the [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/) feature, **Essentials** is automatically assigned. +4. (Optional) Select the color picker to customize the color of your workspace icon. +5. (Optional) Add a workspace description of up to 200 characters. This option is disabled when the description exceeds the character limit. +6. (Optional) Enter a custom **Workspace ID**. If left blank, an ID is auto-generated. A custom ID must be 6--36 characters using only letters, numbers, underscores (`_`), and hyphens (`-`). If a workspace with the provided ID already exists, an error is returned. +7. Save your workspace. + - The **Create workspace** button becomes active once you enter the information for all required fields. You become the workspace owner automatically. The system redirects you to either the collaborators page if the saved objects permission is enabled or the overview page if the saved objects permission is disabled. See [Configuring dashboard admin]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators) for more information about permissions. + +To set up permissions, see [Workspace access control lists]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/) for more information. + +## Associating data sources with a workspace + +The **Associate data source** option is only visible when the multiple data sources feature is enabled. Before creating your workspace, you must connect it with at least one data source. If you have not set up your data sources, see [Data sources]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/). Once your sources are connected, you can link them to your new workspace. +{: .warning} + +### Associating OpenSearch data sources + +To associate OpenSearch data sources, follow these steps: + +1. Select the **Associate OpenSearch Data Sources** button to open the selection modal. +2. View the available data sources in the modal: + - Standard OpenSearch sources appear as single entries. + - Sources with direct query connections show a +N indicator. +3. Select the appropriate data source name(s). +4. Select the **Associate data sources** button to complete the association. + +### Associating direct query sources + +To associate direct query sources, follow these steps: + +1. Select the **Associate direct query data sources** button to open the selection modal. The modal displays only sources with direct query connections. +2. Select a data source to automatically expand its direct query connections. +3. Select the **Associate data sources** button to complete the association. diff --git a/_dashboards/workspace/index.md b/_dashboards/workspace/index.md new file mode 100644 index 00000000..22b1b96d --- /dev/null +++ b/_dashboards/workspace/index.md @@ -0,0 +1,29 @@ +--- +layout: default +title: Getting started with workspaces +parent: Workspaces +nav_order: 0 +redirect_from: + - /dashboards/workspace/ +--- + +# Getting started with workspaces +**Introduced 2.18** +{: .label .label-purple } + +OpenSearch Dashboards 2.18 introduces an enhanced home page that provides a comprehensive view of all your workspaces. + +The new home page includes the following features: + +1. A **Create workspace** button for [OpenSearch Dashboard admins]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators) to navigate to the [create workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/create-workspace/) page. +2. Workspace access time information and a link to the workspace overview page. +3. A use case information icon that displays information about the workspace's purpose. +4. A **View all workspaces** button that navigates to the [workspace management]({{site.url}}{{site.baseurl}}/dashboards/workspace/manage-workspace/#navigating-the-workspaces-list) page. +5. Links to the latest OpenSearch documentation through the **Learn more from documentation** button and to [OpenSearch Playground](https://playground.opensearch.org/app/home#/) through the **Explore live demo environment at playground.opensearch.org** button. + +The navigation logic ensures a seamless user experience by directing you to the appropriate page based on your workspace access level: + +- If a you have a default workspace configured, you are directed to the workspace overview page. +- If a you have only one workspace, you are directed to the overview page of that workspace. +- If a you have multiple workspaces, you are directed to the new home page. +- If a you have no workspaces, you are directed to the new home page. diff --git a/_dashboards/workspace/manage-workspace.md b/_dashboards/workspace/manage-workspace.md new file mode 100644 index 00000000..1d2d24a2 --- /dev/null +++ b/_dashboards/workspace/manage-workspace.md @@ -0,0 +1,135 @@ +--- +layout: default +title: Manage workspaces +parent: Workspaces +nav_order: 2 +--- + +# Manage workspaces +**Introduced 2.18** +{: .label .label-purple } + +You can access and modify the workspace details, including name, description, use case, and icon color, on the **Workspace details** page. + +To access and modify your workspace details, follow these steps: + +1. Open OpenSearch Dashboards and navigate to **My Workspaces**. +2. Choose the desired workspace and then select the **Edit** button to make changes +3. Select the **Save** button to confirm changes or the **Discard changes** button to cancel modifications. + +## Workspace update permissions + +The following permissions apply when changing workspaces: + +1. **Without the Security plugin:** All users can edit and update the workspace. +2. **With the Security plugin installed and `savedObjects.permission.enabled: false` in the `config/opensearch_dashboards.yml` file:** All users can edit and update workspaces. +3. **With the Security plugin and `savedObjects.permission.enabled: true` in the `config/opensearch_dashboards.yml`:** Only the [workspace owner]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#defining-workspace-collaborators) and the [workspace admins]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators) can edit and update workspaces. + +## Workspace update restrictions + +When updating workspace use cases, the following rules apply. + +Original use case | Target use case | +:---: | :---: +Analytics | Cannot be changed to any other use case +Search | Analytics +Security Analytics | Analytics +Observability | Analytics +Essentials | Analytics Search<br> Security Analytics<br> Observability + +## Workspace control panel + +The **Workspace details** page features the following buttons in the upper-right corner: + +1. **Delete** ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/} icon) + - **Without the Security plugin installed:** All users can delete the workspace. + - **With the Security plugins installed and `savedObjects.permission.enabled: false` in the `config/opensearch_dashboards.yml` file:** All users can delete the workspace. + - **With the Security plugin installed and `savedObjects.permission.enabled: true` in the `config/opensearch_dashboards.yml` file:** Only the admin can delete the workspace. +2. **Set as default workspace:** Sets the current workspace as the default login destination. +3. **Workspace overview:** Opens the **Overview** page in a new tab. + +## Adding assets to the workspace + +Access the **Sample data** in the navigation menu on the left. Select the appropriate dataset to install it in your cluster and OpenSearch Dashboards. + +## Migrating unassigned assets into a workspace + +Saved objects created before workspaces were enabled don't belong to any workspace. A workspace displays only the assets assigned to it, so these assets aren't visible in any workspace even though they still exist in the cluster. A [dashboard admin]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators) can move all unassigned assets into a new workspace using the migration wizard. + +When unassigned assets exist, the workspaces landing page displays a **Migrate existing assets (N)** button to dashboard admins, where N is the number of unassigned assets. + +To migrate unassigned assets into a new workspace, follow these steps: + +1. On the workspaces landing page, select **Migrate existing assets (N)**. +1. In the **Workspace name** field, enter a name for the new workspace. +1. Review the list of unassigned assets. You can search the list and filter it by asset type. The wizard migrates all unassigned assets, regardless of the search term or filter. +1. Select **Create workspace and migrate**. OpenSearch Dashboards creates the workspace, connects all data sources and data connections to it so that migrated dashboards continue to display data, and then migrates the assets. You can't close the wizard while the migration is running. +1. Review the summary, which shows the number of migrated assets, failed assets, and connected data sources. +1. Select **Go to \<workspace name\>** to open the new workspace. + +Assets that fail to migrate remain unassigned, and the summary lists each one with the reason it failed. To migrate them into the same workspace, select **Retry failed assets**. If the migration stops before it finishes, select **Continue migrating** to migrate the remaining assets into the same workspace. + +## Copying assets between workspaces + +Data sources and configuration copying are not supported. +{: .warning} + +The assets page provides the following methods for copying assets across workspaces: + +1. **Copy all assets to...:** Copies all assets in the table. +2. **Copy to...:** Moves selected assets from the table. +3. **Copy to...:** Copies a single asset from the table. + +After selecting a copy option, choose the target workspace from the dropdown menu. The **Copy related assets** checkbox allows you to transfer associated assets. + +Upon selecting the **Copy** button, a side panel appears showing successful and failed asset transfers. Asset copy destinations depend on the following security configurations: + +1. **Without the Security plugin:** All workspaces are accessible. +2. **With the Security plugin and `savedObjects.permission.enabled: false` in the `config/opensearch_dashboards.yml` file:** All workspaces are accessible. +3. **With the Security plugin and `savedObjects.permission.enabled: true` in the `config/opensearch_dashboards.yml` file:** Only workspaces for which the user has read and write or admin permissions are accessible. + +## Associating data sources + +On the data source management page, you can access a comprehensive list of associated OpenSearch connections, monitor direct query connections relevant to your current workspace, and establish new data source associations as needed. + +### Managing OpenSearch connections + +The OpenSearch connections tab displays all associated connections for the current workspace. Follow these steps to manage your connections: + +1. Access a comprehensive list of associated OpenSearch connections on the connections tab. +2. Use the **Remove association** button to unlink connections as needed. +3. Add new data sources by selecting the **OpenSearch data sources** button and subsequent modal. +4. Select from unassociated OpenSearch connections to expand your workspace's capabilities. + +### Adding direct query connections + +The **Direct query connections** tab displays a list of all direct query connections associated with your current workspace. To add more direct query connections to your workspace, select the **Direct query data sources** button. A modal window opens. + +The association modal displays a list of OpenSearch connections that contain direct query connections and have not yet been associated with your current workspace. When you associate an OpenSearch connection with your current workspace, all direct query connections within that OpenSearch connection are automatically associated as well. + +## Deleting your workspace + +Workspace deletion is restricted to admins. If you do not see a {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/} icon, check your permissions. See [Configuring dashboard administrators]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace-acl/#configuring-dashboard-administrators) for more information. +{: .warning} + +Deleting a workspace permanently erases all its assets (except data sources) and the workspace itself. This action cannot be reversed. + +To delete a workspace, follow these steps: + +1. From the **Workspace details** page, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/} (trash can) icon in the upper-right corner to delete the current workspace. +2. Alternatively, from the workspace list page, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/} (ellipsis) icon and select **Delete**. Optionally, select multiple workspaces for bulk deletion. + +## Navigating the workspaces list + +The workspaces list page serves as your central hub for workspace management, displaying all workspaces for which you have access permissions. Key features include the following: + +- Search: Quickly find a workspace by name. +- Filter: Sort workspaces by use case. +- At a glance: View each workspace's name, use case, description, last update time, and associated data sources. + +Each workspace entry includes an **Actions** column with the following functional buttons. These tools streamline your workspace management, allowing for efficient organization and customization of your OpenSearch Dashboards environment: + +1. Copy ID: One-click copying of the workspace ID. +2. Edit: Direct access to the workspace's detailed configuration page. +3. Set as default: Easily set any workspace as your default workspace. +4. Delete: Remove workspaces as needed (may require admin privileges). diff --git a/_dashboards/workspace/workspace-acl.md b/_dashboards/workspace/workspace-acl.md new file mode 100644 index 00000000..acac73a9 --- /dev/null +++ b/_dashboards/workspace/workspace-acl.md @@ -0,0 +1,207 @@ +--- +layout: default +title: Workspace access control lists +parent: Workspaces +nav_order: 3 +--- + +# Workspace access control lists +**Introduced 2.18** +{: .label .label-purple } + +Workspace access control lists (ACLs) manage authorization for saved objects while relying on the [Security plugin]({{site.url}}{{site.baseurl}}/security/) for authentication. + +## Personas + +**Workspace** use cases involve the following key personas: + +* **Dashboard admin:** Has full access to all OpenSearch Dashboards functions and data. +* **Workspace administrator (also called _owner_):** Has full control over a specific workspace, including its configuration and saved objects. When a workspace is created, its creator is automatically assigned the role of workspace owner. +* **Workspace content producer:** Can view, create, and update saved objects within the workspace. +* **Workspace viewer:** Has read-only access to saved objects in the workspace. + + Roles are workspace specific, allowing users to assume different roles across workspaces. + {: .note} + +## Enabling permission control + +See [Enabling the ACL feature]({{site.url}}{{site.baseurl}}/dashboards/management/acl#enabling-the-acl-feature) for instructions. + +## Configuring dashboard administrators + +To grant full access to all workspaces and objects in OpenSearch Dashboards, configure the admin permissions. Edit the `opensearch_dashboards.yml` file to define the admin by user ID and backend role, as shown in the following configuration: + +```yaml +opensearchDashboards.dashboardAdmin.users: ["UserID"] +opensearchDashboards.dashboardAdmin.groups: ["BackendRole"] +savedObjects.permission.enabled: true +``` +{% include copy.html %} + +By default, the configuration is set to `[]`, meaning that no users are designated as admins. If the Security plugin is not installed and `savedObjects.permission.enabled: false`, all users are granted admin permissions. + +### Configuring global admin access + +Set all users as admins with this wildcard setting: + +```yaml +opensearchDashboards.dashboardAdmin.users: ["*"] +``` +{% include copy.html %} + +### Configuring admin access for a single user + +Configure a user with the `admin-user-id` setting: + +```yaml +opensearchDashboards.dashboardAdmin.users: ["admin-user-id"] +``` +{% include copy.html %} + +### Configuring admin access by backend role + +Configure a user with the `admin-role` setting: + +```yaml +opensearchDashboards.dashboardAdmin.groups: ["admin-role"] +``` +{% include copy.html %} + +### Admin-restricted operations + +Admin-restricted operations include the following: + +- Workspace creation +- Workspace deletion +- Data source connections +- Disconnecting data sources from workspaces + +## Defining workspace collaborators + +Access to collaborator management is limited to admins. The **Collaborators** feature is only available when permission control is enabled. For instructions on activating permission control, see [Enabling permission control](#enabling-permission-control). Access levels include the following: + +- **Read only:** Grants permission to view the workspace and its assets. +- **Read and write:** Allows viewing and editing of assets within the workspace. +- **Admin:** Provides full access, including viewing and editing of assets within the workspace and updating workspace metadata, such as name, description, data sources, and collaborators. + +#### Permission modes + +When you assign collaborators through the UI, access levels are applied automatically. When you assign collaborators through the [Workspace APIs]({{site.url}}{{site.baseurl}}/dashboards/workspace/apis/), each access level corresponds to a specific combination of permission modes. The following table describes the available permission modes. + +| Permission mode | Target | Description | +| :--- | :--- | :--- | +| `read` | The workspace itself | The principal can open and view the workspace. | +| `write` | The workspace itself | The principal can manage the workspace itself: edit its name, description, and settings, manage collaborators, and associate data sources. | +| `library_read` | The saved objects (assets) in the workspace | The principal can view assets such as dashboards, visualizations, and index patterns. | +| `library_write` | The saved objects (assets) in the workspace | The principal can create, edit, and delete assets in the workspace. | + +Each access level requires one permission mode for the workspace and one permission mode for the workspace's assets, as listed in the following table. If a user or group is assigned only a partial combination of permission modes (for example, `read` without `library_read`), that user or group does not appear as a collaborator. + +| Access level | Required permission modes | +| :--- | :--- | +| Read only | `library_read` + `read` | +| Read and write | `library_write` + `read` | +| Admin | `library_write` + `write` | + +From the **Collaborators** page, you can search by collaborator ID and filter results by collaborator type and access level. + +### Adding collaborators + +Workspace creators are granted the **Admin** access level as a collaborator. To add more collaborators, select the **Add collaborators** button, which displays a dropdown menu. Choose **Add Users** or **Add Groups** to access the corresponding modal for adding new collaborators. + +#### Adding users + +To add users, follow these steps: + +1. Select the **Add Users** button to open the modal. The modal displays one empty `User ID` field by default. +2. Choose an access level: **Read only**, **Read and write**, or **Admin**. +3. Choose **Add another User** to add multiple users. Do not use duplicate or existing `User ID` fields to avoid errors. +4. Resolve any errors before finalizing. Successfully added users appear in the collaborators table. + +#### Adding groups + +To add groups, follow these steps: + +1. Select the **Add Groups** button to open the modal. The modal displays one empty `Group ID` field by default. +2. Choose an access level: **Read only**, **Read and write**, or **Admin**. +3. Use **Add another group** to add multiple groups. Do not use duplicate or existing `Group ID` fields to avoid errors. +4. Resolve any errors before finalizing. Successfully added groups appear in the collaborators table. + +### Modifying access levels + +You can modify collaborators' access levels after adding them to the collaborators table if you have the required permissions. Collaborators can be assigned any access level. However, if all **Admin** collaborators are changed to lower access levels, then only admins can manage workspace collaboration. + +#### Modifying individual access levels + +To modify a single collaborator's access level, follow these steps: + +1. Select the action icon on the right of the table row. +2. Select **Change access level** from the dropdown menu. +3. Choose the desired access level from the list. +4. Confirm the change in the modal that appears and select **Confirm**. The collaborator's access level is updated in the table upon confirmation. + +#### Modifying access levels in batch + +To change access levels for several collaborators simultaneously, follow these steps: + +1. Select the desired collaborator rows in the table. +2. Select the **Actions** button that appears. +3. Select **Change access level** from the dropdown menu. +4. Select the new access level from the list provided. +5. Review and confirm the changes in the modal that appears. The access levels for all selected collaborators are updated in the table upon confirmation. + +### Deleting collaborators + +After adding collaborators to the table, you have the option to delete them. Be cautious when removing admin collaborators because deleting all of them restricts workspace collaborator management to admins only. A confirmation modal is displayed before finalizing this action. + +#### Deleting individual collaborators + +To delete an individual collaborator, follow these steps: + +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/} icon on the right of the table row to display a dropdown menu. +2. Select **Delete collaborator** from the dropdown menu. A confirmation modal appears to verify your action. +3. Select **Confirm** in the modal to remove the collaborator from the table. + +#### Deleting collaborators in batch + +To remove several collaborators simultaneously, follow these steps: + +1. Select the rows containing the collaborators you want to remove from the table. A "Delete x collaborators" button appears. +2. Select the **Delete x collaborators** button. +3. Review the confirmation modal that appears. +4. Select **Confirm** to remove all selected collaborators from the table. + +## Configuring workspace privacy + +When permission control is enabled, workspace administrators can set one of the following three access levels: + +* **Private to collaborators (Default):** Only workspace collaborators can access the workspace. +* **Anyone can view:** Grants **Read only** permissions to all workspace users, allowing them to view workspace assets. +* **Anyone can edit:** Grants **Read and write** permissions to all users, allowing them to view, create, and update workspace assets. + +Collaborators receive whichever permission is higher: their individual access level or the workspace-wide privacy setting. For example, if workspace privacy is set to "Anyone can edit", a collaborator with read-only access can also edit workspace assets. +You can set up workspace privacy on the **Create workspace** page as a **Dashboard admin**. You can also modify it on the **Collaborators** or **Workspace details** pages as a **Workspace admin** or **Dashboard admin**. + +### Setting up workspace privacy during workspace creation + +Use the following steps to change workspace privacy settings when creating a new workspace: + +1. Choose the desired access level from the **Set up privacy** panel. +2. (Optional) Select the **Add collaborators after workspace creation** checkbox to add collaborators later. +3. Select **Create workspace** to create the workspace. + +### Modifying workspace privacy on the **Collaborators** page + +Use the following steps to edit the workspace privacy settings on the **Collaborators** page: + +1. Next to **Workspace privacy**, select **Edit**. +2. Select the new access level from the dropdown menu. +3. Select **Save changes** to apply the modifications. + +### Modifying workspace privacy on the **Workspace details** page + +Use the following steps to edit the workspace privacy settings on the **Workspace details** page: + +1. Select the **Edit** button in the upper-right corner of the **Details** panel. +2. Select the new access level from the dropdown menu. +3. Select **Save** to apply the modifications. diff --git a/_dashboards/workspace/workspace.md b/_dashboards/workspace/workspace.md new file mode 100644 index 00000000..00cde8c4 --- /dev/null +++ b/_dashboards/workspace/workspace.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Workspaces +nav_order: 120 +has_children: true +--- + +# Workspaces +**Introduced 2.18** +{: .label .label-purple } + +Workspaces enable you to tailor your environment with use-case-specific configurations. For example, you can create dedicated workspaces for observability scenarios, allowing you to focus on relevant functionalities. Additionally, you can organize visual assets, such as dashboards and visualizations, within a workspace with isolated storage. + +## Workspace data model + +The workspace data model is defined by the following structure: + +```typescript +interface Workspace { + id: string; + name: string; + description?: string; + features?: string[]; + color: string; + uiSettings: Record<string, unknown>; +} +``` +{% include copy.html %} + +The workspace data model is composed of the following key attributes: + +- `id`: String type; unique ID for each workspace. +- `name`: String type; designates the name of the workspace. +- `description`: Optional string type; provides contextual information for the workspace. +- `features`: Optional array of strings; contains use case IDs linked to the workspace. + +--- + +#### Example workspace object + +The following object shows a typical workspace configuration: + +```typescript +{ + id: "M5NqCu", + name: "Analytics team", + description: "Analytics team workspace", + features: ["use-case-analytics"], +} +``` +{% include copy.html %} + +The configuration creates the `Analytics team` using the `use-case-observability` feature set. Use cases map to specific feature groups, limiting functionality to the defined set within each workspace. + +The following are predefined use case options: + +- `use-case-observability` +- `use-case-security-analytics` +- `use-case-search` +- `use-case-essentials` +- `use-case-all` + +--- + +## Associating saved objects with workspaces + +Saved objects in OpenSearch Dashboards, such as dashboards, visualizations, and index patterns, can be associated with specific workspaces, improving organization and accessibility as the volume of objects grows. + +The `workspaces` attribute, an array of strings, is added to saved objects to be linked with one or more workspaces. As a result, saved objects such as dashboards and visualizations are only accessible within their designated workspaces. + +The following saved object shows a dashboard object associated with the workspace `M5NqCu`: + +```typescript +{ + type: "dashboard", + id: "da123f20-6680-11ee-93fa-df944ec23359", + workspaces: ["M5NqCu"] +} +``` +{% include copy.html %} + +Saved objects support association with multiple workspaces, facilitating cross-team collaboration and resource sharing. This feature is useful when an object is relevant to multiple teams, projects, or use cases. + +The following example shows a data source object linked to multiple workspaces: + +```typescript +{ + type: "data-source", + id: "da123f20-6680-11ee-93fa-df944ec23359", + workspaces: ["M5NqCu", "<TeamA-workspace-id>", "<Analytics-workspace-id>"] +} +``` +{% include copy.html %} + +## Non-workspace saved objects + +Not all saved objects in OpenSearch Dashboards are associated with a workspace. Some objects operate independently of the workspace framework. These objects lack `workspace` attributes and serve system-wide functions. For example, the global user interface settings object manages configurations affecting the entire OpenSearch Dashboards interface in order to maintain consistent functionality across all workspaces. + +This dual approach allows OpenSearch Dashboards to balance granular, context-specific customization with overall system consistency. + +## Enabling workspaces + +In your `opensearch_dashboards.yml` file, set the following options: + +```yaml +workspace.enabled: true +uiSettings: + overrides: + "home:useNewHomePage": true +``` +{% include copy.html %} + +If your cluster has the Security plugin installed, then multi-tenancy must be disabled to avoid conflicts with similar workspaces: + +```yaml +opensearch_security.multitenancy.enabled: false +``` +{% include copy.html %} + +After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. diff --git a/_data-prepper/common-use-cases/anomaly-detection.md b/_data-prepper/common-use-cases/anomaly-detection.md index e7003558..5084ea13 100644 --- a/_data-prepper/common-use-cases/anomaly-detection.md +++ b/_data-prepper/common-use-cases/anomaly-detection.md @@ -5,9 +5,9 @@ parent: Common use cases nav_order: 5 --- -# Anomaly detection +# Anomaly detection with Data Prepper -You can use Data Prepper to train models and generate anomalies in near real time on time-series aggregated events. You can generate anomalies either on events generated within the pipeline or on events coming directly into the pipeline, like OpenTelemetry metrics. You can feed these tumbling window aggregated time-series events to the [`anomaly_detector` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/anomaly-detector/), which trains a model and generates anomalies with a grade score. Then you can configure your pipeline to write the anomalies to a separate index to create document monitors and trigger fast alerting. +You can use OpenSearch Data Prepper to train models and generate anomalies in near real time on time-series aggregated events. You can generate anomalies either on events generated within the pipeline or on events coming directly into the pipeline, like OpenTelemetry metrics. You can feed these tumbling window aggregated time-series events to the [`anomaly_detector` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/anomaly-detector/), which trains a model and generates anomalies with a grade score. Then you can configure your pipeline to write the anomalies to a separate index to create document monitors and trigger fast alerting. ## Metrics from logs @@ -111,7 +111,7 @@ span-pipeline: pipeline: name: "entry-pipeline" processor: - - otel_trace_raw: + - otel_traces: sink: - opensearch: ... diff --git a/_data-prepper/common-use-cases/codec-processor-combinations.md b/_data-prepper/common-use-cases/codec-processor-combinations.md index 57185f2c..78dc944c 100644 --- a/_data-prepper/common-use-cases/codec-processor-combinations.md +++ b/_data-prepper/common-use-cases/codec-processor-combinations.md @@ -7,7 +7,7 @@ nav_order: 10 # Codec processor combinations -At ingestion time, data received by the [`s3` source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/) can be parsed by [codecs]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#codec). Codecs compresses and decompresses large data sets in a certain format before ingestion them through a Data Prepper pipeline [processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/). +At ingestion time, data received by the [`s3` source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/) can be parsed by [codecs]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#codec). Codecs compresses and decompresses large data sets in a certain format before ingestion them through an OpenSearch Data Prepper pipeline [processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/). While most codecs can be used with most processors, the following codec processor combinations can make your pipeline more efficient when used with the following input types. @@ -21,11 +21,11 @@ The JSON array does not require a processor. Unlike a JSON array, [NDJSON](https://www.npmjs.com/package/ndjson) allows for each row of data to be delimited by a newline, meaning data is processed per line instead of an array. -The NDJSON input type is parsed using the [newline]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#newline-codec) codec, which parses each single line as a single log event. The [parse_json]({{site.url}}{{site.baseurl}}data-prepper/pipelines/configuration/processors/parse-json/) processor then outputs each line as a single event. +The NDJSON input type is parsed using the [newline]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#newline-codec) codec, which parses each single line as a single log event. The [parse_json]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/parse-json/) processor then outputs each line as a single event. ## CSV -The CSV data type inputs data as a table. It can used without a codec or processor, but it does require one or the other, for example, either just the `csv` processor or the `csv` codec. +The CSV data type inputs data as a table. It can used without a codec or processor, but it does require one or the other, for example, either only the `csv` processor or the `csv` codec. The CSV input type is most effective when used with the following codec processor combinations. @@ -35,13 +35,19 @@ When the [`csv` codec]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/confi ### `newline` codec -The [`newline` codec]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#newline-codec) parses each row as a single log event. The codec will only detect a header when `header_destination` is configured. The [csv]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/csv/) processor then outputs the event into columns. The header detected in `header_destination` from the `newline` codec can be used in the `csv` processor under `column_names_source_key.` +The [`newline` codec]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#newline-codec) parses each row as a single log event. The codec will only detect a header when `header_destination` is configured. The [`csv`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/csv/) processor then outputs the event into columns. The header detected in `header_destination` from the `newline` codec can be used in the `csv` processor under `column_names_source_key.` ## Parquet -[Apache Parquet](https://parquet.apache.org/docs/overview/) is a columnar storage format built for Hadoop. It is most efficient without the use of a codec. Positive results, however, can be achieved when it's configured with [S3 Select]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#using-s3_select-with-the-s3-source). +[Apache Parquet](https://parquet.apache.org/docs/overview/) is a columnar storage format built for Hadoop. When configuring a pipeline, you can use the Parquet codec to read Parquet data directly from the Amazon Simple Storage Service (Amazon S3) object. This will retrieve all data from Parquet. Alternatively, you can use [S3 Select]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#using-s3_select-with-the-s3-source) instead of the codec. In this case, [S3 Select]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#using-s3_select-with-the-s3-source) parses the Parquet file directly. This can be more efficient if you are filtering or loading a subset of data. + +Additional S3 charges apply when using [S3 Select]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#using-s3_select-with-the-s3-source). +{: .note} ## Avro -[Apache Avro] helps streamline streaming data pipelines. It is most efficient when used with the [`avro` codec]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/s3#avro-codec) inside an `s3` sink. +[Apache Avro](https://avro.apache.org/docs) is a columnar storage format built for Hadoop. It is most efficient without the use of a codec. When used with [S3 Select]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3#using-s3_select-with-the-s3-source), Avro can deliver strong performance by enabling selective data retrieval. +## `event_json` + +The `event_json` output codec converts event data and metadata into JSON format to send to a sink, such as an S3 sink. The `event_json` input codec reads the event and its metadata to create an event in Data Prepper. diff --git a/_data-prepper/common-use-cases/common-use-cases.md b/_data-prepper/common-use-cases/common-use-cases.md index 342a8fc8..adca1141 100644 --- a/_data-prepper/common-use-cases/common-use-cases.md +++ b/_data-prepper/common-use-cases/common-use-cases.md @@ -9,4 +9,4 @@ redirect_from: # Common use cases -You can use Data Prepper for several different purposes, including trace analytics, log analytics, Amazon S3 log analytics, and metrics ingestion. \ No newline at end of file +You can use OpenSearch Data Prepper for several different purposes, including trace analytics, log analytics, Amazon S3 log analytics, and metrics ingestion. \ No newline at end of file diff --git a/_data-prepper/common-use-cases/event-aggregation.md b/_data-prepper/common-use-cases/event-aggregation.md index f6e2757d..4e1464b5 100644 --- a/_data-prepper/common-use-cases/event-aggregation.md +++ b/_data-prepper/common-use-cases/event-aggregation.md @@ -7,7 +7,7 @@ nav_order: 25 # Event aggregation -You can use Data Prepper to aggregate data from different events over a period of time. Aggregating events can help to reduce unnecessary log volume and manage use cases like multiline logs that are received as separate events. The [`aggregate` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/aggregate/) is a stateful processor that groups events based on the values for a set of specified identification keys and performs a configurable action on each group. +You can use OpenSearch Data Prepper to aggregate data from different events over a period of time. Aggregating events can help to reduce unnecessary log volume and manage use cases like multiline logs that are received as separate events. The [`aggregate` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/aggregate/) is a stateful processor that groups events based on the values for a set of specified identification keys and performs a configurable action on each group. The `aggregate` processor state is stored in memory. For example, in order to combine four events into one, the processor needs to retain pieces of the first three events. The state of an aggregate group of events is kept for a configurable amount of time. Depending on your logs, the aggregate action being used, and the number of memory options in the processor configuration, the aggregation could take place over a long period of time. diff --git a/_data-prepper/common-use-cases/log-analytics.md b/_data-prepper/common-use-cases/log-analytics.md index 30a021b1..4a5fcd7e 100644 --- a/_data-prepper/common-use-cases/log-analytics.md +++ b/_data-prepper/common-use-cases/log-analytics.md @@ -7,13 +7,13 @@ nav_order: 30 # Log analytics -Data Prepper is an extendable, configurable, and scalable solution for log ingestion into OpenSearch and Amazon OpenSearch Service. Data Prepper supports receiving logs from [Fluent Bit](https://fluentbit.io/) through the [HTTP Source](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/http-source/README.md) and processing those logs with a [Grok Processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/grok-processor/README.md) before ingesting them into OpenSearch through the [OpenSearch sink](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/opensearch/README.md). +OpenSearch Data Prepper is an extendable, configurable, and scalable solution for log ingestion into OpenSearch and Amazon OpenSearch Service. Data Prepper supports receiving logs from [Fluent Bit](https://fluentbit.io/) through the [HTTP Source](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/http-source/README.md) and processing those logs with a [Grok Processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/grok-processor/README.md) before ingesting them into OpenSearch through the [OpenSearch sink](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/opensearch/README.md). The following image shows all of the components used for log analytics with Fluent Bit, Data Prepper, and OpenSearch. ![Log analytics component]({{site.url}}{{site.baseurl}}/images/data-prepper/log-analytics/log-analytics-components.jpg) -In the application environment, run Fluent Bit. Fluent Bit can be containerized through Kubernetes, Docker, or Amazon Elastic Container Service (Amazon ECS). You can also run Fluent Bit as an agent on Amazon Elastic Compute Cloud (Amazon EC2). Configure the [Fluent Bit http output plugin](https://docs.fluentbit.io/manual/pipeline/outputs/http) to export log data to Data Prepper. Then deploy Data Prepper as an intermediate component and configure it to send the enriched log data to your OpenSearch cluster. From there, use OpenSearch Dashboards to perform more intensive visualization and analysis. +In the application environment, run Fluent Bit. Fluent Bit can be containerized through Kubernetes, Docker, or Amazon Elastic Container Service (Amazon ECS). You can also run Fluent Bit as an agent on Amazon Elastic Compute Cloud (Amazon EC2). Configure the [Fluent Bit HTTP output plugin](https://docs.fluentbit.io/manual/pipeline/outputs/http) to export log data to Data Prepper. Then deploy Data Prepper as an intermediate component and configure it to send the enriched log data to your OpenSearch cluster. From there, use OpenSearch Dashboards to perform more intensive visualization and analysis. ## Log analytics pipeline @@ -27,7 +27,7 @@ The [HTTP Source](https://github.com/opensearch-project/data-prepper/blob/main/d ### Processor -Data Prepper 1.2 and above come with a [Grok Processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/grok-processor/README.md). The Grok Processor is an invaluable tool for structuring and extracting important fields from your logs, making them more queryable. +Data Prepper 1.2 and later come with a [Grok Processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/grok-processor/README.md). The Grok Processor is an invaluable tool for structuring and extracting important fields from your logs, making them easier to query. The Grok Processor comes with a wide variety of [default patterns](https://github.com/thekrakken/java-grok/blob/master/src/main/resources/patterns/patterns) that match common log formats like Apache logs or syslogs, but it can easily accept any custom patterns that cater to your specific log format. @@ -66,8 +66,8 @@ log-pipeline: hosts: [ "https://localhost:9200" ] # Change to your credentials username: "admin" - password: "admin" - # Add a certificate file if you are accessing an OpenSearch cluster with a self-signed certificate + password: "<custom-admin-password>" + # Add a certificate file if you are accessing an OpenSearch cluster with a self-signed certificate #cert: /path/to/cert # If you are connecting to an Amazon OpenSearch Service domain without # Fine-Grained Access Control, enable these settings. Comment out the @@ -78,6 +78,7 @@ log-pipeline: # You should change this to correspond with how your OpenSearch indexes are set up. index: apache_logs ``` +{% include copy.html %} This pipeline configuration is an example of Apache log ingestion. Don't forget that you can easily configure the Grok Processor for your own custom logs. You will need to modify the configuration for your OpenSearch cluster. @@ -92,7 +93,7 @@ The following are the main changes you need to make: ## Fluent Bit -You will need to run Fluent Bit in your service environment. See [Getting Started with Fluent Bit](https://docs.fluentbit.io/manual/installation/getting-started-with-fluent-bit) for installation instructions. Ensure that you can configure the [Fluent Bit http output plugin](https://docs.fluentbit.io/manual/pipeline/outputs/http) to your Data Prepper HTTP source. The following is an example `fluent-bit.conf` that tails a log file named `test.log` and forwards it to a locally running Data Prepper HTTP source, which runs by default on port 2021. +You will need to run Fluent Bit in your service environment. See [Getting Started with Fluent Bit](https://docs.fluentbit.io/manual/installation/getting-started-with-fluent-bit) for installation instructions. Ensure that you can configure the [Fluent Bit HTTP output plugin](https://docs.fluentbit.io/manual/pipeline/outputs/http) to your Data Prepper HTTP source. The following is an example `fluent-bit.conf` that tails a log file named `test.log` and forwards it to a locally running Data Prepper HTTP source, which runs by default on port 2021. Note that you should adjust the file `path`, output `Host`, and `Port` according to how and where you have Fluent Bit and Data Prepper running. @@ -100,7 +101,7 @@ Note that you should adjust the file `path`, output `Host`, and `Port` according The following is an example `fluent-bit.conf` file without SSL and basic authentication enabled on the HTTP source: -``` +```text [INPUT] name tail refresh_interval 5 @@ -115,6 +116,7 @@ The following is an example `fluent-bit.conf` file without SSL and basic authent URI /log/ingest Format json ``` +{% include copy.html %} If your HTTP source has SSL and basic authentication enabled, you will need to add the details of `http_User`, `http_Passwd`, `tls.crt_file`, and `tls.key_file` to the `fluent-bit.conf` file, as shown in the following example. @@ -122,7 +124,7 @@ If your HTTP source has SSL and basic authentication enabled, you will need to a The following is an example `fluent-bit.conf` file with SSL and basic authentication enabled on the HTTP source: -``` +```text [INPUT] name tail refresh_interval 5 @@ -142,11 +144,12 @@ The following is an example `fluent-bit.conf` file with SSL and basic authentica URI /log/ingest Format json ``` +{% include copy.html %} # Next steps See the [Data Prepper Log Ingestion Demo Guide](https://github.com/opensearch-project/data-prepper/blob/main/examples/log-ingestion/README.md) for a specific example of Apache log ingestion from `FluentBit -> Data Prepper -> OpenSearch` running through Docker. -In the future, Data Prepper will offer additional sources and processors that will make more complex log analytics pipelines available. Check out the [Data Prepper Project Roadmap](https://github.com/opensearch-project/data-prepper/projects/1) to see what is coming. +In the future, Data Prepper will offer additional sources and processors that will make more complex log analytics pipelines available. Check out the [Data Prepper Project Roadmap](https://github.com/orgs/opensearch-project/projects/221) to see what is coming. -If there is a specific source, processor, or sink that you would like to include in your log analytics workflow and is not currently on the roadmap, please bring it to our attention by creating a GitHub issue. Additionally, if you are interested in contributing to Data Prepper, see our [Contributing Guidelines](https://github.com/opensearch-project/data-prepper/blob/main/CONTRIBUTING.md) as well as our [developer guide](https://github.com/opensearch-project/data-prepper/blob/main/docs/developer_guide.md) and [plugin development guide](https://github.com/opensearch-project/data-prepper/blob/main/docs/plugin_development.md). +If there is a specific source, processor, or sink that you would like to include in your log analytics workflow and is not currently on the roadmap, create a GitHub issue. Additionally, if you are interested in contributing to Data Prepper, see our [Contributing Guidelines](https://github.com/opensearch-project/data-prepper/blob/main/CONTRIBUTING.md) as well as our [developer guide](https://github.com/opensearch-project/data-prepper/blob/main/docs/developer_guide.md) and [plugin development guide](https://github.com/opensearch-project/data-prepper/blob/main/docs/plugin_development.md). diff --git a/_data-prepper/common-use-cases/log-enrichment.md b/_data-prepper/common-use-cases/log-enrichment.md index b4004251..c09fdec6 100644 --- a/_data-prepper/common-use-cases/log-enrichment.md +++ b/_data-prepper/common-use-cases/log-enrichment.md @@ -7,7 +7,7 @@ nav_order: 35 # Log enrichment -You can perform different types of log enrichment with Data Prepper, including: +You can perform different types of log enrichment with OpenSearch Data Prepper, including: - Filtering. - Extracting key-value pairs from strings. @@ -20,7 +20,7 @@ You can perform different types of log enrichment with Data Prepper, including: Use the [`drop_events`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/drop-events/) processor to filter out specific log events before sending them to a sink. For example, if you're collecting web request logs and only want to store unsuccessful requests, you can create the following pipeline, which drops any requests for which the response is less than 400 so that only log events with HTTP status codes of 400 and higher remain. -```json +```yaml log-pipeline: source: ... @@ -52,22 +52,22 @@ To perform analysis using the search terms, you can extract the value of `q` fro The following example combines the `split_string` and `key_value` processors to extract query parameters from an Apache log line: -```json -pipeline +```yaml +pipeline: ... processor: - grok: - match: - message: [ "%{COMMONAPACHELOG_DATATYPED}" ] + match: + message: [ "%{COMMONAPACHELOG_DATATYPED}" ] - split_string: - entries: - - source: request - delimiter: "?" + entries: + - source: request + delimiter: "?" - key_value: - source: "/request/1" - field_split_characters: "&" - value_split_characters: "=" - destination: query_params + source: "/request/1" + field_split_characters: "&" + value_split_characters: "=" + destination: query_params ``` {% include copy-curl.html %} @@ -77,20 +77,20 @@ The different [mutate event]({{site.url}}{{site.baseurl}}/data-prepper/pipelines In this example, the first processor sets the value of the `debug` key to `true` if the key already exists in the event. The second processor only sets the `debug` key to `true` if the key doesn't exist in the event because `overwrite_if_key_exists` is set to `true`. -```json +```yaml ... processor: - add_entries: - entries: - - key: "debug" - value: true + entries: + - key: "debug" + value: true ... processor: - add_entries: - entries: - - key: "debug" - value: true - overwrite_if_key_exists: true + entries: + - key: "debug" + value: true + overwrite_if_key_exists: true ... ``` {% include copy-curl.html %} @@ -99,12 +99,12 @@ You can also use a format string to construct new entries from existing events. For example, the following pipeline adds new event entries dynamically from existing events: -```json +```yaml processor: - add_entries: - entries: - - key: "key_three" - format: "${key_one}-${key_two} + entries: + - key: "key_three" + format: "${key_one}-${key_two} ``` {% include copy-curl.html %} @@ -133,13 +133,13 @@ The processor transforms it into an event with a new key named `key_three`, whic The various [mutate string]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/mutate-string/) processors offer tools that you can use to manipulate strings in incoming data. For example, if you need to split a string into an array, you can use the `split_string` processor: -```json +```yaml ... processor: - split_string: - entries: - - source: "message" - delimiter: "&" + entries: + - source: "message" + delimiter: "&" ... ``` {% include copy-curl.html %} @@ -152,15 +152,15 @@ The [`list_to_map`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configur For example, consider the following processor configuration: -```json +```yaml ... processor: - - list_to_map: - key: "name" - source: "A-car-as-list" - target: "A-car-as-map" - value_key: "value" - flatten: true + - list_to_map: + key: "name" + source: "A-car-as-list" + target: "A-car-as-map" + value_key: "value" + flatten: true ... ``` {% include copy-curl.html %} @@ -230,20 +230,19 @@ As another example, consider an incoming event with the following structure: You can define the following options in the processor configuration: -```json +```yaml ... processor: - - list_to_map: - key: "somekey" - source: "mylist" - target: "myobject" - value_key: "value" - flatten: true + - list_to_map: + key: "somekey" + source: "mylist" + target: "myobject" + flatten: true ... ``` {% include copy-curl.html %} -The processor modifies the event by removing `mylist` and adding the new `myobject` object: +The processor modifies the event by adding the new `myobject` object: ```json { @@ -266,6 +265,7 @@ The processor modifies the event by removing `mylist` and adding the new `myobje "somevalue" : "val-b3", "anothervalue" : "val-b4" } + ] "c" : [ { "somekey" : "c", @@ -278,21 +278,22 @@ The processor modifies the event by removing `mylist` and adding the new `myobje ``` {% include copy-curl.html %} -In many cases, you may want to flatten the array for each key. In these situations, you must choose only one object to retain. The processor offers a choice of either first or last. For example, consider the following: +In many cases, you may want to flatten the array for each key. In these situations, you can choose which object to retain. The processor offers a choice of either first or last. For example, consider the following: -```json +```yaml ... processor: - - list_to_map: - key: "somekey" - source: "mylist" - target: "myobject" - flatten: true + - list_to_map: + key: "somekey" + source: "mylist" + target: "myobject" + flatten: true + flattened_element: first ... ``` {% include copy-curl.html %} -The incoming event structure is then flattened accordingly: +The fields in the newly created `myobject` are then flattened accordingly: ```json { @@ -321,7 +322,7 @@ The incoming event structure is then flattened accordingly: The [`date`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/date/) processor parses the `timestamp` key from incoming events by converting it to International Organization for Standardization (ISO) 8601 format: -```json +```yaml ... processor: - date: @@ -357,9 +358,9 @@ It converts the event to the following format: The `date` processor can generate timestamps for incoming events if you specify `@timestamp` for the `destination` option: -```json +```yaml ... - processor: + processor: - date: from_time_received: true destination: "@timestamp" @@ -371,24 +372,27 @@ The `date` processor can generate timestamps for incoming events if you specify The [`substitute_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/substitute-string/) processor (which is one of the mutate string processors) lets you derive a punctuation pattern from incoming events. In the following example pipeline, the processor will scan incoming Apache log events and derive punctuation patterns from them: -```json +```yaml processor: - - substitute_string: - entries: - - source: "message" - from: "[a-zA-Z0-9_]+" - to:"" + - substitute_string: + entries: - source: "message" - from: "[ ]+" - to: "_" + from: "[a-zA-Z0-9_]+" + to:"" + - source: "message" + from: "[ ]+" + to: "_" ``` {% include copy-curl.html %} -The following incoming Apache HTTP log will generate a punctuation pattern: +The following incoming Apache HTTP log: ```json [{"message":"10.10.10.11 - admin [19/Feb/2015:15:50:36 -0500] \"GET /big2.pdf HTTP/1.1\" 200 33973115 0.202 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36\""}] +``` +Generates the following punctuation pattern: +```json {"message":"..._-_[//:::_-]_\"_/._/.\"_._\"-\"_\"/._(;_)_/._(,_)_/..._/.\""} ``` {% include copy-curl.html %} diff --git a/_data-prepper/common-use-cases/metrics-logs.md b/_data-prepper/common-use-cases/metrics-logs.md new file mode 100644 index 00000000..fc0518ce --- /dev/null +++ b/_data-prepper/common-use-cases/metrics-logs.md @@ -0,0 +1,70 @@ +--- +layout: default +title: Deriving metrics from logs +parent: Common use cases +nav_order: 15 +--- + +# Deriving metrics from logs + +You can use OpenSearch Data Prepper to derive metrics from logs. + +The following example pipeline receives incoming logs using the [`http` source plugin]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/http-source) and the [`grok` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/grok/). It then uses the [`aggregate` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/aggregate/) to extract the metric bytes aggregated during a 30-second window and derives histograms from the results. + +This pipeline writes data to two different OpenSearch indexes: + +- `logs`: This index stores the original, un-aggregated log events after being processed by the `grok` processor. +- `histogram_metrics`: This index stores the derived histogram metrics extracted from the log events using the `aggregate` processor. + +The pipeline contains two sub-pipelines: + +- `apache-log-pipeline-with-metrics`: Receives logs through an HTTP client like FluentBit, using `grok` to extract important values from the logs by matching the value in the log key against the [Apache Common Log Format](https://httpd.apache.org/docs/2.4/logs.html#accesslog). It then forwards the grokked logs to two destinations: + + - An OpenSearch index named `logs` to store the original log events. + - The `log-to-metrics-pipeline` for further aggregation and metric derivation. + +- `log-to-metrics-pipeline`: Receives the grokked logs from the `apache-log-pipeline-with-metrics` pipeline, aggregates the logs, and derives histogram metrics of bytes based on the values in the `clientip` and `request` keys. Finally, it sends the derived histogram metrics to an OpenSearch index named `histogram_metrics`. + +#### Example pipeline + +```json +apache-log-pipeline-with-metrics: + source: + http: + # Provide the path for ingestion. ${pipelineName} will be replaced with pipeline name configured for this pipeline. + # In this case it would be "/apache-log-pipeline-with-metrics/logs". This will be the FluentBit output URI value. + path: "/${pipelineName}/logs" + processor: + - grok: + match: + log: [ "%{COMMONAPACHELOG_DATATYPED}" ] + sink: + - opensearch: + ... + index: "logs" + - pipeline: + name: "log-to-metrics-pipeline" + +log-to-metrics-pipeline: + source: + pipeline: + name: "apache-log-pipeline-with-metrics" + processor: + - aggregate: + # Specify the required identification keys + identification_keys: ["clientip", "request"] + action: + histogram: + # Specify the appropriate values for each of the following fields + key: "bytes" + record_minmax: true + units: "bytes" + buckets: [0, 25000000, 50000000, 75000000, 100000000] + # Pick the required aggregation period + group_duration: "30s" + sink: + - opensearch: + ... + index: "histogram_metrics" +``` +{% include copy-curl.html %} diff --git a/_data-prepper/common-use-cases/metrics-traces.md b/_data-prepper/common-use-cases/metrics-traces.md index c15eaa09..2cd0dafb 100644 --- a/_data-prepper/common-use-cases/metrics-traces.md +++ b/_data-prepper/common-use-cases/metrics-traces.md @@ -7,7 +7,7 @@ nav_order: 20 # Deriving metrics from traces -You can use Data Prepper to derive metrics from OpenTelemetry traces. The following example pipeline receives incoming traces and extracts a metric called `durationInNanos`, aggregated over a tumbling window of 30 seconds. It then derives a histogram from the incoming traces. +You can use OpenSearch Data Prepper to derive metrics from OpenTelemetry traces. The following example pipeline receives incoming traces and extracts a metric called `durationInNanos`, aggregated over a tumbling window of 30 seconds. It then derives a histogram from the incoming traces. The pipeline contains the following pipelines: diff --git a/_data-prepper/common-use-cases/s3-logs.md b/_data-prepper/common-use-cases/s3-logs.md index 7986a7ee..334713b8 100644 --- a/_data-prepper/common-use-cases/s3-logs.md +++ b/_data-prepper/common-use-cases/s3-logs.md @@ -7,8 +7,7 @@ nav_order: 40 # S3 logs -Data Prepper allows you to load logs from [Amazon Simple Storage Service](https://aws.amazon.com/s3/) (Amazon S3), including traditional logs, JSON documents, and CSV logs. - +OpenSearch Data Prepper allows you to load logs from [Amazon Simple Storage Service](https://aws.amazon.com/s3/) (Amazon S3), including traditional logs, JSON documents, and CSV logs. ## Architecture @@ -18,9 +17,9 @@ Data Prepper polls the Amazon SQS queue for S3 event notifications. When Data Pr The following diagram shows the overall architecture of the components involved. -<img src="{{site.url}}{{site.baseurl}}/images/data-prepper/s3-source/s3-architecture.jpg" alt="S3 source architecture">{: .img-fluid} +![S3 source architecture]({{site.url}}{{site.baseurl}}/images/data-prepper/s3-source/s3-architecture.jpg) -The flow of data is as follows. +The component data flow is as follows: 1. A system produces logs into the S3 bucket. 2. S3 creates an S3 event notification in the SQS queue. @@ -28,14 +27,13 @@ The flow of data is as follows. 4. Data Prepper downloads the content from the S3 object. 5. Data Prepper sends a document to OpenSearch for the content in the S3 object. - ## Pipeline overview Data Prepper supports reading data from S3 using the [`s3` source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/). The following diagram shows a conceptual outline of a Data Prepper pipeline reading from S3. -<img src="{{site.url}}{{site.baseurl}}/images/data-prepper/s3-source/s3-pipeline.jpg" alt="S3 source architecture">{: .img-fluid} +![S3 source architecture]({{site.url}}{{site.baseurl}}/images/data-prepper/s3-source/s3-pipeline.jpg) ## Prerequisites @@ -44,21 +42,19 @@ Before Data Prepper can read log data from S3, you need the following prerequisi - An S3 bucket. - A log producer that writes logs to S3. The exact log producer will vary depending on your specific use case, but could include writing logs to S3 or a service such as Amazon CloudWatch. - ## Getting started Use the following steps to begin loading logs from S3 with Data Prepper. 1. Create an [SQS standard queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/step-create-queue.html) for your S3 event notifications. 2. Configure [bucket notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ways-to-add-notification-config-to-bucket.html) for SQS. Use the `s3:ObjectCreated:*` event type. -3. Grant [AWS IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) permissions to Data Prepper for accessing SQS and S3. +3. Grant [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) permissions to Data Prepper for accessing SQS and S3. 4. (Recommended) Create an [SQS dead-letter queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) (DLQ). 5. (Recommended) Configure an SQS re-drive policy to move failed messages into the DLQ. ### Setting permissions for Data Prepper -To view S3 logs, Data Prepper needs access to Amazon SQS and S3. -Use the following example to set up permissions: +To view S3 logs, Data Prepper needs access to Amazon SQS and S3. Use the following example to set up permissions: ```json { @@ -88,24 +84,25 @@ Use the following example to set up permissions: ] } ``` +{% include copy-curl.html %} If your S3 objects or SQS queues do not use KMS, you can remove the `kms:Decrypt` permission. ### SQS dead-letter queue -The are two options for how to handle errors resulting from processing S3 objects. +The following two options can be used to handle S3 object processing errors: - Use an SQS dead-letter queue (DLQ) to track the failure. This is the recommended approach. - Delete the message from SQS. You must manually find the S3 object and correct the error. The following diagram shows the system architecture when using SQS with DLQ. -<img src="{{site.url}}{{site.baseurl}}/images/data-prepper/s3-source/s3-architecture-dlq.jpg" alt="S3 source architecture with dlq">{: .img-fluid} +![S3 source architecture with DLQ]({{site.url}}{{site.baseurl}}/images/data-prepper/s3-source/s3-architecture-dlq.jpg) To use an SQS dead-letter queue, perform the following steps: -1. Create a new SQS standard queue to act as your DLQ. -2. Configure your SQS's redrive policy [to use your DLQ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue.html). Consider using a low value such as 2 or 3 for the "Maximum Receives" setting. +1. Create a new SQS standard queue to act as the DLQ. +2. Configure your SQS re-drive policy [to use DLQ](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue.html). Consider using a low value such as 2 or 3 for the **Maximum Receives** setting. 3. Configure the Data Prepper `s3` source to use `retain_messages` for `on_error`. This is the default behavior. ## Pipeline design @@ -123,8 +120,9 @@ s3-log-pipeline: sqs: # Change this value to your SQS Queue URL queue_url: "arn:aws:sqs:<YOUR-REGION>:<123456789012>:<YOUR-SQS-QUEUE>" - visibility_timeout: "2m" + visibility_timeout: "PT2M" ``` +{% include copy-curl.html %} Configure the following options according to your use case: @@ -145,7 +143,7 @@ s3-log-pipeline: sqs: # Change this value to your SQS Queue URL queue_url: "arn:aws:sqs:<YOUR-REGION>:<123456789012>:<YOUR-SQS-QUEUE>" - visibility_timeout: "2m" + visibility_timeout: "PT2M" aws: # Specify the correct region region: "<YOUR-REGION>" @@ -161,13 +159,14 @@ s3-log-pipeline: hosts: [ "https://localhost:9200" ] # Change to your credentials username: "admin" - password: "admin" + password: "<custom-admin-password>" index: s3_logs ``` +{% include copy-curl.html %} ## Multiple Data Prepper pipelines -We recommend that you have one SQS queue per Data Prepper pipeline. In addition, you can have multiple nodes in the same cluster reading from the same SQS queue, which doesn't require additional configuration with Data Prepper. +It is recommended that you have one SQS queue per Data Prepper pipeline. In addition, you can have multiple nodes in the same cluster reading from the same SQS queue, which doesn't require additional Data Prepper configuration. If you have multiple pipelines, you must create multiple SQS queues for each pipeline, even if both pipelines use the same S3 bucket. @@ -175,6 +174,55 @@ If you have multiple pipelines, you must create multiple SQS queues for each pip To meet the scale of logs produced by S3, some users require multiple SQS queues for their logs. You can use [Amazon Simple Notification Service](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) (Amazon SNS) to route event notifications from S3 to an SQS [fanout pattern](https://docs.aws.amazon.com/sns/latest/dg/sns-common-scenarios.html). Using SNS, all S3 event notifications are sent directly to a single SNS topic, where you can subscribe to multiple SQS queues. -To make sure that Data Prepper can directly parse the event from the SNS topic, configure [raw message delivery](https://docs.aws.amazon.com/sns/latest/dg/sns-large-payload-raw-message-delivery.html) on the SNS to SQS subscription. Setting this option will not affect other SQS queues that are subscribed to that SNS topic. +To make sure that Data Prepper can directly parse the event from the SNS topic, configure [raw message delivery](https://docs.aws.amazon.com/sns/latest/dg/sns-large-payload-raw-message-delivery.html) on the SNS-to-SQS subscription. Applying this option does not affect other SQS queues subscribed to the SNS topic. +## Filtering and retrieving data using Amazon S3 Select +If a pipeline uses an S3 source, you can use SQL expressions to perform filtering and computations on the contents of S3 objects before ingesting them into the pipeline. + +The `s3_select` option supports objects in the [Parquet File Format](https://parquet.apache.org/docs/). It also works with objects that are compressed with gzip or BZIP2 (for CSV and JSON objects only) and supports columnar compression for the Parquet File Format using gzip and Snappy. + +Refer to [Filtering and retrieving data using Amazon S3 Select](https://docs.aws.amazon.com/AmazonS3/latest/userguide/selecting-content-from-objects.html) and [SQL reference for Amazon S3 Select](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-select-sql-reference.html) for comprehensive information about using Amazon S3 Select. +{: .note} + +The following example pipeline retrieves all data from S3 objects encoded in the Parquet File Format: + +```json +pipeline: + source: + s3: + s3_select: + expression: "select * from s3object s" + input_serialization: parquet + notification_type: "sqs" +... +``` +{% include copy-curl.html %} + +The following example pipeline retrieves only the first 10,000 records in the objects: + +```json +pipeline: + source: + s3: + s3_select: + expression: "select * from s3object s LIMIT 10000" + input_serialization: parquet + notification_type: "sqs" +... +``` +{% include copy-curl.html %} + +The following example pipeline retrieves records from S3 objects that have a `data_value` in the given range of 200--500: + +```json +pipeline: + source: + s3: + s3_select: + expression: "select s.* from s3object s where s.data_value > 200 and s.data_value < 500 " + input_serialization: parquet + notification_type: "sqs" +... +``` +{% include copy-curl.html %} diff --git a/_data-prepper/common-use-cases/sampling.md b/_data-prepper/common-use-cases/sampling.md index 7c77e8c3..47bead46 100644 --- a/_data-prepper/common-use-cases/sampling.md +++ b/_data-prepper/common-use-cases/sampling.md @@ -7,7 +7,7 @@ nav_order: 45 # Sampling -Data Prepper provides the following sampling capabilities: +OpenSearch Data Prepper provides the following sampling capabilities: - Time sampling - Percentage sampling diff --git a/_data-prepper/common-use-cases/text-processing.md b/_data-prepper/common-use-cases/text-processing.md index 041ca63a..1fc81c5d 100644 --- a/_data-prepper/common-use-cases/text-processing.md +++ b/_data-prepper/common-use-cases/text-processing.md @@ -7,7 +7,7 @@ nav_order: 55 # Text processing -Data Prepper provides text processing capabilities with the [`grok processor`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/grok/). The `grok` processor is based on the [`java-grok`](https://mvnrepository.com/artifact/io.krakens/java-grok) library and supports all compatible patterns. The `java-grok` library is built using the [`java.util.regex`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/package-summary.html) regular expression library. +OpenSearch Data Prepper provides text processing capabilities with the [`grok processor`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/grok/). The `grok` processor is based on the [`java-grok`](https://mvnrepository.com/artifact/io.krakens/java-grok) library and supports all compatible patterns. The `java-grok` library is built using the [`java.util.regex`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/package-summary.html) regular expression library. You can add custom patterns to your pipelines by using the `patterns_definitions` option. When debugging custom patterns, the [Grok Debugger](https://grokdebugger.com/) can be helpful. diff --git a/_data-prepper/common-use-cases/trace-analytics.md b/_data-prepper/common-use-cases/trace-analytics.md index 1f6c3b7c..8a24ba5c 100644 --- a/_data-prepper/common-use-cases/trace-analytics.md +++ b/_data-prepper/common-use-cases/trace-analytics.md @@ -5,9 +5,9 @@ parent: Common use cases nav_order: 60 --- -# Trace analytics +# Trace analytics with Data Prepper -Trace analytics allows you to collect trace data and customize a pipeline that ingests and transforms the data for use in OpenSearch. The following provides an overview of the trace analytics workflow in Data Prepper, how to configure it, and how to visualize trace data. +Trace analytics allows you to collect trace data and customize a pipeline that ingests and transforms the data for use in OpenSearch. The following provides an overview of the trace analytics workflow in OpenSearch Data Prepper, how to configure it, and how to visualize trace data. ## Introduction @@ -15,32 +15,32 @@ When using Data Prepper as a server-side component to collect trace data, you ca The following flowchart illustrates the trace analytics workflow, from running OpenTelemetry Collector to using OpenSearch Dashboards for visualization. -<img src="{{site.url}}{{site.baseurl}}/images/data-prepper/trace-analytics/trace-analytics-components.jpg" alt="Trace analytics component overview">{: .img-fluid} +![Trace analytics component overview]({{site.url}}{{site.baseurl}}/images/data-prepper/trace-analytics/trace-analytics-components.jpg) To monitor trace analytics, you need to set up the following components in your service environment: - Add **instrumentation** to your application so it can generate telemetry data and send it to an OpenTelemetry collector. -- Run an **OpenTelemetry collector** as a sidecar or daemonset for Amazon Elastic Kubernetes Service (Amazon EKS), a sidecar for Amazon Elastic Container Service (Amazon ECS), or an agent on Amazon Elastic Compute Cloud (Amazon EC2). You should configure the collector to export trace data to Data Prepper. +- Run an **OpenTelemetry collector** as a sidecar or `daemonset` for Amazon Elastic Kubernetes Service (Amazon EKS), a sidecar for Amazon Elastic Container Service (Amazon ECS), or an agent on Amazon Elastic Compute Cloud (Amazon EC2). You should configure the collector to export trace data to Data Prepper. - Deploy **Data Prepper** as the ingestion collector for OpenSearch. Configure it to send the enriched trace data to your OpenSearch cluster or to the Amazon OpenSearch Service domain. - Use **OpenSearch Dashboards** to visualize and detect problems in your distributed applications. ## Trace analytics pipeline -To monitor trace analytics in Data Prepper, we provide three pipelines: `entry-pipeline`, `raw-trace-pipeline`, and `service-map-pipeline`. The following image provides an overview of how the pipelines work together to monitor trace analytics. +A trace analytics configuration consists of three pipelines: `entry-pipeline`, which receives trace data, and `raw-trace-pipeline` and `service-map-pipeline`, which process it. The following image shows how the pipelines work together. -<img src="{{site.url}}{{site.baseurl}}/images/data-prepper/trace-analytics/trace-analytics-pipeline.jpg" alt="Trace analytics pipeline overview">{: .img-fluid} +![Trace analytics pipeline overview]({{site.url}}{{site.baseurl}}/images/data-prepper/trace-analytics/trace-analytics-pipeline.png) ### OpenTelemetry trace source -The [OpenTelemetry source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-trace-raw/) accepts trace data from the OpenTelemetry Collector. The source follows the [OpenTelemetry Protocol](https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/protocol) and officially supports transport over gRPC and the use of industry-standard encryption (TLS/HTTPS). +The [OpenTelemetry trace source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace-source/) accepts trace data from the OpenTelemetry Collector. The source follows the [OpenTelemetry Protocol](https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/protocol) and officially supports transport over gRPC and the use of industry-standard encryption (TLS/HTTPS). ### Processor There are three processors for the trace analytics feature: -* *otel_traces_raw* - The *otel_traces_raw* processor receives a collection of [span](https://github.com/opensearch-project/data-prepper/blob/fa65e9efb3f8d6a404a1ab1875f21ce85e5c5a6d/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/trace/Span.java) records from [*otel-trace-source*]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace/), and performs stateful processing, extraction, and completion of trace-group-related fields. -* *otel_traces_group* - The *otel_traces_group* processor fills in the missing trace-group-related fields in the collection of [span](https://github.com/opensearch-project/data-prepper/blob/298e7931aa3b26130048ac3bde260e066857df54/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/trace/Span.java) records by looking up the OpenSearch backend. -* *service_map_stateful* – The *service_map_stateful* processor performs the required preprocessing for trace data and builds metadata to display the `service-map` dashboards. +* `otel_traces` -- The `otel_traces` processor receives a collection of [span](https://github.com/opensearch-project/data-prepper/blob/fa65e9efb3f8d6a404a1ab1875f21ce85e5c5a6d/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/trace/Span.java) records from [`otel-trace-source`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace-source/), and performs stateful processing, extraction, and completion of trace-group-related fields. +* `otel_trace_group` -- The `otel_trace_group` processor fills in the missing trace-group-related fields in the collection of [span](https://github.com/opensearch-project/data-prepper/blob/298e7931aa3b26130048ac3bde260e066857df54/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/trace/Span.java) records by looking up the OpenSearch backend. +* `service_map` -- The `service_map` processor performs the required preprocessing for trace data and builds metadata to display the `service-map` dashboards. ### OpenSearch sink @@ -49,14 +49,14 @@ OpenSearch provides a generic sink that writes data to OpenSearch as the destina The sink provides specific configurations for the trace analytics feature. These configurations allow the sink to use indexes and index templates specific to trace analytics. The following OpenSearch indexes are specific to trace analytics: -* *otel-v1-apm-span* – The *otel-v1-apm-span* index stores the output from the [otel_traces_raw]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-trace-raw/) processor. -* *otel-v1-apm-service-map* – The *otel-v1-apm-service-map* index stores the output from the [service_map_stateful]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/service-map-stateful/) processor. +* `otel-v1-apm-span` -- The `otel-v1-apm-span` index stores the output from the [`otel_traces`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-traces/) processor. +* `otel-v1-apm-service-map` -- The `otel-v1-apm-service-map` index stores the output from the [`service_map`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/service-map/) processor. ## Trace tuning Starting with version 0.8.x, Data Prepper supports both vertical and horizontal scaling for trace analytics. You can adjust the size of a single Data Prepper instance to meet your workload's demands and scale vertically. -You can scale horizontally by using the core [peer forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/) to deploy multiple Data Prepper instances to form a cluster. This enables Data Prepper instances to communicate with instances in the cluster and is required for horizontally scaling deployments. +You can scale horizontally by using the core [Peer Forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/) to deploy multiple Data Prepper instances to form a cluster. This enables Data Prepper instances to communicate with instances in the cluster and is required for horizontally scaling deployments. ### Scaling recommendations @@ -64,12 +64,12 @@ Use the following recommended configurations to scale Data Prepper. We recommend #### Buffer -The total number of trace requests processed by Data Prepper is equal to the sum of the `buffer_size` values in `otel-trace-pipeline` and `raw-pipeline`. The total number of trace requests sent to OpenSearch is equal to the product of `batch_size` and `workers` in `raw-trace-pipeline`. For more information about `raw-pipeline`, see [Trace analytics pipeline]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines). +The total number of trace requests processed by Data Prepper is equal to the sum of the `buffer_size` values in `entry-pipeline` and `raw-trace-pipeline`. The total number of trace requests sent to OpenSearch is equal to the product of `batch_size` and `workers` in `raw-trace-pipeline`. For more information about `raw-trace-pipeline`, see [Trace analytics pipeline]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines). We recommend the following when making changes to buffer settings: - * The `buffer_size` value in `otel-trace-pipeline` and `raw-pipeline` should be the same. - * The `buffer_size` should be greater than or equal to `workers` * `batch_size` in the `raw-pipeline`. + * The `buffer_size` value in `entry-pipeline` and `raw-trace-pipeline` should be the same. + * The `buffer_size` should be greater than or equal to `workers` * `batch_size` in the `raw-trace-pipeline`. #### Workers @@ -114,59 +114,60 @@ The following sections provide examples of different types of pipelines and how The following example demonstrates how to build a pipeline that supports the [OpenSearch Dashboards Observability plugin]({{site.url}}{{site.baseurl}}/observability-plugin/trace/ta-dashboards/). This pipeline takes data from the OpenTelemetry Collector and uses two other pipelines as sinks. These two separate pipelines serve two different purposes and write to different OpenSearch indexes. The first pipeline prepares trace data for OpenSearch and enriches and ingests the span documents into a span index within OpenSearch. The second pipeline aggregates traces into a service map and writes service map documents into a service map index within OpenSearch. -Starting with Data Prepper version 2.0, Data Prepper no longer supports the `otel_traces_raw_prepper` processor. The `otel_traces_raw` processor replaces the `otel_traces_raw_prepper` processor and supports some of Data Prepper's recent data model changes. Instead, you should use the `otel_traces_raw` processor. See the following YAML file example: +Starting with Data Prepper version 2.0, Data Prepper no longer supports the `otel_traces_prepper` processor. The `otel_traces` processor replaces the `otel_traces_prepper` and `otel_trace_raw` processors and supports some of Data Prepper's recent data model changes. The following is an example YAML file configuration: -```yml +```yaml entry-pipeline: delay: "100" source: - otel_traces_source: + otel_trace_source: ssl: false buffer: bounded_blocking: - buffer_size: 10240 - batch_size: 160 + buffer_size: 500000 + batch_size: 10000 sink: - pipeline: - name: "raw-trace-pipeline" + name: raw-trace-pipeline - pipeline: - name: "service-map-pipeline" -raw-pipeline: + name: service-map-pipeline +raw-trace-pipeline: source: pipeline: - name: "entry-pipeline" + name: entry-pipeline buffer: bounded_blocking: - buffer_size: 10240 - batch_size: 160 + buffer_size: 500000 + batch_size: 10000 processor: - - otel_traces_raw: + - otel_traces: sink: - opensearch: hosts: ["https://localhost:9200"] insecure: true username: admin - password: admin + password: "<custom-admin-password>" index_type: trace-analytics-raw service-map-pipeline: delay: "100" source: pipeline: - name: "entry-pipeline" + name: entry-pipeline buffer: bounded_blocking: - buffer_size: 10240 - batch_size: 160 + buffer_size: 500000 + batch_size: 10000 processor: - - service_map_stateful: + - service_map: sink: - opensearch: hosts: ["https://localhost:9200"] insecure: true username: admin - password: admin + password: "<custom-admin-password>" index_type: trace-analytics-service-map ``` +{% include copy.html %} To maintain similar ingestion throughput and latency, scale the `buffer_size` and `batch_size` by the estimated maximum batch size in the client request payload. {: .tip} @@ -176,78 +177,81 @@ The following is an example `otel-trace-source` .yaml file with SSL and basic au ```yaml source: - otel_traces_source: + otel_trace_source: #record_type: event # Add this when using Data Prepper 1.x. This option is removed in 2.0 ssl: true - sslKeyCertChainFile: "/full/path/to/certfile.crt" - sslKeyFile: "/full/path/to/keyfile.key" + sslKeyCertChainFile: /full/path/to/certfile.crt + sslKeyFile: /full/path/to/keyfile.key authentication: http_basic: - username: "my-user" - password: "my_s3cr3t" + username: my-user + password: my_s3cr3t ``` +{% include copy.html %} #### Example: pipeline.yaml -The following is an example `pipeline.yaml` file without SSL and basic authentication enabled for the `otel-trace-pipeline` pipeline: +The following is an example `pipeline.yaml` file without SSL and basic authentication enabled for the `entry-pipeline` pipeline: ```yaml -otel-trace-pipeline: - # workers is the number of threads processing data in each pipeline. +entry-pipeline: + # workers is the number of threads processing data in each pipeline. # We recommend same value for all pipelines. # default value is 1, set a value based on the machine you are running Data Prepper - workers: 8 + workers: 8 # delay in milliseconds is how often the worker threads should process data. # Recommend not to change this config as we want the entry-pipeline to process as quick as possible # default value is 3_000 ms - delay: "100" + delay: "100" source: - otel_traces_source: + otel_trace_source: #record_type: event # Add this when using Data Prepper 1.x. This option is removed in 2.0 - ssl: false # Change this to enable encryption in transit + ssl: false authentication: unauthenticated: buffer: bounded_blocking: - # buffer_size is the number of ExportTraceRequest from otel-collector the data prepper should hold in memeory. - # We recommend to keep the same buffer_size for all pipelines. - # Make sure you configure sufficient heap - # default value is 512 - buffer_size: 512 - # This is the maximum number of request each worker thread will process within the delay. - # Default is 8. - # Make sure buffer_size >= workers * batch_size - batch_size: 8 + # buffer_size is the number of ExportTraceRequest from otel-collector the Data Prepper should hold in memory. + # We recommend to keep the same buffer_size for all pipelines. + # Make sure you configure sufficient heap + # default value is 512 + buffer_size: 500000 + # This is the maximum number of request each worker thread will process within the delay. + # Default is 8. + # Make sure buffer_size >= workers * batch_size + batch_size: 10000 sink: - pipeline: - name: "raw-trace-pipeline" + name: raw-trace-pipeline - pipeline: - name: "entry-pipeline" -raw-pipeline: - # Configure same as the otel-trace-pipeline - workers: 8 - # We recommend using the default value for the raw-pipeline. - delay: "3000" + name: service-map-pipeline + +raw-trace-pipeline: + # Configure same as the entry-pipeline + workers: 8 + # We recommend using the default value for the raw-trace-pipeline. + delay: 3000 source: - pipeline: - name: "entry-pipeline" + pipeline: + name: entry-pipeline buffer: - bounded_blocking: - # Configure the same value as in entry-pipeline - # Make sure you configure sufficient heap - # The default value is 512 - buffer_size: 512 - # The raw processor does bulk request to your OpenSearch sink, so configure the batch_size higher. - # If you use the recommended otel-collector setup each ExportTraceRequest could contain max 50 spans. https://github.com/opensearch-project/data-prepper/tree/v0.7.x/deployment/aws - # With 64 as batch size each worker thread could process upto 3200 spans (64 * 50) - batch_size: 64 + bounded_blocking: + # Configure the same value as in entry-pipeline + # Make sure you configure sufficient heap + # The default value is 512 + buffer_size: 500000 + # The raw processor does bulk request to your OpenSearch sink, so configure the batch_size higher. + # If you use the recommended otel-collector setup each ExportTraceRequest could contain max 50 spans. https://github.com/opensearch-project/data-prepper/tree/v0.7.x/deployment/aws + # With 64 as batch size each worker thread could process upto 3200 spans (64 * 50) + batch_size: 10000 processor: - - otel_traces_raw: - - otel_traces_group: - hosts: [ "https://localhost:9200" ] + - otel_traces: + # Optional: only if you want the group-filler stage. + - otel_trace_group: + hosts: [ "https://opensearch:9200" ] # Change to your credentials - username: "admin" - password: "admin" + username: admin + password: "<custom-admin-password>" # Add a certificate file if you are accessing an OpenSearch cluster with a self-signed certificate #cert: /path/to/cert # If you are connecting to an Amazon OpenSearch Service domain without @@ -257,11 +261,11 @@ raw-pipeline: #aws_region: us-east-1 sink: - opensearch: - hosts: [ "https://localhost:9200" ] + hosts: [ "https://opensearch:9200" ] index_type: trace-analytics-raw # Change to your credentials - username: "admin" - password: "admin" + username: admin + password: "<custom-admin-password>" # Add a certificate file if you are accessing an OpenSearch cluster with a self-signed certificate #cert: /path/to/cert # If you are connecting to an Amazon OpenSearch Service domain without @@ -269,36 +273,37 @@ raw-pipeline: # username and password above. #aws_sigv4: true #aws_region: us-east-1 + service-map-pipeline: workers: 8 - delay: "100" + delay: 100 source: - pipeline: - name: "entry-pipeline" + pipeline: + name: entry-pipeline processor: - - service_map_stateful: - # The window duration is the maximum length of time the data prepper stores the most recent trace data to evaluvate service-map relationships. + - service_map: + # The window duration is the maximum length of time the data prepper stores the most recent trace data to evaluvate service-map relationships. # The default is 3 minutes, this means we can detect relationships between services from spans reported in last 3 minutes. - # Set higher value if your applications have higher latency. - window_duration: 180 + # Set higher value if your applications have higher latency. + window_duration: 180 buffer: - bounded_blocking: - # buffer_size is the number of ExportTraceRequest from otel-collector the data prepper should hold in memeory. - # We recommend to keep the same buffer_size for all pipelines. - # Make sure you configure sufficient heap - # default value is 512 - buffer_size: 512 - # This is the maximum number of request each worker thread will process within the delay. - # Default is 8. - # Make sure buffer_size >= workers * batch_size - batch_size: 8 + bounded_blocking: + # buffer_size is the number of ExportTraceRequest from otel-collector the Data Prepper should hold in memory. + # We recommend to keep the same buffer_size for all pipelines. + # Make sure you configure sufficient heap + # default value is 512 + buffer_size: 500000 + # This is the maximum number of request each worker thread will process within the delay. + # Default is 8. + # Make sure buffer_size >= workers * batch_size + batch_size: 10000 sink: - opensearch: - hosts: [ "https://localhost:9200" ] + hosts: [ "https://opensearch:9200" ] index_type: trace-analytics-service-map # Change to your credentials - username: "admin" - password: "admin" + username: admin + password: "<custom-admin-password>" # Add a certificate file if you are accessing an OpenSearch cluster with a self-signed certificate #cert: /path/to/cert # If you are connecting to an Amazon OpenSearch Service domain without @@ -306,7 +311,9 @@ service-map-pipeline: # username and password above. #aws_sigv4: true #aws_region: us-east-1 + ``` +{% include copy.html %} You need to modify the preceding configuration for your OpenSearch cluster so that the configuration matches your environment. Note that it has two `opensearch` sinks that need to be modified. {: .note} @@ -324,37 +331,255 @@ For other configurations available for OpenSearch sinks, see [Data Prepper OpenS You need to run OpenTelemetry Collector in your service environment. Follow [Getting Started](https://opentelemetry.io/docs/collector/getting-started/#getting-started) to install an OpenTelemetry collector. Ensure that you configure the collector with an exporter configured for your Data Prepper instance. The following example `otel-collector-config.yaml` file receives data from various instrumentations and exports it to Data Prepper. -### Example otel-collector-config.yaml file +### Example setup using Docker compose -The following is an example `otel-collector-config.yaml` file: +The following is an example configuration for OpenSearch, OpenSearch Dashboards, Data Prepper, and OpenTelemetry Collector using Docker containers. +Create certificates you will use for Data Prepper and store them in the `certs` directory: + +```bash +mkdir -p certs + +# single self-signed server cert for Data Prepper; adds SAN=DNS:data-prepper +openssl req -x509 -nodes -newkey rsa:2048 \ + -keyout certs/dp.key \ + -out certs/dp.crt \ + -days 365 \ + -subj "/CN=data-prepper" \ + -addext "subjectAltName = DNS:data-prepper" ``` +{% include copy.html %} + +Create the following files: + +`docker-compose.yaml` file: + + +```yaml +version: "3.8" + +networks: + opensearch-net: + +services: + opensearch: + image: opensearchproject/opensearch:3.2.0 + environment: + - discovery.type=single-node + - OPENSEARCH_INITIAL_ADMIN_PASSWORD=<strong_password> + - bootstrap.memory_lock=true + - "OPENSEARCH_JAVA_OPTS=-Xms1g -Xmx1g" + ulimits: + memlock: { soft: -1, hard: -1 } + nofile: { soft: 65536, hard: 65536 } + ports: + - "9200:9200" + networks: [opensearch-net] + + dashboards: + image: opensearchproject/opensearch-dashboards:3.2.0 + environment: + OPENSEARCH_HOSTS: '["https://opensearch:9200"]' + OPENSEARCH_USERNAME: admin + # password must match OpenSearch + OPENSEARCH_PASSWORD: "<strong_password>" + ports: + - "5601:5601" + depends_on: [opensearch] + networks: [opensearch-net] + + data-prepper: + image: opensearchproject/data-prepper:latest + command: ["/usr/share/data-prepper/bin/data-prepper"] + volumes: + - ./pipelines:/usr/share/data-prepper/pipelines:ro + - ./config/data-prepper-config.yaml:/usr/share/data-prepper/config/data-prepper-config.yaml:ro + - ./certs:/usr/share/data-prepper/certs:ro + ports: + # Data Prepper control API (HTTP) + - "4900:4900" + # OTLP gRPC (TLS) + - "21890:21890" + depends_on: [opensearch] + networks: [opensearch-net] + + otel-collector: + image: otel/opentelemetry-collector:latest + command: ["--config=/etc/otelcol/otel-collector.yaml"] + volumes: + - ./otel-collector.yaml:/etc/otelcol/otel-collector.yaml:ro + depends_on: [data-prepper] + networks: [opensearch-net] + ports: + # OTLP gRPC + - "4317:4317" + # OTLP HTTP (optional) + - "4318:4318" +``` +{% include copy.html %} + + +Follow the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements) to set a strong admin password. +{: .note} + +`pipelines/pipelines.yaml` file: + +```yaml +entry-pipeline: + source: + otel_trace_source: + port: 21890 + ssl: true + sslKeyCertChainFile: "certs/dp.crt" + sslKeyFile: "certs/dp.key" + authentication: + unauthenticated: + buffer: + bounded_blocking: + buffer_size: 500000 + batch_size: 10000 + sink: + - pipeline: + name: raw-trace-pipeline + - pipeline: + name: service-map-pipeline + +raw-trace-pipeline: + source: + pipeline: + name: entry-pipeline + processor: + - otel_traces: + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: trace-analytics-raw + +service-map-pipeline: + source: + pipeline: + name: entry-pipeline + processor: + - service_map: + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: trace-analytics-service-map +``` +{% include copy.html %} + +`config/data-prepper-config.yaml` file: + +```yaml +# Disable TLS on the Data Prepper REST API (local only) +ssl: false +serverPort: 4900 + +peer_forwarder: + ssl: false + discovery_mode: local_node +``` +{% include copy.html %} + +`otel-collector.yaml` file: + +```yaml receivers: - jaeger: - protocols: - grpc: otlp: protocols: grpc: - zipkin: - -processors: - batch/traces: - timeout: 1s - send_batch_size: 50 + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 exporters: - otlp/data-prepper: - endpoint: localhost:21890 + otlp: + endpoint: data-prepper:21890 tls: - insecure: true + # TLS is enabled, but hostname/chain is not verified + insecure_skip_verify: true + # optional: see incoming/outgoing spans in logs + debug: + verbosity: basic + +processors: + batch: {} + +extensions: + health_check: {} service: + extensions: [health_check] + telemetry: + logs: + level: debug pipelines: traces: - receivers: [jaeger, otlp, zipkin] - processors: [batch/traces] - exporters: [otlp/data-prepper] + receivers: [otlp] + processors: [batch] + exporters: [otlp, debug] +``` +{% include copy.html %} + +Start all the containers using the `docker-compose up` command. + +Run the following command to start `telemetrygen`, which generates synthetic OpenTelemetry traces for 30 seconds (at approximately 50 spans/sec) and sends them to `otel-collector:4317` over plaintext gRPC: + +```bash +docker run --rm --network anton_opensearch-net \ + ghcr.io/open-telemetry/opentelemetry-collector-contrib/telemetrygen:latest \ + traces \ + --otlp-endpoint=otel-collector:4317 \ + --otlp-insecure \ + --duration=30s \ + --rate=50 +``` +{% include copy.html %} + +This will send sample telemetry to the alias `otel-v1-apm-span` and store the documents in the index `otel-v1-apm-span-000001`. The stored documents will have the following structure: + +```json +"hits": [ + { + "_index": "otel-v1-apm-span-000001", + "_id": "b7446942445f1f0220cc9e3707dcd7d3/153de4602f5169d3", + "_score": 1, + "_source": { + "traceId": "b7446942445f1f0220cc9e3707dcd7d3", + "droppedLinksCount": 0, + "kind": "SPAN_KIND_CLIENT", + "droppedEventsCount": 0, + "traceGroupFields": { + "endTime": "2025-11-11T12:52:42.791867180Z", + "durationInNanos": 123000, + "statusCode": 0 + }, + "traceGroup": "lets-go", + "serviceName": "telemetrygen", + "parentSpanId": "", + "spanId": "153de4602f5169d3", + "traceState": "", + "name": "lets-go", + "startTime": "2025-11-11T12:52:42.791744180Z", + "links": [], + "endTime": "2025-11-11T12:52:42.791867180Z", + "droppedAttributesCount": 0, + "durationInNanos": 123000, + "events": [], + "span.attributes.network@peer@address": "1.2.3.4", + "instrumentationScope.name": "telemetrygen", + "span.attributes.peer@service": "telemetrygen-server", + "resource.attributes.service@name": "telemetrygen", + "status.code": 0 + } + }, + ... ``` After you run OpenTelemetry in your service environment, you must configure your application to use the OpenTelemetry Collector. The OpenTelemetry Collector typically runs alongside your application. @@ -369,9 +594,9 @@ For more information about how to tune and scale Data Prepper for trace analytic Starting with Data Prepper version 1.4, trace processing uses Data Prepper's event model. This allows pipeline authors to configure other processors to modify spans or traces. To provide a migration path, Data Prepper version 1.4 introduced the following changes: -* `otel_traces_source` has an optional `record_type` parameter that can be set to `event`. When configured, it will output event objects. -* `otel_traces_raw` replaces `otel_traces_raw_prepper` for event-based spans. -* `otel_traces_group` replaces `otel_traces_group_prepper` for event-based spans. +* `otel_trace_source` has an optional `record_type` parameter that can be set to `event`. When configured, it will output event objects. +* `otel_traces` replaces `otel_traces_prepper` for event-based spans. +* `otel_trace_group` replaces `otel_trace_group_prepper` for event-based spans. -In Data Prepper version 2.0, `otel_traces_source` will only output events. Data Prepper version 2.0 also removes `otel_traces_raw_prepper` and `otel_traces_group_prepper` entirely. To migrate to Data Prepper version 2.0, you can configure your trace pipeline using the event model. - \ No newline at end of file +In Data Prepper version 2.0, `otel_trace_source` will only output events. Data Prepper version 2.0 also removes `otel_traces_prepper` and `otel_trace_group_prepper` entirely. To migrate to Data Prepper version 2.0, you can configure your trace pipeline using the event model. + diff --git a/_data-prepper/getting-started/configuring-pipelines.md b/_data-prepper/getting-started/configuring-pipelines.md new file mode 100644 index 00000000..61cc8023 --- /dev/null +++ b/_data-prepper/getting-started/configuring-pipelines.md @@ -0,0 +1,146 @@ +--- +layout: default +title: Configuring pipelines +parent: Getting started +nav_order: 15 +--- + +# Configuring pipelines + +OpenSearch Data Prepper requires at least one pipeline to start. You define pipelines in YAML files in the `pipelines` directory of the Data Prepper home directory (`/usr/share/data-prepper/pipelines` in the Docker image). Data Prepper loads every YAML file in this directory at startup. + +## Pipeline structure + +A pipeline configuration has the following structure: + +```yaml +<pipeline-name>: + source: + <source-name>: + <source-options> + buffer: + <buffer-name>: + <buffer-options> + processor: + - <processor-name>: + <processor-options> + sink: + - <sink-name>: + <sink-options> + workers: <number-of-workers> + delay: <delay-in-milliseconds> +``` + +Each pipeline has a name and consists of the following components. + +| Component | Required | Description | +| :--- | :--- | :--- | +| [`source`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/sources/) | Yes | The component that receives or reads data. Each pipeline has exactly one source. | +| [`buffer`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/buffers/) | No | The component that holds events between the source and the processors. If you don't specify a buffer, Data Prepper uses the [`bounded_blocking`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/bounded-blocking/) buffer. | +| [`processor`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/) | No | A list of processors that transform each event. Data Prepper runs the processors in the order in which they are listed. If you don't specify any processors, events pass through the pipeline unchanged. | +| [`sink`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/sinks/) | Yes | A list of one or more destinations for the processed events. Each event is sent to every sink. | + +A pipeline can also contain the following settings, which control how the pipeline reads events from the buffer. + +| Setting | Required | Description | +| :--- | :--- | :--- | +| `workers` | No | The number of threads that read events from the buffer and run the processors. Default is `1`. | +| `delay` | No | The number of milliseconds that each worker waits between buffer reads. Default is `3000`. | + +## Reading and writing files + +The following pipeline reads lines from a text file and writes them to another file. The pipeline doesn't specify a buffer or processors, so it uses the default buffer and passes events through unchanged: + +```yaml +file-pipeline: + source: + file: + path: /usr/share/data-prepper/data/input.txt + record_type: event + sink: + - file: + path: /usr/share/data-prepper/data/output.txt +``` +{% include copy.html %} + +The `record_type: event` setting makes the `file` source produce events. Without this setting, the source produces raw strings. Processors that operate on event fields, such as `uppercase_string`, cannot process raw strings: the pipeline produces no output and logs no error. +{: .important} + +Data Prepper converts each line of `input.txt` into an event containing a `message` field and writes the events to `output.txt`. For example, an input file containing the lines `first line` and `second line` produces the following output: + +```json +{"message":"first line"} +{"message":"second line"} +``` + +## Pipeline containing all components + +The following pipeline specifies every component and setting: + +```yaml +uppercase-pipeline: + workers: 2 + delay: 100 + source: + file: + path: /usr/share/data-prepper/data/input.txt + record_type: event + buffer: + bounded_blocking: + buffer_size: 1024 + batch_size: 256 + processor: + - uppercase_string: + with_keys: ["message"] + sink: + - file: + path: /usr/share/data-prepper/data/output.txt +``` +{% include copy.html %} + +This pipeline processes events as follows: + +1. The `file` source reads each line of `input.txt` as an event and writes it to the buffer. +1. The `bounded_blocking` buffer holds up to 1,024 events. If the buffer is full, the source waits until space is available. +1. Two worker threads read from the buffer. Every 100 milliseconds, each worker reads up to 256 events. +1. Each worker runs the [`uppercase_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/uppercase-string/) processor, which converts the value of the `message` field to uppercase. +1. The `file` sink writes the processed events to `output.txt`. + +The output file contains the following events: + +```json +{"message":"SECOND LINE"} +{"message":"FIRST LINE"} +``` + +Because two workers process events in parallel, the output order can differ from the input order. + +To run the pipelines on this page, see [Running pipelines that read and write files]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/#running-pipelines-that-read-and-write-files). + +## Multiple pipelines + +A Data Prepper instance can run multiple pipelines. You can define each pipeline in its own file or define several pipelines in one file. For example, the following file defines two pipelines: + +```yaml +file-pipeline: + source: + file: + path: /usr/share/data-prepper/data/input.txt + record_type: event + sink: + - stdout: + +http-pipeline: + source: + http: + ssl: false + sink: + - stdout: +``` +{% include copy.html %} + +Pipelines can send events to each other. For more information, see [Pipelines]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines/). + +## Next steps + +- [Run Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/) and send it a test event. diff --git a/_data-prepper/getting-started/index.md b/_data-prepper/getting-started/index.md new file mode 100644 index 00000000..89799888 --- /dev/null +++ b/_data-prepper/getting-started/index.md @@ -0,0 +1,51 @@ +--- +layout: default +title: Getting started +nav_order: 5 +has_children: true +has_toc: false +redirect_from: + - /clients/data-prepper/get-started/ + - /data-prepper/getting-started/ +steps: + - heading: "Install and configure Data Prepper" + description: "Install Data Prepper using the Docker image or a Linux archive and learn how it's configured." + link: "/data-prepper/getting-started/installing/" + - heading: "Configure pipelines" + description: "Learn about the pipeline structure and the server and logging configuration files." + link: "/data-prepper/getting-started/configuring-pipelines/" + - heading: "Run Data Prepper" + description: "Start Data Prepper using a minimal pipeline, send a test event, and then stop Data Prepper." + link: "/data-prepper/getting-started/running/" + - heading: "Ingest log data into OpenSearch" + description: "Build a pipeline that parses raw Apache access logs, writes them to an OpenSearch index, and lets you search the parsed fields." + link: "/data-prepper/getting-started/ingesting-log-data/" +--- + +# Getting started with OpenSearch Data Prepper + +OpenSearch Data Prepper is a server-side data collector that receives data from your applications, transforms it, and sends it to OpenSearch. Data Prepper runs separately from OpenSearch and is not included in the OpenSearch installation packages. + +## Pipelines and events + +Data Prepper runs _pipelines_. Each pipeline reads data from a _source_, transforms or drops events using one or more _processors_, and writes the result to one or more _sinks_. Between the source and the processors, events wait in a _buffer_. For example, a pipeline can receive log lines over HTTP, parse each line into fields, and write the result to an OpenSearch index. A single Data Prepper instance can run multiple pipelines. + +An _event_ is a single data item, such as a log line, that moves through a pipeline. Each event consists of key-value pairs called _fields_, similar to a JSON object. When a pipeline writes to OpenSearch, each event becomes a document. Other sinks, such as Amazon S3, serialize events into files. Processors read and modify the fields of each event before the event reaches a sink. + +## Configuration files + +Data Prepper uses the following configuration files. + +| File | Required | Description | +| :--- | :--- | :--- | +| Pipeline configuration | Yes | One or more YAML files that define the pipelines to run, including their sources, processors, and sinks. Data Prepper does not provide a default pipeline and does not start if no pipeline configuration file exists. For more information, see [Configuring pipelines]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/configuring-pipelines/). | +| `data-prepper-config.yaml` | No | Settings for the Data Prepper server, such as the port, TLS, and authentication for the [core APIs]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/core-apis/). Data Prepper includes a default server configuration file. | +| `log4j2-rolling.properties` | No | The [Log4j 2](https://logging.apache.org/log4j/2.x/) logging configuration. Data Prepper includes a default logging configuration file. | + +Because a pipeline is required, you define at least one pipeline before you start Data Prepper. + +## Next steps + +To get started with Data Prepper, follow these steps in order: + +{% include list.html list_items=page.steps %} diff --git a/_data-prepper/getting-started/ingesting-log-data.md b/_data-prepper/getting-started/ingesting-log-data.md new file mode 100644 index 00000000..6985e73c --- /dev/null +++ b/_data-prepper/getting-started/ingesting-log-data.md @@ -0,0 +1,324 @@ +--- +layout: default +title: Ingesting log data into OpenSearch +parent: Getting started +nav_order: 30 +--- + +# Ingesting log data into OpenSearch + +In this tutorial, you'll run Data Prepper and OpenSearch in Docker, send raw Apache access logs to Data Prepper, and search the parsed log data in OpenSearch. The pipeline that you create performs the following tasks: + +1. Receives log lines over HTTP. +1. Parses each log line into separate fields, such as the client IP address, request path, and response code. +1. Converts the log timestamp into a date and the response code and size into integers. +1. Writes each event to an OpenSearch index and prints it to the Data Prepper log. + +The pipeline parses log lines in the Apache common log format, such as the following: + +```text +10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] "GET /checkout HTTP/1.1" 500 98 +``` + +Each line contains the client IP address, two identity fields (`-` when empty), the timestamp, the request (method, path, and HTTP version), the response code, and the response size in bytes. + +Docker Compose downloads the Data Prepper and OpenSearch images when you start the containers, so you don't need to install Data Prepper first. + +## Prerequisites + +Install [Docker](https://docs.docker.com/get-docker/), including [Docker Compose](https://docs.docker.com/compose/). The containers use ports `9200` (OpenSearch) and `2021` (Data Prepper), so make sure that these ports are not in use. + +If you're using Linux, increase the maximum number of memory maps available to OpenSearch. For more information, see [Important settings]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#important-settings). + +## Step 1: Define a pipeline + +Create a directory for this tutorial (for example, `data-prepper-tutorial`). In this directory, create a file named `pipelines.yaml` containing the following pipeline configuration. Replace `<custom-admin-password>` with a password that meets the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). You'll also use this password for OpenSearch in the next step: + +```yaml +log-pipeline: + source: + http: + ssl: false + processor: + - grok: + match: + message: ['%{COMMONAPACHELOG}'] + - date: + match: + - key: timestamp + patterns: ["dd/MMM/yyyy:HH:mm:ss Z"] + destination: "@timestamp" + - convert_type: + keys: ["response", "bytes"] + type: integer + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index: web-logs + flush_timeout: -1 + - stdout: +``` +{% include copy.html %} + +This file defines one pipeline named `log-pipeline` containing the following components: + +- `source`: The [`http`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/http/) source receives events on port `2021` at the `/log/ingest` path. The `ssl: false` setting accepts plain HTTP requests, which is suitable only for local testing. +- `processor`: Data Prepper runs the processors in the order in which they are listed: + - The [`grok`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/grok/) processor matches the `message` field against the built-in `COMMONAPACHELOG` pattern and adds a field for each part of the log line, such as `clientip`, `verb`, `request`, `response`, `bytes`, and `timestamp`. + - The [`date`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/date/) processor parses the `timestamp` field and writes the result to the `@timestamp` field in ISO 8601 format so that OpenSearch maps it as a date. + - The [`convert_type`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/convert-entry-type/) processor converts the `response` and `bytes` fields from strings to integers so that you can run range queries on them. +- `sink`: Each event is sent to both sinks: + - The [`opensearch`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/opensearch/) sink writes events to the `web-logs` index. The `opensearch` hostname refers to the OpenSearch container that you'll define in the next step. The `insecure: true` setting skips certificate verification because the OpenSearch container uses demo certificates. By default, the sink waits up to 60 seconds to batch events before writing them to OpenSearch. Setting `flush_timeout` to `-1` writes events as soon as they are processed so that you can see the results immediately. + - The [`stdout`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/stdout/) sink prints each processed event to the Data Prepper log so that you can inspect it. + +## Step 2: Create the Docker Compose file + +In the same directory, create a file named `.env` containing the following line. Replace `<custom-admin-password>` with the password that you used in `pipelines.yaml`: + +```bash +OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> +``` +{% include copy.html %} + +Docker Compose reads the `.env` file automatically and passes the password to OpenSearch. If the password does not meet the requirements, OpenSearch does not start. + +Create a file named `docker-compose.yml` containing the following configuration: + +```yaml +services: + opensearch: + image: opensearchproject/opensearch:latest + container_name: opensearch + environment: + - discovery.type=single-node + - OPENSEARCH_INITIAL_ADMIN_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} + ports: + - 9200:9200 + data-prepper: + image: opensearchproject/data-prepper:latest + container_name: data-prepper + volumes: + - ./pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml + ports: + - 2021:2021 + depends_on: + - opensearch +``` +{% include copy.html %} + +This file defines two containers: + +- `opensearch`: A single-node OpenSearch cluster with security enabled, available at `https://localhost:9200`. +- `data-prepper`: A Data Prepper instance. Data Prepper loads every pipeline configuration file in the `/usr/share/data-prepper/pipelines/` directory, so the `volumes` setting mounts your `pipelines.yaml` file into that directory. Port `2021` is published so that you can send data to the `http` source from your machine. + +Your directory now contains the following files: + +```text +data-prepper-tutorial/ +├── .env +├── docker-compose.yml +└── pipelines.yaml +``` + +## Step 3: Start the containers + +From the `data-prepper-tutorial` directory, start the containers in the background: + +```bash +docker compose up -d +``` +{% include copy.html %} + +Follow the Data Prepper log: + +```bash +docker compose logs -f data-prepper +``` +{% include copy.html %} + +While OpenSearch is starting, Data Prepper logs `Failed to initialize OpenSearch sink, retrying` warnings. These warnings are expected. Data Prepper retries until OpenSearch is available, which usually takes less than a minute. When the pipeline is ready, the log contains the following lines: + +```text +data-prepper | ... INFO org.opensearch.dataprepper.plugins.source.loghttp.HTTPSource - Started http source on port 2021... +data-prepper | ... INFO org.opensearch.dataprepper.plugins.sink.opensearch.OpenSearchSink - Initialized OpenSearch sink +``` + +Leave the log running and open a new terminal window for the next step. + +## Step 4: Send log data to Data Prepper + +The `http` source accepts a JSON array in which each object becomes one event. Send three Apache access log lines, each in the `message` field: + +```bash +curl -X POST http://localhost:2021/log/ingest \ + -H "Content-Type: application/json" \ + -d '[ + {"message": "192.168.1.10 - - [19/Oct/2026:10:15:32 +0000] \"GET /products/123 HTTP/1.1\" 200 5120"}, + {"message": "192.168.1.25 - - [19/Oct/2026:10:15:47 +0000] \"POST /cart HTTP/1.1\" 201 342"}, + {"message": "10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] \"GET /checkout HTTP/1.1\" 500 98"} + ]' +``` +{% include copy.html %} + +Data Prepper responds with `200 OK`. + +## Step 5: View the processed events + +Return to the terminal containing the Data Prepper log. The `stdout` sink prints each processed event on a single line. For example, the following event, formatted for readability, was created from the third log line: + +```json +{ + "message": "10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] \"GET /checkout HTTP/1.1\" 500 98", + "request": "/checkout", + "auth": "-", + "ident": "-", + "response": 500, + "bytes": 98, + "clientip": "10.0.0.7", + "verb": "GET", + "httpversion": "1.1", + "timestamp": "19/Oct/2026:10:16:03 +0000", + "@timestamp": "2026-10-19T10:16:03.000Z" +} +``` + +Compare the event to the log line that you sent: + +- The `message` field contains the original log line. +- The `grok` processor added the `clientip`, `ident`, `auth`, `timestamp`, `verb`, `request`, `httpversion`, `response`, and `bytes` fields. +- The `date` processor added the `@timestamp` field. +- The `convert_type` processor changed `response` and `bytes` to integers, so they appear without quotation marks. + +## Step 6: Search the data in OpenSearch + +The `opensearch` sink wrote the same events to the `web-logs` index. Search for requests that returned an error, which are those containing a response code of `400` or higher: + +```bash +curl -X GET "https://localhost:9200/web-logs/_search?pretty" -ku admin:<custom-admin-password> \ + -H "Content-Type: application/json" \ + -d '{ + "query": { + "range": { + "response": { + "gte": 400 + } + } + } + }' +``` +{% include copy.html %} + +The `-k` option skips certificate verification because OpenSearch uses demo certificates. The response contains the event for the request that returned a `500` response code: + +```json +{ + "took" : 41, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "web-logs", + "_id" : "QJmSVKEBVverMSge8P0k", + "_score" : 1.0, + "_source":{"message":"10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] \"GET /checkout HTTP/1.1\" 500 98","request":"/checkout","auth":"-","ident":"-","response":500,"bytes":98,"clientip":"10.0.0.7","verb":"GET","httpversion":"1.1","timestamp":"19/Oct/2026:10:16:03 +0000","@timestamp":"2026-10-19T10:16:03.000Z"} + } + ] + } +} +``` + +The range query works because the `convert_type` processor converted `response` to an integer before the event reached OpenSearch. + +## Step 7: Modify the pipeline + +Data Prepper reads pipeline configuration files only at startup, so you must restart Data Prepper after changing a pipeline. + +The `timestamp` field duplicates the `@timestamp` field. To remove it, add a [`delete_entries`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/delete-entries/) processor to the end of the `processor` list in `pipelines.yaml`: + +```yaml + processor: + - grok: + match: + message: ['%{COMMONAPACHELOG}'] + - date: + match: + - key: timestamp + patterns: ["dd/MMM/yyyy:HH:mm:ss Z"] + destination: "@timestamp" + - convert_type: + keys: ["response", "bytes"] + type: integer + - delete_entries: + with_keys: ["timestamp"] +``` +{% include copy.html %} + +Restart Data Prepper: + +```bash +docker compose restart data-prepper +``` +{% include copy.html %} + +Wait until the Data Prepper log contains a new `Started http source on port 2021` line, and then send another log line: + +```bash +curl -X POST http://localhost:2021/log/ingest \ + -H "Content-Type: application/json" \ + -d '[ + {"message": "10.0.0.7 - - [19/Oct/2026:10:20:11 +0000] \"GET /checkout HTTP/1.1\" 503 64"} + ]' +``` +{% include copy.html %} + +The new event in the Data Prepper log no longer contains the `timestamp` field: + +```json +{ + "message": "10.0.0.7 - - [19/Oct/2026:10:20:11 +0000] \"GET /checkout HTTP/1.1\" 503 64", + "request": "/checkout", + "auth": "-", + "ident": "-", + "response": 503, + "bytes": 64, + "clientip": "10.0.0.7", + "verb": "GET", + "httpversion": "1.1", + "@timestamp": "2026-10-19T10:20:11.000Z" +} +``` + +Events that were indexed before the change are not modified. + +## Step 8: Clean up + +To stop and remove the containers, run the following command from the `data-prepper-tutorial` directory: + +```bash +docker compose down +``` +{% include copy.html %} + +The containers do not use volumes, so removing them deletes the `web-logs` index. + +## Next steps + +- To learn about pipeline structure, conditional routing, and other pipeline options, see [Pipelines]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines/). +- To find the sources, processors, and sinks that you can use in a pipeline, see [Sources]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/sources/), [Processors]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/), and [Sinks]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/sinks/). Some processor pages include complete examples that send data to `localhost:2021` and write to `https://opensearch:9200`. You can run these examples in the environment from this tutorial by copying the example pipeline into `pipelines.yaml`, replacing `<custom-admin-password>` with the admin password from your `.env` file, and restarting Data Prepper. +- To configure the Data Prepper server, including its port, TLS, and authentication, see [Configuring OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/). +- To set up Data Prepper for common use cases, see [Log analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/log-analytics/) and [Trace analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/). +- To send logs from a log collector instead of `curl`, see the Data Prepper repository examples for [Fluent Bit](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion), [Fluentd](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion-fluentd), [Kubernetes](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion-k8s), and [Amazon ECS FireLens](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion-ecs-firelens). diff --git a/_data-prepper/getting-started/installing.md b/_data-prepper/getting-started/installing.md new file mode 100644 index 00000000..931c445e --- /dev/null +++ b/_data-prepper/getting-started/installing.md @@ -0,0 +1,90 @@ +--- +layout: default +title: Installing and configuring Data Prepper +parent: Getting started +nav_order: 10 +--- + +# Installing and configuring Data Prepper + +You can install OpenSearch Data Prepper using the Docker image or a Linux archive. To build Data Prepper from source, see the [Data Prepper Developer Guide](https://github.com/opensearch-project/data-prepper/blob/main/docs/developer_guide.md). + +## Installing the Docker image + +To use Data Prepper in Docker, install [Docker](https://docs.docker.com/get-docker/) and pull the Data Prepper image: + +```bash +docker pull opensearchproject/data-prepper:latest +``` +{% include copy.html %} + +The Data Prepper home directory in the image is `/usr/share/data-prepper`. To provide configuration files, mount them into this directory when you start the container. For more information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). + +## Installing a Linux archive + +Download a Data Prepper archive for your platform from the [OpenSearch downloads page](https://opensearch.org/downloads/){:target='\_blank'}. Each release provides the following archives: + +- `opensearch-data-prepper-jdk-<version>-linux-<architecture>.tar.gz`: Includes a Java runtime. +- `opensearch-data-prepper-<version>-linux-<architecture>.tar.gz`: Does not include a Java runtime. To use this archive, install Java on your host. + +Extract the archive, replacing `<version>` and `<architecture>` with the values in the file name: + +```bash +tar -xzf opensearch-data-prepper-jdk-<version>-linux-<architecture>.tar.gz +``` +{% include copy.html %} + +The extracted directory is the Data Prepper home directory. + +## Directory structure + +The Data Prepper home directory contains the following files and directories. + +| Path | Description | +| :--- | :--- | +| `bin/data-prepper` | The script that starts Data Prepper. | +| `pipelines/` | The directory for pipeline configuration files. Data Prepper loads every YAML file in this directory. This directory contains no pipelines after installation. | +| `config/data-prepper-config.yaml` | The Data Prepper server configuration file. | +| `config/log4j2-rolling.properties` | The Log4j 2 logging configuration file. | +| `lib/` | The Data Prepper libraries and plugins. | + +## Server and logging configuration + +Data Prepper also reads the following optional configuration files from the `config` directory of the Data Prepper home directory. + +### Server configuration + +The `config/data-prepper-config.yaml` file configures the Data Prepper server, which exposes the [core APIs]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/core-apis/) on port `4900`. The Docker image and the Linux archives include different default server configurations. + +| Setting | Docker image | Linux archive | +| :--- | :--- | :--- | +| TLS | Enabled, using a self-signed certificate. Send requests using `https`. | Disabled. Send requests using `http`. | +| Authentication | HTTP basic authentication using the username `admin` and the password `admin`. | None. | + +The default certificate and credentials in the Docker image are intended for testing only. Replace them before using Data Prepper in production. +{: .warning} + +To change these settings, replace `config/data-prepper-config.yaml` with your own file. For example, the following file disables TLS for the core APIs: + +```yaml +ssl: false +serverPort: 4900 +``` +{% include copy.html %} + +For all server settings, see [Configuring OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/). + +### Logging configuration + +Data Prepper reads its logging configuration from `config/log4j2-rolling.properties`. To customize logging, either replace this file or set the `JAVA_OPTS` environment variable to point to a different file: + +```bash +export JAVA_OPTS="-Dlog4j.configurationFile=/path/to/log4j2.properties" +``` +{% include copy.html %} + +For more information, see [Configuring Log4j]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-log4j/). + +## Next steps + +- [Configure a pipeline]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/configuring-pipelines/) for Data Prepper to run. diff --git a/_data-prepper/getting-started/running.md b/_data-prepper/getting-started/running.md new file mode 100644 index 00000000..19a793ea --- /dev/null +++ b/_data-prepper/getting-started/running.md @@ -0,0 +1,182 @@ +--- +layout: default +title: Running Data Prepper +parent: Getting started +nav_order: 20 +--- + +# Running Data Prepper + +OpenSearch Data Prepper requires at least one pipeline to start. If Data Prepper finds no pipeline configuration file, it logs the following error and exits: + +```text +ERROR org.opensearch.dataprepper.pipeline.parser.PipelineConfigurationFileReader - Pipelines configuration file not found at /usr/share/data-prepper/pipelines +``` + +On this page, you'll define a minimal pipeline, start Data Prepper, and send it a test event. If you haven't installed Data Prepper, see [Installing Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/installing/). For more information about pipeline configuration, see [Configuring pipelines]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/configuring-pipelines/). + +## Step 1: Define a pipeline + +Create a file named `pipelines.yaml` containing the following pipeline configuration: + +```yaml +test-pipeline: + source: + http: + ssl: false + sink: + - stdout: +``` +{% include copy.html %} + +This pipeline, named `test-pipeline`, receives events using the [`http`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/http/) source on port `2021` and prints each event to the Data Prepper log using the [`stdout`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/stdout/) sink. The pipeline contains no processors, so events are not modified. + +## Step 2: Start Data Prepper + +Start Data Prepper using the Docker image or a Linux archive. + +### Docker + +From the directory containing `pipelines.yaml`, run the following command: + +```bash +docker run --name data-prepper \ + -p 2021:2021 -p 4900:4900 \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + opensearchproject/data-prepper:latest +``` +{% include copy.html %} + +The `-v` option mounts `pipelines.yaml` into the `pipelines` directory of the container. `${PWD}` is your current directory, so `${PWD}/pipelines.yaml` is the absolute path to the file, which Docker requires for mounts. The `-p` options publish port `2021` for the `http` source and port `4900` for the [core APIs]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/core-apis/). + +To use your own server configuration file, mount it as `/usr/share/data-prepper/config/data-prepper-config.yaml`: + +```bash +docker run --name data-prepper \ + -p 2021:2021 -p 4900:4900 \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + -v ${PWD}/data-prepper-config.yaml:/usr/share/data-prepper/config/data-prepper-config.yaml \ + opensearchproject/data-prepper:latest +``` +{% include copy.html %} + +### Linux archive + +Copy `pipelines.yaml` into the `pipelines` directory of the Data Prepper home directory. Then run the following command from the home directory: + +```bash +bin/data-prepper +``` +{% include copy.html %} + +Alternatively, provide the pipeline configuration file and the server configuration file as arguments, in that order: + +```bash +bin/data-prepper /path/to/pipelines.yaml /path/to/data-prepper-config.yaml +``` +{% include copy.html %} + +## Step 3: Send a test event + +When the pipeline is ready, the Data Prepper log contains the following line: + +```text +INFO org.opensearch.dataprepper.plugins.source.loghttp.HTTPSource - Started http source on port 2021... +``` + +In a new terminal window, send an event to the `http` source. The source accepts a JSON array in which each object becomes one event: + +```bash +curl -X POST http://localhost:2021/log/ingest \ + -H "Content-Type: application/json" \ + -d '[{"message": "Hello, Data Prepper!"}]' +``` +{% include copy.html %} + +Data Prepper responds with `200 OK`, and the `stdout` sink prints the event to the Data Prepper log: + +```json +{"message":"Hello, Data Prepper!"} +``` + +## Step 4: List the running pipelines + +To list the running pipelines, send a request to the core APIs. The request depends on the [default server configuration]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/installing/#server-configuration) of your installation. + +For the Docker image, use `https` and the default credentials. The `-k` option skips certificate verification because the image uses a self-signed certificate: + +```bash +curl -k -u admin:admin https://localhost:4900/list +``` +{% include copy.html %} + +For a Linux archive, use `http`: + +```bash +curl http://localhost:4900/list +``` +{% include copy.html %} + +The response contains the pipeline that you defined: + +```json +{"pipelines":[{"name":"test-pipeline"}]} +``` + +## Step 5: Stop Data Prepper + +To stop Data Prepper, press `Ctrl+C` in the terminal in which Data Prepper is running. If you started the Docker container in the background, run `docker stop data-prepper`. + +Alternatively, send a shutdown request to the core APIs. For the Docker image, send the following request: + +```bash +curl -k -u admin:admin -X POST https://localhost:4900/shutdown +``` +{% include copy.html %} + +For a Linux archive, send the following request: + +```bash +curl -X POST http://localhost:4900/shutdown +``` +{% include copy.html %} + +To remove the stopped Docker container so that you can reuse the `data-prepper` container name, run `docker rm data-prepper`. + +## Running pipelines that read and write files + +The file-based examples in [Configuring pipelines]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/configuring-pipelines/) read from and write to the `/usr/share/data-prepper/data` directory. To run these examples, create a `data` directory containing an `input.txt` file. + +In Docker, mount the `data` directory into the container along with the pipeline file: + +```bash +docker run --name data-prepper \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + -v ${PWD}/data:/usr/share/data-prepper/data \ + opensearchproject/data-prepper:latest +``` +{% include copy.html %} + +Data Prepper writes the processed events to `data/output.txt`. + +For a Linux archive, replace the `path` values in the pipeline with the absolute paths to the input and output files on your host. + +## Running multiple pipelines + +Data Prepper loads every YAML file in the `pipelines` directory, and each file can define one or more pipelines. For more information, see [Multiple pipelines]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/configuring-pipelines/#multiple-pipelines). To run pipelines from multiple files in Docker, mount a directory instead of a single file: + +```bash +docker run --name data-prepper \ + -p 2021:2021 -p 4900:4900 \ + -v ${PWD}/pipelines:/usr/share/data-prepper/pipelines \ + opensearchproject/data-prepper:latest +``` +{% include copy.html %} + +## Updating pipelines + +Data Prepper reads pipeline configuration files only at startup. After you edit, add, or delete a pipeline configuration file, restart Data Prepper to apply the change. + +## Next steps + +- [Ingest log data into OpenSearch]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/ingesting-log-data/) by building a pipeline that parses raw Apache access logs and writes them to OpenSearch. diff --git a/_data-prepper/index.md b/_data-prepper/index.md index 0c7a228b..922645ef 100644 --- a/_data-prepper/index.md +++ b/_data-prepper/index.md @@ -1,6 +1,6 @@ --- layout: default -title: Data Prepper +title: OpenSearch Data Prepper nav_order: 1 has_children: false has_toc: false @@ -10,87 +10,19 @@ redirect_from: - /clients/data-prepper/index/ - /monitoring-plugins/trace/data-prepper/ - /data-prepper/index/ + - /data-prepper/migrating-from-logstash-data-prepper/ --- -# Data Prepper +# ![Data Prepper icon]({{site.url}}{{site.baseurl}}/images/icons/OpenSearch-DataPrepper-1.png){: .heading-icon} OpenSearch Data Prepper -Data Prepper is a server-side data collector capable of filtering, enriching, transforming, normalizing, and aggregating data for downstream analytics and visualization. +OpenSearch Data Prepper is a server-side data collector capable of filtering, enriching, transforming, normalizing, and aggregating data for downstream analysis and visualization. Data Prepper is the preferred data ingestion tool for OpenSearch. It is recommended for most data ingestion use cases in OpenSearch and for processing large, complex datasets. -Data Prepper lets users build custom pipelines to improve the operational view of applications. Two common uses for Data Prepper are trace and log analytics. [Trace analytics]({{site.url}}{{site.baseurl}}/observability-plugin/trace/index/) can help you visualize the flow of events and identify performance problems, and [log analytics]({{site.url}}{{site.baseurl}}/observability-plugin/log-analytics/) can improve searching, analyzing and provide insights into your application. +With Data Prepper you can build custom pipelines to improve the operational view of applications. Two common use cases for Data Prepper are trace analytics and log analytics. [Trace analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) can help you visualize event flows and identify performance problems. [Log analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/log-analytics/) equips you with tools to enhance your search capabilities, conduct comprehensive analysis, and gain insights into your applications' performance and behavior. -## Concepts +## Key concepts -Data Prepper includes one or more **pipelines** that collect and filter data based on the components set within the pipeline. Each component is pluggable, enabling you to use your own custom implementation of each component. These components include the following: - -- One [source](#source) -- One or more [sinks](#sink) -- (Optional) One [buffer](#buffer) -- (Optional) One or more [processors](#processor) - -A single instance of Data Prepper can have one or more pipelines. - -Each pipeline definition contains two required components: **source** and **sink**. If buffers and processors are missing from the Data Prepper pipeline, Data Prepper uses the default buffer and a no-op processor. - -### Source - -Source is the input component that defines the mechanism through which a Data Prepper pipeline will consume events. A pipeline can have only one source. The source can consume events either by receiving the events over HTTP or HTTPS or by reading from external endpoints like OTeL Collector for traces and metrics and Amazon Simple Storage Service (Amazon S3). Sources have their own configuration options based on the format of the events (such as string, JSON, Amazon CloudWatch logs, or open telemetry trace). The source component consumes events and writes them to the buffer component. - -### Buffer - -The buffer component acts as the layer between the source and the sink. Buffer can be either in-memory or disk based. The default buffer uses an in-memory queue called `bounded_blocking` that is bounded by the number of events. If the buffer component is not explicitly mentioned in the pipeline configuration, Data Prepper uses the default `bounded_blocking`. - -### Sink - -Sink is the output component that defines the destination(s) to which a Data Prepper pipeline publishes events. A sink destination could be a service, such as OpenSearch or Amazon S3, or another Data Prepper pipeline. When using another Data Prepper pipeline as the sink, you can chain multiple pipelines together based on the needs of the data. Sink contains its own configuration options based on the destination type. - -### Processor - -Processors are units within the Data Prepper pipeline that can filter, transform, and enrich events using your desired format before publishing the record to the sink component. The processor is not defined in the pipeline configuration; the events publish in the format defined in the source component. You can have more than one processor within a pipeline. When using multiple processors, the processors are run in the order they are defined inside the pipeline specification. - -## Sample pipeline configurations - -To understand how all pipeline components function within a Data Prepper configuration, see the following examples. Each pipeline configuration uses a `yaml` file format. - -### Minimal component - -This pipeline configuration reads from the file source and writes to another file in the same path. It uses the default options for the buffer and processor. - -```yml -sample-pipeline: - source: - file: - path: <path/to/input-file> - sink: - - file: - path: <path/to/output-file> -``` - -### All components - -The following pipeline uses a source that reads string events from the `input-file`. The source then pushes the data to the buffer, bounded by a max size of `1024`. The pipeline is configured to have `4` workers, each of them reading a maximum of `256` events from the buffer for every `100 milliseconds`. Each worker runs the `string_converter` processor and writes the output of the processor to the `output-file`. - -```yml -sample-pipeline: - workers: 4 #Number of workers - delay: 100 # in milliseconds, how often the workers should run - source: - file: - path: <path/to/input-file> - buffer: - bounded_blocking: - buffer_size: 1024 # max number of events the buffer will accept - batch_size: 256 # max number of events the buffer will drain for each read - processor: - - string_converter: - upper_case: true - sink: - - file: - path: <path/to/output-file> -``` - -## Next steps - -To get started building your own custom pipelines with Data Prepper, see [Getting started]({{site.url}}{{site.baseurl}}/clients/data-prepper/get-started/). - -<!---Delete this comment.---> +Data Prepper ingests data through [pipelines]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines/), which process data as _events_. An event is a single data item, such as a log line or a trace span. When a pipeline writes to OpenSearch, each event becomes a document. Each pipeline reads events from a [source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/sources/), transforms or drops them using [processors]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/), and writes the result to one or more [sinks]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/sinks/). For more information, see [Getting started with OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/). +<span class="centering-container"> +[Get started]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/){: .btn-dark-blue} +</span> diff --git a/_data-prepper/managing-data-prepper/configuring-data-prepper.md b/_data-prepper/managing-data-prepper/configuring-data-prepper.md index bcff65ed..b92fe7b4 100644 --- a/_data-prepper/managing-data-prepper/configuring-data-prepper.md +++ b/_data-prepper/managing-data-prepper/configuring-data-prepper.md @@ -1,125 +1,158 @@ --- layout: default -title: Configuring Data Prepper -parent: Managing Data Prepper +title: Configuring OpenSearch Data Prepper +parent: Managing OpenSearch Data Prepper nav_order: 5 redirect_from: - /clients/data-prepper/data-prepper-reference/ - /monitoring-plugins/trace/data-prepper-reference/ --- -# Configuring Data Prepper - -You can customize your Data Prepper configuration by editing the `data-prepper-config.yaml` file in your Data Prepper installation. The following configuration options are independent from pipeline configuration options. +# Configuring OpenSearch Data Prepper +You can customize your OpenSearch Data Prepper configuration by editing the `data-prepper-config.yaml` file in your Data Prepper installation. The following configuration options are independent from pipeline configuration options. ## Data Prepper configuration Use the following options to customize your Data Prepper configuration. -Option | Required | Type | Description +Option | Required | Type | Description :--- | :--- |:--- | :--- -ssl | No | Boolean | Indicates whether TLS should be used for server APIs. Defaults to true. -keyStoreFilePath | No | String | The path to a .jks or .p12 keystore file. Required if `ssl` is true. -keyStorePassword | No | String | The password for keystore. Optional, defaults to empty string. -privateKeyPassword | No | String | The password for a private key within keystore. Optional, defaults to empty string. -serverPort | No | Integer | The port number to use for server APIs. Defaults to 4900. -metricRegistries | No | List | The metrics registries for publishing the generated metrics. Currently supports Prometheus and Amazon CloudWatch. Defaults to Prometheus. -metricTags | No | Map | A map of key-value pairs as common metric tags to metric registries. The maximum number of pairs is three. Note that `serviceName` is a reserved tag key with `DataPrepper` as the default tag value. Alternatively, administrators can set this value through the environment variable `DATAPREPPER_SERVICE_NAME`. If `serviceName` is defined in `metricTags`, that value overwrites those set through the above methods. -authentication | No | Object | The authentication configuration. Valid option is `http_basic` with `username` and `password` properties. If not defined, the server does not perform authentication. -processorShutdownTimeout | No | Duration | The time given to processors to clear any in-flight data and gracefully shut down. Default is 30s. -sinkShutdownTimeout | No | Duration | The time given to sinks to clear any in-flight data and gracefully shut down. Default is 30s. -peer_forwarder | No | Object | Peer forwarder configurations. See [Peer forwarder options](#peer-forwarder-options) for more details. -circuit_breakers | No | [circuit_breakers](#circuit-breakers) | Configures a circuit breaker on incoming data. -extensions | No | Object | The pipeline extension plugin configurations. See [Extension plugins](#extension-plugins) for more details. +`ssl` | No | Boolean | Indicates whether TLS should be used for server APIs. Default is `true`. +`keyStoreFilePath` | No | String | The path to a `.jks` or `.p12` keystore file. Required if `ssl` is `true`. +`keyStorePassword` | No | String | The password for the keystore. Optional; Defaults to an empty string. +`privateKeyPassword` | No | String | The password for a private key within the keystore. Optional; Defaults to an empty string. +`serverPort` | No | Integer | The port number to use for server APIs. Default is `4900`. +`metricRegistries` | No | List | The metric registries for publishing generated metrics. Currently supports **Prometheus** and **Amazon CloudWatch**. Default is **Prometheus**. +`metricTags` | No | Map | A map of up to three key-value pairs that define common metric tags for metric registries. The `serviceName` key is reserved (default is `DataPrepper`). You can override it by setting the environment variable `DATAPREPPER_SERVICE_NAME`. If `serviceName` is included in `metricTags`, it takes precedence. +`authentication` | No | Object | The authentication configuration for the server APIs. Valid value is `http_basic`, which requires a `username` and `password`. If not defined, the server does not perform authentication. +`processorShutdownTimeout` | No | Duration | The amount of time allowed for processors to finish processing in-flight data and shut down gracefully. Default is `30s`. +`sinkShutdownTimeout` | No | Duration | The amount of time allowed for sinks to clear in‑flight data and shut down gracefully. Default is `30s`. +`peer_forwarder` | No | Object | The Peer Forwarder configuration. See [Peer Forwarder options](#peer-forwarder-options). +`circuit_breakers` | No | [circuit_breakers](#circuit-breakers) | Configures one or more circuit breakers to control incoming data. +`extensions` | No | Object | The extension plugin configurations shared by pipelines. See [Extension plugins](#extension-plugins). -### Peer forwarder options +### Peer Forwarder options -The following section details various configuration options for peer forwarder. +The following section details various configuration options for peer forwarding. #### General options for peer forwarding -Option | Required | Type | Description -:--- | :--- | :--- | :--- -port | No | Integer | The peer forwarding server port. Valid options are between 0 and 65535. Defaults is 4994. -request_timeout | No | Integer | The request timeout for the peer forwarder HTTP server in milliseconds. Default is 10000. -server_thread_count | No | Integer | The number of threads used by the peer forwarder server. Default is 200. -client_thread_count | No | Integer | The number of threads used by the peer forwarder client. Default is 200. -max_connection_count | No | Integer | The maximum number of open connections for the peer forwarder server. Default is 500. -max_pending_requests | No | Integer | The maximum number of allowed tasks in ScheduledThreadPool work queue. Default is 1024. -discovery_mode | No | String | The peer discovery mode to use. Valid options are `local_node`, `static`, `dns`, or `aws_cloud_map`. Defaults to `local_node`, which processes events locally. -static_endpoints | Conditionally | List | A list containing endpoints of all Data Prepper instances. Required if `discovery_mode` is set to static. -domain_name | Conditionally | String | A single domain name to query DNS against. Typically, used by creating multiple DNS A Records for the same domain. Required if `discovery_mode` is set to dns. -aws_cloud_map_namespace_name | Conditionally | String | Cloud Map namespace when using AWS Cloud Map service discovery. Required if `discovery_mode` is set to `aws_cloud_map`. -aws_cloud_map_service_name | Conditionally | String | The Cloud Map service name when using AWS Cloud Map service discovery. Required if `discovery_mode` is set to `aws_cloud_map`. -aws_cloud_map_query_parameters | No | Map | A map of key-value pairs to filter the results based on the custom attributes attached to an instance. Only instances that match all the specified key-value pairs are returned. -buffer_size | No | Integer | The maximum number of unchecked records the buffer accepts. Number of unchecked records is the sum of the number of records written into the buffer and the num of in-flight records not yet checked by the Checkpointing API. Default is 512. -batch_size | No | Integer | The maximum number of records the buffer returns on read. Default is 48. -aws_region | Conditionally | String | The AWS region to use with ACM, S3 or AWS Cloud Map. Required if `use_acm_certificate_for_ssl` is set to true or `ssl_certificate_file` and `ssl_key_file` is AWS S3 path or `discovery_mode` is set to `aws_cloud_map`. -drain_timeout | No | Duration | The wait time for the peer forwarder to complete processing data before shutdown. Default is `10s`. - -#### TLS/SSL options for peer forwarder +The following table lists the general configuration for peer forwarding. Option | Required | Type | Description :--- | :--- | :--- | :--- -ssl | No | Boolean | Enables TLS/SSL. Default is `true`. -ssl_certificate_file | Conditionally | String | The SSL certificate chain file path or AWS S3 path. S3 path example `s3://<bucketName>/<path>`. Required if `ssl` is true and `use_acm_certificate_for_ssl` is false. Defaults to `config/default_certificate.pem` which is the default certificate file. Read more about how the certificate file is generated [here](https://github.com/opensearch-project/data-prepper/tree/main/examples/certificates). -ssl_key_file | Conditionally | String | The SSL key file path or AWS S3 path. S3 path example `s3://<bucketName>/<path>`. Required if `ssl` is true and `use_acm_certificate_for_ssl` is false. Defaults to `config/default_private_key.pem` which is the default private key file. Read more about how the default private key file is generated [here](https://github.com/opensearch-project/data-prepper/tree/main/examples/certificates). -ssl_insecure_disable_verification | No | Boolean | Disables the verification of server's TLS certificate chain. Default is false. -ssl_fingerprint_verification_only | No | Boolean | Disables the verification of server's TLS certificate chain and instead verifies only the certificate fingerprint. Default is false. -use_acm_certificate_for_ssl | No | Boolean | Enables TLS/SSL using certificate and private key from AWS Certificate Manager (ACM). Default is false. -acm_certificate_arn | Conditionally | String | The ACM certificate ARN. The ACM certificate takes preference over S3 or a local file system certificate. Required if `use_acm_certificate_for_ssl` is set to true. -acm_private_key_password | No | String | The ACM private key password that decrypts the private key. If not provided, Data Prepper generates a random password. -acm_certificate_timeout_millis | No | Integer | The timeout in milliseconds for ACM to get certificates. Default is 120000. -aws_region | Conditionally | String | The AWS region to use ACM, S3 or AWS Cloud Map. Required if `use_acm_certificate_for_ssl` is set to true or `ssl_certificate_file` and `ssl_key_file` is AWS S3 path or `discovery_mode` is set to `aws_cloud_map`. +`port` | No | Integer | The peer forwarding server port (`0`–`65535`). Default is `4994`. +`request_timeout` | No | Integer | The Peer Forwarder HTTP server request timeout, in milliseconds. Default is `10000`. +`server_thread_count` | No | Integer | The number of threads used by the Peer Forwarder server. Default is `200`. +`client_thread_count` | No | Integer | The number of threads used by the Peer Forwarder client. Default is `200`. +`max_connection_count` | No | Integer | The maximum number of open connections for the Peer Forwarder server. Default is `500`. +`max_pending_requests` | No | Integer | The maximum number of tasks in the `ScheduledThreadPool` work queue. Default is `1024`. +`discovery_mode` | No | String | The peer discovery mode. Valid values are `local_node` (process locally), `static` (fixed list of peers), `dns` (DNS A records), or `aws_cloud_map` (AWS service registry). Default is `local_node`. +`static_endpoints` | Conditional | List | The endpoints for all Data Prepper instances. Required if `discovery_mode` is set to `static`. +`domain_name` | Conditional | String | The domain name used for DNS-based discovery (supports multiple A records). Required if `discovery_mode` is set to `dns`. +`aws_cloud_map_namespace_name` | Conditional | String | The AWS Cloud Map namespace. Required if `discovery_mode` is set to `aws_cloud_map`. +`aws_cloud_map_service_name` | Conditional | String | The AWS Cloud Map service name. Required if `discovery_mode` is set to `aws_cloud_map`. +`aws_cloud_map_query_parameters` | No | Map | The key‑value filters applied to AWS Cloud Map instance attributes. +`buffer_size` | No | Integer | The maximum number of unchecked records the buffer can hold, including written and in-flight records that haven't been saved to a checkpoint. Default is `512`. +`batch_size` | No | Integer | The maximum number of records returned in a single read operation. Default is `48`. +`aws_region` | Conditional | String | The AWS Region used with AWS Certificate Manager (ACM), Amazon Simple Storage Service (Amazon S3), or AWS Cloud Map. Required if:<br> - `use_acm_certificate_for_ssl: true`. <br> - `ssl_certificate_file` or `ssl_key_file` is an S3 path. <br> - `discovery_mode` is set to `aws_cloud_map`. +`drain_timeout` | No | Duration | The amount of time allowed for Peer Forwarder to complete processing before shutdown. Default is `10s`. -#### Authentication options for peer forwarder +#### TLS/SSL options for Peer Forwarder + +Use the following options to enable and configure TLS/SSL for Peer Forwarder, including certificate sources (files, S3, or ACM) and verification behavior. Option | Required | Type | Description :--- | :--- | :--- | :--- -authentication | No | Map | The authentication method to use. Valid options are `mutual_tls` (use mTLS) or `unauthenticated` (no authentication). Default is `unauthenticated`. +`ssl` | No | Boolean | Enables TLS/SSL. Default is `true`. +`ssl_certificate_file` | Conditionally | String | The SSL certificate chain file path or S3 path (`s3://<bucket>/<path>`). Required if `ssl: true` and `use_acm_certificate_for_ssl: false`. Default is `config/default_certificate.pem`. See the [configuration example](https://github.com/opensearch-project/data-prepper/blob/17c3e290676e6c774cb8a0d4d8eaec7ae8bd696a/data-prepper-core/src/test/resources/valid_peer_forwarder_config_with_mutual_tls.yml) in the Data Prepper repo. +`ssl_key_file` | Conditionally | String | The SSL private key file path or S3 path. Required if `ssl` is set to `true` and `use_acm_certificate_for_ssl` is set to `false`. Default is `config/default_private_key.pem`. +`ssl_insecure_disable_verification` | No | Boolean | Disables verification of the server TLS certificate chain. Default is `false`. +`ssl_fingerprint_verification_only` | No | Boolean | If `true`, verifies only the certificate fingerprint (disables chain verification). Default is `false`. +`use_acm_certificate_for_ssl` | No | Boolean | If `true`, enables TLS/SSL using a certificate and private key from ACM. Default is `false`. +`acm_certificate_arn` | Conditionally | String | The ACM certificate Amazon Resource Name (ARN). Required if `use_acm_certificate_for_ssl` is set to `true`. +`acm_private_key_password` | No | String | The password used to decrypt the ACM private key. If not provided, Data Prepper generates a random password. +`acm_certificate_timeout_millis` | No | Integer | The timeout for retrieving ACM certificates, in milliseconds. Default is `120000`. +`aws_region` | Conditionally | String | The AWS Region used with ACM, S3, or AWS Cloud Map. Required if `use_acm_certificate_for_ssl` is set to `true`, the `ssl_certificate_file` or `ssl_key_file` is an S3 path, or `discovery_mode` is set to `aws_cloud_map`. -### Circuit breakers +#### Authentication options for Peer Forwarder -Data Prepper provides a circuit breaker to help prevent exhausting Java memory. And is useful when pipelines have stateful processors as these can retain memory usage outside of the buffers. +Use the following option to specify how Peer Forwarder authenticates requests between peers. -When a circuit breaker is tripped, Data Prepper rejects incoming data routing into buffers. +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`authentication` | No | Map | The authentication method. Valid values are `mutual_tls` (mTLS) or `unauthenticated` (no authentication). Default is `unauthenticated`. +## Circuit breakers + +Data Prepper includes a circuit breaker to prevent Java heap memory exhaustion. This is useful for pipelines that use stateful processors, which retain data in JVM heap memory outside the pipeline buffer. + +When a circuit breaker is open, Data Prepper rejects or delays incoming data depending on the source type and buffer configuration: + +- **All sources**: Write operations to the pipeline buffer fail with a timeout. This timeout has the same effect as a full buffer for each source — for example, the `http` source returns `408 Request Timeout`. The following buffers do not reject write operations: + - Buffers that store data outside of Data Prepper, such as the `kafka` buffer. The data is stored in Kafka and not in the JVM heap. The `kafka` buffer stops reading data from Kafka into Data Prepper until the circuit breaker closes. + - Buffers of pipelines that receive data from another pipeline. The first pipeline has already accepted the data. +- **OpenTelemetry sources**: The `otel_trace_source`, `otel_logs_source`, `otel_metrics_source`, and `otlp` sources reject requests before reading the request body. The source returns `RESOURCE_EXHAUSTED` for gRPC requests and `429 Too Many Requests` for HTTP requests. Both responses contain a retry delay based on the source's `retry_info` setting. The source does not reject health checks. These sources do not reject requests when writing to the `kafka` buffer or another buffer that stores data outside of Data Prepper. +- **Peer Forwarder**: The Peer Forwarder server rejects forwarded batches with `429 Too Many Requests` and a `Retry-After` header. The sending node processes the rejected records locally. + +The following table lists the available circuit breaker configuration blocks. Option | Required | Type | Description :--- | :--- |:---| :--- -heap | No | [heap](#heap-circuit-breaker) | Enables a heap circuit breaker. By default, this is not enabled. +`heap` | No | [heap](#heap-circuit-breaker) | Enables a heap circuit breaker. Disabled by default. +### Heap circuit breaker -#### Heap circuit breaker +The `heap` circuit breaker configures Data Prepper to reject incoming data when the JVM heap reaches a specified usage threshold. The `heap` parameter supports the following values. -Configures Data Prepper to trip a circuit breaker when JVM heap reaches a specified usage threshold. +Option | Required | Type | Default | Description +:--- |:---|:---|:---| :--- +`usage` | Yes | Bytes | None | The JVM heap usage at which to open the circuit breaker (for example, `6.5gb`). If current usage exceeds this value, the circuit breaker opens. +`close_usage` | No | Bytes | Value of `usage` | The JVM heap usage at or below which the circuit breaker closes again (for example, `5.5gb`). Must be greater than `0` and must not exceed `usage`. A value below `usage` keeps the circuit breaker open until enough memory has been freed, which prevents it from opening and closing in quick succession. +`check_interval` | No | Duration | `500ms` | The time interval between heap usage checks. +`reset` | No | Duration | `1s` | The minimum amount of time the circuit breaker remains open before heap usage checks can close it. Does not apply when the garbage collection requested on opening frees enough memory. -Option | Required | Type | Description -:--- |:---|:---| :--- -usage | Yes | Bytes | Specifies the JVM heap usage at which to trip a circuit breaker. If the current Java heap usage exceeds this value then the circuit breaker will be open. This can be a value such as `6.5gb`. -reset | No | Duration | After tripping the circuit breaker, no new checks are made until after this time has passed. This effectively sets the minimum time for a breaker to remain open to allow for clearing memory. Defaults to `1s`. -check_interval | No | Duration | Specifies the time between checks of the heap size. Defaults to `500ms`. +The following example opens the circuit breaker above 6.5 GB of heap usage and closes it again at or below 5.5 GB: -### Extension plugins +```yaml +circuit_breakers: + heap: + usage: 6.5gb + close_usage: 5.5gb +``` +{% include copy.html %} -Since Data Prepper 2.5, Data Prepper provides support for user configurable extension plugins. Extension plugins are shared common -configurations shared across pipeline plugins, such as [sources, buffers, processors, and sinks]({{site.url}}{{site.baseurl}}/data-prepper/index/#concepts). +#### How the heap circuit breaker opens and closes -### AWS extension plugins +Used heap includes garbage that the JVM has not yet collected, so heap usage can exceed `usage` even though Data Prepper is not overloaded. To distinguish between garbage and live data, the heap circuit breaker works as follows: -To use the AWS extension plugin, add the following setting to your `data-prepper-config.yaml` under `aws`. +1. When heap usage exceeds `usage`, the breaker opens and Data Prepper requests a garbage collection. If heap usage afterward is at or below `close_usage`, the breaker closes again in the same check. Data Prepper requests this garbage collection at most once every 5 seconds. If the breaker opens again within this interval, it stays open without a garbage collection. +2. If the breaker stays open, it closes as soon as a check after the `reset` period finds heap usage at or below `close_usage`. While the breaker is open and heap usage stays above `close_usage`, Data Prepper requests another garbage collection after 5 seconds and doubles this interval after each attempt, up to 60 seconds. -Option | Required | Type | Description -:--- |:---|:---| :--- -aws | No | Object | The AWS extension plugins configuration. +With the default G1 garbage collector, a requested garbage collection is a full collection that pauses all application threads. If the JVM runs with `-XX:+DisableExplicitGC`, Data Prepper cannot request garbage collections and the breaker only closes after the JVM collects garbage on its own. +{: .note} -#### AWS secrets extension plugin +#### Metrics -The AWS secrets extension plugin configures the [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) to be -referenced in pipeline plugin configurations, as shown in the following example: +The heap circuit breaker provides the following metrics. -```json +Metric | Type | Description +:--- | :--- | :--- +`core.circuitBreakers.heap.open` | Gauge | `1` while the circuit breaker is open, `0` while it is closed. +`core.circuitBreakers.heap.memoryUsage` | Gauge | The used JVM heap, in bytes. +`core.circuitBreakers.heap.trips` | Counter | The number of times the circuit breaker opened. Includes openings that the requested garbage collection resolved in the same check, which the `open` gauge might not show. +`core.circuitBreakers.heap.garbageCollection` | Timer | The garbage collections requested by the circuit breaker. The count shows how often the circuit breaker requested a garbage collection and the total and maximum time show how long these collections took. + +## Extension plugins + +Data Prepper supports user‑configurable extension plugins. Extension plugins provide a reusable configuration shared across pipeline plugins (sources, buffers, processors, or sinks). + +### AWS extension plugin + +The `aws` extension provides the `secrets` configuration, which integrates with [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) to securely manage sensitive configuration values in your pipelines. The following example shows a basic configuration: + +```yaml extensions: aws: secrets: @@ -128,52 +161,36 @@ extensions: region: <YOUR_REGION_1> sts_role_arn: <YOUR_STS_ROLE_ARN_1> refresh_interval: <YOUR_REFRESH_INTERVAL> + disable_refresh: false <YOUR_SECRET_CONFIG_ID_2>: - ... + # ... ``` - -To use the secrets extension plugin, add the following setting to your `pipeline.yaml` under `extensions` > `aws`. - -Option | Required | Type | Description -:--- |:---|:---| :--- -secrets | No | Object | The AWS Secrets Manager extension plugin configuration. See [Secrets](#secrets) for more details. +{% include copy.html %} ### Secrets -Use the following settings under the `secrets` extension setting. - +The `secrets` configuration supports the following parameters. Option | Required | Type | Description :--- |:---|:---| :--- -secret_id | Yes | String | The AWS secret name or ARN. | -region | No | String | The AWS region of the secret. Defaults to `us-east-1`. -sts_role_arn | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to the AWS Secrets Manager. Defaults to `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). -refresh_interval | No | Duration | The refreshment interval for AWS secrets extension plugin to poll new secret values. Defaults to `PT1H`. See [Automatically refreshing secrets](#automatically-refreshing-secrets) for details. +`secret_id` | Yes | String | The AWS secret name or ARN. +`region` | No | String | The AWS Region containing the secret. Default is `us-east-1`. +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for Secrets Manager requests. Default is `null` (standard SDK behavior for credentials). +`refresh_interval` | No | Duration | The poll interval for refreshing secret values. Default is `PT1H`. See [Automatically refreshing secrets](#automatically-refreshing-secrets). +`disable_refresh` | No | Boolean | Disables regular polling for the latest secret values. Default is `false`. When `true`, `refresh_interval` is ignored. #### Reference secrets -ß -In `pipelines.yaml`, secret values can be referenced within the pipeline plugins using the following formats: -* plaintext: `{% raw %}${{aws_secrets:<YOUR_SECRET_CONFIG_ID>}}{% endraw %}`. -* JSON (key-value pairs): `{% raw %}${{aws_secrets:<YOUR_SECRET_CONFIG_ID>:<YOUR_KEY>}}{% endraw %}` +In `pipelines.yaml`, reference secret values in plugin settings using: - -Replace `<YOUR_SECRET_CONFIG_ID>` with the corresponding secret config ID under `/extensions/aws/secrets`. Replace `<YOUR_KEY>` with the desired key in the secret JSON value. The secret value reference string format can be interpreted for the following plugin setting data types: +* Plaintext: `{% raw %}${{aws_secrets:<YOUR_SECRET_CONFIG_ID>}}{% endraw %}` +* JSON key: `{% raw %}${{aws_secrets:<YOUR_SECRET_CONFIG_ID>:<YOUR_KEY>}}{% endraw %}` -* String -* Number -* Long -* Short -* Integer -* Double -* Float -* Boolean -* Character +You can use the following setting types for secret substitution: string, number, long, short, integer, double, float, Boolean, or character. -The following example section of `data-prepper-config.yaml` names two secret config IDs, `host-secret-config` and `credential-secret-config`: +The following is an example `data-prepper-config.yaml` with two secret configuration IDs (`host-secret-config` and `credential-secret-config`): - -```json +```yaml extensions: aws: secrets: @@ -188,21 +205,20 @@ extensions: sts_role_arn: <YOUR_STS_ROLE_ARN_2> refresh_interval: <YOUR_REFRESH_INTERVAL_2> ``` +{% include copy.html %} -After `<YOUR_SECRET_CONFIG_ID>` is configured, you can reference the IDs in your `pipelines.yaml`: +You can then reference these secrets in `pipelines.yaml` as follows: -``` +```yaml sink: - - opensearch: - hosts: [ {% raw %}"${{aws_secrets:host-secret-config}}"{% endraw %} ] - username: {% raw %}"${{aws_secrets:credential-secret-config:username}}"{% endraw %} - password: {% raw %}"${{aws_secrets:credential-secret-config:password}}"{% endraw %} - index: "test-migration" + - opensearch: + hosts: [{% raw %}"${{aws_secrets:host-secret-config}}"{% endraw %}] + username: {% raw %}"${{aws_secrets:credential-secret-config:username}}"{% endraw %} + password: {% raw %}"${{aws_secrets:credential-secret-config:password}}"{% endraw %} + index: "test-migration" ``` - +{% include copy.html %} #### Automatically refreshing secrets -For each individual secret configuration, the latest secret value is polled on a regular interval to support refreshing secrets in AWS Secrets Manager. The refreshed secret values are utilized by certain pipeline plugins to refresh their components, such as connection and authentication to the backend service. - -For multiple secret configurations, jitter within `60s` will be applied across all configurations during the initial secrets polling. +For each secret configuration, Data Prepper polls the latest value at a regular interval to support rotating secrets in AWS Secrets Manager. Refreshed values are used by plugins that can refresh their connections/authentication (for example, sinks). For multiple secret configurations, a jitter of up to `60s` is applied across all configurations during the initial polling. diff --git a/_data-prepper/managing-data-prepper/configuring-log4j.md b/_data-prepper/managing-data-prepper/configuring-log4j.md index 175c754a..d7c2c5d2 100644 --- a/_data-prepper/managing-data-prepper/configuring-log4j.md +++ b/_data-prepper/managing-data-prepper/configuring-log4j.md @@ -1,29 +1,38 @@ --- layout: default title: Configuring Log4j -parent: Managing Data Prepper +parent: Managing OpenSearch Data Prepper nav_order: 20 --- # Configuring Log4j -You can configure logging using Log4j in Data Prepper. +You can configure logging using Log4j in OpenSearch Data Prepper. ## Logging Data Prepper uses [SLF4J](https://www.slf4j.org/) with a [Log4j 2 binding](https://logging.apache.org/log4j/2.x/log4j-slf4j-impl.html). -For Data Prepper versions 2.0 and later, the Log4j 2 configuration file can be found and edited in `config/log4j2.properties` in the application's home directory. The default properties for Log4j 2 can be found in `log4j2-rolling.properties` in the *shared-config* directory. +Data Prepper reads its Log4j 2 configuration from the `config/log4j2-rolling.properties` file in the Data Prepper home directory. To customize logging, edit or replace this file. In Docker, the file path is `/usr/share/data-prepper/config/log4j2-rolling.properties`. -For Data Prepper versions before 2.0, the Log4j 2 configuration file can be overridden by setting the `log4j.configurationFile` system property when running Data Prepper. The default properties for Log4j 2 can be found in `log4j2.properties` in the *shared-config* directory. - -### Example - -When running Data Prepper, the following command can be overridden by setting the system property `-Dlog4j.configurationFile={property_value}`, where `{property_value}` is a path to the Log4j 2 configuration file: +To use a configuration file in a different location, set the `log4j.configurationFile` system property in the `JAVA_OPTS` environment variable before starting Data Prepper: +```bash +export JAVA_OPTS="-Dlog4j.configurationFile=/path/to/log4j2.properties" +bin/data-prepper ``` -java "-Dlog4j.configurationFile=config/custom-log4j2.properties" -jar data-prepper-core-$VERSION.jar pipelines.yaml data-prepper-config.yaml +{% include copy.html %} + +In Docker, pass the environment variable using the `-e` option and mount the configuration file into the container: + +```bash +docker run --name data-prepper \ + -e JAVA_OPTS="-Dlog4j.configurationFile=/usr/share/data-prepper/custom/log4j2.properties" \ + -v ${PWD}/log4j2.properties:/usr/share/data-prepper/custom/log4j2.properties \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + opensearchproject/data-prepper:latest ``` +{% include copy.html %} See the [Log4j 2 configuration documentation](https://logging.apache.org/log4j/2.x/manual/configuration.html) for more information about Log4j 2 configuration. diff --git a/_data-prepper/managing-data-prepper/core-apis.md b/_data-prepper/managing-data-prepper/core-apis.md index b810c7b1..0465b0ba 100644 --- a/_data-prepper/managing-data-prepper/core-apis.md +++ b/_data-prepper/managing-data-prepper/core-apis.md @@ -1,13 +1,13 @@ --- layout: default title: Core APIs -parent: Managing Data Prepper +parent: Managing OpenSearch Data Prepper nav_order: 15 --- # Core APIs -All Data Prepper instances expose a server with some control APIs. By default, this server runs on port 4900. Some plugins, especially source plugins, may expose other servers that run on different ports. Configurations for these plugins are independent of the core API. For example, to shut down Data Prepper, you can run the following curl request: +All OpenSearch Data Prepper instances expose a server with some control APIs. By default, this server runs on port 4900. Some plugins, especially source plugins, may expose other servers that run on different ports. Configurations for these plugins are independent of the core API. For example, to shut down Data Prepper, you can run the following cURL request: ``` curl -X POST http://localhost:4900/shutdown @@ -72,7 +72,7 @@ authentication: ### Peer Forwarder -Peer Forwarder can be configured to enable stateful aggregation across multiple Data Prepper nodes. For more information about configuring Peer Forwarder, see [Peer forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/). It is supported by the `service_map_stateful`, `otel_traces_raw`, and `aggregate` processors. +Peer Forwarder can be configured to enable stateful aggregation across multiple Data Prepper nodes. For more information about configuring Peer Forwarder, see [Peer Forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/). It is supported by the `service_map`, `otel_traces`, and `aggregate` processors. ### Shutdown timeouts diff --git a/_data-prepper/managing-data-prepper/extensions/extensions.md b/_data-prepper/managing-data-prepper/extensions/extensions.md new file mode 100644 index 00000000..4a060a47 --- /dev/null +++ b/_data-prepper/managing-data-prepper/extensions/extensions.md @@ -0,0 +1,15 @@ +--- +layout: default +title: Extensions +parent: Managing OpenSearch Data Prepper +has_children: true +nav_order: 18 +--- + +# Data Prepper extensions + +OpenSearch Data Prepper extensions provide Data Prepper functionality outside of core Data Prepper pipeline components. +Many extensions provide configuration options that give Data Prepper administrators greater flexibility over Data Prepper's functionality. + +Extension configurations can be configured in the `data-prepper-config.yaml` file under the `extensions:` YAML block. + diff --git a/_data-prepper/managing-data-prepper/extensions/geoip-service.md b/_data-prepper/managing-data-prepper/extensions/geoip-service.md new file mode 100644 index 00000000..7b68493c --- /dev/null +++ b/_data-prepper/managing-data-prepper/extensions/geoip-service.md @@ -0,0 +1,75 @@ +--- +layout: default +title: geoip_service +nav_order: 5 +parent: Extensions +grand_parent: Managing OpenSearch Data Prepper +redirect_from: + - /data-prepper/managing-data-prepper/extensions/geoip_service/ +--- + +# GeoIP service extension + +The `geoip_service` extension configures all [`geoip`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/geoip) processors in OpenSearch Data Prepper. + +## Usage + +You can configure the GeoIP service that Data Prepper uses for the `geoip` processor. +By default, the GeoIP service comes with the [`maxmind`](#maxmind) option configured. + +The following example shows how to configure the `geoip_service` in the `data-prepper-config.yaml` file: + +``` +extensions: + geoip_service: + maxmind: + database_refresh_interval: PT1H + cache_count: 16_384 +``` + +<!-- vale off --> +## maxmind +<!-- vale on --> + +The GeoIP service supports the MaxMind [GeoIP and GeoLite](https://dev.maxmind.com/geoip) databases. +By default, Data Prepper will use all three of the following [MaxMind GeoLite2](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) databases: + +* City +* Country +* ASN + +The service also downloads databases automatically to keep Data Prepper up to date with changes from MaxMind. + +You can use the following options to configure the `maxmind` extension. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`databases` | No | [database](#database) | The database configuration. +`database_refresh_interval` | No | Duration | How frequently to check for updates from MaxMind. This can be any duration in the range of 15 minutes to 30 days. Default is `PT7D`. +`cache_count` | No | Integer | The maximum cache count by number of items in the cache, with a range of 100--100,000. Default is `4096`. +`database_destination` | No | String | The name of the directory in which to store downloaded databases. Default is `{data-prepper.dir}/data/geoip`. +`aws` | No | [`aws`](#aws) | Configures the AWS credentials for downloading the database from Amazon Simple Storage Service (Amazon S3). +`insecure` | No | Boolean | When `true`, this options allows you to download database files over HTTP. Default is `false`. + +<!-- vale off --> +## database +<!-- vale on --> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`city` | No | String | The URL of the city in which the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. +`country` | No | String | The URL of the country in which the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. +`asn` | No | String | The URL of the Autonomous System Number (ASN) of where the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. +`enterprise` | No | String | The URL of the enterprise in which the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. + + +<!-- vale off --> +## aws +<!-- vale on --> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for the credentials. Default is the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon S3. Default is `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`aws_sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes when downloading from Amazon S3. +`sts_external_id` | No | String | An STS external ID used when Data Prepper assumes the STS role. For more information, see the `ExternalID` documentation in the [STS AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API reference. diff --git a/_data-prepper/managing-data-prepper/latency.md b/_data-prepper/managing-data-prepper/latency.md new file mode 100644 index 00000000..8b6a0ead --- /dev/null +++ b/_data-prepper/managing-data-prepper/latency.md @@ -0,0 +1,152 @@ +--- +layout: default +title: Pipeline latency tuning guide +parent: Managing OpenSearch Data Prepper +nav_order: 45 +--- + +# Pipeline latency tuning guide + +This section provides the most effective configurations for reducing end-to-end latency and contains ready-to-use examples. + +There are two latency types: + +- **Ingest latency**: The amount of time from the moment the source receives data until the sink sends it to OpenSearch or another destination. +- **Searchable latency**: The amount of time until data becomes visible in OpenSearch search results. This is capped by the index's `refresh_interval`. + +## Low-latency configuration + +The following table lists configurations that can be adjusted to improve latency. + +Component | Setting | Why it matters | Low‑latency starting point | Trade‑offs +:--- | :--- | :--- | :--- | :--- +**Pipeline loop** | `workers` in each pipeline | Increasing parallelism reduces queueing in CPU- or I/O-bound pipelines. | Typically set to the number of CPU cores; increase if sinks are I/O bound. | Higher CPU usage and more concurrent requests sent to sinks. +**Pipeline loop** | `delay` | The pause between buffer reads. | `0`--`10ms` to pull data as soon as possible. | Lower delays reduce latency but increase polling overhead, context switches, and CPU activations. Adjust to balance latency and CPU usage. +**Bounded blocking buffer** | `batch_size` | Determines how many records are processed per batch; smaller batches flush sooner. | 64--256 | Smaller batches reduce throughput and increase the number of requests. +**Peer Forwarder** | `batch_size`, `request_timeout` | Batch size and request timeouts impact hop-to-hop latency. | Keep `batch_size` moderate, for example, 48--128. | Too small a `batch_size` reduces throughput, and a `request_timeout` that is too short can cause retries or timeouts under load. +**Peer Forwarder** | `forwarder` [configuration]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/#configuration) | Limits queueing before forwarding. | Use low timeouts, for example, 50–200 ms. | Shorter timeouts increase in-flight requests and connections, adding CPU, memory, TLS handshake, and context-switch overhead. Longer timeouts can cause queue buildup and higher tail latency. +**Aggregate processors** | `group_duration` | Determines how long events wait for the aggregation window to close. | Prefer removing aggregation; if needed, keep the window short, for example, `5s`. | Smaller windows can break grouping semantics. +**OpenSearch sink** | `bulk_size` (MiB) | Determines the size of bulk requests; smaller bulks flush sooner. | 1--5 MiB | Very small `bulk_size` increases the number of bulk requests, adds HTTP/TLS overhead, causes more thread pool contention, produces smaller Lucene batches, and lowers throughput. Very large `bulk_size` increases the time needed to fill a batch and can cause memory spikes, larger retries, and higher p95/p99 latency. +**OpenSearch sink** | `index.refresh_interval` | Controls how frequently indexed data becomes searchable. | `1s` (default) | Lower values increase segment churn and indexing overhead. + +The `delay` processor adds latency by design. Avoid it in low‑latency pipelines. +{: .note} + +## Low‑latency configuration examples + +The following are low-latency configuration examples. + +### Logs: Prioritize sub‑second ingest + +You can use the following example when you need sub‑second end‑to‑end ingest for HTTP log intake. It minimizes batching and avoids heavy processors so events flush to OpenSearch quickly while keeping CPU costs predictable: + +```yaml +logs-low-latency: + workers: 4 + delay: 0 + source: + http: + port: 2021 + path: /logs + ssl: true + sslKeyCertChainFile: certs/dp.crt + sslKeyFile: certs/dp.key + buffer: + bounded_blocking: + buffer_size: 4096 + batch_size: 128 + processor: [] # keep light, avoid heavy aggregation + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index_type: log-analytics + bulk_size: 1 # MiB; smaller -> lower latency, lower throughput + max_retries: 8 +``` +{% include copy.html %} + +### Traces with peer forwarding minimizing cross‑node wait + +You can use the following example configuration to minimize cross‑node wait for distributed tracing. The `data-prepper-config.yaml` file enables low‑latency, mTLS‑secured peer forwarding with fast timeouts, and the `pipelines.yml` file splits ingestion from raw indexing so that the forwarding hop stays lightweight. + +Create the following `data-prepper-config.yaml` file: + +```yaml + +ssl: true +serverPort: 4900 +keyStoreFilePath: certs/dp1-admin.p12 # or .jks +keyStorePassword: changeit +privateKeyPassword: changeit + +# Or disable ssl on top-level admin/metrics server +#ssl: false +#serverPort: 4900 + +authentication: + http_basic: + username: myuser + password: "mys3cr3t" + # or disable http_basic authentication + #unauthenticated: + +peer_forwarder: + + ssl: true + ssl_certificate_file: certs/dp1-peer.crt + ssl_key_file: certs/dp1-peer.key + authentication: + mutual_tls: {} + port: 4994 # Default + # choose one discovery mode + # Discovery mode: dns + discovery_mode: dns + domain_name: data-prepper.your-domain.local + + # discovery_mode: static + #port: 4994 + #static_endpoints: ["dp1", "dp2"] + + # lower batching/wait + batch_size: 96 + request_timeout: 1000 # ms +``` +{% include copy.html %} + +Create the following `pipelines.yml` file: + +```yaml +traces-low-latency: + workers: 4 + delay: 0 + source: + otel_trace_source: + port: 21890 + ssl: true + sslKeyCertChainFile: certs/dp.crt + sslKeyFile: certs/dp.key + buffer: + bounded_blocking: + buffer_size: 4096 + batch_size: 96 + processor: + - trace_peer_forwarder: {} + sink: + - pipeline: + name: raw-trace-pipeline # feed the next pipeline + +raw-trace-pipeline: + source: + pipeline: + name: traces-low-latency # consumes from above + processor: + - otel_traces: + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: trace-analytics-raw +``` +{% include copy.html %} \ No newline at end of file diff --git a/_data-prepper/managing-data-prepper/managing-data-prepper.md b/_data-prepper/managing-data-prepper/managing-data-prepper.md index ea2d1f11..204510be 100644 --- a/_data-prepper/managing-data-prepper/managing-data-prepper.md +++ b/_data-prepper/managing-data-prepper/managing-data-prepper.md @@ -1,10 +1,10 @@ --- layout: default -title: Managing Data Prepper +title: Managing OpenSearch Data Prepper has_children: true nav_order: 20 --- -# Managing Data Prepper +# Managing OpenSearch Data Prepper -You can perform administrator functions for Data Prepper, including system configuration, interacting with core APIs, Log4j configuration, and monitoring. You can set up peer forwarding to coordinate multiple Data Prepper nodes when using stateful aggregation. \ No newline at end of file +You can perform administrator functions for OpenSearch Data Prepper, including system configuration, interacting with core APIs, Log4j configuration, and monitoring. You can set up peer forwarding to coordinate multiple Data Prepper nodes when using stateful aggregation. \ No newline at end of file diff --git a/_data-prepper/managing-data-prepper/monitoring.md b/_data-prepper/managing-data-prepper/monitoring.md index 691f376b..2b304644 100644 --- a/_data-prepper/managing-data-prepper/monitoring.md +++ b/_data-prepper/managing-data-prepper/monitoring.md @@ -1,17 +1,17 @@ --- layout: default title: Monitoring -parent: Managing Data Prepper +parent: Managing OpenSearch Data Prepper nav_order: 25 --- -# Monitoring Data Prepper with metrics +# Monitoring OpenSearch Data Prepper with metrics -You can monitor Data Prepper with metrics using [Micrometer](https://micrometer.io/). There are two types of metrics: JVM/system metrics and plugin metrics. [Prometheus](https://prometheus.io/) is used as the default metrics backend. +You can monitor OpenSearch Data Prepper with metrics using [Micrometer](https://micrometer.io/). There are two types of metrics: JVM/system metrics and plugin metrics. [Prometheus](https://prometheus.io/) is used as the default metrics backend. ## JVM and system metrics -JVM and system metrics are runtime metrics that are used to monitor Data Prepper instances. They include metrics for classloaders, memory, garbage collection, threads, and others. For more information, see [JVM and system metrics](https://micrometer.io/?/docs/ref/jvm). +JVM and system metrics are runtime metrics that are used to monitor Data Prepper instances. They include metrics for class loaders, memory, garbage collection, threads, and others. For more information, see [JVM and system metrics](https://micrometer.io/?/docs/ref/jvm). ### Naming @@ -26,34 +26,34 @@ By default, metrics are served from the **/metrics/sys** endpoint on the Data Pr Plugins report their own metrics. Data Prepper uses a naming convention to help with consistency in the metrics. Plugin metrics do not use dimensions. -1. AbstractBuffer - - Counter +1. `AbstractBuffer` + - `Counter` - `recordsWritten`: The number of records written into a buffer - `recordsRead`: The number of records read from a buffer - `recordsProcessed`: The number of records read from a buffer and marked as processed - `writeTimeouts`: The count of write timeouts in a buffer - - Gaugefir + - `Gaugefir` - `recordsInBuffer`: The number of records in a buffer - - `recordsInFlight`: The number of records read from a buffer and being processed by data-prepper downstreams (for example, processor, sink) - - Timer + - `recordsInFlight`: The number of records read from a buffer and being processed by downstream components (for example, processors and sinks) + - `Timer` - `readTimeElapsed`: The time elapsed while reading from a buffer - `checkpointTimeElapsed`: The time elapsed while checkpointing -2. AbstractProcessor - - Counter +2. `AbstractProcessor` + - `Counter` - `recordsIn`: The number of records ingressed into a processor - `recordsOut`: The number of records egressed from a processor - - Timer + - `Timer` - `timeElapsed`: The time elapsed during initiation of a processor -3. AbstractSink - - Counter +3. `AbstractSink` + - `Counter` - `recordsIn`: The number of records ingressed into a sink - - Timer + - `Timer` - `timeElapsed`: The time elapsed during execution of a sink ### Naming -Metrics follow a naming convention of **PIPELINE_NAME_PLUGIN_NAME_METRIC_NAME**. For example, a **recordsIn** metric for the **opensearch-sink** plugin in a pipeline named **output-pipeline** has a qualified name of **output-pipeline_opensearch_sink_recordsIn**. +Metrics follow a naming convention of `PIPELINE_NAME_PLUGIN_NAME_METRIC_NAME`. For example, a `recordsIn` metric for the `opensearch-sink` plugin in a pipeline named `output-pipeline` has a qualified name of `output-pipeline_opensearch_sink_recordsIn`. ### Serving -By default, metrics are served from the **/metrics/sys** endpoint on the Data Prepper server in a Prometheus scrape format. You can configure Prometheus to scrape from the Data Prepper URL. The Data Prepper server port has a default value of `4900` that you can modify, and this port can be used for any frontend that accepts Prometheus metrics, such as [Grafana](https://prometheus.io/docs/visualization/grafana/). You can update the configuration to serve metrics to other registries like CloudWatch, that does not require or host the endpoint, but publishes the metrics directly to CloudWatch. \ No newline at end of file +By default, metrics are served from the `/metrics/sys` endpoint on the Data Prepper server in a Prometheus scrape format. You can configure Prometheus to scrape from the Data Prepper URL. The Data Prepper server port has a default value of `4900` that you can modify, and this port can be used for any frontend that accepts Prometheus metrics, such as [Grafana](https://prometheus.io/docs/visualization/grafana/). You can update the configuration to serve metrics to other registries like CloudWatch, that does not require or host the endpoint, but publishes the metrics directly to CloudWatch. \ No newline at end of file diff --git a/_data-prepper/managing-data-prepper/peer-forwarder.md b/_data-prepper/managing-data-prepper/peer-forwarder.md index f6a0f989..4fd58216 100644 --- a/_data-prepper/managing-data-prepper/peer-forwarder.md +++ b/_data-prepper/managing-data-prepper/peer-forwarder.md @@ -1,15 +1,15 @@ --- layout: default -title: Peer forwarder +title: Peer Forwarder nav_order: 12 -parent: Managing Data Prepper +parent: Managing OpenSearch Data Prepper --- -# Peer forwarder +# Peer Forwarder -Peer forwarder is an HTTP service that performs peer forwarding of an `event` between Data Prepper nodes for aggregation. This HTTP service uses a hash-ring approach to aggregate events and determine which Data Prepper node it should handle on a given trace before rerouting it to that node. Currently, peer forwarder is supported by the `aggregate`, `service_map_stateful`, and `otel_traces_raw` [processors]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/). +Peer Forwarder is an HTTP service that performs peer forwarding of an `event` between OpenSearch Data Prepper nodes for aggregation. This HTTP service uses a hash-ring approach to aggregate events and determine which Data Prepper node it should handle on a given trace before rerouting it to that node. Currently, Peer Forwarder is supported by the `aggregate`, `service_map`, and `otel_traces` [processors]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/). -Peer Forwarder groups events based on the identification keys provided by the supported processors. For `service_map_stateful` and `otel_traces_raw`, the identification key is `traceId` by default and cannot be configured. The `aggregate` processor is configured using the `identification_keys` configuration option. From here, you can specify which keys to use for Peer Forwarder. See [Aggregate Processor page](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#identification_keys) for more information about identification keys. +Peer Forwarder groups events based on the identification keys provided by the supported processors. For `service_map` and `otel_traces`, the identification key is `traceId` by default and cannot be configured. The `aggregate` processor is configured using the `identification_keys` configuration option. From here, you can specify which keys to use for Peer Forwarder. See [Aggregate Processor page](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#identification_keys) for more information about identification keys. Peer discovery allows Data Prepper to find other nodes that it will communicate with. Currently, peer discovery is provided by a static list, a DNS record lookup, or AWS Cloud Map. @@ -41,7 +41,7 @@ peer_forwarder: [AWS Cloud Map](https://docs.aws.amazon.com/cloud-map/latest/dg/what-is-cloud-map.html) provides API-based service discovery as well as DNS-based service discovery. -Peer forwarder can use the API-based service discovery in AWS Cloud Map. To support this, you must have an existing namespace configured for API instance discovery. You can create a new one by following the instructions provided by the [AWS Cloud Map documentation](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html). +Peer Forwarder can use the API-based service discovery in AWS Cloud Map. To support this, you must have an existing namespace configured for API instance discovery. You can create a new one by following the instructions provided by the [AWS Cloud Map documentation](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html). Your Data Prepper configuration needs to include the following: * `aws_cloud_map_namespace_name` – Set to your AWS Cloud Map namespace name. @@ -92,11 +92,11 @@ The following table provides optional configuration values. | Value | Type | Description | | ---- | --- | ----------- | -| `port` | Integer | A value between 0 and 65535 that represents the port that the peer forwarder server is running on. Default value is `4994`. | -| `request_timeout` | Integer | Represents the request timeout duration in milliseconds for the peer forwarder HTTP server. Default value is `10000`. | -| `server_thread_count` | Integer | Represents the number of threads used by the peer forwarder server. Default value is `200`.| -| `client_thread_count` | Integer | Represents the number of threads used by the peer forwarder client. Default value is `200`.| -| `maxConnectionCount` | Integer | Represents the maximum number of open connections for the peer forwarder server. Default value is `500`. | +| `port` | Integer | A value between 0 and 65535 that represents the port that the Peer Forwarder server is running on. Default value is `4994`. | +| `request_timeout` | Integer | Represents the request timeout duration in milliseconds for the Peer Forwarder HTTP server. Default value is `10000`. | +| `server_thread_count` | Integer | Represents the number of threads used by the Peer Forwarder server. Default value is `200`.| +| `client_thread_count` | Integer | Represents the number of threads used by the Peer Forwarder client. Default value is `200`.| +| `maxConnectionCount` | Integer | Represents the maximum number of open connections for the Peer Forwarder server. Default value is `500`. | | `discovery_mode` | String | Represents the peer discovery mode to be used. Allowable values are `local_node`, `static`, `dns`, and `aws_cloud_map`. Defaults to `local_node`, which processes events locally. | | `static_endpoints` | List | Contains the endpoints of all Data Prepper instances. Required if `discovery_mode` is set to `static`. | | `domain_name` | String | Represents the single domain name to query DNS against. Typically used by creating multiple [DNS A records](https://www.cloudflare.com/learning/dns/dns-records/dns-a-record/) for the same domain. Required if `discovery_mode` is set to `dns`. | @@ -105,12 +105,16 @@ The following table provides optional configuration values. | `aws_cloud_map_query_parameters` | Map | Key-value pairs used to filter the results based on the custom attributes attached to an instance. Only instances that match all the specified key-value pairs are returned. | | `buffer_size` | Integer | Represents the maximum number of unchecked records the buffer accepts (the number of unchecked records equals the number of records written into the buffer plus the number of records that are still processing and not yet checked by the Checkpointing API). Default is `512`. | | `batch_size` | Integer | Represents the maximum number of records that the buffer returns on read. Default is `48`. | +| `batch_delay` | Integer | Represents the maximum amount of time, in milliseconds, to retrieve `batch_size` records from the Peer Forwarder buffer. If `batch_size` is not reached within this duration, a partial batch is returned. If set to `0`, all available records up to `batch_size` are returned immediately. If the buffer is empty, it blocks for up to 5 milliseconds while waiting for records. Default is `3000`. | | `aws_region` | String | Represents the AWS Region that uses `ACM`, `Amazon S3`, or `AWS Cloud Map` and is required when any of the following conditions are met:<br> - The `use_acm_certificate_for_ssl` setting is set to `true`. <br> - Either `ssl_certificate_file` or `ssl_key_file` specifies an Amazon Simple Storage Service (Amazon S3) URI (for example, s3://mybucket/path/to/public.cert).<br> - The `discovery_mode` is set to `aws_cloud_map`. | -| `drain_timeout` | Duration | Represents the amount of time that peer forwarder will wait to complete data processing before shutdown. | +| `drain_timeout` | Duration | Represents the amount of time that Peer Forwarder will wait to complete data processing before shutdown. | +| `forwarding_batch_size` | Integer | Represents the maximum number of records to send in each request to a peer. Default is `1500`. Maximum is `15000`. | +| `forwarding_batch_queue_depth` | Integer | Represents the depth of the batching queue. This value is a scalar used to determine the size of the linked blocking queues used for batching records before they are sent to a peer. The queue size is determined by the formula `workers * forwarding_batch_size * forwarding_batch_queue_depth`. Default is `1`. | +| `forwarding_batch_timeout` | Duration | Represents the maximum amount of time that can occur between flushing batches to a peer. Default is `3s`. | ## SSL configuration -The following table provides optional SSL configuration values that allow you to set up a trust manager for the peer forwarder client in order to connect to other Data Prepper instances. +The following table provides optional SSL configuration values that allow you to set up a trust manager for the Peer Forwarder client in order to connect to other Data Prepper instances. | Value | Type | Description | | ----- | ---- | ----------- | @@ -146,16 +150,24 @@ peer_forwarder: mutual_tls: ``` +## Circuit breaker + +When a [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is configured, the Peer Forwarder server rejects forwarded requests with an HTTP `429` response and a `Retry-After` header while the circuit breaker is open. The server rejects the requests before reading their bodies. + +The sending node does not retry rejected requests. Instead, it processes the records locally, following the same behavior used for any failed forwarding request. However, because these records are not processed on the node responsible for their identification keys, stateful processors such as `aggregate` might produce partial results. + +Use the `recordsRejectedByPeer` metric to monitor these rejections. + ## Metrics -Core peer forwarder introduces the following custom metrics. All the metrics are prefixed by `core.peerForwarder`. +Core Peer Forwarder introduces the following custom metrics. All the metrics are prefixed by `core.peerForwarder`. ### Timer -Peer forwarder's timer capability provides the following information: +Peer Forwarder's timer capability provides the following information: -- `requestForwardingLatency`: Measures latency of requests forwarded by the peer forwarder client. -- `requestProcessingLatency`: Measures latency of requests processed by the peer forwarder server. +- `requestForwardingLatency`: Measures latency of requests forwarded by the Peer Forwarder client. +- `requestProcessingLatency`: Measures latency of requests processed by the Peer Forwarder server. ### Counter @@ -166,15 +178,17 @@ The following table provides counter metric options. | `requests`| Measures the total number of forwarded requests. | | `requestsFailed`| Measures the total number of failed requests. Applies to requests with an HTTP response code other than `200`. | | `requestsSuccessful`| Measures the total number of successful requests. Applies to requests with HTTP response code `200`. | -| `requestsTooLarge`| Measures the total number of requests that are too large to be written to the peer forwarder buffer. Applies to requests with HTTP response code `413`. | -| `requestTimeouts`| Measures the total number of requests that time out while writing content to the peer forwarder buffer. Applies to requests with HTTP response code `408`. | -| `requestsUnprocessable`| Measures the total number of requests that fail due to an unprocessable entity. Applies to requests with HTTP response code `422`. | +| `requestsTooLarge`| Measures the total number of requests that are too large to be written to the Peer Forwarder buffer. Applies to requests with HTTP response code `413`. | +| `requestTimeouts`| Measures the total number of requests that time out while writing content to the Peer Forwarder buffer. Applies to requests with HTTP response code `408`. | +| `requestsUnprocessable`| Measures the total number of requests that fail because of an entity that cannot be processed. Applies to requests with HTTP response code `422`. | | `badRequests`| Measures the total number of requests with a bad request format. Applies to requests with HTTP response code `400`. | | `recordsSuccessfullyForwarded`| Measures the total number of successfully forwarded records. | | `recordsFailedForwarding`| Measures the total number of records that fail to be forwarded. | | `recordsToBeForwarded` | Measures the total number of records to be forwarded. | | `recordsToBeProcessedLocally` | Measures the total number of records to be processed locally. | -| `recordsActuallyProcessedLocally`| Measures the total number of records actually processed locally. This value is the sum of `recordsToBeProcessedLocally` and `recordsFailedForwarding`. | +| `recordsActuallyProcessedLocally`| Measures the total number of records processed locally, calculated as the sum of `recordsToBeProcessedLocally` and `recordsFailedForwarding` minus `recordsDroppedAfterFailedForwarding`. | +| `recordsRejectedByPeer`| Measures the total number of records in requests that the receiving peer rejected with an HTTP response code `429` because its [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is open. These records are processed on the sending node instead of the node that owns their identification keys. They are also counted in `recordsFailedForwarding`. | +| `recordsDroppedAfterFailedForwarding`| Measures the total number of records that were dropped because they could not be written to the local buffer after a failed forwarding request. These records are included in `recordsFailedForwarding`. | | `recordsReceivedFromPeers`| Measures the total number of records received from remote peers. | ### Gauge diff --git a/_data-prepper/managing-data-prepper/source-coordination.md b/_data-prepper/managing-data-prepper/source-coordination.md index 3c60b452..a729964d 100644 --- a/_data-prepper/managing-data-prepper/source-coordination.md +++ b/_data-prepper/managing-data-prepper/source-coordination.md @@ -2,12 +2,12 @@ layout: default title: Source coordination nav_order: 35 -parent: Managing Data Prepper +parent: Managing OpenSearch Data Prepper --- # Source coordination -_Source coordination_ is the concept of coordinating and distributing work between Data Prepper data sources in a multi-node environment. Some data sources, such as Amazon Kinesis or Amazon Simple Queue Service (Amazon SQS), handle coordination natively. Other data sources, such as OpenSearch, Amazon Simple Storage Service (Amazon S3), Amazon DynamoDB, and JDBC/ODBC, do not support source coordination. +_Source coordination_ is the concept of coordinating and distributing work between OpenSearch Data Prepper data sources in a multi-node environment. Some data sources, such as Amazon Kinesis or Amazon Simple Queue Service (Amazon SQS), handle coordination natively. Other data sources, such as OpenSearch, Amazon Simple Storage Service (Amazon S3), Amazon DynamoDB, and JDBC/ODBC, do not support source coordination. Data Prepper source coordination decides which partition of work is performed by each node in the Data Prepper cluster and prevents duplicate partitions of work. @@ -47,27 +47,41 @@ Any function that is passed to the `getNextPartition` method creates new partiti ## Configuration -The following table provide optional configuration values for `source_coordination`. +The following table provides optional configuration values for `source_coordination`. | Value | Type | Description | | :--- | :--- | :--- | | `partition_prefix` | String | A prefix to the `sourceIdentifier` used to differentiate between Data Prepper clusters that share the same distributed store. | -| `store` | Object | The object that comprises the configuration for the store to be used, where the key is the name of the store, such as `in_memory` or `dynamodb`, and the value is any configuration available on that store type. | +| `store` | Object | An object containing a key-value pair that configures the store. The key is the store name, such as `in_memory` or `dynamodb`, and the value is an object containing the options for that store. For a list of all supported stores, see [Supported stores](#supported-stores). | ### Supported stores -As of Data Prepper 2.4, only `in_memory` and `dynamodb` stores are supported: -- The `in_memory` store is the -default when no `source_coordination` settings are configured in the `data-prepper-config.yaml` file and should only be used for single-node configurations. -- The `dynamodb` store is used for multi-node Data Prepper environments. The `dynamodb` store can be shared between one or more Data Prepper clusters that need to utilize source coordination. +Data Prepper supports the following source coordination stores. + +| Store | Environment | Description | +| :--- | :--- | :--- | +| `in_memory` | Single node | The default store when no `source_coordination` settings are configured in the `data-prepper-config.yaml` file. For more information, see [In-memory store](#in-memory-store). | +| `dynamodb` | Multi-node | Stores coordination data in Amazon DynamoDB. Multiple Data Prepper clusters that use source coordination can share the store. For more information, see [DynamoDB store](#dynamodb-store). | +| `jdbc` | Multi-node | Stores coordination data in PostgreSQL or MySQL. For more information, see [JDBC store](#jdbc-store). | + +#### In-memory store + +The `in_memory` store is the default store and does not have any options. Use it only for single-node Data Prepper deployments. + +The following example configures the `in_memory` store: + +```yaml +source_coordination: + store: + in_memory: +``` +{% include copy.html %} #### DynamoDB store -Data Prepper will attempt to create the `dynamodb` table on startup unless the `skip_table_creation` flag is configured to `true`. Optionally, you can configure the [time-to-live](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) (`ttl`) on the table, which results in the store cleaning up items over time. Some sources rely on source coordination for the deduplication of data, so be sure to configure a large enough `ttl` for the pipeline duration. +The `dynamodb` store uses an Amazon DynamoDB table to coordinate work across Data Prepper nodes. Multiple Data Prepper clusters can share the same table. To differentiate between the clusters, configure `partition_prefix`. -If `ttl` is not configured on the table, any items no longer needed in the table must be cleaned manually. - -The following shows the full set of permissions needed for Data Prepper to create the table, enable `ttl`, and interact with the table: +By default, Data Prepper creates the table and its index when the store starts. Set `skip_table_creation` to `true` when the table already exists. The following policy statement grants the permissions that Data Prepper requires to create the table, enable TTL, and read and write items: ```json { @@ -83,48 +97,83 @@ The following shows the full set of permissions needed for Data Prepper to creat "dynamodb:Query" ], "Resource": [ - "arn:aws:dynamodb:${REGION}:${AWS_ACCOUNT_ID}:table/${TABLE_NAME}", - "arn:aws:dynamodb:${REGION}:${AWS_ACCOUNT_ID}:table/${TABLE_NAME}/index/source-status" + "arn:aws:dynamodb:<region>:<account-id>:table/<table-name>", + "arn:aws:dynamodb:<region>:<account-id>:table/<table-name>/index/source-status" ] } ``` +{% include copy.html %} +You can configure `ttl` to enable DynamoDB [Time to Live (TTL)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html), which removes expired items from the table. Some sources use these items to prevent duplicate processing, so configure a `ttl` that exceeds the expected pipeline duration. If you don't configure `ttl`, you must manually delete items that are no longer needed. -| Value | Required | Type | Description | -| :--- | :--- | :--- | :--- | -| `table_name` | Yes | String | The name of the table to be used for source coordination. | -| `region` | Yes | String | The region of the DynamoDB table. | -| `sts_role_arn` | No | String | The `sts` role that contains the table permissions. Uses default credentials when not provided. | -| `sts_external_id` | No | String | The external ID used in the API call to assume the `sts_role_arn`. | -| `skip_table_creation` | No | Boolean | If set to `true` when using an existing store, the attempt to create the store is skipped. Default is `false`. | -| `provisioned_write_capacity_units` | No | Integer | The number of write capacity units to configure on the table. Default is `10`. | -| `provisioned_read_capacity_units` | No | Integer | The number of read capacity units to configure on the table. Default is `10`. | -| `ttl` | Duration | Optional. The duration of the TTL for the items in the table. The TTL is extended by this duration when an update is made to the item. Defaults to no TTL being used on the table. | - -The following example shows a `dynamodb` store: +When `skip_table_creation` is `true`, Data Prepper does not enable TTL on the table. If you configure `ttl` for an existing table, enable TTL on the table's `expirationTime` attribute before starting Data Prepper. + +The `dynamodb` store supports the following options. + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `table_name` | Yes | String | The name of the table used for source coordination. | +| `region` | Yes | String | The AWS Region of the DynamoDB table. | +| `sts_role_arn` | No | String | The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that has the table permissions. If not provided, Data Prepper uses the default credentials. | +| `sts_external_id` | No | String | The external ID used in the API call to assume the `sts_role_arn` role. | +| `skip_table_creation` | No | Boolean | When set to `true`, Data Prepper does not create the table. Default is `false`. | +| `provisioned_write_capacity_units` | No | Integer | The number of write capacity units to configure on the table. Default is `10`. | +| `provisioned_read_capacity_units` | No | Integer | The number of read capacity units to configure on the table. Default is `10`. | +| `ttl` | No | Duration | The duration used to set the expiration time for items in the table. Use ISO 8601 duration format, such as `P7D`. Data Prepper extends the expiration time when it updates an item. By default, items do not expire. | + +The following example configures a DynamoDB table as the source coordination store: ```yaml source_coordination: store: - dynamodb: - table_name: "DataPrepperSourceCoordinationStore" - region: "us-east-1" - sts_role_arn: "arn:aws:iam::##########:role/SourceCoordinationTableRole" - ttl: "P7D" - skip_table_creation: true + dynamodb: + table_name: "DataPrepperSourceCoordinationStore" + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/SourceCoordinationTableRole" + ttl: "P7D" + skip_table_creation: true ``` +{% include copy.html %} -#### In-memory store (default) +#### JDBC store -The following example shows an `in_memory` store, which is best used with a single-node cluster: +The `jdbc` store uses a relational database to coordinate work across Data Prepper nodes. Data Prepper includes Java Database Connectivity (JDBC) drivers for PostgreSQL and MySQL. +By default, Data Prepper creates the coordination table and its index when the store starts. The database user must have privileges to create the table and index and to select, insert, update, and delete rows. Set `skip_table_creation` to `true` when the required table and index already exist. + +Data Prepper validates the store settings when a source that uses source coordination starts, not when Data Prepper starts. If a setting is invalid, Data Prepper logs an error and does not run that pipeline. + +You can configure `ttl` to periodically remove expired partition records. Some sources use these records to prevent duplicate processing, so configure a `ttl` that exceeds the expected pipeline duration. + +The `jdbc` store supports the following options. + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `url` | Yes | String | The JDBC connection URL. | +| `username` | Yes | String | The database username. | +| `password` | Yes | String | The database password. | +| `table_name` | No | String | The name of the table used for source coordination. You can specify an unqualified name or a schema-qualified name, such as `schema.table`. Default is `source_coordination`. | +| `skip_table_creation` | No | Boolean | When set to `true`, Data Prepper does not create the coordination table or its index. Default is `false`. | +| `max_pool_size` | No | Integer | The maximum number of connections in the JDBC connection pool. Must be at least `2`, because the store holds one connection while it opens another to update a partition. Default is `5`. | +| `ttl` | No | Duration | The duration used to set the expiration time for partition records. Use ISO 8601 duration format, such as `P7D`. Data Prepper extends the expiration time when it updates a record. By default, records do not expire. | +| `connection_properties` | No | Map | JDBC driver properties to pass to each database connection. | + +The following example configures a PostgreSQL database that requires TLS connections as the source coordination store. If your database does not support TLS, remove the `ssl` connection property: ```yaml source_coordination: store: - in_memory: + jdbc: + url: "jdbc:postgresql://db:5432/dataprepper" + username: "dp_user" + password: {% raw %}"${{aws_secrets:db-secrets:password}}"{% endraw %} + table_name: "source_coordination" + max_pool_size: 5 + ttl: "P7D" + connection_properties: + ssl: "true" ``` - +{% include copy.html %} ## Metrics diff --git a/_data-prepper/migrate-open-distro.md b/_data-prepper/migrate-open-distro.md index e7fdacbd..972bf51d 100644 --- a/_data-prepper/migrate-open-distro.md +++ b/_data-prepper/migrate-open-distro.md @@ -2,6 +2,8 @@ layout: default title: Migrating from Open Distro nav_order: 30 +redirect_from: + - /clients/data-prepper/migrate-open-distro/ --- # Migrating from Open Distro @@ -12,7 +14,7 @@ Existing users can migrate from the Open Distro Data Prepper to OpenSearch Data The `elasticsearch` sink has changed to `opensearch`. Therefore, change your existing pipeline to use the `opensearch` plugin instead of `elasticsearch`. -While the Data Prepper plugin is titled `opensearch`, it remains compatible with Open Distro and ElasticSearch 7.x. +While the Data Prepper plugin is titled `opensearch`, it remains compatible with Open Distro and Elasticsearch 7.x. {: .note} ## Update Docker image @@ -21,4 +23,4 @@ In your Data Prepper Docker configuration, adjust `amazon/opendistro-for-elastic ## Next steps -For more information about Data Prepper configurations, see [Getting Started with Data Prepper]({{site.url}}{{site.baseurl}}/clients/data-prepper/get-started/). +For more information about Data Prepper configurations, see [Getting Started with OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/clients/data-prepper/get-started/). diff --git a/_data-prepper/pipelines/cidrcontains.md b/_data-prepper/pipelines/cidrcontains.md new file mode 100644 index 00000000..f4016ca4 --- /dev/null +++ b/_data-prepper/pipelines/cidrcontains.md @@ -0,0 +1,105 @@ +--- +layout: default +title: cidrContains() +parent: Functions +grand_parent: Pipelines +nav_order: 5 +--- + +<!-- vale off --> +# cidrContains() function +<!-- vale on --> + +The `cidrContains()` function is used to check if an IP address is contained within a specified Classless Inter-Domain Routing (CIDR) block or range of CIDR blocks. It accepts two or more arguments: + +- The first argument is a JSON pointer, which represents the key or path to the field containing the IP address to be checked. It supports both IPv4 and IPv6 address formats. + +- The subsequent arguments are strings representing one or more CIDR blocks or IP address ranges. The function checks if the IP address specified in the first argument matches or is contained within any of these CIDR blocks. + +For example, if your data contains an IP address field named `client.ip` and you want to check if it belongs to the CIDR blocks `192.168.0.0/16` or `10.0.0.0/8`, you can use the `cidrContains()` function as follows: + +``` +cidrContains('/client.ip', '192.168.0.0/16', '10.0.0.0/8') +``` +{% include copy.html %} + +This function returns `true` if the IP address matches any of the specified CIDR blocks or `false` if it does not. + +## Example + +The following pipeline discards any documents that are not part of the specified CIDR blocks: + +```yaml +cidr-allowlist-pipeline: + source: + http: + path: /events + ssl: true + sslKeyCertChainFile: certs/dp.crt + sslKeyFile: certs/dp.key + processor: + - drop_events: + # Drop events whose client IP is NOT in specific CIDR allowlist + drop_when: 'not cidrContains(/client/ip, "10.0.0.0/8", "192.168.0.0/16", "fd00::/8")' + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: logs-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -ksS -X POST "https://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"client":{"ip":"10.23.45.6"},"msg":"allowed 10/8"}, + {"client":{"ip":"8.8.8.8"},"msg":"should be dropped"}, + {"client":{"ip":"fd00::1234"},"msg":"allowed ULA IPv6"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs-2025.10.14", + "_id": "Ng1i4pkBLPEKXekW48BU", + "_score": 1, + "_source": { + "client": { + "ip": "10.23.45.6" + }, + "msg": "allowed 10/8" + } + }, + { + "_index": "logs-2025.10.14", + "_id": "Nw1i4pkBLPEKXekW48BU", + "_score": 1, + "_source": { + "client": { + "ip": "fd00::1234" + }, + "msg": "allowed ULA IPv6" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/configuration/buffers/bounded-blocking.md b/_data-prepper/pipelines/configuration/buffers/bounded-blocking.md index 8370cf22..2f2b51e5 100644 --- a/_data-prepper/pipelines/configuration/buffers/bounded-blocking.md +++ b/_data-prepper/pipelines/configuration/buffers/bounded-blocking.md @@ -6,16 +6,14 @@ grand_parent: Pipelines nav_order: 50 --- -# Bounded blocking +# Bounded blocking buffer -## Overview - -`Bounded blocking` is the default buffer and is memory based. The following table describes the `Bounded blocking` parameters. +The `bounded_blocking` buffer is the default buffer and is memory based. The following table describes the `bounded_blocking` buffer parameters. | Option | Required | Type | Description | | --- | --- | --- | --- | -| buffer_size | No | Integer | The maximum number of records the buffer accepts. Default value is `12800`. | -| batch_size | No | Integer | The maximum number of records the buffer drains after each read. Default value is `200`. | +| `buffer_size` | No | Integer | The maximum number of records the buffer accepts. Default value is `12800`. | +| `batch_size` | No | Integer | The maximum number of records the buffer drains after each read. Default value is `200`. | <!--- ## Configuration diff --git a/_data-prepper/pipelines/configuration/buffers/buffers.md b/_data-prepper/pipelines/configuration/buffers/buffers.md index eeb68260..0f70b5df 100644 --- a/_data-prepper/pipelines/configuration/buffers/buffers.md +++ b/_data-prepper/pipelines/configuration/buffers/buffers.md @@ -3,9 +3,13 @@ layout: default title: Buffers parent: Pipelines has_children: true -nav_order: 20 +nav_order: 30 --- -# Buffers +# Data Prepper buffers + +The `buffer` component acts as an intermediary layer between the `source` and `sink` components in an OpenSearch Data Prepper pipeline. It serves as temporary storage for events, decoupling the `source` from the downstream processors and sinks. Buffers can be either in-memory or disk based. + +If not explicitly specified in the pipeline configuration, Data Prepper uses the default `bounded_blocking` buffer, which is an in-memory queue bounded by the number of events it can store. The `bounded_blocking` buffer is a convenient option when the event volume and processing rates are manageable within the available memory constraints. + -Buffers store data as it passes through the pipeline. If you implement a custom buffer, it can be memory based, which provides better performance, or disk based, which is larger in size. \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/buffers/kafka.md b/_data-prepper/pipelines/configuration/buffers/kafka.md index 675a0c97..a027d424 100644 --- a/_data-prepper/pipelines/configuration/buffers/kafka.md +++ b/_data-prepper/pipelines/configuration/buffers/kafka.md @@ -6,14 +6,14 @@ grand_parent: Pipelines nav_order: 80 --- -# kafka +# Kafka buffer The `kafka` buffer buffers data into an Apache Kafka topic. It uses the Kafka topic to persist data while the data is in transit. The following example shows how to run the Kafka buffer in an HTTP pipeline. It runs against a locally running Kafka cluster. -``` +```yaml kafka-buffer-pipeline: source: http: @@ -41,14 +41,22 @@ Use the following configuration options with the `kafka` buffer. Option | Required | Type | Description --- | --- | --- | --- -`bootstrap_servers` | Yes | String list | The host and port for the initial connection to the Kafka cluster. You can configure multiple Kafka brokers by using the IP address or the port number for each broker. When using [Amazon Managed Streaming for Apache Kafka (Amazon MSK)](https://aws.amazon.com/msk/) as your Kafka cluster, the bootstrap server information is obtained from Amazon MSK using the Amazon Resource Name (ARN) provided in the configuration. -`topics` | Yes | List | A list of [topics](#topic) to use. You must supply one topic per buffer. +`acknowledgements_timeout` | No | Duration | The maximum amount of time to wait for end-to-end acknowledgments of the records read from the Kafka topic. If the records are not acknowledged within this time, the buffer resets the partitions and reads the records again. By default, acknowledgments effectively never time out. `authentication` | No | [Authentication](#authentication) | Sets the authentication options for both the pipeline and Kafka. For more information, see [Authentication](#authentication). +`aws` | No | [AWS](#aws) | The AWS configuration. For more information, see [`aws`](#aws). +`bootstrap_servers` | Yes | String list | The host and port for the initial connection to the Kafka cluster. You can configure multiple Kafka brokers by using the IP address or the port number for each broker. When using [Amazon Managed Streaming for Apache Kafka (Amazon MSK)](https://aws.amazon.com/msk/) as your Kafka cluster, the bootstrap server information is obtained from Amazon MSK using the Amazon Resource Name (ARN) provided in the configuration. +`bounded_batch_size` | No | Integer | The maximum number of records drained from the in-memory buffer after each read. The Kafka buffer consumes records from the topic into this in-memory buffer, from which processors read them. Default is `250000`. +`bounded_buffer_size` | No | Integer | The maximum number of records that the in-memory buffer accepts after consuming them from the Kafka topic. Default is `1000000`. +`custom_metric_prefix` | No | String | A custom prefix for the buffer metrics. The prefix replaces the plugin name in the metric names. For example, setting this option to `mybuffer` produces metrics such as `mybufferRead_recordsConsumedRate`. If not specified, the plugin name `kafka` is used. +`drain_timeout` | No | Duration | The maximum amount of time to wait for the buffer to drain when the pipeline shuts down. Default is `30s`. `encryption` | No | [Encryption](#encryption) | The encryption configuration for encryption in transit. For more information, see [Encryption](#encryption). -`aws` | No | [AWS](#aws) | The AWS configuration. For more information, see [aws](#aws). +`producer_properties` | No | [Producer Properties](#producer_properties) | A list of configurable Kafka producer properties. +`topics` | Yes | List | A list of [topics](#topic) for the buffer to use. You must supply one topic per buffer. +<!-- vale off --> ### topic +<!-- vale on --> The `topic` option configures a single Kafka topic and tells the `kafka` buffer how to use that topic. @@ -57,25 +65,36 @@ Option | Required | Type | Description :--- | :--- | :--- | :--- `name` | Yes | String | The name of the Kafka topic. `group_id` | Yes | String | Sets Kafka's `group.id` option. +`client_id` | No | String | Sets Kafka's `client.id` option for the buffer's consumers. Must be between 1 and 255 characters long. +`create_topic` | No | Boolean | When `true`, the buffer creates the topic when the pipeline starts. Default is `false`. +`number_of_partitions` | No | Integer | The number of partitions to use when creating the topic. Applies only when `create_topic` is `true`. Default is `1`. +`replication_factor` | No | Integer | The replication factor to use when creating the topic. Applies only when `create_topic` is `true`. Default is `1`. `workers` | No | Integer | The number of multithreaded consumers associated with each topic. Default is `2`. The maximum value is `200`. -`encryption_key` | No | String | An Advanced Encryption Standard (AES) encryption key used to encrypt and decrypt data within Data Prepper before sending it to Kafka. This value must be plain text or encrypted using AWS Key Management Service (AWS KMS). +`encryption_key` | No | String | An Advanced Encryption Standard (AES) encryption key used to encrypt and decrypt data within OpenSearch Data Prepper before sending it to Kafka. This value must be plain text or encrypted using AWS Key Management Service (AWS KMS). `kms` | No | AWS KMS key | When configured, uses an AWS KMS key to encrypt data. See [`kms`](#kms) for more information. +`encryption_id` | No | String | The ID of an encryption engine defined in the `encryption` extension of the `data-prepper-config.yaml` file. The buffer uses this encryption engine to encrypt and decrypt data before sending it to Kafka. Use either `encryption_id` or `encryption_key`, not both. `auto_commit` | No | Boolean | When `false`, the consumer offset will not be periodically committed to Kafka in the background. Default is `false`. -`commit_interval` | No | Integer | When `auto_commit` is set to `true`, sets how often, in seconds, the consumer offsets are auto-committed to Kafka through Kafka's `auto.commit.interval.ms` option. Default is `5s`. -`session_timeout` | No | Integer | The amount of time during which the source detects client failures when using Kafka's group management features, which can be used to balance the data stream. Default is `45s`. -`auto_offset_reset` | No | String | Automatically resets the offset to the earliest or the latest offset through Kafka's `auto.offset.reset` option. Default is `latest`. -`thread_waiting_time` | No | Integer | The amount of time that a thread waits for the preceding thread to complete its task and to signal the next thread. The Kafka consumer API poll timeout value is set to half of this setting. Default is `5s`. -`max_partition_fetch_bytes` | No | Integer | Sets the maximum limit, in megabytes, for data returns from each partition through Kafka's `max.partition.fetch.bytes` setting. Default is `1mb`. -`heart_beat_interval` | No | Integer | The expected amount of time between heartbeats to the consumer coordinator when using Kafka's group management facilities through Kafka's `heartbeat.interval.ms` setting. Default is `5s`. -`fetch_max_wait` | No | Integer | The maximum amount of time during which the server blocks a fetch request when there isn't sufficient data to satisfy the `fetch_min_bytes` requirement through Kafka's `fetch.max.wait.ms` setting. Default is `500ms`. -`fetch_max_bytes` | No | Integer | The maximum record size accepted by the broker through Kafka's `fetch.max.bytes` setting. Default is `50mb`. -`fetch_min_bytes` | No | Integer | The minimum amount of data the server returns during a fetch request through Kafka's `retry.backoff.ms` setting. Default is `1b`. -`retry_backoff` | No | Integer | The amount of time to wait before attempting to retry a failed request to a given topic partition. Default is `10s`. -`max_poll_interval` | No | Integer | The maximum delay between invocations of a `poll()` when using group management through Kafka's `max.poll.interval.ms` option. Default is `300s`. +`commit_interval` | No | Duration | When `auto_commit` is set to `true`, sets how often the consumer offsets are auto-committed to Kafka through Kafka's `auto.commit.interval.ms` option. Default is `5s`. +`session_timeout` | No | Duration | The amount of time during which the source detects client failures when using Kafka's group management features, which can be used to balance the data stream. Default is `45s`. +`auto_offset_reset` | No | String | Automatically resets the offset to the earliest or the latest offset through Kafka's `auto.offset.reset` option. Default is `earliest`. +`thread_waiting_time` | No | Duration | The amount of time that a thread waits for the preceding thread to complete its task and to signal the next thread. The Kafka consumer API poll timeout value is set to half of this setting. Default is `5s`. +`max_partition_fetch_bytes` | No | String | Sets the maximum amount of data returned from each partition through Kafka's `max.partition.fetch.bytes` setting. Default is `1mb`. +`heart_beat_interval` | No | Duration | The expected amount of time between heartbeats to the consumer coordinator when using Kafka's group management facilities through Kafka's `heartbeat.interval.ms` setting. Default is `5s`. +`fetch_max_wait` | No | Duration | The maximum amount of time during which the server blocks a fetch request when there isn't sufficient data to satisfy the `fetch_min_bytes` requirement through Kafka's `fetch.max.wait.ms` setting. Default is `1000ms`. +`fetch_max_bytes` | No | String | The maximum amount of data the server returns for a fetch request through Kafka's `fetch.max.bytes` setting. The maximum value is `50mb`. Default is `50mb`. +`fetch_min_bytes` | No | String | The minimum amount of data the server returns during a fetch request through Kafka's `fetch.min.bytes` setting. Default is `2kb`. +`retry_backoff` | No | Duration | The amount of time to wait before attempting to retry a failed request to a given topic partition. Default is `10s`. +`reconnect_backoff` | No | Duration | The amount of time to wait before attempting to reconnect to a broker through Kafka's `reconnect.backoff.ms` setting. Default is `10s`. +`connections_max_idle` | No | Duration | The amount of time after which the buffer's consumers close idle connections, through Kafka's `connections.max.idle.ms` setting. To set this value for the producer, use `connections_max_idle` in [`producer_properties`](#producer_properties). Default is `540s`. +`metadata_max_age` | No | Duration | The amount of time after which the buffer's consumers refresh metadata, through Kafka's `metadata.max.age.ms` setting. To set this value for the producer, use `metadata_max_age` in [`producer_properties`](#producer_properties). Default is `300s`. +`max_poll_interval` | No | Duration | The maximum delay between invocations of a `poll()` when using group management through Kafka's `max.poll.interval.ms` option. Default is `300s`. `consumer_max_poll_records` | No | Integer | The maximum number of records returned in a single `poll()` call through Kafka's `max.poll.records` setting. Default is `500`. +`max_message_bytes` | No | Integer | The maximum size of the message, in bytes. Default is 1 MB. +<!-- vale off --> ### kms +<!-- vale on --> When using AWS KMS, the AWS KMS key can decrypt the `encryption_key` so that it is not stored in plain text. To configure AWS KMS with the `kafka` buffer, use the following options. @@ -103,7 +122,9 @@ Use one of the following options when configuring SASL authentication. Option | Type | Description :--- | :--- | :--- `plaintext` | JSON object | The [PLAINTEXT](#sasl-plaintext) authentication configuration. +`scram` | JSON object | The [SCRAM](#sasl-scram) authentication configuration. `aws_msk_iam` | String | The Amazon MSK AWS Identity and Access Management (IAM) configuration. If set to `role`, the `sts_role_arn` set in the `aws` configuration is used. Default is `default`. +`azure_federated` | JSON object | The configuration for authenticating to the Kafka endpoint of Azure Event Hubs using AWS credentials federated to Microsoft Entra ID. For more information, see [SASL Azure federated](#sasl-azure-federated). #### SASL PLAINTEXT @@ -114,6 +135,53 @@ Option | Type | Description `username` | String | The username for the PLAINTEXT authentication. `password` | String | The password for the PLAINTEXT authentication. +#### SASL SCRAM + +The following options are required when using the Salted Challenge Response Authentication Mechanism (SCRAM). + +Option | Type | Description +:--- | :--- | :--- +`username` | String | The username for the SCRAM authentication. +`password` | String | The password for the SCRAM authentication. +`mechanism` | String | The SCRAM mechanism to use, for example, `SCRAM-SHA-256` or `SCRAM-SHA-512`. The value is passed to Kafka's `sasl.mechanism` setting. + +#### SASL Azure federated + +The `azure_federated` option connects the buffer to the Kafka endpoint of an Azure Event Hubs namespace without storing an Azure client secret in the pipeline. The buffer requests a web identity token from AWS STS using the credentials from the [`aws`](#aws) configuration, exchanges this token for an access token at the Microsoft Entra ID token endpoint, and uses the access token for SASL/OAUTHBEARER authentication. The buffer caches the access token and requests a new one before it expires. + +To use this option, enable outbound identity federation in your AWS account, allow the AWS credentials to call `sts:GetWebIdentityToken`, and add a federated identity credential that trusts the AWS token to the Microsoft Entra application. Set the AWS Region in `aws.region`. If `aws.sts_role_arn` is set, the buffer assumes that role before requesting the token. The connection always uses the `SASL_SSL` security protocol. + +The following options are required when using `azure_federated`. + +Option | Type | Description +:--- | :--- | :--- +`client_id` | String | The application (client) ID of the Microsoft Entra application. +`token_endpoint` | String | The Microsoft Entra ID OAuth 2.0 token endpoint, for example, `https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token`. +`scope` | String | The scope of the requested access token. For Azure Event Hubs, use `https://<namespace>.servicebus.windows.net/.default`. + +The following example configures `azure_federated` authentication: + +```yaml +buffer: + kafka: + bootstrap_servers: ["my-namespace.servicebus.windows.net:9093"] + topics: + - name: my-buffer-event-hub + group_id: data-prepper + encryption: + type: ssl + authentication: + sasl: + azure_federated: + client_id: <application-client-id> + token_endpoint: https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token + scope: https://my-namespace.servicebus.windows.net/.default + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/event-hubs-federation +``` +{% include copy.html %} + #### Encryption Use the following options when setting SSL encryption. @@ -121,10 +189,57 @@ Use the following options when setting SSL encryption. Option | Required | Type | Description :--- | :--- | :--- | :--- `type` | No | String | The encryption type. Use `none` to disable encryption. Default is `ssl`. +`certificate` | No | String | The SSL certificate content. Use either this option or `trust_store_file_path`, not both. +`trust_store_file_path` | No | String | The path to the truststore file containing the SSL certificate. Use either this option or `certificate`, not both. +`trust_store_password` | No | String | The password for the truststore file. `insecure` | No | Boolean | A Boolean flag used to turn off SSL certificate verification. If set to `true`, certificate authority (CA) certificate verification is turned off and insecure HTTP requests are sent. Default is `false`. +<!-- vale off --> +#### producer_properties +<!-- vale on --> +Use the following configuration options to configure a Kafka producer. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`acks` | No | String | The number of acknowledgments the producer requires from the brokers before considering a request complete, through Kafka's `acks` setting. Valid values are `all`, `-1`, `0`, and `1`. If not specified, the Kafka client default is used. +`batch_size` | No | Integer | The maximum size, in bytes, of a batch of records sent to the same partition, through Kafka's `batch.size` setting. If not specified, the Kafka client default is used. +`buffer_memory` | No | String | The total amount of memory that the producer can use to buffer records waiting to be sent to Kafka, through Kafka's `buffer.memory` setting. Default is `50mb`. +`client_dns_lookup` | No | String | Sets Kafka's `client.dns.lookup` option for the producer. Valid values are `use_all_dns_ips` and `resolve_canonical_bootstrap_servers_only`. If not specified, the Kafka client default is used. +`client_id` | No | String | Sets Kafka's `client.id` option for the producer. If not specified, the Kafka client default is used. +`compression_type` | No | String | The compression type for the data that the producer sends, through Kafka's `compression.type` setting, for example, `gzip`, `snappy`, or `zstd`. When the topic uses encryption at rest (`encryption_key`, `kms`, or `encryption_id`), the buffer compresses the data itself before encrypting it and turns off Kafka compression. If not specified, the Kafka client default is used. +`connections_max_idle` | No | Duration | The amount of time after which idle connections are closed, through Kafka's `connections.max.idle.ms` setting. Default is `540s`. +`delivery_timeout` | No | Duration | The maximum amount of time to report the success or failure of a send request, including retries, through Kafka's `delivery.timeout.ms` setting. Default is `120s`. +`enable_idempotence` | No | Boolean | When `true`, the producer writes exactly one copy of each record to the topic, through Kafka's `enable.idempotence` setting. If not specified, the Kafka client default is used. +`interceptor_classes` | No | List | A list of fully qualified class names of Kafka producer interceptors, through Kafka's `interceptor.classes` setting. If not specified, the Kafka client default is used. +`linger_ms` | No | Integer | The amount of time, in milliseconds, that the producer waits for additional records before sending a batch, through Kafka's `linger.ms` setting. If not specified, the Kafka client default is used. +`max_block` | No | Duration | The maximum amount of time that a send request can be blocked, for example, when the producer buffer is full or metadata is unavailable, through Kafka's `max.block.ms` setting. Default is `60s`. +`max_in_flight_requests_per_connection` | No | Integer | The maximum number of unacknowledged requests that the producer sends on a single connection, through Kafka's `max.in.flight.requests.per.connection` setting. If not specified, the Kafka client default is used. +`max_request_size` | No | Integer | The maximum size, in bytes, of the request that the producer sends to Kafka. When `create_topic` is `true` and this value is greater than the default, the topic's `max.message.bytes` setting is also set to this value. Default is `1048576` (1 MB). +`metadata_max_age` | No | Duration | The amount of time after which the producer refreshes metadata, through Kafka's `metadata.max.age.ms` setting. Default is `300s`. +`metadata_max_idle` | No | Duration | The amount of time after which the producer discards cached metadata for an idle topic, through Kafka's `metadata.max.idle.ms` setting. Default is `300s`. +`metric_reporters` | No | List | A list of fully qualified class names of Kafka metric reporters, through Kafka's `metric.reporters` setting. If not specified, the Kafka client default is used. +`metrics_num_samples` | No | Integer | The number of samples maintained to compute Kafka client metrics, through Kafka's `metrics.num.samples` setting. If not specified, the Kafka client default is used. +`metrics_recording_level` | No | String | The highest recording level for Kafka client metrics, through Kafka's `metrics.recording.level` setting. Valid values are `INFO`, `DEBUG`, and `TRACE`. If not specified, the Kafka client default is used. +`metrics_sample_window` | No | Duration | The time window over which Kafka client metric samples are computed, through Kafka's `metrics.sample.window.ms` setting. Default is `300s`. +`partitioner_adaptive_partitioning_enable` | No | Boolean | When `true`, the producer sends more records to partitions on faster brokers, through Kafka's `partitioner.adaptive.partitioning.enable` setting. Default is `false`. +`partitioner_availability_timeout` | No | Duration | If a broker cannot process produce requests for a partition for this amount of time, the partitioner treats the partition as unavailable, through Kafka's `partitioner.availability.timeout.ms` setting. If not specified, the Kafka client default is used. +`partitioner_class` | No | String | The fully qualified class name of the partitioner that determines the partition for each record, through Kafka's `partitioner.class` setting. If not specified, the Kafka client default is used. +`partitioner_ignore_keys` | No | Boolean | When `true`, the producer ignores record keys when choosing a partition, through Kafka's `partitioner.ignore.keys` setting. If not specified, the Kafka client default is used. +`receive_buffer` | No | String | The size of the TCP receive buffer, through Kafka's `receive.buffer.bytes` setting. Default is `50mb`. +`reconnect_backoff` | No | Duration | The amount of time to wait before attempting to reconnect to a broker, through Kafka's `reconnect.backoff.ms` setting. Default is `50ms`. +`reconnect_backoff_max` | No | Duration | The maximum amount of time to wait when repeatedly failing to reconnect to a broker, through Kafka's `reconnect.backoff.max.ms` setting. Default is `1s`. +`request_timeout` | No | Duration | The maximum amount of time that the producer waits for a response to a request, through Kafka's `request.timeout.ms` setting. Default is `30s`. +`retries` | No | Integer | The number of times the producer retries sending a record that failed with a retriable error, through Kafka's `retries` setting. Default is `5`. +`retry_backoff` | No | Duration | The amount of time to wait before retrying a failed request, through Kafka's `retry.backoff.ms` setting. Default is `100ms`. +`send_buffer` | No | String | The size of the TCP send buffer, through Kafka's `send.buffer.bytes` setting. Default is `50mb`. +`socket_connection_setup_timeout` | No | Duration | The amount of time that the producer waits for a socket connection to be established, through Kafka's `socket.connection.setup.timeout.ms` setting. Default is `10s`. +`socket_connection_setup_timeout_max` | No | Duration | The maximum amount of time that the producer waits for a socket connection to be established when repeatedly failing to connect, through Kafka's `socket.connection.setup.timeout.max.ms` setting. Default is `30s`. + + +<!-- vale off --> #### aws +<!-- vale on --> Use the following options when setting up authentication for `aws` services. @@ -133,12 +248,15 @@ Option | Required | Type | Description `region` | No | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). `sts_role_arn` | No | String | The AWS STS role to assume for requests to Amazon Simple Queue Service (Amazon SQS) and Amazon Simple Storage Service (Amazon S3). Default is `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). `msk` | No | JSON object | The [Amazon MSK](#msk) configuration settings. +`sts_header_overrides` | No | Map | A map of headers to add to the AWS STS `AssumeRole` request. You can specify up to 5 headers. +<!-- vale off --> #### msk +<!-- vale on --> Use the following options inside the `msk` object. Option | Required | Type | Description :--- | :--- | :--- | :--- `arn` | Yes | String | The [Amazon MSK ARN](https://docs.aws.amazon.com/msk/1.0/apireference/configurations-arn.html) to use. -`broker_connection_type` No | String | The type of connector to use with the Amazon MSK broker, either `public`, `single_vpc`, or `multi_vpc`. Default is `single_vpc`. +`broker_connection_type` | No | String | The type of connector to use with the Amazon MSK broker, either `public`, `single_vpc`, or `multi_vpc`. Default is `single_vpc`. diff --git a/_data-prepper/pipelines/configuration/processors/add-entries.md b/_data-prepper/pipelines/configuration/processors/add-entries.md index 23e4772f..65fc6646 100644 --- a/_data-prepper/pipelines/configuration/processors/add-entries.md +++ b/_data-prepper/pipelines/configuration/processors/add-entries.md @@ -1,64 +1,405 @@ --- layout: default -title: add_entries +title: Add entries parent: Processors grand_parent: Pipelines -nav_order: 40 +nav_order: 10 --- -# add_entries +# Add entries processor The `add_entries` processor adds entries to an event. -### Configuration +## Configuration You can configure the `add_entries` processor with the following options. | Option | Required | Description | | :--- | :--- | :--- | | `entries` | Yes | A list of entries to add to an event. | -| `key` | Yes | The key of the new entry to be added. Some examples of keys include `my_key`, `myKey`, and `object/sub_Key`. | -| `metadata_key` | Yes | The key for the new metadata attribute. The argument must be a literal string key and not a JSON Pointer. Either one string key or `metadata_key` is required. | +| `key` | No | The key of the new entry to be added. Some examples of keys include `my_key`, `myKey`, and `object/sub_Key`. The key can also be a format expression, for example, `${/key1}` to use the value of field `key1` as the key. | +| `metadata_key` | No | The key for the new metadata attribute. The argument must be a literal string key and not a JSON Pointer. Either one string key or `metadata_key` is required. | +| `value` | No | The value of the new entry to be added, which can be used with any of the following data types: strings, Booleans, numbers, null, nested objects, and arrays. | | `format` | No | A format string to use as the value of the new entry, for example, `${key1}-${key2}`, where `key1` and `key2` are existing keys in the event. Required if neither `value` nor `value_expression` is specified. | -| `value_expression` | No | An expression string to use as the value of the new entry. For example, `/key` is an existing key in the event with a type of either a number, a string, or a Boolean. Expressions can also contain functions returning number/string/integer. For example, `length(/key)` will return the length of the key in the event when the key is a string. For more information about keys, see [Expression syntax](https://opensearch.org/docs/latest/data-prepper/pipelines/expression-syntax/). | -| `add_when` | No | A [conditional expression](https://opensearch.org/docs/latest/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"'`, that will be evaluated to determine whether the processor will be run on the event. | -| `value` | Yes | The value of the new entry to be added. You can use the following data types: strings, Booleans, numbers, null, nested objects, and arrays. | +| `value_expression` | No | An expression string to use as the value of the new entry. For example, `/key` is an existing key in the event with a type of either a number, a string, or a Boolean. Expressions can also contain functions returning number/string/integer. For example, `length(/key)` will return the length of the key in the event when the key is a string. For more information about keys, see [Expression syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). For more information about functions, see [Functions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/functions/). | +| `add_when` | No | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"'`, that will be evaluated to determine whether the processor will be run on the event. | | `overwrite_if_key_exists` | No | When set to `true`, the existing value is overwritten if `key` already exists in the event. The default value is `false`. | +| `append_if_key_exists` | No | When set to `true`, the existing value will be appended if a `key` already exists in the event. An array will be created if the existing value is not an array. Default is `false`. | +| `iterate_on` | No | The key of a list of objects in the event. When specified, the processor adds the entry to each object in the list. Cannot be used with `metadata_key`. | +| `add_to_element_when` | No | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) that determines whether the entry is added to the objects in the `iterate_on` list. By default, the expression is evaluated once against the root event, and the entry is added to all objects in the list or to none of them. To evaluate the expression against each object in the list, set `evaluate_when_on_element` to `true`. Applies only when `iterate_on` is specified. | +| `evaluate_when_on_element` | No | When set to `true`, the `add_to_element_when` expression is evaluated against each object in the `iterate_on` list, and the entry is added only to the objects for which the expression evaluates to `true`. Applies only when both `iterate_on` and `add_to_element_when` are specified. Default is `false`. | +| `disable_root_keys` | No | When set to `false`, `value_expression` and `format` are resolved against the root event so that you can use root-level fields as values in each object in the `iterate_on` list. When set to `true`, they are resolved against each object in the list. Applies only when `iterate_on` is specified. Default is `true`. | +| `flatten_key` | No | When set to `true`, `key` is treated as a literal key name in each object in the `iterate_on` list, so a key such as `a/b` creates a field named `a/b`. When set to `false`, `key` is treated as a JSON pointer, so `a/b` creates a nested `b` field inside an `a` object. Applies only when `iterate_on` is specified. Default is `true`. | -### Usage -To get started, create the following `pipeline.yaml` file: +## Usage + +The following examples show how the `add_entries` processor can be used in different cases. + +### Example: Add entries with simple values + +The following example shows you how to configure the processor to add entries with simple values: ```yaml -pipeline: - source: - ... - .... +... processor: - add_entries: entries: - - key: "newMessage" - value: 3 - overwrite_if_key_exists: true - - metadata_key: myMetadataKey - value_expression: 'length("newMessage")' - add_when: '/some_key == "test"' - sink: + - key: "name" + value: "John" + - key: "age" + value: 20 +... ``` {% include copy.html %} - -For example, when your source contains the following event record: +When the input event contains the following data: ```json {"message": "hello"} ``` -And then you run the `add_entries` processor using the example pipeline, it adds a new entry, `{"newMessage": 3}`, to the existing event, `{"message": "hello"}`, so that the new event contains two entries in the final output: +The processed event will contain the following data: ```json -{"message": "hello", "newMessage": 3} +{"message": "hello", "name": "John", "age": 20} ``` -> If `newMessage` already exists, its existing value is overwritten with a value of `3`. +### Example: Add entries using format strings +The following example shows you how to configure the processor to add entries with values from other fields: + +```yaml +... + processor: + - add_entries: + entries: + - key: "date" + format: "${month}-${day}" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"month": "Dec", "day": 1} +``` + +The processed event will contain the following data: + +```json +{"month": "Dec", "day": 1, "date": "Dec-1"} +``` + +### Example: Add entries using value expressions + +The following example shows you how to configure the processor to use the `value_expression` option: + +```yaml +... + processor: + - add_entries: + entries: + - key: "length" + value_expression: "length(/message)" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"message": "hello"} +``` + +The processed event will contain the following data: + +```json +{"message": "hello", "length": 5} +``` + +### Example: Add metadata + +The following example shows you how to configure the processor to add metadata to events: + +```yaml +... + processor: + - add_entries: + entries: + - metadata_key: "length" + value_expression: "length(/message)" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"message": "hello"} +``` + +The processed event will have the same data, with the metadata, `{"length": 5}`, attached. You can subsequently use expressions like `getMetadata("length")` in the pipeline. For more information, see [`getMetadata` function]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-metadata/). + + +### Example: Add a dynamic key + +The following example shows you how to configure the processor to add metadata to events using a dynamic key: + +```yaml +... + processor: + - add_entries: + entries: + - key: "${/param_name}" + value_expression: "/param_value" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"param_name": "cpu", "param_value": 50} +``` + +The processed event will contain the following data: + +```json +{"param_name": "cpu", "param_value": 50, "cpu": 50} +``` + +### Example: Overwrite existing entries + +The following example shows you how to configure the processor to overwrite existing entries: + +```yaml +... + processor: + - add_entries: + entries: + - key: "message" + value: "bye" + overwrite_if_key_exists: true +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"message": "hello"} +``` + +The processed event will contain the following data: + +```json +{"message": "bye"} +``` + +If `overwrite_if_key_exists` is not set to `true`, then the input event will not be changed after processing. + +### Example: Append values to existing entries + +The following example shows you how to configure the processor to append values to existing entries: + +```yaml +... + processor: + - add_entries: + entries: + - key: "message" + value: "world" + append_if_key_exists: true +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"message": "hello"} +``` + +The processed event will contain the following data: + +```json +{"message": ["hello", "world"]} +``` + +### Example: Add entries to objects in a list + +The following example shows you how to configure the processor to add entries to each object in the `items` list. The first entry is added only to objects in which `type` is `a`, and the second entry copies the root-level `env` field into every object: + +```yaml +... + processor: + - add_entries: + entries: + - key: "tagged" + value: true + iterate_on: "items" + add_to_element_when: '/type == "a"' + evaluate_when_on_element: true + - key: "env" + value_expression: "/env" + iterate_on: "items" + disable_root_keys: false +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"env": "prod", "items": [{"type": "a"}, {"type": "b"}]} +``` + +The processed event will contain the following data: + +```json +{"env": "prod", "items": [{"type": "a", "tagged": true, "env": "prod"}, {"type": "b", "env": "prod"}]} +``` + +## Example + +The following pipeline performs these actions: + +1. Adds an `app_id` field using the format string `${app}-${env}`. +2. Adds a `message_len` field with the value of `length(/message)`. +3. Adds a metadata key `msg_len_meta` with the value of `length(/message)`. +4. If both `/metric/name` and `/metric/value` exist, creates a new field named after `/metric/name` and sets its value to `/metric/value`. +5. If `/level == "error"`, adds the field `severity: "high"`. +6. Appends `"ingested"` to the `tags` field, ensuring that the `tags` field is an array. +7. Sets `env_normalized: "prod"`, overwriting the existing value if the field already exists. + +```yaml +example-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - add_entries: + entries: + - key: app_id + format: ${app}-${env} + + - key: message_len + value_expression: length(/message) + + - metadata_key: msg_len_meta + value_expression: length(/message) + + # dynamic key from the event, only when both metric fields exist + - key: ${/metric/name} + value_expression: /metric/value + add_when: "/metric/name != null and /metric/value != null" + + # set severity ONLY on error level + - key: severity + value: high + add_when: '/level == "error"' + + # append behavior: if tags already exists, it becomes/extends an array + - key: tags + value: ingested + append_if_key_exists: true + + # overwrite behavior + - key: env_normalized + value: prod + overwrite_if_key_exists: true + + sink: + - opensearch: + hosts: [https://opensearch:9200] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: example-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline by executing the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"app":"shop","env":"dev","message":"hello","level":"info","metric":{"name":"cpu","value":42}}, + {"app":"shop","env":"prod","message":"boom","level":"error"}, + {"app":"api","env":"stage","message":"hi","level":"warn","metric":{"name":"mem","value":2048},"tags":"pretag"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +"hits": [ + { + "_index": "example-2025.10.10", + "_id": "BnvWzpkBTMZ443JmHuHI", + "_score": 1, + "_source": { + "app": "shop", + "env": "dev", + "message": "hello", + "level": "info", + "metric": { + "name": "cpu", + "value": 42 + }, + "app_id": "shop-dev", + "message_len": 5, + "cpu": 42, + "tags": "ingested", + "env_normalized": "prod" + } + }, + { + "_index": "example-2025.10.10", + "_id": "B3vWzpkBTMZ443JmHuHI", + "_score": 1, + "_source": { + "app": "shop", + "env": "prod", + "message": "boom", + "level": "error", + "app_id": "shop-prod", + "message_len": 4, + "severity": "high", + "tags": "ingested", + "env_normalized": "prod" + } + }, + { + "_index": "example-2025.10.10", + "_id": "CHvWzpkBTMZ443JmHuHI", + "_score": 1, + "_source": { + "app": "api", + "env": "stage", + "message": "hi", + "level": "warn", + "metric": { + "name": "mem", + "value": 2048 + }, + "tags": [ + "pretag", + "ingested" + ], + "app_id": "api-stage", + "message_len": 2, + "mem": 2048, + "env_normalized": "prod" + } + } +] + +``` diff --git a/_data-prepper/pipelines/configuration/processors/aggregate.md b/_data-prepper/pipelines/configuration/processors/aggregate.md index 699d2502..998c14bb 100644 --- a/_data-prepper/pipelines/configuration/processors/aggregate.md +++ b/_data-prepper/pipelines/configuration/processors/aggregate.md @@ -1,12 +1,12 @@ --- layout: default -title: aggregate +title: Aggregate parent: Processors grand_parent: Pipelines -nav_order: 41 +nav_order: 20 --- -# aggregate +# Aggregate processor The `aggregate` processor groups events based on the values of `identification_keys`. Then, the processor performs an action on each group, helping reduce unnecessary log volume and creating aggregated logs over time. You can use existing actions or create your own custom aggregations using Java code. @@ -17,27 +17,37 @@ The following table describes the options you can use to configure the `aggregat Option | Required | Type | Description :--- | :--- | :--- | :--- -identification_keys | Yes | List | An unordered list by which to group events. Events with the same values as these keys are put into the same group. If an event does not contain one of the `identification_keys`, then the value of that key is considered to be equal to `null`. At least one identification_key is required (for example, `["sourceIp", "destinationIp", "port"]`). -action | Yes | AggregateAction | The action to be performed on each group. One of the [available aggregate actions](#available-aggregate-actions) must be provided, or you can create custom aggregate actions. `remove_duplicates` and `put_all` are the available actions. For more information, see [Creating New Aggregate Actions](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#creating-new-aggregate-actions). -group_duration | No | String | The amount of time that a group should exist before it is concluded automatically. Supports ISO_8601 notation strings ("PT20.345S", "PT15M", etc.) as well as simple notation for seconds (`"60s"`) and milliseconds (`"1500ms"`). Default value is `180s`. +`identification_keys` | Yes | List | An unordered list by which to group events. Events with the same values as these keys are put into the same group. If an event does not contain one of the `identification_keys`, then the value of that key is considered to be equal to `null`. At least one identification_key is required (for example, `["sourceIp", "destinationIp", "port"]`). +`action` | Yes | AggregateAction | The action to be performed on each group. One of the [available aggregate actions](#available-aggregate-actions) must be provided, or you can create custom aggregate actions. `remove_duplicates` and `put_all` are the available actions. For more information, see [Creating New Aggregate Actions](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#creating-new-aggregate-actions). +`group_duration` | No | String | The amount of time that a group should exist before it is concluded automatically. Supports ISO_8601 notation strings (such as "PT20.345S" or "PT15M") as well as simple notation for seconds (`"60s"`) and milliseconds (`"1500ms"`). Default value is `180s`. +`local_mode` | No | Boolean | When `local_mode` is set to `true`, the aggregation is performed locally on each OpenSearch Data Prepper node instead of forwarding events to a specific node based on the `identification_keys` using a hash function. Default is `false`. +`output_unaggregated_events` | No | Boolean | When set to `true`, unaggregated events are forwarded to the next processor or sink in the pipeline. Default is `false`. +`aggregated_events_tag` | No | String | A tag to add to aggregated events in order to distinguish them from unaggregated events. Required when `output_unaggregated_events` is `true`. +`aggregate_when` | No | String | A conditional expression that determines whether the aggregate processor processes an event. When the condition evaluates to `false`, the event is forwarded without aggregation. +`acknowledge_on_conclude` | No | Boolean | When set to `true`, releases the group's event handle when the group is finalized (either by reaching the `group_duration` timeout or by a condition defined by the action). This sacrifices end-to-end acknowledgments but prevents reprocessing. Default is `false`. +`disable_group_acknowledgments` | No | Boolean | When set to `true`, disables group acknowledgments. Default is `false`. ## Available aggregate actions Use the following aggregate actions to determine how the `aggregate` processor processes events in each group. +<!-- vale off --> ### remove_duplicates +<!-- vale on --> -The `remove_duplicates` action processes the first event for a group immediately and drops any events that duplicate the first event from the source. For example, when using `identification_keys: ["sourceIp", "destination_ip"]`: +The `remove_duplicates` action processes the first event for a group immediately and drops any events that duplicate the first event from the source. For example, when using `identification_keys: ["sourceIp", "destinationIp"]`: 1. The `remove_duplicates` action processes `{ "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "status": 200 }`, the first event in the source. -2. Data Prepper drops the `{ "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 1000 }` event because the `sourceIp` and `destinationIp` match the first event in the source. +2. OpenSearch Data Prepper drops the `{ "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 1000 }` event because the `sourceIp` and `destinationIp` match the first event in the source. 3. The `remove_duplicates` action processes the next event, `{ "sourceIp": "127.0.0.2", "destinationIp": "192.168.0.1", "bytes": 1000 }`. Because the `sourceIp` is different from the first event of the group, Data Prepper creates a new group based on the event. +<!-- vale off --> ### put_all +<!-- vale on --> -The `put_all` action combines events belonging to the same group by overwriting existing keys and adding new keys, similarly to the Java `Map.putAll`. The action drops all events that make up the combined event. For example, when using `identification_keys: ["sourceIp", "destination_ip"]`, the `put_all` action processes the following three events: +The `put_all` action combines events belonging to the same group by overwriting existing keys and adding new keys, similarly to the Java `Map.putAll`. The action drops all events that make up the combined event. For example, when using `identification_keys: ["sourceIp", "destinationIp"]`, the `put_all` action processes the following three events: -``` +```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "status": 200 } { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 1000 } { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "http_verb": "GET" } @@ -45,22 +55,28 @@ The `put_all` action combines events belonging to the same group by overwriting Then the action combines the events into one. The pipeline then uses the following combined event: -``` +```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "status": 200, "bytes": 1000, "http_verb": "GET" } ``` +<!-- vale off --> ### count +<!-- vale on --> -The `count` event counts events that belong to the same group and generates a new event with values of the `identification_keys` and the count, which indicates the number of new events. You can customize the processor with the following configuration options: +The `count` action counts events that belong to the same group and generates a new event with values of the `identification_keys` and the count, which indicates the number of events in the group. The action drops all events that make up the combined event. +You can customize the processor with the following configuration options: - * `count_key`: Key used for storing the count. Default name is `aggr._count`. -* `start_time_key`: Key used for storing the start time. Default name is `aggr._start_time`. -* `output_format`: Format of the aggregated event. - * `otel_metrics`: Default output format. Outputs in OTel metrics SUM type with count as value. - * `raw` - Generates a JSON object with the `count_key` field as a count value and the `start_time_key` field with aggregation start time as value. +* `count_key`: The key used for storing the count. Default name is `aggr._count`. +* `start_time_key`: The key used for storing the start time. Default name is `aggr._start_time`. +* `end_time_key`: The key used for storing the end time. Default name is `aggr._end_time`. +* `metric_name`: The name of the metric when using the `otel_metrics` output format. Default is `count`. +* `unique_keys`: A list of keys for which to count unique values. When specified, the count reflects the number of unique combinations of these keys rather than the total number of events. +* `output_format`: The aggregated event format. Valid values are: + * `otel_metrics` (default): Outputs an OpenTelemetry metric of type `SUM` in which the `value` field contains the number of events in the group. + * `raw`: Generates a JSON object with the `count_key` field as the count and the `start_time_key` field as the aggregation start time. -For an example, when using `identification_keys: ["sourceIp", "destination_ip"]`, the `count` action counts and processes the following events: +For an example, when using `identification_keys: ["sourceIp", "destinationIp"]`, the `count` action counts and processes the following events: ```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "status": 200 } @@ -74,25 +90,27 @@ The processor creates the following event: {"isMonotonic":true,"unit":"1","aggregationTemporality":"AGGREGATION_TEMPORALITY_DELTA","kind":"SUM","name":"count","description":"Number of events","startTime":"2022-12-02T19:29:51.245358486Z","time":"2022-12-02T19:30:15.247799684Z","value":3.0,"sourceIp":"127.0.0.1","destinationIp":"192.168.0.1"} ``` +<!-- vale off --> ### histogram +<!-- vale on --> The `histogram` action aggregates events belonging to the same group and generates a new event with values of the `identification_keys` and histogram of the aggregated events based on a configured `key`. The histogram contains the number of events, sum, buckets, bucket counts, and optionally min and max of the values corresponding to the `key`. The action drops all events that make up the combined event. You can customize the processor with the following configuration options: -* `key`: Name of the field in the events the histogram generates. +* `key`: The name of the field from which the histogram is generated. * `generated_key_prefix`: `key_prefix` used by all the fields created in the aggregated event. Having a prefix ensures that the names of the histogram event do not conflict with the field names in the event. * `units`: The units for the values in the `key`. * `record_minmax`: A Boolean value indicating whether the histogram should include the min and max of the values in the aggregation. * `buckets`: A list of buckets (values of type `double`) indicating the buckets in the histogram. -* `output_format`: Format of the aggregated event. - * `otel_metrics`: Default output format. Outputs in OTel metrics SUM type with count as value. - * `raw`: Generates a JSON object with `count_key` field with count as value and `start_time_key` field with aggregation start time as value. +* `metric_name`: The name of the metric when using the `otel_metrics` output format. Default is `histogram`. +* `output_format`: The aggregated event format. Valid values are: + * `otel_metrics` (default): Outputs an OpenTelemetry metric of type `HISTOGRAM` containing the bucket boundaries and the number of values in each bucket. + * `raw`: Generates a JSON object containing the sum, count, buckets, bucket counts, aggregation start time, duration, and, when `record_minmax` is enabled, the min and max. Each field name uses `generated_key_prefix`, so the sum is `aggr._sum` by default. +For example, when using `identification_keys: ["sourceIp", "destinationIp", "request"]`, `key: latency`, and `buckets: [0.0, 0.25, 0.5]`, the `histogram` action processes the following events: -For example, when using `identification_keys: ["sourceIp", "destination_ip", "request"]`, `key: latency`, and `buckets: [0.0, 0.25, 0.5]`, the `histogram` action processes the following events: - -``` +```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "request" : "/index.html", "latency": 0.2 } { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "request" : "/index.html", "latency": 0.55} { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "request" : "/index.html", "latency": 0.25 } @@ -105,9 +123,40 @@ Then the processor creates the following event: {"max":0.55,"kind":"HISTOGRAM","buckets":[{"min":-3.4028234663852886E38,"max":0.0,"count":0},{"min":0.0,"max":0.25,"count":2},{"min":0.25,"max":0.50,"count":1},{"min":0.50,"max":3.4028234663852886E38,"count":1}],"count":4,"bucketCountsList":[0,2,1,1],"description":"Histogram of latency in the events","sum":1.15,"unit":"seconds","aggregationTemporality":"AGGREGATION_TEMPORALITY_DELTA","min":0.15,"bucketCounts":4,"name":"histogram","startTime":"2022-12-14T06:43:40.848762215Z","explicitBoundsCount":3,"time":"2022-12-14T06:44:04.852564623Z","explicitBounds":[0.0,0.25,0.5],"request":"/index.html","sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "key": "latency"} ``` -### rate_limiter +<!-- vale off --> +### sum +<!-- vale on --> -The `rate_limiter` action controls the number of events aggregated per second. By default, `rate_limiter` blocks the `aggregate` processor from running if it receives more events than the configured number allowed. You can overwrite the number events that triggers the `rate_limited` by using the `when_exceeds` configuration option. +The `sum` action sums the numeric values of a configured `key` for all events that belong to the same group and generates a new event with the values of the `identification_keys` and the total. The action drops all events that make up the combined event. + +You can customize the processor with the following configuration options: + +* `key`: The name of the field in the events to sum. The value of this field must be numeric. Required. +* `metric_name`: The name of the metric when using the `otel_metrics` output format. Default is `sum`. +* `count_key`: The key used for storing the number of events that contributed to the sum when using the `raw` output format. Default name is `aggr._count`. +* `output_format`: The aggregated event format. Valid values are: + * `otel_metrics` (default): Outputs an OpenTelemetry metric of type `SUM` in which the `value` field contains the total. The metric is non-monotonic because the summed values are not guaranteed to be non-negative. + * `raw`: Generates a JSON object with the `aggr._sum` field as the total, the `count_key` field as the number of events that contributed to the total, and the `aggr._start_time` field as the aggregation start time. + +For example, when using `identification_keys: ["sourceIp", "destinationIp"]` and `key: bytes_out`, the `sum` action processes the following events: + +```json +{ "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes_out": 1234 } +{ "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes_out": 4321 } +{ "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes_out": 100 } +``` + +The processor creates the following event: + +```json +{"isMonotonic":false,"unit":"1","aggregationTemporality":"AGGREGATION_TEMPORALITY_DELTA","kind":"SUM","name":"sum","description":"Sum of the events","startTime":"2022-12-02T19:29:51.245358486Z","time":"2022-12-02T19:30:15.247799684Z","value":5655.0,"sourceIp":"127.0.0.1","destinationIp":"192.168.0.1"} +``` + +<!-- vale off --> +### rate_limiter +<!-- vale on --> + +The `rate_limiter` action controls the number of events aggregated per second. By default, `rate_limiter` blocks the `aggregate` processor from running if it receives more events than the configured number allowed. You can overwrite the number of events that triggers the `rate_limiter` by using the `when_exceeds` configuration option. You can customize the processor with the following configuration options: @@ -122,15 +171,55 @@ For example, if `events_per_second` is set to `1` and `when_exceeds` is set to ` { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "http_verb": "GET" } ``` -The following event is processed, but all other events are ignored because the `rate_limiter` blocks them: +The first event is processed, but the remaining events are dropped because `when_exceeds` is set to `drop`: ```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "status": 200 } ``` -If `when_exceeds` is set to `drop`, all three events are processed. +If `when_exceeds` is set to `block`, the processor pauses until the next second before processing the remaining events. +<!-- vale off --> +### append +<!-- vale on --> + +The `append` action combines multiple events into a single event by appending values from the specified keys across all events in the group. Unlike `put_all`, which overwrites values, `append` collects all values for the specified keys into lists. + +You can customize the processor with the following configuration option: + +* `keys_to_append`: A list of keys whose values should be appended across the events in the group. The aggregated event contains lists of all values encountered for each key. + +For example, when using `identification_keys: ["sourceIp"]` and `keys_to_append: ["status"]`, the `append` action processes the following events: + +```json +{ "sourceIp": "127.0.0.1", "status": 200 } +{ "sourceIp": "127.0.0.1", "status": 503 } +{ "sourceIp": "127.0.0.1", "status": 400 } +``` + +The processor creates the following event: + +```json +{ "sourceIp": "127.0.0.1", "status": [200, 503, 400] } +``` + +<!-- vale off --> +### tail_sampler +<!-- vale on --> + +The `tail_sampler` action samples OpenTelemetry traces after collecting all spans for a trace within the group duration. It allows you to keep all error traces while sampling a percentage of successful traces, reducing storage while retaining all error traces. + +You can customize the processor with the following configuration options: + +* `wait_period`: The amount of time to wait before considering a trace complete. Must be greater than 0 and no more than 60 seconds. Required. +* `percent`: The percentage of non-error traces to sample (0--100, exclusive). All error traces are always kept. Required. +* `condition`: A conditional expression that determines whether an event is an error event. Events matching this condition are always kept regardless of the `percent` setting. + +For example, when using `identification_keys: ["traceId"]`, `wait_period: "10s"`, `percent: 20`, and `condition: '/status_code == 2'`, the `tail_sampler` action keeps all traces that contain at least one span with `status_code == 2` (error) and samples 20% of the remaining successful traces. + +<!-- vale off --> ### percent_sampler +<!-- vale on --> The `percent_sampler` action controls the number of events aggregated based on a percentage of events. The action drops any events not included in the percentage. @@ -138,7 +227,7 @@ You can set the percentage of events using the `percent` configuration, which in For example, if percent is set to `50`, the action tries to process the following events in the one-second interval: -``` +```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 2500 } { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 500 } { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 1000 } @@ -147,7 +236,7 @@ For example, if percent is set to `50`, the action tries to process the followin The pipeline processes 50% of the events, drops the other events, and does not generate a new event: -``` +```json { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 500 } { "sourceIp": "127.0.0.1", "destinationIp": "192.168.0.1", "bytes": 3100 } ``` @@ -171,9 +260,9 @@ The `aggregate` processor includes the following custom metrics. * `actionHandleEventsDropped`: The number of events that have not been returned from the `handleEvent` call to the configured [action](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#action). * `actionHandleEventsProcessingErrors`: The number of calls made to `handleEvent` for the configured [action](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#action) that resulted in an error. * `actionConcludeGroupEventsOut`: The number of events that have been returned from the `concludeGroup` call to the configured [action](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#action). -* `actionConcludeGroupEventsDropped`: The number of events that have not been returned from the `condludeGroup` call to the configured [action](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#action). +* `actionConcludeGroupEventsDropped`: The number of events that have not been returned from the `concludeGroup` call to the configured [action](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#action). * `actionConcludeGroupEventsProcessingErrors`: The number of calls made to `concludeGroup` for the configured [action](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/aggregate-processor#action) that resulted in an error. **Gauge** -* `currentAggregateGroups`: The current number of groups. This gauge decreases when a group concludes and increases when an event initiates the creation of a new group. \ No newline at end of file +* `currentAggregateGroups`: This gauge represents the current number of active aggregate groups. It decreases when an aggregate group is completed and its results are emitted and increases when a new event initiates the creation of a new aggregate group. diff --git a/_data-prepper/pipelines/configuration/processors/anomaly-detector.md b/_data-prepper/pipelines/configuration/processors/anomaly-detector.md index 9628bb6c..43d5f6e1 100644 --- a/_data-prepper/pipelines/configuration/processors/anomaly-detector.md +++ b/_data-prepper/pipelines/configuration/processors/anomaly-detector.md @@ -1,18 +1,18 @@ --- layout: default -title: anomaly_detector +title: Anomaly detector parent: Processors grand_parent: Pipelines -nav_order: 45 +nav_order: 30 --- -# anomaly_detector +# Anomaly detector processor -The anomaly detector processor takes structured data and runs anomaly detection algorithms on fields that you can configure in that data. The data must be either an integer or a real number for the anomaly detection algorithm to detect anomalies. Deploying the aggregate processor in a pipeline before the anomaly detector processor can help you achieve the best results, as the aggregate processor automatically aggregates events by key and keeps them on the same host. For example, if you are searching for an anomaly in latencies from a specific IP address and if all the events go to the same host, then the host has more data for these events. This additional data results in better training of the machine learning (ML) algorithm, which results in better anomaly detection. +The `anomaly_detector` processor takes structured data and runs anomaly detection algorithms on fields that you can configure in that data. The data must be either an integer or a real number for the anomaly detection algorithm to detect anomalies. Deploying the aggregate processor in a pipeline before the `anomaly_detector` processor can help you achieve the best results, as the aggregate processor automatically aggregates events by key and keeps them on the same host. For example, if you are searching for an anomaly in latencies from a specific IP address and if all the events go to the same host, then the host has more data for these events. This additional data results in better training of the machine learning (ML) algorithm, which results in better anomaly detection. ## Configuration -You can configure the anomaly detector processor by specifying a key and the options for the selected mode. You can use the following options to configure the anomaly detector processor. +You can configure the `anomaly_detector` processor by specifying a key and the options for the selected mode. You can use the following options to configure the `anomaly_detector` processor. | Name | Required | Description | | :--- | :--- | :--- | @@ -25,21 +25,23 @@ You can configure the anomaly detector processor by specifying a key and the opt ### Keys -Keys that are used in the anomaly detector processor are present in the input event. For example, if the input event is `{"key1":value1, "key2":value2, "key3":value3}`, then any of the keys (such as `key1`, `key2`, `key3`) in that input event can be used as anomaly detector keys as long as their value (such as `value1`, `value2`, `value3`) is an integer or real number. +Keys that are used in the `anomaly_detector` processor are present in the input event. For example, if the input event is `{"key1":value1, "key2":value2, "key3":value3}`, then any of the keys (such as `key1`, `key2`, `key3`) in that input event can be used as anomaly detector keys as long as their value (such as `value1`, `value2`, `value3`) is an integer or real number. +<!-- vale off --> ### random_cut_forest mode +<!-- vale on --> -The random cut forest (RCF) ML algorithm is an unsupervised algorithm for detecting anomalous data points within a dataset. To detect anomalies, the anomaly detector processor uses the `random_cut_forest` mode. +The random cut forest (RCF) ML algorithm is an unsupervised algorithm for detecting anomalous data points within a dataset. To detect anomalies, the `anomaly_detector` processor uses the `random_cut_forest` mode. | Name | Description | | :--- | :--- | | `random_cut_forest` | Processes events using the RCF ML algorithm to detect anomalies. | -RCF is an unsupervised ML algorithm for detecting anomalous data points within a dataset. Data Prepper uses RCF to detect anomalies in data by passing the values of the configured key to RCF. For example, when an event with a latency value of 11.5 is sent, the following anomaly event is generated: +RCF is an unsupervised ML algorithm for detecting anomalous data points within a dataset. OpenSearch Data Prepper uses RCF to detect anomalies in data by passing the values of the configured key to RCF. For example, when an event with a latency value of 11.5 is sent, the following anomaly event is generated: - ```json - { "latency": 11.5, "deviation_from_expected":[10.469302736820003],"grade":1.0} +```json +{ "latency": 11.5, "deviation_from_expected":[10.469302736820003],"grade":1.0} ``` In this example, `deviation_from_expected` is a list of deviations for each of the keys from their corresponding expected values, and `grade` is the anomaly grade that indicates the anomaly severity. @@ -53,6 +55,7 @@ You can configure `random_cut_forest` mode with the following options. | `sample_size` | `256` | 100--2500 | The sample size used in the ML algorithm. | | `time_decay` | `0.1` | 0--1.0 | The time decay value used in the ML algorithm. Used as the mathematical expression `timeDecay` divided by `SampleSize` in the ML algorithm. | | `type` | `metrics` | N/A | The type of data sent to the algorithm. | +| `output_after` | 32 | N/A | Specifies the number of events to process before outputting any detected anomalies. | | `version` | `1.0` | N/A | The algorithm version number. | ## Usage @@ -63,14 +66,15 @@ To get started, create the following `pipeline.yaml` file. You can use the follo ad-pipeline: source: ... - .... + .... processor: - anomaly_detector: keys: ["latency"] - mode: + mode: random_cut_forest: ``` +{% include copy.html %} -When you run the anomaly detector processor, the processor extracts the value for the `latency` key, and then passes the value through the RCF ML algorithm. You can configure any key that comprises integers or real numbers as values. In the following example, you can configure `bytes` or `latency` as the key for an anomaly detector. +When you run the `anomaly_detector` processor, the processor extracts the value for the `latency` key and then passes the value through the RCF ML algorithm. You can configure any key that comprises integers or real numbers as values. In the following example, you can configure `bytes` or `latency` as the key for an anomaly detector. `{"ip":"1.2.3.4", "bytes":234234, "latency":0.2}` diff --git a/_data-prepper/pipelines/configuration/processors/aws-lambda.md b/_data-prepper/pipelines/configuration/processors/aws-lambda.md new file mode 100644 index 00000000..5973971d --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/aws-lambda.md @@ -0,0 +1,281 @@ +--- +layout: default +title: AWS Lambda +parent: Processors +grand_parent: Pipelines +nav_order: 40 +--- + +# AWS Lambda processor + +The [AWS Lambda](https://aws.amazon.com/lambda/) integration allows you to use serverless computing capabilities within your OpenSearch Data Prepper pipelines for flexible event processing and data routing. + +## Configuration + +The `aws_lambda` processor enables invocation of an AWS Lambda function within your Data Prepper pipeline in order to process events. It supports both synchronous and asynchronous invocations based on your use case. + +## Configuration fields + +You can configure the processor using the following configuration options. + +Field | Type | Required | Description +-------------------- | ------- | -------- | ---------------------------------------------------------------------------- +`function_name` | String | Required | The name of the AWS Lambda function to invoke. Must be 3--500 characters. +`aws.region` | String | Required | The AWS Region in which the Lambda function is located. +`aws.sts_role_arn` | String | Optional | The Amazon Resource Name (ARN) of the role to assume before invoking the Lambda function. Must be 20--2048 characters. +`aws.sts_external_id` | String | Optional | An external ID for STS role assumption. Must be 2--1224 characters. +`aws.sts_header_overrides` | Map | Optional | STS header overrides. Maximum of 5 headers supported. +`client.max_retries` | Integer | Optional | The maximum number of retries for failed invocations. Default is `3`. +`client.api_call_timeout` | Duration | Optional | The API call timeout. Default is `60s`. +`client.api_call_attempt_timeout` | Duration | Optional | The timeout for individual API call attempts. If not specified, AWS SDK defaults are used. +`client.connection_timeout` | Duration | Optional | The SDK connection timeout. Default is `60s`. +`client.read_timeout` | Duration | Optional | The amount of time the SDK waits for data to be read from an established connection. If not specified, AWS SDK defaults are used. +`client.max_concurrency` | Integer | Optional | The maximum number of concurrent threads on the client. Default is `200`. +`client.base_delay` | Duration | Optional | The base delay for the exponential backoff. Default is `100ms`. +`client.max_backoff` | Duration | Optional | The maximum backoff time for the exponential backoff. Default is `20s`. +`client.retryable_status_codes` | List | Optional | A list of HTTP status codes that trigger a retry when returned by a Lambda invocation, for example `[500, 502, 503, 504]`. Default is an empty list, in which case Data Prepper retries only throttling errors, Lambda service errors, and network or connection errors. Use for idempotent functions for which retrying transient server-side errors is safe. +`batch` | Object | Optional | The batch settings for the Lambda invocations. Contains `key_name` (default: `"events"`) and `threshold` object with `event_count` (default: `100`), `maximum_size` (default: `"5mb"`), and `event_collect_timeout` (default: `10s`). See [Batch processing](#batch-processing) for details. +`lambda_when` | String | Optional | A conditional expression that determines when to invoke the Lambda processor. +`response_codec` | Object | Optional | A codec configuration for parsing Lambda responses. Default is `json`. +`tags_on_failure` | List | Optional | A list of tags to add to events when the Lambda function fails or encounters an exception. +`response_events_match` | Boolean | Optional | Specifies how Data Prepper interprets and processes Lambda function responses. Default is `false`. +`response_mode` | String | Optional | The response handling mode, either `replace` or `merge`. Default is `replace`. +`invocation_type` | String | Optional | The Lambda invocation type. Valid values are `request-response`, `event`, and `streaming-response`. Default is `request-response`. See [Usage](#usage). +`streaming` | Object | Optional | The response streaming configuration. Response streaming is used only when `invocation_type` is `streaming-response` and `streaming.enabled` is `true`. When `streaming` is specified, `batch.threshold.event_count` must be `1`. See [Response streaming](#response-streaming). +`streaming.enabled` | Boolean | Optional | Whether to invoke the Lambda function using response streaming. Default is `false`. +`streaming.response_handling` | String | Optional | Specifies how the streamed response is converted into events. The only valid value is `reconstruct-document`, which merges all parsed chunks of the streamed response into the original event. Default is `reconstruct-document`. +`keys` | List | Optional | Keys to send to the Lambda function. +`cache` | Object | Optional | The cache configuration. Only valid when `response_mode` is `merge` and `keys` are specified. +`cache.ttl` | Long | Optional | The cache time-to-live. +`cache.max_size` | Long | Optional | The maximum cache size. Must be between 1048576 and 10485760. +`circuit_breaker_retries` | Integer | Optional | The maximum number of circuit breaker checks before proceeding. Default is `0`. +`circuit_breaker_wait_interval` | Long | Optional | The amount of time, in milliseconds, between circuit breaker checks. Default is `1000ms`. + +The following is an example configuration: + +```yaml +processor: + - aws_lambda: + function_name: my-lambda-function + response_events_match: false + response_mode: merge + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/my-lambda-role + client: + max_retries: 3 + api_call_timeout: PT60S + api_call_attempt_timeout: PT30S # Optional: per-attempt timeout + connection_timeout: PT60S + read_timeout: PT15M # Optional: for long-running Lambda functions + max_concurrency: 200 + base_delay: "PT0.1S" + max_backoff: "PT20S" + retryable_status_codes: [500, 502, 503, 504] # Optional: retry these Lambda invocation status codes + batch: + key_name: events + threshold: + event_count: 100 + maximum_size: 5mb + event_collect_timeout: PT10S + lambda_when: "/some_key == null" + keys: ["key1", "key2"] + cache: + ttl: 3600 + max_size: 5242880 + circuit_breaker_retries: 0 + circuit_breaker_wait_interval: 1000 + tags_on_failure: ["lambda_failed"] +``` +{% include copy.html %} + +## Timeout configuration + +The `aws_lambda` processor supports multiple timeout layers following AWS SDK best practices: + +- `api_call_timeout`: The total amount of time for the entire API call including all retries. +- `api_call_attempt_timeout`: The time limit for each individual attempt. +- `read_timeout`: The amount of time to wait for data from an established connection. + +For Lambda functions that run for longer than 60 seconds, configure both `api_call_timeout` and `read_timeout` to appropriate values. The `api_call_attempt_timeout` enforces a per-attempt timeout, enabling fast failure of slow requests while preserving overall retry behavior. + +## Usage + +The processor supports the following invocation types: + +- `request-response`: The processor waits for Lambda function completion before proceeding. +- `event`: The function is triggered asynchronously without waiting for a response. +- `streaming-response`: The processor invokes the function using Lambda response streaming and waits for the complete streamed response. Requires `streaming.enabled` to be `true`. See [Response streaming](#response-streaming). + +The `cache` setting is valid only when `invocation_type` is `request-response`. + +### Response streaming + +Use response streaming for Lambda functions that return large responses in multiple chunks. The processor collects all chunks of the streamed response, parses them using the `response_codec`, and merges the resulting data into the original event. Because each response is merged into a single original event, `batch.threshold.event_count` must be set to `1`. + +The following example configures response streaming: + +```yaml +processor: + - aws_lambda: + function_name: my-streaming-function + invocation_type: streaming-response + streaming: + enabled: true + response_handling: reconstruct-document + batch: + threshold: + event_count: 1 + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/my-lambda-role +``` +{% include copy.html %} + +### Batch processing + +The `aws_lambda` processor batches events when invoking Lambda functions. The `batch` configuration allows you to configure the thresholds for bulk invocations. + +The `batch` configuration has the following structure: + +- `key_name`: The key under which events are grouped in the payload sent to Lambda (default: `"events"`). +- `threshold`: An object containing batch threshold settings: + - `event_count`: Maximum number of events per batch (default: `100`). + - `maximum_size`: Maximum batch size (default: `5mb`). + - `event_collect_timeout`: Maximum time to wait for collecting events before sending the batch (default: `10s`). Must be between 1 second and 3600 seconds. + +**Important**: The `event_collect_timeout` parameter must be specified under `batch.threshold`, not directly under `batch`. + +### Response handling + +The processor supports two response modes: +- `replace`: Lambda response replaces the original event data (default) +- `merge`: Lambda response is merged with the original event data + +### Caching + +When `response_mode` is set to `merge` and `keys` are specified, the processor can cache Lambda responses to improve performance for repeated requests. + +### Circuit breaker + +The processor includes circuit breaker functionality to handle memory pressure situations gracefully. + +### Tags on failure + +Custom tags can be applied to events when Lambda processing fails or encounters exceptions using the `tags_on_failure` configuration. + +## Behavior + +When configured for batching, the `aws_lambda` processor groups multiple events into a single request. This grouping is governed by batch thresholds, which can be based on the event count, size limit, or timeout. The processor then sends the entire batch to the Lambda function as a single payload. + +## Lambda response handling + +The `response_events_match` setting defines how Data Prepper handles the relationship between batch events sent to Lambda and the response received: + +- `true`: Lambda returns a JSON array with results for each batched event. Data Prepper maps this array back to its corresponding original event, ensuring that each event in the batch gets the corresponding part of the response from the array. +- `false`: Lambda returns one or more events for the entire batch. Response events are not correlated with the original events. Original event metadata is not preserved in the response events. For example, when `response_events_match` is set to `true`, the Lambda function is expected to return the same number of response events as the number of original requests, maintaining the original order. + +## Lambda function implementation + +When Data Prepper invokes your Lambda function it sends a JSON object with events grouped under the configured `key_name` (default: `"events"`). + +### Input format + +Your Lambda function receives the following input structure: + +```json +{ + "events": [ + {"field1": "value1", "field2": "value2"}, + {"field1": "value3", "field2": "value4"} + ] +} +``` +{% include copy.html %} + +The key name (`"events"` in this example) is configurable through the `batch.key_name` parameter. + +### Output format + +The expected output format depends on the `response_events_match` setting: + +#### When `response_events_match: false` (default) + +Lambda can return one or more new events. The returned events don't need to match the input count. When `response_events_match: false`, the `aws_lambda` processor drops all input events and outputs only the events returned by the Lambda function, replacing the input data rather than combining it: + +```python +def lambda_handler(event, context): + # Process all input events and return new events + return [ + {"result": "processed_data_1"}, + {"result": "processed_data_2"} + ] +``` +{% include copy.html %} + +#### When `response_events_match: true` + +The following function sets a `status` key to the static value `processed` in each event: + +```python +def lambda_handler(event, context): + input_events = event.get('events', []) + output = [] + + # Process each event and maintain order + for input_event in input_events: + processed_event = input_event.copy() + processed_event["status"] = "processed" + # Transform data as needed + for key, value in input_event.items(): + if isinstance(value, str): + processed_event[key] = value.upper() + output.append(processed_event) + + # Must return same count as input + return output +``` +{% include copy.html %} + +<!-- vale off --> +### Example Lambda function +<!-- vale on --> + +The following Lambda function transforms all string fields to uppercase: + +```python +def lambda_handler(event, context): + # Get events from the configured key_name (default: "events") + input_events = event.get('events', []) + output_events = [] + + for input_event in input_events: + # Add transformation marker + input_event["_transformed_"] = True + + # Transform string fields to uppercase + for key, value in input_event.items(): + if isinstance(value, str): + input_event[key] = value.upper() + + output_events.append(input_event) + + return output_events +``` +{% include copy.html %} + +## Limitations + +Note the following limitations: + +- Payload limitation: 6 MB payload limit +- Response codec: JSON-only codec support + +## Integration testing + +Integration tests for this plugin are executed separately from the main Data Prepper build process. Use the following Gradle command to run these tests: + +```bash +./gradlew :data-prepper-plugins:aws-lambda:integrationTest -Dtests.processor.lambda.region="us-east-1" -Dtests.processor.lambda.functionName="lambda_test_function" -Dtests.processor.lambda.sts_role_arn="arn:aws:iam::123456789012:role/dataprepper-role +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/processors/convert-entry-type.md b/_data-prepper/pipelines/configuration/processors/convert-entry-type.md new file mode 100644 index 00000000..4ee92311 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/convert-entry-type.md @@ -0,0 +1,71 @@ +--- +layout: default +title: Convert type +parent: Processors +grand_parent: Pipelines +nav_order: 50 +redirect_from: + - /data-prepper/pipelines/configuration/processors/convert_entry_type/ +--- + +# Convert type processor + +The `convert_type` processor converts a value type associated with the specified key in an event to the specified type. It is a casting processor that changes the types of some fields in events. Some data must be converted to a different type, such as an integer to a double or a string to an integer, so that it will pass the events through condition-based processors or perform conditional routing. + +Starting with OpenSearch Data Prepper version 2.10.0, the `convert_entry_type` processor has been renamed to `convert_type`. Configurations using `convert_entry_type` generate a deprecation warning and should be updated. +{: .important } + +## Configuration + +You can configure the `convert_type` processor with the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: convert_type +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/7d15115c281687aab50e5c471fd210cb1ef90fc5/data-prepper-plugins/mutate-event-processors/src/main/java/org/opensearch/dataprepper/plugins/processor/mutateevent/ConvertEntryTypeProcessorConfig.java +--> + +| Option | Required | Description | +| :--- | :--- | :--- | +| `key`| Conditionally | The key of the value to convert to a different type. Required unless `keys` or `coerce_strings` is specified. Cannot be used with `keys`. | +| `keys`| Conditionally | The keys of the values to convert to a different type. Required unless `key` or `coerce_strings` is specified. Cannot be used with `key`. | +| `type` | No | Target type for the key-value pair. Possible values are `integer`, `long`, `double`, `big_decimal`, `string`, and `boolean`. Default value is `integer`. | +| `null_conversion_values` | No | A list of strings that represent a `null` value. If the value of a field specified in `key` or `keys` equals one of these strings, then the field is removed from the event. | +| `iterate_on` | No | The key of a list of objects in the event. When specified, the processor converts the `key` or `keys` fields in each object in the list. | +| `coerce_strings` | No | When specified, the processor converts the string values of all fields in the event, including fields in nested objects and lists, to the type that the string represents. The strings `true` and `false` (case insensitive) are converted to Booleans. Strings that contain a colon (`:`) and match one of the `coerce_strings.time_formats` patterns are converted to epoch milliseconds. Numeric strings that contain a decimal point or an exponent are converted to doubles, and other numeric strings are converted to integers or, if they are out of the integer range, to longs. Strings that cannot be converted are not changed. Specify `coerce_strings` as an empty object (`{}`) to use the default time formats. | +| `coerce_strings.time_formats` | No | A list of [Java DateTimeFormatter](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) patterns used to convert time strings to epoch milliseconds. Time strings that do not include a time zone offset are interpreted in the system time zone, and patterns that do not include a year use the current year. Default is `["MMM d HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ss.SSSSSSX", "dd/MMM/yyyy:HH:mm:ss Z"]`. | +| `scale` | No | Modifies the scale of the `big_decimal` when converting to a `big_decimal`. The default value is `0`. | +| `tags_on_failure` | No | A list of tags to be added to the event metadata when the event fails to convert. | +| `convert_when` | No | Specifies a condition using a [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) for performing the `convert_type` operation. If specified, the `convert_type` operation runs only when the expression evaluates to `true`. | + +## Usage + +To get started, create the following `pipeline.yaml` file: + +```yaml +type-conv-pipeline: + source: + ... + .... + processor: + - convert_type: + key: "response_status" + type: "integer" +``` +{% include copy.html %} + +Next, create a log file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with that file path. For more information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). + +For example, before you run the `convert_type` processor, if the `logs_json.log` file contains the following event record: + + +```json +{"message": "value", "response_status":"200"} +``` + +The `convert_type` processor converts the output received to the following output, where the type of `response_status` value changes from a string to an integer: + +```json +{"message":"value","response_status":200} +``` diff --git a/_data-prepper/pipelines/configuration/processors/copy-values.md b/_data-prepper/pipelines/configuration/processors/copy-values.md index f654e6f0..e1c5da84 100644 --- a/_data-prepper/pipelines/configuration/processors/copy-values.md +++ b/_data-prepper/pipelines/configuration/processors/copy-values.md @@ -1,12 +1,12 @@ --- layout: default -title: copy_values +title: Copy values parent: Processors grand_parent: Pipelines -nav_order: 48 +nav_order: 60 --- -# copy_values +# Copy values processor The `copy_values` processor copies values within an event and is a [mutate event]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/mutate-event/) processor. @@ -14,44 +14,129 @@ The `copy_values` processor copies values within an event and is a [mutate event You can configure the `copy_values` processor with the following options. -| Option | Required | Description | -:--- | :--- | :--- -| `entries` | Yes | A list of entries to be copied in an event. | -| `from_key` | Yes | The key of the entry to be copied. | -| `to_key` | Yes | The key of the new entry to be added. | -| `overwrite_if_to_key_exists` | No | When set to `true`, the existing value is overwritten if `key` already exists in the event. The default value is `false`. | +| Option | Required | Type | Description | +:--- | :--- | :--- | :--- +| `entries` | Yes | [entry](#entry) | A list of entries to be copied in an event. See [entry](#entry) for more information. | +| `from_list` | No | String | The key for the list of objects to be copied. | +| `to_list` | No | String | The key for the new list to be added. | +| `overwrite_if_to_list_exists` | No | Boolean | When set to `true`, the existing value is overwritten if the `key` specified by `to_list` already exists in the event. Default is `false`. | + +<!-- vale off --> +## entry +<!-- vale on --> + +For each entry, you can configure the following options. + +| Option | Required | Type | Description | +:--- | :--- | :--- | :--- +| `from_key` | Yes | String | The key for the entry to be copied. | +| `to_key` | Yes | String | The key for the new entry to be added. | +| `overwrite_if_to_key_exists` | No | Boolean | When set to `true`, the existing value is overwritten if the `key` already exists in the event. Default is `false`. | +| `copy_when` | No | String | Specifies a condition for performing the `copy_values` operation using a [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). If specified, the `copy_values` operation will only run when the expression evaluates to `true`. | + ## Usage -To get started, create the following `pipeline.yaml` file: +The following examples show you how to use the `copy_values` processor. + +### Example: Copy values and skip existing fields + +The following example shows you how to configure the processor to copy values and skip existing fields: ```yaml -pipeline: - source: - ... - .... +... processor: - copy_values: entries: - - from_key: "message" - to_key: "newMessage" - overwrite_if_to_key_exists: true - sink: + - from_key: "message1" + to_key: "message2" + - from_key: "message1" + to_key: "message3" +... ``` {% include copy.html %} -Next, create a log file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with that filepath. For more information, see [Configuring Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/#2-configuring-data-prepper). - -For example, before you run the `copy_values` processor, if the `logs_json.log` file contains the following event record: +When the input event contains the following data: ```json -{"message": "hello"} +{"message1": "hello", "message2": "bye"} ``` -When you run this processor, it parses the message into the following output: +The processor copies "message1" to "message3" but not to "message2" because "message2" already exists. The processed event contains the following data: ```json -{"message": "hello", "newMessage": "hello"} +{"message1": "hello", "message2": "bye", "message3": "hello"} ``` -If `newMessage` already exists, its existing value is overwritten with `value`. +### Example: Copy values with overwrites + +The following example shows you how to configure the processor to copy values: + +```yaml +... + processor: + - copy_values: + entries: + - from_key: "message1" + to_key: "message2" + overwrite_if_to_key_exists: true + - from_key: "message1" + to_key: "message3" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{"message1": "hello", "message2": "bye"} +``` + +The processor copies "message1" to both "message2" and "message3", overwriting the existing value in "message2". The processed event contains the following data: + +```json +{"message1": "hello", "message2": "hello", "message3": "hello"} +``` + +### Example: Selectively copy values between two lists of objects + +The following example shows you how to configure the processor to copy values between lists: + +```yaml +... + processor: + - copy_values: + from_list: mylist + to_list: newlist + entries: + - from_key: name + to_key: fruit_name +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{ + "mylist": [ + {"name": "apple", "color": "red"}, + {"name": "orange", "color": "orange"} + ] +} +``` + +The processed event contains a `newlist` with selectively copied fields: + +```json +{ + "newlist": [ + {"fruit_name": "apple"}, + {"fruit_name": "orange"} + ], + "mylist": [ + {"name": "apple", "color": "red"}, + {"name": "orange", "color": "orange"} + ] +} +``` diff --git a/_data-prepper/pipelines/configuration/processors/csv.md b/_data-prepper/pipelines/configuration/processors/csv.md index e386db4b..90c60f72 100644 --- a/_data-prepper/pipelines/configuration/processors/csv.md +++ b/_data-prepper/pipelines/configuration/processors/csv.md @@ -1,12 +1,12 @@ --- layout: default -title: csv +title: CSV parent: Processors grand_parent: Pipelines -nav_order: 49 +nav_order: 70 --- -# csv +# CSV processor The `csv` processor parses comma-separated values (CSVs) from the event into columns. @@ -16,12 +16,16 @@ The following table describes the options you can use to configure the `csv` pro Option | Required | Type | Description :--- | :--- | :--- | :--- -source | No | String | The field in the event that will be parsed. Default value is `message`. -quote_character | No | String | The character used as a text qualifier for a single column of data. Default value is `"`. -delimiter | No | String | The character separating each column. Default value is `,`. -delete_header | No | Boolean | If specified, the event header (`column_names_source_key`) is deleted after the event is parsed. If there is no event header, no action is taken. Default value is true. -column_names_source_key | No | String | The field in the event that specifies the CSV column names, which will be automatically detected. If there need to be extra column names, the column names are automatically generated according to their index. If `column_names` is also defined, the header in `column_names_source_key` can also be used to generate the event fields. If too few columns are specified in this field, the remaining column names are automatically generated. If too many column names are specified in this field, the CSV processor omits the extra column names. -column_names | No | List | User-specified names for the CSV columns. Default value is `[column1, column2, ..., columnN]` if there are no columns of data in the CSV record and `column_names_source_key` is not defined. If `column_names_source_key` is defined, the header in `column_names_source_key` generates the event fields. If too few columns are specified in this field, the remaining column names are automatically generated. If too many column names are specified in this field, the CSV processor omits the extra column names. +`source` | No | String | The field in the event that will be parsed. Default value is `message`. +`quote_character` | No | String | The character used as a text qualifier for a single column of data. Default is `"`. +`delimiter` | No | String | The character separating each column. Default is `,`. +`delete_header` | No | Boolean | If specified, the event header (`column_names_source_key`) is deleted after the event is parsed. If there is no event header, no action is taken. Default is `true`. +`column_names_source_key` | No | String | The field in the event that specifies the CSV column names, which will be automatically detected. If there need to be extra column names, the column names are automatically generated according to their index. If `column_names` is also defined, the header in `column_names_source_key` can also be used to generate the event fields. If too few columns are specified in this field, the remaining column names are automatically generated. If too many column names are specified in this field, the CSV processor omits the extra column names. +`column_names` | No | List | User-specified names for the CSV columns. Default is `[column1, column2, ..., columnN]` if there are no columns of data in the CSV record and `column_names_source_key` is not defined. If `column_names_source_key` is defined, the header in `column_names_source_key` generates the event fields. If too few columns are specified in this field, the remaining column names are automatically generated. If too many column names are specified in this field, the CSV processor omits the extra column names. +`delete_source` | No | Boolean | If `true`, deletes the configured `source` field (by default, `message`) after CSV parsing. This configuration option improves memory pressure if the `source` field is not going to be used because the processing is done in batches. Default is `false`. +`normalize_keys` | No | Boolean | If `true`, replaces characters that are not valid in event keys with an underscore (`_`) in the column names. For example, the column name `user:name` becomes `user_name`. Default is `false`. +`multiline` | No | Boolean | If `true`, the `source` field is treated as multiline CSV data in which the first line contains the column names and each following line contains a row of data. The processor creates a new event for each data row, containing the fields of the original event and the parsed columns, and drops the original event. Events that the processor does not parse, such as events in which the `source` field contains only one line, are also dropped. When `multiline` is `true`, the `column_names`, `column_names_source_key`, `delete_header`, and `delete_source` options are not applied. Default is `false`. +`csv_when` | No | String | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some_key == "test"`. If specified, the `csv` processor runs only on events for which the expression evaluates to `true`. ## Usage @@ -48,12 +52,13 @@ csv-pipeline: When run, the processor will parse the message. Although only two column names are specified in processor settings, a third column name is automatically generated because the data contained in `ingest.csv` includes three columns, `1,2,3`: -``` +```json {"message": "1,2,3", "col1": "1", "col2": "2", "column3": "3"} ``` + ### Automatically detect column names -The following configuration automatically detects the header of a CSV file ingested through an [`s3 source`]({{site.url}}{{site.baseurl}}//data-prepper/pipelines/configuration/sources/s3/): +The following configuration automatically detects the header of a CSV file ingested through an [`s3 source`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/): ```yaml csv-s3-pipeline: @@ -80,7 +85,7 @@ csv-s3-pipeline: For example, if the `ingest.csv` file in the Amazon Simple Storage Service (Amazon S3) bucket that the Amazon Simple Queue Service (SQS) queue is attached to contains the following data: -``` +```text Should,skip,this,line a,b,c 1,2,3 @@ -97,6 +102,108 @@ Then, the processor parses the event into the following output. Because `delete_ {"message": "1,2,3", "a": "1", "b": "2", "c": "3"} ``` +### Delete the source field after parsing + +If you want to remove the original `message` field once columns are extracted, enable `delete_source`: + +```yaml +csv-pipeline-delete-source: + source: + file: + path: "/full/path/to/ingest.csv" + record_type: "event" + processor: + - csv: + column_names: ["col1", "col2"] + delete_source: true + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: csv-demo-%{yyyy.MM.dd} +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "csv-demo-2025.11.10", + "_id" : "vTgDb5oBcoMYUXV6ocPH", + "_score" : 1.0, + "_source" : { + "col1" : "1", + "col2" : "2", + "column3" : "3" + } + }, + { + "_index" : "csv-demo-2025.11.10", + "_id" : "vjgDb5oBcoMYUXV6ocPI", + "_score" : 1.0, + "_source" : { + "col1" : "4", + "col2" : "5", + "column3" : "6" + } + } + ] + } +} +``` +{% include copy.html %} + +If `delete_source` is set to `false`, the documents include the `message` field: + +```json +{ + ... + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "csv-demo-2025.11.10", + "_id" : "fpAKb5oB85vgu48rA-rD", + "_score" : 1.0, + "_source" : { + "message" : "1,2,3", + "col1" : "1", + "col2" : "2", + "column3" : "3" + } + }, + { + "_index" : "csv-demo-2025.11.10", + "_id" : "f5AKb5oB85vgu48rA-rD", + "_score" : 1.0, + "_source" : { + "message" : "4,5,6", + "col1" : "4", + "col2" : "5", + "column3" : "6" + } + } + ] + } +} +``` + ## Metrics The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. @@ -113,4 +220,4 @@ The `csv` processor includes the following custom metrics. The `csv` processor includes the following counter metrics: -* `csvInvalidEvents`: The number of invalid events, usually caused by an unclosed quotation mark in the event itself. Data Prepper throws an exception when an invalid event is parsed. +* `csvInvalidEvents`: The number of invalid events, usually caused by an unclosed quotation mark in the event itself. OpenSearch Data Prepper throws an exception when an invalid event is parsed. diff --git a/_data-prepper/pipelines/configuration/processors/date.md b/_data-prepper/pipelines/configuration/processors/date.md index 27b571df..c712bed7 100644 --- a/_data-prepper/pipelines/configuration/processors/date.md +++ b/_data-prepper/pipelines/configuration/processors/date.md @@ -1,32 +1,47 @@ --- layout: default -title: date +title: Date parent: Processors grand_parent: Pipelines -nav_order: 50 +nav_order: 80 --- -# date +# Date processor -The `date` processor adds a default timestamp to an event, parses timestamp fields, and converts timestamp information to the International Organization for Standardization (ISO) 8601 format. This timestamp information can be used as an event timestamp. +The `date` processor adds a default timestamp to an event, parses timestamp fields, and converts timestamp information to the International Organization for Standardization (ISO) 8601 format. This timestamp information can be used as an event timestamp. ## Configuration The following table describes the options you can use to configure the `date` processor. +<!-- +This table is autogenerated. Do not edit it. +- name: date +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/date-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/date/DateProcessorConfig.java +--> + + Option | Required | Type | Description :--- | :--- | :--- | :--- -match | Conditionally | List | List of `key` and `patterns` where patterns is a list. The list of match can have exactly one `key` and `patterns`. There is no default value. This option cannot be defined at the same time as `from_time_received`. Include multiple date processors in your pipeline if both options should be used. -from_time_received | Conditionally | Boolean | A boolean that is used for adding default timestamp to event data from event metadata which is the time when source receives the event. Default value is `false`. This option cannot be defined at the same time as `match`. Include multiple date processors in your pipeline if both options should be used. -destination | No | String | Field to store the timestamp parsed by date processor. It can be used with both `match` and `from_time_received`. Default value is `@timestamp`. -source_timezone | No | String | Time zone used to parse dates. It is used in case the zone or offset cannot be extracted from the value. If the zone or offset are part of the value, then timezone is ignored. Find all the available timezones [the list of database time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List) in the **TZ database name** column. -destination_timezone | No | String | Timezone used for storing timestamp in `destination` field. The available timezone values are the same as `source_timestamp`. -locale | No | String | Locale is used for parsing dates. It's commonly used for parsing month names(`MMM`). It can have language, country and variant fields using IETF BCP 47 or String representation of [Locale](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html) object. For example `en-US` for IETF BCP 47 and `en_US` for string representation of Locale. Full list of locale fields which includes language, country and variant can be found [the language subtag registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). Default value is `Locale.ROOT`. +`match` | Conditionally | [Match](#match) | The date match configuration. This option cannot be defined at the same time as `from_time_received`. There is no default value. +`from_time_received` | Conditionally | Boolean | When `true`, the timestamp from the event metadata, which is the time at which the source receives the event, is added to the event data. This option cannot be defined at the same time as `match`. Default is `false`. +`date_when` | No | String | Specifies under what condition the `date` processor should perform matching. Default is no condition. +`origination_timestamp_to_metadata` | No | Boolean | When `true`, the timestamp parsed using `match` is also added to the event metadata as the event's origination time. Data Prepper uses this time to report the `EndToEndLatency` metric when the event reaches the sink. Default is `false`. +`destination` | No | String | The field used to store the timestamp parsed by the date processor. Can be used with both `match` and `from_time_received`. Default is `@timestamp`. +`output_format` | No | String | Determines the format of the timestamp added to an event. Default is `yyyy-MM-dd'T'HH:mm:ss.SSSXXX`. +`source_timezone` | No | String | The time zone used to parse dates, including when the zone or offset cannot be extracted from the value. If the zone or offset are part of the value, then the time zone is ignored. A list of all the available time zones is contained in the **TZ database name** column of [the list of database time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List). +`destination_timezone` | No | String | The time zone used for storing the timestamp in the `destination` field. A list of all the available time zones is contained in the **TZ database name** column of [the list of database time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List). +`locale` | No | String | The location used for parsing dates. Commonly used for parsing month names (`MMM`). The value can contain language, country, or variant fields in IETF BCP 47, such as `en-US`, or a string representation of the [locale](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html) object, such as `en_US`. A full list of locale fields, including language, country, and variant, can be found in [the language subtag registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). Default is `Locale.ROOT`. -<!---## Configuration -Content will be added to this section.---> +### Match + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`key` | Yes | String | Represents the event key against which to match patterns. Required if `match` is configured. +`patterns` | Yes | List | A list of possible patterns that the timestamp value of the key can have. The patterns are based on a sequence of letters and symbols. The `patterns` support all the patterns listed in the Java [DatetimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) reference. The timestamp value also supports `epoch_second`, `epoch_milli`, and `epoch_nano` values, which represent the timestamp as the number of seconds, milliseconds, and nanoseconds since the epoch. Epoch values always use the UTC time zone. ## Metrics @@ -40,5 +55,402 @@ The following table describes common [Abstract processor](https://github.com/ope The `date` processor includes the following custom metrics. -* `dateProcessingMatchSuccessCounter`: Returns the number of records that match with at least one pattern specified by the `match configuration` option. -* `dateProcessingMatchFailureCounter`: Returns the number of records that did not match any of the patterns specified by the `patterns match` configuration option. \ No newline at end of file +* `dateProcessingMatchSuccessCounter`: Returns the number of records that match at least one pattern specified by the `match configuration` option. +* `dateProcessingMatchFailureCounter`: Returns the number of records that did not match any of the patterns specified by the `patterns match` configuration option. + +## Pattern reference + +The following table provides common `DateTime` patterns. + +| Pattern | Example | Description | +| ------------------------------ | ----------------------------- | ----------------------------- | +| `yyyy-MM-dd'T'HH:mm:ss.SSSXXX` | `2023-03-15T14:30:45.123-05:00` | ISO 8601 format with time zone | +| `dd/MMM/yyyy:HH:mm:ss Z` | `15/Mar/2023:14:30:45 -0500` | Apache Common Log Format | +| `MMM dd HH:mm:ss` | `Mar 15 14:30:45` | Syslog format | +| `yyyy-MM-dd HH:mm:ss` | `2023-03-15 14:30:45` | Standard SQL format | +| `MM/dd/yyyy HH:mm:ss` | `03/15/2023 14:30:45` | US format | + +## Epoch patterns + +The following table provides supported epoch patterns. + +| Pattern | Description | Example value | +| -------------- | -------------------------------------------------- | ------------------- | +| `epoch_second` | Seconds since Unix epoch (`1970-01-01 00:00:00` UTC) | 1678902000 | +| `epoch_milli` | Milliseconds since Unix epoch | 1678902000123 | +| `epoch_micro` | Microseconds since Unix epoch | 1678902000123456 | +| `epoch_nano` | Nanoseconds since Unix epoch | 1678902000123456789 | + +Only one epoch pattern is allowed per pattern list. To support multiple epoch formats, use separate date processors. +{: .note} + +## Examples + +The following are examples of different configurations. + +The examples don't use security and are for demonstration purposes only. We strongly recommend configuring SSL before using these examples in production. +{: .warning} + +### Add the default timestamp to an event using ingestion time + +The following `date` processor configuration can be used to add a default timestamp in the `@timestamp` field applied to all events: + +```yaml +date-ingestion-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - date: + from_time_received: true + destination: "@timestamp" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: date-ingestion-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"app":"web-server","env":"prod","message":"User login successful","level":"info","user_id":"12345"}, + {"app":"database","env":"stage","message":"Connection timeout","level":"error","retry_count":3}, + {"app":"api-gateway","env":"dev","message":"Request processed","level":"debug","response_time_ms":145} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "date-ingestion-2025.10.13", + "_id": "984A3ZkBoQvfnsgqa4od", + "_score": 1, + "_source": { + "app": "web-server", + "env": "prod", + "message": "User login successful", + "level": "info", + "user_id": "12345", + "@timestamp": "2025-10-13T09:56:23.090Z" + } + }, + { + "_index": "date-ingestion-2025.10.13", + "_id": "-M4A3ZkBoQvfnsgqa4od", + "_score": 1, + "_source": { + "app": "database", + "env": "stage", + "message": "Connection timeout", + "level": "error", + "retry_count": 3, + "@timestamp": "2025-10-13T09:56:23.095Z" + } + }, + { + "_index": "date-ingestion-2025.10.13", + "_id": "-c4A3ZkBoQvfnsgqa4od", + "_score": 1, + "_source": { + "app": "api-gateway", + "env": "dev", + "message": "Request processed", + "level": "debug", + "response_time_ms": 145, + "@timestamp": "2025-10-13T09:56:23.096Z" + } + } + ] + } +} +``` + +### Parse a timestamp to convert its format and time zone + +The following example demonstrates how the `date` processor can sequentially parse different timestamp formats (such as epoch milliseconds, epoch seconds, ISO 8601, or Apache Common Log Format) using multiple processors, each handling one specific format: + +```yaml +date-multi-format-pipeline: + source: + http: + path: /events + ssl: false + + processor: + # Handle epoch formats (separate processors for different epoch types) + - date: + match: + - key: event_time + patterns: ["epoch_milli"] + destination: "@timestamp" + output_format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX + source_timezone: UTC + destination_timezone: America/New_York + locale: en_US + date_when: "/event_time != null" + + - date: + match: + - key: event_time + patterns: ["epoch_second"] + destination: "@timestamp" + output_format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX + source_timezone: UTC + destination_timezone: America/New_York + locale: en_US + date_when: "/event_time != null and /@timestamp == null" + + # Handle ISO format variations in a single processor + - date: + match: + - key: event_time + patterns: ["yyyy-MM-dd'T'HH:mm:ss.SSSXXX"] + destination: "@timestamp" + output_format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX + source_timezone: UTC + destination_timezone: America/New_York + locale: en_US + date_when: "/event_time != null and /@timestamp == null" + + # Handle Apache format variations in a single processor + - date: + match: + - key: event_time + patterns: ["dd/MMM/yyyy:HH:mm:ss Z"] + destination: "@timestamp" + output_format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX + source_timezone: UTC + destination_timezone: America/New_York + locale: en_US + date_when: "/event_time != null and /@timestamp == null" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: date-multi-format-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"app":"payment-service","event_time":"1678902000123","transaction_id":"txn_001","amount":99.99,"currency":"USD"}, + {"app":"user-service","event_time":"1678902000","user_id":"user_123","action":"login","ip":"192.168.1.100"}, + {"app":"analytics","event_time":"2023-03-15T14:30:45.123-05:00","event_type":"page_view","page":"/home","session_id":"sess_456"}, + {"app":"web-server","event_time":"15/Mar/2023:14:30:45 -0500","client_ip":"10.0.0.1","method":"GET","url":"/api/users","status":200} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "date-multi-format-2025.10.13", + "_id": "8M4A3ZkBoQvfnsgqaorB", + "_score": 1, + "_source": { + "app": "payment-service", + "event_time": "1678902000123", + "transaction_id": "txn_001", + "amount": 99.99, + "currency": "USD", + "@timestamp": "2023-03-15T13:40:00.123-04:00" + } + }, + { + "_index": "date-multi-format-2025.10.13", + "_id": "8c4A3ZkBoQvfnsgqaorB", + "_score": 1, + "_source": { + "app": "user-service", + "event_time": "1678902000", + "user_id": "user_123", + "action": "login", + "ip": "192.168.1.100", + "@timestamp": "2023-03-15T13:40:00.000-04:00" + } + }, + { + "_index": "date-multi-format-2025.10.13", + "_id": "8s4A3ZkBoQvfnsgqaorB", + "_score": 1, + "_source": { + "app": "analytics", + "event_time": "2023-03-15T14:30:45.123-05:00", + "event_type": "page_view", + "page": "/home", + "session_id": "sess_456", + "@timestamp": "2023-03-15T15:30:45.123-04:00" + } + }, + { + "_index": "date-multi-format-2025.10.13", + "_id": "884A3ZkBoQvfnsgqaorB", + "_score": 1, + "_source": { + "app": "web-server", + "event_time": "15/Mar/2023:14:30:45 -0500", + "client_ip": "10.0.0.1", + "method": "GET", + "url": "/api/users", + "status": 200, + "@timestamp": "2023-03-15T15:30:45.000-04:00" + } + } + ] + } +} +``` + +### Timestamp formats with different day spacing + +The following example demonstrates how the `date` processor handles variable syslog timestamp formats with different day spacing using pattern variations: + +```yaml +date-syslog-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - date: + match: + - key: syslog_timestamp + patterns: ["MMM d HH:mm:ss", "MMM d HH:mm:ss", "MMM dd HH:mm:ss"] + destination: "@timestamp" + output_format: yyyy-MM-dd'T'HH:mm:ss.SSSXXX + source_timezone: America/Los_Angeles + destination_timezone: UTC + locale: en_US + date_when: /syslog_timestamp != null + origination_timestamp_to_metadata: true + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: date-syslog-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"host":"web-server-01","syslog_timestamp":"Mar 15 14:30:45","facility":"daemon","severity":"info","message":"sshd[1234]: Accepted publickey for user1"}, + {"host":"database-02","syslog_timestamp":"Mar 5 09:15:30","facility":"auth","severity":"warning","message":"mysql[5678]: Access denied for user '\''root'\''@'\''localhost'\''"}, + {"host":"app-server-03","syslog_timestamp":"Mar 25 23:45:12","facility":"local0","severity":"error","message":"nginx[9012]: upstream timed out (110: Connection timed out)"}, + {"host":"cache-server-04","message":"redis[3456]: Background saving terminated with success"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "date-syslog-2025.10.13", + "_id": "5s4A3ZkBoQvfnsgqZIrV", + "_score": 1, + "_source": { + "host": "web-server-01", + "syslog_timestamp": "Mar 15 14:30:45", + "facility": "daemon", + "severity": "info", + "message": "sshd[1234]: Accepted publickey for user1", + "@timestamp": "2025-03-15T21:30:45.000Z" + } + }, + { + "_index": "date-syslog-2025.10.13", + "_id": "584A3ZkBoQvfnsgqZIrV", + "_score": 1, + "_source": { + "host": "database-02", + "syslog_timestamp": "Mar 5 09:15:30", + "facility": "auth", + "severity": "warning", + "message": "mysql[5678]: Access denied for user 'root'@'localhost'", + "@timestamp": "2025-03-05T17:15:30.000Z" + } + }, + { + "_index": "date-syslog-2025.10.13", + "_id": "6M4A3ZkBoQvfnsgqZIrV", + "_score": 1, + "_source": { + "host": "app-server-03", + "syslog_timestamp": "Mar 25 23:45:12", + "facility": "local0", + "severity": "error", + "message": "nginx[9012]: upstream timed out (110: Connection timed out)", + "@timestamp": "2025-03-26T06:45:12.000Z" + } + }, + { + "_index": "date-syslog-2025.10.13", + "_id": "6c4A3ZkBoQvfnsgqZIrV", + "_score": 1, + "_source": { + "host": "cache-server-04", + "message": "redis[3456]: Background saving terminated with success" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/configuration/processors/decompress.md b/_data-prepper/pipelines/configuration/processors/decompress.md new file mode 100644 index 00000000..3bfa5024 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/decompress.md @@ -0,0 +1,166 @@ +--- +layout: default +title: Decompress +parent: Processors +grand_parent: Pipelines +nav_order: 90 +--- + +# Decompress processor + +The `decompress` processor decompresses any Base64-encoded compressed fields inside of an event. + +## Configuration + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`keys` | Yes | List<String> | The fields in the event that will be decompressed. +`type` | Yes | Enum | The type of decompression to use for the `keys` in the event. Only `gzip` is supported. +`decompress_when` | No | String| A [Data Prepper conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) that determines when the `decompress` processor will run on certain events. +`tags_on_failure` | No | List<String> | A list of strings with which to tag events when the processor fails to decompress the `keys` inside an event. Defaults to `_decompression_failure`. + +## Usage + +This example demonstrates a complete pipeline that receives compressed log data, decompresses it, and stores it in OpenSearch: + +```yaml +decompress-logs-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - decompress: + keys: ["compressed_log", "compressed_metadata"] + type: gzip + tags_on_failure: ["decompression_failed", "gzip_error"] + + # Only parse if decompression succeeded + - parse_json: + source: compressed_log + destination: parsed_log + parse_when: not hasTags("decompression_failed") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: decompressed-logs-%{yyyy.MM.dd} + tags_target_key: "tags" +``` +{% include copy.html %} + +You can test the pipeline using the two following commands: + +```bash + +GOOD_COMPRESSED_LOG=$(echo '{"message":"Application OK","level":"INFO","service":"api"}' | gzip | base64 | tr -d '\n') +GOOD_COMPRESSED_METADATA=$(echo '{"source_ip":"192.168.1.100","ok":true}' | gzip | base64 | tr -d '\n') + +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d "[ + { + \"compressed_log\": \"${GOOD_COMPRESSED_LOG}\", + \"compressed_metadata\": \"${GOOD_COMPRESSED_METADATA}\", + \"host\": \"web-server-01\", + \"timestamp\": \"2023-10-13T14:30:45Z\" + } + ]" + +BAD_COMPRESSED_LOG=$(echo -n 'this is not gzipped' | base64 | tr -d '\n') +GOOD_COMPRESSED_METADATA=$(echo '{"source_ip":"192.168.1.100","ok":true}' | gzip | base64 | tr -d '\n') + +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d "[ + { + \"compressed_log\": \"${BAD_COMPRESSED_LOG}\", + \"compressed_metadata\": \"${GOOD_COMPRESSED_METADATA}\", + \"host\": \"web-server-02\", + \"timestamp\": \"2023-10-13T14:31:45Z\" + } + ]" +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "decompressed-logs-2025.11.04", + "_id": "dOv1TpoB5Jwkiy-iuKKs", + "_score": 1, + "_source": { + "compressed_log": """{"message":"Application OK","level":"INFO","service":"api"} +""", + "compressed_metadata": """{"source_ip":"192.168.1.100","ok":true} +""", + "host": "web-server-01", + "timestamp": "2023-10-13T14:30:45Z", + "parsed_log": { + "level": "INFO", + "service": "api", + "message": "Application OK" + }, + "tags": [] + } + }, + { + "_index": "decompressed-logs-2025.11.04", + "_id": "dev1TpoB5Jwkiy-iuKKs", + "_score": 1, + "_source": { + "compressed_log": "dGhpcyBpcyBub3QgZ3ppcHBlZA==", + "compressed_metadata": """{"source_ip":"192.168.1.100","ok":true} +""", + "host": "web-server-02", + "timestamp": "2023-10-13T14:31:45Z", + "tags": [ + "decompression_failed", + "gzip_error" + ] + } + } + ] + } +} +``` +{% include copy.html %} + +## Metrics + +By default, Data Prepper serves metrics from the `/metrics/prometheus` endpoint on port `4900`. You can access all the metrics by running the following command: + +```bash +curl http://localhost:4900/metrics/prometheus +``` +{% include copy.html %} + +The following table describes common [abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | The ingress of records to a pipeline component. | +| `recordsOut` | Counter | The egress of records from a pipeline component. | +| `timeElapsed` | Timer | The time elapsed during execution of a pipeline component. | + +### Counter + +The `decompress` processor accounts for the following metrics: + +* `processingErrors`: The number of processing errors that have occurred in the `decompress` processor. + diff --git a/_data-prepper/pipelines/configuration/processors/delay.md b/_data-prepper/pipelines/configuration/processors/delay.md new file mode 100644 index 00000000..c7e716d8 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/delay.md @@ -0,0 +1,28 @@ +--- +layout: default +title: Delay +parent: Processors +grand_parent: Pipelines +nav_order: 100 +--- + +# Delay processor + +This processor will add a delay into the processor chain. Typically, you should use this only for testing, experimenting, and debugging. + +## Configuration + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`for` | No | Duration | The duration of time to delay. Defaults to `1s`. + +## Usage + +The following example shows using the `delay` processor to delay for 2 seconds. + +```yaml +processor: + - delay: + for: 2s +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/processors/delete-entries.md b/_data-prepper/pipelines/configuration/processors/delete-entries.md index 0546ed67..d80b907d 100644 --- a/_data-prepper/pipelines/configuration/processors/delete-entries.md +++ b/_data-prepper/pipelines/configuration/processors/delete-entries.md @@ -1,40 +1,56 @@ --- layout: default -title: delete_entries +title: Delete entries parent: Processors grand_parent: Pipelines -nav_order: 51 +nav_order: 110 --- -# delete_entries +# Delete entries processor -The `delete_entries` processor deletes entries, such as key-value pairs, from an event. You can define the keys you want to delete in the `with-keys` field following `delete_entries` in the YAML configuration file. Those keys and their values are deleted. +The `delete_entries` processor removes entries, such as key-value pairs, from an event. Use the `with_keys` field to specify +the exact keys to delete. To delete keys that match a regular expression pattern, use the `with_keys_regex` field. You can +prevent deletion of specific events when using regular expressions by configuring the `exclude_from_regex` field. + +The only way to configure both `with_keys` and `with_keys_regex` in the same `delete_entries` processor is by using the `entries` field. ## Configuration You can configure the `delete_entries` processor with the following options. -| Option | Required | Description | -:--- | :--- | :--- -| `with_keys` | Yes | An array of keys for the entries to be deleted. | +<!-- +This table is autogenerated. Do not edit it. +- name: delete_entries +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/mutate-event-processors/src/main/java/org/opensearch/dataprepper/plugins/processor/mutateevent/DeleteEntryProcessorConfig.java +--> + +| Option | Required | Description | +:--- |:---------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +| `with_keys` | No | An array that specifies the keys of the entries to delete. | +| `with_keys_regex` | No | An array of regular expression (regex) patterns used to match the keys of entries to delete. | +| `exclude_from_delete` | No | A set of entries to exclude from deletion when using the `with_keys_regex` configuration. | +| `entries` | No | A list of entries to delete from the event. | +| `delete_when` | No | Defines the condition under which the deletion is performed. For example, `value="/some_key == null"` deletes the key only if `/some_key` is null or does not exist. | +|`delete_from_element_when` | No | Defines the condition that determines whether a key–value pair should be removed from each element in the list specified by `iterate_on`. The condition is evaluated for each element, and deletion occurs only if the element's key matches one defined in `with_keys` or `with_keys_regex` and satisfies the condition. | +| `iterate_on` | No | Specifies the key of the list field that contains objects to iterate over. The processor applies any configured deletion rules, such as `with_keys`, `with_keys_regex`, or `delete_from_element_when`, to each element in the list. | ## Usage - To get started, create the following `pipeline.yaml` file: ```yaml pipeline: source: ... - .... + .... processor: - delete_entries: - with_keys: ["message"] + with_keys: [ "message" ] sink: ``` {% include copy.html %} -Next, create a log file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with that filepath. For more information, see [Configuring Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/#2-configuring-data-prepper). +Next, create a log file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with that file path. For more information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). For example, before you run the `delete_entries` processor, if the `logs_json.log` file contains the following event record: @@ -48,4 +64,65 @@ When you run the `delete_entries` processor, it parses the message into the foll {"message2": "goodbye"} ``` -> If `message` does not exist in the event, then no action occurs. + +### Deleting keys that match a pattern + +First, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + ... + .... + processor: + - delete_entries: + with_keys_regex: [ "^tes.*" ] + exclude_from_delete: [ "test" ] + sink: +``` +{% include copy.html %} + +If your `logs_json.log` file contains the following event record: + +```json +{"test": "friends", "test2": "are", "test3": "kind"} +``` + +When you run the `delete_entries` processor, it parses the message into the following output: + +```json +{"test": "friends"} +``` + +### Combining multiple deletion rules + +First, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + ... + .... + processor: + - delete_entries: + entries: + - with_keys: [ "message" ] + - with_keys_regex: [ "^tes.*" ] + exclude_from_delete: [ "test" ] + sink: +``` +{% include copy.html %} + +If your `logs_json.log` file contains the following event record: + +```json +{"message": "hello", "message2": "goodbye", "test": "friends", "test2": "are", "test3": "kind"} +``` + +When you run the `delete_entries` processor, it parses the message into the following output: + +```json +{"message2": "goodbye","test": "friends"} +``` + +> If the `with_keys`, `with_keys_regex`, or `exclude_from_delete` values do not match any event keys, then no action occurs. diff --git a/_data-prepper/pipelines/configuration/processors/dissect.md b/_data-prepper/pipelines/configuration/processors/dissect.md index 2d32ba47..22cbb792 100644 --- a/_data-prepper/pipelines/configuration/processors/dissect.md +++ b/_data-prepper/pipelines/configuration/processors/dissect.md @@ -1,13 +1,13 @@ --- layout: default -title: dissect +title: Dissect parent: Processors grand_parent: Pipelines -nav_order: 52 +nav_order: 120 --- -# dissect - +# Dissect processor + The `dissect` processor extracts values from an event and maps them to individual fields based on user-defined `dissect` patterns. The processor is well suited for field extraction from log messages with a known structure. ## Basic usage @@ -28,10 +28,11 @@ dissect-pipeline: sink: - stdout: ``` +{% include copy.html %} Then create the following file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with the path of a file containing the following JSON data: -``` +```json {"log": "07-25-2023 10:00:00 ERROR: error message"} ``` @@ -39,7 +40,7 @@ The `dissect` processor will retrieve the fields (`Date`, `Time`, `Log_Type`, an After running the pipeline, you should receive the following standard output: -``` +```json { "log" : "07-25-2023 10:00:00 ERROR: Some error", "Date" : "07-25-2023" @@ -57,6 +58,7 @@ You can configure the `dissect` processor with the following options. | :--- | :--- | :--- | :--- | | `map` | Yes | Map | Defines the `dissect` patterns for specific keys. For details on how to define fields in the `dissect` pattern, see [Field notations](#field-notations). | | `target_types` | No | Map | Specifies the data types for extract fields. Valid options are `integer`, `double`, `string`, and `boolean`. By default, all fields are of the `string` type. | +| `delete_source` | No | Boolean | Whether to delete the source field after successful parsing. Default is `false`. | | `dissect_when` | No | String | Specifies a condition for performing the `dissect` operation using a [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). If specified, the `dissect` operation will only run when the expression evaluates to true. | ### Field notations diff --git a/_data-prepper/pipelines/configuration/processors/drop-events.md b/_data-prepper/pipelines/configuration/processors/drop-events.md index d030f14a..5bf55bea 100644 --- a/_data-prepper/pipelines/configuration/processors/drop-events.md +++ b/_data-prepper/pipelines/configuration/processors/drop-events.md @@ -1,21 +1,303 @@ --- layout: default -title: drop_events +title: Drop events parent: Processors grand_parent: Pipelines -nav_order: 53 +nav_order: 130 --- -# drop_events - +# Drop events processor The `drop_events` processor drops all the events that are passed into it. The following table describes when events are dropped and how exceptions for dropping events are handled. Option | Required | Type | Description :--- | :--- | :--- | :--- -drop_when | Yes | String | Accepts a Data Prepper expression string following the [Data Prepper Expression Syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). Configuring `drop_events` with `drop_when: true` drops all the events received. -handle_failed_events | No | Enum | Specifies how exceptions are handled when an exception occurs while evaluating an event. Default value is `drop`, which drops the event so that it is not sent to OpenSearch. Available options are `drop`, `drop_silently`, `skip`, and `skip_silently`. For more information, see [handle_failed_events](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/drop-events-processor#handle_failed_events). +`drop_when` | Yes | String | Accepts an OpenSearch Data Prepper expression string following the [expression syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). Configuring `drop_events` with `drop_when: true` drops all the events received. +`handle_failed_events` | No | Enum | Specifies how exceptions are handled when an exception occurs while evaluating an event. Default is `drop`, which drops the event so that it is not sent to any sinks or further processors. Valid values are: <br> - `drop`: The event will be dropped and a warning will be logged.<br> - `drop_silently`: The event will be dropped without warning. <br> - `skip`: The event will not be dropped and a warning will be logged. <br> - `skip_silently`: The event will not be dropped and no warning will be logged.<br>For more information, see [handle_failed_events](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/drop-events-processor#handle_failed_events). -<!---## Configuration +## Examples -Content will be added to this section.---> +The following are examples of pipeline configurations using `drop_events` processors. + +The examples don't use security and are for demonstration purposes only. We strongly recommend configuring SSL before using these examples in production. +{: .warning} + +### Filter out debug logs + +The following example configuration demonstrates filtering out `DEBUG` level logs to reduce noise and storage costs while allowing `INFO`, `WARN`, and `ERROR` events: + +```yaml +filter-debug-logs-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - drop_events: + drop_when: '/level == "DEBUG"' + handle_failed_events: drop + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: filtered-logs-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"level": "DEBUG", "message": "Database connection established", "service": "user-service", "timestamp": "2023-10-13T14:30:45Z"}, + {"level": "INFO", "message": "User login successful", "service": "user-service", "timestamp": "2023-10-13T14:31:00Z"}, + {"level": "ERROR", "message": "Database connection failed", "service": "user-service", "timestamp": "2023-10-13T14:32:00Z"}, + {"level": "WARN", "message": "Cache miss detected", "service": "user-service", "timestamp": "2023-10-13T14:33:00Z"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "filtered-logs-2025.10.13", + "_id": "1zsA3pkBWoWOQ0uhY3EJ", + "_score": 1, + "_source": { + "level": "INFO", + "message": "User login successful", + "service": "user-service", + "timestamp": "2023-10-13T14:31:00Z" + } + }, + { + "_index": "filtered-logs-2025.10.13", + "_id": "2DsA3pkBWoWOQ0uhY3EJ", + "_score": 1, + "_source": { + "level": "ERROR", + "message": "Database connection failed", + "service": "user-service", + "timestamp": "2023-10-13T14:32:00Z" + } + }, + { + "_index": "filtered-logs-2025.10.13", + "_id": "2TsA3pkBWoWOQ0uhY3EJ", + "_score": 1, + "_source": { + "level": "WARN", + "message": "Cache miss detected", + "service": "user-service", + "timestamp": "2023-10-13T14:33:00Z" + } + } + ] + } +} +``` + +### Multi-condition event filtering + +The following example shows how to drop events based on multiple criteria, such as debug logs, error status codes, and missing user IDs, in order to ensure that only valid and important events reach OpenSearch: + +```yaml +multi-condition-filter-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - drop_events: + drop_when: '/level == "DEBUG" or /status_code >= 400 or /user_id == null' + handle_failed_events: drop_silently + + - date: + from_time_received: true + destination: "@timestamp" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: filtered-events-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"level": "DEBUG", "message": "Cache hit", "status_code": 200, "user_id": "user123", "timestamp": "2023-10-13T14:33:00Z"}, + {"level": "INFO", "message": "Request failed", "status_code": 500, "user_id": "user123", "timestamp": "2023-10-13T14:34:00Z"}, + {"level": "INFO", "message": "Anonymous request", "status_code": 200, "timestamp": "2023-10-13T14:35:00Z"}, + {"level": "INFO", "message": "User request processed", "status_code": 200, "user_id": "user123", "timestamp": "2023-10-13T14:36:00Z"}, + {"level": "INFO", "message": "Another valid request", "status_code": 201, "user_id": "user456", "timestamp": "2023-10-13T14:37:00Z"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "filtered-events-2025.10.13", + "_id": "7DsB3pkBWoWOQ0uhmHH4", + "_score": 1, + "_source": { + "level": "INFO", + "message": "User request processed", + "status_code": 200, + "user_id": "user123", + "timestamp": "2023-10-13T14:36:00Z", + "@timestamp": "2025-10-13T14:37:47.636Z" + } + }, + { + "_index": "filtered-events-2025.10.13", + "_id": "7TsB3pkBWoWOQ0uhmHH4", + "_score": 1, + "_source": { + "level": "INFO", + "message": "Another valid request", + "status_code": 201, + "user_id": "user456", + "timestamp": "2023-10-13T14:37:00Z", + "@timestamp": "2025-10-13T14:37:47.636Z" + } + } + ] + } +} +``` + +### Intelligent data sampling + +The following example demonstrates how to implement sampling strategies that drop high-volume traffic based on request ID patterns and internal IP addresses in order to manage data volume while preserving representative samples: + +```yaml +sampling-pipeline: + source: + http: + path: /events + ssl: false + + processor: + # Sample based on request_id being in specific sets + - drop_events: + drop_when: '/sampling_rate > 0.4 and /request_id not in {1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000}' + handle_failed_events: skip + + - drop_events: + drop_when: '/source_ip =~ "^192.168.*"' + handle_failed_events: skip + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: sampled-events-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"request_id": 12345, "sampling_rate": 0.9, "source_ip": "10.0.0.1", "message": "High volume request - dropped", "timestamp": "2023-10-13T14:37:00Z"}, + {"request_id": 5000, "sampling_rate": 0.9, "source_ip": "10.0.0.1", "message": "High volume request - sampled", "timestamp": "2023-10-13T14:37:30Z"}, + {"request_id": 12346, "sampling_rate": 0.6, "source_ip": "192.168.1.100", "message": "Internal request - dropped", "timestamp": "2023-10-13T14:38:00Z"}, + {"request_id": 12347, "sampling_rate": 0.3, "source_ip": "203.0.113.45", "message": "External request - passed", "timestamp": "2023-10-13T14:39:00Z"}, + {"request_id": 1000, "sampling_rate": 0.9, "source_ip": "10.0.0.2", "message": "Another sampled request", "timestamp": "2023-10-13T14:40:00Z"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "sampled-events-2025.10.13", + "_id": "i2Ej3pkBh3nNS_N9KazV", + "_score": 1, + "_source": { + "request_id": 5000, + "sampling_rate": 0.9, + "source_ip": "10.0.0.1", + "message": "High volume request - sampled", + "timestamp": "2023-10-13T14:37:30Z" + } + }, + { + "_index": "sampled-events-2025.10.13", + "_id": "jGEj3pkBh3nNS_N9KazV", + "_score": 1, + "_source": { + "request_id": 12347, + "sampling_rate": 0.3, + "source_ip": "203.0.113.45", + "message": "External request - passed", + "timestamp": "2023-10-13T14:39:00Z" + } + }, + { + "_index": "sampled-events-2025.10.13", + "_id": "jWEj3pkBh3nNS_N9KazV", + "_score": 1, + "_source": { + "request_id": 1000, + "sampling_rate": 0.9, + "source_ip": "10.0.0.2", + "message": "Another sampled request", + "timestamp": "2023-10-13T14:40:00Z" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/configuration/processors/flatten.md b/_data-prepper/pipelines/configuration/processors/flatten.md new file mode 100644 index 00000000..93e94fa1 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/flatten.md @@ -0,0 +1,310 @@ +--- +layout: default +title: Flatten +parent: Processors +grand_parent: Pipelines +nav_order: 140 +--- + +# Flatten processor + +The `flatten` processor transforms nested objects inside of events into flattened structures. + +## Configuration + +The following table describes configuration options for the `flatten` processor. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The source key on which to perform the operation. If set to an empty string (`""`), then the processor uses the root of the event as the source. +`target` | Yes | String | The target key to put into the flattened fields. If set to an empty string (`""`), then the processor uses the root of the event as the target. +`exclude_keys` | No | List | The keys from the source field that should be excluded from processing. Default is an empty list (`[]`). +`remove_source_keys` | No | Boolean | When `true`, the processor removes all processed fields from the source. Default is `false`. +`remove_list_elements` | No | Boolean | When `true`, the processor removes list indexes from the flattened keys and collects the values of matching keys into lists in the target field. For example, `list[0].name` and `list[1].name` become a single `list[].name` key containing a list of both values. Default is `false`. +`remove_brackets` | No | Boolean | When `true`, the processor also removes the empty brackets (`[]`) that remain in the flattened keys after list indexes are removed. For example, `list[].name` becomes `list.name`. This setting takes effect only when `remove_list_elements` is `true`. Default is `false`. +`flatten_when` | No | String | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"'`, that determines whether the `flatten` processor will be run on the event. Default is `null`, which means that all events will be processed unless otherwise stated. +`flatten_separator` | No | String | The character used to join nested key names into flattened keys. Must be a single character. Default is `.`. +`tags_on_failure` | No | List | A list of tags to add to the event metadata when the event fails to process. + +## Usage + +The following examples show how the `flatten` processor can be used in OpenSearch Data Prepper pipelines. + +### Minimum configuration + +The following example shows only the parameters that are required for using the `flatten` processor, `source` and `target`: + +```yaml +... + processor: + - flatten: + source: "key2" + target: "flattened-key2" +... +``` +{% include copy.html %} + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + } +} +``` + +The `flatten` processor creates a flattened structure under the `flattened-key2` object, as shown in the following output: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "flattened-key2": { + "key3.key4": "val2" + } +} +``` + +### Remove processed fields + +Use the `remove_source_keys` option when flattening all of an event's nested objects. This removes all the event's processed fields, as shown in the following example: + +```yaml +... + processor: + - flatten: + source: "" # empty string represents root of event + target: "" # empty string represents root of event + remove_source_keys: true +... +``` +{% include copy.html %} + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1": [ + { + "list2": [ + { + "name": "name1", + "value": "value1" + }, + { + "name": "name2", + "value": "value2" + } + ] + } + ] +} +``` + + +The `flatten` processor creates a flattened structure in which all processed fields are absent, as shown in the following output: + +```json +{ + "key1": "val1", + "key2.key3.key4": "val2", + "list1[0].list2[0].name": "name1", + "list1[0].list2[0].value": "value1", + "list1[0].list2[1].name": "name2", + "list1[0].list2[1].value": "value2", +} +``` + +### Exclude specific keys from flattening + +Use the `exclude_keys` option to prevent specific keys from being flattened in the output, as shown in the following example, where the `key2` value is excluded: + +```yaml +... + processor: + - flatten: + source: "" # empty string represents root of event + target: "" # empty string represents root of event + remove_source_keys: true + exclude_keys: ["key2"] +... +``` +{% include copy.html %} + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1": [ + { + "list2": [ + { + "name": "name1", + "value": "value1" + }, + { + "name": "name2", + "value": "value2" + } + ] + } + ] +} +``` + +All other nested objects in the input event, excluding the `key2` key, will be flattened, as shown in the following example: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1[0].list2[0].name": "name1", + "list1[0].list2[0].value": "value1", + "list1[0].list2[1].name": "name2", + "list1[0].list2[1].value": "value2", +} +``` + +### Remove list indexes + +Use the `remove_list_elements` option to convert the fields from the source map into lists and put the lists into the target field, as shown in the following example: + +```yaml +... + processor: + - flatten: + source: "" # empty string represents root of event + target: "" # empty string represents root of event + remove_source_keys: true + remove_list_elements: true +... +``` +{% include copy.html %} + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1": [ + { + "list2": [ + { + "name": "name1", + "value": "value1" + }, + { + "name": "name2", + "value": "value2" + } + ] + } + ] +} +``` + +The processor removes all indexes from the output and places them into the source map as a flattened, structured list, as shown in the following example: + +```json +{ + "key1": "val1", + "key2.key3.key4": "val2", + "list1[].list2[].name": ["name1","name2"], + "list1[].list2[].value": ["value1","value2"] +} +``` + +If you also set `remove_brackets` to `true`, the processor removes the empty brackets from the keys, as shown in the following output: + +```json +{ + "key1": "val1", + "key2.key3.key4": "val2", + "list1.list2.name": ["name1","name2"], + "list1.list2.value": ["value1","value2"] +} +``` + +### Custom separator + +Use the `flatten_separator` option to specify a custom character for joining nested key names. The default separator is `.`, but you can use any single character, such as `_`, as shown in the following example: + +```yaml +... + processor: + - flatten: + source: "log" + target: "" + flatten_separator: "_" + remove_source_keys: true +... +``` +{% include copy.html %} + +Consider an input event that contains the following nested objects: + +```json +{ + "timestamp": "2026-07-29T12:00:00Z", + "service": "user-service", + "log": { + "request": { + "method": "POST", + "url": "/api/v1/users", + "headers": { + "content_type": "application/json" + } + }, + "response": { + "status": 200, + "body": { + "user_id": "usr_12345" + } + } + } +} +``` + +The `flatten` processor flattens the `log` field using `_` as the separator and places the results at the root of the event. Because `remove_source_keys` is `true`, the processed nested fields are removed, leaving an empty `log` object, as shown in the following output: + +```json +{ + "timestamp": "2026-07-29T12:00:00Z", + "service": "user-service", + "log": {}, + "request_method": "POST", + "request_url": "/api/v1/users", + "request_headers_content_type": "application/json", + "response_status": 200, + "response_body_user_id": "usr_12345" +} +``` diff --git a/_data-prepper/pipelines/configuration/processors/geoip.md b/_data-prepper/pipelines/configuration/processors/geoip.md new file mode 100644 index 00000000..367dace0 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/geoip.md @@ -0,0 +1,72 @@ +--- +layout: default +title: Geo IP +parent: Processors +grand_parent: Pipelines +nav_order: 150 +--- + +# Geo IP processor + +The `geoip` processor enriches events with geographic information extracted from IP addresses contained in the events. +By default, OpenSearch Data Prepper uses the [MaxMind GeoLite2](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) geolocation database. +Data Prepper administrators can configure the databases using the [`geoip_service`]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/extensions/geoip-service/) extension configuration. + +## Usage + +You can configure the `geoip` processor to work on entries. + +The minimal configuration requires at least one entry, and each entry at least one source field. + +The following configuration extracts all available geolocation data from the IP address provided in the field named `clientip`. +It will write the geolocation data to a new field named `geo`, the default source when none is configured: + +```yaml +my-pipeline: + processor: + - geoip: + entries: + - source: clientip +``` +{% include copy.html %} + +The following example excludes Autonomous System Number (ASN) fields and puts the geolocation data into a field named `clientlocation`: + +```yaml +my-pipeline: + processor: + - geoip: + entries: + - source: clientip + target: clientlocation + include_fields: [asn, asn_organization, network] +``` +{% include copy.html %} + + +## Configuration + +You can use the following options to configure the `geoip` processor. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`entries` | Yes | [entry](#entry) list | The list of entries marked for enrichment. +`geoip_when` | No | String | Specifies under what condition the `geoip` processor should perform matching. Default is no condition. +`lookup_private_addresses` | No | Boolean | When `true`, the processor also looks up private and loopback IP addresses, such as `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, and `127.0.0.0/8`, in the configured databases. Use this setting with a custom database that contains locations for your internal IP ranges. When `false`, the processor treats these addresses as not valid and adds the `tags_on_no_valid_ip` tags. Default is `false`. +`tags_on_no_valid_ip` | No | List | The tags to add to the event metadata if the source field is not a valid IP address. Unless `lookup_private_addresses` is `true`, this includes private and loopback IP addresses. +`tags_on_ip_not_found` | No | List | The tags to add to the event metadata if the `geoip` processor is unable to find a location for the IP address. +`tags_on_engine_failure` | No | List | The tags to add to the event metadata if the `geoip` processor is unable to enrich an event due to an engine failure. + +<!-- vale off --> +## entry +<!-- vale on --> + +The following parameters allow you to configure a single geolocation entry. Each entry corresponds to a single IP address. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The key of the source field containing the IP address to geolocate. +`target` | No | String | The key of the target field in which to save the geolocation data. Default is `geo`. +`include_fields` | No | String list | The list of geolocation fields to include in the `target` object. By default, this is all the fields provided by the configured databases. +`exclude_fields` | No | String list | The list of geolocation fields to exclude from the `target` object. + diff --git a/_data-prepper/pipelines/configuration/processors/grok.md b/_data-prepper/pipelines/configuration/processors/grok.md index d1eea278..0e7d35a3 100644 --- a/_data-prepper/pipelines/configuration/processors/grok.md +++ b/_data-prepper/pipelines/configuration/processors/grok.md @@ -3,10 +3,10 @@ layout: default title: Grok parent: Processors grand_parent: Pipelines -nav_order: 54 +nav_order: 160 --- -# Grok +# Grok processor The Grok processor uses pattern matching to structure and extract important keys from unstructured data. @@ -14,39 +14,451 @@ The Grok processor uses pattern matching to structure and extract important keys The following table describes options you can use with the Grok processor to structure your data and make your data easier to query. +<!-- +This table is autogenerated. Do not edit it. +- name: grok +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/grok-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/grok/GrokProcessorConfig.java +--> + Option | Required | Type | Description -:--- | :--- | :--- | :--- -break_on_match | No | Boolean | Specifies whether to match all patterns or stop once the first successful match is found. Default value is `true`. -grok_when | No | String | Specifies under what condition the `Grok` processor should perform matching. Default is no condition. -keep_empty_captures | No | Boolean | Enables the preservation of `null` captures. Default value is `false`. -keys_to_overwrite | No | List | Specifies which existing keys will be overwritten if there is a capture with the same key value. Default value is `[]`. -match | No | Map | Specifies which keys to match specific patterns against. Default value is an empty body. -named_captures_only | No | Boolean | Specifies whether to keep only named captures. Default value is `true`. -pattern_definitions | No | Map | Allows for custom pattern use inline. Default value is an empty body. -patterns_directories | No | List | Specifies the path of directories that contain customer pattern files. Default value is an empty list. -pattern_files_glob | No | String | Specifies which pattern files to use from the directories specified for `pattern_directories`. Default value is `*`. -target_key | No | String | Specifies a parent-level key used to store all captures. Default value is `null`. -timeout_millis | No | Integer | The maximum amount of time during which matching occurs. Setting to `0` disables the timeout. Default value is `30,000`. +:--- | :--- |:--- | :--- +`break_on_match` | No | Boolean | Specifies whether to stop once the first successful match is found (`true`) or match all patterns (`false`). Default is `true`. +`grok_when` | No | String | Specifies under what condition the `grok` processor should perform matching. For information about this expression, see [Expression syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). Default is no condition. +`keep_empty_captures` | No | Boolean | Enables the preservation of `null` captures from the processed output. Default is `false`. +`keys_to_overwrite` | No | List | Specifies which existing keys will be overwritten if there is a capture with the same key value. Default is `[]`. +`match` | No | Map | Specifies which keys should match specific patterns. Default is an empty response body. +`named_captures_only` | No | Boolean | Specifies whether to keep only named captures. Default is `true`. +`pattern_definitions` | No | Map | Allows for a custom pattern that can be used inline inside the response body. Default is an empty response body. +`patterns_directories` | No | List | Specifies which directory paths contain the custom pattern files. Default is an empty list. +`patterns_files_glob` | No | String | Specifies which pattern files to use from the directories specified for `patterns_directories`. Default is `*`. +`target_key` | No | String | Specifies a parent-level key used to store all captures. Default value is `null`. +`timeout_millis` | No | Integer | The maximum amount of time, in milliseconds, during which matching occurs. Setting to `0` disables the timeout. Default is `30,000`. +`tags_on_match_failure` | No | List | A list of tags to add to the event metadata when the event does not match any pattern or an exception occurs during matching. +`tags_on_timeout` | No | List | A list of tags to add to the event metadata when matching exceeds `timeout_millis`. If not specified, the `tags_on_match_failure` tags are added when matching times out. +`performance_metadata` | No | Boolean | Whether or not to add the performance metadata to events. Default is `false`. For more information, see [Grok performance metadata](#grok-performance-metadata). -<!---## Configuration +## Grok performance metadata -Content will be added to this section.---> +When the `performance_metadata` option is set to `true`, the `grok` processor adds the following metadata keys to each event: -## Conditional grok +* `_total_grok_processing_time`: The total amount of time, in milliseconds, that the `grok` processor takes to match the event. This is the sum of the processing time based on all of the `grok` processors that ran on the event and have the `performance_metadata` option enabled. +* `_total_grok_patterns_attempted`: The total number of `grok` pattern match attempts across all `grok` processors that ran on the event. -The Grok processor can be configured to run conditionally by using the `grok_when` option. The following is an example Grok processor configuration that uses `grok_when`: -``` -processor: - - grok: - grok_when: '/type == "ipv4"' +To include Grok performance metadata when the event is sent to the sink inside the pipeline, use the `add_entries` processor to describe the metadata you want to include, as shown in the following example: + + +```yaml + processor: + - grok: + performance_metadata: true match: - message: ['%{IPV4:clientip} %{WORD:request} %{POSINT:bytes}'] - - grok: - grok_when: '/type == "ipv6"' + log: ["%{COMMONAPACHELOG}"] + break_on_match: true + named_captures_only: true + target_key: "parsed" + + - add_entries: + entries: + - add_when: 'getMetadata("_total_grok_patterns_attempted") != null' + key: "grok_patterns_attempted" + value_expression: 'getMetadata("_total_grok_patterns_attempted")' + - add_when: 'getMetadata("_total_grok_processing_time") != null' + key: "grok_time_spent" + value_expression: 'getMetadata("_total_grok_processing_time")' +``` + +## Example + +The following examples demonstrate different ways in which the `grok` processor can be configured. + +The examples don't use security and are for demonstration purposes only. We strongly recommend configuring SSL before using these examples in production. +{: .warning} + +### Parse Apache access logs + +This example demonstrates parsing standard Apache HTTP access logs to extract client IP, timestamp, HTTP method, URL, status code, and response size: + +```yaml +apache-access-logs-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + - grok: match: - message: ['%{IPV6:clientip} %{WORD:request} %{POSINT:bytes}'] + message: ['%{COMBINEDAPACHELOG}'] + break_on_match: true + named_captures_only: true + keep_empty_captures: false + target_key: "parsed" + + - date: + match: + - key: "/parsed/timestamp" # JSON Pointer ✔ + patterns: ["dd/MMM/yyyy:HH:mm:ss Z"] + destination: "@timestamp" + source_timezone: "UTC" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: "apache-logs-%{yyyy.MM.dd}" +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\""}, + {"message":"192.168.1.5 - - [13/Oct/2025:17:42:10 +0000] \"POST /login HTTP/1.1\" 302 512 \"-\" \"curl/8.5.0\""} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "apache-logs-2025.10.13", + "_id": "gLO73pkBpMIC6s6zUMMX", + "_score": 1, + "_source": { + "message": "127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache.gif HTTP/1.0\" 200 2326 \"http://www.example.com/start.html\" \"Mozilla/4.08 [en] (Win98; I ;Nav)\"", + "parsed": { + "request": "/apache.gif", + "referrer": "http://www.example.com/start.html", + "agent": "Mozilla/4.08 [en] (Win98; I ;Nav)", + "auth": "frank", + "ident": "-", + "response": "200", + "bytes": "2326", + "clientip": "127.0.0.1", + "verb": "GET", + "httpversion": "1.0", + "timestamp": "10/Oct/2000:13:55:36 -0700" + }, + "@timestamp": "2000-10-10T20:55:36.000Z" + } + }, + { + "_index": "apache-logs-2025.10.13", + "_id": "gbO73pkBpMIC6s6zUMMX", + "_score": 1, + "_source": { + "message": "192.168.1.5 - - [13/Oct/2025:17:42:10 +0000] \"POST /login HTTP/1.1\" 302 512 \"-\" \"curl/8.5.0\"", + "parsed": { + "request": "/login", + "referrer": "-", + "agent": "curl/8.5.0", + "auth": "-", + "ident": "-", + "response": "302", + "bytes": "512", + "clientip": "192.168.1.5", + "verb": "POST", + "httpversion": "1.1", + "timestamp": "13/Oct/2025:17:42:10 +0000" + }, + "@timestamp": "2025-10-13T17:42:10.000Z" + } + } + ] + } +} +``` + +### Parse application logs with custom patterns + +This example demonstrates parsing custom application logs with user-defined patterns for extracting structured data from proprietary log formats: + +```yaml +application-logs-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + - grok: + match: + message: ['%{TIMESTAMP_ISO8601:timestamp} \\[%{LOGLEVEL:level}\\] %{DATA:component} - %{GREEDYDATA:details}'] + pattern_definitions: + LOGLEVEL: (?:INFO|WARN|ERROR|DEBUG|TRACE) + break_on_match: true + target_key: "parsed" + keep_empty_captures: false + + - date: + match: + - key: "/parsed/timestamp" + patterns: + - "yyyy-MM-dd HH:mm:ss" + - "yyyy-MM-dd HH:mm:ss.SSS" + destination: "@timestamp" # you could also use "/@timestamp" + source_timezone: "UTC" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: "application-logs-%{yyyy.MM.dd}" +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + {"message": "2025-10-13 14:30:45 [INFO] UserService - User login successful"}, + {"message": "2025-10-13 14:31:15 [ERROR] DatabaseConnection - Connection timeout"}, + {"message": "2025-10-13 14:32:30 [DEBUG] CacheManager - Cache hit"}, + {"message": "2025-10-13 14:33:05 [WARN] MetricsCollector - High memory usage detected"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "application-logs-2025.10.13", + "_id": "i7O83pkBpMIC6s6zhsNK", + "_score": 1, + "_source": { + "message": "2025-10-13 14:30:45 [INFO] UserService - User login successful", + "parsed": { + "component": "UserService", + "level": "INFO", + "details": "User login successful", + "timestamp": "2025-10-13 14:30:45" + }, + "@timestamp": "2025-10-13T14:30:45.000Z" + } + }, + { + "_index": "application-logs-2025.10.13", + "_id": "jLO83pkBpMIC6s6zhsNK", + "_score": 1, + "_source": { + "message": "2025-10-13 14:31:15 [ERROR] DatabaseConnection - Connection timeout", + "parsed": { + "component": "DatabaseConnection", + "level": "ERROR", + "details": "Connection timeout", + "timestamp": "2025-10-13 14:31:15" + }, + "@timestamp": "2025-10-13T14:31:15.000Z" + } + }, + { + "_index": "application-logs-2025.10.13", + "_id": "jbO83pkBpMIC6s6zhsNK", + "_score": 1, + "_source": { + "message": "2025-10-13 14:32:30 [DEBUG] CacheManager - Cache hit", + "parsed": { + "component": "CacheManager", + "level": "DEBUG", + "details": "Cache hit", + "timestamp": "2025-10-13 14:32:30" + }, + "@timestamp": "2025-10-13T14:32:30.000Z" + } + }, + { + "_index": "application-logs-2025.10.13", + "_id": "jrO83pkBpMIC6s6zhsNK", + "_score": 1, + "_source": { + "message": "2025-10-13 14:33:05 [WARN] MetricsCollector - High memory usage detected", + "parsed": { + "component": "MetricsCollector", + "level": "WARN", + "details": "High memory usage detected", + "timestamp": "2025-10-13 14:33:05" + }, + "@timestamp": "2025-10-13T14:33:05.000Z" + } + } + ] + } +} +``` + +### Parse network device logs with multiple patterns + +This example demonstrates using multiple `grok` patterns to handle different log formats from network devices, with conditional processing based on log type: + +```yaml +network-device-logs-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + - grok: + match: + message: [ + # syslog-like + '%{SYSLOGTIMESTAMP:timestamp} %{SYSLOGHOST:host} %{DATA:program}(?:\\[%{POSINT:pid}\\])?: %{GREEDYDATA:message}', + # ISO8601 + IP + '%{TIMESTAMP_ISO8601:timestamp} %{IP:host} %{DATA:program}: %{GREEDYDATA:message}', + # Cisco style + '%{CISCO_TIMESTAMP:timestamp}: %{DATA:facility}-%{INT:severity}-%{DATA:mnemonic}: %{GREEDYDATA:message}' + ] + break_on_match: true + named_captures_only: true + pattern_definitions: + CISCO_TIMESTAMP: '%{MONTH} %{MONTHDAY} %{TIME}' + target_key: "parsed" + timeout_millis: 5000 + + # Extract login info from the parsed message text + - grok: + match: + /parsed/message: ['User %{USERNAME:user} logged in from %{IP:source_ip}'] + break_on_match: true + target_key: "login_info" + + - date: + match: + - key: "/parsed/timestamp" + patterns: + # syslog-like (no year) + - "MMM d HH:mm:ss" + # ISO8601 without/with millis & TZ + - "yyyy-MM-dd'T'HH:mm:ssXXX" + - "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + destination: "@timestamp" + source_timezone: "UTC" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: "network-logs-%{yyyy.MM.dd}" +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"Oct 13 14:30:45 router1 sshd[1234]: User alice logged in from 10.0.0.5"}, + {"message":"2025-10-13T16:01:22Z 192.168.0.10 dhcpd: Lease granted to 192.168.0.55"}, + {"message":"Oct 13 16:30:45: LOCAL4-3-LINK_UPDOWN: Interface Gi0/1 changed state to up"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "network-logs-2025.10.13", + "_id": "-kzC3pkBl88jNjkRQ1TJ", + "_score": 1, + "_source": { + "message": "Oct 13 14:30:45 router1 sshd[1234]: User alice logged in from 10.0.0.5", + "parsed": { + "host": "router1", + "pid": "1234", + "program": "sshd", + "message": "User alice logged in from 10.0.0.5", + "timestamp": "Oct 13 14:30:45" + }, + "login_info": { + "user": "alice", + "source_ip": "10.0.0.5" + }, + "@timestamp": "2025-10-13T14:30:45.000Z" + } + }, + { + "_index": "network-logs-2025.10.13", + "_id": "-0zC3pkBl88jNjkRQ1TJ", + "_score": 1, + "_source": { + "message": "2025-10-13T16:01:22Z 192.168.0.10 dhcpd: Lease granted to 192.168.0.55", + "parsed": { + "host": "192.168.0.10", + "program": "dhcpd", + "message": "Lease granted to 192.168.0.55", + "timestamp": "2025-10-13T16:01:22Z" + }, + "login_info": {}, + "@timestamp": "2025-10-13T16:01:22.000Z" + } + }, + { + "_index": "network-logs-2025.10.13", + "_id": "_EzC3pkBl88jNjkRQ1TJ", + "_score": 1, + "_source": { + "message": "Oct 13 16:30:45: LOCAL4-3-LINK_UPDOWN: Interface Gi0/1 changed state to up", + "parsed": { + "severity": "3", + "mnemonic": "LINK_UPDOWN", + "message": "Interface Gi0/1 changed state to up", + "facility": "LOCAL4", + "timestamp": "Oct 13 16:30:45" + }, + "login_info": {}, + "@timestamp": "2025-10-13T16:30:45.000Z" + } + } + ] + } +} ``` -The `grok_when` option can take a conditional expression. This expression is detailed in the [Expression syntax](https://opensearch.org/docs/latest/data-prepper/pipelines/expression-syntax/) documentation. ## Metrics @@ -69,4 +481,4 @@ The Grok processor includes the following custom metrics. ### Timer -* `grokProcessingTime`: The time taken by individual records to match against `match` patterns. The `avg` metric is the most useful metric for this timer because because it provides the average time taken to match records. +* `grokProcessingTime`: The time taken by individual records to match against `match` patterns. The `avg` metric is the most useful metric for this timer because it provides the average time taken to match records. diff --git a/_data-prepper/pipelines/configuration/processors/key-value.md b/_data-prepper/pipelines/configuration/processors/key-value.md index 884ae975..d41dc322 100644 --- a/_data-prepper/pipelines/configuration/processors/key-value.md +++ b/_data-prepper/pipelines/configuration/processors/key-value.md @@ -1,45 +1,383 @@ --- layout: default -title: key_value +title: Key-value parent: Processors grand_parent: Pipelines -nav_order: 56 +nav_order: 170 --- -# key_value +# Key-value processor You can use the `key_value` processor to parse the specified field into key-value pairs. You can customize the `key_value` processor to parse field information with the following options. The type for each of the following options is `string`. -| Option | Description | Example | -| :--- | :--- | :--- | -| source | The message field to be parsed. Optional. Default value is `message`. | If `source` is `"message1"`, `{"message1": {"key1=value1"}, "message2": {"key2=value2"}}` parses into `{"message1": {"key1=value1"}, "message2": {"key2=value2"}, "parsed_message": {"key1": "value1"}}`. | -| destination | The destination field for the parsed source. The parsed source overwrites the preexisting data for that key. Optional. If `destination` is set to `null`, the parsed fields will be written to the root of the event. Default value is `parsed_message`. | If `destination` is `"parsed_data"`, `{"message": {"key1=value1"}}` parses into `{"message": {"key1=value1"}, "parsed_data": {"key1": "value1"}}`. | -| field_delimiter_regex | A regular expression specifying the delimiter that separates key-value pairs. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be defined at the same time as `field_split_characters`. Optional. If this option is not defined, `field_split_characters` is used. | If `field_delimiter_regex` is `"&\\{2\\}"`, `{"key1=value1&&key2=value2"}` parses into `{"key1": "value1", "key2": "value2"}`. | -| field_split_characters | A string of characters specifying the delimeter that separates key-value pairs. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be defined at the same time as `field_delimiter_regex`. Optional. Default value is `&`. | If `field_split_characters` is `"&&"`, `{"key1=value1&&key2=value2"}` parses into `{"key1": "value1", "key2": "value2"}`. | -| key_value_delimiter_regex | A regular expression specifying the delimiter that separates the key and value within a key-value pair. Special regular expression characters such as `[` and `]` must be escaped with `\\`. This option cannot be defined at the same time as `value_split_characters`. Optional. If this option is not defined, `value_split_characters` is used. | If `key_value_delimiter_regex` is `"=\\{2\\}"`, `{"key1==value1"}` parses into `{"key1": "value1"}`. | -| value_split_characters | A string of characters specifying the delimiter that separates the key and value within a key-value pair. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be defined at the same time as `key_value_delimiter_regex`. Optional. Default value is `=`. | If `value_split_characters` is `"=="`, `{"key1==value1"}` parses into `{"key1": "value1"}`. | -| non_match_value | When a key-value pair cannot be successfully split, the key-value pair is placed in the `key` field, and the specified value is placed in the `value` field. Optional. Default value is `null`. | `key1value1&key2=value2` parses into `{"key1value1": null, "key2": "value2"}`. | -| prefix | A prefix to append before all keys. Optional. Default value is an empty string. | If `prefix` is `"custom"`, `{"key1=value1"}` parses into `{"customkey1": "value1"}`.| -| delete_key_regex | A regular expression specifying the characters to delete from the key. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be an empty string. Optional. No default value. | If `delete_key_regex` is `"\s"`, `{"key1 =value1"}` parses into `{"key1": "value1"}`. | -| delete_value_regex | A regular expression specifying the characters to delete from the value. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be an empty string. Optional. No default value. | If `delete_value_regex` is `"\s"`, `{"key1=value1 "}` parses into `{"key1": "value1"}`. | -| include_keys | An array specifying the keys that should be added for parsing. By default, all keys will be added. | If `include_keys` is `["key2"]`,`key1=value1&key2=value2` will parse into `{"key2": "value2"}`. | -| exclude_keys | An array specifying the parsed keys that should not be added to the event. By default, no keys will be excluded. | If `exclude_keys` is `["key2"]`, `key1=value1&key2=value2` will parse into `{"key1": "value1"}`. | -| default_values | A map specifying the default keys and their values that should be added to the event in case these keys do not exist in the source field being parsed. If the default key already exists in the message, the value is not changed. The `include_keys` filter will be applied to the message before `default_values`. | If `default_values` is `{"defaultkey": "defaultvalue"}`, `key1=value1` will parse into `{"key1": "value1", "defaultkey": "defaultvalue"}`. <br /> If `default_values` is `{"key1": "abc"}`, `key1=value1` will parse into `{"key1": "value1"}`. <br /> If `include_keys` is `["key1"]` and `default_values` is `{"key2": "value2"}`, `key1=value1&key2=abc` will parse into `{"key1": "value1", "key2": "value2"}`. | -| transform_key | When to lowercase, uppercase, or capitalize keys. | If `transform_key` is `lowercase`, `{"Key1=value1"}` will parse into `{"key1": "value1"}`. <br /> If `transform_key` is `uppercase`, `{"key1=value1"}` will parse into `{"KEY1": "value1"}`. <br /> If `transform_key` is `capitalize`, `{"key1=value1"}` will parse into `{"Key1": "value1"}`. | -| whitespace | Specifies whether to be lenient or strict with the acceptance of unnecessary white space surrounding the configured value-split sequence. Default is `lenient`. | If `whitespace` is `"lenient"`, `{"key1 = value1"}` will parse into `{"key1 ": " value1"}`. If `whitespace` is `"strict"`, `{"key1 = value1"}` will parse into `{"key1": "value1"}`. | -| skip_duplicate_values | A Boolean option for removing duplicate key-value pairs. When set to `true`, only one unique key-value pair will be preserved. Default is `false`. | If `skip_duplicate_values` is `false`, `{"key1=value1&key1=value1"}` will parse into `{"key1": ["value1", "value1"]}`. If `skip_duplicate_values` is `true`, `{"key1=value1&key1=value1"}` will parse into `{"key1": "value1"}`. | -| remove_brackets | Specifies whether to treat square brackets, angle brackets, and parentheses as value "wrappers" that should be removed from the value. Default is `false`. | If `remove_brackets` is `true`, `{"key1=(value1)"}` will parse into `{"key1": value1}`. If `remove_brackets` is `false`, `{"key1=(value1)"}` will parse into `{"key1": "(value1)"}`. | -| recursive | Specifies whether to recursively obtain additional key-value pairs from values. The extra key-value pairs will be stored as sub-keys of the root key. Default is `false`. The levels of recursive parsing must be defined by different brackets for each level: `[]`, `()`, and `<>`, in this order. Any other configurations specified will only be applied to the outmost keys. <br />When `recursive` is `true`: <br /> `remove_brackets` cannot also be `true`;<br />`skip_duplicate_values` will always be `true`; <br />`whitespace` will always be `"strict"`. | If `recursive` is true, `{"item1=[item1-subitem1=item1-subitem1-value&item1-subitem2=(item1-subitem2-subitem2A=item1-subitem2-subitem2A-value&item1-subitem2-subitem2B=item1-subitem2-subitem2B-value)]&item2=item2-value"}` will parse into `{"item1": {"item1-subitem1": "item1-subitem1-value", "item1-subitem2" {"item1-subitem2-subitem2A": "item1-subitem2-subitem2A-value", "item1-subitem2-subitem2B": "item1-subitem2-subitem2B-value"}}}`. | -| overwrite_if_destination_exists | Specifies whether to overwrite existing fields if there are key conflicts when writing parsed fields to the event. Default is `true`. | If `overwrite_if_destination_exists` is `true` and destination is `null`, `{"key1": "old_value", "message": "key1=new_value"}` will parse into `{"key1": "new_value", "message": "key1=new_value"}`. | -| tags_on_failure | When a `kv` operation causes a runtime exception within the processor, the operation is safely stopped without crashing the processor, and the event is tagged with the provided tags. | If `tags_on_failure` is set to `["keyvalueprocessor_failure"]`, `{"tags": ["keyvalueprocessor_failure"]}` will be added to the event's metadata in the event of a runtime exception. | +## Examples + +The following examples demonstrate several configurations you can use with this processor. + +The examples don't use security and are for demonstration purposes only. We strongly recommend configuring SSL before using these examples in production. +{: .warning} + +### Key-value parsing, normalization, and deduplication + +The following example parses the `message` field into `key=value` pairs, normalizes and cleans the keys, prefixes them with `meta_`, deduplicates values, and drops keys without values into `parsed_kv`: + +```yaml +kv-basic-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + - key_value: + # Read key=value pairs from the "message" field (default anyway) + source: message + # Write parsed pairs into a nested object "parsed_kv" + destination: parsed_kv + + # Split pairs on '&' and split key vs value on '=' + field_split_characters: "&" + value_split_characters: "=" + + # Normalize keys and trim garbage whitespace around keys/values + transform_key: lowercase + delete_key_regex: "\\s+" # remove spaces from keys + delete_value_regex: "^\\s+|\\s+$" # trim leading/trailing spaces + + # Add a prefix to every key (after normalization + delete_key_regex) + prefix: meta_ + + # Keep a single unique value for duplicate keys + skip_duplicate_values: true + + # Drop keys whose value is empty/absent (e.g., `empty=` or `novalue`) + drop_keys_with_no_value: true + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: kv-basic-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"key1=value1&key1=value1&Key Two = value two & empty=&novalue"}, + {"message":"ENV = prod & TEAM = core & owner = alice "} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "kv-basic-2025.10.14", + "_id": "M6d84pkB3P3jd6EROH_f", + "_score": 1, + "_source": { + "message": "key1=value1&key1=value1&Key Two = value two & empty=&novalue", + "parsed_kv": { + "meta_key1": "value1", + "meta_empty": "", + "meta_keytwo": "value two" + } + } + }, + { + "_index": "kv-basic-2025.10.14", + "_id": "NKd84pkB3P3jd6EROH_f", + "_score": 1, + "_source": { + "message": "ENV = prod & TEAM = core & owner = alice ", + "parsed_kv": { + "meta_owner": "alice", + "meta_team": "core", + "meta_env": "prod" + } + } + } + ] + } +} +``` + +### Grouped values to root + +The following example parses the `payload` field by using `&&` to separate pairs and `==` to separate keys and values. It preserves bracketed groups as single values, writes the parsed results to the event root without overwriting existing fields, and records any unmatched tokens as `null`: + +```yaml +kv-grouping-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + - key_value: + source: "payload" + destination: null + + field_split_characters: "&&" # pair delimiter (OK with grouping) + value_split_characters: null # disable the default "=" + key_value_delimiter_regex: "==" # exact '==' for key/value + + value_grouping: true + remove_brackets: false + destination_conflict_strategy: skip + non_match_value: null + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: "kv-regex-%{yyyy.MM.dd}" +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + { + "payload":"a==1&&b==[x=y,z=w]&&c==(inner=thing)&&http==http://example.com path", + "a":"keep-me" + }, + { + "payload":"good==yes&&broken-token&&url==https://opensearch.org home", + "note":"second doc" + } + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "kv-regex-2025.10.14", + "_id": "FuCX4pkB344hN2Iu62oT", + "_score": 1, + "_source": { + "payload": "a==1&&b==[x=y,z=w]&&c==(inner=thing)&&http==http://example.com path", + "a": "keep-me", + "b": "[x=y,z=w]", + "c": "(inner=thing)", + "http": "http://example.com path" + } + }, + { + "_index": "kv-regex-2025.10.14", + "_id": "F-CX4pkB344hN2Iu62oT", + "_score": 1, + "_source": { + "payload": "good==yes&&broken-token&&url==https://opensearch.org home", + "note": "second doc", + "broken-token": null, + "good": "yes", + "url": "https://opensearch.org home" + } + } + ] + } +} +``` + +### Conditional recursive key-value parsing + +The following example parses bracketed nested `key=value` structures from `body` into `parsed.*` only when `/type == "nested"`. It preserves group hierarchy, enforces strict nesting rules, applies default fields, and leaves non-nested events unchanged: + +```yaml +kv-conditional-recursive-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + - key_value: + source: "body" + destination: "parsed" + + key_value_when: '/type == "nested"' + recursive: true + + # Split rules (per docs; not regex) + field_split_characters: "&" + value_split_characters: "=" + + # Grouping & quoting (per docs) + value_grouping: true + string_literal_character: "\"" + remove_brackets: false + + # Keep only some top-level keys; then set defaults + include_keys: ["item1","item2","owner"] + default_values: + owner: "unknown" + region: "eu-west-1" + + strict_grouping: true + tags_on_failure: ["keyvalueprocessor_failure"] + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: "kv-recursive-%{yyyy.MM.dd}" +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + { + "type":"nested","body":"item1=[a=1&b=(c=3&d=<e=5>)]&item2=2&owner=alice" + }, + { + "type":"flat","body":"item1=[should=not&be=parsed]&item2=42" + }, + { + "type":"nested","body":"item1=[desc=\"a=b + c=d\"&x=1]&item2=2" + } +]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "kv-recursive-2025.10.14", + "_id": "Q7fC4pkBc0UY8I7pZ6vZ", + "_score": 1, + "_source": { + "type": "nested", + "body": "item1=[a=1&b=(c=3&d=<e=5>)]&item2=2&owner=alice", + "parsed": { + "owner": "alice", + "item2": "2", + "item1": { + "a": "1", + "b": { + "c": "3", + "d": { + "e": "5" + } + } + }, + "region": "eu-west-1" + } + } + }, + { + "_index": "kv-recursive-2025.10.14", + "_id": "RLfC4pkBc0UY8I7pZ6vZ", + "_score": 1, + "_source": { + "type": "flat", + "body": "item1=[should=not&be=parsed]&item2=42" + } + }, + { + "_index": "kv-recursive-2025.10.14", + "_id": "RbfC4pkBc0UY8I7pZ6vZ", + "_score": 1, + "_source": { + "type": "nested", + "body": """item1=[desc="a=b + c=d"&x=1]&item2=2""", + "parsed": { + "owner": "unknown", + "item2": "2", + "item1": { + "desc": "\"a=b + c=d\"", + "x": "1" + }, + "region": "eu-west-1" + } + } + } + ] + } +} +``` + +## Configuration + +Option | Description | Example +:--- | :--- | :--- +`source` | The message field to be parsed. Optional. Default value is `message`. | If `source` is `"message1"`, `{"message1": {"key1=value1"}, "message2": {"key2=value2"}}` parses into `{"message1": {"key1=value1"}, "message2": {"key2=value2"}, "parsed_message": {"key1": "value1"}}`. +`destination` | The destination field for the parsed source. If the field already exists, the parsed source overwrites the preexisting data for that key unless `destination_conflict_strategy` specifies otherwise. Optional. If `destination` is set to `null`, the parsed fields are written to the root of the event. Default value is `parsed_message`. | If `destination` is `"parsed_data"`, `{"message": {"key1=value1"}}` parses into `{"message": {"key1=value1"}, "parsed_data": {"key1": "value1"}}`. +`field_delimiter_regex` | A regular expression specifying the delimiter that separates key-value pairs. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be defined at the same time as `field_split_characters`. Optional. If this option is not defined, `field_split_characters` is used. | If `field_delimiter_regex` is `"&\\{2\\}"`, `{"key1=value1&&key2=value2"}` parses into `{"key1": "value1", "key2": "value2"}`. +`field_split_characters` | A string of characters specifying the delimiter that separates key-value pairs. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be defined at the same time as `field_delimiter_regex`. Optional. Default value is `&`. | If `field_split_characters` is `"&&"`, `{"key1=value1&&key2=value2"}` parses into `{"key1": "value1", "key2": "value2"}`. +`key_value_delimiter_regex` | A regular expression specifying the delimiter that separates the key and value within a key-value pair. Special regular expression characters such as `[` and `]` must be escaped with `\\`. This option cannot be defined at the same time as `value_split_characters`. Optional. If this option is not defined, `value_split_characters` is used. | If `key_value_delimiter_regex` is `"=\\{2\\}"`, `{"key1==value1"}` parses into `{"key1": "value1"}`. +`value_split_characters` | A string of characters specifying the delimiter that separates the key and value within a key-value pair. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be defined at the same time as `key_value_delimiter_regex`. Optional. Default value is `=`. | If `value_split_characters` is `"=="`, `{"key1==value1"}` parses into `{"key1": "value1"}`. +`non_match_value` | When a key-value pair cannot be successfully split, the key-value pair is placed in the `key` field, and the specified value is placed in the `value` field. Optional. Default value is `null`. | `key1value1&key2=value2` parses into `{"key1value1": null, "key2": "value2"}`. | +`prefix` | A prefix to append before all keys. Optional. Default value is an empty string. | If `prefix` is `"custom"`, `{"key1=value1"}` parses into `{"customkey1": "value1"}`. +`delete_key_regex` | A regular expression specifying the characters to delete from the key. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be an empty string. Optional. No default value. | If `delete_key_regex` is `"\s"`, `{"key1 =value1"}` parses into `{"key1": "value1"}`. +`delete_value_regex` | A regular expression specifying the characters to delete from the value. Special regular expression characters such as `[` and `]` must be escaped with `\\`. Cannot be an empty string. Optional. No default value. | If `delete_value_regex` is `"\s"`, `{"key1=value1 "}` parses into `{"key1": "value1"}`. +`include_keys` | An array specifying the keys that should be added for parsing. By default, all keys will be added. | If `include_keys` is `["key2"]`,`key1=value1&key2=value2` will parse into `{"key2": "value2"}`. +`exclude_keys` | An array specifying the parsed keys that should not be added to the event. By default, no keys will be excluded. | If `exclude_keys` is `["key2"]`, `key1=value1&key2=value2` will parse into `{"key1": "value1"}`. +`default_values` | A map specifying the default keys and their values that should be added to the event in case these keys do not exist in the source field being parsed. If the default key already exists in the message, the value is not changed. The `include_keys` filter will be applied to the message before `default_values`. | If `default_values` is `{"defaultkey": "defaultvalue"}`, `key1=value1` will parse into `{"key1": "value1", "defaultkey": "defaultvalue"}`. <br /> If `default_values` is `{"key1": "abc"}`, `key1=value1` will parse into `{"key1": "value1"}`. <br /> If `include_keys` is `["key1"]` and `default_values` is `{"key2": "value2"}`, `key1=value1&key2=abc` will parse into `{"key1": "value1", "key2": "value2"}`. +`transform_key` | When to lowercase, uppercase, or capitalize keys. | If `transform_key` is `lowercase`, `{"Key1=value1"}` will parse into `{"key1": "value1"}`. <br /> If `transform_key` is `uppercase`, `{"key1=value1"}` will parse into `{"KEY1": "value1"}`. <br /> If `transform_key` is `capitalize`, `{"key1=value1"}` will parse into `{"Key1": "value1"}`. +`normalize_keys` | Specifies whether to replace characters that are not valid in event keys with an underscore (`_`) in the parsed keys. Default is `false`. | If `normalize_keys` is `true`, `user:name=alice&order#id=5` parses into `{"user_name": "alice", "order_id": "5"}`. +`whitespace` | Specifies whether to be lenient or strict with the acceptance of unnecessary white space surrounding the configured value-split sequence. Default is `lenient`. | If `whitespace` is `"lenient"`, `{"key1 = value1"}` will parse into `{"key1 ": " value1"}`. If `whitespace` is `"strict"`, `{"key1 = value1"}` will parse into `{"key1": "value1"}`. +`skip_duplicate_values` | A Boolean option for removing duplicate key-value pairs. When set to `true`, only one unique key-value pair will be preserved. Default is `false`. | If `skip_duplicate_values` is `false`, `{"key1=value1&key1=value1"}` will parse into `{"key1": ["value1", "value1"]}`. If `skip_duplicate_values` is `true`, `{"key1=value1&key1=value1"}` will parse into `{"key1": "value1"}`. +`remove_brackets` | Specifies whether to treat square brackets, angle brackets, and parentheses as value "wrappers" that should be removed from the value. Default is `false`. | If `remove_brackets` is `true`, `{"key1=(value1)"}` will parse into `{"key1": value1}`. If `remove_brackets` is `false`, `{"key1=(value1)"}` will parse into `{"key1": "(value1)"}`. +`recursive` | Specifies whether to recursively obtain additional key-value pairs from values. The extra key-value pairs will be stored as sub-keys of the root key. Default is `false`. The levels of recursive parsing must be defined by different brackets for each level: `[]`, `()`, and `<>`, in this order. Any other configurations specified will only be applied to the outmost keys. <br />When `recursive` is `true`: <br /> `remove_brackets` cannot also be `true`;<br />`skip_duplicate_values` will always be `true`; <br />`whitespace` will always be `"strict"`. | If `recursive` is true, `{"item1=[item1-subitem1=item1-subitem1-value&item1-subitem2=(item1-subitem2-subitem2A=item1-subitem2-subitem2A-value&item1-subitem2-subitem2B=item1-subitem2-subitem2B-value)]&item2=item2-value"}` will parse into `{"item1": {"item1-subitem1": "item1-subitem1-value", "item1-subitem2" {"item1-subitem2-subitem2A": "item1-subitem2-subitem2A-value", "item1-subitem2-subitem2B": "item1-subitem2-subitem2B-value"}}}`. +`destination_conflict_strategy` | Specifies how to write the parsed fields when the `destination` field already exists in the event. Valid values are the following:<br />- `skip`: Leaves the existing `destination` field unchanged.<br />- `overwrite`: Replaces the existing `destination` field with the parsed fields.<br />- `merge_preserve_existing_keys`: Adds the parsed fields to the existing `destination` object. If a key exists in both, the existing value is kept.<br />- `merge_overwrite_existing_keys`: Adds the parsed fields to the existing `destination` object. If a key exists in both, the parsed value replaces the existing value.<br />If the existing `destination` field is not an object, `merge_preserve_existing_keys` leaves it unchanged and `merge_overwrite_existing_keys` replaces it. If `destination` is `null`, each parsed field is written to the root of the event: `skip` and `merge_preserve_existing_keys` keep the values of existing fields, and `overwrite` and `merge_overwrite_existing_keys` replace them. Default is `overwrite`. | If `destination_conflict_strategy` is `merge_preserve_existing_keys` and `destination` is `"parsed"`, `{"parsed": {"key1": "old_value"}, "message": "key1=new_value&key2=value2"}` parses into `{"parsed": {"key1": "old_value", "key2": "value2"}, "message": "key1=new_value&key2=value2"}`. <br /> If `destination_conflict_strategy` is `overwrite` and `destination` is `null`, `{"key1": "old_value", "message": "key1=new_value"}` parses into `{"key1": "new_value", "message": "key1=new_value"}`. +`tags_on_failure` | When a `kv` operation causes a runtime exception within the processor, the operation is safely stopped without crashing the processor, and the event is tagged with the provided tags. | If `tags_on_failure` is set to `["keyvalueprocessor_failure"]`, `{"tags": ["keyvalueprocessor_failure"]}` will be added to the event's metadata in the event of a runtime exception. +`value_grouping` | Specifies whether to group values using predefined value grouping delimiters: `{...}`, `[...]', `<...>`, `(...)`, `"..."`, `'...'`, `http://... (space)`, and `https:// (space)`. If this flag is enabled, then the content between the delimiters is considered to be one entity and is not parsed for key-value pairs. Default is `false`. If `value_grouping` is `true`, then `{"key1=[a=b,c=d]&key2=value2"}` parses to `{"key1": "[a=b,c=d]", "key2": "value2"}`. +`drop_keys_with_no_value` | Specifies whether keys should be dropped if they have a null value. Default is `false`. If `drop_keys_with_no_value` is set to `true`, then `{"key1=value1&key2"}` parses to `{"key1": "value1"}`. +`strict_grouping` | Specifies whether strict grouping should be enabled when the `value_grouping` or `string_literal_character` options are used. Default is `false`. | When enabled, groups with unmatched end characters yield errors. The event is ignored after the errors are logged. +`string_literal_character` | Can be set to either a single quotation mark (`'`) or a double quotation mark (`"`). Default is `null`. | When this option is used, any text contained within the specified quotation mark character will be ignored and excluded from key-value parsing. For example, `text1 "key1=value1" text2 key2=value2` would parse to `{"key2": "value2"}`. +`key_value_when` | Allows you to specify a [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"`, that will be evaluated to determine whether the processor should be applied to the event. - -<!--- ## Configuration - -Content will be added to this section. - -## Metrics - -Content will be added to this section. ---> \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/processors/list-to-map.md b/_data-prepper/pipelines/configuration/processors/list-to-map.md index 4b137f5c..0348a961 100644 --- a/_data-prepper/pipelines/configuration/processors/list-to-map.md +++ b/_data-prepper/pipelines/configuration/processors/list-to-map.md @@ -1,12 +1,12 @@ --- layout: default -title: list_to_map +title: List to map parent: Processors grand_parent: Pipelines -nav_order: 58 +nav_order: 180 --- -# list_to_map +# List to map processor The `list_to_map` processor converts a list of objects from an event, where each object contains a `key` field, into a map of target keys. @@ -16,12 +16,16 @@ The following table describes the configuration options used to generate target Option | Required | Type | Description :--- | :--- | :--- | :--- -`key` | Yes | String | The key of the fields to be extracted as keys in the generated mappings. `source` | Yes | String | The list of objects with `key` fields to be converted into keys for the generated map. `target` | No | String | The target for the generated map. When not specified, the generated map will be placed in the root node. +`key` | Conditionally | String | The key of the fields to be extracted as keys in the generated mappings. Must be specified if `use_source_key` is `false`. +`use_source_key` | No | Boolean | When `true`, keys in the generated map will use original keys from the source. Default is `false`. `value_key` | No | String | When specified, values given a `value_key` in objects contained in the source list will be extracted and converted into the value specified by this option based on the generated map. When not specified, objects contained in the source list retain their original value when mapped. +`extract_value` | No | Boolean | When `true`, object values from the source list will be extracted and added to the generated map. When `false`, object values from the source list are added to the generated map as they appear in the source list. Default is `false` `flatten` | No | Boolean | When `true`, values in the generated map output flatten into single items based on the `flattened_element`. Otherwise, objects mapped to values from the generated map appear as lists. -`flattened_element` | Conditionally | String | The element to keep, either `first` or `last`, when `flatten` is set to `true`. +`flattened_element` | Conditionally | String | The element to keep, either `first` or `last`, when `flatten` is set to `true`. Default is `first`. +`list_to_map_when` | No | String | A [`conditional expression`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"`, that is evaluated to determine whether the processor runs on the event. By default, the processor runs on all events. +`tags_on_failure` | No | List | A list of tags to add to the event metadata when the processor fails to convert the list, for example, when the `source` field does not contain a list. ## Usage @@ -302,4 +306,52 @@ Some objects in the response may have more than one element in their values, as "val-c" ] } +``` + +### Example: `use_source_key` and `extract_value` set to `true` + +The following example `pipeline.yaml` file sets `flatten` to `false`, causing the processor to output values from the generated map as a list: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - list_to_map: + source: "mylist" + use_source_key: true + extract_value: true + sink: + - stdout: +``` +{% include copy.html %} + +Object values from `mylist` are extracted and added to fields with the source keys `name` and `value`, as shown in the following response: + +```json +{ + "mylist": [ + { + "name": "a", + "value": "val-a" + }, + { + "name": "b", + "value": "val-b1" + }, + { + "name": "b", + "value": "val-b2" + }, + { + "name": "c", + "value": "val-c" + } + ], + "name": ["a", "b", "b", "c"], + "value": ["val-a", "val-b1", "val-b2", "val-c"] +} ``` \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/processors/lowercase-string.md b/_data-prepper/pipelines/configuration/processors/lowercase-string.md index 34ca0597..2cbd94c5 100644 --- a/_data-prepper/pipelines/configuration/processors/lowercase-string.md +++ b/_data-prepper/pipelines/configuration/processors/lowercase-string.md @@ -1,24 +1,53 @@ --- layout: default -title: lowercase_string +title: Lowercase string parent: Processors grand_parent: Pipelines -nav_order: 60 +nav_order: 190 --- -# lowercase_string +# Lowercase string processor +The `lowercase string` processor converts a string to lowercase. -The `lowercase_string` processor converts a string to its lowercase counterpart and is a [mutate string](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/mutate-string-processors#mutate-string-processors) processor. The following table describes options for configuring the `lowercase_string` processor to convert strings to a lowercase format. +### Configuration -Option | Required | Type | Description -:--- | :--- | :--- | :--- -with_keys | Yes | List | A list of keys to convert to lowercase. +You can configure the `lowercase string` processor with the following options. -<!---## Configuration +Option | Required | Description +:--- | :--- | :--- + `with_keys` | Yes | A list of keys to convert to lowercase. | -Content will be added to this section. +### Usage -## Metrics +To get started, create the following `pipeline.yaml` file: -Content will be added to this section.---> +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - lowercase_string: + with_keys: + - "lowercaseField" + sink: + - stdout: +``` +{% include copy.html %} + +Next, create a log file named `logs_json.log`. After that, replace the `path` in the file source of your `pipeline.yaml` file with the correct file path. For more detailed information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). + +Before you run Data Prepper, the source appears in the following format: + +```json +{"lowercaseField": "TESTmeSSage"} +``` + +After you run Data Prepper, the source is converted to the following format: + +```json +{"lowercaseField": "testmessage"} +``` diff --git a/_data-prepper/pipelines/configuration/processors/map-to-list.md b/_data-prepper/pipelines/configuration/processors/map-to-list.md new file mode 100644 index 00000000..0869ee4f --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/map-to-list.md @@ -0,0 +1,277 @@ +--- +layout: default +title: Map to list +parent: Processors +grand_parent: Pipelines +nav_order: 200 +--- + +# Map to list processor + +The `map_to_list` processor converts a map of key-value pairs to a list of objects. Each object contains the key and value in separate fields. + +## Configuration + +The following table describes the configuration options for the `map_to_list` processor. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The source map used to perform the mapping operation. When set to an empty string (`""`), it will use the root of the event as the `source`. +`target` | Yes | String | The target for the generated list. +`key_name` | No | String | The name of the field in which to store the original key. Default is `key`. +`value_name` | No | String | The name of the field in which to store the original value. Default is `value`. +`exclude_keys` | No | List | The keys in the source map that will be excluded from processing. Default is an empty list (`[]`). +`remove_processed_fields` | No | Boolean | When `true`, the processor will remove the processed fields from the source map. Default is `false`. +`convert_field_to_list` | No | Boolean | If `true`, the processor will convert the fields from the source map into lists and place them in fields in the target list. Default is `false`. +`map_to_list_when` | No | String | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"'`, that will be evaluated to determine whether the processor will be run on the event. Default is `null`. All events will be processed unless otherwise stated. +`tags_on_failure` | No | List | A list of tags to add to the event metadata when the event fails to process. + +## Usage + +The following examples show how the `map_to_list` processor can be used in your pipeline. + +### Example: Minimum configuration + +The following example shows the `map_to_list` processor with only the required parameters, `source` and `target`, configured: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + + +The processed event will contain the following output: + +```json +{ + "my-list": [ + { + "key": "key1", + "value": "value1" + }, + { + "key": "key2", + "value": "value2" + }, + { + "key": "key3", + "value": "value3" + } + ], + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +### Example: Custom key name and value name + +The following example shows how to configure a custom key name and value name: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" + key_name: "name" + value_name: "data" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will contain the following output: + +```json +{ + "my-list": [ + { + "name": "key1", + "data": "value1" + }, + { + "name": "key2", + "data": "value2" + }, + { + "name": "key3", + "data": "value3" + } + ], + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +### Example: Exclude specific keys from processing and remove any processed fields + +The following example shows how to exclude specific keys and remove any processed fields from the output: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" + exclude_keys: ["key1"] + remove_processed_fields: true +... +``` +{% include copy.html %} + +When the input event contains the following data: +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will remove the "key2" and "key3" fields, but the "my-map" object, "key1", will remain, as shown in the following output: + +```json +{ + "my-list": [ + { + "key": "key2", + "value": "value2" + }, + { + "key": "key3", + "value": "value3" + } + ], + "my-map": { + "key1": "value1" + } +} +``` + +### Example: Use convert_field_to_list + +The following example shows how to use the `convert_field_to_list` option in the processor: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" + convert_field_to_list: true +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will convert all fields into lists, as shown in the following output: + +```json +{ + "my-list": [ + ["key1", "value1"], + ["key2", "value2"], + ["key3", "value3"] + ], + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +### Example: Use the event root as the source + +The following example shows how you can use an event's root as the source by setting the `source` setting to an empty string (`""`): + +```yaml +... + processor: + - map_to_list: + source: "" + target: "my-list" +... +``` +{% include copy.html %} + +When the input event contains the following data: + +```json +{ + "key1": "value1", + "key2": "value2", + "key3": "value3" +} +``` + +The processed event will contain the following output: + +```json +{ + "my-list": [ + { + "key": "key1", + "value": "value1" + }, + { + "key": "key2", + "value": "value2" + }, + { + "key": "key3", + "value": "value3" + } + ], + "key1": "value1", + "key2": "value2", + "key3": "value3" +} +``` diff --git a/_data-prepper/pipelines/configuration/processors/ml-inference.md b/_data-prepper/pipelines/configuration/processors/ml-inference.md new file mode 100644 index 00000000..883ed33c --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/ml-inference.md @@ -0,0 +1,114 @@ +--- +layout: default +title: ML inference +parent: Processors +grand_parent: Pipelines +nav_order: 210 +--- + +# ML inference processor + +The `ml_inference` processor allows you to use OpenSearch machine learning (ML) functionality within OpenSearch Data Prepper. By integrating ML models into Data Prepper pipelines, you can apply them during data ingestion into Amazon OpenSearch Service in order to power AI-driven search experiences such as vector search, semantic search, or conversational search. To explore OpenSearch AI-powered search types, see [AI search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/). + +Using the `ml_inference` processor, you can invoke an OpenSearch-hosted ML model within your Data Prepper pipeline in order to process events. The processor supports both real-time invocations and asynchronous (offline) batch job invocations. + +To use the `ml_inference` processor, you must have the ML Commons plugin installed on your cluster. The plugin is included by default in standard OpenSearch distributions. For more information, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). +{: .note} + +## Configuration fields + +The following table describes the configuration options for the `ml_inference` processor. + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `host` | Yes | String | The name of the OpenSearch host. | +| `action_type` | Yes | String | The type of action to perform. Currently, only `batch_predict` is supported. Default is `batch_predict`. | +| `model_id` | Yes | String | The ID of the ML model to invoke. When `service_name` is `bedrock`, you can also set `model_id` to one of the built-in Amazon Bedrock model IDs: `amazon.titan-embed-text-v2:0`, `amazon.titan-embed-image-v1`, or `amazon.nova-2-multimodal-embeddings-v1:0`. For built-in models, the processor creates the batch inference job directly in Amazon Bedrock without sending a request to the OpenSearch host, and `aws.job_sts_role_arn` is required. | +| `output_path` | Yes | String | The [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) location to which the offline batch job results will be written. | +| `aws.region` | Yes | String | The AWS Region to which OpenSearch Service is deployed. | +| `aws.sts_role_arn` | No | String | The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role to assume. | +| `aws.sts_external_id` | No | String | The external ID to use when assuming the IAM role. Must be 2--1224 characters. | +| `aws.sts_header_overrides` | No | Map | A map of header overrides to use when assuming the IAM role. Maximum of 5 headers. | +| `aws.job_sts_role_arn` | Conditionally | String | The ARN of the IAM role that Amazon Bedrock assumes to run the batch inference job. Required when `model_id` is a built-in Amazon Bedrock model ID. Must be 20--2048 characters. | +| `service_name` | No | String | The name of the AI service hosting the model used for inference. Default is `sagemaker` (Amazon SageMaker). | +| `input_key` | No | String | The name of the event field to use as the S3 object key name when writing batch job results. This allows dynamic naming of output files based on event data. | +| `ml_when` | No | String | A conditional expression that determines when to invoke the `ml_inference` processor. | +| `tags_on_failure` | No | List | A list of tags to add to events if the `ml_inference` processor fails or encounters an error. | +| `max_batch_size` | No | Integer | Applies when `service_name` is `sagemaker`. The maximum number of events to include in one batch job. The processor creates a batch job when the number of collected events reaches this value or when no new events arrive for 1 minute. Default is `100`. | +| `retry_time_window` | No | Duration | The amount of time for which the processor retains events for retry after a batch job request is throttled. Events that cannot be processed within this time window are treated as failed. Supports ISO 8601 notation strings (for example, `PT20.345S` or `PT15M`) and simple notation strings for seconds (`60s`) and milliseconds (`1500ms`). Default is `PT10M`. | +| `retry_interval` | No | Duration | Applies when `service_name` is `bedrock`. The amount of time to wait between retries of throttled batch job requests. Supports ISO 8601 notation strings (for example, `PT1M`) and simple notation strings for seconds (`60s`) and milliseconds (`1500ms`). Valid values are 3 seconds to 5 minutes. Default is `60s`. | +| `dlq` | No | Object | The [dead-letter queue (DLQ)]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/dlq/) configuration for events for which a batch job cannot be created. If the DLQ configuration does not specify `region` or `sts_role_arn`, the values from the `aws` configuration are used. | + + + +#### Example configuration + +The following example shows an example `map_to_list` processor configuration: + +```yaml + processor: + - ml_inference: + host: "https://search-ml-inference-test.us-west-2.es.amazonaws.com" + action_type: "batch_predict" + service_name: "sagemaker" + model_id: "9t4AbpYBQB1BoSOe8g8N" + output_path: "s3://test-bucket/output" + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-inference-role" + ml_when: /bucket == "offlinebatch" + +``` +{% include copy.html %} + +## Usage + +The processor supports `batch_predict` operations, which invoke the [Batch Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/batch-predict/) for offline batch processing. + + +## Behavior + +For `batch_predict` operations, the `ml_inference` processor works best with the [S3 source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/). To configure S3 to process metadata only, configure the S3 scan block as follows: + +```yaml +scan: + buckets: + - bucket: + name: test-offlinebatch + data_selection: metadata_only +``` +{% include copy.html %} + +When `metadata_only` is enabled, the processor receives events in the following format: + +```json +{"bucket":"test-offlinebatch","length":6234,"time":1738108982.000000000,"key":"input_folder/batch_input_1.json"} +``` + +To filter specific records for processing, use `ml_when` conditions. + + +## Monitoring the offline batch job status + +Once an offline batch job is created by the Data Prepper pipeline, you can track its status using the AI provider's (Amazon SageMaker or Amazon Bedrock) native console. + +Alternatively, you can check the job status by calling the [Search ML Tasks API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/search-task/). For example, to search for all currently running tasks, use the following request: + +```json +GET /_plugins/_ml/tasks/_search +{ + "query": { + "bool": { + "filter": [ + { + "term": { + "state": "RUNNING" + } + } + ] + } + }, + "_source": ["model_id", "state", "task_type", "create_time", "last_update_time"] +} +``` +{% include copy-curl.html %} diff --git a/_data-prepper/pipelines/configuration/processors/obfuscate.md b/_data-prepper/pipelines/configuration/processors/obfuscate.md index 4c33d8ba..f9f54562 100644 --- a/_data-prepper/pipelines/configuration/processors/obfuscate.md +++ b/_data-prepper/pipelines/configuration/processors/obfuscate.md @@ -1,12 +1,12 @@ --- layout: default -title: obfuscate +title: Obfuscate parent: Processors grand_parent: Pipelines -nav_order: 71 +nav_order: 240 --- -# obfuscate +# Obfuscate processor The `obfuscate` process enables obfuscation of fields inside your documents in order to protect sensitive data. @@ -62,11 +62,21 @@ When run, the `obfuscate` processor parses the fields into the following output: Use the following configuration options with the `obfuscate` processor. +<!-- +This table is autogenerated. Do not edit it. +- name: obfuscate +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/253e59245fd9c39c959c1c8caaeff1b226a5a0ab/data-prepper-plugins/obfuscate-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/obfuscation/ObfuscationProcessorConfig.java +--> + | Parameter | Required | Description | | :--- | :--- | :--- | | `source` | Yes | The source field to obfuscate. | | `target` | No | The new field in which to store the obfuscated value. This leaves the original source field unchanged. When no `target` is provided, the source field updates with the obfuscated value. | | `patterns` | No | A list of regex patterns that allow you to obfuscate specific parts of a field. Only parts that match the regex pattern will obfuscate. When not provided, the processor obfuscates the whole field. | +| `single_word_only` | No | When set to `true`, a word boundary `\b` is added to the pattern, which causes obfuscation to be applied only to words that are standalone in the input text. By default, it is `false`, meaning obfuscation patterns are applied to all occurrences. Can be used for Data Prepper 2.8 or greater. +| `obfuscate_when` | No | Specifies under what condition the Obfuscate processor should perform matching. Default is no condition. | +| `tags_on_match_failure` | No | The tag to add to an event if the obfuscate processor fails to match the pattern. | | `action` | No | The obfuscation action. As of Data Prepper 2.3, only the `mask` action is supported. | You can customize the `mask` action with the following optional configuration options. @@ -87,9 +97,9 @@ You cannot use multiple patterns for one obfuscate processor. Use one pattern fo | Pattern name | Examples | |-----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| %{EMAIL_ADDRESS} | abc@test.com<br/> 123@test.com<br/>abc123@test.com<br/>abc_123@test.com<br/>a-b@test.com<br/>a.b@test.com<br/>abc@test-test.com<br/>abc@test.com.cn<br/>abc@test.mail.com.org | -| %{IP_ADDRESS_V4} | 1.1.1.1<br/>192.168.1.1<br/>255.255.255.0 | -| %{BASE_NUMBER} | 1.1<br/>.1<br/>2000 | -| %{CREDIT_CARD_NUMBER} | 5555555555554444<br/>4111111111111111<br/>1234567890123456<br/>1234 5678 9012 3456<br/> 1234-5678-9012-3456 | -| %{US_PHONE_NUMBER} | 1555 555 5555<br/>5555555555<br/>1-555-555-5555<br/>1-(555)-555-5555<br/>1(555) 555 5555<br/>(555) 555 5555<br/>+1-555-555-5555<br/> | -| %{US_SSN_NUMBER} | 123-11-1234 +| `%{EMAIL_ADDRESS}` | `abc@test.com`<br/>`123@test.com`<br/>`abc123@test.com`<br/>`abc_123@test.com`<br/>`a-b@test.com`<br/>`a.b@test.com`<br/>`abc@test-test.com`<br/>`abc@test.com.cn`<br/>`abc@test.mail.com.org` | +| `%{IP_ADDRESS_V4}` | `1.1.1.1`<br/>`192.168.1.1`<br/>`255.255.255.0` | +| `%{BASE_NUMBER}` | `1.1`<br/>`.1`<br/>`2000` | +| `%{CREDIT_CARD_NUMBER}` | `5555555555554444`<br/>`4111111111111111`<br/>`1234567890123456`<br/>`1234 5678 9012 3456`<br/>`1234-5678-9012-3456` | +| `%{US_PHONE_NUMBER}` | `1555 555 5555`<br/>`5555555555`<br/>`1-555-555-5555`<br/>`1-(555)-555-5555`<br/>`1(555) 555 5555`<br/>`(555) 555 5555`<br/>`+1-555-555-5555` | +| `%{US_SSN_NUMBER}` | `123-11-1234` diff --git a/_data-prepper/pipelines/configuration/processors/otel-apm-service-map.md b/_data-prepper/pipelines/configuration/processors/otel-apm-service-map.md new file mode 100644 index 00000000..296418b6 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/otel-apm-service-map.md @@ -0,0 +1,132 @@ +--- +layout: default +title: OTel APM Service map +parent: Processors +grand_parent: Pipelines +nav_order: 245 +--- + +# OTel APM service map processor + +The `otel_apm_service_map` processor analyzes OpenTelemetry (OTel) trace spans to automatically generate Application Performance Monitoring (APM) service map relationships and metrics. It creates structured events that can be visualized as service topology graphs, showing how services communicate with each other and detailing their performance characteristics. + +The `otel_apm_service_map` processor provides all the functionality of the existing [`service_map` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/service-map/) while offering enhanced observability capabilities. In addition to generating service maps, it creates time-based service maps that capture how relationships between services evolve over time rather than producing a static representation. + +The processor also automatically generates Rate, Errors, and Duration (RED) metrics for each service, delivering immediate insight into service health and performance without requiring additional configuration. + + +## Configuration + +The following table describes the options you can use to configure the `otel_apm_service_map` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: otel_apm_service_map +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/6eb06fe60c21bc4125875af5a3052e332908a12a/data-prepper-plugins/otel-apm-service-map-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/otel_apm_service_map/OTelApmServiceMapProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`window_duration` | No | Duration | The fixed time window during which APM service map relationships are evaluated. Supports ISO-8601 duration format (for example, `PT60S` or `PT1M`) or simple integer values (interpreted as seconds). Default is `60s`. +`db_path` | No | String | The directory in which the processor creates database files that store transient data off heap when processing APM service map data. Default is `data/otel-apm-service-map/`. +`group_by_attributes` | No | List | A list of OTel resource attribute names to copy into `Service.groupByAttributes` when they are present in a span's resource attributes. This setting applies only to primary `Service` objects and not to dependency services. Default is an empty list. +`metric_timestamp_source` | No | String | The source of the timestamp assigned to emitted metrics and service map events. Valid values are `arrival_time` and `span_end_time`. When set to `arrival_time`, the processor uses the time at which it evaluates the window, so all spans in a window share one timestamp. When set to `span_end_time`, the processor uses the end time of each span. Spans that arrive late can then produce data points that have the same timestamp as data points already written, which metrics backends such as Prometheus can reject. If a span has no valid end time, the processor uses the evaluation time. Default is `arrival_time`. +`metric_timestamp_granularity` | No | String | The time unit to which the timestamps of emitted metrics and service map events are truncated. Valid values are `seconds` and `minutes`. Default is `seconds`. +`dependency_nodes` | No | Object | Configures how the processor creates nodes for databases, message brokers, and external endpoints that do not emit their own spans. See [Dependency nodes](#dependency-nodes). + +### Dependency nodes + +A dependency node represents a downstream component that a service calls but that does not emit its own `SERVER` span, such as a database, a message broker, or an external endpoint. The processor creates dependency nodes from the spans of the calling service and generates RED metrics for them. Each dependency node has one of the following types: + +- `database`: Created from a `CLIENT` span that contains database (`db.*`) attributes and has no child `SERVER` span. +- `external`: Created from a `CLIENT` span that contains HTTP, RPC, or peer attributes and has no child `SERVER` span. +- `messaging`: Created from a `PRODUCER` or `CONSUMER` span. The broker node connects producers to consumers. + +The processor does not create an `external` node for a peer if the peer host is unresolved, is an IP address or a loopback address, or matches a pattern in `hostname_denylist_patterns`. For a `database` node, such a host is left out of the node name, which then uses `<db.system>:<db.namespace>` or `<db.system>`. + +The processor creates dependency nodes only from spans in the OpenTelemetry format. If you use the [`otel_trace_source`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace-source/) source, set its `output_format` to `otel`. With the default `opensearch` format, the processor generates service metrics but no dependency nodes. +{: .important} + +If your version of OpenSearch Dashboards does not support dependency nodes, it lists them as services. In this case, set `enabled` to `false`. +{: .note} + +You can configure the following options in the `dependency_nodes` object. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`enabled` | No | Boolean | Whether to create dependency nodes. When set to `false`, the processor does not create nodes for components that do not emit their own spans. Default is `true`. +`max_dependencies_per_service` | No | Integer | The maximum number of distinct dependencies that a single source service can hold. A dependency that a service already holds remains admitted in later windows. When the limit is reached, free slots go to the new dependencies that have the most calls in the window, and calls to the remaining dependencies are grouped into an overflow node named `OtherDatabase`, `OtherExternal`, or `OtherMessaging`, depending on the dependency type. A dependency that is not seen for more than 10 consecutive windows releases its slot. Must be at least `1`. Default is `100`. +`max_remote_operations_per_service` | No | Integer | The maximum number of distinct dependency remote operations that a single source service can hold. Operations are admitted and released in the same way as dependencies. When the limit is reached, calls to the remaining operations are grouped into an operation named `OtherRemoteOperation`. Must be at least `1`. Default is `100`. +`hostname_denylist_patterns` | No | List | A list of regular expressions matched against the host name of a dependency. Matching is case insensitive, and a pattern must match the entire host name. The processor does not create a node for a host that matches any pattern. Setting this option replaces the default list. By default, the list contains patterns that match host names derived from IP addresses, such as Amazon EC2 host names (`ip-10-0-0-5.ec2.internal` or `ec2-1-2-3-4.compute-1.amazonaws.com`) and Kubernetes pod DNS names (`10-0-0-5.ns.pod.cluster.local`). + +The following example sets custom limits and a custom host name denylist: + +```yaml +processor: + - otel_apm_service_map: + dependency_nodes: + enabled: true + max_dependencies_per_service: 50 + max_remote_operations_per_service: 200 + hostname_denylist_patterns: + - '^ip-\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}(\..*)?$' + - '^egress-proxy$' +``` +{% include copy.html %} + +## Usage + +```yaml +entry-pipeline: + source: + otel_trace_source: + path: "/test/path" + sink: + - pipeline: + name: "raw-pipeline" + - pipeline: + name: "service-map-pipeline" +raw-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - otel_trace_raw: + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-raw +service-map-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - otel_apm_service_map: + window_duration: 60s + db_path: "data/otel-apm-service-map/" + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-service-map +``` +{% include copy.html %} + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | The ingress of records to a pipeline component. | +| `recordsOut` | Counter | The egress of records from a pipeline component. | +| `timeElapsed` | Timer | The time elapsed during execution of a pipeline component, in milliseconds. | + +The `otel_apm_service_map` processor includes the following custom metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `spansDbSize` | Gauge | The total size of all three span database windows, in bytes. | +| `spansDbCount` | Gauge | The total number of span entries across all three span database windows. | +| `dependencyCallsOverflowed` | Counter | The number of calls grouped into an overflow dependency node because `max_dependencies_per_service` was reached. Reported only when dependency nodes are enabled. | +| `dependencyRemoteOperationCallsOverflowed` | Counter | The number of calls grouped into `OtherRemoteOperation` because `max_remote_operations_per_service` was reached. Reported only when dependency nodes are enabled. | diff --git a/_data-prepper/pipelines/configuration/processors/otel-metrics.md b/_data-prepper/pipelines/configuration/processors/otel-metrics.md index 08fb7281..17d4adfc 100644 --- a/_data-prepper/pipelines/configuration/processors/otel-metrics.md +++ b/_data-prepper/pipelines/configuration/processors/otel-metrics.md @@ -1,12 +1,12 @@ --- layout: default -title: otel_metrics +title: OTel metrics parent: Processors grand_parent: Pipelines -nav_order: 72 +nav_order: 250 --- -# otel_metrics +# OTel metrics processor The `otel_metrics` processor serializes a collection of `ExportMetricsServiceRequest` records sent from the [OTel metrics source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-metrics-source/) into a collection of string records. @@ -16,7 +16,7 @@ To get started, add the following processor to your `pipeline.yaml` configuratio ``` yaml processor: - - otel_metrics_raw_processor: + - otel_metrics: ``` {% include copy.html %} @@ -24,6 +24,13 @@ processor: You can use the following optional parameters to configure histogram buckets and their default values. A histogram displays numerical data by grouping data into buckets. You can use histogram buckets to view sets of events that are organized by the total event count and aggregate sum for all events. For more detailed information, see [OpenTelemetry Histograms](https://opentelemetry.io/docs/reference/specification/metrics/data-model/#histogram). +<!-- +This table is autogenerated. Do not edit it. +- name: otel_metrics +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/otel-metrics-raw-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/otelmetrics/OtelMetricsRawProcessorConfig.java +--> + | Parameter | Default value | Description | | :--- | :--- | :--- | | `calculate_histogram_buckets` | `True` | Whether or not to calculate histogram buckets. | @@ -31,7 +38,9 @@ You can use the following optional parameters to configure histogram buckets and | `exponential_histogram_max_allowed_scale` | `10` | Maximum allowed scale in exponential histogram calculation. | | `flatten_attributes` | `False` | Whether or not to flatten the `attributes` field in the JSON data. | +<!-- vale off --> ### calculate_histogram_buckets +<!-- vale on --> If `calculate_histogram_buckets` is not set to `false`, then the following `JSON` file will be added to every histogram JSON. If `flatten_attributes` is set to `false`, the `JSON` string format of the metrics does not change the attributes field. If `flatten_attributes` is set to `true`, the values in the attributes field are placed in the parent `JSON` object. The default value is `true`. See the following `JSON` example: @@ -77,7 +86,9 @@ Each array element describes one bucket. Each bucket contains the lower boundary +<!-- vale off --> ### calculate_exponential_histogram_buckets +<!-- vale on --> If `calculate_exponential_histogram_buckets` is set to `true` (the default setting), the following `JSON` values are added to each `JSON` histogram: @@ -130,11 +141,13 @@ The following `JSON` file is a more detailed form of OpenTelemetry representatio ``` +<!-- vale off --> ### exponential_histogram_max_allowed_scale +<!-- vale on --> -The `exponential_histogram_max_allowed_scale` parameter defines the maximum allowed scale for an exponential histogram. If you increase this parameter, you will increase potential memory consumption. See the [OpenTelemetry specifications](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto) for more information on exponential histograms and their computational complexity. +The `exponential_histogram_max_allowed_scale` parameter defines the maximum allowed scale for an exponential histogram. If you increase this parameter, you will increase potential memory consumption. See the [OpenTelemetry specifications](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto) for more information about exponential histograms and their computational complexity. -All exponential histograms that have a scale that is above the configured parameter (by default, a value of `10`) are discarded and logged with an error level. You can check the log that Data Prepper creates to see the `ERROR` log message. +All exponential histograms that have a scale that is above the configured parameter (by default, a value of `10`) are discarded and logged with an error level. You can check the log that OpenSearch Data Prepper creates to see the `ERROR` log message. The absolute scale value is used for comparison, so a scale of `-11` that is treated equally to `11` exceeds the configured value of `10` and can be discarded. {: .note} diff --git a/_data-prepper/pipelines/configuration/processors/otel-trace-group.md b/_data-prepper/pipelines/configuration/processors/otel-trace-group.md index 06bc754a..b057e14c 100644 --- a/_data-prepper/pipelines/configuration/processors/otel-trace-group.md +++ b/_data-prepper/pipelines/configuration/processors/otel-trace-group.md @@ -1,12 +1,12 @@ --- layout: default -title: otel_trace_group +title: OTel trace group parent: Processors grand_parent: Pipelines -nav_order: 73 +nav_order: 270 --- -# otel_trace_group +# OTel trace group processor The `otel_trace_group` processor completes missing trace-group-related fields in the collection of [span](https://github.com/opensearch-project/data-prepper/blob/834f28fdf1df6d42a6666e91e6407474b88e7ec6/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/trace/Span.java) records by looking up the OpenSearch backend. The `otel_trace_group` processor identifies the missing trace group information for a `spanId` by looking up the relevant fields in its root `span` stored in OpenSearch. @@ -55,8 +55,8 @@ You can configure the `otel_trace_group` processor with the following options. | `aws_sts_role_arn`| An AWS Identity and Access Management (IAM) role that the sink plugin assumes to sign the request to Amazon OpenSearch Service. If not provided, the plugin uses the [default credentials](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.html). | `null` | | `aws_sts_header_overrides` | A map of header overrides that the IAM role assumes for the sink plugin. | `null` | | `insecure` | A Boolean flag used to turn off SSL certificate verification. If set to `true`, CA certificate verification is turned off and insecure HTTP requests are sent. | `false` | -| `username` | A string that contains the username and is used in the [internal users](https://opensearch.org/docs/latest/security/access-control/users-roles/) `YAML` configuration file of your OpenSearch cluster. | `null` | -| `password` | A string that contains the password and is used in the [internal users](https://opensearch.org/docs/latest/security/access-control/users-roles/) `YAML` configuration file of your OpenSearch cluster. | `null` | +| `username` | A string that contains the username and is used in the [internal users]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/) `YAML` configuration file of your OpenSearch cluster. | `null` | +| `password` | A string that contains the password and is used in the [internal users]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/) `YAML` configuration file of your OpenSearch cluster. | `null` | ## Configuration option examples diff --git a/_data-prepper/pipelines/configuration/processors/otel-traces.md b/_data-prepper/pipelines/configuration/processors/otel-traces.md new file mode 100644 index 00000000..f09a7d4e --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/otel-traces.md @@ -0,0 +1,175 @@ +--- +layout: default +title: OTel trace +parent: Processors +grand_parent: Pipelines +nav_order: 260 +redirect_from: + - /data-prepper/pipelines/configuration/processors/otel-trace-raw/ +--- + +# OTel trace processor + +The `otel_traces` processor completes trace-group-related fields in all incoming OpenSearch Data Prepper span records by caching the root span information for each `traceId`. It also enriches traces from generative AI (GenAI) agents and large language model (LLM) applications. For more information, see [GenAI agent trace enrichment](#genai-agent-trace-enrichment). + +The processor was previously named `otel_trace_raw`. You can still use the `otel_trace_raw` name, but it is deprecated and is planned for removal in Data Prepper 3.0. +{: .note} + +## Usage + +This processor adds the following fields to span events: + +* `traceGroup`: Root span name +* `endTime`: End time of the entire trace in International Organization for Standardization (ISO) 8601 format +* `durationInNanos`: Duration of the entire trace in nanoseconds +* `statusCode`: Status code for the entire trace + +## Configuration + +The following table describes the options you can use to configure the `otel_traces` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: otel_traces +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/4fcb0f6d4df60ae5f6cd6df3007704d28a72c774/data-prepper-plugins/otel-trace-raw-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/oteltrace/OtelTraceRawProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`trace_flush_interval` | No | Integer | The amount of time, in seconds, after which the processor flushes descendant spans that have no root span. Default is `180`. +`trace_group_cache_ttl` | No | Duration | The amount of time to keep trace group details in the cache. Accepts ISO 8601 notation, such as `PT1M30S`, or a duration and unit, such as `45s`. Default is `15s`. +`trace_group_cache_max_size` | No | Integer | The maximum number of trace groups from root spans to keep in the cache. Default is `1000000`. +`disable_genai_enrichment` | No | Boolean | Turns off GenAI agent trace enrichment: normalizing vendor attributes to `gen_ai.*`, stripping flattened sub-keys that conflict with their parent, marking agent root spans, and copying agent data onto trace roots. Traces that contain no GenAI spans are not changed. Default is `false`. +`genai_coverage_cache_max_size` | No | Integer | The maximum number of GenAI span IDs to keep in the coverage cache across all traces. The cache prevents GenAI spans that arrive after their ancestors from being marked as a trace's AI root. Must be at least `1`. Cannot be set when `disable_genai_enrichment` is `true`. For more information, see [Late spans and the coverage cache](#late-spans-and-the-coverage-cache). Default is `500000`. +`genai_root_propagation` | No | String | Determines which root spans receive the GenAI attributes and token totals copied from their child spans. Valid values are `ai_root`, `all_roots`, and `none`. Cannot be set when `disable_genai_enrichment` is `true`. For more information, see [Root span enrichment](#root-span-enrichment). Default is `ai_root`. + +The `disable_genai_enrichment`, `genai_coverage_cache_max_size`, and `genai_root_propagation` options are available in Data Prepper 2.17 and later. +{: .note} + +## GenAI agent trace enrichment + +The `otel_traces` processor enriches traces from GenAI agents and LLM applications so that agent runs can be found, listed, and measured from the spans themselves, for example, in the OpenSearch Dashboards **Agent Traces** page. Enrichment is turned on by default, is available in Data Prepper 2.14 and later, and does not change traces that contain no GenAI data. + +Enrichment matches attributes by their OpenTelemetry (OTel) key names, for example, `gen_ai.operation.name`, so the source must emit spans in the OTel format. The [`otel_trace_source`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace-source/) source defaults to the `opensearch` format, so set its `output_format` to `otel`. The [`otlp`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otlp-source/) source uses the `otel` format by default. The `opensearch` format rewrites attribute keys (for example, `http.method` becomes `span.attributes.http@method`), and the enrichment then finds no GenAI data. +{: .important} + +For each trace in a batch, the processor applies the following steps in order: + +1. [Vendor attribute normalization](#vendor-attribute-normalization) +1. [Flattened sub-key stripping](#flattened-sub-key-stripping) +1. [Root span enrichment](#root-span-enrichment) +1. [Agent root marker](#agent-root-marker) + +To turn off all of these steps, set `disable_genai_enrichment` to `true`. Span attributes are then left as they arrive, and the processor creates no coverage cache. + +### Vendor attribute normalization + +Instrumentation libraries name the same data differently. For example, input tokens are `llm.token_count.prompt` in OpenInference, `llm.usage.prompt_tokens` in OpenLLMetry, and `gen_ai.usage.input_tokens` in the [OTel GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/). The processor copies vendor attributes to their `gen_ai.*` names so that queries, dashboards, and the rest of the enrichment only need the standard names. The normalization follows these rules: + +* The mappings are listed in [`genai-attribute-mappings.yaml`](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/otel-trace-raw-processor/src/main/resources/genai-attribute-mappings.yaml) and grouped by source: `openinference`, `openllmetry` (Traceloop), and `claude_code`. +* The original attributes are kept. The `gen_ai.*` copy is added next to them. +* A `gen_ai.*` attribute that is already on the span is never overwritten. +* When several attributes on one span map to the same `gen_ai.*` name, the one listed first in the mappings file is used. For example, the OpenInference `session.id` attribute is used before Traceloop's `traceloop.association.properties.session_id`; both map to `gen_ai.conversation.id`. +* Operation kinds are mapped to `gen_ai.operation.name` values. For example, the OpenInference `LLM` kind becomes `chat`, `AGENT` and `CHAIN` become `invoke_agent`, and `TOOL` becomes `execute_tool`. +* Some mappings wrap a single value in a JSON array, for example, a finish reason in `gen_ai.response.finish_reasons`. + +Starting in Data Prepper 2.17, Traceloop session IDs (`traceloop.association.properties.session_id`) are mapped to `gen_ai.conversation.id`, which groups traces into sessions. + +### Flattened sub-key stripping + +Some instrumentations emit the same field twice: as a JSON string (for example, `llm.input_messages`) and as flattened sub-keys (for example, `llm.input_messages.0.message.content`). OpenSearch rejects such documents with a mapping conflict. When the parent string is present, the processor removes the indexed sub-keys. When only the sub-keys are present, they are kept so that no data is lost. + +### Root span enrichment + +The processor can copy `gen_ai.system`, `gen_ai.provider.name`, `gen_ai.agent.name`, `gen_ai.request.model`, and the trace's token totals from child spans onto the trace's root span. Attributes that the root span already has are kept. Values are taken from the outermost GenAI spans first (by earliest start time), then from other GenAI spans, and then from the remaining children. + +The `genai_root_propagation` option selects which root spans receive the copies, as described in the following table. + +Value | Root spans that receive the copies +:--- | :--- +`ai_root` (default) | Only a root span that is its trace's AI root: a GenAI span, or a span marked `derived.gen_ai.is_root: true` at the source. +`all_roots` | Every root span, including non-GenAI roots such as the HTTP span that an agent runs behind. This was the default before Data Prepper 2.17. +`none` | No root span. + +With `ai_root`, a non-GenAI root span keeps only its own attributes. Copying agent data onto a non-GenAI root span makes the HTTP span appear to call a model and use tokens, combines parallel agents into one agent name, and counts the trace's tokens again for any consumer that sums usage across spans. The [agent root marker](#agent-root-marker) span carries this data instead. + +Marking does not depend on this option: with `none`, an agent span that the processor marks still receives its descendants' token totals. + +In Data Prepper 2.17, the default changed from copying onto every root span to `ai_root`. If your queries or dashboards read agent data, such as `gen_ai.agent.name` or token totals, from non-GenAI root spans, set `genai_root_propagation` to `all_roots` to keep the previous behavior, or read the data from the marked agent span. +{: .important} + +### Agent root marker + +Agents often run behind a service: the trace's root span is an HTTP or RPC span, such as `POST /plan`, and the agent span is nested under it. Consumers that list traces by their root span then miss the agent or show the HTTP span instead. Starting in Data Prepper 2.17, the processor marks the span that represents each agent run with `derived.gen_ai.is_root: true`. The marker follows these rules: + +* Each outermost GenAI span of a trace is marked. This is a span that has `gen_ai.operation.name` and no GenAI ancestor: either the root span itself, when it is a GenAI span, or the agent span nested under a non-GenAI root. +* When several top-level agents run under one root span, each is marked as one agent run. +* In a chain of agents that call agents, such as `invoke_agent` > HTTP client > HTTP server > `invoke_agent`, only the calling agent is marked because the called agent has a GenAI ancestor. +* A span that the processor marks and that reports no token usage of its own receives the usage of its descendants. Spans marked at the source do not receive these totals. Descendant usage is counted as described in [Token usage](#token-usage). +* An SDK or the user can set the marker on a span at the source. If any span in a trace is marked `true` at the source, the processor marks no other span in that trace. A span set to `false` is never marked, so setting `false` on a trace's outermost GenAI spans excludes the trace from marking. +* Spans that are flushed after `trace_flush_interval` without their root span are still marked because the marker only needs the span's descendants. + +To list a trace's agent runs, query its marked spans. For data indexed before the marker existed, query root spans that are GenAI spans instead. + +#### Late spans and the coverage cache + +The spans of one trace can arrive in several batches. A span that arrives after its agent span was processed is enriched without its ancestors, so it would appear to be outermost and would be marked as a second agent run. To prevent this, the processor records, per trace, which span IDs are already covered by a GenAI span or a marker, and checks this record when a span's parent is not in the batch. The coverage cache works as follows: + +* Entries are kept for twice the `trace_flush_interval` plus the `trace_group_cache_ttl` (375 seconds by default), so they outlive the flush of spans that arrive without their root span. +* The cache stores at most `genai_coverage_cache_max_size` span IDs across all traces. Only traces that contain GenAI spans are stored. The `genAiCoverageSpanIdCount` metric reports how full the cache is, in span IDs. +* The cache supports about `genai_coverage_cache_max_size` / (2 × `trace_flush_interval` + `trace_group_cache_ttl`) GenAI spans per second, which is about 1,300 spans per second by default. At higher rates, traces are evicted early and a late span can be marked again, so increase `genai_coverage_cache_max_size` for higher GenAI span rates. +* The covered-span lookup, the marking, and the update run atomically for each trace, so pipeline workers that process spans of the same trace at the same time do not both mark a span. + +The coverage cache has the following limitations: + +* A span that arrives after its trace's entry has expired or was evicted can be marked. +* If a trace's child spans are flushed before a GenAI root span arrives, both the root span and the outermost child span can be marked. Consumers should prefer the marked span that has no parent. +* If a called service's spans are flushed after `trace_flush_interval` without the caller's spans, the called agent is also marked and is listed as a separate agent run. + +### Token usage + +When the processor sums `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`, either onto a root span or onto a marked agent span, it counts only spans that have no ancestor that also reports usage. Agent spans such as `invoke_agent` often report the total of their own LLM calls, so adding every span that reports usage would count those calls twice. Token counting follows these rules: + +* An ancestor's reported usage is assumed to include its subtree. A sub-agent that runs its own LLM calls under a parent that reports only its own usage is not added. +* A span that reports either token count is treated as reporting usage and keeps its own values. +* Token counts sent as numeric strings are read as numbers. Other values are ignored. + +### Example + +The following pipeline receives OpenTelemetry Protocol (OTLP) traces in the OTel format and writes enriched spans to OpenSearch. The GenAI options are shown with their default values: + +```yaml +otel-traces-pipeline: + source: + otel_trace_source: + ssl: false + output_format: otel + processor: + - otel_traces: + disable_genai_enrichment: false + genai_root_propagation: ai_root + genai_coverage_cache_max_size: 500000 + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index_type: trace-analytics-plain-raw +``` +{% include copy.html %} + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `otel_traces` processor includes the following custom metrics: + +* `traceGroupCacheCount`: The number of trace groups in the trace group cache. +* `spanSetCount`: The number of span sets in the span set collection. +* `genAiCoverageCount`: The number of traces in the GenAI coverage cache. +* `genAiCoverageSpanIdCount`: The number of span IDs in the GenAI coverage cache, in the same unit as `genai_coverage_cache_max_size`. Available in Data Prepper 2.17 and later. diff --git a/_data-prepper/pipelines/configuration/processors/parse-ion.md b/_data-prepper/pipelines/configuration/processors/parse-ion.md new file mode 100644 index 00000000..9d9dda12 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/parse-ion.md @@ -0,0 +1,83 @@ +--- +layout: default +title: Parse Ion +parent: Processors +grand_parent: Pipelines +nav_order: 280 +--- + +# Parse Ion processor + +The `parse_ion` processor parses [Amazon Ion](https://amazon-ion.github.io/ion-docs/) data. + +## Configuration + +You can configure the `parse_ion` processor with the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: parse_ion +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/253e59245fd9c39c959c1c8caaeff1b226a5a0ab/data-prepper-plugins/parse-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/parse/ion/ParseIonProcessorConfig.java +--> + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `source` | No | String | The field in the `event` that is parsed. Default value is `message`. | +| `destination` | No | String | The destination field of the parsed JSON. Defaults to the root of the `event`. Cannot be `""`, `/`, or any white-space-only `string` because these are not valid `event` fields. | +| `pointer` | No | String | A JSON pointer to the field to be parsed. There is no `pointer` by default, meaning that the entire `source` is parsed. The `pointer` can access JSON array indexes as well. If the JSON pointer is invalid, then the entire `source` data is parsed into the outgoing `event`. If the key that is pointed to already exists in the `event` and the `destination` is the root, then the pointer uses the entire path of the key. | +| `parse_when` | No | String | Specifies under which conditions the processor should perform parsing. Default is no condition. Accepts an OpenSearch Data Prepper expression string following the [expression syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). | +| `overwrite_if_destination_exists` | No | Boolean | Overwrites the destination if set to `true`. Set to `false` to prevent changing a destination value that exists. Defaults is `true`. | +| `delete_source` | No | Boolean | If set to `true`, then the source field is deleted. Defaults is `false`. | +| `tags_on_failure` | No | List | A list of strings specifying the tags to be set in the event that the processor fails or an unknown exception occurs during parsing. | +| `handle_failed_events` | No | String | Determines how to handle events containing Ion processing errors. Valid values are `skip` (log the error and send the event downstream to the next processor) and `skip_silently` (send the event downstream to the next processor without logging the error). Default is `skip`. | +| `depth` | No | Integer | The nesting level at which the processor stops parsing nested structs. Structs nested deeper than this level are stored as JSON strings. For example, if `depth` is `1`, only the top-level fields are parsed, and any struct value of a top-level field is stored as a JSON string. Structs inside lists are always parsed. Valid values are 0--10. Default is `0`, which parses all nesting levels. | + +## Usage + +The following examples show how to use the `parse_ion` processor in your pipeline. + +### Example: Minimum configuration + +The following example shows the minimum configuration for the `parse_ion` processor: + +```yaml +parse-json-pipeline: + source: + stdin: + processor: + - parse_json: + source: "my_ion" + sink: + - stdout: +``` +{% include copy.html %} + +When the input event contains the following data: + +``` +{"my_ion": "{ion_value1: \"hello\", ion_value2: \"world\"}"} +``` + +The processor parses the event into the following output: + +``` +{"ion_value1": "hello", "ion_value2" : "world"} +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `parse_ion` processor includes the following custom metrics. + +### Counter + +* `parseErrors`: The number of parse errors resulting from invalid Ion format in events. This indicates that the Ion format could not be parsed. +* `processingFailures`: The number of processing failures that have occurred in the `parse_ion` processor. This indicates unexpected errors not related to invalid Ion format. diff --git a/_data-prepper/pipelines/configuration/processors/parse-json.md b/_data-prepper/pipelines/configuration/processors/parse-json.md index 2cbce478..6cd421f7 100644 --- a/_data-prepper/pipelines/configuration/processors/parse-json.md +++ b/_data-prepper/pipelines/configuration/processors/parse-json.md @@ -1,77 +1,136 @@ --- layout: default -title: parse_json +title: Parse JSON parent: Processors grand_parent: Pipelines -nav_order: 80 +nav_order: 290 --- -# parse_json - -The `parse_json` processor parses JSON data for an event, including any nested fields. The processor extracts the JSON pointer data and adds the input event to the extracted fields. +# Parse JSON processor +The `parse_json` processor parses JSON-formatted strings within an event, including nested fields. It can optionally use a JSON pointer to extract a specific part of the source JSON and add the extracted data to the event. ## Configuration You can configure the `parse_json` processor with the following options. +<!-- +This table is autogenerated. Do not edit it. +- name: parse_json +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/253e59245fd9c39c959c1c8caaeff1b226a5a0ab/data-prepper-plugins/parse-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/parse/json/ParseJsonProcessorConfig.java +--> + | Option | Required | Type | Description | | :--- | :--- | :--- | :--- | -| `source` | No | String | The field in the `event` that will be parsed. Default value is `message`. | -| `destination` | No | String | The destination field of the parsed JSON. Defaults to the root of the `event`. Cannot be `""`, `/`, or any white-space-only `string` because these are not valid `event` fields. | -| `pointer` | No | String | A JSON pointer to the field to be parsed. There is no `pointer` by default, meaning the entire `source` is parsed. The `pointer` can access JSON array indexes as well. If the JSON pointer is invalid then the entire `source` data is parsed into the outgoing `event`. If the key that is pointed to already exists in the `event` and the `destination` is the root, then the pointer uses the entire path of the key. | +| `source` | No | String | The field in the event that will be parsed. Default is `message`. | +| `destination` | No | String | The destination field for the parsed JSON. Default is the root of the event. Cannot be `""`, `/`, or any white-space-only string. | +| `pointer` | No | String | A JSON pointer (as defined by [RFC 6901](https://datatracker.ietf.org/doc/html/rfc6901)) to a specific field in the source JSON. If omitted, the entire `source` is parsed. If the pointer is invalid, the full `source` is parsed instead. When writing to the root destination, existing keys will be preserved unless overwritten. | +| `parse_when` | No | String | A condition expression that determines when to parse the field. Accepts a string following the [expression syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). | +| `overwrite_if_destination_exists` | No | Boolean | Whether to overwrite the destination field if it already exists. Default is `true`. | +| `delete_source` | No | Boolean | Whether to delete the source field after parsing. Default is `false`. | +| `tags_on_failure` | No | List | A list of tags to apply if parsing fails or an unexpected exception occurs. | +| `handle_failed_events` | No | String | Determines how to handle events containing JSON processing errors. Valid values are `skip` (log the error and send the event downstream to the next processor) and `skip_silently` (send the event downstream to the next processor without logging the error). Default is `skip`. | +| `depth` | No | Integer | The nesting level at which the processor stops parsing nested objects. Objects nested deeper than this level are stored as JSON strings. For example, if `depth` is `1`, only the top-level fields are parsed, and any object value of a top-level field is stored as a JSON string. Objects inside lists are always parsed. Valid values are 0--10. Default is `0`, which parses all nesting levels. | +| `normalize_keys` | No | Boolean | If `true`, replaces characters that are not valid in event keys with an underscore (`_`) in the parsed keys, including the keys of nested objects. For example, the key `user:name` becomes `user_name`. Default is `false`. | ## Usage -To get started, create the following `pipeline.yaml` file: +To use the `parse_json` processor, add it to your `pipeline.yaml` configuration file: ```yaml parse-json-pipeline: source: ... - .... + ... processor: - parse_json: ``` +{% include copy.html %} + +All examples use the following JSON message for the event output: + +```json +{"outer_key": {"inner_key": "inner_value"}} +``` +{% include copy.html %} ### Basic example -To test the `parse_json` processor with the previous configuration, run the pipeline and paste the following line into your console, then enter `exit` on a new line: +The following example parses a JSON message field and flattens the data into the event. The original `message` from the example event remains, and the parsed content is added at the root level, as shown in the following output: -``` -{"outer_key": {"inner_key": "inner_value"}} -``` -{% include copy.html %} - -The `parse_json` processor parses the message into the following format: - -``` -{"message": {"outer_key": {"inner_key": "inner_value"}}", "outer_key":{"inner_key":"inner_value"}}} +```json +{ + "message": "{\"outer_key\": {\"inner_key\": \"inner_value\"}}", + "outer_key": { + "inner_key": "inner_value" + } +} ``` -### Example with a JSON pointer +### Delete a source -You can use a JSON pointer to parse a selection of the JSON data by specifying the `pointer` option in the configuration. To get started, create the following `pipeline.yaml` file: +If you want to remove the original field from the originating JSON message, use the `delete_source` option, as shown in the following example pipeline: ```yaml parse-json-pipeline: source: ... - .... + ... processor: - parse_json: - pointer: "outer_key/inner_key" -``` - -To test the `parse_json` processor with the pointer option, run the pipeline, paste the following line into your console, and then enter `exit` on a new line: - -``` -{"outer_key": {"inner_key": "inner_value"}} + delete_source: true ``` {% include copy.html %} -The processor parses the message into the following format: +In the following event, the `message` field is parsed and removed, leaving only the structured output: +```json +{ + "outer_key": { + "inner_key": "inner_value" + } +} ``` -{"message": {"outer_key": {"inner_key": "inner_value"}}", "inner_key": "inner_value"} -``` \ No newline at end of file + + +### Example using a JSON pointer + +You can use the `pointer` option to extract a specific nested field from the JSON data, as shown in the following example pipeline: + +```yaml +parse-json-pipeline: + source: + ... + ... + processor: + - parse_json: + pointer: "/outer_key/inner_key" +``` +{% include copy.html %} + +Only the value at the pointer path `/outer_key/inner_key` is extracted and added to the event. If you set `destination`, the extracted value will be added to that field instead: + +```json +{ + "message": "{\"outer_key\": {\"inner_key\": \"inner_value\"}}", + "inner_key": "inner_value" +} +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `parse_json` processor includes the following custom metrics. + +### Counter + +* `parseErrors`: The number of parse errors resulting from invalid JSON in events. This indicates that the JSON format could not be parsed. +* `processingFailures`: The number of processing failures that have occurred in the `parse_json` processor. This indicates unexpected errors not related to invalid JSON format. diff --git a/_data-prepper/pipelines/configuration/processors/parse-xml.md b/_data-prepper/pipelines/configuration/processors/parse-xml.md new file mode 100644 index 00000000..d7226d75 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/parse-xml.md @@ -0,0 +1,82 @@ +--- +layout: default +title: Parse XML +parent: Processors +grand_parent: Pipelines +nav_order: 300 +--- + +# Parse XML processor + +The `parse_xml` processor parses XML data for an event. + +## Configuration + +You can configure the `parse_xml` processor with the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: parse_xml +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/253e59245fd9c39c959c1c8caaeff1b226a5a0ab/data-prepper-plugins/parse-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/parse/xml/ParseXmlProcessorConfig.java +--> + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `source` | No | String | Specifies which `event` field to parse. | +| `destination` | No | String | The destination field of the parsed XML. Defaults to the root of the `event`. Cannot be `""`, `/`, or any white-space-only string because these are not valid `event` fields. | +| `pointer` | No | String | A JSON pointer to the field to be parsed. The value is null by default, meaning that the entire `source` is parsed. The `pointer` can access JSON array indexes as well. If the JSON pointer is invalid, then the entire `source` data is parsed into the outgoing `event` object. If the key that is pointed to already exists in the `event` object and the `destination` is the root, then the pointer uses the entire path of the key. | +| `parse_when` | No | String | Specifies under what conditions the processor should perform parsing. Default is no condition. Accepts an OpenSearch Data Prepper expression string following the [expression syntax]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). | +| `overwrite_if_destination_exists` | No | Boolean | Overwrites the destination if set to `true`. Set to `false` to prevent changing a destination value that exists. Defaults to `true`. | +| `delete_source` | No | Boolean | If set to `true` then this will delete the source field. Defaults to `false`. | +| `tags_on_failure` | No | String | A list of strings specifying the tags to be set in the event that the processor fails or an unknown exception occurs during parsing. | +| `handle_failed_events` | No | String | Determines how to handle events containing XML processing errors. Valid values are `skip` (log the error and send the event downstream to the next processor) and `skip_silently` (send the event downstream to the next processor without logging the error). Default is `skip`. | + +## Usage + +The following examples show how to use the `parse_xml` processor in your pipeline. + +### Example: Minimum configuration + +The following example shows the minimum configuration for the `parse_xml` processor: + +```yaml +parse-xml-pipeline: + source: + stdin: + processor: + - parse_xml: + source: "my_xml" + sink: + - stdout: +``` +{% include copy.html %} + +When the input event contains the following data: + +``` +{ "my_xml": "<Person><name>John Doe</name><age>30</age></Person>" } +``` + +The processor parses the event into the following output: + +``` +{ "name": "John Doe", "age": "30" } +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `parse_xml` processor includes the following custom metrics. + +### Counter + +* `parseErrors`: The number of parse errors resulting from invalid XML in events. This indicates that the XML format could not be parsed. +* `processingFailures`: The number of processing failures that have occurred in the `parse_xml` processor. This indicates unexpected errors not related to invalid XML format. \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/processors/processors.md b/_data-prepper/pipelines/configuration/processors/processors.md index 3000d716..c29e8e38 100644 --- a/_data-prepper/pipelines/configuration/processors/processors.md +++ b/_data-prepper/pipelines/configuration/processors/processors.md @@ -3,12 +3,44 @@ layout: default title: Processors has_children: true parent: Pipelines -nav_order: 25 +nav_order: 35 +redirect_from: + - /data-prepper/pipelines/configuration/processors/mutate-event/ + - /data-prepper/pipelines/configuration/processors/mutate-string/ + - /data-prepper/pipelines/configuration/processors/ --- -# Processors +# Data Prepper processors -Processors perform an action on your data, such as filtering, transforming, or enriching. +Processors are components within an OpenSearch Data Prepper pipeline that enable you to filter, transform, and enrich events using your desired format before publishing records to the `sink` component. If no `processor` is defined in the pipeline configuration, then the events are published in the format specified by the `source` component. You can incorporate multiple processors within a single pipeline, and they are executed sequentially as defined in the pipeline. + +Prior to Data Prepper 1.3, these components were named *preppers*. In Data Prepper 1.3, the term *prepper* was deprecated in favor of *processor*. In Data Prepper 2.0, the term *prepper* was removed. +{: .note } + +# Mutate event processors + +Use mutate event processors to modify events in OpenSearch Data Prepper. The following processors are available. + +| Processor | Description | +|-----------|-------------| +| [`add_entries`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/add-entries/) | Add entries to an event. | +| [`convert_entry_type`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/convert-entry-type/) | Convert value types in an event. | +| [`copy_values`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/copy-values/) | Copy values within an event. | +| [`delete_entries`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/delete-entries/) | Delete entries from an event. | +| [`list_to_map`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/list-to-map) | Convert a list of objects from an event, where each object contains a `key` field, into a map of target keys. | +| [`map_to_list`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/map-to-list) | Convert a map of objects from an event, where each object contains a `key` field, into a list of target keys. | +| [`rename_keys`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/rename-keys/) | Rename keys in an event. | +| [`select_entries`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/select-entries/) | Select entries from an event. | + +## Mutate string processors + +Use mutate string processors to modify the contents or format of string values. The following processors are available. + +| Processor | Description | +|-----------|-------------| +| [`substitute_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/substitute-string/) | Replace part of a string with a specified value using a regular expression. | +| [`split_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/split-string/) | Split a string into a list using a specified delimiter. | +| [`uppercase_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/uppercase-string/) | Convert a string to uppercase. | +| [`lowercase_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/lowercase-string/) | Convert a string to lowercase. | +| [`trim_string`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/trim-string/) | Remove leading and trailing white space from a string. | -Prior to Data Prepper 1.3, processors were named preppers. Starting in Data Prepper 1.3, the term *prepper* is deprecated in favor of the term *processor*. Data Prepper will continue to support the term *prepper* until 2.0, where it will be removed. -{: .note } \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/processors/rename-keys.md b/_data-prepper/pipelines/configuration/processors/rename-keys.md index f57b4e50..c9fbca88 100644 --- a/_data-prepper/pipelines/configuration/processors/rename-keys.md +++ b/_data-prepper/pipelines/configuration/processors/rename-keys.md @@ -1,12 +1,12 @@ --- layout: default -title: rename_keys +title: Rename keys parent: Processors grand_parent: Pipelines -nav_order: 85 +nav_order: 310 --- -# rename_keys +# Rename keys processor The `rename_keys` processor renames keys in an event. @@ -16,63 +16,135 @@ You can configure the `rename_keys` processor with the following options. | Option | Required | Description | | :--- | :--- | :--- | -| `entries` | Yes | A list of event entries to rename. | -| `from_key` | Yes | The key of the entry to be renamed. | +| `entries` | Conditionally | A list of event entries to rename. Required if `transform_key` is not set. Cannot be used together with `transform_key`. | +| `transform_key` | Conditionally | Transforms the names of all keys in the event, including nested keys. Valid values are `lowercase`, `uppercase`, `capitalize` (converts the first character to uppercase), and `none`. Required if `entries` is not set. Cannot be used together with `entries`. Default is `none`, which does not transform keys. | +| `from_key` | Conditionally | The key of the entry to be renamed. Either `from_key` or `from_key_regex` is required. Cannot be used together with `from_key_regex`. | +| `from_key_regex` | Conditionally | A regular expression that matches the top-level keys of the entries to be renamed. Either `from_key` or `from_key_regex` is required. Cannot be used together with `from_key`. If more than one key matches and `overwrite_if_to_key_exists` is `false`, only the first matching key is renamed. | | `to_key` | Yes | The new key of the entry. | | `overwrite_if_to_key_exists` | No | When set to `true`, the existing value is overwritten if `key` already exists in the event. The default value is `false`. | +| `rename_when` | No | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/type == "app"`, that determines whether the entry is applied to the event. By default, the entry is applied to all events. | ## Usage To get started, create the following `pipeline.yaml` file: ```yaml -pipeline: +rename-keys-nested-pipeline: source: - file: - path: "/full/path/to/logs_json.log" - record_type: "event" - format: "json" + http: + path: /logs + ssl: false processor: - rename_keys: entries: - - from_key: "message" - to_key: "newMessage" - overwrite_if_to_key_exists: true + # Top-level rename + - from_key: message + to_key: msg + # Level-2 (nested) renames — use slash paths + - from_key: user/name + to_key: user/username + - from_key: user/id + to_key: user/user_id + - from_key: http/response/code + to_key: http/status_code + # If a target exists already, overwrite it + - from_key: env + to_key: metadata/environment + overwrite_if_to_key_exists: true sink: - - stdout: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: rename-%{yyyy.MM.dd} ``` {% include copy.html %} +You can test this pipeline using the following command: -Next, create a log file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with that filepath. For more information, see [Configuring Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/#2-configuring-data-prepper). +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + { + "message": "hello world", + "user": { "name": "alice", "id": 123 }, + "http": { "response": { "code": 200 } }, + "env": "prod", + "metadata": { "environment": "staging" } + }, + { + "message": "goodbye", + "user": { "name": "bob", "id": 456 }, + "http": { "response": { "code": 503 } }, + "env": "dev" + } + ]' +``` +{% include copy.html %} -For example, before you run the `rename_keys` processor, if the `logs_json.log` file contains the following event record: +The documents stored in OpenSearch contain the following information: ```json -{"message": "hello"} +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "rename-2025.11.04", + "_id": "kq3NTpoBNvg1WLcAJOak", + "_score": 1, + "_source": { + "user": { + "username": "alice", + "user_id": 123 + }, + "http": { + "response": {}, + "status_code": 200 + }, + "metadata": { + "environment": "prod" + }, + "msg": "hello world" + } + }, + { + "_index": "rename-2025.11.04", + "_id": "k63NTpoBNvg1WLcAJOak", + "_score": 1, + "_source": { + "user": { + "username": "bob", + "user_id": 456 + }, + "http": { + "response": {}, + "status_code": 503 + }, + "msg": "goodbye", + "metadata": { + "environment": "dev" + } + } + } + ] + } +} ``` -When you run the `rename_keys` processor, it parses the message into the following "newMessage" output: - -```json -{"newMessage": "hello"} -``` - -> If `newMessage` already exists, its existing value is overwritten with `value`. - - - ## Special considerations Renaming operations occur in the order that the key-value pair entries are listed in the `pipeline.yaml` file. This means that chaining (where key-value pairs are renamed in sequence) is implicit in the `rename_keys` processor. See the following example `pipeline.yaml` file: ```yaml -pipeline: - source: - file: - path: "/full/path/to/logs_json.log" - record_type: "event" - format: "json" processor: - rename_keys: entries: @@ -80,19 +152,10 @@ pipeline: to_key: "message2" - from_key: "message2" to_key: "message3" - sink: - - stdout: ``` -Add the following contents to the `logs_json.log` file: - -```json -{"message": "hello"} -``` -{% include copy.html %} - -After the `rename_keys` processor runs, the following output appears: +If the processor receives `{"message": "hello"}`, the resulting output is as follows: ```json {"message3": "hello"} -``` \ No newline at end of file +``` diff --git a/_data-prepper/pipelines/configuration/processors/select-entries.md b/_data-prepper/pipelines/configuration/processors/select-entries.md new file mode 100644 index 00000000..d9561e85 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/select-entries.md @@ -0,0 +1,134 @@ +--- +layout: default +title: Select entries +parent: Processors +grand_parent: Pipelines +nav_order: 320 +--- + +# Select entries processor + +The `select_entries` processor selects entries from an OpenSearch Data Prepper event. +Only the selected entries remain in the processed event and while all other entries are removed. However, the processor does not remove any events from the Data Prepper pipeline. + +## Configuration + +You can configure the `select_entries` processor using the following options. + +| Option | Required | Description | +| :--- |:---------| :--- | +| `include_keys` | No | A list of keys to be selected from an event. | +| `include_keys_regex` | No | A regular expression (regex) pattern that matches the keys to be selected from an event. | +| `select_when` | No | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/some-key == "test"`, that is evaluated to determine whether the processor will be executed on the event. If the condition is not met, then the event continues through the pipeline unmodified, with all the original fields present. | + +## Usage + +First, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + ... + .... + processor: + - select_entries: + include_keys: [ "key1", "key2" ] + select_when: '/some_key == "test"' + sink: +``` +{% include copy.html %} + + +For example, when your source contains the following event record: + +```json +{ + "message": "hello", + "key1" : "value1", + "key2" : "value2", + "some_key" : "test" +} +``` + +After processing, only the keys listed in `include_keys` are retained in the event; all other keys are removed: + +```json +{"key1": "value1", "key2": "value2"} +``` + +### Selecting keys using a regex + +The following example shows how to configure the `include_keys_regex` field in the `pipeline.yaml` file: + +```yaml +pipeline: + source: + ... + .... + processor: + - select_entries: + include_keys: [ "key1", "key2" ] + include_keys_regex: ["^ran.*"] + select_when: '/some_key == "test"' + sink: +``` +{% include copy.html %} + +For example, when your source contains the following event record: + +```json +{ + "message": "hello", + "key1" : "value1", + "key2" : "value2", + "some_key" : "test", + "random1": "another", + "random2" : "set", + "random3": "of", + "random4": "values" +} +``` + +The processor retains keys explicitly listed in `include_keys` and any keys matching the` include_keys_regex` pattern, removing all other keys from the event: + +```json +{"key1": "value1", "key2": "value2", "random1": "another", "random2" : "set", "random3": "of", "random4": "values"} +``` + +### Accessing nested fields + +Use `/` to access nested fields. + +For example, when your source contains the following events with nested fields: + +``` +{ + "field1": "abc", + "field2": 123, + "field3": { + "name": "Alice", + "surname": "Smith" + }, + "field4": { + "address": "123 Main St" + } +} +``` + +You can use the following syntax to select a subset of fields: + +``` +pipeline: + source: + ... + .... + processor: + - select_entries: + include_keys: + - field1 + - field2 + - field3/name + select_when: '/field3/surname == "Smith"' + sink: +``` + diff --git a/_data-prepper/pipelines/configuration/processors/service-map.md b/_data-prepper/pipelines/configuration/processors/service-map.md new file mode 100644 index 00000000..a24e7d36 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/service-map.md @@ -0,0 +1,87 @@ +--- +layout: default +title: Service map +parent: Processors +grand_parent: Pipelines +nav_order: 330 +redirect_from: + - /data-prepper/pipelines/configuration/processors/service-map-stateful/ +--- + +# Service map processor + +The `service_map` processor uses OpenTelemetry data to create a distributed service map for visualization in OpenSearch Dashboards. + +The `service_map` processor generates a static service map and doesn't reflect the changes in the topology over time. The new [`otel_apm_service_map` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-apm-service-map/) provides a time-based service map. + +## Configuration + +The following table describes the options you can use to configure the `service_map` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: service_map +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/service-map-stateful/src/main/java/org/opensearch/dataprepper/plugins/processor/ServiceMapProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`window_duration` | No | Integer | The fixed time window during which service map relationships are evaluated, in seconds. Default is `180`. +`db_path` | No | String | The directory in which the processor creates database files that store transient data off heap when processing service map data. Default is `data/service-map/`. + +## Usage + +```yaml +entry-pipeline: + source: + otel_trace_source: + path: "/test/path" + sink: + - pipeline: + name: "raw-pipeline" + - pipeline: + name: "service-map-pipeline" +raw-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - otel_trace_raw: + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-raw +service-map-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - service_map: + window_duration: 60 + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-service-map +``` +{% include copy.html %} + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | The ingress of records to a pipeline component. | +| `recordsOut` | Counter | The egress of records from a pipeline component. | +| `timeElapsed` | Timer | The time elapsed during execution of a pipeline component, in milliseconds. | + +The `service_map` processor includes the following custom metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `spansDbSize` | Gauge | The total size of both current and previous span database windows, in bytes. | +| `spansDbCount` | Gauge | The total number of span entries across both current and previous span database windows. | +| `traceGroupDbSize` | Gauge | The total size of both current and previous trace group database windows, in bytes. | +| `traceGroupDbCount` | Gauge | The total number of trace group entries across both current and previous trace group database windows. | +| `relationshipCount` | Gauge | The total number of unique service map relationships discovered and stored in the relationship state. | diff --git a/_data-prepper/pipelines/configuration/processors/split-event.md b/_data-prepper/pipelines/configuration/processors/split-event.md new file mode 100644 index 00000000..21a7c110 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/split-event.md @@ -0,0 +1,72 @@ +--- +layout: default +title: Split event +parent: Processors +grand_parent: Pipelines +nav_order: 340 +--- + +# Split event processor + +The `split_event` processor is used to split events based on a delimiter and generates multiple events from a user-specified field. + +## Configuration + +The following table describes the configuration options for the `split_event` processor. + +| Option | Type | Description | +|------------------|---------|-----------------------------------------------------------------------------------------------| +| `field` | String | The event field to be split. | +| `delimiter_regex`| String | The regular expression used as the delimiter for splitting the field. | +| `delimiter` | String | The delimiter used for splitting the field. If not specified, the default delimiter is used. | +| `split_when` | String | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) that determines whether the processor is applied to the event. If the condition evaluates to `false`, the event remains unchanged. Default is `null` (all events are processed). | + +# Usage + +To use the `split_event` processor, add the following to your `pipelines.yaml` file: + +```yaml +split-event-pipeline: + source: + http: + processor: + - split_event: + field: query + delimiter: ' ' + sink: + - stdout: +``` +{% include copy.html %} + +When an event contains the following example input: + +```json +{"query" : "open source", "some_other_field" : "abc" } +``` + +The input will be split into multiple events based on the `query` field, with the delimiter set as white space, as shown in the following example: + +```json +{"query" : "open", "some_other_field" : "abc" } +{"query" : "source", "some_other_field" : "abc" } +``` + +## Conditional splitting with split_when + +You can use `split_when` to conditionally apply the split based on event content. This is useful in multi-tenant pipelines where only certain events should be split. In the following example, the `split_event` processor only splits events in which the `body` field contains a new line character. Events without new lines remain unchanged: + +```yaml +split-event-pipeline: + source: + http: + processor: + - split_event: + field: body + delimiter: "\n" + split_when: "contains(/body, \"\n\")" + sink: + - stdout: +``` +{% include copy.html %} + + diff --git a/_data-prepper/pipelines/configuration/processors/split-string.md b/_data-prepper/pipelines/configuration/processors/split-string.md index 3959ae5a..68ba7c41 100644 --- a/_data-prepper/pipelines/configuration/processors/split-string.md +++ b/_data-prepper/pipelines/configuration/processors/split-string.md @@ -1,27 +1,132 @@ --- layout: default -title: split_string +title: Split string parent: Processors grand_parent: Pipelines -nav_order: 100 +nav_order: 350 --- -# split_string +# Split string processor -The `split_string` processor splits a field into an array using a delimiting character and is a [mutate string](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/mutate-string-processors#mutate-string-processors) processor. The following table describes the options you can use to configure the `split_string` processor. +The `split_string` processor splits a field into an array using a delimiting character. + +## Configuration + +The following table describes the options you can use to configure the `split_string` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: split_string +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/mutate-string-processors/src/main/java/org/opensearch/dataprepper/plugins/processor/mutatestring/SplitStringProcessorConfig.java +--> Option | Required | Type | Description :--- | :--- | :--- | :--- -entries | Yes | List | List of entries. Valid values are `source`, `delimiter`, and `delimiter_regex`. -source | N/A | N/A | The key to split. -delimiter | No | N/A | The separator character responsible for the split. Cannot be defined at the same time as `delimiter_regex`. At least `delimiter` or `delimiter_regex` must be defined. -delimiter_regex | No | N/A | The regex string responsible for the split. Cannot be defined at the same time as `delimiter`. At least `delimiter` or `delimiter_regex` must be defined. +`entries` | Yes | List | List of entries. Valid values are `source`, `delimiter`, `delimiter_regex`, and `split_when`. +`source` | N/A | N/A | The key to split. +`delimiter` | No | N/A | The separator character responsible for the split. Cannot be defined at the same time as `delimiter_regex`. At least `delimiter` or `delimiter_regex` must be defined. +`delimiter_regex` | No | N/A | The regex string responsible for the split. Cannot be defined at the same time as `delimiter`. At least `delimiter` or `delimiter_regex` must be defined. +`split_when` | No | String | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `startsWith(/path, "/var")`, that determines whether the entry is applied to the event. By default, the entry is applied to all events. -<!---## Configuration +### Example -Content will be added to this section. +To get started, create the following `pipeline.yaml` file: -## Metrics +```yaml +split-string-all-configs-pipeline: + source: + http: + path: /logs + ssl: false -Content will be added to this section.---> \ No newline at end of file + processor: + - split_string: + # 1) The top-level list of split "entries" + entries: + # 2) Use `source` + `delimiter` (comma) + - source: csv_line + delimiter: "," + + # 3) Another `source` + `delimiter` (pipe) + - source: tags + delimiter: "|" + + # 4) `source` + `delimiter` (slash) to split a path + - source: path + delimiter: "/" + + # 5) `source` + `delimiter_regex` (semicolon + optional spaces) + - source: semicolons + delimiter_regex: ";\\s*" + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: split-string-demo-%{yyyy.MM.dd} + +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + { + "csv_line": "x,y", + "tags": "beta|test", + "path": "usr/local/bin", + "semicolons": "alpha;beta ; gamma" + } + ]' +``` +{% include copy.html %} + +The document stored in OpenSearch contains the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "split-string-demo-2025.10.15", + "_id": "YSAz6JkBrcmuDURMmTeo", + "_score": 1, + "_source": { + "csv_line": [ + "x", + "y" + ], + "tags": [ + "beta", + "test" + ], + "path": [ + "usr", + "local", + "bin" + ], + "semicolons": [ + "alpha", + "beta ", + "gamma" + ] + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/configuration/processors/string-converter.md b/_data-prepper/pipelines/configuration/processors/string-converter.md index 32055791..042fce8d 100644 --- a/_data-prepper/pipelines/configuration/processors/string-converter.md +++ b/_data-prepper/pipelines/configuration/processors/string-converter.md @@ -1,19 +1,26 @@ --- layout: default -title: string_converter +title: String converter parent: Processors grand_parent: Pipelines -nav_order: 105 +nav_order: 360 --- -# string_converter +# String converter processor The `string_converter` processor converts a string to uppercase or lowercase. You can use it as an example for developing your own processor. The following table describes the option you can use to configure the `string_converter` processor. +<!-- +This table is autogenerated. Do not edit it. +- name: string_converter +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/common/src/main/java/org/opensearch/dataprepper/plugins/processor/StringProcessor.java +--> + Option | Required | Type | Description :--- | :--- | :--- | :--- -upper_case | No | Boolean | Whether to convert to uppercase (`true`) or lowercase (`false`). +`upper_case` | No | Boolean | Whether to convert to uppercase (`true`) or lowercase (`false`). <!---## Configuration diff --git a/_data-prepper/pipelines/configuration/processors/substitute-string.md b/_data-prepper/pipelines/configuration/processors/substitute-string.md index 5d18bf6a..6f777cfb 100644 --- a/_data-prepper/pipelines/configuration/processors/substitute-string.md +++ b/_data-prepper/pipelines/configuration/processors/substitute-string.md @@ -1,24 +1,69 @@ --- layout: default -title: substitute_string +title: Substitute string parent: Processors grand_parent: Pipelines -nav_order: 110 +nav_order: 370 --- -# substitute_string +# Substitute string processor -The `substitute_string` processor matches a key's value against a regular expression and replaces all matches with a replacement string. `substitute_string` is a [mutate string](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/mutate-string-processors#mutate-string-processors) processor. +The `substitute_string` processor matches a key's value against a regular expression and replaces all matches with a replacement string. ## Configuration The following table describes the options you can use to configure the `substitute_string` processor. +<!-- +This table is autogenerated. Do not edit it. +- name: substitute_string +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/mutate-string-processors/src/main/java/org/opensearch/dataprepper/plugins/processor/mutatestring/SubstituteStringProcessorConfig.java +--> + Option | Required | Type | Description :--- | :--- | :--- | :--- -entries | Yes | List | List of entries. Valid values are `source`, `from`, and `to`. -source | N/A | N/A | The key to modify. -from | N/A | N/A | The Regex String to be replaced. Special regex characters such as `[` and `]` must be escaped using `\\` when using double quotes and `\ ` when using single quotes. See [Java Patterns](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html) for more information. -to | N/A | N/A | The String to be substituted for each match of `from`. +`entries` | Yes | List | List of entries. Valid values are `source`, `from`, `to`, and `substitute_when`. +`source` | N/A | N/A | The key to modify. +`from` | N/A | N/A | The Regex String to be replaced. Special regex characters such as `[` and `]` must be escaped using `\\` when using double quotes and `\ ` when using single quotes. See [Java Patterns](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html) for more information. +`to` | N/A | N/A | The String to be substituted for each match of `from`. +`substitute_when` | No | String | A [conditional expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `/env == "prod"`, that determines whether the entry is applied to the event. By default, the entry is applied to all events. +### Usage + +To get started, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - substitute_string: + entries: + - source: "message" + from: ":" + to: "-" + sink: + - stdout: +``` +{% include copy.html %} + +Next, create a log file named `logs_json.log`. After that, replace the `path` of the file source in your `pipeline.yaml` file with your file path. For more detailed information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). + +Before you run Data Prepper, the source appears in the following format: + +```json +{"message": "ab:cd:ab:cd"} +``` + +After you run Data Prepper, the source is converted to the following format: + +```json +{"message": "ab-cd-ab-cd"} +``` + +`from` defines which string is replaced, and `to` defines the string that replaces the `from` string. In the preceding example, string `ab:cd:ab:cd` becomes `ab-cd-ab-cd`. If the `from` regex string does not return a match, the key is returned without any changes. diff --git a/_data-prepper/pipelines/configuration/processors/trace-peer-forwarder.md b/_data-prepper/pipelines/configuration/processors/trace-peer-forwarder.md index a73295b8..7278ef92 100644 --- a/_data-prepper/pipelines/configuration/processors/trace-peer-forwarder.md +++ b/_data-prepper/pipelines/configuration/processors/trace-peer-forwarder.md @@ -1,20 +1,20 @@ --- layout: default -title: trace_peer_forwarder +title: Trace Peer Forwarder parent: Processors grand_parent: Pipelines -nav_order: 115 +nav_order: 380 --- -# trace peer forwarder +# Trace Peer Forwarder processor -The `trace_peer_forwarder` processor is used with [peer forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/) to reduce by half the number of events forwarded in a [Trace Analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) pipeline. In Trace Analytics, each event is typically duplicated when it is sent from `otel-trace-pipeline` to `raw-pipeline` and `service-map-pipeline`. When pipelines forward events, this causes the core peer forwarder to send multiple HTTP requests for the same event. You can use `trace peer forwarder` to forward an event once through the `otel-trace-pipeline` instead of `raw-pipeline` and `service-map-pipeline`, which prevents unnecessary HTTP requests. +The `trace_peer_forwarder` processor is used with [Peer Forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/) to reduce by half the number of events forwarded in a [Trace Analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) pipeline. In Trace Analytics, each event is typically duplicated when it is sent from `otel-trace-pipeline` to `raw-pipeline` and `service-map-pipeline`. When pipelines forward events, this causes the core Peer Forwarder to send multiple HTTP requests for the same event. You can use `trace peer forwarder` to forward an event once through the `otel-trace-pipeline` instead of `raw-pipeline` and `service-map-pipeline`, which prevents unnecessary HTTP requests. You should use `trace_peer_forwarder` for Trace Analytics pipelines when you have multiple nodes. ## Usage -To get started with `trace_peer_forwarder`, first configure [peer forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/). Then create a `pipeline.yaml` file and specify `trace peer forwarder` as the processor. You can configure `peer forwarder` in your `data-prepper-config.yaml` file. For more detailed information, see [Configuring Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/#2-configuring-data-prepper). +To get started with `trace_peer_forwarder`, first configure [Peer Forwarder]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/peer-forwarder/). Then create a `pipeline.yaml` file and specify `trace peer forwarder` as the processor. You can configure `peer forwarder` in your `data-prepper-config.yaml` file. For more detailed information, see [Configuring OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/). See the following example `pipeline.yaml` file: @@ -35,7 +35,7 @@ raw-pipeline: pipeline: name: "entry-pipeline" processor: - - otel_trace_raw: + - otel_traces: sink: - opensearch: service-map-pipeline: @@ -44,7 +44,7 @@ service-map-pipeline: pipeline: name: "entry-pipeline" processor: - - service_map_stateful: + - service_map: sink: - opensearch: ``` diff --git a/_data-prepper/pipelines/configuration/processors/translate.md b/_data-prepper/pipelines/configuration/processors/translate.md index d29aa589..86f6102e 100644 --- a/_data-prepper/pipelines/configuration/processors/translate.md +++ b/_data-prepper/pipelines/configuration/processors/translate.md @@ -1,12 +1,12 @@ --- layout: default -title: translate +title: Translate parent: Processors grand_parent: Pipelines -nav_order: 117 +nav_order: 390 --- -# translate +# Translate processor The `translate` processor transforms values in events into preconfigured values. @@ -42,7 +42,7 @@ Then create the following file named `logs_json.log` and replace the `path` in t The `translate` processor configuration in `pipeline.yaml` retrieves the `source` value from the event data and compares it against the keys specified under the `targets`. When a match is found, the processor places the corresponding mapped value into the `target` key provided in the configuration. -When you run Data Prepper with the previous `pipeline.yaml` file, you should receive the following output: +When you run OpenSearch Data Prepper with the previous `pipeline.yaml` file, you should receive the following output: ```json { @@ -90,30 +90,34 @@ You can use the following options to configure the `translate` processor. | Parameter | Required | Type | Description | | :--- | :--- | :--- | :--- | -| mappings | No | List | Defines inline mappings. For more information, see [mappings](#mappings). | -| file | No | Map | Points to the file that contains mapping configurations. For more information, see [file](#file). | +| `mappings` | No | List | Defines inline mappings. For more information, see [mappings](#mappings). | +| `file` | No | Map | Points to the file that contains mapping configurations. For more information, see [file](#file). | +<!-- vale off --> ### mappings +<!-- vale on --> Each item in the `mappings` configuration contains the following options. | Parameter | Required | Type | Description | | :--- | :--- | :--- | :--- | -| source | Yes | String or list | The source field to translate. Can be a string or a list of strings. | -| targets | Yes | List | A list of target field configurations, such as the target field key or translation maps. | +| `source` | Yes | String or list | The source field to translate. Can be a string or a list of strings. | +| `targets` | Yes | List | A list of target field configurations, such as the target field key or translation maps. | Each item in the `targets` configuration contains the following options. | Parameter | Required | Type | Description | | :--- | :--- | :--- | :--- | -| target | Yes | String | The key that specifies the field in the output in which the translated value will be placed. | -| map | No | Map | A list of key-value pairs that define the translations. Each key represents a possible value in the source field, and the corresponding value represents what it should be translated to. For examples, see [map option](#map-option). At least one of `map` and `regex` should be configured. | -| regex | No | Map | A map of keys that defines the translation map. For more options, see [regex option](#regex-option). At least one of `map` and `regex` should be configured. | -| default | No | String | The default value to use when no match is found during translation. | -| type | No | String | Specifies the data type for the target value. | -| translate_when | No | String | Uses a [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) to specify a condition for performing the translation. When specified, the expression will only translate when the condition is met. | +| `target` | Yes | String | The key that specifies the field in the output in which the translated value will be placed. | +| `map` | No | Map | A list of key-value pairs that define the translations. Each key represents a possible value in the source field, and the corresponding value represents what it should be translated to. For examples, see [map option](#map-option). At least one of `map` and `regex` should be configured. | +| `regex` | No | Map | A map of keys that defines the translation map. For more options, see [regex option](#regex-option). At least one of `map` and `regex` should be configured. | +| `default` | No | String | The default value to use when no match is found during translation. | +| `type` | No | String | Specifies the data type for the target value. Valid values are `integer`, `long`, `double`, `big_decimal`, `string`, and `boolean`. Default is `string`. | +| `translate_when` | No | String | Uses a [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) to specify a condition for performing the translation. When specified, the expression will only translate when the condition is met. | +<!-- vale off --> #### map option +<!-- vale on --> You can use the following key types when using the map option: @@ -138,16 +142,20 @@ You can use the following key types when using the map option: When configuring the keys inside the `map` option, do not use any overlapping number ranges or duplicate keys. +<!-- vale off --> #### regex option +<!-- vale on --> You can use the following options with the `regex` option. | Parameter | Required | Type | Description | | :--- | :--- | :--- | :--- | -| patterns | Yes | Map | A map of key-value pairs defining the regex patterns of keys and the value to translate to for each pattern. | -| exact | No | Boolean | Whether to use full string match or partial string match on the regex pattern. If `true`, the pattern is considered a match only when the entire key matches the pattern. Otherwise, the pattern is considered a match when a sub-string of the key matches the pattern. | +| `patterns` | Yes | Map | A map of key-value pairs defining the regex patterns of keys and the value to translate to for each pattern. | +| `exact` | No | Boolean | Whether to use full string match or partial string match on the regex pattern. If `true`, the pattern is considered a match only when the entire key matches the pattern. Otherwise, the pattern is considered a match when a sub-string of the key matches the pattern. Default is `true`. | +<!-- vale off --> ### file +<!-- vale on --> The `file` option in the `translate` processor takes a local YAML file or an Amazon Simple Storage Service (Amazon S3) object containing translation mappings. The file's contents should be in the following format: ```yaml @@ -164,8 +172,8 @@ You can use the following options in the `file` configuration. | Parameter | Required | Type | Description | | :--- | :--- | :--- | :--- | -| name | Yes | String | The full path to a local file or key name for an S3 object. | -| aws | No | Map | The AWS configuration when the file is an S3 object. See the following table for more information. | +| `name` | Yes | String | The full path to a local file or key name for an S3 object. | +| `aws` | No | Map | The AWS configuration when the file is an S3 object. See the following table for more information. | You can use the following options with the `aws` configuration. diff --git a/_data-prepper/pipelines/configuration/processors/trim-string.md b/_data-prepper/pipelines/configuration/processors/trim-string.md index 46b6ad4a..fb2c75c3 100644 --- a/_data-prepper/pipelines/configuration/processors/trim-string.md +++ b/_data-prepper/pipelines/configuration/processors/trim-string.md @@ -1,23 +1,53 @@ --- layout: default -title: trim_string +title: Trim string parent: Processors grand_parent: Pipelines -nav_order: 120 +nav_order: 400 --- -# trim_string +# Trim string processor -The `trim_string` processor removes white space from the beginning and end of a key and is a [mutate string](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/mutate-string-processors#mutate-string-processors) processor. The following table describes the option you can use to configure the `trim_string` processor. +The `trim_string` processor removes white space from the beginning and end of a key. -Option | Required | Type | Description -:--- | :--- | :--- | :--- -with_keys | Yes | List | A list of keys to trim the white space from. +### Configuration -<!---## Configuration +You can configure the `trim_string` processor with the following options. -Content will be added to this section. +Option | Required | Description +:--- | :--- | :--- + `with_keys` | Yes | A list of keys from which to trim the white space. | -## Metrics +### Usage -Content will be added to this section.---> \ No newline at end of file +To get started, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - trim_string: + with_keys: + - "trimField" + sink: + - stdout: +``` +{% include copy.html %} + +Next, create a log file named `logs_json.log`. After that, replace the `path` in the file source of your `pipeline.yaml` file with the correct file path. For more detailed information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). + +Before you run Data Prepper, the source appears in the following format: + +```json +{"trimField": " Space Ship "} +``` + +After you run Data Prepper, the source is converted to the following format: + +```json +{"trimField": "Space Ship"} +``` diff --git a/_data-prepper/pipelines/configuration/processors/truncate.md b/_data-prepper/pipelines/configuration/processors/truncate.md new file mode 100644 index 00000000..73c26cdf --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/truncate.md @@ -0,0 +1,115 @@ +--- +layout: default +title: Truncate +parent: Processors +grand_parent: Pipelines +nav_order: 410 +--- + +# Truncate processor + +The `truncate` processor truncates a key's value at the beginning, the end, or on both sides of the value string, based on the processor's configuration. If the key's value is a list, then each member in the string list is truncated. Non-string members of the list are not truncated. When the `truncate_when` option is provided, input is truncated only when the condition specified is `true` for the event being processed. + +## Configuration + +You can configure the `truncate` processor using the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: truncate +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/truncate-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/truncate/TruncateProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`entries` | Yes | String list | A list of entries to add to an event. +`source_keys` | No | String list | The list of source keys that will be modified by the processor. The default value is an empty list, which indicates that all values will be truncated. +`truncate_when` | No | Conditional expression | A condition that, when met, determines when the truncate operation is performed. +`start_at` | No | Integer | Where in the string value to start truncation. Default is `0`, which specifies to start truncation at the beginning of each key's value. +`length` | No | Integer| The length of the string after truncation. When not specified, the processor will measure the length based on where the string ends. +`recursive` | No | Boolean | If `true` and the value of a source key is an object, the processor truncates the string values of all fields in the object, including fields in nested objects. If `false`, object values are not truncated. Default is `false`. + +Either the `start_at` or `length` options must be present in the configuration in order for the `truncate` processor to run. You can define both values in the configuration in order to further customize where truncation occurs in the string. + +## Usage + +The following examples show how to configure the `truncate` processor in the `pipeline.yaml` file: + +## Example: Minimum configuration + +The following example shows the minimum configuration for the `truncate` processor: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - truncate: + entries: + - source_keys: ["message1", "message2"] + length: 5 + - source_keys: ["info"] + length: 6 + start_at: 4 + - source_keys: ["log"] + start_at: 5 + sink: + - stdout: +``` + +For example, the following event contains several keys with string values: + +```json +{"message1": "hello,world", "message2": "test message", "info", "new information", "log": "test log message"} +``` + +The `truncate` processor produces the following output, where: + +- The `start_at` setting is `0` for the `message1` and `message 2` keys, indicating that truncation will begin at the start of the string, with the string itself truncated to a length of `5`. +- The `start_at` setting is `4` for the `info` key, indicating that truncation will begin at letter `i` of the string, with the string truncated to a length of `6`. +- The `start_at` setting is `5` for the `log` key, with no length specified, indicating that truncation will begin at letter `l` of the string. + +```json +{"message1":"hello", "message2":"test ", "info":"inform", "log": "log message"} +``` + + +## Example: Using `truncate_when` + +The following example configuration shows the `truncate` processor with the `truncate_when` option configured: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - truncate: + entries: + - source_keys: ["message"] + length: 5 + start_at: 8 + truncate_when: '/id == 1' + sink: + - stdout: +``` + +The following example contains two events: + +```json +{"message": "hello, world", "id": 1} +{"message": "hello, world,not-truncated", "id": 2} +``` + +When the `truncate` processor runs on the events, only the first event is truncated because the `id` key contains a value of `1`: + +```json +{"message": "world", "id": 1} +{"message": "hello, world,not-truncated", "id": 2} +``` diff --git a/_data-prepper/pipelines/configuration/processors/uppercase-string.md b/_data-prepper/pipelines/configuration/processors/uppercase-string.md index 88e6e901..c3d03507 100644 --- a/_data-prepper/pipelines/configuration/processors/uppercase-string.md +++ b/_data-prepper/pipelines/configuration/processors/uppercase-string.md @@ -1,23 +1,52 @@ --- layout: default -title: uppercase_string +title: Uppercase string parent: Processors grand_parent: Pipelines -nav_order: 125 +nav_order: 420 --- -# uppercase_string +# Uppercase string processor -The `uppercase_string` processor converts an entire string to uppercase and is a [mutate string](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/mutate-string-processors#mutate-string-processors) processor. The following table describes the option you can use to configure the `uppercase_string` processor. +The `uppercase_string` processor converts the value (a string) of a key from its current case to uppercase. -Option | Required | Type | Description -:--- | :--- | :--- | :--- -with_keys | Yes | List | A list of keys to convert to uppercase. +### Configuration -<!---## Configuration +You can configure the `uppercase_string` processor with the following options. -Content will be added to this section. +Option | Required | Description +:--- | :--- | :--- + `with_keys` | Yes | A list of keys to convert to uppercase. | -## Metrics +### Usage -Content will be added to this section.---> \ No newline at end of file +To get started, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - uppercase_string: + with_keys: + - "uppercaseField" + sink: + - stdout: +``` +{% include copy.html %} + +Next, create a log file named `logs_json.log`. After that, replace the `path` in the file source of your `pipeline.yaml` file with the correct file path. For more detailed information, see [Running Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/running/). + +Before you run Data Prepper, the source appears in the following format: + +```json +{"uppercaseField": "hello"} +``` +After you run Data Prepper, the source is converted to the following format: + +```json +{"uppercaseField": "HELLO"} +``` \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/processors/user-agent.md b/_data-prepper/pipelines/configuration/processors/user-agent.md index 8d2592a5..1d2868ab 100644 --- a/_data-prepper/pipelines/configuration/processors/user-agent.md +++ b/_data-prepper/pipelines/configuration/processors/user-agent.md @@ -1,12 +1,12 @@ --- layout: default -title: user_agent +title: User agent parent: Processors grand_parent: Pipelines -nav_order: 130 +nav_order: 430 --- -# user_agent +# User agent processor The `user_agent` processor parses any user agent (UA) string in an event and then adds the parsing results to the event's write data. diff --git a/_data-prepper/pipelines/configuration/processors/write-json.md b/_data-prepper/pipelines/configuration/processors/write-json.md new file mode 100644 index 00000000..65ad1408 --- /dev/null +++ b/_data-prepper/pipelines/configuration/processors/write-json.md @@ -0,0 +1,135 @@ +--- +layout: default +title: Write JSON +parent: Processors +grand_parent: Pipelines +nav_order: 440 +redirect_from: + - /data-prepper/pipelines/configuration/processors/write_json/ +--- + +# Write JSON processor + + +The `write_json` processor converts an object in an event into a JSON string. You can customize the processor to choose the source and target field names. + +<!-- +This table is autogenerated. Do not edit it. +- name: write_json +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/f0bd8d8e4773dc3d7318c19b8623c2213a099a86/data-prepper-plugins/write-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/write_json/WriteJsonProcessorConfig.java +--> + +Option | Description | Example +:--- | :--- | :--- +`source` | Mandatory field that specifies the name of the field in the event containing the message or object to be parsed. | If `source` is set to `"message"` and the input is `{"message": {"key1":"value1", "key2":{"key3":"value3"}}}`, then the `write_json` processor outputs the event as `"{\"key1\":\"value1\",\"key2\":{\"key3\":\"value3\"}}"`. +`target` | An optional field that specifies the name of the field in which the resulting JSON string should be stored. If `target` is not specified, then the `source` field is used. | `key1` + +## Example + +The following example uses `write_json` twice, first to copy the `details` object into a new JSON string field named `target` and then to overwrite the original `payload` field when target is omitted: + +```yaml +write-json-demo-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + # 1) Copy the nested "details" object into a JSON string at "details_json" + - write_json: + source: details + target: details_json + + # 2) Overwrite "payload" with its JSON-string representation + - write_json: + # no target -> result stored back into "payload" + source: payload + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: write-json-demo-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + { + "message": "order created", + "details": {"order_id": 123, "items": [{"sku": "A1", "qty": 2}], "expedited": true}, + "payload": {"user": {"id": "u-42", "role": "admin"}, "ip": "10.0.0.5"} + }, + { + "message": "order updated", + "details": {"order_id": 124, "items": [{"sku": "B9", "qty": 1}], "expedited": false}, + "payload": {"user": {"id": "u-77", "role": "viewer"}, "ip": "10.0.0.9"} + } + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "write-json-demo-2025.10.15", + "_id" : "YMQA6ZkB1u9wkbZgz8wu", + "_score" : 1.0, + "_source" : { + "message" : "order created", + "details" : { + "order_id" : 123, + "items" : [ + { + "sku" : "A1", + "qty" : 2 + } + ], + "expedited" : true + }, + "payload" : "{\"user\":{\"id\":\"u-42\",\"role\":\"admin\"},\"ip\":\"10.0.0.5\"}", + "details_json" : "{\"order_id\":123,\"items\":[{\"sku\":\"A1\",\"qty\":2}],\"expedited\":true}" + } + }, + { + "_index" : "write-json-demo-2025.10.15", + "_id" : "YcQA6ZkB1u9wkbZgz8wu", + "_score" : 1.0, + "_source" : { + "message" : "order updated", + "details" : { + "order_id" : 124, + "items" : [ + { + "sku" : "B9", + "qty" : 1 + } + ], + "expedited" : false + }, + "payload" : "{\"user\":{\"id\":\"u-77\",\"role\":\"viewer\"},\"ip\":\"10.0.0.9\"}", + "details_json" : "{\"order_id\":124,\"items\":[{\"sku\":\"B9\",\"qty\":1}],\"expedited\":false}" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/configuration/sinks/aws-lambda.md b/_data-prepper/pipelines/configuration/sinks/aws-lambda.md new file mode 100644 index 00000000..a736aeac --- /dev/null +++ b/_data-prepper/pipelines/configuration/sinks/aws-lambda.md @@ -0,0 +1,100 @@ +--- +layout: default +title: AWS Lambda +parent: Sinks +grand_parent: Pipelines +nav_order: 10 +--- + +# AWS Lambda sink + +This page explains how to configure and use [AWS Lambda](https://aws.amazon.com/lambda/) with OpenSearch Data Prepper, enabling Lambda functions to serve as both processors and sinks. + +## Configuration + +Configure the Lambda sink using the following parameters. + +Field | Type | Required | Description +--------------------| ------- | -------- | ---------------------------------------------------------------------------- +`function_name` | String | Yes | The name of the AWS Lambda function to invoke. +`invocation_type` | String | No | Specifies the invocation type. Default is `event`. +`aws.region` | String | Yes | The AWS Region in which the Lambda function is located. +`aws.sts_role_arn` | String | No | The Amazon Resource Name (ARN) of the role to assume before invoking the Lambda function. +`aws.sts_external_id` | String | No | The external ID to use when assuming the role specified in `aws.sts_role_arn`. Must be between 2 and 1,224 characters. +`aws.sts_header_overrides` | Map | No | A map of header overrides to apply to the request that assumes the role specified in `aws.sts_role_arn`. Maximum of 5 headers. +`client.max_retries` | Integer | No | The maximum number of AWS SDK client-level retries for individual API calls. This controls the underlying SDK retry mechanism for network or service errors. Default is `3`. +`client.api_call_timeout` | Duration | No | The total timeout for the entire API call including all retries. Default is `60s`. +`client.api_call_attempt_timeout` | Duration | No | The timeout for each individual retry attempt. If not specified, AWS SDK defaults are used. +`client.connection_timeout` | Duration | No | The SDK connection timeout. Default is `60s`. +`client.read_timeout` | Duration | No | The amount of time the SDK waits for data to be read from an established connection. If not specified, AWS SDK defaults are used. +`client.max_concurrency` | Integer | No | The maximum number of concurrent threads in the client. Default is `200`. +`client.base_delay` | Duration | No | The base delay for the exponential backoff. Default is `100ms`. +`client.max_backoff` | Duration | No | The maximum backoff time for the exponential backoff. Default is `20s`. +`client.retryable_status_codes` | List | No | A list of HTTP status codes that trigger a client-level retry when returned by a Lambda invocation, for example `[500, 502, 503, 504]`. These retries count toward `client.max_retries`. Default is an empty list, in which case Data Prepper retries only throttling errors, Lambda service errors, and network or connection errors. Use for idempotent functions for which retrying transient server-side errors is safe. +`batch` | Object | No | Optional batch settings for Lambda invocations. Contains `key_name` (default: `"events"`) and `threshold` object with `event_count` (default: `100`), `maximum_size` (default: `"5mb"`), and `event_collect_timeout` (default: `10s`). +`dlq` | Object | No | The dead-letter queue (DLQ) configuration for failed invocations. + +#### Example configuration + +```yaml +sink: + - aws_lambda: + function_name: "my-lambda-sink" + invocation_type: "event" + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-lambda-sink-role" + client: + max_retries: 3 + api_call_timeout: PT60S + api_call_attempt_timeout: PT30S # Optional: per-attempt timeout + connection_timeout: PT60S + read_timeout: PT15M # Optional: for long-running Lambda functions + max_concurrency: 200 + base_delay: PT0.1S + max_backoff: PT20S + retryable_status_codes: [500, 502, 503, 504] # Optional: retry these Lambda invocation status codes + batch: + key_name: "events" + threshold: + event_count: 50 + maximum_size: "3mb" + event_collect_timeout: PT5S + dlq: + s3: + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/my-sqs-role" + bucket: "<<your-dlq-bucket-name>>" +``` +{% include copy.html %} + +## Timeout configuration + +The AWS Lambda sink supports multiple timeout layers following AWS SDK best practices: + +- `api_call_timeout`: The total amount of time for the entire API call including all retries. +- `api_call_attempt_timeout`: The time limit for each individual attempt. +- `read_timeout`: The amount of time to wait for data from an established connection. + +For Lambda functions that run for longer than 60 seconds, configure both `api_call_timeout` and `read_timeout` to appropriate values. + +## Usage + +The invocation types are as follows: + +- `event` (Default): Executes functions asynchronously without waiting for responses. +- `request-response` (Sink only): Executes functions synchronously, though responses are not processed. +- `batch`: Automatically groups events based on configured thresholds. +- `dlq`: Supports the DLQ configuration for failed invocations after retry attempts. + +Data Prepper components use an AWS Identity and Access Management (IAM) role assumption, `aws.sts_role_arn`, for secure Lambda function invocation and respect Lambda's concurrency limits during event processing. For more information, see the [AWS Lambda documentation](https://docs.aws.amazon.com/lambda). +{: .note} + +## Developer guide + +Integration tests must be executed separately from the main Data Prepper build. Execute them with the following command: + +```bash +./gradlew :data-prepper-plugins:aws-lambda:integrationTest -Dtests.sink.lambda.region="us-east-1" -Dtests.sink.lambda.functionName="lambda_test_function" -Dtests.sink.lambda.sts_role_arn="arn:aws:iam::123456789012:role/dataprepper-role +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sinks/file.md b/_data-prepper/pipelines/configuration/sinks/file.md index 74af5a18..63780fbe 100644 --- a/_data-prepper/pipelines/configuration/sinks/file.md +++ b/_data-prepper/pipelines/configuration/sinks/file.md @@ -1,12 +1,12 @@ --- layout: default -title: file +title: File parent: Sinks grand_parent: Pipelines nav_order: 45 --- -# file +# File sink Use the `file` sink to create a flat file output, usually a `.log` file. @@ -16,13 +16,14 @@ The following table describes options you can configure for the `file` sink. Option | Required | Type | Description :--- | :--- | :--- | :--- -path | Yes | String | Path for the output file (e.g. `logs/my-transformed-log.log`). +`path` | Yes | String | Path for the output file (e.g. `logs/my-transformed-log.log`). +`append` | No | Boolean | When `true`, the sink file is opened in append mode. ## Usage The following example shows basic usage of the `file` sink: -``` +```yaml sample-pipeline: sink: - file: diff --git a/_data-prepper/pipelines/configuration/sinks/opensearch.md b/_data-prepper/pipelines/configuration/sinks/opensearch.md index b4861f68..d4ad15e3 100644 --- a/_data-prepper/pipelines/configuration/sinks/opensearch.md +++ b/_data-prepper/pipelines/configuration/sinks/opensearch.md @@ -1,12 +1,12 @@ --- layout: default -title: opensearch +title: OpenSearch parent: Sinks grand_parent: Pipelines nav_order: 50 --- -# opensearch +# OpenSearch sink You can use the `opensearch` sink plugin to send data to an OpenSearch cluster, a legacy Elasticsearch cluster, or an Amazon OpenSearch Service domain. @@ -51,44 +51,302 @@ pipeline: The following table describes options you can configure for the `opensearch` sink. Option | Required | Type | Description -:--- | :--- | :--- | :--- -hosts | Yes | List | List of OpenSearch hosts to write to (for example, `["https://localhost:9200", "https://remote-cluster:9200"]`). -cert | No | String | Path to the security certificate (for example, `"config/root-ca.pem"`) if the cluster uses the OpenSearch Security plugin. -username | No | String | Username for HTTP basic authentication. -password | No | String | Password for HTTP basic authentication. -aws_sigv4 | No | Boolean | Default value is false. Whether to use AWS Identity and Access Management (IAM) signing to connect to an Amazon OpenSearch Service domain. For your access key, secret key, and optional session token, Data Prepper uses the default credential chain (environment variables, Java system properties, `~/.aws/credential`, etc.). -aws_region | No | String | The AWS region (for example, `"us-east-1"`) for the domain if you are connecting to Amazon OpenSearch Service. -aws_sts_role_arn | No | String | IAM role that the plugin uses to sign requests sent to Amazon OpenSearch Service. If this information is not provided, the plugin uses the default credentials. -[max_retries](#configure-max_retries) | No | Integer | The maximum number of times the OpenSearch sink should try to push data to the OpenSearch server before considering it to be a failure. Defaults to `Integer.MAX_VALUE`. If not provided, the sink will try to push data to the OpenSearch server indefinitely because the default value is high and exponential backoff would increase the waiting time before retry. -socket_timeout | No | Integer | The timeout, in milliseconds, waiting for data to return (or the maximum period of inactivity between two consecutive data packets). A timeout value of zero is interpreted as an infinite timeout. If this timeout value is negative or not set, the underlying Apache HttpClient would rely on operating system settings for managing socket timeouts. -connect_timeout | No | Integer | The timeout in milliseconds used when requesting a connection from the connection manager. A timeout value of zero is interpreted as an infinite timeout. If this timeout value is negative or not set, the underlying Apache HttpClient would rely on operating system settings for managing connection timeouts. -insecure | No | Boolean | Whether or not to verify SSL certificates. If set to true, certificate authority (CA) certificate verification is disabled and insecure HTTP requests are sent instead. Default value is `false`. -proxy | No | String | The address of a [forward HTTP proxy server](https://en.wikipedia.org/wiki/Proxy_server). The format is "<host name or IP>:<port>". Examples: "example.com:8100", "http://example.com:8100", "112.112.112.112:8100". Port number cannot be omitted. -index | Conditionally | String | Name of the export index. Applicable and required only when the `index_type` is `custom`. -index_type | No | String | This index type tells the Sink plugin what type of data it is handling. Valid values: `custom`, `trace-analytics-raw`, `trace-analytics-service-map`, `management-disabled`. Default value is `custom`. -template_type | No | String | Defines what type of OpenSearch template to use. The available options are `v1` and `index-template`. The default value is `v1`, which uses the original OpenSearch templates available at the `_template` API endpoints. The `index-template` option uses composable [index templates]({{site.url}}{{site.baseurl}}/opensearch/index-templates/) which are available through OpenSearch's `_index_template` API. Composable index types offer more flexibility than the default and are necessary when an OpenSearch cluster has already existing index templates. Composable templates are available for all versions of OpenSearch and some later versions of Elasticsearch. When `distribution_version` is set to `es6`, Data Prepper enforces the `template_type` as `v1`. -template_file | No | String | The path to a JSON [index template]({{site.url}}{{site.baseurl}}/opensearch/index-templates/) file such as `/your/local/template-file.json` when `index_type` is set to `custom`. For an example template file, see [otel-v1-apm-span-index-template.json](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/opensearch/src/main/resources/otel-v1-apm-span-index-template.json). If you supply a template file it must match the template format specified by the `template_type` parameter. -document_id_field | No | String | The field from the source data to use for the OpenSearch document ID (for example, `"my-field"`) if `index_type` is `custom`. -dlq_file | No | String | The path to your preferred dead letter queue file (for example, `/your/local/dlq-file`). Data Prepper writes to this file when it fails to index a document on the OpenSearch cluster. -dlq | No | N/A | DLQ configurations. See [Dead Letter Queues]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/dlq/) for details. If the `dlq_file` option is also available, the sink will fail. -bulk_size | No | Integer (long) | The maximum size (in MiB) of bulk requests sent to the OpenSearch cluster. Values below 0 indicate an unlimited size. If a single document exceeds the maximum bulk request size, Data Prepper sends it individually. Default value is 5. -ism_policy_file | No | String | The absolute file path for an ISM (Index State Management) policy JSON file. This policy file is effective only when there is no built-in policy file for the index type. For example, `custom` index type is currently the only one without a built-in policy file, thus it would use the policy file here if it's provided through this parameter. For more information, see [ISM policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/). -number_of_shards | No | Integer | The number of primary shards that an index should have on the destination OpenSearch server. This parameter is effective only when `template_file` is either explicitly provided in Sink configuration or built-in. If this parameter is set, it would override the value in index template file. For more information, see [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). -number_of_replicas | No | Integer | The number of replica shards each primary shard should have on the destination OpenSearch server. For example, if you have 4 primary shards and set number_of_replicas to 3, the index has 12 replica shards. This parameter is effective only when `template_file` is either explicitly provided in Sink configuration or built-in. If this parameter is set, it would override the value in index template file. For more information, see [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). -distribution_version | No | String | Indicates whether the sink backend version is Elasticsearch 6 or later. `es6` represents Elasticsearch 6. `default` represents the latest compatible backend version, such as Elasticsearch 7.x, OpenSearch 1.x, or OpenSearch 2.x. Default is `default`. -enable_request_compression | No | Boolean | Whether to enable compression when sending requests to OpenSearch. When `distribution_version` is set to `es6`, default is `false`. For all other distribution versions, default is `true`. -serverless | No | Boolean | Determines whether the OpenSearch backend is Amazon OpenSearch Serverless. Set this value to `true` when the destination for the `opensearch` sink is an Amazon OpenSearch Serverless collection. Default is `false`. -serverless_options | No | Object | The network configuration options available when the backend of the `opensearch` sink is set to Amazon OpenSearch Serverless. For more information, see [Serverless options](#serverless-options). +:--- | :--- |:---| :--- +`hosts` | Yes | List | A list of OpenSearch hosts to write to, such as `["https://localhost:9200", "https://remote-cluster:9200"]`. +`cert` | No | String | The path to the security certificate. For example, `"config/root-ca.pem"` if the cluster uses the OpenSearch Security plugin. +`username` | No | String | The username for HTTP basic authentication. +`password` | No | String | The password for HTTP basic authentication. Many Data Prepper examples authenticate as the `admin` user and use the `<custom-admin-password>` placeholder for its [password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#admin-password). You can also authenticate as a user that has only the permissions that the sink requires. For more information, see [OpenSearch cluster security](#opensearch-cluster-security). +`authentication` | No | Object | The authentication configuration for connecting to OpenSearch. Use this object to configure HTTP basic authentication or client certificate authentication. Cannot be used together with the top-level `username` and `password` options. For more information, see [Authentication](#authentication). +`api_token` | No | String | A token that the sink sends as a bearer token in the `Authorization` header of each request to OpenSearch. Ignored when `authentication` is configured. +`aws` | No | AWS | The [AWS](#aws) configuration. +[`max_retries`](#configure-max_retries) | No | Integer | The maximum number of times that the `opensearch` sink should try to push data to the OpenSearch server before considering it to be a failure. Defaults to `Integer.MAX_VALUE`. When not provided, the sink will try to push data to the OpenSearch server indefinitely and exponential backoff will increase the waiting time before a retry. +`aws_sigv4` | No | Boolean | **Deprecated in Data Prepper 2.7.** Default is `false`. Whether to use AWS Identity and Access Management (IAM) signing to connect to an Amazon OpenSearch Service domain. For your access key, secret key, and optional session token, OpenSearch Data Prepper uses the default credential chain (environment variables, Java system properties, `~/.aws/credential`). +`aws_region` | No | String | **Deprecated in Data Prepper 2.7.** The AWS Region (for example, `"us-east-1"`) for the domain when you are connecting to Amazon OpenSearch Service. +`aws_sts_role_arn` | No | String | **Deprecated in Data Prepper 2.7.** The IAM role that the plugin uses to sign requests sent to Amazon OpenSearch Service. If this information is not provided, then the plugin uses the default credentials. +`socket_timeout` | No | Integer | The timeout value, in milliseconds, when waiting for data to be returned (the maximum period of inactivity between two consecutive data packets). A timeout value of `0` is interpreted as an infinite timeout. If this timeout value is negative or not set, then the underlying Apache HttpClient will rely on operating system settings to manage socket timeouts. +`connect_timeout` | No | Integer| The timeout value, in milliseconds, when requesting a connection from the connection manager. A timeout value of `0` is interpreted as an infinite timeout. If this timeout value is negative or not set, the underlying Apache HttpClient will rely on operating system settings to manage connection timeouts. +`insecure` | No | Boolean | Whether or not to verify SSL certificates. If set to `true`, then certificate authority (CA) certificate verification is disabled and insecure HTTP requests are sent instead. Default is `false`. +`proxy` | No | String | The address of the [forward HTTP proxy server](https://en.wikipedia.org/wiki/Proxy_server). The format is `"<hostname or IP>:<port>"` (for example, `"example.com:8100"`, `"http://example.com:8100"`, `"112.112.112.112:8100"`). The port number cannot be omitted. +`path_prefix` | No | String | A path prefix that the sink adds to the path of every request sent to OpenSearch, for example, `/opensearch`. Use this option when OpenSearch is accessible under a subpath, such as behind a reverse proxy. +`index` | Conditionally | String | The name of the export index. Only required when the `index_type` is `custom`. The index can be a plain string, such as `my-index-name`, contain [Java date-time patterns](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html), such as `my-index-%{yyyy.MM.dd}` or `my-%{yyyy-MM-dd-HH}-index`, be formatted using field values, such as `my-index-${/my_field}`, or use [Data Prepper expressions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `my-index-${getMetadata(\"my_metadata_field\"}`. All formatting options can be combined to provide flexibility when creating static, dynamic, and rolling indexes. +`index_type` | No | String | Specifies the type of data the sink plugin handles. Valid values include `custom`, `trace-analytics-raw`, `trace-analytics-plain-raw`, `trace-analytics-plain-raw-v2`, `trace-analytics-service-map`, `otel-v2-apm-service-map`, `log-analytics`, `log-analytics-plain`, `metric-analytics`, `metric-analytics-plain`, `tsdb`, and `management_disabled`. <br><br>To produce Amazon Security Lake–compliant data from the `otel_logs_source` with `output_format: otel`, set `index_type` to `log-analytics-plain`. <br>For `otel_metrics_source` with `output_format: otel`, set `index_type` to `metric-analytics-plain`. <br>For `otel_trace_source` with `output_format: otel`, set `index_type` to `trace-analytics-plain-raw`. <br><br>The `trace-analytics-plain-raw-v2` value writes spans to the `otel-v2-apm-span` index alias using a composable index template. It is not supported when `distribution_version` is `es6`. <br><br>Default is `custom`. -### Serverless options + +`template_type` | No | String | Defines what type of OpenSearch template to use. Available options are `v1` and `index-template`. The default value is `v1`, which uses the original OpenSearch templates available at the `_template` API endpoints. The `index-template` option uses composable [index templates]({{site.url}}{{site.baseurl}}/opensearch/index-templates/), which are available through the OpenSearch `_index_template` API. Composable index types offer more flexibility than the default and are necessary when an OpenSearch cluster contains existing index templates. Composable templates are available for all versions of OpenSearch and some later versions of Elasticsearch. When `distribution_version` is set to `es6`, Data Prepper enforces the `template_type` as `v1`. +`template_file` | No | String | The path to a JSON [index template]({{site.url}}{{site.baseurl}}/opensearch/index-templates/) file, such as `/your/local/template-file.json`, when `index_type` is set to `custom`. For an example template file, see [otel-v1-apm-span-index-template.json](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/opensearch/src/main/resources/otel-v1-apm-span-index-template.json). If you supply a template file, then it must match the template format specified by the `template_type` parameter. +`template_content` | No | JSON | Contains all the inline JSON found inside of the index [index template]({{site.url}}{{site.baseurl}}/opensearch/index-templates/). For an example of template content, see [the example template content](#example-with-template_content-and-actions). +`component_templates` | No | List | A list of [component template]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/#reusing-configuration-with-component-templates) names to add to the `composed_of` list of the index template that Data Prepper creates. The names are added after any component templates that the index template already lists, whether the index template comes from `template_file`, `template_content`, or the built-in template for the `index_type`. OpenSearch applies component templates in order, and settings and mappings in the index template itself take precedence over all of them. Data Prepper does not create these component templates, so they must exist in the cluster before the pipeline starts. Requires `template_type` to be `index-template`. The `trace-analytics-plain-raw-v2` index type always uses `index-template`, so it does not require setting `template_type`. Cannot be used when `index_type` is `management_disabled`. +`document_id_field` | No | String | **Deprecated in Data Prepper 2.7 in favor of `document_id`.** The field from the source data to use for the OpenSearch document ID (for example, `"my-field"`) if `index_type` is `custom`. +`document_id` | No | String | A format string to use as the `_id` in OpenSearch documents. To specify a single field in an event, use `${/my_field}`. You can also use Data Prepper expressions to construct the `document_id`, for example, `${getMetadata(\"some_metadata_key\")}`. These options can be combined into more complex formats, such as `${/my_field}-test-${getMetadata(\"some_metadata_key\")}`. +`document_version` | No | String | A format string to use as the `_version` in OpenSearch documents. To specify a single field in an event, use `${/my_field}`. You can also use Data Prepper expressions to construct the `document_version`, for example, `${getMetadata(\"some_metadata_key\")}`. These options can be combined into more complex versions, such as `${/my_field}${getMetadata(\"some_metadata_key\")}`. The `document_version` format must evaluate to a long type and can only be used when `document_version_type` is set to either `external` or `external_gte`. +`document_version_type` | No | String | The document version type for index operations. Must be one of `external`, `external_gte`, or `internal`. If set to `external` or `external_gte`, then `document_version` is required. +`dlq_file` | No | String | The path to your preferred dead letter queue file (such as `/your/local/dlq-file`). Data Prepper writes to this file when it fails to index a document on the OpenSearch cluster. +`dlq` | No | N/A | [DLQ configurations]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/dlq/). +`bulk_size` | No | Integer (long) | The maximum size (in MiB) of bulk requests sent to the OpenSearch cluster. Values below `0` indicate an unlimited size. If a single document exceeds the maximum bulk request size, then Data Prepper sends each request individually. Default value is `5`. +`estimate_bulk_size_using_compression` | No | Boolean | Whether to estimate the size of a bulk request using its compressed size when determining whether the request has reached `bulk_size`. The sink compresses the partially filled request locally to calculate an approximate size. Ignored when request compression is disabled (see `enable_request_compression`). Default is `false`. +`max_local_compressions_for_estimation` | No | Integer | The maximum number of times that the sink compresses a partially filled bulk request to estimate its size. Higher values improve the accuracy of the estimate but reduce performance. Applies only when `estimate_bulk_size_using_compression` is `true`. Default is `2`. +`ism_policy_file` | No | String | The absolute file path for an Index State Management (ISM) policy JSON file. This policy file is effective only when there is no built-in policy file for the index type. For example, the `custom` index type is currently the only type without a built-in policy file, so it will use this policy file if it is provided through this parameter. For more information about the policy JSON file, see [ISM policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/). +`number_of_shards` | No | Integer | The number of primary shards that an index should have on the destination OpenSearch server. This parameter is effective only when `template_file` is either explicitly provided in the sink configuration or built in. If this parameter is set, then it will override the value in the index template file. For more information, see [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). +`number_of_replicas` | No | Integer | The number of replica shards that each primary shard should have on the destination OpenSearch server. For example, if you have 4 primary shards and set `number_of_replicas` to `3`, then the index has 12 replica shards. This parameter is effective only when `template_file` is either explicitly provided in the sink configuration or built in. If this parameter is set, then it will override the value in the index template file. For more information, see [Create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). +`distribution_version` | No | String | Indicates whether the backend version of the sink is Elasticsearch 6 or later. `es6` represents Elasticsearch 6. `default` represents the latest compatible backend version, such as Elasticsearch 7.x, OpenSearch 1.x, or OpenSearch 2.x. Default is `default`. +`enable_request_compression` | No | Boolean | Whether to enable compression when sending requests to OpenSearch. When `distribution_version` is set to `es6`, default is `false`. For all other distribution versions, default is `true`. +`action` | No | String | The OpenSearch bulk action to use for documents. Must be one of `create`, `index`, `update`, `upsert`, or `delete`. Default is `index`. +`actions` | No | List | A [list of actions](#actions) that can be used as an alternative to `action`, which reads as a switch case statement that conditionally determines the bulk action to take for an event. +`script` | No | Object | A [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/) script that OpenSearch runs to update documents. Can be used only when `action` is set to `update`, `upsert`, or an expression. For more information, see [Script](#script). +`flush_timeout` | No | Long | A long class that contains the amount of time, in milliseconds, to try packing a bulk request up to the `bulk_size` before flushing the request. If this timeout expires before a bulk request has reached the `bulk_size`, the request will be flushed. Set to `-1` to disable the flush timeout and instead flush whatever is present at the end of each batch. Default is `60,000`, or 1 minute. +`normalize_index` | No | Boolean | If true, then the OpenSearch sink will try to create dynamic index names. Index names with format options specified in `${})` are valid according to the [index naming restrictions]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/#index-naming-restrictions). Any invalid characters will be removed. Default value is `false`. +`routing` | No | String | A string used as a hash for generating the `shard_id` for a document when it is stored in OpenSearch. Each incoming record is searched. When present, the string is used as the routing field for the document. When not present, the default routing mechanism (`document_id`) is used by OpenSearch when storing the document. Supports formatting with fields in events and [Data Prepper expressions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `${/my_field}-test-${getMetadata(\"some_metadata_key\")}`. +`document_root_key` | No | String | The key in the event that will be used as the root in the document. The default is the root of the event. If the key does not exist, then the entire event is written as the document. If `document_root_key` is of a basic value type, such as a string or integer, then the document will have a structure of `{"data": <value of the document_root_key>}`. +`serverless` | No | Boolean | **Deprecated in Data Prepper 2.7. Use this option with the `aws` configuration instead.** Determines whether the OpenSearch backend is Amazon OpenSearch Serverless. Set this value to `true` when the destination for the `opensearch` sink is an Amazon OpenSearch Serverless collection. Default is `false`. +`serverless_options` | No | Object | **Deprecated in Data Prepper 2.7. Use this option with the `aws` configuration instead.** The network configuration options available when the backend of the `opensearch` sink is set to Amazon OpenSearch Serverless. For more information, see [Serverless options](#serverless-options). +`query_lookup` | No | Object | Configuration for querying existing documents before indexing to prevent duplicates. For more information, see [Query lookup](#query-lookup). +`pull_indexing` | No | Object | Configures the sink to write documents to a streaming platform from which an OpenSearch index ingests them using pull-based ingestion. When this option is set, the sink does not send bulk requests to OpenSearch. This is an experimental feature. For more information, see [Pull-based indexing](#pull-based-indexing). + + +## Authentication + +The `authentication` object supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`username` | No | String | The username for HTTP basic authentication. +`password` | No | String | The password for HTTP basic authentication. +`client_certificate` | Conditionally | String | The client certificate used for TLS client certificate authentication, in PEM format. Specify either the path to a PEM file or the PEM content, starting with `-----BEGIN`. Required if `client_key` is set. +`client_key` | Conditionally | String | The unencrypted private key for the client certificate, in PEM format. Specify either the path to a PEM file or the PEM content, starting with `-----BEGIN`. Required if `client_certificate` is set. + +The following example configures client certificate authentication: + +```yaml +pipeline: + ... + sink: + - opensearch: + hosts: ["https://localhost:9200"] + cert: path/to/root-ca.pem + index: my-index + authentication: + client_certificate: path/to/client.pem + client_key: path/to/client-key.pem +``` +{% include copy.html %} + +## Query lookup + +The `query_lookup` configuration enables deduplication by querying OpenSearch for existing documents before indexing new ones. This feature helps prevent duplicates in two scenarios: + +1. **Conditional querying**: Query for documents based on a condition before indexing them. +2. **Error-based querying**: Query for documents when bulk operation errors occur that could result in partial success, such as socket timeouts or 500 internal server errors. + +### Query lookup options + +The `query_lookup` object supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`query_when` | Yes | String | A [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) that determines which documents qualify for querying before indexing. For example, `getMetadata("potential_duplicate") == true` will only query documents with that metadata field set to `true`. +`query_term` | Yes | String | The unique field of the document that will be used to query for existing documents in OpenSearch. This is typically an ID field. +`query_on_bulk_errors` | No | Boolean | When set to `true`, documents that encounter recoverable bulk operation errors (such as socket timeouts or 500 errors) will be queried rather than immediately retried. This helps prevent duplicates when the initial indexing request may have partially succeeded. Default is `false`. +`query_duration` | No | Duration | The amount of time to query for a given document before indexing it. Use ISO 8601 duration format, such as `PT5M` for 5 minutes. Default is `PT3M`. +`async_limit` | No | Integer | The maximum number of documents that can be queried concurrently before blocking the processor worker threads. Default is `5000`. + +### Query lookup example + +The following example configuration queries for documents with a `potential_duplicate` metadata field before indexing: + +```yaml +pipeline: + ... + sink: + opensearch: + hosts: ["https://localhost:9200"] + username: YOUR_USERNAME + password: YOUR_PASSWORD + index: my-index + query_lookup: + query_when: 'getMetadata("potential_duplicate") == true' + query_term: 'document_id' + query_on_bulk_errors: true + query_duration: PT5M + async_limit: 5000 +``` + +In this configuration: +- Documents with the `potential_duplicate` metadata set to `true` are queried before indexing. +- The `document_id` field is used as the unique identifier for querying. +- If a bulk operation encounters errors like socket timeouts or 500 errors, the affected documents are queried rather than immediately retried. +- Documents are queried for up to 5 minutes before being indexed. +- Up to 5,000 documents can be queried concurrently. + +If a document already exists in OpenSearch, it will be dropped and the event handle will be released, preventing duplicates. + +<!-- vale off --> +## aws +<!-- vale on --> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon SQS and Amazon S3. Defaults to `null`, which will use [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_header_overrides` | No | Map | A map of header overrides that the IAM role assumes for the sink plugin. +`sts_external_id` | No | String | The external ID to attach to AssumeRole requests from AWS STS. +`serverless` | No | Boolean | Determines whether the OpenSearch backend is Amazon OpenSearch Serverless. Set this value to `true` when the destination for the `opensearch` sink is an Amazon OpenSearch Serverless collection. Default is `false`. +`serverless_options` | No | Object | The network configuration options available when the backend of the `opensearch` sink is set to Amazon OpenSearch Serverless. For more information, see [Serverless options](#serverless-options). +`resource_name` | No | String | The name of the Amazon OpenSearch Service domain or the ID of the Amazon OpenSearch Serverless collection in which the sink creates the index when `semantic_enrichment` is configured. If not set, the sink derives the domain name or collection ID from the first host in `hosts`. +`semantic_enrichment` | No | Object | The fields for which the sink enables semantic enrichment when it creates the index. For more information, see [Semantic enrichment](#semantic-enrichment). + +### Semantic enrichment + +When `aws.semantic_enrichment` is configured, the sink creates the index specified in `index` before writing documents to it. The sink creates the index using the Amazon OpenSearch Service or Amazon OpenSearch Serverless `CreateIndex` API and maps each listed field as a `text` field that has semantic enrichment enabled. If the index already exists, the sink does not modify it. Semantic enrichment is available only for Amazon OpenSearch Service domains and Amazon OpenSearch Serverless collections. + +The `semantic_enrichment` object supports the following option. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`fields` | Yes | List | The fields for which to enable semantic enrichment. + +Each object in the `fields` list supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`name` | Yes | String | The name of the field. +`language` | Yes | String | The language of the field content. Valid values are `english` and `multilingual`. + +The following example creates an index in which the `title` and `description` fields have semantic enrichment enabled: + +```yaml +pipeline: + ... + sink: + - opensearch: + hosts: ["https://search-my-domain-abc123.us-east-1.es.amazonaws.com"] + index: my-index + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/PipelineRole + resource_name: my-domain + semantic_enrichment: + fields: + - name: title + language: english + - name: description + language: multilingual +``` +{% include copy.html %} + +<!-- vale off --> +## actions +<!-- vale on --> + +The following options can be used inside the `actions` option. + +Option | Required | Type | Description +:--- |:---| :--- | :--- +`type` | Yes | String | The type of bulk action to use if the `when` condition evaluates to true. Must be either `create`, `index`, `update`, `upsert`, or `delete`. +`when` | No | String | A [Data Prepper expression]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/) that conditionally evaluates whether an event will be sent to OpenSearch using the bulk action configured in `type`. When empty, the bulk action will be chosen automatically when the event is sent to OpenSearch. + + +## Script + +The `script` object configures a [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/) script that OpenSearch runs for each update operation. The script receives the event as the `params.doc` parameter. When `action` is `update`, the script runs on the existing document. When `action` is `upsert`, the sink sends a scripted upsert, so the script also runs when the document does not exist. In this case, the event is used as the initial document. + +The `script` object supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The Painless script. Lines that start with `//` are removed before the script is sent to OpenSearch. +`params` | No | Map | The parameters to pass to the script, which can access them as `params.<parameter_name>`. String values can contain format expressions, such as `${/my_field}`, which are evaluated for each event. Do not name a parameter `doc` because it replaces the event in `params.doc`. + +The following example adds the value of the `inc` parameter to the `counter` field of an existing document and records the `source` value of the latest event: + +```yaml +pipeline: + ... + sink: + - opensearch: + hosts: ["https://localhost:9200"] + index: my-index + document_id: "${/id}" + action: upsert + script: + source: | + if (ctx._source.counter == null) { ctx._source.counter = params.doc.counter; } + else { ctx._source.counter += params.inc; } + ctx._source.last_source = params.source_name; + params: + inc: 5 + source_name: "${/source}" +``` +{% include copy.html %} + +## Pull-based indexing + +This is an experimental feature and is not recommended for use in a production environment. +{: .warning} + +When `pull_indexing` is configured, the sink writes documents to a streaming platform, such as Apache Kafka, and the OpenSearch index ingests them using [pull-based ingestion]({{site.url}}{{site.baseurl}}/api-reference/document-apis/pull-based-ingestion/). When the sink starts, it reads the number of shards and the `ingestion_source.param.topic` setting of the index and creates the topic if it does not exist. The topic contains one partition for each shard. The sink writes each document to the partition that corresponds to the shard to which OpenSearch routes the document, based on `routing` or the document ID. + +### Prerequisites + +Before you configure pull-based indexing, complete the following steps: + +1. Create the index specified in `index` and configure it for pull-based ingestion. The sink does not create the index. +1. Enable experimental features in `data-prepper-config.yaml`: + + ```yaml + experimental: + enable_all: true + ``` + {% include copy.html %} + +### Configuration + +Pull-based indexing has the following requirements: + +- The `index` option must contain a static index name. +- The `action` option and the `type` of each entry in `actions` must be `index`, `create`, or `delete`. +- The `document_id` and `document_version` options must be set. Events for which the sink cannot determine a document ID or version are not written. + +The `pull_indexing` object supports the following option. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`engine` | Yes | Object | The streaming platform to which the sink writes documents. The only supported engine is `kafka`. + +The `kafka` engine supports the following option. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`bootstrap_servers` | Yes | List | The host and port pairs of the Kafka brokers, for example, `["kafka-broker:9092"]`. + +The following example writes documents to the Kafka topic configured for the `my-pull-index` index: + +```yaml +pipeline: + ... + sink: + - opensearch: + hosts: ["https://localhost:9200"] + index: my-pull-index + document_id: "${/id}" + document_version: "${/version}" + document_version_type: external + action: index + pull_indexing: + engine: + kafka: + bootstrap_servers: ["kafka-broker:9092"] +``` +{% include copy.html %} + +## Serverless options The following options can be used in the `serverless_options` object. Option | Required | Type | Description :--- | :--- | :---| :--- -network_policy_name | Yes | String | The name of the network policy to create. -collection_name | Yes | String | The name of the Amazon OpenSearch Serverless collection to configure. -vpce_id | Yes | String | The virtual private cloud (VPC) endpoint to which the source connects. +`network_policy_name` | Yes | String | The name of the network policy to create. +`collection_name` | Yes | String | The name of the Amazon OpenSearch Serverless collection to configure. +`vpce_id` | Yes | String | The virtual private cloud (VPC) endpoint to which the source connects. ### Configure max_retries @@ -98,6 +356,41 @@ If you specify `max_retries` and a pipeline has a [dead-letter queue (DLQ)]({{si If you don't specify `max_retries`, only data that is rejected by sinks is written to the DLQ. Pipelines continue to try to write all other data to the sinks. +### Error handling with acknowledgments + +When pipelines have [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/#end-to-end-acknowledgments) enabled, error handling is controlled by two key configurations: +* [Dead-letter queue (DLQ)]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/dlq/) +* [`max_retries`](#configure-max_retries) + +#### DLQ configuration (strongly recommended) + +The OpenSearch sink acknowledges events only when: +* Successfully sent to OpenSearch. +* Successfully sent to DLQ. + +Without a DLQ configured: +* Failed events remain unacknowledged. +* Source must handle retries. +* Risk of infinite reprocessing for non-retryable errors. + +#### Example: S3 source with acknowledgments + +Consider an [S3 source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/) with acknowledgments enabled: + +**Without DLQ**: +* A single failed event prevents acknowledgment of an entire S3 object. +* The entire S3 object requires reprocessing. +* Non-retryable errors can cause infinite reprocessing ("poison pill"). + +**With `max_retries` but no DLQ**: +* Reaching `max_retries` still prevents acknowledgment. +* Results in unnecessary reprocessing of entire S3 objects. + +**Best practice**---always configure a DLQ when using acknowledgments to: +* Prevent infinite reprocessing. +* Handle non-retryable errors gracefully. +* Minimize unnecessary reprocessing. + ## OpenSearch cluster security In order to send data to an OpenSearch cluster using the `opensearch` sink plugin, you must specify your username and password within the pipeline configuration. The following example `pipelines.yaml` file demonstrates how to specify admin security credentials: @@ -106,7 +399,7 @@ In order to send data to an OpenSearch cluster using the `opensearch` sink plugi sink: - opensearch: username: "admin" - password: "admin" + password: "<custom-admin-password>" ... ``` @@ -118,13 +411,17 @@ Alternately, rather than admin credentials, you can specify the credentials of a - `indices:admin/template/get` - `indices:admin/template/put` +If the target is an OpenSearch data stream, the following permission is required by the data stream detector: + +- `indices:admin/data_stream/get` + ### Index permissions - Index: `otel-v1*`; Index permission: `indices_all` - Index: `.opendistro-ism-config`; Index permission: `indices_all` - Index: `*`; Index permission: `manage_aliases` -For instructions on how to map users to roles, see [Map users to roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/#map-users-to-roles). +For instructions on how to map users to roles, see [Map users to roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/#mapping-users-to-roles). ## Amazon OpenSearch Service domain security @@ -191,7 +488,6 @@ If your domain uses a master user in the internal user database, specify the mas sink: opensearch: hosts: ["https://your-fgac-amazon-opensearch-service-endpoint"] - aws_sigv4: false username: "master-username" password: "master-password" ``` @@ -302,3 +598,53 @@ log-pipeline: sts_role_arn: "arn:aws:iam::<AccountId>:role/PipelineRole" region: "us-east-1" ``` + +### Example with template_content and actions + +The following example pipeline contains both `template_content` and a list of conditional `actions`: + +```yaml +log-pipeline: + source: + http: + processor: + - date: + from_time_received: true + destination: "@timestamp" + sink: + - opensearch: + hosts: [ "https://<serverless-public-collection-endpoint>" ] + index: "my-serverless-index" + template_type: index-template + template_content: > + { + "template" : { + "mappings" : { + "properties" : { + "Data" : { + "type" : "binary" + }, + "EncodedColors" : { + "type" : "binary" + }, + "Type" : { + "type" : "keyword" + }, + "LargeDouble" : { + "type" : "double" + } + } + } + } + } + # index is the default case + actions: + - type: "delete" + when: '/operation == "delete"' + - type: "update" + when: '/operation == "update"' + - type: "index" + aws: + sts_role_arn: "arn:aws:iam::<AccountId>:role/PipelineRole" + region: "us-east-1" +``` diff --git a/_data-prepper/pipelines/configuration/sinks/otlp.md b/_data-prepper/pipelines/configuration/sinks/otlp.md new file mode 100644 index 00000000..ba942eee --- /dev/null +++ b/_data-prepper/pipelines/configuration/sinks/otlp.md @@ -0,0 +1,218 @@ +--- +layout: default +title: OTLP +parent: Sinks +grand_parent: Pipelines +nav_order: 52 +--- + +# OTLP sink + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the [`otlp` sink plugin](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/otlp-sink) in the OpenSearch Data Prepper repository. +{: .warning} + +The `otlp` sink exports traces, metrics, and logs to an endpoint that accepts [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otlp/) requests over HTTP. It encodes each batch as Protobuf, compresses it with `gzip`, and signs the request with AWS Signature Version 4 (SigV4). To send data to an endpoint that accepts SigV4-signed requests, set `service_name` to that endpoint's signing name. Because the sink signs every request and requires AWS credentials, it is designed for endpoints that use AWS authentication. + +The sink determines the signal type of each event from the event's type: span events are exported as OTLP trace data, metric events as metric data, and log events as log data. The sink accepts only span, metric, and log events, such as the events produced by the [`otlp` source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otlp-source/). Any other event is dropped and counted in the `failedRecordsCount` metric. + +The sink maintains a separate buffer for each signal type, so each signal type is batched independently. Each request contains a batch of events of a single signal type, assembled according to the [threshold configuration](#threshold-configuration). A batch can contain spans from many traces, and the spans of a single trace can be sent in different requests. + +Each sink sends all signals to the single URL configured in `endpoint`. Because OTLP/HTTP endpoints use a different path for each signal (`/v1/traces`, `/v1/metrics`, and `/v1/logs`), configure one `otlp` sink per signal and use [conditional routing]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#conditional-routing) when a pipeline carries more than one signal type. For an example, see [Routing mixed signal types](#routing-mixed-signal-types). + +## Prerequisites + +To use the `otlp` sink, enable the experimental `otlp` plugin in `data-prepper-config.yaml`: + +```yaml +experimental: + enabled_plugins: + sink: + - otlp +``` +{% include copy.html %} + +## Usage + +The following examples configure the `otlp` sink for different scenarios. + +### Sending traces to AWS X-Ray + +The following pipeline sends spans to the AWS X-Ray OTLP endpoint. Because the endpoint host contains the Region, `aws.region` can be omitted: + +```yaml +trace-pipeline: + source: + otlp: + ssl: false + sink: + - otlp: + endpoint: "https://xray.us-east-1.amazonaws.com/v1/traces" + aws: + sts_role_arn: "arn:aws:iam::123456789012:role/data-prepper-otlp-role" +``` +{% include copy.html %} + +### Configuring custom signing values and headers + +The following pipeline sends logs to an endpoint that accepts SigV4-signed requests but is not AWS X-Ray. It sets `service_name` to the endpoint's Signature Version 4 signing name, sets `aws.region` explicitly because the endpoint host does not contain a Region, and adds a custom header to every request: + +```yaml +log-pipeline: + source: + http: + port: 2021 + path: "/logs" + sink: + - otlp: + endpoint: "https://my-otlp-endpoint.example.com:443/v1/logs" + service_name: "my-service" + max_retries: 3 + threshold: + max_events: 100 + flush_timeout: 5s + aws: + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/data-prepper-otlp-role" + additional_headers: + x-custom-header: "my-value" +``` +{% include copy.html %} + +### Routing mixed signal types + +The following pipeline receives all three signal types from an [`otlp` source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otlp-source/) and routes each one to a sink configured with the matching signal path: + +```yaml +otlp-pipeline: + source: + otlp: + ssl: false + route: + - traces: 'getEventType() == "TRACE"' + - metrics: 'getEventType() == "METRIC"' + - logs: 'getEventType() == "LOG"' + sink: + - otlp: + routes: + - traces + endpoint: "https://xray.us-east-1.amazonaws.com/v1/traces" + aws: + region: "us-east-1" + - otlp: + routes: + - metrics + endpoint: "https://my-otlp-endpoint.example.com/v1/metrics" + service_name: "my-service" + aws: + region: "us-east-1" + - otlp: + routes: + - logs + endpoint: "https://my-otlp-endpoint.example.com/v1/logs" + service_name: "my-service" + aws: + region: "us-east-1" +``` +{% include copy.html %} + +## Configuration + +Use the following options to configure the `otlp` sink. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`endpoint` | Yes | String | The OTLP/HTTP endpoint URL, including the signal path, for example, `https://xray.us-east-1.amazonaws.com/v1/traces`. +`aws` | Yes | [AWS configuration](#aws-configuration) | The AWS configuration used for SigV4 signing. All requests are signed, so this block must be present, even when it is empty. +`service_name` | No | String | The SigV4 signing name used for requests, for example, `logs` or `osis`. Default is `xray`. +`max_retries` | No | Integer | The maximum number of retries for a failed request. The sink retries the `429`, `502`, `503`, and `504` status codes using exponential backoff with jitter. Default is `5`. +`threshold` | No | [Threshold configuration](#threshold-configuration) | The batching and flushing configuration. +`additional_headers` | No | Map | The HTTP headers added to every request. Default is an empty map. + +The `aws` block is required in this release. Support for OTLP endpoints that do not use Signature Version 4 signing is not yet available. +{: .note} + +Headers in `additional_headers` are added after the request is signed, so they are not part of the Signature Version 4 signature. To keep signing valid, the sink rejects the `Authorization`, `Host`, `Content-Type`, `Content-Encoding`, and `Content-Length` headers and any header whose name begins with `x-amz-`. A pipeline that configures one of these headers fails to start. +{: .note} + +## Threshold configuration + +The sink flushes a batch when any threshold is reached. Use the following options to configure batching and flushing. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`max_events` | No | Integer | The maximum number of events in a batch. Set to `0` to flush based only on `max_batch_size` and `flush_timeout`. Default is `512`. +`max_batch_size` | No | String | The maximum size of the uncompressed batch payload. Default is `1mb`. +`flush_timeout` | No | Duration | The maximum amount of time to wait before flushing a batch. Must be at least `1ms`. Default is `200ms`. + +The sink sets the HTTP response timeout to twice the `flush_timeout` value, within a range of 3 to 10 seconds. For a `flush_timeout` of 1.5 seconds or less, the response timeout is 3 seconds. For a `flush_timeout` between 1.5 and 5 seconds, the response timeout is twice the `flush_timeout`. For a `flush_timeout` of 5 seconds or more, the response timeout is 10 seconds. +{: .note} + +Each signal type uses its own queue of events waiting to be batched. The queue capacity is 10 times `max_events`, with a minimum of 2,000 events, so the queue grows when you increase `max_events`. When a queue is full, the sink applies backpressure to the pipeline and does not drop events. + +## AWS configuration + +Use the following options in the `aws` block to configure credentials and signing. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region used for SigV4 signing and credentials. If not specified, the sink parses the Region from the hostname in `endpoint` and fails at startup if the hostname does not contain a valid Region. +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests. Defaults to `null`, which uses the [default credential provider chain](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | The external ID to use when assuming the AWS STS role. + +## Limitations + +The `otlp` sink has the following limitations: + +- Traces can be sent only to AWS X-Ray-compatible endpoints (`https://xray.<region>.amazonaws.com/v1/traces`). Metrics and logs can be sent to any OTLP endpoint that accepts SigV4-signed Protobuf requests. +- Only OTLP over HTTP is supported. OTLP over gRPC is not supported. +- When the retries configured in `max_retries` are exhausted, the batch is dropped and the failure is logged and counted. Because the sink retries a batch after a retryable status code, the endpoint can receive the same batch more than once. Dead-letter queue (DLQ) delivery is not supported. + +## Metrics + +The `otlp` sink provides the following metrics in addition to the [common sink metrics]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/monitoring/). + +### Counters + +The following counters track the records and responses processed by the `otlp` sink. + +Metric | Description +:--- | :--- +`recordsOut` | The number of records that the endpoint accepted. +`rejectedRecordsCount` | The number of records that the endpoint rejected or that could not be delivered. +`failedRecordsCount` | The number of records that the sink could not process, including events that are not spans, metrics, or logs. +`rejectedSpansCount`, `rejectedMetricsCount`, `rejectedLogsCount` | The number of rejected records for each signal type. +`failedSpansCount`, `failedMetricsCount`, `failedLogsCount` | The number of failed records for each signal type. +`errorsCount` | The number of unexpected worker thread errors. +`http2xxResponses`, `http4xxResponses`, `http5xxResponses` | The number of responses received for each status code category. + +### Timers + +The following timer tracks request latency in the `otlp` sink. + +Metric | Description +:--- | :--- +`httpLatency` | The amount of time taken to receive a response from the endpoint. + +### Distribution summaries + +The following distribution summaries track payload sizes in the `otlp` sink. + +Metric | Description +:--- | :--- +`payloadSize` | The distribution of uncompressed request payload sizes, in bytes. +`payloadGzipSize` | The distribution of `gzip`-compressed request payload sizes, in bytes. + +### Gauges + +The following gauges track the queue of each signal type in the `otlp` sink. + +Metric | Description +:--- | :--- +`queueSize` | The number of events waiting to be sent. +`queueCapacity` | The total capacity of the queue. + +## Related documentation + +- [OTLP source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otlp-source/) +- [getEventType()]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-eventtype/) +- [Conditional routing]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#conditional-routing) diff --git a/_data-prepper/pipelines/configuration/sinks/pipeline.md b/_data-prepper/pipelines/configuration/sinks/pipeline.md index 3cba75a2..3c63c34b 100644 --- a/_data-prepper/pipelines/configuration/sinks/pipeline.md +++ b/_data-prepper/pipelines/configuration/sinks/pipeline.md @@ -1,12 +1,12 @@ --- layout: default -title: pipeline +title: Pipeline parent: Sinks grand_parent: Pipelines nav_order: 55 --- -# pipeline +# Pipeline sink Use the `pipeline` sink to write to another pipeline. @@ -22,7 +22,7 @@ name | Yes | String | Name of the pipeline to write to. The following example configures a `pipeline` sink that writes to a pipeline named `movies`: -``` +```yaml sample-pipeline: sink: - pipeline: diff --git a/_data-prepper/pipelines/configuration/sinks/prometheus.md b/_data-prepper/pipelines/configuration/sinks/prometheus.md new file mode 100644 index 00000000..f29e489c --- /dev/null +++ b/_data-prepper/pipelines/configuration/sinks/prometheus.md @@ -0,0 +1,178 @@ +--- +layout: default +title: Prometheus +parent: Sinks +grand_parent: Pipelines +nav_order: 59 +--- + +# Prometheus sink + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the [`prometheus` sink plugin](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/prometheus-sink) in the OpenSearch Data Prepper repository. +{: .warning} + +The Prometheus sink buffers OpenTelemetry metrics and exports them in Prometheus time series format using the Remote Write API. It supports both open-source Prometheus and Amazon Managed Service for Prometheus (AMP). + +The `prometheus` sink processes only metric data. All other data types are sent to the [DLQ pipeline]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/dlq/), if it is configured. + +To ensure compatibility, the Prometheus sink sorts metrics by timestamp within each batch before sending them to the server. It also supports an out-of-order window, which allows ingestion of metrics with older timestamps. + +## Prerequisites + +To use the `prometheus` sink, enable the experimental `prometheus` plugin in `data-prepper-config.yaml`: + +```yaml +experimental: + enabled_plugins: + sink: + - prometheus +``` +{% include copy.html %} + +## Usage + +The following examples configure the Prometheus sink for different deployment scenarios. + +### Open-source Prometheus with no authentication + +To use an open-source Prometheus instance, provide an `https://` URL. To use `http://`, set `insecure` to `true`. No `aws` block is needed. Prometheus must be started with the `--web.enable-remote-write-receiver` flag: + +```yaml +pipeline: + ... + sink: + - prometheus: + url: "http://localhost:9090/api/v1/write" + insecure: true + threshold: + max_events: 1000 + flush_interval: PT5S +``` +{% include copy.html %} + +### Open-source Prometheus with HTTP Basic authentication + +To authenticate with HTTP Basic credentials (for example, when Prometheus is behind a reverse proxy with basic authentication enabled), use the `authentication` block: + +```yaml +pipeline: + ... + sink: + - prometheus: + url: "https://localhost:9090/api/v1/write" + authentication: + http_basic: + username: "promuser" + password: "prompass" +``` +{% include copy.html %} + +### AMP + +To use AMP, provide the `aws` configuration block. An `https://` URL is required when using AWS authentication: + +```yaml +pipeline: + ... + sink: + - prometheus: + url: "https://aps-workspaces.us-east-2.amazonaws.com/workspaces/ws-xxxxxxxx-xxxx/api/v1/remote_write" + aws: + region: "us-east-2" + sts_role_arn: "arn:aws:iam::123456789012:role/data-prepper-prometheus-role" + threshold: + max_events: 1000 + flush_interval: PT5S +``` +{% include copy.html %} + +## IAM permissions + +When using AMP, configure AWS Identity and Access Management (IAM) to grant OpenSearch Data Prepper permissions to write to Amazon Managed Service for Prometheus. You can use a configuration similar to the following JSON configuration: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "amp-access", + "Effect": "Allow", + "Action": [ + "aps:RemoteWrite" + ], + "Resource": "arn:aws:aps:<region>:<account-id:workspace>/<workspace-id>" + } + ] +} +``` +{% include copy.html %} + +## Configuration + +Use the following options when customizing the `prometheus` sink. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`url` | Yes | String | The Prometheus Remote Write endpoint URL. Supports `https://` by default. To use `http://`, set `insecure` to `true`. When `aws` is configured, `https://` is required. +`insecure` | No | Boolean | When set to `true`, allows `http://` URLs. By default, only `https://` URLs are permitted. Default is `false`. +`encoding` | No | String | The compression format used for requests. Only `snappy` is supported. Default is `snappy`. +`remote_write_version` | No | String | The version of the Prometheus remote write protocol. Only `0.1.0` is supported. +`content_type` | No | String | The MIME type of the body. Only `application/x-protobuf` is supported. +`out_of_order_time_window` | No | Duration | The time window allowed for late-arriving data points. Data older than this window relative to the latest point will be dropped. Default is `10s`. +`sanitize_names` | No | Boolean | Determines whether metric and label names are sanitized in order to comply with Prometheus naming conventions. Default is `true`. +`instance_label` | No | String | The name of a label that identifies the Data Prepper instance in every time series that the sink writes. Use it when multiple instances run the same pipeline. For more information, see [Instance label](#instance-label). By default, no instance label is added. +`connection_timeout` | No | Duration | The maximum amount of time allowed to establish an HTTP connection. Must be between 1 and 600 seconds. Default is `60s`. +`idle_timeout` | No | Duration | The maximum amount of time an idle HTTP connection remains open before being closed. Must be between 1 and 600 seconds. Default is `60s`. +`request_timeout` | No | Duration | The maximum amount of time allowed for a full end-to-end HTTP request to complete. Must be between 1 and 600 seconds. Default is `60s`. +`threshold` | No | [Threshold configuration](#threshold-configuration) | Configuration for batching and flushing time-series data. +`max_retries` | No | Integer | The maximum number of attempts for failed ingestion requests. Uses exponential backoff with jitter on `retryable` status codes (`429`, `502`, `503`, or `504`). Default is `5`. +`aws` | No | [AWS configuration](#aws-configuration) | AWS configuration for AWS Signature Version 4 signing. When present, requests are signed with AWS credentials. Cannot be used with `authentication`. +`authentication` | No | [Authentication configuration](#authentication-configuration) | HTTP Basic authentication credentials. Cannot be used with `aws`. + +## Instance label + +When multiple Data Prepper instances run the same pipeline configuration, they write identical time series, and the Remote Write endpoint keeps only one sample for each series and timestamp. To keep the samples from each instance, set `instance_label` to a label name. The sink adds this label to every time series it writes. The label value is a truncated SHA-256 hash of the host identity, which the sink resolves once at startup from the local hostname, the `HOSTNAME` environment variable, or a local network address. If no host identity can be resolved, the pipeline fails to start. Instances that share a network namespace resolve the same identity unless they have distinct `HOSTNAME` values. + +The label name must match `[a-zA-Z_][a-zA-Z0-9_]*`, must not begin with `__`, and cannot be `le`, `ge`, or `quantile`. If a series already has a label with the same name, the existing label value is kept and the instance label is not added to that series. The comparison uses the final label names that the sink generates, which include a prefix for attributes. For example, a metric attribute named `x` becomes the `metric_attributes_x` label, so setting `instance_label` to `x` adds both labels. + +The following example adds the `dp_instance` label: + +```yaml +sink: + - prometheus: + url: "http://localhost:9090/api/v1/write" + instance_label: dp_instance +``` +{% include copy.html %} + +To calculate the total across instances, aggregate the label away in your queries, for example, `sum without (dp_instance) (my_metric)`. + +## Threshold configuration + +Use the following options to configure batching and flushing behavior for the Prometheus sink. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`max_events` | No | Integer | The maximum number of events to accumulate before flushing to Prometheus. Default is `1000`. +`max_request_size` | No | String | The maximum size of the request payload before flushing. Default is `1mb`. +`flush_interval` | No | Duration | The maximum amount of time to wait before flushing events. Default is `10s`. + +## AWS configuration + +When an `aws` block is present, requests are automatically signed with Signature Version 4. An `https://` URL is required. The AWS configuration supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The STS role to assume for requests to AWS. Defaults to `null`, which uses [standard SDK credential behavior](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_header_overrides` | No | Map | A map of header overrides to make when assuming the IAM role. Maximum of 5 headers. +`sts_external_id` | No | String | An optional external ID to use when assuming the IAM role. Must be between 2 and 1,224 characters. + +## Authentication configuration + +The `authentication` block supports HTTP Basic authentication. It cannot be used together with `aws` (Signature Version 4 signing). The authentication configuration supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`http_basic.username` | Yes | String | The username for HTTP Basic authentication. +`http_basic.password` | Yes | String | The password for HTTP Basic authentication. diff --git a/_data-prepper/pipelines/configuration/sinks/s3.md b/_data-prepper/pipelines/configuration/sinks/s3.md index cb881e81..776a0cb6 100644 --- a/_data-prepper/pipelines/configuration/sinks/s3.md +++ b/_data-prepper/pipelines/configuration/sinks/s3.md @@ -1,20 +1,36 @@ --- layout: default -title: s3 +title: S3 parent: Sinks grand_parent: Pipelines -nav_order: 55 +nav_order: 60 --- -# s3 +# S3 sink -The `s3` sink saves batches of events to [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) objects. +The `s3` sink saves and writes batches of OpenSearch Data Prepper events to Amazon Simple Storage Service (Amazon S3) objects. The configured `codec` determines how the `s3` sink serializes the data into Amazon S3. + +The `s3` sink uses the following format when batching events: + +``` +${pathPrefix}events-%{yyyy-MM-dd'T'HH-mm-ss'Z'}-${currentTimeInNanos}-${uniquenessId}.${codecSuppliedExtension} +``` +{% include copy.html %} + +When a batch of objects is written to Amazon S3, the objects are formatted similarly to the following: + +``` +my-logs/2023/06/09/06/events-2023-06-09T06-00-01-1686290401871214927-ae15b8fa-512a-59c2-b917-295a0eff97c8.json +``` +{% include copy.html %} + +For more information about how to configure an object, refer to [Object key](#object-key-configuration). ## Usage -The following example creates a pipeline configured with an s3 sink. It contains additional options for customizing the event and size thresholds for which the pipeline sends record events and sets the codec type `ndjson`: +The following example creates a pipeline configured with an `s3` sink. It contains additional options for customizing the event and size thresholds for the pipeline and sets the codec type as `ndjson`: -``` +```yaml pipeline: ... sink: @@ -22,137 +38,323 @@ pipeline: aws: region: us-east-1 sts_role_arn: arn:aws:iam::123456789012:role/Data-Prepper - sts_header_overrides: max_retries: 5 - bucket: - name: bucket_name - object_key: - path_prefix: my-elb/%{yyyy}/%{MM}/%{dd}/ + bucket: bucket_name + object_key: + path_prefix: my-logs/%{yyyy}/%{MM}/%{dd}/ threshold: - event_count: 2000 + event_count: 10000 maximum_size: 50mb event_collect_timeout: 15s codec: ndjson: buffer_type: in_memory ``` +{% include copy.html %} + +## IAM permissions + +To use the `s3` sink, configure AWS Identity and Access Management (IAM) to grant Data Prepper permissions to write to Amazon S3. You can use a configuration similar to the following JSON configuration: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "s3-access", + "Effect": "Allow", + "Action": [ + "s3:PutObject" + ], + "Resource": "arn:aws:s3:::<YOUR-BUCKET>/*" + } + ] +} +``` +{% include copy.html %} + +## Cross-account S3 access<a name="s3_bucket_ownership"></a> + +When Data Prepper fetches data from an S3 bucket, it verifies bucket ownership using a [bucket owner condition](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-owner-condition.html). + +By default, the S3 sink does not require `bucket_owners`. If `bucket_owners` is configured and a bucket is not included in one of the mapped configurations, `default_bucket_owner` defaults to the account ID in `aws.sts_role_arn`. You can configure both `bucket_owners` and `default_bucket_owner` and apply the settings together. + +When ingesting data from multiple S3 buckets with different account associations, configure Data Prepper for cross-account S3 access based on the following conditions: + +- For S3 buckets belonging to the same account, set `default_bucket_owner` to that account's ID. +- For S3 buckets belonging to multiple accounts, use a `bucket_owners` map. + +A `bucket_owners` map specifies account IDs for buckets belonging to multiple accounts. For example, in the following configuration, `my-bucket-01` is owned by `123456789012` and `my-bucket-02` is owned by `999999999999`: + +```yaml +sink: + - s3: + default_bucket_owner: 111111111111 + bucket_owners: + my-bucket-01: 123456789012 + my-bucket-02: 999999999999 +``` +{% include copy.html %} ## Configuration Use the following options when customizing the `s3` sink. -Option | Required | Type | Description -:--- | :--- | :--- | :--- -`bucket` | Yes | String | The object from which the data is retrieved and then stored. The `name` must match the name of your object store. -`codec` | Yes | [Buffer type](#buffer-type) | Determines the buffer type. -`aws` | Yes | AWS | The AWS configuration. See [aws](#aws) for more information. -`threshold` | Yes | [Threshold](#threshold-configuration) | Configures when to write an object to S3. -`object_key` | No | Sets the `path_prefix` and the `file_pattern` of the object store. Defaults to the S3 object `events-%{yyyy-MM-dd'T'hh-mm-ss}` found inside the root directory of the bucket. -`compression` | No | String | The compression algorithm to apply: `none`, `gzip`, or `snappy`. Default is `none`. -`buffer_type` | No | [Buffer type](#buffer-type) | Determines the buffer type. -`max_retries` | No | Integer | The maximum number of times a single request should retry when ingesting data to S3. Defaults to `5`. +Option | Required | Type | Description +:--- |:---------|:------------------------------------------------| :--- +`bucket` | Conditionally | String | Specifies the sink's S3 bucket name. Supports dynamic bucket naming using [Data Prepper expressions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), for example, `test-${/bucket_id}`. If a dynamic bucket is inaccessible and no `default_bucket` is configured, then the object data is dropped. Required if `bucket_selector` is not set. Cannot be used together with `bucket_selector`. +`bucket_selector` | Conditionally | [Bucket selector](#bucket-selector) | A plugin that determines the bucket and path prefix to which the sink writes objects. Required if `bucket` is not set. Cannot be used together with `bucket`. +`default_bucket` | No | String | A static bucket for inaccessible dynamic buckets in `bucket`. +`bucket_owners` | No | Map | A map of bucket names and their account owner IDs for cross-account access. Refer to [Cross-account S3 access](#s3_bucket_ownership). +`default_bucket_owner` | No | String | The AWS account ID for an S3 bucket owner. Refer to [Cross-account S3 access](#s3_bucket_ownership). +`codec` | Yes | [Codec](#codec) | Serializes data in S3 objects. +`aws` | Yes | AWS | The AWS configuration. Refer to [`aws`](#aws). +`threshold` | Yes | [Threshold](#threshold-configuration) | Condition for writing objects to S3. +`aggregate_threshold` | No | [Aggregate threshold](#aggregate-threshold-configuration) | A condition for flushing objects with a dynamic `path_prefix`. +`object_key` | No | [Object key](#object-key-configuration) | Sets `path_prefix` and `name_pattern_prefix` for object storage. The default object name pattern is `events-%{yyyy-MM-dd'T'HH-mm-ss'Z'}`. By default, these objects are found in the bucket's root directory. +`object_metadata` | No | [Object metadata](#object-metadata) | The user-defined metadata to add to each S3 object. Cannot be used together with `predefined_object_metadata`. +`predefined_object_metadata` | No | [Object metadata](#object-metadata) | The user-defined metadata to add to each S3 object. Cannot be used together with `object_metadata`. +`compression` | No | String | The compression algorithm: Either `none`, `gzip`, or `snappy`. Default is `none`. +`buffer_type` | No | [Buffer type](#buffer-type) | The buffer type configuration. +`max_retries` | No | Integer | The maximum number of retries for S3 ingestion requests. Default is `5`. +`client` | No | [Client](#client-configuration) | The configuration of the HTTP client that the sink uses to connect to Amazon S3. +`server_side_encryption` | No | [Server-side encryption](#server-side-encryption) | The server-side encryption settings for objects written to S3. -## aws +## `aws` Option | Required | Type | Description :--- | :--- | :--- | :--- `region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). -`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon SQS and Amazon S3. Defaults to `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon Simple Queue Service (Amazon SQS) and Amazon S3. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). `sts_header_overrides` | No | Map | A map of header overrides that the IAM role assumes for the sink plugin. -`sts_external_id` | No | String | The external ID to attach to AssumeRole requests from AWS STS. - +`sts_external_id` | No | String | An AWS STS external ID used when Data Prepper assumes the role. For more information, refer to the `ExternalId` section under [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) in the AWS STS API reference. ## Threshold configuration -Use the following options to set ingestion thresholds for the `s3` sink. +Use the following options to set ingestion thresholds for the `s3` sink. Data Prepper writes events to an S3 object when any of these conditions occur. Option | Required | Type | Description :--- | :--- | :--- | :--- -`event_count` | Yes | Integer | The maximum number of events the S3 bucket can ingest. -`maximum_size` | Yes | String | The maximum number of bytes that the S3 bucket can ingest after compression. Defaults to `50mb`. -`event_collect_timeout` | Yes | String | Sets the time period during which events are collected before ingestion. All values are strings that represent duration, either an ISO_8601 notation string, such as `PT20.345S`, or a simple notation, such as `60s` or `1500ms`. +`event_count` | No | Integer | The number of Data Prepper events to accumulate before writing an object to S3. Valid values are 0--10,000,000. If set to `0` or not set, the number of events does not trigger a write. +`maximum_size` | No | String | The maximum number of bytes to accumulate before writing an object to S3. Default is `50mb`. +`event_collect_timeout` | Yes | String | The maximum amount of time before Data Prepper writes an event to S3. The value should be either an ISO-8601 duration, such as `PT2M30S`, or a simple notation, such as `60s` or `1500ms`. Valid values are 1 second to 1 hour. +## Aggregate threshold configuration + +Use the following options to set rules or limits that trigger certain actions or behavior when an aggregated value crosses a defined threshold. + +Option | Required | Type | Description +:--- |:-----------------------------------|:-------| :--- +`flush_capacity_ratio` | No | Float | The percentage of groups to be force-flushed when `aggregate_threshold maximum_size` is reached. The percentage is expressed as a number between `0.0` and `1.0`. Default is `0.5`. +`maximum_size` | Yes | String | The maximum number of bytes to accumulate before force-flushing objects. For example, `128mb`. ## Buffer type -`buffer_type` is an optional configuration that records stored events temporarily before flushing them into an S3 bucket. The default value is `in_memory`. Use one of the following options: +`buffer_type` is an optional configuration that determines how Data Prepper temporarily stores data before writing an object to S3. The default value is `in_memory`. + +Use one of the following options: - `in_memory`: Stores the record in memory. -- `local_file`: Flushes the record into a file on your machine. +- `local_file`: Flushes the record into a file on your local machine. This option uses your machine's temporary directory. - `multipart`: Writes using the [S3 multipart upload](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html). Every 10 MB is written as a part. ## Object key configuration +Use the following options to define how object keys are constructed for objects stored in S3. + Option | Required | Type | Description :--- | :--- | :--- | :--- -`path_prefix` | Yes | String | The S3 key prefix path to use. Accepts date-time formatting. For example, you can use `%{yyyy}/%{MM}/%{dd}/%{HH}/` to create hourly folders in S3. By default, events write to the root of the bucket. +`path_prefix` | No | String | The S3 key prefix path to use for objects written to S3. Accepts date-time formatting and dynamic injection of values using [Data Prepper expressions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/). For example, you can use `/${/my_partition_key}/%{yyyy}/%{MM}/%{dd}/%{HH}/` to create hourly folders in S3 based on the `my_partition_key` value. The prefix path should end with `/`. By default, Data Prepper writes objects to the S3 bucket root. +`name_pattern_prefix` | No | String | The prefix of the object name. The sink appends `-%{yyyy-MM-dd'T'HH-mm-ss'Z'}` to this prefix, followed by a unique ID and the codec extension. For example, setting `name_pattern_prefix` to `app-logs` produces object names such as `app-logs-2026-06-09T06-00-01Z-1686290401871214927-ae15b8fa-512a-59c2-b917-295a0eff97c8.json`. Supports [Data Prepper expressions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/expression-syntax/), such as `app-${/service}`. Cannot contain date-time patterns (`%{...}`). Default is `events`. +## Object metadata -## codec +Use the following options to add user-defined metadata to each S3 object. The sink adds metadata only when `buffer_type` is `in_memory`. + +The `object_metadata` object supports the following option. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`number_of_events_key` | No | String | The name of the metadata key in which the sink stores the number of events in the object. + +The `predefined_object_metadata` object supports the following option. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`number_of_objects` | No | String | The name of the metadata key in which the sink stores the number of events in the object. + +## Client configuration + +Use the following options to configure the HTTP client that the sink uses to connect to Amazon S3. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`max_connections` | No | Integer | The maximum number of concurrent connections to Amazon S3. Default is `50`. +`acquire_timeout` | No | String | The maximum amount of time to wait for a connection to become available. The value should be either an ISO-8601 duration, such as `PT30S`, or a simple notation, such as `30s` or `1500ms`. Default is `10s`. + +## Server-side encryption + +Use the following options to configure server-side encryption for objects written to S3. For more information, see [Protecting data with server-side encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html) in the Amazon S3 documentation. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`type` | No | String | The server-side encryption type. Valid values are `s3` (server-side encryption with Amazon S3 managed keys), `kms` (server-side encryption with AWS Key Management Service (AWS KMS) keys), and `kms_dsse` (dual-layer server-side encryption with AWS KMS keys). Default is `s3`. +`kms_key_id` | No | String | The ID or Amazon Resource Name (ARN) of the AWS KMS key used to encrypt objects. Applies only when `type` is `kms` or `kms_dsse`. If not set, Amazon S3 uses the AWS managed key. +`bucket_key_enabled` | No | Boolean | Whether to use an S3 Bucket Key to encrypt objects. Applies only when `type` is `kms` or `kms_dsse`. Default is `true`. + +The following example encrypts objects using an AWS KMS key: + +```yaml +pipeline: + ... + sink: + - s3: + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/Data-Prepper + bucket: my-bucket + server_side_encryption: + type: kms + kms_key_id: arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab + threshold: + event_collect_timeout: 60s + codec: + ndjson: +``` +{% include copy.html %} + +## Bucket selector + +The `bucket_selector` option specifies a plugin that determines the bucket and path prefix of the objects that the sink writes. When `bucket_selector` is set, the sink ignores `object_key.path_prefix`. The only supported bucket selector is `aws_security_lake`. + +### `aws_security_lake` + +The `aws_security_lake` bucket selector writes objects to [Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html). When the sink starts, it creates a custom log source in Security Lake and writes objects to the S3 location of that source. The path prefix of each object consists of the custom source location followed by `region=<region>/accountId=<account_id>/eventDay=<yyyyMMdd>/`, where the Region is `aws.region`, the account ID is taken from `aws.sts_role_arn`, and the date is the day on which the sink starts. The `aws.sts_role_arn` option is required and is used as the crawler role of the custom source. + +The Security Lake client uses the default AWS credentials and Region provider chains to create the custom source, so the Region must be available, for example, in the `AWS_REGION` environment variable. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`log_class` | Yes | String | The Open Cybersecurity Schema Framework (OCSF) event class of the data written to the custom source, for example, `NETWORK_ACTIVITY`. +`source_name` | No | String | The name of the custom log source. The sink appends four random characters to this name. If not set, the sink generates a random name. +`source_version` | No | String | The version of the custom log source. Default is `1.0`. +`external_id` | No | String | The external ID of the custom source provider identity. Default is `extid`. + +The following example writes Parquet objects to a Security Lake custom source: + +```yaml +pipeline: + ... + sink: + - s3: + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/Data-Prepper + bucket_selector: + aws_security_lake: + source_name: my-source + log_class: NETWORK_ACTIVITY + threshold: + event_collect_timeout: 60s + codec: + parquet: + auto_schema: true +``` +{% include copy.html %} + +## `codec` The `codec` determines how the `s3` source formats data written to each S3 object. -### avro codec +### `avro` codec -The `avro` codec writes an event as an [Apache Avro](https://avro.apache.org/) document. +The `avro` codec writes an event as an [Apache Avro](https://avro.apache.org/) document. Because Avro requires a schema, you may either define the schema or have Data Prepper automatically generate it. Defining your own schema is recommended because this will allow it to be tailored to your particular use case. -Because Avro requires a schema, you may either define the schema yourself, or Data Prepper will automatically generate a schema. -In general, you should define your own schema because it will most accurately reflect your needs. +When you provide your own Avro schema, that schema defines the final structure of your data. Any extra values in any incoming events that are not mapped in the Avro schema will not be included in the final destination. Data Prepper does not allow the use of `include_keys` or `exclude_keys` with a custom schema so as to avoid confusion between a custom Avro schema and the `include_keys` or `exclude_keys` sink configurations. -We recommend that you make your Avro fields use a null [union](https://avro.apache.org/docs/current/specification/#unions). -Without the null union, each field must be present or the data will fail to write to the sink. -If you can be certain that each each event has a given field, you can make it non-nullable. +In cases where your data is uniform, you may be able to automatically generate a schema. Automatically generated schemas are based on the first event that the codec receives. The schema will only contain keys from this event, and all keys must be present in all events in order to automatically generate a working schema. Automatically generated schemas make all fields nullable. Use the `include_keys` and `exclude_keys` sink configurations to control which data is included in the automatically generated schema. -When you provide your own Avro schema, that schema defines the final structure of your data. -Therefore, any extra values inside any incoming events that are not mapped in the Arvo schema will not be included in the final destination. -To avoid confusion between a custom Arvo schema and the `include_keys` or `exclude_keys` sink configurations, Data Prepper does not allow the use of the `include_keys` or `exclude_keys` with a custom schema. - -In cases where your data is uniform, you may be able to automatically generate a schema. -Automatically generated schemas are based on the first event received by the codec. -The schema will only contain keys from this event. -Therefore, you must have all keys present in all events in order for the automatically generated schema to produce a working schema. -Automatically generated schemas make all fields nullable. -Use the sink's `include_keys` and `exclude_keys` configurations to control what data is included in the auto-generated schema. +Avro fields should use a null [union](https://avro.apache.org/docs/1.12.0/specification/#unions) because this will allow missing values. Otherwise, all required fields must be present for each event. Use non-nullable fields only when you are certain they exist. +Use the following options to configure the codec. Option | Required | Type | Description :--- | :--- | :--- | :--- -`schema` | Yes | String | The Avro [schema declaration](https://avro.apache.org/docs/current/specification/#schema-declaration). Not required if `auto_schema` is set to true. -`auto_schema` | No | Boolean | When set to `true`, automatically generates the Avro [schema declaration](https://avro.apache.org/docs/current/specification/#schema-declaration) from the first event. - +`schema` | Yes | String | The Avro [schema declaration](https://avro.apache.org/docs/1.12.0/specification/#schema-declaration). Not required if `auto_schema` is set to true. +`auto_schema` | No | Boolean | When set to `true`, automatically generates the Avro [schema declaration](https://avro.apache.org/docs/1.12.0/specification/#schema-declaration) from the first event. -### ndjson codec +### `ndjson` codec -The `ndjson` codec writes each line as a JSON object. +The `ndjson` codec writes each line as a JSON object. The `ndjson` codec does not take any configurations. -The `ndjson` codec does not take any configurations. +### `json` codec +The `json` codec writes events in a single large JSON file. Each event is written into an object within a JSON array. -### json codec - -The `json` codec writes events in a single large JSON file. -Each event is written into an object within a JSON array. - +Use the following options to configure the codec. Option | Required | Type | Description :--- | :--- | :--- | :--- `key_name` | No | String | The name of the key for the JSON array. By default this is `events`. +### `parquet` codec -### parquet codec +The `parquet` codec writes events into a Parquet file. When using the codec, set `buffer_type` to `in_memory`. -The `parquet` codec writes events into a Parquet file. -When using the Parquet codec, set the `buffer_type` to `in_memory`. +The `parquet` codec writes data using the schema. Because Parquet requires an Avro schema, you may either define the schema yourself or have Data Prepper automatically generate it. Defining your own schema is recommended because this will allow it to be tailored to your particular use case. -The Parquet codec writes data using the Avro schema. -Because Parquet requires an Avro schema, you may either define the schema yourself, or Data Prepper will automatically generate a schema. -However, we generally recommend that you define your own schema so that it can best meet your needs. - -For details on the Avro schema and recommendations, see the [Avro codec](#avro-codec) documentation. +For more information about the Avro schema, refer to [Avro codec](#avro-codec). +Use the following options to configure the codec. Option | Required | Type | Description :--- | :--- | :--- | :--- -`schema` | Yes | String | The Avro [schema declaration](https://avro.apache.org/docs/current/specification/#schema-declaration). Not required if `auto_schema` is set to true. -`auto_schema` | No | Boolean | When set to `true`, automatically generates the Avro [schema declaration](https://avro.apache.org/docs/current/specification/#schema-declaration) from the first event. +`schema` | Yes | String | The Avro [schema declaration](https://avro.apache.org/docs/1.12.0/specification/#schema-declaration). Not required if `auto_schema` is set to true. +`auto_schema` | No | Boolean | When set to `true`, automatically generates the Avro [schema declaration](https://avro.apache.org/docs/1.12.0/specification/#schema-declaration) from the first event. +### Setting a schema with Parquet + +The following example pipeline shows how to configure the `s3` sink to write Parquet data into a Parquet file using a schema for [VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html#flow-log-records): + +```yaml +pipeline: + ... + sink: + - s3: + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/Data-Prepper + bucket: mys3bucket + object_key: + path_prefix: vpc-flow-logs/%{yyyy}/%{MM}/%{dd}/%{HH}/ + codec: + parquet: + schema: > + { + "type" : "record", + "namespace" : "org.opensearch.dataprepper.examples", + "name" : "VpcFlowLog", + "fields" : [ + { "name" : "version", "type" : ["null", "string"]}, + { "name" : "srcport", "type": ["null", "int"]}, + { "name" : "dstport", "type": ["null", "int"]}, + { "name" : "accountId", "type" : ["null", "string"]}, + { "name" : "interfaceId", "type" : ["null", "string"]}, + { "name" : "srcaddr", "type" : ["null", "string"]}, + { "name" : "dstaddr", "type" : ["null", "string"]}, + { "name" : "start", "type": ["null", "int"]}, + { "name" : "end", "type": ["null", "int"]}, + { "name" : "protocol", "type": ["null", "int"]}, + { "name" : "packets", "type": ["null", "int"]}, + { "name" : "bytes", "type": ["null", "int"]}, + { "name" : "action", "type": ["null", "string"]}, + { "name" : "logStatus", "type" : ["null", "string"]} + ] + } + threshold: + event_count: 500000000 + maximum_size: 20mb + event_collect_timeout: PT15M + buffer_type: in_memory +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sinks/sinks.md b/_data-prepper/pipelines/configuration/sinks/sinks.md index 0f3af6ab..9869459a 100644 --- a/_data-prepper/pipelines/configuration/sinks/sinks.md +++ b/_data-prepper/pipelines/configuration/sinks/sinks.md @@ -3,20 +3,22 @@ layout: default title: Sinks parent: Pipelines has_children: true -nav_order: 30 +nav_order: 25 --- -# Sinks +# Data Prepper sinks -Sinks define where Data Prepper writes your data to. +A `sink` is an output component that specifies the destination(s) to which an OpenSearch Data Prepper pipeline publishes events. Sink destinations can be services like OpenSearch, Amazon Simple Storage Service (Amazon S3), or even another Data Prepper pipeline, enabling chaining of multiple pipelines. The sink component has the following configurable options that you can use to customize the destination type. -## General options for all sink types +## Configuration options The following table describes options you can use to configure the `sinks` sink. Option | Required | Type | Description :--- | :--- |:------------| :--- -routes | No | String list | A list of routes for which this sink applies. If not provided, this sink receives all events. See [conditional routing]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#conditional-routing) for more information. -tags_target_key | No | String | When specified, includes event tags in the output of the provided key. -include_keys | No | String list | When specified, provides the keys in this list in the data sent to the sink. Some codecs and sinks do not allow use of this field. -exclude_keys | No | String list | When specified, excludes the keys given from the data sent to the sink. Some codecs and sinks do not allow use of this field. +`routes` | No | String list | A list of routes to which the sink applies. If not provided, then the sink receives all events. See [conditional routing]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#conditional-routing) for more information. +`tags_target_key` | No | String | When specified, includes event tags in the output under the provided key. +`include_keys` | No | String list | When specified, provides only the listed keys in the data sent to the sink. Some codecs and sinks may not support this field. +`exclude_keys` | No | String list | When specified, excludes the listed keys from the data sent to the sink. Some codecs and sinks may not support this field. + + diff --git a/_data-prepper/pipelines/configuration/sinks/stdout.md b/_data-prepper/pipelines/configuration/sinks/stdout.md index 35b1b081..18a0d0f1 100644 --- a/_data-prepper/pipelines/configuration/sinks/stdout.md +++ b/_data-prepper/pipelines/configuration/sinks/stdout.md @@ -1,11 +1,11 @@ --- layout: default -title: stdout sink +title: Standard output parent: Sinks grand_parent: Pipelines -nav_order: 45 +nav_order: 70 --- -# stdout sink +# Standard output sink Use the `stdout` sink for console output and testing. It has no configurable options. diff --git a/_data-prepper/pipelines/configuration/sources/atlassian-confluence.md b/_data-prepper/pipelines/configuration/sources/atlassian-confluence.md new file mode 100644 index 00000000..19f31246 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/atlassian-confluence.md @@ -0,0 +1,150 @@ +--- +layout: default +title: Atlassian Confluence +parent: Sources +grand_parent: Pipelines +nav_order: 5 +--- + +# Atlassian Confluence source + +You can use the OpenSearch Data Prepper `confluence` source to ingest records from one or more [Atlassian Confluence](https://www.atlassian.com/software/confluence) spaces. + +## Usage + +Set up Confluence project access credentials by choosing one of the following options: + +- **Basic authentication** (API key authentication): Follow [these instructions](https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/). +- **OAuth 2.0 authentication**: Follow [these instructions](https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#faq-rrt-config). +- **Bearer token authentication**: Provide a token that the source sends in the `Authorization: Bearer` header of each request. + +As an additional optional step, store the credentials in AWS Secrets Manager. If you don't store the credentials in AWS Secrets Manager, then you must provide plain-text credentials directly in the pipeline configuration. + +The following example pipeline specifies `confluence` as a source. The pipeline ingests data from multiple Confluence spaces named `space1` and `space2` and applies filters to select wiki content (pages and blog posts) from these projects as a source: + +```yaml +version: "2" +extension: + aws: + secrets: + confluence-account-credentials: + secret_id: "arn:aws:secretsmanager:us-east-1:123456789012:secret:confluence-credentials-secret" + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/Example-Role" +atlassian-confluence-pipeline: + source: + confluence: + hosts: ["https://example.atlassian.net/"] + acknowledgments: true + preserve_formatting: true + authentication: + # Provide one of the authentication method to use. Supported methods are 'basic', 'oauth2', and 'bearer_token'. + # For basic authentication, password is the API key that you generate using your confluence account + basic: + username: {% raw %} ${{aws_secrets:confluence-account-credentials:username}} {% endraw %} + password: {% raw %} ${{aws_secrets:confluence-account-credentials:password}} {% endraw %} + # For OAuth 2.0-based authentication, we require the following 4 key values stored in the secret + # Follow atlassian instructions at the following link to generate these keys + # https://developer.atlassian.com/cloud/confluence/oauth-2-3lo-apps/ + # If you are using OAuth 2.0 authentication, we also require, write permission to your aws secret to + # be able to write the renewed tokens back into the secret + # oauth2: + # client_id: {% raw %} ${{aws_secrets:confluence-account-credentials:clientId}} {% endraw %} + # client_secret: {% raw %} ${{aws_secrets:confluence-account-credentials:clientSecret}} {% endraw %} + # access_token: {% raw %} ${{aws_secrets:confluence-account-credentials:accessToken}} {% endraw %} + # refresh_token: {% raw %} ${{aws_secrets:confluence-account-credentials:refreshToken}} {% endraw %} + filter: + space: + key: + include: + # This is not space name. + # It is an alphanumeric space key that you can find under space details in confluence + - "space1" + - "space2" + # exclude: + # - "<<space key>>" + # - "<<space key>>" + page_type: + include: + - "page" + # - "blogpost" + # - "comment" + # exclude: + # - "attachment" +``` +{% include copy.html %} + +## Configuration options + +The `confluence` source supports the following configuration options. + +| Option | Required | Type | Description | +|:------------------|:---------|:----------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `hosts` | Yes | List | The Atlassian Confluence hostname. Currently, only one host is supported, so this list is expected to be of size 1. | +| `acknowledgments` | No | Boolean | When set to `true`, enables the `confluence` source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. | +| `preserve_formatting` | No | Boolean | When set to `true`, Confluence content formatting markup tags are kept as is. Default is `false` (remove markup tags and convert to plain text). | +| `allow_internal_address` | No | Boolean | When set to `true`, allows the host specified in `hosts` to resolve to a private, loopback, or link-local IP address. When set to `false`, the source rejects hosts that resolve to these addresses. Default is `false`. | +| `authentication` | Yes | [authentication](#Authentication) | Configures the authentication method used to access `confluence` source records from the specified host. | +| `filter` | No | [filter](#Filter) | Applies specific filter criteria while extracting Confluence content. | + +### Authentication + +Use one of the following authentication methods to access a Confluence host. You must provide exactly one of the following parameters. + +| Option | Required | Type | Description | +|:---------|:---------|:------------------|:-------------------------------------------------------------| +| `basic` | Yes | [Basic](#basic-authentication) | Basic authentication credentials used to access a Confluence host. | +| `oauth2` | Yes | [OAuth 2.0](#oauth-20-authentication) | OAuth 2.0 authentication credentials used to access a Confluence host. | +| `bearer_token` | Yes | String | A bearer token or reference to the secret key storing the bearer token. The source sends the token in the `Authorization: Bearer` header of each request. If the token is stored in AWS Secrets Manager, the source reloads the secret value when the host returns a `401` response. | + +#### Basic authentication + +If you use `basic` authentication, the following fields are required. + +| Option | Required | Type | Description | +|:-----------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `username` | Yes | String | A username or reference to the secret key storing the username. | +| `password` | Yes | String | A password (API key) or reference to the secret key storing the password. | + +#### OAuth 2.0 authentication + +If you use OAuth 2.0, the following fields are required. + +| Option | Required | Type | Description | +|:----------------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `client_id` | Yes | String | A `client_id` or reference to the secret key storing the `client_id`. | +| `client_secret` | Yes | String | A `client_secret` or reference to the secret key storing the `client_secret`. | +| `access_token` | Yes | String | An `access_token` or reference to the secret key storing the `access_token`. | +| `refresh_token` | Yes | String | A `refresh_token` or reference to the secret key storing the `refresh_token`. | + +### Filter + +Optionally, you can specify filters to select specific content, shown in the following table. If no filters are specified, all the spaces and content visible for the specified credentials are extracted and sent to the specified sink in the pipeline. + +| Option | Required | Type | Description | +|:------------|:---------|:-------|:----------------------------------------------| +| `space` | No | Object | Filters content by space. Contains the `key` object, which accepts `include` and `exclude` lists of space keys. Use the space key, not the space name. Each space key must be 2--100 characters long and contain only letters and digits. A space key cannot appear in both lists. | +| `page_type` | No | Object | Filters content by type. Accepts `include` and `exclude` lists of content types. Valid values are `page`, `blogpost`, `comment`, and `attachment`. A content type cannot appear in both lists. | + +The source validates filter values when it starts crawling. If a filter contains an invalid value, the source logs an error and does not ingest content. + +### AWS secrets + +You can use the following options in the `aws` secrets configuration if you plan to store the credentials in AWS Secrets Manager. Storing secrets in AWS Secrets Manager is optional. If AWS Secrets Manager is not used, credentials must be specified in the pipeline YAML itself, in plain text. + +If OAuth 2.0 authentication is used in combination with `aws` secrets, this source requires write permissions to AWS Secrets Manager to be able to write back the updated (or renewed) access token once the current token expires. + +| Option | Required | Type | Description | +|:---------------|:---------|:-------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `region` | Yes | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). | +| `sts_role_arn` | Yes | String | The AWS Security Token Service (AWS STS) role to assume for requests to Atlassian Confluence. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). | +| `secret_id` | Yes | Map | The Amazon Resource Name (ARN) of the secret where the credentials are stored. | + +## Metrics + +The `confluence` source includes the following metrics (counters): + +* `crawlingTime`: The amount of time taken to crawl through all the new changes in Confluence. +* `pageFetchLatency`: The page fetch API operation latency. +* `searchCallLatency`: The search API operation latency. +* `searchResultsFound`: The number of pages found in a specified search API call. diff --git a/_data-prepper/pipelines/configuration/sources/atlassian-jira.md b/_data-prepper/pipelines/configuration/sources/atlassian-jira.md new file mode 100644 index 00000000..20284439 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/atlassian-jira.md @@ -0,0 +1,153 @@ +--- +layout: default +title: Atlassian Jira +parent: Sources +grand_parent: Pipelines +nav_order: 7 +--- + +# Atlassian Jira source + +You can use the OpenSearch Data Prepper `jira` source to ingest records from one or more [Atlassian Jira](https://www.atlassian.com/software/jira) projects. + +## Usage + +Set up Jira project access credentials by choosing one of the following options: + +- **Basic authentication** (API key authentication): Follow [these instructions](https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/). +- **OAuth 2.0 authentication**: Follow [these instructions](https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#faq-rrt-config). + +As an additional optional step, store the credentials in AWS Secrets Manager. If you don't store the credentials in AWS Secrets Manager, then you must provide plain-text credentials directly in the pipeline configuration. + +The following example pipeline specifies `jira` as a source. The pipeline ingests data from Jira projects named `project1` and `project2` and applies filters to select tickets from these projects as a source: + +```yaml +version: "2" +extension: + aws: + secrets: + jira-account-credentials: + secret_id: "arn:aws:secretsmanager:us-east-1:123456789012:secret:jira-credentials-secret" + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/Example-Role" +atlassian-jira-pipeline: + source: + jira: + hosts: ["https://example.atlassian.net/"] + acknowledgments: true + authentication: + # Provide one of the authentication method to use. Supported methods are 'basic' and 'oauth2'. + # For basic authentication, password is the API key that you generate using your jira account + basic: + username: {% raw %} ${{aws_secrets:jira-account-credentials:username}} {% endraw %} + password: {% raw %} ${{aws_secrets:jira-account-credentials:password}} {% endraw %} + # For OAuth 2.0-based authentication, we require the following 4 key values stored in the secret + # Follow atlassian instructions at the following link to generate these keys + # https://developer.atlassian.com/cloud/confluence/oauth-2-3lo-apps/ + # If you are using OAuth 2.0 authentication, we also require, write permission to your aws secret to + # be able to write the renewed tokens back into the secret + # oauth2: + # client_id: {% raw %} ${{aws_secrets:jira-account-credentials:clientId}} {% endraw %} + # client_secret: {% raw %} ${{aws_secrets:jira-account-credentials:clientSecret}} {% endraw %} + # access_token: {% raw %} ${{aws_secrets:jira-account-credentials:accessToken}} {% endraw %} + # refresh_token: {% raw %} ${{aws_secrets:jira-account-credentials:refreshToken}} {% endraw %} + filter: + project: + key: + include: + # This is not project name. + # It is an alphanumeric project key that you can find under project details in jira + - "PROJECT1" + - "PROJECT2" + # exclude: + # - "<<project key>>" + # - "<<project key>>" + issue_type: + include: + - "Story" + # - "Bug" + # - "Task" + # exclude: + # - "Epic" + status: + include: + - "To Do" + # - "In Progress" + # - "Done" + # exclude: + # - "Backlog" +``` +{% include copy.html %} + +## Configuration options + +The `jira` source supports the following configuration options. + +| Option | Required | Type | Description | +|:------------------|:---------|:----------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `hosts` | Yes | List | The Atlassian Jira hostname. Currently, only one host is supported, so this list is expected to be of size 1. | +| `acknowledgments` | No | Boolean | When set to `true`, enables the `jira` source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. | +| `authentication` | Yes | [authentication](#Authentication) | Configures the authentication method used to access `jira` source records from the specified host. | +| `filter` | No | [filter](#Filter) | Applies specific filter criteria while extracting Jira tickets. | + +### Authentication + +You can use one of the following authentication methods to access the specified Jira host. You must provide one of the following parameters. + +| Option | Required | Type | Description | +|:---------|:---------|:------------------|:-------------------------------------------------------| +| `basic` | Yes | [Basic](#basic-authentication) | Basic authentication credentials used to access a Jira host. | +| `oauth2` | Yes | [OAuth 2.0](#oauth-20-authentication)| OAuth 2.0 authentication credentials used to access a Jira host. | + +#### Basic authentication + +Either basic or OAuth 2.0 credentials are required to access the Jira site. If you use `basic` authentication, the following fields are required. + +| Option | Required | Type | Description | +|:-----------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `username` | Yes | String | A username or reference to the secret key storing the username. | +| `password` | Yes | String | A password (API key) or reference to the secret key storing the password. | + +#### OAuth 2.0 authentication + +Either basic or OAuth 2.0 credentials are required to access the Jira site. If you use OAuth 2.0, the following fields are required. + +| Option | Required | Type | Description | +|:----------------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `client_id` | Yes | String | A `client_id` or reference to the secret key storing the `client_id`. | +| `client_secret` | Yes | String | A `client_secret` or reference to the secret key storing the `client_secret`. | +| `access_token` | Yes | String | An `access_token` or reference to the secret key storing the `access_token`. | +| `refresh_token` | Yes | String | A `refresh_token` or reference to the secret key storing the `refresh_token`. | + +### Filter + +Optionally, you can specify filters to select specific content. If no filters are specified, all the projects and tickets visible for the specified credentials will be extracted and sent to the specified sink in the pipeline. + +| Option | Required | Type | Description | +|:-------------|:---------|:-------|:-----------------------------------------------| +| `project` | No | Object | Filters issues by project. Contains the `key` object, which accepts `include` and `exclude` lists of project keys. Each project key must be 2--100 characters long and contain only uppercase letters and digits. A project key cannot appear in both lists. | +| `issue_type` | No | Object | Filters issues by issue type. Accepts `include` and `exclude` lists of issue type names, for example, `Story` or `Bug`. | +| `status` | No | Object | Filters issues by status. Accepts `include` and `exclude` lists of status names, for example, `In Progress` or `Done`. | + +The source validates project keys when it starts crawling. If a project filter contains an invalid key, the source logs an error and does not ingest issues. + +### AWS secrets + +You can use the following options in the `aws` secrets configuration if you plan to store the credentials in AWS Secrets Manager. Storing secrets in AWS Secrets Manager is optional. If AWS Secrets Manager is not used, credentials must be specified in the pipeline YAML itself, in plain text. + +If OAuth 2.0 authentication is used in combination with `aws` secrets, this source requires write permissions to the secret to be able to write back the updated (or renewed) access token once the current token expires. + +| Option | Required | Type | Description | +|:---------------|:---------|:-------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `region` | Yes | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). | +| `sts_role_arn` | Yes | String | The AWS Security Token Service (AWS STS) role to assume for requests to Atlassian Jira. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). | +| `secret_id` | Yes | Map | The Amazon Resource Name (ARN) of the secret where the credentials are stored. + +## Metrics + +The `jira` source includes the following metrics (counters): + +* `crawlingTime`: The amount of time taken to crawl through all the new changes in Jira. +* `ticketFetchLatency`: The ticket fetch API operation latency. +* `searchCallLatency`: The search API operation latency. +* `searchResultsFound`: The number of tickets found in a specified search API call. diff --git a/_data-prepper/pipelines/configuration/sources/documentdb.md b/_data-prepper/pipelines/configuration/sources/documentdb.md new file mode 100644 index 00000000..551bb3fe --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/documentdb.md @@ -0,0 +1,98 @@ +--- +layout: default +title: DocumentDB +parent: Sources +grand_parent: Pipelines +nav_order: 10 +--- + +# DocumentDB source + +The `documentdb` source reads documents from [Amazon DocumentDB](https://aws.amazon.com/documentdb/) collections. +It can read historical data from an export and keep up to date on the data using Amazon DocumentDB [change streams](https://docs.aws.amazon.com/documentdb/latest/developerguide/change_streams.html). + +The `documentdb` source reads data from Amazon DocumentDB and puts that data into an [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) bucket. +Then, other OpenSearch Data Prepper workers read from the S3 bucket to process data. + +## Usage +The following example pipeline uses the `documentdb` source: + +```yaml +version: "2" +documentdb-pipeline: + source: + documentdb: + host: "docdb-mycluster.cluster-random.us-west-2.docdb.amazonaws.com" + port: 27017 + authentication: + {% raw %}username: ${{aws_secrets:secret:username}} + password: ${{aws_secrets:secret:password}}{% endraw %} + aws: + sts_role_arn: "arn:aws:iam::123456789012:role/MyRole" + s3_bucket: my-bucket + s3_region: us-west-2 + collections: + - collection: my-database.my-collection + export: true + stream: true + acknowledgments: true +``` +{% include copy.html %} + +## Configuration + +You can use the following options to configure the `documentdb` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`host` | Yes | String | The hostname of the Amazon DocumentDB cluster. +`port` | No | Integer | The port number of the Amazon DocumentDB cluster. Defaults to `27017`. +`trust_store_file_path` | No | String | The path to a truststore file that contains the public certificate for the Amazon DocumentDB cluster. +`trust_store_password` | No | String | The password for the truststore specified by `trust_store_file_path`. +`authentication` | Yes | Authentication | The authentication configuration. See the [authentication](#authentication) section for more information. +`collections` | Yes | List | A list of collection configurations. Exactly one collection is required. See the [collections](#collection) section for more information. +`s3_bucket` | Yes | String | The S3 bucket to use for processing events from Amazon DocumentDB. +`s3_prefix` | No | String | An optional Amazon S3 key prefix. By default, there is no key prefix. +`s3_region` | No | String | The AWS Region in which the S3 bucket resides. +`aws` | Yes | AWS | The AWS configuration. See the [`aws`](#aws) section for more information. +`id_key` | No | String | When specified, the Amazon DocumentDB `_id` field is set to the key name specified by `id_key`. You can use this when you need more information than is provided by the `ObjectId` string saved to your sink. By default, the `_id` is not included as part of the event. +`direct_connection` | No | Boolean | When `true`, the MongoDB driver connects directly to the specified Amazon DocumentDB server(s) without discovering and connecting to the entire replica set. Defaults to `true`. +`read_preference` | No | String | Determines how to read from Amazon DocumentDB. See [Read Preference Modes](https://www.mongodb.com/docs/v3.6/reference/read-preference/#read-preference-modes) for more information. Defaults to `primaryPreferred`. +`disable_s3_read_for_leader` | No | Boolean | When `true`, the current leader node does not read from Amazon S3. It only reads the stream. Defaults to `false`. +`scan_mode` | No | String | Determines whether the pipeline continues to list S3 folder partitions in which no new objects are found. Valid values are `idle_optimized` and `continuous`. In `idle_optimized` mode, a folder partition in which no objects are found for 1 hour is no longer listed until a later bucket scan finds new objects in that folder. This reduces the number of S3 `ListObjectsV2` requests while the collection is idle but delays the detection of the first changes written to that folder after the idle period. In `continuous` mode, the pipeline keeps listing every folder partition, so new changes are detected sooner at the cost of more `ListObjectsV2` requests. Defaults to `idle_optimized`. +`partition_acknowledgment_timeout` | No | Duration | Configures the amount of time during which the node holds a partition. Defaults to `PT2H`. +`acknowledgments` | No | Boolean | When set to `true`, enables [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) on the source after events are sent to the sinks. Defaults to `false`. +`insecure` | No | Boolean | Disables TLS. Defaults to `false`. Do not use this value in production. +`ssl_insecure_disable_verification` | No | Boolean | Disables TLS hostname verification. Defaults to `false`. Do not enable this flag in production. Instead, use the `trust_store_file_path` to verify the hostname. + +### `authentication` + +The following parameters enable you to configure `authentication` for the Amazon DocumentDB cluster. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`username` | Yes | String | The username to use when authenticating with the Amazon DocumentDB cluster. Supports automatic refresh. +`password` | Yes | String | The password to use when authenticating with the Amazon DocumentDB cluster. Supports automatic refresh. + +### `collection` + +The following parameters enable you to configure `collection` to read from the Amazon DocumentDB cluster. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`collection` | Yes | String | The name of the collection, in the `<database>.<collection>` format. +`export` | No | Boolean | Whether to include an export or a full load. Defaults to `true`. +`stream` | No | Boolean | Whether to enable a stream. Defaults to `true`. +`partition_count` | No | Integer | Defines the number of partitions to create in Amazon S3. Defaults to `100`. +`export_batch_size` | No | Integer | Defaults to `10,000`. +`stream_batch_size` | No | Integer | Defaults to `1,000`. + +## `aws` + +The following parameters enable you to configure your access to Amazon DocumentDB. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon Simple Queue Service (Amazon SQS) and Amazon S3. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. +`sts_external_id` | No | String | An external STS ID used when Data Prepper assumes the STS role. See `ExternalID` in the [STS AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API reference documentation. diff --git a/_data-prepper/pipelines/configuration/sources/dynamo-db.md b/_data-prepper/pipelines/configuration/sources/dynamo-db.md index 597e8351..ce70ef5d 100644 --- a/_data-prepper/pipelines/configuration/sources/dynamo-db.md +++ b/_data-prepper/pipelines/configuration/sources/dynamo-db.md @@ -1,12 +1,12 @@ --- layout: default -title: dynamodb +title: DynamoDB parent: Sources grand_parent: Pipelines -nav_order: 3 +nav_order: 20 --- -# dynamodb +# DynamoDB source The `dynamodb` source enables change data capture (CDC) on [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) tables. It can receive table events, such as `create`, `update`, or `delete`, using DynamoDB streams and supports initial snapshots using [point-in-time recovery (PITR)](https://aws.amazon.com/dynamodb/pitr/). @@ -31,6 +31,7 @@ cdc-pipeline: s3_prefix: "myprefix" stream: start_position: "LATEST" # Read latest data from streams (Default) + view_on_remove: NEW_IMAGE aws: region: "us-west-2" sts_role_arn: "arn:aws:iam::123456789012:role/my-iam-role" @@ -42,13 +43,15 @@ The following tables describe the configuration options for the `dynamodb` sourc Option | Required | Type | Description :--- | :--- | :--- | :--- -`aws` | Yes | AWS | The AWS configuration. See [aws](#aws) for more information. -`acknowledgments` | No | Boolean | When `true`, enables `s3` sources to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. -`shared_acknowledgement_timeout` | No | Duration | The amount of time that elapses before the data read from a DynamoDB stream expires when used with acknowledgements. Default is 10 minutes. -`s3_data_file_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from a DynamoDB export expires when used with acknowledgments. Default is 5 minutes. +`aws` | Yes | AWS | The AWS configuration. See [`aws`](#aws) for more information. +`acknowledgments` | No | Boolean | When `true`, enables the `dynamodb` source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `false`. +`shard_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from a DynamoDB stream expires when used with acknowledgments. Default is 30 minutes. +`s3_data_file_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from a DynamoDB export expires when used with acknowledgments. Default is 15 minutes. `tables` | Yes | List | The configuration for the DynamoDB table. See [tables](#tables) for more information. +<!-- vale off --> ### aws +<!-- vale on --> Use the following options in the AWS configuration. @@ -56,10 +59,13 @@ Option | Required | Type | Description :--- | :--- | :--- | :--- `region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). `sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon Simple Queue Service (Amazon SQS) and Amazon Simple Storage Service (Amazon S3). Defaults to `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). -`aws_sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the sink plugin. +`sts_external_id` | No | String | The external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. +<!-- vale off --> ### tables +<!-- vale on --> Use the following options with the `tables` configuration. @@ -82,15 +88,129 @@ Option | Required | Type | Description #### Stream option -The following option lets you customize how the pipeline reads events from the DynamoDB table. +The following options let you customize how the pipeline reads events from the DynamoDB table. -Option | Required | Type | Description +Option | Required | Type | Description :--- | :--- | :--- | :--- `start_position` | No | String | The position from where the source starts reading stream events when the DynamoDB stream option is enabled. `LATEST` starts reading events from the most recent stream record. +`view_on_remove` | No | Enum | The [stream record view](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) to use for REMOVE events from DynamoDB streams. Must be either `NEW_IMAGE` or `OLD_IMAGE` . Defaults to `NEW_IMAGE`. If the `OLD_IMAGE` option is used and the old image can not be found, the source will find the `NEW_IMAGE`. +`disable_checkpointing` | No | Boolean | When `true`, the source does not resume reading a shard from its saved checkpoint. Each time the source starts reading a shard, it reads from the oldest available record in the shard. Default is `false`. +`shard_discovery_interval` | No | Duration | How often the leader node checks the DynamoDB stream for new shards. Because DynamoDB Streams continuously closes shards and opens new child shards, records in a new shard are not read until the next check. A shorter interval reduces this delay at the cost of more frequent DynamoDB Streams API requests. Minimum is `1s`. Default is `60s`. + +## Exposed metadata attributes + +The following metadata will be added to each event that is processed by the `dynamodb` source. These metadata attributes can be accessed using the [expression syntax `getMetadata` function]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-metadata/). + +* `primary_key`: The primary key of the DynamoDB item. For tables that only contain a partition key, this value provides the partition key. For tables that contain both a partition and sort key, the `primary_key` attribute will be equal to the partition and sort key, separated by a `|`, for example, `partition_key|sort_key`. +* `partition_key`: The partition key of the DynamoDB item. +* `sort_key`: The sort key of the DynamoDB item. This will be null if the table does not contain a sort key. +* `dynamodb_timestamp`: The timestamp of the DynamoDB item. This will be the export time for export items and the DynamoDB stream event time for stream items. This timestamp is used by sinks to emit an `EndtoEndLatency` metric for DynamoDB stream events that tracks the latency between a change occurring in the DynamoDB table and that change being applied to the sink. +* `document_version`: Uses the `dynamodb_timestamp` to modify break ties between stream items that are received in the same second. Recommend for use with the `opensearch` sink's `document_version` setting. +* `opensearch_action`: A default value for mapping DynamoDB event actions to OpenSearch actions. This action will be `index` for export items, and `INSERT` or `MODIFY` for stream events, and `REMOVE` stream events when the OpenSearch action is `delete`. +* `dynamodb_event_name`: The exact event type for the item. Will be `null` for export items and either `INSERT`, `MODIFY`, or `REMOVE` for stream events. +* `table_name`: The name of the DynamoDB table that an event came from. +* `ttl_delete`: A Boolean value indicating whether a `REMOVE` event was triggered by DynamoDB Time-To-Live (TTL). The `ttl_delete` attribute is `true` for TTL-based deletions and `false` for all other events. This metadata can be used with conditional routing or filtering to handle TTL deletions differently from manual deletions. +## Permissions +The following are the minimum required permissions for running DynamoDB as a source: +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "allowDescribeTable", + "Effect": "Allow", + "Action": [ + "dynamodb:DescribeTable" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:{account-id}:table/my-table" + ] + }, + { + "Sid": "allowRunExportJob", + "Effect": "Allow", + "Action": [ + "dynamodb:DescribeContinuousBackups", + "dynamodb:ExportTableToPointInTime" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:{account-id}:table/my-table" + ] + }, + { + "Sid": "allowCheckExportjob", + "Effect": "Allow", + "Action": [ + "dynamodb:DescribeExport" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:{account-id}:table/my-table/export/*" + ] + }, + { + "Sid": "allowReadFromStream", + "Effect": "Allow", + "Action": [ + "dynamodb:DescribeStream", + "dynamodb:GetRecords", + "dynamodb:GetShardIterator" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:{account-id}:table/my-table/stream/*" + ] + }, + { + "Sid": "allowReadAndWriteToS3ForExport", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:AbortMultipartUpload", + "s3:PutObject", + "s3:PutObjectAcl" + ], + "Resource": [ + "arn:aws:s3:::my-bucket/*" + ] + } + ] +} +``` +When performing an export, the `"Sid": "allowReadFromStream"` section is not required. If only reading from DynamoDB streams, the +`"Sid": "allowReadAndWriteToS3ForExport"`, `"Sid": "allowCheckExportjob"`, and ` "Sid": "allowRunExportJob"` sections are not required. + +## Limitations + +Note the following limitations: + +* Each Data Prepper instance can process up to 150 DynamoDB stream shards in parallel. To prevent high latency and data loss, set the number of Data Prepper instances to the maximum number of open shards divided by 150 (rounded up to the nearest integer). + +## Metrics + +The `dynamodb` source includes the following metrics. + +### Counters + +* `exportJobSuccess`: The number of export jobs that have been submitted successfully. +* `exportJobFailure`: The number of export job submission attempts that have failed. +* `exportS3ObjectsTotal`: The total number of export data files found in S3. +* `exportS3ObjectsProcessed`: The total number of export data files that have been processed successfully from S3. +* `exportRecordsTotal`: The total number of records found in the export. +* `exportRecordsProcessed`: The total number of export records that have been processed successfully. +* `exportRecordsProcessingErrors`: The number of export record processing errors. +* `changeEventsProcessed`: The number of change events processed from DynamoDB streams. +* `changeEventsProcessingErrors`: The number of processing errors for change events from DynamoDB streams. +* `shardProgress`: The incremented shard progress when DynamoDB streams are being read correctly. This being`0` for any significant amount of time means there is a problem with the pipeline that has streams enabled. + +### Gauges + +The `dynamodb` source includes the following gauges: + +* `totalOpenShards`: The number of open shards in the DynamoDB stream. Open shards are shards that are not assigned an `EndingSequenceNumber`. +* `activeShardsInProcessing`: The number of shards currently being processed by Data Prepper. diff --git a/_data-prepper/pipelines/configuration/sources/file.md b/_data-prepper/pipelines/configuration/sources/file.md new file mode 100644 index 00000000..20ad37e7 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/file.md @@ -0,0 +1,213 @@ +--- +layout: default +title: File +parent: Sources +grand_parent: Pipelines +nav_order: 24 +--- + +# File source + +The `file` plugin reads events from one or more local files. By default, the source reads each file once when the pipeline starts. This is useful for loading seed data, testing processors and sinks, or replaying a fixed dataset. To continuously read lines appended to files, such as application logs, set `tail` to `true`. + +The source reads files in one of the following ways, depending on its configuration: + +- If you specify `path` and none of the `paths`, `exclude_paths`, `codec`, or `tail` settings, the source reads the file once, line by line, and creates events according to the `format` and `record_type` settings. +- If you specify `paths`, `exclude_paths`, `codec`, or `tail`, the source ignores the `format` setting. When `codec` is configured, `record_type` must be set to `event`. It parses each file using the configured `codec` or, if no `codec` is configured, creates one event for each line. For the structure of these events, see [Event structure](#event-structure). + +We recommend setting `record_type` to `event` and configuring a `codec`. The `format` setting and the `string` record type are legacy settings. + +## Configuration + +The following table lists the general settings for the `file` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`path` | Conditionally | String | An absolute path to the input file inside the Data Prepper container, for example, `/usr/share/data-prepper/data/input.jsonl`. Either `path` or `paths` is required. +`paths` | Conditionally | List | A list of absolute file paths or glob patterns that specify the files to read, for example, `/var/log/app/*.log` or `/var/log/**/*.log`. Either `path` or `paths` is required. +`exclude_paths` | No | List | A list of absolute file paths or glob patterns that specify files to skip among the files matched by `paths`. +`format` | No | String | Specifies how to interpret the file content. Valid values are `json` and `plain`. Use `json` when your file has one JSON object per line or a JSON array. Use `plain` for raw text lines. Applies only when `path` is used without `paths`, `exclude_paths`, `codec`, or `tail`. This is a legacy setting; use `codec` for new configurations. Default is `plain`. +`record_type` | No | String | The type of output record produced by the source. Valid values are `event` and `string`. Use `event` to produce structured events expected by downstream processors and the OpenSearch sink. Must be set to `event` when `codec` is configured. The `string` value is a legacy setting. Default is `string`. +`codec` | No | Object | The codec used to parse the file content, for example, `ndjson`, `json`, `csv`, or `newline`. When `codec` is set, the source creates one event for each record parsed by the codec, and `record_type` must be set to `event`. For codec settings, see [codec]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/#codec). +`compression` | No | String | The compression algorithm used to decompress the files. Valid values are `none`, `gzip`, `snappy`, and `zstd`. Applies only when `path` is used without `paths`, `exclude_paths`, `codec`, or `tail`, or when `codec` is set and `tail` is `false`. Default is `none`. +`encoding` | No | String | The character encoding of the files, for example, `UTF-8` or `ISO-8859-1`. Not applied when `codec` is set. Default is `UTF-8`. +`tail` | No | Boolean | When `true`, the source continuously monitors the files matched by `paths` and `path`, reads lines appended to them, and detects new, rotated, and removed files. When `false`, the source reads each file once. For more settings, see [Tail settings](#tail-settings). Default is `false`. + +Duration settings accept ISO 8601 duration notation, such as `PT30S`, or simple notation for seconds and milliseconds, such as `30s` or `500ms`. + +### File reading settings + +The following settings apply only when `paths`, `exclude_paths`, `codec`, or `tail` is configured. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`include_file_metadata` | No | Boolean | When `true`, adds the `file` object and `offset` field to each event. For more information, see [Event structure](#event-structure). Not applied when `codec` is set. Default is `true`. +`max_line_length` | No | Integer | The maximum length of a line, in characters. The source truncates longer lines to this length. Not applied when `codec` is set. Default is `1048576`. +`read_buffer_size` | No | Integer | The size of the buffer used to read from a file, in bytes. Default is `65536`. +`max_active_files` | No | Integer | The maximum number of files that the source reads at the same time. Additional matching files wait in a queue until a reader becomes available. Default is `1000`. +`reader_threads` | No | Integer | The number of threads used to read files. Default is `4` when `tail` is `true` and `1` when `tail` is `false`. +`max_read_time_per_file` | No | Duration | The maximum amount of time that a reader spends reading a file in a single pass before releasing the thread to other files. This setting also limits how long the source retries writing an event to a full buffer. If the buffer remains full for longer than this time, the event is dropped. Default is `5s`. +`fingerprint_bytes` | No | Integer | The number of bytes at the start of a file used to compute a fingerprint that identifies the file. The source uses the fingerprint only when the file system does not provide a unique file key, such as an inode. Default is `1024`. + +### Tail settings + +The following settings apply when `tail` is `true`. In tail mode, the source detects two types of file rotation: a file that is renamed and replaced by a new file at the same path, and a file that is truncated after being copied. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`start_position` | No | String | The position from which the source starts reading a file that has no checkpoint entry. Valid values are `beginning` and `end`. When set to `end`, the source skips any content that a file contains when the source first opens it, including files discovered after the pipeline starts. The `end` value is valid only when `tail` is `true`. Default is `beginning`. +`poll_interval` | No | Duration | How often the source scans `paths` for new and removed files. When the file system provides change notifications, the source uses them to detect new and removed files and scans at 10 times this interval. Default is `1s`. +`rotate_wait` | No | Duration | The amount of time that the source waits after a monitored file disappears before treating the file as removed. Default is `5s`. +`rotation_drain_timeout` | No | Duration | The maximum amount of time that the source spends reading the remaining data from a file after detecting that the file was renamed. Default is `30s`. +`close_inactive` | No | Duration | The amount of time without new data after which the source closes the reader for a file. Default is `PT30M`. +`close_removed` | No | Boolean | When `true`, the source closes the reader for a file after the file is removed. Default is `true`. + +### Checkpoint settings + +The source records the read position of each file in a checkpoint so that it can resume from that position after a restart. The following settings apply only when `paths`, `exclude_paths`, `codec`, or `tail` is configured. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`checkpoint_file` | No | String | The path to the file in which the source stores checkpoints. If not set, the source does not persist checkpoints, and after a restart it reads files according to `start_position`. +`checkpoint_interval` | No | Duration | How often the source writes checkpoints to the `checkpoint_file`. Default is `5s`. +`checkpoint_cleanup_after` | No | Duration | The amount of time after which the source removes the checkpoint entry of a completed file. A file is completed when it is fully read and `tail` is `false` or when it is removed and `tail` is `true`. Default is `P7D` (7 days). + +### Acknowledgment settings + +The following settings apply only when `paths`, `exclude_paths`, `codec`, or `tail` is configured. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`acknowledgments` | No | Boolean | When `true`, enables [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines/#end-to-end-acknowledgments). The source groups events from each file into batches and records the position up to which the sinks have acknowledged the events. Default is `false`. +`batch_size` | No | Integer | The maximum number of events in an acknowledgment batch. Default is `100`. +`batch_timeout` | No | Duration | The maximum amount of time that an acknowledgment batch remains open before the source completes it. Default is `5s`. +`acknowledgment_timeout` | No | Duration | The amount of time that the source waits for the sinks to acknowledge a batch. Default is `60s`. +`max_acknowledgment_retries` | No | Integer | The maximum number of consecutive negative acknowledgments for a file. After this number is exceeded, the source records the failed batch as acknowledged and continues. Default is `3`. + +## Event structure + +When `paths`, `exclude_paths`, or `tail` is configured and `codec` is not set, the source creates one event for each line. The event contains the following fields. + +Field | Description +:--- | :--- +`message` | The text of the line. +`file.path` | The absolute path of the file. Added when `include_file_metadata` is `true`. +`file.name` | The name of the file. Added when `include_file_metadata` is `true`. +`offset` | The position in the file, in bytes, at which the source started the read that contains the line. Lines read together share the same offset. Added when `include_file_metadata` is `true`. + +The following is an example event: + +```json +{ + "message": "2026-10-21T10:00:01Z [ERROR] order 1002 failed", + "file": { + "path": "/var/log/app/app.log", + "name": "app.log" + }, + "offset": 0 +} +``` + +To parse structured lines, such as JSON, use a `codec` or a processor such as [`parse_json`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/parse-json/). + +## Examples + +The following examples demonstrate how different file types can be processed. + +### JSON file + +The following example processes a JSON file: + +```yaml +file-to-opensearch: + source: + file: + path: /usr/share/data-prepper/data/input.ndjson + format: json + record_type: event + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: file-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} + +### Plain text file + +A raw text file can be processed using the following pipeline: + +```yaml +plain-file-to-opensearch: + source: + file: + path: /usr/share/data-prepper/data/app.log + format: plain + record_type: event + processor: + - grok: + match: + message: + - '%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:msg}' + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: plain-file-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} + +### CSV file + +You can process a CSV file using the `csv` processor: + +```yaml +csv-file-to-opensearch: + source: + file: + path: /usr/share/data-prepper/data/ingest.csv + format: plain + record_type: event + processor: + - csv: + column_names: ["time","level","message"] + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: csv-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} + +### Tailing log files + +The following example continuously reads lines appended to all `.log` files in a directory, skips the debug log, and stores read positions in a checkpoint file so that the pipeline resumes from the last position after a restart: + +```yaml +tail-logs-to-opensearch: + source: + file: + paths: ["/usr/share/data-prepper/logs/*.log"] + exclude_paths: ["/usr/share/data-prepper/logs/debug.log"] + tail: true + checkpoint_file: /usr/share/data-prepper/data/file-checkpoints.json + processor: + - grok: + match: + message: + - '%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:msg}' + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: tail-logs-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sources/http.md b/_data-prepper/pipelines/configuration/sources/http.md new file mode 100644 index 00000000..909ea58c --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/http.md @@ -0,0 +1,207 @@ +--- +layout: default +title: HTTP +parent: Sources +grand_parent: Pipelines +nav_order: 30 +redirect_from: + - /data-prepper/pipelines/configuration/sources/http-source/ +--- + +# HTTP source + +The `http` plugin accepts HTTP requests from clients. The following table describes options you can use to configure the `http` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`port` | No | Integer | The port that the source is running on. Default value is `2021`. Valid options are between `0` and `65535`. +`path` | No | String | The URI path for log ingestion should start with a forward slash (/), for example, `/${pipelineName}/logs`. The `${pipelineName}` placeholder will be replaced with the pipeline name. The default value is `/log/ingest`. +`health_check_service` | No | Boolean | Enables the health check service on the `/health` endpoint on the defined port. Default value is `false`. +`unauthenticated_health_check` | No | Boolean | Determines whether or not authentication is required on the health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default value is `false`. +`request_timeout` | No | Integer | The request timeout, in milliseconds. Default value is `10000`. +`thread_count` | No | Integer | The number of threads to keep in the ScheduledThreadPool. Default value is `200`. +`max_connection_count` | No | Integer | The maximum allowed number of open connections. Default value is `500`. +`max_pending_requests` | No | Integer | The maximum allowed number of tasks in the `ScheduledThreadPool` work queue. Default value is `1024`. +`max_request_length` | No | ByteCount | The maximum number of bytes allowed in the payload of a single HTTP request. Default value is `10mb`. +`metadata_headers` | No | List | A list of HTTP request header names. The source adds the values of these headers to the metadata of each event created from the request. Header names are case insensitive. The source stores the values in the `headers` metadata attribute as a map keyed by the lowercase header name. A header that appears multiple times in a request is stored as a list of values. For security, the source never extracts the `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `WWW-Authenticate`, `Proxy-Authenticate`, `X-Api-Key`, `X-Csrf-Token`, `X-Xsrf-Token`, `X-Auth-Token`, `X-Amz-Security-Token`, and `X-Amz-Credential` headers. Headers are not added when the pipeline uses a buffer that stores raw bytes, such as the `kafka` buffer. For an example, see [Adding request headers to event metadata](#adding-request-headers-to-event-metadata). +`compression` | No | String | The compression type applied to the client request payload. Valid values are `none` and `gzip`. Use `gzip` to apply gzip decompression to incoming requests that contain the `Content-Encoding: gzip` header. Default is `none`. +`codec` | No | Object | The codec used to parse the request body, for example, `ndjson` or `csv`. When `codec` is set, the source creates one event for each record parsed by the codec. If not set, the request body must be a JSON array. Not applied when the pipeline uses a buffer that stores raw bytes, such as the `kafka` buffer. For codec settings, see [codec]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/s3/#codec). +`authentication` | No | Object | An authentication configuration. By default, this creates an unauthenticated server for the pipeline. This uses pluggable authentication for HTTPS. To use basic authentication define the `http_basic` plugin with a `username` and `password`. To provide customer authentication, use or create a plugin that implements [ArmeriaHttpAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/1.2.0/data-prepper-plugins/armeria-common/src/main/java/com/amazon/dataprepper/armeria/authentication/ArmeriaHttpAuthenticationProvider.java). +`ssl` | No | Boolean | Enables TLS/SSL. Default value is `false`. +`ssl_certificate_file` | Conditionally | String | The SSL certificate chain file path or Amazon Simple Storage Service (Amazon S3) path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true` and `use_acm_certificate_for_ssl` is set to `false`. +`ssl_key_file` | Conditionally | String | The SSL key file path or Amazon S3 path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true` and `use_acm_certificate_for_ssl` is set to `false`. +`use_acm_certificate_for_ssl` | No | Boolean | Enables TLS/SSL using the certificate and private key from AWS Certificate Manager (ACM). Default is `false`. +`acm_certificate_arn` | Conditionally | String | The ACM certificate Amazon Resource Name (ARN). The ACM certificate takes preference over Amazon S3 or a local file system certificate. Required if `use_acm_certificate_for_ssl` is set to true. +`acm_private_key_password` | No | String | ACM private key password that decrypts the private key. If not provided, Data Prepper generates a random password. +`acm_certificate_timeout_millis` | No | Integer | Timeout, in milliseconds, that ACM takes to get certificates. Default value is 120000. +`aws_region` | Conditionally | String | AWS region used by ACM or Amazon S3. Required if `use_acm_certificate_for_ssl` is set to true or `ssl_certificate_file` and `ssl_key_file` is the Amazon S3 path. + +<!--- ## Configuration + +Content will be added to this section.---> + +## Ingestion + +Clients should send HTTP `POST` requests to the endpoint `/log/ingest`. + +By default, the `http` source accepts JSON UTF-8 request bodies containing an array of objects, for example, `[{"key1": "value1"}, {"key2": "value2"}]`. To accept other formats, configure a `codec`. + +## Example + +The following examples demonstrate different configurations that can be used with the `http` source. + +### Minimal HTTP source + +The following is the minimal configuration using all default values: + +```yaml +minimal-http-pipeline: + source: + http: + sink: + - stdout: {} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -s "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + --data '[{"msg":"one"},{"msg":"two"}]' +``` +{% include copy.html %} + +You should see the following output in the Data Prepper logs: + +``` +{"msg":"one"} +{"msg":"two"} +``` + +### Custom path using the pipeline name and health check + +The following example uses a custom path, configures a custom port, and enables health checks: + +```yaml +audit-pipeline: + source: + http: + port: 2022 + path: "/${pipelineName}/logs" # -> /audit-pipeline/logs + health_check_service: true + unauthenticated_health_check: true + sink: + - stdout: {} +``` +{% include copy.html %} + +You can use the following command to check the pipeline health: + +```bash +curl -s "http://localhost:2022/health" +``` +{% include copy.html %} + +You can ingest data using the following command: + +```bash +curl -s "http://localhost:2022/audit-pipeline/logs" \ + -H "Content-Type: application/json" \ + --data '[{"event":"login","user":"alice"}]' +``` +{% include copy.html %} + +### Basic authentication on the source + +The following example configures a custom port and path, enables health checks, and configures basic authentication: + +```yaml +secure-intake-pipeline: + source: + http: + port: 2023 + path: /ingest + authentication: + http_basic: + username: ingest + password: s3cr3t + health_check_service: true + unauthenticated_health_check: true + sink: + - stdout: {} + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -s -u ingest:s3cr3t "http://localhost:2023/ingest" \ + -H "Content-Type: application/json" \ + --data '[{"service":"web","status":"ok"}]' +``` +{% include copy.html %} + +### Adding request headers to event metadata + +The following example adds the `X-Tenant-Id` request header to the metadata of each event and then copies the header value into the `tenant` field using the `add_entries` processor. To read a single header, use the `headers/<lowercase-header-name>` metadata key: + +```yaml +tenant-pipeline: + source: + http: + metadata_headers: ["X-Tenant-Id"] + processor: + - add_entries: + entries: + - key: tenant + value_expression: 'getMetadata("headers/x-tenant-id")' + sink: + - stdout: {} +``` +{% include copy.html %} + +You can test this pipeline using the following command: + +```bash +curl -s "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -H "X-Tenant-Id: store-eu" \ + --data '[{"order":"1001"}]' +``` +{% include copy.html %} + +You should see the following output in the Data Prepper logs: + +``` +{"order":"1001","tenant":"store-eu"} +``` + +## Metrics + +The `http` source includes the following metrics. + +### Counters + +- `requestsReceived`: Measures the total number of requests received by the `/log/ingest` endpoint. +- `requestsRejected`: Measures the total number of requests rejected (429 response status code) by the HTTP Source plugin. +- `successRequests`: Measures the total number of requests successfully processed (200 response status code) the by HTTP Source plugin. +- `badRequests`: Measures the total number of requests with either an invalid content type or format processed by the HTTP Source plugin (400 response status code). +- `requestTimeouts`: Measures the total number of requests that time out in the HTTP source server (415 response status code). +- `requestsTooLarge`: Measures the total number of requests where the size of the event is larger than the buffer capacity (413 response status code). +- `internalServerError`: Measures the total number of requests processed by the HTTP Source with a custom exception type (500 response status code). + +### Timers + +- `requestProcessDuration`: Measures the latency of requests processed by the HTTP Source plugin in seconds. + +### Distribution summaries + +- `payloadSize`: Measures the incoming request payload size in bytes. diff --git a/_data-prepper/pipelines/configuration/sources/iceberg.md b/_data-prepper/pipelines/configuration/sources/iceberg.md new file mode 100644 index 00000000..51bc9fa4 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/iceberg.md @@ -0,0 +1,206 @@ +--- +layout: default +title: Iceberg +parent: Sources +grand_parent: Pipelines +nav_order: 35 +--- + +# Iceberg source + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/data-prepper/issues/6552). +{: .warning} + +The `iceberg` source provides change data capture (CDC) on [Apache Iceberg](https://iceberg.apache.org/) tables. It polls for new Iceberg snapshots and detects `INSERT`, `UPDATE`, and `DELETE` operations by computing changes between snapshots using the [`IncrementalChangelogScan`](https://iceberg.apache.org/javadoc/latest/org/apache/iceberg/IncrementalChangelogScan.html) API. + +The source supports the following: +- Iceberg table format v1, v2, and v3. +- Copy-on-Write (CoW) tables only. Merge-on-Read (MoR) tables are not supported. +- Parquet, Avro, and ORC file formats. +- Any Iceberg catalog implementation, including AWS Glue Data Catalog, Hive Metastore, and REST catalogs. + +The source includes two ingestion modes: + +1. **Export**: An initial snapshot load that reads the current state of the table. +2. **Stream**: Polls for new snapshots and processes incremental changelog events. + +## Prerequisites + +To use the Iceberg source, you must enable the experimental `iceberg` plugin in `data-prepper-config.yaml`: + +```yaml +experimental: + enabled_plugins: + source: + - iceberg +``` +{% include copy.html %} + +## Usage + +The following example pipeline specifies an `iceberg` source. It reads incremental changes from an Iceberg table using a REST catalog with Amazon S3 storage. The `catalog` is defined at the top level so that all tables share the same catalog configuration. + +In the sink configuration, `action` is set to `${getMetadata("bulk_action")}` so that `INSERT` and `UPDATE` operations upsert the document while `DELETE` operations remove it. The `document_id` is set to `${getMetadata("document_id")}`, which concatenates the `identifier_columns` values using a `|` separator so that each Iceberg row maps to a unique OpenSearch document: + +```yaml +version: "2" +iceberg-cdc-pipeline: + source: + iceberg: + catalog: + type: rest + uri: "http://iceberg-rest-catalog:8181" + io-impl: "org.apache.iceberg.aws.s3.S3FileIO" + client.region: "us-east-1" + tables: + - table_name: "my_database.my_table" + identifier_columns: ["id"] + polling_interval: "PT30S" + acknowledgments: true + sink: + - opensearch: + hosts: ["https://localhost:9200"] + index: "my-index" + action: "${getMetadata(\"bulk_action\")}" + document_id: "${getMetadata(\"document_id\")}" +``` +{% include copy.html %} + +To use a different catalog for a specific table, specify `catalog` at the table level to override the top-level definition: + +```yaml +iceberg: + catalog: + type: rest + uri: "http://iceberg-rest-catalog:8181" + io-impl: "org.apache.iceberg.aws.s3.S3FileIO" + tables: + - table_name: "db.table_a" + identifier_columns: ["id"] + - table_name: "db.table_b" + identifier_columns: ["id"] + catalog: + type: glue + warehouse: "s3://other-bucket/warehouse" + io-impl: "org.apache.iceberg.aws.s3.S3FileIO" +``` +{% include copy.html %} + +## Configuration options + +The `iceberg` source supports the following configuration options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`catalog` | No | Map | Default catalog properties applied to all tables. When a table specifies its own `catalog`, the table-level definition fully replaces the top-level one. For common properties, see [catalog](#catalog). +`tables` | Yes | List | A list of Iceberg table configurations. For supported options, see [tables](#tables). +`polling_interval` | No | Duration | How often the leader node polls for new snapshots. Supports [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) duration notation such as `PT30S` or `PT5M`. Default is `PT30S`. +`acknowledgments` | No | Boolean | When `true`, enables [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments). Default is `true`. +`shuffle` | No | Object | Configuration for the distributed shuffle used when processing snapshots with `DELETE` operations. For supported options, see [shuffle](#shuffle). + +<!-- vale off --> +### tables +<!-- vale on --> + +Use the following options for each table entry. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`table_name` | Yes | String | The fully qualified Iceberg table name (for example, `my_database.my_table`). +`catalog` | No | Map | A map of Apache Iceberg catalog properties. When specified, fully replaces the top-level `catalog`. For common properties, see [catalog](#catalog). +`identifier_columns` | No | List | A list of column names used as the document identifier for `UPDATE` and `DELETE` detection. Required when processing tables with `UPDATE` or `DELETE` operations. If not specified, the source cannot determine document IDs or correctly detect updates. +`disable_export` | No | Boolean | When `true`, skips the initial snapshot export and starts with CDC only. Default is `false`. + +<!-- vale off --> +### catalog +<!-- vale on --> + +The `catalog` option accepts any property supported by the Apache Iceberg catalog implementation. For the full list of available properties, see the documentation for each catalog type, such as the [REST catalog](https://iceberg.apache.org/rest-catalog-spec/), [AWS Glue](https://iceberg.apache.org/docs/latest/aws/#glue-catalog), or [Hive Metastore](https://iceberg.apache.org/docs/latest/hive/#global-hive-catalog). The following table lists the common properties. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`type` | Yes | String | The catalog type. Supported values include `glue`, `hive`, `rest`, and other Iceberg catalog implementations. +`io-impl` | No | String | The FileIO implementation class. For example, `org.apache.iceberg.aws.s3.S3FileIO` for Amazon S3 or `org.apache.iceberg.hadoop.HadoopFileIO` for HDFS. When not specified, each catalog uses its own default (REST catalogs use `ResolvingFileIO`, which is selected automatically based on file path scheme, Glue uses `S3FileIO`, Hadoop and JDBC use `HadoopFileIO`). + +For AWS-specific catalog and S3 properties, see the [Apache Iceberg AWS integration documentation](https://iceberg.apache.org/docs/latest/aws/). + +<!-- vale off --> +### shuffle +<!-- vale on --> + +When processing snapshots that contain `DELETE` operations (`UPDATE` or `DELETE` in Copy-on-Write tables), the source uses a distributed shuffle to ensure correct results across multiple nodes. The shuffle routes all records containing the same `identifier_columns` values to the same node so that matching `INSERT` and `DELETE` pairs can be resolved correctly. + +The shuffle activates automatically when a snapshot contains `DELETE` operations. For `INSERT`-only snapshots, the shuffle is not used. + +The following table lists the `shuffle` configuration options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`partitions` | No | Integer | The number of hash partitions. Must be 1--10,000. Default is `64`. +`target_partition_size` | No | String | The target size for coalesced shuffle read tasks. Small adjacent partitions are merged to reduce the number of tasks. Default is `64mb`. +`storage_path` | No | String | The local directory for intermediate shuffle files. Default is `${data-prepper.dir}/data/shuffle` when `data-prepper.dir` is set, otherwise `${java.io.tmpdir}/data-prepper-shuffle`. +`port` | No | Integer | The port for the HTTP server used for node-to-node shuffle data transfer. Default is `4995`. +`ssl` | No | Boolean | When `true`, enables Transport Layer Security (TLS) for the shuffle HTTP server. Default is `true`. +`ssl_certificate_file` | Conditionally | String | The path to the TLS certificate file in PEM format. Supports local file paths and Amazon S3 URIs (for example, `s3://my-bucket/certs/cert.pem`). Required when `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. +`ssl_key_file` | Conditionally | String | The path to the TLS private key file in PEM format. Supports local file paths and Amazon S3 URIs (for example, `s3://my-bucket/certs/key.pem`). Required when `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. +`use_acm_certificate_for_ssl` | No | Boolean | When `true`, uses AWS Certificate Manager (ACM) for TLS certificates instead of `ssl_certificate_file` and `ssl_key_file`. Default is `false`. +`acm_certificate_arn` | Conditionally | String | The ACM certificate ARN. Required when `use_acm_certificate_for_ssl` is `true`. +`acm_private_key_password` | No | String | The password used to decrypt the private key exported from ACM. If not provided, Data Prepper generates a random password. +`acm_certificate_timeout_millis` | No | Integer | The maximum amount of time, in milliseconds, that Data Prepper waits to retrieve the certificate from ACM. Default is `120000`. +`aws_region` | Conditionally | String | The AWS Region for ACM or S3 certificate access. Required when `use_acm_certificate_for_ssl` is `true` or when certificate files are in Amazon S3. +`ssl_client_auth` | No | Boolean | When `true`, enables mutual TLS (mTLS) for node-to-node authentication. All nodes must present a valid client certificate during shuffle communication. Default is `false`. +`ssl_insecure_disable_verification` | No | Boolean | When `true`, disables TLS certificate verification for node-to-node shuffle communication. Default is `false`. + +When running multiple Data Prepper nodes, each node must be able to reach the other nodes on the configured `port`. +{: .note} + +## Exposed metadata attributes + +The following metadata attributes are added to each event processed by the `iceberg` source. These attributes can be accessed using the [expression syntax `getMetadata` function]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-metadata/): + +- `bulk_action`: The recommended bulk action for the OpenSearch sink. Set to `index` for `INSERT` and `UPDATE` operations, or `delete` for `DELETE` operations. +- `document_id`: The document identifier, composed by joining the `identifier_columns` values with a `|` separator. Only set when `identifier_columns` is configured. +- `iceberg_operation`: The CDC operation type. Set to `INSERT` or `DELETE`. When a row is updated in Iceberg, the source receives a `DELETE` and `INSERT` pair with the same `identifier_columns` values. The source recognizes this as an update and emits only the `INSERT` event, because upserting by `document_id` produces the correct result without a separate delete. +- `iceberg_table_name`: The name of the source Iceberg table. +- `iceberg_snapshot_id`: The snapshot ID from which the event originated. + +## Permissions + +The required permissions depend on the catalog type and storage backend. The following is an example of the minimum IAM permissions when using AWS Glue Data Catalog and Amazon S3: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "allowReadingFromS3", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:ListBucket", + "s3:GetBucketLocation" + ], + "Resource": [ + "arn:aws:s3:::my-iceberg-bucket", + "arn:aws:s3:::my-iceberg-bucket/*" + ] + }, + { + "Sid": "allowGlueCatalogAccess", + "Effect": "Allow", + "Action": [ + "glue:GetTable", + "glue:GetTables", + "glue:GetDatabase", + "glue:GetDatabases" + ], + "Resource": [ + "arn:aws:glue:region:account-id:catalog", + "arn:aws:glue:region:account-id:database/*", + "arn:aws:glue:region:account-id:table/*/*" + ] + } + ] +} +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sources/kafka.md b/_data-prepper/pipelines/configuration/sources/kafka.md index 4df72cfd..f8d50ecf 100644 --- a/_data-prepper/pipelines/configuration/sources/kafka.md +++ b/_data-prepper/pipelines/configuration/sources/kafka.md @@ -1,30 +1,32 @@ --- layout: default -title: kafka +title: Kafka parent: Sources grand_parent: Pipelines -nav_order: 6 +nav_order: 40 --- -# kafka +# Kafka source -You can use the Apache Kafka source (`kafka`) in Data Prepper to read records from one or more Kafka [topics](https://kafka.apache.org/intro#intro_concepts_and_terms). These records hold events that your Data Prepper pipeline can ingest. The `kafka` source uses Kafka's [Consumer API](https://kafka.apache.org/documentation/#consumerapi) to consume messages from the Kafka broker, which then creates Data Prepper events for further processing by the Data Prepper pipeline. +You can use the Apache Kafka source (`kafka`) in OpenSearch Data Prepper to read records from one or more Kafka [topics](https://kafka.apache.org/intro#intro_concepts_and_terms). These records hold events that your Data Prepper pipeline can ingest. The `kafka` source uses Kafka's [Consumer API](https://kafka.apache.org/documentation/#consumerapi) to consume messages from the Kafka broker, which then creates Data Prepper events for further processing by the Data Prepper pipeline. ## Usage The following example shows the `kafka` source in a Data Prepper pipeline: -```json +```yaml kafka-pipeline: source: kafka: bootstrap_servers: - - 127.0.0.1:9093 + - 127.0.0.1:9092 topics: - name: Topic1 group_id: groupID1 - name: Topic2 group_id: groupID1 + sink: + - stdout: {} ``` ## Configuration @@ -40,90 +42,209 @@ Option | Required | Type | Description `encryption` | No | JSON object | The encryption configuration. For more information, see [Encryption](#encryption). `aws` | No | JSON object | The AWS configuration. For more information, see [aws](#aws). `acknowledgments` | No | Boolean | If `true`, enables the `kafka` source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines/#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `false`. +`acknowledgments_timeout` | No | Duration | The maximum amount of time to wait for end-to-end acknowledgments of the records read from Kafka. Applies only when `acknowledgments` is `true`. If the records are not acknowledged within this time, their offsets are not committed. By default, acknowledgments effectively never time out. +`acknowledgments_expiry_reset` | No | Boolean | If `true`, an acknowledgment set that expires before all of its events are acknowledged is treated as a negative acknowledgment, so the source seeks the affected partitions back to the last committed offset and reads the records again. If `false`, expired acknowledgment sets are ignored. Applies only when `acknowledgments` is `true`. Default is `false`. `client_dns_lookup` | Yes, when a DNS alias is used. | String | Sets Kafka's `client.dns.lookup` option. Default is `default`. ### Topics -Use the following options in the `topics` array. +Use the following options in the `topics` array for each topic. Option | Required | Type | Description :--- | :--- | :--- | :--- `name` | Yes | String | The name of each Kafka topic. `group_id` | Yes | String | Sets Kafka's `group.id` option. +`client_id` | No | String | Sets Kafka's `client.id` option for the topic's consumers. Must be between 1 and 255 characters long. `workers` | No | Integer | The number of multithreaded consumers associated with each topic. Default is `2`. The maximum value is `200`. `serde_format` | No | String | Indicates the serialization and deserialization format of the messages in the topic. Default is `plaintext`. `auto_commit` | No | Boolean | When `false`, the consumer's offset will not be periodically committed to Kafka in the background. Default is `false`. -`commit_interval` | No | Integer | When `auto_commit` is set to `true`, sets how frequently, in seconds, the consumer offsets are auto-committed to Kafka through Kafka's `auto.commit.interval.ms` option. Default is `5s`. -`session_timeout` | No | Integer | The amount of time during which the source detects client failures when using Kafka's group management features, which can be used to balance the data stream. Default is `45s`. -`auto_offset_reset` | No | String | Automatically resets the offset to an earlier or the latest offset through Kafka's `auto.offset.reset` option. Default is `latest`. -`thread_waiting_time` | No | Integer | The amount of time that threads wait for the preceding thread to complete its task and to signal the next thread. The Kafka consumer API poll timeout value is set to half of this setting. Default is `5s`. -`max_partition_fetch_bytes` | No | Integer | Sets the maximum limit in megabytes for max data returns from each partition through Kafka's `max.partition.fetch.bytes` setting. Default is `1mb`. -`heart_beat_interval` | No | Integer | The expected amount of time between heartbeats to the consumer coordinator when using Kafka's group management facilities through Kafka's `heartbeat.interval.ms` setting. Default is `5s`. -`fetch_max_wait` | No | Integer | The maximum amount of time during which the server blocks a fetch request when there isn't sufficient data to satisfy the `fetch_min_bytes` requirement through Kafka's `fetch.max.wait.ms` setting. Default is `500ms`. -`fetch_max_bytes` | No | Integer | The maximum record size accepted by the broker through Kafka's `fetch.max.bytes` setting. Default is `50mb`. -`fetch_min_bytes` | No | Integer | The minimum amount of data the server returns during a fetch request through Kafka's `retry.backoff.ms` setting. Default is `1b`. -`retry_backoff` | No | Integer | The amount of time to wait before attempting to retry a failed request to a given topic partition. Default is `10s`. -`max_poll_interval` | No | Integer | The maximum delay between invocations of a `poll()` when using group management through Kafka's `max.poll.interval.ms` option. Default is `300s`. +`commit_interval` | No | Duration | When `auto_commit` is set to `true`, sets how frequently the consumer offsets are auto-committed to Kafka through Kafka's `auto.commit.interval.ms` option. Default is `5s`. +`session_timeout` | No | Duration | The amount of time during which the source detects client failures when using Kafka's group management features, which can be used to balance the data stream. Default is `45s`. +`auto_offset_reset` | No | String | Automatically resets the offset to an earlier or the latest offset through Kafka's `auto.offset.reset` option. Default is `earliest`. +`thread_waiting_time` | No | Duration | The amount of time that threads wait for the preceding thread to complete its task and to signal the next thread. The Kafka consumer API poll timeout value is set to half of this setting. Default is `5s`. +`max_partition_fetch_bytes` | No | String | Sets the maximum amount of data returned from each partition through Kafka's `max.partition.fetch.bytes` setting. Default is `1mb`. +`heart_beat_interval` | No | Duration | The expected amount of time between heartbeats to the consumer coordinator when using Kafka's group management facilities through Kafka's `heartbeat.interval.ms` setting. Default is `5s`. +`fetch_max_wait` | No | Integer | The maximum amount of time, in milliseconds, during which the server blocks a fetch request when there isn't sufficient data to satisfy the `fetch_min_bytes` requirement through Kafka's `fetch.max.wait.ms` setting. Default is `500`. +`fetch_max_bytes` | No | String | The maximum amount of data the server returns for a fetch request through Kafka's `fetch.max.bytes` setting. The maximum value is `50mb`. Default is `50mb`. +`fetch_min_bytes` | No | String | The minimum amount of data the server returns during a fetch request through Kafka's `fetch.min.bytes` setting. Default is `1b`. +`retry_backoff` | No | Duration | The amount of time to wait before attempting to retry a failed request to a given topic partition. Default is `10s`. +`reconnect_backoff` | No | Duration | The amount of time to wait before attempting to reconnect to a broker through Kafka's `reconnect.backoff.ms` setting. Default is `10s`. +`connections_max_idle` | No | Duration | The amount of time after which the consumer closes idle connections, through Kafka's `connections.max.idle.ms` setting. Minimum is `1s`. Default is `540s`. +`metadata_max_age` | No | Duration | The amount of time after which the consumer refreshes metadata, through Kafka's `metadata.max.age.ms` setting. The consumer detects new partitions when it refreshes metadata. Default is `300s`. +`max_poll_interval` | No | Duration | The maximum delay between invocations of a `poll()` when using group management through Kafka's `max.poll.interval.ms` option. Default is `300s`. `consumer_max_poll_records` | No | Integer | The maximum number of records returned in a single `poll()` call through Kafka's `max.poll.records` setting. Default is `500`. -`key_mode` | No | String | Indicates how the key field of the Kafka message should be handled. The default setting is `include_as_field`, which includes the key in the `kafka_key` event. The `include_as_metadata` setting includes the key in the event's metadata. The `discard` setting discards the key. +`isolation_level` | No | String | Controls how the consumer reads messages written transactionally, through Kafka's `isolation.level` setting. Valid values are `read_uncommitted`, which returns all messages, and `read_committed`, which returns only messages from committed transactions. Default is `read_uncommitted`. +`key_mode` | No | String | Indicates how the key field of the Kafka message should be handled. The default setting is `include_as_field`, which includes the key in the `kafka_key` event. The `include_as_metadata` setting includes the key in the event's metadata. The `discard` setting discards the key. ### Schema -The following option is required inside the `schema` configuration. +The `schema` configuration has the following options. -Option | Type | Description -:--- | :--- | :--- -`type` | String | Sets the type of schema based on your registry, either the AWS Glue Schema Registry, `aws_glue`, or the Confluent Schema Registry, `confluent`. When using the `aws_glue` registry, set any [AWS](#aws) configuration options. +Option | Type | Required | Description +:--- | :--- | :--- | :--- +`type` | String | Yes | Sets the type of schema based on your registry. Valid values are `aws_glue` (AWS Glue schema registry) and `confluent` (Confluent schema registry) . When using the `aws_glue` registry, set any [AWS](#aws) configuration options. +`override_endpoint` | Boolean | No | When `true` and `type` is `aws_glue`, the `kafka` source uses the `registry_url` as the AWS Glue Schema Registry endpoint. Default is `false`. +`basic_auth_credentials_source` | String | No | Where schema registry credentials come from. Use `USER_INFO` when providing `api_key/api_secret`. Other valid values are `URL` and `SASL_INHERIT`. Default typically aligns with the underlying client. The following configuration options are only required when using a `confluent` registry. Option | Type | Description :--- | :--- | :--- -`registry_url` | String | Deserializes a record value from a `bytearray` into a string. Default is `org.apache.kafka.common.serialization.StringDeserializer`. -`version` | String | Deserializes a record key from a `bytearray` into a string. Default is `org.apache.kafka.common.serialization.StringDeserializer`. -`schema_registry_api_key` | String | The schema registry API key. -`schema_registry_api_secret` | String | The schema registry API secret. +`registry_url` | String | The base URL of the schema registry (for example, `http://schema-registry:8081` or `https://sr.example.com`). +`version` | Integer | The schema version to use per subject. If not specified, the latest version is used. +`api_key` | String | The schema registry API key. +`api_secret` | String | The schema registry API secret. -### Authentication +The following example configures a schema registry: -The following option is required inside the `authentication` object. +```yaml +schema: + type: confluent + registry_url: "http://schema-registry:8081" + api_key: "<optional if using basic/key auth>" + api_secret: "<optional if using basic/key auth>" +``` +{% include copy.html %} -Option | Type | Description -:--- | :--- | :--- -`sasl` | JSON object | The Simple Authentication and Security Layer (SASL) authentication configuration. +#### Schema registry over TLS -### SASL +The Kafka source uses the JVM truststore when connecting to the schema registry over `https`. If the schema registry is signed by a custom CA, add that CA to the Data Prepper JVM truststore or provide a custom truststore using environment variables. + +You can use the following command to build a truststore with your CA certificate: + +```bash +keytool -importcert -noprompt -alias sr-ca -file sr-ca.pem -keystore /usr/share/data-prepper/certs/sr.truststore.jks -storepass changeit +``` +{% include copy.html %} + +The following command configures Data Prepper using `JAVA_TOOL_OPTIONS`: + +```yaml +JAVA_TOOL_OPTIONS=-Djavax.net.ssl.trustStore=/usr/share/data-prepper/certs/sr.truststore.jks -Djavax.net.ssl.trustStorePassword=changeit +``` +{% include copy.html %} + +You can configure Data Pepper in `docker-compose.yaml` using the following method: + +```yaml +environment: + - JAVA_TOOL_OPTIONS=-Djavax.net.ssl.trustStore=/usr/share/data-prepper/certs/sr.truststore.jks -Djavax.net.ssl.trustStorePassword=changeit +volumes: + - ./certs:/usr/share/data-prepper/certs:ro +``` +{% include copy.html %} + +### Authentication + +The `authentication` section configures SASL: + +```yaml +authentication: + sasl: + plaintext: + username: alice + password: secret +``` +{% include copy.html %} + +| Option | Type | Description | +|:---|:---|:---| +| `sasl` | Object | SASL configuration. | + +#### SASL Use one of the following options when configuring SASL authentication. - Option | Type | Description :--- | :--- | :--- -`plaintext` | JSON object | The [PLAINTEXT](#sasl-plaintext) authentication configuration. -`aws_msk_iam` | String | The Amazon MSK AWS Identity and Access Management (IAM) configuration. If set to `role`, the `sts_role_arm` set in the `aws` configuration is used. Default is `default`. +`plaintext` | JSON object | The plaintext authentication configuration. The alias `plain` is also supported for backward compatibility. For more information, see [SASL plaintext](#sasl-plaintext). +`scram` | JSON object | The Salted Challenge Response Authentication Mechanism (SCRAM) authentication configuration. For more information, see [SASL SCRAM](#sasl-scram). +`aws_msk_iam` | String | The Amazon MSK AWS Identity and Access Management (IAM) configuration. If set to `role`, the `sts_role_arn` set in the `aws` configuration is used. Default is `default`. +`azure_federated` | JSON object | The configuration for authenticating to the Kafka endpoint of Azure Event Hubs using AWS credentials federated to Microsoft Entra ID. For more information, see [SASL Azure federated](#sasl-azure-federated). +##### SASL plaintext +The following options are required when using the [SASL.plain](https://kafka.apache.org/10/javadoc/org/apache/kafka/common/security/auth/SecurityProtocol.html) protocol. -#### SASL PLAINTEXT +| Option | Type | Description | +|:---|:---|:---| +| `username` | String | The SASL/PLAIN username. | +| `password` | String | The SASL/PLAIN password. | -The following options are required when using the [SASL PLAINTEXT](https://kafka.apache.org/10/javadoc/org/apache/kafka/common/security/auth/SecurityProtocol.html) protocol. +##### SASL SCRAM -Option | Type | Description -:--- | :--- | :--- -`username` | String | The username for the PLAINTEXT auth. -`password` | String | The password for the PLAINTEXT auth. +The following options are required when using SCRAM authentication. -#### Encryption +| Option | Type | Description | +|:---|:---|:---| +| `username` | String | The SCRAM username. | +| `password` | String | The SCRAM password. | +| `mechanism` | String | The SCRAM mechanism to use, for example, `SCRAM-SHA-256` or `SCRAM-SHA-512`. The value is passed to Kafka's `sasl.mechanism` setting. | + +##### SASL Azure federated + +The `azure_federated` option connects the source to the Kafka endpoint of an Azure Event Hubs namespace without storing an Azure client secret in the pipeline. The source requests a web identity token from AWS STS using the credentials from the [`aws`](#aws) configuration, exchanges this token for an access token at the Microsoft Entra ID token endpoint, and uses the access token for SASL/OAUTHBEARER authentication. The source caches the access token and requests a new one before it expires. + +To use this option, enable outbound identity federation in your AWS account, allow the AWS credentials to call `sts:GetWebIdentityToken`, and add a federated identity credential that trusts the AWS token to the Microsoft Entra application. The source uses the Region set in `aws.region` and, if `aws.sts_role_arn` is set, assumes that role before requesting the token. The connection always uses the `SASL_SSL` security protocol. + +The following options are required when using `azure_federated`. + +| Option | Type | Description | +|:---|:---|:---| +| `client_id` | String | The application (client) ID of the Microsoft Entra application. | +| `token_endpoint` | String | The Microsoft Entra ID OAuth 2.0 token endpoint, for example, `https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token`. | +| `scope` | String | The scope of the requested access token. For Azure Event Hubs, use `https://<namespace>.servicebus.windows.net/.default`. | + +The following example configures `azure_federated` authentication: + +```yaml +kafka-pipeline: + source: + kafka: + bootstrap_servers: + - my-namespace.servicebus.windows.net:9093 + topics: + - name: my-event-hub + group_id: data-prepper-group + encryption: + type: ssl + authentication: + sasl: + azure_federated: + client_id: <application-client-id> + token_endpoint: https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token + scope: https://my-namespace.servicebus.windows.net/.default + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/event-hubs-federation + sink: + - stdout: {} +``` +{% include copy.html %} + +### Encryption Use the following options when setting SSL encryption. Option | Required | Type | Description :--- | :--- | :--- | :--- `type` | No | String | The encryption type. Use `none` to disable encryption. Default is `ssl`. -`Insecure` | No | Boolean | A Boolean flag used to turn off SSL certificate verification. If set to `true`, certificate authority (CA) certificate verification is turned off and insecure HTTP requests are sent. Default is `false`. +`certificate` | No | String | The SSL certificate content. Use either this option or `trust_store_file_path`, not both. +`trust_store_file_path` | No | String | The path to the truststore file containing the SSL certificate. Use either this option or `certificate`, not both. +`trust_store_password` | No | String | The password for the truststore file. +`insecure` | No | Boolean | A Boolean flag used to turn off SSL certificate verification. If set to `true`, certificate authority (CA) certificate verification is turned off and insecure HTTP requests are sent. Default is `false`. +Use the following configuration to enable SSL encryption: -#### AWS +```yaml +encryption: + type: ssl + # With public CA: no extra config needed. + # With private CA: trust using JVM truststore. +``` +{% include copy.html %} + +### AWS Use the following options when setting up authentication for `aws` services. @@ -132,6 +253,7 @@ Option | Required | Type | Description `region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). `sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon Simple Queue Service (Amazon SQS) and Amazon Simple Storage Service (Amazon S3). Default is `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). `msk` | No | JSON object | The [MSK](#msk) configuration settings. +`sts_header_overrides` | No | Map | A map of headers to add to the AWS STS `AssumeRole` request. You can specify up to 5 headers. #### MSK @@ -140,5 +262,161 @@ Use the following options inside the `msk` object. Option | Required | Type | Description :--- | :--- | :--- | :--- `arn` | Yes | String | The [MSK ARN](https://docs.aws.amazon.com/msk/1.0/apireference/configurations-arn.html) to use. -`broker_connection_type` No | String | The type of connector to use with the MSK broker, either `public`, `single_vpc`, or `multip_vpc`. Default is `single_vpc`. +`broker_connection_type` | No | String | The type of connector to use with the MSK broker. Valid values are `public`, `single_vpc`, and `multi_vpc`. Default is `single_vpc`. + +## Configuration examples + +This section demonstrates different pipeline configuration options. + +### Basic Kafka source + +The following example pipeline reads JSON messages from a single plaintext Kafka topic with multiple consumer workers, parses them, and indexes them into OpenSearch: + +```yaml +kafka-pipeline: + source: + kafka: + bootstrap_servers: + - localhost:9092 + topics: + - name: my-topic + group_id: data-prepper-group + workers: 4 + processor: + - parse_json: + sink: + - opensearch: + hosts: ["https://localhost:9200"] + username: admin + password: "<custom-admin-password>" + index: kafka-data +``` +{% include copy.html %} + +### Kafka source with SSL encryption + +The following example pipeline connects to a Kafka broker over TLS, consumes messages from a secure topic, and writes the results to OpenSearch: + +```yaml +kafka-pipeline: + source: + kafka: + bootstrap_servers: + - kafka-broker.example.com:9093 + topics: + - name: secure-topic + group_id: secure-group + encryption: + type: ssl + sink: + - opensearch: + hosts: ["https://localhost:9200"] + username: admin + password: "<custom-admin-password>" + index: secure-kafka-data +``` +{% include copy.html %} + +### Kafka source with SASL PLAIN authentication + +The following example pipeline authenticates to Kafka using the SASL/PLAIN protocol over TLS, consumes messages from the topic, and indexes them into OpenSearch: + +```yaml +kafka-pipeline: + source: + kafka: + bootstrap_servers: + - kafka-broker.example.com:9094 + topics: + - name: authenticated-topic + group_id: auth-group + encryption: + type: ssl + authentication: + sasl: + plaintext: + username: kafka-user + password: kafka-password + sink: + - opensearch: + hosts: ["https://localhost:9200"] + username: admin + password: "<custom-admin-password>" + index: authenticated-kafka-data +``` +{% include copy.html %} + +### Amazon MSK with AWS Glue schema registry + +The following example configures Amazon MSK with the AWS Glue schema registry, consumes messages from an MSK cluster using AWS settings, deserializes the payload using the AWS Glue schema registry, normalizes timestamps, and writes to an Amazon OpenSearch domain: + +```yaml +msk-pipeline: + source: + kafka: + acknowledgments: true + topics: + - name: my-msk-topic + group_id: msk-consumer-group + auto_offset_reset: earliest + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/data-prepper-role + msk: + arn: arn:aws:kafka:us-east-1:123456789012:cluster/my-cluster-name/uuid + schema: + type: aws_glue + processor: + - date: + match: + - key: timestamp + patterns: ["epoch_milli"] + destination: "@timestamp" + sink: + - opensearch: + hosts: ["https://search-my-domain.us-east-1.opensearch.amazonaws.com"] + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/opensearch-role + index: msk-data + index_type: custom +``` +{% include copy.html %} + +### Confluent Kafka with schema registry + +The following example configures Confluent Kafka with the schema registry, connects to Confluent Cloud over TLS using SASL and Confluent schema registry credentials, decodes payloads, and indexes them into OpenSearch: + +```yaml +confluent-pipeline: + source: + kafka: + bootstrap_servers: + - pkc-xxxxx.us-east-1.aws.confluent.cloud:9092 + topics: + - name: confluent-topic + group_id: confluent-group + auto_offset_reset: earliest + encryption: + type: ssl + authentication: + sasl: + plaintext: + username: confluent-api-key + password: confluent-api-secret + schema: + type: confluent + registry_url: https://psrc-xxxxx.us-east-1.aws.confluent.cloud + api_key: "{% raw %}${{aws_secrets:schema-secret:schema_registry_api_key}}{% endraw %}" + api_secret: "{% raw %}${{aws_secrets:schema-secret:schema_registry_api_secret}}{% endraw %}" + basic_auth_credentials_source: USER_INFO + sink: + - opensearch: + hosts: ["https://localhost:9200"] + username: admin + password: "<custom-admin-password>" + index_type: custom + index: confluent-data +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sources/kinesis.md b/_data-prepper/pipelines/configuration/sources/kinesis.md new file mode 100644 index 00000000..f0a0a116 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/kinesis.md @@ -0,0 +1,198 @@ +--- +layout: default +title: Kinesis +parent: Sources +grand_parent: Pipelines +nav_order: 45 +--- + +# Kinesis source + +You can use the OpenSearch Data Prepper `kinesis` source to ingest records from one or more [Amazon Kinesis Data Streams](https://aws.amazon.com/kinesis/data-streams/). + +## Usage + +The following example pipeline specifies Kinesis as a source. The pipeline ingests data from multiple Kinesis data streams named `stream1` and `stream2` and sets the `initial_position` to indicate the starting point for reading the stream records: + +```yaml +version: "2" +kinesis-pipeline: + source: + kinesis: + streams: + - stream_name: "stream1" + initial_position: "LATEST" + - stream_name: "stream2" + initial_position: "LATEST" + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-iam-role" +``` + +## Configuration options + +The `kinesis` source supports the following configuration options. + +Option | Required | Type | Description +:--- |:---------|:---------| :--- +`aws` | Yes | AWS | Specifies the AWS configuration. See [`aws`](#aws). +`acknowledgments` | No | Boolean | When set to `true`, enables the `kinesis` source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `false`. +`streams` | Yes | List | Configures a list of multiple Kinesis data streams that the `kinesis` source uses to read records. You can configure up to four streams. See [Streams](#streams). +`codec` | Yes | Codec | Specifies the [codec](#codec) to apply. +`buffer_timeout` | No | Duration | Sets the amount of time allowed for writing events to the Data Prepper buffer before timeout occurs. Any events that the source cannot write to the buffer during the specified amount of time are discarded. Default is `1s`. +`records_to_accumulate` | No | Integer | Determines the number of messages that accumulate before being written to the buffer. Default is `100`. +`consumer_strategy` | No | String | Selects the consumer strategy to use for ingesting Kinesis data streams. The default is `fan-out`, but `polling` can also be used. If `polling` is enabled, the additional configuration is required. +`polling` | No | polling | See [polling](#polling). +`max_initialization_attempts` | No | Integer | The maximum number of attempts to initialize the Kinesis consumer before the source stops retrying. Default is `2147483647`. +`initialization_backoff_time` | No | Duration | The amount of time to wait between attempts to initialize the Kinesis consumer. Default is `1s`. + +### Streams + +You can use the following options in the `streams` array. + +Option | Required | Type | Description +:--- |:---------| :--- | :--- +`stream_name` | No | String | Defines the name of each Kinesis data stream. Either `stream_name` or `stream_arn` is required. +`stream_arn` | No | String | The Amazon Resource Name (ARN) of the Kinesis data stream. If both `stream_name` and `stream_arn` are specified, `stream_arn` is used. +`consumer_arn` | No | String | The ARN of the enhanced fan-out consumer to use for the stream. Applies only when `stream_arn` is specified and `consumer_strategy` is `fan-out`. If not specified, the source uses the stream consumer named after the pipeline. +`initial_position` | No | String | Sets the `initial_position` to control where the `kinesis` source begins reading stream records. Use `LATEST` to start from the most recent record, `EARLIEST` to read from the beginning of the stream, or `AT_TIMESTAMP` to start from a specific timestamp. Default is `LATEST`. +`initial_timestamp`| No | String | Specifies the timestamp from which to begin reading stream records. The value must follow the [ISO LocalDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) format and be provided in the UTC time zone (for example, `2023-01-23T10:00:00`). When `initial_position` is set to `AT_TIMESTAMP`, you must specify either `initial_timestamp` or `range`. +`range` | No | String | Specifies how far back from the current time to begin reading Kinesis data stream records. Supports ISO-8601 duration strings (such as `PT20.345S` or `PT15M`) as well as shorthand notation for seconds (`60s`) and milliseconds (`1600ms`). For example, `PT12H` starts reading records from 12 hours before the pipeline started. When `initial_position` is set to `AT_TIMESTAMP`, you must specify either `initial_timestamp` or `range`. + +`checkpoint_interval` | No | Duration | Configure the `checkpoint_interval` to periodically checkpoint Kinesis data streams and avoid duplication of record processing. Default is `PT2M`. +`compression` | No | String | Specifies the compression format. To decompress records added by a [CloudWatch Logs Subscription Filter](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html) to Kinesis, use the `gzip` compression format. + +<!-- vale off --> +## codec +<!-- vale on --> + +The `codec` determines how the `kinesis` source parses each Kinesis stream record. For increased and more efficient performance, you can use [codec combinations]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/codec-processor-combinations/) with certain processors. + +<!-- vale off --> +### json codec +<!-- vale on --> + +The `json` codec parses each single line as a single JSON object from a JSON array and then creates a Data Prepper event for each object in the array. It can be used for parsing nested CloudWatch events into individual log entries. +It also supports the following configuration to use with this codec. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`key_name` | No | String | The name of the input field from which to extract the JSON array and create Data Prepper events. +`include_keys` | No | List | The list of input fields to be extracted and added as additional fields in the Data Prepper event. +`include_keys_metadata` | No | List | The list of input fields to be extracted and added to the Data Prepper event metadata object. +`max_event_length` | No | Integer | The maximum size of any single event being read by the JSON codec. Default is 20,000,000 characters. + + +### `newline` codec + +The `newline` codec parses each Kinesis stream record as a single log event, making it ideal for processing single-line records. It also works well with the [`parse_json` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/parse-json/) to parse each line. + +You can use the following options to configure the `newline` codec. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`skip_lines` | No | Integer | Sets the number of lines to skip before creating events. You can use this configuration to skip common header rows. Default is `0`. +`header_destination` | No | String | Defines a key value to assign to the header line of the stream event. If this option is specified, then each event will contain a `header_destination` field. + +### `otel_traces` codec + +The `otel_traces` codec parses each Kinesis data stream record as an OpenTelemetry trace record and creates a Data Prepper span event for each span record. + +You can use the following options to configure the `otel_traces` codec. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`format` | No | String | Specifies the format of the OpenTelemetry traces. Valid values are `json` and `protobuf`. Default is `json`. +`otel_format` | No | String | Specifies the output format of the decoded spans. Valid values are `opensearch` and `otel`. Default is `opensearch`. +`length_prefixed_encoding` | No | Boolean | Specifies whether the length precedes the data in protobuf format. Default is `false`. + +<!-- vale off --> +### polling +<!-- vale on --> + +When the `consumer_strategy` is set to `polling`, the `kinesis` source uses a polling-based approach to read records from the Kinesis data streams, instead of the default `fan-out` approach. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`max_polling_records` | No | Integer | Sets the number of records to fetch from Kinesis during a single call. Default is `10000`. +`idle_time_between_reads` | No | Duration | Defines the amount of idle time between calls. Default is `250ms`. + +<!-- vale off --> +### aws +<!-- vale on --> + +You can use the following options in the `aws` configuration. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | Sets the AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | Defines the AWS Security Token Service (AWS STS) role to assume for requests to Amazon Kinesis Data Streams and Amazon DynamoDB. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | Defines the external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | Defines a map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. + +## Exposed metadata attributes + +The `kinesis` source adds the following metadata to each processed event. You can access the metadata attributes using the [expression syntax `getMetadata` function]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-metadata/). + +- `stream_name`: Contains the name of the Kinesis data stream from which the event was obtained. + +## Permissions + +The following minimum permissions are required in order to run `kinesis` as a source: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "kinesis:DescribeStream", + "kinesis:DescribeStreamConsumer", + "kinesis:DescribeStreamSummary", + "kinesis:GetRecords", + "kinesis:GetShardIterator", + "kinesis:ListShards", + "kinesis:ListStreams", + "kinesis:ListStreamConsumers", + "kinesis:RegisterStreamConsumer", + "kinesis:SubscribeToShard" + ], + "Resource": [ + "arn:aws:kinesis:us-east-1:{account-id}:stream/stream1", + "arn:aws:kinesis:us-east-1:{account-id}:stream/stream2" + ] + }, + { + "Sid": "allowCreateTable", + "Effect": "Allow", + "Action": [ + "dynamodb:CreateTable", + "dynamodb:PutItem", + "dynamodb:DescribeTable", + "dynamodb:DeleteItem", + "dynamodb:GetItem", + "dynamodb:Scan", + "dynamodb:UpdateItem", + "dynamodb:Query" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:{account-id}:table/kinesis-pipeline" + ] + } + ] +} +``` + +The `kinesis` source uses a DynamoDB table for ingestion coordination among multiple workers, so you need DynamoDB permissions. + +## Metrics + +The `kinesis` source includes the following metrics. + +### Counters + +* `recordsProcessed`: Counts the number of processed stream records. +* `recordProcessingErrors`: Counts the number of stream record processing errors. +* `acknowledgementSetSuccesses`: Counts the number of processed stream records that were successfully added to the sink. +* `acknowledgementSetFailures`: Counts the number of processed stream records that failed to be added to the sink. diff --git a/_data-prepper/pipelines/configuration/sources/opensearch-api.md b/_data-prepper/pipelines/configuration/sources/opensearch-api.md new file mode 100644 index 00000000..43b1cd01 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/opensearch-api.md @@ -0,0 +1,252 @@ +--- +layout: default +title: OpenSearch API +parent: Sources +grand_parent: Pipelines +nav_order: 55 +--- + +# OpenSearch API source + +The `opensearch_api` source accepts HTTP requests compatible with the [OpenSearch Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/). Standard OpenSearch clients like [Apache Flink OpenSearch Connector](https://nightlies.apache.org/flink/flink-docs-stable/docs/connectors/datastream/opensearch/), Logstash, and [`opensearch-py`]({{site.url}}{{site.baseurl}}/clients/python-low-level/) can send data to Data Prepper through this source. + +Unlike the OpenSearch Bulk API, this source writes asynchronously. Events are buffered for downstream processing rather than written directly to OpenSearch. When the `zero` buffer is used, events pass directly to the sink. Regardless of buffer type, the response is synthetic and does not reflect actual indexing results from OpenSearch. + +## Usage + +The `opensearch_api` source supports the following endpoints: + +```json +POST /{path}/_bulk +POST /{path}/{index}/_bulk +``` + +## Configuration + +The following table lists the configuration options for the `opensearch_api` source. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `port` | Integer | No | `9200` | The port the source listens on. Must be 0--65535. | +| `path` | String | No | `/` | The URI path for the endpoint. Must start with `/`. Supports the `${pipelineName}` placeholder. | +| `request_timeout` | Integer | No | `10000` | The request timeout, in milliseconds. | +| `thread_count` | Integer | No | `200` | The number of threads in the scheduled thread pool. | +| `max_connection_count` | Integer | No | `500` | The maximum number of open connections. | +| `max_pending_requests` | Integer | No | `1024` | The maximum number of tasks in the work queue. | +| `max_request_length` | ByteCount | No | `10mb` | The maximum number of bytes allowed in the payload of a single HTTP request, for example, `5mb`. Requests that exceed this size are rejected with a `413` status code. | +| `health_check_service` | Boolean | No | `false` | Enables a `/health` endpoint on the configured port. | +| `unauthenticated_health_check` | Boolean | No | `false` | If `true`, the health endpoint does not require authentication. | +| `compression` | String | No | `none` | The compression applied to the request payload. Valid values are `none` and `gzip`. | +| `authentication` | Object | No | Unauthenticated | The authentication configuration. See [Authentication](#authentication). | +| `ssl` | Boolean | No | `false` | Enables TLS/SSL. | +| `ssl_certificate_file` | String | Conditional | — | The path to the SSL certificate file. Required if `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. Supports Amazon Simple Storage Service (Amazon S3) paths (`s3://bucket/path`). | +| `ssl_key_file` | String | Conditional | — | The path to the SSL key file (decrypted). Required if `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. Supports Amazon S3 paths. | +| `use_acm_certificate_for_ssl` | Boolean | No | `false` | When `true`, uses AWS Certificate Manager (ACM) for TLS certificates. | +| `acm_certificate_arn` | String | Conditional | — | The ACM certificate Amazon Resource Name (ARN). Required if `use_acm_certificate_for_ssl` is `true`. | +| `acm_private_key_password` | String | No | Random | The password to decrypt the ACM private key. | +| `acm_certificate_timeout_millis` | Integer | No | `120000` | The timeout for ACM certificate retrieval, in milliseconds. | +| `aws_region` | String | Conditional | — | The AWS Region for ACM or Amazon S3 certificate access. | + +## Authentication + +By default, the source runs without authentication. To make this explicit in your configuration, use the `unauthenticated` key: + +```yaml +source: + opensearch_api: + authentication: + unauthenticated: +``` +{% include copy.html %} + +### HTTP basic authentication + +The following example configures HTTP basic authentication with a username and password: + +```yaml +source: + opensearch_api: + authentication: + http_basic: + username: my-user + password: my_s3cr3t +``` +{% include copy.html %} + +### Custom authentication + +To provide custom authentication, create a plugin that implements the [`ArmeriaHttpAuthenticationProvider`](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/armeria-common/src/main/java/org/opensearch/dataprepper/armeria/authentication/ArmeriaHttpAuthenticationProvider.java) interface. + +## Event metadata attributes + +For each action in the bulk request, the source creates a Data Prepper event with the following metadata attributes. + +| Attribute | Description | Example | +|-----------|-------------|---------| +| `opensearch_action` | The bulk action type | `index`, `create`, `update`, `delete` | +| `opensearch_index` | Target index name | `my-index` | +| `opensearch_id` | Document ID (if provided) | `doc-123` | +| `opensearch_routing` | Routing value (if provided) | `user-456` | +| `opensearch_pipeline` | Ingest pipeline (if provided) | `my-pipeline` | + +You can reference these attributes in processors and sinks using the `getMetadata` method or `${metadata_key}` syntax. + +## Response format + +On success, the source returns a JSON response with an empty `items` array: + +```json +{ + "took": 5, + "errors": false, + "items": [] +} +``` + +The following table lists the response fields. + +| Field | Description | +|-------|-------------| +| `took` | The actual processing time, measured from request receipt to buffer write completion, in milliseconds. | +| `errors` | Indicates whether any errors occurred. Always `false` when all data is successfully written to the buffer. | +| `items` | Always an empty array. Because Data Prepper buffers documents for downstream processing rather than indexing them directly, per-item results are not available at request time. | + +## Response status codes + +The following table lists the possible response status codes. + +| Status | Description | +|--------|-------------| +| `200` | Request data successfully written to the buffer. | +| `400` | Request data is malformed or uses an unsupported format. | +| `408` | Request timed out writing to the buffer. | +| `413` | Request payload exceeds the configured buffer capacity or the `max_request_length` value. | +| `429` | Source is at full capacity; request rejected. | + +## Buffer compatibility + +The `opensearch_api` source works with the following buffer types. + +| Buffer | Supported | Notes | +|--------|-----------|-------| +| [`bounded_blocking`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/bounded-blocking/) | Yes | Default. Events are stored in an in-memory blocking queue. | +| [`kafka`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/kafka/) | Yes | Requires Data Prepper 2.x. Events are serialized to Apache Kafka and reconstructed on the consumer side. | +| `zero` | Yes | Events pass directly to the sink with no buffering. | + +## Metrics + +The `opensearch_api` source emits the following metrics. + +### Counters + +The following table lists the counter metrics. + +| Metric | Description | +|--------|-------------| +| `requestsReceived` | The total number of requests received by the endpoint. | +| `successRequests` | The total number of requests successfully processed (200). | +| `badRequests` | The total number of requests with invalid format (400). | +| `requestTimeouts` | The total number of requests that timed out (408). | +| `requestsTooLarge` | The total number of requests exceeding buffer capacity (413). | +| `requestsRejected` | The total number of requests rejected due to full capacity (429). | +| `internalServerError` | The total number of requests with internal errors (500). | + +### Timer + +The following table lists the timer metric. + +| Metric | Description | +|--------|-------------| +| `requestProcessDuration` | The request processing latency, in seconds. | + +### Distribution summary + +The following table lists the distribution summary metric. + +| Metric | Description | +|--------|-------------| +| `payloadSize` | The distribution of incoming request payload sizes, in bytes. | + +## Examples + +The following examples demonstrate common configurations for the `opensearch_api` source. + +### Basic pipeline with an OpenSearch sink + +The following example configures a pipeline that receives bulk requests and writes events to an OpenSearch sink using metadata attributes: + +```yaml +opensearch-pipeline: + source: + opensearch_api: + port: 9202 + path: "/opensearch" + sink: + - opensearch: + hosts: ["https://opensearch-node:9200"] + index: "${getMetadata(\"opensearch_index\")}" + document_id: "${getMetadata(\"opensearch_id\")}" + routing: "${getMetadata(\"opensearch_routing\")}" + action: "${getMetadata(\"opensearch_action\")}" +``` +{% include copy.html %} + +### SSL enabled + +The following example enables SSL with HTTP basic authentication: + +```yaml +opensearch-pipeline: + source: + opensearch_api: + port: 9202 + ssl: true + ssl_certificate_file: "/certs/server.crt" + ssl_key_file: "/certs/server.key" + authentication: + http_basic: + username: admin + password: admin + sink: + - opensearch: + hosts: ["https://opensearch-node:9200"] + index: "${getMetadata(\"opensearch_index\")}" + action: "${getMetadata(\"opensearch_action\")}" +``` +{% include copy.html %} + +### Sending data using cURL + +The following example sends a bulk request to the `opensearch_api` source using cURL: + +```bash +curl -XPOST "http://localhost:9202/opensearch/_bulk" \ + -H "Content-Type: application/json" \ + -d '{"index":{"_index":"movies","_id":"1"}} +{"title":"Rush","year":2013} +{"delete":{"_index":"movies","_id":"2"}} +' +``` +{% include copy.html %} + +<!-- vale off --> +### Sending data using opensearch-py +<!-- vale on --> + +The following example sends a bulk request using the `opensearch-py` client: + +```python +from opensearchpy import OpenSearch + +client = OpenSearch( + hosts=[{"host": "localhost", "port": 9202}], + use_ssl=False, + url_prefix="/opensearch" +) + +client.bulk(body=[ + {"index": {"_index": "movies", "_id": "1"}}, + {"title": "Rush", "year": 2013}, +]) +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sources/opensearch.md b/_data-prepper/pipelines/configuration/sources/opensearch.md index 7cc0b9a3..c6552223 100644 --- a/_data-prepper/pipelines/configuration/sources/opensearch.md +++ b/_data-prepper/pipelines/configuration/sources/opensearch.md @@ -1,12 +1,12 @@ --- layout: default -title: opensearch +title: OpenSearch parent: Sources grand_parent: Pipelines -nav_order: 30 +nav_order: 50 --- -# opensearch +# OpenSearch source The `opensearch` source plugin is used to read indexes from an OpenSearch cluster, a legacy Elasticsearch cluster, an Amazon OpenSearch Service domain, or an Amazon OpenSearch Serverless collection. @@ -84,7 +84,11 @@ The `opensearch` source can be configured with Amazon OpenSearch Serverless by s ## Using metadata -When the `opensource` source constructs Data Prepper events from documents in the cluster, the document index is stored in the EventMetadata with an `opensearch-index` key, and the document_id is stored in the `EventMetadata` with the `opensearch-document_id` as the key. This allows for conditional routing based on the index or `document_id`. The following example pipeline configuration sends events to an `opensearch` sink and uses the same index and `document_id` from the source cluster as in the destination cluster: +When the `opensource` source constructs OpenSearch Data Prepper events from documents, the document index is stored in the `EventMetadata` with `opensearch-index` as the key, and the `document_id` is stored in the `EventMetadata` with the `opensearch-document_id` as the key. The document version is stored in the metadata as `opensearch_document_version`. + +You can reference this metadata in your pipeline configuration as needed. For example, you can use the `opensearch-document_id` to prevent duplicates in sinks that support document updates, such as the `opensearch` sink. You can also use the original document metadata for conditional routing. + +The following example pipeline configuration sends events to an `opensearch` sink and uses the same index, `document_id`, and `document_version` from the source cluster as in the destination cluster to prevent duplicate documents: ```yaml @@ -99,6 +103,8 @@ opensearch-migration-pipeline: hosts: [ "https://sink-cluster:9200" ] username: "username" password: "password" + document_version_type: external + document_version: "${getMetadata(\"opensearch_document_version\")}" document_id: "${getMetadata(\"opensearch-document_id\")}" index: "${getMetadata(\"opensearch-index\"}" ``` @@ -113,8 +119,9 @@ Option | Required | Type | Description `hosts` | Yes | List | A list of OpenSearch hosts to write to, for example, `["https://localhost:9200", "https://remote-cluster:9200"]`. `username` | No | String | The username for HTTP basic authentication. Since Data Prepper 2.5, this setting can be refreshed at runtime if [AWS secrets reference]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#reference-secrets) is applied. `password` | No | String | The password for HTTP basic authentication. Since Data Prepper 2.5, this setting can be refreshed at runtime if [AWS secrets reference]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#reference-secrets) is applied. +`authentication` | No | Object | The HTTP basic authentication configuration. Cannot be used together with the top-level `username` and `password` options. For more information, see [Authentication](#authentication). `disable_authentication` | No | Boolean | Whether authentication is disabled. Defaults to `false`. -`aws` | No | Object | The AWS configuration. For more information, see [aws](#aws). +`aws` | No | Object | The AWS configuration. For more information, see [`aws`](#aws). `acknowledgments` | No | Boolean | When `true`, enables the `opensearch` source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines/#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `false`. `connection` | No | Object | The connection configuration. For more information, see [Connection](#connection). `indices` | No | Object | The configuration for filtering which indexes are processed. Defaults to all indexes, including system indexes. For more information, see [indexes](#indices). @@ -122,6 +129,16 @@ Option | Required | Type | Description `search_options` | No | Object | A list of search options performed by the source. For more information, see [Search options](#search_options). `serverless` | No | Boolean | Determines whether the OpenSearch backend is Amazon OpenSearch Serverless. Set this value to `true` when the destination for the `opensearch` source is an Amazon OpenSearch Serverless collection. Default is `false`. `serverless_options` | No | Object | The network configuration options available when the backend of the `opensearch` source is set to Amazon OpenSearch Serverless. For more information, see [Serverless options](#serverless-options). +`distribution_version` | No | String | The distribution of the source cluster. Valid values are `opensearch` and `es7`. If the source cannot retrieve the cluster information, it treats the cluster as an Elasticsearch cluster. Set this option to `opensearch` to treat the cluster as an OpenSearch cluster in this case. The source then uses `scroll` search unless `search_context_type` is specified. + +### Authentication + +Use the following options in the `authentication` object. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`username` | No | String | The username for HTTP basic authentication. +`password` | No | String | The password for HTTP basic authentication. ### Serverless options @@ -135,20 +152,23 @@ Option | Required | Type | Description ### Scheduling -The `scheduling` configuration allows the user to configure how indexes are reprocessed in the source based on the the `index_read_count` and recount time `interval`. +The `scheduling` configuration allows the user to configure how indexes are reprocessed in the source based on the `index_read_count` and recount time `interval`. -For example, setting `index_read_count` to `3` with an `interval` of `1h` will result in all indexes being reprocessed 3 times, 1 hour apart. By default, indexes will only be processed once. +For example, setting `index_read_count` to `3` with an `interval` of `PT1H` reprocesses all indexes 3 times, 1 hour apart. By default, indexes are processed only once. Use the following options under the `scheduling` configuration. Option | Required | Type | Description :--- | :--- |:----------------| :--- `index_read_count` | No | Integer | The number of times each index will be processed. Default is `1`. -`interval` | No | String | The interval that determines the amount of time between reprocessing. Supports ISO 8601 notation strings, such as "PT20.345S" or "PT15M", as well as simple notation strings for seconds ("60s") and milliseconds ("1500ms"). Defaults to `8h`. +`interval` | No | String | The interval that determines the amount of time between reprocessing. Supports ISO 8601 notation strings, such as "PT20.345S" or "PT15M", as well as simple notation strings for seconds ("60s") and milliseconds ("1500ms"). Defaults to `PT8H`. `start_time` | No | String | The time when processing should begin. The source will not start processing until this time. The string must be in ISO 8601 format, such as `2007-12-03T10:15:30.00Z`. The default option starts processing immediately. +`discovery_mode` | No | String | Determines how often the source discovers indexes to process. Valid values are `periodic` and `single_scan`. When set to `periodic`, the source periodically checks for indexes to process, and each index is processed according to `index_read_count` and `interval`. When set to `single_scan`, the source discovers indexes once and processes each index one time. Default is `periodic`. +<!-- vale off --> ### indices +<!-- vale on --> The following options help the `opensearch` source determine which indexes are processed from the source cluster using regex patterns. An index will only be processed if it matches one of the `index_name_regex` patterns under the `include` setting and does not match any of the patterns under the `exclude` setting. @@ -165,7 +185,9 @@ Option | Required | Type | Description :--- |:----|:-----------------| :--- `index_name_regex` | Yes | Regex string | The regex pattern to match indexes against. +<!-- vale off --> ### search_options +<!-- vale on --> Use the following settings under the `search_options` configuration. @@ -173,12 +195,13 @@ Option | Required | Type | Description :--- |:---------|:--------| :--- `batch_size` | No | Integer | The number of documents to read while paginating from OpenSearch. Default is `1000`. `search_context_type` | No | Enum | An override for the type of search/pagination to use on indexes. Can be [point_in_time]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#point-in-time-with-search_after)), [scroll]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#scroll-search), or `none`. The `none` option will use the [search_after]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-search_after-parameter) parameter. For more information, see [Default Search Behavior](#default-search-behavior). +`sort` | No | List | A list of fields by which to sort documents when paginating. Each entry contains a required `name`, which specifies the field name, and an optional `order`, which is either `ascending` (default) or `descending`. Include `_id` in the list so that each document has a unique sort value; otherwise, pagination may skip or duplicate documents. By default, documents are sorted by `_doc` and then by `_id` (or only by `_doc` when using `scroll`). ### Default search behavior -By default, the `opensearch` source will look up the cluster version and distribution to determine -which `search_context_type` to use. For versions and distributions that support [Point in Time](https://opensearch.org/docs/latest/search-plugins/searching-data/paginate/#point-in-time-with-search_after), `point_in_time` will be used. -If `point_in_time` is not supported by the cluster, then [scroll](https://opensearch.org/docs/latest/search-plugins/searching-data/paginate/#scroll-search) will be used. For Amazon OpenSearch Serverless collections, [search_after](https://opensearch.org/docs/latest/search-plugins/searching-data/paginate/#the-search_after-parameter) will be used because neither `point_in_time` nor `scroll` are supported by collections. +By default, the `opensearch` source uses the cluster's version and distribution to determine which `search_context_type` to use. For clusters and domains that support [Point in Time]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#point-in-time-with-search_after), the source uses `point_in_time`. If the cluster does not support Point in Time search, it falls back to [scroll search]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#scroll-search). + +For Amazon OpenSearch Serverless collections, the default behavior is to use [`search_after`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#the-search_after-parameter). However, we recommend using `point_in_time` instead. ### Connection @@ -188,6 +211,9 @@ Option | Required | Type | Description :--- | :--- |:--------| :--- `cert` | No | String | The path to the security certificate, for example, `"config/root-ca.pem"`, when the cluster uses the OpenSearch Security plugin. `insecure` | No | Boolean | Whether or not to verify SSL certificates. If set to `true`, the certificate authority (CA) certificate verification is disabled and insecure HTTP requests are sent. Default is `false`. +`certificate` | No | String | The path to the CA certificate file or the content of the certificate in PEM format. Cannot be used together with `cert`. +`socket_timeout` | No | Duration | The socket timeout for requests to the cluster. If not specified, the default timeout of the underlying client is used. +`connection_timeout` | No | Duration | The timeout for establishing a connection to the cluster. If not specified, the default timeout of the underlying client is used. ### AWS @@ -198,6 +224,8 @@ Option | Required | Type | Description :--- | :--- |:--------| :--- `region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). `sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon OpenSearch Service and Amazon OpenSearch Serverless. Default is `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | The external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. `serverless` | No | Boolean | Should be set to `true` when processing from an Amazon OpenSearch Serverless collection. Defaults to `false`. ## Metrics @@ -229,7 +257,7 @@ In order to pull data from an OpenSearch cluster using the `opensearch` source p source: opensearch: username: "admin" - password: "admin" + password: "<custom-admin-password>" ... ``` diff --git a/_data-prepper/pipelines/configuration/sources/otel-logs-source.md b/_data-prepper/pipelines/configuration/sources/otel-logs-source.md index 58d8a2b0..64edf8b9 100644 --- a/_data-prepper/pipelines/configuration/sources/otel-logs-source.md +++ b/_data-prepper/pipelines/configuration/sources/otel-logs-source.md @@ -1,17 +1,17 @@ --- layout: default -title: otel_logs_source +title: OTel logs parent: Sources grand_parent: Pipelines -nav_order: 25 +nav_order: 60 --- -# otel_logs_source +# OTel logs source The `otel_logs_source` source is an OpenTelemetry source that follows the [OpenTelemetry Protocol Specification](https://github.com/open-telemetry/oteps/blob/master/text/0035-opentelemetry-protocol.md) and receives logs from the OTel Collector in the form of `ExportLogsServiceRequest` records. -This source supports the `OTLP/gRPC` protocol. +This source supports the `OTLP/gRPC` protocol. To also accept `OTLP/HTTP` requests, configure the `http_path` option. {: .note} ## Configuration @@ -20,14 +20,22 @@ You can configure the `otel_logs_source` source with the following options. | Option | Type | Description | | :--- | :--- | :--- | -| port | int | Represents the port that the `otel_logs_source` source is running on. Default value is `21892`. | -| path | string | Represents the path for sending unframed HTTP requests. You can use this option to support an unframed gRPC request with an HTTP idiomatic path to a configurable path. The path should start with `/`, and its length should be at least 1. The `/opentelemetry.proto.collector.logs.v1.LogsService/Export` endpoint is disabled for both gRPC and HTTP requests if the path is configured. The path can contain a `${pipelineName}` placeholder, which is replaced with the pipeline name. If the value is empty and `unframed_requests` is `true`, then the path that the source provides is `/opentelemetry.proto.collector.logs.v1.LogsService/Export`. | -| request_timeout | int | Represents the request timeout duration in milliseconds. Default value is `10000`. | +| port | Integer | Represents the port that the `otel_logs_source` source is running on. Default value is `21892`. | +| path | String | Represents the path for sending unframed HTTP requests. Use this option to support an unframed gRPC request with an HTTP idiomatic path to a configurable path. The path should start with `/`, and its length should be at least 1. The `/opentelemetry.proto.collector.logs.v1.LogsService/Export` endpoint is disabled for both gRPC and HTTP requests if the path is configured. The path can contain a `${pipelineName}` placeholder, which is replaced with the pipeline name. If the value is empty and `unframed_requests` is `true`, then the source provides the path `/opentelemetry.proto.collector.logs.v1.LogsService/Export`. | +| http_path | String | The path for an `OTLP/HTTP` endpoint that accepts JSON and Protobuf requests, for example, `/v1/logs`. The path can contain a `${pipelineName}` placeholder, which is replaced with the pipeline name. If not set, the source does not provide an `OTLP/HTTP` endpoint. When `http_path` is set and `health_check_service` is `true`, the source also provides an HTTP health check at `/health`. | +| max_request_length | String | The maximum number of bytes allowed in the payload of a single gRPC or HTTP request. Default value is `10mb`. | +| request_timeout | Integer | Represents the request timeout duration in milliseconds. Default value is `10000`. | | health_check_service | Boolean | Enables the gRPC health check service under `grpc.health.v1/Health/Check`. Default value is `false`. | | proto_reflection_service | Boolean | Enables a reflection service for Protobuf services (see [ProtoReflectionService](https://grpc.github.io/grpc-java/javadoc/io/grpc/protobuf/services/ProtoReflectionService.html) and [gRPC reflection](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md)). Default value is `false`. | | unframed_requests | Boolean | Enables requests that are not framed using the gRPC wire protocol. Default value is `false`. | -| thread_count | int | The number of threads to keep in the `ScheduledThreadPool`. Default value is `500`. | -| max_connection_count | int | The maximum number of open connections allowed. Default value is `500`. | +| thread_count | Integer | The number of threads to keep in the `ScheduledThreadPool`. Default value is `200`. | +| max_connection_count | Integer | The maximum number of open connections allowed. Default value is `500`. | +| max_connection_age | Duration | The maximum amount of time that a client connection can remain open. When a connection reaches this age, the source closes it gracefully, and the client must open a new connection. Use this setting when multiple Data Prepper nodes run behind DNS-based load balancing: gRPC clients resolve DNS only when they open a connection, so closing connections periodically allows clients to connect to newly added nodes. Must be between 1 second and 24 hours. By default, connections have no maximum age. | +| connection_drain_duration | Duration | The amount of time that the source waits for in-flight requests to complete when it gracefully closes a connection, for example, after the connection reaches the `max_connection_age`. Must be between 0 seconds and 1 hour. | +| compression | String | The compression type applied to the client request payload. Valid values are `none` or `gzip`. Use `gzip` to apply gzip decompression to the incoming request. Default is `none` (no compression). | +| authentication | Object | An authentication configuration. By default, an unauthenticated server is created for the pipeline. To use basic authentication, define the `http_basic` plugin with a `username` and `password`. Authentication applies to gRPC requests, `OTLP/HTTP` requests, and the health check. To provide custom authentication, use or create a plugin that implements [GrpcAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/armeria-common/src/main/java/org/opensearch/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). | +| retry_info | Object | Configures the retry delay that the source returns to clients in `RESOURCE_EXHAUSTED` responses, for example, when the buffer is full or a request times out. Supports the `min_delay` (default `100ms`) and `max_delay` (default `2s`) options. The suggested delay starts at `min_delay` and doubles with each consecutive rejection, up to `max_delay`. | +| output_format | String | Specifies the output format of the generated events. Valid values are `otel` or `opensearch`. Default is `opensearch`. | ### SSL @@ -35,20 +43,146 @@ You can configure SSL in the `otel_logs_source` source with the following option | Option | Type | Description | | :--- | :--- | :--- | -| ssl | Boolean | Enables TLS/SSL. Default value is `true`. | -| sslKeyCertChainFile | string | Represents the SSL certificate chain file path or Amazon Simple Storage Service (Amazon S3) path. For example, see the Amazon S3 path `s3://<bucketName>/<path>`. Required if `ssl` is set to `true`. | -| sslKeyFile | string | Represents the SSL key file path or Amazon S3 path. For example, see the Amazon S3 path `s3://<bucketName>/<path>`. Required if `ssl` is set to `true`. | -| useAcmCertForSSL | Boolean | Enables TLS/SSL using a certificate and private key from AWS Certificate Manager (ACM). Default value is `false`. | -| acmCertificateArn | string | Represents the ACM certificate Amazon Resource Name (ARN). ACM certificates take precedence over Amazon S3 or local file system certificates. Required if `useAcmCertForSSL` is set to `true`. | -| awsRegion | string | Represents the AWS Region used by ACM or Amazon S3. Required if `useAcmCertForSSL` is set to `true` or `sslKeyCertChainFile` or `sslKeyFile` is the Amazon S3 path. | +| `ssl` | Boolean | Enables TLS/SSL. Default value is `true`. | +| `sslKeyCertChainFile` | String | Represents the SSL certificate chain file path or Amazon Simple Storage Service (Amazon S3) path. For example, see the Amazon S3 path `s3://<bucketName>/<path>`. Required if `ssl` is set to `true`. | +| `sslKeyFile` | String | Represents the SSL key file path or Amazon S3 path. For example, see the Amazon S3 path `s3://<bucketName>/<path>`. Required if `ssl` is set to `true`. | +| `useAcmCertForSSL` | Boolean | Enables TLS/SSL using a certificate and private key from AWS Certificate Manager (ACM). Default value is `false`. | +| `acmCertificateArn` | String | Represents the ACM certificate Amazon Resource Name (ARN). ACM certificates take precedence over Amazon S3 or local file system certificates. Required if `useAcmCertForSSL` is set to `true`. | +| `acmPrivateKeyPassword` | String | The password used to decrypt the private key exported from ACM. If not provided, Data Prepper generates a random password. | +| `acmCertIssueTimeOutMillis` | Integer | The maximum amount of time, in milliseconds, that Data Prepper waits to retrieve the certificate from ACM. Default value is `120000`. | +| `awsRegion` | String | Represents the AWS Region used by ACM or Amazon S3. Required if `useAcmCertForSSL` is set to `true` or `sslKeyCertChainFile` or `sslKeyFile` is the Amazon S3 path. | ## Usage To get started, create a `pipeline.yaml` file and add `otel_logs_source` as the source: -``` +```yaml source: - - otel_logs_source: + otel_logs_source: +``` +{% include copy.html %} + +To generate data in the OpenTelemetry format, set the `output_format` setting to `otel`, as shown in the following example: + +```yaml +source: + otel_logs_source: + output_format: otel +``` +{% include copy.html %} + +## Example + +The following pipeline shows Data Prepper receiving OTLP logs over HTTPS using a PEM certificate and key, with unframed HTTP at a custom path, accepting gzip-compressed payloads, and indexing them into OpenSearch using the OpenTelemetry field schema: + +```yaml +otel-logs-otel-output: + source: + otel_logs_source: + ssl: true + sslKeyFile: /usr/share/data-prepper/certs/dp-key.pem + sslKeyCertChainFile: /usr/share/data-prepper/certs/dp-cert.pem + unframed_requests: true + path: /ingest/${pipelineName}/v1/logs + compression: gzip + output_format: otel + request_timeout: 15000 + health_check_service: true + proto_reflection_service: true + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: otel-logs-otel-output + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} + +You can test this pipeline using the following commands: + +```bash +cat > /tmp/otel-log3.json <<'JSON' +{ + "resourceLogs": [{ + "resource": {"attributes":[ + {"key":"service.name","value":{"stringValue":"checkout"}}, + {"key":"service.version","value":{"stringValue":"1.4.2"}} + ]}, + "scopeLogs": [{ + "scope": {"name":"manual-gzip"}, + "logRecords": [{ + "timeUnixNano": "1739999999000000000", + "severityText": "ERROR", + "body": {"stringValue":"payment gateway timeout"}, + "attributes":[ + {"key":"region","value":{"stringValue":"eu-west-1"}}, + {"key":"latency_ms","value":{"doubleValue":1234.5}} + ] + }] + }] + }] +} +JSON + +gzip -c /tmp/otel-log3.json > /tmp/otel-log3.json.gz + +curl -s -X POST "https://localhost:21892/ingest/otel-logs-otel-output/v1/logs" \ + -H 'Content-Type: application/json' \ + -H 'Content-Encoding: gzip' \ + --insecure \ + --data-binary @/tmp/otel-log3.json.gz +``` +{% include copy.html %} + +The document stored in OpenSearch contains the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "otel-logs-otel-output", + "_id": "l24NBpoBk9xzgdmMXFDm", + "_score": 1, + "_source": { + "traceId": "", + "instrumentationScope": { + "name": "manual-gzip", + "droppedAttributesCount": 0 + }, + "resource": { + "attributes": { + "service.name": "checkout", + "service.version": "1.4.2" + }, + "schemaUrl": "", + "droppedAttributesCount": 0 + }, + "flags": 0, + "severityNumber": 0, + "body": "payment gateway timeout", + "schemaUrl": "", + "spanId": "", + "severityText": "ERROR", + "attributes": { + "region": "eu-west-1", + "latency_ms": 1234.5 + }, + "time": "2025-02-19T21:19:59Z", + "droppedAttributesCount": 0, + "observedTimestamp": "1970-01-01T00:00:00Z" + } + } + ] + } +} ``` ## Metrics @@ -58,10 +192,11 @@ You can use the following metrics with the `otel_logs_source` source. | Option | Type | Description | | :--- | :--- | :--- | | `requestTimeouts` | Counter | Measures the total number of requests that time out. | +| `requestsRejectedByCircuitBreaker` | Counter | Measures the total number of requests rejected because the [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is open. These requests are rejected before the request body is read and are not counted in `requestTimeouts`. | | `requestsReceived` | Counter | Measures the total number of requests received by the `otel_logs_source` source. | | `badRequests` | Counter | Measures the total number of requests that could not be parsed. | | `requestsTooLarge` | Counter | Measures the total number of requests that exceed the maximum allowed size. Indicates that the size of the data being written into the buffer is beyond the buffer's maximum capacity. | | `internalServerError` | Counter | Measures the total number of requests that are erroneous due to errors other than `requestTimeouts` or `requestsTooLarge`. | | `successRequests` | Counter | Measures the total number of requests successfully written to the buffer. | | `payloadSize` | Distribution summary | Measures the distribution of all incoming payload sizes. | -| `requestProcessDuration` | Timer | Measures the duration of request processing. | \ No newline at end of file +| `requestProcessDuration` | Timer | Measures the duration of request processing. | diff --git a/_data-prepper/pipelines/configuration/sources/otel-metrics-source.md b/_data-prepper/pipelines/configuration/sources/otel-metrics-source.md index 03019635..e5b50dbb 100644 --- a/_data-prepper/pipelines/configuration/sources/otel-metrics-source.md +++ b/_data-prepper/pipelines/configuration/sources/otel-metrics-source.md @@ -1,35 +1,66 @@ --- layout: default -title: otel_metrics_source +title: OTel metrics parent: Sources grand_parent: Pipelines -nav_order: 10 +nav_order: 70 --- -# otel_metrics_source +# OTel metrics source -`otel_metrics_source` is an OpenTelemetry Collector source that collects metric data. The following table describes options you can use to configure the `otel_metrics_source` source. +The `otel_metrics_source` is an OpenTelemetry Collector source that collects metric data. The following table describes options you can use to configure the `otel_metrics_source` source. + +## Configuration + +You can configure the `otel_metrics_source` source with the following options. Option | Required | Type | Description :--- | :--- | :--- | :--- -port | No | Integer | The port that the OpenTelemtry metrics source runs on. Default value is `21891`. -request_timeout | No | Integer | The request timeout, in milliseconds. Default value is `10000`. -health_check_service | No | Boolean | Enables a gRPC health check service under `grpc.health.v1/Health/Check`. Default value is `false`. -proto_reflection_service | No | Boolean | Enables a reflection service for Protobuf services (see [gRPC reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md) and [gRPC Server Reflection Tutorial](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md) docs). Default value is `false`. -unframed_requests | No | Boolean | Enables requests not framed using the gRPC wire protocol. -thread_count | No | Integer | The number of threads to keep in the `ScheduledThreadPool`. Default value is `200`. -max_connection_count | No | Integer | The maximum allowed number of open connections. Default value is `500`. -ssl | No | Boolean | Enables connections to the OpenTelemetry source port over TLS/SSL. Default value is `true`. -sslKeyCertChainFile | Conditionally | String | File-system path or Amazon Simple Storage Service (Amazon S3) path to the security certificate (for example, `"config/demo-data-prepper.crt"` or `"s3://my-secrets-bucket/demo-data-prepper.crt"`). Required if `ssl` is set to `true`. -sslKeyFile | Conditionally | String | File-system path or Amazon S3 path to the security key (for example, `"config/demo-data-prepper.key"` or `"s3://my-secrets-bucket/demo-data-prepper.key"`). Required if `ssl` is set to `true`. -useAcmCertForSSL | No | Boolean | Whether to enable TLS/SSL using a certificate and private key from AWS Certificate Manager (ACM). Default value is `false`. -acmCertificateArn | Conditionally | String | Represents the ACM certificate ARN. ACM certificate take preference over S3 or local file system certificates. Required if `useAcmCertForSSL` is set to `true`. -awsRegion | Conditionally | String | Represents the AWS Region used by ACM or Amazon S3. Required if `useAcmCertForSSL` is set to `true` or `sslKeyCertChainFile` and `sslKeyFile` is the Amazon S3 path. -authentication | No | Object | An authentication configuration. By default, an unauthenticated server is created for the pipeline. This uses pluggable authentication for HTTPS. To use basic authentication, define the `http_basic` plugin with a `username` and `password`. To provide customer authentication, use or create a plugin that implements [GrpcAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/1.2.0/data-prepper-plugins/armeria-common/src/main/java/com/amazon/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). +`port` | No | Integer | The port that the OpenTelemtry metrics source runs on. Default value is `21891`. +`request_timeout` | No | Integer | The request timeout, in milliseconds. Default value is `10000`. +`health_check_service` | No | Boolean | Enables a gRPC health check service under `grpc.health.v1/Health/Check`. Default value is `false`. +`unauthenticated_health_check` | No | Boolean | Determines whether or not authentication is required on the health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default value is `false`. +`proto_reflection_service` | No | Boolean | Enables a reflection service for Protobuf services (see [gRPC reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md) and [gRPC Server Reflection Tutorial](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md) docs). Default value is `false`. +`unframed_requests` | No | Boolean | Enables requests not framed using the gRPC wire protocol. +`thread_count` | No | Integer | The number of threads to keep in the `ScheduledThreadPool`. Default value is `200`. +`max_connection_count` | No | Integer | The maximum allowed number of open connections. Default value is `500`. +`max_connection_age` | No | Duration | The maximum amount of time that a client connection can remain open. When a connection reaches this age, the source closes it gracefully, and the client must open a new connection. Use this setting when multiple Data Prepper nodes run behind DNS-based load balancing: gRPC clients resolve DNS only when they open a connection, so closing connections periodically allows clients to connect to newly added nodes. Must be between 1 second and 24 hours. By default, connections have no maximum age. +`connection_drain_duration` | No | Duration | The amount of time that the source waits for in-flight requests to complete when it gracefully closes a connection, for example, after the connection reaches the `max_connection_age`. Must be between 0 seconds and 1 hour. +| `output_format` | String | Specifies the output format of the generated events. Valid values are `otel` or `opensearch`. Default is `opensearch`. | +`max_request_length` | No | ByteCount | The maximum number of bytes allowed in the payload of a single gRPC or HTTP request. Default value is `10mb`. +`path` | No | String | A custom path for the metrics export service, for example, `/v1/metrics`. Must start with `/`. When set, the source receives gRPC and unframed requests at this path, and the default `/opentelemetry.proto.collector.metrics.v1.MetricsService/Export` path is disabled. The path can contain a `${pipelineName}` placeholder, which is replaced with the pipeline name. +`compression` | No | String | The compression type applied to the client request payload. Valid values are `none` and `gzip`. Use `gzip` to apply gzip decompression to the incoming request. Default is `none`. +`retry_info` | No | Object | Configures the retry delay that the source returns to clients in `RESOURCE_EXHAUSTED` responses, for example, when the buffer is full or a request times out. Supports the `min_delay` (default `100ms`) and `max_delay` (default `2s`) options. The suggested delay starts at `min_delay` and doubles with each consecutive rejection, up to `max_delay`. +`partition_keys` | No | List | The keys used to split each request into partitions when the pipeline uses a buffer that stores raw bytes, such as the `kafka` buffer. Valid values are `name` and `service_name`. The list must contain `name` and can also contain `service_name`. The source then writes metrics to the buffer partitioned by metric name or by service and metric name. +`ssl` | No | Boolean | Enables connections to the OpenTelemetry source port over TLS/SSL. Default value is `true`. +`sslKeyCertChainFile` | Conditionally | String | File-system path or Amazon Simple Storage Service (Amazon S3) path to the security certificate (for example, `"config/demo-data-prepper.crt"` or `"s3://my-secrets-bucket/demo-data-prepper.crt"`). Required if `ssl` is set to `true`. +`sslKeyFile` | Conditionally | String | File-system path or Amazon S3 path to the security key (for example, `"config/demo-data-prepper.key"` or `"s3://my-secrets-bucket/demo-data-prepper.key"`). Required if `ssl` is set to `true`. +`useAcmCertForSSL` | No | Boolean | Whether to enable TLS/SSL using a certificate and private key from AWS Certificate Manager (ACM). Default value is `false`. +`acmCertificateArn` | Conditionally | String | Represents the ACM certificate ARN. ACM certificate take preference over S3 or local file system certificates. Required if `useAcmCertForSSL` is set to `true`. +`acmPrivateKeyPassword` | No | String | The password used to decrypt the private key exported from ACM. If not provided, Data Prepper generates a random password. +`acmCertIssueTimeOutMillis` | No | Integer | The maximum amount of time, in milliseconds, that Data Prepper waits to retrieve the certificate from ACM. Default value is `120000`. +`awsRegion` | Conditionally | String | Represents the AWS Region used by ACM or Amazon S3. Required if `useAcmCertForSSL` is set to `true` or `sslKeyCertChainFile` and `sslKeyFile` is the Amazon S3 path. +`authentication` | No | Object | An authentication configuration. By default, an unauthenticated server is created for the pipeline. This uses pluggable authentication for HTTPS. To use basic authentication, define the `http_basic` plugin with a `username` and `password`. To provide customer authentication, use or create a plugin that implements [GrpcAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/1.2.0/data-prepper-plugins/armeria-common/src/main/java/com/amazon/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). -<!--- ## Configuration +## Usage + +To use the `otel-metrics` source, create the following `pipeline.yaml` file with `otel_metrics_source` as the source: + +```yaml +source: + - otel_metrics_source: +``` +{% include copy.html %} + +To use the OpenTelemetry format for your output, set the `output_format` to `otel`, as shown in the following example: + +```yaml +source: + - otel_metrics_source: + output_format: otel +``` +{% include copy.html %} -Content will be added to this section.---> ## Metrics @@ -38,5 +69,6 @@ The `otel_metrics_source` source includes the following metrics. ### Counters - `requestTimeouts`: Measures the total number of requests that time out. +- `requestsRejectedByCircuitBreaker`: Measures the total number of requests rejected because the [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is open. These requests are rejected before the request body is read and are not counted in `requestTimeouts`. - `requestsReceived`: Measures the total number of requests received by the OpenTelemetry metrics source. diff --git a/_data-prepper/pipelines/configuration/sources/otel-trace-source.md b/_data-prepper/pipelines/configuration/sources/otel-trace-source.md new file mode 100644 index 00000000..c07aac67 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/otel-trace-source.md @@ -0,0 +1,212 @@ +--- +layout: default +title: OTel trace +parent: Sources +grand_parent: Pipelines +nav_order: 80 +redirect_from: + - /data-prepper/pipelines/configuration/sources/otel-trace/ +--- + + +# OTel trace source + +The `otel_trace_source` is a source for the OpenTelemetry Collector. The following table describes options you can use to configure the `otel_trace_source` source. + +## Configuration + +You can configure the `otel_trace_source` source with the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`port` | No | Integer | The port that the `otel_trace_source` source runs on. Default value is `21890`. +`request_timeout` | No | Integer | The request timeout, in milliseconds. Default value is `10000`. +`health_check_service` | No | Boolean | Enables a gRPC health check service under `grpc.health.v1/Health/Check`. Default value is `false`. +`unauthenticated_health_check` | No | Boolean | Determines whether or not authentication is required on the health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default value is `false`. +`proto_reflection_service` | No | Boolean | Enables a reflection service for Protobuf services (see [gRPC reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md) and [gRPC Server Reflection Tutorial](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md) docs). Default value is `false`. +`unframed_requests` | No | Boolean | Enable requests not framed using the gRPC wire protocol. +`thread_count` | No | Integer | The number of threads to keep in the ScheduledThreadPool. Default value is `200`. +`max_connection_count` | No | Integer | The maximum allowed number of open connections. Default value is `500`. +`max_connection_age` | No | Duration | The maximum amount of time that a client connection can remain open. When a connection reaches this age, the source closes it gracefully, and the client must open a new connection. Use this setting when multiple Data Prepper nodes run behind DNS-based load balancing: gRPC clients resolve DNS only when they open a connection, so closing connections periodically allows clients to connect to newly added nodes. Must be between 1 second and 24 hours. By default, connections have no maximum age. +`connection_drain_duration` | No | Duration | The amount of time that the source waits for in-flight requests to complete when it gracefully closes a connection, for example, after the connection reaches the `max_connection_age`. Must be between 0 seconds and 1 hour. +| `output_format` | String | Specifies the output format of the generated events. Valid values are `otel` or `opensearch`. Default is `opensearch`. | +`max_request_length` | No | ByteCount | The maximum number of bytes allowed in the payload of a single gRPC or HTTP request. Default value is `10mb`. +`path` | No | String | A custom path for the traces export service, for example, `/v1/traces`. Must start with `/`. When set, the source receives gRPC and unframed requests at this path, and the default `/opentelemetry.proto.collector.trace.v1.TraceService/Export` path is disabled. The path can contain a `${pipelineName}` placeholder, which is replaced with the pipeline name. +`compression` | No | String | The compression type applied to the client request payload. Valid values are `none` and `gzip`. Use `gzip` to apply gzip decompression to the incoming request. Default is `none`. +`retry_info` | No | Object | Configures the retry delay that the source returns to clients in `RESOURCE_EXHAUSTED` responses, for example, when the buffer is full or a request times out. Supports the `min_delay` (default `100ms`) and `max_delay` (default `2s`) options. The suggested delay starts at `min_delay` and doubles with each consecutive rejection, up to `max_delay`. +`ssl` | No | Boolean | Enables connections to the OTel source port over TLS/SSL. Defaults to `true`. +sslKeyCertChainFile | Conditionally | String | File system path or Amazon Simple Storage Service (Amazon S3) path to the security certificate (for example, `"config/demo-data-prepper.crt"` or `"s3://my-secrets-bucket/demo-data-prepper.crt"`). Required if `ssl` is set to `true`. +`sslKeyFile` | Conditionally | String | File system path or Amazon S3 path to the security key (for example, `"config/demo-data-prepper.key"` or `"s3://my-secrets-bucket/demo-data-prepper.key"`). Required if `ssl` is set to `true`. +`useAcmCertForSSL` | No | Boolean | Whether to enable TLS/SSL using a certificate and private key from AWS Certificate Manager (ACM). Default value is `false`. +`acmCertificateArn` | Conditionally | String | Represents the ACM certificate ARN. ACM certificate take preference over S3 or local file system certificate. Required if `useAcmCertForSSL` is set to `true`. +`acmPrivateKeyPassword` | No | String | The password used to decrypt the private key exported from ACM. If not provided, Data Prepper generates a random password. +`acmCertIssueTimeOutMillis` | No | Integer | The maximum amount of time, in milliseconds, that Data Prepper waits to retrieve the certificate from ACM. Default value is `120000`. +`awsRegion` | Conditionally | String | Represents the AWS region used by ACM or Amazon S3. Required if `useAcmCertForSSL` is set to `true` or `sslKeyCertChainFile` and `sslKeyFile` are Amazon S3 paths. +`authentication` | No | Object | An authentication configuration. By default, an unauthenticated server is created for the pipeline. This parameter uses pluggable authentication for HTTPS. To use basic authentication, define the `http_basic` plugin with a `username` and `password`. To provide customer authentication, use or create a plugin that implements [GrpcAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/1.2.0/data-prepper-plugins/armeria-common/src/main/java/com/amazon/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). + +## Usage + +To use the `otel-metrics` source, create the following `pipeline.yaml` file with `otel_metrics_source` as the source: + +```yaml +source: + otel_trace_source: +``` +{% include copy.html %} + +If you want to use the OpenTelemetry format for your output, set the `output_format` to `otel`, as shown in the following example: + +```yaml +source: + otel_trace_source: + output_format: otel +``` +{% include copy.html %} + +## Example + +The following example shows Data Prepper ingesting OTLP traces over HTTPS using a PEM certificate and key with unframed HTTP at a custom path, accepting gzip-compressed payloads, preserving OpenTelemetry document structure, and indexing them into OpenSearch: + +```yaml +otel-traces-https: + source: + otel_trace_source: + ssl: true + sslKeyFile: /usr/share/data-prepper/certs/dp-key.pem + sslKeyCertChainFile: /usr/share/data-prepper/certs/dp-cert.pem + unframed_requests: true + path: /ingest/${pipelineName}/v1/traces + compression: gzip + output_format: otel + request_timeout: 15000 + health_check_service: true + proto_reflection_service: true + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: otel-traces-https + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +cat > /tmp/otel-trace3.json <<'JSON' +{ + "resourceSpans": [{ + "resource": {"attributes":[ + {"key":"service.name","value":{"stringValue":"billing"}}, + {"key":"service.version","value":{"stringValue":"2.1.0"}} + ]}, + "scopeSpans": [{ + "scope": {"name":"manual-https"}, + "spans": [{ + "traceId": "1234567890abcdef1234567890abcdef", + "spanId": "feedfacecafebeef", + "name": "PUT /invoice/42", + "startTimeUnixNano": "1739999999000000000", + "endTimeUnixNano": "1740000000000000000", + "attributes": [ + {"key":"region","value":{"stringValue":"eu-west-1"}}, + {"key":"retry.count","value":{"intValue":"1"}} + ] + }] + }] + }] +} +JSON + +gzip -c /tmp/otel-trace3.json > /tmp/otel-trace3.json.gz + +curl -s -X POST "https://localhost:21890/ingest/otel-traces-https/v1/traces" \ + -H 'Content-Type: application/json' \ + -H 'Content-Encoding: gzip' \ + --insecure \ + --data-binary @/tmp/otel-trace3.json.gz +``` +{% include copy.html %} + +The document stored in OpenSearch contains the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "otel-traces-https", + "_id": "V_5RBpoBqZ1V_u-TvYXf", + "_score": 1, + "_source": { + "traceId": "d76df8e7aefcf7469b71d79fd76df8e7aefcf7469b71d79f", + "droppedLinksCount": 0, + "instrumentationScope": { + "name": "manual-https", + "droppedAttributesCount": 0 + }, + "resource": { + "schemaUrl": "", + "attributes": { + "service.name": "billing", + "service.version": "2.1.0" + }, + "droppedAttributesCount": 0 + }, + "kind": "SPAN_KIND_UNSPECIFIED", + "droppedEventsCount": 0, + "flags": 0, + "parentSpanId": "", + "schemaUrl": "", + "spanId": "7de79d7da71e71a7de6de79f", + "traceState": "", + "name": "PUT /invoice/42", + "startTime": "2025-02-19T21:19:59Z", + "attributes": { + "retry.count": 1, + "region": "eu-west-1" + }, + "links": [], + "endTime": "2025-02-19T21:20:00Z", + "droppedAttributesCount": 0, + "durationInNanos": 1000000000, + "events": [], + "status": { + "code": 0, + "message": "" + } + } + } + ] + } +} +``` + +## Metrics + +The `otel_trace_source` source includes the following metrics. + +### Counters + +- `requestTimeouts`: Measures the total number of requests that time out. +- `requestsRejectedByCircuitBreaker`: Measures the total number of requests rejected because the [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is open. These requests are rejected before the request body is read and are not counted in `requestTimeouts`. +- `requestsReceived`: Measures the total number of requests received by the `otel_trace` source. +- `successRequests`: Measures the total number of requests successfully processed by the `otel_trace` source plugin. +- `badRequests`: Measures the total number of requests with an invalid format processed by the `otel_trace` source plugin. +- `requestsTooLarge`: Measures the total number of requests whose number of spans exceeds the buffer capacity. +- `internalServerError`: Measures the total number of requests processed by the `otel_trace` source with a custom exception type. + +### Timers + +- `requestProcessDuration`: Measures the latency of requests processed by the `otel_trace` source plugin in seconds. + +### Distribution summaries + +- `payloadSize`: Measures the incoming request payload size distribution in bytes. diff --git a/_data-prepper/pipelines/configuration/sources/otlp-source.md b/_data-prepper/pipelines/configuration/sources/otlp-source.md new file mode 100644 index 00000000..b6ba4852 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/otlp-source.md @@ -0,0 +1,342 @@ +--- +layout: default +title: OTLP +parent: Sources +grand_parent: Pipelines +nav_order: 85 +--- + +# OTLP source + +The `otlp` source is a unified OpenTelemetry source that follows the [OpenTelemetry Protocol (OTLP) specification](https://opentelemetry.io/docs/specs/otlp/) and can receive logs, metrics, and traces through a single endpoint. This source consolidates the functionality of the individual `otel_logs_source`, `otel_metrics_source`, and `otel_trace_source` sources, providing a streamlined approach to ingesting all OpenTelemetry telemetry signals. + +The `otlp` source supports both the `OTLP/gRPC` and `OTLP/HTTP` protocols. For `OTLP/HTTP`, only Protobuf encoding is supported. This makes it compatible with a wide range of OpenTelemetry collectors and instrumentation libraries. +{: .note} + +## Configuration + +You can configure the `otlp` source with the following options. + +| Option | Type | Description | +| :--- | :--- | :--- | +| `port` | Integer | The port on which the `otlp` source listens. Default is `21893`. | +| `logs_path` | String | The path for sending unframed HTTP requests for logs. Must start with `/` and have a minimum length of 1. Default is `/opentelemetry.proto.collector.logs.v1.LogsService/Export`. | +| `metrics_path` | String | The path for sending unframed HTTP requests for metrics. Must start with `/` and have a minimum length of 1. Default is `/opentelemetry.proto.collector.metrics.v1.MetricsService/Export`. | +| `traces_path` | String | The path for sending unframed HTTP requests for traces. Must start with `/` and have a minimum length of 1. Default is `/opentelemetry.proto.collector.trace.v1.TraceService/Export`. | +| `request_timeout` | Duration | The request timeout duration. Default is `10s`. | +| `retry_info` | Object | Configures retry behavior. Supports `min_delay` (default `100ms`) and `max_delay` (default `2s`) parameters to control exponential backoff. See [Retry configuration](#retry-configuration).| +| `health_check_service` | Boolean | Enables a gRPC health check service under `grpc.health.v1.Health/Check`. When `unframed_requests` is `true`, enables HTTP health check at `/health`. Default is `false`. | +| `unauthenticated_health_check` | Boolean | Determines whether or not authentication is required on the HTTP health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default is `false`. | +| `proto_reflection_service` | Boolean | Enables a reflection service for Protobuf services (see [ProtoReflectionService](https://grpc.github.io/grpc-java/javadoc/io/grpc/protobuf/services/ProtoReflectionService.html) and [gRPC reflection](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md)). Default is `false`. | +| `unframed_requests` | Boolean | Enables requests not framed using the gRPC wire protocol. Default is `false`. | +| `thread_count` | Integer | The number of threads to keep in the scheduled thread pool. Default is `200`. | +| `max_connection_count` | Integer | The maximum allowed number of open connections. Default is `500`. | +| `max_connection_age` | Duration | The maximum amount of time that a client connection can remain open. When a connection reaches this age, the source closes it gracefully, and the client must open a new connection. Use this setting when multiple Data Prepper nodes run behind DNS-based load balancing: gRPC clients resolve DNS only when they open a connection, so closing connections periodically allows clients to connect to newly added nodes. Must be between 1 second and 24 hours. By default, connections have no maximum age. | +| `connection_drain_duration` | Duration | The amount of time that the source waits for in-flight requests to complete when it gracefully closes a connection, for example, after the connection reaches the `max_connection_age`. Must be between 0 seconds and 1 hour. | +| `max_request_length` | String | The maximum number of bytes allowed in the payload of a single gRPC or HTTP request. Default is `10mb`. | +| `compression` | String | The compression type applied to the client request payload. Valid values are `none` (no compression) or `gzip` (apply `gzip` decompression). Default is `none`. | +| `authentication` | Object | The authentication configuration. By default, the source runs without authentication. See [Authentication configuration](#authentication-configuration). | +| `output_format` | String | Specifies the decoded output format for all signals (logs, metrics, and traces) if individual output format options are not set. Valid values are `otel` (OpenTelemetry format) and `opensearch` (OpenSearch format). Default is `otel`. | +| `logs_output_format` | String | Specifies the decoded output format specifically for logs. Takes precedence over `output_format` for logs. Valid values are `otel` and `opensearch`. Default is `otel`. | +| `metrics_output_format` | String | Specifies the decoded output format specifically for metrics. Takes precedence over `output_format` for metrics. Valid values are `otel` and `opensearch`. Default is `otel`. | +| `traces_output_format` | String | Specifies the decoded output format specifically for traces. Takes precedence over `output_format` for traces. Valid values are `otel` and `opensearch`. Default is `otel`. | + +If an individual output format (for example, `logs_output_format`) is set, it takes precedence over the generic `output_format` for that signal type. If neither is set, the default is `otel`. +{: .note} + +### SSL/TLS configuration + +You can configure SSL/TLS in the `otlp` source with the following options. + +| Option | Type | Description | +| :--- | :--- | :--- | +| `ssl` | Boolean | Enables SSL/TLS. Default is `true`. | +| `ssl_certificate_file` | String | The SSL certificate chain file path or Amazon Simple Storage Service (Amazon S3) path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true`. | +| `ssl_key_file` | String | The SSL key file path or Amazon S3 path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true`. | +| `use_acm_certificate_for_ssl` | Boolean | Enables SSL/TLS using a certificate and private key from AWS Certificate Manager (ACM). Default is `false`. | +| `acm_certificate_arn` | String | The ACM certificate Amazon Resource Name (ARN). ACM certificates take precedence over Amazon S3 or local file system certificates. Required if `use_acm_certificate_for_ssl` is set to `true`. | +| `acm_private_key_password` | String | The ACM private key password that decrypts the private key. If not provided, OpenSearch Data Prepper generates a random password. | +| `acm_certificate_timeout` | Duration | The maximum amount of time that Data Prepper waits to retrieve the certificate from ACM. Must be between `5s` and `3600s`. Default is `120s`. | +| `aws_region` | String | The AWS Region used by ACM or Amazon S3. Required if `use_acm_certificate_for_ssl` is set to `true` or if `ssl_certificate_file` and `ssl_key_file` are Amazon S3 paths. | + +### Authentication configuration + +By default, the `otlp` source runs without authentication. You can configure authentication using the following options. + +To explicitly disable authentication, specify the following settings: + +```yaml +source: + otlp: + authentication: + unauthenticated: +``` +{% include copy.html %} + +To enable HTTP Basic authentication, specify the following settings: + +```yaml +source: + otlp: + authentication: + http_basic: + username: my-user + password: my_s3cr3t +``` +{% include copy.html %} + +This plugin uses pluggable authentication for gRPC servers. To provide custom authentication, create a plugin that implements [`GrpcAuthenticationProvider`](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/armeria-common/src/main/java/org/opensearch/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). + +### Retry configuration + +To configure retry behavior, use the `retry_info` setting. The setting specifies the amount of time to wait before the next request when backpressure occurs, including when the [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is open. The retry mechanism applies exponential backoff with a configurable maximum delay: + +```yaml +source: + otlp: + retry_info: + min_delay: 100ms # defaults to 100ms + max_delay: 2s # defaults to 2s +``` +{% include copy.html %} + +## Usage + +The following examples demonstrate how to configure and use the `otlp` source in various scenarios. + +### Basic configuration + +To get started with the `otlp` source, create a `pipeline.yaml` file with the following minimal configuration: + +```yaml +pipeline: + source: + otlp: + ssl: false + sink: + - stdout: +``` +{% include copy.html %} + +### Routing telemetry signals + +One of the key features of the `otlp` source is its ability to route different telemetry signals (logs, metrics, and traces) to different processors or sinks based on your specific needs. Routing is determined by metadata using the `getEventType()` function: + +```yaml +version: "2" +otel-telemetry: + source: + otlp: + ssl: false + route: + - traces: 'getEventType() == "TRACE"' + - logs: 'getEventType() == "LOG"' + - metrics: 'getEventType() == "METRIC"' + sink: + - opensearch: + routes: + - logs + hosts: [ "https://opensearch:9200" ] + index: logs-%{yyyy.MM.dd} + username: admin + password: "<custom-admin-password>" + insecure: true + - pipeline: + name: traces-raw + routes: + - traces + - pipeline: + name: otel-metrics + routes: + - metrics + +traces-raw: + source: + pipeline: + name: otel-telemetry + processor: + - otel_trace_raw: + sink: + - opensearch: + hosts: [ "https://opensearch:9200" ] + index_type: trace-analytics-raw + username: admin + password: "<custom-admin-password>" + insecure: true + +otel-metrics: + source: + pipeline: + name: otel-telemetry + processor: + - otel_metrics: + calculate_histogram_buckets: true + calculate_exponential_histogram_buckets: true + exponential_histogram_max_allowed_scale: 10 + flatten_attributes: false + sink: + - opensearch: + hosts: [ "https://opensearch:9200" ] + index: metrics-otel-%{yyyy.MM.dd} + username: admin + password: "<custom-admin-password>" + insecure: true +``` +{% include copy.html %} + +### Using OpenSearch output format + +To generate data in the OpenSearch format for all telemetry signals, specify the following settings: + +```yaml +source: + otlp: + output_format: opensearch +``` +{% include copy.html %} + +To use different output formats for different signal types, specify the following settings: + +```yaml +source: + otlp: + logs_output_format: opensearch + metrics_output_format: otel + traces_output_format: opensearch +``` +{% include copy.html %} + +### Configuring with SSL/TLS + +To enable SSL/TLS with local certificates, specify the following settings: + +```yaml +source: + otlp: + ssl: true + ssl_certificate_file: "/path/to/certificate.crt" + ssl_key_file: "/path/to/private-key.key" +``` +{% include copy.html %} + +To use the ACM, specify the following settings: + +```yaml +source: + otlp: + ssl: true + use_acm_certificate_for_ssl: true + acm_certificate_arn: "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012" + aws_region: "us-east-1" +``` +{% include copy.html %} + +## Metrics + +The `otlp` source includes the following metrics for monitoring its performance and health. + +### Counters + +The following counters track request activity and errors in the `otlp` source. + +| Metric | Description | +| :--- | :--- | +| `requestTimeouts` | The total number of requests that timed out. | +| `requestsRejectedByCircuitBreaker` | The total number of requests rejected because the [circuit breaker]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#circuit-breakers) is open. These requests are rejected before the request body is read and are not counted in `requestTimeouts`. | +| `requestsReceived` | The total number of requests received by the `otlp` source. | +| `successRequests` | The total number of requests successfully processed by the `otlp` source. | +| `badRequests` | The total number of requests with an invalid format processed by the `otlp` source. | +| `requestsTooLarge` | The total number of requests that exceed the maximum allowed size. | +| `internalServerError` | The total number of requests processed by the `otlp` source with custom exception types. | + +### Timers + +The following timers track request activity and errors in the `otlp` source. + +| Metric | Description | +| :--- | :--- | +| `requestProcessDuration` | The latency of requests processed by the `otlp` source, in seconds. | + +### Distribution summaries + +The following distribution summaries track request activity and errors in the `otlp` source. + +| Metric | Description | +| :--- | :--- | +| `payloadSize` | The distribution of incoming request payload sizes, in bytes. | + +## Migrating from individual OpenTelemetry sources + +If you're using separate `otel_logs_source`, `otel_metrics_source`, or `otel_trace_source` sources, you can migrate to the unified `otlp` source by following these steps: + +1. Replace all three sources with a single `otlp` source. +2. Use [routing configuration](#routing-telemetry-signals) to direct different signal types to their appropriate pipelines. +3. Change the port numbers if needed (the `otlp` source uses port `21893` by default). + +### Migration example + +The following example demonstrates how to consolidate separate OpenTelemetry log, metric, and trace sources into a single `otlp` source. + +Consider a setup where logs, metrics, and traces are configured separately: + +```yaml +logs-pipeline: + source: + otel_logs_source: + port: 21892 + sink: + - opensearch: + index: logs +``` +```yaml +metrics-pipeline: + source: + otel_metrics_source: + port: 21891 + sink: + - opensearch: + index: metrics +``` +```yaml +traces-pipeline: + source: + otel_trace_source: + port: 21890 + sink: + - opensearch: + index: traces +``` + +You can consolidate logs, metrics, and traces into a single `otlp` source as follows: + +```yaml +otlp-pipeline: + source: + otlp: + port: 21893 + route: + - logs: 'getEventType() == "LOG"' + - metrics: 'getEventType() == "METRIC"' + - traces: 'getEventType() == "TRACE"' + sink: + - opensearch: + routes: + - logs + index: logs + - opensearch: + routes: + - metrics + index: metrics + - opensearch: + routes: + - traces + index: traces +``` +{% include copy.html %} + +## Related documentation + +- [OTel logs source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-logs-source/) +- [OTel metrics source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-metrics-source/) +- [OTel trace source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace-source/) +- [getEventType()]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-eventtype/) \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/sources/pipeline.md b/_data-prepper/pipelines/configuration/sources/pipeline.md new file mode 100644 index 00000000..f2ed00d9 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/pipeline.md @@ -0,0 +1,31 @@ +--- +layout: default +title: Pipeline +parent: Sources +grand_parent: Pipelines +nav_order: 90 +--- + +# Pipeline source + +Use the `pipeline` sink to read from another pipeline. + +## Configuration + +The `pipeline` source supports the following configuration options. + +| Option | Required | Type | Description | +|:-------|:---------|:-------|:---------------------------------------| +| `name` | Yes | String | The name of the pipeline to read from. | + +## Usage + +The following example configures a `pipeline` sink named `sample-pipeline` that reads from a pipeline named `movies`: + +```yaml +sample-pipeline: + source: + - pipeline: + name: "movies" +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/configuration/sources/rds.md b/_data-prepper/pipelines/configuration/sources/rds.md new file mode 100644 index 00000000..a17b8a73 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/rds.md @@ -0,0 +1,333 @@ +--- +layout: default +title: RDS +parent: Sources +grand_parent: Pipelines +nav_order: 95 +--- + +# RDS source + +The `rds` source enables change data capture (CDC) on [Amazon Relational Database Service (Amazon RDS)](https://aws.amazon.com/rds/) and [Amazon Aurora](https://aws.amazon.com/aurora/) databases. It can receive database events, such as `INSERT`, `UPDATE`, or `DELETE`, using database replication logs and supports initial load using RDS exports to Amazon Simple Storage Service (Amazon S3). + +The source supports the following database engines: +- Aurora MySQL and Aurora PostgreSQL +- RDS MySQL and RDS PostgreSQL + +The source includes two ingestion options for ingesting data from Aurora/RDS: + +1. Export: A full initial export from Aurora/RDS to S3 gets an initial load of the current state of the Aurora/RDS database. +2. Stream: Stream events from database replication logs (MySQL `binlog` or PostgreSQL WAL). + +## Usage + +The following example pipeline specifies an `rds` source. It ingests data from an Aurora MySQL cluster: + +```yaml +version: "2" +rds-pipeline: + source: + rds: + db_identifier: "my-rds-instance" + engine: "aurora-mysql" + database: "mydb" + authentication: + username: "myuser" + password: "mypassword" + s3_bucket: "my-export-bucket" + s3_region: "us-west-2" + s3_prefix: "rds-exports" + export: + kms_key_id: "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012" + export_role_arn: "arn:aws:iam::123456789012:role/rds-export-role" + stream: true + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-pipeline-role" +``` + +## Configuration options + +The following tables describe the configuration options for the `rds` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`db_identifier` | Yes | String | The identifier for the RDS instance or Aurora cluster. +`cluster` | No | Boolean | Whether the `db_identifier` refers to a cluster (`true`) or an instance (`false`). Default is `false`. For Aurora engines, this option is always `true`. +`engine` | Yes | String | The database engine type. Must be one of `mysql`, `postgresql`, `aurora-mysql`, or `aurora-postgresql`. +`database` | Yes | String | The name of the database to connect to. +`tables` | No | Object | The configuration for specifying which tables to include or exclude. See [tables](#tables) for more information. +`authentication` | Yes | Object | Database authentication credentials. See [authentication](#authentication) for more information. +`aws` | Yes | Object | The AWS configuration. See [`aws`](#aws) for more information. +`acknowledgments` | No | Boolean | When `true`, enables the source to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `true`. +`s3_data_file_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from an RDS export expires when used with acknowledgments. Default is 30 minutes. +`stream_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from database streams expires when used with acknowledgments. Default is 10 minutes. +`s3_bucket` | Yes | String | The name of the S3 bucket in which RDS export data will be stored. +`s3_prefix` | No | String | The prefix for S3 objects in the export bucket. +`s3_region` | No | String | The AWS Region for the S3 bucket. If not specified, uses the same Region as specified in the [`aws`](#aws) configuration. +`partition_count` | No | Integer | The number of folder partitions in the S3 buffer. Must be between 1 and 1,000. Default is 100. +`export` | No | Object | The configuration for RDS export operations. See [export](#export-options) for more information. +`stream` | No | Boolean | Whether to enable streaming of database change events. Default is `false`. +`tls` | No | Object | The TLS configuration for database connections. See [`tls`](#tls-options) for more information. +`disable_s3_read_for_leader` | No | Boolean | Whether to disable S3 read operations for the leader node. Default is `false`. +`scan_mode` | No | String | Determines whether the pipeline continues to list S3 buffer folder partitions in which no new objects are found. Valid values are `idle_optimized` and `continuous`. In `idle_optimized` mode, a folder partition in which no objects are found for 1 hour is no longer listed until a later bucket scan finds new objects in that folder. This reduces the number of S3 `ListObjectsV2` requests while the database is idle but delays the detection of the first changes written to that folder after the idle period. In `continuous` mode, the pipeline keeps listing every folder partition, so new changes are detected sooner at the cost of more `ListObjectsV2` requests. Default is `idle_optimized`. +`empty_scan_delay` | No | Duration | The minimum amount of time to wait before listing an S3 buffer folder partition again after a listing returns no objects. A longer delay reduces the number of S3 `ListObjectsV2` requests when the database receives changes infrequently but can delay the processing of new changes by up to the configured amount. Must be between 0 seconds and 30 minutes. Default is `0s`, which lists an empty folder partition again without waiting. +`joins` | No | Object | The configuration for combining rows from related tables into a single OpenSearch document. See [joins](#joins) for more information. + +<!-- vale off --> +### aws +<!-- vale on --> + +Use the following options in the AWS configuration. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon RDS and Amazon S3. Defaults to `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | The external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. + +<!-- vale off --> +### authentication +<!-- vale on --> + +Use the following options for database authentication. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`username` | Yes | String | The database username for authentication. +`password` | Yes | String | The database password for authentication. + +<!-- vale off --> +### tables +<!-- vale on --> + +Use the following options to specify which tables to include in the data capture. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`include` | No | List | A list of table names to include in data capture. Maximum of 1,000 tables. If specified, only these tables will be processed. +`exclude` | No | List | A list of table names to exclude from data capture. Maximum of 1,000 tables. These tables will be ignored even if they match include patterns. + +<!-- vale off --> +### export options +<!-- vale on --> + +The following options let you customize the RDS export functionality. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`kms_key_id` | Yes | String | The AWS Key Management Service (AWS KMS) key ID or Amazon Resource Name (ARN) to use for encrypting the export data. +`export_role_arn` | Yes | String | The ARN of the IAM role that RDS will assume to perform the export operation. + +<!-- vale off --> +### tls options +<!-- vale on --> + +The following options let you configure TLS for database connections. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`insecure` | No | Boolean | Whether to disable TLS encryption for database connections. Default is `false` (TLS enabled). + +<!-- vale off --> +### joins +<!-- vale on --> + +Use the `joins` configuration to combine each parent table row and its related child table rows into one OpenSearch document. When `joins` is configured, Data Prepper updates the `opensearch` sink to use the `upsert` action with a script that merges events from the parent and child tables. The document ID is the value of the parent key. Parent and child table names are specified without the database name. + +Changes to a parent row update the fields of its document, and deleting a parent row deletes the document. Child rows are added to the document as follows: + +- For `one_to_many` relations, each child row is stored as an object in an array field named after the child table. +- For `one_to_one` relations, the child row's fields are added to the root of the document. + +The following options are available in the `joins` configuration. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`relations` | No | List | A list of parent-child table relations. See [relations](#relations) for more information. +`version_field` | No | String | The name of the document field that stores the latest version applied to the document from each table. Data Prepper uses this field to skip events that are older than the stored version. Default is `__versions`. + +<!-- vale off --> +#### relations +<!-- vale on --> + +Use the following options in each entry of the `relations` list. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`parent` | Yes | String | The name of the parent table. +`child` | Yes | String | The name of the child table. +`parent_key` | Yes | String or list | The column or columns in the parent table that identify the parent row. The parent key value is used as the document ID. For composite keys, values are concatenated using a `\|` separator. +`child_key` | Yes | String or list | The column or columns in the child table that reference the parent row. Must contain the same number of columns as `parent_key`. +`child_primary_key` | Yes | String or list | The primary key column or columns of the child table. Used to identify each child row in the document. +`join_type` | No | String | The type of relation between the parent and child tables. Valid values are `one_to_many` and `one_to_one`. Default is `one_to_many`. +`max_child_records` | No | Integer | The maximum number of child rows stored in the array of a `one_to_many` relation. When a new child row exceeds this limit, the oldest child row is removed from the array. Default is `1000`. + +The following example combines rows from the `order_items` table into the `orders` documents: + +```yaml +rds-pipeline: + source: + rds: + db_identifier: "my-rds-instance" + engine: "aurora-mysql" + database: "mydb" + ... + joins: + relations: + - parent: "orders" + child: "order_items" + parent_key: "order_id" + child_key: "order_id" + child_primary_key: "item_id" + join_type: "one_to_many" + max_child_records: 500 +``` + +## Exposed metadata attributes + +The following metadata will be added to each event that is processed by the `rds` source. These metadata attributes can be accessed using the [expression syntax `getMetadata` function]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-metadata/). + +* `primary_key`: The primary key of the database record. For tables with composite primary keys, values are concatenated with a `|` separator. +* `event_timestamp`: The timestamp, in epoch milliseconds, of when the database change occurred. For export events, this represents the export time. For stream events, this represents the transaction commit time. +* `document_version`: A long integer number generated from the event timestamp to use as the document version. +* `opensearch_action`: The bulk action that will be used to send the event to OpenSearch, such as `index` or `delete`. +* `change_event_type`: The stream event type. Can be `insert`, `update`, or `delete`. +* `table_name`: The name of the database table from which the event originated. +* `schema_name`: The name of the schema from which the event originated. For MySQL, `schema_name` is the same as `database_name`. +* `database_name`: The name of the database from which the event originated. +* `ingestion_type`: Indicates whether the event originated from an export or stream. Valid values are `EXPORT` and `STREAM`. +* `s3_partition_key`: Events are stored in an S3 staging bucket before processing. This metadata indicates the location in the S3 bucket where the event is stored before processing. + +## Permissions + +The following are the required permissions for running RDS as a source: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "allowReadingFromS3Buckets", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:DeleteObject", + "s3:GetBucketLocation", + "s3:ListBucket", + "s3:PutObject" + ], + "Resource": [ + "arn:aws:s3:::s3_bucket", + "arn:aws:s3:::s3_bucket/*" + ] + }, + { + "Sid": "AllowDescribeInstances", + "Effect": "Allow", + "Action": [ + "rds:DescribeDBInstances" + ], + "Resource": [ + "arn:aws:rds:region:account-id:db:*" + ] + }, + { + "Sid": "AllowDescribeClusters", + "Effect": "Allow", + "Action": [ + "rds:DescribeDBClusters" + ], + "Resource": [ + "arn:aws:rds:region:account-id:cluster:*" + ] + }, + { + "Sid": "AllowSnapshots", + "Effect": "Allow", + "Action": [ + "rds:DescribeDBClusterSnapshots", + "rds:CreateDBClusterSnapshot", + "rds:DescribeDBSnapshots", + "rds:CreateDBSnapshot", + "rds:AddTagsToResource" + ], + "Resource": [ + "arn:aws:rds:region:account-id:cluster:*", + "arn:aws:rds:region:account-id:cluster-snapshot:*", + "arn:aws:rds:region:account-id:db:*", + "arn:aws:rds:region:account-id:snapshot:*" + ] + }, + { + "Sid": "AllowExport", + "Effect": "Allow", + "Action": [ + "rds:StartExportTask" + ], + "Resource": [ + "arn:aws:rds:region:account-id:cluster:*", + "arn:aws:rds:region:account-id:cluster-snapshot:*", + "arn:aws:rds:region:account-id:snapshot:*" + ] + }, + { + "Sid": "AllowDescribeExports", + "Effect": "Allow", + "Action": [ + "rds:DescribeExportTasks" + ], + "Resource": "*" + }, + { + "Sid": "AllowAccessToKmsForExport", + "Effect": "Allow", + "Action": [ + "kms:Decrypt", + "kms:Encrypt", + "kms:DescribeKey", + "kms:RetireGrant", + "kms:CreateGrant", + "kms:ReEncrypt*", + "kms:GenerateDataKey*" + ], + "Resource": [ + "arn:aws:kms:region:account-id:key/export-key-id" + ] + }, + { + "Sid": "AllowPassingExportRole", + "Effect": "Allow", + "Action": "iam:PassRole", + "Resource": [ + "arn:aws:iam::account-id:role/export-role" + ] + } + ] +} +``` + +## Metrics + +The `rds` source includes the following metrics: + +* `exportJobSuccess`: The number of RDS export tasks that have succeeded. +* `exportJobFailure`: The number of RDS export tasks that have failed. +* `exportS3ObjectsTotal`: The total number of export data files found in S3. +* `exportS3ObjectsProcessed`: The total number of export data files that have been processed successfully from S3. +* `exportS3ObjectsErrors`: The total number of export data files that have failed to be processed from S3. +* `exportRecordsTotal`: The total number of records found in the export. +* `exportRecordsProcessed`: The total number of export records that have been processed successfully. +* `exportRecordsProcessingErrors`: The number of export record processing errors. +* `changeEventsProcessed`: The number of change events processed from database streams. +* `changeEventsProcessingErrors`: The number of processing errors for change events from database streams. +* `bytesReceived`: The total number of bytes received by the source. +* `bytesProcessed`: The total number of bytes processed by the source. +* `positiveAcknowledgementSets`: The number of acknowledgment sets that are positively acknowledged in stream processing. +* `negativeAcknowledgementSets`: The number of acknowledgment sets that are negatively acknowledged in stream processing. +* `checkpointCount`: The total number of checkpoints in stream processing. +* `noDataExtendLeaseCount`: The number of times that the lease is extended on a partition with no new data processed since the last checkpoint. +* `giveupPartitionCount`: The number of times a partition is given up. +* `replicationLogEntryProcessingTime`: The time taken to process a replication log event. +* `replicationLogEntryProcessingErrors`: The number of replication log events that have failed to process. diff --git a/_data-prepper/pipelines/configuration/sources/rss.md b/_data-prepper/pipelines/configuration/sources/rss.md new file mode 100644 index 00000000..f3185579 --- /dev/null +++ b/_data-prepper/pipelines/configuration/sources/rss.md @@ -0,0 +1,126 @@ +--- +layout: default +title: RSS +parent: Sources +grand_parent: Pipelines +nav_order: 97 +--- + +# RSS source + +The `rss` source polls one or more RSS or Atom feeds and converts their items into OpenSearch Data Prepper events. Each feed is polled on a schedule, and new items are written to the [`buffer`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/buffers/). + +Each feed keeps a bounded in-memory cache of recently seen items, so already ingested items are not re-emitted on subsequent polls. This cache is not persisted, so it resets when Data Prepper restarts. + +## Usage + +Provide one or more feeds under the `feeds` map, which is keyed by feed name. Each feed requires a `url` and can optionally set a per-feed `polling_frequency` and `authentication`. The following example pipeline specifies an `rss` source that polls three feeds. Enclose the `password` value in quotation marks when it contains characters that YAML treats as syntax, such as `:` or `#`: + +```yaml +rss-pipeline: + source: + rss: + workers: 2 + polling_frequency: PT5M + feeds: + opensearch-forum: + url: https://forum.opensearch.org/latest.rss + example-news: + url: https://api.example.com/v2/rss?partnerKey=abc123 + polling_frequency: PT1M + internal: + url: https://private.example.com/feed.xml + authentication: + basic: + username: my-username + password: "p@ss:w0rd#123!" +``` +{% include copy.html %} + +You can avoid storing plaintext credentials in your pipeline configuration by referencing them from a configured secret store. To use AWS Secrets Manager as a secret store, configure the [`aws` extension]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#aws-extension-plugin). Then specify `{% raw %}${{aws_secrets:<secret-config-id>:<key>}}{% endraw %}` as the `password` value. Data Prepper resolves the reference at startup. For more information, see [Reference secrets]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#reference-secrets). + +## Configuration options + +Use the following options to configure the `rss` source. All duration values support ISO 8601 notation (such as `PT15M` or `PT20.345S`) and simple notation for seconds (`60s`) and milliseconds (`1500ms`). + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`feeds` | Yes | Map | A non-empty map of feeds to poll. Each key is the feed name, which is attached to events as `feed_name` and can be used for index routing. Feed names must be 1--64 characters long and can contain only letters, digits, underscores, and hyphens. Each value is a feed configuration. For more information, see [Feed options](#feed-options). +`polling_frequency` | No | Duration | The default polling frequency for feeds that do not set their own. Must be at least 1 second. Default is `PT5M` (5 minutes). +`workers` | No | Integer | The size of the polling thread pool. Must be between 1 and 1,000. The pool never contains more threads than the number of configured feeds. Default is `1`. +`request_timeout` | No | Duration | The connection, request, and read timeout applied to each feed fetch. This timeout prevents a slow or unresponsive feed from blocking its worker thread indefinitely. Default is `PT30S` (30 seconds). + +### Feed options + +Use the following options for each entry in the `feeds` map. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`url` | Yes | String | The RSS or Atom feed URL to read from. +`polling_frequency` | No | Duration | Overrides the top-level `polling_frequency` for this feed. Must be at least 1 second. +`authentication` | No | Object | The authentication configuration for the feed. For more information, see [Authentication](#authentication). + +### Authentication + +Use the following option in a feed's `authentication` object to configure HTTP basic authentication. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`basic` | No | Object | The HTTP basic authentication credentials. Contains a `username` and a `password`, both of which are required when `basic` is specified. + +## Event schema + +The source emits each item as an event of type `rss-item` that contains the following top-level body fields. + +Field | Description +:--- | :--- +`title` | The item title. +`link` | The item link. +`description` | The item description or summary. +`publication_date` | The item publication date. +`item_id` | The item's globally unique identifier (GUID). If the item has no GUID, the source uses the `link` value. If both are absent, the source uses a content hash. This field is always non-empty. +`feed_name` | The feed's key from the `feeds` map. This field is always present. +`feed_url` | The configured feed URL with its query string redacted. This field is always present. + +When a feed provides the following feed channel details, the source attaches them as event metadata rather than storing them in the document body. + +Metadata attribute | Description +:--- | :--- +`feed_title` | The feed channel's `<title>`. +`feed_link` | The feed channel's `<link>` (the publisher's site). +`feed_language` | The feed channel's `<language>`. +`feed_categories` | The feed channel's `<category>` values. + +Because `feed_name` and `feed_url` are body fields, they are searchable and can be used directly for per-feed routing at the sink. Use `item_id` as the `document_id` at the sink so that a republished item updates the existing document, as shown in the following example: + +```yaml +sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: "rss-${/feed_name}-%{yyyy.MM.dd}" + document_id: "${/item_id}" +``` +{% include copy.html %} + +Do not configure the sink to depend on a channel metadata attribute, because the attribute is absent when the feed does not provide it. Use the always present `feed_name`, `feed_url`, and `item_id` body fields for routing and document IDs. + +## Failure handling + +Feeds are polled independently. When a feed fails, the source logs the failure with the query string redacted from the feed URL, increments the `feedPollsFailed` metric for that feed, and backs off exponentially before retrying. A failure in one feed does not stop the other feeds or permanently stop polling. + +## Metrics + +The `rss` source includes the following metrics (counters). Each metric is recorded separately for every feed, with the feed name appended to the metric name: + +* `feedPollsFailed.<feed-name>`: The number of polls that have failed for the feed. +* `itemsIngested.<feed-name>`: The number of items the source has written to the buffer for the feed. + + +## Limitations + +The following capabilities are not yet supported: + +- Bearer token authentication +- Custom header authentication +- Deduplication across restarts and nodes using source coordination +- End-to-end acknowledgments \ No newline at end of file diff --git a/_data-prepper/pipelines/configuration/sources/s3.md b/_data-prepper/pipelines/configuration/sources/s3.md index 7dc31caa..0ca79cf2 100644 --- a/_data-prepper/pipelines/configuration/sources/s3.md +++ b/_data-prepper/pipelines/configuration/sources/s3.md @@ -1,14 +1,17 @@ --- layout: default -title: s3 source +title: S3 parent: Sources grand_parent: Pipelines -nav_order: 20 +nav_order: 100 --- -# s3 source +# S3 source -`s3` is a source plugin that reads events from [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) objects. It requires an [Amazon Simple Queue Service (Amazon SQS)](https://aws.amazon.com/sqs/) queue that receives [S3 Event Notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/NotificationHowTo.html). After Amazon SQS is configured, the `s3` source receives messages from Amazon SQS. When the SQS message indicates that an S3 object was created, the `s3` source loads the S3 objects and then parses them using the configured [codec](#codec). You can also configure the `s3` source to use [Amazon S3 Select](https://docs.aws.amazon.com/AmazonS3/latest/userguide/selecting-content-from-objects.html) instead of Data Prepper to parse S3 objects. +`s3` is a source plugin that reads events from [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) objects. You can configure the source to either use an [Amazon Simple Queue Service (Amazon SQS)](https://aws.amazon.com/sqs/) queue or scan an S3 bucket: + +- To use Amazon SQS notifications, configure S3 event notifications on your S3 bucket. After Amazon SQS is configured, the `s3` source receives messages from Amazon SQS. When the SQS message indicates that an S3 object has been created, the `s3` source loads the S3 objects and then parses them using the configured [codec](#codec). +- To use an S3 bucket, configure the `s3` source to use Amazon S3 Select instead of OpenSearch Data Prepper to parse S3 objects. ## IAM permissions @@ -80,51 +83,68 @@ You can use both `bucket_owners` and `default_bucket_owner` together. ## Configuration -You can use the following options to configure the `s3` source. +You can use the following parameters to configure the `s3` source. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `notification_type` | Yes | String | Must be `sqs`. `notification_source` | No | String | Determines how notifications are received by SQS. Must be `s3` or `eventbridge`. `s3` represents notifications that are directly sent from Amazon S3 to Amazon SQS or fanout notifications from Amazon S3 to Amazon Simple Notification Service (Amazon SNS) to Amazon SQS. `eventbridge` represents notifications from [Amazon EventBridge](https://aws.amazon.com/eventbridge/) and [Amazon Security Lake](https://aws.amazon.com/security-lake/). Default is `s3`. -`compression` | No | String | The compression algorithm to apply: `none`, `gzip`, or `automatic`. Default is `none`. +`compression` | No | String | The compression algorithm to apply: `none`, `gzip`, `snappy`, or `automatic`. Default is `none`. `codec` | Yes | Codec | The [codec](#codec) to apply. -`sqs` | Yes | SQS | The SQS configuration. See [sqs](#sqs) for more information. -`aws` | Yes | AWS | The AWS configuration. See [aws](#aws) for more information. +`sqs` | Yes | SQS | The SQS configuration. See [`sqs`](#sqs) for more information. +`aws` | Yes | AWS | The AWS configuration. See [`aws`](#aws) for more information. `on_error` | No | String | Determines how to handle errors in Amazon SQS. Can be either `retain_messages` or `delete_messages`. `retain_messages` leaves the message in the Amazon SQS queue and tries to send the message again. This is recommended for dead-letter queues. `delete_messages` deletes failed messages. Default is `retain_messages`. -buffer_timeout | No | Duration | The amount of time allowed for writing events to the Data Prepper buffer before timeout occurs. Any events that the Amazon S3 source cannot write to the buffer during the set amount of time are discarded. Default is `10s`. +`buffer_timeout` | No | Duration | The amount of time allowed for writing events to the Data Prepper buffer before timeout occurs. Any events that the Amazon S3 source cannot write to the buffer during the specified amount of time are discarded. Default is `10s`. `records_to_accumulate` | No | Integer | The number of messages that accumulate before being written to the buffer. Default is `100`. `metadata_root_key` | No | String | The base key for adding S3 metadata to each event. The metadata includes the key and bucket for each S3 object. Default is `s3/`. +`default_bucket_owner` | No | String | The AWS account ID for the owner of an S3 bucket. For more information, see [Cross-account S3 access](#s3_bucket_ownership). +`bucket_owners` | No | Map | A map of bucket names that includes the IDs of the accounts that own the buckets. For more information, see [Cross-account S3 access](#s3_bucket_ownership). `disable_bucket_ownership_validation` | No | Boolean | When `true`, the S3 source does not attempt to validate that the bucket is owned by the expected account. The expected account is the same account that owns the Amazon SQS queue. Default is `false`. -`acknowledgments` | No | Boolean | When `true`, enables `s3` sources to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. +`acknowledgments` | No | Boolean | When `true`, enables `s3` sources to receive [end-to-end acknowledgments]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `false`. `s3_select` | No | [s3_select](#s3_select) | The Amazon S3 Select configuration. `scan` | No | [scan](#scan) | The S3 scan configuration. `delete_s3_objects_on_read` | No | Boolean | When `true`, the S3 scan attempts to delete S3 objects after all events from the S3 object are successfully acknowledged by all sinks. `acknowledgments` should be enabled when deleting S3 objects. Default is `false`. +`workers` | No | Integer | Configures the number of worker threads (1--1,000) that the source uses to read data from S3. Leave this value as the default unless your S3 objects are less than 1 MB in size. Performance may decrease for larger S3 objects. This setting affects SQS-based sources and S3-Scan sources. Default is `1`. +`disable_s3_metadata_in_event` | No | Boolean | When `true`, the source does not add the S3 bucket and key fields (under `metadata_root_key`) to events. Default is `false`. +`data_selection` | No | String | Determines which data the source reads from S3 objects received through Amazon SQS notifications. Valid values are `data_and_metadata`, `data_only`, and `metadata_only`. The `data_and_metadata` value parses the object using the configured codec and adds the S3 bucket and key fields to each event. The `data_only` value parses the object without adding the bucket and key fields. The `metadata_only` value does not parse the object and creates one event per object containing the `bucket`, `key`, `time` (last modified time), and `length` fields. Default is `data_and_metadata`. +`filters` | No | Map | A map of S3 bucket names to key filters. Each filter can contain an `include_prefix` list and an `exclude_suffix` list, which work like those in the scan [filter](#filter). Applies to objects received through Amazon SQS notifications and objects found by S3 scan. For Amazon SQS, messages for objects that do not match the filter are deleted without processing the objects. Cannot be used together with a bucket-level `filter` in the `scan` configuration. +`backoff_time` | No | Duration | The amount of time that each S3 scan worker waits before checking again when no objects are available to process. Default is `30s`. + +<!-- vale off --> ## sqs +<!-- vale on --> The following parameters allow you to configure usage for Amazon SQS in the `s3` source plugin. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `queue_url` | Yes | String | The URL of the Amazon SQS queue from which messages are received. `maximum_messages` | No | Integer | The maximum number of messages to receive from the Amazon SQS queue in any single request. Default is `10`. -`visibility_timeout` | No | Duration | The visibility timeout to apply to messages read from the Amazon SQS queue. This should be set to the amount of time that Data Prepper may take to read all the S3 objects in a batch. Default is `30s`. +`visibility_timeout` | No | Duration | The visibility timeout to apply to messages read from the Amazon SQS queue. This parameter should be set to the amount of time that Data Prepper may take to read all the S3 objects in a batch. If processing exceeds this timeout and `visibility_duplication_protection` is not enabled, the message becomes visible in the queue again and may be reprocessed, which can create duplicate data in the sink. The maximum value is 12 hours (`43200s`). Default is `30s`. `wait_time` | No | Duration | The amount of time to wait for long polling on the Amazon SQS API. Default is `20s`. `poll_delay` | No | Duration | A delay placed between the reading and processing of a batch of Amazon SQS messages and making a subsequent request. Default is `0s`. -`visibility_duplication_protection` | No | Boolean | If set to `true`, Data Prepper attempts to avoid duplicate processing by extending the visibility timeout of SQS messages. Until the data reaches the sink, Data Prepper will regularly call `ChangeMessageVisibility` to avoid reading the S3 object again. To use this feature, you need to grant permissions to `ChangeMessageVisibility` on the IAM role. Default is `false`. -`visibility_duplicate_protection_timeout` | No | Duration | Sets the maximum total length of time that a message will not be processed when using `visibility_duplication_protection`. Defaults to two hours. +`visibility_duplication_protection` | No | Boolean | If set to `true`, Data Prepper attempts to avoid duplicate processing by extending the visibility timeout of SQS messages. Until the data reaches the sink, Data Prepper regularly calls `ChangeMessageVisibility` to avoid rereading the S3 object. This option takes effect only when `acknowledgments` is enabled on the `s3` source, because the visibility timeout is extended through end-to-end acknowledgments. When `acknowledgments` is not enabled, the visibility timeout is not extended even if this option is set to `true`. To use this feature, you must grant permissions to `sqs:ChangeMessageVisibility` on the IAM role. Default is `false`. +`visibility_duplicate_protection_timeout` | No | Duration | Sets the maximum total length of time that a message will not be processed when using `visibility_duplication_protection`. The minimum value is `30s` and the maximum value is 24 hours (`86400s`). Default is 2 hours (`7200s`). +`max_receive_attempts` | No | Integer | The maximum number of times a message can be received from the queue before it is automatically deleted. When a message has been received more than this number of times, Data Prepper deletes it from the queue. This helps prevent repeatedly failing messages from blocking the queue. Minimum value is `1`. When this option is configured, the `sqsMessageDelay` metric is not recorded for messages that have been received more than once. Disabled by default. +`shutdown_timeout` | No | Duration | The amount of time to wait for Amazon SQS workers to finish when the source stops. Minimum is `30s`. Default is `30s`. +<!-- vale off --> ## aws +<!-- vale on --> -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). `sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon SQS and Amazon S3. Defaults to `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). -`aws_sts_header_overrides` | No | Map | A map of header overrides that the IAM role assumes for the sink plugin. +`sts_header_overrides` | No | Map | A map of header overrides that the IAM role assumes for the source plugin. Maximum of 5 headers. +`sts_external_id` | No | String | An STS external ID used when Data Prepper assumes the STS role. For more information, see the `ExternalID` documentation in the [STS AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API reference. +<!-- vale off --> ## codec +<!-- vale on --> The `codec` determines how the `s3` source parses each Amazon S3 object. For increased and more efficient performance, you can use [codec combinations]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/codec-processor-combinations/) with certain processors. @@ -132,103 +152,184 @@ The `codec` determines how the `s3` source parses each Amazon S3 object. For inc The `newline` codec parses each single line as a single log event. This is ideal for most application logs because each event parses per single line. It can also be suitable for S3 objects that have individual JSON objects on each line, which matches well when used with the [parse_json]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/parse-json/) processor to parse each line. -Use the following options to configure the `newline` codec. +Use the following parameters to configure the `newline` codec. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- |:--------| :--- `skip_lines` | No | Integer | The number of lines to skip before creating events. You can use this configuration to skip common header rows. Default is `0`. -`header_destination` | No | String | A key value to assign to the header line of the S3 object. If this option is specified, then each event will contain a `header_destination` field. +`header_destination` | No | String | A key value to assign to the header line of the S3 object. If this parameter is specified, then each event will contain a `header_destination` field. +<!-- vale off --> ### json codec +<!-- vale on --> -The `json` codec parses each S3 object as a single JSON object from a JSON array and then creates a Data Prepper log event for each object in the array. +The `json` codec parses each S3 object as a single JSON object from a JSON array and then creates a Data Prepper log event for each object in the array. +Use the following parameters to configure the `json` codec. + +Parameter | Required | Type | Description +:--- | :--- |:--------| :--- +`key_name` | No | String | The name of the input field from which to extract the JSON array and create events. + +<!-- vale off --> ### csv codec +<!-- vale on --> -The `csv` codec parses objects in comma-separated value (CSV) format, with each row producing a Data Prepper log event. Use the following options to configure the `csv` codec. +The `csv` codec parses objects in comma-separated value (CSV) format, with each row producing a Data Prepper log event. -Option | Required | Type | Description +Use the following parameters to configure the `csv` codec. + +Parameters | Required | Type | Description :--- |:---------|:------------| :--- `delimiter` | Yes | Integer | The delimiter separating columns. Default is `,`. `quote_character` | Yes | String | The character used as a text qualifier for CSV data. Default is `"`. `header` | No | String list | The header containing the column names used to parse CSV data. `detect_header` | No | Boolean | Whether the first line of the Amazon S3 object should be interpreted as a header. Default is `true`. +### `otel_traces` codec +The `otel_traces` codec parses each S3 object as an OpenTelemetry trace record and creates a Data Prepper span event for each span record. +Use the following parameters to configure the `otel_traces` codec. + +Parameter | Required | Type | Description +:--- | :--- |:--------| :--- +`format` | No | String | Specifies the format of the OpenTelemetry traces. Valid values are `json` and `protobuf`. Default is `json`. +`otel_format` | No | String | Specifies the output format of the decoded spans. Valid values are `opensearch` and `otel`. Default is `opensearch`. +`length_prefixed_encoding` | No | Boolean | Specifies whether the length precedes the data in protobuf format. Default is `false`. ## Using `s3_select` with the `s3` source<a name="s3_select"></a> -When configuring `s3_select` to parse Amazon S3 objects, use the following options: +When configuring `s3_select` to parse S3 objects, use the following parameters. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- |:-----------------------|:------------| :--- `expression` | Yes, when using `s3_select` | String | The expression used to query the object. Maps directly to the [expression](https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html#AmazonS3-SelectObjectContent-request-Expression) property. `expression_type` | No | String | The type of the provided expression. Default value is `SQL`. Maps directly to the [ExpressionType](https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html#AmazonS3-SelectObjectContent-request-ExpressionType). `input_serialization` | Yes, when using `s3_select` | String | Provides the S3 Select file format. Amazon S3 uses this format to parse object data into records and returns only records that match the specified SQL expression. May be `csv`, `json`, or `parquet`. `compression_type` | No | String | Specifies an object's compression format. Maps directly to the [CompressionType](https://docs.aws.amazon.com/AmazonS3/latest/API/API_InputSerialization.html#AmazonS3-Type-InputSerialization-CompressionType). -`csv` | No | [csv](#s3_select_csv) | Provides the CSV configuration for processing CSV data. -`json` | No | [json](#s3_select_json) | Provides the JSON configuration for processing JSON data. +`csv` | No | [`csv`](#s3_select_csv) | Provides the CSV configuration for processing CSV data. +`json` | No | [`json`](#s3_select_json) | Provides the JSON configuration for processing JSON data. +<!-- vale off --> ### csv<a name="s3_select_csv"></a> +<!-- vale on --> -Use the following options in conjunction with the `csv` configuration for `s3_select` to determine how your parsed CSV file should be formatted. +Use the following parameters in conjunction with the `csv` configuration for `s3_select` to determine how your parsed CSV file should be formatted. -These options map directly to options available in the S3 Select [CSVInput](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CSVInput.html) data type. +These parameters map directly to inputs available in the S3 Select [`CSVInput`](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CSVInput.html) data type. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- |:---------|:------------| :--- `file_header_info` | No | String | Describes the first line of input. Maps directly to the [FileHeaderInfo](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CSVInput.html#AmazonS3-Type-CSVInput-FileHeaderInfo) property. `quote_escape` | No | String | A single character used for escaping the quotation mark character inside an already escaped value. Maps directly to the [QuoteEscapeCharacter](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CSVInput.html#AmazonS3-Type-CSVInput-QuoteEscapeCharacter) property. `comments` | No | String | A single character used to indicate that a row should be ignored when the character is present at the start of that row. Maps directly to the [Comments](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CSVInput.html#AmazonS3-Type-CSVInput-Comments) property. +<!-- vale off --> #### json<a name="s3_select_json"></a> +<!-- vale on --> -Use the following option in conjunction with `json` for `s3_select` to determine how S3 Select processes the JSON file. +Use the following parameters in conjunction with `json` for `s3_select` to determine how S3 Select processes the JSON file. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `type` | No | String | The type of JSON array. May be either `DOCUMENT` or `LINES`. Maps directly to the [Type](https://docs.aws.amazon.com/AmazonS3/latest/API/API_JSONInput.html#AmazonS3-Type-JSONInput-Type) property. ## Using `scan` with the `s3` source<a name="scan"></a> -The following parameters allow you to scan S3 objects. All options can be configured at the bucket level. +The following parameters allow you to scan S3 objects. All parameters can be configured at the bucket level. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `start_time` | No | String | The time from which to start scanning objects modified after the given `start_time`. This should follow [ISO LocalDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) format, for example, `023-01-23T10:00:00`. If `end_time` is configured along with `start_time`, all objects after `start_time` and before `end_time` will be processed. `start_time` and `range` cannot be used together. `end_time` | No | String | The time after which no objects will be scanned after the given `end_time`. This should follow [ISO LocalDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) format, for example, `023-01-23T10:00:00`. If `start_time` is configured along with `end_time`, all objects after `start_time` and before `end_time` will be processed. `end_time` and `range` cannot be used together. `range` | No | String | The time range from which objects are scanned from all buckets. Supports ISO_8601 notation strings, such as `PT20.345S` or `PT15M`, and notation strings for seconds (`60s`) and milliseconds (`1600ms`). `start_time` and `end_time` cannot be used with `range`. Range `P12H` scans all the objects modified in the last 12 hours from the time pipeline started. -`buckets` | Yes | List | A list of [buckets](#bucket) to scan. +`buckets` | Yes | List | A list of [scan buckets](#scan-bucket) to scan. `scheduling` | No | List | The configuration for scheduling periodic scans on all buckets. `start_time`, `end_time` and `range` can not be used if scheduling is configured. +`acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read by an S3 scan expires when used with acknowledgments. Default is 2 hours (`PT2H`). +`folder_partitions` | No | [folder_partitions](#folder_partitions) | Groups the scanned objects into partitions by folder prefix so that each worker processes the objects in one folder at a time. Requires both `acknowledgments` and `delete_s3_objects_on_read` to be set to `true`. -### bucket +<!-- vale off --> +### scan bucket +<!-- vale on --> -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- |:-----| :--- -`bucket` | Yes | Map | Provides options for each bucket. +`bucket` | Yes | Map | Provides parameters for each bucket. -You can configure the following options inside the [bucket](#bucket) setting. +You can configure the following parameters in the `bucket` setting map. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `name` | Yes | String | The string representing the S3 bucket name to scan. `filter` | No | [Filter](#filter) | Provides the filter configuration. +`data_selection` | No | String | Determines which data the source reads from objects with keys that start with one of the `include_prefix` values in the bucket's `filter`. Accepts the same values as the top-level `data_selection` option. Objects that do not match an `include_prefix` value are read using `data_and_metadata`. Default is `data_and_metadata`. +`processing_conditions` | No | List | A list of conditions that must be satisfied before an S3 object is processed. Each condition downloads a companion object located in the same S3 directory and evaluates a `when` expression against its content. If any condition is not met, processing of the S3 object is deferred and retried. Conditions are evaluated once per S3 object, not per record. See [processing_conditions](#processing_conditions). `start_time` | No | String | The time from which to start scanning objects modified after the given `start_time`. This should follow [ISO LocalDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) format, for example, `023-01-23T10:00:00`. If `end_time` is configured along with `start_time`, all objects after `start_time` and before `end_time` will be processed. `start_time` and `range` cannot be used together. This will overwrites the `start_time` at the [scan](#scan) level. `end_time` | No | String | The time after which no objects will be scanned after the given `end_time`. This should follow [ISO LocalDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) format, for example, `023-01-23T10:00:00`. If `start_time` is configured along with `end_time`, all objects after `start_time` and before `end_time` will be processed. This overwrites the `end_time` at the [scan](#scan) level. `range` | No | String | The time range from which objects are scanned from all buckets. Supports ISO_8601 notation strings, such as `PT20.345S` or `PT15M`, and notation strings for seconds (`60s`) and milliseconds (`1600ms`). `start_time` and `end_time` cannot be used with `range`. Range `P12H` scans all the objects modified in the last 12 hours from the time pipeline started. This overwrites the `range` at the [scan](#scan) level. +<!-- vale off --> ### filter +<!-- vale on --> -Use the following options inside the `filter` configuration. +Use the following parameters in the `filter` configuration. -Option | Required | Type | Description +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `include_prefix` | No | List | A list of S3 key prefix strings included in the scan. By default, all the objects in a bucket are included. `exclude_suffix` | No | List | A list of S3 key suffix strings excluded from the scan. By default, no objects in a bucket are excluded. -### scheduling +<!-- vale off --> +### processing_conditions +<!-- vale on --> -Option | Required | Type | Description +Use the following parameters in each `processing_conditions` entry. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`object_name` | Yes | String | The name of the companion object (for example, `_SUCCESS` or `manifest.json`) located in the same S3 directory as the data object. The companion object is downloaded and evaluated against the `when` expression. +`when` | Yes | String | A Data Prepper expression that is evaluated against the content of the companion object. The S3 data object is processed only when this expression evaluates to `true`. For example, `/status == "complete"`. +`applicable_prefix` | No | List | A list of S3 key prefix strings. The condition is evaluated only for objects whose keys start with at least one of these prefixes. When omitted, the condition applies to all objects in the bucket. +`retry_delay` | No | String | The duration to wait before rechecking the condition when it is not met. Supports ISO 8601 duration format (for example, `PT5M`). Minimum is `PT1M`, maximum is `PT60M`. Default is `PT5M`. +`max_retry` | No | Integer | The maximum number of times to recheck the condition before processing the object regardless of the result. Accepts values from `0` to `100`. Default is `10`. When this limit is reached, the object is processed as-is. +`codec` | No | Codec | A codec plugin used to parse the companion object. When configured, the `when` expression is evaluated against the first record parsed by the `codec`. When omitted, the companion object is parsed as a flat JSON document. + +The following example configures `processing_conditions` at the bucket level: + +```yaml +- bucket: + name: batchinference + data_selection: data_only + processing_conditions: + - object_name: "manifest.json.out" + when: "/processedRecordCount == /totalRecordCount" + codec: + ndjson: + applicable_prefix: + - "bedrock-batch-job/output/" + retry_delay: PT2M + max_retry: 3 +``` +{% include copy.html %} + +<!-- vale off --> +### folder_partitions +<!-- vale on --> + +Use the following parameters in the `folder_partitions` configuration. + +Parameter | Required | Type | Description +:--- | :--- | :--- | :--- +`depth` | No | Integer | The number of folder levels in the object key that determine the partition. For example, with a `depth` of `2`, the object `logs/2026/01/file.json` belongs to the `logs/2026/` partition. Objects whose keys contain fewer folder levels than `depth` are not processed. Default is `1`. +`max_objects_per_ownership` | No | Integer | The maximum number of objects that a worker processes from a folder partition each time it acquires the partition. Default is `50`. +`idle_scan_mode` | No | String | Determines whether the source continues to list folder partitions in which no new objects are found. Valid values are `idle_optimized` and `continuous`. In `idle_optimized` mode, a folder partition in which no objects are found for 1 hour is removed and is not listed again until a later bucket scan finds new objects in that folder. This reduces the number of S3 `ListObjectsV2` requests while the bucket is idle, but new objects in a removed folder are not detected until the next bucket scan. In `continuous` mode, folder partitions are never removed, so workers keep listing every folder and detect new objects sooner at the cost of more `ListObjectsV2` requests. Default is `idle_optimized`. +`empty_folder_rescan_delay` | No | Duration | The minimum amount of time to wait before listing a folder partition again after a listing returns no objects. During this time, the worker keeps ownership of the folder partition so that no other worker lists it. A longer delay reduces the number of `ListObjectsV2` requests for folders that receive objects infrequently but can delay the processing of new objects in those folders by up to the configured amount. Must be between 0 seconds and 30 minutes. Default is `0s`, which lists an empty folder partition again without waiting. + +<!-- vale off --> +### scheduling +<!-- vale on --> + +Parameter | Required | Type | Description :--- | :--- | :--- | :--- `interval` | Yes | String | Indicates the minimum interval between each scan. The next scan in the interval will start after the interval duration from the last scan ends and when all the objects from the previous scan are processed. Supports ISO 8601 notation strings, such as `PT20.345S` or `PT15M`, and notation strings for seconds (`60s`) and milliseconds (`1600ms`). `count` | No | Integer | Specifies how many times a bucket will be scanned. Defaults to `Integer.MAX_VALUE`. @@ -244,13 +345,17 @@ The `s3` source includes the following metrics: * `s3ObjectsNotFound`: The number of S3 objects that the `s3` source failed to read due to an S3 "Not Found" error. These are also counted toward `s3ObjectsFailed`. * `s3ObjectsAccessDenied`: The number of S3 objects that the `s3` source failed to read due to an "Access Denied" or "Forbidden" error. These are also counted toward `s3ObjectsFailed`. * `s3ObjectsSucceeded`: The number of S3 objects that the `s3` source successfully read. +* `s3ObjectNoRecordsFound`: The number of S3 objects that resulted in 0 records being added to the buffer by the `s3` source. +* `s3ObjectsDeleted`: The number of S3 objects deleted by the `s3` source. +* `s3ObjectsDeleteFailed`: The number of S3 objects that the `s3` source failed to delete. +* `s3ObjectsEmpty`: The number of S3 objects that are considered empty because they have a size of `0`. These objects will be skipped by the `s3` source. * `sqsMessagesReceived`: The number of Amazon SQS messages received from the queue by the `s3` source. * `sqsMessagesDeleted`: The number of Amazon SQS messages deleted from the queue by the `s3` source. * `sqsMessagesFailed`: The number of Amazon SQS messages that the `s3` source failed to parse. -* `s3ObjectNoRecordsFound` -- The number of S3 objects that resulted in 0 records added to the buffer by the `s3` source. * `sqsMessagesDeleteFailed` -- The number of SQS messages that the `s3` source failed to delete from the SQS queue. -* `s3ObjectsDeleted` -- The number of S3 objects deleted by the `s3` source. -* `s3ObjectsDeleteFailed` -- The number of S3 objects that the `s3` source failed to delete. +* `sqsVisibilityTimeoutChangedCount`: The number of times that the `s3` source changed the visibility timeout for an SQS message. This includes multiple visibility timeout changes on the same message. +* `sqsVisibilityTimeoutChangeFailedCount`: The number of times that the `s3` source failed to change the visibility timeout for an SQS message. This includes multiple visibility timeout change failures on the same message. +* `acknowledgementSetCallbackCounter`: The number of times that the `s3` source received an acknowledgment from Data Prepper. ### Timers @@ -263,7 +368,9 @@ The `s3` source includes the following metrics: * `s3ObjectProcessedBytes`: Measures the bytes processed by the `s3` source for a given object. For compressed objects, this is the uncompressed size. * `s3ObjectsEvents`: Measures the number of events (sometimes called records) produced by an S3 object. +<!-- vale off --> ## Example: Uncompressed logs with sqs +<!-- vale on --> The following pipeline.yaml file shows the minimum configuration for reading uncompressed newline-delimited logs: diff --git a/_data-prepper/pipelines/configuration/sources/sources.md b/_data-prepper/pipelines/configuration/sources/sources.md index b684db56..75079daa 100644 --- a/_data-prepper/pipelines/configuration/sources/sources.md +++ b/_data-prepper/pipelines/configuration/sources/sources.md @@ -3,9 +3,13 @@ layout: default title: Sources parent: Pipelines has_children: true -nav_order: 15 +nav_order: 110 +redirect_from: + - /data-prepper/pipelines/configuration/sources/ --- -# Sources +# Data Prepper sources + +A `source` is an input component that specifies how an OpenSearch Data Prepper pipeline ingests events. Each pipeline has a single source that either receives events over HTTP(S) or reads from external endpoints, such as OpenTelemetry Collector or Amazon Simple Storage Service (Amazon S3). Sources have configurable options based on the event format (string, JSON, Amazon CloudWatch logs, OpenTelemtry traces). The source consumes events and passes them to the [`buffer`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/buffers/) component. + -Sources define where your data comes from within a Data Prepper pipeline. diff --git a/_data-prepper/pipelines/contains.md b/_data-prepper/pipelines/contains.md new file mode 100644 index 00000000..7ec15576 --- /dev/null +++ b/_data-prepper/pipelines/contains.md @@ -0,0 +1,117 @@ +--- +layout: default +title: contains() +parent: Functions +grand_parent: Pipelines +nav_order: 10 +--- + +<!-- vale off --> +# contains() function +<!-- vale on --> + +The `contains()` function is used to check if a substring exists within a given string or the value of a field in an event. It takes two arguments: + +- The first argument is either a literal string or a JSON pointer that represents the field or value to be searched. + +- The second argument is the substring to be searched for within the first argument. +The function returns `true` if the substring specified in the second argument is found within the string or field value represented by the first argument. It returns `false` if it is not. + +For example, if you want to check if the string `"abcd"` is contained within the value of a field named `message`, you can use the `contains()` function as follows: + +``` +'contains(/message, "abcd")' +``` +{% include copy.html %} + +This call returns `true` if the field `message` contains the substring `abcd` or `false` if it does not. + +Alternatively, you can use a literal string as the first argument: + +``` +'contains("This is a test message", "test")' +``` +{% include copy.html %} + +In this case, the function returns `true` because the substring `test` is present within the string `This is a test message`. + +The `contains()` function performs a case-sensitive search. +{: .note} + +## Example + +The following pipeline uses the `contains()` function to add a Boolean flag `has_test` based on a substring in `/message` and filters out non-matching events, forwarding only messages that contain the string `ERROR` to OpenSearch: + +```yaml +contains-demo-pipeline: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: has_test + value_expression: contains(/message, "test") + - drop_events: + drop_when: not contains(/message, "ERROR") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"ok hello"}, + {"message":"this has test but ok"}, + {"message":"ERROR: something bad"}, + {"message":"ERROR: unit test failed"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2025.10.21", + "_id": "5YACB5oBqZitdAAb4n3r", + "_score": 1, + "_source": { + "message": "ERROR: something bad", + "has_test": false + } + }, + { + "_index": "demo-index-2025.10.21", + "_id": "5oACB5oBqZitdAAb4n3r", + "_score": 1, + "_source": { + "message": "ERROR: unit test failed", + "has_test": true + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/dlq.md b/_data-prepper/pipelines/dlq.md index 3032536e..25f8641d 100644 --- a/_data-prepper/pipelines/dlq.md +++ b/_data-prepper/pipelines/dlq.md @@ -2,41 +2,49 @@ layout: default title: Dead-letter queues parent: Pipelines -nav_order: 13 +nav_order: 15 --- # Dead-letter queues -Data Prepper pipelines support dead-letter queues (DLQs) for offloading failed events and making them accessible for analysis. +OpenSearch Data Prepper pipelines support dead-letter queues (DLQs) for offloading failed events and making them accessible for analysis. -As of Data Prepper 2.3, only the `s3` source supports DLQs. +To use a DLQ, configure the `dlq` setting of a plugin that supports it, such as the `opensearch` sink. ## Configure a DLQ writer -To configure a DLQ writer for the `s3` source, add the following to your pipeline.yaml file: +To configure a DLQ writer for the `opensearch` sink, add the following to your `pipeline.yaml` file: ```yaml - sink: - opensearch: +sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: my-index + username: admin + password: "<custom-admin-password>" + insecure: true + dlq: s3: - bucket: "my-dlq-bucket" - key_path_prefix: "dlq-files/" - region: "us-west-2" - sts_role_arn: "arn:aws:iam::123456789012:role/dlq-role" + bucket: my-dlq-bucket + key_path_prefix: dlq-files/ + region: us-west-2 + sts_role_arn: arn:aws:iam::123456789012:role/dlq-role + bucket_owner: 123456789012 ``` -The resulting DLQ file outputs as a JSON array of DLQ objects. Any file written to the S3 DLQ contains the following name pattern: +By default, each DLQ file contains a JSON object in which the `dlqObjects` array holds the DLQ objects. When `codec` is `ndjson`, each DLQ file contains one DLQ object per line. Any file written to the `s3` DLQ contains the following name pattern: ``` -dlq-v${version}-${pipelineName}-${pluginId}-${timestampIso8601}-${uniqueId} +dlq-v${version}-${pipelineName}-${pluginId}-${timestampIso8601}-${uniqueId}.${extension} ``` + The following information is replaced in the name pattern: - - `version`: The Data Prepper version. -- `pipelineName`: The pipeline name indicated in pipeline.yaml. +- `pipelineName`: The pipeline name indicated in `pipelines.yaml`. - `pluginId`: The ID of the plugin associated with the DLQ event. +- `extension`: The value of the `codec` option, either `json` or `ndjson`. ## Configuration @@ -44,13 +52,18 @@ DLQ supports the following configuration options. Option | Required | Type | Description :--- | :--- | :--- | :--- -bucket | Yes | String | The name of the bucket into which the DLQ outputs failed records. -key_path_prefix | No | String | The `key_prefix` used in the S3 bucket. Defaults to `""`. Supports time value pattern variables, such as `/%{yyyy}/%{MM}/%{dd}`, including any variables listed in the [Java DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html). For example, when using the `/%{yyyy}/%{MM}/%{dd}` pattern, you can set `key_prefix` as `/2023/01/24`. -region | No | String | The AWS Region of the S3 bucket. Defaults to `us-east-1`. -sts_role_arn | No | String | The STS role the DLQ assumes in order to write to an AWS S3 bucket. Default is `null`, which uses the standard SDK behavior for credentials. To use this option, the S3 bucket must have the `S3:PutObject` permission configured. - -When using DLQ with an OpenSearch sink, you can configure the [max_retries]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/opensearch/#configure-max_retries) option to send failed data to the DLQ when the sink reaches the maximum number of retries. +`bucket` | Yes | String | The name of the bucket into which the DLQ outputs failed records. +`key_path_prefix` | No | String | The `key_prefix` used in the Amazon Simple Storage Service (Amazon S3) bucket. Defaults to `""`. Supports time value pattern variables, such as `/%{yyyy}/%{MM}/%{dd}`, including any variables listed in the [Java DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html). For example, when using the `/%{yyyy}/%{MM}/%{dd}` pattern, you can set `key_prefix` as `/2023/01/24`. +`region` | No | String | The AWS Region of the S3 bucket. Defaults to `us-east-1`. +`sts_role_arn` | No | String | The STS role the DLQ assumes in order to write to an AWS S3 bucket. Default is `null`, which uses the standard SDK behavior for credentials. To use this option, the S3 bucket must have the `s3:PutObject` permission configured. +`sts_external_id` | No | String | The external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | A map of headers to add to the AWS STS `AssumeRole` request. +`force_path_style` | No | Boolean | When `true`, the DLQ addresses the S3 bucket using path-style URLs (`https://s3.<region>.amazonaws.com/<bucket>/<key>`) rather than virtual-hosted-style URLs. Default is `false`. +`legacy_md5_checksum` | No | Boolean | When `true`, the DLQ sends a `Content-MD5` header with each request and calculates checksums only when the S3 operation requires them. Use this setting for S3-compatible storage that does not support the newer AWS SDK checksum algorithms. Default is `false`. +`bucket_owner` | No | String | The AWS account ID of the S3 bucket owner. When set, Data Prepper passes this value to S3 as `expectedBucketOwner`, and S3 rejects writes if it does not match the actual bucket owner. Default is `null`, which performs no explicit bucket owner check. +`codec` | No | String | The format of the DLQ files. Valid values are `json` and `ndjson`. When `json`, each file contains a JSON object in which the `dlqObjects` array holds all DLQ objects in the batch. When `ndjson`, each file contains one DLQ object per line and uses the `.ndjson` file extension. Default is `json`. +When using DLQ with an OpenSearch sink, you can configure the [`max_retries`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/opensearch/#configure-max_retries) option to send failed records to the DLQ after the sink reaches the maximum number of retry attempts. ## Metrics @@ -75,9 +88,8 @@ DLQ supports the following metrics. DLQ supports the following DLQ objects: -* `pluginId`: The ID of the plugin that originated the event sent to the DLQ. -* `pluginName`: The name of the plugin. -* `failedData` : An object that contains the failed object and its options. This object is unique to each plugin. -* `pipelineName`: The name of the Data Prepper pipeline in which the event failed. -* `timestamp`: The timestamp of the failures in an `ISO8601` format. - +- `pluginId`: The ID of the plugin that originated the event sent to the DLQ. +- `pluginName`: The name of the plugin. +- `failedData`: An object that contains the failed object and its options. This object is unique to each plugin. +- `pipelineName`: The name of the Data Prepper pipeline in which the event failed. +- `timestamp`: The timestamp of the failure in `ISO8601` format. diff --git a/_data-prepper/pipelines/expression-syntax.md b/_data-prepper/pipelines/expression-syntax.md index 8257ab89..5041189a 100644 --- a/_data-prepper/pipelines/expression-syntax.md +++ b/_data-prepper/pipelines/expression-syntax.md @@ -2,70 +2,44 @@ layout: default title: Expression syntax parent: Pipelines -nav_order: 12 +nav_order: 5 --- -# Expression syntax +# Expression syntax -The following sections provide information about expression syntax in Data Prepper. +Expressions provide flexibility in manipulating, filtering, and routing data. The following sections provide information about expression syntax in OpenSearch Data Prepper. -## Supported operators +## Key terms -Operators are listed in order of precedence (top to bottom, left to right). +The following key terms are used in the context of expressions. -| Operator | Description | Associativity | -|----------------------|-------------------------------------------------------|---------------| -| `()` | Priority Expression | left-to-right | -| `not`<br> `+`<br> `-`| Unary Logical NOT<br>Unary Positive<br>Unary negative | right-to-left | -| `<`, `<=`, `>`, `>=` | Relational Operators | left-to-right | -| `==`, `!=` | Equality Operators | left-to-right | -| `and`, `or` | Conditional Expression | left-to-right | +Term | Definition +-----|----------- +**Expression** | A generic component that contains a primary or an operator. Expressions can be nested within other expressions. An expression's imminent children can contain 0–1 operators. +**Expression string** | The highest priority in a Data Prepper expression and supports only one expression string resulting in a return value. An expression string is not the same as an expression. +**Literal** | A fundamental value that has no children. A literal can be one of the following: float, integer, Boolean, JSON pointer, string, or null. See [Literals](#literals). +**Operator** | A hardcoded token that identifies the operation used in an expression. +**Primary** | Can be one of the following: set initializer, priority expression, or literal. +**Statement** | The highest-priority component within an expression string. -## Reserved for possible future functionality +## Operators -Reserved symbol set: `^`, `*`, `/`, `%`, `+`, `-`, `xor`, `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `++`, `--`, `${<text>}` +The following table lists the supported operators. Operators are listed in order of precedence (top to bottom, left to right). -## Set initializer +| Operator | Description | Associativity | +|------------------------|-------------------------------------------------------|---------------| +| `()` | Priority expression | Left to right | +| `not`<br> `+`<br> `-` | Unary logical NOT<br>Unary positive<br>Unary negative | Right to left | +| `*`, `/`, `%` | Multiplication (`*`), division (`/`), and modulo (`%`) operators | Left to right | +| `+`, `-` | Addition and subtraction operators | Left to right | +| `+` | String concatenation operator | Left to right | +| `<`, `<=`, `>`, `>=` | Relational operators | Left to right | +| `==`, `!=` | Equality operators | Left to right | +| `and`, `or` | Conditional expression | Left to right | -The set initializer defines a set or term and/or expressions. +### Relational operators -### Examples - -The following are examples of set initializer syntax. - -#### HTTP status codes - -``` -{200, 201, 202} -``` - -#### HTTP response payloads - -``` -{"Created", "Accepted"} -``` - -#### Handle multiple event types with different keys - -``` -{/request_payload, /request_message} -``` - -## Priority expression - -A priority expression identifies an expression that will be evaluated at the highest priority level. A priority expression must contain an expression or value; empty parentheses are not supported. - -### Example - -``` -/is_cool == (/name == "Steven") -``` - -## Relational operators - -Relational operators are used to test the relationship of two numeric values. The operands must be numbers or JSON Pointers that resolve to numbers. - -### Syntax +Relational operators compare numeric values or JSON pointers that resolve to numeric values. The operators are used to test the relationship between two operands, determining if one is greater than, less than, or equal to the other. The syntax for using relational operators is as follows: ``` <Number | JSON Pointer> < <Number | JSON Pointer> @@ -73,59 +47,43 @@ Relational operators are used to test the relationship of two numeric values. Th <Number | JSON Pointer> > <Number | JSON Pointer> <Number | JSON Pointer> >= <Number | JSON Pointer> ``` +{% include copy.html %} -### Example +For example, to check if the value of the `status_code` field in an event is within the range of successful HTTP responses (200--299), you can use the following expression: ``` /status_code >= 200 and /status_code < 300 ``` +{% include copy.html %} -## Equality operators +### Equality operators -Equality operators are used to test whether two values are equivalent. +Equality operators are used to test whether two values are equivalent. These operators compare values of any type, including JSON pointers, literals, and expressions. The syntax for using equality operators is as follows: -### Syntax ``` <Any> == <Any> <Any> != <Any> ``` +{% include copy.html %} -### Examples -``` -/is_cool == true -3.14 != /status_code -{1, 2} == /event/set_property -``` -## Using equality operators to check for a JSON Pointer +The following are some example equality operators: -Equality operators can also be used to check whether a JSON Pointer exists by comparing the value with `null`. +- `/is_cool == true`: Checks if the value referenced by the JSON pointer is equal to the Boolean value. +- `3.14 != /status_code`: Checks if the numeric value is not equal to the value referenced by the JSON pointer. +- `{1, 2} == /event/set_property`: Checks if the array is equal to the value referenced by the JSON pointer. -### Syntax -``` -<JSON Pointer> == null -<JSON Pointer> != null -null == <JSON Pointer> -null != <JSON Pointer> -``` +### Conditional expressions -### Example -``` -/response == null -null != /response -``` +Conditional expressions allow you to combine multiple expressions or values using logical operators to create more complex evaluation criteria. The available conditional operators are `and`, `or`, and `not`. The syntax for using these conditional operators is as follows: -#### Conditional expression - -A conditional expression is used to chain together multiple expressions and/or values. - -#### Syntax ``` <Any> and <Any> <Any> or <Any> not <Any> ``` -### Example +The following are some example conditional expressions: + ``` /status_code == 200 and /message == "Hello world" /status_code == 200 or /status_code == 202 @@ -133,80 +91,135 @@ not /status_code in {200, 202} /response == null /response != null ``` +{% include copy.html %} -## Definitions +### Arithmetic expressions -This section provides expression definitions. +Arithmetic expressions enable basic mathematical operations like addition, subtraction, multiplication, and division. These expressions can be combined with conditional expressions to create more complex conditional statements. The available arithmetic operators are +, -, *, and /. The syntax for using the arithmetic operators is as follows: -### Literal -A literal is a fundamental value that has no children: -- Float: Supports values from 3.40282347 × 10<sup>38</sup> to 1.40239846 × 10<sup>−45</sup>. -- Integer: Supports values from −2,147,483,648 to 2,147,483,647. -- Boolean: Supports true or false. -- JSON Pointer: See the [JSON Pointer](#json-pointer) section for details. -- String: Supports valid Java strings. -- Null: Supports null check to see whether a JSON Pointer exists. - -### Expression string -An expression string takes the highest priority in a Data Prepper expression and only supports one expression string resulting in a return value. An _expression string_ is not the same as an _expression_. - -### Statement -A statement is the highest-priority component of an expression string. - -### Expression -An expression is a generic component that contains a _Primary_ or an _Operator_. Expressions may contain expressions. An expression's imminent children can contain 0–1 _Operators_. - -### Primary - -- _Set_ -- _Priority Expression_ -- _Literal_ - -### Operator -An operator is a hardcoded token that identifies the operation used in an _expression_. - -### JSON Pointer -A JSON Pointer is a literal used to reference a value within an event and provided as context for an _expression string_. JSON Pointers are identified by a leading `/` containing alphanumeric characters or underscores, delimited by `/`. JSON Pointers can use an extended character set if wrapped in double quotes (`"`) using the escape character `\`. Note that JSON Pointers require `~` and `/` characters, which should be used as part of the path and not as a delimiter that needs to be escaped. - -The following are examples of JSON Pointers: - -- `~0` representing `~` -- `~1` representing `/` - -#### Shorthand syntax (Regex, `\w` = `[A-Za-z_]`) ``` -/\w+(/\w+)* +<Any> + <Any> +<Any> - <Any> +<Any> * <Any> +<Any> / <Any> ``` -#### Example of shorthand +The following are example arithmetic expressions: -The following is an example of shorthand: +``` +/value + length(/message) +/bytes / 1024 +/value1 - /value2 +/TimeInSeconds * 1000 +``` +{% include copy.html %} + +The following are some example arithmetic expressions used in conditional expressions : + +``` +/value + length(/message) > 200 +/bytes / 1024 < 10 +/value1 - /value2 != /value3 + /value4 +``` +{% include copy.html %} + +### String concatenation expressions + +String concatenation expressions enable you to combine strings to create new strings. These concatenated strings can also be used within conditional expressions. The syntax for using string concatenation is as follows: + +``` +<String Variable or String Literal> + <String Variable or String Literal> +``` + +The following are example string concatenation expressions: + +``` +/name + "suffix" +"prefix" + /name +"time of " + /timeInMs + " ms" +``` +{% include copy.html %} + +The following are example string concatenation expressions that can be used in conditional expressions: + +``` +/service + ".com" == /url +"www." + /service != /url +``` +{% include copy.html %} + +### Reserved symbols + +Certain symbols, such as ^, %, xor, =, +=, -=, *=, /=, %=, ++, --, and ${<text>}, are reserved for future functionality or extensions. Reserved symbols include `^`, `%`, `xor`, `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `++`, `--`, and `${<text>}`. + +## Syntax components + +Syntax components are the building blocks of expressions in Data Prepper. They allow you to define sets, specify evaluation order, reference values within events, use literal values, and follow specific white space rules. Understanding these components is crucial for creating and working with expressions effectively in Data Prepper pipelines. + +### Priority expressions + +Priority expressions specify the evaluation order of expressions. They are enclosed in parentheses `()`. Priority expressions must contain an expression or value (empty parentheses are not supported). The following is an example priority expression: + +``` +/is_cool == (/name == "Steven") +``` +{% include copy.html %} + +### JSON pointers + +JSON pointers are used to reference values within an event. They start with a leading forward slash `/` followed by alphanumeric characters or underscores that are separated by additional forward slashes `/`. + +JSON pointers can use an extended character set by wrapping the entire pointer in double quotation marks `""` and escaping characters using a backslash `\`. Note that the `~` and `/` characters are considered to be part of the pointer path and do not need to be escaped. The following are some examples of valid JSON pointers: `~0` to represent the literal character `~` or `~1` to represent the literal character `/`. + +#### Shorthand syntax + +The shorthand syntax for a JSON pointer can be expressed using the following regular expression pattern, where `\w` represents any word character (A--Z, a-z, 0--9, or underscore): + +``` +/\w+(/\w+)*` +``` +{% include copy.html %} + + +The following is an example of this shorthand syntax: ``` /Hello/World/0 ``` +{% include copy.html %} -#### Example of escaped syntax +#### Escaped syntax + +The escaped syntax for a JSON pointer can be expressed as follows: -The following is an example of escaped syntax: ``` "/<Valid String Characters | Escaped Character>(/<Valid String Characters | Escaped Character>)*" ``` +{% include copy.html %} -#### Example of an escaped JSON Pointer +The following is an example of an escaped JSON pointer: -The following is an example of an escaped JSON Pointer: ``` # Path # { "Hello - 'world/" : [{ "\"JsonPointer\"": true }] } "/Hello - 'world\//0/\"JsonPointer\"" ``` +{% include copy.html %} -## White space +### Literals -White space is **optional** surrounding relational operators, regex equality operators, equality operators, and commas. -White space is **required** surrounding set initializers, priority expressions, set operators, and conditional expressions. +Literals are fundamental values that have no children. Data Prepper supports the following literal types: +- **Float:** Supports values from 3.40282347 x 10^38 to 1.40239846 x 10^-45. +- **Integer:** Supports values from -2,147,483,648 to 2,147,483,647. +- **Boolean:** Supports `true` or `false`. +- **JSON pointer:** See [JSON pointers](#json-pointers) for more information. +- **String:** Supports valid Java strings. +- **Null:** Supports `null` to check if a JSON pointer exists. + +### White space rules + +White space is optional around relational operators, regex equality operators, equality operators, and commas. White space is required around set initializers, priority expressions, set operators, and conditional expressions. | Operator | Description | White space required | ✅ Valid examples | ❌ Invalid examples | |----------------------|--------------------------|----------------------|----------------------------------------------------------------|---------------------------------------| @@ -214,34 +227,15 @@ White space is **required** surrounding set initializers, priority expressions, | `()` | Priority expression | Yes | `/a==(/b==200)`<br>`/a in ({200})` | `/status in({200})` | | `in`, `not in` | Set operators | Yes | `/a in {200}`<br>`/a not in {400}` | `/a in{200, 202}`<br>`/a not in{400}` | | `<`, `<=`, `>`, `>=` | Relational operators | No | `/status < 300`<br>`/status>=300` | | -| `=~`, `!~` | Regex equality pperators | No | `/msg =~ "^\w*$"`<br>`/msg=~"^\w*$"` | | +| `+` | String concatenation operator | No | `/status_code + /message + "suffix"` +| `+`, `-` | Arithmetic addition and subtraction operators | No | `/status_code + length(/message) - 2` +| `*`, `/` | Multiplication and division operators | No | `/status_code * length(/message) / 3` +| `=~`, `!~` | Regex equality operators | No | `/msg =~ "^\w*$"`<br>`/msg=~"^\w*$"` | | | `==`, `!=` | Equality operators | No | `/status == 200`<br>`/status_code==200` | | | `and`, `or`, `not` | Conditional operators | Yes | `/a<300 and /b>200` | `/b<300and/b>200` | | `,` | Set value delimiter | No | `/a in {200, 202}`<br>`/a in {200,202}`<br>`/a in {200 , 202}` | `/a in {200,}` | +| `typeof` | Type check operator | Yes | `/a typeof integer`<br>`/a typeof long`<br>`/a typeof string`<br> `/a typeof double`<br> `/a typeof boolean`<br>`/a typeof map`<br>`/a typeof array` |`/a typeof /b`<br>`/a typeof 2` | +## Related documentation -## Functions - -Data Prepper supports the following built-in functions that can be used in an expression. - -### `length()` - -The `length()` function takes one argument of the JSON pointer type and returns the length of the value passed. For example, `length(/message)` returns a length of `10` when a key message exists in the event and has a value of `1234567890`. - -### `hasTags()` - -The `hastags()` function takes one or more string type arguments and returns `true` if all the arguments passed are present in an event's tags. When an argument does not exist in the event's tags, the function returns `false`. For example, if you use the expression `hasTags("tag1")` and the event contains `tag1`, Data Prepper returns `true`. If you use the expression `hasTags("tag2")` but the event only contains a `tag1` tag, Data Prepper returns `false`. - -### `getMetadata()` - -The `getMetadata()` function takes one literal string argument to look up specific keys in a an event's metadata. If the key contains a `/`, then the function looks up the metadata recursively. When passed, the expression returns the value corresponding to the key. The value returned can be of any type. For example, if the metadata contains `{"key1": "value2", "key2": 10}`, then the function, `getMetadata("key1")`, returns `value2`. The function, `getMetadata("key2")`, returns 10. - -### `contains()` - -The `contains()` function takes two string arguments and determines whether either a literal string or a JSON pointer is contained within an event. When the second argument contains a substring of the first argument, such as `contains("abcde", "abcd")`, the function returns `true`. If the second argument does not contain any substrings, such as `contains("abcde", "xyz")`, it returns `false`. - -### `cidrContains()` - -The `cidrContains()` function takes two or more arguments. The first argument is a JSON pointer, which represents the key to the IP address that is checked. It supports both IPv4 and IPv6 addresses. Every argument that comes after the key is a string type that represents CIDR blocks that are checked against. - -If the IP address in the first argument is in the range of any of the given CIDR blocks, the function returns `true`. If the IP address is not in the range of the CIDR blocks, the function returns `false`. For example, `cidrContains(/sourceIp,"192.0.2.0/24","10.0.1.0/16")` will return `true` if the `sourceIp` field indicated in the JSON pointer has a value of `192.0.2.5`. +- [Functions]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/functions/) diff --git a/_data-prepper/pipelines/functions.md b/_data-prepper/pipelines/functions.md new file mode 100644 index 00000000..bb56b986 --- /dev/null +++ b/_data-prepper/pipelines/functions.md @@ -0,0 +1,26 @@ +--- +layout: default +title: Functions +parent: Pipelines +nav_order: 10 +has_children: true +--- + +# Data Prepper expression functions + +OpenSearch Data Prepper offers a range of built-in functions that can be used within expressions to perform common data preprocessing tasks, such as calculating lengths, checking for tags, retrieving metadata, searching for substrings, checking IP address ranges, joining list elements, and generating unique identifiers. These functions include the following: + +- [`cidrContains()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/cidrcontains/) +- [`contains()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/contains/) +- [`generateUuid()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/generate-uuid/) +- [`getMetadata()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-metadata/) +- [`getEventType()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/get-eventtype/) +- [`hasTags()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/has-tags/) +- [`join()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/join/) +- [`length()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/length/) +- [`startsWith()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/startswith/) +- [`subList()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/sublist/) +- [`substringAfter()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/substring-after/) +- [`substringAfterLast()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/substring-after-last/) +- [`substringBefore()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/substring-before/) +- [`substringBeforeLast()`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/substring-before-last/) diff --git a/_data-prepper/pipelines/generate-uuid.md b/_data-prepper/pipelines/generate-uuid.md new file mode 100644 index 00000000..d0119681 --- /dev/null +++ b/_data-prepper/pipelines/generate-uuid.md @@ -0,0 +1,73 @@ +--- +layout: default +title: generateUuid() +parent: Functions +grand_parent: Pipelines +nav_order: 11 +--- + +<!-- vale off --> +# generateUuid() function +<!-- vale on --> + +The `generateUuid()` function takes no arguments and returns a randomly generated [UUID version 4](https://www.rfc-editor.org/rfc/rfc4122) string, for example, `"550e8400-e29b-41d4-a716-446655440000"`. Each call produces a unique value using a cryptographically strong random number generator, so collision probability is negligible in practice. + +This function is useful when source records do not contain a natural unique identifier---for example, when running asynchronous batch inference jobs that require a stable key to match inference results back to the original records. + +## Usage + +Use `generateUuid()` as a `value_expression` in the [`add_entries`]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/add-entries/) processor. This example adds a `recordId` field containing a unique UUID to every event passing through the processor: + +```yaml +processor: + - add_entries: + entries: + - key: recordId + value_expression: 'generateUuid()' +``` +{% include copy.html %} + + +## Example + +The following pipeline assigns a unique `recordId` to each incoming log record before forwarding it to OpenSearch: + +```yaml +uuid-demo-pipeline: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: recordId + value_expression: 'generateUuid()' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` +{% include copy.html %} + +Given the following input event: + +```json +{ "message": "user login", "user": "alice" } +``` +{% include copy.html %} + +The document stored in OpenSearch contains the following information: + +```json +{ + "message": "user login", + "user": "alice", + "recordId": "550e8400-e29b-41d4-a716-446655440000" +} +``` diff --git a/_data-prepper/pipelines/get-eventtype.md b/_data-prepper/pipelines/get-eventtype.md new file mode 100644 index 00000000..17d21903 --- /dev/null +++ b/_data-prepper/pipelines/get-eventtype.md @@ -0,0 +1,88 @@ +--- +layout: default +title: getEventType() +parent: Functions +grand_parent: Pipelines +nav_order: 12 +--- + +<!-- vale off --> +# getEventType() function +<!-- vale on --> + +The `getEventType()` function returns the internal event type of the current event. This function is particularly useful when working with unified sources that can receive multiple types of telemetry data, such as the [OTLP source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otlp-source/). + +## Syntax + +```java +getEventType() +``` + +## Return value + +The function returns a string representing the event type. The supported event types are `LOG`, `TRACE`, `METRIC`, and `DOCUMENT`. + +## Usage + +Use this function to check the event type before performing conditional processing or routing. This is especially useful when you need to handle different types of telemetry data differently in your pipeline. + +### Basic example + +Check whether an event is a trace event: + +```json +getEventType() == "TRACE" +``` +{% include copy.html %} + +### Routing example with OTLP source + +To route different telemetry signals to different pipelines based on event type, use the `getEventType()` function to determine each event's type and route the different event types to different pipelines: + +```yaml +otel-telemetry-pipeline: + source: + otlp: + ssl: false + route: + - logs: 'getEventType() == "LOG"' + - traces: 'getEventType() == "TRACE"' + - metrics: 'getEventType() == "METRIC"' + sink: + - pipeline: + name: "logs-pipeline" + routes: + - "logs" + - pipeline: + name: "traces-pipeline" + routes: + - "traces" + - pipeline: + name: "metrics-pipeline" + routes: + - "metrics" +``` +{% include copy.html %} + +### Conditional processing example + +To process events differently based on their type, use the `add_when` expression to conditionally add fields to each event: + +```yaml +processor: + - add_entries: + entries: + - key: "log_processed" + value: true + add_when: 'getEventType() == "LOG"' + - add_entries: + entries: + - key: "metric_type" + value: "otel" + add_when: 'getEventType() == "METRIC"' +``` +{% include copy.html %} + +## Related documentation + +- [OTLP source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otlp-source/) \ No newline at end of file diff --git a/_data-prepper/pipelines/get-metadata.md b/_data-prepper/pipelines/get-metadata.md new file mode 100644 index 00000000..9c879541 --- /dev/null +++ b/_data-prepper/pipelines/get-metadata.md @@ -0,0 +1,101 @@ +--- +layout: default +title: getMetadata() +parent: Functions +grand_parent: Pipelines +nav_order: 15 +--- + +<!-- vale off --> +# getMetadata() function +<!-- vale on --> + +The `getMetadata()` function takes one literal string argument and looks up specific keys in event metadata. + +If the key contains a `/`, then the function looks up the metadata recursively. When passed, the expression returns the value corresponding to the key. + +The value returned can be of any type. For example, if the metadata contains `{"key1": "value2", "key2": 10}`, then the function `getMetadata("key1")` returns `value2`. The function `getMetadata("key2")` returns `10`. + +## Example + +The following pipeline writes request-derived values into event metadata and then uses `getMetadata()` in the OpenSearch sink to construct tenant-scoped daily index names and document IDs: + +```yaml +metadata-pass-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + # write to metadata + - metadata_key: tenant + value_expression: /tenant + - metadata_key: ingest_marker + value: batch-001 + - add_entries: + entries: + - key: tenant_from_meta + value_expression: getMetadata("tenant") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + # Use metadata inside sink format strings + index: demo-%{yyyy.MM.dd}-${getMetadata("tenant")} + document_id: ${/id}-${getMetadata("tenant")} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[{"id":"1","tenant":"eu","message":"hello"}, {"id":"2","tenant":"us","message":"hi"}]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-2025.10.22-eu", + "_id": "1-eu", + "_score": 1, + "_source": { + "id": "1", + "tenant": "eu", + "message": "hello", + "tenant_from_meta": "eu" + } + }, + { + "_index": "demo-2025.10.22-us", + "_id": "2-us", + "_score": 1, + "_source": { + "id": "2", + "tenant": "us", + "message": "hi", + "tenant_from_meta": "us" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/has-tags.md b/_data-prepper/pipelines/has-tags.md new file mode 100644 index 00000000..1d3a505f --- /dev/null +++ b/_data-prepper/pipelines/has-tags.md @@ -0,0 +1,47 @@ +--- +layout: default +title: hasTags() +parent: Functions +grand_parent: Pipelines +nav_order: 20 +--- + +<!-- vale off --> +# hasTags() function +<!-- vale on --> + +The `hasTags()` function takes one or more string type arguments and returns `true` if all of the arguments passed are present in an event's tags. If an argument does not exist in the event's tags, then the function returns `false`. + +For example, if you use the expression `hasTags("tag1")` and the event contains `tag1`, then OpenSearch Data Prepper returns `true`. If you use the expression `hasTags("tag2")` but the event only contains `tag1`, then Data Prepper returns `false`. + +#### Example + +```json +{ + "events": [ + { + "tags": ["tag1"], + "data": { + // ... + } + }, + { + "tags": ["tag1", "tag2"], + "data": { + // ... + } + } + ], + "expressions": [ + { + "expression": "hasTags(\"tag1\")", + "expected_results": [true, true] + }, + { + "expression": "hasTags(\"tag2\")", + "expected_results": [false, true] + } + ] +} +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/join.md b/_data-prepper/pipelines/join.md new file mode 100644 index 00000000..03b73cf3 --- /dev/null +++ b/_data-prepper/pipelines/join.md @@ -0,0 +1,138 @@ +--- +layout: default +title: join() +parent: Functions +grand_parent: Pipelines +nav_order: 25 +--- + +<!-- vale off --> +# join() function +<!-- vale on --> + + +The `join()` function joins elements of a list to form a string. The function takes a JSON pointer, which represents the key to a list or map where values are of the list type, and joins the lists as strings using a delimiter. The default delimiter is a comma (`,`). + +## Parameters + +The `join` function takes the following parameters: + +- `delimiter` (string, optional): The string placed between elements. Examples: `,`, ` | `, `; `. Default is `,`. +- `pointer` (required): A JSON pointer resolving to a list in the event. + +## Returns +The `join` command returns the following value: + +- `string`: All elements concatenated using the specified `delimiter`. + +## Quick examples +- `join("-", /labels)` returns `"prod-api-us"` for `labels: ["prod","api","us"]` +- `join(" | ", /authors)` returns `"Ada | Linus | Grace"` for `authors: ["Ada","Linus","Grace"]` + +## Using `join()` in a pipeline + +You can use `join()` inside processors that support `value_expression`, for example, the `add_entries` processor: + +```yaml +processor: + - add_entries: + entries: + - key: labels_csv + value_expression: join(" | ", /labels) +``` +{% include copy.html %} + +## Example + +The following pipeline ingests JSON events using an `http` source. It then uses `add_entries` with `join()` to build two new fields, `labels_csv` and `authors_pipe`: + +```yaml +join-demo: + source: + http: + path: /events + ssl: false + processor: + - add_entries: + entries: + - key: labels_csv + value_expression: join(/labels) # Comma is used by default + - key: authors_pipe + value_expression: join(" | ", /authors) + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: join-demo-%{yyyy.MM.dd} + username: admin + password: "<custom-admin-password>" + index_type: custom + insecure: true # set to true for self-signed local clusters +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"hello","labels":["prod","api","us"],"authors":["Ada","Linus","Grace"]}, + {"message":"world","labels":["stage","etl"],"authors":["Marie","Alan"]} + ]' +``` +{% include copy.html %} + +The document stored in OpenSearch contains the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "join-demo-2025.11.06", + "_id": "aGFyWZoBjfY5UoR7NC36", + "_score": 1, + "_source": { + "message": "hello", + "labels": [ + "prod", + "api", + "us" + ], + "authors": [ + "Ada", + "Linus", + "Grace" + ], + "labels_csv": "prod,api,us", + "authors_pipe": "Ada | Linus | Grace" + } + }, + { + "_index": "join-demo-2025.11.06", + "_id": "aWFyWZoBjfY5UoR7NC36", + "_score": 1, + "_source": { + "message": "world", + "labels": [ + "stage", + "etl" + ], + "authors": [ + "Marie", + "Alan" + ], + "labels_csv": "stage,etl", + "authors_pipe": "Marie | Alan" + } + } + ] + } +} +``` \ No newline at end of file diff --git a/_data-prepper/pipelines/length.md b/_data-prepper/pipelines/length.md new file mode 100644 index 00000000..87c3d81e --- /dev/null +++ b/_data-prepper/pipelines/length.md @@ -0,0 +1,26 @@ +--- +layout: default +title: length() +parent: Functions +grand_parent: Pipelines +nav_order: 30 +--- + +<!-- vale off --> +# length() function +<!-- vale on --> + +The `length()` function takes one argument of the JSON pointer type and returns the length of the passed value. For example, `length(/message)` returns a length of `10` when a key message exists in the event and has a value of `1234567890`. + +#### Example + +```json +{ + "event": { + "/message": "1234567890" + }, + "expression": "length(/message)", + "expected_output": 10 +} +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/pipelines.md b/_data-prepper/pipelines/pipelines.md index e897ed55..a18049b5 100644 --- a/_data-prepper/pipelines/pipelines.md +++ b/_data-prepper/pipelines/pipelines.md @@ -6,15 +6,21 @@ nav_order: 10 redirect_from: - /data-prepper/pipelines/ - /clients/data-prepper/pipelines/ + - /data-prepper/pipelines/configuration/processors/routes/ + - /data-prepper/pipelines/pipelines-configuration-options/ --- -# Pipelines +# Data Prepper pipelines -The following image illustrates how a pipeline works. +Pipelines are critical components that streamline the process of acquiring, transforming, and loading data from various sources into a centralized data repository or processing system. The following diagram illustrates how OpenSearch Data Prepper ingests data into OpenSearch. -<img src="{{site.url}}{{site.baseurl}}/images/data-prepper-pipeline.png" alt="Data Prepper pipeline">{: .img-fluid} +![Data Prepper pipeline]({{site.url}}{{site.baseurl}}/images/data-prepper-pipeline.png) -To use Data Prepper, you define pipelines in a configuration YAML file. Each pipeline is a combination of a source, a buffer, zero or more processors, and one or more sinks. For example: +## Configuring Data Prepper pipelines + +Pipelines are defined in the configuration YAML file. Starting with Data Prepper 2.0, you can define pipelines across multiple YAML configuration files, with each file containing the configuration for one or more pipelines. This gives you flexibility to organize and chain together complex pipeline configurations. To ensure proper loading of your pipeline configurations, place the YAML configuration files in the `pipelines` folder in your application's home directory, for example, `/usr/share/data-prepper`. + +The following is an example configuration: ```yml simple-sample-pipeline: @@ -32,321 +38,133 @@ simple-sample-pipeline: sink: - stdout: ``` +{% include copy.html %} -- Sources define where your data comes from. In this case, the source is a random UUID generator (`random`). +### Pipeline components -- Buffers store data as it passes through the pipeline. +The following table describes the components used in the given pipeline. - By default, Data Prepper uses its one and only buffer, the `bounded_blocking` buffer, so you can omit this section unless you developed a custom buffer or need to tune the buffer settings. +Option | Required | Type | Description +:--- | :--- |:------------| :--- +`workers` | No | Integer | The number of application threads. Set to the number of CPU cores. Default is `1`. +`delay` | No | Integer | The number of milliseconds that `workers` wait between buffer read attempts. Default is `3000`. +`source` | Yes | String list | `random` generates random numbers by using a Universally Unique Identifier (UUID) generator. +`bounded_blocking` | No | String list | The default buffer in Data Prepper. +`processor` | No | String list | A `string_converter` with an `upper_case` processor that converts strings to uppercase. +`sink` | Yes | `stdout` outputs to standard output. -- Processors perform some action on your data: filter, transform, enrich, etc. +## Pipeline concepts - You can have multiple processors, which run sequentially from top to bottom, not in parallel. The `string_converter` processor transform the strings by making them uppercase. +The following are fundamental concepts relating to Data Prepper pipelines. -- Sinks define where your data goes. In this case, the sink is stdout. +### End-to-end acknowledgments -Starting from Data Prepper 2.0, you can define pipelines across multiple configuration YAML files, where each file contains the configuration for one or more pipelines. This gives you more freedom to organize and chain complex pipeline configurations. For Data Prepper to load your pipeline configuration properly, place your configuration YAML files in the `pipelines` folder under your application's home directory (e.g. `/usr/share/data-prepper`). -{: .note } +Data Prepper ensures reliable and durable data delivery from sources to sinks through end-to-end (E2E) acknowledgments. The E2E acknowledgment process begins at the source, which monitors event batches within pipelines and waits for a positive acknowledgment upon successful delivery to the sinks. In pipelines with multiple sinks, including nested Data Prepper pipelines, the E2E acknowledgment is sent when events reach the final sink in the pipeline chain. Conversely, the source sends a negative acknowledgment if an event cannot be delivered to a sink for any reason. -## End-to-end acknowledgments +If a pipeline component fails to process and send an event, then the source receives no acknowledgment. In the case of a failure, the pipeline's source times out, allowing you to take necessary actions, such as rerunning the pipeline or logging the failure. -Data Prepper ensures the durability and reliability of data written from sources and delivered to sinks through end-to-end (E2E) acknowledgments. An E2E acknowledgment begins at the source, which monitors a batch of events set inside pipelines and waits for a positive acknowledgment when those events are successfully pushed to sinks. When a pipeline contains multiple sinks, including sinks set as additional Data Prepper pipelines, the E2E acknowledgment sends when events are received by the final sink in a pipeline chain. +### Conditional routing -Alternatively, the source sends a negative acknowledgment when an event cannot be delivered to a sink for any reason. +Pipelines also support conditional routing, which enables the routing of events to different sinks based on specific conditions. To add conditional routing, specify a list of named routes using the `route` component and assign specific routes to sinks using the `routes` property. Any sink with the `routes` property only accepts events matching at least one of the routing conditions. -When any component of a pipeline fails and is unable to send an event, the source receives no acknowledgment. In the case of a failure, the pipeline's source times out. This gives you the ability to take any necessary actions to address the source failure, including rerunning the pipeline or logging the failure. +In the following pipeline, routes are defined at the pipeline level under `route`. The route uses [Data Prepper expressions](https://github.com/opensearch-project/data-prepper/tree/main/examples) to define the condition. Two named routes are declared: +- `errors: /level == "ERROR"` -## Conditional routing +- `slow_requests: /latency_ms != null and /latency_ms >= 1000` -Pipelines also support **conditional routing** which allows you to route events to different sinks based on specific conditions. To add conditional routing to a pipeline, specify a list of named routes under the `route` component and add specific routes to sinks under the `routes` property. Any sink with the `routes` property will only accept events that match at least one of the routing conditions. +Each OpenSearch sink can opt in to one or more routes using the `routes:` setting. Events that satisfy a route's condition are delivered to the sinks that reference that route. For example, the first sink receives events matching `errors`, and the second sink receives events matching `slow_requests`. -In the following example, `application-logs` is a named route with a condition set to `/log_type == "application"`. The route uses [Data Prepper expressions](https://github.com/opensearch-project/data-prepper/tree/main/examples) to define the conditions. Data Prepper only routes events that satisfy the condition to the first OpenSearch sink. By default, Data Prepper routes all events to a sink which does not define a route. In the example, all events route into the third OpenSearch sink. +By default, any sink without a `routes:` list receives all events, regardless of whether they matched other routes. In the following example, the third sink has no `routes:` setting, so it receives all events, including those already routed to the first two sinks: ```yml -conditional-routing-sample-pipeline: +routes-demo-pipeline: source: http: - processor: - route: - - application-logs: '/log_type == "application"' - - http-logs: '/log_type == "apache"' - sink: - - opensearch: - hosts: [ "https://opensearch:9200" ] - index: application_logs - routes: [application-logs] - - opensearch: - hosts: [ "https://opensearch:9200" ] - index: http_logs - routes: [http-logs] - - opensearch: - hosts: [ "https://opensearch:9200" ] - index: all_logs -``` - - -## Examples - -This section provides some pipeline examples that you can use to start creating your own pipelines. For more pipeline configurations, select from the following options for each component: - -- [Buffers]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/buffers/buffers/) -- [Processors]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/processors/) -- [Sinks]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sinks/sinks/) -- [Sources]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/sources/) - -The Data Prepper repository has several [sample applications](https://github.com/opensearch-project/data-prepper/tree/main/examples) to help you get started. - -### Log ingestion pipeline - -The following example `pipeline.yaml` file with SSL and basic authentication enabled for the `http-source` demonstrates how to use the HTTP Source and Grok Prepper plugins to process unstructured log data: - - -```yaml -log-pipeline: - source: - http: - ssl_certificate_file: "/full/path/to/certfile.crt" - ssl_key_file: "/full/path/to/keyfile.key" - authentication: - http_basic: - username: "myuser" - password: "mys3cret" - processor: - - grok: - match: - # This will match logs with a "log" key against the COMMONAPACHELOG pattern (ex: { "log": "actual apache log..." } ) - # You should change this to match what your logs look like. See the grok documenation to get started. - log: [ "%{COMMONAPACHELOG}" ] - sink: - - opensearch: - hosts: [ "https://localhost:9200" ] - # Change to your credentials - username: "admin" - password: "admin" - # Add a certificate file if you are accessing an OpenSearch cluster with a self-signed certificate - #cert: /path/to/cert - # If you are connecting to an Amazon OpenSearch Service domain without - # Fine-Grained Access Control, enable these settings. Comment out the - # username and password above. - #aws_sigv4: true - #aws_region: us-east-1 - # Since we are Grok matching for Apache logs, it makes sense to send them to an OpenSearch index named apache_logs. - # You should change this to correspond with how your OpenSearch indexes are set up. - index: apache_logs -``` - -This example uses weak security. We strongly recommend securing all plugins which open external ports in production environments. -{: .note} - -### Trace analytics pipeline - -The following example demonstrates how to build a pipeline that supports the [Trace Analytics OpenSearch Dashboards plugin]({{site.url}}{{site.baseurl}}/observability-plugin/trace/ta-dashboards/). This pipeline takes data from the OpenTelemetry Collector and uses two other pipelines as sinks. These two separate pipelines index trace and the service map documents for the dashboard plugin. - -Starting from Data Prepper 2.0, Data Prepper no longer supports `otel_trace_raw_prepper` processor due to the Data Prepper internal data model evolution. -Instead, users should use `otel_trace_raw`. - -```yml -entry-pipeline: - delay: "100" - source: - otel_trace_source: + path: /logs ssl: false - buffer: - bounded_blocking: - buffer_size: 10240 - batch_size: 160 - sink: - - pipeline: - name: "raw-pipeline" - - pipeline: - name: "service-map-pipeline" -raw-pipeline: - source: - pipeline: - name: "entry-pipeline" - buffer: - bounded_blocking: - buffer_size: 10240 - batch_size: 160 - processor: - - otel_trace_raw: + + route: + - errors: '/level == "ERROR"' + - slow_requests: '/latency_ms != null and /latency_ms >= 1000' + sink: + # 1) Only events matching the "errors" route - opensearch: - hosts: ["https://localhost:9200"] + hosts: ["https://opensearch:9200"] insecure: true username: admin - password: admin - index_type: trace-analytics-raw -service-map-pipeline: - delay: "100" - source: - pipeline: - name: "entry-pipeline" - buffer: - bounded_blocking: - buffer_size: 10240 - batch_size: 160 - processor: - - service_map_stateful: - sink: + password: "<custom-admin-password>" + index_type: custom + index: routed-errors-%{yyyy.MM.dd} + routes: [errors] + + # 2) Only events matching the "slow_requests" route - opensearch: - hosts: ["https://localhost:9200"] + hosts: ["https://opensearch:9200"] insecure: true username: admin - password: admin - index_type: trace-analytics-service-map -``` + password: "<custom-admin-password>" + index_type: custom + index: routed-slow-%{yyyy.MM.dd} + routes: [slow_requests] -To maintain similar ingestion throughput and latency, scale the `buffer_size` and `batch_size` by the estimated maximum batch size in the client request payload. -{: .tip} - -### Metrics pipeline - -Data Prepper supports metrics ingestion using OTel. It currently supports the following metric types: - -* Gauge -* Sum -* Summary -* Histogram - -Other types are not supported. Data Prepper drops all other types, including Exponential Histogram and Summary. Additionally, Data Prepper does not support Scope instrumentation. - -To set up a metrics pipeline: - -```yml -metrics-pipeline: - source: - otel_metrics_source: - processor: - - otel_metrics_raw_processor: - sink: + # 3) All events - opensearch: - hosts: ["https://localhost:9200"] - username: admin - password: admin + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: routed-other-%{yyyy.MM.dd} ``` +{% include copy.html %} -### S3 log ingestion pipeline - -The following example demonstrates how to use the S3Source and Grok Processor plugins to process unstructured log data from [Amazon Simple Storage Service](https://aws.amazon.com/s3/) (Amazon S3). This example uses application load balancer logs. As the application load balancer writes logs to S3, S3 creates notifications in Amazon SQS. Data Prepper monitors those notifications and reads the S3 objects to get the log data and process it. - -```yml -log-pipeline: - source: - s3: - notification_type: "sqs" - compression: "gzip" - codec: - newline: - sqs: - queue_url: "https://sqs.us-east-1.amazonaws.com/12345678910/ApplicationLoadBalancer" - aws: - region: "us-east-1" - sts_role_arn: "arn:aws:iam::12345678910:role/Data-Prepper" - - processor: - - grok: - match: - message: ["%{DATA:type} %{TIMESTAMP_ISO8601:time} %{DATA:elb} %{DATA:client} %{DATA:target} %{BASE10NUM:request_processing_time} %{DATA:target_processing_time} %{BASE10NUM:response_processing_time} %{BASE10NUM:elb_status_code} %{DATA:target_status_code} %{BASE10NUM:received_bytes} %{BASE10NUM:sent_bytes} \"%{DATA:request}\" \"%{DATA:user_agent}\" %{DATA:ssl_cipher} %{DATA:ssl_protocol} %{DATA:target_group_arn} \"%{DATA:trace_id}\" \"%{DATA:domain_name}\" \"%{DATA:chosen_cert_arn}\" %{DATA:matched_rule_priority} %{TIMESTAMP_ISO8601:request_creation_time} \"%{DATA:actions_executed}\" \"%{DATA:redirect_url}\" \"%{DATA:error_reason}\" \"%{DATA:target_list}\" \"%{DATA:target_status_code_list}\" \"%{DATA:classification}\" \"%{DATA:classification_reason}"] - - grok: - match: - request: ["(%{NOTSPACE:http_method})? (%{NOTSPACE:http_uri})? (%{NOTSPACE:http_version})?"] - - grok: - match: - http_uri: ["(%{WORD:protocol})?(://)?(%{IPORHOST:domain})?(:)?(%{INT:http_port})?(%{GREEDYDATA:request_uri})?"] - - date: - from_time_received: true - destination: "@timestamp" - - - sink: - - opensearch: - hosts: [ "https://localhost:9200" ] - username: "admin" - password: "admin" - index: alb_logs -``` - -## Migrating from Logstash - -Data Prepper supports Logstash configuration files for a limited set of plugins. Simply use the logstash config to run Data Prepper. +You can test this pipeline using the following command: ```bash -docker run --name data-prepper \ - -v /full/path/to/logstash.conf:/usr/share/data-prepper/pipelines/pipelines.conf \ - opensearchproject/opensearch-data-prepper:latest +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + {"level":"ERROR","message":"DB connection failed","latency_ms":120}, + {"level":"INFO","message":"GET /api/items","latency_ms":1500}, + {"level":"INFO","message":"health check ok","latency_ms":42} + ]' +``` +{% include copy.html %} + +The documents are stored in the corresponding indexes: + +``` +health status index uuid pri rep docs.count docs.deleted store.size pri.store.size +... +green open routed-other-2025.10.14 IBZTXO3ySBGky0tIHRaRmg 1 1 3 0 5.4kb 5.4kb +green open routed-slow-2025.10.14 J-hzZ9m8RkWvpMKC_oQLVQ 1 1 1 0 5kb 5kb +green open routed-errors-2025.10.14 v3r7JzPfQVOS8dWOBF1o2w 1 1 1 0 5kb 5kb +... ``` -This feature is limited by feature parity of Data Prepper. As of Data Prepper 1.2 release, the following plugins from the Logstash configuration are supported: +### DLQ pipeline -- HTTP Input plugin -- Grok Filter plugin -- Elasticsearch Output plugin -- Amazon Elasticsearch Output plugin +The dead-letter queue (DLQ) pipeline is a dedicated pipeline that captures events Data Prepper cannot process at any stage, including the source, processor, buffer, or sink. You define this pipeline using the reserved name `dlq_pipeline`, and it must be configured without a source. -## Configure the Data Prepper server +The pipeline can include optional processors and routes, but it must contain at least one sink used to send failed events to an external destination. Like other pipelines, the DLQ pipeline can use routes and multiple sinks to direct different events to different destinations. -Data Prepper itself provides administrative HTTP endpoints such as `/list` to list pipelines and `/metrics/prometheus` to provide Prometheus-compatible metrics data. The port that has these endpoints has a TLS configuration and is specified by a separate YAML file. By default, these endpoints are secured by Data Prepper docker images. We strongly recommend providing your own configuration file for securing production environments. Here is an example `data-prepper-config.yaml`: +The following is an example configuration: ```yml -ssl: true -keyStoreFilePath: "/usr/share/data-prepper/keystore.jks" -keyStorePassword: "password" -privateKeyPassword: "other_password" -serverPort: 1234 -``` - -To configure the Data Prepper server, run Data Prepper with the additional yaml file. - -```bash -docker run --name data-prepper \ - -v /full/path/to/my-pipelines.yaml:/usr/share/data-prepper/pipelines/my-pipelines.yaml \ - -v /full/path/to/data-prepper-config.yaml:/usr/share/data-prepper/data-prepper-config.yaml \ - opensearchproject/data-prepper:latest -``` - -## Configure peer forwarder - -Data Prepper provides an HTTP service to forward events between Data Prepper nodes for aggregation. This is required for operating Data Prepper in a clustered deployment. Currently, peer forwarding is supported in `aggregate`, `service_map_stateful`, and `otel_trace_raw` processors. Peer forwarder groups events based on the identification keys provided by the processors. For `service_map_stateful` and `otel_trace_raw` it's `traceId` by default and can not be configured. For `aggregate` processor, it is configurable using `identification_keys` option. - -Peer forwarder supports peer discovery through one of three options: a static list, a DNS record lookup , or AWS Cloud Map. Peer discovery can be configured using `discovery_mode` option. Peer forwarder also supports SSL for verification and encryption, and mTLS for mutual authentication in a peer forwarding service. - -To configure peer forwarder, add configuration options to `data-prepper-config.yaml` mentioned in the [Configure the Data Prepper server](#configure-the-data-prepper-server) section: - -```yml -peer_forwarder: - discovery_mode: dns - domain_name: "data-prepper-cluster.my-domain.net" - ssl: true - ssl_certificate_file: "<cert-file-path>" - ssl_key_file: "<private-key-file-path>" - authentication: - mutual_tls: -``` - - -## Pipeline Configurations - -Since Data Prepper 2.5, shared pipeline components can be configured under the reserved section `pipeline_configurations` when all pipelines are defined in a single pipeline configuration YAML file. -Shared pipeline configurations can include certain components within [Extension Plugins]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#extension-plugins), as shown in the following example that refers to secrets configurations for an `opensearch` sink: - -```json -pipeline_configurations: - aws: - secrets: - credential-secret-config: - secret_id: <YOUR_SECRET_ID> - region: <YOUR_REGION> - sts_role_arn: <YOUR_STS_ROLE_ARN> -simple-sample-pipeline: - ... +dlq_pipeline: + processor: + - uppercase_string: + with_keys: + - "uppercaseField" sink: - opensearch: - hosts: [ {% raw %}"${{aws_secrets:host-secret-config}}"{% endraw %} ] - username: {% raw %}"${{aws_secrets:credential-secret-config:username}}"{% endraw %} - password: {% raw %}"${{aws_secrets:credential-secret-config:password}}"{% endraw %} - index: "test-migration" ``` +{% include copy.html %} -When the same component is defined in both `pipelines.yaml` and `data-prepper-config.yaml`, the definition in the `pipelines.yaml` will overwrite the counterpart in `data-prepper-config.yaml`. For more information on shared pipeline components, see [AWS secrets extension plugin]({{site.url}}{{site.baseurl}}/data-prepper/managing-data-prepper/configuring-data-prepper/#aws-secrets-extension-plugin) for details. + + +## Next steps + +- See [Common uses cases]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/common-use-cases/) for example configurations. diff --git a/_data-prepper/pipelines/startswith.md b/_data-prepper/pipelines/startswith.md new file mode 100644 index 00000000..e0d00700 --- /dev/null +++ b/_data-prepper/pipelines/startswith.md @@ -0,0 +1,124 @@ +--- +layout: default +title: startsWith() +parent: Functions +grand_parent: Pipelines +nav_order: 40 +--- + +<!-- vale off --> +# startsWith() function +<!-- vale on --> + +The `startsWith()` function checks whether a string starts with the given string. It takes two arguments: + +- The first argument is either a literal string or a JSON pointer that represents the field or value to be checked. + +- The second argument is the string to be checked in the first argument. +The function returns `true` if the string or field value represented by the first argument starts with the string specified in the second argument and `false` otherwise. + +For example, to check whether the value of a field name `message` starts with a string `"abcd"`, use the `startsWith()` function as follows: + +``` +startsWith('/message', 'abcd') +``` +{% include copy.html %} + +This call returns `true` if the `message` field starts with the string `abcd` or `false` if it does not. + +Alternatively, you can use a literal string as the first argument: + +``` +startsWith('abcdef', 'abcd') +``` +{% include copy.html %} + +In this case, the function returns `true` because the string `abcdef` starts with `abcd`. + +The `startsWith()` function performs a case-sensitive check. +{: .note } + +## Example + +The following pipeline uses the `startsWith()` function to add two Boolean flags, `starts_abcd` and `starts_error`, to each event and forwards only events that start with the string `ERROR:` to OpenSearch: + +```yaml +startswith-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: starts_abcd + value_expression: startsWith(/message, "abcd") + + - key: starts_error + value_expression: startsWith(/message, "ERROR:") + + # forward only messages that start with "ERROR:" + - drop_events: + drop_when: not startsWith(/message, "ERROR:") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: startswith-demo-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"ok hello"}, + {"message":"abcd-hello"}, + {"message":"ERROR: something bad"}, + {"message":"ERROR: abcd unit test failed"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "startswith-demo-2025.11.10", + "_id" : "X97tbpoBnoSLj36HBGoL", + "_score" : 1.0, + "_source" : { + "starts_abcd" : false, + "starts_error" : true, + "message" : "ERROR: something bad" + } + }, + { + "_index" : "startswith-demo-2025.11.10", + "_id" : "YN7tbpoBnoSLj36HBGoL", + "_score" : 1.0, + "_source" : { + "starts_abcd" : false, + "starts_error" : true, + "message" : "ERROR: abcd unit test failed" + } + } + ] + } +} +``` \ No newline at end of file diff --git a/_data-prepper/pipelines/sublist.md b/_data-prepper/pipelines/sublist.md new file mode 100644 index 00000000..89dd0436 --- /dev/null +++ b/_data-prepper/pipelines/sublist.md @@ -0,0 +1,83 @@ +--- +layout: default +title: subList() +parent: Functions +grand_parent: Pipelines +nav_order: 50 +--- + +<!-- vale off --> +# subList() function +<!-- vale on --> + +The `subList(<key>, <start_index, inclusive>, <end_index, exclusive>)` function extracts a sublist from a list field in an event. It takes the following arguments: + +- A JSON pointer to an event field containing a list +- A start index (inclusive) +- An end index (exclusive) + +The function returns the portion of the list between the specified start and end indexes. If the end index is `-1`, the function extracts elements from the start index to the end of the list. + + +## Examples + +The following examples show how the `sublist()` function works. + +<!-- vale off --> +### add_entries processor +<!-- vale on --> + +You can use `subList()` in the `add_entries` processor, as shown in the following example. + +The function uses the following input to extract a sublist: + +``` +input: {"my_list": [ 0, 1, 2, 3, 4, 5, 6]} +``` + +Then, the following configuration uses the `add_entries` processor to extract a sublist from `my_list`, starting at index `1` and ending before index `4`: + +```yaml +add_entries: + entries: + - key: "my_list" + value_expression: '/subList(/my_list, 1, 4)' + overwrite_if_key_exists: true +``` +{% include copy.html %} + +The following output shows the resulting list after extracting elements from index `1` to `3` and overwriting the original list: + +``` +output: my_list: [1, 2, 3] +``` + +### Specific ranges + +Each of the following examples demonstrates how the `subList()` function extracts a specific range of elements from a list. + +The following example extracts elements from index `0` to `2` (excluding index `3`), resulting in the first three elements of the list: + +```json +{ + "event": { + "/my_list": [0, 1, 2, 3, 4, 5, 6] + }, + "expression": "subList(/my_list, 4, -1)", + "expected_output": [4, 5, 6] +} +``` +{% include copy.html %} + +The following example uses `-1` as the end index, which specifies to include all elements from index `4` to the end of the list: + +```json +{ + "event": { + "/my_list": [0, 1, 2, 3, 4, 5, 6] + }, + "expression": "subList(/my_list, 4, -1)", + "expected_output": [4, 5, 6] +} +``` +{% include copy.html %} diff --git a/_data-prepper/pipelines/substring-after-last.md b/_data-prepper/pipelines/substring-after-last.md new file mode 100644 index 00000000..77bf90f3 --- /dev/null +++ b/_data-prepper/pipelines/substring-after-last.md @@ -0,0 +1,114 @@ +--- +layout: default +title: substringAfterLast() +parent: Functions +grand_parent: Pipelines +nav_order: 70 +--- + +<!-- vale off --> +# substringAfterLast() function +<!-- vale on --> + +The `substringAfterLast()` function is used to extract the portion of a string that follows the last occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string after the last occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to extract the file extension from the `/filepath` field containing a file path, use the `substringAfterLast()` function as follows: + +``` +'substringAfterLast(/filepath, ".")' +``` +{% include copy.html %} + +If the `/filepath` field contains `archive.tar.gz`, the function returns `gz`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringAfterLast("one-two-three", "-")' +``` +{% include copy.html %} + +The function returns `three` because it extracts the portion of the string after the last `-` character. + +The `substringAfterLast()` function performs a case-sensitive search. +{: .note} + +## Example + +The following pipeline uses the `substringAfterLast()` function to extract the file name from a full file path. It adds the extracted file name as a new field called `filename`: + +```yaml +substring-after-last-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: filename + value_expression: 'substringAfterLast(/filepath, "/")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"filepath":"/var/log/syslog"}, + {"filepath":"/home/user/docs/report.pdf"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "filepath": "/var/log/syslog", + "filename": "syslog" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "filepath": "/home/user/docs/report.pdf", + "filename": "report.pdf" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/substring-after.md b/_data-prepper/pipelines/substring-after.md new file mode 100644 index 00000000..51a83979 --- /dev/null +++ b/_data-prepper/pipelines/substring-after.md @@ -0,0 +1,114 @@ +--- +layout: default +title: substringAfter() +parent: Functions +grand_parent: Pipelines +nav_order: 60 +--- + +<!-- vale off --> +# substringAfter() function +<!-- vale on --> + +The `substringAfter()` function is used to extract the portion of a string that follows the first occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string after the first occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to extract the value after the first occurrence of the `=` character in a field named `header`, use the `substringAfter()` function as follows: + +``` +'substringAfter(/header, "=")' +``` +{% include copy.html %} + +If `/header` contains `Content-Type=application/json`, the function returns `application/json`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringAfter("hello-world-foo", "-")' +``` +{% include copy.html %} + +The function returns `world-foo` because it extracts the portion of the string after the first `-` character. + +The `substringAfter()` function performs a case-sensitive search. +{: .note} + +## Example + +The following pipeline uses the `substringAfter()` function to extract the domain name from an email address field. It adds the extracted domain name as a new field called `domain`: + +```yaml +substring-after-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: domain + value_expression: 'substringAfter(/email, "@")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"email":"user@example.com"}, + {"email":"admin@opensearch.org"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "email": "user@example.com", + "domain": "example.com" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "email": "admin@opensearch.org", + "domain": "opensearch.org" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/substring-before-last.md b/_data-prepper/pipelines/substring-before-last.md new file mode 100644 index 00000000..1716c9a2 --- /dev/null +++ b/_data-prepper/pipelines/substring-before-last.md @@ -0,0 +1,114 @@ +--- +layout: default +title: substringBeforeLast() +parent: Functions +grand_parent: Pipelines +nav_order: 90 +--- + +<!-- vale off --> +# substringBeforeLast() function +<!-- vale on --> + +The `substringBeforeLast()` function is used to extract the portion of a string that precedes the last occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string before the last occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to remove the file extension from a filename field, use the `substringBeforeLast()` function as follows: + +``` +'substringBeforeLast(/filename, ".")' +``` +{% include copy.html %} + +If the `/filename` field contains `archive.tar.gz`, the function returns `archive.tar`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringBeforeLast("one-two-three", "-")' +``` +{% include copy.html %} + +The function returns `one-two` because it extracts the portion of the string before the last `-` character. + +The `substringBeforeLast()` function performs a case-sensitive search. +{: .note} + +## Example + +The following pipeline uses the `substringBeforeLast()` function to extract the directory path from a full file path. It adds the extracted directory path as a new field called `directory`: + +```yaml +substring-before-last-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: directory + value_expression: 'substringBeforeLast(/filepath, "/")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"filepath":"/var/log/syslog"}, + {"filepath":"/home/user/docs/report.pdf"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "filepath": "/var/log/syslog", + "directory": "/var/log" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "filepath": "/home/user/docs/report.pdf", + "directory": "/home/user/docs" + } + } + ] + } +} +``` diff --git a/_data-prepper/pipelines/substring-before.md b/_data-prepper/pipelines/substring-before.md new file mode 100644 index 00000000..0fec2a6f --- /dev/null +++ b/_data-prepper/pipelines/substring-before.md @@ -0,0 +1,114 @@ +--- +layout: default +title: substringBefore() +parent: Functions +grand_parent: Pipelines +nav_order: 80 +--- + +<!-- vale off --> +# substringBefore() function +<!-- vale on --> + +The `substringBefore()` function is used to extract the portion of a string that precedes the first occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string before the first occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to extract the username from an email address field, use the `substringBefore()` function as follows: + +``` +'substringBefore(/email, "@")' +``` +{% include copy.html %} + +If the `/email` field contains `user@example.com`, the function returns `user`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringBefore("hello-world-foo", "-")' +``` +{% include copy.html %} + +The function returns `hello` because it extracts the portion of the string before the first `-` character. + +The `substringBefore()` function performs a case-sensitive search. +{: .note} + +## Example + +The following pipeline uses the `substringBefore()` function to extract the URL protocol from a URL field. It adds the extracted protocol as a new field called `protocol`: + +```yaml +substring-before-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: protocol + value_expression: 'substringBefore(/url, "://")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` +{% include copy.html %} + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"url":"https://opensearch.org/docs"}, + {"url":"http://example.com/page"} + ]' +``` +{% include copy.html %} + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "url": "https://opensearch.org/docs", + "protocol": "https" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "url": "http://example.com/page", + "protocol": "http" + } + } + ] + } +} +``` diff --git a/_im-plugin/append-only-index.md b/_im-plugin/append-only-index.md new file mode 100644 index 00000000..c5fbd1db --- /dev/null +++ b/_im-plugin/append-only-index.md @@ -0,0 +1,103 @@ +--- +layout: default +title: Append-only index +nav_order: 30 +--- + +# Append-only index + +An append-only index is an immutable index that only allows document ingestion (appending) while blocking all updates or deletions after initial document creation. When you enable the append-only setting for an index, OpenSearch prevents any modifications to existing documents. You can only add new documents to the index. + +When you configure an index as append-only, the following operations return an error: + +- Document update call (Update API) +- Document delete call (Delete API) +- Update by query call +- Delete by query call +- Bulk API calls made with the update, delete, or upsert actions +- Bulk API calls containing an index action with a custom document ID + +Because an append-only index performs no updates or deletions, it skips soft deletes and version tracking, which reduces storage use and the work done during segment merges. Use an append-only index for data that is not modified after it is ingested, such as logs, metrics, observability data, or security events. + +## Creating an append-only index + +The following request creates a new index named `my-append-only-index` with all updates disabled: + +```json +PUT /my-append-only-index +{ + "settings": { + "index.append_only.enabled": true + } +} +``` +{% include copy-curl.html %} + +After an index is set to append-only, it cannot be changed to another index type. +{: .warning} + + +To append data from an existing index to a new append-only index, use the Reindex API. Because append-only indexes don't support custom document IDs, you need to set the `ctx._id` of the source index to `null`. This allows documents to be added through reindexing. + +The following example reindexes documents from a source index (`my-source-index`) into the new append-only index. Create the source index first: + +```json +POST /my-source-index/_doc?refresh=true +{ + "message": "login attempt" +} +``` +{% include copy-curl.html %} + +Then reindex its documents into the append-only index: + +```json +POST /_reindex +{ + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-append-only-index" + }, + "script": { + "source": "ctx._id = null", + "lang": "painless" + } +} + +``` +{% include copy-curl.html %} + +## Adaptive shard selection for bulk indexing +**Introduced 3.5** +{: .label .label-purple } + +For append-only indexes, OpenSearch automatically generates a random `_id` for write routing when you don't explicitly specify one. In bulk writing, a single bulk entry may be split into dozens of sub-bulks and dispatched to different shards, which leads to significant long-tail latency and markedly degrades write performance. + +Adaptive shard selection guarantees that all sub-bulks of a single bulk entry are routed to the same shard, thereby achieving a substantial boost in bulk write performance. + +The `index.bulk.adaptive_shard_selection.enabled` setting is dynamic, so you can enable it on an existing append-only index: + +```json +PUT /my-append-only-index/_settings +{ + "index.bulk.adaptive_shard_selection.enabled": "true" +} +``` +{% include copy-curl.html %} + +You can also set it when you create the index: + +```json +PUT /my-new-append-only-index +{ + "settings": { + "index.append_only.enabled": "true", + "index.bulk.adaptive_shard_selection.enabled": "true" + } +} +``` +{% include copy-curl.html %} + +For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). \ No newline at end of file diff --git a/_im-plugin/data-streams.md b/_im-plugin/data-streams.md index d59526b7..475c6ec8 100644 --- a/_im-plugin/data-streams.md +++ b/_im-plugin/data-streams.md @@ -1,45 +1,57 @@ --- layout: default title: Data streams -nav_order: 13 +nav_order: 25 +redirect_from: + - /opensearch/data-streams/ + - /dashboards/im-dashboards/datastream/ + - /dashboards/admin-ui-index/datastream/ --- # Data streams -If you're ingesting continuously generated time-series data such as logs, events, and metrics into OpenSearch, you're likely in a scenario where the number of documents grows rapidly and you don't need to update older documents. +A data stream is a single name that you write to and search, backed by a series of hidden indexes that OpenSearch rolls over for you. Indexing requests go to the current write index, and search requests go to all of the backing indexes. -A typical workflow to manage time-series data involves multiple steps, such as creating a rollover index alias, defining a write index, and defining common mappings and settings for the backing indexes. +Data streams are for continuously generated time-series data, such as logs, events, and metrics, where documents accumulate quickly and older documents are never updated. Managing that data as plain indexes means creating a rollover alias, designating a write index, and repeating the same mappings and settings for each new index. A data stream does this from one index template. -Data streams simplify this process and enforce a setup that best suits time-series data, such as being designed primarily for append-only data and ensuring that each document has a timestamp field. +Data streams have the following characteristics: -A data stream is internally composed of multiple backing indexes. Search requests are routed to all the backing indexes, while indexing requests are routed to the latest write index. [ISM]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) policies let you automatically handle index rollovers or deletions. +- Every document must contain a timestamp field. A document without one is rejected. +- A data stream is append-only. Indexing requests sent to the data stream name can only create new documents. To update or delete existing documents, use an update by query or delete by query request, or send the request to the backing index that contains the document. For more information, see [Updating and deleting documents in a data stream](#updating-and-deleting-documents-in-a-data-stream). +- Backing indexes are named `.ds-<data-stream>-<generation>` and are hidden. The generation number increases with each rollover. +- A data stream can only be created from an index template that contains a `data_stream` object. +Attach an [Index State Management (ISM)]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) policy to automate rollover and deletion of the backing indexes based on their age, size, or document count. The policy is applied to each backing index when it is created, so attaching a policy to a data stream affects only its future backing indexes. You do not need to provide the `rollover_alias` setting because the policy takes that information from the backing index. -## Get started with data streams +To define granular permissions for a data stream, use its name as you would an index name. For more information, see [Permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/). -### Step 1: Create an index template +## Creating an index template for a data stream -To create a data stream, you first need to create an index template that configures a set of indexes as a data stream. The `data_stream` object indicates that it’s a data stream and not a regular index template. The index pattern matches with the name of the data stream: +A data stream is defined by an index template that contains a `data_stream` object. The template's index patterns must match the names of the data streams that you intend to create: ```json PUT _index_template/logs-template { "index_patterns": [ - "my-data-stream", "logs-*" ], "data_stream": {}, "priority": 100 } ``` +{% include copy-curl.html %} -In this case, each ingested document must have an `@timestamp` field. -You also have the ability to define your own custom timestamp field as a property in the `data_stream` object. You can also add index mappings and other settings here, just as you would for a regular index template. +A data stream template claims its index patterns exclusively. While this template exists, creating a regular index whose name starts with `logs-` fails with `cannot create index with name [...], because it matches with template [logs-template] that creates data streams only`. Choose patterns narrow enough that they do not overlap with your regular indexes. +{: .note} + +Documents indexed into a data stream created from this template must contain an `@timestamp` field. To use a different field name, specify it in `timestamp_field`. The `template` object accepts the same settings, mappings, and aliases as a regular index template and applies them to each backing index: ```json -PUT _index_template/logs-template-nginx +PUT _index_template/logs-nginx-template { - "index_patterns": "logs-nginx", + "index_patterns": [ + "logs-nginx" + ], "data_stream": { "timestamp_field": { "name": "request_time" @@ -54,22 +66,20 @@ PUT _index_template/logs-template-nginx } } ``` +{% include copy-curl.html %} -In this case, `logs-nginx` index matches both the `logs-template` and `logs-template-nginx` templates. When you have a tie, OpenSearch selects the matching index template with the higher priority value. +The name `logs-nginx` matches both templates. OpenSearch applies `logs-nginx-template` because it has the higher priority. For more information, see [Index templates]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/). -### Step 2: Create a data stream +## Creating a data stream -After you create an index template, you can create a data stream. -You can use the data stream API to explicitly create a data stream. The data stream API initializes the first backing index: +Create the data stream explicitly to initialize its first backing index: ```json PUT _data_stream/logs-redis -PUT _data_stream/logs-nginx ``` +{% include copy-curl.html %} -You can also directly start ingesting data without creating a data stream. - -Because we have a matching index template with a data_stream object, OpenSearch automatically creates the data stream: +You can also skip this step and start indexing. Because a matching template contains a `data_stream` object, OpenSearch creates the data stream on the first indexing request: ```json POST logs-staging/_doc @@ -78,90 +88,50 @@ POST logs-staging/_doc "@timestamp": "2013-03-01T00:00:00" } ``` +{% include copy-curl.html %} -To see information about a specific data stream: +## Ingesting data into a data stream + +Index documents into a data stream by name, using the same [Document APIs]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index/) that you use for a regular index. Each document must contain the timestamp field defined by the template: ```json -GET _data_stream/logs-nginx -``` - -#### Example response - -```json -{ - "data_streams" : [ - { - "name" : "logs-nginx", - "timestamp_field" : { - "name" : "request_time" - }, - "indices" : [ - { - "index_name" : ".ds-logs-nginx-000001", - "index_uuid" : "-VhmuhrQQ6ipYCmBhn6vLw" - } - ], - "generation" : 1, - "status" : "GREEN", - "template" : "logs-template-nginx" - } - ] -} -``` - -You can see the name of the timestamp field, the list of the backing indexes, and the template that's used to create the data stream. You can also see the health of the data stream, which represents the lowest status of all its backing indexes. - -To see more insights about the data stream, use the `_stats` endpoint: - -```json -GET _data_stream/logs-nginx/_stats -``` - -#### Example response - -```json -{ - "_shards" : { - "total" : 1, - "successful" : 1, - "failed" : 0 - }, - "data_stream_count" : 1, - "backing_indices" : 1, - "total_store_size_bytes" : 208, - "data_streams" : [ - { - "data_stream" : "logs-nginx", - "backing_indices" : 1, - "store_size_bytes" : 208, - "maximum_timestamp" : 0 - } - ] -} -``` - -To see information about all data streams, use the following request: - -```json -GET _data_stream -``` - -### Step 3: Ingest data into the data stream - -To ingest data into a data stream, you can use the regular indexing APIs. Make sure every document that you index has a timestamp field. If you try to ingest a document that doesn't have a timestamp field, you get an error. - -```json -POST logs-redis/_doc +POST logs-redis/_doc?refresh=true { "message": "login attempt", "@timestamp": "2013-03-01T00:00:00" } ``` +{% include copy-curl.html %} -### Step 4: Searching a data stream +The `refresh=true` parameter makes the document searchable immediately, so that the search in the next section returns it. Omit it in production, where the [refresh interval]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) handles this. -You can search a data stream just like you search a regular index or an index alias. -The search operation applies to all of the backing indexes (all data present in the stream). +A data stream accepts only write requests for which the operation type is `create`. A `POST <data-stream>/_doc` request with an automatically generated document ID is a `create` operation. To specify a document ID, use the `_create` endpoint or set the `op_type=create` query parameter. A `PUT <data-stream>/_doc/<id>` request without `op_type=create` is an `index` operation and is rejected. The following request creates a document with the ID `1`: + +```json +PUT logs-redis/_create/1?refresh=true +{ + "message": "logout", + "@timestamp": "2013-03-01T00:05:00" +} +``` +{% include copy-curl.html %} + +In a [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) request, use the `create` action for each document. The `index` action is rejected for data streams: + +```json +POST _bulk?refresh=true +{ "create": { "_index": "logs-redis", "_id": "2" } } +{ "message": "session expired", "@timestamp": "2013-03-01T00:10:00" } +{ "create": { "_index": "logs-redis", "_id": "3" } } +{ "message": "password reset", "@timestamp": "2013-03-01T00:15:00" } +``` +{% include copy-curl.html %} + +Each item in the response shows the backing index that stores the document, for example, `"_index": ".ds-logs-redis-000001"`. + +## Searching a data stream + +Search a data stream as you would an index or an alias. The request covers all of the backing indexes: ```json GET logs-redis/_search @@ -173,34 +143,119 @@ GET logs-redis/_search } } ``` +{% include copy-curl.html %} -#### Example response +The `_index` field of each hit contains the name of the backing index that holds the document: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} ```json { - "took" : 514, - "timed_out" : false, - "_shards" : { - "total" : 5, - "successful" : 5, - "skipped" : 0, - "failed" : 0 + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 }, - "hits" : { - "total" : { - "value" : 1, - "relation" : "eq" + "hits": { + "total": { + "value": 1, + "relation": "eq" }, - "max_score" : 0.2876821, - "hits" : [ + "max_score": 0.13076457, + "hits": [ { - "_index" : ".ds-logs-redis-000001", - "_type" : "_doc", - "_id" : "-rhVmXoBL6BAVWH3mMpC", - "_score" : 0.2876821, - "_source" : { - "message" : "login attempt", - "@timestamp" : "2013-03-01T00:00:00" + "_index": ".ds-logs-redis-000001", + "_id": "iCnxtaABPpBDXMo4kFWl", + "_score": 0.13076457, + "_source": { + "message": "login attempt", + "@timestamp": "2013-03-01T00:00:00" + } + } + ] + } +} +``` +</details> + +You can also query a data stream using [asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/index/), [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/index/), or [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/), and build visualizations on it as you would on an index or an alias. + +## Updating and deleting documents in a data stream + +Single-document update and delete requests sent to the data stream name are rejected. To change documents in a data stream, use one of the following methods. + +### Updating or deleting documents by query + +The [Update by Query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-by-query/) and [Delete by Query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/delete-by-query/) APIs accept a data stream name and process the matching documents in all of its backing indexes. The following request changes the message of the document that contains `expired`: + +```json +POST logs-redis/_update_by_query?refresh=true +{ + "query": { + "match": { + "message": "expired" + } + }, + "script": { + "source": "ctx._source.message = \"session timed out\"" + } +} +``` +{% include copy-curl.html %} + +The following request deletes the document that contains `password`: + +```json +POST logs-redis/_delete_by_query?refresh=true +{ + "query": { + "match": { + "message": "password" + } + } +} +``` +{% include copy-curl.html %} + +### Updating or deleting a single document + +To update or delete a single document, send the request to the backing index that contains it. To find the backing index, search the data stream for the document. The following request returns the document with the ID `1`, along with its sequence number and primary term: + +```json +GET logs-redis/_search?seq_no_primary_term=true +{ + "query": { + "ids": { + "values": ["1"] + } + } +} +``` +{% include copy-curl.html %} + +The `_index` field of the hit contains the name of the backing index: + +```json +{ + ... + "hits": { + "hits": [ + { + "_index": ".ds-logs-redis-000001", + "_id": "1", + "_seq_no": 1, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "message": "logout", + "@timestamp": "2013-03-01T00:05:00" } } ] @@ -208,64 +263,181 @@ GET logs-redis/_search } ``` -### Step 5: Rollover a data stream +Send the update to the backing index. To prevent overwriting a change made after your search, include the `if_seq_no` and `if_primary_term` values from the search response: -A rollover operation creates a new backing index that becomes the data stream’s new write index. +```json +POST .ds-logs-redis-000001/_update/1?if_seq_no=1&if_primary_term=1&refresh=true +{ + "doc": { + "message": "logout requested" + } +} +``` +{% include copy-curl.html %} -To perform manual rollover operation on the data stream: +Similarly, to delete the document, send the request to the backing index: + +```json +DELETE .ds-logs-redis-000001/_doc/1?refresh=true +``` +{% include copy-curl.html %} + +## Rolling over a data stream + +A rollover creates a new backing index and makes it the write index of the data stream. Roll over manually with the following request: ```json POST logs-redis/_rollover ``` +{% include copy-curl.html %} -#### Example response +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} ```json { - "acknowledged" : true, - "shards_acknowledged" : true, - "old_index" : ".ds-logs-redis-000001", - "new_index" : ".ds-logs-redis-000002", - "rolled_over" : true, - "dry_run" : false, - "conditions" : { } + "acknowledged": true, + "shards_acknowledged": true, + "old_index": ".ds-logs-redis-000001", + "new_index": ".ds-logs-redis-000002", + "rolled_over": true, + "dry_run": false, + "conditions": {} } ``` +</details> -If you now perform a `GET` operation on the `logs-redis` data stream, you see that the generation ID is incremented from 1 to 2. +The generation number of the data stream increases with each rollover. For rollover conditions and parameters, see [Roll Over API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/rollover/). To roll over automatically, use an [ISM policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/). -You can also set up an [Index State Management (ISM) policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/) to automate the rollover process for the data stream. -The ISM policy is applied to the backing indexes at the time of their creation. When you associate a policy to a data stream, it only affects the future backing indexes of that data stream. +## Inspecting data streams -You also don’t need to provide the `rollover_alias` setting, because the ISM policy infers this information from the backing index. +The following table lists common data stream requests. The response to a get request contains the timestamp field name, the backing indexes, the generation number, the template that created the data stream, and its status, which is the lowest status of its backing indexes. -### Step 6: Manage data streams in OpenSearch Dashboards +| Task | Request | +| :--- | :--- | +| List all data streams | `GET _data_stream` | +| Get one data stream | `GET _data_stream/logs-redis` | +| Get statistics for a data stream | `GET _data_stream/logs-redis/_stats` | +| Delete a data stream and its backing indexes | `DELETE _data_stream/logs-redis` | -To manage data streams from OpenSearch Dashboards, open **OpenSearch Dashboards**, choose **Index Management**, select **Indices** or **Policy managed indices**. - -You see a toggle switch for data streams that you can use to show or hide indexes belonging to a data stream. - -When you enable this switch, you see a data stream multi-select dropdown menu that you can use for filtering data streams. -You also see a data stream column that shows you the name of the data stream the index is contained in. - -![data stream toggle]({{site.url}}{{site.baseurl}}/images/data_streams_toggle.png) - -You can select one or more data streams and apply an ISM policy on them. You can also apply a policy on any individual backing index. - -You can performing visualizations on a data stream just like you would on a regular index or index alias. - -### Step 7: Delete a data stream - -The delete operation first deletes the backing indexes of a data stream and then deletes the data stream itself. - -To delete a data stream and all of its hidden backing indexes: +For example, the following request returns the `logs-redis` data stream after one rollover: ```json -DELETE _data_stream/<name_of_data_stream> +GET _data_stream/logs-redis ``` +{% include copy-curl.html %} -You can use wildcards to delete more than one data stream. +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} -We recommend deleting data from a data stream using an ISM policy. +```json +{ + "data_streams": [ + { + "name": "logs-redis", + "timestamp_field": { + "name": "@timestamp" + }, + "indices": [ + { + "index_name": ".ds-logs-redis-000001", + "index_uuid": "Xq04oCQ-TiCjIL81Q_ZL9g" + }, + { + "index_name": ".ds-logs-redis-000002", + "index_uuid": "UBX0UhE9TFKTi-jB5mB7tQ" + } + ], + "generation": 2, + "status": "YELLOW", + "template": "logs-template" + } + ] +} +``` +</details> -You can also use [asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/index/), [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/index/), and [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) to query your data stream directly. You can also use the Security plugin to define granular permissions for the data stream name. +You can use wildcards to address more than one data stream. Deleting a data stream deletes its backing indexes and cannot be undone; to remove data on a schedule, use an ISM policy instead. +{: .warning} + +For all data stream operations and their parameters, see [Data stream APIs]({{site.url}}{{site.baseurl}}/api-reference/data-stream/). + +## Modifying the backing indexes of a data stream + +Add or remove the backing indexes of an existing data stream using the [Modify Data Stream API]({{site.url}}{{site.baseurl}}/api-reference/data-stream/modify-data-stream/). This is a metadata-only operation, so you can migrate an existing regular index into a data stream, or detach a backing index without deleting its data. To attach a restored backing index to a data stream during a snapshot restore, set `attach_to_data_stream` to `true` in the [Restore Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/restore-snapshot/). + +## Data streams in OpenSearch Dashboards + +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Data streams** to list the data streams in your cluster. + +The **Data streams** table contains the following columns. + +| Column | Description | +| :--- | :--- | +| **Data stream name** | The name of the data stream. | +| **Status** | The lowest health status of the data stream's backing indexes: green if all primary and replica shards are assigned, yellow if at least one replica shard is unassigned, and red if at least one primary shard is unassigned. | +| **Template** | The index template that created the data stream. | +| **Backing indexes count** | The number of backing indexes that hold the data. | +| **Total size** | The storage used by the data stream across all primary and replica shards. | + +The following image shows the **Data streams** page. + +![Data streams page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/data-streams-list.png) + +### Viewing a data stream + +Select the data stream in the **Data stream name** column. **Data stream details** shows its name, status, template, number of backing indexes, and timestamp field name. **Backing indexes** lists each backing index with its health, status, size, document counts, shard counts, whether it is the write index, and whether an ISM policy manages it. Select a backing index to see its details in the same form as a regular index. For more information, see [Viewing index details]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#viewing-index-details). + +### Viewing backing indexes in the Indexes list + +Backing indexes are hidden from the **Indexes** table by default: + +1. In **Index Management**, select **Indexes**. +1. Select **Show data stream indexes**. A **Data stream** column is added to the table, showing which data stream each backing index belongs to, and a **Data streams** list is added to the table header. +1. Optionally, select one or more data streams from the **Data streams** list to show only their backing indexes. + +### Creating a data stream + +A data stream can only be created from an index template whose type is **Data streams**. To create one, see [Creating an index template]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/#creating-an-index-template-1). + +1. In **Index Management**, select **Data streams**, and then select **Create data stream**. +1. In **Data stream name**, start entering a name. As you type, a list of matching index patterns and their index templates appears. +1. Select an index pattern from the list, and then complete the name so that it matches the pattern. + + **Matching template** shows the index template that contains the pattern. The values in **Inherited settings from template** are read-only. + +1. Select **Create data stream**. + +### Deleting a data stream + +1. In **Index Management**, select **Data streams**. +1. Select the checkbox next to each data stream that you want to delete. +1. Select **Actions**, and then select **Delete**. +1. Enter `delete` in the confirmation dialog, and then select **Delete**. + +Deleting a data stream deletes its backing indexes. The data cannot be recovered. +{: .warning} + +### Rolling over a data stream + +1. In **Index Management**, select **Data streams**. +1. Select **Actions**, and then select **Roll over**. +1. In **Configure source**, select the data stream to roll over. +1. Select **Roll over**. + +The **Backing indexes** table on the details page of the data stream contains the new write index. + +Refresh, flush, clear cache, and force merge are also available from the **Data streams** page and apply to the backing indexes of the selected data streams. For those procedures, see [Index maintenance in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#index-maintenance-in-opensearch-dashboards). + +## Related documentation + +- [Data stream APIs]({{site.url}}{{site.baseurl}}/api-reference/data-stream/) +- [Index templates]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/) +- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) +- [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) diff --git a/_im-plugin/index-alias.md b/_im-plugin/index-alias.md index 1816b0e0..b7841f07 100644 --- a/_im-plugin/index-alias.md +++ b/_im-plugin/index-alias.md @@ -1,40 +1,56 @@ --- layout: default title: Index aliases -nav_order: 11 +nav_order: 20 redirect_from: - /opensearch/index-alias/ --- # Index aliases -An alias is a virtual index name that can point to one or more indexes. +An alias is a virtual index name that points to one or more indexes. Query the alias and OpenSearch resolves it to the indexes behind it, so your clients can keep using one stable name while the indexes it covers change. -If your data is spread across multiple indexes, rather than keeping track of which indexes to query, you can create an alias and query it instead. +For example, if you store logs in monthly indexes and you usually query the last two months, create a `last_2_months` alias and update the indexes it points to each month. The queries in your application never change. -For example, if you’re storing logs into indexes based on the month and you frequently query the logs for the previous two months, you can create a `last_2_months` alias and update the indexes it points to each month. +Aliases are also how you do the following: -Because you can change the indexes an alias points to at any time, referring to indexes using aliases in your applications allows you to reindex your data without any downtime. +- Switch from one index to another with no downtime, such as when you reindex into a new mapping and cut over once the copy is complete. +- Serve different views of the same data by attaching a filter to the alias. +- Keep environment-specific names, such as `production-data` and `staging-data`, independent of the indexes they resolve to. +- Route the requests that go through the alias to specific shards, so that a search reads fewer shards. For more information, see [Manage aliases]({{site.url}}{{site.baseurl}}/api-reference/alias/aliases-api/#example-basic-routing). +- Roll over time-series indexes behind a single write target. See [Rolling over an index]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#rolling-over-an-index). -## Create aliases +Aliases have the following characteristics: -To create an alias, use a POST request: +- Alias changes are atomic. An alias never points to an unintended set of indexes, even for a moment. +- A wildcard pattern is resolved when the alias is created. Indexes created later that match the pattern are not added automatically. +- To write to an alias that points to more than one index, designate one of them as the write index. +- The filter on a filtered alias applies to all search, count, and delete-by-query operations through that alias. + +## Creating an alias + +The examples in this section use two indexes, which you can create with the following requests: ```json -POST _aliases +PUT /logs-2024-01 ``` {% include copy-curl.html %} -Use the `actions` method to specify the list of actions that you want to perform. This command creates an alias named `alias1` and adds `index-1` to this alias: +```json +PUT /logs-2024-02 +``` +{% include copy-curl.html %} + +The most basic alias points to a single index: ```json -POST _aliases +POST /_aliases { "actions": [ { "add": { - "index": "index-1", - "alias": "alias1" + "index": "logs-2024-01", + "alias": "current-logs" } } ] @@ -42,62 +58,37 @@ POST _aliases ``` {% include copy-curl.html %} -The following response is returned: +You can also attach aliases when you create the index: ```json +PUT /logs-2024-03 { - "acknowledged": true + "aliases": { + "current-logs": {}, + "all-logs": {} + } } ``` {% include copy-curl.html %} -If the request fails, make sure the index that you're adding to the alias already exists. +## Switching an alias to a different index -You can also create an alias using one of the following requests: +Combine `remove` and `add` in one request so that the alias moves between indexes in a single atomic step: ```json -PUT <index>/_aliases/<alias name> -POST <index>/_aliases/<alias name> -PUT <index>/_alias/<alias name> -POST <index>/_alias/<alias name> -``` -{% include copy-curl.html %} - -The `<index>` in the above requests can be an index name, a comma-separated list of index names, or a wildcard expression. Use `_all` to refer to all indexes. - -To check if `alias1` refers to `index-1`, run one of the following commands: - -```json -GET /_alias/alias1 -GET /index-1/_alias/alias1 -``` -{% include copy-curl.html %} - -To get the indexes' mappings and settings information referenced by the alias, run the following command: - -```json -GET alias1 -``` -{% include copy-curl.html %} - -## Add or remove indexes - -You can perform multiple actions using the same `_aliases` operation. For example, the following command removes `index-1` and adds `index-2` to `alias1`: - -```json -POST _aliases +POST /_aliases { "actions": [ { "remove": { - "index": "index-1", - "alias": "alias1" + "index": "logs-2024-01", + "alias": "current-logs" } }, { "add": { - "index": "index-2", - "alias": "alias1" + "index": "logs-2024-02", + "alias": "current-logs" } } ] @@ -105,16 +96,18 @@ POST _aliases ``` {% include copy-curl.html %} -The `add` and `remove` actions occur atomically, which means that at no point will `alias1` point to both `index-1` and `index-2`. You can also add indexes based on an index pattern, as shown in the following POST request: +## Pointing an alias to multiple indexes + +Use the `indices` field to cover several indexes with one alias: ```json -POST _aliases +POST /_aliases { "actions": [ { "add": { - "index": "index*", - "alias": "alias1" + "indices": ["logs-2024-01", "logs-2024-02"], + "alias": "recent-logs" } } ] @@ -122,19 +115,25 @@ POST _aliases ``` {% include copy-curl.html %} -The `remove` action also supports the `must_exist` parameter. If the parameter is set to `true` and the specified alias does not exist, an exception is thrown. If the parameter is set to `false`, then no action is taken if the specified alias does not exist. The default value for `must_exist` is `null`. An exception will be thrown only if none of the specified aliases exist. +## Designating a write index -The following POST request uses the `remove` action with the `must_exist` parameter set to `true`: +An alias that points to multiple indexes rejects indexing requests until one of those indexes is marked as the write index: ```json -POST _aliases +POST /_aliases { "actions": [ { - "remove": { - "index": "index-1", - "alias": "alias1", - "must_exist": true + "add": { + "index": "logs-2024-02", + "alias": "active-logs", + "is_write_index": true + } + }, + { + "add": { + "index": "logs-2024-01", + "alias": "active-logs" } } ] @@ -142,95 +141,37 @@ POST _aliases ``` {% include copy-curl.html %} -## Manage aliases +## Filtering an alias -To list the mapping of aliases to indexes, run the following command: - -```json -GET _cat/aliases?v -``` -{% include copy-curl.html %} - -#### Example response - -```json -alias index filter routing.index routing.search -alias1 index-1 * - - -``` -{% include copy-curl.html %} - -To check which indexes an alias points to, run the following command: - -```json -GET _alias/alias1 -``` -{% include copy-curl.html %} - -#### Example response +Attach a filter to an alias to expose a subset of an index under its own name. Create an index with a `level` field to filter on: ```json +PUT /application-logs { - "index-2": { - "aliases": { - "alias1": {} + "mappings": { + "properties": { + "level": { + "type": "keyword" + } } } } ``` {% include copy-curl.html %} -Conversely, to find which alias points to a specific index, run the following command: +The following alias returns only the documents in `application-logs` whose `level` field is `ERROR`: ```json -GET /index-2/_alias/* -``` -{% include copy-curl.html %} - -To get all index names and their aliases, run the following command: - -```json -GET /_alias -``` -{% include copy-curl.html %} - -To check if an alias exists, run one of the following commands: - -```json -HEAD /alias1/_alias/ -HEAD /_alias/alias1/ -HEAD index-1/_alias/alias1/ -``` -{% include copy-curl.html %} - -## Add aliases at index creation - -You can add an index to an alias as you create the index, as shown in the following PUT request: - -```json -PUT index-1 -{ - "aliases": { - "alias1": {} - } -} -``` -{% include copy-curl.html %} - -## Create filtered aliases - -You can create a filtered alias to access a subset of documents or fields in the underlying indexes. This command adds only a specific timestamp field to `alias1`. The following shows an example POST request: - -```json -POST _aliases +POST /_aliases { "actions": [ { "add": { - "index": "index-1", - "alias": "alias1", + "index": "application-logs", + "alias": "error-logs", "filter": { "term": { - "timestamp": "1574641891142" + "level": "ERROR" } } } @@ -240,35 +181,66 @@ POST _aliases ``` {% include copy-curl.html %} -## Index alias options +## Inspecting and querying aliases -You can specify the options shown in the following table. +The following table lists common alias requests. -Option | Valid values | Description | Required -:--- | :--- | :--- -`index` | String | The name of the index that the alias points to. | Yes -`alias` | String | The name of the alias. | No -`filter` | Object | Add a filter to the alias. | No -`routing` | String | Limit search to an associated shard value. You can specify `search_routing` and `index_routing` independently. | No -`is_write_index` | String | Specify the index that accepts any write operations to the alias. If this value is not specified, then no write operations are allowed. | No +| Task | Request | +| :--- | :--- | +| List all aliases | `GET /_cat/aliases?v` | +| Get one alias | `GET /_alias/current-logs` | +| Check whether an alias exists | `HEAD /_alias/current-logs` | +| Search through an alias | `GET /current-logs/_search` | -## Delete aliases +For all alias operations and their parameters, see [Alias APIs]({{site.url}}{{site.baseurl}}/api-reference/alias/). -To delete one or more aliases from an index, use the following request: +## Index aliases in OpenSearch Dashboards -```json -DELETE <index>/_alias/<alias> -DELETE <index>/_aliases/<alias> -``` -{% include copy-curl.html %} +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Aliases** to list the aliases in your cluster, with the write index and the indexes of each one. -Both `<index>` and `<alias>` in the above request support comma-separated lists and wildcard expressions. Use `_all` in place of `<alias>` to delete all aliases for the indexes listed in `<index>`. +The following image shows the **Aliases** page. -For example, if `alias1` refers to `index-1` and `index-2`, you can run the following command to remove `alias1` from `index-1`: +![Aliases page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/aliases-list.png) -```json -DELETE index-1/_alias/alias1 -``` -{% include copy-curl.html %} +### Creating an alias -After running the request, `alias1` no longer refers to `index-1` but still refers to `index-2`. +An alias covers at least one index, so create the indexes before the alias. To create an index, see [Creating an index]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#creating-an-index-1). + +1. In **Index Management**, select **Aliases**, and then select **Create alias**. +1. Enter a name for the alias. +1. In **Indexes or index patterns**, select or enter the indexes and index patterns that the alias covers. +1. Select **Create alias**. + +### Editing an alias + +1. In **Index Management**, select **Aliases**. +1. Select the alias name in the **Alias name** column. +1. In **Indexes or index patterns**, add or remove indexes and index patterns. You cannot rename an existing alias. +1. Select **Save changes**. + +### Deleting an alias + +1. In **Index Management**, select **Aliases**. +1. Select the checkbox next to each alias that you want to delete. +1. Select **Actions**, and then select **Delete**. +1. Enter `delete` in the confirmation dialog, and then select **Delete**. + +Deleting an alias does not delete the indexes behind it. + +### Rolling over an alias + +1. In **Index Management**, select **Aliases**. +1. Select **Actions**, and then select **Roll over**. +1. In **Configure source**, select the alias to roll over. Its current write index is displayed as **Assigned source index**. +1. In **Configure new rollover index**, enter a name for the new write index, then enter its definition, settings, and mappings. To reuse the configuration of the current write index, select **Import from old write index**. +1. Select **Roll over**. + +The **Write index** column shows the new write index, and the **Index name** column lists all of the indexes in the alias. + +Refresh, flush, clear cache, and force merge are also available from the **Aliases** page and apply to the open backing indexes of the selected aliases. For those procedures, see [Index maintenance in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#index-maintenance-in-opensearch-dashboards). + +## Related documentation + +- [Alias APIs]({{site.url}}{{site.baseurl}}/api-reference/alias/) +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) diff --git a/_im-plugin/index-codecs.md b/_im-plugin/index-codecs.md index f880e141..77878a8d 100644 --- a/_im-plugin/index-codecs.md +++ b/_im-plugin/index-codecs.md @@ -1,40 +1,61 @@ --- layout: default title: Index codecs -nav_order: 3 -parent: Index settings +parent: Tuning indexes +nav_order: 30 --- # Index codecs -Index codecs determine how the index’s stored fields are compressed and stored on disk. The index codec is controlled by the static `index.codec` setting that specifies the compression algorithm. The setting impacts the index shard size and index operation performance. +Index codecs determine how the index's stored fields are compressed and stored on disk. The index codec is controlled by the static `index.codec` setting that specifies the compression algorithm. The setting impacts the index shard size and index operation performance. ## Supported codecs -OpenSearch provides support for four codecs that can be used for compressing the stored fields. Each codec offers different tradeoffs between compression ratio (storage size) and indexing performance (speed): +OpenSearch provides support for four codecs that can be used for compressing the stored fields. Each codec offers different trade-offs between compression ratio (storage size) and indexing performance (speed): -* `default` -- This codec employs the [LZ4 algorithm](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) with a preset dictionary, which prioritizes performance over compression ratio. It offers faster indexing and search operations when compared with `best_compression` but may result in larger index/shard sizes. If no codec is provided in the index settings, then LZ4 is used as the default algorithm for compression. -* `best_compression` -- This codec uses [zlib](https://en.wikipedia.org/wiki/Zlib) as an underlying algorithm for compression. It achieves high compression ratios that result in smaller index sizes. However, this may incur additional CPU usage during index operations and may subsequently result in high indexing and search latencies. +* `default` -- This codec employs the [`LZ4` algorithm](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) with a preset dictionary, which prioritizes performance over compression ratio. It offers faster indexing and search operations when compared with `best_compression` but may result in larger index/shard sizes. If no codec is provided in the index settings, then `LZ4` is used as the default algorithm for compression. +* `best_compression` -- This codec uses [`zlib`](https://en.wikipedia.org/wiki/Zlib) as an underlying algorithm for compression. It achieves high compression ratios that result in smaller index sizes. However, this may incur additional CPU usage during index operations and may subsequently result in high indexing and search latencies. -As of OpenSearch 2.9, two new codecs based on the [Zstandard compression algorithm](https://github.com/facebook/zstd) are available. This algorithm provides a good balance between compression ratio and speed. +OpenSearch also provides two codecs based on the [Zstandard compression algorithm](https://github.com/facebook/zstd) are available. This algorithm provides a good balance between compression ratio and speed. It may be challenging to change the codec setting of an existing index (see [Changing an index codec](#changing-an-index-codec)), so it is important to test a representative workload in a non-production environment before using a new codec setting. {: .important} -* `zstd` (OpenSearch 2.9 and later) -- This codec provides significant compression comparable to the `best_compression` codec with reasonable CPU usage and improved indexing and search performance compared to the `default` codec. -* `zstd_no_dict` (OpenSearch 2.9 and later) -- This codec is similar to `zstd` but excludes the dictionary compression feature. It provides faster indexing and search operations compared to `zstd` at the expense of a slightly larger index size. +* `zstd` -- This codec provides significant compression comparable to the `best_compression` codec with reasonable CPU usage and improved indexing and search performance compared to the `default` codec. +* `zstd_no_dict` -- This codec is similar to `zstd` but excludes the dictionary compression feature. It provides faster indexing and search operations compared to `zstd` at the expense of a slightly larger index size. -As of OpenSearch 2.10, the `zstd` and `zstd_no_dict` compression codecs cannot be used for [k-NN]({{site.url}}{{site.baseurl}}/search-plugins/knn/index/) or [Security Analytics]({{site.url}}{{site.baseurl}}/security-analytics/index/) indexes. +The `zstd` and `zstd_no_dict` compression codecs cannot be used for [k-NN]({{site.url}}{{site.baseurl}}/search-plugins/knn/index/) or [Security Analytics]({{site.url}}{{site.baseurl}}/security-analytics/index/) indexes. {: .warning} -For the `zstd` and `zstd_no_dict` codecs, you can optionally specify a compression level in the `index.codec.compression_level` setting. This setting takes integers in the [1, 6] range. A higher compression level results in a higher compression ratio (smaller storage size) with a tradeoff in speed (slower compression and decompression speeds lead to greater indexing and search latencies). +For the `zstd` and `zstd_no_dict` codecs, you can optionally specify a compression level in the `index.codec.compression_level` setting. This setting takes integers in the [1, 6] range. A higher compression level results in a higher compression ratio (smaller storage size) with a trade-off in speed (slower compression and decompression speeds lead to greater indexing and search latencies). When an index segment is created, it uses the current index codec for compression. If you update the index codec, any segment created after the update will use the new compression algorithm. For specific operation considerations, see [Index codec considerations for index operations](#index-codec-considerations-for-index-operations). {: .note} +Hardware-accelerated compression codecs for the `DEFLATE` and `LZ4` compression algorithms are available. These hardware-accelerated codecs are available on the latest 4th and 5th Gen Intel®️ Xeon®️ processors running Linux kernel 3.10 and later. For all other systems and platforms, the codecs use that platform's corresponding software implementations. + +The hardware-accelerated codecs can be used by setting one of the following `index.codec` values: +* `qat_lz4`: Hardware-accelerated `LZ4` +* `qat_deflate`: Hardware-accelerated `DEFLATE` +* `qat_zstd`: Hardware-accelerated `ZSTD` + +The `qat_deflate` codec offers a much better compression ratio than `qat_lz4`, with a modest drop in compression and decompression speed. The `qat_zstd` codec uses hardware acceleration for compression but relies on software-based decompression. +{: .note} + +The `index.codec.compression_level` setting can be used to specify the compression level for both `qat_lz4`, `qat_deflate`, and `qat_zstd`. + +The `index.codec.qatmode` setting controls the behavior of the hardware accelerator and uses one of the following values: + +* `auto`: If hardware acceleration fails, then the algorithm switches to software acceleration. +* `hardware`: Guarantees hardware-only compression. If hardware is not available, then an exception occurs until hardware exists. + +For information about the `index.codec.qatmode` setting's effects on snapshots, see the [Snapshots](#snapshots) section. + +For more information about hardware acceleration on Intel, see the [Intel (R) QAT accelerator overview](https://www.intel.com/content/www/us/en/developer/topic-technology/open/quick-assist-technology/overview.html). + ## Choosing a codec -The choice of index codec impacts the amount of disk space required to store the index data. Codecs like `best_compression`, `zstd`, and `zstd_no_dict` can achieve higher compression ratios, resulting in smaller index sizes. Conversely, the `default` codec doesn’t prioritize compression ratio, resulting in larger index sizes but faster search operations than `best_compression`. +The choice of index codec impacts the amount of disk space required to store the index data. Codecs like `best_compression`, `zstd`, and `zstd_no_dict` can achieve higher compression ratios, resulting in smaller index sizes. Conversely, the `default` codec doesn't prioritize compression ratio, resulting in larger index sizes but faster search operations than `best_compression`. ## Index codec considerations for index operations @@ -58,6 +79,11 @@ When creating a [snapshot]({{site.url}}{{site.baseurl}}/tuning-your-cluster/avai When you restore the indexes from a snapshot of a cluster to another cluster, it is important to verify that the target cluster supports the codecs of the segments in the source snapshot. For example, if the source snapshot contains segments of the `zstd` or `zstd_no_dict` codecs (introduced in OpenSearch 2.9), you won't be able to restore the snapshot to a cluster that runs on an older OpenSearch version because it doesn't support these codecs. +For hardware-accelerated compression codecs, available in OpenSearch 2.15 and later, the value of `index.codec.qatmode` affects how snapshots and restores are performed. If the value is `auto` (the default), then snapshots and restores work without issue. However, if the value is `hardware`, then it must be reset to `auto` in order for the restore process to succeed on systems lacking the hardware accelerator. + +You can modify the value of `index.codec.qatmode` during the restore process by setting its value as follows: `"index_settings": {"index.codec.qatmode": "auto"}`. +{: .note} + ### Reindexing When you are performing a [reindex]({{site.url}}{{site.baseurl}}/im-plugin/reindex-data/) operation from a source index, the new segments created in the target index will have the properties of the codec settings of the target index. @@ -76,7 +102,7 @@ Depending on your specific use case, you might need to experiment with different ### Benchmarking -The following table provides a performance comparison of the `best_compression`, `zstd`, and `zstd_no_dict` codecs against the `default` codec. The tests were performed with the [`nyc_taxi`](https://github.com/topics/nyc-taxi-dataset) dataset. The results are listed in terms of percent change, and bold results indicate performance improvement. +The following table provides a performance comparison of the `best_compression`, `zstd`, and `zstd_no_dict` codecs against the `default` codec. The tests were performed with the [`nyc_taxi`](https://github.com/toddwschneider/nyc-taxi-data) dataset. The results are listed in terms of percent change, and bold results indicate performance improvement. | | `best_compression` | `zstd` | `zstd_no_dict` | |:--- |:--- |:--- |:--- | diff --git a/_im-plugin/index-context.md b/_im-plugin/index-context.md new file mode 100644 index 00000000..9cc2b226 --- /dev/null +++ b/_im-plugin/index-context.md @@ -0,0 +1,180 @@ +--- +layout: default +title: Index context +parent: Tuning indexes +nav_order: 50 +redirect_from: + - /opensearch/index-context/ +--- + +# Index context +**Introduced 2.17** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +Index context declares the use case for an index. Using the context information, OpenSearch applies a predetermined set of settings and mappings, which provides the following benefits: + +- Optimized performance +- Settings tuned to your specific use case +- Accurate mappings and aliases based on [OpenSearch Integrations]({{site.url}}{{site.baseurl}}/integrations/) + +The settings and metadata configuration that are applied using component templates are automatically loaded when your cluster starts. Component templates that start with `@abc_template@` or Application-Based Configuration (ABC) templates can only be used through a `context` object declaration, in order to prevent configuration issues. +{: .warning} + +## Enabling index context + +Index context requires two settings, both of which are applied at node startup. Enable both on every node in the cluster, and then restart the nodes: + +1. Set the `opensearch.experimental.feature.application_templates.enabled` feature flag to `true`. For more information, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). + +2. Add the following line to `opensearch.yml`: + + ```yaml + cluster.application_templates.enabled: true + ``` + {% include copy.html %} + +Do not set `cluster.application_templates.enabled` using the [Cluster settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/). The API accepts the update and returns `200`, but the node then fails to apply the resulting cluster state, logging an error that the feature flag is not enabled. The node repeatedly gives up its cluster manager role, and every request that changes the cluster state, such as creating an index, stops responding until you restart the node. If you set the value as a persistent setting, it is reapplied after the restart. +{: .warning} + +The `opensearch-system-templates` plugin supplies the component templates that back each context. It is bundled with all OpenSearch distributions except the minimal distribution. If you use the minimal distribution, install it using one of the [installation methods]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#installing-plugins). + +## Using the `context` setting + +Use the `context` setting with the Index API to add use-case-specific context. + +### Considerations + +Consider the following when using the `context` parameter during index creation: + +- If you use the `context` parameter to create an index, you cannot include any settings declared in the index context during index creation or dynamic settings updates. +- The index context becomes permanent when set on an index or index template. + +When you adhere to these limitations, suggested configurations or mappings are uniformly applied on indexed data within the specified context. + +If `cluster.application_templates.enabled` is not enabled, a request that declares a context is rejected with `400`. + +### Examples + +The following examples show how to use index context. + +#### Create an index + +The following example request creates an index in which to store metric data by declaring a `metrics` mapping as the context: + +```json +PUT /my-metrics-index +{ + "context": { + "name": "metrics" + } +} +``` +{% include copy-curl.html %} + +After creation, the context is added to the index and the corresponding settings are applied. To confirm this, send the following request: + +```json +GET /my-metrics-index +``` +{% include copy-curl.html %} + +The response contains the context and the settings that it applied: + +```json +{ + "my-metrics-index": { + "aliases": {}, + "mappings": {}, + "settings": { + "index": { + "codec": "zstd_no_dict", + "refresh_interval": "60s", + "number_of_shards": "1", + "provided_name": "my-metrics-index", + "merge": { + "policy": "log_byte_size" + }, + "context": { + "created_version": "1", + "current_version": "1" + }, + ... + } + }, + "context": { + "name": "metrics", + "version": "_latest" + } + } +} +``` + + +#### Create an index template + +You can also use the `context` parameter when creating an index template. The following example request creates an index template with the context information as `logs`: + +```json +PUT _index_template/my-logs +{ + "context": { + "name": "logs", + "version": "1" + }, + "index_patterns": [ + "my-logs-*" + ] +} +``` +{% include copy-curl.html %} + +All indexes created using this index template will get the metadata provided by the associated component template. To confirm that `context` was added to the template, send the following request: + +```json +GET _index_template/my-logs +``` +{% include copy-curl.html %} + +The response contains the context: + +```json +{ + "index_templates": [ + { + "name": "my-logs", + "index_template": { + "index_patterns": [ + "my-logs-*" + ], + "context": { + "name": "logs", + "version": "1" + } + } + } + ] +} +``` + +If there is any conflict between any settings, mappings, or aliases directly declared by your template and the backing component template for the context, the latter gets higher priority during index creation. + + +## Available context templates + +The following templates can be used through the `context` parameter: + +- `logs` +- `metrics` +- `nginx-logs` +- `amazon-cloudtrail-logs` +- `amazon-elb-logs` +- `amazon-s3-logs` +- `apache-web-logs` +- `k8s-logs` + +For more information about these templates, see the [OpenSearch system templates repository](https://github.com/opensearch-project/opensearch-system-templates/tree/main/src/main/resources/org/opensearch/system/applicationtemplates/v1). + +To view the current version of these templates on your cluster, use `GET /_component_template`. diff --git a/_im-plugin/index-maintenance.md b/_im-plugin/index-maintenance.md new file mode 100644 index 00000000..31be6fa4 --- /dev/null +++ b/_im-plugin/index-maintenance.md @@ -0,0 +1,296 @@ +--- +layout: default +title: Index maintenance +nav_order: 10 +redirect_from: + - /dashboards/im-dashboards/forcemerge/ + - /dashboards/im-dashboards/rollover/ + - /dashboards/admin-ui-index/forcemerge/ + - /dashboards/admin-ui-index/rollover/ +--- + +# Index maintenance + +OpenSearch refreshes indexes, flushes the translog, and merges segments in the background, so most clusters never need these operations to be run by hand. Run them yourself when you need a result at a specific moment: making a document searchable immediately after indexing it, reclaiming disk space from deleted documents before a snapshot, or changing the shard count of an index that has outgrown its original layout. + +Each operation is available through the [index operations APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-operations/) and, except for cloning, from the **Index Management** page in OpenSearch Dashboards. + +For lifecycle operations such as creating, opening, closing, and deleting an index, see [Index operations]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/). + +The examples on this page operate on an index named `logs-2026` with two primary shards, which you can create with the following request: + +```json +PUT /logs-2026 +{ + "settings": { + "index.number_of_shards": 2, + "index.number_of_replicas": 0 + } +} +``` +{% include copy-curl.html %} + +## Refreshing an index + +A refresh writes the documents in the in-memory buffer to a new segment, making them visible to search. OpenSearch refreshes each index every second by default, so a document becomes searchable about a second after you index it. Refresh an index manually when a test or a client needs to search a document immediately after writing it: + +```json +POST /logs-2026/_refresh +``` +{% include copy-curl.html %} + +Refreshing creates a segment each time it runs, so refreshing frequently during a bulk load slows indexing. When you load a large amount of data, set `index.refresh_interval` to `-1` for the duration of the load and refresh once at the end. For more information, see [Refresh index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/refresh/). + +A refresh applies only to open indexes. + +## Flushing an index + +A flush performs a Lucene commit, writing the segments in the file system cache to disk and starting a new translog. This is what makes indexed data durable across a node restart. OpenSearch flushes automatically based on translog size and age: + +```json +POST /logs-2026/_flush +``` +{% include copy-curl.html %} + +Flush manually before you shut a node down for maintenance so that recovery does not have to replay a large translog. For more information, see [Flush]({{site.url}}{{site.baseurl}}/api-reference/index-apis/flush/). + +A flush applies only to open indexes. + +## Clearing an index cache + +OpenSearch caches field data, query results, and request-level aggregation results to speed up repeated searches. Clearing these caches frees heap memory but makes the next searches slower until the caches refill: + +```json +POST /logs-2026/_cache/clear +``` +{% include copy-curl.html %} + +To clear one cache instead of all of them, use the `fielddata`, `query`, or `request` query parameter. For more information, see [Clear cache]({{site.url}}{{site.baseurl}}/api-reference/index-apis/clear-index-cache/). + +Clearing a cache applies only to open indexes. + +## Force merging an index + +OpenSearch stores an index as a set of immutable segments and merges smaller segments into larger ones in the background. A deleted document is only marked as deleted; its space is reclaimed when the segment containing it is merged. A force merge runs that merge immediately, reducing the segment count and expunging deleted documents: + +```json +POST /logs-2026/_forcemerge?max_num_segments=1 +``` +{% include copy-curl.html %} + +Force merging is expensive in I/O and can produce segments that the automatic merge policy never merges again. Run it only on indexes that no longer receive writes, such as a rolled-over time-series index. For more information, see [Force merge]({{site.url}}{{site.baseurl}}/api-reference/index-apis/force-merge/). + +## Shrinking an index + +Shrinking copies an index into a new index with fewer primary shards. Shrink an index that was created with more shards than its final size warrants, because the number of primary shards of an existing index cannot be changed in place. + +First, block write operations on the source index. Shrinking an index that still accepts writes fails with an `illegal_state_exception`: + +```json +PUT /logs-2026/_settings +{ + "index.blocks.write": true +} +``` +{% include copy-curl.html %} + +Then shrink the index: + +```json +POST /logs-2026/_shrink/logs-2026-shrunk +{ + "settings": { + "index.number_of_shards": 1 + } +} +``` +{% include copy-curl.html %} + +The source index must meet the following conditions: + +- The index is read-only, with a write block set. See [Blocks]({{site.url}}{{site.baseurl}}/api-reference/index-apis/blocks/). +- A copy of every shard, primary or replica, resides on the same node. Use [shard allocation filtering]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shard-allocation/) to move the copies together. +- Every shard of the source index is allocated, that is, the index health is not red. +- The target index does not already exist. +- The source index has more primary shards than the target index, and the target shard count is a factor of the source shard count. For example, an index with 8 primary shards can be shrunk to 4, 2, or 1. An index with a prime number of shards, such as 7, can be shrunk only to 1. +- No single target shard receives more than 2,147,483,519 documents, which is the maximum a Lucene shard can hold. +- The node performing the shrink has enough free disk space for a second copy of the index. + +For more information, see [Shrink index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/shrink-index/). + +## Splitting an index + +Splitting copies an index into a new index with more primary shards, dividing each source shard into several target shards. Split an index that has outgrown its original shard count and needs more capacity for data volume or query load. Splitting also requires a write block on the source index: + +```json +PUT /logs-2026/_settings +{ + "index.blocks.write": true +} +``` +{% include copy-curl.html %} + +Then split the index: + +```json +POST /logs-2026/_split/logs-2026-split +{ + "settings": { + "index.number_of_shards": 4 + } +} +``` +{% include copy-curl.html %} + +The source index must meet the following conditions: + +- The index is read-only, with a write block set. See [Blocks]({{site.url}}{{site.baseurl}}/api-reference/index-apis/blocks/). +- Every shard of the source index is allocated, that is, the index health is not red. +- The target index does not already exist. +- The source index has fewer primary shards than the target index, and the target shard count is a multiple of the source shard count. For example, an index with 2 primary shards can be split into 4, 6, or 8. An index with 1 primary shard can be split into any number of shards. +- The node performing the split has enough free disk space for a second copy of the index. + +For more information, see [Split index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/split/). + +## Cloning an index + +Cloning copies an index into a new index with the same number of primary shards, mappings, and settings. Clone an index to test a mapping or settings change against real data without touching the original. Like shrinking and splitting, cloning requires a write block on the source index: + +```json +PUT /logs-2026/_settings +{ + "index.blocks.write": true +} +``` +{% include copy-curl.html %} + +Then clone the index: + +```json +POST /logs-2026/_clone/logs-2026-copy +``` +{% include copy-curl.html %} + +Remove the write block when you are finished by setting `index.blocks.write` to `false`. + +For more information, see [Clone index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/clone/). Cloning is available only through the API. + +## Rolling over an index + +A rollover creates a new index and redirects the write alias or data stream to it, so that writes continue against a fresh index while the previous one becomes read-only. This keeps individual time-series indexes at a manageable size and lets you delete or archive old data by dropping whole indexes. + +A rollover target must be a [data stream]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) or an [index alias]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/) with a designated write index. Create an index whose name ends in a number and point a write alias at it: + +```json +PUT /logs-000001 +{ + "aliases": { + "logs": { + "is_write_index": true + } + } +} +``` +{% include copy-curl.html %} + +The following request rolls over the `logs` alias when its write index reaches 50 GB, 10 million documents, or 7 days of age: + +```json +POST /logs/_rollover +{ + "conditions": { + "max_size": "50gb", + "max_docs": 10000000, + "max_age": "7d" + } +} +``` +{% include copy-curl.html %} + +None of the conditions are met on a new index, so the response reports `"rolled_over": false`. For more information, see [Roll over index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/rollover/). + +To roll over on a schedule instead of calling the API when a condition is met, define an [Index State Management policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) with a `rollover` action. ISM evaluates the conditions for you and rolls the index over when they are met. + +## Index maintenance in OpenSearch Dashboards + +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. The maintenance operations for the selected indexes are in the **Actions** menu on the **Indexes** page, as shown in the following image. + +![Actions menu on the Indexes page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/index-actions-menu.png) + +These procedures act on an index that already exists. To create one, see [Creating an index]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#creating-an-index-1). + +### Refreshing, flushing, or clearing the cache + +1. In **Index Management**, select **Indexes**, **Data streams**, or **Aliases**. +1. Optionally, select the checkbox next to each item that you want the operation to apply to. If you do not select any, the operation applies to all of them. +1. Select **Actions**, and then select **Refresh**, **Flush**, or **Clear cache**. +1. Select the same option in the confirmation dialog. + +For aliases and data streams, these operations apply to the open backing indexes. + +### Force merging an index + +1. In **Index Management**, select **Indexes**, **Data streams**, or **Aliases**. +1. Select **Actions**, and then select **Force merge**. +1. In **Configure source index**, select the indexes, data streams, or aliases to merge. +1. Optionally, expand **Advanced settings** and set any of the following options: + + - To merge to a specific number of segments, select **Manually set number of segments** in **Index segments** and enter the number. Enter `1` to merge each shard into a single segment. + - To flush the indexes after the merge completes, select **Flush indexes**. + - To expunge the documents that are marked as deleted, select **Remove deleted documents**. + +1. Optionally, in **Notifications**, select **Has failed / timed out**, **Has completed**, or both to be notified about the outcome. +1. Select **Force merge**. + +### Shrinking an index + +1. In **Index Management**, select **Indexes**. +1. Select the index to shrink, and then select **Actions > Shrink**. +1. In **Configure target index**, enter a name in **Target index name**. +1. Enter the new shard count in **Number of primary shards** and the replica count in **Number of replicas**. +1. Optionally, select or enter one or more aliases for the target index in **Index alias**. +1. Optionally, expand **Advanced settings** to add notifications. See [Sending additional notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/#sending-additional-notifications). +1. Select **Shrink**. + +If the source index does not meet the [conditions for shrinking](#shrinking-an-index), the interface prompts you to resolve them, including setting a write block on the index. + +### Splitting an index + +1. In **Index Management**, select **Indexes**. +1. Select the index to split, and then select **Actions > Split**. +1. In **Configure target index**, enter a name in **Target index name**. +1. Enter the new shard count in **Number of primary shards** and the replica count in **Number of replicas**. +1. Optionally, select or enter one or more aliases for the target index in **Index alias**. +1. Optionally, expand **Advanced settings** to add notifications. See [Sending additional notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/#sending-additional-notifications). +1. Select **Split**. + +### Rolling over a data stream + +1. In **Index Management**, select **Data streams**. +1. Select **Actions**, and then select **Roll over**. +1. In **Configure source**, select the data stream to roll over. +1. Select **Roll over**. + +### Rolling over an alias + +1. In **Index Management**, select **Aliases**. +1. Select **Actions**, and then select **Roll over**. +1. In **Configure source**, select the alias to roll over. If the alias has no write index, you are prompted to designate one. +1. In **Define index**, enter a name for the new index and, optionally, an alias for it. +1. In **Index settings**, enter the number of primary shards, the number of replicas, and the refresh interval. +1. Select **Roll over**. + +### Checking the status of long-running operations + +Reindex, shrink, and split operations can take from tens of seconds to hours, depending on the amount of data involved. Because each is a one-time, non-recursive operation, you can track it to completion: + +1. In **Index Management**, select **Indexes**. +1. Find the index that the operation applies to. +1. Read the **Status** column for the state of the operation. + +## Related documentation + +- [Index operations APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-operations/) +- [Index operations]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/) +- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) +- [Long-running operation notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/) diff --git a/_im-plugin/index-operations.md b/_im-plugin/index-operations.md new file mode 100644 index 00000000..a414f7d4 --- /dev/null +++ b/_im-plugin/index-operations.md @@ -0,0 +1,205 @@ +--- +layout: default +title: Index operations +nav_order: 5 +redirect_from: + - /dashboards/im-dashboards/index-management/ + - /dashboards/admin-ui-index/index-management/ +--- + +# Index operations + +An index is the basic unit of data storage in OpenSearch. Over the lifetime of an index, you create it, inspect its settings and statistics, close it while you change static settings, reopen it, and eventually delete it. You can perform each of these operations using the [core index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/core-index-apis/) or from the **Index Management** page in OpenSearch Dashboards. + +For information about maintenance operations such as refresh, flush, force merge, shrink, and split, see [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/). + +## Creating an index + +You can let OpenSearch create an index implicitly when you index the first document into it, or you can create the index explicitly so that you control its mappings and settings from the start. Create the index explicitly when you need a specific number of shards, a custom refresh interval, or field mappings that differ from the dynamically inferred ones. + +The following request creates an index with two primary shards, one replica, and a `date` mapping for the `timestamp` field: + +```json +PUT /logs-2026 +{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "timestamp": { "type": "date" }, + "message": { "type": "text" } + } + } +} +``` +{% include copy-curl.html %} + +For all available settings and mappings, see [Create Index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/). To apply the same settings and mappings to every index whose name matches a pattern, use an [index template]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/). + +### Naming restrictions for indexes + +OpenSearch indexes have the following naming restrictions: + +- All letters must be lowercase. +- Index names can't begin with underscores (`_`) or hyphens (`-`). +- Index names can't contain spaces, commas, or the following characters: + + `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<` + +Names beginning with a period (`.`) are reserved for OpenSearch system indexes. + +## Viewing index information + +To retrieve the settings, mappings, and aliases of an index, use the [Get Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-index/): + +```json +GET /logs-2026 +``` +{% include copy-curl.html %} + +To check whether an index exists without retrieving it, use [Index Exists]({{site.url}}{{site.baseurl}}/api-reference/index-apis/exists/). To resolve an alias, data stream, or wildcard expression to the concrete indexes it covers, use [Resolve Index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/resolve-index/). For document counts, store size, and per-operation metrics, use [Index Stats]({{site.url}}{{site.baseurl}}/api-reference/index-apis/stats/). + +## Closing and opening an index + +A closed index rejects read and write requests and releases the memory its shards were using, but its data remains on disk. Close an index when you need to change a static setting, which can only be updated on a closed index, or when you want to retain an index that is no longer queried without paying its memory cost. + +To close an index, use the [Close Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/close-index/): + +```json +POST /logs-2026/_close +``` +{% include copy-curl.html %} + +To make the index available again, use the [Open Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/open-index/): + +```json +POST /logs-2026/_open +``` +{% include copy-curl.html %} + +For the list of settings that require a closed index, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +## Deleting an index + +Deleting an index removes its documents, shards, and metadata. Use the [Delete Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/delete-index/): + +```json +DELETE /logs-2026 +``` +{% include copy-curl.html %} + +A deleted index cannot be recovered unless you restore it from a [snapshot]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/index/). +{: .warning} + +To delete indexes on a schedule rather than manually, define an [Index State Management policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) with a `delete` action. + +## Index operations in OpenSearch Dashboards + +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. The **Indexes** page lists the indexes in your cluster and provides the following information about each one. + +| Column | Description | +| :--- | :--- | +| **Index** | The name of the index. | +| **Health** | The replication status of the index: green (all primary and replica shards are assigned), yellow (at least one replica shard is not assigned), or red (at least one primary shard is not assigned). | +| **Managed by policy** | Whether an Index State Management policy applies to the index, either directly or through an alias. | +| **Status** | Whether the index is open or closed. | +| **Total size** | The storage used by the index across all primary and replica shards. | +| **Size of primaries** | The storage used by the index across all primary shards. | +| **Total documents** | The number of documents in the index. | +| **Deleted documents** | The number of documents deleted from the index. | +| **Primaries** | The number of primary shards. | +| **Replicas** | The number of replica shards for each primary shard. | + +Because the list can span several pages, use the search box to find an index by name. + +The following image shows the **Indexes** page. + +![Indexes page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/indexes-list.png) + +### Viewing index details + +1. In **Index Management**, select **Indexes**. +1. Select an index name in the **Index** column. + +The index page shows an **Overview** panel with metrics for the index, along with **Settings**, **Mappings**, and **Alias** tabs that you can edit. To return to the list, select **Indexes** in the breadcrumb trail. + +### Creating an index + +1. In **Index Management**, select **Indexes**, and then select **Create Index**. +1. In **Define index**, enter an index name. Optionally, select existing aliases for the index or enter the name of a new alias to create. +1. In **Index settings**, enter the number of primary shards, the number of replicas, and the refresh interval. The default refresh interval is `1s`. To supply additional settings as a flat JSON object, expand **Advanced settings**. For the available options, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). +1. In **Index mapping**, define the fields in your documents. Select **Visual editor** to add fields one at a time or **JSON editor** to paste an existing mapping. In the visual editor, select **Add new field** or **Add new object**, enter a field name, and select a field type. For an object field, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/plus-icon.png" class="inline-icon" alt="plus icon"/>{:/} (plus) icon to add nested fields. This panel is optional; if you leave it empty, OpenSearch infers mappings from the first documents you index. +1. Select **Create**. Any new aliases that you specified are created along with the index. + +To create an [append-only index]({{site.url}}{{site.baseurl}}/im-plugin/append-only-index/), add the following setting in **Advanced settings** before you create the index: + +```json +"index.append_only.enabled": "true" +``` +{% include copy.html %} + +An index cannot be converted to or from an append-only index after it is created. +{: .warning} + +### Editing an index + +1. In **Index Management**, select **Indexes**. +1. Select an index name in the **Index** column. +1. Select the tab for what you want to change: + + - To change the number of replicas or the refresh interval, select **Settings**. To supply other settings as a flat JSON object, expand **Advanced settings**. You cannot change the number of primary shards of an existing index; to change it, [shrink]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#shrinking-an-index-1) or [split]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#splitting-an-index-1) the index instead. + - To add fields or objects, select **Mappings**. You cannot change the name or type of an existing field. + - To add an alias, select an existing alias, or remove one, select **Alias**. To remove an alias, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>{:/} (cross) icon next to its name. + +1. Select **Save**. + +### Closing an index + +1. In **Index Management**, select **Indexes**. +1. Select the checkbox next to each index that you want to close. +1. Select **Actions**, and then select **Close**. +1. Enter `close` in the confirmation dialog, and then select **Close**. + +### Opening an index + +1. In **Index Management**, select **Indexes**. +1. Select the checkbox next to each closed index that you want to open. +1. Select **Actions**, and then select **Open**. +1. Select **Open** in the confirmation dialog. + +### Deleting an index + +1. In **Index Management**, select **Indexes**. +1. Select the checkbox next to each index that you want to delete. +1. Select **Actions**, and then select **Delete**. +1. Enter `delete` in the confirmation dialog, and then select **Delete**. + +### Applying a policy + +To attach an Index State Management policy to an index from the index list: + +1. In **Index Management**, select **Indexes**. +1. Select the checkbox next to each index that you want the policy to manage. +1. Select **Actions**, and then select **Apply policy**. +1. Select a policy from **Policy ID**. A preview of the policy is displayed. +1. If the policy includes a `rollover` action, enter an existing alias in **Rollover alias**. +1. Select **Apply**. + +For more information, see [Managed indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/). + +### Permissions and error reporting + +Permissions are enforced at the API level through [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/) and action groups. OpenSearch Dashboards does not add a separate layer of permission control: you can view the **Index Management** pages if you have access to them, and you can complete an operation if you have permission to call the corresponding API. + +An operation that fails immediately reports an error in the interface. For an operation that runs longer, the failure is reported when it occurs. You can also check the state of an operation in the **Status** column of the index list. For more information, see [Checking the status of long-running operations]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#checking-the-status-of-long-running-operations). + +## Related documentation + +- [Add and manage your data]({{site.url}}{{site.baseurl}}/getting-started/manage-data/) +- [Core index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/core-index-apis/) +- [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) +- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) diff --git a/_im-plugin/index-rollups/index.md b/_im-plugin/index-rollups/index.md index 59cd304d..a07365c4 100644 --- a/_im-plugin/index-rollups/index.md +++ b/_im-plugin/index-rollups/index.md @@ -1,75 +1,52 @@ --- layout: default title: Index rollups -nav_order: 35 +nav_order: 50 has_children: true +has_toc: false redirect_from: - /im-plugin/index-rollups/ --- # Index rollups -Time series data increases storage costs, strains cluster health, and slows down aggregations over time. Index rollup lets you periodically reduce data granularity by rolling up old data into summarized indexes. +Uncompressed time-series data eventually increases storage costs, strains cluster health, and slows down aggregations. _Index rollup_ mitigates these effects by periodically compressing old data into summarized indexes with reduced granularity. -You pick the fields that interest you and use index rollup to create a new index with only those fields aggregated into coarser time buckets. You can store months or years of historical data at a fraction of the cost with the same query performance. +You pick the fields that interest you and use index rollup to create a new index with only those fields, aggregated into coarser time buckets. You can store months or years of historical data at a fraction of the cost with the same query performance. -For example, say you collect CPU consumption data every five seconds and store it on a hot node. Instead of moving older data to a read-only warm node, you can roll up or compress this data with only the average CPU consumption per day or with a 10% decrease in its interval every week. +For example, say you collect CPU consumption data every five seconds and store it on a hot node. Instead of moving older data to a read-only warm node, you can progressively compress this data with a 10% decrease in its interval every week. Or you could save only the average CPU consumption per day. You can use index rollup in three ways: -1. Use the index rollup API for an on-demand index rollup job that operates on an index that's not being actively ingested such as a rolled-over index. For example, you can perform an index rollup operation to reduce data collected at a five minute interval to a weekly average for trend analysis. -2. Use the OpenSearch Dashboards UI to create an index rollup job that runs on a defined schedule. You can also set it up to roll up your indexes as it’s being actively ingested. For example, you can continuously roll up Logstash indexes from a five second interval to a one hour interval. -3. Specify the index rollup job as an ISM action for complete index management. This allows you to roll up an index after a certain event such as a rollover, index age reaching a certain point, index becoming read-only, and so on. You can also have rollover and index rollup jobs running in sequence, where the rollover first moves the current index to a warm node and then the index rollup job creates a new index with the minimized data on the hot node. +1. Use the Index Rollup API for an on-demand index rollup job that operates on an index that's not being actively ingested, such as a rolled-over index. For example, you can perform an index rollup operation to aggregate data collected at a 5-minute interval into a weekly average for trend analysis. +2. Use the OpenSearch Dashboards UI to create an index rollup job that runs on a defined schedule. Or you can configure the job to roll up your indexes as they are being ingested. For example, you can continuously roll up Logstash indexes from a five second interval to a one hour interval. +3. Specify the index rollup job as an ISM action as a part of complete index management. This enables you to trigger a rollup after an event such as a rollover, index age reaching a certain point, index becoming read-only, and so on. You can also have rollover and index rollup jobs running in sequence, where the rollover first moves the current index to a warm node and then the index rollup job creates a new index with the minimized data on the hot node. -## Create an Index Rollup Job +## Configuring a rollup job -To get started, choose **Index Management** in OpenSearch Dashboards. -Select **Rollup Jobs** and choose **Create rollup job**. +A rollup job reads from a source index and writes summarized documents to a target index. The source index is unchanged, and you cannot change either index selection after the job is created. -### Step 1: Set up indexes +A job aggregates the source documents on a timestamp field, using either a fixed interval, where every bucket is the same length, or a calendar interval, which follows calendar entities such as months and can be unequal. You can group by additional fields---terms aggregation for any field type and histogram aggregation for numeric fields---and save `avg`, `sum`, `max`, `min`, `value_count`, and `cardinality` metrics for numeric fields. -1. In the **Job name and description** section, specify a unique name and an optional description for the index rollup job. -2. In the **Indices** section, select the source and target index. The source index is the one that you want to roll up. The source index remains as is, the index rollup job creates a new index referred to as a target index. The target index is where the index rollup results are saved. For target index, you can either type in a name for a new index or you select an existing index. -5. Choose **Next** +Choose the fields to group by carefully. Highly granular fields produce nearly as many rolled-up documents as source documents and save little space. The order of the fields matters: group by the fields with the fewest buckets first. For a dataset of demographics by city, for example, group by city and save the demographics as metrics. -After you create an index rollup job, you can't change your index selections. +A job runs on a fixed interval or on a schedule that you define with a [cron expression]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/), and processes a number of pages per run that trades run time against memory. Add an execution delay to give ingestion time to finish: with a delay of 10 minutes, the run that rolls up the hour from 1 PM to 2 PM starts at 2:10 PM. Mark the job as continuous to roll up data as it is ingested rather than in one pass. -### Step 2: Define aggregations and metrics +To create a job, use the [Index rollups API]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/) or the steps in [Creating a rollup job](#creating-a-rollup-job). -Select the attributes with the aggregations (terms and histograms) and metrics (avg, sum, max, min, and value count) that you want to roll up. Make sure you don’t add a lot of highly granular attributes, because you won’t save much space. +## Searching the target index -For example, consider a dataset of cities and demographics within those cities. You can aggregate based on cities and specify demographics within a city as metrics. -The order in which you select attributes is critical. A city followed by a demographic is different from a demographic followed by a city. +Search the target index with the `_search` API. The query must match the constraints of the target index. A terms aggregation on a field that you did not group by, or an aggregation on a metric that you did not save, is rejected with `400`. -1. In the **Time aggregation** section, select a timestamp field. Choose between a **Fixed** or **Calendar** interval type and specify the interval and timezone. The index rollup job uses this information to create a date histogram for the timestamp field. -2. (Optional) Add additional aggregations for each field. You can choose terms aggregation for all field types and histogram aggregation only for numeric fields. -3. (Optional) Add additional metrics for each field. You can choose between **All**, **Min**, **Max**, **Sum**, **Avg**, or **Value Count**. -4. Choose **Next**. +An `avg` sub-aggregation nested under a `date_histogram` returns `400` with a `script_exception` on a rollup index. Use `sum` and `value_count` and divide them, or nest the `avg` under a `terms` aggregation instead. +{: .note} -### Step 3: Specify schedule - -Specify a schedule to roll up your indexes as it’s being ingested. The index rollup job is enabled by default. - -1. Specify if the data is continuous or not. -3. For roll up execution frequency, select **Define by fixed interval** and specify the **Rollup interval** and the time unit or **Define by cron expression** and add in a cron expression to select the interval. To learn how to define a cron expression, see [Alerting]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/cron/). -4. Specify the number of pages per execution process. A larger number means faster execution and more cost for memory. -5. (Optional) Add a delay to the roll up executions. This is the amount of time the job waits for data ingestion to accommodate any processing time. For example, if you set this value to 10 minutes, an index rollup that executes at 2 PM to roll up 1 PM to 2 PM of data starts at 2:10 PM. -6. Choose **Next**. - -### Step 4: Review and create - -Review your configuration and select **Create**. - -### Step 5: Search the target index - -You can use the standard `_search` API to search the target index. Make sure that the query matches the constraints of the target index. For example, if you don’t set up terms aggregations on a field, you don’t receive results for terms aggregations. If you don’t set up the maximum aggregations, you don’t receive results for maximum aggregations. - -You can’t access the internal structure of the data in the target index because the plugin automatically rewrites the query in the background to suit the target index. This is to make sure you can use the same query for the source and target index. +You cannot access the internal structure of the documents in the target index. OpenSearch rewrites the query to suit the target index so that you can use the same query against the source and target indexes. To query the target index, set `size` to 0: ```json -GET target_index/_search +GET {target_index}/_search { "size": 0, "query": { @@ -87,9 +64,416 @@ GET target_index/_search Consider a scenario where you collect rolled up data from 1 PM to 9 PM in hourly intervals and live data from 7 PM to 11 PM in minutely intervals. If you execute an aggregation over these in the same query, for 7 PM to 9 PM, you see an overlap of both rolled up data and live data because they get counted twice in the aggregations. -## Sample Walkthrough +## Cardinality metric +**Introduced 3.5** +{: .label .label-purple } -This walkthrough uses the OpenSearch Dashboards sample e-commerce data. To add that sample data, log in to OpenSearch Dashboards, choose **Home** and **Try our sample data**. For **Sample eCommerce orders**, choose **Add data**. +The cardinality metric enables memory-efficient tracking of unique counts in rolled-up data using the HyperLogLog++ (HLL++) algorithm. This is ideal for high-cardinality fields like user IDs, IP addresses, or session IDs where storing all unique values would be prohibitively expensive. + +### Configuration + +When defining a cardinality metric in a rollup job, you can specify the following parameter. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `precision_threshold` | Integer | Controls the trade-off between accuracy and memory usage. Higher values provide more accuracy but use more memory. Use a value between 100 and 40,000; values outside that range are accepted without an error but are not supported. Default is 3,000.| + +You can specify the `precision_threshold` parameter in the `cardinality` object as follows: + +```json +{ + "metrics": [ + { + "source_field": "user_id", + "metrics": [ + { + "cardinality": { + "precision_threshold": 10000 + } + } + ] + } + ] +} +``` + +### Querying cardinality metrics + +You can query cardinality metrics on rollup indexes in the same way you would on source indexes: + +```json +GET {rollup_index}/_search +{ + "size": 0, + "aggs": { + "unique_users": { + "cardinality": { + "field": "user_id" + } + } + } +} +``` +{% include copy-curl.html %} + +When querying rollup indexes, any `precision_threshold` specified in the query is ignored. The system always uses the precision threshold configured when the rollup job was created. This ensures consistency with the stored HLL sketches. +{: .important } + +### Example: Tracking unique visitors + +This example creates a rollup job that tracks the number of unique visitors per hour. First create the source index: + +```json +PUT web_logs +{ + "mappings": { + "properties": { + "timestamp": { "type": "date" }, + "visitor_id": { "type": "keyword" }, + "page_views": { "type": "integer" } + } + } +} +``` +{% include copy-curl.html %} + +Then create the rollup job: + +```json +PUT _plugins/_rollup/jobs/visitor_rollup +{ + "rollup": { + "description": "Unique visitors per hour", + "enabled": true, + "schedule": { + "interval": { + "period": 1, + "unit": "Hours" + } + }, + "source_index": "web_logs", + "target_index": "web_logs_hourly", + "page_size": 1000, + "dimensions": [ + { + "date_histogram": { + "source_field": "timestamp", + "fixed_interval": "1h" + } + } + ], + "metrics": [ + { + "source_field": "visitor_id", + "metrics": [ + { + "cardinality": { + "precision_threshold": 10000 + } + } + ] + }, + { + "source_field": "page_views", + "metrics": [ + { + "sum": {} + } + ] + } + ] + } +} +``` +{% include copy-curl.html %} + +A rollup job creates its target index on its first run, which happens once the configured interval elapses. Until then, searching the target index returns `index_not_found_exception`. To check whether a job has run, send `GET _plugins/_rollup/jobs/visitor_rollup/_explain`: a `rollup_metadata` of `null` means the job has not run yet. +{: .note} + +Query the rollup index: + +```json +GET web_logs_hourly/_search +{ + "size": 0, + "aggs": { + "hourly_stats": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "1h" + }, + "aggs": { + "unique_visitors": { + "cardinality": { + "field": "visitor_id" + } + }, + "total_page_views": { + "sum": { + "field": "page_views" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Multi-tier rollups +**Introduced 3.5** +{: .label .label-purple } + +Multi-tier rollups allow you to create rollup-of-rollup jobs, enabling progressive data granularity reduction over time. This is useful for long-term data retention strategies where you want to keep fine-grained data for recent periods and increasingly coarse-grained data for older periods. + +With multi-tier rollups, you can create a hierarchy of rollup jobs: + +``` +Raw Data (5-second intervals) + ↓ Tier 1 Rollup +Hourly Rollup (1-hour intervals) + ↓ Tier 2 Rollup +Daily Rollup (1-day intervals) + ↓ Tier 3 Rollup +Weekly Rollup (1-week intervals) +``` + +Each tier uses the previous tier's rollup index as its source, progressively reducing storage requirements while maintaining the ability to query the data. + +### Prerequisites + +For multi-tier rollups to work correctly, you must fulfill the following prerequisites: + +1. All tiers must use the same dimension fields, and the field names and types must match. +2. Each tier's interval must be a multiple of the previous tier's interval, for example, `5m` → `1h` → `1d`. +3. All tiers must use the same `precision_threshold` value if they use [cardinality metrics](#cardinality-metric). +4. The source index for the second and subsequent tiers must be a rollup index created by a previous tier. +5. The source tier must complete at least one rollup execution before you create the next tier. Creating a rollup job from an empty rollup index succeeds but produces unexpected results. + +### Example: Two-tier rollup strategy + +This example demonstrates a two-tier rollup for Internet of Things (IoT) sensor data. It consists of Tier 1 and Tier 2: +- Both tiers use identical dimension fields: `timestamp`, `sensor_id`, `location`. +- Both tiers use identical metric fields: `temperature` (`avg`/`max`/`min`), `device_id` (`cardinality`). +- The cardinality `precision_threshold` is the same in both tiers (`10000`). +- Tier 2 uses `sensor_data_hourly` (the output of Tier 1) as its source. + +Create the source index and add a few documents to it: + +```json +PUT sensor_data +{ + "mappings": { + "properties": { + "timestamp": { "type": "date" }, + "sensor_id": { "type": "keyword" }, + "location": { "type": "keyword" }, + "device_id": { "type": "keyword" }, + "temperature": { "type": "double" } + } + } +} +``` +{% include copy-curl.html %} + +```json +POST _bulk?refresh=true +{ "index": { "_index": "sensor_data" } } +{ "timestamp": "2026-01-05T08:15:00", "sensor_id": "s1", "location": "warehouse", "device_id": "d1", "temperature": 21.4 } +{ "index": { "_index": "sensor_data" } } +{ "timestamp": "2026-01-05T08:45:00", "sensor_id": "s1", "location": "warehouse", "device_id": "d1", "temperature": 22.1 } +{ "index": { "_index": "sensor_data" } } +{ "timestamp": "2026-01-05T09:10:00", "sensor_id": "s2", "location": "cold-store", "device_id": "d2", "temperature": 4.8 } +{ "index": { "_index": "sensor_data" } } +{ "timestamp": "2026-01-05T10:05:00", "sensor_id": "s2", "location": "cold-store", "device_id": "d2", "temperature": 5.2 } +``` +{% include copy-curl.html %} + +**Tier 1: Raw data → Hourly rollup** + +```json +PUT _plugins/_rollup/jobs/sensors_hourly +{ + "rollup": { + "description": "Hourly rollup of raw sensor data", + "enabled": true, + "schedule": { + "interval": { + "period": 1, + "unit": "Hours" + } + }, + "source_index": "sensor_data", + "target_index": "sensor_data_hourly", + "page_size": 1000, + "dimensions": [ + { + "date_histogram": { + "source_field": "timestamp", + "fixed_interval": "1h" + } + }, + { + "terms": { + "source_field": "sensor_id" + } + }, + { + "terms": { + "source_field": "location" + } + } + ], + "metrics": [ + { + "source_field": "temperature", + "metrics": [ + {"avg": {}}, + {"max": {}}, + {"min": {}} + ] + }, + { + "source_field": "device_id", + "metrics": [ + { + "cardinality": { + "precision_threshold": 10000 + } + } + ] + } + ] + } +} +``` +{% include copy-curl.html %} + +**Tier 2: Hourly rollup → Daily rollup** + +```json +PUT _plugins/_rollup/jobs/sensors_daily +{ + "rollup": { + "description": "Daily rollup of hourly sensor data", + "enabled": true, + "schedule": { + "interval": { + "period": 1, + "unit": "Days" + } + }, + "source_index": "sensor_data_hourly", + "target_index": "sensor_data_daily", + "page_size": 1000, + "dimensions": [ + { + "date_histogram": { + "source_field": "timestamp", + "fixed_interval": "1d" + } + }, + { + "terms": { + "source_field": "sensor_id" + } + }, + { + "terms": { + "source_field": "location" + } + } + ], + "metrics": [ + { + "source_field": "temperature", + "metrics": [ + {"avg": {}}, + {"max": {}}, + {"min": {}} + ] + }, + { + "source_field": "device_id", + "metrics": [ + { + "cardinality": { + "precision_threshold": 10000 + } + } + ] + } + ] + } +} +``` +{% include copy-curl.html %} + +Each tier runs on its own interval, so `sensor_data_hourly` appears after the first hourly run and `sensor_data_daily` appears after the first daily run. +{: .note} + +### Querying multi-tier rollups + +You can query any tier independently or search across multiple tiers. + +**Query a specific tier**: + +```json +GET sensor_data_daily/_search +{ + "size": 0, + "aggs": { + "daily_avg_temp": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "1d" + }, + "aggs": { + "max_temperature": { + "max": { + "field": "temperature" + } + }, + "unique_devices": { + "cardinality": { + "field": "device_id" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +**Query across multiple tiers** (using index patterns): + +```json +GET sensor_data_hourly,sensor_data_daily/_search +{ + "size": 0, + "aggs": { + "temperature_stats": { + "date_histogram": { + "field": "timestamp", + "fixed_interval": "1d" + }, + "aggs": { + "max_temp": { + "max": { + "field": "temperature" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Sample walkthrough + +This walkthrough uses the OpenSearch Dashboards sample e-commerce data. To add it, go to the OpenSearch Dashboards home page, select **Try our sample data**, and then select **Add data** in **Sample eCommerce orders**. Then run a search: @@ -118,7 +502,6 @@ GET opensearch_dashboards_sample_data_ecommerce/_search "hits": [ { "_index": "opensearch_dashboards_sample_data_ecommerce", - "_type": "_doc", "_id": "jlMlwXcBQVLeQPrkC_kQ", "_score": 1, "_source": { @@ -524,46 +907,112 @@ To take advantage of shorter and more easily written strings in Query DSL, you c ```json "query": { - "query_string": { - "query": "field_name:field_value" - } + "query_string": { + "query": "field_name:field_value" } +} ``` +{% include copy.html %} -The following example uses a query string with a `*` wildcard operator to search inside a rollup index called `my_server_logs_rollup`: +You can only query fields that the rollup job indexed as dimensions. The following example uses a query string with a `*` wildcard operator to search the `sensor_data_hourly` rollup index for two of its `location` dimension values: ```json -GET my_server_logs_rollup/_search +GET sensor_data_hourly/_search { "size": 0, "query": { - "query_string": { - "query": "email* OR inventory", - "default_field": "service_name" - } - }, - + "query_string": { + "query": "warehouse OR cold*", + "default_field": "location" + } + }, "aggs": { - "service_name": { + "by_location": { "terms": { - "field": "service_name" + "field": "location" }, "aggs": { - "region": { + "by_sensor": { "terms": { - "field": "region" + "field": "sensor_id" }, "aggs": { - "average quantity": { - "avg": { - "field": "cpu_usage" - } + "average temperature": { + "avg": { + "field": "temperature" } } } } } } + } +} +``` +{% include copy-curl.html %} + +The response contains one bucket per matching location: + +```json +{ + "took": 52, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "by_location": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "cold-store", + "doc_count": 2, + "by_sensor": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "s2", + "doc_count": 2, + "average temperature": { + "value": 5.0 + } + } + ] + } + }, + { + "key": "warehouse", + "doc_count": 2, + "by_sensor": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "s1", + "doc_count": 2, + "average temperature": { + "value": 21.75 + } + } + ] + } + } + ] + } + } } ``` @@ -584,8 +1033,8 @@ The `source_index` parameter in {% raw %}`{{ctx.source_index}}`{% endraw %} cann When data is rolled up into multiple target indexes, you can run one search across all of the rollup indexes. To search multiple target indexes that have the same rollup, specify the index names as a comma-separated list or a wildcard pattern. For example, with `target_index` as <span style="white-space: nowrap">`{% raw %}rollup_ndx-{{ctx.source_index}}{% endraw %}`</span> and source indexes that start with `log`, specify the `rollup_ndx-log*` pattern. Or, to search for rolled up log-000001 and log-000002 indexes, specify the `rollup_ndx-log-000001,rollup_ndx-log-000002` list. -You cannot search a mix of rollup and non-rollup indexes with the same query. -{: .note} +Do not search a mix of rollup and non-rollup indexes with the same query. The request returns `200`, but the rollup index fails as a shard failure, so the results contain only the non-rollup data. +{: .warning} ## Example @@ -690,7 +1139,7 @@ PUT log-000001 } ``` -**Step 4:** Index four documents into the index created above. Two of the documents have the message "Success", and two have the message "Error". +**Step 4:** Index four documents into the index created previously. Two of the documents have the message "Success", and two have the message "Error". ```json POST log/_doc?refresh=true @@ -728,9 +1177,9 @@ POST log/_doc?refresh=true } ``` -Once you index the first document, the rollover action is executed. This action creates the index `log-000002` with `rollover_policy` attached to it. Then the rollup action is executed, which creates the rollup index `rollup_ndx-log-000001`. +After you index the first document, the rollover action runs and creates the index `log-000002` with `rollover_policy` attached to it. The rollup action then runs and creates the rollup index `rollup_ndx-log-000001`. -To monitor the status of rollover and rollup index creation, you can use the ISM explain API: `GET _plugins/_ism/explain` +Each step waits for the next run of the ISM job, so the full sequence takes several ISM cycles to complete---about 20 minutes at the default `job_interval` of 5 minutes. To follow its progress, run `GET _plugins/_ism/explain` and watch the state change. {: .tip} **Step 5:** Search the rollup index. @@ -833,4 +1282,58 @@ The response contains two buckets, "Error" and "Success", and the document count ## Index codec considerations -For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#index-rollups-and-transforms). \ No newline at end of file +For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#index-rollups-and-transforms). + +## Index rollups in OpenSearch Dashboards + +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Rollup jobs** to list the rollup jobs in your cluster with their status and the time of their next run. Select a job to view its configuration and the results of its runs. To act on a job, select the checkbox next to it and then select **Enable**, **Disable**, or **Actions > Delete**. + +The following image shows the **Rollup jobs** page. + +![Rollup jobs page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/rollup-jobs-list.png) + +A rollup job needs a source index that contains a timestamp field. If your cluster has no time-series data to roll up, add the sample e-commerce data from the OpenSearch Dashboards home page and roll up its `order_date` field, as described in [Sample walkthrough](#sample-walkthrough). + +### Creating a rollup job + +1. In **Index Management**, select **Rollup jobs**, and then select **Create rollup job**. +1. Enter a **Name** for the job and, optionally, a description. +1. In **Source index**, select the index or index pattern to roll up. +1. In **Target index**, select an existing index or enter a name for a new one. The name can contain [embedded variables](#dynamic-target-index). +1. Select **Next**. +1. In **Time aggregation**, do the following: + + 1. Select the **Timestamp field** to aggregate on. + 1. Select an **Interval type**. Fixed intervals are all the same length. Calendar intervals follow calendar entities, such as months, and can be unequal. + 1. In **Interval**, select the length of the interval. + 1. In **Timezone**, select the time zone of the timestamp. + +1. Optionally, in **Additional aggregation**, add the fields to group by: + + 1. Select **Add fields**, select the field names, and then select **Add**. + 1. For each field, select an **Aggregation method**. Keyword fields can only be aggregated by term. + 1. For each histogram aggregation, enter the number of timestamp intervals per bucket in **Interval**. + 1. Optionally, reorder the fields so that the fields with the fewest buckets come first. + +1. Optionally, in **Additional metrics**, add the metrics to save: + + 1. Select **Add fields**, select the numeric field names, and then select **Add**. + 1. For each field, select the metrics to save: **Min**, **Max**, **Sum**, **Avg**, **Value count**, or **All**. To save every metric for every field in the table, select **Enable all**; to clear them, select **Disable all**. + +1. Select **Next**. +1. In **Schedule**, do the following: + + 1. To run the job on its schedule rather than only when a policy calls it, keep **Enable job by default** selected. + 1. To roll up data as it is ingested, select **Yes** in **Continuous**. + 1. In **Rollup execution frequency**, select **Define by fixed interval** and enter the **Rollup interval**, or select **Define by cron expression** and enter a cron expression and a time zone. For the expression syntax, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). + 1. In **Page per execution**, enter the number of pages to process in each run. A larger number runs faster and uses more memory. + 1. Optionally, in **Execution delay**, enter how long the job waits for ingestion to finish before it runs. + +1. Select **Next**, review the configuration, and then select **Create**. + +## Related documentation + +- [Index rollups API]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/) +- [Index rollup settings]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/settings/) +- [Index transforms]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/index/) +- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) diff --git a/_im-plugin/index-rollups/rollup-api.md b/_im-plugin/index-rollups/rollup-api.md index 61bfdf76..51f618c3 100644 --- a/_im-plugin/index-rollups/rollup-api.md +++ b/_im-plugin/index-rollups/rollup-api.md @@ -2,7 +2,7 @@ layout: default title: Index rollups API parent: Index rollups -nav_order: 9 +nav_order: 10 --- # Index rollups API @@ -19,21 +19,26 @@ Use the index rollup operations to programmatically work with index rollup jobs. --- ## Create or update an index rollup job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } -Creates or updates an index rollup job. -You must provide the `seq_no` and `primary_term` parameters. +Creates or updates an index rollup job. To update an existing job, provide the `if_seq_no` and `if_primary_term` parameters, which you can read from the [Get an index rollup job](#get-an-index-rollup-job) response. Omitting them on an update returns `409 version_conflict_engine_exception`. An update must also repeat the job's current `schedule.interval.start_time`. #### Request +To create a job, send the following request: + ```json -PUT _plugins/_rollup/jobs/<rollup_id> // Create -PUT _plugins/_rollup/jobs/<rollup_id>?if_seq_no=1&if_primary_term=1 // Update +PUT _plugins/_rollup/jobs/{rollup_id} { "rollup": { "source_index": "nyc-taxi-data", "target_index": "rollup-nyc-taxi-data", + "target_index_settings":{ + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index.codec": "best_compression" + }, "schedule": { "interval": { "period": 1, @@ -44,12 +49,8 @@ PUT _plugins/_rollup/jobs/<rollup_id>?if_seq_no=1&if_primary_term=1 // Update "enabled": true, "page_size": 200, "delay": 0, - "roles": [ - "rollup_all", - "nyc_taxi_all", - "example_rollup_index_all" - ], "continuous": false, + "routing_field": "PULocationID", "dimensions": [ { "date_histogram": { @@ -89,29 +90,38 @@ PUT _plugins/_rollup/jobs/<rollup_id>?if_seq_no=1&if_primary_term=1 // Update } } ``` +{% include copy-curl.html %} + +To update an existing job, add the `if_seq_no` and `if_primary_term` parameters and send the complete job definition, including its current `start_time`: + +```json +PUT _plugins/_rollup/jobs/{rollup_id}?if_seq_no=1&if_primary_term=1 +``` +{% include copy-curl.html %} You can specify the following options. Options | Description | Type | Required -:--- | :--- |:--- |:--- | -`source_index` | The name of the detector. | String | Yes -`target_index` | Specify the target index that the rolled up data is ingested into. You can either create a new target index or use an existing index. The target index cannot be a combination of raw and rolled up data. This field supports dynamically generated index names like {% raw %}`rollup_{{ctx.source_index}}`{% endraw %}, where `source_index` cannot contain wildcards. | String | Yes -`schedule` | Schedule of the index rollup job which can be an interval or a cron expression. | Object | Yes -`schedule.interval` | Specify the frequency of execution of the rollup job. | Object | No -`schedule.interval.start_time` | Start time of the interval. | Timestamp | Yes -`schedule.interval.period` | Define the interval period. | String | Yes +:--- |:--- |:--- |:--- | +`source_index` | The index that the rollup job reads from. Cannot contain wildcards. | String | Yes +`target_index` | Specify the target index that the rolled up data is ingested into. You can either create a new target index or use an existing index. The target index cannot be a combination of raw and rolled up data. This field supports dynamically generated index names like {% raw %}`rollup_{{ctx.source_index}}`{% endraw %}, where `source_index` cannot contain wildcards. | String | Yes +`target_index_settings` | Specify any [index settings]({{site.url}}{{site.baseurl}}/im-plugin/index-settings/) to be applied to the target index created during the rollup. | Object | No +`schedule` | Schedule of the index rollup job which can be an interval or a [cron expression]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). | Object | Yes +`schedule.interval` | Specify the frequency of execution of the rollup job. | Object | No +`schedule.interval.start_time` | Start time of the interval. If omitted when you create a job, OpenSearch sets it to the current time. Required when you update a job. | Timestamp | No +`schedule.interval.period` | Define the interval period. | String | Yes `schedule.interval.unit` | Specify the time unit of the interval. | String | Yes -`schedule.interval.cron` | Optionally, specify a cron expression to define therollup frequency. | List | No -`schedule.interval.cron.expression` | Specify a Unix cron expression. | String | Yes -`schedule.interval.cron.timezone` | Specify timezones as defined by the IANA Time Zone Database. Defaults to UTC. | String | No -`description` | Optionally, describe the rollup job. | String | No -`enabled` | When true, the index rollup job is scheduled. Default is true. | Boolean | Yes -`continuous` | Specify whether or not the index rollup job continuously rolls up data forever or just executes over the current data set once and stops. Default is false. | Boolean | Yes -`error_notification` | Set up a Mustache message template for error notifications. For example, if an index rollup job fails, the system sends a message to a Slack channel. | Object | No +`schedule.cron` | Specify a cron expression to define the rollup frequency instead of an interval. Specify either `schedule.interval` or `schedule.cron`, not both. | Object | No +`schedule.cron.expression` | Specify a Unix cron expression. | String | Yes +`schedule.cron.timezone` | Specify timezones as defined by the IANA Time Zone Database. Defaults to UTC. | String | No +`description` | Describe the rollup job. | String | Yes +`enabled` | When true, the index rollup job is scheduled. Default is `true`. | Boolean | No +`continuous` | Specify whether or not the index rollup job continuously rolls up data forever or executes over the current dataset once and stops. Default is `false`. | Boolean | No `page_size` | Specify the number of buckets to paginate at a time during rollup. | Number | Yes -`delay` | The number of milliseconds to delay execution of the index rollup job. | Long | No -`dimensions` | Specify aggregations to create dimensions for the roll up time window. Supported groups are `terms`, `histogram`, and `date_histogram`. For more information, see [Bucket Aggregations]({{site.url}}{{site.baseurl}}/opensearch/bucket-agg). | Array | Yes -`metrics` | Specify a list of objects that represent the fields and metrics that you want to calculate. Supported metrics are `sum`, `max`, `min`, `value_count` and `avg`. For more information, see [Metric Aggregations]({{site.url}}{{site.baseurl}}/opensearch/metric-agg). | Array | No +`delay` | The number of milliseconds to delay execution of the index rollup job. | Long | No +`dimensions` | Specify aggregations to create dimensions for the roll up time window. Supported groups are `terms`, `histogram`, and `date_histogram`. For more information, see [Bucket aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/index/). | Array | Yes +`routing_field` | The `source_field` of a `terms` dimension to use as the routing value for rolled up documents in the target index. When set, each rolled up document is indexed using the value of that dimension as its routing value. This ensures that searches specifying the same `routing` value are directed to the correct shard and can find the rolled up documents. If not set, rolled up documents are distributed across shards based on document ID, and searches that specify a `routing` value may not return matching documents. The value must match the `source_field` of one of the `terms` dimensions defined in `dimensions`. This setting is immutable and cannot be changed when updating an existing rollup job. Available in OpenSearch 3.7 and later. | String | No +`metrics` | Specify a list of objects that represent the fields and metrics that you want to calculate. Supported metrics are `sum`, `max`, `min`, `value_count`, `avg`, and `cardinality`. For more information, see [Metric aggregations]({{site.url}}{{site.baseurl}}/aggregations/metric/index/). | Array | No #### Example response @@ -119,7 +129,7 @@ Options | Description | Type | Required ```json { "_id": "<rollup_id>", - "_version": 3, + "_version": 1, "_seq_no": 1, "_primary_term": 1, "rollup": { @@ -136,13 +146,21 @@ Options | Description | Type | Required "last_updated_time": 1680159934649, "enabled_time": 1680159934649, "description": "Example rollup job", - "schema_version": 17, + "schema_version": 30, "source_index": "nyc-taxi-data", "target_index": "rollup-nyc-taxi-data", + "target_index_settings": { + "index": { + "number_of_shards": "1", + "codec": "best_compression", + "number_of_replicas": "1" + } + }, "metadata_id": null, "page_size": 200, "delay": 0, "continuous": false, + "routing_field": "PULocationID", "dimensions": [ { "date_histogram": { @@ -187,7 +205,7 @@ Options | Description | Type | Required ## Get an index rollup job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Returns all information about an index rollup job based on the `rollup_id`. @@ -195,7 +213,7 @@ Returns all information about an index rollup job based on the `rollup_id`. #### Request ```json -GET _plugins/_rollup/jobs/<rollup_id> +GET _plugins/_rollup/jobs/{rollup_id} ``` @@ -204,8 +222,9 @@ GET _plugins/_rollup/jobs/<rollup_id> ```json { "_id": "my_rollup", - "_seqNo": 1, - "_primaryTerm": 1, + "_version": 3, + "_seq_no": 1, + "_primary_term": 1, "rollup": { ... } } ``` @@ -214,7 +233,7 @@ GET _plugins/_rollup/jobs/<rollup_id> --- ## Delete an index rollup job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Deletes an index rollup job based on the `rollup_id`. @@ -222,20 +241,36 @@ Deletes an index rollup job based on the `rollup_id`. #### Request ```json -DELETE _plugins/_rollup/jobs/<rollup_id> +DELETE _plugins/_rollup/jobs/{rollup_id} ``` +{% include copy-curl.html %} #### Example response ```json -200 OK +{ + "_index": ".opendistro-ism-config", + "_id": "my_rollup", + "_version": 4, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 15, + "_primary_term": 1 +} ``` +A request for a job that does not exist returns `404`. + --- ## Start or stop an index rollup job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Start or stop an index rollup job. @@ -243,53 +278,91 @@ Start or stop an index rollup job. #### Request ```json -POST _plugins/_rollup/jobs/<rollup_id>/_start -POST _plugins/_rollup/jobs/<rollup_id>/_stop -``` - - -#### Example response - -```json -200 OK -``` - - ---- - -## Explain an index rollup job -Introduced 1.0 -{: .label .label-purple } - -Returns detailed metadata information about the index rollup job and its current progress. - -#### Request - -```json -GET _plugins/_rollup/jobs/<rollup_id>/_explain +POST _plugins/_rollup/jobs/{rollup_id}/_start +POST _plugins/_rollup/jobs/{rollup_id}/_stop ``` #### Example response +```json +{ + "acknowledged": true +} +``` + + +--- + +## Explain an index rollup job +**Introduced 1.0** +{: .label .label-purple } + +Returns metadata information about the index rollup job. + +#### Request + +```json +GET _plugins/_rollup/jobs/{rollup_id}/_explain +``` + + +#### Example response: Job not yet executed + +When the rollup job has not yet executed, both fields return `null`: + ```json { "example_rollup": { - "rollup_id": "example_rollup", - "last_updated_time": 1602014281, - "continuous": { - "next_window_start_time": 1602055591, - "next_window_end_time": 1602075591 - }, - "status": "running", - "failure_reason": null, - "stats": { - "pages_processed": 342, - "documents_processed": 489359, - "rollups_indexed": 3420, - "index_time_in_ms": 30495, - "search_time_in_ms": 584922 + "metadata_id": null, + "rollup_metadata": null + } +} +``` + +#### Example response: Job executed + +After the rollup job executes at least once, the response includes detailed metadata and statistics: + +```json +{ + "example_rollup": { + "metadata_id": "GtWGlZwBm3bOohSSvi2r", + "rollup_metadata": { + "rollup_id": "example_rollup", + "last_updated_time": 1772035161995, + "status": "finished", + "failure_reason": null, + "stats": { + "pages_processed": 2, + "documents_processed": 3, + "rollups_indexed": 3, + "index_time_in_millis": 28, + "search_time_in_millis": 46 + } } } } ``` + +For continuous rollup jobs, the `rollup_metadata` object may include additional fields such as `next_window_start_time` and `next_window_end_time` to indicate the time window for the next scheduled execution. +{: .note} + +#### Response fields + +The response contains the rollup job ID as the key, with the following fields: + +Field | Description +:--- | :--- +`metadata_id` | The document ID of the rollup metadata stored in the system index. Returns `null` if the rollup job has not yet executed. +`rollup_metadata` | Metadata about the rollup job execution. Returns `null` if the rollup job has not yet executed. When populated, contains the following nested fields. +`rollup_metadata.rollup_id` | The ID of the rollup job. +`rollup_metadata.last_updated_time` | The timestamp (in milliseconds since epoch) when the rollup job was last updated. +`rollup_metadata.status` | The current status of the rollup job. Possible values are `init` (job is initializing), `started` (job is currently executing), `finished` (job completed successfully), `failed` (job encountered an error), `stopped` (job was stopped), or `retry` (job is retrying after a failure). +`rollup_metadata.failure_reason` | The reason for failure if the job failed. Returns `null` if the job succeeded. +`rollup_metadata.stats` | Statistics about the rollup job execution. +`rollup_metadata.stats.pages_processed` | The number of pages processed during the rollup. +`rollup_metadata.stats.documents_processed` | The total number of documents processed during the rollup. +`rollup_metadata.stats.rollups_indexed` | The number of rollup documents created and indexed. +`rollup_metadata.stats.index_time_in_millis` | The time spent indexing rollup documents, in milliseconds. +`rollup_metadata.stats.search_time_in_millis` | The time spent searching source documents, in milliseconds. diff --git a/_im-plugin/index-rollups/settings.md b/_im-plugin/index-rollups/settings.md index 3ee1be33..627e83fc 100644 --- a/_im-plugin/index-rollups/settings.md +++ b/_im-plugin/index-rollups/settings.md @@ -2,7 +2,7 @@ layout: default title: Settings parent: Index rollups -nav_order: 30 +nav_order: 20 --- # Index rollup settings @@ -15,8 +15,8 @@ Setting | Default | Description :--- | :--- | :--- `plugins.rollup.search.backoff_millis` | 1000 milliseconds | The backoff time between retries for failed rollup jobs. `plugins.rollup.search.backoff_count` | 5 | How many retries the plugin should attempt for failed rollup jobs. -`plugins.rollup.search.search_all_jobs` | false | Whether OpenSearch should return all jobs that match all specified search terms. If disabled, OpenSearch returns just one, as opposed to all, of the jobs that matches the search terms. +`plugins.rollup.search.search_all_jobs` | false | Whether OpenSearch should return all jobs that match all specified search terms. If disabled, OpenSearch returns only one, as opposed to all, of the jobs that matches the search terms. `plugins.rollup.dashboards.enabled` | true | Whether rollups are enabled in OpenSearch Dashboards. `plugins.rollup.enabled` | true | Whether the rollup plugin is enabled. -`plugins.ingest.backoff_millis` | 1000 milliseconds | The backoff time between data ingestions for rollup jobs. -`plugins.ingest.backoff_count` | 5 | How many retries the plugin should attempt for failed ingestions. +`plugins.rollup.ingest.backoff_millis` | 1000 milliseconds | The backoff time between data ingest operations for rollup jobs. +`plugins.rollup.ingest.backoff_count` | 5 | How many retries the plugin should attempt for failed ingest operations. diff --git a/_im-plugin/index-sorting.md b/_im-plugin/index-sorting.md new file mode 100644 index 00000000..e228577f --- /dev/null +++ b/_im-plugin/index-sorting.md @@ -0,0 +1,202 @@ +--- +layout: default +title: Index sorting +parent: Tuning indexes +nav_order: 20 +--- + + +# Index sorting + +OpenSearch allows you to configure how documents are organized within each segment at index creation time. By default, Lucene applies no sorting to documents. The `index.sort.*` settings specify how documents are organized within each segment. + +The sorting behavior is controlled by the `index.sort.field`, `index.sort.order`, `index.sort.mode`, and `index.sort.missing` settings. For more information, see [Static index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#index-sort-settings). + +Index sorting can only be configured during index creation and cannot be modified afterward. This feature impacts indexing performance because documents must be sorted during flush and merge operations. We recommend testing the performance impact of sorting before implementing it in production. +{: .note} + +## Sorting by a single field + +The following example sorts the index by the `timestamp` field in descending order: + +```json +PUT /sample-index +{ + "settings": { + "index": { + "sort.field": "timestamp", + "sort.order": "desc" + } + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + } + } + } +} +``` +{% include copy-curl.html %} + +## Sorting by multiple fields + +You can also sort by multiple fields, with priority given to the first field. The following example sorts documents first by `category` in ascending order, then by `timestamp` in descending order: + +```json +PUT /multi-sort-index +{ + "settings": { + "index": { + "sort.field": [ + "category", + "timestamp" + ], + "sort.order": [ + "asc", + "desc" + ] + } + }, + "mappings": { + "properties": { + "category": { + "type": "keyword", + "doc_values": true + }, + "timestamp": { + "type": "date" + } + } + } +} +``` +{% include copy-curl.html %} + +## Sorting by nested fields +**Introduced 3.3** +{: .label .label-purple } + +You can configure index sorting on an index whose mappings contain nested fields. Sort by the top-level fields of the index; the nested fields can appear in the mappings but not in `sort.field`. The following example sorts an index that has a `comments` nested field by the top-level `user_id` and `created_at` fields: + +```json +PUT /nested-index +{ + "settings": { + "index": { + "sort.field": [ + "user_id", + "created_at" + ], + "sort.order": [ + "asc", + "desc" + ] + } + }, + "mappings": { + "properties": { + "user_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "comments": { + "type": "nested", + "properties": { + "message": { "type": "text" }, + "timestamp": { "type": "date" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index sorting cannot be applied to a field inside a nested object, which keeps nested documents structurally intact. Naming one, such as `comments.timestamp`, is rejected with `400`. +{: .note} + +## Search optimization with early termination + +When your index sort configuration matches your search sort criteria, OpenSearch can optimize query performance by limiting the number of documents examined per segment. This optimization is particularly effective for retrieving top-ranked results. + +Consider an index sorted by timestamp in descending order: + +```json +PUT /events +{ + "settings": { + "index": { + "sort.field": "timestamp", + "sort.order": "desc" + } + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + } + } + } +} +``` +{% include copy-curl.html %} + +Add some events to it: + +```json +POST /events/_bulk?refresh=true +{ "index": {} } +{ "timestamp": "2025-01-01T00:00:00" } +{ "index": {} } +{ "timestamp": "2025-01-02T00:00:00" } +{ "index": {} } +{ "timestamp": "2025-01-03T00:00:00" } +``` +{% include copy-curl.html %} + +To retrieve the 10 most recent events, use the following request: + +```json +GET /events/_search +{ + "size": 10, + "sort": [ + { + "timestamp": "desc" + } + ] +} +``` +{% include copy-curl.html %} + +OpenSearch recognizes that the segment documents are already sorted and only examines the first 10 documents per segment while still collecting remaining documents for total count and aggregations. + +If you don't need the total hit count, disable hit tracking for maximum performance: + +```json +GET /events/_search +{ + "size": 10, + "sort": [ + { "timestamp": "desc" } + ], + "track_total_hits": false +} +``` +{% include copy-curl.html %} + +This allows OpenSearch to terminate collection after finding the required number of documents per segment. + +Aggregations process all matching documents regardless of the `track_total_hits` setting. +{: .note} + +## Optimizing conjunction queries + +Index sorting can improve the performance of conjunction queries (AND operations) by organizing document IDs to group documents that match similar criteria. This organization helps skip large ranges of documents that don't match the query conditions. + +This technique works best with low-cardinality fields that are frequently used in filters. Sort priority should favor fields with both low cardinality and high filter frequency. The sort direction (ascending or descending) doesn't matter for this optimization. + +For example, when indexing vehicle listings, you might sort by fuel type, body style, manufacturer, year, and, finally, mileage to optimize common filter combinations. diff --git a/_im-plugin/index-templates.md b/_im-plugin/index-templates.md index 015c9908..1587e1af 100644 --- a/_im-plugin/index-templates.md +++ b/_im-plugin/index-templates.md @@ -1,25 +1,22 @@ --- layout: default title: Index templates -nav_order: 6 +nav_order: 15 redirect_from: - /opensearch/index-templates/ + - /dashboards/im-dashboards/component-templates/ + - /dashboards/admin-ui-index/component-templates/ --- # Index templates -Index templates let you initialize new indexes with predefined mappings and settings. For example, if you continuously index log data, you can define an index template so that all of these indexes have the same number of shards and replicas. +An index template applies mappings, settings, and aliases to every new index whose name matches one of the template's index patterns. Templates apply only at index creation: changing a template has no effect on indexes that already exist. -### Create a template +Use a template when new indexes appear on their own and need to be configured consistently, such as the daily indexes behind a log alias or the backing indexes of a data stream. The alternative---specifying settings and mappings in each [Create Index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/) request---does not apply to indexes that OpenSearch creates for you. -To create an index template, use a PUT or POST request: +## Creating an index template -```json -PUT _index_template/<template name> -POST _index_template/<template name> -``` - -This command creates a template named `daily_logs` and applies it to any new index whose name matches the pattern `logs-2020-01-*` and also adds it to the `my_logs` alias: +The following request creates a template named `daily_logs`, applies it to any new index matching `logs-2020-01-*`, and adds each of those indexes to the `my_logs` alias: ```json PUT _index_template/daily_logs @@ -49,101 +46,41 @@ PUT _index_template/daily_logs } } ``` +{% include copy-curl.html %} -You should see the following response: - -```json -{ - "acknowledged": true -} -``` - -If you create an index named `logs-2020-01-01`, you can see that it has the mappings and settings from the template: +Creating `logs-2020-01-01` now produces an index with the template's alias, settings, and mappings, and so does every other index matching the pattern: ```json PUT logs-2020-01-01 +``` +{% include copy-curl.html %} + +To view the resulting configuration, send the following request: + +```json GET logs-2020-01-01 ``` +{% include copy-curl.html %} -```json -{ - "logs-2020-01-01": { - "aliases": { - "my_logs": {} - }, - "mappings": { - "properties": { - "timestamp": { - "type": "date", - "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" - }, - "value": { - "type": "double" - } - } - }, - "settings": { - "index": { - "creation_date": "1578107970779", - "number_of_shards": "2", - "number_of_replicas": "1", - "uuid": "U1vMDMOHSAuS2IzPcPHpOA", - "version": { - "created": "7010199" - }, - "provided_name": "logs-2020-01-01" - } - } - } -} -``` +An index pattern cannot contain any of the following characters: `:`, `"`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<`. -Any additional indexes that match this pattern---`logs-2020-01-02`, `logs-2020-01-03`, and so on---will inherit the same mappings and settings. +Settings and mappings that you specify in a [Create Index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/) request override the ones from a matching template. +{: .note} -Index patterns cannot contain any of the following characters: `:`, `"`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, and `<`. +## Resolving conflicts between templates -### Retrieve a template +When an index name matches more than one template, OpenSearch applies the template with the highest `priority` and ignores the others---the templates are not merged. A template without a `priority` is assigned `0`, the lowest priority. -To list all index templates: +Give overlapping templates distinct priorities. A template whose patterns overlap those of an existing template at the same priority is rejected with `400`, because OpenSearch cannot determine which one to apply. +{: .note} -```json -GET _cat/templates -GET /_index_template -``` - -To find a template by its name: - -```json -GET _index_template/daily_logs -``` - -To get a list of all templates that match a pattern: - -```json -GET _index_template/daily* -``` - -To check if a specific template exists: - -```json -HEAD _index_template/<name> -``` - -### Configure multiple templates - -You can create multiple index templates for your indexes. If the index name matches more than one template, OpenSearch takes the mappings and settings from the template with the highest priority and applies it to the index. - -For example, say you have the following two templates that both match the `logs-2020-01-02` index and there’s a conflict in the `number_of_shards` field: - -#### Template 1 +For example, an index named `logs-2020-01-02` matches both of the following templates, which disagree about `number_of_shards`: ```json PUT _index_template/template-01 { - "index_patterns": [ - "logs*" - ], - "priority": 0, + "index_patterns": ["logs*"], + "priority": 5, "template": { "settings": { "number_of_shards": 2, @@ -152,16 +89,13 @@ PUT _index_template/template-01 } } ``` - -#### Template 2 +{% include copy-curl.html %} ```json PUT _index_template/template-02 { - "index_patterns": [ - "logs-2020-01-*" - ], - "priority": 1, + "index_patterns": ["logs-2020-01-*"], + "priority": 10, "template": { "settings": { "number_of_shards": 3 @@ -169,36 +103,17 @@ PUT _index_template/template-02 } } ``` +{% include copy-curl.html %} -Because `template-02` has a higher `priority` value, it takes precedence over `template-01` . The `logs-2020-01-02` index would have the `number_of_shards` value as 3 and the `number_of_replicas` as the default value 1. +Because `template-02` has the higher priority, the index gets 3 primary shards and the default of 1 replica. It does not inherit `number_of_replicas` from `template-01`. -### Delete a template +To view the template that applies to a name before you create the index, use [Simulate Index Template]({{site.url}}{{site.baseurl}}/api-reference/index-apis/simulate-index-template/). -You can delete an index template using its name: +## Reusing configuration with component templates -```json -DELETE _index_template/daily_logs -``` +A component template holds aliases, settings, or mappings that several index templates share. Instead of repeating the same mapping block in every template---which inflates the cluster state and has to be edited in every copy when it changes---define it once as a component template and reference it. -## Composable index templates - -Managing multiple index templates has the following challenges: - -- If you have duplication between index templates, storing these index templates results in a bigger cluster state. -- If you want to make a change across all your index templates, you have to manually make the change for each template. - -You can use composable index templates to overcome these challenges. Composable index templates let you abstract common settings, mappings, and aliases into a reusable building block called a component template. - -You can combine component templates to compose an index template. - -Settings and mappings that you specify directly in the [create index]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/) request override any settings or mappings specified in an index template and its component templates. -{: .note } - -### Create a component template - -Let's define two component templates⁠---`component_template_1` and `component_template_2`: - -#### Component template 1 +The following requests define two component templates: ```json PUT _component_template/component_template_1 @@ -214,8 +129,7 @@ PUT _component_template/component_template_1 } } ``` - -#### Component template 2 +{% include copy-curl.html %} ```json PUT _component_template/component_template_2 @@ -231,18 +145,18 @@ PUT _component_template/component_template_2 } } ``` +{% include copy-curl.html %} -### Use component templates to create an index template - -When creating index templates, you need to include the component templates in a `composed_of` list. - -OpenSearch applies the component templates in the order in which you specify them within the index template. The settings, mappings, and aliases that you specify inside the index template are applied last. +List the component templates in `composed_of` to build an index template from them. OpenSearch applies them in the order you list them, and applies anything in the template's own `template` block last, so the index template's values win: ```json PUT _index_template/daily_logs { - "index_patterns": [ - "logs-2020-01-*" + "index_patterns": ["logs-2020-01-*"], + "priority": 200, + "composed_of": [ + "component_template_1", + "component_template_2" ], "template": { "aliases": { @@ -264,75 +178,129 @@ PUT _index_template/daily_logs } } }, - "priority": 200, - "composed_of": [ - "component_template_1", - "component_template_2" - ], "version": 3, "_meta": { "description": "using component templates" } } ``` +{% include copy-curl.html %} -If you create an index named `logs-2020-01-01`, you can see that it derives its mappings and settings from both the component templates: +An index created from this template has the `@timestamp` and `ip_address` fields from the component templates alongside the `timestamp` and `value` fields from the index template. -```json -PUT logs-2020-01-01 -GET logs-2020-01-01 -``` +A component template takes effect only where an index template lists it in `composed_of`. Creating a component template does not attach it to index templates that already exist; add it to their `composed_of` list yourself. Updating a component template does reach every index template that already references it, but applies only to indexes created after the update. Indexes that already exist keep the configuration they were created with. -#### Example response +## Retrieving and deleting templates -```json -{ - "logs-2020-01-01": { - "aliases": { - "my_logs": {} - }, - "mappings": { - "properties": { - "@timestamp": { - "type": "date" - }, - "ip_address": { - "type": "ip" - }, - "timestamp": { - "type": "date", - "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis" - }, - "value": { - "type": "double" - } - } - }, - "settings": { - "index": { - "creation_date": "1625382479459", - "number_of_shards": "2", - "number_of_replicas": "1", - "uuid": "rYUlpOXDSUSuZifQLPfa5A", - "version": { - "created": "7100299" - }, - "provided_name": "logs-2020-01-01" - } - } - } -} -``` +The following table lists common template requests. +| Task | Request | +| :--- | :--- | +| List all templates | `GET _cat/templates` or `GET _index_template` | +| Get one template | `GET _index_template/daily_logs` | +| Get templates matching a pattern | `GET _index_template/daily*` | +| Check whether a template exists | `HEAD _index_template/daily_logs` | +| Delete a template | `DELETE _index_template/daily_logs` | -## Index template options +For all template operations and their parameters, see [Index template APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-templates/). -You can specify the following template options: +## Index templates in OpenSearch Dashboards -Option | Type | Description | Required -:--- | :--- | :--- | :--- -`template` | `Object` | Specify index settings, mappings, and aliases. | No -`priority` | `Integer` | The priority of the index template. | No -`composed_of` | `String array` | The names of component templates applied on a new index together with the current template. | No -`version` | `Integer` | Specify a version number to simplify template management. Default is `null`. | No -`_meta ` | `Object` | Specify meta information about the template. | No +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Templates** to list the index templates in your cluster; **Component templates** appears in the navigation once you do. + +The following image shows the **Templates** page. + +![Templates page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/templates-list.png) + +### Creating an index template + +1. In **Index Management**, select **Templates**, and then select **Create template**. +1. In **Template settings**, do the following: + + 1. Enter a name in **Template name**. + 1. Select a **Template type**. Select **Data streams** if the template backs a [data stream]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/), and then enter the name of the timestamp field in **Time field**. A data stream template requires a timestamp field. + 1. In **Index patterns**, enter the patterns that the template matches, separated by commas. + 1. In **Priority**, enter the template priority. The default is `0`, the lowest priority. OpenSearch uses the priority when an index name matches more than one template. + 1. Select **Simple template** to define the configuration here, or **Component template** to build the template from existing component templates. See [Building a template from component templates](#building-a-template-from-component-templates). + +1. In **Template definition**, do the following: + + 1. In **Index alias**, select or enter the aliases to add each new index to. + 1. In **Index settings**, enter the number of primary shards, the number of replicas, and the refresh interval. The default refresh interval is `1s`. To supply other settings as JSON, expand **Advanced settings**. + 1. In **Index mapping**, define the fields in your documents. Select **Visual editor** to add fields one at a time, or **JSON editor** to paste an existing mapping. + +1. Select **Create template**. + +To define a field in the visual editor, select **Add new field**, enter a name in **Field name**, and select a type from **Field type**. To define an object, select **Add new object**, name it, select the `object` type, and then select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/plus-icon.png" class="inline-icon" alt="plus icon"/>{:/} (plus) icon in **Actions** to add fields inside it. + +### Editing an index template + +1. In **Index Management**, select **Templates**. +1. Select the template in the **Template name** column. +1. On the **Configuration** tab, change the template settings and definition. +1. To check the result before saving, select **Preview template**, review the configuration, and then select **Close**. +1. Select **Save**. + +Editing a template does not change indexes that were created from it. + +### Deleting an index template + +1. In **Index Management**, select **Templates**. +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/trash-icon.png" class="inline-icon" alt="trashcan icon"/>{:/} (trashcan) icon in the row of the template. +1. Enter `delete` in the confirmation dialog, and then select **Delete**. + +### Creating an index from a template + +An index inherits a template when its name matches one of the template's index patterns: + +1. In **Index Management**, select **Indexes**, and then select **Create Index**. +1. In **Index name**, enter a name that matches one of the template's index patterns. For example, a template with the pattern `flight-data-*` applies to an index named `flight-data-1`. +1. Optionally, change any alias, setting, or mapping value to override the one from the template. The template values populate the form as soon as focus leaves the **Index name** box, and any value you replace is kept. +1. Select **Create**. + +### Creating a component template + +1. In **Index Management**, select **Templates > Component templates**, and then select **Create component template**. +1. Enter a name in **Name** and, optionally, a description of what the component template configures or when to use it. +1. In each of the **Index alias**, **Index settings**, and **Index mapping** panels that you want the component template to define, select **Use configuration** and then enter the values. All three panels are optional, so a component template can define one configuration or a complete index. +1. Select **Create component template**. + +### Building a template from component templates + +Follow the steps in [Creating an index template](#creating-an-index-template-1), and in **Template settings**, select **Component templates** as the method. Then do the following: + +1. In the **Component template** panel, select **Associate component template**. +1. Select the component templates to include, and then select **Associate**. +1. Optionally, select **Override template definition** and enter alias, settings, or mapping values that take precedence over the ones from the component templates. +1. Select **Create template**, or **Save** if you are editing an existing template. + +When two component templates define the same value, the one later in the list wins. Avoid associating multiple component templates that configure the same thing, unless you have checked that their values do not conflict. + +### Editing a component template + +1. In **Index Management**, select **Templates > Component templates**. +1. Select the component template in the **Name** column. +1. Turn **Use configuration** on or off for **Index alias**, **Index settings**, or **Index mapping**, and add, change, or remove values in the configurations that are turned on. +1. Select **Apply changes**. + +The new configuration applies to every index template that uses this component template. Indexes that already exist do not change. + +### Deleting a component template + +1. In **Index Management**, select **Templates > Component templates**. +1. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/trash-icon.png" class="inline-icon" alt="trashcan icon"/>{:/} (trashcan) icon in the row of the component template. +1. In the confirmation dialog, select **Unlink index templates and delete**, and then select **Apply changes**. + +Deleting a component template removes it from every index template that used it, with the following results: + +- Values that came from the component template are removed from those index templates. +- A value that an index template overrode remains in the index template. +- A value that an index template did not override becomes undefined in the index template. +- Indexes created from those templates are unchanged. + +## Related documentation + +- [Index template APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index-templates/) +- [Mappings and field types]({{site.url}}{{site.baseurl}}/field-types/) +- [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) diff --git a/_im-plugin/index-transforms/index.md b/_im-plugin/index-transforms/index.md index 3488eae3..38fd97bf 100644 --- a/_im-plugin/index-transforms/index.md +++ b/_im-plugin/index-transforms/index.md @@ -1,9 +1,10 @@ --- layout: default title: Index transforms -nav_order: 20 +nav_order: 60 has_children: true -redirect_from: /im-plugin/index-transforms/ +redirect_from: + - /im-plugin/index-transforms/ has_toc: false --- @@ -11,66 +12,86 @@ has_toc: false Whereas index rollup jobs let you reduce data granularity by rolling up old data into condensed indexes, transform jobs let you create a different, summarized view of your data centered around certain fields, so you can visualize or analyze the data in different ways. -For example, suppose that you have airline data that’s scattered across multiple fields and categories, and you want to view a summary of the data that’s organized by airline, quarter, and then price. You can use a transform job to create a new, summarized index that’s organized by those specific categories. +For example, suppose that you have airline data that's scattered across multiple fields and categories, and you want to view a summary of the data that's organized by airline, quarter, and then price. You can use a transform job to create a new, summarized index that's organized by those specific categories. -You can use transform jobs in two ways: +Create a transform job in either of the following ways: -1. Use the OpenSearch Dashboards UI to specify the index you want to transform and any optional data filters you want to use to filter the original index. Then select the fields you want to transform and the aggregations to use in the transformation. Finally, define a schedule for your job to follow. -1. Use the transforms API to specify all the details about your job: the index you want to transform, target groups you want the transformed index to have, any aggregations you want to use to group columns, and a schedule for your job to follow. +- In OpenSearch Dashboards, which shows the fields of the source index with sample data, previews the transformed fields as you select them, and lists the jobs you have created with their status. See [Creating a transform job](#creating-a-transform-job). +- Using the [Transforms APIs]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/transforms-apis/), which take the whole job configuration as JSON, so you can store it in version control and replicate it across clusters. -OpenSearch Dashboards provides a detailed summary of the jobs you created and their relevant information, such as associated indexes and job statuses. You can review and edit your job’s details and selections before creation, and even preview a transformed index’s data as you’re choosing which fields to transform. However, you can also use the REST API to create transform jobs and preview transform job results, but you must know all of the necessary settings and parameters to submit them as part of the HTTP request body. Submitting your transform job configurations as JSON scripts offers you more portability, allowing you to share and replicate your transform jobs, which is harder to do using OpenSearch Dashboards. +## Configuring a transform job -Your use cases will help you decide which method to use to create transform jobs. +A transform job reads from a source index and writes summarized documents to a target index. To transform only part of the source index, add a filter written in [query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). -## Create a transform job +The job configuration has two parts: -If you don't have any data in your cluster, you can use the sample flight data within OpenSearch Dashboards to try out transform jobs. Otherwise, after launching OpenSearch Dashboards, choose **Index Management**. Select **Transform Jobs**, and choose **Create Transform Job**. +- *Groups* place documents into buckets in the target index. Each group names a `source_field` in the source index and the `target_field` to write it to, so grouping the `DestAirportID` field of the sample flight data into a `DestAirportID_terms` target field produces one bucket per airport. If you omit `target_field`, it takes the name of the source field. OpenSearch Dashboards appends the name of the grouping, as in `DestAirportID_terms`. Transform jobs support the `histogram`, `date_histogram`, and `terms` [bucket aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/index/). +- *Aggregations* calculate a value for each bucket, such as a `sum_of_total_ticket_price` field that adds up the ticket prices in it. The `sum`, `avg`, `max`, `min`, `value_count`, `percentiles`, and `scripted_metric` [metric aggregations]({{site.url}}{{site.baseurl}}/aggregations/metric/index/) are supported. -### Step 1: Choose indexes +You cannot change the groups or aggregations of a job after you create it. -1. In the **Job name and description** section, specify a name and an optional description for your job. -2. In the **Indices** section, select the source and target index. You can either select an existing target index or create a new one by entering a name for your new index. If you want to transform just a subset of your source index, choose **Edit data filter**, and use the OpenSearch query DSL to specify a subset of your source index. For more information about the OpenSearch query DSL, see [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). -3. Choose **Next**. +A job runs at the transform execution interval that you set. A continuous job runs at each interval and transforms the buckets that changed since the last run, including buckets that new data was added to. A job that is not continuous runs once, after the first interval elapses. The number of pages processed per run trades speed against memory: a larger number processes more data per search request and can exceed the memory limits of the cluster. -### Step 2: Select fields to transform +## Example: Transforming the sample flight data -After specifying the indexes, you can select the fields you want to use in your transform job, as well as whether to use groupings or aggregations. +This example summarizes the OpenSearch Dashboards sample flight data by carrier and destination airport. To add the data, go to the OpenSearch Dashboards home page, select **Try our sample data**, and then select **Add data** in **Sample flight data**. -You can use groupings to place your data into separate buckets in your transformed index. For example, if you want to group all of the airport destinations within the sample flight data, you can group the `DestAirportID` field into a target field of `DestAirportID_terms` field, and you can find the grouped airport IDs in your transformed index after the transform job finishes. - -On the other hand, aggregations let you perform simple calculations. For example, you can include an aggregation in your transform job to define a new field of `sum_of_total_ticket_price` that calculates the sum of all airplane tickets, and then analyze the newly summer data within your transformed index. - -1. In the data table, select the fields you want to transform and expand the drop-down menu within the column header to choose the grouping or aggregation you want to use. - - Currently, transform jobs support histogram, date_histogram, and terms groupings. For more information about groupings, see [Bucket Aggregations]({{site.url}}{{site.baseurl}}/opensearch/bucket-agg/). In terms of aggregations, you can select from `sum`, `avg`, `max`, `min`, `value_count`, `percentiles`, and `scripted_metric`. For more information about aggregations, see [Metric Aggregations]({{site.url}}{{site.baseurl}}/opensearch/metric-agg/). - -1. Repeat step 1 for any other fields that you want to transform. -1. After selecting the fields that you want to transform and verifying the transformation, choose **Next**. - -### Step 3: Specify a schedule - -You can configure transform jobs to run once or multiple times on a schedule. Transform jobs are enabled by default. - -1. Choose whether the job should be **continuous**. Continuous jobs execute at each **transform execution interval** and incrementally transform newly modified buckets, which can include new data added to the source indexes. Non-continuous jobs execute only once. -1. For **transformation execution interval**, specify a transform interval in minutes, hours, or days. This interval dicatates how often continuous jobs should execute, and non-continuous jobs execute once after the interval elapses. -1. Under **Advanced**, specify an optional amount for **Pages per execution**. A larger number means more data is processed in each search request, but also uses more memory and causes higher latency. Exceeding allowed memory limits can cause exceptions and errors to occur. -1. Choose **Next**. - -### Step 4: Review and confirm details - -After confirming your transform job’s details are correct, choose **Create Transform Job**. If you want to edit any part of the job, choose **Edit** of the section you want to change, and make the necessary changes. You can’t change aggregations or groupings after creating a job. - -### Step 5: Search through the transformed index. - -Once the transform job finishes, you can use the `_search` API operation to search the target index. +The following job groups the `Carrier` and `DestAirportID` fields and adds up the ticket prices in each bucket: ```json -GET <target_index>/_search +PUT _plugins/_transform/sample_flight_job +{ + "transform": { + "enabled": true, + "schedule": { + "interval": { + "period": 1, + "unit": "Minutes", + "start_time": 1602100553 + } + }, + "description": "Sample flight transform job", + "source_index": "opensearch_dashboards_sample_data_flights", + "target_index": "finished_flight_job", + "page_size": 1000, + "groups": [ + { + "terms": { + "source_field": "Carrier", + "target_field": "Carrier_terms" + } + }, + { + "terms": { + "source_field": "DestAirportID", + "target_field": "DestAirportID_terms" + } + } + ], + "aggregations": { + "sum_of_total_ticket_price": { + "sum": { + "field": "AvgTicketPrice" + } + } + } + } +} ``` +{% include copy-curl.html %} -For example, after running a transform job that transforms the flight data based on a `DestAirportID` field, you can run the following request that returns all of the fields that have a value of `SFO`. +The job runs after the first interval elapses. To check its progress, use the [Explain API]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/transforms-apis/#get-the-status-of-a-transform-job): -**Sample Request** +```json +GET _plugins/_transform/sample_flight_job/_explain +``` +{% include copy-curl.html %} + +## Searching the transformed index + +After the transform job finishes, search the target index with the `_search` API. Each document in the target index contains the grouped fields, the aggregated values, the ID of the job that wrote it in `transform._id`, and the number of source documents in the bucket, reported in both `_doc_count` and `transform._doc_count`. + +The following request returns the buckets of the transformed flight index in which `DestAirportID_terms` is `SFO`: ```json GET finished_flight_job/_search @@ -82,16 +103,21 @@ GET finished_flight_job/_search } } ``` +{% include copy-curl.html %} -**Sample Response** +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} ```json { "took" : 3, "timed_out" : false, "_shards" : { - "total" : 5, - "successful" : 5, + "total" : 1, + "successful" : 1, "skipped" : 0, "failed" : 0 }, @@ -100,58 +126,117 @@ GET finished_flight_job/_search "value" : 4, "relation" : "eq" }, - "max_score" : 3.845883, + "max_score" : 1.0, "hits" : [ { "_index" : "finished_flight_job", - "_id" : "dSNKGb8U3OJOmC4RqVCi1Q", - "_score" : 3.845883, + "_id" : "ifSaM4kOvFxWHw84UpfMRQ", + "_score" : 1.0, "_source" : { "transform._id" : "sample_flight_job", - "transform._doc_count" : 14, - "Carrier_terms" : "Dashboards Airlines", - "DestAirportID_terms" : "SFO" + "_doc_count" : 10, + "transform._doc_count" : 10, + "Carrier_terms" : "BeatsWest", + "DestAirportID_terms" : "SFO", + "sum_of_total_ticket_price" : 7012.053009033203 } }, { "_index" : "finished_flight_job", - "_id" : "_D7oqOy7drx9E-MG96U5RA", - "_score" : 3.845883, + "_id" : "uBoQr4Q393MMLHCzz1DQPQ", + "_score" : 1.0, "_source" : { "transform._id" : "sample_flight_job", + "_doc_count" : 14, "transform._doc_count" : 14, "Carrier_terms" : "Logstash Airways", - "DestAirportID_terms" : "SFO" + "DestAirportID_terms" : "SFO", + "sum_of_total_ticket_price" : 9678.005126953125 } }, { "_index" : "finished_flight_job", - "_id" : "YuZ8tOt1OsBA54e84WuAEw", - "_score" : 3.6988301, + "_id" : "1pi8feMm2fDwop05MkC6qA", + "_score" : 1.0, "_source" : { "transform._id" : "sample_flight_job", + "_doc_count" : 14, + "transform._doc_count" : 14, + "Carrier_terms" : "OpenSearch Dashboards Airlines", + "DestAirportID_terms" : "SFO", + "sum_of_total_ticket_price" : 9238.96060180664 + } + }, + { + "_index" : "finished_flight_job", + "_id" : "56d2npFptOKeHZEt6BlohA", + "_score" : 1.0, + "_source" : { + "transform._id" : "sample_flight_job", + "_doc_count" : 11, "transform._doc_count" : 11, - "Carrier_terms" : "ES-Air", - "DestAirportID_terms" : "SFO" - } - }, - { - "_index" : "finished_flight_job", - "_id" : "W_-e7bVmH6eu8veJeK8ZxQ", - "_score" : 3.6988301, - "_source" : { - "transform._id" : "sample_flight_job", - "transform._doc_count" : 10, - "Carrier_terms" : "JetBeats", - "DestAirportID_terms" : "SFO" + "Carrier_terms" : "OpenSearch-Air", + "DestAirportID_terms" : "SFO", + "sum_of_total_ticket_price" : 6317.92561340332 } } ] } } - ``` +</details> ## Index codec considerations -For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#index-rollups-and-transforms). \ No newline at end of file +For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#index-rollups-and-transforms). + +## Index transforms in OpenSearch Dashboards + +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Transform jobs** to list the transform jobs in your cluster with their source index, target index, and status. Select a job to view its configuration and the results of its runs. To act on a job, select the checkbox next to it and then select **Enable**, **Disable**, or **Actions > Delete**. + +The following image shows the **Transform jobs** page. + +![Transform jobs page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/transform-jobs-list.png) + +If your cluster has no data to transform, add the sample flight data from the OpenSearch Dashboards home page and transform that. For more information, see [Add sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +### Creating a transform job + +1. In **Index Management**, select **Transform jobs**, and then select **Create transform job**. +1. Enter a **Name** for the job and, optionally, a description. +1. In **Source index**, select the index to transform. +1. Optionally, in **Source index filter**, select **Edit data filter**, enter a [query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) query that selects the documents to transform, and then select **Save**. For example, the following filter selects the flights whose tickets cost at least $1,000: + + ```json + { + "bool": { + "filter": [ + { "range": { "AvgTicketPrice": { "gte": "1000" }}} + ] + } + } + ``` + {% include copy.html %} + +1. In **Target index**, select an existing index or enter a name for a new one. +1. Select **Next**. +1. In **Define transforms**, select the fields to summarize: + + 1. Select the **N columns hidden** link and select the fields that you want in the target index. To start from an empty table, select **Hide all** and then add the fields one at a time. + 1. For each field in **Original fields with sample data**, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/add-filter-icon.png" class="inline-icon" alt="plus icon"/>{:/} (plus) icon, and then select a grouping or an aggregation. The result is added to **Transformed fields preview based on sample data**. + +1. Select **Next**. +1. In **Specify schedule**, do the following: + + 1. To run the job on its schedule rather than only when it is started by hand, keep **Job enabled by default** selected. + 1. To transform the buckets that change after each run, select **Yes** in **Continuous**. + 1. In **Transform execution interval**, enter an interval and select **Minute(s)**, **Hour(s)**, or **Day(s)**. + 1. Optionally, expand **Advanced** and enter the number of **Pages per execution**. A larger number runs faster and uses more memory. + +1. Select **Next**, review the configuration, and then select **Create transform job**. To change a panel, select **Edit** in that panel. + +## Related documentation + +- [Transforms APIs]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/transforms-apis/) +- [Index rollups]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/) +- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) diff --git a/_im-plugin/index-transforms/transforms-apis.md b/_im-plugin/index-transforms/transforms-apis.md index df9ff19f..3652bda8 100644 --- a/_im-plugin/index-transforms/transforms-apis.md +++ b/_im-plugin/index-transforms/transforms-apis.md @@ -1,7 +1,7 @@ --- layout: default title: Transforms APIs -nav_order: 45 +nav_order: 10 parent: Index transforms has_toc: true --- @@ -10,49 +10,48 @@ has_toc: true Aside from using OpenSearch Dashboards, you can also use the REST API to create, start, stop, and complete other operations relative to transform jobs. +The examples on this page use the OpenSearch Dashboards sample e-commerce data. To add it, go to the OpenSearch Dashboards home page, select **Try our sample data**, and then select **Add data** in **Sample eCommerce orders**. + #### Table of contents - TOC {:toc} ## Create a transform job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Creates a transform job. -### Request format +### Endpoints ```json -PUT _plugins/_transform/<transform_id> +PUT _plugins/_transform/{transform_id} ``` ### Path parameters -Parameter | Data Type | Description +Parameter | Data type | Description :--- | :--- | :--- -transform_id | String | Transform ID | +`transform_id` | String | Transform ID | ### Request body fields You can specify the following options in the HTTP request body: -Option | Data Type | Description | Required +Option | Data type | Description | Required :--- | :--- | :--- | :--- -enabled | Boolean | If true, the transform job is enabled at creation. | No -continuous | Boolean | Specifies whether the transform job should be continuous. Continuous jobs execute every time they are scheduled according to the `schedule` field and run based off of newly transformed buckets as well as any new data added to source indexes. Non-continuous jobs execute only once. Default is false. | No -schedule | Object | The schedule for the transform job. | Yes -start_time | Integer | The Unix epoch time of the transform job's start time. | Yes -description | String | Describes the transform job. | No -metadata_id | String | Any metadata to be associated with the transform job. | No -source_index | String | The source index containing the data to be transformed. | Yes -target_index | String | The target index the newly transformed data is added to. You can create a new index or update an existing one. | Yes -data_selection_query | Object | The query DSL to use to filter a subset of the source index for the transform job. See [query domain-specific language(DSL)]({{site.url}}{{site.baseurl}}/opensearch/query-dsl) for more information. | Yes -page_size | Integer | The number of buckets IM processes and indexes concurrently. A higher number results in better performance, but it requires more memory. If your machine runs out of memory, Index Management (IM) automatically adjusts this field and retries until the operation succeeds. | Yes -groups | Array | Specifies the grouping(s) to use in the transform job. Supported groups are `terms`, `histogram`, and `date_histogram`. For more information, see [Bucket Aggregations]({{site.url}}{{site.baseurl}}/opensearch/bucket-agg). | Yes if not using aggregations. -source_field | String | The field(s) to transform. | Yes -aggregations | Object | The aggregations to use in the transform job. Supported aggregations are `sum`, `max`, `min`, `value_count`, `avg`, `scripted_metric`, and `percentiles`. For more information, see [Metric Aggregations]({{site.url}}{{site.baseurl}}/opensearch/metric-agg). | Yes if not using groups. +`enabled` | Boolean | Whether the transform job is enabled at creation. Default is `true`. | No +`continuous` | Boolean | Specifies whether the transform job should be continuous. Continuous jobs execute every time they are scheduled according to the `schedule` field and run based off of newly transformed buckets as well as any new data added to source indexes. Non-continuous jobs execute only once. Default is `false`. | No +`schedule` | Object | The schedule for the transform job. Contains an `interval` object with the fields `period`, `unit`, and `start_time`. | Yes +`description` | String | Describes the transform job. | Yes +`source_index` | String | The source index containing the data to be transformed. | Yes +`target_index` | String | The target index the newly transformed data is added to. You can create a new index or update an existing one. | Yes +`data_selection_query` | Object | The query DSL to use to filter a subset of the source index for the transform job. If you omit this field, the job transforms every document in the source index. For more information, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). | No +`page_size` | Integer | The number of buckets IM processes and indexes concurrently. A higher number results in better performance, but it requires more memory. If your machine runs out of memory, Index Management (IM) automatically adjusts this field and retries until the operation succeeds. | Yes +`groups` | Array | Specifies the grouping(s) to use in the transform job. Each entry names a `source_field` in the source index and the `target_field` to write it to. Supported groups are `terms`, `histogram`, and `date_histogram`. A job must define at least one group. For more information, see [Bucket aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/index/). | Yes +`aggregations` | Object | The aggregations to use in the transform job. Supported aggregations are `sum`, `max`, `min`, `value_count`, `avg`, `scripted_metric`, and `percentiles`. For more information, see [Metric aggregations]({{site.url}}{{site.baseurl}}/aggregations/metric/index/). | No -#### Sample Request +#### Example request The following request creates a transform job with the id `sample`: @@ -70,8 +69,8 @@ PUT _plugins/_transform/sample } }, "description": "Sample transform job", - "source_index": "sample_index", - "target_index": "sample_target", + "source_index": "opensearch_dashboards_sample_data_ecommerce", + "target_index": "ecommerce_transform", "data_selection_query": { "match_all": {} }, @@ -100,22 +99,22 @@ PUT _plugins/_transform/sample } } ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { "_id": "sample", - "_version": 7, + "_version": 1, "_seq_no": 13, "_primary_term": 1, "transform": { "transform_id": "sample", - "schema_version": 7, - "continuous": true, + "schema_version": 30, "schedule": { "interval": { - "start_time": 1621467964243, + "start_time": 1602100553, "period": 1, "unit": "Minutes" } @@ -125,14 +124,13 @@ PUT _plugins/_transform/sample "enabled": true, "enabled_at": 1621467964243, "description": "Sample transform job", - "source_index": "sample_index", + "source_index": "opensearch_dashboards_sample_data_ecommerce", "data_selection_query": { "match_all": { "boost": 1.0 } }, - "target_index": "sample_target", - "roles": [], + "target_index": "ecommerce_transform", "page_size": 1, "groups": [ { @@ -154,21 +152,25 @@ PUT _plugins/_transform/sample "field": "total_quantity" } } - } + }, + "continuous": true } } ``` +The `metadata_id` field is assigned by OpenSearch and is `null` until the job runs for the first time. Setting it in the request has no effect. +{: .note} + ## Update a transform job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Updates the transform job if `transform_id` already exists. For this request you must specify the sequence number and primary term of the transform to be updated. To get these, use the [Get a transform job's details](#get-a-transform-jobs-details) API call. -### Request format +### Endpoints ```json -PUT _plugins/_transform/<transform_id>?if_seq_no=<seq_no>&if_primary_term=<primary_term> +PUT _plugins/_transform/{transform_id}?if_seq_no={seq_no}&if_primary_term={primary_term} ``` ### Query parameters @@ -177,77 +179,36 @@ The update operation supports the following query parameters: Parameter | Description | Required :---| :--- | :--- -`seq_no` | Only perform the transform operation if the last operation that changed the transform job has the specified sequence number. | Yes -`primary_term` | Only perform the transform operation if the last operation that changed the transform job has the specified sequence term. | Yes +`if_seq_no` | Only perform the transform operation if the last operation that changed the transform job has the specified sequence number. | Yes +`if_primary_term` | Only perform the transform operation if the last operation that changed the transform job has the specified sequence term. | Yes ### Request body fields -You can update the following fields. +Send the whole transform object in the request body. You can change only the following fields. -Option | Data Type | Description +Option | Data type | Description :--- | :--- | :--- -schedule | Object | The schedule for the transform job. Contains the fields `interval.start_time`, `interval.period`, and `interval.unit`. -start_time | Integer | The Unix epoch start time of the transform job. -period | Integer | How often to execute the transform job. -unit | String | The unit of time associated with the execution period. Available options are `Minutes`, `Hours`, and `Days`. -description | Integer | Describes the transform job. -page_size | Integer | The number of buckets IM processes and indexes concurrently. A higher number results in better performance, but it requires more memory. If your machine runs out of memory, IM automatically adjusts this field and retries until the operation succeeds. +`enabled` | Boolean | Whether the transform job is enabled. +`schedule` | Object | The schedule for the transform job. Contains the fields `interval.start_time`, `interval.period`, and `interval.unit`. +`interval.start_time` | Integer | The Unix epoch start time of the transform job. +`interval.period` | Integer | How often to execute the transform job. +`interval.unit` | String | The unit of time associated with the execution period. Available options are `Minutes`, `Hours`, and `Days`. +`description` | String | Describes the transform job. +`page_size` | Integer | The number of buckets IM processes and indexes concurrently. A higher number results in better performance, but it requires more memory. If your machine runs out of memory, IM automatically adjusts this field and retries until the operation succeeds. -#### Sample Request +Repeat the remaining fields with the values that the job already has. Changing `continuous`, `source_index`, `target_index`, `data_selection_query`, `groups`, or `aggregations` is rejected with `400`, and omitting one of them counts as a change. For example, leaving `continuous` out of the body of a job that was created with `"continuous": true` fails. +{: .note} + +#### Example request The following request updates a transform job with the id `sample`, sequence number `13`, and primary term `1`: -```json -PUT _plugins/_transform/sample?if_seq_no=13&if_primary_term=1 -{ - "transform": { - "enabled": true, - "schedule": { - "interval": { - "period": 1, - "unit": "Minutes", - "start_time": 1602100553 - } - }, - "description": "Sample transform job", - "source_index": "sample_index", - "target_index": "sample_target", - "data_selection_query": { - "match_all": {} - }, - "page_size": 1, - "groups": [ - { - "terms": { - "source_field": "customer_gender", - "target_field": "gender" - } - }, - { - "terms": { - "source_field": "day_of_week", - "target_field": "day" - } - } - ], - "aggregations": { - "quantity": { - "sum": { - "field": "total_quantity" - } - } - } - } -} -``` - -#### Sample Response - ```json PUT _plugins/_transform/sample?if_seq_no=13&if_primary_term=1 { "transform": { "enabled": true, + "continuous": true, "schedule": { "interval": { "period": 1, @@ -255,13 +216,13 @@ PUT _plugins/_transform/sample?if_seq_no=13&if_primary_term=1 "start_time": 1602100553 } }, - "description": "Sample transform job", - "source_index": "sample_index", - "target_index": "sample_target", + "description": "Updated sample transform job", + "source_index": "opensearch_dashboards_sample_data_ecommerce", + "target_index": "ecommerce_transform", "data_selection_query": { "match_all": {} }, - "page_size": 1, + "page_size": 10, "groups": [ { "terms": { @@ -286,60 +247,117 @@ PUT _plugins/_transform/sample?if_seq_no=13&if_primary_term=1 } } ``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_id": "sample", + "_version": 2, + "_seq_no": 14, + "_primary_term": 1, + "transform": { + "transform_id": "sample", + "schema_version": 30, + "schedule": { + "interval": { + "start_time": 1602100553, + "period": 1, + "unit": "Minutes" + } + }, + "metadata_id": null, + "updated_at": 1621467999831, + "enabled": true, + "enabled_at": 1621467999830, + "description": "Updated sample transform job", + "source_index": "opensearch_dashboards_sample_data_ecommerce", + "data_selection_query": { + "match_all": { + "boost": 1.0 + } + }, + "target_index": "ecommerce_transform", + "page_size": 10, + "groups": [ + { + "terms": { + "source_field": "customer_gender", + "target_field": "gender" + } + }, + { + "terms": { + "source_field": "day_of_week", + "target_field": "day" + } + } + ], + "aggregations": { + "quantity": { + "sum": { + "field": "total_quantity" + } + } + }, + "continuous": true + } +} +``` ## Get a transform job's details -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Returns a transform job's details. -### Request format +### Endpoints ```json -GET _plugins/_transform/<transform_id> +GET _plugins/_transform/{transform_id} ``` -#### Sample Request +#### Example request The following request returns the details of the transform job with the id `sample`: ```json GET _plugins/_transform/sample ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { "_id": "sample", - "_version": 7, - "_seq_no": 13, + "_version": 3, + "_seq_no": 15, "_primary_term": 1, "transform": { "transform_id": "sample", - "schema_version": 7, - "continuous": true, + "schema_version": 30, "schedule": { "interval": { - "start_time": 1621467964243, + "start_time": 1602100553, "period": 1, "unit": "Minutes" } }, - "metadata_id": null, - "updated_at": 1621467964243, + "metadata_id": "cAgQ_8RVFy4ZoSZb0g4XNw", + "updated_at": 1621468022451, "enabled": true, - "enabled_at": 1621467964243, - "description": "Sample transform job", - "source_index": "sample_index", + "enabled_at": 1621467999830, + "description": "Updated sample transform job", + "source_index": "opensearch_dashboards_sample_data_ecommerce", "data_selection_query": { "match_all": { "boost": 1.0 } }, - "target_index": "sample_target", - "roles": [], - "page_size": 1, + "target_index": "ecommerce_transform", + "page_size": 10, "groups": [ { "terms": { @@ -360,22 +378,24 @@ GET _plugins/_transform/sample "field": "total_quantity" } } - } + }, + "continuous": true } } ``` You can also get details of all transform jobs by omitting `transform_id`. -#### Sample Request +#### Example request The following request returns the details of all transform jobs: ```json GET _plugins/_transform/ ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { @@ -383,33 +403,31 @@ GET _plugins/_transform/ "transforms": [ { "_id": "sample", - "_seq_no": 13, + "_seq_no": 15, "_primary_term": 1, "transform": { "transform_id": "sample", - "schema_version": 7, - "continuous": true, + "schema_version": 30, "schedule": { "interval": { - "start_time": 1621467964243, + "start_time": 1602100553, "period": 1, "unit": "Minutes" } }, - "metadata_id": null, - "updated_at": 1621467964243, + "metadata_id": "cAgQ_8RVFy4ZoSZb0g4XNw", + "updated_at": 1621468022451, "enabled": true, - "enabled_at": 1621467964243, - "description": "Sample transform job", - "source_index": "sample_index", + "enabled_at": 1621467999830, + "description": "Updated sample transform job", + "source_index": "opensearch_dashboards_sample_data_ecommerce", "data_selection_query": { "match_all": { "boost": 1.0 } }, - "target_index": "sample_target", - "roles": [], - "page_size": 1, + "target_index": "ecommerce_transform", + "page_size": 10, "groups": [ { "terms": { @@ -430,34 +448,38 @@ GET _plugins/_transform/ "field": "total_quantity" } } - } + }, + "continuous": true } } ] } ``` +Each entry omits `_version`, which the response returns only when you request a single transform job. + ### Query parameters -You can specify the following GET API operation’s query parameters to filter the results. +You can specify the following GET API operation's query parameters to filter the results. Parameter | Description | Required :--- | :--- | :--- -from | The starting transform to return. Default is 0. | No -size | Specifies the number of transforms to return. Default is 10. | No -search |The search term to use to filter results. | No -sortField | The field to sort results with. | No -sortDirection | Specifies the direction to sort results in. Can be `ASC` or `DESC`. Default is ASC. | No +`from` | The starting transform to return. Default is 0. | No +`size` | Specifies the number of transforms to return. Default is 10. | No +`search` |The search term to use to filter results. | No +`sortField` | The field by which to sort the results, given as a path into the stored transform document, such as `transform.transform_id.keyword` or `transform.updated_at`. An unmapped name such as `transform_id` is rejected with `500`. | No +`sortDirection` | Specifies the direction to sort results in. Can be `ASC` or `DESC`. Default is `ASC`. | No -#### Sample Request +#### Example request -The following request returns two results starting from transform `8`: +The following request returns two results starting from transform `8`, sorted by transform ID: ```json -GET _plugins/_transform?size=2&from=8 +GET _plugins/_transform?size=2&from=8&sortField=transform.transform_id.keyword ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { @@ -469,7 +491,7 @@ GET _plugins/_transform?size=2&from=8 "_primary_term": 1, "transform": { "transform_id": "sample8", - "schema_version": 7, + "schema_version": 30, "schedule": { "interval": { "start_time": 1622063596812, @@ -482,14 +504,13 @@ GET _plugins/_transform?size=2&from=8 "enabled": false, "enabled_at": null, "description": "Sample transform job", - "source_index": "sample_index3", + "source_index": "opensearch_dashboards_sample_data_ecommerce", "data_selection_query": { "match_all": { "boost": 1.0 } }, - "target_index": "sample_target3", - "roles": [], + "target_index": "ecommerce_transform8", "page_size": 1, "groups": [ { @@ -511,7 +532,8 @@ GET _plugins/_transform?size=2&from=8 "field": "total_quantity" } } - } + }, + "continuous": false } }, { @@ -520,7 +542,7 @@ GET _plugins/_transform?size=2&from=8 "_primary_term": 1, "transform": { "transform_id": "sample9", - "schema_version": 7, + "schema_version": 30, "schedule": { "interval": { "start_time": 1622063598065, @@ -533,14 +555,13 @@ GET _plugins/_transform?size=2&from=8 "enabled": false, "enabled_at": null, "description": "Sample transform job", - "source_index": "sample_index4", + "source_index": "opensearch_dashboards_sample_data_ecommerce", "data_selection_query": { "match_all": { "boost": 1.0 } }, - "target_index": "sample_target4", - "roles": [], + "target_index": "ecommerce_transform9", "page_size": 1, "groups": [ { @@ -562,7 +583,8 @@ GET _plugins/_transform?size=2&from=8 "field": "total_quantity" } } - } + }, + "continuous": false } } ] @@ -570,26 +592,27 @@ GET _plugins/_transform?size=2&from=8 ``` ## Start a transform job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Transform jobs created using the API are automatically enabled, but if you ever need to enable a job, you can use the start API operation. -### Request format +### Endpoints -``` -POST _plugins/_transform/<transform_id>/_start +```json +POST _plugins/_transform/{transform_id}/_start ``` -#### Sample Request +#### Example request The following request starts the transform job with the ID `sample`: ```json POST _plugins/_transform/sample/_start ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { @@ -598,26 +621,27 @@ POST _plugins/_transform/sample/_start ``` ## Stop a transform job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Stops a transform job. -### Request format +### Endpoints -``` -POST _plugins/_transform/<transform_id>/_stop +```json +POST _plugins/_transform/{transform_id}/_stop ``` -#### Sample Request +#### Example request The following request stops the transform job with the ID `sample`: ```json POST _plugins/_transform/sample/_stop ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { @@ -626,162 +650,233 @@ POST _plugins/_transform/sample/_stop ``` ## Get the status of a transform job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Returns the status and metadata of a transform job. -### Request format +### Endpoints -``` -GET _plugins/_transform/<transform_id>/_explain +```json +GET _plugins/_transform/{transform_id}/_explain ``` -#### Sample Request +#### Example request The following request returns the details of the transform job with the ID `sample`: ```json GET _plugins/_transform/sample/_explain ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { "sample": { - "metadata_id": "PzmjweME5xbgkenl9UpsYw", + "metadata_id": "cAgQ_8RVFy4ZoSZb0g4XNw", "transform_metadata": { + "transform_id": "sample", + "last_updated_at": 1621883525873, + "status": "started", + "failure_reason": null, + "stats": { + "pages_processed": 3, + "documents_processed": 4675, + "documents_indexed": 14, + "index_time_in_millis": 22, + "search_time_in_millis": 88 + }, "continuous_stats": { "last_timestamp": 1621883525672, "documents_behind": { - "sample_index": 72 - } - }, - "transform_id": "sample", - "last_updated_at": 1621883525873, - "status": "finished", - "failure_reason": "null", - "stats": { - "pages_processed": 0, - "documents_processed": 0, - "documents_indexed": 0, - "index_time_in_millis": 0, - "search_time_in_millis": 0 + "opensearch_dashboards_sample_data_ecommerce": 0 + } } } } } ``` +The `status` field is `started` while the job is running, `finished` after a job that is not continuous completes, `stopped` after you stop it, and `failed` if it fails, in which case `failure_reason` holds the message, such as `Failed to index the documents`. The `continuous_stats` object is present only for a continuous job, where `documents_behind` counts the source documents that the job has not yet transformed. + +Both `metadata_id` and `transform_metadata` are `null` until the job runs for the first time. +{: .note} + ## Preview a transform job's results -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } -Returns a preview of what a transformed index would look like. +Returns a preview of what a transformed index would look like. The preview does not create the job or write to the target index. -#### Sample Request +### Endpoints ```json POST _plugins/_transform/_preview +``` +#### Example request + +```json +POST _plugins/_transform/_preview { "transform": { - "enabled": false, - "schedule": { - "interval": { - "period": 1, - "unit": "Minutes", - "start_time": 1602100553 - } - }, - "description": "test transform", - "source_index": "sample_index", - "target_index": "sample_target", - "data_selection_query": { - "match_all": {} - }, - "page_size": 10, - "groups": [ - { - "terms": { - "source_field": "customer_gender", - "target_field": "gender" - } + "enabled": false, + "schedule": { + "interval": { + "period": 1, + "unit": "Minutes", + "start_time": 1602100553 + } }, - { - "terms": { - "source_field": "day_of_week", - "target_field": "day" + "description": "test transform", + "source_index": "opensearch_dashboards_sample_data_ecommerce", + "target_index": "ecommerce_transform", + "data_selection_query": { + "match_all": {} + }, + "page_size": 10, + "groups": [ + { + "terms": { + "source_field": "customer_gender", + "target_field": "gender" + } + }, + { + "terms": { + "source_field": "day_of_week", + "target_field": "day" + } + } + ], + "aggregations": { + "quantity": { + "sum": { + "field": "total_quantity" + } + } } - } - ], - "aggregations": { - "quantity": { - "sum": { - "field": "total_quantity" - } - } - } } } ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response + +Each document holds the grouped fields, the aggregated values, and the number of source documents in the bucket, reported in both `_doc_count` and `transform._doc_count`: ```json { "documents" : [ - { - "quantity" : 862.0, - "gender" : "FEMALE", - "day" : "Friday" - }, - { - "quantity" : 682.0, - "gender" : "FEMALE", - "day" : "Monday" - }, - { - "quantity" : 772.0, - "gender" : "FEMALE", - "day" : "Saturday" - }, - { - "quantity" : 669.0, - "gender" : "FEMALE", - "day" : "Sunday" - }, - { - "quantity" : 887.0, - "gender" : "FEMALE", - "day" : "Thursday" - } + { + "_doc_count" : 399, + "quantity" : 862.0, + "gender" : "FEMALE", + "transform._doc_count" : 399, + "day" : "Friday" + }, + { + "_doc_count" : 320, + "quantity" : 682.0, + "gender" : "FEMALE", + "transform._doc_count" : 320, + "day" : "Monday" + }, + { + "_doc_count" : 365, + "quantity" : 772.0, + "gender" : "FEMALE", + "transform._doc_count" : 365, + "day" : "Saturday" + }, + { + "_doc_count" : 315, + "quantity" : 669.0, + "gender" : "FEMALE", + "transform._doc_count" : 315, + "day" : "Sunday" + }, + { + "_doc_count" : 417, + "quantity" : 887.0, + "gender" : "FEMALE", + "transform._doc_count" : 417, + "day" : "Thursday" + }, + { + "_doc_count" : 323, + "quantity" : 690.0, + "gender" : "FEMALE", + "transform._doc_count" : 323, + "day" : "Tuesday" + }, + { + "_doc_count" : 294, + "quantity" : 612.0, + "gender" : "FEMALE", + "transform._doc_count" : 294, + "day" : "Wednesday" + }, + { + "_doc_count" : 371, + "quantity" : 821.0, + "gender" : "MALE", + "transform._doc_count" : 371, + "day" : "Friday" + }, + { + "_doc_count" : 259, + "quantity" : 586.0, + "gender" : "MALE", + "transform._doc_count" : 259, + "day" : "Monday" + }, + { + "_doc_count" : 371, + "quantity" : 798.0, + "gender" : "MALE", + "transform._doc_count" : 371, + "day" : "Saturday" + } ] } ``` +The preview returns at most `page_size` documents, so raise `page_size` to view the remaining buckets. +{: .note} + ## Delete a transform job -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Deletes a transform job. This operation does not delete the source or target indexes. -### Request format +An enabled job cannot be deleted. [Stop the job](#stop-a-transform-job) first, or set `force` to `true` to delete it while it is still enabled. -``` -DELETE _plugins/_transform/<transform_id> +### Endpoints + +```json +DELETE _plugins/_transform/{transform_id} ``` -#### Sample Request +### Query parameters + +Parameter | Description | Required +:--- | :--- | :--- +`force` | Deletes the transform job even if it is enabled. Default is `false`. | No + +#### Example request The following request deletes the transform job with the ID `sample`: ```json DELETE _plugins/_transform/sample ``` +{% include copy-curl.html %} -#### Sample Response +#### Example response ```json { @@ -790,7 +885,7 @@ DELETE _plugins/_transform/sample "items": [ { "delete": { - "_index": ".opensearch-ism-config", + "_index": ".opendistro-ism-config", "_id": "sample", "_version": 4, "result": "deleted", @@ -808,3 +903,6 @@ DELETE _plugins/_transform/sample ] } ``` + +Deleting a job that is still enabled fails with `409`. Deleting a job that does not exist returns `200`, with `"result": "not_found"` and `"status": 404` in the item. +{: .note} diff --git a/_im-plugin/index-tuning.md b/_im-plugin/index-tuning.md new file mode 100644 index 00000000..2afc883d --- /dev/null +++ b/_im-plugin/index-tuning.md @@ -0,0 +1,25 @@ +--- +layout: default +title: Tuning indexes +nav_order: 80 +has_children: true +has_toc: false +--- + +# Tuning indexes + +The settings on this page change how an index stores its data on disk, how its documents are ordered within a segment, how matching documents are scored, and how it advertises itself to other features. Most of them are static, so you set them when you create the index and cannot change them afterward without reindexing. + +| Topic | Description | +| :--- | :--- | +| [Refresh search analyzer]({{site.url}}{{site.baseurl}}/im-plugin/refresh-analyzer/) | Update the synonym list of a search analyzer without closing or reindexing an index. | +| [Index sorting]({{site.url}}{{site.baseurl}}/im-plugin/index-sorting/) | Order documents within each segment so that early termination can stop a search before it scans every document. | +| [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/) | Choose the compression algorithm used for stored fields, trading index size against indexing and search performance. | +| [Similarity]({{site.url}}{{site.baseurl}}/im-plugin/similarity/) | Configure the algorithm that scores and ranks matching documents. | +| [Index context]({{site.url}}{{site.baseurl}}/im-plugin/index-context/) | Apply a predefined set of settings and mappings for a use case, such as logs or metrics. | + +## Related documentation + +- [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) +- [Mappings and field types]({{site.url}}{{site.baseurl}}/field-types/) +- [Tuning for indexing speed]({{site.url}}{{site.baseurl}}/tuning-your-cluster/performance-tuning/indexing-speed/) diff --git a/_im-plugin/index.md b/_im-plugin/index.md index 87accd9a..0436ef32 100644 --- a/_im-plugin/index.md +++ b/_im-plugin/index.md @@ -6,285 +6,61 @@ has_children: false nav_exclude: true permalink: /im-plugin/ redirect_from: - - /opensearch/index-data/ - - /opensearch/rest-api/index-apis/index/ - /im-plugin/index/ --- # Managing indexes -You index data using the OpenSearch REST API. Two APIs exist: the index API and the `_bulk` API. +An index is the basic unit of data storage in OpenSearch: a collection of JSON documents, each identified by a unique ID, distributed across one or more shards. You can manage indexes using either the OpenSearch API or OpenSearch Dashboards. -For situations in which new data arrives incrementally (for example, customer orders from a small business), you might use the index API to add documents individually as they arrive. For situations in which the flow of data is less frequent (for example, weekly updates to a marketing website), you might prefer to generate a file and send it to the `_bulk` API. For large numbers of documents, lumping requests together and using the `_bulk` API offers superior performance. If your documents are enormous, however, you might need to index them individually. +If you are new to OpenSearch, start with [Add and manage your data]({{site.url}}{{site.baseurl}}/getting-started/manage-data/), which walks through creating an index, adding documents to it, and reading them back. -When indexing documents, the document `_id` must be 512 bytes or less in size. +## Working with indexes +Use the following topics to add documents, create and maintain indexes, and copy data between indexes. -## Introduction to indexing +| Topic | Description | +| :--- | :--- | +| [Indexing data]({{site.url}}{{site.baseurl}}/im-plugin/indexing-data/) | Add one or many documents to an index, with or without your own document IDs. | +| [Index operations]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/) | Create, inspect, close, open, and delete an index. | +| [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) | Refresh, flush, clear caches, force merge, shrink, split, clone, and roll over an index. | +| [Index templates]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/) | Apply the same settings and mappings to every index whose name matches a pattern. | +| [Index aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/) | Query a group of indexes under one name and switch that name between indexes without changing your clients. | +| [Reindexing data]({{site.url}}{{site.baseurl}}/im-plugin/reindex-data/) | Copy documents from one index into another, applying new mappings or transformations. | -Before you can search data, you must *index* it. Indexing is the method by which search engines organize data for fast retrieval. The resulting structure is called, fittingly, an index. +## Controlling how data is written -In OpenSearch, the basic unit of data is a JSON *document*. Within an index, OpenSearch identifies each document using a unique ID. +OpenSearch provides the following alternatives to a standard index, depending on how your data arrives and whether it changes after it is written. -A request to the index API looks like this: +| Topic | Description | +| :--- | :--- | +| [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) | Manage append-only time-series data as a single named stream backed by rolling indexes. | +| [Append-only index]({{site.url}}{{site.baseurl}}/im-plugin/append-only-index/) | Prevent updates and deletes on an index to reduce indexing overhead. | +| [Pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/) | Create an index that pulls data directly from Apache Kafka, Amazon Kinesis, or object storage. | -```json -PUT <index>/_doc/<id> -{ "A JSON": "document" } -``` +## Automating and summarizing data -A request to the `_bulk` API looks a little different, because you specify the index and ID in the bulk data: +Use the following features to run index operations automatically, summarize historical data, and get notified when long-running operations finish. -```json -POST _bulk -{ "index": { "_index": "<index>", "_id": "<id>" } } -{ "A JSON": "document" } -``` +| Topic | Description | +| :--- | :--- | +| [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) | Automate lifecycle operations, such as rollover and delete, based on index age, size, or document count. | +| [Index rollups]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/) | Summarize historical data into a smaller index to reduce storage cost. | +| [Index transforms]({{site.url}}{{site.baseurl}}/im-plugin/index-transforms/index/) | Build a materialized summary of your data, grouped by the fields you query most. | +| [Long-running operation notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/) | Get notified when a reindex, force merge, shrink, split, or open operation finishes or fails. | -Bulk data must conform to a specific format, which requires a newline character (`\n`) at the end of every line, including the last line. This is the basic format: +## Tuning and securing indexes -``` -Action and metadata\n -Optional document\n -Action and metadata\n -Optional document\n -``` +Use the following topics to optimize how indexes store and retrieve data and to control who can manage them. -The document is optional, because `delete` actions don't require a document. The other actions (`index`, `create`, and `update`) all require a document. If you specifically want the action to fail if the document already exists, use the `create` action instead of the `index` action. -{: .note } +| Topic | Description | +| :--- | :--- | +| [Tuning indexes]({{site.url}}{{site.baseurl}}/im-plugin/index-tuning/) | Configure codecs, index sorting, similarity, and other storage and retrieval options. | +| [Index management security]({{site.url}}{{site.baseurl}}/im-plugin/security/) | Control who can perform index management operations. | -To index bulk data using the `curl` command, navigate to the folder where you have your file saved and run the following command: - -```json -curl -H "Content-Type: application/x-ndjson" -POST https://localhost:9200/data/_bulk -u 'admin:admin' --insecure --data-binary "@data.json" -``` - -If any one of the actions in the `_bulk` API fail, OpenSearch continues to execute the other actions. Examine the `items` array in the response to figure out what went wrong. The entries in the `items` array are in the same order as the actions specified in the request. - -OpenSearch automatically creates an index when you add a document to an index that doesn't already exist. It also automatically generates an ID if you don't specify an ID in the request. This simple example automatically creates the movies index, indexes the document, and assigns it a unique ID: - -```json -POST movies/_doc -{ "title": "Spirited Away" } -``` - -Automatic ID generation has a clear downside: because the indexing request didn't specify a document ID, you can't easily update the document at a later time. Also, if you run this request 10 times, OpenSearch indexes this document as 10 different documents with unique IDs. To specify an ID of 1, use the following request (note the use of PUT instead of POST): - -```json -PUT movies/_doc/1 -{ "title": "Spirited Away" } -``` - -Because you must specify an ID, if you run this command 10 times, you still have just one document indexed with the `_version` field incremented to 10. - -Indexes default to one primary shard and one replica. If you want to specify non-default settings, create the index before adding documents: - -```json -PUT more-movies -{ "settings": { "number_of_shards": 6, "number_of_replicas": 2 } } -``` - -## Naming restrictions for indexes - -OpenSearch indexes have the following naming restrictions: - -- All letters must be lowercase. -- Index names can't begin with underscores (`_`) or hyphens (`-`). -- Index names can't contain spaces, commas, or the following characters: - - `:`, `"`, `*`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<` - - - -## Read data - -After you index a document, you can retrieve it by sending a GET request to the same endpoint that you used for indexing: - -```json -GET movies/_doc/1 - -{ - "_index" : "movies", - "_type" : "_doc", - "_id" : "1", - "_version" : 1, - "_seq_no" : 0, - "_primary_term" : 1, - "found" : true, - "_source" : { - "title" : "Spirited Away" - } -} -``` - -You can see the document in the `_source` object. If the document is not found, the `found` key is `false` and the `_source` object is not part of the response. - -To retrieve multiple documents with a single command, use the `_mget` operation. -The format for retrieving multiple documents is similar to the `_bulk` operation, where you must specify the index and ID in the request body: - -```json -GET _mget -{ - "docs": [ - { - "_index": "<index>", - "_id": "<id>" - }, - { - "_index": "<index>", - "_id": "<id>" - } - ] -} -``` - -To only return specific fields in a document: - -```json -GET _mget -{ - "docs": [ - { - "_index": "<index>", - "_id": "<id>", - "_source": "field1" - }, - { - "_index": "<index>", - "_id": "<id>", - "_source": "field2" - } - ] -} -``` - -To check if a document exists: - -```json -HEAD movies/_doc/<doc-id> -``` - -If the document exists, you get back a `200 OK` response, and if it doesn't, you get back a `404 - Not Found` error. - -## Update data - -To update existing fields or to add new fields, send a POST request to the `_update` operation with your changes in a `doc` object: - -```json -POST movies/_update/1 -{ - "doc": { - "title": "Castle in the Sky", - "genre": ["Animation", "Fantasy"] - } -} -``` - -Note the updated `title` field and new `genre` field: - -```json -GET movies/_doc/1 - -{ - "_index" : "movies", - "_type" : "_doc", - "_id" : "1", - "_version" : 2, - "_seq_no" : 1, - "_primary_term" : 1, - "found" : true, - "_source" : { - "title" : "Castle in the Sky", - "genre" : [ - "Animation", - "Fantasy" - ] - } -} -``` - -The document also has an incremented `_version` field. Use this field to keep track of how many times a document is updated. - -POST requests make partial updates to documents. To altogether replace a document, use a PUT request: - -```json -PUT movies/_doc/1 -{ - "title": "Spirited Away" -} -``` - -The document with ID of 1 will contain only the `title` field, because the entire document will be replaced with the document indexed in this PUT request. - -Use the `upsert` object to conditionally update documents based on whether they already exist. Here, if the document exists, its `title` field changes to `Castle in the Sky`. If it doesn't, OpenSearch indexes the document in the `upsert` object. - -```json -POST movies/_update/2 -{ - "doc": { - "title": "Castle in the Sky" - }, - "upsert": { - "title": "Only Yesterday", - "genre": ["Animation", "Fantasy"], - "date": 1993 - } -} -``` - -### Example response - -```json -{ - "_index" : "movies", - "_type" : "_doc", - "_id" : "2", - "_version" : 2, - "result" : "updated", - "_shards" : { - "total" : 2, - "successful" : 1, - "failed" : 0 - }, - "_seq_no" : 3, - "_primary_term" : 1 -} -``` - -Each update operation for a document has a unique combination of the `_seq_no` and `_primary_term` values. - -OpenSearch first writes your updates to the primary shard and then sends this change to all the replica shards. An uncommon issue can occur if multiple users of your OpenSearch-based application make updates to existing documents in the same index. In this situation, another user can read and update a document from a replica before it receives your update from the primary shard. Your update operation then ends up updating an older version of the document. In the best case, you and the other user make the same changes, and the document remains accurate. In the worst case, the document now contains out-of-date information. - -To prevent this situation, use the `_seq_no` and `_primary_term` values in the request header: - -```json -POST movies/_update/2?if_seq_no=3&if_primary_term=1 -{ - "doc": { - "title": "Castle in the Sky", - "genre": ["Animation", "Fantasy"] - } -} -``` - -If the document is updated after we retrieved it, the `_seq_no` and `_primary_term` values are different and our update operation fails with a `409 — Conflict` error. - -When using the `_bulk` API, specify the `_seq_no` and `_primary_term` values within the action metadata. - -## Delete data - -To delete a document from an index, use a DELETE request: - -```json -DELETE movies/_doc/1 -``` - -The DELETE operation increments the `_version` field. If you add the document back to the same ID, the `_version` field increments again. This behavior occurs because OpenSearch deletes the document `_source`, but retains its metadata. - - -## Next steps - -- The Index Management (IM) plugin lets you automate recurring index management activities and reduce storage costs. For more information, see [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index). - -- For instructions on how to reindex data, see [Reindex data]({{site.url}}{{site.baseurl}}/im-plugin/reindex-data/). +## Related documentation +- [Index APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/index/) +- [Index Management in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/index/) +- [Ingest your data into OpenSearch]({{site.url}}{{site.baseurl}}/getting-started/ingest-data/) +- [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) diff --git a/_im-plugin/indexing-data.md b/_im-plugin/indexing-data.md new file mode 100644 index 00000000..baa35b40 --- /dev/null +++ b/_im-plugin/indexing-data.md @@ -0,0 +1,48 @@ +--- +layout: default +title: Indexing data +nav_order: 3 +redirect_from: + - /opensearch/index-data/ +--- + +# Indexing data + +OpenSearch creates an index automatically the first time you add a document to a name that does not yet exist, and generates a document ID if you do not supply one. The following request creates the `movies` index and indexes one document into it: + +```json +POST movies/_doc +{ "title": "Spirited Away" } +``` +{% include copy-curl.html %} + +Specify the ID yourself when you expect to update or retrieve the document later. Sending the following request repeatedly leaves a single document in the index and increments its `_version` field, whereas repeating the preceding request creates a new document each time: + +```json +PUT movies/_doc/1 +{ "title": "Spirited Away" } +``` +{% include copy-curl.html %} + +A document ID must be 512 bytes or smaller. + +## Indexing multiple documents + +To index many documents in one request, use the [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/). Each action is described by a metadata line followed by the document itself, and every line must end with a newline character (`\n`), including the last one: + +```json +POST _bulk +{ "index": { "_index": "movies", "_id": "2" } } +{ "title": "My Neighbor Totoro" } +{ "index": { "_index": "movies", "_id": "3" } } +{ "title": "Princess Mononoke" } +``` +{% include copy-curl.html %} + +Bulk requests give better throughput than individual requests for large numbers of documents. If one action in a bulk request fails, OpenSearch runs the remaining actions and reports the outcome of each one in the `items` array of the response, in the order in which you specified the actions. + +## Related documentation + +- [Add and manage your data]({{site.url}}{{site.baseurl}}/getting-started/manage-data/): A tutorial that creates an index, adds documents to it, and reads them back. +- [Ingest data]({{site.url}}{{site.baseurl}}/getting-started/ingest-data/): Other ways to send data to OpenSearch, such as OpenSearch Ingestion and pull-based ingestion. +- [Document APIs]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index/): Retrieving, updating, and deleting documents. diff --git a/_im-plugin/ism/api.md b/_im-plugin/ism/api.md index 441f737e..4dd6bf7f 100644 --- a/_im-plugin/ism/api.md +++ b/_im-plugin/ism/api.md @@ -2,12 +2,12 @@ layout: default title: ISM API parent: Index State Management -nav_order: 20 +nav_order: 30 --- # ISM API -Use the index state management operations to programmatically work with policies and managed indexes. +Use the Index State Management (ISM) API to programmatically work with policies and managed indexes. --- @@ -20,11 +20,17 @@ Use the index state management operations to programmatically work with policies ## Create policy -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Creates a policy. +#### Endpoints + +```json +PUT _plugins/_ism/policies/{policy_id} +``` + #### Example request ```json @@ -74,7 +80,7 @@ PUT _plugins/_ism/policies/policy_1 } } ``` - +{% include copy-curl.html %} #### Example response @@ -97,8 +103,14 @@ PUT _plugins/_ism/policies/policy_1 "name": "ingest", "actions": [ { + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "1m" + }, "rollover": { - "min_doc_count": 5 + "min_doc_count": 5, + "copy_alias": false } } ], @@ -124,34 +136,57 @@ PUT _plugins/_ism/policies/policy_1 "name": "delete", "actions": [ { + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "1m" + }, "delete": {} } ], "transitions": [] } - ] + ], + "ism_template": null } } } ``` +The response echoes the policy with the defaults that ISM filled in, so each action gains a `retry` object and each operation gains the parameters that you did not set. --- ## Add policy -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } -Adds a policy to an index. This operation does not change the policy if the index already has one. +Adds a policy to an index. To change the policy of an index that already has one, use [Update managed index policy](#update-managed-index-policy) instead. + +#### Endpoints + +```json +POST _plugins/_ism/add/{index} +``` #### Example request +Create the index first: + +```json +PUT index_1 +``` +{% include copy-curl.html %} + +Then add the policy to the index: + ```json POST _plugins/_ism/add/index_1 { "policy_id": "policy_1" } ``` +{% include copy-curl.html %} #### Example response @@ -163,6 +198,22 @@ POST _plugins/_ism/add/index_1 } ``` +Adding a policy to an index that already has one does not overwrite it. The request returns `200`, but the index appears in `failed_indices` and `failures` is `true`: + +```json +{ + "updated_indices": 0, + "failures": true, + "failed_indices": [ + { + "index_name": "index_1", + "index_uuid": "t6a6I5YDQTiXY9c7cymI_w", + "reason": "This index already has a policy, use the update policy API to update index policies" + } + ] +} +``` + If you use a wildcard `*` while adding a policy to an index, the ISM plugin interprets `*` as all indexes, including system indexes like `.opendistro-security`, which stores users, roles, and tenants. A delete action in your policy might accidentally delete all user roles and tenants in your cluster. Don't use the broad `*` wildcard, and instead add a prefix, such as `my-logs*`, when specifying indexes with the `_ism/add` API. {: .warning } @@ -171,12 +222,18 @@ Don't use the broad `*` wildcard, and instead add a prefix, such as `my-logs*`, ## Update policy -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Updates a policy. Use the `seq_no` and `primary_term` parameters to update an existing policy. If these numbers don't match the existing policy or the policy doesn't exist, ISM throws an error. -It's possible that the policy currently applied to your index isn't the most up-to-date policy available. To see what policy is currently applied to your index, see [Explain index]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#explain-index). To get the most up-to-date version of a policy, see [Get policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#get-policy). +It's possible that the policy currently applied to your index isn't the most up-to-date policy available. To view the policy that is currently applied to your index, see [Explain index]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#explain-index). To get the most up-to-date version of a policy, see [Get policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#get-policy). + +#### Endpoints + +```json +PUT _plugins/_ism/policies/{policy_id}?if_seq_no={seq_no}&if_primary_term={primary_term} +``` #### Example request @@ -227,6 +284,7 @@ PUT _plugins/_ism/policies/policy_1?if_seq_no=7&if_primary_term=1 } } ``` +{% include copy-curl.html %} #### Example response @@ -250,8 +308,14 @@ PUT _plugins/_ism/policies/policy_1?if_seq_no=7&if_primary_term=1 "name": "ingest", "actions": [ { + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "1m" + }, "rollover": { - "min_doc_count": 5 + "min_doc_count": 5, + "copy_alias": false } } ], @@ -277,12 +341,18 @@ PUT _plugins/_ism/policies/policy_1?if_seq_no=7&if_primary_term=1 "name": "delete", "actions": [ { + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "1m" + }, "delete": {} } ], "transitions": [] } - ] + ], + "ism_template": null } } } @@ -292,16 +362,23 @@ PUT _plugins/_ism/policies/policy_1?if_seq_no=7&if_primary_term=1 --- ## Get policy -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Gets the policy by `policy_id`. +#### Endpoints + +```json +GET _plugins/_ism/policies/{policy_id} +``` + #### Example request ```json GET _plugins/_ism/policies/policy_1 ``` +{% include copy-curl.html %} #### Example response @@ -316,7 +393,7 @@ GET _plugins/_ism/policies/policy_1 "policy_id": "policy_1", "description": "ingesting logs", "last_updated_time": 1577990934044, - "schema_version": 1, + "schema_version": 30, "error_notification": null, "default_state": "ingest", "states": [ @@ -324,8 +401,14 @@ GET _plugins/_ism/policies/policy_1 "name": "ingest", "actions": [ { + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "1m" + }, "rollover": { - "min_doc_count": 5 + "min_doc_count": 5, + "copy_alias": false } } ], @@ -351,29 +434,117 @@ GET _plugins/_ism/policies/policy_1 "name": "delete", "actions": [ { + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "1m" + }, "delete": {} } ], "transitions": [] } - ] + ], + "ism_template": null } } ``` --- +## Get policies +**Introduced 1.0** +{: .label .label-purple } + +Gets a list of policies. This API accepts search parameters to filter and paginate the results. + +#### Endpoints + +```json +GET _plugins/_ism/policies +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `size` | Integer | The number of policies to return. | +| `from` | Integer | The starting position for pagination. | +| `sortField` | String | The field by which to sort the results, given as a path into the stored policy document, such as `policy.policy_id.keyword` or `policy.last_updated_time`. An unmapped name such as `policy_id` is rejected with `400`. | +| `sortOrder` | String | The sort order for the results. Valid values are `asc` (ascending) and `desc` (descending). | +| `queryString` | String | A query string used to filter policies by name or other attributes. See [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/).| + +#### Example request + +```json +GET _plugins/_ism/policies +``` +{% include copy-curl.html %} + +#### Example response + +Each entry contains the sequence number and primary term of the policy but not its `_version`. The `states` array of each policy is omitted from the following response for brevity: + +```json +{ + "policies": [ + { + "_id": "policy_1", + "_seq_no": 10, + "_primary_term": 1, + "policy": { + "policy_id": "policy_1", + "description": "ingesting logs", + "last_updated_time": 1577990934044, + "schema_version": 30, + "error_notification": null, + "default_state": "ingest", + "states": [], + "ism_template": null + } + }, + { + "_id": "policy_2", + "_seq_no": 11, + "_primary_term": 1, + "policy": { + "policy_id": "policy_2", + "description": "ingesting logs", + "last_updated_time": 1577990934042, + "schema_version": 30, + "error_notification": null, + "default_state": "ingest", + "states": [], + "ism_template": null + } + } + ], + "total_policies": 2 +} +``` + +--- + ## Remove policy from index -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Removes any ISM policy from the index. +#### Endpoints + +```json +POST _plugins/_ism/remove/{index} +``` + #### Example request ```json POST _plugins/_ism/remove/index_1 ``` +{% include copy-curl.html %} #### Example response @@ -389,7 +560,7 @@ POST _plugins/_ism/remove/index_1 --- ## Update managed index policy -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Updates the managed index policy to a new policy (or to a new version of the policy). You can use an index pattern to update multiple indexes at once. When updating multiple indexes, you might want to include a state filter to only affect certain managed indexes. The change policy filters out all the existing managed indexes and only applies the change to the ones in the state that you specify. You can also explicitly specify the state that the managed index transitions to after the change policy takes effect. @@ -398,6 +569,12 @@ A policy change is an asynchronous background process. The changes are queued an In this example, the policy applied on the `index_1` index is changed to `policy_1`, which could either be a completely new policy or an updated version of its existing policy. The process only applies the change if the index is currently in the `searches` state. After this change in policy takes place, `index_1` transitions to the `delete` state. +#### Endpoints + +```json +POST _plugins/_ism/change_policy/{index} +``` + #### Example request ```json @@ -412,59 +589,96 @@ POST _plugins/_ism/change_policy/index_1 ] } ``` +{% include copy-curl.html %} #### Example response ```json { - "updated_indices": 0, + "updated_indices": 1, "failures": false, "failed_indices": [] } ``` +The change is queued on the managed index and takes effect on the next job run, so `updated_indices` counts the indexes whose change policy was recorded, not the indexes that have already moved to the new policy. + --- ## Retry failed index -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Retries the failed action for an index. For the retry call to succeed, ISM must manage the index, and the index must be in a failed state. You can use index patterns (`*`) to retry multiple failed indexes. +Use [Explain index](#explain-index) to confirm that an index is in a failed state: its `action` object contains `"failed": true` and its `step` object contains `"step_status": "failed"`. + +Optionally, specify a `state` in the request body to restart the index in that state rather than in the state in which it failed. + +#### Endpoints + +```json +POST _plugins/_ism/retry/{index} +``` + #### Example request ```json POST _plugins/_ism/retry/index_1 { - "state": "delete" + "state": "hot" } ``` +{% include copy-curl.html %} #### Example response ```json { - "updated_indices": 0, + "updated_indices": 1, "failures": false, "failed_indices": [] } ``` +If the index is not in a failed state, the response reports the index in `failed_indices`: + +```json +{ + "updated_indices": 0, + "failures": true, + "failed_indices": [ + { + "index_name": "index_1", + "index_uuid": "t6a6I5YDQTiXY9c7cymI_w", + "reason": "This index is not in failed state." + } + ] +} +``` + --- ## Explain index -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Gets the current state of the index. You can use index patterns to get the status of multiple indexes. +#### Endpoints + +```json +GET _plugins/_ism/explain/{index} +``` + #### Example request ```json GET _plugins/_ism/explain/index_1 ``` +{% include copy-curl.html %} #### Example response @@ -472,11 +686,20 @@ GET _plugins/_ism/explain/index_1 ```json { "index_1": { - "index.plugins.index_state_management.policy_id": "policy_1" - } + "index.plugins.index_state_management.policy_id": "policy_1", + "index.opendistro.index_state_management.policy_id": "policy_1", + "index": "index_1", + "index_uuid": "t6a6I5YDQTiXY9c7cymI_w", + "policy_id": "policy_1", + "enabled": true + }, + "total_managed_indices": 1 } ``` +Immediately after you add a policy, the fields of the response are `null` and `total_managed_indices` is `0`. ISM creates the managed index job on its next sweep, and the response is populated from then on. +{: .note} + Optionally, you can add the `show_policy` parameter to your request's path to get the policy that is currently applied to your index, which is useful for seeing whether the policy applied to your index is the latest one. To get the most up-to-date policy, see [Get Policy API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#get-policy). #### Example request @@ -484,6 +707,7 @@ Optionally, you can add the `show_policy` parameter to your request's path to ge ```json GET _plugins/_ism/explain/index_1?show_policy=true ``` +{% include copy-curl.html %} #### Example response @@ -500,10 +724,10 @@ GET _plugins/_ism/explain/index_1?show_policy=true "policy_id": "sample-policy", "description": "ingesting logs", "last_updated_time": 1647284980148, - "schema_version": 13, + "schema_version": 30, "error_notification": null, "default_state": "ingest", - "states": [...], + "states": [], "ism_template": null } }, @@ -513,19 +737,363 @@ GET _plugins/_ism/explain/index_1?show_policy=true The `plugins.index_state_management.policy_id` setting is deprecated starting from ODFE version 1.13.0. We retain this field in the response API for consistency. +## Explain index with filtering +**Introduced 2.12** +{: .label .label-purple } + +You can use the `POST` method with the Explain API to filter the results based on specific criteria. This allows you to query indexes based on their policy ID, current state, or action type. + +#### Endpoints + +```json +POST _plugins/_ism/explain/{index} +``` + +#### Request body + +The request body supports the following optional filters. If a filter is not specified, indexes with any value for that parameter are included in the results. The API returns only indexes that match all specified filters. + +| Parameter | Type | Description | +|:----------|:-----|:------------| +| `policy_id` | String | Filter results to show only indexes managed by the specified policy ID. | +| `state` | String | Filter results to show only indexes currently in the specified state. | +| `action_type` | String | Filter results to show only indexes currently executing the specified action type. | +| `failed` | Boolean | Filter results to show only failed managed indexes. | + +#### Example request: Filter by policy ID + +```json +POST _plugins/_ism/explain/log-* +{ + "filter": { + "policy_id": "hot-warm-delete-policy" + } +} +``` +{% include copy-curl.html %} + +#### Example request: Filter by state and action type + +```json +POST _plugins/_ism/explain/app-* +{ + "filter": { + "state": "warm", + "action_type": "allocation" + } +} +``` +{% include copy-curl.html %} + +#### Example request: Filter by all criteria + +```json +POST _plugins/_ism/explain/data-* +{ + "filter": { + "policy_id": "data-lifecycle-policy", + "state": "hot", + "action_type": "rollover" + } +} +``` +{% include copy-curl.html %} + +#### Example response + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "test-logs-001": { + "index.plugins.index_state_management.policy_id": "test-lifecycle-policy", + "index": "test-logs-001", + "index_uuid": "LmJgKNatQZWHQu-qIHlcJw", + "policy_id": "test-lifecycle-policy", + "enabled": true, + "policy": { + "policy_id": "test-lifecycle-policy", + "description": "Lifecycle policy for log data: hot -> warm -> cold -> delete", + "last_updated_time": 1730308440926, + "schema_version": 30, + "error_notification": null, + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [ + { + "rollover": { + "min_doc_count": 10000, + "min_size": "1gb", + "min_index_age": "1d" + } + } + ], + "transitions": [ + { + "state_name": "warm", + "conditions": { + "min_index_age": "7d" + } + } + ] + }, + { + "name": "warm", + "actions": [ + { + "replica_count": { + "number_of_replicas": 0 + } + } + ], + "transitions": [ + { + "state_name": "cold", + "conditions": { + "min_index_age": "30d" + } + } + ] + }, + { + "name": "cold", + "actions": [], + "transitions": [ + { + "state_name": "delete", + "conditions": { + "min_index_age": "90d" + } + } + ] + }, + { + "name": "delete", + "actions": [ + { + "delete": {} + } + ], + "transitions": [] + } + ], + "ism_template": null + }, + "policy_seq_no": 0, + "policy_primary_term": 1, + "rolled_over": false, + "index_creation_date": 1730308447399, + "state": { + "name": "hot", + "start_time": 1730308447644 + }, + "action": { + "name": "rollover", + "start_time": 1730308447644, + "index": 0, + "failed": false, + "consumed_retries": 0, + "last_retry_time": 0 + }, + "step": { + "name": "attempt_rollover", + "start_time": 1730308447644, + "step_status": "starting" + }, + "retry_info": { + "failed": false, + "consumed_retries": 0 + }, + "info": { + "message": "Currently checking rollover conditions" + }, + "enabled": true, + "enabled_time": 1730308447644 + }, + "total_managed_indices": 1 +} +``` + +</details> + +--- + +## Simulate policy +**Introduced 3.7** +{: .label .label-purple } + +Previews how a policy would apply to one or more indexes without making any changes. For each index, the response contains the current state, the next action to execute, the evaluation of every transition condition, and which state the index would move to next. Use this endpoint to validate a policy before attaching it or to debug why an index is not transitioning as expected. + +Exactly one of `policy_id` or `policy` must be provided. + +#### Endpoints + +```json +POST _plugins/_ism/simulate +``` + +#### Request body fields + +The following table lists the available request body fields. + +| Field | Type | Required | Description | +|:------|:-----|:---------|:------------| +| `policy_id` | String | Conditional | The ID of a stored ISM policy to simulate. Required when `policy` is not provided. | +| `policy` | Object | Conditional | An inline policy definition to simulate without saving it. Required when `policy_id` is not provided. | +| `indices` | Array of strings | Yes | The index names or wildcard patterns to simulate against. Wildcard patterns are expanded to matching concrete indexes. Patterns that match no indexes are silently ignored. Concrete index names that do not exist return an error in the per-index result. | + +#### Response body fields + +The following table lists all response body fields. The response contains a `simulate_results` array with one entry per index. + +| Field | Type | Description | +|:------|:-----|:------------| +| `index_name` | String | The name of the index. | +| `index_uuid` | String | The UUID of the index. `null` when the index was not found. | +| `policy_id` | String | The ID of the policy used for simulation. Empty string for inline policies. | +| `is_managed` | Boolean | Whether the index is managed by ISM. | +| `current_state` | String | The state the index is in, or would start in for unmanaged indexes. Omitted when `error` is present. | +| `current_action` | String | The action that would execute next in the current state. Omitted when `error` is present. | +| `transition_evaluation` | Array | Per-transition condition evaluations. Present only when the index is in the transition phase (no pending actions). Omitted when `error` is present. | +| `next_state` | String | The state the index would transition to (first met condition). `null` if no condition is met. Omitted when `error` is present. | +| `error` | String | An index-level error message. Present when the index does not exist or another index-level error occurs. When this field is present, all other fields except `index_name`, `index_uuid`, `policy_id`, and `is_managed` are omitted. | + +Each object in `transition_evaluation` contains the following fields. + +| Field | Type | Description | +|:------|:-----|:------------| +| `state_name` | String | The target state this transition would move the index to. | +| `condition_met` | Boolean | Whether the transition condition is satisfied. | +| `condition_type` | String | The condition type (for example, `min_index_age`, `min_doc_count`, `min_size`). Set to `unconditional` for transitions with no conditions. | +| `current_value` | String | The current value of the metric being checked, formatted as a readable string (for example, `"3d 4h"`). Omitted for unconditional transitions. | +| `required_value` | String | The threshold required by the condition, formatted as a readable string (for example, `"7d"`). Omitted for unconditional transitions. | + +#### Example request: Simulate a stored policy + +The following request simulates the [`policy_1` policy](#create-policy) against `index_1` and an index that does not exist: + +```json +POST _plugins/_ism/simulate +{ + "policy_id": "policy_1", + "indices": ["index_1", "nonexistent-index"] +} +``` +{% include copy-curl.html %} + +#### Example response: Simulate a stored policy + +The first result shows that `index_1` would start in the `ingest` state with `rollover` as its next action. The second shows the `error` field that a concrete index name returns when the index does not exist in the cluster: + +```json +{ + "simulate_results": [ + { + "index_name": "index_1", + "index_uuid": "CNMBFMEIR12NYiOeW-pX4A", + "policy_id": "policy_1", + "is_managed": false, + "current_state": "ingest", + "current_action": "rollover", + "next_state": null + }, + { + "index_name": "nonexistent-index", + "index_uuid": null, + "policy_id": "policy_1", + "is_managed": false, + "error": "Index 'nonexistent-index' not found in cluster" + } + ] +} +``` + +#### Example request: Simulate an inline policy + +The following request simulates a policy that is not stored in the cluster: + +```json +POST _plugins/_ism/simulate +{ + "policy": { + "description": "hot-warm lifecycle", + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [], + "transitions": [ + { + "state_name": "warm", + "conditions": { "min_index_age": "7d" } + } + ] + }, + { "name": "warm", "actions": [], "transitions": [] } + ] + }, + "indices": ["index_1"] +} +``` +{% include copy-curl.html %} + +#### Example response: Simulate an inline policy + +Because the `hot` state defines no actions, the next action is the transition itself, so the response contains a `transition_evaluation` array. The `min_index_age` condition is not met, so `next_state` is `null`. The `policy_id` field is an empty string because the policy is not stored: + +```json +{ + "simulate_results": [ + { + "index_name": "index_1", + "index_uuid": "CNMBFMEIR12NYiOeW-pX4A", + "policy_id": "", + "is_managed": false, + "current_state": "hot", + "current_action": "transition", + "transition_evaluation": [ + { + "state_name": "warm", + "condition_met": false, + "condition_type": "min_index_age", + "current_value": "8.5s", + "required_value": "7d" + } + ], + "next_state": null + } + ] +} +``` + + + --- ## Delete policy -Introduced 1.0 +**Introduced 1.0** {: .label .label-purple } Deletes the policy by `policy_id`. +#### Endpoints + +```json +DELETE _plugins/_ism/policies/{policy_id} +``` + #### Example request ```json DELETE _plugins/_ism/policies/policy_1 ``` +{% include copy-curl.html %} #### Example response @@ -548,31 +1116,34 @@ DELETE _plugins/_ism/policies/policy_1 ``` ## Error prevention validation -Introduced 2.4 +**Introduced 2.4** {: .label .label-purple } -ISM allows you to run an action automatically. However, running an action can fail for a variety of reasons. You can use error prevention validation to test an action in order to rule out failures. +ISM runs actions automatically. However, actions can fail for various reasons. You can use error prevention validation to test an action and identify potential failures. -To enable error prevention validation, set the `plugins.index_state_management.validation_service.enabled` setting to `true`: +To enable error prevention validation, set `plugins.index_state_management.action_validation.enabled` to `true`: -```bash +```json PUT _cluster/settings { - "persistent":{ - "plugins.index_state_management.validation_action.enabled": true + "persistent": { + "plugins.index_state_management.action_validation.enabled": true } } ``` +{% include copy-curl.html %} #### Example response +The following response confirms the setting was updated: + ```json { "acknowledged" : true, "persistent" : { "plugins" : { "index_state_management" : { - "validation_action" : { + "action_validation" : { "enabled" : "true" } } @@ -582,11 +1153,12 @@ PUT _cluster/settings } ``` -To check an error prevention validation status and message, pass `validate_action=true` to the `_plugins/_ism/explain` endpoint: +To retrieve the error prevention validation status and message, pass `validate_action=true` to the `_plugins/_ism/explain` endpoint: -```bash +```json GET _plugins/_ism/explain/test-000001?validate_action=true ``` +{% include copy-curl.html %} #### Example response @@ -638,17 +1210,17 @@ The response contains an additional validate object with a validation message an } ``` -If you pass `validate_action=false` or do not pass a `validate_action` value to the `_plugins/_ism/explain` endpoint, the response will not contain an error prevention validation status and message: +If you pass `validate_action=false` or omit the `validate_action` parameter, the response does not contain the validation status and message: -```bash +```json GET _plugins/_ism/explain/test-000001?validate_action=false ``` +{% include copy-curl.html %} -Or: - -```bash +```json GET _plugins/_ism/explain/test-000001 ``` +{% include copy-curl.html %} #### Example response @@ -692,4 +1264,4 @@ GET _plugins/_ism/explain/test-000001 }, "total_managed_indices" : 1 } -``` \ No newline at end of file +``` diff --git a/_im-plugin/ism/error-prevention/api.md b/_im-plugin/ism/error-prevention/api.md index a273d25c..145d0966 100644 --- a/_im-plugin/ism/error-prevention/api.md +++ b/_im-plugin/ism/error-prevention/api.md @@ -1,9 +1,9 @@ --- layout: default title: ISM Error Prevention API -parent: ISM Error Prevention +parent: ISM error prevention grand_parent: Index State Management -nav_order: 10 +nav_order: 20 --- # ISM Error Prevention API @@ -12,18 +12,19 @@ The ISM Error Prevention API allows you to enable Index State Management (ISM) e ## Enable error prevention validation -You can configure error prevention validation by setting the `plugins.index_state_management.validation_service.enabled` parameter. +You can configure error prevention validation by setting the `plugins.index_state_management.action_validation.enabled` parameter. #### Example request -```bash +```json PUT _cluster/settings { "persistent":{ - "plugins.index_state_management.validation_action.enabled": true + "plugins.index_state_management.action_validation.enabled": true } } ``` +{% include copy-curl.html %} #### Example response @@ -33,7 +34,7 @@ PUT _cluster/settings "persistent" : { "plugins" : { "index_state_management" : { - "validation_action" : { + "action_validation" : { "enabled" : "true" } } @@ -43,15 +44,16 @@ PUT _cluster/settings } ``` -## Check validation status and message via the Explain API +## Check validation status and message using the Explain API -Pass the `validate_action=true` path parameter in the Explain API URI to see the validation status and message. +Pass the `validate_action=true` path parameter in the Explain API URI to view the validation status and message. #### Example request -```bash +```json GET _plugins/_ism/explain/test-000001?validate_action=true ``` +{% include copy-curl.html %} #### Example response @@ -101,15 +103,21 @@ GET _plugins/_ism/explain/test-000001?validate_action=true } ``` -If you pass the parameter without a value or false, then it doesn't return the validation status and message. Only if you pass `validate_action=true` will the response will return the validation status and message. +The validation status and message are returned only when you pass `validate_action=true`. Setting the parameter to `false` or omitting it returns neither. #### Example request -```bash +```json GET _plugins/_ism/explain/test-000001?validate_action=false - --- OR --- +``` +{% include copy-curl.html %} + +Omitting the parameter has the same result: + +```json GET _plugins/_ism/explain/test-000001 ``` +{% include copy-curl.html %} #### Example response diff --git a/_im-plugin/ism/error-prevention/index.md b/_im-plugin/ism/error-prevention/index.md index a76f62d4..4fb61362 100644 --- a/_im-plugin/ism/error-prevention/index.md +++ b/_im-plugin/ism/error-prevention/index.md @@ -1,12 +1,12 @@ --- layout: default -title: ISM Error Prevention -nav_order: 90 +title: ISM error prevention +parent: Index State Management +nav_order: 40 has_children: true has_toc: false redirect_from: - /im-plugin/ism/error-prevention/ - - /im-plugin/ism/error-prevention/index/ --- # ISM error prevention @@ -22,17 +22,17 @@ Error prevention validates Index State Management (ISM) actions before they are --- -## rollover +## Roll over ISM does not perform a `rollover` action for an index under any of these conditions: - [The index is not the write index]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#the-index-is-not-the-write-index). - [The index does not have an alias]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#the-index-does-not-have-an-alias). - [The rollover policy does not contain a rollover_alias index setting]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#the-rollover-policy-misses-rollover_alias-index-setting). -- [Skipping of a rollover action has occured]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#skipping-rollover-action-is-true). +- [Skipping of a rollover action has occurred]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#skipping-rollover-action-is-true). - [The index has already been rolled over using the alias successfully]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#this-index-has-already-been-rolled-over-successfully). -## delete +## Delete ISM does not perform a `delete` action for an index under any of these conditions: @@ -40,55 +40,64 @@ ISM does not perform a `delete` action for an index under any of these condition - The index name is invalid. - The index is the write index for a data stream. -## force_merge +## Force merge ISM does not perform a `force_merge` action for an index if its dataset is too large and exceeds the threshold. -## replica_count +## Replica count ISM does not perform a `replica_count` action for an index under any of these conditions: - The amount of data exceeds the threshold. - The number of shards exceeds the maximum. -## open +## Open ISM does not perform an `open` action for an index under any of these conditions: - The index is blocked. - The number of shards exceeds the maximum. -## read_only +## Read only ISM does not perform a `read_only` action for an index under any of these conditions: - The index is blocked. - The amount of data exceeds the threshold. -## read_write +## Read write ISM does not perform a `read_write` action for an index if the index is blocked. -## close +## Close ISM does not perform a `close` action for an index under any of these conditions: - The index does not exist. - The index name is invalid. -## index_priority +## Index priority ISM does not perform an `index_priority` action for an index that does not have `read-only-allow-delete` permission. -## snapshot +## Snapshot ISM does not perform a `snapshot` action for an index under any of these conditions: - The index does not exist. - The index name is invalid. -## transition +## Search only + +ISM does not perform a `search_only` action for an index under any of these conditions: + +- The index does not exist. +- [Remote store is not enabled]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#remote-store-is-not-enabled) on the cluster. +- [Segment replication is not enabled]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#segment-replication-is-not-enabled) for the index. +- [No search replicas are configured]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/resolutions/#no-search-replicas-configured) for the index. + +## Transition ISM does not perform a `transition` action for an index under any of these conditions: diff --git a/_im-plugin/ism/error-prevention/resolutions.md b/_im-plugin/ism/error-prevention/resolutions.md index 5502691f..35d67587 100644 --- a/_im-plugin/ism/error-prevention/resolutions.md +++ b/_im-plugin/ism/error-prevention/resolutions.md @@ -1,9 +1,9 @@ --- layout: default -title: ISM Error Prevention resolutions -parent: ISM Error Prevention +title: ISM error prevention resolutions +parent: ISM error prevention grand_parent: Index State Management -nav_order: 5 +nav_order: 10 --- # ISM error prevention resolutions @@ -23,17 +23,18 @@ Resolutions of errors for each validation rule action are listed in the followin To confirm that the index is a write index, run the following request: -```bash -GET <index>/_alias?pretty +```json +GET {index}/_alias?pretty ``` +{% include copy-curl.html %} -If the response does not contain `"is_write_index"` : true, the index is not a write index. The following example confirms that the index is a write index: +The following example response shows that the index is a write index: ```json { "<index>" : { "aliases" : { - "<index_alias>" : { + "<index_alias>" : { "is_write_index" : true } } @@ -41,63 +42,82 @@ If the response does not contain `"is_write_index"` : true, the index is not a w } ``` -To set the index as a write index, run the following request: +If `is_write_index` is not `true`, the index is not a write index. To set the index as a write index, run the following request: -```bash -PUT <index> -{ - "aliases": { - "<index_alias>" : { - "is_write_index" : true - } - } -} -``` - -## The index does not have an alias - -If the index does not have an alias, you can add one by running the following request: - -```bash +```json POST _aliases { "actions": [ { "add": { - "index": "<target_index>", + "index": "<index>", + "alias": "<index_alias>", + "is_write_index": true + } + } + ] +} +``` +{% include copy-curl.html %} + +## The index does not have an alias + +If the index does not have an alias, you can add one by running the following request: + +```json +POST _aliases +{ + "actions": [ + { + "add": { + "index": "<index>", "alias": "<index_alias>" } } ] } ``` +{% include copy-curl.html %} ## Skipping rollover action is true -In the event that skipping a rollover action occurs, run the following request: +If the rollover action is being skipped, check the index settings by running the following request: -```bash - GET <target_index>/_settings?pretty +```json +GET {index}/_settings?pretty ``` +{% include copy-curl.html %} -If you receive the response in the first example, you can reset it by running the request in the second example: +The following example response shows that rollover is set to be skipped: ```json { - "index": { - "opendistro.index_state_management.rollover_skip": true + "<index>" : { + "settings" : { + "index" : { + "plugins" : { + "index_state_management" : { + "rollover_skip" : "true" + } + }, + ... + } + } } } ``` -```bash -PUT <target_index>/_settings +To reset the setting, run the following request: + +```json +PUT {index}/_settings { - "index": { - "index_state_management.rollover_skip": false + "index": { + "plugins.index_state_management.rollover_skip": false } } ``` +{% include copy-curl.html %} ## This index has already been rolled over successfully @@ -107,17 +127,18 @@ Remove the [rollover policy from the index]({{site.url}}{{site.baseurl}}/im-plug Add a `rollover_alias` index setting to the rollover policy to resolve this issue. Run the following request: -```bash +```json PUT _index_template/ism_rollover { "index_patterns": ["<index_patterns_in_rollover_policy>"], "template": { - "settings": { - "plugins.index_state_management.rollover_alias": "<rollover_alias>" - } - } + "settings": { + "plugins.index_state_management.rollover_alias": "<rollover_alias>" + } + } } ``` +{% include copy-curl.html %} ## Data too large and exceeding the threshold @@ -127,43 +148,57 @@ Check the [JVM information]({{site.url}}{{site.baseurl}}/api-reference/nodes-api The shard limit per node, or per index, causes this issue to occur. Check whether there is a `total_shards_per_node` limit by running the following request: -```bash +```json GET /_cluster/settings ``` +{% include copy-curl.html %} If the response contains `total_shards_per_node`, increase its value temporarily by running the following request: -```bash +```json PUT _cluster/settings { - "transient":{ - "cluster.routing.allocation.total_shards_per_node":100 - } + "transient": { + "cluster.routing.allocation.total_shards_per_node": 100 + } } ``` +{% include copy-curl.html %} To check whether there is a shard limit for an index, run the following request: -```bash -GET <index>/_settings/index.routing- +```json +GET {index}/_settings/index.routing.* ``` +{% include copy-curl.html %} -If the response contains the setting in the first example, increase its value or set it to `-1` for unlimited shards, as shown in the second example: +The following example response shows a limit of 10 shards per node: ```json -"index" : { +{ + "<index>" : { + "settings" : { + "index" : { "routing" : { "allocation" : { "total_shards_per_node" : "10" } } } + } + } +} ``` -```bash -PUT <index>/_settings -{"index.routing.allocation.total_shards_per_node":-1} +To increase the limit, or to set it to `-1` for unlimited shards, run the following request: + +```json +PUT {index}/_settings +{ + "index.routing.allocation.total_shards_per_node": -1 +} ``` +{% include copy-curl.html %} ## The index is a write index for some data stream @@ -173,57 +208,102 @@ If you still want to delete the index, check your [data stream]({{site.url}}{{si Generally, the index is blocked because disk usage has exceeded the flood-stage watermark and the index has a `read-only-allow-delete` block. To resolve this issue, you can: -1. Remove the `-index.blocks.read_only_allow_delete-` parameter. +1. Remove the `index.blocks.read_only_allow_delete` parameter. 1. Temporarily increase the disk watermarks. 1. Temporarily disable the disk allocation threshold. To prevent the issue from reoccurring, it is better to reduce the usage of the disk by increasing disk space, adding new nodes, or removing data or indexes that are no longer needed. -Remove `-index.blocks.read_only_allow_delete-` by running the following request: +Remove `index.blocks.read_only_allow_delete` by running the following request: -```bash -PUT <index>/_settings +```json +PUT {index}/_settings { - "index.blocks.read_only_allow_delete": null + "index.blocks.read_only_allow_delete": null } ``` +{% include copy-curl.html %} -Increase the low disk watermarks by running the following request: +The `read-only-allow-delete` block is applied when disk usage exceeds the `flood_stage` watermark, so raising only the `low` watermark does not remove it. Set the `low`, `high`, and `flood_stage` watermarks together, specifying all three as percentages or all three as byte values. -```bash +Percentages set the maximum disk usage, so the `low` watermark must be the smallest value. To increase the watermarks using percentages, send the following request: + +```json PUT _cluster/settings { - "transient": { - "cluster": { - "routing": { - "allocation": { - "disk": { - "watermark": { - "low": "25.0gb" - } - } - } + "transient": { + "cluster": { + "routing": { + "allocation": { + "disk": { + "watermark": { + "low": "90%", + "high": "95%", + "flood_stage": "97%" } + } } + } } + } } ``` +{% include copy-curl.html %} + +Byte values set the minimum free disk space, so the `low` watermark must be the largest value. Use whole numbers because OpenSearch rejects fractional byte values. To set the watermarks using byte values, send the following request: + +```json +PUT _cluster/settings +{ + "transient": { + "cluster": { + "routing": { + "allocation": { + "disk": { + "watermark": { + "low": "50gb", + "high": "25gb", + "flood_stage": "10gb" + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +When disk usage on the node falls below the `high` watermark, OpenSearch removes the `read-only-allow-delete` block automatically. After you free up disk space, reset the watermarks to their default values by setting them to `null`. Disable the disk allocation threshold by running the following request: -```bash +```json PUT _cluster/settings { - "transient": { - "cluster": { - "routing": { - "allocation": { - "disk": { - "threshold_enabled" : false - } - } - } + "transient": { + "cluster": { + "routing": { + "allocation": { + "disk": { + "threshold_enabled": false + } } + } } + } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +## Remote store is not enabled + +The `search_only` action requires remote store to be enabled on the cluster. Remote store must be enabled at cluster creation time and cannot be enabled on an existing cluster. For more information, see [Remote-backed storage]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/index/). + +## Segment replication is not enabled + +The `search_only` action requires segment replication to be enabled for the index. Segment replication must be configured at index creation time. For more information, see [Segment replication]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/segment-replication/). + +## No search replicas configured + +The `search_only` action requires at least one search replica. For more information about configuring search replicas, see [Separating index and search workloads]({{site.url}}{{site.baseurl}}/tuning-your-cluster/performance-tuning/separate-index-and-search-workloads/). diff --git a/_im-plugin/ism/index.md b/_im-plugin/ism/index.md index 90744e1a..bba60a3b 100644 --- a/_im-plugin/ism/index.md +++ b/_im-plugin/ism/index.md @@ -1,7 +1,7 @@ --- layout: default title: Index State Management -nav_order: 16 +nav_order: 40 has_children: true redirect_from: - /im-plugin/ism/ @@ -10,60 +10,41 @@ has_toc: false # Index State Management -If you analyze time-series data, you likely prioritize new data over old data. You might periodically perform certain operations on older indexes, such as reducing replica count or deleting them. +Index State Management (ISM) runs administrative operations on an index for you, triggered by the index's age, size, or document count. Use it for the periodic work that time-series data creates: rolling over an index once it reaches a size, reducing its replica count as it ages, force merging it during off-peak hours, taking a snapshot of it, and deleting it when it is no longer needed. -Index State Management (ISM) is a plugin that lets you automate these periodic, administrative operations by triggering them based on changes in the index age, index size, or number of documents. Using the ISM plugin, you can define *policies* that automatically handle index rollovers or deletions to fit your use case. +For example, a policy can move an index into a `read_only` state after 30 days, snapshot it after 60, delete it after 90, and send you a notification each time it changes state. -For example, you can define a policy that moves your index into a `read_only` state after 30 days and then deletes it after a set period of 90 days. You can also set up the policy to send you a notification message when the index is deleted. +## Policies, states, actions, and transitions -You might want to perform an index rollover after a certain amount of time or run a `force_merge` operation on an index during off-peak hours to improve search performance during peak hours. +A *policy* is a JSON document that describes how an index is managed. It is a state machine built from three parts: -To use the ISM plugin, your user role needs to be mapped to the `all_access` role that gives you full access to the cluster. To learn more, see [Users and roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/). -{: .note } +- A *state* is a status that a managed index can be in, such as `hot`, `warm`, or `delete`. An index is in exactly one state at a time. +- An *action* is an operation that ISM runs when the index enters a state, such as `rollover`, `force_merge`, or `snapshot`. Actions run in the order in which you define them. +- A *transition* is a condition that moves the index from one state to the next, such as reaching a minimum age or document count. -## Get started with ISM +A policy can define any number of states, any number of actions in each state, and a transition between any two states, including from a state to itself. For the full policy structure, see [Policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/). -To get started, choose **Index Management** in OpenSearch Dashboards. +After a policy is attached to an index, ISM creates a job that runs every 5 minutes by default. Each run performs the actions of the current state, evaluates the transition conditions, and moves the index to its next state. To change the interval, see [Settings]({{site.url}}{{site.baseurl}}/im-plugin/ism/settings/). ISM does not run jobs while the cluster state is red. -### Step 1: Set up policies +ISM runs its jobs using the Job Scheduler plugin. To view the jobs on a cluster or to investigate a policy that stops running, see [Scheduled jobs]({{site.url}}{{site.baseurl}}/tuning-your-cluster/scheduled-jobs/index/). -A policy is a set of rules that describes how an index should be managed. For information about creating a policy, see [Policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/). +## Attaching a policy to new indexes -You can use the visual editor or JSON editor to create policies. Compared to the JSON editor, the visual editor offers a more structured way of defining policies by separating the process into creating error notifications, defining ISM templates, and adding states. We recommend using the visual editor if you want to see pre-defined fields, such as which actions you can assign to a state or under what conditions a state can transition into a destination state. - -#### Visual editor - -1. Choose the **Index Policies** tab. -2. Choose **Create policy**. -3. Choose **Visual editor**. -4. In the **Policy info** section, enter a policy ID and an optional description. -5. In the **Error notification** section, set up an optional error notification that gets sent whenever a policy execution fails. For more information, see [Error notifications]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies#error-notifications). If you're using auto rollovers in your policy, we recommend setting up error notifications, which notify you of unexpectedly large indexes if rollovers fail. -6. In **ISM templates**, enter any ISM template patterns to automatically apply this policy to future indexes. For example, if you specify a template of `sample-index*`, the ISM plugin automatically applies this policy to any indexes whose names start with `sample-index`. Your pattern cannot contain any of the following characters: `:`, `"`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, and `<`. -7. In **States**, add any states you want to include in the policy. Each state has [actions]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/#actions) the plugin executes when the index enters a certain state, and [transitions]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/#transitions), which have conditions that, when met, transition the index into a destination state. The first state you create in a policy is automatically set as the initial state. Each policy must have at least one state, but actions and transitions are optional. -8. Choose **Create**. - - -#### JSON editor - -1. Choose the **Index Policies** tab. -2. Choose **Create policy**. -3. Choose **JSON editor**. -4. In the **Name policy** section, enter a policy ID. -5. In the **Define policy** section, enter your policy. -6. Choose **Create**. - -After you create a policy, your next step is to attach it to an index or indexes. -You can set up an `ism_template` in the policy so when an index that matches the ISM template pattern is created, the plugin automatically attaches the policy to the index. - -The following example demonstrates how to create a policy that automatically gets attached to all indexes whose names start with `index_name-`. +Add an `ism_template` object to a policy so that ISM attaches the policy to each new index whose name matches one of the patterns. The following policy is attached to every index created with a name beginning with `index_name-`: ```json -PUT _plugins/_ism/policies/policy_id +PUT _plugins/_ism/policies/example_policy { "policy": { "description": "Example policy.", - "default_state": "...", - "states": [...], + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [], + "transitions": [] + } + ], "ism_template": { "index_patterns": ["index_name-*"], "priority": 100 @@ -71,52 +52,31 @@ PUT _plugins/_ism/policies/policy_id } } ``` +{% include copy-curl.html %} -If you have more than one template that matches an index pattern, ISM uses the priority value to determine which template to apply. +An index pattern cannot contain any of the following characters: `:`, `"`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<`. When more than one template matches the name of a new index, ISM applies the template with the highest `priority`. -For an example ISM template policy, see [Sample policy with ISM template for auto rollover]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies#sample-policy-with-ism-template-for-auto-rollover). +For a complete example, see [Sample policy with ISM template for auto rollover]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies-examples/#sample-policy-with-ism-template-for-auto-rollover). -Older versions of the plugin include the `policy_id` in an index template, so when an index is created that matches the index template pattern, the index will have the policy attached to it: +An `ism_template` applies only to indexes created after it. To attach a policy to indexes that already exist, see [Managed indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/) or [Applying a policy]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#applying-a-policy). -```json -PUT _index_template/<template_name> -{ - "index_patterns": [ - "index_name-*" - ], - "template": { - "settings": { - "opendistro.index_state_management.policy_id": "policy_id" - } - } -} -``` +The `opendistro.index_state_management.policy_id` index setting, which attached a policy through an index template, is deprecated. Use `ism_template` instead. +{: .note} -The `opendistro.index_state_management.policy_id` setting is deprecated. You can continue to automatically manage newly created indexes with the ISM template field. -{: .note } +## In this section -### Step 2: Attach policies to indexes +| Topic | Description | +| :--- | :--- | +| [Policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/) | The structure of a policy, the operations that an action can perform, and complete policy examples. | +| [Managed indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/) | Change, remove, and retry the policy that manages an index. | +| [Restoring ISM from a snapshot]({{site.url}}{{site.baseurl}}/im-plugin/ism/restore/) | Restore the ISM configuration index so that each managed index resumes its policy. | +| [ISM API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/) | Create policies, attach and detach them, and explain the state of a managed index. | +| [ISM error prevention]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/index/) | Validate actions before they run and resolve the validation messages. | +| [Settings]({{site.url}}{{site.baseurl}}/im-plugin/ism/settings/) | Cluster settings that control the job interval, history, and validation. | -1. Choose **indexes**. -2. Choose the index or indexes that you want to attach your policy to. -3. Choose **Apply policy**. -4. From the **Policy ID** menu, choose the policy that you created. -You can see a preview of your policy. -5. If your policy includes a rollover operation, specify a rollover alias. -Make sure that the alias that you enter already exists. For more information about the rollover operation, see [rollover]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies#rollover). -6. Choose **Apply**. +## Related documentation -After you attach a policy to an index, ISM creates a job that runs every 5 minutes by default to perform policy actions, check conditions, and transition the index into different states. To change the default time interval for this job, see [Settings]({{site.url}}{{site.baseurl}}/im-plugin/ism/settings/). - -ISM does not run jobs if the cluster state is red. - -### Step 3: Manage indexes - -1. Choose **Managed indexes**. -2. To change your policy, see [Change Policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes#change-policy). -3. To attach a rollover alias to your index, select your policy and choose **Add rollover alias**. -Make sure that the alias that you enter already exists. For more information about the rollover operation, see [rollover]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies#rollover). -4. To remove a policy, choose your policy, and then choose **Remove policy**. -5. To retry a policy, choose your policy, and then choose **Retry policy**. - -For information about managing your policies, see [Managed indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/). +- [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) +- [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/) +- [Snapshots]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/index/) +- [Index management security]({{site.url}}{{site.baseurl}}/im-plugin/security/) diff --git a/_im-plugin/ism/managedindexes.md b/_im-plugin/ism/managedindexes.md index 8de7a3e9..266c613c 100644 --- a/_im-plugin/ism/managedindexes.md +++ b/_im-plugin/ism/managedindexes.md @@ -1,7 +1,7 @@ --- layout: default title: Managed indexes -nav_order: 3 +nav_order: 20 parent: Index State Management has_children: false redirect_from: @@ -10,27 +10,39 @@ redirect_from: # Managed indexes -You can change or update a policy using the managed index operations. +A managed index is an index that an Index State Management (ISM) policy is attached to. This page describes how to move a managed index from one policy to another. -This table lists the fields of managed index operations. +## Change policy + +Changing the policy of a managed index is constrained so that a change cannot leave an index in a state that the new policy does not define. + +If the new policy contains a state identical to the current one---same name, same actions, in the same order---ISM applies the new policy immediately, even in the middle of an action. Use this when an index is stuck in its current state and you need the change to take effect now. + +If the new policy does not contain an identical state, ISM applies it only after every action in the current state finishes. You can also name a state in the current policy after which the new policy takes effect. + +To change a policy, use the [Update Managed Index Policy API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#update-managed-index-policy) or the steps in [Changing the policy of an index](#changing-the-policy-of-an-index). + +## Change policy parameters + +This table lists the parameters of the Change Policy operation. Parameter | Description | Type | Required | Read Only :--- | :--- |:--- |:--- | -`name` | The name of the managed index policy. | `string` | Yes | No -`index` | The name of the managed index that this policy is managing. | `string` | Yes | No -`index_uuid` | The uuid of the index. | `string` | Yes | No -`enabled` | When `true`, the managed index is scheduled and run by the scheduler. | `boolean` | Yes | No -`enabled_time` | The time the managed index was last enabled. If the managed index process is disabled, then this is null. | `timestamp` | Yes | Yes -`last_updated_time` | The time the managed index was last updated. | `timestamp` | Yes | Yes -`schedule` | The schedule of the managed index job. | `object` | Yes | No -`policy_id` | The name of the policy used by this managed index. | `string` | Yes | No -`policy_seq_no` | The sequence number of the policy used by this managed index. | `number` | Yes | No -`policy_primary_term` | The primary term of the policy used by this managed index. | `number` | Yes | No -`policy_version` | The version of the policy used by this managed index. | `number` | Yes | Yes -`policy` | The cached JSON of the policy for the `policy_version` that's used during runs. If the policy is null, it means that this is the first execution of the job and the latest policy document is read in/saved. | `object` | No | No -`change_policy` | The information regarding what policy and state to change to. | `object` | No | No -`policy_name` | The name of the policy to update to. To update to the latest version, set this to be the same as the current `policy_name`. | `string` | No | Yes -`state` | The state of the managed index after it finishes updating. If no state is specified, it's assumed that the policy structure did not change. | `string` | No | Yes +`name` | The name of the managed index policy. | String | Yes | No +`index` | The name of the managed index that this policy is managing. | String | Yes | No +`index_uuid` | The UUID of the index. | String | Yes | No +`enabled` | When `true`, the managed index is scheduled and run by the scheduler. | Boolean | Yes | No +`enabled_time` | The time the managed index was last enabled. If the managed index process is disabled, then this is null. | Timestamp | Yes | Yes +`last_updated_time` | The time the managed index was last updated. | Timestamp | Yes | Yes +`schedule` | The schedule of the managed index job. | Object | Yes | No +`policy_id` | The name of the policy used by this managed index. | String | Yes | No +`policy_seq_no` | The sequence number of the policy used by this managed index. | Number | Yes | No +`policy_primary_term` | The primary term of the policy used by this managed index. | Number | Yes | No +`policy_version` | The version of the policy used by this managed index. | Number | Yes | Yes +`policy` | The cached JSON of the policy for the `policy_version` that's used during runs. If the policy is null, it means that this is the first execution of the job and the latest policy document is read in/saved. | Object | No | No +`change_policy` | The information regarding what policy and state to change to. | Object | No | No +`policy_name` | The name of the policy to update to. To update to the latest version, set this to be the same as the current `policy_name`. | String | No | Yes +`state` | The state of the managed index after it finishes updating. If no state is specified, it's assumed that the policy structure did not change. | String | No | Yes The following example shows a managed index policy: @@ -58,18 +70,66 @@ The following example shows a managed index policy: } ``` -## Change policy +## Managed indexes in OpenSearch Dashboards -You can change any managed index policy, but ISM has a few constraints in place to make sure that policy changes don't break indexes. +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Policy managed indexes** to list the indexes that a policy manages, along with the policy, the current state, and the status of the last action. -If an index is stuck in its current state, never proceeding, and you want to update its policy immediately, make sure that the new policy includes the same state---same name, same actions, same order---as the old policy. In this case, even if the policy is in the middle of executing an action, ISM applies the new policy. +The following image shows the **Policy managed indexes** page. -If you update the policy without including an identical state, ISM updates the policy only after all actions in the current state finish executing. Alternately, you can choose a specific state in your old policy after which you want the new policy to take effect. +![Policy managed indexes page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/policy-managed-indexes.png) -To change a policy using OpenSearch Dashboards, do the following: +To attach a policy to an index that is not managed yet, see [Applying a policy]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#applying-a-policy). + +### Viewing the state of a managed index + +The **Policy managed indexes** table shows the state each index is in and the status of its last action. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/arrow-right-icon.png" class="inline-icon" alt="expand icon"/>{:/} (expand) icon in the **Info** column of a failed index to view the reason for the failure. To narrow the table to particular indexes, enter a name in the search box. + +### Changing the policy of an index + +1. In **Index Management**, select **Policy managed indexes**. +1. Select the checkbox next to each index whose policy you want to change, and then select **Change policy**. +1. In **Choose managed indexes**, confirm the indexes. To limit the change to indexes in particular states, select those states in **State filters**. +1. In **Choose new policy**, select the policy to change to. +1. Select when the new policy takes effect: + + - **Keep indexes in their current state after the policy takes effect** starts the new policy in the state that each index is in. + - **Start from a chosen state after changing policies** starts the new policy in the state that you select. + +1. Select **Change**. + +For the constraints on when the change takes effect, see [Change policy](#change-policy). + +### Adding a rollover alias + +A policy that contains a `rollover` action needs an alias to roll over. If the index was not created with one, add it: + +1. In **Index Management**, select **Policy managed indexes**. +1. Select the checkbox next to the index. **Edit rollover alias** is available only when exactly one index is selected. +1. Select **Edit rollover alias**. +1. Enter the name of an existing alias, and then select **Edit**. + +### Removing a policy + +1. In **Index Management**, select **Policy managed indexes**. +1. Select the checkbox next to each index that you want to stop managing. +1. Select **Remove policy**. +1. Select **Remove** in the confirmation dialog. + +Removing a policy leaves the index and its data as they are. The state that the policy last applied to the index, such as `read_only`, remains in effect. + +### Retrying a policy + +When an action fails and its retries are exhausted, the managed index stops in a failed state. Correct the cause, such as a missing rollover alias or a snapshot repository that does not exist, and then retry: + +1. In **Index Management**, select **Policy managed indexes**. +1. Select the checkbox next to each failed index. **Retry policy** is available only when a selected index has failed. +1. Select **Retry policy**. +1. Select **Retry from the failed action**, or select **Retry policy from a specific state** and select the state to restart from. +1. Select **Retry**. + +## Related documentation + +- [Policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/) +- [ISM API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/) +- [ISM error prevention]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/index/) -- Under **Index Management**, choose the indexes that you want to attach the new policy to. -- To attach the new policy to indexes in specific states, choose **Choose state filters**, and then choose those states. -- Under **Choose New Policy**, choose the new policy. -- To start the new policy for indexes in the current state, choose **Keep indices in their current state after the policy takes effect**. -- To start the new policy in a specific state, choose **Start from a chosen state after changing policies**, and then choose the default start state in your new policy. diff --git a/_im-plugin/ism/policies-examples.md b/_im-plugin/ism/policies-examples.md new file mode 100644 index 00000000..bcb2e417 --- /dev/null +++ b/_im-plugin/ism/policies-examples.md @@ -0,0 +1,325 @@ +--- +layout: default +title: Policy examples +nav_order: 20 +parent: Policies +grand_parent: Index State Management +has_children: false +--- + +# Policy examples + +The following examples are complete policies in JSON format. For the components of a policy, see [Policies]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/). To create a policy in OpenSearch Dashboards, see [Creating a policy]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies/#creating-a-policy). To create one using the API, see [ISM API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/). + + +## Sample policy with ISM template for auto rollover + +The following sample template policy is for a rollover use case. + +If you want to skip rollovers for an index, set `index.plugins.index_state_management.rollover_skip` to `true` in the settings of that index. + +1. Create a policy with an `ism_template` field: + + ```json + PUT _plugins/_ism/policies/rollover_policy + { + "policy": { + "description": "Example rollover policy.", + "default_state": "rollover", + "states": [ + { + "name": "rollover", + "actions": [ + { + "rollover": { + "min_doc_count": 1 + } + } + ], + "transitions": [] + } + ], + "ism_template": { + "index_patterns": ["log*"], + "priority": 100 + } + } + } + ``` + {% include copy-curl.html %} + + You need to specify the `index_patterns` field. If you don't specify a value for `priority`, it defaults to 0. + +2. Set up a template with the `rollover_alias` as `log` : + + ```json + PUT _index_template/ism_rollover + { + "index_patterns": ["log*"], + "template": { + "settings": { + "plugins.index_state_management.rollover_alias": "log" + } + } + } + ``` + {% include copy-curl.html %} + +3. Create an index with the `log` alias: + + ```json + PUT log-000001 + { + "aliases": { + "log": { + "is_write_index": true + } + } + } + ``` + {% include copy-curl.html %} + +4. Index a document to trigger the rollover condition: + + ```json + POST log/_doc + { + "message": "dummy" + } + ``` + {% include copy-curl.html %} + +5. Verify if the policy is attached to the `log-000001` index: + + ```json + GET _plugins/_ism/explain/log-000001?pretty + ``` + {% include copy-curl.html %} + +## Example policy with ISM templates for the alias action + +The following example policy is for an alias action use case. + +In the following example, the first job will trigger the rollover action, and a new index will be created. Next, another document is added to the two indexes. The new job will then cause the second index to point to the log alias, and the older index will be removed due to the alias action. + +First, create an ISM policy: + +```json +PUT /_plugins/_ism/policies/rollover_alias_policy +{ + "policy": { + "description": "Example alias action policy.", + "default_state": "rollover", + "states": [ + { + "name": "rollover", + "actions": [ + { + "rollover": { + "min_doc_count": 1 + } + } + ], + "transitions": [{ + "state_name": "alias", + "conditions": { + "min_doc_count": "2" + } + }] + }, + { + "name": "alias", + "actions": [ + { + "alias": { + "actions": [ + { + "remove": { + "alias": "alias-log" + } + } + ] + } + } + ] + } + ], + "ism_template": { + "index_patterns": ["alias-log*"], + "priority": 100 + } + } +} +``` +{% include copy-curl.html %} + +An `ism_template` whose index patterns overlap those of an existing policy at the same priority is rejected, so this policy uses its own `alias-log*` pattern rather than the `log*` pattern of the preceding example. +{: .note} + +Next, create an index template on which to enable the policy: + +```json +PUT /_index_template/ism_rollover_alias +{ + "index_patterns": ["alias-log*"], + "template": { + "settings": { + "plugins.index_state_management.rollover_alias": "alias-log" + } + } +} +``` +{% include copy-curl.html %} + +Next, change the cluster settings to trigger jobs every minute: + +```json +PUT /_cluster/settings?pretty=true +{ + "persistent" : { + "plugins.index_state_management.job_interval" : 1 + } +} +``` +{% include copy-curl.html %} + +Next, create a new index: + +```json +PUT /alias-log-000001 +{ + "aliases": { + "alias-log": { + "is_write_index": true + } + } +} +``` +{% include copy-curl.html %} + +Finally, add a document to the index to trigger the job: + +```json +POST /alias-log-000001/_doc +{ + "message": "dummy" +} +``` +{% include copy-curl.html %} + +You can verify these steps using the Alias and Index API: + +```json +GET /_cat/indices?pretty +``` +{% include copy-curl.html %} + +```json +GET /_cat/aliases?pretty +``` +{% include copy-curl.html %} + +The `index` and `remove_index` parameters are not allowed with alias action policies. Only the `add` and `remove` alias action parameters are allowed. +{: .warning } + +When you are finished, restore the job interval to its default so that the shortened interval does not apply to every managed index in the cluster: + +```json +PUT /_cluster/settings +{ + "persistent" : { + "plugins.index_state_management.job_interval" : null + } +} +``` +{% include copy-curl.html %} + +## Example policy + +The following example policy implements a `hot`, `warm`, and `delete` workflow. You can use this policy as a template to prioritize resources to your indexes based on their levels of activity. + +In this case, an index is initially in a `hot` state. After 7 days, it changes to a `warm` state, where the number of replicas is reduced to 1 and the indexes are moved to nodes with the `warm` attribute. + +After 30 days, the policy moves this index into a `delete` state. The service sends a notification to a Chime room that the index is being deleted, and then permanently deletes it. + +```json +PUT _plugins/_ism/policies/hot_warm_delete_policy +{ + "policy": { + "description": "hot warm delete workflow", + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [ + { + "rollover": { + "min_index_age": "7d", + "min_primary_shard_size": "30gb" + } + } + ], + "transitions": [ + { + "state_name": "warm" + } + ] + }, + { + "name": "warm", + "actions": [ + { + "replica_count": { + "number_of_replicas": 1 + } + }, + { + "allocation": { + "require": { + "temp": "warm" + } + } + } + ], + "transitions": [ + { + "state_name": "delete", + "conditions": { + "min_index_age": "30d" + } + } + ] + }, + { + "name": "delete", + "actions": [ + { + "notification": { + "destination": { + "chime": { + "url": "<URL>" + } + }, + "message_template": { + "source": "The index {% raw %}{{ctx.index}}{% endraw %} is being deleted" + } + } + }, + { + "delete": {} + } + ] + } + ], + "ism_template": { + "index_patterns": ["index-*"], + "priority": 100 + } + } +} +``` +{% include copy-curl.html %} + +This diagram shows the `states`, `transitions`, and `actions` of the preceding policy as a finite-state machine. For more information about finite-state machines, see [Wikipedia](https://en.wikipedia.org/wiki/Finite-state_machine). + +![Policy State Machine]({{site.url}}{{site.baseurl}}/images/ism.png) diff --git a/_im-plugin/ism/policies-operations.md b/_im-plugin/ism/policies-operations.md new file mode 100644 index 00000000..9b1769e7 --- /dev/null +++ b/_im-plugin/ism/policies-operations.md @@ -0,0 +1,777 @@ +--- +layout: default +title: ISM supported operations +nav_order: 10 +parent: Policies +grand_parent: Index State Management +has_children: false +--- + + +# ISM supported operations + +ISM supports the following operations: + +- [Force merge](#force-merge) +- [Read only](#read-only) +- [Read write](#read-write) +- [Publish field domains](#publish-field-domains) +- [Replica count](#replica-count) +- [Shrink](#shrink) +- [Close](#close) +- [Open](#open) +- [Delete](#delete) +- [Rollover](#rollover) +- [Notification](#notification) +- [Snapshot](#snapshot) +- [Convert index to remote](#convert-index-to-remote) +- [Index priority](#index-priority) +- [Allocation](#allocation) +- [Rollup](#rollup) +- [Stop replication](#stop-replication) +- [Search only](#search-only) + +## Force merge + +Reduces the number of Lucene segments by merging the segments of individual shards. This operation attempts to set the index to a `read-only` state before starting the merging process. + +Parameter | Description | Type | Required +:--- | :--- |:--- |:--- | +`max_num_segments` | The number of segments to reduce the shard to. | Integer | Yes + +The following example merges the segments of each shard into a single segment: + +```json +{ + "force_merge": { + "max_num_segments": 1 + } +} +``` +{% include copy.html %} + +## Read only + +Sets a managed index to be read only. + +The `read_only` operation takes no parameters: + +```json +{ + "read_only": {} +} +``` +{% include copy.html %} + +Set the index setting `index.blocks.write` to `true` for a managed index. + +The `index.blocks.write` block does not prevent the index from refreshing. +{: .note} + +## Read write + +Sets a managed index to be writeable. + +The `read_write` operation takes no parameters: + +```json +{ + "read_write": {} +} +``` +{% include copy.html %} + +## Publish field domains +**Introduced 3.9** +{: .label .label-purple } + +Computes the field domains for a managed index and publishes them to the index metadata. OpenSearch uses field domains for [index-level search pruning]({{site.url}}{{site.baseurl}}/search-plugins/index-level-search-pruning/). + +A field domain contains the minimum and maximum values for a field in one index. The `date_range` field domain type applies to `date` and `date_nanos` fields. For `date` fields, ISM stores the bounds in epoch milliseconds; for `date_nanos` fields, ISM stores the bounds in epoch nanoseconds. + +Before computing field domains, ISM refreshes the index. It then computes the minimum and maximum values for each configured field and publishes them to the index's `index_field_domains` metadata. If a configured field has no values in the index, ISM does not publish a field domain for that field, and if no field domains are produced, the action completes without publishing any field domains. + +Parameter | Description | Type | Required +:--- | :--- |:--- |:--- | +`fields` | The fields for which ISM computes and publishes field domains. | Array | Yes +`fields.field` | The field name. | String | Yes +`fields.type` | The field domain type. Valid value is `date_range`. | String | Yes + +The following example publishes a `date_range` field domain for the `@timestamp` field: + +```json +{ + "publish_field_domains": { + "fields": [ + { + "field": "@timestamp", + "type": "date_range" + } + ] + } +} +``` +{% include copy.html %} + +The managed index must be write blocked before this action runs, so add a `read_only` action before `publish_field_domains`: + +```json +{ + "actions": [ + { + "read_only": {} + }, + { + "publish_field_domains": { + "fields": [ + { + "field": "@timestamp", + "type": "date_range" + } + ] + } + } + ] +} +``` +{% include copy.html %} + +Use this action only for indexes that remain write blocked after publishing. If writes resume, a new document can fall outside the published field domain, and pruning can skip an index that holds matching documents, silently dropping results from searches. +{: .important} + +If the Security plugin is enabled, the ISM execution user must have permission to publish field domains using the `indices:admin/field_domains/put` action. + +## Replica count + +Sets the number of replicas to assign to an index. + +Parameter | Description | Type | Required +:--- | :--- |:--- |:--- | +`number_of_replicas` | Defines the number of replicas to assign to an index. | Integer | Yes + +The following example assigns two replicas to the index: + +```json +{ + "replica_count": { + "number_of_replicas": 2 + } +} +``` +{% include copy.html %} + +For information about setting replicas, see [Primary and replica shards]({{site.url}}{{site.baseurl}}/intro/#primary-and-replica-shards). + +## Shrink + +Allows you to reduce the number of primary shards in your indexes. With this action, you can specify: + +- The number of primary shards that the target index should contain. +- A max shard size for the primary shards in the target index. +- Specify a percentage to shrink the number of primary shards in the target index. + +The following example shrinks the index to one primary shard, names the target index by appending `_shrunken` to the source index name, and adds the `my-alias` alias: + +```json +"shrink": { + "num_new_shards": 1, + "target_index_name_template": { + "source": "{% raw %}{{ctx.index}}{% endraw %}_shrunken" + }, + "aliases": [ + { + "my-alias": {} + } + ], + "switch_aliases": true, + "force_unsafe": false +} +``` +{% include copy.html %} + +Parameter | Description | Type | Example | Required +:--- | :--- |:--- |:--- | +`num_new_shards` | The maximum number of primary shards in the shrunken index. | Integer | `5` | Yes. It, however, cannot be used with `max_shard_size` or `percentage_of_source_shards`. +`max_shard_size` | The maximum size in bytes of a shard for the target index. | Keyword | `5gb` | Yes, however, it cannot be used with `num_new_shards` or `percentage_of_source_shards`. +`percentage_of_source_shards` | Percentage of the number of original primary shards to shrink. This parameter indicates the minimum percentage to use when shrinking the number of primary shards. Must be between 0.0 and 1.0, exclusive. | Percentage | `0.5` | Yes, however it cannot be used with `max_shard_size` or `num_new_shards` +`target_index_name_template` | The name of the shrunken index. Accepts strings and the Mustache variables `{% raw %}{{ctx.index}}{% endraw %}` and `{% raw %}{{ctx.indexUuid}}{% endraw %}`. | String or Mustache template | `{"source": "{% raw %}{{ctx.index}}_shrunken"}{% endraw %}` | No +`aliases` | Aliases to add to the new index. | Object | `myalias` | No. It must be an array of alias objects. +`switch_aliases` | If `true`, copies the aliases from the source index to the target index. If there is a name conflict with an alias from the `aliases` field, the alias in the `aliases` field is used instead of the name. | Boolean | `true` | No. The default implicit value is `false`, which means no aliases are copied by default. +`force_unsafe` | If `true`, shrinks the index even if it has no replicas. | Boolean | `false` | No + +If you want to add `aliases` to the action, the parameter must include an array of [alias objects]({{site.url}}{{site.baseurl}}/api-reference/alias/), as in the following example: + +```json +"aliases": [ + { + "my-alias": {} + }, + { + "my-second-alias": { + "is_write_index": false, + "filter": { + "multi_match": { + "query": "QUEEN", + "fields": ["speaker", "text_entry"] + } + }, + "index_routing" : "1", + "search_routing" : "1" + } + } +] +``` +{% include copy.html %} + +## Close + +Closes the managed index. + +The `close` operation takes no parameters: + +```json +{ + "close": {} +} +``` +{% include copy.html %} + +Closed indexes remain on disk, but consume no CPU or memory. You can't read from, write to, or search closed indexes. + +Closing an index is a good option if you need to retain data for longer than you need to actively search it and have sufficient disk space on your data nodes. If you need to search the data again, reopening a closed index is simpler than restoring an index from a snapshot. + +## Open + +Opens a managed index. + +The `open` operation takes no parameters: + +```json +{ + "open": {} +} +``` +{% include copy.html %} + +## Delete + +Deletes a managed index. + +The `delete` operation takes no parameters: + +```json +{ + "delete": {} +} +``` +{% include copy.html %} + +## Rollover + +Rolls an alias over to a new index when the managed index meets one of the rollover conditions. + +<p id="important-note"></p> + +> **IMPORTANT** +> +>ISM checks the conditions for operations on **every execution of the policy** based on the **set interval**, _not_ continuously. The rollover will be performed if the value **has reached** or _has exceeded_ the configured limit **when the check is performed**. For example, with `min_size` configured to a value of 100 GiB, ISM might check the index at 99 GiB and not perform the rollover. However, if the index has grown past the limit by the next check (for example, to 105 GiB), the operation is performed. +{: .important} + +If you need to skip the rollover action, you can set the index setting `index.plugins.index_state_management.rollover_skip` to `true`. For example, if you receive the error message "Missing alias or not the write index...", you can set the `index.plugins.index_state_management.rollover_skip` parameter to `true` and retry to skip the rollover action. + +The index format must match the pattern: `^.*-\d+$`. For example, `(logs-000001)`. +Set `index.plugins.index_state_management.rollover_alias` as the alias to rollover. + +The `rollover` operation has the following parameters, all of which are optional. + +Parameter | Description | Type | Example +:--- | :--- |:--- |:--- +`min_size` | The minimum size of the total primary shard storage (not counting replicas) required to roll over the index. For example, if you set `min_size` to 100 GiB and your index has 5 primary shards and 5 replica shards of 20 GiB each, the total size of all primary shards is 100 GiB, so the rollover occurs. See [**Important** note](#important-note). | String | `20gb` or `5mb` +`min_primary_shard_size` | The minimum storage size of a **single primary shard** required to roll over the index. For example, if you set `min_primary_shard_size` to 30 GiB and **one of** the primary shards in the index has a size greater than the condition, the rollover occurs. See [**Important** note](#important-note). | String | `20gb` or `5mb` +`min_doc_count` | The minimum number of documents required to roll over the index. See [**Important** note](#important-note). | Integer | `2000000` +`min_index_age` | The minimum age required to roll over the index. Index age is the time between its creation and the present. Supported units are `d` (days), `h` (hours), `m` (minutes), `s` (seconds), `ms` (milliseconds), and `micros` (microseconds). See [**Important** note](#important-note). | String | `5d` or `7h` +`copy_alias` | Controls whether to copy over all aliases from the current index to a newly created index. Default is `false`. | Boolean | `true` or `false` +`prevent_empty_rollover` | Controls whether to skip the rollover when the index contains no documents. When `true`, an empty index does not roll over. Default is `false`. | Boolean | `true` or `false` +`any_of` | A list of condition groups. Each group is an object containing one or more of `min_size`, `min_primary_shard_size`, `min_doc_count`, and `min_index_age`. Within a group, the conditions are combined with AND; the groups are combined with OR. Mutually exclusive with the conditions set directly on the `rollover` object. Specifying both, an empty list, or an empty group returns an error. | Array | `[{"min_index_age": "7d"}]` + +Conditions set directly on the `rollover` object are combined with a logical OR, so the rollover occurs as soon as one of them is met. The following rollover action rolls the index over when the index is at least 7 days old or at least 50 GiB in size: + +```json +{ + "rollover": { + "min_index_age": "7d", + "min_size": "50gb" + } +} +``` +{% include copy.html %} + +To require that several conditions be met together, use `any_of`. This parameter takes a list of condition groups. The conditions within a group are combined with AND, and the groups are combined with OR, so the rollover occurs when every condition in at least one group is met. + +The following rollover action rolls the index over when it is at least 7 days old and at least 50 GiB in size, or when it reaches 100,000,000 documents: + +```json +{ + "rollover": { + "any_of": [ + { + "min_index_age": "7d", + "min_size": "50gb" + }, + { + "min_doc_count": 100000000 + } + ] + } +} +``` +{% include copy.html %} + +In a mixed-version cluster, every node must be running OpenSearch 3.7 or later to evaluate grouped conditions. Nodes running earlier versions do not process `any_of`. +{: .note} + +## Notification + +Sends you a notification. + +Parameter | Description | Type | Required +:--- | :--- |:--- |:--- | +`destination` | The destination URL. | Slack, Amazon Chime, or webhook URL | Yes +`message_template` | The text of the message. You can add variables to your messages using [Mustache templates](https://mustache.github.io/mustache.5.html). | Object | Yes + +The destination system **must** return a response otherwise the notification operation throws an error. + +### Example 1: Chime notification + +The following notification operation sends a message to an Amazon Chime webhook: + +```json +{ + "notification": { + "destination": { + "chime": { + "url": "<url>" + } + }, + "message_template": { + "source": "the index is {% raw %}{{ctx.index}}{% endraw %}" + } + } +} +``` +{% include copy.html %} + +### Example 2: Custom webhook notification + +The following notification operation sends a message to a custom webhook: + +```json +{ + "notification": { + "destination": { + "custom_webhook": { + "url": "https://<your_webhook>" + } + }, + "message_template": { + "source": "the index is {% raw %}{{ctx.index}}{% endraw %}" + } + } +} +``` +{% include copy.html %} + +### Example 3: Slack notification + +The following notification operation sends a message to a Slack webhook: + +```json +{ + "notification": { + "destination": { + "slack": { + "url": "https://hooks.slack.com/services/xxx/xxxxxx" + } + }, + "message_template": { + "source": "the index is {% raw %}{{ctx.index}}{% endraw %}" + } + } +} +``` +{% include copy.html %} + +You can use `ctx` variables in your message to represent a number of policy parameters based on the past executions of your policy. For example, if your policy has a rollover action, you can use `{% raw %}{{ctx.action.name}}{% endraw %}` in your message to represent the name of the rollover. + +The following `ctx` variable options are available for every policy: + +### Guaranteed variables + +Parameter | Description | Type +:--- | :--- |:--- |:--- | +`index` | The name of the index. | String +`index_uuid` | The UUID of the index. | String +`policy_id` | The name of the policy. | String + +## Snapshot + +Back up your cluster's indexes and state. For more information about snapshots, see [Take and restore snapshots]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore/). + +The `snapshot` operation has the following parameters. + +Parameter | Description | Type | Required | Default +:--- | :--- |:--- |:--- | +`repository` | The repository name that you register through the native snapshot API operations. | String | Yes | - +`snapshot` | The name of the snapshot. Accepts strings and the Mustache variables `{% raw %}{{ctx.index}}{% endraw %}` and `{% raw %}{{ctx.indexUuid}}{% endraw %}`. If the Mustache variables are invalid, then the snapshot name defaults to the index's name. | String or Mustache template | Yes | - + +The following example takes a snapshot of the index in the `my_backup` repository and names the snapshot using the index UUID: + +```json +{ + "snapshot": { + "repository": "my_backup", + "snapshot": "{% raw %}{{ctx.indexUuid}}{% endraw %}" + } +} +``` +{% include copy.html %} + +## Convert index to remote + +Converts an existing index into a searchable snapshot by restoring it from a remote snapshot repository. This action reduces storage costs by moving infrequently accessed data to remote storage while keeping it searchable. Set `delete_original_index` to `true` to remove the original index once the restore request is accepted, so that only the remote snapshot-backed index remains. + +The `convert_index_to_remote` operation has the following parameters. + +Parameter | Description | Type | Required | Default +:--- | :--- |:--- |:--- | +`repository` | The repository name registered through the native snapshot API operations. Must be a remote repository (for example, S3, Azure, or GCS). | String | Yes | N/A +`snapshot` | The name of the snapshot created by the snapshot action. | String | Yes | N/A +`include_aliases` | Whether to include index aliases during the restore operation. If `true`, all aliases associated with the original index are restored with the remote index. If your application accesses the index using aliases, set this parameter to `true`. | Boolean | No | `false` +`ignore_index_settings` | A comma-separated list of index settings to ignore during the restore operation. For example, `index.refresh_interval,index.number_of_replicas`. This is useful when you want to apply different settings to the restored remote index than the ones configured in the original index. | String | No | Empty string +`number_of_replicas` | The number of replicas to configure for the restored remote index. This allows you to control replica allocation during the conversion process without requiring a separate update operation. Setting `number_of_replicas` during conversion helps prevent the cluster from entering a yellow state or creating unnecessary load during replica assignment. | Integer | No | `0` +`rename_pattern` | The naming pattern for the restored searchable snapshot index. Use `$1` as a placeholder for the original index name. For example, `remote_$1` renames `my-index` to `remote_my-index`. | String | No | `$1_remote` +`delete_original_index` | Whether to delete the original index after the restore request is accepted. | Boolean | No | `false` + +### Prerequisites + +Before using the `convert_index_to_remote` action, ensure the following: + +- A remote repository (S3, Azure, or GCS) is registered and accessible. +- A snapshot of the index exists in the specified repository, typically created using the `snapshot` action. +- The repository name matches the one used in the snapshot action. + +### Usage notes + +Note the following to ensure a smooth and predictable conversion when restoring an index as a searchable snapshot: + +- The original index is deleted after the remote snapshot restore is successfully accepted only if you set `delete_original_index` to `true`. By default, the original index remains alongside the searchable snapshot version. +- The repository name used in the `convert_index_to_remote` operation must match the repository name specified during the snapshot action. +- Each object in the `actions` array holds one action. Putting `snapshot` and `convert_index_to_remote` in the same object is accepted, but only one of them is stored, so the snapshot is never taken. List each one in its own object. +- You can reference the snapshot using Mustache variables like `{% raw %}{{ctx.index}}{% endraw %}` or `{% raw %}{{ctx.indexUuid}}{% endraw %}` for dynamic naming. +- Consider your cluster's capacity when setting `number_of_replicas`. If there aren't enough eligible nodes for replica restoration, the cluster may enter a yellow state. + +### Basic example + +The following example shows a basic conversion using the minimum required parameters. The `snapshot` action creates the snapshot that `convert_index_to_remote` then restores, so each one is a separate object in the `actions` array: + +```json +"actions": [ + { + "snapshot": { + "repository": "my_backup", + "snapshot": "{% raw %}{{ctx.index}}{% endraw %}" + } + }, + { + "convert_index_to_remote": { + "repository": "my_backup", + "snapshot": "{% raw %}{{ctx.index}}{% endraw %}" + } + } +] +``` +{% include copy.html %} + +### Advanced configuration example + +The following example demonstrates using all available configuration options. This configuration includes aliases, ignores certain index settings during restore, and configures two replicas for the searchable snapshot: + +```json +{ + "convert_index_to_remote": { + "repository": "my_backup", + "snapshot": "daily-snapshot", + "include_aliases": true, + "ignore_index_settings": "index.refresh_interval,index.number_of_replicas", + "number_of_replicas": 0, + "rename_pattern": "remote_$1" + } +} +``` +{% include copy.html %} + +### Complete policy example + +The following policy moves indexes older than 30 days to searchable snapshots with optimized settings for cost efficiency: + +```json +{ + "policy": { + "description": "Convert old indexes to searchable snapshots", + "default_state": "active", + "states": [ + { + "name": "active", + "actions": [], + "transitions": [ + { + "state_name": "archive", + "conditions": { + "min_index_age": "30d" + } + } + ] + }, + { + "name": "archive", + "actions": [ + { + "snapshot": { + "repository": "remote-repo", + "snapshot": "{% raw %}{{ctx.index}}{% endraw %}" + } + }, + { + "convert_index_to_remote": { + "repository": "remote-repo", + "snapshot": "{% raw %}{{ctx.index}}{% endraw %}", + "include_aliases": true, + "ignore_index_settings": "index.refresh_interval,index.number_of_replicas", + "number_of_replicas": 0 + } + } + ], + "transitions": [] + } + ] + } +} +``` +{% include copy.html %} + +## Index priority + +Set the priority for the index in a specific state. Unallocated shards of indexes are recovered in the order of their priority, whenever possible. The indexes with higher priority values are recovered first followed by the indexes with lower priority values. + +The `index_priority` operation has the following parameter. + +Parameter | Description | Type | Required | Default +:--- | :--- |:--- |:--- |:--- +`priority` | The priority for the index as soon as it enters a state. | Integer | Yes | 1 + +The following example sets the index priority to `50`: + +```json +"actions": [ + { + "index_priority": { + "priority": 50 + } + } +] +``` +{% include copy.html %} + +## Allocation + +Allocate the index to a node with a specific attribute set [like this]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#advanced-step-7-set-up-a-hot-warm-architecture). +For example, setting `require` to `warm` moves your data only to "warm" nodes. + +The `allocation` operation has the following parameters. At least one of `require`, `include`, or `exclude` must be specified. + +Parameter | Description | Type | Required +:--- | :--- |:--- |:--- +`require` | Allocate the index to a node with a specified attribute. | Object | No +`include` | Allocate the index to a node with any of the specified attributes. | Object | No +`exclude` | Don't allocate the index to a node with any of the specified attributes. | Object | No +`wait_for` | Wait for the policy to execute before allocating the index to a node with a specified attribute. | Boolean | No. Default is `false`. + +The following example allocates the index to nodes whose `temp` attribute is set to `warm`: + +```json +"actions": [ + { + "allocation": { + "require": { "temp": "warm" } + } + } +] +``` +{% include copy.html %} + +## Rollup + +[Index rollup]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/) lets you periodically reduce data granularity by rolling up old data into summarized indexes. Define the job in an `ism_rollup` object. For the fields it accepts, see [Create or update an index rollup job]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/#create-or-update-an-index-rollup-job). + +Rollup jobs can be continuous or non-continuous. A rollup job created using an ISM policy can only be non-continuous. +{: .note } + +The following policy rolls the `opensearch_dashboards_sample_data_ecommerce` fields up into hourly buckets in a `target` index: + +```json +PUT _plugins/_ism/policies/sample_rollup_policy +{ + "policy": { + "description": "Sample rollup" , + "default_state": "rollup", + "states": [ + { + "name": "rollup", + "actions": [ + { + "rollup": { + "ism_rollup": { + "description": "Creating rollup through ISM", + "target_index": "target", + "target_index_settings":{ + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index.codec": "best_compression" + }, + "page_size": 1000, + "dimensions": [ + { + "date_histogram": { + "fixed_interval": "60m", + "source_field": "order_date", + "target_field": "order_date", + "timezone": "America/Los_Angeles" + } + }, + { + "terms": { + "source_field": "customer_gender", + "target_field": "customer_gender" + } + }, + { + "terms": { + "source_field": "day_of_week", + "target_field": "day_of_week" + } + } + ], + "metrics": [ + { + "source_field": "taxless_total_price", + "metrics": [ + { + "sum": {} + } + ] + }, + { + "source_field": "total_quantity", + "metrics": [ + { + "avg": {} + }, + { + "max": {} + } + ] + } + ] + } + } + } + ], + "transitions": [] + } + ] + } +} +``` +{% include copy-curl.html %} + +To create a rollup job in OpenSearch Dashboards, see [Creating a rollup job]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/#creating-a-rollup-job). + +## Stop replication + +Stops replication and converts the follower index to a regular index. + +The `stop_replication` operation takes no parameters: + +```json +{ + "stop_replication": {} +} +``` +{% include copy.html %} + +When cross-cluster replication is enabled, the follower index becomes read-only, preventing all write operations. To manage replicated indexes on a follower cluster, you can perform the `stop_replication` action before performing other write operations. For example, you can define a policy that first runs `stop_replication` and then deletes the index by running a `delete` action. + +If security is enabled, in addition to [stop replication permissions]({{site.url}}{{site.baseurl}}/tuning-your-cluster/replication-plugin/permissions/#replication-permissions), you must have the `indices:internal/plugins/replication/index/stop` permission in order to use the `stop_replication` action. +{: .note} + +## Search only + +When an index enters `search_only` mode, OpenSearch removes its primary and regular replica shards while retaining search replicas for query operations. All write operations to the index are blocked. This is useful for log lifecycle management where older indexes no longer need write capability but should remain searchable. + +> This action requires the following prerequisites: +> - Remote store must be enabled on the cluster. +> - Segment replication must be enabled on the index. +> - Search replicas must be configured on the index. +> +> For more information about search-only mode and reader/writer separation, see [Separating index and search workloads]({{site.url}}{{site.baseurl}}/tuning-your-cluster/performance-tuning/separate-index-and-search-workloads/). +{: .note} + +Set an index to search-only mode using the following action: + +```json +{ + "search_only": {} +} +``` +{% include copy.html %} + +If the index is already in search-only mode, the action completes successfully without making any changes. + +You can manually enable or disable `search_only` mode outside of ISM policies by calling the [Scale API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/scale/). +{: .tip} + +The following example policy transitions an index to `search_only` mode after 7 days: + +```json +PUT _plugins/_ism/policies/hot-warm-search-only +{ + "policy": { + "description": "Move indexes to search-only mode after 7 days", + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [], + "transitions": [ + { + "state_name": "warm", + "conditions": { + "min_index_age": "7d" + } + } + ] + }, + { + "name": "warm", + "actions": [ + { + "search_only": {} + } + ], + "transitions": [] + } + ] + } +} +``` +{% include copy-curl.html %} diff --git a/_im-plugin/ism/policies.md b/_im-plugin/ism/policies.md index e6262e88..dea20b84 100644 --- a/_im-plugin/ism/policies.md +++ b/_im-plugin/ism/policies.md @@ -1,589 +1,143 @@ --- layout: default title: Policies -nav_order: 1 +nav_order: 10 parent: Index State Management -has_children: false +has_children: true --- -# Policies +# ISM policies -Policies are JSON documents that define the following: +Policies are entities (stored as JSON documents) that define the following: - The *states* that an index can be in, including the default state for new indexes. For example, you might name your states "hot," "warm," "delete," and so on. For more information, see [States](#states). - Any *actions* that you want the plugin to take when an index enters a state, such as performing a rollover. For more information, see [Actions](#actions). - The conditions that must be met for an index to move into a new state, known as *transitions*. For example, if an index is more than eight weeks old, you might want to move it to the "delete" state. For more information, see [Transitions](#transitions). -In other words, a policy defines the *states* that an index can be in, the *actions* to perform when in a state, and the conditions that must be met to *transition* between states. +Actions and transitions are associated with states. A condition (such as index size or age) triggers a transition to a new state, and entering a state triggers its actions. You have complete flexibility in the way you can design your policies. You can create any state, transition to any other state, and specify any number of actions in each state. -This table lists the relevant fields of a policy. +The following table lists the fields of a policy. Field | Description | Type | Required | Read Only :--- | :--- |:--- |:--- | -`policy_id` | The name of the policy. | `string` | Yes | Yes -`description` | A human-readable description of the policy. | `string` | Yes | No -`ism_template` | Specify an ISM template to automatically apply the policy to the newly created index. | `nested list of objects` | No | No -`ism_template.index_patterns` | Specify a pattern that matches the newly created index name. | `list of strings` | No | No -`ism_template.priority` | Specify a priority to disambiguate when multiple policies match the newly created index name. | `number` | No | No -`last_updated_time` | The time the policy was last updated. | `timestamp` | Yes | Yes -`error_notification` | The destination and message template for error notifications. The destination could be Amazon Chime, Slack, or a webhook URL. | `object` | No | No -`default_state` | The default starting state for each index that uses this policy. | `string` | Yes | No -`states` | The states that you define in the policy. | `nested list of objects` | Yes | No +`policy_id` | The name of the policy. | String | Yes | Yes +`description` | A human-readable description of the policy. | String | Yes | No +`ism_template` | An ISM template to automatically apply the policy to the newly created index. | Nested list of objects | No | No +`ism_template.index_patterns` | A pattern that matches the newly created index name. | List of strings | No | No +`ism_template.priority` | A priority used to choose which policy to apply when multiple policies match a newly created index name. | Integer | No | No +`last_updated_time` | The time the policy was last updated. | Timestamp | Yes | Yes +`error_notification` | The destination and message template for error notifications. The destination could be Amazon Chime, Slack, or a webhook URL. | Object | No | No +`default_state` | The default starting state for each index that uses this policy. | String | Yes | No +`states` | The states that you define in the policy. | Nested list of objects | Yes | No ---- - -#### Table of contents -1. TOC -{:toc} - - ---- ## States -A state is the description of the status that the managed index is currently in. A managed index can be in only one state at a time. Each state has associated actions that are executed sequentially on entering a state and transitions that are checked after all the actions have been completed. +A state defines the status of a managed index. A managed index can be in only one state at a time. A state's actions are executed sequentially on entering a state. A state's transitions are checked periodically after all the actions have been completed. -This table lists the parameters that you can define for a state. +The following table lists the parameters that you can define for a state. Field | Description | Type | Required :--- | :--- |:--- |:--- | -`name` | The name of the state. | `string` | Yes -`actions` | The actions to execute after entering a state. For more information, see [Actions](#actions). | `nested list of objects` | Yes -`transitions` | The next states and the conditions required to transition to those states. If no transitions exist, the policy assumes that it's complete and can now stop managing the index. For more information, see [Transitions](#transitions). | `nested list of objects` | Yes +`name` | The name of the state. | String | Yes +`actions` | The actions to execute after entering a state. If you omit this field, the state performs no actions. For more information, see [Actions](#actions). | Nested list of objects | No +`transitions` | The next states and the conditions required to transition to those states. If no transitions exist, the policy assumes that it's complete and can now stop managing the index. For more information, see [Transitions](#transitions). | Nested list of objects | No ---- ## Actions -Actions are the steps that the policy sequentially executes on entering a specific state. +Actions are [operations]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies-operations/) that a policy can execute upon entering a specific state. -ISM executes actions in the order in which they are defined. For example, if you define actions [A,B,C,D], ISM executes action A, and then goes into a sleep period based on the cluster setting `plugins.index_state_management.job_interval`. Once the sleep period ends, ISM continues to execute the remaining actions. However, if ISM cannot successfully execute action A, the operation ends, and actions B, C, and D do not get executed. +ISM executes actions in the order in which they are defined. If an action fails, the state actions are abandoned, and remaining actions are not executed. -Optionally, you can define an action's timeout period, which, if exceeded, forcibly fails the action. For example, if timeout is set to `1d`, and ISM has not completed the action within one day, even after retries, the action fails. +For example, if you define actions `[A,B,C,D]`, ISM does the following: +1. Executes action `A`. +2. Sleeps for a period based on the cluster setting `plugins.index_state_management.job_interval`. +3. Executes action `B`. -This table lists the parameters that you can define for an action. +And so on. + +If ISM cannot successfully execute action `A`, actions `B`, `C`, and `D` do not get executed. + +Optionally, you can define an action's timeout period. When the timeout expires, ISM fails the action. The timeout covers the whole action, not a single attempt: the clock starts when ISM begins the action and keeps running through every step, retry, and retry delay, including the time between job runs while the action waits for its conditions to be met. + +ISM checks the clock only when the managed index job runs, which is every 5 minutes by default. For example, a [rollover]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies-operations/#rollover) operation with `min_index_age` set to `1d` evaluates `min_index_age` on each job run until the index is 1 day old. A `timeout` of `1h` therefore causes the action to fail before the index can meet the condition. + +When the timeout expires, ISM marks the action as failed and stops managing the index until you call the Retry failed index API, which restarts the action and its clock. A timeout does not stop work that ISM already started or undo changes that the action already made. + +Because ISM runs one step per job run, make the timeout longer than the total time that the action needs, plus one job interval for each of its steps. If you omit `timeout`, the action never times out and continues to retry according to its `retry` configuration. + +The following table lists the parameters that you can define for an action. Parameter | Description | Type | Required | Default :--- | :--- |:--- |:--- | -`timeout` | The timeout period for the action. Accepts time units for minutes, hours, and days. | `time unit` | No | - -`retry` | The retry configuration for the action. | `object` | No | Specific to action +`timeout` | The timeout period for the action. Accepts time units for minutes, hours, and days. | Time unit | No | - +`retry` | The retry configuration for the action. | Object | No | Specific to action -The `retry` operation has the following parameters: +The `retry` operation has the following parameters. Parameter | Description | Type | Required | Default :--- | :--- |:--- |:--- | -`count` | The number of retry counts. | `number` | Yes | - -`backoff` | The backoff policy type to use when retrying. Valid values are Exponential, Constant, and Linear. | `string` | No | Exponential -`delay` | The time to wait between retries. Accepts time units for minutes, hours, and days. | `time unit` | No | 1 minute +`count` | The number of retry counts. | Integer | Yes | - +`backoff` | The backoff policy type to use when retrying. Valid values are Exponential, Constant, and Linear. | String | No | Exponential +`delay` | The time to wait between retries. Accepts time units for minutes, hours, and days. | Time unit | No | 1 minute -The following example action has a timeout period of one hour. The policy retries this action three times with an exponential backoff policy, with a delay of 10 minutes between each retry: +### Example action -```json -"actions": { - "timeout": "1h", - "retry": { - "count": 3, - "backoff": "exponential", - "delay": "10m" - } -} -``` - -For a list of available unit types, see [Supported units]({{site.url}}{{site.baseurl}}/opensearch/units/). - -## ISM supported operations - -ISM supports the following operations: - -- [force_merge](#force_merge) -- [read_only](#read_only) -- [read_write](#read_write) -- [replica_count](#replica_count) -- [shrink](#shrink) -- [close](#close) -- [open](#open) -- [delete](#delete) -- [rollover](#rollover) -- [notification](#notification) -- [snapshot](#snapshot) -- [index_priority](#index_priority) -- [allocation](#allocation) -- [rollup](#rollup) - -### force_merge - -Reduces the number of Lucene segments by merging the segments of individual shards. This operation attempts to set the index to a `read-only` state before starting the merging process. - -Parameter | Description | Type | Required -:--- | :--- |:--- |:--- | -`max_num_segments` | The number of segments to reduce the shard to. | `number` | Yes -`wait_for_completion` | Boolean | When set to `false`, the request returns immediately instead of after the operation is finished. To monitor the operation status, use the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) with the task ID returned by the request. Default is `true`. -`task_execution_timeout` | Time | The explicit task execution timeout. Only useful when `wait_for_completion` is set to `false`. Default is `1h`. | No - -```json -{ - "force_merge": { - "max_num_segments": 1 - } -} -``` - -### read_only - -Sets a managed index to be read only. - -```json -{ - "read_only": {} -} -``` - -Set the index setting `index.blocks.write` to `true` for a managed index. ***Note:** this block does not prevent the index from refreshing. - -### read_write - -Sets a managed index to be writeable. - -```json -{ - "read_write": {} -} -``` - -### replica_count - -Sets the number of replicas to assign to an index. - -Parameter | Description | Type | Required -:--- | :--- |:--- |:--- | -`number_of_replicas` | Defines the number of replicas to assign to an index. | `number` | Yes - -```json -{ - "replica_count": { - "number_of_replicas": 2 - } -} -``` - -For information about setting replicas, see [Primary and replica shards]({{site.url}}{{site.baseurl}}/intro/#primary-and-replica-shards). - -### shrink - -Allows you to reduce the number of primary shards in your indexes. With this action, you can specify: - -- The number of primary shards that the target index should contain. -- A max shard size for the primary shards in the target index. -- Specify a percentage to shrink the number of primary shards in the target index. - -```json -"shrink": { - "num_new_shards": 1, - "target_index_name_template": { - "source": "{{ctx.index}}_shrunken" - }, - "aliases": [ - { - "my-alias": {} - } - ], - "switch_aliases": true, - "force_unsafe": false -} -``` - -Parameter | Description | Type | Example | Required -:--- | :--- |:--- |:--- | -`num_new_shards` | The maximum number of primary shards in the shrunken index. | Integer | `5` | Yes. It, however, cannot be used with `max_shard_size` or `percentage_of_source_shards`. -`max_shard_size` | The maximum size in bytes of a shard for the target index. | Keyword | `5gb` | Yes, however, it cannot be used with `num_new_shards` or `percentage_of_source_shards`. -`percentage_of_source_shards` | Percentage of the number of original primary shards to shrink. This parameter indicates the minimum percentage to use when shrinking the number of primary shards. Must be between 0.0 and 1.0, exclusive. | Percentage | `0.5` | Yes, however it cannot be used with `max_shard_size` or `num_new_shards` -`target_index_name_template` | The name of the shrunken index. Accepts strings and the Mustache variables `{{ctx.index}}` and `{{ctx.indexUuid}}`. | String or Mustache template | `{"source": "{{ctx.index}}_shrunken"}` | No -`aliases` | Aliases to add to the new index. | Object | `myalias` | No. It must be an array of alias objects. -`switch_aliases` | If `true`, copies the aliases from the source index to the target index. If there is a name conflict with an alias from the `aliases` field, the alias in the `aliases` field is used instead of the name. | Boolean | `true` | No. The default implicit value is `false`, which means no aliases are copied by default. -`force_unsafe` | If `true`, shrinks the index even if it has no replicas. | Boolean | `false` | No - -If you want to add `aliases` to the action, the parameter must include an array of [alias objects]({{site.url}}{{site.baseurl}}/api-reference/alias/). For example, - -```json -"aliases": [ - { - "my-alias": {} - }, - { - "my-second-alias": { - "is_write_index": false, - "filter": { - "multi_match": { - "query": "QUEEN", - "fields": ["speaker", "text_entry"] - } - }, - "index_routing" : "1", - "search_routing" : "1" - } - }, -] -``` - -### close - -Closes the managed index. - -```json -{ - "close": {} -} -``` - -Closed indexes remain on disk, but consume no CPU or memory. You can't read from, write to, or search closed indexes. - -Closing an index is a good option if you need to retain data for longer than you need to actively search it and have sufficient disk space on your data nodes. If you need to search the data again, reopening a closed index is simpler than restoring an index from a snapshot. - -### open - -Opens a managed index. - -```json -{ - "open": {} -} -``` - -### delete - -Deletes a managed index. - -```json -{ - "delete": {} -} -``` - -### rollover - -Rolls an alias over to a new index when the managed index meets one of the rollover conditions. - -ISM checks the conditions for operations on **every execution of the policy** based on the **set interval**, _not_ continuously. The rollover will be performed if the value **has reached** or _has exceeded_ the configured limit **when the check is performed**. For example with `min_size` configured to a value of 100GiB, ISM might check the index at 99 GiB and not perform the rollover. However, if the index has grown past the limit (e.g., 105GiB) by the next check, the operation is performed. - -If you need to skip the rollover action, you can set the index setting `index.plugins.index_state_management.rollover_skip` to `true`. For example, if you receive the error message "Missing alias or not the write index...", you can set the `index.plugins.index_state_management.rollover_skip` parameter to `true` and retry to skip rollover action. - -The index format must match the pattern: `^.*-\d+$`. For example, `(logs-000001)`. -Set `index.plugins.index_state_management.rollover_alias` as the alias to rollover. - -Parameter | Description | Type | Example | Required -:--- | :--- |:--- |:--- | -`min_size` | The minimum size of the total primary shard storage (not counting replicas) required to roll over the index. For example, if you set `min_size` to 100 GiB and your index has 5 primary shards and 5 replica shards of 20 GiB each, the total size of all primary shards is 100 GiB, so the rollover occurs. See **Important** note above. | `string` | `20gb` or `5mb` | No -`min_primary_shard_size` | The minimum storage size of a **single primary shard** required to roll over the index. For example, if you set `min_primary_shard_size` to 30 GiB and **one of** the primary shards in the index has a size greater than the condition, the rollover occurs. See **Important** note above. | `string` | `20gb` or `5mb` | No -`min_doc_count` | The minimum number of documents required to roll over the index. See **Important** note above. | `number` | `2000000` | No -`min_index_age` | The minimum age required to roll over the index. Index age is the time between its creation and the present. Supported units are `d` (days), `h` (hours), `m` (minutes), `s` (seconds), `ms` (milliseconds), and `micros` (microseconds). See **Important** note above. | `string` | `5d` or `7h` | No -`copy_alias` | Controls whether to copy over all aliases from the current index to a newly created index. Defaults to `false`. | `boolean` | `true` or `false` | No - -```json -{ - "rollover": { - "min_size": "50gb" - } -} -``` - -```json -{ - "rollover": { - "min_primary_shard_size": "30gb" - } -} -``` - -```json -{ - "rollover": { - "min_doc_count": 100000000 - } -} -``` - -```json -{ - "rollover": { - "min_index_age": "30d" - } -} -``` - -### notification - -Sends you a notification. - -Parameter | Description | Type | Required -:--- | :--- |:--- |:--- | -`destination` | The destination URL. | `Slack, Amazon Chime, or webhook URL` | Yes -`message_template` | The text of the message. You can add variables to your messages using [Mustache templates](https://mustache.github.io/mustache.5.html). | `object` | Yes - -The destination system **must** return a response otherwise the notification operation throws an error. - -#### Example 1: Chime notification - -```json -{ - "notification": { - "destination": { - "chime": { - "url": "<url>" - } - }, - "message_template": { - "source": "the index is {% raw %}{{ctx.index}}{% endraw %}" - } - } -} -``` - -#### Example 2: Custom webhook notification - -```json -{ - "notification": { - "destination": { - "custom_webhook": { - "url": "https://<your_webhook>" - } - }, - "message_template": { - "source": "the index is {% raw %}{{ctx.index}}{% endraw %}" - } - } -} -``` - -#### Example 3: Slack notification - -```json -{ - "notification": { - "destination": { - "slack": { - "url": "https://hooks.slack.com/services/xxx/xxxxxx" - } - }, - "message_template": { - "source": "the index is {% raw %}{{ctx.index}}{% endraw %}" - } - } -} -``` - -You can use `ctx` variables in your message to represent a number of policy parameters based on the past executions of your policy. For example, if your policy has a rollover action, you can use `{% raw %}{{ctx.action.name}}{% endraw %}` in your message to represent the name of the rollover. - -The following `ctx` variable options are available for every policy: - -#### Guaranteed variables - -Parameter | Description | Type -:--- | :--- |:--- |:--- | -`index` | The name of the index. | `string` -`index_uuid` | The uuid of the index. | `string` -`policy_id` | The name of the policy. | `string` - -### snapshot - -Back up your cluster’s indexes and state. For more information about snapshots, see [Take and restore snapshots]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore). - -The `snapshot` operation has the following parameters: - -Parameter | Description | Type | Required | Default -:--- | :--- |:--- |:--- | -`repository` | The repository name that you register through the native snapshot API operations. | `string` | Yes | - -`snapshot` | The name of the snapshot. Accepts strings and the Mustache variables `{{ctx.index}}` and `{{ctx.indexUuid}}`. If the Mustache variables are invalid, then the snapshot name defaults to the index's name. | `string` or Mustache template | Yes | - - -```json -{ - "snapshot": { - "repository": "my_backup", - "snapshot": "{{ctx.indexUuid}}" - } -} -``` - -### index_priority - -Set the priority for the index in a specific state. Unallocated shards of indexes are recovered in the order of their priority, whenever possible. The indexes with higher priority values are recovered first followed by the indexes with lower priority values. - -The `index_priority` operation has the following parameter: - -Parameter | Description | Type | Required | Default -:--- | :--- |:--- |:--- |:--- -`priority` | The priority for the index as soon as it enters a state. | `number` | Yes | 1 +The following example `read_only` action has a timeout period of one hour. The policy retries this action three times with an exponential backoff policy, with a delay of 10 minutes between each retry: ```json "actions": [ { - "index_priority": { - "priority": 50 - } + "timeout": "1h", + "retry": { + "count": 3, + "backoff": "exponential", + "delay": "10m" + }, + "read_only": {} } ] ``` -### allocation - -Allocate the index to a node with a specific attribute set [like this]({{site.url}}{{site.baseurl}}/opensearch/cluster/#advanced-step-7-set-up-a-hot-warm-architecture). -For example, setting `require` to `warm` moves your data only to "warm" nodes. - -The `allocation` operation has the following parameters: - -Parameter | Description | Type | Required -:--- | :--- |:--- |:--- -`require` | Allocate the index to a node with a specified attribute. | `string` | Yes -`include` | Allocate the index to a node with any of the specified attributes. | `string` | Yes -`exclude` | Don’t allocate the index to a node with any of the specified attributes. | `string` | Yes -`wait_for` | Wait for the policy to execute before allocating the index to a node with a specified attribute. | `string` | Yes - -```json -"actions": [ - { - "allocation": { - "require": { "temp": "warm" } - } - } -] -``` - -### rollup - -[Index rollup]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/index/) lets you periodically reduce data granularity by rolling up old data into summarized indexes. - -Rollup jobs can be continuous or non-continuous. A rollup job created using an ISM policy can only be non-continuous. -{: .note } - -#### Path and HTTP methods - -````bash -PUT _plugins/_rollup/jobs/<rollup_id> -GET _plugins/_rollup/jobs/<rollup_id> -DELETE _plugins/_rollup/jobs/<rollup_id> -POST _plugins/_rollup/jobs/<rollup_id>/_start -POST _plugins/_rollup/jobs/<rollup_id>/_stop -GET _plugins/_rollup/jobs/<rollup_id>/_explain -```` - -#### Sample ISM rollup policy - -````json -{ - "policy": { - "description": "Sample rollup" , - "default_state": "rollup", - "states": [ - { - "name": "rollup", - "actions": [ - { - "rollup": { - "ism_rollup": { - "description": "Creating rollup through ISM", - "target_index": "target", - "page_size": 1000, - "dimensions": [ - { - "date_histogram": { - "fixed_interval": "60m", - "source_field": "order_date", - "target_field": "order_date", - "timezone": "America/Los_Angeles" - } - }, - { - "terms": { - "source_field": "customer_gender", - "target_field": "customer_gender" - } - }, - { - "terms": { - "source_field": "day_of_week", - "target_field": "day_of_week" - } - } - ], - "metrics": [ - { - "source_field": "taxless_total_price", - "metrics": [ - { - "sum": {} - } - ] - }, - { - "source_field": "total_quantity", - "metrics": [ - { - "avg": {} - }, - { - "max": {} - } - ] - } - ] - } - } - } - ], - "transitions": [] - } - ] - } -} -```` - -#### Request fields - -Request fields are required when creating an ISM policy. You can reference the [Index rollups API]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/#create-or-update-an-index-rollup-job) page for request field options. - -#### Adding a rollup policy in Dashboards - -To add a rollup policy in Dashboards, follow the steps below. - -- Select the menu button on the top-left of the Dashboards user interface. -- In the Dashboards menu, select `Index Management`. -- On the next screen select `Rollup jobs`. -- Select the `Create rollup` button. -- Follow the steps in the `Create rollup job` wizard. -- Add a name for the policy in the `Name` box. -- You can reference the [Index rollups API]({{site.url}}{{site.baseurl}}/im-plugin/index-rollups/rollup-api/#create-or-update-an-index-rollup-job) page to configure the rollup policy. -- Finally, select the `Create` button on the bottom-right of the Dashboards user interface. - ---- +For a list of available unit types, see [Supported units]({{site.url}}{{site.baseurl}}/api-reference/units/). ## Transitions -Transitions define the conditions that need to be met for a state to change. After all actions in the current state are completed, the policy starts checking the conditions for transitions. +Transitions define the conditions that trigger a state to change. After all actions in the current state are completed, the policy starts checking the conditions for transitions. -ISM evaluates transitions in the order in which they are defined. For example, if you define transitions: [A,B,C,D], ISM iterates through this list of transitions until it finds a transition that evaluates to `true`, it then stops and sets the next state to the one defined in that transition. On its next execution, ISM dismisses the rest of the transitions and starts in that new state. +ISM evaluates transitions in the order in which they are defined. It uses the first transition that evaluates to `true`. -If you don't specify any conditions in a transition and leave it empty, then it's assumed to be the equivalent of always true. This means that the policy transitions the index to this state the moment it checks. +If you don't specify any conditions in a transition, then it always evaluates to `true`. If the policy checks such a transition, it immediately transitions the index to the state defined in the transition. + +For example, assume you've defined the transitions: `[A,B,C,D]`, and that transitions `A`, `B`, and `C` currently evaluate to `false` and that `D` has no conditions. ISM iterates through the list in order and sets the next state to the one defined in transition `D`. On its next execution, ISM starts in the state defined by `D`. This table lists the parameters you can define for transitions. Parameter | Description | Type | Required :--- | :--- |:--- |:--- | -`state_name` | The name of the state to transition to if the conditions are met. | `string` | Yes -`conditions` | List the conditions for the transition. | `list` | Yes +`state_name` | The name of the state to transition to if the conditions are met. | String | Yes +`conditions` | List the conditions for the transition. | List | Yes -The `conditions` object has the following parameters: +The `conditions` object has the following parameters. Parameter | Description | Type | Required :--- | :--- |:--- |:--- | -`min_index_age` | The minimum age of the index required to transition. | `string` | No -`min_rollover_age` | The minimum age required after a rollover has occurred to transition to the next state. | `string` | No -`min_doc_count` | The minimum document count of the index required to transition. | `number` | No -`min_size` | The minimum size of the total primary shard storage (not counting replicas) required to transition. For example, if you set `min_size` to 100 GiB and your index has 5 primary shards and 5 replica shards of 20 GiB each, the total size of all primary shards is 100 GiB, so your index is transitioned to the next state. | `string` | No -`cron` | The `cron` job that triggers the transition if no other transition happens first. | `object` | No -`cron.cron.expression` | The `cron` expression that triggers the transition. | `string` | Yes -`cron.cron.timezone` | The timezone that triggers the transition. | `string` | Yes +`min_index_age` | The minimum age of the index required to transition. | String | No +`min_rollover_age` | The minimum age required after a rollover has occurred to transition to the next state. | String | No +`min_state_age` | The minimum amount of time the index must spend in the current state before transitioning. | String | No +`min_doc_count` | The minimum document count of the index required to transition. | Integer | No +`min_size` | The minimum size of the total primary shard storage (not counting replicas) required to transition. For example, if you set `min_size` to 100 GiB and your index has 5 primary shards and 5 replica shards of 20 GiB each, the total size of all primary shards is 100 GiB, so your index is transitioned to the next state. Specify the value as a byte size containing a unit, for example, `50gb`. | String | No +`no_alias` | Controls transition based on alias presence. If `true`, transition occurs only when the index has **no aliases**. If `false`, transition occurs only when at least **one alias exists**. | Boolean | No +`cron` | The `cron` job that triggers the transition if no other transition happens first. | Object | No +`cron.cron.expression` | The `cron` expression that triggers the transition. For the syntax, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). | String | Yes +`cron.cron.timezone` | The time zone for the triggering `cron` expression triggers the transition. | String | Yes + +All time-based values (`min_index_age`, `min_rollover_age`, `min_state_age`) use [standard OpenSearch time units]({{site.url}}{{site.baseurl}}/api-reference/units/#time-units). The `min_size` value uses [byte size units]({{site.url}}{{site.baseurl}}/api-reference/units/#byte-size-units) and must be a whole number that includes the unit. Values without a unit, such as `"50"`, and fractional values, such as `"1.5gb"`, are rejected. +{: .note} + The following example transitions the index to a `cold` state after a period of 30 days: @@ -598,7 +152,20 @@ The following example transitions the index to a `cold` state after a period of ] ``` -ISM checks the conditions on every execution of the policy based on the set interval. +The following example transitions the index to a `warm` state when its primary shards reach a total size of 50 GB: + +```json +"transitions": [ + { + "state_name": "warm", + "conditions": { + "min_size": "50gb" + } + } +] +``` + +ISM checks the conditions on every execution of the policy based on the `job_interval` [setting]({{site.url}}{{site.baseurl}}/im-plugin/ism/settings/). This example uses the `cron` condition to transition indexes every Saturday at 5:00 PT: @@ -618,42 +185,57 @@ This example uses the `cron` condition to transition indexes every Saturday at 5 ] ``` -Note that this condition does not execute at exactly 5:00 PM; the job still executes based off the `job_interval` setting. Due to this variance in start time and the amount of time that it can take for actions to complete prior to checking transition conditions, we recommend against overly narrow cron expressions. For example, don't use `15 17 * * SAT` (5:15 PM on Saturday). +Note that this condition does not execute at exactly 5:00 PM; the job still executes as defined by the `job_interval` setting. Due to this variance in start time and the amount of time that it can take for actions to complete prior to checking transition conditions, we recommend against overly narrow cron expressions. For example, don't use `15 17 * * SAT` (5:15 PM on Saturday). -A window of an hour, which this example uses, is generally sufficient, but you might increase it to 2--3 hours to avoid missing the window and having to wait a week for the transition to occur. Alternately, you could use a broader expression such as `* * * * SAT,SUN` to have the transition occur at any time during the weekend. +A window of an hour, which this example uses, is generally sufficient, but you might increase it to 2 or 3 hours to avoid missing the window and having to wait a week for the transition to occur. Alternately, you could use a broader expression such as `* * * * SAT,SUN` to have the transition occur at any time during the weekend. -For information on writing cron expressions, see [Cron expression reference]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/cron/). +For information about writing cron expressions, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). ---- ## Error notifications -The `error_notification` operation sends you a notification if your managed index fails. -It notifies a single destination or [notification channel]({{site.url}}{{site.baseurl}}/notifications-plugin/index) with a custom message. - -Set up error notifications at the policy level: +An `error_notification` sends a notification if your managed index fails. Set it at the policy level, alongside `default_state` and `states`: ```json +PUT _plugins/_ism/policies/hot_delete_workflow { "policy": { - "description": "hot warm delete workflow", + "description": "hot delete workflow", "default_state": "hot", - "schema_version": 1, - "error_notification": { }, - "states": [ ] + "error_notification": { + "channel": { + "id": "<channel_id>" + }, + "message_template": { + "source": "The index {% raw %}{{ctx.index}}{% endraw %} failed during policy execution." + } + }, + "states": [ + { + "name": "hot", + "actions": [], + "transitions": [] + } + ] } } ``` +{% include copy-curl.html %} + +An `error_notification` requires a `message_template`, and it must name either a `destination` or a `channel`, so an empty object is rejected with `400`. +{: .note} + +An error notification sends to a single destination or [notification channel]({{site.url}}{{site.baseurl}}/notifications-plugin/index/) with a custom message. Parameter | Description | Type | Required :--- | :--- |:--- |:--- | -`destination` | The destination URL. | `Slack, Amazon Chime, or webhook URL` | Yes if `channel` isn't specified -`channel` | A notification channel's ID | `string` | Yes if `destination` isn't specified -`message_template` | The text of the message. You can add variables to your messages using [Mustache templates](https://mustache.github.io/mustache.5.html). | `object` | Yes +`destination` | The destination URL. | Slack, Amazon Chime, or webhook URL | Yes if `channel` isn't specified +`channel` | A notification channel's ID | String | Yes if `destination` isn't specified +`message_template` | The text of the message. You can add variables to your messages using [Mustache templates](https://mustache.github.io/mustache.5.html). | Object | Yes The destination system **must** return a response otherwise the `error_notification` operation throws an error. -#### Example 1: Chime notification +### Example 1: Chime notification ```json { @@ -670,7 +252,7 @@ The destination system **must** return a response otherwise the `error_notificat } ``` -#### Example 2: Custom webhook notification +### Example 2: Custom webhook notification ```json { @@ -687,7 +269,7 @@ The destination system **must** return a response otherwise the `error_notificat } ``` -#### Example 3: Slack notification +### Example 3: Slack notification ```json { @@ -704,7 +286,7 @@ The destination system **must** return a response otherwise the `error_notificat } ``` -#### Example 4: Using a notification channel +### Example 4: Using a notification channel ```json { @@ -719,294 +301,87 @@ The destination system **must** return a response otherwise the `error_notificat } ``` -You can use the same options for `ctx` variables as the [notification](#notification) operation. +You can use the same options for `ctx` variables as the [Notification]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies-operations/#notification) operation. -## Sample policy with ISM template for auto rollover +## Policies in OpenSearch Dashboards -The following sample template policy is for a rollover use case. +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **State management policies** to list the policies in your cluster. -If you want to skip rollovers for an index, set `index.plugins.index_state_management.rollover_skip` to `true` in the settings of that index. +Policies are created in either a visual editor or a JSON editor. The visual editor presents the parts of a policy as separate panels---error notification, ISM templates, and states---with the available actions and transition conditions in lists, so use it to compose a new policy. Use the JSON editor to paste a policy that you already have. -1. Create a policy with an `ism_template` field: +The following image shows the **State management policies** page. - ```json - PUT _plugins/_ism/policies/rollover_policy - { - "policy": { - "description": "Example rollover policy.", - "default_state": "rollover", - "states": [ - { - "name": "rollover", - "actions": [ - { - "rollover": { - "min_doc_count": 1 - } - } - ], - "transitions": [] - } - ], - "ism_template": { - "index_patterns": ["log*"], - "priority": 100 - } - } - } - ``` +![State management policies page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/state-management-policies.png) - You need to specify the `index_patterns` field. If you don't specify a value for `priority`, it defaults to 0. +### Viewing a policy -2. Set up a template with the `rollover_alias` as `log` : +1. In **Index Management**, select **State management policies**. +1. Select the policy in the **Policy** column. - ```json - PUT _index_template/ism_rollover - { - "index_patterns": ["log*"], - "template": { - "settings": { - "plugins.index_state_management.rollover_alias": "log" - } - } - } - ``` +The page shows the **Policy settings**, **ISM templates**, and **States** panels. To view the actions and transitions of a state, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/arrow-right-icon.png" class="inline-icon" alt="expand icon"/>{:/} (expand) icon next to the state name. -3. Create an index with the `log` alias: +### Creating a policy - ```json - PUT log-000001 - { - "aliases": { - "log": { - "is_write_index": true - } - } - } - ``` +1. In **Index Management**, select **State management policies**, and then select **Create policy**. +1. Select **Visual editor** or **JSON editor**, and then select **Continue**. +1. In **Policy info**, enter a unique **Policy ID** that describes what the policy does, such as `hot_cold_workflow`, and, optionally, a description. +1. Optionally, in **Error notification**, select a **Channel ID** to be notified when a policy run fails. For more information, see [Error notifications](#error-notifications). If the policy rolls over indexes automatically, configure this notification: it tells you about unexpectedly large indexes when a rollover fails. +1. Optionally, in **ISM templates**, add the index patterns that attach this policy to new indexes. See [Adding an ISM template](#adding-an-ism-template). +1. In **States**, select **Add state** to add each state of the policy. See [Adding a state](#adding-a-state). A policy must contain at least one state. +1. In **Initial state**, select the state that a newly managed index starts in. +1. Select **Create**. -4. Index a document to trigger the rollover condition: +In the JSON editor, enter the policy ID in **Name policy**, enter the policy in **Define policy**, and then select **Create**. - ```json - POST log/_doc - { - "message": "dummy" - } - ``` +### Adding a state -5. Verify if the policy is attached to the `log-000001` index: +In **States** on the **Create policy** page, select **Add state**, and then do the following: - ```json - GET _plugins/_ism/explain/log-000001?pretty - ``` +1. Enter a **State name** that describes the stage of the index lifecycle, such as `hot`, `warm`, or `delete`. +1. To place the state relative to the states that you have already defined, select **Add before** or **Add after** in **Order**, and then select the state to position it against. Skip this step for the first state. +1. For each operation that the state performs, do the following: -## Example policy with ISM templates for the alias action + 1. Select **Add action**. + 1. Select an **Action type**. For the available types and their parameters, see [ISM supported operations]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies-operations/). + 1. Enter the parameters of the action. For example, the snapshot action requires a repository and a snapshot name. + 1. Optionally, enter a **Timeout** period after which the action fails, such as `5h`, and a **Retry count**, **Retry backoff** policy, and **Retry delay**, such as `1d`. + 1. Select **Add action**. -The following example policy is for an alias action use case. +1. For each transition out of the state, do the following: -In the following example, the first job will trigger the rollover action, and a new index will be created. Next, another document is added to the two indexes. The new job will then cause the second index to point to the log alias, and the older index will be removed due to the alias action. + 1. Select **Add transition**. + 1. In **Destination state**, select the state to transition to. To transition a state to itself, enter its name, because it is not in the list. + 1. Select a **Condition** and enter its parameters. For example, the minimum document count condition requires the number of documents that triggers the transition. A transition without a condition always evaluates to `true`. + 1. Select **Add transition**. -First, create an ISM policy: +1. Select **Save state**. -```json -PUT /_plugins/_ism/policies/rollover_policy?pretty -{ - "policy": { - "description": "Example rollover policy.", - "default_state": "rollover", - "states": [ - { - "name": "rollover", - "actions": [ - { - "rollover": { - "min_doc_count": 1 - } - } - ], - "transitions": [{ - "state_name": "alias", - "conditions": { - "min_doc_count": "2" - } - }] - }, - { - "name": "alias", - "actions": [ - { - "alias": { - "actions": [ - { - "remove": { - "alias": "log" - } - } - ] - } - } - ] - } - ], - "ism_template": { - "index_patterns": ["log*"], - "priority": 100 - } - } -} -``` +### Adding an ISM template -Next, create an index template on which to enable the policy: +An ISM template attaches the policy to each new index whose name matches one of its index patterns: -```json -PUT /_index_template/ism_rollover? -{ - "index_patterns": ["log*"], - "template": { - "settings": { - "plugins.index_state_management.rollover_alias": "log" - } - } -} -``` -{% include copy-curl.html %} +1. In **ISM templates** on the **Create policy** page, select **Add template**. +1. In **Index patterns**, enter an index pattern. For example, the pattern `sample-index-*` attaches the policy to every new index whose name begins with `sample-index-`. An index pattern cannot contain any of the following characters: `:`, `"`, `+`, `/`, `\`, `|`, `?`, `#`, `>`, or `<`. +1. In **Priority**, enter a priority for the pattern. When more than one template matches the name of a new index, ISM applies the template with the highest priority. +1. Optionally, repeat the preceding steps to add more templates. -Next, change the cluster settings to trigger jobs every minute: +An ISM template applies only to indexes created after it. For more information, see [Attaching a policy to new indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/#attaching-a-policy-to-new-indexes). -```json -PUT /_cluster/settings?pretty=true -{ - "persistent" : { - "plugins.index_state_management.job_interval" : 1 - } -} -``` -{% include copy-curl.html %} +### Editing a policy -Next, create a new index: +1. In **Index Management**, select **State management policies**. +1. Select the policy in the **Policy** column, and then select **Edit**. +1. Select **Visual editor** or **JSON editor**. +1. Change any part of the policy except the policy ID, and then select **Update**. -```json -PUT /log-000001 -{ - "aliases": { - "log": { - "is_write_index": true - } - } -} -``` -{% include copy-curl.html %} +The changes take effect the next time the policy runs. Indexes that the policy already manages continue with the cached version of the policy until then. To move a managed index to a different policy, see [Managed indexes]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/). -Finally, add a document to the index to trigger the job: +### Deleting a policy -```json -POST /log-000001/_doc -{ - "message": "dummy" -} -``` -{% include copy-curl.html %} +1. In **Index Management**, select **State management policies**. +1. Select the checkbox next to each policy that you want to delete, and then select **Delete**. +1. Select **Delete** in the confirmation dialog. -You can verify these steps using the Alias and Index API: +A deleted policy stops managing its indexes immediately and cannot be recovered. +{: .warning} -```json -GET /_cat/indices?pretty -``` -{% include copy-curl.html %} - -```json -GET /_cat/aliases?pretty -``` -{% include copy-curl.html %} - -Note: The `index` and `remove_index` parameters are not allowed with alias action policies. Only the `add` and `remove` alias action parameters are allowed. -{: .warning } - -## Example policy - -The following example policy implements a `hot`, `warm`, and `delete` workflow. You can use this policy as a template to prioritize resources to your indexes based on their levels of activity. - -In this case, an index is initially in a `hot` state. After 7 days, it changes to a `warm` state, where the number of replicas is reduced to 1 and the indexes are moved to nodes with the `warm` attribute. - -After 30 days, the policy moves this index into a `delete` state. The service sends a notification to a Chime room that the index is being deleted, and then permanently deletes it. - -```json -{ - "policy": { - "description": "hot warm delete workflow", - "default_state": "hot", - "schema_version": 1, - "states": [ - { - "name": "hot", - "actions": [ - { - "rollover": { - "min_index_age": "7d", - "min_primary_shard_size": "30gb" - } - } - ], - "transitions": [ - { - "state_name": "warm" - } - ] - }, - { - "name": "warm", - "actions": [ - { - "replica_count": { - "number_of_replicas": 1 - } - }, - { - "allocation": { - "require": { - "temp": "warm" - } - } - } - ], - "transitions": [ - { - "state_name": "delete", - "conditions": { - "min_index_age": "30d" - } - } - ] - }, - { - "name": "delete", - "actions": [ - { - "notification": { - "destination": { - "chime": { - "url": "<URL>" - } - }, - "message_template": { - "source": "The index {% raw %}{{ctx.index}}{% endraw %} is being deleted" - } - } - }, - { - "delete": {} - } - ] - } - ], - "ism_template": { - "index_patterns": ["log*"], - "priority": 100 - } - } -} -``` - -This diagram shows the `states`, `transitions`, and `actions` of the above policy as a finite-state machine. For more information about finite-state machines, see [Wikipedia](https://en.wikipedia.org/wiki/Finite-state_machine). - -![Policy State Machine]({{site.baseurl}}/images/ism.png) diff --git a/_im-plugin/ism/restore.md b/_im-plugin/ism/restore.md new file mode 100644 index 00000000..9a69f6d0 --- /dev/null +++ b/_im-plugin/ism/restore.md @@ -0,0 +1,46 @@ +--- +layout: default +title: Restoring ISM from a snapshot +parent: Index State Management +nav_order: 25 +--- + +# Restoring ISM from a snapshot +**Introduced 3.10** +{: .label .label-purple } + +Index State Management (ISM) stores policies and the policy progress of each [managed index]({{site.url}}{{site.baseurl}}/im-plugin/ism/managedindexes/) in the `.opendistro-ism-config` system index. If you restore `.opendistro-ism-config` from a snapshot, such as when migrating to another cluster, each managed index resumes its policy from the state recorded in the snapshot. For managed indexes to resume their policies, you must restore them before you restore `.opendistro-ism-config`. + +## Restoration order + +ISM can match an index to its saved progress only if the index already exists when `.opendistro-ism-config` is restored. ISM matches saved progress to an index using the index name and creation date. If an index was deleted and then recreated under the same name, it has a new creation date. ISM doesn't match the recreated index to its saved progress, so the index starts its policy from the beginning. + +Using the [Restore Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/restore-snapshot/), restore indexes in the following order: + +1. Restore the managed indexes and wait for the restore operation to finish: + + ```json + POST /_snapshot/my-repository/snapshot-1/_restore?wait_for_completion=true + { + "indices": "my-index-*", + "include_global_state": false + } + ``` + {% include copy-curl.html %} + +1. Restore `.opendistro-ism-config` in a separate request: + + ```json + POST /_snapshot/my-repository/snapshot-1/_restore + { + "indices": ".opendistro-ism-config", + "include_global_state": false + } + ``` + {% include copy-curl.html %} + +If you restore `.opendistro-ism-config` first or in the same request as the managed indexes, ISM can't match the managed indexes to their saved progress. Indexes that were attached to a policy by an ISM template restart the policy from the beginning. ISM stops managing indexes that were attached using the [Add Policy API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/#add-policy). + +## Permissions + +If the Security plugin protects system indexes in your cluster, restoring `.opendistro-ism-config` requires permission to restore system indexes. A user mapped to a role in `plugins.security.restapi.roles_enabled` can restore a system index if the index is listed in the `plugins.security.system_indices.restore.indices` setting. `.opendistro-ism-config` is listed by default. You can also restore system indexes as a super admin or using system index permissions. For more information, see [Who can restore system indexes]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#who-can-restore-system-indexes). diff --git a/_im-plugin/ism/settings.md b/_im-plugin/ism/settings.md index 8725c3b1..369d6bd8 100644 --- a/_im-plugin/ism/settings.md +++ b/_im-plugin/ism/settings.md @@ -2,7 +2,7 @@ layout: default title: Settings parent: Index State Management -nav_order: 4 +nav_order: 50 --- # ISM settings @@ -13,17 +13,26 @@ Index State Management (ISM) stores its configuration in the `.opendistro-ism-co All settings are available using the OpenSearch `_cluster/settings` operation. None require a restart, and all can be marked `persistent` or `transient`. To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +Because ISM settings are cluster settings, persistent ISM settings are part of the global cluster state and are included in a snapshot taken with `include_global_state` set to `true`. Transient settings are not included. ISM policies are stored in the `.opendistro-ism-config` index, not in the cluster state, so a snapshot includes them only if it includes that index. For more information, see [Global cluster state]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#global-cluster-state). + +These settings apply only to ISM jobs. The Job Scheduler plugin, which runs ISM jobs, has separate settings that apply to the scheduled jobs of all plugins. For more information, see [Scheduled job settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/scheduled-jobs/index/#scheduled-job-settings). + Setting | Default | Description :--- | :--- | :--- `plugins.index_state_management.enabled` | True | Specifies whether ISM is enabled or not. -`plugins.index_state_management.job_interval` | 5 minutes | The interval at which the managed index jobs are run. -`plugins.index_state_management.jitter` | 0.6 | A randomized delay that is added to a job's base run time to prevent a surge of activity from all indexes at the same time. A value of 0.6 means a delay of 0-60% of a job interval is added to the base interval. For example, if you have a base interval time of 30 minutes, a value of 0.6 means an amount anywhere between 0 to 18 minutes gets added to your job interval. Maximum is 1, which means an additional interval time of 100%. This maximum cannot exceed `plugins.jobscheduler.jitter_limit`, which also has a default of 0.6. For example, if `plugins.index_state_management.jitter` is set to 0.8, ISM uses `plugins.jobscheduler.jitter_limit` of 0.6 instead. -`plugins.index_state_management.coordinator.sweep_period` | 10 minutes | How often the routine background sweep is run. -`plugins.index_state_management.coordinator.backoff_millis` | 50 milliseconds | The backoff time between retries for failures in the `ManagedIndexCoordinator` (such as when we update managed indexes). +`plugins.index_state_management.job_interval` | 5 | The interval (in minutes) at which the managed index jobs are run. +`plugins.index_state_management.jitter` | 0.6 | A randomized delay that is added to a job's base run time to prevent a surge of activity from all indexes at the same time. A value of 0.6 means a delay of 0--60% of a job interval is added to the base interval. For example, if you have a base interval time of 30 minutes, a value of 0.6 means an amount anywhere between 0 to 18 minutes gets added to your job interval. Maximum is 1, which means an additional interval time of 100%. This maximum cannot exceed `plugins.jobscheduler.jitter_limit`, which also has a default of 0.6. For example, if `plugins.index_state_management.jitter` is set to 0.8, ISM uses `plugins.jobscheduler.jitter_limit` of 0.6 instead. +`plugins.index_state_management.coordinator.sweep_period` | 10m | How often the routine background sweep is run. +`plugins.index_state_management.coordinator.backoff_millis` | 50ms | The backoff time between retries for failures in the `ManagedIndexCoordinator` (such as when we update managed indexes). `plugins.index_state_management.coordinator.backoff_count` | 2 | The count of retries for failures in the `ManagedIndexCoordinator`. `plugins.index_state_management.history.enabled` | True | Specifies whether audit history is enabled or not. The logs from ISM are automatically indexed to a logs document. -`plugins.index_state_management.history.max_docs` | 2,500,000 | The maximum number of documents before rolling over the audit history index. -`plugins.index_state_management.history.max_age` | 24 hours | The maximum age before rolling over the audit history index. -`plugins.index_state_management.history.rollover_check_period` | 8 hours | The time between rollover checks for the audit history index. -`plugins.index_state_management.history.rollover_retention_period` | 30 days | How long audit history indexes are kept. -`plugins.index_state_management.allow_list` | All actions | List of actions that you can use. +`plugins.index_state_management.history.max_docs` | 2500000 | The maximum number of documents before rolling over the audit history index. +`plugins.index_state_management.history.max_age` | 24h | The maximum age before rolling over the audit history index. +`plugins.index_state_management.history.rollover_check_period` | 8h | The time between rollover checks for the audit history index. +`plugins.index_state_management.history.rollover_retention_period` | 30d | How long audit history indexes are kept. +`plugins.index_state_management.allow_list` | `alias`, `allocation`, `close`, `convert_index_to_remote`, `delete`, `force_merge`, `index_priority`, `notification`, `open`, `read_only`, `read_write`, `replica_count`, `rollover`, `rollup`, `search_only`, `shrink`, `snapshot`, `stop_replication`, `transform` | The actions that a policy can use. Removing an action from this list makes every policy that uses it fail. +`plugins.index_state_management.action_validation.enabled` | False | Specifies whether ISM validates an action before running it. For more information, see [ISM error prevention]({{site.url}}{{site.baseurl}}/im-plugin/ism/error-prevention/index/). +`plugins.index_state_management.coordinator.sweep_skip_period` | 5m | How long the coordinator waits before sweeping a managed index again after a failure. +`plugins.index_state_management.history.number_of_shards` | 1 | The number of primary shards in the audit history index. +`plugins.index_state_management.history.number_of_replicas` | 1 | The number of replicas of the audit history index. +`plugins.index_state_management.snapshot.deny_list` | Empty list | The snapshot repositories that the `snapshot` action cannot write to. diff --git a/_im-plugin/notifications-settings.md b/_im-plugin/notifications-settings.md index 57d31f00..fdfb6e87 100644 --- a/_im-plugin/notifications-settings.md +++ b/_im-plugin/notifications-settings.md @@ -1,24 +1,28 @@ --- layout: default -title: Notification settings -nav_order: 100 +title: Long-running operation notifications +nav_order: 70 +redirect_from: + - /im-plugin/notifications/ + - /dashboards/im-dashboards/notifications/ + - /dashboards/admin-ui-index/notifications/ --- -# Notification settings +# Long-running operation notifications -Introduced 2.8 +**Introduced 2.8** {: .label .label-purple } -You can use notification settings to configure notifications about long-running index operations. Set up automatic [notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) when long-running index operations are complete by [using Notifications in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/im-dashboards/notifications/) or through the API. +Reindex, resize, force merge, and open operations can run for minutes or hours. When you send one of these requests with `wait_for_completion` set to `false`, it returns a task ID immediately instead of blocking. Configure a notification against that task ID, or against the operation type, to be told when the work finishes or fails rather than polling for it. -Configuring notification settings is useful for long-running index operations, such as `open`, `reindex`, `resize`, and `force merge`. When you send a request for those operations and set the `wait_for_completion` parameter to `false`, the operation returns immediately and the response contains a task ID. You can use that task ID to configure notifications for this operation. +Notifications are delivered through the channels configured in the [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) application, which supports Amazon Chime, Amazon Simple Notification Service (Amazon SNS), Amazon Simple Email Service (Amazon SES), email through SMTP, Slack, and custom webhooks. ## Configuring notification settings -You can configure long-running operation notifications through the API by using the `task_id` and `action_name` parameters: +An `lron_config` object takes either a `task_id` or an `action_name`, and the choice determines how long the setting lives: -- **One-time setting**: If you pass `task_id` in the `lron_config` object, the task runs one time and the setting is automatically deleted when the task ends. If you pass both `task_id` and `action_name`, `action_name` is ignored but may be useful to you for searching and debugging notification settings. -- **Global, persistent setting**: If you pass `action_name` and not `task_id` in the `lron_config` object, the task is global and persistent and applies to all operations of this action type. +- Provide `task_id` for a one-time setting. It is deleted automatically when the task ends. If you provide both `task_id` and `action_name`, `action_name` is ignored, though it can help you search for and debug your notification settings. +- Provide `action_name` without `task_id` for a global, persistent setting that applies to every operation of that type. The following table lists the parameters for long-running index operation notifications. @@ -32,52 +36,99 @@ The following table lists the parameters for long-running index operation notifi | `lron_condition.failure` | Boolean | Set this parameter to `true` to be notified when the operation fails or times out. Optional. Default is `true`. | | `channels` | Object | Supported communication channels include Amazon Chime, Amazon Simple Notification Service (Amazon SNS), Amazon Simple Email Service (Amazon SES), email through SMTP, Slack, and custom webhooks. If either `lron_condition.success` or `lron_condition.failure` is `true`, `channels` must contain at least one channel. Learn how to configure notification channels in [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/). | -## Create notification settings +### Create notification settings -The following example request sets up notifications on a failure of a reindex task: +The following example request sets up notifications for every reindex operation that fails: ```json POST /_plugins/_im/lron { "lron_config": { - "task_id":"dQlcQ0hQS2mwF-AQ7icCMw:12354", - "action_name":"indices:data/write/reindex", - "lron_condition": { - "success": false, - "failure": true - }, - "channels":[ - {"id":"channel1"}, - {"id":"channel2"} - ] - } -} -``` -{% include copy-curl.html %} - -The preceding request results in the following response: - -```json -{ - "_id": "LRON:dQlcQ0hQS2mwF-AQ7icCMw:12354", - "lron_config": { + "action_name": "indices:data/write/reindex", "lron_condition": { "success": false, "failure": true }, - "task_id": "dQlcQ0hQS2mwF-AQ7icCMw:12354", - "action_name": "indices:data/write/reindex", "channels": [ { - "id": "channel1" - }, - { - "id": "channel2" + "id": "my_chime" } ] } } ``` +{% include copy-curl.html %} + +The response contains the ID of the new notification setting: + +```json +{ + "_id": "LRON:indices:data/write/reindex", + "lron_config": { + "lron_condition": { + "success": false, + "failure": true + }, + "action_name": "indices:data/write/reindex", + "channels": [ + { + "id": "my_chime" + } + ] + } +} +``` + +To be notified about a single operation rather than all operations of a type, provide its task ID. Send the operation with `wait_for_completion` set to `false` so that it returns a task ID instead of blocking. + +The following request indexes a document, which creates the source index that the reindex operation reads from: + +```json +POST /my-source-index/_doc?refresh=true +{ + "message": "test document" +} +``` +{% include copy-curl.html %} + +The following request reindexes that index and returns a task ID: + +```json +POST /_reindex?wait_for_completion=false +{ + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-dest-index" + } +} +``` +{% include copy-curl.html %} + +Then provide the returned task ID in `task_id`: + +```json +POST /_plugins/_im/lron +{ + "lron_config": { + "task_id": "<task_id>", + "lron_condition": { + "success": false, + "failure": true + }, + "channels": [ + { + "id": "my_chime" + } + ] + } +} +``` +{% include copy-curl.html %} + +The task ID must belong to a node in the cluster. A task ID from another cluster, or one you invent, is rejected with `400`. +{: .note} ### Notification setting ID @@ -95,12 +146,19 @@ The following examples retrieve the current configured notification settings. Use the following request to retrieve a notification setting with the specified [notification setting ID](#notification-setting-id): ```json - GET /_plugins/_im/lron/<lronID> + GET /_plugins/_im/lron/{lronID} ``` {% include copy-curl.html %} For example, the following request retrieves the notification setting for the `reindex` operation: +```json +GET /_plugins/_im/lron/LRON:indices:data%2Fwrite%2Freindex +``` +{% include copy-curl.html %} + +The response contains the setting: + ```json { "lron_configs": [ @@ -123,7 +181,6 @@ For example, the following request retrieves the notification setting for the `r "total_number": 1 } ``` -{% include copy-curl.html %} Use the following request to retrieve all notification settings: @@ -173,19 +230,19 @@ The response contains all configured notification settings with their IDs: The following example modifies an existing notification setting with the specified [notification setting ID](#notification-setting-id): ```json -PUT /_plugins/_im/lron/<lronID> +PUT /_plugins/_im/lron/LRON:indices:data%2Fwrite%2Freindex { "lron_config": { - "task_id":"dQlcQ0hQS2mwF-AQ7icCMw:12354", - "action_name":"indices:data/write/reindex", - "lron_condition": { - "success": false, - "failure": true - }, - "channels":[ - {"id":"channel1"}, - {"id":"channel2"} - ] + "action_name": "indices:data/write/reindex", + "lron_condition": { + "success": true, + "failure": true + }, + "channels": [ + { + "id": "my_chime" + } + ] } } ``` @@ -195,20 +252,16 @@ The response contains the updated setting: ```json { - "_id": "LRON:dQlcQ0hQS2mwF-AQ7icCMw:12354", + "_id": "LRON:indices:data/write/reindex", "lron_config": { "lron_condition": { - "success": false, + "success": true, "failure": true }, - "task_id": "dQlcQ0hQS2mwF-AQ7icCMw:12354", "action_name": "indices:data/write/reindex", "channels": [ { - "id": "channel1" - }, - { - "id": "channel2" + "id": "my_chime" } ] } @@ -220,7 +273,7 @@ The response contains the updated setting: The following example removes a notifications setting with the specified [notification setting ID](#notification-setting-id): ```json -DELETE /_plugins/_im/lron/<lronID> +DELETE /_plugins/_im/lron/{lronID} ``` {% include copy-curl.html %} @@ -231,7 +284,51 @@ DELETE _plugins/_im/lron/LRON:indices:data%2Fwrite%2Freindex ``` {% include copy-curl.html %} -## Next steps +## Notifications in OpenSearch Dashboards -- Learn more about the [ISM API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/). -- Learn more about the [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) application. +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. Select **Notification settings** to set the defaults for the operations that support notifications, as shown in the following image. + +![Notification settings page]({{site.url}}{{site.baseurl}}/images/admin-ui-index/notification-settings.png) + +### Creating a notification channel + +A notification setting needs at least one channel to deliver to: + +1. In **Index Management**, select **Notification settings**, and then select **Manage channels**. The **Channels** page opens in a separate window. +1. Select **Create channel**. +1. Enter a name for the channel and, optionally, a description. +1. In **Configurations**, select a **Channel type**. The settings that follow depend on the type: an email channel asks for a sender type, a sender, and recipients, while a Slack channel asks for a webhook URL. +1. Enter the settings for the channel type. +1. Optionally, select **Send test message** to confirm that the channel works. +1. Select **Create**. + +### Setting defaults for all operations + +Default settings apply to every reindex, shrink, split, clone, force merge, and open operation in the cluster: + +1. In **Index Management**, select **Notification settings**. +1. In **Defaults for index operations**, select **Has failed**, **Has completed**, or both for each of **reindex**, **shrink, split, clone**, **force merge**, and **open**. +1. For each operation that you selected a notification for, select one or more channels from **Notification channels**. +1. Select **Save**. + +Viewing or changing default notification settings requires permission to read them. + +### Sending additional notifications + +Reindex, split, shrink, and force merge operations can carry their own notification settings in addition to the defaults: + +1. In **Index Management**, select **Indexes**. +1. Select the index that the operation applies to. +1. Select **Actions**, and then select the operation, such as **Reindex**. +1. Expand **Advanced settings**. The **Notifications** section lists the defaults currently in effect. +1. Select **Send additional notifications**. +1. Select **Has failed / timed out**, **Has completed**, or both. +1. Select a channel from **Notification channels**. +1. Select the button for the operation, such as **Reindex**. + +## Related documentation + +- [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) +- [Index maintenance]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/) +- [Reindexing data]({{site.url}}{{site.baseurl}}/im-plugin/reindex-data/) +- [ISM API]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/) diff --git a/_im-plugin/pull-based-ingestion/index.md b/_im-plugin/pull-based-ingestion/index.md new file mode 100644 index 00000000..b22d7715 --- /dev/null +++ b/_im-plugin/pull-based-ingestion/index.md @@ -0,0 +1,246 @@ +--- +layout: default +title: Pull-based ingestion +nav_order: 33 +has_children: true +has_toc: false +redirect_from: + - /im-plugin/pull-based-ingestion/ + - /api-reference/document-apis/pull-based-ingestion/ +--- + +# Pull-based ingestion +**Introduced 3.0** +{: .label .label-purple } + +Pull-based ingestion enables OpenSearch to ingest data from streaming sources such as Apache Kafka or Amazon Kinesis or from files in object storage. Unlike traditional ingestion methods where clients actively push data to OpenSearch through REST APIs, pull-based ingestion allows OpenSearch to control the data flow by retrieving data directly from the source. This approach provides native backpressure handling, helping prevent server overload during traffic spikes. Pull-based ingestion guarantees at-least-once ingestion semantics and uses external versioning to ensure data consistency. + +## Supported sources + +OpenSearch supports the following pull-based ingestion sources. Each source requires its own plugin. + +| Source | Plugin | `type` value | +| :--- | :--- | :--- | +| [Apache Kafka]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/kafka/) | `ingestion-kafka` | `kafka` | +| [Amazon Kinesis]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/kinesis/) | `ingestion-kinesis` | `kinesis` | +| [Object store]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/object-store/) | `ingestion-object-store` | `object_store` | + +To pause, resume, or check the state of ingestion, use the [pull-based ingestion management APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pull-based-ingestion-management/). + +## Prerequisites + +Before using pull-based ingestion, ensure that the following prerequisites are met: + +* Install the ingestion plugin for your source using the command `bin/opensearch-plugin install <plugin-name>`. For more information, see [Additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/index/). +* Configure pull-based ingestion during [index creation](#creating-an-index-for-pull-based-ingestion). You cannot convert an existing push-based index to a pull-based one. + +## Creating an index for pull-based ingestion + +To ingest data from a source, first create an index containing pull-based ingestion settings in `ingestion_source`. For an example request for each source, see [Supported sources](#supported-sources). + +### Ingestion source settings + +The `ingestion_source` settings control how OpenSearch pulls data from the source. A _poll_ is an operation in which OpenSearch actively requests a batch of data from the source. The following table lists all settings that `ingestion_source` supports. + +Dynamic settings can be updated using the [Update Settings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/) without restarting the ingestion process. Static settings cannot be changed after index creation. For more information about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +{: .note} + +| Setting | Dynamic | Description | +| :--- | :--- | :--- | +| `type` | No | The source type. Required. Valid values are `kafka`, `kinesis`, or `object_store`. | +| `pointer.init.reset` | No | Determines the stream location from which to start reading. Optional. Valid values are `earliest`, `latest`, `reset_by_offset`, `reset_by_timestamp`, or `none`. See [Stream position](#stream-position). | +| `pointer.init.reset.value` | No | Required only for `reset_by_offset` or `reset_by_timestamp`. Specifies the offset value or timestamp in milliseconds. See [Stream position](#stream-position). | +| `error_strategy` | Yes | How to handle failed messages. Optional. Valid values are `DROP` (failed messages are skipped and ingestion continues) and `BLOCK` (when a message fails, ingestion stops). Default is `DROP`. | +| `poll.max_batch_size` | Yes | The maximum number of records to retrieve in each poll operation. Optional. | +| `poll.timeout` | Yes | The maximum time to wait for data in each poll operation. Optional. | +| `num_processor_threads` | No | The number of threads for processing ingested data. Optional. Default is 1. | +| `internal_queue_size` | No | The size of the internal blocking queue for advanced tuning. Valid values are from 1 to 100,000, inclusive. Optional. Default is 100. | +| `all_active` | No | Whether to enable the all-active ingestion mode. Cannot be enabled for indexes that use segment replication mode. Default is `false`. See [Ingestion modes](#ingestion-modes). | +| `pointer_based_lag_update_interval` | No | The interval at which pointer-based lag is calculated. Accepts time units. Default is `10s`. Setting this value to `0` disables pointer-based lag calculation. | +| `warmup.timeout` | Yes | The maximum amount of time to wait for the shard to catch up with the source during the warmup phase after node restart or shard relocation. Shards will not serve queries until warmup completes or times out. Accepts time units. Optional. Default is `-1` (disabled). | +| `warmup.lag_threshold` | Yes | The acceptable pointer-based lag threshold for warmup completion. Warmup completes when the lag is at or below this value. A value of `0` means that the shard is synchronized with the source. Optional. Default is `100`. | +| `mapper_type` | No | Defines the mapper for the input message format. Valid values are `default` and `raw_payload`. See [Message format](#message-format). | +| `param` | Yes | Source-specific configuration parameters. Required. For the parameters of each source, see [Kafka source parameters]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/kafka/#source-parameters), [Kinesis source parameters]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/kinesis/#source-parameters), or [Object store source parameters]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/object-store/#source-parameters). | + + +### Other settings + +Pull-based ingestion supports the following OpenSearch settings. + +| Setting | Dynamic | Description | +| :--- | :--- | :--- | +| `index.periodic_flush_interval` | Yes | The interval at which OpenSearch triggers a flush operation. Default for pull-based ingestion indexes is `10m`. See [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#periodic-flush-interval). | + +### Ingestion modes + +Pull-based ingestion supports the following modes. + +#### Segment replication mode + +In segment replication mode, the primary shards ingest events from a source and index the documents. The pull-based index is configured to use [segment replication]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/segment-replication/index/) to copy over the segment files from primary to replica shards, as shown in the following image. + +![Pull-based ingestion segment replication mode]({{site.url}}{{site.baseurl}}/images/pull-based-ingestion/pull-based-segrep-mode.png){: width="50%" } + +We recommend using this mode with [remote-backed storage]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/index/). +{: .tip} + +#### All-active mode + +Enabling all-active mode allows both primary and replica shards to independently ingest and index events from the source, as shown in the following image. + +![Pull-based ingestion all active mode]({{site.url}}{{site.baseurl}}/images/pull-based-ingestion/pull-based-all-active-mode.png){: width="50%" } + +There is no replication or coordination between the shards, although replica shards may fetch segment files from the primary shard during bootstrapping if a local copy is unavailable. This mode is not supported with segment replication. + +### Stream position + +When creating an index, you can specify where OpenSearch should start reading from the stream by configuring the `pointer.init.reset` and `pointer.init.reset.value` settings in the `ingestion_source` parameter. OpenSearch will resume reading from the last committed position for existing indexes. + +The following table provides the valid `pointer.init.reset` values and their corresponding `pointer.init.reset.value` values. + +| `pointer.init.reset` | Starting ingestion point | `pointer.init.reset.value` | +| :--- | :--- | :--- | +| `earliest` | The beginning of the stream | None | +| `latest` | The current end of the stream | None | +| `reset_by_offset` | A specific offset in the stream | A positive integer offset. Required. | +| `reset_by_timestamp` | A specific timestamp | A Unix timestamp in milliseconds. Required. <br> For Kafka streams, defaults to Kafka's `auto.offset.reset` policy if no messages are found for the given timestamp. | +| `none` | The last committed position for existing indexes | None | + +The object store source supports only some of these values. For more information, see [Creating an index]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/object-store/#creating-an-index). + +### Stream partitioning + +When using partitioned streams (such as Kafka topics or Kinesis shards), note the following relationships between stream partitions and OpenSearch shards: + +- OpenSearch shards map one-to-one to stream partitions. +- The number of index shards must be greater than or equal to the number of stream partitions. +- Extra shards beyond the number of partitions remain empty. +- Documents must be sent to the same partition for successful updates. + +The object store source divides objects among shards differently. For more information, see [Dividing objects among shards]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/object-store/#dividing-objects-among-shards). + +When using pull-based ingestion, traditional REST API--based ingestion is disabled for the index. +{: .note} + +### Updating the error policy + +You can use the [Update Settings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/) to dynamically update the error policy by setting `index.ingestion_source.error_strategy` to either `DROP` or `BLOCK`. + +The following example demonstrates how to update the error policy: + +<!-- spec_insert_start +component: example_code +rest: PUT /my-index/_settings +body: | +{ + "index.ingestion_source.error_strategy": "DROP" +} +--> +{% capture step1_rest %} +PUT /my-index/_settings +{ + "index.ingestion_source.error_strategy": "DROP" +} +{% endcapture %} + +{% capture step1_python %} + + +response = client.indices.put_settings( + index = "my-index", + body = { + "index.ingestion_source.error_strategy": "DROP" + } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} +<!-- spec_insert_end --> + +## Message format + +To be correctly processed by OpenSearch, messages in the streaming source must have the following format: + +```json +{"_id":"1", "_version":"1", "_source":{"name": "alice", "age": 30}, "_op_type": "index"} +{"_id":"2", "_version":"2", "_source":{"name": "alice", "age": 30}, "_op_type": "delete"} +``` + +Each data unit in the streaming source (Kafka message or Kinesis record) must include the following fields that specify how to create or modify an OpenSearch document. This is the default format supported by pull-based ingestion. + +| Field | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `_id` | String | No | A unique identifier for a document. If not provided, OpenSearch auto-generates an ID. Required for document updates or deletions. | +| `_version` | Long | No | A document version number, which must be maintained externally. If provided, OpenSearch drops messages with versions earlier than the current document version. If not provided, no version checking occurs. | +| `_op_type` | String | No | The operation to perform. Valid values are:<br>- `index`: Creates a new document or updates an existing one.<br>- `create`: Creates a new document in append mode. Note that this will not update existing documents. <br>- `delete`: Soft deletes a document. | +| `_source` | Object | Yes | The message payload containing the document data. | + +We recommend using the document `_id` field to prevent duplicates, since pull-based ingestion provides at-least-once ingestion semantics. If your producer cannot guarantee event ordering, also set `_version` field to ensure data consistency. +{: .tip} + +Alternatively, pull-based ingestion supports indexing raw payloads in append-only mode without transformations. To enable this behavior, set `index.ingestion_source.mapper_type` to `raw_payload`. Note that in this mode, the index mappings must conform to the message structure because dynamic mapping is not supported. When using `raw_payload`, you must provide raw JSON objects exactly as they appear in the incoming data stream, as shown in the following example: + +```json +{"name": "alice", "age": 30} +{"name": "bob", "age": 30} +``` + +## Pull-based ingestion metrics + +Pull-based ingestion provides metrics that can be used to monitor the ingestion process. The `polling_ingest_stats` metric is available at the shard level. + +The following table lists the available `polling_ingest_stats` metrics. + +| Metric | Description | +| :--- | :--- | +| `message_processor_stats.total_processed_count` | The total number of messages processed by the message processor. | +| `message_processor_stats.total_invalid_message_count` | The number of invalid messages encountered. | +| `message_processor_stats.total_version_conflicts_count` | The number of version conflicts due to which older version messages will be dropped. | +| `message_processor_stats.total_failed_count` | The total number of failed messages, which error out during processing. | +| `message_processor_stats.total_failures_dropped_count` | The total number of failed messages, which are dropped after exhausting retries. Note that messages are only dropped when the DROP error policy is used. | +| `message_processor_stats.total_processor_thread_interrupt_count` | Indicates the number of thread interruptions on the processor thread. | +| `consumer_stats.total_polled_count` | The total number of messages polled from the stream consumer. | +| `consumer_stats.total_consumer_error_count` | The total number of fatal consumer read errors. | +| `consumer_stats.total_poller_message_failure_count` | The total number of failed messages on the poller. | +| `consumer_stats.total_poller_message_dropped_count` | The total number of failed messages on the poller that were dropped. | +| `consumer_stats.lag_in_millis` | Lag in milliseconds, computed as the time elapsed since the last processed message timestamp. | +| `consumer_stats.pointer_based_lag` | The Apache Kafka offset-based lag, calculated as the difference between the latest available offset and the current message offset. This metric applies only when Apache Kafka is used as the streaming source. For the [object store source]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/object-store/), it is the number of bytes the shard still has to read. | + +To retrieve shard-level pull-based ingestion metrics, use the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/): + +<!-- spec_insert_start +component: example_code +rest: GET /_nodes/stats/indices?level=shards&pretty +--> +{% capture step1_rest %} +GET /_nodes/stats/indices?level=shards&pretty +{% endcapture %} + +{% capture step1_python %} + + +response = client.nodes.info( + metric = "indices", + node_id = "stats", + params = { "level": "shards", "pretty": "true" } +) + +{% endcapture %} + +{% include code-block.html + rest=step1_rest + python=step1_python %} +<!-- spec_insert_end --> + + +## Limitations + +The following limitations apply when using pull-based ingestion: + +* [Ingest pipelines]({{site.url}}{{site.baseurl}}/ingest-pipelines/) are not compatible with pull-based ingestion. +* [Dynamic mapping]({{site.url}}{{site.baseurl}}/mappings/) is not supported. +* [Index rollover]({{site.url}}{{site.baseurl}}/api-reference/index-apis/rollover/) is not supported. +* Operation listeners are not supported. diff --git a/_im-plugin/pull-based-ingestion/kafka.md b/_im-plugin/pull-based-ingestion/kafka.md new file mode 100644 index 00000000..0f98c425 --- /dev/null +++ b/_im-plugin/pull-based-ingestion/kafka.md @@ -0,0 +1,70 @@ +--- +layout: default +title: Kafka source +parent: Pull-based ingestion +nav_order: 10 +--- + +# Kafka source for pull-based ingestion +**Introduced 3.0** +{: .label .label-purple } + +The `kafka` source lets an index consume messages from an Apache Kafka topic. Each OpenSearch shard reads from one partition of the topic. For more information, see [Stream partitioning]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#stream-partitioning). + +## Prerequisites + +Before you create an index that uses the Kafka source, install the `ingestion-kafka` plugin on every node using `bin/opensearch-plugin install ingestion-kafka`. + +## Creating an index + +The following request creates an index that pulls data from a Kafka topic in the segment replication mode. For other available modes, see [Ingestion modes]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#ingestion-modes): + +```json +PUT /my-index +{ + "settings": { + "ingestion_source": { + "type": "kafka", + "pointer.init.reset": "earliest", + "param": { + "topic": "test", + "bootstrap_servers": "localhost:49353" + } + }, + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index": { + "replication.type": "SEGMENT" + } + }, + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } +} +``` +{% include copy-curl.html %} + +For all `ingestion_source` settings, see [Ingestion source settings]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#ingestion-source-settings). + +## Source parameters + +The following table lists the source parameters. Specify them in the `param` object of `ingestion_source`. + +| Parameter | Required | Description | +| :--- | :--- | :--- | +| `topic` | Yes | The Kafka topic to consume from. | +| `bootstrap_servers` | Yes | The Kafka server addresses. | + +Optionally, you can provide additional standard Kafka consumer parameters (such as `fetch.min.bytes`). These parameters are passed directly to the Kafka consumer. + +## Related documentation + +* [Pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/) +* [Pull-based ingestion management APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pull-based-ingestion-management/) diff --git a/_im-plugin/pull-based-ingestion/kinesis.md b/_im-plugin/pull-based-ingestion/kinesis.md new file mode 100644 index 00000000..36ebc64a --- /dev/null +++ b/_im-plugin/pull-based-ingestion/kinesis.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Kinesis source +parent: Pull-based ingestion +nav_order: 20 +--- + +# Kinesis source for pull-based ingestion +**Introduced 3.0** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The `kinesis` source lets an index consume records from an Amazon Kinesis data stream. Each OpenSearch shard reads from one Kinesis shard. For more information, see [Stream partitioning]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#stream-partitioning). + +## Prerequisites + +Before you create an index that uses the Kinesis source, install the `ingestion-kinesis` plugin on every node using `bin/opensearch-plugin install ingestion-kinesis`. + +## Creating an index + +The following request creates an index that pulls data from a Kinesis stream in the segment replication mode. For other available modes, see [Ingestion modes]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#ingestion-modes): + +```json +PUT /my-index +{ + "settings": { + "ingestion_source": { + "type": "kinesis", + "pointer.init.reset": "earliest", + "param": { + "stream": "test", + "region": "us-east-1", + "access_key": "<access_key>", + "secret_key": "<secret_key>" + } + }, + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index": { + "replication.type": "SEGMENT" + } + }, + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } +} +``` +{% include copy-curl.html %} + +For all `ingestion_source` settings, see [Ingestion source settings]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#ingestion-source-settings). + +## Source parameters + +The following table lists the source parameters. Specify them in the `param` object of `ingestion_source`. + +| Parameter | Required | Description | +| :--- | :--- | :--- | +| `stream` | Yes | The Kinesis stream name. | +| `region` | Yes | The AWS Region. | +| `access_key` | Yes | The AWS access key. | +| `secret_key` | Yes | The AWS secret key. | +| `endpoint_override` | No | A custom endpoint for the Kinesis service. | + +When you reset a Kinesis consumer by offset, provide a Kinesis sequence number as the offset. For more information, see [Resume Ingestion API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/resume-ingestion/). + +## Related documentation + +* [Pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/) +* [Pull-based ingestion management APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pull-based-ingestion-management/) diff --git a/_im-plugin/pull-based-ingestion/object-store.md b/_im-plugin/pull-based-ingestion/object-store.md new file mode 100644 index 00000000..fbb2f927 --- /dev/null +++ b/_im-plugin/pull-based-ingestion/object-store.md @@ -0,0 +1,163 @@ +--- +layout: default +title: Object store source +parent: Pull-based ingestion +has_children: false +nav_order: 30 +redirect_from: + - /api-reference/document-apis/pull-based-ingestion-object-store/ +--- + +# Object store source for pull-based ingestion +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The `object_store` source lets an index pull newline-delimited JSON (NDJSON) files directly from object storage, such as Amazon Simple Storage Service (Amazon S3), Google Cloud Storage, Azure Blob Storage, or a shared file system. Each shard reads its own portion of the files, so you don't need a separate streaming system or loading tool for a one-time load. + +The source reads objects through a registered [snapshot repository]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/), so the bucket, endpoint, and credentials are stored in the repository configuration and never appear in index settings. + +## Prerequisites + +Before you create an index that uses the object store source, ensure that the following prerequisites are met: + +* Install the `ingestion-object-store` plugin on every node using `bin/opensearch-plugin install ingestion-object-store`. +* Register a repository of type `s3`, `gcs`, `azure`, or `fs` and set `readonly` to `true`. The source rejects repositories that are not read-only, so it cannot modify or delete objects in your storage. +* Place the files in the repository before you create the index. The files must not change during ingestion. + +The following request registers a read-only S3 repository: + +```json +PUT /_snapshot/ingest-repo +{ + "type": "s3", + "settings": { + "bucket": "my-bucket", + "base_path": "exports", + "readonly": true + } +} +``` +{% include copy-curl.html %} + +## Creating an index + +The following request creates an index that reads five NDJSON files, assigning each file to one of three shards: + +```json +PUT /events +{ + "settings": { + "index.number_of_shards": 3, + "index.number_of_replicas": 0, + "index.replication.type": "SEGMENT", + "index.ingestion_source.type": "object_store", + "index.ingestion_source.pointer.init.reset": "earliest", + "index.ingestion_source.mapper_type": "raw_payload", + "index.ingestion_source.param.repository": "ingest-repo", + "index.ingestion_source.param.shard_split": "whole_files", + "index.ingestion_source.param.source_prefix": "events/part-", + "index.ingestion_source.param.manifest": "[{\"key\":\"events/part-0001.ndjson\",\"size\":76},{\"key\":\"events/part-0002.ndjson\",\"size\":50},{\"key\":\"events/part-0003.ndjson\",\"size\":52},{\"key\":\"events/part-0004.ndjson\",\"size\":26},{\"key\":\"events/part-0005.ndjson\",\"size\":50}]" + }, + "mappings": { + "properties": { + "name": { "type": "keyword" }, + "age": { "type": "integer" } + } + } +} +``` +{% include copy-curl.html %} + +The object store source requires the following `ingestion_source` settings to have non-default values: + +* The `pointer.init.reset` setting must be `earliest` or `none`. The default value, `latest`, starts reading at the end of the data, so the source rejects it. The source also rejects `reset_by_timestamp` and accepts `reset_by_offset` only for single-shard indexes. For more information, see [Stream position]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#stream-position). +* The `mapper_type` setting must be `raw_payload`. Each line of a file is indexed as one document, using the line as the document body. For more information, see [Message format]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#message-format). + +## Source parameters + +The following table lists the source parameters. Specify each parameter as `index.ingestion_source.param.<name>`. + +| Parameter | Required | Default | Description | +| :--- | :--- | :--- | :--- | +| `repository` | Yes | | The name of a registered read-only `s3`, `gcs`, `azure`, or `fs` repository. If the repository is not registered, the shard retries every 10 seconds, so you can register the repository after creating the index. | +| `source_url` | Conditional | | The key of a single object, relative to the repository base path. Either `source_url` or `source_prefix` is required. Required when `shard_split` is `equal_bytes`. | +| `source_prefix` | Conditional | | The key prefix of the objects to read, relative to the repository base path. Either `source_url` or `source_prefix` is required. Required when `shard_split` is `whole_files` or `shard_prefixes`. | +| `shard_split` | Yes | | The method used to divide objects among shards. Valid values are `whole_files`, `shard_prefixes`, and `equal_bytes`. For more information, see [Dividing objects among shards](#dividing-objects-among-shards). | +| `discovery` | No | `manifest` | The method that shards use to find objects. Valid values are `manifest` and `list`. For more information, see [Finding objects](#finding-objects). | +| `manifest` | Conditional | | The list of objects and their exact sizes in bytes, provided as a JSON array in a string: `[{"key":"<key>","size":<size>}, ...]`. Required when `discovery` is `manifest`. Maximum size is 1 MB. | +| `format` | No | `ndjson` | The file format. Only `ndjson` is supported. | +| `max_record_bytes` | No | `10485760` (10 MB) | The maximum record size, in bytes. A line that exceeds this size pauses the shard. | +| `max_objects` | No | `1000000` | The maximum number of objects that a manifest can list or that a shard can discover. | +| `max_list_requests` | No | Unlimited | The maximum number of list requests that a shard can send to the object store. | +| `max_get_requests` | No | Unlimited | The maximum number of read requests that a shard can send to the object store. | +| `max_bytes` | No | Unlimited | The maximum number of bytes that a shard can read from the object store. | + +All keys are relative to the repository base path. A key cannot start with `/`; contain `//`, `*`, or `?`; or contain a `.` or `..` path segment. + +Object storage providers can charge per request and per byte transferred. If `max_list_requests`, `max_get_requests`, or `max_bytes` is unlimited, OpenSearch logs a warning. Limits are counted per shard and reset when the shard restarts or relocates. +{: .note} + +## Finding objects + +The `discovery` parameter determines how each shard finds the objects to read. It supports the `manifest` and `list` methods. + +### Manifest + +When `discovery` is `manifest` (the default), you list every object and its exact size in the `manifest` parameter. Every shard reads the same list, so the source sends no list requests to the object store. Each key must start with the `source_prefix` value. Because the manifest is stored in the cluster state, it is limited to 1 MB. For larger sets of objects, use the `list` method. + +Objects added to the object store after the index is created are not read. If an object is removed, truncated, or enlarged before it is fully read, the shard pauses. + +### List + +When `discovery` is `list`, each shard lists the objects in its own folder when it starts. This method requires setting `shard_split` to `shard_prefixes` and omitting the `manifest` parameter. Shard `N` reads the objects in `<source_prefix>/N/`. For example, if `source_prefix` is `listed/` and the index has two shards, shard 0 reads `listed/0/` and shard 1 reads `listed/1/`. Listing includes nested folders up to 64 levels deep. + +A shard lists its folder each time it starts, including after a restart, a relocation, or a settings update. Place all objects in the folders before you create the index, and don't change them during ingestion. If objects change between listings, the shard processes them as follows: + +* An object added after the previous listing is read only if its name sorts after the object that the shard was reading. +* An unread object that was removed is skipped. +* A resized object is read up to its new size. +* If the object that the shard was reading was removed and other objects remain in the folder, the shard pauses. +* If no objects remain in the folder, the shard reads nothing and reports a lag of `0`. + +Objects that are not in any shard folder are not read. + +## Dividing objects among shards + +Each shard determines its own portion of the objects from the same settings, so each record is read by exactly one shard. The `shard_split` parameter supports the following values: + +* `whole_files`: Each object is assigned to one shard based on a hash of its key. This method balances the number of objects per shard and does not account for object size. +* `shard_prefixes`: Objects in `<source_prefix>/N/` are assigned to shard `N`. +* `equal_bytes`: The single object specified in `source_url` is divided into one byte range per shard. Each range boundary is moved forward to the start of the next line so that no record is split between shards. The manifest must contain exactly this one object, and its size must be greater than 0. + +## Exactly-once ingestion + +Each document ID is built from the shard number, the object key, and the byte offset at which the record starts. If a record is read again after a crash or restart, it receives the same ID and overwrites the earlier copy, so each record produces exactly one document. + +## Monitoring ingestion progress + +The `consumer_stats.pointer_based_lag` metric reports the number of bytes that the shard has not yet read. Ingestion is complete when this metric is `0` on every shard. For more information, see [Pull-based ingestion metrics]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#pull-based-ingestion-metrics). + +## Errors + +The following errors pause the shard: + +* A configuration error. The reason is written to the logs. +* A read error, such as a missing object or a reached cost limit. +* An object size mismatch. The source verifies that each object has its declared size. If an object is shorter or longer than declared, or is declared empty but contains data, the shard pauses so that partial data is not indexed. + +Lines that cannot be parsed are handled according to the `error_strategy` setting. For more information, see [Updating the error policy]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/#updating-the-error-policy). + +## Limitations + +The object store source has the following limitations: + +* Compressed files, such as gzip files, are not supported. +* You cannot change the `manifest`, `source_url`, `source_prefix`, `shard_split`, or `discovery` parameters on an existing index. To change these parameters, create a new index. + +## Related documentation + +* [Pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/) +* [Pull-based ingestion management APIs]({{site.url}}{{site.baseurl}}/api-reference/index-apis/pull-based-ingestion-management/) diff --git a/_im-plugin/refresh-analyzer.md b/_im-plugin/refresh-analyzer.md index 2e50f06d..f7370a6a 100644 --- a/_im-plugin/refresh-analyzer.md +++ b/_im-plugin/refresh-analyzer.md @@ -1,7 +1,8 @@ --- layout: default title: Refresh search analyzer -nav_order: 50 +parent: Tuning indexes +nav_order: 10 has_toc: false redirect_from: - /query-dsl/analyzers/refresh-analyzer/ @@ -10,31 +11,98 @@ redirect_from: # Refresh search analyzer -With ISM installed, you can refresh search analyzers in real time with the following API: +Use the Refresh Search Analyzer API to apply a change to a search analyzer's resource files in real time. For example, if you change the synonym list in your analyzer, the change takes effect without you needing to close and reopen the index: ```json -POST /_plugins/_refresh_search_analyzers/<index or alias or wildcard> +POST /_plugins/_refresh_search_analyzers/{index} ``` -For example, if you change the synonym list in your analyzer, the change takes effect without you needing to close and reopen the index. +{% include copy-curl.html %} -To work, the token filter must have an `updateable` flag of `true`: +## Path parameters + +The following table lists the available path parameters. All path parameters are required. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `index` | String | A comma-separated list of indexes, data streams, or index aliases to which the operation is applied. Supports wildcard expressions (`*`). Use `_all` or `*` to specify all indexes and data streams in a cluster. | + +## Query parameters + +The following table lists the supported query parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`reload_cached_resources` | Boolean | When set to `true`, reloads cached resources from disk without rebuilding caches for token filters that load files from disk (for example, the [`hunspell`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/hunspell/) filter's dictionary files). When `false` (the default), analyzer factories are rebuilt but cached resources are reused. + +## Making a token filter updatable + +A token filter is only refreshed if it has an `updateable` flag of `true`. An updatable filter can be used only in a search analyzer, not in an index analyzer, because existing documents are not reanalyzed. The following request creates an index with an updatable synonym filter and applies it as the search analyzer for the `desc` field: ```json +PUT /synonym_index { - "analyzer": { - "my_synonyms": { - "tokenizer": "whitespace", - "filter": [ - "synonym" - ] + "settings": { + "index": { + "analysis": { + "analyzer": { + "my_synonyms": { + "tokenizer": "whitespace", + "filter": [ + "synonym" + ] + } + }, + "filter": { + "synonym": { + "type": "synonym_graph", + "synonyms_path": "analysis/synonyms.txt", + "updateable": true + } + } + } } }, - "filter": { - "synonym": { - "type": "synonym_graph", - "synonyms_path": "synonyms.txt", - "updateable": true + "mappings": { + "properties": { + "desc": { + "type": "text", + "analyzer": "standard", + "search_analyzer": "my_synonyms" + } } } } ``` +{% include copy-curl.html %} + +The `synonyms_path` is relative to the `config` directory of each node. After you edit the file, refresh the analyzer: + +```json +POST /_plugins/_refresh_search_analyzers/synonym_index +``` +{% include copy-curl.html %} + +## Example response + +The response lists the analyzers that were refreshed in each index: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "successful_refresh_details": [ + { + "index": "synonym_index", + "refreshed_analyzers": [ + "my_synonyms" + ] + } + ] +} +``` + +Searches against `desc` now use the updated synonym list. + diff --git a/_im-plugin/reindex-data.md b/_im-plugin/reindex-data.md index 2e328808..3fcfa509 100644 --- a/_im-plugin/reindex-data.md +++ b/_im-plugin/reindex-data.md @@ -1,268 +1,110 @@ --- layout: default -title: Reindex data -nav_order: 15 +title: Reindexing data +nav_order: 22 redirect_from: - - /opensearch/reindex-data/ + - /im-plugin/reindex-data/index/ --- -# Reindex data +# Reindexing data -After creating an index, you might need to make an extensive change such as adding a new field to every document or combining multiple indexes to form a new one. Rather than deleting your index, making the change offline, and then indexing your data again, you can use the `reindex` operation. +Some changes cannot be made to an index in place. You cannot change the type of an existing field, remove a field from a mapping, or change the number of primary shards without rebuilding the index. Reindexing copies documents from one or more source indexes into a destination index that has the configuration you want, so you can make these changes without exporting your data and loading it again. -With the `reindex` operation, you can copy all or a subset of documents that you select through a query to another index. Reindex is a `POST` operation. In its most basic form, you specify a source index and a destination index. +Reindexing is also how you combine several indexes into one, split one index by a query, apply an ingest pipeline to documents that are already stored, or move data between clusters. -Reindexing can be an expensive operation depending on the size of your source index. We recommend you disable replicas in your destination index by setting `number_of_replicas` to `0` and re-enable them once the reindex process is complete. -{: .note } +Reindexing reads each document from the `_source` field of the source index and indexes it into the destination index using the destination's mappings and settings. This has two consequences: ---- +- The source index must have `_source` enabled. Any `stored_fields` configuration is ignored. +- The destination index does not inherit the mappings and settings of the source index. If it does not exist, OpenSearch creates it with dynamic mappings inferred from the first documents copied, which is rarely what you want. Create it with the mappings and settings you need before you start. -#### Table of contents -1. TOC -{:toc} +Reindexing a large index is expensive in I/O and can slow down searches on the cluster. Set `number_of_replicas` to `0` on the destination index while the copy runs and restore it afterward, and consider throttling the operation. For more information, see [Performance optimization]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/#performance-optimization). +{: .note} +## Reindexing an index ---- - -## Reindex all documents - -You can copy all documents from one index to another. - -You first need to create a destination index with your desired field mappings and settings or you can copy the ones from your source index: +In its simplest form, a reindex request names a source and a destination. Create the source index and add a document to it: ```json -PUT destination +POST my-source-index/_doc?refresh=true { - "mappings":{ - "Add in your desired mappings" - }, - "settings":{ - "Add in your desired settings" - } + "title": "Spirited Away" } ``` +{% include copy-curl.html %} -This `reindex` command copies all the documents from a source index to a destination index: - -```json -POST _reindex -{ - "source":{ - "index":"source" - }, - "dest":{ - "index":"destination" - } -} -``` - -If the destination index is not already created, the `reindex` operation creates a new destination index with default configurations. - -## Reindex from a remote cluster - -You can copy documents from an index in a remote cluster. Use the `remote` option to specify the remote hostname and the required login credentials. - -This command reaches out to a remote cluster, logs in with the username and password, and copies all the documents from the source index in that remote cluster to the destination index in your local cluster: - -```json -POST _reindex -{ - "source":{ - "remote":{ - "host":"https://<REST_endpoint_of_remote_cluster>:9200", - "username":"YOUR_USERNAME", - "password":"YOUR_PASSWORD" - }, - "index": "source" - }, - "dest":{ - "index":"destination" - } -} -``` - -You can specify the following options: - -Options | Valid values | Description | Required -:--- | :--- | :--- -`host` | String | The REST endpoint of the remote cluster. | Yes -`username` | String | The username to log into the remote cluster. | No -`password` | String | The password to log into the remote cluster. | No -`socket_timeout` | Time Unit | The wait time for socket reads (default 30s). | No -`connect_timeout` | Time Unit | The wait time for remote connection timeouts (default 30s). | No - - -## Reindex a subset of documents - -You can copy a specific set of documents that match a search query. - -This command copies only a subset of documents matched by a query operation to the destination index: - -```json -POST _reindex -{ - "source":{ - "index":"source", - "query": { - "match": { - "field_name": "text" - } - } - }, - "dest":{ - "index":"destination" - } -} -``` - -For a list of all query operations, see [Full-text queries]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/full-text/index). - -## Combine one or more indexes - -You can combine documents from one or more indexes by adding the source indexes as a list. - -This command copies all documents from two source indexes to one destination index: - -```json -POST _reindex -{ - "source":{ - "index":[ - "source_1", - "source_2" - ] - }, - "dest":{ - "index":"destination" - } -} -``` -Make sure the number of shards for your source and destination indexes is the same. - -## Reindex only unique documents - -You can copy only documents missing from a destination index by setting the `op_type` option to `create`. -In this case, if a document with the same ID already exists, the operation ignores the one from the source index. -To ignore all version conflicts of documents, set the `conflicts` option to `proceed`. - -```json -POST _reindex -{ - "conflicts":"proceed", - "source":{ - "index":"source" - }, - "dest":{ - "index":"destination", - "op_type":"create" - } -} -``` - -## Transform documents during reindexing - -You can transform your data during the reindexing process using the `script` option. -We recommend Painless for scripting in OpenSearch. - -This command runs the source index through a Painless script that increments a `number` field inside an `account` object before copying it to the destination index: - -```json -POST _reindex -{ - "source":{ - "index":"source" - }, - "dest":{ - "index":"destination" - }, - "script":{ - "lang":"painless", - "source":"ctx._account.number++" - } -} -``` - -You can also specify an ingest pipeline to transform your data during the reindexing process. - -You would first have to create a pipeline with `processors` defined. You have a number of different `processors` available to use in your ingest pipeline. - -Here's a sample ingest pipeline that defines a `split` processor that splits a `text` field based on a `space` separator and stores it in a new `word` field. The `script` processor is a Painless script that finds the length of the `word` field and stores it in a new `word_count` field. The `remove` processor removes the `test` field. - -```json -PUT _ingest/pipeline/pipeline-test -{ -"description": "Splits the text field into a list. Computes the length of the 'word' field and stores it in a new 'word_count' field. Removes the 'test' field.", -"processors": [ - { - "split": { - "field": "text", - "separator": "\\s+", - "target_field": "word" - }, - } - { - "script": { - "lang": "painless", - "source": "ctx.word_count = ctx.word.length" - } - }, - { - "remove": { - "field": "test" - } - } -] -} -``` - -After creating a pipeline, you can use the `reindex` operation: +Then copy it into the destination index: ```json POST _reindex { "source": { - "index": "source", + "index": "my-source-index" }, "dest": { - "index": "destination", - "pipeline": "pipeline-test" + "index": "my-destination-index" } } ``` +{% include copy-curl.html %} -## Update documents in the current index +By default, the request runs to completion and returns a summary of the documents copied. To run it in the background, set `wait_for_completion` to `false`; the response contains a task ID that you can pass to the [Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/) to check on progress, or use to [set up a notification]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/). -To update the data in your current index itself without copying it to a different index, use the `update_by_query` operation. +The [Reindex Documents API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) documents the rest of what a reindex request can do, including the following: -The `update_by_query` operation is `POST` operation that you can perform on a single index at a time. +- Copying a subset of documents selected by a query +- Combining several source indexes into one destination +- Reindexing from a remote cluster +- Skipping documents that already exist in the destination +- Transforming documents during the copy with a script or an ingest pipeline +- Slicing the operation to run in parallel -```json -POST <index_name>/_update_by_query -``` +## Reindexing data in OpenSearch Dashboards -If you run this command with no parameters, it increments the version number for all documents in the index. +To navigate to the **Index Management** page, go to **Management > Index Management** on the top menu. -## Source index options +The following image shows the reindex form. -You can specify the following options for your source index: +![Reindex form]({{site.url}}{{site.baseurl}}/images/admin-ui-index/reindex-form.png) -Option | Valid values | Description | Required -:--- | :--- | :--- -`index` | String | The name of the source index. You can provide multiple source indexes as a list. | Yes -`max_docs` | Integer | The maximum number of documents to reindex. | No -`query` | Object | The search query to use for the reindex operation. | No -`size` | Integer | The number of documents to reindex. | No -`slice` | String | Specify manual or automatic slicing to parallelize reindexing. | No +To reindex an index, follow these steps: -## Destination index options +1. Optionally, [create the destination index]({{site.url}}{{site.baseurl}}/im-plugin/index-operations/#creating-an-index-1) first. You can also create it during the following steps and import the settings and mappings from the source index. +1. In **Index Management**, select **Indexes**. +1. Select **Actions**, and then select **Reindex**. +1. In **Configure source index**, select the indexes, aliases, or data streams to copy from. +1. In **Specify a reindex option**, select **Reindex all documents** or **Reindex a subset of documents**. +1. If you are reindexing a subset, enter a [query]({{site.url}}{{site.baseurl}}/query-dsl/) in **Query expression** to select the documents to copy. For example, the following query selects the documents with a `timestamp` on or after January 1, 2024: -You can specify the following options for your destination index: + ```json + { + "bool": { + "filter": [ + { "range": { "timestamp": { "gte": "2024-01-01" }}} + ] + } + } + ``` + {% include copy.html %} -Option | Valid values | Description | Required -:--- | :--- | :--- -`index` | String | The name of the destination index. | Yes -`version_type` | Enum | The version type for the indexing operation. Valid values: internal, external, external_gt, external_gte. | No +1. In **Configure destination index**, select the destination. To create it here, select **Create index**, enter a name, optionally select aliases, and then select **Import settings and mappings** and select the source index to copy its configuration. You can add fields to the destination in **Index mapping**. +1. Optionally, expand **Advanced settings** and set any of the following options: -## Index codec considerations + - To skip the documents whose IDs already exist in the destination, select **Reindex only unique documents**. + - To keep a version conflict from stopping the operation, select **Ignore conflicts during reindexing** in **Version conflicts**. + - To split the operation into parallel subtasks, select **Slice this reindexing operation**. + - To apply an [ingest pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/) to each document before it is written, select the pipeline in **Transform with ingest pipeline**. + - To be notified about the outcome, select **Send additional notifications**. For more information, see [Sending additional notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/#sending-additional-notifications). -For index codec considerations, see [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#reindexing). +1. Select **Reindex**. + +Reindexing can take a long time. To follow its progress, see [Checking the status of long-running operations]({{site.url}}{{site.baseurl}}/im-plugin/index-maintenance/#checking-the-status-of-long-running-operations). + +The source and destination must be different. Reindexing an index into itself is rejected; to update documents in place, use [Update By Query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-by-query/). +{: .note} + +## Related documentation + +- [Reindex Documents API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) +- [Update By Query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-by-query/) +- [Index codecs]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/#reindexing) +- [Long-running operation notifications]({{site.url}}{{site.baseurl}}/im-plugin/notifications-settings/) diff --git a/_im-plugin/security.md b/_im-plugin/security.md index bfdc458d..944d422f 100644 --- a/_im-plugin/security.md +++ b/_im-plugin/security.md @@ -1,7 +1,7 @@ --- layout: default title: Index management security -nav_order: 40 +nav_order: 90 has_children: false --- @@ -9,7 +9,7 @@ has_children: false Using the Security plugin with index management lets you limit non-admin users to certain actions. For example, you might want to set up your security such that a group of users can only read ISM policies, while others can create, delete, or change policies. -All index management data are protected as system indexes, and only a super admin or an admin with a Transport Layer Security (TLS) certificate can access system indexes. For more information, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices). +All index management data is protected as system indexes, and only a super admin or an admin with a Transport Layer Security (TLS) certificate can access system indexes. For more information, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). ## Basic permissions @@ -17,13 +17,13 @@ The Security plugin comes with one role that offers full access to index managem With security enabled, users not only need the correct index management permissions, but they also need permissions to execute actions to involved indexes. For example, if a user wants to use the REST API to attach a policy that executes a rollup job to an index named `system-logs`, they would need the permissions to attach a policy and execute a rollup job, as well as access to `system-logs`. -Finally, with the exceptions of Create Policy, Get Policy, and Delete Policy, users also need the `indices:admin/opensearch/ism/managedindex` permission to execute [ISM APIs]({{site.url}}{{site.baseurl}}/im-plugin/ism/api). +Finally, users also need the `indices:admin/opensearch/ism/managedindex` permission for the target indexes to use the following [ISM APIs]({{site.url}}{{site.baseurl}}/im-plugin/ism/api/): add policy, remove policy from index, update managed index policy, retry failed index, and explain index. The remove, update, and retry operations fail if the user lacks this permission for any target index. The add policy and explain index operations skip the indexes for which the user lacks this permission. ## (Advanced) Limit access by backend role You can use backend roles to configure fine-grained access to index management policies and actions. For example, users of different departments in an organization might view different policies depending on what roles and permissions they are assigned. -First, ensure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/access-control/api#create-user). +First, ensure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/api/users/create-user/). Use the REST API to enable the following setting: @@ -35,6 +35,10 @@ PUT _cluster/settings } } ``` +{% include copy-curl.html %} + +Only enable this setting on a cluster that has the Security plugin enabled. On a cluster with security disabled, the setting is accepted but every index management write request then fails with `403 Filter by user backend roles in IndexManagement is not supported with security disabled`. +{: .warning} With security enabled, only users who share at least one backend role can see and execute the policies and actions relevant to their roles. diff --git a/_im-plugin/similarity.md b/_im-plugin/similarity.md new file mode 100644 index 00000000..e4af861a --- /dev/null +++ b/_im-plugin/similarity.md @@ -0,0 +1,675 @@ +--- +layout: default +title: Similarity +parent: Tuning indexes +nav_order: 40 +--- + +# Similarity + +A similarity defines how matching documents are scored and ranked during search operations. OpenSearch uses similarity algorithms to calculate relevance scores that determine the order of search results. + +Each field can have its own similarity configuration, allowing fine-tuned control over how different types of content are scored. You can define custom similarity algorithms in your index settings at the index level. Once configured, you can apply these algorithms to specific fields using the [`similarity` mapping parameter]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/similarity/). + +Configuring custom similarity settings is an advanced feature. The built-in similarities are sufficient for most use cases. + +## Configuring similarity at the index level + +OpenSearch uses BM25 as the default similarity for all fields. You can change the default similarity for an index to apply a single similarity algorithm to all fields in that index. + +### Setting default similarity at index creation + +You can set the default similarity when creating an index: + +```json +PUT /product_catalog +{ + "settings": { + "index": { + "similarity": { + "default": { + "type": "boolean" + } + } + } + } +} +``` +{% include copy-curl.html %} + +When you use the special `default` name, the similarity is automatically applied to all fields in the index. You don't need to specify the similarity in individual field mappings. + +### Changing default similarity after index creation + +Similarity settings are not dynamic, so updating them on an open index fails. To change the default similarity after index creation, close the index, update the settings, and then reopen it. + +First, close the index: + +```json +POST /product_catalog/_close +``` +{% include copy-curl.html %} + +Next, update the default similarity: + +```json +PUT /product_catalog/_settings +{ + "index": { + "similarity": { + "default": { + "type": "DFR", + "basic_model": "g", + "after_effect": "l", + "normalization": "h2", + "normalization.h2.c": "3.0" + } + } + } +} +``` +{% include copy-curl.html %} + +Finally, reopen the index: + +```json +POST /product_catalog/_open +``` +{% include copy-curl.html %} + +To verify that the default similarity has changed, send the following request: + +```json +GET /product_catalog/_settings +``` +{% include copy-curl.html %} + +The response confirms that the default similarity has been updated: + +```json +{ + "product_catalog": { + "settings": { + "index": { + "replication": { + "type": "DOCUMENT" + }, + "number_of_shards": "1", + "provided_name": "product_catalog", + "similarity": { + "default": { + "basic_model": "g", + "type": "DFR", + "normalization": "h2", + "after_effect": "l", + "normalization.h2": { + "c": "3.0" + } + } + }, + "creation_date": "1761328470322", + "number_of_replicas": "1", + "uuid": "YFr9ts8VSaSV-YkHZP3mYQ", + "version": { + "created": "137227827" + } + } + } + } +} +``` + +### Parameter persistence when changing similarity types + +When changing from one similarity type to another, OpenSearch retains the parameters from the previous configuration. If the new similarity type doesn't support these parameters, the update fails. + +For example, change the default similarity from `DFR` to `boolean`. First, close the index: + +```json +POST /product_catalog/_close +``` +{% include copy-curl.html %} + +Then update the default similarity: + +```json +PUT /product_catalog/_settings +{ + "index": { + "similarity": { + "default": { + "type": "boolean" + } + } + } +} +``` +{% include copy-curl.html %} + +The request fails because the `DFR` parameters are still set: + +```json +{ + "error": { + "root_cause": [ + { + "type": "illegal_argument_exception", + "reason": "Unknown settings for similarity of type [boolean]: [normalization.h2.c, normalization, after_effect, basic_model]" + } + ], + "type": "illegal_argument_exception", + "reason": "Unknown settings for similarity of type [boolean]: [normalization.h2.c, normalization, after_effect, basic_model]" + }, + "status": 400 +} +``` + +To resolve this, explicitly set the old parameters to `null` in the same request: + +```json +PUT /product_catalog/_settings +{ + "index": { + "similarity": { + "default": { + "type": "boolean", + "basic_model": null, + "after_effect": null, + "normalization": null, + "normalization.h2.c": null + } + } + } +} +``` +{% include copy-curl.html %} + +Then reopen the index: + +```json +POST /product_catalog/_open +``` +{% include copy-curl.html %} + +## Configuring a built-in similarity at the field level + +OpenSearch provides built-in similarity algorithms (`BM25` and `boolean`) that can be used directly in field mappings. To configure a similarity at the field level, apply it to the field when creating the index. The following example applies a `boolean` similarity to the `content` field: + +```json +PUT /blog_posts_2/ +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "similarity": "boolean" + } + } + } +} +``` +{% include copy-curl.html %} + +In this example, only the `content` field uses a `boolean` similarity. Other fields in the index will use the default `BM25` similarity. + +## Configuring a custom similarity + +For more advanced use cases, you can define named custom similarities that can be applied to specific fields. This approach provides greater flexibility when different fields in your index need different scoring algorithms. + +Configuring named custom similarities requires a two-step process: + +1. Define the similarity in the index settings with a custom name. +2. Apply the similarity to specific fields in mappings. + +### Step 1: Define a custom similarity + +The following example creates an index with a custom `DFR` similarity configuration: + +```json +PUT /blog_posts +{ + "settings": { + "index": { + "similarity": { + "blog_similarity": { + "type": "DFR", + "basic_model": "g", + "after_effect": "l", + "normalization": "h2", + "normalization.h2.c": "3.0" + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Step 2: Apply the custom similarity to fields + +After defining the similarity, you must explicitly apply it to specific fields in your mappings. Unlike the default similarity, custom similarities are not automatically applied to all fields: + +```json +PUT /blog_posts/_mapping +{ + "properties": { + "content": { + "type": "text", + "similarity": "blog_similarity" + } + } +} +``` +{% include copy-curl.html %} + +In this example, only the `content` field uses the custom `blog_similarity`. Other fields in the index (if any) continue using the default `BM25` similarity unless explicitly configured otherwise. + +## Available similarity types + +OpenSearch supports the following similarity types. + +### BM25 similarity (default) + +The `BM25` similarity is based on TF/IDF and includes built-in term frequency normalization. It works well for most text fields, particularly shorter fields like titles and names. + +The `BM25` similarity supports the following parameters. + +| Parameter | Description | Default | Required | +|-----------|-------------|---------|----------| +| `k1` | Controls non-linear term frequency normalization (saturation). | `1.2` | No | +| `b` | Controls how much document length normalizes term frequency values. | `0.75` | No | +| `discount_overlaps` | Determines whether overlap tokens (tokens with 0 position increment) are ignored when computing norms. | `true` (ignore overlap tokens when computing norms) | No | + +### Boolean similarity + +The built-in `boolean` similarity assigns all matching documents the same constant score, which is useful when you only need to determine whether documents match rather than how relevant they are. This similarity ignores term frequency, document length, and other scoring factors. + +The `boolean` similarity does not support parameters. + +### DFR similarity + +The `DFR` similarity implements the [divergence from randomness](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/DFRSimilarity.html) framework for document scoring. + +The `DFR` similarity supports the following parameters. + +| Parameter | Description | Valid values | Required | +|-----------|-------------|------------------|----------| +| `basic_model` | Basic model for the DFR framework. | [`g`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/BasicModelG.html), [`if`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/BasicModelIF.html), [`in`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/BasicModelIn.html), [`ine`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/BasicModelIne.html) | Yes | +| `after_effect` | After effect model for the DFR framework. | [`b`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/AfterEffectB.html), [`l`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/AfterEffectL.html) | Yes | +| `normalization` | Normalization model for the DFR framework. `h1`, `h2`, and `h3` accept an optional `c` parameter, specified as `normalization.h1.c`, `normalization.h2.c`, or `normalization.h3.c`. `z` accepts an optional `z` parameter, specified as `normalization.z.z`, whose value must be greater than 0 and less than 0.5. `no` accepts no parameter. | [`no`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/Normalization.NoNormalization.html), [`h1`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/NormalizationH1.html), [`h2`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/NormalizationH2.html), [`h3`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/NormalizationH3.html), [`z`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/NormalizationZ.html) | Yes | + +### DFI similarity + +The `DFI` similarity implements the [divergence from independence (DFI)](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/DFISimilarity.html) model. + +The `DFI` similarity supports the following parameters. + +| Parameter | Description | Valid values | Required | +|-----------|-------------|------------------|----------| +| `independence_measure` | Independence measure for the DFI model. | [`standardized`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/IndependenceStandardized.html), [`saturated`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/IndependenceSaturated.html), [`chisquared`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/IndependenceChiSquared.html) | Yes | + +When using `DFI` similarity, avoid removing stop words for optimal relevance. Terms with a frequency that is lower than expected will receive a score of 0. + +### IB similarity + +The `IB` similarity uses the [information-based model](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/IBSimilarity.html), which analyzes the repetitive usage of basic elements in symbolic distributions. + +The `IB` similarity supports the following parameters. + +| Parameter | Description | Valid values | Required | +|-----------|-------------|------------------|----------| +| `distribution` | Distribution model for the `IB` framework. | [`ll`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/DistributionLL.html), [`spl`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/DistributionSPL.html) | Yes | +| `lambda` | Lambda model for the `IB` framework. | [`df`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/LambdaDF.html), [`ttf`](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/LambdaTTF.html) | Yes | +| `normalization` | Normalization model for the `IB` framework. | Same options as `DFR` similarity | Yes | + +<!-- vale off --> +### LM Dirichlet similarity +<!-- vale on --> + +The `LMDirichlet` similarity uses [language model similarity](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/LMDirichletSimilarity.html) with Dirichlet smoothing. + +The `LMDirichlet` similarity supports the following parameters. + +| Parameter | Description | Default | Required | +|-----------|-------------|---------|----------| +| `mu` | Smoothing parameter. | `2000` | No | + +Terms with fewer occurrences than predicted by the language model receive a score of 0. + +<!-- vale off --> +### LM Jelinek Mercer similarity +<!-- vale on --> + +The `LMJelinekMercer` similarity uses [language model similarity](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.html) with Jelinek-Mercer smoothing. + +The `LMJelinekMercer` similarity supports the following parameters. + +| Parameter | Description | Default | Required | +|-----------|-------------|---------|----------| +| `lambda` | Interpolation parameter. Values around `0.1` work well for title queries, while `0.7` is better for longer queries. | `0.1` | No | + +### Scripted similarity + +The `scripted` similarity allows custom scoring logic using OpenSearch's scripting capabilities. + +When writing scripts for `scripted` similarities, you have access to the following variables. These variables allow you to implement custom scoring algorithms based on term frequency, document frequency, field statistics, and document characteristics. + +| Variable | Description | +|----------|-------------| +| `weight` | A document-independent weight (obtained from the `weight_script` if provided, otherwise `1.0`). | +| `query.boost` | A query-level boost factor applied to the term. | +| `field.docCount` | The total number of documents that have this field. | +| `field.sumDocFreq` | The sum of document frequencies across all terms in this field. | +| `field.sumTotalTermFreq` | The sum of total term frequencies across all terms in this field. | +| `term.docFreq` | The number of documents containing this specific term. | +| `term.totalTermFreq` | The total number of occurrences of this term across all documents. | +| `doc.freq` | The frequency of this term in the current document. | +| `doc.length` | The total number of terms in the current document. | + +To ensure correct search behavior, `scripted` similarities must follow these rules: + +- Returned scores must be positive. +- Scores must not decrease when `doc.freq` increases and all other variables remain the same. +- Scores must not increase when `doc.length` increases and all other variables remain the same. + +The following example shows a custom TF-IDF implementation. + +First, create an index and define a script to calculate similarity: + +```json +PUT /research_papers +{ + "settings": { + "number_of_shards": 1, + "similarity": { + "custom_tfidf": { + "type": "scripted", + "script": { + "source": "double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;" + } + } + } + }, + "mappings": { + "properties": { + "abstract": { + "type": "text", + "similarity": "custom_tfidf" + } + } + } +} +``` +{% include copy-curl.html %} + +Index sample documents: + +```json +PUT /research_papers/_doc/1 +{ + "abstract": "machine learning algorithms data mining" +} +``` +{% include copy-curl.html %} + +```json +PUT /research_papers/_doc/2 +{ + "abstract": "data analysis statistical methods" +} +``` +{% include copy-curl.html %} + +Refresh the index: + +```json +POST /research_papers/_refresh +``` +{% include copy-curl.html %} + +Now you can search the index and request scoring explanations: + +```json +GET /research_papers/_search?explain=true +{ + "query": { + "bool": { + "must": [ + { + "match": { + "abstract": "machine" + } + } + ], + "boost": 2.0 + } + } +} +``` +{% include copy-curl.html %} + +The response shows the custom TF-IDF calculation with a score of `1.2570862` for the matching document. The `_explanation` section reveals all the variables available to your script and their values for this specific search: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2570862, + "hits": [ + { + "_shard": "[research_papers][0]", + "_node": "KfEEGG7_SsKZVFqI4ko2FA", + "_index": "research_papers", + "_id": "1", + "_score": 1.2570862, + "_source": { + "abstract": "machine learning algorithms data mining" + }, + "_explanation": { + "value": 1.2570862, + "description": "weight(abstract:machine in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 1.2570862, + "description": "score from ScriptedSimilarity(weightScript=[null], script=[Script{type=inline, lang='painless', idOrCode='double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;', options={}, params={}}]) computed from:", + "details": [ + { + "value": 1.0, + "description": "weight", + "details": [] + }, + { + "value": 2.0, + "description": "query.boost", + "details": [] + }, + { + "value": 2, + "description": "field.docCount", + "details": [] + }, + { + "value": 9, + "description": "field.sumDocFreq", + "details": [] + }, + { + "value": 9, + "description": "field.sumTotalTermFreq", + "details": [] + }, + { + "value": 1, + "description": "term.docFreq", + "details": [] + }, + { + "value": 1, + "description": "term.totalTermFreq", + "details": [] + }, + { + "value": 1.0, + "description": "doc.freq", + "details": [] + }, + { + "value": 5, + "description": "doc.length", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` + +You can improve performance by separating document-independent calculations into another script named `weight_script`. For queries matching many documents, the `weight_script` runs once per term, while the main `script` runs once per document. The score produced by the `weight_script` is available in the `weight` variable: + +```json +PUT /research_papers_optimized +{ + "settings": { + "number_of_shards": 1, + "similarity": { + "optimized_tfidf": { + "type": "scripted", + "weight_script": { + "source": "double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; return query.boost * idf;" + }, + "script": { + "source": "double tf = Math.sqrt(doc.freq); double norm = 1/Math.sqrt(doc.length); return weight * tf * norm;" + } + } + } + }, + "mappings": { + "properties": { + "abstract": { + "type": "text", + "similarity": "optimized_tfidf" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the same sample documents into `research_papers_optimized`, refresh the index, and run the same query. The response shows how the optimized similarity works: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2570862, + "hits": [ + { + "_shard": "[research_papers_optimized][0]", + "_node": "KfEEGG7_SsKZVFqI4ko2FA", + "_index": "research_papers_optimized", + "_id": "1", + "_score": 1.2570862, + "_source": { + "abstract": "machine learning algorithms data mining" + }, + "_explanation": { + "value": 1.2570862, + "description": "weight(abstract:machine in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 1.2570862, + "description": "score from ScriptedSimilarity(weightScript=[Script{type=inline, lang='painless', idOrCode='double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; return query.boost * idf;', options={}, params={}}], script=[Script{type=inline, lang='painless', idOrCode='double tf = Math.sqrt(doc.freq); double norm = 1/Math.sqrt(doc.length); return weight * tf * norm;', options={}, params={}}]) computed from:", + "details": [ + { + "value": 2.8109303, + "description": "weight", + "details": [] + }, + { + "value": 2.0, + "description": "query.boost", + "details": [] + }, + { + "value": 2, + "description": "field.docCount", + "details": [] + }, + { + "value": 9, + "description": "field.sumDocFreq", + "details": [] + }, + { + "value": 9, + "description": "field.sumTotalTermFreq", + "details": [] + }, + { + "value": 1, + "description": "term.docFreq", + "details": [] + }, + { + "value": 1, + "description": "term.totalTermFreq", + "details": [] + }, + { + "value": 1.0, + "description": "doc.freq", + "details": [] + }, + { + "value": 5, + "description": "doc.length", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` + +In this optimized example: + +- The `weight_script` calculates the score of `2.8109303` (IDF + query boost, same for all documents). +- The main `script` calculates document-specific factors using the precalculated `weight` value. +- The final score is `1.2570862` (identical to the single-script approach but more efficient). + +The `weight_script` parameter name is reserved and cannot be changed. The result is always available in the `weight` variable within your main script. +{: .note} + +## Related documentation + +- [`similarity` mapping parameter]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/similarity/) \ No newline at end of file diff --git a/_ingest-pipelines/accessing-data.md b/_ingest-pipelines/accessing-data.md new file mode 100644 index 00000000..14540d03 --- /dev/null +++ b/_ingest-pipelines/accessing-data.md @@ -0,0 +1,294 @@ +--- +layout: default +title: Access data in a pipeline +nav_order: 20 +--- + +# Access data in a pipeline + +Pipeline processors have read and write access to both the `_source` field of a document and its metadata fields. How you refer to a field depends on where you refer to it: + +- In processor parameters such as `field` and `target_field`, use the field name. +- In [`script` processors]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/script/) and `if` conditions, use the `ctx` object, which represents the document being processed, for example, `ctx.user`. + +## Accessing document fields + +In processor parameters, refer to a top-level field by its name. Refer to a nested field using dot notation. + +### Example: Access a top-level field + +Given the following example document: + +```json +{ + "user": "alice" +} +``` + +You can access `user` as follows: + +```json +"field": "user" +``` + +In a script or condition, use `ctx.user`. + +### Example: Access a nested field + +Given the following example document: + +```json +{ + "user": { + "name": "alice" + } +} +``` + +You can access `user.name` as follows: + +```json +"field": "user.name" +``` + +In a script or condition, use `ctx.user.name`. If the `user` object might be missing, use the null-safe operator: `ctx.user?.name`. + +## Accessing a field in the source + +To access a field in the document `_source`, refer to the field by its name: + +```json +{ + "set": { + "field": "environment", + "value": "production" + } +} +``` + +Alternatively, you can explicitly use `_source`: + +```json +{ + "set": { + "field": "_source.environment", + "value": "production" + } +} +``` + +## Accessing metadata fields + +A document's `_source` can't contain fields whose names match metadata fields, so you can refer to metadata fields by name, in the same way as source fields. Processors can read and write the following metadata fields: + +- `_index` +- `_id` +- `_routing` +- `_version` +- `_version_type` +- `_if_seq_no` +- `_if_primary_term` + +### Example: Set `_routing` dynamically + +```json +{ + "set": { + "field": "_routing", + "value": "{% raw %}{{region}}{% endraw %}" + } +} +``` + + +## Accessing ingest metadata fields + +The `_ingest.timestamp` field represents the time at which the ingest node received the document. To persist this timestamp, use the `set` processor: + +```json +{ + "set": { + "field": "received_at", + "value": "{% raw %}{{_ingest.timestamp}}{% endraw %}" + } +} +``` + +Ingest metadata exists only while the pipeline processes the document. OpenSearch doesn't index the `_ingest` fields, so to keep a value, copy it into a document field, as shown in the preceding example. + +A document's `_source` can contain a field named `_ingest`. To access this field, use the `_source._ingest` prefix. Without the prefix, `_ingest` refers to the ingest metadata. The following processor copies the value of the `_ingest` source field into the `ingest_source` field: + +```json +{ + "set": { + "field": "ingest_source", + "value": "{% raw %}{{_source._ingest}}{% endraw %}" + } +} +``` + +## Using field values in Mustache templates + +Use Mustache templates to insert field values into processor settings. Only some processor parameters support templates; each processor's parameter table states which ones do. For more information, see [Template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). Templates refer to fields by name, without `ctx`. + +Double curly braces ({% raw %}`{{` and `}}`{% endraw %}) escape special characters in the value, such as quotation marks and backslashes, by adding a backslash before them. Triple curly braces ({% raw %}`{{{` and `}}}`{% endraw %}) insert the value without escaping. For example, if the `title` field contains `say "hi"`, then {% raw %}`{{title}}`{% endraw %} produces `say \"hi\"` and {% raw %}`{{{title}}}`{% endraw %} produces `say "hi"`. + +### Example: Combining source fields + +The following processor configuration combines the `app` and `env` fields, separated by an underscore (_), and stores the result in the `log_label` field: + +```json +{ + "set": { + "field": "log_label", + "value": "{% raw %}{{{app}}}_{{{env}}}{% endraw %}" + } +} +``` + +### Example: Generating a dynamic greeting using the `set` processor + +If a document's `user` field is set to `alice`, use the following syntax to produce the result `"greeting": "Hello, alice!"`: + +```json +{ + "set": { + "field": "greeting", + "value": "Hello, {% raw %}{{{user}}}{% endraw %}!" + } +} +``` + +## Dynamic field names + +You can use a field's value as the name of a new field: + +```json +{ + "set": { + "field": "{% raw %}{{service}}{% endraw %}", + "value": "{% raw %}{{code}}{% endraw %}" + } +} +``` + +## Example: Routing to a dynamic index based on status + +The following processor configuration sets the target index dynamically by appending `-events` to the value of the `status` field: + +```json +{ + "set": { + "field": "_index", + "value": "{% raw %}{{status}}{% endraw %}-events" + } +} +``` + +## Using `ctx` in the `script` processor + +Use the `script` processor for advanced transformations. + +### Example: Adding a field only if another is missing + +The following processor adds the `error_message` field with the value "none" only if the field is missing from the document: + +```json +{ + "script": { + "lang": "painless", + "source": "if (ctx.error_message == null) { ctx.error_message = 'none'; }" + } +} +``` + +### Example: Copying a value from one field to another + +The following processor copies the value from the `timestamp` field into a new field called `event_time`: + +```json +{ + "script": { + "lang": "painless", + "source": "ctx.event_time = ctx.timestamp;" + } +} +``` + +## Example of a complete pipeline + +The following example defines a complete ingest pipeline that sets a tagline using the `user.first` and `department` fields, extracts the `year` from the `date` field, and records the document’s ingest timestamp in the `received_at` field: + +```json +PUT _ingest/pipeline/example-pipeline +{ + "description": "Sets a tagline, extracts the year, and records the ingest time", + "processors": [ + { + "set": { + "field": "tagline", + "value": "{% raw %}{{{user.first}}} from {{{department}}}{% endraw %}" + } + }, + { + "script": { + "lang": "painless", + "source": "ctx.year = ctx.date.substring(0, 4);" + } + }, + { + "set": { + "field": "received_at", + "value": "{% raw %}{{_ingest.timestamp}}{% endraw %}" + } + } + ] +} +``` + +To test the pipeline, use the following request: + +```json +POST _ingest/pipeline/example-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "user": { + "first": "Liam" + }, + "department": "Engineering", + "date": "2024-12-03T14:05:00Z" + } + } + ] +} +``` + +The response shows the enriched document after processing, including the newly added `tagline`, extracted `year`, and the `received_at` timestamp generated by the ingest pipeline: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "user": { + "first": "Liam" + }, + "department": "Engineering", + "date": "2024-12-03T14:05:00Z", + "tagline": "Liam from Engineering", + "year": "2024", + "received_at": "2025-04-14T18:40:00.000Z" + }, + "_ingest": { + "timestamp": "2025-04-14T18:40:00.000Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/complex-conditionals.md b/_ingest-pipelines/complex-conditionals.md new file mode 100644 index 00000000..0ba7d6f3 --- /dev/null +++ b/_ingest-pipelines/complex-conditionals.md @@ -0,0 +1,582 @@ +--- +layout: default +title: Complex conditionals +parent: Conditional execution +nav_order: 50 +--- + +# Complex conditionals + +In ingest pipelines, the `if` parameter in processors can evaluate complex conditions using Painless scripts. These conditionals help fine-tune document processing, allowing advanced logic such as type checking, regular expressions, and combining multiple criteria. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +OpenSearch evaluates the condition for every document that passes through the processor, so expensive conditions slow down ingestion. Keep conditions as simple as possible. +{: .tip} + +## Writing multi-statement conditions + +A condition can contain multiple Painless statements, such as variable declarations and loops, as long as it returns a Boolean value. Because JSON strings can't contain line breaks, write the entire script on one line and separate the statements using semicolons. In OpenSearch Dashboards Dev Tools, you can instead enclose a multi-line script in triple quotation marks (`"""`). For more information, see [Using triple quotation marks in queries]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/console/#using-triple-quotation-marks-in-queries). + +The following pipeline calculates the total value of an order from its `items` array and flags orders whose total exceeds `1000` for review. Orders without an `items` field aren't flagged: + +```json +PUT _ingest/pipeline/flag_large_orders +{ + "processors": [ + { + "set": { + "field": "review_required", + "value": true, + "if": "if (ctx.items == null) { return false; } double total = 0; for (def item : ctx.items) { total += item.price * item.quantity; } return total > 1000;" + } + } + ] +} +``` +{% include copy-curl.html %} + +Test the pipeline using the following `_simulate` request: + +```json +POST _ingest/pipeline/flag_large_orders/_simulate +{ + "docs": [ + { + "_source": { + "order_id": "A-2001", + "items": [ + { "name": "Laptop stand", "price": 45.0, "quantity": 2 }, + { "name": "Monitor", "price": 329.0, "quantity": 1 } + ] + } + }, + { + "_source": { + "order_id": "A-2002", + "items": [ + { "name": "Monitor", "price": 329.0, "quantity": 4 } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The first order totals `419` and isn't flagged. The second order totals `1316`, so the `review_required` field is added: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "order_id": "A-2001", + "items": [ + { "name": "Laptop stand", "price": 45.0, "quantity": 2 }, + { "name": "Monitor", "price": 329.0, "quantity": 1 } + ] + }, + "_ingest": { + "timestamp": "2026-10-14T20:23:18.723081887Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "review_required": true, + "order_id": "A-2002", + "items": [ + { "name": "Monitor", "price": 329.0, "quantity": 4 } + ] + }, + "_ingest": { + "timestamp": "2026-10-14T20:23:18.723092429Z" + } + } + } + ] +} +``` + +## Multiple condition checks + +You can combine logical operators like `&&` (and), `||` (or), and `!` (not) to construct more complex conditions. The following pipeline tags documents as `spam` and drops them if they contain an `error_code` higher than `1000`: + +```json +PUT _ingest/pipeline/spammy_error_handler +{ + "processors": [ + { + "set": { + "field": "tags", + "value": ["spam"], + "if": "ctx.message != null && ctx.message.contains('OutOfMemoryError')" + } + }, + { + "drop": { + "if": "ctx.tags != null && ctx.tags.contains('spam') && ctx.error_code != null && ctx.error_code > 1000" + } + } + ] +} +``` +{% include copy-curl.html %} + +You can test the pipeline using the following `_simulate` request: + +```json +POST _ingest/pipeline/spammy_error_handler/_simulate +{ + "docs": [ + { "_source": { "message": "OutOfMemoryError occurred", "error_code": 1200 } }, + { "_source": { "message": "OutOfMemoryError occurred", "error_code": 800 } }, + { "_source": { "message": "All good", "error_code": 200 } } + ] +} +``` +{% include copy-curl.html %} + +The first document is dropped because it contains an `OutOfMemoryError` string and an `error_code` higher than `1000`: + +```json +{ + "docs": [ + null, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "error_code": 800, + "message": "OutOfMemoryError occurred", + "tags": [ + "spam" + ] + }, + "_ingest": { + "timestamp": "2025-04-23T10:20:10.704359884Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "error_code": 200, + "message": "All good" + }, + "_ingest": { + "timestamp": "2025-04-23T10:20:10.704369801Z" + } + } + } + ] +} +``` + +## Type-safe evaluations + +Use `instanceof` to ensure you're working with the right data types before performing operations. The following pipeline is configured to add a `processed` field set to `true` only if `message` is of type `String` and longer than `10` characters: + +```json +PUT _ingest/pipeline/string_message_check +{ + "processors": [ + { + "set": { + "field": "processed", + "value": true, + "if": "ctx.message != null && ctx.message instanceof String && ctx.message.length() > 10" + } + } + ] +} +``` +{% include copy-curl.html %} + +Test the pipeline using the following `_simulate` request: + +```json +POST _ingest/pipeline/string_message_check/_simulate +{ + "docs": [ + { "_source": { "message": "short" } }, + { "_source": { "message": "This is a longer message" } }, + { "_source": { "message": 1234567890 } } + ] +} +``` +{% include copy-curl.html %} + +Only the second document has a new field added: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "short" + }, + "_ingest": { + "timestamp": "2025-04-23T10:28:14.040115261Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "processed": true, + "message": "This is a longer message" + }, + "_ingest": { + "timestamp": "2025-04-23T10:28:14.040141469Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": 1234567890 + }, + "_ingest": { + "timestamp": "2025-04-23T10:28:14.040144844Z" + } + } + } + ] +} +``` + + +## Using regular expressions + +Painless scripting supports the `=~` operator to evaluate regular expressions. For more examples and the limits that apply to regular expressions, see [Regex conditionals]({{site.url}}{{site.baseurl}}/ingest-pipelines/regex-conditionals/). The following pipeline flags suspicious IP patterns beginning with `192.168.`: + +```json +PUT _ingest/pipeline/flag_suspicious_ips +{ + "processors": [ + { + "set": { + "field": "alert", + "value": "suspicious_ip", + "if": "ctx.ip != null && ctx.ip =~ /^192\\.168\\.\\d+\\.\\d+$/" + } + } + ] +} +``` +{% include copy-curl.html %} + +Test the pipeline using the following `_simulate` request: + +```json +POST _ingest/pipeline/flag_suspicious_ips/_simulate +{ + "docs": [ + { "_source": { "ip": "192.168.0.1" } }, + { "_source": { "ip": "10.0.0.1" } } + ] +} +``` +{% include copy-curl.html %} + +The first document has an `alert` field added: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "alert": "suspicious_ip", + "ip": "192.168.0.1" + }, + "_ingest": { + "timestamp": "2025-04-23T10:32:45.367916428Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "ip": "10.0.0.1" + }, + "_ingest": { + "timestamp": "2025-04-23T10:32:45.36793772Z" + } + } + } + ] +} +``` + +## Combining fields and null checks + +The following pipeline adds a `priority` field set to `high` if `level` is `critical` and `timestamp` is provided. The script also ensures that all fields are present and meet specific conditions before proceeding: + +```json +PUT _ingest/pipeline/critical_log_handler +{ + "processors": [ + { + "set": { + "field": "priority", + "value": "high", + "if": "ctx.level != null && ctx.level == 'critical' && ctx.timestamp != null" + } + } + ] +} +``` +{% include copy-curl.html %} + +Test the pipeline using the following `_simulate` request: + +```json +POST _ingest/pipeline/critical_log_handler/_simulate +{ + "docs": [ + { "_source": { "level": "critical", "timestamp": "2025-04-01T00:00:00Z" } }, + { "_source": { "level": "info", "timestamp": "2025-04-01T00:00:00Z" } }, + { "_source": { "level": "critical" } } + ] +} +``` +{% include copy-curl.html %} + +Only the first document has a `priority` field added: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "priority": "high", + "level": "critical", + "timestamp": "2025-04-01T00:00:00Z" + }, + "_ingest": { + "timestamp": "2025-04-23T10:39:25.46840371Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "level": "info", + "timestamp": "2025-04-01T00:00:00Z" + }, + "_ingest": { + "timestamp": "2025-04-23T10:39:25.46843021Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "level": "critical" + }, + "_ingest": { + "timestamp": "2025-04-23T10:39:25.468434835Z" + } + } + } + ] +} +``` + +## Multi-conditional processing + +The following pipeline: + +- Adds an `env` field set to `production` if it doesn't already exist. +- Adds a `severity` field set to `major` if the value in the `status` field is greater than or equal to `500`. +- Drops the document if the `env` field is set to `test` and the `message` field contains `debug`. + +```json +PUT _ingest/pipeline/advanced_log_pipeline +{ + "processors": [ + { + "set": { + "field": "env", + "value": "production", + "if": "!ctx.containsKey('env')" + } + }, + { + "set": { + "field": "severity", + "value": "major", + "if": "ctx.status != null && ctx.status >= 500" + } + }, + { + "drop": { + "if": "ctx.env == 'test' && ctx.message != null && ctx.message.contains('debug')" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the following `_simulate` request to test the pipeline: + +```json +POST _ingest/pipeline/advanced_log_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "status": 503, + "message": "Server unavailable" + } + }, + { + "_source": { + "env": "test", + "message": "debug log output" + } + }, + { + "_source": { + "status": 200, + "message": "OK" + } + } + ] +} +``` +{% include copy-curl.html %} + +In the response, note that the first document has the `env: production` and `severity: major` fields added. The second document is dropped. The third document has an `env: production` field added: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "severity": "major", + "message": "Server unavailable", + "env": "production", + "status": 503 + }, + "_ingest": { + "timestamp": "2025-04-23T10:51:46.795026554Z" + } + } + }, + null, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "OK", + "env": "production", + "status": 200 + }, + "_ingest": { + "timestamp": "2025-04-23T10:51:46.795048304Z" + } + } + } + ] +} +``` + +## Null-safe notation + +Use null-safe navigation notation (`?.`) to check whether the field is `null`. Note that this notation can return `null` silently; therefore, we recommend first checking whether the returned value is `null` and then using operations like `.contains` or `==`. + +Unsafe syntax: + +``` +"if": "ctx.message?.contains('debug')" +``` + +If the `message` field does not exist in the document, this request returns a `null_pointer_exception` with the message `Cannot invoke "Object.getClass()" because "value" is null`. + +Safe syntax: + +``` +"if": "ctx.message != null && ctx.message.contains('debug')" +``` + +## Debugging conditions + +To check how each condition was evaluated, run the [Simulate Pipeline API]({{site.url}}{{site.baseurl}}/ingest-pipelines/simulate-ingest/) with the `verbose` parameter set to `true`. For each processor, the response contains a `status` field. If a processor's condition evaluates to `false`, the `status` is `skipped`, and the `if` object shows the condition and its result. + +The following request simulates a processor whose condition evaluates to `false` for the provided document: + +```json +POST _ingest/pipeline/_simulate?verbose=true +{ + "pipeline": { + "processors": [ + { + "set": { + "field": "severity", + "value": "major", + "if": "ctx.status != null && ctx.status >= 500" + } + } + ] + }, + "docs": [ + { "_source": { "status": 200 } } + ] +} +``` +{% include copy-curl.html %} + +The response shows that the `set` processor was skipped because the condition returned `false`: + +```json +{ + "docs": [ + { + "processor_results": [ + { + "processor_type": "set", + "status": "skipped", + "if": { + "condition": "ctx.status != null && ctx.status >= 500", + "result": false + } + } + ] + } + ] +} +``` diff --git a/_ingest-pipelines/conditional-execution.md b/_ingest-pipelines/conditional-execution.md new file mode 100644 index 00000000..aa01b2cc --- /dev/null +++ b/_ingest-pipelines/conditional-execution.md @@ -0,0 +1,248 @@ +--- +layout: default +title: Conditional execution +has_children: true +nav_order: 40 +--- + +# Conditional execution + +In ingest pipelines, you can control whether a processor runs by using the optional `if` parameter. This allows for conditional execution of processors based on the incoming document contents. The condition is written as a Painless script and evaluated against the document context (`ctx`). For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +## Basic conditional execution + +Each processor can include an `if` clause. If the condition evaluates to `true`, the processor runs; otherwise, it's skipped. + +In the condition, `ctx` is read-only. A condition can read document fields but can't add, change, or remove them. To modify a document conditionally, put the modification in the processor and use the condition only to decide whether the processor runs. + +### Example: Drop debug-level logs + +The following pipeline drops any document in which the `log_level` field is equal to `debug`: + +```json +PUT _ingest/pipeline/drop_debug_logs +{ + "processors": [ + { + "drop": { + "if": "ctx.log_level == 'debug'" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Example index request + +```json +POST logs/_doc/1?pipeline=drop_debug_logs +{ + "message": "User logged in", + "log_level": "debug" +} +``` +{% include copy-curl.html %} + +This document is dropped because the condition evaluates to `true`: + +```json +{ + "_index": "logs", + "_id": "1", + "_version": -3, + "result": "noop", + "_shards": { + "total": 0, + "successful": 0, + "failed": 0 + } +} +``` + +## Null-safe field checks when using nested fields + +When working with nested fields, it's important to avoid null pointer exceptions. Use the null-safe `?.` operator in Painless scripts. + +### Example: Drop documents based on a nested field + +The following drop processor executes only if the nested `app.env` field exists and equals `debug`: + +```json +PUT _ingest/pipeline/drop_debug_env +{ + "processors": [ + { + "drop": { + "if": "ctx.app?.env == 'debug'" + } + } + ] +} +``` +{% include copy-curl.html %} + +If the null-safe `?.` operator is not configured, indexing any document that doesn't contain the `app` object triggers the following null pointer exception: + +```json +{ + "error": "IngestProcessorException[ScriptException[runtime error]; nested: NullPointerException[Cannot invoke \"Object.getClass()\" because \"callArgs[0]\" is null];]", + "status": 400 +} +``` + +## Handling flattened fields + +If your document has a flattened field, for example, `"app.env": "debug"`, use the [`dot_expander`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/dot-expander/) processor to convert it into a nested structure: + +```json +PUT _ingest/pipeline/drop_debug_env +{ + "processors": [ + { + "dot_expander": { + "field": "app.env" + } + }, + { + "drop": { + "if": "ctx.app?.env == 'debug'" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Safe method calls in conditions + +The `?.` operator returns `null` if the object is `null`, and the `==` operator handles `null` values, so conditions such as `ctx.app?.env == 'debug'` are null safe. However, calling a method on a `null` value causes a null pointer exception. For example, `ctx.app?.env.equalsIgnoreCase('debug')` fails for documents that don't contain the `app.env` field because `ctx.app?.env` returns `null`. + +To make a method call null safe, call the method on a constant, which is never `null`, and pass the field as the argument: + +```json +{ + "drop": { + "if": "'debug'.equalsIgnoreCase(ctx.app?.env)" + } +} +``` + +If no method can be called on a constant, check for `null` explicitly before calling the method: + +```json +{ + "drop": { + "if": "ctx.app?.env != null && ctx.app.env.contains('debug')" + } +} +``` + +## Full example: Multi-step conditional pipeline + +The following ingest pipeline uses three processors: + +1. `set`: If no value is provided in the `user` field, sets the `user` field to `guest`. +2. `set`: If the `status_code` is provided and is greater than or equal to `400`, sets the `error` field to `true`. +3. `drop`: If the `app.env` field is equal to `debug`, drops the entire document. + +```json +PUT _ingest/pipeline/logs_processing +{ + "processors": [ + { + "set": { + "field": "user", + "value": "guest", + "if": "ctx.user == null" + } + }, + { + "set": { + "field": "error", + "value": true, + "if": "ctx.status_code != null && ctx.status_code >= 400" + } + }, + { + "drop": { + "if": "ctx.app?.env == 'debug'" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Simulate the pipeline + +The following simulation request applies the conditional logic to three documents: + +```json +POST _ingest/pipeline/logs_processing/_simulate +{ + "docs": [ + { + "_source": { + "message": "Successful login", + "status_code": 200 + } + }, + { + "_source": { + "message": "Database error", + "status_code": 500, + "user": "alice" + } + }, + { + "_source": { + "message": "Debug mode trace", + "app": { "env": "debug" } + } + } + ] +} +``` +{% include copy-curl.html %} + +The response demonstrates how the processors respond based on each condition: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "status_code": 200, + "message": "Successful login", + "user": "guest" + }, + "_ingest": { + "timestamp": "2025-04-16T14:04:35.923159885Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "status_code": 500, + "message": "Database error", + "error": true, + "user": "alice" + }, + "_ingest": { + "timestamp": "2025-04-16T14:04:35.923198551Z" + } + } + }, + null + ] +} +``` + + diff --git a/_ingest-pipelines/conditional-pipeline-processor.md b/_ingest-pipelines/conditional-pipeline-processor.md new file mode 100644 index 00000000..6d3ffc7c --- /dev/null +++ b/_ingest-pipelines/conditional-pipeline-processor.md @@ -0,0 +1,272 @@ +--- +layout: default +title: Conditionals with the pipeline processor +parent: Conditional execution +nav_order: 60 +--- + +# Conditionals with the pipeline processor + +The `pipeline` processor in ingest pipelines allows conditional execution of different sub-pipelines based on document contents. This provides powerful flexibility when different types of documents require separate processing logic. You can use the `if` parameter in the `pipeline` processor to direct documents to different pipelines based on field values, data types, or content structure. Each pipeline can then apply its own set of processors independently. This approach keeps your pipelines modular and maintainable by applying logic only where it's relevant. + +## Example: Route logs by service + +The following example demonstrates how to route logs to different sub-pipelines depending on the `service.name` field in the document. + +Create the first pipeline named `webapp_logs`: + +```json +PUT _ingest/pipeline/webapp_logs +{ + "processors": [ + { "set": { "field": "log_type", "value": "webapp" } } + ] +} +``` +{% include copy-curl.html %} + +Create the second pipeline named `api_logs`: + +```json +PUT _ingest/pipeline/api_logs +{ + "processors": [ + { "set": { "field": "log_type", "value": "api" } } + ] +} +``` +{% include copy-curl.html %} + +Create the main routing pipeline named `service_router`, which routes the documents to the corresponding pipelines based on `service.name`: + +```json +PUT _ingest/pipeline/service_router +{ + "processors": [ + { + "pipeline": { + "name": "webapp_logs", + "if": "ctx.service?.name == 'webapp'" + } + }, + { + "pipeline": { + "name": "api_logs", + "if": "ctx.service?.name == 'api'" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the following request to simulate the pipelines: + +```json +POST _ingest/pipeline/service_router/_simulate +{ + "docs": [ + { "_source": { "service": { "name": "webapp" }, "message": "Homepage loaded" } }, + { "_source": { "service": { "name": "api" }, "message": "GET /v1/users" } }, + { "_source": { "service": { "name": "worker" }, "message": "Task started" } } + ] +} +``` +{% include copy-curl.html %} + +The response confirms that the first document was processed by the `webapp_logs` pipeline and the second document was processed by the `api_logs` pipeline. The third document remains unchanged because it doesn't match any conditions: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "log_type": "webapp", + "message": "Homepage loaded", + "service": { + "name": "webapp" + } + }, + "_ingest": { + "timestamp": "2025-04-24T10:54:12.555447087Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "log_type": "api", + "message": "GET /v1/users", + "service": { + "name": "api" + } + }, + "_ingest": { + "timestamp": "2025-04-24T10:54:12.55548442Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "Task started", + "service": { + "name": "worker" + } + }, + "_ingest": { + "timestamp": "2025-04-24T10:54:12.555490754Z" + } + } + } + ] +} +``` + +### Rejecting unmatched documents + +In the preceding example, documents that don't match any condition are indexed without processing. To reject these documents, add a [`fail` processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/fail/) whose condition matches when none of the other conditions do: + +```json +PUT _ingest/pipeline/service_router +{ + "processors": [ + { + "pipeline": { + "name": "webapp_logs", + "if": "ctx.service?.name == 'webapp'" + } + }, + { + "pipeline": { + "name": "api_logs", + "if": "ctx.service?.name == 'api'" + } + }, + { + "fail": { + "if": "!['webapp', 'api'].contains(ctx.service?.name)", + "message": "The service.name field must be webapp or api. Received: {% raw %}{{service.name}}{% endraw %}" + } + } + ] +} +``` +{% include copy-curl.html %} + +When you simulate the pipeline using the same documents as in the preceding example, the first two documents are processed as before. The third document fails with the message `The service.name field must be webapp or api. Received: worker`, and OpenSearch doesn't index it. If a document has no `service.name` field, the message ends with an empty value. + +### Applying the router to all indexing requests + +To route every document indexed into an index without specifying the `pipeline` parameter in each request, set the routing pipeline as the index's default pipeline. To apply it to all indexes that match a pattern, set `index.default_pipeline` in an [index template]({{site.url}}{{site.baseurl}}/im-plugin/index-templates/): + +```json +PUT _index_template/service_logs +{ + "index_patterns": ["service-logs-*"], + "template": { + "settings": { + "index.default_pipeline": "service_router" + } + } +} +``` +{% include copy-curl.html %} + +For more information, see [Applying a pipeline to documents]({{site.url}}{{site.baseurl}}/ingest-pipelines/#applying-a-pipeline-to-documents). + +## Example: Type-specific processing + +You can also use the pipeline processor to apply type-specific pipelines. The following pipeline directs logs to a `numeric_handler` if the `code` field is a number and to a `string_handler` if it is of type `String`. + +Create the first pipeline named `numeric_handler`: + +```json +PUT _ingest/pipeline/numeric_handler +{ + "processors": [ + { "set": { "field": "code_type", "value": "numeric" } } + ] +} +``` +{% include copy-curl.html %} + +Create the second pipeline named `string_handler`: + +```json +PUT _ingest/pipeline/string_handler +{ + "processors": [ + { "set": { "field": "code_type", "value": "string" } } + ] +} +``` +{% include copy-curl.html %} + +Create the main routing pipeline named `type_router`, which routes the documents to the corresponding pipelines based on the `code` field: + +```json +PUT _ingest/pipeline/type_router +{ + "processors": [ + { + "pipeline": { + "name": "numeric_handler", + "if": "ctx.code instanceof Integer || ctx.code instanceof Long || ctx.code instanceof Double" + } + }, + { + "pipeline": { + "name": "string_handler", + "if": "ctx.code instanceof String" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the following request to simulate the pipelines: + +```json +POST _ingest/pipeline/type_router/_simulate +{ + "docs": [ + { "_source": { "code": 404 } }, + { "_source": { "code": "ERR_NOT_FOUND" } } + ] +} +``` +{% include copy-curl.html %} + +The returned documents have the new field `code_type` added by individual sub-pipelines: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "code": 404, + "code_type": "numeric" + } + } + }, + { + "doc": { + "_source": { + "code": "ERR_NOT_FOUND", + "code_type": "string" + } + } + } + ] +} +``` \ No newline at end of file diff --git a/_ingest-pipelines/create-ingest.md b/_ingest-pipelines/create-ingest.md index 540d3364..d62fd025 100644 --- a/_ingest-pipelines/create-ingest.md +++ b/_ingest-pipelines/create-ingest.md @@ -1,28 +1,56 @@ --- layout: default -title: Create pipeline +title: Create or update pipeline nav_order: 10 redirect_from: - /opensearch/rest-api/ingest-apis/create-update-ingest/ - /api-reference/ingest-apis/create-ingest/ + - /api-reference/ingest-apis/create-update-ingest/ --- -# Create pipeline +# Create or Update Pipeline API **Introduced 1.0** {: .label .label-purple } -Use the create pipeline API operation to create or update pipelines in OpenSearch. Note that the pipeline requires you to define at least one processor that specifies how to change the documents. +The Create or Update Pipeline API creates an ingest pipeline or replaces the definition of an existing pipeline. The request body must contain the `processors` field. When you update an existing pipeline, the new definition replaces the old one and applies to indexing requests immediately. -## Path and HTTP method - -Replace `<pipeline-id>` with your pipeline ID: +## Endpoints ```json -PUT _ingest/pipeline/<pipeline-id> +PUT /_ingest/pipeline/{pipeline-id} ``` -#### Example request -Here is an example in JSON format that creates an ingest pipeline with two `set` processors and an `uppercase` processor. The first `set` processor sets the `grad_year` to `2023`, and the second `set` processor sets `graduated` to `true`. The `uppercase` processor converts the `name` field to uppercase. +## Path parameters + +The following table lists the available path parameters. + +Parameter | Required | Data type | Description +:--- | :--- | :--- | :--- +`pipeline-id` | Required | String | The ID of the pipeline to create or update. Can be at most 512 bytes long when UTF-8 encoded. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time to wait for a response. Default is `30s`. + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`processors` | Array of objects | The processors that transform documents, in the order in which they run. For a list of processors, see [Ingest processors]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/). Required. +`description` | String | A description of the pipeline. Optional. +`on_failure` | Array of objects | Processors to run if a processor in the pipeline fails. For more information, see [Handling failures at the pipeline level]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/#handling-failures-at-the-pipeline-level). Optional. +`version` | Integer | A version number for the pipeline. OpenSearch doesn't use the version. External systems can use it to manage pipelines. For more information, see [Pipeline versioning](#pipeline-versioning). Optional. + +## Example request + +The following request creates a pipeline with two `set` processors and an `uppercase` processor. The first `set` processor sets `grad_year` to `2023`, the second `set` processor sets `graduated` to `true`, and the `uppercase` processor converts the `name` field to uppercase: ```json PUT _ingest/pipeline/my-pipeline @@ -53,29 +81,91 @@ PUT _ingest/pipeline/my-pipeline ``` {% include copy-curl.html %} -To learn more about error handling, see [Handling pipeline failures]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/pipeline-failures/). +## Example response -## Request body fields +```json +{ + "acknowledged": true +} +``` -The following table lists the request body fields used to create or update a pipeline. +## Using the pipeline -Parameter | Required | Type | Description -:--- | :--- | :--- | :--- -`processors` | Required | Array of processor objects | An array of processors, each of which transforms documents. Processors are run sequentially in the order specified. -`description` | Optional | String | A description of your ingest pipeline. +To index a document through the pipeline, specify the pipeline name in the `pipeline` query parameter: -## Path parameters +```json +POST students/_doc/1?pipeline=my-pipeline +{ + "name": "john doe" +} +``` +{% include copy-curl.html %} -Parameter | Required | Type | Description -:--- | :--- | :--- | :--- -`pipeline-id` | Required | String | The unique identifier, or pipeline ID, assigned to the ingest pipeline. +To verify the pipeline processed the document, retrieve it: -## Query parameters +```json +GET students/_doc/1 +``` +{% include copy-curl.html %} -Parameter | Required | Type | Description -:--- | :--- | :--- | :--- -`cluster_manager_timeout` | Optional | Time | Period to wait for a connection to the cluster manager node. Defaults to 30 seconds. -`timeout` | Optional | Time | Period to wait for a response. Defaults to 30 seconds. +The response shows that the pipeline set `grad_year` and `graduated` and converted `name` to uppercase: + +```json +{ + "_index": "students", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "graduated": true, + "name": "JOHN DOE", + "grad_year": 2023 + } +} +``` + +For more information about handling processor errors, see [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). + +## Pipeline versioning + +If you manage pipelines using deployment scripts or configuration management tools, you can record which revision of a pipeline is installed on a cluster. For example, a deployment tool can compare the installed version with the version in source control and update the pipeline only if they differ. To record the revision, specify an integer in the `version` field when you create or update the pipeline: + +```json +PUT _ingest/pipeline/students-pipeline +{ + "description": "Processes student data", + "version": 2, + "processors": [ + { + "uppercase": { + "field": "name" + } + } + ] +} +``` +{% include copy-curl.html %} + +To check the current version of the pipeline, filter the [Get Pipeline API]({{site.url}}{{site.baseurl}}/ingest-pipelines/get-ingest/) response by the `version` field: + +```json +GET _ingest/pipeline/students-pipeline?filter_path=*.version +``` +{% include copy-curl.html %} + +The response contains the pipeline version: + +```json +{ + "students-pipeline": { + "version": 2 + } +} +``` + +Updating a pipeline replaces its entire definition. To remove the version number, update the pipeline without specifying the `version` field. ## Template snippets @@ -83,19 +173,247 @@ Some processor parameters support [Mustache](https://mustache.github.io/) templa #### Example: `set` ingest processor using Mustache template snippet -The following example sets the field `{% raw %}{{{role}}}{% endraw %}` with a value `{% raw %}{{{tenure}}}{% endraw %}`: +Building on the student data pipeline shown in the [example request](#example-request), the following example uses Mustache template snippets to dynamically set field names and values. Instead of hardcoding the field name and value, the processor reads them from the document itself. In this example, the field name is taken from the document's `{% raw %}{{{department}}}{% endraw %}` field and the value is taken from the `{% raw %}{{{advisor}}}{% endraw %}` field: ```json PUT _ingest/pipeline/my-pipeline { - "processors": [ + "processors": [ { "set": { - "field": "{% raw %}{{{role}}}{% endraw %}", - "value": "{% raw %}{{{tenure}}}{% endraw %}" - } + "field": "{% raw %}{{{department}}}{% endraw %}", + "value": "{% raw %}{{{advisor}}}{% endraw %}" + } } ] } ``` {% include copy-curl.html %} + +To test this pipeline, index a document that contains the `department` and `advisor` fields: + +```json +POST students/_doc/2?pipeline=my-pipeline +{ + "name": "Jane Smith", + "department": "computer_science", + "advisor": "Dr. Smith" +} +``` +{% include copy-curl.html %} + +Retrieve the document to verify the result: + +```json +GET students/_doc/2 +``` +{% include copy-curl.html %} + +The response shows that the pipeline dynamically created a `computer_science` field with the value `Dr. Smith`: + +```json +{ + "_index": "students", + "_id": "2", + "_version": 1, + "_seq_no": 1, + "_primary_term": 1, + "found": true, + "_source": { + "advisor": "Dr. Smith", + "computer_science": "Dr. Smith", + "name": "Jane Smith", + "department": "computer_science" + } +} +``` + +## Using processor tags for monitoring and debugging + +When monitoring ingest pipeline performance using the `GET /_nodes/stats/ingest` API, processors without tags appear with generic names in the statistics output. This makes it difficult to identify which specific processor stage might be causing performance bottlenecks in complex pipelines. All ingest processors support an optional `tag` parameter that assigns a meaningful identifier to each processor. This parameter is useful for monitoring pipeline performance and debugging issues in production environments. + +The following examples demonstrate the difference between using processors with and without tags when monitoring pipeline performance. + +Create a pipeline without processor tags: + +```json +PUT _ingest/pipeline/log-processing-without-tags +{ + "description": "Process web server logs without processor tags", + "processors": [ + { + "grok": { + "field": "message", + "patterns": ["%{COMMONAPACHELOG}"] + } + }, + { + "date": { + "field": "timestamp", + "formats": ["dd/MMM/yyyy:HH:mm:ss Z"] + } + }, + { + "convert": { + "field": "response", + "type": "integer" + } + } + ] +} +``` +{% include copy-curl.html %} + +Create a pipeline with processor tags: + +```json +PUT _ingest/pipeline/log-processing-with-tags +{ + "description": "Process web server logs with processor tags for monitoring", + "processors": [ + { + "grok": { + "field": "message", + "patterns": ["%{COMMONAPACHELOG}"], + "tag": "parse-apache-log" + } + }, + { + "date": { + "field": "timestamp", + "formats": ["dd/MMM/yyyy:HH:mm:ss Z"], + "tag": "parse-timestamp" + } + }, + { + "convert": { + "field": "response", + "type": "integer", + "tag": "convert-response-code" + } + } + ] +} +``` +{% include copy-curl.html %} + +Test both pipelines with sample log data: + +```json +POST logs-without-tags/_doc?pipeline=log-processing-without-tags +{ + "message": "192.168.1.100 - - [30/Oct/2023:14:23:45 +0000] \"POST /api/users HTTP/1.1\" 201 512" +} +``` +{% include copy-curl.html %} + +```json +POST logs-with-tags/_doc?pipeline=log-processing-with-tags +{ + "message": "192.168.1.100 - - [30/Oct/2023:14:23:45 +0000] \"POST /api/users HTTP/1.1\" 201 512" +} +``` +{% include copy-curl.html %} + +Check the ingest statistics to see the difference in processor identification: + +```json +GET _nodes/stats/ingest +``` +{% include copy-curl.html %} + +The pipeline without tags contains generic processor names: + +```json +"log-processing-without-tags": { + "count": 1, + "time_in_millis": 1, + "current": 0, + "failed": 0, + "processors": [ + { + "grok": { + "type": "grok", + "stats": { + "count": 1, + "time_in_millis": 0, + "current": 0, + "failed": 0 + } + } + }, + { + "date": { + "type": "date", + "stats": { + "count": 1, + "time_in_millis": 1, + "current": 0, + "failed": 0 + } + } + }, + { + "convert": { + "type": "convert", + "stats": { + "count": 1, + "time_in_millis": 0, + "current": 0, + "failed": 0 + } + } + } + ] +} +``` + +The pipeline with tags contains descriptive processor names: + +```json +"log-processing-with-tags": { + "count": 1, + "time_in_millis": 0, + "current": 0, + "failed": 0, + "processors": [ + { + "grok:parse-apache-log": { + "type": "grok", + "stats": { + "count": 1, + "time_in_millis": 0, + "current": 0, + "failed": 0 + } + } + }, + { + "date:parse-timestamp": { + "type": "date", + "stats": { + "count": 1, + "time_in_millis": 0, + "current": 0, + "failed": 0 + } + } + }, + { + "convert:convert-response-code": { + "type": "convert", + "stats": { + "count": 1, + "time_in_millis": 0, + "current": 0, + "failed": 0 + } + } + } + ] +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/ingest/pipeline/put`. diff --git a/_ingest-pipelines/delete-ingest.md b/_ingest-pipelines/delete-ingest.md index 0eb864f4..97cefbf4 100644 --- a/_ingest-pipelines/delete-ingest.md +++ b/_ingest-pipelines/delete-ingest.md @@ -7,22 +7,61 @@ redirect_from: - /api-reference/ingest-apis/delete-ingest/ --- -# Delete pipeline +# Delete Pipeline API **Introduced 1.0** {: .label .label-purple } -Use the following request to delete a pipeline. +The Delete Pipeline API deletes one or more ingest pipelines. If an index uses a deleted pipeline as its default or final pipeline, indexing requests to that index fail until you update the index settings. -To delete a specific pipeline, pass the pipeline ID as a parameter: +## Endpoints ```json -DELETE /_ingest/pipeline/<pipeline-id> +DELETE /_ingest/pipeline/{pipeline-id} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Required | Data type | Description +:--- | :--- | :--- | :--- +`pipeline-id` | Required | String | The ID of the pipeline to delete. Supports wildcard expressions, for example, `logs-*`. To delete all pipelines in the cluster, use `*`. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. +`timeout` | Time | The amount of time to wait for a response. Default is `30s`. + +## Example request + +The following request deletes the `my-pipeline` pipeline: + +```json +DELETE /_ingest/pipeline/my-pipeline ``` {% include copy-curl.html %} -To delete all pipelines in a cluster, use the wildcard character (`*`): +The following request deletes all pipelines whose IDs start with `logs-`: ```json -DELETE /_ingest/pipeline/* +DELETE /_ingest/pipeline/logs-* ``` {% include copy-curl.html %} + +## Example response + +```json +{ + "acknowledged": true +} +``` + +If no pipeline matches the specified ID, the API returns a `404` error. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/ingest/pipeline/delete`. diff --git a/_ingest-pipelines/get-ingest.md b/_ingest-pipelines/get-ingest.md index 9fd5279e..f05dff5b 100644 --- a/_ingest-pipelines/get-ingest.md +++ b/_ingest-pipelines/get-ingest.md @@ -7,31 +7,61 @@ redirect_from: - /api-reference/ingest-apis/get-ingest/ --- -# Get pipeline +# Get Pipeline API **Introduced 1.0** {: .label .label-purple } -Use the get ingest pipeline API operation to retrieve all the information about the pipeline. +The Get Pipeline API returns the definitions of one or more ingest pipelines. -## Retrieving information about all pipelines - -The following example request returns information about all ingest pipelines: +## Endpoints ```json -GET _ingest/pipeline/ +GET /_ingest/pipeline +GET /_ingest/pipeline/{pipeline-id} +``` + +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`pipeline-id` | String | A comma-separated list of IDs of the pipelines to retrieve. Supports wildcard expressions. If not specified, the API returns all pipelines in the cluster. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`cluster_manager_timeout` | Time | The amount of time to wait for a connection to the cluster manager node. Default is `30s`. + +## Example request + +The following request returns the definition of the `my-pipeline` pipeline: + +```json +GET /_ingest/pipeline/my-pipeline ``` {% include copy-curl.html %} -## Retrieving information about a specific pipeline - -The following example request returns information about a specific pipeline, which for this example is `my-pipeline`: +The following request returns the definitions of all pipelines whose IDs start with `logs-` and of the `orders-pipeline` pipeline: ```json -GET _ingest/pipeline/my-pipeline +GET /_ingest/pipeline/logs-*,orders-pipeline ``` {% include copy-curl.html %} -The response contains the pipeline information: +To retrieve only the version of a pipeline, filter the response using the `filter_path` query parameter. For more information, see [Pipeline versioning]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#pipeline-versioning). + +```json +GET /_ingest/pipeline/my-pipeline?filter_path=*.version +``` +{% include copy-curl.html %} + +## Example response + +The response contains the definition of each requested pipeline, keyed by pipeline ID: ```json { @@ -61,3 +91,20 @@ The response contains the pipeline information: } } ``` + +If no pipeline matches the specified ID, the API returns an empty object and a `404` status code. + +## Response body fields + +The response contains one object for each returned pipeline, named after the pipeline ID. Each pipeline object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`description` | String | The pipeline description. Returned only if the pipeline has a description. +`version` | Integer | The pipeline version. Returned only if the pipeline has a version. +`processors` | Array of objects | The processors in the pipeline, in the order in which they run. +`on_failure` | Array of objects | The processors that run if a processor in the pipeline fails. Returned only if the pipeline defines pipeline-level failure handling. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/ingest/pipeline/get`. diff --git a/_ingest-pipelines/index.md b/_ingest-pipelines/index.md index 8d1ed8d7..5dd1e667 100644 --- a/_ingest-pipelines/index.md +++ b/_ingest-pipelines/index.md @@ -12,44 +12,238 @@ redirect_from: # Ingest pipelines -An _ingest pipeline_ is a sequence of _processors_ that are applied to documents as they are ingested into an index. Each [processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/) in a pipeline performs a specific task, such as filtering, transforming, or enriching data. +An _ingest pipeline_ is a sequence of [processors]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/) that are applied to documents as they are ingested into an index. Each processor performs a specific task, such as filtering, transforming, or enriching data. Processors run in the order in which they're listed, and each processor receives the output of the previous one. The modified documents appear in your index after all processors run. -Processors are customizable tasks that run in a sequential order as they appear in the request body. This order is important, as each processor depends on the output of the previous processor. The modified documents appear in your index after the processors are applied. +For example, a web server log line such as `203.0.113.24 GET /cart/checkout 200` arrives as a single string. A pipeline can split it into separate `client_ip`, `method`, `path`, and `status` fields so that you can search, filter, and aggregate on each one. The [example](#example-parsing-web-server-logs) on this page builds this pipeline. -Ingest pipelines can only be managed using [ingest API operations]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/index/). -{: .note} +## Ingest pipelines compared to Data Prepper + +Ingest pipelines run on the nodes of your OpenSearch cluster and process each document as it's indexed. [Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) runs as a separate service outside the cluster and sends processed data to OpenSearch. + +Use ingest pipelines for lightweight transformations of individual documents, such as parsing fields or generating vector embeddings using a model registered in OpenSearch. Use Data Prepper for large data volumes, data from multiple sources, or processing that spans multiple documents, such as aggregating events. Moving processing to Data Prepper also removes the processing load from your cluster. ## Prerequisites -The following are prerequisites for using OpenSearch ingest pipelines: +The following are prerequisites for using ingest pipelines: -- When using ingestion in a production environment, your cluster should contain at least one node with the node roles permission set to `ingest`. For information about setting up node roles within a cluster, see [Cluster Formation]({{site.url}}{{site.baseurl}}/opensearch/cluster/). -- If the OpenSearch Security plugin is enabled, you must have the `cluster_manage_pipelines` permission to manage ingest pipelines. +- At least one node with the `ingest` role. By default, every node has this role, so no setup is required. +- If the OpenSearch Security plugin is enabled, you must have permissions to manage ingest pipelines, for example, through the `cluster_manage_pipelines` action group. For more information, see [Ingest APIs]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/index/#required-permissions). -## Define a pipeline +In a production environment, you can dedicate specific nodes to ingest processing by assigning the `ingest` role only to those nodes in the `node.roles` setting. For more information, see [Cluster formation]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/). +{: .tip} -A _pipeline definition_ describes the sequence of an ingest pipeline and can be written in JSON format. An ingest pipeline consists of the following: +## Defining a pipeline + +To define a pipeline, list the processors to run in the `processors` array, in the order in which they should run. Optionally, describe the pipeline in the `description` field. + +Each processor is an object whose key is the processor type and whose value contains the processor's parameters. The following pipeline definition contains two processors. The `lowercase` processor converts the `category` field to lowercase, and then the `set` processor adds an `in_stock` field with the value `true`: ```json { - "description" : "..." - "processors" : [...] + "description": "Normalizes product data", + "processors": [ + { + "lowercase": { + "field": "category" + } + }, + { + "set": { + "field": "in_stock", + "value": true + } + } + ] } ``` -#### Request body fields +Each processor type has its own parameters. For the parameters of each processor, see [Ingest processors]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/). -Field | Required | Type | Description -:--- | :--- | :--- | :--- -`processors` | Required | Array of processor objects | A component that performs a specific data processing task as the data is being ingested into OpenSearch. -`description` | Optional | String | A description of the ingest pipeline. +A pipeline definition can also include the following optional fields: -## Next steps +- `version`: A version number that you can use to track changes to the pipeline. For more information, see [Pipeline versioning]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#pipeline-versioning). +- `on_failure`: Processors to run if a processor in the pipeline fails and doesn't handle the failure itself. For more information, see [Handling failures at the pipeline level]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/#handling-failures-at-the-pipeline-level). -Learn how to: +## Example: Parsing web server logs -- [Create a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/). -- [Test a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/simulate-ingest/). -- [Retrieve information about a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/get-ingest/). -- [Delete a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/delete-ingest/). -- [Use ingest processors in OpenSearch]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/) \ No newline at end of file +The following example creates a pipeline that parses web server log lines into separate fields, tests it, and then uses it to index a document. + +Create a pipeline named `parse-web-logs`. The `dissect` processor splits the `message` field into four fields, the `convert` processor changes `status` to an integer, and the `remove` processor deletes the original `message` field. In the `dissect` pattern, each `%{name}` captures the text up to the next space and stores it in a field with that name: + +```json +PUT _ingest/pipeline/parse-web-logs +{ + "description": "Parses web server log lines", + "processors": [ + { + "dissect": { + "field": "message", + "pattern": "%{client_ip} %{method} %{path} %{status}" + } + }, + { + "convert": { + "field": "status", + "type": "integer" + } + }, + { + "remove": { + "field": "message" + } + } + ] +} +``` +{% include copy-curl.html %} + +Test the pipeline on a sample document without indexing it: + +```json +POST _ingest/pipeline/parse-web-logs/_simulate +{ + "docs": [ + { + "_source": { + "message": "203.0.113.24 GET /cart/checkout 200" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows the document as it would be indexed. The `message` field is gone, the log line is split into four fields, and `status` is now the number `200` instead of a string: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "path": "/cart/checkout", + "client_ip": "203.0.113.24", + "method": "GET", + "status": 200 + }, + "_ingest": { + "timestamp": "2026-10-14T21:15:18.025620512Z" + } + } + } + ] +} +``` + +### Applying a pipeline to documents + +To process a document using a pipeline, specify the pipeline ID in the `pipeline` query parameter of an indexing request. The [Index Document]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index-document/), [Bulk]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/), and [Update by Query]({{site.url}}{{site.baseurl}}/api-reference/document-apis/update-by-query/) APIs support this parameter. For the [Reindex]({{site.url}}{{site.baseurl}}/api-reference/document-apis/reindex/) API, specify the pipeline in the `dest.pipeline` request body field. + +The following request indexes a document using the `parse-web-logs` pipeline: + +```json +PUT web-logs/_doc/1?pipeline=parse-web-logs +{ + "message": "203.0.113.24 GET /cart/checkout 200" +} +``` +{% include copy-curl.html %} + +To verify the result, retrieve the document: + +```json +GET web-logs/_doc/1 +``` +{% include copy-curl.html %} + +The stored document contains the parsed fields: + +```json +{ + "_index": "web-logs", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "path": "/cart/checkout", + "method": "GET", + "client_ip": "203.0.113.24", + "status": 200 + } +} +``` + +You can also configure pipelines that run automatically for every document in an index, using the following index settings: + +- `index.default_pipeline`: The pipeline that runs if the indexing request doesn't specify a `pipeline` parameter. To skip the default pipeline for a request, set `pipeline` to `_none`. +- `index.final_pipeline`: The pipeline that runs after the request pipeline or default pipeline. The final pipeline always runs, even if the request sets `pipeline` to `_none`. Use a final pipeline for processing that every document must receive, such as adding an ingest timestamp, regardless of which pipeline the request specifies. A final pipeline can't change the document's target index; if it changes `_index`, the document fails. + +To try the final pipeline setting, first create a pipeline named `add-ingest-time` that records when each document was ingested. The {% raw %}`{{_ingest.timestamp}}`{% endraw %} template inserts the time at which OpenSearch received the document. For more information about templates and metadata, see [Access data in a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/accessing-data/): + +```json +PUT _ingest/pipeline/add-ingest-time +{ + "processors": [ + { + "set": { + "field": "ingested_at", + "value": "{% raw %}{{_ingest.timestamp}}{% endraw %}" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following request creates an index named `web-logs-v2` that runs the `parse-web-logs` pipeline by default and the `add-ingest-time` pipeline for every document: + +```json +PUT web-logs-v2 +{ + "settings": { + "index.default_pipeline": "parse-web-logs", + "index.final_pipeline": "add-ingest-time" + } +} +``` +{% include copy-curl.html %} + +For more information about these settings, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). + +## Common uses for ingest pipelines + +The following table lists common tasks and the processors that perform them. For a complete list, see [Ingest processors]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/). + +Task | Processors +:--- | :--- +Parse log lines and other unstructured text into fields | [`grok`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/grok/), [`dissect`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/dissect/), [`kv`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/kv/), [`csv`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/csv/) +Add, rename, copy, or remove fields | [`set`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/set/), [`rename`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/rename/), [`copy`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/copy/), [`remove`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/remove/) +Convert data types and formats | [`convert`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/convert/), [`date`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/date/), [`json`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/json/), [`bytes`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/bytes/) +Generate vector embeddings for semantic search | [`text_embedding`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/text-embedding/), [`sparse_encoding`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/sparse-encoding/), [`text_image_embedding`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/text-image-embedding/) +Add geographic information based on IP addresses | [`ip2geo`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/ip2geo/) +Drop documents or route them to a different index | [`drop`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/drop/), [`date_index_name`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/date-index-name/), [`set`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/set/) (on the `_index` field) +Apply custom logic | [`script`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/script/) + +## Storing pipelines + +OpenSearch stores pipeline definitions in the cluster state. A snapshot includes them when you take it with `include_global_state` set to `true`. For more information, see [Global cluster state]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#global-cluster-state). + +## Ingest pipeline APIs + +OpenSearch supports the following ingest pipeline APIs: + +- [Create a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/) +- [Test a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/simulate-ingest/) +- [Retrieve information about a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/get-ingest/) +- [Delete a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/delete-ingest/) + +## Related documentation + +- [Use ingest processors in OpenSearch]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/) +- [Access document fields and metadata in a pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/accessing-data/) +- [Run processors conditionally]({{site.url}}{{site.baseurl}}/ingest-pipelines/conditional-execution/) +- [Handle pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/) diff --git a/_ingest-pipelines/pipeline-failures.md b/_ingest-pipelines/pipeline-failures.md index 47e75168..4ed27302 100644 --- a/_ingest-pipelines/pipeline-failures.md +++ b/_ingest-pipelines/pipeline-failures.md @@ -1,7 +1,7 @@ --- layout: default title: Handling pipeline failures -nav_order: 15 +nav_order: 30 redirect_from: - /api-reference/ingest-apis/pipeline-failures/ --- @@ -10,10 +10,11 @@ redirect_from: **Introduced 1.0** {: .label .label-purple } -Each ingest pipeline consists of a series of processors that are applied to the documents in sequence. If a processor fails, the entire pipeline will fail. You have two options for handling failures: +Each ingest pipeline consists of a series of processors that are applied to the documents in sequence. By default, if a processor fails, the entire pipeline fails and the document isn't indexed. You can change this using the following options: -- **Fail the entire pipeline:** If a processor fails, the entire pipeline will fail and the document will not be indexed. -- **Fail the current processor and continue with the next processor:** This can be useful if you want to continue processing the document even if one of the processors fails. +- Set `ignore_failure` on a processor to skip its failure and continue with the next processor. +- Specify `on_failure` on a processor to run other processors when it fails and then continue with the next processor. +- Specify `on_failure` at the pipeline level to run other processors when a processor that doesn't handle its own failure fails, and then stop the pipeline. By default, an ingest pipeline stops if one of its processors fails. If you want the pipeline to continue running when a processor fails, you can set the `ignore_failure` parameter for that processor to `true` when creating the pipeline: @@ -34,7 +35,7 @@ PUT _ingest/pipeline/my-pipeline/ ``` {% include copy-curl.html %} -You can specify the `on_failure` parameter to run immediately after a processor fails. If you have specified `on_failure`, OpenSearch will run the other processors in the pipeline even if the `on_failure` configuration is empty: +You can specify the `on_failure` parameter to run immediately after a processor fails. If you specify `on_failure` for a processor, OpenSearch runs the `on_failure` processors and then continues running the remaining processors in the pipeline. The `on_failure` list must contain at least one processor. Processors in an `on_failure` list can define their own `on_failure`, so you can handle failures that occur during failure handling: ```json PUT _ingest/pipeline/my-pipeline/ @@ -61,8 +62,169 @@ PUT _ingest/pipeline/my-pipeline/ ``` {% include copy-curl.html %} -If the processor fails, OpenSearch logs the failure and continues to run all remaining processors in the search pipeline. To check whether there were any failures, you can use [ingest pipeline metrics]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/pipeline-failures/#ingest-pipeline-metrics). -{: tip} +If the processor fails, OpenSearch runs the `on_failure` processors and then continues to run all remaining processors in the ingest pipeline. The failure is still counted in the processor statistics. To check whether there were any failures, use [ingest pipeline metrics](#ingest-pipeline-metrics). +{: .tip} + +## Handling failures at the pipeline level + +You can also specify `on_failure` at the pipeline level, alongside the `processors` array. OpenSearch runs the pipeline-level `on_failure` processors when a processor that doesn't define its own `on_failure` fails. After the pipeline-level `on_failure` processors run, the pipeline stops, and the remaining processors don't run. A processor-level `on_failure` takes precedence over the pipeline-level `on_failure`. + +A common use of pipeline-level failure handling is to route documents that fail processing to a separate index so that you can inspect and reprocess them later. The following pipeline renames the `region` field and converts the `quantity` field to an integer. If either processor fails, the pipeline-level `on_failure` processor changes the document's target index to `failed-orders`: + +```json +PUT _ingest/pipeline/orders-pipeline +{ + "description": "Parses order data and routes failed documents to a separate index", + "processors": [ + { + "rename": { + "field": "region", + "target_field": "location.region" + } + }, + { + "convert": { + "field": "quantity", + "type": "integer" + } + } + ], + "on_failure": [ + { + "set": { + "field": "_index", + "value": "failed-orders" + } + } + ] +} +``` +{% include copy-curl.html %} + +Index a document that doesn't contain the `region` field: + +```json +PUT orders/_doc/1?pipeline=orders-pipeline +{ + "order_id": "A-1001", + "quantity": "3" +} +``` +{% include copy-curl.html %} + +The `rename` processor fails, so OpenSearch indexes the document into the `failed-orders` index: + +```json +{ + "_index": "failed-orders", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +Because the pipeline stopped after the `rename` processor failed, the `convert` processor didn't run, and the `quantity` field in the indexed document is still a string. + +## Accessing error metadata + +Processors in an `on_failure` block can read information about the failure from the following ingest metadata fields. + +Field | Description +:--- | :--- +`_ingest.on_failure_message` | The error message of the failure. +`_ingest.on_failure_processor_type` | The type of the processor that failed, for example, `rename`. +`_ingest.on_failure_processor_tag` | The `tag` of the processor that failed. Empty if the processor doesn't have a `tag`. +`_ingest.on_failure_pipeline` | The ID of the pipeline in which the processor failed. Populated only when the failure occurs in a pipeline run by a [`pipeline` processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/pipeline/). Empty when the failure occurs in the pipeline that contains the `on_failure` block. + +These fields exist only while the `on_failure` processors run. To keep the failure information, copy it into the document using template snippets. The following pipeline records the error details in the `error` object: + +```json +PUT _ingest/pipeline/orders-error-details +{ + "description": "Records error details for failed documents", + "processors": [ + { + "rename": { + "tag": "rename-region", + "field": "region", + "target_field": "location.region" + } + } + ], + "on_failure": [ + { + "set": { + "field": "_index", + "value": "orders-errors" + } + }, + { + "set": { + "field": "error.message", + "value": "{% raw %}{{ _ingest.on_failure_message }}{% endraw %}" + } + }, + { + "set": { + "field": "error.processor_type", + "value": "{% raw %}{{ _ingest.on_failure_processor_type }}{% endraw %}" + } + }, + { + "set": { + "field": "error.processor_tag", + "value": "{% raw %}{{ _ingest.on_failure_processor_tag }}{% endraw %}" + } + } + ] +} +``` +{% include copy-curl.html %} + +Index a document that doesn't contain the `region` field: + +```json +PUT orders/_doc/1?pipeline=orders-error-details +{ + "order_id": "A-1001" +} +``` +{% include copy-curl.html %} + +Retrieve the document from the `orders-errors` index: + +```json +GET orders-errors/_doc/1 +``` +{% include copy-curl.html %} + +The document contains the error details: + +```json +{ + "_index": "orders-errors", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "order_id": "A-1001", + "error": { + "message": "field [region] doesn't exist", + "processor_type": "rename", + "processor_tag": "rename-region" + } + } +} +``` ## Ingest pipeline metrics @@ -132,5 +294,5 @@ The response contains statistics for all ingest pipelines, for example: } ``` -**Troubleshooting ingest pipeline failures:** The first thing you should do is check the logs to see whether there are any errors or warnings that can help you identify the cause of the failure. OpenSearch logs contain information about the ingest pipeline that failed, including the processor that failed and the reason for the failure. +**Troubleshooting ingest pipeline failures:** When a document fails in a pipeline, the indexing response contains the error and the reason for the failure. OpenSearch also logs these failures at the `DEBUG` level. To include them in the OpenSearch logs, set the `logger.org.opensearch.ingest` log level to `DEBUG`. For more information, see [Logs]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/logs/). {: .tip} diff --git a/_ingest-pipelines/processors/append.md b/_ingest-pipelines/processors/append.md index f52e23db..9b3fb32f 100644 --- a/_ingest-pipelines/processors/append.md +++ b/_ingest-pipelines/processors/append.md @@ -6,15 +6,19 @@ nav_order: 10 redirect_from: - /api-reference/ingest-apis/processors/append/ --- - + +This documentation describes using the `append` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `add_entries` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/add-entries/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Append processor The `append` processor is used to add values to a field: + - If the field is an array, the `append` processor appends the specified values to that array. - If the field is a scalar field, the `append` processor converts it to an array and appends the specified values to that array. - If the field does not exist, the `append` processor creates an array with the specified values. -### Syntax +## Syntax The following is the syntax for the `append` processor: @@ -26,9 +30,9 @@ The following is the syntax for the `append` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `append` processor. @@ -39,14 +43,15 @@ Parameter | Required/Optional | Description | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | +`allow_duplicates` | Optional | Specifies whether to append the values already contained in the field. If `true`, duplicate values are appended. Otherwise, they are skipped. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `user-behavior`, that has one append processor. It appends the `page_view` of each new document ingested into OpenSearch to an array field named `event_types`: @@ -66,7 +71,7 @@ PUT _ingest/pipeline/user-behavior ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -86,8 +91,6 @@ POST _ingest/pipeline/user-behavior/_simulate ``` {% include copy-curl.html %} -**Response** - The following response confirms that the pipeline is working as expected: ```json @@ -111,7 +114,7 @@ The following response confirms that the pipeline is working as expected: } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -122,7 +125,7 @@ PUT testindex1/_doc/1?pipeline=user-behavior ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -131,20 +134,4 @@ GET testindex1/_doc/1 ``` {% include copy-curl.html %} -Because the document does not contain an `event_types` field, an array field is created and the event is appended to the array: - -```json -{ - "_index": "testindex1", - "_id": "1", - "_version": 2, - "_seq_no": 1, - "_primary_term": 1, - "found": true, - "_source": { - "event_types": [ - "page_view" - ] - } -} -``` +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/bytes.md b/_ingest-pipelines/processors/bytes.md index 29a30ca3..a3fde546 100644 --- a/_ingest-pipelines/processors/bytes.md +++ b/_ingest-pipelines/processors/bytes.md @@ -11,7 +11,9 @@ redirect_from: The `bytes` processor converts a human-readable byte value to its equivalent value in bytes. The field can be a scalar or an array. If the field is a scalar, the value is converted and stored in the field. If the field is an array, all values of the array are converted. -### Syntax +The processor supports the `b`, `kb`, `mb`, `gb`, `tb`, and `pb` units, which are case insensitive. Each unit is 1,024 times the preceding unit, so `1kb` is converted to `1024`. The value must be a whole number, for example, `1536b` instead of `1.5kb`. The value must be a string that includes a unit; for example, `10` without a unit fails. The processor also fails if the value isn't in a supported format or if the result exceeds 2<sup>63</sup> − 1 bytes. + +## Syntax The following is the syntax for the `bytes` processor: @@ -22,28 +24,28 @@ The following is the syntax for the `bytes` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `bytes` processor. Parameter | Required/Optional | Description | |-----------|-----------|-----------| -`field` | Required | The name of the field containing the data to be converted. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`field` | Required | The name of the field containing the data to be converted. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | `target_field` | Optional | The name of the field in which to store the parsed data. If not specified, the value will be stored in place in the `field` field. Default is `field`. | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `file_upload`, that has one `bytes` processor. It converts the `file_size` to its byte equivalent and stores it in a new field named `file_size_bytes`: @@ -63,7 +65,7 @@ PUT _ingest/pipeline/file_upload ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -78,9 +80,7 @@ POST _ingest/pipeline/file_upload/_simulate "_index": "testindex1", "_id": "1", "_source": { - "file_size_bytes": "10485760", - "file_size": - "10MB" + "file_size": "10MB" } } ] @@ -88,8 +88,6 @@ POST _ingest/pipeline/file_upload/_simulate ``` {% include copy-curl.html %} -**Response** - The following response confirms that the pipeline is working as expected: ```json @@ -100,10 +98,7 @@ The following response confirms that the pipeline is working as expected: "_index": "testindex1", "_id": "1", "_source": { - "event_types": [ - "event_type" - ], - "file_size_bytes": "10485760", + "file_size_bytes": 10485760, "file_size": "10MB" }, "_ingest": { @@ -115,7 +110,7 @@ The following response confirms that the pipeline is working as expected: } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -127,7 +122,7 @@ PUT testindex1/_doc/1?pipeline=file_upload ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -135,3 +130,5 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/community_id.md b/_ingest-pipelines/processors/community_id.md new file mode 100644 index 00000000..7146e79e --- /dev/null +++ b/_ingest-pipelines/processors/community_id.md @@ -0,0 +1,176 @@ +--- +layout: default +title: Community ID +parent: Ingest processors +nav_order: 25 +--- + +# Community ID processor + +The `community_id` processor is used to generate the community ID flow hash for network flow tuples. The community ID flow hash algorithm is defined in the [community ID specification](https://github.com/corelight/community-id-spec). The processor-generated hash value can be used to correlate all related network events so that you can filter the network flow data by the hash value or generate statistics by aggregating on the hash field. The processor supports the TCP, UDP, SCTP, ICMP, and IPv6-ICMP network protocols. The SHA-1 hash algorithm is used to generate the hash value. + +The following is the `community_id` processor syntax: + +```json +{ + "community_id": { + "source_ip_field": "source_ip", + "source_port_field": "source_port", + "destination_ip_field": "destination_ip", + "destination_port_field": "destination_port", + "iana_protocol_number_field": "iana_protocol_number", + "source_port_field": "source_port", + "target_field": "community_id" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `community_id` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`source_ip_field` | Required | The name of the field containing the source IP address. | +`source_port_field` | Optional | The name of the field containing the source port address. If the network protocol is TCP, UDP, or SCTP, then the field is required. Otherwise, it is not required.| +`destination_ip_field` | Required | The name of the field containing the destination IP address. | +`destination_port_field` | Optional | The name of the field containing the destination port address. If the network protocol is TCP, UDP, or SCTP, then the field is required. Otherwise, it is not required. | +`iana_protocol_number` | Optional | The name of the field containing the protocol number defined by the Internet Assigned Numbers Authority (IANA). The supported values are 1 (ICMP), 6 (TCP), 17 (UDP), 58 (IPv6-ICMP), and 132 (SCTP). | +`protocol_field` | Optional | The name of the field containing the protocol name. If `iana_protocol_number` is not set, then the field is required. Otherwise, it is not required. | +`icmp_type_field` | Optional | The name of the field containing the ICMP message type. Required when the protocol is ICMP or IPv6-ICMP. | +`icmp_code_field` | Optional | The name of the field containing the ICMP message code. For certain ICMP message types that do not have a code, the field is optional. Otherwise, it is required. | +`seed` | Optional | The seed for generating the community ID hash. The value must be between 0 and 65535. | +`target_field` | Optional | The name of the field in which to store the community ID hash value. Default target field is `community_id`. | +`ignore_missing` | Optional | Specifies whether the processor should exit quietly if one of the required fields is missing. Default is `false`. | +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | If set to `true`, then failures are ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `community_id_pipeline` that uses the `community_id` processor to generate a hash value for the network flow tuple: + +```json +PUT /_ingest/pipeline/commnity_id_pipeline +{ + "description": "generate hash value for the network flow tuple", + "processors": [ + { + "community_id": { + "source_ip_field": "source_ip", + "source_port_field": "source_port", + "destination_ip_field": "destination_ip", + "destination_port_field": "destination_port", + "iana_protocol_number_field": "iana_protocol_number", + "target_field": "community_id" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before ingesting documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/commnity_id_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "source_ip": "66.35.250.204", + "source_port": 80, + "destination_ip": "128.232.110.120", + "destination_port": 34855, + "iana_protocol_number": 6 + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "community_id": "1:LQU9qZlK+B5F3KDmev6m5PMibrg=", + "destination_ip": "128.232.110.120", + "destination_port": 34855, + "source_port": 80, + "iana_protocol_number": 6, + "source_ip": "66.35.250.204" + }, + "_ingest": { + "timestamp": "2024-03-11T02:17:22.329823Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=commnity_id_pipeline +{ + "source_ip": "66.35.250.204", + "source_port": 80, + "destination_ip": "128.232.110.120", + "destination_port": 34855, + "iana_protocol_number": 6 +} +``` +{% include copy-curl.html %} + +The request indexes the document into the `testindex1` index: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/convert.md b/_ingest-pipelines/processors/convert.md index f3eda15e..8478f0d1 100644 --- a/_ingest-pipelines/processors/convert.md +++ b/_ingest-pipelines/processors/convert.md @@ -7,6 +7,9 @@ redirect_from: - /api-reference/ingest-apis/processors/convert/ --- +This documentation describes using the `convert` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `convert_entry_type` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/convert-entry-type/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Convert processor The `convert` processor converts a field in a document to a different type, for example, a string to an integer or an integer to a string. For an array field, all values in the array are converted. @@ -23,29 +26,29 @@ The following is the syntax for the `convert` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `convert` processor. Parameter | Required/Optional | Description | |-----------|-----------|-----------| -`field` | Required | The name of the field containing the data to be converted. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | -`type` | Required | The type to convert the field value to. The supported types are `integer`, `long`, `float`, `double`, `string`, `boolean`, and `auto`. If the `type` is `boolean`, the value is set to `true` if the field value is a string `true` (ignoring case) and to `false` if the field value is a string `false` (ignoring case). If the value is not one of the allowed values, an error will occur. | +`field` | Required | The name of the field containing the data to be converted. | +`type` | Required | The type to convert the field value to. The supported types are `integer`, `long`, `float`, `double`, `string`, `boolean`, `ip`, and `auto`. If the `type` is `boolean`, then the value is set to `true` if the field value is a string `true` (ignoring case) and to `false` if the field value is a string `false` (ignoring case). Any other string value causes the processor to fail. If the type is set to `ip`, then this processor validates whether the field value adheres to the correct format for IPv4 or IPv6 addresses; if the value is invalid, an error is raised. If the type is set to `auto`, then the processor converts a string value to the first matching type in the following order: `boolean`, `integer`, `long`, `float`, and `double`. Because `float` is tried before `double`, a decimal string is always converted to a `float`, which can reduce precision. If the string doesn't match any of these types, or the value isn't a string, then the value isn't changed. If `target_field` is specified, the unchanged value is still copied to `target_field`. If `type` isn't one of the supported types, the pipeline is rejected. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | `target_field` | Optional | The name of the field in which to store the parsed data. If not specified, the value will be stored in the `field` field. Default is `field`. | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `convert-price`, that converts `price` to a floating-point number, stores the converted value in the `price_float` field, and sets the value to `0` if it is less than `0`: @@ -73,7 +76,7 @@ PUT _ingest/pipeline/convert-price ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -96,8 +99,6 @@ POST _ingest/pipeline/convert-price/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -120,19 +121,19 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: ```json PUT testindex1/_doc/1?pipeline=convert-price { - "price": "10.5" + "price": "-10.5" } ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -140,3 +141,58 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Converting values automatically + +The following request uses the `auto` type to convert several string fields: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { "convert": { "field": "in_stock", "type": "auto" } }, + { "convert": { "field": "quantity", "type": "auto" } }, + { "convert": { "field": "weight_kg", "type": "auto" } }, + { "convert": { "field": "color", "type": "auto" } } + ] + }, + "docs": [ + { + "_source": { + "in_stock": "TRUE", + "quantity": "42", + "weight_kg": "1.23456789", + "color": "dark gray" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows that `in_stock` was converted to a Boolean and `quantity` was converted to an integer. The `weight_kg` value was converted to a `float`, so its precision was reduced. The `color` value doesn't match any type, so it remains a string: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "in_stock": true, + "quantity": 42, + "weight_kg": 1.2345679, + "color": "dark gray" + }, + "_ingest": { + "timestamp": "2026-10-14T19:42:37.458135758Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/processors/copy.md b/_ingest-pipelines/processors/copy.md index 24435306..962ece06 100644 --- a/_ingest-pipelines/processors/copy.md +++ b/_ingest-pipelines/processors/copy.md @@ -7,6 +7,9 @@ redirect_from: - /api-reference/ingest-apis/processors/copy/ --- +This documentation describes using the `copy` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `copy_values` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/copy-values/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Copy processor The `copy` processor copies an entire object in an existing field to another field. @@ -26,9 +29,9 @@ The following is the syntax for the `copy` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `copy` processor. @@ -43,13 +46,13 @@ The following table lists the required and optional parameters for the `copy` pr `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, the failure is ignored. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline named `copy_object` that copies a nested object from one field to the root level: @@ -72,7 +75,7 @@ PUT /_ingest/pipeline/copy_object ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -100,8 +103,6 @@ POST _ingest/pipeline/copy_object/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -112,6 +113,7 @@ The following example response confirms that the pipeline is working as expected "_index": "testindex1", "_id": "1", "_source": { + "message": {}, "content": { "foo": "bar", "zoo": [1, 2, 3] @@ -126,22 +128,24 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: ```json PUT testindex1/_doc/1?pipeline=copy_object { - "content": { - "foo": "bar", - "zoo": [1, 2, 3] + "message": { + "content": { + "foo": "bar", + "zoo": [1, 2, 3] + } } } ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -149,3 +153,5 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/csv.md b/_ingest-pipelines/processors/csv.md index baf28a9c..ba4942e6 100644 --- a/_ingest-pipelines/processors/csv.md +++ b/_ingest-pipelines/processors/csv.md @@ -7,6 +7,9 @@ redirect_from: - /api-reference/ingest-apis/processors/csv/ --- +This documentation describes using the `csv` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `csv` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/csv/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # CSV processor The `csv` processor is used to parse CSVs and store them as individual fields in a document. The processor ignores empty fields. @@ -23,32 +26,32 @@ The following is the syntax for the `csv` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `csv` processor. Parameter | Required/Optional | Description | |-----------|-----------|-----------| -`field` | Required | The name of the field containing the data to be converted. Supports template snippets. | -`target_fields` | Required | The name of the field in which to store the parsed data. | +`field` | Required | The name of the field containing the CSV data to be parsed. | +`target_fields` | Required | An array of field names in which to store the parsed values, one for each CSV column. Can't be empty. | `description` | Optional | A brief description of the processor. | -`empty_value` | Optional | Represents optional parameters that are not required or are not applicable. | +`empty_value` | Optional | The value to store for empty CSV fields. If not specified, then empty fields are skipped and the corresponding target field isn't added to the document. An empty quoted value (`""`) is also treated as empty. For example, given the line `1,,3` and an `empty_value` of `N/A`, the second target field is set to `N/A`. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`quote` | Optional | The character used to quote fields in the CSV data. Default is `"`. | -`separator` | Optional | The delimiter used to separate the fields in the CSV data. Default is `,`. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | -`trim` | Optional | If set to `true`, the processor trims white space from the beginning and end of the text. Default is `false`. | +`quote` | Optional | The character used to quote fields in the CSV data. Must be a single character. Default is `"`. | +`separator` | Optional | The delimiter used to separate the fields in the CSV data. Must be a single character. Default is `,`. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +`trim` | Optional | If set to `true`, the processor trims white space from the beginning and end of the text. White space inside quotation marks is preserved, so the processor doesn't trim quoted values. For example, given the line `Wireless mouse, " dark gray "`, the processor returns `Wireless mouse` and ` dark gray `. Default is `false`. | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `csv-processor`, that splits `resource_usage` into three new fields named `cpu_usage`, `memory_usage`, and `disk_usage`: @@ -69,7 +72,7 @@ PUT _ingest/pipeline/csv-processor ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -84,10 +87,7 @@ POST _ingest/pipeline/csv-processor/_simulate "_index": "testindex1", "_id": "1", "_source": { - "resource_usage": "25,4096,10", - "memory_usage": "4096", - "disk_usage": "10", - "cpu_usage": "25" + "resource_usage": "25,4096,10" } } ] @@ -95,8 +95,6 @@ POST _ingest/pipeline/csv-processor/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -121,7 +119,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -133,7 +131,7 @@ PUT testindex1/_doc/1?pipeline=csv-processor ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -141,3 +139,5 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/date-index-name.md b/_ingest-pipelines/processors/date-index-name.md index e40b0d6e..330932e6 100644 --- a/_ingest-pipelines/processors/date-index-name.md +++ b/_ingest-pipelines/processors/date-index-name.md @@ -7,7 +7,7 @@ nav_order: 55 # Date index name processor -The `date_index_name` processor is used to point documents to the correct time-based index based on the date or timestamp field within the document. The processor sets the `_index` metadata field to a [date math]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/date/#date-math) index name expression. Then the processor fetches the date or timestamp from the `field` field in the document being processed and formats it into a date math index name expression. The extracted date, `index_name_prefix` value, and `date_rounding` value are then combined to create the date math index expression. For example, if the `field` field contains the value `2023-10-30T12:43:29.000Z` and `index_name_prefix` is set to `week_index-` and `date_rounding` is set to `w`, then the date math index name expression is `week_index-2023-10-30`. You can use the `date_formats` field to specify how the date in the date math index expression should be formatted. +The `date_index_name` processor is used to point documents to the correct time-based index based on the date or timestamp field within the document. The processor sets the `_index` metadata field to a [date math]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#date-math) index name expression. Then the processor fetches the date or timestamp from the `field` field in the document being processed and formats it into a date math index name expression. The extracted date, `index_name_prefix` value, and `date_rounding` value are then combined to create the date math index expression. For example, if the `field` field contains the value `2023-10-30T12:43:29.000Z` and `index_name_prefix` is set to `week_index-` and `date_rounding` is set to `w`, then the date math index name expression is `<week_index-{2023-10-30||/w{yyyy-MM-dd|UTC}}>`, which resolves to the `week_index-2023-10-30` index. Use the `date_formats` parameter to specify how to parse the date in the document, and use the `index_name_format` parameter to specify how to format the date in the index name. The following is the syntax for the `date_index_name` processor: @@ -19,34 +19,34 @@ The following is the syntax for the `date_index_name` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `date_index_name` processor. Parameter | Required/Optional | Description | |-----------|-----------|-----------| -`field` | Required | The date or timestamp field in the incoming document. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | -`date_rounding` | Required | The rounded date format within the index name . Valid values are `y` (year), `M` (month), `w` (week), `d` (day), `h` (hour), `m` (minute), and `s` (second). | -`date_formats` | Optional | An array of date formats used to parse the date or timestamp field. Valid options include a java time pattern or one of the following formats: ISO8601, UNIX, UNIX_MS, or TAI64N. Default is `yyyy-MM-dd'T'HH:mm:ss.SSSXX`. | -`index_name_format` | Optional | The date format. Default is `yyyy-MM-dd`. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | -`index_name_prefix` | Optional | The index name prefix to append before the date. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). +`field` | Required | The date or timestamp field in the incoming document. | +`date_rounding` | Required | The time unit to which the date is rounded in the index name. Valid values are `y` (year), `M` (month), `w` (week), `d` (day), `h` (hour), `m` (minute), and `s` (second). Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`date_formats` | Optional | An array of date formats used to parse the date or timestamp field. Valid options include a Java time pattern or one of the following formats: ISO8601, UNIX, UNIX_MS, or TAI64N. Default is `yyyy-MM-dd'T'HH:mm:ss.SSSXX`. | +`index_name_format` | Optional | The format of the date in the index name. Default is `yyyy-MM-dd`. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`index_name_prefix` | Optional | The prefix to add before the date in the index name. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running this processor. | `ignore_failure` | Optional | If set to `true`, failures are ignored. Default is `false`. | -`locale` | `locale` | Optional | The locale to use when parsing the month name and week day of the date. Default is `ENGLISH`. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`locale` | Optional | The locale to use when parsing the month name and week day of the date. Default is `ENGLISH`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | -`timezone` | Optional | The time zone to use when parsing the date. Default is `UTC`. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +`timezone` | Optional | The time zone used to parse the date and to compute the concrete index name from the date math expression. Default is `UTC`. | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline.** +### Step 1: Create a pipeline -The following query creates a pipeline, named `date-index-name1`, that uses the `date_index_name` processor to index logs into monthly indexes: +The following query creates a pipeline, named `date-index-name1`, that uses the `date_index_name` processor to index logs into weekly indexes: ```json PUT /_ingest/pipeline/date-index-name1 @@ -58,7 +58,7 @@ PUT /_ingest/pipeline/date-index-name1 "field": "date_field", "index_name_prefix": "week_index-", "date_rounding": "w", - "date_formats": ["YYYY-MM-DD"] + "date_formats": ["yyyy-MM-dd"] } } ] @@ -66,7 +66,7 @@ PUT /_ingest/pipeline/date-index-name1 ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline.** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -89,8 +89,6 @@ POST _ingest/pipeline/date-index-name1/_simulate ``` {% include copy-curl.html %} -#### Response - The following example response confirms that the pipeline is working as expected: ```json @@ -98,7 +96,7 @@ The following example response confirms that the pipeline is working as expected "docs": [ { "doc": { - "_index": "<week_index-{2023-10-01||/w{yyyy-MM-dd|UTC}}>", + "_index": "<week_index-{2023-10-30||/w{yyyy-MM-dd|UTC}}>", "_id": "1", "_source": { "date_field": "2023-10-30" @@ -112,7 +110,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document.** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -124,9 +122,7 @@ PUT testindex1/_doc/1?pipeline=date-index-name1 ``` {% include copy-curl.html %} -#### Response - -The request indexes the document into the index `week_index-2023-10-23` and will index all documents with a timestamp within that week into the same index because the pipeline rounds by week. +The request indexes the document into the index `week_index-2023-10-30` and will index all documents with a timestamp within that week into the same index because the pipeline rounds by week. ```json { @@ -144,7 +140,7 @@ The request indexes the document into the index `week_index-2023-10-23` and will } ``` -**Step 4 (Optional): Retrieve the document.** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -152,3 +148,5 @@ To retrieve the document, run the following query: GET week_index-2023-10-30/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/date.md b/_ingest-pipelines/processors/date.md index 364e6cce..210a90b1 100644 --- a/_ingest-pipelines/processors/date.md +++ b/_ingest-pipelines/processors/date.md @@ -7,11 +7,14 @@ redirect_from: - /api-reference/ingest-apis/processors/date/ --- +This documentation describes using the `date` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `date` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/date/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Date processor The `date` processor is used to parse dates from document fields and to add the parsed data to a new field. By default, the parsed data is stored in the `@timestamp` field. -## Syntax example +## Syntax The following is the syntax for the `date` processor: @@ -23,23 +26,23 @@ The following is the syntax for the `date` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `date` processor. Parameter | Required/Optional | Description | |-----------|-----------|-----------| -`field` | Required | The name of the field containing the data to be converted. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | -`formats` | Required | An array of the expected date formats. Can be a [date format]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/date/#formats) or one of the following formats: ISO8601, UNIX, UNIX_MS, or TAI64N. | +`field` | Required | The name of the field containing the data to be converted. | +`formats` | Required | An array of the expected date formats. The processor tries every format in the order specified. If more than one format can parse the date, the last matching format determines the result. Can be a [date format]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#formats) or one of the following formats: ISO8601, UNIX, UNIX_MS, or TAI64N. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | -`locale` | Optional | The locale to use when parsing the date. Default is `ENGLISH`. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`locale` | Optional | The locale to use when parsing the date. If not specified, the root locale is used, which parses English month and day names. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | `on_failure` | Optional | A list of processors to run if the processor fails. | -`output_format` | Optional | The [date format]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/date/#formats) to use for the target field. Default is `yyyy-MM-dd'T'HH:mm:ss.SSSZZ`. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`output_format` | Optional | The [date format]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#formats) to use for the target field. Default is `yyyy-MM-dd'T'HH:mm:ss.SSSXXX`, for example, `2023-06-30T00:00:00.000Z`. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | `target_field` | Optional | The name of the field in which to store the parsed data. Default target field is `@timestamp`. | `timezone` | Optional | The time zone to use when parsing the date. Default is `UTC`. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | @@ -47,7 +50,7 @@ Parameter | Required/Optional | Description | Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `date-output-format`, that uses the `date` processor to convert from European date format to US date format, adding the new field `date_us` with the desired `output_format`: @@ -70,7 +73,7 @@ PUT /_ingest/pipeline/date-output-format ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -85,7 +88,6 @@ POST _ingest/pipeline/date-output-format/_simulate "_index": "testindex1", "_id": "1", "_source": { - "date_us": "06/30/2023", "date_european": "30/06/2023" } } @@ -94,8 +96,6 @@ POST _ingest/pipeline/date-output-format/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -118,7 +118,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -130,7 +130,7 @@ PUT testindex1/_doc/1?pipeline=date-output-format ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -138,3 +138,65 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Using time zones and locales from the document + +Because the `timezone` and `locale` parameters support template snippets, you can read them from fields in the document being processed. This is useful when documents come from sources in different regions. The following request parses a French date string using the time zone and locale stored in the `store` object: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "date": { + "field": "order_date", + "formats": ["dd MMMM yyyy HH:mm"], + "timezone": "{% raw %}{{{store.timezone}}}{% endraw %}", + "locale": "{% raw %}{{{store.locale}}}{% endraw %}" + } + } + ] + }, + "docs": [ + { + "_source": { + "order_date": "14 octobre 2026 09:30", + "store": { + "timezone": "Europe/Paris", + "locale": "fr" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows that the date was parsed using the French month name and the Paris time zone: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "order_date": "14 octobre 2026 09:30", + "store": { + "locale": "fr", + "timezone": "Europe/Paris" + }, + "@timestamp": "2026-10-14T09:30:00.000+02:00" + }, + "_ingest": { + "timestamp": "2026-10-14T20:32:15.764960761Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/processors/dissect.md b/_ingest-pipelines/processors/dissect.md index 94649cf0..eeda1571 100644 --- a/_ingest-pipelines/processors/dissect.md +++ b/_ingest-pipelines/processors/dissect.md @@ -5,6 +5,9 @@ parent: Ingest processors nav_order: 60 --- +This documentation describes using the `dissect` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `dissect` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/dissect/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Dissect The `dissect` processor extracts values from a document text field and maps them to individual fields based on dissect patterns. The processor is well suited for field extractions from log messages with a known structure. Unlike the `grok` processor, `dissect` does not use regular expressions and has a simpler syntax. @@ -21,10 +24,10 @@ The following is the syntax for the `dissect` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `dissect` processor. @@ -38,13 +41,13 @@ Parameter | Required/Optional | Description | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, the processor failure is ignored. Default is `false`. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `dissect-test`, that uses the `dissect` processor to parse the log line: @@ -64,7 +67,7 @@ PUT /_ingest/pipeline/dissect-test ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -87,8 +90,6 @@ POST _ingest/pipeline/dissect-test/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -103,7 +104,7 @@ The following example response confirms that the pipeline is working as expected "http_method": "POST", "http_version": "HTTP/1.1", "client_ip": "192.168.1.10", - "message": """192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] "POST /login HTTP/1.1" 200 3456""", + "message": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456", "url": "/login", "response_size": "3456", "timestamp": "03/Nov/2023:15:20:45 +0000" @@ -117,7 +118,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -129,7 +130,7 @@ PUT testindex1/_doc/1?pipeline=dissect-test ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -138,6 +139,8 @@ GET testindex1/_doc/1 ``` {% include copy-curl.html %} +The response contains the ingested document, transformed as shown in the response in Step 2. + ## Dissect patterns A dissect pattern is a method of telling the `dissect` processor how to parse a string into a structured format. The pattern is defined by the parts of the string that you want to discard. For example, the `%{client_ip} - - [%{timestamp}]` dissect pattern parses the string `"192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456"` into the following fields: @@ -181,7 +184,7 @@ Detailed descriptions of each key modifier, along with usage examples, are provi ### Right padding modifier (`->`) -The dissection algorithm is precise and requires that every character in the pattern exactly match the source string. For example, the pattern `%{hellokey} %{worldkey}` (one space) will match the string "Hello world" (one space) but not the string "Hello world" (two spaces) because the pattern only has one space while the source string has two. +The dissection algorithm is precise and requires that every character in the pattern exactly match the source string. For example, the pattern `%{hellokey} %{worldkey}` (1 space) will match the string `Hello world` (1 space) but not the string <code>Hello  world</code> (2 spaces) because the pattern only has 1 space while the source string has 2. The _right padding modifier_ can be used to address this issue. When added to the pattern `%{helloworldkey->} %{worldkey}`, the right padding modifier will match <code>Hello world</code> (1 space), <code>Hello  world</code> (2 spaces), and even <code>Hello          world</code> (10 spaces). @@ -258,7 +261,6 @@ Your response should appear similar to the following: ] } ``` -{% include copy-curl.html %} ### Append modifier (`+`) @@ -324,7 +326,6 @@ The substrings are appended to the `address` field, as shown in the following re ] } ``` -{% include copy-curl.html %} ### Append with order modifier (`+` and `/n`) @@ -390,7 +391,6 @@ The substrings are appended to the `address` field in reverse order, as shown in ] } ``` -{% include copy-curl.html %} ### Named skip key modifier @@ -456,7 +456,6 @@ Your response should appear similar to the following: ] } ``` -{% include copy-curl.html %} ### Reference keys (`*` and `&`) @@ -523,4 +522,3 @@ The two key-value pairs were extracted into fields, as shown in the following re ] } ``` -{% include copy-curl.html %} diff --git a/_ingest-pipelines/processors/dot-expander.md b/_ingest-pipelines/processors/dot-expander.md index 5cfebba7..c0415ec9 100644 --- a/_ingest-pipelines/processors/dot-expander.md +++ b/_ingest-pipelines/processors/dot-expander.md @@ -18,9 +18,9 @@ The following is the syntax for the `dot_expander` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `dot_expander` processor. @@ -32,7 +32,7 @@ Parameter | Required/Optional | Description | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | If set to `true`, failures are ignored. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor @@ -86,8 +86,6 @@ POST _ingest/pipeline/dot-expander-pipeline/_simulate ``` {% include copy-curl.html %} -#### Response - The following example response confirms that the pipeline is working as expected: ```json @@ -121,8 +119,8 @@ The following query ingests a document into an index named `testindex1`: ```json PUT testindex1/_doc/1?pipeline=dot-expander-pipeline { - "user.address.city": "Denver", - "user.address.state": "CO" + "user.address.city": "New York", + "user.address.state": "NY" } ``` {% include copy-curl.html %} @@ -136,28 +134,7 @@ GET testindex1/_doc/1 ``` {% include copy-curl.html %} -#### Response - -The following response confirms that the specified fields were expanded into nested fields: - -```json -{ - "_index": "testindex1", - "_id": "1", - "_version": 1, - "_seq_no": 3, - "_primary_term": 1, - "found": true, - "_source": { - "user": { - "address": { - "city": "Denver", - "state": "CO" - } - } - } -} -``` +The response contains the ingested document, transformed as shown in the response in Step 2. ## The `path` parameter diff --git a/_ingest-pipelines/processors/drop.md b/_ingest-pipelines/processors/drop.md index 1dd5fdb9..de6c3ded 100644 --- a/_ingest-pipelines/processors/drop.md +++ b/_ingest-pipelines/processors/drop.md @@ -5,13 +5,16 @@ parent: Ingest processors nav_order: 70 --- +This documentation describes using the `drop` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `drop_events` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/drop-events/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Drop processor The `drop` processor is used to discard documents without indexing them. This can be useful for preventing documents from being indexed based on certain conditions. For example, you might use a `drop` processor to prevent documents that are missing important fields or contain sensitive information from being indexed. The `drop` processor does not raise any errors when it discards documents, making it useful for preventing indexing problems without cluttering your OpenSearch logs with error messages. -## Syntax example +## Syntax The following is the syntax for the `drop` processor: @@ -22,9 +25,9 @@ The following is the syntax for the `drop` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `drop` processor. @@ -34,13 +37,13 @@ Parameter | Required | Description | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | If set to `true`, failures are ignored. Default is `false`. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/) for more information. | `on_failure` | Optional | A list of processors to run if the processor fails. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/) for more information. | -`tag` | Optional | An identifier tag for the processor. Useful for distinguishing between processors of the same type when debugging. | +`tag` | Optional | An identifier tag for the processor. Useful for distinguishing between processors of the same type when debugging. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `drop-pii`, that uses the `drop` processor to prevent a document containing personally identifiable information (PII) from being indexed: @@ -59,7 +62,7 @@ PUT /_ingest/pipeline/drop-pii ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before ingesting documents. {: .tip} @@ -82,8 +85,6 @@ POST _ingest/pipeline/drop-pii/_simulate ``` {% include copy-curl.html %} -#### Response - The following example response confirms that the pipeline is working as expected (the document has been dropped): ```json @@ -93,9 +94,8 @@ The following example response confirms that the pipeline is working as expected ] } ``` -{% include copy-curl.html %} -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -109,6 +109,7 @@ PUT testindex1/_doc/1?pipeline=drop-pii The following response confirms that the document with the ID of `1` was not indexed: +```json { "_index": "testindex1", "_id": "1", @@ -120,4 +121,4 @@ The following response confirms that the document with the ID of `1` was not ind "failed": 0 } } -{% include copy-curl.html %} +``` diff --git a/_ingest-pipelines/processors/fail.md b/_ingest-pipelines/processors/fail.md new file mode 100644 index 00000000..0dd7563a --- /dev/null +++ b/_ingest-pipelines/processors/fail.md @@ -0,0 +1,148 @@ +--- +layout: default +title: Fail +parent: Ingest processors +nav_order: 100 +--- + +# Fail processor + +The `fail` processor raises an exception that stops the pipeline and fails the indexing request. The primary use case for the `fail` processor is to fail an indexing operation when certain conditions are met and return a custom message to the client. + +The following is the syntax for the `fail` processor: + +```json +"fail": { + "if": "ctx.foo == 'bar'", + "message": "Custom error message" + } +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `fail` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`message` | Required | A custom error message to be included in the failure response. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets), for example, `Order {% raw %}{{order_id}}{% endraw %} is missing a price`. +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline, named `fail-log-pipeline`, that uses the `fail` processor to intentionally fail the pipeline execution for log events: + +```json +PUT _ingest/pipeline/fail-log-pipeline +{ + "description": "A pipeline to test the fail processor for log events", + "processors": [ + { + "fail": { + "if": "ctx.user_info.contains('password') || ctx.user_info.contains('credit card')", + "message": "Document containing personally identifiable information (PII) cannot be indexed!" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/fail-log-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "user_info": "Sensitive information including credit card" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "error": { + "root_cause": [ + { + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + } + ], + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=fail-log-pipeline +{ + "user_info": "Sensitive information including credit card" +} +``` +{% include copy-curl.html %} + +The request fails to index the log event into the index `testindex1` due to the string `credit card` being present in `user_info`. The following response includes the custom error message specified in the fail processor: + +```json +{ + "error": { + "root_cause": [ + { + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + } + ], + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + }, + "status": 500 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +Because the pipeline failed, the document was not indexed, so the response contains `"found": false`: + +```json +{ + "_index": "testindex1", + "_id": "1", + "found": false +} +``` diff --git a/_ingest-pipelines/processors/fingerprint.md b/_ingest-pipelines/processors/fingerprint.md new file mode 100644 index 00000000..674ed0e7 --- /dev/null +++ b/_ingest-pipelines/processors/fingerprint.md @@ -0,0 +1,156 @@ +--- +layout: default +title: Fingerprint +parent: Ingest processors +nav_order: 105 +--- + +# Fingerprint processor +Introduced 2.16 +{: .label .label-purple } + +The `fingerprint` processor is used to generate a hash value for either certain specified fields or all fields in a document. The hash value can be used to deduplicate documents within an index and collapse search results. + +For each field, the field name, the length of the field value, and the field value itself are concatenated and separated by the pipe character `|`. For example, if the field name is `field1` and the value is `value1`, then the concatenated string would be `|field1|3:value1|field2|10:value2|`. For object fields, the field name is flattened by joining the nested field names with a period `.`. For instance, if the object field is `root_field` with a sub-field `sub_field1` having the value `value1` and another sub-field `sub_field2` with the value `value2`, then the concatenated string would be `|root_field.sub_field1|1:value1|root_field.sub_field2|100:value2|`. + +The following is the syntax for the `fingerprint` processor: + +```json +{ + "community_id": { + "fields": ["foo", "bar"], + "target_field": "fingerprint", + "hash_method": "SHA-1@2.16.0" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `fingerprint` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`fields` | Optional | A list of fields used to generate a hash value. | +`exclude_fields` | Optional | Specifies the fields to be excluded from hash value generation. It is mutually exclusive with the `fields` parameter; if both `exclude_fields` and `fields` are empty or null, then all fields are included in the hash value calculation. | +`hash_method` | Optional | Specifies the hashing algorithm to be used, with options being `MD5@2.16.0`, `SHA-1@2.16.0`, `SHA-256@2.16.0`, or `SHA3-256@2.16.0`. Default is `SHA-1@2.16.0`. The version number is appended to ensure consistent hashing across OpenSearch versions, and new versions will support new hash methods. | +`target_field` | Optional | Specifies the name of the field in which the generated hash value will be stored. If not provided, then the hash value is stored in the `fingerprint` field by default. | +`ignore_missing` | Optional | Specifies whether the processor should exit quietly if one of the required fields is missing. Default is `false`. | +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | If set to `true`, then failures are ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `fingerprint_pipeline` that uses the `fingerprint` processor to generate a hash value for specified fields in the document: + +```json +PUT /_ingest/pipeline/fingerprint_pipeline +{ + "description": "generate hash value for some specified fields the document", + "processors": [ + { + "fingerprint": { + "fields": ["foo", "bar"] + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before ingesting documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/fingerprint_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "foo": "foo", + "bar": "bar" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "foo": "foo", + "bar": "bar", + "fingerprint": "SHA-1@2.16.0:fYeen7hTJ2zs9lpmUnk6nvH54sM=" + }, + "_ingest": { + "timestamp": "2024-03-11T02:17:22.329823Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=fingerprint_pipeline +{ + "foo": "foo", + "bar": "bar" +} +``` +{% include copy-curl.html %} + +The request indexes the document into the `testindex1` index: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/foreach.md b/_ingest-pipelines/processors/foreach.md new file mode 100644 index 00000000..02dd1c92 --- /dev/null +++ b/_ingest-pipelines/processors/foreach.md @@ -0,0 +1,318 @@ +--- +layout: default +title: Foreach +parent: Ingest processors +nav_order: 110 +--- + +<!-- vale off --> +# Foreach processor +<!-- vale on --> + +The `foreach` processor is used to iterate over a list of values in an input document and apply a transformation to each value. This can be useful for tasks like processing all the elements in an array consistently, such as converting all elements in an array to lowercase or uppercase. + +The following is the syntax for the `foreach` processor: + +```json +{ + "foreach": { + "field": "<field_name>", + "processor": { + "<processor_type>": { + "<processor_config>": "<processor_value>" + } + } + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `foreach` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The array field to iterate over. +`processor` | Required | The processor to run for each element of the array. +`ignore_missing` | Optional | If `true` and the specified field does not exist or is null, then the processor will quietly exit without modifying the document. Default is `false`. +`description` | Optional | A brief description of the processor. +`if` | Optional | A condition for running the processor. +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. +`on_failure` | Optional | A list of processors to run if the processor fails. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Accessing array elements + +For each array element, the `foreach` processor stores the element in the `_ingest._value` ingest metadata field and then runs the inner processor. To read or modify the current element, set the inner processor's field to `_ingest._value`. If the element is an object, access its fields using dot notation, for example, `_ingest._value.name`. + +The inner processor can also read and modify any other field in the document. + +While the `foreach` processor runs, `_ingest._value` always holds the current array element, which hides any value that an earlier processor stored in `_ingest._value`. When the loop ends, OpenSearch puts the earlier value back, so processors later in the pipeline can still read it. + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `test-foreach` that uses the `foreach` processor to iterate over each element in the `protocols` field: + +```json +PUT _ingest/pipeline/test-foreach +{ + "description": "Lowercase all the elements in an array", + "processors": [ + { + "foreach": { + "field": "protocols", + "processor": { + "lowercase": { + "field": "_ingest._value" + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/test-foreach/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "protocols": ["HTTP","HTTPS","TCP","UDP"] + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected, showing that the four elements have been lowercased: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "protocols": [ + "http", + "https", + "tcp", + "udp" + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2024-05-23T02:44:10.8201Z" + } + } + } + ] +} + +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +POST testindex1/_doc/1?pipeline=test-foreach +{ + "protocols": ["HTTP","HTTPS","TCP","UDP"] +} +``` +{% include copy-curl.html %} + +The request indexes the document into the index `testindex1` and applies the pipeline before indexing: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 6, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 5, + "_primary_term": 67 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Processing an array of objects + +The following request removes the `internal_sku` field from each object in the `products` array: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "foreach": { + "field": "products", + "processor": { + "remove": { + "field": "_ingest._value.internal_sku" + } + } + } + } + ] + }, + "docs": [ + { + "_source": { + "order_id": "A-1001", + "products": [ + { "name": "Wireless mouse", "price": 24.99, "internal_sku": "WM-4471" }, + { "name": "USB-C cable", "price": 9.99, "internal_sku": "UC-2210" } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows that the `internal_sku` field was removed from both objects: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "order_id": "A-1001", + "products": [ + { + "name": "Wireless mouse", + "price": 24.99 + }, + { + "name": "USB-C cable", + "price": 9.99 + } + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2026-10-14T19:40:29.753456004Z" + } + } + } + ] +} +``` + +## Handling failures for array elements + +If the inner processor fails for an element and doesn't define `on_failure`, the `foreach` processor stops processing the array and fails. + +To handle failures for individual elements, specify `on_failure` in the inner processor. In the following request, the second object in the `products` array doesn't contain the `internal_sku` field, so the `remove` processor fails for that element. The `on_failure` processor sends the document to the `failed-orders` index: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "foreach": { + "field": "products", + "processor": { + "remove": { + "field": "_ingest._value.internal_sku", + "on_failure": [ + { + "set": { + "field": "_index", + "value": "failed-orders" + } + } + ] + } + } + } + } + ] + }, + "docs": [ + { + "_index": "orders", + "_source": { + "order_id": "A-1002", + "products": [ + { "name": "Wireless mouse", "price": 24.99, "internal_sku": "WM-4471" }, + { "name": "USB-C cable", "price": 9.99 } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows that the target index changed to `failed-orders`. Because the `on_failure` block handled the failure, the `foreach` processor continued to process the remaining elements, and the elements that were processed successfully retain their changes: + +```json +{ + "docs": [ + { + "doc": { + "_index": "failed-orders", + "_id": "_id", + "_source": { + "order_id": "A-1002", + "products": [ + { + "name": "Wireless mouse", + "price": 24.99 + }, + { + "name": "USB-C cable", + "price": 9.99 + } + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2026-10-14T19:40:29.808936921Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/processors/grok.md b/_ingest-pipelines/processors/grok.md index 981ec34b..ae681ab1 100644 --- a/_ingest-pipelines/processors/grok.md +++ b/_ingest-pipelines/processors/grok.md @@ -2,19 +2,35 @@ layout: default title: Grok parent: Ingest processors -grand_parent: Ingest pipelines -nav_order: 140 +nav_order: 120 --- # Grok processor The `grok` processor is used to parse and structure unstructured data using pattern matching. You can use the `grok` processor to extract fields from log messages, web server access logs, application logs, and other log data that follows a consistent format. +This documentation describes using the `grok` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `grok` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/grok/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + ## Grok basics -The `grok` processor uses a set of predefined patterns to match parts of the input text. Each pattern consists of a name and a regular expression. For example, the pattern `%{IP:ip_address}` matches an IP address and assigns it to the field `ip_address`. You can combine multiple patterns to create more complex expressions. For example, the pattern `%{IP:client} %{WORD:method} %{URIPATHPARM:request} %{NUMBER:bytes %NUMBER:duration}` matches a line from a web server access log and extracts the client IP address, the HTTP method, the request URI, the number of bytes sent, and the duration of the request. +The `grok` processor uses a set of predefined patterns to match parts of the input text. Each pattern consists of a name and a regular expression. For example, the pattern `%{IP:ip_address}` matches an IP address and assigns it to the field `ip_address`. You can combine multiple patterns to create more complex expressions. For example, the pattern `%{IP:client} %{WORD:method} %{URIPATHPARAM:request} %{NUMBER:bytes} %{NUMBER:duration}` matches a line from a web server access log and extracts the client IP address, the HTTP method, the request URI, the number of bytes sent, and the duration of the request. -The `grok` processor is built on the [Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE) and supports all the patterns from that library. You can use the [Grok Debugger](https://grokdebugger.com/) tool to test and debug your grok expressions. +For a list of available predefined patterns, see [Grok patterns](https://github.com/opensearch-project/OpenSearch/blob/main/libs/grok/src/main/resources/patterns/grok-patterns). +{: .tip} + +The `grok` processor is built on the [Oniguruma regular expression library](https://github.com/kkos/oniguruma/blob/master/doc/RE) and supports all the patterns from that library. You can use the built-in [Grok Debugger]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/grok-debugger/) in OpenSearch Dashboards Dev Tools to test and debug your grok expressions. + +A pattern reference takes one of the following forms: + +- `%{PATTERN_NAME}`: Matches the text but doesn't store it in a field. +- `%{PATTERN_NAME:field_name}`: Stores the matched text as a string in `field_name`. +- `%{PATTERN_NAME:field_name:type}`: Stores the matched text in `field_name`, converted to `type`. Valid types are `int`, `long`, `float`, `double`, and `boolean`. + +For example, given the text `3 items 0.25 2048`, the pattern `%{NUMBER} items %{NUMBER:response_time:float} %{NUMBER:body_size:long}` skips the item count, stores `response_time` as a float, and stores `body_size` as a long. + +Note that patterns are *not anchored*. For performance and reliability, include a start-of-line anchor (`^`) in your pattern. +{: .note} ## Syntax @@ -28,9 +44,9 @@ The following is the basic syntax for the `grok` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters To configure the `grok` processor, you have various options that allow you to define patterns, match specific keys, and control the processor's behavior. The following table lists the required and optional parameters for the `grok` processor. @@ -39,19 +55,20 @@ Parameter | Required/Optional | Description | `field` | Required | The name of the field containing the text to be parsed. | `patterns` | Required | A list of grok expressions used to match and extract named captures. The first matching expression in the list is returned. | `pattern_definitions` | Optional | A dictionary of pattern names and pattern tuples used to define custom patterns for the current processor. If a pattern matches an existing name, it overrides the pre-existing definition. | -`trace_match` | Optional | When the parameter is set to `true`, the processor adds a field named `_grok_match_index` to the processed document. This field contains the index of the pattern within the `patterns` array that successfully matched the document. This information can be useful for debugging and understanding which pattern was applied to the document. Default is `false`. | +`trace_match` | Optional | When the parameter is set to `true`, the processor adds the `_grok_match_index` field to the ingest metadata of the processed document (`_ingest._grok_match_index`). This field contains the index of the pattern within the `patterns` array that successfully matched the document. This information can be useful for debugging and understanding which pattern was applied to the document. Default is `false`. | +`capture_all_matches` | Optional | When set to `true`, captures all matches of repeated grok patterns instead of only the first match. For example, given the text `192.168.1.1 10.0.0.1 172.16.0.1` and the pattern `%{IP:ipAddress} %{IP:ipAddress} %{IP:ipAddress}`, all three IP addresses are collected into an array in the `ipAddress` field. Works only with explicitly repeated patterns, not with quantified patterns such as `(%{IP:ipAddress})+`. Default is `false`. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | -## Creating a pipeline +## Using the processor -The following steps guide you through creating an [ingest pipeline]({{site.url}}{{site.baseurl}}/ingest-pipelines/index/) with the `grok` processor. +Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `log_line`. It extracts fields from the `message` field of the document using the specified pattern. In this case, it extracts the `clientip`, `timestamp`, and `response_status` fields: @@ -63,7 +80,7 @@ PUT _ingest/pipeline/log_line { "grok": { "field": "message", - "patterns": ["%{IPORHOST:clientip} %{HTTPDATE:timestamp} %{NUMBER:response_status:int}"] + "patterns": ["^%{IPORHOST:clientip} %{HTTPDATE:timestamp} %{NUMBER:response_status:int}"] } } ] @@ -71,7 +88,7 @@ PUT _ingest/pipeline/log_line ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline.** +### Step 2 (Optional): Test the pipeline {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/alert-icon.png" class="inline-icon" alt="alert icon"/>{:/} **NOTE**<br>It is recommended that you test your pipeline before you ingest documents. {: .note} @@ -84,7 +101,7 @@ POST _ingest/pipeline/log_line/_simulate "docs": [ { "_source": { - "message": "127.0.0.1 198.126.12 10/Oct/2000:13:55:36 -0700 200" + "message": "198.51.100.12 10/Oct/2000:13:55:36 -0700 200" } } ] @@ -92,8 +109,6 @@ POST _ingest/pipeline/log_line/_simulate ``` {% include copy-curl.html %} -**Response** - The following response confirms that the pipeline is working as expected: ```json @@ -104,9 +119,9 @@ The following response confirms that the pipeline is working as expected: "_index": "_index", "_id": "_id", "_source": { - "message": "127.0.0.1 198.126.12 10/Oct/2000:13:55:36 -0700 200", + "message": "198.51.100.12 10/Oct/2000:13:55:36 -0700 200", "response_status": 200, - "clientip": "198.126.12", + "clientip": "198.51.100.12", "timestamp": "10/Oct/2000:13:55:36 -0700" }, "_ingest": { @@ -118,19 +133,19 @@ The following response confirms that the pipeline is working as expected: } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: ```json PUT testindex1/_doc/1?pipeline=log_line { - "message": "127.0.0.1 198.126.12 10/Oct/2000:13:55:36 -0700 200" + "message": "198.51.100.12 10/Oct/2000:13:55:36 -0700 200" } ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -139,9 +154,11 @@ GET testindex1/_doc/1 ``` {% include copy-curl.html %} +The response contains the ingested document, transformed as shown in the response in Step 2. + ## Custom patterns -You can use default patterns, or you can add custom patterns to your pipelines using the `patterns_definitions` parameter. Custom grok patterns can be used in a pipeline to extract structured data from log messages that do not match the built-in grok patterns. This can be useful for parsing log messages from custom applications or for parsing log messages that have been modified in some way. Custom patterns adhere to a straightforward structure: each pattern has a unique name and the corresponding regular expression that defines its matching behavior. +Use the default patterns, or add custom patterns to your pipelines using the `pattern_definitions` parameter. Custom grok patterns can be used in a pipeline to extract structured data from log messages that do not match the built-in grok patterns. This can be useful for parsing log messages from custom applications or for parsing log messages that have been modified in some way. Custom patterns adhere to a straightforward structure: each pattern has a unique name and the corresponding regular expression that defines its matching behavior. The following is an example of how to include a custom pattern in your configuration. In this example, the issue number is between 3 and 4 digits and is parsed into the `issue_number` field and the status is parsed into the `status` field: @@ -152,7 +169,7 @@ PUT _ingest/pipeline/log_line { "grok": { "field": "message", - "patterns": ["The issue number %{NUMBER:issue_number} is %{STATUS:status}"], + "patterns": ["^The issue number %{NUMBER:issue_number} is %{STATUS:status}"], "pattern_definitions" : { "NUMBER" : "\\d{3,4}", "STATUS" : "open|closed" @@ -164,6 +181,57 @@ PUT _ingest/pipeline/log_line ``` {% include copy-curl.html %} +## Retrieving built-in patterns + +To view the built-in patterns that you can reference in grok expressions, use the following request: + +```json +GET _ingest/processor/grok +``` +{% include copy-curl.html %} + +The response contains a `patterns` object that maps each pattern name to its regular expression. The following is a truncated example response: + +```json +{ + "patterns": { + "IP": "(?:%{IPV6}|%{IPV4})", + ... + } +} +``` + +To sort the patterns alphabetically by name, set the `s` query parameter to `true`: + +```json +GET _ingest/processor/grok?s=true +``` +{% include copy-curl.html %} + +## Grok watchdog settings + +To protect the node from expressions that run for an unexpectedly long time, OpenSearch monitors each grok evaluation using a watchdog thread. If an evaluation runs longer than the allowed time, the watchdog stops it and the `grok` processor returns an error. You can configure the watchdog using the following static settings in `opensearch.yml`: + +- `ingest.grok.watchdog.interval` (Static, time unit): The interval between watchdog runs. On each run, the watchdog stops any evaluation that has exceeded `ingest.grok.watchdog.max_execution_time`. Default is `1s`. + +- `ingest.grok.watchdog.max_execution_time` (Static, time unit): The maximum amount of time that a grok expression evaluation can run before it is interrupted. Default is `1s`. + +## Logging grok processing + +When OpenSearch compiles the grok expressions in a processor, which happens when a pipeline is created or loaded or when a pipeline definition is passed to the Simulate Pipeline API, the regular expression compiler can report warnings about the expressions. OpenSearch logs these warnings at the `DEBUG` level. To include them in the OpenSearch logs, increase the log level for the processor: + +```json +PUT _cluster/settings +{ + "persistent": { + "logger.org.opensearch.ingest.common.GrokProcessor": "DEBUG" + } +} +``` +{% include copy-curl.html %} + +For more information, see [Logs]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/logs/). + ## Tracing which patterns matched To trace which patterns matched and populated the fields, you can use the `trace_match` parameter. The following is an example of how to include this parameter in your configuration: @@ -176,7 +244,7 @@ PUT _ingest/pipeline/log_line { "grok": { "field": "message", - "patterns": ["%{HTTPDATE:timestamp} %{IPORHOST:clientip}", "%{IPORHOST:clientip} %{HTTPDATE:timestamp} %{NUMBER:response_status:int}"], + "patterns": ["^%{HTTPDATE:timestamp} %{IPORHOST:clientip}", "%{IPORHOST:clientip} %{HTTPDATE:timestamp} %{NUMBER:response_status:int}"], "trace_match": true } } @@ -185,7 +253,7 @@ PUT _ingest/pipeline/log_line ``` {% include copy-curl.html %} -When you simulate the pipeline, OpenSearch returns the `_ingest` metadata that includes the `grok_match_index`, as shown in the following output: +When you simulate the pipeline, OpenSearch returns the `_ingest` metadata that includes the `_grok_match_index`, as shown in the following output. The index is zero based, so a value of `1` means that the second pattern matched. Because `_grok_match_index` is ingest metadata, it isn't indexed: ```json { @@ -195,9 +263,9 @@ When you simulate the pipeline, OpenSearch returns the `_ingest` metadata that i "_index": "_index", "_id": "_id", "_source": { - "message": "127.0.0.1 198.126.12 10/Oct/2000:13:55:36 -0700 200", + "message": "198.51.100.12 10/Oct/2000:13:55:36 -0700 200", "response_status": 200, - "clientip": "198.126.12", + "clientip": "198.51.100.12", "timestamp": "10/Oct/2000:13:55:36 -0700" }, "_ingest": { diff --git a/_ingest-pipelines/processors/gsub.md b/_ingest-pipelines/processors/gsub.md new file mode 100644 index 00000000..f3660412 --- /dev/null +++ b/_ingest-pipelines/processors/gsub.md @@ -0,0 +1,148 @@ +--- +layout: default +title: gsub +parent: Ingest processors +nav_order: 125 +--- + +<!-- vale off --> +# Gsub processor +<!-- vale on --> + +The `gsub` processor performs a regular expression search-and-replace operation on string fields in incoming documents. If the field contains an array of strings, the operation is applied to all elements in the array. However, if the field contains non-string values, the processor throws an exception. Use cases for the `gsub` processor include removing sensitive information from log messages or user-generated content, normalizing data formats or conventions (for example, converting date formats, removing special characters), and extracting or transforming substrings from field values for further processing or analysis. + +The following is the syntax for the `gsub` processor: + +```json +"gsub": { + "field": "field_name", + "pattern": "regex_pattern", + "replacement": "replacement_string" +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `gsub` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The field to apply the replacement to. +`pattern` | Required | The pattern to be replaced. +`replacement` | Required | The string that will replace the matching patterns. +`target_field` | Optional | The name of the field in which to store the parsed data. If `target_field` is not specified, the parsed data replaces the original data in the `field` field. Default is `field`. +`description` | Optional | A brief description of the processor. +`if` | Optional | A condition for running the processor. +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field or in which the field is `null`. Default is `false`. +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. +`on_failure` | Optional | A list of processors to run if the processor fails. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `gsub_pipeline` that uses the `gsub` processor to replace all occurrences of the word `error` with the word `warning` in the `message` field: + +```json +PUT _ingest/pipeline/gsub_pipeline +{ + "description": "Replaces 'error' with 'warning' in the 'message' field", + "processors": [ + { + "gsub": { + "field": "message", + "pattern": "error", + "replacement": "warning" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/gsub_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "message": "This is an error message" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "This is an warning message" + }, + "_ingest": { + "timestamp": "2024-05-22T19:47:00.645687211Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `logs`: + +```json +PUT logs/_doc/1?pipeline=gsub_pipeline +{ + "message": "This is an error message" +} +``` +{% include copy-curl.html %} + +The following response shows that the request indexed the document into the index named `logs` and that the `gsub` processor replaced all occurrences of the word `error` with the word `warning` in the `message` field: + +```json +{ + "_index": "logs", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET logs/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/html-strip.md b/_ingest-pipelines/processors/html-strip.md new file mode 100644 index 00000000..9cffb46a --- /dev/null +++ b/_ingest-pipelines/processors/html-strip.md @@ -0,0 +1,144 @@ +--- +layout: default +title: HTML strip +parent: Ingest processors +nav_order: 140 +--- + +# HTML strip processor + +The `html_strip` processor removes HTML tags from string fields in incoming documents. This processor is useful when indexing data from webpages or other sources that may contain HTML markup. Block-level tags, such as `<p>`, `<div>`, `<br>`, and `<li>`, are replaced with newline characters (`\n`). Inline tags, such as `<b>`, `<span>`, and `<a>`, are removed. For example, `<p>Hello <b>world</b></p>` becomes `\nHello world\n`. For array fields, the processor strips the tags from each string element. + +The following is the syntax for the `html_strip` processor: + +```json +{ + "html_strip": { + "field": "webpage" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `html_strip` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The string field from which to remove HTML tags. +`target_field` | Optional | The field that receives the plain text version after stripping HTML tags. If not specified, then the field is updated in-place. +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field or in which the field is `null`. Default is `false`. +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Optional | Specifies a list of processors to run if the processor fails during execution. These processors are executed in the order they are specified. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `strip-html-pipeline` that uses the `html_strip` processor to remove HTML tags from the description field and store the processed value in a new field named `cleaned_description`: + +```json +PUT _ingest/pipeline/strip-html-pipeline +{ + "description": "A pipeline to strip HTML from description field", + "processors": [ + { + "html_strip": { + "field": "description", + "target_field": "cleaned_description" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/strip-html-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "description": "This is a <b>test</b> description with <i>some</i> HTML tags." + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "description": "This is a <b>test</b> description with <i>some</i> HTML tags.", + "cleaned_description": "This is a test description with some HTML tags." + }, + "_ingest": { + "timestamp": "2024-05-22T21:46:11.227974965Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `products`: + +```json +PUT products/_doc/1?pipeline=strip-html-pipeline +{ + "description": "This is a <b>test</b> description with <i>some</i> HTML tags." +} +``` +{% include copy-curl.html %} + +The response shows that the request has indexed the document into the index `products` and will index all documents with the `description` field containing HTML tags while storing the plain text version in the `cleaned_description` field: + +```json +{ + "_index": "products", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET products/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/index-processors.md b/_ingest-pipelines/processors/index-processors.md index 4a962937..a760e9e2 100644 --- a/_ingest-pipelines/processors/index-processors.md +++ b/_ingest-pipelines/processors/index-processors.md @@ -1,7 +1,7 @@ --- layout: default title: Ingest processors -nav_order: 30 +nav_order: 80 has_children: true has_toc: false redirect_from: @@ -19,17 +19,20 @@ GET /_nodes/ingest?filter_path=nodes.*.ingest.processors ``` {% include copy-curl.html %} -To set up and deploy ingest processors, make sure you have the necessary permissions and access rights. See [Security plugin REST API]({{site.url}}{{site.baseurl}}/security/access-control/api/) to learn more. +Every processor in a pipeline must be installed on all nodes in the cluster. If a processor is missing from any node, the Create or Update Pipeline API request fails. If you use processors provided by a plugin, list the plugin in the [`plugin.mandatory`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/plugin-settings/) setting so that a node without the plugin doesn't start. + +To set up and deploy ingest processors, make sure you have the necessary permissions and access rights. For more information, see [API permissions]({{site.url}}{{site.baseurl}}/security/access-control/api/). {:.note} ## Supported processors -Processor types and their required or optional parameters vary depending on your specific use case. OpenSearch supports the following ingest processors. For tutorials on using these processors in an OpenSerch pipeline, go to each processor's respective documentation. +Processor types and their required or optional parameters vary depending on your specific use case. OpenSearch supports the following ingest processors. For tutorials on using these processors in an OpenSearch pipeline, go to each processor's respective documentation. Processor type | Description :--- | :--- `append` | Adds one or more values to a field in a document. `bytes` | Converts a human-readable byte value to its value in bytes. +`community_id` | Generates a community ID flow hash algorithm for the network flow tuples. `convert` | Changes the data type of a field in a document. `copy` | Copies an entire object in an existing field to another field. `csv` | Extracts CSVs and stores them as individual fields in a document. @@ -39,8 +42,8 @@ Processor type | Description `dot_expander` | Expands a field with dots into an object field. `drop` |Drops a document without indexing it or raising any errors. `fail` | Raises an exception and stops the execution of a pipeline. -`foreach` | Allows for another processor to be applied to each element of an array or an object field in a document. -`geoip` | Adds information about the geographical location of an IP address. +`fingerprint` | Generates a hash value for either certain specified fields or all fields in a document. +`foreach` | Applies another processor to each element of an array field in a document. `geojson-feature` | Indexes GeoJSON data into a geospatial field. `grok` | Parses and structures unstructured data using pattern matching. `gsub` | Replaces or deletes substrings within a string field of a document. @@ -50,16 +53,68 @@ Processor type | Description `json` | Converts a JSON string into a structured JSON object. `kv` | Automatically parses key-value pairs in a field. `lowercase` | Converts text in a specific field to lowercase letters. +`ml_inference` | Runs a machine learning model registered in OpenSearch and adds the model outputs to the document. `pipeline` | Runs an inner pipeline. `remove` | Removes fields from a document. +`remove_by_pattern` | Removes fields from a document by field pattern. +`rename` | Renames an existing field. `script` | Runs an inline or stored script on incoming documents. `set` | Sets the value of a field to a specified value. `sort` | Sorts the elements of an array in ascending or descending order. `sparse_encoding` | Generates a sparse vector/token and weights from text fields for neural sparse search using sparse retrieval. `split` | Splits a field into an array using a separator character. +`text_chunking` | Splits long documents into smaller chunks. `text_embedding` | Generates vector embeddings from text fields for semantic search. -`text_image_embedding` | Generates combined vector embeddings from text and image fields for multimodal neural search. +`text_image_embedding` | Generates combined vector embeddings from text and image fields for multimodal search. `trim` | Removes leading and trailing white space from a string field. `uppercase` | Converts text in a specific field to uppercase letters. `urldecode` | Decodes a string from URL-encoded format. `user_agent` | Extracts details from the user agent sent by a browser to its web requests. + +## Common processor parameters + +Each processor has its own parameters. Additionally, all processors support the following optional parameters. + +Parameter | Type | Description +:--- | :--- | :--- +`description` | String | A description of the processor. +`if` | String or object | A Painless script condition, specified either as a string or as a script object containing `source`, `lang`, and `params`. The processor runs only if the condition evaluates to `true`. For more information, see [Conditional execution]({{site.url}}{{site.baseurl}}/ingest-pipelines/conditional-execution/). +`ignore_failure` | Boolean | If `true`, the pipeline continues to run if the processor fails. Default is `false`. For more information, see [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Array of processor objects | Processors to run if the processor fails. For more information, see [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`tag` | String | An identifier for the processor. The tag appears in error metadata and in ingest statistics returned by the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/), which helps you identify a specific processor in a pipeline. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +The following `lowercase` processor normalizes the `coupon_code` field. It runs only for documents in which the coupon code is longer than four characters, and if it fails, it records the error message in the `coupon_error` field so that the pipeline continues: + +```json +{ + "lowercase": { + "description": "Normalizes coupon codes", + "tag": "normalize-coupon", + "if": "ctx.coupon_code instanceof String && ctx.coupon_code.length() > 4", + "field": "coupon_code", + "on_failure": [ + { + "set": { + "field": "coupon_error", + "value": "{% raw %}{{ _ingest.on_failure_message }}{% endraw %}" + } + } + ] + } +} +``` +{% include copy.html %} + +## Processor limit settings + +You can limit the number of ingest processors using the cluster setting `cluster.ingest.max_number_processors`. The total number of processors includes both the number of processors and the number of [`on_failure`]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/) processors. + +The default value for `cluster.ingest.max_number_processors` is `Integer.MAX_VALUE`. Adding a higher number of processors than the value configured in `cluster.ingest.max_number_processors` will throw an `IllegalStateException`. + +## Batch-enabled processors + +Some processors support batch ingestion---they can process multiple documents at the same time as a batch. These batch-enabled processors usually provide better performance when using batch processing. For batch processing, use the [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) and provide a `batch_size` parameter. All batch-enabled processors have a batch mode and a single-document mode. When you ingest documents using the `PUT` method, the processor functions in single-document mode and processes documents in series. Only the `text_embedding` and `sparse_encoding` processors are batch enabled. All other processors process documents one at a time. + +## Selectively enabling processors + +Processors defined by the [ingest-common module](https://github.com/opensearch-project/OpenSearch/blob/main/modules/ingest-common/src/main/java/org/opensearch/ingest/common/IngestCommonModulePlugin.java) can be selectively enabled by providing the `ingest.common.processors.allowed` static setting in `opensearch.yml`. If not provided, then all processors are enabled by default. Specifying an empty list disables all processors. If the setting is changed to remove previously enabled processors, then any pipeline using a disabled processor will fail after node restart when the new setting takes effect. diff --git a/_ingest-pipelines/processors/ip2geo.md b/_ingest-pipelines/processors/ip2geo.md index 1563208b..3068d378 100644 --- a/_ingest-pipelines/processors/ip2geo.md +++ b/_ingest-pipelines/processors/ip2geo.md @@ -2,7 +2,7 @@ layout: default title: IP2Geo parent: Ingest processors -nav_order: 130 +nav_order: 150 redirect_from: - /api-reference/ingest-apis/processors/ip2geo/ --- @@ -18,7 +18,7 @@ The `ip2geo` processor adds information about the geographical location of an IP ## Getting started -To get started with the `ip2geo` processor, the `opensearch-geospatial` plugin must be installed. See [Installing plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) to learn more. +To get started with the `ip2geo` processor, the `opensearch-geospatial` plugin must be installed. See [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) to learn more. ## Cluster settings @@ -122,7 +122,7 @@ To update the date source, run the following query: ```json PUT /_plugins/geospatial/ip2geo/datasource/my-datasource/_settings { - "endpoint": https://geoip.maps.opensearch.org/v1/geolite2-city/manifest.json, + "endpoint": "https://geoip.maps.opensearch.org/v1/geolite2-city/manifest.json", "update_interval_in_days": 10 } ``` @@ -143,7 +143,7 @@ DELETE /_plugins/geospatial/ip2geo/datasource/my-datasource Once the data source is created, you can create the pipeline. -## Syntax +## Syntax The following is the syntax for the `ip2geo` processor: @@ -155,9 +155,8 @@ The following is the syntax for the `ip2geo` processor: } } ``` -{% include copy-curl.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `ip2geo` processor. @@ -168,12 +167,17 @@ The following table lists the required and optional parameters for the `ip2geo` | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | | `properties` | Optional | The field that controls which properties are added to `target_field` from `datasource`. Default is all the fields in `datasource`. | | `target_field` | Optional | The field containing the geographical information retrieved from the data source. Default is `ip2geo`. | +| `description` | Optional | A brief description of the processor. | +| `if` | Optional | A condition for running the processor. | +| `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | +| `on_failure` | Optional | A list of processors to run if the processor fails. | +| `tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `my-pipeline`, that converts the IP address to geographical information: @@ -193,7 +197,7 @@ PUT /_ingest/pipeline/my-pipeline ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/info-icon.png" class="inline-icon" alt="info icon"/>{:/} **NOTE**<br>It is recommended that you test your pipeline before you ingest documents. {: .note} @@ -208,15 +212,13 @@ POST _ingest/pipeline/my-pipeline/_simulate "_index": "testindex1", "_id": "1", "_source": { - "ip": "172.0.0.1", + "ip": "172.0.0.1" } } ] } ``` -**Response** - The following response confirms that the pipeline is working as expected: ```json @@ -242,21 +244,20 @@ The following response confirms that the pipeline is working as expected: ] } ``` -{% include copy-curl.html %} -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `my-index`: ```json -PUT /my-index/_doc/my-id?pipeline=ip2geo +PUT /my-index/_doc/my-id?pipeline=my-pipeline { "ip": "172.0.0.1" } ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -264,3 +265,5 @@ To retrieve the document, run the following query: GET /my-index/_doc/my-id ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/join.md b/_ingest-pipelines/processors/join.md new file mode 100644 index 00000000..917bc3f0 --- /dev/null +++ b/_ingest-pipelines/processors/join.md @@ -0,0 +1,134 @@ +--- +layout: default +title: Join +parent: Ingest processors +nav_order: 160 +--- + +# Join processor + +The `join` processor concatenates the elements of an array into a single string value, using a specified separator between each element. It throws an exception if the provided input is not an array. + +The following is the syntax for the `join` processor: + +```json +{ + "join": { + "field": "field_name", + "separator": "separator_string" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `join` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The name of the field to which the join operator is applied. Must be an array. +`separator` | Required | A string separator to use when joining field values. If not specified, then the values are concatenated without a separator. +`target_field` | Optional | The field to assign the cleaned value to. If not specified, then the field is updated in place. +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore failures for the processor. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Optional | Specifies to handle failures for the processor. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`tag` | Optional | An identifier for the processor. Useful for debugging and metrics. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `example-join-pipeline` that uses the `join` processor to concatenate all the values of the `uri` field, separating them with the specified separator `/`: + +```json +PUT _ingest/pipeline/example-join-pipeline +{ + "description": "Example pipeline using the join processor", + "processors": [ + { + "join": { + "field": "uri", + "separator": "/" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/example-join-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "uri": [ + "app", + "home", + "overview" + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "uri": "app/home/overview" + }, + "_ingest": { + "timestamp": "2024-05-24T02:16:01.00659117Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +POST testindex1/_doc/1?pipeline=example-join-pipeline +{ + "uri": [ + "app", + "home", + "overview" + ] +} +``` +{% include copy-curl.html %} + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/json.md b/_ingest-pipelines/processors/json.md new file mode 100644 index 00000000..ce758a3f --- /dev/null +++ b/_ingest-pipelines/processors/json.md @@ -0,0 +1,193 @@ +--- +layout: default +title: JSON +parent: Ingest processors +nav_order: 170 +--- + +# JSON processor + +The `json` processor parses a JSON-formatted string into structured data, which can be useful for various data processing and enrichment tasks. The processor parses all JSON data types: objects, arrays, strings, numbers, Booleans, and `null`. For example, the string `"[1,2,3]"` is parsed into an array, and the string `"42"` is parsed into a number. + +The following is the syntax for the `json` processor: + +```json +{ + "json": { + "field": "<field_name>", + "target_field": "<target_field_name>", + "add_to_root": <boolean> + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `json` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The name of the field containing the JSON-formatted string to be deserialized. +`target_field` | Optional | The name of the field in which the deserialized JSON data is stored. When not provided, the data is stored in the `field` field. If `target_field` exists, its existing value is overwritten with the new JSON data. +`add_to_root` | Optional | A Boolean flag that determines whether the deserialized JSON data should be added to the root of the document (`true`) or stored in the target_field (`false`). If `add_to_root` is `true`, then `target_field` is invalid. Parsed fields overwrite root fields with the same names. The processor fails if `add_to_root` is `true` and the parsed value isn't a JSON object. Default value is `false`. +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure`| Optional | Specifies a list of processors to run if the processor fails during execution. These processors are executed in the order they are specified. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `my-json-pipeline` that uses the `json` processor to process JSON data and enrich the documents with additional information: + +```json +PUT _ingest/pipeline/my-json-pipeline +{ + "description": "Example pipeline using the JsonProcessor", + "processors": [ + { + "json": { + "field": "raw_data", + "target_field": "parsed_data", + "on_failure": [ + { + "set": { + "field": "error_message", + "value": "Failed to parse JSON data" + } + }, + { + "fail": { + "message": "Failed to process JSON data" + } + } + ] + } + }, + { + "set": { + "field": "processed_timestamp", + "value": "{% raw %}{{_ingest.timestamp}}{% endraw %}" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/my-json-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "raw_data": "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}" + } + }, + { + "_source": { + "raw_data": "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "processed_timestamp": "2024-05-30T15:24:48.064472090Z", + "raw_data": "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}", + "parsed_data": { + "name": "John", + "city": "New York", + "age": 30 + } + }, + "_ingest": { + "timestamp": "2024-05-30T15:24:48.06447209Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "processed_timestamp": "2024-05-30T15:24:48.064543006Z", + "raw_data": "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}", + "parsed_data": { + "name": "Jane", + "city": "Los Angeles", + "age": 25 + } + }, + "_ingest": { + "timestamp": "2024-05-30T15:24:48.064543006Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `my-index`: + +```json +PUT my-index/_doc/1?pipeline=my-json-pipeline +{ + "raw_data": "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}" +} +``` +{% include copy-curl.html %} + +The response confirms that the document containing the JSON data from the `raw_data` field was successfully indexed: + +```json +{ + "_index": "my-index", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 3, + "_primary_term": 2 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET my-index/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/kv.md b/_ingest-pipelines/processors/kv.md index 450cfd22..0f20c4d1 100644 --- a/_ingest-pipelines/processors/kv.md +++ b/_ingest-pipelines/processors/kv.md @@ -3,15 +3,19 @@ layout: default title: KV parent: Ingest processors nav_order: 200 -redirect_from: - - /api-reference/ingest-apis/processors/lowercase/ --- +This documentation describes using the `kv` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `key_value` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/key-value/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # KV processor -The `kv` processor automatically extracts specific event fields or messages that are in a `key=value` format. This structured format organizes your data by grouping it together based on keys and values. It's helpful for analyzing, visualizing, and using data, such as user behavior analytics, performance optimizations, or security investigations. +The `kv` processor automatically extracts specific event fields or messages that are in a `key=value` format. This structured format organizes your data by grouping it together based on keys and values. It's helpful for analyzing, visualizing, and using data, such as user behavior analytics, performance optimizations, or security investigations. -## Example +The `kv` processor creates a field for each key that it extracts, so the keys in your data determine the field names in your index. If the keys vary widely, the number of fields in the mapping can grow quickly. To store all extracted keys in a single field, set `target_field` and map that field as a [`flat_object`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/flat-object/). +{: .tip} + +## Syntax The following is the syntax for the `kv` processor: @@ -20,39 +24,40 @@ The following is the syntax for the `kv` processor: "kv": { "field": "message", "field_split": " ", - "value_split": " " + "value_split": "=" } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `kv` processor. | Parameter | Required/Optional | Description | -`field` | Required | The name of the field containing the data to be parsed. | +|-----------|-----------|-----------| +`field` | Required | The name of the field containing the data to be parsed. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | `field_split` | Required | The regex pattern for key-value pair splitting. | `value_split` | Required | The regex pattern for splitting the key from the value within a key-value pair, for example, equal sign `=` or colon `:`. -`exclude_keys` | Optional | The keys to exclude from the document. Default is `null`. | -`include_keys` | Optional | The keys for filtering and inserting. Default is to include all keys. | +`exclude_keys` | Optional | A list of keys to exclude from the document. Default is `null`. | +`include_keys` | Optional | A list of keys to extract. Other keys are ignored. Default is to include all keys. | `prefix` | Optional | The prefix to add to the extracted keys. Default is `null`. | `strip_brackets` | Optional | If set to `true`, strips brackets (`()`, `<>,` or `[]`) and quotes (`'` or `"`) from extracted values. Default is `false`. `trim_key` | Optional | The string of characters to trim from the extracted keys. | -`trim value` | Optional | The string of characters to trim from the extracted values. | +`trim_value` | Optional | The string of characters to trim from the extracted values. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | If set to `true`, failures are ignored. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. Default is `false`. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | -`target_field` | Optional | The name of the field in which to insert the extracted keys. Default is `null`. | +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field or in which the field is `null`. Default is `false`. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +`target_field` | Optional | The name of the field in which to insert the extracted keys. If not specified, the keys are added to the root of the document. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `kv-pipeline`, that uses the `kv` processor to extract the `message` field of a document: @@ -73,7 +78,7 @@ PUT _ingest/pipeline/kv-pipeline ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -82,8 +87,6 @@ To test the pipeline, run the following query: ```json POST _ingest/pipeline/kv-pipeline/_simulate - -```json { "docs": [ { @@ -98,9 +101,7 @@ POST _ingest/pipeline/kv-pipeline/_simulate ``` {% include copy-curl.html %} -**Response** - -The following example response confirms that the pipeline is working as expected: +The following example response confirms that, in addition to the original `message` field, the document contains fields generated from key-value pairs: ```json { @@ -123,21 +124,19 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: ```json PUT testindex1/_doc/1?pipeline=kv-pipeline - -```json { "message": "goodbye=everybody hello=world" } ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -145,3 +144,5 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/lowercase.md b/_ingest-pipelines/processors/lowercase.md index f957e963..ae018eda 100644 --- a/_ingest-pipelines/processors/lowercase.md +++ b/_ingest-pipelines/processors/lowercase.md @@ -7,9 +7,12 @@ redirect_from: - /api-reference/ingest-apis/processors/lowercase/ --- +This documentation describes using the `lowercase` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `lowercase_string` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/lowercase-string/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Lowercase processor -The `lowercase` processor converts all the text in a specific field to lowercase letters. +The `lowercase` processor converts all the text in a specific field to lowercase letters. For array fields, the processor converts each string element. ## Syntax @@ -22,28 +25,28 @@ The following is the syntax for the `lowercase` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `lowercase` processor. | Parameter | Required | Description | |---|---|---| -`field` | Required | The name of the field containing the data to be converted. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`field` | Required | The name of the field containing the data to be converted. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | `target_field` | Optional | The name of the field in which to store the parsed data. Default is `field`. By default, `field` is updated in place. | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `lowercase-title`, that uses the `lowercase` processor to lowercase the `title` field of a document: @@ -62,7 +65,7 @@ PUT _ingest/pipeline/lowercase-title ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -85,8 +88,6 @@ POST _ingest/pipeline/lowercase-title/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -108,7 +109,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -120,7 +121,7 @@ PUT testindex1/_doc/1?pipeline=lowercase-title ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -128,3 +129,5 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/ml-inference.md b/_ingest-pipelines/processors/ml-inference.md new file mode 100644 index 00000000..f0737de9 --- /dev/null +++ b/_ingest-pipelines/processors/ml-inference.md @@ -0,0 +1,462 @@ +--- +layout: default +title: ML inference +parent: Ingest processors +nav_order: 215 +redirect_from: +- /api-reference/ingest-apis/processors/ml-inference/ +--- + +# ML inference processor + +The `ml_inference` processor invokes [machine learning (ML) models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/) registered in OpenSearch. The model outputs are added as new fields to the ingested documents. + +**PREREQUISITE**<br> +Before using the `ml_inference` processor, you must have either a local ML model hosted on your OpenSearch cluster or an externally hosted model connected to your OpenSearch cluster. For more information about local models, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). For more information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). +{: .note} + +## Syntax + +The following is the syntax for the `ml_inference` processor: + +```json +{ + "ml_inference": { + "model_id": "<model_id>", + "function_name": "<function_name>", + "full_response_path": "<full_response_path>", + "model_config":{ + "<model_config_field>": "<config_value>" + }, + "model_input": "<model_input>", + "input_map": [ + { + "<model_input_field>": "<document_field>" + } + ], + "output_map": [ + { + "<new_document_field>": "<model_output_field>" + } + ], + "override": "<override>" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `ml_inference` processor. + +| Parameter | Data type | Required/Optional | Description | +|:--- | :--- | :--- | :--- | +| `model_id` | String | Required | The ID of the ML model used by the processor. | +| `function_name` | String | Optional for externally hosted models<br/><br/>Required for local models | The function name of the ML model configured in the processor. For local models, valid values are `sparse_encoding`, `sparse_tokenize`, `text_embedding`, and `text_similarity`. For externally hosted models, valid value is `remote`. Default is `remote`. | +| `model_config` | Object | Optional | Custom configuration options for the ML model. For externally hosted models, if set, this configuration overrides the default connector parameters. For local models, you can add `model_config` to `model_input` to override the model configuration set during registration. For more information, see [The `model_config` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-model_config-object). | +| `model_input` | String | Optional for externally hosted models<br/><br/>Required for local models | A template that defines the input field format expected by the model. Each local model type might use a different set of inputs. For externally hosted models, default is `"{ \"parameters\": ${ml_inference.parameters} }`.| +| `input_map` | Array | Optional for externally hosted models<br/><br/>Required for local models | An array specifying how to map ingested document fields to the model input fields. Each element of the array is a map in the `"<model_input_field>": "<document_field>"` format and corresponds to one model invocation for a document field. If no input mapping is specified for an externally hosted model, then all fields from the document are passed to the model directly as input. The `input_map` size indicates the number of times the model is invoked (the number of Predict API requests). For externally hosted models, the model input fields are the parameters in the connector request body template. For more information, see [Providing input as parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-parameters). | +| `<model_input_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The model input field name. | +| `<document_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The name or JSON path of the ingested document field used as the model input. | +| `output_map` | Array | Optional for externally hosted models<br/><br/>Required for local models | An array specifying how to map the model output fields to new fields in the ingested document. Each element of the array is a map in the `"<new_document_field>": "<model_output_field>"` format.| +| `<new_document_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The name of the new field in the ingested document in which the model's output (specified by `model_output`) is stored. If no output mapping is specified for externally hosted models, then all fields from the model output are added to the new document field. | +| `<model_output_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The name or JSON path of the field in the model output to be stored in the `new_document_field`. | +| `full_response_path` | Boolean | Optional | Set this parameter to `true` if the `model_output_field` contains a full JSON path to the field instead of the field name. The model output will then be fully parsed to get the value of the field. Default is `true` for local models and `false` for externally hosted models. | +| `ignore_missing` | Boolean | Optional | If `true` and any of the input fields defined in the `input_map` or `output_map` are missing, then the missing fields are ignored. Otherwise, a missing field causes a failure. Default is `false`. | +| `ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If `true`, then any failure is ignored and ingestion continues. If `false`, then any failure causes ingestion to be canceled. Default is `false`. | +| `override` | Boolean | Optional | Relevant if an ingested document already contains a field with the name specified in `<new_document_field>`. If `override` is `false`, then the input field is skipped. If `true`, then the existing field value is overridden by the new model output. Default is `false`. | +| `max_prediction_tasks` | Integer | Optional | The maximum number of concurrent model invocations that can run during document ingestion. Default is `10`. | +| `description` | String | Optional | A brief description of the processor. | +| `if` | String containing a Boolean expression | Optional | A condition for running the processor. | +| `on_failure` | List | Optional | A list of processors to run if the processor fails. | +| `tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +The `input_map` and `output_map` mappings support standard [JSON path](https://github.com/json-path/JsonPath) notation for specifying complex data structures. +{: .note} + +## Using the processor + +Follow these steps to use the processor in a pipeline. You must provide a model ID when creating the processor. Before testing a pipeline or ingesting the documents using the processor, make sure that the model is successfully deployed. You can check the model state using the [Get Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/get-model/). + +For local models, you must provide a `model_input` field that specifies the model input format. Add any input fields in `model_config` to `model_input`. + +For remote models, the `model_input` field is optional, and its default value is `"{ \"parameters\": ${ml_inference.parameters} }`. + +### Example: Externally hosted model + +The following example configures an `ml_inference` processor with an externally hosted model. + +#### Step 1: Create a pipeline + +The following example creates an ingest pipeline for an externally hosted text embedding model. The model requires an `input` field and generates results in a `data` field. It converts the text in the `passage_text` field into text embeddings and stores the embeddings in the `passage_embedding` field. The `function_name` is not explicitly specified in the processor configuration, so it defaults to `remote`, signifying an externally hosted model: + +```json +PUT /_ingest/pipeline/ml_inference_pipeline +{ + "description": "Generate passage_embedding for ingested documents", + "processors": [ + { + "ml_inference": { + "model_id": "<your model id>", + "input_map": [ + { + "input": "passage_text" + } + ], + "output_map": [ + { + "passage_embedding": "data" + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +For a Predict API request to an externally hosted model, all fields are usually nested inside the `parameters` object: + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict +{ + "parameters": { + "input": [ + { + ... + } + ] + } +} +``` + +When specifying the `input_map` for an externally hosted model, you can directly reference the `input` field instead of providing its dot path `parameters.input`: + +```json +"input_map": [ + { + "input": "passage_text" + } +] +``` + +Each key in the `input_map` names a parameter that fills a placeholder in the connector request body template. In this example, the `input` key fills the `${parameters.input}` placeholder. For more information, see [Providing input as parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-parameters). + +#### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/ml_inference_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source":{ + "passage_text": "hello world" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response confirms that the processor has generated text embeddings in the `passage_embedding` field. The document now contains both the `passage_text` and `passage_embedding` fields: + +```json +{ + "docs" : [ + { + "doc" : { + "_index" : "testindex1", + "_id" : "1", + "_source" : { + "passage_embedding" : [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ... + ], + "passage_text" : "hello world" + }, + "_ingest" : { + "timestamp" : "2023-10-11T22:35:53.654650086Z" + } + } + } + ] +} +``` + +Once you have created an ingest pipeline, you need to create an index for ingestion and ingest documents into the index. +{: .note} + +### Example: Local model + +The following example configures an `ml_inference` processor with a local model. + +#### Step 1: Create a pipeline + +The following example creates an ingest pipeline for the `huggingface/sentence-transformers/all-distilroberta-v1` local model. The model is a sentence transformer [pretrained model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#sentence-transformers) hosted in your OpenSearch cluster. + +If you invoke the model using the Predict API, then the request looks like this: + +```json +POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs":[ "today is sunny"], + "return_number": true, + "target_response": ["sentence_embedding"] +} +``` + +Using this schema, specify the `model_input` as follows: + +```json + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }" +``` + +In the `input_map`, map the `book.*.chunk.text.*.context` document field to the `text_docs` field expected by the model: + +```json +"input_map": [ + { + "text_docs": "book.*.chunk.text.*.context" + } +] +``` + +Because you specified the field to convert into embeddings as a JSON path, you need to set the `full_response_path` to `true` so that the full JSON document is parsed to obtain the input field: + +```json +"full_response_path": true +``` + +The documents you index will appear as follows. The text in the `context` field will be used to generate embeddings: + +```json +"book": [ + { + "chunk": { + "text": [ + { + "chapter": "first chapter", + "context": "this is the first part" + } + ] + } + } +] +``` + +The Predict API request returns the following response: + +```json +{ + "inference_results" : [ + { + "output" : [ + { + "name" : "sentence_embedding", + "data_type" : "FLOAT32", + "shape" : [ + 768 + ], + "data" : [ + 0.25517133, + -0.28009856, + 0.48519906, + ... + ] + } + ] + } + ] +} +``` + +The model generates embeddings in the `$.inference_results.*.output.*.data` field. The `output_map` maps this field to the newly created `book.*.chunk.text.*.context_embedding` field in the ingested document: + +```json +"output_map": [ + { + "book.*.chunk.text.*.context_embedding": "$.inference_results.*.output.*.data" + } +] +``` + +To configure an `ml_inference` processor with a local model, specify the `function_name` explicitly. In this example, `function_name` is `text_embedding`. For information about valid `function_name` values, see [Parameters](#parameters). + +In this example, the final configuration of the `ml_inference` processor with the local model is as follows: + +```json +PUT /_ingest/pipeline/ml_inference_pipeline_local +{ + "description": "ingests reviews and generates embeddings", + "processors": [ + { + "ml_inference": { + "function_name": "text_embedding", + "full_response_path": true, + "model_id": "<your model id>", + "model_config": { + "return_number": true, + "target_response": ["sentence_embedding"] + }, + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }", + "input_map": [ + { + "text_docs": "book.*.chunk.text.*.context" + } + ], + "output_map": [ + { + "book.*.chunk.text.*.context_embedding": "$.inference_results.*.output.*.data" + } + ], + "ignore_missing": true, + "ignore_failure": true + } + } + ] +} +``` +{% include copy-curl.html %} + +#### Step 2 (Optional): Test the pipeline + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/ml_inference_pipeline/_simulate +{ + "docs": [ + { + "_index": "my_books", + "_id": "1", + "_source": { + "book": [ + { + "chunk": { + "text": [ + { + "chapter": "first chapter", + "context": "this is the first part" + }, + { + "chapter": "first chapter", + "context": "this is the second part" + } + ] + } + }, + { + "chunk": { + "text": [ + { + "chapter": "second chapter", + "context": "this is the third part" + }, + { + "chapter": "second chapter", + "context": "this is the fourth part" + } + ] + } + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The response confirms that the processor has generated text embeddings in the `context_embedding` field. The document now contains both the `context` and `context_embedding` fields at the same path: + +```json +{ + "docs" : [ + { + "doc" : { + "_index": "my_books", + "_id": "1", + "_source": { + "book": [ + { + "chunk": { + "text": [ + { + "chapter": "first chapter", + "context": "this is the first part", + "context_embedding": [ + 0.15756914, + 0.05150984, + 0.25225413, + 0.4941875, + ... + ] + }, + { + "chapter": "first chapter", + "context": "this is the second part", + "context_embedding": [ + 0.10526893, + 0.026559234, + 0.28763372, + 0.4653795, + ... + ] + } + ] + } + }, + { + "chunk": { + "text": [ + { + "chapter": "second chapter", + "context": "this is the third part", + "context_embedding": [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ... + ] + }, + { + "chapter": "second chapter", + "context": "this is the fourth part", + "context_embedding": [ + 0.37742054, + 0.046911318, + 1.2053889, + 0.04663613, + ... + ] + } + ] + } + } + ] + } + } + } + ] +} +``` + +Once you have created an ingest pipeline, you need to create an index for ingestion and ingest documents into the index. +{: .note} + +## Next steps + +- For a complete example of generating text and image embeddings during ingestion, see [Multimodal search using ML inference processors]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-search/multimodal-search-ml-inference/). +- For a complete example of detecting document language during ingestion, see [Identifying document language for multilingual search]({{site.url}}{{site.baseurl}}/tutorials/language-identification/). +- For a complete example of generating embeddings for text chunks, see [Semantic search using text chunking]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-search/long-document/). \ No newline at end of file diff --git a/_ingest-pipelines/processors/pipeline.md b/_ingest-pipelines/processors/pipeline.md new file mode 100644 index 00000000..ac25999f --- /dev/null +++ b/_ingest-pipelines/processors/pipeline.md @@ -0,0 +1,248 @@ +--- +layout: default +title: Pipeline +parent: Ingest processors +nav_order: 220 +--- + +# Pipeline processor + +The `pipeline` processor allows a pipeline to reference and include another predefined pipeline. This can be useful when you have a set of common processors that need to be shared across multiple pipelines. Instead of redefining those common processors in each pipeline, you can create a separate base pipeline containing the shared processors and then reference that base pipeline from other pipelines using the pipeline processor. + +The following is the syntax for the `pipeline` processor: + +```json +{ + "pipeline": { + "name": "general-pipeline" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `pipeline` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`name` | Required | The name of the pipeline to execute. Supports [template snippets](#selecting-a-pipeline-dynamically). +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Optional | Specifies to handle processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`tag` | Optional | An identifier for the processor. Useful for debugging and metrics. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `general-pipeline` that converts the `protocol` field to uppercase and removes the `name` field: + +```json +PUT _ingest/pipeline/general-pipeline +{ + "description": "a general pipeline", + "processors": [ + { + "uppercase": { + "field": "protocol" + } + }, + { + "remove": { + "field": "name" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following query creates a pipeline named `outer-pipeline` that uses the `pipeline` processor to run `general-pipeline`: + +```json +PUT _ingest/pipeline/outer-pipeline +{ + "description": "an outer pipeline referencing the general pipeline", + "processors": [ + { + "pipeline": { + "name": "general-pipeline" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/outer-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "protocol": "https", + "name":"test" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "protocol": "HTTPS" + }, + "_ingest": { + "timestamp": "2024-05-24T02:43:43.700735801Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +POST testindex1/_doc/1?pipeline=outer-pipeline +{ + "protocol": "https", + "name": "test" +} +``` +{% include copy-curl.html %} + +The request indexes the document into the `testindex1` index with the `protocol` field converted to uppercase and the `name` field removed, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 2, + "result": "created", + "_shards": { + "total": 2, + "successful": 2, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Selecting a pipeline dynamically + +The `name` parameter supports template snippets, so you can select the pipeline to run based on a field value in the document. The following request creates a pipeline that parses NGINX logs: + +```json +PUT _ingest/pipeline/logs-nginx +{ + "processors": [ + { + "set": { + "field": "parsed_by", + "value": "{% raw %}{{_ingest.pipeline}}{% endraw %}" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following request creates a pipeline that runs the pipeline named `logs-` followed by the value of the document's `service` field: + +```json +PUT _ingest/pipeline/logs-router +{ + "processors": [ + { + "set": { + "field": "routed_by", + "value": "{% raw %}{{_ingest.pipeline}}{% endraw %}" + } + }, + { + "pipeline": { + "name": "logs-{% raw %}{{service}}{% endraw %}" + } + } + ] +} +``` +{% include copy-curl.html %} + +Index a document whose `service` field is `nginx`: + +```json +PUT logs/_doc/1?pipeline=logs-router +{ + "service": "nginx", + "message": "GET /index.html 200" +} +``` +{% include copy-curl.html %} + +Retrieve the document: + +```json +GET logs/_doc/1 +``` +{% include copy-curl.html %} + +The response shows that the `logs-router` pipeline ran the `logs-nginx` pipeline: + +```json +{ + "_index": "logs", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "parsed_by": "logs-nginx", + "service": "nginx", + "message": "GET /index.html 200", + "routed_by": "logs-router" + } +} +``` + +If the resolved pipeline doesn't exist, or if running it would create a cycle in which a pipeline runs itself, the `pipeline` processor fails. + +## Accessing the current pipeline name + +The `_ingest.pipeline` ingest metadata field contains the ID of the pipeline that is currently running. In the preceding example, the `routed_by` field contains `logs-router` and the `parsed_by` field contains `logs-nginx` because each `set` processor ran in a different pipeline. After the inner pipeline completes, `_ingest.pipeline` again contains the ID of the outer pipeline. diff --git a/_ingest-pipelines/processors/remove-by-pattern.md b/_ingest-pipelines/processors/remove-by-pattern.md new file mode 100644 index 00000000..0d3f1a35 --- /dev/null +++ b/_ingest-pipelines/processors/remove-by-pattern.md @@ -0,0 +1,133 @@ +--- +layout: default +title: Remove by pattern +parent: Ingest processors +nav_order: 225 +redirect_from: + - /ingest-pipelines/processors/remove_by_pattern/ +--- + +# Remove by pattern processor + +The `remove_by_pattern` processor removes the root-level fields from a document by using specified wildcard patterns. + +## Syntax + +The following is the syntax for the `remove_by_pattern` processor: + +```json +{ + "remove_by_pattern": { + "field_pattern": "field_name_prefix*" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `remove_by_pattern` processor. + +| Parameter | Required/Optional | Description | +|---|---|---| +`field_pattern` | Optional | Removes fields that match the specified pattern. All of the metadata fields, such as `_index`, `_version`, `_version_type`, and `_id`, are ignored if they match the pattern. This option only supports the root-level fields in the document. | +`exclude_field_pattern` | Optional | Removes fields that do not match the specified pattern. All of the metadata fields, such as `_index`, `_version`, `_version_type`, and `_id`, are ignored if they do not match the pattern. This option only supports the root-level fields in the document. The `field_pattern` and `exclude_field_pattern` options are mutually exclusive. | +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, the failure is ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `remove_fields_by_pattern` that removes the fields that match the pattern `foo*`: + +```json +PUT /_ingest/pipeline/remove_fields_by_pattern +{ + "description": "Pipeline that removes the fields by patterns.", + "processors": [ + { + "remove_by_pattern": { + "field_pattern": "foo*" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/remove_fields_by_pattern/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source":{ + "foo1": "foo1", + "foo2": "foo2", + "bar": "bar" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "bar": "bar" + }, + "_ingest": { + "timestamp": "2023-08-24T18:02:13.218986756Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=remove_fields_by_pattern +{ + "foo1": "foo1", + "foo2": "foo2", + "bar": "bar" +} +``` +{% include copy-curl.html %} + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/remove.md b/_ingest-pipelines/processors/remove.md index 9656f437..bd95a552 100644 --- a/_ingest-pipelines/processors/remove.md +++ b/_ingest-pipelines/processors/remove.md @@ -2,7 +2,7 @@ layout: default title: Remove parent: Ingest processors -nav_order: 230 +nav_order: 222 redirect_from: - /api-reference/ingest-apis/processors/remove/ --- @@ -22,27 +22,41 @@ The following is the syntax for the `remove` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +To remove multiple fields, specify an array of field names: + +```json +{ + "remove": { + "field": ["field_name_1", "field_name_2"] + } +} +``` +{% include copy.html %} + +The `exclude_field` parameter also accepts an array of field names to retain. + +## Parameters The following table lists the required and optional parameters for the `remove` processor. | Parameter | Required/Optional | Description | |---|---|---| -`field` | Optional | The field name containing the data to be removed. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). The metadata fields `_index`, `_version`, `_version_type`, and `_id` cannot be removed. If `version` is specified, `_id` cannot be removed from the ingested document. | -`exclude_field` | Optional | The field name to be retained. All other fields, except metadata fields, will be removed. The `exclude_field` and `field` options are mutually exclusive. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`field` | Optional | The field name containing the data to be removed. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). The metadata fields `_index`, `_version`, and `_version_type` cannot be removed. The `_id` field cannot be removed if the request specifies an external version type. Either `field` or `exclude_field` must be specified. | +`exclude_field` | Optional | The field name to be retained. All other fields, except metadata fields, will be removed. The `exclude_field` and `field` options are mutually exclusive. Only top-level field names are supported. If you specify a nested field such as `user.name`, it doesn't match any top-level field, so the processor removes all fields, including the entire `user` object. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist. Default is `false`. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline The following query creates a pipeline, named `remove_ip`, that removes the `ip_address` field from a document: @@ -61,7 +75,7 @@ PUT /_ingest/pipeline/remove_ip ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -85,8 +99,6 @@ POST _ingest/pipeline/remove_ip/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -108,7 +120,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -121,7 +133,7 @@ PUT testindex1/_doc/1?pipeline=remove_ip ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -129,3 +141,57 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Removing multiple fields + +The following request removes the `internal_sku` and `warehouse_code` fields from a document: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "remove": { + "field": ["internal_sku", "warehouse_code"] + } + } + ] + }, + "docs": [ + { + "_source": { + "product": "Wireless mouse", + "internal_sku": "WM-4471", + "warehouse_code": "SEA-02", + "price": 24.99 + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows that both fields were removed: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "product": "Wireless mouse", + "price": 24.99 + }, + "_ingest": { + "timestamp": "2026-10-14T19:44:03.195795881Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/processors/rename.md b/_ingest-pipelines/processors/rename.md new file mode 100644 index 00000000..d8cfde69 --- /dev/null +++ b/_ingest-pipelines/processors/rename.md @@ -0,0 +1,142 @@ +--- +layout: default +title: Rename +parent: Ingest processors +nav_order: 227 +redirect_from: + - /api-reference/ingest-apis/processors/rename/ +--- + +# Rename processor + +The `rename` processor is used to rename an existing field, which can also be used to move a field from one object to another object or to the root level. + +## Syntax + +The following is the syntax for the `rename` processor: + +```json +{ + "rename": { + "field": "field_name", + "target_field" : "target_field_name" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `rename` processor. + +Parameter | Required/Optional | Description | +---|---|---| +`field` | Required | The name of the field to be renamed. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`target_field` | Required | The new name of the field. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified `field`. If set to `true`, the processor does not modify the document if the `field` does not exist. If set to `false`, the processor fails if the `field` does not exist. Default is `false`. | +`override_target` | Optional | Determines what happens when `target_field` exists in the document. If set to `true`, the processor overwrites the existing `target_field` value with the new value. If set to `false` and `target_field` exists, the processor fails. Default is `false`. | +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, failures are ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `rename_field` that moves a field in an object to the root level: + +```json +PUT /_ingest/pipeline/rename_field +{ + "description": "Pipeline that moves a field to the root level.", + "processors": [ + { + "rename": { + "field": "message.content", + "target_field": "content" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before ingesting documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/rename_field/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source":{ + "message": { + "type": "nginx", + "content": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "message": { + "type": "nginx" + }, + "content": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456" + }, + "_ingest": { + "timestamp": "2024-04-15T07:54:16.010447Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=rename_field +{ + "message": { + "type": "nginx", + "content": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456" + } +} +``` +{% include copy-curl.html %} + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/script.md b/_ingest-pipelines/processors/script.md new file mode 100644 index 00000000..d83e8d87 --- /dev/null +++ b/_ingest-pipelines/processors/script.md @@ -0,0 +1,207 @@ +--- +layout: default +title: Script +parent: Ingest processors +nav_order: 230 +--- + +# Script ingest processor + +The `script` processor executes inline and stored scripts that can modify or transform data in an OpenSearch document during the ingestion process. The processor uses script caching for improved performance because scripts may be recompiled per document. Refer to [Script APIs]({{site.url}}{{site.baseurl}}/api-reference/script-apis/index/) for information about working with scripts in OpenSearch. + +The following is the syntax for the `script` processor: + +```json +{ + "script": { + "source": "<script_source>", + "lang": "<script_language>", + "params": { + "<param_name>": "<param_value>" + } + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `script` processor. + +| Parameter | Required/Optional | Description | +|---|---|---| +`source` | Optional | The Painless script to be executed. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). Either `id` or `source` must be specified---but not both. If `source` is specified, then the script is executed using the provided source code. +`id` | Optional | The ID of a stored script previously created using the [Create Stored Script API]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/). Either `id` or `source` must be specified, but not both. If `id` is specified, then the script source is retrieved from the stored script with the specified ID. +`lang` | Optional | The programming language of the script. Default is `painless`. +`params` | Optional | The parameters that can be passed to the script. +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Optional | Specifies a list of processors to run if the processor fails during execution. These processors are executed in the order they are specified. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `my-script-pipeline` that uses the `script` processor to convert the `message` field to uppercase: + +```json +PUT _ingest/pipeline/my-script-pipeline +{ + "description": "Example pipeline using the ScriptProcessor", + "processors": [ + { + "script": { + "source": "ctx.message = ctx.message.toUpperCase()", + "lang": "painless", + "description": "Convert message field to uppercase" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/my-script-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "message": "hello, world!" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "HELLO, WORLD!" + }, + "_ingest": { + "timestamp": "2024-05-30T16:24:23.30265405Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=my-script-pipeline +{ + "message": "hello, world!" +} +``` +{% include copy-curl.html %} + +The response confirms that the document has been indexed into `testindex1` and has indexed all documents with the `message` field converted to uppercase: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 2 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Using parameters and modifying metadata + +In the script, the `ctx` variable provides access to the document fields and metadata fields, such as `_index`. Parameters passed in `params` are available in the script as `params.<name>`. When values are passed as parameters, the script source stays the same as the values change, so OpenSearch can reuse the compiled script. For more information, see [How to use scripts]({{site.url}}{{site.baseurl}}/scripting/using-scripts/). + +The following request calculates a total price using a discount passed as a parameter and changes the target index of the document: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "script": { + "source": "ctx.total_price = ctx.unit_price * ctx.quantity * (1 - params.discount); ctx._index = params.target_index;", + "params": { + "discount": 0.1, + "target_index": "orders-processed" + } + } + } + ] + }, + "docs": [ + { + "_index": "orders-raw", + "_source": { + "unit_price": 20.0, + "quantity": 3 + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows the calculated `total_price` and the changed `_index`: + +```json +{ + "docs": [ + { + "doc": { + "_index": "orders-processed", + "_id": "_id", + "_source": { + "quantity": 3, + "unit_price": 20.0, + "total_price": 54.0 + }, + "_ingest": { + "timestamp": "2026-10-14T20:10:38.9908023Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/processors/set.md b/_ingest-pipelines/processors/set.md new file mode 100644 index 00000000..e916c581 --- /dev/null +++ b/_ingest-pipelines/processors/set.md @@ -0,0 +1,213 @@ +--- +layout: default +title: Set +parent: Ingest processors +nav_order: 240 +--- + +# Set processor + +The `set` processor adds or updates fields in a document. It sets one field and associates it with the specified value. If the field already exists, then its value is replaced with the provided one unless the `override` parameter is set to `false`. When `override` is `false` and the specified field exists and isn't `null`, the value of the field remains unchanged. A field whose value is `null` is always overwritten. + +The following is the syntax for the `set` processor: + +```json +{ + "description": "...", + "processors": [ + { + "set": { + "field": "new_field", + "value": "some_value" + } + } + ] +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `set` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The name of the field to be set or updated. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). +`value` | Required | The value assigned to the field. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). +`override` | Optional | A Boolean flag that determines whether the processor should override the existing value of the field. Default is `true`. +`ignore_empty_value` | Optional | A Boolean flag that determines whether the processor should ignore `null` values or empty strings. Default is `false`. +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Optional | Specifies a list of processors to run if the processor fails during execution. These processors are executed in the order they are specified. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `set-pipeline` that uses the `set` processor to add a new field `new_field` with the value `some_value` to the document: + +```json +PUT _ingest/pipeline/set-pipeline +{ + "description": "Adds a new field 'new_field' with the value 'some_value'", + "processors": [ + { + "set": { + "field": "new_field", + "value": "some_value" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/set-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "existing_field": "value" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "existing_field": "value", + "new_field": "some_value" + }, + "_ingest": { + "timestamp": "2024-05-30T21:56:15.066180712Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +POST testindex1/_doc?pipeline=set-pipeline +{ + "existing_field": "value" +} +``` +{% include copy-curl.html %} + +The request indexes the document into the `testindex1` index with the `new_field` field set to `some_value`, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Copying a value from another field + +To copy a value from one field to another, reference the source field in `value` using a template snippet. The following request copies the value of the `customer.address.city` field to the `shipping.city` field: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "set": { + "field": "shipping.city", + "value": "{% raw %}{{{customer.address.city}}}{% endraw %}" + } + } + ] + }, + "docs": [ + { + "_source": { + "customer": { + "address": { + "city": "Portland" + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows that the `shipping.city` field contains the copied value: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "shipping": { + "city": "Portland" + }, + "customer": { + "address": { + "city": "Portland" + } + } + }, + "_ingest": { + "timestamp": "2026-10-14T19:44:03.269176256Z" + } + } + } + ] +} +``` + +Template snippets always produce a string. For example, copying a numeric field value of `24.99` produces the string `"24.99"`. To copy a value while preserving its type, or to copy an entire object, use the [`copy` processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/copy/). diff --git a/_ingest-pipelines/processors/sort.md b/_ingest-pipelines/processors/sort.md new file mode 100644 index 00000000..39ebbf19 --- /dev/null +++ b/_ingest-pipelines/processors/sort.md @@ -0,0 +1,171 @@ +--- +layout: default +title: Sort +parent: Ingest processors +nav_order: 250 +--- + +# Sort ingest processor + +The `sort` processor sorts an array of items in either ascending or descending order. Numeric arrays are sorted numerically, while string or mixed arrays (strings and numbers) are sorted lexicographically. The processor throws an error if the input is not an array. + +The following is the syntax for the `sort` processor: + +```json +{ + "description": "Sort an array of items", + "processors": [ + { + "sort": { + "field": "my_array_field", + "order": "desc" + } + } + ] +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `sort` processor. + +| Parameter | Required/Optional | Description | +|---|---|---| +`field` | Required | The field to be sorted. Must be an array. +`order` | Optional | The sort order to apply. Accepts `asc` for ascending or `desc` for descending. Default is `asc`. +`target_field` | Optional | The name of the field in which the sorted array is stored. If not specified, then the sorted array is stored in the same field as the original array (the `field` variable). +`description` | Optional | A description of the processor's purpose or configuration. +`if` | Optional | Specifies to conditionally execute the processor. +`ignore_failure` | Optional | Specifies to ignore processor failures. See [Handling pipeline failures]({{site.url}}{{site.baseurl}}/ingest-pipelines/pipeline-failures/). +`on_failure` | Optional | Specifies a list of processors to run if the processor fails during execution. These processors are executed in the order they are specified. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `sort-pipeline` that uses the `sort` processor to sort the `my_field` in descending order and store the sorted values in the `sorted_field`: + +```json +PUT _ingest/pipeline/sort-pipeline +{ + "description": "Sort an array of items in descending order", + "processors": [ + { + "sort": { + "field": "my_array_field", + "order": "desc", + "target_field": "sorted_array" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/sort-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "my_array_field": [3, 1, 4, 1, 5, 9, 2, 6, 5] + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "sorted_array": [ + 9, + 6, + 5, + 5, + 4, + 3, + 2, + 1, + 1 + ], + "my_array_field": [ + 3, + 1, + 4, + 1, + 5, + 9, + 2, + 6, + 5 + ] + }, + "_ingest": { + "timestamp": "2024-05-30T22:10:13.405692128Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +POST testindex1/_doc?pipeline=sort-pipeline +{ + "my_array_field": [3, 1, 4, 1, 5, 9, 2, 6, 5] +} +``` +{% include copy-curl.html %} + +The request indexes the document into the index `testindex1` and then indexes all documents with the `my_array_field` sorted in descending order, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "no-Py48BwFahnwl9KZzf", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 9, + "_primary_term": 2 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/no-Py48BwFahnwl9KZzf +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/sparse-encoding.md b/_ingest-pipelines/processors/sparse-encoding.md index 1f86447e..64b1f464 100644 --- a/_ingest-pipelines/processors/sparse-encoding.md +++ b/_ingest-pipelines/processors/sparse-encoding.md @@ -2,7 +2,7 @@ layout: default title: Sparse encoding parent: Ingest processors -nav_order: 240 +nav_order: 252 redirect_from: - /api-reference/ingest-apis/processors/sparse-encoding/ --- @@ -27,26 +27,49 @@ The following is the syntax for the `sparse_encoding` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `sparse_encoding` processor. | Parameter | Data type | Required/Optional | Description | |:---|:---|:---|:---| `model_id` | String | Required | The ID of the model that will be used to generate the embeddings. The model must be deployed in OpenSearch before it can be used in neural search. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). +`prune_type` | String | Optional | The prune strategy for sparse vectors. Valid values are `max_ratio`, `alpha_mass`, `top_k`, `abs_value`, and `none`. Default is `none`. +`prune_ratio` | Float | Optional | The ratio for the pruning strategy. Required when `prune_type` is specified. `field_map` | Object | Required | Contains key-value pairs that specify the mapping of a text field to a `rank_features` field. `field_map.<input_field>` | String | Required | The name of the field from which to obtain text for generating vector embeddings. `field_map.<vector_field>` | String | Required | The name of the vector field in which to store the generated vector embeddings. `description` | String | Optional | A brief description of the processor. | -`tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | +`tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +`if` | String containing a Boolean expression | Optional | A condition for running the processor. | +`ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, the processor failure is ignored. Default is `false`. | +`on_failure` | List | Optional | A list of processors to run if the processor fails. | +`batch_size` | Integer | Optional | Specifies the number of documents to be batched and processed each time. Default is `1`. If you specify `if`, the processor doesn't batch documents and processes them one at a time. | +`skip_existing` | Boolean | Optional | When `true`, the processor does not make inference calls for fields that already contain embeddings, leaving existing embeddings unchanged. Default is `false`.| + +### Pruning sparse vectors + +A sparse vector often has a long-tail distribution of token weights, with less important tokens occupying a significant amount of storage space. Pruning reduces the size of an index by removing tokens with lower semantic importance, yielding a slight decrease in search relevance in exchange for a more compact index. + +The `sparse_encoding` processor can be used to prune sparse vectors by configuring the `prune_type` and `prune_ratio` parameters. The following table lists the supported pruning options for the `sparse_encoding` processor. + +| Pruning type | Valid pruning ratio | Description | +|:---|:---|:---| +`max_ratio` | Float [0, 1) | Prunes a sparse vector by keeping only elements whose values are within the `prune_ratio` of the largest value in the vector. +`abs_value` | Float (0, +∞) | Prunes a sparse vector by removing elements with values lower than the `prune_ratio`. +`alpha_mass` | Float [0, 1) | Prunes a sparse vector by keeping only elements whose cumulative sum of values is within the `prune_ratio` of the total sum. +`top_k` | Integer (0, +∞) | Prunes a sparse vector by keeping only the top `prune_ratio` elements. +`none` | N/A | Leaves sparse vectors unchanged. + +Among all pruning options, specifying `max_ratio` as equal to `0.1` demonstrates strong generalization on test datasets. This approach reduces storage requirements by approximately 40% while incurring less than a 1% loss in search relevance. ## Using the processor Follow these steps to use the processor in a pipeline. You must provide a model ID when creating the processor. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). -**Step 1: Create a pipeline.** +### Step 1: Create a pipeline The following example request creates an ingest pipeline where the text from `passage_text` will be converted into text embeddings and the embeddings will be stored in `passage_embedding`: @@ -58,6 +81,8 @@ PUT /_ingest/pipeline/nlp-ingest-pipeline { "sparse_encoding": { "model_id": "aP2Q8ooBpBj3wT4HVS8a", + "prune_type": "max_ratio", + "prune_ratio": 0.1, "field_map": { "passage_text": "passage_embedding" } @@ -68,7 +93,7 @@ PUT /_ingest/pipeline/nlp-ingest-pipeline ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline.** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -91,8 +116,6 @@ POST _ingest/pipeline/nlp-ingest-pipeline/_simulate ``` {% include copy-curl.html %} -#### Response - The response confirms that in addition to the `passage_text` field, the processor has generated text embeddings in the `passage_embedding` field: ```json @@ -110,23 +133,15 @@ The response confirms that in addition to the `passage_text` field, the processo "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 }, "passage_text" : "hello world" @@ -140,7 +155,7 @@ The response confirms that in addition to the `passage_text` field, the processo } ``` -Once you have created an ingest pipeline, you need to create an index for ingestion and ingest documents into the index. To learn more, see [Step 2: Create an index for ingestion]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/#step-2-create-an-index-for-ingestion) and [Step 3: Ingest documents into the index]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/#step-3-ingest-documents-into-the-index) of [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). +Once you have created an ingest pipeline, you need to create an index for ingestion and ingest documents into the index. For a complete example, see [Generating sparse vector embeddings automatically]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-with-pipelines/). --- @@ -149,4 +164,4 @@ Once you have created an ingest pipeline, you need to create an index for ingest - To learn how to use the `neural_sparse` query for a sparse search, see [Neural sparse query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural-sparse/). - To learn more about sparse search, see [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). - To learn more about using models in OpenSearch, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). -- For a comprehensive example, see [Neural search tutorial]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). +- For a comprehensive example, see [Getting started with semantic and hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). diff --git a/_ingest-pipelines/processors/split.md b/_ingest-pipelines/processors/split.md new file mode 100644 index 00000000..9235dfc6 --- /dev/null +++ b/_ingest-pipelines/processors/split.md @@ -0,0 +1,211 @@ +--- +layout: default +title: Split +parent: Ingest processors +nav_order: 255 +--- + +# Split ingest processor + +The `split` processor is used to split a string field into an array of substrings based on a specified delimiter. + +The following is the syntax for the `split` processor: + +```json +{ + "split": { + "field": "field_to_split", + "separator": "<delimiter>", + "target_field": "split_field" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `split` processor. + +Parameter | Required/Optional | Description +:--- | :--- | :--- +`field` | Required | The field containing the string to be split. +`separator` | Required | A regular expression that matches the delimiter used to split the string. To split on a character that has a special meaning in regular expressions, such as `.` or `+`, escape it, for example, `\\.`. +`preserve_trailing` | Optional | If set to `true`, preserves empty trailing fields (for example, `''`) in the resulting array. If set to `false`, then empty trailing fields are removed from the resulting array. Default is `false`. +`target_field` | Optional | The field where the array of substrings is stored. If not specified, then the field is updated in-place. +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, then the processor ignores missing values in the field and leaves the `target_field` unchanged. Default is `false`. +`description` | Optional | A brief description of the processor. +`if` | Optional | A condition for running the processor. +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. +`on_failure` | Optional | A list of processors to run if the processor fails. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `split_pipeline` that uses the `split` processor to split the `log_message` field on the comma character and store the resulting array in the `log_parts` field: + +```json +PUT _ingest/pipeline/split_pipeline +{ + "description": "Split log messages by comma", + "processors": [ + { + "split": { + "field": "log_message", + "separator": ",", + "target_field": "log_parts" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/split_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "log_message": "error,warning,info" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "log_message": "error,warning,info", + "log_parts": [ + "error", + "warning", + "info" + ] + }, + "_ingest": { + "timestamp": "2024-04-26T22:29:23.207849376Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=split_pipeline +{ + "log_message": "error,warning,info" +} +``` +{% include copy-curl.html %} + +The request indexes the document into the index `testindex1` and splits the `log_message` field on the comma delimiter and stores the result in the `log_parts` field before indexing, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 70, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 72, + "_primary_term": 47 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Preserving empty trailing fields + +By default, the `split` processor removes empty trailing elements from the resulting array. The following request splits the same value with and without `preserve_trailing`: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "split": { + "field": "colors", + "separator": "," + } + }, + { + "split": { + "field": "colors_preserved", + "separator": ",", + "preserve_trailing": true + } + } + ] + }, + "docs": [ + { + "_source": { + "colors": "red,green,,", + "colors_preserved": "red,green,," + } + } + ] +} +``` +{% include copy-curl.html %} + +In the response, the `colors` array contains only the two non-empty elements, while the `colors_preserved` array also contains the two empty trailing elements: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "colors": ["red", "green"], + "colors_preserved": ["red", "green", "", ""] + }, + "_ingest": { + "timestamp": "2026-10-14T19:44:03.298240422Z" + } + } + } + ] +} +``` diff --git a/_ingest-pipelines/processors/text-chunking.md b/_ingest-pipelines/processors/text-chunking.md new file mode 100644 index 00000000..5843e8d2 --- /dev/null +++ b/_ingest-pipelines/processors/text-chunking.md @@ -0,0 +1,270 @@ +--- +layout: default +title: Text chunking +parent: Ingest processors +nav_order: 258 +--- + +# Text chunking processor + +The `text_chunking` processor splits a long document into shorter passages. The processor supports the following algorithms for text splitting: + +- [`fixed_token_length`](#the-fixed-token-length-algorithm): Splits text into passages of the length specified by the number of tokens. +- [`fixed_char_length`](#the-fixed-character-length-algorithm): Splits text into passages of the length specified by the number of characters. +- [`delimiter`](#the-delimiter-algorithm): Splits text into passages on a delimiter. + +The following is the syntax for the `text_chunking` processor: + +```json +{ + "text_chunking": { + "field_map": { + "<input_field>": "<output_field>" + }, + "algorithm": { + "<name>": "<parameters>" + } + } +} +``` + +## Parameters + +The following table lists the required and optional parameters for the `text_chunking` processor. + +| Parameter | Data type | Required/Optional | Description | +|:----------------------------|:----------|:---|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `field_map` | Object | Required | Contains key-value pairs that specify the mapping of a text field to the output field. | +| `field_map.<input_field>` | String | Required | The name of the field from which to obtain text for generating chunked passages. | +| `field_map.<output_field>` | String | Required | The name of the field in which to store the chunked results. | +| `algorithm` | Object | Required | Contains at most one key-value pair that specifies the chunking algorithm and parameters. | +| `algorithm.<name>` | String | Optional | The name of the chunking algorithm. Valid values are [`fixed_token_length`](#the-fixed-token-length-algorithm), [`fixed_char_length`](#the-fixed-character-length-algorithm), and [`delimiter`](#the-delimiter-algorithm). Default is `fixed_token_length`. | +| `algorithm.<parameters>` | Object | Optional | The parameters for the chunking algorithm. By default, contains the default parameters of the `fixed_token_length` algorithm. | +| `ignore_missing` | Boolean | Optional | If `true`, empty fields are excluded from the output. If `false`, the output will contain an empty list for every empty field. Default is `false`. | +| `description` | String | Optional | A brief description of the processor. | +| `tag` | String | Optional | An identifier tag for the processor. Useful when debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +| `if` | String containing a Boolean expression | Optional | A condition for running the processor. | +| `ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, the processor failure is ignored. Default is `false`. | +| `on_failure` | List | Optional | A list of processors to run if the processor fails. | + +To perform chunking on nested fields, specify `input_field` and `output_field` values as JSON objects. Dot paths of nested fields are not supported. For example, use `"field_map": { "foo": { "bar": "bar_chunk"} }` instead of `"field_map": { "foo.bar": "foo.bar_chunk"}`. +{: .note} + +### The fixed token length algorithm + +The following table lists the optional parameters for the `fixed_token_length` algorithm. + +| Parameter | Data type | Required/Optional | Description | +|:---|:----------|:---|:---| +| `token_limit` | Integer | Optional | The maximum number of tokens in a chunk. Valid values are integers of at least `1`. Default is `384`, which is calculated as `512 (tokens) * 0.75` so that chunks don't exceed the 512-token input limit of the [OpenSearch-supported pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#supported-pretrained-models). The `standard` tokenizer splits text into words, and according to [OpenAI](https://platform.openai.com/docs/introduction), 1 token equals approximately 0.75 words of English text. | +| `tokenizer` | String | Optional | The [word tokenizer]({{site.url}}{{site.baseurl}}/analyzers/tokenizers/index/#word-tokenizers) name. Default is `standard`. | +| `overlap_rate` | Float | Optional | The degree of overlap between chunks. Valid values are floats between `0` and `0.5`, inclusive. Default is `0`. As suggested by [Amazon Bedrock](https://aws.amazon.com/blogs/aws/knowledge-bases-now-delivers-fully-managed-rag-experience-in-amazon-bedrock/), we recommend a value of 0--0.2 to improve accuracy. | +| `max_chunk_limit` | Integer | Optional | The maximum number of chunks. If the processor generates more chunks than this limit, the excess text is added to the last chunk. Default is `100`. To disable this parameter, set it to `-1`. | + +### The fixed character length algorithm + +The following table lists the optional parameters for the `fixed_char_length` algorithm. + +| Parameter | Data type | Required/Optional | Description | +|:---|:----------|:---|:---| +| `char_limit` | Integer | Optional | The maximum number of characters in a chunk. Valid values are integers of at least `1`. Default is `2048`, which is calculated as `512 (tokens) * 4 (chars)` because 512 tokens is a common limit for text embedding models. According to [OpenAI](https://platform.openai.com/docs/concepts#tokens), 1 token equals approximately 4 characters of English text. | +| `overlap_rate` | Float | Optional | The degree of overlap between chunks. Valid values are floats between `0` and `0.5`, inclusive. Default is `0`. As suggested by [Amazon Bedrock](https://aws.amazon.com/blogs/aws/knowledge-bases-now-delivers-fully-managed-rag-experience-in-amazon-bedrock/), we recommend a value of 0--0.2 to improve accuracy. | +| `max_chunk_limit` | Integer | Optional | The maximum number of chunks. If the processor generates more chunks than this limit, the excess text is added to the last chunk. Default is `100`. To disable this parameter, set it to `-1`. | + +The 4-characters-per-token estimate does not apply to Chinese, Japanese, or Korean text, in which 1 token typically covers only 1--2 characters. For example, a 2,048-character chunk of Chinese text contains about 2,000 tokens for the `bert-base-multilingual-uncased` tokenizer and about 1,200 tokens for the XLM-RoBERTa tokenizer. Text embedding models ignore text beyond their token limit without returning an error, so most of such a chunk is not represented in its embedding. For Chinese, Japanese, or Korean text, set `char_limit` to approximately the model's token limit (for example, `500` for a model with a 512-token limit). +{: .important} + +### The delimiter algorithm + +The following table lists the optional parameters for the `delimiter` algorithm. + +| Parameter | Data type | Required/Optional | Description | +|:---|:---|:---|:---| +| `delimiter` | String | Optional | A string delimiter used to split text. You can set the `delimiter` to any string, for example, `\n` (split text into paragraphs on a new line) or `.` (split text into sentences). Default is `\n\n` (split text into paragraphs on two new line characters). | +| `max_chunk_limit` | Integer | Optional | The maximum number of chunks. If the processor generates more chunks than this limit, the excess text is added to the last chunk. Default is `100`. To disable this parameter, set it to `-1`. | + +## Using the processor + +Follow these steps to use the processor in a pipeline. You can specify the chunking algorithm when creating the processor. If you don't provide an algorithm name, the chunking processor will use the default `fixed_token_length` algorithm along with all its default parameters. + +### Step 1: Create a pipeline + +The following example request creates an ingest pipeline that converts the text in the `passage_text` field into chunked passages, which will be stored in the `passage_chunk` field: + +```json +PUT _ingest/pipeline/text-chunking-ingest-pipeline +{ + "description": "A text chunking ingest pipeline", + "processors": [ + { + "text_chunking": { + "algorithm": { + "fixed_token_length": { + "token_limit": 10, + "overlap_rate": 0.2, + "tokenizer": "standard" + } + }, + "field_map": { + "passage_text": "passage_chunk" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before ingesting documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/text-chunking-ingest-pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex", + "_id": "1", + "_source":{ + "passage_text": "This is an example document to be chunked. The document contains a single paragraph, two sentences and 24 tokens by standard tokenizer in OpenSearch." + } + } + ] +} +``` +{% include copy-curl.html %} + +The response confirms that, in addition to the `passage_text` field, the processor has generated chunking results in the `passage_chunk` field. The processor split the paragraph into 10-word chunks. Because of the `overlap` setting of 0.2, the last 2 words of a chunk are duplicated in the following chunk: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex", + "_id": "1", + "_source": { + "passage_text": "This is an example document to be chunked. The document contains a single paragraph, two sentences and 24 tokens by standard tokenizer in OpenSearch.", + "passage_chunk": [ + "This is an example document to be chunked. The document ", + "The document contains a single paragraph, two sentences and 24 ", + "and 24 tokens by standard tokenizer in OpenSearch." + ] + }, + "_ingest": { + "timestamp": "2024-03-20T02:55:25.642366Z" + } + } + } + ] +} +``` + +Once you have created an ingest pipeline, you need to create an index for document ingestion. To learn more, see [Text chunking]({{site.url}}{{site.baseurl}}/search-plugins/text-chunking/). + +## Cascading text chunking processors + +You can chain multiple text chunking processors together. For example, to split documents into paragraphs, apply the `delimiter` algorithm and specify the parameter as `\n\n`. To prevent a paragraph from exceeding the token limit, append another text chunking processor that uses the `fixed_token_length` algorithm. You can configure the ingest pipeline for this example as follows: + +```json +PUT _ingest/pipeline/text-chunking-cascade-ingest-pipeline +{ + "description": "A text chunking pipeline with cascaded algorithms", + "processors": [ + { + "text_chunking": { + "algorithm": { + "delimiter": { + "delimiter": "\n\n" + } + }, + "field_map": { + "passage_text": "passage_chunk1" + } + } + }, + { + "text_chunking": { + "algorithm": { + "fixed_token_length": { + "token_limit": 500, + "overlap_rate": 0.2, + "tokenizer": "standard" + } + }, + "field_map": { + "passage_chunk1": "passage_chunk2" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +### Recursive text chunking using cascaded processors + +For more advanced control, you can chain more than two processors in order to create a recursive chunking effect. This strategy involves deconstructing text into progressively smaller, more semantically meaningful units. + +For example, you can first split a document into paragraphs (`\n\n`) and then split each paragraph into sentences (`. `). Finally, you can chunk each sentence using the `fixed_char_length` algorithm to ensure that the final passages do not exceed a specific length. This hierarchical approach helps maintain as much semantic context as possible within the final size constraints. + +The following example configures a three-stage recursive chunking pipeline: + +```json +PUT _ingest/pipeline/recursively-text-chunking-cascade-ingest-pipeline +{ + "description": "A pipeline that recursively chunks text by paragraph, then sentence, then character length.", + "processors": [ + { + "text_chunking": { + "algorithm": { + "delimiter": { + "delimiter": "\n\n" + } + }, + "field_map": { + "original_text": "paragraph_chunks" + } + } + }, + { + "text_chunking": { + "algorithm": { + "delimiter": { + "delimiter": ". " + } + }, + "field_map": { + "paragraph_chunks": "sentence_chunks" + } + } + }, + { + "text_chunking": { + "algorithm": { + "fixed_char_length": { + "char_limit": 300, + "overlap_rate": 0.1 + } + }, + "field_map": { + "sentence_chunks": "final_recursive_chunks" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +## Next steps + +- For a complete example, see [Text chunking]({{site.url}}{{site.baseurl}}/search-plugins/text-chunking/). +- To learn more about semantic search, see [Semantic search]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/). +- To learn more about sparse search, see [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). +- To learn more about using models in OpenSearch, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). +- For a tutorial that chunks long documents and generates embeddings using an externally hosted model, see [Semantic search using text chunking]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-search/long-document/). diff --git a/_ingest-pipelines/processors/text-embedding.md b/_ingest-pipelines/processors/text-embedding.md index 28b18c2e..0afe8916 100644 --- a/_ingest-pipelines/processors/text-embedding.md +++ b/_ingest-pipelines/processors/text-embedding.md @@ -15,6 +15,9 @@ The `text_embedding` processor is used to generate vector embeddings from text f Before using the `text_embedding` processor, you must set up a machine learning (ML) model. For more information, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). {: .note} +**Token limits and truncation**: Text embedding models have maximum token limits (typically 512 tokens for BERT-based models). When a document exceeds this limit, the model automatically truncates the text, and the truncated content is not represented in the embeddings. This can significantly impact search relevance because documents may not be returned in search results if the relevant content was truncated. To avoid this issue, split long documents into smaller chunks before generating embeddings. +{: .warning} + The following is the syntax for the `text_embedding` processor: ```json @@ -27,26 +30,31 @@ The following is the syntax for the `text_embedding` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `text_embedding` processor. | Parameter | Data type | Required/Optional | Description | |:---|:---|:---|:---| -`model_id` | String | Required | The ID of the model that will be used to generate the embeddings. The model must be deployed in OpenSearch before it can be used in neural search. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Semantic search]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/). +`model_id` | String | Required | The ID of the model that will be used to generate the embeddings. The model must be deployed in OpenSearch before it can be used. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Semantic search]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/). `field_map` | Object | Required | Contains key-value pairs that specify the mapping of a text field to a vector field. `field_map.<input_field>` | String | Required | The name of the field from which to obtain text for generating text embeddings. -`field_map.<vector_field>` | String | Required | The name of the vector field in which to store the generated text embeddings. +`field_map.<vector_field>` | String | Required | The name of the vector field in which to store the generated text embeddings. For a nested input field, specify only the field name and not the full path. For more information, see [Embedding a nested field](#embedding-a-nested-field). `description` | String | Optional | A brief description of the processor. | -`tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | +`tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +`batch_size` | Integer | Optional | Specifies the number of documents to be batched and processed each time. Default is `1`. If you specify `if`, the processor doesn't batch documents and processes them one at a time. | +`if` | String containing a Boolean expression | Optional | A condition for running the processor. | +`ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, the processor failure is ignored. Default is `false`. | +`on_failure` | List | Optional | A list of processors to run if the processor fails. | +`skip_existing` | Boolean | Optional | When `true`, the processor compares the incoming document with the document already indexed under the same document ID. If the input text is unchanged and the indexed document already contains embeddings, the processor makes no inference call and copies the existing embeddings. Because the comparison requires an indexed document, this parameter has no effect in `_simulate` requests. Default is `false`. | ## Using the processor Follow these steps to use the processor in a pipeline. You must provide a model ID when creating the processor. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). -**Step 1: Create a pipeline.** +### Step 1: Create a pipeline The following example request creates an ingest pipeline where the text from `passage_text` will be converted into text embeddings and the embeddings will be stored in `passage_embedding`: @@ -68,10 +76,10 @@ PUT /_ingest/pipeline/nlp-ingest-pipeline ``` {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline.** +Creating the pipeline does not validate `model_id`. The request succeeds even if the model does not exist or is not deployed, and the error appears only when you ingest a document. Test the pipeline before ingesting documents. +{: .note} -It is recommended that you test your pipeline before you ingest documents. -{: .tip} +### Step 2 (Optional): Test the pipeline To test the pipeline, run the following query: @@ -91,8 +99,6 @@ POST _ingest/pipeline/nlp-ingest-pipeline/_simulate ``` {% include copy-curl.html %} -#### Response - The response confirms that in addition to the `passage_text` field, the processor has generated text embeddings in the `passage_embedding` field: ```json @@ -121,11 +127,41 @@ The response confirms that in addition to the `passage_text` field, the processo } ``` +If a document does not contain the input field, the processor makes no inference call and indexes the document without the vector field. No error is returned, so confirm that your documents contain the input field. +{: .note} + Once you have created an ingest pipeline, you need to create an index for ingestion and ingest documents into the index. To learn more, see [Step 2: Create an index for ingestion]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/#step-2-create-an-index-for-ingestion) and [Step 3: Ingest documents into the index]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/#step-3-ingest-documents-into-the-index) of [Semantic search]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/). +## Embedding a nested field + +To generate embeddings from a field nested in an object, specify the full path of the input field and only the field name of the vector field. The processor stores the vector field in the same object as the input field. + +The following example request creates a pipeline that generates embeddings from `obj.passage_text` and stores them in `obj.passage_embedding`: + +```json +PUT /_ingest/pipeline/nlp-nested-ingest-pipeline +{ + "description": "A text embedding pipeline for a nested field", + "processors": [ + { + "text_embedding": { + "model_id": "<model_id>", + "field_map": { + "obj.passage_text": "passage_embedding" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +If you specify the full path (`obj.passage_embedding`) as the vector field, the processor resolves the path relative to the object containing the input field and stores the embeddings in `obj.obj.passage_embedding`. + ## Next steps - To learn how to use the `neural` query for text search, see [Neural query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/). - To learn more about semantic search, see [Semantic search]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/). - To learn more about using models in OpenSearch, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). -- For a comprehensive example, see [Neural search tutorial]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). \ No newline at end of file +- For a comprehensive example, see [Getting started with semantic and hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). +- For an example that generates embeddings for arrays of objects, see [Generating embeddings from arrays of objects]({{site.url}}{{site.baseurl}}/tutorials/vector-search/vector-operations/generate-embeddings/). diff --git a/_ingest-pipelines/processors/text-image-embedding.md b/_ingest-pipelines/processors/text-image-embedding.md index 212e9f96..b97f471a 100644 --- a/_ingest-pipelines/processors/text-image-embedding.md +++ b/_ingest-pipelines/processors/text-image-embedding.md @@ -7,9 +7,11 @@ redirect_from: - /api-reference/ingest-apis/processors/text-image-embedding/ --- +<!-- vale off --> # Text/image embedding processor +<!-- vale on --> -The `text_image_embedding` processor is used to generate combined vector embeddings from text and image fields for [multimodal neural search]({{site.url}}{{site.baseurl}}/search-plugins/multimodal-search/). +The `text_image_embedding` processor is used to generate combined vector embeddings from text and image fields for [multimodal search]({{site.url}}{{site.baseurl}}/search-plugins/multimodal-search/). **PREREQUISITE**<br> Before using the `text_image_embedding` processor, you must set up a machine learning (ML) model. For more information, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). @@ -29,7 +31,7 @@ The following is the syntax for the `text_image_embedding` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} ## Parameters @@ -37,19 +39,23 @@ The following table lists the required and optional parameters for the `text_ima | Parameter | Data type | Required/Optional | Description | |:---|:---|:---|:---| -`model_id` | String | Required | The ID of the model that will be used to generate the embeddings. The model must be deployed in OpenSearch before it can be used in neural search. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Multimodal search]({{site.url}}{{site.baseurl}}/search-plugins/multimodal-search/). +`model_id` | String | Required | The ID of the model that will be used to generate the embeddings. The model must be deployed in OpenSearch before it can be used. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Multimodal search]({{site.url}}{{site.baseurl}}/search-plugins/multimodal-search/). `embedding` | String | Required | The name of the vector field in which to store the generated embeddings. A single embedding is generated for both `text` and `image` fields. `field_map` | Object | Required | Contains key-value pairs that specify the fields from which to generate embeddings. `field_map.text` | String | Optional | The name of the field from which to obtain text for generating vector embeddings. You must specify at least one `text` or `image`. `field_map.image` | String | Optional | The name of the field from which to obtain the image for generating vector embeddings. You must specify at least one `text` or `image`. `description` | String | Optional | A brief description of the processor. | -`tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | +`tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | +`if` | String containing a Boolean expression | Optional | A condition for running the processor. | +`ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, the processor failure is ignored. Default is `false`. | +`on_failure` | List | Optional | A list of processors to run if the processor fails. | +`skip_existing` | Boolean | Optional | When `true`, the processor does not make inference calls for fields that already contain embeddings, leaving existing embeddings unchanged. Default is `false`.| ## Using the processor Follow these steps to use the processor in a pipeline. You must provide a model ID when creating the processor. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). -**Step 1: Create a pipeline.** +### Step 1: Create a pipeline The following example request creates an ingest pipeline where the text from `image_description` and the image from `image_binary` will be converted into vector embeddings and the embeddings will be stored in `vector_embedding`: @@ -76,7 +82,7 @@ PUT /_ingest/pipeline/nlp-ingest-pipeline You can set up multiple processors in one pipeline to generate embeddings for multiple fields. {: .note} -**Step 2 (Optional): Test the pipeline.** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -100,8 +106,6 @@ POST _ingest/pipeline/nlp-ingest-pipeline/_simulate ``` {% include copy-curl.html %} -#### Response - The response confirms that in addition to the `image_description` and `image_binary` fields, the processor has generated vector embeddings in the `vector_embedding` field: ```json @@ -138,4 +142,4 @@ Once you have created an ingest pipeline, you need to create an index for ingest - To learn how to use the `neural` query for a multimodal search, see [Neural query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/). - To learn more about multimodal search, see [Multimodal search]({{site.url}}{{site.baseurl}}/search-plugins/multimodal-search/). - To learn more about using models in OpenSearch, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). -- For a comprehensive example, see [Neural search tutorial]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). \ No newline at end of file +- For a comprehensive example, see [Getting started with semantic and hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). \ No newline at end of file diff --git a/_ingest-pipelines/processors/trim.md b/_ingest-pipelines/processors/trim.md new file mode 100644 index 00000000..b9984170 --- /dev/null +++ b/_ingest-pipelines/processors/trim.md @@ -0,0 +1,145 @@ +--- +layout: default +title: Trim +parent: Ingest processors +nav_order: 300 +--- + +# Trim processor + +The `trim` processor is used to remove leading and trailing white space characters from a specified field. White space within the value isn't removed. For array fields, the processor trims each string element. + +The following is the syntax for the `trim` processor: + +```json +{ + "trim": { + "field": "field_to_trim", + "target_field": "trimmed_field" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `trim` processor. + +Parameter | Required/Optional | Description +:---|:---|:--- +`field` | Required | The field containing the text to be trimmed. +`target_field` | Optional | The field in which the trimmed text is stored. If not specified, then the field is updated in-place. +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, then the processor ignores missing values in the field and leaves the `target_field` unchanged. Default is `false`. +`description` | Optional | A brief description of the processor. +`if` | Optional | A condition for running the processor. +`ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. +`on_failure` | Optional | A list of processors to run if the processor fails. +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `trim_pipeline` that uses the `trim` processor to remove leading and trailing white space from the `raw_text` field and store the trimmed text in the `trimmed_text` field: + +```json +PUT _ingest/pipeline/trim_pipeline +{ + "description": "Trim leading and trailing white space", + "processors": [ + { + "trim": { + "field": "raw_text", + "target_field": "trimmed_text" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/trim_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "raw_text": " Hello, world! " + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "raw_text": " Hello, world! ", + "trimmed_text": "Hello, world!" + }, + "_ingest": { + "timestamp": "2024-04-26T20:58:17.418006805Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=trim_pipeline +{ + "raw_text": " Hello, world! " +} +``` +{% include copy-curl.html %} + +The request indexes the document into the `testindex1` index. The `trim_pipeline` trims the `raw_text` value and stores the result in the `trimmed_text` field, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 68, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 70, + "_primary_term": 47 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/uppercase.md b/_ingest-pipelines/processors/uppercase.md index e3cea317..a7db96d5 100644 --- a/_ingest-pipelines/processors/uppercase.md +++ b/_ingest-pipelines/processors/uppercase.md @@ -7,9 +7,12 @@ redirect_from: - /api-reference/ingest-apis/processors/uppercase/ --- +This documentation describes using the `uppercase` processor in OpenSearch ingest pipelines. Consider using the [Data Prepper `uppercase_string` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/uppercase-string/), which runs outside the OpenSearch cluster, if your use case involves large or complex datasets. +{: .note} + # Uppercase processor -The `uppercase` processor converts all the text in a specific field to uppercase letters. +The `uppercase` processor converts all the text in a specific field to uppercase letters. For array fields, the processor converts each string element. ## Syntax @@ -22,30 +25,30 @@ The following is the syntax for the `uppercase` processor: } } ``` -{% include copy-curl.html %} +{% include copy.html %} -## Configuration parameters +## Parameters The following table lists the required and optional parameters for the `uppercase` processor. | Parameter | Required/Optional | Description | |---|---|---| -`field` | Required | The name of the field containing the data to be appended. Supports [template snippets]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#template-snippets). | +`field` | Required | The name of the field containing the data to be converted. | `description` | Optional | A brief description of the processor. | `if` | Optional | A condition for running the processor. | `ignore_failure` | Optional | Specifies whether the processor continues execution even if it encounters errors. If set to `true`, failures are ignored. Default is `false`. | `ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified field. If set to `true`, the processor does not modify the document if the field does not exist or is `null`. Default is `false`. | `on_failure` | Optional | A list of processors to run if the processor fails. | -`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | `target_field` | Optional | The name of the field in which to store the parsed data. Default is `field`. By default, `field` is updated in place. | ## Using the processor Follow these steps to use the processor in a pipeline. -**Step 1: Create a pipeline** +### Step 1: Create a pipeline -The following query creates a pipeline, named `uppercase`, that converts the text in the `field` field to uppercase: +The following query creates a pipeline, named `uppercase`, that converts the text in the `name` field to uppercase: ```json PUT _ingest/pipeline/uppercase @@ -62,7 +65,7 @@ PUT _ingest/pipeline/uppercase {% include copy-curl.html %} -**Step 2 (Optional): Test the pipeline** +### Step 2 (Optional): Test the pipeline It is recommended that you test your pipeline before you ingest documents. {: .tip} @@ -85,8 +88,6 @@ POST _ingest/pipeline/uppercase/_simulate ``` {% include copy-curl.html %} -**Response** - The following example response confirms that the pipeline is working as expected: ```json @@ -108,7 +109,7 @@ The following example response confirms that the pipeline is working as expected } ``` -**Step 3: Ingest a document** +### Step 3: Ingest a document The following query ingests a document into an index named `testindex1`: @@ -120,7 +121,7 @@ PUT testindex1/_doc/1?pipeline=uppercase ``` {% include copy-curl.html %} -**Step 4 (Optional): Retrieve the document** +### Step 4 (Optional): Retrieve the document To retrieve the document, run the following query: @@ -128,3 +129,5 @@ To retrieve the document, run the following query: GET testindex1/_doc/1 ``` {% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/urldecode.md b/_ingest-pipelines/processors/urldecode.md new file mode 100644 index 00000000..ced90474 --- /dev/null +++ b/_ingest-pipelines/processors/urldecode.md @@ -0,0 +1,145 @@ +--- +layout: default +title: URL decode +parent: Ingest processors +nav_order: 320 +--- + +# URL decode processor + +The `urldecode` processor is useful for decoding URL-encoded strings in log data or other text fields. This can make the data more readable and easier to analyze, especially when working with URLs or query parameters that contain special characters or spaces. For array fields, the processor decodes each string element. Both percent-encoded characters and plus signs are decoded; for example, `wireless+mouse%21` becomes `wireless mouse!`. + +The following is the syntax for the `urldecode` processor: + +```json +{ + "urldecode": { + "field": "field_to_decode", + "target_field": "decoded_field" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `urldecode` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The field containing the URL-encoded string to be decoded. | +`target_field` | Optional | The field in which the decoded string is stored. If not specified, then the decoded string is stored in the same field as the original encoded string. | +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified `field`. If set to `true`, then the processor ignores missing values in the `field` and leaves the `target_field` unchanged. Default is `false`. | +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | Specifies whether the processor continues to run even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `urldecode_pipeline` that uses the `urldecode` processor to decode the URL-encoded string in the `encoded_url` field and store the decoded string in the `decoded_url` field: + +```json +PUT _ingest/pipeline/urldecode_pipeline +{ + "description": "Decode URL-encoded strings", + "processors": [ + { + "urldecode": { + "field": "encoded_url", + "target_field": "decoded_url" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/urldecode_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "encoded_url": "https://example.com/search?q=hello%20world" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "decoded_url": "https://example.com/search?q=hello world", + "encoded_url": "https://example.com/search?q=hello%20world" + }, + "_ingest": { + "timestamp": "2024-04-25T23:16:44.886165001Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=urldecode_pipeline +{ + "encoded_url": "https://example.com/search?q=hello%20world" +} +``` +{% include copy-curl.html %} + +The preceding request indexes the document into the `testindex1` index. The `urldecode_pipeline` decodes the `encoded_url` value and stores the result in the `decoded_url` field, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 67, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 68, + "_primary_term": 47 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. diff --git a/_ingest-pipelines/processors/user-agent.md b/_ingest-pipelines/processors/user-agent.md new file mode 100644 index 00000000..d23a79d7 --- /dev/null +++ b/_ingest-pipelines/processors/user-agent.md @@ -0,0 +1,175 @@ +--- +layout: default +title: User agent +parent: Ingest processors +nav_order: 330 +--- + +# User agent processor + +The `user_agent` processor is used to extract information from the user agent string, such as the browser, device, and operating system used by the client. The `user_agent` processor is particularly useful for analyzing user behavior and identifying trends based on user devices, operating systems, and browsers. It can also be helpful for troubleshooting issues specific to certain user agent configurations. + +The following is the syntax for the `user_agent` processor: + +```json +{ + "user_agent": { + "field": "user_agent", + "target_field": "user_agent_info" + } +} +``` +{% include copy.html %} + +## Parameters + +The following table lists the required and optional parameters for the `user_agent` processor. + +Parameter | Required/Optional | Description | +|-----------|-----------|-----------| +`field` | Required | The field containing the user agent string. +`target_field` | Optional | The field in which to store the extracted user agent information. If not specified, then the information is stored in the `user_agent` field. +`ignore_missing` | Optional | Specifies whether the processor should ignore documents that do not contain the specified `field`. If set to `true`, the processor does not modify the document if the `field` does not exist or is `null`. Default is `false`. | +`regex_file` | Optional | The name of a file containing regular expression patterns used to parse the user agent string, for example, `custom-regexes.yml`. The file must be located in the `config/ingest-user-agent` directory. If not specified, then the processor uses the regular expressions bundled with OpenSearch. For more information, see [Using a custom regex file](#using-a-custom-regex-file). +`properties` | Optional | A list of properties to be extracted from the user agent string and added to the `target_field`. Valid values are `name`, `version`, `os`, `device`, and `original`. If not specified, then all of these properties are extracted. +`description` | Optional | A brief description of the processor. | +`if` | Optional | A condition for running the processor. | +`ignore_failure` | Optional | Specifies whether the processor continues to run even if it encounters an error. If set to `true`, then failures are ignored. Default is `false`. | +`on_failure` | Optional | A list of processors to run if the processor fails. | +`tag` | Optional | An identifier tag for the processor. Useful for debugging in order to distinguish between processors of the same type. For more information, see [Using processor tags for monitoring and debugging]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#using-processor-tags-for-monitoring-and-debugging). | + +## Using the processor + +Follow these steps to use the processor in a pipeline. + +### Step 1: Create a pipeline + +The following query creates a pipeline named `user_agent_pipeline` that uses the `user_agent` processor to extract user agent information: + +```json +PUT _ingest/pipeline/user_agent_pipeline +{ + "description": "User agent pipeline", + "processors": [ + { + "user_agent": { + "field": "user_agent", + "target_field": "user_agent_info" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2 (Optional): Test the pipeline + +It is recommended that you test your pipeline before you ingest documents. +{: .tip} + +To test the pipeline, run the following query: + +```json +POST _ingest/pipeline/user_agent_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" + } + } + ] +} +``` +{% include copy-curl.html %} + +The following example response confirms that the pipeline is working as expected: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3", + "user_agent_info": { + "name": "Chrome", + "original": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3", + "os": { + "name": "Windows", + "version": "10", + "full": "Windows 10" + }, + "device": { + "name": "Other" + }, + "version": "58.0.3029.110" + } + }, + "_ingest": { + "timestamp": "2024-04-25T21:41:28.744407425Z" + } + } + } + ] +} +``` + +### Step 3: Ingest a document + +The following query ingests a document into an index named `testindex1`: + +```json +PUT testindex1/_doc/1?pipeline=user_agent_pipeline +{ + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" +} +``` +{% include copy-curl.html %} + +The preceding request parses the `user_agent` string into its components and indexes the document, including the parsed components, into the `testindex1` index, as shown in the following response: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 66, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 65, + "_primary_term": 47 +} +``` + +### Step 4 (Optional): Retrieve the document + +To retrieve the document, run the following query: + +```json +GET testindex1/_doc/1 +``` +{% include copy-curl.html %} + +The response contains the ingested document, transformed as shown in the response in Step 2. + +## Using a custom regex file + +To parse user agent strings using your own regular expressions, create a regex file and specify its name in the `regex_file` parameter. The file must meet the following requirements: + +- The file has a `.yml` extension. +- The file is located in the `config/ingest-user-agent` directory on every node. +- The file exists when the node starts. OpenSearch loads regex files only at startup, so changes to existing files and new files take effect only after you restart the node. + +The bundled regular expressions are based on the [`regexes.yaml`](https://github.com/ua-parser/uap-core/blob/master/regexes.yaml) file from the uap-core project. A custom regex file is typically a newer or modified version of this file. + +## Settings + +The `user_agent` processor caches parsing results. All `user_agent` processors on a node share one cache. You can configure the cache using the following static setting in `opensearch.yml`: + +- `ingest.user_agent.cache_size` (Static, long): The maximum number of parsing results to cache. Default is `1000`. diff --git a/_ingest-pipelines/regex-conditionals.md b/_ingest-pipelines/regex-conditionals.md new file mode 100644 index 00000000..a827b88f --- /dev/null +++ b/_ingest-pipelines/regex-conditionals.md @@ -0,0 +1,205 @@ +--- +layout: default +title: Regex conditionals +parent: Conditional execution +nav_order: 70 +--- + +# Regex conditionals + +Ingest pipelines support conditional logic using regular expressions (regex) with the Painless scripting language. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). This allows fine-grained control over which documents get processed based on the structure and contents of text fields. Regex can be used within the `if` parameter to evaluate string patterns. This is especially useful for matching IP formats, validating email addresses, identifying UUIDs, or processing logs with specific keywords. + +Regular expressions can be expensive to evaluate. To limit their CPU consumption, OpenSearch limits the number of characters that a Painless regular expression can read, based on the `script.painless.regex.enabled` and `script.painless.regex.limit-factor` settings. For more information, see [Controlling regular expressions]({{site.url}}{{site.baseurl}}/scripting/painless/#controlling-regular-expressions). + +## Example: Email domain filtering + +The following pipeline uses regex to identify users from the `@example.com` email domain and tag those documents accordingly: + +```json +PUT _ingest/pipeline/tag_example_com_users +{ + "processors": [ + { + "set": { + "field": "user_domain", + "value": "example.com", + "if": "ctx.email != null && ctx.email =~ /@example\\.com$/" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the following request to simulate the pipeline: + +```json +POST _ingest/pipeline/tag_example_com_users/_simulate +{ + "docs": [ + { "_source": { "email": "alice@example.com" } }, + { "_source": { "email": "bob@another.com" } } + ] +} +``` +{% include copy-curl.html %} + +Only the first document has `user_domain` added: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "email": "alice@example.com", + "user_domain": "example.com" + } + } + }, + { + "doc": { + "_source": { + "email": "bob@another.com" + } + } + } + ] +} +``` + +## Example: Detect IPv6 addresses + +The following pipeline uses regex to identify and flag IPv6-formatted addresses: + +```json +PUT _ingest/pipeline/ipv6_flagger +{ + "processors": [ + { + "set": { + "field": "ip_type", + "value": "IPv6", + "if": "ctx.ip != null && ctx.ip =~ /^[a-fA-F0-9:]+$/ && ctx.ip.contains(':')" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the following request to simulate the pipeline: + +```json +POST _ingest/pipeline/ipv6_flagger/_simulate +{ + "docs": [ + { "_source": { "ip": "2001:0db8:85a3:0000:0000:8a2e:0370:7334" } }, + { "_source": { "ip": "192.168.0.1" } } + ] +} +``` +{% include copy-curl.html %} + +The first document contains an added `ip_type` field set to `IPv6`: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "ip": "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + "ip_type": "IPv6" + } + } + }, + { + "doc": { + "_source": { + "ip": "192.168.0.1" + } + } + } + ] +} +``` + +## Example: Validate UUID strings + +The following pipeline uses regex to verify whether a `session_id` field contains a valid UUID: + +```json +PUT _ingest/pipeline/uuid_checker +{ + "processors": [ + { + "set": { + "field": "valid_uuid", + "value": true, + "if": "ctx.session_id != null && ctx.session_id =~ /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the following request to simulate the pipeline: + +```json +POST _ingest/pipeline/uuid_checker/_simulate +{ + "docs": [ + { "_source": { "session_id": "550e8400-e29b-41d4-a716-446655440000" } }, + { "_source": { "session_id": "invalid-uuid-1234" } } + ] +} +``` +{% include copy-curl.html %} + +The first document is tagged with a new `valid_uuid` field: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "session_id": "550e8400-e29b-41d4-a716-446655440000", + "valid_uuid": true + } + } + }, + { + "doc": { + "_source": { + "session_id": "invalid-uuid-1234" + } + } + } + ] +} +``` + +## Using string methods for simple matches + +String methods are less expensive to evaluate than regular expressions. When a string method can perform the same match, use the string method. For example, the following condition is equivalent to the [email domain example](#example-email-domain-filtering) but uses the `endsWith` method: + +```json +PUT _ingest/pipeline/tag_example_com_users +{ + "processors": [ + { + "set": { + "field": "user_domain", + "value": "example.com", + "if": "ctx.email != null && ctx.email.endsWith('@example.com')" + } + } + ] +} +``` +{% include copy-curl.html %} + +Other string methods that can replace common regular expressions include `startsWith` and `contains`. diff --git a/_ingest-pipelines/simulate-ingest.md b/_ingest-pipelines/simulate-ingest.md index 33ae9351..b4f35d19 100644 --- a/_ingest-pipelines/simulate-ingest.md +++ b/_ingest-pipelines/simulate-ingest.md @@ -7,56 +7,57 @@ redirect_from: - /api-reference/ingest-apis/simulate-ingest/ --- -# Simulate pipeline +# Simulate Pipeline API **Introduced 1.0** {: .label .label-purple } -Use the simulate ingest pipeline API operation to run or test the pipeline. +The Simulate Pipeline API runs an ingest pipeline against a set of sample documents and returns the transformed documents without indexing them. Use it to test a pipeline before you apply it to your data. You can simulate an existing pipeline or provide a pipeline definition in the request body. -## Path and HTTP methods - -The following requests **simulate the latest ingest pipeline created**: +## Endpoints +```json +GET /_ingest/pipeline/_simulate +POST /_ingest/pipeline/_simulate +GET /_ingest/pipeline/{pipeline-id}/_simulate +POST /_ingest/pipeline/{pipeline-id}/_simulate ``` -GET _ingest/pipeline/_simulate -POST _ingest/pipeline/_simulate -``` -{% include copy-curl.html %} -The following requests **simulate a single pipeline based on the pipeline ID**: +## Path parameters -``` -GET _ingest/pipeline/<pipeline-id>/_simulate -POST _ingest/pipeline/<pipeline-id>/_simulate -``` -{% include copy-curl.html %} +The following table lists the available path parameters. All path parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`pipeline-id` | String | The ID of an existing pipeline to simulate. If not specified, provide the pipeline definition in the `pipeline` request body field. + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`verbose` | Boolean | If `true`, the response contains the result of each processor in the pipeline, including the document after each processor runs. Default is `false`. ## Request body fields -The following table lists the request body fields used to run a pipeline. +The following table lists the available request body fields. -Field | Required | Type | Description -:--- | :--- | :--- | :--- -`docs` | Required | Array | The documents to be used to test the pipeline. -`pipeline` | Optional | Object | The pipeline to be simulated. If the pipeline identifier is not included, then the response simulates the latest pipeline created. - -The `docs` field can include subfields listed in the following table. - -Field | Required | Type | Description -:--- | :--- | :--- | :--- -`source` | Required | Object | The document's JSON body. -`id` | Optional | String | A unique document identifier. The identifier cannot be used elsewhere in the index. -`index` | Optional | String | The index where the document's transformed data appears. - -## Query parameters - -The following table lists the query parameters for running a pipeline. - -Parameter | Type | Description +Field | Data type | Description :--- | :--- | :--- -`verbose` | Boolean | Verbose mode. Display data output for each processor in the executed pipeline. +`docs` | Array of objects | The documents to run through the pipeline. Required. +`pipeline` | Object | The definition of the pipeline to simulate. Contains the same fields as the [Create or Update Pipeline API]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#request-body-fields) request body. Required if the pipeline ID is not specified in the path. -#### Example: Specify a pipeline in the path +Each object in the `docs` array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`_source` | Object | The document's JSON body. Required. +`_id` | String | The document ID. Processors can read and modify the ID using the `_id` metadata field. Optional. +`_index` | String | The index name. Processors can read and modify the index name using the `_index` metadata field. Optional. + +## Example: Simulating an existing pipeline + +The following request runs two documents through the `my-pipeline` pipeline created in the [Create or Update Pipeline API example]({{site.url}}{{site.baseurl}}/ingest-pipelines/create-ingest/#example-request): ```json POST /_ingest/pipeline/my-pipeline/_simulate @@ -85,7 +86,7 @@ POST /_ingest/pipeline/my-pipeline/_simulate ``` {% include copy-curl.html %} -The request returns the following response: +The response contains each document after the pipeline processed it: ```json { @@ -122,9 +123,29 @@ The request returns the following response: } ``` -#### Example: Verbose mode +## Example: Viewing the result of each processor -When the previous request is run with the `verbose` parameter set to `true`, the response shows the sequence of transformations for each document. For example, for the document with the ID `1`, the response contains the results of applying each processor in the pipeline in sequence: +To view the document after each processor runs, set the `verbose` query parameter to `true`: + +```json +POST /_ingest/pipeline/my-pipeline/_simulate?verbose=true +{ + "docs": [ + { + "_index": "my-index", + "_id": "1", + "_source": { + "grad_year": 2024, + "graduated": false, + "name": "John Doe" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response contains the results of applying each processor in the pipeline in sequence: ```json { @@ -152,7 +173,7 @@ When the previous request is run with the `verbose` parameter set to `true`, the { "processor_type": "set", "status": "success", - "description": "Sets 'graduated' to true", + "description": "Sets graduated to true", "doc": { "_index": "my-index", "_id": "1", @@ -190,16 +211,16 @@ When the previous request is run with the `verbose` parameter set to `true`, the } ``` -#### Example: Specify a pipeline in the request body +## Example: Simulating a pipeline defined in the request body -Alternatively, you can specify a pipeline directly in the request body without first creating a pipeline: +To test a pipeline without creating it, provide the pipeline definition in the request body: ```json POST /_ingest/pipeline/_simulate { "pipeline" : { - "description": "Splits text on white space characters", + "description": "Splits comma-separated text into fields", "processors": [ { "csv" : { @@ -236,8 +257,6 @@ POST /_ingest/pipeline/_simulate ``` {% include copy-curl.html %} -#### Response - The request returns the following response: ```json @@ -274,3 +293,30 @@ The request returns the following response: ] } ``` + +## Response body fields + +The response contains the `docs` array, with one object for each document in the request, in the same order as the request. If a processor dropped a document, the array contains `null` for that document. Each object in the array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`doc` | Object | The document after the pipeline processed it, including its `_index`, `_id`, `_source`, and `_ingest` metadata. Returned when `verbose` is `false` and the document was processed successfully. +`error` | Object | The error that caused the pipeline to fail for this document. Returned if processing failed. In this case, `doc` isn't returned. +`processor_results` | Array of objects | The result of each processor, in the order in which the processors ran. Returned only when `verbose` is `true`. + +Each object in the `processor_results` array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`processor_type` | String | The processor type, for example, `set`. +`status` | String | The processor result. Valid values are `success`, `error` (the processor failed; if it defines `on_failure`, the results of the `on_failure` processors follow), `error_ignored` (the processor failed and `ignore_failure` is `true`), `skipped` (the processor's `if` condition returned `false`), and `dropped` (the processor dropped the document). +`description` | String | The processor description. Returned only if the processor has a description. +`tag` | String | The processor tag. Returned only if the processor has a tag. +`if` | Object | The processor's `if` condition (`condition`) and its result (`result`). Returned only if the processor has a condition. +`doc` | Object | The document after this processor ran. +`error` | Object | The error returned by the processor. Returned if the status is `error`. +`ignored_error` | Object | The error that the processor ignored. Returned if the status is `error_ignored`. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/ingest/pipeline/simulate`. diff --git a/_install-and-configure/additional-plugins/index.md b/_install-and-configure/additional-plugins/index.md new file mode 100644 index 00000000..42911f56 --- /dev/null +++ b/_install-and-configure/additional-plugins/index.md @@ -0,0 +1,51 @@ +--- +layout: default +title: Additional plugins +parent: Managing OpenSearch plugins +nav_order: 10 +has_children: true +has_toc: false +redirect_from: + - /install-and-configure/additional-plugins/ +--- + +# Additional plugins + +There are many more plugins available in addition to those provided by the standard distribution of OpenSearch. These additional plugins have been built by OpenSearch developers or members of the OpenSearch community. Most are maintained in the [OpenSearch/plugins](https://github.com/opensearch-project/OpenSearch/tree/main/plugins) directory on GitHub and can be installed by name, for example, by running `bin/opensearch-plugin install <plugin-name>`. To list all plugins that you can install by name, run `bin/opensearch-plugin install --help`. Plugins maintained in a separate repository, such as `opensearch-jvector`, must be installed from a downloaded package. + +The following table lists commonly used additional plugins and the earliest OpenSearch version in which each is available. + +| Plugin name | Earliest available version | +|:---|:---| +| `analysis-icu` | 1.0.0 | +| `analysis-kuromoji` | 1.0.0 | +| `analysis-nori` | 1.0.0 | +| [`analysis-phonenumber`]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/phone-analyzers/) | 2.18.0 | +| `analysis-phonetic` | 1.0.0 | +| `analysis-smartcn` | 1.0.0 | +| [`analysis-stempel`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/polish/) | 1.0.0 | +| [`analysis-ukrainian`]({{site.url}}{{site.baseurl}}/analyzers/language-analyzers/ukrainian/) | 1.0.0 | +| `discovery-azure-classic` | 1.0.0 | +| `discovery-ec2` | 1.0.0 | +| `discovery-gce` | 1.0.0 | +| [`ingest-attachment`]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/ingest-attachment-plugin/) | 1.0.0 | +| `ingestion-kafka` | 3.0.0 | +| `ingestion-kinesis` | 3.0.0 | +| `mapper-annotated-text` | 1.0.0 | +| `mapper-murmur3` | 1.0.0 | +| [`mapper-size`]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/mapper-size-plugin/) | 1.0.0 | +| [`opensearch-jvector`]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/opensearch-jvector/) | 3.5.0 | +| `repository-azure` | 1.0.0 | +| `repository-gcs` | 1.0.0 | +| `repository-hdfs` | 1.0.0 | +| `repository-s3` | 1.0.0 | +| `store-smb` | 1.0.0 | +| `transport-grpc` | 3.0.0 | +| `workload-management` | 2.18.0 | + +## Related documentation + +- [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) +- [`ingest-attachment` plugin]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/ingest-attachment-plugin/) +- [`mapper-size` plugin]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/mapper-size-plugin/) +- [`opensearch-jvector` plugin]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/opensearch-jvector/) diff --git a/_install-and-configure/additional-plugins/ingest-attachment-plugin.md b/_install-and-configure/additional-plugins/ingest-attachment-plugin.md new file mode 100644 index 00000000..903192ba --- /dev/null +++ b/_install-and-configure/additional-plugins/ingest-attachment-plugin.md @@ -0,0 +1,229 @@ +--- +layout: default +title: Ingest-attachment plugin +parent: Additional plugins +grand_parent: Managing OpenSearch plugins +nav_order: 20 + +--- + +# Ingest-attachment plugin + +The `ingest-attachment` plugin enables OpenSearch to extract content and other information from files using the Apache text extraction library [Tika](https://tika.apache.org/). +Supported document formats include PPT, PDF, RTF, ODF, and many more. See Tika [supported document formats](https://tika.apache.org/3.2.2/formats.html). + +The input field must be a Base64-encoded binary. + +## Installing the plugin + +Install the `ingest-attachment` plugin using the following command: + +```sh +./bin/opensearch-plugin install ingest-attachment +``` + +## Attachment processor options + +| Name | Required | Default | Description | +| :--- | :--- | :--- | :--- | +| `field` | Yes | N/A | The field from which to get the Base64-encoded binary. | +| `target_field` | No | Attachment | The field that stores the attachment information. | +| `properties` | No | All properties | An array of properties that should be stored. Can be `content`, `language`, `date`, `title`, `author`, `keywords`, `content_type`, or `content_length`. | +| `indexed_chars` | No | `100_000` | The number of characters used for extraction to prevent fields from becoming too large. Use `-1` for no limit. | +| `indexed_chars_field` | No | `null` | The field name used to overwrite the number of chars being used for extraction, for example, `indexed_chars`. | +| `ignore_missing` | No | `false` | When `true`, the processor exits without modifying the document when the specified field doesn't exist. | + +## Example + +The following steps show you how to get started with the `ingest-attachment` plugin. + +### Step 1: Create an index for storing your attachments + +The following command creates an index for storing your attachments: + +```json +PUT /example-attachment-index +{ + "mappings": { + "properties": {} + } +} +``` + +### Step 2: Create a pipeline + +The following command creates a pipeline containing the attachment processor: + +```json +PUT _ingest/pipeline/attachment +{ + "description" : "Extract attachment information", + "processors" : [ + { + "attachment" : { + "field" : "data" + } + } + ] +} +``` + +### Step 3: Store an attachment + +Convert the attachment to a Base64 string to pass it as `data`. +In this example the `base64` command converts the file `lorem.rtf`: + +```sh +base64 lorem.rtf +``` + +Alternatively, you can use Node.js to read the file to `base64`, as shown in the following commands: + +```typescript +import * as fs from "node:fs/promises"; +import path from "node:path"; + +const filePath = path.join(import.meta.dirname, "lorem.rtf"); +const base64File = await fs.readFile(filePath, { encoding: "base64" }); + +console.log(base64File); +``` + +The`.rtf` file contains the following Base64 text: + +`Lorem ipsum dolor sit amet`: +`e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=`. + +```json +PUT example-attachment-index/_doc/lorem_rtf?pipeline=attachment +{ + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=" +} +``` + +### Query results + +With the attachment processed, you can now search through the data using search queries, as shown in the following example: + +```json +POST example-attachment-index/_search +{ + "query": { + "match": { + "attachment.content": "ipsum" + } + } +} +``` + +OpenSearch responds with the following: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.1724279, + "hits": [ + { + "_index": "example-attachment-index", + "_id": "lorem_rtf", + "_score": 1.1724279, + "_source": { + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=", + "attachment": { + "content_type": "application/rtf", + "language": "pt", + "content": "Lorem ipsum dolor sit amet", + "content_length": 28 + } + } + } + ] + } +} +``` + +## Extracted information + +The following fields can be extracted using the plugin: + +- `content` +- `language` +- `date` +- `title` +- `author` +- `keywords` +- `content_type` +- `content_length` + +To extract only a subset of these fields, define them in the `properties` of the +pipeline processor, as shown in the following example: + +```json +PUT _ingest/pipeline/attachment +{ + "description" : "Extract attachment information", + "processors" : [ + { + "attachment" : { + "field" : "data", + "properties": ["content", "title", "author"] + } + } + ] +} +``` + +## Limit the extracted content + +To prevent extracting too many characters and overloading the node memory, the default limit is `100_000`. +You can change this value using the setting `indexed_chars`. For example, you can use `-1` for unlimited characters, but you need to make sure you have enough HEAP space on your OpenSearch node to extract the content of large documents. + +You can also define this limit per document using the `indexed_chars_field` request field. +If a document contains `indexed_chars_field`, it will overwrite the `indexed_chars` setting, as shown in the following example: + +```json +PUT _ingest/pipeline/attachment +{ + "description" : "Extract attachment information", + "processors" : [ + { + "attachment" : { + "field" : "data", + "indexed_chars" : 10, + "indexed_chars_field" : "max_chars", + } + } + ] +} +``` + +With the attachment pipeline configured, you can extract the default `10` characters without specifying `max_chars` in the request, as shown in the following example: + +```json +PUT example-attachment-index/_doc/lorem_rtf?pipeline=attachment +{ + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=" +} +``` + +Alternatively, you can change the `max_char` per document in order to extract up to `15` characters, as shown in the following example: + +```json +PUT example-attachment-index/_doc/lorem_rtf?pipeline=attachment +{ + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=", + "max_chars": 15 +} +``` diff --git a/_install-and-configure/additional-plugins/mapper-size-plugin.md b/_install-and-configure/additional-plugins/mapper-size-plugin.md new file mode 100644 index 00000000..133140de --- /dev/null +++ b/_install-and-configure/additional-plugins/mapper-size-plugin.md @@ -0,0 +1,101 @@ +--- +layout: default +title: Mapper-size plugin +parent: Additional plugins +grand_parent: Managing OpenSearch plugins +nav_order: 25 + +--- + +# Mapper-size plugin + +The `mapper-size` plugin enables the use of the `_size` field in OpenSearch indexes. The `_size` field stores the size, in bytes, of each document. + +## Installing the plugin + +You can install the `mapper-size` plugin using the following command: + +```sh +./bin/opensearch-plugin install mapper-size +``` + +## Examples + +After starting up a cluster, you can create an index with size mapping enabled, index a document, and search for documents, as shown in the following examples. + +### Create an index with size mapping enabled + +```sh +curl -XPUT example-index -H "Content-Type: application/json" -d '{ + "mappings": { + "_size": { + "enabled": true + }, + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } +}' +``` + +### Index a document + +```sh +curl -XPOST example-index/_doc -H "Content-Type: application/json" -d '{ + "name": "John Doe", + "age": 30 +}' +``` + +### Query the index + +```sh +curl -XGET example-index/_search -H "Content-Type: application/json" -d '{ + "query": { + "match_all": {} + }, + "stored_fields": ["_size", "_source"] +}' +``` + +### Query results + +In the following example, the `_size` field is included in the query results and shows the size, in bytes, of the indexed document: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "example_index", + "_id": "Pctw0I8BLto8I5f_NLKK", + "_score": 1.0, + "_size": 37, + "_source": { + "name": "John Doe", + "age": 30 + } + } + ] + } +} +``` + diff --git a/_install-and-configure/additional-plugins/opensearch-jvector.md b/_install-and-configure/additional-plugins/opensearch-jvector.md new file mode 100644 index 00000000..10a7542c --- /dev/null +++ b/_install-and-configure/additional-plugins/opensearch-jvector.md @@ -0,0 +1,116 @@ +--- +layout: default +title: OpenSearch JVector plugin +parent: Additional plugins +grand_parent: Managing OpenSearch plugins +nav_order: 30 +--- + +# OpenSearch JVector plugin +**Introduced 3.5** +{: .label .label-purple } + +The `opensearch-jvector` plugin provides the `jvector` engine for [vector search]({{site.url}}{{site.baseurl}}/vector-search/). The engine implements DiskANN-style approximate nearest neighbor search in pure Java using the [JVector](https://github.com/datastax/jvector) library, so it needs no native libraries and no Java Native Interface (JNI) layer. It supports vectors of up to 16,000 dimensions and indexes containing billions of documents, and you can refine searches with aggregations and filter clauses in the same way as with the built-in engines. + +Because the `jvector` engine builds indexes from quantized vectors that are read from disk, memory use stays bounded as a dataset grows beyond available memory. The engine also accepts concurrent inserts and merges segments incrementally, so it avoids the graph rebuilds that continuous indexing causes with the built-in engines. These properties make it suitable for recommendation systems, image and video similarity search, semantic document search, and fraud detection pipelines that index millions to billions of vectors. + +The plugin replaces the k-NN plugin, so it also provides the `lucene` engine, which works the same way as in the k-NN plugin. The `faiss` and `nmslib` engines aren't available. + +The `opensearch-jvector` plugin isn't included in any OpenSearch distribution, and it can't run alongside the k-NN plugin. Installing it requires removing `opensearch-knn`. +{: .note} + +## Features + +The `jvector` engine provides the following capabilities: + +- Because the engine is written in pure Java and needs no native libraries or JNI layer, deployment and maintenance are simpler than with the built-in engines. +- Indexes are fully thread-safe and accept concurrent inserts and updates, scaling nearly linearly as the number of CPU cores increases. Ingestion throughput doesn't depend on merge operations for parallelism. +- Vectors can be added to an existing index incrementally, avoiding the full index rebuilds that frequent updates require, especially for large graph-based indexes. +- Quantization codebooks are refined incrementally during merges. This improves search accuracy and recall without recomputing the codebooks and reduces computational overhead. +- DiskANN-style quantization is combined with reranking, which keeps recall high for datasets larger than available memory, for which in-memory indexing isn't feasible. +- Product quantization (PQ) uses single instruction, multiple data (SIMD) optimizations and separate codebooks, providing fast search with low memory use. +- Advanced quantization techniques, such as Non-Uniform Vector Quantization (NVQ) and anisotropic PQ, compute similarity more accurately and with fewer resources than standard quantization. + +## Comparison with the k-NN plugin + +The following table compares the built-in k-NN plugin with the `opensearch-jvector` plugin. The last three rows describe the `jvector` engine; the `lucene` engine is unchanged from the k-NN plugin. + +| Aspect | k-NN plugin | JVector plugin | +| :--- | :--- | :--- | +| Engines | `faiss`, `lucene`, and `nmslib` (deprecated) | `jvector` and `lucene` | +| Methods | `hnsw` and `ivf` | `disk_ann` for `jvector` and `hnsw` for `lucene` | +| Default engine | `faiss` | `jvector` | +| Included in distributions | Yes | No | +| Concurrent ingestion | Varies by engine | The `jvector` engine accepts concurrent inserts | +| Index update cost | Graphs are rebuilt when segments merge | Merges are incremental, with no full graph rebuilds | +| Memory use | Vectors are held in memory unless you configure on-disk mode | Vectors are quantized and read from disk | + +For the methods, parameters, and space types that the `jvector` engine supports, see [JVector engine]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-methods-engines/#jvector-engine). + +## Installation + +Removing the k-NN plugin makes indexes that use the `faiss` or `nmslib` engine unreadable. Before you begin, confirm that no index in the cluster uses either engine, or reindex that data using the `lucene` engine while the k-NN plugin is still installed. Indexes that use the `lucene` engine remain searchable after the `opensearch-jvector` plugin is installed. +{: .warning} + +Repeat the following steps on every node in the cluster: + +1. Stop OpenSearch on the node. +1. Remove the neural search and k-NN plugins. Remove `opensearch-neural-search` first, because it depends on `opensearch-knn`: + + ```bash + bin/opensearch-plugin remove opensearch-neural-search + bin/opensearch-plugin remove opensearch-knn + ``` + {% include copy.html %} + +1. Install the `opensearch-jvector` plugin from Maven Central using the plugin's Maven coordinates: + + ```bash + bin/opensearch-plugin install org.opensearch.plugin:opensearch-jvector-plugin:{{site.opensearch_version}}.0 + ``` + {% include copy.html %} + + Installing by Maven coordinates requires a direct connection to Maven Central. If the node connects through a proxy or a local repository, install the plugin from its URL instead: + + ```bash + bin/opensearch-plugin install https://repo1.maven.org/maven2/org/opensearch/plugin/opensearch-jvector-plugin/{{site.opensearch_version}}.0/opensearch-jvector-plugin-{{site.opensearch_version}}.0.zip + ``` + {% include copy.html %} + +1. Start OpenSearch on the node. + +For a full list of available plugin versions, see the [`opensearch-jvector-plugin` directory](https://repo1.maven.org/maven2/org/opensearch/plugin/opensearch-jvector-plugin/) in Maven Central. To skip the prompt that requests confirmation of the plugin's additional permissions, add the `--batch` option to the `install` command. For more information, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#installing-a-plugin-using-maven-coordinates). + +To confirm that the plugin is installed, use the [CAT Plugins API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-plugins/): + +```json +GET _cat/plugins?v +``` +{% include copy-curl.html %} + +The response contains a row for `opensearch-jvector` on each node. + +## Supported OpenSearch features + +The plugin supports the following OpenSearch vector search features. + +| Feature | Available in plugin version | +| :--- | :--- | +| [Product quantization (PQ)]({{site.url}}{{site.baseurl}}/vector-search/optimizing-storage/knn-vector-quantization/) | 3.5.0 | +| [Maximal marginal relevance (MMR) reranking]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/vector-search-mmr/) | 3.6.0 | +| [Derived source]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/source/#derived-source) | 3.6.0 | + +## Limitations + +The plugin has the following limitations: + +- The plugin isn't part of any OpenSearch distribution, so you must install it manually on every node. +- The plugin and `opensearch-knn` can't be installed in the same cluster. +- The upstream `opensearch-neural-search` plugin doesn't recognize the `jvector` engine, so neural and hybrid queries aren't available. + +## Related documentation + +- [JVector engine]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-methods-engines/#jvector-engine) +- [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) +- [Vector search]({{site.url}}{{site.baseurl}}/vector-search/) +- [Using a JVector efficient filter]({{site.url}}{{site.baseurl}}/vector-search/filter-search-knn/efficient-knn-filtering/#using-a-jvector-efficient-filter) diff --git a/_install-and-configure/configuring-dashboards.md b/_install-and-configure/configuring-dashboards.md index 381e1457..458b95a8 100644 --- a/_install-and-configure/configuring-dashboards.md +++ b/_install-and-configure/configuring-dashboards.md @@ -6,6 +6,99 @@ nav_order: 15 # Configuring OpenSearch Dashboards -OpenSearch Dashboards uses the `opensearch_dashboards.yml` configuration file to read settings when you spin up a cluster. You can find `opensearch_dashboards.yml` in `/usr/share/opensearch-dashboards/config/opensearch_dashboards.yml` (Docker) or `/etc/opensearch-dashboards/opensearch_dashboards.yml` (most Linux distributions) on each node. +OpenSearch Dashboards reads its settings from the `opensearch_dashboards.yml` configuration file when it starts. The file location depends on how you installed OpenSearch Dashboards. -For information about OpenSearch Dashboards settings, see the sample [`opensearch_dashboards.yml`](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml) file. \ No newline at end of file +Installation method | File location +:--- | :--- +Docker | `/usr/share/opensearch-dashboards/config/opensearch_dashboards.yml` +Debian or RPM package | `/etc/opensearch-dashboards/opensearch_dashboards.yml` +Tarball or Windows ZIP archive | `config/opensearch_dashboards.yml` in the OpenSearch Dashboards installation directory + +After you change `opensearch_dashboards.yml`, restart OpenSearch Dashboards to apply the changes. + +Some OpenSearch Dashboards settings can also be changed in the UI without editing `opensearch_dashboards.yml`. For more information, see [Advanced settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/). + +## Example configuration file + +The following `opensearch_dashboards.yml` file configures OpenSearch Dashboards to accept connections on all network interfaces and to connect to an OpenSearch cluster that uses the Security plugin: + +```yaml +server.host: "0.0.0.0" +server.port: 5601 +opensearch.hosts: ["https://localhost:9200"] +opensearch.username: "kibanaserver" +opensearch.password: "<kibanaserver-password>" +opensearch.ssl.verificationMode: full +opensearch.ssl.certificateAuthorities: ["/etc/opensearch-dashboards/root-ca.pem"] +opensearch.requestHeadersAllowlist: ["authorization", "securitytenant"] +``` +{% include copy.html %} + +Replace `<kibanaserver-password>` with the password of the `kibanaserver` user and update the certificate authority path to match your environment. For information about the `kibanaserver` user, see [Multi-tenancy configuration]({{site.url}}{{site.baseurl}}/security/multi-tenancy/multi-tenancy-config/#kibana_server-role-details). + +For a list of all settings, see the sample [`opensearch_dashboards.yml`](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml) file in the OpenSearch Dashboards repository. + +## Server settings + +The following table lists the settings for the OpenSearch Dashboards server. + +Setting | Data type | Description +:--- | :--- | :--- +`server.host` | String | The host name or IP address to which the OpenSearch Dashboards server binds. To allow connections from other machines, set this to a non-loopback address or to `0.0.0.0`. Default is `localhost`. +`server.port` | Integer | The port on which OpenSearch Dashboards listens. Default is `5601`. +`server.name` | String | A display name for this OpenSearch Dashboards instance. Default is the machine's host name. +`server.basePath` | String | The path at which OpenSearch Dashboards is served when it runs behind a reverse proxy, for example, `/dashboards`. Must start with a slash (`/`) and must not end with one. Default is empty. +`server.rewriteBasePath` | Boolean | Whether OpenSearch Dashboards removes `server.basePath` from incoming request paths. Set to `false` if your reverse proxy removes the base path before forwarding requests. Default is `false`. + +## OpenSearch connection settings + +The following table lists the settings that control how OpenSearch Dashboards connects to OpenSearch. + +Setting | Data type | Description +:--- | :--- | :--- +`opensearch.hosts` | String or array of strings | The URLs of the OpenSearch nodes to which OpenSearch Dashboards sends requests. All nodes must belong to the same cluster. Default is `http://localhost:9200`. +`opensearch.username` | String | The user name that the OpenSearch Dashboards server uses to connect to OpenSearch, for example, to manage its own system index. +`opensearch.password` | String | The password for `opensearch.username`. +`opensearch.requestTimeout` | Integer | The amount of time, in milliseconds, to wait for a response from OpenSearch. Default is `30000` (30 seconds). +`opensearch.pingTimeout` | Integer | The amount of time, in milliseconds, to wait for OpenSearch to respond to a ping. Default is the value of `opensearch.requestTimeout`. +`opensearchDashboards.index` | String | The name of the index in which OpenSearch Dashboards stores saved objects, such as index patterns, visualizations, and dashboards. Default is `.kibana`. + +## TLS settings + +To encrypt traffic between the browser and OpenSearch Dashboards (`server.ssl.*` settings) or between OpenSearch Dashboards and OpenSearch (`opensearch.ssl.*` settings), see [Configuring TLS for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tls/). + +## Security plugin settings + +The Security plugin for OpenSearch Dashboards uses settings that start with `opensearch_security`. These settings are documented with the features that they configure: + +- OpenID Connect (`opensearch_security.openid.*`): See [OpenSearch Dashboards single sign-on]({{site.url}}{{site.baseurl}}/security/authentication-backends/openid-connect/#opensearch-dashboards-single-sign-on). +- SAML (`opensearch_security.saml.*`): See [OpenSearch Dashboards settings]({{site.url}}{{site.baseurl}}/security/authentication-backends/saml/#opensearch-dashboards-settings). +- Multiple authentication types on the sign-in page (`opensearch_security.auth.*`): See [Configuring Dashboards sign-in for multiple authentication options]({{site.url}}{{site.baseurl}}/security/configuration/multi-auth/). +- Multi-tenancy (`opensearch_security.multitenancy.*`): See [Multi-tenancy configuration]({{site.url}}{{site.baseurl}}/security/multi-tenancy/multi-tenancy-config/). + +## Logging settings + +By default, OpenSearch Dashboards writes logs to standard output. The following table lists the logging settings. + +Setting | Data type | Description +:--- | :--- | :--- +`logging.dest` | String | Where to write logs. Set to `stdout` or to the path of a log file. Default is `stdout`. +`logging.silent` | Boolean | If `true`, OpenSearch Dashboards writes no logs. Default is `false`. +`logging.quiet` | Boolean | If `true`, OpenSearch Dashboards writes only error messages. Default is `false`. +`logging.verbose` | Boolean | If `true`, OpenSearch Dashboards logs all events, including system usage information and all requests. Default is `false`. + +## Language settings + +To display the OpenSearch Dashboards interface in a language other than English, set `i18n.locale` to a locale code, for example: + +```yaml +i18n.locale: "fr-FR" +``` +{% include copy.html %} + +The default is `en`. Each available locale has a translation file in the [`src/translations`](https://github.com/opensearch-project/OpenSearch-Dashboards/tree/main/src/translations) directory of the OpenSearch Dashboards repository, named after its locale code. Translations can be incomplete, so some text may still appear in English. + +## Related documentation + +- [Settings and administration]({{site.url}}{{site.baseurl}}/dashboards/settings-and-administration/) +- [Advanced settings]({{site.url}}{{site.baseurl}}/dashboards/management/advanced-settings/) diff --git a/_install-and-configure/configuring-opensearch/admission-control-settings.md b/_install-and-configure/configuring-opensearch/admission-control-settings.md new file mode 100644 index 00000000..f2eae731 --- /dev/null +++ b/_install-and-configure/configuring-opensearch/admission-control-settings.md @@ -0,0 +1,49 @@ +--- +layout: default +title: Admission control settings +parent: Configuring OpenSearch +nav_order: 130 +--- + +# Admission control settings + +OpenSearch provides admission control settings to help prevent cluster overload by limiting resource usage for different types of operations. Admission control monitors CPU and I/O usage and can reject requests when resource utilization exceeds configured thresholds. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## Transport layer settings + +OpenSearch supports the following transport layer admission control settings: + +- `admission_control.transport.mode` (Dynamic, string): Controls the overall admission control mode for the transport layer. Valid values are: + - `disabled` (default): Admission control is disabled. + - `shadow`: Admission control runs in monitoring mode only, collecting metrics without rejecting requests. + - `enforced`: Admission control actively rejects requests when thresholds are exceeded. + +## CPU-based admission control settings + +CPU-based admission control monitors CPU usage and applies limits to different types of operations. All CPU limits are specified as percentages (0--100). + +OpenSearch supports the following dynamic CPU-based admission control settings: + +- `admission_control.cluster.admin.cpu_usage.limit` (Dynamic, long): The CPU usage threshold for cluster administration operations. When CPU usage exceeds this limit, cluster admin requests may be rejected to preserve cluster stability. Default is `95`. + +- `admission_control.search.cpu_usage.limit` (Dynamic, long): The CPU usage threshold for search operations. When CPU usage exceeds this limit, new search requests may be rejected to prevent cluster overload. Default is `95`. + +- `admission_control.indexing.cpu_usage.limit` (Dynamic, long): The CPU usage threshold for indexing operations. When CPU usage exceeds this limit, indexing requests may be rejected to maintain cluster performance. Default is `95`. + +- `admission_control.transport.cpu_usage.mode_override` (Dynamic, string): Overrides the global transport mode specifically for CPU-based admission control. Accepts the same values as `admission_control.transport.mode`: `disabled`, `shadow`, or `enforced`. If not specified, uses the global transport mode setting. + +## I/O-based admission control settings + +I/O-based admission control monitors disk I/O usage and applies limits to different types of operations. All I/O limits are specified as percentages (0--100). + +OpenSearch supports the following I/O-based admission control settings: + +- `admission_control.search.io_usage.limit` (Dynamic, long): The I/O usage threshold for search operations. When I/O usage exceeds this limit, search requests may be rejected. Default is `95`. + +- `admission_control.indexing.io_usage.limit` (Dynamic, long): The I/O usage threshold for indexing operations. When I/O usage exceeds this limit, indexing requests may be rejected. Default is `95`. + +- `admission_control.cluster_admin.io_usage.limit` (Static, long): The I/O usage threshold for cluster administration operations. This is a static setting that requires a cluster restart to modify. Default is `100`. + +- `admission_control.transport.io_usage.mode_override` (Dynamic, string): Overrides the global transport mode specifically for I/O-based admission control. Accepts the same values as `admission_control.transport.mode`: `disabled`, `shadow`, or `enforced`. If not specified, uses the global transport mode setting. diff --git a/_install-and-configure/configuring-opensearch/availability-recovery.md b/_install-and-configure/configuring-opensearch/availability-recovery.md index d25396a6..9e09d75d 100644 --- a/_install-and-configure/configuring-opensearch/availability-recovery.md +++ b/_install-and-configure/configuring-opensearch/availability-recovery.md @@ -2,44 +2,60 @@ layout: default title: Availability and recovery settings parent: Configuring OpenSearch -nav_order: 90 +nav_order: 100 --- # Availability and recovery settings Availability and recovery settings include settings for the following: +- [General recovery settings](#general-recovery-settings) - [Snapshots](#snapshot-settings) - [Cluster manager task throttling](#cluster-manager-task-throttling-settings) - [Remote-backed storage](#remote-backed-storage-settings) - [Search backpressure](#search-backpressure-settings) +- [Concurrency limits](#concurrency-limit-settings) - [Shard indexing backpressure](#shard-indexing-backpressure-settings) - [Segment replication](#segment-replication-settings) - [Cross-cluster replication](#cross-cluster-replication-settings) -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## General recovery settings + +OpenSearch supports the following general recovery settings: + +- `indices.recovery.chunk_size` (Dynamic, byte unit): Controls the chunk size used when transferring data during index recovery operations. This setting affects the amount of data transferred in each network request during shard recovery. Larger chunk sizes can improve recovery speed but may increase memory usage. Default is `512kb`. + +- `indices.recovery.recovery_activity_timeout` (Dynamic, time unit): Sets the timeout for individual recovery activities during shard recovery operations. If a recovery activity (such as transferring a file chunk) takes longer than this timeout, the recovery operation is considered failed and will be retried. Default is `30m`. ## Snapshot settings OpenSearch supports the following snapshot settings: -- `snapshot.max_concurrent_operations`(Dynamic, integer): The maximum number of concurrent snapshot operations. Default is `1000`. +- `snapshot.max_concurrent_operations` (Dynamic, integer): The maximum number of concurrent snapshot operations. Default is `1000`. + +- `snapshot.repository_data.cache.threshold` (Static, byte size value or percentage): The maximum size of repository metadata that can be cached in memory. This setting improves snapshot operation performance by reducing the need to repeatedly download metadata during clone, restore, and status check operations. You can specify this value as an absolute size (for example, `2gb` or `500mb`) or as a percentage of heap memory (for example, `3%` or `1%`). Metadata that exceeds this threshold is not cached. Under heap memory pressure, cached data may be garbage collected automatically because it is stored using soft references. Default is 500 KB or 1% of heap memory, whichever is higher. ### Security-related snapshot settings For security-related snapshot settings, see [Security settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/security-settings/). -### File system settings +### Shared file system -For information about file system settings, see [Shared file system]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#shared-file-system). +For information about using a shared file system, see [Shared file system]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#shared-file-system). ### Amazon S3 settings For information about Amazon S3 repository settings, see [Amazon S3]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#amazon-s3). +### Azure Blob Storage settings + +For information about Azure Blob Storage repository settings, see [Configuring Microsoft Azure Blob Storage]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#configuring-microsoft-azure-blob-storage). + ## Cluster manager task throttling settings -For information about cluster manager task throttling settings, see [Setting throttling limits]({{site.url}}{{site.baseurl}}/tuning-your-cluster/cluster-manager-task-throttling/#setting-throttling-limits). +For information about cluster manager task throttling settings, see [Setting throttling limits]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/cluster-manager-task-throttling/#setting-throttling-limits). ## Remote-backed storage settings @@ -47,19 +63,23 @@ OpenSearch supports the following cluster-level remote-backed storage settings: - `cluster.remote_store.translog.buffer_interval` (Dynamic, time unit): The default value of the translog buffer interval used when performing periodic translog updates. This setting is only effective when the index setting `index.remote_store.translog.buffer_interval` is not present. -- `remote_store.moving_average_window_size` (Dynamic, integer): The moving average window size used to calculate the rolling statistic values exposed through the [Remote Store Stats API]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/remote-store-stats-api/). Default is `20`. Minimum enforced is `5`. - For more remote-backed storage settings, see [Remote-backed storage]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/index/) and [Configuring remote-backed storage]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/index/#configuring-remote-backed-storage). For remote segment backpressure settings, see [Remote segment backpressure settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/remote-segment-backpressure/#remote-segment-backpressure-settings). +For remote segment warmer settings, see [Remote segment warmer settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/remote-segment-warmer/#remote-segment-warmer-settings). + ## Search backpressure settings -Search backpressure is a mechanism used to identify resource-intensive search requests and cancel them when the node is under duress. For more information, see [Search backpressure settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/search-backpressure/#search-backpressure-settings). +Search backpressure is a mechanism used to identify resource-intensive search requests and cancel them when the node is under duress. For more information, see [Search backpressure settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/search-backpressure/#search-backpressure-settings). + +## Concurrency limit settings + +Concurrency limits adaptively restrict the number of active requests for any transport action. For more information, see [Concurrency limit settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/concurrency-limits/#concurrency-limit-settings). ## Shard indexing backpressure settings -Shard indexing backpressure is a smart rejection mechanism at a per-shard level that dynamically rejects indexing requests when your cluster is under strain. For more information, see shard indexing backpressure [settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/shard-indexing-settings/). +Shard indexing backpressure is a smart rejection mechanism at a per-shard level that dynamically rejects indexing requests when your cluster is under strain. For more information, see shard indexing backpressure [settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/load-protection/shard-indexing-settings/). ## Segment replication settings diff --git a/_install-and-configure/configuring-opensearch/cache-settings.md b/_install-and-configure/configuring-opensearch/cache-settings.md new file mode 100644 index 00000000..586b0c2a --- /dev/null +++ b/_install-and-configure/configuring-opensearch/cache-settings.md @@ -0,0 +1,26 @@ +--- +layout: default +title: Cache settings +parent: Configuring OpenSearch +nav_order: 70 +--- + +# Cache settings + +OpenSearch provides various cache settings to optimize memory usage and performance. These settings control how OpenSearch manages cached data structures and memory allocation for caching operations. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## Cache recycler settings + +The cache recycler manages the reuse of memory pages to reduce garbage collection overhead. OpenSearch supports the following cache recycler settings: + +- `cache.recycler.page.limit.heap` (Static, byte size): The memory size limit for page cache recycler heap usage. Default is `10%` of heap. + +- `cache.recycler.page.weight.bytes` (Static, double): The weight factor for byte page recycling in the cache recycler. Default is `1.0`. Minimum is `0.0`. + +- `cache.recycler.page.weight.ints` (Static, double): The weight factor for integer page recycling in the cache recycler. Default is `1.0`. Minimum is `0.0`. + +- `cache.recycler.page.weight.longs` (Static, double): The weight factor for long page recycling in the cache recycler. Default is `1.0`. Minimum is `0.0`. + +- `cache.recycler.page.weight.objects` (Static, double): The weight factor for object page recycling in the cache recycler. Object pages are less useful so given lower weight by default. Default is `0.1`. Minimum is `0.0`. \ No newline at end of file diff --git a/_install-and-configure/configuring-opensearch/circuit-breaker.md b/_install-and-configure/configuring-opensearch/circuit-breaker.md index a32d5d92..2a2bed95 100644 --- a/_install-and-configure/configuring-opensearch/circuit-breaker.md +++ b/_install-and-configure/configuring-opensearch/circuit-breaker.md @@ -2,14 +2,14 @@ layout: default title: Circuit breaker settings parent: Configuring OpenSearch -nav_order: 50 +nav_order: 120 --- # Circuit breaker settings Circuit breakers prevent OpenSearch from causing a Java OutOfMemoryError. The parent circuit breaker specifies the total available amount of memory for all child circuit breakers. The child circuit breakers specify the total available amount of memory for themselves. -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). ## Parent circuit breaker settings @@ -45,20 +45,12 @@ The in-flight request circuit breaker limits the memory usage for all currently ## Script compilation circuit breaker settings -The script compilation circuit breaker limits the number of inline script compilations within a time interval. OpenSearch supports the following script compilation circuit breaker setting: - -- `script.max_compilations_rate` (Dynamic, rate): The maximum number of unique dynamic scripts compiled within a time interval for a given context. Default is 150 every 5 minutes (`150/5m`). +The script compilation circuit breaker limits the number of unique scripts that OpenSearch compiles within a time interval. When the limit is exceeded, OpenSearch returns a `circuit_breaking_exception`. By default, each script context has its own limit of 75 compilations every 5 minutes, set by `script.context.<context>.max_compilations_rate`. The `script.max_compilations_rate` setting replaces the per-context limits with a single cluster-wide limit. For more information, see [Script compilation settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/script-and-resource-settings/#script-compilation-settings). ## Regular expression circuit breaker settings The regular expression circuit breaker enables or disables regular expressions and limits their complexity. OpenSearch supports the following regular expression circuit breaker settings: -- `script.painless.regex.enabled` (Static, string): Enables regular expressions in Painless scripts. - Valid values are: - - `limited`: Enables regular expressions and limits their complexity using the `script.painless.regex.limit-factor` setting. - - `true`: Enables regular expressions. Turns off the regular expression circuit breaker and does not limit regular expression complexity. - - `false`: Disables regular expressions. If a Painless script contains a regular expression, it returns an error. +- `script.painless.regex.enabled` (Static, string): Determines whether Painless scripts can contain regular expressions and whether their complexity is bounded. Valid values are `limited`, `true`, and `false`. Default is `limited`. For a description of each value, see [Controlling regular expressions]({{site.url}}{{site.baseurl}}/scripting/painless/#controlling-regular-expressions). - Default is `limited`. - -- `script.painless.regex.limit-factor` (Static, integer): Applied only if `script.painless.regex.enabled` is set to `limited`. Limits the number of characters a regular expression in a Painless script. The character limit is calculated by multiplying the number of characters in the script input by `script.painless.regex.limit-factor`. Default is 6 (thus, if the input has 5 characters, the maximum number of characters in a regular expression is 5 · 6 = 30). +- `script.painless.regex.limit-factor` (Static, integer): Applied only when `script.painless.regex.enabled` is set to `limited`. Limits the number of characters that a regular expression in a Painless script can examine. The character limit is calculated by multiplying the number of characters in the script input by `script.painless.regex.limit-factor`. Default is `6`, so if the input has 5 characters, the regular expression can examine at most 5 · 6 = 30 characters. diff --git a/_install-and-configure/configuring-opensearch/cluster-settings-for-indexes.md b/_install-and-configure/configuring-opensearch/cluster-settings-for-indexes.md new file mode 100644 index 00000000..cfb04e0a --- /dev/null +++ b/_install-and-configure/configuring-opensearch/cluster-settings-for-indexes.md @@ -0,0 +1,101 @@ +--- +layout: default +title: Cluster settings for indexes +parent: Configuring OpenSearch +nav_order: 60 +--- + +# Cluster settings for indexes + +The following cluster settings apply to all indexes in the cluster. For settings that apply to individual indexes, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## Static settings + +OpenSearch supports the following static cluster settings for indexes: + +- `indices.cache.cleanup_interval` (Static, time unit): Schedules a recurring background task that cleans up expired entries from the cache at the specified interval. Default is `1m` (1 minute). For more information, see [Index request cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/request-cache/). + +- `indices.requests.cache.size` (Static, string): The cache size as a percentage of the heap size (for example, to use 1% of the heap, specify `1%`). Default is `1%`. For more information, see [Index request cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/request-cache/). + +- `indices.analysis.hunspell.dictionary.ignore_case` (Static, Boolean): Controls whether Hunspell dictionary matching ignores case globally for all locales. When enabled, dictionary matching becomes case insensitive. This setting can be configured at multiple levels: node level (this setting), per-locale using `indices.analysis.hunspell.dictionary.<locale>.ignore_case` (for example, `indices.analysis.hunspell.dictionary.en_US.ignore_case`), or in dictionary-specific `settings.yml` files within each dictionary directory. Per-locale and dictionary-specific settings override the global setting. Default is `false`. + +- `indices.analysis.hunspell.dictionary.lazy` (Static, Boolean): Controls when Hunspell dictionaries are loaded. If `true`, dictionary loading is deferred until a dictionary is actually used, reducing startup time but potentially increasing latency on first use. If `false`, the dictionary directory is checked and all dictionaries are automatically loaded when the node starts. Default is `false`. + +- `indices.analysis.hunspell.dictionary.<locale>.strict_affix_parsing` (Static, Boolean): Controls whether errors encountered while reading Hunspell affix rules files cause exceptions or are silently ignored. When set to `true`, parsing errors in affix files will throw exceptions and prevent dictionary loading. When set to `false`, parsing errors are ignored and the dictionary continues to load. This setting can be configured per locale by replacing `<locale>` with the specific locale code (for example, `indices.analysis.hunspell.dictionary.en_US.strict_affix_parsing`). Default is `true`. + +- `indices.memory.index_buffer_size` (Static, string): Controls the amount of heap memory allocated for indexing operations across all shards on a node. Accepts either a percentage (like `10%`) or a byte size value (like `512mb`). This buffer is shared across all shards and is used to batch indexing operations before writing to disk. Default is `10%` of the total heap. + +- `indices.memory.min_index_buffer_size` (Static, byte unit): Sets the absolute minimum size for the indexing buffer when `indices.memory.index_buffer_size` is specified as a percentage. This ensures the indexing buffer never becomes too small on nodes with limited heap memory. Default is `48mb`. + +- `indices.memory.max_index_buffer_size` (Static, byte unit): Sets the absolute maximum size for the indexing buffer when `indices.memory.index_buffer_size` is specified as a percentage. This prevents the indexing buffer from consuming too much memory on nodes with large heaps. Default is unbounded (no limit). + +- `indices.queries.cache.size` (Static, string): Controls the memory size allocated for the query cache (filter cache) on each data node. The query cache stores the results of frequently used filters to improve search performance. Accepts either a percentage value (like `5%`) or an exact byte value (like `512mb`). Default is `10%` of heap memory. + +- `indices.queries.cache.all_segments` (Static, Boolean): Whether to cache queries across all segments or only frequently accessed ones. + +- `indices.queries.cache.count` (Static, integer): The maximum number of queries to cache. + +- `index.store.hybrid.nio.extensions` (Static, list): **Expert setting.** Lucene file extensions to load with NIO instead of memory mapping. Default includes common extensions like `segments_N`, `write.lock`, `si`, and `cfe`. + +- `indexing_pressure.memory.limit` (Static, byte size): Controls the memory limit for indexing operations to prevent memory exhaustion during heavy indexing workloads. When indexing operations exceed this threshold, they may be rejected or throttled to protect cluster stability. Accepts percentage values (like `10%` of heap) or byte size values (like `512mb`). Default is `10%` of the total heap memory. + +- `indices.query.query_string.allowLeadingWildcard` (Static, Boolean): Controls whether leading wildcards are allowed in query string queries. When enabled, queries like `*term` or `?term` are permitted but may impact performance as they require scanning all terms in the index. When disabled, leading wildcard queries are rejected to improve query performance. Default is `true`. + +- `indices.query.query_string.analyze_wildcard` (Static, Boolean): Controls whether wildcard terms in query string queries are analyzed using the configured analyzer. When enabled, wildcard queries undergo analysis (tokenization, filtering) which can improve matching but may affect performance. When disabled, wildcard terms are used as-is without analysis. Default is `false`. + +- `indices.time_series_index.default_index_merge_policy` (Static, string): Sets the default merge policy for time series indices across the cluster. This setting controls how Lucene segments are merged for time-series data, which can significantly impact indexing performance and storage efficiency. Valid values include `default`, `tiered`, and `log_byte_size`. Default is `default`. + +- `cluster.remote_store.translog.path.prefix` (Static, string): Controls the fixed path prefix for translog data on a remote-store-enabled cluster. This setting only applies when the `cluster.remote_store.index.path.type` setting is either `HASHED_PREFIX` or `HASHED_INFIX`. Default is an empty string, `""`. + +- `cluster.remote_store.segments.path.prefix` (Static, string): Controls the fixed path prefix for segment data on a remote-store-enabled cluster. This setting only applies when the `cluster.remote_store.index.path.type` setting is either `HASHED_PREFIX` or `HASHED_INFIX`. Default is an empty string, `""`. + +- `cluster.snapshot.shard.path.prefix` (Static, string): Controls the fixed path prefix for snapshot shard-level blobs. This setting only applies when the repository `shard_path_type` setting is either `HASHED_PREFIX` or `HASHED_INFIX`. Default is an empty string, `""`. + +## Dynamic settings + +OpenSearch supports the following dynamic cluster settings for indexes: + +- `action.auto_create_index` (Dynamic, Boolean): Automatically creates an index if the index doesn't already exist. Also applies any index templates that are configured. Default is `true`. + +- `action.destructive_requires_name` (Dynamic, Boolean): When `true`, you must specify the index name to delete an index. You cannot delete all indexes or use wildcards. Default is `false`. + +- `cluster.default.index.refresh_interval` (Dynamic, time unit): Sets the refresh interval when the `index.refresh_interval` setting is not provided. This setting can be useful when you want to set a default refresh interval across all indexes in a cluster and support the `searchIdle` setting. You cannot set the interval lower than the `cluster.minimum.index.refresh_interval` setting. + +- `cluster.minimum.index.refresh_interval` (Dynamic, time unit): Sets the minimum refresh interval and applies it to all indexes in the cluster. The `cluster.default.index.refresh_interval` setting should be higher than this setting's value. If, during index creation, the `index.refresh_interval` setting is lower than the minimum set, index creation fails. + +- `cluster.indices.close.enable` (Dynamic, Boolean): Enables closing of open indexes in OpenSearch. Default is `true`. + +- `indices.recovery.max_bytes_per_sec` (Dynamic, string): Limits the total inbound and outbound recovery traffic for each node. This applies to peer recoveries and snapshot recoveries. Default is `40mb`. If you set the recovery traffic value to less than or equal to `0mb`, rate limiting will be disabled, which causes recovery data to be transferred at the highest possible rate. + +- `indices.recovery.max_concurrent_file_chunks` (Dynamic, integer): The number of file chunks sent in parallel for each recovery operation. Default is `2`. + +- `indices.recovery.max_concurrent_operations` (Dynamic, integer): The number of operations sent in parallel for each recovery. Default is `1`. + +- `indices.recovery.max_concurrent_remote_store_streams` (Dynamic, integer): The number of streams to the remote repository that can be opened in parallel when recovering a remote store index. Default is `20`. + +- `indices.replication.max_bytes_per_sec` (Dynamic, string): Limits the total inbound and outbound replication traffic for each node. If a value is not specified in the configured value the `indices.recovery.max_bytes_per_sec` setting is used, which defaults to 40 Mb. If you set the replication traffic value to less than or equal to 0 Mb, rate limiting is disabled, which causes replication data to be transferred at the highest possible rate. + +- `indices.fielddata.cache.size` (Dynamic, string): The maximum size of the field data cache. May be specified as an absolute value (for example, `8GB`) or a percentage of the node heap (for example, `50%`). This setting is dynamic. If you don't specify this setting, the maximum size is `35%`. This value should be smaller than the `indices.breaker.fielddata.limit`. For more information, see [Field data circuit breaker]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/circuit-breaker/#field-data-circuit-breaker-settings). + +- `indices.query.bool.max_clause_count` (Dynamic, integer): Defines the maximum product of fields and terms that can be searched simultaneously. Before OpenSearch 2.16, a cluster restart was required in order to apply this static setting. Now dynamic, existing search thread pools may use the old static value initially, causing `TooManyClauses` exceptions. New thread pools use the updated value. Default is `1024`. + +- `cluster.remote_store.index.path.type` (Dynamic, string): The path strategy for the data stored in the remote store. This setting is effective only for remote-store-enabled clusters. This setting supports the following values: + - `fixed`: Stores the data in path structure `<repository_base_path>/<index_uuid>/<shard_id>/`. + - `hashed_prefix`: Stores the data in path structure `hash(<shard-data-idenitifer>)/<repository_base_path>/<index_uuid>/<shard_id>/`. + - `hashed_infix`: Stores the data in path structure `<repository_base_path>/hash(<shard-data-idenitifer>)/<index_uuid>/<shard_id>/`. + `shard-data-idenitifer` is characterized by the index_uuid, shard_id, kind of data (translog, segments), and type of data (data, metadata, lock_files). + Default is `fixed`. + +- `cluster.remote_store.index.path.hash_algorithm` (Dynamic, string): The hash function used to derive the hash value when `cluster.remote_store.index.path.type` is set to `hashed_prefix` or `hashed_infix`. This setting is effective only for remote-store-enabled clusters. This setting supports the following values: + - `fnv_1a_base64`: Uses the FNV1a hash function and generates a url-safe 20-bit Base64-encoded hash value. + - `fnv_1a_composite_1`: Uses the FNV1a hash function and generates a custom encoded hash value that scales well with most remote store options. The FNV1a function generates 64-bit value. The custom encoding uses the most significant 6 bits to create a URL-safe Base64 character and the next 14 bits to create a binary string. Default is `fnv_1a_composite_1`. + +- `cluster.remote_store.translog.transfer_timeout` (Dynamic, time unit): Controls the timeout value while uploading translog and checkpoint files during a sync to the remote store. This setting is applicable only for remote-store-enabled clusters. Default is `30s`. + +- `cluster.remote_store.index.segment_metadata.retention.max_count` (Dynamic, integer): Controls the minimum number of metadata files to keep in the segment repository on a remote store. A value below `1` disables the deletion of stale segment metadata files. Default is `10`. + +- `cluster.remote_store.segment.transfer_timeout` (Dynamic, time unit): Controls the maximum amount of time to wait for all new segments to update after refresh to the remote store. If the upload does not complete within a specified amount of time, it throws a `SegmentUploadFailedException` error. Default is `30m`. It has a minimum constraint of `10m`. + +- `cluster.default_number_of_replicas` (Dynamic, integer): Controls the default number of replicas for indexes in the cluster. The index-level `index.number_of_replicas` setting defaults to this value if not configured. Default is `1`. diff --git a/_install-and-configure/configuring-opensearch/cluster-settings.md b/_install-and-configure/configuring-opensearch/cluster-settings.md index c10f8773..8f8ba4b2 100644 --- a/_install-and-configure/configuring-opensearch/cluster-settings.md +++ b/_install-and-configure/configuring-opensearch/cluster-settings.md @@ -1,21 +1,21 @@ --- layout: default -title: Cluster settings +title: Cluster management settings parent: Configuring OpenSearch -nav_order: 60 +nav_order: 50 --- -# Cluster settings +# Cluster management settings -The following settings are related to the OpenSearch cluster. +The following settings control shard allocation, coordination, fault detection, and other cluster-wide operations. -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). ## Cluster-level routing and allocation settings -OpenSearch supports the following cluster-level routing and shard allocation settings. All settings in this list are dynamic: +OpenSearch supports the following cluster-level routing and shard allocation settings: -- `cluster.routing.allocation.enable` (String): Enables or disables allocation for specific kinds of shards. +- `cluster.routing.allocation.enable` (Dynamic, string): Enables or disables allocation for specific kinds of shards. Valid values are: - `all` – Allows shard allocation for all types of shards. @@ -25,17 +25,19 @@ OpenSearch supports the following cluster-level routing and shard allocation set Default is `all`. -- `cluster.routing.allocation.node_concurrent_incoming_recoveries` (Integer): Configures how many concurrent incoming shard recoveries are allowed to happen on a node. Default is `2`. +- `cluster.routing.allocation.node_concurrent_incoming_recoveries` (Dynamic, integer): Configures how many concurrent incoming shard recoveries are allowed to occur on a node. Default is `2`. -- `cluster.routing.allocation.node_concurrent_outgoing_recoveries` (Integer): Configures how many concurrent outgoing shard recoveries are allowed to happen on a node. Default is `2`. +- `cluster.routing.allocation.node_concurrent_outgoing_recoveries` (Dynamic, integer): Configures how many concurrent outgoing shard recoveries are allowed to occur on a node. Default is `2`. -- `cluster.routing.allocation.node_concurrent_recoveries` (String): Used to set `cluster.routing.allocation.node_concurrent_incoming_recoveries` and `cluster.routing.allocation.node_concurrent_outgoing_recoveries` to the same value. +- `cluster.routing.allocation.node_concurrent_recoveries` (Dynamic, string): Used to set `cluster.routing.allocation.node_concurrent_incoming_recoveries` and `cluster.routing.allocation.node_concurrent_outgoing_recoveries` to the same value. -- `cluster.routing.allocation.node_initial_primaries_recoveries` (Integer): Sets the number of recoveries for unassigned primaries after a node restart. Default is `4`. +- `cluster.routing.allocation.node_initial_primaries_recoveries` (Dynamic, integer): Sets the number of recoveries for unassigned primaries after a node restart. Default is `4`. -- `cluster.routing.allocation.same_shard.host` (Boolean): When set to `true`, multiple copies of a shard are prevented from being allocated to distinct nodes on the same host. Default is `false`. +- `cluster.routing.allocation.unassigned.node_left.delayed_timeout` (Dynamic, time unit): Sets the default amount of time OpenSearch waits before allocating a replica shard that became unassigned after a node leaves the cluster. Delaying allocation helps avoid unnecessary shard recoveries during rolling upgrades, node restarts, and transient network failures. This setting applies only to indexes for which the index-level `index.unassigned.node_left.delayed_timeout` setting is not configured. Set to `0` to disable delayed allocation for indexes that use the cluster default. Default is `1m`. -- `cluster.routing.rebalance.enable` (String): Enables or disables rebalancing for specific kinds of shards. +- `cluster.routing.allocation.same_shard.host` (Dynamic, Boolean): When set to `true`, multiple copies of a shard are prevented from being allocated to distinct nodes on the same host. Default is `false`. + +- `cluster.routing.rebalance.enable` (Dynamic, string): Enables or disables rebalancing for specific kinds of shards. Valid values are: - `all` – Allows shard balancing for all types of shards. @@ -45,7 +47,7 @@ OpenSearch supports the following cluster-level routing and shard allocation set Default is `all`. -- `cluster.routing.allocation.allow_rebalance` (String): Specifies when shard rebalancing is allowed. +- `cluster.routing.allocation.allow_rebalance` (Dynamic, string): Specifies when shard rebalancing is allowed. Valid values are: - `always` – Always allow rebalancing. @@ -54,31 +56,57 @@ OpenSearch supports the following cluster-level routing and shard allocation set Default is `indices_all_active`. -- `cluster.routing.allocation.cluster_concurrent_rebalance` (Integer): Allows you to control how many concurrent shard rebalances are allowed across a cluster. Default is `2`. +- `cluster.routing.allocation.cluster_concurrent_rebalance` (Dynamic, integer): Allows you to control how many concurrent shard rebalances are allowed across a cluster. Default is `2`. -- `cluster.routing.allocation.balance.shard` (Floating point): Defines the weight factor for the total number of shards allocated per node. Default is `0.45`. +- `cluster.routing.allocation.balance.shard` (Dynamic, floating point): Defines the weight factor for the total number of shards allocated per node. Default is `0.45`. -- `cluster.routing.allocation.balance.index` (Floating point): Defines the weight factor for the number of shards per index allocated on a node. Default is `0.55`. +- `cluster.routing.allocation.balance.index` (Dynamic, floating point): Defines the weight factor for the number of shards per index allocated on a node. Default is `0.55`. -- `cluster.routing.allocation.balance.threshold` (Floating point): The minimum optimization value of operations that should be performed. Default is `1.0`. +- `cluster.routing.allocation.balance.threshold` (Dynamic, floating point): The minimum optimization value of operations that should be performed. Default is `1.0`. -- `cluster.routing.allocation.balance.prefer_primary` (Boolean): When set to `true`, OpenSearch attempts to evenly distribute the primary shards between the cluster nodes. Enabling this setting does not always guarantee an equal number of primary shards on each node, especially in the event of failover. Changing this setting to `false` after it was set to `true` does not invoke redistribution of primary shards. Default is `false`. +- `cluster.routing.allocation.balance.prefer_primary` (Dynamic, Boolean): When set to `true`, OpenSearch attempts to evenly distribute the primary shards between the cluster nodes. Enabling this setting does not always guarantee an equal number of primary shards on each node, especially in the event of a failover. Changing this setting to `false` after it was set to `true` does not invoke redistribution of primary shards. Default is `false`. -- `cluster.routing.allocation.disk.threshold_enabled` (Boolean): When set to `false`, disables the disk allocation decider. This will also remove any existing `index.blocks.read_only_allow_delete index blocks` when disabled. Default is `true`. +- `cluster.routing.allocation.rebalance.primary.enable` (Dynamic, Boolean): When set to `true`, OpenSearch attempts to rebalance the primary shards between the cluster nodes. When enabled, the cluster tries to maintain the number of primary shards on each node, with the maximum buffer defined by the `cluster.routing.allocation.rebalance.primary.buffer` setting. Changing this setting to `false` after it was set to `true` does not invoke the redistribution of primary shards. Default is `false`. -- `cluster.routing.allocation.disk.watermark.low` (String): Controls the low watermark for disk usage. When set to a percentage, OpenSearch will not allocate shards to nodes with that percentage of disk used. This can also be entered as ratio value, like `0.85`. Finally, this can also be set to a byte value, like `400mb`. This setting does not affect the primary shards of newly created indexes, but will prevent their replicas from being allocated. Default is `85%`. +- `cluster.routing.allocation.rebalance.primary.buffer` (Dynamic, floating point): Defines the maximum allowed buffer of primary shards between nodes when `cluster.routing.allocation.rebalance.primary.enable` is enabled. Default is `0.1`. -- `cluster.routing.allocation.disk.watermark.high` (String): Controls the high watermark. OpenSearch will attempt to relocate shards away from a node whose disk usage is above the percentage defined. This can also be entered as a ratio value, like `0.85`. Finally, this can also be set to a byte value, like `400mb`. This setting affects the allocation of all shards. Default is `90%`. +- `cluster.routing.allocation.disk.threshold_enabled` (Dynamic, Boolean): When set to `false`, disables the disk allocation decider. This will also remove any existing `index.blocks.read_only_allow_delete index blocks` when disabled. Default is `true`. -- `cluster.routing.allocation.disk.watermark.flood_stage` (String): Controls the flood stage watermark. This is a last resort to prevent nodes from running out of disk space. OpenSearch enforces a read-only index block (`index.blocks.read_only_allow_delete`) on every index that has one or more shards allocated on the node and that has at least one disk exceeding the flood stage. The index block is released once the disk utilization falls below the high watermark. This can also be entered as a ratio value, like `0.85`. Finally, this can also be set to a byte value, like `400mb`. Default is `95%`. +- `cluster.routing.allocation.disk.watermark.low` (Dynamic, string): Controls the low watermark for disk usage. When set to a percentage, OpenSearch will not allocate shards to nodes with that percentage of disk usage. This can also be entered as a ratio value, like `0.85`. Finally, this can also be set to a byte value, like `400mb`. This setting does not affect the primary shards of newly created indexes but will prevent their replicas from being allocated. Default is `85%`. -- `cluster.info.update.interval` (Time unit): Sets how often OpenSearch should check disk usage for each node in the cluster. Default is `30s`. +- `cluster.routing.allocation.disk.watermark.high` (Dynamic, string): Controls the high watermark. OpenSearch will attempt to relocate shards away from a node whose disk usage is above the defined percentage. This can also be entered as a ratio value, like `0.85`. Finally, this can also be set to a byte value, like `400mb`. This setting affects the allocation of all shards. Default is `90%`. -- `cluster.routing.allocation.include.<attribute>` (Enum): Allocates shards to a node whose `attribute` has at least one of the included comma-separated values. +- `cluster.routing.allocation.disk.watermark.flood_stage` (Dynamic, string): Controls the flood stage watermark. This is a last resort to prevent nodes from running out of disk space. OpenSearch enforces a read-only index block (`index.blocks.read_only_allow_delete`) on every index that has one or more shards allocated on the node and at least one disk exceeding the flood stage. The index block is released once the disk utilization falls below the high watermark. This can also be entered as a ratio value, like `0.85`. Finally, this can also be set to a byte value, like `400mb`. Default is `95%`. -- `cluster.routing.allocation.require.<attribute>` (Enum): Only allocates shards to a node whose `attribute` has all of the included comma-separated values. +- `cluster.info.update.interval` (Dynamic, time unit): Sets how often OpenSearch should check disk usage for each node in the cluster. Default is `30s`. -- `cluster.routing.allocation.exclude.<attribute>` (Enum): Does not allocate shards to a node whose `attribute` has any of the included comma-separated values. The cluster allocation settings support the following built-in attributes. +- `cluster.blocks.create_index` (Dynamic, Boolean): Controls whether index creation is blocked at the cluster level. When set to `true`, prevents new indexes from being created. Default is `false`. + +- `cluster.blocks.create_index.auto_release` (Dynamic, Boolean): Controls whether automatic index creation blocks (triggered by high disk usage) are automatically removed when disk usage returns below threshold levels. Default is `true`. + +- `cluster.ignore_dot_indexes` (Dynamic, Boolean): When set to `true`, ignores dot-prefixed indexes (like `.opensearch-*`) in shard limit validation checks. Default is `false`. + +- `cluster.routing.allocation.awareness.balance` (Dynamic, Boolean): Enables awareness-based replica balancing across awareness attributes. Takes effect only when both `cluster.routing.allocation.awareness.attributes` and `cluster.routing.allocation.awareness.force.zone.values` are specified. Default is `false`. + +- `cluster.routing.allocation.primary_constraint.threshold` (Dynamic, long): The threshold for primary shard constraint checks in allocation decisions. Default is `10`. Minimum enforced is `0`. + +- `cluster.routing.allocation.remote_primary.ignore_throttle` (Dynamic, Boolean): Whether to ignore throttling limits for remote primary shard restoration operations. Default is `true`. + +- `cluster.routing.ignore_weighted_routing` (Dynamic, Boolean): When set to `true`, ignores weighted routing configurations and uses default routing behavior. Default is `false`. + +- `cluster.routing.weighted.default_weight` (Dynamic, double): The default weight assigned to nodes when weighted routing is enabled but no specific weight is configured. Default is `1.0`. Minimum enforced is `1.0`. + +- `cluster.routing.weighted.fail_open` (Dynamic, Boolean): When weighted routing is enabled, determines whether to fail open (allow requests to any node) if all weighted nodes are unavailable. Default is `true`. + +- `cluster.routing.weighted.strict` (Dynamic, Boolean): When enabled, enforces strict weighted routing where requests are only routed to nodes with appropriate weights. Default is `true`. + +- `cluster.routing.allocation.awareness.attributes` (Dynamic, list): See [Shard allocation awareness]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#shard-allocation-awareness). + +- `cluster.routing.allocation.include.<attribute>` (Dynamic, enum): Allocates shards to a node whose `attribute` contains at least one of the included comma-separated values. + +- `cluster.routing.allocation.require.<attribute>` (Dynamic, enum): Only allocates shards to a node whose `attribute` contains all of the included comma-separated values. + +- `cluster.routing.allocation.exclude.<attribute>` (Dynamic, enum): Does not allocate shards to a node whose `attribute` contains any of the included comma-separated values. The cluster allocation settings support the following built-in attributes. Valid values are: - `_name` – Match nodes by node name. @@ -87,25 +115,88 @@ OpenSearch supports the following cluster-level routing and shard allocation set - `_ip` – Match either `_host_ip` or `_publish_ip`. - `_host` – Match nodes by hostname. - `_id` – Match nodes by node ID. - - `_tier` – Match nodes by data tier role. + - `_tier` – Match nodes by data tier role. -- `cluster.routing.allocation.shard_movement_strategy` (Enum): Determines the order in which shards are relocated from outgoing to incoming nodes. +- `cluster.routing.allocation.awareness.force.<attribute>.values` (Dynamic, list): See [Forced awareness]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#forced-awareness). + +- `cluster.routing.allocation.shard_movement_strategy` (Dynamic, enum): Determines the order in which shards are relocated from outgoing to incoming nodes. This setting supports the following strategies: - `PRIMARY_FIRST` – Primary shards are relocated first, before replica shards. This prioritization may help prevent a cluster's health status from going red if the relocating nodes fail during the process. - `REPLICA_FIRST` – Replica shards are relocated first, before primary shards. This prioritization may help prevent a cluster's health status from going red when carrying out shard relocation in a mixed-version, segment-replication-enabled OpenSearch cluster. In this situation, primary shards relocated to OpenSearch nodes of a newer version could try to copy segment files to replica shards on an older version of OpenSearch, which would result in shard failure. Relocating replica shards first may help to avoid this in multi-version clusters. - `NO_PREFERENCE` – The default behavior in which the order of shard relocation has no importance. +- `cluster.routing.search_replica.strict` (Dynamic, Boolean): Controls how search requests are routed when search replica shards exist for an index, such as when `index.number_of_search_replicas` is greater than `0`. This setting applies only when search replicas are configured for an index. When set to `true`, all search requests for such indexes are routed only to search replica shards. If search replicas are unassigned, the requests fail. When set to `false`, if search replicas are unassigned, requests fall back to any available shard. Default is `true`. + +- `cluster.allocator.gateway.batch_size` (Dynamic, integer): Limits the number of shards sent to data nodes in a single batch to fetch any unassigned shard metadata. Default is `2000`. + +- `cluster.allocator.existing_shards_allocator.batch_enabled` (Static, Boolean): Enables batch allocation of unassigned shards that already exist on the disk, as opposed to allocating one shard at a time. This reduces memory and transport overhead by fetching any unassigned shard metadata in a batch call. Default is `false`. + +- `cluster.routing.allocation.shards_batch_gateway_allocator.primary_allocator_timeout` (Dynamic, time value): Sets the timeout for the primary shard batch allocator during reroute operations. When the timeout is reached, the reroute iteration is interrupted, allowing higher-priority tasks to execute and preventing the cluster from becoming unmanageable during large-scale shard allocations. This helps prevent API timeouts and ensures cluster responsiveness. Valid values are time values greater than or equal to `20s`, or `-1ms` to disable the timeout. Default is `20s`. + +- `cluster.routing.allocation.shards_batch_gateway_allocator.replica_allocator_timeout` (Dynamic, time value): Sets the timeout for the replica shard batch allocator during reroute operations. When the timeout is reached, the reroute iteration is interrupted, allowing higher-priority tasks to execute and preventing the cluster from becoming unmanageable during large-scale shard allocations. This helps prevent API timeouts and ensures cluster responsiveness. Valid values are time values greater than or equal to `20s`, or `-1ms` to disable the timeout. Default is `20s`. + +- `cluster.routing.allocation.total_shards_per_node` (Dynamic, integer): The maximum combined total number of primary and replica shards that can be allocated to a single node. Default is `-1` (unlimited). Helps distribute shards evenly across nodes by limiting the total number of shards per node. Use with caution because shards may remain unallocated if nodes reach their configured limits. + +- `cluster.routing.allocation.total_primary_shards_per_node` (Dynamic, integer): The maximum number of primary shards that can be allocated to a single node. This setting is applicable only for remote-backed clusters. Default is `-1`(unlimited). Helps distribute primary shards evenly across nodes by limiting the number of primary shards per node. Use with caution because primary shards may remain unallocated if nodes reach their configured limits. + +- `cluster.routing.allocation.disk.watermark.enable_for_single_data_node` (Static, Boolean): Enables disk watermark checks for clusters with only a single data node. When enabled, disk-based shard allocation decisions are enforced even in single-node clusters. Default is `false`. + +### Advanced cluster routing and allocation settings + +OpenSearch supports the following advanced cluster routing and allocation settings: + +- `cluster.routing.allocation.balanced_shards_allocator.allocator_timeout` (Dynamic, time unit): Controls the timeout for balanced shard allocator operations. When set to `-1`, the timeout is disabled. When set to a positive value, the allocator will timeout after the specified duration if allocation cannot be completed. Default is `-1` (no timeout). Minimum value is `20s` when timeout is enabled. + +- `cluster.routing.allocation.cluster_concurrent_recoveries` (Dynamic, integer): Controls the maximum number of concurrent recovery operations allowed at the cluster level. This setting limits the total number of recovery operations (relocation operations) happening simultaneously across the entire cluster to prevent resource exhaustion. Set to `-1` for unlimited concurrent recoveries. Default is `-1`. + +### Load-aware allocation settings + +OpenSearch supports the following load-aware allocation settings for distributing shards based on node resource utilization: + +- `cluster.routing.allocation.load_awareness.allow_unassigned_primaries` (Dynamic, Boolean): When load-aware allocation is enabled, this setting controls whether newly created primary shards can be assigned even if it would breach the skew factor. Setting to `true` allows new primaries to be assigned while preventing replica allocation from breaching the skew factor. Setting to `false` can result in primaries remaining unassigned and the cluster turning red. Default is `true`. + +- `cluster.routing.allocation.load_awareness.flat_skew` (Dynamic, integer): The flat skew factor used in load-aware allocation to determine acceptable imbalance between nodes. Higher values allow more imbalance but provide greater allocation flexibility. Default is `2`. Minimum is `2`. + +- `cluster.routing.allocation.load_awareness.provisioned_capacity` (Dynamic, integer): The provisioned capacity setting for load-aware allocation. This helps the allocator understand the intended capacity of nodes for better load distribution. Set to `-1` to disable. Default is `-1`. + +- `cluster.routing.allocation.load_awareness.skew_factor` (Dynamic, double): The skew factor threshold for load-aware allocation. This controls how much imbalance is tolerated between nodes before the allocator takes corrective action. Higher values allow more skew. Default is `50`. Set to `-1` to disable skew-based allocation. + +- `cluster.routing.allocation.move.primary_first` (Dynamic, Boolean): When rebalancing shards, this setting controls whether primary shards are moved before replica shards. Moving primaries first can help balance the load more effectively but may impact search performance during rebalancing. Default is `false`. + +- `cluster.routing.allocation.node_initial_replicas_recoveries` (Dynamic, integer): The maximum number of initial replica recoveries that can happen simultaneously on a single node during cluster startup or when a node joins. This is separate from the concurrent recoveries limit and helps control startup load. Default is `2`. + +## Cluster-level snapshot settings + +OpenSearch supports the following cluster-level snapshot settings: + +- `cluster.snapshot.info.max_concurrent_fetches` (Dynamic, integer): The maximum number of concurrent snapshot information fetch operations allowed. This setting helps control the load when retrieving snapshot metadata from the repository. Higher values can improve performance when managing many snapshots but may increase resource usage. Default is `5`. + +## Cluster-level composite index settings + +OpenSearch supports the following composite index settings: + +- `indices.composite_index.translog.max_flush_threshold_size` (Dynamic, byte size): The maximum translog size threshold for composite indexes before a flush is triggered. This setting helps control memory usage and ensures translog data is persisted to disk regularly for composite indexes. Default is `512mb`. Minimum value is `128mb`. + ## Cluster-level shard, block, and task settings OpenSearch supports the following cluster-level shard, block, and task settings: +- `action.search.shard_count.limit` (Integer): Limits the maximum number of shards to be hit during search. Requests that exceed this limit will be rejected. + - `cluster.blocks.read_only` (Boolean): Sets the entire cluster to read-only. Default is `false`. - `cluster.blocks.read_only_allow_delete` (Boolean): Similar to `cluster.blocks.read_only`, but allows you to delete indexes. +- `cluster.no_cluster_manager_block` (String): Configures the operations that are rejected when no cluster manager is active. Accepts one of the following three option: + - `all`: Blocks all read and write requests to the cluster. + - `write`: Blocks only write requests. Read requests can still be processed. + - `metadata_write`: Metadata-related writes, such as updates to mappings or routing tables, are blocked, but normal document indexing can still be performed. Read and write requests are processed using the cluster state last received by the node. Because the node may be cut off from the rest of the cluster, this can lead to serving outdated information or returning only part of the data. + - `cluster.max_shards_per_node` (Integer): Limits the total number of primary and replica shards for the cluster. The limit is calculated as follows: `cluster.max_shards_per_node` multiplied by the number of non-frozen data nodes. Shards for closed indexes do not count toward this limit. Default is `1000`. +- `cluster.max_remote_capable_shards_per_node` (Integer): Limits the total number of primary and replica shards for the cluster used by warm role nodes. The limit is calculated as `cluster.max_remote_capable_shards_per_node` multiplied by the number of warm data nodes. This setting is useful for controlling the total number of shards for searchable snapshots. Default is `1000`. + - `cluster.persistent_tasks.allocation.enable` (String): Enables or disables allocation for persistent tasks. Valid values are: @@ -116,6 +207,18 @@ OpenSearch supports the following cluster-level shard, block, and task settings: - `cluster.persistent_tasks.allocation.recheck_interval` (Time unit): The cluster manager automatically checks whether persistent tasks need to be assigned when the cluster state changes in a significant way. There are other factors, such as memory usage, that will affect whether persistent tasks are assigned to nodes but do not otherwise cause the cluster state to change. This setting defines how often assignment checks are performed in response to these factors. Default is `30 seconds`, with a minimum of `10 seconds` being required. +- `task_cancellation.duration_millis` (Dynamic, long): The duration threshold in milliseconds for tracking canceled tasks in the task cancellation monitoring system. Default is `10000` (10 seconds). + +- `task_cancellation.enabled` (Dynamic, Boolean): Enables or disables the task cancellation monitoring service. Default is `true`. + +- `task_resource_tracking.enabled` (Dynamic, Boolean): Controls whether task resource tracking is enabled to monitor CPU and memory usage of individual tasks. Default is `true`. + +## Cluster-level search settings + +OpenSearch supports the following cluster-level search settings: + +- `cluster.search.ignore_awareness_attributes` (Boolean): Controls whether awareness attributes are considered during shard query routing. If `true`, the cluster ignores awareness attributes and uses Adaptive Replica Selection (ARS) to choose the optimal shard copy, reducing query response latency. Set this to `false` for routing decisions to prioritize awareness attributes instead of performance-based selection. Default is `true` (`false` for Amazon OpenSearch Service). + ## Cluster-level slow log settings For more information, see [Search request slow logs]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/logs/#search-request-slow-logs). @@ -130,9 +233,9 @@ For more information, see [Search request slow logs]({{site.url}}{{site.baseurl} - `cluster.search.request.slowlog.level` (String): Sets the minimum slow log level to log: `WARN`, `INFO`, `DEBUG`, and `TRACE`. Default is `TRACE`. -## Cluster-level index settings +## Cluster settings for indexes -For information about index-level index settings, see [Cluster-level index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#cluster-level-index-settings). +For information about cluster settings that apply to all indexes, see [Cluster settings for indexes]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/). ## Cluster-level coordination settings @@ -141,3 +244,147 @@ OpenSearch supports the following cluster-level coordination settings. All setti - `cluster.fault_detection.leader_check.timeout` (Time unit): The amount of time a node waits for a response from the elected cluster manager during a leader check before deeming the check a failure. Valid values are from `1ms` to `60s`, inclusive. Default is `10s`. Changing this setting to a value other than the default can result in an unstable cluster. - `cluster.fault_detection.follower_check.timeout` (Time unit): The amount of time the elected cluster manager waits for a response during a follower check before deeming the check a failure. Valid values are from `1ms` to `60s`, inclusive. Default is `10s`. Changing this setting to a value other than the default can result in an unstable cluster. + +- `cluster.fault_detection.follower_check.interval` (Time unit): The amount of time that the elected cluster manager waits between sending follower checks to other nodes in the cluster. Valid values are `100ms` and higher. Default is `1000ms`. Changing this setting to a value other than the default can result in an unstable cluster. + +- `cluster.follower_lag.timeout` (Time unit): The amount of time that the elected cluster manager waits to receive acknowledgements for cluster state updates from lagging nodes. Default is `90s`. If a node does not successfully apply the cluster state update within this period of time, it is considered to have failed and is removed from the cluster. + +- `cluster.publish.timeout` (Time unit): The amount of time that the cluster manager waits for each cluster state update to be completely published to all nodes, unless `discovery.type` is set to `single-node`. Default is `30s`. + +## Cluster-level fault detection settings + +OpenSearch supports the following cluster-level fault detection settings that control how nodes detect and respond to failures: + +- `cluster.fault_detection.follower_check.retry_count` (Static, integer): Sets how many consecutive follower check failures must occur before the elected cluster manager considers a node to be faulty and removes it from the cluster. This setting controls fault detection sensitivity for follower nodes. Default is `3`. **Warning**: Changing this setting from the default may cause your cluster to become unstable. + +- `cluster.fault_detection.leader_check.interval` (Static, time unit): Sets how long each node waits between checks of the elected cluster manager. This controls the frequency of leader health checks performed by follower nodes. Default is `1s`. **Warning**: Changing this setting from the default may cause your cluster to become unstable. + +- `cluster.fault_detection.leader_check.retry_count` (Static, integer): Sets how many consecutive leader check failures must occur before a node considers the elected cluster manager to be faulty and attempts to find or elect a new cluster manager. This setting controls fault detection sensitivity for the cluster manager node. Default is `3`. **Warning**: Changing this setting from the default may cause your cluster to become unstable. + +- `cluster.indices.tombstones.size` (Static, integer): Sets the maximum number of index deletion tombstones to keep in the cluster state. Index tombstones prevent nodes that are not part of the cluster when a delete occurs from joining the cluster and reimporting the index as though the delete was never issued. To prevent the cluster state from growing too large, only the most recent deletions are kept. Default is `500`. You can increase this value if you expect nodes to be absent from the cluster and miss more than 500 index deletions, though this is rare. Tombstones use minimal space, but very large values (like 50,000) are not recommended. + +## Cluster-level CAT response limit settings + +OpenSearch supports the following cluster-level CAT API response limit settings, all of which are dynamic: + +- `cat.indices.response.limit.number_of_indices` (Integer): Sets a limit on the number of indexes returned by the [CAT Indices API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-indices/). The default value is `-1` (no limit). If the number of indexes in the response exceeds this limit, the API returns a `429` error. To avoid this, you can specify an index pattern filter in your query (for example, `_cat/indices/<index-pattern>`). + +- `cat.shards.response.limit.number_of_shards` (Integer): Sets a limit on the number of shards returned by the [CAT Shards API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-shards/). The default value is `-1` (no limit). If the number of shards in the response exceeds this limit, the API returns a `429` error. To avoid this, you can specify an index pattern filter in your query (for example, `_cat/shards/<index-pattern>`). + +- `cat.segments.response.limit.number_of_indices` (Integer): Sets a limit on the number of indexes returned by the [CAT Segments API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-segments/). The default value is `-1` (no limit). If the number of indexes in the response exceeds this limit, the API returns a `429` error. To avoid this, you can specify an index pattern filter in your query (for example, `_cat/segments/<index-pattern>`). + +## Cluster-level gateway and indexes settings + +OpenSearch supports the following gateway and indexes settings: + +- `gateway.slow_write_logging_threshold` (Dynamic, time unit): The threshold for logging slow write operations in gateway cluster state persistence. Default is `10s`. Minimum enforced is `0`. + +- `indices.id_field_data.enabled` (Dynamic, Boolean): Controls whether ID field data is enabled for indexes, allowing sorting and aggregating on the `_id` field. Default is `true`. + +- `indices.mapping.max_in_flight_updates` (Dynamic, integer): The maximum number of concurrent mapping update requests allowed. Default is `10`. Minimum enforced is `1`. Maximum allowed is `1000`. + +- `indices.recovery.internal_action_long_timeout` (Dynamic, time unit): The timeout for long-running internal recovery actions. Default is twice the value of `indices.recovery.internal_action_timeout`. Minimum enforced is `0`. + +- `indices.recovery.internal_remote_upload_timeout` (Dynamic, time unit): The timeout for internal remote upload operations during shard recovery. Default is `1h`. + +- `indices.replication.initial_retry_backoff_bound` (Dynamic, time unit): The maximum bound for the first retry backoff when replication operations fail. Default is `50ms`. Minimum enforced is `10ms`. + +- `indices.replication.retry_timeout` (Dynamic, time unit): The total timeout for retrying failed replication requests. Default is `60s`. + +## Cluster-level metadata settings + +OpenSearch supports the following cluster-level metadata settings: + +- `cluster.metadata.<key>` (Dynamic, varies): Adds cluster metadata in the `"cluster.metadata.key": "value"` format. This setting is useful for persisting arbitrary, infrequently changing information about the cluster, such as contact details or annotations, without creating a dedicated index. **Important**: User-defined cluster metadata is not intended to store sensitive or confidential information. The values are visible to anyone with access to the Get Cluster Settings API and are recorded in the logs. + +## Cluster-level remote cluster settings + +OpenSearch supports the following remote cluster settings: + +- `cluster.remote.initial_connect_timeout` (Dynamic, time unit): Sets the timeout period for establishing initial connections to remote clusters when the node starts. This prevents nodes from hanging indefinitely during startup if remote clusters are unavailable. Default is `30s`. + +- `cluster.remote.connections_per_cluster` (Static, integer): The maximum number of connections that will be established to a remote cluster. If there is only a single seed node, other nodes will be discovered up to this number. Default is `3`. Minimum is `1`. + +- `cluster.remote.<cluster_alias>.mode` (Dynamic, string): Specifies the connection mode for a specific remote cluster. Valid values are `sniff` (discovers and connects to multiple nodes in the remote cluster) and `proxy` (connects through a single proxy address). Default is `sniff`. + +- `node.remote_cluster_client` (Static, Boolean): Controls whether a node can act as a cross-cluster client and connect to remote clusters. Default is `true`. Set to `false` to prevent a node from connecting to remote clusters. Remote cluster requests must be sent to a node on which this setting is enabled. + +- `cluster.remote.<cluster_alias>.skip_unavailable` (Dynamic, Boolean): Controls whether cross-cluster operations should continue when this specific remote cluster is unavailable. When set to `true`, the cluster becomes optional and operations will skip it if unreachable. When set to `false`, operations fail if this cluster is unavailable. Default is `false`. + +- `cluster.remote.<cluster_alias>.transport.compress` (Dynamic, Boolean): Enables compression for transport communications with a specific remote cluster. When enabled, reduces network bandwidth usage but increases CPU overhead for compression operations. If unset, uses the global `transport.compress` setting as a fallback. Default is `false`. + +- `cluster.remote.<cluster_alias>.transport.ping_schedule` (Dynamic, time unit): Sets the interval for sending application-level ping messages to maintain connections with a specific remote cluster. Setting to `-1` disables pings for this cluster. If unset, uses the global `transport.ping_schedule` setting. Default is `-1` (disabled). + +- `cluster.remote.<cluster_alias>.seeds` (Dynamic, list): Applicable to `sniff` mode only. Specifies the list of seed nodes used to discover the remote cluster topology. These nodes are contacted initially to retrieve the cluster state and identify gateway nodes for ongoing connections. + +- `cluster.remote.<cluster_alias>.node_connections` (Dynamic, integer): Applicable to `sniff` mode only. Sets the number of gateway nodes to which to maintain active connections in the remote cluster. More connections provide better availability but consume more resources. Default is `3`. + +- `cluster.remote.<cluster_alias>.cluster_name` (Dynamic, string): Applicable only to `sniff` mode. Specifies the expected name of the remote cluster. When configured, the remote cluster name is validated when establishing the connection. This helps prevent accidental connections to an unintended cluster if seed nodes are misconfigured or outdated. + +- `cluster.remote.node.attr` (Static, string): Applicable to `sniff` mode only. Specifies a node attribute to filter nodes that are eligible as gateway nodes in remote clusters. When set, only remote cluster nodes with the specified attribute will be used for connections. For example, if remote cluster nodes have `node.attr.gateway: true` and this setting is set to `gateway`, only those nodes will be connected to for cross-cluster operations. + +- `cluster.remote.<cluster_alias>.proxy_address` (Dynamic, string): Applicable to `proxy` mode only. Specifies the proxy server address for connecting to the remote cluster. All remote connections are routed through this single proxy endpoint. + +- `cluster.remote.<cluster_alias>.proxy_socket_connections` (Dynamic, integer): Applicable to `proxy` mode only. Sets the number of socket connections to open to the proxy server for this remote cluster. More connections can improve throughput but consume more resources. Default is `18`. + +- `cluster.remote.<cluster_alias>.server_name` (Dynamic, string): Applicable to `proxy` mode only. Specifies the hostname sent in the TLS Server Name Indication (SNI) extension when TLS is enabled for the remote cluster connection. This must be a valid hostname according to TLS SNI specifications. + +## Cluster manager task throttling settings + +OpenSearch supports the following dynamic cluster manager task throttling settings that control the number of pending tasks for specific cluster manager operations: + +- `cluster_manager.throttling.thresholds.<task_name>.value` (Dynamic, integer): Sets the throttling limit for specific cluster manager task types. When this limit is reached, additional tasks of this type are queued rather than processed immediately. Setting to `-1` disables throttling for the specified task type. Default varies by task type. Available task names include: + - `create-index`: Controls index creation operations + - `delete-index`: Controls index deletion operations + - `put-mapping`: Controls mapping update operations + - `index-aliases`: Controls index alias operations + - `cluster-update-settings`: Controls cluster settings updates + - `put-pipeline`: Controls ingest pipeline operations + - `delete-pipeline`: Controls ingest pipeline deletion + - `put-search-pipeline`: Controls search pipeline operations + - `delete-search-pipeline`: Controls search pipeline deletion + - `put-script`: Controls stored script operations + - `delete-script`: Controls stored script deletion + - `create-snapshot`: Controls snapshot creation operations + - `delete-snapshot`: Controls snapshot deletion operations + - And other cluster manager task types + + +## Cluster-level remote store settings + +OpenSearch supports the following remote store settings: + +For practical examples and step-by-step configuration guides, see [Remote-backed storage]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/remote-store/). +{: .tip} + + +- `cluster.remote_store.index.restrict.async-durability` (Static, Boolean): **Restricted Access Setting.** When enabled (`true`), restricts the creation or modification of indexes where `index.translog.durability` is set to `async`. This setting prevents indexes from using `async` durability mode in remote store environments, enforcing stronger durability guarantees. When set to `false`, indexes can use any durability mode (`sync` or `async`) and can be switched between modes at any time. When set to `true`, any attempt to create or update an index with `index.translog.durability=async` will be rejected. This setting is specifically designed for remote store deployments where asynchronous durability might compromise data consistency. Default is `false`. + +- `cluster.remote_store.compatibility_mode` (Dynamic, string): Controls the compatibility mode for remote store operations during cluster migration. Valid values are: + - `strict`: Only nodes with identical remote store configuration can join the cluster + - `mixed`: Allows mixed clusters with both remote-store-enabled and regular nodes during migration + Default is `strict`. + +- `cluster.remote_store.state.enabled` (Static, Boolean): Enables remote cluster state functionality. When enabled, cluster state metadata is stored in a remote repository in addition to local storage, enabling features like seamless search replica recovery and improved cluster resilience. This setting must be configured during cluster initialization and requires proper remote repository configuration. Default is `false`. + +- `cluster.remote_store.publication.enabled` (Static, Boolean): Enables remote publication of cluster state updates. When enabled, cluster state changes are published to the remote store, allowing for distributed state management and improved cluster coordination. This setting requires `cluster.remote_store.state.enabled` to be `true`. Default is `false`. + +- `cluster.remote_store.index_metadata.path_type` (Static, string): Defines the path structure used for storing index metadata in the remote store. Valid values are: + - `FIXED`: Uses a fixed path structure for metadata storage + - `HASHED_PREFIX`: Uses a hashed prefix in the path structure for better distribution + - `HASHED_INFIX`: Uses a hashed infix in the path structure for load balancing + Default is `HASHED_PREFIX`. + +- `cluster.remote_store.index_metadata.path_hash_algo` (Static, string): Specifies the hash algorithm used for constructing prefixes or infixes in index metadata paths when `cluster.remote_store.index_metadata.path_type` is set to `HASHED_PREFIX` or `HASHED_INFIX`. Valid values are: + - `FNV_1A_BASE64`: Uses FNV-1a hash with Base64 encoding + - `FNV_1A_COMPOSITE_1`: Uses FNV-1a hash with composite encoding for better distribution + Default is `FNV_1A_BASE64`. + +- `cluster.filecache.remote_data_ratio` (Dynamic, double): Controls the ratio of remote data to local disk cache for file caching in remote store configurations. This setting determines how much remote data is cached locally to improve performance. Higher values cache more data locally but consume more disk space. Value should be between 0.0 and 1.0. Default is `0.8`. + +- `cluster.indices.replication.strategy` (Dynamic, string): Sets the replication strategy for indexes in the cluster. Valid values include: + - `DOCUMENT`: Traditional document-based replication + - `SEGMENT`: Segment-based replication for improved performance and efficiency + Default is `DOCUMENT`. + +- `cluster.index.restrict.replication.type` (Dynamic, Boolean): When enabled, restricts the creation of indexes with specific replication types to ensure consistency across the cluster. This setting helps enforce replication policies and prevents incompatible replication configurations. Default is `false`. diff --git a/_install-and-configure/configuring-opensearch/configuration-system.md b/_install-and-configure/configuring-opensearch/configuration-system.md index 97ab2ea9..26f88ca7 100644 --- a/_install-and-configure/configuring-opensearch/configuration-system.md +++ b/_install-and-configure/configuring-opensearch/configuration-system.md @@ -7,18 +7,54 @@ nav_order: 10 # Configuration and system settings -For an overview of creating an OpenSearch cluster and examples of configuration settings, see [Creating a cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/index/). To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +For an overview of creating an OpenSearch cluster and examples of configuration settings, see [Creating a cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/). To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). -OpenSearch supports the following system settings: +## Cluster and node identity settings -- `cluster.name` (Static, string): The cluster name. +These are the fundamental settings required to identify your cluster and nodes: -- `node.name` (Static, string): A descriptive name for the node. +- `cluster.name` (Static, string): The cluster name. Default is `opensearch`. -- `node.roles` (Static, list): Defines one or more roles for an OpenSearch node. Valid values are `cluster_manager`, `data`, `ingest`, `search`, `ml`, `remote_cluster_client`, and `coordinating_only`. +- `node.name` (Static, string): A descriptive name for the node. Required. -- `path.data` (Static, string): A path to the directory where your data is stored. Separate multiple locations with commas. +- `node.roles` (Static, list): Defines one or more roles for an OpenSearch node. Valid values are `cluster_manager`, `data`, `ingest`, `search`, `ml`, `remote_cluster_client`, and `warm`. A node with the `search` role cannot have any other role. To configure a dedicated coordinating-only node, set `node.roles` to an empty list (`[]`). For more information, see [Coordinating node]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#coordinating-node). Default is `cluster_manager,data,ingest,remote_cluster_client`. -- `path.logs` (Static, string): A path to log files. +- `node.id.seed` (Static, long): Provides a seed value for determining the persisted unique UUID of a node. When a node starts for the first time, this seed helps generate a unique node identifier. If the node already has a persisted UUID on disk from a previous startup, this seed is ignored and the existing UUID is reused. This setting is useful for ensuring consistent node identification in automated deployments. Default is `0`. Accepts any long value including negative numbers. -- `bootstrap.memory_lock` (Static, Boolean): Locks the memory at startup. We recommend setting the heap size to about half the memory available on the system and that the owner of the process is allowed to use this limit. OpenSearch doesn't perform well when the system is swapping the memory. +## Path settings + +Path settings define directory locations for OpenSearch installation and data storage: + +- `path.home` (Static, string): Specifies the home directory path for the OpenSearch installation. This is the root directory where OpenSearch is installed and contains the bin, config, lib, and other installation directories. This setting is typically set automatically during installation but can be explicitly configured if needed. No default value - must be specified during startup. + +- `path.data` (Static, string): A path to the directory where your data is stored. Separate multiple locations with commas. Default is `$OPENSEARCH_HOME/data`. + +- `path.logs` (Static, string): A path to log files. Default is `$OPENSEARCH_HOME/logs`. + +- `path.shared_data` (Static, string): Specifies the path to a shared data directory that can be accessed by multiple nodes. This setting is useful in multi-node deployments where certain data needs to be shared across nodes in the cluster. The specified directory must be accessible by all nodes that need to share data. No default value - only set when shared data functionality is required. + +## Memory and storage settings + +Settings that control how OpenSearch uses system memory and storage: + +- `bootstrap.memory_lock` (Static, Boolean): Locks the memory at startup. We recommend setting the heap size to about half the memory available on the system and that the owner of the process be allowed to use this limit. OpenSearch doesn't perform well when the system is swapping the memory. Default is `false`. + +- `node.store.allow_mmap` (Static, Boolean): Controls whether memory-mapped file access is allowed for index storage operations. When enabled, OpenSearch can use memory mapping (`mmapfs` and `hybridfs` store types) to improve I/O performance by mapping files directly into virtual memory. Disabling this setting forces the use of alternative storage implementations that don't require memory mapping, which may be necessary in environments with memory mapping restrictions or limited virtual address space. Default is `true`. + +- `node.local_storage` (Static, Boolean): Controls whether the node can store data locally on its file system. When enabled, the node can write index data, cluster state, and other persistent information to local disk. When disabled, the node operates as a stateless node that does not persist any data locally. This setting is useful for creating dedicated coordination-only nodes that don't store shard data. Default is `true`. + +## Bootstrap and system security settings + +Settings that control system-level security and bootstrap behavior: + +- `bootstrap.system_call_filter` (Static, Boolean): Controls whether OpenSearch asks the operating system to block the system calls that create a new process. Set it to `false` only on a platform where the filter cannot be installed. For the mechanism used on each platform and the conditions under which a failed installation stops the node, see [Blocking process creation at the operating system level]({{site.url}}{{site.baseurl}}/scripting/script-security/#blocking-process-creation-at-the-operating-system-level). Default is `true`. + +- `bootstrap.ctrlhandler` (Static, Boolean): Controls whether OpenSearch enables a control handler for graceful shutdown on Windows systems. When enabled, allows OpenSearch to respond to system shutdown signals and perform cleanup operations. This setting is primarily relevant for Windows deployments and helps ensure proper shutdown behavior. Default is `true`. + +## Process management settings + +Settings for external monitoring and process management tools: + +- `node.portsfile` (Static, Boolean): Controls whether OpenSearch writes the node's port information to a file on disk. When enabled, the node creates a file containing the ports it's listening on, which can be useful for external monitoring and automation tools. This file is typically written to the node's data directory and is removed when the node shuts down cleanly. Default is `false`. + +- `node.pidfile` (Static, string): Specifies the path where OpenSearch should write its process ID (PID) file. The PID file contains the process ID of the running OpenSearch node and is commonly used by system administrators and process management tools to track and manage the OpenSearch process. The file is created when the node starts and removed when it shuts down cleanly. The specified path should be writable by the OpenSearch process. No default value - PID file is not created unless this setting is specified. diff --git a/_install-and-configure/configuring-opensearch/discovery-gateway-settings.md b/_install-and-configure/configuring-opensearch/discovery-gateway-settings.md index e08e436f..c2c7cf28 100644 --- a/_install-and-configure/configuring-opensearch/discovery-gateway-settings.md +++ b/_install-and-configure/configuring-opensearch/discovery-gateway-settings.md @@ -9,28 +9,34 @@ nav_order: 30 The following are settings related to discovery and local gateway. -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). ## Discovery settings -The discovery process is used when a cluster is formed. It consists of discovering nodes and electing a cluster manager node. OpenSearch supports the following discovery settings: +The discovery process is used when a cluster is formed. It consists of discovering nodes and electing a cluster manager node. For comprehensive information about discovery and cluster formation settings, see [Discovery and cluster formation settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/discovery-cluster-formation/settings/). -- `discovery.seed_hosts` (Static, list): The list of hosts that perform discovery when a node is started. The default list of hosts is `["127.0.0.1", "[::1]"]`. +- `discovery.find_peers_interval_during_decommission` (Static, time unit): Sets the time interval between attempts to find all peers when a node is in decommissioned state. When a node is being decommissioned, it continues to discover other nodes at this interval to maintain cluster membership information during the decommission process. This helps ensure proper coordination during controlled node removal. Default is `120s` (2 minutes). Minimum is `1000ms`. -- `discovery.seed_providers` (Static, list): Specifies the types of seed hosts provider to use for obtaining seed node addresses in order to start the discovery process. +- `discovery.unconfigured_bootstrap_timeout` (Static, time unit): Sets the timeout period for unconfigured bootstrap process during cluster formation. This setting controls how long a node will wait during the bootstrap phase when the cluster is not properly configured (e.g., when `cluster.initial_cluster_manager_nodes` is not set). After this timeout, the node will proceed with bootstrap operations or fail appropriately. This setting helps prevent nodes from waiting indefinitely in unconfigured states. Default is `3s`. Minimum is `1ms`. -- `discovery.type` (Static, string): By default, OpenSearch forms a multi-node cluster. Set `discovery.type` to `single-node` to form a single-node cluster. - -- `cluster.initial_cluster_manager_nodes` (Static, list): A list of cluster-manager-eligible nodes used to bootstrap the cluster. ## Gateway settings -The local gateway stores cluster state and shard data that is used when a cluster is restarted. OpenSearch supports the following local gateway settings: +The local gateway stores on-disk cluster state and shard data that is used when a cluster is restarted. The following local gateway settings are supported: -- `gateway.recover_after_nodes` (Static, integer): After a full cluster restart, the number of nodes that must join the cluster before recovery can begin. +- `gateway.recover_after_data_nodes` (Static, integer): The minimum number of data nodes that must be running after a full cluster restart before recovery can begin. + - **Default**: `0` + - **Recommendation**: Set to a significant portion of the data nodes—approximately 50–70% of the total data nodes—to avoid premature recovery. -- `gateway.recover_after_data_nodes` (Static, integer): After a full cluster restart, the number of data nodes that must join the cluster before recovery can begin. +- `gateway.expected_data_nodes` (Static, integer): The expected number of data nodes in the cluster. When all are present, recovery of local shards can start immediately. + - **Default**: `0` + - **Recommendation**: Set this to the actual number of data nodes in your cluster so that recovery can start immediately once all data nodes are running. -- `gateway.expected_data_nodes` (Static, integer): The number of data nodes expected to exist in the cluster. After the expected number of nodes joins the cluster, recovery of local shards can begin. +- `gateway.recover_after_time` (Static, time unit): The maximum amount of time to wait until recovery if the expected data node count hasn't been reached. After this time, recovery proceeds. + - **Default**: `5m` if `expected_data_nodes` or `recover_after_data_nodes` is set. Otherwise disabled. + - **Recommendation**: Set slightly above your typical node join time; larger clusters often need longer to recover and are tuned based on observed startup behavior. + +- `gateway.write_dangling_indices_info` (Static, Boolean): Controls whether OpenSearch writes information about dangling indexes to disk during cluster state persistence. When enabled, the system maintains metadata about indexes that exist on disk but are not part of the current cluster state, which can help with recovery and troubleshooting scenarios. Default is `true`. + +- `gateway.auto_import_dangling_indices` (Static, Boolean): Controls whether OpenSearch automatically imports dangling indexes discovered during cluster startup. Dangling indexes are indexes that exist on disk but are not part of the current cluster state, typically left behind after improper cluster shutdowns or node removals. When enabled, these orphaned indexes are automatically imported back into the cluster state during startup. When disabled, dangling indexes remain on disk but are not automatically imported, requiring manual intervention through the Dangling Indices API. This setting helps recover potentially lost data but should be used carefully to avoid importing unwanted indexes. Default is `true`. -- `gateway.recover_after_time` (Static, time value): The amount of time to wait before starting recovery if the number of data nodes is less than the expected number of data nodes. diff --git a/_install-and-configure/configuring-opensearch/experimental.md b/_install-and-configure/configuring-opensearch/experimental.md index 1a2e0e57..d80afc63 100644 --- a/_install-and-configure/configuring-opensearch/experimental.md +++ b/_install-and-configure/configuring-opensearch/experimental.md @@ -2,7 +2,7 @@ layout: default title: Experimental feature flags parent: Configuring OpenSearch -nav_order: 120 +nav_order: 180 --- # Experimental feature flags @@ -20,10 +20,10 @@ opensearch.experimental.feature.<feature_name>.enabled: true ## Enable on Docker containers -If you’re running Docker, add the following line to `docker-compose.yml` under the `opensearch-node` > `environment` section: +If you're running Docker Compose, add the flag to the `OPENSEARCH_JAVA_OPTS` variable in the `environment` section of each OpenSearch service in `docker-compose.yml`. Keep any options that the variable already contains, such as heap size settings: -```bash -OPENSEARCH_JAVA_OPTS="-Dopensearch.experimental.feature.<feature_name>.enabled=true" +```yaml +- "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m -Dopensearch.experimental.feature.<feature_name>.enabled=true" ``` {% include copy.html %} diff --git a/_install-and-configure/configuring-opensearch/index-settings.md b/_install-and-configure/configuring-opensearch/index-settings.md index 8f37be48..f6aa2f7d 100644 --- a/_install-and-configure/configuring-opensearch/index-settings.md +++ b/_install-and-configure/configuring-opensearch/index-settings.md @@ -2,51 +2,23 @@ layout: default title: Index settings parent: Configuring OpenSearch -nav_order: 70 +nav_order: 170 redirect_from: - /im-plugin/index-settings/ --- # Index settings -Index settings can be of two types: [cluster-level settings](#cluster-level-index-settings) that affect all indexes in the cluster and [index-level settings](#index-level-index-settings) that affect individual indexes. +Index settings apply to individual indexes, and their names begin with `index.`. For cluster settings that apply to all indexes in the cluster, see [Cluster settings for indexes]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/). -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +You specify index settings when creating an index. Index settings can be static or dynamic. The following table describes when and how you can update each type of setting. -## Cluster-level index settings +| Setting type | When you can update it | How to update it | +|:---|:---|:---| +| [Static](#static-index-settings) | When the index is closed | Close the index, update the setting using the Update Index Settings API, and then reopen the index. For more information, see [Updating a static index setting](#updating-a-static-index-setting). | +| [Dynamic](#dynamic-index-settings) | At any time | Use the Update Index Settings API. For more information, see [Updating a dynamic index setting](#updating-a-dynamic-index-setting). | -OpenSearch supports the following cluster-level index settings. All settings in this list are dynamic: - -- `action.auto_create_index` (Boolean): Automatically creates an index if the index doesn't already exist. Also applies any index templates that are configured. Default is `true`. - -- `action.destructive_requires_name` (Boolean): When set to `true`, you must specify the index name to delete an index. You cannot delete all indexes or use wildcards. Default is `true`. - -- `cluster.default.index.refresh_interval` (Time unit): Sets the refresh interval when the `index.refresh_interval` setting is not provided. This setting can be useful when you want to set a default refresh interval across all indexes in a cluster and support the `searchIdle` setting. You cannot set the interval lower than the `cluster.minimum.index.refresh_interval` setting. - -- `cluster.minimum.index.refresh_interval` (Time unit): Sets the minimum refresh interval and applies it to all indexes in the cluster. The `cluster.default.index.refresh_interval` setting should be higher than this setting's value. If, during index creation, the `index.refresh_interval` setting is lower than the minimum set, index creation fails. - -- `cluster.indices.close.enable` (Boolean): Enables closing of open indexes in OpenSearch. Default is `true`. - -- `indices.recovery.max_bytes_per_sec` (String): Limits the total inbound and outbound recovery traffic for each node. This applies to peer recoveries and snapshot recoveries. Default is `40mb`. If you set the recovery traffic value to less than or equal to `0mb`, rate limiting will be disabled, which causes recovery data to be transferred at the highest possible rate. - -- `indices.recovery.max_concurrent_file_chunks` (Integer): The number of file chunks sent in parallel for each recovery operation. Default is `2`. - -- `indices.recovery.max_concurrent_operations` (Integer): The number of operations sent in parallel for each recovery. Default is `1`. - -- `indices.recovery.max_concurrent_remote_store_streams` (Integer): The number of streams to the remote repository that can be opened in parallel when recovering a remote store index. Default is `20`. - -- `indices.time_series_index.default_index_merge_policy` (String): This setting allows you to specify the default merge policy for time-series indexes, particularly for those with an `@timestamp` field, such as data streams. The two available options are `tiered` (default) and `log_byte_size`. Using `log_byte_size` for time-series indexes is recommended for enhancing the performance of range queries with the `@timestamp` field. To override the merge policy on a per-index basis, you can use the `index.merge.policy` index setting. - -- `indices.fielddata.cache.size` (String): The maximum size of the field data cache. May be specified as an absolute value (for example, `8GB`) or a percentage of the node heap (for example, `50%`). This value is static so you must specify it in the `opensearch.yml` file. If you don't specify this setting, the maximum size is unlimited. This value should be smaller than the `indices.breaker.fielddata.limit`. For more information, see [Field data circuit breaker]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/circuit-breaker/#field-data-circuit-breaker-settings). - -## Index-level index settings - -You can specify index settings at index creation. There are two types of index settings: - -- [Static index-level index settings](#static-index-level-index-settings) are settings that you cannot update while the index is open. To update a static setting, you must close the index, update the setting, and then reopen the index. -- [Dynamic index-level index settings](#dynamic-index-level-index-settings) are settings that you can update at any time. - -### Specifying a setting when creating an index +## Specifying a setting when creating an index When creating an index, you can specify its static or dynamic settings as follows: @@ -61,51 +33,11 @@ PUT /testindex ``` {% include copy-curl.html %} -### Static index-level index settings - -OpenSearch supports the following static index-level index settings: - -- `index.number_of_shards` (Integer): The number of primary shards in the index. Default is 1. - -- `index.number_of_routing_shards` (Integer): The number of routing shards used to split an index. - -- `index.shard.check_on_startup` (Boolean): Whether the index's shards should be checked for corruption. Available options are `false` (do not check for corruption), `checksum` (check for physical corruption), and `true` (check for both physical and logical corruption). Default is `false`. - -- `index.codec` (String): Determines how the index’s stored fields are compressed and stored on disk. This setting impacts the size of the index shards and the performance of the index operations. - - Valid values are: - - - `default` - - `best_compression` - - `zstd` (OpenSearch 2.9 and later) - - `zstd_no_dict`(OpenSearch 2.9 and later) - - For `zstd` and `zstd_no_dict`, you can specify the compression level in the `index.codec.compression_level` setting. For more information, see [Index codec settings]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/). Optional. Default is `default`. - -- `index.codec.compression_level` (Integer): The compression level setting provides a tradeoff between compression ratio and speed. A higher compression level results in a higher compression ratio (smaller storage size) with a tradeoff in speed (slower compression and decompression speeds lead to greater indexing and search latencies). Can only be specified if `index.codec` is set to `zstd` and `zstd_no_dict` compression levels in OpenSearch 2.9 and later. Valid values are integers in the [1, 6] range. For more information, see [Index codec settings]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/). Optional. Default is 3. - -- `index.routing_partition_size` (Integer): The number of shards a custom routing value can go to. Routing helps an imbalanced cluster by relocating values to a subset of shards rather than a single shard. To enable routing, set this value to greater than 1 but less than `index.number_of_shards`. Default is 1. - -- `index.soft_deletes.retention_lease.period` (Time unit): The maximum amount of time to retain a shard's history of operations. Default is `12h`. - -- `index.load_fixed_bitset_filters_eagerly` (Boolean): Whether OpenSearch should preload cached filters. Available options are `true` and `false`. Default is `true`. - -- `index.hidden` (Boolean): Whether the index should be hidden. Hidden indexes are not returned as part of queries that have wildcards. Available options are `true` and `false`. Default is `false`. - -- `index.merge.policy` (String): This setting controls the merge policy for the Lucene segments. The available options are `tiered` and `log_byte_size`. The default is `tiered`, but for time-series data, such as log events, we recommend that you use the `log_byte_size` merge policy, which can improve query performance when conducting range queries on the `@timestamp` field. We recommend that you not change the merge policy of an existing index. Instead, configure this setting when creating a new index. - -- `index.merge_on_flush.enabled` (Boolean): This setting controls Apache Lucene's merge-on-refresh feature that aims to reduce the number of segments by performing merges _on refresh_ (or in terms of OpenSearch, _on flush_). Default is `true`. - -- `index.merge_on_flush.max_full_flush_merge_wait_time` (Time unit): This setting sets the amount of time to wait for merges when `index.merge_on_flush.enabled` is enabled. Default is `10s`. - -- `index.merge_on_flush.policy` (default | merge-on-flush): This setting controls which merge policy should be used when `index.merge_on_flush.enabled` is enabled. Default is `default`. - - -### Updating a static index setting +## Updating a static index setting You can update a static index setting only on a closed index. The following example demonstrates updating the index codec setting. -First, close an index: +First, close an index: ```json POST /testindex/_close @@ -134,59 +66,7 @@ POST /testindex/_open For more information about updating settings, including supported query parameters, see [Update settings]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/). -### Dynamic index-level index settings - -OpenSearch supports the following dynamic index-level index settings: - -- `index.number_of_replicas` (Integer): The number of replica shards each primary shard should have. For example, if you have 4 primary shards and set `index.number_of_replicas` to 3, the index has 12 replica shards. Default is 1. - -- `index.auto_expand_replicas` (String): Whether the cluster should automatically add replica shards based on the number of data nodes. Specify a lower bound and upper limit (for example, 0--9) or `all` for the upper limit. For example, if you have 5 data nodes and set `index.auto_expand_replicas` to 0--3, then the cluster does not automatically add another replica shard. However, if you set this value to `0-all` and add 2 more nodes for a total of 7, the cluster will expand to now have 6 replica shards. Default is disabled. - -- `index.search.idle.after` (Time unit): The amount of time a shard should wait for a search or get request until it goes idle. Default is `30s`. - -- `index.refresh_interval` (Time unit): How often the index should refresh, which publishes its most recent changes and makes them available for searching. Can be set to `-1` to disable refreshing. Default is `1s`. - -- `index.max_result_window` (Integer): The maximum value of `from` + `size` for searches of the index. `from` is the starting index to search from, and `size` is the number of results to return. Default is 10000. - -- `index.max_inner_result_window` (Integer): The maximum value of `from` + `size` that specifies the number of returned nested search hits and most relevant document aggregated during the query. `from` is the starting index to search from, and `size` is the number of top hits to return. Default is 100. - -- `index.max_rescore_window` (Integer): The maximum value of `window_size` for rescore requests to the index. Rescore requests reorder the index's documents and return a new score, which can be more precise. Default is the same as `index.max_inner_result_window` or 10000 by default. - -- `index.max_docvalue_fields_search` (Integer): The maximum number of `docvalue_fields` allowed in a query. Default is 100. - -- `index.max_script_fields` (Integer): The maximum number of `script_fields` allowed in a query. Default is 32. - -- `index.max_ngram_diff` (Integer): The maximum difference between `min_gram` and `max_gram` values for the `NGramTokenizer` and `NGramTokenFilter`. Default is 1. - -- `index.max_shingle_diff` (Integer): The maximum difference between `max_shingle_size` and `min_shingle_size` to feed into the `shingle` token filter. Default is 3. - -- `index.max_refresh_listeners` (Integer): The maximum number of refresh listeners each shard is allowed to have. - -- `index.analyze.max_token_count` (Integer): The maximum number of tokens that can be returned from the `_analyze` API operation. Default is 10000. - -- `index.highlight.max_analyzed_offset` (Integer): The number of characters a highlight request can analyze. Default is 1000000. - -- `index.max_terms_count` (Integer): The maximum number of terms a terms query can accept. Default is 65536. - -- `index.max_regex_length` (Integer): The maximum character length of regex that can be in a regexp query. Default is 1000. - -- `index.query.default_field` (List): A field or list of fields that OpenSearch uses in queries in case a field isn't specified in the parameters. - -- `index.routing.allocation.enable` (String): Specifies options for the index’s shard allocation. Available options are `all` (allow allocation for all shards), `primaries` (allow allocation only for primary shards), `new_primaries` (allow allocation only for new primary shards), and `none` (do not allow allocation). Default is `all`. - -- `index.routing.rebalance.enable` (String): Enables shard rebalancing for the index. Available options are `all` (allow rebalancing for all shards), `primaries` (allow rebalancing only for primary shards), `replicas` (allow rebalancing only for replicas), and `none` (do not allow rebalancing). Default is `all`. - -- `index.gc_deletes` (Time unit): The amount of time to retain a deleted document's version number. Default is `60s`. - -- `index.default_pipeline` (String): The default ingest node pipeline for the index. If the default pipeline is set and the pipeline does not exist, then index requests fail. The pipeline name `_none` specifies that the index does not have an ingest pipeline. - -- `index.final_pipeline` (String): The final ingest node pipeline for the index. If the final pipeline is set and the pipeline does not exist, then index requests fail. The pipeline name `_none` specifies that the index does not have an ingest pipeline. - -- `index.optimize_doc_id_lookup.fuzzy_set.enabled` (Boolean): This setting controls whether `fuzzy_set` should be enabled in order to optimize document ID lookups in index or search calls by using an additional data structure, in this case, the Bloom filter data structure. Enabling this setting improves performance for upsert and search operations that rely on document ID by creating a new data structure (Bloom filter). The Bloom filter allows for the handling of negative cases (that is, IDs being absent in the existing index) through faster off-heap lookups. Default is `false`. This setting can only be used if the feature flag `opensearch.experimental.optimize_doc_id_lookup.fuzzy_set.enabled` is set to `true`. - -- `index.optimize_doc_id_lookup.fuzzy_set.false_positive_probability` (Double): Sets the false-positive probability for the underlying `fuzzy_set` (that is, the Bloom filter). A lower false-positive probability ensures higher throughput for `UPSERT` and `GET` operations. Allowed values range between `0.01` and `0.50`. Default is `0.20`. This setting can only be used if the feature flag `opensearch.experimental.optimize_doc_id_lookup.fuzzy_set.enabled` is set to `true`. - -### Updating a dynamic index setting +## Updating a dynamic index setting You can update a dynamic index setting at any time through the API. For example, to update the refresh interval, use the following request: @@ -201,3 +81,305 @@ PUT /testindex/_settings {% include copy-curl.html %} For more information about updating settings, including supported query parameters, see [Update settings]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/). + +## Static index settings + +Static index settings are settings that you can update only on a closed index. Some static index settings are _final_. You can specify a final setting only when creating an index and cannot update it afterward, even on a closed index. + +OpenSearch supports the following static index settings: + +- `index.number_of_shards` (Final, integer): The number of primary shards in the index. Default is 1. + +- `index.number_of_routing_shards` (Static, integer): The number of routing shards used to split an index. + +- `index.shard.check_on_startup` (Static, Boolean): Whether the index's shards should be checked for corruption. Available options are `false` (do not check for corruption), `checksum` (check for physical corruption), and `true` (check for both physical and logical corruption). Default is `false`. + +- `index.codec` (Static, string): Determines how the index’s stored fields are compressed and stored on disk. This setting impacts the size of the index shards and the performance of the index operations. + + Valid values are: + + - `default` + - `best_compression` + - `zstd` (OpenSearch 2.9 and later) + - `zstd_no_dict`(OpenSearch 2.9 and later) + - `qat_lz4` (OpenSearch 2.14 and later, on supported systems) + - `qat_deflate` (OpenSearch 2.14 and later, on supported systems) + - `qat_zstd` (OpenSearch 2.19.3 and later, on supported systems) + +For `zstd`, `zstd_no_dict`, `qat_lz4`, `qat_deflate`, and `qat_zstd`, you can specify the compression level in the `index.codec.compression_level` setting. For more information, see [Index codec settings]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/). Optional. Default is `default`. + +- `index.codec.compression_level` (Static, integer): The compression level setting provides a trade-off between compression ratio and speed. A higher compression level results in a higher compression ratio (smaller storage size), but slower compression and decompression speeds lead to higher indexing and search latencies. This setting can only be specified if `index.codec` is set to `zstd` or `zstd_no_dict` in OpenSearch 2.9 and later; `qat_lz4` or `qat_deflate` in OpenSearch 2.14 and later; or `qat_zstd` in OpenSearch 2.19.3 and later. Valid values are integers in the `[1, 6]` range. For more information, see [Index codec settings]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/). Optional. Default is `3`. + +- `index.routing_partition_size` (Static, integer): The number of shards a custom routing value can go to. Routing helps an imbalanced cluster by relocating values to a subset of shards rather than a single shard. To enable routing, set this value to greater than 1 but less than `index.number_of_shards`. Default is 1. + +<p id="index-sort-settings"></p> + +- `index.sort.field` (Final, string): Specifies the field used to sort documents at index time. The default sort order is `asc` (ascending). To change the order, set the `index.sort.order` parameter. + +- `index.sort.order` (Final, string): Specifies the document sort order at index time. Valid values are `asc` (ascending) and `desc` (descending). Default is `asc`. This setting requires `index.sort.field` to also be set. + +- `index.sort.mode` (Final, string): Controls how multi-valued fields are handled during sorting. Valid values are `min` (uses the lowest value) and `max` (uses the highest value). + +- `index.sort.missing` (Final, string): Determines how documents missing the sort field are handled. Valid values are `_last` (places documents without the field at the end) and `_first` (places documents without the field at the beginning). + +- `index.load_fixed_bitset_filters_eagerly` (Static, Boolean): Whether OpenSearch should preload cached filters. Available options are `true` and `false`. Default is `true`. + +- `index.queries.cache.enabled` (Static, Boolean): Enables or disables the query cache for the index. The query cache stores the results of frequently used filters on each data node. To configure the size of the query cache, use the node-level [`indices.queries.cache.size`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/) setting. Default is `true`. + +- `index.query.parse.allow_unmapped_fields` (Static, Boolean): Allows unmapped fields in query parsing. Default is `true`. + +- `index.query_string.lenient` (Static, Boolean): Enables lenient parsing for query strings. Default is `false`. + +- `index.store.type` (Static, string): The file system implementation that OpenSearch uses to store and read the index's shard data on disk. Valid values are: + + - `fs`: OpenSearch selects the implementation for the operating environment. It uses `hybridfs` on 64-bit systems when memory mapping is allowed and `niofs` otherwise. + - `hybridfs`: Reads most index files using memory mapping and reads the file types listed in the [`index.store.hybrid.nio.extensions`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/) setting using Java NIO. + - `mmapfs`: Reads all index files using memory mapping. Memory mapping uses virtual address space in proportion to the size of the files, so make sure that the operating system allows enough memory map areas. + - `niofs`: Reads all index files using Java NIO, without memory mapping. + + If memory mapping is disabled using the [`node.store.allow_mmap`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/configuration-system/) setting, OpenSearch rejects the `hybridfs` and `mmapfs` values. Default is `fs`. + +- `index.store.stats_refresh_interval` (Static, time unit): The refresh interval for index store statistics. Default is `10s`. + +- `index.check_pending_flush.enabled` (Static, Boolean): This setting controls the Apache Lucene `checkPendingFlushOnUpdate` index writer setting, which specifies whether an indexing thread should check for pending flushes on an update in order to flush indexing buffers to disk. Default is `true`. + +- `index.use_compound_file` (Static, Boolean): This setting controls the Apache Lucene `useCompoundFile` index writer settings, which specifies whether newly written segment files will be packed into a compound file. Default is `true`. + +- `index.append_only.enabled` (Final, Boolean): Set to `true` to prevent any updates to documents in the index. Default is `false`. + +- `index.derived_source.enabled` (Final, Boolean): Set to `true` to dynamically generate the source without explicitly storing the `_source` field, which can optimize storage. Default is `false`. For more information, see [Derived source]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/source/#derived-source). + +- `index.mapping.ignore_malformed` (Static, Boolean): Controls whether malformed fields are ignored during document parsing. When enabled, documents with malformed field values are indexed successfully, with the malformed fields either ignored or set to null depending on the field type. When disabled, documents with malformed fields are rejected. This setting provides a default behavior that can be overridden at the field level. Default is `false`. + +- `index.soft_deletes.enabled` (Final, Boolean): Enables soft deletes for the index. When enabled, deleted documents are marked as deleted rather than immediately removed, allowing for better recovery and replication performance. This setting is mandatory for OpenSearch 2.0+ indices and is enabled by default for legacy indices. Once set, this setting cannot be changed after index creation. Default is `true`. + +- `index.store.preload` (Static, list): Specifies which file extensions should be preloaded into the filesystem cache when the index is opened. This setting only works with the `mmap` directory implementation and provides best-effort caching. Preloading files can improve search performance by reducing disk I/O, but it consumes more memory. Common extensions include `nvd` (norms), `dvd` (doc values), and `tim` (terms index). Default is `[]` (empty list). + +- `index.replication.type` (Final, string): Defines the replication strategy used for the index. Valid values are: + - `DOCUMENT`: Traditional document-based replication where individual documents are replicated + - `SEGMENT`: Segment-based replication for improved performance and reduced network overhead + This setting must be configured during index creation and cannot be changed afterward. Default is `DOCUMENT`. + +<p id="merge-policy"></p> + +- `index.merge.policy` (Static, string): Selects the merge policy that controls how Lucene segments are merged. Valid values are `tiered`, `log_byte_size`, and `default`. The `default` value resolves to `tiered` for standard indexes. For time-series indexes, which OpenSearch identifies by the presence of a `@timestamp` field, `default` resolves to the policy named by the node-level `indices.time_series_index.default_index_merge_policy` setting. Default is `default`. For time-series data, such as log events, we recommend `log_byte_size`, which can improve query performance for range queries on the `@timestamp` field. To configure the selected policy, use the [merge settings](#merge-settings). + +## Dynamic index settings + +Dynamic index settings are settings that you can update at any time. + +OpenSearch supports the following dynamic index settings: + +- `index.codec.qatmode` (Dynamic, string): The hardware acceleration mode used for the `qat_lz4`, `qat_deflate`, and `qat_zstd` compression codecs. Valid values are `auto` and `hardware`. For more information, see [Index codec settings]({{site.url}}{{site.baseurl}}/im-plugin/index-codecs/). Optional. Default is `auto` (the recommended setting). + +- `index.hidden` (Dynamic, Boolean): Whether the index should be hidden. Hidden indexes are not returned as part of queries that have wildcards. Available options are `true` and `false`. Default is `false`. + +- `index.soft_deletes.retention_lease.period` (Dynamic, time unit): The maximum amount of time to retain a shard's history of operations. Default is `12h`. + +- `index.bulk.adaptive_shard_selection.enabled` (Dynamic, Boolean): Set to `true` to enable adaptive shard selection for bulk operations so that a single shard is chosen for append-only indexes. Default is `false`. For more information, see [Adaptive shard selection for bulk indexing]({{site.url}}{{site.baseurl}}/im-plugin/append-only-index/#adaptive-shard-selection-for-bulk-indexing). + +- `index.number_of_replicas` (Dynamic, integer): The number of replica shards each primary shard should have. For example, if you have 4 primary shards and set `index.number_of_replicas` to 3, the index has 12 replica shards. If not set, defaults to `cluster.default_number_of_replicas` (which is `1` by default). + +- `index.number_of_search_replicas` (Dynamic, integer): The number of search replica shards that each primary shard should have. For example, if you have 4 primary shards and set `index.number_of_search_replicas` to 3, the index has 12 search replica shards. Default is `0`. + +- `index.auto_expand_replicas` (Dynamic, string): Whether the cluster should automatically add replica shards based on the number of data nodes. Specify a lower bound and upper limit (for example, 0--9) or `all` for the upper limit. For example, if you have 5 data nodes and set `index.auto_expand_replicas` to 0--3, then the cluster does not automatically add another replica shard. However, if you set this value to `0-all` and add 2 more nodes for a total of 7, the cluster will expand to now have 6 replica shards. Default is disabled. + +- `index.auto_expand_search_replicas` (Dynamic, string): Controls whether the cluster automatically adjusts the number of search replica shards based on the number of available search nodes. Specify the value as a range with a lower and upper bound, for example, `0-3` or `0-all`. If you don't specify a value, this feature is disabled. + + For example, if you have 5 data nodes and set `index.auto_expand_search_replicas` to `0-3`, the index can have up to 3 search replicas and the cluster does not automatically add another search replica shard. However, if you set `index.auto_expand_search_replicas` to `0-all` and add 2 more nodes, for a total of 7, the cluster will expand to now have 7 search replica shards. This setting is disabled by default. + +- `index.blocks.write` (Dynamic, Boolean): Specifies whether the index is read-only. Setting to `true` blocks all write requests and makes the index read-only. Default is `false`. + +- `index.search.idle.after` (Dynamic, time unit): The amount of time a shard should wait for a search or get request until it goes idle. Default is `30s`. + +- `index.search.default_pipeline` (Dynamic, string): The name of the search pipeline that is used if no pipeline is explicitly set when searching an index. If a default pipeline is set and the pipeline doesn't exist, then the index requests fail. Use the pipeline name `_none` to specify no default search pipeline. For more information, see [Default search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/using-search-pipeline/#default-search-pipeline). + +- `index.refresh_interval` (Dynamic, time unit): How often the index should refresh, which publishes its most recent changes and makes them available for searching. Can be set to `-1` to disable refreshing. Default is `1s`. + + If you don't set this setting explicitly, shards that haven't received a search request for the period specified in `index.search.idle.after` stop refreshing in the background until the next search request arrives. This optimizes bulk indexing for indexes that aren't being searched. To refresh on a fixed schedule regardless of search traffic, set `index.refresh_interval` to `1s` explicitly. For more information, see [Refresh interval]({{site.url}}{{site.baseurl}}/api-reference/index-apis/refresh/#refresh-interval). + +- `index.max_result_window` (Dynamic, integer): The maximum value of `from` + `size` for searches of the index. `from` is the starting index to search from, and `size` is the number of results to return. Default is 10000. + +- `index.max_inner_result_window` (Dynamic, integer): The maximum value of `from` + `size` that specifies the number of returned nested search hits and most relevant document aggregated during the query. `from` is the starting index to search from, and `size` is the number of top hits to return. Default is 100. + +- `index.max_rescore_window` (Dynamic, integer): The maximum value of `window_size` for rescore requests to the index. Rescore requests reorder the index's documents and return a new score, which can be more precise. Default is the same as `index.max_inner_result_window` or 10000 by default. + +- `index.max_docvalue_fields_search` (Dynamic, integer): The maximum number of `docvalue_fields` allowed in a query. Default is 100. + +- `index.max_script_fields` (Dynamic, integer): The maximum number of `script_fields` allowed in a query. Default is 32. + +- `index.max_ngram_diff` (Dynamic, integer): The maximum difference between `min_gram` and `max_gram` values for the `NGramTokenizer` and `NGramTokenFilter`. Default is 1. + +- `index.max_shingle_diff` (Dynamic, integer): The maximum difference between `max_shingle_size` and `min_shingle_size` to feed into the `shingle` token filter. Default is 3. + +- `index.max_refresh_listeners` (Dynamic, integer): The maximum number of refresh listeners each shard is allowed to have. + +- `index.analyze.max_token_count` (Dynamic, integer): The maximum number of tokens that can be returned from the `_analyze` API operation. Default is 10000. + +- `index.highlight.max_analyzed_offset` (Dynamic, integer): The number of characters a highlight request can analyze. Default is 1000000. + +- `index.max_terms_count` (Dynamic, integer): The maximum number of terms a terms query can accept. Default is 65536. + +- `index.max_regex_length` (Dynamic, integer): The maximum character length of regex that can be in a regexp query. Default is 1000. + +- `index.query.default_field` (Dynamic, list): A field or list of fields that OpenSearch uses in queries in case a field isn't specified in the parameters. + +- `index.query.max_nested_depth` (Dynamic, integer): The maximum number of nesting levels for `nested` queries. Default is `20`. Minimum is `1` (single `nested` query). + +- `index.requests.cache.enable` (Dynamic, Boolean): Enables or disables the index request cache. Default is `true`. For more information, see [Index request cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/request-cache/). + +- `index.routing.allocation.enable` (Dynamic, string): Specifies options for the index’s shard allocation. Available options are `all` (allow allocation for all shards), `primaries` (allow allocation only for primary shards), `new_primaries` (allow allocation only for new primary shards), and `none` (do not allow allocation). Default is `all`. + +- `index.unassigned.node_left.delayed_timeout` (Dynamic, time unit): Sets the amount of time OpenSearch waits before allocating a replica shard that became unassigned because a node left the cluster. This setting overrides the cluster-level `cluster.routing.allocation.unassigned.node_left.delayed_timeout` setting. If neither setting is configured, the default is `1m`. Set to `0` to disable delayed allocation for the index. + +- `index.priority` (Dynamic, integer): The priority of the index when OpenSearch allocates unassigned shards, for example, after a cluster restart. OpenSearch allocates shards of system indexes first and then allocates shards of indexes with a higher `index.priority` before shards of indexes with a lower one. Indexes with the same priority are allocated in order of creation date, newest first, and then by index name. Must be `0` or greater. Default is `1`. + +- `index.routing.rebalance.enable` (Dynamic, string): Enables shard rebalancing for the index. Available options are `all` (allow rebalancing for all shards), `primaries` (allow rebalancing only for primary shards), `replicas` (allow rebalancing only for replicas), and `none` (do not allow rebalancing). Default is `all`. + +- `index.gc_deletes` (Dynamic, time unit): The amount of time to retain a deleted document's version number. Default is `60s`. + +- `index.default_pipeline` (Dynamic, string): The default ingest node pipeline for the index. If the default pipeline is set and the pipeline does not exist, then index requests fail. The pipeline name `_none` specifies that the index does not have an ingest pipeline. + +- `index.final_pipeline` (Dynamic, string): The final ingest node pipeline for the index. If the final pipeline is set and the pipeline does not exist, then index requests fail. The pipeline name `_none` specifies that the index does not have an ingest pipeline. + +- `index.optimize_doc_id_lookup.fuzzy_set.enabled` (Dynamic, Boolean): This setting controls whether `fuzzy_set` should be enabled in order to optimize document ID lookups in index or search calls by using an additional data structure, in this case, the Bloom filter data structure. Enabling this setting improves performance for upsert and search operations that rely on document IDs by creating a new data structure (Bloom filter). The Bloom filter allows for the handling of negative cases (that is, IDs being absent in the existing index) through faster off-heap lookups. Note that creating a Bloom filter requires additional heap usage during indexing time. Default is `false`. + +- `index.optimize_doc_id_lookup.fuzzy_set.false_positive_probability` (Dynamic, double): Sets the false-positive probability for the underlying `fuzzy_set` (that is, the Bloom filter). A lower false-positive probability ensures higher throughput for upsert and get operations but results in increased storage and memory use. Allowed values range between `0.01` and `0.50`. Default is `0.20`. + +- `index.routing.allocation.total_shards_per_node` (Dynamic, integer): The maximum combined total number of primary and replica shards from a single index that can be allocated to a single node. Default is `-1` (unlimited). Helps control per-index shard distribution across nodes by limiting the number of shards per node. Use with caution because shards from this index may remain unallocated if nodes reach their configured limits. + +- `index.routing.allocation.total_primary_shards_per_node` (Dynamic, integer): The maximum number of primary shards from a single index that can be allocated to a single node. This setting is applicable only for remote-backed clusters. Default is `-1` (unlimited). Helps control per-index primary shard distribution across nodes by limiting the number of primary shards per node. Use with caution because primary shards from this index may remain unallocated if nodes reach their configured limits. + +- `index.derived_source.translog.enabled` (Dynamic, Boolean): Controls how documents are read from the translog for an index with derived source enabled. Defaults to the `index.derived_source.enabled` value. For more information, see [Derived source]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/source/#derived-source). + +- `index.flush_after_merge` (Dynamic, byte unit): The size (in bytes) after which to flush after merge operations. Default is `512MB`. + +- `index.max_slices_per_pit` (Dynamic, integer): The maximum number of slices per point-in-time search. Default is `1024`. + +- `index.unreferenced_file_cleanup.enabled` (Dynamic, Boolean): Enables cleanup of index files that are not referenced. Default is `true`. + +- `index.warmer.enabled` (Dynamic, Boolean): Enables index warmer functionality. Default is `true`. + +- `index.allocation.max_retries` (Dynamic, integer): The maximum number of times shards can be retried for allocation before giving up. This setting prevents infinite allocation retry loops when shards cannot be allocated due to resource constraints or other issues. Default is `5`. Range is `0` to `Integer.MAX_VALUE`. + +- `index.max_adjacency_matrix_filters` (Dynamic, integer): The maximum number of adjacency matrix filters allowed in aggregations. Adjacency matrix aggregations analyze relationships between different filters. Higher values allow more complex relationship analysis but consume more memory. Default is `100`. Minimum is `2`. + +- `index.max_slices_per_scroll` (Dynamic, integer): The maximum number of slices allowed per scroll request for this index. Slicing allows scroll operations to be parallelized across multiple slices for better performance. Higher values enable more parallelization but consume more resources. Default is `1024`. Minimum is `1`. + +- `index.optimize_auto_generated_id` (Dynamic, Boolean): Enables optimization for documents with auto-generated IDs. When enabled, OpenSearch can optimize indexing performance for documents that use automatically generated document IDs rather than custom IDs. This optimization may not apply immediately and depends on the engine state. Default is `true`. + +- `index.translog.generation_threshold_size` (Dynamic, byte unit): The size threshold that triggers the creation of a new translog generation. When the current translog generation reaches this size, OpenSearch creates a new generation file. Larger values can improve indexing performance by reducing the frequency of generation rollovers but may increase recovery time. Default is `64MB`. Minimum is `64KB`. + +- `index.translog.durability` (Dynamic, string): Controls when the translog is fsynced to disk and committed. Valid values are `request` and `async`. When set to `request`, OpenSearch fsyncs and commits the translog on the primary and every allocated replica before it acknowledges an index, delete, update, or bulk request, so every acknowledged write survives a node crash. When set to `async`, OpenSearch fsyncs and commits in the background at the interval set by `index.translog.sync_interval`, which reduces indexing overhead but discards any acknowledged writes made since the last commit if a node fails. Values are case insensitive. Default is `request`. + +- `index.translog.sync_interval` (Dynamic, time unit): The frequency at which the translog is fsynced to disk and committed. More frequent syncing provides better durability guarantees but may impact indexing performance. Less frequent syncing improves performance but increases the risk of data loss during failures. Default is `5s`. Minimum is `100ms`. + +- `index.translog.flush_threshold_size` (Dynamic, byte unit): The maximum total size of translog operations that are not yet committed to Lucene. When the translog reaches this size, OpenSearch flushes the index, which creates a new Lucene commit point and starts a new translog generation. Smaller values shorten recovery times because fewer operations must be replayed, but they trigger flushes more frequently. Default is `512mb`. Minimum is `56b`. + +- `index.translog.retention.age` (Dynamic, time unit): The maximum age of translog files to retain for operations-based peer recovery. Translog files older than this setting are deleted during translog cleanup. This setting applies only to indexes that have soft deletes disabled. Because soft deletes are required for all indexes created in OpenSearch 2.0 and later, the setting has no effect on current indexes. Default is `-1` (retention disabled). + +- `index.translog.retention.size` (Dynamic, byte unit): The maximum total size of translog files to retain for operations-based peer recovery. When the total size exceeds this threshold, older files are deleted during cleanup. Like `index.translog.retention.age`, this setting applies only to indexes that have soft deletes disabled, so it has no effect on indexes created in OpenSearch 2.0 and later. Default is `-1` (retention disabled). + +- `index.soft_deletes.retention.operations` (Dynamic, long): The maximum number of soft-deleted operations to retain in the index. Soft deletes allow for efficient replication and point-in-time recovery by marking documents as deleted rather than immediately removed. This setting controls how many soft-deleted operations are preserved before they are eligible for cleanup. Default is `0` (unlimited retention). + +- `index.remote_store.translog.keep_extra_gen` (Dynamic, integer): The number of extra translog generations to keep in the remote store beyond the minimum required for recovery. Higher values provide more recovery options but consume more storage space. This setting helps balance between storage costs and recovery flexibility in remote store configurations. Default is `0`. + +- `index.remote_store.translog.buffer_interval` (Dynamic, time unit): The interval at which translog data is buffered before being uploaded to the remote store. More frequent uploads provide better durability but may impact performance. This setting works in conjunction with the cluster-level `cluster.remote_store.translog.buffer_interval` setting, with the index-level setting taking precedence. Default inherits from cluster setting. + +- `index.blocks.read_only` (Dynamic, Boolean): When set to `true`, makes the index read-only by blocking all write operations including indexing, updates, and deletes. Read operations like searches and gets continue to work normally. This setting is useful for temporarily preventing writes during maintenance or troubleshooting. Default is `false`. + +- `index.routing.allocation.require.temp` (Dynamic, string): Requires shards for this index to be allocated only to nodes with the specified temperature attribute. This setting is used for hot-warm architectures where different node types handle different data temperatures. The value should match a node attribute like `hot`, `warm`, or `cold`. No default value - when not set, shards can be allocated to any eligible node. + +<p id="periodic-flush-interval"> </p> + +- `index.periodic_flush_interval` (Dynamic, time unit): Triggers a flush periodically at the configured interval, storing all in-memory operations to segments on disk. OpenSearch automatically performs flush operations in the background based on conditions such as transaction log size. Default is `-1`, which disables periodic flush. For pull-based ingestion indexes, the default is `10m`. See [Pull-based ingestion]({{site.url}}{{site.baseurl}}/im-plugin/pull-based-ingestion/index/). You can configure this setting if your workload requires predictable, time-based flush intervals. + +### Merge settings + +Merge settings control how Lucene segments are merged. The `index.merge.policy` setting, which selects the merge policy, is static. All other merge settings are dynamic. For more information about selecting a merge policy, see [`index.merge.policy`](#merge-policy). + +#### Tiered merge policy settings + +When using the `tiered` merge policy (the default), the following settings control merge behavior: + +- `index.merge.policy.max_merge_at_once` (Dynamic, integer): Sets the maximum number of segments to be merged at a time during normal merging operations. Higher values can reduce the total number of merges but require more memory and I/O resources during each merge operation. Default is `30`. Minimum is `2`. + +- `index.merge.policy.segments_per_tier` (Dynamic, double): Controls the allowed number of segments per tier in the tiered merge policy. Smaller values result in more merging but fewer segments, which can improve search performance at the cost of increased indexing overhead. Default is `10.0`. Minimum is `2.0`. + +- `index.merge.policy.floor_segment` (Dynamic, byte unit): Sets the smallest segment size that the merge policy distinguishes. Segments smaller than this value are rounded up to it and treated as equally sized when the policy selects candidates for merging, so the smallest segments are grouped and merged early instead of accumulating as a long tail of tiny segments. Larger values merge small segments more aggressively, which lowers the total segment count but increases merge work. The value must be greater than `0`. Default is `16mb`. + +- `index.merge.policy.max_merged_segment` (Dynamic, byte unit): Sets the maximum size of a segment produced by a background merge. The merge policy stops merging a group of segments when the estimated result would exceed this size, so segments larger than this value are only produced by a force merge. Smaller values keep individual merges shorter but leave more segments in the index. Default is `5gb`. + +- `index.merge.policy.deletes_pct_allowed` (Dynamic, double): Sets the percentage of deleted documents that the index is allowed to accumulate before the merge policy begins merging segments specifically to reclaim that space. Lower values reclaim disk space sooner but increase merge work. Default is `20.0`. Valid values are from `5.0` to `50.0`. + +- `index.merge.policy.expunge_deletes_allowed` (Dynamic, double): Sets the percentage of deleted documents a segment must contain before a force merge with `only_expunge_deletes` set to `true` rewrites it. Default is `10.0`. Valid values are from `0.0` to `100.0`. For more information, see [Force Merge API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/force-merge/). + +- `index.merge.policy.reclaim_deletes_weight` (Dynamic, double): Deprecated and no longer applied. OpenSearch accepts and stores the value but does not pass it to the merge policy, so changing it has no effect. Use `index.merge.policy.deletes_pct_allowed` to control when deleted documents are reclaimed. Default is `2.0`. Minimum is `0.0`. + +#### Log byte size merge policy settings + +When using the `log_byte_size` merge policy, the following settings control merge behavior: + +- `index.merge.log_byte_size_policy.merge_factor` (Dynamic, integer): Controls how many segments are merged at once during normal merging operations. Higher values lead to fewer, larger segments, which can improve search performance but use more resources during merging. Default is `10`. Minimum is `2`. + +- `index.merge.log_byte_size_policy.min_merge` (Dynamic, byte unit): Sets the minimum size threshold for segment merging. Segments smaller than this size are more aggressively merged. Smaller values lead to fewer small segments but more merge operations. Default is `16mb`. + +- `index.merge.log_byte_size_policy.max_merge_segment` (Dynamic, byte unit): Controls the maximum size of segments created during normal merge operations. Larger segments improve query performance but require more memory and can increase merge times. Default is `5gb`. + +- `index.merge.log_byte_size_policy.max_merge_segment_forced_merge` (Dynamic, byte unit): Sets the maximum segment size when performing forced merge operations (such as during index optimization). This allows forced merges to create larger segments than normal merges. Default is unlimited. + +- `index.merge.log_byte_size_policy.max_merged_docs` (Dynamic, integer): Sets the maximum number of documents that a single segment can contain. The merge policy skips any merge that would produce a segment exceeding this count, which caps segment size by document count rather than by bytes. Default is `2147483647`, which places no practical limit on the number of documents per segment. + +- `index.merge.log_byte_size_policy.no_cfs_ratio` (Dynamic, double): Sets the largest share of the total index size that a segment can occupy and still be written in Lucene's compound file format, which packs a segment's files into a single file and reduces the number of open file handles. Segments larger than this share of the index are written as separate files. Set the value to `1.0` (or `true`) to use the compound format for all segments and `0.0` (or `false`) to disable it. Default is `0.1`. Valid values are from `0.0` to `1.0`. + +#### Merge scheduler settings + +The following settings control the merge scheduler, which determines how merge operations are executed: + +- `index.merge.scheduler.max_thread_count` (Dynamic, integer): Sets the maximum number of threads on a single shard that may be merging at once. This controls the concurrency of merge operations within each shard. Higher values can improve merge performance on systems with SSDs and multiple CPU cores, but may increase resource usage. If your index is on spinning platter drives, decrease this to 1. Default is `Math.max(1, Math.min(4, node.processors / 2))`, which works well for solid-state drives. Minimum is `1`. + +- `index.merge.scheduler.auto_throttle` (Dynamic, Boolean): Enables automatic throttling of merge operations to prevent them from overwhelming the system. When enabled, OpenSearch automatically adjusts merge I/O rates based on incoming indexing load. Default is `true`. + +- `index.merge_on_flush.enabled` (Dynamic, Boolean): This setting controls Apache Lucene's merge-on-refresh feature that aims to reduce the number of segments by performing merges _on refresh_ (or in terms of OpenSearch, _on flush_). Default is `true`. + +- `index.merge_on_flush.max_full_flush_merge_wait_time` (Dynamic, time unit): This setting sets the amount of time to wait for merges when `index.merge_on_flush.enabled` is enabled. Default is `10s`. + +- `index.merge_on_flush.policy` (Dynamic, string): This setting controls which merge policy should be used when `index.merge_on_flush.enabled` is enabled. Default is `default`. + +### Slow log settings + +OpenSearch supports the following dynamic slow log settings for monitoring search and indexing performance. + +#### Indexing slow log settings + +- `index.indexing.slowlog.threshold.index.warn` (Dynamic, time unit): Sets the time threshold for logging slow indexing operations at the WARN level. Indexing operations that take longer than this threshold are logged as warnings. Default is `-1` (disabled). + +- `index.indexing.slowlog.threshold.index.info` (Dynamic, time unit): Sets the time threshold for logging slow indexing operations at the INFO level. Indexing operations that take longer than this threshold are logged for informational purposes. Default is `-1` (disabled). + +- `index.indexing.slowlog.threshold.index.debug` (Dynamic, time unit): Sets the time threshold for logging slow indexing operations at the DEBUG level. This provides detailed debugging information for indexing performance analysis. Default is `-1` (disabled). + +- `index.indexing.slowlog.threshold.index.trace` (Dynamic, time unit): Sets the time threshold for logging slow indexing operations at the TRACE level. This provides the most detailed logging for troubleshooting indexing performance issues. Default is `-1` (disabled). + +#### Search slow log settings + +- `index.search.slowlog.threshold.query.warn` (Dynamic, time unit): Sets the time threshold for logging slow search query operations at the WARN level. Query operations that take longer than this threshold are logged as warnings. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.query.info` (Dynamic, time unit): Sets the time threshold for logging slow search query operations at the INFO level. Query operations that take longer than this threshold are logged for informational purposes. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.query.debug` (Dynamic, time unit): Sets the time threshold for logging slow search query operations at the DEBUG level. This provides detailed debugging information for query performance analysis. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.query.trace` (Dynamic, time unit): Sets the time threshold for logging slow search query operations at the TRACE level. This provides the most detailed logging for troubleshooting query performance issues. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.fetch.warn` (Dynamic, time unit): Sets the time threshold for logging slow search fetch operations at the WARN level. Fetch operations that take longer than this threshold are logged as warnings. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.fetch.info` (Dynamic, time unit): Sets the time threshold for logging slow search fetch operations at the INFO level. Fetch operations that take longer than this threshold are logged for informational purposes. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.fetch.debug` (Dynamic, time unit): Sets the time threshold for logging slow search fetch operations at the DEBUG level. This provides detailed debugging information for fetch performance analysis. Default is `-1` (disabled). + +- `index.search.slowlog.threshold.fetch.trace` (Dynamic, time unit): Sets the time threshold for logging slow search fetch operations at the TRACE level. This provides the most detailed logging for troubleshooting fetch performance issues. Default is `-1` (disabled). + +## Related documentation + +- [Create Index API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/create-index/) +- [Get Index Settings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-settings/) +- [Update Index Settings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/update-settings/) diff --git a/_install-and-configure/configuring-opensearch/index.md b/_install-and-configure/configuring-opensearch/index.md index ecbce131..8c303144 100755 --- a/_install-and-configure/configuring-opensearch/index.md +++ b/_install-and-configure/configuring-opensearch/index.md @@ -3,38 +3,175 @@ layout: default title: Configuring OpenSearch nav_order: 10 has_children: true +has_toc: false redirect_from: - - /install-and-configure/configuring-opensearch/ - /opensearch/configuration/ + - /install-and-configure/configuring-opensearch/ --- # Configuring OpenSearch -There are two types of OpenSearch settings: [dynamic](#dynamic-settings) and [static](#static-settings). +Each OpenSearch setting is either a cluster setting or an index setting. Cluster settings apply to the whole cluster or to individual nodes. Index settings apply to a single index, and their names begin with `index.`. The settings pages in this section list cluster settings grouped by area, such as networking, security, and thread pools. For information about index settings, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). -## Dynamic settings +Settings are also either [static](#static-settings) or [dynamic](#dynamic-settings). Whether a setting is static or dynamic determines whether you can change it while OpenSearch is running. To determine whether a setting is static or dynamic, use the [Describe Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/describe-cluster-settings/). -Dynamic index settings are settings that you can update at any time. You can configure dynamic OpenSearch settings through the Cluster Settings API. For details, see [Update cluster settings using the API](#updating-cluster-settings-using-the-api). +The following table lists the ways in which you can specify cluster settings. -Whenever possible, use the Cluster Settings API; `opensearch.yml` is local to each node, whereas the API applies the setting to all nodes in the cluster. -{: .tip} +| Method | Setting types | Applies to | Changes take effect | +|:---|:---|:---|:---| +| [Configuration file](#configuration-file) (`opensearch.yml`) | Static and dynamic | The node | When the node starts | +| [Startup options](#specifying-configuration-settings-at-startup) (command-line flags or environment variables) | Static and dynamic | The node | When the node starts | +| [Cluster Settings API](#updating-cluster-settings-using-the-api) | Dynamic only | The whole cluster | Immediately | + +If you specify a cluster setting using more than one method, OpenSearch determines the value to use based on [setting precedence](#setting-precedence). ## Static settings -Certain operations are static and require you to modify the `opensearch.yml` [configuration file](#configuration-file) and restart the cluster. In general, these settings relate to networking, cluster formation, and the local file system. To learn more, see [Cluster formation]({{site.url}}{{site.baseurl}}/opensearch/cluster/). +Static settings are settings that you cannot update while the cluster is running. To change a static setting, update it in `opensearch.yml` or using a startup flag on each node and then restart the node. In general, static settings relate to networking, cluster formation, and the local file system. For more information, see [Creating a cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/). -## Specifying settings as environment variables +## Dynamic settings -You can specify environment variables as arguments using `-E` when launching OpenSearch: +Dynamic settings are settings that you can update while the cluster is running. You can specify dynamic settings using any of the methods on this page, including the Cluster Settings API. For more information, see [Updating cluster settings using the API](#updating-cluster-settings-using-the-api). + +We recommend using the Cluster Settings API for cluster-wide dynamic settings. Settings updated using the API apply to all nodes, which keeps the configuration consistent across the cluster and makes configuration changes easier to track. +{: .tip} + +## Configuration file + +You can find `opensearch.yml` in `/usr/share/opensearch/config/opensearch.yml` (Docker) or `/etc/opensearch/opensearch.yml` (most Linux distributions) on each node. + +To change the configuration directory location, set the `OPENSEARCH_PATH_CONF` environment variable, for example, `OPENSEARCH_PATH_CONF=/etc/opensearch`. This variable is sourced from `/etc/default/opensearch` (Debian package) and `/etc/sysconfig/opensearch` (RPM package). + +If you set a custom `OPENSEARCH_PATH_CONF` variable, other default environment variables are not loaded. + +Settings in `opensearch.yml` are not marked as persistent or transient. The following example uses the flat form: + +```yml +cluster.name: my-application +action.auto_create_index: true +compatibility.override_main_response_version: true +``` + +The demo configuration includes several [settings for the Security plugin]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/security-settings/) that you should modify before using OpenSearch for a production workload. To learn more, see [Security]({{site.url}}{{site.baseurl}}/security/). + +### (Optional) CORS header configuration + +If you are working on a client application running against an OpenSearch cluster on a different domain, you can configure headers in `opensearch.yml` to allow for developing a local application on the same machine. Use [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) so that your application can make calls to the OpenSearch API running locally. Add the following lines to `opensearch.yml`: + +```yml +http.host: 0.0.0.0 +http.port: 9200 +http.cors.allow-origin: "http://localhost" +http.cors.enabled: true +http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization +http.cors.allow-credentials: true +``` +{% include copy.html %} + +## Specifying configuration settings at startup + +When you start OpenSearch, you can specify settings using command-line flags or environment variables. These settings apply only to the node that you start. + +### Command-line flags + +To pass a setting directly to OpenSearch at startup, use the `-E` flag: ```bash ./opensearch -Ecluster.name=opensearch-cluster -Enode.name=opensearch-node1 -Ehttp.host=0.0.0.0 -Ediscovery.type=single-node ``` {% include copy.html %} +### Environment variables + +OpenSearch reads environment variables that configure the startup process, such as `OPENSEARCH_JAVA_OPTS` for JVM options and `OPENSEARCH_PATH_CONF` for the configuration directory location. + +To specify OpenSearch settings using environment variables, define a custom environment variable and reference it in `opensearch.yml` using the `${ENV_VAR}` syntax: + +```yml +node.name: ${NODE_NAME} +cluster.name: ${CLUSTER_NAME} +``` +{% include copy.html %} + +You can set environment variables in the shell, in a `systemd` service file, or in a Docker container. + +#### Shell + +To set environment variables in a shell, export them before starting OpenSearch. Run the following commands in the same shell session. + +To set the JVM heap size, export the `OPENSEARCH_JAVA_OPTS` variable: + +```bash +export OPENSEARCH_JAVA_OPTS="-Xms2g -Xmx2g" +``` +{% include copy.html %} + +To set the configuration directory location, export the `OPENSEARCH_PATH_CONF` variable: + +```bash +export OPENSEARCH_PATH_CONF="/etc/opensearch" +``` +{% include copy.html %} + +Then start OpenSearch: + +```bash +./opensearch +``` +{% include copy.html %} + +Do not export OpenSearch settings directly, for example, `export discovery.type=single-node`. Setting names contain dots, which most shells do not accept in variable names. To pass a setting directly at startup, use the `-E` flag. For more information, see [Command-line flags](#command-line-flags). + +<!-- vale off --> +#### systemd service file +<!-- vale on --> + +When running OpenSearch as a service managed by `systemd`, you can specify environment variables in a service override file. The following example `/etc/systemd/system/opensearch.service.d/override.conf` file sets two environment variables: + +```ini +[Service] +Environment="OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g" +Environment="OPENSEARCH_PATH_CONF=/etc/opensearch" +``` +{% include copy.html %} + +After creating or modifying the file, reload the `systemd` configuration: + +```bash +sudo systemctl daemon-reload +``` +{% include copy.html %} + +Then restart the OpenSearch service: + +```bash +sudo systemctl restart opensearch +``` +{% include copy.html %} + +#### Docker + +When running OpenSearch in Docker, you can specify environment variables using the `-e` option of the `docker run` command, as shown in the following example: + +```bash +docker run -e "OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g" -e "OPENSEARCH_PATH_CONF=/usr/share/opensearch/config" opensearchproject/opensearch:latest +``` +{% include copy.html %} + +Docker accepts environment variable names that contain dots, so you can pass OpenSearch settings directly using the `-e` option. The OpenSearch Docker image converts each environment variable whose name has the form of a setting into an `-E` flag. A name has the form of a setting if it begins with at least two dot-separated parts containing lowercase letters, digits, or underscores, for example, `discovery.type`. The `processors` setting is also converted. The following command passes two settings as environment variables: + +```bash +docker run -e "discovery.type=single-node" -e "cluster.name=my-cluster" opensearchproject/opensearch:latest +``` +{% include copy.html %} + +The image skips environment variables that have an empty value, so you cannot use an empty variable to clear a value set in `opensearch.yml`. To set a list setting to an empty list, use `[]`, for example, `-e "node.roles=[]"`. + ## Updating cluster settings using the API -The first step in changing a setting is to view the current settings by sending the following request: +Using the [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/), you can update dynamic settings for the whole cluster while it is running. You can update a setting as either _persistent_ or _transient_. Persistent settings are written to the cluster state and persist after a cluster restart. After a restart, OpenSearch clears transient settings. Transient settings take precedence over persistent settings. For more information, see [Setting precedence](#setting-precedence). + +Before changing a setting, view the current settings by sending the following request: ```json GET _cluster/settings?include_defaults=true @@ -48,16 +185,7 @@ GET _cluster/settings ``` {% include copy-curl.html %} -Three categories of setting exist in the cluster settings API: persistent, transient, and default. Persistent settings, well, persist after a cluster restart. After a restart, OpenSearch clears transient settings. - -If you specify the same setting in multiple places, OpenSearch uses the following precedence: - -1. Transient settings -2. Persistent settings -3. Settings from `opensearch.yml` -4. Default settings - -To change a setting, use the [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/) and specify the new value as either persistent or transient. This example shows the flat settings form: +To change a setting, specify the new value as either persistent or transient. The following example shows the flat settings form: ```json PUT _cluster/settings @@ -83,34 +211,103 @@ PUT _cluster/settings ``` {% include copy-curl.html %} ---- +## Setting precedence -## Configuration file +If you specify a setting in more than one place, OpenSearch uses the value from the source that appears first in the following list: -You can find `opensearch.yml` in `/usr/share/opensearch/config/opensearch.yml` (Docker) or `/etc/opensearch/opensearch.yml` (most Linux distributions) on each node. +1. Transient cluster settings, specified using the Cluster Settings API +2. Persistent cluster settings, specified using the Cluster Settings API +3. Settings passed using the `-E` flag at startup +4. Values in `opensearch.yml`, including values supplied by `${ENV_VAR}` references +5. Default setting values -You can edit the `OPENSEARCH_PATH_CONF=/etc/opensearch` to change the config directory location. This variable is sourced from `/etc/default/opensearch`(Debian package) and `/etc/sysconfig/opensearch`(RPM package). +OpenSearch reads `opensearch.yml`, applies the `-E` flags, and then resolves any `${ENV_VAR}` references. Thus, an `-E` flag overrides the value in `opensearch.yml`, including a value supplied by an environment variable. -If you set your customized `OPENSEARCH_PATH_CONF` variable, be aware that other default environment variables will not be loaded. +Transient and persistent cluster settings apply only to dynamic settings. For static settings, precedence starts with the `-E` flag. -You don't mark settings in `opensearch.yml` as persistent or transient, and settings use the flat form: +When you send a `GET _cluster/settings?include_defaults=true` request, the `defaults` object in the response contains values specified in `opensearch.yml` and using the `-E` flag in addition to built-in default values. The response does not indicate the source of each value. -```yml -cluster.name: my-application -action.auto_create_index: true -compatibility.override_main_response_version: true +## Resetting settings + +To reset a setting that you updated using the Cluster Settings API, assign it a `null` value. OpenSearch then applies the value from the next available source in the [precedence order](#setting-precedence). For example, when you reset a transient setting, OpenSearch applies the persistent value if one exists. The following request resets a transient setting: + +```json +PUT _cluster/settings +{ + "transient": { + "action.auto_create_index": null + } +} ``` +{% include copy-curl.html %} -The demo configuration includes a number of [settings for the Security plugin]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/security-settings/) that you should modify before using OpenSearch for a production workload. To learn more, see [Security]({{site.url}}{{site.baseurl}}/security/). +You can also use wildcards to reset multiple related settings at once: -### (Optional) CORS header configuration +```json +PUT _cluster/settings +{ + "persistent": { + "indices.recovery.*": null + } +} +``` +{% include copy-curl.html %} -If you are working on a client application running against an OpenSearch cluster on a different domain, you can configure headers in `opensearch.yml` to allow for developing a local application on the same machine. Use [Cross Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) so that your application can make calls to the OpenSearch API running locally. Add the following lines in your `custom-opensearch.yml` file (note that the "-" must be the first character in each line). -```yml -- http.host:0.0.0.0 -- http.port:9200 -- http.cors.allow-origin:"http://localhost" -- http.cors.enabled:true -- http.cors.allow-headers:X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization -- http.cors.allow-credentials:true -``` \ No newline at end of file +### Restoring the default value + +A reset setting returns to its default value only if no other source specifies it. To restore the default value, remove the setting from every source: + +1. Reset both the transient and persistent values using the Cluster Settings API: + + ```json + PUT _cluster/settings + { + "transient": { + "action.auto_create_index": null + }, + "persistent": { + "action.auto_create_index": null + } + } + ``` + {% include copy-curl.html %} + +1. On each node, remove the setting from `opensearch.yml` and from any `-E` flags that specify it, including Docker environment variables that OpenSearch converts to `-E` flags. If `opensearch.yml` references an environment variable for the setting, remove the reference. +1. Restart each node that you changed in the previous step. + +If the setting is not specified in `opensearch.yml` or at startup, the first step is sufficient and no restart is required. + +## Settings reference + +The following pages list cluster settings grouped by area: + +- [Configuration and system settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/configuration-system/) +- [Network settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/network-settings/) +- [Discovery and gateway settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/discovery-gateway-settings/) +- [Security settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/security-settings/) +- [Cluster management settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/) +- [Cluster settings for indexes]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/) +- [Cache settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cache-settings/) +- [Search settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/search-settings/) +- [Monitoring settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/monitoring-settings/) +- [Availability and recovery settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/availability-recovery/) +- [Thread pool settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/thread-pool-settings/) +- [Circuit breaker settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/circuit-breaker/) +- [Admission control settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/admission-control-settings/) +- [Plugin settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/plugin-settings/) +- [Ingest settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/ingest-settings/) +- [Script and resource settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/script-and-resource-settings/) + +The following page lists settings that apply to individual indexes: + +- [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) + +The following pages describe other configuration options: + +- [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/) +- [Logs]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/logs/) + +## Related documentation + +- [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/) +- [Describe Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/describe-cluster-settings/) diff --git a/_install-and-configure/configuring-opensearch/ingest-settings.md b/_install-and-configure/configuring-opensearch/ingest-settings.md new file mode 100644 index 00000000..bfd2324e --- /dev/null +++ b/_install-and-configure/configuring-opensearch/ingest-settings.md @@ -0,0 +1,40 @@ +--- +layout: default +title: Ingest settings +parent: Configuring OpenSearch +nav_order: 150 +--- + +# Ingest settings + +OpenSearch provides ingest settings that control which ingest processors are allowed for data processing pipelines. These settings help maintain security and control over data transformation operations by restricting which processors can be used in ingest pipelines. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## User agent processor settings + +User agent processor settings control which user agent parsing processors are allowed in ingest pipelines. + +OpenSearch supports the following static User agent processor settings: + +- `ingest.useragent.processors.allowed` (Static, list): Specifies which User agent processors are allowed to be used in ingest pipelines. When this list is empty (default), no restriction is applied and all available User agent processors can be used. When configured with specific processor names, only those processors will be permitted in pipelines. This setting helps control which user agent parsing processors can be used for security and data governance purposes. Default is `[]` (empty list - no restrictions). + +## Common processor settings + +Common processor settings control which standard ingest processors are allowed in ingest pipelines. + +OpenSearch supports the following static common processor settings: + +- `ingest.common.processors.allowed` (Static, list): Specifies which common ingest processors are allowed to be used in ingest pipelines. When this list is empty (default), no restriction is applied and all available common processors (such as `set`, `remove`, `rename`, and `convert`) can be used. When configured with specific processor names, only those processors will be permitted in pipelines. This setting provides fine-grained control over data transformation capabilities for security and compliance requirements. Default is `[]` (empty list - no restrictions). + +## Caching and performance settings + +Caching and performance settings control cache sizes and execution limits for various ingest processors. + +OpenSearch supports the following static caching and performance settings: + +- `ingest.user_agent.cache_size` (Static, long): Sets the cache size for User agent string parsing results. This cache stores parsed user agent information to improve performance when processing documents with repeated user agent strings. Higher values reduce parsing overhead for common user agents but use more memory. The cache stores mappings between user agent strings and their parsed components (browser, operating system, and device information). Default is `1000`. Minimum is `0`. + +- `ingest.grok.watchdog.interval` (Static, time unit): Sets the interval at which the Grok processor watchdog checks for long-running pattern matching operations. The watchdog helps prevent Grok processors from consuming excessive CPU time with complex or inefficient patterns. More frequent checks provide better protection against runaway operations but add slight overhead. Default is `1s`. + +- `ingest.grok.watchdog.max_execution_time` (Static, time unit): Sets the maximum execution time allowed for Grok pattern matching operations before the watchdog interrupts them. This prevents poorly designed or malicious Grok patterns from causing excessive CPU usage or blocking ingest processing. Operations exceeding this limit are terminated to maintain cluster stability. Default is `1s`. diff --git a/_install-and-configure/configuring-opensearch/logs.md b/_install-and-configure/configuring-opensearch/logs.md index e601a1ee..c50b0755 100644 --- a/_install-and-configure/configuring-opensearch/logs.md +++ b/_install-and-configure/configuring-opensearch/logs.md @@ -2,7 +2,7 @@ layout: default title: Logs parent: Configuring OpenSearch -nav_order: 120 +nav_order: 190 redirect_from: - /opensearch/logs/ - /monitoring-your-cluster/logs/ @@ -32,18 +32,19 @@ Rather than changing the default log level (`logger.level`), you change the log PUT /_cluster/settings { "persistent" : { - "logger.org.opensearch.index.reindex" : "DEBUG" + "logger.org.opensearch.index.reindex" : "DEBUG", + "logger.org.opensearch.indices.recovery": "TRACE" } } ``` {% include copy-curl.html %} -The easiest way to identify modules is not from the logs, which abbreviate the path (for example, `o.o.i.r`), but from the [OpenSearch source code](https://github.com/opensearch-project/opensearch/tree/master/server/src/main/java/org/opensearch). +Common categories can be found in [Common core logging categories](#common-core-logging-categories) and [Plugin logger categories](#plugin-logger-categories); however, the easiest way to identify modules is not in the logs, which abbreviate the path (for example, `o.o.i.r`), but in the [OpenSearch source code](https://github.com/opensearch-project/opensearch/tree/master/server/src/main/java/org/opensearch). {: .tip } After this sample change, OpenSearch emits much more detailed logs during reindex operations: -```plaintext +``` [2019-10-18T16:52:51,184][DEBUG][o.o.i.r.TransportReindexAction] [node1] [1626]: starting [2019-10-18T16:52:51,186][DEBUG][o.o.i.r.TransportReindexAction] [node1] executing initial scroll against [some-index] [2019-10-18T16:52:51,291][DEBUG][o.o.i.r.TransportReindexAction] [node1] scroll returned [3] documents with a scroll id of [DXF1Z==] @@ -93,8 +94,71 @@ There are other ways to change log levels: - `${sys:opensearch.logs.base_path}` is the directory for logs (for example, `/var/log/opensearch/`). - `${sys:opensearch.logs.cluster_name}` is the name of the cluster. + - `${sys:opensearch.logs.node_name}` is the name of the node. - `[%node_name]` is the name of the node. +### Common core logging categories + +The following table lists the common core logging categories. + +| Logger key prefix | Description | +| :--------- | :------- +| `org.opensearch.action` | Transport actions, such as `index`, `bulk`, `get`, or `cluster` actions. Useful when tracing request execution across nodes. | +| `org.opensearch.cluster` | Cluster state publication, routing, and metadata updates. Turn on for cluster formation, routing, and allocation issues. | +| `org.opensearch.discovery` | Node discovery and cluster coordination. Helpful during cluster formation or network partition tests. Sub-packages include cloud discovery. | +| `org.opensearch.gateway` | Gateway, ClusterState, Recoveries and Allocations. Useful for node restarts, shard allocations and shard recovery from on-disk and remote storage. | +| `org.opensearch.http` | Low-level HTTP layer request handling. Use for issues with HTTP communication and settings. | +| `org.opensearch.index` | Per-index internals, such as engine, translog, or shard operations. Use for shard/engine behavior debugging. | +| `org.opensearch.indices` | Cross-index services, such as recovery, storage, or cluster state services. Enable during shard recovery and indexing pressure analysis. | +| `org.opensearch.ingest` | Ingest pipelines and processors. Turn on when debugging pipeline execution. | +| `org.opensearch.node` | Node lifecycle and bootstrap. Useful for addressing boot up issues. | +| `org.opensearch.repositories` | Snapshot/restore repository interactions, such as with Amazon Simple Storage Service (Amazon S3), Amazon Elastic File System (Amazon EFS), and others. Use for repository errors and snapshot coordination. | +| `org.opensearch.rest` | REST handlers and routing to actions. Helpful for REST API handling details. | +| `org.opensearch.script` | Scripting engine. Use for script compilation and execution debugging. | +| `org.opensearch.search` | Search phase, such as `query`, `fetch`, or `rewrite`. Turn on for query execution debugging. | +| `org.opensearch.snapshots` | Snapshot and restore orchestration. Use when diagnosing a snapshot lifecycle. | +| `org.opensearch.threadpool` | Thread pool execution. Helpful for understanding queuing and pool saturation. | +| `org.opensearch.transport` | Inter-node transport TCP layer. Use for node-to-node communication issues. | +| `org.opensearch.deprecation` | Deprecation warnings. Useful during upgrades for finding deprecated APIs and settings. | + + +### Plugin logger categories + +The following table lists the common plugin logger categories. + +| Plugin | Logger prefix example | Description | +| :--------- | :------- | :------ | +| Security | `org.opensearch.security` | Used for debugging authentication, authorization, and TLS within the Security plugin. | +| k-NN | `org.opensearch.knn` | Used for debugging k-NN index building, search, and memory management. | +| ML Commons | `org.opensearch.ml` | Used for model registration, inference, and task runners. | +| Alerting | `org.opensearch.alerting` | Used to monitor execution and notifications. | +| Index Management | `org.opensearch.indexmanagement` | Used for Index State Management (ISM) policies, rollups, and transforms. | +| Discovery -- Amazon Elastic Compute Cloud (Amazon EC2) | `org.opensearch.discovery.ec2` | Cloud discovery information. | + + + +## Error logs + +OpenSearch logs errors at the `WARN`, `ERROR`, and `FATAL` levels. Additionally, certain exceptions from the `DEBUG` level are logged, including the following: + +- `org.opensearch.index.mapper.MapperParsingException` +- `org.opensearch.index.query.QueryShardException` +- `org.opensearch.action.search.SearchPhaseExecutionException` +- `org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException` +- `java.lang.IllegalArgumentException` + +Error logs can help with troubleshooting in many situations, including the following: + +- Painless script compilation issues +- Invalid queries +- Indexing issues +- Snapshot failures +- Index State Management migration failures + +### Mapper parsing exception scope + +Mapper parsing exceptions are logged only when they are triggered by explicit mapping requests, such as the [Put Mapping API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/put-mapping/) requests. They are not logged when triggered by document indexing operations, such as the [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) or the [Index API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/index-document/) requests. For example, if a document contains a field value that conflicts with the index mapping (for example, when you send a string value in an integer field), the Bulk API returns a `mapper_parsing_exception` in the response body, but this error is not written to the error logs. To identify documents causing a `mapper_parsing_exception` during bulk indexing, inspect the Bulk API response for errors rather than relying on error logs. + ## Search request slow logs New in version 2.12, OpenSearch offers request-level slow logs for search. These logs rely on thresholds to define what qualifies as "slow." All requests which exceed the threshold are logged. @@ -118,7 +182,7 @@ PUT /_cluster/settings A line from `opensearch_index_search_slowlog.log` might look like this: ```plaintext -[2023-10-30T15:47:42,630][TRACE][c.s.r.slowlog] [runTask-0] took[80.8ms], took_millis[80], phase_took_millis[{expand=0, query=39, fetch=22}], total_hits[4 hits], search_type[QUERY_THEN_FETCH], shards[{total: 10, successful: 10, skipped: 0, failed: 0}], source[{"query":{"match_all":{"boost":1.0}}}], id[] +[2023-10-30T15:47:42,630][TRACE][c.s.r.slowlog] [runTask-0] took[80.8ms], took_millis[80], phase_took_millis[{expand=0, query=39, fetch=22}], total_hits[4 hits], search_type[QUERY_THEN_FETCH], shards[{total: 10, successful: 10, skipped: 0, failed: 0}], indices[index_1, index_2, my_index_*], source[{"query":{"match_all":{"boost":1.0}}}], id[] ``` Search request slow logs can consume considerable disk space and affect performance if you set low threshold values. Consider enabling them temporarily for troubleshooting or performance tuning. To disable search request slow logs, return all thresholds to `-1`. @@ -133,7 +197,7 @@ These logs rely on thresholds to define what qualifies as a "slow" search or "sl Unlike search request slow logs, shard slow log thresholds are configured for individual shard took time. ```json -GET <some-index>/_settings?include_defaults=true +GET {some-index}/_settings?include_defaults=true { "indexing": { "slowlog": { @@ -176,7 +240,7 @@ GET <some-index>/_settings?include_defaults=true To enable these logs, increase one or more thresholds: ```json -PUT <some-index>/_settings +PUT {some-index}/_settings { "indexing": { "slowlog": { @@ -208,7 +272,8 @@ A line from `opensearch_index_indexing_slowlog.log` might look like this: node1 | [2019-10-24T19:48:51,012][WARN][i.i.s.index] [node1] [some-index/i86iF5kyTyy-PS8zrdDeAA] took[3.4ms], took_millis[3], type[_doc], id[1], routing[], source[{"title":"Your Name", "Director":"Makoto Shinkai"}] ``` -Shard slow logs can consume considerable disk space and affect performance if you set low threshold values. Consider enabling them temporarily for troubleshooting or performance tuning. To disable shard slow logs, return all thresholds to `-1`. +Shard slow logs can consume considerable disk space and affect performance if you set low threshold values. The logs produced are more verbose than [Search request slow logs](#search-request-slow-logs). Consider enabling them temporarily for troubleshooting or performance tuning. To disable shard slow logs, return all thresholds to `-1`. +{: .important} ## Task logs diff --git a/_install-and-configure/configuring-opensearch/monitoring-settings.md b/_install-and-configure/configuring-opensearch/monitoring-settings.md new file mode 100644 index 00000000..d9d38800 --- /dev/null +++ b/_install-and-configure/configuring-opensearch/monitoring-settings.md @@ -0,0 +1,50 @@ +--- +layout: default +title: Monitoring settings +parent: Configuring OpenSearch +nav_order: 90 +--- + +# Monitoring settings + +OpenSearch provides settings to monitor various aspects of cluster health and performance, including file system operations, JVM garbage collection, operating system metrics, and process statistics. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## File system health monitoring settings + +OpenSearch supports the following file system health monitoring settings: + +- `monitor.fs.health.enabled` (Dynamic, Boolean): Enables file system health monitoring to detect slow or unresponsive file system operations. Default is `true`. + +- `monitor.fs.health.healthy_timeout_threshold` (Dynamic, time unit): The threshold for considering a file system operation as healthy. Operations taking longer are flagged as slow. Default is `60s`. Minimum enforced is `1ms`. + +- `monitor.fs.health.slow_path_logging_threshold` (Dynamic, time unit): The threshold for logging slow file system path operations. Default is `5s`. Minimum enforced is `1ms`. + +- `monitor.fs.health.refresh_interval` (Static, time unit): The refresh interval for file system health monitoring. Default is `60s`. Minimum is `1ms`. + +- `monitor.fs.refresh_interval` (Static, time unit): The refresh interval for file system statistics monitoring. Default is `1s`. Minimum is `1s`. + +## JVM monitoring settings + +OpenSearch supports the following JVM monitoring settings: + +- `monitor.jvm.gc.enabled` (Static, Boolean): Enables JVM garbage collection monitoring. Default is `true`. + +- `monitor.jvm.gc.overhead.debug` (Static, integer): The GC overhead percentage threshold for debug logging. Default is `10`. Range is `0-100`. + +- `monitor.jvm.gc.overhead.info` (Static, integer): The GC overhead percentage threshold for info logging. Default is `25`. Range is `0-100`. + +- `monitor.jvm.gc.overhead.warn` (Static, integer): The GC overhead percentage threshold for warning logging. Default is `50`. Range is `0-100`. + +- `monitor.jvm.gc.refresh_interval` (Static, time unit): The refresh interval for JVM GC monitoring. Default is `1s`. Minimum is `1s`. + +- `monitor.jvm.refresh_interval` (Static, time unit): The refresh interval for JVM statistics monitoring. Default is `1s`. Minimum is `1s`. + +## Operating system and process monitoring settings + +OpenSearch supports the following operating system and process monitoring settings: + +- `monitor.os.refresh_interval` (Static, time unit): The refresh interval for operating system statistics monitoring. Default is `1s`. Minimum is `1s`. + +- `monitor.process.refresh_interval` (Static, time unit): The refresh interval for process statistics monitoring. Default is `1s`. Minimum is `1s`. diff --git a/_install-and-configure/configuring-opensearch/network-settings.md b/_install-and-configure/configuring-opensearch/network-settings.md index 3728c55b..14c8c44b 100644 --- a/_install-and-configure/configuring-opensearch/network-settings.md +++ b/_install-and-configure/configuring-opensearch/network-settings.md @@ -9,7 +9,7 @@ nav_order: 20 OpenSearch uses HTTP settings to configure communication with external clients through the REST API and transport settings for internal node-to-node communication within OpenSearch. -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). OpenSearch supports the following common network settings: @@ -27,6 +27,30 @@ OpenSearch supports the following advanced network settings: - `network.publish_host` (Static, list): Specifies an address or addresses that an OpenSearch node publishes to other nodes in the cluster so that they can connect to it. +## General TCP settings + +OpenSearch supports the following TCP settings that apply to all network connections, including both the HTTP and transport layers: + +- `network.tcp.keep_alive` (Static, Boolean): Enables or disables TCP keep-alive for all TCP connections used by OpenSearch, including the HTTP and transport layers. When enabled, the operating system will send periodic keep-alive packets to detect dead connections. Default is `true`. + +- `network.tcp.no_delay` (Static, Boolean): Enables or disables the `TCP_NODELAY` option for all TCP connections. When enabled, disables Nagle's algorithm, which can reduce latency for small messages at the cost of increased network traffic. This applies to both HTTP and transport connections. Default is `true`. + +- `network.tcp.receive_buffer_size` (Static, byte unit): Sets the size of the TCP receive buffer for all TCP connections used by OpenSearch. This affects both HTTP and transport connections. A larger buffer can improve throughput for high-bandwidth connections. By default, this is not explicitly set and uses the operating system default. + +- `network.tcp.reuse_address` (Static, Boolean): Controls whether TCP addresses can be reused for all TCP connections. This affects socket binding behavior for both HTTP and transport connections. Default is `true` on non-Windows machines and `false` on Windows. + +- `network.tcp.send_buffer_size` (Static, byte unit): Sets the size of the TCP send buffer for all TCP connections used by OpenSearch. This affects both HTTP and transport connections. A larger buffer can improve throughput for high-bandwidth connections. By default, this is not explicitly set and uses the operating system default. + +- `network.server` (Static, Boolean): Enables network server functionality. Default is `true`. + +- `network.tcp.keep_count` (Static, integer): Number of TCP keep-alive probes before connection is dropped. Default is `-1` (system default). Minimum is `-1`. + +- `network.tcp.keep_idle` (Static, integer): The amount of time, in seconds, before starting TCP keep-alive probes. Default is `-1` (system default). Minimum is `-1`. Maximum is `300`. + +- `network.tcp.keep_interval` (Static, integer): The time interval, in seconds, between TCP keep-alive probes. Default is `-1` (system default). Minimum is `-1`. Maximum is `300`. + +- `network.tcp.connect_timeout` (Static, time unit): Sets the timeout for establishing TCP connections across all network layers. This setting applies to both HTTP and transport connections and controls how long to wait for a connection to be established before timing out. Default is `30s`. + ## Advanced HTTP settings OpenSearch supports the following advanced network settings for HTTP communication: @@ -39,6 +63,108 @@ OpenSearch supports the following advanced network settings for HTTP communicati - `http.compression` (Static, Boolean): Enables support for compression using `Accept-Encoding` when applicable. When `HTTPS` is enabled, the default is `false`, otherwise, the default is `true`. Disabling compression for HTTPS helps mitigate potential security risks, such as `BREACH` attacks. To enable compression for HTTPS traffic, explicitly set `http.compression` to `true`. +- `http.max_header_size`: (Static, string) The maximum combined size of all HTTP headers allowed in a request. Default is `16KB`. + +- `http.compression_level` (Static, integer): Defines the compression level to use for HTTP responses when compression is enabled. Valid values are in the range of 1 (minimum compression) to 9 (maximum compression). Higher values provide better compression but use more CPU resources. Default is `3`. + +- `http.max_chunk_size` (Static, byte unit): Sets the maximum size of HTTP chunks for request and response processing. This setting controls how HTTP messages are broken into smaller pieces for transmission. Larger chunk sizes can improve throughput for large requests but may increase memory usage. Default is `8kb`. + +- `http.max_content_length` (Static, byte unit): Sets the maximum content length allowed for HTTP requests. Requests exceeding this limit will be rejected. This setting helps prevent memory issues caused by extremely large requests. Default is `100mb`. + +- `http.max_initial_line_length` (Static, byte unit): Sets the maximum length allowed for HTTP URLs in the initial request line. URLs exceeding this limit will be rejected. Default is `4kB`. + +- `http.max_warning_header_count` (Static, integer): Sets the maximum number of warning headers that can be included in HTTP responses to clients. Warning headers provide additional information about the request processing. Default is unbounded (no limit). + +- `http.max_warning_header_size` (Static, byte unit): Sets the maximum total size of all warning headers combined in HTTP responses to clients. This helps prevent response headers from becoming too large. Default is unbounded (no limit). + +- `http.pipelining.max_events` (Static, integer): Sets the maximum number of events that can be queued up in memory before an HTTP connection is closed. This setting helps manage memory usage for pipelined HTTP requests. Default is `10000`. + +- `http.publish_port` (Static, integer): Specifies the port that HTTP clients should use when communicating with this node. This setting is useful when a cluster node is behind a proxy or firewall and the actual `http.port` is not directly addressable from outside the network. Default is the actual port assigned via `http.port`. + +- `http.tcp.no_delay` (Static, Boolean): Controls the `TCP_NODELAY` option for HTTP connections. When enabled, disables Nagle's algorithm, which can reduce latency for small messages at the cost of increased network traffic. Default is `true`. + +## HTTP CORS settings + +OpenSearch supports the following Cross-Origin Resource Sharing (CORS) settings for HTTP: + +- `http.cors.enabled` (Static, Boolean): Enables or disables CORS for HTTP requests. When enabled, OpenSearch processes CORS preflight requests and responds with appropriate `Access-Control-Allow-Origin` headers if the request origin is permitted. When disabled, OpenSearch ignores the `Origin` request header, effectively disabling CORS. Default is `false`. + +- `http.cors.allow-origin` (Static, list): Specifies which origins are allowed for CORS requests. You can use wildcards (`*`) to allow all origins, though this is considered to be a security risk. You can also use regular expressions by wrapping the value with forward slashes (for example, `/https?:\/\/localhost(:[0-9]+)?/`). Default is no origins allowed. + +- `http.cors.allow-methods` (Static, list): Specifies which HTTP methods are allowed for CORS requests. Default is `OPTIONS, HEAD, GET, POST, PUT, DELETE`. + +- `http.cors.allow-headers` (Static, list): Specifies which HTTP headers are allowed in CORS requests. Default is `X-Requested-With, Content-Type, Content-Length`. + +- `http.cors.allow-credentials` (Static, Boolean): Controls whether the `Access-Control-Allow-Credentials` header should be included in CORS responses. This header is only returned when this setting is `true`. Default is `false`. + +- `http.cors.max-age` (Static, time unit): Defines for how long browsers should cache the results of CORS preflight `OPTIONS` requests. Browsers send preflight requests to determine CORS settings before making actual cross-origin requests. Default is `1728000` seconds (20 days). + +## HTTP error handling settings + +OpenSearch supports the following HTTP error handling settings: + +- `http.detailed_errors.enabled` (Static, Boolean): Controls whether detailed error messages and stack traces are included in HTTP response output. When set to `false`, only simple error messages are returned unless the `error_trace` request parameter is specified (which will return an error when detailed errors are disabled). Default is `true`. + +## HTTP debugging settings + +OpenSearch supports the following HTTP debugging settings for tracing HTTP communication: + +- `http.tracer.include` (Dynamic, list): Specifies a comma-separated list of HTTP request paths or wildcard patterns to include in HTTP tracing. When configured, only HTTP requests matching these patterns are traced in the logs. This setting is useful for debugging specific HTTP endpoints or API calls. Default is `[]` (empty list, traces all requests when HTTP tracing is enabled). + +- `http.tracer.exclude` (Dynamic, list): Specifies a comma-separated list of HTTP request paths or wildcard patterns to exclude from HTTP tracing. HTTP requests matching these patterns are not traced in the logs, even if HTTP tracing is enabled. This setting is useful for reducing noise from frequent or unimportant endpoints. Default is `[]` (empty list, no exclusions when HTTP tracing is enabled). + +- `http.netty.receive_predictor_size` (Static, byte size): The initial receive buffer size prediction for Netty HTTP transport. Default is `64kb`. + +- `http.netty.worker_count` (Static, integer): The number of worker threads for Netty HTTP transport. Default is `0` (auto-detect). + +- `http.read_timeout` (Static, time unit): The read timeout for HTTP connections. A default of 0 means no read timeout. Default is `0`. Minimum is `0`. + +- `http.reset_cookies` (Static, Boolean): Whether to reset cookies in HTTP responses. Disabled by default since cookies aren't typically needed. Default is `false`. + +- `http.tcp.keep_alive` (Static, Boolean): Enables TCP keep-alive for HTTP connections. Default is `true`. + +- `http.tcp.keep_count` (Static, integer): The number of TCP keep-alive probes before connection is dropped. Default is system default. Minimum is `-1`. + +- `http.tcp.keep_idle` (Static, integer): The amount of time, in seconds, before starting TCP keep-alive probes. Default is system default. Minimum is `-1`. Maximum is `300`. + +- `http.tcp.keep_interval` (Static, integer): The time interval, in seconds, between TCP keep-alive probes. Default is system default. Minimum is `-1`. Maximum is `300`. + +- `http.tcp.receive_buffer_size` (Static, byte size): The TCP receive buffer size for HTTP connections. Default is system default. + +- `http.tcp.reuse_address` (Static, Boolean): Enables TCP address reuse for HTTP connections. Default is system default. + +- `http.tcp.send_buffer_size` (Static, byte size): The TCP send buffer size for HTTP connections. Default is system default. + +## Experimental HTTP settings + +OpenSearch supports the following experimental HTTP settings: + +- `http.protocol.http3.enabled` (Static, Boolean): Enables the HTTP/3 protocol if it is supported by the operating system and architecture. Default is `false`. + + The HTTP/3 transport is currently experimental and should be used with caution. + {: .warning} + + It is not possible to determine in advance whether a target server supports HTTP/3. Additionally, existing HTTP/1.1 or HTTP/2 connections cannot be upgraded to HTTP/3 because HTTP/1.1 and HTTP/2 are built on TCP streams, whereas HTTP/3 uses QUIC over UDP datagrams. When enabled, the HTTP/3 transport is available on the same port as the HTTP/1.1 and HTTP/2 transports by default. + {: .note} + + The implementation relies on native libraries and uses direct NIO buffers, unlike the HTTP/1.1 and HTTP/2 transports. Take this into account when estimating native memory usage. + + HTTP/3 is secure by default and is available only when SSL/TLS is enabled for HTTP transports. OpenSearch advertises HTTP/3 availability using the `Alt-Svc` header, for example: + + ```yaml + < HTTP/2 200 + < alt-svc: h3=":9200"; ma=3600 + < x-opensearch-version: OpenSearch/3.5.0 (opensearch) + < content-type: application/json; charset=UTF-8 + < content-length: 572 + ``` + + The following platforms and architectures are supported: + - Linux/Aarch64 + - Linux/x86_64 + - OSX/Aarch64 + - Windows/x86_64 + ## Advanced transport settings OpenSearch supports the following advanced network settings for transport communication: @@ -49,11 +175,125 @@ OpenSearch supports the following advanced network settings for transport commun - `transport.publish_host` (Static, list): Specifies an address or addresses that an OpenSearch node publishes to other nodes for transport communication. +- `transport.netty.boss_count` (Static, integer): The number of boss threads for Netty transport. Default is `1`. Minimum is `1`. + +- `transport.netty.receive_predictor_max` (Static, byte size): The maximum receive buffer size prediction for Netty transport. Default is `64kb`. + +- `transport.netty.receive_predictor_min` (Static, byte size): The minimum receive buffer size prediction for Netty transport. Default is `64kb`. + +- `transport.netty.receive_predictor_size` (Static, byte size): The initial receive buffer size prediction for Netty transport. Default is `64kb`. + +- `transport.ssl.dual_mode.enabled` (Static, Boolean): Enables dual-mode SSL for transport layer (both SSL and non-SSL). Default is `false`. + +## Transport connection settings + +OpenSearch supports the following transport connection settings that control the number of connections established between nodes for different types of operations: + +- `transport.connections_per_node.bulk` (Static, integer): Sets the number of connections per node dedicated to bulk operations such as bulk indexing and bulk update requests. These connections handle high-throughput data transfer operations between nodes. Higher values can improve bulk operation performance in large clusters but consume more network resources. Default is `3`. Minimum is `1`. + +- `transport.connections_per_node.ping` (Static, integer): Sets the number of connections per node used for ping operations and basic connectivity checks between nodes. Ping connections are used for cluster health monitoring and node discovery. Default is `1`. Minimum is `1`. + +- `transport.connections_per_node.recovery` (Static, integer): Sets the number of connections per node dedicated to shard recovery operations, including replica recovery and shard rebalancing. Recovery connections handle the transfer of shard data between nodes during recovery processes. Higher values can speed up recovery operations but may increase network load. Default is `2`. Minimum is `1`. + +- `transport.connections_per_node.reg` (Static, integer): Sets the number of regular connections per node used for general cluster operations, search requests, and administrative tasks. These are the primary connections for most inter-node communication. This setting has the highest default value as regular operations are the most common. Default is `6`. Minimum is `1`. + +- `transport.connections_per_node.state` (Static, integer): Sets the number of connections per node used for cluster state synchronization and metadata operations. State connections handle the distribution of cluster state updates, mapping changes, and other metadata operations. Default is `1`. Minimum is `1`. + +## Transport debugging settings + +OpenSearch supports the following transport debugging settings for tracing transport communication: + +- `transport.tracer.include` (Dynamic, list): Specifies a comma-separated list of transport actions or patterns to include in transport tracing. When configured, only transport communications matching these patterns are traced in the logs. This setting is useful for debugging specific internal OpenSearch operations. Default is `[]` (empty list, traces all actions when transport tracing is enabled). + +- `transport.tracer.exclude` (Dynamic, list): Specifies a comma-separated list of transport actions or patterns to exclude from transport tracing. Transport communications matching these patterns are not traced in the logs, even if transport tracing is enabled. This setting is useful for reducing noise from frequent or unimportant operations. Default is `[]` (empty list, no exclusions when transport tracing is enabled). + +## Transport profile settings + +OpenSearch supports the following transport profile settings that allow configuration of multiple transport profiles for different types of connections. + +Transport profiles allow you to bind to multiple ports on different interfaces for different types of connections. The `default` profile serves as a fallback for other profiles and controls how this node connects to other nodes in the cluster. The following settings can be configured for each transport profile: + +- `transport.profiles.<profile_name>.port` (Dynamic, single value or range): Sets the port or port range to bind for this transport profile. Different profiles can use different ports to separate types of traffic. + +- `transport.profiles.<profile_name>.bind_host` (Dynamic, list): Specifies which network interfaces this transport profile should bind to for incoming connections. Different profiles can bind to different network interfaces. + +- `transport.profiles.<profile_name>.publish_host` (Dynamic, list): Specifies the address that this transport profile publishes to other nodes so they can connect to it. This is useful when the bind address differs from the externally accessible address. + +- `transport.profiles.<profile_name>.tcp.no_delay` (Dynamic, Boolean): Controls the `TCP_NODELAY` option for connections on this transport profile. When enabled, disables Nagle's algorithm to reduce latency for small messages. + +- `transport.profiles.<profile_name>.tcp.keep_alive` (Dynamic, Boolean): Controls the `SO_KEEPALIVE` option for connections on this transport profile. When enabled, the operating system sends periodic keep-alive packets to detect dead connections. + +- `transport.profiles.<profile_name>.tcp.keep_idle` (Dynamic, time unit): Sets the amount of time a connection must be idle before starting to send TCP keep alive probes. Only available on Linux and Mac with JDK 11 or later. Default is `-1` (uses system default). + +- `transport.profiles.<profile_name>.tcp.keep_interval` (Dynamic, time unit): Sets the interval between TCP keep alive probes for connections on this transport profile. Only available on Linux and Mac with JDK 11 or later. Default is `-1` (uses system default). + +- `transport.profiles.<profile_name>.tcp.keep_count` (Dynamic, integer): Sets the number of TCP keep alive probes that can be unacknowledged before the connection is dropped. Only available on Linux and Mac with JDK 11 or later. Default is `-1` (uses system default). + +- `transport.profiles.<profile_name>.tcp.reuse_address` (Dynamic, Boolean): Controls the `SO_REUSEADDR` option for sockets on this transport profile, allowing address reuse after socket closure. + +- `transport.profiles.<profile_name>.tcp.send_buffer_size` (Dynamic, byte unit): Sets the TCP send buffer size for connections on this transport profile. Larger buffers can improve throughput for high-bandwidth connections. + +- `transport.profiles.<profile_name>.tcp.receive_buffer_size` (Dynamic, byte unit): Sets the TCP receive buffer size for connections on this transport profile. Larger buffers can improve throughput for high-bandwidth connections. + +## Advanced transport settings + +OpenSearch supports the following advanced transport settings: + +- `transport.compress` (Static, Boolean): Enables `DEFLATE` compression for all inter-node transport communications. When enabled, data transmitted between nodes is compressed to reduce network bandwidth usage, which can be beneficial for clusters connected over slower network links. However, compression adds CPU overhead for compression and decompression operations. Default is `false`. + +- `transport.connect_timeout` (Static, time unit): Sets the timeout period for establishing new transport connections between nodes. If a connection attempt does not complete within this time limit, it is considered to be failed. This setting helps prevent nodes from hanging indefinitely when trying to connect to unresponsive or unreachable nodes. Default is `30s`. + +- `transport.ping_schedule` (Static, time unit): Configures the interval for sending application-level ping messages to maintain transport connections between nodes. When set to a positive value, nodes will send periodic ping messages to detect and prevent idle connection timeouts. Setting this to `-1` disables application-level pings. It is generally recommended to use TCP keep-alive settings instead because they provide more comprehensive connection monitoring for all connection types. Default is `-1` (disabled). + +- `transport.publish_port` (Static, integer): Specifies the port that other nodes should use when connecting to this node for transport communication. This setting is particularly useful when nodes are behind proxies, firewalls, or NAT configurations where the actual bind port differs from the externally accessible port. If not specified, other nodes will use the port determined by the `transport.port` setting. Default is the actual port assigned via `transport.port`. + +## Transport TCP settings + +OpenSearch supports the following transport layer TCP settings that control low-level TCP behavior for inter-node communication: + +- `transport.tcp.keep_alive` (Static, Boolean): Enables TCP keep-alive for transport connections between nodes. When enabled, the operating system sends periodic keep-alive packets to detect dead connections and maintain connection state. This helps detect network failures and unresponsive nodes more quickly. Default is `true`. + +- `transport.tcp.keep_count` (Static, integer): Sets the number of TCP keep-alive probes that can be sent without receiving a response before the connection is considered dead and closed. This setting only takes effect when TCP keep-alive is enabled. Default is `-1` (uses system default). Minimum is `-1`. + +- `transport.tcp.keep_idle` (Static, integer): Sets the amount of time, in seconds, that a transport connection must be idle before starting to send TCP keep-alive probes. This setting controls when the keep-alive mechanism activates for idle connections. Default is `-1` (uses system default). Minimum is `-1`. Maximum is `300`. + +- `transport.tcp.keep_interval` (Static, integer): Sets the time interval, in seconds, between TCP keep-alive probes for transport connections. Once keep-alive probes start, this setting determines how frequently they are sent. Default is `-1` (uses system default). Minimum is `-1`. Maximum is `300`. + +- `transport.tcp.receive_buffer_size` (Static, byte unit): Sets the TCP receive buffer size for transport connections. This controls how much data the operating system buffers for incoming transport messages. Larger buffers can improve throughput for high-bandwidth inter-node communication but consume more memory. Default is `-1` (uses system default). + +- `transport.tcp.reuse_address` (Static, Boolean): Controls the `SO_REUSEADDR` socket option for transport connections. When enabled, allows the transport layer to reuse TCP addresses immediately after connection closure, which can be helpful during rapid node restarts or high connection turnover. Default depends on the operating system (typically `true` on non-Windows systems and `false` on Windows). + +- `transport.tcp.send_buffer_size` (Static, byte unit): Sets the TCP send buffer size for transport connections. This controls how much data the operating system buffers for outgoing transport messages. Larger buffers can improve throughput for high-bandwidth inter-node communication but consume more memory. Default is `-1` (uses system default). + +- `transport.tcp.no_delay` (Static, Boolean): Controls the `TCP_NODELAY` option for transport connections between nodes. When enabled, disables Nagle's algorithm, which can reduce latency for small messages at the cost of increased network traffic. This setting is particularly important for cluster communication where low latency is critical. Default is `true`. + +- `transport.tcp.compress` (Static, Boolean): Enables DEFLATE compression for transport layer communication between nodes. When enabled, reduces network bandwidth usage at the cost of additional CPU overhead for compression and decompression. This setting is superseded by the newer `transport.compress` setting. Default is `false`. + +- `transport.tcp.connect_timeout` (Static, time unit): Sets the timeout for establishing TCP connections at the transport layer between nodes. If a connection attempt does not complete within this time limit, it is considered failed. This setting is superseded by the newer `transport.connect_timeout` setting. Default is `30s`. + +- `transport.tcp_no_delay` (Static, Boolean): **Deprecated.** Legacy setting that controls the `TCP_NODELAY` option for transport connections. This setting has been replaced by `transport.tcp.no_delay` and is maintained for backward compatibility. Use `transport.tcp.no_delay` instead. Default is `true`. + +## Transport features settings + +OpenSearch supports the following transport features settings that control optional transport layer functionality: + +- `transport.features.*` (Static, group setting): Controls which transport features are enabled for inter-node communication. This is a group setting that allows enabling or disabling specific transport layer features such as compression, security enhancements, or protocol extensions. Individual feature names are appended as suffixes to configure specific transport capabilities. These settings must be configured consistently across all nodes in the cluster to ensure compatibility. + +## Transport and HTTP type settings + +OpenSearch supports settings that control the default transport and HTTP implementation types used by the cluster. + +OpenSearch supports the following static transport and HTTP type settings: + +- `transport.type.default` (Static, string): Sets the default transport implementation type for inter-node communication. This setting determines which transport implementation OpenSearch uses when no specific transport type is configured. The default implementation is `netty4`, which provides efficient asynchronous networking based on Netty 4. Alternative implementations can be provided by plugins. Default is `netty4`. + +- `http.type.default` (Static, string): Sets the default HTTP implementation type for client communication. This setting determines which HTTP implementation OpenSearch uses when no specific HTTP type is configured. The default implementation is `netty4`, which provides efficient asynchronous HTTP processing based on Netty 4. Alternative implementations like `reactor-netty4` can be provided by plugins. Default is `netty4`. + ## Selecting the transport -The default OpenSearch transport is provided by the `transport-netty4` module and uses the [Netty 4](https://netty.io/) engine for both internal TCP-based communication between nodes in the cluster and external HTTP-based communication with clients. This communication is fully asynchronous and non-blocking. However, there are other transport plugins available that can be used interchangeably: +The default OpenSearch transport is provided by the `transport-netty4` module and uses the [Netty 4](https://netty.io/) engine for both internal TCP-based communication between nodes in the cluster and external HTTP-based communication with clients. This communication is fully asynchronous and non-blocking. The following table lists other available transport plugins that can be used interchangeably. Plugin | Description :---------- | :-------- -`transport-nio` | The OpenSearch transport based on Java NIO. <br> Installation: `./bin/opensearch-plugin install transport-nio` <br> Configuration (using `opensearch.yml`): <br> `transport.type: nio-transport` <br> `http.type: nio-http-transport` -`transport-reactor-netty4` | The OpenSearch HTTP transport based on [Project Reactor](https://github.com/reactor/reactor-netty) and Netty 4 (**experimental**) <br> Installation: `./bin/opensearch-plugin install transport-reactor-netty4` <br> Configuration (using `opensearch.yml`): <br> `http.type: reactor-netty4` +`transport-reactor-netty4` | The OpenSearch HTTP transport based on [Project Reactor](https://github.com/reactor/reactor-netty) and Netty 4 (**experimental**) <br> Installation: `./bin/opensearch-plugin install transport-reactor-netty4` <br> Configuration (using `opensearch.yml`): <br> `http.type: reactor-netty4` <br> `http.type: reactor-netty4-secure`<br>Supported protocols: **HTTP/1.1**, **HTTP/2**, **HTTP/3** (experimental, see [HTTP experimental settings](#experimental-http-settings)) + diff --git a/_install-and-configure/configuring-opensearch/plugin-settings.md b/_install-and-configure/configuring-opensearch/plugin-settings.md index cc2212fb..0bed0e1a 100644 --- a/_install-and-configure/configuring-opensearch/plugin-settings.md +++ b/_install-and-configure/configuring-opensearch/plugin-settings.md @@ -2,16 +2,18 @@ layout: default title: Plugin settings parent: Configuring OpenSearch -nav_order: 100 +nav_order: 140 --- # Plugin settings The following settings are related to OpenSearch plugins. +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + ## Alerting plugin settings -For information about alerting settings, see [Alerting settings]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/settings/#alerting-settings). +For information about alerting settings, see [Alerting settings]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/settings/). ## Anomaly Detection plugin settings @@ -27,12 +29,14 @@ For information about cross-cluster replication settings, see [Replication setti ## Flow Framework plugin settings -For information about automatic workflow settings, see [Workflow settings]({{site.url}}{{site.baseurl}}/automating-configurations/workflow-settings/). +For information about automatic workflow settings, see [Workflow settings]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/workflow-settings/). ## Geospatial plugin settings For information about the Geospatial plugin's IP2Geo processor settings, see [Cluster settings]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/ip2geo/#cluster-settings). +For information about the Geospatial plugin's GeoJSON complexity settings, see [Configuring GeoJSON complexity]({{site.url}}{{site.baseurl}}/dashboards/visualize/geojson-regionmaps/#configuring-geojson-complexity). + ## Index Management plugin settings For information about index state management (ISM) settings, see [ISM settings]({{site.url}}{{site.baseurl}}/im-plugin/ism/settings/). @@ -43,7 +47,7 @@ For information about index rollup settings, see [Index rollup settings]({{site. ## Job Scheduler plugin settings -For information about the Job Scheduler plugin settings, see [Job Scheduler cluster settings]({{site.url}}{{site.baseurl}}/monitoring-your-cluster/job-scheduler/index/#job-scheduler-cluster-settings). +For information about the Job Scheduler plugin settings, see [Scheduled job settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/scheduled-jobs/index/#scheduled-job-settings). ## k-NN plugin settings @@ -55,9 +59,7 @@ For information about machine learning settings, see [ML Commons cluster setting ## Neural Search plugin settings -The Security Analytics plugin supports the following settings: - -- `plugins.neural_search.hybrid_search_disabled` (Dynamic, Boolean): Disables hybrid search. Default is `false`. +For information about Neural Search plugin settings, see [Neural Search plugin settings]({{site.url}}{{site.baseurl}}/vector-search/settings/#neural-search-plugin-settings). ## Notifications plugin settings @@ -83,9 +85,14 @@ The Notifications plugin supports the following settings. All settings in this l - `opensearch.notifications.general.filter_by_backend_roles` (Boolean): Enables filtering by backend roles (role-based access control for the notification channels). Default is `false`. +- `opensearch.notifications.general.filter_by_backend_roles_access_strategy` (String): Controls filtering by backend roles (role-based access control for the notification channels). Valid values are: + - `intersect` (Default) -- Users have access to notifications objects if they share at least one backend role with the user who created the object. + - `exact` -- Users have access to notifications objects if they have exactly the same (with no additional) backend roles as the user who created the object. + - `all` -- Users have access to notifications objects if their backend roles contain all of the backend roles of the user who created the object. + ## Query Insights plugin settings -For information about Query Insights plugin settings, see [Query insights settings]({{site.url}}{{site.baseurl}}/observing-your-data/query-insights/index#query-insights-settings). +For information about Query Insights plugin settings, see [Query Insights features and settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/query-insights/index#query-insights-features-and-settings). ## Security plugin settings @@ -93,8 +100,18 @@ For information about the Security plugin settings, see [Security settings]({{si ## Security Analytics plugin settings -For information about security analytics settings, see [Security Analytics settings]({{site.url}}{{site.baseurl}}/security-analytics/settings/). +For information about the Security Analytics plugin settings, see [Security Analytics settings]({{site.url}}{{site.baseurl}}/security-analytics/settings/). ## SQL plugin settings -For information about settings related to SQL and PPL, see [SQL settings]({{site.url}}{{site.baseurl}}/search-plugins/sql/settings/). \ No newline at end of file +For information about settings related to SQL and PPL, see [SQL settings]({{site.url}}{{site.baseurl}}/search-plugins/sql/settings/). + +## Workload Management plugin settings + +For information about workload management settings, see [Workload management settings]({{site.url}}{{site.baseurl}}/tuning-your-cluster/workload-management/wlm-feature-overview/#workload-management-settings). + +## General plugin settings + +OpenSearch supports the following general plugin configuration settings: + +- `plugin.mandatory` (Static, list): Specifies plugins that are required for the node to start successfully. If any of the listed plugins are not available or fail to load, the node will not start. This setting is particularly important for clusters that depend on custom processors or other critical plugin functionality to ensure consistent behavior across all nodes. You can specify multiple plugins as a comma-separated list. Default is `[]` (empty list). diff --git a/_install-and-configure/configuring-opensearch/script-and-resource-settings.md b/_install-and-configure/configuring-opensearch/script-and-resource-settings.md new file mode 100644 index 00000000..1fb6b73d --- /dev/null +++ b/_install-and-configure/configuring-opensearch/script-and-resource-settings.md @@ -0,0 +1,80 @@ +--- +layout: default +title: Script and resource settings +parent: Configuring OpenSearch +nav_order: 160 +--- + +# Script and resource settings + +OpenSearch provides settings for managing script compilation behavior and resource file monitoring. These settings help control script performance, security, and automatic reloading of configuration files and other resources. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## Resource reload settings + +Resource reload settings control the monitoring and automatic reloading of configuration files, security certificates, and other resources that OpenSearch needs to watch for changes. + +OpenSearch supports the following static resource reload settings: + +- `resource.reload.enabled` (Static, Boolean): Enables or disables the resource watcher service. When enabled, OpenSearch monitors registered resources for changes and reloads them periodically. This is useful for automatically detecting changes to configuration files, security certificates, and other resources without requiring a cluster restart. Default is `true`. + +- `resource.reload.interval.low` (Static, time unit): Sets the reload interval for low-frequency resource monitoring. Resources registered with low frequency are checked for changes at this interval. This is typically used for resources that change infrequently, such as configuration files. Default is `60s` (60 seconds). + +- `resource.reload.interval.medium` (Static, time unit): Sets the reload interval for medium-frequency resource monitoring. Resources registered with medium frequency are checked for changes at this interval. This provides a balance between responsiveness and system load for moderately changing resources. Default is `30s` (30 seconds). + +- `resource.reload.interval.high` (Static, time unit): Sets the reload interval for high-frequency resource monitoring operations. This setting controls how often OpenSearch checks for changes to resources that require frequent monitoring, such as configuration files or security certificates. More frequent checks provide faster response to changes but consume more system resources. This setting is used by the resource watcher service for high-priority resources. Default is `5s`. + +## Script size settings + +OpenSearch supports the following dynamic script size setting: + +- `script.max_size_in_bytes` (Dynamic, integer): Sets the maximum size, in bytes, of an individual script. OpenSearch rejects a longer script. Default is `65535`. + +Lower `script.max_size_in_bytes` only after deleting any stored script that exceeds the new value. OpenSearch accepts the setting but then fails to apply it, and the node stops applying further cluster state updates until the setting is removed. +{: .warning} + +## Script compilation settings + +OpenSearch compiles a script on first use and caches the compiled result, so a script is recompiled only when its definition changes. A compilation rate limit caps how many new compilations a node performs in a time window, which prevents a high number of unique scripts from consuming a node's CPU on compilation. For an explanation of how the cache and the rate limit apply to a workload, see [Compilation limits and caching]({{site.url}}{{site.baseurl}}/scripting/using-scripts/#compilation-limits-and-caching). + +The value of `script.max_compilations_rate` determines whether the cache and the rate limit are tracked separately for each script context or shared across the cluster. OpenSearch supports the following script compilation settings: + +- `script.max_compilations_rate` (Dynamic, string): Set to `use-context` to give each script context its own cache and compilation rate, configured through the [script context settings](#script-context-settings). Set it to a rate in the form `<count>/<time>`, such as `150/5m`, to use a single cluster-wide limit and one shared cache instead, in which case the per-context settings are rejected. Default is `use-context`. + +- `script.cache.max_size` (Static, integer): Sets the number of compiled scripts held in the shared cache on each node. When the cache is full, the least recently used script is evicted. Configuring this setting explicitly also changes the default of `script.context.<context>.cache_max_size` to the same value. Default is `100`. + +- `script.cache.expire` (Static, time unit): Sets the time after which a compiled script is evicted from the shared cache and must be recompiled on next use. Configuring this setting explicitly also changes the default of `script.context.<context>.cache_expire` to the same value. Default is `0ms`, which means that cached scripts do not expire on a timer. + +- `script.disable_max_compilations_rate` (Static, Boolean): Removes the compilation rate limit entirely when set to `true`. This setting conflicts with both an explicit `script.max_compilations_rate` and any per-context rate, so remove those before setting it. Default is `false`. + +`script.max_compilations_rate`, `script.cache.max_size`, and `script.cache.expire` are deprecated, because they exist to support the single shared cache. Leave `script.max_compilations_rate` at `use-context` and configure the per-context settings, which are dynamic and take effect without a restart. +{: .note} + +A cluster with no compilation limit lets any client that can submit a script consume unbounded compilation CPU. Parameterize the scripts that trip the limit rather than turning the limit off. For more information, see [Passing values as parameters]({{site.url}}{{site.baseurl}}/scripting/using-scripts/#passing-values-as-parameters). +{: .warning} + +## Script context settings + +Script context settings control caching and compilation for an individual script context, so that heavy recompilation in one context does not evict the cached scripts of another. They apply only when `script.max_compilations_rate` is set to `use-context`. Replace `<context>` with a context name returned by the [Get Script Contexts API]({{site.url}}{{site.baseurl}}/api-reference/script-apis/get-script-contexts/). + +OpenSearch supports the following dynamic script context settings: + +- `script.context.<context>.cache_max_size` (Dynamic, integer): Sets the number of compiled scripts held for this context. A larger cache reduces compilation overhead for a workload that uses many distinct scripts and consumes more memory. Default is `100` for most contexts, or the value of `script.cache.max_size` when that setting is configured explicitly. + +- `script.context.<context>.cache_expire` (Dynamic, time unit): Sets the time after which a compiled script for this context is evicted from the cache and must be recompiled on next use. Default is `0ms`, which means that cached scripts do not expire on a timer, or the value of `script.cache.expire` when that setting is configured explicitly. + +- `script.context.<context>.max_compilations_rate` (Dynamic, string): Sets the number of compilations allowed for this context in a time window, in the form `<count>/<time>`, such as `200/1m`. Set it to `unlimited` to remove the limit for this context. When the rate is exceeded, OpenSearch returns a `circuit_breaking_exception` with a "Too many dynamic script compilations" message. Default is `75/5m` for most contexts. + +Three contexts have different defaults. The following table lists them. + +Context | Purpose | `cache_max_size` | `max_compilations_rate` +:--- | :--- | :--- | :--- +`search` | The [`script` search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/script-processor/). | `200` | `unlimited` +`ingest` | The [`script` ingest processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/script/). | `200` | `unlimited` +`processor_conditional` | The `if` condition on an ingest processor. | `200` | `unlimited` + +Configuring any per-context setting while `script.max_compilations_rate` is set to an explicit rate fails with `Context cache settings [<settings>] requires [script.max_compilations_rate] to be [use-context]`. +{: .note} + +For the settings that limit which scripts a cluster accepts and how regular expressions in Painless are constrained, see [Script security]({{site.url}}{{site.baseurl}}/scripting/script-security/). \ No newline at end of file diff --git a/_install-and-configure/configuring-opensearch/search-settings.md b/_install-and-configure/configuring-opensearch/search-settings.md index 3890097e..0eae02e4 100644 --- a/_install-and-configure/configuring-opensearch/search-settings.md +++ b/_install-and-configure/configuring-opensearch/search-settings.md @@ -7,6 +7,10 @@ nav_order: 80 # Search settings +OpenSearch provides settings that control how search requests run across the cluster, including request limits, timeouts and cancellation, scroll and Point in Time (PIT) context lifetimes, and query and aggregation optimizations. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + OpenSearch supports the following search settings: - `search.max_buckets` (Dynamic, integer): The maximum number of aggregation buckets allowed in a single response. Default is `65535`. @@ -15,11 +19,27 @@ OpenSearch supports the following search settings: - `search.allow_expensive_queries` (Dynamic, Boolean): Allows or disallows expensive queries. For more information, see [Expensive queries]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries). +- `search.query_rewriting.enabled` (Dynamic, Boolean): Enables query rewriting optimizations that can improve search performance by transforming queries into more efficient forms. When enabled, OpenSearch can automatically optimize certain query patterns, such as merging multiple `term` queries on the same field into a single `terms` query. Default is `false`. + +- `search.query_rewriting.terms_threshold` (Dynamic, integer): Controls the threshold for the number of `term` queries on the same field that triggers the `terms` merging rewriter to combine them into a single `terms` query. For example, if set to `16` (default), when 16 or more term queries target the same field within a Boolean clause, they will be merged into a single `terms` query for better performance. Minimum is `2`. Default is `16`. + +- `search.query.max_query_string_length` (Dynamic, integer): The maximum allowed length for query string queries. This setting helps prevent performance issues by rejecting query strings longer than the specified limit. Default is `32000`. + - `search.default_allow_partial_results` (Dynamic, Boolean): A cluster-level setting that allows returning partial search results if a request times out or a shard fails. If a search request contains an `allow_partial_search_results` parameter, the parameter takes precedence over this setting. Default is `true`. -- `search.cancel_after_time_interval` (Dynamic, time unit): A cluster-level setting that specifies the maximum amount of time that a search request can run before it is canceled at the shard level. After this time has been reached, a request is stopped and all associated tasks are canceled. Default is `-1`. +- `search.node_level_query_fanout.enabled` (Dynamic, Boolean): Enables node-level query fan-out. When enabled, the coordinating node groups shard-level `query_then_fetch` query and `can_match` requests by target data node instead of sending one transport request per shard. If a search request contains the `node_level_query_fanout` parameter, the parameter takes precedence over this setting. Default is `false`. -- `search.default_search_timeout` (Dynamic, time unit): A cluster-level setting that sets the default timeout for all search requests at the coordinating node level. If the `timeout` is specified in the search request, it takes precedence over this setting. Default is `-1` (no timeout). +<p id="index-pruning-settings"></p> + +- `search.index_pruning.enabled` (Dynamic, Boolean): Enables index-level search pruning, which runs on the coordinating node before any shard-level request. For more information, see [Index-level search pruning]({{site.url}}{{site.baseurl}}/search-plugins/index-level-search-pruning/). Default is `false`. + +- `search.index_pruning.min_shards` (Dynamic, integer): The minimum number of active shard groups (a primary shard and its replicas count as one group) required before OpenSearch attempts index-level search pruning. Default is `128`. + +- `search.index_pruning.fields` (Dynamic, list): The query fields eligible for index-level search pruning. OpenSearch extracts range constraints only for these fields. Default is `[]`. + +- `search.cancel_after_time_interval` (Dynamic, time unit): A cluster-level setting that sets the default timeout for all search requests at the coordinating node level. After the specified time has been reached, the request is stopped and all associated tasks are canceled. Default is `-1` (no timeout). + +- `search.default_search_timeout` (Dynamic, time unit): A cluster-level setting that specifies the maximum amount of time that a search request can run before the request is canceled at the shard-level. If the `timeout` interval is specified in the search request, that interval takes precedence over the configured setting. Default is `-1`. - `search.default_keep_alive` (Dynamic, time unit): Specifies the default keep alive value for scroll and Point in Time (PIT) searches. Because a request may land on a shard multiple times (for example, during the query and fetch phases), OpenSearch opens a _request context_ that exists for the full duration of the request to ensure consistency of the shard state for each individual shard request. In a standard search, once the fetch phase completes, the request context is closed. For a scroll or a PIT search, OpenSearch keeps the request context open until explicitly closed (or until the keep alive time is reached). A background thread periodically checks all open scroll and PIT contexts and deletes the ones that have exceeded their keep alive timeout. The `search.keep_alive_interval` setting specifies how frequently the contexts are checked for expiration. The `search.default_keep_alive` setting is the default deadline for expiration. A scroll or PIT request can explicitly specify the keep alive, which takes precedence over this setting. Default is `5m`. @@ -31,12 +51,22 @@ OpenSearch supports the following search settings: - `search.max_open_scroll_context` (Dynamic, integer): A node-level setting that specifies the maximum number of open scroll contexts for the node. Default is `500`. -- `search.request_stats_enabled` (Dynamic, Boolean): Turns on node-level collection of phase-timing statistics from the perspective of the coordinator node. The request-level statistics keep track of how long (in total) search requests spend in each of the different search phases. You can retrieve these counters using the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/). Default is `false`. +- `search.request_stats_enabled` (Dynamic, Boolean): Turns on node-level collection of phase-timing statistics from the perspective of the coordinating node. The request-level statistics keep track of how long (in total) search requests spend in each of the different search phases. You can retrieve these counters using the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/). Default is `false`. - `search.highlight.term_vector_multi_value` (Static, Boolean): Specifies to highlight snippets across values of a multi-valued field. Default is `true`. +- `search.max_aggregation_rewrite_filters` (Dynamic, integer): Determines the maximum number of rewrite filters allowed during aggregation. Set this value to `0` to disable the filter rewrite optimization for aggregations. This is an experimental feature and may change or be removed in future versions. + +- `search.dynamic_pruning.cardinality_aggregation.max_allowed_cardinality` (Dynamic, integer): Determines the threshold for applying dynamic pruning in cardinality aggregation. If a field's cardinality exceeds this threshold, the aggregation reverts to the default method. This is an experimental feature and may change or be removed in future versions. + +- `search.aggregation.bucket_selection_strategy_factor` (Dynamic, integer): Controls the algorithm used to select top buckets in terms aggregations. This factor determines when to use a priority queue (better for small result sets) and when to use quick select (better for large result sets). The strategy is chosen based on the condition `size * factor < bucketsInOrd`. A factor of `0` always uses priority queue, while higher values favor quick select for larger result sets. Valid values are `0` to `10` (inclusive). Default is `5`. + +- `search.keyword_index_or_doc_values_enabled` (Dynamic, Boolean): Determines whether to use the index or doc values when running `multi_term` queries on `keyword` fields. Default value is `false`. + +## Scripting settings + +Scripts used in searches are governed by the script size, compilation, and caching settings. For more information, see [Script and resource settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/script-and-resource-settings/). + ## Point in Time settings -For information about PIT settings, see [PIT settings]({{site.url}}{{site.baseurl}}/search-plugins/point-in-time-api/#pit-settings). - -To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +For information about PIT settings, see [PIT settings]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/#pit-settings). diff --git a/_install-and-configure/configuring-opensearch/security-settings.md b/_install-and-configure/configuring-opensearch/security-settings.md index 3ea3e3a6..6215e1c8 100644 --- a/_install-and-configure/configuring-opensearch/security-settings.md +++ b/_install-and-configure/configuring-opensearch/security-settings.md @@ -9,47 +9,57 @@ nav_order: 40 The Security plugin provides a number of YAML configuration files that are used to store the necessary settings that define the way the Security plugin manages users, roles, and activity within the cluster. For a full list of the Security plugin configuration files, see [Modifying the YAML files]({{site.url}}{{site.baseurl}}/security/configuration/yaml/). -The following sections describe security-related settings in `opensearch.yml`. To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). +The following sections describe security-related settings in `opensearch.yml`. You can find the `opensearch.yml` in the `<OPENSEARCH_HOME>/config/opensearch.yml`. To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). ## Common settings The Security plugin supports the following common settings: -- `plugins.security.nodes_dn` (Static): Specifies a list of distinguished names (DNs) that denote the other nodes in the cluster. This setting supports wildcards and regular expressions. The list of DNs are also read from the security index **in addition** to the YAML configuration when `plugins.security.nodes_dn_dynamic_config_enabled` is `true`. +- `plugins.security.nodes_dn` (Static): Specifies a list of distinguished names (DNs) that denote the other nodes in the cluster. This setting supports wildcards and regular expressions. The list of DNs are also read from the security index **in addition** to the YAML configuration when `plugins.security.nodes_dn_dynamic_config_enabled` is `true`. If this setting is not configured correctly, the cluster will fail to form as the nodes will not be able to trust each other and will result in the following error: `Transport client authentication no longer supported`. -- `plugins.security.nodes_dn_dynamic_config_enabled` (Static): Relevant for `cross_cluster` use cases where there is a need to manage the allow listed `nodes_dn` without having to restart the nodes every time a new `cross_cluster` remote is configured. +- `plugins.security.nodes_dn_dynamic_config_enabled` (Static): Relevant for `cross_cluster` use cases where there is a need to manage the allow listed `nodes_dn` without having to restart the nodes every time a new `cross_cluster` remote is configured. Setting `nodes_dn_dynamic_config_enabled` to `true` enables **super-admin callable** Distinguished Names APIs, which provide means to update or retrieve `nodes_dn` dynamically. This setting only has effect if `plugins.security.cert.intercluster_request_evaluator_class` is not set. Default is `false`. - `plugins.security.authcz.admin_dn` (Static): Defines the DNs of certificates to which admin privileges should be assigned. Required. -- `plugins.security.roles_mapping_resolution` (Static): Defines how backend roles are mapped to Security roles. - - Valid values are: +- `plugins.security.roles_mapping_resolution` (Static): Defines how backend roles are mapped to Security roles. The following values are supported: - `MAPPING_ONLY`(Default): Mappings must be configured explicitly in `roles_mapping.yml`. - `BACKENDROLES_ONLY`: Backend roles are mapped to security roles directly. Settings in `roles_mapping.yml` have no effect. - `BOTH`: Backend roles are mapped to security roles both directly and through `roles_mapping.yml`. -- `plugins.security.dls.mode` (Static): Sets the document-level security (DLS) evaluation mode. Default is `adaptive`. See [How to set the DLS evaluation mode]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/#how-to-set-the-dls-evaluation-mode-in-opensearchyml). +- `plugins.security.dls.write_blocked` (Dynamic): When set to `true`, the Security plugin rejects index and delete operations, including those in bulk requests, from users to whom document-level security (DLS), field-level security (FLS), or field masking applies on the target index. Default is `false`. -- `plugins.security.compliance.salt` (Static): The salt to use when generating the hash value for field masking. Must be at least 32 characters. Only ASCII characters are allowed. Optional. +- `plugins.security.dfm_empty_overrides_all` (Dynamic): When set to `true`, a role that grants access to an index without DLS, FLS, or field masking restrictions overrides the restrictions that other roles of the same user apply to that index. Default is `false`. Set this setting in `opensearch.yml`. Although the Cluster Settings API accepts this setting, a value set using the API reverts to the `opensearch.yml` value the next time the security configuration changes. For more information, see [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/). + +- `plugins.security.compliance.salt` (Static): The salt to use when generating the hash value for field masking. Must contain at least 16 ASCII characters. Only the first 16 bytes are used. Optional. + +- `plugins.security.compliance.immutable_indices` (Static): Documents in indexes that are marked as immutable follow the write-once, read-many paradigm. Documents created in these indexes cannot be changed and are therefore immutable. - `config.dynamic.http.anonymous_auth_enabled` (Static): Enables anonymous authentication. This will cause all HTTP authenticators to not challenge. Default is `false`. +- `http.detailed_errors.enabled` (Static): Enables a detailed error message for REST calls performed against the OpenSearch cluster. If set to `true`, provides the `root_cause` together with the error code. Default is `true`. + ## REST management API settings The Security plugin supports the following REST management API settings: - `plugins.security.restapi.roles_enabled` (Static): Enables role-based access to the REST management API for listed roles. Roles are separated by a comma. Default is an empty list (no role is allowed to access the REST management API). See [Access control for the API]({{site.url}}{{site.baseurl}}/security/access-control/api/#access-control-for-the-api). -- `plugins.security.restapi.endpoints_disabled.<role>.<endpoint>` (Static): Disables specific endpoints and their HTTP methods for roles. Values for this setting compose an array of HTTP methods. For example: `plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"]`. By default, all endpoints and methods are allowed. Existing endpoints include `ACTIONGROUPS`, `CACHE`, `CONFIG`, `ROLES`, `ROLESMAPPING`, `INTERNALUSERS`, `SYSTEMINFO`, `PERMISSIONSINFO`, and `LICENSE`. See [Access control for the API]({{site.url}}{{site.baseurl}}/security/access-control/api/#access-control-for-the-api). +- `plugins.security.restapi.endpoints_disabled.<role>.<endpoint>` (Static): Disables specific endpoints and their HTTP methods for roles. Values for this setting compose an array of HTTP methods. For example: `plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"]`. By default, all endpoints and methods are allowed. To disable an endpoint for every role, use `global` in place of the role name. For the valid `<endpoint>` values, see [Endpoint values]({{site.url}}{{site.baseurl}}/security/access-control/api/#endpoint-values). + +- `plugins.security.restapi.admin.enabled` (Static): Enables the `restapi:admin/*` cluster permissions, which grant a role access to the allow list, distinguished name, and certificate APIs. When this setting is `false`, these permissions have no effect, and those APIs are reachable only with an admin certificate. Default is `false`. See [REST API admin permissions]({{site.url}}{{site.baseurl}}/security/access-control/api/#rest-api-admin-permissions). + +- `plugins.security.restapi.max_string_length` (Static): Sets the maximum number of characters allowed for any individual string value in a Security REST API request body. Valid values are between `1` and `50000000`, inclusive. Default is `4096`. Increase this value if you submit large free-form values, such as document-level security (DLS) queries, through the REST API. + +- `plugins.security.restapi.bulk_max_entries` (Dynamic): Sets the maximum number of entries in one bulk create or update request to the Security REST API. Valid values are 1--100000. Default is `1000`. Only users with a role listed in `plugins.security.restapi.roles_enabled` can change this setting. - `plugins.security.restapi.password_validation_regex` (Static): Specifies a regular expression to set the criteria for the login password. For more information, see [Password settings]({{site.url}}{{site.baseurl}}/security/configuration/yaml/#password-settings). - `plugins.security.restapi.password_validation_error_message` (Static): Specifies an error message that loads when a password doesn’t pass validation. This setting is used in conjunction with `plugins.security.restapi.password_validation_regex`. -- `plugins.security.restapi.password_min_length` (Static): Sets the minimum number of characters for the password length when using the score-based password strength estimator. The default is 8. This is also the minimum. For more information, see [Password settings]({{site.url}}{{site.baseurl}}/security/configuration/yaml/#password-settings). +- `plugins.security.restapi.password_min_length` (Static): Sets the minimum number of characters for the password length. Default is `-1`, which means that no minimum length is enforced. For more information, see [Password settings]({{site.url}}{{site.baseurl}}/security/configuration/yaml/#password-settings). -- `plugins.security.restapi.password_score_based_validation_strength` (Static): Sets a threshold to determine whether the password is strong or weak. Valid values are `fair`, `good`, `strong`, and `very_strong`. This setting is used in conjunction with `plugins.security.restapi.password_min_length`. +- `plugins.security.restapi.password_score_based_validation_strength` (Static): Sets a threshold to determine whether the password is strong or weak. Valid values are `fair`, `good`, `strong`, and `very_strong`. Default is `strong`. This setting is used in conjunction with `plugins.security.restapi.password_min_length`. - `plugins.security.unsupported.restapi.allow_securityconfig_modification` (Static): Enables the use of the PUT and PATCH methods for the configuration APIs. @@ -71,6 +81,8 @@ The Security plugin supports the following advanced settings: These certificates are well known and therefore unsafe for production. Use only in a private network/environment. {: .warning} +- `plugins.security.ccs.ignore_source_security_roles` (Dynamic): When set to `true`, a remote cluster ignores the security roles propagated from the coordinating cluster on cross-cluster search requests and evaluates access using only its own `roles_mapping.yml` configuration. Default is `false`. See [Remote cluster role evaluation]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/#remote-cluster-role-evaluation). + - `plugins.security.system_indices.permission.enabled` (Static): Enables the system index permissions feature. When set to `true`, the feature is enabled and users with permission to modify roles can create roles that include permissions that grant access to system indexes. When set to `false`, the permission is disabled and only admins with an admin certificate can make changes to system indexes. By default, the permission is set to `false` in a new cluster. ## Expert-level settings @@ -110,6 +122,10 @@ The Security plugin supports the following expert-level settings: - `plugins.security.system_indices.indices` (Static): A list of indexes to be used as system indexes. This setting is controlled by the `plugins.security.system_indices.enabled` setting. +- `plugins.security.system_indices.restore.indices` (Dynamic): A list of system indexes that a user mapped to a role in `plugins.security.restapi.roles_enabled` can restore from a snapshot. The restore request must name each system index that it restores, or match it with a pattern that is no broader than an entry in this list, and it must not rename indexes. This setting doesn't apply to a super admin or to users who have the [system index permission]({{site.url}}{{site.baseurl}}/security/access-control/permissions/#system-index-permissions). By default, the list contains the system indexes that have been tested for restoration to a new cluster running the same OpenSearch version as the original cluster. To view the default list, send `GET /_cluster/settings?include_defaults=true&filter_path=defaults.plugins.security.system_indices.restore.indices`. If you configure this setting, the specified list replaces the default list. To preserve the default entries, include them in your list. To update this setting using the Cluster Settings API, set `plugins.security.system_indices.restore.dynamic.enabled` to `true`. You can always set it in `opensearch.yml`. + +- `plugins.security.system_indices.restore.dynamic.enabled` (Static): When set to `true`, allows updating `plugins.security.system_indices.restore.indices` using the Cluster Settings API. Default is `false`. + - `plugins.security.allow_default_init_securityindex` (Static): When set to `true`, sets the Security plugin to its default security settings if an attempt to create the security index fails when OpenSearch launches. Default security settings are stored in YAML files contained in the `opensearch-project/security/config` directory. Default is `false`. - `plugins.security.cert.intercluster_request_evaluator_class` (Static): A class to be used for evaluating intercluster communication. @@ -118,6 +134,51 @@ The Security plugin supports the following expert-level settings: - `plugins.security.check_snapshot_restore_write_privileges` (Static): Enforces write privilege evaluation when creating snapshots. Default is `true`. +If you change any of the following password hashing properties, you must rehash all internal passwords to ensure compatibility and security. +{: .warning} + +- `plugins.security.password.hashing.algorithm`: (Static): Specifies the password hashing algorithm to use. The following values are supported: + - `BCrypt` (Default) + - `PBKDF2` (Compliant with FIPS 140-2 and FIPS 140-3) + - `Argon2` + +- `plugins.security.password.hashing.bcrypt.rounds` (Static): Specifies the number of rounds to use for password hashing with `BCrypt`. Valid values are between `4` and `31`, inclusive. Default is `12`. + +- `plugins.security.password.hashing.bcrypt.minor` (Static): Specifies the minor version of the `BCrypt` algorithm to use for password hashing. The following values are supported: + - `A` + - `B` + - `Y` (Default) + +- `plugins.security.password.hashing.pbkdf2.function` (Static): Specifies the pseudo-random function applied to the password. The following values are supported: + - `SHA1` + - `SHA224` + - `SHA256` (Default) + - `SHA384` + - `SHA512` + +- `plugins.security.password.hashing.pbkdf2.iterations` (Static): Specifies the number of times that the pseudo-random function is applied to the password. Default is `600,000`. + +- `plugins.security.password.hashing.pbkdf2.length` (Static): Specifies the desired length of the final derived key. Default is `256`. + +- `plugins.security.password.hashing.argon2.iterations`: Specifies the number of passes over memory that the algorithm performs. Increasing this value raises CPU computation time and improves resistance to brute-force attacks. Default: `3`. + +- `plugins.security.password.hashing.argon2.memory`: Specifies the amount of memory (in kibibytes) used during hashing. Default: `65536` (64 MiB). + +- `plugins.security.password.hashing.argon2.parallelism`: Specifies the number of parallel threads used for computation. Default: `1`. + +- `plugins.security.password.hashing.argon2.length`: Specifies the length (in bytes) of the resulting hash output. Default: `32`. + +- `plugins.security.password.hashing.argon2.type`: Specifies which variant of Argon2 to use. The following values are supported: + - `Argon2i` + - `Argon2d` + - `Argon2id` (default) + +- `plugins.security.password.hashing.argon2.version`: Specifies which version of Argon2 to use. The following values are supported: + - `16` + - `19` (default) + + + ## Audit log settings The Security plugin supports the following audit log settings: @@ -126,23 +187,31 @@ The Security plugin supports the following audit log settings: - `plugins.security.audit.enable_transport` (Dynamic): Enables or disables transport-level request logging. Default is `false` (disable). -- `plugins.security.audit.resolve_bulk_requests` (Dynamic): Enable or disable bulk request logging. When enabled, all subrequests in bulk requests are also logged. Default is `false` (disabled). +- `plugins.security.audit.resolve_bulk_requests` (Dynamic): Enable or disable bulk request logging. When enabled, all individual requests within bulk requests are also logged. Default is `false` (disabled). - `plugins.security.audit.config.disabled_categories` (Dynamic): Disables the specified event categories. - `plugins.security.audit.ignore_requests` (Dynamic): Excludes the specified requests from being logged. Allows wildcards and regular expressions containing actions or REST request paths. -- `plugins.security.audit.threadpool.size` (Static): Determines the number of threads in the thread pool used to log events. Default is `10`. Setting this value to `0` disables the thread pool, which means the plugin logs events synchronously. +- `plugins.security.audit.threadpool.size` (Static): Determines the number of threads in the thread pool used to log events. Default is `10`. If the value is `0` or less, the node fails to start. -- `plugins.security.audit.threadpool.max_queue_len` (Static): Sets the maximum queue length per thread. Default is `100000`. +- `plugins.security.audit.threadpool.max_queue_len` (Static): Sets the maximum number of audit events that can wait in the queue shared by all threads in the thread pool. Default is `100000`. If the value is `0` or less, the node fails to start. - `plugins.security.audit.ignore_users` (Dynamic): An array of users. Audit requests from the users in the list will not be logged. - `plugins.security.audit.type` (Static): The destination of audit log events. Valid values are `internal_opensearch`, `external_opensearch`, `debug`, and `webhook`. +- `plugins.security.audit.enable_standalone` (Static): Enables standalone audit logging for clusters running without fine-grained access control (SSL-only or security-disabled modes). Set this to `true` and also set `plugins.security.audit.type` to activate standalone audit logging. Default is `false`. For more information, see [Standalone audit logging]({{site.url}}{{site.baseurl}}/security/audit-logs/standalone/). + +- `plugins.security.audit.config.body_logging_exclusions` (Dynamic): A list of action group names or raw action and path patterns for which request body logging is suppressed. Default is `[]`, which logs all request bodies. For more information, see [Body logging exclusions]({{site.url}}{{site.baseurl}}/security/audit-logs/index/#body-logging-exclusions). + +- `plugins.security.audit.config.action_groups.<NAME>` (Static): Defines named groups of action and path patterns for use with `body_logging_exclusions`. Each group is a comma-separated string of transport action patterns, REST paths, or both. Supports wildcards. + +- `plugins.security.audit.config.log4j.enable_mdc_routing` (Static): Enables Mapped Diagnostic Context (MDC) routing for the Log4j audit sink. When enabled, audit events set the `audit_category`, `audit_action`, `audit_user`, and `audit_request_type` MDC keys, which Log4j routing appenders can use. Default is `false`. + - `plugins.security.audit.config.http_endpoints` (Static): A list of endpoints for `localhost`. -- `plugins.security.audit.config.index` (Static): The audit log index. The default is `auditlog6`. The index can be static or an index that includes a date so that it rotates on a daily basis, for example, `"'auditlog6-'YYYY.MM.dd"`. In either case, make sure to secure the index properly. +- `plugins.security.audit.config.index` (Static): The audit log index. The default is the date-rolling pattern `"'security-auditlog-'YYYY.MM.dd"`, which produces a new index daily (for example, `security-auditlog-2023.06.15`). You can also specify a fixed index name instead. In either case, make sure to secure the index properly. - `plugins.security.audit.config.type` (Static): Specify the audit log type as `auditlog`. @@ -160,17 +229,17 @@ The Security plugin supports the following audit log settings: - `plugins.security.audit.config.pemkey_filepath` (Static): The `/config` relative file path to the Privacy Enhanced Mail (PEM) key used for audit logging. -- `plugins.security.audit.config.pemkey_content` (Static): The base64-encoded content of the PEM key used for audit logging. This is an alternative to `...config.pemkey_filepath`. +- `plugins.security.audit.config.pemkey_content` (Static): The Base64-encoded content of the PEM key used for audit logging. This is an alternative to `...config.pemkey_filepath`. - `plugins.security.audit.config.pemkey_password` (Static): Password for the PEM-formatted private key used by the client. - `plugins.security.audit.config.pemcert_filepath` (Static): The `/config` relative file path to the PEM certificate used for audit logging. -- `plugins.security.audit.config.pemcert_content` (Static): The base64-encoded content of the PEM certificate used for audit logging. This is an alternative to specifying the file path with `...config.pemcert_filepath`. +- `plugins.security.audit.config.pemcert_content` (Static): The Base64-encoded content of the PEM certificate used for audit logging. This is an alternative to specifying the file path with `...config.pemcert_filepath`. -- `plugins.security.audit.config.pemtrustedcas_filepath` (Static): The `/config` relative filepath to trusted root certificate authority. +- `plugins.security.audit.config.pemtrustedcas_filepath` (Static): The `/config` relative file path to trusted root certificate authority. -- `plugins.security.audit.config.pemtrustedcas_content` (Static): The base64-encoded content of the root certificate authority. This is an alternative to `...config.pemtrustedcas_filepath`. +- `plugins.security.audit.config.pemtrustedcas_content` (Static): The Base64-encoded content of the root certificate authority. This is an alternative to `...config.pemtrustedcas_filepath`. - `plugins.security.audit.config.webhook.url` (Static): The webhook URL. @@ -180,7 +249,7 @@ The Security plugin supports the following audit log settings: - `plugins.security.audit.config.webhook.ssl.pemtrustedcas_filepath` (Static): The `/config` relative file path to trusted certificate authority against which webhook requests are verified. -- `plugins.security.audit.config.webhook.ssl.pemtrustedcas_content` (Static): The base64-encoded content of the certificate authority used to verify webhook requests. This is an alternative to `...config.pemtrustedcas_filepath`. +- `plugins.security.audit.config.webhook.ssl.pemtrustedcas_content` (Static): The Base64-encoded content of the certificate authority used to verify webhook requests. This is an alternative to `...config.pemtrustedcas_filepath`. - `plugins.security.audit.config.log4j.logger_name` (Static): A custom name for the Log4j logger. @@ -190,13 +259,23 @@ The Security plugin supports the following audit log settings: - `opendistro_security.audit.config.disabled_transport_categories` (Dynamic): A list of transport layer categories to be ignored by the logger. Valid values are `AUTHENTICATED` and `GRANTED_PRIVILEGES`. +When fine-grained access control (FGAC) is enabled, a `PUT _cluster/settings` request that updates a dynamic audit filter setting or any `plugins.security.audit.compliance.*` setting is rejected unless the caller holds a role listed in `plugins.security.restapi.roles_enabled`. This restriction is not enforced in SSL-only or security-disabled mode. The `plugins.security.audit.config.body_logging_exclusions` and `plugins.security.audit.config.action_groups.<NAME>` settings are exceptions and do not require the elevated role. + +The following table describes the audit settings that a caller can read using `GET _cluster/settings` in each mode. + +Mode | Audit settings visible in settings responses +:--- | :--- +SSL-only | Any caller can read the non-secret dynamic configuration under `plugins.security.audit.config.*` and `plugins.security.audit.compliance.*`. Credential-bearing sink settings remain hidden. +Security disabled | No `plugins.security.audit.*` settings are filtered, so sink credentials and PEM content may be visible. +FGAC | The entire `plugins.security.audit.*` subtree is filtered for all callers. This filtering is not role based. + ## Hostname verification and DNS lookup settings The Security plugin supports the following hostname verification and DNS lookup settings: -- `plugins.security.ssl.transport.enforce_hostname_verification` (Static): Whether to verify hostnames on the transport layer. Optional. Default is `true`. +- `transport.ssl.enforce_hostname_verification` (Static): Whether to verify hostnames on the transport layer. Optional. Default is `true`. -- `plugins.security.ssl.transport.resolve_hostname` (Static): Whether to resolve hostnames against DNS on the transport layer. Optional. Default is `true`. Only works if hostname verification is enabled. +- `transport.ssl.resolve_hostname` (Static): Whether to resolve hostnames against DNS on the transport layer. Optional. Default is `true`. Only works if hostname verification is enabled. For more information, see [Hostname verification and DNS lookup]({{site.url}}{{site.baseurl}}/security/configuration/tls/#advanced-hostname-verification-and-dns-lookup). @@ -222,62 +301,52 @@ The Security plugin supports the following enabled cipher and protocol settings. For more information, see [Enabled ciphers and protocols]({{site.url}}{{site.baseurl}}/security/configuration/tls/#advanced-enabled-ciphers-and-protocols). -## Key store and trust store files---transport layer TLS settings +## Keystore and truststore files---transport layer TLS settings -The Security plugin supports the following transport layer TLS key store and trust store settings: +The Security plugin supports the following transport layer TLS keystore and truststore settings: -- `plugins.security.ssl.transport.keystore_type` (Static): The type of the key store file. Optional. Valid values are `JKS` or `PKCS12/PFX`. Default is `JKS`. +- `plugins.security.ssl.transport.keystore_type` (Static): The type of the keystore file. Optional. Valid values are `JKS` or `PKCS12/PFX`. If not set, the Security plugin detects the type from the file contents. -- `plugins.security.ssl.transport.keystore_filepath` (Static): The path to the key store file, which must be under the `config` directory, specified using a relative path. Required. +- `plugins.security.ssl.transport.keystore_filepath` (Static): The path to the keystore file, which must be under the `config` directory, specified using a relative path. Required. -- `plugins.security.ssl.transport.keystore_alias` (Static): The key store alias name. Optional. Default is the first alias. +- `plugins.security.ssl.transport.keystore_alias` (Static): The keystore alias name. Optional. Default is the first alias. -- `plugins.security.ssl.transport.keystore_password` (Static): The key store password. Default is `changeit`. +- `plugins.security.ssl.transport.keystore_password` (Static): The keystore password. Default is `changeit`. -- `plugins.security.ssl.transport.truststore_type` (Static): The type of the trust store file. Optional. Valid values are `JKS` or `PKCS12/PFX`. Default is `JKS`. +- `plugins.security.ssl.transport.truststore_type` (Static): The type of the truststore file. Optional. Valid values are `JKS` or `PKCS12/PFX`. If not set, the Security plugin detects the type from the file contents. -- `plugins.security.ssl.transport.truststore_filepath` (Static): The path to the trust store file, which must be under the `config` directory, specified using a relative path. Required. +- `plugins.security.ssl.transport.truststore_filepath` (Static): The path to the truststore file, which must be under the `config` directory, specified using a relative path. Required. -- `plugins.security.ssl.transport.truststore_alias` (Static): The trust store alias name. Optional. Default is all certificates. +- `plugins.security.ssl.transport.truststore_alias` (Static): The truststore alias name. Optional. Default is all certificates. -- `plugins.security.ssl.transport.truststore_password` (Static): The trust store password. Default is `changeit`. +- `plugins.security.ssl.transport.truststore_password` (Static): The truststore password. Default is `changeit`. -For more information about key store and trust store files, see [Transport layer TLS]({{site.url}}{{site.baseurl}}/security/configuration/tls/#transport-layer-tls-1). +For more information about keystore and truststore files, see [Transport layer TLS]({{site.url}}{{site.baseurl}}/security/configuration/tls/#transport-layer-tls-1). -## Key store and trust store files---REST layer TLS settings +## Keystore and truststore files---REST layer TLS settings -The Security plugin supports the following REST layer TLS key store and trust store settings: +The Security plugin supports the following REST layer TLS keystore and truststore settings: - `plugins.security.ssl.http.enabled` (Static): Whether to enable TLS on the REST layer. If enabled, only HTTPS is allowed. Optional. Default is `false`. -- `plugins.security.ssl.http.keystore_type` (Static): The type of the key store file. Optional. Valid values are `JKS` or `PKCS12/PFX`. Default is `JKS`. +- `plugins.security.ssl.http.keystore_type` (Static): The type of the keystore file. Optional. Valid values are `JKS` or `PKCS12/PFX`. If not set, the Security plugin detects the type from the file contents. -- `plugins.security.ssl.http.keystore_filepath` (Static): The path to the key store file, which must be under the `config` directory, specified using a relative path. Required. +- `plugins.security.ssl.http.keystore_filepath` (Static): The path to the keystore file, which must be under the `config` directory, specified using a relative path. Required. -- `plugins.security.ssl.http.keystore_alias` (Static): The key store alias name. Optional. Default is the first alias. +- `plugins.security.ssl.http.keystore_alias` (Static): The keystore alias name. Optional. Default is the first alias. -- `plugins.security.ssl.http.keystore_password`: The key store password. Default is `changeit`. +- `plugins.security.ssl.http.keystore_password`: The keystore password. Default is `changeit`. -- `plugins.security.ssl.http.truststore_type`: The type of the trust store file. Optional. Valid values are `JKS` or `PKCS12/PFX`. Default is `JKS`. +- `plugins.security.ssl.http.truststore_type`: The type of the truststore file. Optional. Valid values are `JKS` or `PKCS12/PFX`. If not set, the Security plugin detects the type from the file contents. -- `plugins.security.ssl.http.truststore_filepath`: The path to the trust store file, which must be under the `config` directory, specified using a relative path. Required. +- `plugins.security.ssl.http.truststore_filepath`: The path to the truststore file, which must be under the `config` directory, specified using a relative path. Required. -- `plugins.security.ssl.http.truststore_alias` (Static): The trust store alias name. Optional. Default is all certificates. +- `plugins.security.ssl.http.truststore_alias` (Static): The truststore alias name. Optional. Default is all certificates. -- `plugins.security.ssl.http.truststore_password` (Static): The trust store password. Default is `changeit`. +- `plugins.security.ssl.http.truststore_password` (Static): The truststore password. Default is `changeit`. For more information, see [REST layer TLS]({{site.url}}{{site.baseurl}}/security/configuration/tls/#rest-layer-tls-1). -## OpenSSL settings - -The Security plugin supports the following OpenSSL settings: - -- `plugins.security.ssl.transport.enable_openssl_if_available` (Static): Enables OpenSSL on the transport layer if available. Optional. Default is `true`. - -- `plugins.security.ssl.http.enable_openssl_if_available` (Static): Enables OpenSSL on the REST layer if available. Optional. Default is `true`. - -For more information, see [OpenSSL]({{site.url}}{{site.baseurl}}/security/configuration/tls/#advanced-openssl). - ## X.509 PEM certificates and PKCS #8 keys---transport layer TLS settings The Security plugin supports the following transport layer TLS settings related to X.509 PEM certificates and PKCS #8 keys: @@ -316,17 +385,17 @@ The Security plugin supports the following transport layer security settings: - `plugins.security.ssl.transport.client.pemkey_password` (Static): The password for the PEM-formatted private key used by the transport client. -- `plugins.security.ssl.transport.keystore_keypassword` (Static): The password for the key inside the key store. +- `plugins.security.ssl.transport.keystore_keypassword` (Static): The password for the key inside the keystore. -- `plugins.security.ssl.transport.server.keystore_keypassword` (Static): The password for the key inside the server key store. +- `plugins.security.ssl.transport.server.keystore_keypassword` (Static): The password for the key inside the server keystore. -- `plugins.sercurity.ssl.transport.server.keystore_alias` (Static): The alias name for the key store of the server. +- `plugins.sercurity.ssl.transport.server.keystore_alias` (Static): The alias name for the keystore of the server. -- `plugins.sercurity.ssl.transport.client.keystore_alias` (Static): The alias name for the key store of the client. +- `plugins.sercurity.ssl.transport.client.keystore_alias` (Static): The alias name for the keystore of the client. -- `plugins.sercurity.ssl.transport.server.truststore_alias` (Static): The alias name for the trust store of the server. +- `plugins.sercurity.ssl.transport.server.truststore_alias` (Static): The alias name for the truststore of the server. -- `plugins.sercurity.ssl.transport.client.truststore_alias` (Static): The alias name for the trust store of the client. +- `plugins.sercurity.ssl.transport.client.truststore_alias` (Static): The alias name for the truststore of the client. - `plugins.security.ssl.client.external_context_id` (Static): Provides the transport client an ID to use for an external SSL context. @@ -344,7 +413,9 @@ The Security plugin supports the following transport layer security settings: - `plugins.security.ssl.http.crl.disable_crldp` (Static): Disables CRL endpoints in certificates. Default is `false` (CRL endpoints are enabled). -- `plugins.security.ssl.allow_client_initiated_renegotiation` (Static): Enables or disables client renegotiation. Default is `false` (client initiated renegotiation is not allowed). +- `plugins.security.ssl.allow_client_initiated_renegotiation` (Static): Enables or disables client renegotiation. Default is `false` (client initiated renegotiation is not allowed). + +- `plugins.security_config.ssl_dual_mode_enabled` (Static): Enables dual-mode SSL, allowing a node to accept both encrypted (TLS) and non-encrypted traffic on the transport layer. When set to `true`, nodes can communicate with other nodes using either SSL or non-SSL connections. This setting is designed for transitional scenarios, such as migrating a cluster from having security disabled to having security enabled through a rolling restart process. This setting should not be used indefinitely in production environments. Use it only temporarily during the migration, and disable it once all nodes in the cluster are using the same security configuration. Default is `false`. ## Security plugin settings examples @@ -353,13 +424,14 @@ The Security plugin supports the following transport layer security settings: plugins.security.nodes_dn: - "CN=*.example.com, OU=SSL, O=Test, L=Test, C=DE" - "CN=node.other.com, OU=SSL, O=Test, L=Test, C=DE" + - "CN=node.example.com, OU=SSL\\, Inc., L=Test, C=DE" # escape additional comma with `\\` plugins.security.authcz.admin_dn: - CN=kirk,OU=client,O=client,L=test, C=de plugins.security.roles_mapping_resolution: MAPPING_ONLY plugins.security.ssl.transport.pemcert_filepath: esnode.pem plugins.security.ssl.transport.pemkey_filepath: esnode-key.pem plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem -plugins.security.ssl.transport.enforce_hostname_verification: false +transport.ssl.enforce_hostname_verification: false plugins.security.ssl.http.enabled: true plugins.security.ssl.http.pemcert_filepath: esnode.pem plugins.security.ssl.http.pemkey_filepath: esnode-key.pem @@ -383,7 +455,7 @@ plugins.security.cache.ttl_minutes: 60 # # REST Management API configuration settings plugins.security.restapi.roles_enabled: ["all_access","xyz_role"] -plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"] # Alternative example: plugins.security.restapi.endpoints_disabled.xyz_role.LICENSE: ["DELETE"] # +plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"] # Alternative example: plugins.security.restapi.endpoints_disabled.xyz_role.INTERNALUSERS: ["DELETE"] # # Audit log configuration settings plugins.security.audit.enable_rest: true plugins.security.audit.enable_transport: false @@ -397,7 +469,7 @@ plugins.security.audit.type: internal_opensearch # # external_opensearch settings plugins.security.audit.config.http_endpoints: ['localhost:9200','localhost:9201','localhost:9202'] -plugins.security.audit.config.index: "'auditlog6-'2023.06.15" +plugins.security.audit.config.index: "'security-auditlog-'2023.06.15" plugins.security.audit.config.type: auditlog plugins.security.audit.config.username: auditloguser plugins.security.audit.config.password: auditlogpassword diff --git a/_install-and-configure/configuring-opensearch/thread-pool-settings.md b/_install-and-configure/configuring-opensearch/thread-pool-settings.md new file mode 100644 index 00000000..19842ab9 --- /dev/null +++ b/_install-and-configure/configuring-opensearch/thread-pool-settings.md @@ -0,0 +1,148 @@ +--- +layout: default +title: Thread pool settings +parent: Configuring OpenSearch +nav_order: 110 +--- + +# Thread pool settings + +OpenSearch uses several thread pools to manage memory consumption and handle different types of operations efficiently. Thread pools can be configured to optimize performance based on your cluster's workload patterns. + +To learn how to apply these settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +## Node processor settings + +OpenSearch automatically detects the number of available processors and configures thread pools accordingly. You can override this detection: + +- `node.processors` (Static, integer): Explicitly sets the number of processors that OpenSearch should use for thread pool sizing calculations. This is useful when running multiple OpenSearch instances on the same host or when the automatic processor detection is incorrect. When set, thread pool sizes are calculated based on this value instead of the detected processor count. Default is the number of automatically detected processors. + +## Thread pool types + +OpenSearch supports the following thread pool types. Each type supports different parameters. + +### Fixed thread pools + +Fixed thread pools maintain a constant number of threads and use a queue for pending requests. + +OpenSearch supports the following fixed thread pools: + +- `get`: For document retrieval operations (fixed type) +- `analyze`: For Analyze API requests (fixed type) +- `write`: For indexing, deletion, update, and bulk operations (fixed type) +- `force_merge`: For force merge operations (fixed type) +- `search`: For search operations (fixed type) +- `search_throttled`: For throttled search operations (fixed type) + +Fixed thread pools support the following settings: + +- `thread_pool.<pool_name>.size` (Static, integer): Sets the number of threads in the thread pool. The thread count remains constant regardless of workload. + +- `thread_pool.<pool_name>.queue_size` (Static, integer): Controls the size of the queue for pending requests when all threads are busy. Set to `-1` for unbounded queues. When the queue is full, new requests are rejected. Default varies by thread pool type. + +### Scaling thread pools + +Scaling thread pools dynamically adjust the number of threads based on workload. + +OpenSearch supports the following scaling thread pools: + +- `generic`: For general background operations like node discovery (scaling type) +- `snapshot`: For snapshot and restore operations (scaling type) +- `warmer`: For index warming operations (scaling type) +- `refresh`: For index refresh operations (scaling type) +- `flush`: For `flush` and `fsync` operations (scaling type) +- `management`: For cluster management operations (scaling type) +- `fetch_shard_started`: For shard state operations (scaling type) +- `fetch_shard_store`: For shard store operations (scaling type) + +Scaling thread pools support the following settings: + +- `thread_pool.<pool_name>.core` (Static, integer): Sets the minimum number of threads to keep in the pool, even when idle. + +- `thread_pool.<pool_name>.max` (Static, integer): Sets the maximum number of threads that can be created in the pool. + +- `thread_pool.<pool_name>.keep_alive` (Static, time unit): Determines how long idle threads are kept in the pool before being terminated. Threads above the core size are terminated after this period of inactivity. + +### Fork-join thread pool +**Introduced 3.2** +{: .label .label-purple } + +Fork-join thread pools use the Java `ForkJoinPool` to provide efficient parallelism for workloads that benefit from work stealing and task splitting. This is useful for compute-intensive operations. In OpenSearch, fork-join thread pools support features that rely on parallel computation, such as the [`opensearch-jvector` plugin]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/opensearch-jvector/), which accelerates index builds. + +Fork-join thread pools support the following settings: + +- `thread_pool.<pool_name>.parallelism` (Static, integer): Sets the target parallelism level (number of worker threads) for the pool. Typically, this value matches the number of available processors but can be tuned for specific workloads. +- `thread_pool.<pool_name>.async_mode` (Static, Boolean): If set to `true`, uses the asynchronous mode for fork-join pool scheduling. +- `thread_pool.<pool_name>.queue_size` (Static, integer): Sets the size of the submission queue for tasks. Set this value to `-1` for unbounded queue size. + + +## Example configurations + +To configure a fixed thread pool, update the configuration file as follows: + +```yaml +thread_pool: + write: + size: 30 + queue_size: 1000 +``` +{% include copy.html %} + +To configure a scaling thread pool, update the configuration file as follows: + +```yaml +thread_pool: + warmer: + core: 1 + max: 8 + keep_alive: 2m +``` +{% include copy.html %} + +To configure a fork-join thread pool, update the configuration file as follows: + +```yaml +thread_pool: + fork_join: + parallelism: 8 +``` +{% include copy.html %} + +To set a custom processor count, update the configuration file as follows: + +```yaml +node.processors: 8 +``` +{% include copy.html %} + +## Thread pool timing settings + +OpenSearch supports the following thread pool timing settings: + +- `thread_pool.estimated_time_interval` (Static, time unit): Sets the time interval for updating cached time values used by thread pools and other time-sensitive operations. This setting controls how frequently OpenSearch updates its internal time cache to reduce the overhead of frequent system time calls. A smaller interval provides more accurate time measurements but increases CPU overhead from more frequent time updates. Setting this to `0` disables caching and calls system time directly on each request (typically used for testing). Default is `200ms`. Minimum is `0ms`. + +## Cluster-level thread pool settings + +OpenSearch supports cluster-level dynamic settings that allow you to override thread pool configurations across all nodes in the cluster: + +- `cluster.thread_pool.generic.max` (Dynamic, integer): Sets the maximum size of the generic thread pool across all nodes in the cluster. This overrides the default thread pool configuration specified in `opensearch.yml`. The generic thread pool handles lightweight operations and background tasks. Use this setting to dynamically adjust thread pool sizes without restarting nodes. + +- `cluster.thread_pool.snapshot.max` (Dynamic, integer): Sets the maximum size of the snapshot thread pool across all nodes in the cluster. This overrides the default thread pool configuration for snapshot operations. The snapshot thread pool handles snapshot creation and restoration operations. Use this setting to adjust snapshot concurrency during high-load periods. + +- `cluster.thread_pool.<fixed-threadpool>.size` (Dynamic, integer): Controls the sizes of both the fixed and resizable queue thread pools. Overrides the defaults provided in `opensearch.yml`. + +- `cluster.thread_pool.<scaling-threadpool>.max` (Dynamic, integer): Sets the maximum size of the scaling thread pool. Overrides the default provided in `opensearch.yml`. + +- `cluster.thread_pool.<scaling-threadpool>.core` (Dynamic, integer): Specifies the core size of the scaling thread pool. Overrides the default provided in `opensearch.yml`. + +Before tuning thread pool settings dynamically, note that these are expert-level settings that can potentially destabilize your cluster. Modifying thread pool settings applies the same thread pool size to all nodes, so it's not recommended for clusters with different hardware for the same roles. Similarly, avoid tuning thread pools shared by both data nodes and cluster manager nodes. After making these changes, we recommend monitoring your cluster to ensure that it remains stable and performs as expected. +{: .warning} + +## Best practices + +When updating thread pool settings, follow these best practices: + +- Monitor thread pool usage: Use the [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/) to monitor thread pool metrics. +- Avoid over-provisioning: Setting thread pool sizes too high can lead to memory pressure and context switching overhead. +- Consider workload patterns: Adjust thread pool sizes based on your cluster's specific read/write patterns. +- Test configuration changes: Always test thread pool modifications in a non-production environment first. \ No newline at end of file diff --git a/_install-and-configure/index.md b/_install-and-configure/index.md index 4fedacfd..b0256b85 100644 --- a/_install-and-configure/index.md +++ b/_install-and-configure/index.md @@ -1,6 +1,6 @@ --- layout: default -title: Install and upgrade OpenSearch +title: Install and configure OpenSearch nav_order: 1 has_children: false has_toc: false @@ -10,26 +10,45 @@ redirect_from: - /install-and-configure/index/ --- -# Install and upgrade OpenSearch +# Install and configure OpenSearch -OpenSearch and OpenSearch Dashboards are available on any compatible host that supports Docker (such as Linux, MacOS, or Windows). Additionally, you can install both products on various Linux distributions and on Windows. +You can install OpenSearch and OpenSearch Dashboards in containers, on Kubernetes, on Linux hosts, or on Windows. After installation, configure the cluster for your deployment and install any additional plugins that you need. -[Download OpenSearch](https://opensearch.org/downloads.html) for your preferred platform and then choose one of the following installation guides. +## Trying OpenSearch -| OpenSearch | OpenSearch Dashboards | +To try OpenSearch on your computer, see [Installation quickstart]({{site.url}}{{site.baseurl}}/getting-started/quickstart/). The quickstart starts OpenSearch and OpenSearch Dashboards using Docker Compose and is intended for testing, not for production. + +## Before installation + +Before you install OpenSearch, review the following information: + +- The host requirements and important settings in [Installing OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/) +- The supported operating systems in [Compatible operating systems]({{site.url}}{{site.baseurl}}/install-and-configure/os-comp/) + +## Choosing an installation method + +The following table lists the installation methods and links to the installation guides for each product. The OpenSearch Kubernetes Operator and the Ansible playbook install OpenSearch and OpenSearch Dashboards together, so each has one guide. + +| Method | Installation guides | | :--- | :--- | -| [Docker]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/) | [Docker]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/docker/) | -| [Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/) | [Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/helm/) | -| [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/) | [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tar/) | -| [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/) | [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/rpm/) | -| [Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/debian/) | [Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/debian/) | -| [Ansible playbook]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/ansible/) | | -| [Windows]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/windows/) | [Windows]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/windows/) | +| Docker | [OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/), [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/docker/) | +| OpenSearch Kubernetes Operator | [OpenSearch and OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/) | +| Helm | [OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/), [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/helm/) | +| Debian | [OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/debian/), [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/debian/) | +| RPM | [OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/), [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/rpm/) | +| Tarball | [OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/), [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tar/) | +| Ansible playbook | [OpenSearch and OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/ansible/) | +| Windows | [OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/windows/), [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/windows/) | -After you've installed OpenSearch, learn about [configuring]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) it for your deployment. +## After installation -For more information about upgrading your OpenSearch cluster, see the [upgrade guide]({{site.url}}{{site.baseurl}}/install-and-configure/upgrade-opensearch/index/). +After you install OpenSearch, use the following guides to set up your deployment: -For information about upgrade tools, see [OpenSearch upgrade, migration, and comparison tools]({{site.url}}{{site.baseurl}}/tools/index/#opensearch-upgrade-migration-and-comparison-tools). +- [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) +- [Configuring OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-dashboards/) +- [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) +- [Managing OpenSearch Dashboards plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/plugins/) -For plugin installation, see [Installing plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). \ No newline at end of file +## Related documentation + +- To upgrade an existing cluster, see [Migrate or upgrade]({{site.url}}{{site.baseurl}}/migrate-or-upgrade/). diff --git a/_install-and-configure/install-dashboards/debian.md b/_install-and-configure/install-dashboards/debian.md index 43720492..0ff67e99 100644 --- a/_install-and-configure/install-dashboards/debian.md +++ b/_install-and-configure/install-dashboards/debian.md @@ -2,132 +2,325 @@ layout: default title: Debian parent: Installing OpenSearch Dashboards -nav_order: 33 +nav_order: 20 --- -# Installing OpenSearch Dashboards (Debian) +{% comment %} +The following liquid syntax declares a variable, major_version_mask, which is transformed into "N.x" where "N" is the major version number. This is required for proper versioning references to the Yum repo. +{% endcomment %} +{% assign version_parts = site.opensearch_major_minor_version | split: "." %} +{% assign major_version_mask = version_parts[0] | append: ".x" %} + +# Installing OpenSearch Dashboards on Debian Installing OpenSearch Dashboards using the Advanced Packaging Tool (APT) package manager simplifies the process considerably compared to the [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tar/) method. For example, the package manager handles several technical considerations, such as the installation path, location of configuration files, and creation of a service managed by `systemd`. -Before installing OpenSearch Dashboards you must configure an OpenSearch cluster. Refer to the OpenSearch [Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/debian/) installation guide for steps. -{: .important} - This guide assumes that you are comfortable working from the Linux command line interface (CLI). You should understand how to input commands, navigate between directories, and edit text files. Some example commands reference the `vi` text editor, but you may use any text editor available. {:.note} -## Installing OpenSearch Dashboards from a package +## Prerequisites + +Install OpenSearch. For more information, see [Installing OpenSearch on Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/debian/). + +## Install OpenSearch Dashboards from a package 1. Download the Debian package for the desired version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. The Debian package can be downloaded for both **x64** and **arm64** architectures. 1. From the CLI, install using `dpkg`. + + x64: ```bash - # x64 - sudo dpkg -i opensearch-dashboards-{{site.opensearch_version}}-linux-x64.deb - # arm64 - sudo dpkg -i opensearch-dashboards-{{site.opensearch_version}}-linux-arm64.deb + sudo dpkg -i opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb ``` -1. After the installation completes, reload the systemd manager configuration. + {% include copy.html %} + + arm64: + ```bash + sudo dpkg -i opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-arm64.deb + ``` + {% include copy.html %} + + For new installations of OpenSearch Dashboards 3.7 and later, you can disable the Security Dashboards plugin by adding the `DISABLE_SECURITY_DASHBOARDS_PLUGIN=true` environment variable before the installation command with the `env` keyword: + ```bash + sudo env DISABLE_SECURITY_DASHBOARDS_PLUGIN=true dpkg -i opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb + ``` + {% include copy.html %} + +1. After the installation completes, reload the `systemd` manager configuration: ```bash sudo systemctl daemon-reload ``` -1. Enable OpenSearch as a service. + {% include copy.html %} + +1. Enable OpenSearch Dashboards as a service: ```bash sudo systemctl enable opensearch-dashboards ``` -1. Start the OpenSearch service. + {% include copy.html %} + +1. Start the OpenSearch Dashboards service: ```bash sudo systemctl start opensearch-dashboards ``` -1. Verify that OpenSearch launched correctly. + {% include copy.html %} + +1. Verify that OpenSearch Dashboards launched correctly: ```bash sudo systemctl status opensearch-dashboards ``` + {% include copy.html %} + +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). ### Fingerprint verification The Debian package is not signed. If you would like to verify the fingerprint, the OpenSearch Project provides a `.sig` file as well as the `.deb` package for use with GNU Privacy Guard (GPG). -1. Download the desired Debian package. +1. Download the desired Debian package: ```bash - curl -SLO https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_version}}/opensearch-dashboards-{{site.opensearch_version}}-linux-x64.deb - ``` -1. Download the corresponding signature file. - ```bash - curl -SLO https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_version}}/opensearch-dashboards-{{site.opensearch_version}}-linux-x64.deb.sig - ``` -1. Download and import the GPG key. - ```bash - curl -o- https://artifacts.opensearch.org/publickeys/opensearch.pgp | gpg --import - - ``` -1. Verify the signature. - ```bash - gpg --verify opensearch-dashboards-{{site.opensearch_version}}-linux-x64.deb.sig opensearch-dashboards-{{site.opensearch_version}}-linux-x64.deb + curl -SLO https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_dashboards_version}}/opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb ``` + {% include copy.html %} -## Installing OpenSearch Dashboards from an APT repository +1. Download the corresponding signature file: + ```bash + curl -SLO https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_dashboards_version}}/opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb.sig + ``` + {% include copy.html %} + +1. Download and import the GPG key: + ```bash + curl -o- https://artifacts.opensearch.org/publickeys/opensearch-release.pgp | gpg --import - + ``` + {% include copy.html %} + +1. Verify the signature: + ```bash + gpg --verify opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb.sig opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb + ``` + {% include copy.html %} + +## Install OpenSearch Dashboards from an APT repository APT, the primary package management tool for Debian–based operating systems, allows you to download and install the Debian package from the APT repository. -1. Install the necessary packages. +1. Install the necessary packages: ```bash sudo apt-get update && sudo apt-get -y install lsb-release ca-certificates curl gnupg2 ``` + {% include copy.html %} + +1. Create the keyrings directory if it doesn't already exist: + ```bash + sudo mkdir -p /etc/apt/keyrings + ``` + {% include copy.html %} + 1. Import the public GPG key. This key is used to verify that the APT repository is signed. ```bash - curl -o- https://artifacts.opensearch.org/publickeys/opensearch.pgp | sudo gpg --dearmor --batch --yes -o /usr/share/keyrings/opensearch-keyring + curl -o- https://artifacts.opensearch.org/publickeys/opensearch-release.pgp | sudo gpg --dearmor --batch --yes -o /etc/apt/keyrings/opensearch-release-keyring ``` -1. Create an APT repository for OpenSearch. + {% include copy.html %} + +1. Create an APT repository for OpenSearch Dashboards: ```bash - echo "deb [signed-by=/usr/share/keyrings/opensearch-keyring] https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/2.x/apt stable main" | sudo tee /etc/apt/sources.list.d/opensearch-dashboards-2.x.list + echo "deb [signed-by=/etc/apt/keyrings/opensearch-release-keyring] https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{major_version_mask}}/apt stable main" | sudo tee /etc/apt/sources.list.d/opensearch-dashboards-{{major_version_mask}}.list ``` -1. Verify that the repository was created successfully. + {% include copy.html %} + +1. Verify that the repository was created successfully: ```bash sudo apt-get update ``` -1. With the repository information added, list all available versions of OpenSearch: + {% include copy.html %} + +1. (Optional) As of May 22, 2024, the `Origin` and `Label` values of the APT repository were updated as part of [this change](https://github.com/opensearch-project/opensearch-build/issues/4485). If you created the APT repository before this date, run the following command to accept the updated release information: + ```bash + sudo apt-get update --allow-releaseinfo-change + ``` + {% include copy.html %} + +1. With the repository information added, list all available versions of OpenSearch Dashboards: ```bash sudo apt list -a opensearch-dashboards ``` -1. Choose the version of OpenSearch you want to install: - - Unless otherwise indicated, the latest available version of OpenSearch is installed. + {% include copy.html %} + +1. Choose the version of OpenSearch Dashboards you want to install: + - Unless otherwise indicated, the latest available version of OpenSearch Dashboards is installed: ```bash sudo apt-get install opensearch-dashboards ``` - - To install a specific version of OpenSearch Dashboards, pass a version number after the package name. + {% include copy.html %} + + - To install a specific version of OpenSearch Dashboards, pass a version number after the package name: ```bash - # Specify the version manually using opensearch=<version> - sudo apt-get install opensearch-dashboards={{site.opensearch_version}} + sudo apt-get install opensearch-dashboards={{site.opensearch_dashboards_version}} ``` -1. Once complete, enable OpenSearch. + {% include copy.html %} + +1. Once complete, enable OpenSearch Dashboards: ```bash sudo systemctl enable opensearch-dashboards ``` -1. Start OpenSearch. + {% include copy.html %} + +1. Start OpenSearch Dashboards: ```bash sudo systemctl start opensearch-dashboards ``` -1. Verify that OpenSearch launched correctly. + {% include copy.html %} + +1. Verify that OpenSearch Dashboards launched correctly: ```bash sudo systemctl status opensearch-dashboards ``` + {% include copy.html %} -## Exploring OpenSearch Dashboards +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + +## (Optional) Allow access from other hosts By default, OpenSearch Dashboards, like OpenSearch, binds to `localhost` when you initially install it. As a result, OpenSearch Dashboards is not reachable from a remote host unless the configuration is updated. -1. Open `opensearch_dashboards.yml`. +1. Open `opensearch_dashboards.yml`: ```bash sudo vi /etc/opensearch-dashboards/opensearch_dashboards.yml ``` -1. Specify a network interface that OpenSearch Dashboards should bind to. - ```bash - # Use 0.0.0.0 to bind to any available interface. + {% include copy.html %} + +1. Specify a network interface that OpenSearch Dashboards should bind to. Use `0.0.0.0` to bind to any available interface: + ```yaml server.host: 0.0.0.0 ``` + {% include copy.html %} + 1. Save and quit. -1. Restart OpenSearch Dashboards to apply the configuration change. +1. Restart OpenSearch Dashboards to apply the configuration change: ```bash sudo systemctl restart opensearch-dashboards ``` -1. From a web browser, navigate to OpenSearch Dashboards. The default port is 5601. -1. Log in with the default username `admin` and the default password `admin`. (For OpenSearch 2.12 and later, the password should be the custom admin password) -1. Visit [Getting started with OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/index/) to learn more. + {% include copy.html %} + +## Upgrade to a newer version + +OpenSearch Dashboards instances installed using `dpkg` or `apt-get` can be upgraded to a newer version. + +Upgrade your OpenSearch cluster before you upgrade OpenSearch Dashboards. OpenSearch Dashboards must run the same version as the cluster it connects to, and installed plugins must match that version. For more information, see [Plugin compatibility]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/plugins/#plugin-compatibility). +{: .important} + +### Prepare the host for an upgrade + +The `opensearch-dashboards` package declares no dependencies on other Debian packages. An upgrade that fails with unresolved dependencies therefore points to the APT configuration on the host rather than to OpenSearch Dashboards itself. Complete the following steps before you run an upgrade command. + +1. Install the packages that APT needs in order to read the OpenSearch Dashboards repository over HTTPS: + ```bash + sudo apt-get update && sudo apt-get -y install lsb-release ca-certificates curl gnupg2 + ``` + {% include copy.html %} + +1. Back up your configuration. The package registers the following files as configuration files, and `dpkg` prompts you to keep or replace each one that you edited: + + - `/etc/opensearch-dashboards/opensearch_dashboards.yml` + - `/etc/opensearch-dashboards/node.options` + - `/etc/default/opensearch-dashboards` + - `/etc/init.d/opensearch-dashboards` + + To back up the main configuration file, run the following command: + ```bash + sudo cp /etc/opensearch-dashboards/opensearch_dashboards.yml /etc/opensearch-dashboards/opensearch_dashboards.yml.bak + ``` + {% include copy.html %} + + Run the upgrade from an interactive shell so that you can respond to these prompts. An unattended upgrade either stops at the prompt or applies the default answer configured in `Dpkg::Options` on the host. + {: .note} + +1. Refresh the package lists and confirm that a newer version is available: + ```bash + sudo apt-get update && sudo apt list -a opensearch-dashboards + ``` + {% include copy.html %} + + If `apt-get update` reports that a public key is unavailable, or if the newest version listed is the version that you already have, see [Upgrade across major versions](#upgrade-across-major-versions). + +### Upgrade manually using `dpkg` + +Download the Debian package for the desired upgrade version directly from the [OpenSearch Project downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. + +Navigate to the directory containing the distribution and run the following command: + +```bash +sudo dpkg -i opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.deb +``` +{% include copy.html %} + +This method reads the package file directly and does not use an APT repository, so it also upgrades across major versions. +{: .tip} + +### Upgrade using `apt-get` + +To upgrade to the newest available version of OpenSearch Dashboards, run the following command: + +```bash +sudo apt-get install --only-upgrade opensearch-dashboards +``` +{% include copy.html %} + +You can also upgrade to a specific OpenSearch Dashboards version by providing the version number: + +```bash +sudo apt-get install opensearch-dashboards=<version> +``` +{% include copy.html %} + +The `apt-get upgrade` subcommand acts on every installed package on the host and cannot install or remove packages, so an unrelated package that APT holds back stops the OpenSearch Dashboards upgrade. The `--only-upgrade` option limits the operation to the `opensearch-dashboards` package. +{: .note} + +### Upgrade across major versions + +The repository definition that you create during installation is pinned to one major version, so APT reports no newer version when you try to move to a different major version. The repositories for different major versions are also signed with different GPG keys, so APT reports a missing public key when it reads the new repository using your existing keyring. + +1. Import the public GPG key for the new repository: + ```bash + curl -o- https://artifacts.opensearch.org/publickeys/opensearch-release.pgp | sudo gpg --dearmor --batch --yes -o /etc/apt/keyrings/opensearch-release-keyring + ``` + {% include copy.html %} + + Repositories for OpenSearch Dashboards 2.x are signed with the key published at `https://artifacts.opensearch.org/publickeys/opensearch.pgp`. Leave the keyring for that key in place until you remove the 2.x repository definition. Otherwise, `apt-get update` fails while reading the 2.x repository. + {: .note} + +1. Add the repository for the new major version: + ```bash + echo "deb [signed-by=/etc/apt/keyrings/opensearch-release-keyring] https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{major_version_mask}}/apt stable main" | sudo tee /etc/apt/sources.list.d/opensearch-dashboards-{{major_version_mask}}.list + ``` + {% include copy.html %} + +1. Remove the repository definition for your previous major version, replacing `<previous-major-version>` with a value such as `2.x`: + ```bash + sudo rm /etc/apt/sources.list.d/opensearch-dashboards-<previous-major-version>.list + ``` + {% include copy.html %} + +1. Refresh the package lists and confirm that the new version appears: + ```bash + sudo apt-get update && sudo apt list -a opensearch-dashboards + ``` + {% include copy.html %} + +1. Install the new version: + ```bash + sudo apt-get install opensearch-dashboards=<version> + ``` + {% include copy.html %} + +### Automatically restart the service after a package upgrade + +To automatically restart OpenSearch Dashboards after a package upgrade, enable the `opensearch-dashboards.service` through `systemd`: + +```bash +sudo systemctl enable opensearch-dashboards.service +``` +{% include copy.html %} + +## Related documentation + +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-dashboards/docker.md b/_install-and-configure/install-dashboards/docker.md index aa9ca1d5..ace03f22 100644 --- a/_install-and-configure/install-dashboards/docker.md +++ b/_install-and-configure/install-dashboards/docker.md @@ -2,25 +2,65 @@ layout: default title: Docker parent: Installing OpenSearch Dashboards -nav_order: 1 +nav_order: 5 redirect_from: - /dashboards/install/docker/ - /opensearch/install/docker-security/ --- -# Run OpenSearch Dashboards using Docker +# Installing OpenSearch Dashboards using Docker -You *can* start OpenSearch Dashboards using `docker run` after [creating a Docker network](https://docs.docker.com/engine/reference/commandline/network_create/) and starting OpenSearch, but the process of connecting OpenSearch Dashboards to OpenSearch is significantly easier with a Docker Compose file. +You can use either Docker or Docker Compose to run OpenSearch Dashboards. The Docker Compose method is easier because the sample Compose file starts OpenSearch and OpenSearch Dashboards together. -1. Run `docker pull opensearchproject/opensearch-dashboards:2`. +## Prerequisites -1. Create a [`docker-compose.yml`](https://docs.docker.com/compose/compose-file/) file appropriate for your environment. A sample file that includes OpenSearch Dashboards is available on the OpenSearch [Docker installation page]({{site.url}}{{site.baseurl}}/opensearch/install/docker#sample-docker-composeyml). +Install OpenSearch using Docker. For more information, see [Installing OpenSearch using Docker]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/). - Just like `opensearch.yml`, you can pass a custom `opensearch_dashboards.yml` to the container in the Docker Compose file. - {: .tip } +## Install OpenSearch Dashboards using Docker -1. Run `docker-compose up`. +If you have defined your network using `docker network create os-net` and started OpenSearch using the following command: - Wait for the containers to start. Then see the [OpenSearch Dashboards documentation]({{site.url}}{{site.baseurl}}/dashboards/index/). +```bash +docker run -d --name opensearch-node -p 9200:9200 --network os-net -e "discovery.type=single-node" -e "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<admin_password>" opensearchproject/opensearch:latest +``` +{% include copy.html %} -1. When finished, run `docker-compose down`. +Then you can start OpenSearch Dashboards using the following steps: + +1. Start OpenSearch Dashboards, specifying the OpenSearch container name in the `OPENSEARCH_HOSTS` environment variable: + + ```bash + docker run -d --name osd \ + --network os-net \ + -p 5601:5601 \ + -e 'OPENSEARCH_HOSTS=["https://opensearch-node:9200"]' \ + opensearchproject/opensearch-dashboards:latest + ``` + {% include copy.html %} + +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + +## Install OpenSearch Dashboards using Docker Compose + +The [sample `docker-compose.yml`]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/#sample-docker-composeyml) file includes an `opensearch-dashboards` service, so OpenSearch Dashboards starts together with OpenSearch. When you [deploy the cluster using Docker Compose]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/#deploy-an-opensearch-cluster-using-docker-compose), no additional steps are required to install OpenSearch Dashboards. + +In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + +## Customizing the OpenSearch Dashboards configuration + +The OpenSearch Dashboards image includes a default `opensearch_dashboards.yml` file that works with the demo security configuration, so most deployments don't need to change it. To change a setting, pass it as an environment variable. The variable name is the setting name in uppercase, with dots replaced by underscores. For example, `OPENSEARCH_HOSTS` sets `opensearch.hosts`, and `OPENSEARCH_REQUESTTIMEOUT` sets `opensearch.requestTimeout`. + +When using `docker run`, pass the variables with the `-e` option. When using Docker Compose, add the variables to the `environment` section of the `opensearch-dashboards` service: + +```yaml +opensearch-dashboards: + environment: + OPENSEARCH_HOSTS: '["https://opensearch-node1:9200","https://opensearch-node2:9200"]' + OPENSEARCH_REQUESTTIMEOUT: 60000 +``` + +Not every setting can be passed as an environment variable. To use settings that aren't supported as environment variables, create your own `opensearch_dashboards.yml` file and mount it in the container, replacing the default file. Because the mounted file replaces the default file entirely, it must contain every setting that OpenSearch Dashboards needs, including `opensearch.hosts` and the connection credentials. For an example, see [Complete Docker Compose example with custom configuration]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/#complete-docker-compose-example-with-custom-configuration). + +## Related documentation + +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-dashboards/helm.md b/_install-and-configure/install-dashboards/helm.md index 58ca995c..47baf009 100644 --- a/_install-and-configure/install-dashboards/helm.md +++ b/_install-and-configure/install-dashboards/helm.md @@ -2,16 +2,16 @@ layout: default title: Helm parent: Installing OpenSearch Dashboards -nav_order: 35 +nav_order: 15 redirect_from: - /dashboards/install/helm/ --- -# Run OpenSearch Dashboards using Helm +# Installing OpenSearch Dashboards using Helm Helm is a package manager that allows you to easily install and manage OpenSearch Dashboards in a Kubernetes cluster. You can define your OpenSearch configurations in a YAML file and use Helm to deploy your applications in a version-controlled and reproducible way. -The Helm chart contains the resources described in the following table. +The [Helm chart](https://github.com/opensearch-project/helm-charts) contains the resources described in the following table. Resource | Description :--- | :--- @@ -29,109 +29,156 @@ The instructions here assume you have a Kubernetes cluster with Helm preinstalle ## Prerequisites -Before you get started, you must first use [Helm to install OpenSearch]({{site.url}}{{site.baseurl}}/opensearch/install/helm/). +Install OpenSearch. For more information, see [Installing OpenSearch using Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/). -Make sure that you can send requests to your OpenSearch pod: - -```json -$ curl -XGET https://localhost:9200 -u 'admin:<custom-admin-password>' --insecure -{ - "name" : "opensearch-cluster-master-1", - "cluster_name" : "opensearch-cluster", - "cluster_uuid" : "hP2gq5bPS3SLp8Z7wXm8YQ", - "version" : { - "distribution" : "opensearch", - "number" : "1.0.0", - "build_type" : "tar", - "build_hash" : "34550c5b17124ddc59458ef774f6b43a086522e3", - "build_date" : "2021-07-02T23:22:21.383695Z", - "build_snapshot" : false, - "lucene_version" : "8.8.2", - "minimum_wire_compatibility_version" : "6.8.0", - "minimum_index_compatibility_version" : "6.0.0-beta1" - }, - "tagline" : "The OpenSearch Project: https://opensearch.org/" -} -``` +Before you install OpenSearch Dashboards, make sure that OpenSearch is running. For more information, see [Verify the deployment]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/#verify-the-deployment). ## Install OpenSearch Dashboards using Helm -1. Change to the `opensearch-dashboards` directory: +The following steps use the `opensearch` Helm repository that you added when you installed OpenSearch. + +1. Deploy OpenSearch Dashboards. The chart's default CPU limit of `100m` is too low for OpenSearch Dashboards to start before the startup probe fails, so the following command sets the CPU request and limit to 1 CPU: ```bash - cd opensearch-dashboards + helm install my-dashboards opensearch/opensearch-dashboards \ + --set resources.requests.cpu=1 \ + --set resources.limits.cpu=1 ``` + {% include copy.html %} -1. Package the Helm chart: + To customize the deployment, pass in the values that you want to override using a custom YAML file. Include the CPU settings in the file: + + ```yaml + resources: + requests: + cpu: "1" + limits: + cpu: "1" + ``` + {% include copy.html %} + + Then deploy OpenSearch Dashboards using the custom file: ```bash - helm package . + helm install my-dashboards opensearch/opensearch-dashboards -f customvalues.yaml + ``` + {% include copy.html %} + + The output shows the deployed release: + + ```yaml + NAME: my-dashboards + LAST DEPLOYED: Fri Oct 2 02:30:49 2026 + NAMESPACE: default + STATUS: deployed + REVISION: 1 + TEST SUITE: None + NOTES: + 1. Get the application URL by running these commands: + export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/name=opensearch-dashboards,app.kubernetes.io/instance=my-dashboards" -o jsonpath="{.items[0].metadata.name}") + export CONTAINER_PORT=$(kubectl get pod --namespace default $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") + echo "Visit http://127.0.0.1:8080 to use your application" + kubectl --namespace default port-forward $POD_NAME 8080:$CONTAINER_PORT ``` -1. Deploy OpenSearch Dashboards: +After the deployment completes, follow these steps to access OpenSearch Dashboards: + +1. To ensure that your OpenSearch Dashboards pod is running, use the following command: ```bash - helm install --generate-name opensearch-dashboards-1.0.0.tgz + kubectl get pods ``` - The output shows you the specifications instantiated from the install. - To customize the deployment, pass in the values that you want to override with a custom YAML file: + {% include copy.html %} + + Wait until the OpenSearch Dashboards pod shows `1/1` in the `READY` column: ```bash - helm install --values=customvalues.yaml opensearch-dashboards-1.0.0.tgz + NAME READY STATUS RESTARTS AGE + my-dashboards-opensearch-dashboards-567b777979-xx8jj 1/1 Running 0 70s + opensearch-cluster-master-0 1/1 Running 0 3m + opensearch-cluster-master-1 1/1 Running 0 3m + opensearch-cluster-master-2 1/1 Running 0 3m ``` -#### Sample output +1. Configure port forwarding from the OpenSearch Dashboards service: -```yaml -NAME: opensearch-dashboards-1-1629223356 -LAST DEPLOYED: Tue Aug 17 18:02:37 2021 -NAMESPACE: default -STATUS: deployed -REVISION: 1 -TEST SUITE: None -NOTES: -1. Get the application URL by running these commands: - export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/name=opensearch-dashboards,app.kubernetes.io/instance=op -ensearch-dashboards-1-1629223356" -o jsonpath="{.items[0].metadata.name}") - export CONTAINER_PORT=$(kubectl get pod --namespace default $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}") - echo "Visit http://127.0.0.1:8080 to use your application" - kubectl --namespace default port-forward $POD_NAME 8080:$CONTAINER_PORT -``` + ```bash + kubectl port-forward svc/my-dashboards-opensearch-dashboards 5601 + ``` + {% include copy.html %} -To make sure your OpenSearch Dashboards pod is up and running, run the following command: - -```bash -$ kubectl get pods -NAME READY STATUS RESTARTS AGE -opensearch-cluster-master-0 1/1 Running 0 4m35s -opensearch-cluster-master-1 1/1 Running 0 4m35s -opensearch-cluster-master-2 1/1 Running 0 4m35s -opensearch-dashboards-1-1629223356-758bd8747f-8www5 1/1 Running 0 66s -``` - -To set up port forwarding to access OpenSearch Dashboards, exit the OpenSearch shell and run the following command: - -```bash -$ kubectl port-forward deployment/opensearch-dashboards-1-1629223356 5601 -``` - -You can now access OpenSearch Dashboards from your browser at: http://localhost:5601. +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + OpenSearch Dashboards can take about 1 minute after the pod is ready to finish starting. Until then, requests return a `503` error. If you receive this error, wait and then reload the page. + {: .note} ## Uninstall using Helm -To identify the OpenSearch Dashboards deployment that you want to delete: +To identify the OpenSearch Dashboards deployment that you want to delete, run the following command: ```bash -$ helm list -NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION -opensearch-1-1629223146 default 1 2021-08-17 17:59:07.664498239 +0000 UTCdeployedopensearch-1.0.0 1.0.0 -opensearch-dashboards-1-1629223356 default 1 2021-08-17 18:02:37.600796946 +0000 UTCdepl -oyedopensearch-dashboards-1.0.0 1.0.0 +helm list ``` +{% include copy.html %} -To delete or uninstall a deployment, run the following command: +The response lists the current Helm deployments: ```bash -helm delete opensearch-dashboards-1-1629223356 +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +my-dashboards default 1 2026-10-02 02:30:49.128429961 +0000 UTC deployed opensearch-dashboards-{{site.opensearch_dashboards_version}} {{site.opensearch_dashboards_version}} +my-deployment default 1 2026-10-02 02:28:00.553978943 +0000 UTC deployed opensearch-{{site.opensearch_version}} {{site.opensearch_version}} ``` + +To uninstall a deployment, run the following command: + +```bash +helm uninstall my-dashboards +``` +{% include copy.html %} + +## Common issues + +The following issues can occur when you install OpenSearch Dashboards using Helm. + +### The OpenSearch Dashboards pod restarts repeatedly and never becomes ready + +If the OpenSearch Dashboards pod shows `0/1` in the `READY` column and its `RESTARTS` count keeps increasing, the pod might not have enough CPU to start before the startup probe fails. To confirm, run the following command: + +```bash +kubectl describe pod -l app.kubernetes.io/instance=my-dashboards +``` +{% include copy.html %} + +The `Events` section of the output contains `Startup probe failed` messages and the `Container dashboards failed startup probe, will be restarted` message. To fix this issue, increase the CPU request and limit to 1 CPU: + +```bash +helm upgrade my-dashboards opensearch/opensearch-dashboards --reuse-values \ + --set resources.requests.cpu=1 \ + --set resources.limits.cpu=1 +``` +{% include copy.html %} + +The `--reuse-values` flag keeps the values that you set when you installed OpenSearch Dashboards. Without this flag, `helm upgrade` resets all values that you do not specify in the command to the chart defaults. + +### OpenSearch Dashboards returns "OpenSearch Dashboards server is not ready yet" + +If the OpenSearch Dashboards pod shows `1/1` in the `READY` column but OpenSearch Dashboards returns a `503` error with the `OpenSearch Dashboards server is not ready yet` message for more than a few minutes, OpenSearch Dashboards might not be able to reach OpenSearch. To confirm, check the OpenSearch Dashboards logs: + +```bash +kubectl logs deploy/my-dashboards-opensearch-dashboards +``` +{% include copy.html %} + +If the logs contain `ConnectionError` messages and the `Unable to retrieve version information from OpenSearch nodes` message, OpenSearch Dashboards cannot connect to the OpenSearch service. OpenSearch Dashboards connects to OpenSearch at the address specified in the `opensearchHosts` parameter, which defaults to `https://opensearch-cluster-master:9200`. If your OpenSearch service has a different name, set `opensearchHosts` to `https://<service-name>:9200`, replacing `<service-name>` with the name of your OpenSearch service: + +```bash +helm upgrade my-dashboards opensearch/opensearch-dashboards --reuse-values \ + --set opensearchHosts=https://<service-name>:9200 +``` +{% include copy.html %} + +For information about how the OpenSearch chart names the service, see [Verify the deployment]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/#verify-the-deployment). + +## Related documentation + +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-dashboards/index.md b/_install-and-configure/install-dashboards/index.md index 58c2051f..ebbb6e61 100644 --- a/_install-and-configure/install-dashboards/index.md +++ b/_install-and-configure/install-dashboards/index.md @@ -6,20 +6,49 @@ has_children: true redirect_from: - /dashboards/install/index/ - /dashboards/compatibility/ - - /install-and-configure/install-dashboards/index/ + - /install-and-configure/install-dashboards/ --- # Installing OpenSearch Dashboards -OpenSearch Dashboards provides a fully integrated solution for visually exploring, discovering, and querying your observability data. You can install OpenSearch Dashboards with any of the following options: +OpenSearch Dashboards is the user interface for OpenSearch. You can use it to explore, visualize, and query your data. You can install OpenSearch Dashboards using any of the following methods: - [Docker]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/docker/) -- [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tar/) -- [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/rpm/) -- [Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/debian/) +- [OpenSearch Kubernetes Operator]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/), which installs OpenSearch and OpenSearch Dashboards together - [Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/helm/) +- [Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/debian/) +- [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/rpm/) +- [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tar/) +- [Ansible playbook]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/ansible/), which installs OpenSearch and OpenSearch Dashboards together - [Windows]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/windows/) +OpenSearch Dashboards connects to an existing OpenSearch cluster, so install OpenSearch first. For more information, see [Installing OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/). + +## Preparing OpenSearch Dashboards for production + +The [Installation quickstart]({{site.url}}{{site.baseurl}}/getting-started/quickstart/) and the default configuration in most guides connect OpenSearch Dashboards to OpenSearch using the demo security configuration. In this configuration, OpenSearch Dashboards serves pages over HTTP, does not verify the OpenSearch certificate, and authenticates to OpenSearch using the `kibanaserver` user's known default password. Before you use OpenSearch Dashboards in production, complete the following tasks: + +- Prepare the OpenSearch cluster for production. For more information, see [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production). +- Enable TLS between browsers and OpenSearch Dashboards, and verify the OpenSearch certificate by setting `opensearch.ssl.verificationMode` to `full`. For more information, see [Configuring TLS for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tls/). +- Change the `kibanaserver` password. For more information, see [Dashboards service account password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#dashboards-service-account-password). +- Configure how users sign in. For more information, see [Configuring sign-in options]({{site.url}}{{site.baseurl}}/security/configuration/multi-auth/). + +## Accessing OpenSearch Dashboards + +After you install and start OpenSearch Dashboards, open it in a web browser: + +1. Go to `http://localhost:5601`. OpenSearch Dashboards listens on port `5601` by default. If OpenSearch Dashboards runs on a different host, replace `localhost` with the IP address or DNS name of that host. + + By default, the tarball, RPM, and Debian installations bind OpenSearch Dashboards to `localhost`, so you cannot reach it from other hosts. To allow access from other hosts, set `server.host` to `0.0.0.0` or to an IP address of the host in `opensearch_dashboards.yml` and restart OpenSearch Dashboards. + +1. Log in as the `admin` user using the custom admin password that you set when you installed OpenSearch. If you disabled the Security plugin, no login is required. + +OpenSearch Dashboards can take about 1 minute to start. If the page does not load or returns a `503` error, wait and then reload the page. + +If you cannot log in, see [Common issues](#common-issues). + +To learn how to use OpenSearch Dashboards, see [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/index/). + ## Browser compatibility OpenSearch Dashboards supports the following web browsers: @@ -31,41 +60,88 @@ OpenSearch Dashboards supports the following web browsers: Other Chromium-based browsers might work, as well. Internet Explorer and Microsoft Edge Legacy are **not** supported. +<!-- vale off --> ## Node.js compatibility +<!-- vale on --> OpenSearch Dashboards requires the Node.js runtime binary to run. One is included in the distribution packages available from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. -OpenSearch Dashboards 2.8.0 and newer can use Node.js versions 14, 16, and 18. The distribution packages for OpenSearch Dashboards 2.10.0 and newer include Node.js 18 and 14 (for backward compatibility). +OpenSearch Dashboards versions 2.8 through 2.19 support Node.js 14, 16, and 18. Distribution packages for versions 2.10 through 2.19 include Node.js 18 and Node.js 14 (for backward compatibility). + +OpenSearch Dashboards versions 3.0 through 3.4 include Node.js 20. Versions 3.5 and later include Node.js 22. To use a Node.js runtime binary other than the ones included in the distribution packages, follow these steps: -1. Download and install [Node.js](https://nodejs.org/en/download){:target='\_blank'}; the compatible versions are `>=14.20.1 <19`. -2. Set the installation path to the `NODE_HOME` or `NODE_OSD_HOME` environment variables. - - - On UNIX, if Node.js is installed to `/usr/local/nodejs` and the runtime binary is `/usr/local/nodejs/bin/node`: - ```bash - export NODE_HOME=/usr/local/nodejs - ``` +1. Download and install [Node.js](https://nodejs.org/en/download){:target='\_blank'}. The compatible versions are `>=14.20.1 <23`. +1. Set the `OSD_NODE_HOME` or `NODE_HOME` environment variable to the Node.js installation directory: - - If Node.js is installed using NVM and the runtime binary is `/Users/user/.nvm/versions/node/v18.19.0/bin/node`: - ```bash - export NODE_HOME=/Users/user/.nvm/versions/node/v18.19.0 - # or, if NODE_HOME is used for something else: - export NODE_OSD_HOME=/Users/user/.nvm/versions/node/v18.19.0 - ``` + - On Linux or macOS, if Node.js is installed to `/usr/local/nodejs` and the runtime binary is `/usr/local/nodejs/bin/node`: - - On Windows, if Node.js is installed to `C:\Program Files\nodejs` and the runtime binary is `C:\Program Files\nodejs\node.exe`: - ```powershell - set "NODE_HOME=C:\Program Files\nodejs" - # or using PowerShell: - $Env:NODE_HOME = 'C:\Program Files\nodejs' - ``` + ```bash + export NODE_HOME=/usr/local/nodejs + ``` + + - If Node.js is installed using NVM and the runtime binary is `/Users/user/.nvm/versions/node/v22.22.3/bin/node`: + + ```bash + export NODE_HOME=/Users/user/.nvm/versions/node/v22.22.3 + # or, if NODE_HOME is used for something else: + export OSD_NODE_HOME=/Users/user/.nvm/versions/node/v22.22.3 + ``` + + - On Windows, if Node.js is installed to `C:\Program Files\nodejs` and the runtime binary is `C:\Program Files\nodejs\node.exe`, use the following command in Command Prompt: + + ```bat + set "NODE_HOME=C:\Program Files\nodejs" + ``` + + Alternatively, use the following command in PowerShell: + + ```powershell + $Env:NODE_HOME = 'C:\Program Files\nodejs' + ``` Consult your operating system's documentation to make a persistent change to the environment variables. -The OpenSearch Dashboards start script,`bin/opensearch-dashboards`, searches for the Node.js runtime binary using `NODE_OSD_HOME`, -and then `NODE_HOME`, before using the binaries included with the distribution packages. If a usable Node.js runtime binary is not found, the start script will attempt to find one in the system-wide `PATH` before failing. +The OpenSearch Dashboards start script, `bin/opensearch-dashboards`, searches for the Node.js runtime binary using `OSD_NODE_HOME` and then `NODE_HOME` before using the binaries included with the distribution packages. If a usable Node.js runtime binary is not found, the start script attempts to find one in the system-wide `PATH` before failing. ## Configuration -To learn how to configure TLS for OpenSearch Dashboards, see [Configure TLS]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tls/). +To learn how to configure TLS for OpenSearch Dashboards, see [Configuring TLS for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/tls/). + +## Common issues + +Review these common issues and suggested solutions if OpenSearch Dashboards fails to start or you cannot log in. + +### Error message: "Request Timeout after 30000ms" + +If you encounter the error `FATAL Error: Request Timeout after 30000ms` when OpenSearch Dashboards starts, run OpenSearch Dashboards on a host that has more resources. We recommend four CPU cores and 8 GB of RAM. + +### You can't log in to OpenSearch Dashboards + +OpenSearch Dashboards does not have its own users. You log in using a user defined in the OpenSearch Security plugin. After installation, log in as the `admin` user using the password that you set in `OPENSEARCH_INITIAL_ADMIN_PASSWORD` when you installed OpenSearch. The `admin` user does not have a default password, so `admin` as a password does not work. The `kibanaserver` user is the account that OpenSearch Dashboards uses to connect to OpenSearch and is not intended for logging in. + +### The login page appears after you disable security in OpenSearch + +If you disable the Security plugin in OpenSearch, also remove the Security plugin from OpenSearch Dashboards. Otherwise, OpenSearch Dashboards shows a login page, but no credentials work. For more information, see [Removing the Security plugin from OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/security/configuration/disable-enable-security/#removing-the-security-plugin-from-opensearch-dashboards). + +### Error message: "OpenSearch Dashboards server is not ready yet" + +This message means that OpenSearch Dashboards cannot connect to OpenSearch. To find the cause, follow these steps: + +1. Make sure that OpenSearch is running by sending a request directly to OpenSearch: + + ```bash + curl https://localhost:9200 -u admin:<custom-admin-password> --insecure + ``` + {% include copy.html %} + + If this request fails, the problem is in OpenSearch, not in OpenSearch Dashboards. Check the OpenSearch log. + +1. Make sure that `opensearch.hosts` in `opensearch_dashboards.yml` contains the address of OpenSearch. + +1. Make sure that `opensearch.username` and `opensearch.password` in `opensearch_dashboards.yml` match the credentials of the `kibanaserver` user in OpenSearch. If you changed the `kibanaserver` password in `internal_users.yml`, set `opensearch.password` to the new password in plain text and restart OpenSearch Dashboards. + +### Error message: "Client network socket disconnected before secure TLS connection was established" + +OpenSearch Dashboards connects to OpenSearch using the protocol in `opensearch.hosts`. This error means that OpenSearch Dashboards tried to connect using HTTPS but OpenSearch did not complete a TLS handshake. If the Security plugin is disabled in OpenSearch, OpenSearch serves HTTP, so use `http://` in `opensearch.hosts`. If the Security plugin is enabled, use `https://`. diff --git a/_install-and-configure/install-dashboards/plugins.md b/_install-and-configure/install-dashboards/plugins.md index 6a15e65f..be191636 100644 --- a/_install-and-configure/install-dashboards/plugins.md +++ b/_install-and-configure/install-dashboards/plugins.md @@ -4,187 +4,128 @@ title: Managing OpenSearch Dashboards plugins nav_order: 100 redirect_from: - /dashboards/install/plugins/ - - /install-and-configure/install-dashboards/plugins/ --- # Managing OpenSearch Dashboards plugins -OpenSearch Dashboards provides a command line tool called `opensearch-dashboards-plugin` for managing plugins. This tool allows you to: +OpenSearch Dashboards provides a command line tool called `opensearch-dashboards-plugin` for managing plugins. -- List installed plugins. -- Install plugins. -- Remove an installed plugin. +## Prerequisites + +- A compatible OpenSearch cluster +- The corresponding OpenSearch plugins [installed on that cluster]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) +- The corresponding version of [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/) (for example, OpenSearch Dashboards 2.3.0 works with OpenSearch 2.3.0) + +## Using the `opensearch-dashboards-plugin` tool + +Run `opensearch-dashboards-plugin` from the OpenSearch Dashboards installation directory, for example, `/usr/share/opensearch-dashboards` for RPM and Debian installations. The tool refuses to run as the `root` user and returns an `OpenSearch Dashboards should not be run as root` error. The RPM and Debian packages install the `plugins` directory with `root` ownership, so for these installations, run the tool with `sudo` and add the `--allow-root` option, as shown in the examples on this page. For tarball and Windows installations, run the tool as the user that owns the installation directory, without `sudo` or `--allow-root`. + +Use the `opensearch-dashboards-plugin` tool to perform the following actions: + +- [List](#listing-installed-plugins) installed plugins. +- [Install](#installing-plugins) plugins. +- [Remove](#removing-plugins) installed plugins. + +### Listing installed plugins + +To view the list of installed plugins from the command line, use the following command: + +```bash +sudo bin/opensearch-dashboards-plugin list --allow-root +``` +{% include copy.html %} + +The command returns the list of installed plugins and their versions: + +```text +alertingDashboards@{{site.opensearch_dashboards_version}}.0 +anomalyDetectionDashboards@{{site.opensearch_dashboards_version}}.0 +assistantDashboards@{{site.opensearch_dashboards_version}}.0 +customImportMapDashboards@{{site.opensearch_dashboards_version}}.0 +flowFrameworkDashboards@{{site.opensearch_dashboards_version}}.0 +indexManagementDashboards@{{site.opensearch_dashboards_version}}.0 +investigationDashboards@{{site.opensearch_dashboards_version}}.0 +mlCommonsDashboards@{{site.opensearch_dashboards_version}}.0 +notificationsDashboards@{{site.opensearch_dashboards_version}}.0 +observabilityDashboards@{{site.opensearch_dashboards_version}}.0 +queryInsightsDashboards@{{site.opensearch_dashboards_version}}.0 +queryWorkbenchDashboards@{{site.opensearch_dashboards_version}}.0 +reportsDashboards@{{site.opensearch_dashboards_version}}.0 +searchRelevanceDashboards@{{site.opensearch_dashboards_version}}.0 +securityAnalyticsDashboards@{{site.opensearch_dashboards_version}}.0 +securityDashboards@{{site.opensearch_dashboards_version}}.0 +``` + +### Installing plugins + +To install a plugin, provide the URL of the plugin's zip file: + +```bash +sudo bin/opensearch-dashboards-plugin install <plugin-zip-url> --allow-root +``` +{% include copy.html %} + +To install a plugin from a zip file on the host, provide the file path using the `file://` scheme: + +```bash +sudo bin/opensearch-dashboards-plugin install file:///<path-to-plugin-zip> --allow-root +``` +{% include copy.html %} + +The plugin version must match your OpenSearch Dashboards version. For more information, see [Plugin compatibility](#plugin-compatibility). After installing the plugin, restart OpenSearch Dashboards. + +The download URLs of the bundled plugins are listed in the `manifest.yml` file located in the root of the OpenSearch Dashboards installation directory. For more information, see [Downloading bundled plugins for offline installation]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#downloading-bundled-plugins-for-offline-installation). + +### Removing plugins + +To remove a plugin, use the following command: + +```bash +sudo bin/opensearch-dashboards-plugin remove alertingDashboards --allow-root +``` +{% include copy.html %} + +Then remove all associated entries from `opensearch_dashboards.yml` and restart OpenSearch Dashboards. + +### Updating plugins + +The `opensearch-dashboards-plugin` tool does not update plugins. To update a plugin, [remove the old version](#removing-plugins), [install the new version](#installing-plugins), and restart OpenSearch Dashboards. + +## Available plugins + +The following table lists available OpenSearch Dashboards plugins. All listed plugins are included in the default OpenSearch distributions. + +| Plugin name | Repository | Introduced in | +| :--- | :--- | :--- | +| `alertingDashboards` | [alerting-dashboards-plugin](https://github.com/opensearch-project/alerting-dashboards-plugin) | 1.0.0 | +| `anomalyDetectionDashboards` | [anomaly-detection-dashboards-plugin](https://github.com/opensearch-project/anomaly-detection-dashboards-plugin) | 1.0.0 | +| `assistantDashboards` | [dashboards-assistant](https://github.com/opensearch-project/dashboards-assistant) | 2.13.0 | +| `customImportMapDashboards` | [dashboards-maps](https://github.com/opensearch-project/dashboards-maps) | 2.2.0 | +| `flowFrameworkDashboards` | [dashboards-flow-framework](https://github.com/opensearch-project/dashboards-flow-framework) | 2.19.0 | +| `indexManagementDashboards` | [index-management-dashboards-plugin](https://github.com/opensearch-project/index-management-dashboards-plugin) | 1.0.0 | +| `investigationDashboards` | [dashboards-investigation](https://github.com/opensearch-project/dashboards-investigation) | 3.8.0 | +| `mlCommonsDashboards` | [ml-commons-dashboards](https://github.com/opensearch-project/ml-commons-dashboards) | 2.6.0 | +| `notificationsDashboards` | [dashboards-notifications](https://github.com/opensearch-project/dashboards-notifications) | 2.0.0 | +| `observabilityDashboards` | [dashboards-observability](https://github.com/opensearch-project/dashboards-observability) | 2.0.0 | +| `queryInsightsDashboards` | [query-insights-dashboards](https://github.com/opensearch-project/query-insights-dashboards) | 2.19.0 | +| `queryWorkbenchDashboards` | [query-workbench](https://github.com/opensearch-project/dashboards-query-workbench) | 1.0.0 | +| `reportsDashboards` | [dashboards-reporting](https://github.com/opensearch-project/dashboards-reporting) | 1.0.0 | +| `searchRelevanceDashboards` | [dashboards-search-relevance](https://github.com/opensearch-project/dashboards-search-relevance) | 2.4.0 | +| `securityAnalyticsDashboards` | [security-analytics-dashboards-plugin](https://github.com/opensearch-project/security-analytics-dashboards-plugin)| 2.4.0 | +| `securityDashboards` | [security-dashboards-plugin](https://github.com/opensearch-project/security-dashboards-plugin) | 1.0.0 | + +_<sup>*</sup>`dashboardNotebooks` was merged into the Observability plugin with the release of OpenSearch 1.2.0._<br> ## Plugin compatibility Major, minor, and patch plugin versions must match OpenSearch major, minor, and patch versions in order to be compatible. For example, plugins versions 2.3.0.x work only with OpenSearch 2.3.0. {: .warning} -## Prerequisites +## Plugin dependencies -- A compatible OpenSearch cluster -- The corresponding OpenSearch plugins [installed on that cluster]({{site.url}}{{site.baseurl}}/opensearch/install/plugins/) -- The corresponding version of [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/) (for example, OpenSearch Dashboards 2.3.0 works with OpenSearch 2.3.0) +Some plugins extend functionality of other plugins. If a plugin has a dependency on another plugin, you must install the required dependency before installing the dependent plugin. For plugin dependencies, see the [manifest file](https://github.com/opensearch-project/opensearch-build/blob/main/manifests/{{site.opensearch_dashboards_version}}/opensearch-dashboards-{{site.opensearch_dashboards_version}}.yml). In this file, each plugin's dependencies are listed in the `depends_on` parameter. -## Available plugins +## Related documentation -The following table lists available OpenSearch Dashboards plugins. - -| Plugin Name | Repository | Earliest Available Version | -| :--- | :--- | :--- | -| Alerting Dashboards | [alerting-dashboards-plugin](https://github.com/opensearch-project/alerting-dashboards-plugin) | 1.0.0 | -| Anomaly Detection Dashboards | [anomaly-detection-dashboards-plugin](https://github.com/opensearch-project/anomaly-detection-dashboards-plugin) | 1.0.0 | -| Custom Import Maps Dashboards | [dashboards-maps](https://github.com/opensearch-project/dashboards-maps) | 2.2.0 | -| Search Relevance Dashboards | [dashboards-search-relevance](https://github.com/opensearch-project/dashboards-search-relevance) | 2.4.0 | -| Gantt Chart Dashboards | [gantt-chart](https://github.com/opensearch-project/dashboards-visualizations) | 1.0.0 | -| Index Management Dashboards | [index-management-dashboards-plugin](https://github.com/opensearch-project/index-management-dashboards-plugin) | 1.0.0 | -| Notebooks Dashboards | [dashboards-notebooks](https://github.com/opensearch-project/dashboards-notebooks) | 1.0.0 | -| Notifications Dashboards | [dashboards-notifications](https://github.com/opensearch-project/dashboards-notifications) | 2.0.0 | -| Observability Dashboards | [dashboards-observability](https://github.com/opensearch-project/dashboards-observability) | 2.0.0 | -| Query Workbench Dashboards | [query-workbench](https://github.com/opensearch-project/dashboards-query-workbench) | 1.0.0 | -| Reports Dashboards | [dashboards-reporting](https://github.com/opensearch-project/dashboards-reporting) | 1.0.0 | -| Security Analytics Dashboards | [security-analytics-dashboards-plugin](https://github.com/opensearch-project/security-analytics-dashboards-plugin)| 2.4.0 | -| Security Dashboards | [security-dashboards-plugin](https://github.com/opensearch-project/security-dashboards-plugin) | 1.0.0 | - -## Install - -Navigate to the OpenSearch Dashboards home directory (for example, `/usr/share/opensearch-dashboards`) and run the install command for each plugin. - -{% comment %} - -#### Security OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-security/opensearchSecurityOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.0.1.zip -``` - -This plugin provides a user interface for managing users, roles, mappings, action groups, and tenants. - -#### Alerting OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-alerting/opensearchAlertingOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.0.0.zip -``` - -This plugin provides a user interface for creating monitors and managing alerts. - -#### Index State Management OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-index-management/opensearchIndexManagementOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.0.1.zip -``` - -This plugin provides a user interface for managing policies. - -#### Anomaly Detection OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-anomaly-detection/opensearchAnomalyDetectionOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.0.0.zip -``` - -This plugin provides a user interface for adding detectors. - -#### Query Workbench OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-query-workbench/opensearchQueryWorkbenchOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.0.0.zip -``` - -This plugin provides a user interface for using SQL queries to explore your data. - -#### Trace Analytics - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-trace-analytics/opensearchTraceAnalyticsOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.2.0.zip -``` - -This plugin uses distributed trace data (indexed in OpenSearch using Data Prepper) to display latency trends, error rates, and more. - -#### Notebooks OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-notebooks/opensearchNotebooksOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.2.0.zip -``` - -This plugin lets you combine OpenSearch Dashboards visualizations and narrative text in a single interface. - -#### Reports OpenSearch Dashboards - -```bash -# x86 Linux -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-reports/linux/x64/opensearchReportsOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.2.0-linux-x64.zip -# ARM64 Linux -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-reports/linux/arm64/opensearchReportsOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.2.0-linux-arm64.zip -# x86 Windows -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-reports/windows/x64/opensearchReportsOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.2.0-windows-x64.zip -``` - -This plugin lets you export and share reports from OpenSearch Dashboards dashboards, visualizations, and saved searches. - -#### Gantt Chart OpenSearch Dashboards - -```bash -sudo bin/opensearch-dashboards-plugin install https://d3g5vo6xdbdb9a.cloudfront.net/downloads/opensearch-dashboards-plugins/opensearch-gantt-chart/opensearchGanttChartOpenSearch Dashboards-{{site.opensearch_major_minor_version}}.0.0.zip -``` - -This plugin adds a new Gantt chart visualization. - -{% endcomment %} - -## Viewing a list of installed plugins - -To view the list of installed plugins from the command line, use the following command: - -```bash -sudo bin/opensearch-dashboards-plugin list -``` - -## Remove plugins - -To remove a plugin: - -```bash -sudo bin/opensearch-dashboards-plugin remove <plugin-name> -``` - -Then remove all associated entries from `opensearch_dashboards.yml`. - -For certain plugins, you must also remove the "optimize" bundle. This is a sample command for the Anomaly Detection plugin: - -```bash -sudo rm /usr/share/opensearch-dashboards/optimize/bundles/opensearch-anomaly-detection-opensearch-dashboards.* -``` - -Then restart OpenSearch Dashboards. After you remove any plugin, OpenSearch Dashboards performs an optimize operation the next time you start it. This operation takes several minutes even on fast machines, so be patient. - -## Updating plugins - -OpenSearch Dashboards doesn’t update plugins. Instead, you have to remove the old version and its optimized bundle, reinstall them, and restart OpenSearch Dashboards: - -1. Remove the old version: - - ```bash - sudo bin/opensearch-dashboards-plugin remove <plugin-name> - ``` - -1. Remove the optimized bundle: - - ```bash - sudo rm /usr/share/opensearch-dashboards/optimize/bundles/<bundle-name> - ``` - -1. Reinstall the new version: - - ```bash - sudo bin/opensearch-dashboards-plugin install <plugin-name> - ``` - -1. Restart OpenSearch Dashboards. - -For example, to remove and reinstall the Anomaly Detection plugin: - -```bash -sudo bin/opensearch-dashboards-plugin remove anomalyDetectionDashboards -sudo rm /usr/share/opensearch-dashboards/optimize/bundles/opensearch-anomaly-detection-opensearch-dashboards.* -sudo bin/opensearch-dashboards-plugin install <AD OpenSearch Dashboards plugin artifact URL> -``` +- [Installing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) +- [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) diff --git a/_install-and-configure/install-dashboards/rpm.md b/_install-and-configure/install-dashboards/rpm.md index d250c4c1..2e35262c 100644 --- a/_install-and-configure/install-dashboards/rpm.md +++ b/_install-and-configure/install-dashboards/rpm.md @@ -2,7 +2,7 @@ layout: default title: RPM parent: Installing OpenSearch Dashboards -nav_order: 31 +nav_order: 25 redirect_from: - /dashboards/install/rpm/ --- @@ -13,44 +13,78 @@ The following liquid syntax declares a variable, major_version_mask, which is tr {% assign version_parts = site.opensearch_major_minor_version | split: "." %} {% assign major_version_mask = version_parts[0] | append: ".x" %} -# Run OpenSearch Dashboards using RPM Package Manager (RPM) +# Installing OpenSearch Dashboards using RPM -OpenSearch Dashboards is the default visualization tool for data in OpenSearch. It also serves as a user interface for many of the OpenSearch plugins, including security, alerting, Index State Management, SQL, and more. +You can install OpenSearch Dashboards on RPM-based Linux distributions, such as Red Hat Enterprise Linux, Amazon Linux, Alma Linux, and Rocky Linux, using the RPM Package Manager (RPM). Install the package that you download from the OpenSearch downloads page or from the OpenSearch Dashboards YUM repository. The package manager sets the installation path and the location of the configuration files and creates an `opensearch-dashboards` service managed by `systemd`. + +## Prerequisites + +Install OpenSearch. For more information, see [Installing OpenSearch using RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/). ## Install OpenSearch Dashboards from a package -1. Download the RPM package for the desired version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. The RPM package can be download for both **x64** and **arm64** architectures. +1. Download the RPM package for the desired version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. The RPM package is available for both **x64** and **arm64** architectures. 1. Import the public GPG key. This key verifies that your OpenSearch instance is signed. ```bash - sudo rpm --import https://artifacts.opensearch.org/publickeys/opensearch.pgp + sudo rpm --import https://artifacts.opensearch.org/publickeys/opensearch-release.pgp ``` + {% include copy.html %} + 1. From the command line interface (CLI), you can install the package with `rpm` or `yum`. + **x64** + + Install the x64 package using yum: ```bash - # Install the x64 package using yum. - sudo yum install opensearch-dashboards-{{site.opensearch_version}}-linux-x64.rpm - # Install the x64 package using rpm. - sudo rpm -ivh opensearch-dashboards-{{site.opensearch_version}}-linux-x64.rpm + sudo yum install opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.rpm ``` + {% include copy.html %} + + Install the x64 package using rpm: + ```bash + sudo rpm -ivh opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.rpm + ``` + {% include copy.html %} + **arm64** + + Install the arm64 package using yum: ```bash - # Install the arm64 package using yum. - sudo yum install opensearch-dashboards-{{site.opensearch_version}}-linux-arm64.rpm - # Install the arm64 package using rpm. - sudo rpm -ivh opensearch-dashboards-{{site.opensearch_version}}-linux-arm64.rpm + sudo yum install opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-arm64.rpm ``` -1. After the installation succeeds, enable OpenSearch Dashboards as a service. + {% include copy.html %} + + Install the arm64 package using rpm: + ```bash + sudo rpm -ivh opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-arm64.rpm + ``` + {% include copy.html %} + + For new installations of OpenSearch Dashboards 3.7 and later, you can disable the Security Dashboards plugin by adding the `DISABLE_SECURITY_DASHBOARDS_PLUGIN=true` environment variable before the installation command with the `env` keyword: + ```bash + sudo env DISABLE_SECURITY_DASHBOARDS_PLUGIN=true rpm -ivh opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.rpm + ``` + {% include copy.html %} + +1. After the installation succeeds, enable OpenSearch Dashboards as a service: ```bash sudo systemctl enable opensearch-dashboards ``` -1. Start OpenSearch Dashboards. + {% include copy.html %} + +1. Start OpenSearch Dashboards: ```bash sudo systemctl start opensearch-dashboards ``` -1. Verify that OpenSearch Dashboards launched correctly. + {% include copy.html %} + +1. Verify that OpenSearch Dashboards launched correctly: ```bash sudo systemctl status opensearch-dashboards ``` + {% include copy.html %} + +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). ## Install OpenSearch Dashboards from a local YUM repository @@ -60,33 +94,94 @@ YUM, the primary package management tool for Red Hat-based operating systems, al ```bash sudo curl -SL https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{major_version_mask}}/opensearch-dashboards-{{major_version_mask}}.repo -o /etc/yum.repos.d/opensearch-dashboards-{{major_version_mask}}.repo ``` -1. Verify that the repository was created successfully. + {% include copy.html %} + +1. Verify that the repository was created successfully: ```bash sudo yum repolist ``` + {% include copy.html %} + 1. Clean your YUM cache, to ensure a smooth installation: ```bash sudo yum clean all ``` + {% include copy.html %} + 1. With the repository file downloaded, list all available versions of OpenSearch-Dashboards: ```bash sudo yum list opensearch-dashboards --showduplicates ``` -1. Choose the version of OpenSearch Dashboards you want to install: - - Unless otherwise indicated, the highest minor version of OpenSearch installs. + {% include copy.html %} + +1. Choose the version of OpenSearch Dashboards you want to install: + - Unless otherwise indicated, the highest minor version of OpenSearch installs: ```bash sudo yum install opensearch-dashboards ``` + {% include copy.html %} + - To install a specific version of OpenSearch Dashboards: ```bash - sudo yum install 'opensearch-dashboards-{{site.opensearch_version}}' + sudo yum install 'opensearch-dashboards-{{site.opensearch_dashboards_version}}' ``` -1. During installation, the installer will present you with the GPG key fingerprint. Verify that the information matches the following: - ```bash - Fingerprint: c5b7 4989 65ef d1c2 924b a9d5 39d3 1987 9310 d3fc + {% include copy.html %} + +1. The first time YUM downloads the repository metadata (for example, when you list the available versions) and again during installation, YUM prompts you to import the GPG key and presents the key fingerprint. Verify that the information matches the following: + ```text + Fingerprint: A8B2 D9E0 4CD5 1FEF 6AA2 DB53 BA81 D999 8119 1457 ``` + - If correct, enter `yes` or `y`. The OpenSearch installation continues. -1. Once complete, you can run OpenSearch Dashboards. +1. Start OpenSearch Dashboards: ```bash sudo systemctl start opensearch-dashboards - ``` \ No newline at end of file + ``` + {% include copy.html %} + +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + +## Upgrade to a newer version + +OpenSearch Dashboards instances installed using RPM or YUM can be easily upgraded to a newer version. We recommend using YUM, but you can also choose RPM. + + +### Upgrade manually using RPM + +Download the RPM package for the desired upgrade version directly from the [OpenSearch Project downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. + +Navigate to the directory containing the distribution and run the following command: + +```bash +sudo rpm -Uvh opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.rpm +``` +{% include copy.html %} + +### Upgrade using YUM + +To upgrade to the latest version of OpenSearch Dashboards using YUM, run the following command: + +```bash +sudo yum update opensearch-dashboards +``` +{% include copy.html %} + +You can also upgrade to a specific OpenSearch Dashboards version by providing the version number: + + ```bash + sudo yum update opensearch-dashboards-<version-number> + ``` + {% include copy.html %} + +### Automatically restart the service after a package upgrade + +The OpenSearch Dashboards RPM package does not support automatically restarting the service after a package upgrade. The upgrade stops OpenSearch Dashboards, so start the service after the upgrade completes: + +```bash +sudo systemctl start opensearch-dashboards +``` +{% include copy.html %} + +## Related documentation + +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-dashboards/tar.md b/_install-and-configure/install-dashboards/tar.md index 439abb63..118d9fe1 100644 --- a/_install-and-configure/install-dashboards/tar.md +++ b/_install-and-configure/install-dashboards/tar.md @@ -7,25 +7,69 @@ redirect_from: - /dashboards/install/tar/ --- -# Run OpenSearch Dashboards using the tarball +# Installing OpenSearch Dashboards from a tarball -1. Download the tarball from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. +You can install OpenSearch Dashboards on any Linux distribution by extracting a tarball archive on x64 or arm64 hosts. The tarball is a self-contained directory that includes everything you need to run OpenSearch Dashboards, including the configuration files in the `config` directory. The tarball does not create a system service, so you start OpenSearch Dashboards manually from the extracted directory. -1. Extract the TAR file to a directory and change to that directory: +## Prerequisites + +Install OpenSearch. For more information, see [Installing OpenSearch from a tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/). + +## Install OpenSearch Dashboards from a tarball + +To install OpenSearch Dashboards from a tarball, follow these steps: + +1. Download the tarball from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'} or by using the command line, for example, using `curl`. + + For an x64 host, use the following command: ```bash - # x64 - tar -zxf opensearch-dashboards-{{site.opensearch_version}}-linux-x64.tar.gz - cd opensearch-dashboards - # ARM64 - tar -zxf opensearch-dashboards-{{site.opensearch_version}}-linux-arm64.tar.gz - cd opensearch-dashboards + curl -fsSLO https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_dashboards_version}}/opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.tar.gz ``` + {% include copy.html %} -1. If desired, modify `config/opensearch_dashboards.yml`. + For an ARM64 host, use the following command: -1. Run OpenSearch Dashboards: + ```bash + curl -fsSLO https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_dashboards_version}}/opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-arm64.tar.gz + ``` + {% include copy.html %} + +1. Extract the TAR file to a directory. + + For an x64 host, use the following command: + + ```bash + tar -zxf opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-x64.tar.gz + ``` + {% include copy.html %} + + For an ARM64 host, use the following command: + + ```bash + tar -zxf opensearch-dashboards-{{site.opensearch_dashboards_version}}-linux-arm64.tar.gz + ``` + {% include copy.html %} + + Then change to the extracted directory: + + ```bash + cd opensearch-dashboards-{{site.opensearch_dashboards_version}} + ``` + {% include copy.html %} + +1. Start OpenSearch Dashboards: ```bash ./bin/opensearch-dashboards ``` + {% include copy.html %} + +1. In a web browser, go to `http://localhost:5601` and log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. OpenSearch Dashboards can take about 1 minute to start. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + +By default, OpenSearch Dashboards connects to OpenSearch at `https://localhost:9200` as the `kibanaserver` user and accepts connections only from the host on which it runs. To change these settings, edit `config/opensearch_dashboards.yml`. For more information, see [Configuring OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-dashboards/). +{: .note} + +## Related documentation + +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-dashboards/tls.md b/_install-and-configure/install-dashboards/tls.md index ba3da799..07d52efc 100644 --- a/_install-and-configure/install-dashboards/tls.md +++ b/_install-and-configure/install-dashboards/tls.md @@ -1,51 +1,81 @@ --- layout: default -title: Configure TLS +title: Configuring TLS parent: Installing OpenSearch Dashboards -nav_order: 40 +nav_order: 50 redirect_from: - /dashboards/install/tls/ --- -# Configure TLS for OpenSearch Dashboards +# Configuring TLS for OpenSearch Dashboards -By default, for ease of testing and getting started, OpenSearch Dashboards runs over HTTP. To enable TLS for HTTPS, update the following settings in `opensearch_dashboards.yml`. +By default, for ease of testing and getting started, OpenSearch Dashboards runs over HTTP. + +The following table lists the certificates that OpenSearch Dashboards uses, depending on your configuration. + +Certificate | Settings | Description +:--- | :--- | :--- +Server certificate and key | `server.ssl.certificate`, `server.ssl.key` | The certificate that OpenSearch Dashboards presents to web browsers over HTTPS. Use a certificate issued for the OpenSearch Dashboards host. This certificate is separate from the OpenSearch node certificates. +CA certificates | `opensearch.ssl.certificateAuthorities` | The certificates of the CA that signed the OpenSearch node certificates. OpenSearch Dashboards uses them to verify OpenSearch, so they are the same CA certificates that your OpenSearch cluster uses. +Client certificate and key | `opensearch.ssl.certificate`, `opensearch.ssl.key` | Required only if OpenSearch requires OpenSearch Dashboards to authenticate using a certificate (mTLS). The certificate must be signed by a CA that OpenSearch trusts. + +To enable TLS for HTTPS, update the following settings in `opensearch_dashboards.yml`. Setting | Description :--- | :--- `server.ssl.enabled` | Enables SSL communication between the OpenSearch Dashboards server and the user's web browser. Set to `true` for HTTPS or `false` for HTTP. -`server.ssl.supportedProtocols` | Specifies the array of supported TLS protocols. Possible values are `TLSv1`, `TLSv1.1`, and `TLSv1.2`, `TLSv1.3`. Default is `['TLSv1.1', 'TLSv1.2', and 'TLSv1.3']`. +`server.ssl.supportedProtocols` | Specifies the array of supported TLS protocols. Valid values are `TLSv1`, `TLSv1.1`, `TLSv1.2`, and `TLSv1.3`. Default is `['TLSv1.1', 'TLSv1.2', and 'TLSv1.3']`. `server.ssl.cipherSuites` | Specifies the array of TLS cipher suites. Optional. `server.ssl.certificate` | If `server.ssl.enabled` is set to `true`, specifies the full path to a valid Privacy Enhanced Mail (PEM) server certificate for OpenSearch Dashboards. You can [generate your own certificate]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/) or get one from a certificate authority (CA). `server.ssl.key` | If `server.ssl.enabled` is set to `true`, specifies the full path to the key for your server certificate, for example, `/usr/share/opensearch-dashboards-1.0.0/config/my-client-cert-key.pem`. You can [generate your own certificate]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/) or get one from a CA. `server.ssl.keyPassphrase` | Sets the password for the key. Omit this setting if the key has no password. Optional. `server.ssl.keystore.path` | Uses a JKS (Java KeyStore) or PKCS12/PFX (Public-Key Cryptography Standards) file instead of a PEM certificate and key. -`server.ssl.keystore.password` | Sets the password for the key store. Required. +`server.ssl.keystore.password` | Sets the password for the keystore. Required. `server.ssl.clientAuthentication` | Specifies the TLS client authentication mode to use. Can be one of the following: `none`, `optional`, or `required`. If set to `required`, your web browser needs to send a valid client certificate signed by the CA configured in `server.ssl.certificateAuthorities`. Default is `none`. `server.ssl.certificateAuthorities` | Specifies the full path to one or more CA certificates in an array that issues the certificate used for client authentication. Required if `server.ssl.clientAuthentication` is set to `optional` or `required`. -`server.ssl.truststore.path` | Uses a JKS or PKCS12/PFX trust store file instead of PEM CA certificates. -`server.ssl.truststore.password` | Sets the password for the trust store. Required. +`server.ssl.truststore.path` | Uses a JKS or PKCS12/PFX truststore file instead of PEM CA certificates. +`server.ssl.truststore.password` | Sets the password for the truststore. Required. `opensearch.ssl.verificationMode` | Establishes communication between OpenSearch and OpenSearch Dashboards. Valid values are `full`, `certificate`, or `none`. `full` is recommended if TLS is enabled, which enables hostname verification. `certificate` checks the certificate but not the hostname. `none` performs no checks (suitable for HTTP). Default is `full`. `opensearch.ssl.certificateAuthorities` | If `opensearch.ssl.verificationMode` is set to `full` or `certificate`, specifies the full path to one or more CA certificates in an array that comprises a trusted chain for an OpenSearch cluster. For example, you might need to include a root CA _and_ an intermediate CA if you used the intermediate CA to issue your admin, client, and node certificates. -`opensearch.ssl.truststore.path` | Uses a JKS or PKCS12/PFX trust store file instead of PEM CA certificates. -`opensearch.ssl.truststore.password` | Sets the password for the trust store. Required. +`opensearch.ssl.truststore.path` | Uses a JKS or PKCS12/PFX truststore file instead of PEM CA certificates. +`opensearch.ssl.truststore.password` | Sets the password for the truststore. Required. `opensearch.ssl.alwaysPresentCertificate` | Sends the client certificate to the OpenSearch cluster if set to `true`, which is necessary when mTLS is enabled in OpenSearch. Default is `false`. `opensearch.ssl.certificate` | If `opensearch.ssl.alwaysPresentCertificate` is set to `true`, specifies the full path to a valid client certificate for the OpenSearch cluster. You can [generate your own certificate]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/) or get one from a CA. `opensearch.ssl.key` | If `opensearch.ssl.alwaysPresentCertificate` is set to `true`, specifies the full path to the key for the client certificate. You can [generate your own certificate]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/) or get one from a CA. `opensearch.ssl.keyPassphrase` | Sets the password for the key. Omit this setting if the key has no password. Optional. -`opensearch.ssl.keystore.path` | Uses a JKS or PKCS12/PFX key store file instead of a PEM certificate and key. -`opensearch.ssl.keystore.password` | Sets the password for the key store. Required. +`opensearch.ssl.keystore.path` | Uses a JKS or PKCS12/PFX keystore file instead of a PEM certificate and key. +`opensearch.ssl.keystore.password` | Sets the password for the keystore. Required. `opensearch_security.cookie.secure` | If TLS is enabled for OpenSearch Dashboards, change this setting to `true`. For HTTP, set it to `false`. +`opensearch_security.session.keepalive`| Determines whether the session TTL resets (is "kept alive") on each user activity. Optional. Default is `true`. +`opensearch_security.session.ttl`| Defines the time-to-live (TTL) for user sessions, in milliseconds. Optional. Default is `3600000` (1 hour). -The following `opensearch_dashboards.yml` configuration shows OpenSearch and OpenSearch Dashboards running on the same machine with the demo configuration: +## Example: OpenSearch Dashboards and OpenSearch on the same machine + +The following example configures TLS for OpenSearch Dashboards running on the same machine as an OpenSearch node that uses the demo security configuration. The example requires the following files in the OpenSearch Dashboards `config` directory: + +- `root-ca.pem`: The root CA certificate that signed the OpenSearch node certificates. The demo security configuration creates this file in the OpenSearch `config` directory, for example, `/usr/share/opensearch/config/` for Docker, `/etc/opensearch/` for RPM and Debian, or the `config` directory of a tarball installation. Copy it to the OpenSearch Dashboards `config` directory. +- `client-cert.pem` and `client-cert-key.pem`: The certificate and key that OpenSearch Dashboards presents to web browsers. The demo security configuration does not create these files. You can [generate your own certificate]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/) or get one from a CA. For testing, you can create a self-signed certificate and key using the following command: + + ```bash + openssl req -x509 -newkey rsa:2048 -nodes -keyout client-cert-key.pem -out client-cert.pem -days 30 -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost" + ``` + {% include copy.html %} + +If a certificate or key file specified in `opensearch_dashboards.yml` does not exist, OpenSearch Dashboards fails to start with an `ENOENT: no such file or directory` error. +{: .note} + +The demo node certificate includes `localhost` as a subject alternative name, so the `full` verification mode succeeds when `opensearch.hosts` uses `localhost`. + +Add the following settings to `opensearch_dashboards.yml`: ```yml +server.host: '0.0.0.0' server.ssl.enabled: true server.ssl.certificate: /usr/share/opensearch-dashboards/config/client-cert.pem server.ssl.key: /usr/share/opensearch-dashboards/config/client-cert-key.pem opensearch.hosts: ["https://localhost:9200"] opensearch.ssl.verificationMode: full -opensearch.ssl.certificateAuthorities: [ "/usr/share/opensearch-dashboards/config/root-ca.pem", "/usr/share/opensearch-dashboards/config/intermediate-ca.pem" ] +opensearch.ssl.certificateAuthorities: [ "/usr/share/opensearch-dashboards/config/root-ca.pem" ] opensearch.username: "kibanaserver" opensearch.password: "kibanaserver" opensearch.requestHeadersAllowlist: [ authorization,securitytenant ] @@ -54,7 +84,15 @@ opensearch_security.multitenancy.tenants.preferred: ["Private", "Global"] opensearch_security.readonly_mode.roles: ["kibana_read_only"] opensearch_security.cookie.secure: true ``` +{% include copy.html %} -If you use the Docker install option, you can pass a custom `opensearch_dashboards.yml` file to the container. To learn more, see the [Docker installation page]({{site.url}}{{site.baseurl}}/opensearch/install/docker/). +If your OpenSearch certificates are signed by an intermediate CA, add the intermediate CA certificate to `opensearch.ssl.certificateAuthorities` in `opensearch_dashboards.yml`: + +```yml +opensearch.ssl.certificateAuthorities: [ "/usr/share/opensearch-dashboards/config/root-ca.pem", "/usr/share/opensearch-dashboards/config/intermediate-ca.pem" ] +``` +{% include copy.html %} + +If you use the Docker install option, you can pass a custom `opensearch_dashboards.yml` file to the container. To learn more, see the [Docker installation page]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/docker/). You can connect to OpenSearch Dashboards at `https://localhost:5601` after enabling these settings and starting the application. You might need to acknowledge a browser warning if your certificates are self-signed. To avoid this type of warning (or outright browser incompatibility), it is best practice to use certificates from a trusted CA. diff --git a/_install-and-configure/install-dashboards/windows.md b/_install-and-configure/install-dashboards/windows.md index 9c9ee316..48aa0d35 100644 --- a/_install-and-configure/install-dashboards/windows.md +++ b/_install-and-configure/install-dashboards/windows.md @@ -2,39 +2,99 @@ layout: default title: Windows parent: Installing OpenSearch Dashboards -nav_order: 37 +nav_order: 40 redirect_from: - /dashboards/install/windows/ --- -# Run OpenSearch Dashboards on Windows +<!-- vale off --> +# Installing OpenSearch Dashboards on Windows +<!-- vale on --> -Perform the following steps to install OpenSearch Dashboards on Windows. +## Prerequisites -Make sure you have a zip utility installed. -{: .note } +Before you install OpenSearch Dashboards, complete the following tasks: -1. Download the [`opensearch-dashboards-{{site.opensearch_version}}-windows-x64.zip`](https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_version}}/opensearch-dashboards-{{site.opensearch_version}}-windows-x64.zip){:target='\_blank'} archive. +- Install OpenSearch. For more information, see [Installing OpenSearch on Windows]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/windows/). +- Install a zip utility. -1. To extract the archive contents, right-click to select **Extract All**. - - **Note**: Some versions of the Windows operating system limit the file path length. If you encounter a path-length-related error when unzipping the archive, perform the following steps to enable long path support: +## Install OpenSearch Dashboards on Windows + +To install OpenSearch Dashboards on Windows, follow these steps: + +1. Download the [`opensearch-dashboards-{{site.opensearch_dashboards_version}}-windows-x64.zip`](https://artifacts.opensearch.org/releases/bundle/opensearch-dashboards/{{site.opensearch_dashboards_version}}/opensearch-dashboards-{{site.opensearch_dashboards_version}}-windows-x64.zip){:target='\_blank'} archive. + +1. To extract the archive contents, right-click to select **Extract All**. The archive contains about 100,000 files, so extracting it this way can take a long time. Alternatively, extract the archive from Command Prompt or PowerShell using the `tar` command included with Windows, which is faster: + + ```bat + tar -xf opensearch-dashboards-{{site.opensearch_dashboards_version}}-windows-x64.zip + ``` + {% include copy.html %} + + **Note**: Some file paths in the archive are close to the 260-character path length limit of some versions of Windows. Extracting the archive to a short path, such as `C:\opensearch`, helps you avoid path-length errors. If you encounter a path-length-related error when unzipping the archive, perform the following steps to enable long path support: 1. Open Powershell by entering `powershell` in the search box next to **Start** on the taskbar. 1. Run the following command in Powershell: - ```bat + ```powershell Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled -Type DWORD -Value 1 -Force ``` + {% include copy.html %} 1. Restart your computer. +1. Configure OpenSearch Dashboards. + + There are two ways to configure OpenSearch Dashboards, depending on whether OpenSearch is configured with security enabled or disabled. + + In order for any changes to the `opensearch_dashboards.yml` file to take effect, a restart of OpenSearch Dashboards is required. + {: .note} + + 1. Option 1 -- With security enabled: + + Configuration file `\path\to\opensearch-dashboards-{{site.opensearch_dashboards_version}}\config\opensearch_dashboards.yml` comes packaged with following basic settings: + + ```yaml + opensearch.hosts: [https://localhost:9200] + opensearch.ssl.verificationMode: none + opensearch.username: kibanaserver + opensearch.password: kibanaserver + opensearch.requestHeadersWhitelist: [authorization, securitytenant] + + opensearch_security.multitenancy.enabled: true + opensearch_security.multitenancy.tenants.preferred: [Private, Global] + opensearch_security.readonly_mode.roles: [kibana_read_only] + # Use this setting if you are running opensearch-dashboards without https + opensearch_security.cookie.secure: false + ``` + + 1. Option 2 -- With OpenSearch security disabled: + + If you are using OpenSearch with security disabled, remove the Security plugin from OpenSearch Dashboards using the following command: + + ```bat + \path\to\opensearch-dashboards-{{site.opensearch_dashboards_version}}\bin\opensearch-dashboards-plugin.bat remove securityDashboards + ``` + {% include copy.html %} + + Then replace the contents of the `opensearch_dashboards.yml` file with the following setting: + + ```yaml + opensearch.hosts: [http://localhost:9200] + ``` + {% include copy.html %} + + After you remove the Security plugin, OpenSearch Dashboards fails to start with an `Unknown configuration key(s)` error if `opensearch_dashboards.yml` still contains `opensearch_security` settings. Make sure to remove all of the packaged settings. + {: .note} + + Note the plain `http` method, instead of `https`. + {: .note} + 1. Run OpenSearch Dashboards. There are two ways of running OpenSearch Dashboards: 1. Run the batch script using the Windows UI: - 1. Navigate to the top directory of your OpenSearch Dashboards installation and open the `opensearch-dashboards-{{site.opensearch_version}}` folder. - 1. If desired, modify `opensearch_dashboards.yml` located in the `config` folder, to change the default OpenSearch Dashboards settings. + 1. Navigate to the top directory of your OpenSearch Dashboards installation and open the `opensearch-dashboards-{{site.opensearch_dashboards_version}}` folder. 1. Open the `bin` folder and run the batch script by double-clicking the `opensearch-dashboards.bat` file. This opens a command prompt with an OpenSearch Dashboards instance running. 1. Run the batch script from Command Prompt or Powershell: @@ -42,13 +102,20 @@ Make sure you have a zip utility installed. 1. Open Command Prompt by entering `cmd`, or Powershell by entering `powershell`, in the search box next to **Start** on the taskbar. 1. Change to the top directory of your OpenSearch Dashboards installation. ```bat - cd \path\to\opensearch-dashboards-{{site.opensearch_version}} + cd \path\to\opensearch-dashboards-{{site.opensearch_dashboards_version}} ``` - 1. If desired, modify `config\opensearch_dashboards.yml`. + {% include copy.html %} 1. Run the batch script to start OpenSearch Dashboards. ```bat .\bin\opensearch-dashboards.bat ``` + {% include copy.html %} -To stop OpenSearch Dashboards, press `Ctrl+C` in Command Prompt or Powershell, or simply close the Command Prompt or Powershell window. -{: .tip} \ No newline at end of file +1. In a web browser, go to `http://localhost:5601`. OpenSearch Dashboards can take about 2 minutes to start. If you configured OpenSearch Dashboards with security enabled, log in as the `admin` user using the [custom admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#setting-the-initial-admin-password) that you set when you installed OpenSearch. If OpenSearch Dashboards runs on a remote host, replace `localhost` with the IP address or DNS name of that host. For more information, see [Accessing OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#accessing-opensearch-dashboards). + +To stop OpenSearch Dashboards, press `Ctrl+C` in Command Prompt or Powershell, or close the Command Prompt or Powershell window. +{: .tip} + +## Related documentation + +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-opensearch/ansible.md b/_install-and-configure/install-opensearch/ansible.md index 9efa5406..605554c5 100644 --- a/_install-and-configure/install-opensearch/ansible.md +++ b/_install-and-configure/install-opensearch/ansible.md @@ -2,72 +2,135 @@ layout: default title: Ansible playbook parent: Installing OpenSearch -nav_order: 60 +nav_order: 35 redirect_from: - /opensearch/install/ansible/ --- -# Ansible playbook +{% assign os_major = site.opensearch_major_minor_version | split: "." | first %} +{% assign os_previous_major = os_major | minus: 1 %} + +# Installing OpenSearch and OpenSearch Dashboards using Ansible You can use an Ansible playbook to install and configure a production-ready OpenSearch cluster along with OpenSearch Dashboards. -The Ansible playbook only supports deployment of OpenSearch and OpenSearch Dashboards to CentOS7 hosts. +The Ansible playbook deploys OpenSearch and OpenSearch Dashboards to Linux hosts that use `systemd`. For the operating systems that OpenSearch is tested on, see [Compatible operating systems]({{site.url}}{{site.baseurl}}/install-and-configure/os-comp/). {: .note } ## Prerequisites -Make sure you have [Ansible](https://www.ansible.com/) and [Java 8](https://www.java.com/en/download/manual.jsp) installed. +The machine on which you run the playbook (the control node) must have the following installed: + +- [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/index.html) 2.9 or later. If you install only `ansible-core` instead of the full `ansible` package, also install the collections that the playbook uses: + + ```bash + ansible-galaxy collection install ansible.posix community.general + ``` + {% include copy.html %} + +- Java 8 or later. The playbook uses Java on the control node to generate the TLS certificates for the cluster. If Java is not installed, the playbook fails with a `java: command not found` error. + +The control node must have direct SSH access to the `root` user on each target host. ## Configuration -1. Clone the OpenSearch [ansible-playbook](https://github.com/opensearch-project/ansible-playbook) repository: +1. Clone the OpenSearch [`ansible-playbook`](https://github.com/opensearch-project/ansible-playbook) repository and navigate to the repository directory: ```bash git clone https://github.com/opensearch-project/ansible-playbook + cd ansible-playbook ``` {% include copy.html %} -2. Configure the node properties in the `inventories/opensearch/hosts` file: + The `main` branch installs the latest OpenSearch {{os_major}}.x version. To install OpenSearch {{os_previous_major}}.x, check out the `{{os_previous_major}}.x` branch. - ```bash - ansible_host=<Public IP address> ansible_user=root ip=<Private IP address / 0.0.0.0> +1. Configure the target hosts in the `inventories/opensearch/hosts` file. The default file defines a cluster of five OpenSearch nodes and one OpenSearch Dashboards node. Each line specifies a host name and the following variables: + + - `ansible_host`: The IP address that Ansible uses to connect to the target host. + - `ansible_user`: The user that Ansible uses to connect to the target host. + - `ip`: The IP address that OpenSearch and OpenSearch Dashboards bind to. Specify the private IP address of the target host or `0.0.0.0`. + - `roles`: The [node roles]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#nodes) of the OpenSearch node. + + Each host must also be listed in the groups at the end of the file: `os-cluster` for OpenSearch nodes, `master` for cluster manager-eligible nodes, and `dashboards` for the OpenSearch Dashboards node. Hosts that are not listed in a group are not installed. Replace the IP addresses in the default file with the addresses of your hosts. + + To install OpenSearch and OpenSearch Dashboards on a single host, replace the contents of the file with the following, specifying the IP addresses of your host: + + ```ini + os1 ansible_host=<public-ip-address> ansible_user=root ip=<private-ip-address> roles=data,master + + [os-cluster] + os1 + + [master] + os1 + + [dashboards] + os1 ``` {% include copy.html %} - where: + For a single host, also set `cluster_type` to `single-node` in the `inventories/opensearch/group_vars/all/all.yml` file: - - `ansible_host` is the IP address of the target node that you want the Ansible playbook to install OpenSearch and OpenSearch DashBoards on. - - `ip` is the IP address that you want OpenSearch and OpenSearch DashBoards to bind to. You can specify the private IP of the target node, or localhost, or 0.0.0.0. + ```yaml + cluster_type: single-node + ``` + {% include copy.html %} -3. You can modify the default configuration values in the `inventories/opensearch/group_vars/all/all.yml` file. For example, you can increase the Java memory heap size: +1. You can modify the default configuration values in the `inventories/opensearch/group_vars/all/all.yml` file. For example, you can increase the Java memory heap size: - ```bash + ```yaml xms_value: 8 xmx_value: 8 ``` {% include copy.html %} -Make sure you have direct SSH access into the root user of the target node. -{: .note } +## Install OpenSearch and OpenSearch Dashboards using the Ansible playbook -## Run OpenSearch and OpenSearch Dashboards using Ansible playbook - -1. Run the Ansible playbook with root privileges: +1. From the `ansible-playbook` directory, run the Ansible playbook: ```bash ansible-playbook -i inventories/opensearch/hosts opensearch.yml --extra-vars "admin_password=Test@123 kibanaserver_password=Test@6789 logstash_password=Test@456" ``` {% include copy.html %} - You can set the passwords for reserved users (`admin`, `kibanaserver`, and `logstash`) using the `admin_password`, `kibanaserver_password`, and `logstash_password` variables. + You can set the passwords for reserved users (`admin`, `kibanaserver`, and `logstash`) using the `admin_password`, `kibanaserver_password`, and `logstash_password` variables. To change the admin password after deployment, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). -2. After the deployment process is complete, you can access OpenSearch and OpenSearch Dashboards with the username `admin` and the password that you set for the `admin_password` variable. +1. After the deployment process is complete, you can access OpenSearch and OpenSearch Dashboards with the username `admin` and the password that you set for the `admin_password` variable. - If you bind `ip` to a private IP or localhost, make sure you're logged into the server that deployed the playbook to access OpenSearch and OpenSearch Dashboards: + To verify that OpenSearch is running, send a request to the IP address that you specified in the `ip` variable. If you specified a private IP address, send the request from a machine in the same network: ```bash - curl https://localhost:9200 -u 'admin:Test@123' --insecure + curl https://<private-ip-address>:9200 -u 'admin:Test@123' --insecure ``` {% include copy.html %} - If you bind `ip` to 0.0.0.0, then replace `localhost` with the public IP or the private IP (if it's in the same network). + If you specified `0.0.0.0`, you can send the request to `localhost` from the target host or to any IP address of the target host. + +1. To access OpenSearch Dashboards, go to `http://<ip-address>:5601` in your browser. OpenSearch Dashboards can take about 1 minute to start after the playbook finishes. + +## Rerunning the playbook + +The playbook restarts OpenSearch on all target hosts at the same time every time it runs, so the cluster is unavailable while the nodes restart. Plan reruns, for example, to apply configuration changes, for a maintenance window. + +By default, the playbook generates the TLS certificates on the control node in the `/tmp/opensearch-nodecerts` directory. When you rerun the playbook, it reuses the certificates and does not copy the security configuration to the target hosts again if this directory exists. If the directory doesn't exist, for example, because the control node was restarted and `/tmp` was cleared, the playbook generates a new root certificate authority (CA) and new node and admin certificates and copies them to all target hosts. Clients that verify the cluster's certificates then need the new `root-ca.pem` file. + +To manage an existing cluster using repeated playbook runs, set `iac_enable` to `true` in the `inventories/opensearch/group_vars/all/all.yml` file. In this mode, the playbook updates the configuration files on every run but copies new certificates only if at least one certificate is missing on at least one host, for example, when you add a host to the cluster. In that case, it replaces the certificates on all hosts. + +### Rotating certificates + +The generated certificates are valid for the number of days set in the `cert_valid_days` variable (default `730`). To replace them with new certificates, delete the `/tmp/opensearch-nodecerts` directory on the control node, make sure that `iac_enable` is `false`, and rerun the playbook. All nodes restart using the new certificates at the same time. + +## Upgrading a cluster installed using the playbook + +The playbook installs OpenSearch but doesn't upgrade it. Changing `os_version` and rerunning the playbook isn't a supported upgrade method for the following reasons: + +- The playbook downloads the OpenSearch archive to `/tmp/opensearch.tar.gz` on each target host and skips the download if that file exists. Unless `iac_enable` is `true`, the new version is not installed on hosts that still have the archive from the previous run. +- When the new version is installed, the playbook extracts it over the existing installation in `/usr/share/opensearch`, so files from the previous version that are not part of the new version remain in the installation directory. +- The playbook restarts all nodes at the same time instead of one node at a time. + +To upgrade a cluster installed using the playbook, upgrade the nodes one at a time by following the [rolling upgrade]({{site.url}}{{site.baseurl}}/migrate-or-upgrade/rolling-upgrade/) procedure. The playbook installs OpenSearch in `/usr/share/opensearch` and stores the configuration, certificates, and Security plugin configuration in `/usr/share/opensearch/config`. Preserve these files when you install the new version on each node. After you upgrade all nodes, update `os_version` and `os_dashboards_version` in `inventories/opensearch/group_vars/all/all.yml` to match the installed version. + +## Related documentation + +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) +- [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production) diff --git a/_install-and-configure/install-opensearch/debian.md b/_install-and-configure/install-opensearch/debian.md index 6f9167a1..d1291d29 100644 --- a/_install-and-configure/install-opensearch/debian.md +++ b/_install-and-configure/install-opensearch/debian.md @@ -4,7 +4,7 @@ title: Debian parent: Installing OpenSearch redirect_from: - /opensearch/install/deb/ -nav_order: 55 +nav_order: 20 --- {% comment %} @@ -13,9 +13,9 @@ The following liquid syntax declares a variable, major_version_mask, which is tr {% assign version_parts = site.opensearch_major_minor_version | split: "." %} {% assign major_version_mask = version_parts[0] | append: ".x" %} -# Debian +# Installing OpenSearch on Debian -Installing OpenSearch using the Advanced Packaging Tool (APT) package manager simplifies the process considerably compared to the [Tarball]({{site.url}}{{site.baseurl}}/opensearch/install/tar/) method. Several technical considerations, such as the installation path, location of configuration files, and creation of a service managed by `systemd`, as examples, are handled automatically by the package manager. +Installing OpenSearch using the Advanced Packaging Tool (APT) package manager simplifies the process considerably compared to the [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/) method. Several technical considerations, such as the installation path, location of configuration files, and creation of a service managed by `systemd`, as examples, are handled automatically by the package manager. Generally speaking, installing OpenSearch from the Debian distribution can be broken down into a few steps: @@ -34,39 +34,64 @@ This guide assumes that you are comfortable working from the Linux command line ## Step 1: Download and install OpenSearch +You can install OpenSearch from a package or an APT repository. + ### Install OpenSearch from a package 1. Download the Debian package for the desired version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. The Debian package can be downloaded for both **x64** and **arm64** architectures. -1. From the CLI, install using `dpkg`. +1. From the CLI, install the package using `dpkg`. + + For new installations of OpenSearch 3.7 and later, you can use the following installation-time environment variables to control the Security plugin behavior: + * `DISABLE_INSTALL_DEMO_CONFIG=true` -- Prevents the installer from setting up demo security configuration (certificates, users, and roles). Use this for installations where you will configure security manually. + * `DISABLE_SECURITY_PLUGIN=true` -- Disables the Security plugin entirely. Only use this for testing or development environments where security is not required. + + To use these environment variables, add them before the installation command with the `env` keyword: ```bash - # x64 - sudo dpkg -i opensearch-{{site.opensearch_version}}-linux-x64.deb - - # arm64 - sudo dpkg -i opensearch-{{site.opensearch_version}}-linux-arm64.deb + sudo env DISABLE_INSTALL_DEMO_CONFIG=true dpkg -i opensearch-{{site.opensearch_version}}-linux-x64.deb ``` - For OpenSearch 2.12 and greater, a custom admin password is required in order to set up a security demo configuration. To set a custom admin password, use one the following commands: + {% include copy.html %} + + For new installations of OpenSearch 2.12 and later, you must define a custom admin password in order to set up a demo security configuration. OpenSearch uses this password only when it sets up the demo security configuration. To change the admin password later, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). Use one of the following commands to define a custom admin password: + + x64: ```bash - # x64 sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> dpkg -i opensearch-{{site.opensearch_version}}-linux-x64.deb - - # arm64 + ``` + {% include copy.html %} + + arm64: + ```bash sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> dpkg -i opensearch-{{site.opensearch_version}}-linux-arm64.deb ``` + {% include copy.html %} -1. After the installation succeeds, enable OpenSearch as a service. + Use the following commands for OpenSearch versions 2.11 and earlier. + + x64: + ```bash + sudo dpkg -i opensearch-<version>-linux-x64.deb + ``` + {% include copy.html %} + + arm64: + ```bash + sudo dpkg -i opensearch-<version>-linux-arm64.deb + ``` + {% include copy.html %} + +1. After the installation succeeds, enable OpenSearch as a service: ```bash sudo systemctl enable opensearch ``` {% include copy.html %} -1. Start the OpenSearch service. +1. Start the OpenSearch service: ```bash sudo systemctl start opensearch ``` {% include copy.html %} -1. Verify that OpenSearch launched correctly. +1. Verify that OpenSearch launched correctly: ```bash sudo systemctl status opensearch ``` @@ -76,25 +101,25 @@ This guide assumes that you are comfortable working from the Linux command line The Debian package is not signed. If you would like to verify the fingerprint, the OpenSearch Project provides a `.sig` file as well as the `.deb` package for use with GNU Privacy Guard (GPG). -1. Download the desired Debian package. +1. Download the desired Debian package: ```bash curl -SLO https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-linux-x64.deb ``` {% include copy.html %} -1. Download the corresponding signature file. +1. Download the corresponding signature file: ```bash curl -SLO https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-linux-x64.deb.sig ``` {% include copy.html %} -1. Download and import the GPG key. +1. Download and import the GPG key: ```bash - curl -o- https://artifacts.opensearch.org/publickeys/opensearch.pgp | gpg --import - + curl -o- https://artifacts.opensearch.org/publickeys/opensearch-release.pgp | gpg --import - ``` {% include copy.html %} -1. Verify the signature. +1. Verify the signature: ```bash gpg --verify opensearch-{{site.opensearch_version}}-linux-x64.deb.sig opensearch-{{site.opensearch_version}}-linux-x64.deb ``` @@ -104,68 +129,102 @@ The Debian package is not signed. If you would like to verify the fingerprint, t APT, the primary package management tool for Debian–based operating systems, allows you to download and install the Debian package from the APT repository. -1. Install the necessary packages. +1. Install the necessary packages: ```bash sudo apt-get update && sudo apt-get -y install lsb-release ca-certificates curl gnupg2 ``` {% include copy.html %} +1. Create the keyrings directory if it doesn't already exist: + ```bash + sudo mkdir -p /etc/apt/keyrings + ``` + {% include copy.html %} + 1. Import the public GPG key. This key is used to verify that the APT repository is signed. ```bash - curl -o- https://artifacts.opensearch.org/publickeys/opensearch.pgp | sudo gpg --dearmor --batch --yes -o /usr/share/keyrings/opensearch-keyring + curl -fsSL https://artifacts.opensearch.org/publickeys/opensearch-release.pgp \ + | sudo gpg --dearmor -o /etc/apt/keyrings/opensearch.gpg ``` {% include copy.html %} 1. Create an APT repository for OpenSearch: ```bash - echo "deb [signed-by=/usr/share/keyrings/opensearch-keyring] https://artifacts.opensearch.org/releases/bundle/opensearch/2.x/apt stable main" | sudo tee /etc/apt/sources.list.d/opensearch-2.x.list + echo "deb [signed-by=/etc/apt/keyrings/opensearch.gpg] https://artifacts.opensearch.org/releases/bundle/opensearch/{{major_version_mask}}/apt stable main" \ + | sudo tee /etc/apt/sources.list.d/opensearch-{{major_version_mask}}.list ``` {% include copy.html %} -1. Verify that the repository was created successfully. +1. Verify that the repository was created successfully: ```bash sudo apt-get update ``` {% include copy.html %} +1. (Optional) As of May 22, 2024, the `Origin` and `Label` values of the APT repository were updated as part of [this change](https://github.com/opensearch-project/opensearch-build/issues/4485). If you created the APT repository before this date, run the following command to accept the updated release information: + ```bash + sudo apt-get update --allow-releaseinfo-change + ``` + {% include copy.html %} + 1. With the repository information added, list all available versions of OpenSearch: ```bash sudo apt list -a opensearch ``` {% include copy.html %} -1. Choose the version of OpenSearch you want to install: +1. Choose the version of OpenSearch you want to install: - Unless otherwise indicated, the latest available version of OpenSearch is installed. + + For new installations of OpenSearch 2.12 and later, you must define a custom admin password in order to set up a demo security configuration: + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> apt-get install opensearch + ``` + {% include copy.html %} + + For more information, see the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). + {: .note} + + - To install a specific version of OpenSearch. + + For new installations of OpenSearch 2.12 and later, you must define a custom admin password in order to set up a demo security configuration: + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> apt-get install opensearch={{site.opensearch_version}} + ``` + {% include copy.html %} + + Use the following command for OpenSearch versions 2.11 and earlier: + ```bash + sudo apt-get install opensearch=<version> + ``` + {% include copy.html %} + +1. If the installation succeeds, it means APT has validated that the repository metadata was signed with a trusted GPG key. To manually confirm that the key you imported matches the official OpenSearch release key, execute the following command: + ```bash - sudo apt-get install opensearch + gpg --no-default-keyring --keyring /etc/apt/keyrings/opensearch.gpg --fingerprint ``` {% include copy.html %} - - To install a specific version of OpenSearch: - ```bash - # Specify the version manually using opensearch=<version> - sudo apt-get install opensearch={{site.opensearch_version}} + In the output you should see the following snippet: + ```text + pub rsa4096 2025-03-06 [SC] + A8B2 D9E0 4CD5 1FEF 6AA2 DB53 BA81 D999 8119 1457 ``` -1. During installation, the installer will present you with the GPG key fingerprint. Verify that the information matches the following: - ```bash - Fingerprint: c5b7 4989 65ef d1c2 924b a9d5 39d3 1987 9310 d3fc - ``` - {% include copy.html %} - -1. Once complete, enable OpenSearch. +1. Once complete, enable OpenSearch: ```bash sudo systemctl enable opensearch ``` {% include copy.html %} -1. Start OpenSearch. +1. Start OpenSearch: ```bash sudo systemctl start opensearch ``` {% include copy.html %} -1. Verify that OpenSearch launched correctly. +1. Verify that OpenSearch launched correctly: ```bash sudo systemctl status opensearch ``` @@ -177,7 +236,7 @@ Before proceeding with any configuration, you should test your installation of O When OpenSearch is installed using the Debian package, some demo security settings are automatically applied. This includes self-signed TLS certificates and several users and roles. If you would like to configure these yourself, see [Set up OpenSearch in your environment](#step-3-set-up-opensearch-in-your-environment). -An OpenSearch node in its default configuration (with demo certificates and users with default passwords) is not suitable for a production environment. If you plan to use the node in a production environment, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security-plugin/configuration/yaml). See [Security configuration]({{site.url}}{{site.baseurl}}/security-plugin/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. +An OpenSearch node in its default configuration (with demo certificates and users with default passwords) is not suitable for a production environment. If you plan to use the node in a production environment, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security-plugin/configuration/yaml/). See [Security configuration]({{site.url}}{{site.baseurl}}/security-plugin/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. {: .warning} 1. Send requests to the server to verify that OpenSearch is running. Note the use of the `--insecure` flag, which is required because the TLS certificates are self-signed. @@ -188,7 +247,7 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} You should get a response that looks like this: - ```bash + ```json { "name":"hostname", "cluster_name":"opensearch", @@ -214,16 +273,19 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} The response should look like this: - ```bash + ```text name component version hostname opensearch-alerting {{site.opensearch_version}} hostname opensearch-anomaly-detection {{site.opensearch_version}} hostname opensearch-asynchronous-search {{site.opensearch_version}} hostname opensearch-cross-cluster-replication {{site.opensearch_version}} + hostname opensearch-custom-codecs {{site.opensearch_version}} + hostname opensearch-flow-framework {{site.opensearch_version}} hostname opensearch-geospatial {{site.opensearch_version}} hostname opensearch-index-management {{site.opensearch_version}} hostname opensearch-job-scheduler {{site.opensearch_version}} hostname opensearch-knn {{site.opensearch_version}} + hostname opensearch-ltr {{site.opensearch_version}} hostname opensearch-ml {{site.opensearch_version}} hostname opensearch-neural-search {{site.opensearch_version}} hostname opensearch-notifications {{site.opensearch_version}} @@ -231,9 +293,14 @@ An OpenSearch node in its default configuration (with demo certificates and user hostname opensearch-observability {{site.opensearch_version}} hostname opensearch-performance-analyzer {{site.opensearch_version}} hostname opensearch-reports-scheduler {{site.opensearch_version}} + hostname opensearch-search-relevance {{site.opensearch_version}} hostname opensearch-security {{site.opensearch_version}} hostname opensearch-security-analytics {{site.opensearch_version}} + hostname opensearch-skills {{site.opensearch_version}} hostname opensearch-sql {{site.opensearch_version}} + hostname opensearch-system-templates {{site.opensearch_version}} + hostname opensearch-ubi {{site.opensearch_version}} + hostname query-insights {{site.opensearch_version}} ``` ## Step 3: Set up OpenSearch in your environment @@ -254,41 +321,61 @@ If you ran the security demo script, then you will need to manually reconfigure Before modifying any configuration files, it's always a good idea to save a backup copy before making changes. The backup file can be used to mitigate any issues caused by a bad configuration. {:.tip} -1. Open `opensearch.yml`. +1. Open `opensearch.yml`: ```bash sudo vi /etc/opensearch/opensearch.yml ``` {% include copy.html %} -1. Add the following lines: - ```bash - # Bind OpenSearch to the correct network interface. Use 0.0.0.0 - # to include all available interfaces or specify an IP address - # assigned to a specific interface. +1. Replace the content with the following lines. + + Path to directory where to store the data (separate multiple locations by comma): + ```yaml + path.data: /var/lib/opensearch + ``` + {% include copy.html %} + + Path to log files: + ```yaml + path.logs: /var/log/opensearch + ``` + {% include copy.html %} + + Bind OpenSearch to the correct network interface. Use 0.0.0.0 to include all available interfaces or specify an IP address assigned to a specific interface: + ```yaml network.host: 0.0.0.0 + ``` + {% include copy.html %} - # Unless you have already configured a cluster, you should set - # discovery.type to single-node, or the bootstrap checks will - # fail when you try to start the service. + Unless you have already configured a cluster, you should set discovery.type to single-node, or the bootstrap checks will fail when you try to start the service: + ```yaml discovery.type: single-node + ``` + {% include copy.html %} - # If you previously disabled the Security plugin in opensearch.yml, - # be sure to re-enable it. Otherwise you can skip this setting. + If you configure a multi-node cluster instead, set `vm.max_map_count` to at least `262144` on the host. Otherwise, the bootstrap checks fail when the service starts. For more information, see [Important settings]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#important-settings). + + If you previously disabled the Security plugin in opensearch.yml, be sure to reenable it. Otherwise you can skip this setting: + ```yaml plugins.security.disabled: false ``` {% include copy.html %} + The [Configure TLS](#configure-tls) section provides guidance on adding the custom TLS configuration. + 1. Save your changes and close the file. 1. Specify initial and maximum JVM heap sizes. - 1. Open `jvm.options`. + 1. Open `jvm.options`: + ```bash - vi /etc/opensearch/jvm.options + sudo vi /etc/opensearch/jvm.options ``` {% include copy.html %} 1. Modify the values for initial and maximum heap sizes. As a starting point, you should set these values to half of the available system memory. For dedicated hosts this value can be increased based on your workflow requirements. - As an example, if the host machine has 8 GB of memory, then you might want to set the initial and maximum heap sizes to 4 GB: - ```bash + + ```text -Xms4g -Xmx4g ``` @@ -300,80 +387,103 @@ Before modifying any configuration files, it's always a good idea to save a back TLS certificates provide additional security for your cluster by allowing clients to confirm the identity of hosts and encrypt traffic between the client and host. For more information, refer to [Configure TLS Certificates]({{site.url}}{{site.baseurl}}/security-plugin/configuration/tls/) and [Generate Certificates]({{site.url}}{{site.baseurl}}/security-plugin/configuration/generate-certificates/), which are included in the [Security plugin]({{site.url}}{{site.baseurl}}/security-plugin/index/) documentation. For work performed in a development environment, self-signed certificates are usually adequate. This section will guide you through the basic steps required to generate your own TLS certificates and apply them to your OpenSearch host. -1. Navigate to the directory where the certificates will be stored. - ```bash - cd /etc/opensearch - ``` - {% include copy.html %} +1. Delete the demo certificates: -1. Delete the demo certificates. ```bash - sudo rm -f *pem + sudo sh -c 'rm /etc/opensearch/*.pem' ``` {% include copy.html %} 1. Generate a root certificate. This is what you will use to sign your other certificates. + + Create a private key for the root certificate: ```bash - # Create a private key for the root certificate - sudo openssl genrsa -out root-ca-key.pem 2048 - - # Use the private key to create a self-signed root certificate. Be sure to - # replace the arguments passed to -subj so they reflect your specific host. - sudo openssl req -new -x509 -sha256 -key root-ca-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=ROOT" -out root-ca.pem -days 730 + sudo openssl genrsa -out /etc/opensearch/root-ca-key.pem 2048 ``` + {% include copy.html %} + + Use the private key to create a self-signed root certificate. Be sure to replace the arguments passed to -subj so they reflect your specific host: + ```bash + sudo openssl req -new -x509 -sha256 -key /etc/opensearch/root-ca-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=ROOT" -out /etc/opensearch/root-ca.pem -days 730 + ``` + {% include copy.html %} + 1. Next, create the admin certificate. This certificate is used to gain elevated rights for performing administrative tasks relating to the Security plugin. - ```bash - # Create a private key for the admin certificate. - sudo openssl genrsa -out admin-key-temp.pem 2048 - # Convert the private key to PKCS#8. - sudo openssl pkcs8 -inform PEM -outform PEM -in admin-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out admin-key.pem - - # Create the certficiate signing request (CSR). A common name (CN) of "A" is acceptable because this certificate is - # used for authenticating elevated access and is not tied to a host. - sudo openssl req -new -key admin-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=A" -out admin.csr - - # Sign the admin certificate with the root certificate and private key you created earlier. - sudo openssl x509 -req -in admin.csr -CA root-ca.pem -CAkey root-ca-key.pem -CAcreateserial -sha256 -out admin.pem -days 730 + Create a private key for the admin certificate: + ```bash + sudo openssl genrsa -out /etc/opensearch/admin-key-temp.pem 2048 ``` + {% include copy.html %} + + Convert the private key to PKCS#8: + ```bash + sudo openssl pkcs8 -inform PEM -outform PEM -in /etc/opensearch/admin-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out /etc/opensearch/admin-key.pem + ``` + {% include copy.html %} + + Create the certificate signing request (CSR). A common name (CN) of "A" is acceptable because this certificate is used for authenticating elevated access and is not tied to a host: + ```bash + sudo openssl req -new -key /etc/opensearch/admin-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=A" -out /etc/opensearch/admin.csr + ``` + {% include copy.html %} + + Sign the admin certificate with the root certificate and private key you created earlier: + ```bash + sudo openssl x509 -req -in /etc/opensearch/admin.csr -CA /etc/opensearch/root-ca.pem -CAkey /etc/opensearch/root-ca-key.pem -CAcreateserial -sha256 -out /etc/opensearch/admin.pem -days 730 + ``` + {% include copy.html %} + 1. Create a certificate for the node being configured. - ```bash - # Create a private key for the node certificate. - sudo openssl genrsa -out node1-key-temp.pem 2048 - - # Convert the private key to PKCS#8. - sudo openssl pkcs8 -inform PEM -outform PEM -in node1-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out node1-key.pem - # Create the CSR and replace the arguments passed to -subj so they reflect your specific host. - # The CN should match a DNS A record for the host-do not use the hostname. - sudo openssl req -new -key node1-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=node1.dns.a-record" -out node1.csr - - # Create an extension file that defines a SAN DNS name for the host. This - # should match the DNS A record of the host. - sudo sh -c 'echo subjectAltName=DNS:node1.dns.a-record > node1.ext' - - # Sign the node certificate with the root certificate and private key that you created earlier. - sudo openssl x509 -req -in node1.csr -CA root-ca.pem -CAkey root-ca-key.pem -CAcreateserial -sha256 -out node1.pem -days 730 -extfile node1.ext - ``` -1. Remove temporary files that are no longer required. + Create a private key for the node certificate: ```bash - sudo rm -f *temp.pem *csr *ext + sudo openssl genrsa -out /etc/opensearch/node1-key-temp.pem 2048 ``` {% include copy.html %} -1. Make sure the remaining certificates are owned by the opensearch user. + Convert the private key to PKCS#8: ```bash - sudo chown opensearch:opensearch admin-key.pem admin.pem node1-key.pem node1.pem root-ca-key.pem root-ca.pem root-ca.srl + sudo openssl pkcs8 -inform PEM -outform PEM -in /etc/opensearch/node1-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out /etc/opensearch/node1-key.pem ``` {% include copy.html %} -1. Add these certificates to `opensearch.yml` as described in [Generate Certificates]({{site.url}}{{site.baseurl}}/security-plugin/configuration/generate-certificates/#add-distinguished-names-to-opensearchyml). Advanced users might also choose to append the settings using a script: + Create the CSR and replace the arguments passed to -subj so they reflect your specific host. The CN should match a DNS A record for the host-do not use the hostname: + ```bash + sudo openssl req -new -key /etc/opensearch/node1-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=node1.dns.a-record" -out /etc/opensearch/node1.csr + ``` + {% include copy.html %} + + Create an extension file that defines a SAN DNS name for the host. This should match the DNS A record of the host: + ```bash + sudo sh -c 'echo subjectAltName=DNS:node1.dns.a-record > /etc/opensearch/node1.ext' + ``` + {% include copy.html %} + + Sign the node certificate with the root certificate and private key that you created earlier: + ```bash + sudo openssl x509 -req -in /etc/opensearch/node1.csr -CA /etc/opensearch/root-ca.pem -CAkey /etc/opensearch/root-ca-key.pem -CAcreateserial -sha256 -out /etc/opensearch/node1.pem -days 730 -extfile /etc/opensearch/node1.ext + ``` + {% include copy.html %} + +1. Remove temporary files that are no longer required: + + ```bash + sudo sh -c 'rm -f /etc/opensearch/*temp.pem /etc/opensearch/*.csr /etc/opensearch/*.ext' + ``` + {% include copy.html %} + +1. Make sure the remaining certificates are owned by the `opensearch` user: + + ```bash + sudo chown opensearch:opensearch /etc/opensearch/admin-key.pem /etc/opensearch/admin.pem /etc/opensearch/node1-key.pem /etc/opensearch/node1.pem /etc/opensearch/root-ca-key.pem /etc/opensearch/root-ca.pem /etc/opensearch/root-ca.srl + ``` + {% include copy.html %} + +1. Add these certificates to `/etc/opensearch/opensearch.yml` as described in [Generate Certificates]({{site.url}}{{site.baseurl}}/security-plugin/configuration/generate-certificates/#add-distinguished-names-to-opensearchyml). Advanced users might also choose to append the settings using the following script. Before running this script, make sure to replace the CN in the node's distinguished name with a real DNS A record: ```bash #! /bin/bash - # Before running this script, make sure to replace the CN in the - # node's distinguished name with a real DNS A record. - echo "plugins.security.ssl.transport.pemcert_filepath: /etc/opensearch/node1.pem" | sudo tee -a /etc/opensearch/opensearch.yml echo "plugins.security.ssl.transport.pemkey_filepath: /etc/opensearch/node1-key.pem" | sudo tee -a /etc/opensearch/opensearch.yml echo "plugins.security.ssl.transport.pemtrustedcas_filepath: /etc/opensearch/root-ca.pem" | sudo tee -a /etc/opensearch/opensearch.yml @@ -394,19 +504,25 @@ TLS certificates provide additional security for your cluster by allowing client {% include copy.html %} 1. (Optional) Add trust for the self-signed root certificate. + + Copy the root certificate to the correct directory: ```bash - # Copy the root certificate to the correct directory - sudo cp /etc/opensearch/root-ca.pem /etc/pki/ca-trust/source/anchors/ - - # Add trust - sudo update-ca-trust + sudo install -m 0644 /etc/opensearch/root-ca.pem /usr/local/share/ca-certificates/root-ca.crt ``` + {% include copy.html %} + + Add trust: + ```bash + sudo update-ca-certificates + ``` + {% include copy.html %} ### Configure a user -Users are defined and authenticated by OpenSearch in a variety of ways. One method that does not require additional backend infrastructure is to manually configure users in `internal_users.yml`. See [YAML files]({{site.url}}{{site.baseurl}}/security-plugin/configuration/yaml/) for more information about configuring users. The following steps explain how to add a new internal user and how to replace the `admin` default password using a script. +Users are defined and authenticated by OpenSearch in a variety of ways. One method that does not require additional backend infrastructure is manually configuring users in `internal_users.yml`. See [YAML files]({{site.url}}{{site.baseurl}}/security-plugin/configuration/yaml/) for more information about configuring users. The following steps explain how to replace the `admin` default password using a script: + +1. Navigate to the Security plugins tools directory: -1. Navigate to the Security plugins tools directory. ```bash cd /usr/share/opensearch/plugins/opensearch-security/tools ``` @@ -414,15 +530,16 @@ Users are defined and authenticated by OpenSearch in a variety of ways. One meth 1. Run `hash.sh` to generate a new password. - This script will fail if a path to the JDK has not been defined. - ```bash - # Example output if a JDK isn't found... + + Example output if a JDK isn't found: + ```text $ ./hash.sh ************************************************************************** ** This tool will be deprecated in the next major release of OpenSearch ** ** https://github.com/opensearch-project/security/issues/1755 ** ************************************************************************** which: no java in (/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/user/.local/bin:/home/user/bin) - WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use + WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use ./hash.sh: line 35: java: command not found ``` {% include copy.html %} @@ -434,14 +551,16 @@ Users are defined and authenticated by OpenSearch in a variety of ways. One meth {% include copy.html %} - Enter the desired password at the prompt and make a note of the output hash. -1. Open `internal_users.yml`. +1. Open `internal_users.yml`: + ```bash sudo vi /etc/opensearch/opensearch-security/internal_users.yml ``` {% include copy.html %} -1. Add a new internal user and replace the hash inside `internal_users.yml` with the output provided by `hash.sh` in step 2. The file should look similar to the following example: - ```bash +1. Replace the admin password hash in `internal_users.yml` with the output provided by `hash.sh` in step 2. The file should appear similar to the following example: + + ```yaml --- # This is the internal user database # The hash value is a bcrypt hash and can be generated with plugin/tools/hash.sh @@ -465,7 +584,7 @@ Users are defined and authenticated by OpenSearch in a variety of ways. One meth backend_roles: [] description: "New internal user" - # Other users + # Other users ... ``` {% include copy.html %} @@ -474,21 +593,21 @@ Users are defined and authenticated by OpenSearch in a variety of ways. One meth Now that TLS certificates are installed and demo users were removed or assigned new passwords, the last step is to apply the configuration changes. This last configuration step requires invoking `securityadmin.sh` while OpenSearch is running on the host. -1. OpenSearch must be running for `securityadmin.sh` to apply changes. If you made changes to `opensearch.yml`, restart OpenSearch. +1. OpenSearch must be running for `securityadmin.sh` to apply changes. If you made changes to `opensearch.yml`, restart OpenSearch: ```bash sudo systemctl restart opensearch ``` {% include copy.html %} -1. Open a separate terminal session with the host and navigate to the directory containing `securityadmin.sh`. +1. Navigate to the directory containing `securityadmin.sh`: ```bash - # Change to the correct directory cd /usr/share/opensearch/plugins/opensearch-security/tools ``` -1. Invoke the script. See [Apply changes using securityadmin.sh]({{site.url}}{{site.baseurl}}/security-plugin/configuration/security-admin/) for definitions of the arguments you must pass. + {% include copy.html %} + +1. Invoke the script. See [Apply changes using securityadmin.sh]({{site.url}}{{site.baseurl}}/security-plugin/configuration/security-admin/) for definitions of the arguments you must pass. You can omit the environment variable if you declared this in your $PATH: ```bash - # You can omit the environment variable if you declared this in your $PATH. - OPENSEARCH_JAVA_HOME=/usr/share/opensearch/jdk ./securityadmin.sh -cd /etc/opensearch/opensearch-security/ -cacert /etc/opensearch/root-ca.pem -cert /etc/opensearch/admin.pem -key /etc/opensearch/admin-key.pem -icl -nhnv + sudo OPENSEARCH_JAVA_HOME=/usr/share/opensearch/jdk ./securityadmin.sh -cd /etc/opensearch/opensearch-security/ -cacert /etc/opensearch/root-ca.pem -cert /etc/opensearch/admin.pem -key /etc/opensearch/admin-key.pem -icl -nhnv ``` {% include copy.html %} @@ -502,7 +621,13 @@ You should add trust for the root certificate to your client before sending requ {:.tip} ```bash -$ curl https://your.host.address:9200 -u admin:yournewpassword -k +curl https://localhost:9200 -u admin:<yournewpassword> -k +``` +{% include copy.html %} + +You should receive the following response: + +```json { "name":"hostname", "cluster_name":"opensearch", @@ -526,33 +651,50 @@ $ curl https://your.host.address:9200 -u admin:yournewpassword -k OpenSearch instances installed using `dpkg` or `apt-get` can be easily upgraded to a newer version. -### Manual upgrade with DPKG +### Upgrade manually using `dpkg` -Download the Debian package for the desired upgrade version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. +Download the Debian package for the desired upgrade version directly from the [OpenSearch Project downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. Navigate to the directory containing the distribution and run the following command: + ```bash sudo dpkg -i opensearch-{{site.opensearch_version}}-linux-x64.deb ``` {% include copy.html %} -### APT-GET +### Upgrade using `apt-get` + +To upgrade to the newest available version of OpenSearch, run the following command: -To upgrade to the latest version of OpenSearch using `apt-get`: ```bash -sudo apt-get upgrade opensearch +sudo apt-get install --only-upgrade opensearch ``` {% include copy.html %} -You can also upgrade to a specific OpenSearch version: +You can also upgrade to a specific OpenSearch version by providing the version number: + ```bash -sudo apt-get upgrade opensearch=<version> +sudo apt-get install opensearch=<version> ``` {% include copy.html %} -## Related links +The `apt-get upgrade` subcommand acts on every installed package on the host. The `--only-upgrade` option limits the operation to the `opensearch` package. +{: .note} +### Automatically restart the service after a package upgrade + +To automatically restart OpenSearch after a package upgrade, enable the `opensearch.service` through `systemd`: + +```bash +sudo systemctl enable opensearch.service +``` +{% include copy.html %} + +## Related documentation + +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) +- [Common installation issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#common-issues) - [OpenSearch configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) - [Install and configure OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) -- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/opensearch/install/plugins/) +- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) - [About the Security plugin]({{site.url}}{{site.baseurl}}/security-plugin/index/) diff --git a/_install-and-configure/install-opensearch/docker.md b/_install-and-configure/install-opensearch/docker.md index 189d647c..d0a46dac 100644 --- a/_install-and-configure/install-opensearch/docker.md +++ b/_install-and-configure/install-opensearch/docker.md @@ -5,14 +5,13 @@ parent: Installing OpenSearch nav_order: 5 redirect_from: - /opensearch/install/docker/ - - /install-and-configure/install-opensearch/docker/ --- -# Docker +# Installing OpenSearch using Docker [Docker](https://www.docker.com/) greatly simplifies the process of configuring and managing your OpenSearch clusters. You can pull official images from [Docker Hub](https://hub.docker.com/u/opensearchproject) or [Amazon Elastic Container Registry (Amazon ECR)](https://gallery.ecr.aws/opensearchproject/) and quickly deploy a cluster using [Docker Compose](https://github.com/docker/compose) and any of the sample Docker Compose files included in this guide. Experienced OpenSearch users can further customize their deployment by creating a custom Docker Compose file. -Docker containers are portable and will run on any compatible host that supports Docker (such as Linux, MacOS, or Windows). The portability of a Docker container offers flexibility over other installations methods, like [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/) or a manual [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/) installation, which both require additional configuration after downloading and unpacking. +Docker containers are portable and will run on any compatible host that supports Docker (such as Linux, macOS, or Windows). The portability of a Docker container offers flexibility over other installations methods, like [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/) or a manual [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/) installation, which both require additional configuration after downloading and unpacking. This guide assumes that you are comfortable working from the Linux command line interface (CLI). You should understand how to input commands, navigate between directories, and edit text files. For help with [Docker](https://www.docker.com/) or [Docker Compose](https://github.com/docker/compose), refer to the official documentation on their websites. {:.note} @@ -26,7 +25,7 @@ Docker Desktop users should set host memory utilization to a minimum of 4 GB by Docker Compose is a utility that allows users to launch multiple containers with a single command. You pass a file to Docker Compose when you invoke it. Docker Compose reads those settings and starts the requested containers. Docker Compose is installed automatically with Docker Desktop, but users operating in a command line environment must install Docker Compose manually. You can find information about installing Docker Compose on the official [Docker Compose GitHub page](https://github.com/docker/compose). -If you need to install Docker Compose manually and your host supports Python, you can use [pip](https://pypi.org/project/pip/) to install the [Docker Compose package](https://pypi.org/project/docker-compose/) automatically. +On Linux, you can install Docker Compose as a Docker plugin. For more information, see [Install the Docker Compose plugin](https://docs.docker.com/compose/install/linux/). The examples in this guide use the `docker compose` command provided by the plugin. {: .tip} ## Configure important host settings @@ -35,34 +34,55 @@ Before installing OpenSearch using Docker, configure the following settings. The ### Linux settings For a Linux environment, run the following commands: -1. Disable memory paging and swapping performance on the host to improve performance. +1. Disable memory paging and swapping performance on the host to improve performance: + ```bash sudo swapoff -a ``` -1. Increase the number of memory maps available to OpenSearch. + {% include copy.html %} + +1. Increase the number of memory maps available to OpenSearch. Open the `sysctl` configuration file: + ```bash - # Edit the sysctl config file sudo vi /etc/sysctl.conf + ``` + {% include copy.html %} - # Add a line to define the desired value - # or change the value if the key exists, - # and then save your changes. + Add the following line, or change the value if the setting already exists, and then save your changes: + + ```bash vm.max_map_count=262144 + ``` + {% include copy.html %} - # Reload the kernel parameters using sysctl + Reload the kernel parameters: + + ```bash sudo sysctl -p + ``` + {% include copy.html %} - # Verify that the change was applied by checking the value + Verify that the change was applied by checking the value: + + ```bash cat /proc/sys/vm/max_map_count ``` + {% include copy.html %} ### Windows settings -For Windows workloads using WSL through Docker Desktop, run the following commands in a terminal to set the `vm.max_map_count`: +For Windows workloads using WSL through Docker Desktop, set `vm.max_map_count` in the Docker Desktop WSL distribution. First, open a shell in the distribution: ```bash wsl -d docker-desktop +``` +{% include copy.html %} + +Then set the value: + +```bash sysctl -w vm.max_map_count=262144 -``` +``` +{% include copy.html %} ## Run OpenSearch in a Docker container @@ -70,23 +90,23 @@ Official OpenSearch images are hosted on [Docker Hub](https://hub.docker.com/u/o [Docker Hub](https://hub.docker.com/u/opensearchproject/): ```bash -docker pull opensearchproject/opensearch:2 +docker pull opensearchproject/opensearch:{{ site.opensearch_version | split: "." | first }} ``` {% include copy.html %} ```bash -docker pull opensearchproject/opensearch-dashboards:2 +docker pull opensearchproject/opensearch-dashboards:{{ site.opensearch_version | split: "." | first }} ``` {% include copy.html %} [Amazon ECR](https://gallery.ecr.aws/opensearchproject/): ```bash -docker pull public.ecr.aws/opensearchproject/opensearch:2 +docker pull public.ecr.aws/opensearchproject/opensearch:{{ site.opensearch_version | split: "." | first }} ``` {% include copy.html %} ```bash -docker pull public.ecr.aws/opensearchproject/opensearch-dashboards:2 +docker pull public.ecr.aws/opensearchproject/opensearch-dashboards:{{ site.opensearch_version | split: "." | first }} ``` {% include copy.html %} @@ -95,18 +115,19 @@ To download a specific version of OpenSearch or OpenSearch Dashboards other than Before continuing, you should verify that Docker is working correctly by deploying OpenSearch in a single container. -1. Run the following command: +1. Start OpenSearch in Docker. + OpenSearch 2.12 or later requires that you set a custom admin password when starting. For more information, see [Setting a custom admin password](#setting-a-custom-admin-password). If the password is insufficiently strong, an error is reported in the log and OpenSearch quits: ```bash - # This command maps ports 9200 and 9600, sets the discovery type to "single-node" and requests the newest image of OpenSearch - docker run -d -p 9200:9200 -p 9600:9600 -e "discovery.type=single-node" opensearchproject/opensearch:latest + docker run -d -p 9200:9200 -e "discovery.type=single-node" -e "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" opensearchproject/opensearch:latest ``` - For OpenSearch 2.12 or greater, set a new custom admin password before installation using the following command: - ```bash - docker run -d -p 9200:9200 -p 9600:9600 -e "discovery.type=single-node" -e "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" opensearchproject/opensearch:latest - ``` -1. Send a request to port 9200. The default username and password are `admin`. + Older versions do not include a password when starting: ```bash - curl https://localhost:9200 -ku 'admin:<custom-admin-password>' + # This command maps port 9200, sets the discovery type to "single-node" and requests the newest image of OpenSearch + docker run -d -p 9200:9200 -e "discovery.type=single-node" opensearchproject/opensearch:latest + ``` +1. After waiting a few minutes for OpenSearch to start, send a request to port `9200`. For versions earlier than 2.12, the default username and password are `admin`. + ```bash + curl https://localhost:9200 -ku admin:"<custom-admin-password>" ``` {% include copy.html %} @@ -132,9 +153,15 @@ Before continuing, you should verify that Docker is working correctly by deployi ``` 1. Before stopping the running container, display a list of all running containers and copy the container ID for the OpenSearch node you are testing. In the following example, the container ID is `a937e018cee5`: ```bash - $ docker container ls + docker container ls + ``` + {% include copy.html %} + + The response lists the running containers: + + ```bash CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES - a937e018cee5 opensearchproject/opensearch:latest "./opensearch-docker…" 19 minutes ago Up 19 minutes 0.0.0.0:9200->9200/tcp, 9300/tcp, 0.0.0.0:9600->9600/tcp, 9650/tcp wonderful_boyd + a937e018cee5 opensearchproject/opensearch:latest "./opensearch-docker…" 19 minutes ago Up 19 minutes 0.0.0.0:9200->9200/tcp, 9300/tcp, 9600/tcp, 9650/tcp wonderful_boyd ``` 1. Stop the running container by passing the container ID to `docker stop`. ```bash @@ -142,7 +169,7 @@ Before continuing, you should verify that Docker is working correctly by deployi ``` {% include copy.html %} -Remember that `docker container ls` does not list stopped containers. If you would like to review stopped containers, use `docker container ls -a`. You can remove unneeded containers manually with `docker container rm <containerId_1> <containerId_2> <containerId_3> [...]` (pass all container IDs you wish to stop, separated by spaces), or if you want to remove all stopped containers, you can use the shorter command `docker container prune`. +Remember that `docker container ls` does not list stopped containers. If you would like to review stopped containers, use `docker container ls -a`. You can remove unneeded containers manually with `docker container rm <containerId_1> <containerId_2> <containerId_3> [...]` (pass all container IDs you want to stop, separated by spaces), or if you want to remove all stopped containers, you can use the shorter command `docker container prune`. {: .tip} ## Deploy an OpenSearch cluster using Docker Compose @@ -160,10 +187,10 @@ If none of those files exist in your current directory, the `docker-compose` com You can specify a custom file location and name when invoking `docker-compose` with the `-f` flag: ```bash # Use a relative or absolute path to the file. -docker-compose -f /path/to/your-file.yml up +docker compose -f /path/to/your-file.yml up ``` -If this is your first time launching an OpenSearch cluster using Docker Compose, use the following example `docker-compose.yml` file. Save it in the home directory of your host and name it `docker-compose.yml`. This file creates a cluster that contains three containers: two containers running the OpenSearch service and a single container running OpenSearch Dashboards. These containers communicate over a bridge network called `opensearch-net` and use two volumes, one for each OpenSearch node. Because this file does not explicitly disable the demo security configuration, self-signed TLS certificates are installed and internal users with default names and passwords are created. +If this is your first time launching an OpenSearch cluster using Docker Compose, use the [sample `docker-compose.yml` file](#sample-docker-composeyml). This file creates a cluster that contains three containers: two containers running the OpenSearch service and a single container running OpenSearch Dashboards. These containers communicate over a bridge network called `opensearch-net` and use two volumes, one for each OpenSearch node. Because this file does not explicitly disable the demo security configuration, self-signed TLS certificates are installed and internal users with default names and passwords are created. ### Setting a custom admin password @@ -177,113 +204,66 @@ Starting with OpenSearch 2.12, a custom admin password is required to set up a d - Create an `.env` file in the same folder as your `docker-compose.yml` file with the `OPENSEARCH_INITIAL_ADMIN_PASSWORD` and a strong password value. -### Sample docker-compose.yml +### Password requirements -```yml -version: '3' -services: - opensearch-node1: # This is also the hostname of the container within the Docker network (i.e. https://opensearch-node1/) - image: opensearchproject/opensearch:latest # Specifying the latest available image - modify if you want a specific version - container_name: opensearch-node1 - environment: - - cluster.name=opensearch-cluster # Name the cluster - - node.name=opensearch-node1 # Name the node that will run in this container - - discovery.seed_hosts=opensearch-node1,opensearch-node2 # Nodes to look for when discovering the cluster - - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 # Nodes eligible to serve as cluster manager - - bootstrap.memory_lock=true # Disable JVM heap memory swapping - - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # Set min and max JVM heap sizes to at least 50% of system RAM - - OPENSEARCH_INITIAL_ADMIN_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} # Sets the demo admin user password when using demo configuration, required for OpenSearch 2.12 and later - ulimits: - memlock: - soft: -1 # Set memlock to unlimited (no soft or hard limit) - hard: -1 - nofile: - soft: 65536 # Maximum number of open files for the opensearch user - set to at least 65536 - hard: 65536 - volumes: - - opensearch-data1:/usr/share/opensearch/data # Creates volume called opensearch-data1 and mounts it to the container - ports: - - 9200:9200 # REST API - - 9600:9600 # Performance Analyzer - networks: - - opensearch-net # All of the containers will join the same Docker bridge network - opensearch-node2: - image: opensearchproject/opensearch:latest # This should be the same image used for opensearch-node1 to avoid issues - container_name: opensearch-node2 - environment: - - cluster.name=opensearch-cluster - - node.name=opensearch-node2 - - discovery.seed_hosts=opensearch-node1,opensearch-node2 - - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 - - bootstrap.memory_lock=true - - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" - - OPENSEARCH_INITIAL_ADMIN_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} - ulimits: - memlock: - soft: -1 - hard: -1 - nofile: - soft: 65536 - hard: 65536 - volumes: - - opensearch-data2:/usr/share/opensearch/data - networks: - - opensearch-net - opensearch-dashboards: - image: opensearchproject/opensearch-dashboards:latest # Make sure the version of opensearch-dashboards matches the version of opensearch installed on other nodes - container_name: opensearch-dashboards - ports: - - 5601:5601 # Map host port 5601 to container port 5601 - expose: - - "5601" # Expose port 5601 for web access to OpenSearch Dashboards - environment: - OPENSEARCH_HOSTS: '["https://opensearch-node1:9200","https://opensearch-node2:9200"]' # Define the OpenSearch nodes that OpenSearch Dashboards will query - networks: - - opensearch-net +The password you set in `OPENSEARCH_INITIAL_ADMIN_PASSWORD` must meet a minimum length, include several character classes, and pass an entropy-based strength check. For the full list, see [Admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). -volumes: - opensearch-data1: - opensearch-data2: +### Sample `docker-compose.yml` -networks: - opensearch-net: +Download the sample Docker Compose file to the home directory of your host. You can download the file using command line utilities like `curl` and `wget`, or you can manually copy [`docker-compose.yml`](https://github.com/opensearch-project/documentation-website/blob/{{site.opensearch_major_minor_version}}/assets/examples/docker-compose.yml) from the OpenSearch Project `documentation-website` repository using a web browser. + +To use cURL, send the following request: + +```bash +curl -O https://raw.githubusercontent.com/opensearch-project/documentation-website/{{site.opensearch_major_minor_version}}/assets/examples/docker-compose.yml ``` {% include copy.html %} +To use wget, send the following request: + +```bash +wget https://raw.githubusercontent.com/opensearch-project/documentation-website/{{site.opensearch_major_minor_version}}/assets/examples/docker-compose.yml +``` +{% include copy.html %} + +This file is based on the Docker Compose files maintained in the [`opensearch-build` repository](https://github.com/opensearch-project/opensearch-build/tree/main/docker/release/dockercomposefiles). + If you override `opensearch_dashboards.yml` settings using environment variables in your compose file, use all uppercase letters and replace periods with underscores (for example, for `opensearch.hosts`, use `OPENSEARCH_HOSTS`). This behavior is inconsistent with overriding `opensearch.yml` settings, where the conversion is just a change to the assignment operator (for example, `discovery.type: single-node` in `opensearch.yml` is defined as `discovery.type=single-node` in `docker-compose.yml`). {: .note} From the home directory of your host (containing `docker-compose.yml`), create and start the containers in detached mode: ```bash -docker-compose up -d +docker compose up -d ``` {% include copy.html %} Verify that the service containers started correctly: ```bash -docker-compose ps +docker compose ps ``` {% include copy.html %} If a container failed to start, you can review the service logs: ```bash -# If you don't pass a service name, docker-compose will show you logs from all of the nodes -docker-compose logs <serviceName> +# If you don't pass a service name, docker compose will show you logs from all of the nodes +docker compose logs <serviceName> ``` {% include copy.html %} -Verify access to OpenSearch Dashboards by connecting to http://localhost:5601 from a browser. The default username and password are `admin`. We do not recommend using this configuration on hosts that are accessible from the public internet until you have customized the security configuration of your deployment. +For solutions to common startup errors, see [Common issues](#common-issues). + +Verify access to OpenSearch Dashboards by connecting to http://localhost:5601 from a browser. For OpenSearch 2.12 and later, you must use your configured username and password. For earlier versions, the default username and password are `admin`. We do not recommend using this configuration on hosts that are accessible from the public internet until you have customized the security configuration of your deployment. Remember that `localhost` cannot be accessed remotely. If you are deploying these containers to a remote host, then you will need to establish a network connection and replace `localhost` with the IP or DNS record corresponding to the host. {: .note} Stop the running containers in your cluster: ```bash -docker-compose down +docker compose down ``` {% include copy.html %} -`docker-compose down` will stop the running containers, but it will not remove the Docker volumes that exist on the host. If you don't care about the contents of these volumes, use the `-v` option to delete all volumes, for example, `docker-compose down -v`. +`docker compose down` will stop the running containers, but it will not remove the Docker volumes that exist on the host. If you don't care about the contents of these volumes, use the `-v` option to delete all volumes, for example, `docker compose down -v`. {: .tip} ## Configure OpenSearch @@ -293,7 +273,7 @@ Unlike the RPM distribution of OpenSearch, which requires a large amount of post For example, take a look at the following command: ```bash docker run \ - -p 9200:9200 -p 9600:9600 \ + -p 9200:9200 \ -e "discovery.type=single-node" \ -v /path/to/custom-opensearch.yml:/usr/share/opensearch/config/opensearch.yml \ opensearchproject/opensearch:latest @@ -301,13 +281,13 @@ docker run \ {% include copy.html %} By reviewing each part of the command, you can see that it: -- Maps ports `9200` and `9600` (`HOST_PORT`:`CONTAINER_PORT`). +- Maps port `9200` (`HOST_PORT`:`CONTAINER_PORT`). - Sets `discovery.type` to `single-node` so that bootstrap checks don't fail for this single-node deployment. - Uses the [-v flag](https://docs.docker.com/engine/reference/commandline/run#mount-volume--v---read-only) to pass a local file called `custom-opensearch.yml` to the container, replacing the `opensearch.yml` file included with the image. - Requests the `opensearchproject/opensearch:latest` image from Docker Hub. - Runs the container. -If you compare this command to the [Sample docker-compose.yml](#sample-docker-composeyml) file, you might notice some common settings, such as the port mappings and the image reference. The command, however, is only deploying a single container running OpenSearch and will not create a container for OpenSearch Dashboards. Furthermore, if you want to use custom TLS certificates, users, or roles, or define additional volumes and networks, then this "one-line" command rapidly grows to an impractical size. That is where the utility of Docker Compose becomes useful. +If you compare this command to the [sample `docker-compose.yml`](#sample-docker-composeyml) file, you might notice some common settings, such as the port mappings and the image reference. The command, however, is only deploying a single container running OpenSearch and will not create a container for OpenSearch Dashboards. Furthermore, if you want to use custom TLS certificates, users, or roles, or define additional volumes and networks, then this "one-line" command rapidly grows to an impractical size. That is where the utility of Docker Compose becomes useful. When you build your OpenSearch cluster with Docker Compose you might find it easier to pass custom configuration files from your host to the container, as opposed to enumerating every individual setting in `docker-compose.yml`. Similar to how the example `docker run` command mounted a volume from the host to the container using the `-v` flag, compose files can specify volumes to mount as a sub-option to the corresponding service. The following truncated YAML file demonstrates how to mount a file or directory to the container. Refer to the official Docker documentation on [volumes](https://docs.docker.com/storage/volumes/) for comprehensive information about volume usage and syntax. @@ -331,7 +311,6 @@ services: If you want to build your own compose file from an example, review the following sample `docker-compose.yml` file. This sample file creates two OpenSearch nodes and one OpenSearch Dashboards node with the Security plugin disabled. You can use this sample file as a starting point while reviewing [Configuring basic security settings](#configuring-basic-security-settings). ```yml -version: '3' services: opensearch-node1: image: opensearchproject/opensearch:latest @@ -356,7 +335,6 @@ services: - opensearch-data1:/usr/share/opensearch/data # Creates volume called opensearch-data1 and mounts it to the container ports: - 9200:9200 # REST API - - 9600:9600 # Performance Analyzer networks: - opensearch-net # All of the containers will join the same Docker bridge network opensearch-node2: @@ -406,7 +384,7 @@ networks: ### Configuring basic security settings -Before making your OpenSearch cluster available to external hosts, it's a good idea to review the deployment's security configuration. You may recall from the first [Sample docker-compose.yml](#sample-docker-composeyml) file that, unless disabled by setting `DISABLE_SECURITY_PLUGIN=true`, a bundled script will apply a default demo security configuration to the nodes in the cluster. Because this configuration is used for demo purposes, the default usernames and passwords are known. For that reason, we recommend that you create your own security configuration files and use `volumes` to pass these files to the containers. For specific guidance on OpenSearch security settings, see [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/). +Before making your OpenSearch cluster available to external hosts, it's a good idea to review the deployment's security configuration. You may recall from the first [sample `docker-compose.yml`](#sample-docker-composeyml) file that, unless disabled by setting `DISABLE_SECURITY_PLUGIN=true`, a bundled script will apply a default demo security configuration to the nodes in the cluster. Because this configuration is used for demo purposes, the default usernames and passwords are known. For that reason, we recommend that you create your own security configuration files and use `volumes` to pass these files to the containers. For specific guidance on OpenSearch security settings, see [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/). To use your own certificates in your configuration, add all of the necessary certificates to the volumes section of the compose file: ```yml @@ -431,7 +409,7 @@ volumes: ``` {% include copy.html %} -Remember that the certificates you specify in your compose file must be the same as the certificates defined in your custom `opensearch.yml` file. You should replace the root, admin, and node certificates with your own. For more information see [Configure TLS certificates]({{site.url}}{{site.baseurl}}/security/configuration/tls). +Remember that the certificates you specify in your compose file must be the same as the certificates defined in your custom `opensearch.yml` file. You should replace the root, admin, and node certificates with your own. For more information see [Configure TLS certificates]({{site.url}}{{site.baseurl}}/security/configuration/tls/). ```yml plugins.security.ssl.transport.pemcert_filepath: node1.pem plugins.security.ssl.transport.pemkey_filepath: node1-key.pem @@ -449,7 +427,7 @@ After configuring security settings, your custom `opensearch.yml` file might loo plugins.security.ssl.transport.pemcert_filepath: node1.pem plugins.security.ssl.transport.pemkey_filepath: node1-key.pem plugins.security.ssl.transport.pemtrustedcas_filepath: root-ca.pem -plugins.security.ssl.transport.enforce_hostname_verification: false +transport.ssl.enforce_hostname_verification: false plugins.security.ssl.http.enabled: true plugins.security.ssl.http.pemcert_filepath: node1.pem plugins.security.ssl.http.pemkey_filepath: node1-key.pem @@ -473,12 +451,180 @@ For a full list of settings, see [Security]({{site.url}}{{site.baseurl}}/securit Use the same process to specify a [Backend configuration]({{site.url}}{{site.baseurl}}/security/configuration/configuration/) in `/usr/share/opensearch/config/opensearch-security/config.yml` as well as new internal users, roles, mappings, action groups, and tenants in their respective [YAML files]({{site.url}}{{site.baseurl}}/security/configuration/yaml/). -After replacing the certificates and creating your own internal users, roles, mappings, action groups, and tenants, use Docker Compose to start the cluster: +#### Complete Docker Compose example with custom configuration + +This example uses the `${OS_VER}` and `${OSD_VER}` environment variables to specify the OpenSearch and OpenSearch Dashboards versions. If either variable is not set, Docker Compose fails with an `invalid reference format` error. Before using this example, set the versions by exporting the variables: + ```bash -docker-compose up -d +export OS_VER={{ site.opensearch_version }} +export OSD_VER={{ site.opensearch_dashboards_version }} ``` {% include copy.html %} +Alternatively, create a `.env` file in the same directory as your `docker-compose.yml`: + +```bash +OS_VER={{ site.opensearch_version }} +OSD_VER={{ site.opensearch_dashboards_version }} +``` +{% include copy.html %} + +Using environment variables or explicit version tags (such as `{{ site.opensearch_version }}`) is recommended for production deployments to ensure consistent versions across your cluster and avoid unexpected updates. +{: .tip} + +After creating your own certificates, `internal_users.yml`, `roles.yml`, `roles_mapping.yml`, and the rest of the security configuration files, your `docker-compose.yaml` file should appear similar to the following: + +```yaml +services: + opensearch-node1: + image: opensearchproject/opensearch:${OS_VER} + container_name: opensearch-node1_${OS_VER} + environment: + - cluster.name=opensearch-cluster + - node.name=opensearch-node1 + - discovery.seed_hosts=opensearch-node1,opensearch-node2,opensearch-node3 + - cluster.initial_master_nodes=opensearch-node1,opensearch-node2,opensearch-node3 + - bootstrap.memory_lock=true + - "OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g" + ulimits: + memlock: + soft: -1 + hard: -1 + nofile: + soft: 65536 + hard: 65536 + volumes: + - ./opensearch.yml:/usr/share/opensearch/config/opensearch.yml + - ./esnode.pem:/usr/share/opensearch/config/esnode.pem + - ./esnode-key.pem:/usr/share/opensearch/config/esnode-key.pem + - ./root-ca.pem:/usr/share/opensearch/config/root-ca.pem + - ./kirk-key.pem:/usr/share/opensearch/config/kirk-key.pem + - ./kirk.pem:/usr/share/opensearch/config/kirk.pem + - ./config.yml:/usr/share/opensearch/config/opensearch-security/config.yml + - ./roles_mapping.yml:/usr/share/opensearch/config/opensearch-security/roles_mapping.yml + - ./roles.yml:/usr/share/opensearch/config/opensearch-security/roles.yml + - ./action_groups.yml:/usr/share/opensearch/config/opensearch-security/action_groups.yml + - ./allowlist.yml:/usr/share/opensearch/config/opensearch-security/allowlist.yml + - ./audit.yml:/usr/share/opensearch/config/opensearch-security/audit.yml + - ./internal_users.yml:/usr/share/opensearch/config/opensearch-security/internal_users.yml + - ./nodes_dn.yml:/usr/share/opensearch/config/opensearch-security/nodes_dn.yml + - ./tenants.yml:/usr/share/opensearch/config/opensearch-security/tenants.yml + ports: + - 9201:9200 + networks: + - opensearch-net + + opensearch-node2: + image: opensearchproject/opensearch:${OS_VER} + container_name: opensearch-node2_${OS_VER} + environment: + - cluster.name=opensearch-cluster + - node.name=opensearch-node2 + - discovery.seed_hosts=opensearch-node1,opensearch-node2,opensearch-node3 + - cluster.initial_master_nodes=opensearch-node1,opensearch-node2,opensearch-node3 + - bootstrap.memory_lock=true + - "OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g" + ulimits: + memlock: + soft: -1 + hard: -1 + nofile: + soft: 65536 + hard: 65536 + volumes: + - ./opensearch.yml:/usr/share/opensearch/config/opensearch.yml + - ./esnode.pem:/usr/share/opensearch/config/esnode.pem + - ./esnode-key.pem:/usr/share/opensearch/config/esnode-key.pem + - ./root-ca.pem:/usr/share/opensearch/config/root-ca.pem + - ./kirk-key.pem:/usr/share/opensearch/config/kirk-key.pem + - ./kirk.pem:/usr/share/opensearch/config/kirk.pem + - ./config.yml:/usr/share/opensearch/config/opensearch-security/config.yml + - ./roles_mapping.yml:/usr/share/opensearch/config/opensearch-security/roles_mapping.yml + - ./roles.yml:/usr/share/opensearch/config/opensearch-security/roles.yml + - ./action_groups.yml:/usr/share/opensearch/config/opensearch-security/action_groups.yml + - ./allowlist.yml:/usr/share/opensearch/config/opensearch-security/allowlist.yml + - ./audit.yml:/usr/share/opensearch/config/opensearch-security/audit.yml + - ./internal_users.yml:/usr/share/opensearch/config/opensearch-security/internal_users.yml + - ./nodes_dn.yml:/usr/share/opensearch/config/opensearch-security/nodes_dn.yml + - ./tenants.yml:/usr/share/opensearch/config/opensearch-security/tenants.yml + ports: + - 9200:9200 + networks: + - opensearch-net + + opensearch-node3: + image: opensearchproject/opensearch:${OS_VER} + container_name: opensearch-node3_${OS_VER} + environment: + - cluster.name=opensearch-cluster + - node.name=opensearch-node3 + - discovery.seed_hosts=opensearch-node1,opensearch-node2,opensearch-node3 + - cluster.initial_master_nodes=opensearch-node1,opensearch-node2,opensearch-node3 + - bootstrap.memory_lock=true + - "OPENSEARCH_JAVA_OPTS=-Xms2g -Xmx2g" + ulimits: + memlock: + soft: -1 + hard: -1 + nofile: + soft: 65536 + hard: 65536 + volumes: + - ./opensearch.yml:/usr/share/opensearch/config/opensearch.yml + - ./esnode.pem:/usr/share/opensearch/config/esnode.pem + - ./esnode-key.pem:/usr/share/opensearch/config/esnode-key.pem + - ./root-ca.pem:/usr/share/opensearch/config/root-ca.pem + - ./kirk-key.pem:/usr/share/opensearch/config/kirk-key.pem + - ./kirk.pem:/usr/share/opensearch/config/kirk.pem + - ./config.yml:/usr/share/opensearch/config/opensearch-security/config.yml + - ./roles_mapping.yml:/usr/share/opensearch/config/opensearch-security/roles_mapping.yml + - ./roles.yml:/usr/share/opensearch/config/opensearch-security/roles.yml + - ./action_groups.yml:/usr/share/opensearch/config/opensearch-security/action_groups.yml + - ./allowlist.yml:/usr/share/opensearch/config/opensearch-security/allowlist.yml + - ./audit.yml:/usr/share/opensearch/config/opensearch-security/audit.yml + - ./internal_users.yml:/usr/share/opensearch/config/opensearch-security/internal_users.yml + - ./nodes_dn.yml:/usr/share/opensearch/config/opensearch-security/nodes_dn.yml + - ./tenants.yml:/usr/share/opensearch/config/opensearch-security/tenants.yml + ports: + - 9202:9200 + networks: + - opensearch-net + + opensearch-dashboards: + image: opensearchproject/opensearch-dashboards:${OSD_VER} + container_name: opensearch-dashboards_${OSD_VER} + volumes: + - ./opensearch_dashboards.yml:/usr/share/opensearch-dashboards/config/opensearch_dashboards.yml + - ./opensearch_dashboards.crt:/usr/share/opensearch-dashboards/config/opensearch_dashboards.crt + - ./opensearch_dashboards.key:/usr/share/opensearch-dashboards/config/opensearch_dashboards.key + ports: + - 5601:5601 + expose: + - "5601" + environment: + OPENSEARCH_HOSTS: '["https://opensearch-node1:9200", "https://opensearch-node2:9200", "https://opensearch-node3:9200" ]' + networks: + - opensearch-net + depends_on: + - opensearch-node1 + - opensearch-node2 + - opensearch-node3 + +networks: + opensearch-net: + +``` +{% include copy.html %} + +Use Docker Compose to start the cluster: +```bash +docker compose up -d +``` +{% include copy.html %} + +The password for the `admin` user provided in the `.env` file is overridden by the password provided in the `internal_users.yml` file. +{: .note} + ### Working with plugins To use the OpenSearch image with a custom plugin, you must first create a [`Dockerfile`](https://docs.docker.com/engine/reference/builder/). Review the official Docker documentation for information about creating a Dockerfile. @@ -492,7 +638,7 @@ Then run the following commands: # Build an image from a Dockerfile docker build --tag=opensearch-custom-plugin . # Start the container from the custom image -docker run -p 9200:9200 -p 9600:9600 -v /usr/share/opensearch/data opensearch-custom-plugin +docker run -p 9200:9200 -e "discovery.type=single-node" -e "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" -v /usr/share/opensearch/data opensearch-custom-plugin ``` Alternatively, you might want to remove a plugin from an image before deploying it. This example Dockerfile removes the Security plugin: @@ -512,9 +658,64 @@ COPY --chown=opensearch:opensearch my-root-cas.pem /usr/share/opensearch/config/ ``` {% include copy.html %} -## Related links +## Common issues +Review these common issues and suggested solutions if your containers fail to start or exit unexpectedly. + +For issues that can occur with any installation method, such as HTTP requests to an HTTPS endpoint or a rejected admin password, see [Common issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#common-issues). + +### Docker commands require elevated permissions + +Eliminate the need for running your Docker commands with `sudo` by adding your user to the `docker` user group. See Docker's [Post-installation steps for Linux](https://docs.docker.com/engine/install/linux-postinstall/) for more information. + +```bash +sudo usermod -aG docker $USER +``` +{% include copy.html %} + +### Error message: "Authentication finally failed for admin" + +If requests that use the admin password return a `401` status code and the OpenSearch log contains `Authentication finally failed for admin`, the password that you're using doesn't match the stored admin password. + +OpenSearch applies `OPENSEARCH_INITIAL_ADMIN_PASSWORD` only when it starts for the first time with empty data volumes. If you change the value later and restart the containers, the admin password doesn't change and the previous password still works. To change the admin password, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). To start over with the new password, remove the volumes by running `docker compose down -v`, which deletes all data stored in the volumes, and then start the cluster again. + +If the password contains a dollar sign (`$`), Docker Compose reads the characters that follow it in an `.env` file as a variable name, so an unquoted or double-quoted value loses characters. For example, `Zz$Strong9Pass!` becomes `Zz!`. Enclose the value in single quotation marks, for example, `OPENSEARCH_INITIAL_ADMIN_PASSWORD='<custom-admin-password>'`, or write each `$` as `$$`. + +When you pass the credentials to `curl`, enclose them in single quotation marks so that the shell doesn't change special characters, for example, `curl https://localhost:9200 -ku 'admin:<custom-admin-password>'`. + +### Error message: "max virtual memory areas vm.max_map_count [65530] is too low" + +OpenSearch fails to start if the `vm.max_map_count` setting of your host is too low. Set `vm.max_map_count` on the host machine, not in the container, as described in [Linux settings](#linux-settings). For more information, see [Common issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#error-message-max-virtual-memory-areas-vmmax_map_count-65530-is-too-low). + +### Error message: "local node does not have quorum in voting configuration" + +The data volumes in the [sample `docker-compose.yml`](#sample-docker-composeyml) file store the state of the two-node cluster. If you change the file to run a single node with `discovery.type: single-node` but keep the existing volumes, OpenSearch fails to start and logs an error similar to the following: + +``` +cannot start with [discovery.type] set to [single-node] when local node does not have quorum in voting configuration +``` + +To fix this error, remove the existing volumes: + +```bash +docker compose down -v +``` +{% include copy.html %} + +The `docker compose down -v` command deletes all data stored in the volumes. +{: .warning} + +Then start the cluster again: + +```bash +docker compose up -d +``` +{% include copy.html %} + +## Related documentation + +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) - [OpenSearch configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) -- [Performance analyzer]({{site.url}}{{site.baseurl}}/monitoring-plugins/pa/index/) +- [Performance Analyzer]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/performance-analyzer/) - [Install and configure OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) - [About Security in OpenSearch]({{site.url}}{{site.baseurl}}/security/index/) diff --git a/_install-and-configure/install-opensearch/helm.md b/_install-and-configure/install-opensearch/helm.md index ed2aa628..b4c7077c 100644 --- a/_install-and-configure/install-opensearch/helm.md +++ b/_install-and-configure/install-opensearch/helm.md @@ -2,16 +2,16 @@ layout: default title: Helm parent: Installing OpenSearch -nav_order: 6 +nav_order: 15 redirect_from: - /opensearch/install/helm/ --- -# Helm +# Installing OpenSearch using Helm Helm is a package manager that allows you to easily install and manage OpenSearch in a Kubernetes cluster. You can define your OpenSearch configurations in a YAML file and use Helm to deploy your applications in a version-controlled and reproducible way. -The Helm chart contains the resources described in the following table. +The [Helm chart](https://github.com/opensearch-project/helm-charts) contains the resources described in the following table. Resource | Description :--- | :--- @@ -22,7 +22,7 @@ Resource | Description The specification in the default Helm chart supports many standard use cases and setups. You can modify the default chart to configure your desired specifications and set Transport Layer Security (TLS) and role-based access control (RBAC). For information about the default configuration, steps to configure security, and configurable parameters, see the -[README](https://github.com/opensearch-project/helm-charts/blob/main/README.md). +[`README`](https://github.com/opensearch-project/helm-charts/blob/main/README.md). The instructions here assume you have a Kubernetes cluster with Helm preinstalled. See the [Kubernetes documentation](https://kubernetes.io/docs/setup/) for steps to configure a Kubernetes cluster and the [Helm documentation](https://helm.sh/docs/intro/install/) to install Helm. {: .note } @@ -31,9 +31,13 @@ The instructions here assume you have a Kubernetes cluster with Helm preinstalle The default Helm chart deploys a three-node cluster. We recommend that you have at least 8 GiB of memory available for this deployment. You can expect the deployment to fail if, say, you have less than 4 GiB of memory available. +OpenSearch requires the `vm.max_map_count` kernel setting on each Kubernetes node to be at least `262144`. If the value is lower, the OpenSearch pods fail the bootstrap checks and enter the `CrashLoopBackOff` status. The `values.yaml` file in the following steps sets `sysctlInit.enabled` to `true`, which runs a privileged init container that sets `vm.max_map_count` on the node. If your nodes are already configured or your cluster does not allow privileged containers, remove this setting and configure `vm.max_map_count` on the nodes instead. For more information, see [Important settings]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#important-settings). + +For OpenSearch 2.12 or later, you must provide `OPENSEARCH_INITIAL_ADMIN_PASSWORD` to start the cluster. Set the admin password in `values.yaml` under `extraEnvs`, following the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). OpenSearch uses this password only when it sets up the demo security configuration. To change the admin password later, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). + ## Install OpenSearch using Helm -1. Add `opensearch` [helm-charts](https://github.com/opensearch-project/helm-charts) repository to Helm: +1. Add `opensearch` [`helm-charts`](https://github.com/opensearch-project/helm-charts) repository to Helm: ```bash helm repo add opensearch https://opensearch-project.github.io/helm-charts/ @@ -54,25 +58,64 @@ The default Helm chart deploys a three-node cluster. We recommend that you have ``` {% include copy.html %} + The available charts are provided in the response: + ```bash - NAME CHART VERSION APP VERSION DESCRIPTION - opensearch/opensearch 1.0.7 1.0.0 A Helm chart for OpenSearch - opensearch/opensearch-dashboards 1.0.4 1.0.0 A Helm chart for OpenSearch Dashboards + NAME CHART VERSION APP VERSION DESCRIPTION + opensearch/opensearch {{site.opensearch_version}} {{site.opensearch_version}} A Helm chart for OpenSearch + opensearch/opensearch-dashboards {{site.opensearch_dashboards_version}} {{site.opensearch_dashboards_version}} A Helm chart for OpenSearch Dashboards + opensearch/data-prepper 0.3.1 2.8.0 A Helm chart for Data Prepper ``` +1. Create a minimal `values.yaml` file, replacing `<custom-admin-password>` with your admin password: + + ```yaml + config: + opensearch.yml: |- + cluster.name: opensearch-cluster + network.host: 0.0.0.0 + extraEnvs: + - name: OPENSEARCH_INITIAL_ADMIN_PASSWORD + value: <custom-admin-password> + sysctlInit: + enabled: true + ``` + {% include copy.html %} + 1. Deploy OpenSearch: ```bash - helm install my-deployment opensearch/opensearch + helm install my-deployment opensearch/opensearch -f values.yaml ``` {% include copy.html %} -You can also build the `opensearch-1.0.0.tgz` file manually: + The output shows the deployed release: -1. Change to the `opensearch` directory: + ```yaml + NAME: my-deployment + LAST DEPLOYED: Fri Oct 2 02:28:00 2026 + NAMESPACE: default + STATUS: deployed + REVISION: 1 + TEST SUITE: None + NOTES: + Watch all cluster members come up. + $ kubectl get pods --namespace=default -l app.kubernetes.io/component=opensearch-cluster-master -w + ``` + +You can also build the `opensearch-<VERSION>.tgz` file manually: + +1. Clone the [`helm-charts` repo](https://github.com/opensearch-project/helm-charts/tree/main): ```bash - cd charts/opensearch + git clone https://github.com/opensearch-project/helm-charts.git + ``` + {% include copy.html %} + +1. Navigate to the `opensearch` directory: + + ```bash + cd helm-charts/charts/opensearch ``` {% include copy.html %} @@ -86,65 +129,75 @@ You can also build the `opensearch-1.0.0.tgz` file manually: 1. Deploy OpenSearch: ```bash - helm install --generate-name opensearch-1.0.0.tgz + helm install --generate-name opensearch-<VERSION>.tgz -f /path/to/values.yaml ``` {% include copy.html %} - The output shows you the specifications instantiated from the install. - To customize the deployment, pass in the values that you want to override with a custom YAML file: + Helm generates the release name, for example, `opensearch-{{ site.opensearch_version | split: "." | first }}-1790908448`. Use this name instead of `my-deployment` when you uninstall the release. - ```bash - helm install --values=customvalues.yaml opensearch-1.0.0.tgz - ``` - {% include copy.html %} +## Verify the deployment -For OpenSearch 2.12 or greater, customize the admin password in `values.yaml` under `extraEnvs`, as shown in the following example: - -```yaml -extraEnvs: - - name: OPENSEARCH_INITIAL_ADMIN_PASSWORD - value: <custom-admin-password> -``` - -#### Sample output - - ```yaml - NAME: opensearch-1-1629223146 - LAST DEPLOYED: Tue Aug 17 17:59:07 2021 - NAMESPACE: default - STATUS: deployed - REVISION: 1 - TEST SUITE: None - NOTES: - Watch all cluster members come up. - $ kubectl get pods --namespace=default -l app=opensearch-cluster-master -w - ``` - -To make sure your OpenSearch pod is up and running, run the following command: +To make sure your OpenSearch pods are up and running, run the following command: ```bash -$ kubectl get pods -NAME READY STATUS RESTARTS AGE -opensearch-cluster-master-0 1/1 Running 0 3m56s -opensearch-cluster-master-1 1/1 Running 0 3m56s -opensearch-cluster-master-2 1/1 Running 0 3m56s -``` - -To access the OpenSearch shell: - -```bash -$ kubectl exec -it opensearch-cluster-master-0 -- /bin/bash +kubectl get pods --namespace=default -w ``` {% include copy.html %} -You can send requests to the pod to verify that OpenSearch is up and running: +Wait until all pods show `1/1` in the `READY` column and `Running` in the `STATUS` column, which takes about 1 minute: + +```bash +NAME READY STATUS RESTARTS AGE +opensearch-cluster-master-0 1/1 Running 0 41s +opensearch-cluster-master-1 1/1 Running 0 41s +opensearch-cluster-master-2 1/1 Running 0 41s +``` + +The chart names the OpenSearch service and pods using the `clusterName` and `nodeGroup` parameters, in the `<clusterName>-<nodeGroup>` format. The commands in this section use the default name, `opensearch-cluster-master`. If you changed either parameter, replace `opensearch-cluster-master` with your service name. To list the services, run `kubectl get svc`. + +Once all pods are ready, you can verify that OpenSearch is running. Use one of the following methods. + +### Port forwarding from your local machine + +To access OpenSearch from your local machine, set up port forwarding from the OpenSearch service: + +```bash +kubectl port-forward svc/opensearch-cluster-master 9200:9200 +``` +{% include copy.html %} + +Leave this command running and open a separate terminal session. Then send a request to verify that OpenSearch is running: + +```bash +curl -XGET https://localhost:9200 -u 'admin:<custom-admin-password>' --insecure +``` +{% include copy.html %} + +### Exec into the pod + +Alternatively, you can access the OpenSearch shell directly: + +```bash +kubectl exec -it opensearch-cluster-master-0 -- /bin/bash +``` +{% include copy.html %} + +Then send a request from inside the pod: + +```bash +curl -XGET https://localhost:9200 -u 'admin:<custom-admin-password>' --insecure +``` +{% include copy.html %} + +### Expected response + +The following is an example response: ```json -$ curl -XGET https://localhost:9200 -u 'admin:admin' --insecure { - "name" : "opensearch-cluster-master-1", + "name" : "opensearch-cluster-master-0", "cluster_name" : "opensearch-cluster", - "cluster_uuid" : "hP2gq5bPS3SLp8Z7wXm8YQ", + "cluster_uuid" : "72e_wDs1QdWHmwum_E2feA", "version" : { "distribution" : "opensearch", "number" : <version>, @@ -153,28 +206,67 @@ $ curl -XGET https://localhost:9200 -u 'admin:admin' --insecure "build_date" : <build-date>, "build_snapshot" : false, "lucene_version" : <lucene-version>, - "minimum_wire_compatibility_version" : "6.8.0", - "minimum_index_compatibility_version" : "6.0.0-beta1" + "minimum_wire_compatibility_version" : "2.19.0", + "minimum_index_compatibility_version" : "2.0.0" }, "tagline" : "The OpenSearch Project: https://opensearch.org/" } ``` +If you receive an `OpenSearch Security not initialized` error, the cluster is still starting up. Wait a few minutes for all nodes to fully initialize and form the cluster, then try the request again. +{: .note } + ## Uninstall using Helm -To identify the OpenSearch deployment that you want to delete: +To identify the OpenSearch deployment that you want to delete, run the following command: ```bash -$ helm list -NAME NAMESPACEREVISIONUPDATED STATUS CHART APP VERSION -opensearch-1-1629223146 default 1 2021-08-17 17:59:07.664498239 +0000 UTCdeployedopensearch-1.0.0 1.0.0 -``` - -To delete or uninstall a deployment, run the following command: - -```bash -helm delete opensearch-1-1629223146 +helm list ``` {% include copy.html %} -For steps to install OpenSearch Dashboards, see [Helm to install OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/install/helm/). \ No newline at end of file +The response lists the current Helm deployments: + +```bash +NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION +my-deployment default 1 2026-10-02 02:28:00.553978943 +0000 UTC deployed opensearch-{{site.opensearch_version}} {{site.opensearch_version}} +``` + +To uninstall a deployment, run the following command: + +```bash +helm uninstall my-deployment +``` +{% include copy.html %} + +Uninstalling the release does not delete the persistent volume claims (PVCs) that store the OpenSearch data. If you reinstall the release, OpenSearch reuses the existing data, including the original admin password. To delete the data, delete the PVCs: + +```bash +kubectl delete pvc -l app.kubernetes.io/instance=my-deployment +``` +{% include copy.html %} + +For instructions to install OpenSearch Dashboards, see [Installing OpenSearch Dashboards using Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/helm/). + +## Common issues + +Review these common issues and suggested solutions if your pods fail to start. + +For issues that can occur with any installation method, such as HTTP requests to an HTTPS endpoint or a rejected admin password, see [Common issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#common-issues). + +### The admin password in `values.yaml` has no effect + +If `values.yaml` contains more than one `extraEnvs` key, Helm uses only the last one. A second `extraEnvs` key silently replaces the list that sets `OPENSEARCH_INITIAL_ADMIN_PASSWORD`, so `helm install` or `helm upgrade` succeeds, but the pods restart repeatedly. Define all environment variables in a single `extraEnvs` list: + +```yaml +extraEnvs: + - name: OPENSEARCH_INITIAL_ADMIN_PASSWORD + value: <custom-admin-password> + - name: <another-variable> + value: <value> +``` +{% include copy.html %} + +## Related documentation + +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) diff --git a/_install-and-configure/install-opensearch/index.md b/_install-and-configure/install-opensearch/index.md index cf0252bd..312e93c7 100644 --- a/_install-and-configure/install-opensearch/index.md +++ b/_install-and-configure/install-opensearch/index.md @@ -7,27 +7,44 @@ redirect_from: - /opensearch/install/ - /opensearch/install/compatibility/ - /opensearch/install/important-settings/ - - /install-and-configure/index/ - /opensearch/install/index/ + - /install-and-configure/install-opensearch/ --- # Installing OpenSearch -This section details how to install OpenSearch on your host, including which operating systems are [compatible with OpenSearch](#operating-system-compatibility), which [ports to open](#network-requirements), and which [important settings](#important-settings) to configure on your host. +You can install OpenSearch using Docker, Helm, the OpenSearch Kubernetes Operator, tarball, RPM, Debian packages, Ansible, or on Windows. Each method requires specific [ports to be open](#network-requirements) and [important settings](#important-settings) to be configured on your host. -## Operating system compatibility +To try OpenSearch on your computer, see [Installation quickstart]({{site.url}}{{site.baseurl}}/getting-started/quickstart/). -OpenSearch and OpenSearch Dashboards are compatible with Red Hat Enterprise Linux (RHEL) and Debian-based Linux distributions that use [`systemd`](https://en.wikipedia.org/wiki/Systemd), such as CentOS, Amazon Linux 2, and Ubuntu Long-Term Support (LTS). While OpenSearch and OpenSearch Dashboards should work on most Linux distributions, we only test a subset. +For operating system compatibility, see [Compatible operating systems]({{site.url}}{{site.baseurl}}/install-and-configure/os-comp/). -The following table lists the operating system versions that we currently support. +## Installation steps -OS | Version -:---------- | :-------- -RHEL/CentOS | 7/8 -Rocky Linux | 8 -Ubuntu | 16.04/18.04/20.04 -Windows Server | 2019 +Installation steps vary depending on the deployment method. For steps specific to your deployment, see the following installation guides: +- [Docker]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/) +- [OpenSearch Kubernetes Operator]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/) +- [Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/) +- [Debian]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/debian/) +- [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/) +- [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/) +- [Ansible playbook]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/ansible/) +- [Windows]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/windows/) + +## Preparing a cluster for production + +The [Installation quickstart]({{site.url}}{{site.baseurl}}/getting-started/quickstart/) and the default installations in most guides create a cluster that uses the demo security configuration. The demo configuration uses self-signed demo certificates and known passwords for internal users, so it is intended for testing only. Before you use a cluster in production, complete the following tasks: + +- Replace the demo certificates with certificates issued by your own certificate authority. For more information, see [Configuring TLS certificates]({{site.url}}{{site.baseurl}}/security/configuration/tls/). +- Configure how users authenticate. You can use the internal user database of the Security plugin or connect an external identity provider for single sign-on, such as [SAML]({{site.url}}{{site.baseurl}}/security/authentication-backends/saml/), [OpenID Connect]({{site.url}}{{site.baseurl}}/security/authentication-backends/openid-connect/), or [LDAP]({{site.url}}{{site.baseurl}}/security/authentication-backends/ldap/). For more information, see [Configuring the security backend]({{site.url}}{{site.baseurl}}/security/configuration/configuration/). +- Map users or the backend roles provided by your identity provider to roles that grant access to the cluster. For more information, see [Defining users and roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles/). +- Replace the default passwords of the demo internal users, or remove the users that you don't need. For more information, see [Demo configuration passwords]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#demo-configuration-passwords). +- Configure the [important settings](#important-settings) on every host. +- Run multiple nodes, including dedicated cluster manager nodes, so that the cluster remains available when a node fails. For more information, see [Creating a cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/). +- Back up your data using snapshots. For more information, see [Snapshots]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/index/). + +For more security recommendations, see [Best practices for OpenSearch security]({{site.url}}{{site.baseurl}}/security/configuration/best-practices/). ## File system recommendations @@ -37,77 +54,139 @@ Avoid using a network file system for node storage in a production workflow. Usi The OpenSearch distribution for Linux ships with a compatible [Adoptium JDK](https://adoptium.net/) version of Java in the `jdk` directory. To find the JDK version, run `./jdk/bin/java -version`. For example, the OpenSearch 1.0.0 tarball ships with Java 15.0.1+9 (non-LTS), OpenSearch 1.3.0 ships with Java 11.0.14.1+1 (LTS), and OpenSearch 2.0.0 ships with Java 17.0.2+8 (LTS). OpenSearch is tested with all compatible Java versions. -OpenSearch Version | Compatible Java Versions | Bundled Java Version +OpenSearch version | Compatible Java versions | Java version bundled in the latest release :---------- | :-------- | :----------- 1.0--1.2.x | 11, 15 | 15.0.1+9 -1.3.x | 8, 11, 14 | 11.0.22+7 +1.3.x | 8, 11, 14 | 11.0.25+9 2.0.0--2.11.x | 11, 17 | 17.0.2+8 -2.12.0 | 11, 17, 21 | 21.0.2+13 +2.12.0--2.19.x | 11, 17, 21 | 21.0.13.1+2 +3.0.0--3.1.x | 21 | 21.0.7+6 +3.2.0--3.3.x | 21, 24 | 24.0.2+12 +3.4.0--3.6.0 | 21, 25 | 25.0.2+10 +3.7.0--3.10.x | 21, 25, 26 | 25.0.5.1+2 + +To use a different Java installation, set the `OPENSEARCH_JAVA_HOME` or `JAVA_HOME` environment variable to the Java installation location. For example: -To use a different Java installation, set the `OPENSEARCH_JAVA_HOME` or `JAVA_HOME` environment variable to the Java install location. For example: ```bash export OPENSEARCH_JAVA_HOME=/path/to/opensearch-{{site.opensearch_version}}/jdk ``` +{% include copy.html %} ## Network requirements -The following ports need to be open for OpenSearch components. +The following TCP ports need to be open for OpenSearch components. Port number | OpenSearch component :--- | :--- 443 | OpenSearch Dashboards in AWS OpenSearch Service with encryption in transit (TLS) 5601 | OpenSearch Dashboards 9200 | OpenSearch REST API -9250 | Cross-cluster search -9300 | Node communication and transport -9600 | Performance Analyzer +9300 | Node communication and transport (internal), cross cluster search + +No UDP ports are used. +{: .note} ## Important settings -For production workloads, make sure the [Linux setting](https://www.kernel.org/doc/Documentation/sysctl/vm.txt) `vm.max_map_count` is set to at least 262144. Even if you use the Docker image, set this value on the *host machine*. To check the current value, run this command: +The following settings apply to every Linux host that runs OpenSearch. Some installation methods configure them for you, as described in each section. The [Java heap size](#java-heap-size) settings also apply to Windows. + +If OpenSearch binds to a non-loopback address, for example, using `network.host: 0.0.0.0`, it runs bootstrap checks at startup unless `discovery.type` is set to `single-node`. OpenSearch fails to start if `vm.max_map_count`, the Java heap size, or the file descriptor limit does not meet the requirements in this section or if `bootstrap.memory_lock` is `true` but OpenSearch cannot lock the memory. + +### `vm.max_map_count` + +For production workloads running on Linux, make sure the [Linux setting](https://www.kernel.org/doc/Documentation/sysctl/vm.txt) `vm.max_map_count` is set to at least `262144`. + +The RPM and Debian packages set `vm.max_map_count` to `262144` when you install them, using the `/usr/lib/sysctl.d/opensearch.conf` file. The Helm chart and the OpenSearch Kubernetes Operator can set it using an init container. For other installation methods, set the value manually. + +Even if you use the Docker image, set this value on the host machine. To check the current value, run this command: ```bash cat /proc/sys/vm/max_map_count ``` +{% include copy.html %} To increase the value, add the following line to `/etc/sysctl.conf`: ``` vm.max_map_count=262144 ``` +{% include copy.html %} -Then run `sudo sysctl -p` to reload. +Then reload the settings: -For Windows workloads, you can set the `vm.max_map_count` running the following commands: +```bash +sudo sysctl -p +``` +{% include copy.html %} + +For Windows workloads, set `vm.max_map_count` in the Docker Desktop WSL distribution. First, open a shell in the distribution: ```bash wsl -d docker-desktop +``` +{% include copy.html %} + +Then set the value: + +```bash sysctl -w vm.max_map_count=262144 ``` +{% include copy.html %} -The [sample docker-compose.yml]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/#sample-docker-composeyml) file also contains several key settings: +### Memory lock -- `bootstrap.memory_lock=true` +Swapping can dramatically decrease performance and stability, so make sure that the OpenSearch heap is never swapped to disk on production clusters. To lock the heap in memory, set `bootstrap.memory_lock` to `true` in `opensearch.yml` and allow the user that runs OpenSearch to lock an unlimited amount of memory. The way you set the memory lock limit depends on the installation method: - Disables swapping (along with `memlock`). Swapping can dramatically decrease performance and stability, so you should ensure it is disabled on production clusters. +- If you use Docker, the [sample `docker-compose.yml`]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker/#sample-docker-composeyml) file sets `bootstrap.memory_lock=true` and sets the `memlock` ulimits to `-1` (unlimited). +- If you installed OpenSearch from an RPM or Debian package, the `opensearch` systemd service does not set a memory lock limit. To add one, run `sudo systemctl edit opensearch` and add the following lines: - Enabling the `bootstrap.memory_lock` setting will cause the JVM to reserve any memory it needs. The [Java SE Hotspot VM Garbage Collection Tuning Guide](https://docs.oracle.com/javase/9/gctuning/other-considerations.htm#JSGCT-GUID-B29C9153-3530-4C15-9154-E74F44E3DAD9) documents a default 1 gigabyte (GB) Class Metadata native memory reservation. Combined with Java heap, this may result in an error due to the lack of native memory on VMs with less memory than these requirements. To prevent errors, limit the reserved memory size using `-XX:CompressedClassSpaceSize` or `-XX:MaxMetaspaceSize` and set the size of the Java heap to make sure you have enough system memory. + ``` + [Service] + LimitMEMLOCK=infinity + ``` + {% include copy.html %} -- `OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m` + Then restart OpenSearch by running `sudo systemctl restart opensearch`. - Sets the size of the Java heap (we recommend half of system RAM). +- If you installed OpenSearch from a tarball, set the limit in `/etc/security/limits.conf`, as described in [Setting limits for tarball installations](#setting-limits-for-tarball-installations). -- `nofile 65536` +Alternatively, disable swapping on the host by running `sudo swapoff -a`. - Sets a limit of 65536 open files for the OpenSearch user. +When the memory lock is enabled, the JVM reserves all the memory it needs at startup. The [Java SE Hotspot VM Garbage Collection Tuning Guide](https://docs.oracle.com/javase/9/gctuning/other-considerations.htm#JSGCT-GUID-B29C9153-3530-4C15-9154-E74F44E3DAD9) documents a default 1 gigabyte (GB) native memory reservation for class metadata. On VMs with limited memory, this reservation combined with the Java heap can exhaust native memory and cause an error. To prevent errors, limit the reserved memory size using `-XX:CompressedClassSpaceSize` or `-XX:MaxMetaspaceSize` and make sure that the host has enough memory for the Java heap. -- `port 9600` +### Java heap size - Allows you to access Performance Analyzer on port 9600. +OpenSearch uses a 1 GB Java heap by default (`-Xms1g -Xmx1g`). We recommend setting the heap size to half of the system RAM. Set the initial heap size (`-Xms`) and the maximum heap size (`-Xmx`) to the same value. You can set the heap size in either of the following locations: -Do not declare the same JVM options in multiple locations because it can result in unexpected behavior or a failure of the OpenSearch service to start. If you declare JVM options using an environment variable, such as `OPENSEARCH_JAVA_OPTS=-Xms3g -Xmx3g`, then you should comment out any references to that JVM option in `config/jvm.options`. Conversely, if you define JVM options in `config/jvm.options`, then you should not define those JVM options using environment variables. +- The `jvm.options` file in the OpenSearch configuration directory (`config/` for tarball and Windows installations, `/etc/opensearch/` for RPM and Debian installations). +- The `OPENSEARCH_JAVA_OPTS` environment variable, for example, `OPENSEARCH_JAVA_OPTS="-Xms4g -Xmx4g"`. The sample `docker-compose.yml` file uses this variable. + +The default `-Xms1g -Xmx1g` values take precedence over heap sizes specified using percentage notation (`-XX:MinRAMPercentage`, `-XX:MaxRAMPercentage`). For example, if you set `OPENSEARCH_JAVA_OPTS=-XX:MinRAMPercentage=30 -XX:MaxRAMPercentage=70`, OpenSearch uses a 1 GB heap. To set the heap size, use the `-Xms` and `-Xmx` notation. {: .note} +Do not declare the same JVM options in multiple locations because it can result in unexpected behavior or a failure of the OpenSearch service to start. If you declare JVM options using an environment variable, such as `OPENSEARCH_JAVA_OPTS=-Xms3g -Xmx3g`, then comment out any references to that JVM option in `jvm.options`. Conversely, if you define JVM options in `jvm.options`, then do not define those JVM options using environment variables. +{: .note} + +### File descriptors + +OpenSearch requires the user that runs it to be able to open at least 65,535 files. The way you set this limit depends on the installation method: + +- If you use Docker, the sample `docker-compose.yml` file sets the `nofile` ulimits to `65536`. +- If you installed OpenSearch from an RPM or Debian package, the `opensearch` systemd service sets `LimitNOFILE=65535`, so no action is needed. +- If you installed OpenSearch from a tarball, set the limit in `/etc/security/limits.conf`, as described in [Setting limits for tarball installations](#setting-limits-for-tarball-installations). + +### Setting limits for tarball installations + +A user without root privileges cannot raise a limit higher than its hard limit using `ulimit`, so set the limits for the user that runs OpenSearch in `/etc/security/limits.conf`. Add the following lines, replacing `opensearch` with the name of that user. Include the `memlock` line only if you set `bootstrap.memory_lock` to `true`: + +``` +opensearch - nofile 65535 +opensearch - memlock unlimited +``` +{% include copy.html %} + +The limits apply to new login sessions, so log out and log back in before starting OpenSearch. To verify the limits, run `ulimit -n` and `ulimit -l` as that user. + ## Important system properties OpenSearch has a number of system properties, listed in the following table, that you can specify in `config/jvm.options` or `OPENSEARCH_JAVA_OPTS` using `-D` command line argument notation. @@ -117,5 +196,56 @@ Property | Description `opensearch.xcontent.string.length.max=<value>` | By default, OpenSearch does not impose any limits on the maximum length of the JSON/YAML/CBOR/Smile string fields. To protect your cluster against potential distributed denial-of-service (DDoS) or memory issues, you can set the `opensearch.xcontent.string.length.max` system property to a reasonable limit (the maximum is 2,147,483,647), for example, `-Dopensearch.xcontent.string.length.max=5000000`. | `opensearch.xcontent.fast_double_writer=[true|false]` | By default, OpenSearch serializes floating-point numbers using the default implementation provided by the Java Runtime Environment. Set this value to `true` to use the Schubfach algorithm, which is faster but may lead to small differences in precision. Default is `false`. | `opensearch.xcontent.name.length.max=<value>` | By default, OpenSearch does not impose any limits on the maximum length of the JSON/YAML/CBOR/Smile field names. To protect your cluster against potential DDoS or memory issues, you can set the `opensearch.xcontent.name.length.max` system property to a reasonable limit (the maximum is 2,147,483,647), for example, `-Dopensearch.xcontent.name.length.max=50000`. | -`opensearch.xcontent.depth.max=<value>` | By default, OpenSearch does not impose any limits on the maximum nesting depth for JSON/YAML/CBOR/Smile documents. To protect your cluster against potential DDoS or memory issues, you can set the `opensearch.xcontent.depth.max` system property to a reasonable limit (the maximum is 2,147,483,647), for example, `-Dopensearch.xcontent.name.length.max=1000`. | -`opensearch.xcontent.codepoint.max=<value>` | By default, OpenSearch imposes a limit of `52428800` on the maximum size of the YAML documents (in code points). To protect your cluster against potential DDoS or memory issues, you can change the `opensearch.xcontent.codepoint.max` system property to a reasonable limit (the maximum is 2,147,483,647). For example, `-Dopensearch.xcontent.codepoint.max=5000000`. | \ No newline at end of file +`opensearch.xcontent.depth.max=<value>` | By default, OpenSearch does not impose any limits on the maximum nesting depth for JSON/YAML/CBOR/Smile documents. To protect your cluster against potential DDoS or memory issues, you can set the `opensearch.xcontent.depth.max` system property to a reasonable limit (the maximum is 2,147,483,647), for example, `-Dopensearch.xcontent.depth.max=1000`. | +`opensearch.xcontent.codepoint.max=<value>` | By default, OpenSearch imposes a limit of `52428800` on the maximum size of the YAML documents (in code points). To protect your cluster against potential DDoS or memory issues, you can change the `opensearch.xcontent.codepoint.max` system property to a reasonable limit (the maximum is 2,147,483,647). For example, `-Dopensearch.xcontent.codepoint.max=5000000`. | +`opensearch.xcontent.recycler.pool=<value>` | Controls the Jackson buffer recycler pool used for XContent parsing and serialization. Set this property as a JVM option in `config/jvm.options` or `OPENSEARCH_JAVA_OPTS` before startup (for example, `-Dopensearch.xcontent.recycler.pool=thread_local`). OpenSearch reads the value once during class initialization. Valid values are: <br> - `thread_local` (default): Uses a thread-local pool to avoid cross-thread contention. <br> - `default` or `concurrent_deque`: Uses Jackson 3's default concurrent deque pool.<br> - `shared_concurrent_deque`: Uses a single concurrent deque pool shared across the JVM. | + +## Common issues + +The following issues can occur with any installation method. + +### Error message: "max virtual memory areas vm.max_map_count [65530] is too low" + +OpenSearch fails to start on Linux if the `vm.max_map_count` setting of the host is too low. The OpenSearch log contains the following error: + +``` +ERROR: [1] bootstrap checks failed +[1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] +``` + +To fix this error, set `vm.max_map_count` to at least `262144` as described in [Important settings](#important-settings). If you use Docker, set the value on the host machine, not in the container. + +### Error message: "NotSslRecordException: not an SSL/TLS record" + +The demo security configuration serves the REST API over HTTPS. If a client sends a request over HTTP, the client receives an empty reply, and OpenSearch logs the following error for every request: + +``` +io.netty.handler.ssl.NotSslRecordException: not an SSL/TLS record: 474554202f20485454502f312e310d0a... +``` + +To fix this error, send requests to `https://localhost:9200` instead of `http://localhost:9200`. Check every client that connects to OpenSearch, including monitoring tools and other services on the host that send requests on a schedule. + +### Error message: "Password failed validation" + +OpenSearch does not start if the value of `OPENSEARCH_INITIAL_ADMIN_PASSWORD` is not a strong password. The OpenSearch log contains an error similar to the following: + +``` +Password admin failed validation: "Password is too short". Please re-try with a minimum 8 character password and must contain at least one uppercase letter, one lowercase letter, one digit, and one special character that is strong. +``` + +To fix this error, choose a password that meets the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). + +### Error message: "the default discovery settings are unsuitable for production use" + +When OpenSearch binds to an address other than `localhost`, for example, after you set `network.host` to `0.0.0.0` so that other hosts can reach it, OpenSearch enforces bootstrap checks. If the node has no discovery settings, OpenSearch fails to start and logs the following error: + +``` +bound or publishing to a non-loopback address, enforcing bootstrap checks +ERROR: [1] bootstrap checks failed +[1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_cluster_manager_nodes / cluster.initial_master_nodes] must be configured +``` + +To fix this error, configure discovery in `opensearch.yml`: + +- For a single-node cluster, set `discovery.type: single-node`. +- For a multi-node cluster, set `discovery.seed_hosts` and `cluster.initial_cluster_manager_nodes`. For more information, see [Creating a cluster]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/). diff --git a/_install-and-configure/install-opensearch/operator/index.md b/_install-and-configure/install-opensearch/operator/index.md new file mode 100644 index 00000000..675586f8 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/index.md @@ -0,0 +1,220 @@ +--- +layout: default +title: OpenSearch Kubernetes Operator +parent: Installing OpenSearch +nav_order: 10 +has_children: true +redirect_from: + - /clients/k8s-operator/ + - /tools/k8s-operator/ + - /install-and-configure/install-opensearch/operator/ +--- + +# OpenSearch Kubernetes Operator + +The OpenSearch Kubernetes Operator is an open-source Kubernetes operator that helps automate the deployment and provisioning of OpenSearch and OpenSearch Dashboards in a containerized environment. The operator can manage multiple OpenSearch clusters that can be scaled up and down depending on your needs. + +## Installing the operator + +The operator Helm chart installs a validation webhook whose certificate is issued by [cert-manager](https://cert-manager.io/), so cert-manager must be installed in your Kubernetes cluster before you install the operator. If cert-manager is not installed, the operator installation fails. For other options, see [Webhooks](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/userguide/webhooks.md). + +To install the operator using Helm, follow these steps: + +1. Install `cert-manager`. First, add the `cert-manager` Helm repository: + + ```bash + helm repo add jetstack https://charts.jetstack.io + ``` + {% include copy.html %} + + Then install `cert-manager` and its custom resource definitions: + + ```bash + helm install cert-manager jetstack/cert-manager --namespace cert-manager --create-namespace --set crds.enabled=true + ``` + {% include copy.html %} + +1. Add the operator Helm repository: + + ```bash + helm repo add opensearch-operator https://opensearch-project.github.io/opensearch-k8s-operator/ + ``` + {% include copy.html %} + +1. Update your local Helm chart information. If you added the repository previously, this step ensures that Helm installs the latest operator version: + + ```bash + helm repo update + ``` + {% include copy.html %} + +1. Install the operator: + + ```bash + helm install opensearch-operator opensearch-operator/opensearch-operator + ``` + {% include copy.html %} + + +## Quickstart + +After you have successfully installed the operator, you can deploy your first OpenSearch cluster by creating a custom `OpenSearchCluster` object in Kubernetes. + +The following steps show you how to deploy a minimal cluster and are only intended for demonstration purposes. To learn how to configure and manage your cluster for production environments, see [Configuration and management](#configuration-and-management). +{: .important} + +Follow these steps to deploy the cluster, verify that it is running, access it, and clean up resources when finished: + +1. Create a `cluster.yaml` file containing the following content: + + ```yaml + apiVersion: opensearch.org/v1 + kind: OpenSearchCluster + metadata: + name: my-first-cluster + namespace: default + spec: + security: + tls: + transport: + generate: true + http: + generate: true + general: + serviceName: my-first-cluster + version: "3" + dashboards: + enable: true + version: "3" + replicas: 1 + resources: + requests: + memory: "512Mi" + cpu: "200m" + limits: + memory: "512Mi" + cpu: "200m" + nodePools: + - component: nodes + replicas: 3 + diskSize: "5Gi" + nodeSelector: + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "cluster_manager" + - "data" + ``` + {% include copy.html %} + + The `version` values must be quoted strings. The `security.tls` section is required: if you omit it, the OpenSearch pods never become ready. The `security.tls` section enables the Security plugin, and `generate: true` instructs the operator to generate self-signed TLS certificates. The operator also creates the `my-first-cluster-admin-password` and `my-first-cluster-dashboards-password` secrets containing randomly generated passwords. For more information, see [TLS]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-opensearch-config/#tls) and [User and role management]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-security/). + {: .note} + +1. Create the cluster by running the following command: + + ```bash + kubectl apply -f cluster.yaml + ``` + {% include copy.html %} + +1. (Optional) Monitor the cluster status by running the following command: + + ```bash + watch -n 2 kubectl get pods + ``` + {% include copy.html %} + + The operator creates several pods: + + - A bootstrap pod (`my-first-cluster-bootstrap-0`) that helps with initial cluster manager discovery. + - Three pods for the OpenSearch cluster (`my-first-cluster-nodes-0`, `my-first-cluster-nodes-1`, and `my-first-cluster-nodes-2`), named after the `nodes` node pool. + - A pod for the OpenSearch Dashboards instance (`my-first-cluster-dashboards-<id>`). + - A job pod (`my-first-cluster-securityconfig-update-<id>`) that applies the security configuration and then shows the `Completed` status. + + The cluster is ready when the three OpenSearch pods and the OpenSearch Dashboards pod show `1/1` in the `READY` column, which takes about 3 minutes. The operator then removes the bootstrap pod. You can now connect to your cluster using port forwarding. + +1. Retrieve the generated password for the `admin` user from the `my-first-cluster-admin-password` secret: + + ```bash + kubectl get secret my-first-cluster-admin-password -o jsonpath='{.data.password}' | base64 -d; echo + ``` + {% include copy.html %} + +1. Access OpenSearch Dashboards or use the OpenSearch REST API: + + - To access OpenSearch Dashboards, start port forwarding by running the following command: + + ```bash + kubectl port-forward svc/my-first-cluster-dashboards 5601 + ``` + {% include copy.html %} + + Then go to [`http://localhost:5601`](http://localhost:5601) in your browser and log in as the `admin` user using the password that you retrieved in the previous step. + + - To use the OpenSearch REST API, start port forwarding by running the following command: + + ```bash + kubectl port-forward svc/my-first-cluster 9200 + ``` + {% include copy.html %} + + Then open a second terminal and run the following command, replacing `<admin-password>` with the password that you retrieved in the previous step: + + ```bash + curl -k -u 'admin:<admin-password>' "https://localhost:9200/_cat/nodes?v" + ``` + {% include copy.html %} + + The response lists the three deployed nodes. + +1. To delete your cluster, run the following command: + + ```bash + kubectl delete -f cluster.yaml + ``` + {% include copy.html %} + + This removes Kubernetes resources created by the operator but does not delete the persistent volumes. For a complete cleanup, delete the PVCs: + + ```bash + kubectl delete pvc -l opensearch.org/opensearch-cluster=my-first-cluster + ``` + {% include copy.html %} + +Single-node clusters are not supported. Your cluster must have at least 3 nodes with the `master` or `cluster_manager` role configured. +{: .note} + +## Configuration and management + +After deploying your cluster, you can configure and manage it using the following guides: + +- [Operator configuration]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-config/): Operator-level settings such as log levels, namespaces, and `pprof` endpoints. +- [OpenSearch cluster configuration]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-opensearch-config/): OpenSearch-specific settings including node pools, TLS, plugins, and keystore management. +- [OpenSearch Dashboards configuration]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-dashboards-config/): OpenSearch Dashboards settings, including authentication, base path, and TLS. +- [Kubernetes deployment customization]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-kubernetes-custom/): Kubernetes-level settings such as persistence, security contexts, volumes, and probes. +- [Cluster operations]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-cluster-ops/): Cluster lifecycle operations including recovery, upgrades, and volume expansion. +- [User and role management]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-security/): Security settings, users, roles, and access control. +- [Advanced management]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-advanced/): Monitoring, ISM policies, index templates, and snapshot policies. + +## Operator releases + +Note the following about operator releases: + +- For a compatibility matrix of the operator and OpenSearch releases, see [Compatibility](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/README.md#compatibility). +- The [OpenSearch Operator User Guide](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/userguide/main.md) in the repository corresponds to the current development state of the code. To view the documentation for a specific released version, switch to the version tag in the GitHub menu. +- Feature requests are tracked as GitHub issues. If you would like a feature implemented and find a corresponding issue, note that an issue closed as completed means that the feature has been implemented in the development version. It may still take time before the feature is included in an official release. If you're unsure, review the project's release list on GitHub to see whether the feature appears in the release notes. + +## Next steps + +- Before you use the cluster in production, see [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) and [Preparing OpenSearch Dashboards for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/#preparing-opensearch-dashboards-for-production). + +- For more information about customizing your OpenSearch cluster on Kubernetes, including data persistence, authentication methods, and scaling, see the [OpenSearch Kubernetes Operator User Guide](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/userguide/main.md). + +- To contribute to the development of the OpenSearch Kubernetes Operator, see the repository [design documents](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/designs/high-level.md). + +- For more information, see [OpenSearch Operator](https://operatorhub.io/operator/opensearch-operator). diff --git a/_install-and-configure/install-opensearch/operator/operator-advanced.md b/_install-and-configure/install-opensearch/operator/operator-advanced.md new file mode 100644 index 00000000..9d59b695 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-advanced.md @@ -0,0 +1,248 @@ +--- +layout: default +title: Advanced management +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 70 +--- + +# Advanced OpenSearch Operator management + +This page covers advanced cluster management features including monitoring, Index State Management (ISM) policies, index and component templates, and snapshot policies. + +## OpenSearch monitoring + +You can install and enable the [Prometheus exporter plugin for OpenSearch](https://github.com/opensearch-project/opensearch-prometheus-exporter) on your cluster. When enabled, the operator installs the plugin into the OpenSearch pods and generates a Prometheus `ServiceMonitor` object to configure the plugin for scraping. + +By default, the admin user is used to access the monitoring API. To use a separate user with limited permissions, create that user using one of the following options: + +- Create a user using the OpenSearch API or Dashboards, create a Kubernetes secret with `username` and `password` keys, and provide that secret name in the `monitoringUserSecret` field. +- Use the `OpenSearchUser` CRD to create the user and provide the secret in the `monitoringUserSecret` field. For more information, see [User and role management]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-security/). + +To configure monitoring, add the following fields to your cluster `spec`: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +metadata: + name: my-first-cluster + namespace: default +spec: + general: + version: <YOUR_CLUSTER_VERSION> + monitoring: + enable: true # Enable or disable the monitoring plugin + labels: # The labels added to the ServiceMonitor + someLabelKey: someLabelValue + scrapeInterval: 30s # The scrape interval for Prometheus + monitoringUserSecret: monitoring-user-secret # Optional, name of a secret with username/password for Prometheus to access the plugin metrics endpoint with, defaults to the admin user + pluginUrl: https://github.com/opensearch-project/opensearch-prometheus-exporter/releases/download/<YOUR_CLUSTER_VERSION>.0/prometheus-exporter-<YOUR_CLUSTER_VERSION>.0.zip # Optional, custom URL for the monitoring plugin + tlsConfig: # Optional, use this to override the tlsConfig of the generated ServiceMonitor, only the following provided options can be set + serverName: "testserver.test.local" + insecureSkipVerify: true # The operator currently does not allow configuring the ServiceMonitor with certificates, so this needs to be set + # ... +``` +{% include copy.html %} + +## Managing ISM policies with Kubernetes resources + +The operator provides a custom Kubernetes resource that lets you create, update, or manage ISM policies using Kubernetes objects. + +Fields in the CRD directly map to the OpenSearch ISM policy structure. The operator does not modify policies that already exist. You can create an example policy as follows: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchISMPolicy +metadata: + name: sample-policy +spec: + opensearchCluster: + name: my-first-cluster + description: Hot-warm-delete lifecycle policy + policyId: sample-policy + defaultState: hot + states: + - name: hot + actions: + - replicaCount: + numberOfReplicas: 4 + transitions: + - stateName: warm + conditions: + minIndexAge: "10d" + - name: warm + actions: + - replicaCount: + numberOfReplicas: 2 + transitions: + - stateName: delete + conditions: + minIndexAge: "30d" + - name: delete + actions: + - delete: {} +``` +{% include copy.html %} + +The `OpenSearchISMPolicy` must be created in the same namespace as the OpenSearch cluster. The `policyId` field is optional; if not provided, the operator uses `metadata.name`. + +## Managing index and component templates + +The operator provides the `OpensearchIndexTemplate` and `OpensearchComponentTemplate` CRDs for managing index and component templates. + +The two CRD specifications closely mirror the OpenSearch API structure with some field name changes from `snake_case` to `camelCase`: + +- `index_patterns` → `indexPatterns` (`OpensearchIndexTemplate` only) +- `composed_of` → `composedOf` (`OpensearchIndexTemplate` only) +- `template.aliases.<alias>.is_write_index` → `template.aliases.<alias>.isWriteIndex` + +The following example creates a component template that sets the number of shards and replicas and specifies a time format for documents: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchComponentTemplate +metadata: + name: sample-component-template +spec: + opensearchCluster: + name: my-first-cluster + + template: # required + aliases: # optional + my_alias: {} + settings: # optional + number_of_shards: 2 + number_of_replicas: 1 + mappings: # optional + properties: + timestamp: + type: date + format: yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis + value: + type: double + version: 1 # optional + _meta: # optional + description: example description +``` +{% include copy.html %} + +The following index template uses the component template defined earlier (see `composedOf`) for all indexes matching the `logs-2020-01-*` pattern: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchIndexTemplate +metadata: + name: sample-index-template +spec: + opensearchCluster: + name: my-first-cluster + + name: logs_template # name of the index template - defaults to metadata.name. Can't be updated in-place + + indexPatterns: # required index patterns + - "logs-2020-01-*" + composedOf: # optional + - sample-component-template + priority: 100 # optional + + template: {} # optional + version: 1 # optional + _meta: {} # optional +``` +{% include copy.html %} + +The `.spec.name` field of the index template is immutable and cannot be changed after deployment. +{: .note} + +## Apply ISM policies to existing indexes + +To apply an ISM policy to existing indexes in the OpenSearch cluster, set the `applyToExistingIndices` flag to `true` in the `OpenSearchISMPolicy` CRD: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchISMPolicy +metadata: + name: test-policy-apply +spec: + opensearchCluster: + name: opensearch-cluster + applyToExistingIndices: true + description: "ISM policy applied to existing indexes" + defaultState: "hot" + ismTemplate: + indexPatterns: + - "logs-*" + states: + - name: hot + actions: + - replicaCount: + numberOfReplicas: 2 + transitions: + - stateName: warm + conditions: + minIndexAge: "1d" + - name: warm + actions: + - replicaCount: + numberOfReplicas: 1 +``` +{% include copy.html %} + +The `applyToExistingIndices` field defaults to `false` if omitted. +{: .note} + +When set to `true`, the operator applies the ISM policy to all existing indexes matching the specified index pattern. If multiple ISM policies target the same index pattern with this flag enabled, each policy must have a different priority. + +## Managing snapshot policies with Kubernetes resources + +The operator provides a custom Kubernetes resource to create, update, and manage Snapshot Lifecycle Management (SLM) policies using Kubernetes manifests. This allows you to declaratively define and control snapshot policies alongside your cluster resources. + +Fields in the CRD map directly to the OpenSearch snapshot policy structure. The operator does not modify policies that already exist. You can define a new policy using the following example: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchSnapshotPolicy +metadata: + name: sample-policy + namespace: default +spec: + policyName: sample-policy + enabled: true + description: Daily snapshot policy with weekly retention + opensearchCluster: + name: my-first-cluster + creation: + schedule: + cron: + expression: "0 0 * * *" + timezone: "UTC" + timeLimit: "1h" + deletion: + schedule: + cron: + expression: "0 1 * * *" + timezone: "UTC" + timeLimit: "30m" + deleteCondition: + maxAge: "7d" + maxCount: 10 + minCount: 3 + snapshotConfig: + repository: sample-repository + indices: "*" + includeGlobalState: true + ignoreUnavailable: false + partial: false + dateFormat: "yyyy-MM-dd-HH-mm" + dateFormatTimezone: "UTC" + metadata: + createdBy: "sample-operator" +``` +{% include copy.html %} + +Note the following considerations: + +- The `OpensearchSnapshotPolicy` must be created in the same namespace as the OpenSearch cluster it targets. +- `policyName` is optional. If not provided, the operator uses `metadata.name`. +- The `repository` field must reference an existing snapshot repository configured in the OpenSearch cluster. For information about configuring snapshot repositories, see [Configuring snapshot repositories]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-opensearch-config/#configuring-snapshot-repositories). +{: .note} diff --git a/_install-and-configure/install-opensearch/operator/operator-cluster-ops.md b/_install-and-configure/install-opensearch/operator/operator-cluster-ops.md new file mode 100644 index 00000000..2929bfbb --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-cluster-ops.md @@ -0,0 +1,65 @@ +--- +layout: default +title: Cluster operations +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 50 +--- + +# Cluster operations + +The operator automates common management tasks during the cluster lifecycle, including failure recovery, rolling upgrades, configuration changes, and volume expansion. + +## Cluster recovery + +The operator automatically handles common failure scenarios and restarts crashed pods. Normally, the operator restarts pods one by one to maintain quorum and cluster stability. + +If the operator detects multiple crashed or missing pods for a node pool at the same time, it switches into a special recovery mode that starts all pods at once and allows the cluster to form a new quorum. This parallel recovery mode is experimental and only works with PVC-based storage, as it uses the number of existing PVCs to determine the number of missing pods. + +The recovery is done by temporarily changing the `StatefulSet` underlying each node pool and setting the `podManagementPolicy` to `Parallel`. If you encounter problems, disable parallel recovery by redeploying the operator and adding `manager.parallelRecoveryEnabled: false` to your `values.yaml`. Report any issues by opening a GitHub issue in the operator project. + +The recovery mode also activates if you delete your cluster but keep the PVCs and then reinstall the cluster. + +If every node pool uses `emptyDir` storage, the operator starts recovery in the following failure scenarios: + +1. More than half the cluster manager nodes are missing or crashed, breaking the quorum. +2. All data nodes are missing or crashed, leaving no data node available. + +Because `emptyDir` storage is ephemeral, data is lost and not recoverable when pods are deleted. The operator deletes and recreates the entire OpenSearch cluster in this scenario. + +## Rolling upgrades + +The operator supports automatic rolling version upgrades. To upgrade, change the `general.version` in your cluster `spec` and reapply it: + +```yaml +spec: + general: + version: 3.0.0 +``` +{% include copy.html %} + +The operator then performs a rolling upgrade, restarting nodes one by one and waiting after each node for the cluster to stabilize and reach a green status. Depending on the number of nodes and the size of the data stored, this can take some time. + +Downgrades and upgrades spanning more than one major version are not supported, as they put the OpenSearch cluster in an unsupported state. If you use `emptyDir` storage for data nodes, set `general.drainDataNodes` to `true` to avoid data loss. + +## Configuration changes + +If you change the OpenSearch configuration on an already installed cluster, the operator detects it and performs a rolling restart of all cluster nodes to apply the new configuration. For more information about adding OpenSearch configuration, see [Configuring opensearch.yml]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-opensearch-config/#configuring-opensearchyml). The same applies to node-pool-specific configuration such as `resources`, `annotations`, or `labels`. + +## Volume expansion + +If your underlying storage supports online volume expansion, the operator can orchestrate that action for you. + +To increase the disk volume size, set the `diskSize` of a node pool to the desired value and reapply the cluster `spec` YAML. This operation has no downtime, and the cluster remains operational. + +Consider the following when increasing the disk size: + +- This only works for PVC-based persistence. +- Before expanding the cluster disk, back up the volumes and data so that any failure can be recovered by restoring from the backup. +- Ensure the cluster storage class has `allowVolumeExpansion: true` before applying the new `diskSize`. For more information, see [Kubernetes storage classes](https://kubernetes.io/docs/concepts/storage/storage-classes/). +- After verifying the storage class configuration, apply the cluster YAML with the new `diskSize` value to all node pools or to a single node pool. +- Do not apply any other changes to the cluster at the same time as volume expansion. +- Ensure the size unit is consistent. For example, if the `diskSize` is `30G`, use `G` for expansion (such as `50G`). Do not switch between `G` and `Gi` during expansion. + +To change the `diskSize` unit from `G` to `Gi` or the other way around, first back up the data and calculate the correct conversion so that the underlying volume size remains the same. Then reapply the cluster YAML. This ensures the `StatefulSet` is re-created with the correct value in `VolumeClaimTemplates`. This operation has no downtime. +{: .note} diff --git a/_install-and-configure/install-opensearch/operator/operator-config.md b/_install-and-configure/install-opensearch/operator/operator-config.md new file mode 100644 index 00000000..e8134907 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-config.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Operator configuration +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 10 +--- + +# Operator configuration + +You can configure general options for the operator itself using Helm values you provide during installation: `helm install opensearch-operator opensearch-operator/opensearch-operator -f values.yaml`. + +For a list of all supported values, see the default chart [`values.yaml`](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/charts/opensearch-operator/values.yaml). The following are some important configuration options: + +```yaml +manager: + # Log level of the operator. Possible values: debug, info, warn, error + loglevel: info + + # If specified, the operator will be restricted to watch objects only in the desired namespace. The default is to watch all namespaces. + # To watch multiple namespaces, either separate their names using commas or define them as a list. + # Examples: + # watchNamespaces: 'ns1,ns2' + # watchNamespace: [ns1, ns2] + watchNamespace: + + # Configure extra environment variables for the operator. You can also pull them from secrets or ConfigMaps. + extraEnv: [] + # - name: MY_ENV + # value: somevalue +``` +{% include copy.html %} + +The operator uses admission controller webhooks to validate OpenSearch Custom Resource Definitions (CRDs). +{: .note} + +<!-- vale off --> +## pprof endpoints +<!-- vale on --> + +To diagnose memory issues, you can enable the standard Go [`pprof`](https://pkg.go.dev/net/http/pprof) endpoints by adding the following to your `values.yaml`: + +```yaml +manager: + pprofEndpointsEnabled: true +``` +{% include copy.html %} + +For security reasons, the endpoints are only exposed on `localhost` inside the pod. To access them, use port-forwarding: + +```bash +kubectl port-forward deployment/opensearch-operator-controller-manager 6060 +``` +{% include copy.html %} + +Then use the Go `pprof` tool from another terminal: + +```bash +go tool pprof http://localhost:6060/debug/pprof/heap +``` +{% include copy.html %} + +## Custom operator communication URL + +You can configure the operator to use a custom URL when communicating with OpenSearch by setting the `operatorClusterURL` field: + +```yaml +spec: + general: + serviceName: my-cluster + version: "3.0.0" + httpPort: 9200 + vendor: "opensearch" + operatorClusterURL: "opensearch.example.com" # Optional: custom FQDN for operator communication +``` +{% include copy.html %} + +Use this configuration when you have external certificates (for example, from cert-manager) valid for a specific FQDN. The operator uses this custom URL instead of the default internal Kubernetes DNS name, allowing you to use the same certificate for both external access and operator communication. diff --git a/_install-and-configure/install-opensearch/operator/operator-dashboards-config.md b/_install-and-configure/install-opensearch/operator/operator-dashboards-config.md new file mode 100644 index 00000000..61f2d865 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-dashboards-config.md @@ -0,0 +1,115 @@ +--- +layout: default +title: OpenSearch Dashboards configuration +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 30 +--- + +# OpenSearch Dashboards configuration + +The operator can automatically deploy and manage an OpenSearch Dashboards instance. To enable it, add the following section to your cluster `spec`: + +```yaml +# ... +spec: + dashboards: + enable: true # Set to true to enable the OpenSearch Dashboards deployment + version: 3.0.0 # The OpenSearch Dashboards version to deploy. This should match the OpenSearch cluster version + replicas: 1 # The number of replicas to deploy +``` +{% include copy.html %} + +## Configuring opensearch_dashboards.yml + +You can customize the OpenSearch Dashboards configuration (`opensearch_dashboards.yml`) using the `additionalConfig` field in the dashboards section of the `OpenSearchCluster` custom resource: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +#... +spec: + dashboards: + additionalConfig: + opensearch_security.auth.type: "proxy" + opensearch.requestHeadersWhitelist: | + ["securitytenant","Authorization","x-forwarded-for","x-auth-request-access-token", "x-auth-request-email", "x-auth-request-groups"] + opensearch_security.multitenancy.enabled: "true" +``` +{% include copy.html %} + +You can use this to configure any of the [backend authentication types]({{site.url}}{{site.baseurl}}/security-plugin/configuration/configuration/) for OpenSearch Dashboards. + +The configuration must be valid. If the configuration is invalid, the OpenSearch Dashboards instance will fail to start. +{: .note} + +## Storing sensitive information in the dashboards configuration + +You may need to store sensitive information in the OpenSearch Dashboards configuration file (for example, a client secret for OpenID Connect). To do this safely, use OpenSearch Dashboards variable substitution. + +Create a secret with the sensitive information (for example, `dashboards-oidc-config`) and mount it as an environment variable in the OpenSearch Dashboards pod. For instructions, see [Adding environment variables to pods]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-kubernetes-custom/#adding-environment-variables-to-pods). You can then reference any keys from that secret in your OpenSearch Dashboards configuration. + +The following example shows a portion of a cluster `spec`: + +```yaml +spec: + dashboards: + env: + - name: OPENID_CLIENT_SECRET + valueFrom: + secretKeyRef: + name: dashboards-oidc-config + key: client_secret + additionalConfig: + opensearch_security.openid.client_secret: "${OPENID_CLIENT_SECRET}" +``` +{% include copy.html %} + +Changing the value in the secret does not directly affect the OpenSearch Dashboards configuration. To apply the changes, restart the OpenSearch Dashboards pods. +{: .note} + +## Configuring a base path + +When using OpenSearch Dashboards behind a reverse proxy on a subpath (for example, `/logs`), configure a base path by setting the `basePath` field. The operator automatically adds the correct configuration options to the OpenSearch Dashboards configuration: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +metadata: + name: my-cluster +spec: + dashboards: + enable: true + basePath: "/logs" +``` +{% include copy.html %} + +This also sets the `server.rewriteBasePath` option to `true`. If you expose OpenSearch Dashboards using an ingress controller, configure it to match this setting. + +## OpenSearch Dashboards HTTP + +OpenSearch Dashboards can expose its API and UI using HTTP or HTTPS. By default, the connection is not encrypted (HTTP). To secure the connection, you can either let the operator generate and sign a certificate or provide your own. The following fields in the `OpenSearchCluster` custom resource configure TLS for OpenSearch Dashboards: + +```yaml +# ... +spec: + dashboards: + enable: true # Deploy OpenSearch Dashboards component + tls: + enable: true # Configure TLS + generate: true # Have the operator generate and sign a certificate + # How long generated certificates are valid (default: 8760h = 1 year) + duration: "8760h" + secret: + name: # Name of the secret that contains the provided certificate + caSecret: + name: # Name of the secret that contains a CA the operator should use +# ... +``` +{% include copy.html %} + +To let the operator generate the certificate, set `tls.enable: true` and `tls.generate: true` (you can omit the other fields under `tls`). As with the node certificates, you can supply your own CA using `caSecret.name` for the operator to use. + +To use your own certificate, provide it as a Kubernetes TLS secret (with fields `tls.key` and `tls.crt`) and specify the secret name in `secret.name`. + +When exposing OpenSearch Dashboards outside the cluster, use operator-generated certificates internally and let an ingress controller present a valid certificate from an accredited CA (for example, Let's Encrypt). diff --git a/_install-and-configure/install-opensearch/operator/operator-kubernetes-custom.md b/_install-and-configure/install-opensearch/operator/operator-kubernetes-custom.md new file mode 100644 index 00000000..05aa6502 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-kubernetes-custom.md @@ -0,0 +1,663 @@ +--- +layout: default +title: Kubernetes deployment customization +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 40 +--- + +# Kubernetes deployment customization + +Besides configuring OpenSearch itself, you can also customize how the operator deploys the OpenSearch and OpenSearch Dashboards pods. + +## Data persistence + +By default, the operator creates OpenSearch node pools with persistent storage from the default [Storage Class](https://kubernetes.io/docs/concepts/storage/storage-classes/). This behavior can be changed per node pool. You may supply an alternative storage class and access mode, or configure `hostPath` or `emptyDir` storage. + +The available storage options are: + +<!-- vale off --> +### Persistent Volume Claim (PVC) +<!-- vale on --> + +The default option is persistent storage using PVCs. You can explicitly define the `storageClass`, `annotations`, and `labels` if needed: + +```yaml +nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "data" + - "master" + persistence: + pvc: + storageClass: mystorageclass # Set the name of the storage class to be used + accessModes: # You can change the accessMode + - ReadWriteOnce + annotations: # You can add annotations + test.io/crypt-key-id: "your-kms-key-id" + labels: # You can add labels + team: "backend-data" +``` +{% include copy.html %} + +<!-- vale off --> +### emptyDir +<!-- vale on --> + +If you do not want to use persistent storage, you can use the `emptyDir` option. Note that this can lead to data loss, so you should only use this option for testing or for data that is otherwise persisted. + +```yaml +nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "data" + - "master" + persistence: + emptyDir: {} # This configures emptyDir +``` +{% include copy.html %} + +If you are using `emptyDir`, set `spec.general.drainDataNodes` to `true`. This ensures that shards are drained from the pods before rolling upgrades or restart operations are performed. + +<!-- vale off --> +### hostPath +<!-- vale on --> + +As a last option, you can use `hostPath`. Using `hostPath` is strongly discouraged. By default, the operator applies pod anti-affinity to prevent multiple pods from scheduling on the same node, which helps when using `hostPath`. However, if you need stricter control, configure explicit affinity rules for the node pool to ensure that multiple pods do not schedule to the same Kubernetes host. + +```yaml +nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "data" + - "master" + persistence: + hostPath: + path: "/var/opensearch" # Define the path on the host here +``` +{% include copy.html %} + +## Security context for pods and containers + +You can set the security context for the OpenSearch pods and the OpenSearch Dashboards pod to define privilege and access control settings. To specify security settings for pods, include the `podSecurityContext` field. For containers, include the `securityContext` field. + +The structure is the same for both OpenSearch pods (in `spec.general`) and the OpenSearch Dashboards pod (in `spec.dashboards`): + +```yaml +spec: + general: + podSecurityContext: + runAsUser: 1000 + runAsGroup: 1000 + runAsNonRoot: true + securityContext: + allowPrivilegeEscalation: false + privileged: false + dashboards: + podSecurityContext: + fsGroup: 1000 + runAsNonRoot: true + securityContext: + capabilities: + drop: + - ALL + privileged: false +``` +{% include copy.html %} + +The OpenSearch pods by default launch an init container to configure the volume. This container needs to run with root permissions and does not use a defined `securityContext`. If your Kubernetes environment does not allow containers with the root user, [disable this init helper](#disabling-the-init-helper). In this situation, set `general.setVMMaxMapCount` to `false` because this feature also launches an init container with root. + +The bootstrap pod started during initial cluster setup uses the same pod `securityContext` as the OpenSearch pods (with the same limitations for the init containers). +{: .note} + +The bootstrap pod uses persistent storage (PVC) to maintain cluster state across restarts during initialization. This prevents cluster formation failures when the bootstrap pod restarts after the security configuration update job completes. The bootstrap PVC is automatically created and deleted along with the bootstrap pod. + +## Labels or annotations on OpenSearch nodes + +You can add additional labels or annotations to the node pool configuration. This is useful for integration with other applications, such as a service mesh, or for configuring a Prometheus scrape endpoint. + +Additionally, you can configure annotations globally using the `spec.general.annotations` field. These annotations apply not only to the node pool but also to Kubernetes services. + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "5Gi" + labels: # Add any extra labels as key-value pairs here + someLabelKey: someLabelValue + annotations: # Add any extra annotations as key-value pairs here + someAnnotationKey: someAnnotationValue + nodeSelector: + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "data" + - "master" +``` +{% include copy.html %} + +Any annotations and labels defined are added directly to the node pool pods. + +## Add labels or annotations to the OpenSearch Dashboards deployment + +You can add labels or annotations to the OpenSearch Dashboards pod specification. This is helpful if you want OpenSearch Dashboards to be part of a service mesh or integrate with other applications that rely on labels or annotations. + +```yaml +spec: + dashboards: + enable: true + version: 3.0.0 + replicas: 1 + labels: # Add any extra labels as key-value pairs here + someLabelKey: someLabelValue + annotations: # Add any extra annotations as key-value pairs here + someAnnotationKey: someAnnotationValue +``` +{% include copy.html %} + +Any annotations and labels defined are added directly to the OpenSearch Dashboards pods. + +## Priority class on OpenSearch nodes + +You can configure OpenSearch nodes to use a `PriorityClass` by specifying the priority class name. This helps prevent unwanted evictions of your OpenSearch nodes. + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "5Gi" + priorityClassName: somePriorityClassName + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "master" +``` +{% include copy.html %} + +## Pod affinity + +By default, the operator applies pod anti-affinity rules to prevent multiple pods from the same OpenSearch cluster from being scheduled on the same node. This improves high availability by reducing the risk of multiple pods being affected by a single node failure. + +The default anti-affinity uses `PreferredDuringSchedulingIgnoredDuringExecution`, which is a soft preference that won't prevent scheduling if no other nodes are available, but will prefer to spread pods across nodes. + +You can override this default behavior by explicitly setting the `affinity` field in your node pool, bootstrap, or OpenSearch Dashboards configuration: + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "master" + - "data" + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchLabels: + opensearch.org/opensearch-cluster: my-cluster + topologyKey: kubernetes.io/hostname + bootstrap: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + labelSelector: + matchLabels: + opensearch.org/opensearch-cluster: my-cluster + topologyKey: kubernetes.io/hostname + dashboards: + enable: true + affinity: + podAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + labelSelector: + matchLabels: + app: opensearch-dashboards + topologyKey: kubernetes.io/zone +``` +{% include copy.html %} + +If you set an explicit `affinity`, it completely replaces the default anti-affinity behavior. To disable anti-affinity entirely, set `affinity: {}`. + +## Sidecar containers + +You can deploy additional sidecar containers alongside OpenSearch in the same pod. This is useful for log shipping, monitoring agents, or other auxiliary services that need to run alongside OpenSearch nodes. + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "master" + - "data" + sidecarContainers: + - name: log-shipper + image: fluent/fluent-bit:latest + resources: + requests: + memory: "64Mi" + cpu: "100m" + limits: + memory: "128Mi" + cpu: "200m" + volumeMounts: + - name: varlog + mountPath: /var/log + - name: monitoring-agent + image: prometheus/node-exporter:latest + ports: + - containerPort: 9100 + name: metrics +``` +{% include copy.html %} + +Sidecar containers share the same network namespace and storage volumes as the OpenSearch container because they run in the same pod. + +## Additional volumes + +You can mount additional volumes into the OpenSearch pods to provide additional configuration (for example, plugin config files). Supported volume types include `ConfigMap`, `Secret`, `emptyDir`, projected volumes, and CSI volumes. + +Provide an array of additional volumes in either `spec.general.additionalVolumes` or `spec.dashboards.additionalVolumes`: + +```yaml +spec: + general: + additionalVolumes: + - name: example-configmap + path: /path/to/mount/volume + #subPath: mykey # Add this to mount only a specific key of the configmap/secret + configMap: + name: config-map-name + restartPods: true # Set this to true to restart the pods when the content of the configMap changes + - name: temp + path: /tmp + emptyDir: {} + - name: example-csi-volume + path: /path/to/mount/volume + #subPath: "subpath" # Add this to mount the CSI volume at a specific subpath + csi: + driver: csi-driver-name + readOnly: true + volumeAttributes: + secretProviderClass: example-secret-provider-class + - name: example-projected-volume + path: /path/to/mount/volume + projected: + sources: + - serviceAccountToken: + path: "token" + - name: example-persistentvolumeclaim-volume + path: /path/to/mount/volume + persistentVolumeClaim: + claimName: claim-name + - name: nfs-volume + path: /mnt/backups/opensearch + nfs: + server: 192.168.1.233 + path: /export/backups/opensearch + readOnly: false # Optional, defaults to false + dashboards: + additionalVolumes: + - name: example-secret + path: /path/to/mount/volume + secret: + secretName: secret-name +``` +{% include copy.html %} + +### NFS volume support + +NFS volumes can be mounted directly into OpenSearch pods without requiring external provisioners or CSI drivers. This is particularly useful for snapshot repositories stored on NFS shares. To configure an NFS volume, specify the `nfs` field with the required `server` and `path` parameters: + +```yaml +spec: + general: + additionalVolumes: + - name: nfs-backups + path: /mnt/backups/opensearch + nfs: + server: 192.168.1.233 + path: /export/backups/opensearch + readOnly: false # Optional, defaults to false +``` +{% include copy.html %} + +This can be combined with snapshot repository configuration: + +```yaml +spec: + general: + additionalVolumes: + - name: nfs-backups + path: /mnt/backups/opensearch + nfs: + server: 192.168.1.233 + path: /export/backups/opensearch + snapshotRepositories: + - name: nfs-repository + type: fs + settings: + location: /mnt/backups/opensearch +``` +{% include copy.html %} + +The operator adds the defined volumes to all pods of the OpenSearch cluster. It is currently not possible to define them per node pool (`nodePools`). + +## Adding environment variables to pods + +You can add your own environment variables to the OpenSearch pods and the OpenSearch Dashboards pods. You can provide the value as a string literal or mount it from a secret or `ConfigMap`. + +The structure is the same for both OpenSearch and OpenSearch Dashboards: + +```yaml +spec: + dashboards: + env: + - name: MY_ENV_VAR + value: "myvalue" + - name: MY_SECRET_VAR + valueFrom: + secretKeyRef: + name: my-secret + key: some_key + - name: MY_CONFIGMAP_VAR + valueFrom: + configMapKeyRef: + name: my-configmap + key: some_key + nodePools: + - component: nodes + env: + - name: MY_ENV_VAR + value: "myvalue" + # The other options are supported here as well. +``` +{% include copy.html %} + +## Custom cluster domain name + +If your Kubernetes cluster is configured with a custom domain name (default is `cluster.local`), configure the operator accordingly for internal routing to work properly. Set `manager.dnsBase` in the Helm chart values. + +```yaml +manager: + # ... + dnsBase: custom.domain +``` +{% include copy.html %} + +## Custom init helper + +During cluster initialization, the operator uses init containers as helpers. For these containers, a `busybox` image is used (specifically `docker.io/busybox:latest`). If you are working in an offline environment and the cluster cannot access the registry or you want to customize the image, you can override the image used by specifying the `initHelper` image in your cluster `spec`: + +```yaml +spec: + initHelper: + # You can either only specify the version + version: "1.27.2-buildcustom" + # Or specify a totally different image + image: "mycustomrepo.cr/mycustombusybox:myversion" + # Additionally you can define the imagePullPolicy + imagePullPolicy: IfNotPresent + # and imagePullSecrets if needed + imagePullSecrets: + - name: docker-pull-secret +``` +{% include copy.html %} + +## Edit init container resources + +Init containers run without any resource constraints, but it's possible to specify resource requests and limits by adding a resources section to the YAML definition. You can control the amount of CPU and memory allocated to the init container, helping to ensure that it doesn't starve other containers, by setting appropriate resource limits. + +```yaml +spec: + initHelper: + resources: + requests: + memory: "128Mi" + cpu: "250m" + limits: + memory: "512Mi" + cpu: "500m" +``` +{% include copy.html %} + +## Disabling the init helper + +In some cases, you may want to avoid the `chmod` init container (for example, on OpenShift or if your cluster blocks containers running as `root`). +It can be disabled by adding the following to your `values.yaml`: + +```yaml +manager: + extraEnv: + - name: SKIP_INIT_CONTAINER + value: "true" +``` +{% include copy.html %} + +## PodDisruptionBudget + +The PDB (Pod Disruption Budget) is a Kubernetes resource that helps ensure the high availability of applications by defining the acceptable disruption level during maintenance or unexpected events. +It specifies the minimum number of pods that must remain available to maintain the desired level of service. +The PDB definition is unique for every node pool (`nodePools`). +Provide either `minAvailable` or `maxUnavailable` to configure PDB, but not both. + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + pdb: + enable: true + minAvailable: 3 + - component: datas + replicas: 7 + diskSize: "100Gi" + pdb: + enable: true + maxUnavailable: 2 +``` +{% include copy.html %} + +## Exposing OpenSearch Dashboards + +To expose the OpenSearch Dashboards instance of your cluster for users or services outside of your Kubernetes cluster, the recommended way is to use ingress. + +A simple example: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: opensearch-dashboards + namespace: default +spec: + tls: + - hosts: + - dashboards.my.company + rules: + - host: dashboards.my.company + http: + paths: + - backend: + service: + name: my-cluster-dashboards + port: + number: 5601 + path: "/(.*)" + pathType: ImplementationSpecific +``` +{% include copy.html %} + +If you have enabled HTTPS for OpenSearch Dashboards, instruct your ingress controller to use an HTTPS connection internally. This is specific to the controller you are using (for example, nginx-ingress or `traefik`). +{: .note} + +## Configuring the OpenSearch Dashboards Kubernetes service + +You can customize the Kubernetes Service object that the operator generates for the OpenSearch Dashboards deployment. + +Supported Service Types: + +- ClusterIP (default) +- NodePort +- LoadBalancer + +When using type `LoadBalancer`, you can optionally set the load balancer source ranges. + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + dashboards: + service: + type: LoadBalancer # Set one of the supported types + loadBalancerSourceRanges: "10.0.0.0/24, 192.168.0.0/24" # Optional, add source ranges for a load balancer +``` +{% include copy.html %} + +## Exposing the OpenSearch cluster REST API + +To expose the REST API of OpenSearch outside your Kubernetes cluster, the recommended way is to use ingress. +Internally, use self-signed certificates (you can let the operator generate them) and then let the ingress use a certificate from an accepted CA (for example, Let's Encrypt or a company-internal CA). That way you do not have the hassle of supplying custom certificates to the OpenSearch cluster but your users still see valid certificates. + +## Customizing probe timeouts and thresholds + +If the cluster nodes do not start before the threshold is reached and the pod restarts, you can configure the timeouts and thresholds per node as needed. + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + probes: + liveness: + initialDelaySeconds: 10 + periodSeconds: 20 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 10 + startup: + initialDelaySeconds: 10 + periodSeconds: 20 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 10 + readiness: + initialDelaySeconds: 60 + periodSeconds: 30 + timeoutSeconds: 30 + successThreshold: 1 + failureThreshold: 5 +``` +{% include copy.html %} + +## Customize startup and readiness probe command + +While the `liveness` probe is a TCP check, the startup and readiness probes use the OpenSearch API with cURL. + +If you need to customize the startup or readiness probe commands, you can override them as shown in the following example: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +... +spec: + nodePools: + - component: masters + ... + probes: + startup: + command: + - echo + - "Hello, World!" + readiness: + command: + - echo + - "Hello, World!" +``` +{% include copy.html %} + +## Configuring resource limits and requests + +In addition to the information provided in the previous sections on how to specify resource requirements for the node pools, you can also specify resources for all entities created by the operator for more advanced use cases. + +The operator generates many pods using resources such as jobs, stateful sets, and replica sets that use init containers. The following configuration lets you specify a default resources configuration for all init containers. + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + initHelper: + resources: + requests: + memory: "50Mi" + cpu: "50m" + limits: + memory: "200Mi" + cpu: "200m" +``` +{% include copy.html %} + +You can also configure the resources for the security update job as shown in the following example. + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + security: + config: + updateJob: + resources: + limits: + cpu: "100m" + memory: "100Mi" + requests: + cpu: "100m" + memory: "100Mi" +``` +{% include copy.html %} + +The examples provided here do not reflect actual resource requirements. You may need to conduct further testing to properly adjust the resources based on your specific needs. +{: .note} diff --git a/_install-and-configure/install-opensearch/operator/operator-opensearch-config.md b/_install-and-configure/install-opensearch/operator/operator-opensearch-config.md new file mode 100644 index 00000000..362a8117 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-opensearch-config.md @@ -0,0 +1,398 @@ +--- +layout: default +title: OpenSearch cluster configuration +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 20 +--- + +# OpenSearch cluster configuration + +The operator deploys and manages OpenSearch clusters. You can configure node pools, TLS certificates, plugins, keystore secrets, and other cluster-specific settings. + +## Node pools and scaling + +OpenSearch clusters consist of one or more node pools. Each node pool is a logical group of nodes with the same [role]({{site.url}}{{site.baseurl}}/tuning-your-cluster/creating-a-cluster/#nodes) and can have its own resources. For each configured node pool, the operator creates a Kubernetes `StatefulSet` and `Service`, allowing you to communicate with specific node pools: + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 # The number of replicas + diskSize: "30Gi" # The disk size to use + resources: # The resource requests and limits for that nodepool + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: # The roles the nodes should have + - "cluster_manager" + - "data" + - component: nodes + replicas: 3 + diskSize: "10Gi" + nodeSelector: + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "data" +``` +{% include copy.html %} + +For additional node pool configuration options, such as storage, security context, labels, and affinity rules, see [Kubernetes deployment customization]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-kubernetes-custom/). + +## Configuring opensearch.yml + +The operator automatically generates an `opensearch.yml` configuration file based on the parameters in the cluster `spec` you provide (for example, Transport Layer Security (TLS) configuration). To add custom settings, use the `additionalConfig` field in the cluster `spec`: + +```yaml +spec: + general: + # ... + additionalConfig: + some.config.option: somevalue + # ... +nodePools: + - component: masters + # ... + additionalConfig: + some.other.config: foobar +``` +{% include copy.html %} + +Use `spec.general.additionalConfig` to add settings applied to all cluster nodes. The operator stores these settings in a shared `ConfigMap` and mounts it to all node pools. + +For node-pool-specific configuration, use `nodePools[].additionalConfig`. The operator merges these settings with `spec.general.additionalConfig` for that node pool, with node pool settings taking precedence. When a node pool has `additionalConfig` defined, it receives its own `ConfigMap` containing the merged configuration. + +Provide all settings as a map of strings using the flat form. For non-string values (for example, Boolean or numeric values), enclose them in quotes: `"true"` or `"1234"`. + +The operator merges its generated settings with the custom settings you provide. You cannot override basic settings such as `node.name`, `node.roles`, `cluster.name`, and network and discovery settings using `additionalConfig`. + +Changing any `additionalConfig` triggers a rolling restart of the cluster. To avoid a restart, use the [Cluster Settings API]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) to change settings at runtime. +{: .note} + +## TLS + +For security reasons, encryption is required for communication with the OpenSearch cluster and between cluster nodes. If you do not configure any encryption, OpenSearch uses the included demo TLS certificates, which are not suitable for active deployments. + +Depending on your requirements, the operator offers the following ways of managing TLS certificates: + +- **Operator-generated certificates (Recommended)**: The operator generates its own Certificate Authority (CA) and signs certificates for all nodes using that CA. Use this option unless you want to directly expose your OpenSearch cluster outside your Kubernetes cluster or your organization has rules about using self-signed certificates for internal communication. +- **Your own certificates**: Supply your own certificates. + +When the operator generates certificates, you can control certificate validity using the `duration` field (for example, `"720h"`, `"17520h"`). If omitted, it defaults to one year (`"8760h"`). +{: .note} + +TLS certificates are used for the following endpoints (each can be configured independently): + +- [Node transport](#node-transport) +- [Node HTTP REST API](#node-http-rest-api) +- [OpenSearch Dashboards HTTP]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-dashboards-config/#opensearch-dashboards-http) + +### Node transport + +OpenSearch cluster nodes communicate with each other using the OpenSearch transport protocol (port 9300 by default). This endpoint is not exposed externally, so in almost all cases, operator-generated certificates are adequate. + +To configure node transport security, you can use the following fields in the `OpenSearchCluster` custom resource: + +```yaml +# ... +spec: + security: + tls: # Everything related to TLS configuration + transport: # Configuration of the transport endpoint + enabled: true # Enable TLS for transport (default: true if transport config exists) + generate: true # Have the operator generate and sign certificates + perNode: true # Separate certificate per node + # How long generated certificates are valid (default: 8760h = 1 year) + duration: "8760h" + secret: + name: # Name of the secret that contains the provided certificate + caSecret: + name: # Name of the secret that contains a CA the operator should use + nodesDn: [] # List of certificate DNs allowed to connect +# ... +``` +{% include copy.html %} + +To have the operator generate the certificates, set `generate` and `perNode` to `true` (you can omit the other fields). The operator generates a CA certificate, issues one certificate per node, and signs them. Certificates default to one year validity, which you can configure using `duration`. The operator supports rotation by reissuing certificates when near expiry if `rotateDaysBeforeExpiry` is set. + +Alternatively, you can provide the certificates yourself (for example, if your organization has an internal CA). You can either provide one certificate to be used by all nodes or provide a certificate for each node (recommended). In this mode, set `generate: false` and `perNode` to `true` or `false` depending on whether you're providing per-node certificates. + +If you provide only one certificate, place it in a Kubernetes TLS secret (with the fields `ca.crt`, `tls.key`, and `tls.crt`, all PEM-encoded) and provide the name of the secret as `secret.name`. To keep the CA certificate separate, place it in a separate secret and supply that as `caSecret.name`. If you provide one certificate per node, place all certificates into one secret (including the `ca.crt`) with a `<hostname>.key` and `<hostname>.crt` for each node. The hostname is defined as `<cluster-name>-<nodepool-component>-<index>` (for example, `my-first-cluster-masters-0`). + +If you provide the certificates yourself, you must also provide the list of certificate Distinguished Names (DNs) in `nodesDn`. Wildcards can be used (for example, `"CN=my-first-cluster-*,OU=my-org"`). + +### Node HTTP REST API + +Each OpenSearch cluster node exposes the REST API using HTTPS (by default, at port 9200). + +To configure HTTP API security, the following fields in the `OpenSearchCluster` custom resource are available: + +```yaml +# ... +spec: + security: + tls: # Everything related to TLS configuration + http: # Configuration of the HTTP endpoint + enabled: true # Enable TLS for HTTP (default: true if http config exists, false to disable) + generate: true # Have the operator generate and sign certificates + customFQDN: "opensearch.example.com" # Optional: Custom FQDN for the certificate + # How long generated certificates are valid (default: 8760h = 1 year) + duration: "8760h" + secret: + name: # Name of the secret that contains the provided certificate + caSecret: + name: # Name of the secret that contains a CA the operator should use +# ... +``` +{% include copy.html %} + +You can either let the operator generate and sign the certificates or provide your own. The only difference between node transport certificates and node HTTP REST API certificates is that per-node certificates are not supported for HTTP REST API. Otherwise, the two work the same way. + +The `enabled` field controls whether TLS is enabled for the HTTP endpoint. If `enabled` is set to `false`, the cluster uses HTTP instead of HTTPS. If `enabled` is `nil` (not set), TLS is enabled by default when the HTTP config exists. To explicitly disable TLS, set `enabled: false`. +{: .note} + +When using generated certificates, you can optionally specify a `customFQDN` field to include a custom domain in the certificate's Subject Alternative Names (SAN) alongside the default cluster DNS names. + +If you provide your own certificates, add the following names as SAN: `<cluster-name>`, `<cluster-name>.<namespace>`, `<cluster-name>.<namespace>.svc`, `<cluster-name>.<namespace>.svc.cluster.local`. + +Directly exposing the node HTTP port outside the Kubernetes cluster is not recommended. Instead, configure an ingress. The ingress can then present a certificate from an accredited CA (for example, Let's Encrypt) and hide self-signed certificates used internally. In this configuration, supply the nodes internally with properly signed certificates. + +If you provide your own node certificates, you must also provide an admin cert that the operator can use for managing the cluster: + +```yaml +spec: + security: + config: + adminSecret: + name: my-first-cluster-admin-cert # The secret must have keys tls.crt and tls.key +``` +{% include copy.html %} + +Make sure the DN of the certificate is set in the `adminDn` field. + +## Adding plugins + +You can extend the OpenSearch functionality using [plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/plugins/#available-plugins). Commonly used ones are snapshot repository plugins for external backups (for example, to Amazon S3 or Microsoft Azure Blob Storage). The operator supports automatically installing plugins during setup. + +To install a plugin for OpenSearch, add it to the `general.pluginsList`: + +```yaml +general: + version: 3.0.0 + httpPort: 9200 + vendor: opensearch + serviceName: my-cluster + pluginsList: + [ + "repository-s3", + "https://github.com/opensearch-project/opensearch-prometheus-exporter/releases/download/3.0.0.0/prometheus-exporter-3.0.0.0.zip", + ] +``` +{% include copy.html %} + +To install a plugin for OpenSearch Dashboards, add it to the `dashboards.pluginsList`: + +```yaml +dashboards: + enable: true + version: 3.0.0 + pluginsList: + - sample-plugin-name +``` +{% include copy.html %} + +To install a plugin for the bootstrap pod, add it to the `bootstrap.pluginsList`: + +```yaml +bootstrap: + pluginsList: ["repository-s3"] +``` +{% include copy.html %} + +Note the following considerations: + +- [Bundled plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/plugins/#bundled-plugins) are installed automatically and do not need to be added to the list. +- You can provide either a plugin name or a complete URL to the plugin ZIP file. The items you provide are passed to the `bin/opensearch-plugin install <plugin-name>` command. +- Updating the plugin list for an already installed cluster triggers a rolling restart of all OpenSearch nodes. +- If your plugin requires additional configuration, provide it in either `additionalConfig` (see [Configuring opensearch.yml](#configuring-opensearchyml)) or as secrets in the OpenSearch keystore (see [Add secrets to keystore](#add-secrets-to-keystore)). + +## Add secrets to keystore + +Some OpenSearch features (for example, snapshot repository plugins) require sensitive configuration. OpenSearch handles this using the OpenSearch keystore. You can populate this keystore using Kubernetes secrets. + +Add the secrets under the `general.keystore` section: + +```yaml +general: + # ... + keystore: + - secret: + name: credentials + - secret: + name: some-other-secret +``` +{% include copy.html %} + +With this configuration, all keys of the secrets become keys in the keystore. + +If you only want to load some keys from a secret or rename the existing keys, you can add key mappings as a map: + +```yaml +general: + # ... + keystore: + - secret: + name: many-secret-values + keyMappings: + # Only read "sensitive-value" from the secret, keep its name. + sensitive-value: sensitive-value + - secret: + name: credentials + keyMappings: + # Renames key accessKey in secret to s3.client.default.access_key in keystore + accessKey: s3.client.default.access_key + password: s3.client.default.secret_key +``` +{% include copy.html %} + +Only provided keys are loaded from the secret. Any keys not specified are ignored. +{: .note} + +To populate the keystore of the bootstrap pod, add the secrets under the `bootstrap.keystore` section: + +```yaml +bootstrap: + # ... + keystore: + - secret: + name: credentials + - secret: + name: some-other-secret +``` +{% include copy.html %} + +## SmartScaler + +SmartScaler is a mechanism built into the operator that enables nodes to be safely removed from the cluster. When a node is being removed from a cluster, the safe drain process ensures that all of its data is transferred to other nodes in the cluster before the node is taken offline. This prevents any data loss or corruption that could occur if the node were shut down or disconnected without first transferring its data to other nodes. + +During the safe drain process, the node being removed is marked as "draining", which means that it no longer receives new requests. Instead, it only processes outstanding requests until its workload is completed. Once all requests are processed, the node begins transferring its data to other nodes in the cluster. The safe drain process continues until all data is transferred and the node is no longer part of the cluster. Only after that does the operator turn down the node. + +## Set the Java heap size + +To configure the amount of memory allocated to the OpenSearch nodes, set the heap size using the `jvm` field. This operation has no downtime, and the cluster remains operational. + +Set the heap size to half of the memory request. +{: .note} + +```yaml +spec: + nodePools: + - component: nodes + replicas: 3 + diskSize: "10Gi" + jvm: -Xmx1024M -Xms1024M + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "data" +``` +{% include copy.html %} + +If `jvm` is not provided, the Java heap size is set to half of `resources.requests.memory`, which is the recommended value for data nodes. + +If `jvm` is not provided and `resources.requests.memory` does not exist, the value is `-Xmx512M -Xms512M`. + +## Configure `vm.max_map_count` + +OpenSearch requires the Linux kernel `vm.max_map_count` option [to be set to at least 262144]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#important-settings). The operator sets this option to `262144` by default using an init container for each OpenSearch pod. If you already set this option on the Kubernetes hosts using `sysctl` and don't want the operator to change it, disable it by adding the following option to your cluster `spec`: + +```yaml +spec: + general: + setVMMaxMapCount: false +``` +{% include copy.html %} + +By default, the init container uses a `busybox` image. To change this (for example, to use an image from a private registry), see [Custom init helper]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/operator/operator-kubernetes-custom/#custom-init-helper). + +## Configuring snapshot repositories + +You can configure snapshot repositories for the OpenSearch cluster using the operator. The `general.snapshotRepositories` field supports multiple snapshot repositories. After configuring a snapshot repository, users can create custom ISM policies in OpenSearch Dashboards to back up indexes. + +```yaml +spec: + general: + snapshotRepositories: + - name: my_s3_repository_1 + type: s3 + settings: + bucket: opensearch-s3-snapshot + region: us-east-1 + base_path: os-snapshot + - name: my_s3_repository_3 + type: s3 + settings: + bucket: opensearch-s3-snapshot + region: us-east-1 + base_path: os-snapshot_1 +``` +{% include copy.html %} + +### Prerequisites for configuring snapshot repositories + +Before configuring `snapshotRepositories` for a cluster, ensure the following prerequisites are met: + +1. The appropriate cloud provider native plugins are installed. For example: + + ```yaml + spec: + general: + pluginsList: ["repository-s3"] + ``` + {% include copy.html %} + +2. The required roles/permissions for the backend cloud are pre-created. The following example shows an Amazon Web Services (AWS) Identity and Access Management (IAM) role added for Kubernetes nodes so that snapshots can be published to the `opensearch-s3-snapshot` S3 bucket: + + ```json + { + "Statement": [ + { + "Action": [ + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:ListBucketMultipartUploads", + "s3:ListBucketVersions" + ], + "Effect": "Allow", + "Resource": ["arn:aws:s3:::opensearch-s3-snapshot"] + }, + { + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:AbortMultipartUpload", + "s3:ListMultipartUploadParts" + ], + "Effect": "Allow", + "Resource": ["arn:aws:s3:::opensearch-s3-snapshot/*"] + } + ], + "Version": "2012-10-17" + } + ``` + {% include copy.html %} diff --git a/_install-and-configure/install-opensearch/operator/operator-security.md b/_install-and-configure/install-opensearch/operator/operator-security.md new file mode 100644 index 00000000..5a16e6d2 --- /dev/null +++ b/_install-and-configure/install-opensearch/operator/operator-security.md @@ -0,0 +1,294 @@ +--- +layout: default +title: User and role management +parent: OpenSearch Kubernetes Operator +grand_parent: Installing OpenSearch +nav_order: 60 +--- + +# User and role management + +User and role management is essential for controlling access to your OpenSearch cluster using the OpenSearch Security plugin. By default, the operator uses the included demo security configuration with default users. For production installations, replace this with your own configuration. + +You can configure security in two ways: + +- Defining your own security configuration +- Managing users and roles using Kubernetes resources + +A combination of both approaches is not supported. After you start using CRDs, you cannot provide your own security configuration because they would overwrite each other. +{: .note} + +## Defining your own security configuration + +You can provide your own [security configuration]({{site.url}}{{site.baseurl}}/security/configuration/yaml/) with custom users and roles. Provide a secret containing all required security configuration YAML files. + +Configure security using the following fields in the `OpenSearchCluster` custom resource: + +```yaml +# ... +spec: + security: + config: # Everything related to the security configuration + securityConfigSecret: + name: # Name of the secret that contains the security configuration files + adminSecret: + name: # Name of a secret that contains the admin client certificate + adminCredentialsSecret: + name: # Name of a secret that contains username/password for admin access +# ... +``` +{% include copy.html %} + +Provide the name of the secret that contains your security configuration YAML files as `securityConfigSecret.name`. This secret acts as the authoritative configuration that you manage. + +The operator creates its own runtime secret named `<cluster-name>-security-config-generated` and copies your files into it. If no secret is supplied, the operator uses the bundled defaults. The operator automatically updates the password hashes for the admin and OpenSearch Dashboards (`kibanaserver`) users before applying the configuration to the cluster. + +You no longer need to provide password hashes for the `admin` or `kibanaserver` users in your security config secret. The operator automatically generates password hashes from the credentials secrets and overrides any hash values you provide in the security config secret for these users. This means you only need to manage passwords in one place (the credentials secrets), not in both the credentials secrets and the security config secret. +{: .important} + +OpenSearch requires all the files to be applied when the cluster is first created. For the files that you do not provide in the security configuration secret, the operator uses the default files provided in the Security plugin. +{: .note} + +To avoid using the default files, provide at least a minimum configuration for each file: + +```yaml +tenants.yml: |- + _meta: + type: "tenants" + config_version: 2 +``` +{% include copy.html %} + +These minimum configuration files can later be removed from the secret so that you don't overwrite the resources created using the CRDs or the REST APIs when modifying other configuration files. + +You can provide a secret as `adminCredentialsSecret.name` with fields `username` and `password` for a user that the operator uses for communicating with OpenSearch. The operator uses this user for retrieving cluster status, performing health checks, and coordinating node draining during cluster scaling operations. + +If you omit this field, the operator automatically creates `<cluster-name>-admin-password` with the default `admin` username and a random password. The operator then generates the password hash and adds it to the generated security configuration. + +If you provide your own secret, the operator reads the password from your secret, generates the hash, and adds it to the generated security configuration without modifying your source secret. + +Similarly, for OpenSearch Dashboards, if you don't provide `dashboards.opensearchCredentialsSecret`, the operator automatically creates `<cluster-name>-dashboards-password` with a random password for the `kibanaserver` user and automatically generates the password hash and adds it to the generated security configuration. + +You must also configure TLS for HTTP. You can either let the operator generate all needed certificates or supply them yourself. If you use your own certificates, you must also provide an admin certificate that the operator can use to apply the security configuration. + +If you provide your own certificate for TLS over HTTP, you must also provide an admin client certificate (as a Kubernetes TLS secret with fields `ca.crt`, `tls.key`, and `tls.crt`) as `adminSecret.name`. The DN of the certificate must be listed under `security.tls.http.adminDn`. + +The `adminDn` must be defined so that the admin certificate cannot be used or recognized as a node certificate. Otherwise, OpenSearch will reject any authentication request using the admin certificate. +{: .important} + +To apply the security configuration to the OpenSearch cluster, the operator uses a separate Kubernetes job (named `<cluster-name>-securityconfig-update`). This job is run during the initial provisioning of the cluster. The operator also monitors the secret with the security configuration for any changes and then reruns the update job to apply the new config. Note that the operator only checks for changes in certain intervals, so it might take a minute or two for the changes to be applied. If the changes are not applied after a few minutes, use `kubectl` to check the logs of the pod of the `<cluster-name>-securityconfig-update` job. If you have an error in your configuration it will be reported there. + +## Managing security configurations with Kubernetes resources + +The operator provides custom Kubernetes resources that let you create, update, or manage security configuration resources such as users, roles, action groups, and tenants as Kubernetes objects. + +### OpenSearch users + +You can manage OpenSearch users in Kubernetes with the operator. The operator does not modify users that already exist. You can create an example user as follows: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchUser +metadata: + name: sample-user + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + passwordFrom: + name: sample-user-password + key: password + backendRoles: + - kibanauser +``` +{% include copy.html %} + +The namespace of the `OpenSearchUser` must be the namespace the OpenSearch cluster itself is deployed in. + +A secret called `sample-user-password` must exist in the `default` namespace with the Base64-encoded password in the `password` key. +{: .note} + +You can also store multiple user passwords in the same secret. To do this, create a secret in which each key equals a user name and the value is the user password. Otherwise, changes in the secret do not trigger user reconciliation. + +### OpenSearch roles + +You can manage OpenSearch roles in Kubernetes with the operator. The operator does not modify roles that already exist. You can create an example role as follows: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchRole +metadata: + name: sample-role + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + clusterPermissions: + - cluster_composite_ops + - cluster_monitor + indexPermissions: + - indexPatterns: + - logs* + allowedActions: + - index + - read +``` +{% include copy.html %} + +### Linking OpenSearch users and roles + +The operator allows you to link any number of users, backend roles, and roles with an OpensearchUserRoleBinding. Each user in the binding is granted each role: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchUserRoleBinding +metadata: + name: sample-urb + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + users: + - sample-user + backendRoles: + - sample-backend-role + roles: + - sample-role +``` +{% include copy.html %} + +### OpenSearch action groups + +You can manage OpenSearch action groups in Kubernetes with the operator. The operator does not modify action groups that already exist. You can create an example action group as follows: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchActionGroup +metadata: + name: sample-action-group + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + allowedActions: + - indices:admin/aliases/get + - indices:admin/aliases/exists + type: index + description: Sample action group +``` +{% include copy.html %} + +### OpenSearch tenants + +You can manage OpenSearch tenants in Kubernetes with the operator. The operator does not modify tenants that already exist. You can create an example tenant as follows: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchTenant +metadata: + name: sample-tenant + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + description: Sample tenant +``` +{% include copy.html %} + +## Custom admin user + +To create your cluster with an admin user different from the default, provide your own admin credentials secret. The operator automatically generates the password hash and adds it to the security config, so you no longer need to manually generate and include the password hash in your security config secret. + +First, create a secret with your admin user configuration (in this example `admin-credentials-secret`): + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: admin-credentials-secret +type: Opaque +data: + # admin + username: YWRtaW4= + # admin123 + password: YWRtaW4xMjM= +``` +{% include copy.html %} + +> You do not need to include the password hash in your security config secret. The operator automatically: +> 1. Reads the password from your `adminCredentialsSecret` +> 2. Generates the `bcrypt` hash +> 3. Overrides the `admin` user's hash in the generated security config secret (`<cluster-name>-security-config-generated`) +{: .important} + +If you provide your own security configuration secret, you can optionally include the admin user definition, but any hash you provide is automatically overridden by the operator: + +```yaml +internal_users.yml: |- + _meta: + type: "internalusers" + config_version: 2 + admin: + # hash field is optional - operator will override it automatically + reserved: true + backend_roles: + - "admin" + description: "Demo admin user" +``` +{% include copy.html %} + +Add the following security configuration to your `cluster.yaml` file: + +```yaml +security: + config: + adminCredentialsSecret: + name: admin-credentials-secret # The secret with the admin credentials for the operator to use + securityConfigSecret: + name: securityconfig-secret # Optional: The secret containing your customized security configuration + tls: + transport: + generate: true + http: + generate: true +``` +{% include copy.html %} + +At a minimum, the `security.tls` section is required for the cluster to start with security enabled. Setting `generate: true` for both `transport` and `http` instructs the operator to automatically generate the required TLS certificates. The operator also automatically creates the admin and OpenSearch Dashboards credentials secrets (`<cluster-name>-admin-password` and `<cluster-name>-dashboards-password`) when they are not explicitly specified. +{: .note} + +### Changing the admin password + +To change the admin password after the cluster has been created, update the password in your `admin-credentials-secret`. The operator automatically: + +1. Detects the password change. +2. Generates a new password hash. +3. Updates the generated security config secret. +4. Triggers a security config update job to apply the changes to OpenSearch. + +You no longer need to manually update the password hash in the security config secret. + +## Custom OpenSearch Dashboards user + +OpenSearch Dashboards requires an OpenSearch user (typically `kibanaserver`) to connect to the cluster. + +If you don't provide a custom credentials secret, the operator automatically: +1. Creates a secret named `<cluster-name>-dashboards-password` with a random password for the `kibanaserver` user. +2. Generates the password hash and automatically adds it to the generated security config secret. +3. Configures OpenSearch Dashboards to use these credentials. + +To use custom credentials, create a secret with keys `username` and `password` and supply it to the operator using the cluster `spec`: + +```yaml +spec: + dashboards: + opensearchCredentialsSecret: + name: dashboards-credentials # This is the name of your secret that contains the credentials for OpenSearch Dashboards to use +``` +{% include copy.html %} + +> Similarly to configuring the admin user, you do not need to include the password hash for the `kibanaserver` user in your security config secret. The operator automatically: +> 1. Reads the password from your `opensearchCredentialsSecret` (or uses the generated random password if not provided) +> 2. Generates the `bcrypt` hash +> 3. Overrides the `kibanaserver` user's hash in the generated security config secret +{: .important} diff --git a/_install-and-configure/install-opensearch/rpm.md b/_install-and-configure/install-opensearch/rpm.md index ac3ff4e0..7dacef87 100644 --- a/_install-and-configure/install-opensearch/rpm.md +++ b/_install-and-configure/install-opensearch/rpm.md @@ -4,7 +4,7 @@ title: RPM parent: Installing OpenSearch redirect_from: - /opensearch/install/rpm/ -nav_order: 51 +nav_order: 25 --- {% comment %} @@ -13,9 +13,9 @@ The following liquid syntax declares a variable, major_version_mask, which is tr {% assign version_parts = site.opensearch_major_minor_version | split: "." %} {% assign major_version_mask = version_parts[0] | append: ".x" %} -# RPM +# Installing OpenSearch using RPM -Installing OpenSearch using RPM Package Manager (RPM) simplifies the process considerably compared to the [Tarball]({{site.url}}{{site.baseurl}}/opensearch/install/tar/) method. Several technical considerations, such as the installation path, location of configuration files, and creation of a service managed by `systemd`, as examples, are handled automatically by the package manager. +Installing OpenSearch using RPM Package Manager (RPM) simplifies the process considerably compared to the [Tarball]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/tar/) method. Several technical considerations, such as the installation path, location of configuration files, and creation of a service managed by `systemd`, as examples, are handled automatically by the package manager. Generally speaking, installing OpenSearch from the RPM distribution can be broken down into a few steps: @@ -27,54 +27,88 @@ Generally speaking, installing OpenSearch from the RPM distribution can be broke 1. **Configure OpenSearch for your environment.** - Apply basic settings to OpenSearch and start using it in your environment. -The RPM distribution provides everything you need to run OpenSearch inside Red Hat or Red Hat–based Linux Distributions. For a list of supported operating systems, see [Operating system compatibility]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#operating-system-compatibility). +The RPM distribution provides everything you need to run OpenSearch inside Red Hat or Red Hat–based Linux Distributions. For a list of supported operating systems, see [Operating system compatibility]({{site.url}}{{site.baseurl}}/install-and-configure/os-comp/). This guide assumes that you are comfortable working from the Linux command line interface (CLI). You should understand how to input commands, navigate between directories, and edit text files. Some example commands reference the `vi` text editor, but you may use any text editor available. {:.note} ## Step 1: Download and install OpenSearch +You can install OpenSearch from a package or a YUM repository. + ### Install OpenSearch from a package 1. Download the RPM package for the desired version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. The RPM package can be downloaded for both **x64** and **arm64** architectures. 1. Import the public GNU Privacy Guard (GPG) key. This key verifies that your OpenSearch instance is signed. ```bash - sudo rpm --import https://artifacts.opensearch.org/publickeys/opensearch.pgp + sudo rpm --import https://artifacts.opensearch.org/publickeys/opensearch-release.pgp ``` {% include copy.html %} -1. For OpenSearch 2.12 and greater, a custom admin password is required in order to set up a security demo configuration. To set a custom admin password, use one the following commands: - - ```bash - # Install the x64 package using yum. - sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> yum install opensearch-{{site.opensearch_version}}-linux-x64.rpm - - # Install the x64 package using rpm. - sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> rpm -ivh opensearch-{{site.opensearch_version}}-linux-x64.rpm - - # Install the arm64 package using yum. - sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> yum install opensearch-{{site.opensearch_version}}-linux-x64.rpm - - # Install the arm64 package using rpm. - sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> rpm -ivh opensearch-{{site.opensearch_version}}-linux-x64.rpm - ``` - 1. From the CLI, you can install the package with `rpm` or `yum`. + For new installations of OpenSearch 3.7 and later, you can use the following installation-time environment variables to control the Security plugin behavior: + * `DISABLE_INSTALL_DEMO_CONFIG=true` -- Prevents the installer from setting up demo security configuration (certificates, users, and roles). Use this for installations where you will configure security manually. + * `DISABLE_SECURITY_PLUGIN=true` -- Disables the Security plugin entirely. Only use this for testing or development environments where security is not required. + + To use these environment variables, add them before the installation command with the `env` keyword: ```bash - # Install the x64 package using yum. - sudo yum install opensearch-{{site.opensearch_version}}-linux-x64.rpm - - # Install the x64 package using rpm. - sudo rpm -ivh opensearch-{{site.opensearch_version}}-linux-x64.rpm - - # Install the arm64 package using yum. - sudo yum install opensearch-{{site.opensearch_version}}-linux-x64.rpm - - # Install the arm64 package using rpm. - sudo rpm -ivh opensearch-{{site.opensearch_version}}-linux-x64.rpm + sudo env DISABLE_INSTALL_DEMO_CONFIG=true yum install opensearch-{{site.opensearch_version}}-linux-x64.rpm ``` + {% include copy.html %} + + For new installations of OpenSearch 2.12 and later, you must define a custom admin password in order to set up a demo security configuration. Use one of the following commands to define a custom admin password, following the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). OpenSearch uses this password only when it sets up the demo security configuration. To change the admin password later, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). + + Install the x64 package using yum: + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> yum install opensearch-{{site.opensearch_version}}-linux-x64.rpm + ``` + {% include copy.html %} + + Install the x64 package using rpm: + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> rpm -ivh opensearch-{{site.opensearch_version}}-linux-x64.rpm + ``` + {% include copy.html %} + + Install the arm64 package using yum: + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> yum install opensearch-{{site.opensearch_version}}-linux-arm64.rpm + ``` + {% include copy.html %} + + Install the arm64 package using rpm: + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> rpm -ivh opensearch-{{site.opensearch_version}}-linux-arm64.rpm + ``` + {% include copy.html %} + + Use the following commands for OpenSearch versions 2.11 and earlier. + + Install the x64 package using yum: + ```bash + sudo yum install opensearch-<version>-linux-x64.rpm + ``` + {% include copy.html %} + + Install the x64 package using rpm: + ```bash + sudo rpm -ivh opensearch-<version>-linux-x64.rpm + ``` + {% include copy.html %} + + Install the arm64 package using yum: + ```bash + sudo yum install opensearch-<version>-linux-arm64.rpm + ``` + {% include copy.html %} + + Install the arm64 package using rpm: + ```bash + sudo rpm -ivh opensearch-<version>-linux-arm64.rpm + ``` + {% include copy.html %} 1. After the installation succeeds, enable OpenSearch as a service. @@ -125,25 +159,42 @@ YUM, the primary package management tool for Red Hat–based operating systems, ``` {% include copy.html %} -1. Choose the version of OpenSearch you want to install: +1. Choose the version of OpenSearch you want to install: - Unless otherwise indicated, the latest available version of OpenSearch is installed. + + For OpenSearch versions 2.12 and later, a custom admin password is required in order to set up a demo security configuration for a new installation. To set a custom admin password, use the following command: + + ```bash + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> yum install opensearch + ``` + {% include copy.html %} + + For OpenSearch versions 2.11 and earlier, use the following command: + ```bash sudo yum install opensearch ``` {% include copy.html %} - - To install a specific version of OpenSearch: + - To install a specific version of OpenSearch, pass a version number after the package name. + + For OpenSearch versions 2.12 and later, a custom admin password is required in order to set up a demo security configuration for a new installation. To set a custom admin password, use the following command: ```bash - sudo yum install 'opensearch-{{site.opensearch_version}}' + sudo env OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> yum install 'opensearch-{{site.opensearch_version}}' ``` {% include copy.html %} -1. During installation, the installer will present you with the GPG key fingerprint. Verify that the information matches the following: + Use the following command for OpenSearch versions 2.11 and earlier: ```bash - Fingerprint: c5b7 4989 65ef d1c2 924b a9d5 39d3 1987 9310 d3fc + sudo yum install 'opensearch-2.11.0' ``` {% include copy.html %} +1. The first time YUM downloads the repository metadata (for example, when you list the available versions) and again during installation, YUM prompts you to import the GPG key and presents the key fingerprint. Verify that the information matches the following: + ```text + Fingerprint: A8B2 D9E0 4CD5 1FEF 6AA2 DB53 BA81 D999 8119 1457 + ``` + - If correct, enter `yes` or `y`. The OpenSearch installation continues. 1. Once complete, you can run OpenSearch. ```bash @@ -163,7 +214,7 @@ Before proceeding with any configuration, you should test your installation of O When OpenSearch is installed using the RPM package, some demo security settings are automatically applied. This includes self-signed TLS certificates and several users and roles. If you would like to configure these yourself, see [Set up OpenSearch in your environment](#step-3-set-up-opensearch-in-your-environment). -An OpenSearch node in its default configuration (with demo certificates and users with default passwords) is not suitable for a production environment. If you plan to use the node in a production environment, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security/configuration/yaml). See [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. +An OpenSearch node in its default configuration (with demo certificates and users with default passwords) is not suitable for a production environment. If you plan to use the node in a production environment, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security/configuration/yaml/). See [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. {: .warning} 1. Send requests to the server to verify that OpenSearch is running. Note the use of the `--insecure` flag, which is required because the TLS certificates are self-signed. @@ -206,17 +257,28 @@ An OpenSearch node in its default configuration (with demo certificates and user hostname opensearch-anomaly-detection {{site.opensearch_version}} hostname opensearch-asynchronous-search {{site.opensearch_version}} hostname opensearch-cross-cluster-replication {{site.opensearch_version}} + hostname opensearch-custom-codecs {{site.opensearch_version}} + hostname opensearch-flow-framework {{site.opensearch_version}} + hostname opensearch-geospatial {{site.opensearch_version}} hostname opensearch-index-management {{site.opensearch_version}} hostname opensearch-job-scheduler {{site.opensearch_version}} hostname opensearch-knn {{site.opensearch_version}} + hostname opensearch-ltr {{site.opensearch_version}} hostname opensearch-ml {{site.opensearch_version}} + hostname opensearch-neural-search {{site.opensearch_version}} hostname opensearch-notifications {{site.opensearch_version}} hostname opensearch-notifications-core {{site.opensearch_version}} hostname opensearch-observability {{site.opensearch_version}} hostname opensearch-performance-analyzer {{site.opensearch_version}} hostname opensearch-reports-scheduler {{site.opensearch_version}} + hostname opensearch-search-relevance {{site.opensearch_version}} hostname opensearch-security {{site.opensearch_version}} + hostname opensearch-security-analytics {{site.opensearch_version}} + hostname opensearch-skills {{site.opensearch_version}} hostname opensearch-sql {{site.opensearch_version}} + hostname opensearch-system-templates {{site.opensearch_version}} + hostname opensearch-ubi {{site.opensearch_version}} + hostname query-insights {{site.opensearch_version}} ``` ## Step 3: Set up OpenSearch in your environment @@ -243,20 +305,24 @@ Before modifying any configuration files, it's always a good idea to save a back ``` {% include copy.html %} -1. Add the following lines: - ```bash - # Bind OpenSearch to the correct network interface. Use 0.0.0.0 - # to include all available interfaces or specify an IP address - # assigned to a specific interface. +1. Add the following lines. + + Bind OpenSearch to the correct network interface. Use 0.0.0.0 to include all available interfaces or specify an IP address assigned to a specific interface: + ```yaml network.host: 0.0.0.0 + ``` + {% include copy.html %} - # Unless you have already configured a cluster, you should set - # discovery.type to single-node, or the bootstrap checks will - # fail when you try to start the service. + Unless you have already configured a cluster, you should set discovery.type to single-node, or the bootstrap checks will fail when you try to start the service: + ```yaml discovery.type: single-node + ``` + {% include copy.html %} - # If you previously disabled the Security plugin in opensearch.yml, - # be sure to re-enable it. Otherwise you can skip this setting. + If you configure a multi-node cluster instead, set `vm.max_map_count` to at least `262144` on the host. Otherwise, the bootstrap checks fail when the service starts. For more information, see [Important settings]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#important-settings). + + If you previously disabled the Security plugin in opensearch.yml, be sure to reenable it. Otherwise you can skip this setting: + ```yaml plugins.security.disabled: false ``` {% include copy.html %} @@ -265,7 +331,7 @@ Before modifying any configuration files, it's always a good idea to save a back 1. Specify initial and maximum JVM heap sizes. 1. Open `jvm.options`. ```bash - vi /etc/opensearch/jvm.options + sudo vi /etc/opensearch/jvm.options ``` {% include copy.html %} @@ -296,67 +362,90 @@ TLS certificates provide additional security for your cluster by allowing client {% include copy.html %} 1. Generate a root certificate. This is what you will use to sign your other certificates. + + Create a private key for the root certificate: ```bash - # Create a private key for the root certificate sudo openssl genrsa -out root-ca-key.pem 2048 - - # Use the private key to create a self-signed root certificate. Be sure to - # replace the arguments passed to -subj so they reflect your specific host. + ``` + {% include copy.html %} + + Use the private key to create a self-signed root certificate. Be sure to replace the arguments passed to -subj so they reflect your specific host: + ```bash sudo openssl req -new -x509 -sha256 -key root-ca-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=ROOT" -out root-ca.pem -days 730 ``` + {% include copy.html %} 1. Next, create the admin certificate. This certificate is used to gain elevated rights for performing administrative tasks relating to the Security plugin. - ```bash - # Create a private key for the admin certificate. - sudo openssl genrsa -out admin-key-temp.pem 2048 - # Convert the private key to PKCS#8. + Create a private key for the admin certificate: + ```bash + sudo openssl genrsa -out admin-key-temp.pem 2048 + ``` + {% include copy.html %} + + Convert the private key to PKCS#8: + ```bash sudo openssl pkcs8 -inform PEM -outform PEM -in admin-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out admin-key.pem - - # Create the certficiate signing request (CSR). A common name (CN) of "A" is acceptable because this certificate is - # used for authenticating elevated access and is not tied to a host. + ``` + {% include copy.html %} + + Create the certificate signing request (CSR). A common name (CN) of "A" is acceptable because this certificate is used for authenticating elevated access and is not tied to a host: + ```bash sudo openssl req -new -key admin-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=A" -out admin.csr - - # Sign the admin certificate with the root certificate and private key you created earlier. + ``` + {% include copy.html %} + + Sign the admin certificate with the root certificate and private key you created earlier: + ```bash sudo openssl x509 -req -in admin.csr -CA root-ca.pem -CAkey root-ca-key.pem -CAcreateserial -sha256 -out admin.pem -days 730 ``` + {% include copy.html %} 1. Create a certificate for the node being configured. - ```bash - # Create a private key for the node certificate. - sudo openssl genrsa -out node1-key-temp.pem 2048 - - # Convert the private key to PKCS#8. - sudo openssl pkcs8 -inform PEM -outform PEM -in node1-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out node1-key.pem - - # Create the CSR and replace the arguments passed to -subj so they reflect your specific host. - # The CN should match a DNS A record for the host-do not use the hostname. - sudo openssl req -new -key node1-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=node1.dns.a-record" -out node1.csr - - # Create an extension file that defines a SAN DNS name for the host. This - # should match the DNS A record of the host. - sudo sh -c 'echo subjectAltName=DNS:node1.dns.a-record > node1.ext' - # Sign the node certificate with the root certificate and private key that you created earlier. + Create a private key for the node certificate: + ```bash + sudo openssl genrsa -out node1-key-temp.pem 2048 + ``` + {% include copy.html %} + + Convert the private key to PKCS#8: + ```bash + sudo openssl pkcs8 -inform PEM -outform PEM -in node1-key-temp.pem -topk8 -nocrypt -v1 PBE-SHA1-3DES -out node1-key.pem + ``` + {% include copy.html %} + + Create the CSR and replace the arguments passed to -subj so they reflect your specific host. The CN should match a DNS A record for the host-do not use the hostname: + ```bash + sudo openssl req -new -key node1-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=node1.dns.a-record" -out node1.csr + ``` + {% include copy.html %} + + Create an extension file that defines a SAN DNS name for the host. This should match the DNS A record of the host: + ```bash + sudo sh -c 'echo subjectAltName=DNS:node1.dns.a-record > node1.ext' + ``` + {% include copy.html %} + + Sign the node certificate with the root certificate and private key that you created earlier: + ```bash sudo openssl x509 -req -in node1.csr -CA root-ca.pem -CAkey root-ca-key.pem -CAcreateserial -sha256 -out node1.pem -days 730 -extfile node1.ext ``` + {% include copy.html %} 1. Remove temporary files that are no longer required. ```bash sudo rm -f *temp.pem *csr *ext ``` {% include copy.html %} -1. Make sure the remaining certificates are owned by the opensearch user. +1. Make sure the remaining certificates are owned by the `opensearch` user. ```bash sudo chown opensearch:opensearch admin-key.pem admin.pem node1-key.pem node1.pem root-ca-key.pem root-ca.pem root-ca.srl ``` {% include copy.html %} -1. Add these certificates to `opensearch.yml` as described in [Generate Certificates]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/#add-distinguished-names-to-opensearchyml). Advanced users might also choose to append the settings using a script: +1. Add these certificates to `opensearch.yml` as described in [Generate Certificates]({{site.url}}{{site.baseurl}}/security/configuration/generate-certificates/#add-distinguished-names-to-opensearchyml). Advanced users might also choose to append the settings using a script. Before running this script, make sure to replace the CN in the node's distinguished name with a real DNS A record: ```bash #! /bin/bash - # Before running this script, make sure to replace the CN in the - # node's distinguished name with a real DNS A record. - echo "plugins.security.ssl.transport.pemcert_filepath: /etc/opensearch/node1.pem" | sudo tee -a /etc/opensearch/opensearch.yml echo "plugins.security.ssl.transport.pemkey_filepath: /etc/opensearch/node1-key.pem" | sudo tee -a /etc/opensearch/opensearch.yml echo "plugins.security.ssl.transport.pemtrustedcas_filepath: /etc/opensearch/root-ca.pem" | sudo tee -a /etc/opensearch/opensearch.yml @@ -377,13 +466,18 @@ TLS certificates provide additional security for your cluster by allowing client {% include copy.html %} 1. (Optional) Add trust for the self-signed root certificate. - ```bash - # Copy the root certificate to the correct directory - sudo cp /etc/opensearch/root-ca.pem /etc/pki/ca-trust/source/anchors/ - # Add trust + Copy the root certificate to the correct directory: + ```bash + sudo cp /etc/opensearch/root-ca.pem /etc/pki/ca-trust/source/anchors/ + ``` + {% include copy.html %} + + Add trust: + ```bash sudo update-ca-trust ``` + {% include copy.html %} ### Configure a user @@ -397,17 +491,20 @@ Users are defined and authenticated by OpenSearch in a variety of ways. One meth 1. Run `hash.sh` to generate a new password. - This script will fail if a path to the JDK has not been defined. + + Example output if a JDK isn't found: ```bash - # Example output if a JDK isn't found... $ ./hash.sh ************************************************************************** ** This tool will be deprecated in the next major release of OpenSearch ** ** https://github.com/opensearch-project/security/issues/1755 ** ************************************************************************** which: no java in (/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/user/.local/bin:/home/user/bin) - WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use + WARNING: nor OPENSEARCH_JAVA_HOME nor JAVA_HOME is set, will use ./hash.sh: line 35: java: command not found ``` + {% include copy.html %} + - Declare an environment variable when you invoke the script in order to avoid issues: ```bash OPENSEARCH_JAVA_HOME=/usr/share/opensearch/jdk ./hash.sh @@ -446,22 +543,23 @@ Users are defined and authenticated by OpenSearch in a variety of ways. One meth Now that TLS certificates are installed and demo users were removed or assigned new passwords, the last step is to apply the configuration changes. This last configuration step requires invoking `securityadmin.sh` while OpenSearch is running on the host. -1. OpenSearch must be running for `securityadmin.sh` to apply changes. If you made changes to `opensearch.yml`, restart OpenSearch. +1. OpenSearch must be running for `securityadmin.sh` to apply changes. If you made changes to `opensearch.yml`, restart OpenSearch: ```bash sudo systemctl restart opensearch ``` + {% include copy.html %} -1. Open a separate terminal session with the host and navigate to the directory containing `securityadmin.sh`. +1. Open a separate terminal session with the host and navigate to the directory containing `securityadmin.sh`: ```bash - # Change to the correct directory cd /usr/share/opensearch/plugins/opensearch-security/tools ``` + {% include copy.html %} -1. Invoke the script. See [Apply changes using securityadmin.sh]({{site.url}}{{site.baseurl}}/security/configuration/security-admin/) for definitions of the arguments you must pass. +1. Invoke the script. See [Apply changes using securityadmin.sh]({{site.url}}{{site.baseurl}}/security/configuration/security-admin/) for definitions of the arguments you must pass. You can omit the environment variable if you declared this in your $PATH: ```bash - # You can omit the environment variable if you declared this in your $PATH. OPENSEARCH_JAVA_HOME=/usr/share/opensearch/jdk ./securityadmin.sh -cd /etc/opensearch/opensearch-security/ -cacert /etc/opensearch/root-ca.pem -cert /etc/opensearch/admin.pem -key /etc/opensearch/admin-key.pem -icl -nhnv ``` + {% include copy.html %} ### Verify that the service is running @@ -473,7 +571,13 @@ You should add trust for the root certificate to your client before sending requ {:.tip} ```bash -$ curl https://your.host.address:9200 -u admin:yournewpassword -k +curl https://your.host.address:9200 -u admin:yournewpassword -k +``` +{% include copy.html %} + +You should receive the following response: + +```json { "name" : "hostname-here", "cluster_name" : "opensearch", @@ -498,21 +602,21 @@ $ curl https://your.host.address:9200 -u admin:yournewpassword -k OpenSearch instances installed using RPM or YUM can be easily upgraded to a newer version. We recommend updating with YUM, but you can also upgrade using RPM. -### Manual upgrade with RPM +### Upgrade manually using RPM -Download the RPM package for the desired upgrade version directly from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. +Download the RPM package for the desired upgrade version directly from the [OpenSearch Project downloads page](https://opensearch.org/downloads.html){:target='\_blank'}. Navigate to the directory containing the distribution and run the following command: ```bash -rpm -Uvh opensearch-{{site.opensearch_version}}-linux-x64.rpm +sudo rpm -Uvh opensearch-{{site.opensearch_version}}-linux-x64.rpm ``` {% include copy.html %} -### YUM +### Upgrade using YUM To upgrade to the latest version of OpenSearch using YUM: ```bash -sudo yum update +sudo yum update opensearch ``` {% include copy.html %} @@ -522,9 +626,20 @@ sudo yum update ``` {% include copy.html %} -## Related links +### Automatically restart the service after a package upgrade +The OpenSearch RPM package does not support automatically restarting the service after a package upgrade. The upgrade stops OpenSearch, so start the service after the upgrade completes: + +```bash +sudo systemctl start opensearch +``` +{% include copy.html %} + +## Related documentation + +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) +- [Common installation issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#common-issues) - [OpenSearch configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) - [Install and configure OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) -- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/opensearch/install/plugins/) +- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) - [About the Security plugin]({{site.url}}{{site.baseurl}}/security/index/) diff --git a/_install-and-configure/install-opensearch/tar.md b/_install-and-configure/install-opensearch/tar.md index 1e5fe47a..939f97a9 100644 --- a/_install-and-configure/install-opensearch/tar.md +++ b/_install-and-configure/install-opensearch/tar.md @@ -2,12 +2,12 @@ layout: default title: Tarball parent: Installing OpenSearch -nav_order: 10 +nav_order: 30 redirect_from: - /opensearch/install/tar/ --- -# Tarball +# Installing OpenSearch from a tarball Installing OpenSearch from a tarball, also known as a tar archive, may appeal to users who want granular control over installation details like file permissions and installation paths. @@ -22,33 +22,48 @@ Generally speaking, the installation of OpenSearch from a tarball can be broken 1. **Configure OpenSearch for your environment.** - Apply basic settings to OpenSearch and start using it in your environment. -The tarball is a self-contained directory with everything needed to run OpenSearch, including an integrated Java Development Kit (JDK). This installation method is compatible with most Linux distributions, including CentOS 7, Amazon Linux 2, and Ubuntu 18.04. If you have your own Java installation and set the environment variable `JAVA_HOME` in the terminal, macOS works as well. +The tarball is a self-contained directory with everything needed to run OpenSearch, including an integrated Java Development Kit (JDK). This installation method is compatible with most Linux distributions. For the operating systems that OpenSearch is tested on, see [Compatible operating systems]({{site.url}}{{site.baseurl}}/install-and-configure/os-comp/). If you have your own Java installation and set the environment variable `JAVA_HOME` in the terminal, macOS works as well. This guide assumes that you are comfortable working from the Linux command line interface (CLI). You should understand how to input commands, navigate between directories, and edit text files. Some example commands reference the `vi` text editor, but you may use any text editor available. {:.note} ## Step 1: Download and unpack OpenSearch -1. Download the appropriate tar.gz archive from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'} or by using the command line (such as with `wget`). +1. Download the appropriate tar.gz archive from the [OpenSearch downloads page](https://opensearch.org/downloads.html){:target='\_blank'} or by using the command line, for example, using `curl`. + + For an x64 host, use the following command: + ```bash - # x64 - wget https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-linux-x64.tar.gz + curl -fsSLO https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-linux-x64.tar.gz + ``` + {% include copy.html %} + + For an ARM64 host, use the following command: + + ```bash + curl -fsSLO https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-linux-arm64.tar.gz + ``` + {% include copy.html %} + +1. Extract the contents of the tarball. + + For an x64 host, use the following command: - # ARM64 - wget https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-linux-arm64.tar.gz - ``` -1. Extract the contents of the tarball. ```bash - # x64 tar -xvf opensearch-{{site.opensearch_version}}-linux-x64.tar.gz - - # ARM64 + ``` + {% include copy.html %} + + For an ARM64 host, use the following command: + + ```bash tar -xvf opensearch-{{site.opensearch_version}}-linux-arm64.tar.gz ``` + {% include copy.html %} ## Step 2: Configure important system settings -Before launching OpenSearch you should review some [important system settings]({{site.url}}{{site.baseurl}}/opensearch/install/important-settings/){:target='\_blank'}. +Before launching OpenSearch you should review some [important system settings]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#important-settings){:target='\_blank'}. 1. Disable memory paging and swapping performance on the host to improve performance. ```bash sudo swapoff -a @@ -71,6 +86,7 @@ Before launching OpenSearch you should review some [important system settings]({ # Verify that the change was applied by checking the value cat /proc/sys/vm/max_map_count ``` + {% include copy.html %} ## Step 3: (Optional) Test OpenSearch @@ -83,7 +99,7 @@ The demo security script will apply a generic configuration to your instance of If you only want to verify that the service is properly configured and you intend to configure security settings yourself, then you may want to disable the Security plugin and launch the service without encryption or authentication. -An OpenSearch node configured by the demo security script is not suitable for a production environment. If you plan to use the node in a production environment after running `opensearch-tar-install.sh`, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security/configuration/yaml). See [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. +An OpenSearch node configured by the demo security script is not suitable for a production environment. If you plan to use the node in a production environment after running `opensearch-tar-install.sh`, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security/configuration/yaml/). See [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. {: .warning} ### Option 1: Test your OpenSearch settings with security enabled @@ -94,15 +110,15 @@ An OpenSearch node configured by the demo security script is not suitable for a ``` {% include copy.html %} -1. Run the OpenSearch startup script with the security demo configuration. +1. For OpenSearch 2.12 or later, set a custom admin password, following the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). If you do not set a password, the startup script exits without starting OpenSearch. OpenSearch uses this password only when it sets up the demo security configuration. To change the admin password later, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). To set the password, run the following command: ```bash - ./opensearch-tar-install.sh + export OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> ``` {% include copy.html %} - For OpenSearch 2.12 or greater, set a new custom admin password before installation using the following command: +1. Run the OpenSearch startup script with the security demo configuration. ```bash - $ export OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> + ./opensearch-tar-install.sh ``` {% include copy.html %} @@ -146,17 +162,28 @@ An OpenSearch node configured by the demo security script is not suitable for a hostname opensearch-anomaly-detection {{site.opensearch_version}} hostname opensearch-asynchronous-search {{site.opensearch_version}} hostname opensearch-cross-cluster-replication {{site.opensearch_version}} + hostname opensearch-custom-codecs {{site.opensearch_version}} + hostname opensearch-flow-framework {{site.opensearch_version}} + hostname opensearch-geospatial {{site.opensearch_version}} hostname opensearch-index-management {{site.opensearch_version}} hostname opensearch-job-scheduler {{site.opensearch_version}} hostname opensearch-knn {{site.opensearch_version}} + hostname opensearch-ltr {{site.opensearch_version}} hostname opensearch-ml {{site.opensearch_version}} + hostname opensearch-neural-search {{site.opensearch_version}} hostname opensearch-notifications {{site.opensearch_version}} hostname opensearch-notifications-core {{site.opensearch_version}} hostname opensearch-observability {{site.opensearch_version}} hostname opensearch-performance-analyzer {{site.opensearch_version}} hostname opensearch-reports-scheduler {{site.opensearch_version}} + hostname opensearch-search-relevance {{site.opensearch_version}} hostname opensearch-security {{site.opensearch_version}} + hostname opensearch-security-analytics {{site.opensearch_version}} + hostname opensearch-skills {{site.opensearch_version}} hostname opensearch-sql {{site.opensearch_version}} + hostname opensearch-system-templates {{site.opensearch_version}} + hostname opensearch-ubi {{site.opensearch_version}} + hostname query-insights {{site.opensearch_version}} ``` 1. Return to the original terminal session and stop the process by pressing `CTRL + C`. @@ -169,12 +196,19 @@ An OpenSearch node configured by the demo security script is not suitable for a {% include copy.html %} 1. Add the following line to disable the Security plugin: - ```bash + ```yaml plugins.security.disabled: true ``` {% include copy.html %} 1. Save the change and close the file. +1. Change to the top directory of your OpenSearch installation and start OpenSearch: + ```bash + cd /path/to/opensearch-{{site.opensearch_version}} + ./bin/opensearch + ``` + {% include copy.html %} + 1. Open another terminal session and send requests to the server to verify that OpenSearch is running. Because the Security plugin has been disabled, you will be sending commands using `HTTP` rather than `HTTPS`. - Send a request to port 9200. ```bash @@ -215,17 +249,28 @@ An OpenSearch node configured by the demo security script is not suitable for a hostname opensearch-anomaly-detection {{site.opensearch_version}} hostname opensearch-asynchronous-search {{site.opensearch_version}} hostname opensearch-cross-cluster-replication {{site.opensearch_version}} + hostname opensearch-custom-codecs {{site.opensearch_version}} + hostname opensearch-flow-framework {{site.opensearch_version}} + hostname opensearch-geospatial {{site.opensearch_version}} hostname opensearch-index-management {{site.opensearch_version}} hostname opensearch-job-scheduler {{site.opensearch_version}} hostname opensearch-knn {{site.opensearch_version}} + hostname opensearch-ltr {{site.opensearch_version}} hostname opensearch-ml {{site.opensearch_version}} + hostname opensearch-neural-search {{site.opensearch_version}} hostname opensearch-notifications {{site.opensearch_version}} hostname opensearch-notifications-core {{site.opensearch_version}} hostname opensearch-observability {{site.opensearch_version}} hostname opensearch-performance-analyzer {{site.opensearch_version}} hostname opensearch-reports-scheduler {{site.opensearch_version}} + hostname opensearch-search-relevance {{site.opensearch_version}} hostname opensearch-security {{site.opensearch_version}} + hostname opensearch-security-analytics {{site.opensearch_version}} + hostname opensearch-skills {{site.opensearch_version}} hostname opensearch-sql {{site.opensearch_version}} + hostname opensearch-system-templates {{site.opensearch_version}} + hostname opensearch-ubi {{site.opensearch_version}} + hostname query-insights {{site.opensearch_version}} ``` ## Step 4: Set up OpenSearch in your environment @@ -240,7 +285,7 @@ The following recommended settings will allow you to: - Configure your own TLS certificates - no third-party certificate authority (CA) is required. - Create an admin user with a custom password. -If you ran the security demo script, then you will need to manually reconfigure settings that were modified. Refer to [Security configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) for guidance before proceeding. +OpenSearch fails to start with a `Duplicate Object property` error if `opensearch.yml` contains the same setting more than once. If you tested OpenSearch using Option 1 or Option 2, either start from a freshly extracted tarball or remove the settings that the following steps add from `opensearch.yml`, including `plugins.security.disabled` and the `plugins.security` settings added by the security demo script. Refer to [Security configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) for guidance before proceeding. {:.note} Before modifying any configuration files, it's always a good idea to save a backup copy before making changes. The backup file can be used to revert any issues caused by a bad configuration. @@ -253,7 +298,7 @@ Before modifying any configuration files, it's always a good idea to save a back {% include copy.html %} 1. Add the following lines. - ```bash + ```yaml # Bind OpenSearch to the correct network interface. Use 0.0.0.0 # to include all available interfaces or specify an IP address # assigned to a specific interface. @@ -312,6 +357,7 @@ TLS certificates provide additional security for your cluster by allowing client # replace the arguments passed to -subj so they reflect your specific host. openssl req -new -x509 -sha256 -key root-ca-key.pem -subj "/C=CA/ST=ONTARIO/L=TORONTO/O=ORG/OU=UNIT/CN=ROOT" -out root-ca.pem -days 730 ``` + {% include copy.html %} 1. Next, create the admin certificate. This certificate is used to gain elevated rights for performing administrative tasks relating to the Security plugin. ```bash # Create a private key for the admin certificate. @@ -327,6 +373,7 @@ TLS certificates provide additional security for your cluster by allowing client # Sign the admin certificate with the root certificate and private key you created earlier. openssl x509 -req -in admin.csr -CA root-ca.pem -CAkey root-ca-key.pem -CAcreateserial -sha256 -out admin.pem -days 730 ``` + {% include copy.html %} 1. Create a certificate for the node being configured. ```bash # Create a private key for the node certificate. @@ -346,6 +393,7 @@ TLS certificates provide additional security for your cluster by allowing client # Sign the node certificate with the root certificate and private key that you created earlier. openssl x509 -req -in node1.csr -CA root-ca.pem -CAkey root-ca-key.pem -CAcreateserial -sha256 -out node1.pem -days 730 -extfile node1.ext ``` + {% include copy.html %} 1. Remove temporary files that are no longer required. ```bash rm *temp.pem *csr *ext @@ -387,6 +435,7 @@ TLS certificates provide additional security for your cluster by allowing client # Add trust sudo update-ca-trust ``` + {% include copy.html %} ### Configure a user @@ -459,53 +508,62 @@ Now that TLS certificates are installed and demo users were removed or assigned # Run the service in the foreground ./opensearch ``` + {% include copy.html %} 1. Open a separate terminal session with the host and navigate to the directory containing `securityadmin.sh`. ```bash # Change to the correct directory cd /path/to/opensearch-{{site.opensearch_version}}/plugins/opensearch-security/tools ``` + {% include copy.html %} 1. Invoke the script. See [Apply changes using securityadmin.sh]({{site.url}}{{site.baseurl}}/security/configuration/security-admin/) for definitions of the arguments you must pass. ```bash # You can omit the environment variable if you declared this in your $PATH. OPENSEARCH_JAVA_HOME=/path/to/opensearch-{{site.opensearch_version}}/jdk ./securityadmin.sh -cd /path/to/opensearch-{{site.opensearch_version}}/config/opensearch-security/ -cacert /path/to/opensearch-{{site.opensearch_version}}/config/root-ca.pem -cert /path/to/opensearch-{{site.opensearch_version}}/config/admin.pem -key /path/to/opensearch-{{site.opensearch_version}}/config/admin-key.pem -icl -nhnv ``` + {% include copy.html %} 1. Stop and restart the running OpenSearch process to apply the changes. ### Verify that the service is running OpenSearch is now running on your host with custom TLS certificates and a secure user for basic authentication. You can verify external connectivity by sending an API request to your OpenSearch node from another host. -During previous tests you directed requests to `localhost`. Now that TLS certificates have been applied and the new certificates reference your host's actual DNS record, requests to `localhost` will fail the CN check and the certificate will be considered invalid. Instead, requests should be sent to the address you specified while generating the certificate. +During previous tests you directed requests to `localhost`. Now that TLS certificates have been applied and the new certificates reference your host's actual DNS record, requests to `localhost` will fail the common name (CN) check and the certificate will be considered invalid. Instead, requests should be sent to the address you specified while generating the certificate. You should add trust for the root certificate to your client before sending requests. If you do not add trust, then you must use the `-k` option so that cURL ignores CN and root certificate validation. {:.tip} ```bash -$ curl https://your.host.address:9200 -u admin:yournewpassword -k +curl https://your.host.address:9200 -u admin:yournewpassword -k +``` +{% include copy.html %} + +You should receive the following response: + +```json { "name" : "hostname-here", "cluster_name" : "opensearch", "cluster_uuid" : "efC0ANNMQlGQ5TbhNflVPg", "version" : { "distribution" : "opensearch", - "number" : "2.1.0", + "number" : "{{site.opensearch_version}}", "build_type" : "tar", - "build_hash" : "388c80ad94529b1d9aad0a735c4740dce2932a32", - "build_date" : "2022-06-30T21:31:04.823801692Z", + "build_hash" : <build-hash>, + "build_date" : <build-date>, "build_snapshot" : false, - "lucene_version" : "9.2.0", - "minimum_wire_compatibility_version" : "7.10.0", - "minimum_index_compatibility_version" : "7.0.0" + "lucene_version" : <lucene-version>, + "minimum_wire_compatibility_version" : "2.19.0", + "minimum_index_compatibility_version" : "2.0.0" }, "tagline" : "The OpenSearch Project: https://opensearch.org/" } ``` -### Run OpenSearch as a service with systemd +### Run OpenSearch as a service using `systemd` This section will guide you through creating a service for OpenSearch and registering it with `systemd`. After the service has been defined, you can enable, start, and stop the OpenSearch service using `systemctl` commands. The commands in this section reflect an environment where OpenSearch has been installed to `/opt/opensearch` and should be changed depending on your installation path. -The following configuration is only suitable for testing in a non-production environment. We do not recommend using the following configuration in a production environment. You should install OpenSearch with the [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm) distribution if you want to run OpenSearch as a systemd-managed service on your host. The tarball installation does not define a specific installation path, users, roles, or permissions. Failure to properly secure your host environment can result in unexpected behavior. +The following configuration is only suitable for testing in a non-production environment. We do not recommend using the following configuration in a production environment. You should install OpenSearch with the [RPM]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/rpm/) distribution if you want to run OpenSearch as a systemd-managed service on your host. The tarball installation does not define a specific installation path, users, roles, or permissions. Failure to properly secure your host environment can result in unexpected behavior. {: .warning} 1. Create a user for the OpenSearch service. @@ -590,10 +648,12 @@ The following configuration is only suitable for testing in a non-production env ``` {% include copy.html %} -## Related links +## Related documentation +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) +- [Common installation issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#common-issues) - [OpenSearch configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) -- [Configure Performance Analyzer for Tarball Installation]({{site.url}}{{site.baseurl}}/monitoring-plugins/pa/index/#install-performance-analyzer) +- [Performance Analyzer]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/performance-analyzer/) - [Install and configure OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/index/) -- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/opensearch/install/plugins/) +- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) - [About the Security plugin]({{site.url}}{{site.baseurl}}/security/index/) \ No newline at end of file diff --git a/_install-and-configure/install-opensearch/windows.md b/_install-and-configure/install-opensearch/windows.md index 14595a0e..53e51d37 100644 --- a/_install-and-configure/install-opensearch/windows.md +++ b/_install-and-configure/install-opensearch/windows.md @@ -2,10 +2,10 @@ layout: default title: Windows parent: Installing OpenSearch -nav_order: 65 +nav_order: 40 --- -# Windows +# Installing OpenSearch on Windows The following sections describe installing OpenSearch on Windows from a zip archive. @@ -29,7 +29,15 @@ Make sure you have a zip utility installed. Perform the following steps to install OpenSearch on Windows. 1. Download the [`opensearch-{{site.opensearch_version}}-windows-x64.zip`](https://artifacts.opensearch.org/releases/bundle/opensearch/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}-windows-x64.zip){:target='\_blank'} archive. -1. To extract the archive contents, right-click to select **Extract All**. +1. To extract the archive contents, right-click to select **Extract All**. Alternatively, extract the archive from Command Prompt or PowerShell using the `tar` command included with Windows, which is faster for large archives: + + ```bat + tar -xf opensearch-{{site.opensearch_version}}-windows-x64.zip + ``` + {% include copy.html %} + +Ensure there are no spaces in the extraction path, as this will prevent OpenSearch from starting. +{: .warning} ## Step 2: (Optional) Test OpenSearch @@ -42,7 +50,7 @@ The batch script will apply a generic configuration to your instance of OpenSear If you only want to verify that the service is properly configured and you intend to configure security settings yourself, then you may want to disable the Security plugin and launch the service without encryption or authentication. -An OpenSearch node in its default configuration (with demo certificates and users with default passwords) is not suitable for a production environment. If you plan to use the node in a production environment, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security/configuration/yaml). See [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. +An OpenSearch node in its default configuration (with demo certificates and users with default passwords) is not suitable for a production environment. If you plan to use the node in a production environment, you should, at a minimum, replace the demo TLS certificates with your own TLS certificates and [update the list of internal users and passwords]({{site.url}}{{site.baseurl}}/security/configuration/yaml/). See [Security configuration]({{site.url}}{{site.baseurl}}/security/configuration/index/) for additional guidance to ensure that your nodes are configured according to your security requirements. {: .warning} ### Option 1: Test your OpenSearch settings with security enabled @@ -57,11 +65,24 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} 1. Run the batch script. - For OpenSearch 2.12 or later, use the following command to specify a custom admin password: + For OpenSearch 2.12 or later, specify a custom admin password, following the [admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). If you do not set a password, the batch script exits without starting OpenSearch. OpenSearch uses this password only when it sets up the demo security configuration. To change the admin password later, see [Changing the admin password]({{site.url}}{{site.baseurl}}/security/configuration/passwords/#changing-the-admin-password). + + In Command Prompt, use the following command: ```bat - > set OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> + set OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> ``` {% include copy.html %} + + In PowerShell, use the following command: + ```powershell + $env:OPENSEARCH_INITIAL_ADMIN_PASSWORD="<custom-admin-password>" + ``` + {% include copy.html %} + + The Command Prompt `set` command does not set an environment variable in PowerShell, so make sure to use the command for your shell. + {: .note} + + Then run the batch script: ```bat .\opensearch-windows-install.bat ``` @@ -75,7 +96,7 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} You should get a response that looks like this: - ```bat + ```json { "name" : "hostname-here", "cluster_name" : "opensearch", @@ -101,24 +122,33 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} The response should look like this: - ```bat + ```text + name component version hostname opensearch-alerting {{site.opensearch_version}} hostname opensearch-anomaly-detection {{site.opensearch_version}} hostname opensearch-asynchronous-search {{site.opensearch_version}} hostname opensearch-cross-cluster-replication {{site.opensearch_version}} + hostname opensearch-custom-codecs {{site.opensearch_version}} + hostname opensearch-flow-framework {{site.opensearch_version}} hostname opensearch-geospatial {{site.opensearch_version}} hostname opensearch-index-management {{site.opensearch_version}} hostname opensearch-job-scheduler {{site.opensearch_version}} hostname opensearch-knn {{site.opensearch_version}} + hostname opensearch-ltr {{site.opensearch_version}} hostname opensearch-ml {{site.opensearch_version}} hostname opensearch-neural-search {{site.opensearch_version}} hostname opensearch-notifications {{site.opensearch_version}} hostname opensearch-notifications-core {{site.opensearch_version}} hostname opensearch-observability {{site.opensearch_version}} hostname opensearch-reports-scheduler {{site.opensearch_version}} + hostname opensearch-search-relevance {{site.opensearch_version}} hostname opensearch-security {{site.opensearch_version}} hostname opensearch-security-analytics {{site.opensearch_version}} + hostname opensearch-skills {{site.opensearch_version}} hostname opensearch-sql {{site.opensearch_version}} + hostname opensearch-system-templates {{site.opensearch_version}} + hostname opensearch-ubi {{site.opensearch_version}} + hostname query-insights {{site.opensearch_version}} ``` ### Option 2: Test your OpenSearch settings with security disabled @@ -142,21 +172,21 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} You should get a response that looks like this: - ```bat + ```json { "name" : "hostname-here", "cluster_name" : "opensearch", "cluster_uuid" : "7Nqtr0LrQTOveFcBb7Kufw", "version" : { "distribution" : "opensearch", - "number" : "2.4.0", + "number" : "{{site.opensearch_version}}", "build_type" : "zip", - "build_hash" : "77ef9e304dd6ee95a600720a387a9735bbcf7bc9", - "build_date" : "2022-11-05T05:50:15.404072800Z", + "build_hash" : <build-hash>, + "build_date" : <build-date>, "build_snapshot" : false, - "lucene_version" : "9.4.1", - "minimum_wire_compatibility_version" : "7.10.0", - "minimum_index_compatibility_version" : "7.0.0" + "lucene_version" : <lucene-version>, + "minimum_wire_compatibility_version" : "2.19.0", + "minimum_index_compatibility_version" : "2.0.0" }, "tagline" : "The OpenSearch Project: https://opensearch.org/" } @@ -168,24 +198,33 @@ An OpenSearch node in its default configuration (with demo certificates and user {% include copy.html %} The response should look like this: - ```bat + ```text + name component version hostname opensearch-alerting {{site.opensearch_version}} hostname opensearch-anomaly-detection {{site.opensearch_version}} hostname opensearch-asynchronous-search {{site.opensearch_version}} hostname opensearch-cross-cluster-replication {{site.opensearch_version}} + hostname opensearch-custom-codecs {{site.opensearch_version}} + hostname opensearch-flow-framework {{site.opensearch_version}} hostname opensearch-geospatial {{site.opensearch_version}} hostname opensearch-index-management {{site.opensearch_version}} hostname opensearch-job-scheduler {{site.opensearch_version}} hostname opensearch-knn {{site.opensearch_version}} + hostname opensearch-ltr {{site.opensearch_version}} hostname opensearch-ml {{site.opensearch_version}} hostname opensearch-neural-search {{site.opensearch_version}} hostname opensearch-notifications {{site.opensearch_version}} hostname opensearch-notifications-core {{site.opensearch_version}} hostname opensearch-observability {{site.opensearch_version}} hostname opensearch-reports-scheduler {{site.opensearch_version}} + hostname opensearch-search-relevance {{site.opensearch_version}} hostname opensearch-security {{site.opensearch_version}} hostname opensearch-security-analytics {{site.opensearch_version}} + hostname opensearch-skills {{site.opensearch_version}} hostname opensearch-sql {{site.opensearch_version}} + hostname opensearch-system-templates {{site.opensearch_version}} + hostname opensearch-ubi {{site.opensearch_version}} + hostname query-insights {{site.opensearch_version}} ``` To stop OpenSearch, press `Ctrl+C` in Command Prompt or Powershell, or simply close the Command Prompt or Powershell window. @@ -201,7 +240,7 @@ The following recommended settings will allow you to: - Set initial and maximum JVM heap sizes. - Define an environment variable that points to the bundled JDK. -If you ran the security demo script, then you will need to manually reconfigure settings that were modified. Refer to [Security configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) for guidance before proceeding. +The following steps assume that you ran the security demo script in [Option 1](#option-1-test-your-opensearch-settings-with-security-enabled), which configures the TLS certificates that the Security plugin requires. If you start OpenSearch with the Security plugin enabled and no TLS configuration, OpenSearch fails to start. If you tested OpenSearch using [Option 2](#option-2-test-your-opensearch-settings-with-security-disabled), remove the `plugins.security.disabled: true` line from `opensearch.yml` instead of adding `plugins.security.disabled: false`. OpenSearch fails to start with a `Duplicate Object property` error if `opensearch.yml` contains the same setting more than once. Refer to [Security configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) for guidance before proceeding. {:.note} Before modifying any configuration files, it's always a good idea to save a backup copy before making changes. The backup file can be used to revert any issues caused by a bad configuration. @@ -210,7 +249,7 @@ Before modifying any configuration files, it's always a good idea to save a back 1. Open the `opensearch-{{site.opensearch_version}}\config` folder. 1. Open the `opensearch.yml` file with a text editor. 1. Add the following lines: - ```bash + ```yaml # Bind OpenSearch to the correct network interface. Use 0.0.0.0 # to include all available interfaces or specify an IP address # assigned to a specific interface. @@ -249,12 +288,16 @@ Before modifying any configuration files, it's always a good idea to save a back 1. In **Variable value**, enter `\path\to\opensearch-{{site.opensearch_version}}\jdk`. 1. Select **OK** to close all dialogs. +1. Start or restart OpenSearch using `\path\to\opensearch-{{site.opensearch_version}}\bin\opensearch.bat`. + ## Plugin compatibility -The Performance Analyzer plugin is not available on Windows. All other OpenSearch plugins, including the k-NN plugin, are available. For a complete list of plugins, see [Available plugins]({{site.url}}{{site.baseurl}}/opensearch/install/plugins/#available-plugins). +The Performance Analyzer plugin is not available on Windows. All other OpenSearch plugins, including the k-NN plugin, are available. For a complete list of plugins, see [Available plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#available-plugins). -## Related links +## Related documentation +- [Preparing a cluster for production]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#preparing-a-cluster-for-production) +- [Common installation issues]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/#common-issues) - [OpenSearch configuration]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/) -- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/opensearch/install/plugins/) +- [OpenSearch plugin installation]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) - [About the Security plugin]({{site.url}}{{site.baseurl}}/security/index/) diff --git a/_install-and-configure/os-comp.md b/_install-and-configure/os-comp.md new file mode 100644 index 00000000..dd6afdd2 --- /dev/null +++ b/_install-and-configure/os-comp.md @@ -0,0 +1,34 @@ +--- +layout: default +title: Compatible operating systems +nav_order: 120 +--- + +# Compatible operating systems + +OpenSearch and OpenSearch Dashboards are compatible with Red Hat Enterprise Linux (RHEL) and Debian-based Linux distributions that use [`systemd`](https://en.wikipedia.org/wiki/Systemd), such as Amazon Linux, and Ubuntu Long-Term Support (LTS). While OpenSearch and OpenSearch Dashboards should work on most Linux distributions, we only test a subset. + +## Supported operating systems + +The following table lists the operating system versions that we test for OpenSearch and OpenSearch Dashboards {{site.opensearch_major_minor_version}}. To view the operating systems tested for a different OpenSearch version, select that version in the documentation version selector. + +Operating system | Version +:---------- | :-------- +Rocky Linux | 8 +Alma Linux | 8 +Amazon Linux | 2023 +Ubuntu | 24.04 +Windows Server | 2019 + + +## Change log + +The following table lists changes made to operating system compatibility. + +| Date | Issue | PR | Details | +|:-----------|:-------|:-------|:--------------------------| +| `2026-09-29` | [`opensearch-build` issue 5227](https://github.com/opensearch-project/opensearch-build/issues/5227) | [PR 12853](https://github.com/opensearch-project/documentation-website/pull/12853) | Remove [Amazon Linux 2](https://aws.amazon.com/amazon-linux-2/faqs/) | +| `2025-02-06` | [`opensearch-build` issue 5270](https://github.com/opensearch-project/opensearch-build/issues/5270) | [PR 9165](https://github.com/opensearch-project/documentation-website/pull/9165) | Remove [Ubuntu 20.04](https://ubuntu.com/blog/ubuntu-20-04-lts-end-of-life-standard-support-is-coming-to-an-end-heres-how-to-prepare) | +| `2024-07-23` | [`opensearch-build` issue 4379](https://github.com/opensearch-project/opensearch-build/issues/4379) | [PR 7821](https://github.com/opensearch-project/documentation-website/pull/7821) | Remove [CentOS7](https://blog.centos.org/2023/04/end-dates-are-coming-for-centos-stream-8-and-centos-linux-7/) | +| `2024-03-08` | [`opensearch-build` issue 4573](https://github.com/opensearch-project/opensearch-build/issues/4573) | [PR 6637](https://github.com/opensearch-project/documentation-website/pull/6637) | Remove CentOS8, add Almalinux8/Rockylinux8, and remove Ubuntu 16.04/18.04 because we currently only test on 20.04 | +| `2023-06-06` | [`documentation-website` issue 4217](https://github.com/opensearch-project/documentation-website/issues/4217) | [PR 4218](https://github.com/opensearch-project/documentation-website/pull/4218) | Support matrix creation | diff --git a/_install-and-configure/plugins.md b/_install-and-configure/plugins.md index b18257cf..d4544a53 100644 --- a/_install-and-configure/plugins.md +++ b/_install-and-configure/plugins.md @@ -1,33 +1,66 @@ --- layout: default -title: Installing plugins +title: Managing OpenSearch plugins nav_order: 90 +has_children: true redirect_from: - /opensearch/install/plugins/ - /install-and-configure/install-opensearch/plugins/ --- -# Installing plugins +# Managing OpenSearch plugins -You can install individual plugins for OpenSearch based on your needs. For information about available plugins, see [Available plugins](#available-plugins). +OpenSearch includes a number of plugins that add features and capabilities to the core platform. The plugins available to you are dependent on how OpenSearch was installed and which plugins were subsequently added or removed. For example, the minimal distribution of OpenSearch enables only core functionality, such as indexing and search. Using the minimal distribution of OpenSearch is beneficial when you are working in a testing environment, have custom plugins, or are intending to integrate OpenSearch with other services. -For plugins to work properly with OpenSearch, all plugins must have the ability to access the data in the cluster, including metadata about cluster operations. Therefore, to protect your cluster's data and preserve its integrity, first be sure you understand the function of a plugin before installing it on your OpenSearch cluster. Second, when selecting a custom plugin, make sure the plugin's source is a reliable one. +The standard distribution of OpenSearch includes many more plugins offering much more functionality. You can choose to add additional plugins or remove any of the plugins you don't need. + +For a list of the available plugins, see [Available plugins](#available-plugins). + +To manage OpenSearch Dashboards plugins, see [Managing OpenSearch Dashboards plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/plugins/). + +For a plugin to work properly with OpenSearch, it may request certain permissions as part of the installation process. Review the requested permissions and proceed accordingly. It is important that you understand a plugin's functionality before installation. When opting for a community-provided plugin, ensure that the source is trustworthy and reliable. {: .warning} -## Managing plugins +## Listing installed plugins using the CAT API -OpenSearch uses a command line tool called `opensearch-plugin` for managing plugins. This tool allows you to: +You can list installed plugins by using the [CAT API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-plugins/). -- [List](#list) installed plugins. -- [Install](#install) plugins. -- [Remove](#remove) an installed plugin. +#### Usage -Print help text by passing `-h` or `--help`. Depending on your host configuration, you might also need to run the command with `sudo` privileges. +```json +GET _cat/plugins +``` +{% include copy-curl.html %} -If you are running OpenSearch in a Docker container, plugins must be installed, removed, and configured by modifying the Docker image. For information, see [Working with plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker#working-with-plugins) +#### Example response + +```bash +opensearch-node1 opensearch-alerting 2.0.1.0 +opensearch-node1 opensearch-anomaly-detection 2.0.1.0 +opensearch-node1 opensearch-asynchronous-search 2.0.1.0 +opensearch-node1 opensearch-cross-cluster-replication 2.0.1.0 +opensearch-node1 opensearch-index-management 2.0.1.0 +opensearch-node1 opensearch-job-scheduler 2.0.1.0 +opensearch-node1 opensearch-knn 2.0.1.0 +opensearch-node1 opensearch-ml 2.0.1.0 +opensearch-node1 opensearch-notifications 2.0.1.0 +opensearch-node1 opensearch-notifications-core 2.0.1.0 +``` + +## Using the `opensearch-plugin` tool + +To manage plugins in OpenSearch, you can use a command line tool called `opensearch-plugin`. This tool allows you to perform the following actions: + +- [List](#listing-installed-plugins) installed plugins. +- [Install](#installing-plugins) plugins. +- [Remove](#removing-plugins) an installed plugin. + +You can print help text by passing `-h` or `--help`. Depending on your host configuration, you might also need to run the command with `sudo` privileges. + +If you're running OpenSearch in a Docker container, plugins must be installed, removed, and configured by modifying the Docker image. For more information, see [Working with plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/docker#working-with-plugins). {: .note} -## List +### Listing installed plugins Use `list` to see a list of plugins that have already been installed. @@ -35,8 +68,9 @@ Use `list` to see a list of plugins that have already been installed. ```bash bin/opensearch-plugin list ``` +{% include copy.html %} -#### Example +#### Example response ```bash $ ./opensearch-plugin list opensearch-alerting @@ -57,47 +91,25 @@ opensearch-security opensearch-sql ``` -You can also list installed plugins by using the [CAT API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-plugins/). +### Installing plugins -#### Path and HTTP method +There are three ways to install plugins using the `opensearch-plugin` tool: -```bash -GET _cat/plugins -``` +- [Install a plugin by name](#installing-a-plugin-by-name). +- [Install a plugin from a zip file](#installing-a-plugin-from-a-zip-file). +- [Install a plugin using Maven coordinates](#installing-a-plugin-using-maven-coordinates). -#### Example response +#### Installing a plugin by name -```bash -opensearch-node1 opensearch-alerting 2.0.1.0 -opensearch-node1 opensearch-anomaly-detection 2.0.1.0 -opensearch-node1 opensearch-asynchronous-search 2.0.1.0 -opensearch-node1 opensearch-cross-cluster-replication 2.0.1.0 -opensearch-node1 opensearch-index-management 2.0.1.0 -opensearch-node1 opensearch-job-scheduler 2.0.1.0 -opensearch-node1 opensearch-knn 2.0.1.0 -opensearch-node1 opensearch-ml 2.0.1.0 -opensearch-node1 opensearch-notifications 2.0.1.0 -opensearch-node1 opensearch-notifications-core 2.0.1.0 -``` +You can install plugins that aren't already preinstalled in your installation by using the plugin name. For a list of plugins that may not be preinstalled, see [Additional plugins](#additional-plugins). -## Install - -There are three ways to install plugins using the `opensearch-plugin`: - -- [Install a plugin by name](#install-a-plugin-by-name). -- [Install a plugin from a ZIP file](#install-a-plugin-from-a-zip-file). -- [Install a plugin using Maven coordinates](#install-a-plugin-using-maven-coordinates). - -### Install a plugin by name: - -For a list of plugins that can be installed by name, see [Additional plugins](#additional-plugins). - -#### Usage +##### Usage ```bash bin/opensearch-plugin install <plugin-name> ``` +{% include copy.html %} -#### Example +##### Example response ```bash $ sudo ./opensearch-plugin install analysis-icu -> Installing analysis-icu @@ -106,16 +118,23 @@ $ sudo ./opensearch-plugin install analysis-icu -> Installed analysis-icu with folder name analysis-icu ``` -### Install a plugin from a zip file +#### Installing a plugin from a zip file -Remote zip files can be installed by replacing `<zip-file>` with the URL of the hosted file. The tool only supports downloading over HTTP/HTTPS protocols. For local zip files, replace `<zip-file>` with `file:` followed by the absolute or relative path to the plugin zip file as in the second example below. +You can install remote zip files by replacing `<zip-file>` with the URL of the hosted file. The tool supports downloading over HTTP/HTTPS protocols only. For local zip files, replace `<zip-file>` with `file:` followed by the absolute or relative path to the plugin zip file, as shown in the second example that follows. -#### Usage +##### Usage ```bash bin/opensearch-plugin install <zip-file> ``` +{% include copy.html %} -#### Example +##### Example response +<details markdown="block"> + <summary> + Select to expand the example + </summary> + {: .text-delta} + ```bash # Zip file is hosted on a remote server - in this case, Maven central repository. $ sudo ./opensearch-plugin install https://repo1.maven.org/maven2/org/opensearch/plugin/opensearch-anomaly-detection/2.2.0.0/opensearch-anomaly-detection-2.2.0.0.zip @@ -165,18 +184,27 @@ for descriptions of what these permissions allow and the associated risks. Continue with installation? [y/N]y -> Installed opensearch-anomaly-detection with folder name opensearch-anomaly-detection ``` +</details> -### Install a plugin using Maven coordinates +#### Installing a plugin using Maven coordinates -The `opensearch-plugin install` tool also accepts Maven coordinates for available artifacts and versions hosted on [Maven Central](https://search.maven.org/search?q=org.opensearch.plugin). `opensearch-plugin` will parse the Maven coordinates you provide and construct a URL. As a result, the host must be able to connect directly to [Maven Central](https://search.maven.org/search?q=org.opensearch.plugin). The plugin installation will fail if you pass coordinates to a proxy or local repository. +The `opensearch-plugin install` tool also allows you to specify Maven coordinates for available artifacts and versions hosted on [Maven Central](https://central.sonatype.com/namespace/org.opensearch.plugin). The tool parses the Maven coordinates you provide and constructs a URL. As a result, the host must be able to connect directly to the Maven Central site. The plugin installation fails if you pass coordinates to a proxy or local repository. -#### Usage +##### Usage ```bash bin/opensearch-plugin install <groupId>:<artifactId>:<version> ``` +{% include copy.html %} -#### Example -```bash +##### Example response + +<details markdown="block"> + <summary> + Select to expand the example + </summary> + {: .text-delta} + +```console $ sudo ./opensearch-plugin install org.opensearch.plugin:opensearch-anomaly-detection:2.2.0.0 -> Installing org.opensearch.plugin:opensearch-anomaly-detection:2.2.0.0 -> Downloading org.opensearch.plugin:opensearch-anomaly-detection:2.2.0.0 from maven central @@ -200,6 +228,7 @@ for descriptions of what these permissions allow and the associated risks. Continue with installation? [y/N]y -> Installed opensearch-anomaly-detection with folder name opensearch-anomaly-detection ``` +</details> Restart your OpenSearch node after installing a plugin. {: .note} @@ -212,13 +241,25 @@ Multiple plugins can be installed in a single invocation. ```bash bin/opensearch-plugin install <plugin-name> <plugin-name> ... <plugin-name> ``` +{% include copy.html %} -#### Example -```bash -$ sudo $ ./opensearch-plugin install analysis-nori repository-s3 +#### Example response +```console +$ sudo ./opensearch-plugin install analysis-nori repository-s3 ``` -## Remove +### Installing plugins in batch mode + +When installing a plugin that requires additional privileges that are not included by default, the plugin will prompt you for confirmation of the required privileges. To grant all requested privileges, use batch mode to skip the confirmation prompt. + +To force batch mode when installing plugins, add the `-b` or `--batch` option: +```bash +bin/opensearch-plugin install --batch <plugin-name> +``` +{% include copy.html %} + + +### Removing plugins You can remove a plugin that has already been installed with the `remove` option. @@ -226,103 +267,108 @@ You can remove a plugin that has already been installed with the `remove` option ```bash bin/opensearch-plugin remove <plugin-name> ``` +{% include copy.html %} -#### Example -```bash -$ sudo $ ./opensearch-plugin remove opensearch-anomaly-detection +#### Example response +```console +$ sudo ./opensearch-plugin remove opensearch-anomaly-detection -> removing [opensearch-anomaly-detection]... ``` Restart your OpenSearch node after removing a plugin. {: .note} -## Batch mode - -When installing plugins that require additional privileges not included by default, the plugins will prompt the user for confirmation of the required privileges. To grant all requested privileges, use batch mode to skip the confirmation prompt. - -To force batch mode when installing plugins, add the `-b` or `--batch` option: -```bash -bin/opensearch-plugin install --batch <plugin-name> -``` ## Available plugins -Major, minor, and patch plugin versions must match OpenSearch major, minor, and patch versions in order to be compatible. For example, plugins versions 2.3.0.x work only with OpenSearch 2.3.0. -{: .warning} +OpenSearch provides several bundled plugins that are available for immediate use with all OpenSearch distributions except for the minimal distribution. Additional plugins are available but must be installed separately using one of the installation options. ### Bundled plugins -The following plugins are bundled with all OpenSearch distributions except for minimum distribution packages. +The following plugins are bundled with all OpenSearch distributions except for the minimal distribution. If you are using the minimal distribution, you can add these plugins by using one of the installation methods. | Plugin name | Repository | Earliest available version | | :--- | :--- | :--- | -| Alerting | [opensearch-alerting](https://github.com/opensearch-project/alerting) | 1.0.0 | -| Anomaly Detection | [opensearch-anomaly-detection](https://github.com/opensearch-project/anomaly-detection) | 1.0.0 | -| Asynchronous Search | [opensearch-asynchronous-search](https://github.com/opensearch-project/asynchronous-search) | 1.0.0 | -| Cross Cluster Replication | [opensearch-cross-cluster-replication](https://github.com/opensearch-project/cross-cluster-replication) | 1.1.0 | -| Custom Codecs | [opensearch-custom-codecs](https://github.com/opensearch-project/custom-codecs) | 2.10.0 | -| Flow Framework | [flow-framework](https://github.com/opensearch-project/flow-framework) | 2.12.0 | -| Notebooks<sup>1</sup> | [opensearch-notebooks](https://github.com/opensearch-project/dashboards-notebooks) | 1.0.0 to 1.1.0 | -| Notifications | [notifications](https://github.com/opensearch-project/notifications) | 2.0.0 -| Reports Scheduler | [opensearch-reports-scheduler](https://github.com/opensearch-project/dashboards-reports) | 1.0.0 | -| Geospatial | [opensearch-geospatial](https://github.com/opensearch-project/geospatial) | 2.2.0 | -| Index Management | [opensearch-index-management](https://github.com/opensearch-project/index-management) | 1.0.0 | -| Job Scheduler | [opensearch-job-scheduler](https://github.com/opensearch-project/job-scheduler) | 1.0.0 | -| k-NN | [opensearch-knn](https://github.com/opensearch-project/k-NN) | 1.0.0 | -| ML Commons | [opensearch-ml](https://github.com/opensearch-project/ml-commons) | 1.3.0 | -| Neural Search | [neural-search](https://github.com/opensearch-project/neural-search) | 2.4.0 | -| Observability | [opensearch-observability](https://github.com/opensearch-project/observability) | 1.2.0 | -| Performance Analyzer<sup>2</sup> | [opensearch-performance-analyzer](https://github.com/opensearch-project/performance-analyzer) | 1.0.0 | -| Security | [opensearch-security](https://github.com/opensearch-project/security) | 1.0.0 | -| Security Analytics | [opensearch-security-analytics](https://github.com/opensearch-project/security-analytics) | 2.4.0 | -| SQL | [opensearch-sql](https://github.com/opensearch-project/sql) | 1.0.0 | +| Alerting | [`opensearch-alerting`](https://github.com/opensearch-project/alerting) | 1.0.0 | +| Anomaly Detection | [`opensearch-anomaly-detection`](https://github.com/opensearch-project/anomaly-detection) | 1.0.0 | +| Asynchronous Search | [`opensearch-asynchronous-search`](https://github.com/opensearch-project/asynchronous-search) | 1.0.0 | +| Cross Cluster Replication | [`opensearch-cross-cluster-replication`](https://github.com/opensearch-project/cross-cluster-replication) | 1.1.0 | +| Custom Codecs | [`opensearch-custom-codecs`](https://github.com/opensearch-project/custom-codecs) | 2.10.0 | +| Flow Framework | [`flow-framework`](https://github.com/opensearch-project/flow-framework) | 2.12.0 | +| Notebooks<sup>1</sup> | [`opensearch-notebooks`](https://github.com/opensearch-project/dashboards-notebooks) | 1.0.0 to 1.1.0 | +| Notifications | [`notifications`](https://github.com/opensearch-project/notifications) | 2.0.0 | +| Reports Scheduler | [`opensearch-reports-scheduler`](https://github.com/opensearch-project/dashboards-reports) | 1.0.0 | +| Geospatial | [`opensearch-geospatial`](https://github.com/opensearch-project/geospatial) | 2.2.0 | +| Index Management | [`opensearch-index-management`](https://github.com/opensearch-project/index-management) | 1.0.0 | +| Job Scheduler | [`opensearch-job-scheduler`](https://github.com/opensearch-project/job-scheduler) | 1.0.0 | +| k-NN | [`opensearch-knn`](https://github.com/opensearch-project/k-NN) | 1.0.0 | +| Learning to Rank | [`opensearch-ltr`](https://github.com/opensearch-project/opensearch-learning-to-rank-base) | 2.19.0 | +| ML Commons | [`opensearch-ml`](https://github.com/opensearch-project/ml-commons) | 1.3.0 | +| Skills | [`opensearch-skills`](https://github.com/opensearch-project/skills) | 2.12.0 | +| Neural Search | [`neural-search`](https://github.com/opensearch-project/neural-search) | 2.4.0 | +| Observability | [`opensearch-observability`](https://github.com/opensearch-project/observability) | 1.2.0 | +| Performance Analyzer<sup>2</sup> | [`opensearch-performance-analyzer`](https://github.com/opensearch-project/performance-analyzer) | 1.0.0 | +| Security | [`opensearch-security`](https://github.com/opensearch-project/security) | 1.0.0 | +| Security Analytics | [`opensearch-security-analytics`](https://github.com/opensearch-project/security-analytics) | 2.4.0 | +| SQL | [`opensearch-sql`](https://github.com/opensearch-project/sql) | 1.0.0 | +| Remote Metadata SDK | [`opensearch-remote-metadata-sdk`](https://github.com/opensearch-project/opensearch-remote-metadata-sdk) | 2.19.0 | +| Query Insights | [`query-insights`](https://github.com/opensearch-project/query-insights) | 2.16.0 | +| System Templates | [`opensearch-system-templates`](https://github.com/opensearch-project/opensearch-system-templates) | 2.17.0 | +| User Behavior Insights | [`ubi`](https://github.com/opensearch-project/user-behavior-insights) | 3.0.0 | +| Search Relevance | [`search-relevance`](https://github.com/opensearch-project/search-relevance) | 3.1.0 | _<sup>1</sup>Dashboard Notebooks was merged in to the Observability plugin with the release of OpenSearch 1.2.0._<br> _<sup>2</sup>Performance Analyzer is not available on Windows._ +#### Downloading bundled plugins for offline installation + +Each bundled plugin can be downloaded and installed offline from a [zip file](#installing-a-plugin-from-a-zip-file). + +The URL for the corresponding plugin can be found in the `manifest.yml` file located in the root directory of the extracted bundle. + +### Core plugins + +A _core_ (or _native_) plugin in OpenSearch is a plugin that resides in the [OpenSearch core engine repository](https://github.com/opensearch-project/OpenSearch/tree/main/plugins). These plugins are tightly integrated with the OpenSearch engine, are versioned alongside core releases, and are not bundled by default in the standard OpenSearch distribution. + + +#### Downloading core plugins for offline installation + +Each core plugins in [this list](https://github.com/opensearch-project/OpenSearch/tree/main/plugins) can be downloaded and installed offline from a [zip file](#installing-a-plugin-from-a-zip-file) using the official `plugins` repository URL template: + +```html +https://artifacts.opensearch.org/releases/plugins/<plugin-name>/<version>/<plugin-name>-<version>.zip +``` + +The `<plugin-name>` corresponds to the name of the bundled plugin (for example, `analysis-icu`). The `<version>` must match the version of the OpenSearch distribution (for example, `2.19.1`). + +For example, use the following URL to download the `analysis-icu` bundled plugin distribution for OpenSearch version `2.19.1`: + +``` +https://artifacts.opensearch.org/releases/plugins/analysis-icu/2.19.1/analysis-icu-2.19.1.zip +``` + ### Additional plugins -Members of the OpenSearch community have built countless plugins for the service. Although it isn't possible to build an exhaustive list of every plugin, since many plugins are not maintained within the OpenSearch GitHub repository, the following list of plugins are available to be installed by name using `bin/opensearch-plugin install <plugin-name>`. +There are many more plugins available in addition to those provided by the default distribution. These additional plugins have been built by OpenSearch developers or members of the OpenSearch community. For a list of additional plugins you can install, see [Additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/additional-plugins/index/). -| Plugin name | Earliest available version | -| :--- | :--- | -| analysis-icu | 1.0.0 | -| analysis-kuromoji | 1.0.0 | -| analysis-nori | 1.0.0 | -| analysis-phonetic | 1.0.0 | -| analysis-smartcn | 1.0.0 | -| analysis-stempel | 1.0.0 | -| analysis-ukrainian | 1.0.0 | -| discovery-azure-classic | 1.0.0 | -| discovery-ec2 | 1.0.0 | -| discovery-gce | 1.0.0 | -| ingest-attachment | 1.0.0 | -| mapper-annotated-text | 1.0.0 | -| mapper-murmur3 | 1.0.0 | -| mapper-size | 1.0.0 | -| query-insights | 2.12.0 | -| repository-azure | 1.0.0 | -| repository-gcs | 1.0.0 | -| repository-hdfs | 1.0.0 | -| repository-s3 | 1.0.0 | -| store-smb | 1.0.0 | -| transport-nio | 1.0.0 | +## Plugin compatibility -## Related links +You can specify plugin compatibility with a particular OpenSearch version in the `plugin-descriptor.properties` file. For example, a plugin with the following property is compatible only with OpenSearch 2.3.0: + +```properties +opensearch.version=2.3.0 +``` +Alternatively, you can specify a range of compatible OpenSearch versions by setting the `dependencies` property in the `plugin-descriptor.properties` file to one of the following notations: +- `dependencies={ opensearch: "2.3.0" }`: The plugin is compatible only with OpenSearch version 2.3.0. +- `dependencies={ opensearch: "=2.3.0" }`: The plugin is compatible only with OpenSearch version 2.3.0. +- `dependencies={ opensearch: "~2.3.0" }`: The plugin is compatible with all versions from 2.3.0 up to the next minor version, in this example, 2.4.0 (exclusive). +- `dependencies={ opensearch: "^2.3.0" }`: The plugin is compatible with all versions from 2.3.0 up to the next major version, in this example, 3.0.0 (exclusive). + +You can specify only one of the `opensearch.version` or `dependencies` properties. +{: .note} + +## Plugin dependencies + +Some plugins extend functionality of other plugins. If a plugin has a dependency on another plugin, you must install the required dependency before installing the dependent plugin. For plugin dependencies, see the [manifest file](https://github.com/opensearch-project/opensearch-build/blob/main/manifests/{{site.opensearch_version}}/opensearch-{{site.opensearch_version}}.yml). In this file, each plugin's dependencies are listed in the `depends_on` parameter. -- [About Observability]({{site.url}}{{site.baseurl}}/observability-plugin/index/) -- [About security analytics]({{site.url}}{{site.baseurl}}/security-analytics/index/) -- [About the Security plugin]({{site.url}}{{site.baseurl}}/security/index/) -- [Alerting]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/index/) -- [Anomaly detection]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/index/) -- [Asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/index/) -- [Cross-cluster replication]({{site.url}}{{site.baseurl}}/replication-plugin/index/) -- [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) -- [k-NN]({{site.url}}{{site.baseurl}}/search-plugins/knn/index/) -- [ML Commons plugin]({{site.url}}{{site.baseurl}}/ml-commons-plugin/index/) -- [Neural Search]({{site.url}}{{site.baseurl}}/neural-search-plugin/index/) -- [Notifications]({{site.url}}{{site.baseurl}}/notifications-plugin/index/) -- [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/index/) -- [Performance Analyzer]({{site.url}}{{site.baseurl}}/monitoring-plugins/pa/index/) -- [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/index/) diff --git a/_ml-commons-plugin/agentic-memory-retention.md b/_ml-commons-plugin/agentic-memory-retention.md new file mode 100644 index 00000000..8781db0b --- /dev/null +++ b/_ml-commons-plugin/agentic-memory-retention.md @@ -0,0 +1,245 @@ +--- +layout: default +title: Agentic memory retention +parent: Agentic memory +grand_parent: Memory and context +nav_order: 30 +--- + +# Agentic memory retention +**Introduced 3.8** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +By default, agentic memories accumulate indefinitely, which increases storage use and can cause agents to retrieve outdated memories. To automatically delete old or excess memories, define a _retention policy_ for a [memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-containers). The retention policy specifies an age limit, a count limit, or both for each memory type. A background job enforces the policy on a schedule. It deletes `sessions`, `long-term`, and `history` memories that exceed a count limit, or `sessions` and `long-term` memories that exceed an age limit. In contrast, `working` memory is not subject to the retention policy and is deleted when its parent session no longer exists. To control the amount of time that `working` memories are retained, configure retention for `sessions`. + +You can exclude `sessions` and `long-term` memories from the retention policy by pinning them. For more information, see [Pinning memories](#pinning-memories). + +## Enabling memory retention + +Retention is disabled by default. To enable it cluster-wide, configure the following dynamic cluster setting: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.memory.retention_enabled": true + } +} +``` +{% include copy-curl.html %} + +## Defining a retention policy + +The `retention_policy` object is specified in the container's `configuration` object and maps each memory type to the retention limits for that type. Replace `{memory_type}` with `sessions`, `long-term`, or `history`: + +```json +"configuration": { + "retention_policy": { + "{memory_type}": { + "retention_days": 90, + "max_count": 5000 + } + } +} +``` + +Each `{memory_type}` object accepts the following optional fields. When both fields are set, a memory is deleted if it violates either rule. + +Field | Data type | Supported memory types | Description +:--- | :--- | :--- | :--- +`retention_days` | Integer | `sessions`, `long-term` | Deletes memories older than this many days, measured from the memory's `last_updated_time`. +`max_count` | Integer | `sessions`, `long-term`, `history` | Keeps at most this many memories, deleting the oldest first. Sessions and long-term memory are ordered by `last_updated_time`; history is ordered by `created_time`. + +A retention rule takes effect only if the container stores that memory type. For `long-term` and `history` memories to be stored, you must configure `strategies`; otherwise, retention rules for those types have no effect. For more information, see [The created indexes]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/#the-created-indexes). +{: .note} + +### Configuring a retention policy + +To configure a policy when you create a memory container, include the `retention_policy` field in the create request. The following example creates a container with session tracking, a strategy, and a retention policy that retains up to 5,000 sessions for 90 days and limits long-term memory to 2,000 entries: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "my-agent-memory", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "your-embedding-model-id", + "embedding_dimension": 1024, + "llm_id": "your-llm-model-id", + "strategies": [ + { + "type": "SEMANTIC", + "namespace": ["user_id"] + } + ], + "retention_policy": { + "sessions": { + "retention_days": 90, + "max_count": 5000 + }, + "long-term": { + "max_count": 2000 + } + } + } +} +``` +{% include copy-curl.html %} + +You can also add a retention policy for an existing container at any time by sending the `retention_policy` object in an update request: + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +{ + "configuration": { + "retention_policy": { + "sessions": { + "retention_days": 90, + "max_count": 5000 + }, + "long-term": { + "max_count": 2000 + } + } + } +} +``` +{% include copy-curl.html %} + +A policy applies to all memories in the container, including those created before you added the policy. For example, adding a `max_count` of 100 to a container that holds 10,000 sessions deletes the 9,900 least recently updated sessions. To preserve specific memories, [pin](#pinning-memories) them before adding the policy. +{: .warning} + +### Viewing a retention policy + +To view the stored policy, retrieve the container using the [Get Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/get-memory-container/): + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id} +``` +{% include copy-curl.html %} + +### Updating a retention policy + +Updating a `retention_policy` merges your changes into the existing policy rather than replacing it. Memory types and fields that you omit are left unchanged. + +To remove a single field, set it to `null`. For example, the following request updates the policy in the [Configuring a retention policy](#configuring-a-retention-policy) example by removing `retention_days` from `sessions` while keeping the `max_count` of 5,000: + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +{ + "configuration": { + "retention_policy": { + "sessions": { + "retention_days": null + } + } + } +} +``` +{% include copy-curl.html %} + +### Disabling retention for a container + +To disable retention for the entire container, set `retention_policy` to `null`: + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +{ + "configuration": { + "retention_policy": null + } +} +``` +{% include copy-curl.html %} + +Setting `retention_policy` to `null` differs from omitting it. Omitting the policy leaves the container eligible for [cluster-level default settings](#default-settings); setting it to `null` exempts the container from those defaults. You can send this request even when retention is disabled cluster-wide. + +## Pinning memories + +Pinning a memory exempts it from deletion under a container's [retention policy](#defining-a-retention-policy). You can pin `sessions` and `long-term` memories. Pinning `sessions` retains all of their `working` memories. Because pinned memories are never deleted, they can accumulate over time. To reduce the container size, unpin `sessions` that no longer require protection. + +Pinning protects a memory from deletion but does not change its age. A memory's age is measured from its `last_updated_time`, which advances only when its content changes, such as when a `working` memory is added to a session or a `long-term` memory is updated. Pinning does not update this timestamp, so if you later unpin the memory, its age still reflects its last content change and it may become immediately eligible for deletion. + +Use the following request field to pin a memory. + +Field | Data type | Description +:--- | :--- | :--- +`pinned` | Boolean | Set to `true` to pin a memory or `false` to unpin it. Valid for `sessions` and `long-term` memories. + +The following example pins a memory (specify either `sessions` or `long-term` as `memory_type`): + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id}/memories/{memory_type}/{memory_id} +{ + "pinned": true +} +``` +{% include copy-curl.html %} + +## Retention job + +A background job enforces retention policies on a [schedule](#retention-job-schedule) (by default, every 24 hours). Because enforcement is scheduled rather than continuous, a memory that has passed its age or count limit is still returned in search results until the job next runs and deletes it. + +Memories are evaluated against the following limits: + +- `retention_days` is measured from a memory's `last_updated_time`. Adding a `working` memory to a session advances the session's timestamp, so active conversations are retained. Pinning a memory does not advance it. +- `max_count` applies regardless of age. If a container holds more than `max_count` non-pinned memories of a type, the oldest are deleted until `max_count` remain, even if they are newer than `retention_days`. +- When a memory type sets both limits, a memory is deleted if it exceeds either one. + +When enforcing `max_count`, each run deletes at most 50,000 memories in a container for each memory type. A larger backlog is reduced over successive runs, so a container that far exceeds its `max_count` may take several runs to reach the limit. Deletions based on `retention_days` are not capped. + +When the job evicts a `sessions` memory, its `working` memories are deleted first so that no orphans are created. Manually deleting a `sessions` memory does not delete its `working` memories, leaving them orphaned. After enforcing the policies, the job removes orphaned `working` memories whose `created_time` is older than `orphan_ttl_days`. The first time the job checks a container for orphans, it records a baseline and deletes nothing, so orphan deletion in that container begins `orphan_ttl_days` after the baseline. + +Orphan cleanup runs only for containers that have a retention policy and that were created with `disable_session` set to `false` (the default). In a container with no retention policy, orphaned `working` memories are retained indefinitely. + +A container created with `disable_session` set to `true` stores no `sessions` memories, so neither of the preceding mechanisms applies to it. Its `working` memories are deleted only by the `plugins.ml_commons.memory.working_memory_ttl_days` setting, which is disabled by default. Until you set it to a positive value, these containers retain `working` memories indefinitely. For more information, see [Memory retention settings](#memory-retention-settings). + +The job is disabled when multi-tenancy is active. In this case, no retention is enforced, even for containers that have a policy. + +## Pausing retention + +To pause retention while preserving configured retention policies, set `plugins.ml_commons.memory.retention_enabled` to `false`. Setting it back to `true` resumes enforcement. + +## Memory retention settings + +You can customize retention behavior using the following dynamic cluster settings: + +- `plugins.ml_commons.memory.retention_enabled` (Boolean): Enables retention cluster-wide. While this setting is `false`, the retention job deletes nothing and the container APIs reject a `retention_policy`. Default is `false`. + +- `plugins.ml_commons.memory.retention_job_throttle_seconds` (Integer): Specifies how long the retention job pauses after processing a container in which it deleted memories, before it moves on to the next container. Increase this value to reduce cluster load. Valid values are in the `[1, 60]` range. Default is `5`. + +- `plugins.ml_commons.memory.working_memory_ttl_days` (Integer): Deletes a `working` memory this many days after it is created. Applicable only to containers created with `disable_session` set to `true`. Because those containers store no `sessions` memories, this setting is the only mechanism that deletes their `working` memories. Valid values are in the `[1, 365]` range. Default is `-1` (disabled). + +- `plugins.ml_commons.memory.orphan_ttl_days` (Integer): Deletes a `working` memory whose parent `sessions` memory no longer exists, measured from the `working` memory's `created_time`. For more information, see [Retention job](#retention-job). Valid values are in the `[1, 365]` range. Default is `7`. + +### Default settings + +The default settings apply to any container that has not set its own retention policy. They take effect only after [retention is enabled for the cluster](#enabling-memory-retention); until then, they are stored but have no effect. Once retention is enabled, the next scheduled job applies them to containers that have no policy and deletes any memories that exceed the default values, including memories that were created before you set the defaults. + +Defaults are applied to a container only once; changing these settings later does not update containers to which they were already applied. To exempt a container from the defaults, set its `retention_policy` to `null`. To update a container's policy after the defaults are applied, use the [Update Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/update-memory-container/). + +Each of the following dynamic settings provides the default for one field of a [retention policy](#defining-a-retention-policy). The default `-1` applies no default for that field: + +- `plugins.ml_commons.memory.default_session_retention_days` (Integer): Sets the default `retention_days` for `sessions` memories. Valid values are in the `[1, 3650]` range. Default is `-1`. + +- `plugins.ml_commons.memory.default_session_max_count` (Integer): Sets the default `max_count` for `sessions` memories. Valid values are in the `[1, 1000000]` range. Default is `-1`. + +- `plugins.ml_commons.memory.default_long_term_max_count` (Integer): Sets the default `max_count` for `long-term` memories. Valid values are in the `[1, 1000000]` range. Default is `-1`. + +- `plugins.ml_commons.memory.default_history_max_count` (Integer): Sets the default `max_count` for `history` memories. Valid values are in the `[1, 10000000]` range. Default is `-1`. + +### Retention job schedule + +<!-- TODO: When this feature goes GA, revisit the retention_job_interval_hours behavior (currently static-like; dynamic interval updates are planned for a future release). --> + +The following setting controls the retention job schedule. Set it in `opensearch.yml` before starting the cluster. The job reads it once, when it is first scheduled at startup; updating it through the Cluster Settings API on a running cluster has no effect: + +- `plugins.ml_commons.memory.retention_job_interval_hours` (Integer): Specifies how often the retention job runs, in hours. Valid values are in the `[1, 168]` range. Default is `24`. + +## Next steps + +- For more information about memory containers and agentic memory, see [Agentic memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/). +- For the container creation API reference, see [Create Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/). diff --git a/_ml-commons-plugin/agentic-memory.md b/_ml-commons-plugin/agentic-memory.md new file mode 100644 index 00000000..0302ac4e --- /dev/null +++ b/_ml-commons-plugin/agentic-memory.md @@ -0,0 +1,272 @@ +--- +layout: default +title: Agentic memory +parent: Memory and context +has_children: true +has_toc: false +nav_order: 10 +--- + +# Agentic memory +**Introduced 3.3** +{: .label .label-purple } + +Agentic memory enables AI agents to learn, remember, and reason over structured information across conversations. Unlike simple conversation memory that only stores message history, agentic memory provides persistent, intelligent storage that helps agents maintain context, learn user preferences, and improve their responses over time. + +Using agentic memory, you can build AI agents that can do the following: + +- Remember user preferences across multiple conversation sessions +- Learn from past interactions to provide more personalized responses +- Maintain conversation context beyond simple message history +- Store and retrieve factual knowledge extracted from conversations +- Track agent execution traces for debugging and analysis +- Organize information across different users, sessions, or agent instances + +Agentic memory is designed for integration with both OpenSearch's internal [agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/) and external agent frameworks like LangChain and LangGraph. + +> **Important**: +> +> The agentic memory capability in OpenSearch is provided as a framework that enables you to build and manage memory for AI agents. As the administrator or owner of a memory container, you are responsible for the configuration, management, and security of your implementation. +> You are responsible for the following: +> - Data access control: Implement and enforce all necessary data access controls for the conversation data stored within the memory container. This includes, but is not limited to, configuring appropriate index-level permissions, document-level security (DLS), or other mechanisms to restrict access. This responsibility is especially critical when the use_system_index option is set to false, because data will be stored in a standard index that requires explicit permission management. +> - Custom system prompt management: If you choose to use a customized system prompt instead of the default, you are responsible for the content, management, and behavior of that prompt. OpenSearch is not responsible for the outputs or interactions resulting from user-defined system prompts. +> Failure to properly configure and secure your agentic memory implementation may result in unauthorized data access, data leakage, or unintended agent behavior. +{: .warning} + +## Memory containers + +Agentic memory is organized into _memory containers_ that hold all memory types for a specific use case, such as a chatbot, research assistant, or customer service agent. + +Each container can be configured with the following components: + +- Text embedding models: For semantic search capabilities. +- Large language models (LLMs): For inference and knowledge extraction. +- [Memory processing strategies](#memory-processing-strategies): For defining how memories are processed or extracted. +- [Namespaces](#namespaces): For partitioning and isolating memories by context, user, agent, or session. + +For example, to create a memory container with two strategies, send the following request: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "customer-service-agent", + "description": "Memory container for customer service agent", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "your-embedding-model-id", + "embedding_dimension": 1024, + "llm_id": "your-llm-model-id", + "strategies": [ + { + "type": "USER_PREFERENCE", + "namespace": ["user_id"] + }, + { + "type": "SUMMARY", + "namespace": ["user_id", "session_id"] + } + ] + } +} +``` +{% include copy-curl.html %} + +## Memory types + +Each memory container can store four distinct types of memory: + +- `sessions` -- Manages conversation sessions and their metadata. Each session represents a distinct interaction context between users and agents, containing session-specific information such as start time, participants, and session state. + +- `working` -- Stores active conversation data and structured information that agents use during ongoing interactions. This includes recent messages, current context, agent state, execution traces, and temporary data needed for immediate processing. + +- `long-term` -- Contains processed knowledge and facts extracted from conversations over time. When inference is enabled, LLMs extract key insights, user preferences, and important information from working memory and store them as persistent knowledge. + +- `history` -- Maintains an audit trail of all memory operations (add, update, delete) across the memory container. This provides a comprehensive log of how memories have evolved and changed over time. + +## Payload types + +When adding memories, you can specify different payload types: + +- `conversational` -- Stores conversational messages between users and assistants. +- `data` -- Stores structured, non-conversational data such as agent state, checkpoints, or reference information. + +To add a conversation memory with inference, send the following request: + +```json +POST /_plugins/_ml/memory_containers/{container_id}/memories +{ + "messages": [ + { + "role": "user", + "content": [ + { + "text": "I prefer email notifications over SMS", + "type": "text" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "text": "I've noted your preference for email notifications", + "type": "text" + } + ] + } + ], + "namespace": { + "user_id": "user123", + "session_id": "session456" + }, + "payload_type": "conversational", + "infer": true +} +``` +{% include copy-curl.html %} + +To add agent state data, send the following request: + +```json +POST /_plugins/_ml/memory_containers/{container_id}/memories +{ + "structured_data": { + "agent_state": "researching", + "current_task": "analyze customer feedback", + "progress": 0.75 + }, + "namespace": { + "agent_id": "research-agent-1", + "session_id": "session456" + }, + "payload_type": "data", + "infer": false +} +``` +{% include copy-curl.html %} + +## Inference mode + +You can control how OpenSearch processes memories using the `infer` parameter: + +- `false` (default) -- Stores raw messages and data in `working` memory without LLM processing. +- `true` -- Uses the configured LLM to extract key information and knowledge from the content. + +## Memory processing strategies + +Memory containers can use the following _strategies_ to automatically process and organize memories: + +- `SEMANTIC` -- Groups related memories by meaning and content similarity. +- `USER_PREFERENCE` -- Extracts and stores user preferences from conversations. +- `SUMMARY` -- Creates condensed summaries of conversation content. + +Strategies are optional; you can create containers without them for simple storage needs. + +## Namespaces + +_Namespaces_ organize memories within containers by grouping them with identifiers like `user_id`, `session_id`, or `agent_id`. This allows you to separate memories for different users or conversation sessions. + +To search memories by namespace, send the following request: + +```json +GET /_plugins/_ml/memory_containers/{container_id}/memories/long-term/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "namespace.user_id": "user123" + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +## Example use cases + +The following examples demonstrate how you can use agentic memory. + +### Personalized chatbot + +Create a memory container that learns user preferences over time: + +- Store conversations in `working` memory with inference enabled. +- Extract user preferences into `long-term` memory using the `USER_PREFERENCE` strategy. +- Use namespaces to separate different users' memories. + +### Research assistant agent + +Build an agent that accumulates knowledge from research sessions: + +- Store research queries and results in `working` memory. +- Use the `SEMANTIC` strategy to group related research topics. +- Maintain `history` to track how knowledge evolved over time. + +### Customer service agent + +Develop an agent that remembers customer interactions: + +- Store customer conversations with inference to extract key issues. +- Use `SUMMARY` strategy to create concise interaction summaries. +- Organize by customer ID using namespaces. + +## Getting started + +To implement agentic memory in your agents: + +1. **[Create a memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/)** with appropriate models and strategies. +2. **[Add memories]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/add-memory/)** during agent interactions. +3. **[Search and retrieve]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/search-memory/)** relevant memories to inform agent responses. +4. **[Update memories]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/update-memory/)** as conversations evolve. + +For detailed API documentation, see [Agentic Memory APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/). + +## Inspecting memory data (OpenSearch agents) + +After executing OpenSearch agents configured with agentic memory, you can inspect session and trace data using the [Get Memory API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/get-memory/) or [Search Memory API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/search-memory/): + +1. Retrieve the session by `memory_id`: + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/sessions/{memory_id} +``` +{% include copy-curl.html %} + +2. Retrieve a message by interaction ID (`parent_interaction_id` from the agent execution output): + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/working/{interaction_id} +``` +{% include copy-curl.html %} + +3. Get full working-memory trace data for a session using `namespace.session_id = <memory_id>`: + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/working/_search +{ + "query": { + "match": { + "namespace.session_id": "<memory_id>" + } + }, + "sort": [ + { + "created_time": { + "order": "asc" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Next steps + +- Learn about [agentic memory retention]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory-retention/). +- Explore [memory container configuration]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/) options. +- Review the complete [Agentic Memory API reference]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/). +- For a tutorial that uses agentic memory as the long-term memory of an agent built using Strands Agents, see [Using agentic memory with Strands Agents]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/agentic-memory-strands/). diff --git a/_ml-commons-plugin/agents-tools/agents-tools-tutorial.md b/_ml-commons-plugin/agents-tools/agents-tools-tutorial.md index bc2b7443..28b05d3b 100644 --- a/_ml-commons-plugin/agents-tools/agents-tools-tutorial.md +++ b/_ml-commons-plugin/agents-tools/agents-tools-tutorial.md @@ -2,17 +2,13 @@ layout: default title: Agents and tools tutorial parent: Agents and tools -grand_parent: ML Commons APIs -nav_order: 10 +nav_order: 5 --- # Agents and tools tutorial -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The following tutorial illustrates creating a flow agent for retrieval-augmented generation (RAG). A flow agent runs its configured tools sequentially, in the order specified. In this example, you'll create an agent with two tools: 1. `VectorDBTool`: The agent will use this tool to retrieve OpenSearch documents relevant to the user question. You'll ingest supplementary information into an OpenSearch index. To facilitate vector search, you'll deploy a text embedding model that translates text into vector embeddings. OpenSearch will translate the ingested documents into embeddings and store them in the index. When you provide a user question to the agent, the agent will construct a query from the question, run vector search on the OpenSearch index, and pass the relevant retrieved documents to the `MLModelTool`. @@ -23,7 +19,7 @@ The following tutorial illustrates creating a flow agent for retrieval-augmented To use the memory feature, first configure the following cluster settings. This tutorial assumes that you have no dedicated machine learning (ML) nodes: ```json -PUT _cluster/settings +PUT /_cluster/settings { "persistent": { "plugins.ml_commons.only_run_on_ml_node": "false", @@ -45,7 +41,7 @@ In this tutorial, you'll use the `huggingface/sentence-transformers/all-MiniLM-L POST /_plugins/_ml/models/_register?deploy=true { "name": "huggingface/sentence-transformers/all-MiniLM-L12-v2", - "version": "1.0.1", + "version": "1.0.2", "model_format": "TORCH_SCRIPT" } ``` @@ -60,14 +56,14 @@ Registering a model is an asynchronous task. OpenSearch returns a task ID for th } ``` -You can check the status of the task by calling the Tasks API: +You can check the status of the task by calling the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): ```json GET /_plugins/_ml/tasks/aFeif4oB5Vm0Tdw8yoN7 ``` {% include copy-curl.html %} -Once the task is complete, the task state changes to `COMPLETED` and the Tasks API response includes a model ID for the deployed model: +Once the task is complete, the task state changes to `COMPLETED` and the ML Tasks API response includes a model ID for the deployed model: ```json { @@ -104,13 +100,14 @@ PUT /_ingest/pipeline/test-pipeline-local-model ] } ``` +{% include copy-curl.html %} -## Step 3: Create a k-NN index and ingest data +## Step 3: Create a vector index and ingest data -Now you'll ingest supplementary data into an OpenSearch index. In OpenSearch, vectors are stored in a k-NN index. You can create a [k-NN index]({{site.url}}{{site.baseurl}}/search-plugins/knn/knn-index/) by sending the following request: +Now you'll ingest supplementary data into an OpenSearch index. In OpenSearch, vectors are stored in a vector index. You can create a [vector index]({{site.url}}{{site.baseurl}}/search-plugins/knn/knn-index/) by sending the following request: ```json -PUT my_test_data +PUT /my_test_data { "mappings": { "properties": { @@ -119,13 +116,13 @@ PUT my_test_data }, "embedding": { "type": "knn_vector", - "dimension": 384 + "dimension": 384, + "space_type": "cosinesimil" } } }, "settings": { "index": { - "knn.space_type": "cosinesimil", "default_pipeline": "test-pipeline-local-model", "knn": "true" } @@ -137,7 +134,7 @@ PUT my_test_data Then, ingest data into the index by using a bulk request: ```json -POST _bulk +POST /_bulk {"index": {"_index": "my_test_data", "_id": "1"}} {"text": "Chart and table of population level and growth rate for the Ogden-Layton metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\nThe current metro area population of Ogden-Layton in 2023 is 750,000, a 1.63% increase from 2022.\nThe metro area population of Ogden-Layton in 2022 was 738,000, a 1.79% increase from 2021.\nThe metro area population of Ogden-Layton in 2021 was 725,000, a 1.97% increase from 2020.\nThe metro area population of Ogden-Layton in 2020 was 711,000, a 2.16% increase from 2019."} {"index": {"_index": "my_test_data", "_id": "2"}} @@ -171,9 +168,9 @@ POST /_plugins/_ml/connectors/_create "endpoint": "bedrock.us-east-1.amazonaws.com", "auth": "Sig_V4", "content_type": "application/json", - "max_tokens_to_sample": 8000, + "max_tokens": 8000, "temperature": 0.0001, - "response_filter": "$.completion" + "response_filter": "$.content[0].text" }, "credential": { "access_key": "<bedrock_access_key>", @@ -184,12 +181,12 @@ POST /_plugins/_ml/connectors/_create { "action_type": "predict", "method": "POST", - "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", "headers": { "content-type": "application/json", "x-amz-content-sha256": "required" }, - "request_body": "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" } ] } @@ -232,7 +229,7 @@ Next, register and deploy the externally hosted Claude model: ```json POST /_plugins/_ml/models/_register?deploy=true { - "name": "Bedrock Claude V2 model", + "name": "Bedrock Claude Sonnet 4.6 model", "function_name": "remote", "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", "description": "test model", @@ -247,14 +244,14 @@ Similarly to [Step 1](#step-1-register-and-deploy-a-text-embedding-model), the r { "model_id": "NWR9YIsBUysqmzBdifVJ", "task_type": "REGISTER_MODEL", - "function_name": "remote", + "function_name": "REMOTE", "state": "COMPLETED", "worker_node": [ "4p6FVOmJRtu3wehDD74hzQ" ], "create_time": 1694358489722, "last_update_time": 1694358499139, - "is_async": true + "is_async": false } ``` @@ -264,7 +261,7 @@ To test the LLM, send the following predict request: POST /_plugins/_ml/models/NWR9YIsBUysqmzBdifVJ/_predict { "parameters": { - "prompt": "\n\nHuman:hello\n\nnAssistant:" + "prompt": "hello" } } ``` @@ -296,7 +293,7 @@ POST /_plugins/_ml/agents/_register "description": "A general tool to answer any question", "parameters": { "model_id": "NWR9YIsBUysqmzBdifVJ", - "prompt": "\n\nHuman:You are a professional data analyst. You will always answer a question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say you don't know. \n\n Context:\n${parameters.VectorDBTool.output}\n\nHuman:${parameters.question}\n\nAssistant:" + "prompt": "You are a professional data analyst. You will always answer a question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say you don't know. \n\n Context:\n${parameters.VectorDBTool.output}\n\nQuestion: ${parameters.question}" } } ] @@ -339,6 +336,7 @@ The LLM does not have the recent information in its knowledge base, so it infers { "output": [ { + "name": "MLModelTool", "result": """ Based on the given context, the key information is: The metro area population of Seattle in 2021 was 3,461,000. @@ -354,4 +352,4 @@ Therefore, the population increase of Seattle from 2021 to 2023 is 58,000.""" } ] } -``` \ No newline at end of file +``` diff --git a/_ml-commons-plugin/agents-tools/agents/ag-ui.md b/_ml-commons-plugin/agents-tools/agents/ag-ui.md new file mode 100644 index 00000000..8d722ff7 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/agents/ag-ui.md @@ -0,0 +1,351 @@ +--- +layout: default +title: AG-UI agents +has_children: false +has_toc: false +nav_order: 50 +parent: Agents +grand_parent: Agents and tools +--- + +# AG-UI agents +**Introduced 3.5** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +An Agent-User Interaction (AG-UI) agent follows the [AG-UI protocol](https://docs.ag-ui.com/introduction) for integrating AI agents with frontend applications. This implementation brings real-time AI agent capabilities directly into user interfaces with standardized streaming interactions and sophisticated tool execution. + +Similar to a [conversational agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/), an AG-UI agent is configured with a large language model (LLM) and optional tools. When processing user input, the agent uses the LLM to reason about the request, considering both the conversation history and available frontend context. The agent then determines the tools to use and executes them to provide an appropriate response. + +AG-UI agents can use two types of tools: +- **Backend tools**: Registered with the agent (like `ListIndexTool` or `SearchIndexTool`) and query OpenSearch data and perform server-side operations. +- **Frontend tools**: Provided in each request and allow the agent to interact with the UI, such as refreshing dashboards, applying filters, or navigating between pages. + +## Prerequisites + +Before using AG-UI agents, you must enable the feature by updating your cluster settings. The `ag_ui_enabled` and `stream_enabled` settings are required, while `mcp_connector_enabled` (to connect to Model Context Protocol [MCP] servers) and `unified_agent_api_enabled` are optional but recommended: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.ag_ui_enabled": true, + "plugins.ml_commons.stream_enabled": true, + "plugins.ml_commons.mcp_connector_enabled": true, + "plugins.ml_commons.unified_agent_api_enabled": true + } +} +``` +{% include copy-curl.html %} + +## Creating an AG-UI agent + +AG-UI agents use the unified registration method to streamline agent creation into a single API call. To register an AG-UI agent, set the `type` field to `AG_UI` and configure your model using the Unified Agent API. + +For complete registration instructions, field definitions, and examples for all supported model providers (Amazon Bedrock, Google Gemini, OpenAI), see [Unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#unified-agent-registration). + +<!-- vale off --> +### Example request: Amazon Bedrock Converse +<!-- vale on --> + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<AWS ACCESS KEY>", + "secret_key": "<AWS SECRET KEY>", + "session_token": "<AWS SESSION TOKEN>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 5, + "mcp_connectors": [{ + "mcp_connector_id": "<MCP CONNECTOR ID>" + }] + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +### Example request: OpenAI Chat Completion +<!-- vale on --> + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "openai/v1/chat/completions", + "credential": { + "openai_api_key": "<OPENAI API KEY>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 50, + "mcp_connectors": [{ + "mcp_connector_id": "<MCP CONNECTOR ID>" + }] + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +## Execute agent stream + +AG-UI agents use a specialized execution protocol designed for frontend applications. Unlike regular agent execution (the [Execute Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/)) that uses the `input` field, AG-UI agents use the AG-UI protocol format with frontend context, tools, and streaming responses. + +### AG-UI protocol format + +AG-UI execution follows the [AG-UI protocol](https://docs.ag-ui.com/introduction) specification, providing structured communication between frontend applications and AI agents. The protocol includes conversation threading, frontend tool integration, and real-time streaming responses. + +For more information about the input format specification, see [RunAgentInput](https://docs.ag-ui.com/sdk/js/core/types#runagentinput) in the AG-UI documentation. + +### Request fields + +The following table lists the request fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `threadId` | String | Required | Unique identifier for the conversation thread, generated by the frontend. Used to maintain conversation continuity across multiple requests and enable conversation memory. | +| `runId` | String | Required | Unique identifier for this specific execution within the thread, generated by the frontend. Each new request should have a new `runId`. | +| `state` | Object | Required | Current internal state of the agent session. Can store workflow state, user preferences, or session-specific data that persists across tool calls within the same run. | +| `messages` | Array | Required | Array of conversation messages including both user input and previous assistant responses. Each message has an `id`, `role` (user/assistant), and `content`. | +| `tools` | Array | Required | Array of frontend-specific tools the agent can call to interact with the UI. Each tool includes a `name`, `description`, and `parameters` schema defining how the agent can invoke UI actions. | +| `context` | Array | Required | Array of context objects providing current application state to the agent. Includes information like active dashboard, applied filters, time ranges, or any relevant UI context that helps the agent understand the user's current situation. | +| `forwardedProps` | Object | Required | Additional properties forwarded from the frontend application, such as user authentication details, permissions, application configuration, or other metadata needed for agent operations. | + +#### Example request + +The following example shows how to execute an AG-UI agent using the AG-UI protocol format with frontend tools, conversation context, and application state: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "threadId": "thread-xxxxx", + "runId": "run-xxxxx", + "messages": [ + { + "id": "msg-xxxxx", + "role": "user", + "content": "hello" + } + ], + "tools": [ + { + "name": "frontend_tool_example", + "description": "This is a frontend tool", + "parameters": { + ... + } + } + ], + "context": [ + { + "description": "Page context example", + "value": "{\"appId\":\"example\",\"timeRange\":{\"from\":\"now-15m\",\"to\":\"now\"},\"query\":{\"query\":\"example\",\"language\":\"PPL\"}}" + } + ], + "state": {}, + "forwardedProps": {} +} +``` +{% include copy-curl.html %} + +### Example response + +AG-UI agents return Server-Sent Events (SSEs) that allow frontends to provide real-time feedback as the agent processes the request: + +```json +data: {"type":"RUN_STARTED","timestamp":1234567890,"threadId":"thread-xxxxx","runId":"run-xxxxx"} + +data: {"type":"TEXT_MESSAGE_START","timestamp":1234567890,"messageId":"msg-xxxxx","role":"assistant"} + +data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1234567890,"messageId":"msg-xxxxx","delta":"Response text here"} + +data: {"type":"TEXT_MESSAGE_END","timestamp":1234567890,"messageId":"msg-xxxxx"} + +data: {"type":"TOOL_CALL_START","timestamp":1234567890,"toolCallId":"tool-xxxxx","toolCallName":"frontend_tool_example"} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1234567890,"toolCallId":"tool-xxxxx","delta":"{\"param\":\"value\"}"} + +data: {"type":"TOOL_CALL_END","timestamp":1234567890,"toolCallId":"tool-xxxxx"} + +data: {"type":"RUN_FINISHED","timestamp":1234567890,"threadId":"thread-xxxxx","runId":"run-xxxxx"} +``` + +### Response fields + +Each SSE contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `type` | String | The event type. | +| `timestamp` | Long | The Unix timestamp, in milliseconds, when the event was generated. | +| `threadId` | String | The conversation thread ID from the request. | +| `runId` | String | The run ID from the request. | +| `messageId` | String | The unique identifier for the message (present in message events). | +| `role` | String | The role of the message sender, typically "assistant" (present in message start events). | +| `delta` | String | Incremental content for streaming text or tool arguments (present in content/args events). | +| `toolCallId` | String | The unique identifier for the tool call (present in tool call events). | +| `toolCallName` | String | The name of the tool being called (present in tool call start events). | + +### Event types + +AG-UI agents return SSEs with the following event types in the `type` field. + +| Event type | Description | +| :--- | :--- | +| `RUN_STARTED` | Indicates the beginning of a run | +| `TEXT_MESSAGE_START` | Marks the start of an assistant message | +| `TEXT_MESSAGE_CONTENT` | Contains incremental text content (streaming) | +| `TEXT_MESSAGE_END` | Marks the end of an assistant message | +| `TOOL_CALL_START` | Indicates the beginning of a tool call | +| `TOOL_CALL_ARGS` | Contains incremental tool call arguments | +| `TOOL_CALL_END` | Marks the end of a tool call | +| `RUN_FINISHED` | Indicates the completion of a run | + +## Tracking token usage +**Introduced 3.6** +{: .label .label-purple } + +AG-UI agents support token usage tracking, which provides detailed metrics about token consumption for each LLM call during agent execution. Token usage is delivered as part of the streaming event sequence. + +For AG-UI agents, token usage tracking is enabled during agent registration by setting `"include_token_usage": true` in the `parameters` field. This applies to both the unified registration method (new interface) and the regular registration method (old interface). Once the agent is registered, this setting cannot be changed during agent execution, it must be set at registration time. + +### Enabling token usage tracking during registration (unified method) + +To enable token usage tracking for an AG-UI agent using the unified registration method, include the `include_token_usage` parameter in the `parameters` field during registration: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<AWS ACCESS KEY>", + "secret_key": "<AWS SECRET KEY>", + "session_token": "<AWS SESSION TOKEN>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 5, + "include_token_usage": true + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +### Enabling token usage tracking during registration (regular method) + +Alternatively, you can enable token usage tracking using the regular registration method by including `include_token_usage` in the agent's `parameters`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "llm": { + "model_id": "<MODEL_ID>", + "parameters": { + "max_iteration": 5 + } + }, + "tools": [{ + "type": "ListIndexTool" + }], + "parameters": { + "include_token_usage": true + }, + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +### Token usage in streaming responses + +When token usage tracking is enabled, the streaming response includes a `Custom` event with token usage metrics after the `RUN_FINISHED` event. The metrics include per-turn and per-model token consumption: + +```json +data: {"type":"RUN_STARTED","timestamp":1775501029508,"threadId":"thread-agui-new-agmem-postman","runId":"run-postman-agui-new-am"} + +data: {"type":"TOOL_CALL_START","timestamp":1775501031547,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","toolCallName":"ListIndexTool"} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1775501031549,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","delta":""} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1775501031814,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","delta":"{\"indi"} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1775501031814,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","delta":"ces\": []}"} + +data: {"type":"TOOL_CALL_END","timestamp":1775501031893,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w"} + +data: {"type":"TOOL_CALL_RESULT","timestamp":1775501031911,"messageId":"msg_66642762007875","toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","content":"..."} + +data: {"type":"TEXT_MESSAGE_START","timestamp":1775501033817,"messageId":"msg_66644668213500","role":"assistant"} + +data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1775501033818,"messageId":"msg_66644668213500","delta":"Here are all the indices..."} + +data: {"type":"TEXT_MESSAGE_END","timestamp":1775501041102,"messageId":"msg_66644668213500"} + +data: {"type":"Custom","timestamp":1775501041115,"name":"token_usage","value":{"per_turn_usage":[{"model_name":"Auto-generated model for us.anthropic.claude-sonnet-4-5-20250929-v1:0","model_url":"https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse","total_tokens":4806.0,"output_tokens":54.0,"turn":1.0,"model_id":"9RIbZJ0B1Feno22Ak-7G","input_tokens":4752.0},{"model_name":"Auto-generated model for us.anthropic.claude-sonnet-4-5-20250929-v1:0","model_url":"https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse","total_tokens":6262.0,"output_tokens":898.0,"turn":2.0,"model_id":"9RIbZJ0B1Feno22Ak-7G","input_tokens":5364.0}],"per_model_usage":[{"model_name":"Auto-generated model for us.anthropic.claude-sonnet-4-5-20250929-v1:0","model_url":"https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse","call_count":2.0,"total_tokens":11068.0,"output_tokens":952.0,"model_id":"9RIbZJ0B1Feno22Ak-7G","input_tokens":10116.0}]}} + +data: {"type":"RUN_FINISHED","timestamp":1775501041116,"threadId":"thread-agui-new-agmem-postman","runId":"run-postman-agui-new-am"} +``` + +The `token_usage` event contains: +- **`per_turn_usage`**: Token metrics for each individual turn during the agent execution, including `turn` number, `model_id`, `model_name`, `model_url`, `input_tokens`, `output_tokens`, and `total_tokens`. +- **`per_model_usage`**: Aggregated token metrics grouped by model, including `model_id`, `model_name`, `model_url`, `call_count`, `input_tokens`, `output_tokens`, and `total_tokens`. + +For detailed information about token usage fields and how tokens are calculated by different model providers, see [Tracking token usage]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#tracking-token-usage) in the Execute Agent API documentation. + +## Next steps + +- For AG-UI agent registration, see [Unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method). +- For unified agent execution, see [Unified agent execution]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#unified-agent-execution). +- Learn about the [AG-UI protocol specification](https://docs.ag-ui.com/introduction). +- Explore available backend [tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/) for your agents. +- Review [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/) for additional functionality. diff --git a/_ml-commons-plugin/agents-tools/agents/conversational-flow.md b/_ml-commons-plugin/agents-tools/agents/conversational-flow.md new file mode 100644 index 00000000..33b8f2b4 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/agents/conversational-flow.md @@ -0,0 +1,79 @@ +--- +layout: default +title: Conversational flow agents +has_children: false +has_toc: false +nav_order: 20 +parent: Agents +grand_parent: Agents and tools +--- + +# Conversational flow agents +**Introduced 2.13** +{: .label .label-purple } + +Similarly to a [flow agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/flow/), a conversational flow agent is configured with a set of tools that it runs in order. The difference between them is that a conversational flow agent stores the conversation in an index, in the following example, the `conversation_index`. The following agent runs the `VectorDBTool` and then the `MLModelTool`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "population data analysis agent", + "type": "conversational_flow", + "description": "This is a demo agent for population data analysis", + "app_type": "rag", + "memory": { + "type": "conversation_index" + }, + "tools": [ + { + "type": "VectorDBTool", + "name": "population_knowledge_base", + "parameters": { + "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", + "index": "test_population_data", + "embedding_field": "population_description_embedding", + "source_field": [ + "population_description" + ], + "input": "${parameters.question}" + } + }, + { + "type": "MLModelTool", + "name": "bedrock_claude_model", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "YOUR_LLM_MODEL_ID", + "prompt": """You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. + +Context: +${parameters.population_knowledge_base.output:-} + +${parameters.chat_history:-} + +Question: ${parameters.question}""" + } + } + ] +} +``` +{% include copy-curl.html %} + +For more information about the Register Agent API request fields, see [Request body fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#request-body-fields). + +For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). + +## Using external MCP tools +**Introduced 3.8** +{: .label .label-purple } + +Conversational flow agents can call external MCP server tools in a fixed pipeline alongside OpenSearch tools such as `MLModelTool`. Configure `parameters.mcp_connectors` and declare each MCP tool explicitly in the `tools` array using `McpStreamableHttpTool` or `McpSseTool`. For setup steps and examples, see [Using MCP tools with flow agents and conversational flow agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/#flow-agents-and-conversational-flow-agents). + +## Next steps + +- To learn more about registering agents, see [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +- For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +- For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). +- For supported APIs, see [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/). +- To create agents and tools using a workflow template, see [AI search workflows]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/index/). +- For a tutorial that uses a conversational flow agent to build a RAG chatbot, see [RAG chatbot with a conversational flow agent]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/chatbots/rag-conversational-agent/). diff --git a/_ml-commons-plugin/agents-tools/agents/conversational.md b/_ml-commons-plugin/agents-tools/agents/conversational.md new file mode 100644 index 00000000..ad263c16 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/agents/conversational.md @@ -0,0 +1,298 @@ +--- +layout: default +title: Conversational agents +has_children: false +has_toc: false +nav_order: 30 +parent: Agents +grand_parent: Agents and tools +--- + +# Conversational agents +**Introduced 2.13** +{: .label .label-purple } + +A conversational agent uses a large language model (LLM) and a set of supplementary tools to reason iteratively and provide a response. The agent selects the best tool for each question using the Chain-of-Thought (CoT) process and stores conversation history so that users can ask follow-up questions. Conversational agents use [function calling]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#request-body-fields) to invoke tools. + +OpenSearch provides two types of conversational agents: + +- **[The `conversational_v2` agent](#the-conversational_v2-agent-with-full-multimodal-support)** (OpenSearch 3.6 and later): An enhanced agent with built-in multimodal support through a standardized interface. Requires the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method) and [agentic memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/). + +- **[The `conversational` agent (v1)](#the-conversational-agent-v1)** (OpenSearch 2.13 and later): Supports both the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method) (plain text input only) and the [regular registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#regular-registration-method) (connector-dependent capabilities). Supports both `conversation_index` and `agentic_memory` memory types. + +## The `conversational_v2` agent with full multimodal support +**Introduced 3.6** +{: .label .label-purple } + +A `conversational_v2` agent extends the `conversational` agent by providing built-in multimodal support through the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method), without requiring custom connector configuration. Unlike `conversational` agents, which accept only plain text input when using the unified registration method, the `conversational_v2` agents support the following input formats: + +- **Plain text**: A simple string input. +- **Content blocks**: Multimodal arrays containing text, images, and documents. +- **Messages**: Full conversation history with roles and multimodal content blocks for multi-turn interactions. + +The agent returns a response that includes the stop reason, the assistant's message, the memory session ID, and token usage metrics. The `conversational_v2` agents require the `agentic_memory` memory type. + +### Prerequisites + +The `conversational_v2` agent uses the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method) and requires the unified agent API to be enabled. For setup instructions, see [Prerequisites]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#prerequisites). + +### Registering a `conversational_v2` agent + +To register a `conversational_v2` agent, follow these steps. + +**Step 1: Create a memory container** + +Before registering a `conversational_v2` agent, create a memory container using the [Create Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/): + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "my-agent-memory" +} +``` +{% include copy-curl.html %} + +This creates a memory container with default settings. Depending on your use case, you may want to configure additional options such as `disable_session`, `embedding_model_id`, or memory strategies. For all available options, see [Create Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/). + +The response returns a `memory_container_id` that you use when registering the agent: + +```json +{ + "memory_container_id": "SdjmmpgBOh0h20Y9kWuN", + "status": "created" +} +``` + +**Step 2: Register the agent** + +To register the agent, send the following request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Conversational Agent V2", + "type": "conversational_v2", + "description": "A multimodal conversational agent", + "model": { + "model_id": "us.anthropic.claude-sonnet-4-6", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<YOUR_AWS_ACCESS_KEY>", + "secret_key": "<YOUR_AWS_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + } + }, + "memory": { + "type": "agentic_memory", + "memory_container_id": "<YOUR_MEMORY_CONTAINER_ID>" + }, + "tools": [ + { + "type": "ListIndexTool" + } + ] +} +``` +{% include copy-curl.html %} + +### Executing a `conversational_v2` agent + +The `conversational_v2` agents use the `input` field and support the following input formats: + +- **Plain text input**: + + ```json + POST /_plugins/_ml/agents/{agent_id}/_execute + { + "input": "What indexes are in my cluster?" + } + ``` + {% include copy-curl.html %} + +- **Multimodal content block input**: + + ```json + POST /_plugins/_ml/agents/{agent_id}/_execute + { + "input": [ + { + "type": "text", + "text": "What can you see in this image?" + }, + { + "type": "image", + "source": { + "type": "base64", + "format": "png", + "data": "iVBORw0KGgoAAAANSUhEUgAA..." + } + } + ] + } + ``` + {% include copy-curl.html %} + +- **Message input** (multi-turn conversation history): + + ```json + POST /_plugins/_ml/agents/{agent_id}/_execute + { + "input": [ + { + "role": "user", + "content": [{"type": "text", "text": "I like the color red"}] + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "Thanks for sharing that!"}] + }, + { + "role": "user", + "content": [{"type": "text", "text": "What color do I like?"}] + } + ] + } + ``` + {% include copy-curl.html %} + +### The `conversational_v2` agent response format + +The `conversational_v2` agent returns a standardized response format: + +```json +{ + "stop_reason": "end_turn", + "message": { + "role": "assistant", + "content": [ + { + "text": "Based on your cluster, I found the following indexes..." + } + ] + }, + "memory_id": "test_memory_id", + "metrics": { + "total_usage": { + "inputTokens": 1234, + "outputTokens": 567, + "totalTokens": 1801 + } + } +} +``` + +For the `conversational_v2` agent response fields, see [The `conversational_v2` agent response format]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#the-conversational_v2-agent-response-format). + +### Limitations + +The following limitations apply to the `conversational_v2` agent: + +- **Memory type**: Only `agentic_memory` is supported. The `conversation_index` memory type is not compatible with `conversational_v2` agents. +- **Streaming**: Streaming responses are not supported. +- **Hooks and context management**: Agent execution hooks and context management are not supported. + +## The `conversational` agent (v1) + +The `conversational` agent supports two registration methods, each with different capabilities: + +- **[Unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method)**: Accepts only plain text input. Uses the `model` field for LLM configuration. +- **[Regular registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#regular-registration-method)**: Input capabilities depend on connector configuration. Uses the `llm` field for LLM configuration. Multimodal input is supported if you configure the connector to pass multimodal content to the LLM. + +For full multimodal support through a standardized interface, use the [`conversational_v2` agent](#the-conversational_v2-agent-with-full-multimodal-support). +{: .note} + +A `conversational` agent can be configured with a large language model (LLM) and a set of supplementary tools that perform specific jobs. For example, you can set up an LLM and a `ListIndexTool`. When you send a question to the model, the agent includes the `ListIndexTool` as context. The LLM then decides whether it needs to use the tool to answer questions like "How many indexes are in my cluster?" This allows the LLM to answer questions outside of its knowledge base. + +### Using the unified registration method + +The following example registers a `conversational` agent using the unified registration method: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Conversational Agent", + "type": "conversational", + "description": "A conversational agent using unified registration", + "model": { + "model_id": "us.anthropic.claude-sonnet-4-6", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<YOUR_AWS_ACCESS_KEY>", + "secret_key": "<YOUR_AWS_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + } + }, + "memory": { + "type": "conversation_index" + }, + "tools": [ + { + "type": "ListIndexTool" + } + ] +} +``` +{% include copy-curl.html %} + +### Using the regular registration method + +The following example registers a `conversational` agent using the regular registration method: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_ReAct_Claude", + "type": "conversational", + "description": "This is a test agent", + "llm": { + "model_id": "YOUR_LLM_MODEL_ID", + "parameters": { + "max_iteration": 5, + "stop_when_no_tool_found": true, + "response_filter": "$.content[0].text" + } + }, + "memory": { + "type": "conversation_index" + }, + "tools": [ + { + "type": "VectorDBTool", + "name": "VectorDBTool", + "description": "A tool to search OpenSearch index with natural language question. If you don't know answer for some question, you should always try to search data with this tool. Action Input: <natural language question>", + "parameters": { + "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", + "index": "my_test_data", + "embedding_field": "embedding", + "source_field": [ "text" ], + "input": "${parameters.question}" + } + }, + { + "type": "ListIndexTool", + "name": "ListIndexTool", + "description": "Use this tool to get OpenSearch index information: (health, status, index, uuid, primary count, replica count, docs.count, docs.deleted, store.size, primary.store.size)." + } + ], + "app_type": "my app" +} +``` +{% include copy-curl.html %} + +## Tracking token usage +**Introduced 3.6** +{: .label .label-purple } + +Conversational agents support token usage tracking, which provides detailed metrics about token consumption for each LLM call during agent execution. This helps you monitor costs, debug performance, and compare model efficiency. + +To enable token usage tracking, set the `include_token_usage` parameter to `true` when executing the agent. The response will include a `token_usage` output with per-turn and per-model aggregated metrics. For detailed information about token usage fields and how tokens are calculated by different model providers, see [Tracking token usage]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#tracking-token-usage) in the Execute Agent API documentation. + +## Next steps + +- To learn more about registering agents, see [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +- For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +- For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). +- For supported APIs, see [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/). +- To create agents and tools using a workflow template, see [AI search workflows]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/index/). +- For a tutorial that uses a conversational agent to build a RAG chatbot, see [RAG chatbot]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/chatbots/rag-chatbot/). +- For a tutorial that uses conversational agents to build a chatbot for OpenSearch Dashboards, see [Build your own chatbot]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/chatbots/build-chatbot/). diff --git a/_ml-commons-plugin/agents-tools/agents/flow.md b/_ml-commons-plugin/agents-tools/agents/flow.md new file mode 100644 index 00000000..0e9da8f3 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/agents/flow.md @@ -0,0 +1,63 @@ +--- +layout: default +title: Flow agents +has_children: false +has_toc: false +nav_order: 10 +parent: Agents +grand_parent: Agents and tools +--- + +# Flow agents +**Introduced 2.13** +{: .label .label-purple } + +A flow agent is configured with a set of tools that it runs in order. For example, the following agent runs the `VectorDBTool` and then the `MLModelTool`. The agent coordinates the tools so that one tool's output can become another tool's input. In this example, the `VectorDBTool` queries the k-NN index, and the agent passes its output `${parameters.VectorDBTool.output}` to the `MLModelTool` as context along with the `${parameters.question}` (see the `prompt` parameter): + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_RAG", + "type": "flow", + "description": "this is a test agent", + "tools": [ + { + "type": "VectorDBTool", + "parameters": { + "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", + "index": "my_test_data", + "embedding_field": "embedding", + "source_field": ["text"], + "input": "${parameters.question}" + } + }, + { + "type": "MLModelTool", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "YOUR_LLM_MODEL_ID", + "prompt": "You are a professional data analyst. You will always answer a question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say you don't know. \n\nContext:\n${parameters.VectorDBTool.output}\n\nQuestion: ${parameters.question}" + } + } + ] +} +``` +{% include copy-curl.html %} + +For more information about the Register Agent API request fields, see [Request body fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#request-body-fields). + +For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). + +## Using external MCP tools +**Introduced 3.8** +{: .label .label-purple } + +Flow agents can call external MCP server tools in a fixed pipeline alongside OpenSearch tools such as `MLModelTool`. Configure `parameters.mcp_connectors` and declare each MCP tool explicitly in the `tools` array using `McpStreamableHttpTool` or `McpSseTool`. For setup steps and examples, see [Using MCP tools with flow agents and conversational flow agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/#flow-agents-and-conversational-flow-agents). + +## Next steps + +- To learn more about registering agents, see [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +- For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +- For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). +- For supported APIs, see [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/). +- To create agents and tools using a workflow template, see [AI search workflows]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/index/). \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/agents/index.md b/_ml-commons-plugin/agents-tools/agents/index.md new file mode 100644 index 00000000..00ccb779 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/agents/index.md @@ -0,0 +1,201 @@ +--- +layout: default +title: Agents +parent: Agents and tools +has_children: true +has_toc: false +nav_order: 10 +redirect_from: + - /ml-commons-plugin/agents-tools/agents/ +--- + +# Agents +**Introduced 2.13** +{: .label .label-purple } + +An _agent_ is a coordinator that uses a large language model (LLM) to solve a problem. After the LLM reasons and decides what action to take, the agent coordinates the action execution. OpenSearch supports the following agent types: + +- [_Flow agent_]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/flow/): Runs tools sequentially, in the order specified in its configuration. The workflow of a flow agent is fixed. Useful for retrieval-augmented generation (RAG). +- [_Conversational flow agent_]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational-flow/): Runs tools sequentially, in the order specified in its configuration. The workflow of a conversational flow agent is fixed. Stores conversation history so that users can ask follow-up questions. Useful for creating a chatbot. +- [_Conversational agent_]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/): Reasons in order to provide a response based on the available knowledge, including the LLM knowledge base and a set of tools provided to the LLM. The LLM reasons iteratively to decide what action to take until it obtains the final answer or reaches the iteration limit. Stores conversation history so that users can ask follow-up questions. The workflow of a conversational agent is variable, based on follow-up questions. For specific questions, uses the Chain-of-Thought (CoT) process to select the best tool from the configured tools for providing a response to the question. Useful for creating a chatbot that employs RAG. +- [_Conversational agent V2_]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/#the-conversational_v2-agent-with-full-multimodal-support): An enhanced version of the conversational agent with built-in multimodal support out of the box, requiring minimal configuration. Accepts text, images, documents, and multi-turn message history as input using a standardized interface, without requiring custom connector setup. Returns a standardized output format along with token usage metrics. Requires the [unified registration method](#unified-registration-method) and [Agentic Memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/). +- [_Plan-execute-reflect agent_]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/plan-execute-reflect/): Dynamically plans, executes, and refines multi-step workflows to solve complex tasks. Internally, a plan-execute-reflect agent uses a conversational agent to execute each individual step in the plan. The agent automatically selects the most appropriate tool for each step based on tool descriptions and context. Ideal for long-running, exploratory processes that benefit from iterative reasoning and adaptive execution. Useful for conducting research or performing root cause analysis (RCA). +- [_AG-UI agent_]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/ag-ui/): Follows the AG-UI protocol for integrating AI agents with frontend applications. Enables seamless communication between OpenSearch and UIs by accepting frontend context and tools, allowing the agent to interact directly with UI components and application state. Useful for interactive dashboards. + +## Creating agents + +You can create agents using two registration methods: the regular registration method or the unified registration method. + +### Regular registration method + +The regular registration method uses the [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/) and requires multiple steps to create an agent: + +1. **Register a connector**: Create a connector with a complex JSON configuration including a `request_body` and `url` parameters. +2. **Register a model**: Create a model that manually references the `connector_id` from Step 1. +3. **Register an agent**: Create the agent by providing the `model_id`, configuring the `_llm_interface` parameter, and mapping `question` to `prompt`. +4. **Execute the agent**: Execute the agent with a limited text-based `question` parameter only. + +### Unified registration method +**Introduced 3.5** +{: .label .label-purple } + +The Unified Agent API streamlines agent creation and execution by automating connector and model setup, significantly reducing the complexity of working with agents in OpenSearch. The Unified Agent API registers an agent in a single API call by automatically handling model group creation, connector configuration, and model registration based on the `model` block configuration: + +1. **Register an agent** (connector and model are created automatically). +2. **Execute the agent** using the `input` field. + +The unified registration method differs from the regular registration method in the following ways. + +| Aspect | Regular registration method | Unified registration method | +| :--- | :--- | :--- | +| **Workflow steps** | 1. Register connector<br>2. Register model<br>3. Register agent<br>4. Execute with `question` parameter | 1. Register agent (automatic connector/model creation)<br>2. Execute with flexible `input` field | +| **Configuration complexity** | Manual connector configuration with request bodies, URLs, and parameter mappings | Automatic configuration with built-in validation and defaults | +| **Model setup** | Requires separate model registration before agent creation | Creates model resources automatically during agent registration | +| **Model reference** | Uses `llm.model_id` to reference preregistered models | Uses `model` block with provider credentials and configuration | +| **LLM interface** | Manual `_llm_interface` parameter configuration | Automatic `_llm_interface` detection from `model_provider` | +| **Input capabilities** | Limited to text-based `question` parameter | Supports multimodal inputs (text, images, messages) through enhanced execution API | + +#### Supported models + +The following models are supported: + +- **Amazon Bedrock Converse API** with Anthropic Claude models +- **Google Gemini** models +- **OpenAI** models + +#### Prerequisites + +The Unified Agent API is enabled by default. If the API was disabled, enable it by updating the following cluster setting: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.unified_agent_api_enabled": true + } +} +``` +{% include copy-curl.html %} + +If you plan to use Model Context Protocol (MCP) connectors with your unified agents, also enable MCP connector support: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.mcp_connector_enabled": true + } +} +``` +{% include copy-curl.html %} + +#### Example + +The following example demonstrates the unified registration method. + +**Step 1: Register an agent** + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Conversational Agent", + "type": "conversational", + "description": "A conversational agent using OpenAI gpt-4o-mini", + "model": { + "model_id": "gpt-4o-mini", + "model_provider": "openai/v1/chat/completions", + "credential": { + "openai_api_key": "sk-your-api-key" + }, + "model_parameters": { + "max_tokens": 1000, + "temperature": 0.7 + } + } +} +``` +{% include copy-curl.html %} + +For complete registration details, field definitions, and examples for all model providers, see [Unified agent registration]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#unified-agent-registration). + +**Step 2: Execute the agent** + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "input": "What tools do you have access to?" +} +``` +{% include copy-curl.html %} + +For execution details and input format specifications, see [Unified agent execution]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#unified-agent-execution). + +#### Limitations + +The following limitations apply to the unified registration method: + +- **Agent types**: Only `conversational`, `conversational_v2`, `plan_execute_and_reflect`, and `AG_UI` agents are supported. +- **Multimodal input**: When using the unified registration method, content block and message-based input formats require `conversational_v2` agents. All other unified agent types, including `conversational` agents using either `conversation_index` or `agentic_memory`, accept only plain text input. When using the regular registration method, multimodal support is possible if the connector is configured to pass multimodal content to the LLM, with the input format determined by the connector configuration. + +The Unified Agent API is fully backward compatible with existing agents. Agents created using the regular registration method continue to function normally. You can use both registration methods in the same cluster. + +Agents created using the Unified Agent API cannot be updated to use the regular registration method parameters. +{: .note} + +## Hidden agents +**Introduced 2.13** +{: .label .label-purple } + +To hide agent details from end users, including the cluster admin, you can register a _hidden_ agent. If an agent is hidden, non-superadmin users don't have permission to call any [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/index/), except for the [Execute API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/), on the agent. + +Only superadmin users can register a hidden agent. To register a hidden agent, you first need to authenticate with an [admin certificate]({{site.url}}{{site.baseurl}}/security/configuration/tls/#configuring-admin-certificates): + +```bash +curl -k --cert ./kirk.pem --key ./kirk-key.pem -XGET 'https://localhost:9200/.opendistro_security/_search' +``` +{% include copy.html %} + +All agents created by a superadmin user are automatically registered as hidden. Only the superadmin user can view hidden agent details and delete hidden agents. +To register a hidden agent, send a request to the `_register` endpoint: + +```bash +curl -k --cert ./kirk.pem --key ./kirk-key.pem -X POST 'https://localhost:9200/_plugins/_ml/agents/_register' -H 'Content-Type: application/json' -d ' +{ + "name": "Test_Agent_For_RAG", + "type": "flow", + "description": "this is a test agent", + "tools": [ + { + "name": "vector_tool", + "type": "VectorDBTool", + "parameters": { + "model_id": "zBRyYIsBls05QaITo5ex", + "index": "my_test_data", + "embedding_field": "embedding", + "source_field": [ + "text" + ], + "input": "${parameters.question}" + } + }, + { + "type": "MLModelTool", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "NWR9YIsBUysqmzBdifVJ", + "prompt": "You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\nContext:\n${parameters.vector_tool.output}\n\nQuestion: ${parameters.question}" + } + } + ] +}' +``` +{% include copy.html %} + +## Next steps + +- To learn more about registering agents, see [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +- For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +- For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). +- For a step-by-step tutorial on using a plan-execute-reflect agent, see [Building a plan-execute-reflect agent]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/). +- For supported APIs, see [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/). +- To create agents and tools using a workflow template, see [AI search workflows]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/index/). diff --git a/_ml-commons-plugin/agents-tools/agents/plan-execute-reflect.md b/_ml-commons-plugin/agents-tools/agents/plan-execute-reflect.md new file mode 100644 index 00000000..63d0df58 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/agents/plan-execute-reflect.md @@ -0,0 +1,483 @@ +--- +layout: default +title: Plan-execute-reflect agents +has_children: false +has_toc: false +nav_order: 40 +parent: Agents +grand_parent: Agents and tools +--- + +# Plan-execute-reflect agents +**Introduced 3.0** +{: .label .label-purple } + +Plan-execute-reflect agents are designed to solve complex tasks that require iterative reasoning and step-by-step execution. These agents use one large language model (LLM)---the _planner_---to create and update a plan and another LLM (or the same one by default) to execute each individual step using a built-in conversational agent. + +A plan-execute-reflect agent works in three phases: + +- **Planning** – The planner LLM generates an initial step-by-step plan using the available tools. +- **Execution** – Each step is executed sequentially using the conversational agent and the available tools. +- **Re-evaluation** – After executing each step, the planner LLM re-evaluates the plan using intermediate results. The LLM can adjust the plan dynamically to skip, add, or change steps based on new context. + +Similarly to a conversational agent, the plan-execute-reflect agent stores the interaction between the LLM and the agent in a memory index. In the following example, the agent uses a `conversation_index` to persist the execution history, including the user's question, intermediate results, and final outputs. + +The agent automatically selects the most appropriate tool for each step based on the tool descriptions and current context. + +The agent supports re-evaluation only after each step. This allows the agent to dynamically adapt the plan based on intermediate results before proceeding to the next step. + +## Creating a plan-execute-reflect agent + +The following example request creates a plan-execute-reflect agent with three tools: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Plan Execute Reflect Agent", + "type": "plan_execute_and_reflect", + "description": "Agent for dynamic task planning and reasoning", + "llm": { + "model_id": "YOUR_LLM_MODEL_ID", + "parameters": { + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "YOUR_LLM_INTERFACE" + }, + "tools": [ + { "type": "ListIndexTool" }, + { "type": "SearchIndexTool" }, + { "type": "IndexMappingTool" } + ], + "app_type": "os_chat" +} +``` +{% include copy-curl.html %} + +It is important to provide thorough descriptions of the tools so that the LLM can decide in which situations to use those tools. +{: .tip} + +For more information about the Register Agent API request fields, see [Request body fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#request-body-fields). + +## Supported LLMs + +The plan-execute-reflect agent provides built-in function calling interfaces for the following LLMs: + +- [Anthropic Claude Sonnet 4.6 model hosted on Amazon Bedrock](https://aws.amazon.com/bedrock/claude/) +- OpenAI GPT-4o model +- DeepSeek-R1 model hosted on Amazon Bedrock + +To request default support for an LLM, [create a feature request issue in the ML Commons repository](https://github.com/opensearch-project/ml-commons/issues). + +For a step-by-step tutorial on using a plan-execute-reflect agent, see [Building a plan-execute-reflect agent]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/). + +To configure a plan-execute-reflect agent with a particular model, you need to modify the connector in [Step 1(a): Create a connector]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/#step-1a-create-a-connector) and provide a model-specific `llm_interface` parameter in [Step 2: Create an agent]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/#step-2-create-an-agent): + +```json +"parameters": { + "_llm_interface": "bedrock/converse/claude" +} +``` + +For valid values of the `_llm_interface` field, see [Request body fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/#request-body-fields). + +The following examples provide the connector and agent creation requests for the supported models. + +### Anthropic Claude on Amazon Bedrock + +To create a connector for the Anthropic Claude Sonnet 4.6 model hosted on Amazon Bedrock, use the following request: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Amazon Bedrock Claude Sonnet 4.6 connector", + "description": "Connector to Amazon Bedrock service for the Claude model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "your_aws_region", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "credential": { + "access_key": "your_aws_access_key", + "secret_key": "your_aws_secret_key", + "session_token": "your_aws_session_token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] +} +``` +{% include copy-curl.html %} + +To create a plan-execute-reflect agent with the Anthropic Claude Sonnet 4.6 model, use the following request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Plan Execute and Reflect agent with Claude Sonnet 4.6", + "type": "plan_execute_and_reflect", + "description": "this is a test agent", + "llm": { + "model_id": "your_llm_model_id", + "parameters": { + "prompt": "${parameters.question}" + }}, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "bedrock/converse/claude" + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ] +} +``` +{% include copy-curl.html %} + +### OpenAI GPT-4o + +To create a connector for an OpenAI GPT-4o model, use the following request: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My openai connector: gpt-4o-mini", + "description": "The connector to openai chat model", + "version": 1, + "protocol": "http", + "parameters": { + "model": "gpt-4o" + }, + "credential": { + "openAI_key": "your_open_ai_key" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] +} +``` +{% include copy-curl.html %} + +Then register the model and register an agent, specifying `openai/v1/chat/completions` in the `_llm_interface` field. + +### Deepseek-R1 on Amazon Bedrock + +To create a connector for a DeepSeek-R1 model hosted on Amazon Bedrock, use the following request: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My DeepSeek R1 connector", + "description": "my test connector", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "your_region", + "service_name": "bedrock", + "model": "us.deepseek.r1-v1:0" + }, + "credential": { + "access_key": "your_access_key", + "secret_key": "your_secret_key", + "session_token": "your_session_token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}] }" + } + ] +} +``` +{% include copy-curl.html %} + +Then register the model and register an agent, specifying `bedrock/converse/deepseek_r1` in the `_llm_interface` field. + +Because the Deepseek-R1 model hosted on Amazon Bedrock lacks default function-calling support, provide the following prompt as an `executor_system_prompt` during agent registration: + +```json +"You are a helpful assistant. You can ask Human to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n[${parameters._tools.toString()}]\n\nIf need to use tool, return which tool should be used and the input to user is enough. User will run the tool to get information. To make it easier for user to parse the response to know whether they should invoke a tool or not, please also return \"stop_reason\", it only return one of two enum values: [end_turn, tool_use], add a random tool call id to differenciate in case same tool invoked multiple times. Tool call id follow this pattern \"tool_use_<random string>\". The random string should be some UUID.\n\nFor example, you should return a json like this if need to use tool:\n{\"stop_reason\": \"tool_use\", \"tool_calls\": [{\"id\":\"tool_use_IIHBxMgOTjGb6ascCiOILg\",tool_name\":\"search_opensearch_index\",\"input\": {\"index\":\"population_data\",\"query\":{\"query\":{\"match\":{\"city\":\"New York City\"}}}}}]}\n\nIf don't need to use tool, return a json like this:\n{\"stop_reason\": \"end_turn\", \"message\": {\"role\":\"user\",\"content\":[{\"text\":\"What is the most popular song on WZPZ?\"}]}}\n\nNOTE: Don't wrap response in markdown ```json<response>```. For example don't return ```json\\n{\"stop_reason\": \"end_turn\", \"message\": {\"role\":\"user\",\"content\":[{\"text\":\"What is the most popular song on WZPZ?\"}]}}```\n" +``` +{% include copy.html %} + +## Tracking agent execution and memory + +When you execute a plan-execute-reflect agent asynchronously using the [Agent Execute API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/), the API returns the `memory_id` and the `parent_interaction_id` of the planner agent once the agent is started. + +In the final response, the API also returns the `executor_agent_memory_id` and `executor_agent_parent_interaction_id`, which correspond to the internal executor agent responsible for carrying out each step of the plan. The `executor_agent_memory_id` and `executor_agent_parent_interaction_id` are updated in the task as soon as they are available, even before the agent has completed execution. This enables real-time tracking of the execution process. + +For a complete example, see [Building a plan-execute-reflect agent]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/#test-the-agent). + +## Default prompts + +The plan-execute-reflect agent uses the following predefined prompts. You can customize the prompts by providing new ones in the following ways: + +- During agent registration in the `parameters` object +- Dynamically during agent execution + +### Planner template and prompt + +To create a custom planner prompt template, modify the `planner_prompt_template` parameter. The following template is used to ask the LLM to devise a plan for the given task: + +```json +${parameters.tools_prompt} \n${parameters.planner_prompt} \nObjective: ```${parameters.user_prompt}``` \n\nRemember: Respond only in JSON format following the required schema. +``` + +To create a custom planner prompt, modify the `planner_prompt` parameter. +The following prompt is used to ask the LLM to devise a plan for the given task: + +``` +For the given objective, generate a step-by-step plan composed of simple, self-contained steps. The final step should directly yield the final answer. Avoid unnecessary steps. +``` + +### Planner prompt with a history template + +To create a custom planner prompt with a history template, modify the `planner_with_history_template` parameter. The following template is used when `memory_id` is provided during agent execution to give the LLM context about the previous task:: + +```json +${parameters.tools_prompt} \n${parameters.planner_prompt} \nObjective: ```${parameters.user_prompt}``` \n\nYou have currently executed the following steps: \n[${parameters.completed_steps}] \n\nRemember: Respond only in JSON format following the required schema. +``` + +### Reflection prompt and template + +To create a custom reflection prompt template, modify the `reflect_prompt_template` parameter. The following template is used to ask the LLM to rethink the original plan based on completed steps: + +```json +${parameters.tools_prompt} \n${parameters.planner_prompt} \n\nObjective: ```${parameters.user_prompt}```\n\nPrevious plan:\n[${parameters.steps}] \n\nYou have currently executed the following steps: \n[${parameters.completed_steps}] \n\n${parameters.reflect_prompt} \n\n.Remember: Respond only in JSON format following the required schema. +``` + +To create a custom reflection prompt, modify the `reflect_prompt` parameter. +The following prompt is used to ask the LLM to rethink the original plan: + +``` +Update your plan based on the latest step results. If the task is complete, return the final answer. Otherwise, include only the remaining steps. Do not repeat previously completed steps. +``` + +### Planner system prompt + +To create a custom planner system prompt, modify the `system_prompt` parameter. The following is the planner system prompt: + +```` +# Investigation Planner Agent + +You are a thoughtful and analytical planner agent in a plan-execute-reflect framework. Your job is to design a clear, step-by-step plan for a given objective. + +# Instructions + +## Core Planning Rules +- Break the objective into an ordered list of atomic, self-contained Steps that, if executed, will lead to the final result or complete the objective +- Each Step must state what to do, where, and which tool/parameters would be used. You do not execute tools, only reference them for planning +- Use only the provided tools; do not invent or assume tools. If no suitable tool applies, use reasoning or observations instead +- Base your plan only on the data and information explicitly provided; do not rely on unstated knowledge or external facts +- If there is insufficient information to create a complete plan, summarize what is known so far and clearly state what additional information is required to proceed +- Stop and summarize if the task is complete or further progress is unlikely +- Avoid vague instructions; be specific about data sources, indexes, or parameters +- Never make assumptions or rely on implicit knowledge +- Respond only in JSON format +## Step Examples +**Good example:** "Use Tool to sample documents from index: 'my-index'" + +**Bad example:** "Use Tool to sample documents from each index" + +**Bad example:** "Use Tool to sample documents from all indices" + +# Response Format + +## JSON Response Requirements +Only respond in JSON format. Always follow the given response instructions. Do not return any content that does not follow the response instructions. Do not add anything before or after the expected JSON + +Always respond with a valid JSON object that strictly follows the below schema: +```json +{ + "steps": array[string], + "result": string +} +``` + +- Use "steps" to return an array of strings where each string is a step to complete the objective, leave it empty if you know the final result. Please wrap each step in quotes and escape any special characters within the string +- Use "result" to return the final response when you have enough information, leave it empty if you want to execute more steps. +Here are examples of valid responses following the required JSON schema: + +Example 1 - When you need to execute steps: +{ + "steps": ["This is an example step", "this is another example step"], + "result": "" +} + +Example 2 - When you have the final result: +{ + "steps": [], + "result": "This is an example result\n with escaped special characters" +} +## Critical Rules +1. Do not use commas within individual steps +2. Do not add any content before or after the JSON +3. Only respond with a pure JSON object + +When you deliver your final result, include a comprehensive report. This report must: +1. List every analysis or step you performed. +2. Summarize the inputs, methods, tools, and data used at each step. +3. Include key findings from all intermediate steps — do NOT omit them. +4. Clearly explain how the steps led to your final conclusion. Only mention the completed steps. +5. Return the full analysis and conclusion in the 'result' field, even if some of this was mentioned earlier. Ensure that special characters are escaped in the 'result' field. +6. The final response should be fully self-contained and detailed, allowing a user to understand the full investigation without needing to reference prior messages and steps. +```` + +We do not recommend modifying the response format instructions. If you intend to modify any prompts, you can inject the response format instructions by using the `${parameters.plan_execute_reflect_response_format}` parameter. +{: .tip} + +### Customizing parts of the planner system prompt + +To change parts of the planner system prompt while keeping the core planning rules and the response format, use the following parameters: + +Parameter | Data type | Description +:--- | :--- | :--- +`planner_system_prompt_prefix` | String | Replaces the beginning of the planner system prompt, which consists of the `# Investigation Planner Agent` heading and the paragraph that follows it. Default is that heading and paragraph. +`result_expand_and_override` | String | Text appended to the instruction for the `result` field in the response format. When this parameter is set, the prompt omits the example responses (the text starting with `Here are examples of valid responses`). Default is empty. +`important_rules_expand` | String | Text appended to the `## Critical Rules` list in the response format, for example, an additional numbered rule. Default is empty. + +When you set any of these parameters, the agent builds the planner system prompt from the prefix, the core planning rules, and the response format, using the defaults for any of the three parameters that you don't set. The resulting prompt replaces the `system_prompt` value and doesn't include the final result report instructions (the text starting with `When you deliver your final result`). + +The following request sets all three parameters during agent execution: + +```json +POST /_plugins/_ml/agents/your_agent_id/_execute?async=true +{ + "parameters": { + "question": "How many indexes in this cluster have names that start with .plugins-ml-am?", + "planner_system_prompt_prefix": "# Index Planner\n\nYou are a planner agent. Write every step in the plan in all uppercase letters.\n", + "result_expand_and_override": "The result field must start with a one-sentence answer.", + "important_rules_expand": "4. Every step string must start with the name of the tool to use" + } +} +``` +{% include copy-curl.html %} + +### Executor system prompt + +To create a custom executor system prompt, modify the `executor_system_prompt` parameter. The following is the executor system prompt: + +``` +You are a precise and reliable executor agent in a plan-execute-reflect framework. Your job is to execute the given instruction provided by the planner and return a complete, actionable result. + +Instructions: +- Fully execute the given Step using the most relevant tool or reasoning. If executing the Step requires multiple tool invocations, invoke at most one tool per response and perform remaining tool invocations in subsequent responses. +- Include all relevant raw tool outputs (e.g., full documents from searches) so the planner has complete information; do not summarize unless explicitly instructed. +- Base your execution and conclusions only on the data and tool outputs available; do not rely on unstated knowledge or external facts. +- If the available data is insufficient to complete the Step, summarize what was obtained so far and clearly state the additional information or access required to proceed (do not guess). +- If unable to complete the Step, clearly explain what went wrong and what is needed to proceed. +- Avoid making assumptions and relying on implicit knowledge. +- Before generating any PPL or DSL query, always retrieve the index mapping first to ensure correct field names. Do not guess field names. +- Your response must be self-contained and ready for the planner to use without modification. Never end with a question. +- Break complex searches into simpler queries when appropriate. +- Never invoke more than one tool in a single response. Returning multiple tool calls in one response is invalid. +``` + +## Modifying default prompts + +To modify the prompts, provide them during agent registration: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Plan Execute and Reflect agent with Claude Sonnet 4.6", + "type": "plan_execute_and_reflect", + "description": "this is a test agent", + "llm": { + "model_id": "your_llm_model_id_from_step1", + "parameters": { + "prompt": "${parameters.question}" + }}, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "bedrock/converse/claude", + "planner_prompt_template": "your_planner_prompt_template", + "planner_prompt": "your_planner_prompt", + "reflect_prompt_template": "your_reflect_prompt_template", + "reflect_prompt": "your_reflect_prompt", + "planner_with_history_template": "your_planner_with_history_template", + "system_prompt": "your_planner_system_prompt", + "executor_system_prompt": "your_executor_system_prompt" + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ] +} +``` +{% include copy-curl.html %} + +You can also modify the prompts during agent execution: + +```json +POST /_plugins/_ml/agents/your_agent_id/_execute?async=true +{ + "parameters": { + "question": "How many flights from Beijing to Seattle?", + "planner_prompt_template": "your_planner_prompt_template", + "planner_prompt": "your_planner_prompt" + } +} +``` +{% include copy-curl.html %} + +## Tracking token usage +**Introduced 3.6** +{: .label .label-purple } + +Plan-execute-reflect agents support token usage tracking, which provides detailed metrics about token consumption for each LLM call during agent execution, including planning, execution (using a subagent), and reflection LLM calls. Subagent token data is automatically merged into the parent agent's token usage report. + +To enable token usage tracking, set the `include_token_usage` parameter to `true` when executing the agent. The response will include a `token_usage` output with per-turn and per-model aggregated metrics. For detailed information about token usage fields and how tokens are calculated by different model providers, see [Tracking token usage]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#tracking-token-usage) in the Execute Agent API documentation. + +## Next steps + +- To learn more about registering agents, see [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +- For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +- For a step-by-step tutorial on using a plan-execute-reflect agent, see [Building a plan-execute-reflect agent]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/). +- For supported APIs, see [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/). +- To create agents and tools using a workflow template, see [AI search workflows]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/index/). \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/index.md b/_ml-commons-plugin/agents-tools/index.md index 016a077c..6a86b493 100644 --- a/_ml-commons-plugin/agents-tools/index.md +++ b/_ml-commons-plugin/agents-tools/index.md @@ -3,179 +3,26 @@ layout: default title: Agents and tools has_children: true has_toc: false -nav_order: 27 +nav_order: 20 +redirect_from: + - /ml-commons-plugin/agents-tools/ --- # Agents and tools -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} +You can automate machine learning (ML) tasks using agents and tools. -You can automate machine learning (ML) tasks using agents and tools. An _agent_ orchestrates and runs ML models and tools. A _tool_ performs a set of specific tasks. Some examples of tools are the `VectorDBTool`, which supports vector search, and the `CATIndexTool`, which executes the `cat indices` operation. For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +An _agent_ orchestrates and runs ML models and tools. For a list of supported agents, see [Agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). -## Agents +<!-- vale off --> +A _tool_ performs a set of specific tasks. Some examples of tools are the [`VectorDBTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/vector-db-tool/), which supports vector search, and the [`ListIndexTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/list-index-tool/), which executes the List Indices API. For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +<!-- vale on --> -An _agent_ is a coordinator that uses a large language model (LLM) to solve a problem. After the LLM reasons and decides what action to take, the agent coordinates the action execution. OpenSearch supports the following agent types: +You can modify and transform tool outputs using a [processor chain]({{site.url}}{{site.baseurl}}/ml-commons-plugin/processor-chain/). +This section describes OpenSearch agents and tools that run inside the OpenSearch cluster and perform common OpenSearch operations such as listing indexes and running queries. -- [_Flow agent_](#flow-agents): Runs tools sequentially, in the order specified in its configuration. The workflow of a flow agent is fixed. Useful for retrieval-augmented generation (RAG). -- [_Conversational flow agent_](#conversational-flow-agents): Runs tools sequentially, in the order specified in its configuration. The workflow of a conversational flow agent is fixed. Stores conversation history so that users can ask follow-up questions. Useful for creating a chatbot. -- [_Conversational agent_](#conversational-agents): Reasons in order to provide a response based on the available knowledge, including the LLM knowledge base and a set of tools provided to the LLM. Stores conversation history so that users can ask follow-up questions. The workflow of a conversational agent is variable, based on follow-up questions. For specific questions, uses the Chain-of-Thought (CoT) process to select the best tool from the configured tools for providing a response to the question. Useful for creating a chatbot that employs RAG. +## Related features -### Flow agents - -A flow agent is configured with a set of tools that it runs in order. For example, the following agent runs the `VectorDBTool` and then the `MLModelTool`. The agent coordinates the tools so that one tool's output can become another tool's input. In this example, the `VectorDBTool` queries the k-NN index and the agent passes its output `${parameters.VectorDBTool.output}` to the `MLModelTool` as context, along with the `${parameters.question}` (see the `prompt` parameter): - -```json -POST /_plugins/_ml/agents/_register -{ - "name": "Test_Agent_For_RAG", - "type": "flow", - "description": "this is a test agent", - "tools": [ - { - "type": "VectorDBTool", - "parameters": { - "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", - "index": "my_test_data", - "embedding_field": "embedding", - "source_field": ["text"], - "input": "${parameters.question}" - } - }, - { - "type": "MLModelTool", - "description": "A general tool to answer any question", - "parameters": { - "model_id": "YOUR_LLM_MODEL_ID", - "prompt": "\n\nHuman:You are a professional data analyst. You will always answer a question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say you don't know. \n\n Context:\n${parameters.VectorDBTool.output}\n\nHuman:${parameters.question}\n\nAssistant:" - } - } - ] -} -``` - -### Conversational flow agents - -Similarly to a flow agent, a conversational flow agent is configured with a set of tools that it runs in order. The difference between them is that a conversational flow agent stores the conversation in an index, in the following example, the `conversation_index`. The following agent runs the `VectorDBTool` and then the `MLModelTool`: - -```json -POST /_plugins/_ml/agents/_register -{ - "name": "population data analysis agent", - "type": "conversational_flow", - "description": "This is a demo agent for population data analysis", - "app_type": "rag", - "memory": { - "type": "conversation_index" - }, - "tools": [ - { - "type": "VectorDBTool", - "name": "population_knowledge_base", - "parameters": { - "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", - "index": "test_population_data", - "embedding_field": "population_description_embedding", - "source_field": [ - "population_description" - ], - "input": "${parameters.question}" - } - }, - { - "type": "MLModelTool", - "name": "bedrock_claude_model", - "description": "A general tool to answer any question", - "parameters": { - "model_id": "YOUR_LLM_MODEL_ID", - "prompt": """ - -Human:You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. - -Context: -${parameters.population_knowledge_base.output:-} - -${parameters.chat_history:-} - -Human:${parameters.question} - -Assistant:""" - } - } - ] -} -``` - -### Conversational agents - -Similarly to a conversational flow agent, a conversational agent stores the conversation in an index, in the following example, the `conversation_index`. A conversational agent can be configured with an LLM and a set of supplementary tools that perform specific jobs. For example, you can set up an LLM and a `CATIndexTool` when configuring an agent. When you send a question to the model, the agent also includes the `CATIndexTool` as context. The LLM then decides whether it needs to use the `CATIndexTool` to answer questions like "How many indexes are in my cluster?" The context allows an LLM to answer specific questions that are outside of its knowledge base. For example, the following agent is configured with an LLM and a `CATIndexTool` that retrieves information about your OpenSearch indexes: - -```json -POST /_plugins/_ml/agents/_register -{ - "name": "Test_Agent_For_ReAct_ClaudeV2", - "type": "conversational", - "description": "this is a test agent", - "llm": { - "model_id": "YOUR_LLM_MODEL_ID", - "parameters": { - "max_iteration": 5, - "stop_when_no_tool_found": true, - "response_filter": "$.completion" - } - }, - "memory": { - "type": "conversation_index" - }, - "tools": [ - { - "type": "VectorDBTool", - "name": "VectorDBTool", - "description": "A tool to search opensearch index with natural language quesiotn. If you don't know answer for some question, you should always try to search data with this tool. Action Input: <natrual language question>", - "parameters": { - "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", - "index": "my_test_data", - "embedding_field": "embedding", - "source_field": [ "text" ], - "input": "${parameters.question}" - } - }, - { - "type": "CatIndexTool", - "name": "RetrieveIndexMetaTool", - "description": "Use this tool to get OpenSearch index information: (health, status, index, uuid, primary count, replica count, docs.count, docs.deleted, store.size, primary.store.size)." - } - ], - "app_type": "my app" -} -``` - -It is important to provide thorough descriptions of the tools so that the LLM can decide in which situations to use those tools. -{: .tip} - -## Enabling the feature - -To enable agents and tools, configure the following setting: - -```yaml -plugins.ml_commons.agent_framework_enabled: true -``` -{% include copy.html %} - -For conversational agents, you also need to enable RAG for use in conversational search. To enable RAG, configure the following setting: - -```yaml -plugins.ml_commons.rag_pipeline_feature_enabled: true -``` -{% include copy.html %} - -For more information about ways to enable experimental features, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). - -## Next steps - -- For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). -- For a step-by-step tutorial, see [Agents and tools tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents-tools-tutorial/). -- For supported APIs, see [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/). -- To use agents and tools in configuration automation, see [Automating configurations]({{site.url}}{{site.baseurl}}/automating-configurations/index/). \ No newline at end of file +OpenSearch also provides tools for external AI assistants to connect to and query your clusters. These tools run outside your OpenSearch cluster. For more information, see [AI agent integrations]({{site.url}}{{site.baseurl}}/ai-agent-integrations/). diff --git a/_ml-commons-plugin/agents-tools/mcp/index.md b/_ml-commons-plugin/agents-tools/mcp/index.md new file mode 100644 index 00000000..9d0daa18 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/mcp/index.md @@ -0,0 +1,29 @@ +--- +layout: default +title: Using MCP tools +parent: Agents and tools +has_children: true +nav_order: 30 +redirect_from: + - /ml-commons-plugin/agents-tools/mcp/ +--- + +# Using MCP tools +**Introduced 3.0** +{: .label .label-purple } + +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol standard that provides a standardized way for AI models to connect to external data sources and tools. OpenSearch integrates with MCP, enabling agents to use external tools and data sources through MCP servers. + +Connecting to external MCP servers expands agent capabilities to include the following functionality: + +- Using the tools provided by MCP servers +- Filtering available tools based on your application needs +- Implementing secure authentication and authorization for tool access +- Interacting with various tools through a consistent, standardized interface + +To start using MCP, see [Connecting to an external MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/). + +This section describes the in-cluster MCP connector that lets OpenSearch agents call tools hosted on external MCP servers. + +OpenSearch also provides an MCP server that exposes OpenSearch APIs to external AI assistants. In contrast to the in-cluster MCP connector, the OpenSearch MCP Server lets external clients query OpenSearch rather than letting OpenSearch agents call external tools. For more information, see [OpenSearch MCP Server]({{site.url}}{{site.baseurl}}/ai-agent-integrations/mcp-server/). +{: .note} \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/mcp/mcp-connector.md b/_ml-commons-plugin/agents-tools/mcp/mcp-connector.md new file mode 100644 index 00000000..bad5f27e --- /dev/null +++ b/_ml-commons-plugin/agents-tools/mcp/mcp-connector.md @@ -0,0 +1,477 @@ +--- +layout: default +title: Connecting to an external MCP server +parent: Using MCP tools +grand_parent: Agents and tools +nav_order: 10 +--- + +# Connecting to an external MCP server +**Introduced 3.0** +{: .label .label-purple } + +OpenSearch supports agentic workflows using [agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). While OpenSearch provides built-in tools for running complex queries, [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) enables integration with external tools and data sources. MCP is an open protocol standard that provides a standardized way for AI models to connect to external data sources and tools, acting as a "universal adapter" for remote MCP server tools. + +OpenSearch supports MCP servers that use either the Server-Sent Events (SSE) protocol or the Streamable HTTP protocol. Standard Input/Output (`stdio`) protocol is not supported. +{: .note} + +The following example demonstrates using MCP tools in agentic workflows. + +## Prerequisites + +Before using MCP tools, you must complete the following prerequisites. + +### Enable MCP and configure trusted connector endpoints + +- Enable the MCP protocol by configuring the `plugins.ml_commons.mcp_connector_enabled` setting. +- Configure trusted connector endpoints in the `plugins.ml_commons.trusted_connector_endpoints_regex` setting. For security purposes, this setting uses regex patterns to define which MCP server URLs are allowed. The value you provide replaces the default list of trusted endpoints, so also include the endpoints of any other connectors that you use, such as the OpenAI endpoint used in [Step 2](#step-2-register-a-model). + +To configure both settings, send the following request: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.trusted_connector_endpoints_regex": [ + "<mcp server url>", + "^https://api\\.openai\\.com/.*$" + ], + "plugins.ml_commons.mcp_connector_enabled": "true" + } +} +``` +{% include copy-curl.html %} + +### Set up an MCP server + +Ensure you have a running MCP server that is accessible from your OpenSearch cluster. + +## Step 1: Create an MCP connector + +An MCP connector stores connection details and credentials for your MCP server. You can connect using either SSE or Streamable HTTP. + +To create an MCP connector using SSE, send the following request: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My MCP Connector", + "description": "Connects to the external MCP server for weather tools", + "version": 1, + "protocol": "mcp_sse", + "url": "https://my-mcp-server.domain.com", + "credential": { + "mcp_server_key": "THE_MCP_SERVER_API_KEY" + }, + "parameters":{ + "sse_endpoint": "/sse" + }, + "headers": { + "Authorization": "Bearer ${credential.mcp_server_key}" + } +} +``` +{% include copy-curl.html %} + +To create an MCP connector using Streamable HTTP, set `protocol` to `mcp_streamable_http`. Optionally, set `parameters.endpoint` to override the default endpoint (`/mcp/`). For example, to connect to the OpenSearch MCP server, set `parameters.endpoint` to `/_plugins/_ml/mcp`. No SSE-specific endpoint is required: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My MCP Connector (Streamable HTTP)", + "description": "Connects to the external MCP server using Streamable HTTP", + "version": 1, + "protocol": "mcp_streamable_http", + "url": "https://my-mcp-server.domain.com", + "credential": { + "mcp_server_key": "THE_MCP_SERVER_API_KEY" + }, + "parameters": { + "endpoint": "/_plugins/_ml/mcp" + }, + "headers": { + "Authorization": "Bearer ${credential.mcp_server_key}" + } +} +``` +{% include copy-curl.html %} + +The following table describes the connector parameters. For more information about standard connector parameters, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). + +| Parameter | Data type | Required | Description | +|:----------|:---------|:---|:------------| +| `protocol` | String | Yes | Specify `mcp_sse` for SSE or `mcp_streamable_http` for Streamable HTTP. | +| `url` | String | Yes | The complete base URL of the MCP server, including protocol, hostname, and port, if not using the default port (for example, `https://my-mcp-server.com:8443`). | +| `credential` | Object | Yes | Contains sensitive authentication information such as API keys or tokens. Values stored in this object can be securely referenced in the `headers` section using the `${credential.*}` syntax. | +| `parameters` | Object | No | Contains configuration parameters for the MCP connector. | +| `parameters.sse_endpoint` | String | No | Applicable for SSE only. The SSE endpoint path for the MCP server. Default is `/sse`. | +| `parameters.endpoint` | String | No | Applicable for Streamable HTTP only. The MCP server endpoint path. Default is `/mcp/`. | +| `headers` | Object | No | The HTTP headers to include with requests to the MCP server. For authentication headers, use the `${credential.*}` syntax to reference values from the `credential` object (for example, `"Authorization": "Bearer ${credential.mcp_server_key}"`). | + +The response contains the connector ID: + +```json +{ + "connector_id": "NZ2W2ZUBZ_3SyqdOvh2n" +} +``` + +## Step 2: Register a model + +Register any externally hosted large language model (LLM) using a connector. For a list of supported models, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). + +For example, to register an OpenAI chat model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "My OpenAI model: gpt-4o-mini", + "function_name": "remote", + "description": "Test model registration (this example uses OpenAI, but you can register any model)", + "connector": { + "name": "My OpenAI Connector: gpt-4o-mini", + "description": "Connector for the OpenAI chat model", + "version": 1, + "protocol": "http", + "parameters": { + "model": "gpt-4o" + }, + "credential": { + "openAI_key": "<YOUR_API_KEY>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_instruction}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}], \"tools\": [${parameters._tools:-}],\"parallel_tool_calls\":${parameters.parallel_tool_calls},\"tool_choice\": \"${parameters.tool_choice}\" }" + } + ] + } +} +``` +{% include copy-curl.html %} + +The response contains the model ID: + +```json +{ + "task_id": "K_iQfpYBjoQOEoSHN3wU", + "status": "CREATED", + "model_id": "LPiQfpYBjoQOEoSHN3zH" +} +``` + +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/). Once the registration is complete, the task `state` changes to `COMPLETED`. + +## Step 3: Register an agent for accessing MCP tools + +The following table lists the agent types that support MCP tools. + +| Agent type | MCP integration | +|:---|:---| +| [`conversational`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/) | The LLM selects MCP tools at runtime. | +| [`plan_execute_and_reflect`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/plan-execute-reflect/) | The LLM selects MCP tools at runtime. | +| [`flow`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/flow/) | MCP tools run in a fixed pipeline order. | +| [`conversational_flow`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational-flow/) | MCP tools run in a fixed pipeline order with conversation memory. | + +For all supported agent types, include one or more MCP connectors in `parameters.mcp_connectors`. How you configure the `tools` array depends on the agent type. + +Each connector must specify the following parameters in the `parameters.mcp_connectors` array. + +| Parameter | Data type | Required | Description | +|:--- |:--- |:--- |:--- | +| `mcp_connector_id` | String | Yes | The connector ID of the MCP connector. | +| `tool_filters` | Array | No | An array of Java-style regular expressions that specify which tools from the MCP server to make available to the agent. A tool is included if it matches at least one of the regular expressions in the array. If omitted or set to an empty array, all tools exposed by the connector are available. Use the `^` or `$` anchors or literal strings to precisely match tool names. For example, `^get_forecast` matches any tool starting with "get_forecast", while `search_indices` matches only "search_indices".| +| `tool_descriptions` | Array | No | An array of objects that override the tool descriptions sent to the LLM. Each object maps a tool name (key) to a replacement description (string value). Only tools that pass the `tool_filters` evaluation can be overridden. Entries are ignored if the tool does not exist on the connector, is excluded by `tool_filters`, or has a blank, null, or non-string value. If the same tool name appears in multiple objects, the last value wins. | + +For `conversational` and `plan_execute_and_reflect` agents, MCP tools are discovered from the configured connectors and presented to the LLM. The LLM decides which MCP tool to call during execution. You do not need to list MCP tools explicitly in the `tools` array, but you can include OpenSearch built-in tools alongside MCP tools. + +The following example registers a conversational agent using the connector ID created in Step 1. The MCP server has two tools available (`get_alerts` and `get_forecasts`), but only the `get_alerts` tool is included in the agent's configuration because it matches the specified regex pattern `^get_alerts$`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Weather & Search Bot", + "type": "conversational", + "description": "Uses MCP to fetch forecasts and OpenSearch indices", + "llm": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "parameters": { + "max_iteration": 5, + "system_instruction": "You are a helpful assistant.", + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "openai/v1/chat/completions", + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>", + "tool_filters": [ + "^get_alerts$" + ] + } + ] + }, + "tools": [ + { "type": "ListIndexTool" }, + { "type": "SearchIndexTool" } + ], + "app_type": "os_chat" +} +``` +{% include copy-curl.html %} + +The response contains the agent ID: + +```json +{ + "agent_id": "LfiXfpYBjoQOEoSH93w7" +} +``` + +### Overriding MCP tool descriptions +**Introduced 3.8** +{: .label .label-purple } + +Each MCP tool includes a description that helps the LLM decide when to call it. To replace a tool's description without modifying the MCP server, use the `tool_descriptions` parameter. This is useful when the server-provided description is too generic, uses internal naming, or does not match your agent's domain vocabulary. + +Each entry in `tool_descriptions` must be a JSON object with a single key-value pair: the MCP tool name and the override description string. You can specify multiple overrides by adding multiple objects to the array. + +The following example registers an agent that exposes only the `get_alerts` tool (using `tool_filters`) and replaces its description with agent-specific guidance: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Weather & Search Bot", + "type": "conversational", + "description": "Uses MCP to fetch forecasts and OpenSearch indices", + "llm": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "parameters": { + "max_iteration": 5 + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "openai/v1/chat/completions", + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>", + "tool_filters": [ + "^get_alerts$" + ], + "tool_descriptions": [ + { + "get_alerts": "Fetch active weather alerts for a US state. Use when the user asks about warnings or advisories." + } + ] + } + ] + }, + "tools": [ + { "type": "ListIndexTool" } + ], + "app_type": "os_chat" +} +``` +{% include copy-curl.html %} + +To override descriptions for multiple tools without applying `tool_filters`, omit the `tool_filters` parameter or set it to an empty array so that all connector tools remain available: + +```json +"mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>", + "tool_descriptions": [ + { "get_alerts": "Fetch active weather alerts for a US state." }, + { "get_forecast": "Fetch a multi-day weather forecast for a city." } + ] + } +] +``` + +Overrides for tool names that are not exposed by the connector or that `tool_filters` excludes have no effect. The agent continues to use the MCP server's original description for any tool without a valid override. + +### Flow agents and conversational flow agents +**Introduced 3.8** +{: .label .label-purple } + +For [`flow`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/flow/) and [`conversational_flow`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational-flow/) agents, MCP tools run in the fixed order defined in the `tools` array. You must declare each MCP tool explicitly and match the tool `type` to your connector protocol. + +| Connector protocol | MCP tool `type` | +|:---|:---| +| `mcp_streamable_http` | `McpStreamableHttpTool` | +| `mcp_sse` | `McpSseTool` | + +Each MCP tool entry in the `tools` array supports the following fields. + +| Field | Data type | Required | Description | +|:---|:---|:---|:---| +| `name` | String | Yes | The MCP server tool name. Must match a tool exposed by the configured connector. Used for output chaining (for example, `${parameters.get_simple_price.output}`). | +| `type` | String | Yes | `McpStreamableHttpTool` or `McpSseTool`, matching the connector protocol. | +| `description` | String | No | A description of the tool. If omitted, OpenSearch uses the description from the MCP server when available. | +| `parameters.input` | String | Yes | The tool input payload, typically a JSON string passed to the MCP server tool. | + +You can mix MCP tools with OpenSearch tools such as `MLModelTool` in the same pipeline. Output from one step can be passed to the next using `${parameters.<tool_name>.output}`. + +If an MCP tool is listed in `tools` but is not available from the configured connector, agent execution fails with an error indicating the tool is not available. If multiple MCP connectors expose a tool with the same name, OpenSearch uses the tool from the first matching connector in the `mcp_connectors` array. + +Before registering a flow or conversational flow agent, use the [List Connector MCP Tools API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools/) to discover tool names, types, descriptions, and input schemas from your MCP connector. Use the `name` and `type` values from the response when configuring MCP tools in the agent, and build the `parameters.input` JSON string from each tool's `input_schema`. + +The following example registers a `flow` agent that calls `search_documents` and `get_weather` in sequence, then summarizes the results with `MLModelTool`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research and weather flow agent", + "type": "flow", + "description": "Flow agent using MCP tools in a fixed order", + "parameters": { + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>" + } + ] + }, + "tools": [ + { + "name": "search_documents", + "type": "McpStreamableHttpTool", + "description": "Search a document repository for relevant content.", + "parameters": { + "input": "{\"query\":\"OpenSearch agentic search\",\"limit\":5}" + } + }, + { + "name": "get_weather", + "type": "McpStreamableHttpTool", + "description": "Retrieve current weather conditions for a specified location.", + "parameters": { + "input": "{\"location\":\"Seattle\",\"units\":\"celsius\"}" + } + }, + { + "name": "summarize_results", + "type": "MLModelTool", + "description": "Summarize MCP tool outputs", + "parameters": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "prompt": "You are a research assistant.\n\nDocument search results:\n${parameters.search_documents.output}\n\nWeather:\n${parameters.get_weather.output}\n\nProvide a brief summary of the findings." + } + } + ] +} +``` +{% include copy-curl.html %} + +To use the same MCP pipeline with conversation memory, set `type` to `conversational_flow` and add a `memory` block at the same level as `parameters` and `tools`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research and weather conversational flow agent", + "type": "conversational_flow", + "description": "Conversational flow agent using MCP tools in a fixed order", + "memory": { + "type": "conversation_index" + }, + "parameters": { + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>" + } + ] + }, + "tools": [ + { + "name": "search_documents", + "type": "McpStreamableHttpTool", + "description": "Search a document repository for relevant content.", + "parameters": { + "input": "{\"query\":\"OpenSearch agentic search\",\"limit\":5}" + } + }, + { + "name": "get_weather", + "type": "McpStreamableHttpTool", + "description": "Retrieve current weather conditions for a specified location.", + "parameters": { + "input": "{\"location\":\"Seattle\",\"units\":\"celsius\"}" + } + }, + { + "name": "summarize_results", + "type": "MLModelTool", + "description": "Summarize MCP tool outputs", + "parameters": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "prompt": "You are a research assistant.\n\nDocument search results:\n${parameters.search_documents.output}\n\nWeather:\n${parameters.get_weather.output}\n\nProvide a brief summary of the findings." + } + } + ] +} +``` +{% include copy-curl.html %} + +## Step 4: Run the agent + +Invoke the registered agent by calling the Execute Agent API and providing a user question: + +```json +POST /_plugins/_ml/agents/{Agent_ID}/_execute +{ + "parameters": { + "question": "Any weather alerts in Washington", + "verbose": true + } +} +``` +{% include copy-curl.html %} + +The agent uses both the OpenSearch tools specified in the `tools` array and the selected tools from the MCP server (based on your tool filters) to return the answer: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "memory_id", + "result": "MfiZfpYBjoQOEoSH13wj" + }, + { + "name": "parent_interaction_id", + "result": "MviZfpYBjoQOEoSH13xC" + }, + { + "name": "response", + "result": "{\"id\":\"chatcmpl-BRRcdxVjkrKG7HjkVWZVwueJSEjgd\",\"object\":\"chat.completion\",\"created\":1.745880735E9,\"model\":\"gpt-4o-2024-08-06\",\"choices\":[{\"index\":0.0,\"message\":{\"role\":\"assistant\",\"tool_calls\":[{\"id\":\"call_yWg0wk4mfE2v8ARebupfbJ87\",\"type\":\"function\",\"function\":{\"name\":\"get_alerts\",\"arguments\":\"{\\\"state\\\":\\\"WA\\\"}\"}}],\"annotations\":[]},\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":201.0,\"completion_tokens\":16.0,\"total_tokens\":217.0,\"prompt_tokens_details\":{\"cached_tokens\":0.0,\"audio_tokens\":0.0},\"completion_tokens_details\":{\"reasoning_tokens\":0.0,\"audio_tokens\":0.0,\"accepted_prediction_tokens\":0.0,\"rejected_prediction_tokens\":0.0}},\"service_tier\":\"default\",\"system_fingerprint\":\"fp_f5bdcc3276\"}" + }, + { + "name": "response", + "result": "[{\"text\":\"\\nEvent: Wind Advisory\\nArea: Kittitas Valley\\nSeverity: Moderate\\nDescription: * WHAT...Northwest winds 25 to 35 mph with gusts up to 45 mph\\nexpected.\\n\\n* WHERE...Kittitas Valley.\\n\\n* WHEN...From 2 PM to 8 PM PDT Tuesday.\\n\\n* IMPACTS...Gusty winds will blow around unsecured objects. Tree\\nlimbs could be blown down and a few power outages may result.\\nInstructions: Winds this strong can make driving difficult, especially for high\\nprofile vehicles. Use extra caution.\\n\"}]" + }, + { + "name": "response", + "result": "There is a Wind Advisory for the Kittitas Valley in Washington. Here are the details:\n\n- **Event:** Wind Advisory\n- **Area:** Kittitas Valley\n- **Severity:** Moderate\n- **Description:** Northwest winds 25 to 35 mph with gusts up to 45 mph expected.\n- **When:** From 2 PM to 8 PM PDT Tuesday.\n- **Impacts:** Gusty winds may blow around unsecured objects, potentially causing tree limbs to fall, and resulting in a few power outages.\n\n**Instructions:** These strong winds can make driving difficult, especially for high-profile vehicles. Use extra caution if you are traveling in the area." + } + ] + } + ] +} +``` + +## Additional resources + +* For more information about the MCP protocol, see [MCP protocol documentation](https://modelcontextprotocol.io/introduction). +* For information about using MCP in Java, see [MCP Java SDK](https://github.com/modelcontextprotocol/java-sdk). diff --git a/_ml-commons-plugin/agents-tools/tools/agent-tool.md b/_ml-commons-plugin/agents-tools/tools/agent-tool.md index 272456d6..e0e4ec09 100644 --- a/_ml-commons-plugin/agents-tools/tools/agent-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/agent-tool.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Agent tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `AgentTool` runs any agent. ## Step 1: Set up an agent for AgentTool to run @@ -107,4 +104,8 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- -`question` | String | Required | The natural language question to send to the LLM. \ No newline at end of file +`question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/connector-tool.md b/_ml-commons-plugin/agents-tools/tools/connector-tool.md new file mode 100644 index 00000000..07d767b2 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/connector-tool.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Connector tool +has_children: false +has_toc: false +nav_order: 20 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Connector tool +**Introduced 2.15** +{: .label .label-purple } +<!-- vale on --> + +The `ConnectorTool` uses a [connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/) to call any REST API function. For example, you can use a `ConnectorTool` to call a Lambda function through its REST API interface. + +## Step 1: Register a connector with an execute action + +The `ConnectorTool` can only run an `execute` action within a connector. Before you can create a `ConnectorTool`, you need to configure a connector and provide an `execute` action in the `actions` array. The `execute` action is used to invoke a function at a REST API endpoint. It is similar to the `predict` action, which is used to invoke a machine learning (ML) model. + +For this example, you'll create a connector for a simple AWS Lambda function that accepts two integers and returns their sum. This function is hosted on a dedicated endpoint with a specific URL, which you'll provide in the `url` parameter. For more information, see [Lambda function URLs](https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html). + +To create a connector, send the following request: + +```json +POST _plugins/_ml/connectors/_create +{ + "name": "Lambda connector of simple calculator", + "description": "Demo connector of lambda function", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "<YOUR AWS REGION>", + "service_name": "lambda" + }, + "credential": { + "access_key": "<YOUR ACCESS KEY>", + "secret_key": "<YOUR SECRET KEY>", + "session_token": "<YOUR SESSION TOKEN>" + }, + "actions": [ + { + "action_type": "execute", + "method": "POST", + "url": "<YOUR LAMBDA FUNCTION URL>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"number1\":\"${parameters.number1}\", \"number2\":\"${parameters.number2}\" }" + } + ] +} +``` +{% include copy-curl.html %} + +OpenSearch responds with a connector ID: + +```json +{ + "connector_id": "Zz1XEJABXWrLmr4mewEF" +} +``` + +## Step 2: Register a flow agent that will run the ConnectorTool + +For this example, the Lambda function adds the two input numbers and returns their sum in the `result` field: + +```json +{ + "result": 5 +} +``` + +By default, the `ConnectorTool` expects the response from the Lambda function to contain a field named `response`. However, in this example the Lambda function response doesn't include a `response` field. To retrieve the result from the `result` field instead, you need to provide a `response_filter`, specifying the [JSON path](https://github.com/json-path/JsonPath) to the `result` field (`$.result`). Using the `response_filter`, the `ConnectorTool` will retrieve the result with the specified JSON path and return it in the `response` field. + +To configure the Lambda function workflow, create a flow agent. A flow agent runs a sequence of tools in order and returns the last tool's output. To create a flow agent, send the following register agent request, providing the connector ID from the previous step and a `response_filter`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Demo agent of Lambda connector", + "type": "flow", + "description": "This is a demo agent", + "app_type": "demo", + "tools": [ + { + "type": "ConnectorTool", + "name": "lambda_function", + "parameters": { + "connector_id": "Zz1XEJABXWrLmr4mewEF", + "response_filter": "$.result" + } + } + ] +} +``` +{% include copy-curl.html %} + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "az1XEJABXWrLmr4miAFj" +} +``` + +## Step 3: Run the agent + +Then, run the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/az1XEJABXWrLmr4miAFj/_execute +{ + "parameters": { + "number1": 2, + "number2": 3 + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the output of the Lambda function execution. In the output, the field name is `response`, and the `result` field contains the Lambda function result: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": 5 + } + ] + } + ] +} +``` + +## Register parameters + +The following table lists all tool parameters that are available when registering an agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`connector_id` | String | Required | A connector ID of a connector configured with an `execute` action that invokes an API. +`response_filter` | String | Optional | A [JSON path](https://github.com/json-path/JsonPath) to the response field that contains the result of invoking the API. If a `response_filter` is not specified, then the `ConnectorTool` expects the API response to be in a field named `response`. + +## Execute parameters + +When running the agent, you can define any parameter needed for the API call in the `request_body` of your connector's `execute` action. In this example, the parameters are `number1` and `number2`: + +```json +"actions": [ + { + "action_type": "execute", + "method": "POST", + "url": "<YOUR LAMBDA FUNCTION URL>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"number1\":\"${parameters.number1}\", \"number2\":\"${parameters.number2}\" }" + } + ] +``` + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/create-anomaly-detector.md b/_ml-commons-plugin/agents-tools/tools/create-anomaly-detector.md new file mode 100644 index 00000000..366d3738 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/create-anomaly-detector.md @@ -0,0 +1,169 @@ +--- +layout: default +title: Create Anomaly Detector tool +has_children: false +has_toc: false +nav_order: 22 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Create Anomaly Detector tool +**Introduced 2.16** +{: .label .label-purple } +<!-- vale on --> + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/skills/issues/337). +{: .warning} + +The `CreateAnomalyDetectorTool` helps create anomaly detectors based on your provided index. This tool retrieves index mappings and enables a large language model (LLM) to recommend category fields, aggregation fields, and their corresponding aggregation methods, which are required by the Create Anomaly Detector API. + +For comprehensive information about anomaly detectors, see [Anomaly detection]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/). +{: .tip} + +## Step 1: Register a flow agent that runs the CreateAnomalyDetectorTool + +A flow agent runs a sequence of tools in order, returning the output of the last tool. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Create_Anomaly_Detector_Tool", + "type": "flow", + "description": "this is a test agent for the CreateAnomalyDetectorTool", + "tools": [ + { + "type": "CreateAnomalyDetectorTool", + "name": "DemoCreateAnomalyDetectorTool", + "parameters": { + "model_id": "<the model id of LLM>" + } + } + ] +} +``` +{% include copy-curl.html %} + +OpenSearch responds with an agent ID, for example, as follows: + +```json +{ + "agent_id": "EuJYYo0B9RaBCvhuy1q8" +} +``` + +## Step 2: Run the agent + +Run the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/EuJYYo0B9RaBCvhuy1q8/_execute +{ + "parameters": { + "index": "sample_weblogs_test" + } +} +``` +{% include copy-curl.html %} + +OpenSearch responds with a JSON string containing all of the recommended parameters for creating an anomaly detector, such as the string shown in the following example response: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result":"""{"index":"sample_weblogs_test","categoryField":"ip.keyword","aggregationField":"bytes,response,responseLatency","aggregationMethod":"sum,avg,avg","dateFields":"utc_time,timestamp"}""" + } + ] + } + ] +} +``` + +You can then create an anomaly detector containing the recommended parameters by sending a request similar to the following: + +```json +POST _plugins/_anomaly_detection/detectors +{ + "name": "test-detector", + "description": "Test detector", + "time_field": "timestamp", + "indices": [ + "sample_weblogs_test" + ], + "feature_attributes": [ + { + "feature_name": "feature_bytes", + "feature_enabled": true, + "aggregation_query": { + "agg1": { + "sum": { + "field": "bytes" + } + } + } + }, + { + "feature_name": "feature_response", + "feature_enabled": true, + "aggregation_query": { + "agg2": { + "avg": { + "field": "response" + } + } + } + }, + { + "feature_name": "feature_responseLatency", + "feature_enabled": true, + "aggregation_query": { + "agg3": { + "avg": { + "field": "responseLatency" + } + } + } + } + ], + "detection_interval": { + "period": { + "interval": 1, + "unit": "Minutes" + } + }, + "window_delay": { + "period": { + "interval": 1, + "unit": "Minutes" + } + } +} +``` +{% include copy-curl.html %} + +## Register parameters + +The following table lists the available tool parameters for agent registration. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`model_id` | String | Required | The LLM model ID used for suggesting required Create Anomaly Detector API parameters. +`model_type` | String | Optional | The model type. Valid values are `CLAUDE` (Anthropic Claude models) and `OPENAI` (OpenAI models). Default is `CLAUDE`. The model type determines the default prompt sent to the LLM. +`prompt` | String | Optional | A custom prompt that the tool sends to the LLM. If not specified, the tool uses the default prompt for the specified `model_type`. + +## Execute parameters + +The following table lists the available tool parameters for running the agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`index` | String | Required | The index name. Supports wildcards (for example, `weblogs-*`). If wildcards are used, then the tool fetches mappings from the first resolved index and sends them to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/data-distribution-tool.md b/_ml-commons-plugin/agents-tools/tools/data-distribution-tool.md new file mode 100644 index 00000000..17ef4909 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/data-distribution-tool.md @@ -0,0 +1,210 @@ +--- +layout: default +title: Data Distribution tool +has_children: false +has_toc: false +nav_order: 25 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Data Distribution tool +**Introduced 3.3.0** +{: .label .label-purple } +<!-- vale on --> + +The `DataDistributionTool` analyzes data distribution patterns within datasets and compares distributions between different time periods. It supports both single dataset analysis and comparative analysis to identify significant changes in field value distributions, helping detect anomalies, trends, and data quality issues. + +The tool supports both [query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/) and [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) queries for flexible data retrieval and filtering. + +## Analysis modes + +The tool automatically selects the appropriate analysis mode based on the provided parameters: + +- **Comparative analysis**: When both baseline and selection time ranges are provided, the tool compares field distributions between the two periods to identify significant changes and divergences. +- **Single dataset analysis**: When only a selection time range is provided, the tool analyzes distribution patterns within the dataset to provide insights into field value frequencies and characteristics. + +## Step 1: Register a flow agent that runs the DataDistributionTool + +A flow agent runs a sequence of tools in order, returning the last tool's output. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Data_Distribution_Tool", + "type": "flow", + "description": "this is a test agent for the DataDistributionTool", + "tools": [ + { + "type": "DataDistributionTool", + "parameters": {} + } + ] +} +``` +{% include copy-curl.html %} + +No parameters are required to register the tool. The tool uses dynamic parameter validation at execution time. + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "OQutgJYBAc35E4_KvI1q" +} +``` + +## Step 2: Run the agent + +Run the agent to perform either a comparative distribution analysis or a single dataset distribution analysis. + +### Comparative analysis + +To perform a comparative distribution analysis between two time periods, provide both the baseline and selection time ranges: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "logs-2025.01.15", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "baselineTimeRangeStart": "2025-01-15 08:00:00", + "baselineTimeRangeEnd": "2025-01-15 09:00:00", + "size": 1000, + "queryType": "dsl", + "filter": ["{\"term\": {\"status\": \"error\"}}", "{\"range\": {\"response_time\": {\"gte\": 100}}}"] + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns a field-by-field comparison showing distribution changes between time periods: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"comparisonAnalysis\":[{\"field\":\"response_time\",\"divergence\":0.6666666666666667,\"topChanges\":[{\"value\":\"120\",\"selectionPercentage\":0.33,\"baselinePercentage\":1.0},{\"value\":\"200\",\"selectionPercentage\":0.67,\"baselinePercentage\":0.0}]},{\"field\":\"host\",\"divergence\":0.33333333333333337,\"topChanges\":[{\"value\":\"web-1\",\"selectionPercentage\":0.67,\"baselinePercentage\":1.0},{\"value\":\"web-2\",\"selectionPercentage\":0.33,\"baselinePercentage\":0.0}]}]}" + } + ] + } + ] +} +``` + +### Single dataset analysis + +To perform a single dataset distribution analysis, provide only a selection time range: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "application_logs", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "size": 1000, + "queryType": "dsl" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns distribution patterns for the analyzed dataset: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"singleAnalysis\":[{\"field\":\"status\",\"divergence\":0.7,\"topChanges\":[{\"value\":\"success\",\"selectionPercentage\":0.7,\"baselinePercentage\":null},{\"value\":\"error\",\"selectionPercentage\":0.3,\"baselinePercentage\":null}]},{\"field\":\"host\",\"divergence\":0.6,\"topChanges\":[{\"value\":\"web-1\",\"selectionPercentage\":0.6,\"baselinePercentage\":null},{\"value\":\"web-2\",\"selectionPercentage\":0.4,\"baselinePercentage\":null}]}]}" + } + ] + } + ] +} +``` + +## Using a PPL query + +Run the agent using PPL for data retrieval: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "logs-2025.01.15", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "size": 1000, + "queryType": "ppl", + "ppl": "source=logs-2025.01.15 | where status='error'" + } +} +``` +{% include copy-curl.html %} + +## Using a custom DSL query + +Run the agent with a complete custom DSL query: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "logs-2025.01.15", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "size": 1000, + "queryType": "dsl", + "dsl": "{\"bool\": {\"must\": [{\"term\": {\"status\": \"error\"}}], \"filter\": [{\"range\": {\"response_time\": {\"gte\": 100}}}]}}" + } +} +``` +{% include copy-curl.html %} + +## Execute parameters + +The following table lists the available tool parameters for running the agent. + +| Parameter | Type | Required/Optional | Description | +|:----------|:-----|:------------------|:------------| +| `index` | String | Required | The name of the OpenSearch index containing the data to analyze. | +| `timeField` | String | Optional | A date/time field for time-based filtering. Default is `@timestamp`. | +| `selectionTimeRangeStart` | String | Required | The start time for the analysis period, in UTC date string format (for example, `2025-01-15 10:00:00`). | +| `selectionTimeRangeEnd` | String | Required | The end time for the analysis period, in UTC date string format (for example, `2025-01-15 11:00:00`). | +| `baselineTimeRangeStart` | String | Optional | The start time for the baseline comparison period, in UTC date string format (for example, `2025-01-15 10:00:00`). Required for the comparative analysis mode. | +| `baselineTimeRangeEnd` | String | Optional | The end time for the baseline comparison period, in UTC date string format (for example, `2025-01-15 11:00:00`). Required for the comparative analysis mode. | +| `size` | Integer | Optional | The maximum number of documents to analyze. Default is `1000`. Maximum is `10000`. | +| `queryType` | String | Optional | The query type. Valid values are `ppl` and `dsl`. Default is `dsl`. | +| `filter` | Array | Optional | Additional DSL query conditions for filtering, specified as JSON strings (for example, `["{\"term\": {\"status\": \"error\"}}", "{\"range\": {\"level\": {\"gte\": 3}}}"]`). | +| `dsl` | String | Optional | A complete raw DSL query as a JSON string. If provided, takes precedence over the `filter` parameter. | +| `ppl` | String | Optional | A complete PPL statement without time information. Used when `queryType` is `ppl`. | + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. + +## Limitations + +The Data Distribution tool has the following limitations: + +- **Maximum document volume**: The tool has a default limit of 1,000 documents per execution, with a maximum configurable limit of 10,000 documents (`MAX_SIZE_LIMIT = 10000`). +- **Field cardinality limits**: High-cardinality fields are automatically filtered to ensure meaningful analysis results: + - ID fields: Maximum of 30 unique values. + - Data fields: Maximum of 10 unique values (or dataset size ÷ 2, whichever is larger). +- **Result limits**: + - Comparative analysis: Returns the top 10 field differences. + - Single dataset analysis: Returns the top 30 field distributions. + - Top changes per field: Limited to 10 items. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/index-mapping-tool.md b/_ml-commons-plugin/agents-tools/tools/index-mapping-tool.md index f27b0592..fcd7c146 100644 --- a/_ml-commons-plugin/agents-tools/tools/index-mapping-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/index-mapping-tool.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Index Mapping tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `IndexMappingTool` retrieves mapping and setting information for indexes in your cluster. ## Step 1: Register a flow agent that will run the IndexMappingTool @@ -55,7 +52,7 @@ OpenSearch responds with an agent ID: ## Step 2: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). +Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). Then, run the agent by sending the following request and providing the index name and the question: @@ -110,7 +107,7 @@ The following table lists all tool parameters that are available when registerin Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `input` | String | Required | The user input used to return index information. -`index` | Array | Required | A comma-delimited list of one or more indexes for which to obtain mapping and setting information. Default is an empty list, which means all indexes. +`index` | Array | Required | A comma-delimited list of one or more indexes for which to obtain mapping and setting information. If the list is empty, the tool returns a message stating that no results were found. `local` | Boolean | Optional | Whether to return information from the local node only instead of the cluster manager node (default is `false`). ## Execute parameters @@ -120,4 +117,8 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. -`index` | Array | Optional | A comma-delimited list of one or more indexes for which to obtain mapping and setting information. Default is an empty list, which means all indexes. \ No newline at end of file +`index` | Array | Optional | A comma-delimited list of one or more indexes for which to obtain mapping and setting information. If the list is empty, the tool returns a message stating that no results were found. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/index.md b/_ml-commons-plugin/agents-tools/tools/index.md index fe6d574d..dbca55fd 100644 --- a/_ml-commons-plugin/agents-tools/tools/index.md +++ b/_ml-commons-plugin/agents-tools/tools/index.md @@ -6,11 +6,13 @@ has_children: true has_toc: false nav_order: 20 redirect_from: - - /ml-commons-plugin/extensibility/index/ + - /ml-commons-plugin/agents-tools/tools/ + - /ml-commons-plugin/agents-tools/tools/cat-index-tool/ + - /ml-commons-plugin/agents-tools/tools/dynamic-tool/ --- # Tools -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } A _tool_ performs a set of specific tasks. The following table lists all tools that OpenSearch supports. @@ -29,23 +31,35 @@ Specify a tool by providing its `type`, `parameters`, and, optionally, a `descri Each tool takes a list of parameters specific to that tool. In the preceding example, the `AgentTool` takes an `agent_id` of the agent it will run. For a list of parameters, see each tool's documentation. +You can also run tools directly without creating an agent using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/), which is useful for testing individual tools or performing standalone operations. + |Tool | Description | |:--- |:--- | |[`AgentTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/agent-tool/) |Runs any agent. | -|[`CatIndexTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/cat-index-tool/) |Retrieves index information for the OpenSearch cluster. | +|[`ConnectorTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/connector-tool/) | Uses a [connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/) to call any REST API function. | +|[`CreateAnomalyDetectorTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/create-anomaly-detector/) | Enables an LLM to suggest required parameters for creating an anomaly detector. | +|[`DataDistributionTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/data-distribution-tool/) | Analyzes data distribution patterns within datasets and compares distributions between different time periods. | |[`IndexMappingTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index-mapping-tool/) |Retrieves index mapping and setting information for an index. | +|[`ListIndexTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/list-index-tool/) |Retrieves index information for the OpenSearch cluster. Introduced in OpenSearch version 3.0 as a replacement for the `CatIndexTool`. | +|[`LogPatternAnalysisTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool/) |Performs advanced log analysis by detecting exceptional log patterns and sequences through comparative analysis. | +|[`LogPatternTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/log-pattern-tool/) |Analyzes log data to extract and identify recurring structural patterns across log messages. | |[`MLModelTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/ml-model-tool/) |Runs machine learning models. | |[`NeuralSparseSearchTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/neural-sparse-tool/) | Performs sparse vector retrieval. | |[`PPLTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/ppl-tool/) |Translates natural language into a Piped Processing Language (PPL) query. | +|[`QueryPlanningTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/) |Creates and executes an OpenSearch DSL query based on a user's natural language question. | |[`RAGTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/rag-tool/) |Uses neural search or neural sparse search to retrieve documents and integrates a large language model to summarize the answers. | +|[`ReadFromScratchPadTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/scratchpad-tools/) |Reads notes and information from an agent's temporary scratchpad memory during execution. | |[`SearchAlertsTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-alerts-tool/) |Searches for alerts. | |[`SearchAnomalyDetectorsTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-anomaly-detectors/) | Searches for anomaly detectors. | |[`SearchAnomalyResultsTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-anomaly-results/) | Searches anomaly detection results generated by anomaly detectors. | |[`SearchIndexTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-index-tool/) |Searches an index using a query written in query domain-specific language (DSL). | |[`SearchMonitorsTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-monitors-tool/) | Searches for alerting monitors. | +|[`SearchTemplateFillTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-template-fill-tool/) |Generates an OpenSearch DSL query by filling the parameters of a registered search template. | |[`VectorDBTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/vector-db-tool/) |Performs dense vector retrieval. | |[`VisualizationTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/visualization-tool/) |Finds visualizations in OpenSearch Dashboards. | +|[`WebSearchTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/web-search-tool/) |Answers a user's question using a web search. | +|[`WriteToScratchPadTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/scratchpad-tools/) |Writes notes and information to an agent's temporary scratchpad memory during execution. | ## Developer information -The agents and tools framework is flexible and extensible. You can find the list of tools provided by OpenSearch in the [Tools library](https://github.com/opensearch-project/skills/tree/main/src/main/java/org/opensearch/agent/tools). For a different use case, you can build your own tool by implementing the [_Tool_ interface](https://github.com/opensearch-project/ml-commons/blob/2.x/spi/src/main/java/org/opensearch/ml/common/spi/tools/Tool.java). \ No newline at end of file +The agents and tools framework offers flexibility and extensibility. See the [tools library](https://github.com/opensearch-project/skills/tree/main/src/main/java/org/opensearch/agent/tools) for OpenSearch-provided tools. Implement the [**Tool** interface](https://github.com/opensearch-project/ml-commons/blob/main/spi/src/main/java/org/opensearch/ml/common/spi/tools/Tool.java) to build custom tools for different use cases. diff --git a/_ml-commons-plugin/agents-tools/tools/list-index-tool.md b/_ml-commons-plugin/agents-tools/tools/list-index-tool.md new file mode 100644 index 00000000..471e8725 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/list-index-tool.md @@ -0,0 +1,118 @@ +--- +layout: default +title: List Index tool +has_children: false +has_toc: false +nav_order: 35 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# List Index tool +**Introduced 3.0** +{: .label .label-purple } +<!-- vale on --> + +The `ListIndexTool` retrieves index information for the OpenSearch cluster, similarly to the [List Indices API]({{site.url}}{{site.baseurl}}/api-reference/list/list-indices/). + +The `ListIndexTool` replaces the `CatIndexTool` starting with OpenSearch version 3.0. +{: .note} + +## Step 1: Register a flow agent that will run the ListIndexTool + +A flow agent runs a sequence of tools in order and returns the last tool's output. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_ListIndex_tool", + "type": "flow", + "description": "this is a test agent for the ListIndexTool", + "tools": [ + { + "type": "ListIndexTool", + "name": "DemoListIndexTool", + "parameters": { + "input": "${parameters.question}" + } + } + ] +} +``` +{% include copy-curl.html %} + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +## Step 2: Run the agent + +Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). + +Then, run the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How many indices do I have?" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the index information: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,.plugins-ml-model-group,lHgGEgJhT_mpADyOZoXl2g,1,0,9,2,16.7kb,16.7kb +2,green,open,.plugins-ml-config,G7gxGQB7TZeQzBasHd5PUg,1,0,1,0,3.9kb,3.9kb +3,green,open,sample-ecommerce,UPYOQcAfRGqFAlSxcZlRjw,1,0,40320,0,2mb,2mb +4,green,open,.plugins-ml-model,WYcjBHcnRuSDHeVWPVupoA,1,0,191,45,2.1gb,2.1gb +5,green,open,opensearch_dashboards_sample_data_ecommerce,wnE6r7OvSPqc5YHj8wHSLA,1,0,4675,0,4.9mb,4.9mb +... +""" + } + ] + } + ] +} +``` + +## Register parameters + +The following table lists all tool parameters that are available when registering an agent. + +<!-- vale off --> +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`indices` | Array | Optional | An array of one or more indexes on which to run the list index operation, specified as a JSON array (for example, `["index1", "index2"]`). Default is an empty array, which means all indexes. +`local` | Boolean | Optional | When `true`, retrieves information from the local node only instead of the cluster manager node. Default is `false`. +`page_size` | Integer | Optional | Specifies the number of index results returned per page when using the List Indices API. The API retrieves index status in a paginated manner. Default is `100`. +`include_unloaded_segments` | Boolean | Optional | When `true`, the index statistics include information from segments that are not loaded into memory. Default is `false`. +<!-- vale on --> + +## Execute parameters + +The following table lists all tool parameters that are available when running the agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool.md b/_ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool.md new file mode 100644 index 00000000..0b0f57e7 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool.md @@ -0,0 +1,240 @@ +--- +layout: default +title: Log Pattern Analysis tool +has_children: false +has_toc: false +nav_order: 38 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Log Pattern Analysis tool +**Introduced 3.3.0** +{: .label .label-purple } +<!-- vale on --> + +The `LogPatternAnalysisTool` performs an advanced log analysis by detecting anomalous log patterns and sequences through comparative analysis between baseline and selection time ranges. It supports the following analysis modes: + +- Log sequence analysis (with trace correlation) +- Log pattern difference analysis +- Log insights analysis for error detection + +The tool uses machine learning clustering algorithms and statistical methods to identify anomalous patterns that appear significantly more frequently in the selection period compared to the baseline period, helping detect system issues and performance anomalies. + +## Analysis modes + +The tool automatically selects the appropriate analysis mode based on the provided parameters: + +- **Log sequence analysis**: When both a trace field and a baseline time range are provided, the tool analyzes trace-correlated log sequences to identify anomalous execution paths. +- **Log pattern difference analysis**: When a baseline time range is provided without a trace field, the tool compares log patterns between baseline and selection periods to detect anomalous patterns. +- **Log insights analysis**: When only a selection time range is provided, the tool performs pattern analysis based on error keywords in order to identify critical issues. + +## Step 1: Register a flow agent that will run the LogPatternAnalysisTool + +A flow agent runs a sequence of tools in order, returning the last tool's output. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Log_Pattern_Analysis_Tool", + "type": "flow", + "description": "this is a test agent for the LogPatternAnalysisTool", + "tools": [ + { + "type": "LogPatternAnalysisTool", + "parameters": {} + } + ] +} +``` +{% include copy-curl.html %} + +No parameters are required to register the tool. The tool uses dynamic parameter validation at execution time. + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "OQutgJYBAc35E4_KvI1q" +} +``` + +## Step 2: Run the agent + +Run the agent to perform various analysis types. + +The examples use fixed time ranges. To run an example on your own data, set `index` to your log index and set the time range parameters to times within the range of timestamps in that index. To find the earliest and latest timestamps, run a `min` and `max` aggregation on the time field: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "earliest": { "min": { "field": "@timestamp" } }, + "latest": { "max": { "field": "@timestamp" } } + } +} +``` +{% include copy-curl.html %} + +The `value_as_string` fields contain the earliest and latest timestamps: + +```json +{ + ... + "aggregations": { + "earliest": { + "value": 1.791074342912E12, + "value_as_string": "2026-10-04T00:39:02.912Z" + }, + "latest": { + "value": 1.796334326749E12, + "value_as_string": "2026-12-03T21:45:26.749Z" + } + } +} +``` + +Provide the time range parameters in the `yyyy-MM-dd HH:mm:ss` format, for example, `2026-10-04 00:00:00`. + +### Log sequence analysis + +To perform a trace-based sequence analysis, provide a `traceFieldName`, `baseTimeRangeStart`, and `baseTimeRangeEnd`: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "ss4o_logs-otel-2025.06.24", + "timeField": "@timestamp", + "logFieldName": "body", + "traceFieldName": "traceId", + "baseTimeRangeStart": "2025-06-24 07:33:05", + "baseTimeRangeEnd": "2025-06-24 07:51:27", + "selectionTimeRangeStart": "2025-06-24 07:50:26", + "selectionTimeRangeEnd": "2025-06-24 07:55:56" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns exceptional trace sequences that differ significantly from baseline patterns: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"EXCEPTIONAL\": {\"trace456\": \"User login -> Database timeout -> Error handling -> Retry -> Response sent\"}, \"BASE\": {\"trace123\": \"User login -> Database query -> Response sent\"}}" + } + ] + } + ] +} +``` + +### Log pattern difference analysis + +The following example uses the OpenSearch Dashboards sample web logs. To add the sample web logs, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). When you add sample data, OpenSearch Dashboards shifts its timestamps relative to the date you add it, so your copy doesn't contain the 2018 dates used in this example. Replace `2018-07-22` with the date of the earliest timestamp returned by the preceding aggregation. + +To perform a pattern comparison analysis, provide a `baseTimeRangeStart` and `baseTimeRangeEnd`: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "opensearch_dashboards_sample_data_logs", + "timeField": "@timestamp", + "logFieldName": "message", + "baseTimeRangeStart": "2018-07-22 00:00:00", + "baseTimeRangeEnd": "2018-07-22 12:00:00", + "selectionTimeRangeStart": "2018-07-22 12:00:00", + "selectionTimeRangeEnd": "2018-07-22 23:59:59" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns patterns with significant frequency changes between time periods. The `base` and `selection` fields contain the fraction of logs that match the pattern in the baseline and selection time ranges, and `lift` is the ratio of the larger fraction to the smaller one. The tool returns patterns whose `lift` is greater than 3 and patterns that appear only in the selection time range. A pattern that appears only in the selection time range has a `base` of `0.0` and a `lift` of `null`, as in the following response: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"patternMapDifference\":[{\"pattern\":\"<*IP*> - - [<*DATETIME*>] \\\"GET <*> HTTP/<*>\\\" <*> 0 \\\"-\\\" \\\"Mozilla/<*> (<*>; Linux <*>_<*>; rv:<*>) Gecko/<*> Firefox/<*>\\\"\",\"base\":0.0,\"selection\":0.4224137931034483,\"lift\":null},{\"pattern\":\"<*IP*> - - [<*DATETIME*>] \\\"GET <*> HTTP/<*>\\\" 200 <*> \\\"-\\\" \\\"Mozilla/<*> (compatible; MSIE 6<*>; Windows NT 5<*>; <*>; .NET CLR 1<*>)\\\"\",\"base\":0.0,\"selection\":0.27586206896551724,\"lift\":null}]}" + } + ] + } + ] +} +``` + +### Log insights analysis + +To perform an error pattern detection, provide only a selection time range: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "application_logs", + "timeField": "@timestamp", + "logFieldName": "message", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns error patterns with sample logs: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"logInsights\":[{\"pattern\":\"<*DATETIME*> ERROR User <*> authentication failed\",\"count\":23.0,\"sampleLogs\":[\"2025-01-15 10:30:15 ERROR User user123 authentication failed\",\"2025-01-15 10:32:08 ERROR User admin456 authentication failed\",\"2025-01-15 10:35:42 ERROR User user789 authentication failed\"]}]}" + } + ] + } + ] +} +``` + +## Execute parameters + +The following table lists the available tool parameters for running the agent. + +| Parameter | Type | Required/Optional | Description | +|:----------|:-----|:------------------|:------------| +| `index` | String | Required | The name of the OpenSearch index containing log data (for example, `ss4o_logs-otel-2025.06.24`). | +| `timeField` | String | Optional | A date/time field in the index mapping used for time-based filtering. Default is `@timestamp`. | +| `logFieldName` | String | Optional | The field containing raw log messages to analyze (for example, `body`, `message`, or `log`). Default is `message`. | +| `traceFieldName` | String | Optional | The field containing a trace ID or correlation ID to enable sequence analysis (for example, `traceId` or `correlationId`). Required for the log sequence analysis mode. | +| `baseTimeRangeStart` | String | Optional | The start time for the baseline comparison period, in UTC date string format (for example, `2025-06-24 07:33:05`). Required for the sequence and pattern difference analysis modes. | +| `baseTimeRangeEnd` | String | Optional | The end time for the baseline comparison period, in UTC date string format (for example, `2025-06-24 07:51:27`). Required for the sequence and pattern difference analysis modes. | +| `selectionTimeRangeStart` | String | Required | The start time for the analysis target period, in UTC date string format (for example, `2025-06-24 07:50:26`). | +| `selectionTimeRangeEnd` | String | Required | The end time for the analysis target period, in UTC date string format (for example, `2025-06-24 07:55:56`). | +| `filter` | String | Optional | A PPL Boolean expression that filters the logs before analysis (for example, `severity='ERROR'`). The tool applies it as an additional `where` clause. Not applied in the log sequence analysis mode, which requires all logs in a trace. | + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. + +## Limitations + +The Log Pattern Analysis tool has the following limitations: + +- **Log volume**: The tool processes logs through PPL queries with a maximum limit of 10,000 documents per query. For optimal performance, limit analysis to specific time ranges. +- **Result limits**: + - Pattern difference analysis: Returns up to 10 patterns with the highest `lift` and up to 10 patterns that appear only in the selection time range. + - Log insights analysis: Returns the top 5 error patterns, with up to 5 sample logs each. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/log-pattern-tool.md b/_ml-commons-plugin/agents-tools/tools/log-pattern-tool.md new file mode 100644 index 00000000..74e01589 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/log-pattern-tool.md @@ -0,0 +1,127 @@ +--- +layout: default +title: Log Pattern tool +has_children: false +has_toc: false +nav_order: 37 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Log Pattern tool +**Introduced 2.19** +{: .label .label-purple } +<!-- vale on --> + +The `LogPatternTool` analyzes log data retrieved using [query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/) or [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) queries to extract and identify recurring structural patterns across log messages. After grouping similar logs based on their shared templates, it returns the most common patterns. Each pattern includes representative sample logs and the total count of log entries that match the pattern in your dataset. + +OpenSearch determines whether you're using a DSL or PPL query based on the presence of the `input` or `ppl` parameter in the request: + +- If the `input` parameter (a DSL query JSON as a string) is present, the tool interprets the request as a DSL query. + +- If the `ppl` parameter is present and `input` is not, the tool interprets the request as a PPL query. + +- If both are provided, the tool will prioritize the DSL query. + +To avoid ambiguity, provide only one of the two---`input` for DSL or `ppl` for PPL---in your request when you run the agent. + +## Step 1: Register a flow agent that will run the LogPatternTool + +A flow agent runs a sequence of tools in order, returning the last tool's output. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Log_Pattern_Tool", + "type": "flow", + "description": "this is a test agent for the LogPatternTool", + "tools": [ + { + "type": "LogPatternTool", + "parameters": { + "sample_log_size": 1 + } + } + ] +} +``` +{% include copy-curl.html %} + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "OQutgJYBAc35E4_KvI1q" +} +``` + +## Step 2: Run the agent + +The following example searches the OpenSearch Dashboards sample web logs. To add the sample web logs, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). The query doesn't filter by time, so it returns the patterns shown in the example response regardless of when you add the sample data. To run the example on your own logs, change the `index` and the query. + +Run the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "input": "{\"query\":{\"bool\":{\"filter\":[{\"range\":{\"bytes\":{\"from\":10,\"to\":null,\"include_lower\":true,\"include_upper\":true,\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}", + "index": "opensearch_dashboards_sample_data_logs" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns a JSON response containing the most common log patterns found in your data, up to the specified limit. Each identified pattern is represented as a JSON object with three key components: the pattern template, a set of representative sample logs that match the pattern, and a count indicating how often the pattern appears in your dataset. The structure follows the format `{"pattern": "...", "sample logs": [...], "total count": N}`, as illustrated in the following example response: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result":"""[{"pattern":"<*IP*> - - [<*DATETIME*>] "GET <*> HTTP/<*><*>\" 200 <*> \"-\" \"Mozilla/<*><*> (<*>; Linux <*>_<*>; rv:<*><*><*>) Gecko/<*> Firefox/<*><*><*>\"","sample logs":["223.87.60.27 - - [2018-07-22T00:39:02.912Z] \"GET /opensearch/opensearch-1.0.0.deb_1 HTTP/1.1\" 200 6219 \"-\" \"Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1\""],"total count":367},{"pattern":"<*IP*> - - [<*DATETIME*>] \"GET <*> HTTP/<*><*>\" 200 <*> \"-\" \"Mozilla/<*><*> (<*>; Linux <*>) AppleWebKit/<*><*> (KHTML like Gecko) Chrome<*IP*> Safari/<*><*>\"","sample logs":["216.9.22.134 - - [2018-07-22T05:27:11.939Z] \"GET /beats/metricbeat_1 HTTP/1.1\" 200 3629 \"-\" \"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24\""],"total count":311},{"pattern":"<*IP*> - - [<*DATETIME*>] \"GET <*> HTTP/<*><*>\" 200 <*> \"-\" \"Mozilla/<*><*> (compatible; MSIE 6<*>; Windows NT 5<*>; <*>; .NET CLR 1<*><*>)\"","sample logs":["99.74.118.237 - - [2018-07-22T03:34:43.399Z] \"GET /beats/metricbeat/metricbeat-6.3.2-amd64.deb_1 HTTP/1.1\" 200 14113 \"-\" \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\""],"total count":269}]""" + } + ] + } + ] +} +``` + +## Register parameters + +The following table lists the available tool parameters for agent registration. + +| Parameter | Type | Required/Optional | Description | +|:-----------------|:---------|:-------------------------------------------------|:------------| +| `index` | String | Required for DSL queries | The index to search for pattern analysis. | +| `input` | String | Required for DSL queries | A DSL query JSON as a string. If both `input` and `ppl` are provided, `input` (DSL) is used. | +| `ppl` | String | Required for PPL queries | A PPL query string. Ignored if `input` is also provided. | +| `source_field` | String | Optional | The field(s) to return in the result. Can be a single field or an array (for example, `["field1", "field2"]`). | +| `doc_size` | Integer | Optional | The number of documents to fetch. Default is `1000`. | +| `top_n_pattern` | Integer | Optional | Limits the output to the specified number of most frequent patterns. Default is `3`. | +| `sample_log_size`| Integer | Optional | The number of sample logs to include per pattern. Default is `20`. | +| `pattern_field` | String | Optional | The field to analyze for pattern detection. If not specified, the tool selects the longest text field from the first document. | +| `variable_count_threshold` | Integer | Optional | The threshold used by the log parser to identify variable tokens when grouping logs into patterns. Default is `5`. | + + +## Execute parameters + +The following table lists the available tool parameters for running the agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- |:-----------------------| :--- +| `index` | String | Required for DSL queries | The index to search for pattern analysis. | +| `input` | String | Required for DSL queries | A DSL query JSON as a string. If both `input` and `ppl` are provided, `input` (DSL) takes precedence. | +| `ppl` | String | Required for PPL queries | A PPL query string. Ignored if `input` is also provided. | +| `top_n_pattern` | Integer | Optional | Limits the output to the specified number of most frequent patterns. Overrides the value set during registration. | +| `sample_log_size` | Integer | Optional | The number of sample logs to include per pattern. Overrides the value set during registration. | +| `pattern_field` | String | Optional | The field to analyze for pattern detection. Overrides the value set during registration. | + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/ml-model-tool.md b/_ml-commons-plugin/agents-tools/tools/ml-model-tool.md index c0f8aeab..5a4aeee6 100644 --- a/_ml-commons-plugin/agents-tools/tools/ml-model-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/ml-model-tool.md @@ -10,14 +10,11 @@ grand_parent: Agents and tools <!-- vale off --> # ML Model tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - -The `MLModelTool` runs a machine learning (ML) model and returns inference results. +The `MLModelTool` runs a machine learning (ML) model and returns inference results. ## Step 1: Create a connector for a model @@ -102,7 +99,7 @@ POST /_plugins/_ml/agents/_register "description": "A general tool to answer any question", "parameters": { "model_id": "h5AUWo0BkIylWTeYT4SU", - "prompt": "\n\nHuman:You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\nHuman:${parameters.question}\n\nAssistant:" + "prompt": "You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\nQuestion: ${parameters.question}" } } ] @@ -167,4 +164,8 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- -`question` | String | Required | The natural language question to send to the LLM. \ No newline at end of file +`question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/neural-sparse-tool.md b/_ml-commons-plugin/agents-tools/tools/neural-sparse-tool.md index bc1fd484..bc3326ea 100644 --- a/_ml-commons-plugin/agents-tools/tools/neural-sparse-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/neural-sparse-tool.md @@ -10,26 +10,23 @@ grand_parent: Agents and tools <!-- vale off --> # Neural Sparse Search tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `NeuralSparseSearchTool` performs sparse vector retrieval. For more information about neural sparse search, see [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). ## Step 1: Register and deploy a sparse encoding model OpenSearch supports several pretrained sparse encoding models. You can either use one of those models or your own custom model. For a list of supported pretrained models, see [Sparse encoding models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#sparse-encoding-models). For more information, see [OpenSearch-provided pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/) and [Custom local models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). -In this example, you'll use the `amazon/neural-sparse/opensearch-neural-sparse-encoding-v1` pretrained model for both ingestion and search. To register and deploy the model to OpenSearch, send the following request: +In this example, you'll use the `amazon/neural-sparse/opensearch-neural-sparse-encoding-v2-distill` pretrained model for both ingestion and search. To register the model and deploy it to OpenSearch, send the following request: ```json POST /_plugins/_ml/models/_register?deploy=true { - "name": "amazon/neural-sparse/opensearch-neural-sparse-encoding-v1", - "version": "1.0.1", + "name": "amazon/neural-sparse/opensearch-neural-sparse-encoding-v2-distill", + "version": "1.0.0", "model_format": "TORCH_SCRIPT" } ``` @@ -44,7 +41,7 @@ OpenSearch responds with a task ID for the model registration and deployment tas } ``` -You can monitor the status of the task by calling the Tasks API: +You can monitor the status of the task by calling the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): ```json GET _plugins/_ml/tasks/M_9KY40Bk4MTqirc5lP8 @@ -168,9 +165,7 @@ OpenSearch responds with an agent ID: ## Step 4: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample web logs` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). - -Then, run the agent by sending the following request: +Run the agent by sending the following request: ```json POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute @@ -215,6 +210,7 @@ Parameter | Type | Required/Optional | Description `name` | String | Optional | The tool name. Useful when an LLM needs to select an appropriate tool for a task. `description` | String | Optional | A description of the tool. Useful when an LLM needs to select an appropriate tool for a task. `doc_size` | Integer | Optional | The number of documents to fetch. Default is `2`. +`nested_path` | String | Optional | The path to the nested object for the nested query. Only used for nested fields. Default is `null`. ## Execute parameters @@ -223,3 +219,8 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/ppl-tool.md b/_ml-commons-plugin/agents-tools/tools/ppl-tool.md index f153ca88..0c649352 100644 --- a/_ml-commons-plugin/agents-tools/tools/ppl-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/ppl-tool.md @@ -9,13 +9,10 @@ grand_parent: Agents and tools --- # PPL tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - -The `PPLTool` translates natural language into a PPL query. The tool provides an `execute` flag to specify whether to run the query. If you set the flag to `true`, the `PPLTool` runs the query and returns the query and the results. +The `PPLTool` translates natural language into a Piped Processing Language (PPL) query. The tool provides an `execute` flag to specify whether to run the query. If you set the flag to `true`, the `PPLTool` runs the query and returns the query and the results. ## Prerequisite @@ -102,9 +99,6 @@ POST /_plugins/_ml/agents/_register "name": "Test_Agent_For_PPL", "type": "flow", "description": "this is a test agent", - "memory": { - "type": "demo" - }, "tools": [ { "type": "PPLTool", @@ -133,7 +127,7 @@ OpenSearch responds with an agent ID: ## Step 4: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample web logs` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). +Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample web logs` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). Then, run the agent by sending the following request: @@ -190,7 +184,7 @@ The following table lists all tool parameters that are available when registerin Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `model_id` | String | Required | The model ID of the large language model (LLM) to use for translating text into a PPL query. -`model_type` | String | Optional | The model type. Valid values are `CLAUDE` (Anthropic Claude model), `OPENAI` (OpenAI models), and `FINETUNE` (custom fine-tuned model). +`model_type` | String | Optional | The model type. Valid values are `CLAUDE` (Anthropic Claude model), `OPENAI` (OpenAI models), and `FINETUNE` (custom fine-tuned model). Default is `CLAUDE`. `prompt` | String | Optional | The prompt to provide to the LLM. `execute` | Boolean | Optional | Specifies whether to run the PPL query. Default is `true`. `input` | Object | Optional | Contains two parameters that specify the index to search and the question for the LLM. For example, `"input": "{\"index\": \"${parameters.index}\", \"question\": ${parameters.question} }"`. @@ -204,4 +198,8 @@ Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `index` | String | Required | The index on which to run the PPL query. `question` | String | Required | The natural language question to send to the LLM. -`verbose` | Boolean | Optional | Whether to provide verbose output. Default is `false`. \ No newline at end of file +`verbose` | Boolean | Optional | Whether to provide verbose output. Default is `false`. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/query-planning-tool.md b/_ml-commons-plugin/agents-tools/tools/query-planning-tool.md new file mode 100644 index 00000000..1ae34d78 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/query-planning-tool.md @@ -0,0 +1,738 @@ +--- +layout: default +title: Query Planning tool +has_children: false +has_toc: false +nav_order: 50 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Query Planning tool +**Introduced 3.3** +{: .label .label-purple } +<!-- vale on --> + +The `QueryPlanningTool` generates an OpenSearch query domain-specific language (DSL) query from a natural language question. It is a core component of [agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/), which enables natural language query processing through agent-driven workflows. + +The `QueryPlanningTool` supports two approaches for generating DSL queries from natural language questions: + +- **Using LLM knowledge only (default)**: The large language model (LLM) generates queries using only its training knowledge and any system/user prompts you provide. This approach relies entirely on the model's understanding of DSL syntax and your specific prompting instructions. + +- **Using search templates**: The LLM uses predefined search templates as additional context when generating queries. You provide a collection of search templates with descriptions, and the LLM uses these as examples and guidance to create more accurate queries. If the LLM determines that none of the provided templates are suitable for the user's question, the LLM attempts to generate the query independently. + +Using search templates is particularly useful when you have established query patterns for your specific use case or domain: it helps the LLM to generate queries that follow your preferred structure and to use appropriate field names from your index mappings. + +## Step 1: Create an index and ingest sample data + +First, create an index for the `iris` dataset: + +```json +PUT /iris-index +{ + "mappings": { + "properties": { + "petal_length_in_cm": { + "type": "float" + }, + "petal_width_in_cm": { + "type": "float" + }, + "sepal_length_in_cm": { + "type": "float" + }, + "sepal_width_in_cm": { + "type": "float" + }, + "species": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Next, ingest sample documents into the index: + +```json +POST _bulk +{ "index": { "_index": "iris-index", "_id": "1" } } +{ "petal_length_in_cm": 1.4, "petal_width_in_cm": 0.2, "sepal_length_in_cm": 5.1, "sepal_width_in_cm": 3.5, "species": "setosa" } +{ "index": { "_index": "iris-index", "_id": "2" } } +{ "petal_length_in_cm": 4.5, "petal_width_in_cm": 1.5, "sepal_length_in_cm": 6.4, "sepal_width_in_cm": 2.9, "species": "versicolor" } +{ "index": { "_index": "iris-index", "_id": "3" } } +{ "petal_length_in_cm": 6.0, "petal_width_in_cm": 2.5, "sepal_length_in_cm": 5.9, "sepal_width_in_cm": 3.0, "species": "virginica" } +``` +{% include copy-curl.html %} + +## Step 2: Register and deploy a model + +The following request registers a remote model from Amazon Bedrock and deploys it to your cluster. The API call creates the connector and model in one step. Replace the `region`, `access_key`, `secret_key`, and `session_token` with your own values. You can use any model that supports the `converse` API, such as [Anthropic Claude 4](https://www.anthropic.com/news/claude-4) or [GPT 5](https://openai.com/index/introducing-gpt-5). You can use other model providers by creating a connector to this model (see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/)). + +**Important**: When creating connectors for the `QueryPlanningTool`, the request body must include the `system_prompt` and `user_prompt` parameters. These parameters are required for the tool to properly inject the system and user prompts into the model's request. + +The following example registers and deploys the Anthropic Claude 4 model: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Claude 4 Sonnet Query Planner Tool Model", + "function_name": "remote", + "description": "Claude 4 sonnet for Query Planning", + "connector": { + "name": "Bedrock Claude 4 Sonnet Connector", + "description": "Amazon Bedrock connector for Claude 4 Sonnet", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-20250514-v1:0" + }, + "credential": { + "access_key": "your-aws-access-key", + "secret_key": "your-aws-secret-key", + "session_token": "your-aws-session-token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.user_prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] + } +} +``` +{% include copy-curl.html %} + +The following example registers and deploys the OpenAI GPT 5 model: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "My OpenAI model: gpt-5", + "function_name": "remote", + "description": "test model", + "connector": { + "name": "My openai connector: gpt-5", + "description": "The connector to openai chat model", + "version": 1, + "protocol": "http", + "parameters": { + "model": "gpt-5" + }, + "credential": { + "openAI_key": "your-openai-api-key" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.user_prompt}\"}${parameters._interactions:-}], \"reasoning_effort\":\"low\"${parameters.tool_configs:-}}" + } + ] + } +} +``` +{% include copy-curl.html %} + +OpenSearch responds with the model ID: + +```json +{ + "task_id": "_9iSxJgBOh0h20Y9XYTH", + "status": "CREATED", + "model_id": "ANiSxJgBOh0h20Y9XYXl" +} +``` + +## Step 3: Register an agent + +You can use any [OpenSearch agent type]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/) to run the `QueryPlanningTool`. The following example uses a `flow` agent, which runs a sequence of tools in order and returns the last tool's output. + +### Using LLM knowledge only + +To use prompts only, don't specify the `generation_type`, so it defaults to `llmGenerated`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Agentic Search with Claude 4", + "type": "flow", + "description": "A test agent for query planning.", + "tools": [ + { + "type": "QueryPlanningTool", + "parameters": { + "model_id": "ANiSxJgBOh0h20Y9XYXl", + "response_filter": "$.output.message.content[0].text" + } + } + ] +} +``` +{% include copy-curl.html %} + +The `response_filter` parameter extracts the generated query from the model response. Without it, the tool returns the full model response, which a search pipeline can't use as a query. This example uses the filter for Anthropic Claude models called through the Amazon Bedrock Converse API. For an OpenAI model, use `$.choices[0].message.content`. For more information, see [Response filter configuration](#response-filter-configuration). + +The tool sets the `system_prompt` and `user_prompt` parameters itself, so values for these parameters provided during agent registration are not used. To customize the prompts, specify `query_planner_system_prompt` and `query_planner_user_prompt`. For more information, see [Customizing the prompts](#customizing-the-prompts). + +### Using search templates + +You can add [search templates]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/index/) as additional context to assist the LLM in OpenSearch DSL generation. + +With this approach, the LLM still writes the full query. To have the LLM fill only the template parameters while OpenSearch renders the query, see [Filling search templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/index/). +{: .tip} + +First, create the search templates: + +```json +POST /_scripts/flower_species_search_template +{ + "script": { + "lang": "mustache", + "source": { + "from": "{% raw %} {{from}}{{^from}}0{{/from}} {% endraw %} ", + "size": "{% raw %} {{size}}{{^size}}10{{/size}} {% endraw %} ", + "query": { + "match": { + "species": "{% raw %} {{species}} {% endraw %} " + } + } + } + } +} +``` +{% include copy-curl.html %} + +```json +POST /_scripts/flower_petal_length_range_template +{ + "script": { + "lang": "mustache", + "source": { + "from": "{% raw %} {{from}}{{^from}}0{{/from}} {% endraw %} ", + "size": "{% raw %} {{size}}{{^size}}10{{/size}} {% endraw %} ", + "query": { + "range": { + "petal_length_in_cm": { + "gte": "{% raw %} {{min_length}} {% endraw %} ", + "lte": "{% raw %} {{max_length}} {% endraw %} " + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Next, register an agent with `generation_type` set to `user_templates` and provide the `template_id` and `template_description` for each template in the `search_templates` parameter: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Agentic Search with Claude 4", + "type": "flow", + "description": "A test agent for query planning.", + "tools": [ + { + "type": "QueryPlanningTool", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "ANiSxJgBOh0h20Y9XYXl", + "response_filter": "$.output.message.content[0].text", + "generation_type": "user_templates", + "search_templates": [ + { + "template_id": "flower_species_search_template", + "template_description": "This template searches for flowers that match the given species using a match query." + }, + { + "template_id": "flower_petal_length_range_template", + "template_description": "This template searches for flowers within a specific petal length range using a range query." + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The LLM uses the `template_description` as the only context to help it choose the best template to use when generating an OpenSearch DSL query based on the user-provided `question`. Make sure to provide a good description of the templates to help the LLM make appropriate choices. Note that the LLM doesn't directly populate template variables or render the template; instead, it analyzes the template's query structure and uses it as a guide to generate a new, contextually appropriate OpenSearch DSL query. + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "RNjQi5gBOh0h20Y9-RX1" +} +``` + +## Step 4: Execute the agent + +Execute the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/RNjQi5gBOh0h20Y9-RX1/_execute +{ + "parameters": { + "question": "How many iris flowers of type setosa are there?", + "index_name": "iris-index" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the inference results, which include the generated query DSL: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"size\":0,\"query\":{\"term\":{\"species.keyword\":\"setosa\"}},\"aggs\":{\"count_setosa\":{\"value_count\":{\"field\":\"species.keyword\"}}}}" + } + ] + } + ] +} +``` + +## Register parameters + +The following table lists all tool parameters that are available when registering an agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`model_id` | String | Required | The model ID of the LLM used to generate the query DSL. When used within a `conversational` agent, if this value is not provided, the agent's own `llm.model_id` is used by default. +`response_filter` | String | Optional | A JSONPath expression used to extract the generated query from the LLM response. If not specified, the tool returns the full LLM response. Specify this parameter when running the tool in a `flow` agent. See [Response filter configuration](#response-filter-configuration). +`generation_type` | String | Optional | Determines how queries are generated. Use `llmGenerated` to rely solely on the LLM built-in knowledge or `user_templates` to provide predefined search templates that guide query generation for consistent results. Default is `llmGenerated`. +`query_planner_system_prompt` | String | Optional | A system prompt that provides high-level instructions to the LLM. +`query_planner_user_prompt` | String | Optional | A user prompt template that defines how the natural language question and context are presented to the LLM for query generation. +`search_templates` | Array | Optional | Applicable only when `generation_type` is `user_templates`. A list of search templates that provide the LLM with predefined query patterns for generating query DSL. Each template must include a `template_id` (unique identifier) and `template_description` (explains the template's purpose and use case to help the LLM choose appropriately). +`template_selection_system_prompt` | String | Optional | Applicable only when `generation_type` is `user_templates`. A system prompt that instructs the LLM how to choose a search template from `search_templates`. If not specified, the tool uses a default template selection prompt. +`template_selection_user_prompt` | String | Optional | Applicable only when `generation_type` is `user_templates`. A user prompt that presents the question and the available search templates to the LLM for template selection. If not specified, the tool uses a default template selection prompt. +`fallback_query` | String | Optional | An OpenSearch query DSL query used if the LLM fails to generate a valid DSL query for the given query text. See [Fallback behavior](#fallback-behavior). + +All parameters that were configured either in the connector or in the agent registration can be overridden during agent execution. +{: .note} + +## Response filter configuration + +The `response_filter` parameter uses JSONPath expressions to extract the generated query from the LLM response. Different model providers return responses in different formats, so you need to specify the appropriate filter for your model type. + +**OpenAI models**: + +```json +"response_filter": "$.choices[0].message.content" +``` +{% include copy.html %} + +**Anthropic Claude models (Amazon Bedrock Converse API)**: + +```json +"response_filter": "$.output.message.content[0].text" +``` +{% include copy.html %} + +## Execute parameters + +The `QueryPlanningTool` accepts the following execution parameters. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`question` | String | Required | A complete natural language query with all necessary context to generate OpenSearch DSL. Include the question, any specific requirements, filters, or constraints. Examples: `Find all products with price greater than 100 dollars`, `Show me documents about machine learning published in 2023`, `Search for users with status active and age between 25 and 35`. +`index_name` | String | Required | The name of the index for which the query needs to be generated. +`embedding_model_id` | String | Optional | The model ID used to perform semantic search. +`query_fields` | String | Optional | The fields that the LLM should prioritize when generating the query. Passed to the LLM through the `${parameters.query_fields}` placeholder in the default user prompt. + +## Customizing the prompts + +You can provide your own `query_planner_system_prompt` and `query_planner_user_prompt` to customize how the LLM generates OpenSearch DSL queries. + +When creating custom prompts, ensure that they include clear output formatting rules so that they work properly with agentic search. The system prompt should specify that the LLM must return only a valid JSON object without any additional text, code fences, or explanations. +{: .important} + +**Custom prompt configuration**: +Provide your custom prompts during tool registration in agents as follows: +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Flow Agent for Agentic Search", + "type": "flow", + "description": "Flow agent for agentic search", + "tools": [ + { + "type": "QueryPlanningTool", + "parameters": { + "model_id": "your_model_id", + "response_filter": "<response-filter-based-on-model-type>", + "query_planner_system_prompt": "<YOUR CUSTOM SYSTEM PROMPT>", + "query_planner_user_prompt": "<YOUR CUSTOM USER PROMPT>" + } + } + ] +} +``` +{% include copy-curl.html %} + +Use the appropriate `response_filter` based on your model type. For more information and examples, see [Response filter configuration](#response-filter-configuration). +{: .note} + +The following is the default system prompt: + +<details open markdown="block"> + <summary> + Prompt + </summary> + {: .text-delta} + +```json +==== PURPOSE ==== +You are an OpenSearch DSL expert. Convert a natural-language question into a strict JSON OpenSearch query body. + +==== RULES ==== +Use only fields present in the provided mapping; never invent names. +Choose query types based on user intent and field types: + +match: single-token full-text on analyzed text fields. + +match_phrase: multi-token phrases on analyzed text fields (search string contains spaces, hyphens, commas, etc.). + +multi_match: when multiple analyzed text fields are equally relevant. + +term / terms: exact match on keyword, numeric, boolean. + +range: numeric/date comparisons (gt, lt, gte, lte). + +bool with must, should, must_not, filter: AND/OR/NOT logic. + +wildcard / prefix on keyword: "starts with" / pattern matching. + +exists: field presence/absence. + +nested query / nested agg: ONLY if the mapping for that exact path (or a parent) has "type":"nested". + +neural: semantic similarity on a 'semantic' or 'knn_vector' field (dense). Use "query_text" and "k"; include "model_id" unless bound in mapping. + +neural (top-level): allowed when it's the only relevance clause needed; otherwise wrap in a bool when combining with filters/other queries. + +Mechanics: + +Put exact constraints (term, terms, range, exists, prefix, wildcard) in bool.filter (non-scoring). Put full-text relevance (match, match_phrase, multi_match) in bool.must. + +Top N items/products/documents: return top hits (set "size": N as an integer) and sort by the relevant metric(s). Do not use aggregations for item lists. + +Neural retrieval size: set "k" ≥ "size" (e.g. heuristic, k = max(size*5, 100) and k<=ef_search). + +Spelling tolerance: match_phrase does NOT support fuzziness; use match or multi_match with "fuzziness": "AUTO" when tolerant matching is needed. + +Text operators (OR vs AND): default to OR for natural-language queries; to tighten, use minimum_should_match (e.g., "75%"). Use AND only when every token is essential; if order/adjacency matters, use match_phrase. + +Numeric note: use ONLY integers for size and k (not floats). + +Aggregations (counts, averages, grouped summaries, distributions): + +Use aggregations when the user asks for grouped summaries (e.g., counts by category, averages by brand, or top N categories/brands). + +terms on field.keyword or numeric for grouping / top N groups (not items). + +Metric aggs (avg, min, max, sum, stats, cardinality) on numeric fields. + +date_histogram, histogram, range for distributions. + +Always set "size": 0 when only aggregations are needed. + +Use sub-aggregations + order for "top N groups by metric". + +If grouping/filtering exactly on a text field, use its .keyword sub-field when present. + +DATE RULES + +Use range on date/date_nanos in bool.filter. + +Emit ISO 8601 UTC ('Z') bounds; don't set time_zone for explicit UTC. (now is UTC) + +Date math: now±N{y|M|w|d|h|m|s}. + +Rounding: "/UNIT" floors to start (now/d, now/w, now/M, now/y). + +End boundaries: prefer the next unit’s start. + +Formats: only add "format" when inputs aren’t default; epoch_millis allowed. + +Buckets: use date_histogram with calendar_interval or fixed_interval. + +NEURAL / SEMANTIC SEARCH +When to use: conceptual/semantic intent, or when user asks for semantic/neural/vector/embedding search. +When not to use: purely structured/exact queries, or when no semantic/knn_vector field or model_id is available. +How to query: + +Use the "neural" clause against the chosen field. + +Required: "query_text" and "k". + +Model rules: + +For "semantic" fields, omit model_id unless overriding. + +For "knn_vector", include model_id unless default is bound. + +If no model id, do not generate neural clause. + +Top-level allowed if no filters/other queries. Otherwise wrap in bool with filters in bool.filter. + +Size: set "k" ≥ "size" (heuristic: k = max(size*5, 100)). + +FIELD SELECTION & PROXYING +Goal: pick the smallest set of mapping fields that best capture the user's intent. + +When provided, and present in the mapping, prioritize query_fields. + +Proxy Rule: If at least one field is loosely related, proceed with the best proxy; do NOT fallback to match_all due to ambiguity. + +Steps: harvest candidates, pick mapping fields, ignore irrelevant ones. + +Micro Self-Check: verify fields exist; if not, swap to proxies. Only if no relevant fields exist at all, fallback to match_all. + +==== OUTPUT FORMAT ==== + +Return EXACTLY ONE JSON object (valid OpenSearch request body). + +No escapes, no code fences, no quotes around the whole object. + +If nothing relevant exists, return exactly: +{"size":10,"query":{"match_all":{}}} + +==== EXAMPLES ==== +(Then follows Examples 1–13 exactly as in your original text, but without escapes.) + +==== TEMPLATE USE ==== +Use this search template provided by the user as reference to generate the query: ${parameters.template} +Note that this template might contain terms that are not relevant to the question at hand; in that case ignore the template. +``` + +</details> + +The following is the default user prompt: + +```json +Question: ${parameters.question} +Index: ${parameters.index_name} +Mapping: ${parameters.index_mapping:-} +Query Fields: ${parameters.query_fields:-} +Sample Document from index: ${parameters.sample_document:-} +In UTC: ${parameters.current_time:-} format: yyyy-MM-dd'T'HH:mm:ss'Z' +Embedding Model ID for Neural Search: ${parameters.embedding_model_id:- not provided} + +==== OUTPUT ==== +GIVE THE OUTPUT PART ONLY IN YOUR RESPONSE (a single JSON object) +Output: +``` + +## Fallback behavior + +The `QueryPlanningTool` uses a fallback query when the LLM fails to generate valid query DSL. By default, the fallback query is `{"size":10,"query":{"match_all":{}}}`. You can override this default by specifying a custom `fallback_query` parameter when registering the agent. + +The tool automatically extracts the first valid JSON object from the LLM response, even if the JSON is surrounded by additional text, Markdown code fences, explanations, or other content. However, if no valid JSON can be extracted from the response (for example, when the response is completely empty, contains only non-JSON text, or contains only malformed JSON), the tool returns the fallback query (either the default or your custom query). + +When the fallback is triggered, no error is thrown. Instead, a debug log is shown in the system logs. This ensures that query planning operations continue to work even when the LLM provides unexpected output. + +### Overriding the default fallback query + +The following example demonstrates how the fallback query operates. + +To follow this example, first complete Steps 1--3 from the [Agentic search tutorial]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/): create an index, ingest data, and register a model. + +Next, register an agent using the model ID from Step 3. Include a custom `fallback_query` parameter to demonstrate the fallback behavior, and set `response_filter` for your model type (see [Response filter configuration](#response-filter-configuration)): + +```json +POST _plugins/_ml/agents/_register +{ + "name": "Iris Search Agent with Fallback", + "type": "flow", + "tools": [ + { + "type": "QueryPlanningTool", + "parameters": { + "model_id": "<your-model-id>", + "response_filter": "<response-filter-based-on-model-type>", + "fallback_query": "{\"size\":10,\"query\":{\"bool\":{\"should\":[{\"match\":{\"species\":{\"query\":\"${parameters.question}\",\"fuzziness\":\"AUTO\"}}},{\"match_all\":{\"boost\":0.1}}],\"minimum_should_match\":1}}}" + } + } + ] +} +``` +{% include copy-curl.html %} + +Next, create a search pipeline using the agent ID from the previous step: + +```json +PUT _search/pipeline/agentic_search_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "<your-agent-id>" + } + } + ], + "response_processors": [ + { + "agentic_context": { + "dsl_query": true + } + } + ] +} +``` +{% include copy-curl.html %} + +To test the fallback behavior, send a search request with a question unrelated to the `iris-index`: + +```json +POST /iris-index/_search?search_pipeline=agentic_search_pipeline&pretty +{ + "query": { + "agentic": { + "query_text": "Find all employees hired in 2023 with salary above 100000" + } + } +} +``` +{% include copy-curl.html %} + +The response includes the `dsl_query` field in the `ext` section containing the fallback query: + +```json +{ + "took" : 5396, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.1, + "hits" : [ + { + "_index" : "iris-index", + "_id" : "1", + "_score" : 0.1, + "_source" : { + "petal_length_in_cm" : 1.4, + "petal_width_in_cm" : 0.2, + "sepal_length_in_cm" : 5.1, + "sepal_width_in_cm" : 3.5, + "species" : "setosa" + } + }, + { + "_index" : "iris-index", + "_id" : "2", + "_score" : 0.1, + "_source" : { + "petal_length_in_cm" : 4.5, + "petal_width_in_cm" : 1.5, + "sepal_length_in_cm" : 6.4, + "sepal_width_in_cm" : 2.9, + "species" : "versicolor" + } + } + ] + }, + "ext" : { + "dsl_query" : "{\"size\":10,\"query\":{\"bool\":{\"should\":[{\"match\":{\"species\":{\"query\":\"Find all employees hired in 2023 with salary above 100000\",\"fuzziness\":\"AUTO\"}}},{\"match_all\":{\"boost\":0.1}}],\"minimum_should_match\":1}}}" + } +} +``` + +Next, ask a question related to the `iris-index`: + +```json +POST /iris-index/_search?search_pipeline=agentic_search_pipeline +{ + "query": { + "agentic": { + "query_text": "Find all setosa species" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the proper LLM-generated query instead of using the fallback query: + +```json +{ + "took" : 4037, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "iris-index", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "petal_length_in_cm" : 1.4, + "petal_width_in_cm" : 0.2, + "sepal_length_in_cm" : 5.1, + "sepal_width_in_cm" : 3.5, + "species" : "setosa" + } + } + ] + }, + "ext" : { + "dsl_query" : "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"species.keyword\":\"setosa\"}}]}}}" + } +} +``` + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. + +## Related documentation + +- [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index) diff --git a/_ml-commons-plugin/agents-tools/tools/rag-tool.md b/_ml-commons-plugin/agents-tools/tools/rag-tool.md index ae3ad128..437b973e 100644 --- a/_ml-commons-plugin/agents-tools/tools/rag-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/rag-tool.md @@ -10,20 +10,17 @@ grand_parent: Agents and tools <!-- vale off --> # RAG tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `RAGTool` performs retrieval-augmented generation (RAG). For more information about RAG, see [Conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/). RAG calls a large language model (LLM) and supplements its knowledge by providing relevant OpenSearch documents along with the user question. To retrieve relevant documents from an OpenSearch index, you'll need a text embedding model that facilitates vector search. The RAG tool supports the following search methods: -- [Neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/): Dense vector retrieval, which uses a text embedding model. +- [Semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/semantic-search/): Dense vector retrieval, which uses a text embedding model. - [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/): Sparse vector retrieval, which uses a sparse encoding model. ## Before you start @@ -36,7 +33,7 @@ The following example uses neural search. To configure neural sparse search and ## Step 1: Register a flow agent that will run the RAGTool <!-- vale on --> -A flow agent runs a sequence of tools in order and returns the last tool's output. To create a flow agent, send the following request, providing the text embedding model ID in the `embedding_model_id` parameter and the LLM model ID in the `inference_model_id` parameter: +A flow agent runs a sequence of tools in order and returns the last tool's output. Content generation is enabled by default, so the `RAGTool` sends the retrieved documents and the question to the LLM. To create a flow agent, send the following request, providing the text embedding model ID in the `embedding_model_id` parameter and the LLM model ID in the `inference_model_id` parameter: ```json POST /_plugins/_ml/agents/_register @@ -58,7 +55,7 @@ POST /_plugins/_ml/agents/_register "text" ], "input": "${parameters.question}", - "prompt": "\n\nHuman:You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\n Context:\n${parameters.output_field}\n\nHuman:${parameters.question}\n\nAssistant:" + "prompt": "You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\nContext:\n${parameters.output_field}\n\nQuestion: ${parameters.question}" } } ] @@ -76,13 +73,11 @@ OpenSearch responds with an agent ID: } ``` -To create a conversational agent containing a `RAGTool`, see [Conversational agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/index/#conversational-agents). +To create a conversational agent containing a `RAGTool`, see [Conversational agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/). ## Step 2: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample web logs` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). - -Then, run the agent by sending the following request: +Run the agent by sending the following request: ```json POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute @@ -94,7 +89,7 @@ POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute ``` {% include copy-curl.html %} -OpenSearch performs vector search and returns the relevant documents: +OpenSearch performs vector search, sends the retrieved documents and the question to the LLM, and returns the LLM response: ```json { @@ -103,17 +98,75 @@ OpenSearch performs vector search and returns the relevant documents: "output": [ { "name": "response", - "result": """{"_index":"my_test_data","_source":{"text":"Chart and table of population level and growth rate for the Seattle metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\n - The current metro area population of Seattle in 2023 is 3,519,000, a 0.86% increase from 2022.\\n - The metro area population of Seattle in 2022 was 3,489,000, a 0.81% increase from 2021.\\n - The metro area population of Seattle in 2021 was 3,461,000, a 0.82% increase from 2020.\\n - The metro area population of Seattle in 2020 was 3,433,000, a 0.79% increase from 2019."},"_id":"6","_score":0.8173238} - {"_index":"my_test_data","_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.\\n - The current metro area population of New York City in 2023 is 18,937,000, a 0.37% increase from 2022.\\n - The metro area population of New York City in 2022 was 18,867,000, a 0.23% increase from 2021.\\n - The metro area population of New York City in 2021 was 18,823,000, a 0.1% increase from 2020.\\n - The metro area population of New York City in 2020 was 18,804,000, a 0.01% decline from 2019."},"_id":"2","_score":0.6641471} - """ + "result": "Using the context, Seattle's metro area population was:\n\n- 2021: 3,461,000\n- 2023: 3,519,000\n\n**Increase from 2021 to 2023:** 3,519,000 − 3,461,000 = **58,000 people**\n\nThat is about a 1.68% increase over the two years (58,000 ÷ 3,461,000)." + } + ] + } + ] +} +``` + +## Step 3 (Optional): Return the retrieved documents without content generation + +To return the retrieved documents without calling the LLM, set `enable_content_generation` to `false` in the tool parameters. The LLM parameters `inference_model_id` and `prompt` are not needed in this case. Register a flow agent by sending the following request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_RagTool_Search_Only", + "type": "flow", + "description": "this is a test flow agent", + "tools": [ + { + "type": "RAGTool", + "description": "A description of the tool", + "parameters": { + "embedding_model_id": "Hv_PY40Bk4MTqircAVmm", + "index": "my_test_data", + "embedding_field": "embedding", + "query_type": "neural", + "source_field": [ + "text" + ], + "input": "${parameters.question}", + "enable_content_generation": false + } + } +] +} +``` +{% include copy-curl.html %} + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "Gn8yWI0Bpc3sThaJeZ2k" +} +``` + +Run the agent using the same question: + +```json +POST /_plugins/_ml/agents/Gn8yWI0Bpc3sThaJeZ2k/_execute +{ + "parameters": { + "question": "what's the population increase of Seattle from 2021 to 2023" + } +} +``` +{% include copy-curl.html %} + +The `result` field contains the retrieved documents, one search hit per line: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"_index\":\"my_test_data\",\"_source\":{\"text\":\"Chart and table of population level and growth rate for the Seattle metro area from 1950 to 2023. United Nations population projections are also included through the year 2035.\\\\nThe current metro area population of Seattle in 2023 is 3,519,000, a 0.86% increase from 2022.\\\\nThe metro area population of Seattle in 2022 was 3,489,000, a 0.81% increase from 2021.\\\\nThe metro area population of Seattle in 2021 was 3,461,000, a 0.82% increase from 2020.\\\\nThe metro area population of Seattle in 2020 was 3,433,000, a 0.79% increase from 2019.\"},\"_id\":\"6\",\"_score\":0.8882475}\n{\"_index\":\"my_test_data\",\"_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.\"},\"_id\":\"2\",\"_score\":0.7471547}\n" } ] } @@ -128,17 +181,17 @@ The following table lists all tool parameters that are available when registerin Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `embedding_model_id` | String | Required | The model ID of the model to use for generating vector embeddings. -`inference_model_id` | String | Required | The model ID of the LLM to use for inference. +`inference_model_id` | String | Required if `enable_content_generation` is `true` | The model ID of the LLM to use for inference. `index` | String | Required | The index from which to retrieve relevant documents to pass to the LLM. -`embedding_field` | String | Required | When the model encodes raw text documents, the encoding result is saved in a field. Specify this field as the `embedding_field`. Neural search matches documents to the query by calculating the similarity score between the query text and the text in the document's `embedding_field`. +`embedding_field` | String | Required | When the model encodes raw text documents, the encoding result is saved in a field. Specify this field as the `embedding_field`. OpenSearch matches documents to the query by calculating the similarity score between the query text and the text in the document's `embedding_field`. `source_field` | String | Required | The document field or fields to return. You can provide a list of multiple fields as an array of strings, for example, `["field1", "field2"]`. `input` | String | Required for flow agent | Runtime input sourced from flow agent parameters. If using an LLM, this field is populated with the LLM response. -`output_field` | String | Optional | The name of the output field. Default is `response`. -`query_type` | String | Optional | Specifies the type of query to run to perform neural search. Valid values are `neural` (for dense retrieval) and `neural_sparse` (for sparse retrieval). Default is `neural`. +`query_type` | String | Optional | Specifies the type of query to run. Valid values are `neural` (for dense retrieval) and `neural_sparse` (for sparse retrieval). Default is `neural`. `doc_size` | Integer | Optional | The number of documents to fetch. Default is `2`. -`prompt` | String | Optional | The prompt to provide to the LLM. -`k` | Integer | Optional | The number of nearest neighbors to search for when performing neural search. Default is 10. -`enable_Content_Generation` | Boolean | Optional | If `true`, returns results generated by an LLM. If `false`, returns results directly without LLM-assisted content generation. Default is `true`. +`prompt` | String | Optional | The prompt to provide to the LLM. To insert the retrieved documents into the prompt, use the `${parameters.output_field}` placeholder. +`k` | Integer | Optional | The number of nearest neighbors to search for. Default is `10`. +`enable_content_generation` | Boolean | Optional | If `true`, returns results generated by an LLM. If `false`, returns results directly without LLM-assisted content generation. Default is `true`. +`nested_path` | String | Optional | The path to the nested object for the nested query. Only used for nested fields. Default is `null`. ## Execute parameters @@ -146,4 +199,8 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- -`question` | String | Required | The natural language question to send to the LLM. \ No newline at end of file +`question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/scratchpad-tools.md b/_ml-commons-plugin/agents-tools/tools/scratchpad-tools.md new file mode 100644 index 00000000..abc5ee66 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/scratchpad-tools.md @@ -0,0 +1,353 @@ +--- +layout: default +title: Scratchpad tools +has_children: false +has_toc: false +nav_order: 60 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Scratchpad tools +**Introduced 3.3** +{: .label .label-purple } +<!-- vale on --> + +The scratchpad tools consist of `WriteToScratchPadTool` and `ReadFromScratchPadTool`, which enable agents to store and retrieve intermediate thoughts and results during runtime. These tools serve as temporary memory for a single agent execution session, allowing agents to take notes and store important findings during tool executions. + +The scratchpad acts as runtime memory that persists only during a single agent execution. When you call the agent's `_execute` API, a new scratchpad is created for that session. All notes and data, except `persistent_notes`, are cleared when the execution completes, ensuring each execution starts with a fresh scratchpad. +{: .important} + +## Use cases + +- **Task decomposition**: Store research plans, intermediate findings, and progress notes during multi-step operations within a single execution. +- **Temporary state management**: Maintain context and accumulated knowledge during the current agent execution session. +- **Multi-step workflows**: Save key findings after searches to build comprehensive responses in complex tasks. +- **Execution planning**: Store and reference step-by-step plans during complex operations. + +## Scratchpad lifecycle + +The scratchpad follows a simple lifecycle: + +1. **Creation**: A new, empty scratchpad is created when an agent execution begins. +2. **Usage**: During execution, the agent can read from and write to the scratchpad multiple times. +3. **Cleanup**: The scratchpad is automatically cleared when execution completes. + +Each call to the agent's `_execute` API creates a fresh scratchpad, ensuring executions are isolated from each other. + +## Best practices + +- **Structured notes**: Encourage agents to maintain organized, structured notes in the scratchpad. +- **Regular updates**: Have agents update the scratchpad after each significant step or finding. +- **Session awareness**: Remember that scratchpad content is temporary and specific to the current execution. +- **Efficient usage**: Use the scratchpad for intermediate results that need to be referenced multiple times during execution. + +## Example: Building a research agent with scratchpad tools + +Use the following steps to build a research agent with scratchpad tools. + +### Step 1: Register and deploy a model + +Register a conversational model that supports the agent framework. The following example uses Anthropic Claude: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Claude Sonnet for Research Agent", + "function_name": "remote", + "description": "Claude model for research agent with scratchpad", + "connector": { + "name": "Bedrock Claude Sonnet Connector", + "description": "Amazon Bedrock connector for Claude Sonnet", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "credential": { + "access_key": "${AWS_ACCESS_KEY_ID}", + "secret_key": "${AWS_SECRET_ACCESS_KEY}", + "session_token": "${AWS_SESSION_TOKEN}" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": """{"system": [{"text": "${parameters.system_prompt}"}], "messages": [${parameters._chat_history:-}{"role":"user","content":[{"text":"${parameters.prompt}"}]}${parameters._interactions:-}]${parameters.tool_configs:-}, "inferenceConfig": {"maxTokens": 8000, "temperature": 0}}""" + } + ] + } +} +``` +{% include copy-curl.html %} + +### Step 2: Register an agent with scratchpad tools + +Register a conversational agent that includes both scratchpad tools and other research tools: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research Agent with Scratchpad", + "type": "conversational", + "description": "Research assistant with persistent scratchpad memory", + "app_type": "rag", + "llm": { + "model_id": "<your-model-id>", + "parameters": { + "max_iteration": 50, + "system_prompt": "You are a sophisticated research assistant with access to OpenSearch indices and a persistent scratchpad for note-taking.\n\nYour Research Workflow:\n1. Check Scratchpad: Before starting a new research task, check your scratchpad to see if you have any relevant information already saved\n2. Create Research Plan: Create a structured research plan\n3. Write to Scratchpad: Save the research plan and any important information to your scratchpad\n4. Use Search: Gather information using OpenSearch search queries\n5. Update Scratchpad: After each search, update your scratchpad with new findings\n6. Iterate: Repeat searching and updating until you have comprehensive information\n7. Complete Task: Provide a thorough response based on your accumulated research\n\nRemember: Your scratchpad is temporary memory for this execution session only. Use it to organize your thoughts and findings during this task.", + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "bedrock/converse/claude" + }, + "tools": [ + { + "type": "SearchIndexTool" + }, + { + "type": "ListIndexTool" + }, + { + "type": "IndexMappingTool" + }, + { + "type": "ReadFromScratchPadTool", + "name": "ReadFromScratchPadTool", + "parameters": { + "persistent_notes": "You are a helpful researcher. Before making searches, use the ListIndexTool to discover available indices. Write down important notes after using tools." + } + }, + { + "type": "WriteToScratchPadTool", + "name": "WriteToScratchPadTool" + } + ] +} +``` +{% include copy-curl.html %} + +### Step 3: Execute the agent + +Execute the agent with a research question: + +```json +POST /_plugins/_ml/agents/{your-agent-id}/_execute?async=true +{ + "parameters": { + "question": "How many residents are in New York?" + } +} +``` +{% include copy-curl.html %} + + +The agent will: +1. Read from its scratchpad to check for existing relevant information (starts empty for new executions). +2. Create and save a research plan to the scratchpad. +3. Execute searches and update the scratchpad with findings. +4. Provide a comprehensive answer based on accumulated research. + +Because the request specifies `async=true`, OpenSearch returns a task ID without waiting for the agent to finish. The response also contains the `memory_id` and `parent_interaction_id`: + +```json +{ + "task_id": "pfztP6EBqoCArR_TRGp7", + "status": "RUNNING", + "response": { + "memory_id": "o_ztP6EBqoCArR_TRGpJ", + "parent_interaction_id": "pPztP6EBqoCArR_TRGpo" + } +} +``` + +Note the `parent_interaction_id` for later tracing steps. For more information, see [Viewing scratchpad activity](#viewing-scratchpad-activity). + +To get the agent's answer, send a [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/) request using the `task_id`. When the task `state` is `COMPLETED`, the task `response` contains the agent's `inference_results`. + +## Tool parameters + +The following are the parameters for the scratchpad tools. + +### ReadFromScratchPadTool + +The following are the **registration parameters** used when adding to an agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`persistent_notes` | String | Optional | Initial notes or instructions to store in the scratchpad when first created. + +The following are the **execution parameters** used when calling the tool directly. + +Parameter | Type | Required/Optional | Description +:--- | :--- |:------------------| :--- +`persistent_notes` | String | Optional | Initial notes or instructions to store in the scratchpad. + +### WriteToScratchPadTool + +The following **registration parameters** are used when adding to an agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`return_history` | Boolean | Optional | When set to `true`, returns the full scratchpad content after writing. When `false` or omitted (default), returns the newly added note with confirmation. + +The following **execution parameters** are used when calling the tool directly. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`notes` | String | Required | The content to write to the scratchpad. +`return_history` | Boolean | Optional | When set to `true`, returns the full scratchpad content after writing. When `false` or omitted (default), returns the newly added note with confirmation. + + +## Testing the tools + +You can use the Tools API directly to execute both scratchpad tools and test their responses before registering them with your agents. + +### Testing the ReadFromScratchPadTool + +```json +POST /_plugins/_ml/tools/_execute/ReadFromScratchPadTool +{ + "parameters": { + "persistent_notes": "You are a helpful researcher to conduct searches in OpenSearch cluster. Before making the search, please remember to use the listIndexTool to figure out what are the available indices first. When using listIndexTool, remember the index name has to be in an array format. Please write down important notes after tool used." + } +} +``` +{% include copy-curl.html %} + +When provided `persistent_notes`, the tool attempts to show the persistent notes in the response: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """Notes from scratchpad: +- You are a helpful researcher to conduct searches in OpenSearch cluster. Before making the search, please remember to use the listIndexTool to figure out what are the available indices first. When using listIndexTool, remember the index name has to be in an array format. Please write down important notes after tool used.""" + } + ] + } + ] +} +``` + +You can also test with an empty `persistent_notes` field: + +```json +POST /_plugins/_ml/tools/_execute/ReadFromScratchPadTool +{ + "parameters": { + "persistent_notes": "" + } +} +``` +{% include copy-curl.html %} + +The response indicates that the scratchpad is empty: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "Scratchpad is empty." + } + ] + } + ] +} +``` + +### Testing the WriteToScratchPadTool + +You can use the Tools API directly to execute the `WriteToScratchPadTool` and test the tool response before registering it with your agents. + +```json +POST /_plugins/_ml/tools/_execute/WriteToScratchPadTool +{ + "parameters": { + "notes": "Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n a. Key architectural upgrades\\n b. New machine learning capabilities, especially ML Commons Agent framework \\n c. Descriptions of major Agent tools added\\n d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n" + } +} +``` +{% include copy-curl.html %} + +The following is the example response from the tool output: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "Wrote to scratchpad: Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n a. Key architectural upgrades\\n b. New machine learning capabilities, especially ML Commons Agent framework \\n c. Descriptions of major Agent tools added\\n d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n" + } + ] + } + ] +} +``` + +You can set the `return_history` parameter to `true` to get the full scratchpad content after writing: + +```json +POST /_plugins/_ml/tools/_execute/WriteToScratchPadTool +{ + "parameters": { + "notes": "Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n a. Key architectural upgrades\\n b. New machine learning capabilities, especially ML Commons Agent framework \\n c. Descriptions of major Agent tools added\\n d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n", + "return_history": true + } +} +``` +{% include copy-curl.html %} + +The response contains the full scratchpad content: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """Scratchpad updated. Full content: +- Research Plan for OpenSearch History and ML Evolution:\n\n1. OpenSearch version history, major releases after v2.0\n2. For each major release:\n a. Key architectural upgrades\n b. New machine learning capabilities, especially ML Commons Agent framework \n c. Descriptions of major Agent tools added\n d. GitHub issue IDs tied to Agent framework features\n3. Look for official OpenSearch documentation, release notes, blogs\n4. Search code repositories for more technical details on ML changes\n""" + } + ] + } + ] +} +``` + +## Viewing scratchpad activity + +You can monitor how the agent uses the scratchpad by examining the execution traces: + +```json +GET /_plugins/_ml/memory/message/{parent_interaction_id}/traces?next_token=0 +``` +{% include copy-curl.html %} + +The traces show the sequence of scratchpad reads and writes, demonstrating how the agent accumulates knowledge during the execution session. + +## Related documentation + +- [Agents and tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/) +- [Conversational agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/) diff --git a/_ml-commons-plugin/agents-tools/tools/search-alerts-tool.md b/_ml-commons-plugin/agents-tools/tools/search-alerts-tool.md index 387ef1cb..b3ec2f22 100644 --- a/_ml-commons-plugin/agents-tools/tools/search-alerts-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/search-alerts-tool.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Search Alerts tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `SearchAlertsTool` retrieves information about generated alerts. For more information about alerts, see [Alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/). ## Step 1: Register a flow agent that will run the SearchAlertsTool @@ -29,9 +26,6 @@ POST /_plugins/_ml/agents/_register "name": "Test_Agent_For_Search_Alerts_Tool", "type": "flow", "description": "this is a test agent for the SearchAlertsTool", - "memory": { - "type": "demo" - }, "tools": [ { "type": "SearchAlertsTool", @@ -76,7 +70,7 @@ OpenSearch responds with a list of generated alerts and the total number of aler "output": [ { "name": "response", - "result": "Alerts=[Alert(id=rv9nYo0Bk4MTqirc_DkW, version=394, schemaVersion=5, monitorId=ZuJnYo0B9RaBCvhuEVux, workflowId=, workflowName=, monitorName=test-monitor-2, monitorVersion=1, monitorUser=User[name=admin, backend_roles=[admin], roles=[own_index, all_access], custom_attribute_names=[], user_requested_tenant=null], triggerId=ZeJnYo0B9RaBCvhuEVul, triggerName=t-1, findingIds=[], relatedDocIds=[], state=ACTIVE, startTime=2024-02-01T02:03:18.420Z, endTime=null, lastNotificationTime=2024-02-01T08:36:18.409Z, acknowledgedTime=null, errorMessage=null, errorHistory=[], severity=1, actionExecutionResults=[], aggregationResultBucket=null, executionId=ZuJnYo0B9RaBCvhuEVux_2024-02-01T02:03:18.404853331_51c18f2c-5923-47c3-b476-0f5a66c6319b, associatedAlertIds=[])]TotalAlerts=1" + "result": "Alerts=[Alert(id=rv9nYo0Bk4MTqirc_DkW, version=394, schemaVersion=6, monitorId=ZuJnYo0B9RaBCvhuEVux, workflowId=, workflowName=, monitorName=test-monitor-2, monitorVersion=1, monitorUser=User[name=admin, backend_roles=[admin], roles=[own_index, all_access], custom_attribute_names=[], user_requested_tenant=null, user_requested_tenant_access=null], triggerId=ZeJnYo0B9RaBCvhuEVul, triggerName=t-1, findingIds=[], relatedDocIds=[], state=ACTIVE, startTime=2024-02-01T02:03:18.420Z, endTime=null, lastNotificationTime=2024-02-01T08:36:18.409Z, acknowledgedTime=null, errorMessage=null, errorHistory=[], severity=1, actionExecutionResults=[], aggregationResultBucket=null, executionId=ZuJnYo0B9RaBCvhuEVux_2024-02-01T02:03:18.404853331_51c18f2c-5923-47c3-b476-0f5a66c6319b, associatedAlertIds=[], clusters=null, query=null, queryResults=[], target=null)]TotalAlerts=1" } ] } @@ -108,7 +102,9 @@ The following table lists all tool parameters that are available when registerin Parameter | Type | Description :--- | :--- | :--- `alertIds` | Array | The ID of the alert to search for. -`monitorId` | String | The name of the monitor by which to filter the alerts. +`alertIndex` | String | The name of the alert index to search (default is `null`). +`monitorId` | String | The ID of the monitor by which to filter the alerts. +`monitorIds` | Array | A list of monitor IDs by which to filter the alerts. `workflowIds` | Array | A list of workflow IDs by which to filter the alerts. `alertState` | String | The alert state by which to filter the alerts. Valid values are `ALL`, `ACTIVE`, `ERROR`, `COMPLETED`, and `ACKNOWLEDGED`. Default is `ALL`. `severityLevel` | String| The severity level by which to filter the alerts. Valid values are `ALL`, `1`, `2`, and `3`. Default is `ALL`. @@ -125,3 +121,7 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/search-anomaly-detectors.md b/_ml-commons-plugin/agents-tools/tools/search-anomaly-detectors.md index de93a404..654ed703 100644 --- a/_ml-commons-plugin/agents-tools/tools/search-anomaly-detectors.md +++ b/_ml-commons-plugin/agents-tools/tools/search-anomaly-detectors.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Search Anomaly Detectors tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `SearchAnomalyDetectorsTool` retrieves information about anomaly detectors set up on your cluster. For more information about anomaly detectors, see [Anomaly detection]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/). ## Step 1: Register a flow agent that will run the SearchAnomalyDetectorsTool @@ -29,9 +26,6 @@ POST /_plugins/_ml/agents/_register "name": "Test_Agent_For_Search_Anomaly_Detectors_Tool", "type": "flow", "description": "this is a test agent for the SearchAnomalyDetectorsTool", - "memory": { - "type": "demo" - }, "tools": [ { "type": "SearchAnomalyDetectorsTool", @@ -95,12 +89,11 @@ Parameter | Type | Description `indices` | String | The index name or index pattern of the indexes that the returned detectors are using as data sources. `highCardinality` | Boolean | Whether to return information about high-cardinality detectors. Leave this parameter unset (or set it to `null`) to return information about both high-cardinality (multi-entity) and non-high-cardinality (single-entity) detectors. Set this parameter to `true` to only return information about high-cardinality detectors. Set this parameter to `false` to only return information about non-high-cardinality detectors. `lastUpdateTime` | Long | Specifies the earliest last updated time of the detectors to return, in epoch milliseconds. Default is `null`. -`sortOrder` |String | The sort order for the results. Valid values are `asc` (ascending) and `desc` (descending). Default is `desc`. +`sortOrder` |String | The sort order for the results. Valid values are `asc` (ascending) and `desc` (descending). Default is `asc`. `sortString`| String | Specifies the detector field by which to sort the results. Default is `name.keyword`. `size` | Integer | The number of results to return. Default is `20`. `startIndex`| Integer | The paginated index of the detector to start from. Default is `0`. `running`| Boolean | Whether to return information about detectors that are currently running. Leave this parameter unset (or set it to `null`) to return both running and non-running detector information. Set this parameter to `true` to only return information about running detectors. Set this parameter to `false` to return only information about detectors that are not currently running. Default is `null`. -`disabled` | Boolean | Whether to return information about detectors that are currently disabled. Leave this parameter unset (or set it to `null`) to return information about both enabled and disabled detectors. Set this parameter to `true` to return only information about disabled detectors. Set this parameter to `false` to return only information about enabled detectors. Default is `null`. `failed` | Boolean | Whether to return information about detectors that are currently failing. Leave this parameter unset (or set it to `null`) to return information about both failed and non-failed detectors. Set this parameter to `true` to return only information about failed detectors. Set this parameter to `false` to return only information about non-failed detectors. Default is `null`. ## Execute parameters @@ -110,3 +103,7 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/search-anomaly-results.md b/_ml-commons-plugin/agents-tools/tools/search-anomaly-results.md index bce27bba..5b4ff18b 100644 --- a/_ml-commons-plugin/agents-tools/tools/search-anomaly-results.md +++ b/_ml-commons-plugin/agents-tools/tools/search-anomaly-results.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Search Anomaly Results tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `SearchAnomalyResultsTool` retrieves information about anomaly detector results. For more information about anomaly detectors, see [Anomaly detection]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/). ## Step 1: Register a flow agent that will run the SearchAnomalyResultsTool @@ -29,9 +26,6 @@ POST /_plugins/_ml/agents/_register "name": "Test_Agent_For_Search_Anomaly_Results_Tool", "type": "flow", "description": "this is a test agent for the SearchAnomalyResultsTool", - "memory": { - "type": "demo" - }, "tools": [ { "type": "SearchAnomalyResultsTool", @@ -109,10 +103,10 @@ Parameter | Type | Description :--- | :--- | :--- `detectorId` | String | The ID of the detector from which to return results. `realTime` | Boolean | Whether to return real-time anomaly detector results. Set this parameter to `false` to return only historical analysis results. -`anomalyGradeThreshold` | Float | The minimum anomaly grade for the returned anomaly detector results. Anomaly grade is a number between 0 and 1 that indicates how anomalous a data point is. +`anomalyGradeThreshold` | Float | The minimum anomaly grade for the returned anomaly detector results. Anomaly grade is a number between 0 and 1 that indicates how anomalous a data point is. The tool returns only results whose anomaly grade is greater than this value. Default is `0`. `dataStartTime` | Long | The earliest time for which to return anomaly detector results, in epoch milliseconds. `dataEndTime` | Long | The latest time for which to return anomaly detector results, in epoch milliseconds. -`sortOrder` |String | The sort order for the results. Valid values are `asc` (ascending) and `desc` (descending). Default is `desc`. +`sortOrder` |String | The sort order for the results. Valid values are `asc` (ascending) and `desc` (descending). Default is `asc`. `sortString`| String | Specifies the detector field by which to sort the results. Default is `data_start_time`. `size` | Integer | The number of results to return. Default is `20`. `startIndex`| Integer | The paginated index of the result to start from. Default is `0`. @@ -124,3 +118,7 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/search-index-tool.md b/_ml-commons-plugin/agents-tools/tools/search-index-tool.md index 86ecbfc6..72754e08 100644 --- a/_ml-commons-plugin/agents-tools/tools/search-index-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/search-index-tool.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Search Index tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `SearchIndexTool` searches an index using a query written in query domain-specific language (DSL) and returns the query results. ## Step 1: Register a flow agent that will run the SearchIndexTool @@ -29,9 +26,6 @@ POST /_plugins/_ml/agents/_register "name": "Test_Agent_For_Search_Index_Tool", "type": "flow", "description": "this is a test for search index tool", - "memory": { - "type": "demo" - }, "tools": [ { "type": "SearchIndexTool" @@ -51,7 +45,7 @@ OpenSearch responds with an agent ID: ## Step 2: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). +Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). Then, run the agent by sending the following request. The `SearchIndexTool` takes one parameter named `input`. This parameter includes the index name and the query: @@ -114,10 +108,63 @@ OpenSearch returns the query results: } ``` +## Using the tool in a conversational agent + +In a `conversational` agent that uses function calling, the LLM provides the tool input according to the tool's input schema. By default, the input schema requires the LLM to provide the `index` and `query` parameters. To have the LLM provide only a question, specify the index and a query in the tool parameters and define a custom input schema in `attributes.input_schema`. + +The following tool definition runs a `neural` query on the `test_population_data` index. The LLM provides a `question`, which the tool uses as the `query_text`: + +```json +{ + "type": "SearchIndexTool", + "name": "retrieve_population_data", + "description": "This tool provides population data of US cities.", + "parameters": { + "input": "{\"index\": \"${parameters.index}\", \"query\": ${parameters.query} }", + "index": "test_population_data", + "query": { + "query": { + "neural": { + "population_description_embedding": { + "query_text": "${parameters.question}", + "model_id": "your_text_embedding_model_id" + } + } + }, + "size": 2, + "_source": "population_description" + } + }, + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "Natural language question" + } + }, + "required": [ "question" ], + "additionalProperties": false + }, + "strict": false + } +} +``` + +For a complete example, see [Using the Search Index tool with a neural query]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/chatbots/rag-chatbot/#using-the-search-index-tool-with-a-neural-query). + ## Execute parameters -The following table lists all tool parameters that are available when registering an agent. +The following table lists all tool parameters that are available when running the agent. Parameter | Type | Description :--- | :--- | :--- -`input`| String | The index name and the query to use for search, in JSON format. The `index` parameter contains the name of the index and the `query` parameter contains the query formatted in Query DSL. For example, `"{\"index\": \"opensearch_dashboards_sample_data_ecommerce\", \"query\": {\"size\": 22, \"_source\": \"category\"}}"`. The `input` parameter and the `index` and `query` parameters it contains are required. \ No newline at end of file +`input`| String | The index name and the query to use for search, in JSON format. The `index` parameter contains the name of the index, and the `query` parameter contains the query formatted in Query DSL. For example, `"{\"index\": \"opensearch_dashboards_sample_data_ecommerce\", \"query\": {\"size\": 22, \"_source\": \"category\"}}"`. The `input` parameter and the `index` and `query` parameters it contains are required unless you provide the top-level `index` and `query` parameters. +`index` | String | The name of the index to search. Used together with `query` when `input` is not provided. +`query` | String | The search query in Query DSL format, as a JSON string (for example, `"{\"size\": 1, \"_source\": \"email\"}"`). Used together with `index` when `input` is not provided. +`return_raw_response` | Boolean | If `true`, the tool returns the full search response as a JSON object instead of one line per hit. Default is `false`. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/search-monitors-tool.md b/_ml-commons-plugin/agents-tools/tools/search-monitors-tool.md index 2b746d34..84123b34 100644 --- a/_ml-commons-plugin/agents-tools/tools/search-monitors-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/search-monitors-tool.md @@ -10,13 +10,10 @@ grand_parent: Agents and tools <!-- vale off --> # Search Monitors tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - The `SearchMonitorsTool` retrieves information about alerting monitors set up on your cluster. For more information about alerting monitors, see [Monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). ## Step 1: Register a flow agent that will run the SearchMonitorsTool @@ -29,9 +26,6 @@ POST /_plugins/_ml/agents/_register "name": "Test_Agent_For_Search_Monitors_Tool", "type": "flow", "description": "this is a test agent for the SearchMonitorsTool", - "memory": { - "type": "demo" - }, "tools": [ { "type": "SearchMonitorsTool", @@ -114,7 +108,7 @@ Parameter | Type | Description `hasTriggers` | Boolean | Whether to return information about monitors that have triggers enabled. Leave this parameter unset (or set it to `null`) to return information about monitors that have triggers enabled and disabled. Set this parameter to `true` to return only information about monitors with triggers enabled. Set this parameter to `false` to return only information about monitors with triggers disabled. Default is `null`. `indices` | String | The index name or index pattern of the indexes tracked by the returned monitors. `sortOrder`| String | The sort order of the results. Valid values are `asc` (ascending) and `desc` (descending). Default is `asc`. -`sortString`| String | Specifies the monitor field by which to sort the results. Default is `name.keyword`. +`sortString`| String | Specifies the monitor field by which to sort the results. Default is `monitor.name.keyword`. `size` | Integer | The number of results to return. Default is `20`. `startIndex`| Integer | The paginated index of the monitor to start from. Default is `0`. @@ -125,3 +119,7 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/search-template-fill-tool.md b/_ml-commons-plugin/agents-tools/tools/search-template-fill-tool.md new file mode 100644 index 00000000..c8f438b3 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/search-template-fill-tool.md @@ -0,0 +1,134 @@ +--- +layout: default +title: Search Template Fill tool +has_children: false +has_toc: false +nav_order: 105 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Search Template Fill tool +**Introduced 3.10** +{: .label .label-purple } +<!-- vale on --> + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +The `SearchTemplateFillTool` generates an OpenSearch query domain-specific language (DSL) query from a natural language question by filling the parameters of a registered agentic search template. The large language model (LLM) returns only the parameter values, and OpenSearch renders them into the stored Mustache template. The tool falls back to the [`QueryPlanningTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/), which writes the full query, in the following cases: + +- No template in `template_ids` is usable for the index, for example, because no template is registered for the index or every template's parameter schema is empty. +- The LLM sets `cannot_express` to indicate that no template can express the question or chooses no template. +- The LLM response contains no tool call, a value that doesn't match the parameter schema, or a template that isn't a candidate. +- The rendered template isn't a single JSON object. + +If reading the registered templates or the LLM call fails, the tool returns the error without falling back. + +For a complete example, including how to store and register templates, see [Filling search templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/index/). + +## Prerequisites + +Before using the tool, complete the following steps: + +1. Set `plugins.ml_commons.agentic_search_template_enabled` to `true`. The tool isn't available when multi-tenancy is enabled. +1. Store one or more search templates and register each one using the Register Agentic Search Template API. For more information, see [Register Agentic Search Template API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template/). +1. Register an externally hosted model for which the connector `request_body` includes `${parameters.tool_configs:-}`, `${parameters.system_prompt}`, and either `${parameters.user_prompt}` or `${parameters.prompt}`. + +## Step 1: Register a flow agent + +The following example registers a `flow` agent that runs the `SearchTemplateFillTool`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "template-fill-agent", + "type": "flow", + "tools": [ + { + "type": "SearchTemplateFillTool", + "parameters": { + "model_id": "<model_id>", + "_llm_interface": "bedrock/converse/claude", + "response_filter": "$.output.message.content[0].text" + }, + "config": { + "template_ids": "[\"product_search\",\"similar_search\"]" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Step 2: Execute the agent + +Execute the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/<agent_id>/_execute +{ + "parameters": { + "question": "the 2 most expensive footwear shoes", + "index_name": "products" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the rendered query: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"title\":\"shoes\"}}],\"filter\":[{\"term\":{\"category\":\"footwear\"}}]}},\"sort\":[{\"price\":\"desc\"}],\"size\":2}" + } + ] + } + ] +} +``` + +## Register parameters + +The following table lists the parameters that you can set in the tool's `parameters` when registering an agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`model_id` | String | Required | The model ID of the LLM that fills the template. The fallback `QueryPlanningTool` uses the same model. +`_llm_interface` | String | Required | The function calling interface of the model. Valid values are `bedrock/converse/claude`, `openai/v1/chat/completions`, and `gemini/v1beta/generatecontent`. +`response_filter` | String | Optional | A JSONPath expression that extracts the generated query from the LLM response. Used only by the fallback `QueryPlanningTool`. See [Response filter configuration]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/#response-filter-configuration). + +All other parameters are passed to the fallback `QueryPlanningTool`. For example, `fallback_query` and `query_planner_system_prompt` customize the fallback. For more information, see [Query Planning tool register parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/#register-parameters). + +The following table lists the fields that you can set in the tool's `config`. Execute requests can't override these fields, so registering an agent with either field in `parameters` returns an error. + +Field | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`template_ids` | String | Required | The agentic search templates that the agent can fill, as a JSON array of template IDs, for example, `"[\"product_search\"]"`, or as a single template ID. Templates are offered in the listed order. Only templates that are registered for the searched index, have a non-empty parameter schema, and have a stored script that the user can read are used, and at most eight templates are offered. +`fallback_enabled` | String | Optional | Whether the tool falls back to the `QueryPlanningTool` when it can't fill a template. Valid values are `true` and `false`. If `false`, the tool returns an error instead. Default is `true`. + +## Execute parameters + +The following table lists the parameters that you can provide when executing the agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`question` | String | Required | The natural language question. +`index_name` | String | Required | The name of the index to search. Templates registered for other indexes are skipped. + +## Permissions + +When the Security plugin is enabled, the tool reads and renders each stored script as the user running the search, so that user needs the `cluster:admin/script/get` permission. If the user can't read a template's stored script, the tool doesn't offer that template to the LLM. + +## Related documentation + +- [Filling search templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/index/) +- [Agentic search template APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/index/) +- [Query Planning tool]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/) +- [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/) diff --git a/_ml-commons-plugin/agents-tools/tools/vector-db-tool.md b/_ml-commons-plugin/agents-tools/tools/vector-db-tool.md index d8b8083d..5a1102b1 100644 --- a/_ml-commons-plugin/agents-tools/tools/vector-db-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/vector-db-tool.md @@ -10,16 +10,13 @@ grand_parent: Agents and tools <!-- vale off --> # Vector DB tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } <!-- vale on --> -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} +The `VectorDBTool` performs dense vector retrieval. For more information about OpenSearch vector database capabilities, see [Vector search]({{site.url}}{{site.baseurl}}/vector-search/). -The `VectorDBTool` performs dense vector retrieval. For more information about OpenSearch vector database capabilities, see [neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/). - -## Step 1: Register and deploy a sparse encoding model +## Step 1: Register and deploy a text embedding model OpenSearch supports several pretrained models. You can use one of those models, use your own custom model, or create a connector for an externally hosted model. For a list of supported pretrained models, see [OpenSearch-provided pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/). For more information about custom models, see [Custom local models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). For information about integrating an externally hosted model, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). @@ -29,7 +26,7 @@ In this example, you'll use the `huggingface/sentence-transformers/all-MiniLM-L1 POST /_plugins/_ml/models/_register?deploy=true { "name": "huggingface/sentence-transformers/all-MiniLM-L12-v2", - "version": "1.0.1", + "version": "1.0.2", "model_format": "TORCH_SCRIPT" } ``` @@ -44,7 +41,7 @@ OpenSearch responds with a task ID for the model registration and deployment tas } ``` -You can monitor the status of the task by calling the Tasks API: +You can monitor the status of the task by calling the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): ```json GET _plugins/_ml/tasks/M_9KY40Bk4MTqirc5lP8 @@ -70,7 +67,7 @@ Once the model is registered and deployed, the task `state` changes to `COMPLETE ## Step 2: Ingest data into an index -First, you'll set up an ingest pipeline to encode documents using the sparse encoding model set up in the previous step: +First, you'll set up an ingest pipeline to encode documents using the text embedding model set up in the previous step: ```json PUT /_ingest/pipeline/test-pipeline-local-model @@ -102,13 +99,13 @@ PUT my_test_data }, "embedding": { "type": "knn_vector", - "dimension": 384 + "dimension": 384, + "space_type": "cosinesimil" } } }, "settings": { "index": { - "knn.space_type": "cosinesimil", "default_pipeline": "test-pipeline-local-model", "knn": "true" } @@ -174,9 +171,7 @@ OpenSearch responds with an agent ID: ## Step 4: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample web logs` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). - -Then, run the agent by sending the following request: +Run the agent by sending the following request: ```json POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute @@ -222,12 +217,13 @@ The following table lists all tool parameters that are available when registerin Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `model_id` | String | Required | The model ID of the model to use at search time. -`index` | String | Required | The index to search. -`embedding_field` | String | Required | When the model encodes raw text documents, the encoding result is saved in a field. Specify this field as the `embedding_field`. Neural search matches documents to the query by calculating the similarity score between the query text and the text in the document's `embedding_field`. +`index` | String | Required | The index to search. This value can also be provided at runtime by the LLM; runtime values take precedence over registered defaults. +`embedding_field` | String | Required | When the model encodes raw text documents, the encoding result is saved in a field. Specify this field as the `embedding_field`. OpenSearch matches documents to the query by calculating the similarity score between the query text and the text in the document's `embedding_field`. This value can also be provided at runtime by the LLM; runtime values take precedence over registered defaults. `source_field` | String | Required | The document field or fields to return. You can provide a list of multiple fields as an array of strings, for example, `["field1", "field2"]`. `input` | String | Required for flow agent | Runtime input sourced from flow agent parameters. If using a large language model (LLM), this field is populated with the LLM response. `doc_size` | Integer | Optional | The number of documents to fetch. Default is `2`. -`k` | Integer | Optional | The number of nearest neighbors to search for when performing neural search. Default is `10`. +`k` | Integer | Optional | The number of nearest neighbors to search for. Default is `10`. +`nested_path` | String | Optional | The path to the nested object for the nested query. Only used for nested fields. Default is `null`. ## Execute parameters @@ -236,3 +232,7 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/visualization-tool.md b/_ml-commons-plugin/agents-tools/tools/visualization-tool.md index 14072325..a9cce63e 100644 --- a/_ml-commons-plugin/agents-tools/tools/visualization-tool.md +++ b/_ml-commons-plugin/agents-tools/tools/visualization-tool.md @@ -9,13 +9,10 @@ grand_parent: Agents and tools --- # Visualization tool -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - -Use the `VisualizationTool` to find visualizations relevant to a question. +Use the `VisualizationTool` to find visualizations relevant to a question. ## Step 1: Register a flow agent that will run the VisualizationTool @@ -54,7 +51,7 @@ OpenSearch responds with an agent ID: ## Step 2: Run the agent -Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/quickstart#adding-sample-data). +Before you run the agent, make sure that you add the sample OpenSearch Dashboards `Sample eCommerce orders` dataset. To learn more, see [Adding sample data]({{site.url}}{{site.baseurl}}/dashboards/getting-started/data-setup/#add-sample-data). Then, run the agent by sending the following request: @@ -104,3 +101,7 @@ The following table lists all tool parameters that are available when running th Parameter | Type | Required/Optional | Description :--- | :--- | :--- | :--- `question` | String | Required | The natural language question to send to the LLM. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/agents-tools/tools/web-search-tool.md b/_ml-commons-plugin/agents-tools/tools/web-search-tool.md new file mode 100644 index 00000000..a9042926 --- /dev/null +++ b/_ml-commons-plugin/agents-tools/tools/web-search-tool.md @@ -0,0 +1,327 @@ +--- +layout: default +title: Web Search tool +has_children: false +has_toc: false +nav_order: 130 +parent: Tools +grand_parent: Agents and tools +--- + +<!-- vale off --> +# Web Search tool +**Introduced 3.0** +{: .label .label-purple } +<!-- vale on --> + +The `WebSearchTool` retrieves search results based on a user's question. It supports [Google](#using-google-as-a-search-engine), Bing, and [DuckDuckGo](#using-duckduckgo-as-a-search-engine) as search engines or can use a [custom API](#using-a-custom-api-as-a-search-engine) to perform searches. + +## Using DuckDuckGo as a search engine + +To use DuckDuckGo as a search engine with the `WebSearchTool`, follow these steps. + +### Step 1: Register a flow agent that will run the WebSearchTool + +A flow agent runs a sequence of tools in order and returns the last tool's output. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_WebSearch_tool", + "type": "flow", + "description": "this is a test agent for the WebSearchTool", + "tools": [ + { + "type": "WebSearchTool", + "name": "DuckduckgoWebSearchTool", + "parameters": { + "engine": "duckduckgo", + "input": "${parameters.question}" + } + } + ] +} +``` +{% include copy-curl.html %} + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +### Step 2: Run the agent + +Then, run the agent by sending the following request (DuckDuckGo doesn't require any credentials): + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How to create a index pattern in OpenSearch?" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the web search results: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """ + { + "next_page": "https://html.duckduckgo.com/html?q=how+to+create+index+pattern+in+OpenSearch&ia=web&dc=11", + "items": [ + { + "url": "http://someurl", + "title": "the page result title", + "content": "the page content..." + }, + { + "url": "https://anotherurl", + "title": "the page result title", + "content": "the page content..." + } + ... + ] + } + """ + } + ] + } + ] +} +``` + +## Using Google as a search engine + +To use Google as a search engine with the `WebSearchTool`, follow these steps. + +### Step 1: Register a flow agent that will run the WebSearchTool + +A flow agent runs a sequence of tools in order and returns the last tool's output. To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_WebSearch_tool", + "type": "flow", + "description": "this is a test agent for the WebSearchTool", + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleWebSearchTool", + "parameters": { + "engine": "google", + "engine_id": "${your_google_engine_id}", + "api_key": "${your_google_api_key}", + "input": "${parameters.question}" + } + } + ] +} +``` +{% include copy-curl.html %} + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +### Step 2: Run the agent + +Before you run the agent, ensure that you have obtained the credentials needed to access Google search programmatically. + +Then, run the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How to create a index pattern in OpenSearch?" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the web search results: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """ + { + "next_page": "https://customsearch.googleapis.com/customsearch/v1?q=how+to+create+index+pattern+in+OpenSearch&start=10", + "items": [ + { + "url": "http://someurl", + "title": "the page result title", + "content": "the page content..." + }, + { + "url": "https://anotherurl", + "title": "the page result title", + "content": "the page content..." + } + ... + ] + } + """ + } + ] + } + ] +} +``` + +## Using a custom API as a search engine + +To use a custom API as a search engine with the `WebSearchTool`, follow these steps. + +### Step 1: Register a flow agent that will run the WebSearchTool + +To use a custom endpoint for search, you need to configure the following parameters: + +- `Authorization`: For authentication +- `endpoint`: For the API connection +- `custom_res_url_jsonpath`: For parsing the JSON response and extracting links + +Your API must return responses in JSON format. The links returned by the API must be retrievable using [JSONPath](https://en.wikipedia.org/wiki/JSONPath) expressions. Other parameters like `query_key`, `offset_key`, and `limit_key` are optional but should be specified if your API uses different values than the defaults. + +To create a flow agent, send the following register agent request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_WebSearch_tool", + "type": "flow", + "description": "this is a test agent for the WebSearchTool", + "tools": [ + { + "type": "WebSearchTool", + "name": "CustomWebSearchTool", + "parameters": { + "engine": "custom", + "endpoint": "${your_custom_endpoint}", + "custom_res_url_jsonpath": "$.data[*].link", + "Authorization": "Bearer xxxx", + "query_key": "q", + "offset_key": "offset", + "limit_key": "limit" + } + } + ] +} +``` +{% include copy-curl.html %} + +For parameter descriptions, see [Register parameters](#register-parameters). + +OpenSearch responds with an agent ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +### Step 2: Run the agent + +Before you run the agent, ensure that you have obtained the credentials needed to access your custom search API programmatically. + +Then, run the agent by sending the following request: + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How to create a index pattern in OpenSearch?" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the web search results: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """ + { + "next_page": "{your_custom_endpoint}?q=how+to+create+index+pattern+in+OpenSearch&offset=10&limit=10", + "items": [ + { + "url": "http://someurl", + "title": "the page result title", + "content": "the page content..." + }, + { + "url": "https://anotherurl", + "title": "the page result title", + "content": "the page content..." + } + ... + ] + } + """ + } + ] + } + ] +} +``` + + + +## Register parameters + +The following table lists all tool parameters that are available when registering an agent. + + + +| Parameter | Type | Required/Optional | Description | +|:---|:---|:---|:---| +| `engine` | String | Optional | The search engine to use. Valid values are `google`, `bing`, `duckduckgo`, or `custom`. Default is `google`. | +| `engine_id` | String | Optional | The Custom Search Engine ID for Google. Required when `engine` is set to `google`. | +| `api_key` | String | Optional | The API key for authentication. Required when `engine` is set to `google` or `bing`. | +| `endpoint` | String | Optional | The URL endpoint for the custom search API. Required when `engine` is set to `custom`. | +| `Authorization` | String | Optional | The authorization header value for the custom API. Required when `engine` is set to `custom`. | +| `query_key` | String | Optional | The parameter name for the search query in the custom API URL (for example, `${endpoint}?my_query_key=${question}`). Default is `q`. | +| `offset_key` | String | Optional | The parameter name for the pagination offset in the custom API URL (for example, `${endpoint}?q=${question}&start=10`). Default is `offset`. | +| `limit_key` | String | Optional | The parameter name for the result limit in the custom API URL (for example, `${endpoint}?q=${question}&start=10&limit=10`). Default is `limit`. | +| `custom_res_url_jsonpath` | String | Optional | The JSONPath expression used to extract URLs from the custom API response (for example, `$[*].link`). Required when `engine` is set to `custom`. | + +## Execute parameters + +The following table lists all tool parameters that are available when running the agent. + +Parameter | Type | Required/Optional | Description +:--- | :--- | :--- | :--- +`question` | String | Required | The natural language question to send to the LLM. +`next_page` | String | Optional | The URL of the next page of search results, returned in the `next_page` field of a previous response. If provided, the tool returns results from this page instead of running a new search. + +## Testing the tool + +You can run this tool either as part of an agent workflow or independently using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). The Execute Tool API is useful for testing individual tools or performing standalone operations. \ No newline at end of file diff --git a/_ml-commons-plugin/algorithms.md b/_ml-commons-plugin/algorithms.md index d7809d51..05e512be 100644 --- a/_ml-commons-plugin/algorithms.md +++ b/_ml-commons-plugin/algorithms.md @@ -2,12 +2,12 @@ layout: default title: Supported algorithms has_children: false -nav_order: 125 +nav_order: 100 --- # Supported algorithms -ML Commons supports various algorithms to help train and predict machine learning (ML) models or test data-driven predictions without a model. This page outlines the algorithms supported by the ML Commons plugin and the API operations they support. +OpenSearch provides built-in machine learning (ML) algorithms that run natively within your cluster for tasks like anomaly detection, clustering, and predictive analytics. These algorithms allow you to analyze your data directly in OpenSearch without requiring external ML models or services. Each algorithm is optimized for specific use cases, from detecting unusual patterns in metrics to grouping similar data points together. ## Common limitations @@ -52,6 +52,7 @@ POST /_plugins/_ml/_train/kmeans ] } ``` +{% include copy-curl.html %} ### Limitations @@ -59,20 +60,31 @@ The training process supports multithreading, but the number of threads must be ## Linear regression -Linear regression maps the linear relationship between inputs and outputs. In ML Commons, the linear regression algorithm is adopted from the public machine learning library [Tribuo](https://tribuo.org/), which offers multidimensional linear regression models. The model supports the linear optimizer in training, including popular approaches like Linear Decay, SQRT_DECAY, [ADA](https://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf), [ADAM](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/Adam.html), and [RMS_DROP](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/RMSProp.html). +Linear regression maps the linear relationship between inputs and outputs. In ML Commons, the linear regression algorithm is adopted from the public machine learning library [Tribuo](https://tribuo.org/), which offers multidimensional linear regression models. The model supports the linear optimizer in training, including popular approaches like Linear Decay, SQRT_DECAY, [ADA](https://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf), [ADAM](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/Adam.html), and [RMS_PROP](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/RMSProp.html). + +**Optimizers supported:** [SIMPLE_SGD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.html#:~:text=learning%20rate%20SGD.-,getSimpleSGD,-public%20static%C2%A0), [LINEAR_DECAY_SGD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.html#:~:text=linear%20decay%20SGD.-,getLinearDecaySGD,-public%20static%C2%A0), [SQRT_DECAY_SGD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.html#:~:text=sqrt%20decay%20SGD.-,getSqrtDecaySGD,-public%20static%C2%A0), [ADA_GRAD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/AdaGrad.html), [ADA_DELTA](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/AdaDelta.html), [ADAM](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/Adam.html), and [RMS_PROP](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/RMSProp.html). +**Objectives supported:** [ABSOLUTE_LOSS](https://tribuo.org/learn/4.2/javadoc/org/tribuo/regression/sgd/objectives/AbsoluteLoss.html), [HUBER](https://tribuo.org/learn/4.2/javadoc/org/tribuo/regression/sgd/objectives/Huber.html), and [SQUARED_LOSS](https://tribuo.org/learn/4.2/javadoc/org/tribuo/regression/sgd/objectives/SquaredLoss.html). +**momentum_type supported:** [STANDARD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.Momentum.html#STANDARD:~:text=No%20momentum.-,STANDARD,-public%20static%20final) and [NESTEROV](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.Momentum.html#STANDARD:~:text=Standard%20momentum.-,NESTEROV,-public%20static%20final). ### Parameters Parameter | Type | Description | Default value :--- |:--- | :--- | :--- -`learningRate` | Double | The initial step size used in an iterative optimization algorithm. | `0.01` -`momentumFactor` | Double | The extra weight factors that accelerate the rate at which the weight is adjusted. This helps move the minimization routine out of local minima. | `0` +`target` | String | The name of the target variable to predict. Identifies which feature the model will learn to predict during training. | `NA` +`learning_rate` | Double | The initial step size used in an iterative optimization algorithm. | `0.01` +`momentum_factor` | Double | The extra weight factors that accelerate the rate at which the weight is adjusted. This helps move the minimization routine out of local minima. | `0` `epsilon` | Double | The value for stabilizing gradient inversion. | `1.00E-06` `beta1` | Double | The exponential decay rates for the moment estimates. | `0.9` `beta2` | Double | The exponential decay rates for the moment estimates. | `0.99` -`decayRate` | Double | The Root Mean Squared Propagation (RMSProp). | `0.9` -`momentumType` | String | The defined Stochastic Gradient Descent (SGD) momentum type that helps accelerate gradient vectors in the right directions, leading to a fast convergence.| `STANDARD` -`optimizerType` | String | The optimizer used in the model. | `SIMPLE_SGD` +`decay_rate` | Double | The Root Mean Squared Propagation (RMSProp). | `0.9` +`momentum_type` | String | The defined Stochastic Gradient Descent (SGD) momentum type that helps accelerate gradient vectors in the right directions, leading to a fast convergence.| `STANDARD` +`optimiser` | String | The optimizer used in the model. | `ADA_GRAD` +`objective` | String | The objective function used. | `SQUARED_LOSS` +`epochs` | Integer | The number of iterations. | `5`| +`batch_size` | Integer | The minimum batch size. | `1` +`logging_interval` | Integer | The frequency of logging during training iterations. Set to `-1` to disable logging. | `-1` +`seed` | Long | A random seed used for reproducible results. Controls the initialization of random number generators. | `12345` + ### Supported APIs @@ -120,6 +132,7 @@ POST _plugins/_ml/_predict/LINEAR_REGRESSION/ROZs-38Br5eVE0lTsoD9 } } ``` +{% include copy-curl.html %} #### Example response @@ -226,7 +239,6 @@ The following example estimates cluster centers and provides cluster labels for POST _plugins/_ml/_train_predict/RCF_SUMMARIZE { "parameters": { - "centroids": 3, "max_k": 15, "distance_type": "L2" }, @@ -258,6 +270,7 @@ POST _plugins/_ml/_train_predict/RCF_SUMMARIZE } } ``` +{% include copy-curl.html %} #### Example response @@ -277,7 +290,7 @@ The `rows` parameter within the prediction result has been modified for length. { "values": [ { - "column_type": "DOUBLE", + "column_type": "INTEGER", "value": 0 } ] @@ -294,7 +307,7 @@ The Localization algorithm finds subset-level information for aggregate data (fo ### Parameters -All parameters are required except `filter_query` and `anomaly_start`. +All parameters are required except `filter_query` and `anomaly_start_time`. Parameter | Type | Description | Default value :--- | :--- | :--- | :--- @@ -303,11 +316,11 @@ Parameter | Type | Description | Default value `aggregations` | List | The fields and aggregation for values. | N/A `time_field_name` | String | The timestamp field. | `null` `start_time` | Long | The beginning of the time range. | `0` -`end_time` | Long | The end of the time range. | 0`` +`end_time` | Long | The end of the time range. | `0` `min_time_interval` | Long | The minimum time interval/scale for analysis. | `0` `num_outputs` | Integer | The maximum number of values from localization/slicing. | `0` -`filter_query` | Long | (Optional) Reduces the collection of data for analysis. | N/A -anomal`y_star | Time units | (Optional) The time after which the data will be analyzed. | N/A +`filter_query` | Object | (Optional) A query that reduces the collection of data for analysis. | N/A +`anomaly_start_time` | Long | (Optional) The time after which the data will be analyzed. | N/A ### Example: Execute localization @@ -315,7 +328,7 @@ The following example executes Localization against an RCA index. #### Example request -```bash +```json POST /_plugins/_ml/_execute/anomaly_localization { "index_name": "rca-index", @@ -338,6 +351,7 @@ POST /_plugins/_ml/_execute/anomaly_localization "num_outputs": 10 } ``` +{% include copy-curl.html %} #### Example response @@ -412,23 +426,27 @@ The Localization algorithm can only be executed directly. Therefore, it cannot b A classification algorithm, logistic regression models the probability of a discrete outcome given an input variable. In ML Commons, these classifications include both binary and multi-class. The most common is the binary classification, which takes two values, such as "true/false" or "yes/no", and predicts the outcome based on the values specified. Alternatively, a multi-class output can categorize different inputs based on type. This makes logistic regression most useful for situations where you are trying to determine how your inputs fit best into a specified category. +**Optimizers supported:** [SIMPLE_SGD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.html#:~:text=learning%20rate%20SGD.-,getSimpleSGD,-public%20static%C2%A0), [LINEAR_DECAY_SGD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.html#:~:text=linear%20decay%20SGD.-,getLinearDecaySGD,-public%20static%C2%A0), [SQRT_DECAY_SGD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.html#:~:text=sqrt%20decay%20SGD.-,getSqrtDecaySGD,-public%20static%C2%A0), [ADA_GRAD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/AdaGrad.html), [ADA_DELTA](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/AdaDelta.html), [ADAM](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/Adam.html), and [RMS_PROP](https://tribuo.org/learn/4.1/javadoc/org/tribuo/math/optimisers/RMSProp.html). +**Objectives supported:** [HINGE](https://tribuo.org/learn/4.2/javadoc/org/tribuo/classification/sgd/objectives/Hinge.html) and [LOGMULTICLASS](https://tribuo.org/learn/4.2/javadoc/org/tribuo/classification/sgd/objectives/LogMulticlass.html). +**Momentum type supported:** [STANDARD](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.Momentum.html#STANDARD:~:text=No%20momentum.-,STANDARD,-public%20static%20final) and [NESTEROV](https://tribuo.org/learn/4.2/javadoc/org/tribuo/math/optimisers/SGD.Momentum.html#STANDARD:~:text=Standard%20momentum.-,NESTEROV,-public%20static%20final). + ### Parameters | Parameter | Type | Description | Default value | |---|---|---|---| -| `learningRate` | Double | The initial step size used in an iterative optimization algorithm. | `1` | -| `momentumFactor` | Double | The extra weight factors that accelerate the rate at which the weight is adjusted. This helps move the minimization routine out of local minima. | `0` | +| `learning_rate` | Double | The initial step size used in an iterative optimization algorithm. | `1` | +| `momentum_factor` | Double | The extra weight factors that accelerate the rate at which the weight is adjusted. This helps move the minimization routine out of local minima. | `0` | | `epsilon` | Double | The value for stabilizing gradient inversion. | `0.1` | | `beta1` | Double | The exponential decay rates for the moment estimates. | `0.9` | | `beta2` | Double | The exponential decay rates for the moment estimates. | `0.99` | -| `decayRate` | Double | The Root Mean Squared Propagation (RMSProp). | `0.9` | -| `momentumType` | String | The Stochastic Gradient Descent (SGD) momentum that helps accelerate gradient vectors in the right direction, leading to faster convergence between vectors. | `STANDARD` | -| `optimizerType` | String | The optimizer used in the model. | `AdaGrad` | +| `decay_rate` | Double | The Root Mean Squared Propagation (RMSProp). | `0.9` | +| `momentum_type` | String | The Stochastic Gradient Descent (SGD) momentum that helps accelerate gradient vectors in the right directions, leading to a fast convergence. | `STANDARD` | +| `optimiser` | String | The optimizer used in the model. | `ADA_GRAD` | | `target` | String | The target field. | null | -| `objectiveType` | String | The objective function type. | `LogMulticlass` | +| `objective` | String | The objective function type. | `LOGMULTICLASS` | | `epochs` | Integer | The number of iterations. | `5` | -| `batchSize` | Integer | The size of min batches. | `1` | -| `loggingInterval` | Integer | The interval of logs lost after many iterations. The interval is `1` if the algorithm contains no logs. | `1000` | +| `batch_size` | Integer | The minimum batch size. | `1` | +| `logging_interval` | Integer | The interval of logs lost after many iterations. The interval is `1` if the algorithm contains no logs. | `1000` | ### Supported APIs @@ -443,7 +461,7 @@ The following example creates an index in OpenSearch with the [Iris dataset](htt Before using this request, make sure that you have downloaded [Iris data](https://archive.ics.uci.edu/dataset/53/iris). -```bash +```json PUT /iris_data { "mappings": { @@ -467,10 +485,11 @@ PUT /iris_data } } ``` +{% include copy-curl.html %} #### Ingest data from IRIS_data.txt -```bash +```json POST _bulk { "index" : { "_index" : "iris_data" } } {"sepal_length_in_cm":5.1,"sepal_width_in_cm":3.5,"petal_length_in_cm":1.4,"petal_width_in_cm":0.2,"class":"Iris-setosa"} @@ -486,7 +505,8 @@ This example uses a multi-class logistic regression categorization methodology. **Request** -```bash +```json +POST _plugins/_ml/_train/logistic_regression { "parameters": { "target": "class" @@ -509,6 +529,7 @@ This example uses a multi-class logistic regression categorization methodology. ] } ``` +{% include copy-curl.html %} #### Example response @@ -525,8 +546,8 @@ The `model_id` will be used to predict the class of the Iris. Using the `model_id` of the trained Iris dataset, logistic regression will predict the class of the Iris based on the input data. -```bash -POST _plugins/_ml/_predict/logistic_regression/SsfQaoIBEoC4g4joZiyD +```json +POST _plugins/_ml/_predict/logistic_regression/TOgsf4IByBqD7FK_FQGc { "parameters": { "target": "class" @@ -595,6 +616,7 @@ POST _plugins/_ml/_predict/logistic_regression/SsfQaoIBEoC4g4joZiyD } } ``` +{% include copy-curl.html %} #### Example response @@ -651,6 +673,7 @@ PUT /_cluster/settings } } ``` +{% include copy-curl.html %} ### Parameters @@ -658,7 +681,7 @@ To use the metrics correlation algorithm, include the following parameters. | Parameter | Type | Description | Default value | |---|---|---|---| -metrics | Array | A list of metrics within the time series that can be correlated to anomalous behavior | N/A +`metrics` | Array | A list of metrics within the time series that can be correlated to anomalous behavior | N/A ### Input @@ -678,6 +701,7 @@ The following example inputs the number of metrics (M) as 3 and the number of ti POST /_plugins/_ml/_execute/METRICS_CORRELATION {"metrics": [[-1.1635416, -1.5003631, 0.46138194, 0.5308311, -0.83149344, -3.7009873, -3.5463789, 0.22571462, -5.0380244, 0.76588845, 1.236113, 1.8460795, 1.7576948, 0.44893077, 0.7363948, 0.70440894, 0.89451003, 4.2006273, 0.3697659, 2.2458954, -2.302939, -1.7706926, 1.7445002, -1.5246059, 0.07985192, -2.7756078, 1.0002468, 1.5977372, 2.9152713, 1.4172368, -0.26551363, -2.2883027, 1.5882446, 2.0145164, 3.4862874, -1.2486862, -2.4811826, -0.17609037, -2.1095612, -1.2184235, 0.63118523, -1.8909532, 2.039797, -0.5317177, -2.2922578, -2.0179775, -0.07992507, -0.12554549, -0.2553092, 1.1450123, -0.4640453, -2.190223, -4.671612, -1.5076426, 1.635445, -1.1394824, -0.7503817, 0.98424894, -0.38896716, 1.0328646, 1.9543738, -0.5236269, 0.14298044, 3.2963762, 8.1641035, 5.717064, 7.4869685, 2.5987444, 11.018798, 9.151356, 5.7354255, 6.862203, 3.0524514, 4.431755, 5.1481285, 7.9548607, 7.4519925, 6.09533, 7.634116, 8.898271, 3.898491, 9.447067, 8.197385, 5.8284273, 5.804283, 7.7688456, 10.574343, 7.5679493, 7.1888094, 7.1107903, 8.454468, 8.066334, 8.83665, 7.11204, 4.4898267, 8.614764, 6.336754, 11.577503, 3.3998494, 9.501525, 13.17289, 6.1116023, 5.143777, 2.7813284, 3.7917604, 7.1683135, 7.627272, 7.290255, 3.1299121, 7.089733, 9.140584, 8.844729, 9.403275, 10.220029, 8.039719, 8.85549, 4.034555, 4.412663, 7.54451, 7.2116737, 4.6346946, 7.0044127, 9.7557, 10.982841, 5.897937, 6.870126, 3.5638695, 5.7872133], [1.3037996, 2.7976995, -0.12042701, 1.3688855, 1.6955005, -2.2575269, 0.080582514, 3.011721, -0.4320283, 3.2440786, -1.0321085, 1.2346085, -2.3152106, -0.9783513, 0.6837618, 1.5320586, -1.6148578, -0.94538075, 0.55978125, -4.7430468, 3.466028, 2.3792691, 1.3269067, -0.35359794, -1.5547276, 0.5202475, 1.0269136, -1.7531714, 0.43987304, -0.18845831, 2.3086758, 2.519588, 2.0116413, 0.019745048, -0.010070452, 2.496933, 1.1557871, 0.08433053, 1.375894, -1.2135965, -1.2588277, -0.31454003, 0.045949124, -1.7518936, -2.3533764, -2.0125146, 0.10255043, 1.1782314, 2.4579153, -0.8780899, -4.1442213, 3.8300152, 2.772975, 2.6803262, 0.9867382, 0.77618766, 0.46541777, 3.8959959, -2.1713195, 0.10609512, -0.26438138, -2.145317, 3.6734529, 1.4830295, -5.3445525, -10.6427765, -8.300354, -1.9608921, -6.6779685, -10.019544, -8.341513, -9.607174, -7.2441607, -3.411102, -6.180552, -8.318714, -6.060591, -7.790343, -5.9695, -7.9429936, -3.775652, -5.2827606, -3.7168224, -6.729588, -9.761094, -7.4683576, -7.2595067, -6.6790915, -9.832726, -8.352172, -6.936336, -8.252518, -6.787475, -9.091013, -11.465944, -6.712504, -8.987438, -6.946672, -8.877166, -6.7854185, -3.6417139, -6.1036086, -5.360772, -4.0435786, -4.5864973, -6.971063, -10.522461, -6.3692527, -4.387658, -9.723745, -4.7020173, -5.097396, -9.903703, -4.882414, -4.1999683, -6.7829437, -6.2555966, -8.121125, -5.334131, -9.174302, -3.9752126, -4.179469, -8.335524, -9.359406, -6.4938803, -6.794677, -8.382997, -9.879416], [1.8792984, -3.1561708, -0.8443318, -1.998743, -0.6319316, 2.4614046, -0.44511616, 0.82785237, 1.7911717, -1.8172283, 0.46574894, -1.8691323, 3.9586513, 0.8078605, 0.9049874, 5.4086914, -0.7425967, -0.20115769, -1.197923, 2.741789, 0.85432875, -1.1688408, -1.7771784, 1.615249, -4.1103697, 0.4721327, -2.75669, -0.38393462, -3.1137516, -2.2572582, 0.9580673, -3.7139492, -0.68303126, 1.6007807, 0.6313973, -2.5115106, 0.703251, 2.4844077, -1.7405633, -3.007687, 2.372802, 2.4684637, 0.6443977, -3.1433117, 0.05976736, -1.9809214, 3.514713, 2.1880944, 1.242541, 1.8236228, 0.8642841, -0.17313614, 1.7042321, 0.8298376, 4.2443194, 0.13983983, 1.1940852, 2.5076652, 39.285202, 82.73858, 44.707516, -4.267148, 0.25930226, 0.20799652, -3.7213502, 1.475217, -1.2394199, -0.0034497892, 1.1413965, 55.18923, -2.2969518, -4.1400924, -2.4707043, 43.193188, -0.19258368, 3.471275, 1.1374166, 1.2147579, 4.13017, -2.0576499, 2.1529694, -0.28360432, 0.8477302, -0.63012695, 1.2569811, 1.943168, 0.17070436, 3.2358394, -2.3737662, 0.77060974, 4.99065, 3.1079204, 3.6347675, 0.6801177, -2.2205186, 1.0961101, -2.4445753, -2.0919478, -2.895031, 2.5458927, 0.38599384, 1.0492333, -0.081834644, -7.4079595, -2.1785216, -0.7277175, -2.7413428, -3.2083786, 3.2958643, -1.1839997, 5.4849496, 2.0259023, 5.607272, -1.0125756, 3.721461, 2.5715313, 0.7741753, -0.55034757, 0.7526307, -2.6758716, -2.964664, -0.57379586, -0.28817406, -3.2334063, -0.22387607, -2.0793931, -6.4562697, 0.80134094]]} ``` +{% include copy-curl.html %} #### Example response @@ -691,19 +715,16 @@ In the following example response, each item corresponds to an event discovered ```json { - "function_name": "METRICS_CORRELATION", - "output": { - "inference_results": [ - { - "event_window": [ - 52, - 72 - ], - "event_pattern": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.99625e-05, 0.0001052875, 0.0002605894, 0.00064648513, 0.0014303402, 0.002980127, 0.005871893, 0.010885878, 0.01904726, 0.031481907, 0.04920215, 0.07283493, 0.10219432, 0.1361888, 0.17257516, 0.20853643, 0.24082609, 0.26901975, 0.28376183, 0.29364157, 0.29541212, 0.2832976, 0.29041746, 0.2574534, 0.2610143, 0.22938538, 0.19999361, 0.18074994, 0.15539801, 0.13064545, 0.10544432, 0.081248805, 0.05965102, 0.041305058, 0.027082501, 0.01676033, 0.009760197, 0.005362286, 0.0027713624, 0.0013381141, 0.0006126331, 0.0002634901, 0.000106459476, 4.0407333e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - "suspected_metrics": [0,1,2] - } - ] - } + "inference_results": [ + { + "event_window": [ + 52.0, + 72.0 + ], + "event_pattern": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.99625e-05, 0.0001052875, 0.0002605894, 0.00064648513, 0.0014303402, 0.002980127, 0.005871893, 0.010885878, 0.01904726, 0.031481907, 0.04920215, 0.07283493, 0.10219432, 0.1361888, 0.17257516, 0.20853643, 0.24082609, 0.26901975, 0.28376183, 0.29364157, 0.29541212, 0.2832976, 0.29041746, 0.2574534, 0.2610143, 0.22938538, 0.19999361, 0.18074994, 0.15539801, 0.13064545, 0.10544432, 0.081248805, 0.05965102, 0.041305058, 0.027082501, 0.01676033, 0.009760197, 0.005362286, 0.0027713624, 0.0013381141, 0.0006126331, 0.0002634901, 0.000106459476, 4.0407333e-05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + "suspected_metrics": [0,1,2] + } + ] } ``` diff --git a/_ml-commons-plugin/api/agent-apis/delete-agent.md b/_ml-commons-plugin/api/agent-apis/delete-agent.md index 0327c3bf..76ba2f65 100644 --- a/_ml-commons-plugin/api/agent-apis/delete-agent.md +++ b/_ml-commons-plugin/api/agent-apis/delete-agent.md @@ -2,33 +2,38 @@ layout: default title: Delete agent parent: Agent APIs -grand_parent: ML Commons APIs -nav_order: 50 +grand_parent: ML APIs +nav_order: 40 --- -# Delete an agent -**Introduced 2.12** +# Delete Agent API +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - You can use this API to delete an agent based on the `agent_id`. -## Path and HTTP methods +## Endpoints ```json -DELETE /_plugins/_ml/agents/<agent_id> +DELETE /_plugins/_ml/agents/{agent_id} ``` -#### Example request +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `agent_id` | String | The ID of the agent to delete. Required. | + +## Example request ```json DELETE /_plugins/_ml/agents/MzcIJX8BA7mbufL6DOwl ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -36,6 +41,7 @@ DELETE /_plugins/_ml/agents/MzcIJX8BA7mbufL6DOwl "_id" : "MzcIJX8BA7mbufL6DOwl", "_version" : 2, "result" : "deleted", + "forced_refresh" : true, "_shards" : { "total" : 2, "successful" : 2, @@ -44,4 +50,24 @@ DELETE /_plugins/_ml/agents/MzcIJX8BA7mbufL6DOwl "_seq_no" : 27, "_primary_term" : 18 } +``` + +## Error responses + +If you attempt to delete an agent that doesn't exist, OpenSearch returns a 404 error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Fail to find ml agent" + } + ], + "type": "status_exception", + "reason": "Fail to find ml agent" + }, + "status": 404 +} ``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/agent-apis/execute-agent.md b/_ml-commons-plugin/api/agent-apis/execute-agent.md index 8302ac26..79d7b846 100644 --- a/_ml-commons-plugin/api/agent-apis/execute-agent.md +++ b/_ml-commons-plugin/api/agent-apis/execute-agent.md @@ -2,35 +2,55 @@ layout: default title: Execute agent parent: Agent APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 20 --- -# Execute an agent -**Introduced 2.12** +# Execute Agent API +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} +When an agent is executed, it runs the tools with which it is configured. You can execute an agent asynchronously by setting the `async` query parameter to `true`. -When an agent is executed, it runs the tools with which it is configured. +Agents created using the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method) support a standardized `input` field that accepts plain text, multimodal content, or message-based conversations. This requires the `plugins.ml_commons.unified_agent_api_enabled` cluster setting to be enabled. +{: .note} -### Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/agents/<agent_id>/_execute +POST /_plugins/_ml/agents/{agent_id}/_execute ``` -## Request fields +## Query parameters + +The following table lists the available query parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`async` | Boolean | Optional | If `true`, executes the agent asynchronously and returns a `task_id` to track execution. To check the status of the task, use the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/). Default is `false`. + +## Request body fields The following table lists the available request fields. Field | Data type | Required/Optional | Description -:--- | :--- | :--- -`parameters`| Object | Required | The parameters required by the agent. -`parameters.verbose`| Boolean | Optional | Provides verbose output. +:--- | :--- | :--- | :--- +`parameters`| Object | Optional | The parameters required by the agent. Any agent parameters configured during registration can be overridden using this field. Use with the [regular registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +`parameters.question`| String | Optional | The question to ask the agent. Use with the [regular registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). +`parameters.verbose`| Boolean | Optional | Provides verbose output. +`parameters.memory_id` | String | Optional | The memory session ID used to continue an existing conversation. This field is supported for conversational memory backends, including `conversation_index` and `agentic_memory`. To start a new session, omit this parameter. +`parameters.memory_container_id` | String | Optional | Overrides the configured memory container for this execution when the agent uses `agentic_memory`. +`parameters.include_token_usage` | Boolean | Optional | When set to `true`, includes detailed token consumption metrics for each large language model (LLM) call in the response. Supported for `conversational` (v1), `plan-execute-reflect`, and `AG-UI` agents. The `conversational_v2` agent always includes token usage in its response format and does not require this parameter. Default is `false`. See [Tracking token usage](#tracking-token-usage). +`input` | String or Array | Optional | A standardized input field supporting plain text, multimodal content blocks, or message-based conversations. Use with the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method). -#### Example request +> When `conversation_index` or `agentic_memory` is configured, the response includes a `memory_id`. To continue the same session, include the `memory_id` in subsequent requests. Omit the `memory_id` to start a new session. +> +> When using `agentic_memory`, you must also provide a memory container ID. Specify it either during agent registration (`memory.memory_container_id`) or in each request (`parameters.memory_container_id`). If a memory container ID is not provided, the request fails. +{: .note} + +## Regular agent execution + +For agents created using the regular registration method (the [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/) multi-step process), use the `parameters` field: ```json POST /_plugins/_ml/agents/879v9YwBjWKCe6Kg12Tx/_execute @@ -42,7 +62,7 @@ POST /_plugins/_ml/agents/879v9YwBjWKCe6Kg12Tx/_execute ``` {% include copy-curl.html %} -#### Example response +### Example response ```json { @@ -50,6 +70,7 @@ POST /_plugins/_ml/agents/879v9YwBjWKCe6Kg12Tx/_execute { "output": [ { + "name": "MLModelTool", "result": """ Based on the given context, the key information is: The metro area population of Seattle in 2021 was 3,461,000. @@ -65,4 +86,382 @@ Therefore, the population increase of Seattle from 2021 to 2023 is 58,000.""" } ] } -``` \ No newline at end of file +``` + +## Response fields + +The following table lists the base response fields for agent execution. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `inference_results` | Array | Contains the agent's execution results. | +| `inference_results.output` | Array | Contains output objects with name-value pairs. | +| `inference_results.output.name` | String | The output field name. Common values: `response`, `memory_id`, `parent_interaction_id`, `token_usage`. | +| `inference_results.output.result` | String | The output value for simple string results (present when `name` is `memory_id` or `parent_interaction_id`, or the name of a tool whose output a flow agent returns). | +| `inference_results.output.dataAsMap` | Object | The output value for structured results. For a `response` output of a conversational agent, contains the `response` text and an `additional_info` object. For a `token_usage` output, see [Token usage response fields](#token-usage-response-fields). | + +## Unified agent execution +**Introduced 3.5** +{: .label .label-purple } + +For agents created using the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method), use the `input` field. The supported input formats depend on the agent type: + +- **`conversational` and other V1 agent types**: Support plain text input only. +- **`conversational_v2`** (Introduced 3.6): Supports all three input formats — plain text, multimodal content blocks, and message-based conversations. + +### Plain text input + +All unified agents support plain text input. For simple text prompts, pass a string directly to the `input` field: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "input": "What tools do you have access to?" +} +``` +{% include copy-curl.html %} + +#### Example response: Plain text input + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "memory_id", + "result": "iEgpJZwBZx9B0F4spD5v" + }, + { + "name": "response", + "dataAsMap": { + "response": "I have access to the following tools:\n\n1. ListIndexTool - Lists all indices in the cluster\n2. SearchIndexTool - Searches within OpenSearch indices\n3. IndexMappingTool - Retrieves index mapping information", + "additional_info": {} + } + } + ] + } + ] +} +``` + +### Multimodal content blocks + +When using the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method), multimodal content block and message-based inputs require a `conversational_v2` agent. All other unified agent types accept only plain text input. When using the [regular registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#regular-registration-method), multimodal support is possible if the connector is configured to pass multimodal content to the LLM, with the input format determined by the connector configuration. +{: .note} + +For multimodal inputs (text, images, documents), use an array of content blocks: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "input": [ + { + "type": "text", + "text": "What can you see in this image?" + }, + { + "type": "image", + "source": { + "type": "base64", + "format": "png", + "data": "iVBORw0KGgoAAAANSUhEUgAA..." + } + } + ] +} +``` +{% include copy-curl.html %} + +#### Supported content types + +The following table lists the supported content types. + +| Content type | Description | Fields | +| :--- | :--- | :--- | +| `text` | Plain text content | `text`: The text string.| +| `image` | Image data | `source.type`: The source type. Valid value is `base64`. <br>`source.format`: The image format (for example, `jpeg`, `png`, `gif`, or `webp`).<br>`source.data`: Base64-encoded image data. | +| `video` | Video data | `source.type`: The source type. Valid value is `base64`. <br>`source.format`: The video format (for example, `mp4`, `mov`, or `avi`).<br>`source.data`: Base64-encoded video data. | +| `document` | Document data | `source.type`: The source type. Valid value is `base64`. <br>`source.format`: The document format (for example, `pdf`, `docx`, or `txt`).<br>`source.data`: Base64-encoded document data. | + +Content type support depends on the model provider. OpenAI models do not accept `video` or `document` content. + +### Message-based conversations + +For multi-turn conversations, provide an array of messages with roles: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "input": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "I like the color red" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "Thanks for telling me that! I'll remember it." + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "What color do I like?" + } + ] + } + ] +} +``` +{% include copy-curl.html %} + +These messages are stored in the agent's memory. + +#### Message fields + +The following table lists the supported message fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `role` | String | Required | The message role. Valid values: `user`, `assistant`, `system`, and `tool`. | +| `content` | Array | Required | An array of content blocks (text, image, and so on). | +| `toolCalls` | Array | Optional | For `assistant` messages, the tool calls requested by the assistant. Each tool call contains an `id`, a `type` (default is `function`), and a `function` object containing the tool `name` and its `arguments` as a JSON-encoded string. | +| `toolCallId` | String | Optional | For `tool` messages, the ID of the tool call whose result the message contains. | + +#### Example response: Message-based conversation + +The agent remembers context from previous messages: + +```json +{ + "stop_reason": "end_turn", + "message": { + "role": "assistant", + "content": [ + { + "text": "You like the color red, which you mentioned earlier in our conversation." + } + ] + }, + "memory_id": "iEgpJZwBZx9B0F4spD5v", + "metrics": { + "total_usage": { + "inputTokens": 764, + "outputTokens": 18, + "totalTokens": 782 + } + } +} +``` + +### The `conversational_v2` agent response format + +The `conversational_v2` agents return the following standardized response format. The fields are at the top level of the response body: + +```json +{ + "stop_reason": "end_turn", + "message": { + "role": "assistant", + "content": [ + { + "text": "Here is what I found..." + } + ] + }, + "memory_id": "abc123xyz", + "metrics": { + "total_usage": { + "inputTokens": 1234, + "outputTokens": 567, + "totalTokens": 1801 + } + } +} +``` + +The following table lists the `conversational_v2` agent response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `stop_reason` | String | The reason the agent stopped generating a response. Valid values are `end_turn` (normal completion) and `max_iterations` (iteration limit reached). | +| `message` | Object | The assistant's final response message. | +| `message.role` | String | Always `assistant`. | +| `message.content` | Array | An array of content blocks containing the response text or other content. | +| `memory_id` | String | The memory session ID. Include this ID in subsequent requests in the `parameters.memory_id` field to continue the conversation. | +| `metrics.total_usage.inputTokens` | Integer | The number of input tokens consumed. | +| `metrics.total_usage.outputTokens` | Integer | The number of output tokens generated. | +| `metrics.total_usage.totalTokens` | Integer | The total number of tokens used. | + +For more information about the unified registration method and input formats, see [Unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method). + +## Tracking token usage +**Introduced 3.6** +{: .label .label-purple } + +When `include_token_usage` is set to `true`, the response includes detailed token consumption metrics that help you monitor costs, debug performance, and compare model efficiency. This parameter is supported for `conversational` (v1), `plan-execute-reflect`, and `AG-UI` agents using both regular and unified registration methods. + +The `conversational_v2` agent automatically includes token usage in its response format through the `metrics` field and does not require this parameter. For details, see [The `conversational_v2` agent response format](#the-conversational_v2-agent-response-format). +{: .note} + +### Example request: Regular registration +**Introduced 3.6** +{: .label .label-purple } + +For agents created using regular registration, set `include_token_usage` to `true` in the `parameters` object. + +This example demonstrates a multi-turn agent execution where the agent is a conversational agent configured with the `WebSearchTool`. Multi-turn execution occurs because the agent: +1. **Turn 1**: Receives the question, reasons about what information is needed, and decides to use the `WebSearchTool` to find population data. +2. **Turn 2**: Receives the tool results and generates a final answer by analyzing and synthesizing the search results. + +```json +POST /_plugins/_ml/agents/879v9YwBjWKCe6Kg12Tx/_execute +{ + "parameters": { + "question": "what's the population increase of Seattle from 2021 to 2023", + "include_token_usage": true + } +} +``` +{% include copy-curl.html %} + +### Example request: Unified registration +**Introduced 3.6** +{: .label .label-purple } + +For agents created using unified registration, pass both the `input` field and the `parameters` object with `include_token_usage` set to `true`: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "input": "What tools do you have access to?", + "parameters": { + "include_token_usage": true + } +} +``` +{% include copy-curl.html %} + +### Example response: Tracking token usage + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "memory_id", + "result": "lD3rP6EBrGbhC91R6B01" + }, + { + "name": "parent_interaction_id", + "result": "lT3rP6EBrGbhC91R6B1D" + }, + { + "name": "response", + "dataAsMap": { + "response": """ Based on the given context, the key information is: + +The metro area population of Seattle in 2021 was 3,461,000. +The metro area population of Seattle in 2023 is 3,519,000. + +To calculate the population increase from 2021 to 2023: + +Population in 2023 (3,519,000) - Population in 2021 (3,461,000) = 58,000 + +Therefore, the population increase of Seattle from 2021 to 2023 is 58,000.""", + "additional_info": {} + } + }, + { + "name": "token_usage", + "dataAsMap": { + "per_turn_usage": [ + { + "turn": 1, + "model_id": "rk6okJwB_kOxOUbO6853", + "model_name": "Sonnet 4", + "model_url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-20250514-v1:0/converse", + "input_tokens": 1042, + "output_tokens": 69, + "total_tokens": 1111, + "cache_read_input_tokens": 0, + "cache_creation_input_tokens": 0 + }, + { + "turn": 2, + "model_id": "rk6okJwB_kOxOUbO6853", + "model_name": "Sonnet 4", + "model_url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-20250514-v1:0/converse", + "input_tokens": 1541, + "output_tokens": 269, + "total_tokens": 1810, + "cache_read_input_tokens": 0, + "cache_creation_input_tokens": 0 + } + ], + "per_model_usage": [ + { + "model_id": "rk6okJwB_kOxOUbO6853", + "model_name": "Sonnet 4", + "model_url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-20250514-v1:0/converse", + "call_count": 2, + "input_tokens": 2583, + "output_tokens": 338, + "total_tokens": 2921, + "cache_read_input_tokens": 0, + "cache_creation_input_tokens": 0 + } + ] + } + } + ] + } + ] +} +``` + +### The token usage output response fields + +The `token_usage` output contains the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `per_turn_usage` | Array | An array of token usage records for each LLM call (turn) within a single agent execution. Multiple turns occur when an agent needs to reason, use tools, and then generate a final response—each LLM interaction counts as one turn. See [Token usage response fields](#token-usage-response-fields). | +| `per_model_usage` | Array | Aggregated token usage grouped by model. See [Token usage response fields](#token-usage-response-fields). | + +### Token usage response fields + +The following table lists the fields that appear in the `per_turn_usage` and `per_model_usage` arrays. + +Field | Data type | Present in | Description +:--- | :--- | :--- | :--- +`input_tokens` | Integer | Both | The number of tokens in the input/prompt sent to the model. +`output_tokens` | Integer | Both | The number of tokens in the model's output/completion. +`total_tokens` | Integer | Both | The total number of tokens (input + output). +`cache_read_input_tokens` | Integer | Both | The number of input tokens served from the prompt cache. Supported by Anthropic (through Bedrock), OpenAI, and Gemini. Cached tokens are often cheaper than regular input tokens. +`cache_creation_input_tokens` | Integer | Both | The number of tokens used to create new cache entries. Supported by Anthropic (through Bedrock). +`reasoning_tokens` | Integer | Both | The number of tokens used for reasoning or thinking. Only extracted for OpenAI models (from `completion_tokens_details.reasoning_tokens`) and Gemini models (from `thoughtsTokenCount`). +`turn` | Integer | `per_turn_usage` | The sequence number of this LLM call within the agent execution. +`call_count` | Integer | `per_model_usage` | The total number of LLM calls made using this model. +`model_id` | String | Both | The internal OpenSearch model ID. +`model_name` | String | Both | The human-readable model name (for example, `Sonnet 4`, `GPT-4`). +`model_url` | String | Both | The endpoint URL for the model service. + +### How tokens are calculated + +Token counts are calculated by the model provider and may vary based on tokenization methods. For more information about how tokens are calculated, refer to your model provider's documentation: +- [Amazon Bedrock TokenUsage](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_TokenUsage.html) +- [OpenAI tokenization](https://platform.openai.com/docs/guides/tokenization) +- [Google Gemini token counting](https://ai.google.dev/gemini-api/docs/tokens) \ No newline at end of file diff --git a/_ml-commons-plugin/api/agent-apis/execute-stream-agent.md b/_ml-commons-plugin/api/agent-apis/execute-stream-agent.md new file mode 100644 index 00000000..1c23259b --- /dev/null +++ b/_ml-commons-plugin/api/agent-apis/execute-stream-agent.md @@ -0,0 +1,390 @@ +--- +layout: default +title: Execute agent stream +parent: Agent APIs +grand_parent: ML APIs +nav_order: 25 +--- + +# Execute Agent Stream API +**Introduced 3.3** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The Execute Agent Stream API provides the same functionality as the [Execute Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/) but returns responses in a streaming format, delivering data in chunks as it becomes available. This streaming approach is particularly beneficial for large language model interactions with lengthy responses, allowing you to see partial results immediately rather than waiting for the complete response. + +Alternatively, you can stream agent execution over gRPC. For more information, see [gRPC Execute Agent Stream API]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/execute-agent-stream/). +{: .note} + +This API supports the following agent types: + +- **Conversational agents** with the following externally hosted model types: + - [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) + - [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +- **AG-UI agents** using the AG-UI protocol request and response format. For more information, see [AG-UI agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/ag-ui/). + +## Endpoint + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +``` + +## Prerequisites + +Before using this API, ensure that you have fulfilled the following prerequisites. + +### Set up your cluster + +Follow these steps to set up your cluster. + +#### Step 1: Install the required plugins + +The Execute Agent Stream API depends on the following plugins, which are included in the OpenSearch distribution but must be explicitly installed as follows: + +```bash +bin/opensearch-plugin install transport-reactor-netty4 +bin/opensearch-plugin install arrow-flight-rpc +``` + +For more information, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). + +#### Step 2: Configure OpenSearch settings + +Add these settings to your `opensearch.yml` file or Docker Compose configuration: + +```yaml +opensearch.experimental.feature.transport.stream.enabled: true + +# Choose one based on your security settings +http.type: reactor-netty4 # security disabled +http.type: reactor-netty4-secure # security enabled + +# Multi-node cluster settings (if applicable) +# Use network.host IP for opensearch.yml or node name for Docker +arrow.flight.publish_host: <ip> +arrow.flight.bind_host: <ip> + +# Security-enabled cluster settings (if applicable) +transport.stream.type.default: FLIGHT-SECURE +flight.ssl.enable: true +transport.ssl.enforce_hostname_verification: false +``` +{% include copy.html %} + +If you're using the security demo certificates, change `plugins.security.ssl.transport.enforce_hostname_verification: false` to `transport.ssl.enforce_hostname_verification: false` in your `opensearch.yml` file. +{: .note} + +For more information about enabling experimental features, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). + +#### Step 3: Configure JVM options + +Add these settings to your `jvm.options` file: + +```yaml +-Dio.netty.allocator.numDirectArenas=1 +-Dio.netty.noUnsafe=false +-Dio.netty.tryUnsafe=true +-Dio.netty.tryReflectionSetAccessible=true +--add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED +``` +{% include copy.html %} + +### Configure the necessary APIs + +Configure the API using the following steps. + +#### Step 1: Enable the streaming feature flag + +To enable the streaming feature flag, update the cluster settings as follows: + +```json +PUT /_cluster/settings +{ + "persistent" : { + "plugins.ml_commons.stream_enabled": true + } +} +``` +{% include copy-curl.html %} + +#### Step 2: Register a compatible externally hosted model + +To register an OpenAI Chat Completion model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "OpenAI gpt-4o-mini", + "function_name": "remote", + "description": "OpenAI model", + "connector": { + "name": "OpenAI Chat Connector", + "description": "The connector to OpenAI model service for gpt-4o-mini", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-4o-mini" + }, + "credential": { + "openAI_key": "<your_api_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\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] + } +} +``` +{% include copy-curl.html %} + +To register an Amazon Bedrock Converse Stream model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Amazon Bedrock Converse Stream model", + "function_name": "remote", + "description": "Amazon Bedrock Claude model", + "connector": { + "name": "Amazon Bedrock Converse", + "description": "The connector to Amazon Bedrock Converse", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<your_aws_access_key>", + "secret_key": "<your_aws_secret_key>", + "session_token": "<your_aws_session_token>" + }, + "parameters": { + "region": "<your_aws_region>", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] + } +} +``` +{% include copy-curl.html %} + +#### Step 3: Register a conversational agent + +When registering your agent, you must include the `_llm_interface` parameter that corresponds to your model type: +- OpenAI Chat Completion: `openai/v1/chat/completions` +- Amazon Bedrock Converse Stream: `bedrock/converse/claude` + +To register your agent, send the following request: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Chat Agent with RAG", + "type": "conversational", + "description": "This is a test agent", + "llm": { + "model_id": "<model_id_from_step_2>", + "parameters": { + "max_iteration": 5, + "system_prompt": "You are a helpful assistant. You are able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics.\nIf the question is complex, you will split it into several smaller questions, and solve them one by one. For example, the original question is:\nhow many orders in last three month? Which month has highest?\nYou will spit into several smaller questions:\n1.Calculate total orders of last three month.\n2.Calculate monthly total order of last three month and calculate which months order is highest. You MUST use the available tools everytime to answer the question", + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "openai/v1/chat/completions" + }, + "tools": [ + { + "type": "IndexMappingTool", + "name": "DemoIndexMappingTool", + "parameters": { + "index": "${parameters.index}", + "input": "${parameters.question}" + } + }, + { + "type": "ListIndexTool", + "name": "RetrieveIndexMetaTool", + "description": "Use this tool to get OpenSearch index information: (health, status, index, uuid, primary count, replica count, docs.count, docs.deleted, store.size, primary.store.size)." + } + ], + "app_type": "my_app" +} +``` +{% include copy-curl.html %} + +## Example request: Conversational agent + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "parameters": { + "question": "How many indices are in my cluster?" + } +} +``` +{% include copy-curl.html %} + +## Example response: Conversational agent + +```json +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"[{\"index\":0.0,\"id\":\"call_HjpbrbdQFHK0omPYa6m2DCot\",\"type\":\"function\",\"function\":{\"name\":\"RetrieveIndexMetaTool\",\"arguments\":\"\"}}]","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"[{\"index\":0.0,\"function\":{\"arguments\":\"{}\"}}]","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"{\"choices\":[{\"message\":{\"tool_calls\":[{\"type\":\"function\",\"function\":{\"name\":\"RetrieveIndexMetaTool\",\"arguments\":\"{}\"},\"id\":\"call_HjpbrbdQFHK0omPYa6m2DCot\"}]},\"finish_reason\":\"tool_calls\"}]}","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards)\n1,green,open,.plugins-ml-model-group,Msb1Y4W5QeiLs5yUQi-VRg,1,1,2,0,17.1kb,5.9kb\n2,green,open,.plugins-ml-memory-message,1IWd1HPeSWmM29qE6rcj_A,1,1,658,0,636.4kb,313.5kb\n3,green,open,.plugins-ml-memory-meta,OETb21fqQJa3Y2hGQbknCQ,1,1,267,7,188kb,93.9kb\n4,green,open,.plugins-ml-config,0mnOWX5gSX2s-yP27zPFNw,1,1,1,0,8.1kb,4kb\n5,green,open,.plugins-ml-model,evYOOKN4QPqtmUjxsDwJYA,1,1,5,5,421.5kb,210.7kb\n6,green,open,.plugins-ml-agent,I0SpBovjT3C6NABCBzGiiQ,1,1,6,0,205.5kb,111.3kb\n7,green,open,.plugins-ml-task,_Urzn9gdSuCRqUaYAFaD_Q,1,1,100,4,136.1kb,45.3kb\n8,green,open,top_queries-2025.09.26-00444,jb7Q1FiLSl-wTxjdSUKs_w,1,1,1736,126,1.8mb,988kb\n9,green,open,.plugins-ml-connector,YaJORo4jT0Ksp24L5cW1uA,1,1,2,0,97.8kb,48.9kb\n","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"There","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" are","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" ","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"9","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" indices","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" in","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" your","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" cluster","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":".","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"","is_last":true}}]}]} +``` + +## Example request with token usage +**Introduced 3.6** +{: .label .label-purple } + +To receive detailed token usage metrics in the streaming response, set `include_token_usage` to `true`: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "parameters": { + "question": "How many indices are in my cluster?", + "include_token_usage": true + } +} +``` +{% include copy-curl.html %} + +### Example response with token usage + +The streaming response includes a `token_usage` chunk sent after the content chunks and before the final completion chunk: + +```json +... (content chunks as shown above) ... + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"token_usage","dataAsMap":{"per_turn_usage":[{"turn":1,"model_id":"rk6okJwB_kOxOUbO6853","model_name":"gpt-4o-mini","model_url":"https://api.openai.com/v1/chat/completions","input_tokens":1042,"output_tokens":69,"total_tokens":1111,"cache_read_input_tokens":0}],"per_model_usage":[{"model_id":"rk6okJwB_kOxOUbO6853","model_name":"gpt-4o-mini","model_url":"https://api.openai.com/v1/chat/completions","call_count":1,"input_tokens":1042,"output_tokens":69,"total_tokens":1111,"cache_read_input_tokens":0}]}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"","is_last":true}}]}]} +``` + +## Example request: AG-UI agent +**Introduced 3.5** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +AG-UI agents use the AG-UI protocol format for frontend integration: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "threadId": "thread-xxxxx", + "runId": "run-xxxxx", + "messages": [ + { + "id": "msg-xxxxx", + "role": "user", + "content": "How many indices are in my cluster?" + } + ], + "tools": [], + "context": [], + "state": {}, + "forwardedProps": {} +} +``` +{% include copy-curl.html %} + +## Example response: AG-UI agent + +AG-UI agents return SSEs using the AG-UI protocol format: + +```json +data: {"type":"RUN_STARTED","timestamp":1734567890123,"threadId":"thread-xxxxx","runId":"run-xxxxx"} + +data: {"type":"TEXT_MESSAGE_START","timestamp":1734567890124,"messageId":"msg-xxxxx","role":"assistant"} + +data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1734567890125,"messageId":"msg-xxxxx","delta":"Your cluster has 9 indices."} + +data: {"type":"TEXT_MESSAGE_END","timestamp":1734567890140,"messageId":"msg-xxxxx"} + +data: {"type":"RUN_FINISHED","timestamp":1734567890251,"threadId":"thread-xxxxx","runId":"run-xxxxx"} +``` + +For complete AG-UI agent documentation, including setup, prerequisites, field definitions, and implementation details, see [AG-UI agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/ag-ui/). + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- |:------------------------------------------------------------------------------------------------------------| +| `inference_results` | Array | Contains the streaming response data returned by the agent. | +| `inference_results.output` | Array | Contains output objects for each inference result. | +| `inference_results.output.name` | String | The name of the output field. Can be `memory_id`, `parent_interaction_id`, `response`, or `token_usage`. | +| `inference_results.output.result` | String | The values of the `memory_id` and `parent_interaction_id` fields. | +| `inference_results.output.dataAsMap` | Object | Contains the response content and metadata (present for `response` and `token_usage` outputs). | +| `inference_results.output.dataAsMap.content` | String | The agent's response content, which can include tool calls, tool results, or final text output. | +| `inference_results.output.dataAsMap.is_last` | Boolean | Indicates whether this is the final chunk in the stream: `true` for the last chunk, `false` if there are more chunks. | +| `inference_results.output.dataAsMap.token_usage` | Object | Token usage metrics for the agent execution. Delivered as a separate streaming chunk before the final completion chunk. Only present when `include_token_usage` is set to `true`. **Introduced 3.6** | + +### Token usage in streaming responses +**Introduced 3.6** +{: .label .label-purple } + +To enable token usage tracking in streaming responses, set the `parameters.include_token_usage` field to `true` in your request. When enabled, the streaming response sequence is as follows: + +1. Content chunks stream through (with `is_last: false`) +2. A `token_usage` chunk is sent containing detailed metrics +3. A final completion chunk is sent (with empty content and `is_last: true`) + +The token usage chunk contains the same structure as the non-streaming API response: + +- **`per_turn_usage`**: An array of token usage records for each LLM call during agent execution. Each record includes `turn` (the sequence number), `model_id`, `model_name`, `model_url`, `input_tokens`, `output_tokens`, `total_tokens`, and optional cache-related fields. +- **`per_model_usage`**: Aggregated token usage grouped by model. Each record includes `model_id`, `model_name`, `model_url`, `call_count` (number of LLM calls), `input_tokens`, `output_tokens`, `total_tokens`, and optional cache-related fields. + +For a complete description of token usage fields and how tokens are calculated by different model providers, see [Tracking token usage]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/#tracking-token-usage) in the Execute Agent API documentation. diff --git a/_ml-commons-plugin/api/agent-apis/get-agent.md b/_ml-commons-plugin/api/agent-apis/get-agent.md index be49a875..e2468efe 100644 --- a/_ml-commons-plugin/api/agent-apis/get-agent.md +++ b/_ml-commons-plugin/api/agent-apis/get-agent.md @@ -2,23 +2,20 @@ layout: default title: Get agent parent: Agent APIs -grand_parent: ML Commons APIs -nav_order: 20 +grand_parent: ML APIs +nav_order: 30 --- -# Get an agent -**Introduced 2.12** +# Get Agent API +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - You can retrieve agent information using the `agent_id`. -## Path and HTTP methods +## Endpoints ```json -GET /_plugins/_ml/agents/<agent_id> +GET /_plugins/_ml/agents/{agent_id} ``` ## Path parameters @@ -30,14 +27,14 @@ The following table lists the available path parameters. | `agent_id` | String | The agent ID of the agent to retrieve. | -#### Example request +## Example request ```json GET /_plugins/_ml/agents/N8AE1osB0jLkkocYjz7D ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -61,25 +58,22 @@ GET /_plugins/_ml/agents/N8AE1osB0jLkkocYjz7D "description": "A general tool to answer any question", "parameters": { "model_id": "ygAzT40Bdo8gePIqxk0H", - "prompt": """ + "prompt": """You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. -Human:You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. - - Context: +Context: ${parameters.VectorDBTool.output} -Human:${parameters.question} - -Assistant:""" +Question: ${parameters.question}""" }, "include_output_in_agent_response": false } ], "created_time": 1706821658743, - "last_updated_time": 1706821658743 + "last_updated_time": 1706821658743, + "is_hidden": false } ``` -## Response fields +## Response body fields -For response field descriptions, see [Register Agent API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent#request-fields). \ No newline at end of file +For response field descriptions, see [Register Agent API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields). \ No newline at end of file diff --git a/_ml-commons-plugin/api/agent-apis/index.md b/_ml-commons-plugin/api/agent-apis/index.md index 4b6954a7..a84d577a 100644 --- a/_ml-commons-plugin/api/agent-apis/index.md +++ b/_ml-commons-plugin/api/agent-apis/index.md @@ -1,26 +1,26 @@ --- layout: default title: Agent APIs -parent: ML Commons APIs +parent: ML APIs has_children: true has_toc: false -nav_order: 27 -redirect_from: /ml-commons-plugin/api/agent-apis/ +nav_order: 60 +redirect_from: + - /ml-commons-plugin/api/agent-apis/ --- # Agent APIs -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - You can automate machine learning (ML) tasks using agents and tools. An _agent_ orchestrates and runs ML models and tools. For more information, see [Agents and tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/index/). -ML Commons supports the following agent-level APIs: +OpenSearch supports the following agent APIs: - [Register agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/) +- [Update agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/update-agent/) - [Execute agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/) +- [Execute agent stream]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-stream-agent/) - [Get agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/get-agent/) - [Search agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/search-agent/) - [Delete agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/delete-agent/) \ No newline at end of file diff --git a/_ml-commons-plugin/api/agent-apis/register-agent.md b/_ml-commons-plugin/api/agent-apis/register-agent.md index 75a63d40..3e3badc7 100644 --- a/_ml-commons-plugin/api/agent-apis/register-agent.md +++ b/_ml-commons-plugin/api/agent-apis/register-agent.md @@ -2,59 +2,101 @@ layout: default title: Register agent parent: Agent APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 10 --- -# Register an agent -**Introduced 2.12** +# Register Agent API +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - Use this API to register an agent. Agents may be of the following types: -- Flow agent -- Conversational flow agent -- Conversational agent +- _Flow_ agent +- _Conversational flow_ agent +- _Conversational agent_ +- _Plan-execute-reflect_ agent +- _AG-UI_ agent -For more information about agents, see [Agents and tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/index/). +For more information about agents, see [Agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). -## Path and HTTP methods +You can use the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method) to register agents with automated connector and model creation. This method supports Amazon Bedrock Converse, Google Gemini, and OpenAI models and requires the `plugins.ml_commons.unified_agent_api_enabled` cluster setting to be enabled. +{: .note} + +## Endpoints ```json POST /_plugins/_ml/agents/_register ``` -{% include copy-curl.html %} -## Request fields +## Request body fields The following table lists the available request fields. Field | Data type | Required/Optional | Agent type | Description :--- | :--- | :--- | :--- | :--- `name`| String | Required | All | The agent name. | -`type` | String | Required | All | The agent type. Valid values are `flow`, `conversational_flow`, and `conversational`. For more information, see [Agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/index/). | +`type` | String | Required | All | The agent type. Valid values are [`flow`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/flow/), [`conversational_flow`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational-flow/), [`conversational`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/#the-conversational-agent-v1), [`conversational_v2`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/#the-conversational_v2-agent-with-full-multimodal-support), [`plan_execute_and_reflect`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/plan-execute-reflect/), and [`ag_ui`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/ag-ui/). For more information, see [Agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/). | +`agent_id` | String | Optional | All | A unique identifier for the agent. If omitted, OpenSearch generates one automatically. | `description` | String | Optional| All | A description of the agent. | `tools` | Array | Optional | All | A list of tools for the agent to execute. `app_type` | String | Optional | All | Specifies an optional agent category. You can then perform operations on all agents in the category. For example, you can delete all messages for RAG agents. -`memory.type` | String | Optional | `conversational_flow`, `conversational` | Specifies where to store the conversational memory. Currently, the only supported type is `conversation_index` (store the memory in a conversational system index). +`memory.type` | String | Optional | `conversational_flow`, `conversational`, `plan_execute_and_reflect` | Specifies where to store the conversational memory. Supported values are `conversation_index` (store memory in conversation indexes) and `agentic_memory` (store memory in a memory container). +`memory.memory_container_id` | String | Optional | `conversational_flow`, `conversational`, `plan_execute_and_reflect` | The default memory container ID for `agentic_memory`. If omitted, you must provide a `parameters.memory_container_id` when executing the agent. If neither is provided, the request fails. `llm.model_id` | String | Required | `conversational` | The model ID of the LLM to which to send questions. -`llm.parameters.response_filter` | String | Required | `conversational` | The pattern for parsing the LLM response. For each LLM, you need to provide the field where the response is located. For example, for the Anthropic Claude model, the response is located in the `completion` field, so the pattern is `$.completion`. For OpenAI models, the pattern is `$.choices[0].message.content`. -`llm.parameters.max_iteration` | Integer | Optional | `conversational` | The maximum number of messages to send to the LLM. Default is `3`. +`llm.parameters.response_filter` | String | Required | `conversational` | The pattern for parsing the LLM response. For each LLM, you need to provide the field where the response is located. For example, for an Anthropic Claude model that uses the Messages API, the response is located in the `content[0].text` field, so the pattern is `$.content[0].text`. For OpenAI models, the pattern is `$.choices[0].message.content`. +`llm.parameters.max_iteration` | Integer | Optional | `conversational` | The maximum number of messages to send to the LLM. Default is `10`. +`parameters` | Object | Optional | All | Agent parameters, which may be used to control the `max_steps` executed by the agent, modify default prompts, and so on. +`parameters.executor_agent_id`| String | Optional | `plan_execute_and_reflect` | The `plan_execute_and_reflect` agent internally uses a `conversational` agent to execute each step. By default, this executor agent uses the same model as the planning model specified in the `llm` configuration. To use a different model for executing steps, create a `conversational` agent using another model and pass the agent ID in this field. This can be useful if you want to use different models for planning and execution. +`parameters.max_steps` | Integer | Optional | `plan_execute_and_reflect` | The maximum number of steps executed by the LLM. Default is `20`. +`parameters.executor_max_iterations` | Integer | Optional | `plan_execute_and_reflect` | The maximum number of messages sent to the LLM by the executor agent. Default is `20`. +`parameters.message_history_limit` | Integer | Optional | `plan_execute_and_reflect` | The number of recent messages from conversation memory to include as context for the planner. Default is `10`. +`parameters.executor_message_history_limit` | Integer | Optional | `plan_execute_and_reflect` | The number of recent messages from conversation memory to include as context for the executor. Default is `10`. +`parameters._llm_interface` | String | Required | `plan_execute_and_reflect`, `conversational` | Specifies how to parse the LLM output when using function calling. Valid values are: <br> - `bedrock/converse/claude`: Anthropic Claude conversational models hosted on Amazon Bedrock <br> - `bedrock/converse/deepseek_r1`: DeepSeek-R1 models hosted on Amazon Bedrock <br> - `openai/v1/chat/completions`: OpenAI chat completion models hosted on OpenAI. Each interface defines a default response schema and function call parser. +`parameters.inject_datetime` | Boolean | Optional | `conversational`, `plan_execute_and_reflect` | Whether to automatically inject the current date into the system prompt. Default is `false`. +`parameters.datetime_format` | String | Optional | `conversational`, `plan_execute_and_reflect` | A format string for dates used when `inject_datetime` is enabled. Default is `"yyyy-MM-dd'T'HH:mm:ss'Z'"` (ISO format). +`model` | Object | Optional | `conversational`, `conversational_v2`, `plan_execute_and_reflect`, `ag_ui` | **Unified registration method only (3.5+)**: Model configuration that automatically creates a connector and model. See [Unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method). +`model.model_id` | String | Required (if using `model`) | `conversational`, `conversational_v2`, `plan_execute_and_reflect`, `ag_ui` | The model identifier (for example, `us.anthropic.claude-sonnet-4-6` for Amazon Bedrock or `gemini-2.5-pro` for Google Gemini). +`model.model_provider` | String | Required (if using `model`) | `conversational`, `conversational_v2`, `plan_execute_and_reflect`, `ag_ui` | The model provider. Supported values: `bedrock/converse`, `gemini/v1beta/generatecontent`, `openai/v1/chat/completions`. +`model.credential` | Object | Required (if using `model`) | `conversational`, `conversational_v2`, `plan_execute_and_reflect`, `ag_ui` | Credentials for accessing the model. Accepts any credential format supported by connectors. For details, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). +`model.model_parameters` | Object | Optional (if using `model`) | `conversational`, `conversational_v2`, `plan_execute_and_reflect`, `ag_ui` | Model-specific parameters such as system prompts and other configuration options. +`context_management_name` | String | Optional | `conversational`, `plan_execute_and_reflect` | The name of a context management configuration to apply to the agent. Cannot be specified together with `context_management`. For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). +`context_management` | Object | Optional | `conversational`, `plan_execute_and_reflect` | An inline context management configuration containing a `name` and a `hooks` object that maps hook names to lists of context managers. The `name` is required. Inline hook names must be uppercase: `PRE_LLM`, `POST_LLM`, `PRE_TOOL`, `POST_TOOL`, or `POST_MEMORY`. Cannot be specified together with `context_management_name`. For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). +`provisioned_by` | String | Optional | All | An optional attribution tag identifying the plugin or client that registered the agent (for example, `flow-framework`). Included in ML statistics metrics. + +### Using agentic memory + +To use agentic memory, create a memory container using the [Create Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/) and set the memory configuration as follows: + +```json +"memory": { + "type": "agentic_memory", + "memory_container_id": "<memory_container_id>" +} +``` +{% include copy.html %} + +For agents configured with `agentic_memory`, see [Inspecting memory data]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#inspecting-memory-data-opensearch-agents) for information about inspecting session and trace data after agent execution. + +### Tool configuration The `tools` array contains a list of tools for the agent. Each tool contains the following fields. Field | Data type | Required/Optional | Description -:--- | :--- | :--- +:--- | :--- | :--- | :--- +`type` | String | Required | The tool type. For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). `name`| String | Optional | The tool name. The tool name defaults to the `type` parameter value. If you need to include multiple tools of the same type in an agent, specify different names for the tools. | -`type` | String | Required | The tool type. For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +`description`| String | Optional | The tool description. Defaults to a built-in description for the specified type. | `parameters` | Object | Optional | The parameters for this tool. The parameters are highly dependent on the tool type. You can find information about specific tool types in [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +`parameters.output_processors` | Array | Optional | A list of processors used to transform the tool's output. For more information, see [Processor chain]({{site.url}}{{site.baseurl}}/ml-commons-plugin/processor-chain/). +`attributes.input_schema` | Object | Optional | The expected input format for this tool defined as a [JSON schema](https://json-schema.org/). Used to define the structure the LLM should follow when calling the tool. +`attributes.strict` | Boolean | Optional | Whether function calling reliably adheres to the input schema or not. +`include_output_in_agent_response` | Boolean | Optional | Whether to include the tool output in the agent response. By default, a flow or conversational flow agent returns only the output of the last tool. Default is `false`. +`config` | Object | Optional | Applies to `conversational` and `plan_execute_and_reflect` agents. Tool parameters that are applied when the LLM calls the tool. Values in `config` override the values in `parameters`. If `config` contains an `input` key, the agent uses its value as the tool input in place of the input generated by the LLM. The value can contain placeholders, for example, `"input": "${parameters.question}"`. -#### Example request: Flow agent +## Example request: Flow agent ```json POST /_plugins/_ml/agents/_register @@ -81,7 +123,7 @@ POST /_plugins/_ml/agents/_register "description": "A general tool to answer any question", "parameters": { "model_id": "NWR9YIsBUysqmzBdifVJ", - "prompt": "\n\nHuman:You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\n Context:\n${parameters.vector_tool.output}\n\nHuman:${parameters.question}\n\nAssistant:" + "prompt": "You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\nContext:\n${parameters.vector_tool.output}\n\nQuestion: ${parameters.question}" } } ] @@ -89,7 +131,7 @@ POST /_plugins/_ml/agents/_register ``` {% include copy-curl.html %} -#### Example request: Conversational flow agent +## Example request: Conversational flow agent ```json POST /_plugins/_ml/agents/_register @@ -121,18 +163,14 @@ POST /_plugins/_ml/agents/_register "description": "A general tool to answer any question", "parameters": { "model_id": "your_LLM_model_id", - "prompt": """ - -Human:You are a professional data analysist. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. + "prompt": """You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. Context: ${parameters.population_knowledge_base.output:-} ${parameters.chat_history:-} -Human:${parameters.question} - -Assistant:""" +Question: ${parameters.question}""" } } ] @@ -140,12 +178,12 @@ Assistant:""" ``` {% include copy-curl.html %} -#### Example request: Conversational agent +## Example request: Conversational agent ```json POST /_plugins/_ml/agents/_register { - "name": "Test_Agent_For_ReAct_ClaudeV2", + "name": "Test_Agent_For_ReAct_Claude", "type": "conversational", "description": "this is a test agent", "app_type": "my chatbot", @@ -154,7 +192,7 @@ POST /_plugins/_ml/agents/_register "parameters": { "max_iteration": 5, "stop_when_no_tool_found": true, - "response_filter": "$.completion" + "response_filter": "$.content[0].text" } }, "memory": { @@ -164,7 +202,7 @@ POST /_plugins/_ml/agents/_register { "type": "VectorDBTool", "name": "VectorDBTool", - "description": "A tool to search opensearch index with natural language quesiotn. If you don't know answer for some question, you should always try to search data with this tool. Action Input: <natrual language question>", + "description": "A tool to search opensearch index with natural language question. If you don't know answer for some question, you should always try to search data with this tool. Action Input: <natural language question>", "parameters": { "model_id": "<embedding_model_id>", "index": "<your_knn_index>", @@ -176,7 +214,7 @@ POST /_plugins/_ml/agents/_register } }, { - "type": "CatIndexTool", + "type": "ListIndexTool", "name": "RetrieveIndexMetaTool", "description": "Use this tool to get OpenSearch index information: (health, status, index, uuid, primary count, replica count, docs.count, docs.deleted, store.size, primary.store.size)." } @@ -185,7 +223,87 @@ POST /_plugins/_ml/agents/_register ``` {% include copy-curl.html %} -#### Example response +## Example request: Plan-execute-reflect agent +**Introduced 3.0** +{: .label .label-purple } + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My plan execute and reflect agent", + "type": "plan_execute_and_reflect", + "description": "this is a test agent", + "llm": { + "model_id": "<llm_model_id>", + "parameters": { + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "<llm_interface>" + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ], + "app_type": "os_chat" +} +``` +{% include copy-curl.html %} + +## Example request: AG-UI agent +**Introduced 3.5** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +AG-UI agents use the unified registration method for integrating AI agents with frontend applications. The following example shows the basic structure: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<AWS ACCESS KEY>", + "secret_key": "<AWS SECRET KEY>", + "session_token": "<AWS SESSION TOKEN>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 5 + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +For complete AG-UI agent documentation, including field definitions, prerequisites, execution examples, and the AG-UI protocol format, see [AG-UI agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/ag-ui/). + +## Example response OpenSearch responds with an agent ID that you can use to refer to the agent: @@ -193,4 +311,225 @@ OpenSearch responds with an agent ID that you can use to refer to the agent: { "agent_id": "bpV_Zo0BRhAwb9PZqGja" } -``` \ No newline at end of file +``` + +## Unified agent registration +**Introduced 3.5** +{: .label .label-purple } + +The unified registration method streamlines agent creation by automatically handling connector and model setup in a single API call. This method supports the Amazon Bedrock Converse API with Anthropic Claude models, Google Gemini models, and OpenAI models. + +Before using unified agents, see [Prerequisites]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#prerequisites) for required cluster settings. For more information and supported agent types, see [Unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method). + +### Unified registration request fields + +The following table lists the available request fields for unified agent registration. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `name` | String | Required | The agent name. | +| `type` | String | Required | The agent type. Supported values: `conversational`, `conversational_v2`, `plan_execute_and_reflect`, and `AG_UI`. | +| `agent_id` | String | Optional | A unique identifier for the agent. If omitted, OpenSearch generates one automatically. | +| `description` | String | Optional | A description of the agent. | +| `model` | Object | Required | Configuration for the LLM model using the unified registration method. Replaces the regular `llm` object and automatically creates model resources. | +| `model.model_id` | String | Required | The provider's model identifier. For Amazon Bedrock, use the full model ID (for example, `us.anthropic.claude-sonnet-4-6`). For Google Gemini, use the model name (for example, `gemini-2.5-pro`). For OpenAI, use model names like `gpt-4o-mini`. | +| `model.model_provider` | String | Required | The model provider type. Valid values: `bedrock/converse`, `gemini/v1beta/generatecontent`, `openai/v1/chat/completions`. | +| `model.credential` | Object | Required | Credentials for the model provider. Structure depends on the provider. | +| `model.credential.access_key` | String | Required (Amazon Bedrock) | AWS access key for Amazon Bedrock models. | +| `model.credential.secret_key` | String | Required (Amazon Bedrock) | AWS secret key for Amazon Bedrock models. | +| `model.credential.session_token` | String | Optional (Amazon Bedrock) | AWS session token for Amazon Bedrock models when using temporary credentials. | +| `model.credential.openai_api_key` | String | Required (OpenAI) | API key for OpenAI models. | +| `model.credential.gemini_api_key` | String | Required (Google Gemini) | The API key for Google Gemini models. | +| `model.model_parameters` | Object | Optional | Model-specific parameters and configuration. | +| `model.model_parameters.system_prompt` | String | Optional | The system prompt that defines the agent's role and behavior. | +| `model.model_parameters.temperature` | Float | Optional | Controls randomness in model responses (0.0 to 1.0). Default varies by model. | +| `model.model_parameters.max_tokens` | Integer | Optional | The maximum number of tokens in the model response. Default varies by model. | +| `parameters` | Object | Optional | Additional agent parameters for controlling behavior. | +| `parameters.max_iteration` | Integer | Optional | The maximum number of reasoning iterations the agent can perform. Default is 10. | +| `parameters.mcp_connectors` | Array | Optional | An array of Model Context Protocol (MCP) connector configurations that extend agent capabilities. For `conversational` and `plan_execute_and_reflect` agents, MCP tools are discovered automatically. For `flow` and `conversational_flow` agents, list MCP tools explicitly in the `tools` array. See [Connecting to an external MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/#step-3-register-an-agent-for-accessing-mcp-tools). | +| `parameters.mcp_connectors[].mcp_connector_id` | String | Required | The ID of a registered MCP connector. | +| `parameters.mcp_connectors[].tool_filters` | Array | Optional | Java regular expressions that specify the MCP tools available to the agent. | +| `parameters.mcp_connectors[].tool_descriptions` | Array | Optional | Objects that override MCP tool descriptions presented to the LLM. | +| `tools` | Array | Optional | Array of tools available to the agent. For supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). | +| `memory` | Object | Optional | Configuration for conversation memory storage. | +| `memory.type` | String | Optional | The memory storage type. Supported values: `conversation_index`, `agentic_memory`. | + +Each tool in the `tools` array contains the following fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `type` | String | Required | The tool type (for example, `ListIndexTool`, `SearchIndexTool`, `McpStreamableHttpTool`, `McpSseTool`). For MCP tools in `flow` and `conversational_flow` agents, use `McpStreamableHttpTool` with `mcp_streamable_http` connectors or `McpSseTool` with `mcp_sse` connectors. | +| `name` | String | Optional | A custom name for the tool. Defaults to the `type` value. Required when using multiple tools of the same type. For MCP tools in flow agents, set `name` to the MCP server tool name. | +| `description` | String | Optional | Tool description that helps the LLM understand when and how to use the tool. | +| `parameters` | Object | Optional | Tool-specific parameters. Structure varies by tool type. | + +<!-- vale off --> +### Example request: Amazon Bedrock Claude +<!-- vale on --> + +This example creates an agent using an Anthropic Claude model hosted on Amazon Bedrock: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Claude Research Agent", + "type": "conversational", + "description": "An agent using Claude for research tasks", + "model": { + "model_id": "us.anthropic.claude-sonnet-4-6", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "YOUR_AWS_ACCESS_KEY", + "secret_key": "YOUR_AWS_SECRET_KEY", + "session_token": "YOUR_AWS_SESSION_TOKEN" + }, + "model_parameters": { + "system_prompt": "You are a helpful research assistant with access to OpenSearch data.", + "temperature": 0.7, + "max_tokens": 1000 + } + }, + "parameters": { + "max_iteration": 5 + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +### Example request: Google Gemini +<!-- vale on --> + +This example creates an agent using Google Gemini models: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Gemini Analysis Agent", + "type": "conversational", + "description": "An agent using Gemini for data analysis", + "model": { + "model_id": "gemini-2.5-pro", + "model_provider": "gemini/v1beta/generatecontent", + "credential": { + "gemini_api_key": "YOUR_GEMINI_API_KEY" + }, + "model_parameters": { + "system_prompt": "You are an expert data analyst with access to OpenSearch indices." + } + }, + "tools": [ + { + "type": "SearchIndexTool" + } + ], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +### Example request: OpenAI Chat Completion +<!-- vale on --> + +This example creates an agent using OpenAI's GPT models: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "GPT Customer Service Agent", + "type": "conversational", + "description": "An agent using GPT for customer service tasks", + "model": { + "model_id": "gpt-4o-mini", + "model_provider": "openai/v1/chat/completions", + "credential": { + "openai_api_key": "YOUR_OPENAI_API_KEY" + }, + "model_parameters": { + "system_prompt": "You are a helpful customer service agent with access to customer data.", + "temperature": 0.3, + "max_tokens": 800 + } + }, + "parameters": { + "max_iteration": 10 + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + } + ], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +### Example request: Plan-execute-reflect agent + +This example creates a plan-execute-reflect agent for complex multi-step tasks: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research Planning Agent", + "type": "plan_execute_and_reflect", + "description": "An agent that can plan and execute complex research tasks", + "model": { + "model_id": "us.anthropic.claude-sonnet-4-6", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "YOUR_AWS_ACCESS_KEY", + "secret_key": "YOUR_AWS_SECRET_KEY", + "session_token": "YOUR_AWS_SESSION_TOKEN" + }, + "model_parameters": { + "system_prompt": "You are an expert researcher who can plan and execute multi-step research tasks." + } + }, + "parameters": { + "max_steps": 15, + "max_iteration": 20 + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ], + "memory": { + "type": "conversation_index" + } +} +``` +{% include copy-curl.html %} + +## Related documentation + +- For agents configured with `agentic_memory`, see [Inspecting memory data]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/). diff --git a/_ml-commons-plugin/api/agent-apis/search-agent.md b/_ml-commons-plugin/api/agent-apis/search-agent.md index c5df482a..18d01af7 100644 --- a/_ml-commons-plugin/api/agent-apis/search-agent.md +++ b/_ml-commons-plugin/api/agent-apis/search-agent.md @@ -2,27 +2,24 @@ layout: default title: Search agent parent: Agent APIs -grand_parent: ML Commons APIs -nav_order: 30 +grand_parent: ML APIs +nav_order: 35 --- -# Search for an agent -**Introduced 2.12** +# Search Agent API +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/ml-commons/issues/1161). -{: .warning} - Use this command to search for agents you've already created. You can provide any OpenSearch search query in the request body. -## Path and HTTP methods +## Endpoints ```json GET /_plugins/_ml/agents/_search POST /_plugins/_ml/agents/_search ``` -#### Example request: Searching for all agents +## Example request: Searching for all agents ```json POST /_plugins/_ml/agents/_search @@ -35,7 +32,7 @@ POST /_plugins/_ml/agents/_search ``` {% include copy-curl.html %} -#### Example request: Searching for agents of a certain type +## Example request: Searching for agents of a certain type ```json POST /_plugins/_ml/agents/_search @@ -51,10 +48,10 @@ POST /_plugins/_ml/agents/_search ``` {% include copy-curl.html %} -#### Example: Searching for an agent by description +## Example request: Searching for an agent by description ```json -GET _plugins/_ml/agents/_search +GET /_plugins/_ml/agents/_search { "query": { "bool": { @@ -72,7 +69,7 @@ GET _plugins/_ml/agents/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -102,6 +99,7 @@ GET _plugins/_ml/agents/_search "created_time": 1707532959502, "last_updated_time": 1707532959502, "name": "Test_Agent_For_RagTool", + "is_hidden": false, "description": "this is a test flow agent", "type": "flow", "tools": [ @@ -117,16 +115,12 @@ GET _plugins/_ml/agents/_search "embedding_field": "embedding", "index": "my_test_data", "query_type": "neural", - "prompt": """ + "prompt": """You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. -Human:You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. - - Context: +Context: ${parameters.output_field} -Human:${parameters.question} - -Assistant:""" +Question: ${parameters.question}""" } } ] @@ -137,6 +131,6 @@ Assistant:""" } ``` -## Response fields +## Response body fields -For response field descriptions, see [Register Agent API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent#request-fields). +For response field descriptions, see [Register Agent API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields). diff --git a/_ml-commons-plugin/api/agent-apis/update-agent.md b/_ml-commons-plugin/api/agent-apis/update-agent.md new file mode 100644 index 00000000..679edb26 --- /dev/null +++ b/_ml-commons-plugin/api/agent-apis/update-agent.md @@ -0,0 +1,83 @@ +--- +layout: default +title: Update agent +parent: Agent APIs +grand_parent: ML APIs +nav_order: 15 +--- + +# Update Agent API +**Introduced 3.1** +{: .label .label-purple } + +Use this API to update an existing agent's configuration. + +## Endpoints + +```json +PUT /_plugins/_ml/agents/{agent_id} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `agent_id` | String | The agent ID of the agent to update. | + +## Request body fields + +The following table lists the available request fields. All request body fields are optional. + +Field | Data type | Agent type | Description +:--- | :--- | :--- | :--- +`name`| String | All | The agent name. +`description` | String | All | A description of the agent. +`tools` | Array | All | A list of tools for the agent to execute. +`app_type` | String | All | Specifies an optional agent category. +`memory.type` | String | `conversational_flow`, `conversational` | Specifies where to store the conversational memory. The only supported type is `conversation_index` (store the memory in a conversational system index). +`llm.model_id` | String | `conversational` | The model ID of the large language model (LLM) to send questions to. +`llm.parameters.response_filter` | String | `conversational` | The pattern for parsing the LLM response. +`llm.parameters.max_iteration` | Integer | `conversational` | The maximum number of messages to send to the LLM. +`parameters` | Object | All | Agent parameters. The parameters you provide are merged with the existing agent parameters, overwriting parameters that have the same name. + +## Example request: Update tool prompt + +```json +PUT /_plugins/_ml/agents/N8AE1osB0jLkkocYjz7D +{ + "name": "Updated_Test_Agent_For_RAG", + "description": "Updated description for test agent", + "tools": [ + { + "type": "MLModelTool", + "description": "Updated general tool to answer any question", + "parameters": { + "model_id": "NWR9YIsBUysqmzBdifVJ", + "prompt": "This is an updated prompt" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-agent", + "_id": "ryN5jpcBfY4uTYhorKvh", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/agentic-memory-apis/add-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/add-memory.md new file mode 100644 index 00000000..1df65048 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/add-memory.md @@ -0,0 +1,202 @@ +--- +layout: default +title: Add agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 45 +--- + +# Add Agentic Memory API +**Introduced 3.3** +{: .label .label-purple } + + +Use this API to add an agentic memory to a [memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container). You can specify different [payload types]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#payload-types) and control [inference mode]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#inference-mode) for how OpenSearch processes the memory. + +Once an agentic memory is created, provide its `memory_id` to other APIs. + +## Endpoints + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container to add the memory to. | + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`messages` | Array | Conditional | A list of messages for a `conversational` payload. Each message must include a `content` field specified as an array of objects. Each object must contain the `type` (for example, `text`) and the corresponding content. Each message may include a `role` (commonly, `user` or `assistant`) when `infer` is set to `true`. Required when `payload_type` is `conversational`. +`structured_data` | Object | Conditional | Structured data content for data memory. Required when `payload_type` is `data`. +`structured_data_blob` | Object | Optional | Structured data that is stored with the memory but not indexed, so it cannot be searched. +`binary_data` | String | Optional | Binary data content encoded as a Base64 string for binary payloads. +`payload_type` | String | Optional | The type of payload. Valid values are `conversational` or `data`. Default is `conversational`. See [Payload types]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#payload-types). +`namespace` | Object | Optional | The [namespace]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#namespaces) context for organizing memories (for example, `user_id`, `session_id`, or `agent_id`). If `session_id` is not specified in the `namespace` field, the `payload_type` is `conversational`, the memory container has an `llm_id`, and `disable_session` is `false` (the default), a new session with a new session ID is created. The LLM generates the session summary from the messages. +`metadata` | Object | Optional | Additional metadata for the memory (for example, `status`, `branch`, or custom fields). +`tags` | Object | Optional | Tags for categorizing and organizing memories. +`message_id` | Integer | Optional | The sequence number of the message in a conversation. Agents use this field to order conversation messages. +`checkpoint_id` | String | Optional | A checkpoint identifier to store with the memory. +`parameters` | Object | Optional | Parameters that override the memory container's [`parameters`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/#the-parameters-object) for this request only. +`infer` | Boolean | Optional | Whether to use a large language model (LLM) to extract key information from messages. Default is `false`. When `true`, the LLM extracts key information from the original text and stores it as a memory. Requires the memory container to have an `llm_id`. See [Inference mode]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#inference-mode). + +This API creates `working` memories, which cannot be pinned, so the request rejects the `pinned` field. To exclude a conversation from a retention policy, pin its session after you add the memory. For more information, see [Pinning memories]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory-retention/#pinning-memories). +{: .note} + +## Example request: Conversational payload + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories +{ + "messages": [ + { + "role": "user", + "content": [ + { + "text": "I'm Bob, I really like swimming.", + "type": "text" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "text": "Cool, nice. Hope you enjoy your life.", + "type": "text" + } + ] + } + ], + "namespace": { + "user_id": "bob" + }, + "metadata": { + "status": "checkpoint", + "branch": { + "branch_name": "high", + "root_event_id": "228nadfs879mtgk" + } + }, + "tags": { + "topic": "personal info" + }, + "infer": true, + "payload_type": "conversational" +} +``` +{% include copy-curl.html %} + +## Example response: Conversational payload + +```json +{ + "session_id": "XSEuiJkBeh2gPPwzjYVh", + "working_memory_id": "XyEuiJkBeh2gPPwzjYWM" +} +``` + +## Example request: Data payload + +To store agent state in working memory, send the following request: + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories +{ + "structured_data": { + "time_range": { + "start": "2025-09-11", + "end": "2025-09-15" + } + }, + "namespace": { + "agent_id": "testAgent1" + }, + "metadata": { + "status": "checkpoint", + "anyobject": "abc" + }, + "tags": { + "topic": "agent_state" + }, + "infer": false, + "payload_type": "data" +} +``` +{% include copy-curl.html %} + +## Example response: Data payload + +```json +{ + "working_memory_id": "Z8xeTpkBvwXRq366l0iA" +} +``` + +## Example request: Storing tool invocation data + +To store agent trace data in working memory, send the following request: + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories +{ + "structured_data": { + "tool_invocations": [ + { + "tool_name": "ListIndexTool", + "tool_input": { + "filter": "*,-.plugins*" + }, + "tool_output": "green open security-auditlog-2025.09.17..." + } + ] + }, + "namespace": { + "user_id": "bob", + "agent_id": "testAgent1", + "session_id": "123" + }, + "metadata": { + "status": "checkpoint", + "branch": { + "branch_name": "high", + "root_event_id": "228nadfs879mtgk" + }, + "anyobject": "abc" + }, + "tags": { + "topic": "personal info", + "parent_memory_id": "o4-WWJkBFT7urc7Ed9hM", + "data_type": "trace" + }, + "infer": false, + "payload_type": "data" +} +``` +{% include copy-curl.html %} + +## Example response: Trace data + +```json +{ + "session_id": "123", + "working_memory_id": "Z8xeTpkBvwXRq366l0iA" +} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :-------------- | :-------- | :------------------------------------------------------------------------------------------------ | +| `session_id` | String | The session ID associated with the memory. Returned when a session is created or when the `namespace` contains a `session_id`. | +| `working_memory_id` | String | The unique identifier for the created working memory entry. | diff --git a/_ml-commons-plugin/api/agentic-memory-apis/create-memory-container.md b/_ml-commons-plugin/api/agentic-memory-apis/create-memory-container.md new file mode 100644 index 00000000..94eee803 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/create-memory-container.md @@ -0,0 +1,372 @@ +--- +layout: default +title: Create memory container +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 10 +--- + +# Create Memory Container API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to create a [memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-containers) to store agentic memories. The container can have two model types associated with it: + +- A text embedding model for vectorizing the message so it can be searched. Use a text embedding model for dense vector embeddings or a sparse encoding model for sparse vector formats. If no embedding model is specified, messages are stored but cannot be used for vector-based searches. +- A large language model (LLM) for reasoning over the message to produce factual or processed content. If no LLM is specified, messages are stored directly, without applying inference. Long-term memory requires both an LLM model and embedding model to be configured. + +For more information, see [Integrating ML models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/). + +LLM connectors must support `system_prompt` and `user_prompt` parameters for agentic memory processing. The default `llm_result_path` is the Amazon Bedrock Converse API response path (`"$.output.message.content[0].text"`). If using an OpenAI GPT model, set the `llm_result_path` to `$.choices[0].message.content`. +{: .note} + +Once a memory container is created, provide its `memory_container_id` to other APIs. + +## The created indexes + +The indexes created for a memory container depend on the `configuration` you provide. The following table summarizes the behavior. + +Configuration | Indexes created | Capabilities +:--- | :--- | :--- +No `configuration` or no `strategies` | Working memory + session (unless `disable_session` is `true`) | Raw message storage and retrieval. No semantic search, no long-term memory, no fact extraction. +With `strategies` (requires `llm_id`, `embedding_model_id`, and `embedding_model_type`) | Working memory + session + long-term memory + history (unless `disable_session` is `true`) | Semantic search, fact extraction, memory consolidation (ADD/UPDATE/DELETE decisions), and an audit trail of all long-term memory changes. + +Each index type serves a specific purpose: + +- **Working memory**: Stores raw messages as they are received. Always created. +- **Session**: Tracks conversation sessions and their metadata. Created by default. To disable session tracking, set `disable_session` to `true`. +- **Long-term memory**: Stores extracted facts and persistent knowledge produced by strategies. Created only when strategies are configured. +- **History**: An audit trail that records every ADD, UPDATE, and DELETE operation on long-term memory. Created only when strategies are configured. Can be opted out of by setting `disable_history` to `true`. + +## Prerequisites + +If you want to use one of the model types to process memories, register the models in OpenSearch. + +### Embedding model + +Register either a local or externally hosted embedding model. OpenSearch supports text embedding and sparse encoding models. + +For more information about using models locally, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). For a list of supported models, see [OpenSearch-provided pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#supported-pretrained-models). + + +For more information about using externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). For example, to register an externally hosted Amazon Titan Embeddings model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Bedrock embedding model", + "function_name": "remote", + "description": "test model", + "connector": { + "name": "Amazon Bedrock Connector: embedding", + "description": "The connector to bedrock Titan embedding model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "model": "amazon.titan-embed-text-v2:0", + "dimensions": 1024, + "normalize": true, + "embeddingTypes": [ + "float" + ] + }, + "credential": { + "access_key": "...", + "secret_key": "...", + "session_token": "..." + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": """{ "inputText": "${parameters.inputText}", "dimensions": ${parameters.dimensions}, "normalize": ${parameters.normalize}, "embeddingTypes": ${parameters.embeddingTypes} }""", + "pre_process_function": "connector.pre_process.bedrock.embedding", + "post_process_function": "connector.post_process.bedrock.embedding" + } + ] + } +} +``` +{% include copy-curl.html %} + +### LLM + + +To register an Anthropic Claude model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Bedrock infer model", + "function_name": "remote", + "description": "test model", + "connector": { + "name": "Amazon Bedrock Connector: Chat", + "description": "The connector to bedrock Claude Sonnet 4.6 model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "max_tokens": 8000, + "temperature": 1, + "model": "us.anthropic.claude-sonnet-4-6" + }, + "credential": { + "access_key": "...", + "secret_key": "...", + "session_token": "..." + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "request_body": "{ \"inferenceConfig\": { \"maxTokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }, \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [ { \"role\": \"user\", \"content\": [ {\"text\": \"${parameters.user_prompt}\" }] }]}" + } + ] + } +} +``` +{% include copy-curl.html %} + +The `system_prompt` parameter is required for Claude models. +{: .note} + +To make the LLM return extracted facts in a fixed JSON schema, set `supports_structured_output` to `true` in the connector's `predict` action. For more information, see [The actions object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#the-actions-object). + +For more information about using externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). + +## Endpoints + +```json +POST /_plugins/_ml/memory_containers/_create +``` + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`name` | String | Required | The name of the memory container. +`memory_container_id` | String | Optional | A unique identifier for the memory container. If omitted, OpenSearch generates one automatically. | +`description` | String | Optional | The description of the memory container. +`configuration` | Object | Optional | The memory container configuration. When not provided, a default configuration is used that creates a working-memory-only container with no AI capabilities. For full functionality including semantic search and long-term memory, provide a configuration with model IDs and strategies. See [The `configuration` object](#the-configuration-object). +`backend_roles` | Array | Optional | A list of backend roles for access control. Each role must be at most 128 characters and contain only alphanumeric characters and `:+=,.@-_/`. + +### The configuration object + +The `configuration` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`embedding_model_type` | String | Optional | The embedding model type. Supported types are `TEXT_EMBEDDING` and `SPARSE_ENCODING`. Required if `embedding_model_id` is provided. +`embedding_model_id` | String | Optional | The embedding model ID. Required if `embedding_model_type` is provided. +`embedding_dimension` | Integer | Optional | The dimension of the embedding model. Required if `embedding_model_type` is `TEXT_EMBEDDING`. Not allowed if `embedding_model_type` is `SPARSE_ENCODING`. +`llm_id` | String | Optional | The LLM model ID for processing and inference. +`index_prefix` | String | Optional | A custom prefix for memory indexes. If not specified, a default prefix is used: `default` when `use_system_index` is `true`, or an 8-character random UUID when `use_system_index` is `false`. +`use_system_index` | Boolean | Optional | Whether to use system indexes (hidden indexes prefixed with `.plugins-ml-am-`). Default is `true`. +`disable_history` | Boolean | Optional | Whether to disable the history audit trail index. Default is `false`. This setting only takes effect when strategies are configured, because the history index records changes to long-term memory. Without strategies, no long-term memory or history index is created regardless of this setting. +`disable_session` | Boolean | Optional | Whether to disable the session tracking index. Default is `false` (sessions are enabled by default). Set to `true` to disable session tracking. +`max_infer_size` | Integer | Optional | The maximum number of similar existing memories retrieved during memory consolidation to make ADD/UPDATE/DELETE decisions. Default is `5`. Maximum is `10`. +`index_settings` | Object | Optional | Custom OpenSearch index settings for the memory storage indexes that will be created for this container. Each memory type (`sessions`, `working`, `long_term`, and `history`) uses its own index. See [The `index_settings` object](#the-index_settings-object). +`strategies` | Array | Optional | An array of [memory processing strategies]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-processing-strategies). When strategies are provided, both `llm_id` and embedding model fields (`embedding_model_id`, `embedding_model_type`) are required. See [The `strategies` array](#the-strategies-array). +`parameters` | Object | Optional | Global parameters for the memory container. See [The `parameters` object](#the-parameters-object). +`retention_policy` | Object | Optional | The retention limits for each memory type. Requires `plugins.ml_commons.memory.retention_enabled` to be `true`. For more information, see [Agentic memory retention]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory-retention/). + +### The index_settings object + +You can customize the OpenSearch index settings for the storage indexes that will be created to store memory data. Each memory type uses a dedicated index, and you can configure settings like the number of shards and replicas for performance optimization. + +Index settings are applied only when the indexes are created. If another memory container already uses the same `index_prefix`, the existing indexes are reused and the specified settings are ignored. +{: .note} + +The following example shows you how to specify custom index settings in the `configuration` object: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "my-memory-container", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "your-model-id", + "embedding_dimension": 1024, + "index_settings": { + "session_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + }, + "working_memory_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + }, + "long_term_memory_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + }, + "long_term_memory_history_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + } + } + } +} +``` +{% include copy-curl.html %} + +### The strategies array + +Each strategy in the `strategies` array supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`type` | String | Required | The strategy type. Valid values are `SEMANTIC`, `USER_PREFERENCE`, and `SUMMARY`. +`namespace` | Array | Required | An array of [namespace]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#namespaces) dimensions for organizing memories (for example, `["user_id"]` or `["agent_id", "session_id"]`). +`configuration` | Object | Optional | Strategy-specific configuration. See [The `strategies.configuration` object](#the-strategies-configuration-object). +`enabled` | Boolean | Optional | Whether to enable the strategy in the memory container. Default is `true`. + +### The strategies configuration object + +The `strategies.configuration` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`llm_result_path` | String | Optional | A JSONPath expression for extracting LLM results from responses. Default is the Amazon Bedrock Converse API response path (`"$.output.message.content[0].text"`). +`system_prompt` | String | Optional | A custom system prompt used to override the default strategy prompt. The prompt must contain the word `JSON` and the quoted key `"facts"`, and it must instruct the LLM to return a JSON object containing a `facts` array of strings. Otherwise, fact extraction fails and an error is recorded in the history index. +`llm_id` | String | Optional | The LLM model ID for this strategy. Overrides the global LLM setting. + +### The parameters object + +The `parameters` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`llm_result_path` | String | Optional | A global JSONPath expression for extracting LLM results from responses. Default is the Amazon Bedrock Converse API response path (`"$.output.message.content[0].text"`). +`session` | Object | Optional | Parameters for the session summary that the LLM generates when a conversational memory is added without a `session_id`. See [The `session` object](#the-session-object). + +### The session object + +The `session` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`max_summary_size` | Integer | Optional | The maximum number of words in the session summary. Default is `10`. +`system_prompt` | String | Optional | A custom system prompt that replaces the default session summary prompt. + +OpenSearch passes any other field in the `session` object to the LLM as a connector parameter for the summary request. For example, if the connector's request body uses `${parameters.max_tokens}`, setting `max_tokens` in the `session` object limits the length of the LLM response for session summaries. + +## Example request: Minimal memory container + +The following request creates a minimal memory container with only working memory (raw message storage). No AI models or strategies are configured: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "simple-message-store" +} +``` +{% include copy-curl.html %} + +This request creates a container with working memory and session indexes. Messages can be stored and retrieved by ID, but semantic search and long-term memory features are not available. + +## Example request: Basic memory container with a strategy + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "<embedding_model_id>", + "embedding_dimension": 1024, + "llm_id": "<llm_id>", + "strategies": [ + { + "type": "SEMANTIC", + "namespace": ["user_id"] + } + ] + } +} +``` +{% include copy-curl.html %} + +This request creates a container with working memory, session, long-term memory, and history indexes. The `SEMANTIC` strategy uses the LLM to extract facts from messages and the embedding model to enable vector-based semantic search over those facts. + +## Example request: Advanced memory container with multiple strategies + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "<embedding_model_id>", + "embedding_dimension": 1024, + "llm_id": "<llm_id>", + "index_prefix": "my_custom_prefix", + "use_system_index": false, + "strategies": [ + { + "type": "SEMANTIC", + "namespace": ["agent_id"], + "configuration": { + "llm_result_path": "$.output.message.content[0].text", + "system_prompt": "Extract semantic information from user conversations. Return only a JSON object in the format {\"facts\": [\"<fact>\"]}.", + "llm_id": "<custom_llm_id>" + } + }, + { + "type": "USER_PREFERENCE", + "namespace": ["agent_id"], + "configuration": { + "llm_result_path": "$.output.message.content[0].text" + } + }, + { + "type": "SUMMARY", + "namespace": ["agent_id"], + "configuration": { + "llm_result_path": "$.output.message.content[0].text" + } + } + ], + "parameters": { + "llm_result_path": "$.output.message.content[0].text" + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response contains the `memory_container_id` that you can use to retrieve or delete the container: + +```json +{ + "memory_container_id": "SdjmmpgBOh0h20Y9kWuN", + "status": "created" +} +``` diff --git a/_ml-commons-plugin/api/agentic-memory-apis/create-session.md b/_ml-commons-plugin/api/agentic-memory-apis/create-session.md new file mode 100644 index 00000000..6ba3606b --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/create-session.md @@ -0,0 +1,96 @@ +--- +layout: default +title: Create session +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 40 +--- + +# Create Session API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to create a new session in a memory container. Sessions represent distinct interaction contexts between users and agents. + +## Endpoints + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/sessions +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container where the session will be created. | + +## Request fields + +The following table lists the available request body fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `session_id` | String | Optional | A custom session ID. If provided, this ID is used for the session. If not provided, a random ID is generated. | +| `summary` | String | Optional | A session summary or description. | +| `metadata` | Object | Optional | Additional metadata for the session provided as key-value pairs. | +| `namespace` | Object | Optional | Namespace information for organizing the session. | +| `agents` | Object | Optional | Information about the agents that participate in the session, provided as key-value pairs. | +| `additional_info` | Object | Optional | Additional information about the session, provided as key-value pairs. | + +## Example request: Create a session with a custom ID + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories/sessions +{ + "session_id": "abc123", + "metadata": { + "key1": "value1" + } +} +``` +{% include copy-curl.html %} + +## Example response: Custom session ID + +```json +{ + "session_id": "abc123", + "status": "created" +} +``` + +## Example request: Create a session with an autogenerated ID + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories/sessions +{ + "summary": "This is a test session", + "metadata": { + "key1": "value1" + }, + "namespace": { + "user_id": "bob" + } +} +``` +{% include copy-curl.html %} + +## Example response: Autogenerated session ID + +```json +{ + "session_id": "jTYm35kBt8CyICnjxJl9", + "status": "created" +} +``` + +## Response fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `session_id` | String | The ID of the created session (either provided or auto-generated). | +| `status` | String | The status of the creation operation. Returned values are `created` if a new session was created or `exists` if a session with the specified `session_id` already exists. | diff --git a/_ml-commons-plugin/api/agentic-memory-apis/delete-memory-container.md b/_ml-commons-plugin/api/agentic-memory-apis/delete-memory-container.md new file mode 100644 index 00000000..97ac9221 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/delete-memory-container.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Delete memory container +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 30 +--- + +# Delete Memory Container API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to delete a memory container by its ID. + +## Endpoints + +```json +DELETE /_plugins/_ml/memory_containers/{memory_container_id} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container to delete. | + +## Query parameters + +The following table lists the available query parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `delete_all_memories` | Boolean | Optional | Controls whether to delete all memory indexes when deleting the container. Default is `false`. When `false`, memory indexes (sessions, working, long-term, history) are preserved. | +| `delete_memories` | Array | Optional | Array of memory types to delete when deleting the container. Default is empty array. Accepts values: `sessions`, `working`, `long-term`, `history`. Example: `delete_memories=sessions,working`. | + +You can also provide `delete_all_memories` and `delete_memories` in the request body. If a parameter is specified in both places, the query parameter takes precedence. + +## Example request: Basic deletion (preserves memory indexes) + +```json +DELETE /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN +``` +{% include copy-curl.html %} + +## Example request: Delete a container and all memory indexes + +```json +DELETE /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN?delete_all_memories=true +``` +{% include copy-curl.html %} + +## Example request: Delete a container and specific memory types + +```json +DELETE /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN?delete_memories=sessions,working +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-am-memory-container", + "_id": "SdjmmpgBOh0h20Y9kWuN", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 1 +} +``` + +## Error responses + +If you attempt to delete a memory container that doesn't exist, OpenSearch returns a 404 Not Found error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Memory container not found" + } + ], + "type": "status_exception", + "reason": "Memory container not found" + }, + "status": 404 +} +``` + +Memory indexes can be deleted only if no other memory container uses the same `index_prefix`. If another container shares the prefix, a request that specifies `delete_all_memories` or `delete_memories` fails with a 409 Conflict error and the container is not deleted. To delete the container, send the request without these parameters. +{: .note} + +## Response fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_index` | String | The name of the index that stores memory containers. | +| `result` | String | The result of the delete operation. | +| `_id` | String | The ID of the deleted memory container. | +| `_version` | Integer | The version number after deletion. | +| `forced_refresh` | Boolean | Whether a refresh was forced after the operation. | +| `_shards` | Object | Information about the shards involved in the operation. | +| `_seq_no` | Long | The sequence number assigned to the delete operation. | +| `_primary_term` | Long | The primary term of the index. | \ No newline at end of file diff --git a/_ml-commons-plugin/api/agentic-memory-apis/delete-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/delete-memory.md new file mode 100644 index 00000000..68274d92 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/delete-memory.md @@ -0,0 +1,190 @@ +--- +layout: default +title: Delete agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 53 +--- + +# Delete Agentic Memory API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to delete a specific memory by its type and ID or to delete memories matching a query. This unified API supports deleting memories of any [memory type]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-types): `sessions`, `working`, `long-term`, or `history`. + +## Delete a memory by type and ID + +Use this API to delete a memory by type and ID. + +### Endpoints + +```json +DELETE /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/{id} +``` + +### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container from which to delete the memory. | +| `type` | String | Required | The type of memory to delete. Valid values are `sessions`, `working`, `long-term`, and `history`. | +| `id` | String | Required | The ID of the specific memory to delete. | + +### Example request: Delete a working memory + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/XyEuiJkBeh2gPPwzjYWM +``` +{% include copy-curl.html %} + +### Example request: Delete a long-term memory + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/DcxjTpkBvwXRq366C1Zz +``` +{% include copy-curl.html %} + +### Example request: Delete a sessions memory + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/CcxjTpkBvwXRq366A1aE +``` +{% include copy-curl.html %} + +### Example request: Delete a history memory + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/history/eMxnTpkBvwXRq366hmAU +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "_index": ".plugins-ml-am-default-memory-working", + "_id": "XyEuiJkBeh2gPPwzjYWM", + "_version": 2, + "result": "deleted", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 1 +} +``` + +### Error responses + +If you attempt to delete a memory from a container that doesn't exist, OpenSearch returns a 404 Not Found error. OpenSearch also returns a 404 error if the memory doesn't exist. The following response is returned for a container that doesn't exist: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Memory container not found" + } + ], + "type": "status_exception", + "reason": "Memory container not found" + }, + "status": 404 +} +``` + +### Response fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_index` | String | The name of the index from which the memory was deleted. | +| `result` | String | The result of the delete operation. | +| `_id` | String | The ID of the deleted memory. | +| `_version` | Integer | The version number after deletion. | +| `_shards` | Object | Information about the shards involved in the operation. | +| `_seq_no` | Long | The sequence number assigned to the delete operation. | +| `_primary_term` | Long | The primary term of the index. | + +## Delete memories by query + +Use this API to delete multiple memories using a query to match specific criteria. + +### Endpoints + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/_delete_by_query +``` + +### Path parameters + +| Field | Data type | Required/Optional | Description | +|:----------------------| :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container from which to delete the memory. | +| `type` | String | Required | The type of memory to delete. Valid values are `sessions`, `working`, `long-term`, and `history`. | + +### Request body fields + +The request body must contain a query to match the memories you want to delete. + +### Example request + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/_delete_by_query +{ + "query": { + "match": { + "owner_id": "admin" + } + } +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "took": 159, + "timed_out": false, + "total": 6, + "updated": 0, + "created": 0, + "deleted": 6, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0, + "failures": [] +} +``` + +### Response fields + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `took` | Integer | The time, in milliseconds, taken to execute the request. | +| `timed_out` | Boolean | Whether the request timed out. | +| `total` | Integer | The total number of documents processed. | +| `deleted` | Integer | The number of documents deleted. | +| `batches` | Integer | The number of batches processed. | +| `version_conflicts` | Integer | The number of version conflicts encountered. | +| `noops` | Integer | The number of no-operation updates. | +| `retries` | Object | Information about bulk and search retries. | +| `throttled_millis` | Integer | The time, in milliseconds, that the request was throttled. | +| `requests_per_second` | Float | The number of requests processed per second. | +| `throttled_until_millis` | Integer | The time, in milliseconds, until throttling is lifted. | +| `failures` | Array | Any failures that occurred during the operation. | + diff --git a/_ml-commons-plugin/api/agentic-memory-apis/get-memory-container.md b/_ml-commons-plugin/api/agentic-memory-apis/get-memory-container.md new file mode 100644 index 00000000..3c917343 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/get-memory-container.md @@ -0,0 +1,73 @@ +--- +layout: default +title: Get memory container +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 20 +--- + +# Get Memory Container API +**Introduced 3.3** +{: .label .label-purple } + + +Use this API to retrieve a memory container by its ID. + +## Endpoints + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container to retrieve. | + +## Example request + +```json +GET /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization", + "created_time": 1792070644500, + "last_updated_time": 1792070644500, + "configuration": { + "index_prefix": "default", + "llm_id": "aFouy5kBrfmzAZ6R6wo-", + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "uXZAtJkBvHNmcp1JAROh", + "embedding_dimension": 1024, + "max_infer_size": 5, + "strategies": [ + { + "id": "semantic_53d1751c", + "enabled": true, + "type": "SEMANTIC", + "namespace": [ + "user_id" + ] + } + ], + "disable_history": false, + "disable_session": false, + "use_system_index": true + } +} +``` + +## Response body fields + +For response field descriptions, see [Create Memory Container API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container#request-body-fields). + +Each [strategy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-processing-strategies) in the response also contains an `id` generated by OpenSearch. To update a strategy, provide this `id` in an [Update Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/update-memory-container/) request. diff --git a/_ml-commons-plugin/api/agentic-memory-apis/get-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/get-memory.md new file mode 100644 index 00000000..a92926e4 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/get-memory.md @@ -0,0 +1,240 @@ +--- +layout: default +title: Get agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 51 +--- + +# Get Agentic Memory API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to retrieve a specific memory by its type and ID. This unified API supports the four [memory types]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-types): `sessions`, `working`, `long-term`, and `history`. + +## Endpoints + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/{id} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container from which to retrieve the memory. | +| `type` | String | Required | The memory type. Valid values are `sessions`, `working`, `long-term`, and `history`. | +| `id` | String | Required | The ID of the memory to retrieve. | + +## Example request: Get a working memory + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/XyEuiJkBeh2gPPwzjYWM +``` +{% include copy-curl.html %} + +## Example response: Working memory + +```json +{ + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "payload_type": "conversational", + "messages": [ + { + "role": "user", + "content": [ + { + "text": "I'm Bob, I really like swimming.", + "type": "text" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "text": "Cool, nice. Hope you enjoy your life.", + "type": "text" + } + ] + } + ], + "namespace": { + "user_id": "bob", + "session_id": "S-dqiJkB1SltqOcZ1cYO" + }, + "namespace_size": 2, + "infer": true, + "metadata": { + "branch": "{\"root_event_id\":\"228nadfs879mtgk\",\"branch_name\":\"high\"}", + "status": "checkpoint" + }, + "tags": { + "topic": "personal info" + }, + "created_time": 1758930326804, + "last_updated_time": 1758930326804 +} +``` + +## Example request: Get a long-term memory + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/DcxjTpkBvwXRq366C1Zz +``` +{% include copy-curl.html %} + +## Example response: Long-term memory + +```json +{ + "memory": "Kubernetes RBAC permission issues detected with CloudWatch agents experiencing persistent permission denials", + "strategy_type": "SUMMARY", + "tags": { + "agent_type": "chat_agent", + "conversation": "true" + }, + "namespace": { + "agent_id": "chat-agent" + }, + "namespace_size": 1, + "created_time": 1760052801773, + "last_updated_time": 1760052801773, + "memory_embedding": [0.018510794, 0.056366503, "..."], + "owner_id": "admin", + "strategy_id": "summary_96f04d97" +} +``` + +## Example request: Get a session + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/CcxjTpkBvwXRq366A1aE +``` +{% include copy-curl.html %} + +## Example response: Session + +```json +{ + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "summary": "This is a test session", + "created_time": 1757956735881, + "last_updated_time": 1757956735881, + "namespace": { + "user_id": "bob" + } +} +``` + +## Example request: Get a history memory + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/history/eMxnTpkBvwXRq366hmAU +``` +{% include copy-curl.html %} + +## Example response: History + +```json +{ + "owner_id": "admin", + "memory_container_id": "nrJBy5kByIxXWyhQjmqv", + "memory_id": "4bJMy5kByIxXWyhQvGr9", + "action": "ADD", + "after": { + "memory": "A comprehensive security investigation was performed across multiple data sources including 55 OpenSearch indices, 50 CloudTrail events, 22 VPC Flow logs, 38 WAF events, 74 CloudWatch log groups, active CloudWatch alarms, and OpenSearch cluster security configuration." + }, + "namespace": { + "agent_id": "chat-agent" + }, + "namespace_size": 1, + "tags": { + "agent_type": "chat_agent", + "conversation": "true" + }, + "created_time": 1760052428089 +} +``` + +## Response fields + +The response fields vary depending on the memory type. + +### Working memory response fields + +The following table lists all working memory response body fields. + +| Field | Data type | Description | +|:----------------------| :--- |:--------------------------------------------------------| +| `memory_container_id` | String | The ID of the memory container. | +| `payload_type` | String | The type of payload. Valid values are `conversational` and `data`. | +| `messages` | Array | Array of conversation messages (applicable only to the `conversational` payload type). | +| `structured_data` | Object | The structured data content (applicable only to the `data` payload type). | +| `structured_data_blob` | Object | The structured data stored without indexing. | +| `binary_data` | String | The Base64-encoded binary data content. | +| `message_id` | Integer | The sequence number of the message in a conversation. | +| `checkpoint_id` | String | The checkpoint identifier stored with the memory. | +| `namespace` | Object | The namespace context for this memory. | +| `namespace_size` | Integer | The number of namespace fields. | +| `owner_id` | String | The ID of the memory owner. Present only when the Security plugin is enabled. | +| `metadata` | Object | Additional metadata associated with the memory. | +| `tags` | Object | Associated tags for categorization. | +| `infer` | Boolean | Whether inference was enabled for this memory. | +| `created_time` | Long | The timestamp of when the memory was created. | +| `last_updated_time` | Long | The timestamp of when the memory was last updated. | + +### Long-term memory response fields + +The following table lists all long-term memory response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory` | String | The extracted long-term memory fact. | +| `strategy_type` | String | The type of memory strategy used (for example, `SEMANTIC`, `SUMMARY`, or `USER_PREFERENCE`). | +| `namespace` | Object | The namespace context for this memory. | +| `namespace_size` | Integer | The number of namespaces. | +| `tags` | Object | Associated tags for categorization. | +| `created_time` | Long | The timestamp when the memory was created. | +| `last_updated_time` | Long | The timestamp when the memory was last updated. | +| `memory_embedding` | Array | The vector embedding of the memory content (truncated in display). | +| `owner_id` | String | The ID of the memory owner. | +| `strategy_id` | String | The unique identifier for the strategy instance. | +| `pinned` | Boolean | Whether the memory is pinned and exempt from the container's retention policy. | + +### Session response fields + +The following table lists all session response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory_container_id` | String | The ID of the memory container. | +| `summary` | String | The session summary. | +| `metadata` | Object | Additional metadata associated with the session. | +| `agents` | Object | Information about the agents that participate in the session. | +| `additional_info` | Object | Additional information about the session. | +| `namespace` | Object | The namespace context for this session. | +| `owner_id` | String | The ID of the session owner. Present only when the Security plugin is enabled. | +| `pinned` | Boolean | Whether the session is pinned and exempt from the container's retention policy. | +| `created_time` | Long | The timestamp of when the session was created. | +| `last_updated_time` | Long | The timestamp of when the session was last updated. | + +### History response fields + +The following table lists all history response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `owner_id` | String | The ID of the memory owner. | +| `memory_container_id` | String | The ID of the memory container. | +| `memory_id` | String | The ID of the affected memory. | +| `action` | String | The type of operation: `ADD`, `UPDATE`, or `DELETE`. | +| `after` | Object | The memory content after the operation. | +| `before` | Object | The memory content before the operation (for `UPDATE` operations). | +| `namespace` | Object | The namespace context for this memory. | +| `namespace_size` | Integer | The number of namespaces. | +| `tags` | Object | Associated tags for categorization. | +| `error` | String | The error message if the operation failed. | +| `created_time` | Long | The timestamp of when the operation occurred. | diff --git a/_ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory.md new file mode 100644 index 00000000..0a5bb100 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory.md @@ -0,0 +1,177 @@ +--- +layout: default +title: Hybrid search agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 70 +--- + +# Hybrid Search Agentic Memory API +**Introduced 3.6** +{: .label .label-purple } + +Use this API to search long-term memories using a combination of BM25 keyword matching and semantic search. This is useful when your query benefits from both exact keyword precision and semantic understanding. + +Hybrid search combines two search methods in a single query: + +1. **BM25 keyword search**: A `match` query on the `memory` field for exact keyword matching. +2. **Neural vector search**: A `neural` query (or `neural_sparse` for `SPARSE_ENCODING` models) on the `memory_embedding` field for semantic similarity. + +Results are combined using an inline normalization processor pipeline using `min_max` normalization and `arithmetic_mean` combination. The `bm25_weight` and `neural_weight` parameters control the relative importance of each search method. No preconfigured search pipeline is required. + +The memory container must have an embedding model and at least one [memory strategy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-processing-strategies) configured. +{: .note} + +## Endpoints + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_hybrid_search +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_hybrid_search +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container. | + +## Request fields + +The following table lists the available request fields. + +| Field | Data type | Required/Optional | Default | Description | +| :--- | :--- | :--- | :--- | :--- | +| `query` | String | Required | N/A | A natural language search query used for both BM25 keyword matching and semantic search. | +| `k` | Integer | Optional | 10 | The number of results to return. Valid values are `1`–`10000`, inclusive. | +| `namespace` | Object | Optional | N/A | Filters results by namespace fields. For example, `{"user_id": "alice"}`. | +| `tags` | Object | Optional | N/A | Filters results by tag fields. For example, `{"topic": "food"}`. | +| `min_score` | Float | Optional | N/A | The minimum relevance score threshold. Results below this score are excluded. | +| `filter` | Object | Optional | N/A | An additional [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) filter applied alongside the hybrid query. | +| `bm25_weight` | Float | Optional | 0.5 | The weight for the BM25 keyword search component. Valid values are `0.0`–`1.0`. The sum of `bm25_weight` and `neural_weight` must equal `1.0`. | +| `neural_weight` | Float | Optional | 0.5 | The weight for the neural vector search component. Valid values are `0.0`–`1.0`. The sum of `bm25_weight` and `neural_weight` must equal `1.0`. | + +## Example request: Basic hybrid search + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_hybrid_search +{ + "query": "retirement timeline five years portfolio rebalancing", + "k": 10, + "namespace": { + "user_id": "bob" + } +} +``` +{% include copy-curl.html %} + +## Example request: Custom weights + +You can adjust the balance between keyword and semantic search for each request. Increasing `neural_weight` prioritizes semantic similarity, while increasing `bm25_weight` prioritizes exact keyword matches: + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_hybrid_search +{ + "query": "machine learning outdoor activities", + "k": 5, + "namespace": { + "user_id": "alice" + }, + "bm25_weight": 0.3, + "neural_weight": 0.7 +} +``` +{% include copy-curl.html %} + +## Example request: Minimum score and tags filter + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_hybrid_search +{ + "query": "LGBTQ workshop therapeutic methods", + "k": 10, + "namespace": { + "user_id": "caroline" + }, + "tags": { + "topic": "wellness" + }, + "min_score": 0.3 +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "abc123", + "_score": 1.0, + "_source": { + "created_time": 1700000000000, + "memory": "Caroline attended an LGBTQ+ counseling workshop focused on therapeutic methods", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "caroline" + }, + "strategy_id": "semantic_53d1751c", + "strategy_type": "SEMANTIC", + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "tags": { + "topic": "wellness" + } + } + }, + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "def456", + "_score": 0.52, + "_source": { + "created_time": 1700000000000, + "memory": "Caroline attended an LGBTQ conference on community building", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "caroline" + }, + "strategy_id": "semantic_53d1751c", + "strategy_type": "SEMANTIC", + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "tags": { + "topic": "wellness" + } + } + } + ] + } +} +``` + +## Response fields + +The response uses the standard OpenSearch search response format. For field descriptions, see [Semantic search memory response fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory/#response-fields). + +The `memory_embedding` field is excluded from the response. + +## Related documentation + +- [Hybrid search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/) diff --git a/_ml-commons-plugin/api/agentic-memory-apis/index.md b/_ml-commons-plugin/api/agentic-memory-apis/index.md new file mode 100644 index 00000000..841859c6 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/index.md @@ -0,0 +1,49 @@ +--- +layout: default +title: Agentic memory APIs +parent: ML APIs +has_children: true +has_toc: false +nav_order: 70 +redirect_from: + - /ml-commons-plugin/api/agentic-memory-apis/ +--- + +# Agentic memory APIs +**Introduced 3.3** +{: .label .label-purple } + +Agentic memory APIs provide persistent memory management for AI agents. For an overview of concepts, use cases, and getting started information, see [Agentic memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/). + +## Disabling agentic memory APIs + +Agentic memory APIs are enabled by default. To disable agentic memory APIs, update the following cluster setting: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.agentic_memory_enabled": false + } +} +``` +{% include copy-curl.html %} + +OpenSearch supports the following memory container APIs: + +- [Create memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/) +- [Get memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/get-memory-container/) +- [Update memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/update-memory-container/) +- [Delete memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/delete-memory-container/) +- [Search memory container]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/search-memory-container/) + +OpenSearch supports the following memory APIs: + +- [Add memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/add-memory/) +- [Create session]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-session/) +- [Get memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/get-memory/) +- [Update memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/update-memory/) +- [Delete memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/delete-memory/) +- [Search memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/search-memory/) +- [Semantic search memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory/) +- [Hybrid search memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory/) diff --git a/_ml-commons-plugin/api/agentic-memory-apis/search-memory-container.md b/_ml-commons-plugin/api/agentic-memory-apis/search-memory-container.md new file mode 100644 index 00000000..399ec1c5 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/search-memory-container.md @@ -0,0 +1,107 @@ +--- +layout: default +title: Search memory containers +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 25 +--- + +# Search Memory Containers API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to search for memory containers using OpenSearch query domain-specific language (DSL). + +## Endpoints + +```json +GET /_plugins/_ml/memory_containers/_search +POST /_plugins/_ml/memory_containers/_search +``` + +## Request fields + +The request body supports standard OpenSearch query DSL. For more information, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +## Example request + +```json +GET /_plugins/_ml/memory_containers/_search +{ + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-ml-am-memory-container", + "_id": "HudqiJkB1SltqOcZusVU", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "created_time": 1757956737699, + "last_updated_time": 1757956737699, + "configuration": { + "embedding_model_id": "uXZAtJkBvHNmcp1JAROh", + "strategies": [ + { + "namespace": ["user_id"], + "id": "semantic_53d1751c", + "type": "SEMANTIC", + "enabled": true + } + ], + "max_infer_size": 5, + "embedding_dimension": 1024, + "index_prefix": "default", + "use_system_index": true, + "llm_id": "aFouy5kBrfmzAZ6R6wo-", + "disable_history": false, + "embedding_model_type": "TEXT_EMBEDDING", + "disable_session": false + }, + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization" + } + }, + ... + ] + } +} +``` + +## Response fields + +The response uses the standard OpenSearch search response format. The following table lists the fields in the `_source` object of each element of the `hits` array. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `name` | String | The name of the memory container. | +| `description` | String | The description of the memory container. | +| `configuration` | Object | The memory container configuration, including models and strategies. | +| `created_time` | Long | The timestamp of when the container was created. | +| `last_updated_time` | Long | The timestamp of when the container was last updated. | +| `backend_roles` | Array | The backend roles that have access to the container. Present only if backend roles are configured. | diff --git a/_ml-commons-plugin/api/agentic-memory-apis/search-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/search-memory.md new file mode 100644 index 00000000..b151bbce --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/search-memory.md @@ -0,0 +1,201 @@ +--- +layout: default +title: Search agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 54 +--- + +# Search Agentic Memory API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to search for memories of a specific type within a memory container. This unified API supports searching `sessions`, `working`, `long-term`, and `history` [memory types]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-types). + +## Endpoints + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/_search +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/_search +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container. | +| `type` | String | Required | The memory type. Valid values are `sessions`, `working`, `long-term`, and `history`. | + +## Request fields + +The request body supports standard OpenSearch query domain-specific language (DSL). For more information, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +## Example request: Search sessions + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example request: Search long-term memories + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "namespace.user_id": "bob" + } + } + ] + } + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example request: Search a history memory + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/history/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example request: Search working memories with a namespace filter + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "namespace.user_id": "bob" + } + } + ], + "must_not": [ + { + "exists": { + "field": "tags.parent_memory_id" + } + } + ] + } + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example request: Search trace data by session + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/_search +{ + "query": { + "term": { + "namespace.session_id": "123" + } + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": ".plugins-ml-am-default-memory-sessions", + "_id": "CcxjTpkBvwXRq366A1aE", + "_version": 1, + "_seq_no": 10, + "_primary_term": 1, + "_score": null, + "_source": { + "summary": "This is a test session", + "created_time": 1757956735881, + "last_updated_time": 1757956735881, + "namespace": { + "user_id": "bob" + }, + "memory_container_id": "HudqiJkB1SltqOcZusVU" + }, + "sort": [ + 1757956735881 + ] + } + ] + } +} +``` + +## Response fields + +The response fields vary depending on the memory type being searched. For field descriptions, see [Get memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/get-memory/#response-fields). diff --git a/_ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory.md new file mode 100644 index 00000000..4b2bc607 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory.md @@ -0,0 +1,177 @@ +--- +layout: default +title: Semantic search agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 60 +--- + +# Semantic Search Agentic Memory API +**Introduced 3.6** +{: .label .label-purple } + +Use this API to search long-term memories using natural language queries. OpenSearch automatically generates embeddings from your query text and performs vector similarity search against stored memory embeddings. This eliminates the need to manually construct k-NN queries with pregenerated embeddings. + +The memory container must have an embedding model and at least one [memory strategy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-processing-strategies) configured. +{: .note} + +## Endpoints + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_semantic_search +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_semantic_search +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container. | + +## Request fields + +The following table lists the available request fields. + +| Field | Data type | Required/Optional | Default | Description | +| :--- | :--- | :--- | :--- | :--- | +| `query` | String | Required | N/A | A natural language search query. OpenSearch generates the embedding automatically using the memory container's configured embedding model. | +| `k` | Integer | Optional | 10 | The number of results to return. Valid values are 1–10,000. | +| `namespace` | Object | Optional | N/A | Filters results by namespace fields. For example, `{"user_id": "alice"}`. | +| `tags` | Object | Optional | N/A | Filters results by tag fields. For example, `{"topic": "food"}`. | +| `min_score` | Float | Optional | N/A | The minimum relevance score threshold. Results below this score are excluded. | +| `filter` | Object | Optional | N/A | An additional [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) filter applied alongside the semantic query. | + +## Example request: Basic semantic search + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_semantic_search +{ + "query": "retirement planning portfolio rebalancing", + "k": 5, + "namespace": { + "user_id": "bob" + } +} +``` +{% include copy-curl.html %} + +## Example request: Minimum score and tags filter + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_semantic_search +{ + "query": "client risk tolerance and investment preferences", + "k": 5, + "namespace": { + "user_id": "bob" + }, + "tags": { + "topic": "finance" + }, + "min_score": 0.6 +} +``` +{% include copy-curl.html %} + +## Example request: Query DSL filter + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_semantic_search +{ + "query": "programming languages for data science", + "k": 10, + "namespace": { + "user_id": "alice" + }, + "filter": { + "range": { + "created_time": { + "gte": 1700000000000 + } + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.87, + "hits": [ + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "abc123", + "_score": 0.87, + "_source": { + "created_time": 1700000000000, + "memory": "Client plans to retire in five years with a gradual rebalancing strategy", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "bob" + }, + "strategy_id": "semantic_53d1751c", + "strategy_type": "SEMANTIC", + "memory_container_id": "HudqiJkB1SltqOcZusVU" + } + }, + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "def456", + "_score": 0.82, + "_source": { + "created_time": 1700000000000, + "memory": "Client prefers conservative investments and wants to shift away from equities", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "bob" + }, + "strategy_id": "user_preference_0771b88e", + "strategy_type": "USER_PREFERENCE", + "memory_container_id": "HudqiJkB1SltqOcZusVU" + } + } + ] + } +} +``` + +## Response fields + +The response uses the standard OpenSearch search response format. Each hit in the `hits.hits` array contains the following fields in `_source`. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory` | String | The extracted memory text. | +| `strategy_type` | String | The strategy that produced this memory (`SEMANTIC`, `USER_PREFERENCE`, or `SUMMARY`). | +| `namespace` | Object | The namespace fields associated with this memory. | +| `namespace_size` | Integer | The number of namespace fields. | +| `strategy_id` | String | The ID of the strategy that produced this memory. | +| `tags` | Object | The tags associated with this memory. Present only if the memory has tags. | +| `memory_container_id` | String | The ID of the memory container. | +| `created_time` | Long | The timestamp when the memory was created. | +| `last_updated_time` | Long | The timestamp when the memory was last updated. | + +The `memory_embedding` field is excluded from the response. + +## Related documentation + +- [Semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/semantic-search/) \ No newline at end of file diff --git a/_ml-commons-plugin/api/agentic-memory-apis/update-memory-container.md b/_ml-commons-plugin/api/agentic-memory-apis/update-memory-container.md new file mode 100644 index 00000000..d92099c6 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/update-memory-container.md @@ -0,0 +1,129 @@ +--- +layout: default +title: Update memory container +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 15 +--- + +# Update Memory Container API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to update an existing memory container's properties, such as name, description, configuration, and access permissions. + +## Endpoints + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +``` + +## Path parameters + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container to update. | + +## Request fields + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `name` | String | Optional | The updated name of the memory container. | +| `description` | String | Optional | The updated description of the memory container. | +| `backend_roles` | Array | Optional | A list of backend roles for access control. Overwrites the existing list. | +| `configuration` | Object | Optional | The configuration object containing strategies and embedding settings. See [The configuration object](#the-configuration-object). | + +### The configuration object + +The `configuration` object supports the following fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `llm_id` | String | Optional | The large language model (LLM) ID to use to extract facts. | +| `max_infer_size` | Integer | Optional | The maximum number of similar existing memories retrieved during memory consolidation. Maximum is `10`. To update this value, include `llm_id` in the same request. | +| `strategies` | Array | Optional | An array of strategy objects for memory processing. Each strategy supports the `id`, `type`, `namespace`, `enabled`, and `configuration` fields. For field descriptions, see [The strategies array]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/create-memory-container/#the-strategies-array). | +| `embedding_model_id` | String | Optional | The embedding model ID. Can only be updated if no long-term memory index exists. | +| `embedding_model_type` | String | Optional | The embedding model type. Can only be updated if no long-term memory index exists. | +| `embedding_dimension` | Integer | Optional | The embedding dimension. Can only be updated if no long-term memory index exists. | +| `retention_policy` | Object | Optional | The retention limits for each memory type. Changes are merged into the existing policy. Set to `null` to remove the policy. For more information, see [Agentic memory retention]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory-retention/). | + +## Update behavior + +Note the following update behavior. + +### Strategy updates + +- To update a specific strategy, specify the strategy `id`. Only the fields that you provide are updated. You cannot change the `type` of an existing strategy. +- To create a new strategy, specify a strategy without an `id`. +- To disable a strategy without removing it, set its `enabled` field to `false`. + +### Backend roles updates + +- Adding new `backend_roles` grants new users read or write access with those roles. +- The new `backend_roles` field overwrites the existing field, so include the original roles if you want to keep them. + +### Namespace updates + +- The `namespace` field in the `strategies` object is updated by overwriting. Include the original namespace if you want to keep it. + +### Embedding model restrictions + +- The `embedding_model_id`, `embedding_model_type`, and `embedding_dimension` fields can only be updated if no long-term memory index has been created for this memory container. Once a long-term memory index with the specified `index_prefix` is created, these embedding fields cannot be updated. + +## Example request + +The following request updates the namespace of an existing strategy and adds a `USER_PREFERENCE` strategy. To find the IDs of existing strategies, use the [Get Memory Container API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/get-memory-container/): + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU +{ + "name": "opensearch-agents-memory", + "description": "Updated memory container for OpenSearch agents", + "backend_roles": ["admin", "ml_user"], + "configuration": { + "strategies": [ + { + "id": "semantic_53d1751c", + "namespace": ["user_id", "session_id"] + }, + { + "type": "USER_PREFERENCE", + "namespace": ["user_id"] + } + ] + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-am-memory-container", + "_id": "HudqiJkB1SltqOcZusVU", + "_version": 2, + "result": "updated", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 5, + "_primary_term": 1 +} +``` + +## Response fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_index` | String | The name of the index that stores memory containers. | +| `result` | String | The result of the update operation. | +| `_id` | String | The ID of the updated memory container. | +| `_version` | Integer | The version number of the updated memory container. | +| `_shards` | Object | Information about the shards involved in the operation. | +| `_seq_no` | Long | The sequence number assigned to the update operation. | +| `_primary_term` | Long | The primary term of the index. | diff --git a/_ml-commons-plugin/api/agentic-memory-apis/update-memory.md b/_ml-commons-plugin/api/agentic-memory-apis/update-memory.md new file mode 100644 index 00000000..071fa915 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-memory-apis/update-memory.md @@ -0,0 +1,144 @@ +--- +layout: default +title: Update agentic memory +parent: Agentic memory APIs +grand_parent: ML APIs +nav_order: 52 +--- + +# Update Agentic Memory API +**Introduced 3.3** +{: .label .label-purple } + +Use this API to update a specific memory by its type and ID. This unified API supports updating `sessions`, `working`, and `long-term` [memory types]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/#memory-types). `history` memory does not support updates. + +## Endpoints + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/{id} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | Required | The ID of the memory container. | +| `type` | String | Required | The memory type. Valid values are `sessions`, `working`, and `long-term`. Note that `history` memory cannot be updated. | +| `id` | String | Required | The ID of the memory to update. | + +## Request fields + +The request fields vary depending on the memory type being updated. All request fields are optional, but the request body must contain at least one field. Each field that you provide replaces the existing value of that field. For example, providing `tags` replaces all existing tags. + +### Session memory request fields + +The following table lists all session memory request body fields. + +| Field | Data type | Description | +|:-----------|:----------------------| :--- | +| `summary` | String | The summary of the session. +| `metadata` | Object | Additional metadata for the memory (for example, `status`, `branch`, or custom fields). | +| `agents` | Object | Additional information about the agents. | +| `additional_info` | Object | Additional metadata to associate with the session. | +| `pinned` | Boolean | Whether to pin the session so that it is exempt from the container's retention policy. Requires `plugins.ml_commons.memory.retention_enabled` to be `true`. For more information, see [Agentic memory retention]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory-retention/). | + +### Working memory request fields + +The following table lists all working memory request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `messages` | Array | Updated conversation messages (for conversation type). Optional. | +| `structured_data` | Object | Updated structured data content (for `data` memory payloads). | +| `structured_data_blob` | Object | Updated structured data that is stored but not indexed. | +| `binary_data` | String | Updated Base64-encoded binary data content (for `data` memory payloads). Optional. | +| `tags` | Object | Updated tags for categorization. | +| `metadata` | Object | Additional metadata for the memory (for example, `status`, `branch`, or custom fields). + +### Long-term memory request fields + +The following table lists all long-term memory request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory` | String | The updated memory content. Optional. | +| `tags` | Object | Updated tags for categorization. Optional. | +| `pinned` | Boolean | Whether to pin the memory so that it is exempt from the container's retention policy. Requires `plugins.ml_commons.memory.retention_enabled` to be `true`. Optional. | + +When you update the `memory` field, OpenSearch regenerates the memory embedding. + +## Example request: Update a session + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/N2CDipkB2Mtr6INFFcX8 +{ + "additional_info": { + "key1": "value1", + "last_activity": "2025-09-15T17:30:00Z" + } +} +``` +{% include copy-curl.html %} + +## Example request: Update a working memory + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/XyEuiJkBeh2gPPwzjYWM +{ + "tags": { + "topic": "updated_topic", + "priority": "high" + } +} +``` +{% include copy-curl.html %} + +## Example request: Update a long-term memory + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/DcxjTpkBvwXRq366C1Zz +{ + "memory": "User's name is Bob Smith", + "tags": { + "topic": "personal info", + "updated": "true" + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-am-default-memory-sessions", + "_id": "N2CDipkB2Mtr6INFFcX8", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 11, + "_primary_term": 1 +} +``` + +## Response fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `_index` | String | The name of the index that stores the memory. | +| `result` | String | The result of the update operation. | +| `_id` | String | The ID of the updated memory. | +| `_version` | Integer | The version number of the updated memory. | +| `forced_refresh` | Boolean | Whether a refresh was forced after the operation. | +| `_shards` | Object | Information about the shards involved in the operation. | +| `_seq_no` | Long | The sequence number assigned to the update operation. | +| `_primary_term` | Long | The primary term of the index. | diff --git a/_ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template.md b/_ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template.md new file mode 100644 index 00000000..d6e21efb --- /dev/null +++ b/_ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template.md @@ -0,0 +1,52 @@ +--- +layout: default +title: Delete agentic search template +parent: Agentic search template APIs +grand_parent: ML APIs +nav_order: 50 +--- + +# Delete Agentic Search Template API +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +Use this API to delete a registered agentic search template. Deleting an agentic search template doesn't delete the stored script. + +## Endpoints + +```json +DELETE /_plugins/_ml/agentic_search_templates/{template_id} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`template_id` | String | Required | The ID of the agentic search template to delete. + +## Example request + +```json +DELETE /_plugins/_ml/agentic_search_templates/similar_search +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "template_id": "similar_search", + "status": "deleted" +} +``` + +If the template isn't registered, the API returns a `404` error. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/agentic_search_templates/delete`. diff --git a/_ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template.md b/_ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template.md new file mode 100644 index 00000000..8be8614e --- /dev/null +++ b/_ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template.md @@ -0,0 +1,78 @@ +--- +layout: default +title: Get agentic search template +parent: Agentic search template APIs +grand_parent: ML APIs +nav_order: 30 +--- + +# Get Agentic Search Template API +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +Use this API to retrieve a registered agentic search template, including its parameter schema. + +## Endpoints + +```json +GET /_plugins/_ml/agentic_search_templates/{template_id} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`template_id` | String | Required | The ID of the agentic search template to retrieve. + +## Example request + +```json +GET /_plugins/_ml/agentic_search_templates/similar_search +``` +{% include copy-curl.html %} + +## Example response + +The following response is for the template registered with a provided parameter schema in the [Register Agentic Search Template API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template/#example-request-provide-the-parameter-schema) example: + +```json +{ + "template_id": "similar_search", + "index_binding": "products", + "description": "Fuzzy search for products similar to a name", + "param_schema": { + "query_text": { + "type": "string", + "required": true, + "description": "The product name to match. May contain misspellings." + } + }, + "created_time": 1792716795385, + "last_updated_time": 1792716795385 +} +``` + +If the template isn't registered, the API returns a `404` error. + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`template_id` | String | The agentic search template ID, which is also the stored script ID. +`index_binding` | String | The index that the template searches. +`description` | String | The template description, if one was provided or derived. +`param_schema` | Object | The parameter schema. See [The `param_schema` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template/#the-param_schema-object). +`created_time` | Long | The time at which the template was registered, in epoch milliseconds. +`last_updated_time` | Long | The time at which the template was last updated, in epoch milliseconds. +`created_by` | String | The user who registered the template. Present only when the Security plugin is enabled. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/agentic_search_templates/get`. diff --git a/_ml-commons-plugin/api/agentic-search-template-apis/index.md b/_ml-commons-plugin/api/agentic-search-template-apis/index.md new file mode 100644 index 00000000..ab820b2c --- /dev/null +++ b/_ml-commons-plugin/api/agentic-search-template-apis/index.md @@ -0,0 +1,46 @@ +--- +layout: default +title: Agentic search template APIs +parent: ML APIs +has_children: true +has_toc: false +nav_order: 80 +redirect_from: + - /ml-commons-plugin/api/agentic-search-template-apis/ +--- + +# Agentic search template APIs +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +Agentic search template APIs register stored search templates so that agentic search can have a large language model (LLM) fill their parameters instead of writing the full query. For an overview and a complete example, see [Filling search templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/index/). + +OpenSearch supports the following agentic search template APIs: + +- [Register agentic search template]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template/) +- [Get agentic search template]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template/) +- [List agentic search templates]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates/) +- [Update agentic search template]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template/) +- [Delete agentic search template]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template/) + +Agentic search templates are not supported when multi-tenancy is enabled. +{: .note} + +## Enabling agentic search template APIs + +To enable the agentic search template APIs and the `SearchTemplateFillTool`, update the following cluster setting: + +```json +PUT _cluster/settings +{ + "persistent": { + "plugins.ml_commons.agentic_search_template_enabled": true + } +} +``` +{% include copy-curl.html %} + +For more information about enabling experimental features, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). diff --git a/_ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates.md b/_ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates.md new file mode 100644 index 00000000..8fbfe875 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates.md @@ -0,0 +1,77 @@ +--- +layout: default +title: List agentic search templates +parent: Agentic search template APIs +grand_parent: ML APIs +nav_order: 40 +--- + +# List Agentic Search Templates API +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +Use this API to list registered agentic search templates. + +## Endpoints + +```json +GET /_plugins/_ml/agentic_search_templates +``` + +## Query parameters + +The following table lists the available query parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`from` | Integer | Optional | The starting index for pagination. Must be non-negative. Default is `0`. +`size` | Integer | Optional | The maximum number of templates to return. Valid values are 1--1000. Default is `10`. + +## Example request + +```json +GET /_plugins/_ml/agentic_search_templates?from=0&size=10 +``` +{% include copy-curl.html %} + +## Example response + +The following response lists a single registered template: + +```json +{ + "total": 1, + "templates": [ + { + "template_id": "similar_search", + "index_binding": "products", + "description": "Fuzzy search for products similar to a name", + "param_schema": { + "query_text": { + "type": "string", + "required": true, + "description": "The product name to match. May contain misspellings." + } + }, + "created_time": 1792716795385, + "last_updated_time": 1792716795385 + } + ] +} +``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`total` | Long | The total number of registered templates. +`templates` | Array | The templates on the requested page. Each template contains the fields described in [Get Agentic Search Template API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template/#response-body-fields). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/agentic_search_templates/list`. diff --git a/_ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template.md b/_ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template.md new file mode 100644 index 00000000..8c63c555 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template.md @@ -0,0 +1,98 @@ +--- +layout: default +title: Register agentic search template +parent: Agentic search template APIs +grand_parent: ML APIs +nav_order: 10 +--- + +# Register Agentic Search Template API +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +Use this API to register a stored search template for agentic search. Before registering, store the template using the [Create or Update Stored Script API]({{site.url}}{{site.baseurl}}/api-reference/script-apis/create-stored-script/). + +During registration, OpenSearch reads the stored template and the index mapping, derives a parameter schema (unless you provide one), and verifies that the template renders valid JSON both with all parameters filled and with only the required parameters filled. OpenSearch rejects a template that fails this validation. + +## Endpoints + +```json +POST /_plugins/_ml/agentic_search_templates +``` + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`template_id` | String | Required | The ID of a search template stored using `PUT _scripts/<template_id>`. Also used as the agentic search template ID. +`index` | String | Required | The index that the template searches. The [`SearchTemplateFillTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-template-fill-tool/) uses the template only for searches on this index or on an alias or index pattern that resolves to indexes within it. For how the OpenSearch Agent Server uses this index, see [Filling templates in the agent server]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/agent-server/#step-1-create-a-connector-to-the-agent-server). +`description` | String | Optional | A description of what the template searches. Used to choose among several templates. If you omit both `description` and `param_schema`, OpenSearch attempts to derive a description from the template. +`param_schema` | Object | Optional | The parameter schema. If omitted, OpenSearch derives it from the template and the index mapping. If provided, it is stored as sent, and every parameter must appear in the template. See [The `param_schema` object](#the-param_schema-object). + +### The param_schema object + +The `param_schema` object maps each template parameter to an object with the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`type` | String | Required | The parameter type. Derived schemas use `string`, `number`, `boolean`, or `array`. An `array` parameter is passed as a raw JSON string and must be rendered using triple braces (`{% raw %}{{{param}}}{% endraw %}`). +`required` | Boolean | Optional | Whether the LLM must provide the parameter. Default is `false`. +`enum` | Array | Optional | The allowed values. Each value must match `type`: a number for `number`, a Boolean for `boolean`, and a string otherwise. For a parameter named `field` or `sort_by`, or one whose name ends in `_field`, derived schemas take the allowed values from the index mapping's field names. When the parameter sets the sort field, only sortable fields are listed; for example, a `text` field is omitted but its `keyword` subfield is included. +`description` | String | Optional | Describes the parameter to the LLM. +`source` | String | Optional | Set to `mapping` in derived schemas when `enum` contains field names from the index mapping. + +## Example request: Derive the parameter schema + +```json +POST /_plugins/_ml/agentic_search_templates +{ + "template_id": "product_search", + "index": "products", + "description": "Product search by title with an optional category filter and an optional descending sort" +} +``` +{% include copy-curl.html %} + +## Example request: Provide the parameter schema + +```json +POST /_plugins/_ml/agentic_search_templates +{ + "template_id": "similar_search", + "index": "products", + "description": "Fuzzy search for products similar to a name", + "param_schema": { + "query_text": { + "type": "string", + "required": true, + "description": "The product name to match. May contain misspellings." + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "template_id": "similar_search", + "status": "created" +} +``` + +If an agentic search template with the same ID is already registered, the API returns a `409` error. If no stored script exists with the specified ID, the API returns a `400` error. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/agentic_search_templates/register`. Because OpenSearch reads the stored script and the index as the calling user, you also need `cluster:admin/script/get` and `indices:admin/get` on the specified index. + +## Related documentation + +- [Filling search templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/index/) +- [Search templates]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/index/) diff --git a/_ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template.md b/_ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template.md new file mode 100644 index 00000000..d6fa0f04 --- /dev/null +++ b/_ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template.md @@ -0,0 +1,82 @@ +--- +layout: default +title: Update agentic search template +parent: Agentic search template APIs +grand_parent: ML APIs +nav_order: 20 +--- + +# Update Agentic Search Template API +**Introduced 3.10** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/opensearch-agent-server/issues/150). +{: .warning} + +Use this API to update the description or parameter schema of a registered agentic search template. To change the query itself, update the stored script. To change the index that the template searches, delete the template and register it again. + +The OpenSearch Agent Server caches each template's parameter schema for 60 seconds, so an update can take up to 60 seconds to reach the agent server. + +## Endpoints + +```json +PUT /_plugins/_ml/agentic_search_templates/{template_id} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`template_id` | String | Required | The ID of the agentic search template to update. + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`description` | String | Optional | A description of what the template searches. +`param_schema` | Object | Optional | Changes to the parameter schema. For each parameter that you specify, the fields that you provide replace the stored fields, and the other fields are unchanged. You can't add parameters that aren't in the stored schema. OpenSearch validates the merged schema against the template before saving it. See [The `param_schema` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template/#the-param_schema-object). + +## Example request + +The following request limits the `sort_by` parameter derived for the `product_search` template to the `price` field and leaves the parameter's other fields unchanged: + +```json +PUT /_plugins/_ml/agentic_search_templates/product_search +{ + "param_schema": { + "sort_by": { + "enum": ["price"] + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-agentic-search-templates", + "_id": "product_search", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` + +If the template isn't registered, the API returns a `404` error. If the merged schema is invalid or the template doesn't render valid JSON with it, the API returns a `400` error. + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/agentic_search_templates/update`. diff --git a/_ml-commons-plugin/api/connector-apis/create-connector.md b/_ml-commons-plugin/api/connector-apis/create-connector.md index 4225a240..627b0116 100644 --- a/_ml-commons-plugin/api/connector-apis/create-connector.md +++ b/_ml-commons-plugin/api/connector-apis/create-connector.md @@ -2,38 +2,87 @@ layout: default title: Create connector parent: Connector APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 10 --- -# Create a connector +# Create Connector API -Creates a standalone connector. For more information, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). +Creates a standalone connector. For more information, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). For information about how the `request_body` template and the pre- and post-processing functions build the request and process the response, see [Connector input and output]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/). To write a connector definition for a model that has no OpenSearch-provided blueprint, see [Creating a custom blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). -## Path and HTTP methods +## Endpoints ```json POST /_plugins/_ml/connectors/_create ``` -## Request fields +## Request body fields -For a list of request fields, see [Blueprint configuration parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints#configuration-parameters). +The following table lists the fields in a Create Connector API request. -#### Example request +| Field | Data type | Is required | Description | +|:-------------------------------------------------|:---|:------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `name` | String | Yes | The name of the connector. | +| `connector_id` | String | No | A unique identifier for the connector. If omitted, OpenSearch generates one automatically. | +| `description` | String | No | A description of the connector. | +| `version` | String | Yes | The connector version. | +| `protocol` | String | Yes | The protocol for the connection, which determines how OpenSearch authenticates to the platform. For AWS services, such as Amazon SageMaker and Amazon Bedrock, use `aws_sigv4`. For Google Cloud Vertex AI, use `google_cloud`. For all other platforms, use `http`. For more information, see [Connector authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-authentication/). | +| `parameters` | JSON object | No | Default values for the placeholders in the `url` and `request_body` templates of the connector actions. A value provided in a Predict API request overrides the default. OpenSearch inserts default values without escaping special characters, so they must be valid in the template as written. For more information, see [Connector input and output]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/). | +| `parameters.skip_validating_missing_parameters` | Boolean | No | If `true`, OpenSearch sends the request to the model even if the request body contains placeholders that have no value. If `false`, OpenSearch rejects the request. Default is `false`. | +| `credential` | JSON object | Depends on `protocol` | Defines the credential variables that OpenSearch uses to authenticate to your endpoint. Required for all protocols except `google_cloud` in Application Default Credentials mode (`auth_mode` set to `adc`) and the `mcp_sse` and `mcp_streamable_http` protocols, which resolve credentials outside the connector. For every other protocol, including `http`, omitting this object or leaving it empty returns a `400` error. The fields that this object accepts depend on the `protocol`. For more information, see [Connector authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-authentication/). | +| `actions` | JSON array | Yes | The operations that the connector supports. Each object defines the HTTP request that OpenSearch sends for one operation, such as `predict`. For the fields of each object, see [The `actions` object](#the-actions-object). | +| `backend_roles` | JSON array | No | A list of OpenSearch backend roles. For more information about configuring backend roles, see [Assigning backend roles to users]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#assigning-backend-roles-to-users). | +| `access_mode` | String | No | Sets the access mode for the connector, either `public`, `restricted`, or `private`. Default is `private`. For more information about `access_mode`, see [Model groups]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#model-groups). | +| `add_all_backend_roles` | Boolean | No | If `true`, all backend roles of the user creating the connector are added to the connector. If you set this parameter to `true` without specifying `access_mode`, the access mode is set to `restricted`. Can be used only with the `restricted` access mode, and the user must have at least one backend role. Cannot be specified at the same time as `backend_roles`. Admin users cannot set this parameter to `true`. | +| `client_config` | JSON object | No | The client configuration object, which provides settings for the client connections that the connector uses. These settings allow you to manage connection limits, timeouts, and TLS options, ensuring efficient and reliable communication. For more information, see [The `client_config` object](#the-client_config-object). | +| `provisioned_by` | String | No | An optional attribution tag identifying the plugin or client that provisioned the connector (for example, `flow-framework`). Included in ML statistics metrics. Set at creation time only; ignored by the Update Connector API. | -To create a standalone connector, send a request to the `connectors/_create` endpoint and provide all of the parameters described in [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/): +### The actions object + +The `actions` object supports the following fields. + +| Field | Data type | Description | +|:---|:---|:---| +| `action_type` | String | Required. Specifies the ML API operation to use upon connection. Valid values are `predict`, `batch_predict`, `batch_predict_status`, `cancel_batch_predict`, and `execute`. | +| `method` | String | Required. Defines the HTTP method for the API call. Supports `POST` and `GET`. | +| `url` | String | Required. The endpoint URL to which OpenSearch sends the request for this action. Can contain `${parameters.<parameter_name>}` placeholders. The URL must match one of the trusted endpoint patterns. For more information, see [Adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#adding-trusted-endpoints). Starting with OpenSearch 3.10, some addresses are always refused regardless of settings. For all endpoint address restrictions, see [Breaking changes]({{site.url}}{{site.baseurl}}/breaking-changes/#ml-commons-plugin-1). | +| `request_body` | String | Optional. The request body template that OpenSearch sends to the model endpoint for the action. Use `${parameters.<parameter_name>}` placeholders to insert parameter values, for example, `${parameters.inputText}`. For more information, see [Request body templates]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#request-body-templates). | +| `pre_process_function` | String | Optional. The name of a built-in preprocessing function or a custom Painless script that converts `text_docs` input or text similarity input into the parameters that fill the `request_body` template. For more information, see [Built-in pre- and post-processing functions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#built-in-pre--and-post-processing-functions) and [Custom pre- and post-processing functions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#custom-pre--and-post-processing-functions). | +| `post_process_function` | String | Optional. The name of a built-in post-processing function or a custom Painless script that converts the model response into the format that OpenSearch requires. For more information, see [Built-in pre- and post-processing functions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#built-in-pre--and-post-processing-functions) and [Custom pre- and post-processing functions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#custom-pre--and-post-processing-functions). | +| `headers` | JSON object | Optional. The HTTP headers that OpenSearch sends with the request for this action. To authenticate, refer to values in the `credential` object using `${credential.<credential_name>}` placeholders, for example, `"Authorization": "Bearer ${credential.openAI_key}"`. If you don't specify a `Content-Type` header, OpenSearch sends `Content-Type: application/json`. | +| `supports_structured_output` | Boolean | Optional. Applies only to `predict` actions of LLM connectors used for [agentic memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/) fact extraction. If `true`, OpenSearch adds a structured output field to the request body during fact extraction so that the model returns the extracted facts in a fixed JSON schema (constrained decoding). OpenSearch selects the field based on the provider in the action `url`: `toolConfig` for the Amazon Bedrock Converse API, `generationConfig` for Google Gemini, and `response_format` for OpenAI, Azure OpenAI, DeepSeek, the Cohere v2 Chat API, and other endpoints whose path contains `/v1/chat/completions`. The field is added only if the `request_body` is a JSON object. If `false`, or if OpenSearch does not recognize the provider, OpenSearch adds format instructions to the fact extraction prompt. Default is `false`. | + +### The client_config object + +The `client_config` object supports the following fields. + +| Field | Data type | Description | +|:---|:---|:---| +| `max_connection` | Integer | The maximum number of concurrent connections that the client can establish to the server. Some remote services, like SageMaker, constrain the maximum number of concurrent connections and throw a throttling exception if the number of concurrent connections exceeds the threshold. The maximum number of concurrent OpenSearch connections is `max_connection`*`node_number_for_connector`. To mitigate this issue, try to decrease the value of this parameter and modify the retry settings in `client_config`. Default is `30`. | +| `connection_timeout` | Integer | The maximum amount of time (in seconds) that the client waits while trying to establish a connection to the server. A timeout prevents the client from waiting indefinitely and allows the client to recover when it encounters unreachable network endpoints. Default is `30`. | +| `read_timeout` | Integer | The maximum amount of time (in seconds) that the client waits for a response from the server after sending a request. This is useful when the server is slow to respond or encounters an issue while processing a request. Default is `30`. | +| `retry_backoff_policy` | String | The backoff policy for retries to the remote connector. This is useful when there is spike in traffic causing throttling exceptions. Supported policies are `constant`, `exponential_equal_jitter`, and `exponential_full_jitter`. Default is `constant`. | +| `max_retry_times` | Integer | The maximum number of times that a single remote inference request is retried. This is useful when there is a spike in traffic causing throttling exceptions. When set to `0`, retrying is disabled. When set to `-1`, OpenSearch does not limit the number of `retry_times`. Setting this to a positive integer specifies the maximum number of retry attempts. Default is `0`. | +| `retry_backoff_millis` | Integer | The base backoff time in milliseconds for retry policy. The suspend time during two retries is determined by this parameter and `retry_backoff_policy`. Default is `200`. | +| `retry_timeout_seconds` | Integer | The timeout value, in seconds, for the retry. If the retry can not succeed within the specified amount of time, the connector stops retrying and throws an exception. Default is `30`. | +| `skip_ssl_verification` | Boolean | If set to `true`, disables SSL certificate verification for the connector, allowing connections to endpoints with self-signed or otherwise invalid certificates. Use only in development or testing environments. If set to `false`, SSL certificate verification remains enabled (recommended for production). Default is `false`. | +| `mutual_tls_enabled` | Boolean | If set to `true`, the connector presents a client certificate to the endpoint using mutual TLS (mTLS). Provide the certificate material in the connector's `credential` object. Supported only for connectors that use the `http` protocol. Cannot be enabled together with `skip_ssl_verification`. Default is `false`. For more information, see [Client certificate authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/#client-certificate-authentication). | +| `keystore_type` | String | The format of the client certificate material supplied in the `credential` object. Valid values are `PEM` and `PKCS12` (not case sensitive). Applies only when `mutual_tls_enabled` is `true`. Default is `PEM`. | + +## Example request + +The following request creates a standalone connector to the OpenAI `gpt-4o-mini` chat model: ```json POST /_plugins/_ml/connectors/_create { "name": "OpenAI Chat Connector", - "description": "The connector to public OpenAI model service for GPT 3.5", + "description": "The connector to public OpenAI model service for gpt-4o-mini", "version": 1, "protocol": "http", "parameters": { "endpoint": "api.openai.com", - "model": "gpt-3.5-turbo" + "model": "gpt-4o-mini" }, "credential": { "openAI_key": "..." @@ -53,7 +102,7 @@ POST /_plugins/_ml/connectors/_create ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { diff --git a/_ml-commons-plugin/api/connector-apis/delete-connector.md b/_ml-commons-plugin/api/connector-apis/delete-connector.md index 75dff320..bba906c3 100644 --- a/_ml-commons-plugin/api/connector-apis/delete-connector.md +++ b/_ml-commons-plugin/api/connector-apis/delete-connector.md @@ -2,28 +2,31 @@ layout: default title: Delete connector parent: Connector APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 30 --- -# Delete a connector +# Delete Connector API Deletes a standalone connector. For more information, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). -## Path and HTTP methods +You cannot delete a connector that is used by a model. Delete the models that use the connector or update them to use a different connector, and then delete the connector. +{: .important} + +## Endpoints ```json -DELETE /_plugins/_ml/connectors/<connector_id> +DELETE /_plugins/_ml/connectors/{connector_id} ``` -#### Example request +## Example request ```json DELETE /_plugins/_ml/connectors/KsAo1YsB0jLkkocY6j4U ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -31,12 +34,34 @@ DELETE /_plugins/_ml/connectors/KsAo1YsB0jLkkocY6j4U "_id" : "KsAo1YsB0jLkkocY6j4U", "_version" : 1, "result" : "deleted", + "forced_refresh" : true, "_shards" : { - "total" : 2, - "successful" : 2, + "total" : 1, + "successful" : 1, "failed" : 0 }, "_seq_no" : 27, "_primary_term" : 18 } +``` + +## Error responses + +If you attempt to delete a connector that doesn't exist, OpenSearch returns a 200 response with `"result": "not_found"` rather than an error: + +```json +{ + "_index": ".plugins-ml-connector", + "_id": "nonexistent-connector-id", + "_version": 1, + "result": "not_found", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} ``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/connector-apis/get-connector.md b/_ml-commons-plugin/api/connector-apis/get-connector.md index 6a8507cd..5be4d4bb 100644 --- a/_ml-commons-plugin/api/connector-apis/get-connector.md +++ b/_ml-commons-plugin/api/connector-apis/get-connector.md @@ -2,34 +2,34 @@ layout: default title: Get connector parent: Connector APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 20 --- -# Get a connector +# Get Connector API This API retrieves a connector by its ID. -### Path and HTTP methods +## Endpoints ```json -GET /_plugins/_ml/connectors/<connector_id> +GET /_plugins/_ml/connectors/{connector_id} ``` -#### Example request +## Example request ```json GET /_plugins/_ml/connectors/N8AE1osB0jLkkocYjz7D ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { - "name" : "BedRock Claude-Instant v1", + "name" : "BedRock Claude Sonnet 4.6", "version" : "1", - "description" : "Bedrock connector for Claude Instant testing", + "description" : "Bedrock connector for Claude Sonnet 4.6 testing", "protocol" : "aws_sigv4", "parameters" : { "endpoint" : "bedrock.us-east-1.amazonaws.com", @@ -43,13 +43,15 @@ GET /_plugins/_ml/connectors/N8AE1osB0jLkkocYjz7D { "action_type" : "PREDICT", "method" : "POST", - "url" : "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-instant-v1/invoke", + "url" : "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", "headers" : { "x-amz-content-sha256" : "required", "content-type" : "application/json" }, - "request_body" : "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" + "request_body" : "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" } - ] + ], + "created_time" : 1792088573796, + "last_updated_time" : 1792088573796 } ``` diff --git a/_ml-commons-plugin/api/connector-apis/index.md b/_ml-commons-plugin/api/connector-apis/index.md index a8945bb8..5d3947da 100644 --- a/_ml-commons-plugin/api/connector-apis/index.md +++ b/_ml-commons-plugin/api/connector-apis/index.md @@ -1,15 +1,17 @@ --- layout: default title: Connector APIs -parent: ML Commons APIs +parent: ML APIs has_children: true has_toc: false -nav_order: 25 +nav_order: 30 +redirect_from: + - /ml-commons-plugin/api/connector-apis/ --- # Connector APIs -ML Commons supports the following connector APIs: +OpenSearch supports the following connector APIs: - [Create connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/) - [Get connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/get-connector/) diff --git a/_ml-commons-plugin/api/connector-apis/search-connector.md b/_ml-commons-plugin/api/connector-apis/search-connector.md index 3b59d51a..1e8e6b87 100644 --- a/_ml-commons-plugin/api/connector-apis/search-connector.md +++ b/_ml-commons-plugin/api/connector-apis/search-connector.md @@ -2,22 +2,22 @@ layout: default title: Search connector parent: Connector APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 25 --- -# Search for a connector +# Search Connector API Use the `_search` endpoint to search for a connector. This API uses a query to search for matching connectors. -## Path and HTTP methods +## Endpoints ```json POST /_plugins/_ml/connectors/_search GET /_plugins/_ml/connectors/_search ``` -#### Example request +## Example request ```json POST /_plugins/_ml/connectors/_search @@ -30,7 +30,7 @@ POST /_plugins/_ml/connectors/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -57,7 +57,9 @@ POST /_plugins/_ml/connectors/_search "_primary_term" : 1, "_score" : 1.0, "_source" : { + "created_time" : 1792088563675, "protocol" : "aws_sigv4", + "last_updated_time" : 1792088563675, "name" : "BedRock claude Connector", "description" : "The connector to BedRock service for claude model", "version" : "1", @@ -65,10 +67,10 @@ POST /_plugins/_ml/connectors/_search "endpoint" : "bedrock.us-east-1.amazonaws.com", "content_type" : "application/json", "auth" : "Sig_V4", - "max_tokens_to_sample" : "8000", + "max_tokens" : "8000", "service_name" : "bedrock", "temperature" : "1.0E-4", - "response_filter" : "$.completion", + "response_filter" : "$.content[0].text", "region" : "us-east-1", "anthropic_version" : "bedrock-2023-05-31" }, @@ -79,9 +81,9 @@ POST /_plugins/_ml/connectors/_search "content-type" : "application/json" }, "method" : "POST", - "request_body" : "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }", + "request_body" : "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }", "action_type" : "PREDICT", - "url" : "https://bedrock.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke" + "url" : "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" } ] } @@ -94,7 +96,9 @@ POST /_plugins/_ml/connectors/_search "_primary_term" : 1, "_score" : 1.0, "_source" : { + "created_time" : 1792088569179, "protocol" : "aws_sigv4", + "last_updated_time" : 1792088569179, "name" : "BedRock claude Connector", "description" : "The connector to BedRock service for claude model", "version" : "1", @@ -102,10 +106,10 @@ POST /_plugins/_ml/connectors/_search "endpoint" : "bedrock.us-east-1.amazonaws.com", "content_type" : "application/json", "auth" : "Sig_V4", - "max_tokens_to_sample" : "8000", + "max_tokens" : "8000", "service_name" : "bedrock", "temperature" : "1.0E-4", - "response_filter" : "$.completion", + "response_filter" : "$.content[0].text", "region" : "us-east-1", "anthropic_version" : "bedrock-2023-05-31" }, @@ -116,9 +120,9 @@ POST /_plugins/_ml/connectors/_search "content-type" : "application/json" }, "method" : "POST", - "request_body" : "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }", + "request_body" : "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }", "action_type" : "PREDICT", - "url" : "https://bedrock.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke" + "url" : "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" } ] } @@ -131,9 +135,11 @@ POST /_plugins/_ml/connectors/_search "_primary_term" : 1, "_score" : 1.0, "_source" : { + "created_time" : 1792088573796, "protocol" : "aws_sigv4", - "name" : "BedRock Claude-Instant v1", - "description" : "Bedrock connector for Claude Instant testing", + "last_updated_time" : 1792088573796, + "name" : "BedRock Claude Sonnet 4.6", + "description" : "Bedrock connector for Claude Sonnet 4.6 testing", "version" : "1", "parameters" : { "endpoint" : "bedrock.us-east-1.amazonaws.com", @@ -150,9 +156,9 @@ POST /_plugins/_ml/connectors/_search "content-type" : "application/json" }, "method" : "POST", - "request_body" : "{\"prompt\":\"${parameters.prompt}\", \"max_tokens_to_sample\":${parameters.max_tokens_to_sample}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }", + "request_body" : "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }", "action_type" : "PREDICT", - "url" : "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-instant-v1/invoke" + "url" : "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" } ] } diff --git a/_ml-commons-plugin/api/connector-apis/update-connector.md b/_ml-commons-plugin/api/connector-apis/update-connector.md index 64790bb5..dc66f363 100644 --- a/_ml-commons-plugin/api/connector-apis/update-connector.md +++ b/_ml-commons-plugin/api/connector-apis/update-connector.md @@ -2,56 +2,61 @@ layout: default title: Update connector parent: Connector APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 27 --- -# Update a connector +# Update Connector API **Introduced 2.12** {: .label .label-purple } -Use this API to update a standalone connector based on the `model_ID`. To update a connector created within a specific model, use the [Update Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/update-model/). +Use this API to update a standalone connector based on the connector ID. To update a connector created within a specific model, use the [Update Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/update-model/). Before updating a standalone connector, you must undeploy all models that use the connector. For information about undeploying a model, see [Undeploy Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/undeploy-model/). {: .note} -Using this API, you can update the connector fields listed in the [Request fields](#request-fields) section and add optional fields to your connector. You cannot delete fields from a connector using this API. +Using this API, you can update the connector fields listed in the [Request fields](#request-body-fields) section and add optional fields to your connector. You cannot delete fields from a connector using this API. For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json -PUT /_plugins/_ml/connectors/<connector_id> +PUT /_plugins/_ml/connectors/{connector_id} ``` -## Request fields +## Request body fields -The following table lists the updatable fields. For more information about all connector fields, see [Blueprint configuration parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints#configuration-parameters). +The following table lists the updatable fields. For more information about all connector fields, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). -| Field | Data type | Description | -| :--- | :--- | :--- | -| `name` | String | The name of the connector. | -| `description` | String | A description of the connector. | -| `version` | Integer | The version of the connector. | -| `protocol` | String | The protocol for the connection. For AWS services, such as Amazon SageMaker and Amazon Bedrock, use `aws_sigv4`. For all other services, use `http`. | -| `parameters` | JSON object | The default connector parameters, including `endpoint` and `model`. Any parameters included in this field can be overridden by parameters specified in a predict request. | -| `credential` | JSON object | Defines any credential variables required in order to connect to your chosen endpoint. ML Commons uses **AES/GCM/NoPadding** symmetric encryption to encrypt your credentials. When the connection to the cluster first starts, OpenSearch creates a random 32-byte encryption key that persists in OpenSearch's system index. Therefore, you do not need to manually set the encryption key. | -| `actions` | JSON array | Defines which actions can run within the connector. If you're an administrator creating a connection, add the [blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/) for your desired connection. | -| `backend_roles` | JSON array | A list of OpenSearch backend roles. For more information about setting up backend roles, see [Assigning backend roles to users]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#assigning-backend-roles-to-users). | -| `access_mode` | String | Sets the access mode for the model, either `public`, `restricted`, or `private`. Default is `private`. For more information about `access_mode`, see [Model groups]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#model-groups). | +| Field | Data type | Description | +| :--- |:------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `name` | String | The name of the connector. | +| `description` | String | A description of the connector. | +| `version` | Integer | The connector version. | +| `protocol` | String | The protocol for the connection. For AWS services, such as Amazon SageMaker and Amazon Bedrock, use `aws_sigv4`. For all other services, use `http`. | +| `parameters` | JSON object | The default connector parameters, including `endpoint` and `model`. Any parameters included in this field can be overridden by parameters specified in a predict request. | +| `credential` | JSON object | Defines any credential variables required in order to connect to your chosen endpoint. OpenSearch uses **AES/GCM/NoPadding** symmetric encryption to encrypt your credentials. When the connection to the cluster first starts, OpenSearch creates a random 32-byte encryption key that persists in OpenSearch's system index. Therefore, you do not need to manually set the encryption key. | +| `actions` | JSON array | The operations that the connector supports. Each object defines the HTTP request that OpenSearch sends for one operation, such as `predict`. For the fields of each object, see [The actions object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#the-actions-object). | +| `backend_roles` | JSON array | A list of OpenSearch backend roles. For more information about setting up backend roles, see [Assigning backend roles to users]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#assigning-backend-roles-to-users). | +| `add_all_backend_roles` | Boolean | Has no effect when updating a connector. To change the connector's backend roles, specify them in `backend_roles`. | +| `client_config` | JSON object | The client configuration object, which controls connection limits, timeouts, retries, and TLS options. For more information, see [The client_config object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#the-client_config-object). | +| `access_mode` | String | Sets the access mode for the connector, either `public`, `restricted`, or `private`. If omitted, the connector keeps its current access mode. For more information about `access_mode`, see [Model groups]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#model-groups). | +| `parameters.skip_validating_missing_parameters` | Boolean | When set to `true`, this option allows you to send a request using a connector without validating any missing parameters. Default is `false`. | -#### Example request + + +## Example request ```json PUT /_plugins/_ml/connectors/u3DEbI0BfUsSoeNTti-1 { - "description": "The connector to public OpenAI model service for GPT 3.5" + "description": "The connector to public OpenAI model service for gpt-4o-mini" } ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -59,6 +64,7 @@ PUT /_plugins/_ml/connectors/u3DEbI0BfUsSoeNTti-1 "_id": "u3DEbI0BfUsSoeNTti-1", "_version": 2, "result": "updated", + "forced_refresh": true, "_shards": { "total": 1, "successful": 1, diff --git a/_ml-commons-plugin/api/context-management-apis/create-context-management.md b/_ml-commons-plugin/api/context-management-apis/create-context-management.md new file mode 100644 index 00000000..d00cd2aa --- /dev/null +++ b/_ml-commons-plugin/api/context-management-apis/create-context-management.md @@ -0,0 +1,132 @@ +--- +layout: default +title: Create context management +parent: Context management APIs +grand_parent: ML APIs +nav_order: 10 +--- + +# Create Context Management API +**Introduced 3.5** +{: .label .label-purple } + +Use this API to configure [context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/) that defines teams of context managers to optimize agent context at specific execution points. + +## Endpoints + +```json +POST /_plugins/_ml/context_management/{context_management_name} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`context_management_name` | String | Required | The unique name for the context management. Must be 1--49 characters long and contain only lowercase letters, numbers, hyphens (`-`), and underscores (`_`). + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`description` | String | Optional | A human-readable description of what this context management does. +`hooks` | Object | Required | A map of hook names to lists of context manager configurations. Must contain at least one hook. See [The `hooks` object](#the-hooks-object). + +### The hooks object + +The `hooks` object maps hook names to arrays of context manager configurations. Hook names are case sensitive and must be uppercase. The API accepts other hook names, but context managers configured under them never run. The following hooks are supported. + +Hook | Description +:--- | :--- +`PRE_LLM` | Executes before sending requests to the large language model (LLM). +`POST_TOOL` | Executes after tool execution completes. + +Each hook contains an array of context manager configurations with the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`type` | String | Required | The context manager type. Valid values are `SlidingWindowManager`, `SummarizationManager`, and `ToolsOutputTruncateManager`. +`config` | Object | Optional | Configuration specific to the context manager type. If omitted, the default values are used. See [Context manager configurations](#context-manager-configurations). + +### Context manager configurations + +The following context manager configurations are supported based on the context manager type. + +#### SlidingWindowManager + +The `SlidingWindowManager` supports the following parameters in the `config` object. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`max_messages` | Integer | Optional | The maximum number of messages to retain. Default is `20`. +`activation` | Object | Optional | The activation rules. Defaults to always activated. See [Activation rules](#activation-rules). + +#### SummarizationManager + +The `SummarizationManager` supports the following parameters in the `config` object. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`summary_ratio` | Double | Optional | The ratio of messages to summarize (0.1--0.8). Default is `0.3`. +`preserve_recent_messages` | Integer | Optional | The number of recent messages to preserve. Default is `10`. +`summarization_model_id` | String | Optional | A model ID for summarization. Uses the agent's model if not specified. +`summarization_system_prompt` | String | Optional | A system prompt for summarization. If not specified, the default system prompt is used. +`activation` | Object | Optional | The activation rules. Defaults to always activated. See [Activation rules](#activation-rules). + +#### ToolsOutputTruncateManager + +The `ToolsOutputTruncateManager` supports the following parameters in the `config` object. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`max_output_length` | Integer | Optional | The maximum length of tool output to retain. Default is `40000`. +`activation` | Object | Optional | The activation rules. Defaults to always activated. See [Activation rules](#activation-rules). + +### Activation rules + +Activation rules determine when a context manager should execute. If omitted, the manager always executes. Multiple rules use `AND` logic---all rules must be satisfied for activation. For more information and examples, see [Activation rules]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/#activation-rules). + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`message_count_exceed` | Integer | Optional | Activates when the message count exceeds this threshold. +`tokens_exceed` | Integer | Optional | Activates when the token count exceeds this threshold. + +## Example request: Basic sliding window context management + +```json +POST /_plugins/_ml/context_management/basic-sliding-window +{ + "description": "Basic sliding window context management", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "message_count_exceed": 12 + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "context_management_name": "basic-sliding-window", + "status": "created" +} +``` + +## Related documentation + +For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). + diff --git a/_ml-commons-plugin/api/context-management-apis/delete-context-management.md b/_ml-commons-plugin/api/context-management-apis/delete-context-management.md new file mode 100644 index 00000000..5259d050 --- /dev/null +++ b/_ml-commons-plugin/api/context-management-apis/delete-context-management.md @@ -0,0 +1,70 @@ +--- +layout: default +title: Delete context management +parent: Context management APIs +grand_parent: ML APIs +nav_order: 40 +--- + +# Delete Context Management API +**Introduced 3.5** +{: .label .label-purple } + +Use this API to delete a context management configuration. Once deleted, the context management can no longer be used by agents. + +Agents store the name of the context management configuration, not a copy of it. After you delete a configuration, executing an agent registered with its name fails with a 404 error, and registering a new agent with its name fails with a 400 error. To run such an agent, recreate the configuration with the same name or specify a different configuration in the `context_management_name` parameter when executing the agent. +{: .note} + +## Endpoints + +```json +DELETE /_plugins/_ml/context_management/{context_management_name} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`context_management_name` | String | Required | The name of the context management to delete. + +## Example request + +```json +DELETE /_plugins/_ml/context_management/advanced-context-management +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "context_management_name": "advanced-context-management", + "status": "deleted" +} +``` + +## Error responses + +If you attempt to delete a context management configuration that doesn't exist, the API returns a 404 error indicating the resource was not found: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Context management template not found: sliding_window_max_40000_tokens_managers123" + } + ], + "type": "status_exception", + "reason": "Context management template not found: sliding_window_max_40000_tokens_managers123" + }, + "status": 404 +} +``` + +## Related documentation + +For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). \ No newline at end of file diff --git a/_ml-commons-plugin/api/context-management-apis/get-context-management.md b/_ml-commons-plugin/api/context-management-apis/get-context-management.md new file mode 100644 index 00000000..dff0852a --- /dev/null +++ b/_ml-commons-plugin/api/context-management-apis/get-context-management.md @@ -0,0 +1,84 @@ +--- +layout: default +title: Get context management +parent: Context management APIs +grand_parent: ML APIs +nav_order: 20 +--- + +# Get Context Management API +**Introduced 3.5** +{: .label .label-purple } + +Use this API to retrieve a context management configuration by its name. + +## Endpoints + +```json +GET /_plugins/_ml/context_management/{context_management_name} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`context_management_name` | String | Required | The name of the context management to retrieve. + +## Example request + +```json +GET /_plugins/_ml/context_management/token-aware-truncation +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "name": "token-aware-truncation", + "description": "Context management that truncates tool outputs longer than 100,000 characters and applies sliding window to keep last 6 messages when tokens exceed 200,000", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "tokens_exceed": 200000 + } + } + } + ], + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 100000 + } + } + ] + }, + "created_time": 1754943902286, + "last_modified": 1754943902286, + "created_by": "admin" +} +``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`name` | String | The name of the context management. +`description` | String | The description of the context management. +`hooks` | Object | A map of hook names to lists of context manager configurations. For more information, see [The `hooks` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/#the-hooks-object). +`created_time` | Long | The time when the context management was created, in epoch milliseconds. +`last_modified` | Long | The time when the context management was last updated, in epoch milliseconds. +`created_by` | String | The user who created the context management. Present only when the Security plugin is enabled. + +## Related documentation + +For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). \ No newline at end of file diff --git a/_ml-commons-plugin/api/context-management-apis/index.md b/_ml-commons-plugin/api/context-management-apis/index.md new file mode 100644 index 00000000..2d856113 --- /dev/null +++ b/_ml-commons-plugin/api/context-management-apis/index.md @@ -0,0 +1,24 @@ +--- +layout: default +title: Context management APIs +parent: ML APIs +has_children: true +has_toc: false +nav_order: 90 +redirect_from: + - /ml-commons-plugin/api/context-management-apis/ +--- + +# Context management APIs +**Introduced 3.5** +{: .label .label-purple } + +Context management APIs provide dynamic context optimization for AI agents. For an overview of concepts, use cases, and getting started information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). + +OpenSearch supports the following context management APIs: + +- [Create context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/) +- [Get context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/get-context-management/) +- [Update context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/update-context-management/) +- [Delete context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/delete-context-management/) +- [List context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/list-context-management/) diff --git a/_ml-commons-plugin/api/context-management-apis/list-context-management.md b/_ml-commons-plugin/api/context-management-apis/list-context-management.md new file mode 100644 index 00000000..d3a2967c --- /dev/null +++ b/_ml-commons-plugin/api/context-management-apis/list-context-management.md @@ -0,0 +1,89 @@ +--- +layout: default +title: List context management +parent: Context management APIs +grand_parent: ML APIs +nav_order: 50 +--- + +# List Context Management API +**Introduced 3.5** +{: .label .label-purple } + +Use this API to retrieve a list of all context management configurations in the cluster. + +## Endpoints + +```json +GET /_plugins/_ml/context_management +``` + +## Query parameters + +The following table lists the available query parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`size` | Integer | Optional | The maximum number of results to return. Valid values are 1--1000. Default is `10`. +`from` | Integer | Optional | The starting index for pagination. Default is `0`. + +## Example request + +```json +GET /_plugins/_ml/context_management +``` +{% include copy-curl.html %} + +## Example request with pagination + +```json +GET /_plugins/_ml/context_management?size=20&from=0 +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "total": 1, + "templates": [ + { + "name": "sliding_window_max_40000_tokens_managers", + "description": "Context management for truncating tool outputs to prevent input length issues", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 8 + } + } + ], + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 40000 + } + } + ] + }, + "created_time": 1769457277774, + "last_modified": 1769457277774 + } + ] +} +``` + +## Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`total` | Integer | The number of context management configurations returned in this response. +`templates` | Array | A list of context management configurations. For field descriptions, see [Get Context Management API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/get-context-management/#response-body-fields). + +## Related documentation + +For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). \ No newline at end of file diff --git a/_ml-commons-plugin/api/context-management-apis/update-context-management.md b/_ml-commons-plugin/api/context-management-apis/update-context-management.md new file mode 100644 index 00000000..a34ff5f9 --- /dev/null +++ b/_ml-commons-plugin/api/context-management-apis/update-context-management.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Update context management +parent: Context management APIs +grand_parent: ML APIs +nav_order: 30 +--- + +# Update Context Management API +**Introduced 3.5** +{: .label .label-purple } + +Use this API to update an existing context management configuration. You can modify the description, hooks configuration, and context manager settings. + +## Endpoints + +```json +PUT /_plugins/_ml/context_management/{context_management_name} +``` + +## Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`context_management_name` | String | Required | The name of the context management to update. + +## Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`description` | String | Optional | A human-readable description of what this context management does. +`hooks` | Object | Optional | A map of hook names to lists of context manager configurations. See [The `hooks` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/#the-hooks-object). + +The request body follows the same structure as the [Create Context Management API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/). Fields that you omit keep their existing values. In the `hooks` object, each hook that you specify replaces the existing configuration for that hook, and hooks that you omit are unchanged. + +## Example request: Update description + +```json +PUT /_plugins/_ml/context_management/advanced-context-management +{ + "description": "Updated description for advanced context management with multiple strategies" +} +``` +{% include copy-curl.html %} + +## Example request: Update hooks configuration + +```json +PUT /_plugins/_ml/context_management/sliding_window_max_40000_tokens_managers +{ + "description": "Context management for truncating tool outputs to prevent input length issues", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 8 + } + } + ], + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 40000 + } + } + ] + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-context-management-templates", + "_id": "sliding_window_max_40000_tokens_managers", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 4, + "_primary_term": 1 +} +``` + +## Related documentation + +For more information, see [Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/). \ No newline at end of file diff --git a/_ml-commons-plugin/api/controller-apis/create-controller.md b/_ml-commons-plugin/api/controller-apis/create-controller.md index 91a6be43..9def7418 100644 --- a/_ml-commons-plugin/api/controller-apis/create-controller.md +++ b/_ml-commons-plugin/api/controller-apis/create-controller.md @@ -2,30 +2,29 @@ layout: default title: Create controller parent: Controller APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 10 --- -# Create or update a controller +# Create or Update Controller API **Introduced 2.12** {: .label .label-purple } Use this API to create or update a controller for a model. A model may be shared by multiple users. A controller sets rate limits for the number of [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) calls users can make on the model. A controller consists of a set of rate limiters for different users. -You can only create a controller for a model once you have registered the model and received a model ID. +You can only create a controller for a model once you have registered the model and received a model ID. Controllers are supported only for text embedding models and externally hosted (remote) models. {: .tip} -The POST method creates a new controller. The PUT method updates an existing controller. +The POST method creates a new controller or overwrites an existing one. The PUT method updates an existing controller. If no controller exists for the model, a PUT request fails with a 409 Conflict error. To learn how to set rate limits at the model level for all users, see [Update Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/update-model/). The rate limit is set to either the model-level limit or the user-level limit, whichever is more restrictive. For example, if the model-level limit is 2 requests per minute and the user-level limit is 4 requests per minute, the overall limit will be set to 2 requests per minute. -## Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/controllers/<model_id> -PUT /_plugins/_ml/controllers/<model_id> +POST /_plugins/_ml/controllers/{model_id} +PUT /_plugins/_ml/controllers/{model_id} ``` -{% include copy-curl.html %} ## Path parameters @@ -35,7 +34,7 @@ Parameter | Data type | Description :--- | :--- | :--- `model_id` | String | The model ID of the model for which you want to set rate limits. Required. -## Request fields +## Request body fields The following table lists the available request fields. @@ -51,7 +50,7 @@ Field | Data type | Description `unit` | String | The unit of time for the rate limiter. Valid values are `DAYS`, `HOURS`, `MICROSECONDS`, `MILLISECONDS`, `MINUTES`, `NANOSECONDS`, and `SECONDS`. -#### Example request: Create a controller +## Example request: Create a controller ```json POST _plugins/_ml/controllers/mtw-ZI0B_1JGmyB068C0 @@ -70,7 +69,7 @@ POST _plugins/_ml/controllers/mtw-ZI0B_1JGmyB068C0 ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -79,7 +78,7 @@ POST _plugins/_ml/controllers/mtw-ZI0B_1JGmyB068C0 } ``` -#### Example request: Update the rate limit for one user +## Example request: Update the rate limit for one user To update the limit for `user1`, send a PUT request and specify the updated information: @@ -114,7 +113,7 @@ This will update only the `user1` object, leaving all other user limits intact: } ``` -#### Example response +## Example response ```json { @@ -133,7 +132,7 @@ This will update only the `user1` object, leaving all other user limits intact: } ``` -#### Example request: Delete the rate limit for one user +## Example request: Delete the rate limit for one user To delete the limit for `user2`, send a POST request containing all other users' limits: @@ -164,22 +163,12 @@ This will overwrite the controller with the new information: } ``` -#### Example response +## Example response ```json { - "_index": ".plugins-ml-controller", - "_id": "mtw-ZI0B_1JGmyB068C0", - "_version": 2, - "result": "updated", - "forced_refresh": true, - "_shards": { - "total": 2, - "successful": 2, - "failed": 0 - }, - "_seq_no": 1, - "_primary_term": 1 + "model_id": "mtw-ZI0B_1JGmyB068C0", + "status": "UPDATED" } ``` diff --git a/_ml-commons-plugin/api/controller-apis/delete-controller.md b/_ml-commons-plugin/api/controller-apis/delete-controller.md index 44120198..64e8e063 100644 --- a/_ml-commons-plugin/api/controller-apis/delete-controller.md +++ b/_ml-commons-plugin/api/controller-apis/delete-controller.md @@ -2,20 +2,20 @@ layout: default title: Delete controller parent: Controller APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 50 --- -# Delete a controller +# Delete Controller API **Introduced 2.12** {: .label .label-purple } Use this API to delete a controller for a model based on the `model_id`. -## Path and HTTP methods +## Endpoints ```json -DELETE /_plugins/_ml/controllers/<model_id> +DELETE /_plugins/_ml/controllers/{model_id} ``` ## Path parameters @@ -26,14 +26,14 @@ The following table lists the available path parameters. | :--- | :--- | :--- | | `model_id` | String | The model ID of the model for which to delete the controller. | -#### Example request +## Example request ```json DELETE /_plugins/_ml/controllers/MzcIJX8BA7mbufL6DOwl ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -41,6 +41,7 @@ DELETE /_plugins/_ml/controllers/MzcIJX8BA7mbufL6DOwl "_id" : "MzcIJX8BA7mbufL6DOwl", "_version" : 2, "result" : "deleted", + "forced_refresh" : true, "_shards" : { "total" : 2, "successful" : 2, @@ -51,6 +52,34 @@ DELETE /_plugins/_ml/controllers/MzcIJX8BA7mbufL6DOwl } ``` +## Error responses + +If you attempt to delete a controller that doesn't exist, OpenSearch returns a 404 Not Found error. The following error is returned when the controller index doesn't exist: + +```json +{ + "error": { + "root_cause": [ + { + "type": "index_not_found_exception", + "reason": "no such index [.plugins-ml-controller]", + "index": ".plugins-ml-controller", + "resource.id": ".plugins-ml-controller", + "resource.type": "index_expression", + "index_uuid": "_na_" + } + ], + "type": "index_not_found_exception", + "reason": "no such index [.plugins-ml-controller]", + "index": ".plugins-ml-controller", + "resource.id": ".plugins-ml-controller", + "resource.type": "index_expression", + "index_uuid": "_na_" + }, + "status": 404 +} +``` + ## Required permissions If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/controllers/delete`. \ No newline at end of file diff --git a/_ml-commons-plugin/api/controller-apis/get-controller.md b/_ml-commons-plugin/api/controller-apis/get-controller.md index b30fe156..84acb73b 100644 --- a/_ml-commons-plugin/api/controller-apis/get-controller.md +++ b/_ml-commons-plugin/api/controller-apis/get-controller.md @@ -2,20 +2,20 @@ layout: default title: Get controller parent: Controller APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 20 --- -# Get a controller +# Get Controller API **Introduced 2.12** {: .label .label-purple } Use this API to retrieve information about a controller for a model by model ID. -### Path and HTTP methods +## Endpoints ```json -GET /_plugins/_ml/controllers/<model_id> +GET /_plugins/_ml/controllers/{model_id} ``` ## Path parameters @@ -26,14 +26,14 @@ The following table lists the available path parameters. | :--- | :--- | :--- | | `model_id` | String | The model ID of the model for which to retrieve the controller. | -#### Example request +## Example request ```json GET /_plugins/_ml/controllers/T_S-cY0BKCJ3ot9qr0aP ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -59,19 +59,19 @@ If there is no controller defined for the model, OpenSearch returns an error: "root_cause": [ { "type": "status_exception", - "reason": "Failed to find model controller with the provided model ID: T_S-cY0BKCJ3ot9qr0aP" + "reason": "Failed to find model controller with the provided model ID" } ], "type": "status_exception", - "reason": "Failed to find model controller with the provided model ID: T_S-cY0BKCJ3ot9qr0aP" + "reason": "Failed to find model controller with the provided model ID" }, "status": 404 } ``` -## Response fields +## Response body fields -For response field descriptions, see [Create Controller API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/controller-apis/create-controller#request-fields). +For response field descriptions, see [Create Controller API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/controller-apis/create-controller#request-body-fields). ## Required permissions diff --git a/_ml-commons-plugin/api/controller-apis/index.md b/_ml-commons-plugin/api/controller-apis/index.md index 2f9afc14..d59d2a82 100644 --- a/_ml-commons-plugin/api/controller-apis/index.md +++ b/_ml-commons-plugin/api/controller-apis/index.md @@ -1,11 +1,12 @@ --- layout: default title: Controller APIs -parent: ML Commons APIs +parent: ML APIs has_children: true has_toc: false -nav_order: 29 -redirect_from: /ml-commons-plugin/api/controller-apis/ +nav_order: 40 +redirect_from: + - /ml-commons-plugin/api/controller-apis/ --- # Controller APIs @@ -14,7 +15,7 @@ redirect_from: /ml-commons-plugin/api/controller-apis/ You can configure a rate limit for a specific user or users of a model by calling the Controller APIs. -ML Commons supports the following controller-level APIs: +OpenSearch supports the following controller APIs: - [Create or update controller]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/controller-apis/create-controller/) - [Get controller]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/controller-apis/get-controller/) diff --git a/_ml-commons-plugin/api/execute-algorithm.md b/_ml-commons-plugin/api/execute-algorithm.md index 7b06cfef..8ce18530 100644 --- a/_ml-commons-plugin/api/execute-algorithm.md +++ b/_ml-commons-plugin/api/execute-algorithm.md @@ -1,21 +1,34 @@ --- layout: default title: Execute algorithm -parent: ML Commons APIs -nav_order: 30 +parent: Model APIs +grand_parent: ML APIs +nav_order: 80 --- -# Execute algorithm +# Execute Algorithm API Some algorithms, such as [Localization]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms#localization), don't require trained models. You can run no-model-based algorithms using the `execute` API. -## Path and HTTP methods +## Endpoints ```json -POST _plugins/_ml/_execute/<algorithm_name> +POST /_plugins/_ml/_execute/{algorithm_name} ``` -#### Example request: Execute localization +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `algorithm_name` | String | The name of the algorithm to run, for example, `anomaly_localization` or `metrics_correlation`. Required. | + +## Request body fields + +The request body fields depend on the algorithm. For the fields of each algorithm, see [Localization]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms#localization) and [Metrics correlation]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms#metrics-correlation). + +## Example request: Execute localization The following example uses the Localization algorithm to find subset-level information for aggregate data (for example, aggregated over time) that demonstrates the activity of interest, such as spikes, drops, changes, or anomalies. @@ -44,7 +57,7 @@ POST /_plugins/_ml/_execute/anomaly_localization ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { diff --git a/_ml-commons-plugin/api/execute-tool.md b/_ml-commons-plugin/api/execute-tool.md new file mode 100644 index 00000000..7b3033ac --- /dev/null +++ b/_ml-commons-plugin/api/execute-tool.md @@ -0,0 +1,126 @@ +--- +layout: default +title: Execute tool +parent: ML APIs +nav_order: 100 +--- + +# Execute Tool API +**Introduced 3.3** +{: .label .label-purple } + +The Execute Tool API allows you to run individual tools directly without creating an agent first. This API is particularly beneficial for applications requiring quick, single-tool operations where the overhead of agent creation and management is unnecessary. + +## Use cases + +The Execute Tool API is ideal for: + +- **Direct tool execution**: Run specific tools like search, data analysis, or retrieval operations without agent setup. +- **Testing and debugging**: Quickly test tool functionality during development. +- **Lightweight integrations**: Integrate specific OpenSearch capabilities into applications without full agent workflows. +- **Standalone operations**: Perform single tasks that don't require conversation memory or complex orchestration. + +## Supported tools + +This API supports all available OpenSearch tools. Each tool can be executed independently with its specific parameters. + +For more information regarding the list of available tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). + +## Endpoint + +```json +POST /_plugins/_ml/tools/_execute/{tool_name} +``` + +The `<tool_name>` parameter refers to the predefined tool type name, such as `PPLTool`, `SearchIndexTool`, or `VectorDBTool`,---not a custom tool name that you define. +{: .note} + +The Execute Tool API is enabled by default. To disable it, set `plugins.ml_commons.execute_tools_enabled` to `false`. + +## Request body fields + +The following table lists all request body fields. + +| Field | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `parameters` | Object | Yes | Contains tool-specific parameters that vary depending on the tool being executed. Each tool requires different parameters based on its functionality. | + +### Parameter structure + +The `parameters` object combines the parameters used during tool registration and tool execution. The specific fields depend on the tool being executed. + +To determine the required parameters for a specific tool, refer to the individual tool documentation in the [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/) section. + +| Component | Description | +|:-------------------------|:-----------------------------------------------| +| Tool registration parameters | Parameters specified during tool registration. | +| Tool execution parameters | Parameters specified during tool execution. | + +## Example requests + +The following are examples of both simple and complex tool execution. + +### Example 1: Simple tool execution + +```json +POST /_plugins/_ml/tools/_execute/ListIndexTool +{ + "parameters": { + "question": "How many indices do I have?" + } +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,yellow,open,movies,kKcJKu2aT0C9uwJIPP4hxw,2,1,2,0,7.8kb,7.8kb +2,green,open,.plugins-ml-config,h8ovp_KFTq6_zvcBEn2kvg,1,0,1,0,4kb,4kb +3,green,open,.plugins-ml-agent,1oGlUBCIRAGXLbLv27Qg8w,1,0,1,0,8kb,8kb +""" + } + ] + } + ] +} +``` + +### Example 2: Complex tool execution + +```json +POST /_plugins/_ml/tools/_execute/PPLTool +{ + "parameters": { + "question": "what's the population of Seattle in 2021?", + "index": "test-population", + "model_id": "1TuQQ5gBMJhRgCqgSV79" + } +} + +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"ppl\":\"source=test-population | where QUERY_STRING(['population_description'], 'Seattle') AND QUERY_STRING(['population_description'], '2021')\",\"executionResult\":\"{\\n \\\"schema\\\": [\\n {\\n \\\"name\\\": \\\"population_description\\\",\\n \\\"type\\\": \\\"string\\\"\\n }\\n ],\\n \\\"datarows\\\": [],\\n \\\"total\\\": 0,\\n \\\"size\\\": 0\\n}\"}" + } + ] + } + ] +} +``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/index.md b/_ml-commons-plugin/api/index.md index a41679f6..eeffbedd 100644 --- a/_ml-commons-plugin/api/index.md +++ b/_ml-commons-plugin/api/index.md @@ -1,23 +1,47 @@ --- layout: default -title: ML Commons APIs -has_children: false -nav_order: 130 +title: ML APIs +nav_order: 110 has_children: true has_toc: false redirect_from: - /ml-commons-plugin/api/ + - /ml-commons-plugin/api/train-predict/ --- -# ML Commons APIs +# ML APIs -ML Commons supports the following APIs: +OpenSearch supports machine learning (ML) APIs for models, agents, conversational search, and monitoring. + +## Models + +The following APIs manage models and connectors: - [Model APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/) - [Model group APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/index/) - [Connector APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/index/) -- [Tasks APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/index/) -- [Train and Predict APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/index/) -- [Execute Algorithm API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-algorithm/) +- [Controller APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/controller-apis/index/) + +## Agents and tools + +The following APIs manage agents and the memory, context, templates, and tools that agents use: + +- [Agent APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/index/) +- [Agentic memory APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/) +- [Agentic search template APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-search-template-apis/index/) +- [Context management APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/index/) +- [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/) +- [MCP server APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/) +- [MCP client APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-client-apis/) + +## Conversational search + +The [Memory APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/index/) store the conversation history for [conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/). + +## Tasks and monitoring + +The following APIs track ML tasks and report on model and cluster state: + +- [ML Tasks APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/index/) - [Profile API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/profile/) - [Stats API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/stats/) diff --git a/_ml-commons-plugin/api/mcp-client-apis/index.md b/_ml-commons-plugin/api/mcp-client-apis/index.md new file mode 100644 index 00000000..8d3c835e --- /dev/null +++ b/_ml-commons-plugin/api/mcp-client-apis/index.md @@ -0,0 +1,22 @@ +--- +layout: default +title: MCP client APIs +parent: ML APIs +has_children: true +has_toc: false +nav_order: 120 +redirect_from: + - /ml-commons-plugin/api/mcp-client-apis/ +--- + +# MCP client APIs +**Introduced 3.8** +{: .label .label-purple } + +When OpenSearch connects to an external [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server through an MCP connector, it acts as an MCP client. These APIs let you discover and inspect tools exposed by external MCP servers before configuring agents. + +This differs from [MCP server APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/), where OpenSearch exposes its own tools to external MCP clients. For conceptual information about using external MCP servers with agents, see [Connecting to an external MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/). + +OpenSearch supports the following MCP client APIs: + +- [List connector MCP tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools/) diff --git a/_ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools.md b/_ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools.md new file mode 100644 index 00000000..82749605 --- /dev/null +++ b/_ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools.md @@ -0,0 +1,109 @@ +--- +layout: default +title: List connector MCP tools +parent: MCP client APIs +grand_parent: ML APIs +nav_order: 10 +--- + +# List Connector MCP Tools API +**Introduced 3.8** +{: .label .label-purple } + +Use this API to list all tools available on an external MCP server through a registered MCP connector. The response includes each tool's name, type, description, and input schema. + +Flow and conversational flow agents require tools to be defined in advance during agent registration. Use this API to discover available tools and their parameters before adding MCP tools to an agent configuration. For more information, see [Register Agent API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/). + +This API differs from the [List MCP Tools API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools/), which lists tools registered on OpenSearch's own MCP server. +{: .note} + +## Prerequisites + +Before using this API, complete the following steps: + +1. Enable MCP connectors by setting `plugins.ml_commons.mcp_connector_enabled` to `true`. +2. Configure trusted MCP server endpoints in `plugins.ml_commons.trusted_connector_endpoints_regex`. +3. Create an MCP connector with protocol `mcp_sse` or `mcp_streamable_http`. + +For setup instructions, see [Connecting to an external MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/). + +## Endpoints + +```json +GET /_plugins/_ml/connectors/{connector_id}/tools +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `connector_id` | String | Required | The ID of the MCP connector. Obtain this ID from the [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/) response. The connector must use the `mcp_sse` or `mcp_streamable_http` protocol. | + +## Example request + +The following example lists tools for an MCP connector with ID `1MlVyZwBBtWLSsWgaB6w`: + +```json +GET /_plugins/_ml/connectors/1MlVyZwBBtWLSsWgaB6w/tools +``` +{% include copy-curl.html %} + +## Example response + +OpenSearch connects to the external MCP server through the specified connector and returns the available tools: + +```json +{ + "tools": [ + { + "name": "search_documents", + "type": "McpStreamableHttpTool", + "description": "Search a document repository for relevant content.", + "input_schema": "{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"The search query.\"},\"limit\":{\"type\":\"integer\",\"description\":\"The maximum number of results to return.\",\"minimum\":1,\"maximum\":100}},\"required\":[\"query\"]}" + }, + { + "name": "get_weather", + "type": "McpStreamableHttpTool", + "description": "Retrieve current weather conditions for a specified location.", + "input_schema": "{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city or geographic location.\"},\"units\":{\"type\":\"string\",\"description\":\"The temperature unit system.\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}" + } + ] +} +``` + +If the MCP server exposes no tools, OpenSearch returns an empty `tools` array: + +```json +{ + "tools": [] +} +``` + +## Response body fields + +The following table lists the top-level response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `tools` | Array | A list of tools available on the external MCP server. Returns an empty array if the MCP server exposes no tools. | + +Each object in the `tools` array contains the following fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `name` | String | Required | The tool name as defined by the external MCP server. Use this value as the `name` field when configuring MCP tools in an agent. | +| `type` | String | Required | The OpenSearch tool type used to execute the MCP tool. Valid values are `McpStreamableHttpTool` for connectors with protocol `mcp_streamable_http` and `McpSseTool` for connectors with protocol `mcp_sse`. Use this value as the `type` field when configuring MCP tools in an agent. | +| `description` | String | Optional | A human-readable description of the tool's purpose, as provided by the external MCP server. Omitted from the response when the MCP server does not provide a description. | +| `input_schema` | String | Optional | A JSON Schema string describing the tool's input parameters. The schema follows the [JSON Schema](https://json-schema.org/) format and defines properties, types, descriptions, and required fields. Omitted from the response when the MCP server does not provide an input schema. | + +## Error responses + +The following table describes common error responses. + +| HTTP status | Condition | Example error message | +| :--- | :--- | :--- | +| `400` | The connector exists but is not an MCP connector (for example, an HTTP or Amazon Bedrock connector). | `Connector with ID {connector_id} is not of type McpConnector or McpStreamableHttpConnector` | +| `404` | The connector ID does not exist. | `Failed to find connector` | +| `500` | MCP connectors are disabled, the external MCP server is unreachable, or another internal error occurs. | `The MCP connector is not enabled. To enable, please update the setting plugins.ml_commons.mcp_connector_enabled` | diff --git a/_ml-commons-plugin/api/mcp-server-apis/index.md b/_ml-commons-plugin/api/mcp-server-apis/index.md new file mode 100644 index 00000000..f940a9f6 --- /dev/null +++ b/_ml-commons-plugin/api/mcp-server-apis/index.md @@ -0,0 +1,38 @@ +--- +layout: default +title: MCP server APIs +parent: ML APIs +has_children: true +has_toc: false +nav_order: 110 +redirect_from: + - /ml-commons-plugin/api/mcp-server-apis/ + - /ml-commons-plugin/api/mcp-server-apis/sse-message/ + - /ml-commons-plugin/api/mcp-server-apis/sse-session/ +--- + +# MCP server APIs +**Introduced 3.0** +{: .label .label-purple } + +Use these APIs to manage the in-cluster [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server, which lets external MCP clients discover and call [tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/) registered in your cluster. + +The in-cluster MCP server uses the Streamable HTTP transport protocol to communicate with the clients. For details about the transport, see the [official MCP documentation](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports). +{: .note } + +For instructions on setting up the MCP server and connecting a client, see [Using the in-cluster MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/in-cluster-mcp-server/). + +The in-cluster MCP server supports the following APIs: + +- [Register MCP tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/register-mcp-tools/) +- [Update MCP tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/update-mcp-tools/) +- [List MCP tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools/) +- [Remove MCP tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools/) +- [MCP Streamable HTTP Server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/mcp-server/) + +## Removed APIs + +The following experimental APIs were removed in OpenSearch 3.3 in favor of the Streamable HTTP transport: + +- MCP SSE Message API +- MCP SSE Session API \ No newline at end of file diff --git a/_ml-commons-plugin/api/mcp-server-apis/list-mcp-tools.md b/_ml-commons-plugin/api/mcp-server-apis/list-mcp-tools.md new file mode 100644 index 00000000..b56d45b8 --- /dev/null +++ b/_ml-commons-plugin/api/mcp-server-apis/list-mcp-tools.md @@ -0,0 +1,71 @@ +--- +layout: default +title: List MCP tools +parent: MCP server APIs +grand_parent: ML APIs +nav_order: 30 +--- + +# List MCP Tools API +**Introduced 3.1** +{: .label .label-purple } + +Use this API to list all Model Context Protocol (MCP)-based tools by name. + +## Endpoints + +```json +GET /_plugins/_ml/mcp/tools/_list +``` + +## Example request + +```json +GET /_plugins/_ml/mcp/tools/_list +``` +{% include copy-curl.html %} + +## Example response + +OpenSearch responds with the MCP tool list: + +```json +{ + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleSearchTool", + "description": "This tool can be used to perform search via google engine and parse the content of the searched results", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "next_page": { + "description": "The search result's next page link. If this is provided, the WebSearchTool will fetch the next page results using this link and crawl the links on the page.", + "type": "string" + }, + "engine": { + "description": "The search engine that will be used by the tool.", + "type": "string" + }, + "query": { + "description": "The search query parameter that will be used by the engine to perform the search.", + "type": "string" + } + }, + "required": [ + "engine", + "query" + ] + }, + "strict": false + }, + "create_time": 1749864622040 + } + ] +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/mcp_tools/list`. diff --git a/_ml-commons-plugin/api/mcp-server-apis/mcp-server.md b/_ml-commons-plugin/api/mcp-server-apis/mcp-server.md new file mode 100644 index 00000000..e7bf058b --- /dev/null +++ b/_ml-commons-plugin/api/mcp-server-apis/mcp-server.md @@ -0,0 +1,81 @@ +--- +layout: default +title: MCP Streamable HTTP Server +parent: MCP server APIs +grand_parent: ML APIs +nav_order: 50 +--- + +# MCP Streamable HTTP Server API +**Introduced 3.3** +{: .label .label-purple } + +The in-cluster Model Context Protocol (MCP) server is exposed through the `/_plugins/_ml/mcp` endpoint and implements the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports). MCP clients use this endpoint to discover and call the tools registered in your cluster. + +The server is stateless: all communication happens over individual HTTP `POST` requests, and the server does not open Server-Sent Events (SSE) streams. If a client sends a `GET` request, the server returns a `405 Method Not Allowed` response. + +To use this endpoint, enable the `plugins.ml_commons.mcp_server_enabled` setting. For setup instructions and example requests, see [Using the in-cluster MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/in-cluster-mcp-server/). + +## Endpoints + +```json +POST /_plugins/_ml/mcp +``` + +## Request body fields + +The request body is a [JSON-RPC 2.0](https://www.jsonrpc.org/specification) message. The following table lists the request body fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `jsonrpc` | String | Required | The JSON-RPC version. Must be `2.0`. | +| `id` | Integer or string | Optional | The request ID, which the server returns in the response. Omit the ID for notifications. | +| `method` | String | Required | The MCP method. Clients use `initialize` and `notifications/initialized` to establish a connection, `tools/list` to discover tools, and `tools/call` to call a tool. The server also responds to `ping` and returns empty lists for `prompts/list` and `resources/list` because it provides only tools. | +| `params` | Object | Optional | The method parameters. For example, a `tools/call` request provides the tool `name` and `arguments`. | + +## Example request + +The following request calls the `ListIndexTool` tool: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "ListIndexTool", + "arguments": { + "indices": ["opensearch_dashboards_sample_data_ecommerce"] + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The server returns the tool output in the `content` array: + +```json +{ + "jsonrpc": "2.0", + "id": 3, + "result": { + "content": [ + { + "type": "text", + "text": "row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards)\n1,green,open,opensearch_dashboards_sample_data_ecommerce,ryn25tMCTDex530BrUVmfw,1,0,4675,0,4mb,4mb\n" + } + ], + "isError": false, + "_meta": {} + } +} +``` + +For the full sequence of requests that an MCP client sends, see [Sending MCP requests manually]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/in-cluster-mcp-server/#sending-mcp-requests-manually). + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/mcp/server`. Tools run using the permissions of the calling user, so calling a tool that accesses index data also requires the corresponding index permissions. For more information, see [Permissions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/in-cluster-mcp-server/#permissions). diff --git a/_ml-commons-plugin/api/mcp-server-apis/register-mcp-tools.md b/_ml-commons-plugin/api/mcp-server-apis/register-mcp-tools.md new file mode 100644 index 00000000..caf87bc4 --- /dev/null +++ b/_ml-commons-plugin/api/mcp-server-apis/register-mcp-tools.md @@ -0,0 +1,403 @@ +--- +layout: default +title: Register MCP tools +parent: MCP server APIs +grand_parent: ML APIs +nav_order: 10 +--- + +# Register MCP Tools API +**Introduced 3.0** +{: .label .label-purple } + +Use this API to register one or more Model Context Protocol (MCP)-based tools. For more information about supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). + +## Endpoints + +```json +POST /_plugins/_ml/mcp/tools/_register +``` + +## Request body fields + +The following table lists the available request fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`tools` | Array | Required | A list of tools. + + +The `tools` array contains a list of tools. Each tool contains the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`name`| String | Optional | The tool name. The tool name defaults to the `type` parameter value. If you need to include multiple tools of the same type in the MCP server, specify different names for the tools. | +`type` | String | Required | The tool type. For a list of supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +`description` | String | Optional | The description of the tool. +`parameters` | Object | Optional | The parameters for the tool. The parameters are dependent on the tool type. For information about specific tool types, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +`attributes` | Object | Optional | The configuration properties (attributes) for the tool. The most important attribute in this field is the tool's `input_schema`, which defines the expected parameter format for the tool. This schema is sent to the large language model (LLM) so it can properly format parameters when executing the tool. + +## Example requests + +The [built-in tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/) are categorized as either zero-configuration tools (no parameters required) or parameterized tools (require parameters). Zero-configuration tools use a standard initialization process and thus have the same request body because no parameters are required. In contrast, for parameterized tools, you must provide the correct initialization parameters to ensure the tool functions as expected. + +### Example request: Zero-configuration tools + +<details markdown="block"> + <summary> + Example request + </summary> + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "name": "ListIndexTool", + "type": "ListIndexTool", + "description": "This tool gets index information from the OpenSearch cluster. It takes 2 optional arguments named `indices` which is a comma-delimited list of one or more indices to get information from (default is an empty list meaning all indices), and `local` which means whether to return information from the local node only instead of the cluster manager node (default is false). The tool returns the indices information, including `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, `pri.store. size `, `pri.store.size`, `pri.store`.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "indices": { + "type": "array", + "items": { + "type": "string" + }, + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"], use empty array [] to list all indices in the cluster" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchIndexTool", + "type": "SearchIndexTool", + "description": "Use this tool to search an index by providing two parameters: 'index' for the index name, and 'query' for the OpenSearch DSL formatted query. Only use this tool when both index name and DSL query is available.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "string" + }, + "query": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "IndexMappingTool", + "type": "IndexMappingTool", + "description": "This tool gets index mapping information from a certain index. It takes 1 required argument named 'index' which is a comma-delimited list of one or more indices to get mapping information from, which expands wildcards. It takes 1 optional argument named 'local' which means whether to return information from the local node only instead of the cluster manager node (Default is false). The tool returns a list of index mappings and settings for each index. The mappings are in JSON format under the key 'properties' which includes the field name as a key and a JSON object with field type under the key 'type'. The settings are in flattened map with 'index' as the top element and key-value pairs for each setting.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "array", + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"]", + "items": { + "type": "string" + } + } + }, + "required": [ + "index" + ], + "additionalProperties": false + } + } + }, + { + "name": "SearchAlertsTool", + "type": "SearchAlertsTool", + "description": "Use this tool to search an index by providing two parameters: 'index' for the index name, and 'query' for the OpenSearch DSL formatted query. Only use this tool when both index name and DSL query is available.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "string", + "description": "OpenSearch index name. for example: index1" + }, + "query": { + "type": "object", + "description": "OpenSearch search index query. You need to get index mapping to write correct search query. It must be a valid OpenSearch query. Valid value:\n{\"query\":{\"match\":{\"population_description\":\"seattle 2023 population\"}},\"size\":2,\"_source\":\"population_description\"}\nInvalid value: \n{\"match\":{\"population_description\":\"seattle 2023 population\"}}\nThe value is invalid because the match not wrapped by \"query\".", + "additionalProperties": false + } + }, + "required": ["index", "query"], + "additionalProperties": false + } + } + }, + { + "name": "SearchAnomalyDetectorsTool", + "type": "SearchAnomalyDetectorsTool", + "description": "This is a tool that searches anomaly detectors. It takes 12 optional arguments named detectorName which is the explicit name of the detector (default is null), and detectorNamePattern which is a wildcard query to match detector name (default is null), and indices which defines the index or index pattern the detector is detecting over (default is null), and highCardinality which defines whether the anomaly detector is high cardinality (synonymous with multi-entity) of non-high-cardinality (synonymous with single-entity) (default is null, indicating both), and lastUpdateTime which defines the latest update time of the anomaly detector in epoch milliseconds (default is null), and sortOrder which defines the order of the results (options are asc or desc, and default is asc), and sortString which defines how to sort the results (default is name.keyword), and size which defines the size of the request to be returned (default is 20), and startIndex which defines the paginated index to start from (default is 0), and running which defines whether the anomaly detector is running (default is null, indicating both), and failed which defines whether the anomaly detector has failed (default is null, indicating both). The tool returns 2 values: a list of anomaly detectors (each containing the detector id, detector name, detector type indicating multi-entity or single-entity (where multi-entity also means high-cardinality), detector description, name of the configured index, last update time in epoch milliseconds), and the total number of anomaly detectors.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "detectorName": { + "type": "string", + "description": "Anomaly detector name" + }, + "detectorNamePattern": { + "type": "string", + "description": "Anomaly detector name pattern" + }, + "indices": { + "type": "string", + "description": "The index name that anomaly detector uses" + }, + "highCardinality": { + "type": "string", + "description": "The value is true of false, the detector type will be set to MULTI_ENTITY if it's value is true, otherwise SINGLE_ENTITY if it's false" + }, + "lastUpdateTime": { + "type": "string", + "description": "The last update time of the anomaly detector" + }, + "sortString": { + "type": "string", + "description": "The sort key of the search result, default value is `name.keyword` which means the sorting is based on the detector name" + }, + "sortOrder": { + "type": "string", + "description": "The search result order is based on this value, default is asc which means the sorting is in ascending manner." + }, + "size": { + "type": "string", + "description": "This value controls how many search results will be fetched, default value is 20 which means at most 20 anomaly detecotrs can return" + }, + "startIndex": { + "type": "string", + "description": "The start index of the search, default value is 0 which means starts from the beginning" + }, + "running": { + "type": "string", + "description": "The running status of the anomaly detector, valid values are true and false, default is null" + }, + "failed": { + "type": "string", + "description": "The failed status of the anomaly detector, valid values are true and false, default is null" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchAnomalyResultsTool", + "type": "SearchAnomalyResultsTool", + "description": "This is a tool that searches anomaly results. It takes 9 arguments named detectorId which defines the detector ID to filter for (default is null), and realtime which defines whether the anomaly results are from a realtime detector (set to false to only get results from historical analyses) (default is null), and anomalyGradeThreshold which defines the threshold for anomaly grade (a number between 0 and 1 that indicates how anomalous a data point is) (default is greater than 0), and dataStartTime which defines the start time of the anomaly data in epoch milliseconds (default is null), and dataEndTime which defines the end time of the anomaly data in epoch milliseconds (default is null), and sortOrder which defines the order of the results (options are asc or desc, and default is desc), and sortString which defines how to sort the results (default is data_start_time), and size which defines the number of anomalies to be returned (default is 20), and startIndex which defines the paginated index to start from (default is 0). The tool returns 2 values: a list of anomaly results (where each result contains the detector ID, the anomaly grade, and the confidence), and the total number of anomaly results.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "detectorId": { + "type": "string", + "description": "Anomaly detector id" + }, + "realTime": { + "type": "string", + "description": "If the anomaly detector a real time one, valid values are true and false, default is null" + }, + "anomalyGradeThreshold": { + "type": "string", + "description": "A float number to indicate the anomaly grade" + }, + "dataStartTime": { + "type": "string", + "description": "Start time of the data in the anomaly detector" + }, + "dataEndTime": { + "type": "string", + "description": "End time of the data in the anomaly detector" + }, + "sortString": { + "type": "string", + "description": "The sort key of the search result, default value is `name.keyword` which means the sorting is based on the detector name" + }, + "sortOrder": { + "type": "string", + "description": "The search result order is based on this value, default is asc which means the sorting is in ascending manner." + }, + "size": { + "type": "string", + "description": "This value controls how many search results will be fetched, default value is 20 which means at most 20 anomaly detecotrs can return" + }, + "startIndex": { + "type": "string", + "description": "The start index of the search, default value is 0 which means starts from the beginning" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchMonitorsTool", + "type": "SearchMonitorsTool", + "description": "This is a tool that searches alerting monitors. It takes 10 optional arguments named monitorId which defines the monitor ID to filter for (default is null), and monitorName which defines explicit name of the monitor (default is null), and monitorNamePattern which is a wildcard query to match monitor name (default is null), and enabled which defines whether the monitor is enabled (default is null, indicating both enabled and disabled), and hasTriggers which defines whether the monitor has triggers enabled (default is null, indicating both), and indices which defines the index being monitored (default is null), and sortOrder which defines the order of the results (options are asc or desc, and default is asc), and sortString which defines how to sort the results (default is name.keyword), and size which defines the size of the request to be returned (default is 20), and startIndex which defines the paginated index to start from (default is 0). The tool returns 2 values: a list of alerting monitors (each containining monitor ID, monitor name, monitor type (indicating query-level, document-level, or bucket-level monitor types), enabled, enabled time in epoch milliseconds, last update time in epoch milliseconds), and the total number of alerting monitors.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "monitorId": { + "type": "string", + "description": "Alerting monitor id" + }, + "monitorName": { + "type": "string", + "description": "Alerting monitor name" + }, + "monitorNamePattern": { + "type": "string", + "description": "Alerting monitor name pattern" + }, + "enabled": { + "type": "string", + "description": "If the alerting monitor enabled or not, valid values are true and false, default is null" + }, + "hasTriggers": { + "type": "string", + "description": "If the alerting monitor has triggers, valid values are true and false, default is null" + }, + "indices": { + "type": "string", + "description": "The index names that alerting monitor uses" + }, + "sortString": { + "type": "string", + "description": "The sort key of the search result, default value is `name.keyword` which means the sorting is based on the detector name" + }, + "sortOrder": { + "type": "string", + "description": "The search result order is based on this value, default is asc which means the sorting is in ascending manner." + }, + "size": { + "type": "string", + "description": "This value controls how many search results will be fetched, default value is 20 which means at most 20 alerting monitors can return" + }, + "startIndex": { + "type": "string", + "description": "The start index of the search, default value is 0 which means starts from the beginning" + } + }, + "additionalProperties": false + } + } + } + ] +} +``` +{% include copy-curl.html %} + +</details> + +### Example requests: Parameterized tools + +The following sections provide example requests for registering parameterized tools. For information about tool-specific parameters, see the corresponding [tool documentation]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). + +#### WebSearchTool + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleSearchTool", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "engine": { + "type": "string", + "description": "The search engine that will be used by the tool." + }, + "query": { + "type": "string", + "description": "The search query parameter that will be used by the engine to perform the search." + }, + "next_page": { + "type": "string", + "description": "The search result's next page link. If this is provided, the WebSearchTool will fetch the next page results using this link and crawl the links on the page." + } + }, + "required": [ + "engine", + "query" + ] + }, + "strict": false + } + } + ] +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +#### PPLTool +<!-- vale on --> + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "type": "PPLTool", + "name": "TransferQuestionToPPLAndExecuteTool", + "description": "Use this tool to convert natural language into PPL queries and execute them. Use this tool after you know the index name; otherwise, call IndexRoutingTool first. The input parameters are: {index: IndexName, question: UserQuestion}", + "parameters": { + "model_id": "${your_model_id}", + "model_type": "FINETUNE" + }, + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "The user's natural language question that needs to be converted to PPL." + }, + "index": { + "type": "string", + "description": "The index on which the generated PPL query will be executed." + } + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example response + +OpenSearch responds with the node ID and the status of the creation of all tools for each node: + +```json +{ + "_ZNV5BrNTVm6ilcM7Jn1pw": { + "created": true + }, + "NZ9aiUCrSp2b5KBqdJGJKw": { + "created": true + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/mcp_tools/register`. diff --git a/_ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools.md b/_ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools.md new file mode 100644 index 00000000..e5ac8a6f --- /dev/null +++ b/_ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools.md @@ -0,0 +1,48 @@ +--- +layout: default +title: Remove MCP tools +parent: MCP server APIs +grand_parent: ML APIs +nav_order: 40 +--- + +# Remove MCP Tools API +**Introduced 3.0** +{: .label .label-purple } + +Use this API to delete one or more Model Context Protocol (MCP)-based tools by name. + +## Endpoints + +```json +POST /_plugins/_ml/mcp/tools/_remove +``` + +## Example request + +```json +POST /_plugins/_ml/mcp/tools/_remove +[ + "GoogleSearchTool", "ListIndexTool" +] +``` +{% include copy-curl.html %} + +## Example response + +OpenSearch responds with the node ID and the status of tool deletion for each node: + +```json +{ + "_ZNV5BrNTVm6ilcM7Jn1pw": { + "removed": true + }, + "NZ9aiUCrSp2b5KBqdJGJKw": { + "removed": true + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/mcp_tools/remove`. diff --git a/_ml-commons-plugin/api/mcp-server-apis/update-mcp-tools.md b/_ml-commons-plugin/api/mcp-server-apis/update-mcp-tools.md new file mode 100644 index 00000000..b5f0c3d0 --- /dev/null +++ b/_ml-commons-plugin/api/mcp-server-apis/update-mcp-tools.md @@ -0,0 +1,139 @@ +--- +layout: default +title: Update MCP tools +parent: MCP server APIs +grand_parent: ML APIs +nav_order: 20 +--- + +# Update MCP Tools API +**Introduced 3.0** +{: .label .label-purple } + +Use this API to update one or more Model Context Protocol (MCP)-based tools. For more information about supported tools, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). + +## Endpoints + +```json +POST /_plugins/_ml/mcp/tools/_update +``` + +## Request body fields + +The following table lists the available request fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`tools` | Array | Required | A list of tools. + + +The `tools` array contains a list of tools. Each tool contains the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`name`| String | Required | The name of the tool to update. | +`type` | String | Optional | The tool type. This field is ignored because the type of a registered tool cannot be changed. +`description` | String | Optional | The description of the tool. +`parameters` | Object | Optional | The parameters for the tool. The parameters are dependent on the tool type. For information about specific tool types, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). +`attributes` | Object | Optional | The configuration properties (attributes) for the tool. The most important attribute in this field is the tool's `input_schema`, which defines the expected parameter format for the tool. This schema is sent to the large language model (LLM) so it can properly format parameters when executing the tool. + + +## Example requests + +The following sections provide example requests for updating tools. For information about tool-specific parameters, see the corresponding [tool documentation]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). + +### WebSearchTool + +```json +POST /_plugins/_ml/mcp/tools/_update +{ + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleSearchTool", + "description": "This tool can be used to perform search via google engine and parse the content of the searched results", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "engine": { + "type": "string", + "description": "The search engine that will be used by the tool." + }, + "query": { + "type": "string", + "description": "The search query parameter that will be used by the engine to perform the search." + }, + "next_page": { + "type": "string", + "description": "The search result's next page link. If this is provided, the WebSearchTool will fetch the next page results using this link and crawl the links on the page." + } + }, + "required": [ + "engine", + "query" + ] + }, + "strict": false + } + } + ] +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +### PPLTool +<!-- vale on --> + +```json +POST /_plugins/_ml/mcp/tools/_update +{ + "tools": [ + { + "type": "PPLTool", + "name": "TransferQuestionToPPLAndExecuteTool", + "description": "Use this tool to convert natural language into PPL queries and execute them. Use this tool after you know the index name; otherwise, call IndexRoutingTool first. The input parameters are: {index: IndexName, question: UserQuestion}", + "parameters": { + "model_id": "${your_model_id}", + "model_type": "FINETUNE" + }, + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "The user's natural language question that needs to be converted to PPL." + }, + "index": { + "type": "string", + "description": "The index on which the generated PPL query will be executed." + } + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +## Example response + +For each node, OpenSearch responds with the node ID and the status of the update operation for all tools: + +```json +{ + "_ZNV5BrNTVm6ilcM7Jn1pw": { + "updated": true + }, + "NZ9aiUCrSp2b5KBqdJGJKw": { + "updated": true + } +} +``` + +## Required permissions + +If you use the Security plugin, make sure you have the appropriate permissions: `cluster:admin/opensearch/ml/mcp_tools/update`. diff --git a/_ml-commons-plugin/api/memory-apis/create-memory.md b/_ml-commons-plugin/api/memory-apis/create-memory.md index c7dac178..8effe43f 100644 --- a/_ml-commons-plugin/api/memory-apis/create-memory.md +++ b/_ml-commons-plugin/api/memory-apis/create-memory.md @@ -2,11 +2,11 @@ layout: default title: Create or update memory parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 10 --- -# Create or update a memory +# Create Or Update Memory API **Introduced 2.12** {: .label .label-purple } @@ -19,11 +19,11 @@ The POST method creates a new memory. The PUT method updates an existing memory. When the Security plugin is enabled, all memories exist in a `private` security mode. Only the user who created a memory can interact with that memory and its messages. {: .important} -## Path and HTTP methods +## Endpoints ```json POST /_plugins/_ml/memory/ -PUT /_plugins/_ml/memory/<memory_id> +PUT /_plugins/_ml/memory/{memory_id} ``` ## Path parameters @@ -34,15 +34,19 @@ Parameter | Data type | Description :--- | :--- | :--- `memory_id` | String | The ID of the memory to be updated. Required for the PUT method. -## Request fields +## Request body fields The following table lists the available request fields. Field | Data type | Required/Optional | Description :--- | :--- | :--- | :--- `name` | String | Optional | The name of the memory. +`additional_info` | Object | Optional | Additional information about the memory, provided as string key-value pairs. When creating a memory, this field is ignored unless `name` is also specified. +`application_type` | String | Optional | The type of application that uses the memory. Applies only to the POST method and is ignored unless `name` is also specified. -#### Example request +The PUT method updates only the `name` and `additional_info` fields. Other fields in a PUT request are ignored. + +## Example request ```json POST /_plugins/_ml/memory/ @@ -52,10 +56,42 @@ POST /_plugins/_ml/memory/ ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { "memory_id": "gW8Aa40BfUsSoeNTvOKI" } +``` + +## Example request: Update a memory + +```json +PUT /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI +{ + "name": "Renamed conversation", + "additional_info": { + "topic": "population growth" + } +} +``` +{% include copy-curl.html %} + +## Example response: Update a memory + +```json +{ + "_index": ".plugins-ml-memory-meta", + "_id": "gW8Aa40BfUsSoeNTvOKI", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 3, + "_primary_term": 1 +} ``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/memory-apis/create-message.md b/_ml-commons-plugin/api/memory-apis/create-message.md index 345f411c..8f8bf9ae 100644 --- a/_ml-commons-plugin/api/memory-apis/create-message.md +++ b/_ml-commons-plugin/api/memory-apis/create-message.md @@ -2,11 +2,11 @@ layout: default title: Create or update message parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 40 --- -# Create or update a message +# Create Or Update Message API **Introduced 2.12** {: .label .label-purple } @@ -16,17 +16,17 @@ Once a message is created, you'll provide its `message_id` to other APIs. The POST method creates a new message. The PUT method updates an existing message. -You can only update the `additional_info` field of a message. +You can only update the `response` and `additional_info` fields of a message. Other fields in a PUT request are ignored. {: .note} When the Security plugin is enabled, all memories exist in a `private` security mode. Only the user who created a memory can interact with that memory and its messages. {: .important} -## Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/memory/<memory_id>/messages -PUT /_plugins/_ml/memory/message/<message_id> +POST /_plugins/_ml/memory/{memory_id}/messages +PUT /_plugins/_ml/memory/message/{message_id} ``` ## Path parameters @@ -38,19 +38,42 @@ Parameter | Data type | Description `memory_id` | String | The ID of the memory to which to add the message. Required for the POST method. `message_id` | String | The ID of the message to be updated. Required for the PUT method. -## Request fields +## Request body fields The following table lists the available request fields. Field | Data type | Required/Optional | Updatable | Description :--- | :--- | :--- | :--- | :--- -| `input` | String | Optional | No | The question (human input) in the message. | -| `prompt_template` | String | Optional | No | The prompt template that was used for the message. The template may contain instructions or examples that were sent to the large language model. | -| `response` | String | Optional | No | The answer (generative AI output) to the question. | -| `origin` | String | Optional | No | The name of the AI or other system that generated the response. | -| `additional_info` | Object | Optional | Yes | Any other information that was sent to the `origin`. | +`input` | String | Optional | No | The question (human input) in the message. | +`prompt_template` | String | Optional | No | The prompt template that was used for the message. The template may contain instructions or examples that were sent to the large language model. | +`response` | String | Optional | Yes | The answer (generative AI output) to the question. | +`origin` | String | Optional | No | The name of the AI or other system that generated the response. | +`additional_info` | Object | Optional | Yes | Any other information that was sent to the `origin`. When updating a message, the specified keys are added to or replace the existing keys. | +`parent_message_id` | String | Optional | No | The ID of the parent message. Specify this field to create a trace message for the parent message. | +`trace_number` | Integer | Optional | No | The order of the trace message among the traces of the parent message. Used with `parent_message_id`. | -#### Example request: Create a message +To create or update a message successfully, you must provide at least one of the `input`, `prompt_template`, `response`, `origin`, or `additional_info` fields. The provided field(s) cannot be null or empty. +{: .note} + +## Response body fields + +The following table lists the available response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory_id` | String | The memory ID. | +| `message_id` | String | The message ID. | +| `create_time` | String | The time at which the message was created. | +| `updated_time` | String | The time at which the message was last updated. | +| `input` | String | The question in the message (human input). | +| `prompt_template` | String | The prompt template that was used for the message. | +| `response` | String | The answer to the question (generative AI output). | +| `origin` | String | The name of the AI or other system that generated the response. | +| `additional_info` | Object | Any other information that was sent to the `origin`. | +| `parent_message_id` | String | The ID of the parent message (for trace messages). | +| `trace_number` | Integer | The trace number (for trace messages). | + +## Example request: Create a message ```json POST /_plugins/_ml/memory/SXA2cY0BfUsSoeNTz-8m/messages @@ -66,15 +89,15 @@ POST /_plugins/_ml/memory/SXA2cY0BfUsSoeNTz-8m/messages ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { - "memory_id": "WnA3cY0BfUsSoeNTI-_J" + "message_id": "WnA3cY0BfUsSoeNTI-_J" } ``` -#### Example request: Add a field to `additional_info` +## Example request: Add a field to `additional_info` ```json PUT /_plugins/_ml/memory/message/WnA3cY0BfUsSoeNTI-_J @@ -86,7 +109,7 @@ PUT /_plugins/_ml/memory/message/WnA3cY0BfUsSoeNTI-_J ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -112,6 +135,7 @@ The updated message contains an additional `feedback` field: "memory_id": "SXA2cY0BfUsSoeNTz-8m", "message_id": "WnA3cY0BfUsSoeNTI-_J", "create_time": "2024-02-03T23:04:15.554370024Z", + "updated_time": "2024-02-03T23:05:20.123456789Z", "input": "How do I make an interaction?", "prompt_template": "Hello OpenAI, can you answer this question?", "response": "Hello, this is OpenAI. Here is the answer to your question.", @@ -123,7 +147,7 @@ The updated message contains an additional `feedback` field: } ``` -#### Example request: Change a field in `additional_info` +## Example request: Change a field in `additional_info` ```json PUT /_plugins/_ml/memory/message/WnA3cY0BfUsSoeNTI-_J @@ -135,7 +159,7 @@ PUT /_plugins/_ml/memory/message/WnA3cY0BfUsSoeNTI-_J ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -161,6 +185,7 @@ The updated message contains the updated `feedback` field: "memory_id": "SXA2cY0BfUsSoeNTz-8m", "message_id": "WnA3cY0BfUsSoeNTI-_J", "create_time": "2024-02-03T23:04:15.554370024Z", + "updated_time": "2024-02-03T23:06:45.987654321Z", "input": "How do I make an interaction?", "prompt_template": "Hello OpenAI, can you answer this question?", "response": "Hello, this is OpenAI. Here is the answer to your question.", diff --git a/_ml-commons-plugin/api/memory-apis/delete-memory.md b/_ml-commons-plugin/api/memory-apis/delete-memory.md index 99e4cdb5..ef35fa78 100644 --- a/_ml-commons-plugin/api/memory-apis/delete-memory.md +++ b/_ml-commons-plugin/api/memory-apis/delete-memory.md @@ -2,11 +2,11 @@ layout: default title: Delete memory parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 30 --- -# Delete a memory +# Delete Memory API **Introduced 2.12** {: .label .label-purple } @@ -15,10 +15,10 @@ Use this API to delete a memory based on the `memory_id`. When the Security plugin is enabled, all memories exist in a `private` security mode. Only the user who created a memory can interact with that memory and its messages. {: .important} -## Path and HTTP methods +## Endpoints ```json -DELETE /_plugins/_ml/memory/<memory_id> +DELETE /_plugins/_ml/memory/{memory_id} ``` ## Path parameters @@ -29,17 +29,37 @@ Parameter | Data type | Description :--- | :--- | :--- `memory_id` | String | The ID of the memory to be deleted. -#### Example request +## Example request ```json DELETE /_plugins/_ml/memory/MzcIJX8BA7mbufL6DOwl ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { "success": true } +``` + +## Error responses + +If you attempt to delete a memory that doesn't exist, OpenSearch returns a 404 error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "resource_not_found_exception", + "reason": "Memory [MzcIJX8BA7mbufL6DOwl] not found" + } + ], + "type": "resource_not_found_exception", + "reason": "Memory [MzcIJX8BA7mbufL6DOwl] not found" + }, + "status": 404 +} ``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/memory-apis/get-memory.md b/_ml-commons-plugin/api/memory-apis/get-memory.md index 63ab548c..cb3ba61d 100644 --- a/_ml-commons-plugin/api/memory-apis/get-memory.md +++ b/_ml-commons-plugin/api/memory-apis/get-memory.md @@ -2,11 +2,11 @@ layout: default title: Get memory parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 20 --- -# Get a memory +# Get Memory API **Introduced 2.12** {: .label .label-purple } @@ -29,10 +29,10 @@ When the Security plugin is enabled, all memories exist in a `private` security You can retrieve memory information by using the `memory_id`. The response includes all messages within the memory. -### Path and HTTP methods +### Endpoints ```json -GET /_plugins/_ml/memory/<memory_id> +GET /_plugins/_ml/memory/{memory_id} ``` ### Path parameters @@ -42,14 +42,14 @@ Parameter | Data type | Description :--- | :--- | :--- `memory_id` | String | The ID of the memory to retrieve. -#### Example request +## Example request ```json GET /_plugins/_ml/memory/N8AE1osB0jLkkocYjz7D ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -65,7 +65,7 @@ GET /_plugins/_ml/memory/N8AE1osB0jLkkocYjz7D Use this command to get all memories. -### Path and HTTP methods +### Endpoints ```json GET /_plugins/_ml/memory @@ -78,11 +78,11 @@ Use the following query parameters to customize your results. All query paramete Parameter | Data type | Description :--- | :--- | :--- `max_results` | Integer | The maximum number of results to return. If there are fewer memories than the number set in `max_results`, the response returns only the number of memories that exist. Default is `10`. -`next_token` | Integer | The index of the first memory in the sorted list of memories to return. Memories are ordered by `create_time`. For example, if memories A, B, and C exist, `next_token=1` returns memories B and C. Default is `0` (return all memories). +`next_token` | Integer | The index of the first memory in the sorted list of memories to return. Memories are ordered by `updated_time`, starting with the most recently updated memory. For example, if memories A, B, and C exist, `next_token=1` returns memories B and C. Default is `0` (return all memories). ### Paginating results -The `next_token` parameter provides the ordered position of the first memory within the sorted list of memories to return in the results. When a memory is added between subsequent GET Memory calls, one of the listed memories will be duplicated in the results. For example, suppose the current ordered list of memories is `BCDEF`, where `B` is the memory created most recently. When you call the Get Memory API with `next_token=0` and `max_results=3`, the API returns `BCD`. Suppose you then create another memory A. The memory list now appears as `ABCDEF`. The next time you call the Get Memory API with `next_token=3` and `max_results=3`, you'll receive `DEF` in the results. Notice that `D` will be returned in the first and second batches of results. The following diagram illustrates the duplication. +The `next_token` parameter provides the ordered position of the first memory within the sorted list of memories to return in the results. When a memory is added between subsequent GET Memory calls, one of the listed memories will be duplicated in the results. For example, suppose the current ordered list of memories is `BCDEF`, where `B` is the memory updated most recently. When you call the Get Memory API with `next_token=0` and `max_results=3`, the API returns `BCD`. Suppose you then create another memory A. The memory list now appears as `ABCDEF`. The next time you call the Get Memory API with `next_token=3` and `max_results=3`, you'll receive `DEF` in the results. Notice that `D` will be returned in the first and second batches of results. The following diagram illustrates the duplication. Request | List of memories (returned memories are enclosed in brackets) | Results returned in the response :--- | :--- | :--- @@ -91,20 +91,21 @@ Create Memory | ABCDEF | - Get Memory (next_token = 3, max_results = 3) -> ABC[DEF] | DEF -#### Example request: Get all memories +## Example request: Get all memories ```json GET /_plugins/_ml/memory/ ``` {% include copy-curl.html %} -#### Example request: Paginating results +## Example request: Paginating results ```json GET /_plugins/_ml/memory?max_results=2&next_token=1 ``` +{% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -116,11 +117,12 @@ GET /_plugins/_ml/memory?max_results=2&next_token=1 "name": "Conversation for a RAG pipeline", "user": "admin" } - ] + ], + "next_token": 3 } ``` -## Response fields +## Response body fields The following table lists the available response fields. @@ -130,4 +132,6 @@ The following table lists the available response fields. | `create_time` | String | The time at which the memory was created. | | `updated_time` | String | The time at which the memory was last updated. | | `name` | String | The memory name. | -| `user` | String | The username of the user who created the memory. | \ No newline at end of file +| `user` | String | The username of the user who created the memory. Present only when the Security plugin is enabled. | +| `additional_info` | Object | Additional information about the memory. Present only if specified when the memory was created or updated. | +| `next_token` | Integer | The index of the first memory to return in the next page of results. Present in the Get All Memories response only if more results may exist. | \ No newline at end of file diff --git a/_ml-commons-plugin/api/memory-apis/get-message-traces.md b/_ml-commons-plugin/api/memory-apis/get-message-traces.md index 300adfc1..2f880411 100644 --- a/_ml-commons-plugin/api/memory-apis/get-message-traces.md +++ b/_ml-commons-plugin/api/memory-apis/get-message-traces.md @@ -2,11 +2,11 @@ layout: default title: Get message traces parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 70 --- -# Get message traces +# Get Message Traces API **Introduced 2.12** {: .label .label-purple } @@ -14,14 +14,16 @@ Use this API to retrieve message trace information for [conversational search]({ For each message, an agent may need to run different tools. You can use the Get Traces API to get all trace data for a message. The trace data includes detailed steps of a message execution. +Agents registered using the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/index/#unified-registration-method) don't record trace data, so this API returns an empty `traces` array for their messages. + When the Security plugin is enabled, all memories exist in a `private` security mode. Only the user who created a memory can interact with that memory and its messages. {: .important} -## Path and HTTP methods +## Endpoints ```json -GET /_plugins/_ml/memory/message/<message_id>/traces +GET /_plugins/_ml/memory/message/{message_id}/traces ``` ## Path parameters @@ -32,14 +34,44 @@ Parameter | Data type | Description :--- | :--- | :--- `message_id` | String | The ID of the message to trace. -#### Example request +## Query parameters + +Use the following query parameters to customize your results. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`max_results` | Integer | The maximum number of traces to return. Default is `10`. +`next_token` | Integer | The index of the first trace in the list of traces, ordered by `trace_number`, to return. Default is `0`. + +## Response body fields + +The following table lists the available response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory_id` | String | The memory ID. | +| `message_id` | String | The message ID. | +| `create_time` | String | The time at which the message was created. | +| `updated_time` | String | The time at which the message was last updated. | +| `input` | String | The question in the message (human input). In a tool trace, the input sent to the tool. | +| `prompt_template` | String | The prompt template that was used for the message. | +| `response` | String | The answer to the question (generative AI output). In a trace, the LLM response or the tool output. | +| `origin` | String | The name of the AI or other system that generated the response. | +| `additional_info` | Object | Any other information that was sent to the `origin`. | +| `parent_message_id` | String | The ID of the parent message (for trace messages). | +| `trace_number` | Integer | The trace number (for trace messages). | +| `next_token` | Integer | The index of the first trace to return in the next page of results. Present only if more results may exist. | + +Fields that have no value are omitted from the response. + +## Example request ```json GET /_plugins/_ml/memory/message/TAuCZY0BT2tRrkdmCPqZ/traces ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -47,96 +79,41 @@ GET /_plugins/_ml/memory/message/TAuCZY0BT2tRrkdmCPqZ/traces { "memory_id": "7Qt4ZY0BT2tRrkdmSPlo", "message_id": "TQuCZY0BT2tRrkdmEvpp", - "create_time": "2024-02-01T16:30:39.719968032Z", + "create_time": "2026-10-15T18:56:22.771010828Z", + "updated_time": "2026-10-15T18:56:22.771010828Z", "input": "Which index has most documents", - "prompt_template": null, - "response": "Let me check the document counts of each index", - "origin": null, - "additional_info": {}, + "response": "{\"metrics\":{\"latencyMs\":816},\"output\":{\"message\":{\"content\":[{\"text\":\"I'll check all the indices in the OpenSearch cluster to find which one has the most documents.\"},{\"toolUse\":{\"input\":{\"indices\":[]},\"name\":\"ListIndexTool\",\"toolUseId\":\"tooluse_0f8V4bl1yDthOP38a0b1Oo\",\"type\":\"tool_use\"}}],\"role\":\"assistant\"}},\"stopReason\":\"tool_use\",\"usage\":{\"cacheReadInputTokenCount\":0,\"cacheReadInputTokens\":0,\"cacheWriteInputTokenCount\":0,\"cacheWriteInputTokens\":0,\"inputTokens\":748,\"outputTokens\":75,\"serverToolUsage\":{},\"totalTokens\":823}}", + "origin": "LLM", "parent_message_id": "TAuCZY0BT2tRrkdmCPqZ", "trace_number": 1 }, { "memory_id": "7Qt4ZY0BT2tRrkdmSPlo", "message_id": "TguCZY0BT2tRrkdmEvp7", - "create_time": "2024-02-01T16:30:39.732979687Z", - "input": "", - "prompt_template": null, - "response": """health status index uuid pri rep docs.count docs.deleted store.size pri.store.size -green open .plugins-ml-model-group lHgGEgJhT_mpADyOZoXl2g 1 1 9 2 33.4kb 16.7kb -green open .plugins-ml-memory-meta b2LEpv0QS8K60QBjXtRm6g 1 1 13 0 117.5kb 58.7kb -green open .ql-datasources 9NXm_tMXQc6s_4uRToSNkQ 1 1 0 0 416b 208b -green open sample-ecommerce UPYOQcAfRGqFAlSxcZlRjw 1 1 40320 0 4.1mb 2mb -green open .plugins-ml-task xYTlprYCQnaaYici69SOjA 1 1 117 0 115.5kb 57.6kb -green open .opendistro_security 7DAqhm9QQmeEsQYhA40cJg 1 1 10 0 117kb 58.5kb -green open sample-host-health Na5tq6UiTt6r_qYME1vV-w 1 1 40320 0 2.6mb 1.3mb -green open .opensearch-observability 6PthtLluSKyYCdZR3Mw0iw 1 1 0 0 416b 208b -green open .plugins-ml-model WYcjBHcnRuSDHeVWPVupoA 1 1 191 45 4.2gb 2.1gb -green open index_for_neural_sparse GQswGabQRIazM_trnqaDrw 1 1 5 0 28.4kb 14.2kb -green open security-auditlog-2024.01.30 BhXR7Nd3QVOVGxJNpR0-jw 1 1 27768 0 13.8mb 7mb -green open sample-http-responses 0gmYYYdOTiCbVUvl_uDL0w 1 1 40320 0 2.5mb 1.2mb -green open security-auditlog-2024.02.01 2VD1ieDGS5m-TfjIdfT8Eg 1 1 36386 0 37mb 18.2mb -green open opensearch_dashboards_sample_data_ecommerce wnE6r7OvSPqc5YHj8wHSLA 1 1 4675 0 8.8mb 4.4mb -green open security-auditlog-2024.01.31 cNRK5-2eTwes0SRlXTl0RQ 1 1 34520 0 20.5mb 9.8mb -green open .plugins-ml-memory-message wTNBU4BBQVSFcFhNlUdfBQ 1 1 88 1 399.7kb 205kb -green open .plugins-flow-framework-state dJUNDv9MSJ2jjwKbzXPlrw 1 1 39 0 114.1kb 57kb -green open .plugins-ml-agent 7X1IzoLuSGmIujOh9i5mmg 1 1 27 0 146.6kb 73.3kb -green open .plugins-flow-framework-templates _ecC0KahTlmG_3tFUst7Uw 1 1 18 0 175.8kb 87.9kb -green open .plugins-ml-connector q45iJfVjQ5KgxeNC65DLSw 1 1 11 0 313.1kb 156.5kb -green open .kibana_1 vRjXK4bHSUueB_4iXiQ8yw 1 1 257 0 264kb 132kb -green open .plugins-ml-config G7gxGQB7TZeQzBasHd5PUg 1 1 1 0 7.8kb 3.9kb -green open .plugins-ml-controller NQTZPREZRhWoDdjCglRLFg 1 1 0 0 50.1kb 49.9kb -green open opensearch_dashboards_sample_data_logs 9gpOTB3rRgqBLvqis_k5LQ 1 1 14074 0 18mb 9mb -green open .plugins-flow-framework-config JlKPsCh6SEq-Jh6rPL_x9Q 1 1 1 0 7.8kb 3.9kb -green open opensearch_dashboards_sample_data_flights pJde0irnTce4-uobHwYmMQ 1 1 13059 0 11.9mb 5.9mb -green open my_test_data T4hwNs7CTJGIfw2QpCqQ_Q 1 1 6 0 91.7kb 45.8kb -green open .opendistro-job-scheduler-lock XjgmXAVKQ4e8Y-ac54VBzg 1 1 3 0 38.7kb 19.4kb + "create_time": "2026-10-15T18:56:22.775631733Z", + "updated_time": "2026-10-15T18:56:22.775631733Z", + "input": "{\"indices\":[]}", + "response": """row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,.plugins-ml-model-group,lHgGEgJhT_mpADyOZoXl2g,1,0,7,3,61.1kb,61.1kb +2,green,open,.plugins-ml-memory-message,wTNBU4BBQVSFcFhNlUdfBQ,1,0,21,2,55.9kb,55.9kb +... +10,green,open,opensearch_dashboards_sample_data_ecommerce,wnE6r7OvSPqc5YHj8wHSLA,1,0,4675,0,4.9mb,4.9mb """, - "origin": "CatIndexTool", - "additional_info": {}, + "origin": "ListIndexTool", "parent_message_id": "TAuCZY0BT2tRrkdmCPqZ", "trace_number": 2 }, { "memory_id": "7Qt4ZY0BT2tRrkdmSPlo", "message_id": "UwuCZY0BT2tRrkdmHPos", - "create_time": "2024-02-01T16:30:42.217897656Z", + "create_time": "2026-10-15T18:56:24.876003692Z", + "updated_time": "2026-10-15T18:56:24.876003692Z", "input": "Which index has most documents", - "prompt_template": null, - "response": "Based on the cluster health information provided, the index with the most documents is .plugins-ml-model with 191 documents", - "origin": null, - "additional_info": {}, + "response": "Based on the results, **`opensearch_dashboards_sample_data_ecommerce`** index has the most documents with **4,675 documents**.\n\nHere's a summary of the top indices by document count:\n1. **opensearch_dashboards_sample_data_ecommerce** - 4,675 documents\n2. **top_queries-2026.10.15-59495** - 231 documents\n...", + "origin": "LLM", "parent_message_id": "TAuCZY0BT2tRrkdmCPqZ", "trace_number": 3 - }, - { - "memory_id": "7Qt4ZY0BT2tRrkdmSPlo", - "message_id": "UQuCZY0BT2tRrkdmHPos", - "create_time": "2024-02-01T16:30:42.218120716Z", - "input": "Which index has most documents", - "prompt_template": null, - "response": "The index with the most documents is the .plugins-ml-model index, which contains 191 documents based on the cluster health information provided.", - "origin": null, - "additional_info": {}, - "parent_message_id": "TAuCZY0BT2tRrkdmCPqZ", - "trace_number": 4 - }, - { - "memory_id": "7Qt4ZY0BT2tRrkdmSPlo", - "message_id": "UguCZY0BT2tRrkdmHPos", - "create_time": "2024-02-01T16:30:42.218240713Z", - "input": "Which index has most documents", - "prompt_template": null, - "response": "The index with the most documents is the .plugins-ml-model index, which contains 191 documents based on the cluster health information provided.", - "origin": null, - "additional_info": {}, - "parent_message_id": "TAuCZY0BT2tRrkdmCPqZ", - "trace_number": 5 } ] } -``` - -## Response fields - -For information about response fields, see [Create Message request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-message#request-fields). \ No newline at end of file +``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/memory-apis/get-message.md b/_ml-commons-plugin/api/memory-apis/get-message.md index 2f4cfc94..ffabf989 100644 --- a/_ml-commons-plugin/api/memory-apis/get-message.md +++ b/_ml-commons-plugin/api/memory-apis/get-message.md @@ -2,11 +2,11 @@ layout: default title: Get message parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 50 --- -# Get message +# Get Message API **Introduced 2.12** {: .label .label-purple } @@ -24,10 +24,10 @@ When the Security plugin is enabled, all memories exist in a `private` security You can retrieve message information by using the `message_id`. -### Path and HTTP methods +### Endpoints ```json -GET /_plugins/_ml/memory/message/<message_id> +GET /_plugins/_ml/memory/message/{message_id} ``` ### Path parameters @@ -38,40 +38,38 @@ Parameter | Data type | Description :--- | :--- | :--- `message_id` | String | The ID of the message to retrieve. -#### Example request +## Example request ```json GET /_plugins/_ml/memory/message/0m8ya40BfUsSoeNTj-pU ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { "memory_id": "gW8Aa40BfUsSoeNTvOKI", "message_id": "0m8ya40BfUsSoeNTj-pU", "create_time": "2024-02-02T19:01:32.113621539Z", - "input": null, - "prompt_template": null, + "updated_time": "2024-02-02T19:01:32.113621539Z", "response": "Hello, this is OpenAI. Here is the answer to your question.", - "origin": null, "additional_info": { "suggestion": "api.openai.com" } } ``` -For information about response fields, see [Create Message request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-message#request-fields). +For information about response fields, see [Create Message request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-message#request-body-fields). ## Get all messages within a memory Use this command to get a list of messages for a certain memory. -### Path and HTTP methods +### Endpoints ```json -GET /_plugins/_ml/memory/<memory_id>/messages +GET /_plugins/_ml/memory/{memory_id}/messages ``` ### Path parameters @@ -82,25 +80,46 @@ Parameter | Data type | Description :--- | :--- | :--- `memory_id` | String | The ID of the memory for which to retrieve messages. -#### Example request +### Query parameters + +Use the following query parameters to customize your results. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`max_results` | Integer | The maximum number of messages to return. Default is `10`. +`next_token` | Integer | The index of the first message in the sorted list of messages to return. Messages are ordered by `create_time`, starting with the oldest message. Default is `0`. + +Trace messages are not included in the results. To retrieve trace messages, use the [Get Message Traces API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/get-message-traces/). + +## Response body fields + +The following table lists the available response fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory_id` | String | The memory ID. | +| `message_id` | String | The message ID. | +| `create_time` | String | The time at which the message was created. | +| `updated_time` | String | The time at which the message was last updated. | +| `input` | String | The question in the message (human input). | +| `prompt_template` | String | The prompt template that was used for the message. | +| `response` | String | The answer to the question (generative AI output). | +| `origin` | String | The name of the AI or other system that generated the response. | +| `additional_info` | Object | Any other information that was sent to the `origin`. | +| `parent_message_id` | String | The ID of the parent message (for trace messages). | +| `trace_number` | Integer | The trace number (for trace messages). | +| `next_token` | Integer | The index of the first message to return in the next page of results. Present only if more results may exist. | + +Fields that have no value are omitted from the response. + +## Example request ```json GET /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI/messages ``` {% include copy-curl.html %} -```json -POST /_plugins/_ml/message/_search -{ - "query": { - "match_all": {} - }, - "size": 1000 -} -``` -{% include copy-curl.html %} - -#### Example response +## Example response ```json { @@ -109,6 +128,7 @@ POST /_plugins/_ml/message/_search "memory_id": "gW8Aa40BfUsSoeNTvOKI", "message_id": "BW8ha40BfUsSoeNT8-i3", "create_time": "2024-02-02T18:43:23.566994302Z", + "updated_time": "2024-02-02T18:43:23.566994302Z", "input": "How do I make an interaction?", "prompt_template": "Hello OpenAI, can you answer this question?", "response": "Hello, this is OpenAI. Here is the answer to your question.", @@ -121,10 +141,8 @@ POST /_plugins/_ml/message/_search "memory_id": "gW8Aa40BfUsSoeNTvOKI", "message_id": "0m8ya40BfUsSoeNTj-pU", "create_time": "2024-02-02T19:01:32.113621539Z", - "input": null, - "prompt_template": null, + "updated_time": "2024-02-02T19:01:32.113621539Z", "response": "Hello, this is OpenAI. Here is the answer to your question.", - "origin": null, "additional_info": { "suggestion": "api.openai.com" } @@ -132,8 +150,3 @@ POST /_plugins/_ml/message/_search ] } ``` - -## Response fields - -For information about response fields, see [Create Message request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-message#request-fields). - diff --git a/_ml-commons-plugin/api/memory-apis/index.md b/_ml-commons-plugin/api/memory-apis/index.md index a279eafa..702e5007 100644 --- a/_ml-commons-plugin/api/memory-apis/index.md +++ b/_ml-commons-plugin/api/memory-apis/index.md @@ -1,11 +1,12 @@ --- layout: default title: Memory APIs -parent: ML Commons APIs +parent: ML APIs has_children: true has_toc: false -nav_order: 28 -redirect_from: /ml-commons-plugin/api/memory-apis/ +nav_order: 130 +redirect_from: + - /ml-commons-plugin/api/memory-apis/ --- # Memory APIs @@ -14,14 +15,14 @@ redirect_from: /ml-commons-plugin/api/memory-apis/ Memory APIs provide operations needed to implement [conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/). A memory stores conversation history for the current conversation. A message represents one question/answer interaction between the user and a large language model. Messages are organized into memories. -ML Commons supports the following memory-level APIs: +OpenSearch supports the following memory APIs: - [Create or update memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-memory/) - [Get memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/get-memory/) - [Search memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/search-memory/) - [Delete memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/delete-memory/) -ML Commons supports the following message-level APIs: +OpenSearch supports the following message APIs: - [Create or update message]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-message/) - [Get message]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/get-message/) diff --git a/_ml-commons-plugin/api/memory-apis/search-memory.md b/_ml-commons-plugin/api/memory-apis/search-memory.md index fc8dd3e1..4bb4de6c 100644 --- a/_ml-commons-plugin/api/memory-apis/search-memory.md +++ b/_ml-commons-plugin/api/memory-apis/search-memory.md @@ -2,11 +2,11 @@ layout: default title: Search memory parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 25 --- -# Search for a memory +# Search Memory API **Introduced 2.12** {: .label .label-purple } @@ -15,14 +15,14 @@ This API retrieves a conversational memory for [conversational search]({{site.ur When the Security plugin is enabled, all memories exist in a `private` security mode. Only the user who created a memory can interact with that memory and its messages. {: .important} -## Path and HTTP methods +## Endpoints ```json GET /_plugins/_ml/memory/_search POST /_plugins/_ml/memory/_search ``` -#### Example request: Searching for all memories +## Example request: Searching for all memories ```json POST /_plugins/_ml/memory/_search @@ -35,7 +35,7 @@ POST /_plugins/_ml/memory/_search ``` {% include copy-curl.html %} -#### Example request: Searching for a memory by name +## Example request: Searching for a memory by name ```json POST /_plugins/_ml/memory/_search @@ -51,7 +51,7 @@ POST /_plugins/_ml/memory/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -120,14 +120,15 @@ POST /_plugins/_ml/memory/_search } ``` -## Response fields +## Response body fields -The following table lists all response fields. +The response uses the standard OpenSearch search response format. The `_id` of each hit is the memory ID. The following table lists the fields in the `_source` object of each element in the `hits` array. | Field | Data type | Description | | :--- | :--- | :--- | -| `memory_id` | String | The memory ID. | | `create_time` | String | The time at which the memory was created. | | `updated_time` | String | The time at which the memory was last updated. | | `name` | String | The memory name. | -| `user` | String | The username of the user who created the memory. | \ No newline at end of file +| `application_type` | String | The type of application that uses the memory. | +| `additional_info` | Object | Additional information about the memory. Present only if specified. | +| `user` | String | The username of the user who created the memory. Present only when the Security plugin is enabled. | diff --git a/_ml-commons-plugin/api/memory-apis/search-message.md b/_ml-commons-plugin/api/memory-apis/search-message.md index a88ccfbb..f5931842 100644 --- a/_ml-commons-plugin/api/memory-apis/search-message.md +++ b/_ml-commons-plugin/api/memory-apis/search-message.md @@ -2,11 +2,11 @@ layout: default title: Search message parent: Memory APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 60 --- -# Search for a message +# Search Message API **Introduced 2.12** {: .label .label-purple } @@ -15,11 +15,11 @@ Retrieves message information for [conversational search]({{site.url}}{{site.bas When the Security plugin is enabled, all memories exist in a `private` security mode. Only the user who created a memory can interact with that memory and its messages. {: .important} -## Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/memory/<memory_id>/_search -GET /_plugins/_ml/memory/<memory_id>/_search +POST /_plugins/_ml/memory/{memory_id}/_search +GET /_plugins/_ml/memory/{memory_id}/_search ``` ### Path parameters @@ -30,7 +30,24 @@ Parameter | Data type | Description :--- | :--- | :--- `memory_id` | String | The ID of the memory used to search for messages matching the query. -#### Example request +## Response body fields + +The response uses the standard OpenSearch search response format. The `_id` of each hit is the message ID. The following table lists the fields in the `_source` object of each element in the `hits` array. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `memory_id` | String | The memory ID. | +| `create_time` | String | The time at which the message was created. | +| `updated_time` | String | The time at which the message was last updated. | +| `input` | String | The question in the message (human input). | +| `prompt_template` | String | The prompt template that was used for the message. | +| `response` | String | The answer to the question (generative AI output). | +| `origin` | String | The name of the AI or other system that generated the response. | +| `additional_info` | Object | Any other information that was sent to the `origin`. | +| `parent_message_id` | String | The ID of the parent message (for trace messages). | +| `trace_number` | Integer | The trace number (for trace messages). | + +## Example request ```json GET /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI/_search @@ -44,7 +61,7 @@ GET /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -75,6 +92,7 @@ GET /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI/_search "memory_id": "gW8Aa40BfUsSoeNTvOKI", "trace_number": null, "create_time": "2024-02-02T18:43:23.566994302Z", + "updated_time": "2024-02-02T18:43:23.566994302Z", "additional_info": { "suggestion": "api.openai.com" }, @@ -88,7 +106,3 @@ GET /_plugins/_ml/memory/gW8Aa40BfUsSoeNTvOKI/_search } } ``` - -## Response fields - -For information about response fields, see [Create Message request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/memory-apis/create-message#request-fields). \ No newline at end of file diff --git a/_ml-commons-plugin/api/model-apis/batch-predict.md b/_ml-commons-plugin/api/model-apis/batch-predict.md new file mode 100644 index 00000000..8e564114 --- /dev/null +++ b/_ml-commons-plugin/api/model-apis/batch-predict.md @@ -0,0 +1,228 @@ +--- +layout: default +title: Batch predict +parent: Model APIs +grand_parent: ML APIs +nav_order: 70 +--- + +# Batch Predict API + +Runs inference on a large dataset offline and asynchronous mode using a model deployed on external model servers. To use the Batch Predict API, provide the `model_id` of an externally hosted model. Amazon SageMaker, Cohere, and OpenAI are the only verified external servers that support this API. + +For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). + +For information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). + +For instructions on how set up batch inference and connector blueprints, see the following: + +- [Amazon SageMaker batch predict connector blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_sagemaker_connector_blueprint.md) + +- [OpenAI batch predict connector blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_openAI_connector_blueprint.md) + +## Endpoints + +```json +POST /_plugins/_ml/models/{model_id}/_batch_predict +``` + +## Prerequisites + +Before using the Batch Predict API, you need to create a connector to the externally hosted model. For each action, specify the `action_type` parameter that describes the action: + +- `batch_predict`: Runs the batch predict operation. +- `batch_predict_status`: Checks the batch predict operation status. +- `cancel_batch_predict`: Cancels the batch predict operation. + +For example, to create a connector to an OpenAI `text-embedding-ada-002` model, send the following request. The `cancel_batch_predict` action is optional and supports canceling the batch job running on OpenAI: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI Embedding model", + "description": "OpenAI embedding model for testing offline batch", + "version": "1", + "protocol": "http", + "parameters": { + "model": "text-embedding-ada-002", + "input_file_id": "<your input file id in OpenAI>", + "endpoint": "/v1/embeddings" + }, + "credential": { + "openAI_key": "<your openAI key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/embeddings", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input\": ${parameters.input}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.openai.embedding", + "post_process_function": "connector.post_process.openai.embedding" + }, + { + "action_type": "batch_predict", + "method": "POST", + "url": "https://api.openai.com/v1/batches", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input_file_id\": \"${parameters.input_file_id}\", \"endpoint\": \"${parameters.endpoint}\", \"completion_window\": \"24h\" }" + }, + { + "action_type": "batch_predict_status", + "method": "GET", + "url": "https://api.openai.com/v1/batches/${parameters.id}", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + } + }, + { + "action_type": "cancel_batch_predict", + "method": "POST", + "url": "https://api.openai.com/v1/batches/${parameters.id}/cancel", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response contains a connector ID that you'll use in the next steps: + +```json +{ + "connector_id": "XU5UiokBpXT9icfOM0vt" +} +``` + +Next, register an externally hosted model and provide the connector ID of the created connector: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "OpenAI model for realtime embedding and offline batch inference", + "function_name": "remote", + "description": "OpenAI text embedding model", + "connector_id": "XU5UiokBpXT9icfOM0vt" +} +``` +{% include copy-curl.html %} + +The response contains the task ID for the register operation: + +```json +{ + "task_id": "rMormY8B8aiZvtEZIO_j", + "status": "CREATED", + "model_id": "lyjxwZABNrAVdFa9zrcZ" +} +``` + +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/). Once the registration is complete, the task `state` changes to `COMPLETED`. + +## Example request + +Once you have completed the prerequisite steps, you can call the Batch Predict API. The parameters in the batch predict request override those defined in the connector: + +```json +POST /_plugins/_ml/models/lyjxwZABNrAVdFa9zrcZ/_batch_predict +{ + "parameters": { + "model": "text-embedding-3-large" + } +} +``` +{% include copy-curl.html %} + +## Example response + +The response contains the task ID for the batch predict operation: + +```json +{ + "task_id": "KYZSv5EBqL2d0mFvs80C", + "status": "CREATED" +} +``` + +To check the status of the batch predict job, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/). You can find the job details in the `remote_job` field in the task. Once the prediction is complete, the task `state` changes to `COMPLETED`. + +## Example request + +```json +GET /_plugins/_ml/tasks/KYZSv5EBqL2d0mFvs80C +``` +{% include copy-curl.html %} + +## Example response + +The response contains the batch predict operation details in the `remote_job` field: + +```json +{ + "model_id": "JYZRv5EBqL2d0mFvKs1E", + "task_type": "BATCH_PREDICTION", + "function_name": "REMOTE", + "state": "RUNNING", + "input_type": "REMOTE", + "worker_node": [ + "Ee5OCIq0RAy05hqQsNI1rg" + ], + "create_time": 1725491751455, + "last_update_time": 1725491751455, + "is_async": false, + "remote_job": { + "cancelled_at": null, + "metadata": null, + "request_counts": { + "total": 3, + "completed": 3, + "failed": 0 + }, + "input_file_id": "file-XXXXXXXXXXXX", + "output_file_id": "file-XXXXXXXXXXXXX", + "error_file_id": null, + "created_at": 1725491753, + "in_progress_at": 1725491753, + "expired_at": null, + "finalizing_at": 1725491757, + "completed_at": null, + "endpoint": "/v1/embeddings", + "expires_at": 1725578153, + "cancelling_at": null, + "completion_window": "24h", + "id": "batch_XXXXXXXXXXXXXXX", + "failed_at": null, + "errors": null, + "object": "batch", + "status": "in_progress" + } +} +``` + +For the definition of each field in the result, see [OpenAI Batch API](https://platform.openai.com/docs/guides/batch). Once the batch inference is complete, you can download the output by calling the [OpenAI Files API](https://platform.openai.com/docs/api-reference/files) and providing the file name specified in the `id` field of the response. + +### Canceling a batch predict job + +You can also cancel the batch predict operation running on the remote platform using the task ID returned by the batch predict request. To add this capability, set the `action_type` to `cancel_batch_predict` in the connector configuration when creating the connector. + +## Example request + +```json +POST /_plugins/_ml/tasks/KYZSv5EBqL2d0mFvs80C/_cancel +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "status": "OK" +} +``` diff --git a/_ml-commons-plugin/api/model-apis/delete-model.md b/_ml-commons-plugin/api/model-apis/delete-model.md index b35e7c80..863d663b 100644 --- a/_ml-commons-plugin/api/model-apis/delete-model.md +++ b/_ml-commons-plugin/api/model-apis/delete-model.md @@ -2,33 +2,35 @@ layout: default title: Delete model parent: Model APIs -grand_parent: ML Commons APIs -nav_order: 50 +grand_parent: ML APIs +nav_order: 47 --- -# Delete a model +# Delete Model API Deletes a model based on the `model_id`. -When you delete the last model version in a model group, that model group is automatically deleted from the index. +You cannot delete a model that is deployed or being deployed. To delete a deployed model, first [undeploy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/undeploy-model/) it. {: .important} +Deleting the last model version in a model group does not delete the model group. To delete the model group, use the [Delete Model Group API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/delete-model-group/). + For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json -DELETE /_plugins/_ml/models/<model_id> +DELETE /_plugins/_ml/models/{model_id} ``` -#### Example request +## Example request ```json DELETE /_plugins/_ml/models/MzcIJX8BA7mbufL6DOwl ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -36,12 +38,44 @@ DELETE /_plugins/_ml/models/MzcIJX8BA7mbufL6DOwl "_id" : "MzcIJX8BA7mbufL6DOwl", "_version" : 2, "result" : "deleted", + "forced_refresh" : true, "_shards" : { - "total" : 2, - "successful" : 2, + "total" : 1, + "successful" : 1, "failed" : 0 }, "_seq_no" : 27, "_primary_term" : 18 } -``` \ No newline at end of file +``` + +## Error responses + +If you attempt to delete a model that doesn't exist, OpenSearch returns a 404 Not Found error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Failed to find model" + } + ], + "type": "status_exception", + "reason": "Failed to find model" + }, + "status": 404 +} +``` + +## Safely deleting a model +Introduced 2.19 +{: .label .label-purple } + +To prevent accidental deletion of models in active use by agents, search pipelines, ingest pipelines, or other components, you can enable a safety check. If the safety check is enabled and you attempt to delete a model that is in current use, OpenSearch returns an error message. To proceed with deletion: + +- Identify any components using the model and either delete them or update them so that they use other models. +- Once all dependencies are cleared, delete the model. + +For information about enabling this feature, see [Feature settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#feature-settings). \ No newline at end of file diff --git a/_ml-commons-plugin/api/model-apis/deploy-model.md b/_ml-commons-plugin/api/model-apis/deploy-model.md index 52cf3f23..7f39da56 100644 --- a/_ml-commons-plugin/api/model-apis/deploy-model.md +++ b/_ml-commons-plugin/api/model-apis/deploy-model.md @@ -2,23 +2,51 @@ layout: default title: Deploy model parent: Model APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 20 --- -# Deploy a model +# Deploy Model API -The deploy model operation reads the model's chunks from the model index and then creates an instance of the model to cache into memory. This operation requires the `model_id`. +The deploy model operation reads the model's chunks from the model index and then creates an instance of the model to cache in memory. This operation requires the `model_id`. + +[Externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/) are deployed automatically by default when you send a Predict API request for the first time. To disable automatic deployment for an externally hosted model, set `plugins.ml_commons.model_auto_deploy.enable` to `false`: + +```json +PUT _cluster/settings +{ + "persistent": { + "plugins.ml_commons.model_auto_deploy.enable": "false" + } +} +``` +{% include copy-curl.html %} For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/models/<model_id>/_deploy +POST /_plugins/_ml/models/{model_id}/_deploy ``` -#### Example request: Deploying to all available ML nodes +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `model_id` | String | The ID of the model to deploy. Required. | + +## Request body fields + +The following table lists the available request body fields. The request body is optional. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `node_ids` | Array | A list of node IDs on which to deploy the model. If omitted, the model is deployed to all eligible ML nodes. Requires `plugins.ml_commons.allow_custom_deployment_plan` to be set to `true`. For more information, see [ML Commons cluster settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/). | + +## Example request: Deploying to all available ML nodes In this example request, OpenSearch deploys the model to any available OpenSearch ML node: @@ -27,9 +55,9 @@ POST /_plugins/_ml/models/WWQI44MBbzI2oUKAvNUt/_deploy ``` {% include copy-curl.html %} -#### Example request: Deploying to a specific node +## Example request: Deploying to a specific node -If you want to reserve the memory of other ML nodes within your cluster, you can deploy your model to a specific node(s) by specifying the `node_ids` in the request body: +If you want to reserve the memory of other ML nodes within your cluster, you can deploy your model to specific nodes by specifying the `node_ids` in the request body. This option requires the `plugins.ml_commons.allow_custom_deployment_plan` setting to be `true`: ```json POST /_plugins/_ml/models/WWQI44MBbzI2oUKAvNUt/_deploy @@ -39,40 +67,28 @@ POST /_plugins/_ml/models/WWQI44MBbzI2oUKAvNUt/_deploy ``` {% include copy-curl.html %} -#### Example response +## Example response + +The Deploy Model API returns a `task_id` that you can use to monitor the deployment progress: ```json { - "task_id" : "hA8P44MBhyWuIwnfvTKP", - "status" : "DEPLOYING" + "task_id": "hA8P44MBhyWuIwnfvTKP", + "task_type": "DEPLOY_MODEL", + "status": "CREATED" } ``` -## Check the status of model deployment +## Monitoring deployment status -To see the status of your model deployment and retrieve the model ID created for the new model version, pass the `task_id` as a path parameter to the Tasks API: +To check the status of your model deployment and retrieve the model ID when deployment completes, use the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/) and provide the returned `task_id` as a path parameter: ```json GET /_plugins/_ml/tasks/hA8P44MBhyWuIwnfvTKP ``` {% include copy-curl.html %} -The response contains the model ID of the model version: +The Get ML Task API returns different response formats depending on whether the deployment is in progress or completed. For detailed information about all possible response formats, see [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/#example-responses). -```json -{ - "model_id": "Qr1YbogBYOqeeqR7sI9L", - "task_type": "DEPLOY_MODEL", - "function_name": "TEXT_EMBEDDING", - "state": "COMPLETED", - "worker_node": [ - "N77RInqjTSq_UaLh1k0BUg" - ], - "create_time": 1685478486057, - "last_update_time": 1685478491090, - "is_async": true -} -``` - -If a cluster or node is restarted, then you need to redeploy the model. To learn how to set up automatic redeployment, see [Enable auto redeploy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#enable-auto-redeploy). +If a cluster or node is restarted, then you need to redeploy the model. To learn how to set up automatic redeployment, see [Model deployment settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#model-deployment-settings). {: .tip} \ No newline at end of file diff --git a/_ml-commons-plugin/api/model-apis/get-model.md b/_ml-commons-plugin/api/model-apis/get-model.md index 0286497d..82c500b3 100644 --- a/_ml-commons-plugin/api/model-apis/get-model.md +++ b/_ml-commons-plugin/api/model-apis/get-model.md @@ -2,20 +2,20 @@ layout: default title: Get model parent: Model APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 30 --- -# Get a model +# Get Model API You can retrieve model information using the `model_id`. For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json -GET /_plugins/_ml/models/<model_id> +GET /_plugins/_ml/models/{model_id} ``` ## Path parameters @@ -26,33 +26,69 @@ The following table lists the available path parameters. | :--- | :--- | :--- | | `model_id` | String | The model ID of the model to retrieve. | -#### Example request +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `return_content` | Boolean | If `true`, the response contains the `model_content` field, which stores the serialized model content for models trained using the [Train API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/train/). Default is `false`. | + +## Example request ```json GET /_plugins/_ml/models/N8AE1osB0jLkkocYjz7D ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { - "name" : "all-MiniLM-L6-v2_onnx", + "name" : "all-MiniLM-L6-v2", + "model_group_id" : "DNrMP6EBzLnYocCrCMsb", "algorithm" : "TEXT_EMBEDDING", - "version" : "1", + "model_version" : "1", + "description" : "test model", "model_format" : "TORCH_SCRIPT", - "model_state" : "LOADED", - "model_content_size_in_bytes" : 83408741, - "model_content_hash_value" : "9376c2ebd7c83f99ec2526323786c348d2382e6d86576f750c89ea544d6bbb14", + "model_state" : "DEPLOYED", + "model_content_size_in_bytes" : 91790008, + "model_content_hash_value" : "c15f0d2e62d872be5b5bc6c84d2e0f4921541e29fefbef51d59cc10a8ae30e0f", "model_config" : { - "model_type" : "bert", - "embedding_dimension" : 384, - "framework_type" : "SENTENCE_TRANSFORMERS", - "all_config" : """{"_name_or_path":"nreimers/MiniLM-L6-H384-uncased","architectures":["BertModel"],"attention_probs_dropout_prob":0.1,"gradient_checkpointing":false,"hidden_act":"gelu","hidden_dropout_prob":0.1,"hidden_size":384,"initializer_range":0.02,"intermediate_size":1536,"layer_norm_eps":1e-12,"max_position_embeddings":512,"model_type":"bert","num_attention_heads":12,"num_hidden_layers":6,"pad_token_id":0,"position_embedding_type":"absolute","transformers_version":"4.8.2","type_vocab_size":2,"use_cache":true,"vocab_size":30522}""" + "model_type" : "bert", + "embedding_dimension" : 384, + "framework_type" : "SENTENCE_TRANSFORMERS", + "all_config" : "{\"_name_or_path\":\"nreimers/MiniLM-L6-H384-uncased\",\"architectures\":[\"BertModel\"],\"attention_probs_dropout_prob\":0.1,\"gradient_checkpointing\":false,\"hidden_act\":\"gelu\",\"hidden_dropout_prob\":0.1,\"hidden_size\":384,\"initializer_range\":0.02,\"intermediate_size\":1536,\"layer_norm_eps\":1e-12,\"max_position_embeddings\":512,\"model_type\":\"bert\",\"num_attention_heads\":12,\"num_hidden_layers\":6,\"pad_token_id\":0,\"position_embedding_type\":\"absolute\",\"transformers_version\":\"4.8.2\",\"type_vocab_size\":2,\"use_cache\":true,\"vocab_size\":30522}" }, - "created_time" : 1665961344044, - "last_uploaded_time" : 1665961373000, - "last_loaded_time" : 1665961815959, - "total_chunks" : 9 + "created_time" : 1792071708389, + "last_updated_time" : 1792071982946, + "last_registered_time" : 1792071731012, + "last_deployed_time" : 1792071982946, + "auto_redeploy_retry_times" : 0, + "total_chunks" : 10, + "planning_worker_node_count" : 1, + "current_worker_node_count" : 1, + "planning_worker_nodes" : [ + "0b8rV9_nRPWZzG4SHpMPhA" + ], + "deploy_to_all_nodes" : true, + "is_hidden" : false } -``` \ No newline at end of file +``` + +## Valid model states + +When a model is registered, deployed, or undeployed in OpenSearch, it transitions through various model states that reflect its availability. These states help you track the model's readiness for use, loading status, or failure conditions. + +The following table lists all valid model states. + +| Model state | Description | +|:---------------------|:---------------------------------------------------------------------------------------------------------| +| `TRAINED` | The model was trained using the Train API and is ready for prediction. Trained models are not deployed. | +| `REGISTERING` | The model is in the process of being registered to the cluster. | +| `REGISTERED` | The model metadata is registered to the cluster but not yet deployed. | +| `DEPLOYED` | The model has been successfully deployed/loaded to all eligible worker nodes and is ready for inference. | +| `DEPLOYING` | The model is in the process of being deployed to memory. | +| `PARTIALLY_DEPLOYED` | The model has been deployed to some of the eligible worker nodes. | +| `UNDEPLOYED` | The model has been successfully unloaded/undeployed from memory on all the nodes. | +| `DEPLOY_FAILED` | An error occurred while trying to deploy the model to the cluster nodes. | diff --git a/_ml-commons-plugin/api/model-apis/index.md b/_ml-commons-plugin/api/model-apis/index.md index 444da1fe..d2bd9c15 100644 --- a/_ml-commons-plugin/api/model-apis/index.md +++ b/_ml-commons-plugin/api/model-apis/index.md @@ -1,24 +1,57 @@ --- layout: default title: Model APIs -parent: ML Commons APIs +parent: ML APIs has_children: true nav_order: 10 has_toc: false +redirect_from: + - /ml-commons-plugin/api/model-apis/ --- # Model APIs -ML Commons supports the following model-level APIs: +OpenSearch supports the following model APIs: -- [Register model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/) -- [Deploy model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/deploy-model/) -- [Get model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/get-model/) -- [Search model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/search-model/) -- [Update model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/update-model/) -- [Undeploy model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/undeploy-model/) -- [Delete model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/delete-model/) -- [Predict]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) (invokes a model) +- [Register Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/) +- [Deploy Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/deploy-model/) +- [Get Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/get-model/) +- [Search Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/search-model/) +- [Update Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/update-model/) +- [Undeploy Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/undeploy-model/) +- [Delete Model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/delete-model/) + +# Predict APIs + +Predict APIs invoke machine learning (ML) models. OpenSearch supports the following Predict APIs: + +- [Predict]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) +- [Predict Stream]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict-stream/) +- [Batch Predict]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/batch-predict/) + +# Train API + +Use the Train API to train ML algorithms synchronously or asynchronously: + +- [Train]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/train/) + +To train tasks through the API, three inputs are required: + +- Algorithm name: Must be a [FunctionName](https://github.com/opensearch-project/ml-commons/blob/1.3/common/src/main/java/org/opensearch/ml/common/parameter/FunctionName.java). This determines what algorithm the ML model runs. To add a new function, see [How To Add a New Function](https://github.com/opensearch-project/ml-commons/blob/main/docs/how-to-add-new-function.md). +- Model hyperparameters: Adjust these parameters to improve model accuracy. +- Input data: The data that trains the ML model or applies it to predictions. You can input data in two ways: query against your index or use a data frame. + +# Train and Predict API + +The Train and Predict API lets you train and invoke the model using the same dataset: + +- [Train and Predict]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/train-and-predict/) + +# Execute Algorithm API + +Use the Execute Algorithm API to run algorithms that don't require a trained model, such as localization: + +- [Execute Algorithm]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-algorithm/) ## Model access control considerations diff --git a/_ml-commons-plugin/api/model-apis/register-model.md b/_ml-commons-plugin/api/model-apis/register-model.md index 880cbd68..f9030ee6 100644 --- a/_ml-commons-plugin/api/model-apis/register-model.md +++ b/_ml-commons-plugin/api/model-apis/register-model.md @@ -2,11 +2,11 @@ layout: default title: Register model parent: Model APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 10 --- -# Register a model +# Register Model API All versions of a particular model are held in a model group. You can either [register a model group]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/register-model-group/) before registering a model to the group or register a first version of a model, thereby creating the group. Each model group name in the cluster must be globally unique. @@ -22,9 +22,9 @@ If you're using [pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plug For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -If the model is more than 10 MB in size, ML Commons splits it into smaller chunks and saves those chunks in the model's index. +If the model is more than 10 MB in size, OpenSearch splits it into smaller chunks and saves those chunks in the model's index. -## Path and HTTP methods +## Endpoints ```json POST /_plugins/_ml/models/_register @@ -38,93 +38,71 @@ The following table lists the available query parameters. All query parameters a | :--- | :--- | :--- | | `deploy` | Boolean | Whether to deploy the model after registering it. The deploy operation is performed by calling the [Deploy Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/deploy-model/). Default is `false`. | -## Register an OpenSearch-provided pretrained model +## Request body fields + +The request body fields depend on the model type. + +### Register an OpenSearch-provided pretrained model OpenSearch provides several pretrained models. For more information, see [OpenSearch-provided pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/). -### Register a pretrained text embedding model +#### Register a pretrained text embedding model To register a pretrained text embedding model, the only required parameters are `name`, `version`, and `model_format`. -#### Request fields - The following table lists the available request fields. Field | Data type | Required/Optional | Description -:--- | :--- | :--- +:--- | :--- | :--- | :--- `name`| String | Required | The model name. | +`model_id` | String | Optional | A unique identifier for the model. If omitted, OpenSearch generates one automatically. | `version` | String | Required | The model version. | `model_format` | String | Required | The portable format of the model file. Valid values are `TORCH_SCRIPT` and `ONNX`. | `description` | String | Optional| The model description. | -`model_group_id` | String | Optional | The model group ID of the model group to register this model to. -`is_enabled`| Boolean | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. +`model_group_id` | String | Optional | The ID of the model group to which to register the model. +`provisioned_by` | String | Optional | An optional attribution tag identifying the plugin or client that registered the model (for example, `flow-framework`). Included in ML statistics metrics. -#### Example request: OpenSearch-provided text embedding model - -```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" -} -``` -{% include copy-curl.html %} - -### Register a pretrained sparse encoding model +#### Register a pretrained sparse encoding model To register a pretrained sparse encoding model, you must set the function name to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. -#### Request fields - The following table lists the available request fields. Field | Data type | Required/Optional | Description -:--- | :--- | :--- +:--- | :--- | :--- | :--- `name`| String | Required | The model name. | +`model_id` | String | Optional | A unique identifier for the model. If omitted, OpenSearch generates one automatically. | `version` | String | Required | The model version. | `model_format` | String | Required | The portable format of the model file. Valid values are `TORCH_SCRIPT` and `ONNX`. | -`function_name` | String | Required | For text embedding models, set this parameter to `TEXT_EMBEDDING`. For sparse encoding models, set this parameter to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. For cross-encoder models, set this parameter to `TEXT_SIMILARITY`. +`function_name` | String | Required | For text embedding models, set this parameter to `TEXT_EMBEDDING`. For sparse encoding models, set this parameter to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. For cross-encoder models, set this parameter to `TEXT_SIMILARITY`. For question answering models, set this parameter to `QUESTION_ANSWERING`. `model_content_hash_value` | String | Required | The model content hash generated using the SHA-256 hashing algorithm. `url` | String | Required | The URL that contains the model. | `description` | String | Optional| The model description. | -`model_group_id` | String | Optional | The model group ID of the model group to register this model to. -`is_enabled`| Boolean | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. +`model_group_id` | String | Optional | The ID of the model group to which to register this model. +`provisioned_by` | String | Optional | An optional attribution tag identifying the plugin or client that registered the model (for example, `flow-framework`). Included in ML statistics metrics. -#### Example request: OpenSearch-provided sparse encoding model - -```json -POST /_plugins/_ml/models/_register -{ - "name": "amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1", - "version": "1.0.1", - "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", - "model_format": "TORCH_SCRIPT" -} -``` -{% include copy-curl.html %} - -## Register a custom model +### Register a custom model To use a custom model locally within the OpenSearch cluster, you need to provide a URL and a config object for that model. For more information, see [Custom local models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). -### Request fields - The following table lists the available request fields. Field | Data type | Required/Optional | Description -:--- | :--- | :--- +:--- | :--- | :--- | :--- `name`| String | Required | The model name. | +`model_id` | String | Optional | A unique identifier for the model. If omitted, OpenSearch generates one automatically. | `version` | String | Required | The model version. | `model_format` | String | Required | The portable format of the model file. Valid values are `TORCH_SCRIPT` and `ONNX`. | -`function_name` | String | Required | Set this parameter to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. +`function_name` | String | Required | Set this parameter to `TEXT_EMBEDDING`, `SPARSE_ENCODING`, `SPARSE_TOKENIZE`, `TEXT_SIMILARITY`, or `QUESTION_ANSWERING`. `model_content_hash_value` | String | Required | The model content hash generated using the SHA-256 hashing algorithm. -[`model_config`](#the-model_config-object) | Object | Required | The model's configuration, including the `model_type`, `embedding_dimension`, and `framework_type`. `all_config` is an optional JSON string that contains all model configurations. | +[`model_config`](#the-model_config-object) | Object | Required | The model's configuration, including the `model_type`, `embedding_dimension`, and `framework_type`. The optional `all_config` JSON string contains all model configurations. The `additional_config` object contains the corresponding `space_type` for pretrained models or the specified `space_type` for custom models. See [Space types]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-spaces/#distance-calculation). | `url` | String | Required | The URL that contains the model. | `description` | String | Optional| The model description. | `model_group_id` | String | Optional | The model group ID of the model group to register this model to. -`is_enabled`| Boolean | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. +`is_enabled`| Boolean | Optional | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. +`rate_limiter` | Object | Optional | Limits the number of times that any user can call the Predict API on the model. For more information, see [Rate limiting inference calls]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#rate-limiting-inference-calls). +`interface`| Object | Optional | The interface for the model. For more information, see [Interface](#the-interface-parameter).| +`provisioned_by` | String | Optional | An optional attribution tag identifying the plugin or client that registered the model (for example, `flow-framework`). Included in ML statistics metrics. #### The `model_config` object @@ -132,17 +110,146 @@ Field | Data type | Required/Optional | Description | :--- | :--- | :--- | `model_type` | String | The model type, such as `bert`. For a Hugging Face model, the model type is specified in `config.json`. For an example, see the [`all-MiniLM-L6-v2` Hugging Face model `config.json`](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/blob/main/config.json#L15). Required. | | `embedding_dimension` | Integer | The dimension of the model-generated dense vector. For a Hugging Face model, the dimension is specified in the model card. For example, in the [`all-MiniLM-L6-v2` Hugging Face model card](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2), the statement `384 dimensional dense vector space` specifies 384 as the embedding dimension. Required. | -| `framework_type` | String | The framework the model is using. Currently, OpenSearch supports `sentence_transformers` and `huggingface_transformers` frameworks. The `sentence_transformers` model outputs text embeddings directly, so ML Commons does not perform any post processing. For `huggingface_transformers`, ML Commons performs post processing by applying mean pooling to get text embeddings. See the example [`all-MiniLM-L6-v2` Hugging Face model](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) for more details. Required. | +| `framework_type` | String | The framework the model is using. OpenSearch supports `sentence_transformers` and `huggingface_transformers` frameworks. The `sentence_transformers` model outputs text embeddings directly, so OpenSearch does not perform any post processing. For `huggingface_transformers`, OpenSearch performs post processing by applying mean pooling to get text embeddings. See the example [`all-MiniLM-L6-v2` Hugging Face model](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) for more details. Required. | | `all_config` | String | This field is used for reference purposes. You can specify all model configurations in this field. For example, if you are using a Hugging Face model, you can minify the `config.json` file to one line and save its contents in the `all_config` field. Once the model is uploaded, you can use the get model API operation to get all model configurations stored in this field. Optional. | +| `additional_config` | Object | Additional model configurations. Contains the `space_type`, which specifies the distance metric for k-NN search. For OpenSearch-provided pretrained models, this value is automatically set to the corresponding metric (for example, `l2` for `huggingface/sentence-transformers/all-distilroberta-v1`). For custom models, specify your preferred space type. Optional. See [Space types]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-spaces/#distance-calculation). | You can further customize a pretrained sentence transformer model's post-processing logic with the following optional fields in the `model_config` object. | Field | Data type | Description | | :--- | :--- | :--- | -| `pooling_mode` | String | The post-process model output, either `mean`, `mean_sqrt_len`, `max`, `weightedmean`, or `cls`.| +| `pooling_mode` | String | The post-process model output, either `mean`, `mean_sqrt_len`, `max`, `weightedmean`, `cls`, `lasttoken`, or `none`. Use `lasttoken` for decoder-only models (for example, Qwen3-Embedding), for which the final non-padding token captures cumulative context through causal attention. Use `none` for models that already provide pre-pooled output (such as `sentence_embedding` or `pooler_output`) to skip additional pooling.| | `normalize_result` | Boolean | When set to `true`, normalizes the model output in order to scale to a standard range for the model. | -#### Example request: Custom model +### Register a model hosted on a third-party platform + +To register a model hosted on a third-party platform, you can either first create a standalone connector and provide the ID of that connector or specify an internal connector for the model. For more information, see [Creating connectors for third-party ML platforms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). + +The following table lists the available request fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`name`| String | Required | The model name. | +`function_name` | String | Required | Set this parameter to `remote`. +`connector_id` | String | Required | The connector ID of a standalone connector for a model hosted on a third-party platform. For more information, see [Standalone connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-standalone-connector). You must provide either `connector_id` or `connector`. +`connector` | Object | Required | Contains specifications for a connector for a model hosted on a third-party platform. For more information, see [Creating a connector for a specific model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-connector-for-a-specific-model). You must provide either `connector_id` or `connector`. +`model_id` | String | Optional | A unique identifier for the model. If omitted, OpenSearch generates one automatically. | +`description` | String | Optional| The model description. | +`model_group_id` | String | Optional | The model group ID of the model group to register this model to. +`is_enabled`| Boolean | Optional | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. +`rate_limiter` | Object | Optional | Limits the number of times that any user can call the Predict API on the model. For more information, see [Rate limiting inference calls]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#rate-limiting-inference-calls). +`guardrails`| Object | Optional | The guardrails for the model input. For more information, see [Guardrails](#the-guardrails-parameter).| +`interface`| Object | Optional | The interface for the model. For more information, see [Interface](#the-interface-parameter).| +`batch_inference_config` | Object | Optional | Configures batch inference for an externally hosted model. For more information, see [The `batch_inference_config` parameter](#the-batch_inference_config-parameter). | +`provisioned_by` | String | Optional | An optional attribution tag identifying the plugin or client that registered the model (for example, `flow-framework`). Included in ML statistics metrics. + +### Access control and deployment fields + +The following optional fields apply to all model types. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`access_mode` | String | Optional | The access mode of the model group created for this model. Valid values are `public`, `private`, and `restricted`. Applies only when you register the first version of a model without providing a `model_group_id`. For more information, see [Register Model Group API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/register-model-group/). +`backend_roles` | Array | Optional | A list of the model owner's backend roles to add to the model group created for this model. Applies only when `model_group_id` is not provided. Cannot be specified at the same time as `add_all_backend_roles`. +`add_all_backend_roles` | Boolean | Optional | If `true`, all backend roles of the model owner are added to the model group created for this model. Applies only when `model_group_id` is not provided. Cannot be specified at the same time as `backend_roles`. Admin users cannot set this parameter to `true`. +`deploy_setting` | Object | Optional | The deployment settings for the model. Supports the `model_ttl_minutes` field (Long), which specifies the number of minutes after which the deployed model is automatically undeployed (default is `-1`, meaning that the model is not automatically undeployed), and the `is_auto_deploy_enabled` field (Boolean), which specifies whether an undeployed model is automatically deployed when it receives a Predict API request (default is `true`). +`model_node_ids` | Array | Optional | A list of node IDs on which to deploy the model when the model is deployed after registration (`deploy=true`). + +### The `guardrails` parameter + +Guardrails are safety measures for large language models (LLMs). They provide a set of rules and boundaries that control how an LLM behaves and what kind of output it generates. + +To register an externally hosted model with guardrails, provide the `guardrails` parameter, which supports the following fields. All fields are optional. + +Field | Data type | Description +:--- | :--- | :--- +`type` | String | The guardrail type. Valid values are [`local_regex`](#example-request-regex-and-stopword-validation) and [`model`](#example-request-guardrail-model-validation). Using `local_regex`, you can specify a regular expression or stop words. Using `model`, you can specify a guardrail model. For more information, see [Guardrails]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/guardrails/). +`input_guardrail`| Object | The guardrail for the model input. +`output_guardrail`| Object | The guardrail for the model output. +`stop_words`| Object | The list of indexes containing stopwords used for model input/output validation. If the model prompt/response contains a stopword contained in any of the indexes, then the predict request on the model is rejected. +`index_name`| Object | The name of the index storing the stopwords. +`source_fields`| Object | The name of the field storing the stopwords. +`regex`| Object | A regular expression used for input/output validation. If the model prompt/response matches the regular expression, then the predict request on the model is rejected. +`model_id`| String | The guardrail model used to validate user input and LLM output. +`response_filter`| String | The dot path of the field containing the guardrail model response. +`response_validation_regex`| String | The regular expression used to validate the guardrail model response. + +### The `interface` parameter + +The model interface provides a highly flexible way to add arbitrary metadata annotations to all local deep learning models and externally hosted models in a JSON schema syntax. This annotation initiates a validation check on the input and output fields of the model during the model's invocation. The validation check ensures that the input and output fields are in the correct format both before and after the model performs inference. + +To register a model with a model interface, provide the `interface` parameter, which supports the following fields. + +Field | Data type | Description +:--- | :--- |:------------------------------------ +`input`| Object | The JSON schema for the model input. | +`output`| Object | The JSON schema for the model output. | + +The input and output fields are evaluated against the provided JSON schema. You do not need to provide both fields simultaneously. + +#### Connector model interfaces + +To simplify your workflow, you can register an externally hosted model using a connector in one of the [connector blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#connector-blueprints) formats. If you do so, a predefined model interface for this connector is generated automatically during model registration. The predefined model interface is generated based on the connector blueprint and the model's metadata, so you must strictly follow the blueprint when creating the connector in order to avoid errors. + +The following connector blueprints support creating predefined model interfaces: + +- [Amazon Comprehend](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_comprehend_connector_blueprint.md) +- [Amazon Textract](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_textract_connector_blueprint.md) (Note that a predefined model interface is only available for the `DetectDocumentText` API; the `DetectEnities` API is not supported). +- [Amazon Bedrock AI21 Labs Jurassic](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md) +- [Amazon Bedrock Anthropic Claude 3](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3_blueprint.md) +- [Amazon Bedrock Anthropic Claude](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude_blueprint.md) +- [Amazon Bedrock Cohere Embed English v3](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_cohere_cohere.embed-english-v3_blueprint.md) +- [Amazon Bedrock Cohere Embed Multilingual v3](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_cohere_cohere.embed-multilingual-v3_blueprint.md) +- [Amazon Bedrock Titan Text Embeddings](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_titan_embedding_blueprint.md) +- [Amazon Bedrock Titan Multimodal Embeddings](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_titan_multimodal_embedding_blueprint.md) + +To learn more about connector blueprints, see [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#connector-blueprints). + +### The `batch_inference_config` parameter + +Use the `batch_inference_config` parameter to limit the number and size of input strings that OpenSearch sends to the model in one call so that each call stays within the externally hosted model's limits. You can also enable dynamic batching, which combines individual requests to improve overall throughput. You must set at least one of `max_items_per_request` and `max_bytes_per_request` to a positive value. + +The following table lists the `batch_inference_config` fields. + +Field | Data type | Required/Optional | Default | Description +:--- | :--- | :--- | :--- | :--- +`max_items_per_request` | Integer | Optional | `-1` (disabled) | The maximum number of input strings in one call to the model. Omit this parameter or set it to `-1` to disable this limit. +`max_bytes_per_request` | Long | Optional | `-1` (disabled) | The maximum combined size, in bytes, of the input strings in a single call to the model. This limit excludes the other fields in the connector request body, so set the value below the endpoint's payload limit to leave room for them. Omit this parameter or set it to `-1` to disable this limit. +`dynamic_batching` | Object | Optional | | Configures dynamic batching. +`dynamic_batching.enabled` | Boolean | Optional | `false` | When `true`, OpenSearch dynamically batches requests before sending them to the model. Dynamic batching requires a positive value for `max_items_per_request` or `max_bytes_per_request`. +`dynamic_batching.flush_timeout_ms` | Long | Optional | `50` | The maximum time, in milliseconds, that the first request waits for additional requests before the model is invoked in batch. Valid values are 1--10,000. The batch might be invoked earlier if the accumulated input strings reach `max_items_per_request` or `max_bytes_per_request` before the timeout is reached. + +## Example requests + +The following examples show how to register different types of models. + +### Example request: OpenSearch-provided text embedding model + +```json +POST /_plugins/_ml/models/_register +{ + "name": "huggingface/sentence-transformers/msmarco-distilbert-base-tas-b", + "version": "1.0.3", + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "model_format": "TORCH_SCRIPT" +} +``` +{% include copy-curl.html %} + +### Example request: OpenSearch-provided sparse encoding model + +```json +POST /_plugins/_ml/models/_register +{ + "name": "amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-distill", + "version": "1.0.0", + "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "model_format": "TORCH_SCRIPT" +} +``` +{% include copy-curl.html %} + +### Example request: Custom model The following example request registers a version `1.0.0` of an NLP sentence transformation model named `all-MiniLM-L6-v2`. @@ -153,6 +260,7 @@ POST /_plugins/_ml/models/_register "version": "1.0.0", "description": "test model", "model_format": "TORCH_SCRIPT", + "function_name": "TEXT_EMBEDDING", "model_group_id": "FTNlQ4gBYW0Qyy5ZoxfR", "model_content_hash_value": "c15f0d2e62d872be5b5bc6c84d2e0f4921541e29fefbef51d59cc10a8ae30e0f", "model_config": { @@ -166,30 +274,12 @@ POST /_plugins/_ml/models/_register ``` {% include copy-curl.html %} -## Register a model hosted on a third-party platform - -To register a model hosted on a third-party platform, you can either first create a standalone connector and provide the ID of that connector or specify an internal connector for the model. For more information, see [Creating connectors for third-party ML platforms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). - -### Request fields - -The following table lists the available request fields. - -Field | Data type | Required/Optional | Description -:--- | :--- | :--- -`name`| String | Required | The model name. | -`function_name` | String | Required | Set this parameter to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. -`connector_id` | Optional | Required | The connector ID of a standalone connector for a model hosted on a third-party platform. For more information, see [Standalone connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-standalone-connector). You must provide either `connector_id` or `connector`. -`connector` | Object | Required | Contains specifications for a connector for a model hosted on a third-party platform. For more information, see [Creating a connector for a specific model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-connector-for-a-specific-model). You must provide either `connector_id` or `connector`. -`description` | String | Optional| The model description. | -`model_group_id` | String | Optional | The model group ID of the model group to register this model to. -`is_enabled`| Boolean | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. - -#### Example request: Remote model with a standalone connector +### Example request: Externally hosted with a standalone connector ```json POST /_plugins/_ml/models/_register { - "name": "openAI-gpt-3.5-turbo", + "name": "openAI-gpt-4o-mini", "function_name": "remote", "model_group_id": "1jriBYsBq7EKuKzZX131", "description": "test model", @@ -198,25 +288,25 @@ POST /_plugins/_ml/models/_register ``` {% include copy-curl.html %} -#### Example request: Remote model with a connector specified as part of the model +### Example request: Externally hosted with a connector specified as part of the model ```json POST /_plugins/_ml/models/_register { - "name": "openAI-GPT-3.5: internal connector", + "name": "openAI-gpt-4o-mini: internal connector", "function_name": "remote", "model_group_id": "lEFGL4kB4ubqQRzegPo2", "description": "test model", "connector": { "name": "OpenAI Connector", - "description": "The connector to public OpenAI model service for GPT 3.5", + "description": "The connector to public OpenAI model service for gpt-4o-mini", "version": 1, "protocol": "http", "parameters": { "endpoint": "api.openai.com", "max_tokens": 7, "temperature": 0, - "model": "text-davinci-003" + "model": "gpt-4o-mini" }, "credential": { "openAI_key": "..." @@ -225,11 +315,11 @@ POST /_plugins/_ml/models/_register { "action_type": "predict", "method": "POST", - "url": "https://${parameters.endpoint}/v1/completions", + "url": "https://${parameters.endpoint}/v1/chat/completions", "headers": { "Authorization": "Bearer ${credential.openAI_key}" }, - "request_body": "{ \"model\": \"${parameters.model}\", \"prompt\": \"${parameters.prompt}\", \"max_tokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }" + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\": \"user\", \"content\": \"${parameters.prompt}\"}], \"max_tokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }" } ] } @@ -237,23 +327,176 @@ POST /_plugins/_ml/models/_register ``` {% include copy-curl.html %} -#### Example response +### Example request: Regex and stopword validation -OpenSearch responds with the `task_id` and task `status`. +The following example uses a regular expression and a set of stopwords to validate the LLM response: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "openAI-gpt-4o-mini", + "function_name": "remote", + "model_group_id": "1jriBYsBq7EKuKzZX131", + "description": "test model", + "connector_id": "a1eMb4kBJ1eYAeTMAljY", + "guardrails": { + "type": "local_regex", + "input_guardrail": { + "stop_words": [ + { + "index_name": "stop_words_input", + "source_fields": ["title"] + } + ], + "regex": ["regex1", "regex2"] + }, + "output_guardrail": { + "stop_words": [ + { + "index_name": "stop_words_output", + "source_fields": ["title"] + } + ], + "regex": ["regex1", "regex2"] + } + } +} +``` +{% include copy-curl.html %} + +For a complete example, see [Validating input/output using stopwords and regex]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/guardrails/#validating-inputoutput-using-stopwords-and-regex). + +### Example request: Guardrail model validation + +The following example uses a guardrail model to validate the LLM response: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Bedrock Claude Sonnet 4.6 model with guardrails model", + "function_name": "remote", + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "description": "Bedrock Claude Sonnet 4.6 model with guardrails model", + "connector_id": "xnJjDZABNFJeYR3IPvTO", + "guardrails": { + "input_guardrail": { + "model_id": "o3JaDZABNFJeYR3I2fRV", + "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$" + }, + "output_guardrail": { + "model_id": "o3JaDZABNFJeYR3I2fRV", + "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$" + }, + "type": "model" + } +} +``` +{% include copy-curl.html %} + +For a complete example, see [Validating input/output using a guardrail model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/guardrails/#validating-inputoutput-using-a-guardrail-model). + +### Example request: Externally hosted model with an interface + +```json +POST /_plugins/_ml/models/_register +{ + "name": "openAI-gpt-4o-mini", + "function_name": "remote", + "description": "test model", + "connector_id": "A-j7K48BZzNMh1sWVdJu", + "interface": { + "input": { + "properties": { + "parameters": { + "properties": { + "messages": { + "type": "string", + "description": "This is a test description field" + } + } + } + } + }, + "output": { + "properties": { + "inference_results": { + "type": "array", + "items": { + "type": "object", + "properties": { + "output": { + "type": "array", + "items": { + "properties": { + "name": { + "type": "string", + "description": "This is a test description field" + }, + "dataAsMap": { + "type": "object", + "description": "This is a test description field" + } + } + }, + "description": "This is a test description field" + }, + "status_code": { + "type": "integer", + "description": "This is a test description field" + } + } + }, + "description": "This is a test description field" + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Example request: Batch inference configuration + +Obtain the input string count (`max_items_per_request`) and payload (`max_bytes_per_request`) limits from the official documentation for the exact model and provider. For a custom endpoint, use the limits configured on the model server. For configuration guidance, see [Batching requests to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/batching-requests/). + +The following request registers an externally hosted model with size limits and dynamic batching enabled: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "remote-embedding-model", + "function_name": "remote", + "connector_id": "<connector_id>", + "batch_inference_config": { + "max_items_per_request": 96, + "max_bytes_per_request": 4000000, + "dynamic_batching": { + "enabled": true, + "flush_timeout_ms": 50 + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +OpenSearch responds with the `task_id` and task `status`. For externally hosted models, the response also contains the `model_id`. For local models, the model ID is returned in the task after registration completes: ```json { "task_id" : "ew8I44MBhyWuIwnfvDIH", - "status" : "CREATED" + "status" : "CREATED", + "model_id": "t8qvDY4BChVAiNVEuo8q" } ``` -## Check the status of model registration +## Checking the status of model registration -To see the status of your model registration and retrieve the model ID created for the new model version, pass the `task_id` as a path parameter to the Tasks API: +To see the status of your model registration and retrieve the model ID created for the new model version, pass the `task_id` as a path parameter to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): ```json -GET /_plugins/_ml/tasks/<task_id> +GET /_plugins/_ml/tasks/{task_id} ``` {% include copy-curl.html %} @@ -262,7 +505,7 @@ The response contains the model ID of the model version: ```json { "model_id": "Qr1YbogBYOqeeqR7sI9L", - "task_type": "DEPLOY_MODEL", + "task_type": "REGISTER_MODEL", "function_name": "TEXT_EMBEDDING", "state": "COMPLETED", "worker_node": [ diff --git a/_ml-commons-plugin/api/model-apis/search-model.md b/_ml-commons-plugin/api/model-apis/search-model.md index 729237eb..50beb527 100644 --- a/_ml-commons-plugin/api/model-apis/search-model.md +++ b/_ml-commons-plugin/api/model-apis/search-model.md @@ -2,11 +2,11 @@ layout: default title: Search model parent: Model APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 35 --- -# Search for a model +# Search Model API You can use this command to search for models you've already created. @@ -18,14 +18,14 @@ The response will contain only those model versions to which you have access. Fo For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json GET /_plugins/_ml/models/_search POST /_plugins/_ml/models/_search ``` -#### Example request: Searching for all models +## Example request: Searching for all models ```json POST /_plugins/_ml/models/_search @@ -38,7 +38,7 @@ POST /_plugins/_ml/models/_search ``` {% include copy-curl.html %} -#### Example request: Searching for models with the algorithm "FIT_RCF" +## Example request: Searching for models with the algorithm "FIT_RCF" ```json POST /_plugins/_ml/models/_search @@ -54,7 +54,7 @@ POST /_plugins/_ml/models/_search ``` {% include copy-curl.html %} -#### Example: Excluding model chunks +## Example request: Excluding model chunks ```json GET /_plugins/_ml/models/_search @@ -79,9 +79,9 @@ GET /_plugins/_ml/models/_search ``` {% include copy-curl.html %} -#### Example: Searching for all model chunks +## Example request: Searching for all model chunks -The following query searches for all chunks of the model with the ID `979y9YwBjWKCe6KgNGTm` and sorts the chunks in ascending order: +The following query searches for all chunks of the model with the ID `9r9w9YwBjWKCe6KgyGST` and sorts the chunks in ascending order: ```json GET /_plugins/_ml/models/_search @@ -108,7 +108,7 @@ GET /_plugins/_ml/models/_search ``` {% include copy-curl.html %} -#### Example: Searching for a model by description +## Example request: Searching for a model by description ```json GET _plugins/_ml/models/_search @@ -134,7 +134,7 @@ GET _plugins/_ml/models/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -161,9 +161,9 @@ GET _plugins/_ml/models/_search "_primary_term" : 15, "_score" : 2.4159138, "_source" : { + "model_version" : "1.0.0", "name" : "FIT_RCF", - "version" : 1, - "content" : "xxx", + "model_state" : "TRAINED", "algorithm" : "FIT_RCF" } }, @@ -175,9 +175,9 @@ GET _plugins/_ml/models/_search "_primary_term" : 8, "_score" : 2.4159138, "_source" : { + "model_version" : "1.0.0", "name" : "FIT_RCF", - "version" : 1, - "content" : "xxx", + "model_state" : "TRAINED", "algorithm" : "FIT_RCF" } } diff --git a/_ml-commons-plugin/api/model-apis/undeploy-model.md b/_ml-commons-plugin/api/model-apis/undeploy-model.md index 0346d045..780a8ce7 100644 --- a/_ml-commons-plugin/api/model-apis/undeploy-model.md +++ b/_ml-commons-plugin/api/model-apis/undeploy-model.md @@ -2,30 +2,48 @@ layout: default title: Undeploy model parent: Model APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 45 --- -# Undeploy a model +# Undeploy Model API To undeploy a model from memory, use the undeploy operation. For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -### Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/models/<model_id>/_undeploy +POST /_plugins/_ml/models/{model_id}/_undeploy +POST /_plugins/_ml/models/_undeploy ``` -#### Example request: Undeploying a model from all ML nodes +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `model_id` | String | The ID of the model to undeploy. If you use the `/_plugins/_ml/models/_undeploy` endpoint, provide the model IDs in the `model_ids` request body field. | + +## Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `model_ids` | Array | A list of IDs of the models to undeploy. Required if you use the `/_plugins/_ml/models/_undeploy` endpoint. If model access control is enabled, you can specify only one model ID per request. | +| `node_ids` | Array | A list of node IDs from which to undeploy the models. If omitted, the models are undeployed from all nodes. Requires `plugins.ml_commons.allow_custom_deployment_plan` to be set to `true`. | + +## Example request: Undeploying a model from all ML nodes ```json POST /_plugins/_ml/models/MGqJhYMBbbh0ushjm8p_/_undeploy ``` {% include copy-curl.html %} -#### Example request: Undeploying specific models from specific nodes +## Example request: Undeploying specific models from specific nodes ```json POST /_plugins/_ml/models/_undeploy @@ -36,23 +54,62 @@ POST /_plugins/_ml/models/_undeploy ``` {% include copy-curl.html %} -#### Example request: Undeploying specific models from all nodes +## Example request: Undeploying specific models from all nodes ```json +POST /_plugins/_ml/models/_undeploy { "model_ids": ["KDo2ZYQB-v9VEDwdjkZ4"] } ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { "sv7-3CbwQW-4PiIsDOfLxQ" : { "stats" : { - "KDo2ZYQB-v9VEDwdjkZ4" : "UNDEPLOYED" + "KDo2ZYQB-v9VEDwdjkZ4" : "undeployed" } } } ``` + +If a model is not deployed on a node, the status for that model is `not_found`. + +## Automatically undeploy a model based on TTL + +Models can be automatically undeployed from memory based on the predefined time-to-live (TTL) when the model was last accessed or used. To define a TTL that automatically undeploys a model, include the following `ModelDeploySetting` in your machine learning (ML) model. Note that model TTLs are checked periodically by a `sync_up` cron job, so the maximum time that a model lives in memory could be TTL + the `sync_up` job interval. The default cron job interval is 10 seconds. To update the cron job internally, use the following cluster setting: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.sync_up_job_interval_in_seconds": 10 + } +} +``` +{% include copy-curl.html %} + +## Example request: Creating a model with a TTL +```json +POST /_plugins/_ml/models/_register + { + "name": "Sample Model Name", + "function_name": "remote", + "description": "test model", + "connector_id": "-g1nOo8BOaAC5MIJ3_4R", + "deploy_setting": {"model_ttl_minutes": 100} + } +``` +{% include copy-curl.html %} + +## Example request: Updating a model with a TTL when the model is undeployed +```json +PUT /_plugins/_ml/models/COj7K48BZzNMh1sWedLK +{ + "deploy_setting": {"model_ttl_minutes" : 100} +} +``` +{% include copy-curl.html %} diff --git a/_ml-commons-plugin/api/model-apis/update-model.md b/_ml-commons-plugin/api/model-apis/update-model.md index 380f4222..65b18feb 100644 --- a/_ml-commons-plugin/api/model-apis/update-model.md +++ b/_ml-commons-plugin/api/model-apis/update-model.md @@ -2,32 +2,34 @@ layout: default title: Update model parent: Model APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 40 --- -# Update a model +# Update Model API **Introduced 2.12** {: .label .label-purple } -Updates a model based on the `model_ID`. +Updates a model based on the model ID. For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json -PUT /_plugins/_ml/models/<model_id> +PUT /_plugins/_ml/models/{model_id} ``` -## Request fields +## Request body fields The following table lists the updatable fields. Not all request fields are applicable to all models. To determine whether the field is applicable to your model type, see [Register Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/). Field | Data type | Description :--- | :--- | :--- -`connector` | Object | Contains specifications for a connector for a model hosted on a third-party platform. For more information, see [Creating a connector for a specific model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-connector-for-a-specific-model). For information about the updatable fields within a connector, see [Update Connector API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/update-connector/#request-fields). -`connector_id` | Optional | The connector ID of a standalone connector for a model hosted on a third-party platform. For more information, see [Standalone connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-standalone-connector). To update a standalone connector, you must undeploy the model, update the connector, and then redeploy the model. +`batch_inference_config` | Object | Configures batch inference for an externally hosted model. For more information, see [The `batch_inference_config` parameter]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-batch_inference_config-parameter). +`connector` | Object | Contains specifications for a connector for a model hosted on a third-party platform. For more information, see [Creating a connector for a specific model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-connector-for-a-specific-model). For information about the updatable fields within a connector, see [Update Connector API request fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/update-connector/#request-body-fields). +`connector_id` | String | The connector ID of a standalone connector for a model hosted on a third-party platform. For more information, see [Standalone connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-standalone-connector). To update a standalone connector, you must undeploy the model, update the connector, and then redeploy the model. +`deploy_setting` | Object | The deployment settings for the model, containing `model_ttl_minutes` and `is_auto_deploy_enabled`. For more information, see [Access control and deployment fields]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#access-control-and-deployment-fields). `description` | String | The model description. `is_enabled`| Boolean | Specifies whether the model is enabled. Disabling the model makes it unavailable for Predict API requests, regardless of the model's deployment status. Default is `true`. `model_config` | Object | The model's configuration, including the `model_type`, `embedding_dimension`, and `framework_type`. `all_config` is an optional JSON string that contains all model configurations. For more information, see [The `model_config` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model#the-model_config-object). | @@ -36,8 +38,10 @@ Field | Data type | Description `rate_limiter` | Object | Limits the number of times any user can call the Predict API on the model. For more information, see [Rate limiting inference calls]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#rate-limiting-inference-calls). `rate_limiter.limit` | Integer | The maximum number of times any user can call the Predict API on the model per `unit` of time. By default, there is no limit on the number of Predict API calls. Once you set a limit, you cannot reset it to no limit. As an alternative, you can specify a high limit value and a small time unit, for example, 1 request per nanosecond. `rate_limiter.unit` | String | The unit of time for the rate limiter. Valid values are `DAYS`, `HOURS`, `MICROSECONDS`, `MILLISECONDS`, `MINUTES`, `NANOSECONDS`, and `SECONDS`. +`guardrails`| Object | The guardrails for the model. +`interface`| Object | The interface for the model. -#### Example request: Disabling a model +## Example request: Disabling a model ```json PUT /_plugins/_ml/models/MzcIJX8BA7mbufL6DOwl @@ -47,7 +51,7 @@ PUT /_plugins/_ml/models/MzcIJX8BA7mbufL6DOwl ``` {% include copy-curl.html %} -#### Example request: Rate limiting inference calls for a model +## Example request: Rate limiting inference calls for a model The following request limits the number of times you can call the Predict API on the model to 4 Predict API calls per minute: @@ -62,7 +66,55 @@ PUT /_plugins/_ml/models/T_S-cY0BKCJ3ot9qr0aP ``` {% include copy-curl.html %} -#### Example response +## Example requests: Updating the guardrails + +```json +PUT /_plugins/_ml/models/MzcIJX8BA7mbufL6DOwl +{ + "guardrails": { + "type": "local_regex", + "input_guardrail": { + "stop_words": [ + { + "index_name": "updated_stop_words_input", + "source_fields": ["updated_title"] + } + ], + "regex": ["updated_regex1", "updated_regex2"] + }, + "output_guardrail": { + "stop_words": [ + { + "index_name": "updated_stop_words_output", + "source_fields": ["updated_title"] + } + ], + "regex": ["updated_regex1", "updated_regex2"] + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /_plugins/_ml/models/9uGdCJABjaMXYrp14YRj +{ + "guardrails": { + "type": "model", + "input_guardrail": { + "model_id": "V-G1CJABjaMXYrp1QoUC", + "response_validation_regex": "^\\s*[Aa]ccept\\s*$" + }, + "output_guardrail": { + "model_id": "V-G1CJABjaMXYrp1QoUC", + "response_validation_regex": "^\\s*[Aa]ccept\\s*$" + } + } +} +``` +{% include copy-curl.html %} + +## Example response ```json { @@ -70,6 +122,7 @@ PUT /_plugins/_ml/models/T_S-cY0BKCJ3ot9qr0aP "_id": "MzcIJX8BA7mbufL6DOwl", "_version": 10, "result": "updated", + "forced_refresh": true, "_shards": { "total": 1, "successful": 1, @@ -78,4 +131,56 @@ PUT /_plugins/_ml/models/T_S-cY0BKCJ3ot9qr0aP "_seq_no": 48, "_primary_term": 4 } -``` \ No newline at end of file +``` + +## Example request: Updating the model interface + +You can update a model's interface to define input and output schemas. This is useful when working with models that lack a default interface or require customization. For more information about model interfaces, see [The `Interface` parameter]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-interface-parameter). + +The following example request specifies the output schema for an [AI21 Labs Jurassic model](https://aws.amazon.com/bedrock/ai21/) that was registered without a post-processing function: + +```json +PUT /_plugins/_ml/models/IMcNB5UB7judm8f45nXo +{ + "interface": { + "output": "{\n \"type\": \"object\",\n \"properties\": {\n \"inference_results\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"output\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"dataAsMap\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"number\"\n },\n \"prompt\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\n \"type\": \"string\"\n },\n \"tokens\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"generatedToken\": {\n \"type\": \"object\",\n \"properties\": {\n \"token\": {\n \"type\": \"string\"\n },\n \"logprob\": {\n \"type\": \"number\"\n },\n \"raw_logprob\": {\n \"type\": \"number\"\n }\n }\n },\n \"textRange\": {\n \"type\": \"object\",\n \"properties\": {\n \"start\": {\n \"type\": \"number\"\n },\n \"end\": {\n \"type\": \"number\"\n }\n }\n }\n }\n }\n }\n }\n },\n \"completions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\n \"type\": \"string\"\n },\n \"tokens\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"generatedToken\": {\n \"type\": \"object\",\n \"properties\": {\n \"token\": {\n \"type\": \"string\"\n },\n \"logprob\": {\n \"type\": \"number\"\n },\n \"raw_logprob\": {\n \"type\": \"number\"\n }\n }\n },\n \"textRange\": {\n \"type\": \"object\",\n \"properties\": {\n \"start\": {\n \"type\": \"number\"\n },\n \"end\": {\n \"type\": \"number\"\n }\n }\n }\n }\n }\n }\n }\n },\n \"finishReason\": {\n \"type\": \"object\",\n \"properties\": {\n \"reason\": {\n \"type\": \"string\"\n },\n \"length\": {\n \"type\": \"number\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"status_code\": {\n \"type\": \"integer\"\n }\n }\n }\n }\n }\n}" + } +} +``` +{% include copy-curl.html %} + +If the model was registered using the [Amazon Bedrock AI21 Labs Jurassic blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md), a default interface is applied automatically. +{: .note} + +If the model interface is no longer needed, you can remove both the input and output schemas in order to bypass model schema validation: + +```json +PUT /_plugins/_ml/models/IMcNB5UB7judm8f45nXo +{ + "interface": { + "input": null, + "output": null + } +} +``` +{% include copy-curl.html %} + +## Example response + +```json +{ + "_index": ".plugins-ml-model", + "_id": "IMcNB5UB7judm8f45nXo", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 379, + "_primary_term": 5 +} +``` + diff --git a/_ml-commons-plugin/api/model-group-apis/delete-model-group.md b/_ml-commons-plugin/api/model-group-apis/delete-model-group.md index 8ea19224..12ea60a5 100644 --- a/_ml-commons-plugin/api/model-group-apis/delete-model-group.md +++ b/_ml-commons-plugin/api/model-group-apis/delete-model-group.md @@ -2,11 +2,11 @@ layout: default title: Delete model group parent: Model group APIs -grand_parent: ML Commons APIs -nav_order: 40 +grand_parent: ML APIs +nav_order: 50 --- -# Delete a model group +# Delete Model Group API You can only delete a model group if it does not contain any model versions. {: .important} @@ -18,19 +18,22 @@ If model access control is disabled on your cluster, users with the `delete mode Admin users can delete any model group. {: .note} -When you delete the last model version in a model group, that model group is automatically deleted from the index. -{: .important} - For more information, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). -#### Example request +## Endpoints ```json -DELETE _plugins/_ml/model_groups/<model_group_id> +DELETE /_plugins/_ml/model_groups/{model_group_id} +``` + +## Example request + +```json +DELETE _plugins/_ml/model_groups/{model_group_id} ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -38,8 +41,9 @@ DELETE _plugins/_ml/model_groups/<model_group_id> "_id": "l8nnQogByXnLJ-QNpEk2", "_version": 5, "result": "deleted", + "forced_refresh": true, "_shards": { - "total": 2, + "total": 1, "successful": 1, "failed": 0 }, @@ -47,3 +51,26 @@ DELETE _plugins/_ml/model_groups/<model_group_id> "_primary_term": 23 } ``` + +## Response for non-existent model groups + +If you attempt to delete a model group that doesn't exist, the delete operation succeeds and returns `"result": "not_found"`: + +```json +{ + "_index": ".plugins-ml-model-group", + "_id": "l8nnQogByXnLJ-QNpEk2", + "_version": 1, + "result": "not_found", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 5, + "_primary_term": 25 +} +``` + +This idempotent behavior ensures that delete operations can be safely retried without causing errors. diff --git a/_ml-commons-plugin/api/model-group-apis/get-model-group.md b/_ml-commons-plugin/api/model-group-apis/get-model-group.md new file mode 100644 index 00000000..10bb40ce --- /dev/null +++ b/_ml-commons-plugin/api/model-group-apis/get-model-group.md @@ -0,0 +1,50 @@ +--- +layout: default +title: Get model group +parent: Model group APIs +grand_parent: ML APIs +nav_order: 30 +--- + +# Get Model Group API + +Introduced 2.12 +{: .label .label-purple } + +The Get Model Group API returns information about a model group based on that group's ID. + +If model access control is enabled on your cluster, only the owner or users with matching backend roles can get private model groups. Any user can get any public model group. + +If model access control is disabled on your cluster, users with the `get model group API` permission can get any model group. + +For more information, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). + +## Path and HTTP method + +```json +GET /_plugins/_ml/model_groups/{model_group_id} +``` + +### Example request + +The following example request gets a model group based on that group's ID: + +```json +GET /_plugins/_ml/model_groups/{model_group_id} +``` +{% include copy-curl.html %} + +### Example response + +The following response returns the model group information, including the model group's name, version, description, access level, and creation information: + +```json +{ + "name": "test_model_group", + "latest_version": 0, + "description": "This is a public model group", + "access": "public", + "created_time": 1715112992748, + "last_updated_time": 1715112992748 +} +``` diff --git a/_ml-commons-plugin/api/model-group-apis/index.md b/_ml-commons-plugin/api/model-group-apis/index.md index 6df8b3e8..83dc64c3 100644 --- a/_ml-commons-plugin/api/model-group-apis/index.md +++ b/_ml-commons-plugin/api/model-group-apis/index.md @@ -1,17 +1,20 @@ --- layout: default title: Model group APIs -parent: ML Commons APIs +parent: ML APIs has_children: true has_toc: false nav_order: 20 +redirect_from: + - /ml-commons-plugin/api/model-group-apis/ --- # Model group APIs -ML Commons supports the following model-group-level APIs: +OpenSearch supports the following model group APIs: - [Register model group]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/register-model-group/) - [Update model group]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/update-model-group/) +- [Get model group]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/get-model-group/) - [Search model group]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/search-model-group/) - [Delete model group]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-group-apis/delete-model-group/) \ No newline at end of file diff --git a/_ml-commons-plugin/api/model-group-apis/register-model-group.md b/_ml-commons-plugin/api/model-group-apis/register-model-group.md index 312513ff..a5c10d5d 100644 --- a/_ml-commons-plugin/api/model-group-apis/register-model-group.md +++ b/_ml-commons-plugin/api/model-group-apis/register-model-group.md @@ -2,11 +2,11 @@ layout: default title: Register model group parent: Model group APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 10 --- -# Register a model group +# Register Model Group API To register a model group, send a `POST` request to the `_register` endpoint. You can register a model group in `public`, `private`, or `restricted` access mode. @@ -21,19 +21,20 @@ For more information, see [Model access control]({{site.url}}{{site.baseurl}}/ml POST /_plugins/_ml/model_groups/_register ``` -## Request fields +## Request body fields The following table lists the available request fields. Field |Data type | Description :--- | :--- | :--- `name` | String | The model group name. Required. +`model_group_id` | String | A unique identifier for the model group. Optional. If omitted, OpenSearch generates one automatically. `description` | String | The model group description. Optional. `access_mode` | String | The access mode for this model. Valid values are `public`, `private`, and `restricted`. When this parameter is set to `restricted`, you must specify either `backend_roles` or `add_all_backend_roles`, but not both. Optional. If you specify none of the security parameters (`access_mode`, `backend_roles`, and `add_all_backend_roles`), the default `access_mode` is `private`. `backend_roles` | Array | A list of the model owner's backend roles to add to the model. Can be specified only if `access_mode` is `restricted`. Cannot be specified at the same time as `add_all_backend_roles`. Optional. `add_all_backend_roles` | Boolean | If `true`, all backend roles of the model owner are added to the model group. Default is `false`. Cannot be specified at the same time as `backend_roles`. Admin users cannot set this parameter to `true`. Optional. -#### Example request +## Example request ```json POST /_plugins/_ml/model_groups/_register @@ -45,7 +46,7 @@ POST /_plugins/_ml/model_groups/_register ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -54,7 +55,7 @@ POST /_plugins/_ml/model_groups/_register } ``` -## Response fields +## Response body fields The following table lists the available response fields. @@ -90,7 +91,7 @@ Any user who shares a backend role with the model group can access any model in An admin user can access all model groups regardless of their access mode. {: .note} -#### Example request: A list of backend roles +## Example request: A list of backend roles The following request registers a restricted model group, which can be accessed only by users with the `IT` backend role: @@ -105,7 +106,7 @@ POST /_plugins/_ml/model_groups/_register ``` {% include copy-curl.html %} -#### Example request: All backend roles +## Example request: All backend roles The following request registers a restricted model group, adding all backend roles of the user to the model group: @@ -147,4 +148,4 @@ POST /_plugins/_ml/model_groups/_register ## Registering a model group in a cluster where model access control is disabled -If model access control is disabled on your cluster (one of the [prerequisites](ml-commons-plugin/model-access-control/#model-access-control-prerequisites) is not met), you can register a model group with a `name` and `description` but cannot specify any of the access parameters (`model_access_name`, `backend_roles`, or `add_backend_roles`). By default, in such a cluster, all model groups are public. \ No newline at end of file +If model access control is disabled on your cluster (one of the [prerequisites]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/#model-access-control-prerequisites) is not met), you can register a model group with a `name` and `description` but cannot specify any of the access parameters (`access_mode`, `backend_roles`, or `add_all_backend_roles`). By default, in such a cluster, all model groups are public. \ No newline at end of file diff --git a/_ml-commons-plugin/api/model-group-apis/search-model-group.md b/_ml-commons-plugin/api/model-group-apis/search-model-group.md index 1d47d550..a174b315 100644 --- a/_ml-commons-plugin/api/model-group-apis/search-model-group.md +++ b/_ml-commons-plugin/api/model-group-apis/search-model-group.md @@ -2,11 +2,11 @@ layout: default title: Search model group parent: Model group APIs -grand_parent: ML Commons APIs -nav_order: 30 +grand_parent: ML APIs +nav_order: 40 --- -# Search for a model group +# Search Model Group API When you search for a model group, only those model groups to which you have access will be returned. For example, for a match all query, model groups that will be returned are: @@ -23,7 +23,7 @@ POST /_plugins/_ml/model_groups/_search GET /_plugins/_ml/model_groups/_search ``` -#### Example request: Match all +## Example request: Match all The following request is sent by `user1` who has the `IT` and `HR` roles: @@ -38,7 +38,7 @@ POST /_plugins/_ml/model_groups/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -81,7 +81,8 @@ POST /_plugins/_ml/model_groups/_search "test_ml" ], "name": "user1", - "user_requested_tenant": "__user__" + "user_requested_tenant": "__user__", + "user_requested_tenant_access": "NONE" }, "created_time": 1685734407714, "access": "restricted", @@ -114,7 +115,8 @@ POST /_plugins/_ml/model_groups/_search "test_ml" ], "name": "user1", - "user_requested_tenant": "__user__" + "user_requested_tenant": "__user__", + "user_requested_tenant_access": "NONE" }, "created_time": 1685734410470, "access": "restricted", @@ -130,7 +132,7 @@ POST /_plugins/_ml/model_groups/_search } ``` -#### Example request: Search for model groups with an owner name +## Example request: Search for model groups with an owner name The following request to search for model groups of `user` is sent by `user2` who has the `IT` backend role: @@ -163,7 +165,7 @@ GET /_plugins/_ml/model_groups/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -206,7 +208,8 @@ GET /_plugins/_ml/model_groups/_search "test_ml" ], "name": "user1", - "user_requested_tenant": "__user__" + "user_requested_tenant": "__user__", + "user_requested_tenant_access": "NONE" }, "created_time": 1685734407714, "access": "restricted", @@ -222,7 +225,7 @@ GET /_plugins/_ml/model_groups/_search } ``` -#### Example request: Search for model groups with a model group ID +## Example request: Search for model groups with a model group ID ```json GET /_plugins/_ml/model_groups/_search @@ -244,7 +247,7 @@ GET /_plugins/_ml/model_groups/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -276,7 +279,6 @@ GET /_plugins/_ml/model_groups/_search ], "owner": { "backend_roles": [ - "", "HR", "IT" ], @@ -287,9 +289,11 @@ GET /_plugins/_ml/model_groups/_search "test-ml" ], "name": "user1", - "user_requested_tenant": null + "user_requested_tenant": null, + "user_requested_tenant_access": "NONE" }, "created_time": 1684362035938, + "access": "restricted", "latest_version": 2, "last_updated_time": 1684362571300, "name": "model_group_test", diff --git a/_ml-commons-plugin/api/model-group-apis/update-model-group.md b/_ml-commons-plugin/api/model-group-apis/update-model-group.md index 5aa52397..3706a972 100644 --- a/_ml-commons-plugin/api/model-group-apis/update-model-group.md +++ b/_ml-commons-plugin/api/model-group-apis/update-model-group.md @@ -2,11 +2,11 @@ layout: default title: Update model group parent: Model group APIs -grand_parent: ML Commons APIs +grand_parent: ML APIs nav_order: 20 --- -# Update a model group +# Update Model Group API To update a model group, send a `PUT` request to the `model_groups` endpoint and provide the ID of the model group you want to update. @@ -21,17 +21,25 @@ For more information, see [Model access control]({{site.url}}{{site.baseurl}}/ml ## Path and HTTP method ```json -PUT /_plugins/_ml/model_groups/<model_group_id> +PUT /_plugins/_ml/model_groups/{model_group_id} ``` -## Request fields +## Request body fields -Refer to [Request fields](#request-fields) for request field descriptions. +The following table lists the available request body fields. All fields are optional. -#### Example request +Field |Data type | Description +:--- | :--- | :--- +`name` | String | The model group name. Must be unique in the cluster. +`description` | String | The model group description. +`access_mode` | String | The access mode for this model group. Valid values are `public`, `private`, and `restricted`. When this parameter is set to `restricted`, you must specify either `backend_roles` or `add_all_backend_roles`, but not both. Changing the access mode to `public` or `private` removes the model group's backend roles. +`backend_roles` | Array | A list of the model owner's backend roles to add to the model group. Can be specified only if `access_mode` is `restricted` or omitted. If you specify `backend_roles` without `access_mode`, the access mode changes to `restricted`. Cannot be specified at the same time as `add_all_backend_roles`. +`add_all_backend_roles` | Boolean | If `true`, all backend roles of the model owner are added to the model group. If you set this parameter to `true` without specifying `access_mode`, the access mode changes to `restricted`. Cannot be specified at the same time as `backend_roles`. Admin users cannot set this parameter to `true`. + +## Example request ```json -PUT /_plugins/_ml/model_groups/<model_group_id> +PUT /_plugins/_ml/model_groups/{model_group_id} { "name": "model_group_test", "description": "This is the updated description", @@ -40,6 +48,14 @@ PUT /_plugins/_ml/model_groups/<model_group_id> ``` {% include copy-curl.html %} +## Example response + +```json +{ + "status": "Updated" +} +``` + ## Updating a model group in a cluster where model access control is disabled -If model access control is disabled on your cluster (one of the [prerequisites](ml-commons-plugin/model-access-control/#model-access-control-prerequisites) is not met), you can update only the `name` and `description` of a model group but cannot update any of the access parameters (`model_access_name`, `backend_roles`, or `add_backend_roles`). \ No newline at end of file +If model access control is disabled on your cluster (one of the [prerequisites]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/#model-access-control-prerequisites) is not met), you can update only the `name` and `description` of a model group but cannot update any of the access parameters (`access_mode`, `backend_roles`, or `add_all_backend_roles`). \ No newline at end of file diff --git a/_ml-commons-plugin/api/profile.md b/_ml-commons-plugin/api/profile.md index e8f65bb1..49bd9251 100644 --- a/_ml-commons-plugin/api/profile.md +++ b/_ml-commons-plugin/api/profile.md @@ -1,13 +1,13 @@ --- layout: default title: Profile -parent: ML Commons APIs -nav_order: 40 +parent: ML APIs +nav_order: 150 --- -# Profile +# ML Profile API -The profile API operation returns runtime information about ML tasks and models. The profile operation can help debug model issues at runtime. +The Profile API returns runtime information about machine learning (ML) tasks and models. Use it to debug model issues at runtime. ## The number of requests returned @@ -21,17 +21,18 @@ PUT _cluster/settings } } ``` +{% include copy-curl.html %} To clear all monitoring requests, set `plugins.ml_commons.monitoring_request_count` to `0`. -## Path and HTTP methods +## Endpoints ```json GET /_plugins/_ml/profile GET /_plugins/_ml/profile/models -GET /_plugins/_ml/profile/models/<model_id> +GET /_plugins/_ml/profile/models/{model_id} GET /_plugins/_ml/profile/tasks -GET /_plugins/_ml/profile/tasks/<task_id> +GET /_plugins/_ml/profile/tasks/{task_id} ``` ## Path parameters @@ -41,19 +42,19 @@ Parameter | Data type | Description `model_id` | String | Returns runtime data for a specific model. You can provide multiple model IDs as comma-separated values to retrieve multiple model profiles. `task_id`| String | Returns runtime data for a specific task. You can provide multiple task IDs as comma-separated values to retrieve multiple task profiles. -### Request fields +### Request body fields All profile body request fields are optional. Field | Data type | Description :--- | :--- | :--- -`node_ids` | String | Returns all tasks and profiles from a specific node. -`model_ids` | String | Returns runtime data for a specific model. You can string together multiple model IDs to return multiple model profiles. -`task_ids` | String | Returns runtime data for a specific task. You can string together multiple task IDs to return multiple task profiles. +`node_ids` | Array | Returns all tasks and profiles from the specified nodes. +`model_ids` | Array | Returns runtime data for the specified models. +`task_ids` | Array | Returns runtime data for the specified tasks. `return_all_tasks` | Boolean | Determines whether or not a request returns all tasks. When set to `false`, task profiles are left out of the response. `return_all_models` | Boolean | Determines whether or not a profile request returns all models. When set to `false`, model profiles are left out of the response. -#### Example request: Returning all tasks and models on a specific node +## Example request: Returning all tasks and models on a specific node ```json GET /_plugins/_ml/profile @@ -65,7 +66,7 @@ GET /_plugins/_ml/profile ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -84,10 +85,22 @@ GET /_plugins/_ml/profile "models" : { "WWQI44MBbzI2oUKAvNUt" : { # model id "model_state" : "DEPLOYED", # model status - "predictor" : "org.opensearch.ml.engine.algorithms.text_embedding.TextEmbeddingModel@592814c9", + "predictor" : "org.opensearch.ml.engine.algorithms.text_embedding.TextEmbeddingDenseModel@592814c9", + "target_worker_nodes" : [ # nodes planned for deployment + "KzONM8c8T4Od-NoUANQNGg" + ], "worker_nodes" : [ # routing table "KzONM8c8T4Od-NoUANQNGg" ], + "model_inference_stats" : { # model inference latency on this node + "count" : 2, + "max" : 88.827301, + "min" : 4.251, + "average" : 46.5391505, + "p50" : 46.5391505, + "p90" : 80.3683304, + "p99" : 87.98140399 + }, "predict_request_stats" : { # predict request stats on this node "count" : 2, # total predict requests on this node "max" : 89.978681, # max latency in milliseconds diff --git a/_ml-commons-plugin/api/stats.md b/_ml-commons-plugin/api/stats.md index 8d93a96d..4642f3b9 100644 --- a/_ml-commons-plugin/api/stats.md +++ b/_ml-commons-plugin/api/stats.md @@ -1,79 +1,141 @@ --- layout: default title: Stats -parent: ML Commons APIs -nav_order: 50 +parent: ML APIs +nav_order: 160 --- -# Stats +# ML Stats API -Gets statistics related to the number of tasks. +The Stats API returns basic machine learning (ML) statistics, such as the number of running tasks. To monitor machine learning workflows using more detailed time-series metrics, see [Monitoring machine learning workflows]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/metrics/#monitoring-machine-learning-workflows). +{: .note } -## Path and HTTP methods +The response contains cluster-level statistics, such as the ML index status and the number of models, and node-level statistics, such as the number of requests, broken down by algorithm and model. + +## Endpoints ```json GET /_plugins/_ml/stats -GET /_plugins/_ml/stats/<stat> -GET /_plugins/_ml/<nodeId>/stats/ -GET /_plugins/_ml/<nodeId>/stats/<stat> +GET /_plugins/_ml/stats/{stat} +GET /_plugins/_ml/{nodeId}/stats/ +GET /_plugins/_ml/{nodeId}/stats/{stat} ``` -#### Example request: Get all stats for all nodes +## Path parameters + +The following table lists the available path parameters. All path parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `nodeId` | String | A comma-separated list of node IDs for which to return statistics. If omitted, statistics for all nodes are returned. | +| `stat` | String | A comma-separated list of statistics to return. Valid cluster-level values are `ml_model_index_status`, `ml_connector_index_status`, `ml_config_index_status`, `ml_task_index_status`, `ml_controller_index_status`, `ml_model_count`, and `ml_connector_count`. Valid node-level values are `ml_jvm_heap_usage`, `ml_executing_task_count`, `ml_request_count`, `ml_failure_count`, `ml_deployed_model_count`, and `ml_circuit_breaker_trigger_count`. | + +## Request body fields + +You can also filter statistics by providing the following optional fields in the request body. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `target_stat_levels` | Array | The levels of statistics to return. Valid values are `cluster`, `node`, `algorithm`, `model`, and `action`. | +| `cluster_level_stats` | Array | The cluster-level statistics to return. For valid values, see the `stat` path parameter. | +| `node_level_stats` | Array | The node-level statistics to return. For valid values, see the `stat` path parameter. | +| `action_level_stats` | Array | The action-level statistics to return. Valid values are `ml_action_request_count` and `ml_action_failure_count`. | +| `node_ids` | Array | The IDs of the nodes for which to return statistics. | +| `algorithms` | Array | The algorithms for which to return statistics, for example, `kmeans` or `text_embedding`. | +| `models` | Array | The IDs of the models for which to return statistics. | +| `actions` | Array | The actions for which to return statistics. Valid values are `train`, `predict`, `train_predict`, `execute`, `register`, `deploy`, `undeploy`, and `batch_predict`. | + +## Example request: Get all stats for all nodes ```json GET /_plugins/_ml/stats ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { - "zbduvgCCSOeu6cfbQhTpnQ" : { - "ml_executing_task_count" : 0 - }, - "54xOe0w8Qjyze00UuLDfdA" : { - "ml_executing_task_count" : 0 - }, - "UJiykI7bTKiCpR-rqLYHyw" : { - "ml_executing_task_count" : 0 - }, - "zj2_NgIbTP-StNlGZJlxdg" : { - "ml_executing_task_count" : 0 - }, - "jjqFrlW7QWmni1tRnb_7Dg" : { - "ml_executing_task_count" : 0 - }, - "3pSSjl5PSVqzv5-hBdFqyA" : { - "ml_executing_task_count" : 0 - }, - "A_IiqoloTDK01uZvCjREaA" : { - "ml_executing_task_count" : 0 + "ml_controller_index_status" : "non-existent", + "ml_task_index_status" : "green", + "ml_config_index_status" : "green", + "ml_connector_index_status" : "green", + "ml_model_count" : 13, + "ml_connector_count" : 1, + "ml_model_index_status" : "green", + "nodes" : { + "zbduvgCCSOeu6cfbQhTpnQ" : { + "ml_jvm_heap_usage" : 77, + "ml_failure_count" : 0, + "ml_executing_task_count" : 0, + "ml_request_count" : 69, + "ml_circuit_breaker_trigger_count" : 0, + "ml_deployed_model_count" : 3, + "algorithms" : { + "text_embedding" : { + "predict" : { + "ml_action_request_count" : 2 + }, + "deploy" : { + "ml_action_request_count" : 3 + }, + "register" : { + "ml_action_request_count" : 6 + } + }, + "kmeans" : { + "train" : { + "ml_action_request_count" : 3 + } + }, + ... + }, + "models" : { + "GtrMP6EBzLnYocCrLsvl" : { + "predict" : { + "ml_action_request_count" : 2 + }, + "deploy" : { + "ml_action_request_count" : 2 + } + }, + ... + } + } } } ``` -#### Example request: Get all stats for a specific node +## Example request: Get all stats for a specific node ```json -GET /_plugins/_ml/<nodeId>/stats/ +GET /_plugins/_ml/{nodeId}/stats/ ``` {% include copy-curl.html %} -#### Example request: Get a specified stat for a specific node +## Example request: Get a specified stat for a specific node ```json -GET /_plugins/_ml/<nodeId>/stats/<stat> +GET /_plugins/_ml/{nodeId}/stats/{stat} ``` {% include copy-curl.html %} -#### Example request: Get a specified stat for all nodes +## Example request: Get a specified stat for all nodes ```json -GET /_plugins/_ml/stats/<stat> +GET /_plugins/_ml/stats/{stat} ``` {% include copy-curl.html %} +## Example request: Filter statistics using the request body - - +```json +GET /_plugins/_ml/stats +{ + "target_stat_levels": ["node", "algorithm"], + "node_level_stats": ["ml_request_count"], + "algorithms": ["kmeans"], + "actions": ["train"] +} +``` +{% include copy-curl.html %} diff --git a/_ml-commons-plugin/api/tasks-apis/delete-task.md b/_ml-commons-plugin/api/tasks-apis/delete-task.md index f3e0b089..e034fb73 100644 --- a/_ml-commons-plugin/api/tasks-apis/delete-task.md +++ b/_ml-commons-plugin/api/tasks-apis/delete-task.md @@ -1,32 +1,32 @@ --- layout: default -title: Delete task -parent: Tasks APIs -grand_parent: ML Commons APIs +title: Delete ML task +parent: ML Tasks APIs +grand_parent: ML APIs nav_order: 20 --- -# Delete a task +# Delete ML Task API -Deletes a task based on the `task_id`. +Deletes a machine learning (ML) task based on the `task_id`. -ML Commons does not check the task status when running the delete request. There is a risk that a currently running task could be deleted before the task completes. To check the status of a task, run `GET /_plugins/_ml/tasks/<task_id>` before task deletion. +OpenSearch does not check the task status when running the delete request. There is a risk that a currently running task could be deleted before the task completes. To check the status of a task, run `GET /_plugins/_ml/tasks/<task_id>` before task deletion. {: .note} -### Path and HTTP methods +## Endpoints ```json -DELETE /_plugins/_ml/tasks/<task_id> +DELETE /_plugins/_ml/tasks/{task_id} ``` -#### Example request +## Example request ```json DELETE /_plugins/_ml/tasks/xQRYLX8BydmmU1x6nuD3 ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -34,12 +34,33 @@ DELETE /_plugins/_ml/tasks/xQRYLX8BydmmU1x6nuD3 "_id" : "xQRYLX8BydmmU1x6nuD3", "_version" : 4, "result" : "deleted", + "forced_refresh" : true, "_shards" : { - "total" : 2, - "successful" : 2, + "total" : 1, + "successful" : 1, "failed" : 0 }, "_seq_no" : 42, "_primary_term" : 7 } +``` + +## Error responses + +If you attempt to delete a task that doesn't exist, OpenSearch returns a 404 Not Found error: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Failed to find task" + } + ], + "type": "status_exception", + "reason": "Failed to find task" + }, + "status": 404 +} ``` \ No newline at end of file diff --git a/_ml-commons-plugin/api/tasks-apis/get-task.md b/_ml-commons-plugin/api/tasks-apis/get-task.md index 14b28e84..b28f8956 100644 --- a/_ml-commons-plugin/api/tasks-apis/get-task.md +++ b/_ml-commons-plugin/api/tasks-apis/get-task.md @@ -1,31 +1,90 @@ --- layout: default -title: Get task -parent: Tasks APIs -grand_parent: ML Commons APIs +title: Get ML task +parent: ML Tasks APIs +grand_parent: ML APIs nav_order: 10 --- -# Get task +# Get ML Task API -You can retrieve information about a task using the `task_id`. +You can retrieve information about a machine learning (ML) task (such as model training, deployment, or prediction tasks) using the `task_id`. -## Path and HTTP methods +This API is different from the [general Tasks API]({{site.url}}{{site.baseurl}}/api-reference/tasks/get-tasks/), which tracks general OpenSearch operations and has a different response format. +{: .important } + +## Endpoints ```json -GET /_plugins/_ml/tasks/<task_id> +GET /_plugins/_ml/tasks/{task_id} ``` -#### Example request +## Example request ```json GET /_plugins/_ml/tasks/MsBi1YsB0jLkkocYjD5f ``` {% include copy-curl.html %} -#### Example response +## Example responses -The response includes information about the task. +The response format depends on the task state. Different ML operations (for example, model training, deployment, or registration) return different response formats based on their current status. + +### Task in progress + +While a model registration task is still running, the response includes task details but excludes the `model_id`: + +```json +{ + "task_type": "REGISTER_MODEL", + "function_name": "TEXT_EMBEDDING", + "state": "CREATED", + "worker_node": ["KfEEGG7_SsKZVFqI4ko2FA"], + "create_time": 1767030135146, + "last_update_time": 1767030135771, + "is_async": true +} +``` + +### Task completed + +When a task completes successfully, the response includes the `model_id` and full task details: + +**Model deployment task**: + +```json +{ + "model_id": "Qr1YbogBYOqeeqR7sI9L", + "task_type": "DEPLOY_MODEL", + "function_name": "TEXT_EMBEDDING", + "state": "COMPLETED", + "worker_node": [ + "N77RInqjTSq_UaLh1k0BUg" + ], + "create_time": 1685478486057, + "last_update_time": 1685478491090, + "is_async": true +} +``` + +**Model registration task**: + +```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 +} +``` + +**Model training task**: ```json { @@ -34,9 +93,30 @@ The response includes information about the task. "function_name" : "KMEANS", "state" : "COMPLETED", "input_type" : "SEARCH_QUERY", - "worker_node" : "54xOe0w8Qjyze00UuLDfdA", + "worker_node" : [ + "54xOe0w8Qjyze00UuLDfdA" + ], "create_time" : 1647545342556, "last_update_time" : 1647545342587, "is_async" : true } ``` + +## Response fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `model_id` | String | The unique identifier for the ML model. Available when task is completed. | +| `task_type` | String | The type of ML operation (for example, `REGISTER_MODEL`, `DEPLOY_MODEL`, or `TRAINING`). | +| `function_name` | String | The ML function type (for example, `TEXT_EMBEDDING` or `KMEANS`). | +| `state` | String | The current task state. Valid values are `CREATED` (task created), `RUNNING` (task actively executing), `COMPLETED` (task finished successfully), `FAILED` (task encountered an error), `CANCELLED` (task was canceled), `COMPLETED_WITH_ERROR` (task completed with errors), `CANCELLING` (task being canceled), `EXPIRED` (task expired), and `UNREACHABLE` (task node unreachable). | +| `worker_node` | Array | An array of node IDs of nodes on which the task is running. | +| `create_time` | Long | The timestamp when the task was created, in milliseconds since epoch. | +| `last_update_time` | Long | The timestamp of the last status update, in milliseconds since epoch. | +| `is_async` | Boolean | Whether the task runs asynchronously. Usually `true` for ML tasks. | +| `input_type` | String | The input type for training tasks (for example, `SEARCH_QUERY`). | +| `error` | String | The error message. Returned only if the task failed or completed with errors. | +| `remote_job` | Object | The details of the remote job, such as the job ID and status, returned by the external service. Returned only for batch prediction tasks. | +| `response` | Object | The agent execution result. Returned only for asynchronous agent execution tasks. | diff --git a/_ml-commons-plugin/api/tasks-apis/index.md b/_ml-commons-plugin/api/tasks-apis/index.md index e6f17aca..5955d373 100644 --- a/_ml-commons-plugin/api/tasks-apis/index.md +++ b/_ml-commons-plugin/api/tasks-apis/index.md @@ -1,15 +1,18 @@ --- layout: default -title: Tasks APIs -parent: ML Commons APIs +title: ML Tasks APIs +parent: ML APIs has_children: true has_toc: false -nav_order: 30 +nav_order: 140 +redirect_from: + - /ml-commons-plugin/api/tasks-apis/ --- -# Tasks APIs +# ML Tasks APIs -ML Commons supports the following Tasks APIs: +OpenSearch supports the following ML Tasks APIs: -- [Get task]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/) -- [Delete task]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/delete-task/) +- [Get ML task]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/) +- [Delete ML task]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/delete-task/) +- [Search ML tasks]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/search-task/) diff --git a/_ml-commons-plugin/api/tasks-apis/search-task.md b/_ml-commons-plugin/api/tasks-apis/search-task.md index 526684a9..71f17a94 100644 --- a/_ml-commons-plugin/api/tasks-apis/search-task.md +++ b/_ml-commons-plugin/api/tasks-apis/search-task.md @@ -1,22 +1,27 @@ --- layout: default -title: Search task -parent: Tasks APIs -grand_parent: ML Commons APIs +title: Search ML tasks +parent: ML Tasks APIs +grand_parent: ML APIs nav_order: 15 --- -# Search for a task +# Search ML Tasks API -Searches tasks based on parameters indicated in the request body. +Searches machine learning (ML) tasks based on parameters indicated in the request body. -## Path and HTTP methods +## Endpoints ```json GET /_plugins/_ml/tasks/_search +POST /_plugins/_ml/tasks/_search ``` -#### Example request: Search for a task in which `function_name` is `KMEANS` +## Request body fields + +The request body accepts the standard [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/) search request fields, such as `query`, `size`, `from`, `sort`, and `_source`. + +## Example request: Search for a task in which `function_name` is `KMEANS` ```json GET /_plugins/_ml/tasks/_search @@ -36,7 +41,7 @@ GET /_plugins/_ml/tasks/_search ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { @@ -68,7 +73,9 @@ GET /_plugins/_ml/tasks/_search "is_async" : true, "function_name" : "KMEANS", "input_type" : "SEARCH_QUERY", - "worker_node" : "jjqFrlW7QWmni1tRnb_7Dg", + "worker_node" : [ + "jjqFrlW7QWmni1tRnb_7Dg" + ], "state" : "COMPLETED", "model_id" : "AAnLJ38BvytMh9aUi-M2", "task_type" : "TRAINING" @@ -87,7 +94,9 @@ GET /_plugins/_ml/tasks/_search "is_async" : true, "function_name" : "KMEANS", "input_type" : "SEARCH_QUERY", - "worker_node" : "A_IiqoloTDK01uZvCjREaA", + "worker_node" : [ + "A_IiqoloTDK01uZvCjREaA" + ], "state" : "COMPLETED", "model_id" : "xARRLX8BydmmU1x6I-CG", "task_type" : "TRAINING" diff --git a/_ml-commons-plugin/api/train-predict/predict-stream.md b/_ml-commons-plugin/api/train-predict/predict-stream.md new file mode 100644 index 00000000..0eaf060c --- /dev/null +++ b/_ml-commons-plugin/api/train-predict/predict-stream.md @@ -0,0 +1,261 @@ +--- +layout: default +title: Predict stream +parent: Model APIs +grand_parent: ML APIs +nav_order: 65 +--- + +# Predict Stream API +**Introduced 3.3** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +The Predict Stream API provides the same functionality as the [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) but returns responses in a streaming format, delivering data in chunks as it becomes available. This streaming approach is particularly beneficial for large language model interactions with lengthy responses, allowing you to see partial results immediately rather than waiting for the complete response. + +Alternatively, you can stream predictions over gRPC. For more information, see [gRPC Predict Model Stream API]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/predict-model-stream/). +{: .note} + +This API supports the following remote model types: +- [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) +- [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +## Endpoint + +```json +POST /_plugins/_ml/models/{model_id}/_predict/stream +``` + +## Prerequisites + +Before using this API, ensure that you have fulfilled the following prerequisites. + +### Set up your cluster + +Follow these steps to set up your cluster. + +#### Step 1: Install the required plugins + +The Predict Stream API depends on the following plugins, which are included in the OpenSearch distribution but must be explicitly installed as follows: + +```bash +bin/opensearch-plugin install transport-reactor-netty4 +bin/opensearch-plugin install arrow-base +bin/opensearch-plugin install arrow-flight-rpc +``` + +For more information, see [Managing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/). + +#### Step 2: Configure OpenSearch settings + +Add these settings to your `opensearch.yml` file or Docker Compose configuration: + +```yaml +opensearch.experimental.feature.transport.stream.enabled: true + +# Choose one based on your security settings +http.type: reactor-netty4 # security disabled +http.type: reactor-netty4-secure # security enabled + +# Multi-node cluster settings (if applicable) +# Use network.host IP for opensearch.yml or node name for Docker +arrow.flight.publish_host: <ip> +arrow.flight.bind_host: <ip> + +# Security-enabled cluster settings (if applicable) +transport.stream.type.default: FLIGHT-SECURE +flight.ssl.enable: true +transport.ssl.enforce_hostname_verification: false +``` +{% include copy.html %} + +If you're using the security demo certificates, change `plugins.security.ssl.transport.enforce_hostname_verification: false` to `transport.ssl.enforce_hostname_verification: false` in your `opensearch.yml` file. +{: .note} + +For more information about enabling experimental features, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). + +#### Step 3: Configure JVM options + +Add these settings to your `jvm.options` file: + +```yaml +-Dio.netty.allocator.numDirectArenas=1 +-Dio.netty.noUnsafe=false +-Dio.netty.tryUnsafe=true +-Dio.netty.tryReflectionSetAccessible=true +--add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED +``` +{% include copy.html %} + +### Configure the necessary APIs + +Configure the API using the following steps. + +#### Step 1: Enable the streaming feature flag + +To enable the streaming feature flag, update the cluster settings as follows: + +```json +PUT _cluster/settings +{ + "persistent" : { + "plugins.ml_commons.stream_enabled": true + } +} +``` +{% include copy-curl.html %} + +#### Step 2: Register a compatible externally hosted model + +To register an OpenAI Chat Completion model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "OpenAI gpt-4o-mini", + "function_name": "remote", + "description": "OpenAI model", + "connector": { + "name": "OpenAI Chat Connector", + "description": "The connector to OpenAI model service for gpt-4o-mini", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-4o-mini" + }, + "credential": { + "openAI_key": "<your_api_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} }", + "response_filter": "$.choices[0].delta.content" + } + ] + } +} +``` +{% include copy-curl.html %} + +To register an Amazon Bedrock Converse Stream model, send the following request: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Amazon Bedrock Converse Stream model", + "function_name": "remote", + "description": "Amazon Bedrock Claude model", + "connector": { + "name": "Amazon Bedrock Converse", + "description": "The connector to Amazon Bedrock Converse", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<your_aws_access_key>", + "secret_key": "<your_aws_secret_key>", + "session_token": "<your_aws_session_token>" + }, + "parameters": { + "region": "<your_aws_region>", + "service_name": "bedrock", + "response_filter": "$.output.message.content[0].text", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.inputs}\"}]}]}" + } + ] + } +} +``` +{% include copy-curl.html %} + +## Example request + +To use the Predict Stream API, you must include the `_llm_interface` parameter that corresponds to your model type: +- OpenAI Chat Completion: `openai/v1/chat/completions` +- Amazon Bedrock Converse Stream: `bedrock/converse/claude` + +For OpenAI Chat Completion, send the following request: + +```json +POST /_plugins/_ml/models/{model_id}/_predict/stream +{ + "parameters": { + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Can you summarize Prince Hamlet of William Shakespeare in around 1000 words?" + } + ], + "_llm_interface": "openai/v1/chat/completions" + } +} +``` +{% include copy-curl.html %} + +For Amazon Bedrock Converse Stream, send the following request: + +```json +POST /_plugins/_ml/models/{model_id}/_predict/stream +{ + "parameters": { + "inputs": "Can you summarize Prince Hamlet of William Shakespeare in around 1000 words?", + "_llm_interface": "bedrock/converse/claude" + } +} +``` +{% include copy-curl.html %} + +## Example response + +The streaming format uses Server-Sent Events (SSE), with each chunk containing a portion of the model's response, and an `is_last` flag to indicate completion. + +```json +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"Sure","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"!","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"Ham","is_last":false}}]}]} + +... + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":" psyche","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":".","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"","is_last":true}}]}]} +``` + +## Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- |:------------------------------------------------------------------------------------------------------------| +| `inference_results` | Array | Contains the streaming response data returned by the model. | +| `inference_results.output` | Array | Contains output objects for each inference result. | +| `inference_results.output.name` | String | The name of the output field (typically, `response`). | +| `inference_results.output.dataAsMap` | Object | Contains the response content and metadata. | +| `inference_results.output.dataAsMap.content` | String | The text content chunk from the model's response. | +| `inference_results.output.dataAsMap.is_last` | Boolean | Indicates whether this is the final chunk in the stream: `true` for the last chunk, `false` if there are more chunks. | \ No newline at end of file diff --git a/_ml-commons-plugin/api/train-predict/predict.md b/_ml-commons-plugin/api/train-predict/predict.md index 299c9571..f454703d 100644 --- a/_ml-commons-plugin/api/train-predict/predict.md +++ b/_ml-commons-plugin/api/train-predict/predict.md @@ -1,27 +1,69 @@ --- layout: default title: Predict -parent: Train and Predict APIs -grand_parent: ML Commons APIs -nav_order: 20 +parent: Model APIs +grand_parent: ML APIs +nav_order: 60 --- -# Predict +# Predict API -ML Commons can predict new data with your trained model either from indexed data or a data frame. To use the Predict API, the `model_id` is required. +Sends input to a model and returns the model's output (inference). The request body fields depend on the model type: + +- Models trained using the [Train API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/train/) predict from indexed data or from a data frame provided in the request. +- Local models, such as text embedding, sparse encoding, text similarity, and question answering models, accept text input. +- Externally hosted models accept the input fields defined in their connector. For information about user access for this API, see [Model access control considerations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/index/#model-access-control-considerations). -## Path and HTTP methods +## Endpoints ```json -POST /_plugins/_ml/_predict/<algorithm_name>/<model_id> +POST /_plugins/_ml/_predict/{algorithm_name}/{model_id} +POST /_plugins/_ml/models/{model_id}/_predict ``` -#### Example request +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `model_id` | String | The model ID. Required. | +| `algorithm_name` | String | The algorithm that determines how OpenSearch reads the request body. Not case sensitive. Valid values are the following:<br>- `remote`: Reads the `parameters` object. Default for externally hosted models.<br>- `text_embedding`, `sparse_encoding`, or `sparse_tokenize`: Reads the `text_docs` array.<br>- `text_similarity`: Reads the `query_text` and `text_docs` fields.<br>- `question_answering`: Reads the `question` and `context` fields.<br>- For models trained using the Train API, the algorithm used to train the model, such as `kmeans`. For a list of algorithms, see [Supported algorithms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/).<br>If you use the `/_plugins/_ml/models/{model_id}/_predict` endpoint, OpenSearch uses the model's algorithm unless you specify the `algorithm` query parameter. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `algorithm` | String | Used with the `/_plugins/_ml/models/{model_id}/_predict` endpoint. The algorithm used to parse the request body. Overrides the model's algorithm. Equivalent to `{algorithm_name}` in the `/_plugins/_ml/_predict/{algorithm_name}/{model_id}` endpoint and accepts the same values. For example, set `algorithm` to `text_embedding` to test an externally hosted embedding model using `text_docs` input, the format that the `text_embedding` ingest processor sends. For more information, see [Providing input as text documents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-text-documents). | + +## Request body fields + +The following table lists the available request fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`parameters` | Object | Optional | Model-specific parameters for prediction. For externally hosted models, contains the values that replace the `${parameters.<parameter_name>}` placeholders in the connector's request body. For more information, see [Providing input as parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-parameters). OpenSearch escapes special characters, such as quotation marks and line breaks, in string values before inserting them into the connector templates. OpenSearch inserts values that are valid JSON objects or arrays and values of the parameters listed in `no_escape_params` unchanged. +`parameters.no_escape_params` | String | Optional | For externally hosted models, a comma-separated list of parameter names whose values OpenSearch inserts into the connector templates without escaping special characters. +`parameters.input_processors` | Array | Optional | A list of processors used to transform the input data before sending it to the model. For more information, see [Processor chain]({{site.url}}{{site.baseurl}}/ml-commons-plugin/processor-chain/). +`parameters.output_processors` | Array | Optional | A list of processors used to transform the model's output data. For more information, see [Processor chain]({{site.url}}{{site.baseurl}}/ml-commons-plugin/processor-chain/). +`input_index` | Array | Optional | For models trained using the [Train API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/train/), a list of indexes containing the data to predict. +`input_query` | Object | Optional | For models trained using the Train API, a search query that selects the documents from `input_index`. +`input_data` | Object | Optional | For models trained using the Train API, the data to predict, provided directly as a data frame containing `column_metas` and `rows`. +`text_docs` | Array | Optional | For text embedding, sparse encoding, and text similarity models, specifies a list of input strings. To send `text_docs` to an externally hosted model, set the algorithm to `text_embedding` using the `algorithm` query parameter or the `{algorithm_name}` path parameter. The connector's preprocessing function converts the strings into the parameters that the connector requires. If the connector doesn't define a preprocessing function, OpenSearch uses `connector.pre_process.default.embedding`, which converts the strings into the `input` parameter. For more information, see [Providing input as text documents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-text-documents). +`query_text` | String | Optional | For text similarity models, the query text compared with each entry in `text_docs`. +`return_number` | Boolean | Optional | For local text embedding models, whether to return the embedding as numbers. Default is `true`. +`target_response` | Array | Optional | For local text embedding models, a list of model output names to return, for example, `sentence_embedding`. +`question` | String | Optional | For question answering models, the question to answer. +`context` | String | Optional | For question answering models, the text containing the answer. + +## Example request ```json -POST /_plugins/_ml/_predict/kmeans/<model-id> +POST /_plugins/_ml/_predict/kmeans/{model-id} { "input_query": { "_source": ["petal_length_in_cm", "petal_width_in_cm"], @@ -34,7 +76,7 @@ POST /_plugins/_ml/_predict/kmeans/<model-id> ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { diff --git a/_ml-commons-plugin/api/train-predict/train-and-predict.md b/_ml-commons-plugin/api/train-predict/train-and-predict.md index 1df0e5e3..d665500a 100644 --- a/_ml-commons-plugin/api/train-predict/train-and-predict.md +++ b/_ml-commons-plugin/api/train-predict/train-and-predict.md @@ -1,20 +1,48 @@ --- layout: default title: Train and predict -parent: Train and Predict APIs -grand_parent: ML Commons APIs -nav_order: 10 +parent: Model APIs +grand_parent: ML APIs +nav_order: 75 --- -## Train and predict +# Train and Predict API -Use to train and then immediately predict against the same training dataset. Can only be used with unsupervised learning models and the following algorithms: +Use to train and then immediately predict against the same training dataset. Can only be used with unsupervised learning models. The following table lists the supported algorithms and the value to specify in the `algorithm` path parameter. -- `BATCH_RCF` -- `FIT_RCF` -- `k-means` +| Algorithm | `algorithm` value | +| :--- | :--- | +| [Batch RCF]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/#batch-rcf) | `batch_rcf` | +| [Fixed in time (FIT) RCF]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/#fit-rcf) | `fit_rcf` | +| [k-means]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/#k-means) | `kmeans` | +| [RCF Summarize]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/#rcf-summarize) | `rcf_summarize` | -#### Example request: Train and predict with indexed data +## Endpoints + +```json +POST /_plugins/_ml/_train_predict/{algorithm} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `algorithm` | String | The name of the algorithm, for example, `kmeans`. The name is not case sensitive. Required. | + +## Request body fields + +The following table lists the available request body fields. Provide the data using either `input_index` and `input_query` or `input_data`. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `parameters` | Object | The algorithm hyperparameters. The available parameters depend on the algorithm. For the parameters of each algorithm, see [Supported algorithms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/). Optional. | +| `input_index` | Array | A list of indexes containing the data. | +| `input_query` | Object | A search query that selects the documents from `input_index`. | +| `input_data` | Object | The data provided directly as a data frame, containing `column_metas` and `rows`. | + +## Example request: Train and predict with indexed data ```json POST /_plugins/_ml/_train_predict/kmeans @@ -47,7 +75,7 @@ POST /_plugins/_ml/_train_predict/kmeans ``` {% include copy-curl.html %} -#### Example request: Train and predict with data directly +## Example request: Train and predict with data directly ```json POST /_plugins/_ml/_train_predict/kmeans @@ -147,7 +175,7 @@ POST /_plugins/_ml/_train_predict/kmeans ``` {% include copy-curl.html %} -#### Example response +## Example response ```json { diff --git a/_ml-commons-plugin/api/train-predict/train.md b/_ml-commons-plugin/api/train-predict/train.md index 8de48619..198c25fd 100644 --- a/_ml-commons-plugin/api/train-predict/train.md +++ b/_ml-commons-plugin/api/train-predict/train.md @@ -1,16 +1,49 @@ --- layout: default title: Train -parent: Train and Predict APIs -grand_parent: ML Commons APIs -nav_order: 10 +parent: Model APIs +grand_parent: ML APIs +nav_order: 50 --- -# Train +# Train API The train API operation trains a model based on a selected algorithm. Training can occur both synchronously and asynchronously. -#### Example request +## Endpoints + +```json +POST /_plugins/_ml/_train/{algorithm} +``` + +## Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `algorithm` | String | The name of the algorithm to train, for example, `kmeans`. The name is not case sensitive. For a list of algorithms, see [Supported algorithms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/). Required. | + +## Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `async` | Boolean | If `true`, the request runs asynchronously and returns a task ID. If `false`, the request returns a model ID after training completes. Default is `false`. | + +## Request body fields + +The following table lists the available request body fields. Provide the training data using either `input_index` and `input_query` or `input_data`. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `parameters` | Object | The algorithm hyperparameters. The available parameters depend on the algorithm. For the parameters of each algorithm, see [Supported algorithms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/). Optional. | +| `input_index` | Array | A list of indexes containing the training data. | +| `input_query` | Object | A search query that selects the training documents from `input_index`. | +| `input_data` | Object | The training data provided directly as a data frame, containing `column_metas` and `rows`. | + +## Example request The following examples use the k-means algorithm to train index data. @@ -56,7 +89,7 @@ POST /_plugins/_ml/_train/kmeans?async=true ``` {% include copy-curl.html %} -#### Example response +## Example response **Synchronous** diff --git a/_ml-commons-plugin/cluster-settings.md b/_ml-commons-plugin/cluster-settings.md index 5bf1c135..376c249c 100644 --- a/_ml-commons-plugin/cluster-settings.md +++ b/_ml-commons-plugin/cluster-settings.md @@ -2,334 +2,165 @@ layout: default title: ML Commons cluster settings has_children: false -nav_order: 10 +nav_order: 120 --- -# ML Commons cluster settings +# ML cluster settings - -To enhance and customize your OpenSearch cluster for machine learning (ML), you can add and modify several configuration settings for the ML Commons plugin in your 'opensearch.yml' file. +The following settings configure the ML Commons plugin. You can specify them in your `opensearch.yml` file or update them using the [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/). All ML Commons settings on this page are dynamic. To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). ## ML node -By default, ML tasks and models only run on ML nodes. When configured without the `data` node role, ML nodes do not store any shards and instead calculate resource requirements at runtime. To use an ML node, create a node in your `opensearch.yml` file. Give your node a custom name and define the node role as `ml`: +By default, ML tasks and local models run only on ML nodes. When configured without the `data` node role, ML nodes do not store any shards and instead calculate resource requirements at runtime. To use an ML node, create a node in your `opensearch.yml` file. Give your node a custom name and define the node role as `ml`: ```yml node.roles: [ ml ] ``` +{% include copy.html %} -### Setting up a cluster with a dedicated ML node +For an example of a cluster with a dedicated ML node, see the example [Docker Compose file](https://github.com/opensearch-project/ml-commons/blob/main/docs/docker/docker-compose.yml). -To set up a cluster with a dedicated ML node, see the sample [Docker compose file](https://github.com/opensearch-project/ml-commons/blob/main/docs/docker/docker-compose.yml). +## Node selection settings -## Run tasks and models on ML nodes only +ML Commons supports the following settings for selecting the nodes on which ML tasks and models run: -If `true`, ML Commons tasks and models run ML tasks on ML nodes only. If `false`, tasks and models run on ML nodes first. If no ML nodes exist, tasks and models run on data nodes. +- `plugins.ml_commons.only_run_on_ml_node` (Dynamic, Boolean): When `true`, local models run only on ML nodes. When `false`, local models run on nodes whose roles are listed in `plugins.ml_commons.task_dispatcher.eligible_node_role.local_model`. To test models on a data node, set it to `false`. Default is `true`. -We suggest running ML workloads on a dedicated ML node rather than on data nodes. Starting with OpenSearch 2.5, ML tasks run on ML nodes only by default. To test models on a data node, set `plugins.ml_commons.only_run_on_ml_node` to `false`. +- `plugins.ml_commons.task_dispatcher.eligible_node_role.local_model` (Dynamic, list): The node roles on which local models can run. This setting applies only when `plugins.ml_commons.only_run_on_ml_node` is `false`. Default is `["data", "ml"]`. -We recommend setting `plugins.ml_commons.only_run_on_ml_node` to `true` on production clusters. +- `plugins.ml_commons.task_dispatcher.eligible_node_role.remote_model` (Dynamic, list): The node roles on which externally hosted models can run. For example, set it to `["ml"]` to run externally hosted models only on ML nodes. Default is `["data", "ml"]`. + +- `plugins.ml_commons.task_dispatch_policy` (Dynamic, string): The policy for dispatching ML tasks to ML nodes. Valid values are `round_robin`, which dispatches tasks using round-robin routing, and `least_load`, which collects runtime information, such as JVM heap memory usage and running tasks, from all ML nodes and dispatches tasks to the node with the lowest load. Default is `round_robin`. + +- `plugins.ml_commons.exclude_nodes._name` (Dynamic, string): A node name or a comma-separated list of node names, such as `node1, node2`, on which ML tasks don't run. + +- `plugins.ml_commons.allow_custom_deployment_plan` (Dynamic, Boolean): When `true`, users can deploy models to specific ML nodes according to their permissions. Default is `false`. + +We recommend setting `plugins.ml_commons.only_run_on_ml_node` to `true` on production clusters. {: .tip} +## Task and model limit settings -### Setting +ML Commons supports the following settings for limiting ML tasks and models: -``` -plugins.ml_commons.only_run_on_ml_node: true -``` +- `plugins.ml_commons.max_ml_task_per_node` (Dynamic, integer): The maximum number of ML tasks that can run on each ML node. When set to `0`, no ML tasks run on any node. Valid values are 0--10,000. Default is `10`. -### Values +- `plugins.ml_commons.max_model_on_node` (Dynamic, integer): The maximum number of models that can be deployed to each ML node. When set to `0`, no models can be deployed to any node. Valid values are 0--10,000. Default is `10`. -- Default value: `true` -- Value range: `true` or `false` +- `plugins.ml_commons.max_register_model_tasks_per_node` (Dynamic, integer): The maximum number of model registration tasks that can run in parallel on one node. When set to `0`, no models can be registered on any node. Valid values are 0--10. Default is `10`. -## Dispatch tasks to ML node +- `plugins.ml_commons.max_deploy_model_tasks_per_node` (Dynamic, integer): The maximum number of model deployment tasks that can run in parallel on one node. When set to `0`, no models can be deployed to any node. Valid values are 0--10. Default is `10`. -`round_robin` dispatches ML tasks to ML nodes using round robin routing. `least_load` gathers runtime information from all ML nodes, like JVM heap memory usage and running tasks, and then dispatches the tasks to the ML node with the lowest load. +- `plugins.ml_commons.ml_task_timeout_in_seconds` (Dynamic, integer): The amount of time, in seconds, that an ML task can run. After the timeout, the task fails. Valid values are 1--86,400. Default is `600`. +- `plugins.ml_commons.sync_up_job_interval_in_seconds` (Dynamic, integer): The interval, in seconds, at which ML Commons runs a job that syncs newly deployed or undeployed models on each node. This job keeps the runtime information returned by the [Profile API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/profile/) up to date. When set to `0`, ML Commons stops the sync job. Valid values are 0--86,400. Default is `10`. -### Setting +- `plugins.ml_commons.monitoring_request_count` (Dynamic, long): The number of prediction requests monitored on each node. When set to `0`, OpenSearch clears all monitored prediction requests from the cache and stops monitoring new prediction requests. Valid values are 0--10,000,000. Default is `100`. -``` -plugins.ml_commons.task_dispatch_policy: round_robin -``` +- `plugins.ml_commons.max_batch_inference_tasks` (Dynamic, integer): The maximum number of [batch inference]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/batch-predict/) tasks in the cluster that can be in the `CREATED` or `RUNNING` state. When this limit is reached, OpenSearch rejects new batch inference requests. When set to `0`, no batch inference tasks can run. Valid values are 0--10,000. Default is `100`. +- `plugins.ml_commons.max_json_size` (Dynamic, integer): The maximum size, in bytes, of a JSON string that ML Commons parses, such as a response from an externally hosted model. If a JSON string exceeds this size, the request fails. To remove the limit, set this value to `-1`. Default is `100000000` (100 MB). -### Values +## Model registration settings -- Default value: `round_robin` -- Value range: `round_robin` or `least_load` +By default, ML Commons allows registration only of [pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/) from the OpenSearch model repository. ML Commons supports the following settings for registering models from other sources: -## Set number of ML tasks per node +- `plugins.ml_commons.allow_registering_model_via_url` (Dynamic, Boolean): When `true`, users can register models using a URL. Default is `false`. -Sets the number of ML tasks that can run on each ML node. When set to `0`, no ML tasks run on any nodes. +- `plugins.ml_commons.allow_registering_model_via_local_file` (Dynamic, Boolean): When `true`, users can register models using a local file. Default is `false`. -### Setting +- `plugins.ml_commons.trusted_url_regex` (Dynamic, string): A Java regular expression that a model URL must match for the model to be registered. The default value allows registering a model file from any HTTP, HTTPS, FTP, or local file URL. Default is `"^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"`. -``` -plugins.ml_commons.max_ml_task_per_node: 10 -``` +When registering a model from a URL, make sure the source is trusted. Loading models from untrusted sources can pose security risks. For more information, see [PyTorch security guidelines for untrusted models](https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models). +{: .warning} -### Values - -- Default value: `10` -- Value range: [0, 10,000] - -## Set number of ML models per node - -Sets the number of ML models that can be deployed to each ML node. When set to `0`, no ML models can deploy on any node. - -### Setting - -``` -plugins.ml_commons.max_model_on_node: 10 -``` - -### Values - -- Default value: `10` -- Value range: [0, 10,000] - -## Set sync job intervals - -When returning runtime information with the [Profile API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/profile/), ML Commons will run a regular job to sync newly deployed or undeployed models on each node. When set to `0`, ML Commons immediately stops sync-up jobs. - - -### Setting - -``` -plugins.ml_commons.sync_up_job_interval_in_seconds: 3 -``` - -### Values - -- Default value: `3` -- Value range: [0, 86,400] - -## Predict monitoring requests - -Controls how many predict requests are monitored on one node. If set to `0`, OpenSearch clears all monitoring predict requests in cache and does not monitor for new predict requests. - -### Setting - -``` -plugins.ml_commons.monitoring_request_count: 100 -``` - -### Value range - -- Default value: `100` -- Value range: [0, 10,000,000] - -## Register model tasks per node - -Controls how many register model tasks can run in parallel on one node. If set to `0`, you cannot run register model tasks on any node. - -### Setting - -``` -plugins.ml_commons.max_register_model_tasks_per_node: 10 -``` - - -### Values - -- Default value: `10` -- Value range: [0, 10] - - -## Deploy model tasks per node - -Controls how many deploy model tasks can run in parallel on one node. If set to 0, you cannot deploy models to any node. - -### Setting - -``` -plugins.ml_commons.max_deploy_model_tasks_per_node: 10 -``` - -### Values - -- Default value: `10` -- Value range: [0, 10] - -## Register models using URLs - -This setting gives you the ability to register models using a URL. By default, ML Commons only allows registration of [pretrained]({{site.url}}{{site.baseurl}}//ml-commons-plugin/pretrained-models/) models from the OpenSearch model repository. - -### Setting - -``` -plugins.ml_commons.allow_registering_model_via_url: false -``` - -### Values - -- Default value: false -- Valid values: `false`, `true` - -## Register models using local files - -This setting gives you the ability to register a model using a local file. By default, ML Commons only allows registration of [pretrained]({{site.url}}{{site.baseurl}}//ml-commons-plugin/pretrained-models/) models from the OpenSearch model repository. - -### Setting - -``` -plugins.ml_commons.allow_registering_model_via_local_file: false -``` - -### Values - -- Default value: false -- Valid values: `false`, `true` - -## Add trusted URL - -The default value allows you to register a model file from any http/https/ftp/local file. You can change this value to restrict trusted model URLs. - - -### Setting - -The default URL value for this trusted URL setting is not secure. For security, use you own regex string to the trusted repository that contains your models, for example `https://github.com/opensearch-project/ml-commons/blob/2.x/ml-algorithms/src/test/resources/org/opensearch/ml/engine/algorithms/text_embedding/*`. +The default value of `plugins.ml_commons.trusted_url_regex` is not secure. For security, set it to a regular expression that matches only the trusted repository containing your models, for example, `https://github.com/opensearch-project/ml-commons/blob/main/ml-algorithms/src/test/resources/org/opensearch/ml/engine/algorithms/text_embedding/*`. {: .warning } +## Connector endpoint settings -``` -plugins.ml_commons.trusted_url_regex: <model-repository-url> -``` +ML Commons supports the following settings for controlling the endpoints to which connectors send requests. These settings apply to all connector requests, including streaming prediction requests: -### Values +- `plugins.ml_commons.trusted_connector_endpoints_regex` (Dynamic, list): A list of Java regular expressions. OpenSearch accepts a connector only if its endpoint URL matches one of these expressions. The value you provide replaces the entire default list. For the default list, see [Adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#adding-trusted-endpoints). -- Default value: `"^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"` -- Value range: Java regular expression (regex) string +- `plugins.ml_commons.connector.private_ip_enabled` (Dynamic, Boolean): When `true`, connectors can send requests to hosts that resolve to a private IP address. When `false`, OpenSearch rejects prediction requests for models whose connector endpoint resolves to such an address. The following addresses are private: the RFC 1918 ranges (`10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`), loopback addresses (`127.0.0.0/8` and `::1`), the unspecified addresses (`0.0.0.0` and `::`), IPv6 unique-local (`fc00::/7`) and site-local (`fec0::/10`) addresses, the local-use NAT64 range (`64:ff9b:1::/48`), and any IPv6 address that carries one of these IPv4 ranges in an IPv4-mapped (`::ffff:a.b.c.d`), IPv4-compatible (`::a.b.c.d`), or NAT64 (`64:ff9b::/96` or `64:ff9b:1::/48`) form, including when a DNS AAAA record returns such an address. Link-local addresses (`169.254.0.0/16` and `fe80::/10`) and cloud instance metadata addresses (`fd00:ec2::/32`, `fd20:ce::254`, and `100.100.100.200`) are always refused, regardless of this setting, including when one of the IPv4 addresses in this list is carried in an IPv4-mapped, IPv4-compatible, or NAT64 form (for example, `::ffff:169.254.169.254`). To apply a change to a deployed model, redeploy the model. Default is `false`. -## Assign task timeout +- `plugins.ml_commons.trusted_connector_private_endpoints_regex` (Dynamic, list): A list of Java regular expressions that limits the private endpoints to which connectors can send requests. This setting applies only when `plugins.ml_commons.connector.private_ip_enabled` is `true`. If the list contains expressions, a connector URL whose host resolves to a private IP address must match one of them. If the list is empty, connectors can send requests to any private endpoint. To apply a change to a deployed model, redeploy the model. Default is `[]`. -Assigns how long in seconds an ML task will live. After the timeout, the task will fail. +- `plugins.ml_commons.connector.restricted_ip_patterns` (Static, list): A list of Java regular expressions, each of which must match a whole IP address. OpenSearch matches them against every IP address to which a connector host resolves, in the format Java uses to print the address (for example, `10.0.0.1` or `fd00:ec2:0:0:0:0:0:254`), and against the dotted-decimal format of an IPv4 address carried in an IPv6 address. OpenSearch refuses requests to an address that matches any of the expressions, regardless of the `plugins.ml_commons.connector.private_ip_enabled` setting. Default is `[]`. -### Setting +## Circuit breaker settings -``` -plugins.ml_commons.ml_task_timeout_in_seconds: 600 -``` +Before running an ML task, ML Commons checks memory and disk usage. If usage exceeds a threshold, OpenSearch triggers a circuit breaker, throws an exception, and doesn't run the task. ML Commons supports the following circuit breaker settings: -### Values +- `plugins.ml_commons.native_memory_threshold` (Dynamic, integer): The maximum native memory usage, as a percentage of the total system memory, at which ML tasks can run. This circuit breaker prevents out-of-memory errors when too many models are loaded. When set to `0`, no ML tasks run. When set to `100`, the circuit breaker is disabled. Valid values are 0--100. Default is `90`. -- Default value: 600 -- Value range: [1, 86,400] +- `plugins.ml_commons.jvm_heap_memory_threshold` (Dynamic, integer): The maximum JVM heap memory usage, as a percentage of the total JVM heap, at which ML tasks can run. When set to `0`, no ML tasks run. When set to `100`, the circuit breaker is disabled. Valid values are 0--100. Default is `85`. -## Set native memory threshold +- `plugins.ml_commons.disk_free_space_threshold` (Dynamic, byte size): The minimum amount of free disk space required to run an ML task. If the free disk space falls below this value, the circuit breaker is triggered. To disable the circuit breaker, set this value to `-1`. Default is `5gb`. -Sets a circuit breaker that checks all system memory usage before running an ML task. If the native memory exceeds the threshold, OpenSearch throws an exception and stops running any ML task. +## Model deployment settings -Values are based on the percentage of memory available. When set to `0`, no ML tasks will run. When set to `100`, the circuit breaker closes and no threshold exists. +ML Commons supports the following settings for automatically deploying and redeploying models: -Starting with OpenSearch 2.5, ML Commons runs a native memory circuit breaker to avoid an out-of-memory error when loading too many models. By default, the native memory threshold is 90%. If memory usage exceeds the threshold, ML Commons returns an error. For testing purposes, you can disable the circuit breaker by setting `plugins.ml_commons.native_memory_threshold` to 100. +- `plugins.ml_commons.model_auto_deploy.enable` (Dynamic, Boolean): When `true`, OpenSearch automatically deploys an externally hosted model when it receives a prediction request for that model and the model is not yet deployed. Default is `true`. -### Setting +- `plugins.ml_commons.model_auto_redeploy.enable` (Dynamic, Boolean): When `true`, OpenSearch automatically redeploys deployed or partially deployed models after a cluster failure. If all ML nodes in a cluster fail, the model enters the `DEPLOY_FAILED` state and must be deployed manually. Default is `true`. -``` -plugins.ml_commons.native_memory_threshold: 90 -``` +- `plugins.ml_commons.model_auto_redeploy.lifetime_retry_times` (Dynamic, integer): The maximum number of times that OpenSearch attempts to redeploy a deployed or partially deployed model when ML nodes in a cluster fail or new ML nodes join the cluster. When set to `0` or a negative value, OpenSearch doesn't automatically redeploy models. Default is `3`. -### Values +- `plugins.ml_commons.model_auto_redeploy_success_ratio` (Dynamic, float): The minimum fraction of available ML nodes on which a model must be redeployed for automatic redeployment to succeed. For example, if the ratio is `0.7` and the model is redeployed on 70% of the available ML nodes, the redeployment succeeds. If the model is redeployed on fewer than 70% of the available ML nodes, OpenSearch retries the redeployment until it succeeds or reaches the `plugins.ml_commons.model_auto_redeploy.lifetime_retry_times` limit. Valid values are 0--1. Default is `0.8`. -- Default value: 90 -- Value range: [0, 100] +## Dynamic batching memory settings -## Allow custom deployment plans +All models on a node share the memory available for [dynamic batching]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/batching-requests/#dynamically-batching-small-prediction-requests). When this memory is exhausted, OpenSearch rejects new queue entries. Retry rejected requests using backoff, or adjust the memory settings for the workload. ML Commons supports the following settings for controlling the amount of this memory: -When enabled, this setting grants users the ability to deploy models to specific ML nodes according to that user's permissions. +- `plugins.ml_commons.dynamic_batching.memory.fraction` (Dynamic, double): The fraction of the maximum JVM heap used to calculate the amount of memory available for dynamic batching on each node. The calculated value is bounded by `plugins.ml_commons.dynamic_batching.memory.min` and `plugins.ml_commons.dynamic_batching.memory.max`. Valid values are 0.0--0.1. Default is `0.01`. -### Setting +- `plugins.ml_commons.dynamic_batching.memory.min` (Dynamic, byte size): The minimum amount of memory available for dynamic batching on each node. Default is `64mb`. -``` -plugins.ml_commons.allow_custom_deployment_plan: false -``` +- `plugins.ml_commons.dynamic_batching.memory.max` (Dynamic, byte size): The maximum amount of memory available for dynamic batching on each node. This value must be greater than or equal to `plugins.ml_commons.dynamic_batching.memory.min`. Default is `512mb`. -### Values +## Feature settings -- Default value: false -- Valid values: `false`, `true` +ML Commons supports the following settings for enabling and disabling features: -## Enable auto redeploy +- `plugins.ml_commons.remote_inference.enabled` (Dynamic, Boolean): When `false`, users can't create connectors or register, deploy, or run predictions using externally hosted models. Default is `true`. -This setting automatically redeploys deployed or partially deployed models upon cluster failure. If all ML nodes inside a cluster crash, the model switches to the `DEPLOYED_FAILED` state, and the model must be deployed manually. +- `plugins.ml_commons.local_model.enabled` (Dynamic, Boolean): When `false`, users can't register, deploy, or run predictions using local models. Default is `true`. -### Setting +- `plugins.ml_commons.offline_batch_inference_enabled` (Dynamic, Boolean): When `false`, users can't run [batch inference]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/batch-predict/) or get or cancel batch inference tasks. Default is `true`. -``` -plugins.ml_commons.model_auto_redeploy.enable: false -``` +- `plugins.ml_commons.controller_enabled` (Dynamic, Boolean): When `false`, users can't create, update, get, or delete model controllers using the [Controller APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/controller-apis/index/). Default is `true`. -### Values +- `plugins.ml_commons.model_access_control_enabled` (Dynamic, Boolean): When `true` and the Security plugin is enabled, admins can control access to models using model groups. For more information, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). Default is `false`. -- Default value: false -- Valid values: `false`, `true` +- `plugins.ml_commons.connector_access_control_enabled` (Dynamic, Boolean): When `true`, admins can control access to the Connector APIs using `backend_roles`. Default is `false`. -## Set retires for auto redeploy +- `plugins.ml_commons.connector.vertexai_enabled` (Dynamic, Boolean): When `true`, users can create connectors that use the `google_cloud` protocol. For more information, see [Google Cloud authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/google-cloud/). Default is `false`. -This setting sets the limit for the number of times a deployed or partially deployed model will try and redeploy when ML nodes in a cluster fail or new ML nodes join the cluster. +- `plugins.ml_commons.connector.mutual_tls_enabled` (Dynamic, Boolean): When `true`, users can create connectors that set `mutual_tls_enabled` to `true` in `client_config` to authenticate using a client certificate. For more information, see [Client certificate authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/#client-certificate-authentication). Default is `false`. -### Setting +- `plugins.ml_commons.mcp_connector_enabled` (Dynamic, Boolean): When `true`, users can create connectors that use the `mcp_sse` or `mcp_streamable_http` protocol and register agents that use MCP connectors. For more information, see [Connecting to an external MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/mcp-connector/). Default is `false`. -``` -plugins.ml_commons.model_auto_redeploy.lifetime_retry_times: 3 -``` +- `plugins.ml_commons.safe_delete_model` (Dynamic, Boolean): When `true`, OpenSearch checks for downstream dependencies before deleting a model. If the model is in use by agents, search pipelines, ingest pipelines, or other downstream tasks, OpenSearch returns an error and doesn't delete the model. Default is `false`. -### Values +- `plugins.ml_commons.enable_inhouse_python_model` (Dynamic, Boolean): When `true`, users can run Python-based models supported by OpenSearch, such as [metrics correlation]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/#metrics-correlation). Default is `false`. -- Default value: 3 -- Value range: [0, 100] +- `plugins.ml_commons.agent_framework_enabled` (Dynamic, Boolean): When `true`, enables the agent framework, including agents and tools, and allows users to register, execute, delete, retrieve, and search agents. Default is `true`. -## Set auto redeploy success ratio +- `plugins.ml_commons.unified_agent_api_enabled` (Dynamic, Boolean): When `false`, users can't register agents using the [unified registration method]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/#unified-registration-method) or execute agents using the standardized `input` field. Default is `true`. -This setting sets the ratio of success for the auto-redeployment of a model based on the available ML nodes in a cluster. For example, if ML nodes crash inside a cluster, the auto redeploy protocol adds another node or retires a crashed node. If the ratio is `0.7` and 70% of all ML nodes successfully redeploy the model on auto-redeploy activation, the redeployment is a success. If the model redeploys on fewer than 70% of available ML nodes, the auto-redeploy retries until the redeployment succeeds or OpenSearch reaches [the maximum number of retries](#set-retires-for-auto-redeploy). - -### Setting - -``` -plugins.ml_commons.model_auto_redeploy_success_ratio: 0.8 -``` - -### Values - -- Default value: 0.8 -- Value range: [0, 1] - -## Run Python-based models - -When set to `true`, this setting enables the ability to run Python-based models supported by OpenSearch, such as [Metrics correlation]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/#metrics-correlation). - -### Setting - -``` -plugins.ml_commons.enable_inhouse_python_model: false -``` - -### Values - -- Default value: false -- Valid values: `false`, `true` - -## Enable access control for connectors - -When set to `true`, the setting allows admins to control access and permissions to the connector API using `backend_roles`. - -### Setting - -``` -plugins.ml_commons.connector_access_control_enabled: true -``` - -### Values - -- Default value: false -- Valid values: `false`, `true` +- `plugins.ml_commons.execute_tools_enabled` (Dynamic, Boolean): When `false`, users can't run tools using the [Execute Tool API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/execute-tool/). Default is `true`. +- `plugins.ml_commons.mcp_server_enabled` (Dynamic, Boolean): When `true`, enables the [MCP server APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/index/), which allow agents to connect to OpenSearch using Model Context Protocol (MCP) and use its tools. Default is `false`. +- `plugins.ml_commons.memory_feature_enabled` (Dynamic, Boolean): When `true`, enables conversational memory, which stores all messages from a conversation for conversational search. Default is `true`. +- `plugins.ml_commons.agentic_memory_enabled` (Dynamic, Boolean): When `true`, enables [agentic memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/), which provides memory management for AI agents, including session memory, working memory, long-term memory, and memory history organized by namespace. Default is `true`. +- `plugins.ml_commons.agentic_search_template_enabled` (Dynamic, Boolean): When `true`, enables the agentic search template APIs and the `SearchTemplateFillTool`. For more information, see [Filling search templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/index/). The APIs and the tool aren't available when multi-tenancy is enabled, regardless of this setting. Default is `false`. +- `plugins.ml_commons.rag_pipeline_feature_enabled` (Dynamic, Boolean): When `true`, enables the search processors for retrieval-augmented generation (RAG). RAG enhances query results by generating responses using relevant information from memory and previous conversations. Default is `true`. diff --git a/_ml-commons-plugin/context-management.md b/_ml-commons-plugin/context-management.md new file mode 100644 index 00000000..26517199 --- /dev/null +++ b/_ml-commons-plugin/context-management.md @@ -0,0 +1,277 @@ +--- +layout: default +title: Context management +parent: Memory and context +nav_order: 20 +--- + +# Context management +**Introduced 3.5** +{: .label .label-purple } + +Context management enables OpenSearch agents to dynamically optimize their context before sending requests to large language models (LLMs). This flexible feature helps prevent context window overflow, reduces token usage, and enables long-running agents by intelligently managing conversation history, tool interactions, and other contextual information. + +Using context management, you can build AI agents that can: + +- Automatically truncate a long tool output when approaching token limits. +- Summarize lengthy tool interactions to preserve essential information. +- Apply sliding window approaches to maintain recent context. +- Implement custom context optimization strategies based on specific use cases. +- Hook into different stages of agent execution for context transformation. + +Context management uses a hook-based system that allows pluggable context managers to inspect and transform agent context at specific execution points. You can experiment with different configurations and combinations to find the optimal setup for your specific use case. + +## Configuring context management + +Context management organizes teams of _context managers_ that work together to optimize agent context at specific execution points during the agent lifecycle. The system is highly configurable, allowing you to tailor its behavior to your specific requirements. + +Each context management can be configured with the following components: + +- **Name**: Unique identifier for the context management. +- **Description**: Human-readable description of the context management's purpose. +- **Hooks**: Different execution points where context managers operate. +- **Context managers**: Individual components that perform specific context transformations. +- **Activation rules**: Conditions that determine when context managers should execute. + +You can mix and match different context managers, adjust their parameters, and experiment with various activation thresholds to achieve optimal performance for your use case. + +For example, to create a context management named `token-aware-truncation` with a `ToolsOutputTruncateManager` and a `SlidingWindowManager`, send the following request: + +```json +POST /_plugins/_ml/context_management/token-aware-truncation +{ + "description": "Context management that truncates tool outputs longer than 100,000 characters and applies sliding window to keep last 6 messages when tokens exceed 200,000", + "hooks": { + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 100000 + } + } + ], + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "tokens_exceed": 200000 + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +## The hook system + +Context management uses a hook-based architecture that allows teams of context managers to execute at specific points during agent execution. The supported hooks are: + +- `PRE_LLM` -- Runs before sending requests to the LLM. +- `POST_TOOL` -- Runs after tool execution completes. + +Hook names are case sensitive and must be uppercase. The Create Context Management API accepts any hook name, but context managers configured under a lowercase name, such as `post_tool`, never run. Inline `context_management` configurations in agent registration requests reject lowercase hook names. +{: .important} + +Context managers registered for each hook are executed in the order in which they are defined in the context management configuration. + +These hooks are supported in OpenSearch [conversational agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/conversational/) and [plan-and-execute agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/plan-execute-reflect/). + +## Activation rules + +Activation rules determine when context managers execute during agent interactions. These rules help you control resource usage and optimize performance by triggering context optimization only when needed. If no activation rules are specified, context managers execute on every interaction at their configured hooks. + +Context managers support the following activation rules, which can be used individually or combined. + +### Message count threshold + +Use `message_count_exceed` to activate a context manager when the conversation history exceeds a specified number of messages: + +```json +{ + "activation": { + "message_count_exceed": 20 + } +} +``` + +This rule is useful for applying context optimization strategies like sliding windows or summarization when conversations become lengthy. + +### Token count threshold + +Use `tokens_exceed` to activate a context manager when the estimated token count of the entire context window exceeds a threshold. The context window includes the system prompt, user prompt, chat history (memory), and tool interactions: + +```json +{ + "activation": { + "tokens_exceed": 200000 + } +} +``` + +This rule helps to prevent context window overflow and to manage LLM API costs by triggering optimization strategies before exceeding model limits. + +### Combining multiple rules + +You can combine multiple activation rules using AND logic. The context manager executes only when all specified conditions are met: + +```json +{ + "activation": { + "message_count_exceed": 15, + "tokens_exceed": 200000 + } +} +``` + +This example activates the context manager only when both the message count exceeds 15 AND the token count exceeds 200,000, providing fine-grained control over when optimization occurs. + +## Context manager types + +OpenSearch provides the following context manager types. For complete configuration parameter details, see [Context manager configurations]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/#context-manager-configurations). + +### SlidingWindowManager + +Implements a sliding window approach that keeps only the most recent N interactions to prevent context window overflow. This example shows a sliding window manager that retains the 6 most recent messages and activates when the conversation exceeds 12 messages: + +```json +{ + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "message_count_exceed": 12 + } + } +} +``` + +For more information, see [SlidingWindowManager]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/#slidingwindowmanager). + +### SummarizationManager + +Summarizes lengthy conversations or tool interactions when token limits are approached. This example shows a summarization manager that summarizes 30% of the conversation history while preserving the 10 most recent messages, activating when the context exceeds 200,000 tokens: + +```json +{ + "type": "SummarizationManager", + "config": { + "summary_ratio": 0.3, + "preserve_recent_messages": 10, + "summarization_model_id": "<your-summarization-model-id>", + "activation": { + "tokens_exceed": 200000 + } + } +} +``` + +For more information, see [SummarizationManager]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/#summarizationmanager). + +### ToolsOutputTruncateManager + +Truncates tool output when it exceeds specified limits in order to prevent context overflow. Configure this manager for the `POST_TOOL` hook. It processes the output of each tool call, both for agents that use function calling (`_llm_interface`) and for agents that don't. If the output is longer than `max_output_length` characters, the manager keeps the first `max_output_length` characters and appends `... [Output truncated - original length: <length> characters]`. The agent sends the truncated output to the LLM and stores it in the agent's traces. This example shows a truncation manager that limits tool output to 40,000 characters and activates when the context exceeds 150,000 tokens: + +```json +{ + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 40000, + "activation": { + "tokens_exceed": 150000 + } + } +} +``` + +For more information, see [ToolsOutputTruncateManager]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/#toolsoutputtruncatemanager). + +## Agent integration + +Context management can be applied to agents either during agent registration or during agent execution. + +### During agent registration + +To apply context management to agents during agent registration, include the name of an existing context management when registering an agent: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "customer-service-agent", + "type": "conversational", + "llm": { + "model_id": "<llm_model_id>" + }, + "tools": [ + { + "type": "ListIndexTool" + } + ], + "context_management_name": "token-aware-truncation" +} +``` +{% include copy-curl.html %} + +### During agent execution + +To apply context management to agents during agent execution, specify the context management name in the `parameters` object of the execution request. If you specify a different context management name in the execution request than the name that was configured during agent registration, the execution request overrides the registered setting: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "parameters": { + "question": "How can I help you today?", + "context_management_name": "token-aware-truncation" + } +} +``` +{% include copy-curl.html %} + +## Example use cases + +The following examples demonstrate how you can use context management. + +### Long conversations + +To support long conversations, configure context management that maintains recent conversation flow while preventing context overflow: + +- Use a `SlidingWindowManager` to keep the most recent N number of messages. +- Hook into `PRE_LLM` to optimize before LLM calls. + +### Tool-heavy agents + +Configure context management for agents that use many tools: + +- Use a `ToolsOutputTruncateManager` to limit tool output size. +- Apply a `SlidingWindowManager` for tool interaction history. +- Hook into `POST_TOOL` to clean up after tool execution. + +### Tool-heavy agents with summarization + +Configure context management for agents with extensive tool interactions: + +- Use `ToolsOutputTruncateManager` to limit tool output size. +- Apply `SlidingWindowManager` for tool interaction history. +- Use `SummarizationManager` to summarize earlier tool interactions. +- Hook into `PRE_LLM` to optimize before LLM calls. + +## Getting started + +To implement context management in your agents: + +1. **[Create a context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/)** containing appropriate managers and hooks. +2. **[Register an agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/register-agent/)** with the context management or specify it during execution. +3. **[Execute the agent]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agent-apis/execute-agent/)** and observe context optimization in action. +4. **[Monitor and adjust]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/update-context-management/)** context management configurations based on performance. + +Start with conservative settings and gradually adjust thresholds, manager combinations, and activation rules to find the optimal configuration for your specific workload and performance requirements. +{: .tip} + +## Next steps + +- Explore [context management configuration]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/create-context-management/) options. +- Review the complete [Context Management API reference]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/). +- Learn about [agent integration]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/) with context management. \ No newline at end of file diff --git a/_ml-commons-plugin/custom-local-models.md b/_ml-commons-plugin/custom-local-models.md index f96f7841..4d78bea9 100644 --- a/_ml-commons-plugin/custom-local-models.md +++ b/_ml-commons-plugin/custom-local-models.md @@ -3,39 +3,40 @@ layout: default title: Custom models parent: Using ML models within OpenSearch grand_parent: Integrating ML models -nav_order: 120 +nav_order: 20 --- # Custom local models -**Generally available 2.9** +**Introduced 2.9** {: .label .label-purple } To use a custom model locally, you can upload it to the OpenSearch cluster. ## Model support -As of OpenSearch 2.6, OpenSearch supports local text embedding models. +OpenSearch supports the following types of local models: -As of OpenSearch 2.11, OpenSearch supports local sparse encoding models. - -As of OpenSearch 2.12, OpenSearch supports local cross-encoder models. +- Text embedding models +- Sparse encoding models +- Cross-encoder models +- Question answering models Running local models on the CentOS 7 operating system is not supported. Moreover, not all local models can run on all hardware and operating systems. {: .important} ## Preparing a model -For both text embedding and sparse encoding models, you must provide a tokenizer JSON file within the model zip file. +For all the models, you must provide a tokenizer JSON file within the model zip file. For sparse encoding models, make sure your output format is `{"output":<sparse_vector>}` so that ML Commons can post-process the sparse vector. -If you fine-tune a sparse model on your own dataset, you may also want to use your own sparse tokenizer model. It is preferable to provide your own [IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) JSON file in the tokenizer model zip file because this increases query performance when you use the tokenizer model in the query. Alternatively, you can use an OpenSearch-provided generic [IDF from MSMARCO](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1/1.0.0/torch_script/opensearch-neural-sparse-tokenizer-v1-1.0.0.zip). If the IDF file is not provided, the default weight of each token is set to 1, which may influence sparse neural search performance. +If you finetune a sparse model on your own dataset, you may also want to use your own sparse tokenizer model. It is preferable to provide your own [IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) JSON file in the tokenizer model zip file because this increases query performance when you use the tokenizer model in the query. Alternatively, you can use an OpenSearch-provided generic [IDF from MSMARCO](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1/1.0.0/torch_script/opensearch-neural-sparse-tokenizer-v1-1.0.0.zip). If the IDF file is not provided, the default weight of each token is set to 1, which may influence neural sparse search performance. ### Model format -To use a model in OpenSearch, you'll need to export the model into a portable format. As of Version 2.5, OpenSearch only supports the [TorchScript](https://pytorch.org/docs/stable/jit.html) and [ONNX](https://onnx.ai/) formats. +To use a model in OpenSearch, you must export the model into a portable format. OpenSearch supports only the [TorchScript](https://pytorch.org/docs/stable/jit.html) and [ONNX](https://onnx.ai/) formats. -You must save the model file as zip before uploading it to OpenSearch. To ensure that ML Commons can upload your model, compress your TorchScript file before uploading. For an example, download a TorchScript [model file](https://github.com/opensearch-project/ml-commons/blob/2.x/ml-algorithms/src/test/resources/org/opensearch/ml/engine/algorithms/text_embedding/all-MiniLM-L6-v2_torchscript_sentence-transformer.zip). +You must save the model file as zip before uploading it to OpenSearch. To ensure that ML Commons can upload your model, compress your TorchScript file before uploading. For an example, download a TorchScript [model file](https://github.com/opensearch-project/ml-commons/blob/main/ml-algorithms/src/test/resources/org/opensearch/ml/engine/algorithms/text_embedding/all-MiniLM-L6-v2_torchscript_sentence-transformer.zip). Additionally, you must calculate a SHA256 checksum for the model zip file that you'll need to provide when registering the model. For example, on UNIX, use the following command to obtain the checksum: @@ -63,19 +64,18 @@ To ensure that this basic local setup works, specify the following cluster setti PUT _cluster/settings { "persistent": { - "plugins": { - "ml_commons": { - "allow_registering_model_via_url": "true", - "only_run_on_ml_node": "false", - "model_access_control_enabled": "true", - "native_memory_threshold": "99" - } - } + "plugins.ml_commons.allow_registering_model_via_url": "true", + "plugins.ml_commons.only_run_on_ml_node": "false", + "plugins.ml_commons.model_access_control_enabled": "true", + "plugins.ml_commons.native_memory_threshold": "99" } } ``` {% include copy-curl.html %} +When registering a model from a URL, make sure the source is trusted. Loading models from untrusted sources can pose security risks. For more information, see [PyTorch security guidelines for untrusted models](https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models). +{: .warning} + ## Step 1: Register a model group To register a model, you have the following options: @@ -107,7 +107,11 @@ To learn more about model groups, see [Model access control]({{site.url}}{{site. ## Step 2: Register a local model -To register a remote model to the model group created in step 1, provide the model group ID from step 1 in the following request: +To register a local model to the model group created in step 1, send a Register Model API request. For descriptions of Register Model API parameters, see [Register a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/). + +The `function_name` corresponds to the model type. For text embedding models, set this parameter to `TEXT_EMBEDDING`. For sparse encoding models, set this parameter to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. For cross-encoder models, set this parameter to `TEXT_SIMILARITY`. For question answering models, set this parameter to `QUESTION_ANSWERING`. In this example, set `function_name` to `TEXT_EMBEDDING` because you're registering a text embedding model. + +Provide the model group ID from step 1 and send the following request: ```json POST /_plugins/_ml/models/_register @@ -116,32 +120,7 @@ POST /_plugins/_ml/models/_register "version": "1.0.1", "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", "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": "TORCH_SCRIPT", - "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": 1676073973126, - "url": "https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.1/torch_script/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.1-torch_script.zip" -} -``` -{% include copy-curl.html %} - -Note that in OpenSearch Dashboards, wrapping the `all_config` field contents in triple quotes (`"""`) automatically escapes quotation marks within the field and provides better readability: - -```json -POST /_plugins/_ml/models/_register -{ - "name": "huggingface/sentence-transformers/msmarco-distilbert-base-tas-b", - "version": "1.0.1", - "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", - "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", + "function_name": "TEXT_EMBEDDING", "model_format": "TORCH_SCRIPT", "model_content_size_in_bytes": 266352827, "model_content_hash_value": "acdc81b652b83121f914c5912ae27c0fca8fabf270e6f191ace6979a19830413", @@ -155,9 +134,7 @@ POST /_plugins/_ml/models/_register "url": "https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.1/torch_script/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.1-torch_script.zip" } ``` -{% include copy.html %} - -For descriptions of Register API parameters, see [Register a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/). The `model_task_type` corresponds to the model type. For text embedding models, set this parameter to `TEXT_EMBEDDING`. For sparse encoding models, set this parameter to `SPARSE_ENCODING` or `SPARSE_TOKENIZE`. For cross-encoder models, set this parameter to `TEXT_SIMILARITY`. +{% include copy-curl.html %} OpenSearch returns the task ID of the register operation: @@ -170,7 +147,7 @@ OpenSearch returns the task ID of the register operation: To check the status of the operation, provide the task ID to the [Get task]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): -```bash +```json GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj ``` {% include copy-curl.html %} @@ -181,14 +158,14 @@ When the operation is complete, the state changes to `COMPLETED`: { "model_id": "cleMb4kBJ1eYAeTMFFg4", "task_type": "REGISTER_MODEL", - "function_name": "REMOTE", + "function_name": "TEXT_EMBEDDING", "state": "COMPLETED", "worker_node": [ "XPcXLV7RQoi5m8NI_jEOVQ" ], "create_time": 1689793598499, "last_update_time": 1689793598530, - "is_async": false + "is_async": true } ``` @@ -198,9 +175,9 @@ Take note of the returned `model_id` because you’ll need it to deploy the mode The deploy operation reads the model's chunks from the model index and then creates an instance of the model to load into memory. The bigger the model, the more chunks the model is split into and longer it takes for the model to load into memory. -To deploy the registered model, provide its model ID from step 3 in the following request: +To deploy the registered model, provide its model ID from step 2 in the following request: -```bash +```json POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_deploy ``` {% include copy-curl.html %} @@ -210,13 +187,14 @@ The response contains the task ID that you can use to check the status of the de ```json { "task_id": "vVePb4kBJ1eYAeTM7ljG", + "task_type": "DEPLOY_MODEL", "status": "CREATED" } ``` -As in the previous step, check the status of the operation by calling the Tasks API: +As in the previous step, check the status of the operation by calling the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): -```bash +```json GET /_plugins/_ml/tasks/vVePb4kBJ1eYAeTM7ljG ``` {% include copy-curl.html %} @@ -227,7 +205,7 @@ When the operation is complete, the state changes to `COMPLETED`: { "model_id": "cleMb4kBJ1eYAeTMFFg4", "task_type": "DEPLOY_MODEL", - "function_name": "REMOTE", + "function_name": "TEXT_EMBEDDING", "state": "COMPLETED", "worker_node": [ "n-72khvBTBi3bnIIR8FTTw" @@ -238,7 +216,7 @@ When the operation is complete, the state changes to `COMPLETED`: } ``` -If a cluster or node is restarted, then you need to redeploy the model. To learn how to set up automatic redeployment, see [Enable auto redeploy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#enable-auto-redeploy). +If a cluster or node is restarted, then you need to redeploy the model. To learn how to set up automatic redeployment, see [Model deployment settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#model-deployment-settings). {: .tip} ## Step 4 (Optional): Test the model @@ -312,12 +290,74 @@ The response contains the tokens and weights: "bright": 0.1756877, ... } + ] } } + ] } + ] } ``` ## Step 5: Use the model for search -To learn how to use the model for vector search, see [Using an ML model for neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/#using-an-ml-model-for-neural-search). +To learn how to use the model for vector search, see [AI search methods]({{site.url}}{{site.baseurl}}/vector-search/ai-search/#ai-search-methods). + +## Question answering models + +A question answering model extracts the answer to a question from a given context. ML Commons supports context in `text` format. + +To register a question answering model, send a request in the following format. Specify the `function_name` as `QUESTION_ANSWERING`: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "question_answering", + "version": "1.0.0", + "function_name": "QUESTION_ANSWERING", + "description": "test model", + "model_format": "TORCH_SCRIPT", + "model_group_id": "lN4AP40BKolAMNtR4KJ5", + "model_content_hash_value": "e837c8fc05fd58a6e2e8383b319257f9c3859dfb3edc89b26badfaf8a4405ff6", + "model_config": { + "model_type": "bert", + "framework_type": "huggingface_transformers" + }, + "url": "https://github.com/opensearch-project/ml-commons/blob/main/ml-algorithms/src/test/resources/org/opensearch/ml/engine/algorithms/question_answering/question_answering_pt.zip?raw=true" +} +``` +{% include copy-curl.html %} + +Then send a request to deploy the model: + +```json +POST _plugins/_ml/models/{model_id}/_deploy +``` +{% include copy-curl.html %} + +To test a question answering model, send the following request. It requires a `question` and the relevant `context` from which the answer will be generated: + +```json +POST /_plugins/_ml/_predict/question_answering/{model_id} +{ + "question": "Where do I live?", + "context": "My name is John. I live in New York" +} +``` +{% include copy-curl.html %} + +The response provides the answer based on the context: + +```json +{ + "inference_results": [ + { + "output": [ + { + "result": "new york" + } + ] + } + ] +} +``` diff --git a/_ml-commons-plugin/gpu-acceleration.md b/_ml-commons-plugin/gpu-acceleration.md index 240df326..77add9e3 100644 --- a/_ml-commons-plugin/gpu-acceleration.md +++ b/_ml-commons-plugin/gpu-acceleration.md @@ -13,12 +13,12 @@ When running a natural language processing (NLP) model in your OpenSearch cluste ## Supported GPUs -Currently, ML nodes support the following GPU instances: +ML nodes support the following GPU instances: - [NVIDIA instances with CUDA 11.6](https://aws.amazon.com/nvidia/) - [AWS Inferentia](https://aws.amazon.com/machine-learning/inferentia/) -If you need GPU power, you can provision GPU instances through [Amazon Elastic Compute Cloud (Amazon EC2)](https://aws.amazon.com/ec2/). For more information on how to provision a GPU instance, see [Recommended GPU Instances](https://docs.aws.amazon.com/dlami/latest/devguide/gpu.html). +If you need GPU power, you can provision GPU instances through [Amazon Elastic Compute Cloud (Amazon EC2)](https://aws.amazon.com/ec2/). For more information about how to provision a GPU instance, see [Recommended GPU Instances](https://docs.aws.amazon.com/dlami/latest/devguide/gpu.html). ## Supported images @@ -26,7 +26,7 @@ You can use GPU acceleration with both [Docker images](https://gitlab.com/nvidia ## PyTorch -GPU-accelerated ML nodes require [PyTorch](https://pytorch.org/docs/stable/index.html) 1.12.1 work with ML models. +GPU-accelerated ML nodes require [PyTorch](https://pytorch.org/docs/stable/index.html) 1.12.1 to work with ML models. ## Setting up a GPU-accelerated ML node @@ -38,7 +38,7 @@ NVIDIA uses CUDA to increase node performance. In order to take advantage of CUD If the `nvidia-uvm` kernel does not exist, run `nvidia-uvm-init.sh`: -``` +```bash #!/bin/bash ## Script to initialize nvidia device nodes. ## https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#runfile-verifications @@ -67,6 +67,18 @@ else fi ``` +If you run OpenSearch natively (without Docker) using the packaged version of OpenSearch, `systemd` may block OpenSearch from accessing your GPU. To accelerate models, you need a working [CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit) installation and access to the NVIDIA device under `/dev`. + +To allow OpenSearch to use the GPU, update the `systemd` service by adding the following configuration: + +```ini +systemctl edit opensearch.service + +[Service] +DevicePolicy=auto +``` + + After verifying that `nvidia-uvm` exists under `/dev`, you can start OpenSearch inside your cluster. ### Preparing AWS Inferentia ML node @@ -77,7 +89,7 @@ To start, [download and install OpenSearch]({{site.url}}{{site.baseurl}}/install Then export OpenSearch and set up your environment variables. This example exports OpenSearch into the directory `opensearch-2.5.0`, so `OPENSEARCH_HOME` = `opensearch-2.5.0`: -``` +```bash echo "export OPENSEARCH_HOME=~/opensearch-2.5.0" | tee -a ~/.bash_profile echo "export PYTORCH_VERSION=1.12.1" | tee -a ~/.bash_profile source ~/.bash_profile @@ -95,7 +107,7 @@ GPU acceleration has only been tested on Ubuntu 20.04 and Amazon Linux 2. Howeve #### Ubuntu 20.04 -``` +```bash . /etc/os-release sudo tee /etc/apt/sources.list.d/neuron.list > /dev/null <<EOF deb https://apt.repos.neuron.amazonaws.com ${VERSION_CODENAME} main @@ -164,7 +176,7 @@ sudo sysctl -w vm.max_map_count=262144 #### Amazon Linux 2 -``` +```bash # Configure Linux for Neuron repository updates sudo tee /etc/yum.repos.d/neuron.repo > /dev/null <<EOF [neuron] @@ -231,17 +243,17 @@ OpenSearch should now be running inside your GPU-accelerated cluster. However, i If the previous two scripts do not provision your GPU-accelerated node properly, you can install the drivers for AWS Inferentia manually: -1. Deploy an AWS accelerator instance based on your chosen Linux operating system. For instructions, see [Deploy on AWS accelerator instance](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/frameworks/torch/torch-neuron/setup/pytorch-install.html#deploy-on-aws-ml-accelerator-instance). +1. Deploy an AWS accelerator instance based on your chosen Linux operating system. For instructions, see [PyTorch Neuron Setup](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/setup/pytorch/index.html). 2. Copy the Neuron library into OpenSearch. The following command uses a directory named `opensearch-2.5.0`: - ``` + ```bash OPENSEARCH_HOME=~/opensearch-2.5.0 ``` 3. Set the `PYTORCH_EXTRA_LIBRARY_PATH` path. In this example, we create a `pytorch` virtual environment in the OPENSEARCH_HOME folder: - ``` + ```bash PYTORCH_NEURON_LIB_PATH=~/pytorch_venv/lib/python3.7/site-packages/torch_neuron/lib/ @@ -249,27 +261,27 @@ If the previous two scripts do not provision your GPU-accelerated node properly, export PYTORCH_EXTRA_LIBRARY_PATH=$OPENSEARCH_HOME/lib/torch_neuron/lib/libtorchneuron.so ``` -4. (Optional) To monitor the GPU usage of your accelerator instance, install [Neuron tools](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/tools/index.html), which allows models to be used inside your instance: +4. (Optional) To monitor the GPU usage of your accelerator instance, install [Neuron tools](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/tools/neuron-sys-tools/index.html), which allows models to be used inside your instance: - ``` + ```bash # Install Neuron Tools sudo apt-get install aws-neuronx-tools -y ``` - ``` + ```bash # Add Neuron tools your PATH export PATH=/opt/aws/neuron/bin:$PATH ``` - ``` + ```bash # Test Neuron tools neuron-top ``` -5. To make sure you have enough memory to upload a model, increase the JVM stack size to `>+2MB`: +5. To make sure you have enough memory to upload a model, increase the JVM stack size to at least 2 MB: - ``` + ```bash echo "-Xss2m" | sudo tee -a $OPENSEARCH_HOME/config/jvm.options ``` @@ -279,24 +291,24 @@ If the previous two scripts do not provision your GPU-accelerated node properly, Due to the amount of data required to work with ML models, you might encounter the following `max file descriptors` or `vm.max_map_count` errors when trying to run OpenSearch in a your cluster: -``` +```bash [1]: max file descriptors [8192] for opensearch process is too low, increase to at least [65535] [2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] ``` To troubleshoot the max file descriptors error, run the following command: -``` +```bash echo "$(whoami) - nofile 65535" | sudo tee -a /etc/security/limits.conf ``` -To fix the `vm.max_map_count` error, run this command to increase the count to `262114`: +To fix the `vm.max_map_count` error, run this command to increase the count to `262144`: -``` +```bash sudo sysctl -w vm.max_map_count=262144 ``` ## Next steps -If you want to try a GPU-accelerated cluster using AWS Inferentia with a pretrained HuggingFace model, see [Compiling and Deploying HuggingFace Pretrained BERT](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html). +If you want to try a GPU-accelerated cluster using AWS Inferentia with a pretrained Hugging Face model, see the [Pretrained BERT Tutorial](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html). diff --git a/_ml-commons-plugin/index.md b/_ml-commons-plugin/index.md index c936f361..b471be7e 100644 --- a/_ml-commons-plugin/index.md +++ b/_ml-commons-plugin/index.md @@ -1,6 +1,6 @@ --- layout: default -title: Machine learning +title: AI and machine learning nav_order: 1 has_children: false has_toc: false @@ -8,26 +8,106 @@ nav_exclude: true permalink: /ml-commons-plugin/ redirect_from: - /ml-commons-plugin/index/ +demo_cards: + - heading: "Explore AI search and RAG demos" + description: "Try interactive Hugging Face demos showcasing AI search, multimodal RAG, and agentic RAG" + link: "https://huggingface.co/spaces/opensearch-project/OpenSearch-AI" +models: + - heading: "Deploy local models to your cluster" + link: "/ml-commons-plugin/using-ml-models/" + list: + - "<b>Pretrained models</b>: Use OpenSearch-provided models for immediate implementation" + - "<b>Custom models</b>: Upload and serve your own models" + - heading: "Connect to externally hosted models" + link: "/ml-commons-plugin/remote-models/" + description: "Connect to models hosted on Amazon Bedrock, Amazon SageMaker, OpenAI, Cohere, DeepSeek, and other platforms" +more_cards: + - heading: "Get started with AI search" + description: "Build your first semantic search application using this hands-on tutorial" + link: "/vector-search/tutorials/neural-search-tutorial/" + - heading: "AI search" + description: "Discover AI search, from <b>semantic</b>, <b>hybrid</b>, and <b>multimodal</b> search to <b>RAG</b>" + link: "/vector-search/ai-search/" + - heading: "Tutorials" + description: "Follow step-by-step tutorials to integrate AI capabilities into your applications" + link: "/vector-search/tutorials/" + - heading: "ML API reference" + description: "Explore comprehensive documentation for machine learning API operations" + link: "/ml-commons-plugin/api/" +agents: + - heading: "Agents" + link: "/ml-commons-plugin/agents-tools/agents/" + description: "Learn about the agent types and choose one for your use case" + - heading: "Tools" + link: "/ml-commons-plugin/agents-tools/tools/" + description: "Give agents specific capabilities, such as running searches or listing indexes" + - heading: "Agents and tools tutorial" + link: "/ml-commons-plugin/agents-tools/agents-tools-tutorial/" + description: "Build a retrieval-augmented generation (RAG) application using an agent and tools" + - heading: "OpenSearch Assistant Toolkit" + link: "/ml-commons-plugin/opensearch-assistant/" + description: "Create AI-powered assistants for OpenSearch Dashboards" +mcp: + - heading: "MCP connector" + link: "/ml-commons-plugin/agents-tools/mcp/" + description: "Let OpenSearch agents call tools hosted on external MCP servers" + - heading: "In-cluster MCP server" + link: "/ml-commons-plugin/mcp/in-cluster-mcp-server/" + description: "Let external MCP clients call tools registered in your cluster" + - heading: "Standalone MCP server" + link: "/ai-agent-integrations/mcp-server/" + description: "Run the OpenSearch MCP Server outside your cluster to let AI assistants query OpenSearch" +memory: + - heading: "Agentic memory" + link: "/ml-commons-plugin/agentic-memory/" + description: "Store and retrieve information, such as user preferences, across agent conversations" + - heading: "Context management" + link: "/ml-commons-plugin/context-management/" + description: "Truncate, summarize, or limit the context that agents send to LLMs" +algorithms: + - heading: "Supported algorithms" + link: "/ml-commons-plugin/algorithms/" + description: "Learn about the natively supported clustering, pattern detection, and statistical analysis algorithms" --- -# Machine learning +# AI and machine learning -The [ML Commons plugin](https://github.com/opensearch-project/ml-commons/) provides machine learning (ML) features in OpenSearch. +OpenSearch provides machine learning (ML) algorithms, model integrations, model inference, agents, and related AI capabilities. Integrate ML models to generate embeddings or text, build agents that use models and tools to perform multi-step tasks, or run built-in algorithms to analyze your data. -## Integrating ML models +## Interactive demos -For ML-model-powered search, you can use a pretrained model provided by OpenSearch, upload your own model to the OpenSearch cluster, or connect to a foundation model hosted on an external platform. In OpenSearch version 2.9 and later, you can integrate local and external models simultaneously within a single cluster. +{% include cards.html cards=page.demo_cards %} -For more information, see [Integrating ML models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/). +## ML models -## Managing ML models in OpenSearch Dashboards +OpenSearch supports ML models that you can use to enhance search relevance through semantic understanding. You can either deploy models directly within your OpenSearch cluster or connect to models hosted on external platforms. These models can transform text into vector embeddings, enabling semantic search capabilities, or provide advanced features like text generation and question answering. For more information, see [Integrating ML models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/). -Administrators of ML clusters can use OpenSearch Dashboards to review and manage the status of ML models running inside a cluster. For more information, see [Managing ML models in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/ml-commons-plugin/ml-dashboard/). +{% include cards.html cards=page.models %} -## Support for algorithms +## Agents and tools -ML Commons supports various algorithms to help train ML models and make predictions or test data-driven predictions without a model. For more information, see [Supported algorithms]({{site.url}}{{site.baseurl}}/ml-commons-plugin/algorithms/). +An _agent_ uses a large language model (LLM) to plan and run multi-step tasks, such as answering questions about your data or generating queries from natural language. To perform these tasks, an agent calls _tools_, each of which runs a specific operation, such as running a search or listing indexes. For more information, see [Agents and tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/index/). -## ML Commons API +{% include cards.html cards=page.agents %} -ML Commons provides its own set of REST APIs. For more information, see [ML Commons API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/index/). \ No newline at end of file +## MCP servers and clients + +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that defines how AI applications discover and call tools. OpenSearch can act as an MCP client, so that its agents can call external tools, or as an MCP server, so that external AI applications can call OpenSearch tools. For more information, see [MCP servers and clients]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/). + +{% include cards.html cards=page.mcp %} + +## Memory and context + +Agents can retain information across conversations and control how much context they send to the LLM. For more information, see [Memory and context]({{site.url}}{{site.baseurl}}/ml-commons-plugin/memory-and-context/). + +{% include cards.html cards=page.memory %} + +## Built-in algorithms for data analysis + +OpenSearch includes built-in algorithms that analyze your data directly within your cluster, enabling tasks like anomaly detection, data clustering, and predictive analytics without requiring external ML models. + +{% include cards.html cards=page.algorithms %} + +## Build your solution + +{% include cards.html cards=page.more_cards %} \ No newline at end of file diff --git a/_ml-commons-plugin/integrating-ml-models.md b/_ml-commons-plugin/integrating-ml-models.md index 4dbf169e..70dde683 100644 --- a/_ml-commons-plugin/integrating-ml-models.md +++ b/_ml-commons-plugin/integrating-ml-models.md @@ -1,8 +1,23 @@ --- layout: default title: Integrating ML models -nav_order: 15 +nav_order: 10 has_children: true +more_cards: + - heading: "Get started with AI search" + description: "Learn how to implement semantic and hybrid search in OpenSearch" + link: "/vector-search/tutorials/neural-search-tutorial/" +local_model: + - heading: "Pretrained models provided by OpenSearch" + link: "/ml-commons-plugin/pretrained-models/" + description: "Requires minimal setup and avoids the time and effort required to train a custom model" + - heading: "Custom models" + link: "/ml-commons-plugin/custom-local-models/" + description: "Offers customization for your specific use case" +external_model: + - heading: "Externally hosted models" + link: "/ml-commons-plugin/remote-models/" + description: "Learn how to create connectors for models hosted on third-party platforms" --- # Integrating ML models @@ -14,32 +29,26 @@ Before you get started, you'll need to [set up]({{site.url}}{{site.baseurl}}/qui ## Choosing a model -To integrate an ML model into your search workflow, choose one of the following options: +To integrate an ML model into your search workflow, choose one of the following options. -1. **Local model**: Upload a model to the OpenSearch cluster and use it locally. This option allows you to serve the model in your OpenSearch cluster but may require significant system resources. +### Local model - 1. **Pretrained model provided by OpenSearch**: This option requires minimal setup and avoids the time and effort required to train a custom model. +Upload a model to the OpenSearch cluster and use it locally. This option allows you to serve the model in your OpenSearch cluster but may require significant system resources. - For a list of supported models and information about using a pretrained model provided by OpenSearch, see [Pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/). +{% include cards.html cards=page.local_model %} - 1. **Custom model**: This option offers customization for your specific use case. +### Externally hosted model - For information about uploading your model, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). - -1. **Externally hosted model**: This option allows you to connect to a model hosted on a third-party platform. It requires more setup but allows the use of models that are already hosted on a service other than OpenSearch. +Connect to a model hosted on a third-party platform. This requires more setup but allows the use of models that are already hosted on a service other than OpenSearch. - To connect to an externally hosted model, you need to set up a connector: - - - For a walkthrough with detailed steps, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). - - For more information about supported connectors, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). - - For information about creating your own connector, see [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). +{% include cards.html cards=page.external_model %} In OpenSearch version 2.9 and later, you can integrate local and external models simultaneously within a single cluster. {: .note} ## Tutorial -For a step-by-step tutorial, see [Neural search tutorial]({{site.url}}{{site.baseurl}}/search-plugins/neural-search-tutorial/). +{% include cards.html cards=page.more_cards %} ## Using a model @@ -56,7 +65,7 @@ You can invoke your model by calling the [Predict API]({{site.url}}{{site.baseur ### Using a model for search -OpenSearch supports multiple search methods that integrate with ML models. For more information, see [Search methods]({{site.url}}{{site.baseurl}}/search-plugins/index/#search-methods). +OpenSearch supports multiple search methods that integrate with ML models. For more information, see [AI search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/). ## Disabling a model diff --git a/_ml-commons-plugin/mcp/in-cluster-mcp-server.md b/_ml-commons-plugin/mcp/in-cluster-mcp-server.md new file mode 100644 index 00000000..ac54ac92 --- /dev/null +++ b/_ml-commons-plugin/mcp/in-cluster-mcp-server.md @@ -0,0 +1,431 @@ +--- +layout: default +title: In-cluster MCP server +parent: MCP servers and clients +nav_order: 10 +--- + +# Using the in-cluster MCP server +**Introduced 3.3** +{: .label .label-purple } + +The in-cluster Model Context Protocol (MCP) server lets external MCP clients, such as AI assistants and agent frameworks, discover and call tools in your OpenSearch cluster. The server runs inside OpenSearch, so no additional installation is required. The server is exposed at the `/_plugins/_ml/mcp` endpoint and uses the [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports). Clients can call only the tools that you register. + +The server is stateless: all communication happens over individual HTTP `POST` requests, and the server does not open Server-Sent Events (SSE) streams. If a client sends a `GET` request, typically to open an SSE stream, the server returns a `405 Method Not Allowed` response, and the client continues using `POST` requests. + +To compare the in-cluster MCP server with the standalone MCP server, see [Choosing an MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/#choosing-an-mcp-server). + +## Step 1: Enable the MCP server + +The MCP server is disabled by default. To enable it, update the `plugins.ml_commons.mcp_server_enabled` setting: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.mcp_server_enabled": "true" + } +} +``` +{% include copy-curl.html %} + +## Step 2: Register tools + +Register the tools that you want MCP clients to call. Each tool definition contains the following fields. + +| Field | Data type | Required/Optional | Description | +| :--- | :--- | :--- | :--- | +| `type` | String | Required | The tool type, such as `ListIndexTool`. For a list of tool types, see [Tools]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). | +| `name` | String | Optional | The name that clients use to call the tool. Default is the `type` value. To register multiple tools of the same type, give each tool a different name. | +| `description` | String | Optional | A description of the tool. The large language model (LLM) in the client uses the description to decide when to call the tool. | +| `parameters` | Object | Optional | The tool parameters. Some tool types require parameters. For the parameters of each tool type, see the corresponding [tool documentation]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/index/). | +| `attributes` | Object | Optional | The tool attributes. Use the `input_schema` attribute to provide a JSON schema that defines the arguments that the tool accepts. The client sends this schema to the LLM so that the LLM can provide correctly formatted arguments. | + +The following request registers a [List Index tool]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/list-index-tool/) and a [Search Index tool]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/search-index-tool/): + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "name": "ListIndexTool", + "type": "ListIndexTool", + "description": "This tool returns information about indices in the OpenSearch cluster along with the index `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, `pri.store. size `, `pri.store.size`, `pri.store`. Optional arguments: 1. `indices`, a comma-delimited list of one or more indices to get information from (default is an empty list meaning all indices). Use only valid index names. 2. `local`, whether to return information from the local node only instead of the cluster manager node (Default is false)", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "indices": { + "type": "array", + "items": { + "type": "string" + }, + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"], use empty array [] to list all indices in the cluster" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchIndexTool", + "type": "SearchIndexTool", + "description": "Searches an index. Provide the index name and a query written in OpenSearch query domain-specific language (DSL).", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "string", + "description": "The name of the index to search." + }, + "query": { + "type": "object", + "description": "The search request body, for example, {\"query\": {\"match\": {\"field\": \"value\"}}}." + } + }, + "required": ["index", "query"], + "additionalProperties": false + } + } + } + ] +} +``` +{% include copy-curl.html %} + +For each node, the response contains the node ID and the registration status: + +```json +{ + "6It0uQ1AR06IDC4nMstPQw": { + "created": true + } +} +``` + +## Step 3: Connect an MCP client + +To connect an MCP client, configure the client to use the Streamable HTTP transport and provide the MCP server URL: + +``` +http://<host>:<port>/_plugins/_ml/mcp +``` + +The following Python example uses the [FastMCP](https://gofastmcp.com/) client to list the registered tools and then call both tools on the `opensearch_dashboards_sample_data_ecommerce` sample index: + +```python +import asyncio +from fastmcp import Client + +async def main(): + async with Client("http://localhost:9200/_plugins/_ml/mcp") as client: + for tool in await client.list_tools(): + print(tool.name) + + result = await client.call_tool( + "ListIndexTool", + {"indices": ["opensearch_dashboards_sample_data_ecommerce"]}, + ) + print(result.content[0].text) + + result = await client.call_tool( + "SearchIndexTool", + { + "index": "opensearch_dashboards_sample_data_ecommerce", + "query": { + "size": 1, + "_source": ["customer_full_name", "products.product_name", "taxful_total_price"], + "query": {"match": {"products.product_name": "jacket"}}, + }, + }, + ) + print(result.content[0].text) + +asyncio.run(main()) +``` +{% include copy.html %} + +The script prints the tool names, the index information, and the search result: + +``` +ListIndexTool +SearchIndexTool +row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,opensearch_dashboards_sample_data_ecommerce,ryn25tMCTDex530BrUVmfw,1,0,4675,0,4mb,4mb + +{"_index":"opensearch_dashboards_sample_data_ecommerce","_source":{"customer_full_name":"Sultan Al Mccarthy","products":[{"product_name":"Summer jacket - navy"},{"product_name":"Light jacket - khaki"}],"taxful_total_price":86.98},"_id":"eWBchqABedeO5z2s7srO","_score":1.6412048} +``` + +### Authenticating to a cluster that uses the Security plugin + +If your cluster uses the Security plugin, the client must authenticate with each request. Pass the credentials in the request headers. For example, to use basic authentication with FastMCP, configure the transport with an `Authorization` header. If your cluster uses a certificate signed by your own certificate authority (CA), provide the path to the CA certificate in the `verify` parameter: + +```python +import asyncio, base64 +from fastmcp import Client +from fastmcp.client.transports import StreamableHttpTransport + +credentials = base64.b64encode(b"<username>:<password>").decode() +transport = StreamableHttpTransport( + "https://localhost:9200/_plugins/_ml/mcp", + headers={"Authorization": f"Basic {credentials}"}, + verify="<path-to-root-ca.pem>", +) + +async def main(): + async with Client(transport) as client: + print([tool.name for tool in await client.list_tools()]) + +asyncio.run(main()) +``` +{% include copy.html %} + +The user must have the permissions described in [Permissions](#permissions). + +## Sending MCP requests manually + +MCP clients communicate with the server using [JSON-RPC](https://www.jsonrpc.org/specification) messages. To debug a client or test the server without one, send the same messages to the MCP endpoint yourself. The following steps show the sequence of requests that a typical MCP client sends. + +### Step 1: Initialize a connection + +Send an `initialize` request containing your client information and capabilities. The `protocolVersion` must match a supported MCP specification version: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": { + "roots": { + "listChanged": true + }, + "sampling": {} + }, + "clientInfo": { + "name": "test-client", + "version": "1.0.0" + } + } +} +``` +{% include copy-curl.html %} + +The server responds with its capabilities and server information. The `tools.listChanged` capability indicates that the server supports dynamic tool discovery: + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-03-26", + "capabilities": { + "logging": {}, + "prompts": { + "listChanged": false + }, + "resources": { + "subscribe": false, + "listChanged": false + }, + "tools": { + "listChanged": true + } + }, + "serverInfo": { + "name": "OpenSearch-MCP-Stateless-Server", + "version": "0.1.0" + }, + "instructions": "OpenSearch MCP Stateless Server - provides access to ML tools without sessions" + } +} +``` + +### Step 2: Send an initialization complete notification + +Send a notification to indicate that initialization is complete: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "method": "notifications/initialized", + "params": {} +} +``` +{% include copy-curl.html %} + +The server returns a `202 Accepted` status with an empty response body. + +### Step 3: List the available tools + +Use the `tools/list` method to discover the available tools: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/list", + "params": {} +} +``` +{% include copy-curl.html %} + +The server returns the registered tools, including the name, description, and input schema (`inputSchema`) of each tool: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "jsonrpc": "2.0", + "id": 2, + "result": { + "tools": [ + { + "name": "ListIndexTool", + "description": "This tool returns information about indices in the OpenSearch cluster along with the index `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, `pri.store. size `, `pri.store.size`, `pri.store`. Optional arguments: 1. `indices`, a comma-delimited list of one or more indices to get information from (default is an empty list meaning all indices). Use only valid index names. 2. `local`, whether to return information from the local node only instead of the cluster manager node (Default is false)", + "inputSchema": { + "type": "object", + "properties": { + "indices": { + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"], use empty array [] to list all indices in the cluster", + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + } + }, + { + "name": "SearchIndexTool", + "description": "Searches an index. Provide the index name and a query written in OpenSearch query domain-specific language (DSL).", + "inputSchema": { + "type": "object", + "properties": { + "query": { + "description": "The search request body, for example, {\"query\": {\"match\": {\"field\": \"value\"}}}.", + "type": "object" + }, + "index": { + "description": "The name of the index to search.", + "type": "string" + } + }, + "required": [ + "index", + "query" + ], + "additionalProperties": false + } + } + ] + } +} +``` +</details> + +### Step 4: Call a tool + +Use the `tools/call` method to call a tool. Provide the tool name and arguments that match the tool's input schema: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "ListIndexTool", + "arguments": { + "indices": ["opensearch_dashboards_sample_data_ecommerce"] + } + } +} +``` +{% include copy-curl.html %} + +The server runs the tool and returns the result in the `content` array. The `isError` field indicates whether the tool ran successfully: + +```json +{ + "jsonrpc": "2.0", + "id": 3, + "result": { + "content": [ + { + "type": "text", + "text": "row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards)\n1,green,open,opensearch_dashboards_sample_data_ecommerce,ryn25tMCTDex530BrUVmfw,1,0,4675,0,4mb,4mb\n" + } + ], + "isError": false, + "_meta": {} + } +} +``` + +## Managing registered tools + +To view the registered tools, send the following request: + +```json +GET /_plugins/_ml/mcp/tools/_list +``` +{% include copy-curl.html %} + +To update a tool, provide the tool name and the fields to change. Fields that you omit keep their current values. For example, the following request updates only the description of the `SearchIndexTool` tool: + +```json +POST /_plugins/_ml/mcp/tools/_update +{ + "tools": [ + { + "name": "SearchIndexTool", + "description": "Searches an index of ecommerce orders. Provide the index name and a query written in OpenSearch query DSL." + } + ] +} +``` +{% include copy-curl.html %} + +To remove tools, provide an array of tool names: + +```json +POST /_plugins/_ml/mcp/tools/_remove +["ListIndexTool", "SearchIndexTool"] +``` +{% include copy-curl.html %} + +For more information, see [MCP server APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/). + +## Permissions + +If your cluster uses the Security plugin, the following permissions control access to the MCP server. + +| Permission | Allows | +| :--- | :--- | +| `cluster:admin/opensearch/ml/mcp/server` | Connecting to the MCP server, listing tools using the `tools/list` method, and calling tools | +| `cluster:admin/opensearch/ml/mcp_tools/list` | Listing registered tools | +| `cluster:admin/opensearch/ml/mcp_tools/register` | Registering tools | +| `cluster:admin/opensearch/ml/mcp_tools/update` | Updating tools | +| `cluster:admin/opensearch/ml/mcp_tools/remove` | Removing tools | + +The `ml_full_access` predefined role includes all of these permissions. The `ml_read_access` role does not include any of them. + +Tools run using the permissions of the user that the client authenticates as. To call a tool that accesses index data, the user also needs the corresponding index permissions. For example, to call the `SearchIndexTool` tool registered in [Step 2](#step-2-register-tools), the user needs the `read` permission on the index that the tool searches. The `ml_full_access` role does not grant permissions on your indexes. + +For more information, see [Permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/). + +## Next steps + +- [MCP server APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/mcp-server-apis/). + diff --git a/_ml-commons-plugin/mcp/index.md b/_ml-commons-plugin/mcp/index.md new file mode 100644 index 00000000..5074b8d6 --- /dev/null +++ b/_ml-commons-plugin/mcp/index.md @@ -0,0 +1,32 @@ +--- +layout: default +title: MCP servers and clients +nav_order: 25 +has_children: true +has_toc: false +redirect_from: + - /ml-commons-plugin/mcp/ +--- + +# MCP servers and clients + +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that defines how AI applications discover and call tools. OpenSearch supports MCP using the following components. + +| Component | Use case | Where it runs | +| :--- | :--- | :--- | +| [MCP connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/mcp/) | Let OpenSearch agents call tools hosted on external MCP servers. OpenSearch acts as an MCP client. | In your cluster | +| [In-cluster MCP server]({{site.url}}{{site.baseurl}}/ml-commons-plugin/mcp/in-cluster-mcp-server/) | Let external MCP clients call tools registered in your cluster. OpenSearch acts as an MCP server. | In your cluster | +| [Standalone MCP server]({{site.url}}{{site.baseurl}}/ai-agent-integrations/mcp-server/) | Let external AI assistants query OpenSearch using its REST APIs. | Outside your cluster | + +The standalone MCP server is the open-source [OpenSearch MCP Server](https://github.com/opensearch-project/opensearch-mcp-server-py) project. + +## Choosing an MCP server + +To let external AI applications access OpenSearch, choose an MCP server based on your requirements. + +| Requirement | In-cluster MCP server | Standalone MCP server | +| :--- | :--- | :--- | +| Setup | Enable the `plugins.ml_commons.mcp_server_enabled` setting. No installation is required. | Install the server and run it as a separate process. | +| Exposed tools | Tools that you register in the cluster | Tools provided by the server, which call OpenSearch REST APIs | +| Transport | Streamable HTTP | Standard input/output (`stdio`), Streamable HTTP, and legacy Server-Sent Events (SSE) | +| Clusters | The cluster that runs the server | One or more clusters, including Amazon OpenSearch Service domains and Amazon OpenSearch Serverless collections | diff --git a/_ml-commons-plugin/memory-and-context.md b/_ml-commons-plugin/memory-and-context.md new file mode 100644 index 00000000..cf5acb18 --- /dev/null +++ b/_ml-commons-plugin/memory-and-context.md @@ -0,0 +1,26 @@ +--- +layout: default +title: Memory and context +nav_order: 30 +has_children: true +has_toc: false +--- + +# Memory and context + +OpenSearch provides intelligent memory and context management systems that enable AI agents to maintain persistent knowledge and conversation context across sessions. + +## Memory systems + +OpenSearch offers two complementary memory approaches: + +- **[Agentic memory]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agentic-memory/)**: An intelligent memory system that uses large language models (LLMs) to extract insights, learn user preferences, and maintain contextual knowledge across agent interactions. + +- **[Context management]({{site.url}}{{site.baseurl}}/ml-commons-plugin/context-management/)**: A structured approach to managing conversation context and system state for AI agents and applications. + +## Related APIs + +For programmatic access to memory and context features, see: + +- **[Agentic Memory APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/agentic-memory-apis/)**: Complete API reference for managing memory containers, sessions, and memories. +- **[Context Management APIs]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/context-management-apis/)**: API reference for creating and managing conversation contexts. diff --git a/_ml-commons-plugin/ml-dashboard.md b/_ml-commons-plugin/ml-dashboard.md index 3195aff8..2908d297 100644 --- a/_ml-commons-plugin/ml-dashboard.md +++ b/_ml-commons-plugin/ml-dashboard.md @@ -1,20 +1,21 @@ --- layout: default title: Managing ML models in OpenSearch Dashboards +parent: Integrating ML models nav_order: 120 redirect_from: - /ml-commons-plugin/ml-dashbaord/ --- # Managing ML models in OpenSearch Dashboards -**Generally available 2.9** +**Introduced 2.9** {: .label .label-purple } Administrators of machine learning (ML) clusters can use OpenSearch Dashboards to manage and check the status of ML models running inside a cluster. This can help ML developers provision nodes to ensure their models run efficiently. You can register and deploy models using the API only. For more information, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-serving-framework/). -## Enabling ML in Dashboards +## Enabling ML in OpenSearch Dashboards In OpenSearch 2.6, ML functionality is disabled by default. To enable it, you need to edit the configuration in `opensearch_dashboards.yml` and then restart your cluster. @@ -22,15 +23,15 @@ To enable the feature: 1. In your OpenSearch cluster, navigate to your Dashboards home directory; for example, in Docker, `/usr/share/opensearch-dashboards`. 2. Open your local copy of the Dashboards configuration file `opensearch_dashboards.yml`. If you don't have a copy, get one from GitHub: [`opensearch_dashboards.yml`](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/config/opensearch_dashboards.yml). -3. Add the setting `ml_commons_dashboards.enabled:` to `opensearch_dashboards.yml`. Then, set it to `ml_commons_dashboards.enabled: true` and save the configuration file. +3. Add the setting `ml_commons_dashboards.enabled:` to `opensearch_dashboards.yml`. Then, set it to `ml_commons_dashboards.enabled: true` and save the configuration file. 4. Restart the Dashboards container. 5. Verify that the feature configuration settings were created and configured properly by launching OpenSearch Dashboards. The Machine Learning section should appear under **OpenSearch plugins**. -## Accessing ML functionality in Dashboards +## Accessing ML functionality in OpenSearch Dashboards -To access ML functionality in OpenSearch Dashboards,select **OpenSearch plugins** > **Machine Learning**. +To access ML functionality in OpenSearch Dashboards, select **OpenSearch plugins** > **Machine Learning**. -<img src="{{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/ml-dashboard.png" alt="Machine Learning section in OpenSearch dashboards"> +![Machine Learning section in OpenSearch dashboards]({{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/ml-dashboard.png) In the Machine Learning section, you now have access to the **Deployed models** dashboard. @@ -38,21 +39,21 @@ In the Machine Learning section, you now have access to the **Deployed models** The deployed models dashboard gives admins the ability to check the status of any models stored inside your OpenSearch cluster. -<img src="{{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/deployed-models.png" alt="The deployed models view."> +![The deployed models view.]({{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/deployed-models.png) The dashboard includes the following information about the model: - **Name**: The name of the model given upon upload. - **Status**: The number of nodes for which the model responds. - When all nodes are responsive, the status is **Green**. - - When some nodes are responsive,the status is **Yellow**. - - When all nodes are unresponsive,the status is **Red**. + - When some nodes are responsive, the status is **Yellow**. + - When all nodes are unresponsive, the status is **Red**. - **Model ID**: The model ID. - **Action**: What actions you can take with the model. -As of OpenSearch 2.6, the only action available is **View Status Details**, shown in the following image. +The only available action is **View Status Details**, shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/view-status-details.png" alt="You can view status details under actions."> +![You can view status details under actions.]({{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/view-status-details.png) When selected, the Status Details panel appears. @@ -63,7 +64,7 @@ The panel provides the following details inside the panel: A list of nodes gives you a view of each node the model is running on, including each node’s **Node ID** and status, as shown in the following image. This is useful if you want to use the node's **Node ID** to determine why a node is unresponsive. -<img src="{{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/model-node-details.png" alt="The status of each node running the model."> +![The status of each node running the model.]({{site.url}}{{site.baseurl}}/images/ml/ml-dashboard/model-node-details.png) ## Next steps diff --git a/_ml-commons-plugin/model-access-control.md b/_ml-commons-plugin/model-access-control.md index 91d134cb..4bb8a0c4 100644 --- a/_ml-commons-plugin/model-access-control.md +++ b/_ml-commons-plugin/model-access-control.md @@ -47,7 +47,7 @@ If any of the prerequisites are not met, all models in the cluster are `public` ## Assigning backend roles to users -Create the appropriate backend roles and assign those roles to users. Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/), but if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/access-control/api#create-user). +Create the appropriate backend roles and assign those roles to users. Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/), but if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/api/users/create-user/). Only admin users can assign backend roles to users. {: .note} @@ -57,33 +57,35 @@ When assigning backend roles, consider the following example of two users: `alic The following request assigns the user `alice` the `analyst` backend role: ```json -PUT _plugins/_security/api/internalusers/alice +PUT /_plugins/_security/api/internalusers/alice { - "password": "alice", + "password": "Str0ngPassw0rd_5521!", "backend_roles": [ "analyst" ], "attributes": {} } ``` +{% include copy-curl.html security=true %} The next request assigns the user `bob` the `human-resources` backend role: ```json -PUT _plugins/_security/api/internalusers/bob +PUT /_plugins/_security/api/internalusers/bob { - "password": "bob", + "password": "Str0ngPassw0rd_6630!", "backend_roles": [ "human-resources" ], "attributes": {} } ``` +{% include copy-curl.html security=true %} Finally, the last request assigns both `alice` and `bob` the role that gives them full access to ML Commons: ```json -PUT _plugins/_security/api/rolesmapping/ml_full_access +PUT /_plugins/_security/api/rolesmapping/ml_full_access { "backend_roles": [], "hosts": [], @@ -93,6 +95,7 @@ PUT _plugins/_security/api/rolesmapping/ml_full_access ] } ``` +{% include copy-curl.html security=true %} If `alice` creates a model group and assigns it the `analyst` backend role, `bob` cannot access this model. @@ -157,8 +160,8 @@ curl -k --cert ./kirk.pem --key ./kirk-key.pem -X POST 'https://localhost:9200/_ "headers": { "content-type": "application/json" }, - "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-v2/invoke", - "request_body": "{\"prompt\":\"\\n\\nHuman: ${parameters.inputs}\\n\\nAssistant:\",\"max_tokens_to_sample\":300,\"temperature\":0.5,\"top_k\":250,\"top_p\":1,\"stop_sequences\":[\"\\\\n\\\\nHuman:\"]}" + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "request_body": "{\"anthropic_version\":\"bedrock-2023-05-31\",\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.inputs}\"}],\"max_tokens\":300,\"temperature\":0.5,\"top_k\":250}" } ] } @@ -166,10 +169,10 @@ curl -k --cert ./kirk.pem --key ./kirk-key.pem -X POST 'https://localhost:9200/_ ``` {% include copy.html %} -Once a hidden model is registered, only a superadmin can invoke operations on the model, including the deploy, undeploy, delete, and get API operations. For example, to deploy a hidden model, send the following request. In this request, `q7wLt4sBaDRBsUkl9BJV` is the model ID: +Once a hidden model is registered, only a superadmin can invoke operations on the model, including the deploy, undeploy, delete, and get API operations. For example, to deploy a hidden model, send the following request. In this request, `OPENSEARCH_ASSISTANT_MODEL` is the model ID: -```json -curl -k --cert ./kirk.pem --key ./kirk-key.pem -X POST 'https://localhost:9200/_plugins/_ml/models/q7wLt4sBaDRBsUkl9BJV/_deploy' +```bash +curl -k --cert ./kirk.pem --key ./kirk-key.pem -X POST 'https://localhost:9200/_plugins/_ml/models/OPENSEARCH_ASSISTANT_MODEL/_deploy' ``` {% include copy.html %} diff --git a/_ml-commons-plugin/model-sharing-access-control.md b/_ml-commons-plugin/model-sharing-access-control.md new file mode 100644 index 00000000..22d07708 --- /dev/null +++ b/_ml-commons-plugin/model-sharing-access-control.md @@ -0,0 +1,132 @@ +--- +layout: default +title: Model access control through resource sharing +parent: Integrating ML models +has_children: false +nav_order: 30 +--- + +# Model access control through resource sharing + +In ML Commons, access to models is controlled through [model groups]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/#model-groups)---collections of versions of a particular model that share the same access permissions. ML Commons integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for these model group resources. + +This resource sharing approach is the new method for controlling model group access and provides more flexible sharing capabilities than the [original model access control system]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). Resource owners can grant specific access levels to users, roles, or backend roles for individual model groups. + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +The following table describes the machine learning (ML) model group resource configuration. + +| Field | Value | +| :--- | :--- | +| Resource type | `ml-model-group` | +| System index | `.plugins-ml-model-group` | +| Onboarded version | OpenSearch 3.3 | + +When resource-level authorization is enabled for ML model groups, each model group's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +## Enable ML model group resource sharing + +To enable resource sharing for ML model groups, you must add the ml-model-group resource type to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for ML model groups: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "ml-model-group" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["ml-model-group"] + } +} +``` +{% include copy-curl.html %} + +When adding the ml-model-group resource type to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## ML model group access levels + +ML Commons provides three predefined access levels for ML model group documents. These access levels determine the specific permissions granted to users who have been granted access to a model group resource. + +### ml_read_only + +The `ml_read_only` read-only access level grants users the ability to view and search shared ML model groups but not modify them. This access level includes the following permissions: + +```yaml +- "cluster:admin/opensearch/ml/model_groups/get" +- "cluster:admin/opensearch/ml/models/get" +``` +{% include copy.html %} + +### ml_read_write + +The `ml_read_write` read-write access level grants users full access to ML model group operations except for sharing capabilities. This access level includes all read permissions plus write operations: + +```yaml +- "cluster:admin/opensearch/ml/*" +``` +{% include copy.html %} + +### ml_full_access + +The `ml_full_access` full access level grants users complete control over an ML model group, including owner-like permissions such as sharing the resource with other users. This access level includes all ML model group operations plus resource sharing permissions: + +```yaml +- "cluster:admin/opensearch/ml/*" +- "cluster:admin/security/resource/share" +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [ML Commons GitHub repository](https://github.com/opensearch-project/ml-commons/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking ML model groups as a protected resource type, cluster administrators must run the migration API to transfer existing model group sharing information from the legacy framework to the new resource sharing system. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Use the following API call to migrate legacy ML model group sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".plugins-ml-model-group", + "username_path": "/owner/name", + "backend_roles_path": "/owner/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "ml-model-group": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own ML model groups without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available ML model group access levels: `ml_read_only`, `ml_read_write`, or `ml_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance \ No newline at end of file diff --git a/_ml-commons-plugin/opensearch-assistant.md b/_ml-commons-plugin/opensearch-assistant.md index 3a8e0c87..4fd036f1 100644 --- a/_ml-commons-plugin/opensearch-assistant.md +++ b/_ml-commons-plugin/opensearch-assistant.md @@ -3,21 +3,18 @@ layout: default title: OpenSearch Assistant Toolkit has_children: false has_toc: false -nav_order: 28 +nav_order: 50 --- # OpenSearch Assistant Toolkit -**Introduced 2.12** +**Introduced 2.13** {: .label .label-purple } -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [OpenSearch forum thread](https://forum.opensearch.org/t/feedback-opensearch-assistant/16741). -{: .warning} - The OpenSearch Assistant Toolkit helps you create AI-powered assistants for OpenSearch Dashboards. The toolkit includes the following elements: - [**Agents and tools**]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/index/): _Agents_ interface with a large language model (LLM) and execute high-level tasks, such as summarization or generating Piped Processing Language (PPL) queries from natural language. The agent's high-level tasks consist of low-level tasks called _tools_, which can be reused by multiple agents. -- [**Configuration automation**]({{site.url}}{{site.baseurl}}/automating-configurations/index/): Uses templates to set up infrastructure for artificial intelligence and machine learning (AI/ML) applications. For example, you can automate configuring agents to be used for chat or generating PPL queries from natural language. -- [**OpenSearch Assistant for OpenSearch Dashboards**]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/index/): This is the OpenSearch Dashboards UI for the AI-powered assistant. The assistant's workflow is configured with various agents and tools. +- [**AI search workflows**]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/index/): Uses templates to set up infrastructure for artificial intelligence and machine learning (AI/ML) applications. For example, you can create the model, ingest pipeline, and vector index for semantic search in a single request. +- [**OpenSearch Assistant for OpenSearch Dashboards**]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/index/): This is the OpenSearch Dashboards web-based interface for the AI-powered assistant. The assistant's workflow is configured with various agents and tools. ## Enabling OpenSearch Assistant @@ -36,8 +33,6 @@ To enable OpenSearch Assistant, perform the following steps: ``` {% include copy.html %} -For more information about ways to enable experimental features, see [Experimental feature flags]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/experimental/). - ## Next steps - For more information about the OpenSearch Assistant UI, see [OpenSearch Assistant for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboards-assistant/index/) \ No newline at end of file diff --git a/_ml-commons-plugin/pretrained-models.md b/_ml-commons-plugin/pretrained-models.md index c68f9c8b..12552ef6 100644 --- a/_ml-commons-plugin/pretrained-models.md +++ b/_ml-commons-plugin/pretrained-models.md @@ -3,11 +3,11 @@ layout: default title: Pretrained models parent: Using ML models within OpenSearch grand_parent: Integrating ML models -nav_order: 120 +nav_order: 10 --- # OpenSearch-provided pretrained models -**Generally available 2.9** +**Introduced 2.9** {: .label .label-purple } OpenSearch provides a variety of open-source pretrained models that can assist with a range of machine learning (ML) search and analytics use cases. You can upload any supported model to the OpenSearch cluster and use it locally. @@ -23,42 +23,56 @@ Running local models on the CentOS 7 operating system is not supported. Moreover Sentence transformer models map sentences and paragraphs across a dimensional dense vector space. The number of vectors depends on the type of model. You can use these models for use cases such as clustering or semantic search. -The following table provides a list of sentence transformer models and artifact links you can use to download them. Note that you must prefix the model name with `huggingface/`, as shown in the **Model name** column. +The following table provides a list of sentence transformer models and artifact links you can use to download them. Note that you must prefix the model name with `huggingface/`, as shown in the **Model name** column. + +**Token limits and truncation**: Text embedding models have maximum token limits (typically 512 tokens for BERT-based models). When a document exceeds this limit, the model automatically truncates the text, and the truncated content is not represented in the embeddings. This can significantly impact search relevance because documents may not be returned in search results if the relevant content was truncated. To avoid this issue, split long documents into smaller chunks before generating embeddings. +{: .warning} | Model name | Version | Vector dimensions | Auto-truncation | TorchScript artifact | ONNX artifact | |:---|:---|:---|:---|:---|:---| -| `huggingface/sentence-transformers/all-distilroberta-v1` | 1.0.1 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.1/torch_script/sentence-transformers_all-distilroberta-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.1/onnx/sentence-transformers_all-distilroberta-v1-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/all-MiniLM-L6-v2` | 1.0.1 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.1/torch_script/sentence-transformers_all-MiniLM-L6-v2-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.1/onnx/sentence-transformers_all-MiniLM-L6-v2-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/all-MiniLM-L12-v2` | 1.0.1 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.1/torch_script/sentence-transformers_all-MiniLM-L12-v2-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.1/onnx/sentence-transformers_all-MiniLM-L12-v2-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/all-mpnet-base-v2` | 1.0.1 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.1/torch_script/sentence-transformers_all-mpnet-base-v2-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.1/onnx/sentence-transformers_all-mpnet-base-v2-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/msmarco-distilbert-base-tas-b` | 1.0.2 | 768-dimensional dense vector space. Optimized for semantic search. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.2/torch_script/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.2/onnx/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.2/onnx/config.json) | -| `huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1` | 1.0.1 | 384-dimensional dense vector space. Designed for semantic search and trained on 215 million question/answer pairs. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.1/torch_script/sentence-transformers_multi-qa-MiniLM-L6-cos-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.1/onnx/sentence-transformers_multi-qa-MiniLM-L6-cos-v1-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1` | 1.0.1 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.1/torch_script/sentence-transformers_multi-qa-mpnet-base-dot-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.1/onnx/sentence-transformers_multi-qa-mpnet-base-dot-v1-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2` | 1.0.1 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.1/torch_script/sentence-transformers_paraphrase-MiniLM-L3-v2-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.1/onnx/sentence-transformers_paraphrase-MiniLM-L3-v2-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 1.0.1 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.1/torch_script/sentence-transformers_paraphrase-multilingual-MiniLM-L12-v2-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.1/onnx/sentence-transformers_paraphrase-multilingual-MiniLM-L12-v2-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.1/onnx/config.json) | -| `huggingface/sentence-transformers/paraphrase-mpnet-base-v2` | 1.0.0 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.0/torch_script/sentence-transformers_paraphrase-mpnet-base-v2-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.0/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.0/onnx/sentence-transformers_paraphrase-mpnet-base-v2-1.0.0-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.0/onnx/config.json) | -| `huggingface/sentence-transformers/distiluse-base-multilingual-cased-v1` | 1.0.1 | 512-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/distiluse-base-multilingual-cased-v1/1.0.1/torch_script/sentence-transformers_distiluse-base-multilingual-cased-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/distiluse-base-multilingual-cased-v1/1.0.1/torch_script/config.json) | Not available | +| `huggingface/sentence-transformers/all-distilroberta-v1` | 1.0.2 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.2/torch_script/sentence-transformers_all-distilroberta-v1-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.2/onnx/sentence-transformers_all-distilroberta-v1-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-distilroberta-v1/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/all-MiniLM-L6-v2` | 1.0.2 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.2/torch_script/sentence-transformers_all-MiniLM-L6-v2-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.2/onnx/sentence-transformers_all-MiniLM-L6-v2-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L6-v2/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/all-MiniLM-L12-v2` | 1.0.2 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.2/torch_script/sentence-transformers_all-MiniLM-L12-v2-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.2/onnx/sentence-transformers_all-MiniLM-L12-v2-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-MiniLM-L12-v2/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/all-mpnet-base-v2` | 1.0.2 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.2/torch_script/sentence-transformers_all-mpnet-base-v2-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.2/onnx/sentence-transformers_all-mpnet-base-v2-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/all-mpnet-base-v2/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/msmarco-distilbert-base-tas-b` | 1.0.3 | 768-dimensional dense vector space. Optimized for semantic search. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.3/torch_script/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.3-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.3/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.3/onnx/sentence-transformers_msmarco-distilbert-base-tas-b-1.0.3-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/msmarco-distilbert-base-tas-b/1.0.3/onnx/config.json) | +| `huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1` | 1.0.2 | 384-dimensional dense vector space. Designed for semantic search and trained on 215 million question/answer pairs. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.2/torch_script/sentence-transformers_multi-qa-MiniLM-L6-cos-v1-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.2/onnx/sentence-transformers_multi-qa-MiniLM-L6-cos-v1-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-MiniLM-L6-cos-v1/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1` | 1.0.2 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.2/torch_script/sentence-transformers_multi-qa-mpnet-base-dot-v1-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.2/onnx/sentence-transformers_multi-qa-mpnet-base-dot-v1-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/multi-qa-mpnet-base-dot-v1/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2` | 1.0.2 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.2/torch_script/sentence-transformers_paraphrase-MiniLM-L3-v2-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.2/onnx/sentence-transformers_paraphrase-MiniLM-L3-v2-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-MiniLM-L3-v2/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 1.0.2 | 384-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.2/torch_script/sentence-transformers_paraphrase-multilingual-MiniLM-L12-v2-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.2/onnx/sentence-transformers_paraphrase-multilingual-MiniLM-L12-v2-1.0.2-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/1.0.2/onnx/config.json) | +| `huggingface/sentence-transformers/paraphrase-mpnet-base-v2` | 1.0.1 | 768-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.1/torch_script/sentence-transformers_paraphrase-mpnet-base-v2-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.1/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.1/onnx/sentence-transformers_paraphrase-mpnet-base-v2-1.0.1-onnx.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/paraphrase-mpnet-base-v2/1.0.1/onnx/config.json) | +| `huggingface/sentence-transformers/distiluse-base-multilingual-cased-v1` | 1.0.2 | 512-dimensional dense vector space. | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/distiluse-base-multilingual-cased-v1/1.0.2/torch_script/sentence-transformers_distiluse-base-multilingual-cased-v1-1.0.2-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/sentence-transformers/distiluse-base-multilingual-cased-v1/1.0.2/torch_script/config.json) | Not available | ### Sparse encoding models **Introduced 2.11** {: .label .label-purple } -Sparse encoding models transfer text into a sparse vector and convert the vector to a list of `<token: weight>` pairs representing the text entry and its corresponding weight in the sparse vector. You can use these models for use cases such as clustering or sparse neural search. +Sparse encoding models transfer text into a sparse vector and convert the vector to a list of `<token: weight>` pairs representing the text entry and its corresponding weight in the sparse vector. You can use these models for use cases such as clustering or neural sparse search. -We recommend the following models for optimal performance: +We recommend the following combinations for optimal performance: -- Use the `amazon/neural-sparse/opensearch-neural-sparse-encoding-v1` model during both ingestion and search. -- Use the `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1` model during ingestion and the -`amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1` model during search. +- Use the `amazon/neural-sparse/opensearch-neural-sparse-encoding-v2-distill` model during both ingestion and search. +- Use the `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-gte` model during ingestion and the +`amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1` tokenizer during search. + +Both `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-distill` and `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-gte` are pruned with a maximum value ratio of 0.1, providing an improved trade-off between retrieval performance and index size. + +For more information about the preceding options for running neural sparse search, see [Generating sparse vector embeddings automatically]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-with-pipelines/). The following table provides a list of sparse encoding models and artifact links you can use to download them. | Model name | Version | Auto-truncation | TorchScript artifact | Description | |:---|:---|:---|:---|:---| -| `amazon/neural-sparse/opensearch-neural-sparse-encoding-v1` | 1.0.1 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-v1/1.0.1/torch_script/neural-sparse_opensearch-neural-sparse-encoding-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-v1/1.0.1/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [HuggingFace documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v1). | -| `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1` | 1.0.1 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1/1.0.1/torch_script/neural-sparse_opensearch-neural-sparse-encoding-doc-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1/1.0.1/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [HuggingFace documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v1). | -| `amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1` | 1.0.1 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1/1.0.1/torch_script/neural-sparse_opensearch-neural-sparse-tokenizer-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1/1.0.1/torch_script/config.json) | A neural sparse tokenizer model. The model tokenizes text into tokens and assigns each token a predefined weight, which is the token's inverse document frequency (IDF). If the IDF file is not provided, the weight defaults to 1. For more information, see [Preparing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/#preparing-a-model). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-v1` | 1.0.1 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-v1/1.0.1/torch_script/neural-sparse_opensearch-neural-sparse-encoding-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-v1/1.0.1/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v1). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-v2-distill` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-v2-distill/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-encoding-v2-distill-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-v2-distill/1.0.0/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v2-distill). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1` | 1.0.1 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1/1.0.1/torch_script/neural-sparse_opensearch-neural-sparse-encoding-doc-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v1/1.0.1/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v1). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v2-distill` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v2-distill/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-encoding-doc-v2-distill-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v2-distill/1.0.0/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v2-distill). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v2-mini` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v2-mini/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-encoding-doc-v2-mini-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v2-mini/1.0.0/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v2-mini). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-distill` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-distill/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-encoding-doc-v3-distill-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-distill/1.0.0/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v3-distill). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-gte` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-gte/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-encoding-doc-v3-gte-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-doc-v3-gte/1.0.0/torch_script/config.json) | A neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-doc-v3-gte). | +| `amazon/neural-sparse/opensearch-neural-sparse-encoding-multilingual-v1` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-multilingual-v1/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-encoding-multilingual-v1-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-encoding-multilingual-v1/1.0.0/torch_script/config.json) | A multilingual neural sparse encoding model. The model transforms text into a sparse vector, identifies the indexes of non-zero elements in the vector, and then converts the vector into `<entry, weight>` pairs, where each entry corresponds to a non-zero element index. To experiment with this model using transformers and the PyTorch API, see the [Hugging Face documentation](https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-multilingual-v1). | +| `amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1` | 1.0.1 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1/1.0.1/torch_script/neural-sparse_opensearch-neural-sparse-tokenizer-v1-1.0.1-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-v1/1.0.1/torch_script/config.json) | A neural sparse tokenizer. The tokenizer splits text into tokens and assigns each token a predefined weight, which is the token's inverse document frequency (IDF). If the IDF file is not provided, the weight defaults to 1. For more information, see [Preparing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/#preparing-a-model). | +| `amazon/neural-sparse/opensearch-neural-sparse-tokenizer-multilingual-v1` | 1.0.0 | Yes | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-multilingual-v1/1.0.0/torch_script/neural-sparse_opensearch-neural-sparse-tokenizer-multilingual-v1-1.0.0-torch_script.zip)<br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/neural-sparse/opensearch-neural-sparse-tokenizer-multilingual-v1/1.0.0/torch_script/config.json) | A multilingual neural sparse tokenizer. The tokenizer splits text into tokens and assigns each token a predefined weight, which is the token's inverse document frequency (IDF). If the IDF file is not provided, the weight defaults to 1. For more information, see [Preparing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/#preparing-a-model). | ### Cross-encoder models **Introduced 2.12** @@ -71,7 +85,22 @@ The following table provides a list of cross-encoder models and artifact links y | Model name | Version | TorchScript artifact | ONNX artifact | |:---|:---|:---|:---| | `huggingface/cross-encoders/ms-marco-MiniLM-L-6-v2` | 1.0.2 | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-6-v2/1.0.2/torch_script/cross-encoders_ms-marco-MiniLM-L-6-v2-1.0.2-torch_script.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-6-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-6-v2/1.0.2/onnx/cross-encoders_ms-marco-MiniLM-L-6-v2-1.0.2-onnx.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-6-v2/1.0.2/onnx/config.json) | -| `huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2` | 1.0.2 | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/torch_script/cross-encoders_ms-marco-MiniLM-L-12-v2-1.0.2-torch_script.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/onnx/cross-encoders_ms-marco-MiniLM-L-12-v2-1.0.2-onnx.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/onnx/config.json) +| `huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2` | 1.0.2 | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/torch_script/cross-encoders_ms-marco-MiniLM-L-12-v2-1.0.2-torch_script.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/torch_script/config.json) | - [model_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/onnx/cross-encoders_ms-marco-MiniLM-L-12-v2-1.0.2-onnx.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/huggingface/cross-encoders/ms-marco-MiniLM-L-12-v2/1.0.2/onnx/config.json) + +### Semantic sentence highlighting models +**Introduced 3.0** +{: .label .label-purple } + +Semantic sentence highlighting models are specifically designed to work with the [`semantic` highlighter]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/#the-semantic-highlighter). These models analyze document text and identify the sentences that are most semantically relevant to the search query. + +For a tutorial on using these models with the semantic highlighter, see [Using semantic highlighting]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-highlighting-tutorial/). + +The following table provides a list of semantic sentence highlighting models and artifact links you can use to download them. Note that you must prefix the model name with `amazon/`, as shown in the **Model name** column. + +| Model name | Version | TorchScript artifact | Description | +|:---|:---|:---|:---| +| `amazon/sentence-highlighting/opensearch-semantic-highlighter-v1` | 1.0.0 | - [model_url](https://artifacts.opensearch.org/models/ml-models/amazon/sentence-highlighting/opensearch-semantic-highlighter-v1/1.0.0/torch_script/sentence-highlighting_opensearch-semantic-highlighter-v1-1.0.0-torch_script.zip) <br>- [config_url](https://artifacts.opensearch.org/models/ml-models/amazon/sentence-highlighting/opensearch-semantic-highlighter-v1/1.0.0/torch_script/config.json) | A model optimized for identifying semantically relevant sentences to be highlighted. | + ## Prerequisites @@ -83,13 +112,9 @@ This example uses a simple setup with no dedicated ML nodes and allows running a PUT _cluster/settings { "persistent": { - "plugins": { - "ml_commons": { - "only_run_on_ml_node": "false", - "model_access_control_enabled": "true", - "native_memory_threshold": "99" - } - } + "plugins.ml_commons.only_run_on_ml_node": "false", + "plugins.ml_commons.model_access_control_enabled": "true", + "plugins.ml_commons.native_memory_threshold": "99" } } ``` @@ -126,7 +151,7 @@ To learn more about model groups, see [Model access control]({{site.url}}{{site. ## Step 2: Register a local OpenSearch-provided model -To register a remote model to the model group created in step 1, provide the model group ID from step 1 in the following request. +To register an OpenSearch-provided model to the model group created in step 1, provide the model group ID from step 1 in the following request. Because pretrained models originate from the ML Commons model repository, you only need to provide the `name`, `version`, `model_group_id`, and `model_format` in the register API request: @@ -134,8 +159,8 @@ Because pretrained models originate from the ML Commons model repository, you on POST /_plugins/_ml/models/_register { "name": "huggingface/sentence-transformers/msmarco-distilbert-base-tas-b", - "version": "1.0.2", - "model_group_id": "Z1eQf4oB5Vm0Tdw8EIP2", + "version": "1.0.3", + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", "model_format": "TORCH_SCRIPT" } ``` @@ -150,9 +175,9 @@ OpenSearch returns the task ID of the register operation: } ``` -To check the status of the operation, provide the task ID to the [Tasks API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): -```bash +```json GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj ``` {% include copy-curl.html %} @@ -163,26 +188,26 @@ When the operation is complete, the state changes to `COMPLETED`: { "model_id": "cleMb4kBJ1eYAeTMFFg4", "task_type": "REGISTER_MODEL", - "function_name": "REMOTE", + "function_name": "TEXT_EMBEDDING", "state": "COMPLETED", "worker_node": [ "XPcXLV7RQoi5m8NI_jEOVQ" ], "create_time": 1689793598499, "last_update_time": 1689793598530, - "is_async": false + "is_async": true } ``` -Take note of the returned `model_id` because you’ll need it to deploy the model. +Take note of the returned `model_id` because you'll need it to deploy the model. ## Step 3: Deploy the model The deploy operation reads the model's chunks from the model index and then creates an instance of the model to load into memory. The bigger the model, the more chunks the model is split into and longer it takes for the model to load into memory. -To deploy the registered model, provide its model ID from step 3 in the following request: +To deploy the registered model, provide its model ID from step 2 in the following request: -```bash +```json POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_deploy ``` {% include copy-curl.html %} @@ -192,13 +217,14 @@ The response contains the task ID that you can use to check the status of the de ```json { "task_id": "vVePb4kBJ1eYAeTM7ljG", + "task_type": "DEPLOY_MODEL", "status": "CREATED" } ``` -As in the previous step, check the status of the operation by calling the Tasks API: +As in the previous step, check the status of the operation by calling the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): -```bash +```json GET /_plugins/_ml/tasks/vVePb4kBJ1eYAeTM7ljG ``` {% include copy-curl.html %} @@ -209,7 +235,7 @@ When the operation is complete, the state changes to `COMPLETED`: { "model_id": "cleMb4kBJ1eYAeTMFFg4", "task_type": "DEPLOY_MODEL", - "function_name": "REMOTE", + "function_name": "TEXT_EMBEDDING", "state": "COMPLETED", "worker_node": [ "n-72khvBTBi3bnIIR8FTTw" @@ -220,7 +246,7 @@ When the operation is complete, the state changes to `COMPLETED`: } ``` -If a cluster or node is restarted, then you need to redeploy the model. To learn how to set up automatic redeployment, see [Enable auto redeploy]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#enable-auto-redeploy). +If a cluster or node is restarted, then you need to redeploy the model. To learn how to set up automatic redeployment, see [Model deployment settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#model-deployment-settings). {: .tip} ## Step 4 (Optional): Test the model @@ -267,9 +293,9 @@ The response contains text embeddings for the provided sentence: } ``` -### Sparse encoding model +### Sparse encoding model or sparse tokenizer -For a sparse encoding model, send the following request: +For a sparse encoding model or sparse tokenizer, send the following request: ```json POST /_plugins/_ml/_predict/sparse_encoding/cleMb4kBJ1eYAeTMFFg4 @@ -279,7 +305,7 @@ POST /_plugins/_ml/_predict/sparse_encoding/cleMb4kBJ1eYAeTMFFg4 ``` {% include copy-curl.html %} -The response contains the tokens and weights: +The response contains the extracted tokens and their corresponding weights: ```json { @@ -298,9 +324,49 @@ The response contains the tokens and weights: "bright": 0.1756877, ... } + ] } } + ] } + ] +} +``` + +The preceding example uses the default `lexical` output format, which returns strings as keys. You can control the output key format by setting `parameters.sparse_embedding_format` to `lexical` (returns string tokens) or `token_id` (returns integer token IDs). The following example sets the `sparse_embedding_format` to `token_id`: + +```json +POST /_plugins/_ml/_predict/sparse_encoding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs": ["hello world"], + "parameters": { + "sparse_embedding_format": "token_id" + } +} +``` +{% include copy-curl.html %} + +The response contains the token IDs and their corresponding token weights: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "output", + "dataAsMap": { + "response": [ + { + "2088": 3.4208686, + "7592": 6.9377565 + } + ] + } + } + ] + } + ] } ``` @@ -309,7 +375,7 @@ The response contains the tokens and weights: For a cross-encoder model, send the following request: ```json -POST _plugins/_ml/models/<model_id>/_predict +POST _plugins/_ml/models/{model_id}/_predict { "query_text": "today is sunny", "text_docs": [ diff --git a/_ml-commons-plugin/processor-chain.md b/_ml-commons-plugin/processor-chain.md new file mode 100644 index 00000000..20c8bfb5 --- /dev/null +++ b/_ml-commons-plugin/processor-chain.md @@ -0,0 +1,671 @@ +--- +layout: default +title: Processor chains +has_children: false +nav_order: 40 +--- + +# Processor chains +**Introduced 3.3** +{: .label .label-purple } + +Processor chains enable flexible data transformation pipelines that can process both input and output data. Chain multiple processors together to create sequential transformations where each processor's output becomes the next processor's input. + +Processors provide a way to: + +- **Transform data formats**: Convert between different data structures (strings, JSON, arrays). +- **Extract specific information**: Use JSONPath or regex patterns to extract relevant data. +- **Clean and filter content**: Remove unwanted fields or apply formatting rules. +- **Standardize data**: Ensure consistent data formats across different components. + +Processors execute in the order in which they appear in the array. Each processor receives the output from the previous processor. +{: .note} + +Processor chains are specifically designed for ML workflows and differ from processors in ingest and search pipelines: + +- [**Ingest pipelines**]({{site.url}}{{site.baseurl}}/ingest-pipelines/): Transform documents during indexing into OpenSearch. +- [**Search pipelines**]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/): Transform queries and search results during search operations. +- **Processor chains**: Transform data within ML Commons workflows (agent tools, model inputs/outputs). + +Processor chains provide specialized data transformation capabilities tailored for AI/ML use cases, such as cleaning model responses, extracting structured data from LLM outputs, and preparing inputs for model inference. + +## Configuration + +Processors can be configured in different contexts: + +- **Tool outputs**: Add an `output_processors` array in the tool's `parameters` section. +- **Model outputs**: Add an `output_processors` array in the model's `parameters` section during a `_predict` call. +- **Model inputs**: Add an `input_processors` array in the model's `parameters` section of a `_predict` call. + +For complete examples, see [Example usage with agents](#example-usage-with-agents) and [Example usage with models](#example-usage-with-models). + +## Supported processor types + +The following table lists all supported processors. + +Processor | Description +:--- | :--- +[`conditional`](#conditional) | Applies different processor chains based on conditions. +[`extract_json`](#extract_json) | Extracts JSON objects or arrays from text strings. +[`for_each`](#for_each) | Iterates through array elements and applies a chain of processors to each element. +[`jsonpath_filter`](#jsonpath_filter) | Extracts data using JSONPath expressions. +[`process_and_set`](#process_and_set) | Applies a chain of processors to the input and sets the result at a specified JSONPath location. +[`regex_capture`](#regex_capture) | Captures specific groups from regex matches. +[`regex_replace`](#regex_replace) | Replaces text using regular expression patterns. +[`remove_jsonpath`](#remove_jsonpath) | Removes fields from JSON objects using JSONPath. +[`set_field`](#set_field) | Sets a field to a specified static value or copies a value from another field. +[`to_string`](#to_string) | Converts the input to a JSON string representation. + +### Conditional + +Applies different processor chains based on conditions. + +**Parameters**: + +- `path` (string, optional): The JSONPath expression used to extract the value for condition evaluation. +- `routes` (array, required): An array of condition-processor mappings. +- `default` (array, optional): The default processors if no conditions match. + +**Supported conditions**: + +- Exact value match: `"value"` +- Numeric comparisons: `">10"`, `"<5"`, `">="`, `"<="`, `"==5"` +- Existence checks: `"exists"`, `"null"`, `"not_exists"` +- Regex matching: `"regex:pattern"` +- Contains text: `"contains:substring"` + +**Example configuration**: + +```json +{ + "type": "conditional", + "path": "$.status", + "routes": [ + { + "green": [ + {"type": "regex_replace", "pattern": "status", "replacement": "healthy"} + ] + }, + { + "red": [ + {"type": "regex_replace", "pattern": "status", "replacement": "unhealthy"} + ] + } + ], + "default": [ + {"type": "regex_replace", "pattern": "status", "replacement": "unknown"} + ] +} +``` + +**Example input**: + +```json +{"index": "test-index", "status": "green", "docs": 100} +``` + +**Example output**: + +```json +{"index": "test-index", "healthy": "green", "docs": 100} +``` + +### extract_json + +Extracts JSON objects or arrays from text strings. + +**Parameters**: + +- `extract_type` (string, optional): The type of JSON to extract: `"object"`, `"array"`, or `"auto"`. Default is `"auto"`. +- `default` (any, optional): The default value if JSON extraction fails. + +**Example configuration**: + +```json +{ + "type": "extract_json", + "extract_type": "object", + "default": {} +} +``` + +**Example input**: + +```json +"The result is: {\"status\": \"success\", \"count\": 5} - processing complete" +``` + +**Example output**: + +```json +{"status": "success", "count": 5} +``` + +### for_each + +Iterates through array elements and applies a chain of processors to each element. Useful for transforming array elements uniformly, such as when adding missing fields, filtering content, or normalizing data structures. + +**Parameters**: + +- `path` (string, required): The JSONPath expression pointing to the array to iterate over. Must use `[*]` notation for array elements. +- `processors` (array, required): A list of processor configurations to apply to each array element. + +**Behavior**: + +- Each element is processed independently using the configured processor chain. +- The output of the processor chain replaces the original element. +- If the path doesn't exist or doesn't point to an array, the input is returned unchanged. +- If the processing of an element fails, the original element is kept. + +**Example configuration**: + +```json +{ + "type": "for_each", + "path": "$.items[*]", + "processors": [ + { + "type": "set_field", + "path": "$.processed", + "value": true + } + ] +} +``` + +**Example input**: + +```json +{ + "items": [ + {"name": "item1", "value": 10}, + {"name": "item2", "value": 20} + ] +} +``` + +**Example output**: + +```json +{ + "items": [ + {"name": "item1", "value": 10, "processed": true}, + {"name": "item2", "value": 20, "processed": true} + ] +} +``` + +### jsonpath_filter + +Extracts data using JSONPath expressions. + +**Parameters**: + +- `path` (string, required): The JSONPath expression used to extract data. +- `default` (any, optional): The default value if the path is not found. + +**Example configuration**: + +```json +{ + "type": "jsonpath_filter", + "path": "$.data.items[*].name", + "default": [] +} +``` + +**Example input**: + +```json +{"data": {"items": [{"name": "item1"}, {"name": "item2"}]}} +``` + +**Example output**: + +```json +["item1", "item2"] +``` + +### process_and_set + +Applies a chain of processors to the input and sets the result at a specified JSONPath location. + +**Parameters**: + +- `path` (string, required): The JSONPath expression specifying where to set the processed result. +- `processors` (array, required): A list of processor configurations to apply sequentially. + +**Path behavior**: + +- If the path exists, it will be updated with the processed value. +- If the path doesn't exist, the processor chain attempts to create it (works for simple nested fields). +- A parent path must exist for new field creation to succeed. + +**Example configuration**: + +```json +{ + "type": "process_and_set", + "path": "$.summary.clean_name", + "processors": [ + { + "type": "to_string" + }, + { + "type": "regex_replace", + "pattern": "[^a-zA-Z0-9]", + "replacement": "_" + } + ] +} +``` + +**Example input**: + +```json +{"name": "Test Index!", "status": "active"} +``` + +**Example output**: + +```json +{"name": "Test Index!", "status": "active", "summary": {"clean_name": "Test_Index_"}} +``` + +### regex_capture + +Captures specific groups from the first regex match in the input. If the pattern doesn't match, the input is returned unchanged. For regex syntax details, see [Java regex syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). + +**Parameters**: + +- `pattern` (string, required): A regular expression pattern with capture groups. +- `groups` (string or array, optional): Group numbers to capture. Can be a single number like `"1"` or array like `"[1, 2, 4]"`. Default is `"1"`. + +**Example configuration**: + +```json +{ + "type": "regex_capture", + "pattern": "(\\d+),(\\w+),(\\w+),([^,]+)", + "groups": "[1, 4]" +} +``` + +**Example input**: + +```json +"1,green,open,.plugins-ml-model-group,DCJHJc7pQ6Gid02PaSeXBQ,1,0" +``` + +**Example output**: + +```json +["1", ".plugins-ml-model-group"] +``` + +### regex_replace + +Replaces text using regular expression patterns. For regex syntax details, see [Java regex syntax](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). + +**Parameters**: +- `pattern` (string, required): A regular expression pattern to match. +- `replacement` (string, optional): Replacement text. Default is `""`. +- `replace_all` (Boolean, optional): Whether to replace all matches or only the first. Default is `true`. + +**Example configuration**: + +```json +{ + "type": "regex_replace", + "pattern": "^.*?\n", + "replacement": "" +} +``` + +**Example input**: + +```json +"row,health,status,index\n1,green,open,.plugins-ml-model\n2,red,closed,test-index" +``` + +**Example output**: + +```json +"1,green,open,.plugins-ml-model\n2,red,closed,test-index" +``` + +### remove_jsonpath + +Removes fields from JSON objects using JSONPath. + +**Parameters**: + +- `paths` (array, required): An array of JSONPath expressions identifying fields to remove. + +**Example configuration**: + +```json +{ + "type": "remove_jsonpath", + "paths": ["$.sensitive_data"] +} +``` + +**Example input**: + +```json +{"name": "user1", "sensitive_data": "secret", "public_info": "visible"} +``` + +**Example output**: + +```json +{"name": "user1", "public_info": "visible"} +``` + +### set_field + +Sets a field to a specified static value or copies a value from another field. + +**Parameters**: + +- `path` (string, required): The JSONPath expression specifying where to set the value. +- `value` (any, conditionally required): The static value to set. Either `value` or `source_path` must be provided. +- `source_path` (string, conditionally required): The JSONPath expression to copy the value from. Either `value` or `source_path` must be provided. +- `default` (any, optional): The default value when `source_path` doesn't exist. Only used with `source_path`. + +**Path behavior**: + +- If the path exists, it will be updated with the new value. +- If the path doesn't exist, the processor chain attempts to create it (works for simple nested fields). +- A parent path must exist for new field creation to succeed. + +**Example configuration (static value)**: + +```json +{ + "type": "set_field", + "path": "$.metadata.processed_at", + "value": "2024-03-15T10:30:00Z" +} +``` + +**Example configuration (copy field)**: + +```json +{ + "type": "set_field", + "path": "$.userId", + "source_path": "$.user.id", + "default": "unknown" +} +``` + +**Example input**: + +```json +{"user": {"id": 123}, "name": "John"} +``` + +**Example output**: + +```json +{"user": {"id": 123}, "name": "John", "userId": 123, "metadata": {"processed_at": "2024-03-15T10:30:00Z"}} +``` + +### to_string + +Converts the input to a JSON string representation. + +**Parameters**: + +- `escape_json` (Boolean, optional): Whether to escape JSON characters. Default is `false`. + +**Example configuration**: + +```json +{ + "type": "to_string", + "escape_json": true +} +``` + +**Example input**: + +```json +{"name": "test", "value": 123} +``` + +**Example output**: + +```json +"{\"name\":\"test\",\"value\":123}" +``` + +## Example usage with agents + +The following example demonstrates using processor chains with agents. + +### Step 1: Register a flow agent with output processors + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Index Summary Agent", + "type": "flow", + "description": "Agent that provides clean index summaries", + "tools": [ + { + "type": "ListIndexTool", + "parameters": { + "output_processors": [ + { + "type": "regex_replace", + "pattern": "^.*?\n", + "replacement": "" + }, + { + "type": "regex_replace", + "pattern": "(\\d+,\\w+,\\w+,[^,\n]+)[^\n]*", + "replacement": "$1" + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2: Execute the agent + +Using the `agent_id` returned in the previous step: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "parameters": { + "question": "List the indices" + } +} +``` +{% include copy-curl.html %} + +Without output processors, the raw `ListIndexTool` returns verbose CSV output with headers and extra columns: + +```cs +row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,.plugins-ml-model-group,DCJHJc7pQ6Gid02PaSeXBQ,1,0,1,0,12.7kb,12.7kb +2,green,open,.plugins-ml-memory-message,6qVpepfRSCi9bQF_As_t2A,1,0,7,0,53kb,53kb +3,green,open,.plugins-ml-memory-meta,LqP3QMaURNKYDZ9p8dTq3Q,1,0,2,0,44.8kb,44.8kb +``` + +The output processors transform the verbose CSV output into a clean, readable format by: + +1. **`regex_replace`**: Removing the CSV header row. +2. **`regex_replace`**: Keeping only the row number, health, status, and index name in each row. The pattern captures the first four columns of a row and matches the rest of the row, and the replacement `$1` replaces the whole row with the captured columns. Because `replace_all` defaults to `true`, every row is processed. + +With output processors, the agent returns one line for each index: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "1,green,open,.plugins-ml-model-group\n2,green,open,.plugins-ml-memory-message\n3,green,open,.plugins-ml-memory-meta\n" + } + ] + } + ] +} +``` + +## Example usage with models + +The following examples demonstrate how to use processor chains with models during Predict API calls. + +### Example: Input processors + +This example shows you how to modify model input using `input_processors` to replace text before processing: + +```json +POST _plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "system_prompt": "You are a helpful assistant.", + "prompt": "Can you summarize Prince Hamlet of William Shakespeare in around 100 words?", + "input_processors": [ + { + "type": "regex_replace", + "pattern": "100", + "replacement": "20" + } + ] + } +} +``` +{% include copy-curl.html %} + +In this example, the `regex_replace` processor modifies the prompt before it's sent to the model, changing "100 words" to "20 words". + +### Example: Output processors + +This example shows you how to process model output using `output_processors` to extract and format JSON data. In this example, the output processors first extract the content from the model response using JSONPath. Then they parse and extract the JSON object from the text response: + +```json +POST _plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "messages": [ + { + "role": "system", + "content": [ + { + "type": "text", + "text": "${parameters.system_prompt}" + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "Can you convert this into a json object: user name is Bob, he likes swimming" + } + ] + } + ], + "system_prompt": "You are a helpful assistant", + "output_processors": [ + { + "type": "jsonpath_filter", + "path": "$.choices[0].message.content" + }, + { + "type": "extract_json", + "extract_type": "auto" + } + ] + } +} +``` +{% include copy-curl.html %} + +Without output processors, the raw response contains the full model output with extensive metadata and a nested structure: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "id": "test-id", + "object": "chat.completion", + "created": 1.759580469E9, + "model": "gpt-4o-mini-2024-07-18", + "choices": [ + { + "index": 0.0, + "message": { + "role": "assistant", + "content": "Sure! Here is the information you provided converted into a JSON object:\n\n```json\n{\n \"user\": {\n \"name\": \"Bob\",\n \"likes\": \"swimming\"\n }\n}\n```", + "refusal": null, + "annotations": [] + }, + "logprobs": null, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 33.0, + "completion_tokens": 42.0, + "total_tokens": 75.0, + "prompt_tokens_details": { + "cached_tokens": 0.0, + "audio_tokens": 0.0 + }, + "completion_tokens_details": { + "reasoning_tokens": 0.0, + "audio_tokens": 0.0, + "accepted_prediction_tokens": 0.0, + "rejected_prediction_tokens": 0.0 + } + }, + "service_tier": "default", + "system_fingerprint": "test-fingerprint" + } + } + ], + "status_code": 200 + } + ] +} +``` + +With output processors, the response is simplified to contain only the extracted and parsed JSON data: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "user": { + "name": "Bob", + "likes": "swimming" + } + } + } + ], + "status_code": 200 + } + ] +} +``` diff --git a/_ml-commons-plugin/remote-models/aws-sigv4.md b/_ml-commons-plugin/remote-models/aws-sigv4.md new file mode 100644 index 00000000..16aa69dc --- /dev/null +++ b/_ml-commons-plugin/remote-models/aws-sigv4.md @@ -0,0 +1,70 @@ +--- +layout: default +title: AWS Signature Version 4 authentication +has_children: false +nav_order: 50 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +--- + +# AWS Signature Version 4 authentication + +Connectors that use the `aws_sigv4` protocol sign each request with AWS Signature Version 4. AWS services, such as Amazon SageMaker, Amazon Bedrock, Amazon Comprehend, and Amazon Textract, use this protocol. The protocol signs each request with the credentials that you provide and adds the required `Authorization` header, so you don't need to specify one. + +The following request creates a standalone connector that uses the `aws_sigv4` protocol. It shows the `credential` and `parameters` fields that the protocol requires. The `url` and `request_body` fields are specific to the service and model that you're calling: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "sagemaker: embedding", + "description": "Connector for a SageMaker embedding model", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<access_key>", + "secret_key": "<secret_key>", + "session_token": "<session_token>" + }, + "parameters": { + "region": "us-west-2", + "service_name": "sagemaker" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://runtime.sagemaker.${parameters.region}.amazonaws.com/endpoints/<endpoint_name>/invocations", + "request_body": "[\"${parameters.inputs}\"]" + } + ] +} +``` +{% include copy-curl.html %} + +For a complete request for your service and model, including the `url`, `request_body`, and any processing functions, see the blueprint for your platform and model in [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). + +## Request body fields + +When `protocol` is set to `aws_sigv4`, the `credential` object supports the following fields. + +| Field | Data type | Required/Optional | Description | +|:---|:---|:---|:---| +| `access_key` | String | Required | The access key for the AWS account. | +| `secret_key` | String | Required | The secret key for the AWS account. | +| `session_token` | String | Optional | A temporary session token for the AWS account. | + +When `protocol` is set to `aws_sigv4`, the `parameters` object supports the following fields. + +| Field | Data type | Required/Optional | Description | +|:---|:---|:---|:---| +| `region` | String | Required | The AWS Region in which the service is hosted. | +| `service_name` | String | Required | The name of the AWS service that the connector calls. | + +## Next steps + +- To find the blueprint for your service and model, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). +- To register and deploy a model that uses this connector, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). diff --git a/_ml-commons-plugin/remote-models/batch-ingestion.md b/_ml-commons-plugin/remote-models/batch-ingestion.md new file mode 100644 index 00000000..87dbcaee --- /dev/null +++ b/_ml-commons-plugin/remote-models/batch-ingestion.md @@ -0,0 +1,260 @@ +--- +layout: default +title: Batch ingestion +has_children: false +has_toc: false +nav_order: 80 +parent: Connecting to externally hosted models +grand_parent: Integrating ML models +redirect_from: + - /ml-commons-plugin/remote-models/async-batch-ingestion/ + - /ml-commons-plugin/api/async-batch-ingest/ +--- + +# Using externally hosted ML models for batch ingestion + +**Introduced 2.15** +{: .label .label-purple } + +If you are ingesting multiple documents and generating embeddings by invoking an externally hosted model, you can use batch ingestion to improve performance. + +When using the [Bulk API]({{site.url}}{{site.baseurl}}/api-reference/document-apis/bulk/) to ingest documents, processors that support batch ingestion will split documents into batches and send each batch of documents to an externally hosted model in a single request. + +The [`text_embedding`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/text-embedding/) and [`sparse_encoding`]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/sparse-encoding/) processors support batch ingestion. + + +## Step 1: Register a model group + +You can register a model in two ways: + +* You can use `model_group_id` to register a model version to an existing model group. +* If you do not use `model_group_id`, then OpenSearch creates a model with a new model group. + +To register a model group, send the following request: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "remote_model_group", + "description": "A model group for external models" +} +``` +{% include copy-curl.html %} + +The response contains the model group ID that you'll use to register a model to this model group: + +```json +{ + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "status": "CREATED" +} +``` + +To learn more about model groups, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). + +## Step 2: Create a connector + +You can create a standalone connector that can be reused by multiple model registrations in OpenSearch that share the same external endpoint and configuration. Alternatively, you can specify a connector when creating a model so that it can be used only for that model. For more information and example connectors, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). + +The Connectors Create API, `/_plugins/_ml/connectors/_create`, creates connectors that facilitate registering and deploying external models in OpenSearch. Using the `endpoint` parameter, you can connect OpenSearch to any supported ML tool by using its specific API endpoint. For example, you can connect to an OpenAI text embedding model by using the `api.openai.com` endpoint: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI embedding connector", + "description": "The connector to the public OpenAI model service for text-embedding-ada-002", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "text-embedding-ada-002", + "input_docs_processed_step_size": 100 + }, + "credential": { + "openAI_key": "<openai_api_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/v1/embeddings", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input\": ${parameters.input}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.openai.embedding", + "post_process_function": "connector.post_process.openai.embedding" + } + ] +} +``` +{% include copy-curl.html %} + +The `parameters.input_docs_processed_step_size` parameter is used to set the maximum batch size for documents sent to a remote server. You can set this parameter to the maximum batch size supported by the remote server or to a smaller number for optimal performance. + +The response contains the connector ID for the newly created connector: + +```json +{ + "connector_id": "a1eMb4kBJ1eYAeTMAljY" +} +``` + +## Step 3: Register an externally hosted model + +To register an externally hosted model to the model group created in step 1, provide the model group ID from step 1 and the connector ID from step 2 in the following request. You must specify the `function_name` as `remote`: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "openAI-text-embedding-ada-002", + "function_name": "remote", + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "description": "test model", + "connector_id": "a1eMb4kBJ1eYAeTMAljY" +} +``` +{% include copy-curl.html %} + +OpenSearch returns the task ID of the register operation: + +```json +{ + "task_id": "cVeMb4kBJ1eYAeTMFFgj", + "status": "CREATED", + "model_id": "cleMb4kBJ1eYAeTMFFg4" +} +``` + +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): + +```json +GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj +``` +{% include copy-curl.html %} + +When the operation is complete, the state changes to `COMPLETED`: + +```json +{ + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "XPcXLV7RQoi5m8NI_jEOVQ" + ], + "create_time": 1689793598499, + "last_update_time": 1689793598530, + "is_async": false +} +``` + +Take note of the returned `model_id` because you’ll need it to deploy the model. + +## Step 4: Deploy the model + +Externally hosted models are deployed automatically when you send a Predict API request for the first time. To disable automatic deployment for an externally hosted model, set `plugins.ml_commons.model_auto_deploy.enable` to `false`: + +```json +PUT _cluster/settings +{ + "persistent": { + "plugins.ml_commons.model_auto_deploy.enable" : "false" + } +} +``` +{% include copy-curl.html %} + +To deploy the model manually, use the [Deploy API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/deploy-model/): + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_deploy +``` +{% include copy-curl.html %} + +The response contains the task ID, which you can use to check the status of the deploy operation: + +```json +{ + "task_id": "vVePb4kBJ1eYAeTM7ljG", + "task_type": "DEPLOY_MODEL", + "status": "COMPLETED" +} +``` + +As in the previous step, check the status of the operation by calling the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): + +```json +GET /_plugins/_ml/tasks/vVePb4kBJ1eYAeTM7ljG +``` +{% include copy-curl.html %} + +When the operation is complete, the state changes to `COMPLETED`: + +```json +{ + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "task_type": "DEPLOY_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "n-72khvBTBi3bnIIR8FTTw" + ], + "create_time": 1689793851077, + "last_update_time": 1689793851101, + "is_async": true +} +``` + +## Step 5: Create an ingest pipeline + +The following example request creates an ingest pipeline with a `text_embedding` processor. The processor converts the text in the `passage_text` field into text embeddings and stores the embeddings in `passage_embedding`: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline +{ + "description": "A text embedding pipeline", + "processors": [ + { + "text_embedding": { + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "field_map": { + "passage_text": "passage_embedding" + }, + "batch_size": 5 + } + } + ] +} +``` +{% include copy-curl.html %} + +## Step 6: Perform bulk indexing + +To ingest documents in bulk, call the Bulk API and provide the `pipeline` parameter. If you don't provide a `pipeline` parameter, then the default ingest pipeline for the index will be used for ingestion. The following request uses the pipeline created in the previous step, whose `text_embedding` processor has a `batch_size` of `5`, so the documents are sent to the model in batches of 5: + +```json +POST _bulk?pipeline=nlp-ingest-pipeline +{ "create": { "_index": "testindex1", "_id": "2" } } +{ "passage_text": "hello world" } +{ "create": { "_index": "testindex1", "_id": "3" } } +{ "passage_text": "big apple" } +{ "create": { "_index": "testindex1", "_id": "4" } } +{ "passage_text": "golden gate bridge" } +{ "create": { "_index": "testindex1", "_id": "5" } } +{ "passage_text": "fine tune" } +{ "create": { "_index": "testindex1", "_id": "6" } } +{ "passage_text": "random test" } +{ "create": { "_index": "testindex1", "_id": "7" } } +{ "passage_text": "sun and moon" } +{ "create": { "_index": "testindex1", "_id": "8" } } +{ "passage_text": "windy" } +{ "create": { "_index": "testindex1", "_id": "9" } } +{ "passage_text": "new york" } +{ "create": { "_index": "testindex1", "_id": "10" } } +{ "passage_text": "fantastic" } + +``` +{% include copy-curl.html %} + diff --git a/_ml-commons-plugin/remote-models/batching-requests.md b/_ml-commons-plugin/remote-models/batching-requests.md new file mode 100644 index 00000000..c3b0e373 --- /dev/null +++ b/_ml-commons-plugin/remote-models/batching-requests.md @@ -0,0 +1,195 @@ +--- +layout: default +title: Request batching +has_children: false +nav_order: 85 +parent: Connecting to externally hosted models +grand_parent: Integrating ML models +--- + +# Batching requests to externally hosted models +**Introduced 3.9** +{: .label .label-purple } + +OpenSearch provides two techniques for controlling how prediction requests are grouped into calls to an externally hosted model: + +- Large prediction requests can be split so that each call to the model stays within the model endpoint's limits. + +- Small prediction requests can be combined into fewer calls to the model, which increases throughput at the cost of a short wait before each call. + +Both techniques are optional and disabled by default, and both operate on input strings. An input string is one string in the `text_docs` array of a prediction request, such as the text of one document field during ingestion or the query text during search. + +You configure both techniques in the `batch_inference_config` parameter when you register the model. For field descriptions and default values, see [The `batch_inference_config` parameter]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-batch_inference_config-parameter). + +These techniques work only for externally hosted models whose [connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/) accepts text document (`text_docs`) input and produces one result for each input string in the same order. A model configured with the `batch_inference_config` parameter rejects prediction requests that use another input type. + +## Splitting large prediction requests + +Use request splitting when the input strings in one prediction request can exceed the model endpoint's limit on the number or combined size of input strings. This pattern is common during bulk ingestion because an [ingest processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/index-processors/) can send many documents in one prediction request. + +### Choosing the size limits + +Set `max_items_per_request`, `max_bytes_per_request`, or both. Use the [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/) to identify the provider and exact model used by the connector. Obtain the limits from the provider's official documentation for the exact model and version, or from the model server configuration for a custom endpoint. + +The `max_items_per_request` parameter limits the number of input strings in each call to the model, and `max_bytes_per_request` limits their combined size in bytes. OpenSearch measures the size of each input string as its UTF-8 byte length. The byte limit counts only the input strings. The request sent to the model also contains the other fields defined in the connector's `request_body` template, so set `max_bytes_per_request` lower than the model's actual limit to leave room for them. + +To change the `batch_inference_config` settings later, use the [Update Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/update-model/). OpenSearch stores `batch_inference_config` on the registered model, so ingest pipelines, Bulk API requests, and queries that use the model don't require any changes. + +### Splitting rules + +OpenSearch splits the `text_docs` array of a prediction request into consecutive groups of input strings, keeping the original order, and sends each group to the model in a separate call. OpenSearch adds input strings to the current call until the next input string would exceed `max_items_per_request` or `max_bytes_per_request` and then starts a new call. A call can reach a limit exactly. For example, consider the following configuration and input sizes: + +```text +max_items_per_request = 3 +max_bytes_per_request = 10 +input sizes in bytes = [4, 3, 5, 2] +``` + +OpenSearch creates the following calls to the model: + +```text +Call 1: [4, 3] +Call 2: [5, 2] +``` + +Adding the 5-byte input string to the first call would produce 12 bytes, so OpenSearch starts the second call. Both calls also remain within the limit of three input strings. + +If the original request already fits within the limits, OpenSearch sends it as a single call to the model. If an individual input string is larger than `max_bytes_per_request`, OpenSearch sends that input string unchanged, and the model endpoint might reject it. + +OpenSearch waits for all calls to the model created from the original prediction request. If all calls succeed, OpenSearch combines their outputs in the original input order. If any call fails, the original prediction request fails and doesn't return a partial result. + +For information about configuring retry and backoff settings for failed calls, see [The client_config object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#the-client_config-object). + +### Configuring request splitting + +To configure request splitting for batch ingestion, follow these steps. + +#### Step 1: Register the ingestion model + +Register an externally hosted model and provide the `batch_inference_config` parameter in the [model registration request]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/). The following request configures request splitting without dynamic batching: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "remote-embedding-model-for-ingest", + "function_name": "remote", + "connector_id": "<connector_id>", + "batch_inference_config": { + "max_items_per_request": 96, + "max_bytes_per_request": 4000000 + } +} +``` +{% include copy-curl.html %} + +The registration request returns a task ID and model ID. Use the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/) to wait for the task to reach the `COMPLETED` state before using the model ID. + +#### Step 2: Add the model to an ingest pipeline + +Use the model ID in an ingest processor. The processor's `batch_size` sets the number of documents in each prediction request, and the model's limits then split each prediction request into calls to the model. The following example configures a [`text_embedding` processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/text-embedding/) that sends up to 100 documents in each prediction request. Because the model registered in Step 1 sets `max_items_per_request` to `96`, OpenSearch splits each of these requests into calls containing no more than 96 input strings: + +```json +PUT /_ingest/pipeline/embedding-pipeline +{ + "processors": [ + { + "text_embedding": { + "model_id": "<ingest_model_id>", + "field_map": { + "passage_text": "passage_embedding" + }, + "batch_size": 100 + } + } + ] +} +``` +{% include copy-curl.html %} + +#### Step 3: Run batch ingestion + +Use the pipeline with the Bulk API as described in [Batch ingestion]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/batch-ingestion/). + +## Dynamically batching small prediction requests + +Dynamic batching is useful when many small prediction requests for the same model arrive close together. This pattern is common during search because each [neural query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/) typically produces a prediction request containing one input string, the query text. + +To apply dynamic batching to search independently from ingestion, register separate model IDs for the two workloads and enable dynamic batching only on the search model. + +To enable dynamic batching, set `dynamic_batching.enabled` to `true`. You must also set `max_items_per_request`, `max_bytes_per_request`, or both. These limits set the maximum size of each batch call, so configure them to allow more than one input string per call to the model. For more information, see [Choosing the size limits](#choosing-the-size-limits). + +OpenSearch queues each prediction request on the node that processes it and invokes the model in batch when any of the following conditions is met: + +- The accumulated number of input strings reaches the configured `max_items_per_request` limit. +- The accumulated size of the input strings, in bytes, reaches the configured `max_bytes_per_request` limit. +- The time elapsed since the first request was received reaches `dynamic_batching.flush_timeout_ms`. + +When traffic is low and neither size limit is reached, the first request waits for the full `dynamic_batching.flush_timeout_ms` value. Setting the value to `10000`, for example, can add 10 seconds before the model is invoked. + +### Batching scope and resource usage + +Each batch belongs to one model ID on one node: + +- Requests that use different model IDs don't share a batch, even when both models reference the same connector. +- Requests for the same model that are routed to different nodes enter different batches. +- Requests for the same model and node share a batch. Within that batch, OpenSearch groups requests whose prediction input fields are all identical except `text_docs`. For direct [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) calls, the endpoint, including `{algorithm_name}` and `{model_id}`, must also be identical. Each group is sent as a separate batch request to the model. + +All models on a node share the memory available for queued requests. A batch retains memory while it waits for additional requests and while its call to the model is in progress. If this memory is exhausted, OpenSearch rejects new requests before calling the model endpoint. For information about the memory settings, see [Dynamic batching memory settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#dynamic-batching-memory-settings). + +### Response routing + +OpenSearch routes each output to the request and position that supplied the corresponding input. If a call to the model returns a different number of results than the number of input strings it contained, OpenSearch can't route the outputs, and the affected requests fail. + +### Configuring dynamic batching for search + +To configure dynamic batching for search, follow these steps. + +#### Step 1: Register a search model with dynamic batching enabled + +Register the search model with the endpoint limits and provide a `dynamic_batching` parameter: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "remote-embedding-model-for-search", + "function_name": "remote", + "connector_id": "<connector_id>", + "batch_inference_config": { + "max_items_per_request": 96, + "max_bytes_per_request": 4000000, + "dynamic_batching": { + "enabled": true, + "flush_timeout_ms": 50 + } + } +} +``` +{% include copy-curl.html %} + +The registration request returns a task ID and a separate model ID for search. + +#### Step 2: Use the model to generate query embeddings + +After the registration task reaches the `COMPLETED` state, use the search model ID in all requests that generate query embeddings. The following example specifies the search model ID in a [neural query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/) for a `knn_vector` field: + +```json +GET /my-index/_search +{ + "query": { + "neural": { + "passage_embedding": { + "query_text": "How does remote inference batching work?", + "model_id": "<search_model_id>", + "k": 10 + } + } + } +} +``` +{% include copy-curl.html %} + +## Related documentation + +- [Sparse encoding processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/sparse-encoding/) +- [Neural sparse query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural-sparse/) +- [Semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/semantic-search/) \ No newline at end of file diff --git a/_ml-commons-plugin/remote-models/blueprints.md b/_ml-commons-plugin/remote-models/blueprints.md index 57e0e417..2ee41e04 100644 --- a/_ml-commons-plugin/remote-models/blueprints.md +++ b/_ml-commons-plugin/remote-models/blueprints.md @@ -1,225 +1,195 @@ --- layout: default -title: Connector blueprints +title: Creating a custom blueprint has_children: false -nav_order: 65 -parent: Connecting to externally hosted models -grand_parent: Integrating ML models -redirect_from: +nav_order: 20 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +redirect_from: - /ml-commons-plugin/extensibility/blueprints/ --- -# Connector blueprints +# Creating a custom blueprint **Introduced 2.9** {: .label .label-purple } -Every [connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/) is specified by a _connector blueprint_. The blueprint defines all the parameters you need to provide when creating a connector. +If OpenSearch doesn't provide a [connector blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/) for your model, create your own. A blueprint is a connector definition for a specific model that contains the model endpoint, the credentials, and a template for the request body that OpenSearch sends to the model. -For example, the following blueprint is a specification for an Amazon SageMaker connector: +To create a custom blueprint, follow these steps: + +1. [Identify the model API format](#step-1-identify-the-model-api-format). +1. [Define the connector action](#step-2-define-the-connector-action). +1. [Choose pre- and post-processing functions](#step-3-choose-pre--and-post-processing-functions). +1. [Create and test the connector](#step-4-create-and-test-the-connector). + +The examples on this page connect to a hypothetical embedding service at `https://embeddings.example.com` for which OpenSearch doesn't provide a blueprint. + +## Step 1: Identify the model API format + +From the model provider documentation, determine the following information: + +- The endpoint URL and HTTP method +- How the API authenticates requests, for example, using an API key in a header +- The request body format +- The response body format + +For example, the embedding service accepts `POST` requests at `https://embeddings.example.com/v1/embed`, authenticates them using an `Authorization: Bearer <api_key>` header, and accepts the following request body: + +```json +{ + "texts": ["red shoes", "blue hat"], + "model": "my-embedding-model" +} +``` + +The service returns one embedding for each string in the following response body: + +```json +{ + "vectors": [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]], + "model": "my-embedding-model" +} +``` + +OpenSearch sends connector requests only to trusted endpoints. Add a pattern for the endpoint, such as `^https://embeddings\.example\.com/.*$`, to the `plugins.ml_commons.trusted_connector_endpoints_regex` setting. For more information, see [Adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#adding-trusted-endpoints). + +## Step 2: Define the connector action + +In the connector `actions` array, define a `predict` action that describes the request to the model API: + +- In `url` and `method`, specify the endpoint and the HTTP method. +- In `headers`, specify the authentication header. Refer to credentials using `${credential.<credential_name>}` placeholders, and provide the credential values in the connector `credential` object. +- In `request_body`, specify a template for the request body. Use `${parameters.<parameter_name>}` placeholders for values that change with each request, and provide default values in the connector `parameters` object. + +For the embedding service, the action and the related connector fields are the following: ```json { - "name": "<YOUR CONNECTOR NAME>", - "description": "<YOUR CONNECTOR DESCRIPTION>", - "version": "<YOUR CONNECTOR VERSION>", - "protocol": "aws_sigv4", - "credential": { - "access_key": "<YOUR AWS ACCESS KEY>", - "secret_key": "<YOUR AWS SECRET KEY>", - "session_token": "<YOUR AWS SECURITY TOKEN>" - }, "parameters": { - "region": "<YOUR AWS REGION>", - "service_name": "sagemaker" + "model": "my-embedding-model" + }, + "credential": { + "api_key": "<api_key>" }, "actions": [ { "action_type": "predict", "method": "POST", + "url": "https://embeddings.example.com/v1/embed", "headers": { - "content-type": "application/json" + "Authorization": "Bearer ${credential.api_key}" }, - "url": "<YOUR SAGEMAKER MODEL ENDPOINT URL>", - "request_body": "<YOUR REQUEST BODY. Example: ${parameters.inputs}>" + "request_body": "{ \"texts\": ${parameters.texts}, \"model\": \"${parameters.model}\" }" } ] } ``` -{% include copy-curl.html %} -## OpenSearch-provided connector blueprints +The `texts` placeholder isn't enclosed in quotation marks because its value is an array. For more information about placeholders, see [Request body templates]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#request-body-templates). For descriptions of all connector fields, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). -OpenSearch provides connector blueprints for several machine learning (ML) platforms and models. For a list of all connector blueprints provided by OpenSearch, see [Supported connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#supported-connectors). +## Step 3: Choose pre- and post-processing functions -As an ML developer, you can build connector blueprints for other platforms. Using those blueprints, administrators and data scientists can create connectors for models hosted on those platforms. +Embedding and rerank features, such as the `text_embedding` ingest processor, the `neural` query, and the `rerank` search processor, send their input in a fixed format and require a specific output format. To use the model with these features, the connector must define a preprocessing function that converts the input into parameters and a post-processing function that converts the model response into the format that OpenSearch requires. If you call the model only using Predict API requests or the `ml_inference` processor, which provide input as parameters, skip this step. -## Configuration parameters +First, check whether a built-in function supports the model format. For more information, see [Built-in pre- and post-processing functions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#built-in-pre--and-post-processing-functions). The embedding service request body contains a `texts` array, which the built-in `connector.pre_process.cohere.embedding` function produces. No built-in post-processing function reads the `vectors` field, so the connector uses the following custom post-processing function: -The following configuration parameters are **required** in order to build a connector blueprint. +```js +def sb = new StringBuilder("["); +for (int i = 0; i < params.vectors.size(); i++) { + if (i > 0) { sb.append(","); } + def v = params.vectors[i]; + sb.append("{\"name\":\"sentence_embedding\",\"data_type\":\"FLOAT32\",\"shape\":[" + v.size() + "],\"data\":" + v + "}"); +} +sb.append("]"); +return sb.toString(); +``` -| Field | Data type | Description | -| :--- | :--- | :--- | -| `name` | String | The name of the connector. | -| `description` | String | A description of the connector. | -| `version` | Integer | The version of the connector. | -| `protocol` | String | The protocol for the connection. For AWS services such as Amazon SageMaker and Amazon Bedrock, use `aws_sigv4`. For all other services, use `http`. | -| `parameters` | JSON object | The default connector parameters, including `endpoint` and `model`. Any parameters indicated in this field can be overridden by parameters specified in a predict request. | -| `credential` | JSON object | Defines any credential variables required in order to connect to your chosen endpoint. ML Commons uses **AES/GCM/NoPadding** symmetric encryption to encrypt your credentials. When the connection to the cluster first starts, OpenSearch creates a random 32-byte encryption key that persists in OpenSearch's system index. Therefore, you do not need to manually set the encryption key. | -| `actions` | JSON array | Defines what actions can run within the connector. If you're an administrator creating a connection, add the [blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/) for your desired connection. | -| `backend_roles` | JSON array | A list of OpenSearch backend roles. For more information about setting up backend roles, see [Assigning backend roles to users]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#assigning-backend-roles-to-users). | -| `access_mode` | String | Sets the access mode for the model, either `public`, `restricted`, or `private`. Default is `private`. For more information about `access_mode`, see [Model groups]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control#model-groups). | -| `add_all_backend_roles` | Boolean | When set to `true`, adds all `backend_roles` to the access list, which only a user with admin permissions can adjust. When set to `false`, non-admins can add `backend_roles`. | +The function reads the `vectors` field of the model response from `params` and returns an output object for each embedding. For more information, see [Custom pre- and post-processing functions]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#custom-pre--and-post-processing-functions). -The `action` parameter supports the following options. +## Step 4: Create and test the connector -| Field | Data type | Description | -| :--- | :--- | :--- | -| `action_type` | String | Required. Sets the ML Commons API operation to use upon connection. As of OpenSearch 2.9, only `predict` is supported. | -| `method` | String | Required. Defines the HTTP method for the API call. Supports `POST` and `GET`. | -| `url` | String | Required. Sets the connection endpoint at which the action occurs. This must match the regex expression for the connection used when [adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index#adding-trusted-endpoints). | -| `headers` | JSON object | Sets the headers used inside the request or response body. Default is `ContentType: application/json`. If your third-party ML tool requires access control, define the required `credential` parameters in the `headers` parameter. | -| `request_body` | String | Required. Sets the parameters contained inside the request body of the action. The parameters must include `\"inputText\`, which specifies how users of the connector should construct the request payload for the `action_type`. | -| `pre_process_function` | String | Optional. A built-in or custom Painless script used to preprocess the input data. OpenSearch provides the following built-in preprocess functions that you can call directly:<br> - `connector.pre_process.cohere.embedding` for [Cohere](https://cohere.com/) embedding models<br> - `connector.pre_process.openai.embedding` for [OpenAI](https://openai.com/) embedding models <br> - `connector.pre_process.default.embedding`, which you can use to preprocess documents in neural search requests so that they are in the format that ML Commons can process with the default preprocessor (OpenSearch 2.11 or later). For more information, see [built-in functions](#built-in-pre--and-post-processing-functions). | -| `post_process_function` | String | Optional. A built-in or custom Painless script used to post-process the model output data. OpenSearch provides the following built-in post-process functions that you can call directly:<br> - `connector.pre_process.cohere.embedding` for [Cohere text embedding models](https://docs.cohere.com/reference/embed)<br> - `connector.pre_process.openai.embedding` for [OpenAI text embedding models](https://platform.openai.com/docs/api-reference/embeddings) <br> - `connector.post_process.default.embedding`, which you can use to post-process documents in the model response so that they are in the format that neural search expects (OpenSearch 2.11 or later). For more information, see [built-in functions](#built-in-pre--and-post-processing-functions). | - -## Built-in pre- and post-processing functions - -Call the built-in pre- and post-processing functions instead of writing a custom Painless script when connecting to the following text embedding models or your own text embedding models deployed on a remote server (for example, Amazon SageMaker): - -- [OpenAI models](https://platform.openai.com/docs/api-reference/embeddings) -- [Cohere models](https://docs.cohere.com/reference/embed) - -OpenSearch provides the following pre- and post-processing functions: - -- OpenAI: `connector.pre_process.openai.embedding` and `connector.post_process.openai.embedding` -- Cohere: `connector.pre_process.cohere.embedding` and `connector.post_process.cohere.embedding` -- [Amazon SageMaker default functions for neural search](#amazon-sagemaker-default-pre--and-post-processing-functions-for-neural-search): `connector.pre_process.default.embedding` and `connector.post_process.default.embedding` - -### Amazon SageMaker default pre- and post-processing functions for neural search - -When you perform vector search using [neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/), the neural search request is routed first to ML Commons and then to the model. If the model is one of the [pretrained models provided by OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/), it can parse the ML Commons request and return the response in the format that ML Commons expects. However, for a model hosted on an external platform, the expected format may be different from the ML Commons format. The default pre- and post-processing functions translate between the format that the model expects and the format that neural search expects. - -For the default functions to be applied, the model input and output must be in the format described in the following sections. - -#### Example request - -The following example request creates a SageMaker text embedding connector and calls the default post-processing function: +The following request creates a connector using the complete blueprint. The custom post-processing function is provided as a string: ```json POST /_plugins/_ml/connectors/_create { - "name": "Sagemaker text embedding connector", - "description": "The connector to Sagemaker", + "name": "Embedding service connector", + "description": "The connector to a custom embedding service", "version": 1, - "protocol": "aws_sigv4", - "credential": { - "access_key": "<YOUR SAGEMAKER ACCESS KEY>", - "secret_key": "<YOUR SAGEMAKER SECRET KEY>", - "session_token": "<YOUR AWS SECURITY TOKEN>" - }, + "protocol": "http", "parameters": { - "region": "ap-northeast-1", - "service_name": "sagemaker" + "model": "my-embedding-model" + }, + "credential": { + "api_key": "<api_key>" }, "actions": [ { "action_type": "predict", "method": "POST", - "url": "sagemaker.ap-northeast-1.amazonaws.com/endpoints/", + "url": "https://embeddings.example.com/v1/embed", "headers": { - "content-type": "application/json" + "Authorization": "Bearer ${credential.api_key}" }, - "post_process_function": "connector.post_process.default.embedding", - "request_body": "${parameters.input}" + "request_body": "{ \"texts\": ${parameters.texts}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.cohere.embedding", + "post_process_function": "def sb = new StringBuilder(\"[\");\nfor (int i = 0; i < params.vectors.size(); i++) {\n if (i > 0) { sb.append(\",\"); }\n def v = params.vectors[i];\n sb.append(\"{\\\"name\\\":\\\"sentence_embedding\\\",\\\"data_type\\\":\\\"FLOAT32\\\",\\\"shape\\\":[\" + v.size() + \"],\\\"data\\\":\" + v + \"}\");\n}\nsb.append(\"]\");\nreturn sb.toString();" } ] } ``` {% include copy-curl.html %} -The `request_body` template must be `${parameters.input}`. -{: .important} +If you use Python, you can also create the connector from your blueprint using the custom connector option of the [`opensearch-py-ml`](https://github.com/opensearch-project/opensearch-py-ml) CLI. For more information, see the [CLI documentation](https://opensearch-project.github.io/opensearch-py-ml/cli/index.html#). +{: .tip} -### Preprocessing function - -The `connector.pre_process.default.embedding` default preprocessing function parses the neural search request and transforms it into the format that the model expects as input. - -The ML Commons [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) provides parameters in the following format: +Register a model using the connector. For more information, see [Step 2: Register an externally hosted model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#step-2-register-an-externally-hosted-model). Then test the model using the input format that embedding features send: ```json +POST /_plugins/_ml/models/{model_id}/_predict?algorithm=text_embedding { - "parameters": { - "input": ["hello", "world"] - } + "text_docs": ["red shoes", "blue hat"] } ``` +{% include copy-curl.html %} -The default preprocessing function sends the `input` field contents to the model. Thus, the model input format must be a list of strings, for example: +The preprocessing function converts the strings into the `texts` parameter, and OpenSearch sends the following request body to the model: ```json -["hello", "world"] +{ "texts": ["red shoes","blue hat"], "model": "my-embedding-model" } ``` -### Post-processing function - -The `connector.post_process.default.embedding` default post-processing function parses the model response and transforms it into the format that neural search expects as input. - -The remote text embedding model output must be a two-dimensional float array, each element of which represents an embedding of a string from the input list. For example, the following two-dimensional array corresponds to the embedding of the list `["hello", "world"]`: +The post-processing function converts the model response. The Predict API response contains one embedding for each string: ```json -[ - [ - -0.048237994, - -0.07612697, - ... - ], - [ - 0.32621247, - 0.02328475, - ... - ] -] -``` - -## Custom pre- and post-processing functions - -You can write your own pre- and post-processing functions specifically for your model format. For example, the following Amazon Bedrock connector definition contains custom pre- and post-processing functions for the Amazon Bedrock Titan embedding model: - -```json -POST /_plugins/_ml/connectors/_create { - "name": "Amazon Bedrock Connector: embedding", - "description": "The connector to the Bedrock Titan embedding model", - "version": 1, - "protocol": "aws_sigv4", - "parameters": { - "region": "<YOUR AWS REGION>", - "service_name": "bedrock" - }, - "credential": { - "access_key": "<YOUR AWS ACCESS KEY>", - "secret_key": "<YOUR AWS SECRET KEY>", - "session_token": "<YOUR AWS SECURITY TOKEN>" - }, - "actions": [ + "inference_results": [ { - "action_type": "predict", - "method": "POST", - "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-embed-text-v1/invoke", - "headers": { - "content-type": "application/json", - "x-amz-content-sha256": "required" - }, - "request_body": "{ \"inputText\": \"${parameters.inputText}\" }", - "pre_process_function": "\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\\"\");\n String first = params.text_docs[0];\n builder.append(first);\n builder.append(\"\\\"\");\n def parameters = \"{\" +\"\\\"inputText\\\":\" + builder + \"}\";\n return \"{\" +\"\\\"parameters\\\":\" + parameters + \"}\";", - "post_process_function": "\n def name = \"sentence_embedding\";\n def dataType = \"FLOAT32\";\n if (params.embedding == null || params.embedding.length == 0) {\n return params.message;\n }\n def shape = [params.embedding.length];\n def json = \"{\" +\n \"\\\"name\\\":\\\"\" + name + \"\\\",\" +\n \"\\\"data_type\\\":\\\"\" + dataType + \"\\\",\" +\n \"\\\"shape\\\":\" + shape + \",\" +\n \"\\\"data\\\":\" + params.embedding +\n \"}\";\n return json;\n " + "output": [ + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [3], + "data": [0.1, 0.2, 0.3] + }, + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [3], + "data": [0.2, 0.2, 0.3] + } + ], + "status_code": 200 } ] } ``` -{% include copy-curl.html %} + +If the response contains `sentence_embedding` output objects, you can use the model with the `text_embedding` ingest processor and the `neural` query. ## Next steps -- To learn more about connecting to external models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). -- For connector examples, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). +- For descriptions of all connector fields, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). +- To learn how a connector builds the request that it sends to the model and processes the model response, see [Connector input and output]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/). +- To find an OpenSearch-provided blueprint, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). diff --git a/_ml-commons-plugin/remote-models/connector-authentication.md b/_ml-commons-plugin/remote-models/connector-authentication.md new file mode 100644 index 00000000..02ec25b6 --- /dev/null +++ b/_ml-commons-plugin/remote-models/connector-authentication.md @@ -0,0 +1,30 @@ +--- +layout: default +title: Connector authentication +has_children: false +nav_order: 30 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +--- + +# Connector authentication + +A connector authenticates to an externally hosted model using the values in its `credential` object. The authentication method is specified in the connector's `protocol` field and is determined by the platform you are connecting to. Each protocol has its own credential fields and cluster prerequisites. + +The following table lists the available protocols. + +| Protocol | Platforms | Documentation | +|:---|:---|:---| +| `http` | Platforms without a dedicated protocol, including OpenAI, Cohere, Azure OpenAI, DeepSeek, Ollama, Aleph Alpha, and Yandex Cloud | [HTTP authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | +| `aws_sigv4` | AWS services, such as Amazon SageMaker, Amazon Bedrock, Amazon Comprehend, and Amazon Textract | [AWS Signature Version 4 authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | +| `google_cloud` | Google Cloud Vertex AI | [Google Cloud authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/google-cloud/) | + +The `aws_sigv4` and `google_cloud` protocols generate and refresh short-lived access tokens for you, so you don't supply or rotate a token by hand. The `http` protocol passes the credentials you provide, most often a token such as an API key. To find the protocol for your platform and model, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). + +Endpoints that require mutual TLS (mTLS) accept a client certificate instead of a token. This applies only to connectors that use the `http` protocol. For more information, see [Client certificate authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/#client-certificate-authentication). + +## Next steps + +- For descriptions of all connector fields, including the `client_config` object, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). +- To change the credentials on an existing connector, see [Updating connector credentials]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#updating-connector-credentials). diff --git a/_ml-commons-plugin/remote-models/connector-input-output.md b/_ml-commons-plugin/remote-models/connector-input-output.md new file mode 100644 index 00000000..9151465f --- /dev/null +++ b/_ml-commons-plugin/remote-models/connector-input-output.md @@ -0,0 +1,519 @@ +--- +layout: default +title: Connector input and output +has_children: false +nav_order: 15 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +--- + +# Connector input and output +**Introduced 2.9** +{: .label .label-purple } + +A connector builds the request that OpenSearch sends to the model API and converts the model response into the format that OpenSearch requires. + +## Request body templates + +The following excerpt from a connector shows the fields that determine the request body. Each object in the `actions` array defines one operation that the connector supports. The `request_body` field is a template for the request body. The template contains placeholders in the format `${parameters.<parameter_name>}`. In this example, the template contains the `model` and `messages` placeholders: + +```json +{ + "parameters": { + "model": "gpt-4o-mini" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": ${parameters.messages} }" + } + ] +} +``` + +When you send a [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) request, OpenSearch replaces each placeholder with the corresponding parameter value and sends the result to the model. OpenSearch obtains parameter values from the Predict API request or, if the request doesn't provide the value, from the connector `parameters` object. In this example, `model` defaults to `gpt-4o-mini`, so a Predict API request must provide only `messages`. + +OpenSearch inserts each value into the template without adding quotation marks. Enclose a placeholder in quotation marks if its value is a string, as with `model` in the preceding example. Don't enclose a placeholder in quotation marks if its value is a number, a Boolean, or a JSON array or object, as with `messages`. OpenSearch escapes special characters, such as quotation marks, in string values provided in the Predict API request. For the exceptions, see the `parameters` field in [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/#request-body-fields). + +The `url` field can also contain parameter placeholders, for example, `"url": "https://${parameters.endpoint}/v1/chat/completions"`, where the connector `parameters` object provides the `endpoint` value. To use parameter placeholders in headers, see [Dynamic header substitution]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/dynamic-header-substitution/). + +To authenticate to the model platform, a connector action can contain `${credential.<credential_name>}` placeholders in its `headers` object, for example, `"Authorization": "Bearer ${credential.openAI_key}"`. OpenSearch fills these placeholders using the values in the connector `credential` object. Credential placeholders are filled only in headers, and a Predict API request can't provide credential values. + +## Input formats + +OpenSearch accepts input in one of the following formats. When you call a model directly, provide input as parameters. Some OpenSearch features always send their input in a different format, which the connector preprocessing function converts into parameters. To test a connector used by one of these features, send a Predict API request in the same format. + +| Input format | Request body fields | When to use | +| :--- | :--- | :--- | +| [Parameters](#providing-input-as-parameters) | `parameters` | To call any externally hosted model directly. The `ml_inference` processor also uses this format. | +| [Text documents](#providing-input-as-text-documents) | `text_docs` | To test an embedding model connector that the `text_embedding` ingest processor or `neural` query uses. | +| [Text similarity input](#providing-input-for-text-similarity) | `query_text` and `text_docs` | To test a rerank model connector that the `rerank` search processor uses. | + +## Providing input as parameters + +In a Predict request, the `parameters` object maps placeholder names to values: each key names a placeholder, and its value replaces that placeholder. Provide a value for every placeholder that doesn't have a default value in the connector `parameters` object. + +The following examples use the OpenAI chat connector shown in [Creating a standalone connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-standalone-connector). The connector `parameters` object provides default values for `endpoint` and `model`. The `request_body` template contains the `model` and `messages` placeholders. Because `messages` has no default value, every Predict request must provide it. + +After you [register a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#step-2-register-an-externally-hosted-model) using this connector, provide the `messages` value in a Predict API request: + +```json +POST /_plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "messages": [ + { + "role": "user", + "content": "Hello" + } + ] + } +} +``` +{% include copy-curl.html %} + +OpenSearch fills the template using the `messages` value from the request and the `model` value from the connector, and sends the following request body to the model: + +```json +{ "model": "gpt-4o-mini", "messages": [{"role":"user","content":"Hello"}] } +``` + +The `dataAsMap` object in the Predict API response contains the model response: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "id": "chatcmpl-7e6s5DYEutmM677UZokF9eH40dIY7", + "object": "chat.completion", + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Hello! How can I assist you today?" + }, + "finish_reason": "stop" + } + ] + } + } + ], + "status_code": 200 + } + ] +} +``` + +To override the connector default value, provide the parameter in the request. For example, the following request sets the model to `gpt-4o`: + +```json +POST /_plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "model": "gpt-4o", + "messages": [ + { + "role": "user", + "content": "Hello" + } + ] + } +} +``` +{% include copy-curl.html %} + +The `ml_inference` ingest processor also provides input as parameters. Its `input_map` maps document fields to parameter names. For more information, see [ML inference processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/ml-inference/). + +## Providing input as text documents + +Embedding features, such as the `text_embedding` ingest processor and the `neural` query, send their input as a `text_docs` array of strings. A connector for an embedding model uses the following functions to translate between this format and the model API: + +- The preprocessing function converts the `text_docs` array into the parameters that fill the request body template. +- The post-processing function converts the model response into the embedding format that OpenSearch requires. + +For example, the following connector uses the built-in OpenAI pre- and post-processing functions: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI embedding connector", + "description": "The connector to the OpenAI embeddings API", + "version": 1, + "protocol": "http", + "parameters": { + "model": "text-embedding-3-small" + }, + "credential": { + "openAI_key": "<openai_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/embeddings", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input\": ${parameters.input}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.openai.embedding", + "post_process_function": "connector.post_process.openai.embedding" + } + ] +} +``` +{% include copy-curl.html %} + +To test the connector using the input that these features send, provide a `text_docs` array in a Predict API request. Set the `algorithm` query parameter to `text_embedding` so that OpenSearch reads the `text_docs` field: + +```json +POST /_plugins/_ml/models/{model_id}/_predict?algorithm=text_embedding +{ + "text_docs": ["red shoes", "blue hat"] +} +``` +{% include copy-curl.html %} + +The preprocessing function converts the strings into the `input` parameter, and OpenSearch sends the following request body to the model: + +```json +{ "input": ["red shoes","blue hat"], "model": "text-embedding-3-small" } +``` + +If the connector doesn't define a preprocessing function, OpenSearch uses `connector.pre_process.default.embedding`, which also converts the strings into the `input` parameter. + +The post-processing function extracts the embeddings from the model response. The Predict API response contains one embedding for each string: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [1536], + "data": [-0.0147, 0.0362, ...] + }, + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [1536], + "data": [0.0081, -0.0215, ...] + } + ], + "status_code": 200 + } + ] +} +``` + +If you don't specify the algorithm, OpenSearch reads only the `parameters` object, so the template placeholders have no values and the request fails. You can also specify the algorithm as a path parameter. For more information, see [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/). + +If the connector doesn't define a post-processing function, the Predict API response contains the unchanged model response. For the input that each built-in function accepts and the output that it produces, see [Built-in pre- and post-processing functions](#built-in-pre--and-post-processing-functions). To write your own functions, see [Custom pre- and post-processing functions](#custom-pre--and-post-processing-functions). + +If the connector uses a built-in preprocessing function, you can also provide the input in a `parameters` object. For example, sending `{"parameters": {"input": ["red shoes", "blue hat"]}}` produces the same model request body as the preceding `text_docs` request. +{: .note} + +## Providing input for text similarity + +The `rerank` search processor sends its input as a `query_text` string and a `text_docs` array containing the text of each search result. A connector for a rerank model must define a preprocessing function that converts this input into parameters because OpenSearch provides no default preprocessing function for text similarity input. + +For example, the following connector uses the built-in Cohere Rerank functions: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Cohere rerank connector", + "description": "The connector to the Cohere Rerank API", + "version": 1, + "protocol": "http", + "parameters": { + "model": "rerank-english-v3.0" + }, + "credential": { + "cohere_key": "<cohere_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.cohere.ai/v1/rerank", + "headers": { + "Authorization": "Bearer ${credential.cohere_key}" + }, + "request_body": "{ \"documents\": ${parameters.documents}, \"query\": \"${parameters.query}\", \"top_n\": ${parameters.top_n}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.cohere.rerank", + "post_process_function": "connector.post_process.cohere.rerank" + } + ] +} +``` +{% include copy-curl.html %} + +To test the connector using the input that the `rerank` processor sends, provide `query_text` and `text_docs` in a Predict API request. Set the `algorithm` query parameter to `text_similarity` so that OpenSearch reads these fields: + +```json +POST /_plugins/_ml/models/{model_id}/_predict?algorithm=text_similarity +{ + "query_text": "Which shoes are waterproof?", + "text_docs": ["Waterproof hiking boots", "Canvas sneakers"] +} +``` +{% include copy-curl.html %} + +The preprocessing function converts the input into the `query`, `documents`, and `top_n` parameters, and OpenSearch sends the following request body to the model: + +```json +{ "documents": ["Waterproof hiking boots","Canvas sneakers"], "query": "Which shoes are waterproof?", "top_n": 2, "model": "rerank-english-v3.0" } +``` + +The post-processing function extracts the relevance scores from the model response. The Predict API response contains one score for each string in `text_docs`, in the same order: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "similarity", + "data_type": "FLOAT32", + "shape": [1], + "data": [0.9] + }, + { + "name": "similarity", + "data_type": "FLOAT32", + "shape": [1], + "data": [0.6] + } + ], + "status_code": 200 + } + ] +} +``` + +For more information about reranking search results, see [Reranking search results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/reranking-search-results/). + +## Built-in pre- and post-processing functions + +A preprocessing function converts `text_docs` input or text similarity input into the parameters that fill the connector request body template. A post-processing function converts the model response into the format that OpenSearch requires. To use a built-in function, specify its name in the `pre_process_function` or `post_process_function` field of a connector's `actions` array element. For more information about input formats, see [Input formats](#input-formats). + +If the input is `text_docs` and the connector doesn't define a preprocessing function, OpenSearch uses the `connector.pre_process.default.embedding` function. Text similarity input requires a preprocessing function. If the input is a `parameters` object, OpenSearch fills the request body template using the values in the object. + +The following table lists the built-in preprocessing functions. + +| Function | Use with | Input | Parameters returned | +| :--- | :--- | :--- | :--- | +| `connector.pre_process.default.embedding` | Amazon SageMaker models or other embedding models that accept an array of strings | `text_docs` | Returns an `input` parameter containing the `text_docs` array. | +| `connector.pre_process.openai.embedding` | OpenAI and Azure OpenAI embedding models | `text_docs` | Returns an `input` parameter containing the `text_docs` array. | +| `connector.pre_process.cohere.embedding` | Cohere Embed models, including Cohere Embed models in Amazon Bedrock | `text_docs` | Returns a `texts` parameter containing the `text_docs` array. | +| `connector.pre_process.cohere.multimodal_embedding` | Cohere Embed models, for image input | `text_docs` containing image data URIs | Returns an `images` parameter containing the `text_docs` array. | +| `connector.pre_process.bedrock.embedding` | Amazon Titan Text Embeddings models in Amazon Bedrock | `text_docs` | Returns an `inputText` parameter containing the first string in `text_docs`. | +| `connector.pre_process.bedrock.multimodal_embedding` | Amazon Titan Multimodal Embeddings in Amazon Bedrock | `text_docs` containing text, optionally followed by an image | Returns an `inputText` parameter containing the first string in `text_docs` and, if `text_docs` contains a second string, an `inputImage` parameter containing that string. | +| `connector.pre_process.bedrock.nova.embedding` | Amazon Nova Multimodal Embeddings in Amazon Bedrock | `text_docs` in which the first string is plain text or a JSON object containing a `text`, `image`, `video`, or `audio` field | Returns a `text`, `image`, `video`, or `audio` parameter containing the value of the matching field. Plain text input returns a `text` parameter. | +| `connector.pre_process.bedrock.nova.text_embedding` | Amazon Nova Multimodal Embeddings in Amazon Bedrock, for text input | `text_docs` | Returns an `inputText` parameter containing the first string in `text_docs`. | +| `connector.pre_process.bedrock.nova.image_embedding` | Amazon Nova Multimodal Embeddings in Amazon Bedrock, for image input | `text_docs` | Returns an `inputImage` parameter containing the first string in `text_docs`. | +| `connector.pre_process.bedrock.nova.video_embedding` | Amazon Nova Multimodal Embeddings in Amazon Bedrock, for video input | `text_docs` | Returns an `inputVideo` parameter containing the first string in `text_docs`. | +| `connector.pre_process.bedrock.nova.audio_embedding` | Amazon Nova Multimodal Embeddings in Amazon Bedrock, for audio input | `text_docs` | Returns an `inputAudio` parameter containing the first string in `text_docs`. | +| `connector.pre_process.default.rerank` | Rerank models that accept a query, an array of documents, and the number of results to return, for example, a model that you deploy on Amazon SageMaker | `query_text` and `text_docs` (text similarity input, such as from the `rerank` search processor) | Returns a `query` parameter containing the query text, a `documents` parameter containing the `text_docs` array, and a `top_n` parameter containing the number of strings in `text_docs`. | +| `connector.pre_process.cohere.rerank` | Cohere Rerank models | `query_text` and `text_docs` (text similarity input, such as from the `rerank` search processor) | Returns a `query` parameter containing the query text, a `documents` parameter containing the `text_docs` array, and a `top_n` parameter containing the number of strings in `text_docs`. | +| `connector.pre_process.bedrock.rerank` | Rerank models accessed through the Amazon Bedrock Rerank API, such as Amazon Rerank. For an example, see [Reranking search results using Amazon Bedrock models]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-bedrock/). | `query_text` and `text_docs` (text similarity input, such as from the `rerank` search processor) | Returns `queries`, `sources`, and `numberOfResults` parameters in the format of the Amazon Bedrock Rerank API. | + +The following table lists the built-in post-processing functions. For each function, the table provides the JSON path of the model response field that contains the embeddings or results. + +| Function | Use with | Response field (JSON path) | +| :--- | :--- | :--- | +| `connector.post_process.default.embedding` | Amazon SageMaker models or other embedding models that return a two-dimensional array | `$[*]`: Each entry of a top-level array. | +| `connector.post_process.openai.embedding` | OpenAI and Azure OpenAI embedding models | `$.data[*].embedding` | +| `connector.post_process.cohere.embedding` | Cohere Embed models, including Cohere Embed models in Amazon Bedrock | `$.embeddings` | +| `connector.post_process.cohere_v2.embedding.float` | Cohere Embed models using the v2 API, for `float` embeddings | `$.embeddings.float` | +| `connector.post_process.cohere_v2.embedding.int8` | Cohere Embed models using the v2 API, for `int8` embeddings | `$.embeddings.int8` | +| `connector.post_process.cohere_v2.embedding.uint8` | Cohere Embed models using the v2 API, for `uint8` embeddings | `$.embeddings.uint8` | +| `connector.post_process.cohere_v2.embedding.binary` | Cohere Embed models using the v2 API, for `binary` embeddings | `$.embeddings.binary` | +| `connector.post_process.cohere_v2.embedding.ubinary` | Cohere Embed models using the v2 API, for `ubinary` embeddings | `$.embeddings.ubinary` | +| `connector.post_process.bedrock.embedding` | Amazon Titan Text Embeddings V1 and Amazon Titan Multimodal Embeddings in Amazon Bedrock | `$.embedding` | +| `connector.post_process.bedrock_v2.embedding.float` | Amazon Titan Text Embeddings V2 in Amazon Bedrock, for `float` embeddings | `$.embeddingsByType.float` | +| `connector.post_process.bedrock_v2.embedding.binary` | Amazon Titan Text Embeddings V2 in Amazon Bedrock, for `binary` embeddings | `$.embeddingsByType.binary` | +| `connector.post_process.bedrock.nova.embedding` | Amazon Nova Multimodal Embeddings in Amazon Bedrock | `$.embeddings[*].embedding` | +| `connector.post_process.default.rerank` | Rerank models that return a top-level array of results, each containing an `index` and a `relevance_score`, for example, a model that you deploy on Amazon SageMaker | `$[*]`: Each entry of a top-level array. The Predict API response contains one score for each document, in the order of the input documents. | +| `connector.post_process.cohere.rerank` | Cohere Rerank models | `$.results` | +| `connector.post_process.bedrock.rerank` | Rerank models accessed through the Amazon Bedrock Rerank API, such as Amazon Rerank. For an example, see [Reranking search results using Amazon Bedrock models]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-bedrock/). | `$.results` | +| `connector.post_process.mlcommons.passthrough` | Endpoints that return responses in the Predict API format, such as ML Commons in another OpenSearch cluster or the OpenSearch Agent Server. For an example, see [Filling templates in the agent server]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agentic-search-templates/agent-server/). | `$`: The entire response. If the response contains an `inference_results` array, the function returns the `output` objects from the array, so the Predict API response doesn't contain one `inference_results` array nested inside another. | + +## Default embedding functions + +When you use [semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/semantic-search/), OpenSearch sends text to the model and requires embeddings in return. [Pretrained models provided by OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/) accept and return these formats. However, a model hosted on an external platform may expect a different format. For example, a model deployed on Amazon SageMaker might accept an array of strings and return one embedding for each string. The default embedding functions, `connector.pre_process.default.embedding` and `connector.post_process.default.embedding`, convert between these formats. + +The following example request creates an Amazon SageMaker text embedding connector that uses the default functions. The connector doesn't define a preprocessing function, so OpenSearch uses `connector.pre_process.default.embedding`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Sagemaker text embedding connector", + "description": "The connector to Sagemaker", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<YOUR SAGEMAKER ACCESS KEY>", + "secret_key": "<YOUR SAGEMAKER SECRET KEY>", + "session_token": "<YOUR AWS SECURITY TOKEN>" + }, + "parameters": { + "region": "ap-northeast-1", + "service_name": "sagemaker" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://runtime.sagemaker.ap-northeast-1.amazonaws.com/endpoints/<endpoint_name>/invocations", + "headers": { + "content-type": "application/json" + }, + "post_process_function": "connector.post_process.default.embedding", + "request_body": "${parameters.input}" + } + ] +} +``` +{% include copy-curl.html %} + +Set the `request_body` template to `${parameters.input}` so that OpenSearch sends the array of strings as the entire request body. +{: .important} + +### Preprocessing function + +The `connector.pre_process.default.embedding` function converts the `text_docs` input into the `input` parameter. For example, the following input contains two strings: + +```json +{ + "text_docs": ["hello", "world"] +} +``` + +The function converts this input into the following parameters: + +```json +{ + "parameters": { + "input": ["hello", "world"] + } +} +``` + +The `${parameters.input}` request body template then sends the list to the model, so the model input format must be a list of strings, for example: + +```json +["hello", "world"] +``` + +### Post-processing function + +The `connector.post_process.default.embedding` function parses the model response and transforms it into the embedding format that OpenSearch requires. + +The remote text embedding model output must be a two-dimensional float array, each element of which represents an embedding of a string from the input list. For example, the following two-dimensional array corresponds to the embedding of the list `["hello", "world"]`: + +```json +[ + [ + -0.048237994, + -0.07612697, + ... + ], + [ + 0.32621247, + 0.02328475, + ... + ] +] +``` + +## Custom pre- and post-processing functions + +If the built-in functions don't support the request or response format of your model API, write your own functions as [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/) scripts. + +A custom preprocessing function reads the input from `params`, for example, `params.text_docs`, and returns a JSON string containing a `parameters` object. The values in the `parameters` object fill the `request_body` template. + +A custom post-processing function reads the model response from `params`. If the response is a JSON object, `params` contains its fields, for example, `params.embedding`. If the response is a JSON array, `params.result` contains the array. The function returns a JSON string containing an output object or an array of output objects. Each output object contains a `name` field and either the `data_type`, `shape`, and `data` fields for an embedding or a `dataAsMap` object for other output. To escape special characters in strings that you insert into the returned JSON, call the built-in `escape()` function. If the function returns a string that isn't valid JSON, the Predict API response contains the string in `dataAsMap.response`. + +For example, the following preprocessing function sends the first string in `text_docs` to the Amazon Bedrock Titan embedding model in the `inputText` parameter: + +```js +StringBuilder builder = new StringBuilder(); +builder.append("\""); +String first = params.text_docs[0]; +builder.append(first); +builder.append("\""); +def parameters = "{" + "\"inputText\":" + builder + "}"; +return "{" + "\"parameters\":" + parameters + "}"; +``` + +The following post-processing function converts the `embedding` field of the model response into an output object: + +```js +def name = "sentence_embedding"; +def dataType = "FLOAT32"; +if (params.embedding == null || params.embedding.length == 0) { + return params.message; +} +def shape = [params.embedding.length]; +def json = "{" + + "\"name\":\"" + name + "\"," + + "\"data_type\":\"" + dataType + "\"," + + "\"shape\":" + shape + "," + + "\"data\":" + params.embedding + + "}"; +return json; +``` + +To use the functions, provide each script as a string in the `pre_process_function` and `post_process_function` fields of the connector action: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Amazon Bedrock Connector: embedding", + "description": "The connector to the Bedrock Titan embedding model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "<YOUR AWS REGION>", + "service_name": "bedrock" + }, + "credential": { + "access_key": "<YOUR AWS ACCESS KEY>", + "secret_key": "<YOUR AWS SECRET KEY>", + "session_token": "<YOUR AWS SECURITY TOKEN>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-embed-text-v1/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{ \"inputText\": \"${parameters.inputText}\" }", + "pre_process_function": "\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\\"\");\n String first = params.text_docs[0];\n builder.append(first);\n builder.append(\"\\\"\");\n def parameters = \"{\" +\"\\\"inputText\\\":\" + builder + \"}\";\n return \"{\" +\"\\\"parameters\\\":\" + parameters + \"}\";", + "post_process_function": "\n def name = \"sentence_embedding\";\n def dataType = \"FLOAT32\";\n if (params.embedding == null || params.embedding.length == 0) {\n return params.message;\n }\n def shape = [params.embedding.length];\n def json = \"{\" +\n \"\\\"name\\\":\\\"\" + name + \"\\\",\" +\n \"\\\"data_type\\\":\\\"\" + dataType + \"\\\",\" +\n \"\\\"shape\\\":\" + shape + \",\" +\n \"\\\"data\\\":\" + params.embedding +\n \"}\";\n return json;\n " + } + ] +} +``` +{% include copy-curl.html %} + +## Next steps + +- To write a connector definition for a model that has no OpenSearch-provided blueprint, see [Creating a custom blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). +- For descriptions of all connector fields, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). +- For all Predict API parameters and request fields, see [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/). diff --git a/_ml-commons-plugin/remote-models/connectors.md b/_ml-commons-plugin/remote-models/connectors.md index 64b55142..71886805 100644 --- a/_ml-commons-plugin/remote-models/connectors.md +++ b/_ml-commons-plugin/remote-models/connectors.md @@ -1,7 +1,7 @@ --- layout: default title: Connectors -has_children: false +has_children: true has_toc: false nav_order: 61 parent: Connecting to externally hosted models @@ -10,68 +10,55 @@ redirect_from: - /ml-commons-plugin/extensibility/connectors/ --- -# Creating connectors for third-party ML platforms +# Connectors for third-party ML platforms **Introduced 2.9** {: .label .label-purple } -Connectors facilitate access to models hosted on third-party machine learning (ML) platforms. - -OpenSearch provides connectors for several platforms, for example: - -- [Amazon SageMaker](https://aws.amazon.com/sagemaker/) allows you to host and manage the lifecycle of text embedding models, powering semantic search queries in OpenSearch. When connected, Amazon SageMaker hosts your models and OpenSearch is used to query inferences. This benefits Amazon SageMaker users who value its functionality, such as model monitoring, serverless hosting, and workflow automation for continuous training and deployment. -- [OpenAI ChatGPT](https://openai.com/blog/chatgpt) enables you to invoke an OpenAI chat model from inside an OpenSearch cluster. -- [Cohere](https://cohere.com/) allows you to use data from OpenSearch to power the Cohere large language models. -- [Amazon Bedrock](https://aws.amazon.com/bedrock/) supports models like [Bedrock Titan Embeddings](https://aws.amazon.com/bedrock/titan/), which can drive semantic search and retrieval-augmented generation in OpenSearch. +A connector defines how OpenSearch calls a model hosted on an external platform, such as Amazon Bedrock, Amazon SageMaker, OpenAI, Cohere, or Google Cloud Vertex AI. The connector contains the model endpoint URL, the credentials, and a template for the request body that OpenSearch sends to the model. ## Connector blueprints -A _connector blueprint_ defines the set of parameters (the request body) you need to provide when sending an API request to create a specific connector. Connector blueprints may differ based on the platform and the model that you are accessing. +To create a connector, start from a _connector blueprint_, a connector definition for a specific model that you can copy and complete with your own values. You can use one of the following blueprints: -OpenSearch provides connector blueprints for several ML platforms and models. For a full list of connector blueprints provided by OpenSearch, see [Supported connectors](#supported-connectors). +- An OpenSearch-provided blueprint. To find the blueprint for your model, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). +- Your own blueprint, if OpenSearch doesn't provide one for your model. For more information, see [Creating a custom blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). -As an ML developer, you can also create connector blueprints for other platforms and models. Data scientists and administrators can then use the blueprint to create connectors. They are only required to enter their `credential` settings, such as `openAI_key`, for the service to which they are connecting. For information about creating connector blueprints, including descriptions of all parameters, see [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). - -## Supported connectors - -The following table lists all connector blueprints provided by OpenSearch. Follow the links to each connector blueprint for an example request that you can use to create the connector, including all parameters, and an example Predict API request. - -Platform | Model | Connector blueprint -:--- | :--- | :--- -[Amazon Bedrock](https://aws.amazon.com/bedrock/) | [AI21 Labs Jurassic-2 Mid](https://aws.amazon.com/bedrock/jurassic/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md) -[Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v2](https://aws.amazon.com/bedrock/claude/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude_blueprint.md) -[Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Titan Text Embeddings](https://aws.amazon.com/bedrock/titan/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/bedrock_connector_titan_embedding_blueprint.md) -[Amazon SageMaker](https://aws.amazon.com/sagemaker/) | Text embedding models | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/sagemaker_connector_blueprint.md) -[Cohere](https://cohere.com/) | [Text Embedding models](https://docs.cohere.com/reference/embed) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/cohere_connector_embedding_blueprint.md) -[Cohere](https://cohere.com/) | [Chat models](https://docs.cohere.com/reference/chat) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_chat_blueprint.md) -[OpenAI](https://openai.com/) | Chat models (for example, `gpt-3.5-turbo`) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/open_ai_connector_chat_blueprint.md) -[OpenAI](https://openai.com/) | Completion models (for example, `text-davinci-003`) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/open_ai_connector_completion_blueprint.md) -[OpenAI](https://openai.com/) | Text embedding models (for example, `text-embedding-ada-002`) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/openai_connector_embedding_blueprint.md) +The connector `protocol` field determines how OpenSearch authenticates to the model platform. For more information, see [Connector authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-authentication/). ## Creating a connector -You can provision connectors in two ways: +You can create a connector in one of the following ways. -1. [Create a standalone connector](#creating-a-standalone-connector): A standalone connector can be reused and shared by multiple models but requires access to both the model and connector in OpenSearch and the third-party platform, such as OpenAI or Amazon SageMaker, that the connector is accessing. Standalone connectors are saved in a connector index. +| Connector type | How to create it | Models that can use it | Access required to use it | +| :--- | :--- | :--- | :--- | +| [Standalone connector](#creating-a-standalone-connector) | Send a Create Connector API request. | Any number of models that call the same model endpoint using the same configuration. | Access to the connector and to the model. | +| [Connector for a specific model](#creating-a-connector-for-a-specific-model) | Provide the connector definition in the `connector` object of a Register Model API request. | Only the model registered in the same request. | Access to the model. | -2. [Create a connector for a specific externally hosted model](#creating-a-connector-for-a-specific-model): Alternatively, you can create a connector that can only be used with the model for which it was created. To access such a connector, you only need access to the model itself because the connection is established inside the model. These connectors are saved in the model index. +The access requirements apply when connector access control and model access control are enabled. For more information, see [Configuring connector access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#configuring-connector-access-control). -## Creating a standalone connector +If you need to connect to a different external model (for example, switching from `gpt-4o-mini` to `gpt-4o`), we recommend creating a separate standalone connector. Alternatively, if the connector request body template uses a placeholder for the model name, you can override the model name in each Predict request. For more information, see [Providing input as parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-parameters). +{: .note} -Standalone connectors can be used by multiple models. To create a standalone connector, send a request to the `connectors/_create` endpoint and provide all of the parameters described in [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/): +If using Python, you can create connectors using the [`opensearch-py-ml`](https://github.com/opensearch-project/opensearch-py-ml) client CLI. The CLI automates many configuration steps, making setup faster and reducing the chance of errors. For more information about using the CLI, see the [CLI documentation](https://opensearch-project.github.io/opensearch-py-ml/cli/index.html#). +{: .tip} + +### Creating a standalone connector + +To create a standalone connector, send a request to the `connectors/_create` endpoint and provide all of the parameters described in [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields): ```json POST /_plugins/_ml/connectors/_create { "name": "OpenAI Chat Connector", - "description": "The connector to public OpenAI model service for GPT 3.5", + "description": "The connector to public OpenAI model service for gpt-4o-mini", "version": 1, "protocol": "http", "parameters": { "endpoint": "api.openai.com", - "model": "gpt-3.5-turbo" + "model": "gpt-4o-mini" }, "credential": { - "openAI_key": "..." + "openAI_key": "<openai_key>" }, "actions": [ { @@ -88,40 +75,37 @@ POST /_plugins/_ml/connectors/_create ``` {% include copy-curl.html %} -## Creating a connector for a specific model +### Creating a connector for a specific model -To create a connector for a specific model, provide all of the parameters described in [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/) within the `connector` object of a request to the `models/_register` endpoint: +To create a connector for a specific model, provide all of the parameters described in [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields) within the `connector` object of a request to the `models/_register` endpoint: ```json POST /_plugins/_ml/models/_register { - "name": "openAI-GPT-3.5 model with a connector", + "name": "openAI-gpt-4o-mini", "function_name": "remote", - "model_group_id": "lEFGL4kB4ubqQRzegPo2", - "description": "test model", + "description": "OpenAI gpt-4o-mini model with a connector", "connector": { - "name": "OpenAI Connector", - "description": "The connector to public OpenAI model service for GPT 3.5", + "name": "OpenAI Chat Connector", + "description": "The connector to public OpenAI model service for gpt-4o-mini", "version": 1, "protocol": "http", "parameters": { "endpoint": "api.openai.com", - "max_tokens": 7, - "temperature": 0, - "model": "text-davinci-003" + "model": "gpt-4o-mini" }, "credential": { - "openAI_key": "..." + "openAI_key": "<openai_key>" }, "actions": [ { "action_type": "predict", "method": "POST", - "url": "https://${parameters.endpoint}/v1/completions", + "url": "https://${parameters.endpoint}/v1/chat/completions", "headers": { "Authorization": "Bearer ${credential.openAI_key}" }, - "request_body": "{ \"model\": \"${parameters.model}\", \"prompt\": \"${parameters.prompt}\", \"max_tokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }" + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": ${parameters.messages} }" } ] } @@ -129,180 +113,44 @@ POST /_plugins/_ml/models/_register ``` {% include copy-curl.html %} -## Connector examples - -The following sections contain examples of connectors for popular ML platforms. For a full list of supported connectors, see [Supported connectors](#supported-connectors). - -### OpenAI chat connector - -You can use the following example request to create a standalone OpenAI chat connector: - -```json -POST /_plugins/_ml/connectors/_create -{ - "name": "OpenAI Chat Connector", - "description": "The connector to public OpenAI model service for GPT 3.5", - "version": 1, - "protocol": "http", - "parameters": { - "endpoint": "api.openai.com", - "model": "gpt-3.5-turbo" - }, - "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} }" - } - ] -} -``` -{% include copy-curl.html %} - -### Amazon SageMaker connector - -You can use the following example request to create a standalone Amazon SageMaker connector: - -```json -POST /_plugins/_ml/connectors/_create -{ - "name": "sagemaker: embedding", - "description": "Test connector for Sagemaker embedding model", - "version": 1, - "protocol": "aws_sigv4", - "credential": { - "access_key": "...", - "secret_key": "...", - "session_token": "..." - }, - "parameters": { - "region": "us-west-2", - "service_name": "sagemaker" - }, - "actions": [ - { - "action_type": "predict", - "method": "POST", - "headers": { - "content-type": "application/json" - }, - "url": "https://runtime.sagemaker.${parameters.region}.amazonaws.com/endpoints/lmi-model-2023-06-24-01-35-32-275/invocations", - "request_body": "[\"${parameters.inputs}\"]" - } - ] -} -``` -{% include copy-curl.html %} - -The `credential` parameter contains the following options reserved for `aws_sigv4` authentication: - -- `access_key`: Required. Provides the access key for the AWS instance. -- `secret_key`: Required. Provides the secret key for the AWS instance. -- `session_token`: Optional. Provides a temporary set of credentials for the AWS instance. - -The `parameters` section requires the following options when using `aws_sigv4` authentication: - -- `region`: The AWS Region in which the AWS instance is located. -- `service_name`: The name of the AWS service for the connector. - -### Cohere connector - -You can use the following example request to create a standalone Cohere connector using the Embed V3 model. For more information, see [Cohere connector blueprint](https://github.com/opensearch-project/ml-commons/blob/2.x/docs/remote_inference_blueprints/cohere_connector_embedding_blueprint.md). - -```json -POST /_plugins/_ml/connectors/_create -{ - "name": "Cohere Embed Model", - "description": "The connector to Cohere's public embed API", - "version": "1", - "protocol": "http", - "credential": { - "cohere_key": "<ENTER_COHERE_API_KEY_HERE>" - }, - "parameters": { - "model": "embed-english-v3.0", - "input_type":"search_document", - "truncate": "END" - }, - "actions": [ - { - "action_type": "predict", - "method": "POST", - "url": "https://api.cohere.ai/v1/embed", - "headers": { - "Authorization": "Bearer ${credential.cohere_key}", - "Request-Source": "unspecified:opensearch" - }, - "request_body": "{ \"texts\": ${parameters.texts}, \"truncate\": \"${parameters.truncate}\", \"model\": \"${parameters.model}\", \"input_type\": \"${parameters.input_type}\" }", - "pre_process_function": "connector.pre_process.cohere.embedding", - "post_process_function": "connector.post_process.cohere.embedding" - } - ] -} -``` -{% include copy-curl.html %} - -### Amazon Bedrock connector - -You can use the following example request to create a standalone Amazon Bedrock connector: - -```json -POST /_plugins/_ml/connectors/_create -{ - "name": "Amazon Bedrock Connector: embedding", - "description": "The connector to the Bedrock Titan embedding model", - "version": 1, - "protocol": "aws_sigv4", - "parameters": { - "region": "<YOUR AWS REGION>", - "service_name": "bedrock" - }, - "credential": { - "access_key": "<YOUR AWS ACCESS KEY>", - "secret_key": "<YOUR AWS SECRET KEY>", - "session_token": "<YOUR AWS SECURITY TOKEN>" - }, - "actions": [ - { - "action_type": "predict", - "method": "POST", - "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-embed-text-v1/invoke", - "headers": { - "content-type": "application/json", - "x-amz-content-sha256": "required" - }, - "request_body": "{ \"inputText\": \"${parameters.inputText}\" }", - "pre_process_function": "\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\\"\");\n String first = params.text_docs[0];\n builder.append(first);\n builder.append(\"\\\"\");\n def parameters = \"{\" +\"\\\"inputText\\\":\" + builder + \"}\";\n return \"{\" +\"\\\"parameters\\\":\" + parameters + \"}\";", - "post_process_function": "\n def name = \"sentence_embedding\";\n def dataType = \"FLOAT32\";\n if (params.embedding == null || params.embedding.length == 0) {\n return params.message;\n }\n def shape = [params.embedding.length];\n def json = \"{\" +\n \"\\\"name\\\":\\\"\" + name + \"\\\",\" +\n \"\\\"data_type\\\":\\\"\" + dataType + \"\\\",\" +\n \"\\\"shape\\\":\" + shape + \",\" +\n \"\\\"data\\\":\" + params.embedding +\n \"}\";\n return json;\n " - } - ] -} -``` -{% include copy-curl.html %} - ## Updating connector credentials -In some cases, you may need to update credentials, like `access_key`, that you use to connect to externally hosted models. You can update credentials without undeploying the model by providing the new credentials in the following request: +In some cases, you may need to update the credentials used to connect to an externally hosted model, such as an expiring API key. To do this without undeploying the model, provide the new credentials in an update request. + +### Connector for a specific model + +To update credentials for a connector linked to a specific model, provide the new credentials in the following request: ```json -PUT /_plugins/_ml/models/<model_id> +PUT /_plugins/_ml/models/{model_id} { "connector": { "credential": { - "openAI_key": "YOUR NEW OPENAI KEY" + "openAI_key": "<new_openai_key>" } } } ``` +{% include copy-curl.html %} + +### Standalone connector + +To update credentials for a standalone connector, provide the new credentials in the following request: + +```json +PUT /_plugins/_ml/connectors/{connector_id} +{ + "credential": { + "openAI_key": "<new_openai_key>" + } +} +``` +{% include copy-curl.html %} ## Next steps +- To learn how a connector builds the request that it sends to the model and processes the model response, see [Connector input and output]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/). +- To find the blueprint and protocol for your platform and model, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). +- To pass per-request values in connector headers, see [Dynamic header substitution]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/dynamic-header-substitution/). - To learn more about connecting to external models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). - To learn more about model access control and model groups, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). diff --git a/_ml-commons-plugin/remote-models/dynamic-header-substitution.md b/_ml-commons-plugin/remote-models/dynamic-header-substitution.md new file mode 100644 index 00000000..edea8759 --- /dev/null +++ b/_ml-commons-plugin/remote-models/dynamic-header-substitution.md @@ -0,0 +1,119 @@ +--- +layout: default +title: Dynamic header substitution +has_children: false +nav_order: 70 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +--- + +# Dynamic header substitution +**Introduced 3.7** +{: .label .label-purple } + +By default, connector headers are resolved once at connector creation time. Dynamic connector headers allow you to use `${parameters.*}` placeholders in header values so that per-request values are substituted at prediction time. This is useful for passing request-scoped metadata such as transaction IDs, correlation IDs, or trace tokens to the externally hosted model endpoint. + +## Configuring dynamic headers + +To configure a dynamic header, define the header with a `${parameters.*}` placeholder in the connector's `actions[].headers` field. You can optionally set a default value for the parameter in the top-level `parameters` field. + +The following example uses the placeholder endpoint `api.example.com`. Connector URLs must match a pattern in `plugins.ml_commons.trusted_connector_endpoints_regex`, so replace the endpoint with your model's endpoint or add it to the trusted endpoints. For more information, see [Adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#adding-trusted-endpoints). + +To create a connector containing a dynamic header, send the following request: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My connector", + "description": "Connector with dynamic headers", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.example.com", + "request_id": "default-request-id" + }, + "credential": { + "api_key": "test-api-key" + }, + "actions": [{ + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/predict", + "headers": { + "Authorization": "${credential.api_key}", + "X-Test-Request-Id": "${parameters.request_id}" + }, + "request_body": "{ \"input\": \"${parameters.input}\" }" + }] +} +``` +{% include copy-curl.html %} + +At prediction time, pass the runtime value in the `parameters` field of the `_predict` request: + +```json +POST /_plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "request_id": "request-123", + "input": "hello world" + } +} +``` +{% include copy-curl.html %} + +The resulting HTTP request to the remote endpoint includes the substituted header: + +```json +POST https://api.example.com/predict +Authorization: test-api-key +X-Test-Request-Id: request-123 +``` + +If no runtime value is provided and no default is set in the connector's `parameters` field, the prediction request is rejected with a 400 error. To avoid this, define a default value for the parameter in the connector's `parameters` field. If no runtime value is provided, the default value is used. + +## Security restrictions + +The following headers cannot contain `${parameters.*}` placeholders. Using them returns a 400 error at connector creation or update time. Use `${credential.*}` for authentication headers instead: + +- Credential headers: + - `Authorization` + - `Proxy-Authorization` + - `Cookie` + - `X-API-Key` + - `X-Auth-Token` + - `X-Auth-Header` + +- IP and host spoofing headers: + - `Host` + - `X-Forwarded-Host` + - `X-Forwarded-Server` + - `X-Forwarded-For` + - `Forwarded` + - `X-Real-IP` + - `X-Client-IP` + - `CF-Connecting-IP` + - `True-Client-IP` + - `X-Originating-IP` + +## Runtime validation + +Before substitution, OpenSearch escapes special characters in the parameter values in the `_predict` request. A newline in a runtime value reaches the header as the two characters `\n`, and other control characters reach it as escape sequences such as `\u0001`. The following values are substituted without escaping: + +- Values of parameters listed in the `no_escape_params` parameter of the `_predict` request +- Values that are valid JSON objects or arrays +- Default values from the connector's `parameters` field + +At prediction time, substituted header values are validated before the request is sent to the model endpoint. A prediction request whose headers fail any of the following checks returns a 400 error: + +- Header values that contain a carriage return (`\r`), a line feed (`\n`), or another control character (`0x00–0x1F`, except tab, and `0x7F`) are rejected to prevent HTTP response splitting. Because runtime values are escaped, this applies only to values substituted without escaping. +- Each header, including its name and value, must not exceed 8 KB (8,192 characters). +- The combined size of all header names and values must not exceed 64 KB (65,536 characters). + +The size limits apply to the escaped values, so escape sequences count toward them. For example, a `"` character in a runtime value counts as two characters (`\"`). + +## Next steps + +- For descriptions of all connector fields, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). +- For information about supplying authentication credentials to a connector, see the authentication method for your platform's protocol in [Connector authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-authentication/). diff --git a/_ml-commons-plugin/remote-models/google-cloud.md b/_ml-commons-plugin/remote-models/google-cloud.md new file mode 100644 index 00000000..045f495b --- /dev/null +++ b/_ml-commons-plugin/remote-models/google-cloud.md @@ -0,0 +1,162 @@ +--- +layout: default +title: Google Cloud authentication +has_children: false +nav_order: 60 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +--- + +# Google Cloud authentication +**Introduced 3.9** +{: .label .label-purple } + +The `google_cloud` connector protocol enables OpenSearch to call Google Cloud Vertex AI models. OpenSearch generates and refreshes the Google Cloud OAuth 2.0 access token and adds an `Authorization` header to each request, so you don't need to supply or rotate a token manually. This protocol is the Google Cloud equivalent of the [`aws_sigv4` protocol]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) for AWS services. + +Google has renamed Vertex AI to Gemini Enterprise Agent Platform. The API endpoints called by the connector, such as `aiplatform.googleapis.com`, are unchanged, so existing connectors do not require modification. +{: .note} + +## Prerequisites + +Before creating a `google_cloud` connector, enable Vertex AI in your Google Cloud project and prepare either a service account key or, for nodes hosted on Google Cloud, Workload Identity. Then configure the cluster settings by following these steps: + +1. Enable the `google_cloud` protocol, which is disabled by default. To enable it, set the `plugins.ml_commons.connector.vertexai_enabled` cluster setting to `true`: + + ```json + PUT /_cluster/settings + { + "persistent": { + "plugins.ml_commons.connector.vertexai_enabled": true + } + } + ``` + {% include copy-curl.html %} + +1. If you have changed the `plugins.ml_commons.trusted_connector_endpoints_regex` setting or are using a version of OpenSearch earlier than 3.10, add the Vertex AI host to the trusted connector endpoints. Starting with OpenSearch 3.10, the default value of this setting includes the Vertex AI host. + + First, retrieve the current list: + + ```json + GET /_cluster/settings?include_defaults=true&filter_path=**.trusted_connector_endpoints_regex + ``` + {% include copy-curl.html %} + + Then update the list by appending the Vertex AI pattern: + + ```json + PUT /_cluster/settings + { + "persistent": { + "plugins.ml_commons.trusted_connector_endpoints_regex": [ + "<every pattern from the preceding response>", + "^https://([a-z0-9][a-z0-9-]*-)?aiplatform\\.googleapis\\.com/.*$" + ] + } + } + ``` + {% include copy-curl.html %} + + The new list overwrites the existing one. If it contains only the Vertex AI pattern, then OpenSearch blocks connections to other providers, such as Amazon Bedrock or OpenAI. For the default list, see [Adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#adding-trusted-endpoints). + {: .warning} + +## Authentication modes + +The `google_cloud` protocol supports two authentication modes. + +### Service account key mode + +Supply the service account's `private_key` and `client_email` in the `credential` object: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Vertex AI Connector: Gemini", + "description": "Vertex AI Gemini generateContent connector", + "version": 1, + "protocol": "google_cloud", + "parameters": { + "project_id": "<project_id>", + "location": "us-central1", + "model": "gemini-2.5-flash", + "scopes": "https://www.googleapis.com/auth/cloud-platform" + }, + "credential": { + "private_key": "<private_key>", + "client_email": "<client_email>", + "token_uri": "https://oauth2.googleapis.com/token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.location}-aiplatform.googleapis.com/v1/projects/${parameters.project_id}/locations/${parameters.location}/publishers/google/models/${parameters.model}:generateContent", + "headers": { + "Content-Type": "application/json" + }, + "request_body": "{\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":\"${parameters.prompt}\"}]}]}" + } + ] +} +``` +{% include copy-curl.html %} + +### Application Default Credentials mode + +On nodes hosted on Google Cloud, use Application Default Credentials (ADC) or Workload Identity instead of a service account key. Set `auth_mode` to `adc` in `parameters` and omit the `credential` object: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Vertex AI Connector: Gemini (ADC)", + "description": "Vertex AI Gemini generateContent connector using ADC", + "version": 1, + "protocol": "google_cloud", + "parameters": { + "project_id": "<project_id>", + "location": "us-central1", + "model": "gemini-2.5-flash", + "auth_mode": "adc", + "scopes": "https://www.googleapis.com/auth/cloud-platform" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.location}-aiplatform.googleapis.com/v1/projects/${parameters.project_id}/locations/${parameters.location}/publishers/google/models/${parameters.model}:generateContent", + "headers": { + "Content-Type": "application/json" + }, + "request_body": "{\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":\"${parameters.prompt}\"}]}]}" + } + ] +} +``` +{% include copy-curl.html %} + +Use ADC mode only on nodes hosted on Google Cloud. ADC resolves credentials from the node environment, which requires contacting the Google Cloud metadata server. The service account key and ADC modes are mutually exclusive: if you include a `credential` object in ADC mode, it must not contain `private_key` or `client_email`. OpenSearch rejects the connector otherwise. + +## Request body fields + +When `protocol` is set to `google_cloud`, the `credential` object supports the following fields. + +| Field | Data type | Required/Optional | Description | +|:---|:---|:---|:---| +| `private_key` | String | Required in service account key mode | The service account's private key. Omit in ADC mode. | +| `client_email` | String | Required in service account key mode | The service account's client email. Omit in ADC mode. | +| `token_uri` | String | Optional | The Google OAuth 2.0 token endpoint. Default is `https://oauth2.googleapis.com/token`. The URL must use HTTPS, the host must be `oauth2.googleapis.com`, and the port must be `443` or omitted. | + +When `protocol` is set to `google_cloud`, the `parameters` object supports the following fields. + +| Field | Data type | Required/Optional | Description | +|:---|:---|:---|:---| +| `project_id` | String | Required | Your Google Cloud project ID. | +| `location` | String | Required | The Vertex AI region, for example, `us-central1`. | +| `model` | String | Required | The Vertex AI model ID, for example, `gemini-2.5-flash`. | +| `auth_mode` | String | Optional | Set to `adc` to use Application Default Credentials or Workload Identity. Omit in service account key mode. | +| `scopes` | String | Optional | The OAuth 2.0 scope to request. Specify a single scope. Default is `https://www.googleapis.com/auth/cloud-platform`. | + +## Next steps + +- To find the blueprint for your model, including Gemini, embeddings, streaming, and batch inference, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). +- To register and deploy a model that uses this connector, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). diff --git a/_ml-commons-plugin/remote-models/guardrails.md b/_ml-commons-plugin/remote-models/guardrails.md new file mode 100644 index 00000000..9901a386 --- /dev/null +++ b/_ml-commons-plugin/remote-models/guardrails.md @@ -0,0 +1,642 @@ +--- +layout: default +title: Guardrails +has_children: false +has_toc: false +nav_order: 70 +parent: Connecting to externally hosted models +grand_parent: Integrating ML models +--- + +# Configuring model guardrails +**Introduced 2.13** +{: .label .label-purple } + +Guardrails can guide a large language model (LLM) toward desired behavior. They act as a filter, preventing the LLM from generating output that is harmful or violates ethical principles and facilitating safer use of AI. Guardrails also cause the LLM to produce more focused and relevant output. + +You can configure guardrails for your LLM using the following methods: +- Provide a list of words to be prohibited in the input or output of the model. Alternatively, you can provide a regular expression against which the model input or output will be matched. For more information, see [Validating input/output using stopwords and regex](#validating-inputoutput-using-stopwords-and-regex). +- Configure a separate LLM whose purpose is to validate the user input and the LLM output. + +## Prerequisites + +Before you start, make sure you have fulfilled the [prerequisites]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/#prerequisites) for connecting to an externally hosted model. + +## Validating input/output using stopwords and regex +**Introduced 2.13** +{: .label .label-purple } + +A simple way to validate the user input and LLM output is to provide a set of prohibited words (stopwords) or a regular expression for validation. + +### Step 1: Create a guardrail index + +To start, create an index that will store the excluded words (_stopwords_). In the index settings, specify a `title` field, which will contain excluded words, and a `query` field of the [percolator]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/percolator/) type. The percolator query will be used to match the LLM input or output: + +```json +PUT /words0 +{ + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "query": { + "type": "percolator" + } + } + } +} +``` +{% include copy-curl.html %} + +### Step 2: Index excluded words or phrases + +Next, index a query string query that will be used to match excluded words in the model input or output: + +```json +PUT /words0/_doc/1?refresh +{ + "query": { + "query_string": { + "query": "title: blacklist" + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /words0/_doc/2?refresh +{ + "query": { + "query_string": { + "query": "title: \"Master slave architecture\"" + } + } +} +``` +{% include copy-curl.html %} + +For more query string options, see [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). + +### Step 3: Register a model group + +To register a model group, send the following request: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "bedrock", + "description": "This is a public model group." +} +``` +{% include copy-curl.html %} + +The response contains the model group ID that you'll use to register a model to this model group: + +```json +{ + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "status": "CREATED" +} +``` + +To learn more about model groups, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). + +### Step 4: Create a connector + +Now you can create a connector for the model. In this example, you'll create a connector to the Anthropic Claude model hosted on Amazon Bedrock: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "BedRock test claude Connector", + "description": "The connector to BedRock service for claude model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "anthropic_version": "bedrock-2023-05-31", + "endpoint": "bedrock.us-east-1.amazonaws.com", + "auth": "Sig_V4", + "content_type": "application/json", + "max_tokens": 8000, + "temperature": 0.0001, + "response_filter": "$.content[0].text" + }, + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" + } + ] +} +``` +{% include copy-curl.html %} + +The response contains the connector ID for the newly created connector: + +```json +{ + "connector_id": "a1eMb4kBJ1eYAeTMAljY" +} +``` + +### Step 5: Register and deploy the model with guardrails + +To register an externally hosted model, provide the model group ID from step 3 and the connector ID from step 4 in the following request. To configure guardrails, include the `guardrails` object: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Bedrock Claude Sonnet 4.6 model", + "function_name": "remote", + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "description": "test model", + "connector_id": "a1eMb4kBJ1eYAeTMAljY", + "guardrails": { + "type": "local_regex", + "input_guardrail": { + "stop_words": [ + { + "index_name": "words0", + "source_fields": [ + "title" + ] + } + ], + "regex": [ + ".*abort.*", + ".*kill.*" + ] + }, + "output_guardrail": { + "stop_words": [ + { + "index_name": "words0", + "source_fields": [ + "title" + ] + } + ], + "regex": [ + ".*abort.*", + ".*kill.*" + ] + } + } +} +``` +{% include copy-curl.html %} + +For more information, see [The `guardrails` parameter]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-guardrails-parameter). + +OpenSearch returns the task ID of the register operation and the model ID of the registered model: + +```json +{ + "task_id": "cVeMb4kBJ1eYAeTMFFgj", + "status": "CREATED", + "model_id": "cleMb4kBJ1eYAeTMFFg4" +} +``` + +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): + +```json +GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj +``` +{% include copy-curl.html %} + +When the operation is complete, the state changes to `COMPLETED`: + +```json +{ + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "n-72khvBTBi3bnIIR8FTTw" + ], + "create_time": 1689793851077, + "last_update_time": 1689793851101, + "is_async": false +} +``` + +### Step 6 (Optional): Test the model + +To demonstrate how guardrails are applied, first run the predict operation that does not contain any excluded words: + +```json +POST /_plugins/_ml/models/p94dYo4BrXGpZpgPp98E/_predict +{ + "parameters": { + "prompt": "this is a test" + } +} +``` +{% include copy-curl.html %} + +The response contains the LLM answer: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "This is a response!\n\nYour message came through successfully. How can I help you today?" + } + } + ], + "status_code": 200 + } + ] +} +``` + +Then run the predict operation that contains excluded words: + +```json +POST /_plugins/_ml/models/p94dYo4BrXGpZpgPp98E/_predict +{ + "parameters": { + "prompt": "this is a test of Master slave architecture" + } +} +``` +{% include copy-curl.html %} + +The response contains an error message because guardrails were triggered: + +```json +{ + "error": { + "root_cause": [ + { + "type": "illegal_argument_exception", + "reason": "guardrails triggered for user input" + } + ], + "type": "illegal_argument_exception", + "reason": "guardrails triggered for user input" + }, + "status": 400 +} +``` + +Guardrails are also triggered when a prompt matches the supplied regular expression. + +## Validating input/output using a guardrail model +**Introduced 2.15** +{: .label .label-purple } + +For more advanced validation, you can configure a guardrail model---a separate LLM whose purpose is to validate the user input and the LLM output. In this example, you'll configure two models: +- Chat model: An Anthropic Claude model hosted on Amazon Bedrock whose purpose is to hold a conversation with a user. +- Guardrail model: An OpenAI model whose purpose is to validate the user input and Anthropic Claude output. + +### Step 1: Create a connector for the guardrail model + +First, create a connector to the OpenAI guardrail model. Note that the OpenAI prompt instructs the model to respond only with the words `accept` or `reject`, depending on whether the input/output is acceptable. Additionally, the request contains the `response_filter` parameter, which specifies the field in which the guardrail model will provide the validation result: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "openai", + "description": "openai", + "version": "1", + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "max_tokens": 7, + "temperature": 0, + "model": "gpt-4o-mini", + "prompt": "You are a helpful assistant and an expert judge of content quality. Your task is to identify whether the input string below contains content that may be malicious, violent, hateful, sexual, or political in nature. Your answer should consist of a single word, either reject or accept. If the input belongs to any of these categories, please write reject. Otherwise, write accept. \\n\\nHere is the input: ${parameters.question}. \\n\\nYour answer: ", + "response_filter": "$.choices[0].message.content" + }, + "credential": { + "openAI_key": "<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\": [{\"role\": \"user\", \"content\": \"${parameters.prompt}\"}], \"max_tokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }" + } + ] +} +``` +{% include copy-curl.html %} + +The response contains the connector ID used in the next steps: + +```json +{ + "connector_id": "j3JVDZABNFJeYR3IVPRz" +} +``` + +### Step 2: Register a model group for the guardrail model + +To register a model group for the OpenAI guardrail model, send the following request: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "guardrail model group", + "description": "This is a guardrail model group." +} +``` +{% include copy-curl.html %} + +The response contains the model group ID used to register a model to this model group: + +```json +{ + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "status": "CREATED" +} +``` + +To learn more about model groups, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). + +### Step 3: Register and deploy the guardrail model + +Using the connector ID and the model group ID, register and deploy the OpenAI guardrail model: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "openai guardrails model", + "function_name": "remote", + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "description": "guardrails test model", + "connector_id": "j3JVDZABNFJeYR3IVPRz" +} +``` +{% include copy-curl.html %} + +OpenSearch returns the task ID of the register operation and the model ID of the registered model: + +```json +{ + "task_id": "onJaDZABNFJeYR3I2fQ1", + "status": "CREATED", + "model_id": "o3JaDZABNFJeYR3I2fRV" +} +``` + +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): + +```json +GET /_plugins/_ml/tasks/onJaDZABNFJeYR3I2fQ1 +``` +{% include copy-curl.html %} + +When the operation is complete, the state changes to `COMPLETED`: + +```json +{ + "model_id": "o3JaDZABNFJeYR3I2fRV", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "n-72khvBTBi3bnIIR8FTTw" + ], + "create_time": 1689793851077, + "last_update_time": 1689793851101, + "is_async": false +} +``` + +### Step 4 (Optional): Test the guardrail model + +You can test the guardrail model user input validation by sending requests that do and do not contain offensive words. + +First, send a request that does not contain offensive words: + +```json +POST /_plugins/_ml/models/o3JaDZABNFJeYR3I2fRV/_predict +{ + "parameters": { + "question": "how many indices do i have in my cluster" + } +} +``` +{% include copy-curl.html %} + +The guardrail model accepts the preceding request: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "accept" + } + } + ], + "status_code": 200 + } + ] +} +``` + +Next, send a request that contains offensive words: + +```json +POST /_plugins/_ml/models/o3JaDZABNFJeYR3I2fRV/_predict +{ + "parameters": { + "question": "how to rob a bank" + } +} +``` +{% include copy-curl.html %} + +The guardrail model rejects the preceding request: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "reject" + } + } + ], + "status_code": 200 + } + ] +} +``` + +### Step 5: Create a connector for the chat model + +In this example, the chat model will be an Anthropic Claude model hosted on Amazon Bedrock. To create a connector for the model, send the following request. Note that the `response_filter` parameter specifies the field in which the guardrail model will provide the validation result: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "BedRock claude Connector", + "description": "BedRock claude Connector", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "anthropic_version": "bedrock-2023-05-31", + "endpoint": "bedrock.us-east-1.amazonaws.com", + "auth": "Sig_V4", + "content_type": "application/json", + "max_tokens": 8000, + "temperature": 0.0001, + "response_filter": "$.content[0].text" + }, + "credential": { + "access_key": "<access_key>", + "secret_key": "<secret_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" + } + ] +} +``` +{% include copy-curl.html %} + +The response contains the connector ID used in the next steps: + +```json +{ + "connector_id": "xnJjDZABNFJeYR3IPvTO" +} +``` + +### Step 6: Register and deploy the chat model with guardrails + +To register and deploy the Anthropic Claude chat model, send the following request. Note that the `guardrails` object contains a `response_validation_regex` parameter that specifies to only treat the input/output as valid if the guardrail model responds with a variant of the word `accept`: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Bedrock Claude Sonnet 4.6 model with openai guardrails model", + "function_name": "remote", + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "description": "Bedrock Claude Sonnet 4.6 model with openai guardrails model", + "connector_id": "xnJjDZABNFJeYR3IPvTO", + "guardrails": { + "input_guardrail": { + "model_id": "o3JaDZABNFJeYR3I2fRV", + "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$" + }, + "output_guardrail": { + "model_id": "o3JaDZABNFJeYR3I2fRV", + "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$" + }, + "type": "model" + } +} +``` +{% include copy-curl.html %} + +OpenSearch returns the task ID of the register operation and the model ID of the registered model: + +```json +{ + "task_id": "1nJnDZABNFJeYR3IvfRL", + "status": "CREATED", + "model_id": "43JqDZABNFJeYR3IQPQH" +} +``` + +### Step 7 (Optional): Test the chat model with guardrails + +You can test the Anthropic Claude chat model with guardrails by sending predict requests that do and do not contain offensive words. + +First, send a request that does not contain offensive words: + +```json +POST /_plugins/_ml/models/43JqDZABNFJeYR3IQPQH/_predict +{ + "parameters": { + "prompt": "${parameters.question}", + "question": "hello" + } +} +``` +{% include copy-curl.html %} + +OpenSearch responds with the LLM answer: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "Hello! How are you doing? Is there something I can help you with today?" + } + } + ], + "status_code": 200 + } + ] +} +``` + +Next, send a request that contains offensive words: + +```json +POST /_plugins/_ml/models/43JqDZABNFJeYR3IQPQH/_predict +{ + "parameters": { + "prompt": "${parameters.question}", + "question": "how to rob a bank" + } +} +``` +{% include copy-curl.html %} + +OpenSearch responds with an error. + +## Next steps + +- For more information about configuring guardrails, see [The `guardrails` parameter]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-guardrails-parameter). +- For a tutorial demonstrating how to use Amazon Bedrock guardrails, see [Amazon Bedrock model guardrails]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/model-controls/bedrock-guardrails/). \ No newline at end of file diff --git a/_ml-commons-plugin/remote-models/http-authentication.md b/_ml-commons-plugin/remote-models/http-authentication.md new file mode 100644 index 00000000..40eff76f --- /dev/null +++ b/_ml-commons-plugin/remote-models/http-authentication.md @@ -0,0 +1,223 @@ +--- +layout: default +title: HTTP authentication +has_children: false +nav_order: 40 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +--- + +# HTTP authentication + +Connectors that use the `http` protocol authenticate to an externally hosted model using the values in the connector's `credential` object. Most endpoints accept a token, such as an API key, which the connector passes in a request header. Endpoints that require mutual TLS (mTLS) accept a client certificate instead. + +## Token authentication + +To authenticate with a token, provide the token in the `credential` object and reference it from a request header using a `${credential.*}` placeholder. The field name is arbitrary---the blueprint for your platform specifies which name to use, such as `openAI_key` or `cohere_key`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI Chat Connector", + "description": "The connector to public OpenAI model service for gpt-4o-mini", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-4o-mini" + }, + "credential": { + "openAI_key": "<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} }" + } + ] +} +``` +{% include copy-curl.html %} + +For the token field name and header format that your platform expects, see the blueprint for your platform and model in [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). + +## Client certificate authentication +**Introduced 3.9** +{: .label .label-purple } + +Client certificate authentication, also called mutual TLS (mTLS), allows a connector to present a client certificate when connecting to an externally hosted model. Both sides of the connection authenticate each other during the TLS handshake: the endpoint proves its identity with a server certificate, and the connector proves its identity with a client certificate. Use mTLS when the model endpoint requires a client certificate rather than a token passed in a request header. + +To enable mTLS, set `mutual_tls_enabled` to `true` in the connector's `client_config` object and provide the certificate material in the connector's `credential` object. + +### Request body fields + +When `mutual_tls_enabled` is set to `true`, the `credential` object supports the following certificate fields. Provide the certificate content itself, either as PEM text with newlines escaped as `\n` or as Base64-encoded content; file paths are not supported. OpenSearch encrypts these fields in the same way as any other credential and makes them available on every node, so you don't need to copy certificate files to individual nodes. + +| Field | Data type | Required/Optional | Description | +|:---|:---|:---|:---| +| `client_cert_pem` | String | Required when `keystore_type` is `PEM` | The client certificate in PEM format. To present a certificate issued by an intermediate certificate authority (CA), include the full chain, ordered leaf certificate first. | +| `client_key_pem` | String | Required when `keystore_type` is `PEM` | The client private key in PEM format. Must be a non-encrypted PKCS #8 key (`-----BEGIN PRIVATE KEY-----`); PKCS #1 keys are not supported. | +| `client_cert_pkcs12` | String | Required when `keystore_type` is `PKCS12` | The Base64-encoded PKCS12 keystore containing the client certificate and private key. | +| `keystore_password` | String | Optional | The password protecting the PKCS12 keystore. Omit it for a keystore that has no password. | +| `ca_cert_pem` | String | Optional | One or more CA certificates, in PEM format, used to validate the endpoint's server certificate. Accepts a bundle of intermediate and root certificates. If omitted, the Java default truststore is used. Provide this field when the endpoint uses a private CA. | + +The `mutual_tls_enabled` and `keystore_type` fields belong to the connector's `client_config` object. For descriptions of both, see [The client_config object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#the-client_config-object). + +### Prerequisites + +Before you configure mTLS, ensure that the following requirements are met: + +- Client certificate authentication is enabled on the cluster. It is disabled by default, and connector requests that set `mutual_tls_enabled` to `true` are rejected with a `403` error until you enable it. To enable it, set the `plugins.ml_commons.connector.mutual_tls_enabled` cluster setting to `true`: + + ```json + PUT /_cluster/settings + { + "persistent": { + "plugins.ml_commons.connector.mutual_tls_enabled": true + } + } + ``` + {% include copy-curl.html %} + +- The connector uses the `http` protocol. For more information, see [Restrictions](#restrictions). +- The endpoint URL matches a trusted endpoint. For more information, see [Adding trusted endpoints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index#adding-trusted-endpoints). +- Private keys in PEM format are non-encrypted and use PKCS #8 encoding (`-----BEGIN PRIVATE KEY-----`). PKCS #1 keys (`-----BEGIN RSA PRIVATE KEY-----`) are not supported. To convert a PKCS #1 key to PKCS #8, use the following command: + +```bash +openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in rsa_key.pem -out pkcs8_key.pem +``` +{% include copy.html %} + +Base64-encoded PEM values are detected and decoded automatically. Because Base64 encoding avoids escaping newlines by hand, it is the more convenient option for multiline certificates. To Base64-encode a certificate or key, use the following command: + +```bash +base64 -i client-cert.pem +``` +{% include copy.html %} + +### Using PEM certificates + +To authenticate with a PEM certificate and private key, set `keystore_type` to `PEM` and provide `client_cert_pem` and `client_key_pem`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Externally hosted model connector with mutual TLS", + "description": "A connector that authenticates using a client certificate", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.example.com" + }, + "credential": { + "client_cert_pem": "<BASE64-ENCODED CLIENT CERTIFICATE>", + "client_key_pem": "<BASE64-ENCODED PRIVATE KEY>", + "ca_cert_pem": "<BASE64-ENCODED CA CERTIFICATE>" + }, + "client_config": { + "mutual_tls_enabled": true, + "keystore_type": "PEM" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/predict", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"input\": \"${parameters.input}\" }" + } + ] +} +``` +{% include copy-curl.html %} + +Because `PEM` is the default, you can omit `keystore_type` when using PEM certificates. +{: .note} + +### Using a PKCS12 keystore + +To authenticate with a PKCS12 keystore, set `keystore_type` to `PKCS12` and provide the Base64-encoded keystore in `client_cert_pkcs12`. A PKCS12 keystore is binary, so it must always be Base64 encoded: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Externally hosted model connector with a PKCS12 keystore", + "description": "A connector that authenticates using a client certificate", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.example.com" + }, + "credential": { + "client_cert_pkcs12": "<BASE64-ENCODED PKCS12 KEYSTORE>", + "keystore_password": "<KEYSTORE PASSWORD>", + "ca_cert_pem": "<BASE64-ENCODED CA CERTIFICATE>" + }, + "client_config": { + "mutual_tls_enabled": true, + "keystore_type": "PKCS12" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/predict", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"input\": \"${parameters.input}\" }" + } + ] +} +``` +{% include copy-curl.html %} + +To create a PKCS12 keystore from an existing PEM certificate and key and then Base64-encode it, use the following commands: + +```bash +openssl pkcs12 -export -in client-cert.pem -inkey client-key.pem -out client.p12 -name client +base64 -i client.p12 +``` +{% include copy.html %} + +### Certificate chains and custom CA certificates + +If your client certificate is issued by an intermediate certificate authority (CA), include the full chain in `client_cert_pem`. Order the chain leaf first, followed by each issuing intermediate certificate, so that every certificate is issued by the one that follows it. A misordered chain is rejected with an error that identifies the certificates involved. + +The `ca_cert_pem` field is optional and controls how the endpoint's server certificate is validated: + +- If you provide `ca_cert_pem`, OpenSearch validates the server certificate against only the certificates it contains. The field accepts a bundle, so you can include both intermediate and root certificates. Provide this field when the endpoint uses a private CA. +- If you omit `ca_cert_pem`, OpenSearch validates the server certificate against the Java default truststore. + +Because a private CA is usually not present in the default truststore, provide `ca_cert_pem` rather than setting `skip_ssl_verification` to `true`. Skipping verification is rejected when mTLS is enabled. +{: .important} + +### Rotating certificates + +To rotate an expiring certificate, send the new certificate material in an update request, as described in [Updating connector credentials]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#updating-connector-credentials). You don't need to undeploy the model or restart any nodes. + +OpenSearch detects the change and builds a new HTTP client for subsequent predict requests. The replaced client is closed after a grace period, so requests already in flight complete against the previous certificate. + +### Restrictions + +The following restrictions apply to client certificate authentication: + +- mTLS applies only to connectors that use the `http` protocol and is not applied to streaming requests. Creating a connector that uses another protocol, such as `aws_sigv4`, with `mutual_tls_enabled` set to `true` returns a `400` error. +- `skip_ssl_verification` and `mutual_tls_enabled` cannot both be set to `true`. Disabling server certificate validation removes the mutual part of mutual TLS, so provide `ca_cert_pem` to validate the server certificate against a private CA. +- The `credential` object cannot contain `api_key` when mTLS is enabled. OpenSearch enforces certificate-only authentication and rejects mixed authentication methods. +- File paths are not supported in certificate fields. Provide the certificate content itself. +- Certificate material and the preceding `skip_ssl_verification` and `api_key` restrictions are validated on the first predict request. A connector with an invalid certificate configuration is created successfully and fails when it is first used. + +## Next steps + +- To find the blueprint for your platform and model, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). +- To register and deploy a model that uses this connector, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). +- For descriptions of all connector fields, including the `client_config` object, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). diff --git a/_ml-commons-plugin/remote-models/index.md b/_ml-commons-plugin/remote-models/index.md index 0b9c6d03..cda91b16 100644 --- a/_ml-commons-plugin/remote-models/index.md +++ b/_ml-commons-plugin/remote-models/index.md @@ -7,28 +7,26 @@ has_toc: false nav_order: 60 redirect_from: - /ml-commons-plugin/extensibility/index/ + - /ml-commons-plugin/remote-models/ --- # Connecting to externally hosted models **Introduced 2.9** {: .label .label-purple } -Integrations with machine learning (ML) models hosted on third-party platforms allow system administrators and data scientists to run ML workloads outside of their OpenSearch cluster. Connecting to externally hosted models enables ML developers to create integrations with other ML services, such as Amazon SageMaker or OpenAI. +OpenSearch can use machine learning (ML) models hosted outside your cluster, such as embedding models and large language models (LLMs) on Amazon Bedrock, Amazon SageMaker, OpenAI, or Cohere. OpenSearch calls the model API each time it needs a result, for example, to generate embeddings for documents during ingestion, to generate an embedding for a semantic search query, to rerank search results, or to generate answers in conversational search and agents. -To integrate a model hosted on a third-party platform, choose from the following options: - -- If you're an ML developer wanting to create integrations with your specific ML services, see [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). -- If you're a system administrator or data scientist wanting to create a connection to an ML service, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). +To call a model, OpenSearch uses a _connector_, which stores the model endpoint URL, the credentials, and a template for the request body. After you create a connector, you can register the model and use it in search requests, ingest pipelines, and agents. For more information, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). ## Prerequisites -If you're an admin deploying an ML connector, make sure that the target model of the connector has already been deployed on your chosen platform. Furthermore, make sure that you have permissions to send and receive data to the third-party API for your connector. +Before you create a connector, ensure that the model is deployed on its platform and that you have credentials that allow you to call the model API. -When access control is enabled on your third-party platform, you can enter your security settings using the `authorization` or `credential` settings inside the connector API. +If your model platform requires authentication, provide the credentials in the connector `credential` object. Depending on the platform, OpenSearch either signs requests using these credentials or sends them in a request header that refers to them, for example, `"Authorization": "Bearer ${credential.openAI_key}"`. For more information, see [Connector authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-authentication/). ### Adding trusted endpoints -To configure connectors in OpenSearch, add the trusted endpoints to your cluster settings by using the `plugins.ml_commons.trusted_connector_endpoints_regex` setting, which supports Java regex expressions: +To configure connectors in OpenSearch, add the trusted endpoints to your cluster settings by using the `plugins.ml_commons.trusted_connector_endpoints_regex` setting, which supports Java regex expressions. The following request sets the default list of trusted endpoints. To trust another endpoint, add its pattern to this list: ```json PUT /_cluster/settings @@ -36,23 +34,37 @@ PUT /_cluster/settings "persistent": { "plugins.ml_commons.trusted_connector_endpoints_regex": [ "^https://runtime\\.sagemaker\\..*[a-z0-9-]\\.amazonaws\\.com/.*$", + "^https://api\\.sagemaker\\..*[a-z0-9-]\\.amazonaws\\.com/.*$", "^https://api\\.openai\\.com/.*$", "^https://api\\.cohere\\.ai/.*$", - "^https://bedrock-runtime\\..*[a-z0-9-]\\.amazonaws\\.com/.*$" + "^https://api\\.deepseek\\.com/.*$", + "^https://generativelanguage\\.googleapis\\.com/.*$", + "^https://([a-z0-9][a-z0-9-]*-)?aiplatform\\.googleapis\\.com/.*$", + "^https://bedrock-runtime\\..*[a-z0-9-]\\.amazonaws\\.com/.*$", + "^https://bedrock-agent-runtime\\..*[a-z0-9-]\\.amazonaws\\.com/.*$", + "^https://bedrock\\..*[a-z0-9-]\\.amazonaws\\.com/.*$", + "^https://textract\\..*[a-z0-9-]\\.amazonaws\\.com$", + "^https://comprehend\\..*[a-z0-9-]\\.amazonaws\\.com$", + "^https://rekognition(-fips)?\\..*[a-z0-9-]\\.amazonaws\\.com$" ] } } ``` {% include copy-curl.html %} +This setting replaces the entire list of trusted endpoints, so include every pattern your cluster needs. +{: .note} +If your model runs on a private network, for example, a model served by Ollama on the same host or on an internal server, also set `plugins.ml_commons.connector.private_ip_enabled` to `true`. If you change this setting after deploying a model, redeploy the model to apply the change. For more information, see [ML Commons cluster settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/). -### Setting up connector access control +Starting with OpenSearch 3.10, some addresses are always refused regardless of settings. For all endpoint address restrictions, see [Breaking changes]({{site.url}}{{site.baseurl}}/breaking-changes/#ml-commons-plugin-1). +{: .important} -If you plan on using a remote connector, make sure to use an OpenSearch cluster with the Security plugin enabled. Using the Security plugin gives you access to connector access control, which is required when using a remote connector. -{: .warning} +### Configuring connector access control -If you require granular access control for your connectors, use the following cluster setting: +To control which users can access a connector, enable the Security plugin and connector access control. Without the Security plugin, OpenSearch doesn't restrict connector access: any client that can send requests to the cluster can use all connectors. + +To enable connector access control, update the following cluster setting: ```json PUT /_cluster/settings @@ -64,7 +76,7 @@ PUT /_cluster/settings ``` {% include copy-curl.html %} -When access control is enabled, you can install the [Security plugin]({{site.url}}{{site.baseurl}}/security/index/). This makes the `backend_roles`, `add_all_backend_roles`, or `access_model` options required in order to use the connector API. If successful, OpenSearch returns the following response: +If successful, OpenSearch returns the following response: ```json { @@ -80,54 +92,27 @@ When access control is enabled, you can install the [Security plugin]({{site.url } ``` -## Step 1: Register a model group +When both the [Security plugin]({{site.url}}{{site.baseurl}}/security/index/) and connector access control are enabled, you can control access to a connector by providing the `backend_roles`, `add_all_backend_roles`, or `access_mode` options when you create it. If you don't provide any of these options, the connector is private. If either the Security plugin or connector access control is disabled, the Create Connector API rejects requests that contain these options. -To register a model, you have the following options: +## Step 1: Create a connector -- You can use `model_group_id` to register a model version to an existing model group. -- If you do not use `model_group_id`, ML Commons creates a model with a new model group. +OpenSearch provides connector blueprints that you can use to connect to different models and platforms. To find a connector to your model, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/). -To register a model group, send the following request: - -```json -POST /_plugins/_ml/model_groups/_register -{ - "name": "remote_model_group", - "description": "A model group for external models" -} -``` -{% include copy-curl.html %} - -The response contains the model group ID that you'll use to register a model to this model group: - -```json -{ - "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", - "status": "CREATED" -} -``` - -To learn more about model groups, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). - -## Step 2: Create a connector - -You can create a standalone connector that can be reused for multiple models. Alternatively, you can specify a connector when creating a model so that it can be used only for that model. For more information and example connectors, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). - -The Connectors Create API, `/_plugins/_ml/connectors/_create`, creates connectors that facilitate registering and deploying external models in OpenSearch. Using the `endpoint` parameter, you can connect ML Commons to any supported ML tool by using its specific API endpoint. For example, you can connect to a ChatGPT model by using the `api.openai.com` endpoint: +To create a connector, send a [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/) request containing the connector definition from the blueprint for your model. The following request creates a connector to the OpenAI `gpt-4o-mini` chat model. The `endpoint` and `model` values in the connector `parameters` object fill the placeholders in the `url` and `request_body` templates: ```json POST /_plugins/_ml/connectors/_create { "name": "OpenAI Chat Connector", - "description": "The connector to public OpenAI model service for GPT 3.5", + "description": "The connector to public OpenAI model service for gpt-4o-mini", "version": 1, "protocol": "http", "parameters": { "endpoint": "api.openai.com", - "model": "gpt-3.5-turbo" + "model": "gpt-4o-mini" }, "credential": { - "openAI_key": "..." + "openAI_key": "<openai_api_key>" }, "actions": [ { @@ -152,34 +137,38 @@ The response contains the connector ID for the newly created connector: } ``` -## Step 3: Register an externally hosted model +The preceding request creates a standalone connector, which several models can use. To create a connector that only one model can use, provide the connector definition when you register the model. For more information, see [Creating a connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/#creating-a-connector). -To register an externally hosted model to the model group created in step 1, provide the model group ID from step 1 and the connector ID from step 2 in the following request. You must specify the `function_name` as `remote`: +## Step 2: Register an externally hosted model + +To register an externally hosted model, provide the connector ID from Step 1 in the following request. You must specify the `function_name` as `remote`: ```json POST /_plugins/_ml/models/_register { - "name": "openAI-gpt-3.5-turbo", + "name": "openAI-gpt-4o-mini", "function_name": "remote", - "model_group_id": "1jriBYsBq7EKuKzZX131", "description": "test model", "connector_id": "a1eMb4kBJ1eYAeTMAljY" } ``` {% include copy-curl.html %} -OpenSearch returns the task ID of the register operation: +OpenSearch returns the task ID of the register operation and the model ID of the registered model: ```json { "task_id": "cVeMb4kBJ1eYAeTMFFgj", - "status": "CREATED" + "status": "CREATED", + "model_id": "cleMb4kBJ1eYAeTMFFg4" } ``` -To check the status of the operation, provide the task ID to the [Tasks API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): +OpenSearch creates a model group for the model. Model groups control which users can access a model. When the Security plugin and model access control are enabled, the new model group is private by default. For more information, see [Model access control]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-access-control/). -```bash +To check the status of the operation, provide the task ID to the [Get ML Task API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/tasks-apis/get-task/): + +```json GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj ``` {% include copy-curl.html %} @@ -201,53 +190,13 @@ When the operation is complete, the state changes to `COMPLETED`: } ``` -Take note of the returned `model_id` because you’ll need it to deploy the model. +Note the returned `model_id`; you'll need it to use the model. -## Step 4: Deploy the model +OpenSearch deploys the model automatically when you send the first Predict API request for it. If automatic deployment is turned off using the `plugins.ml_commons.model_auto_deploy.enable` setting, deploy the model using the [Deploy API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/deploy-model/) before you send requests to it. For more information, see [ML Commons cluster settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/). -To deploy the registered model, provide its model ID from step 3 in the following request: +## Step 3 (Optional): Test the model -```bash -POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_deploy -``` -{% include copy-curl.html %} - -The response contains the task ID that you can use to check the status of the deploy operation: - -```json -{ - "task_id": "vVePb4kBJ1eYAeTM7ljG", - "status": "CREATED" -} -``` - -As in the previous step, check the status of the operation by calling the Tasks API: - -```bash -GET /_plugins/_ml/tasks/vVePb4kBJ1eYAeTM7ljG -``` -{% include copy-curl.html %} - -When the operation is complete, the state changes to `COMPLETED`: - -```json -{ - "model_id": "cleMb4kBJ1eYAeTMFFg4", - "task_type": "DEPLOY_MODEL", - "function_name": "REMOTE", - "state": "COMPLETED", - "worker_node": [ - "n-72khvBTBi3bnIIR8FTTw" - ], - "create_time": 1689793851077, - "last_update_time": 1689793851101, - "is_async": true -} -``` - -## Step 5 (Optional): Test the model - -Use the [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) to test the model: +To test the model, send a [Predict API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/train-predict/predict/) request. In the `parameters` object, provide values for the placeholders in the connector request body template. For this connector, provide only `messages`, because the connector `parameters` object provides a default value for `model`. For more information, see [Providing input as parameters]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/#providing-input-as-parameters): ```json POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict @@ -270,7 +219,7 @@ POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict To learn more about chat functionality within OpenAI, see the [OpenAI Chat API](https://platform.openai.com/docs/api-reference/chat). -The response contains the inference results provided by the OpenAI model: +The `dataAsMap` object in the response contains the OpenAI response: ```json { @@ -283,7 +232,7 @@ The response contains the inference results provided by the OpenAI model: "id": "chatcmpl-7e6s5DYEutmM677UZokF9eH40dIY7", "object": "chat.completion", "created": 1689793889, - "model": "gpt-3.5-turbo-0613", + "model": "gpt-4o-mini", "choices": [ { "index": 0, @@ -301,19 +250,31 @@ The response contains the inference results provided by the OpenAI model: } } } - ] + ], + "status_code": 200 } ] } ``` -## Step 6: Use the model for search +## Step 4: Use the model -To learn how to use the model for vector search, see [Using an ML model for neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/#using-an-ml-model-for-neural-search). +In this example, you connected to an OpenAI chat model, which you can use to generate answers from search results. For information about using chat models, see [Conversational search with RAG]({{site.url}}{{site.baseurl}}/vector-search/ai-search/conversational-search/). + +To learn how to use other types of models, such as embedding and rerank models, see [AI search methods]({{site.url}}{{site.baseurl}}/vector-search/ai-search/#ai-search-methods). + +To generate embeddings for large volumes of documents using an embedding model, see [Using externally hosted ML models for batch ingestion]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/batch-ingestion/). + +## Step 5 (Optional): Undeploy the model + +You can undeploy the model automatically by defining a time to live (TTL) in the model settings or by using the Undeploy API to undeploy the model manually. For more information, see [Undeploy API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/undeploy-model/). ## Next steps - For more information about connectors, including example connectors, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). -- For more information about connector parameters, see [Connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). +- To learn how a connector builds the request that it sends to the model and processes the model response, see [Connector input and output]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-input-output/). +- For more information about connector fields, see [Create Connector API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#request-body-fields). +- To create a connector and register and deploy a model in a single request, use a workflow template. For more information, see [Model deployment templates]({{site.url}}{{site.baseurl}}/vector-search/ai-search/workflows/workflow-templates/#model-deployment-templates). - For more information about managing ML models in OpenSearch, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/model-serving-framework/). -- For more information about interacting with ML models in OpenSearch, see [Managing ML models in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/ml-commons-plugin/ml-dashboard/) +- For more information about interacting with ML models in OpenSearch, see [Managing ML models in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/ml-commons-plugin/ml-dashboard/). +- To configure model guardrails, see [Guardrails]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/guardrails/). diff --git a/_ml-commons-plugin/remote-models/supported-connectors.md b/_ml-commons-plugin/remote-models/supported-connectors.md new file mode 100644 index 00000000..3aa45eb4 --- /dev/null +++ b/_ml-commons-plugin/remote-models/supported-connectors.md @@ -0,0 +1,92 @@ +--- +layout: default +title: OpenSearch-provided connector blueprints +has_children: false +nav_order: 10 +parent: Connectors +grand_parent: Connecting to externally hosted models +great_grand_parent: Integrating ML models +redirect_from: + - /ml-commons-plugin/extensibility/supported-connectors/ +--- + +# OpenSearch-provided connector blueprints + +OpenSearch provides two types of connector blueprints: + +- **Standard blueprints (recommended for OpenSearch 2.14+)**: + + - Designed for connectors that pass input directly to the model and return its raw output without requiring additional transformations. + - Use a registered model without any pre-processing or post-processing functions. + - Compatible with machine learning (ML) inference processors: [ingest processors]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/processors/ml-inference/), [search request processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-request/), and [search response processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-response/). + - Ideal for new implementations in OpenSearch 2.14 and later. + +- **Legacy blueprints**: + + - Suitable for specific input and output formatting requirements. + - Include pre- and post-processing functions. + - Recommended for existing implementations. + - Compatible with [semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/semantic-search/). + +## Find your model and platform + +OpenSearch provides connector blueprints for the following platforms and models. Each blueprint link provides an example request for creating the connector, including all required parameters, and an example Predict API request. The **Protocol** column links to the credential fields and cluster prerequisites for that platform's authentication method. For an overview of the available protocols, see [Connector authentication]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connector-authentication/). + +| Platform | Model | Protocol | Legacy blueprint | Standard blueprint | +|:-------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [Aleph Alpha](https://aleph-alpha.com/) | [Luminous-Base Embedding Model](https://docs.aleph-alpha.com/products/pharia-ai/pharia-os/references/inference/endpoints/semantic_embed/) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/aleph_alpha_connector_luminous_base_embedding_blueprint.md) | N/A | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [AI21 Labs Jurassic-2 Mid](https://aws.amazon.com/bedrock/jurassic/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v2](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v3](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v3.7](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3.7_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3.7_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v4](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude4_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude4_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Cohere Embed Model v3 - English](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-embed.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_cohere_cohere.embed-english-v3_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_cohere_cohere.embed-english-v3_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Cohere Embed Model v3 - Multilingual](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-embed.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_cohere_cohere.embed-multilingual-v3_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_cohere_cohere.embed-multilingual-v3_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Titan Text Embeddings](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_titan_embedding_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_titan_embedding_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Titan Multimodal Embeddings](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-multiemb-models.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_titan_multimodal_embedding_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_titan_multimodal_embedding_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Nova Multimodal Embeddings](https://docs.aws.amazon.com/nova/latest/userguide/modalities.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_nova_multimodal_model_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_nova_multimodal_model_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [OpenAI GPT-OSS](https://aws.amazon.com/bedrock/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_openai_gpt-oss_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_openai_gpt-oss_blueprint.md) | +| [Amazon Bedrock Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) | [Anthropic Claude 3 Sonnet](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_converse_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_converse_blueprint.md) | +| [Amazon Comprehend](https://aws.amazon.com/comprehend/) | [Metadata Embedding Model](https://docs.aws.amazon.com/comprehend/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_comprehend_connector_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_comprehend_connector_blueprint.md) | +| [Amazon Textract](https://aws.amazon.com/textract/) | [Amazon Textract Model](https://docs.aws.amazon.com/textract/) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_textract_connector_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_textract_connector_blueprint.md) | +| [Amazon SageMaker](https://aws.amazon.com/sagemaker/) | [Text embedding models for batch inference](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_sagemaker_connector_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_sagemaker_connector_blueprint.md) | +| [Amazon SageMaker](https://aws.amazon.com/sagemaker/) | [Text embedding models](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/sagemaker_connector_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/sagemaker_connector_blueprint.md) | +| [Amazon SageMaker](https://aws.amazon.com/sagemaker/) | [Semantic highlighter models](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | N/A | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/sagemaker_semantic_highlighter_standard_blueprint.md) | +| [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) | [Chat models](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=global-standard%2Cstandard-chat-completions#gpt-4) (for example, `gpt-4`) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/azure_openai_connector_chat_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/azure_openai_connector_chat_blueprint.md) | +| [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) | [Text embedding models](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings) (for example, `text-embedding-ada-002`) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/azure_openai_connector_embedding_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/azure_openai_connector_embedding_standard_blueprint.md) | +| [Cohere](https://cohere.com/) | [Chat models](https://docs.cohere.com/reference/chat) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_chat_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_chat_blueprint.md) | +| [Cohere](https://cohere.com/) | [Multimodal embedding models](https://docs.cohere.com/reference/embed) (for example, `embed-english-v3.0`) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_image_embedding_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/cohere_connector_image_embedding_standard_blueprint.md) | +| [Cohere](https://cohere.com/) | [Text embedding models](https://docs.cohere.com/reference/embed) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_embedding_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/cohere_connector_text_embedding_standard_blueprint.md) | +| [DeepSeek](https://www.deepseek.com/) | [Chat model](https://api-docs.deepseek.com/api/create-chat-completion) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/deepseek_connector_chat_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/deepseek_connector_chat_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI Gemini](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini) | [`google_cloud`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/google-cloud/) | N/A | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_gemini_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI text embeddings](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings) | [`google_cloud`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/google-cloud/) | N/A | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_embedding_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI text embeddings](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings) (manually refreshed token) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | N/A | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_connector_embedding_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI Gemini streaming](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini) | [`google_cloud`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/google-cloud/) | N/A | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_streaming_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI batch inference](https://cloud.google.com/vertex-ai/docs/predictions/get-batch-predictions) | [`google_cloud`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/google-cloud/) | N/A | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_batch_blueprint.md) | +| [Ollama](https://ollama.ai/) | [Chat models](https://ollama.ai/library) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/ollama_connector_chat_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/ollama_connector_chat_blueprint.md) | +| [OpenAI](https://openai.com/) | [Chat models](https://platform.openai.com/docs/models) (for example, `gpt-4o-mini`) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_chat_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_chat_blueprint.md) | +| [OpenAI](https://openai.com/) | [Completion models](https://platform.openai.com/docs/models) (legacy; OpenAI retired the `/v1/completions` endpoint) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_completion_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_completion_blueprint.md) | +| [OpenAI](https://openai.com/) | [Text embedding models](https://platform.openai.com/docs/models#embeddings) (for example, `text-embedding-ada-002`) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/openai_connector_embedding_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/openai_connector_embedding_standard_blueprint.md) | +| [OpenAI](https://openai.com/) | [Text embedding models for batch inference](https://platform.openai.com/docs/guides/batch/overview#model-availability) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_openAI_connector_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_openAI_connector_blueprint.md) | +| [Yandex Cloud](https://yandex.cloud/en) | [Text embedding models](https://yandex.cloud/en/docs/ai-studio/concepts/embeddings) | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/yandexcloud_connector_embedding_legacy_blueprint.md) | [Blueprint](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/yandexcloud_connector_embedding_standard_blueprint.md) | + +## LLM judgment blueprints for Search Relevance Workbench + +[Search Relevance Workbench]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/) uses a chat model to generate relevance ratings using an LLM-as-a-Judge. For an overview of these blueprints, see [LLM judgment blueprints](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/README.md). The following table lists the available blueprints for connecting Search Relevance Workbench to a chat model. + +| Provider | Protocol | Blueprint | +|:---|:---|:---| +| OpenAI | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [GPT-5, GPT-4.1, GPT-4o](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/openai_chat_blueprint.md) | +| Azure OpenAI | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [GPT-5, GPT-4.1, GPT-4o](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/azure_openai_chat_blueprint.md) | +| DeepSeek | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [DeepSeek-V3, DeepSeek-R1](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/deepseek_chat_blueprint.md) | +| Ollama and other local OpenAI-compatible servers | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Qwen 3, Llama 3.3, Mistral, Phi-4, Gemma 3](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/ollama_chat_blueprint.md) | +| Google Gemini | [`http`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/http-authentication/) | [Gemini 2.5 Pro, Gemini 2.5 Flash](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/google_gemini_chat_blueprint.md) | +| Amazon Bedrock | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Anthropic Claude (native `invoke` API)](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/anthropic_claude_bedrock_blueprint.md) | +| Amazon Bedrock Converse | [`aws_sigv4`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/aws-sigv4/) | [Anthropic Claude, Amazon Nova, Meta Llama, Mistral, AI21, Cohere](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/bedrock_converse_blueprint.md) | + +For more information about using these blueprints with Search Relevance Workbench, see [Using different LLM providers]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/judgments/#using-different-llm-providers). + +## Next steps + +- To register and deploy a model that uses your connector, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). +- To create a connector for a platform or model that has no provided blueprint, see [Creating a custom blueprint]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/blueprints/). diff --git a/_ml-commons-plugin/using-ml-models.md b/_ml-commons-plugin/using-ml-models.md index 5c23e19a..28d49c51 100644 --- a/_ml-commons-plugin/using-ml-models.md +++ b/_ml-commons-plugin/using-ml-models.md @@ -3,25 +3,36 @@ layout: default title: Using ML models within OpenSearch parent: Integrating ML models has_children: true +has_toc: false nav_order: 50 redirect_from: - /ml-commons-plugin/model-serving-framework/ - /ml-commons-plugin/ml-framework/ +models: + - heading: "Pretrained models provided by OpenSearch" + link: "/ml-commons-plugin/pretrained-models/" + description: "Explore OpenSearch's collection of optimized ML models for immediate use in AI applications" + - heading: "Custom models" + link: "/ml-commons-plugin/custom-local-models/" + description: "Learn how to upload and serve your own ML models in OpenSearch for specialized use cases" +gpu: + - heading: "GPU acceleration" + link: "/ml-commons-plugin/gpu-acceleration/" + description: "Take advantage of GPU acceleration on your ML node for better performance" --- # Using ML models within OpenSearch -**Generally available 2.9** +**Introduced 2.9** {: .label .label-purple } -To integrate machine learning (ML) models into your OpenSearch cluster, you can upload and serve them locally. Choose one of the following options: +To integrate machine learning (ML) models into your OpenSearch cluster, you can upload and serve them locally. Choose one of the following options. -- **Pretrained models provided by OpenSearch**: To learn more, see [OpenSearch-provided pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/). For a list of supported models, see [Supported pretrained models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#supported-pretrained-models). +{% include cards.html cards=page.models %} -- **Custom models** such as PyTorch deep learning models: To learn more, see [Custom models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). +For production environments, run local models on dedicated ML nodes rather than data nodes. For more information, see [Node selection settings]({{site.url}}{{site.baseurl}}/ml-commons-plugin/cluster-settings/#node-selection-settings). +{: .important} Running local models on the CentOS 7 operating system is not supported. Moreover, not all local models can run on all hardware and operating systems. {: .important} -## GPU acceleration - -For better performance, you can take advantage of GPU acceleration on your ML node. For more information, see [GPU acceleration]({{site.url}}{{site.baseurl}}/ml-commons-plugin/gpu-acceleration/). +{% include cards.html cards=page.gpu %} diff --git a/_observing-your-data/ad/api.md b/_observing-your-data/ad/api.md index f9846bfc..9a2ef09b 100644 --- a/_observing-your-data/ad/api.md +++ b/_observing-your-data/ad/api.md @@ -1,13 +1,13 @@ --- layout: default -title: Anomaly detection API +title: Anomaly Detection APIs parent: Anomaly detection -nav_order: 1 +nav_order: 60 redirect_from: - /monitoring-plugins/ad/api/ --- -# Anomaly detection API +# Anomaly Detection APIs Use these anomaly detection operations to programmatically create and manage detectors. @@ -28,7 +28,7 @@ Creates an anomaly detector. This command creates a single-entity detector named `test-detector` that finds anomalies based on the sum of the `value` field and stores the result in a custom `opensearch-ad-plugin-result-test` index: -#### Request +#### Example request ```json POST _plugins/_anomaly_detection/detectors @@ -165,7 +165,7 @@ POST _plugins/_anomaly_detection/detectors To create a high cardinality detector by specifying a category field: -#### Request +#### Example request ```json POST _plugins/_anomaly_detection/detectors @@ -326,7 +326,7 @@ Options | Description | Type | Required `name` | The name of the detector. | `string` | Yes `description` | A description of the detector. | `string` | No `time_field` | The name of the time field. | `string` | Yes -`indices` | A list of indices to use as the data source. | `list` | Yes +`indices` | A list of indexes to use as the data source. | `list` | Yes `feature_attributes` | Specify a `feature_name`, set the `enabled` parameter to `true`, and specify an aggregation query. | `list` | Yes `filter_query` | Provide an optional filter query for your feature. | `object` | No `detection_interval` | The time interval for your anomaly detector. | `object` | Yes @@ -362,7 +362,7 @@ POST _plugins/_anomaly_detection/detectors/_validate/model Responses from this API operation return either blocking issues as detector type responses or a response indicating a field that could be revised to increase likelihood of model training completing successfully. Model type issues don’t need to be fixed for detector creation to succeed, but the detector would likely not train successfully if they aren’t addressed. -#### Request +#### Example request ```json POST _plugins/_anomaly_detection/detectors/_validate @@ -417,7 +417,7 @@ POST _plugins/_anomaly_detection/detectors/_validate/detector } ``` -If the validate detector API doesn’t find any issue in the detector configuration, it returns an empty response: +If the Validate Detector API doesn't find any issues in the detector configuration, it returns an empty response: #### Example response @@ -425,7 +425,7 @@ If the validate detector API doesn’t find any issue in the detector configurat {} ``` -If the validate detector API finds an issue, it returns a message explaining what's wrong with the configuration. In this example, the feature query aggregates over a field that doesn’t exist in the data source: +If the Validate Detector API finds a configuration issue, it returns a message explaining the issue. In this example, the feature query aggregates over a field that doesn't exist in the data source: #### Example response @@ -496,11 +496,11 @@ POST _plugins/_anomaly_detection/detectors/_validate/model } ``` -If the validate detector API finds areas of improvement with your configuration, it returns a response with suggestions about how you can change your configuration to improve model training. +If the Validate Detector API identifies areas of improvement in your configuration, it returns a response with suggestions for changing your configuration to improve model training. -#### Sample Responses +#### Example response -In this example, the validate detector API returns a response indicating that changing the detector interval length to at least four minutes can increase the chances of successful model training. +In this example, the Validate Detector API returns a response indicating that changing the detector interval length to at least 4 minutes can increase the probability of successful model training. ```json { @@ -538,10 +538,10 @@ Introduced 1.0 Returns all information about a detector based on the `detector_id`. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId> +GET _plugins/_anomaly_detection/detectors/{detectorId} ``` #### Example response @@ -624,21 +624,21 @@ GET _plugins/_anomaly_detection/detectors/<detectorId> } ``` -A "job" is something that you schedule to run periodically, so it's only applicable for real-time anomaly detection and not historical analysis that you run just one time. +A _job_ is something that you schedule to run periodically, so it's only applicable for real-time anomaly detection and not historical analysis that you run just one time. -When you start a real-time detector, the anomaly detection plugin creates a job or if the job already exists updates it. -When you start or a restart a real-time detector, the plugin creates a new real-time task that records run-time information like detector configuration snapshot, real-time job states (initializing/running/stopped), init progress, and so on. +When you start a real-time detector, OpenSearch creates a job or if the job already exists updates it. +When you start or restart a real-time detector, OpenSearch creates a new real-time task that records run-time information like detector configuration snapshot, real-time job states (initializing/running/stopped), init progress, and so on. A single detector can only have one real-time job (job ID is the same as detector ID), but it can have multiple real-time tasks because each restart of a real-time job creates a new real-time task. You can limit the number of real-time tasks with the `plugins.anomaly_detection.max_old_ad_task_docs_per_detector` setting. -Historical analysis doesn't have an associated job. When you start or rerun historical analysis for a detector, the anomaly detection plugin creates a new historical batch task that tracks the historical analysis runtime information like state, coordinating/worker node, task progress, and so on. You can limit the historical task number with the `plugins.anomaly_detection.max_old_ad_task_docs_per_detector` setting. +Historical analysis doesn't have an associated job. When you start or rerun historical analysis for a detector, OpenSearch creates a new historical batch task that tracks the historical analysis runtime information like state, coordinating/worker node, task progress, and so on. You can limit the historical task number with the `plugins.anomaly_detection.max_old_ad_task_docs_per_detector` setting. Use `job=true` to get real-time analysis task information. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>?job=true +GET _plugins/_anomaly_detection/detectors/{detectorId}?job=true ``` #### Example response @@ -755,10 +755,10 @@ GET _plugins/_anomaly_detection/detectors/<detectorId>?job=true Use `task=true` to get information for both real-time and historical analysis task information. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>?task=true +GET _plugins/_anomaly_detection/detectors/{detectorId}?task=true ``` #### Example response @@ -1049,10 +1049,10 @@ To update a detector, you need to first stop both real-time detection and histor You can't update a category field. {: .note } -#### Request +#### Example request ```json -PUT _plugins/_anomaly_detection/detectors/<detectorId> +PUT _plugins/_anomaly_detection/detectors/{detectorId} { "name": "test-detector", "description": "Test update detector", @@ -1193,10 +1193,10 @@ Introduced 1.0 Deletes a detector based on the `detector_id`. To delete a detector, you need to first stop both real-time detection and historical analysis. -#### Request +#### Example request ```json -DELETE _plugins/_anomaly_detection/detectors/<detectorId> +DELETE _plugins/_anomaly_detection/detectors/{detectorId} ``` #### Example response @@ -1228,7 +1228,7 @@ Passes a date range to the anomaly detector to return any anomalies within that To preview a single-entity detector: -#### Request +#### Example request ```json POST _plugins/_anomaly_detection/detectors/_preview @@ -1369,7 +1369,7 @@ POST _plugins/_anomaly_detection/detectors/_preview If you specify a category field, each result is associated with an entity: -#### Request +#### Example request ```json POST _plugins/_anomaly_detection/detectors/_preview @@ -1657,10 +1657,10 @@ Starts a real-time or historical anomaly detector job. To start a real-time detector job: -#### Request +#### Example request ```json -POST _plugins/_anomaly_detection/detectors/<detectorId>/_start +POST _plugins/_anomaly_detection/detectors/{detectorId}/_start ``` #### Example response @@ -1679,7 +1679,7 @@ The `_id` represents the real-time job ID, which is the same as the detector ID. To start historical analysis: ```json -POST _plugins/_anomaly_detection/detectors/<detectorId>/_start +POST _plugins/_anomaly_detection/detectors/{detectorId}/_start { "start_time": 1633048868000, "end_time": 1633394468000 @@ -1709,10 +1709,10 @@ Stops a real-time or historical anomaly detector job. To stop a real-time detector job: -#### Request +#### Example request ```json -POST _plugins/_anomaly_detection/detectors/<detectorId>/_stop +POST _plugins/_anomaly_detection/detectors/{detectorId}/_stop ``` #### Example response @@ -1732,7 +1732,7 @@ Introduced 1.1 {: .label .label-purple } ```json -POST _plugins/_anomaly_detection/detectors/<detectorId>/_stop?historical=true +POST _plugins/_anomaly_detection/detectors/{detectorId}/_stop?historical=true ``` #### Example response @@ -1756,7 +1756,7 @@ Returns all anomaly detectors for a search query. To search detectors using the `server_log*` index: -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/detectors/_search @@ -1873,7 +1873,7 @@ Searches detector tasks. To search for the latest detector level historical analysis task for a high cardinality detector -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/detectors/tasks/_search @@ -2035,7 +2035,7 @@ POST _plugins/_anomaly_detection/detectors/tasks/_search To search for the latest entity-level tasks for the historical analysis of a high cardinality detector: -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/detectors/tasks/_search @@ -2080,7 +2080,7 @@ The `parent_task_id` is the same as the task ID that you can get with the profil {: .note } -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/detectors/tasks/_search @@ -2182,24 +2182,24 @@ You have the following search options: - To search both the custom result index and default result index, you can either add the custom result index to the search API: ```json - POST _plugins/_anomaly_detection/detectors/results/_search/<custom_result_index> + POST _plugins/_anomaly_detection/detectors/results/_search/{custom_result_index} ``` Or, add the custom result index and set the `only_query_custom_result_index` parameter to `false`: ```json - POST _plugins/_anomaly_detection/detectors/results/_search/<custom_result_index>?only_query_custom_result_index=false + POST _plugins/_anomaly_detection/detectors/results/_search/{custom_result_index}?only_query_custom_result_index=false ``` - To search only the custom result index, add the custom result index to the search API and set the `only_query_custom_result_index` parameter to `true`: ```json - POST _plugins/_anomaly_detection/detectors/results/_search/<custom_result_index>?only_query_custom_result_index=true + POST _plugins/_anomaly_detection/detectors/results/_search/{custom_result_index}?only_query_custom_result_index=true ``` The following example searches anomaly results for grade greater than 0 for real-time analysis: -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/detectors/results/_search/opensearch-ad-plugin-result-test @@ -2233,9 +2233,9 @@ POST _plugins/_anomaly_detection/detectors/results/_search/opensearch-ad-plugin- } ``` -If you specify the custom result index like in this example, the search results API searches both the default result indices and custom result indices. +If you specify the custom result index like in this example, the search results API searches both the default result indexes and custom result indexes. -If you don't specify the custom result index and you just use the `_plugins/_anomaly_detection/detectors/results/_search` URL, the anomaly detection plugin searches only the default result indices. +If you don't specify the custom result index and you just use the `_plugins/_anomaly_detection/detectors/results/_search` URL, OpenSearch searches only the default result indexes. Real-time detection doesn't persist the task ID in the anomaly result, so the task ID will be null. @@ -2334,7 +2334,7 @@ You can search for the latest historical batch task first and then search the hi To search anomaly results for `grade` greater than 0 for historical analysis with the `task_id`: -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/detectors/results/_search @@ -2447,10 +2447,10 @@ Returns the top anomaly results for a high-cardinality detector, bucketed by cat You can pass a `historical` boolean parameter to specify whether you want to analyze real-time or historical results. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>/results/_topAnomalies?historical=false +GET _plugins/_anomaly_detection/detectors/{detectorId}/results/_topAnomalies?historical=false { "size": 3, "category_field": [ @@ -2500,7 +2500,7 @@ Options | Description | Type | Required `size` | Specify the number of top buckets that you want to see. Default is 10. The maximum number is 10,000. | `integer` | No `category_field` | Specify the set of category fields that you want to aggregate on. Defaults to all category fields for the detector. | `list` | No `order` | Specify `severity` (anomaly grade) or `occurrence` (number of anomalies). Default is `severity`. | `string` | No -`task_id` | Specify a historical task ID to see results only from that specific task. Use only when `historical=true`, otherwise the anomaly detection plugin ignores this parameter. | `string` | No +`task_id` | Specify a historical task ID to see results only from that specific task. Use only when `historical=true`, otherwise OpenSearch ignores this parameter. | `string` | No `start_time_ms` | Specify the time to start analyzing results, in Epoch milliseconds. | `long` | Yes `end_time_ms` | Specify the time to end analyzing results, in Epoch milliseconds. | `long` | Yes @@ -2510,11 +2510,11 @@ Options | Description | Type | Required Introduced 1.0 {: .label .label-purple } -Provides information about how the plugin is performing. +Provides information about how anomaly detection is performing. To get all stats: -#### Request +#### Example request ```json GET _plugins/_anomaly_detection/stats @@ -2624,18 +2624,18 @@ If haven't run any historical analysis, these values show up as 0. To get all stats for a specific node: -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/<nodeId>/stats +GET _plugins/_anomaly_detection/{nodeId}/stats ``` To get specific stats for a node: -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/<nodeId>/stats/<stat> +GET _plugins/_anomaly_detection/{nodeId}/stats/{stat} ``` For example, to get the `ad_execute_request_count` value for node `SWD7ihu9TaaW1zKwFZNVNg`: @@ -2658,10 +2658,10 @@ GET _plugins/_anomaly_detection/SWD7ihu9TaaW1zKwFZNVNg/stats/ad_execute_request_ To get a specific type of stats: -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/stats/<stat> +GET _plugins/_anomaly_detection/stats/{stat} ``` For example: @@ -2700,26 +2700,26 @@ This command helps locate logs by identifying the nodes that run the anomaly det It also helps track the initialization percentage, the required shingles, and the estimated time left. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile/ -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all=true -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile/<type> -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile/<type1>,<type2> +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile/ +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile?_all=true +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile/{type} +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile/{type1},{type2} ``` -#### Sample Responses +#### Example response ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile { "state": "DISABLED", "error": "Stopped detector: AD models memory usage exceeds our limit." } -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all=true&pretty +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile?_all=true&pretty { "state": "RUNNING", @@ -2883,7 +2883,7 @@ GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all=true&pretty "model_count": 32 } -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile/total_size_in_bytes +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile/total_size_in_bytes { "total_size_in_bytes": 13369344 @@ -3020,16 +3020,16 @@ For a single-entity detector: The `total_entities` parameter shows you the total number of entities including the number of category fields for a detector. -Getting the total count of entities is an expensive operation for real-time analysis of a detector with more than one category field. By default, for a real-time detection profile, a detector counts the number of entities up to a value of 10,000. For historical analysis, the anomaly detection plugin only detects the top 1,000 entities by default and caches the top entities in memory, so it doesn't cost much to get the total count of entities for historical analysis. +Getting the total count of entities is an expensive operation for real-time analysis of a detector with more than one category field. By default, for a real-time detection profile, a detector counts the number of entities up to a value of 10,000. For historical analysis, anomaly detection only detects the top 1,000 entities by default and caches the top entities in memory, so it doesn't cost much to get the total count of entities for historical analysis. The `profile` operation also provides information about each entity, such as the entity’s `last_sample_timestamp` and `last_active_timestamp`. `last_sample_timestamp` shows the last document in the input data source index containing the entity, while `last_active_timestamp` shows the timestamp when the entity’s model was last seen in the model cache. If there are no anomaly results for an entity, either the entity doesn't have any sample data or resources such as memory and disk IO are constrained relative to the number of entities. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all=true +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile?_all=true { "entity": [ { @@ -3040,7 +3040,7 @@ GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all=true } ``` -#### Sample Responses +#### Example response ```json { @@ -3062,14 +3062,14 @@ GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all=true To get profile information for only historical analysis, specify `ad_task`. Specifying `_all` is an expensive operation for multi-category high cardinality detectors. -#### Request +#### Example request ```json -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile?_all -GET _plugins/_anomaly_detection/detectors/<detectorId>/_profile/ad_task +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile?_all +GET _plugins/_anomaly_detection/detectors/{detectorId}/_profile/ad_task ``` -#### Sample Responses +#### Example response ```json { @@ -3218,11 +3218,11 @@ Introduced 1.1 Deletes the results of a detector based on a query. -The delete detector results API only deletes anomaly result documents in the default result index. It doesn't support deleting anomaly result documents stored in any custom result indices. +The delete detector results API only deletes anomaly result documents in the default result index. It doesn't support deleting anomaly result documents stored in any custom result indexes. -You need to manually delete anomaly result documents that you don't need from custom result indices. +You need to manually delete anomaly result documents that you don't need from custom result indexes. -#### Request +#### Example request ```json DELETE _plugins/_anomaly_detection/detectors/results @@ -3289,7 +3289,7 @@ Introduced 1.0 Create a monitor to set up alerts for the detector. -#### Request +#### Example request ```json POST _plugins/_alerting/monitors diff --git a/_observing-your-data/ad/dashboards-anomaly-detection.md b/_observing-your-data/ad/dashboards-anomaly-detection.md index 6905b8b0..afcb979f 100644 --- a/_observing-your-data/ad/dashboards-anomaly-detection.md +++ b/_observing-your-data/ad/dashboards-anomaly-detection.md @@ -2,7 +2,7 @@ layout: default title: Anomaly detection visualizations and dashboards parent: Anomaly detection -nav_order: 50 +nav_order: 10 --- # Anomaly detection dashboards and visualizations @@ -11,23 +11,17 @@ Introduced 2.9 OpenSearch provides an automated means of detecting harmful outliers and protecting your data when you enable anomaly detection. When applied to metrics, OpenSearch uses algorithms to continuously analyze systems and applications, determine normal baselines, and surface anomalies. -You can connect data visualizations to OpenSearch datasets and then create, run, and view anomaly alarms and results from visualizations in the **Dashboard** interface. With only a couple of steps, you can bring together traces, metrics, and logs to make your applications and infrastructure fully observable. +You can connect data visualizations to OpenSearch datasets and then create, run, and view real-time anomaly results from visualizations in the **Dashboard** interface. With only a couple of steps, you can bring together traces, metrics, and logs to make your applications and infrastructure fully observable. ## Getting started -Before getting started, you must have: - -- Installed OpenSearch and OpenSearch Dashboards version 2.9 or later. See [Installing OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/). -- Installed the Anomaly Detection plugin version 2.9 or later. See [Installing OpenSearch plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins). -- Installed the Anomaly Detection Dashboards plugin version 2.9 or later. See [Managing OpenSearch Dashboards plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/plugins/) to get started. - ## General requirements for anomaly detection visualizations -Anomaly detection visualizations are displayed as time-series charts that give you a snapshot of when anomalies have occurred from different anomaly detectors you have configured for the visualization. You can display up to 10 metrics on your chart, and each series can be shown as a line on the chart. +Anomaly detection visualizations are displayed as time-series charts that give you a snapshot of when anomalies have occurred. You can display up to 10 metrics on your chart, and each series can be shown as a line on the chart. Note that only real-time anomalies will be visible on the chart. For more information about real-time and historical anomaly detection, see [Anomaly detection, Step 3: Set up detector jobs]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/#step-3-set-up-detector-jobs). Keep in mind the following requirements when setting up or creating anomaly detection visualizations. The visualization: -- Must be a [Vizlib line chart](https://community.vizlib.com/support/solutions/articles/35000107262-vizlib-line-chart-introduction) +- Must be a [line chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/line-charts/) in which every series is displayed as a line - Must contain at least a Y-axis metric aggregation - Must not have non-Y-axis metric aggregation types - Must use the date histogram aggregation type for the X-axis bucket @@ -53,7 +47,7 @@ To start, first create an anomaly detector: 8. To preview the visualization within the flyout, toggle the **Show visualization** button. 9. Select **Create detector**. Once you have created a new detector, the detector is added to the visualization, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/add-detector.png" alt="Interface of adding a detector" width="800" height="800"> +![Interface of adding a detector]({{site.url}}{{site.baseurl}}/images/dashboards/add-detector.png){: width="800" height="800" } ## Adding anomaly detectors to visualizations @@ -62,10 +56,10 @@ Use a single interface to add, view, and edit anomaly detectors that you want to 1. Select the ellipsis icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/}) from the visualization panel, then select **Anomaly Detection**. 2. Select **Associate a detector**. 3. From the **Select detector to associate** dropdown menu, select the detector. Only eligible detectors are listed in the dropdown menu. -4. View basic information about the detectors. To view comprehensive details, select **View detector page** to open the Anomaly Detection plugin page. +4. View basic information about the detectors. To view comprehensive details, select **View detector page** to open the detector in Anomaly Detection. 5. Select **Associate detector**. An existing detector is now associated to the visualization, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/anomaly-detect-dashboard.png" alt="Interface and confirmation message of associating a detector" width="800" height="800"> +![Interface and confirmation message of associating a detector]({{site.url}}{{site.baseurl}}/images/dashboards/anomaly-detect-dashboard.png){: width="800" height="800" } ## Refreshing the visualization diff --git a/_observing-your-data/ad/detector-access-control.md b/_observing-your-data/ad/detector-access-control.md new file mode 100644 index 00000000..d5be65ce --- /dev/null +++ b/_observing-your-data/ad/detector-access-control.md @@ -0,0 +1,143 @@ +--- +layout: default +title: Anomaly detector access control +nav_order: 50 +parent: Anomaly detection +has_children: false +redirect_from: + - /monitoring-plugins/ad/detector-access-control/ +--- + +# Anomaly detector access control + +Anomaly Detection integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for anomaly detector resources. This replaces the legacy `plugins.anomaly_detection.filter_by_backend_roles` setting with a more flexible sharing system that allows resource owners to grant specific access levels to users, roles, or backend roles. + +For the predefined anomaly detection roles and permissions, see [Anomaly detection security]({{site.url}}{{site.baseurl}}/observing-your-data/ad/security/). + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +The following table describes the anomaly detector resource configuration. + +| Field | Value | +| :--- | :--- | +| Resource type | `anomaly-detector` | +| System index | `.opendistro-anomaly-detectors` | +| Onboarded version | OpenSearch 3.3 | + +When resource-level authorization is enabled for anomaly detectors, each detector's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +## Enable anomaly detector resource sharing + +To enable resource sharing for anomaly detectors, you must add the anomaly-detector resource type to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for anomaly detectors: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "anomaly-detector" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["anomaly-detector"] + } +} +``` +{% include copy-curl.html %} + +When adding the anomaly-detector resource type to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Anomaly detector access levels + +Anomaly Detection provides three predefined access levels for anomaly detector documents. These access levels determine the specific permissions granted to users who have been granted access to a detector resource. + +### ad_read_only + +The `ad_read_only` read-only access level grants users the ability to view and search shared anomaly detectors but not modify them. This access level includes the following permissions: + +```yaml +- 'cluster:admin/opendistro/ad/detector/info' +- 'cluster:admin/opendistro/ad/detector/validate' +- 'cluster:admin/opendistro/ad/detector/preview' +- 'cluster:admin/opendistro/ad/detectors/get' +- 'cluster:admin/opendistro/ad/result/topAnomalies' +``` +{% include copy.html %} + +### ad_read_write + +The `ad_read_write` read-write access level grants users full access to anomaly detector operations except for sharing capabilities. This access level includes all read permissions plus write operations: + +```yaml +- "cluster:admin/opendistro/ad/*" +- 'cluster:monitor/*' +- "cluster:admin/ingest/pipeline/delete" +- "cluster:admin/ingest/pipeline/put" +``` +{% include copy.html %} + +### ad_full_access + +The `ad_full_access` full access level grants users complete control over an anomaly detector, including owner-like permissions such as sharing the resource with other users. This access level includes all anomaly detector operations plus resource sharing permissions: + +```yaml +- "cluster:admin/ingest/pipeline/delete" +- "cluster:admin/ingest/pipeline/put" +- "cluster:admin/opendistro/ad/*" +- 'cluster:monitor/*' +- "cluster:admin/security/resource/share" +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Anomaly Detection GitHub repository](https://github.com/opensearch-project/anomaly-detection/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking anomaly detectors as a protected resource type, cluster administrators must run the migration API to transfer existing detector sharing information from the legacy framework to the new resource sharing system. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Use the following API call to migrate legacy anomaly detector sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-anomaly-detectors", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "anomaly-detector": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own anomaly detectors without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available anomaly detector access levels: `ad_read_only`, `ad_read_write`, or `ad_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance \ No newline at end of file diff --git a/_observing-your-data/ad/index.md b/_observing-your-data/ad/index.md index 139b63d1..11ef3ab4 100644 --- a/_observing-your-data/ad/index.md +++ b/_observing-your-data/ad/index.md @@ -1,103 +1,193 @@ --- layout: default title: Anomaly detection -nav_order: 80 +nav_order: 120 has_children: true redirect_from: - /monitoring-plugins/ad/ - /monitoring-plugins/ad/index/ + - /observing-your-data/ad/ --- # Anomaly detection -An anomaly in OpenSearch is any unusual behavior change in your time-series data. Anomalies can provide valuable insights into your data. For example, for IT infrastructure data, an anomaly in the memory usage metric might help you uncover early signs of a system failure. +An _anomaly_ in OpenSearch is any unusual behavior change in your time-series data. Anomalies can provide valuable insights into your data. For example, for IT infrastructure data, an anomaly in the memory usage metric can help identify early signs of a system failure. -It can be challenging to discover anomalies using conventional methods such as creating visualizations and dashboards. You could configure an alert based on a static threshold, but this requires prior domain knowledge and isn't adaptive to data that exhibits organic growth or seasonal behavior. +Conventional techniques like visualizations and dashboards can make it difficult to uncover anomalies. Configuring alerts based on static thresholds is possible, but this approach requires prior domain knowledge and may not adapt to data with organic growth or seasonal trends. -Anomaly detection automatically detects anomalies in your OpenSearch data in near real-time using the Random Cut Forest (RCF) algorithm. RCF is an unsupervised machine learning algorithm that models a sketch of your incoming data stream to compute an `anomaly grade` and `confidence score` value for each incoming data point. These values are used to differentiate an anomaly from normal variations. For more information about how RCF works, see [Random Cut Forests](https://www.semanticscholar.org/paper/Robust-Random-Cut-Forest-Based-Anomaly-Detection-on-Guha-Mishra/ecb365ef9b67cd5540cc4c53035a6a7bd88678f9). +Anomaly detection automatically detects anomalies in your OpenSearch data in near real time using the Random Cut Forest (RCF) algorithm. RCF is an unsupervised machine learning algorithm that models a sketch of your incoming data stream to compute an _anomaly grade_ and _confidence score_ value for each incoming data point. These values are used to differentiate an anomaly from normal variations. For more information about how RCF works, see [Robust Random Cut Forest Based Anomaly Detection on Streams](https://www.semanticscholar.org/paper/Robust-Random-Cut-Forest-Based-Anomaly-Detection-on-Guha-Mishra/ecb365ef9b67cd5540cc4c53035a6a7bd88678f9). -You can pair the Anomaly Detection plugin with the [Alerting plugin]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/) to notify you as soon as an anomaly is detected. +You can pair anomaly detection with [Alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/) to notify you as soon as an anomaly is detected. +{: .note} -To get started, choose **Anomaly Detection** in OpenSearch Dashboards. -To first test with sample streaming data, you can try out one of the preconfigured detectors with one of the sample datasets. +## Getting started with anomaly detection in OpenSearch Dashboards + +To get started, go to **OpenSearch Dashboards** > **OpenSearch Plugins** > **Anomaly Detection**. ## Step 1: Define a detector -A detector is an individual anomaly detection task. You can define multiple detectors, and all the detectors can run simultaneously, with each analyzing data from different sources. +A _detector_ is an individual anomaly detection task. You can define multiple detectors, and all detectors can run simultaneously, with each analyzing data from different sources. You can define a detector by following these steps: -1. Choose **Create detector**. -1. Add in the detector details. - - Enter a name and brief description. Make sure the name is unique and descriptive enough to help you to identify the purpose of the detector. -1. Specify the data source. - - For **Data source**, choose the index you want to use as the data source. You can optionally use index patterns to choose multiple indexes. - - (Optional) For **Data filter**, filter the index you chose as the data source. From the **Data filter** menu, choose **Add data filter**, and then design your filter query by selecting **Field**, **Operator**, and **Value**, or choose **Use query DSL** and add your own JSON filter query. -1. Specify a timestamp. - - Select the **Timestamp field** in your index. -1. Define operation settings. - - For **Operation settings**, define the **Detector interval**, which is the time interval at which the detector collects data. - - The detector aggregates the data in this interval, then feeds the aggregated result into the anomaly detection model. - The shorter you set this interval, the fewer data points the detector aggregates. - The anomaly detection model uses a shingling process, a technique that uses consecutive data points to create a sample for the model. This process needs a certain number of aggregated data points from contiguous intervals. +1. On the **Anomaly detection** page, select the **Create detector** button. +2. On the **Define detector** page, add the detector details. Enter a name and a brief description. The name must be unique and descriptive enough to help you identify the detector's purpose. - - We recommend setting the detector interval based on your actual data. If it's too long it might delay the results, and if it's too short it might miss some data. It also won't have a sufficient number of consecutive data points for the shingle process. +3. In the **Select data** pane, specify the data source by selecting one or more sources from the **Index** dropdown menu. You can select indexes, index patterns, or aliases. - - (Optional) To add extra processing time for data collection, specify a **Window delay** value. - - This value tells the detector that the data is not ingested into OpenSearch in real time but with a certain delay. Set the window delay to shift the detector interval to account for this delay. - - For example, say the detector interval is 10 minutes and data is ingested into your cluster with a general delay of 1 minute. Assume the detector runs at 2:00. The detector attempts to get the last 10 minutes of data from 1:50 to 2:00, but because of the 1-minute delay, it only gets 9 minutes of data and misses the data from 1:59 to 2:00. Setting the window delay to 1 minute shifts the interval window to 1:49--1:59, so the detector accounts for all 10 minutes of the detector interval time. -1. Specify custom result index. - - If you want to store the anomaly detection results in your own index, choose **Enable custom result index** and specify the custom index to store the result. The anomaly detection plugin adds an `opensearch-ad-plugin-result-` prefix to the index name that you input. For example, if you input `abc` as the result index name, the final index name is `opensearch-ad-plugin-result-abc`. + - Detectors can use remote indexes, which you can access using the `cluster-name:index-name` pattern. For more information, see [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/). You can also select clusters and indexes directly. If the Security plugin is enabled, see [Selecting remote indexes with fine-grained access control]({{site.url}}{{site.baseurl}}/observing-your-data/ad/security/#selecting-remote-indexes-with-fine-grained-access-control) in the [Anomaly detection security]({{site.url}}{{site.baseurl}}/observing-your-data/ad/security/) documentation. - You can use the dash “-” sign to separate the namespace to manage custom result index permissions. For example, if you use `opensearch-ad-plugin-result-financial-us-group1` as the result index, you can create a permission role based on the pattern `opensearch-ad-plugin-result-financial-us-*` to represent the "financial" department at a granular level for the "us" area. - {: .note } + - To create a cross-cluster detector in OpenSearch Dashboards, you must have the following [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/): `indices:data/read/field_caps`, `indices:admin/resolve/index`, and `cluster:monitor/remote/info`. - - If the custom index you specify doesn’t already exist, the Anomaly Detection plugin creates this index when you create the detector and start your real-time or historical analysis. - - If the custom index already exists, the plugin checks if the index mapping of the custom index matches the anomaly result file. You need to make sure the custom index has valid mapping as shown here: [anomaly-results.json](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/mappings/anomaly-results.json). - - To use the custom result index option, you need the following permissions: - - `indices:admin/create` - If the custom index already exists, you don't need this. - - `indices:data/write/index` - You need the `write` permission for the Anomaly Detection plugin to write results into the custom index for a single-entity detector. - - `indices:data/read/search` - You need the `search` permission because the Anomaly Detection plugin needs to search custom result indexes to show results on the anomaly detection UI. - - `indices:data/write/delete` - Because the detector might generate a large number of anomaly results, you need the `delete` permission to delete old data and save disk space. - - `indices:data/write/bulk*` - You need the `bulk*` permission because the Anomaly Detection plugin uses the bulk API to write results into the custom index. - - Managing the custom result index: - - The anomaly detection dashboard queries all detectors’ results from all custom result indexes. Having too many custom result indexes might impact the performance of the Anomaly Detection plugin. - - You can use [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) to rollover old result indexes. You can also manually delete or archive any old result indexes. We recommend reusing a custom result index for multiple detectors. -1. Choose **Next**. +4. (Optional) Filter the data source by selecting **Add data filter** and then specifying the conditions for **Field**, **Operator**, and **Value**. Alternatively, select **Use query DSL** and enter your filter as a JSON-formatted [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/). Only Boolean queries are supported for query domain-specific language (DSL). -After you define the detector, the next step is to configure the model. + + + +### Example: Filtering data using query DSL + +The following example query retrieves documents in which the `urlPath.keyword` field matches any of the specified values: + +```json + { + "bool": { + "should": [ + { + "term": { + "urlPath.keyword": "/domain/{id}/short" + } + }, + { + "term": { + "urlPath.keyword": "/sub_dir/{id}/short" + } + }, + { + "term": { + "urlPath.keyword": "/abcd/123/{id}/xyz" + } + } + ] + } + } +``` +{% include copy-curl.html %} + +5. In the **Timestamp** pane, select a field from the **Timestamp field** dropdown list. + +6. (Optional) To store anomaly detection results in a custom index, select **Enable custom results index** and provide a name for your index (for example, `abc`). OpenSearch creates an alias prefixed with `opensearch-ad-plugin-result-` followed by your chosen name (for example, `opensearch-ad-plugin-result-abc`). This alias points to an actual index with a name containing the date and a sequence number, such as `opensearch-ad-plugin-result-abc-history-2024.06.12-000002`, where your results are stored. + +You can use `-` to separate the namespace to manage custom results index permissions. For example, if you use `opensearch-ad-plugin-result-financial-us-group1` as the results index, you can create a permission role based on the pattern `opensearch-ad-plugin-result-financial-us-*` to represent the `financial` department at a granular level for the `us` group. +{: .note } + +#### Permissions + +When the Security plugin (fine-grained access control) is enabled, the default results index becomes a system index and is no longer accessible through the standard Index or Search APIs. To access its content, you must use the Anomaly Detection RESTful API or the dashboard. As a result, you cannot build customized dashboards using the default results index if the Security plugin is enabled. However, you can create a custom results index in order to build customized dashboards. + +If the custom index you specify does not exist, OpenSearch creates it when you create the detector and start your real-time or historical analysis. + +If the custom index already exists, OpenSearch verifies that the index mapping matches the required structure for anomaly results. In this case, ensure that the custom index has a valid mapping as defined in the [`anomaly-results.json`](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/mappings/anomaly-results.json) file. +To use the custom results index option, you must have the following permissions: + +- `indices:admin/create` -- The `create` permission is required in order to create and roll over the custom index. +- `indices:admin/aliases` -- The `aliases` permission is required in order to create and manage an alias for the custom index. +- `indices:data/write/index` -- The `write` permission is required in order to write results into the custom index for a single-entity detector. +- `indices:data/read/search` -- The `search` permission is required in order to search custom results indexes to show results on the Anomaly Detection interface. +- `indices:data/write/delete` -- The detector may generate many anomaly results. The `delete` permission is required in order to delete old data and save disk space. +- `indices:data/write/bulk*` -- The `bulk*` permission is required because anomaly detection uses the Bulk API to write results into the custom index. + +#### Flattening nested fields + +Custom results index mappings with nested fields pose aggregation and visualization challenges. The **Enable flattened custom result index** option flattens the nested fields in the custom results index. When selecting this option, OpenSearch creates a separate index prefixed with the custom results index name and detector name. For example, if the detector `Test` uses the custom results index `abc`, a separate index with the alias `opensearch-ad-plugin-result-abc-flattened-test` will store the anomaly detection results with nested fields flattened. + +In addition to creating a separate index, OpenSearch also sets up an ingest pipeline with a script processor. This pipeline is bound to the separate index and uses a Painless script to flatten all nested fields in the custom results index. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +Deactivating this option on a running detector removes its flattening ingest pipeline; it also ceases to be the default for the results index. +When using the flattened custom result option, consider the following: + +- OpenSearch constructs the index name based on the custom results index and detector name, and because the detector name is editable, conflicts can occur. If a conflict occurs, OpenSearch reuses the index name. +- When managing the custom results index, consider the following: + - The Anomaly Detection dashboard queries all detector results from all custom results indexes. Having too many custom results indexes can impact anomaly detection performance. + - You can use [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) to roll over old results indexes. You can also manually delete or archive any old results indexes. Reusing a custom results index for multiple detectors is recommended. + +OpenSearch rolls over an alias to a new index when the custom results index meets any of the conditions in the following table. + +Parameter | Description | Type | Unit | Example | Required +:--- | :--- |:--- |:--- |:--- |:--- +`result_index_min_size` | The minimum total primary shard size (excluding replicas) required for index rollover. When set to 100 GiB with an index that has 5 primary and 5 replica shards of 20 GiB each, the rollover runs. | `integer` | `MB` | `51200` | No +`result_index_min_age` | The minimum index age required for the rollover, calculated from its creation time to the current time. | `integer` |`day` | `7` | No +`result_index_ttl` | The minimum age required in order to delete rolled-over indexes. | `integer` | `day` | `60` | No + +After defining your detector settings, select **Next** to configure the model. ## Step 2: Configure the model -#### Add features to your detector +Add features to your detector. A _feature_ is an aggregation of a field or a Painless script. A detector can discover anomalies across one or more features. -A feature is the field in your index that you want to check for anomalies. A detector can discover anomalies across one or more features. You must choose an aggregation method for each feature: `average()`, `count()`, `sum()`, `min()`, or `max()`. The aggregation method determines what constitutes an anomaly. +You must choose an aggregation method for each feature: `average()`, `count()`, `sum()`, `min()`, or `max()`. The aggregation method determines what constitutes an anomaly. For example, if you choose `min()`, the detector focuses on finding anomalies based on the minimum values of your feature. If you choose `average()`, the detector finds anomalies based on the average values of your feature. -For example, if you choose `min()`, the detector focuses on finding anomalies based on the minimum values of your feature. If you choose `average()`, the detector finds anomalies based on the average values of your feature. +You can also use [custom JSON aggregation queries](#configuring-a-model-based-on-a-json-aggregation-query) as an aggregation method. For more information about creating JSON aggregation queries, see [Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/index/). -A multi-feature model correlates anomalies across all its features. The [curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality) makes it less likely for multi-feature models to identify smaller anomalies as compared to a single-feature model. Adding more features might negatively impact the [precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall) of a model. A higher proportion of noise in your data might further amplify this negative impact. Selecting the optimal feature set is usually an iterative process. By default, the maximum number of features for a detector is 5. You can adjust this limit with the `plugins.anomaly_detection.max_anomaly_features` setting. -{: .note } + +For each configured feature, you can also select the anomaly criteria. By default, the model detects an anomaly when the actual value is either abnormally higher or lower than the expected value. However, you can customize your feature settings so that anomalies are only registered when the actual value is higher than the expected value (indicating a spike in the data) or lower than the expected value (indicating a dip in the data). For example, when creating a detector for the `cpu_utilization` field, you may choose to register anomalies only when the value spikes in order to reduce alert fatigue. + + +### Suppressing anomalies with threshold-based rules + +In the **Feature selection** pane, you can suppress anomalies by setting rules that define acceptable differences between the expected and actual values, either as an absolute value or a relative percentage. This helps reduce false anomalies caused by minor fluctuations, allowing you to focus on significant deviations. + +To suppress anomalies for deviations of less than 30% from the expected value, you can set the following rules in the feature selection pane: + +- Ignore anomalies when the actual value is no more than 30% above the expected value. +- Ignore anomalies when the actual value is no more than 30% below the expected value. + +The following image shows the pane for a feature named `LogVolume`, where you can set the relative deviation percentage settings: + +![Interface of adding a feature with suppression rules]({{site.url}}{{site.baseurl}}/images/anomaly-detection/add-feature-with-relative-rules.png){: width="800" height="800" } + +If you expect that the log volume should differ by at least 10,000 from the expected value before being considered an anomaly, you can set the following absolute thresholds: + +- Ignore anomalies when the actual value is no more than 10,000 above the expected value. +- Ignore anomalies when the actual value is no more than 10,000 below the expected value. + +The following image shows the pane for a feature named `LogVolume`, where you can set the absolute threshold settings: + +![Interface of adding suppression rules with absolute rules]({{site.url}}{{site.baseurl}}/images/anomaly-detection/add-suppression-rules-absolute.png){: width="800" height="800" } + +If no custom suppression rules are set, then the system defaults to a filter that ignores anomalies with deviations of less than 20% from the expected value for each enabled feature. + +A multi-feature model correlates anomalies across all of its features. The [curse of dimensionality](https://en.wikipedia.org/wiki/Curse_of_dimensionality) makes it less likely that a multi-feature model will identify smaller anomalies as compared to a single-feature model. Adding more features can negatively impact the [precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall) of a model. A higher proportion of noise in your data can further amplify this negative impact. To select the optimal feature set limit for anomalies, we recommend an iterative process of testing different limits. By default, the maximum number of features for a detector is `5`. To adjust this limit, use the `plugins.anomaly_detection.max_anomaly_features` setting. +{: .note} + +### Configuring a model based on an aggregation method To configure an anomaly detection model based on an aggregation method, follow these steps: -1. On the **Configure Model** page, enter the **Feature name** and check **Enable feature**. -1. For **Find anomalies based on**, select **Field Value**. -1. For **aggregation method**, select either **average()**, **count()**, **sum()**, **min()**, or **max()**. -1. For **Field**, select from the available options. +1. On the **Detectors** page, select the desired detector from the list. +2. On the detector's details page, select the **Actions** button to activate the dropdown menu and then select **Edit model configuration**. +3. On the **Edit model configuration** page, select the **Add another feature** button. +4. Enter a name in the **Feature name** field and select the **Enable feature** checkbox. +5. Select **Field value** from the dropdown menu under **Find anomalies based on**. +6. Select the desired aggregation from the dropdown menu under **Aggregation method**. +7. Select the desired field from the options listed in the dropdown menu under **Field**. +8. Select the **Save changes** button. + +### Configuring a model based on a JSON aggregation query To configure an anomaly detection model based on a JSON aggregation query, follow these steps: -1. On the **Configure Model** page, enter the **Feature name** and check **Enable feature**. -1. For **Find anomalies based on**, select **Custom expression**. You will see the JSON editor window open up. -1. Enter your JSON aggregation query in the editor. -For acceptable JSON query syntax, see [OpenSearch Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/index/) -{: .note } +1. On the **Edit model configuration** page, select the **Add another feature** button. +2. Enter a name in the **Feature name** field and select the **Enable feature** checkbox. +3. Select **Custom expression** from the dropdown menu under **Find anomalies based on**. The JSON editor window will open. +4. Enter your JSON aggregation query in the editor. +5. Select the **Save changes** button. -#### (Optional) Set category fields for high cardinality +For acceptable JSON query syntax, see [OpenSearch Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/index/). +{: .note} -You can categorize anomalies based on a keyword or IP field type. +### Setting categorical fields for high cardinality -The category field categorizes or slices the source time series with a dimension like IP addresses, product IDs, country codes, and so on. This helps to see a granular view of anomalies within each entity of the category field to isolate and debug issues. +You can categorize anomalies based on a keyword or IP field type. You can enable the **Categorical fields** option to categorize, or "slice," the source time series using a dimension, such as an IP address, a product ID, or a country code. This gives you a granular view of anomalies within each entity of the category field to help isolate and debug issues. -To set a category field, choose **Enable a category field** and select a field. You can’t change the category fields after you create the detector. +To set a category field, select **Enable categorical fields** and select a field. You cannot change the category fields after you create the detector. Only a certain number of unique entities are supported in the category field. Use the following equation to calculate the recommended total number of entities supported in a cluster: @@ -105,7 +195,7 @@ Only a certain number of unique entities are supported in the category field. Us (data nodes * heap size * anomaly detection maximum memory percentage) / (entity model size of a detector) ``` -To get the entity model size of a detector, use the [profile detector API]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/api/#profile-detector). You can adjust the maximum memory percentage with the `plugins.anomaly_detection.model_max_size_percent` setting. +To get the detector's entity model size, use the [Profile Detector API]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/api/#profile-detector). You can adjust the maximum memory percentage using the `plugins.anomaly_detection.model_max_size_percent` setting. Consider a cluster with 3 data nodes, each with 8 GB of JVM heap size and the default 10% memory allocation. With an entity model size of 1 MB, the following formula calculates the estimated number of unique entities: @@ -113,105 +203,198 @@ Consider a cluster with 3 data nodes, each with 8 GB of JVM heap size and the de (8096 MB * 0.1 / 1 MB ) * 3 = 2429 ``` -If the actual total number of unique entities is higher than the number that you calculate (in this case, 2,429), the anomaly detector will attempt to model the extra entities. The detector prioritizes entities that occur more often and are more recent. +If the actual total number of unique entities is higher than the number that you calculate (in this case, 2,429), then the anomaly detector attempts to model the extra entities. The detector prioritizes both entities that occur more often and are more recent. -This formula serves as a starting point. Make sure to test it with a representative workload. You can find more information in the [Improving Anomaly Detection: One million entities in one minute](https://opensearch.org/blog/one-million-enitities-in-one-minute/) blog post. +This formula serves as a starting point. Make sure to test it with a representative workload. See the OpenSearch blog post [Improving Anomaly Detection: One million entities in one minute](https://opensearch.org/blog/one-million-enitities-in-one-minute/) for more information. {: .note } -#### (Advanced settings) Set a shingle size +#### Operational settings -Set the number of aggregation intervals from your data stream to consider in a detection window. It’s best to choose this value based on your actual data to see which one leads to the best results for your use case. +The **Suggest parameters** button in OpenSearch Dashboards initiates a review of recent history in order to recommend sensible defaults. You can override these defaults by adjusting the following parameters. -The anomaly detector expects the shingle size to be in the range of 1 and 60. The default shingle size is 8. We recommend that you don't choose 1 unless you have two or more features. Smaller values might increase [recall](https://en.wikipedia.org/wiki/Precision_and_recall) but also false positives. Larger values might be useful for ignoring noise in a signal. +##### Detector interval -#### Preview sample anomalies +Specifies the aggregation bucket size (for example, 10 minutes). You should set the detector interval based on your actual data characteristics: -Preview sample anomalies and adjust the feature settings if needed. -For sample previews, the Anomaly Detection plugin selects a small number of data samples---for example, one data point every 30 minutes---and uses interpolation to estimate the remaining data points to approximate the actual feature data. It loads this sample dataset into the detector. The detector uses this sample dataset to generate a sample preview of anomaly results. +- **Longer intervals**: Smooth out noise and reduce compute costs but delay detection. +- **Shorter intervals**: Detect changes sooner but increase resource usage and can introduce noise. -Examine the sample preview and use it to fine-tune your feature configurations (for example, enable or disable features) to get more accurate results. +The interval must be large enough that you rarely miss data. The model uses shingling (consecutive, contiguous buckets), and missing buckets degrade data quality and shingle formation. -1. Choose **Preview sample anomalies**. - - If you don't see any sample anomaly result, check the detector interval and make sure you have more than 400 data points for some entities during the preview date range. -1. Choose **Next**. +##### Frequency (optional) + +Specifies how often the job queries, scores, and writes results. Shorter values provide more real-time updates at a higher cost, while longer values reduce load but slow down updates. Frequency must be a multiple of the interval and defaults to the interval value. + +If you're unsure, leave this field blank---the job will use the interval value by default. + +**Common scenarios for using a larger frequency than the interval include:** + +1. **Batching short buckets for efficiency**: In high-frequency or high-volume log streams where ultra-fast alerting is unnecessary. For workloads with heavy joins or high-cardinality features, or for compliance-driven nightly rollups that require an **immutable daily anomaly ledger** for reviews or audits, running the detector every 1--2 minutes can be wasteful. Instead, schedule the detector to run less frequently so it batches many short intervals in one pass (for example, **6 hours**, which processes ~**360** 1-minute buckets at once). Choose a frequency that fits your alerting latency and cost goals (for example, 30 minutes, 1 hour, 3 hours, 6 hours, or 12 hours). + + - **Benefits**: Reduced scheduling overhead and better resource utilization, especially when running many jobs or working with busy clusters. + - **Trade-offs**: Increased detection delay---an anomaly in a 1-minute bucket may only be reported when the batch run is executed. + - **Best for**: Cost and load control, compliance and audit. + +2. **Aligning with infrequent or batch log ingestion**: When logs arrive irregularly or in batches (for example, once per day from S3, or IoT devices that upload in bursts). Running the detector every minute would mostly yield empty results and wasted cycles. Configure the frequency closer to the data arrival rate (for example, 1 day) so each search is more likely to find new data. When timestamps are irregular and low in volume (as is common with sporadic logs), interim results tend to be harmful to accuracy, as the RCF model is stateful and assumes strict ascending order of timestamps. By using a less frequent schedule, you effectively let the job wait for complete data rather than repeatedly checking an empty index. + + - **Benefits**: Reduced pointless queries and CPU overhead; improved efficiency and more accurate results—anomalies will be evaluated once the batch of logs arrives, with minimal risk of false interim anomalies. + - **Trade-offs**: Less frequent anomaly evaluation. + - **Best for**: Batch jobs and sporadic log ingestion patterns. + +##### Window delay (optional) + +To add extra processing time for data collection, specify a **Window delay** value. This signals to the detector that data is not ingested into OpenSearch in real time but with a certain delay. + +**How it works**: + +Set the window delay to shift the detector interval to account for ingestion delay. For example: +- Detector interval: 10 minutes +- Data ingestion delay: 1 minute +- Detector runs at: 2:00 PM + +Without a window delay, the detector attempts to get data from 1:50–2:00 PM but only gets 9 minutes of data, missing data from 1:59–2:00 PM. Setting the window delay to 1 minute shifts the interval window to 1:49–1:59 PM, ensuring the detector captures all 10 minutes of data. + +**Best practices**: +- Set **Window delay** to the upper limit of expected ingestion delay to avoid missing data. +- Balance data accuracy with timely detection—too long of a delay hinders real-time anomaly detection. + +##### History (optional) + +Sets the number of historical data points used to train the initial (cold-start) model. The maximum is 10,000 data points. More history improves initial model accuracy up to that limit. + +##### Choosing between frequency and window delay + +Both **frequency** and **window delay** address ingestion delay but work better for different data patterns: + +- **Window delay**: Best for streaming data (continuous trickle) +- **Frequency**: Best for batch data (periodic drops) + +**Example scenarios**: + +- **Example A -- Data arrives every minute, but always 1 day late → use window delay**: + - **Pattern**: Data for `Day-1 00:01, 00:02, ..., 23:59` arrives steadily, but only on `Day-2` at the same minute marks. + - **Configuration**: `interval = 1 min`, `window_delay = 1 day`, `frequency = 1 min`. + - **Effect**: + - The `Day-2 00:01` run processes `Day-1 00:01` data. + - The `Day-2 00:02` run processes `Day-1 00:02` data. + - ... + - The `Day-2 23:59` run processes `Day-1 23:59` data. + - **Why this fits**: Each minute's data arrives with a predictable 24-hour delay. Setting a 1-day window delay ensures each record is processed at its intended timestamp while keeping the workload incremental. + +- **Example B -- All of `Day-1`'s data arrives at `Day-2 00:00` → use a daily frequency**: + - **Pattern**: No data appears during `Day-1`; instead, a single batch containing all 1,440 minutes of data arrives at `Day-2 00:00`. + - **Configuration**: `interval = 1 min`, `frequency = 1 day` (process the full day at once). + *(Tip: Add a small `window_delay`—for example, 1–5 minutes—to account for indexing or refresh lag.)* + - **Effect**: + - **Best case**: If the detector starts around `00:00`, the `Day-2 00:00` run processes all of `Day-1`'s data right after it arrives. + - **Worst case**: If the detector starts around `23:59`, the daily run won't occur until `Day-2 23:59`, roughly `24 hours` after the drop. + - **General rule**: For a midnight data drop, the extra wait equals your detector's daily start time. + - **Why this works**: Because the entire day's data becomes available at once, a single daily run is much more efficient than processing data minute by minute. + +The following diagram illustrates the timing differences between using window delay and using frequency to handle a 1-day ingestion delay. The timeline shows Day-1 ingestion (top), Day-2 processing with `window_delay = 1 day` (middle, continuous band), and a single daily run when `frequency = 1 day` (bottom, vertical bar). Depending on when you start the detector, a daily frequency can fire just after Day-1 ends (best case, minimal extra delay) or much later (worst case, up to ~+1 day). The job runs every day at approximately the time you first started it. + +![Timeline showing Day-1 ingestion (top), Day-2 processing with window delay (middle), and a single daily run when frequency = 1 day (bottom)]({{site.url}}{{site.baseurl}}/images/anomaly-detection/window-delay-vs-frequency.png){: width="1200" height="350" } + + +### Setting a shingle size + +In the **Advanced settings** pane, you can set the number of data stream aggregation intervals to include in the detection window. Choose this value based on your actual data to find the optimal setting for your use case. To set the shingle size, select **Show** in the **Advanced settings** pane. Enter the desired size in the **intervals** field. + +The anomaly detector requires the shingle size to be between 1 and 128. The default is `8`. Use `1` only if you have at least two features. Values of less than `8` may increase [recall](https://en.wikipedia.org/wiki/Precision_and_recall) but also may increase false positives. Values greater than `8` may be useful for ignoring noise in a signal. + +### Setting an imputation option + +In the **Advanced settings** pane, you can set the imputation option. This allows you to manage missing data in your streams. The options include the following: + +- **Ignore Missing Data (Default):** The system continues without considering missing data points, keeping the existing data flow. +- **Fill with Custom Values:** Specify a custom value for each feature to replace missing data points, allowing for targeted imputation tailored to your data. +- **Fill with Zeros:** Replace missing values with zeros. This is ideal when the absence of data indicates a significant event, such as a drop to zero in event counts. +- **Use Previous Values:** Fill gaps with the last observed value to maintain continuity in your time-series data. This method treats missing data as non-anomalous, carrying forward the previous trend. + +Using these options can improve recall in anomaly detection. For instance, if you are monitoring for drops in event counts, including both partial and complete drops, then filling missing values with zeros helps detect significant data absences, improving detection recall. + +Be cautious when imputing extensively missing data, as excessive gaps can compromise model accuracy. Quality input is critical---poor data quality leads to poor model performance. The confidence score also decreases when imputations occur. You can check whether a feature value has been imputed using the `feature_imputed` field in the anomaly results index. See [Anomaly result mapping]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/result-mapping/) for more information. +{: note} + + +### Previewing sample anomalies + +You can preview anomalies based on sample feature input and adjust the feature settings as needed. OpenSearch selects a small number of data samples---for example, 1 data point every 30 minutes---and uses interpolation to estimate the remaining data points to approximate the actual feature data. The sample dataset is loaded into the detector, which then uses the sample dataset to generate a preview of the anomalies. + +1. Select **Preview sample anomalies**. + - If sample anomaly results are not displayed, check the detector interval to verify that 400 or more data points are set for the entities during the preview date range. +2. Select the **Next** button. ## Step 3: Set up detector jobs -To start a real-time detector to find anomalies in your data in near real-time, check **Start real-time detector automatically (recommended)**. +To start a detector to find anomalies in your data in near real time, select **Start real-time detector automatically (recommended)**. -Alternatively, if you want to perform historical analysis and find patterns in long historical data windows (weeks or months), check **Run historical analysis detection** and select a date range (at least 128 detection intervals). +Alternatively, if you want to perform historical analysis and find patterns in longer historical data windows (weeks or months), select the **Run historical analysis detection** box and select a date range of at least 128 detection intervals. -Analyzing historical data helps you get familiar with the Anomaly Detection plugin. You can also evaluate the performance of a detector with historical data to further fine-tune it. +Analyzing historical data can help to familiarize you with anomaly detection. For example, you can evaluate the performance of a detector against historical data in order to fine-tune it. -We recommend experimenting with historical analysis with different feature sets and checking the precision before moving on to real-time detectors. +You can experiment with historical analysis by using different feature sets and checking the precision before using real-time detectors. -## Step 4: Review and create +## Step 4: Review detector settings -Review your detector settings and model configurations to make sure that they're valid and then select **Create detector**. +Review your detector settings and model configurations to confirm that they are valid and then select **Create detector**. -![Anomaly detection results]({{site.url}}{{site.baseurl}}/images/review_ad.png) - -If you see any validation errors, edit the settings to fix the errors and then return back to this page. +If a validation error occurs, edit the settings to correct the error and return to the detector page. {: .note } ## Step 5: Observe the results -Choose the **Real-time results** or **Historical analysis** tab. For real-time results, you need to wait for some time to see the anomaly results. If the detector interval is 10 minutes, the detector might take more than an hour to start, because its waiting for sufficient data to generate anomalies. +Select either the **Real-time results** or **Historical analysis** tab. For real-time results, it will take some time to display the anomaly results. For example, if the detector interval is 10 minutes, then the detector may take an hour to initiate because it is waiting for sufficient data to be able to generate anomalies. -A shorter interval means the model passes the shingle process more quickly and starts to generate the anomaly results sooner. -Use the [profile detector]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/api#profile-detector) operation to make sure you have sufficient data points. +A shorter interval results in the model passing the shingle process more quickly and generating anomaly results sooner. You can use the [profile detector]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/api#profile-detector) operation to ensure that you have enough data points. -If you see the detector pending in "initialization" for longer than a day, aggregate your existing data using the detector interval to check for any missing data points. If you find a lot of missing data points from the aggregated data, consider increasing the detector interval. +If the detector is pending in "initialization" for longer than 1 day, aggregate your existing data and use the detector interval to check for any missing data points. If you find many missing data points, consider increasing the detector interval. -Choose and drag over the anomaly line chart to zoom in and see a more detailed view of an anomaly. +Click and drag over the anomaly line chart to zoom in and see a detailed view of an anomaly. {: .note } -Analyze anomalies with the following visualizations: +You can analyze anomalies using the following visualizations: -- **Live anomalies** (for real-time results) displays live anomaly results for the last 60 intervals. For example, if the interval is 10, it shows results for the last 600 minutes. The chart refreshes every 30 seconds. -- **Anomaly overview** (for real-time results) / **Anomaly history** (for historical analysis in the **Historical analysis** tab) plots the anomaly grade with the corresponding measure of confidence. This pane includes: +- **Live anomalies** (for real-time results) displays live anomaly results for the last 60 intervals. For example, if the interval is `10`, it shows results for the last 600 minutes. The chart refreshes every 30 seconds. +- **Anomaly overview** (for real-time results) or **Anomaly history** (for historical analysis on the **Historical analysis** tab) plot the anomaly grade with the corresponding measure of confidence. The pane includes: - The number of anomaly occurrences based on the given data-time range. - - The **Average anomaly grade**, a number between 0 and 1 that indicates how anomalous a data point is. An anomaly grade of 0 represents “not an anomaly,” and a non-zero value represents the relative severity of the anomaly. + - The **Average anomaly grade**, a number between 0 and 1 that indicates how anomalous a data point is. An anomaly grade of `0` represents "not an anomaly," and a non-zero value represents the relative severity of the anomaly. - **Confidence** estimate of the probability that the reported anomaly grade matches the expected anomaly grade. Confidence increases as the model observes more data and learns the data behavior and trends. Note that confidence is distinct from model accuracy. - **Last anomaly occurrence** is the time at which the last anomaly occurred. -Underneath **Anomaly overview**/**Anomaly history** are: +The following sections can be found under **Anomaly overview** and **Anomaly history**: - **Feature breakdown** plots the features based on the aggregation method. You can vary the date-time range of the detector. Selecting a point on the feature line chart shows the **Feature output**, the number of times a field appears in your index, and the **Expected value**, a predicted value for the feature output. Where there is no anomaly, the output and expected values are equal. - ![Anomaly detection results]({{site.url}}{{site.baseurl}}/images/feature-contribution-ad.png) - -- **Anomaly occurrences** shows the `Start time`, `End time`, `Data confidence`, and `Anomaly grade` for each detected anomaly. +- **Anomaly occurrences** shows the `Start time`, `End time`, `Data confidence`, and `Anomaly grade` for each detected anomaly. To view logs related to an occurrence in Discover, select the **View in Discover** icon in the **Actions** column. The logs include a 10-minute buffer before and after the start and end times. Selecting a point on the anomaly line chart shows **Feature Contribution**, the percentage of a feature that contributes to the anomaly -![Anomaly detection results]({{site.url}}{{site.baseurl}}/images/feature-contribution-ad.png) - - If you set the category field, you see an additional **Heat map** chart. The heat map correlates results for anomalous entities. This chart is empty until you select an anomalous entity. You also see the anomaly and feature line chart for the time period of the anomaly (`anomaly_grade` > 0). If you have set multiple category fields, you can select a subset of fields to filter and sort the fields by. Selecting a subset of fields lets you see the top values of one field that share a common value with another field. -For example, if you have a detector with the category fields `ip` and `endpoint`, you can select `endpoint` in the **View by** dropdown menu. Then select a specific cell to overlay the top 20 values of `ip` on the charts. The Anomaly Detection plugin selects the top `ip` by default. You can see a maximum of 5 individual time-series values at the same time. +For example, if you have a detector with the category fields `ip` and `endpoint`, you can select `endpoint` in the **View by** dropdown menu. Then select a specific cell to overlay the top 20 values of `ip` on the charts. By default, the top `ip` is selected. You can see a maximum of 5 individual time-series values at the same time. ## Step 6: Set up alerts -Under **Real-time results**, choose **Set up alerts** and configure a monitor to notify you when anomalies are detected. For steps to create a monitor and set up notifications based on your anomaly detector, see [Monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). +Under **Real-time results**, select **Set up alerts** and configure a monitor to notify you when anomalies are detected. For instructions on how to create a monitor and set up notifications based on your anomaly detector, see [Configuring anomaly alerting]({{site.url}}{{site.baseurl}}/observing-your-data/ad/managing-anomalies/). If you stop or delete a detector, make sure to delete any monitors associated with it. -## Step 7: Adjust the model +## Viewing and updating the detector configuration -To see all the configuration settings for a detector, choose the **Detector configuration** tab. +To view all the configuration settings for a detector, select the **Detector configuration** tab. -1. To make any changes to the detector configuration, or fine tune the time interval to minimize any false positives, go to the **Detector configuration** section and choose **Edit**. -- You need to stop real-time and historical analysis to change its configuration. Confirm that you want to stop the detector and proceed. -1. To enable or disable features, in the **Features** section, choose **Edit** and adjust the feature settings as needed. After you make your changes, choose **Save and start detector**. +1. To make any changes to the detector configuration or fine-tune the time interval to minimize any false positives, go to the **Detector configuration** section and select **Edit**. + You must stop real-time and historical analysis to change the detector's configuration. Confirm that you want to stop the detector and proceed. + {: .important} +2. To enable or disable features, in the **Features** section, select **Edit** and adjust the feature settings as needed. After you make your changes, select **Save and start detector**. -## Step 8: Manage your detectors +## Managing your detectors To start, stop, or delete a detector, go to the **Detectors** page. -1. Choose the detector name. -2. Choose **Actions** and select **Start real-time detectors**, **Stop real-time detectors**, or **Delete detectors**. +1. Select the detector name. +2. Select **Actions** and then select **Start real-time detectors**, **Stop real-time detectors**, or **Delete detectors**. diff --git a/_observing-your-data/ad/managing-anomalies.md b/_observing-your-data/ad/managing-anomalies.md new file mode 100644 index 00000000..509255ca --- /dev/null +++ b/_observing-your-data/ad/managing-anomalies.md @@ -0,0 +1,196 @@ +--- +layout: default +title: Configuring anomaly alerting +nav_order: 20 +parent: Anomaly detection +has_children: false +--- + +# Configuring anomaly alerting + +Once you've created an [anomaly detector]({{site.url}}{{site.baseurl}}/observing-your-data/ad/), you can configure alerting to be notified when anomalies occur. To configure alerting, create an [alert monitor]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/), shown in the following image. For instructions on how to create an alert monitor, see [Creating an alert monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/#creating-an-alert-monitor). + +![Alerting editor]({{site.url}}{{site.baseurl}}/images/anomaly-detection/alerting_editor.png){: width="800" height="800" } + +In **Monitor defining method**, choose one of these methods to define your monitor: + +- **Anomaly detector**: Use when monitoring an individual detector's results with thresholds on anomaly grade and confidence. +- **Extraction query editor**: Use when monitoring multiple detectors, writing complex queries, or creating advanced trigger conditions. + + + +## Example alert monitor + +The following monitor is designed for a high-cardinality detector. You can modify the schedule, query, and aggregation to match your specific use case: + +{% raw %} +```json +{ + "name": "ad-monitor", + "type": "monitor", + "monitor_type": "query_level_monitor", + "enabled": true, + "schedule": { + "period": { + "unit": "MINUTES", + "interval": 2 + } + }, + "inputs": [ + { + "search": { + "indices": [ + ".opendistro-anomaly-results*" + ], + "query": { + "size": 1, + "sort": [ + { + "anomaly_grade": "desc" + }, + { + "confidence": "desc" + } + ], + "query": { + "bool": { + "filter": [ + { + "range": { + "execution_end_time": { + "from": "{{period_end}}||-2m", + "to": "{{period_end}}", + "include_lower": true, + "include_upper": true + } + } + }, + { + "term": { + "detector_id": { + "value": "oJzeoZkB8KmRTvydzJDF" + } + } + } + ] + } + }, + "aggregations": { + "max_anomaly_grade": { + "max": { + "field": "anomaly_grade" + } + } + } + } + } + } + ], + "triggers": [ + { + "query_level_trigger": { + "id": "i5zuoZkB8KmRTvydn5Hg", + "name": "ad-trigger", + "severity": "1", + "condition": { + "script": { + "source": "return ctx.results != null && ctx.results.length > 0 && ctx.results[0].aggregations != null && ctx.results[0].aggregations.max_anomaly_grade != null && ctx.results[0].hits.total.value > 0 && ctx.results[0].hits.hits[0]._source != null && ctx.results[0].hits.hits[0]._source.confidence != null && ctx.results[0].aggregations.max_anomaly_grade.value != null && ctx.results[0].aggregations.max_anomaly_grade.value > 0.7 && ctx.results[0].hits.hits[0]._source.confidence > 0.7", + "lang": "painless" + } + }, + "actions": [ + { + "id": "notification606448", + "name": "ad-action", + "destination_id": "fpzsoZkB8KmRTvydkZGQ", + "message_template": { + "source": "Monitor **{{ctx.monitor.name}}** entered **ALERT** state — please investigate.\n\nTrigger : {{ctx.trigger.name}}\nSeverity : {{ctx.trigger.severity}}\nTime range : {{ctx.periodStart}} → {{ctx.periodEnd}} UTC\n\nEntity\n{{#ctx.results.0.hits.hits.0._source.entity}}\n • {{name}} = {{value}}\n{{/ctx.results.0.hits.hits.0._source.entity}}\n", + "lang": "mustache" + }, + "throttle_enabled": true, + "subject_template": { + "source": "Alerting Notification action", + "lang": "mustache" + }, + "throttle": { + "value": 2, + "unit": "MINUTES" + } + } + ] + } + } + ], + "ui_metadata": { + "schedule": { + "timezone": null, + "frequency": "interval", + "period": { + "unit": "MINUTES", + "interval": 2 + }, + "daily": 0, + "weekly": { + "tue": false, + "wed": false, + "thur": false, + "sat": false, + "fri": false, + "mon": false, + "sun": false + }, + "monthly": { + "type": "day", + "day": 1 + }, + "cronExpression": "0 */2 * * *" + }, + "monitor_type": "query_level_monitor", + "search": { + "searchType": "ad", + "timeField": "", + "aggregations": [], + "groupBy": [], + "bucketValue": 1, + "bucketUnitOfTime": "h", + "filters": [] + } + } +} +``` +{% endraw %} +{% include copy.html %} + +Note the following key configuration in the example alert monitor: + +- **`"size": 1`** in the search input: Retrieves a single document so you can reference `ctx.results.0.hits.hits.0` in the notification to identify which entity (such as `host` or `service`) triggered the alert. + +- **`execution_end_time` range `"{{period_end}}||-2m"` → `"{{period_end}}"`**: Filters results based on detector `execution_end_time`---the time the detector finishes running and indexes the result. Because OpenSearch operates in near real time (results are not immediate), indexing and refresh operations introduce a delay before a document becomes searchable. To account for this write-to-search latency, this example includes a small overlap (`-2m`). Specify the overlap based on your system's worst-case delay. Avoid using `data_end_time` (the bucket's logical end), which can miss results that arrive later. + +- **`"indices": [".opendistro-anomaly-results*"]`**: Matches the default result index pattern. Update this pattern if you route results to a custom index, such as `opensearch-ad-plugin-result-abc*`. + +- **`"detector_id": {"value": "oJzeoZkB8KmRTvydzJDF"}`** (optional): Use this filter to target a specific detector and avoid matching unrelated anomalies from other detectors. + +- **`"max_anomaly_grade"` aggregation**: Detects the most severe anomaly in the time window. You can use any field in the anomaly result index for aggregation. For additional fields, see the [Anomaly result mapping]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/result-mapping/). + +- **Monitor schedule every 2 minutes**: Evaluates results every 2 minutes to detect anomalies quickly. Combined with a 2-minute alert throttle, this avoids duplicate notifications for the same event. + +- **Trigger condition `max_anomaly_grade.value > 0.7 && confidence > 0.7`**: Sets appropriate thresholds that reliably indicate anomalies. Adjust these values based on your tolerance for false positives and negatives. + +- **Mustache template with entity block**: Displays both single-dimension (`host=server_3`) and multi-dimension (`host=server_3`, `service=auth`) entity values in the notification. You can also include a link to a pre-filtered dashboard for faster triage. + + +## Example alert notification + +The following example shows a sample alert email generated by the monitor when an anomaly breaches the defined threshold. In this case, the monitor is tracking a high-cardinality detector and has triggered an alert for a specific entity (`host = server_3`): + +```md +Monitor **ad-monitor** entered **ALERT** state — please investigate. + +Trigger : ad-trigger +Severity : 1 +Time range : 2025-10-01T23:42:33.699Z → 2025-10-01T23:44:33.699Z UTC + +Entity + • host = server_3 +``` \ No newline at end of file diff --git a/_observing-your-data/ad/result-mapping.md b/_observing-your-data/ad/result-mapping.md index 7e1482a0..feea48f3 100644 --- a/_observing-your-data/ad/result-mapping.md +++ b/_observing-your-data/ad/result-mapping.md @@ -2,16 +2,14 @@ layout: default title: Anomaly result mapping parent: Anomaly detection -nav_order: 6 +nav_order: 30 redirect_from: - /monitoring-plugins/ad/result-mapping/ --- # Anomaly result mapping -If you enabled custom result index, the anomaly detection plugin stores the results in your own index. - -If the anomaly detector doesn’t detect an anomaly, the result has the following format: +When you select the **Enable custom result index** box on the **Custom result index** pane, OpenSearch saves the results to an index of your choosing. When the anomaly detector does not detect an anomaly, the result format is as follows: ```json { @@ -61,6 +59,7 @@ If the anomaly detector doesn’t detect an anomaly, the result has the followin "threshold": 1.2368549346675202 } ``` +{% include copy-curl.html %} ## Response body fields @@ -80,7 +79,83 @@ Field | Description `model_id` | A unique ID that identifies a model. If a detector is a single-stream detector (with no category field), it has only one model. If a detector is a high-cardinality detector (with one or more category fields), it might have multiple models, one for each entity. `threshold` | One of the criteria for a detector to classify a data point as an anomaly is that its `anomaly_score` must surpass a dynamic threshold. This field records the current threshold. -If an anomaly detector detects an anomaly, the result has the following format: +When the imputation option is enabled, the anomaly results include a `feature_imputed` array showing which features were modified due to missing data. If no features were imputed, then this is excluded. + +In the following example anomaly result output, the `processing_bytes_max` feature was imputed, as shown by the `imputed: true` status: + +```json +{ + "detector_id": "kzcZ43wBgEQAbjDnhzGF", + "schema_version": 5, + "data_start_time": 1635898161367, + "data_end_time": 1635898221367, + "feature_data": [ + { + "feature_id": "processing_bytes_max", + "feature_name": "processing bytes max", + "data": 2322 + }, + { + "feature_id": "processing_bytes_avg", + "feature_name": "processing bytes avg", + "data": 1718.6666666666667 + }, + { + "feature_id": "processing_bytes_min", + "feature_name": "processing bytes min", + "data": 1375 + }, + { + "feature_id": "processing_bytes_sum", + "feature_name": "processing bytes sum", + "data": 5156 + }, + { + "feature_id": "processing_time_max", + "feature_name": "processing time max", + "data": 31198 + } + ], + "execution_start_time": 1635898231577, + "execution_end_time": 1635898231622, + "anomaly_score": 1.8124904404395776, + "anomaly_grade": 0, + "confidence": 0.9802940756605277, + "entity": [ + { + "name": "process_name", + "value": "process_3" + } + ], + "model_id": "kzcZ43wBgEQAbjDnhzGF_entity_process_3", + "threshold": 1.2368549346675202, + "feature_imputed": [ + { + "feature_id": "processing_bytes_max", + "imputed": true + }, + { + "feature_id": "processing_bytes_avg", + "imputed": false + }, + { + "feature_id": "processing_bytes_min", + "imputed": false + }, + { + "feature_id": "processing_bytes_sum", + "imputed": false + }, + { + "feature_id": "processing_time_max", + "imputed": false + } + ] +} +``` +{% include copy-curl.html %} + +When an anomaly is detected, the result is provided in the following format: ```json { @@ -179,24 +254,23 @@ If an anomaly detector detects an anomaly, the result has the following format: "execution_start_time": 1635898427803 } ``` +{% include copy-curl.html %} -You can see the following additional fields: +Note that the result includes the following additional field. Field | Description :--- | :--- `relevant_attribution` | Represents the contribution of each input variable. The sum of the attributions is normalized to 1. `expected_values` | The expected value for each feature. -At times, the detector might detect an anomaly late. -Let's say the detector sees a random mix of the triples {1, 2, 3} and {2, 4, 5} that correspond to `slow weeks` and `busy weeks`, respectively. For example 1, 2, 3, 1, 2, 3, 2, 4, 5, 1, 2, 3, 2, 4, 5, ... and so on. -If the detector comes across a pattern {2, 2, X} and it's yet to see X, the detector infers that the pattern is anomalous, but it can't determine at this point which of the 2's is the cause. If X = 3, then the detector knows it's the first 2 in that unfinished triple, and if X = 5, then it's the second 2. If it's the first 2, then the detector detects the anomaly late. +The detector may be late in detecting an anomaly. For example: The detector observes a sequence of data that alternates between "slow weeks" (represented by the triples {1, 2, 3}) and "busy weeks" (represented by the triples {2, 4, 5}). If the detector comes across a pattern {2, 2, X}, where it has not yet seen the value that X will take, then the detector infers that the pattern is anomalous. However, it cannot determine which 2 is the cause. If X = 3, then the first 2 is the anomaly. If X = 5, then the second 2 is the anomaly. If it is the first 2, then the detector will be late in detecting the anomaly. -If a detector detects an anomaly late, the result has the following additional fields: +When a detector is late in detecting an anomaly, the result includes the following additional fields. Field | Description :--- | :--- -`past_values` | The actual input that triggered an anomaly. If `past_values` is null, the attributions or expected values are from the current input. If `past_values` is not null, the attributions or expected values are from a past input (for example, the previous two steps of the data [1,2,3]). -`approx_anomaly_start_time` | The approximate time of the actual input that triggers an anomaly. This field helps you understand when a detector flags an anomaly. Both single-stream and high-cardinality detectors don't query previous anomaly results because these queries are expensive operations. The cost is especially high for high-cardinality detectors that might have a lot of entities. If the data is not continuous, the accuracy of this field is low and the actual time that the detector detects an anomaly can be earlier. +`past_values` | The actual input that triggered an anomaly. If `past_values` is `null`, then the attributions or expected values are from the current input. If `past_values` is not `null`, then the attributions or expected values are from a past input (for example, the previous two steps of the data [1,2,3]). +`approx_anomaly_start_time` | The approximate time of the actual input that triggered an anomaly. This field helps you understand the time at which a detector flags an anomaly. Both single-stream and high-cardinality detectors do not query previous anomaly results because these queries are costly operations. The cost is especially high for high-cardinality detectors that may have many entities. If the data is not continuous, then the accuracy of this field is low and the actual time at which the detector detects an anomaly can be earlier. ```json { @@ -319,3 +393,163 @@ Field | Description "approx_anomaly_start_time": 1635883620000 } ``` +{% include copy-curl.html %} + +## Flattened anomaly result mapping + +When selecting the **Enable flattened custom result index** option in the **Custom result index** pane, OpenSearch saves the results with all of the nested fields flattened in the index. + +The nested fields stored in the index use the following flattening rules. + +Field | Flattening rule | Example nested input | Example flattened output +:--- | :--- | :--- | :--- +`relevant_attribution` | `relevant_attribution_$FEATURE_NAME_data: $RELEVANT_ATTRIBUTION_FEATURE_DATA` | `relevant_attribution : [{"feature_id": "deny_max1", "data": 0.07339452532666227}]` | `relevant_attribution_deny_max1_data: 0.07339452532666227` +`past_values` | `past_values_$FEATURE_NAME_data: $PAST_VALUES_FEATURE_DATA` | `"past_values": [{"feature_id": "processing_bytes_max", "data": 905}]` | `past_values_processing_bytes_max_data: 905` +`feature_data` | `feature_data_$FEATURE_NAME_data: $FEATURE_DATA_FEATURE_NAME_DATA` | `"feature_data": [{"feature_id": "processing_bytes_max", "feature_name": "processing bytes max", "data": 1360}]` | `feature_data_processing_bytes_max_data: 1360` +`expected_values` | `expected_values_$FEATURE_NAME_data: $EXPECTED_VALUES_FEATURE_DATA` | `"expected_values": [{"likelihood": 1, "value_list": [{"feature_id": "processing_bytes_max", "data": 905}]}]` | `expected_values_processing_bytes_max_data: 905` +`entity` | `entity_$NAME_value: $ENTITY_VALUE ` | `"entity": [{"name": "process_name", "value": "process_3"}]` | `entity_process_name_value: process_3 ` + +For example, when a detector is late in detecting an anomaly, the flattened result appears in the following format: + +```json +{ + "detector_id": "kzcZ43wBgEQAbjDnhzGF", + "confidence": 0.9746820962328963, + "relevant_attribution": [ + { + "feature_id": "deny_max1", + "data": 0.07339452532666227 + }, + { + "feature_id": "deny_avg", + "data": 0.04934972719948845 + }, + { + "feature_id": "deny_min", + "data": 0.01803003656061806 + }, + { + "feature_id": "deny_sum", + "data": 0.14804918212089874 + }, + { + "feature_id": "accept_max5", + "data": 0.7111765287923325 + } + ], + "relevant_attribution_deny_max1_data": 0.07339452532666227, + "relevant_attribution_deny_avg_data": 0.04934972719948845, + "relevant_attribution_deny_min_data": 0.01803003656061806, + "relevant_attribution_deny_sum_data": 0.14804918212089874, + "relevant_attribution_deny_max5_data": 0.7111765287923325, + "task_id": "9Dck43wBgEQAbjDn4zEe", + "threshold": 1, + "model_id": "kzcZ43wBgEQAbjDnhzGF_entity_app_0", + "schema_version": 5, + "anomaly_score": 1.141419389056506, + "execution_start_time": 1635898427803, + "past_values": [ + { + "feature_id": "processing_bytes_max", + "data": 905 + }, + { + "feature_id": "processing_bytes_avg", + "data": 479 + }, + { + "feature_id": "processing_bytes_min", + "data": 128 + }, + { + "feature_id": "processing_bytes_sum", + "data": 1437 + }, + { + "feature_id": "processing_time_max", + "data": 8440 + } + ], + "past_values_processing_bytes_max_data": 905, + "past_values_processing_bytes_avg_data": 479, + "past_values_processing_bytes_min_data": 128, + "past_values_processing_bytes_sum_data": 1437, + "past_values_processing_bytes_max_data": 8440, + "data_end_time": 1635883920000, + "data_start_time": 1635883860000, + "feature_data": [ + { + "feature_id": "processing_bytes_max", + "feature_name": "processing bytes max", + "data": 1360 + }, + { + "feature_id": "processing_bytes_avg", + "feature_name": "processing bytes avg", + "data": 990 + }, + { + "feature_id": "processing_bytes_min", + "feature_name": "processing bytes min", + "data": 608 + }, + { + "feature_id": "processing_bytes_sum", + "feature_name": "processing bytes sum", + "data": 2970 + }, + { + "feature_id": "processing_time_max", + "feature_name": "processing time max", + "data": 9670 + } + ], + "feature_data_processing_bytes_max_data": 1360, + "feature_data_processing_bytes_avg_data": 990, + "feature_data_processing_bytes_min_data": 608, + "feature_data_processing_bytes_sum_data": 2970, + "feature_data_processing_time_max_data": 9670, + "expected_values": [ + { + "likelihood": 1, + "value_list": [ + { + "feature_id": "processing_bytes_max", + "data": 905 + }, + { + "feature_id": "processing_bytes_avg", + "data": 479 + }, + { + "feature_id": "processing_bytes_min", + "data": 128 + }, + { + "feature_id": "processing_bytes_sum", + "data": 4847 + }, + { + "feature_id": "processing_time_max", + "data": 15713 + } + ] + } + ], + "expected_values_processing_bytes_max_data": 905, + "expected_values_processing_bytes_avg_data": 479, + "expected_values_processing_bytes_min_data": 128, + "expected_values_processing_bytes_sum_data": 4847, + "expected_values_processing_time_max_data": 15713, + "execution_end_time": 1635898427895, + "anomaly_grade": 0.5514172746375128, + "entity": [ + { + "name": "process_name", + "value": "process_3" + } + ], + "entity_process_name_value": "process_3", + "approx_anomaly_start_time": 1635883620000 +} +``` diff --git a/_observing-your-data/ad/security.md b/_observing-your-data/ad/security.md index 8eeaa3df..89c2b1aa 100644 --- a/_observing-your-data/ad/security.md +++ b/_observing-your-data/ad/security.md @@ -1,7 +1,7 @@ --- layout: default title: Anomaly detection security -nav_order: 10 +nav_order: 40 parent: Anomaly detection has_children: false redirect_from: @@ -12,10 +12,12 @@ redirect_from: You can use the Security plugin with anomaly detection in OpenSearch to limit non-admin users to specific actions. For example, you might want some users to only be able to create, update, or delete detectors, while others to only view detectors. +To control access to individual detectors using resource sharing, see [Anomaly detector access control]({{site.url}}{{site.baseurl}}/observing-your-data/ad/detector-access-control/). + All anomaly detection indexes are protected as system indexes. Only a super admin user or an admin user with a TLS certificate can access system indexes. For more information, see [System indexes]({{site.url}}{{site.baseurl}}/security/configuration/system-indices/). -Security for anomaly detection works the same as [security for alerting]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/). +Security for anomaly detection works the same as [security for alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/). ## Basic permissions @@ -23,19 +25,60 @@ As an admin user, you can use the Security plugin to assign specific permissions The Security plugin has two built-in roles that cover most anomaly detection use cases: `anomaly_full_access` and `anomaly_read_access`. For descriptions of each, see [Predefined roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles#predefined-roles). +If you use OpenSearch Dashboards to create your anomaly detectors, you may experience access issues even with `anomaly_full_access`. This issue has been resolved in OpenSearch 2.17, but for earlier versions, the following additional permissions need to be added: + +- `indices:data/read/search` -- You need this permission because anomaly detection needs to search the data source in order to validate whether there is enough data to train the model. +- `indices:admin/mappings/fields/get` and `indices:admin/mappings/fields/get*` -- You need these permissions to validate whether the given data source has a valid timestamp field and categorical field (in the case of creating a high-cardinality detector). + If these roles don't meet your needs, mix and match individual anomaly detection [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/) to suit your use case. Each action corresponds to an operation in the REST API. For example, the `cluster:admin/opensearch/ad/detector/delete` permission lets you delete detectors. ### A note on alerts and fine-grained access control -When a trigger generates an alert, the detector and monitor configurations, the alert itself, and any notification that is sent to a channel may include metadata describing the index being queried. By design, the plugin must extract the data and store it as metadata outside of the index. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security) (FLS) access controls are designed to protect the data in the index. But once the data is stored outside the index as metadata, users with access to the detector and monitor configurations, alerts, and their notifications will be able to view this metadata and possibly infer the contents and quality of data in the index, which would otherwise be concealed by DLS and FLS access control. +When a trigger generates an alert, the detector and monitor configurations, the alert itself, and any notification that is sent to a channel may include metadata describing the index being queried. By design, anomaly detection must extract the data and store it as metadata outside of the index. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security/) (FLS) access controls are designed to protect the data in the index. But once the data is stored outside the index as metadata, users with access to the detector and monitor configurations, alerts, and their notifications will be able to view this metadata and possibly infer the contents and quality of data in the index, which would otherwise be concealed by DLS and FLS access control. To reduce the chances of unintended users viewing metadata that could describe an index, we recommend that administrators enable role-based access control and keep these kinds of design elements in mind when assigning permissions to the intended group of users. See [Limit access by backend role](#advanced-limit-access-by-backend-role) for details. +### Selecting remote indexes with fine-grained access control + +To use a remote index as a data source for a detector, see the setup steps in [Authentication flow]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/#authentication-flow) in [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/). You must use a role that exists in both the remote and local clusters. The remote cluster must map the chosen role to the same username as in the local cluster. + +--- + +#### Example: Create a new user on the local cluster + +1. Create a new user on the local cluster to use for detector creation: + +``` +curl -XPUT -k -u 'admin:<custom-admin-password>' 'https://localhost:9200/_plugins/_security/api/internalusers/anomalyuser' -H 'Content-Type: application/json' -d '{"password":"password"}' +``` +{% include copy.html %} + +2. Map the new user to the `anomaly_full_access` role: + +``` +curl -XPUT -k -u 'admin:<custom-admin-password>' -H 'Content-Type: application/json' 'https://localhost:9200/_plugins/_security/api/rolesmapping/anomaly_full_access' -d '{"users" : ["anomalyuser"]}' +``` +{% include copy.html %} + +3. On the remote cluster, create the same user and map `anomaly_full_access` to that role: + +``` +curl -XPUT -k -u 'admin:<custom-admin-password>' 'https://localhost:9250/_plugins/_security/api/internalusers/anomalyuser' -H 'Content-Type: application/json' -d '{"password":"password"}' +curl -XPUT -k -u 'admin:<custom-admin-password>' -H 'Content-Type: application/json' 'https://localhost:9250/_plugins/_security/api/rolesmapping/anomaly_full_access' -d '{"users" : ["anomalyuser"]}' +``` +{% include copy.html %} + +--- + +### Custom results index + +To use a custom results index, you need additional permissions not included in the default roles provided by the OpenSearch Security plugin. To add these permissions, see [Step 1: Define a detector]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/#step-1-define-a-detector) in the [Anomaly detection]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/) documentation. + ## (Advanced) Limit access by backend role Use backend roles to configure fine-grained access to individual detectors based on roles. For example, users of different departments in an organization can view detectors owned by their own department. -First, make sure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/), but if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/access-control/api#create-user). +First, make sure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/), but if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/api/users/create-user/). Next, enable the following setting: diff --git a/_observing-your-data/ad/settings.md b/_observing-your-data/ad/settings.md index 19099441..36c69737 100644 --- a/_observing-your-data/ad/settings.md +++ b/_observing-your-data/ad/settings.md @@ -1,13 +1,13 @@ --- layout: default -title: Settings +title: Anomaly detection settings parent: Anomaly detection -nav_order: 4 +nav_order: 70 redirect_from: - /monitoring-plugins/ad/settings/ --- -# Anomaly Detection settings +# Anomaly detection settings The Anomaly Detection plugin adds several settings to the standard OpenSearch cluster settings. The settings are dynamic, so you can change the default behavior of the plugin without restarting your cluster. To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). @@ -24,29 +24,54 @@ PUT _cluster/settings } } ``` +{% include copy-curl.html %} -Setting | Default | Description -:--- | :--- | :--- -plugins.anomaly_detection.enabled | True | Whether the anomaly detection plugin is enabled or not. If disabled, all detectors immediately stop running. -plugins.anomaly_detection.max_anomaly_detectors | 1,000 | The maximum number of non-high cardinality detectors (no category field) users can create. -plugins.anomaly_detection.max_multi_entity_anomaly_detectors | 10 | The maximum number of high cardinality detectors (with category field) in a cluster. -plugins.anomaly_detection.max_anomaly_features | 5 | The maximum number of features for a detector. -plugins.anomaly_detection.ad_result_history_rollover_period | 12h | How often the rollover condition is checked. If `true`, the anomaly detection plugin rolls over the result index to a new index. -plugins.anomaly_detection.ad_result_history_max_docs_per_shard | 1,350,000,000 | The maximum number of documents in a single shard of the result index. The anomaly detection plugin only counts the refreshed documents in the primary shards. -plugins.anomaly_detection.max_entities_per_query | 1,000,000 | The maximum unique values per detection interval for high cardinality detectors. By default, if the category field(s) have more than the configured unique values in a detector interval, the anomaly detection plugin orders them by the natural ordering of categorical values (for example, entity `ab` comes before `bc`) and then selects the top values. -plugins.anomaly_detection.max_entities_for_preview | 5 | The maximum unique category field values displayed with the preview operation for high cardinality detectors. By default, if the category field(s) have more than the configured unique values in a detector interval, the anomaly detection plugin orders them by the natural ordering of categorical values (for example, entity `ab` comes before `bc`) and then selects the top values. -plugins.anomaly_detection.max_primary_shards | 10 | The maximum number of primary shards an anomaly detection index can have. -plugins.anomaly_detection.filter_by_backend_roles | False | When you enable the Security plugin and set this to `true`, the anomaly detection plugin filters results based on the user's backend role(s). -plugins.anomaly_detection.max_batch_task_per_node | 10 | Starting a historical analysis triggers a batch task. This setting is the number of batch tasks that you can run per data node. You can tune this setting from 1 to 1,000. If the data nodes can’t support all batch tasks and you’re not sure if the data nodes are capable of running more historical analysis, add more data nodes instead of changing this setting to a higher value. Increasing this value might bring more load on each data node. -plugins.anomaly_detection.max_old_ad_task_docs_per_detector | 1 | You can run historical analysis for the same detector many times. For each run, the anomaly detection plugin creates a new task. This setting is the number of previous tasks the plugin keeps. Set this value to at least 1 to track its last run. You can keep a maximum of 1,000 old tasks to avoid overwhelming the cluster. -plugins.anomaly_detection.batch_task_piece_size | 1,000 | The date range for a historical task is split into smaller pieces and the anomaly detection plugin runs the task piece by piece. Each piece contains 1,000 detection intervals by default. For example, if detector interval is 1 minute and one piece is 1,000 minutes, the feature data is queried every 1,000 minutes. You can change this setting from 1 to 10,000. -plugins.anomaly_detection.batch_task_piece_interval_seconds | 5 | Add a time interval between two pieces of the same historical analysis task. This interval prevents the task from consuming too much of the available resources and starving other operations like search and bulk index. You can change this setting from 1 to 600 seconds. -plugins.anomaly_detection.max_top_entities_for_historical_analysis | 1,000 | The maximum number of top entities that you run for a high cardinality detector historical analysis. The range is from 1 to 10,000. -plugins.anomaly_detection.max_running_entities_per_detector_for_historical_analysis | 10 | The number of entity tasks that you can run in parallel for a high cardinality detector analysis. The task slots available on your cluster also impact how many entities run in parallel. If a cluster has 3 data nodes, each data node has 10 task slots by default. Say you already have two high cardinality detectors and each of them run 10 entities. If you start a single-entity detector that takes 1 task slot, the number of task slots available is 10 * 3 - 10 * 2 - 1 = 9. If you now start a new high cardinality detector, the detector can only run 9 entities in parallel and not 10. You can tune this value from 1 to 1,000 based on your cluster's capability. If you set a higher value, the anomaly detection plugin runs historical analysis faster but also consumes more resources. -plugins.anomaly_detection.max_cached_deleted_tasks | 1,000 | You can rerun historical analysis for a single detector as many times as you like. The anomaly detection plugin only keeps a limited number of old tasks, by default 1 old task. If you run historical analysis three times for a detector, the oldest task is deleted. Because historical analysis generates a number of anomaly results in a short span of time, it's necessary to clean up anomaly results for a deleted task. With this field, you can configure how many deleted tasks you can cache at most. The plugin cleans up a task's results when it's deleted. If the plugin fails to do this cleanup, it adds the task's results into a cache and an hourly cron job performs the cleanup. You can use this setting to limit how many old tasks are put into cache to avoid a DDoS attack. After an hour, if still you find an old task result in the cache, use the [delete detector results API]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/api/#delete-detector-results) to delete the task result manually. You can tune this setting from 1 to 10,000. -plugins.anomaly_detection.delete_anomaly_result_when_delete_detector | False | Whether the anomaly detection plugin deletes the anomaly result when you delete a detector. If you want to save some disk space, especially if you've high cardinality detectors generating a lot of results, set this field to true. Alternatively, you can use the [delete detector results API]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/api/#delete-detector-results) to manually delete the results. -plugins.anomaly_detection.dedicated_cache_size | 10 | If the real-time analysis of a high cardinality detector starts successfully, the anomaly detection plugin guarantees keeping 10 (dynamically adjustable via this setting) entities' models in memory per node. If the number of entities exceeds this limit, the plugin puts the extra entities' models in a memory space shared by all detectors. The actual number of entities varies based on the memory that you've available and the frequencies of the entities. If you'd like the plugin to guarantee keeping more entities' models in memory and if you're cluster has sufficient memory, you can increase this setting value. -plugins.anomaly_detection.max_concurrent_preview | 2 | The maximum number of concurrent previews. You can use this setting to limit resource usage. -plugins.anomaly_detection.model_max_size_percent | 0.1 | The upper bound of the memory percentage for a model. -plugins.anomaly_detection.door_keeper_in_cache.enabled | False | When set to `true`, OpenSearch places a bloom filter in front of an inactive entity cache to filter out items that are not likely to appear more than once. -plugins.anomaly_detection.hcad_cold_start_interpolation.enabled | False | When set to `true`, enables interpolation in high-cardinality anomaly detection (HCAD) cold start. \ No newline at end of file +OpenSearch supports the following anomaly detection settings: + +- `plugins.anomaly_detection.enabled` (Dynamic, Boolean): Whether the Anomaly Detection plugin is enabled or not. If disabled, all detectors immediately stop running. Default is `true`. + +- `plugins.anomaly_detection.max_anomaly_detectors` (Dynamic, integer): The maximum number of single-entity detectors (detectors without a category field) in a cluster. Default is `1000`. + +- `plugins.anomaly_detection.max_multi_entity_anomaly_detectors` (Dynamic, integer): The maximum number of high cardinality detectors (detectors with a category field) in a cluster. Default is `10`. + +- `plugins.anomaly_detection.max_anomaly_features` (Dynamic, integer): The maximum number of features for a detector. Default is `5`. + +- `plugins.anomaly_detection.ad_result_history_rollover_period` (Dynamic, time unit): How often the rollover condition is checked. When the rollover condition is met, the Anomaly Detection plugin rolls over the result index to a new index. Default is `12h`. + +- `plugins.anomaly_detection.ad_result_history_max_docs_per_shard` (Dynamic, integer): The maximum number of documents in a single shard of the result index. The Anomaly Detection plugin only counts the refreshed documents in the primary shards. Default is `1350000000`. + +- `plugins.anomaly_detection.max_entities_per_query` (Dynamic, integer): The maximum unique values per detection interval for high cardinality detectors. By default, if the category field(s) have more than the configured unique values in a detector interval, the Anomaly Detection plugin orders them by the natural ordering of categorical values (for example, entity `ab` comes before `bc`) and then selects the top values. Default is `1000000`. + +- `plugins.anomaly_detection.max_entities_for_preview` (Dynamic, integer): The maximum unique category field values displayed with the preview operation for high cardinality detectors. By default, if the category field(s) have more than the configured unique values in a detector interval, the Anomaly Detection plugin orders them by the natural ordering of categorical values (for example, entity `ab` comes before `bc`) and then selects the top values. Default is `5`. + +- `plugins.anomaly_detection.max_primary_shards` (Dynamic, integer): The maximum number of primary shards an anomaly detection index can have. Default is `10`. + +- `plugins.anomaly_detection.filter_by_backend_roles` (Dynamic, Boolean): When you enable the Security plugin and set this to `true`, the Anomaly Detection plugin filters results based on the user's backend role(s). Default is `false`. + +- `plugins.anomaly_detection.max_batch_task_per_node` (Dynamic, integer): Starting a historical analysis triggers a batch task. This setting is the number of batch tasks that you can run per data node. You can tune this setting from 1 to 1,000. If the data nodes can’t support all batch tasks and you’re not sure if the data nodes are capable of running more historical analysis, add more data nodes instead of changing this setting to a higher value. Increasing this value might bring more load on each data node. Default is `10`. + +- `plugins.anomaly_detection.max_old_ad_task_docs_per_detector` (Dynamic, integer): You can run historical analysis for the same detector many times. For each run, the Anomaly Detection plugin creates a new task. This setting is the number of previous tasks the plugin keeps. Set this value to at least 1 to track its last run. You can keep a maximum of 1,000 old tasks to avoid overwhelming the cluster. Default is `1`. + +- `plugins.anomaly_detection.batch_task_piece_size` (Dynamic, integer): The date range for a historical task is split into smaller pieces and the Anomaly Detection plugin runs the task piece by piece. Each piece contains 1,000 detection intervals by default. For example, if detector interval is 1 minute and one piece is 1,000 minutes, the feature data is queried every 1,000 minutes. You can change this setting from 1 to 10,000. Default is `1000`. + +- `plugins.anomaly_detection.batch_task_piece_interval_seconds` (Dynamic, integer): The time interval, in seconds, between two pieces of the same historical analysis task. This interval prevents the task from consuming too much of the available resources and starving other operations like search and bulk index. You can change this setting from 1 to 600 seconds. Default is `5`. + +- `plugins.anomaly_detection.max_top_entities_for_historical_analysis` (Dynamic, integer): The maximum number of top entities that you run for a high cardinality detector historical analysis. The range is from 1 to 10,000. Default is `1000`. + +- `plugins.anomaly_detection.max_running_entities_per_detector_for_historical_analysis` (Dynamic, integer): The number of entity tasks that you can run in parallel for a high cardinality detector analysis. The task slots available on your cluster also impact how many entities run in parallel. If a cluster has 3 data nodes, each data node has 10 task slots by default. Say you already have two high cardinality detectors and each of them run 10 entities. If you start a single-entity detector that takes 1 task slot, the number of task slots available is `10 * 3 - 10 * 2 - 1 = 9`. If you now start a new high cardinality detector, the detector can only run 9 entities in parallel and not 10. You can tune this value from 1 to 1,000 based on your cluster's capability. If you set a higher value, the Anomaly Detection plugin runs historical analysis faster but also consumes more resources. Default is `10`. + +- `plugins.anomaly_detection.max_cached_deleted_tasks` (Dynamic, integer): You can rerun historical analysis for a single detector as many times as you like. The Anomaly Detection plugin only keeps a limited number of old tasks, by default 1 old task. If you run historical analysis three times for a detector, the oldest task is deleted. Because historical analysis generates a number of anomaly results in a short span of time, it's necessary to clean up anomaly results for a deleted task. With this field, you can configure how many deleted tasks you can cache at most. The plugin cleans up a task's results when it's deleted. If the plugin fails to do this cleanup, it adds the task's results into a cache and an hourly cron job performs the cleanup. You can use this setting to limit how many old tasks are put into cache to avoid a DDoS attack. After an hour, if still you find an old task result in the cache, use the [delete detector results API]({{site.url}}{{site.baseurl}}/observing-your-data/ad/api/#delete-detector-results) to delete the task result manually. You can tune this setting from 1 to 10,000. Default is `1000`. + +- `plugins.anomaly_detection.delete_anomaly_result_when_delete_detector` (Dynamic, Boolean): Whether the Anomaly Detection plugin deletes the anomaly result when you delete a detector. If you want to save some disk space, especially if you have high cardinality detectors generating a lot of results, set this setting to `true`. Alternatively, you can use the [delete detector results API]({{site.url}}{{site.baseurl}}/observing-your-data/ad/api/#delete-detector-results) to manually delete the results. Default is `false`. + +- `plugins.anomaly_detection.dedicated_cache_size` (Dynamic, integer): If the real-time analysis of a high cardinality detector starts successfully, the Anomaly Detection plugin guarantees keeping 10 (dynamically adjustable through this setting) entities' models in memory per node. If the number of entities exceeds this limit, the plugin puts the extra entities' models in a memory space shared by all detectors. The actual number of entities varies based on the memory that you have available and the frequencies of the entities. If you'd like the plugin to guarantee keeping more entities' models in memory and if your cluster has sufficient memory, you can increase this setting value. Default is `10`. + +- `plugins.anomaly_detection.max_concurrent_preview` (Dynamic, integer): The maximum number of concurrent previews. You can use this setting to limit resource usage. Default is `2`. + +- `plugins.anomaly_detection.model_max_size_percent` (Dynamic, float): The upper bound of the memory percentage for a model. Default is `0.1`. + +- `plugins.anomaly_detection.door_keeper_in_cache.enabled` (Dynamic, Boolean): When set to `true`, OpenSearch places a bloom filter in front of an inactive entity cache to filter out items that are not likely to appear more than once. Default is `false`. + +- `plugins.anomaly_detection.hcad_cold_start_interpolation.enabled` (Dynamic, Boolean): When set to `true`, enables interpolation for high-cardinality anomaly detection (HCAD) during the initial cold start period. Default is `false`. + +- `plugins.anomaly_detection.jvm_heap_usage_threshold` (Dynamic, integer): The JVM memory usage threshold, as a percentage, at which anomaly detectors are disabled. Valid values are 0--98. Detectors are disabled when JVM heap usage reaches this percentage. Default is `95`. diff --git a/_observing-your-data/agent-traces/agent-tracing.md b/_observing-your-data/agent-traces/agent-tracing.md new file mode 100644 index 00000000..13fdb89e --- /dev/null +++ b/_observing-your-data/agent-traces/agent-tracing.md @@ -0,0 +1,172 @@ +--- +layout: default +title: Viewing agent traces +parent: Agent monitoring +grand_parent: Observability workspace apps +nav_order: 20 +--- + +# Viewing agent traces +**Introduced 3.6** +{: .label .label-purple } + +The **Agent Traces** page in OpenSearch Dashboards lets you explore, debug, and monitor large language model (LLM) agent execution traces. You can view traces in multiple synchronized visualizations, examine span details, and analyze metrics for your agentic AI applications. + +## Enabling agent traces + +Agent traces functionality is included in default OpenSearch distributions. To enable agent traces, add the following feature flags to your `opensearch_dashboards.yml` configuration file: + +```yaml +workspace.enabled: true +explore.enabled: true +explore.agentTraces.enabled: true +``` +{% include copy.html %} + +After updating the configuration, restart OpenSearch Dashboards for the changes to take effect. + +[PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) query support is enabled by default in default OpenSearch distributions. If you're running a minimal distribution of OpenSearch, [install the SQL plugin]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/) before using agent traces. +{: .note} + +## Understanding traces and spans + +In agent tracing, a **trace** represents a complete execution flow (such as a single agent invocation), while **spans** represent individual operations within that trace (such as LLM calls, tool executions, or retrieval operations). Each trace consists of one or more spans organized in a parent-child hierarchy. + +### Span categories + +Agent traces classifies spans into categories based on the `gen_ai.operation.name` attribute. Each category has a distinct color and icon in the **Agent Traces** page. + +| Category | Operation names | Description | +| :--- | :--- | :--- | +| Agent | `invoke_agent`, `create_agent` | Agent invocations and initialization. | +| LLM | `chat`, `text_completion`, `generate_content` | LLM chat completion, text completion, and content generation requests. | +| Tool | `execute_tool` | Tool and function calls. | +| Embeddings | `embeddings` | Embedding generation requests. | +| Retrieval | `retrieval` | Document or data retrieval operations. | +| Other | Unmapped operations | Operations not matching a known category. | + +### Span attributes + +When you instrument your application using the [`opensearch-genai-observability-sdk-py` SDK]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/instrument/), spans are automatically created with the required attributes. The following tables list the core OpenTelemetry attributes and the generative AI semantic convention attributes. + +#### Core attributes + +The following table lists the core OpenTelemetry attributes. + +| Attribute | Required | Description | +| :--- | :--- | :--- | +| `traceId` | Yes | A unique identifier for the trace. | +| `spanId` | Yes | A unique identifier for the span. | +| `parentSpanId` | No | The identifier of the parent span. Empty for root spans. | +| `startTime` | Yes | The span start timestamp. | +| `endTime` | Yes | The span end timestamp. | +| `durationInNanos` | Yes | The span duration, in nanoseconds. | +| `status.code` | Yes | The span status code. Valid values are `OK` (success), `ERROR` (failure), or `UNSET` (default status when not explicitly set). | + +#### Generative AI attributes + +The following table lists the generative AI semantic convention attributes. + +| Attribute | Required | Description | +| :--- | :--- | :--- | +| `gen_ai.operation.name` | Yes | The operation type. Valid values are `chat`, `invoke_agent`, `execute_tool`, `create_agent`, `text_completion`, `embeddings`, or `retrieval`. Used for span categorization, filtering, and tab queries. | +| `gen_ai.provider.name` | Yes | The generative AI provider name (for example, `openai`, `anthropic`). | +| `gen_ai.agent.name` | Optional | A human-readable name of the GenAI agent. | +| `gen_ai.request.model` | Optional | The model name to which the request is sent. | +| `gen_ai.usage.input_tokens` | Optional | The number of input tokens consumed. | +| `gen_ai.usage.output_tokens` | Optional | The number of output tokens generated. | +| `gen_ai.input.messages` | Optional | The chat history or prompt provided as model input. | +| `gen_ai.output.messages` | Optional | The messages or completion returned by the model. | +| `gen_ai.tool.name` | Optional | The name of the tool used by the agent. Only applicable to `execute_tool` operation spans. | +| `gen_ai.tool.call.id` | Optional | The tool call identifier. Only applicable to `execute_tool` operation spans. | + +## Data pipeline + +Agent traces follow this data pipeline: + +1. Instrumented LLM applications send OpenTelemetry Protocol (OTLP) data over gRPC or HTTP. +2. The OpenTelemetry Collector processes and routes the data. +3. [Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/index/) ingests the data into OpenSearch using the `otel_trace_raw` processor. +4. OpenSearch stores trace data in `otel-v1-apm-span-*` indexes. +5. OpenSearch Dashboards displays the traces in the **Agent Traces** page. + +## Using the interface + +To access agent traces, in your Observability workspace, select **Agent monitoring** > **Traces** or **Agent monitoring** > **Spans** in the left navigation. Both open the **Agent Traces** page, on the **Traces** tab or the **Spans** tab. + +The **Agent Traces** page includes the following components. + +### Traces tab + +The Traces tab displays root-level traces in a paginated table. You can expand a row to view child spans inline. + +The following image shows the Traces tab. + +![Traces tab showing root-level agent traces]({{site.url}}{{site.baseurl}}/images/agent-traces/traces-table.png) + +### Spans tab + +The Spans tab shows all generative AI spans, not only root traces. Use this tab to examine individual operations across multiple traces. The table includes the same columns as the [Traces tab](#traces-tab). + +The following image shows the Spans tab. + +![Spans tab showing all generative AI spans]({{site.url}}{{site.baseurl}}/images/agent-traces/spans-table.png) + +## Trace details + +Select a row in the Traces or Spans tab to open the trace details. Trace details provide three synchronized visualization views and a span details panel. Selecting a span in any view highlights it across all three views. + +### Agent graph + +The agent graph renders traces as a directed acyclic graph (DAG) using the Dagre layout algorithm. Parent spans flow downward to child spans, and sibling spans are arranged horizontally. + +The following image shows the agent graph view. + +![Agent Graph showing DAG visualization]({{site.url}}{{site.baseurl}}/images/agent-traces/agent-graph.png) + +Each node in the graph includes the following elements: + +- A color-coded badge indicating the span category (for example, Agent, LLM, or Tool). +- The span name, truncated to 37 characters. +- A bar showing the span duration as a percentage of total trace time. +- A red badge displayed for spans with an `ERROR` status. + +The Agent Graph provides the following controls: + +- Adjust zoom from 0.1x to 2x. +- Reset the viewport to display all nodes. + +Select a node to view its details in the span details panel. Select the background to deselect the node. + +### Trace tree view + +The trace tree view displays all spans in an expandable hierarchical structure. Each row shows the following information: + +- The color-coded span category. +- The operation name. +- The number of tokens consumed by the operation. +- The span duration. + +Expand or collapse nodes to navigate the parent-child relationships. + +The following image shows the trace tree view. + +![Trace tree view showing hierarchical span structure]({{site.url}}{{site.baseurl}}/images/agent-traces/trace-tree.png) + +### Timeline view + +The timeline view presents a Gantt-style chart showing span durations chronologically. Each span appears as a horizontal bar with the following characteristics: + +- The bar width corresponds to the span duration. +- The bar color matches the span category color. +- The indentation reflects the span hierarchy depth. + +Overlapping bars indicate concurrent operations. Use this view to identify bottlenecks and understand the sequential and parallel execution patterns of your agent. + +The following image shows the timeline view. + +![Timeline view showing Gantt-style span chart]({{site.url}}{{site.baseurl}}/images/agent-traces/timeline.png) + +### Span details panel + +The right panel displays detailed information about the selected span, including all JSON attributes and execution timing. diff --git a/_observing-your-data/agent-traces/index.md b/_observing-your-data/agent-traces/index.md new file mode 100644 index 00000000..eaa69311 --- /dev/null +++ b/_observing-your-data/agent-traces/index.md @@ -0,0 +1,53 @@ +--- +layout: default +title: Agent monitoring +parent: Observability workspace apps +nav_order: 60 +has_children: true +has_toc: false +redirect_from: + - /observing-your-data/agent-traces/ +--- + +# Agent monitoring +**Introduced 3.6** +{: .label .label-purple } + +Agent monitoring provides observability for generative AI applications and large language model (LLM) agents. It uses agent traces, which record LLM calls, token usage, tool invocations, and agent reasoning flows following the OpenTelemetry [generative AI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/). + +## Prerequisites + +Agent monitoring requires the following components: + +- An OpenSearch cluster, which stores trace data in `otel-v1-apm-span-*` indexes. +- OpenSearch Dashboards with an Observability workspace and the `explore.enabled` and `explore.agentTraces.enabled` settings set to `true`. For more information, see [Observability workspace apps]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/). +- An [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/). +- [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/), which processes trace data and writes it to OpenSearch. +- Applications instrumented using the OpenTelemetry [generative AI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/). For more information, see [Instrumenting your application]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/instrument/). + +## The agent traces workflow + +The agent traces workflow consists of the following stages: + +1. **Instrument**: Add observability to your AI applications: + - Use the [GenAI SDK](https://observability.opensearch.org/docs/send-data/ai-agents/) containing decorators, enrichment functions, and automatic LLM instrumentation for libraries such as OpenAI, Anthropic, Amazon Bedrock, and LangChain. + +2. **Normalize**: The OpenTelemetry Collector standardizes spans using [generative AI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/), ensuring consistent attribute names across providers. + +3. **Use local tooling** (Optional): Use [Agent Health](https://observability.opensearch.org/docs/agent-health/) for local debugging, scoring, and evaluation during development. + +4. **Process**: [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) routes OpenTelemetry Protocol (OTLP) data into OpenSearch, creating service maps, correlating traces, and aggregating metrics. + +5. **View**: [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/agent-tracing/) displays agent traces as hierarchical trees, directed acyclic graphs (DAGs), and timelines, along with metrics for production monitoring. + +Agent traces support the following frameworks and providers: + +- **Frameworks**: Strands Agents, LangGraph, CrewAI, and the OpenAI Agents SDK. +- **Providers**: OpenAI, Anthropic, Amazon Bedrock, LangChain, LlamaIndex, and other LLM providers. + +## Getting started + +To start using agent traces, explore the following topics: + +- [Instrument your application]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/instrument/) -- Install the SDK and add tracing to your AI agents. +- [Viewing agent traces]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/agent-tracing/) -- Configure and explore agent traces in OpenSearch Dashboards. diff --git a/_observing-your-data/agent-traces/instrument.md b/_observing-your-data/agent-traces/instrument.md new file mode 100644 index 00000000..1208fbbb --- /dev/null +++ b/_observing-your-data/agent-traces/instrument.md @@ -0,0 +1,192 @@ +--- +layout: default +title: Instrumenting your application +parent: Agent monitoring +grand_parent: Observability workspace apps +nav_order: 10 +--- + +# Instrumenting your application +**Introduced 3.6** +{: .label .label-purple } + +The `opensearch-genai-observability-sdk-py` package instruments Python AI agents using [OpenTelemetry](https://opentelemetry.io/). The SDK provides two instrumentation approaches: + +- **Auto-instrumentation**: Automatically captures LLM calls from supported providers (OpenAI, Anthropic, Amazon Bedrock, LangChain, LlamaIndex) without code changes. +- **Manual instrumentation**: Use the `@observe` decorator to trace custom agent logic, tool calls, and orchestration code. + +For most applications, combine both approaches: enable auto-instrumentation for LLM calls and use `@observe` for application-specific operations. + +## Prerequisites + +Before you start, ensure that you have the following: + +- Python 3.10 or later. +- An OpenSearch cluster with [Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/index/) configured for trace ingestion. +- An [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) to normalize spans using generative AI semantic conventions. + +## Installation + +Install the base package: + +```bash +pip install opensearch-genai-observability-sdk-py +``` +{% include copy.html %} + +To enable auto-instrumentation for specific providers, install the corresponding optional dependencies. For example, to instrument OpenAI and LangChain: + +```bash +pip install opensearch-genai-observability-sdk-py[openai,langchain] +``` +{% include copy.html %} + +The following providers support auto-instrumentation: + +| Provider | Package name | +| :--- | :--- | +| OpenAI | `openai` | +| Anthropic | `anthropic` | +| Amazon Bedrock | `bedrock` | +| Google | `google` | +| LangChain | `langchain` | +| LlamaIndex | `llamaindex` | + +## Core API + +The following sections describe the core API functions. + +<!-- vale off --> +### register() +<!-- vale on --> + +The `register()` function configures the OpenTelemetry tracer and exporter. Call it once at application startup: + +```python +from opentelemetry_genai_sdk import register + +register( + endpoint="http://localhost:4318", + service_name="my-agent-app", + protocol="http", + auto_instrument=True +) +``` +{% include copy.html %} + +The following table describes the `register()` parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `endpoint` | String | The OpenTelemetry Protocol (OTLP) endpoint URL. Default is `http://localhost:4318` for the OpenTelemetry Collector. | +| `service_name` | String | An identifier for your application in trace data. | +| `protocol` | String | The transport protocol. Valid values are `http` and `grpc`. | +| `auto_instrument` | Boolean | When `true`, automatically discovers and enables installed provider instrumentation packages. Default is `false`. | + +<!-- vale off --> +### @observe decorator +<!-- vale on --> + +The `@observe` decorator wraps functions to create spans automatically. Use it to trace agent invocations, tool calls, and other operations: + +```python +from opentelemetry_genai_sdk import observe, Op + +@observe(op=Op.INVOKE_AGENT) +def run_agent(prompt: str): + # Agent logic here + return response + +@observe(op=Op.EXECUTE_TOOL) +def search_database(query: str): + # Tool logic here + return results +``` +{% include copy.html %} + +The decorator supports synchronous functions, asynchronous functions, generators, and asynchronous generators. Span names are generated automatically from function names, or you can provide a custom name using the `name_from` parameter. + +<!-- vale off --> +### enrich() +<!-- vale on --> + +The `enrich()` function adds GenAI semantic attributes to the active span: + +```python +from opentelemetry_genai_sdk import enrich + +enrich( + model="gpt-4o-mini", + provider="openai", + input_tokens=150, + output_tokens=50, + finish_reason="stop" +) +``` +{% include copy.html %} + +<!-- vale off --> +### score() +<!-- vale on --> + +The `score()` function attaches evaluation metrics to traces or individual spans: + +```python +from opentelemetry_genai_sdk import score + +score( + trace_id="abc123", + name="relevance", + value=0.95, + explanation="Response directly addresses the query" +) +``` +{% include copy.html %} + +## Operation types + +The `Op` class provides standardized operation names that map to [GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/). These operation types determine how spans are categorized and displayed in the **Agent Traces** page. + +| Operation | Constant | Description | +| :--- | :--- | :--- | +| Invoke agent | `Op.INVOKE_AGENT` | Root-level agent invocation. | +| Execute tool | `Op.EXECUTE_TOOL` | Tool or function call within an agent. | +| Chat | `Op.CHAT` | LLM chat completion request. | +| Create agent | `Op.CREATE_AGENT` | Agent initialization. | +| Retrieval | `Op.RETRIEVAL` | Document or data retrieval operation. | +| Embeddings | `Op.EMBEDDINGS` | Embedding generation request. | +| Text completion | `Op.TEXT_COMPLETION` | Text completion request. | + +## Framework integrations + +The SDK integrates with popular agent frameworks. The general pattern is to combine auto-instrumentation (for LLM calls) with manual `@observe` decorators (for agent-specific logic). + +### Strands Agents + +Strands supports both approaches: +- **Native OpenTelemetry**: Use `StrandsTelemetry` to automatically emit spans for agent invocations, tool executions, and LLM interactions. +- **Manual decoration**: Use `@observe` on custom functions for additional instrumentation. + +### LangGraph + +Wrap LangGraph nodes and the orchestration layer with `@observe`. Enable auto-instrumentation to capture model calls within nodes automatically. + +<!-- vale off --> +### CrewAI +<!-- vale on --> + +Use `@observe` to wrap crew execution functions. Install the appropriate provider package (for example, `[openai]`) to automatically capture LLM calls made by crew members. + +<!-- vale off --> +### OpenAI Agents SDK +<!-- vale on --> + +Enable auto-instrumentation for comprehensive LLM coverage. Supplement with `@observe` for top-level coordination logic and custom operations. + +### Amazon Bedrock + +Install `[bedrock]` to automatically capture `converse` and `invoke_model` calls. Use `@observe` for agent orchestration and custom tool implementations. + +## Next steps + +After instrumenting your application, configure OpenSearch Dashboards to view your traces. See [Viewing agent traces]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/agent-tracing/) for configuration and visualization options. diff --git a/_observing-your-data/alerting/actions.md b/_observing-your-data/alerting/actions.md index 59b2d39c..00bc8bc5 100644 --- a/_observing-your-data/alerting/actions.md +++ b/_observing-your-data/alerting/actions.md @@ -6,7 +6,7 @@ grand_parent: Alerting parent: Monitors --- -# Actions +# Alerting actions Actions send notifications when trigger conditions are met. See [Notifications]({{site.url}}{{site.baseurl}}/notifications-plugin/index/) to learn about creating notifications. If you don't want to receive notifications, don't add actions to your triggers. @@ -34,7 +34,7 @@ To add an action: 1. Choose **Create**. -After an action sends a message, the content of that message has left the purview of the [Security Analytics]({{site.url}}{{site.baseurl}}/security-analytics/index/) plugin. Securing access to the message (for example, access to the Slack channel) is your responsibility. +After an action sends a message, the content of that message is outside the control of OpenSearch. Securing access to the message (for example, access to the Slack channel) is your responsibility. #### Example message @@ -52,7 +52,7 @@ To use the `ctx.results` variable in a message, use `{% raw %}{{ctx.results.0}}{ #### Actions variables Variable | Data type | Description -:--- | :--- | : --- +:--- | :--- | :--- `ctx.trigger.actions.id` | String | The action ID. `ctx.trigger.actions.name` | String | The action name. `ctx.trigger.actions.message_template.source` | String | The message to send in the alert. diff --git a/_observing-your-data/alerting/alerting-access-control.md b/_observing-your-data/alerting/alerting-access-control.md new file mode 100644 index 00000000..1b4f69fd --- /dev/null +++ b/_observing-your-data/alerting/alerting-access-control.md @@ -0,0 +1,156 @@ +--- +layout: default +title: Alerting resource access control +nav_order: 50 +parent: Alerting +has_children: false +--- + +# Alerting resource access control + +Alerting integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for monitors and workflows. This replaces the legacy `plugins.alerting.filter_by_backend_roles` setting with a more flexible sharing system that allows resource owners to grant specific access levels to users, roles, or backend roles. + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +Alerting registers two resource types, both stored in the same configuration index. The following table describes the alerting resource configuration. + +| Resource type | System index | Onboarded version | +| :--- | :--- | :--- | +| `monitor` | `.opendistro-alerting-config` | OpenSearch 3.8 | +| `alerting-workflow` | `.opendistro-alerting-config` | OpenSearch 3.8 | + +The workflow resource type is named `alerting-workflow` in order to avoid a name collision with the `workflow` resource type registered by the Flow Framework plugin. Because both alerting types share the `.opendistro-alerting-config` index, the framework distinguishes them by the fields in each document. + +When resource-level authorization is enabled, each monitor's and workflow's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +Alerts and comments are subordinate to their monitor. They are not registered resource types, so access to them is derived from access to the monitor that produced them. A user who can access a monitor can read its alerts. Adding a comment requires monitor access at the read-write or full-access level. + +## Enable alerting resource sharing + +To enable resource sharing for alerting, add the alerting resource types to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for alerting: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "monitor" + - "alerting-workflow" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["monitor", "alerting-workflow"] + } +} +``` +{% include copy-curl.html %} + +When adding the alerting resource types to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Alerting access levels + +Alerting provides three predefined access levels that apply to both the `monitor` and `alerting-workflow` resource types. These access levels determine the specific permissions granted to users who have been granted access to a monitor or workflow resource. + +### alerting_read_only + +The `alerting_read_only` read-only access level grants users the ability to view and search shared monitors, workflows, and their alerts but not modify them. This access level includes the following permissions: + +```yaml +- 'cluster:admin/opendistro/alerting/monitor/get' +- 'cluster:admin/opendistro/alerting/monitor/search' +- 'cluster:admin/opendistro/alerting/alerts/get' +- 'cluster:admin/opensearch/alerting/workflow/get' +- 'cluster:admin/opensearch/alerting/workflow_alerts/get' +- 'cluster:admin/opensearch/alerting/findings/get' +- 'cluster:admin/opendistro/alerting/destination/get' +``` +{% include copy.html %} + +### alerting_read_write + +The `alerting_read_write` read-write access level grants users full access to monitor and workflow operations, including alerts and comments, except for sharing capabilities. This access level includes all read permissions plus write operations: + +```yaml +- 'cluster:admin/opendistro/alerting/monitor/*' +- 'cluster:admin/opensearch/alerting/workflow/*' +- 'cluster:admin/opendistro/alerting/alerts/*' +- 'cluster:admin/opensearch/alerting/workflow_alerts/*' +- 'cluster:admin/opensearch/alerting/findings/*' +- 'cluster:admin/opendistro/alerting/destination/*' +- 'cluster:admin/opensearch/alerting/comments/*' +``` +{% include copy.html %} + +### alerting_full_access + +The `alerting_full_access` full access level grants users complete control over a monitor or workflow, including owner-like permissions such as sharing the resource with other users. This access level includes all read-write permissions plus remote index and resource sharing permissions: + +```yaml +- 'cluster:admin/opendistro/alerting/monitor/*' +- 'cluster:admin/opensearch/alerting/workflow/*' +- 'cluster:admin/opendistro/alerting/alerts/*' +- 'cluster:admin/opensearch/alerting/workflow_alerts/*' +- 'cluster:admin/opensearch/alerting/findings/*' +- 'cluster:admin/opendistro/alerting/destination/*' +- 'cluster:admin/opensearch/alerting/comments/*' +- 'cluster:admin/opensearch/alerting/remote/indexes/get' +- 'cluster:admin/security/resource/share' +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Alerting GitHub repository](https://github.com/opensearch-project/alerting/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking the alerting resource types as protected, cluster administrators must run the migration API to transfer existing monitor and workflow sharing information from the legacy framework to the new resource sharing system. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Both alerting resource types are stored in the same index but keep owner information under different paths (`monitor.user` and `workflow.user`). Alerting declares these per-type paths on its resource providers, so the framework reads the owner from the correct path for each document. The request-level `username_path` and `backend_roles_path` parameters are still required and are used as a fallback. + +Use the following API call to migrate legacy alerting sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-alerting-config", + "username_path": "/monitor/user/name", + "backend_roles_path": "/monitor/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "monitor": "<select-appropriate-access-level>", + "alerting-workflow": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own monitors and workflows without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available alerting access levels: `alerting_read_only`, `alerting_read_write`, or `alerting_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance +- [Alerting security]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/) -- Built-in alerting roles and legacy backend role filtering diff --git a/_observing-your-data/alerting/api.md b/_observing-your-data/alerting/api.md index 6b95196b..f07b44e9 100644 --- a/_observing-your-data/alerting/api.md +++ b/_observing-your-data/alerting/api.md @@ -1,35 +1,21 @@ --- layout: default -title: API +title: Alerting API parent: Alerting -nav_order: 15 +nav_order: 60 redirect_from: - /monitoring-plugins/alerting/api/ --- # Alerting API -Use the Alerting API to programmatically create, update, and manage monitors and alerts. For APIs that support the composite monitor specifically, see [Managing composite monitors with the API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors/#managing-composite-monitors-with-the-api). - ---- - -<details markdown="block"> - <summary> - Table of contents - </summary> - {: .text-delta } -- TOC -{:toc} -</details> - ---- +Use the Alerting API to programmatically create, update, and manage monitors and alerts. For APIs that support the composite monitor specifically, see [Composite Monitor API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors-api/). ## Create a query-level monitor -Query-level monitors run the query and check whether or not the results should trigger an alert. Query-level monitors can only trigger one alert at a time. For more information about query-level monitors and bucket-level monitors, see [Creating monitors]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/monitors/). +Query-level monitors run the query and determine whether or not the results should trigger an alert. Query-level monitors can only trigger one alert at a time. For more information about query-level and bucket-level monitors, see [Creating monitors]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/monitors/). #### Example request - ```json POST _plugins/_alerting/monitors { @@ -92,9 +78,11 @@ POST _plugins/_alerting/monitors }] } ``` +{% include copy-curl.html %} -If you use a custom webhook for your destination and need to embed JSON in the message body, be sure to escape your quotes: +If you use a custom webhook for your destination and need to embed JSON in the message body, be sure to escape the quotation marks: + ```json { "message_template": { @@ -102,13 +90,14 @@ If you use a custom webhook for your destination and need to embed JSON in the m } } ``` +{% include copy-curl.html %} + Optionally, to specify a backend role, you can add the `rbac_roles` parameter and backend role names to the bottom of your create monitor request. +The following request creates a query-level monitor and provides two backend roles, `role1` and `role2`. The section at the bottom of the request shows the line that specifies the roles with this syntax: `"rbac_roles": ["role1", "role2"]`. To learn about using backend roles to limit access, see [(Advanced) Limit access by backend role]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/#advanced-limit-access-by-backend-role). + #### Example request - -The following request creates a query-level monitor and provides two backend roles, `role1` and `role2`. The section at the bottom of the request shows the line that specifies the roles with this syntax: `"rbac_roles": ["role1", "role2"]`. - ```json POST _plugins/_alerting/monitors { @@ -172,11 +161,16 @@ POST _plugins/_alerting/monitors "rbac_roles": ["role1", "role2"] } ``` +{% include copy-curl.html %} -To learn more about using backend roles to limit access, see [(Advanced) Limit access by backend role]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/#advanced-limit-access-by-backend-role). +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response - ```json { "_id": "vd5k2GsBlQ5JUWWFxhsP", @@ -253,13 +247,14 @@ To learn more about using backend roles to limit access, see [(Advanced) Limit a } } ``` +{% include copy-curl.html %} -If you want to specify a time zone, you can do so by including a [cron expression]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/cron/) with a time zone name in the `schedule` section of your request. +</details> -The following example creates a monitor that runs at 12:10 PM Pacific Time on the 1st day of every month. + +To specify a time zone, you can do so by including a [cron expression]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/) with a time zone name in the `schedule` section of your request. The following example creates a monitor that runs at 12:10 PM Pacific Time on the first day of each month. #### Example request - ```json { "type": "monitor", @@ -321,15 +316,18 @@ The following example creates a monitor that runs at 12:10 PM Pacific Time on th }] } ``` +{% include copy-curl.html %} -For a full list of time zone names, refer to [Wikipedia](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). The Alerting plugin uses the Java [TimeZone](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TimeZone.html) class to convert a [`ZoneId`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/ZoneId.html) to a valid time zone. + +For a full list of time zone names, see [List of `tz` database time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Alerting uses the Java [`TimeZone`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TimeZone.html) class to convert a [`ZoneId`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/ZoneId.html) to a valid time zone. --- ## Bucket-level monitors -Bucket-level monitors categorize results into buckets separated by fields. The monitor then runs your script with each bucket's results and evaluates whether to trigger an alert. For more information about bucket-level and query-level monitors, see [Creating monitors]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/monitors/). +Bucket-level monitors categorize results into buckets separated by fields. The monitor then runs the script with each bucket's results and evaluates whether to trigger an alert. For more information about bucket-level and query-level monitors, see [Creating monitors]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/monitors/). +#### Example request ```json POST _plugins/_alerting/monitors { @@ -444,7 +442,15 @@ POST _plugins/_alerting/monitors ] } ``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response ```json { @@ -584,6 +590,12 @@ POST _plugins/_alerting/monitors } } ``` +{% include copy-curl.html %} + +</details> + +--- + ## Document-level monitors Introduced 2.0 {: .label .label-purple } @@ -594,29 +606,30 @@ To learn more about per document monitors that function similarly to the documen ### Search the findings index -You can use the Alerting search API operation to search the findings index `.opensearch-alerting-finding*` for available document findings with a GET request. By default, a GET request without path parameters returns all available findings. +You can use the alerting search API operation to search the findings index `.opensearch-alerting-finding*` for available document findings with a GET request. By default, a GET request without path parameters returns all available findings. To retrieve any available findings, send a GET request without any path parameters as follows: ```json GET /_plugins/_alerting/findings/_search? ``` - +{% include copy-curl.html %} To retrieve metadata for an individual document finding entry, you can search for the finding by its `findingId` as follows: ```json GET /_plugins/_alerting/findings/_search?findingId=gKQhj8WJit3BxjGfiOXC ``` +{% include copy-curl.html %} The response returns the number of individual finding entries in the `total_findings` field. -To get more specific results in a findings search, you can use any of the optional path parameters that are defined in the following table: +To get more specific results in a findings search, you can use any of the optional path parameters defined in the following table. Path parameter | Description | Usage -:--- | :--- : :--- +:--- | :--- | :--- `findingId` | The identifier for the finding entry. | The finding ID is returned in the initial query response. -`sortString` | This field specifies which string the Alerting plugin uses to sort the findings. | The default value is `id`. +`sortString` | This field specifies which string Alerting uses to sort the findings. | The default value is `id`. `sortOrder` | The order to sort the list of findings, either ascending or descending. | Use `sortOrder=asc` to indicate ascending, or `sortOrder=desc` for descending sort order. `size` | An optional limit for the maximum number of results returned in the response. | There is no minimum or maximum values. `startIndex` | The pagination indicator. | Default is `0`. @@ -624,21 +637,18 @@ Path parameter | Description | Usage ### Create a document-level monitor -You can create a document-level monitor with a POST request that provides the monitor details in the request body. -At a minimum, you need to provide the following details: specify the queries or combinations by tag with the `inputs` field, a valid trigger condition, and provide the notification message in the `action` field. +You can create a document-level monitor with a POST request that provides the monitor details in the request body. At a minimum, you need to provide the following details: specify the queries or combinations by tag with the `inputs` field, a valid trigger condition, and provide the notification message in the `action` field. -The following table shows the syntax to use for each trigger option: +The following table provides the syntax to use for each trigger option. Trigger options | Definition | Syntax -:--- | :--- : :--- +:--- | :--- | :--- Tag | Creates alerts for documents that match a multiple query with this tag applied. If you group multiple queries by a single tag, then you can set it to trigger an alert if the results are returned by this tag name.| `query[tag=<tag-name>]` Query by name | Creates alerts for documents matched or returned by the named query. | `query[name=<query-name>]` Query by ID | Creates alerts for documents that were returned by the identified query. | `query[id=<query-id>]` + #### Example request - -The following example shows how to create a document-level monitor: - ```json POST _plugins/_alerting/monitors { @@ -722,72 +732,22 @@ POST _plugins/_alerting/monitors } ``` +{% include copy-curl.html %} + ### Limitations If you run a document-level query while the index is getting reindexed, the API response will not return the reindexed results. To get updates, wait until the reindexing process completes, then rerun the query. -{: .tip} + +--- ## Update monitor -When updating a monitor, you can optionally include `seq_no` and `primary_term` as URL parameters. If these numbers don't match the existing monitor or the monitor doesn't exist, the Alerting plugin throws an error. OpenSearch increments the version number and the sequence number automatically (see the example response). - -#### Request +When updating a monitor, you can optionally include the `if_seq_no` and `if_primary_term` query parameters, for example, `?if_seq_no=3&if_primary_term=1`. If these numbers do not match the existing monitor or the monitor does not exist, OpenSearch returns an error. OpenSearch increments the version number and the sequence number automatically (see the example response). +#### Example request ```json -PUT _plugins/_alerting/monitors/<monitor_id> -{ - "type": "monitor", - "name": "test-monitor", - "enabled": true, - "enabled_time": 1551466220455, - "schedule": { - "period": { - "interval": 1, - "unit": "MINUTES" - } - }, - "inputs": [{ - "search": { - "indices": [ - "*" - ], - "query": { - "query": { - "match_all": { - "boost": 1 - } - } - } - } - }], - "triggers": [{ - "id": "StaeOmkBC25HCRGmL_y-", - "name": "test-trigger", - "severity": "1", - "condition": { - "script": { - "source": "return true", - "lang": "painless" - } - }, - "actions": [{ - "name": "test-action", - "destination_id": "RtaaOmkBC25HCRGm0fxi", - "subject_template": { - "source": "My Message Subject", - "lang": "mustache" - }, - "message_template": { - "source": "This is my message body.", - "lang": "mustache" - } - }] - }], - "last_update_time": 1551466639295 -} - -PUT _plugins/_alerting/monitors/<monitor_id>?if_seq_no=3&if_primary_term=1 +PUT _plugins/_alerting/monitors/{monitor_id} { "type": "monitor", "name": "test-monitor", @@ -839,9 +799,16 @@ PUT _plugins/_alerting/monitors/<monitor_id>?if_seq_no=3&if_primary_term=1 "last_update_time": 1551466639295 } ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} #### Example response - ```json { "_id": "Q9aXOmkBC25HCRGmzfw-", @@ -900,20 +867,30 @@ PUT _plugins/_alerting/monitors/<monitor_id>?if_seq_no=3&if_primary_term=1 } } ``` +{% include copy-curl.html %} +</details> --- ## Get monitor -#### Request +Retrieve the details of a specific monitor using the following request. +#### Example request ``` -GET _plugins/_alerting/monitors/<monitor_id> +GET _plugins/_alerting/monitors/{monitor_id} ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} #### Example response - ```json { "_id": "Q9aXOmkBC25HCRGmzfw-", @@ -972,7 +949,9 @@ GET _plugins/_alerting/monitors/<monitor_id> } } ``` +{% include copy-curl.html %} +</details> --- @@ -980,17 +959,22 @@ GET _plugins/_alerting/monitors/<monitor_id> Returns statistics about the alerting feature. Use `_plugins/_alerting/stats` to find node IDs and metrics. Then you can drill down using those values. -#### Request - +#### Example request ```json GET _plugins/_alerting/stats -GET _plugins/_alerting/stats/<metric> -GET _plugins/_alerting/<node-id>/stats -GET _plugins/_alerting/<node-id>/stats/<metric> +GET _plugins/_alerting/stats/{metric} +GET _plugins/_alerting/{node-id}/stats +GET _plugins/_alerting/{node-id}/stats/{metric} ``` -#### Example response +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + +#### Example response ```json { "_nodes": { @@ -1161,20 +1145,30 @@ GET _plugins/_alerting/<node-id>/stats/<metric> } } ``` +{% include copy-curl.html %} +</details> --- ## Delete monitor -#### Request +Delete a monitor using the following request. +#### Example request ``` -DELETE _plugins/_alerting/monitors/<monitor_id> +DELETE _plugins/_alerting/monitors/{monitor_id} ``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response - ```json { "_index": ".opensearch-scheduled-jobs", @@ -1191,14 +1185,17 @@ DELETE _plugins/_alerting/monitors/<monitor_id> "_primary_term": 1 } ``` +{% include copy-curl.html %} +</details> --- ## Search monitors -#### Request +Query and retrieve information about existing monitors based on specific criteria, such as the monitor name, using the following request. +#### Example request ```json GET _plugins/_alerting/monitors/_search { @@ -1209,9 +1206,16 @@ GET _plugins/_alerting/monitors/_search } } ``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response - ```json { "took": 17, @@ -1288,7 +1292,9 @@ GET _plugins/_alerting/monitors/_search } } ``` +{% include copy-curl.html %} +</details> --- @@ -1296,15 +1302,20 @@ GET _plugins/_alerting/monitors/_search You can add the optional `?dryrun=true` parameter to the URL to show the results of a run without actions sending any message. - -#### Request - +#### Example request ```json -POST _plugins/_alerting/monitors/<monitor_id>/_execute +POST _plugins/_alerting/monitors/{monitor_id}/_execute ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} #### Example response - ```json { "monitor_name": "logs", @@ -1321,12 +1332,15 @@ POST _plugins/_alerting/monitors/<monitor_id>/_execute } } ``` +{% include copy-curl.html %} + +</details> --- ## Get alerts -Returns an array of all alerts. +Return an array of all alerts. #### Path parameters @@ -1345,14 +1359,20 @@ The following table lists the available path parameters. All path parameters are | `monitorId` | String | Filters by monitor ID. | `workflowIds` | String | Allows for monitoring the status of chained alerts from multiple workflows within a single dashboard. Available in OpenSearch 2.9 or later. -#### Request - +#### Example request ```json GET _plugins/_alerting/monitors/alerts ``` +{% include copy-curl.html %} -#### Response +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + +#### Example response ```json { "alerts": [ @@ -1406,25 +1426,34 @@ GET _plugins/_alerting/monitors/alerts "totalAlerts": 1 } ``` +{% include copy-curl.html %} + +</details> --- ## Acknowledge alert -[After getting your alerts](#get-alerts), you can acknowledge any number of active alerts in one call. If the alert is already in an ERROR, COMPLETED, or ACKNOWLEDGED state, it appears in the `failed` array. - - -#### Request +[After getting your alerts](#get-alerts), you can acknowledge any number of active alerts in one call. If the alert is already in an `ERROR`, `COMPLETED`, or `ACKNOWLEDGED` state, it appears in the `failed` array. +#### Example request ```json -POST _plugins/_alerting/monitors/<monitor-id>/_acknowledge/alerts +POST _plugins/_alerting/monitors/{monitor-id}/_acknowledge/alerts { "alerts": ["eQURa3gBKo1jAh6qUo49"] } ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response - ```json { "success": [ @@ -1433,145 +1462,35 @@ POST _plugins/_alerting/monitors/<monitor-id>/_acknowledge/alerts "failed": [] } ``` +{% include copy-curl.html %} + +</details> --- -## Create destination +## Destinations -#### Requests +Destinations were deprecated in OpenSearch 2.0 and replaced by notification channels. The operations that created, updated, and deleted destinations were removed in the same release, and existing destinations were migrated to notification channels automatically. To configure where alerts are delivered, use the [Notifications API]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/api/). The following read operations remain available for retrieving destinations that did not migrate. +{: .warning} +### Get destination + +Retrieve one destination using the following request. + +#### Example request ```json -POST _plugins/_alerting/destinations -{ - "name": "my-destination", - "type": "slack", - "slack": { - "url": "http://www.example.com" - } -} - -POST _plugins/_alerting/destinations -{ - "type": "custom_webhook", - "name": "my-custom-destination", - "custom_webhook": { - "path": "incomingwebhooks/123456-123456-XXXXXX", - "header_params": { - "Content-Type": "application/json" - }, - "scheme": "HTTPS", - "port": 443, - "query_params": { - "token": "R2x1UlN4ZHF8MXxxVFJpelJNVDgzdGNwXXXXXXXXX" - }, - "host": "hooks.chime.aws" - } -} - -POST _plugins/_alerting/destinations -{ - "type": "email", - "name": "my-email-destination", - "email": { - "email_account_id": "YjY7mXMBx015759_IcfW", - "recipients": [ - { - "type": "email_group", - "email_group_id": "YzY-mXMBx015759_dscs" - }, - { - "type": "email", - "email": "example@email.com" - } - ] - } -} - -// The email_account_id and email_group_id will be the document IDs of the email_account and email_group you have created. +GET _plugins/_alerting/destinations/{destination-id} ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} #### Example response - -```json -{ - "_id": "nO-yFmkB8NzS6aXjJdiI", - "_version" : 1, - "_seq_no" : 3, - "_primary_term" : 1, - "destination": { - "type": "slack", - "name": "my-destination", - "last_update_time": 1550863967624, - "slack": { - "url": "http://www.example.com" - } - } -} -``` - - ---- - -## Update destination - -When updating a destination, you can optionally include `seq_no` and `primary_term` as URL parameters. If these numbers don't match the existing destination or the destination doesn't exist, the Alerting plugin throws an error. OpenSearch increments the version number and the sequence number automatically (see the example response). - -#### Request - -```json -PUT _plugins/_alerting/destinations/<destination-id> -{ - "name": "my-updated-destination", - "type": "slack", - "slack": { - "url": "http://www.example.com" - } -} - -PUT _plugins/_alerting/destinations/<destination-id>?if_seq_no=3&if_primary_term=1 -{ - "name": "my-updated-destination", - "type": "slack", - "slack": { - "url": "http://www.example.com" - } -} -``` - -#### Example response - -```json -{ - "_id": "pe-1FmkB8NzS6aXjqvVY", - "_version" : 2, - "_seq_no" : 4, - "_primary_term" : 1, - "destination": { - "type": "slack", - "name": "my-updated-destination", - "last_update_time": 1550864289375, - "slack": { - "url": "http://www.example.com" - } - } -} -``` - - ---- - -## Get destination - -Retrieve one destination. - -#### Requests - -```json -GET _plugins/_alerting/destinations/<destination-id> -``` - -#### Example response - ```json { "totalDestinations": 1, @@ -1601,22 +1520,28 @@ GET _plugins/_alerting/destinations/<destination-id> ] } ``` +{% include copy-curl.html %} +</details> ---- +### Get destinations -## Get destinations - -Retrieve all destinations. - -#### Requests +Retrieve all destinations using the following request. +#### Example request ```json GET _plugins/_alerting/destinations ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} #### Example response - ```json { "totalDestinations": 1, @@ -1646,44 +1571,17 @@ GET _plugins/_alerting/destinations ] } ``` +{% include copy-curl.html %} +</details> ---- +### Get email account -## Delete destination - -#### Request - -``` -DELETE _plugins/_alerting/destinations/<destination-id> -``` - -#### Example response +Retrieve the details of a specific email account configured for alerting purposes using the following request. +#### Example request ```json -{ - "_index": ".opendistro-alerting-config", - "_type": "_doc", - "_id": "Zu-zFmkB8NzS6aXjLeBI", - "_version": 2, - "result": "deleted", - "forced_refresh": true, - "_shards": { - "total": 2, - "successful": 2, - "failed": 0 - }, - "_seq_no": 8, - "_primary_term": 1 -} -``` ---- - -## Create email account - -#### Request -```json -POST _plugins/_alerting/destinations/email_accounts +GET _plugins/_alerting/destinations/email_accounts/{email_account_id} { "name": "example_account", "email": "example@email.com", @@ -1692,80 +1590,15 @@ POST _plugins/_alerting/destinations/email_accounts "method": "ssl" } ``` +{% include copy-curl.html %} -#### Example response -```json -{ - "_id" : "email_account_id", - "_version" : 1, - "_seq_no" : 7, - "_primary_term" : 2, - "email_account" : { - "schema_version" : 2, - "name" : "example_account", - "email" : "example@email.com", - "host" : "smtp.email.com", - "port" : 465, - "method" : "ssl" - } -} -``` -## Update email account +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} -When updating an email account, you can optionally include `seq_no` and `primary_term` as URL parameters. If these numbers don't match the existing email account or the email account doesn't exist, the Alerting plugin throws an error. OpenSearch increments the version number and the sequence number automatically (see the example response). - -#### Request -```json -PUT _plugins/_alerting/destinations/email_accounts/<email_account_id> -{ - "name": "example_account", - "email": "example@email.com", - "host": "smtp.email.com", - "port": 465, - "method": "ssl" -} - -PUT _plugins/_alerting/destinations/email_accounts/<email_account_id>?if_seq_no=18&if_primary_term=2 -{ - "name": "example_account", - "email": "example@email.com", - "host": "smtp.email.com", - "port": 465, - "method": "ssl" -} -``` -#### Example response -```json -{ - "_id" : "email_account_id", - "_version" : 3, - "_seq_no" : 19, - "_primary_term" : 2, - "email_account" : { - "schema_version" : 2, - "name" : "example_account", - "email" : "example@email.com", - "host" : "smtp.email.com", - "port" : 465, - "method" : "ssl" - } -} -``` - -## Get email account - -#### Request -```json -GET _plugins/_alerting/destinations/email_accounts/<email_account_id> -{ - "name": "example_account", - "email": "example@email.com", - "host": "smtp.email.com", - "port": 465, - "method": "ssl" -} -``` #### Example response ```json { @@ -1783,37 +1616,15 @@ GET _plugins/_alerting/destinations/email_accounts/<email_account_id> } } ``` +{% include copy-curl.html %} -## Delete email account +</details> -#### Request -``` -DELETE _plugins/_alerting/destinations/email_accounts/<email_account_id> -``` -#### Example response +### Search email account -```json -{ - "_index" : ".opendistro-alerting-config", - "_type" : "_doc", - "_id" : "email_account_id", - "_version" : 1, - "result" : "deleted", - "forced_refresh" : true, - "_shards" : { - "total" : 2, - "successful" : 2, - "failed" : 0 - }, - "_seq_no" : 12, - "_primary_term" : 2 -} -``` - -## Search email account - -#### Request +Retrieve information about the configured email accounts used for email-based alerting using the following request. +#### Example request ```json POST _plugins/_alerting/destinations/email_accounts/_search { @@ -1829,9 +1640,16 @@ POST _plugins/_alerting/destinations/email_accounts/_search } } ``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} #### Example response - ```json { "took" : 8, @@ -1873,15 +1691,17 @@ POST _plugins/_alerting/destinations/email_accounts/_search } } ``` +{% include copy-curl.html %} ---- +</details> -## Create email group +### Get email group -#### Request +Retrieve the details of a specific email group destination using the following request, passing the ID of the email group you want to fetch. +#### Example request ```json -POST _plugins/_alerting/destinations/email_groups +GET _plugins/_alerting/destinations/email_groups/{email_group_id} { "name": "example_email_group", "emails": [{ @@ -1889,52 +1709,16 @@ POST _plugins/_alerting/destinations/email_groups }] } ``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response - -```json -{ - "_id" : "email_group_id", - "_version" : 1, - "_seq_no" : 9, - "_primary_term" : 2, - "email_group" : { - "schema_version" : 2, - "name" : "example_email_group", - "emails" : [ - { - "email" : "example@email.com" - } - ] - } -} -``` - -## Update email group - -When updating an email group, you can optionally include `seq_no` and `primary_term` as URL parameters. If these numbers don't match the existing email group or the email group doesn't exist, the Alerting plugin throws an error. OpenSearch increments the version number and the sequence number automatically (see the example response). - -#### Request - -```json -PUT _plugins/_alerting/destinations/email_groups/<email_group_id> -{ - "name": "example_email_group", - "emails": [{ - "email": "example@email.com" - }] -} - -PUT _plugins/_alerting/destinations/email_groups/<email_group_id>?if_seq_no=16&if_primary_term=2 -{ - "name": "example_email_group", - "emails": [{ - "email": "example@email.com" - }] -} -``` -#### Example response - ```json { "_id" : "email_group_id", @@ -1952,69 +1736,15 @@ PUT _plugins/_alerting/destinations/email_groups/<email_group_id>?if_seq_no=16&i } } ``` +{% include copy-curl.html %} -## Get email group +</details> -#### Request -```json -GET _plugins/_alerting/destinations/email_groups/<email_group_id> -{ - "name": "example_email_group", - "emails": [{ - "email": "example@email.com" - }] -} -``` -#### Example response +### Search email group -```json -{ - "_id" : "email_group_id", - "_version" : 4, - "_seq_no" : 17, - "_primary_term" : 2, - "email_group" : { - "schema_version" : 2, - "name" : "example_email_group", - "emails" : [ - { - "email" : "example@email.com" - } - ] - } -} -``` - -## Delete email group - -#### Request -``` -DELETE _plugins/_alerting/destinations/email_groups/<email_group_id> -``` -#### Example response - -```json -{ - "_index" : ".opendistro-alerting-config", - "_type" : "_doc", - "_id" : "email_group_id", - "_version" : 1, - "result" : "deleted", - "forced_refresh" : true, - "_shards" : { - "total" : 2, - "successful" : 2, - "failed" : 0 - }, - "_seq_no" : 11, - "_primary_term" : 2 -} -``` - -## Search email group - -#### Request +Query and retrieve information about existing email groups used for alerting purposes, enabling you to filter and sort the results based on various criteria. An example is shown in the following request. +#### Example request ```json POST _plugins/_alerting/destinations/email_groups/_search { @@ -2030,9 +1760,16 @@ POST _plugins/_alerting/destinations/email_groups/_search } } ``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + #### Example response - ```json { "took" : 7, @@ -2075,4 +1812,195 @@ POST _plugins/_alerting/destinations/email_groups/_search } } ``` ---- +{% include copy-curl.html %} + +</details> + +## Create comment + +Add comments to a specific alert, providing additional context or notes related to that alert, using the following request. + +#### Example request +```json +POST _plugins/_alerting/comments/{alert-id} +{ + "content": "sample comment" +} +``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + +#### Example response +```json +{ + "_id": "0U6aBJABVWc3FrmWer9s", + "_seq_no": 7, + "_primary_term": 2, + "comment": { + "entity_id": "vCZkA5ABWTh3kzuBEL_9", + "entity_type": "alert", + "content": "sample comment", + "created_time": 1718064151148, + "last_updated_time": null, + "user": "admin" + } +} +``` +{% include copy-curl.html %} + +</details> + +## Update comment + +Modify the content of a previously added comment associated with an alert using the following request. + +#### Example request + +```json +PUT _plugins/_alerting/comments/{comment-id} +{ + "content": "sample updated comment" +} +``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + +#### Example response +```json +{ + "_id": "0U6aBJABVWc3FrmWer9s", + "_seq_no": 8, + "_primary_term": 3, + "comment": { + "entity_id": "vCZkA5ABWTh3kzuBEL_9", + "entity_type": "alert", + "content": "sample updated comment", + "created_time": 1718064151148, + "last_updated_time": 1718064745485, + "user": "admin" + } +} +``` +{% include copy-curl.html %} + +</details> + +## Search comment + +Query and retrieve existing comments associated with alerts using the following request. + +#### Example request +```json +GET _plugins/_alerting/comments/_search +{ + "query": { + "match_all" : {} + } +} +``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + +#### Example response +```json +{ + "took": 14, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".opensearch-alerting-comments-history-2024.06.10-1", + "_id": "xE5tBJABVWc3FrmWRL5i", + "_version": 1, + "_seq_no": 3, + "_primary_term": 2, + "_score": 1, + "_source": { + "entity_id": "vCZkA5ABWTh3kzuBEL_9", + "entity_type": "alert", + "content": "a different sample comment", + "created_time": 1718061188191, + "last_updated_time": null, + "user": "admin" + } + }, + { + "_index": ".opensearch-alerting-comments-history-2024.06.10-1", + "_id": "0U6aBJABVWc3FrmWer9s", + "_version": 3, + "_seq_no": 9, + "_primary_term": 3, + "_score": 1, + "_source": { + "entity_id": "vCZkA5ABWTh3kzuBEL_9", + "entity_type": "alert", + "content": "sample updated comment", + "created_time": 1718064151148, + "last_updated_time": 1718064745485, + "user": "admin" + } + } + ] + } +} +``` +{% include copy-curl.html %} + +</details> + +## Delete comment + +Remove a specific comment associated with an alert using the following request. + +#### Example request +```json +DELETE _plugins/_alerting/comments/{comment-id} +``` +{% include copy-curl.html %} + + +<details markdown="block"> + <summary> + Select to expand example response + </summary> + {: .text-delta} + +#### Example response +```json +{ + "_id": "0U6aBJABVWc3FrmWer9s" +} +``` +{% include copy-curl.html %} + +</details> + diff --git a/_observing-your-data/alerting/comments.md b/_observing-your-data/alerting/comments.md new file mode 100644 index 00000000..482f68ad --- /dev/null +++ b/_observing-your-data/alerting/comments.md @@ -0,0 +1,23 @@ +--- +layout: default +title: Adding comments +nav_order: 30 +parent: Alerting +has_children: false +redirect_from: + - /monitoring-plugins/alerting/comments/ +--- + +# Adding alerting comments + +When an alert is generated, add comments to share information about its root cause and facilitate resolution. Comments are enabled by setting `plugins.alerting.comments_enabled` to `true` using the [`cluster/settings` API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/settings/). + +Comments can be accessed through the alerts table view by selecting the comment icon within an alert's row. From there, comments can be added, edited, or deleted. An Alerting Comments API is also available for programmatic comment management. For more information, see [Alerting API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/). + +## Viewing comment authors + +If the Security plugin is installed, then the comment's author is displayed. Otherwise, `Unknown` is displayed. + +## Assigning permissions + +Comment permissions are determined by the backend roles associated with the alert. These backend roles are inherited from the monitor that generated the alert. For more information about how to limit access based on backend roles, see [Limit access by backend role]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/#advanced-limit-access-by-backend-role). diff --git a/_observing-your-data/alerting/composite-monitors-api.md b/_observing-your-data/alerting/composite-monitors-api.md new file mode 100644 index 00000000..a4b87320 --- /dev/null +++ b/_observing-your-data/alerting/composite-monitors-api.md @@ -0,0 +1,567 @@ +--- +layout: default +title: Composite Monitor API +parent: Alerting +nav_order: 65 +--- + +# Composite Monitor API + +Use the Composite Monitor API to create and manage [composite monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors/) and their chained alerts. In the API, a composite monitor is called a _workflow_, and its ID is the workflow ID. + +## Create Composite Monitor + +Creates a composite monitor. + +### Endpoints + +```json +POST _plugins/_alerting/workflows +``` + +### Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required | Description +:--- | :--- | :--- | :--- +`name` | String | Required | The name of the composite monitor. +`workflow_type` | String | Required | Set to `composite`. +`schedule` | Object | Required | How often the composite monitor runs. See [The `schedule` object](#the-schedule-object). +`inputs` | Array | Required | The delegate monitors and the order in which they run. See [The `inputs` array](#the-inputs-array). +`triggers` | Array | Optional | The triggers that generate chained alerts. See [The `triggers` array](#the-triggers-array). +`enabled` | Boolean | Optional | Whether the composite monitor is enabled. Default is `true`. + +### The `schedule` object + +The `schedule` object contains the `period` object, which contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`interval` | Integer | The number of time units between runs. +`unit` | String | The time unit for the interval. Valid values are `MINUTES`, `HOURS`, and `DAYS`. + +### The `inputs` array + +The `inputs` array contains one object with the `composite_input.sequence.delegates` array. Each object in the `delegates` array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`order` | Integer | The position of the delegate monitor in the sequence. Delegate monitors run in ascending order. +`monitor_id` | String | The ID of the delegate monitor. A composite monitor supports per query, per bucket, and per document monitors as delegate monitors. + +### The `triggers` array + +Each object in the `triggers` array contains a `chained_alert_trigger` object, which contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`id` | String | The trigger ID. +`name` | String | The trigger name. +`severity` | String | The alert severity, from `1` (highest) to `5` (lowest). +`condition` | Object | The trigger condition. Contains a `script` object, in which `source` is the Painless condition that generates a chained alert and `lang` is `painless`. See [Defining chained alert trigger conditions](#defining-chained-alert-trigger-conditions). +`actions` | Array | The actions to perform when the trigger condition is met. For the action fields, see [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/). + +### Defining chained alert trigger conditions + +A chained alert trigger condition refers to delegate monitors using `monitor[id=<monitor-id>]`, which is `true` when the delegate monitor generates an alert in the current run. You can combine the references using the following operators: + +- `&&` (AND) +- `||` (OR) +- `!` (NOT) +- `()` (precedence) + +For example: + +- `monitor[id=1] && monitor[id=2]` generates a chained alert when both monitor 1 and monitor 2 generate an alert. +- `monitor[id=1] || !monitor[id=2]` generates a chained alert when monitor 1 generates an alert or monitor 2 doesn't generate an alert. +- `monitor[id=1] && (monitor[id=2] || monitor[id=3])` generates a chained alert when monitor 1 generates an alert and either monitor 2 or monitor 3 generates an alert. + +The order of the monitor IDs in a condition doesn't affect the order in which the delegate monitors run. The run order is set by the `order` field in the `delegates` array. +{: .note } + +### Example request + +The following request creates a composite monitor with two delegate monitors and two triggers. The `Both monitors` trigger generates a chained alert when both delegate monitors generate an alert. The `Either monitor` trigger generates a chained alert when at least one of them does: + +```json +POST _plugins/_alerting/workflows +{ + "name": "Traffic and errors", + "workflow_type": "composite", + "enabled": true, + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "inputs": [ + { + "composite_input": { + "sequence": { + "delegates": [ + { + "order": 1, + "monitor_id": "grsbCIcBvEHfkjWFeCqb" + }, + { + "order": 2, + "monitor_id": "agasbCIcBvEHfkjWFeCqa" + } + ] + } + } + } + ], + "triggers": [ + { + "chained_alert_trigger": { + "id": "m1ANDm2", + "name": "Both monitors", + "severity": "1", + "condition": { + "script": { + "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] && monitor[id=agasbCIcBvEHfkjWFeCqa])", + "lang": "painless" + } + }, + "actions": [] + } + }, + { + "chained_alert_trigger": { + "id": "m1ORm2", + "name": "Either monitor", + "severity": "2", + "condition": { + "script": { + "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] || monitor[id=agasbCIcBvEHfkjWFeCqa])", + "lang": "painless" + } + }, + "actions": [] + } + } + ] +} +``` +{% include copy-curl.html %} + +## Get Composite Monitor + +Returns the configuration of a composite monitor. + +### Endpoints + +```json +GET _plugins/_alerting/workflows/{workflow_id} +``` + +### Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`workflow_id` | String | The workflow ID of the composite monitor. Required. + +### Example request + +```json +GET _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_ +``` +{% include copy-curl.html %} + +## Update Composite Monitor + +Replaces the configuration of a composite monitor. The request body fields are the same as for [Create Composite Monitor](#create-composite-monitor). + +### Endpoints + +```json +PUT _plugins/_alerting/workflows/{workflow_id} +``` + +### Example request + +The following request changes the composite monitor to run every 5 minutes and keeps only the `Both monitors` trigger: + +```json +PUT _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_ +{ + "name": "Traffic and errors", + "workflow_type": "composite", + "enabled": true, + "schedule": { + "period": { + "interval": 5, + "unit": "MINUTES" + } + }, + "inputs": [ + { + "composite_input": { + "sequence": { + "delegates": [ + { + "order": 1, + "monitor_id": "grsbCIcBvEHfkjWFeCqb" + }, + { + "order": 2, + "monitor_id": "agasbCIcBvEHfkjWFeCqa" + } + ] + } + } + } + ], + "triggers": [ + { + "chained_alert_trigger": { + "id": "m1ANDm2", + "name": "Both monitors", + "severity": "1", + "condition": { + "script": { + "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] && monitor[id=agasbCIcBvEHfkjWFeCqa])", + "lang": "painless" + } + }, + "actions": [] + } + } + ] +} +``` +{% include copy-curl.html %} + +## Delete Composite Monitor + +Deletes a composite monitor. The delegate monitors are not deleted. + +### Endpoints + +```json +DELETE _plugins/_alerting/workflows/{workflow_id} +``` + +### Example request + +```json +DELETE _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_ +``` +{% include copy-curl.html %} + +## Execute Composite Monitor + +Runs a composite monitor immediately and returns the trigger results. + +### Endpoints + +```json +POST _plugins/_alerting/workflows/{workflow_id}/_execute +``` + +### Example request + +```json +POST _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_/_execute +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "execution_id": "I0GXeIgBYKBG2nHoiHCL_2023-06-01T20:18:48.511884_a9c1d055-9b70-49c2-b32a-716cff1f562e", + "workflow_name": "scale_up", + "workflow_id": "I0GXeIgBYKBG2nHoiHCL", + "trigger_results": { + "m1ANDm2": { + "name": "jnkjn", + "triggered": true, + "action_results": {}, + "error": null + }, + "m1ORm2": { + "name": "jnkjn", + "triggered": true, + "action_results": {}, + "error": null + } + }, + "monitor_run_results": [{ + "monitor_name": "test triggers", + "period_start": 1685650668501, + "period_end": 1685650728501, + "error": null, + "input_results": { + "results": [{ + "bhjh": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ], + "nkjkj": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ], + "jknkjn": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ] + }], + "error": null + }, + "trigger_results": { + "NC3Dd4cBCDCIfBYtViLI": { + "name": "njkkj", + "triggeredDocs": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ], + "action_results": {}, + "error": null + } + } + }, + { + "monitor_name": "test triggers 2", + "period_start": 1685650668501, + "period_end": 1685650728501, + "error": null, + "input_results": { + "results": [{ + "bhjh": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ], + "nkjkj": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ], + "jknkjn": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ] + }], + "error": null + }, + "trigger_results": { + "NC3Dd4cBCDCIfBYtViLI": { + "name": "njkkj", + "triggeredDocs": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ], + "action_results": {}, + "error": null + } + } + } + ], + "execution_start_time": "2023-06-01T20:18:48.511874Z", + "execution_end_time": "2023-06-01T20:18:53.682405Z", + "error": null +} +``` + +## Get Chained Alerts + +Returns the chained alerts generated by composite monitors. + +### Endpoints + +```json +GET _plugins/_alerting/workflows/alerts +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`workflowIds` | String | A comma-separated list of workflow IDs. Returns only the alerts generated by these composite monitors. +`getAssociatedAlerts` | Boolean | When `true`, the response also contains the audit alerts generated by the delegate monitors. Default is `false`. + +### Example request + +```json +GET _plugins/_alerting/workflows/alerts?workflowIds=SX9egKEBrJhc2kcbnbU_&getAssociatedAlerts=true +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "alerts": [ + { + "id": "PbQoZokBfd2ci_FqMGi6", + "version": 1, + "monitor_id": "", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "scale_up", + "associated_alert_ids": [ + "4e8256c5-529a-484c-bf7b-d3980c03e9a4", + "513a8cb3-44bc-4eee-8aac-131be10b399e" + ], + "schema_version": -1, + "monitor_version": -1, + "monitor_name": "", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "m1ANDm2", + "trigger_name": "jnkjn", + "finding_ids": [], + "related_doc_ids": [], + "state": "ACTIVE", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636057269, + "last_notification_time": 1689636057270, + "end_time": null, + "acknowledged_time": null + }, + { + "id": "PrQoZokBfd2ci_FqMGj8", + "version": 1, + "monitor_id": "", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "scale_up", + "associated_alert_ids": [ + "4e8256c5-529a-484c-bf7b-d3980c03e9a4", + "513a8cb3-44bc-4eee-8aac-131be10b399e" + ], + "schema_version": -1, + "monitor_version": -1, + "monitor_name": "", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "m1ORm2", + "trigger_name": "jnkjn", + "finding_ids": [], + "related_doc_ids": [], + "state": "ACTIVE", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636057340, + "last_notification_time": 1689636057340, + "end_time": null, + "acknowledged_time": null + } + ], + "associatedAlerts": [ + { + "id": "4e8256c5-529a-484c-bf7b-d3980c03e9a4", + "version": -1, + "monitor_id": "DrQoZokBfd2ci_FqCWh8", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "", + "associated_alert_ids": [], + "schema_version": 5, + "monitor_version": 1, + "monitor_name": "test triggers", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "NC3Dd4cBCDCIfBYtViLI", + "trigger_name": "njkkj", + "finding_ids": [ + "277afca7-d5aa-46ed-8023-5449ece65d36" + ], + "related_doc_ids": [ + "H7QoZokBfd2ci_FqFmii|test1" + ], + "state": "AUDIT", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636056410, + "last_notification_time": 1689636056410, + "end_time": null, + "acknowledged_time": null + }, + { + "id": "513a8cb3-44bc-4eee-8aac-131be10b399e", + "version": -1, + "monitor_id": "EbQoZokBfd2ci_FqCmiR", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "", + "associated_alert_ids": [], + "schema_version": 5, + "monitor_version": 1, + "monitor_name": "test triggers 2", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "NC3Dd4cBCDCIfBYtViLI", + "trigger_name": "njkkj", + "finding_ids": [ + "6d185585-a077-4dde-8e43-b4c01b9f3102" + ], + "related_doc_ids": [ + "ILQoZokBfd2ci_FqGmhb|test" + ], + "state": "AUDIT", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636056943, + "last_notification_time": 1689636056943, + "end_time": null, + "acknowledged_time": null + } + ], + "totalAlerts": 2 +} +``` + +### Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`alerts` | Array | The chained alerts generated by the composite monitors. +`associatedAlerts` | Array | The audit alerts generated by the delegate monitors. Returned only when `getAssociatedAlerts` is `true`. +`totalAlerts` | Integer | The total number of chained alerts. + +## Acknowledge Chained Alerts + +Acknowledges one or more active chained alerts. Alerts that are already in the `ERROR`, `COMPLETED`, or `ACKNOWLEDGED` state are returned in the `failed` array. + +### Endpoints + +```json +POST _plugins/_alerting/workflows/{workflow_id}/_acknowledge/alerts +``` + +### Request body fields + +The following table lists the available request body fields. + +Field | Data type | Required | Description +:--- | :--- | :--- | :--- +`alerts` | Array of strings | Required | The IDs of the alerts to acknowledge. To get alert IDs, use [Get Chained Alerts](#get-chained-alerts). + +### Example request + +```json +POST _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_/_acknowledge/alerts +{ + "alerts": ["VH9egKEBrJhc2kcbnrU5"] +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "success": ["VH9egKEBrJhc2kcbnrU5"], + "failed": [] +} +``` diff --git a/_observing-your-data/alerting/composite-monitors.md b/_observing-your-data/alerting/composite-monitors.md index eb26dcc1..be8a9378 100644 --- a/_observing-your-data/alerting/composite-monitors.md +++ b/_observing-your-data/alerting/composite-monitors.md @@ -5,36 +5,15 @@ nav_order: 25 parent: Monitors grand_parent: Alerting has_children: false -redirect_from: - - /observing-your-data/alerting/composite-monitors/ --- # Composite monitors ---- - -<details markdown="block"> - <summary> - Table of contents - </summary> - {: .text-delta } -- TOC -{:toc} -</details> - ---- - ## About composite monitors -Basic [monitor types]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/#monitor-types) for the Alerting plugin are designed to define a single trigger type. For example, a per document monitor can trigger an alert based on a query's match with documents, while a per bucket monitor can trigger an alert based on queries aimed at aggregated values in a data source. The composite monitor combines multiple monitors in a sequence to analyze a data source based on multiple criteria and then uses their individual alerts to generate a single chained alert. This allows you to derive more granular information about a data source, and it doesn't require you to manually coordinate the scheduling of the separate monitors. - -Composite monitors remove the limitations of basic monitors in the following ways: - -* Composite monitors give you the ability to create complex queries through a combination of triggers generated by multiple types of monitors. -* They have the capacity to define a pipeline of rules and queries that are run as a single execution. -* They deliver a single alert to users instead of multiple alerts from the individual monitors in their workflows. -* They provide a more complete view of a given data source by running multiple monitors and multiple types of monitors in sequence, creating more focused results and reducing noise in the results. +Basic [monitor types]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/#monitor-types) in Alerting are designed to define a single trigger type. For example, a per document monitor can trigger an alert based on a query's match with documents, while a per bucket monitor can trigger an alert based on queries aimed at aggregated values in a data source. The composite monitor combines multiple monitors in a sequence to analyze a data source based on multiple criteria and then uses their individual alerts to generate a single chained alert. This allows you to derive more granular information about a data source, and it doesn't require you to manually coordinate the scheduling of the separate monitors. +Because the composite monitor sends a single chained alert instead of an alert from each delegate monitor, it reduces the number of alerts that users receive. The delegate monitors run as a single execution in the order that you define, so you don't need to coordinate their schedules. ## Key terms @@ -61,507 +40,9 @@ You create composite monitors by combining individual monitors in a workflow tha In this simple example, the first monitor could be a per document monitor configured to analyze a data source using three different queries, while the second monitor could be a per bucket monitor that aggregates data by client IP. By combining the requirements of each delegate monitor, the composite monitor focuses the criteria that decide whether an alert is generated or not. This can improve the meaningfulness of the alert while removing extraneous alerts that provide no deterministic value. -## Managing composite monitors with the API +## Managing composite monitors using the API -You can manage composite monitors using the OpenSearch REST API or [OpenSearch Dashboards](#creating-composite-monitors-in-opensearch-dashboards). This section describes API functionality for composite monitors. - -### Create composite monitor - -This API allows you to create a composite monitor. - -```json -POST _plugins/_alerting/workflows -``` -{% include copy-curl.html %} - -#### Request fields - -| Field | Type | Description | -| :--- | :--- | :--- | -| `schedule` | Object | The schedule that determines how often the execution runs. | -| `schedule.period.interval` | Numeral | Accepts a numerical value to set how often the execution runs. | -| `schedule.period.unit` | Object | The time unit of measure for the interval: `SECONDS`, `MINUTES`, `HOURS`, `DAYS`. | -| `inputs` | Object | Accepts inputs to define the delegate monitors, which specify both the delegate monitors and their order in the execution's sequence. | -| `inputs.composite_input.sequence.delegates` | Object | The settings for the individual monitors that underlie the composite monitor. | -| `inputs.composite_input.sequence.delegates.order` | Number | Designates the order in which the monitor runs in the execution. | -| `inputs.composite_input.sequence.delegates.monitor_id` | String | The unique identifier for the monitor. | -| `enabled_time` | Number | The time at which the monitor was enabled. Expressed in epoch time. | -| `enabled` | Boolean | The setting that determines whether the composite monitor is enabled or not. Setting it to `true` enables the composite monitor. Default is `true`. | -| `workflow_type` | String | Set to `composite` for composite monitor. | -| `triggers` | Object | Details for the individual alert triggers. | -| `triggers.chained_alert_trigger` | Object | Details for each individual alert trigger. Each monitor's alert trigger will require settings for its configuration. | -| `triggers.chained_alert_trigger.id` | String | The unique identifier for the alert trigger. | -| `triggers.chained_alert_trigger.name` | String | The name of the alert trigger. | -| `triggers.chained_alert_trigger.severity` | Number | The alert severity. 1 = highest; 2 = high; 3 = medium; 4 = low; 5 = lowest. | -| `triggers.chained_alert_trigger.condition.script` | Object | The script details that determine the conditions for triggering an alert. | -| `triggers.chained_alert_trigger.condition.script.source` | String | The Painless script that defines the conditions for triggering an alert. | -| `triggers.chained_alert_trigger.condition.script.lang` | String | Enter `painless` for the Painless scripting language. | -| `actions` | Object | Provides fields for configuring an alert notification. | - -#### Example request - -```json -POST _plugins/_alerting/workflows -{ - "last_update_time": 1679468231835, - "owner": "alerting", - "type": "workflow", - "schedule": { - "period": { - "interval": 1, - "unit": "MINUTES" - } - }, - "inputs": [{ - "composite_input": { - "sequence": { - "delegates": [{ - "order": 1, - "monitor_id": "grsbCIcBvEHfkjWFeCqb" - }, - { - "order": 2, - "monitor_id": "agasbCIcBvEHfkjWFeCqa" - } - ] - } - } - }], - "enabled_time": 1679468231835, - "enabled": true, - "workflow_type": "composite", - "name": "scale_up", - "triggers": [{ - "chained_alert_trigger": { - "id": "m1ANDm2", - "name": "jnkjn", - "severity": "1", - "condition": { - "script": { - "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] && monitor[id=agasbCIcBvEHfkjWFeCqa])", - "lang": "painless" - } - } - }, - "actions": [{ - "name": "test-action", - "destination_id": "ld7912sBlQ5JUWWFThoW", - "message_template": { - "source": "This is my message body." - }, - "throttle_enabled": true, - "throttle": { - "value": 27, - "unit": "MINUTES" - }, - "subject_template": { - "source": "TheSubject" - } - }] - }, - { - "chained_alert_trigger": { - "id": "m1ORm2", - "name": "jnkjn", - "severity": "1", - "condition": { - "script": { - "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] || monitor[id=agasbCIcBvEHfkjWFeCqa])", - "lang": "painless" - } - } - } - } - ] -} -``` -{% include copy-curl.html %} - -#### Using Painless scripting language to define chained alert trigger conditions - -Composite monitor configurations employ the Painless scripting language to define the conditions for generating chained alerts. Conditions are applied for each execution of the composite monitor. You define the alert trigger conditions in the `triggers.chained_alert_triggers.condition.script.source` field of the request. Using Painless syntax, you can apply logic to links between monitors with the basic Boolean operators AND, OR, NOT, and precedence: - -* AND = `&&` -* OR = `||` -* NOT = `!` -* Precedence = `()` - -See the following examples to understand how each is used in the monitor definition. - -* **Example 1** - - `monitor[id=1] && monitor[id=2]` - - The following conditions for delegate monitors will trigger the composite monitor to produce a chained alert when both monitor #1 AND monitor #2 generate an alert. - -* **Example 2** - - `monitor[id=1] || !monitor[id=2]` - - The following conditions will trigger the composite monitor to produce a chained alert when either monitor #1 generates an alert OR monitor #2 does NOT generate an alert. - -* **Example 3** - - `monitor[id=1] && (monitor[id=2] || monitor[id=3])` - - The following conditions will trigger the composite monitor to produce a chained alert when monitor #1 generates an alert AND monitor #2 OR monitor #3 generates an alert. - -The order of monitor IDs in the Painless script does not define the execution sequence for the monitors. The monitor execution sequence is defined in the `inputs.composite_input.sequence.delegates.order` field in the request. -{: .note } - - -### Get Composite Monitor - -This API retrieves information on the specified monitor. - -```json -GET _plugins/_alerting/workflows/<workflow_id> -``` -{% include copy-curl.html %} - -#### Path parameters - -| Field | Type | Description | -| :--- | :--- | :--- | -| `workflow_id` | String | The composite monitor's [workflow ID](#key-terms). | - - -### Update Composite Monitor - -This API updates the composite monitor's details. See [Create Composite Monitor](#create-composite-monitor) for descriptions of the request fields. - -#### Example request - -```json -PUT _plugins/_alerting/workflows/<workflow_id> -{ - "owner": "security_analytics", - "type": "workflow", - "schedule": { - "period": { - "interval": 1, - "unit": "MINUTES" - } - }, - "inputs": [ - { - "composite_input": { - "sequence": { - "delegates": [ - { - "order": 1, - "monitor_id": "grsbCIcBvEHfkjWFeCqb" - }, - { - "order": 2, - "monitor_id": "agasbCIcBvEHfkjWFeCqa" - } - ] - } - } - } - ], - "enabled_time": 1679468231835, - "enabled": true, - "workflow_type": "composite", - "name": "NTxdwApKbv" -} -``` -{% include copy-curl.html %} - - -### Delete Composite Monitor - -```json -DELETE _plugins/_alerting/workflows/<workflow_id> -``` -{% include copy-curl.html %} - - -### Execute Composite Monitor - -This API begins the workflow execution for a composite monitor: - -```json -POST /_plugins/_alerting/workflows/<workflow_id>/_execute -``` -{% include copy-curl.html %} - -#### Example response - -```json -{ - "execution_id": "I0GXeIgBYKBG2nHoiHCL_2023-06-01T20:18:48.511884_a9c1d055-9b70-49c2-b32a-716cff1f562e", - "workflow_name": "scale_up", - "workflow_id": "I0GXeIgBYKBG2nHoiHCL", - "trigger_results": { - "m1ANDm2": { - "name": "jnkjn", - "triggered": true, - "action_results": {}, - "error": null - }, - "m1ORm2": { - "name": "jnkjn", - "triggered": true, - "action_results": {}, - "error": null - } - }, - "monitor_run_results": [{ - "monitor_name": "test triggers", - "period_start": 1685650668501, - "period_end": 1685650728501, - "error": null, - "input_results": { - "results": [{ - "bhjh": [ - "OkGceIgBYKBG2nHoyHAn|test1", - "O0GceIgBYKBG2nHozHCW|test1" - ], - "nkjkj": [ - "OkGceIgBYKBG2nHoyHAn|test1", - "O0GceIgBYKBG2nHozHCW|test1" - ], - "jknkjn": [ - "OkGceIgBYKBG2nHoyHAn|test1", - "O0GceIgBYKBG2nHozHCW|test1" - ] - }], - "error": null - }, - "trigger_results": { - "NC3Dd4cBCDCIfBYtViLI": { - "name": "njkkj", - "triggeredDocs": [ - "OkGceIgBYKBG2nHoyHAn|test1", - "O0GceIgBYKBG2nHozHCW|test1" - ], - "action_results": {}, - "error": null - } - } - }, - { - "monitor_name": "test triggers 2", - "period_start": 1685650668501, - "period_end": 1685650728501, - "error": null, - "input_results": { - "results": [{ - "bhjh": [ - "PEGceIgBYKBG2nHo1HCw|test", - "PUGceIgBYKBG2nHo3HA8|test" - ], - "nkjkj": [ - "PEGceIgBYKBG2nHo1HCw|test", - "PUGceIgBYKBG2nHo3HA8|test" - ], - "jknkjn": [ - "PEGceIgBYKBG2nHo1HCw|test", - "PUGceIgBYKBG2nHo3HA8|test" - ] - }], - "error": null - }, - "trigger_results": { - "NC3Dd4cBCDCIfBYtViLI": { - "name": "njkkj", - "triggeredDocs": [ - "PEGceIgBYKBG2nHo1HCw|test", - "PUGceIgBYKBG2nHo3HA8|test" - ], - "action_results": {}, - "error": null - } - } - } - ], - "execution_start_time": "2023-06-01T20:18:48.511874Z", - "execution_end_time": "2023-06-01T20:18:53.682405Z", - "error": null -} -``` - - -### Get chained alerts - -This API returns an array of chained alerts generated in composite monitor workflows: - -```json -GET /_plugins/_alerting/workflows/alerts?workflowIds=<workflow_ids>&getAssociatedAlerts=true -``` - -#### Query parameters - -| Field | Type | Required | Description | -| :--- | :--- | :--- | :--- | -| `workflowIds` | Array | No | When this parameter is used, it returns alerts created by the specified workflows. | -| `getAssociatedAlerts` | Boolean | No | When `true`, the response returns audit alerts that the composite monitor used to create a chained alert. Default is `false`. | - - -#### Example response - -```json -{ - "alerts": [ - { - "id": "PbQoZokBfd2ci_FqMGi6", - "version": 1, - "monitor_id": "", - "workflow_id": "G7QoZokBfd2ci_FqD2iZ", - "workflow_name": "scale_up", - "associated_alert_ids": [ - "4e8256c5-529a-484c-bf7b-d3980c03e9a4", - "513a8cb3-44bc-4eee-8aac-131be10b399e" - ], - "schema_version": -1, - "monitor_version": -1, - "monitor_name": "", - "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", - "trigger_id": "m1ANDm2", - "trigger_name": "jnkjn", - "finding_ids": [], - "related_doc_ids": [], - "state": "ACTIVE", - "error_message": null, - "alert_history": [], - "severity": "1", - "action_execution_results": [], - "start_time": 1689636057269, - "last_notification_time": 1689636057270, - "end_time": null, - "acknowledged_time": null - }, - { - "id": "PrQoZokBfd2ci_FqMGj8", - "version": 1, - "monitor_id": "", - "workflow_id": "G7QoZokBfd2ci_FqD2iZ", - "workflow_name": "scale_up", - "associated_alert_ids": [ - "4e8256c5-529a-484c-bf7b-d3980c03e9a4", - "513a8cb3-44bc-4eee-8aac-131be10b399e" - ], - "schema_version": -1, - "monitor_version": -1, - "monitor_name": "", - "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", - "trigger_id": "m1ORm2", - "trigger_name": "jnkjn", - "finding_ids": [], - "related_doc_ids": [], - "state": "ACTIVE", - "error_message": null, - "alert_history": [], - "severity": "1", - "action_execution_results": [], - "start_time": 1689636057340, - "last_notification_time": 1689636057340, - "end_time": null, - "acknowledged_time": null - } - ], - "associatedAlerts": [ - { - "id": "4e8256c5-529a-484c-bf7b-d3980c03e9a4", - "version": -1, - "monitor_id": "DrQoZokBfd2ci_FqCWh8", - "workflow_id": "G7QoZokBfd2ci_FqD2iZ", - "workflow_name": "", - "associated_alert_ids": [], - "schema_version": 5, - "monitor_version": 1, - "monitor_name": "test triggers", - "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", - "trigger_id": "NC3Dd4cBCDCIfBYtViLI", - "trigger_name": "njkkj", - "finding_ids": [ - "277afca7-d5aa-46ed-8023-5449ece65d36" - ], - "related_doc_ids": [ - "H7QoZokBfd2ci_FqFmii|test1" - ], - "state": "AUDIT", - "error_message": null, - "alert_history": [], - "severity": "1", - "action_execution_results": [], - "start_time": 1689636056410, - "last_notification_time": 1689636056410, - "end_time": null, - "acknowledged_time": null - }, - { - "id": "513a8cb3-44bc-4eee-8aac-131be10b399e", - "version": -1, - "monitor_id": "EbQoZokBfd2ci_FqCmiR", - "workflow_id": "G7QoZokBfd2ci_FqD2iZ", - "workflow_name": "", - "associated_alert_ids": [], - "schema_version": 5, - "monitor_version": 1, - "monitor_name": "test triggers 2", - "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", - "trigger_id": "NC3Dd4cBCDCIfBYtViLI", - "trigger_name": "njkkj", - "finding_ids": [ - "6d185585-a077-4dde-8e43-b4c01b9f3102" - ], - "related_doc_ids": [ - "ILQoZokBfd2ci_FqGmhb|test" - ], - "state": "AUDIT", - "error_message": null, - "alert_history": [], - "severity": "1", - "action_execution_results": [], - "start_time": 1689636056943, - "last_notification_time": 1689636056943, - "end_time": null, - "acknowledged_time": null - } - ], - "totalAlerts": 2 -} -``` - -#### Request fields - -| Field | Type | Description | -| :--- | :--- | :--- | -| `alerts` | Array | A list of chained alerts generated by the composite monitor. | -| `associatedAlerts` | Array | A list of audit alerts generated by the delegate monitors. | - - -### Acknowledge chained alerts - -[After getting your alerts](#get-chained-alerts), you can acknowledge multiple active alerts in one call. If the alert is already in an ERROR, COMPLETED, or ACKNOWLEDGED state, it appears in the failed array. - -```json -POST _plugins/_alerting/workflows/<workflow_id>/_acknowledge/alerts -{ - "alerts": ["eQURa3gBKo1jAh6qUo49"] -} -``` -{% include copy-curl.html %} - -#### Request fields - -| Field | Type | Description | -| :--- | :--- | :--- | -| `alerts` | Array | A list of alerts by ID. The results include alerts that are acknowledged by the system as well as alerts not recognized by the system. | - -#### Example response - -```json -{ - "success": [ - "eQURa3gBKo1jAh6qUo49" - ], - "failed": [] -} -``` +To create and manage composite monitors and chained alerts using the REST API, see [Composite Monitor API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors-api/). ## Creating composite monitors in OpenSearch Dashboards @@ -571,7 +52,7 @@ Begin by navigating to the **Create monitor** page in OpenSearch Dashboards: **A To use the visual editor for defining a workflow and trigger conditions, select the **Visual editor** radio button in the **Monitor defining method** section. This is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/alerting/vis-editor.png" alt="Selecting the Visual editor" width="50%"> +![Selecting the Visual editor]({{site.url}}{{site.baseurl}}/images/alerting/vis-editor.png){: width="50%" } To finish creating a composite monitor in the visual editor, follow these steps: @@ -580,7 +61,7 @@ To finish creating a composite monitor in the visual editor, follow these steps: * **Daily** — Specify a time of day and a time zone. * **Weekly** — Specify a day of the week, a time of day, and a time zone. * **Monthly** — Specify a day of the month, a time of day, and a time zone. - * **Custom cron expression** — Create a custom cron expression for the schedule. Use the **cron expressions** link for help with creating these expressions, or see the [Cron expression reference]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/cron/). + * **Custom cron expression** — Create a custom cron expression for the schedule. Use the **cron expressions** link for help with creating these expressions, or see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). 1. In the **Delegate monitors** section, enter the individual monitors you want to include in the workflow by selecting them in the dropdown lists. In the **Visual editor**, the order in which you select the monitors determines their order in the workflow. @@ -591,7 +72,7 @@ To finish creating a composite monitor in the visual editor, follow these steps: 1. Define a trigger or triggers for the composite monitor. In the **Triggers** section, select **Add trigger**. Add a trigger name, then define the trigger conditions. * Use the **Select delegate monitor** label to open the pop-up window shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/alerting/trigger1.png" alt="This pop-up window shows options for selecting a delegate monitor and trigger condition operator" width="50%"> + ![This pop-up window shows options for selecting a delegate monitor and trigger condition operator]({{site.url}}{{site.baseurl}}/images/alerting/trigger1.png){: width="50%" } * Use the **Select delegate monitor** dropdown list to select a delegate monitor from those defined in the previous step. For the first delegate monitor, you can select NOT as the operator if you prefer. After the monitor is populated in the field, you can use the trash can icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/alerting/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/}) to the right of the list to remove the monitor if needed. * Select the plus sign ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/alerting/plus-sign-icon.png" class="inline-icon" alt="plus sign"/>{:/}) to the right of the first monitor to select a second delegate monitor. After selecting a second monitor, select one of the operators `AND`, `OR`, `AND NOT`, or `OR NOT` to apply the condition between the two monitors. After the operator is applied, you can select the operator to open the pop-up window again and change the selection. @@ -609,7 +90,7 @@ To finish creating a composite monitor in the visual editor, follow these steps: To use the extraction query editor for defining a workflow and triggers, select the **Extraction query editor** radio button in the **Monitor defining method** section. This is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/alerting/extract-q-editor.png" alt="Selecting the Extraction query editor" width="50%"> +![Selecting the Extraction query editor]({{site.url}}{{site.baseurl}}/images/alerting/extract-q-editor.png){: width="50%" } The extraction query editor follows the same general steps as the visual editor, but it allows you to build the composite monitor workflow and alert triggers using extractions from the API query. This provides you with the ability to create more advanced configurations not supported by the visual editor. The following sections provide examples of content for each of these two fields. All other steps for composite monitor creation are the same as in those for the visual editor. @@ -638,7 +119,7 @@ The extraction query editor follows the same general steps as the visual editor, * **Trigger condition** - In the **Trigger condition** field, enter the monitors and the operators that will be used to define the conditions between them. This field requires that trigger conditions be formatted in Painless scripting language. To see how these scripts are formed for trigger conditions, see [Using Painless scripting to define chained alert trigger conditions](#using-painless-scripting-language-to-define-chained-alert-trigger-conditions). + In the **Trigger condition** field, enter the monitors and the operators that will be used to define the conditions between them. This field requires that trigger conditions be formatted in Painless scripting language. To see how these scripts are formed for trigger conditions, see [Using Painless scripting to define chained alert trigger conditions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors-api/#defining-chained-alert-trigger-conditions). The following example shows a trigger condition requiring the first monitor OR the second monitor to generate an audit alert before the composite monitor can generate a chained alert: @@ -652,7 +133,7 @@ After a composite monitor is created, it appears in the list of monitors on the For composite monitors, The **Alerts** section of the details window includes the **Actions** column, which includes the view details icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/view-monitor-icon.png" class="inline-icon" alt="view monitor icon"/>{:/}). The following image shows the **Actions** column as the last column to the right. -<img src="{{site.url}}{{site.baseurl}}/images/alerting/comp-details-alerts.png" alt="Alerts section of the monitor details window" width="75%"> +![Alerts section of the monitor details window]({{site.url}}{{site.baseurl}}/images/alerting/comp-details-alerts.png){: width="75%" } Select this icon to open the **Alert details** window. This window shows you all of the audit alerts that were part of the execution that generated the chained alert and includes the delegate monitor that generated the audit alert. Select the **X** in the upper-right corner of the window to close **Alert details**. diff --git a/_observing-your-data/alerting/dashboards-alerting.md b/_observing-your-data/alerting/dashboards-alerting.md index 3c7719ed..90b78525 100644 --- a/_observing-your-data/alerting/dashboards-alerting.md +++ b/_observing-your-data/alerting/dashboards-alerting.md @@ -1,8 +1,9 @@ --- layout: default -title: Alerting dashboards and visualizations +title: Alerting dashboards and visualizations parent: Alerting -nav_order: 50 +nav_order: 20 +has_children: true --- # Alerting dashboards and visualizations @@ -17,15 +18,10 @@ Create, manage, and take action on your alerts in a single, consolidated view an The following image gives you a snapshot of the Dashboard interface. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/alerting-dashboard.png" alt="Example alerting visualization" width="800" height="800"> +![Example alerting visualization]({{site.url}}{{site.baseurl}}/images/dashboards/alerting-dashboard.png){: width="800" height="800" } ## Getting started -Before getting started, you must have: - -- Installed OpenSearch and OpenSearch Dashboards version 2.9 or later. See [Installing OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/index/). -- Installed the Alerting and Notifications Dashboards plugins. See [Managing OpenSearch Dashboards plugins]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/plugins/) to get started. - ## Configuring admin settings Users can only access, create, or manage alerts for resources for which they have permissions. Access to alerting dashboards and visualizations is controlled by OpenSearch and OpenSearch Dashboards permissions. It is enabled by default and appears as a feature under **Dashboards Management** > **Advanced Settings** > **Visualization**. If the setting is disabled, it does not appear. You can disable the setting at the cluster level in the `opensearch-dashboards.yml` file. @@ -36,7 +32,7 @@ Alerting visualizations are displayed as time-series charts that give you a snap Keep in mind the following requirements when setting up or creating alerting visualizations. The visualization: -- Must be a [Vizlib line chart](https://community.vizlib.com/support/solutions/articles/35000107262-vizlib-line-chart-introduction) +- Must be a [line chart]({{site.url}}{{site.baseurl}}/dashboards/visualize/visualize-app/line-charts/) in which every series is displayed as a line - Must contain at least a Y-axis metric aggregation - Must not have non-Y-axis metric aggregation types - Must use the date histogram aggregation type for the X-axis bucket @@ -46,7 +42,7 @@ Keep in mind the following requirements when setting up or creating alerting vis ## Creating alerting monitors -By default, when you begin to create the alert monitor workflow using the Dashboard interface, you are presented with a menu-driven interface. This interface provides a range of options that are displayed in full screen, in pop-ups, in pull-downs, or in dropdowns. They allow you to define the metrics that can be monitored, set thresholds, customize triggers that automate workflows, and generate actions when conditions are met. Currently, you can only create [per query monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). +By default, when you begin to create the alert monitor workflow using the Dashboard interface, you are presented with a menu-driven interface. This interface provides a range of options that are displayed in full screen, in pop-ups, in pull-downs, or in dropdowns. They allow you to define the metrics that can be monitored, set thresholds, customize triggers that automate workflows, and generate actions when conditions are met. You can only create [per query monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). To create an alerting monitor: @@ -60,18 +56,18 @@ To create an alerting monitor: An example of these steps is shown in the following screenshot. -<img src="{{site.url}}{{site.baseurl}}/images/dashboards/create-monitor-menu.png" alt="Create monitor interface" width="400" height="400"> +![Create monitor interface]({{site.url}}{{site.baseurl}}/images/dashboards/create-monitor-menu.png){: width="400" height="400" } ## Associating monitors -You can associate certain monitor types with a visualization using the Dashboard interface instead of the plugin page, giving you a single interface through which to add, view, and edit monitor data. +You can associate certain monitor types with a visualization using the Dashboard interface instead of the Alerting page, giving you a single interface through which to add, view, and edit monitor data. Continuing with the alerting visualization and dashboard created in the preceding section, associate an existing monitor with a visualization by following these steps: 1. From the visualization panel, choose the ellipsis icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/}). 2. Select **Associated monitors**. 3. From the **Select monitor to associate** dropdown menu, select the monitor. Only eligible monitors are listed in the dropdown menu. -4. View the monitor's basic information. To view comprehensive details, select **View monitor page** to open the Alerting plugin page. +4. View the monitor's basic information. To view comprehensive details, select **View monitor page** to open the monitor in Alerting. 5. Select **Associate monitor**. An existing monitor is associated with the visualization. ## Exploring alerting monitor details @@ -83,10 +79,10 @@ Once you've created or associated alerting monitors, verify that the monitor is 3. Select the ellipsis icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/ellipsis-icon.png" class="inline-icon" alt="ellipsis icon"/>{:/}), then **Alerting** > **Associated monitors**. 4. Choose an alerting monitor from the list. Information such as history, alerts, and associated visualizations is shown within the visualization panel. 5. Unlink or edit a monitor. - 1. Unlink a monitor from the visualization by selecting the link icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/link-icon.png" class="inline-icon" alt="link icon"/>{:/}) under **Actions**. This only unlinks the monitor from the visualization; it does not delete the monitor. - 2. Edit the monitor's metrics by selecting the edit icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/dashboards/edit-icon.png" class="inline-icon" alt="edit icon"/>{:/}). + 1. Unlink a monitor from the visualization by selecting the link icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/link-icon.png" class="inline-icon" alt="link icon"/>{:/}) under **Actions**. This only dissociates the monitor from the visualization; it does not delete the monitor. + 2. Edit the monitor's metrics by selecting the edit icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/edit-icon.png" class="inline-icon" alt="edit icon"/>{:/}). ## Next steps -- [Learn more about the Dashboard application](https://opensearch.org/docs/latest/dashboards/dashboard/index/). -- [Learn more about alerting](https://opensearch.org/docs/latest/observing-your-data/alerting/index/). +- [Learn more about the Dashboard application]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/). +- [Learn more about alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/). diff --git a/_observing-your-data/alerting/index.md b/_observing-your-data/alerting/index.md index a78c4cb9..ca58e7d5 100644 --- a/_observing-your-data/alerting/index.md +++ b/_observing-your-data/alerting/index.md @@ -1,16 +1,17 @@ --- layout: default title: Alerting -nav_order: 70 +nav_order: 110 has_children: true redirect_from: - /monitoring-plugins/alerting/ - /monitoring-plugins/alerting/index/ + - /observing-your-data/alerting/ --- # Alerting -To create an alert, do the following: +Alerting lets you monitor your data and automatically send notifications when certain conditions are met. To create an alert, do the following: - Configure a _monitor_, which is a job that runs on a defined schedule and queries OpenSearch indexes. Required. - Configure one or more _triggers_, which define the conditions that generate events. Optional. @@ -26,7 +27,7 @@ Monitor | Job that runs on a defined schedule and queries OpenSearch indexes. Th Trigger | Conditions that, if met, generate alerts. See [Triggers]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/). Alert | Event associated with a trigger. When an alert is created, the trigger performs actions, including sending notifications. Action | Specific task that is performed when an alert is triggered. See [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/). -Notification | Message that is sent to users when an alert is triggered. See [Notifications]({{site.url}}{{site.baseurl}}/notifications-plugin/index/). +Notification | Message that is sent to users when an alert is triggered. See [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/). ## Alert states @@ -42,15 +43,28 @@ Deleted | The monitor or trigger associated with this alert was deleted while th ## Creating an alert monitor -You can follow these basic steps to create an alert monitor: +The following example creates a monitor that generates an alert when a website receives more than 100 requests in a day. The example uses the OpenSearch Dashboards sample web logs. To add the sample data, on the OpenSearch Dashboards home page, select **Add sample data**, and then select **Add data** on the **Sample web logs** card. -1. In the **OpenSearch Plugins** main menu, choose **Alerting**. -1. Choose **Create monitor**. See [Monitors]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) for more information about the monitor types. -1. Enter the **Monitor details**, including monitor type, method, and schedule. -1. Select a data source from the dropdown list. -1. Define the metrics in the Query section. -1. Add a trigger. See [Triggers]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/) for more information about triggers. -1. Add an action. See [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/) for more information about actions. +To create the monitor, follow these steps: + +1. On the top menu, go to **OpenSearch Plugins** > **Alerting**. +1. Select the **Monitors** tab, and then select **Create monitor**. +1. In **Monitor details**, configure the following settings: + - **Monitor name**: Enter `Daily web traffic`. + - **Monitor type**: Select **Per query monitor**. For more information about the monitor types, see [Monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). + - **Monitor defining method**: Select **Visual editor**. + - **Schedule**: Keep the default, which runs the monitor every minute. +1. In **Select data**, in **Indexes**, enter `opensearch_dashboards_sample_data_logs` and press Enter. In **Time field**, select `timestamp`. +1. In **Query**, keep the **COUNT OF documents** metric. In **Time range for the last**, enter `1` and select **day(s)**. +1. In **Triggers**, select **Add trigger**, and then configure the trigger: + - **Trigger name**: Enter `More than 100 requests`. + - **Severity level**: Keep **1 (Highest)**. + - **Trigger condition**: Select **IS ABOVE** and enter `100`. + + The trigger preview shows the document count for the selected time range. For more information, see [Triggers]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/). +1. Optionally, in **Actions**, add an action that sends a notification when the trigger condition is met. Actions require a notification channel. If you don't have one, select **Manage channels** to create one. For more information, see [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/) and [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/). 1. Select **Create**. -Learn more about creating specific monitor types in their respective documentation. \ No newline at end of file +The monitor runs every minute. Because the sample web logs contain more than 100 requests in a typical day, the trigger condition is met and the monitor generates an alert in the **Active** state. To view the alert, select the **Alerts** tab on the **Alerting** page. + +For more information about each setting and to create a per bucket monitor, see [Per query and per bucket monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/). To create other types of monitors, see [Monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). diff --git a/_observing-your-data/alerting/monitors.md b/_observing-your-data/alerting/monitors.md index 2b9e42c4..62909ade 100644 --- a/_observing-your-data/alerting/monitors.md +++ b/_observing-your-data/alerting/monitors.md @@ -1,30 +1,41 @@ --- layout: default title: Monitors -nav_order: 1 +nav_order: 10 parent: Alerting has_children: true redirect_from: - /monitoring-plugins/alerting/monitors/ --- -# Monitors +# Alerting monitors -Proactively monitor your data in OpenSearch with features available in Alerting and Anomaly Detection. For example, you can pair Anomaly Detection with Alerting to ensure that you're notified as soon as an anomaly is detected. You can do this by setting up a detector to automatically detect outliers in your streaming data and monitors to alert you through notifications when data exceeds certain thresholds. +A monitor is a job that runs on a schedule, queries your data or cluster, and passes the results to its triggers. When a trigger condition is met, the monitor generates an alert and can perform actions, such as sending a notification. This page describes the monitor types, how to schedule monitors, and the variables available in trigger conditions and action messages. + +To generate alerts from anomaly detection results, create a per query monitor using the **Anomaly detector** defining method. For more information, see [Per query and per bucket monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/). ## Monitor types -The Alerting plugin provides the following monitor types: +Alerting provides the following monitor types. -1. **per query**: Runs a query and generates alert notifications based on the matching criteria. See [Per query monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/) for information about creating and using this monitor type. -1. **per bucket**: Runs a query that evaluates trigger criteria based on aggregated values in the dataset. See [Per bucket monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/) for information about creating and using this monitor type. -1. **per cluster metrics**: Runs API requests on the cluster to monitor its health. See [Per cluster metrics monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-cluster-metrics-monitors/) for information about creating and using this monitor type. -1. **per document**: Runs a query (or multiple queries combined by a tag) that returns individual documents that match the alert notification trigger condition. See [Per document monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-document-monitors/) for information about creating and using this monitor type. -1. **composite monitor**: Runs multiple monitors in a single workflow and generates a single alert based on multiple trigger conditions. See [Composite monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors/) for information about creating and using this monitor type. +Monitor type | Description +:--- | :--- +[Per query monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/) | Runs a query and generates alerts based on the query results. +[Per bucket monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/) | Runs a query that evaluates trigger criteria based on aggregated values in the dataset. +[PPL monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/ppl-monitors/) | Runs a Piped Processing Language (PPL) query and generates alerts based on the number of results or a custom condition. +[Per cluster metrics monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-cluster-metrics-monitors/) | Runs API requests on the cluster to monitor its health. +[Per document monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-document-monitors/) | Runs a query (or multiple queries combined by a tag) that returns individual documents that match the trigger condition. +[Composite monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/composite-monitors/) | Runs multiple monitors in a single workflow and generates a single alert based on multiple trigger conditions. -The maximum number of monitors you can create is 1,000. You can change the default maximum number of alerts for your cluster by updating the `plugins.alerting.monitor.max_monitors` setting using the [cluster settings API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/settings/). +By default, you can create up to 1,000 monitors. To change this limit, update the `plugins.alerting.monitor.max_monitors` setting using the [Cluster Settings API]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/). For more information, see [Alerting settings]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/settings/). {: .tip} +## Monitor schedules + +A monitor runs either at a fixed interval, such as every hour or every day, or on a schedule that you define with a cron expression. Use a cron expression when the interval does not describe when you need the monitor to run, such as every weekday at 11:30 AM. For the syntax, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). + +For a monitor that uses a cron expression, see [Create a query-level monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/#example-request-2). + ## Monitor variables The following table lists the variables available for customizing your monitors. @@ -32,7 +43,7 @@ The following table lists the variables available for customizing your monitors. Variable | Data type | Description :--- | :--- | :--- `ctx.monitor` | Object | Includes `ctx.monitor.name`, `ctx.monitor.type`, `ctx.monitor.enabled`, `ctx.monitor.enabled_time`, `ctx.monitor.schedule`, `ctx.monitor.inputs`, `triggers` and `ctx.monitor.last_update_time`. -`ctx.monitor.user` | Object | Includes information about the user who created the monitor. Includes `ctx.monitor.user.backend_roles` and `ctx.monitor.user.roles`, which are arrays that contain the backend roles and roles assigned to the user. See [alerting security]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/) for more information. +`ctx.monitor.user` | Object | Includes information about the user who created the monitor. Includes `ctx.monitor.user.backend_roles` and `ctx.monitor.user.roles`, which are arrays that contain the backend roles and roles assigned to the user. See [alerting security]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/) for more information. `ctx.monitor.enabled` | Boolean | Whether the monitor is enabled. `ctx.monitor.enabled_time` | Milliseconds | Unix epoch time of when the monitor was last enabled. `ctx.monitor.schedule` | Object | Contains a schedule of how often or when the monitor should run. @@ -40,19 +51,19 @@ Variable | Data type | Description `ctx.monitor.schedule.period.unit` | String | The interval's unit of time. `ctx.monitor.inputs` | Array | An array that contains the indexes and definition used to create the monitor. `ctx.monitor.inputs.search.indices` | Array | An array that contains the indexes the monitor observes. -`ctx.monitor.inputs.search.query` | N/A | The definition used to define the monitor. +`ctx.monitor.inputs.search.query` | Object | The query that the monitor runs. The following table lists other variables you can use with your monitors. Variable | Data type | Description -:--- | :--- : :--- +:--- | :--- | :--- `ctx.results` | Array | An array with one element, for example, `ctx.results[0]`. Contains the query results. This variable is empty if the trigger was unable to retrieve results. See `ctx.error`. `ctx.last_update_time` | Milliseconds | Unix epoch time of when the monitor was last updated. `ctx.periodStart` | String | Unix timestamp for the beginning of the period during which the alert triggered. For example, if a monitor runs every 10 minutes, a period might begin at 10:40 and end at 10:50. `ctx.periodEnd` | String | The end of the period during which the alert triggered. `ctx.error` | String | The error message if the trigger was unable to retrieve results or unable to evaluate the trigger, typically due to a compile error or null pointer exception. Null otherwise. `ctx.alert` | Object | The current, active alert (if it exists). Includes `ctx.alert.id`, `ctx.alert.version`, and `ctx.alert.isAcknowledged`. Null if no alert is active. Only available with query-level monitors. -`ctx.dedupedAlerts` | Object | Alerts that have already been triggered. OpenSearch keeps the existing alert to prevent the plugin from creating endless amounts of the same alerts. Only available with bucket-level monitors. +`ctx.dedupedAlerts` | Object | Alerts that have already been triggered. OpenSearch keeps the existing alert to prevent the monitor from repeatedly creating the same alert. Only available with bucket-level monitors. `ctx.newAlerts` | Object | Newly created alerts. Only available with bucket-level monitors. `ctx.completedAlerts` | Object | Alerts that are no longer ongoing. Only available with bucket-level monitors. `bucket_keys` | String | Comma-separated list of the monitor's bucket key values. Available only for `ctx.dedupedAlerts`, `ctx.newAlerts`, and `ctx.completedAlerts`. Accessed through `ctx.dedupedAlerts[0].bucket_keys`. diff --git a/_observing-your-data/alerting/per-cluster-metrics-monitors.md b/_observing-your-data/alerting/per-cluster-metrics-monitors.md index 99984a16..2716b2f7 100644 --- a/_observing-your-data/alerting/per-cluster-metrics-monitors.md +++ b/_observing-your-data/alerting/per-cluster-metrics-monitors.md @@ -9,49 +9,104 @@ has_children: false # Per cluster metrics monitors -_Per cluster metrics monitors_ are a type of alert monitor that collects and analyzes metrics from a single cluster, providing insights into the cluster's performance and health. You can set alerts to monitor certain conditions, such as when: +A per cluster metrics monitor runs a cluster API request on a schedule and evaluates the response using a trigger condition. Use it to generate alerts about the state of a cluster, for example, when: - Cluster health reaches yellow or red status. -- Cluster-level metrics---for example, CPU usage and JVM memory usage---reach specified thresholds. -- Node-level metrics---for example, available disk space, JVM memory usage, and CPU usage---reach specified thresholds. -- Total number of documents stored reaches specified thresholds. +- Cluster-level metrics, such as CPU usage and JVM memory usage, reach specified thresholds. +- Node-level metrics, such as available disk space, JVM memory usage, and CPU usage, reach specified thresholds. +- The total number of documents stored reaches a specified threshold. -## Create a cluster metrics monitor +## Creating a per cluster metrics monitor -To create a cluster metrics monitor, follow these steps: +The following example creates a monitor that generates an alert when the cluster health status is not green. -1. Select **Alerting** > **Monitors** > **Create monitor**. -2. Select the **Per cluster metrics monitor** option. -3. In the Query section, pick the **Request type** from the dropdown list. -4. (Optional) If you want to filter the API response to use only certain path parameters, enter those parameters under **Query parameters**. Most APIs that can be used to monitor cluster status support path parameters as described in their documentation (for example, comma-separated lists of index names). -5. In the [Triggers]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/) section, indicate which conditions will trigger an alert. The trigger condition autopopulates a `painless ctx` variable. For example, a cluster monitor watching for Cluster Stats uses the trigger condition `ctx.results[0].indices.count <= 0`, which triggers an alert based on the number of indexes returned by the query. For more specificity, add any additional Painless conditions supported by the API. To see an example of the condition response, select **Preview condition response**. -6. In the Actions section, indicate how you want your users to be notified when a trigger condition is met. -7. Select **Create**. Your new monitor appears in the **Monitors** list. +To create the monitor, follow these steps: -The following example shows a configuration of a cluster metrics monitor. +1. On the top menu, go to **OpenSearch Plugins** > **Alerting**. +1. Select the **Monitors** tab, and then select **Create monitor**. +1. In **Monitor details**, enter a **Monitor name**, such as `Cluster health`, and select **Per cluster metrics monitor**. Optionally, change the **Schedule**. By default, the monitor runs every minute. +1. In **Select data**, keep the local cluster selected. To monitor remote clusters, select them in **Select clusters**. For more information, see [Monitoring remote clusters](#monitoring-remote-clusters). +1. In **Query**, in **Request type**, select **Cluster health**. Optionally, in **Path parameters**, enter path parameters to filter the API response, for example, a comma-separated list of index names. To view the API response, select **Preview query**. +1. In **Triggers**, select **Add trigger**, and then configure the trigger: + - **Trigger name**: Enter `Cluster health is not green`. + - **Severity level**: Keep **1 (Highest)**. + - **Trigger condition**: Keep the default condition for the selected request type, `ctx.results[0].status != "green"`. The condition is a [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/) script that evaluates the API response. To test the condition, select **Preview condition response**. +1. Optionally, in **Actions**, add an action that sends a notification when the trigger condition is met. For more information, see [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/). +1. Select **Create**. -<img src="{{site.url}}{{site.baseurl}}/images/cluster-metrics.png" alt="Cluster metrics monitor" width="700"/> +If the cluster health status is yellow or red, the monitor generates an alert in the **Active** state. For example, a single-node cluster that contains indexes with replicas has a yellow status because the replicas cannot be assigned. + +A per cluster metrics monitor supports up to 10 triggers. For the variables that you can use in trigger conditions, see [Trigger variables]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/#trigger-variables). + +## Creating a per cluster metrics monitor using the API + +To create the monitor from the preceding example using the API, send the following request: + +```json +POST _plugins/_alerting/monitors +{ + "type": "monitor", + "monitor_type": "cluster_metrics_monitor", + "name": "Cluster health", + "enabled": true, + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "inputs": [ + { + "uri": { + "api_type": "CLUSTER_HEALTH", + "path": "_cluster/health", + "path_params": "" + } + } + ], + "triggers": [ + { + "query_level_trigger": { + "name": "Cluster health is not green", + "severity": "1", + "condition": { + "script": { + "source": "ctx.results[0].status != \"green\"", + "lang": "painless" + } + }, + "actions": [] + } + } + ] +} +``` +{% include copy-curl.html %} + +For more information about the monitor APIs, see [Alerting API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/). ## Supported APIs -Trigger conditions use responses from the following API endpoints. Most APIs that can be used to monitor cluster status support path parameters (for example, comma-separated lists of index names). They do not support query parameters. +A per cluster metrics monitor can call the following APIs. The `api_type` column lists the value to use in the `inputs.uri.api_type` field when you create the monitor using the API. The APIs support path parameters, such as a comma-separated list of index names, but not query parameters. -- [_cluster/health]({{site.url}}{{site.baseurl}}/api-reference/cluster-health/) -- [_cluster/stats]({{site.url}}{{site.baseurl}}/api-reference/cluster-stats/) -- [_cluster/settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-settings/) -- [_nodes/stats]({{site.url}}{{site.baseurl}}/opensearch/popular-api/#get-node-statistics) -- [_cat/indices]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-indices/) -- [_cat/pending_tasks]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-pending-tasks/) -- [_cat/recovery]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/) -- [_cat/shards]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-shards/) -- [_cat/snapshots]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-snapshots/) -- [_cat/tasks]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-tasks/) +API | `api_type` | Request type in OpenSearch Dashboards +:--- | :--- | :--- +[Cluster Health]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-health/) | `CLUSTER_HEALTH` | **Cluster health** +[Cluster Settings]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-settings/) | `CLUSTER_SETTINGS` | **Cluster settings** +[Cluster Stats]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/cluster-stats/) | `CLUSTER_STATS` | **Cluster stats** +[CAT Indices]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-indices/) | `CAT_INDICES` | **List indices** +[CAT Pending Tasks]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-pending-tasks/) | `CAT_PENDING_TASKS` | **List pending tasks** +[CAT Recovery]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-recovery/) | `CAT_RECOVERY` | **List index and shard recoveries** +[CAT Shards]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-shards/) | `CAT_SHARDS` | **List shards** +[CAT Snapshots]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-snapshots/) | `CAT_SNAPSHOTS` | **List snapshots** +[CAT Tasks]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-tasks/) | `CAT_TASKS` | **List tasks** +[Nodes Stats]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/) | `NODES_STATS` | Not available. Use the API. -## Restrict API fields +## Restricting API fields -If you want to hide fields from the API response and not expose them for alerting, reconfigure the [supported_json_payloads.json](https://github.com/opensearch-project/alerting/blob/main/alerting/src/main/resources/org/opensearch/alerting/settings/supported_json_payloads.json) file inside the Alerting plugin. The file functions as an allow list for the API fields you want to use in an alert. By default, all APIs and their parameters can be used for monitors and trigger conditions. +To restrict the APIs and response fields that can be used in per cluster metrics monitors, modify the [supported_json_payloads.json](https://github.com/opensearch-project/alerting/blob/main/alerting/src/main/resources/org/opensearch/alerting/settings/supported_json_payloads.json) file inside the Alerting plugin. The file functions as an allow list. By default, all supported APIs and their response fields can be used in monitors and trigger conditions. -However, you can modify the file so that cluster metrics monitors can only be created for APIs referenced. Furthermore, only fields referenced in the supported files can create trigger conditions. This `supported_json_payloads.json` allows for a cluster metrics monitor to be created for the `_cluster/stats` API, and triggers conditions for the `indices.shards.total` and `indices.shards.index.shards.min` fields. +If you modify the file, per cluster metrics monitors can be created only for the APIs that the file lists, and trigger conditions can use only the fields that the file lists. For example, the following entry allows monitors for the Cluster Stats API and trigger conditions that use the `indices.shards.total` and `indices.shards.index.shards.min` fields: ```json "/_cluster/stats": { @@ -62,65 +117,28 @@ However, you can modify the file so that cluster metrics monitors can only be cr } ``` -## Painless triggers +## Monitoring remote clusters -Painless scripts define triggers for cluster metrics monitors, similar to per query or per bucket monitors, which are defined using the extraction query definition option. Painless scripts are composed of at least one statement and any additional functions you wish to run. +A per cluster metrics monitor can call an API on multiple clusters. In OpenSearch Dashboards, select the clusters in **Select clusters**. Using the API, list the clusters in the `inputs.uri.clusters` field, for example, `"clusters": ["cluster-1", "cluster-2"]`. -The cluster metrics monitor supports up to **ten** triggers. +When a monitor calls an API on multiple clusters, `ctx.results[0]` contains a response for each cluster, keyed by cluster name. The following trigger condition generates an alert when the health status of any of the clusters is not green: -In the following example, the monitor is configured to call the Cluster Health API for two clusters, `cluster-1` and `cluster-2`. The trigger condition will create an alert when either of the clusters' `status` is not `green`. - -The `script` parameter points the `source` to the Painless script `for (cluster in ctx.results[0].keySet()) if (ctx.results[0][cluster].status != \"green\") return true`. See [Trigger variables]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/#trigger-variables) for more `painless ctx` variable options. - -```json -{ - "name": "Cluster Health Monitor", - "type": "monitor", - "monitor_type": "query_level_monitor", - "enabled": true, - "schedule": { - "period": { - "unit": "MINUTES", - "interval": 1 - } - }, - "inputs": [ - { - "uri": { - "api_type": "CLUSTER_HEALTH", - "path": "_cluster/health/", - "path_params": "", - "url": "http://localhost:9200/_cluster/health/", - "cluster": ["cluster-1", "cluster-2"] - } - } - ], - "triggers": [ - { - "query_level_trigger": { - "id": "Tf_L_nwBti6R6Bm-18qC", - "name": "Yellow status trigger", - "severity": "1", - "condition": { - "script": { - "source": "for (cluster in ctx.results[0].keySet()) if (ctx.results[0][cluster].status != \"green\") return true", - "lang": "painless" - } - }, - "actions": [] - } - } - ] -} ``` -The dashboards interface supports the selection of clusters to be monitored and the desired API. A view of the interface is shown in the following image. +for (cluster in ctx.results[0].keySet()) if (ctx.results[0][cluster].status != "green") return true +``` +{% include copy.html %} -<img src="{{site.url}}{{site.baseurl}}/images/alerting/cross-cluster-cluster-metrics-monitors.png" alt="Cluster metrics monitor" width="700"/> +To create a cross-cluster monitor in OpenSearch Dashboards, you need the following [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/): `cluster:admin/opensearch/alerting/remote/indexes/get`, `indices:admin/resolve/index`, `cluster:monitor/health`, and `indices:admin/mappings/get`. +{: .note} -### Limitations +The following image shows a per cluster metrics monitor that calls the Cluster Health API on two clusters. + +![Per cluster metrics monitor for multiple clusters]({{site.url}}{{site.baseurl}}/images/alerting/cross-cluster-cluster-metrics-monitors.png){: width="700" } + +## Limitations Per cluster metrics monitors have the following limitations: -- The OpenSearch cluster must be in a state where an index's conditions can be monitored and actions can be executed against the index. -- Removing resource permissions from a user will not prevent that user’s preexisting monitors for that resource from executing. -- Users with permissions to create monitors are not blocked from creating monitors for resources for which they do not have permissions; however, those monitors will not run. +- The cluster must be in a state in which the monitor can run and its actions can be performed. +- Removing resource permissions from a user does not stop that user's existing monitors for that resource from running. +- Users with permissions to create monitors are not prevented from creating monitors for resources that they don't have permissions for. However, those monitors don't run. diff --git a/_observing-your-data/alerting/per-document-monitors.md b/_observing-your-data/alerting/per-document-monitors.md index c1f4c7bf..5456e2d5 100644 --- a/_observing-your-data/alerting/per-document-monitors.md +++ b/_observing-your-data/alerting/per-document-monitors.md @@ -11,42 +11,79 @@ has_children: false Introduced 2.0 {: .label .label-purple } -Per document monitors are a type of alert monitor that can be used to identify and alert on specific documents in an OpenSearch index. For example, you can use the monitor to: +A per document monitor runs one or more queries against the documents added to an index since the monitor's previous run and generates an alert for the documents that match the trigger conditions. For example, you can use a per document monitor to: -- Detect corrupted data or unauthorized changes. -- Enforce data quality policies, such as ensuring all documents contain a certain field or that values in a field are within a certain range. -- Track changes to a specific document over time, which can be helpful for auditing and compliance purposes +- Detect log entries that contain errors or security events as they are ingested. +- Detect documents that violate data quality rules, for example, documents in which a field contains an unexpected value. -## Defining queries +On its first run, a per document monitor does not evaluate the documents that already exist in the index. It evaluates only the documents added after that. -Per document monitors allow you to define up to 10 queries that compare a selected field with a desired value. You can define supported field data types using the following operators: +Per document monitors do not support cross-cluster search. +{: .note} -- `is` -- `is not` -- `is greater than` -- `is greater than equal` -- `is less than` -- `is less than equal` +## Creating a per document monitor -You can query each [trigger]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/) using up to 10 tags, adding the tag as a single trigger condition instead of specifying a single query. The [Alerting plugin]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/) processes the trigger conditions from all queries as a logical `OR` operation, so if any of the query conditions are met, it triggers an alert. The Alerting plugin then tells the [Notifications plugin]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) to send the alert notification to a channel. +The following example creates a monitor that generates an alert when a web log with a `404` response is indexed. -You can only use _tags_--- that is, labels that can be applied to multiple queries to combine them with the logical `OR`` operation---in a per document monitor. -{: .important} +1. Create an index for the example logs. In **Dev Tools**, send the following request: + + ```json + PUT web-logs + { + "mappings": { + "properties": { + "response": { "type": "keyword" }, + "request": { "type": "keyword" }, + "timestamp": { "type": "date" } + } + } + } + ``` + {% include copy-curl.html %} + +1. On the top menu, go to **OpenSearch Plugins** > **Alerting**. +1. Select the **Monitors** tab, and then select **Create monitor**. +1. In **Monitor details**, enter a **Monitor name**, such as `Not found responses`, and select **Per document monitor**. In **Monitor defining method**, select **Visual editor**. Optionally, change the **Schedule**. By default, the monitor runs every minute. +1. In **Select data**, in **Index**, enter `web-logs` and press Enter. +1. In **Query**, define the query: + - **Query name**: Enter `not-found`. + - **Field**: Select `response`, select **is**, and enter `404`. + - **Tags**: Optionally, select **Add tag** and enter `errors`. A tag groups queries so that a trigger condition can refer to all queries with the tag. + + To define more queries, select **Add another query**. A monitor supports up to 10 queries. The available operators depend on the field type. For example, numeric fields support **is greater than** and **is less than**. +1. In **Triggers**, select **Add trigger**, and then configure the trigger: + - **Trigger name**: Enter `Not found responses`. + - **Trigger conditions**: Select the `not-found` query. To refer to all queries with a tag instead, select the tag. To combine conditions, select **Add condition**. +1. Optionally, in **Actions**, add an action that sends a notification when the trigger condition is met. For more information, see [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/). +1. Select **Create**. +1. Index a document that matches the query: + + ```json + POST web-logs/_doc + { + "response": "404", + "request": "/missing-page", + "timestamp": "2026-10-28T02:00:00Z" + } + ``` + {% include copy-curl.html %} + +On its next run, the monitor generates an alert in the **Active** state for the matching document. A document with another response code, such as `200`, does not match the query and does not generate an alert. + +To define the queries and trigger conditions using the API, see [Document-level monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/#document-level-monitors). ## Document findings -The Alerting plugin creates a list of _Findings_ that contain metadata about which document matches each query. A _Finding_ is a record of a document identified by the per document monitor query as meeting the alert condition. Key components of a finding include the document ID, timestamp, alert condition details. Findings are stored in the Findings index, `.opensearch-alerting-finding*`. +When a document matches a query, the monitor creates a _finding_, which is a record of the document and the query that it matched. Findings are stored in the `.opensearch-alerting-finding*` indexes. Each finding contains the following information. -Security Analytics can use the findings data to keep track of and analyze the query data separately from the alert processes. See [Working with findings]({{site.url}}{{site.baseurl}}/security-analytics/usage/findings/) to learn more. +Field | Description +:--- | :--- +Document | The document ID and index name, separated by a vertical bar, for example, `Re5akdirhj3fl` and `web-logs`. +Query | The name of the query that matched the document. +Time found | The time at which the monitor found the document. + +Security Analytics uses findings to analyze query matches separately from alerts. For more information, see [Working with findings]({{site.url}}{{site.baseurl}}/security-analytics/usage/findings/). {: .note} -The Alerting API also provides a _document-level monitor_ that programmatically accomplishes the same function as the _per document monitor_ in OpenSearch Dashboards. See [Document-level monitors]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/api/#document-level-monitors) to learn more. - -To prevent a large volume of findings in a high-ingestion cluster, configuring alert notifications for each finding is not recommended unless rules are well defined. +In a cluster that ingests a large number of documents, a broad query can create many findings. Send a notification for each finding only if the queries are specific. {: .important} - -The following metadata is provided for each document findings entry: - -* **Document**: The document ID and index name. For example: `Re5akdirhj3fl | test-logs-index`. -* **Query**: The query name that matched the document. -* **Time found**: The timestamp that indicates when the document was found during the runtime. diff --git a/_observing-your-data/alerting/per-query-bucket-monitors.md b/_observing-your-data/alerting/per-query-bucket-monitors.md index d4fe0ff9..bbaffce6 100644 --- a/_observing-your-data/alerting/per-query-bucket-monitors.md +++ b/_observing-your-data/alerting/per-query-bucket-monitors.md @@ -9,95 +9,126 @@ has_children: false # Per query and per bucket monitors -Per query monitors are a type of alert monitor that can be used to identify and alert on specific queries that are run against an OpenSearch index; for example, queries that detect and respond to anomalies in specific queries. Per query monitors only trigger one alert at a time. +Per query and per bucket monitors run a query on a schedule and evaluate the results using trigger conditions: -Per bucket monitors are a type of alert monitor that can be used to identify and alert on specific buckets of data that are created by a query against an OpenSearch index. +- A _per query monitor_ evaluates the query result as a whole. For example, it can generate an alert when the number of matching documents is above a threshold. A trigger in a per query monitor has at most one active alert at a time. +- A _per bucket monitor_ groups the query results into buckets using one or more fields and evaluates each bucket separately. For example, it can generate a separate alert for each host or country whose request count is above a threshold. -Both monitor types support querying remote indexes using the same `cluster-name:index-name` pattern used by [cross-cluster search](https://opensearch.org/docs/latest/security/access-control/cross-cluster-search/) or by using OpenSearch Dashboards 2.12 or later. +The examples on this page use the OpenSearch Dashboards sample web logs. To add the sample data, on the OpenSearch Dashboards home page, select **Add sample data**, and then select **Add data** on the **Sample web logs** card. -<img src="{{site.url}}{{site.baseurl}}/images/alerting/cross-cluster-per-query-per-bucket-monitors.png" alt="Cluster metrics monitor" width="700"/> +## Creating a per query monitor -## Creating a per query or per bucket monitor +The following example creates a monitor that generates an alert when the website receives more than 100 requests in a day. -To create a per query monitor, follow these steps: +To create the monitor, follow these steps: -**Step 1.** Define your query and [triggers]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/). You can use any of these methods: visual editor, query editor, or anomaly detector. +1. On the top menu, go to **OpenSearch Plugins** > **Alerting**. +1. Select the **Monitors** tab, and then select **Create monitor**. +1. In **Monitor details**, configure the following settings: + - **Monitor name**: Enter `Daily web traffic`. + - **Monitor type**: Select **Per query monitor**. + - **Monitor defining method**: Select **Visual editor**. To write the query using query domain-specific language (DSL), select **Extraction query editor** instead. For more information, see [Defining the query using the extraction query editor](#defining-the-query-using-the-extraction-query-editor). To generate alerts from anomaly detection results, select **Anomaly detector**. For more information, see [Pairing a monitor with an anomaly detector](#pairing-a-monitor-with-an-anomaly-detector). + - **Schedule**: Keep the default, which runs the monitor every minute. To run the monitor at a specific time, select **Daily**, **Weekly**, **Monthly**, or **Custom cron expression**, and then select a time zone. For more information about cron expressions, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). +1. In **Select data**, in **Indexes**, enter `opensearch_dashboards_sample_data_logs` and press Enter. In **Time field**, select `timestamp`. - - Visual definition works well for monitors that can be defined as "some value is above or below some threshold for some amount of time." It also works well for most monitors. + If you use the Security plugin, you can select only indexes that you have permission to access. For more information, see [Alerting security]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/). +1. In **Query**, configure the query: + - **Metrics**: Keep **COUNT OF documents**. To use another aggregation, such as an average or maximum of a numeric field, select **Add metric**. + - **Time range for the last**: Enter `1` and select **day(s)**. + - **Data filter**: Optionally, select **Add filter** to monitor a subset of the documents. - - Query definition provides flexibility in relation to your query (using [OpenSearch query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/full-text/index)) and how you evaluate the results of that query (Painless scripting). + To view the query and how long it takes to run, expand **Preview query and performance**. The monitor runs this query as often as the schedule specifies, so check that its performance is acceptable. +1. In **Triggers**, select **Add trigger**, and then configure the trigger: + - **Trigger name**: Enter `More than 100 requests`. + - **Severity level**: Keep **1 (Highest)**. + - **Trigger condition**: Select **IS ABOVE** and enter `100`. -The following example averages the `cpu_usage` field: + The trigger preview shows the document count over the selected time range. For more information, see [Triggers]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/triggers/). +1. Optionally, in **Actions**, add an action that sends a notification when the trigger condition is met. Actions require a notification channel. If you don't have one, select **Manage channels** to create one. For more information, see [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/). +1. Select **Create**. + +Because the sample web logs typically contain more than 100 requests in a day, the trigger condition is met and the monitor generates an alert in the **Active** state. To view the alert, select the **Alerts** tab on the **Alerting** page. + +## Creating a per bucket monitor + +The following example creates a monitor that generates a separate alert for each country that sends more than 20 requests in a day. + +To create the monitor, follow these steps: + +1. On the top menu, go to **OpenSearch Plugins** > **Alerting**. +1. Select the **Monitors** tab, and then select **Create monitor**. +1. In **Monitor details**, enter a **Monitor name**, such as `Daily requests by country`. In **Monitor type**, select **Per bucket monitor**. In **Monitor defining method**, select **Visual editor**. +1. In **Select data**, in **Indexes**, enter `opensearch_dashboards_sample_data_logs` and press Enter. In **Time field**, select `timestamp`. +1. In **Query**, configure the query: + - **Metrics**: Keep **COUNT OF documents**. + - **Time range for the last**: Enter `1` and select **day(s)**. + - **Group by**: Select **Add group by**, and then select the `geo.src` field. A per bucket monitor requires at least one group-by field. +1. In **Triggers**, select **Add trigger**, and then configure the trigger: + - **Trigger name**: Enter `More than 20 requests`. + - **Trigger conditions**: In **Metric**, keep **Count of documents**. In **Threshold**, select **IS ABOVE**. In **Value**, enter `20`. + - **Keyword filter**: Optionally, select **Add filter** to evaluate only the buckets whose group-by value matches a keyword. +1. Optionally, in **Actions**, add an action that sends a notification for each bucket that meets the trigger condition. +1. Select **Create**. + +The monitor generates an alert for each country whose request count is above the threshold. Each alert includes the bucket key, for example, `CN`. + +## Defining the query using the extraction query editor + +To define the query using [query DSL]({{site.url}}{{site.baseurl}}/query-dsl/index/), select **Extraction query editor** in **Monitor defining method**. Then enter the query in **Query** and select **Run** to test it. The **Monitor performance** panel shows how long the query takes to run and how many documents it returns. + +To limit the query to the time period of each monitor run, use the `{% raw %}{{period_end}}{% endraw %}` variable. The following query returns the number of `404` responses in the day before each monitor run: ```json - { - "size": 0, - "query": { - "match_all": {} - }, - "aggs": { - "avg_cpu": { - "avg": { - "field": "cpu_usage" - } - } - } - } +{% raw %}{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "range": { + "timestamp": { + "gte": "{{period_end}}||-1d", + "lte": "{{period_end}}", + "format": "epoch_millis" + } + } + }, + { + "term": { + "response.keyword": "404" + } + } + ] + } + } +}{% endraw %} ``` +{% include copy.html %} -You can also filter query results using `{% raw %}{{period_start}}{% endraw %}` and `{% raw %}{{period_end}}{% endraw %}`: +When you use the extraction query editor, you define the trigger condition using a [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/) script. The following condition generates an alert when the query returns more than 5 documents: -```json - { - "size": 0, - "query": { - "bool": { - "filter": [{ - "range": { - "timestamp": { - "from": "{% raw %}{{period_end}}{% endraw %}||-1h", - "to": "{% raw %}{{period_end}}{% endraw %}", - "include_lower": true, - "include_upper": true, - "format": "epoch_millis", - "boost": 1 - } - } - }], - "adjust_pure_negative": true, - "boost": 1 - } - }, - "aggregations": {} - } ``` +ctx.results[0].hits.total.value > 5 +``` +{% include copy.html %} -"Start" and "end" refer to the interval at which the monitor runs. See [Monitor variables]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/#monitor-variables). +To test the condition, select **Preview condition response**. For the variables that you can use in trigger conditions, see [Monitor variables]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/#monitor-variables). -To define a monitor visually, choose **Visual editor**. Then choose a source index, a time frame, an aggregation (for example, `count()` or `average()`), a data filter (if you want to monitor a subset of your source index), and a group-by field if you want to include an aggregation field in your query. At least one group-by field is required if you're defining a per bucket monitor. +## Pairing a monitor with an anomaly detector -Visual definition works well for most monitors. -{: .tip } +To generate alerts from the results of an [anomaly detector]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/), create a per query monitor, select **Anomaly detector** in **Monitor defining method**, and then select the detector. The **Anomaly detector** method is not available for per bucket monitors. -If you use the Security plugin, you can only choose indexes that you have permission to access. For details, see [Alerting security]({{site.url}}{{site.baseurl}}/security/). +Set the monitor interval to at least twice the detector interval. Otherwise, the monitor might miss anomaly results. For example, if both the monitor and the detector run every 5 minutes and you start the detector at 12:00, an anomaly detected at 12:05 might not be available for queries until 12:06. The monitor reads results from 12:00 to 12:05, so it misses that anomaly. When you create a monitor from a detector in OpenSearch Dashboards, the monitor interval is set to twice the detector interval by default. -To use a query, choose **Extraction query editor**, add your query (using [OpenSearch query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/full-text/index)), and test it using the **Run** button. +If you change a detector's interval, update the monitor interval as well. The monitor interval is not updated automatically. -The monitor makes this query to OpenSearch as often as the schedule dictates; check the **Query Performance** section and make sure you're comfortable with the performance implications. +## Querying remote indexes -Anomaly detection is available only if you are defining a per query monitor. -{: .warning} +Both monitor types can query indexes on remote clusters. In **Select data**, select the remote clusters in **Select clusters**, and then select the indexes. When you define the query using the extraction query editor, specify remote indexes using the `<cluster-name>:<index-name>` pattern used by [cross-cluster search]({{site.url}}{{site.baseurl}}/security/access-control/cross-cluster-search/). -To use an anomaly detector, choose **Anomaly detector** and select your **Detector**. +To create a cross-cluster monitor in OpenSearch Dashboards, you need the following [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/): `cluster:admin/opensearch/alerting/remote/indexes/get`, `indices:admin/resolve/index`, `cluster:monitor/health`, and `indices:admin/mappings/get`. +{: .note} -The anomaly detection option is for pairing with the Anomaly Detection plugin. See [Anomaly Detection]({{site.url}}{{site.baseurl}}/monitoring-plugins/ad/). +The following image shows remote indexes selected for a per query monitor. -For anomaly detector, choose an appropriate schedule for the monitor based on the detector interval. Otherwise, the alerting monitor might miss reading the results. For example, assume you set the monitor interval and the detector interval as 5 minutes, and you start the detector at 12:00. If an anomaly is detected at 12:05, it might be available at 12:06 because of the delay between writing the anomaly and it being available for queries. The monitor reads the anomaly results between 12:00 and 12:05, so it does not get the anomaly results available at 12:06. - -To avoid this issue, make sure the alerting monitor is at least twice the detector interval. When you create a monitor using OpenSearch Dashboards, the anomaly detector plugin generates a default monitor schedule that's twice the detector interval. - -Whenever you update a detector’s interval, make sure to update the associated monitor interval, as the Anomaly Detection plugin does not do this automatically. - -**Step 2.** Choose the frequency to run the monitor, for example, either by time intervals (minutes, hours, days) or on a schedule. If you run it by time interval or on a custom [custom cron expression]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/cron/), then you must provide the time zone. - -**Step 3.** Add a trigger to the monitor. +![Selecting remote indexes for a monitor]({{site.url}}{{site.baseurl}}/images/alerting/cross-cluster-per-query-per-bucket-monitors.png){: width="700" } diff --git a/_observing-your-data/alerting/ppl-monitors.md b/_observing-your-data/alerting/ppl-monitors.md new file mode 100644 index 00000000..b87fc4c9 --- /dev/null +++ b/_observing-your-data/alerting/ppl-monitors.md @@ -0,0 +1,304 @@ +--- +layout: default +title: PPL monitors +nav_order: 22 +parent: Monitors +grand_parent: Alerting +has_children: false +--- + +# PPL monitors + +PPL alert monitors use [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/index/) queries to monitor your data. They are [per query monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/per-query-bucket-monitors/) that use PPL instead of query DSL as the query language. + +## Setup + +The examples on this page use an `application_logs` index containing web request logs. To follow along, create the index with the following mapping: + +```json +PUT /application_logs +{ + "mappings": { + "properties": { + "@timestamp": { "type": "date" }, + "endpoint": { "type": "keyword" }, + "service": { "type": "keyword" }, + "level": { "type": "keyword" }, + "response_time": { "type": "integer" } + } + } +} +``` +{% include copy-curl.html %} + +Index the sample documents: + +```json +POST /application_logs/_bulk?refresh=true +{ "index": {} } +{ "@timestamp": "2026-01-15T10:00:00Z", "endpoint": "/api/orders", "service": "orders", "level": "ERROR", "response_time": 4200 } +{ "index": {} } +{ "@timestamp": "2026-01-15T10:01:00Z", "endpoint": "/api/orders", "service": "orders", "level": "ERROR", "response_time": 3600 } +{ "index": {} } +{ "@timestamp": "2026-01-15T10:02:00Z", "endpoint": "/api/checkout", "service": "checkout", "level": "ERROR", "response_time": 2500 } +``` +{% include copy-curl.html %} + +## Creating a PPL monitor in OpenSearch Dashboards + +To create a PPL monitor, follow these steps: + +1. Select **Alerting** > **Monitors** > **Create monitor**. +2. Select the **PPL monitor** option. +3. Enter a name for the monitor and configure the schedule (by time interval or custom cron expression). For more information about cron expressions, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). +4. In the **Query** section, enter your PPL query, for example: + + ```sql + source = application_logs | stats avg(response_time) as avg_response by endpoint + ``` + {% include copy.html %} + +5. Add one or more triggers. For more information about configuring trigger conditions, see [PPL triggers](#ppl-triggers). +6. Add actions to specify notifications when triggers fire. For more information, see [Actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/). +7. Select **Create**. + +## PPL triggers + +PPL monitors use `ppl_trigger` objects, which differ from the Painless-script-based triggers used by other monitor types. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). Each PPL monitor supports up to 10 triggers. + +### Number of results trigger + +A number of results trigger evaluates the total number of rows returned by the base PPL query against a threshold. The following comparison operators are supported. + +Operator | Description +:--- | :--- +`>` | Greater than +`>=` | Greater than or equal to +`<` | Less than +`<=` | Less than or equal to +`==` | Equal to +`!=` | Not equal to + +For example, to trigger an alert when more than one result is returned, use the following trigger definition: + +```json +{ + "ppl_trigger": { + "name": "High result count", + "severity": "1", + "type": "number_of_results", + "num_results_condition": ">", + "num_results_value": 1, + "actions": [] + } +} +``` + +### Custom condition trigger + +A custom condition trigger appends a `where` clause to the base PPL query. If the modified query returns any results, the trigger fires. This allows you to define fine-grained conditions based on computed fields or aggregations. The custom condition is validated as a `where` statement during monitor creation. + +For example, consider the following base query: + +```sql +source = application_logs | stats max(response_time) as max_response by endpoint +``` + +To trigger an alert when any endpoint has a maximum response time above 3000 ms, use the following trigger definition: + +```json +{ + "ppl_trigger": { + "name": "Slow endpoint detected", + "severity": "2", + "type": "custom", + "custom_condition": "where max_response > 3000", + "actions": [] + } +} +``` + +## Template variables + +PPL monitors provide the following additional template variable for use in [actions]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/actions/) and notification messages. + +Variable | Data type | Description +:--- | :--- | :--- +`ctx.ppl_query_results` | Array | A list of maps in which each element represents a PPL query result row. The keys in each map are field names from the query schema. For number of results triggers, the array contains the base query results. For custom condition triggers, it contains the results of the query with the custom condition applied. + +### Mustache template example + +The following example iterates over PPL query results and outputs the fields in each row: + +{% raw %} +``` +PPL Query Results: +{{#ctx.ppl_query_results}} + Endpoint: {{endpoint}}, Average Response Time: {{avg_response}} +{{/ctx.ppl_query_results}} +``` +{% endraw %} + +## Query result format + +PPL query results contain `schema` and `datarows` fields. For example, the query `source = application_logs | where level = 'ERROR' | stats count() as error_count by endpoint` returns the following response: + +```json +{ + "schema": [ + {"name": "error_count", "type": "bigint"}, + {"name": "endpoint", "type": "string"} + ], + "datarows": [ + [1, "/api/checkout"], + [2, "/api/orders"] + ], + "total": 2, + "size": 2 +} +``` + +These results are automatically transformed into a list of maps for use in templates and are available in `ctx.ppl_query_results`: + +```json +[ + {"error_count": 1, "endpoint": "/api/checkout"}, + {"error_count": 2, "endpoint": "/api/orders"} +] +``` + +## Creating a PPL monitor using the API + +The following example creates a PPL monitor with both trigger types: + +```json +POST _plugins/_alerting/monitors +{ + "name": "PPL Error Rate Monitor", + "type": "monitor", + "monitor_type": "ppl_monitor", + "enabled": true, + "schedule": { + "period": { + "unit": "MINUTES", + "interval": 5 + } + }, + "inputs": [ + { + "ppl_input": { + "query": "source = application_logs | where level = 'ERROR' | stats count() as error_count by service", + "query_language": "ppl" + } + } + ], + "triggers": [ + { + "ppl_trigger": { + "name": "Too many errors", + "severity": "1", + "type": "number_of_results", + "num_results_condition": ">", + "num_results_value": 1, + "actions": [ + { + "name": "Notify ops channel", + "destination_id": "your-destination-id", + "message_template": { + "source": {% raw %}"Monitor {{ctx.monitor.name}} detected {{ctx.ppl_query_results.size}} services with errors."{% endraw %} + }, + "subject_template": { + "source": "Alert: High Error Rate Detected" + } + } + ] + } + }, + { + "ppl_trigger": { + "name": "Critical service errors", + "severity": "1", + "type": "custom", + "custom_condition": "where error_count > 1", + "actions": [ + { + "name": "Page oncall", + "destination_id": "your-destination-id", + "message_template": { + "source": {% raw %}"Critical error threshold exceeded:\n{{#ctx.ppl_query_results}}\n Service: {{service}}, Errors: {{error_count}}\n{{/ctx.ppl_query_results}}"{% endraw %} + }, + "subject_template": { + "source": "CRITICAL: Service Error Threshold Exceeded" + } + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The response confirms that the monitor was created and returns its `_id`. The monitor runs on its configured schedule, and each run evaluates the triggers against the latest query results. When a trigger's condition is met, it fires and runs its actions. + +## Testing a PPL monitor + +To run a monitor immediately instead of waiting for its next scheduled run, use the Execute API with the monitor ID. Add `?dryrun=true` to evaluate the triggers without creating alerts or running actions: + +```json +POST _plugins/_alerting/monitors/<monitor_id>/_execute?dryrun=true +``` +{% include copy-curl.html %} + +The response reports the query results and, for each trigger, whether it fired. The `triggered` field indicates whether each trigger's condition was met. For custom condition triggers, `ppl_query_results` contains the rows that matched the condition: + +```json +{ + "monitor_name": "PPL Error Rate Monitor", + "period_start": 1787067810953, + "period_end": 1787068110953, + "error": null, + "input_results": { + "results": [], + "ppl_query_results": [ + { "error_count": 1, "service": "checkout" }, + { "error_count": 2, "service": "orders" } + ], + "ppl_num_results": 2, + "error": null + }, + "trigger_results": { + "too_many_errors": { + "name": "Too many errors", + "triggered": true, + "action_results": {}, + "ppl_query_results": [], + "error": null + }, + "critical_service_errors": { + "name": "Critical service errors", + "triggered": true, + "action_results": {}, + "ppl_query_results": [ + { "error_count": 2, "service": "orders" } + ], + "error": null + } + } +} +``` + +## Settings + +OpenSearch supports the following PPL monitor settings. All settings are dynamic, so you can change them without restarting your cluster: + +- `plugins.alerting.monitor.max_ppl_triggers` (Dynamic, integer): The maximum number of triggers allowed per PPL monitor. This is also the highest accepted value, so you can only lower it. Default is `10`. + +- `plugins.alerting.ppl_query_max_execution_duration` (Dynamic, time unit): The maximum execution time allowed for a PPL query during monitor execution. Default is `30s`. + +- `plugins.alerting.ppl_monitor_max_query_length` (Dynamic, long): The maximum number of characters for a PPL query. Default is `2000`. + +- `plugins.alerting.ppl_query_results_max_datarows` (Dynamic, long): The maximum number of data rows to retrieve when executing a PPL query. Default is `10000`. + +- `plugins.alerting.ppl_query_results_max_size` (Dynamic, long): The maximum estimated size, in bytes, of query results stored in alerts and notifications. If the results exceed this size, the alert replaces them with a message stating that the PPL query results were too large. Default is `3000`. + diff --git a/_observing-your-data/alerting/restore.md b/_observing-your-data/alerting/restore.md new file mode 100644 index 00000000..1c1e3fa0 --- /dev/null +++ b/_observing-your-data/alerting/restore.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Restoring monitors and alerts from a snapshot +parent: Alerting +nav_order: 55 +--- + +# Restoring monitors and alerts from a snapshot +**Introduced 3.10** +{: .label .label-purple } + +OpenSearch stores alerting monitors and workflows in the `.opendistro-alerting-config` system index and alerts, findings, and comments in separate system indexes. When you restore these indexes from a snapshot using the [Restore Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/restore-snapshot/), for example, to another cluster, monitors continue to run in that cluster if you prepare the cluster first and restore the indexes as described in [Restoring the alerting indexes](#restoring-the-alerting-indexes). + +This page uses _original cluster_ for the cluster that took the snapshot and _new cluster_ for the cluster that you restore to. + +## Indexes to restore + +The following table lists the alerting indexes and whether to restore them. + +| Index | Contents | Whether to restore | +| :--- | :--- | :--- | +| `.opendistro-alerting-config` | Monitors and workflows | Yes. | +| `.opendistro-alerting-config-sharing` | The users, roles, and backend roles that each monitor and workflow is shared with | Yes, if the original cluster used [resource sharing]({{site.url}}{{site.baseurl}}/security/access-control/resources/). See [Restoring monitor sharing](#restoring-monitor-sharing). | +| `.opendistro-alerting-alerts` | Active alerts | Yes, to retain active alerts. | +| `.opendistro-alerting-alert-history-*` | Completed alerts | Yes, to retain alert history. | +| `.opensearch-alerting-finding-history-*` | Findings | Yes, to retain findings. | +| `.opensearch-alerting-comments-history-*` | Alert comments, if comments are enabled | Yes, to retain comments. | +| `.opensearch-alerting-queries*` | The queries that document-level monitors run | No. OpenSearch rebuilds it from the monitors. | +| `.opensearch-alerting-config-lock` | Temporary locks held while monitors run | No. | + +Monitor actions send messages through notification channels, which OpenSearch stores in the `.opensearch-notifications-config` system index. If your monitors have actions, also restore that index so that the channels exist in the new cluster. + +## Preparing the new cluster + +Restoring alerting indexes restores your monitors but not the settings and roles that control who can access them. Complete the following steps in the new cluster before you restore the indexes. + +The original cluster might be unavailable when you need to restore its monitors and alerts. Record its settings and back up its security configuration as part of your recovery plan. +{: .tip } + +### Copying settings from the original cluster + +The following table lists the settings that control access to monitors and the retention of alert history. Configure these settings in the new cluster using the values from the original cluster. + +| Setting | What it controls | +| :--- | :--- | +| `plugins.alerting.filter_by_backend_roles` | Whether users can view only the monitors created by users who share a backend role. For more information, see [Limit access by backend role]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/#advanced-limit-access-by-backend-role). | +| `plugins.alerting.filter_by_backend_roles_access_strategy` | How backend roles are compared when `plugins.alerting.filter_by_backend_roles` is `true`. | +| `plugins.security.resource_sharing.enabled` | Whether [resource sharing]({{site.url}}{{site.baseurl}}/security/access-control/resources/) is enabled. | +| `plugins.security.resource_sharing.protected_types` | The resource types that use resource sharing. For alerting, these are `monitor` and `alerting-workflow`. | +| `plugins.alerting.alert_history_retention_period`<br>`plugins.alerting.finding_history_retention_period`<br>`plugins.alerting.comments_history_retention_period` | The amount of time for which history indexes are retained. | + +Restored history indexes that are older than the retention period are deleted. + +To view these values in the original cluster, including values set in `opensearch.yml`, send the following request: + +```json +GET /_cluster/settings?include_defaults=true&filter_path=*.plugins.alerting.filter_by_backend_roles*,*.plugins.alerting.*_retention_period,*.plugins.security.resource_sharing +``` +{% include copy-curl.html %} + +If a setting in the new cluster doesn't match its value in the original cluster, users' access to monitors and alerts in the new cluster differs from their access in the original cluster and no error is reported. For example, if `plugins.alerting.filter_by_backend_roles` is `true` in the original cluster but `false` in the new cluster, every user with alerting permissions can view every monitor and its alerts. + +### Copying roles and role mappings from the original cluster + +Monitors store the roles and backend roles of the user who created them and run with the permissions that those roles have in the new cluster. Copy the roles and role mappings, with the same permissions, from the original cluster to the new cluster. To do this, upload `roles.yml` and `roles_mapping.yml` from a backup of your security configuration using `securityadmin.sh`, or use the [Security APIs]({{site.url}}{{site.baseurl}}/security/api/). For more information about backing up your security configuration, see [A word of caution]({{site.url}}{{site.baseurl}}/security/configuration/security-admin/#a-word-of-caution). If a role grants more permissions in the new cluster, a monitor can read data that its creator couldn't read in the original cluster. + +If the original cluster used resource sharing, a restored monitor is shared with a user, role, or backend role only if a user, role, or backend role with the same name exists in the new cluster. Backend roles provided by an authentication backend, such as LDAP or SAML, require the new cluster to use the same backend. + +## Restoring the alerting indexes + +Restore the alerting indexes to a cluster in which no monitors have been created. If the new cluster contains monitors, it already contains a `.opendistro-alerting-config` index. OpenSearch can't restore an index when an open index with the same name exists, so the restore operation fails. To restore monitors and alerts, follow these steps: + +1. Ensure that you have permission to restore system indexes. By default, a REST admin (a user mapped to a role in `plugins.security.restapi.roles_enabled`) can restore every alerting index that you need to restore, as listed in [Indexes to restore](#indexes-to-restore). To restore notification channels, a REST admin must add `.opensearch-notifications-config` to the `plugins.security.system_indices.restore.indices` setting. For more information, see [Who can restore system indexes]({{site.url}}{{site.baseurl}}/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore/#who-can-restore-system-indexes). +1. Find the names of the history indexes in the snapshot. History index names include a date and a number, such as `.opendistro-alerting-alert-history-2026.10.27-1`. To restore all of them, use a pattern such as `.opendistro-alerting-alert-history-*`. A REST admin can use a pattern only if it is no broader than an entry in the `plugins.security.system_indices.restore.indices` setting. Otherwise, name each index. To list the indexes in the snapshot, use the [Get Snapshot API]({{site.url}}{{site.baseurl}}/api-reference/snapshots/get-snapshot/): + + ```json + GET /_snapshot/my-repository/snapshot-1 + ``` + {% include copy-curl.html %} + +1. Use one request to restore the alerting indexes and the data indexes that your monitors query. Name each alerting system index or match it using a pattern, as described in the previous step: + + ```json + POST /_snapshot/my-repository/snapshot-1/_restore + { + "indices": "my-logs,.opendistro-alerting-config,.opendistro-alerting-alerts,.opendistro-alerting-alert-history-*,.opensearch-alerting-finding-history-*", + "include_global_state": false + } + ``` + {% include copy-curl.html %} + + Add any of the following indexes that apply to your cluster to the same request: + + - `.opendistro-alerting-config-sharing`, if the original cluster used resource sharing + - `.opensearch-alerting-comments-history-*`, to retain alert comments + - `.opensearch-notifications-config`, if your monitors have actions + + Monitors start running as soon as `.opendistro-alerting-config` is restored. If you restore the other alerting indexes in a later request, the restore might fail or alerts might be lost. A monitor can't query a data index that doesn't exist in the new cluster. Restore the data indexes from the same snapshot as `.opendistro-alerting-config` so that each document-level monitor resumes from the last document that it evaluated in the original cluster, as described in [Document-level monitors](#document-level-monitors). + +1. Verify that the monitors were restored by using the [Search Monitors API]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/#search-monitors): + + ```json + GET /_plugins/_alerting/monitors/_search + { + "query": { + "match_all": {} + } + } + ``` + {% include copy-curl.html %} + + The response lists the restored monitors. + +## Restoring monitor sharing + +If you restore `.opendistro-alerting-config` without `.opendistro-alerting-config-sharing`, users other than a super admin lose access to the restored monitors, including the users who created them. To restore their access, restore `.opendistro-alerting-config-sharing` from the same snapshot. Its records refer to monitors and workflows by ID, and a restore retains the IDs. Don't use the [Migrate API]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/#migrate-legacy-sharing-metadata) for this, because it shares each monitor with its creator's backend roles and doesn't restore the original sharing. + +## Document-level monitors + +A document-level monitor records the last document that it evaluated in each shard of its data index and resumes from that document after a restore. On its first run in the new cluster, the monitor might not evaluate documents that were written to its data indexes before that run. After the first run, the monitor evaluates every new document. To ensure that every document is evaluated, wait until each document-level monitor has run once in the new cluster before writing new documents to its data indexes. \ No newline at end of file diff --git a/_observing-your-data/alerting/security.md b/_observing-your-data/alerting/security.md index 2dc1db33..7555749a 100644 --- a/_observing-your-data/alerting/security.md +++ b/_observing-your-data/alerting/security.md @@ -1,7 +1,7 @@ --- layout: default title: Alerting security -nav_order: 10 +nav_order: 40 parent: Alerting has_children: false redirect_from: @@ -12,13 +12,13 @@ redirect_from: If you use the Security plugin alongside alerting, you might want to limit certain users to certain actions. For example, you might want some users to only be able to view and acknowledge alerts, while others can modify monitors and destinations. +To control access to individual monitors and workflows using resource sharing, see [Alerting resource access control]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/alerting-access-control/). ## Basic permissions The Security plugin has three built-in roles that cover most alerting use cases: `alerting_read_access`, `alerting_ack_alerts`, and `alerting_full_access`. For descriptions of each, see [Predefined roles]({{site.url}}{{site.baseurl}}/security/access-control/users-roles#predefined-roles). -If these roles don't meet your needs, mix and match individual alerting [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/) to suit your use case. Each action corresponds to an operation in the REST API. For example, the `cluster:admin/opensearch/alerting/destination/delete` permission lets you delete destinations. - +If these roles don't meet your needs, mix and match individual alerting [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/) to suit your use case. Each action corresponds to an operation in the REST API. For example, the `cluster:admin/opendistro/alerting/monitor/delete` permission lets you delete monitors. ## How monitors access data @@ -33,24 +33,24 @@ Later, the user `psantos` wants to edit the monitor to run every two hours, but After making the change, the monitor now runs with the same permissions as `psantos`, including any [document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/) queries, [excluded fields]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security/), and [masked fields]({{site.url}}{{site.baseurl}}/security/access-control/field-masking/). If you use an extraction query to define your monitor, use the **Run** button to ensure that the response includes the fields you need. -Once a monitor is created, the Alerting plugin will continue executing the monitor, even if the user who created the monitor has their permissions removed. Only a user with the correct cluster permissions can manually disable or delete a monitor to stop it from executing: +Once a monitor is created, OpenSearch continues running the monitor, even if the user who created the monitor has their permissions removed. Only a user with the correct cluster permissions can manually disable or delete a monitor to stop it from executing: - Disable a monitor: `cluster:admin/opendistro/alerting/monitor/write` - Delete a monitor: `cluster:admin/opendistro/alerting/monitor/delete` -If your monitor's trigger has notifications configured, the Alerting plugin continues to send out notifications regardless of destination type. To stop notifications, a user must manually delete them in the trigger's actions. +If your monitor's trigger has notifications configured, OpenSearch continues to send notifications regardless of destination type. To stop notifications, a user must manually delete them in the trigger's actions. ### A note on alerts and fine-grained access control -When a trigger generates an alert, the monitor configuration, the alert itself, and any notification that is sent to a channel may include metadata describing the index being queried. By design, the plugin must extract the data and store it as metadata outside of the index. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security) (FLS) access controls are designed to protect the data in the index. But once the data is stored outside the index as metadata, users with access to the monitor configurations, alerts, and their notifications will be able to view this metadata and possibly infer the contents and quality of data in the index, which would otherwise be concealed by DLS and FLS access control. +When a trigger generates an alert, the monitor configuration, the alert itself, and any notification that is sent to a channel may include metadata describing the index being queried. By design, Alerting must extract the data and store it as metadata outside of the index. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security/) (FLS) access controls are designed to protect the data in the index. But once the data is stored outside the index as metadata, users with access to the monitor configurations, alerts, and their notifications will be able to view this metadata and possibly infer the contents and quality of data in the index, which would otherwise be concealed by DLS and FLS access control. To reduce the chances of unintended users viewing metadata that could describe an index, we recommend that administrators enable role-based access control and keep these kinds of design elements in mind when assigning permissions to the intended group of users. See [Limit access by backend role](#advanced-limit-access-by-backend-role) for details. ## (Advanced) Limit access by backend role -Out of the box, the alerting plugin has no concept of ownership. For example, if you have the `cluster:admin/opensearch/alerting/monitor/write` permission, you can edit *all* monitors, regardless of whether you created them. If a small number of trusted users manage your monitors and destinations, this lack of ownership generally isn't a problem. A larger organization might need to segment access by backend role. +By default, Alerting has no concept of ownership. For example, if you have the `cluster:admin/opensearch/alerting/monitor/write` permission, you can edit *all* monitors, regardless of whether you created them. If a small number of trusted users manage your monitors and destinations, this lack of ownership generally isn't a problem. A larger organization might need to segment access by backend role. -First, make sure that your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to add them manually with a create user operation. To add a backend role to a create user request, follow the [Create user]({{site.url}}{{site.baseurl}}/security/access-control/api#create-user) instructions in the Security plugin API documentation. +First, make sure that your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to add them manually with a create user operation. To add a backend role to a create user request, follow the [Create user]({{site.url}}{{site.baseurl}}/security/api/users/create-user/) instructions in the Security plugin API documentation. Next, enable the following setting: @@ -69,6 +69,32 @@ Now when users view alerting resources in OpenSearch Dashboards (or make REST AP If `jdoe` creates a monitor, `jroe` can see and modify it, but `psantos` can't. If that monitor generates an alert, the situation is the same: `jroe` can see and acknowledge it, but `psantos` can't. If `psantos` creates a destination, `jdoe` and `jroe` can't see or modify it. +### Configuring backend role access + +The `plugins.alerting.filter_by_backend_roles_access_strategy` setting controls how a user's backend roles are compared with the backend roles associated with a monitor to determine whether the user can access the monitor. + +This setting supports the following values: + +- `intersect` (Default) -- Users have access to notifications objects if they share at least one backend role with the user who created the object. +- `exact` -- Users have access to notifications objects if they have exactly the same (with no additional) backend roles as the user who created the object. +- `all` -- Users have access to notifications objects if their backend roles contain all of the backend roles of the user who created the object. + +The following example uses a monitor associated with the `analyst` and `human-resources` backend roles and four users with different backend roles: + +- User `jdoe` has the backend role `analyst`. +- User `jroe` has the backend roles `analyst` and `supervisor`. +- User `psantos` has the backend roles `analyst` and `human-resources`. +- User `bwayne` has the backend roles `analyst`, `human-resources`, and `batman`. + +The following table shows whether each user can access the monitor for each setting value. + +| User | `intersect` | `exact` | `all` +:-- | :-- | :-- | :-- +`jdoe` | Has access | No access | No access +`jroe` | Has access | No access | No access +`psantos` | Has access | Has access | Has access +`bwayne` | Has access | No access | Has access + <!-- ## (Advanced) Limit access by individual If you only want users to be able to see and modify their own monitors and destinations, duplicate the `alerting_full_access` role and add the following [DLS query]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/) to it: @@ -115,7 +141,8 @@ Regular user | No | Don’t update the backend roles on the monitor. - If the user tries to associate roles that they don't have permission to use, it will throw an exception. {: .note } -To create an RBAC role, follow instructions in the Security plugin API documentation to [Create role]({{site.url}}{{site.baseurl}}/security/access-control/api#create-role). +To create an RBAC role, follow instructions in the Security plugin API documentation to [Create role]({{site.url}}{{site.baseurl}}/security/api/roles/create-role/). + ### Create a monitor with an RBAC role When you create a monitor with the Alerting API, you can specify the RBAC roles at the bottom of the request body. Use the `rbac_roles` parameter. @@ -123,10 +150,9 @@ When you create a monitor with the Alerting API, you can specify the RBAC roles The following sample shows the RBAC roles specified by the RBAC parameter: ```json -... +... "rbac_roles": ["role1", "role2"] } ``` To see a full request sample, see [Create a query-level monitor]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/api/#create-a-query-level-monitor). - diff --git a/_observing-your-data/alerting/settings.md b/_observing-your-data/alerting/settings.md index c50636b3..ba8bd6cf 100644 --- a/_observing-your-data/alerting/settings.md +++ b/_observing-your-data/alerting/settings.md @@ -1,14 +1,15 @@ --- layout: default -title: Management +title: Alerting settings parent: Alerting -nav_order: 5 +nav_order: 70 redirect_from: - /monitoring-plugins/alerting/settings/ --- -# Management +# Alerting settings +The following sections describe alerting indexes and settings. ## Alerting indexes @@ -18,45 +19,90 @@ Index | Purpose :--- | :--- `.opendistro-alerting-alerts` | Stores ongoing alerts. `.opendistro-alerting-alert-history-<date>` | Stores a history of completed alerts. -`.opendistro-alerting-config` | Stores monitors, triggers, and destinations. [Take a snapshot]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore) of this index to back up your alerting configuration. +`.opendistro-alerting-config` | Stores monitors, triggers, and destinations. [Take a snapshot]({{site.url}}{{site.baseurl}}/opensearch/snapshots/snapshot-restore/) of this index to back up your alerting configuration. To restore it, see [Restoring monitors and alerts from a snapshot]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/restore/). `.opendistro-alerting-alert-history-write` (alias) | Provides a consistent URI for the `.opendistro-alerting-alert-history-<date>` index. All alerting indexes are hidden by default. For a summary, make the following request: -``` +```json GET _cat/indices?expand_wildcards=open,hidden ``` +{% include copy-curl.html %} - -## Alerting settings +## Settings We don't recommend changing these settings; the defaults should work well for most use cases. All settings are available using the OpenSearch `_cluster/settings` API. None require a restart, and all can be marked `persistent` or `transient`. To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). -Setting | Default | Description -:--- | :--- | :--- -`plugins.scheduled_jobs.enabled` | true | Whether the alerting plugin is enabled or not. If disabled, all monitors immediately stop running. -`plugins.alerting.index_timeout` | 60s | The timeout for creating monitors and destinations using the REST APIs. -`plugins.alerting.request_timeout` | 10s | The timeout for miscellaneous requests from the plugin. -`plugins.alerting.action_throttle_max_value` | 24h | The maximum amount of time you can set for action throttling. By default, this value displays as 1440 minutes in OpenSearch Dashboards. -`plugins.alerting.input_timeout` | 30s | How long the monitor can take to issue the search request. -`plugins.alerting.bulk_timeout` | 120s | How long the monitor can write alerts to the alert index. -`plugins.alerting.alert_backoff_count` | 3 | The number of retries for writing alerts before the operation fails. -`plugins.alerting.alert_backoff_millis` | 50ms | The amount of time to wait between retries---increases exponentially after each failed retry. -`plugins.alerting.alert_history_rollover_period` | 12h | How frequently to check whether the `.opendistro-alerting-alert-history-write` alias should roll over to a new history index and whether the Alerting plugin should delete any history indexes. -`plugins.alerting.move_alerts_backoff_millis` | 250 | The amount of time to wait between retries---increases exponentially after each failed retry. -`plugins.alerting.move_alerts_backoff_count` | 3 | The number of retries for moving alerts to a deleted state after their monitor or trigger has been deleted. -`plugins.alerting.monitor.max_monitors` | 1000 | The maximum number of monitors users can create. -`plugins.alerting.alert_history_max_age` | 30d | The oldest document to store in the `.opendistro-alert-history-<date>` index before creating a new index. If the number of alerts in this time period does not exceed `alert_history_max_docs`, alerting creates one history index per period (e.g. one index every 30 days). -`plugins.alerting.alert_history_max_docs` | 1000 | The maximum number of alerts to store in the `.opendistro-alert-history-<date>` index before creating a new index. -`plugins.alerting.alert_history_enabled` | true | Whether to create `.opendistro-alerting-alert-history-<date>` indexes. -`plugins.alerting.alert_history_retention_period` | 60d | The amount of time to keep history indexes before automatically deleting them. -`plugins.alerting.destination.allow_list` | ["chime", "slack", "custom_webhook", "email", "test_action"] | The list of allowed destinations. If you don't want to allow users to a certain type of destination, you can remove it from this list, but we recommend leaving this setting as-is. -`plugins.alerting.filter_by_backend_roles` | "false" | Restricts access to monitors by backend role. See [Alerting security]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/). -`plugins.alerting.remote_monitoring_enabled` | "false" | Toggles whether cluster metrics monitors support executing against remote clusters. -`plugins.scheduled_jobs.sweeper.period` | 5m | The alerting feature uses its "job sweeper" component to periodically check for new or updated jobs. This setting is the rate at which the sweeper checks to see if any jobs (monitors) have changed and need to be rescheduled. -`plugins.scheduled_jobs.sweeper.page_size` | 100 | The page size for the sweeper. You shouldn't need to change this value. -`plugins.scheduled_jobs.sweeper.backoff_millis` | 50ms | The amount of time the sweeper waits between retries---increases exponentially after each failed retry. -`plugins.scheduled_jobs.sweeper.retry_count` | 3 | The total number of times the sweeper should retry before throwing an error. -`plugins.scheduled_jobs.request_timeout` | 10s | The timeout for the request that sweeps shards for jobs. +OpenSearch supports the following alerting settings: + +- `plugins.scheduled_jobs.enabled` (Dynamic, Boolean): Whether the Alerting plugin is enabled or not. If disabled, all monitors immediately stop running. Default is `true`. + +- `plugins.alerting.index_timeout` (Dynamic, time unit): The timeout for creating monitors and destinations using the REST APIs. Default is `60s`. + +- `plugins.alerting.request_timeout` (Dynamic, time unit): The timeout for miscellaneous requests from the plugin. Default is `10s`. + +- `plugins.alerting.action_throttle_max_value` (Dynamic, time unit): The maximum amount of time you can set for action throttling. By default, this value displays as 1440 minutes in OpenSearch Dashboards. Default is `24h`. + +- `plugins.alerting.input_timeout` (Dynamic, time unit): How long the monitor can take to issue the search request. Default is `30s`. + +- `plugins.alerting.bulk_timeout` (Dynamic, time unit): How long the monitor can write alerts to the alert index. Default is `120s`. + +- `plugins.alerting.alert_backoff_count` (Dynamic, integer): The number of retries for writing alerts before the operation fails. Default is `2`. + +- `plugins.alerting.alert_backoff_millis` (Dynamic, time unit): The amount of time to wait between retries---increases exponentially after each failed retry. Default is `50ms`. + +- `plugins.alerting.alert_history_rollover_period` (Dynamic, time unit): How frequently to check whether the `.opendistro-alerting-alert-history-write` alias should roll over to a new history index and whether the Alerting plugin should delete any history indexes. Default is `12h`. + +- `plugins.alerting.move_alerts_backoff_millis` (Dynamic, time unit): The amount of time to wait between retries---increases exponentially after each failed retry. Default is `250ms`. + +- `plugins.alerting.move_alerts_backoff_count` (Dynamic, integer): The number of retries for moving alerts to a deleted state after their monitor or trigger has been deleted. Default is `3`. + +- `plugins.alerting.monitor.max_monitors` (Dynamic, integer): The maximum number of monitors users can create. Default is `1000`. + +- `plugins.alerting.alert_history_max_age` (Dynamic, time unit): The oldest document to store in the `.opendistro-alert-history-<date>` index before creating a new index. If the number of alerts in this time period does not exceed `alert_history_max_docs`, alerting creates one history index per period (for example, one index every 30 days). Default is `30d`. + +- `plugins.alerting.alert_history_max_docs` (Dynamic, long): The maximum number of alerts to store in the `.opendistro-alert-history-<date>` index before creating a new index. Default is `1000`. + +- `plugins.alerting.alert_history_enabled` (Dynamic, Boolean): Whether to create `.opendistro-alerting-alert-history-<date>` indexes. Default is `true`. + +- `plugins.alerting.alert_history_retention_period` (Dynamic, time unit): The amount of time to store history indexes before automatically deleting them. Default is `60d`. + +- `plugins.alerting.destination.allow_list` (Dynamic, list): The list of allowed destinations. If you don't want to allow users to a certain type of destination, you can remove it from this list, but we recommend leaving this setting as-is. Default is `["chime", "slack", "custom_webhook", "email", "test_action"]`. + +- `plugins.alerting.filter_by_backend_roles` (Dynamic, Boolean): Restricts access to monitors by backend role. See [Alerting security]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/). Default is `false`. + +- `plugins.alerting.filter_by_backend_roles_access_strategy` (Dynamic, string): Controls how user backend roles are compared with the backend roles associated with a monitor to determine whether a user can access the monitor. Valid values are `all`, `exact`, and `intersect`. See [Alerting security documentation on filtering by backend role]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/security/#advanced-limit-access-by-backend-role). Default is `intersect`. + +- `plugins.alerting.cross_cluster_monitoring_enabled` (Dynamic, Boolean): Toggles whether cluster metrics monitors support running against remote clusters. Default is `true`. + +- `plugins.scheduled_jobs.sweeper.period` (Dynamic, time unit): The alerting feature uses its "job sweeper" component to periodically check for new or updated jobs. This setting is the rate at which the sweeper checks to see if any jobs (monitors) have changed and need to be rescheduled. Default is `5m`. + +- `plugins.scheduled_jobs.sweeper.page_size` (Dynamic, integer): The page size for the sweeper. You shouldn't need to change this value. Default is `100`. + +- `plugins.scheduled_jobs.sweeper.backoff_millis` (Dynamic, time unit): The amount of time the sweeper waits between retries---increases exponentially after each failed retry. Default is `50ms`. + +- `plugins.scheduled_jobs.retry_count` (Dynamic, integer): The total number of times the sweeper should retry before throwing an error. Default is `3`. + +- `plugins.scheduled_jobs.request_timeout` (Dynamic, time unit): The timeout for the request that sweeps shards for jobs. Default is `10s`. + +- `plugins.alerting.comments_enabled` (Dynamic, Boolean): Enables or disables comments for the Alerting plugin. Default is `true`. + +- `plugins.alerting.comments_history_max_docs` (Dynamic, long): The maximum number of comments to store in the `.opensearch-alerting-comments-history-<date>` index before creating a new index. Default is `1000`. + +- `plugins.alerting.comments_history_max_age` (Dynamic, time unit): The oldest document to store in an `.opensearch-alerting-comments-history-<date>` index before creating a new one. If the number of comments in the specified time period does not exceed `comments_history_max_docs`, then 1 index is created per period (for example, 1 every 30 days). Default is `30d`. + +- `plugins.alerting.comments_history_rollover_period` (Dynamic, time unit): How often to determine whether the `.opensearch-alerting-comments-history-write` alias should roll over to a new index and delete old comment history indexes. Default is `12h`. + +- `plugins.alerting.comments_history_retention_period` (Dynamic, time unit): The amount of time to keep comment history indexes before automatic deletion. Default is `60d`. + +- `plugins.alerting.max_comment_character_length` (Dynamic, long): The maximum character length of a comment. Default is `2000`. + +- `plugins.alerting.max_comments_per_alert` (Dynamic, long): The maximum number of comments that can be posted on an alert. Default is `500`. + +- `plugins.alerting.max_comments_per_notification` (Dynamic, integer): The maximum number of comments per alert to include in the `ctx` Mustache template variable for alert notifications. Default is `3`. + +### PPL monitor settings + +For information about PPL monitor settings, see [PPL monitor settings]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/ppl-monitors/). \ No newline at end of file diff --git a/_observing-your-data/alerting/triggers.md b/_observing-your-data/alerting/triggers.md index c89f1c45..5742fa96 100644 --- a/_observing-your-data/alerting/triggers.md +++ b/_observing-your-data/alerting/triggers.md @@ -6,7 +6,7 @@ grand_parent: Alerting parent: Monitors --- -# Triggers +# Alerting triggers How you create a trigger differs depending on the monitor method selected when the monitor was created. The monitor methods are **Visual editor**, **Extraction query editor**, and **Anomaly detector**. Learn more about each type in the following sections. @@ -15,7 +15,9 @@ How you create a trigger differs depending on the monitor method selected when t To create a trigger: 1. In the **Create monitor** window, select **Add trigger**. +<!-- vale off --> 2. Enter the trigger name, severity level, and trigger condition. Severity levels, which range from 1 (highest) to 5 (lowest) help manage alerts. For example, a trigger with a high severity level (for example, 1 or 2) may notify a specific individual, whereas a trigger with a low severity level (4 or 5) might notify a chat room. Trigger conditions include "IS ABOVE," "IS BELOW," and "IS EXACTLY." +<!-- vale on --> Query-level monitors run your trigger's script once against the query's results, and bucket-level monitors run your trigger's script on each bucket. Create a trigger that best fits the monitor method. To run multiple scripts, you must create multiple triggers. {: .note} @@ -38,7 +40,7 @@ Now you can create the trigger condition and specify the tag name. This creates ## Extraction query editor -For a query-level monitor, specify a Painless script that returns `true` or `false`. Painless is the default OpenSearch scripting language and has a syntax similar to Groovy. +For a query-level monitor, specify a Painless script that returns `true` or `false`. Painless is the default OpenSearch scripting language and has a syntax similar to Groovy. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). Trigger condition scripts revolve around the `ctx.results[0]` variable, which corresponds to the extraction query response. For example, the script might reference `ctx.results[0].hits.total.value` or `ctx.results[0].hits.hits[i]._source.error_code`. @@ -113,27 +115,94 @@ if (score > 99) { #### Trigger variables Variable | Data type | Description -:--- | :--- | : --- +:--- | :--- | :--- `ctx.trigger.id` | String | The trigger ID. `ctx.trigger.name` | String | The trigger name. `ctx.trigger.severity` | String | The trigger severity. `ctx.trigger.condition`| Object | Contains the Painless script used when the monitor was created. -`ctx.trigger.condition.script.source` | String | The language used to define the script. Must be Painless. -`ctx.trigger.condition.script.lang` | String | The script used to define the trigger. +`ctx.trigger.condition.script.source` | String | The script used to define the trigger. +`ctx.trigger.condition.script.lang` | String | The language used to define the script. Must be Painless. `ctx.trigger.actions`| Array | An array with one element that contains information about the action the monitor needs to trigger. #### Other variables Variable | Data type | Description -:--- | :--- : :--- -`ctx.results` | Array | An array with one element (`ctx.results[0]`). Contains the query results. This variable is empty if the trigger was unable to retrieve results. See `ctx.error`. +:--- | :--- | :--- +`ctx.results` | Array | An array with one element (`ctx.results.0`). Contains the query results. This variable is empty if the trigger is unable to retrieve results. See `ctx.error`. `ctx.last_update_time` | Milliseconds | Unix epoch time of when the monitor was last updated. `ctx.periodStart` | String | Unix timestamp for the beginning of the period during which the alert was triggered. For example, if a monitor runs every 10 minutes, a period might begin at 10:40 and end at 10:50. `ctx.periodEnd` | String | The end of the period during which the alert triggered. `ctx.error` | String | The error message displayed if the trigger was unable to retrieve results or could not be evaluated, typically due to a compile error or null pointer exception. Null otherwise. `ctx.alert` | Object | The current, active alert (if it exists). Includes `ctx.alert.id`, `ctx.alert.version`, and `ctx.alert.isAcknowledged`. Null if no alert is active. Only available with query-level monitors. -`ctx.dedupedAlerts` | Object | Alerts that have been triggered. OpenSearch keeps the existing alert to prevent the plugin from creating endless numbers of the same alert. Only available with bucket-level monitors. -`ctx.newAlerts` | Object | Newly created alerts. Only available with bucket-level monitors. -`ctx.completedAlerts` | Object | Alerts that are no longer ongoing. Only available with bucket-level monitors. -`bucket_keys` | String | Comma-separated list of the monitor's bucket key values. Available only for `ctx.dedupedAlerts`, `ctx.newAlerts`, and `ctx.completedAlerts`. Accessed through `ctx.dedupedAlerts[0].bucket_keys`. -`parent_bucket_path` | String | The parent bucket path of the bucket that triggered the alert. Accessed through `ctx.dedupedAlerts[0].parent_bucket_path`. +`ctx.alerts` | Array | Newly created alerts. Includes the `ctx.alerts.0.finding_ids` that triggered the alert and the `ctx.alerts.0.related_doc_ids` associated with the findings. Only available with document-level monitors. +`ctx.dedupedAlerts` | Array | Triggered alerts. OpenSearch keeps the existing alert to prevent the monitor from repeatedly creating the same alert. Only available with bucket-level monitors. +`ctx.newAlerts` | Array | Newly created alerts. Only available with bucket-level monitors. +`ctx.completedAlerts` | Array | Completed or expired alerts. Only available with bucket-level monitors. +`bucket_keys` | String | A comma-separated list of the monitor's bucket key values. Available only for `ctx.dedupedAlerts`, `ctx.newAlerts`, and `ctx.completedAlerts`. Accessed through the `ctx.dedupedAlerts.0.bucket_keys` variable. +`parent_bucket_path` | String | The parent bucket path of the bucket that triggered the alert. Accessed through `ctx.dedupedAlerts.0.parent_bucket_path`. +`associated_queries` | Array | An array of document-level monitor queries that triggered the creation of the finding associated with the alert. Only available with document-level monitors. Accessed through the `ctx.alerts.0.associated_queries` variable. +`sample_documents` | Array | An array of sample documents that matched the monitor query. Only available with bucket- and document-level monitors. Accessed through the `ctx.newAlerts.0.sample_documents` and `ctx.alerts.0.sample_documents` variables, respectively. + +#### The `associated_queries` and `sample_documents` variables + +Per bucket and per document monitors support printing sample documents in notification messages. Per document monitors support printing the list of queries that triggered the creation of the finding associated with the alert. When the monitor runs, it adds each new alert to the `ctx` variables, for example, `newAlerts` for per bucket monitors and `alerts` for per document monitors. Each alert has its own list of `sample_documents`, and each per document monitor alert has its own list of `associated_queries`. The message template can be formatted to iterate through the list of alerts, the list of `associated_queries`, and the `sample_documents` for each alert. + +An alerting monitor uses the permissions of the user that created it. Be mindful of the Notifications channel to which alert messages are sent and the content of the message mustache template. To learn more about alerting security, see [Alerting security]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/security/). +{: .note} + +#### Sample document variables + +Variable | Data type | Description +:--- | :--- | :--- +`_index` | String | The index containing the sample document. +`_id` | String | The sample document ID. +`_score` | Float | A positive 32-bit floating-point number illustrating the relevance of the returned document. +`_source` | Object | The JSON payload of the sample document. + +##### Mustache template example + +{% raw %} +```groovy +Alerts: +{{#ctx.alerts}} + RULES + {{#associated_queries}} + Name: {{name}} + Id: {{id}} + Tags: {{tags}} + ------------------------ + {{/associated_queries}} +{{/ctx.alerts}} +``` +{% endraw %} + +#### Associated query variables + +Variable | Data type | Description +:--- | :--- | :--- +`id` | String | The ID of the document-level query. +`name` | String | The name of the document-level query. +`tags` | Array | An array of tags (each of type String) configured for the document-level query. + +##### Mustache template example + +The `_source` object in this example is based on the `opensearch_dashboards_sample_data_ecommerce` index available in OpenSearch Dashboards. In this example, the message template is accessing the `ctx.alerts` variable of a per document monitor. +{: .note} + +{% raw %} +```groovy +Alerts +{{#ctx.alerts}} + Sample documents: + {{#sample_documents}} + Index: {{_index}} + Document ID: {{_id}} + + Order date: {{_source.order_date}} + Order ID: {{_source.order_id}} + Clothing category: {{_source.category}} + ----------------- + {{/sample_documents}} +{{/ctx.alerts}} +``` +{% endraw %} \ No newline at end of file diff --git a/_observing-your-data/alerting/unified-alerts-view.md b/_observing-your-data/alerting/unified-alerts-view.md new file mode 100644 index 00000000..37c57cab --- /dev/null +++ b/_observing-your-data/alerting/unified-alerts-view.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Unified alerts view +parent: Alerting dashboards and visualizations +grand_parent: Alerting +nav_order: 10 +--- + +# Unified alerts view +**Introduced 3.7** +{: .label .label-purple } + +The unified alerts view consolidates alerts from OpenSearch monitors and Prometheus alerting rules into a single view, so you can triage alerts across data sources without switching between tools. In OpenSearch Dashboards, the view appears as the **Alerts** page under **Observability**. + +The **Alerts** page can also show anomaly detection and forecasting resources, so you can investigate alerts, anomalies, detectors, and forecasters on one page. + +## Enabling the unified alerts view + +The unified alerts view is disabled by default. To enable it, add the following line to `opensearch_dashboards.yml`: + +```yaml +observability.alertManager.enabled: true +``` +{% include copy.html %} + +Then restart OpenSearch Dashboards. After the restart, an **Alerts** option appears in the OpenSearch Dashboards main menu under **Observability**. + +## Investigating an alert + +The **Alerts** tab displays an alert timeline for the selected time range, a faceted filter panel, and a table of individual alerts and anomalies. You can filter the table by data source, type, severity, state, and label. + +To investigate an alert, select it in the table to open the alert detail flyout. The flyout shows alert metadata and its source monitor. + +The view supports the following alert states: `active`, `pending`, `acknowledged`, `silenced`, `resolved`, and `error`. The supported severity levels are `critical`, `high`, `medium`, `low`, and `info`. + +## Investigating anomalies + +The **Alerts** tab includes anomaly results from real-time anomaly detectors. Anomalies appear in the same table as alerts and use the `anomaly` state. + +When multiple anomaly occurrences belong to the same detector and entity, the table groups them into a single row. Expand the row to inspect individual occurrences, then select an occurrence to open the anomaly detail flyout. + +The anomaly detail flyout shows detector and anomaly metadata, anomaly grade, confidence, start time, duration, and feature data. For high-cardinality detectors, the flyout includes detector result context for the selected entity. For single-entity detectors, the flyout shows metric context for the selected anomaly. + +If an alert is associated with an anomaly result, the alert detail flyout also shows anomaly context so you can review the anomaly that contributed to the alert without leaving the **Alerts** page. + +## Acknowledging alerts + +From the **Alerts** tab, you can acknowledge one or more active OpenSearch alerts. Select the alerts in the table and select **Acknowledge**. + +For Prometheus data sources, the view is read-only. You cannot acknowledge Prometheus alerts from the unified alerts view. +{: .note} + +## Rules + +The **Rules** tab lists alerting rules, monitors, anomaly detectors, and forecasters across the selected data sources. You can filter rules by type and status. + +If no resources are configured for the selected data sources, the page provides options for creating the following: + +- Log or metric alerts +- Anomaly detectors +- Forecasters + +The anomaly detection and forecasting options are enabled only when an OpenSearch data source is selected in the data source filter. + +### Anomaly detectors + +Detectors appear with the **Anomaly Detector** type in the **Type** column. Select a detector to open a flyout that shows the following information: + +- Detector and model configuration +- Current status and health + +To manage the detector lifecycle from this page, use one of the following options: + +- Select one or more detectors and then select **Start** or **Stop** in the action bar. +- Select **Start** or **Stop** in the detector flyout. + +### Forecasters + +Forecasters appear with the **Forecaster** type. Select a forecaster to open a flyout that shows the following information: + +- Forecaster description, index details, and feature definition +- Forecast horizon and interval configuration +- Forecast status and health + +From the flyout, you can start or stop the forecaster. To start or stop several forecasters at once, select them in the **Rules** table and then select **Start** or **Stop**. + +Forecasters produce forecast output for trend and capacity planning. They don't create alert records in the **Alerts** timeline. + +## Notification routing + +The **Routing** tab shows how alerts from the selected data sources map to notification channels. + +## Related documentation + +- [Alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/) +- [Alerting dashboards and visualizations]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/dashboards-alerting/) +- [Monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/) +- [Anomaly detection]({{site.url}}{{site.baseurl}}/observing-your-data/ad/index/) +- [Forecasting]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/index/) diff --git a/_observing-your-data/apm/application-map.md b/_observing-your-data/apm/application-map.md new file mode 100644 index 00000000..c6940c60 --- /dev/null +++ b/_observing-your-data/apm/application-map.md @@ -0,0 +1,95 @@ +--- +layout: default +title: Topology map +nav_order: 50 +parent: Application performance monitoring +grand_parent: Observability workspace apps +--- + +# Topology map +**Introduced 3.6** +{: .label .label-purple } + +The topology map provides an interactive topology visualization autogenerated from trace data by the Data Prepper `otel_apm_service_map` processor. The map displays your services as nodes with directional edges showing communication patterns, overlaid with Rate, Errors, Duration (RED) metrics for each service. + +## Accessing the topology map + +To access the topology map, in your Observability workspace, select **Topology Map** in the left navigation. The following image shows the topology map. + +![Topology map]({{site.url}}{{site.baseurl}}/images/apm/application-map.png) + +## RED metrics on the map + +Each node on the topology map displays the following RED metrics computed from trace span data: + +- **Rate**: The number of requests per second handled by the service. +- **Errors**: The percentage of requests resulting in errors, broken down by `4xx` (client errors) and `5xx` (server faults). +- **Duration**: The response time of the service, typically shown as P50 and P99 latency. + +These metrics are generated by the `otel_apm_service_map` processor in Data Prepper and stored in Prometheus through remote write. For more information, see [APM service map processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-apm-service-map/). + +## Topology visualization + +The topology map autogenerates a directed graph from your trace data: + +- **Nodes** represent individual services in your application. +- **Edges** represent communication between services, with arrows indicating the direction of calls. +- **Color coding** indicates the health status of each service based on its error and fault rates. + +The map updates automatically as new trace data is ingested, reflecting changes in your application topology in near real time. + +## Grouping services + +You can group services by attributes to organize the map view. The following image shows services grouped by attributes. + +![Grouping by attributes]({{site.url}}{{site.baseurl}}/images/apm/groupby-attributes.png) + +- **Group by attributes**: Select an attribute such as programming language, team, or environment to group related services together. +- **Card grid view**: When grouping is applied, the map reorganizes into a card grid layout where each card represents a group of services with aggregated metrics. + +The `group_by_attributes` option in the `otel_apm_service_map` processor configuration determines which attributes are available for grouping. For example, setting `group_by_attributes: [telemetry.sdk.language]` enables grouping by programming language. +{: .note} + +## Viewing node details + +Select a node on the map or choose **View insights** to open a detail panel on the right side of the screen. + +![Node details panel]({{site.url}}{{site.baseurl}}/images/apm/application-map-node-details.png) + +The detail panel includes the following sections: + +- **Health**: + + - **Total Requests**: The total number of requests handled during the selected time range. + - **Total Errors (`4xx`)**: The count of client error responses. + - **Total Faults (`5xx`)**: The count of server fault responses. + +- **Metrics**: Time-series charts showing the trend of each metric over the selected time range: + + - **Requests**: Request volume over time. + - **Latency**: P50, P90, and P99 latency over time. + - **Faults (`5xx`)**: Server fault count over time. + - **Errors (`4xx`)**: Client error count over time. + +From the node detail panel, select **View details** to navigate directly to the [Services]({{site.url}}{{site.baseurl}}/observing-your-data/apm/services/) detail view for the selected service. + +## Filtering the map + +The following image shows the topology map filtered by error rate. + +![Filter by error rate]({{site.url}}{{site.baseurl}}/images/apm/filter-by-error-rate.png) + +Use the filter controls to focus on specific areas of your application topology: + +- **Fault rate**: Show only services with fault rates (`5xx` errors) exceeding a specified threshold. +- **Error rate**: Show only services with error rates (`4xx` errors) exceeding a specified threshold. +- **Environment**: Filter services by deployment environment (for example, `production` or `staging`). + +## In-context correlations + +The topology map integrates with APM correlations to help you navigate from the topology view to detailed telemetry data: + +- **Application spans**: Select a service node and choose **View traces** to see the individual trace spans associated with that service. This is useful for investigating the root cause of latency or error spikes visible on the map. +- **Application logs**: Select a service node and choose **View logs** to see log entries from that service during the selected time range. Log correlations require that you have configured a [correlation]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/correlations/) between your trace and log datasets. + +These in-context navigation paths allow you to move seamlessly from a high-level topology view to the detailed traces and logs needed for root cause analysis. diff --git a/_observing-your-data/apm/configuring-apm.md b/_observing-your-data/apm/configuring-apm.md new file mode 100644 index 00000000..4cf91223 --- /dev/null +++ b/_observing-your-data/apm/configuring-apm.md @@ -0,0 +1,81 @@ +--- +layout: default +title: Configuring APM in OpenSearch Dashboards +nav_order: 20 +parent: Application performance monitoring +grand_parent: Observability workspace apps +--- + +# Configuring APM in OpenSearch Dashboards +**Introduced 3.6** +{: .label .label-purple } + +After ingesting telemetry data using the OpenTelemetry Collector and Data Prepper, you need to configure Application Performance Monitoring (APM) in OpenSearch Dashboards. You'll create datasets, configure index patterns, attach a Prometheus data source, and configure APM settings in your workspace. + +## Step 1: Create datasets for logs and traces + +Create datasets in your Observability workspace to define how APM accesses your trace and log data: + +1. Navigate to your Observability workspace. +2. Select **Datasets** and then select **Create dataset**. +3. Create a **traces dataset** pointing to your trace data index (for example, `otel-v1-apm-span-*`). +4. Create a **logs dataset** pointing to your application logs index (for example, `logs-otel-v1-*`). + +For detailed instructions on creating and configuring datasets, see [Datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/). + +## Step 2: Create a correlation between trace and log datasets + +Link the trace and log datasets so that APM can display related logs when you investigate traces: + +1. Navigate to **Datasets** > **Correlations**. +2. Select the trace dataset you created in [Step 1](#step-1-create-datasets-for-logs-and-traces). +3. Add the logs dataset as a correlated dataset. +4. Save the correlation. + +This enables in-context log correlations throughout the APM interface, including the **Services** and **Topology Map** pages. For detailed instructions, see [Correlations]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/correlations/). + +## Step 3: Create an index pattern for the service map + +APM requires an index pattern for the service map data generated by the `otel_apm_service_map` processor in Data Prepper. To create an index pattern, follow these steps: + +1. Navigate to **Dashboards Management** > **Index patterns**. +2. Select **Create index pattern**. +3. Enter `otel-v2-apm-service-map*` as the index pattern name. +4. Select the appropriate time field and save. + +This index pattern is used by APM to display service topology data and dependency information. + +## Step 4: Attach a Prometheus data source to your workspace + +APM uses Prometheus to store and query rate, error, and duration (RED) metrics. To add a Prometheus data source to your workspace, follow these steps: + +1. Navigate to **Dashboards Management** > **Data sources**. +2. Select **Create data source** and choose **Prometheus**. +3. Enter the connection details for your Prometheus instance (for example, `http://prometheus:9090`). +4. Save the data source and attach it to your Observability workspace. + +For detailed instructions on configuring a Prometheus data source, see [Configuring a Prometheus data source]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-metrics/#configuring-a-prometheus-data-source). + +## Step 5: Configure APM settings + + + +To configure APM settings, follow these steps: + +1. In the left navigation, select **Application performance** > **Services** or **Topology Map**. +2. Select the **APM Settings** button in the upper-right corner. The **Application monitoring settings** dialog appears, as shown in the following image. + ![APM settings modal]({{site.url}}{{site.baseurl}}/images/apm/apm-settings-modal.png) +3. In the **Application monitoring settings** dialog, configure the following settings: + + - **Traces**: Select the trace dataset you created in [Step 1](#step-1-create-datasets-for-logs-and-traces) (for example, `Trace Dataset - Local Cluster`). The number of correlated logs is displayed below the selection. + - **Services**: Select the service map index pattern you created in [Step 3](#step-3-create-an-index-pattern-for-the-service-map) (for example, `otel-v2-apm-service-map*`). + - **RED Metrics**: Select the Prometheus data source you configured in [Step 4](#step-4-attach-a-prometheus-data-source-to-your-workspace) (for example, `ObservabilityStack_Prometheus`). + +4. Select **Update** to save your configuration. + +After completing this setup, APM will display service topology, RED metrics, and in-context correlations across the Services and Topology Map pages. + +## Next steps + +- [Services]({{site.url}}{{site.baseurl}}/observing-your-data/apm/services/): View service performance metrics and dependencies. +- [Topology map]({{site.url}}{{site.baseurl}}/observing-your-data/apm/application-map/): Explore the service topology visualization. diff --git a/_observing-your-data/apm/configuring-telemetry-ingestion.md b/_observing-your-data/apm/configuring-telemetry-ingestion.md new file mode 100644 index 00000000..824d9e16 --- /dev/null +++ b/_observing-your-data/apm/configuring-telemetry-ingestion.md @@ -0,0 +1,182 @@ +--- +layout: default +title: Configuring telemetry ingestion +nav_order: 10 +parent: Application performance monitoring +grand_parent: Observability workspace apps +--- + +# Configuring telemetry ingestion +**Introduced 3.6** +{: .label .label-purple } + +To use APM, you need to ingest application traces and logs into OpenSearch using the OpenTelemetry Collector and Data Prepper pipeline. For an overview of the complete APM architecture, see [APM architecture]({{site.url}}{{site.baseurl}}/observing-your-data/apm/#apm-architecture). + +This page covers configuring the OpenTelemetry Collector and Data Prepper to process and route telemetry data to OpenSearch and Prometheus. + +## Configuring the OpenTelemetry Collector + +The [OpenTelemetry (OTel) Collector](https://opentelemetry.io/docs/collector/) acts as the entry point for all application telemetry. It receives data through the OpenTelemetry Protocol (OTLP) and routes traces and logs to Data Prepper while sending metrics to Prometheus. + +The following example shows the key exporter and pipeline configuration for routing telemetry to Data Prepper and Prometheus: + +```yaml +exporters: + otlp/opensearch: + endpoint: "data-prepper:21893" + tls: + insecure: true + insecure_skip_verify: true + + otlphttp/prometheus: + endpoint: "http://prometheus:9090/api/v1/otlp" + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [otlp] + processors: [resourcedetection, memory_limiter, transform, batch] + exporters: [otlp/opensearch] + + metrics: + receivers: [otlp] + processors: [resourcedetection, memory_limiter, batch] + exporters: [otlphttp/prometheus] + + logs: + receivers: [otlp] + processors: [resourcedetection, memory_limiter, transform, batch] + exporters: [otlp/opensearch] +``` +{% include copy.html %} + +The `otlp/opensearch` exporter sends traces and logs to Data Prepper. The `otlphttp/prometheus` exporter sends metrics directly to Prometheus. For a complete OTel Collector configuration example including receivers, processors, and telemetry settings, see the [observability-stack repository](https://github.com/opensearch-project/observability-stack/blob/main/docker-compose/otel-collector/config.yaml). +{: .note} + +## Configuring Data Prepper pipelines + +Data Prepper receives telemetry data from the OTel Collector and processes it into the formats required for APM. The pipeline architecture routes data through specialized subpipelines for log, trace, and service map generation. + +The following example shows a complete Data Prepper pipeline configuration: + +```yaml +# Main OTLP pipeline - receives all telemetry and routes by type +otlp-pipeline: + source: + otlp: + ssl: false + route: + - logs: "getEventType() == \"LOG\"" + - traces: "getEventType() == \"TRACE\"" + sink: + - pipeline: + name: "otel-logs-pipeline" + routes: + - "logs" + - pipeline: + name: "otel-traces-pipeline" + routes: + - "traces" + +# Log processing pipeline +otel-logs-pipeline: + workers: 5 # config example to set workers + delay: 10 # config example to set delay + source: + pipeline: + name: "otlp-pipeline" + buffer: + bounded_blocking: + sink: + - opensearch: + hosts: ["https://<opensearch-host>:9200"] + username: <username> + password: <password> + insecure: true + index_type: log-analytics-plain + +# Trace processing pipeline +otel-traces-pipeline: + source: + pipeline: + name: "otlp-pipeline" + sink: + - pipeline: + name: "traces-raw-pipeline" + - pipeline: + name: "service-map-pipeline" + +# Raw trace storage pipeline +traces-raw-pipeline: + source: + pipeline: + name: "otel-traces-pipeline" + processor: + - otel_traces: + sink: + - opensearch: + hosts: ["https://<opensearch-host>:9200"] + username: <username> + password: <password> + insecure: true + index_type: trace-analytics-plain-raw + +# Service map and APM metrics pipeline +service-map-pipeline: + source: + pipeline: + name: "otel-traces-pipeline" + processor: + - otel_apm_service_map: + group_by_attributes: [telemetry.sdk.language] # Add any resource attribute to group by + route: + - otel_apm_service_map_route: 'getEventType() == "SERVICE_MAP"' + - service_processed_metrics: 'getEventType() == "METRIC"' + sink: + - opensearch: + hosts: ["https://<opensearch-host>:9200"] + username: <username> + password: <password> + index_type: otel-v2-apm-service-map + routes: [otel_apm_service_map_route] + insecure: true + - prometheus: + url: "http://prometheus:9090/api/v1/write" + routes: [service_processed_metrics] +``` +{% include copy.html %} + +### Pipeline architecture + +The Data Prepper pipeline processes telemetry data using the following steps: + +1. The entry pipeline (`otlp-pipeline`) receives all telemetry on port 21893 and routes logs and traces to their respective subpipelines. +2. The log pipeline (`otel-logs-pipeline`) maps the `time` field to `@timestamp` and writes logs to OpenSearch using the `log-analytics-plain` index type. +3. The trace pipeline (`otel-traces-pipeline`) distributes traces to both the raw storage pipeline and the service map pipeline. +4. The raw trace pipeline (`traces-raw-pipeline`) processes individual trace spans using the `otel_traces` processor and stores them in OpenSearch using the `trace-analytics-plain-raw` index type. +5. The service map pipeline (`service-map-pipeline`) uses the `otel_apm_service_map` processor to generate service dependency maps and RED metrics. Service map topology data is written to OpenSearch, and RED metrics are exported to Prometheus through remote write. + +Two key configuration options for the `otel_apm_service_map` processor are `group_by_attributes` (which determines how services can be grouped in the topology map) and `window_duration` (which sets the time window for aggregating trace data). For complete configuration details, see [APM service map processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-apm-service-map/). +{: .note} + +## Verifying ingestion + +After configuring the OTel Collector and Data Prepper, verify that data is flowing correctly: + +1. Verify that the following indexes are created in your OpenSearch cluster: + - `otel-v1-apm-span-*`: Raw trace spans. + - `otel-v2-apm-service-map`: Service topology data. + - `logs-otel-v1-*`: Application logs. + +2. Verify that the Data Prepper remote write target is active in your Prometheus instance. + +3. In your Observability workspace, select **Application performance** > **Services** in the left navigation to confirm that your services appear in the [Services]({{site.url}}{{site.baseurl}}/observing-your-data/apm/services/) catalog and the [Topology map]({{site.url}}{{site.baseurl}}/observing-your-data/apm/application-map/). + +Ensure that all port mappings are correct between the OTel Collector, Data Prepper, OpenSearch, and Prometheus. Mismatched ports are a common cause of ingestion failures. +{: .warning} + +## Next steps + +- [Configuring APM in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/apm/configuring-apm/): Create datasets, index patterns, and configure APM settings to start using APM features. diff --git a/_observing-your-data/apm/index.md b/_observing-your-data/apm/index.md new file mode 100644 index 00000000..aada1516 --- /dev/null +++ b/_observing-your-data/apm/index.md @@ -0,0 +1,77 @@ +--- +layout: default +title: Application performance monitoring +parent: Observability workspace apps +nav_order: 50 +has_children: true +has_toc: false +redirect_from: + - /observing-your-data/apm/ +--- + +# Application performance monitoring +**Introduced 3.6** +{: .label .label-purple } + +Application Performance Monitoring (APM) provides real-time monitoring of your distributed applications by combining service topology data with Rate, Errors, Duration (RED) metrics. APM provides a unified view of service health, enabling you to quickly identify performance bottlenecks and failures across your microservices architecture. + +## Prerequisites + +APM requires the following components: + +- An OpenSearch cluster and OpenSearch Dashboards with an Observability workspace and the APM settings enabled. For more information, see [Observability workspace apps]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/). +- An [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/). +- [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/). +- [Prometheus](https://prometheus.io/) for metrics storage, connected to OpenSearch as a [Prometheus data source]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/). +- Applications instrumented using [OpenTelemetry](https://opentelemetry.io/docs/instrumentation/). + +## APM architecture + +The following image shows the APM architecture. + +![APM architecture]({{site.url}}{{site.baseurl}}/images/apm/architecture.png) + +APM uses the following data pipeline to collect, process, and visualize application telemetry: + +1. **[OpenTelemetry SDKs](https://opentelemetry.io/docs/instrumentation/)** instrument your application code to generate traces, logs, and metrics. +2. **[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)** receives telemetry through OTLP (gRPC on port 4317 or HTTP on port 4318), processes it, and routes it to Data Prepper and Prometheus. +3. **[OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/)** processes traces and generates service maps and RED metrics using the [`otel_apm_service_map` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/otel-apm-service-map/). +4. **OpenSearch** stores trace data, logs, and service topology information. +5. **Prometheus** stores time-series RED metrics through remote write. +6. **OpenSearch Dashboards** provides the APM user interface for visualization and analysis. + +## Configuring APM + +To configure APM, complete the following steps: + +1. **Create an observability workspace**: APM features are only available within Observability workspaces. To learn how to enable and create workspaces, see [Workspace for OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace/). + +2. **Enable feature flags**: Add the following settings to your `opensearch_dashboards.yml` file: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + explore.discoverMetrics.enabled: true + ``` + {% include copy.html %} + +3. **Instrument your application**: Integrate [OpenTelemetry SDKs](https://opentelemetry.io/docs/instrumentation/) into your application code to generate trace and log data. + +4. **Configure telemetry ingestion**: Set up the OpenTelemetry Collector and Data Prepper to process and route telemetry to OpenSearch and Prometheus. See [Configuring telemetry ingestion]({{site.url}}{{site.baseurl}}/observing-your-data/apm/configuring-telemetry-ingestion/). + +5. **Configure APM in OpenSearch Dashboards**: Create datasets, index patterns, and connect data sources in your Observability workspace. See [Configuring APM in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/apm/configuring-apm/). + +## Using APM + +After completing the setup steps, use the following APM pages to monitor your services: + +- [**Services**]({{site.url}}{{site.baseurl}}/observing-your-data/apm/services/): View a centralized catalog of all instrumented services with key performance indicators, per-operation metrics, and dependency information. +- [**Topology map**]({{site.url}}{{site.baseurl}}/observing-your-data/apm/application-map/): Explore an interactive topology visualization autogenerated from trace data, with RED metrics overlaid on each service node. + +APM is distinct from the older [Application analytics]({{site.url}}{{site.baseurl}}/observing-your-data/app-analytics/) and [Trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/index/) features. APM provides a more integrated experience that combines service topology, RED metrics, and in-context correlations into a single workflow. +{: .note} + +## Next steps + +- [Configuring telemetry ingestion]({{site.url}}{{site.baseurl}}/observing-your-data/apm/configuring-telemetry-ingestion/): Set up the OpenTelemetry Collector and Data Prepper to process and route telemetry to OpenSearch and Prometheus. \ No newline at end of file diff --git a/_observing-your-data/apm/services.md b/_observing-your-data/apm/services.md new file mode 100644 index 00000000..9ae2cfdd --- /dev/null +++ b/_observing-your-data/apm/services.md @@ -0,0 +1,106 @@ +--- +layout: default +title: Services +nav_order: 40 +parent: Application performance monitoring +grand_parent: Observability workspace apps +--- + +# Services +**Introduced 3.6** +{: .label .label-purple } + +The **Services** page provides a centralized catalog of all instrumented services in your application, displaying Rate, Errors, Duration (RED) at a glance. Use this page to identify services with high error rates, latency issues, or throughput anomalies. + +## Accessing the services page + +To access the **Services** page, in your Observability workspace, select **Application performance** > **Services** in the left navigation. The following image shows the **Services** page. + +![Services home page]({{site.url}}{{site.baseurl}}/images/apm/services-home.png) + +The Services home page displays a table of all discovered services with the following information: + +- **Service name**: The name of the instrumented service as reported by the OpenTelemetry SDK. +- **P99/P90/P50 latency**: The 99th, 90th, and 50th percentile response times for the service. +- **Total requests**: The total number of requests handled by the service during the selected time range. +- **Failure ratio**: The percentage of requests resulting in errors (`4xx` and `5xx` responses). +- **Environment**: The deployment environment (for example, `production` or `staging`). + +The Services home page also provides information about the **Top services by fault rate** and **Top dependency paths by fault rate**, helping you quickly identify critical issues and problematic service-to-service communication paths. + +## Service overview + +Select a service name to open the service detail view. The following image shows a service overview. + +![Service overview]({{site.url}}{{site.baseurl}}/images/apm/services-overview.png) + +The **Overview** tab displays metric tiles summarizing the service's current health, along with the following time-series charts: + +- **Latency by service dependencies**: P50, P90, and P99 latency broken down by downstream dependencies. +- **Requests by operations**: Request volume per operation over time. +- **Availability by operations**: Availability percentage per operation over time. +- **Fault rate and error rate by operations**: `5xx` fault rate and `4xx` error rate per operation over time. + +## Operations + +The following image shows the Operations tab. + +![Service operations]({{site.url}}{{site.baseurl}}/images/apm/service-operations.png) + +The **Operations** tab provides a per-operation breakdown of service performance. Each row in the operations table represents a distinct API endpoint or method and displays the following metrics: + +- **Operation name**: The name of the API endpoint or method (for example, `GET /api/products`). +- **P50 latency**: The median response time. +- **P90 latency**: The 90th percentile response time. +- **P99 latency**: The 99th percentile response time. +- **Total requests**: The total number of requests for this operation during the selected time range. +- **Error rate**: The percentage of requests resulting in errors. +- **Availability**: The availability percentage for this operation. + +Use the column headers to sort operations by any metric and identify the slowest or most error-prone endpoints. + +## Dependencies + +The following image shows the Dependencies tab. + +![Service dependencies]({{site.url}}{{site.baseurl}}/images/apm/service-dependencies.png) + +The **Dependencies** tab shows the downstream services that the selected service calls. For each dependency, the following information is displayed: + +- **Dependency service**: The name of the downstream service being called. +- **Remote operation**: The specific operation invoked on the downstream service. +- **Service operations**: The operations on the current service that call this dependency. +- **P99 latency**: The 99th percentile response time for calls to this dependency. +- **P90 latency**: The 90th percentile response time for calls to this dependency. +- **P50 latency**: The median response time for calls to this dependency. +- **Total requests**: The total number of requests to this dependency during the selected time range. +- **Error rate**: The percentage of failed calls to this dependency. +- **Availability**: The availability percentage for this dependency path. + +Use this view to determine whether performance issues in a service are caused by its own logic or by a slow or failing downstream dependency. + +## Correlations + +APM provides in-context correlations that allow you to navigate from service metrics directly to related traces and logs. Correlations are accessible from the **Services home page**, **Service overview**, and **Operations** pages. + +![Service span correlations]({{site.url}}{{site.baseurl}}/images/apm/service-span-correlations.png) + +When viewing a service, you can: + +- **View related traces**: Select a metric or operation to open a flyout panel showing correlated trace spans. This helps you drill down from a high-level metric to the individual requests that contributed to it. +- **View related logs**: The flyout panel also displays log entries associated with the selected traces, giving you full context for debugging issues. +- **Filter by attributes**: Use service attributes such as environment, operation name, or error type to narrow the correlation results. + +For more information about configuring correlations between trace and log datasets, see [Correlations]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/correlations/). + +## Filtering services + +Use the filter controls at the top of the **Services** page to narrow the list of displayed services: + +- **Environment**: Filter by deployment environment (for example, `production`, `staging`, `development`). +- **Latency**: Filter services exceeding a latency threshold. +- **Throughput**: Filter services by request volume. +- **Failure ratio**: Filter services with failure ratios that exceed a specified percentage. + +You can combine multiple filters to quickly isolate services that match specific criteria, for example, production services with a failure ratio greater than 5%. +{: .tip} diff --git a/_observing-your-data/app-analytics.md b/_observing-your-data/app-analytics.md index 44e1939a..c164d1bf 100644 --- a/_observing-your-data/app-analytics.md +++ b/_observing-your-data/app-analytics.md @@ -1,39 +1,40 @@ --- layout: default title: Application analytics -nav_order: 10 -redirect_from: - - /observing-your-data/app-analytics/ +parent: Classic observability apps +nav_order: 40 --- # Application analytics You can use application analytics to create custom observability applications to view the availability status of your systems, where you can combine log events with trace and metric data into a single view of overall system health. This lets you quickly pivot between logs, traces, and metrics to dig into the source of any issues. +Application analytics is a [classic observability app]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/). It is not available when multiple data sources are enabled. To monitor applications in an Observability workspace, see [Application performance monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/apm/). + ## Get started with application analytics -To get started, select the Menu button on the upper left corner of the OpenSearch Dashboards interface. Next, select **Observability**, and then choose **Application analytics**. +To get started, on the top menu, go to **Observability** > **Applications**. ### Create an application -1. Choose **Create application**. -2. Enter a name for your application and optionally add a description. -3. Do at least one of the following: +1. Select **Create application**. +2. In **Application information**, enter a **Name** and, optionally, a **Description**. +3. In **Composition**, do at least one of the following: -- Use [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index) to specify the base query. + - In **Log source**, use [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) to specify the **Base Query**, for example, `source = opensearch_dashboards_sample_data_logs`. -You can't change the base query after the application is created. -{: .note } + You can't change the base query after the application is created. + {: .note } -- Select services & entities from the dropdown or the service map. -- Select trace groups from the dropdown or the table. + - Select **Services & entities** from the dropdown or the service map. + - Select **Trace groups** from the dropdown or the table. -4\. Choose **Create**. +4. Select **Create**. To configure availability immediately, select **Create and Set Availability**. ### Create a visualization 1. Choose the **Log Events** tab. -1. Use [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index) to build upon your base query. +1. Use [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) to build upon your base query. The query editor already applies the base query, so start with the next command, for example, `stats count() by span(timestamp, 1h)`, and then select **Run**. 1. Choose the **Visualizations** tab to see your visualizations. 1. Expand the **Save** dropdown menu, enter a name for your visualization, then choose **Save**. @@ -43,7 +44,7 @@ To see your visualizations, choose the **Panel** tab. Availability is the status of your application determined by availability levels set on a [time series metric]({{site.url}}{{site.baseurl}}/observing-your-data/app-analytics/#time-series-metric). -To create an availability level, you must configure the following: +To set availability for an existing application, select the **Configuration** tab, and then select **Set Availability**. To create an availability level, you must configure the following: - color: The color of the availability badge on the home page. - name: The text in the availability badge on the home page. - expression: Comparison operator to determine the availability. diff --git a/_observing-your-data/classic-observability-apps.md b/_observing-your-data/classic-observability-apps.md new file mode 100644 index 00000000..9a333ff1 --- /dev/null +++ b/_observing-your-data/classic-observability-apps.md @@ -0,0 +1,22 @@ +--- +layout: default +title: Classic observability apps +nav_order: 40 +has_children: true +has_toc: false +--- + +# Classic observability apps + +In classic navigation, OpenSearch Dashboards provides observability apps in the **Observability** menu. These apps don't require a workspace or additional settings in `opensearch_dashboards.yml`. + +The following table describes the apps and lists whether each app is available with a single data source and when [multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/) are enabled. + +| App | Description | Single data source | Multiple data sources | +|:---|:---|:---|:---| +| [Event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics/) | Query log events using Piped Processing Language (PPL) and create visualizations from the results. | Yes | No | +| [Trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/index/) | View dashboards of traces and services, including latency, error rate, and throughput. | Yes | Yes | +| [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/) | Query and visualize metrics stored in Prometheus or in OpenTelemetry metrics indexes in OpenSearch. | Yes | Yes | +| [Application analytics]({{site.url}}{{site.baseurl}}/observing-your-data/app-analytics/) | Combine the logs, traces, and metrics of an application into a single view of its health. | Yes | No | +| [Operational panels]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels/) | Organize PPL visualizations into dashboards. | Yes | No | +| [Notebooks]({{site.url}}{{site.baseurl}}/dashboards/notebooks/) | Combine Markdown text, SQL and PPL queries, and visualizations into reports and runbooks. | Yes | Yes | diff --git a/_observing-your-data/cross-cluster-search.md b/_observing-your-data/cross-cluster-search.md new file mode 100644 index 00000000..e237c1ff --- /dev/null +++ b/_observing-your-data/cross-cluster-search.md @@ -0,0 +1,95 @@ +--- +layout: default +title: Using observability apps for cross-cluster search +nav_order: 180 +redirect_from: + - /observing-your-data/cross-cluster-replication/ +--- + +# Using observability apps for cross-cluster search + +Using cross-cluster search, you can query indexes in remote OpenSearch clusters from [Event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics/) or from the Logs page in an Observability workspace. You run a Piped Processing Language (PPL) query on the local cluster, and the local cluster forwards it to the remote clusters and returns the combined results. + +## Prerequisites + +Before you query a remote cluster, make sure that you meet the following prerequisites: + +- The local cluster can reach the transport port (by default, `9300`) of at least one node in the remote cluster. +- If the Security plugin is enabled, the user has PPL permissions on the local cluster and read permissions for the queried indexes on the remote cluster. For more information, see [Setting permissions]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/#setting-permissions). + +## Connecting to a remote cluster + +On the local cluster, register the remote cluster by providing a name for it and the address of one or more of its nodes: + +```json +PUT _cluster/settings +{ + "persistent": { + "cluster.remote": { + "my-remote-cluster": { + "seeds": ["<remote-node-address>:9300"] + } + } + } +} +``` +{% include copy-curl.html %} + +To verify the connection, send the following request: + +```json +GET _remote/info +``` +{% include copy-curl.html %} + +When the connection succeeds, the response contains `"connected": true` for the remote cluster. For more information about the response, see [Remote cluster information]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/remote-info/). + +For more information about connecting clusters, including node role requirements and sample Docker, Kubernetes, and proxy setups, see [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/). + +## Querying a remote cluster + +In a PPL query, specify a remote index as `<remote-cluster-name>:<index-name>`. You can query more than one cluster in a single query, as shown in the following table. + +| Query | Searches | +|:---|:---| +| `source = my-remote-cluster:application-logs` | The `application-logs` index in `my-remote-cluster` | +| `source = *:application-logs` | The `application-logs` index in every connected remote cluster | +| `source = application-logs, my-remote-cluster:application-logs` | The `application-logs` index in both the local cluster and `my-remote-cluster` | + +### Using Event analytics + +To query a remote cluster in Event analytics, follow these steps: + +1. On the top menu, go to **Observability** > **Logs**, and then select **Event Explorer**. +1. In the query bar, enter a PPL query that specifies the remote index. For example, the following query returns server errors from the `application-logs` index in `my-remote-cluster`: + + ```sql + source = my-remote-cluster:application-logs | where status >= 500 | fields @timestamp, service, status, message + ``` + {% include copy.html %} + +1. Select a time range, and then select **Run**. + +### Using an Observability workspace + +In an Observability workspace, you can query a remote cluster on the [Logs]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/) page. Datasets cannot contain remote indexes, so you specify the remote index in the query instead. + +To query a remote cluster in an Observability workspace, follow these steps: + +1. In your Observability workspace, go to **Logs**. +1. Select a dataset. +1. In the query editor, replace the `source` with the remote index, for example, `source = my-remote-cluster:application-logs | where status >= 500`. +1. Select a time range, and then run the query. + +## Common issues + +This section describes common issues and their solutions. + +### The query fails with a `no such index` error + +If a PPL query on a remote index fails with a `no such index` error even though the index exists on the remote cluster, create an empty index on the local cluster that has the same name and mappings as the remote index. The query returns documents from the remote cluster, not from the local index. + +## Related documentation + +- For setup examples and security configuration, see [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/). +- For PPL limitations and authentication details for cross-cluster queries, see [Cross-cluster search in the SQL plugin documentation](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/cross_cluster_search.md). diff --git a/_observing-your-data/event-analytics.md b/_observing-your-data/event-analytics.md index dd936b7d..83437347 100644 --- a/_observing-your-data/event-analytics.md +++ b/_observing-your-data/event-analytics.md @@ -1,24 +1,27 @@ --- layout: default title: Event analytics -nav_order: 20 +parent: Classic observability apps +nav_order: 10 redirect_from: - - /observing-your-data/event-analytics/ + - /observability-plugin/event-analytics/ --- # Event analytics -Event analytics in OpenSearch Observability allow you to create data visualizations using [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) (PPL) queries. +Event analytics lets you explore log events and create data visualizations using [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) (PPL) queries. + +Event analytics is a [classic observability app]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/). It is not available when multiple data sources or the new home page are enabled. To explore logs in an Observability workspace, see [Logs]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/). ## Getting started with event analytics -To get started, choose **Observability** in OpenSearch Dashboards and then choose **Logs**. If you want to start exploring without adding your own data, choose **Add samples**. Dashboards adds sample visualizations you can interact with. You can also try out preconfigured analytics in [OpenSearch Playground](https://playground.opensearch.org/app/observability-logs#/). +To get started, on the top menu, go to **Observability** > **Logs**, and then select **Event Explorer**. If you want to start exploring without adding your own data, select **Add samples**. Dashboards adds sample visualizations you can interact with. You can also try out preconfigured analytics in [OpenSearch Playground](https://playground.opensearch.org/app/observability-logs#/). ## Building a query To generate custom visualizations, you must first specify a PPL query. OpenSearch Dashboards then automatically creates a visualization based on your query results. -For example, the following PPL query returns a count of how many host addresses are currently in your data. +For example, the following PPL query returns the number of log events in the OpenSearch Dashboards sample web logs data: ``` source = opensearch_dashboards_sample_data_logs | fields host | stats count() @@ -28,10 +31,7 @@ By default, Dashboards shows results from the last 15 minutes of your data. To s For more information about building PPL queries, see [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/). -### OpenSearch Dashboards Query Assistant - -This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [OpenSearch forum thread](https://forum.opensearch.org/t/feedback-opensearch-assistant/16741). -{: .warning} +### OpenSearch Dashboards query assistant Note that machine learning models are probabilistic and that some may perform better than others, so the OpenSearch Assistant may occasionally produce inaccurate information. We recommend evaluating outputs for accuracy as appropriate to your use case, including reviewing the output or combining it with other verification factors. {: .important} @@ -40,48 +40,43 @@ To simplify query building, the **OpenSearch Assistant** toolkit offers an assis ![Sample OpenSearch Query Assist screen view]({{site.url}}{{site.baseurl}}/images/log-explorer-query-assist.png) -#### Enabling Query Assistant +#### Enabling query assistant -To enable **Query Assistant** in OpenSearch Dashboards, locate your copy of the `opensearch_dashboards.yml` file and set the following option: +By default, **Query Assistant** is enabled in OpenSearch Dashboards. To enable summarization of responses, locate your copy of the `opensearch_dashboards.yml` file and set the following option: -``` -observability.query_assist.enabled: true -observability.query_assist.ppl_agent_name: "PPL agent" -``` - -To enable summarization of responses, locate your copy of the `opensearch_dashboards.yml` file and set the following option: - -``` +```yaml observability.summarize.enabled: true observability.summarize.response_summary_agent_name: "Response summary agent" observability.summarize.error_summary_agent_name: "Error summary agent" ``` -#### Setting up Query Assistant +To disable Query Assistant, add `observability.query_assist.enabled: false` to your `opensearch_dashboards.yml`. + +#### Setting up query assistant To set up **Query Assistant**, follow the steps in the [Getting started guide](https://github.com/opensearch-project/dashboards-assistant/blob/main/GETTING_STARTED_GUIDE.md) on GitHub. This guide provides step-by-step setup instructions for **OpenSearch Assistant** and **Query Assistant**. To set up **Query Assistant** only, use the `query-assist-agent` template included in the guide. ## Saving a visualization -After Dashboards generates a visualization, save it if you want to revisit it or include it in an [operational panel]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels). To save a visualization, expand the **Save** dropdown menu in the upper-right corner, enter a name for the visualization, and then select the **Save** button. You can reopen saved visualizations on the event analytics page. +After Dashboards generates a visualization, save it if you want to revisit it or include it in an [operational panel]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels/). To save a visualization, expand the **Save** dropdown menu in the upper-right corner, enter a name for the visualization, and then select the **Save** button. You can reopen saved visualizations on the event analytics page. ## Creating event analytics visualizations and adding them to dashboards -This feature is available in OpenSearch Dashboards 2.7 and later. It works with new visualizations that use PPL to query data from OpenSearch or federated data sources such as Prometheus. +This feature works with new visualizations that use PPL to query data from OpenSearch or federated data sources such as Prometheus. {: .note} To create a PPL visualization, follow these steps: -1. On the main menu, choose **Visualize** > **PPL**. -2. From the **Observability** > **Logs** > **Explorer** window, enter the index source in the **PPL query** field, for example, `source = opensearch_dashboards_sample_data_flights | stats count() by DestCountry`. You must enter the query using PPL syntax. -3. Set the time filter, for example, **This week**, and then select **Refresh**. -4. Choose the visualization type, for example, **Pie**, from the sidebar dropdown menu to the right. +1. On the top menu, go to **Visualize**, select **Create visualization**, and then select **PPL**. The **Observability** > **Logs** > **Explorer** page opens. +2. Enter the index source in the **PPL query** field, for example, `source = opensearch_dashboards_sample_data_flights | stats count() by DestCountry`. You must enter the query using PPL syntax. +3. Set the time filter, for example, **This week**, and then select **Update**. +4. Select the **Visualizations** tab, and then select the visualization type, for example, **Pie**, from the dropdown list on the right. 5. Select **Save** and enter a name for the visualization. You've now created a new visualization that can be added to a new or existing dashboard. To add a PPL query to a dashboard, follow these steps: -1. Select **Dashboards** from the main menu. -2. In the **Dashboards** window, select **Create** > **Dashboard**. +1. On the top menu, go to **Dashboards**. +2. Select **Create** > **Dashboard**. 3. In the **Editing New Dashboard** window, choose **Add an existing**. 4. In the **Add panels** window, choose **PPL** from the **Types** dropdown menu, and then select the visualization. It is now displayed on your dashboard. 5. Select **Save** and enter a name for the dashboard. @@ -93,7 +88,7 @@ The following demo provides an overview of creating event analytics visualizatio ### Limitations of event analytics visualizations -Event analytics visualizations currently do not support [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/) or [query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/index/), and they do not use index patterns. Note the following limitations: +Event analytics visualizations do not support [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/discover/dql/) or [query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/index/), and they do not use index patterns. Note the following limitations: - Event analytics visualizations only use filters created using the dropdown interface. If you have DQL query or DSL filters in a dashboard, the visualizations do not use them. - The **Dashboard** filter dropdown interface only shows fields from the default index pattern or index patterns used by other visualizations in the same dashboard. @@ -122,7 +117,7 @@ With Live Tail, you can select intervals and seamlessly switch between them to c ![Live Tail]({{site.url}}{{site.baseurl}}/images/live_tail.gif) -## Related articles +## Related documentation - [Demonstrating the OpenSearch Assistant toolkit](https://www.youtube.com/watch?v=VTiJtGI2Sr4&t=152s) - [Getting started guide for OpenSearch Assistant in OpenSearch Dashboards](https://github.com/opensearch-project/dashboards-assistant/blob/main/GETTING_STARTED_GUIDE.md) diff --git a/_observing-your-data/exploring-data.md b/_observing-your-data/exploring-data.md new file mode 100644 index 00000000..04c9becd --- /dev/null +++ b/_observing-your-data/exploring-data.md @@ -0,0 +1,41 @@ +--- +layout: default +title: Exploring observability data +nav_order: 30 +--- + +# Exploring observability data + +OpenSearch Dashboards provides two sets of observability apps. Which set you use depends on how OpenSearch Dashboards is configured: + +- [Classic observability apps]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/) are available in the **Observability** menu in classic navigation and require no additional setup. +- [Observability workspace apps]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/) are available in an Observability workspace. To use them, enable workspaces and the observability settings in `opensearch_dashboards.yml`, and then create an Observability workspace. For the required settings, see [Prerequisites]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/index/#prerequisites). Application performance monitoring (APM), service-level objectives (SLOs), and agent monitoring are available only in workspaces. + +The following table lists the app that you use for each task in each set. + +| Task | Classic observability apps | Observability workspace apps | +|:---|:---|:---| +| Explore logs | [Event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics/) | [Logs]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/) | +| Explore traces | [Trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/index/) | [Traces]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-traces/), [Agent monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/) | +| Explore metrics | [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/) | [Metrics]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-metrics/) | +| Monitor applications | [Application analytics]({{site.url}}{{site.baseurl}}/observing-your-data/app-analytics/) | [Application performance monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/apm/), including [Services]({{site.url}}{{site.baseurl}}/observing-your-data/apm/services/), [Topology map]({{site.url}}{{site.baseurl}}/observing-your-data/apm/application-map/), and [SLOs]({{site.url}}{{site.baseurl}}/observing-your-data/slo/) | +| Build dashboards | [Operational panels]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels/) | [Dashboards]({{site.url}}{{site.baseurl}}/dashboards/dashboard/index/) | + +## Choosing a trace tool + +Several apps display trace data. The following table describes each app and where it is available. + +| App | Use it to | Where available | +|:---|:---|:---| +| [Trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/index/) | View prebuilt dashboards of traces and services, including latency, error rate, and throughput, for data ingested using Data Prepper or Jaeger. | Classic navigation and Observability workspaces | +| [Traces]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-traces/) | Search and filter spans and view a single trace as a timeline of its spans. | Observability workspaces | +| [Application performance monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/apm/) | View rate, error, and duration (RED) metrics for each service and a topology map of service dependencies. | Observability workspaces | +| [Agent monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/) | View the steps, tool calls, and token usage of generative AI agents. | Observability workspaces | + +In an Observability workspace, APM replaces Trace analytics when APM and Discover Traces are both enabled. For the settings that enable each app, see [Observability workspace apps]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/). + +For traces that OpenSearch generates for the requests it processes, see [Distributed tracing]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/distributed-tracing/). + +## Visualizing your data + +To share visualizations with your team, add them to a dashboard. In classic navigation, use [operational panels]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels/), and in an Observability workspace, add them to [dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/#adding-visualizations-to-dashboards) from the Logs page. To combine visualizations, queries, and text into reports and runbooks, use [Notebooks]({{site.url}}{{site.baseurl}}/dashboards/notebooks/), which are available in both classic navigation and Observability workspaces. diff --git a/_observing-your-data/exploring-observability-data/correlations.md b/_observing-your-data/exploring-observability-data/correlations.md new file mode 100644 index 00000000..646cb9c8 --- /dev/null +++ b/_observing-your-data/exploring-observability-data/correlations.md @@ -0,0 +1,137 @@ +--- +layout: default +title: Correlations +nav_order: 40 +parent: Observability workspace apps +redirect_from: + - /observability-plugin/correlations/ +--- + +# Correlations +**Introduced 3.5** +{: .label .label-purple } + +Correlations allow you to link trace datasets with logs datasets, enabling you to view related log entries when analyzing distributed traces. Correlating datasets helps you quickly identify the root cause of issues by connecting trace spans to their corresponding application logs. + +When troubleshooting distributed systems, you often need to correlate data across multiple sources. A trace might show that a request failed, but the detailed error information is in your application logs. Using correlations, you can: + +- Link a single trace dataset to up to five logs datasets. +- View related logs directly from the span details panel. +- Navigate seamlessly between trace analysis and log exploration. + +## Prerequisites + +Before using correlations, ensure that you have fulfilled the following prerequisites: + +1. **Enable feature flags**: Add the following settings to your `opensearch_dashboards.yml` file: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + datasetManagement.enabled: true + ``` + {% include copy.html %} + + After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +1. **Create datasets**: You must have at least one trace dataset and one logs dataset configured. For detailed instructions, see [Datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/). + +1. **Configure schema mappings**: Your logs datasets must have schema mappings configured. At a minimum, you need to map the **Trace ID** field so that logs can be matched to traces. + +## Correlation requirements + +For correlations to work correctly, your logs data must include the following fields that can be mapped to trace context. + +| Field | Purpose | +|:------|:--------| +| **Trace ID** | Links log entries to specific traces | +| **Span ID** | Links log entries to specific spans | +| **Service name** | Filters logs by service | +| **Timestamp** | Orders log entries chronologically | + +If your logs do not follow OpenTelemetry conventions, configure schema mappings in your logs dataset to map your custom field names to these standard fields. + +## Creating a trace-to-logs correlation + +To create a correlation between a trace dataset and logs datasets, follow these steps: + +1. Navigate to **Datasets** in the left navigation. + +2. Select the trace dataset you want to correlate with logs. + +3. In the dataset details page, select the **Correlated datasets** tab, as shown in the following image. + + ![Trace dataset Correlated datasets tab]({{site.url}}{{site.baseurl}}/images/datasets/correlations-trace-dataset-tab.png) + +4. Select **Configure correlation**. + +5. In the **Configure correlation** dialog, select up to five logs datasets to correlate with this trace dataset, as shown in the following image. + + ![Configure correlation dialog]({{site.url}}{{site.baseurl}}/images/datasets/correlations-configure-dialog.png) + +6. Select **Save** to create the correlation. + +7. The correlated logs datasets now appear in the **Correlated datasets** table, as shown in the following image. + + ![Created correlation in table]({{site.url}}{{site.baseurl}}/images/datasets/correlations-created-table.png) + +## Viewing correlations in logs datasets + +You can view the trace datasets that are correlated with a logs dataset from the logs dataset details: + +1. Navigate to **Datasets** in the left navigation. + +2. Select a logs dataset that has been correlated with a trace dataset. + +3. Select the **Correlated traces** tab to view trace datasets linked with this logs dataset, as shown in the following image. + + ![Logs dataset Correlated traces tab]({{site.url}}{{site.baseurl}}/images/datasets/correlations-logs-dataset-tab.png) + +This view is read-only. To modify correlations, you must edit them from the trace dataset. +{: .note} + +## Using correlations in the Traces page + +After creating correlations, you can access related logs when analyzing traces. + +### Viewing related logs in span details + +1. In the left navigation, select **Application performance** > **Traces**. + +2. Select a trace to view its details. + +3. Select a span within the trace to open the **Span details**. + +4. In **Span details**, select the **Logs** tab to open **Related logs**, as shown in the following image. The related logs are retrieved by matching the trace ID from the span to log entries in your correlated logs datasets. + + ![Span details with related logs]({{site.url}}{{site.baseurl}}/images/datasets/correlations-span-details-logs.png) + +6. Select a log entry to view its full details or navigate to the **Logs** page for further exploration. + +## Managing correlations + +You can edit or remove correlations from the trace dataset details page. + +### Editing correlations + +To modify an existing correlation, follow these steps: + +1. Navigate to **Datasets** in the left navigation and select the trace dataset you want to modify. +2. Select the **Correlated datasets** tab. +3. Select **Configure correlation** to modify the list of correlated logs datasets. +4. Add or remove datasets as needed. +5. Select **Save** to apply changes. + +### Removing correlations + +To remove a correlation: + +1. Navigate to **Datasets** in the left navigation and select the trace dataset you want to modify. +2. Select the **Correlated datasets** tab. +3. Delete the configured correlations using the delete icon. + +## Related documentation + +- [Datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/) -- Create and manage datasets. +- [Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) -- Ingest OpenTelemetry data into OpenSearch. diff --git a/_observing-your-data/exploring-observability-data/datasets.md b/_observing-your-data/exploring-observability-data/datasets.md new file mode 100644 index 00000000..1e5d35e4 --- /dev/null +++ b/_observing-your-data/exploring-observability-data/datasets.md @@ -0,0 +1,143 @@ +--- +layout: default +title: Datasets +nav_order: 10 +parent: Observability workspace apps +redirect_from: + - /observability-plugin/datasets/ +--- + +# Datasets +**Introduced 3.5** +{: .label .label-purple } + +A _dataset_ represents a collection of indexes that you want to analyze together. Datasets provide a user-friendly way to organize and access your observability data in OpenSearch Dashboards. Datasets allow you to assign types, names, and descriptions to your data sources and indexes, making it easier to work with logs and traces. + +Datasets offer several advantages over traditional index patterns: + +- **User-friendly names**: Assign descriptive names instead of relying on index pattern syntax. +- **Descriptions**: Add context about what data the dataset contains. +- **Schema mappings**: Map fields from non-standard formats to OpenTelemetry-compatible fields for correlation. +- **Type-specific behavior**: Logs and traces datasets integrate with their respective Discover pages. + +## Dataset types + +OpenSearch supports the following dataset types. + +| Type | Description | Use case | +|:-----|:------------|:---------| +| **Logs** | Generic log data for analytics and exploration | Application logs, system logs, access logs | +| **Traces** | OpenTelemetry span data ingested through OpenSearch Data Prepper | Distributed tracing, performance monitoring | + +## Prerequisites + +Before using datasets, ensure that you have fulfilled the following prerequisites: + +1. **Enable feature flags**: Add the following settings to your `opensearch_dashboards.yml` file: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + datasetManagement.enabled: true + # Required to create datasets from indexes in other OpenSearch clusters + data_source.enabled: true + ``` + {% include copy.html %} + + The `data_source.enabled` setting enables multiple data sources. For more information, see [Configuring and using multiple data sources]({{site.url}}{{site.baseurl}}/dashboards/management/multi-data-sources/). Some classic observability apps are not available when multiple data sources are enabled. For more information, see [Classic observability apps]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/). + + After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +1. **Index data**: Your log or trace data must already be indexed in OpenSearch. + +1. **Ensure appropriate permissions**: You need permissions to create and manage datasets in your workspace. + +## Creating a logs dataset + +To create a logs dataset, follow these steps: + +1. In the workspace left navigation, select **Datasets**. + +2. Select **Create dataset** and choose **Logs** from the dropdown menu. + +3. In **Step 1: Select data**, select your data source, as shown in the following image. You can use wildcard patterns (for example, `logs-*`) to match multiple indexes. + + ![Selecting a data source]({{site.url}}{{site.baseurl}}/images/datasets/datasets-select-data-source.png) + +4. In **Step 2: Configure data**, configure the dataset settings, as shown in the following image. + + ![Configuring logs dataset settings]({{site.url}}{{site.baseurl}}/images/datasets/datasets-configure-logs.png) + + You can configure the following settings: + + - **Name** -- Enter a descriptive name for the dataset. + - **Description** (Optional) -- Add the data description. + - **Time field**: Choose the timestamp field for time-based queries. + - **Schema mappings** (Optional) -- Map your log fields to standard OpenTelemetry fields for correlation with traces: + - **Trace ID field**: The field containing trace identifiers. + - **Span ID field**: The field containing span identifiers. + - **Service name field**: The field containing service names. + - **Timestamp field**: The field containing event timestamps. + +5. Select **Create dataset** to save your configuration. + +## Creating a traces dataset + +To create a traces dataset, follow these steps: + +1. In the workspace left navigation, select **Datasets**. + +2. Select **Create dataset** and choose **Traces** from the dropdown menu. + +3. In **Step 1: Select data**, select your trace data source. The data source must reference indexes containing OpenTelemetry span data ingested using Data Prepper. + +4. In **Step 2: Configure data**, configure the dataset settings, as shown in the following image. + + ![Configuring traces dataset settings]({{site.url}}{{site.baseurl}}/images/datasets/datasets-configure-traces.png) + + You can configure the following settings: + + - **Name** -- Enter a descriptive name for the dataset. + - **Description** (Optional) -- Add the data description. + - **Time field** -- Choose the timestamp field (typically, `startTime` or `@timestamp`). + +5. Select **Create dataset** to save your configuration. + +## Viewing datasets + +After creating datasets, you can view and manage them from the **Datasets** page using the following steps: + +1. In the workspace left navigation, select **Datasets**. + +2. The list view displays all datasets with their names, types, and data sources, as shown in the following image. + + ![Datasets list view]({{site.url}}{{site.baseurl}}/images/datasets/datasets-list.png) + +3. Select a dataset to view its details, including configuration settings and any correlations. + +## Analyzing datasets in Discover pages + +Datasets integrate with the Discover interface for exploring your data. + +### Logs datasets + +To analyze logs datasets, follow these steps: + +1. In the left navigation, select **Logs**. +2. From the dataset selector, select your logs dataset. +3. Use Piped Processing Language (PPL) queries to explore and analyze your log data. + +### Traces datasets + +To analyze traces datasets, follow these steps: + +1. In the left navigation, select **Application performance** > **Traces**. +2. Select your traces dataset from the dataset selector. +3. Explore span data and trace flows. + +## Related documentation + +- [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/) -- Compare datasets to traditional index patterns. +- [Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) -- Ingest OpenTelemetry data into OpenSearch. +- [Correlations]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/correlations/) -- Link traces and logs datasets. diff --git a/_observing-your-data/exploring-observability-data/discover-logs.md b/_observing-your-data/exploring-observability-data/discover-logs.md new file mode 100644 index 00000000..e8a3fd5a --- /dev/null +++ b/_observing-your-data/exploring-observability-data/discover-logs.md @@ -0,0 +1,173 @@ +--- +layout: default +title: Logs +nav_order: 20 +parent: Observability workspace apps +redirect_from: + - /observability-plugin/discover-logs/ +--- + +# Analyzing logs in Discover +**Introduced 3.5** +{: .label .label-purple } + +The **Logs** page in OpenSearch Dashboards is a log analytics tool that allows you to explore and analyze application logs using Piped Processing Language (PPL). On this page, you can query log data, create visualizations from aggregated results, and add these visualizations to dashboards. + +The **Logs** page provides the following capabilities: + +- **PPL-based querying**: Use PPL syntax to filter, aggregate, and transform log data. +- **Automatic visualization**: When you use aggregation commands like `stats`, the interface automatically switches to a visualization view. +- **Multiple visualization types**: Choose from various visualization types. +- **Dashboard integration**: Save visualizations directly to new or existing dashboards. +- **Query management**: Save queries for reuse and access recent queries. + +## Prerequisites + +Before using the **Logs** page, ensure that you have fulfilled the following prerequisites: + +1. **Enable feature flags**: Add the following settings to your `opensearch_dashboards.yml` file: + + ```yaml + workspace.enabled: true + explore.enabled: true + ``` + {% include copy.html %} + + After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +2. **Create an observability workspace**: You must be working within an observability workspace. The **Logs** page is only available in this workspace type. + + Note: Workspaces are not compatible with multi-tenancy. To enable workspaces, you must first disable multi-tenancy by setting `opensearch_security.multitenancy.enabled: false`. + {: .note} + +3. **Configure a logs dataset**: You must have at least one logs dataset configured. For detailed instructions, see [Datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/). + +## Accessing the logs page + +To access the **Logs** page: + +1. Navigate to an observability workspace in OpenSearch Dashboards. +2. In the left navigation, select **Logs**. + +## Exploring log data + +The **Logs** page is shown in the following image. + +![Discover logs interface]({{site.url}}{{site.baseurl}}/images/discover-logs/discover-logs-interface.png) + +It consists of the following components: + +- **PPL editor**: The query bar at the top where you write PPL queries. +- **Dataset selector**: Select the logs dataset to explore from the dropdown list at the top of the page. +- **Recent queries**: Access previously run queries at the top of the page. +- **Saved queries**: Access queries you have saved for reuse at the top of the page. +- **Fields**: Located on the left side, the **Fields** panel displays available fields organized into **Selected** fields and **Query** fields sections. +- **Log count**: The **Log count** histogram shows the distribution of log entries over time. Use the **Interval** selector to adjust the time bucket size. +- **Results area**: Displays query results with two tabs: + - **Logs**: Shows individual log entries in a table format. + - **Visualization**: Displays aggregated data as charts when using `stats` commands. +- **Time range selector**: Located in the upper-right corner, allows you to set the time range for your query. + +## Querying logs using PPL + +You can use PPL for querying log data. PPL allows you to chain commands using the pipe character (`|`) to filter, transform, and aggregate data. + +### Basic queries + +To retrieve all logs from your dataset, run a query without any filters by entering a query and selecting **Refresh**. The results appear in the **Logs** tab showing individual log entries. + +### Filtering using the WHERE clause + +Use the `WHERE` clause to filter logs based on field values: + +```sql +| WHERE `resource.attributes.service.name` = 'frontend-proxy' +``` +{% include copy.html %} + +You can combine multiple conditions by providing several `WHERE` clauses: + +```sql +| WHERE `resource.attributes.service.name` = 'frontend-proxy' +| WHERE `attributes.url.path` in ("/api/cart","/api/checkout") +``` +{% include copy.html %} + +### Managing queries + +The **Logs** page provides tools to help you organize and reuse your PPL queries efficiently. + +- **Recent queries**: Select **Recent queries** to view and rerun previously executed queries. +- **Saved queries**: Select **Saved queries** to access queries you have saved. To save the current query, select **Actions** > **Save query**. + +## Creating visualizations from logs + +When you use the `stats` command to aggregate data, the **Logs** page automatically switches to the **Visualization** tab to display the results as a chart. + +### Using the stats command + +The `stats` command aggregates data based on specified fields. For example, to count logs per minute grouped by URL path, use the following query: + +```sql +| WHERE `resource.attributes.service.name` = 'frontend-proxy' +| WHERE `attributes.url.path` in ("/api/cart","/api/checkout") +| STATS count() by span(time, 1m), `attributes.url.path` +``` +{% include copy.html %} + +When you run this query, the interface automatically switches to the **Visualization** tab and displays a chart, as shown in the following image. + +![Visualization from logs]({{site.url}}{{site.baseurl}}/images/discover-logs/discover-logs-visualization.png) + +### Visualization types + +To change the visualization type, go to **Settings** > **Visualization type** and select one of the available options, as shown in the following image. + +![Visualization type options]({{site.url}}{{site.baseurl}}/images/discover-logs/discover-logs-viz-types.png) + +The following visualization types are available. + +| Type | Description | +|:-----|:------------| +| **Line** | Displays data as connected points; ideal for showing trends over time. | +| **Area** | Similar to line charts but with the area below the line filled in. | +| **Bar** | Displays data as vertical or horizontal bars for comparing categories. | +| **Metric** | Shows a single aggregated value as a large number.| +| **State timeline** | Displays state changes over time on a horizontal timeline. | +| **Heatmap** | Uses color intensity to represent values in a matrix format. | +| **Bar Gauge** | Displays values as horizontal bars with configurable thresholds. | +| **Pie** | Shows proportions as slices of a circular chart. | + +### Visualization settings + +To customize your visualization, update the options in the **Settings** panel, shown in the following image. + +![Bar chart with switched axes]({{site.url}}{{site.baseurl}}/images/discover-logs/discover-logs-switch-axes.png) + +You can update the following options: + +- **Fields**: Configure the fields to display on the **X-Axis**, **Y-Axis**, and **Color** (for grouping data series by different values). For bar charts, you can toggle **Switch axes** in the Fields section to change the chart orientation from vertical to horizontal (swap X and Y axes). +- **Bar/Bucket**: For bar charts, configure bar size (**Auto** or **Manual**) and bucket settings (**Type** and **Interval**). +- **Thresholds**: Define value thresholds using custom colors. +- **Axes**: Configure axes labels, scales, and formatting. +- **Legend**: Control legend visibility and position. + +## Adding visualizations to dashboards + +You can save your visualizations directly to dashboards for ongoing monitoring using the following steps: + +1. After creating a visualization, select **Add to dashboard** in the results area. + +2. In the **Save and Add to Dashboard** dialog, choose one of the following options: + - **Save to existing dashboard**: Select an existing dashboard from the dropdown. + - **Save to new dashboard**: Enter a name for the new dashboard. + +3. Enter a name for the saved search in the **Save search** field. + +4. Select **Add** to save the visualization to the dashboard. + +## Related documentation + +- [Datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/) -- Create and manage logs datasets. +- [PPL]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) -- Learn PPL query syntax. +- [Correlations]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/correlations/) -- Link logs and traces datasets. diff --git a/_observing-your-data/exploring-observability-data/discover-metrics.md b/_observing-your-data/exploring-observability-data/discover-metrics.md new file mode 100644 index 00000000..f28e6ce3 --- /dev/null +++ b/_observing-your-data/exploring-observability-data/discover-metrics.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Metrics +nav_order: 30 +parent: Observability workspace apps +--- + +# Analyzing metrics in Discover +**Introduced 3.5** +{: .label .label-purple } + +The **Metrics** page in OpenSearch Dashboards provides a dedicated interface for discovering, querying, and visualizing time-series metric data. This page, shown in the following image, is optimized for working with Prometheus metrics using PromQL. + +![Metrics page interface]({{site.url}}{{site.baseurl}}/images/dashboards/prometheus.png){: width="700" } + +The **Metrics** page is available in observability workspaces. To access the **Metrics** page, navigate to an **Observability** workspace. Then, in the left navigation, select **Metrics**. + +## Prerequisites + +Before using the **Metrics** page, ensure that you have fulfilled the following prerequisites: + +1. **Enable feature flags**: Add the following settings to your `opensearch_dashboards.yml` file: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverMetrics.enabled: true + ``` + {% include copy.html %} + + After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +1. **Create an observability workspace**: You must be working within an observability workspace. The **Metrics** page is only available in this workspace type. + +1. **Configure a Prometheus data source**: You must configure a Prometheus data source. For instructions, see [Configuring a Prometheus data source](#configuring-a-prometheus-data-source). + +## Configuring a Prometheus data source + +Before you start, configure a Prometheus data source using one of the following methods. + +### Configuring a Prometheus data source in OpenSearch Dashboards + +To configure a Prometheus data source in OpenSearch Dashboards, follow these steps: + +1. In the left navigation, go to **Data Administration** > **Data sources**. +1. Select **Create data source**. +1. Select **Prometheus**. +1. Enter a **Data source name** and optional **Description**. +1. Enter the **Prometheus URI** endpoint (for example, `http://prometheus-server:9090`). +1. Configure the **Authentication method**: + - **No authentication**: Use if your Prometheus server does not require authentication. + - **Basic authentication**: Enter a username and password. + - **AWS Signature Version 4**: Use for Amazon Managed Service for Prometheus. +1. Select **Connect**. + +### Configuring a Prometheus data source using the API + +Alternatively, you can configure a Prometheus data source programmatically. For more information, see [Data sources]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/). + +## Query panel + +You can write and execute metric queries in the query panel at the top of the **Metrics** page. The query editor provides autocomplete suggestions and syntax highlighting for PromQL. + +### Writing queries + +Write queries using PromQL syntax. For example: + +```json +up{job="prometheus"} +``` +{% include copy.html %} + +### Running queries + +To run a query, enter your query in the query editor and then select the **Refresh** button. + +You can run multiple PromQL queries together by separating them with a semicolon (`;`): + +```json +up{job="prometheus"}; +node_cpu_seconds_total{mode="idle"}; +``` +{% include copy.html %} + +Each query runs independently, and the results are combined in the output. + +## Time filter + +Use the time filter to specify the time range for your metric data. Select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>{:/} (calendar) icon to access the time filter options: + +- **Quick select**: Choose a relative time range (for example, the last 15 minutes or the last 1 hour). +- **Commonly used**: Select from predefined time ranges. +- **Custom**: Specify absolute start and end times. +- **Auto-refresh**: Set an automatic refresh interval. + +For more information, see [Time filter]({{site.url}}{{site.baseurl}}/dashboards/discover/time-filter/). + +## Viewing results + +After running a query, the results are displayed in a tabbed interface containing the following views: + +- The **Metrics** tab displays the latest data point for each series in a table format. + +- The **Raw** tab shows the latest data point for each series as raw JSON returned by the data source. + +- The **Visualization** tab provides interactive charts for your metric data. + +#### Configuring visualizations + +When the **Visualization** tab is selected, a settings panel appears on the right side of the screen. Use this panel to: + +1. **Select a chart type**: Choose from line, bar, pie, gauge, or table visualizations. +2. **Map axes**: Assign fields to the X and Y axes. +3. **Customize styles**: Adjust colors, legends, gridlines, and other visual options. + +When you modify the settings, the visualization is updated automatically. diff --git a/_observing-your-data/exploring-observability-data/discover-traces.md b/_observing-your-data/exploring-observability-data/discover-traces.md new file mode 100644 index 00000000..18a7c9a8 --- /dev/null +++ b/_observing-your-data/exploring-observability-data/discover-traces.md @@ -0,0 +1,115 @@ +--- +layout: default +title: Traces +nav_order: 30 +parent: Application performance monitoring +grand_parent: Observability workspace apps +--- + +# Analyzing traces in Discover +**Introduced 3.5** +{: .label .label-purple } + +The Discover **Traces** page in OpenSearch Dashboards provides an enhanced way to explore and analyze trace data within Observability workspaces. This page extends the traditional Discover experience by offering specialized capabilities for working with trace data. + +## Prerequisites + +Before using the **Traces** page, ensure that you have fulfilled the following prerequisites: + +1. **Enable feature flags**: Add the following settings to your `opensearch_dashboards.yml` file: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + ``` + {% include copy.html %} + + After updating the configuration file, restart OpenSearch Dashboards for the changes to take effect. + +2. **Create an observability workspace**: You must be working within an observability workspace. The **Traces** page is only available in this workspace type. + + Note: Workspaces are not compatible with multi-tenancy. To enable workspaces, you must first disable multi-tenancy by setting `opensearch_security.multitenancy.enabled: false`. + {: .note} + +3. **Configure a traces dataset**: You must have at least one traces dataset configured. For detailed instructions, see [Datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/). + +## Accessing the traces page + +To access the **Traces** page: + +1. Navigate to an **Observability** workspace in OpenSearch Dashboards. +2. In the left navigation, select **Application performance** > **Traces**. + +![Discover Traces page in navigation]({{site.url}}{{site.baseurl}}/images/discover-traces/trace-page.png) + +## Configuring trace datasets + +To configure trace datasets, use one of the following options. + +### Automatic dataset creation + +If your data source follows the OpenTelemetry naming conventions, the **Traces** page can automatically create trace and log datasets from your data by searching for indexes with the following naming patterns: + +- **Traces**: `otel-v1-apm-span*` +- **Correlated logs**: `logs-otel-v1*` + +When these indexes are detected, select the **Create Trace Datasets** button, as shown in the following image, to automatically generate the datasets and establish the correlation relationship between traces and logs. + +![Auto-create trace datasets]({{site.url}}{{site.baseurl}}/images/discover-traces/trace-auto-create.png) + +### Manual dataset creation + +If your indexes use different naming conventions, you must manually create the datasets and configure the correlation relationships between traces and logs. Navigate to the **Datasets** tab and create a dataset with the **Trace** signal type. + +## Exploring trace data + +The **Traces** page provides comprehensive tools for analyzing span data and understanding trace performance, including: + +- **RED metrics**: View Rate, Errors, and Duration (RED) metrics at the top of the page to quickly assess trace performance and health. +- **Faceted fields**: Use faceted field filters to filter and analyze specific aspects of your traces. +- **Span table**: Browse spans using sortable columns and quick access to detailed information. + +### Viewing a specific span + +To view detailed information about a specific span, select the timestamp in the span table. This opens the **Trace Details** flyout, shown in the following image. + +![Trace details flyout]({{site.url}}{{site.baseurl}}/images/discover-traces/trace-details-flyout.png) + +The **Trace Details** flyout displays the following information: + +- The relationship of the selected span within its parent trace. +- The hierarchical structure showing how the span relates to other spans in the same trace. +- The span attributes and metadata. + +### Trace detail page + +To access the full trace detail page from the **Trace Details** flyout, use one of the following options: + +- Select the **span ID** from the **Traces** page table. +- Select **Open full page** from the flyout. + +The full page view provides an expanded interface for deeper trace analysis, featuring a timeline visualization that shows the hierarchical span relationships and durations, along with detailed span information in a side panel, as shown in the following image. + +![Discover Traces page with RED metrics and faceted fields]({{site.url}}{{site.baseurl}}/images/discover-traces/trace-detail-page.png) + +## Correlating traces with logs + +The **Traces** page provides seamless integration with log data, allowing you to navigate from traces to related logs while preserving proper context. + +### Viewing related logs + +To view the related logs, follow these steps: + +1. In the **Trace Details** flyout, locate the **Related logs** section. +1. Select the **View in Discover Logs** button to navigate to the correlated log entries for the selected trace, as shown in the following image. + +![Related logs button in trace details]({{site.url}}{{site.baseurl}}/images/discover-traces/related-logs.png) + +### Log redirection with context + +When you select **View in Discover Logs**, OpenSearch Dashboards automatically redirects you to the **Logs** page with the trace context applied, as shown in the following image. + +![Discover Logs page with trace context]({{site.url}}{{site.baseurl}}/images/discover-traces/logs-redirection.png) + +The logs are filtered to show only entries related to the selected trace, making it easier to troubleshoot issues and understand the full context of trace events. Preserving context streamlines the debugging process by providing a unified view of your telemetry data, helping you identify root causes and understand the complete picture of application behavior. diff --git a/_observing-your-data/exploring-observability-data/index.md b/_observing-your-data/exploring-observability-data/index.md new file mode 100644 index 00000000..3794d2b0 --- /dev/null +++ b/_observing-your-data/exploring-observability-data/index.md @@ -0,0 +1,73 @@ +--- +layout: default +title: Observability workspace apps +nav_order: 50 +has_children: true +has_toc: false +description: "Set up an Observability workspace to explore logs, traces, and metrics in Discover and to use application performance monitoring, service-level objectives, and agent monitoring." +redirect_from: + - /observing-your-data/exploring-observability-data/ +--- + +# Observability workspace apps +**Introduced 3.5** +{: .label .label-purple } + +In an Observability [workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/index/), OpenSearch Dashboards provides apps for exploring logs, traces, and metrics in Discover, monitoring application performance, tracking service-level objectives (SLOs), and monitoring generative AI agents. Each app is enabled by a setting in `opensearch_dashboards.yml`, which is listed on the app's page. + +## Prerequisites + +To enable all Observability workspace apps, add the following settings to `opensearch_dashboards.yml`, and then restart OpenSearch Dashboards: + +```yaml +workspace.enabled: true +explore.enabled: true # Logs +explore.discoverTraces.enabled: true # Traces, APM, and SLOs +explore.discoverMetrics.enabled: true # Metrics and APM +explore.agentTraces.enabled: true # Agent monitoring +datasetManagement.enabled: true # Datasets and Correlations +observability.slo.enabled: true # SLOs +``` +{% include copy.html %} + +To enable only some of the apps, see the Prerequisites section of each app's page for the settings that the app requires. + +Workspaces have additional requirements, such as disabling multi-tenancy. For more information, see [Enabling workspaces]({{site.url}}{{site.baseurl}}/dashboards/workspace/workspace/#enabling-workspaces). + +## Creating an Observability workspace + +To create an Observability workspace, follow these steps: + +1. On the OpenSearch Dashboards home page, in **My workspaces**, select **Create workspace** on the **Observability** card. +1. In **Workspace details**, enter a **Name** and, optionally, a **Description**. +1. In **Use case and features**, confirm that **Observability** is selected. +1. If you use multiple data sources, select the data sources to associate with the workspace. +1. Select **Create workspace**. + +For more information, see [Create a workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/create-workspace/). + +## Exploring and monitoring your data + +After you create the workspace, use the apps as follows: + +1. Connect your data: + - Create [datasets]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/datasets/) for your log and trace indexes. The Logs and Traces pages, Correlations, and APM use datasets to find your data. + - To use Metrics, APM, or SLOs, connect a [Prometheus data source]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/). +1. Explore your data: + - Use [Logs]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/) to search, filter, and visualize log data using Piped Processing Language (PPL). + - Use [Traces]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-traces/) to search and filter spans and view a single trace as a timeline of its spans. + - Use [Metrics]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-metrics/) to query and visualize Prometheus metrics using PromQL. + - Use [Correlations]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/correlations/) to link a trace dataset to logs datasets so that you can view the log entries related to a trace. +1. Monitor your applications: + - Use [application performance monitoring (APM)]({{site.url}}{{site.baseurl}}/observing-your-data/apm/) to view rate, error, and duration (RED) metrics for each service and a topology map of service dependencies. + - Use [SLOs]({{site.url}}{{site.baseurl}}/observing-your-data/slo/) to define availability and latency targets for your services and track their error budgets. +1. Monitor your AI agents: + - Use [Agent monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/) to view the LLM calls, tool invocations, and token usage of generative AI agents. +1. Share your results: + - Add visualizations from the Logs page to [dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/#adding-visualizations-to-dashboards). + - Use [Notebooks]({{site.url}}{{site.baseurl}}/dashboards/notebooks/) to combine Markdown text, SQL and PPL queries, and visualizations into reports and runbooks. + +## Related documentation + +- To learn how logs, traces, and metrics reach OpenSearch, see [Ingesting observability data]({{site.url}}{{site.baseurl}}/observing-your-data/ingesting-observability-data/). +- To choose between the apps that display trace data, see [Choosing a trace tool]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-data/#choosing-a-trace-tool). \ No newline at end of file diff --git a/_observing-your-data/forecast/api.md b/_observing-your-data/forecast/api.md new file mode 100644 index 00000000..54c4c8a1 --- /dev/null +++ b/_observing-your-data/forecast/api.md @@ -0,0 +1,1280 @@ +--- +layout: default +title: Forecasting API +parent: Forecasting +nav_order: 100 +--- + +# Forecasting API + +Use these operations to programmatically create and manage forecasters that generate forecasts over your time‑series data. + +--- + +## Table of contents +- TOC +{:toc} + +--- + +## Create forecaster + +**Introduced 3.1** +{: .label .label-purple } + +Creates a forecaster for generating time-series forecasts. A forecaster can be either single-stream (without a category field) or high-cardinality (with one or more category fields). + +When creating a forecaster, you define the source indexes, the forecast interval and horizon, the feature to forecast, and optional parameters such as category fields and a custom result index. + + +### Endpoint + +``` +POST _plugins/_forecast/forecasters +``` + +### Request body fields + +This API supports the following request body fields. + +| Field | Data type | Required | Description | +| :---------------------------- | :------------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | String | Required | The forecaster name. | +| `description` | String | Optional | A free-form description of the forecaster. | +| `time_field` | String | Required | The timestamp field for the source documents. | +| `indices` | String or string\[] | Required | One or more source indexes or index aliases. | +| `feature_attributes` | Array of objects | Required | The feature to forecast. Only one feature is supported. Each object must include the `feature_name` and an `aggregation_query`. | +| `forecast_interval` | Object | Required | The interval over which forecasts are generated. | +| `horizon` | Integer | Optional | The number of future intervals to forecast. | +| `window_delay` | Object | Optional | A delay added to account for ingestion latency. | +| `category_field` | String | Optional | One or two fields used to group forecasts by entity. | +| `result_index` | String | Optional | A custom index alias for storing forecast results. Must begin with `opensearch-forecast-result-`. Defaults to `opensearch-forecast-results`. | +| `suggested_seasonality` | Integer | Optional | The seasonal pattern length in intervals. Expected range: 8–256. | +| `recency_emphasis` | Integer | Optional | Controls how much recent data affects the forecast. Defaults to `2560`. | +| `history` | Integer | Optional | The number of past intervals used for model training. | +| `result_index_min_size` | Integer | Optional | The minimum primary shard size (in MB) required to trigger index rollover. | +| `result_index_min_age` | Integer | Optional | The minimum index age (in days) required to trigger index rollover. | +| `result_index_ttl` | Integer | Optional | The minimum amount of time (in days) before rolled-over indexes are deleted. | +| `flatten_custom_result_index` | Boolean | Optional | If `true`, flattens nested fields in the custom result index for easier aggregation. | +| `shingle_size` | Integer | Optional | The number of past intervals used to influence the forecast. Defaults to `8`. Recommended range: 4–128. | + + +### Example request: Single-stream forecaster + +The following example creates a single-stream forecaster for the `network-requests` index. The forecaster predicts the maximum value of the `deny` field every 3 minutes, using the previous 300 intervals for training. The `window_delay` setting accounts for ingest latency by delaying the forecast window by 3 minutes: + + +```json +POST _plugins/_forecast/forecasters +{ + "name": "Second-Test-Forecaster-7", + "description": "ok rate", + "time_field": "@timestamp", + "indices": [ + "network-requests" + ], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "importance": 1, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ], + "window_delay": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "forecast_interval": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "schema_version": 2, + "horizon": 3, + "history": 300 +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_id": "4WnXAYoBU2pVBal92lXD", + "_version": 1, + "forecaster": { + "...": "Configuration (omitted)" + } +} +``` + +### Example request: High-cardinality forecaster + +The following example creates a high-cardinality forecaster that groups forecasts by the `host_nest.host2` field. Like the single-stream example, it forecasts the maximum value of the `deny` field at 3-minute intervals using historical data. This setup enables entity-specific forecasting across different hosts: + +```json +POST _plugins/_forecast/forecasters +{ + "name": "Second-Test-Forecaster-7", + "description": "ok rate", + "time_field": "@timestamp", + "indices": [ + "network-requests" + ], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "importance": 1, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ], + "window_delay": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "forecast_interval": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "schema_version": 2, + "horizon": 3, + "history": 300, + "category_field": ["host_nest.host2"], +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_id": "4WnXAYoBU2pVBal92lXD", + "_version": 1, + "forecaster": { + "...": "Configuration (omitted)" + } +} +``` + + +--- + + +## Validate forecaster + +**Introduced 3.1** +{: .label .label-purple } + +Use this API to verify that a forecaster configuration is valid. You can perform two types of validation: + +- **Configuration-only validation**: Checks that the configuration is syntactically correct and references existing fields. +- **Training-feasibility validation**: Performs a comprehensive validation to ensure that the forecaster can be trained with the specified configuration. + + +### Endpoints + +The following endpoints are available for validating forecasters. + +**Configuration-only validation**: + +```http +POST _plugins/_forecast/forecasters/_validate +``` + +**Training-feasibility validation**: + +```http +POST _plugins/_forecast/forecasters/_validate/model +``` + +### Request body + +The request body is identical to the request body used to create a forecaster. It must include at least the following required fields: `name`, `time_field`, `indices`, `feature_attributes`, and `forecast_interval`. + +If the configuration is valid, the response returns an empty object (`{}`). If the configuration is invalid, the response includes detailed error messages. + + +### Example request: Missing `forecast_interval` + +The following request shows an invalid forecaster configuration that omits the `forecast_interval`: + +```json +POST _plugins/_forecast/forecasters/_validate +{ + "name": "invalid-forecaster", + "time_field": "@timestamp", + "indices": ["network-requests"], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "forecaster": { + "forecast_interval": { + "message": "Forecast interval should be set" + } + } +} +``` + + +--- + +## Suggest configuration + +**Introduced 3.1** +{: .label .label-purple } + +Returns appropriate values for one or more forecaster parameters (`forecast_interval`, `horizon`, `history`, `window_delay`) based on the cadence and density of your data. + + +### Endpoints + +``` +POST _plugins/_forecast/forecasters/_suggest/<comma‑separated-types> +``` + +`types` must be one or more of `forecast_interval`, `horizon`, `history`, or `window_delay`. + + +### Example request: Suggest an interval + +The following request analyzes the source data and suggests an appropriate `forecast_interval` value for the forecaster based on the average event frequency: + +``` +POST _plugins/_forecast/forecasters/_suggest/forecast_interval +{ + "name": "interval‑suggest", + "time_field": "@timestamp", + "indices": ["network-requests"], + ... +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "interval": { + "period": { "interval": 1, "unit": "Minutes" } + } +} +``` + +--- + +## Get forecaster + +**Introduced 3.1** +{: .label .label-purple } + +Retrieves a forecaster and (optionally) its most recent tasks. + +### Endpoints + +``` +GET _plugins/_forecast/forecasters/{forecaster_id}[?task=(true|false)] +``` + +### Example request: Include tasks + +The following request returns metadata about the forecaster and, if specified, details about its associated tasks: + +```json +GET _plugins/_forecast/forecasters/d7-r1YkB_Z-sgDOKo3Z5?task=true +``` +{% include copy-curl.html %} + +The response includes the `forecaster`, `realtime_task`, and `run_once_task` sections. + +--- + +## Update forecaster + +**Introduced 3.1** +{: .label .label-purple } + +Updates the configuration of an existing forecaster. You must stop any active forecasting jobs before making updates. + +Any change that affects the model, such as modifying the `category_field`, `result_index`, or `feature_attributes`, invalidates previous results shown in OpenSearch Dashboards. + +### Endpoints + +``` +PUT _plugins/_forecast/forecasters/{forecaster_id} +``` + + +### Example request: Update the name, result index, and category fields + +The following displays the definition of forecaster `forecaster-i1nwqooBLXq6T-gGbXI-`: + +```json +{ + "_index": ".opensearch-forecasters", + "_id": "forecaster-i1nwqooBLXq6T-gGbXI-", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "category_field": [ + "service" + ], + "description": "ok rate", + "feature_attributes": [{ + "feature_id": "deny_max", + "feature_enabled": true, + "feature_name": "deny max", + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + }], + "forecast_interval": { + "period": { + "unit": "Minutes", + "interval": 1 + } + }, + "schema_version": 2, + "time_field": "@timestamp", + "last_update_time": 1695084997949, + "horizon": 24, + "indices": [ + "network-requests" + ], + "window_delay": { + "period": { + "unit": "Seconds", + "interval": 20 + } + }, + "transform_decay": 1.0E-4, + "name": "Second-Test-Forecaster-3", + "filter_query": { + "match_all": { + "boost": 1.0 + } + }, + "shingle_size": 8, + "result_index": "opensearch-forecast-result-a" + } +} +``` + +The following request updates the `name`, `result_index`, and `category_field` properties of a forecaster: + +```json +PUT localhost:9200/_plugins/_forecast/forecasters/forecast-i1nwqooBLXq6T-gGbXI- +{ + "name": "Second-Test-Forecaster-1", + "description": "ok rate", + "time_field": "@timestamp", + "indices": [ + "network-requests" + ], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "importance": 1, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ], + "window_delay": { + "period": { + "interval": 20, + "unit": "SECONDS" + } + }, + "forecast_interval": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "ui_metadata": { + "aabb": { + "ab": "bb" + } + }, + "schema_version": 2, + "horizon": 24, + "category_field": ["service", "host"] +} +``` +{% include copy-curl.html %} + +--- + + +## Delete forecaster + +**Introduced 3.1** +{: .label .label-purple } + +Deletes a forecaster configuration. You must stop any associated real-time or run-once forecasting jobs before deletion. If a job is still running, the API returns a `400` error. + +### Endpoint + +```http +DELETE _plugins/_forecast/forecasters/{forecaster_id} +``` + +### Example request: Delete a forecaster + +The following request deletes a forecaster configuration using its unique ID: + +```http +DELETE _plugins/_forecast/forecasters/forecast-i1nwqooBLXq6T-gGbXI- +``` +{% include copy-curl.html %} + +--- + +## Start a forecaster job + +**Introduced 3.1** +{: .label .label-purple } + +Begins real-time forecasting for a forecaster. + +### Endpoints + +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/_start +``` + +### Example request: Start a forecaster job + +The following request initiates real-time forecasting for the specified forecaster: + +```bash +POST _plugins/_forecast/forecasters/4WnXAYoBU2pVBal92lXD/_start +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ "_id": "4WnXAYoBU2pVBal92lXD" } +``` + +--- + +## Stop a forecaster job + +**Introduced 3.1** +{: .label .label-purple } + +Stops real-time forecasting for a forecaster. + +### Endpoints +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/_stop +``` + +### Example request: Stop a forecaster job + +The following request stops the real-time forecasting job for the specified forecaster: + +```bash +POST _plugins/_forecast/forecasters/4WnXAYoBU2pVBal92lXD/_stop +``` +{% include copy-curl.html %} + + +--- + +## Run one analysis + +**Introduced 3.1** +{: .label .label-purple } + +Runs backtesting (historical) forecasting. It cannot run while a real-time job is active. + +### Endpoint +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/_run_once +``` + +### Example request: Run a backtesting forecast + +The following request starts a run-once forecast analysis for the specified forecaster: + +```bash +POST _plugins/_forecast/forecasters/{forecaster_id}/_run_once +``` +{% include copy-curl.html %} + +#### Example response + +The response returns the task ID assigned to the run-once job: + +```json +{ "taskId": "vXZG85UBAlM4LplcKI0f" } +``` + +### Example request: Search forecast results by task ID + +Use the returned `taskId` to query the `opensearch-forecast-results*` index for historical forecast output: + +```json +GET opensearch-forecast-results*/_search?pretty +{ + "sort": { + "data_end_time": "desc" + }, + "size": 10, + "query": { + "bool": { + "filter": [ + { "term": { "task_id": "vXZG85UBAlM4LplcKI0f" } }, + { + "range": { + "data_end_time": { + "format": "epoch_millis", + "gte": 1742585746033 + } + } + } + ] + } + }, + "track_total_hits": true +} +``` +{% include copy-curl.html %} + +This query returns the 10 most recent forecast results matching the specified task ID. + + +--- + +## Search forecasters + +**Introduced 3.1** +{: .label .label-purple } + +Provides standard `_search` functionality on the `.opensearch-forecasters` system index, which stores forecaster configurations. You must use this API to query `.opensearch-forecasters` directly because the index is a system index and cannot be accessed through regular OpenSearch queries. + +### Endpoint + +```http +GET _plugins/_forecast/forecasters/_search +``` + +### Example request: Wildcard search by index + +The following request searches for forecasters whose source index names begin with `network` using a leading-anchored wildcard: + +```json +GET _plugins/_forecast/forecasters/_search +{ + "query": { + "wildcard": { + "indices": { + "value": "network*" + } + } + } +} +``` +{% include copy-curl.html %} + +`network*` matches `network`, `network-metrics`, `network_2025-06`, and similar index names. + +#### Example response + +```json +{ + "took": 5, + "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-forecasters", + "_id": "forecast-i1nwqooBLXq6T-gGbXI-", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "category_field": ["server"], + "description": "ok rate", + "feature_attributes": [{ + "feature_id": "deny_max", + "feature_enabled": true, + "feature_name": "deny max", + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + }], + "forecast_interval": { + "period": { + "unit": "Minutes", + "interval": 1 + } + }, + "schema_version": 2, + "time_field": "@timestamp", + "last_update_time": 1695084997949, + "horizon": 24, + "indices": ["network-requests"], + "window_delay": { + "period": { + "unit": "Seconds", + "interval": 20 + } + }, + "transform_decay": 1.0E-4, + "name": "Second-Test-Forecaster-3", + "filter_query": { + "match_all": { + "boost": 1.0 + } + }, + "shingle_size": 8 + } + }] + } +} +``` + +--- + +## Search tasks + +**Introduced 3.1** +{: .label .label-purple } + +Query tasks in the `.opensearch-forecast-state` index. + +### Endpoint + +```http +GET _plugins/_forecast/forecasters/tasks/_search +``` + +### Example request: Search previous run-once tasks + +The following request retrieves previous run-once tasks (excluding the most recent) for a specific forecaster and sorts them by `execution_start_time` in descending order: + +```json +GET _plugins/_forecast/forecasters/tasks/_search +{ + "from": 0, + "size": 1000, + "query": { + "bool": { + "filter": [ + { "term": { "forecaster_id": { "value": "m5apnooBHh7Wss2wewfW", "boost": 1.0 }}}, + { "term": { "is_latest": { "value": false, "boost": 1.0 }}}, + { "terms": { + "task_type": [ + "RUN_ONCE_FORECAST_SINGLE_STREAM", + "RUN_ONCE_FORECAST_HC_FORECASTER" + ], + "boost": 1.0 + }} + ], + "adjust_pure_negative": true, + "boost": 1.0 + } + }, + "sort": [ + { "execution_start_time": { "order": "desc" }} + ] +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { "value": 1, "relation": "eq" }, + "max_score": null, + "hits": [ + { + "_index": ".opensearch-forecast-state", + "_id": "4JaunooBHh7Wss2wOwcw", + "_version": 3, + "_seq_no": 5, + "_primary_term": 1, + "_score": null, + "_source": { + "last_update_time": 1694879344264, + "execution_start_time": 1694879333168, + "forecaster_id": "m5apnooBHh7Wss2wewfW", + "state": "TEST_COMPLETE", + "task_type": "RUN_ONCE_FORECAST_SINGLE_STREAM", + "is_latest": false, + "forecaster": { + "description": "ok rate", + "ui_metadata": { "aabb": { "ab": "bb" }}, + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_enabled": true, + "feature_name": "deny max", + "aggregation_query": { + "deny_max": { + "max": { "field": "deny" } + } + } + } + ], + "forecast_interval": { + "period": { + "unit": "Minutes", + "interval": 1 + } + }, + "schema_version": 2, + "time_field": "@timestamp", + "last_update_time": 1694879022036, + "horizon": 24, + "indices": [ "network-requests" ], + "window_delay": { + "period": { + "unit": "Seconds", + "interval": 20 + } + }, + "transform_decay": 1.0E-4, + "name": "Second-Test-Forecaster-5", + "filter_query": { "match_all": { "boost": 1.0 }}, + "shingle_size": 8 + } + }, + "sort": [ 1694879333168 ] + } + ] + } +} +``` + +--- + +## Top forecasters +**Introduced 3.1** +{: .label .label-purple } + +Returns the *top‑k* entities for a given timestamp range, based on built‑in or custom metrics. + +### Endpoint + +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/results/_topForecasts +``` + +### Query parameters + +The following query parameters are supported. + +| Name | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| `split_by` | String | Required | The field to group by (such as `service`). | +| `forecast_from` | Epoch‑ms | Required | The `data_end_time` of the first forecast in the evaluation window. | +| `size` | Integer | Optional | The number of buckets to return. Defaults is `5`. | +| `filter_by` | Enum | Required | Specifies whether to use a built-in or custom query. Must be either `BUILD_IN_QUERY` or `CUSTOM_QUERY`. | +| `build_in_query` | Enum | Optional | One of the following built-in ranking criteria is required:<br> `MIN_CONFIDENCE_INTERVAL_WIDTH` -- Sorts by the narrowest forecast confidence intervals (most precise).<br> `MAX_CONFIDENCE_INTERVAL_WIDTH` -- Sorts by the widest forecast confidence intervals (least precise).<br> `MIN_VALUE_WITHIN_THE_HORIZON` -- Sorts by the lowest forecast value observed within the prediction window.<br> `MAX_VALUE_WITHIN_THE_HORIZON` -- Sorts by the highest forecast value observed within the prediction window.<br> `DISTANCE_TO_THRESHOLD_VALUE` -- Sorts by the difference between the forecast value and a user-defined threshold. | +| `threshold`, `relation_to_threshold` | Mixed | Conditional | Required only if `build_in_query` is `DISTANCE_TO_THRESHOLD_VALUE`. | +| `filter_query` | Query DSL | Optional | A custom query used when `filter_by=CUSTOM_QUERY`. | +| `subaggregations` | Array | Optional | A list of nested aggregations and sort options used to compute additional metrics within each bucket. | + +### Example request: Built-in query for narrow confidence intervals + +The following request returns the top forecasted entities ranked by the narrowest confidence intervals: + +```json +POST _plugins/_forecast/forecasters/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", + "filter_by": "BUILD_IN_QUERY", + "build_in_query": "MIN_CONFIDENCE_INTERVAL_WIDTH", + "forecast_from": 1691008679297 +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "buckets": [ + { + "key": { "service": "service_6" }, + "doc_count": 1, + "bucket_index": 0, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 27.655361 + }, + ... + ] +} +``` + +### Example request: Built-in query with the narrowest confidence interval + +The following request returns a sorted list of entities whose forecast values have the narrowest confidence intervals. The results are ranked in ascending order based on the `MIN_CONFIDENCE_INTERVAL_WIDTH` metric: + +```json +POST _plugins/_forecast/forecasters/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", + "filter_by": "BUILD_IN_QUERY", + "build_in_query": "MIN_CONFIDENCE_INTERVAL_WIDTH", + "forecast_from": 1691008679297 +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "buckets": [ + { + "key": { + "service": "service_6" + }, + "doc_count": 1, + "bucket_index": 0, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 27.655361 + }, + { + "key": { + "service": "service_4" + }, + "doc_count": 1, + "bucket_index": 1, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 1324.7734 + }, + { + "key": { + "service": "service_0" + }, + "doc_count": 1, + "bucket_index": 2, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 2211.0781 + }, + { + "key": { + "service": "service_2" + }, + "doc_count": 1, + "bucket_index": 3, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 3372.0469 + }, + { + "key": { + "service": "service_3" + }, + "doc_count": 1, + "bucket_index": 4, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 3980.2812 + } + ] +} +``` + +### Example request: Built-in query with distance under a threshold + +The following request returns the top entities whose forecast values fall farthest from a specified threshold, based on the `DISTANCE_TO_THRESHOLD_VALUE` metric: + +```http +POST _plugins/_forecast/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", // group forecasts by the "service" entity field + "filter_by": "BUILD_IN_QUERY", // use a built-in ranking metric + "build_in_query": "DISTANCE_TO_THRESHOLD_VALUE", + "forecast_from": 1691008679297, // data_end_time of the first forecast in scope + "threshold": -82561.8, // user-supplied threshold + "relation_to_threshold": "LESS_THAN" // keep only forecasts below the threshold +} +``` + +#### Example response + +The `DISTANCE_TO_THRESHOLD_VALUE` metric calculates `forecast_value – threshold`. Because `relation_to_threshold` is `LESS_THAN`, the API returns negative distances only and sorts them in ascending order (most negative first). Each bucket includes the following values: + +- `doc_count`: The number of forecast points that matched. +- `DISTANCE_TO_THRESHOLD_VALUE`: The largest distance within the forecast horizon from the threshold value. + +The following response returns the `DISTANCE_TO_THRESHOLD_VALUE`: + +```json +{ + "buckets": [ + { + "key": { "service": "service_5" }, + "doc_count": 18, + "bucket_index": 0, + "DISTANCE_TO_THRESHOLD_VALUE": -330387.12 + }, + ... + { + "key": { "service": "service_0" }, + "doc_count": 1, + "bucket_index": 4, + "DISTANCE_TO_THRESHOLD_VALUE": -83561.8 + } + ] +} +``` + +### Example request: Custom query and nested aggregations + +The following request uses a custom query to match services by name and ranks them by the highest forecast value: + +```json +POST _plugins/_forecast/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", + "forecast_from": 1691018993776, + "filter_by": "CUSTOM_QUERY", + "filter_query": { + "nested": { + "path": "entity", + "query": { + "bool": { + "must": [ + { "term": { "entity.name": "service" } }, + { "wildcard": { "entity.value": "User*" } } + ] + } + } + } + }, + "subaggregations": [ + { + "aggregation_query": { + "forecast_value_max": { + "max": { "field": "forecast_value" } + } + }, + "order": "DESC" + } + ] +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "buckets": [ + { + "key": { "service": "UserAuthService" }, + "doc_count": 24, + "bucket_index": 0, + "forecast_value_max": 269190.38 + }, + ... + ] +} +``` +--- + +## Profile forecaster + +**Introduced 3.1** +{: .label .label-purple } + +Returns execution-time state such as initialization progress, per-entity model metadata, and errors. This API is useful for inspecting forecaster intervals during runtime. + +### Endpoints + +```http +GET _plugins/_forecast/forecasters/{forecaster_id}/_profile[/{type1},{type2}][?_all=true] +``` + +You can retrieve specific profile types or request all available types using the `_all` query parameter. + +The following profile types are supported: + +- `state` +- `error` +- `coordinating_node` +- `total_size_in_bytes` +- `init_progress` +- `models` +- `total_entities` +- `active_entities` +- `forecast_task` + +If you include an `entity` array in the request body, the profile is scoped to that entity only. + +### Example request: Default profile with an entity filter + +The following request returns the default profile types (`state` and `error`) for the specified entity: + +```http +GET _plugins/_forecast/forecasters/tLch1okBCBjX5EchixQ8/_profile +{ + "entity": [ + { + "name": "service", + "value": "app_1" + }, + { + "name": "host", + "value": "server_2" + } + ] +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "state": "RUNNING" +} +``` + +### Example request: Multiple profile types + +The following request retrieves `init_progress`, `error`, `total_entities`, and `state` profile types: + +```http +GET _plugins/_forecast/forecasters/mZ6P0okBTUNS6IWgvpwo/_profile/init_progress,error,total_entities,state +``` +{% include copy-curl.html %} + +### Example request: All profile types + +The following request returns all available profile types: + +```http +GET _plugins/_forecast/forecasters/d7-r1YkB_Z-sgDOKo3Z5/_profile?_all=true&pretty +``` +{% include copy-curl.html %} + + +--- + +## Forecaster stats +**Introduced 3.1** +{: .label .label-purple } + +Returns cluster-level or node-level statistics, including the number of forecasters, model counts, request counters, and the health of internal forecast indexes. + +### Endpoints + +```http +GET _plugins/_forecast/stats +GET _plugins/_forecast/{node_id}/stats +GET _plugins/_forecast/stats/{stat_name} +``` + +### Example request: Retrieve all statistics + +The following request retrieves cluster-level statistics for all forecasters, including counts, model information, and index status: + +```http +GET _plugins/_forecast/stats +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "hc_forecaster_count": 1, + "forecast_results_index_status": "yellow", + "forecast_models_checkpoint_index_status": "yellow", + "single_stream_forecaster_count": 1, + "forecastn_state_status": "yellow", + "forecaster_count": 2, + "job_index_status": "yellow", + "config_index_status": "yellow", + "nodes": { + "8B2S4ClnRFK3GTjO45bwrw": { + "models": [ + { + "model_type": "rcf_caster", + "last_used_time": 1692245336895, + "model_id": "Doj0AIoBEU5Xd2ccoe_9_entity_SO2kPi_PAMsvThWyE-zYHg", + "last_checkpoint_time": 1692233157256, + "entity": [ + { "name": "host_nest.host2", "value": "server_2" } + ] + } + ], + "forecast_hc_execute_request_count": 204, + "forecast_model_corruption_count": 0, + "forecast_execute_failure_count": 0, + "model_count": 4, + "forecast_execute_request_count": 409, + "forecast_hc_execute_failure_count": 0 + } + } +} +``` + +### Example request: Retrieve statistics for a specific node + +The following request retrieves forecaster statistics for a specific node, identified by node ID: + +```http +GET _plugins/_forecast/8B2S4ClnRFK3GTjO45bwrw/stats +``` +{% include copy-curl.html %} + +### Example request: Retrieve the total number of high-cardinality requests + +The following request retrieves the total number of high-cardinality forecaster requests across all nodes: + +```http +GET _plugins/_forecast/stats/forecast_hc_execute_request_count +``` +{% include copy-curl.html %} + +### Example request: Retrieve the high-cardinality request count for a specific node + +The following request retrieves the number of high-cardinality forecaster requests executed by a specific node: + +```http +GET _plugins/_forecast/0ZpL8WEYShy-qx7hLJQREQ/stats/forecast_hc_execute_request_count/ +``` +{% include copy-curl.html %} + + +--- + +## Forecaster info +**Introduced 3.1** +{: .label .label-purple } + +Returns a single integer representing the total number of forecaster configurations in the cluster or checks whether a forecaster that satisfies a given search criterion exists. + + +### Endpoints +```http +GET _plugins/_forecast/forecasters/count +GET _plugins/_forecast/forecasters/match?name={forecaster_name} +``` + +### Example request: Count forecasters + +The following request returns the number of forecaster configurations currently stored in the cluster: + +```http +GET _plugins/_forecast/forecasters/count +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "count": 2, + "match": false +} +``` + +### Example request: Match forecaster name + +The following request looks for a forecaster named `Second-Test-Forecaster-3`: + +```http +GET _plugins/_forecast/forecasters/match?name=Second-Test-Forecaster-3 +``` +{% include copy-curl.html %} + +### Example response: Match found + +```json +{ + "count": 0, + "match": true +} +``` + +### Example response: No match found + +```json +{ + "count": 0, + "match": false +} +``` diff --git a/_observing-your-data/forecast/forecaster-access-control.md b/_observing-your-data/forecast/forecaster-access-control.md new file mode 100644 index 00000000..888e2479 --- /dev/null +++ b/_observing-your-data/forecast/forecaster-access-control.md @@ -0,0 +1,141 @@ +--- +layout: default +title: Forecaster access control +parent: Forecasting +nav_order: 50 +has_children: false +--- + +# Forecaster access control + +The forecaster resource integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for forecaster resources. This replaces the legacy `plugins.forecast.filter_by_backend_roles` setting with a more flexible sharing system that allows resource owners to grant specific access levels to users, roles, or backend roles. + +For the predefined forecasting roles and permissions, see [Forecasting security]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/security/). + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +The following table describes the forecaster resource configuration. + +| Field | Value | +| :--- | :--- | +| Resource type | `forecaster` | +| System index | `.opensearch-forecasters` | +| Onboarded version | OpenSearch 3.3 | + +When resource-level authorization is enabled for forecasters, each forecaster's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +## Enable forecaster resource sharing + +To enable resource sharing for forecasters, you must add the forecaster resource type to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for forecasters: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "forecaster" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["forecaster"] + } +} +``` +{% include copy-curl.html %} + +When adding the forecaster resource type to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Forecaster access levels + +Forecasting provides three predefined access levels for forecaster documents. These access levels determine the specific permissions granted to users who have been granted access to a forecaster resource. + +### forecast_read_only + +The `forecast_read_only` read-only access level grants users the ability to view and search shared forecasters but not modify them. This access level includes the following permissions: + +```yaml +- 'cluster:admin/plugin/forecast/forecaster/info' +- 'cluster:admin/plugin/forecast/forecaster/stats' +- 'cluster:admin/plugin/forecast/forecaster/suggest' +- 'cluster:admin/plugin/forecast/forecaster/validate' +- 'cluster:admin/plugin/forecast/forecasters/get' +- 'cluster:admin/plugin/forecast/forecaster/info' +- 'cluster:admin/plugin/forecast/result/topForecasts' +``` +{% include copy.html %} + +### forecast_read_write + +The `forecast_read_write` read-write access level grants users full access to forecaster operations except for sharing capabilities. This access level includes all read permissions plus write operations: + +```yaml +- 'cluster:admin/plugin/forecast/*' +- 'cluster:monitor/*' +- 'cluster:admin/settings/update' +``` +{% include copy.html %} + +### forecast_full_access + +The `forecast_full_access` full access level grants users complete control over a forecaster, including owner-like permissions such as sharing the resource with other users. This access level includes all forecaster operations plus resource sharing permissions: + +```yaml +- 'cluster:admin/plugin/forecast/*' +- 'cluster:monitor/*' +- 'cluster:admin/settings/update' +- "cluster:admin/security/resource/share" +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Anomaly Detection GitHub repository](https://github.com/opensearch-project/anomaly-detection/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking forecasters as a protected resource type, cluster administrators must run the migration API to transfer existing forecaster sharing information from the legacy framework to the new resource sharing system. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Use the following API call to migrate legacy forecaster sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opensearch-forecasters", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "forecaster": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own forecasters without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available forecaster access levels: `forecast_read_only`, `forecast_read_write`, or `forecast_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance \ No newline at end of file diff --git a/_observing-your-data/forecast/getting-started.md b/_observing-your-data/forecast/getting-started.md new file mode 100644 index 00000000..b046f549 --- /dev/null +++ b/_observing-your-data/forecast/getting-started.md @@ -0,0 +1,353 @@ +--- +layout: default +title: Getting started with forecasting +nav_order: 5 +parent: Forecasting +has_children: false +--- + +# Getting started with forecasting + +You can define and configure forecasters in OpenSearch Dashboards by selecting **Forecasting** from the navigation panel. + +## Step 1: Define a forecaster + +A **forecaster** represents a single forecasting task. You can create multiple forecasters to run in parallel, each analyzing a different data source. Follow these steps to define a new forecaster: + +1. In the **Forecaster list** view, choose **Create forecaster**. + +2. Define the data source by entering the following information: + * **Name** – Provide a unique, descriptive name, such as `requests-10min`. + * **Description** – Summarize the forecaster's purpose, for example, `Forecast total request count every 10 minutes`. + * **Indexes** – Select one or more indexes, index patterns, or aliases. Remote indexes are supported through cross-cluster search (`cluster-name:index-pattern`). For more information, see [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/). If the Security plugin is enabled, see [Selecting remote indexes with fine-grained access control]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/security/#selecting-remote-indexes-with-fine-grained-access-control). + +3. (Optional) Choose **Add data filter** to set a **Field**, **Operator**, and **Value** or choose **Use query DSL** to define a [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/). The following example uses a query domain-specific language (DSL) filter to match three URL paths: + + ```json + { + "bool": { + "should": [ + { "term": { "urlPath.keyword": "/domain/{id}/short" } }, + { "term": { "urlPath.keyword": "/sub_dir/{id}/short" } }, + { "term": { "urlPath.keyword": "/abcd/123/{id}/xyz" } } + ] + } + } + ``` + + +4. Under **Timestamp field**, select the field that stores the timestamps. + +5. In the **Indicator (metric)** section, add a metric for the forecaster. Each forecaster supports one metric for optimal accuracy. Choose one of the following options: + + - Select a predefined aggregation: `average()`, `count()`, `sum()`, `min()`, or `max()`. + - To use a custom aggregation, choose **Custom expression** under **Forecast based on** and define your own [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/index/) expression. For example, the following query forecasts the number of unique accounts with a specific account type: + + ```json + { + "bbb_unique_accounts": { + "filter": { + "bool": { + "must": [ + { + "wildcard": { + "accountType": { + "wildcard": "*blah*", + "boost": 1 + } + } + } + ], + "adjust_pure_negative": true, + "boost": 1 + } + }, + "aggregations": { + "uniqueAccounts": { + "cardinality": { + "field": "account" + } + } + } + } + } + ``` + +6. (Optional) In the **Categorical fields** section, enable **Split time series using categorical fields** to generate forecasts at the entity level (for example, by IP address, product ID, or country code). + + The number of unique entities that can be cached in memory is limited. Use the following formula to estimate capacity: + + ``` + (data nodes × heap size × plugins.forecast.model_max_size_percent) + ────────────────────────────────────────────────────────────────── + entity-model size (MB) + ``` + + For example, a cluster with 3 data nodes, each with 8 GB JVM heap and the default 10% model memory, would contain the following number of entities: + + ``` + (8096 MB × 0.10 ÷ 1 MB) × 3 nodes ≈ 2429 entities + ``` + + To determine the entity-model size, use the [Profile Forecaster API]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/api/#profile-forecaster). You can raise or lower the memory ceiling with the `plugins.forecast.model_max_size_percent` setting. + + +Forecasters cache models for the most frequently and recently observed entities, subject to available memory. Models for less common entities are loaded from indexes on a best-effort basis during each interval, with no guaranteed service-level agreement (SLA). Always validate memory usage against a representative workload. + +For more information, see the blog post [Improving Anomaly Detection: One Million Entities in One Minute](https://opensearch.org/blog/one-million-enitities-in-one-minute/). Although focused on anomaly detection, the recommendations apply to forecasting, as both features share the same underlying Random Cut Forest (RCF) model. + +## Step 2: Add model parameters + +The **Suggest parameters** button in OpenSearch Dashboards initiates a review of recent history to recommend sensible defaults. You can override these defaults by adjusting the following parameters: + +* **Forecasting interval** – Specifies the aggregation bucket (for example, 10 minutes). Longer intervals smooth out noise and reduce compute costs, but they delay detection. Shorter intervals detect changes sooner but increase resource usage and can introduce noise. Choose the shortest interval that still produces a stable signal. +* **Window delay** – Tells the forecaster how much of a delay to expect between event occurrence and ingestion. This delay adjusts the forecasting interval backward to ensure complete data coverage. For example, if the forecasting interval is 10 minutes and ingestion is delayed by 1 minute, setting the window delay to 1 minute ensures that the forecaster evaluates data from 1:49 to 1:59 rather than 1:50 to 2:00. + * To avoid missing data, set the window delay to the upper limit of the expected ingestion delay. However, longer delays reduce the real-time responsiveness of forecasts. +* **Horizon** – Specifies how many future buckets to predict. Forecast accuracy declines with distance, so choose only the forecast window that is operationally meaningful. +* **History** – Sets the number of historical data points used to train the initial (cold-start) model. The maximum is 10,000. More history improves initial model accuracy up to that limit. + +The **Advanced** panel is collapsed by default, allowing most users to proceed with the suggested parameters. If you expand the panel, you can fine-tune three additional parameters: [shingle size](#choosing-a-shingle-size), [suggested seasonality](#choosing-a-shingle-size), and [recency emphasis](#choosing-a-shingle-size). These control how the forecaster balances recent fluctuations against long-term patterns. + +Unless your data or use case demands otherwise, the defaults—**shingle size 8**, **no explicit seasonality**, and **recency emphasis 2560**—are reliable starting points. + +### Choosing a shingle size + +Leave the **Shingle size** field empty to use the automatic heuristic: + +1. Start with the default value of 8. +2. If **Suggested seasonality** is defined and greater than 16, replace it with half the season length. +3. If **Horizon** is defined and one-third of the value is greater than the current candidate, update it accordingly. + +The final value is the maximum of these three: +`max(8, seasonality ÷ 2, horizon ÷ 3)` + +If you provide a custom value, it overrides this calculation. + +### Determining storage amounts + +By default, forecast results are stored in the `opensearch-forecast-results` index alias. You can: + +* Build dashboards and visualizations. +* Use the results in [alerting monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/). +* Query the results as with any other OpenSearch index. + +To manage storage, OpenSearch applies a rollover policy: + +* **Rollover trigger** – When a primary shard reaches approximately 65 GB, a new backing index is created and the alias is updated. +* **Retention** – Rolled-over indexes are retained for at least 30 days before deletion. + +You can customize this behavior using the following settings. + +| Setting | Description | Default | +|---------|-------------|---------| +| `plugins.forecast.forecast_result_history_max_docs_per_shard` | The maximum number of Lucene documents allowed per shard before triggering a rollover. One result is approximately 4 documents at around 47 bytes each, totaling about 65 GB. | `1_350_000_000` | +| `plugins.forecast.forecast_result_history_retention_period` | The duration for which to retain forecast results. Supports duration formats such as `7d`, `90d`. | `30d` | + +### Specifying a custom result index + +You can store forecast results in a custom index by selecting **Custom index** and providing an alias name, such as `abc`. OpenSearch creates an alias like `opensearch-forecast-result-abc` that points to the backing index (for example, `opensearch-forecast-result-abc-history-2024.06.12-000002`). + +To manage permissions, use hyphenated namespaces. For example, assign `opensearch-forecast-result-financial-us-*` to roles for the `financial` department's `us` group. +{: .note } If the Security plugin is enabled, ensure appropriate [permissions are configured]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/security/#custom-result-index-permissions). + +### Flattening nested fields + +If your custom result index's documents include nested fields, enable the **Flattened custom result index** to simplify aggregation and visualization. + +This creates a separate index prefixed with the custom index and forecaster name (for example, `opensearch-forecast-result-abc-flattened-test`) and attaches an ingest pipeline using a [Painless script](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/scripts/flatten-custom-result-index-painless.txt) to flatten nested data. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +If you later disable this option, the associated ingest pipeline is removed. + +Use [Index State Management]({{site.url}}{{site.baseurl}}/im-plugin/ism/index/) to manage rollover and deletion of flattened result indexes. + +### Custom result index lifecycle management + +OpenSearch rolls over custom result indexes when any of the following conditions are met. + +| Parameter | Description | Type | Unit | Default | Required | +|----------|-------------|------|------|---------|----------| +| `result_index_min_size` | The minimum total primary shard size required to trigger a rollover. | Integer | MB | `51200` (50 GB) | No | +| `result_index_min_age` | The minimum index age required to trigger a rollover. | Integer | Days | `7` | No | +| `result_index_ttl` | The minimum amount of time before rolled-over indexes are deleted | Integer | Days | `60` | No | + + +## Step 3: Test your forecaster + +Backtesting is the fastest way to evaluate and refine key forecasting settings such as **Interval** and **Horizon**. During backtesting, the model is trained on historical data, generates forecasts, and plots them alongside actual values to help visualize prediction accuracy. If the results do not meet expectations, you can adjust the settings and run the test again. + +Backtesting uses the following methods: + +1. **Training window**: The model trains on historical data defined by the **History** setting. + +2. **Rolling forecast**: The model progresses through the time series, repeatedly performing the following actions: + * Ingesting the next actual data point + * Emitting forecasts at each step + + Because this is a retrospective simulation, forecasted values are plotted at their original timestamps, allowing you to see how well the model would have performed in real time. + + +### Starting a backtest + +To begin a test: + +1. Scroll to the bottom of the **Add model parameters** page. +2. Select **Create and test**. + +To skip testing and create the forecaster immediately, select **Create**. + +Backtests usually take 1 or 2 minutes, but run time depends on the following factors. + +| Factor | Why it matters | +| --------------------- | ------------------------------------------------------------------------ | +| **History length** | More historical data increases training time. | +| **Data density** | Densely packed data slows aggregation. | +| **Categorical field** | The model trains separately for each entity. | +| **Horizon** | A longer forecast horizon increases the number of generated predictions. | + + +If the chart is empty, as shown in the following image, check that your index contains at least one time series with more than 40 data points at the selected interval. + +![test failed]({{site.url}}{{site.baseurl}}/images/forecast/no_result.png){: width="800" height="800" } + + +### Reading the chart + +When the test succeeds, hover over any point on the chart to view exact values and confidence bounds: + +- **Actual data** – Solid line +- **Median prediction (P50)** – Dotted line +- **Confidence interval** – Shaded band between P10 and P90 + +The following image shows the chart view. + +![Forecast chart with confidence bounds]({{site.url}}{{site.baseurl}}/images/forecast/bound.png){: width="800" height="800" } + +### Viewing forecasts from a specific date + +The forecast chart displays predictions starting from the final actual data point through the end of the configured horizon. + +For example, you might configure the following settings in the **Forecast from** field: + +- **Last actual timestamp**: Mar 5, 2025, 19:23 +- **Interval**: 1 minute +- **Horizon**: 24 + +With these settings, the forecast range would span `Mar 5, 2025, 19:23 – 19:47`, as shown in the following image. + +![Forecast chart with trend]({{site.url}}{{site.baseurl}}/images/forecast/trend.png){: width="800" height="800" } + +You can also use the **Forecast from** dropdown list to view forecasts from earlier test runs, as shown in the following image. + +![Forecast from dropdown]({{site.url}}{{site.baseurl}}/images/forecast/forecast_from_1.png){: width="800" height="800" } + +When you select an earlier **Forecast from** time, the forecast line is drawn directly over the historical data available at that moment. This causes the two series to overlap, as shown in the following image. + +![Overlapping forecast and actual data]({{site.url}}{{site.baseurl}}/images/forecast/forecast_from_2.png){: width="800" height="800" } + +To return to the most recent forecast window, select **Show latest**. + +### Overlay mode: Side-by-side accuracy check + +By default the chart displays forecasts that start from a single origin point. Toggle Overlay mode to lay a forecast curve directly on top of the actual series and inspect accuracy across the entire timeline. + +Because the model emits one forecast per horizon step, for example, 24 forecasts when the horizon is 24, a single timestamp can have many forecasts that were generated from different origins. Overlay mode lets you decide which lead time (k) to plot: + +* Horizon index 0 = Immediate next step +* Horizon index 1 = 1 step ahead +* Horizon index 23 = 23 steps ahead + +The horizon control defaults to **index 3**, but you can choose any value to focus on a different lead time. + +The following image shows Overlay mode enabled with a horizon index of 3. The visualization plots the forecast curve (in purple) directly on top of the actual data points (shown with white-filled markers). This lets you evaluate the accuracy of the model's three-steps-ahead prediction across the full timeline. The forecast range is displayed as a shaded band around the predicted values, helping highlight uncertainty. + +![overlay config]({{site.url}}{{site.baseurl}}/images/forecast/overlay_3.png){: width="800" height="800" } + +### View multiple forecast series + +A high-cardinality forecaster can display many time series at once. Use the **Time series per page** dropdown menu in the results panel to switch between the following views: + +- **Single-series view** (default): Renders one entity per page for maximum readability. +- **Multi-series view**: Plots up to five entities side by side. Confidence bands are translucent by default—hover over a line to highlight its associated band. + +Actual and forecast lines are overlaid so you can assess accuracy point by point. However, in **Multi-series view**, the overlapping lines can make the chart more difficult to interpret. To reduce visual clutter, go to **Visualization options** and turn off **Show actual data at forecast**. + +The following image shows the chart with actual and forecast lines overlaid. + +![Chart with actual and forecast lines overlaid]({{site.url}}{{site.baseurl}}/images/forecast/toggle_overlay_before.png){: width="800" height="800" } + +The following image shows the same chart with actual lines hidden at forecast time to simplify the view. + +![Chart with forecast lines only]({{site.url}}{{site.baseurl}}/images/forecast/toggle_overlay_after.png){: width="800" height="800" } + + +### Exploring the timeline + +Use the following timeline controls to navigate, magnify, and filter any span of your forecast history: + +* **Zoom** – Select **+ / –** to zoom in on forecasts or broaden context. +* **Pan** – Use the arrow buttons to move to earlier or later data points, if any. +* **Quick Select** – Choose common ranges, such as "Last 24 hours", or supply custom dates for the result range. + +### Sorting options in multi-series view + +When a forecaster tracks more than five entities, the chart can't show every line at once. +In **Multi-series view**, you therefore choose the five most informative series and decide what "informative" means by selecting a sort method. The following table lists the available sort methods. + +| Sort method | What it shows | When to use it | +|-------------|--------------|----------------| +| **Minimum confidence-interval width** *(default)* | The five series whose prediction bands are narrowest. A narrow band indicates that the model is highly certain about its forecast. | Surface the most "trustworthy" forecasts. | +| **Maximum confidence-interval width** | The five series with the widest bands—forecasts the model is least sure about. | Spot risky or noisy series that may need review or more training data. | +| **Minimum value within the horizon** | The lowest predicted point across the forecast window for each entity, sorted in ascending order. | Identify entities expected to drop the farthest—useful for capacity planning or alerting on potential dips. | +| **Maximum value within the horizon** | The highest predicted point across the horizon for each entity, sorted in descending order. | Highlight series with the greatest expected peaks, such as traffic spikes or sales surges. | +| **Distance to threshold value** | Filters forecasts by a numeric threshold (>, <, ≥, ≤) and then orders the remainder by how far they sit from that threshold. | Investigate entities that breach—or nearly breach—an SLA or business KPI, such as "show anything forecast to exceed 10,000 requests". | + +If the forecaster monitors five or fewer entities, **Multi-series view** displays all of them. When there are more than five, the view reranks them dynamically each time you change the sort method or adjust the threshold, ensuring that the most relevant series stay in focus. + +To focus on a specific subset of entities, switch **Filter by** to **Custom query** and enter a query DSL query. The following example shows entities where the `host` equals `server_1`: + +```json +{ + "nested": { + "path": "entity", + "query": { + "bool": { + "must": [ + { "term": { "entity.name": "host" } }, + { "wildcard": { "entity.value": "server_1" } } + ] + } + } + } +} +``` + +Next, select a sort method, such as **Maximum value within the horizon**, and select **Update visualization**. The chart updates to show only the forecast series for `host:server_1`, ranked according to your selected criteria. + +### Edit a forecaster + +If the initial backtest shows weak performance, you can adjust the forecaster's configuration and run the test again. + +To edit a forecaster: + +1. Open the forecaster's **Details** page and select **Edit** to enter edit mode. +2. Modify the settings as needed—for example, add a **Category field**, change the **Interval**, or increase the **History** window. +3. Select **Update**. The validation panel automatically evaluates the new configuration and flags any issues. + + The following image shows the validation process in progress. + + ![Validation panel loading]({{site.url}}{{site.baseurl}}/images/forecast/validation_loading.png){: width="800" height="800" } + +4. Resolve any validation errors. When the panel becomes green, select **Start test** in the upper-right corner to run another backtest with the updated parameters. + +### Real-time forecasting + +Once you are confident in the forecasting configuration, go to the **Details** page and click **Start forecasting** to begin real-time forecasting. The forecaster will generate new predictions at each interval moving forward. + +A **Live** badge appears when the chart is synchronized with the most recent data. + +Unlike backtesting, real-time forecasting continuously attempts to initialize using live data if there is not enough historical data. During this initialization period, the forecaster displays an initialization status until it has enough data to begin emitting forecasts. + +## Next steps + +Once you have tested and refined your forecaster, you can begin using it to generate live forecasts or manage it over time. To learn how to start, stop, delete, or update an existing forecaster, see [Managing forecasters]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/managing-forecasters/). + diff --git a/_observing-your-data/forecast/index.md b/_observing-your-data/forecast/index.md new file mode 100644 index 00000000..3f82871b --- /dev/null +++ b/_observing-your-data/forecast/index.md @@ -0,0 +1,31 @@ +--- +layout: default +title: Forecasting +nav_order: 130 +has_children: true +redirect_from: + - /observing-your-data/forecast/ +--- + +# Forecasting + +Forecasting in OpenSearch transforms any time-series field into a self-updating signal using the Random Cut Forest (RCF) model. RCF is an online learning model that updates incrementally with each new data point. Because RCF refreshes in real time, it adapts instantly to changes in technical conditions without requiring costly batch retraining. Each model uses only a small amount of storage—typically a few hundred kilobytes—so both compute and storage overhead remain low. + +Pair forecasting with [Alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/index/) to receive a notification the moment a forecasted value is predicted to breach your threshold. +{: .note} + +## Typical use case + +Forecasting can be used for the following use cases. + +| Domain | What you forecast | Operational benefit | +|--------|-------------------|---------------| +| Predictive maintenance | Future temperature, vibration, or error counts per machine | Replace parts before failure to avoid unplanned downtime. | +| Network forecasting | Future throughput, latency, or connection counts per node | Allocate bandwidth early to meet service-level agreement (SLA) targets. | +| Capacity and cost optimization | Future CPU, RAM, or disk usage per microservice | Rightsize hardware and scale automatically. | +| Financial and operational planning | Future order volume, revenue, or ad spend efficiency | Align staffing and budgets with demand signals. | + + + + + diff --git a/_observing-your-data/forecast/managing-forecasters.md b/_observing-your-data/forecast/managing-forecasters.md new file mode 100644 index 00000000..f8c3519a --- /dev/null +++ b/_observing-your-data/forecast/managing-forecasters.md @@ -0,0 +1,226 @@ +--- +layout: default +title: Managing forecasters +nav_order: 8 +parent: Forecasting +has_children: false +--- + +# Managing forecasters + +After you [create a forecaster]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/getting-started/), you can manage its lifecycle and configuration using the **Details** page. This includes starting or stopping the forecaster, updating its settings, or deleting it entirely. Use this page to monitor forecaster status, troubleshoot issues, and fine-tune behavior over time. + +## Forecasters table + +The **Forecasters** table provides an overview of every forecaster you have configured. + +| Column | Description | +|--------|-------------| +| **Name** | The name you assigned when creating the forecaster. | +| **Status** | The current lifecycle state—for example, `Running`, `Initializing`, or `Test complete`. Click the <i class="euiIcon euiIcon--xs euiIcon--expand"></i> icon for more information, including the timestamp of the most recent status change and any failure messages. | +| **Index** | The source index or alias from which the forecaster reads. | +| **Last updated** | The timestamp of the most recent configuration change. | +| **Quick actions** | Context-aware buttons such as **Start**, **Stop**, or **Delete**, depending on the forecaster's current state. | + +## Execution states + +A forecaster (that is, the underlying forecasting job) can be in any of the following states. Transitions marked *automatic* happen without user action; others require you to manually select **Start** or **Stop**. + +| State | Description | Typical trigger | +|-------|-------------|------------------| +| **Inactive** | The forecaster was created but never started. | None. | +| **Inactive: stopped** | The forecaster was manually stopped after running. | User selects **Stop forecasting**. | +| **Awaiting data to initialize forecast** | The job is trying to start but lacks enough historical data. | Automatic. | +| **Awaiting data to restart forecast** | The job is resuming after a data gap and is waiting for new data. | Automatic after a data outage. | +| **Initializing test** | The model is being built for a one-time backtest. | Automatic on **Create and test** or **Start test**. | +| **Test complete** | The backtest has finished and the job is no longer running. | Automatic. | +| **Initializing forecast** | The model is being trained for continuous real-time forecasting. | Automatic after selecting **Start forecasting**. | +| **Running** | The job is streaming live data and generating forecasts. | Automatic when initialization completes successfully. | +| **Initializing test failed** | The test failed, often due to insufficient data. | Automatic. | +| **Initializing forecast failed** | Real-time mode failed to initialize. | Automatic. | +| **Forecast failed** | The job started but encountered a runtime error, such as a shard failure. | Automatic but requires the user's attention. | + +The following diagram illustrates the relationships and transitions between states. + +![Forecast state diagram]({{site.url}}{{site.baseurl}}/images/forecast/state.png){: width="1600" height="1600" } + +## Find and filter forecasters + +If you have many forecasters, use the pagination controls at the bottom of the table to navigate between pages. You can also use the search bar to filter by **name**, **status**, or **index**, which can be helpful when managing large sets of forecasters. + +## Alert on forecasted values + +Because forecast result indexes are not system indexes, you can create an [Alerting monitor]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/) for the result indexes like you would for any other user index. + +### Example alert monitor + +For example, the following is a monitor for a high-cardinality forecaster. You can modify the schedule, query, and aggregation to match your use case: + +{% raw %} +```json +{ + "name": "test", + "type": "monitor", + "monitor_type": "query_level_monitor", + "enabled": true, + "schedule": { + "period": { + "unit": "MINUTES", + "interval": 1 + } + }, + "inputs": [ + { + "search": { + "indices": [ + "opensearch-forecast-results*" + ], + "query": { + "size": 1, + "query": { + "bool": { + "filter": [ + { + "range": { + "execution_end_time": { + "from": "{{period_end}}||-15m", + "to": "{{period_end}}", + "include_lower": true, + "include_upper": true, + "format": "epoch_millis", + "boost": 1 + } + } + } + ], + "adjust_pure_negative": true, + "boost": 1 + } + }, + "aggregations": { + "metric": { + "max": { + "field": "forecast_upper_bound" + } + } + } + } + } + } + ], + "triggers": [ + { + "query_level_trigger": { + "id": "29oAl5cB5QuI4WJQ3hnx", + "name": "breach", + "severity": "1", + "condition": { + "script": { + "source": "return ctx.results[0].aggregations.metric.value == null ? false : ctx.results[0].aggregations.metric.value > 10000", + "lang": "painless" + } + }, + "actions": [ + { + "id": "notification378084", + "name": "email", + "destination_id": "2uzIlpcBMf-0-aT5HOtn", + "message_template": { + "source": "Monitor **{{ctx.monitor.name}}** entered **ALERT** state — please investigate.\n\nTrigger : {{ctx.trigger.name}}\nSeverity : {{ctx.trigger.severity}}\nTime range : {{ctx.periodStart}} → {{ctx.periodEnd}} UTC\n\nEntity\n{{#ctx.results.0.hits.hits.0._source.entity}}\n • {{name}} = {{value}}\n{{/ctx.results.0.hits.hits.0._source.entity}}\n", + "lang": "mustache" + }, + "throttle_enabled": true, + "subject_template": { + "source": "Alerting Notification action", + "lang": "mustache" + }, + "throttle": { + "value": 15, + "unit": "MINUTES" + } + } + ] + } + } + ], + "ui_metadata": { + "schedule": { + "timezone": null, + "frequency": "interval", + "period": { + "unit": "MINUTES", + "interval": 1 + }, + "daily": 0, + "weekly": { + "tue": false, + "wed": false, + "thur": false, + "sat": false, + "fri": false, + "mon": false, + "sun": false + }, + "monthly": { + "type": "day", + "day": 1 + }, + "cronExpression": "0 */1 * * *" + }, + "monitor_type": "query_level_monitor", + "search": { + "searchType": "query", + "timeField": "execution_end_time", + "aggregations": [ + { + "aggregationType": "max", + "fieldName": "forecast_upper_bound" + } + ], + "groupBy": [], + "bucketValue": 15, + "bucketUnitOfTime": "m", + "filters": [] + } + } +} +``` +{% endraw %} +{% include copy-curl.html %} + +### Monitor design + +The following table explains each design choice used in the example alert monitor and why it matters. + +| Design choice | Rationale | +|---------------|-----------| +| `size: 1` in the search input | Retrieves a single document so you can reference `ctx.results.0.hits.hits.0` in the notification to identify which entity (such as `host` or `service`) triggered the alert. | +| `execution_end_time` range `"now-15m"` → `now` | Filters on the result creation timestamp, which reflects when the forecast was generated. This avoids delays caused by ingestion lag. Avoid filtering on `data_end_time` if your index includes late-arriving data (such as backfilled logs). | +| `max(forecast_upper_bound)` as the metric | Detects upper-bound spikes. Alternatives include: <br> `min(forecast_lower_bound)` for sudden drops. <br> `avg(forecast_value)` for trend shifts. <br> For additional fields, see the [forecast result schema](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/mappings/forecast-results.json). | +| Index pattern `opensearch-forecast-results*` | Matches the default result index pattern. Update this pattern if you route results to a custom index, such as `opensearch-forecast-result-abc*`. | +| Optional term filter on `forecaster_id` | Use this filter to target a specific forecaster and avoid matching unrelated forecasts. | +| Monitor every 1 min, query window 15 min | Evaluates forecasts every minute to detect anomalies quickly. The 15-minute look-back window increases resilience to timing delays. Combined with a 15-minute alert throttle, this avoids duplicate notifications for the same event. | +| Mustache block prints all entity dimensions | Displays both single-dimension (`host=server_3`) and multi-dimension (`host=server_3`, `service=auth`) entity values. You can also include a link to a pre-filtered dashboard for faster triage. | +| Threshold | Use the OpenSearch Dashboards visual editor to analyze recent forecast values and determine an appropriate threshold that reliably indicates anomalies. | + + +### Example alert + +The following example shows a sample alert email generated by a monitor that detects when a forecasted value breaches a defined threshold. In this case, the monitor is tracking a high-cardinality forecaster and has triggered an alert for a specific entity (`host = server_3`): + +``` +Monitor **test** entered **ALERT** state — please investigate. + +Trigger : breach +Severity : 1 +Time range : 2025-06-22T09:56:14.490Z → 2025-06-22T09:57:14.490Z UTC + +Entity + • host = server_3 +``` + +## Next steps + +After setting up and managing your forecasters, you may want to control who can access and modify them. To learn how to manage permissions, secure result indexes, and apply fine-grained access controls, see [the security page]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/security/). + + diff --git a/_observing-your-data/forecast/security.md b/_observing-your-data/forecast/security.md new file mode 100644 index 00000000..f22042e7 --- /dev/null +++ b/_observing-your-data/forecast/security.md @@ -0,0 +1,470 @@ +--- +layout: default +title: Forecasting security +nav_order: 10 +parent: Forecasting +has_children: false +--- + +# Forecasting security + +Forecasting uses the same security framework as anomaly detection. This page explains how to configure permissions for users to create, run, and view forecasters; how to restrict access to system indexes; and how to isolate forecast results across teams. + +To control access to individual forecasters using resource sharing, see [Forecaster access control]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/forecaster-access-control/). + +In all examples, replace credentials, index names, and role names with values appropriate for your environment. +{: .note} + +## Indexes created by forecasting + +The following table describes the indexes used by the Forecasting API and their visibility to regular users. + +| Index pattern | Purpose | Visible to regular users? | +|---------------|---------|---------------------------| +| `.opensearch-forecasters` | Stores forecaster configuration. | No | +| `.opensearch-forecast-checkpoints` | Stores model snapshots (checkpoints). | No | +| `.opensearch-forecast-state` | Stores task metadata for real-time and run-once forecasting. | No | +| `opensearch-forecast-result*` | Stores forecast results from both backtests and real-time forecasting. | Yes | + +Users do not need direct access to `.opensearch-forecast-checkpoints`; it is used internally by forecasting. + +To view `.opensearch-forecasters`, use the [Get forecaster]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/api/#get-forecaster) or [Search forecasters]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/api/#search-forecasters) APIs. + +To view `.opensearch-forecast-state`, use the [Get forecaster]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/api/#get-forecaster) API with the `?task=true` query parameter or call the [Search tasks]({{site.url}}{{site.baseurl}}/observing-your-data/forecast/api/#search-tasks) API directly. + + +## Cluster permissions + +Each Forecasting API route maps to a specific cluster-level permission, as shown in the following table. You must grant these permissions to roles that manage or interact with forecasters. + +| Route | Required permission | +|:------------|:---------------------| +| `POST /_plugins/_forecast/forecasters` | `cluster:admin/plugin/forecast/forecaster/write` | +| `PUT /_plugins/_forecast/forecasters/{id}` | `cluster:admin/plugin/forecast/forecaster/write` | +| `POST /_plugins/_forecast/forecasters/_validate` | `cluster:admin/plugin/forecast/forecaster/validate` | +| `POST /_plugins/_forecast/forecasters/_suggest/{types}` | `cluster:admin/plugin/forecast/forecaster/suggest` | +| `GET /_plugins/_forecast/forecasters/{id}` <br>`GET /_plugins/_forecast/forecasters/{id}?task=true` | `cluster:admin/plugin/forecast/forecasters/get` | +| `DELETE /_plugins/_forecast/forecasters/{id}` | `cluster:admin/plugin/forecast/forecaster/delete` | +| `POST /_plugins/_forecast/forecasters/{id}/_start` <br>`POST /_plugins/_forecast/forecasters/{id}/_stop` | `cluster:admin/plugin/forecast/forecaster/jobmanagement` | +| `POST /_plugins/_forecast/forecasters/{id}/_run_once` | `cluster:admin/plugin/forecast/forecaster/runOnce` | +| `POST /_plugins/_forecast/forecasters/_search` <br>`GET /_plugins/_forecast/forecasters/_search` | `cluster:admin/plugin/forecast/forecasters/search` | +| `GET /_plugins/_forecast/forecasters/tasks/_search` | `cluster:admin/plugin/forecast/tasks/search` | +| `POST /_plugins/_forecast/forecasters/{id}/results/_topForecasts` | `cluster:admin/plugin/forecast/result/topForecasts` | +| `GET /_plugins/_forecast/forecasters/{id}/_profile` | `cluster:admin/plugin/forecast/forecasters/profile` | +| `GET /_plugins/_forecast/stats` | `cluster:admin/plugin/forecast/forecaster/stats` | +| `GET /_plugins/_forecast/forecasters/count` <br>`GET /_plugins/_forecast/forecasters/match` | `cluster:admin/plugin/forecast/forecaster/info` | + +## Required roles + +A forecasting user needs three types of privileges, based on the following responsibilities: + +- Managing the forecasting job +- Reading the source data +- Accessing the forecast results + +These responsibilities correspond to three distinct security layers, as shown in the following table. + +| Layer | What it controls | Typical role | +|-------|------------------|--------------| +| **Forecaster control** | Permissions to create, edit, start, stop, delete, or view a forecaster's configuration. | `forecast_full_access` <br>(manage lifecycle)<br>or<br>`forecast_read_access` <br>(view only) | +| **Data-source read** | Grants the forecaster permission to query the raw metrics index it uses for training and prediction. | Custom role, such as `data_source_read` | +| **Result read** | Grants users and Alerting monitors access to documents in `opensearch-forecast-result*`. | Custom role, such as `forecast_result_read` | + + +The built-in roles `forecast_full_access` and `forecast_read_access` apply only to Forecasting APIs. They do **not** include permissions for source or result indexes—those must be granted separately. +{: .note} + + +### Forecaster control roles + +The Forecasting API includes two built-in roles that you can use as is or use as templates for creating custom roles: + +- `forecast_read_access` – For analysts who need read-only access to forecasters. This role allows users to view forecaster details and results but not create, modify, start, stop, or delete forecasters. + + +- `forecast_full_access` – For users responsible for managing the full lifecycle of forecasters, including creating, editing, starting, stopping, and deleting them. This role does **not** grant access to the source index. To create a forecaster, users must also have index-level permissions that include the `search` action on any index or alias the forecaster reads from. + +The following example shows how these roles are defined: + +```yaml +forecast_read_access: + reserved: true + cluster_permissions: + - 'cluster:admin/plugin/forecast/forecaster/info' + - 'cluster:admin/plugin/forecast/forecaster/stats' + - 'cluster:admin/plugin/forecast/forecaster/suggest' + - 'cluster:admin/plugin/forecast/forecaster/validate' + - 'cluster:admin/plugin/forecast/forecasters/get' + - 'cluster:admin/plugin/forecast/forecaster/info' + - 'cluster:admin/plugin/forecast/forecasters/search' + - 'cluster:admin/plugin/forecast/result/topForecasts' + - 'cluster:admin/plugin/forecast/tasks/search' + index_permissions: + - index_patterns: + - 'opensearch-forecast-result*' + allowed_actions: + - 'indices:admin/mappings/fields/get*' + - 'indices:admin/resolve/index' + - 'indices:data/read*' + +forecast_full_access: + reserved: true + cluster_permissions: + - 'cluster:admin/plugin/forecast/*' + - 'cluster:admin/settings/update' + - 'cluster_monitor' + index_permissions: + - index_patterns: + - '*' + allowed_actions: + - 'indices:admin/aliases/get' + - 'indices:admin/mapping/get' + - 'indices:admin/mapping/put' + - 'indices:admin/mappings/fields/get*' + - 'indices:admin/mappings/get' + - 'indices:admin/resolve/index' + - 'indices:data/read*' + - 'indices:data/read/field_caps*' + - 'indices:data/read/search' + - 'indices:data/write*' + - 'indices_monitor' +``` +{% include copy.html %} + +These roles do not include default `index_permissions` for specific source or result indexes. This is intentional, allowing you to add your own patterns based on your data access requirements. + +### Data source `read` role + +Each forecaster uses the creating user's credentials to query the source index. To enable this, you must grant that user read permissions for your own data index. + +The following example request creates a minimal role that allows read access to the `network-metrics` index: + +```json +PUT _plugins/_security/api/roles/data_source_read +{ + "index_permissions": [{ + "index_patterns": ["network-metrics"], + "allowed_actions": ["read"] + }] +} +``` +{% include copy-curl.html %} + +You can modify the `index_patterns` to match your actual data source. + +### Result-read role + +The `forecast_result_read` role allows users to view forecast results and configure Alerting monitors that query those results. + +The following example request defines a role that grants read access to all indexes matching the `opensearch-forecast-result*` pattern: + +```json +PUT _plugins/_security/api/roles/forecast_result_read +{ + "index_permissions": [{ + "index_patterns": ["opensearch-forecast-result*"], + "allowed_actions": ["read"] + }] +} +``` +{% include copy-curl.html %} + +If you need to isolate result data between teams, you can enhance this role using document-level security (DLS) with a backend role filter, as shown in the following section. + +### Example security role configuration + +The following example request creates a `devOpsEngineer` user and assigns all three required roles for forecasting: + +```json +PUT _plugins/_security/api/internalusers/devOpsEngineer +{ + "password": "DevOps2024!", + "opendistro_security_roles": [ + "forecast_full_access", + "data_source_read", + "forecast_result_read" + ] +} +``` +{% include copy-curl.html %} + +This configuration enables the following: + +- `devOpsEngineer` can manage forecasters (`forecast_full_access`). +- Forecasters can query the source index successfully (`data_source_read`). +- The user and any configured monitors can read forecast results (`forecast_result_read`). + +To grant read-only access to forecaster configurations, replace `forecast_full_access` with `forecast_read_access`. + +--- + +## (Advanced) Limit access by backend role + +You can use backend roles to enforce **team-specific isolation**. This pattern allows different teams to operate forecasters independently while separating configurations and results. + +The model includes three layers: + +1. **Configuration isolation** – Forecasting APIs are restricted to users with a matching backend role. +2. **Result isolation** – DLS limits access to forecast results in `opensearch-forecast-result*`. +3. **Source data access** – A minimal read-only role enables each forecaster to scan its own index. + +The following sections explain how to configure each layer. + +### Assign backend roles to users + +In most environments, backend roles are assigned through LDAP or SAML. However, if you are using the internal user database, you can set them manually, as shown in the following example: + +```json +# Analyst +PUT _plugins/_security/api/internalusers/alice +{ + "password": "alice", + "backend_roles": ["analyst"] +} + +# HR staff +PUT _plugins/_security/api/internalusers/bob +{ + "password": "bob", + "backend_roles": ["human-resources"] +} +``` + +These backend roles can then be used to control access to forecasters and forecast results on a per-team basis. + +### Enable backend-role filtering for configuration access + +To isolate forecaster configurations by team, enable backend-role filtering at the cluster level: + + +```bash +PUT _cluster/settings +{ + "persistent": { + "plugins.forecast.filter_by_backend_roles": true + } +} +``` +{% include copy-curl.html %} + +When this setting is enabled, OpenSearch records the creator's backend roles in each forecaster document. Only users with a matching backend role can view, edit, or delete that forecaster. + +### Create a `result‑access` role per team + +Forecast results are stored in shared indexes, so use DLS to restrict access by backend role. + +The following example request creates a role that allows users with the `analyst` backend role to read and to write only their team's forecast results: + + +```json +PUT _plugins/_security/api/roles/forecast_analyst_result_access +{ + "index_permissions": [{ + "index_patterns": ["opensearch-forecast-result*"], + "dls": """ + { + "bool": { + "filter": [{ + "nested": { + "path": "user", + "query": { + "term": { + "user.backend_roles.keyword": "analyst" + } + }, + "score_mode": "none" + } + }] + } + }""", + "allowed_actions": ["read","write"] + }] +} +``` +{% include copy-curl.html %} + +To isolate results for another team, such as `human-resources`, create a separate role (for example, `forecast_human_resources_result_access`) and update the term value to match the appropriate backend role. + +### Define `data-source` read access + +The `data_source_read` role is defined in the same way as in earlier examples. It grants minimal read access to the metrics index that each forecaster uses for training and prediction. + +You can reuse this role across teams or create separate versions if you need per-index restrictions. + +### Map a user to three roles + +The following example maps the user `alice` to all three required roles—`full_access`, `result_access`, and `data_source_read`—using the `analyst` backend role: + +```json +PUT _plugins/_security/api/internalusers/alice +{ + "password": "alice", + "backend_roles": ["analyst"], + "opendistro_security_roles": [ + "forecast_full_access", + "forecast_analyst_result_access", + "data_source_read" + ] +} +``` +{% include copy-curl.html %} + +With this configuration, Alice can: + +- Create, start, stop, and delete only forecasters tagged with the `analyst` backend role. +- View only forecast results tagged with the `analyst` backend role. +- Read the `network-metrics` index as the source for her forecasters. + +To configure a second user, such as `bob` from the HR team, use a parallel setup with the `human-resources` backend role and `forecast_human_resources_result_access`. + +### Users without backend roles + +If a user has the `forecast_read_access` role but no backend roles, they cannot view any forecasters. Backend-role filtering enforces strict matching and prevents access to configurations that do not align with the user's roles. + +--- + +## Selecting remote indexes with fine-grained access control + +To use a remote index as a data source for a forecaster, follow the steps outlined in the [Authentication flow]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/#authentication-flow) section of the [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/) documentation. + +To succeed, the user must: + +- Use a security role that exists in both the local and remote clusters. +- Have that role mapped to the same username in both clusters. + +### Example: Create a new user in the local cluster + +Using the following command, create a new user in the local cluster who can create the forecaster: + +```bash +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/internalusers/forecastuser' \ + -H 'Content-Type: application/json' \ + -d '{"password":"password"}' +``` +{% include copy.html %} + +Using the following command, map the new user to the `forecast_full_access` role: + +``` +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/rolesmapping/forecast_full_access' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` +{% include copy.html %} + +In the remote cluster, create the same user and map `forecast_full_access` to that role, as shown in the following command: + +```bash +# Create the user +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/internalusers/forecastuser' \ + -H 'Content-Type: application/json' \ + -d '{"password":"password"}' + +# Map the role +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/rolesmapping/forecast_full_access' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` +{% include copy-curl.html %} + +### Grant source index read access in both clusters + +To create a forecaster, the user also needs index-level permissions for the `search` or `read` [action groups]({{site.url}}{{site.baseurl}}/security/access-control/default-action-groups/) on every source index, alias, or pattern that the forecaster reads. The permission check occurs in both clusters when reading a remote index. Define and map the same role in both locations. + + +In the local cluster, define a `read` role that grants access to the source index and map it to the forecasting user, as shown in the following command: + +```bash +# Create a role that can search the data +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/roles/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{ + "index_permissions":[{ + "index_patterns":["network-requests"], + "allowed_actions":["search"] + }] + }' + +# Map the role to forecastuser +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/rolesmapping/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` +{% include copy-curl.html %} + +In the remote cluster, define the same role and map it to the same user to ensure that permissions are mirrored across clusters, as shown in the following command: + +``` +# Create the identical role +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/roles/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{ + "index_permissions":[{ + "index_patterns":["network-requests"], + "allowed_actions":["search"] + }] + }' + +# Map the role to the same user +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/rolesmapping/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` +{% include copy-curl.html %} + + +### Register the remote cluster with the local cluster + +Register the remote cluster with the local cluster using a seed node under the `cluster.remote.<alias>.seeds` setting. In OpenSearch, this is called adding a `follower` cluster. + +Assuming that the remote cluster is listening on transport port `9350`, run the following command in the local cluster: + +``` +curl -X PUT "https://localhost:9200/_cluster/settings" \ + -H "Content-Type: application/json" \ + -u "admin:<custom-admin-password>" \ + -d '{ + "persistent": { + "cluster.remote": { + "follower": { + "seeds": [ "127.0.0.1:9350" ] + } + } + } + }' +``` +{% include copy.html %} + + +- Replace `127.0.0.1` with the remote node's transport layer IP if it's located on a different host. +- The alias `follower` can be any name you choose and will be used when referencing remote indexes or configuring cross-cluster replication. +{: .note} + +--- + +## Custom result index permissions + +You can specify a custom index for forecast results instead of using the default result index. If the custom index does not already exist, it will be created automatically when you create a forecaster and start a real-time analysis or test run. + +If the custom index already exists, the Forecasting API checks that the index mapping matches the expected forecast result structure. To ensure compatibility, the index must conform to the schema defined in the [`forecast-results.json`](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/mappings/forecast-results.json) file. + +When a user creates a forecaster—either in OpenSearch Dashboards or by calling the Forecasting API—the system verifies that the user has the following index-level permissions for the custom index: + +- `indices:admin/create` – Required to create and roll over the custom result index. +- `indices:admin/aliases` – Required to create and manage the index alias. +- `indices:data/write/index` – Required to write forecast results to the index (single-stream forecasters). +- `indices:data/read/search` – Required to search the custom index when displaying forecast results. +- `indices:data/write/delete` – Required to delete older forecast results and manage disk usage. +- `indices:data/write/bulk*` – Required because forecasting writes results using the Bulk API. + +## Next step + +For more information about TLS, authentication backends, tenant isolation, and audit logging, see the [Security plugin documentation]({{site.url}}{{site.baseurl}}/security/). diff --git a/_observing-your-data/index.md b/_observing-your-data/index.md index 88984331..526b3225 100644 --- a/_observing-your-data/index.md +++ b/_observing-your-data/index.md @@ -3,26 +3,115 @@ layout: default title: Observability nav_order: 1 has_children: true +has_toc: false nav_exclude: true permalink: /observing-your-data/ redirect_from: - /observability-plugin/index/ - /observing-your-data/index/ +steps: + - heading: "Ingest or connect your data" + description: "Send logs and traces to OpenSearch or connect a Prometheus data source for metrics." + link: "/observing-your-data/ingesting-observability-data/" + - heading: "Choose your observability apps" + description: "Use the classic apps in the **Observability** menu or the apps in an Observability workspace and find the app for each task." + link: "/observing-your-data/exploring-data/" + - heading: "Configure alerts" + description: "To automatically detect anomalies, create monitors that notify you when your data meets a condition." + link: "/observing-your-data/alerting/index/" +detection_cards: + - heading: "Alerting" + description: "Create monitors that query your data on a schedule, define triggers for alert conditions, and perform actions when alerts fire." + link: "/observing-your-data/alerting/index/" + - heading: "Anomaly detection" + description: "Detect anomalies in your time-series data using machine learning with the Random Cut Forest (RCF) algorithm." + link: "/observing-your-data/ad/index/" + - heading: "Forecasting" + description: "Predict future values in your time-series data using the RCF model to anticipate threshold breaches before they occur." + link: "/observing-your-data/forecast/index/" + - heading: "Notifications" + description: "Configure channels for sending alerts through Slack, email, Amazon SNS, webhooks, and other communication services." + link: "/observing-your-data/notifications/index/" +getting_started_cards: + - heading: "Get started with log analytics" + description: "Send web logs to OpenSearch using Fluent Bit and Data Prepper, and then query and visualize them in OpenSearch Dashboards." + link: "/observing-your-data/log-ingestion/" + - heading: "Get started with trace analytics" + description: "Run a sample application that generates traces, send the traces to OpenSearch using Data Prepper, and view them in Trace analytics." + link: "/observing-your-data/trace/getting-started/" + - heading: "Get started with metric analytics" + description: "Connect OpenSearch to a Prometheus data source, and then query and visualize metrics using PPL in Metric analytics." + link: "/observing-your-data/prometheusmetrics/" --- # Observability -Observability is collection of plugins and applications that let you visualize data-driven events by using Piped Processing Language to explore, discover, and query data stored in OpenSearch. +OpenSearch provides observability capabilities for monitoring applications, infrastructure, and AI agents. You can ingest logs, traces, and metrics, explore and visualize them in OpenSearch Dashboards, and set up alerts that notify you of issues. -Your experience of exploring data might differ, but if you're new to exploring data to create visualizations, we recommend trying a workflow like the following: +--- -1. Explore data within a certain timeframe using [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index). -2. Use [event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics) to turn data-driven events into visualizations. - ![Sample Event Analytics View]({{site.url}}{{site.baseurl}}/images/event-analytics.png) -3. Create [operational panels]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels) and add visualizations to compare data the way you like. - ![Sample Operational Panel View]({{site.url}}{{site.baseurl}}/images/operational-panel.png) -4. Use [log analytics]({{site.url}}{{site.baseurl}}/observing-your-data/log-ingestion/) to transform unstructured log data. -5. Use [trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/index) to create traces and dive deep into your data. - ![Sample Trace Analytics View]({{site.url}}{{site.baseurl}}/images/observability-trace.png) -6. Leverage [notebooks]({{site.url}}{{site.baseurl}}/observing-your-data/notebooks) to combine different visualizations and code blocks that you can share with team members. - ![Sample Notebooks View]({{site.url}}{{site.baseurl}}/images/notebooks.png) +## Getting started + +To get started, choose the type of data that you want to explore. The log and trace analytics tutorials ingest sample data into OpenSearch and explore it in OpenSearch Dashboards. + +{% include cards.html cards=page.getting_started_cards %} + +--- + +## Configuring observability + +To configure observability for your applications, follow these steps. If your data is already in OpenSearch, start at step 2. + +{% include list.html list_items=page.steps %} + +--- + +## Monitoring applications + +OpenSearch provides two ways to monitor applications: application performance monitoring (APM) for microservices and web applications, and agent monitoring for generative AI applications. + +| | APM | Agent monitoring | +|---------|-----|--------------| +| **Purpose** | Monitor microservices and web applications | Monitor AI agents and large language models (LLMs) | +| **Metrics** | Rate, error, and duration (RED) metrics | Token usage, model calls, agent steps | +| **Visualization** | Service maps, latency charts, error tracking | Execution graphs (DAGs), trace trees, timelines | +| **Conventions** | OpenTelemetry standard conventions | OpenTelemetry generative AI semantic conventions | +| **Best for** | APIs, microservices, web services | Chatbots, AI agents, LLM applications | + +### APM + +[APM]({{site.url}}{{site.baseurl}}/observing-your-data/apm/) monitors distributed applications using service topology, RED metrics, and performance tracking. APM requires an Observability workspace, an OpenTelemetry Collector, Data Prepper, and Prometheus. + +APM also includes [service-level objectives (SLOs)]({{site.url}}{{site.baseurl}}/observing-your-data/slo/) that let you define availability and latency targets for your services and track their error budgets. + +### Agent monitoring + +[Agent monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/) traces LLM calls, tool invocations, and token usage in generative AI applications. Agent monitoring requires an Observability workspace, an OpenTelemetry Collector, Data Prepper, and an application instrumented using the OpenTelemetry generative AI semantic conventions. + +--- + +## Alerting and detection + +OpenSearch provides the following tools for detecting issues and sending notifications. They work with any index in OpenSearch, including observability data. + +{% include cards.html cards=page.detection_cards %} + + +--- + +## OpenSearch Observability Stack + +The [OpenSearch Observability Stack](https://observability.opensearch.org/) provides a complete, preconfigured observability platform that you can run locally using Docker Compose. The Observability Stack includes: + +- All APM and agent trace capabilities. +- A GenAI SDK for Python or TypeScript instrumentation. +- An Agent Health tool for local debugging and evaluation. +- A Docker Compose setup with example applications. +- A preconfigured OpenTelemetry Collector, OpenSearch Data Prepper, and Prometheus. + +--- + +## Reference + +- [Observability security]({{site.url}}{{site.baseurl}}/observing-your-data/observability-security/) -- Control which users can view and modify observability objects, such as notebooks and visualizations. +- [Simple Schema for Observability]({{site.url}}{{site.baseurl}}/observing-your-data/ss4o/) -- The index naming conventions and field mappings that some classic observability apps require. \ No newline at end of file diff --git a/_observing-your-data/ingesting-observability-data.md b/_observing-your-data/ingesting-observability-data.md new file mode 100644 index 00000000..62923af9 --- /dev/null +++ b/_observing-your-data/ingesting-observability-data.md @@ -0,0 +1,36 @@ +--- +layout: default +title: Ingesting observability data +nav_order: 20 +--- + +# Ingesting observability data + +Before you can analyze observability data in OpenSearch Dashboards, your applications must send it to OpenSearch or to a backend that OpenSearch can query. Logs and traces are stored in OpenSearch indexes. Metrics are stored in Prometheus, which OpenSearch queries through a Prometheus data source, or stored in OpenSearch indexes. + +The setups described in the documentation use the following components: + +- Applications instrumented using [OpenTelemetry](https://opentelemetry.io/docs/) SDKs produce traces, metrics, and logs. +- Log collectors, such as [Fluent Bit](https://docs.fluentbit.io/manual/), read log files and send log lines. +- The [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) receives data from applications and routes it by type. +- [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) parses and enriches logs and traces and writes them to OpenSearch indexes. +- [Prometheus](https://prometheus.io/) stores metrics. OpenSearch queries Prometheus through a [Prometheus data source]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/), so the Prometheus server must be reachable from the OpenSearch nodes. + +## Ingestion paths + +The following table lists the typical paths that observability data takes to OpenSearch or Prometheus. Find the type of data that you want to ingest and then follow the setup instructions for its path. + +| Data | Path | Setup | +|:---|:---|:---| +| Logs | Log collector or OpenTelemetry Collector → Data Prepper → OpenSearch index <br><br> OR <br><br> Log collector → OpenSearch index | [Getting started with log analytics]({{site.url}}{{site.baseurl}}/observing-your-data/log-ingestion/) (Fluent Bit tutorial) <br> [Ingesting log data into OpenSearch]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/ingesting-log-data/) <br> [Log analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/log-analytics/) <br> [OTel logs source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-logs-source/) <br> [Fluent Bit OpenSearch output](https://docs.fluentbit.io/manual/pipeline/outputs/opensearch) <br> [Logstash]({{site.url}}{{site.baseurl}}/tools/logstash/index/) | +| Traces | Instrumented application → OpenTelemetry Collector → Data Prepper → OpenSearch span and service map indexes | [Getting started with trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/getting-started/) (Jaeger HotROD tutorial) <br> [Trace analytics with Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) <br> [OTel trace source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-trace-source/) | +| Metrics | Instrumented application → OpenTelemetry Collector → Prometheus <br><br> OR <br><br> Instrumented application → OpenTelemetry Collector → Data Prepper → OpenSearch index | [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/) <br> [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/) <br> [OTel metrics source]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/sources/otel-metrics-source/) | +| Logs, traces, and metrics for APM | Instrumented application → OpenTelemetry Collector → Data Prepper → OpenSearch indexes (logs and traces) and Prometheus (metrics) | [Configuring telemetry ingestion]({{site.url}}{{site.baseurl}}/observing-your-data/apm/configuring-telemetry-ingestion/) | +| Agent traces | Application instrumented using the OpenSearch generative AI observability SDK → OpenTelemetry Collector → Data Prepper → OpenSearch index | [Instrumenting your application]({{site.url}}{{site.baseurl}}/observing-your-data/agent-traces/instrument/) | + +Trace analytics and APM require the data that their Data Prepper pipelines create, so follow the setup instructions for the app that you plan to use. + +## Related documentation + +- To install preconfigured dashboards and visualizations for common data sources, see [Integrations]({{site.url}}{{site.baseurl}}/dashboards/integrations/index/). +- For the index naming conventions and field mappings that some classic observability apps require, see [Simple Schema for Observability]({{site.url}}{{site.baseurl}}/observing-your-data/ss4o/). diff --git a/_observing-your-data/log-ingestion.md b/_observing-your-data/log-ingestion.md index 61f427d3..588ad76e 100644 --- a/_observing-your-data/log-ingestion.md +++ b/_observing-your-data/log-ingestion.md @@ -1,82 +1,154 @@ --- layout: default -title: Log ingestion -nav_order: 30 +title: Getting started with log analytics +nav_order: 10 redirect_from: - /observability-plugin/log-analytics/ --- -# Log Ingestion +# Getting started with log analytics -Log ingestion provides a way to transform unstructured log data into structured data and ingest into OpenSearch. Structured log data allows for improved queries and filtering based on the data format when searching logs for an event. +In this tutorial, you'll send Apache access logs to OpenSearch, query them using Piped Processing Language (PPL), and add a visualization of the results to a dashboard. -## Get started with log ingestion +The tutorial uses the following components: -OpenSearch Log Ingestion consists of three components---[Data Prepper]({{site.url}}{{site.baseurl}}/clients/data-prepper/index/), [OpenSearch]({{site.url}}{{site.baseurl}}/quickstart/), and [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/index/). The Data Prepper repository contains several [sample applications](https://github.com/opensearch-project/data-prepper/tree/main/examples) that you can use to get started. +- [Fluent Bit](https://docs.fluentbit.io/manual/) collects log lines from a file and sends them to Data Prepper. +- [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) parses each log line into fields and writes the result to an OpenSearch index. +- [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/index/) queries and visualizes the indexed logs using [Event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics/) and [Operational panels]({{site.url}}{{site.baseurl}}/observing-your-data/operational-panels/). -### Basic flow of data +The following diagram shows how log data flows from an application to OpenSearch. ![Log data flow diagram from a distributed application to OpenSearch]({{site.url}}{{site.baseurl}}/images/la.png) -1. Log Ingestion relies on you adding log collection to your application's environment to gather and send log data. +## Prerequisites - (In the [example](#example) below, [FluentBit](https://docs.fluentbit.io/manual/) is used as a log collector that collects log data from a file and sends the log data to Data Prepper). +To run the tutorial, you need [Docker](https://docs.docker.com/get-docker/) and [Git](https://git-scm.com/downloads). The tutorial starts OpenSearch on port 9200 and OpenSearch Dashboards on port 5601, so stop any other OpenSearch cluster that uses these ports. -2. [Data Prepper]({{site.url}}{{site.baseurl}}/clients/data-prepper/index/) receives the log data, transforms the data into a structure format, and indexes it on an OpenSearch cluster. +## Step 1: Download the example -3. The data can then be explored through OpenSearch search queries or the **Discover** page in OpenSearch Dashboards. +The example is located in the `examples/log-ingestion/` directory of the [Data Prepper repository](https://github.com/opensearch-project/data-prepper) and contains the following files. -### Example +| File | Description | +|:---|:---| +| `docker-compose.yaml` | Defines the Fluent Bit (`fluent-bit`), single-node OpenSearch cluster (`opensearch`), and OpenSearch Dashboards (`dashboards`) containers. | +| `docker-compose-dataprepper.yaml` | Defines the Data Prepper (`data-prepper`) container. | +| `fluent-bit.conf` | Configures Fluent Bit to read `test.log` and send each new line to Data Prepper. | +| `log_pipeline.yaml` | Defines the Data Prepper pipeline, which parses each log line using the `COMMONAPACHELOG` grok pattern and writes it to the `apache_logs` index. | +| `test.log` | The log file that Fluent Bit reads. | -This example mimics the writing of log entries to a log file that are then processed by Data Prepper and stored in OpenSearch. +The example sets the OpenSearch `admin` password to `Developer@123` in both `docker-compose.yaml` and `log_pipeline.yaml`. To use a different password, change it in both files before you start the containers. -Download or clone the [Data Prepper repository](https://github.com/opensearch-project/data-prepper). Then navigate to `examples/log-ingestion/` and open `docker-compose.yml` in a text editor. This file contains a container for: - -- [Fluent Bit](https://docs.fluentbit.io/manual/) (`fluent-bit`) -- Data Prepper (`data-prepper`) -- A single-node OpenSearch cluster (`opensearch`) -- OpenSearch Dashboards (`opensearch-dashboards`). - -Close the file and run `docker-compose up --build` to start the containers. - -After the containers start, your ingestion pipeline is set up and ready to ingest log data. The `fluent-bit` container is configured to read log data from `test.log`. Run the following command to generate log data to send to the log ingestion pipeline. - -``` -echo '63.173.168.120 - - [04/Nov/2021:15:07:25 -0500] "GET /search/tag/list HTTP/1.0" 200 5003' >> test.log -``` - -Fluent-Bit will collect the log data and send it to Data Prepper: - -```angular2html -[2021/12/02 15:35:41] [ info] [output:http:http.0] data-prepper:2021, HTTP status=200 -200 OK -``` - -Data Prepper will process the log and index it: - -``` -2021-12-02T15:35:44,499 [log-pipeline-processor-worker-1-thread-1] INFO com.amazon.dataprepper.pipeline.ProcessWorker - log-pipeline Worker: Processing 1 records from buffer -``` - -This should result in a single document being written to the OpenSearch cluster in the `apache-logs` index as defined in the `log_pipeline.yaml` file. - -Run the following command to see one of the raw documents in the OpenSearch cluster: +Clone the Data Prepper repository and go to the example directory: ```bash -curl -X GET -u 'admin:<custom-admin-password>' -k 'https://localhost:9200/apache_logs/_search?pretty&size=1' +git clone https://github.com/opensearch-project/data-prepper.git +cd data-prepper/examples/log-ingestion +``` +{% include copy.html %} + +## Step 2: Add a timestamp to each log event + +Operational panels filter every visualization by time, so the index must contain a field of the `date` type. The log lines contain a timestamp, but the grok pattern stores it as text. To add a `date` field, add a [`date` processor]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/date/) to the `processor` list in `log_pipeline.yaml`, after the `grok` processor. The updated file contains the following pipeline: + +```yaml +log-pipeline: + source: + http: + ssl: false + processor: + - grok: + match: + log: [ "%{COMMONAPACHELOG}" ] + - date: + from_time_received: true + destination: "@timestamp" + sink: + - opensearch: + hosts: [ "https://opensearch:9200" ] + insecure: true + username: admin + password: Developer@123 + index: apache_logs +``` +{% include copy.html %} + +The `date` processor sets the `@timestamp` field to the time at which Data Prepper receives each event. Using the time received keeps the sample events, whose log lines are from 2021, within the default time range of the OpenSearch Dashboards pages used in this tutorial. + +## Step 3: Start the containers + +Start the containers using both Docker Compose files in a single command: + +```bash +docker compose -f docker-compose.yaml -f docker-compose-dataprepper.yaml up -d +``` +{% include copy.html %} + +Both files must be specified in the same command so that all four containers join the same Docker network. If you start the files separately, Fluent Bit cannot reach Data Prepper and Data Prepper cannot reach OpenSearch, so no data is indexed. + +Wait until Data Prepper is ready to receive data. Run the following command until the output contains a line similar to `Started http source on port 2021`: + +```bash +docker logs data-prepper 2>&1 | grep "Started http source" +``` +{% include copy.html %} + +Data Prepper starts the pipeline only after it connects to OpenSearch, which can take a minute or longer. If you write log data before Data Prepper is ready, Fluent Bit can discard the data after it fails to deliver it. + +## Step 4: Send log data + +Append the following log lines to `test.log`: + +```bash +cat >> test.log <<'EOF' +63.173.168.120 - - [04/Nov/2021:15:07:25 -0500] "GET /search/tag/list HTTP/1.0" 200 5003 +10.0.0.5 - - [04/Nov/2021:15:08:01 -0500] "GET /index.html HTTP/1.1" 200 1024 +10.0.0.7 - - [04/Nov/2021:15:08:12 -0500] "POST /login HTTP/1.1" 401 512 +10.0.0.9 - - [04/Nov/2021:15:09:44 -0500] "GET /missing HTTP/1.1" 404 210 +10.0.0.5 - - [04/Nov/2021:15:10:02 -0500] "GET /cart HTTP/1.1" 500 98 +EOF +``` +{% include copy.html %} + +Fluent Bit collects the log lines and sends them to Data Prepper. To confirm delivery, run `docker logs fluent-bit`. The output contains a line similar to the following: + +```text +[2026/10/27 22:51:53.623] [ info] [output:http:http.0] data-prepper:2021, HTTP status=200 ``` -The response should show the parsed log data: +## Step 5: Search the data in OpenSearch +Data Prepper parses each log line and writes it to the `apache_logs` index, as defined in `log_pipeline.yaml`. Data Prepper sends documents to OpenSearch in batches, so the documents can take a minute or longer to appear. To view the first document, run the following command: + +```bash +curl -X GET -u 'admin:Developer@123' -k 'https://localhost:9200/apache_logs/_search?pretty&size=1' ``` +{% include copy.html %} + +The response contains the parsed log data, including the `@timestamp` field added by the `date` processor. The `date` field, which contains the time at which Fluent Bit read the line in epoch seconds, is added by the Fluent Bit HTTP output: + +```json +{ + "took" : 6, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 5, + "relation" : "eq" + }, + "max_score" : 1.0, "hits" : [ { "_index" : "apache_logs", - "_type" : "_doc", - "_id" : "yGrJe30BgI2EWNKtDZ1g", + "_id" : "B0Oif6EBGoQmkf_UZoQh", "_score" : 1.0, "_source" : { - "date" : 1.638459307042312E9, + "date" : 1.793142650955058E9, "log" : "63.173.168.120 - - [04/Nov/2021:15:07:25 -0500] \"GET /search/tag/list HTTP/1.0\" 200 5003", "request" : "/search/tag/list", "auth" : "-", @@ -86,10 +158,52 @@ The response should show the parsed log data: "clientip" : "63.173.168.120", "verb" : "GET", "httpversion" : "1.0", - "timestamp" : "04/Nov/2021:15:07:25 -0500" + "timestamp" : "04/Nov/2021:15:07:25 -0500", + "@timestamp" : "2026-10-27T23:10:51.594Z" } } ] + } +} ``` -The same data can be viewed in OpenSearch Dashboards by visiting the **Discover** page and searching the `apache_logs` index. Remember, you must create the index in OpenSearch Dashboards if this is your first time searching for the index. \ No newline at end of file +## Step 6: Create a dashboard + +Go to [http://localhost:5601](http://localhost:5601) and log in as the `admin` user using the password `Developer@123`. Then create an operational panel to hold your visualization: + +1. On the top menu, go to **Observability** > **Dashboards**. +1. Select **Create Dashboard**. +1. In **Name**, enter `Web traffic`, and then select **Create**. + +## Step 7: Query and visualize the logs + +Use Event analytics to query the logs and save a visualization to the dashboard: + +1. On the top menu, go to **Observability** > **Logs**, and then select **Event Explorer**. +1. In the query editor, enter the following PPL query, which counts the log events for each HTTP method: + + ```sql + source = apache_logs | stats count() by verb + ``` + {% include copy.html %} + +1. Select **Run**. The **Events** tab lists the results. If no results appear, use the time picker to select a time range that includes the time at which you sent the log data. +1. Select the **Visualizations** tab. The results are displayed as a vertical bar chart, with one bar for each HTTP method. +1. Select **Save**. In **Custom operational dashboards/application**, select **Web traffic**. In **Name**, enter `Requests by method`, and then select **Save**. +1. On the top menu, go to **Observability** > **Dashboards**, and then select **Web traffic**. The dashboard contains the **Requests by method** visualization. + +## Step 8: Clean up + +To stop the containers and delete their data, run the following command: + +```bash +docker compose -f docker-compose.yaml -f docker-compose-dataprepper.yaml down -v +``` +{% include copy.html %} + +## Next steps + +- To learn how logs, traces, and metrics reach OpenSearch, see [Ingesting observability data]({{site.url}}{{site.baseurl}}/observing-your-data/ingesting-observability-data/). +- To learn more about PPL queries and visualizations, see [Event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics/). +- To explore logs in an Observability workspace, see [Logs]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-logs/). +- To learn more about Data Prepper pipelines, see [Ingesting log data into OpenSearch]({{site.url}}{{site.baseurl}}/data-prepper/getting-started/ingesting-log-data/). diff --git a/_observing-your-data/notifications/api.md b/_observing-your-data/notifications/api.md index c99a7195..a604b127 100644 --- a/_observing-your-data/notifications/api.md +++ b/_observing-your-data/notifications/api.md @@ -1,6 +1,6 @@ --- layout: default -title: API +title: Notifications API nav_order: 50 parent: Notifications redirect_from: @@ -9,7 +9,13 @@ redirect_from: # Notifications API -If you want to programmatically define your notification channels and sources for versioning and reuse, you can use the Notifications REST API to define, configure, and delete notification channels and send test messages. +Use the Notifications REST API to programmatically create, retrieve, update, and delete notification configurations, to send test messages, and to send messages to existing channels. Defining channels through the API lets you version and reuse your channel definitions. + +A notification configuration is one of the following types: + +- A channel that receives notifications: `slack`, `chime`, `microsoft_teams`, `webhook`, `email`, or `sns`. +- An email sender that an `email` channel uses to send messages: `smtp_account` or `ses_account`. +- An email recipient group that an `email` channel sends messages to: `email_group`. --- @@ -23,19 +29,27 @@ If you want to programmatically define your notification channels and sources fo To retrieve a list of all supported notification configuration types, send a GET request to the `features` resource. -#### Example request +### Endpoints ```json GET /_plugins/_notifications/features ``` -#### Example response +### Example request + +```json +GET /_plugins/_notifications/features +``` +{% include copy-curl.html %} + +### Example response ```json { "allowed_config_type_list" : [ "slack", "chime", + "microsoft_teams", "webhook", "email", "sns", @@ -49,17 +63,130 @@ GET /_plugins/_notifications/features } ``` -## List all notification configurations +### Response body fields -To retrieve a list of all notification configurations, send a GET request to the `configs` resource. +The following table lists all response body fields. -#### Example request +Field | Data type | Description +:--- | :--- | :--- +`allowed_config_type_list` | Array of strings | The configuration types that the cluster allows. Set by the `opensearch.notifications.core.allowed_config_types` setting. +`plugin_features` | Object | Plugin features and their values. Contains `tooltip_support`, which is set by the `opensearch.notifications.core.tooltip_support` setting. + +## List all notification channels + +To retrieve a list of all notification channels, send a GET request to the `channels` resource. The response contains configurations of the `slack`, `chime`, `microsoft_teams`, `webhook`, `email`, and `sns` types. Email senders and email recipient groups are not channels, so the response omits them. This endpoint does not accept query parameters. + +### Endpoints ```json -GET _plugins/_notifications/configs +GET /_plugins/_notifications/channels ``` -#### Example response +### Example request + +```json +GET /_plugins/_notifications/channels +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "start_index" : 0, + "total_hits" : 2, + "total_hit_relation" : "eq", + "channel_list" : [ + { + "config_id" : "sample-id", + "name" : "Sample Slack Channel", + "description" : "This is a Slack channel", + "config_type" : "slack", + "is_enabled" : true + }, + { + "config_id" : "sample-id2", + "name" : "Test chime channel", + "description" : "A test chime channel", + "config_type" : "chime", + "is_enabled" : true + } + ] +} +``` + +## List all notification configurations + +To retrieve a list of notification configurations of all types, send a GET request to the `configs` resource. + +### Endpoints + +```json +GET /_plugins/_notifications/configs +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. Unrecognized query parameters are rejected. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id` | String | Returns the configuration with this ID. +`config_id_list` | String | Returns the configurations with these IDs. Specify a comma-separated list of configuration IDs. If you specify `config_id` or `config_id_list`, the request ignores all filter parameters. +`from_index` | Integer | The starting index of the results. Default is `0`. +`max_items` | Integer | The maximum number of configurations to return. Default is `1000`. +`sort_field` | String | The field to sort results by. Valid values are the names of the filter parameters in the following two tables, except `email.recipient_list.recipient` and `email_group.recipient_list.recipient`. Default is `last_updated_time_ms`. +`sort_order` | String | The sort direction. Valid values are `asc` and `desc`. Default is `asc`. +`query` | String | Searches all keyword and text filter fields using query string syntax. +`text_query` | String | Searches all text filter fields using query string syntax. + +The following filter parameters match configurations whose field exactly equals the specified value. Where noted, specify multiple comma-separated values to match any of them. + +Parameter | Data type | Description +:--- | :--- | :--- +`last_updated_time_ms` | String | The time at which the configuration was last updated, in epoch milliseconds. Specify an exact value or a range in the `<from>..<to>` format. +`created_time_ms` | String | The time at which the configuration was created, in epoch milliseconds. Specify an exact value or a range in the `<from>..<to>` format. +`is_enabled` | Boolean | Whether the configuration is enabled. +`config_type` | String | The configuration type. Specify one or more comma-separated values. Valid values are `slack`, `chime`, `microsoft_teams`, `webhook`, `email`, `sns`, `smtp_account`, `ses_account`, and `email_group`. +`email.email_account_id` | String | The ID of the email sender that an `email` channel uses. Accepts a comma-separated list. +`email.email_group_id_list` | String | The ID of an email recipient group that an `email` channel uses. Accepts a comma-separated list. +`smtp_account.method` | String | The encryption method of an SMTP sender. Accepts a comma-separated list. +`ses_account.region` | String | The AWS Region of an Amazon Simple Email Service (Amazon SES) sender. Accepts a comma-separated list. + +The following filter parameters match configurations whose field contains the specified text. + +Parameter | Data type | Description +:--- | :--- | :--- +`name` | String | The configuration name. +`description` | String | The configuration description. +`email.recipient_list.recipient` | String | A recipient email address of an `email` channel. +`email_group.recipient_list.recipient` | String | A recipient email address of an email recipient group. +`slack.url` | String | The Slack incoming webhook URL. Must contain `hooks.slack.com/services/` or `hooks.gov-slack.com/services/`. +`chime.url` | String | The Amazon Chime incoming webhook URL. Must contain `hooks.chime.aws/incomingwebhooks/` and a `?token=` parameter. +`microsoft_teams.url` | String | The Microsoft Teams webhook URL. The URL's domain must be `webhook.office.com`, `powerplatform.com`, or `logic.azure.com`. +`webhook.url` | String | The custom webhook URL. +`smtp_account.host` | String | The host of an SMTP sender. +`smtp_account.from_address` | String | The sender email address of an SMTP sender. +`sns.topic_arn` | String | The Amazon Simple Notification Service (Amazon SNS) topic ARN. +`sns.role_arn` | String | The IAM role ARN used to publish to the Amazon SNS topic. +`ses_account.role_arn` | String | The IAM role ARN of an Amazon SES sender. +`ses_account.from_address` | String | The sender email address of an Amazon SES sender. + +### Example request + +```json +GET /_plugins/_notifications/configs +``` +{% include copy-curl.html %} + +The following request returns the first 10 Slack and Amazon Chime configurations, sorted by name: + +```json +GET /_plugins/_notifications/configs?config_type=slack,chime&sort_field=name&sort_order=asc&max_items=10 +``` +{% include copy-curl.html %} + +### Example response ```json { @@ -77,7 +204,7 @@ GET _plugins/_notifications/configs "config_type" : "slack", "is_enabled" : true, "slack" : { - "url" : "https://sample-slack-webhook" + "url" : "https://hooks.slack.com/services/<webhook-path>" } } }, @@ -91,7 +218,7 @@ GET _plugins/_notifications/configs "config_type" : "chime", "is_enabled" : true, "chime" : { - "url" : "https://sample-chime-webhook" + "url" : "https://hooks.chime.aws/incomingwebhooks/<webhook-id>?token=<token>" } } } @@ -99,163 +226,310 @@ GET _plugins/_notifications/configs } ``` -To filter the notification configuration types this request returns, you can refine your query with the following optional path parameters. +### Response body fields -Parameter | Description -:--- | :--- -config_id | Specifies the channel identifier. -config_id_list | Specifies a comma-separated list of channel IDs. -from_index | The starting index to search from. -max_items | The maximum amount of items to return in your request. -sort_order | Specifies the direction to sort results in. Valid options are `asc` and `desc`. -sort_field | Field to sort results with. -last_updated_time_ms | The Unix time in milliseconds of when the channel was last updated. -created_time_ms | The Unix time in milliseconds of when the channel was created. -is_enabled | Indicates whether the channel is enabled. -config_type | The channel type. Valid options are `sns`, `slack`, `chime`, `webhook`, `smtp_account`, `ses_account`, `email_group`, and `email`. -name | The channel name. -description | The channel description. -email.email_account_id | The sender email addresses the channel uses. -email.email_group_id_list | The email groups the channel uses. -email.recipient_list | The channel recipient list. -email_group.recipient_list | The channel list of email recipient groups. -smtp_account.method | The email encryption method. -slack.url | The Slack channel URL. -chime.url | The Amazon Chime connection URL. -webhook.url | The webhook URL. -smtp_account.host | The domain of the SMTP account. -smtp_account.from_address | The email account's sender address. -smtp_account.method | The SMTP account's encryption method. -sns.topic_arn | The Amazon Simple Notification Service (SNS) topic's ARN. -sns.role_arn | The Amazon SNS topic's role ARN. -ses_account.region | The Amazon Simple Email Service (SES) account's AWS Region. -ses_account.role_arn | The Amazon SES account's role ARN. -ses_account.from_address | The Amazon SES account's sender email address. +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`start_index` | Integer | The starting index of the returned results. +`total_hits` | Integer | The total number of configurations that match the request. +`total_hit_relation` | String | Whether `total_hits` is exact (`eq`) or a lower bound (`gte`). +`config_list` | Array of objects | The matching configurations. + +Each object in the `config_list` array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`config_id` | String | The configuration ID. +`last_updated_time_ms` | Long | The time at which the configuration was last updated, in epoch milliseconds. +`created_time_ms` | Long | The time at which the configuration was created, in epoch milliseconds. +`config` | Object | The configuration. Contains the same fields as the `config` object in the [create request](#request-body-fields). ## Create channel configuration -To create a notification channel configuration, send a POST request to the `configs` resource. +To create a notification configuration, send a POST request to the `configs` resource. Use this request to create channels, email senders, and email recipient groups. -#### Example request +If you omit `config_id`, OpenSearch generates an ID. If you specify a `config_id` that already exists, the request fails with a `409 Conflict` status. To modify an existing configuration, use the [Update channel configuration](#update-channel-configuration) API. +{: .note} + +### Endpoints ```json -POST /_plugins/_notifications/configs/ +POST /_plugins/_notifications/configs +``` + +### Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`config_id` | String | The configuration ID. Valid characters are letters, digits, `+`, `/`, `_`, and `-`. Optional. If omitted, OpenSearch generates an ID. +`config` | Object | The configuration. Required. + +The `config` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`name` | String | The configuration name. Required. +`description` | String | The configuration description. Optional. Default is an empty string. +`config_type` | String | The configuration type. Valid values are `slack`, `chime`, `microsoft_teams`, `webhook`, `email`, `sns`, `smtp_account`, `ses_account`, and `email_group`. Required. +`is_enabled` | Boolean | Whether the channel is enabled. OpenSearch does not send notifications to a disabled channel. Optional. Default is `true`. +`<config_type>` | Object | The settings for the configuration type. The field name must match the `config_type` value, for example, `"slack": { ... }` when `config_type` is `slack`. Required. The fields for each type are described in the following sections. + +#### Slack, Amazon Chime, and Microsoft Teams + +The `slack`, `chime`, and `microsoft_teams` objects contain the following field. + +Field | Data type | Description +:--- | :--- | :--- +`url` | String | The incoming webhook URL. Required. A Slack URL must contain `hooks.slack.com/services/` or `hooks.gov-slack.com/services/`. An Amazon Chime URL must contain `hooks.chime.aws/incomingwebhooks/` and a `?token=` parameter. A Microsoft Teams URL's domain must be `webhook.office.com`, `powerplatform.com`, or `logic.azure.com`. + +#### Custom webhook + +The `webhook` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`url` | String | The webhook URL. Must use the `http` or `https` protocol. Required. +`header_params` | Object | The HTTP headers to send with each request, specified as header name and value pairs. Optional. +`method` | String | The HTTP method. Valid values are `POST`, `PUT`, and `PATCH`. Optional. Default is `POST`. Unrecognized values are stored as `POST`. + +#### Email channel + +The `email` object contains the following fields. The sender and recipient groups must exist before you create the channel. + +Field | Data type | Description +:--- | :--- | :--- +`email_account_id` | String | The ID of the `smtp_account` or `ses_account` configuration that sends the emails. Required. +`recipient_list` | Array of objects | The recipients. Each object contains a `recipient` field that specifies an email address. Optional. +`email_group_id_list` | Array of strings | The IDs of `email_group` configurations to send emails to. Optional. + +#### Amazon SNS + +The `sns` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`topic_arn` | String | The ARN of the Amazon SNS topic, in the `arn:aws:sns:<region>:<account_id>:<topic_name>` format. Required. +`role_arn` | String | The ARN of the IAM role that OpenSearch assumes to publish to the topic. Optional. If omitted, OpenSearch uses the AWS credentials available on the cluster nodes. For more information, see [Amazon SNS as a channel type]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/#amazon-sns-as-a-channel-type). + +#### SMTP sender + +The `smtp_account` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`host` | String | The SMTP server host. Required. +`port` | Integer | The SMTP server port. Must be a positive integer. Required. +`method` | String | The encryption method. Valid values are `none`, `ssl`, and `start_tls`. Required. Unrecognized values are stored as `none`. To use `ssl` or `start_tls`, add the sender credentials to the OpenSearch keystore. For more information, see [Authenticate sender account]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/#authenticate-sender-account). +`from_address` | String | The sender email address. Required. + +#### Amazon SES sender + +The `ses_account` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`region` | String | The AWS Region of the Amazon SES account. Required. +`role_arn` | String | The ARN of the IAM role that OpenSearch assumes to send emails. Optional. +`from_address` | String | The sender email address. Required. + +#### Email recipient group + +The `email_group` object contains the following field. + +Field | Data type | Description +:--- | :--- | :--- +`recipient_list` | Array of objects | The recipients. Each object contains a `recipient` field that specifies an email address. Required. + +### Example: Creating a Slack channel + +```json +POST /_plugins/_notifications/configs { "config_id": "sample-id", - "name": "sample-name", "config": { "name": "Sample Slack Channel", "description": "This is a Slack channel", "config_type": "slack", "is_enabled": true, "slack": { - "url": "https://sample-slack-webhook" + "url": "https://hooks.slack.com/services/<webhook-path>" } } } ``` +{% include copy-curl.html %} -The create channel API operation accepts the following fields in its request body: - -Field | Data type | Description | Required -:--- | :--- | :--- | :--- -config_id | String | The configuration's custom ID. | No -config | Object | Contains all relevant information, such as channel name, configuration type, and plugin source. | Yes -name | String | Name of the channel. | Yes -description | String | The channel's description. | No -config_type | String | The destination of your notification. Valid options are `sns`, `slack`, `chime`, `webhook`, `smtp_account`, `ses_account`, `email_group`, and `email`. | Yes -is_enabled | Boolean | Indicates whether the channel is enabled for sending and receiving notifications. Default is true. | No - -The create channel operation accepts multiple `config_types` as possible notification destinations, so follow the format for your preferred `config_type`. +### Example: Creating a custom webhook channel ```json -"sns": { - "topic_arn": "<arn>", - "role_arn": "<arn>" //optional -} -"slack": { - "url": "https://sample-chime-webhoook" -} -"chime": { - "url": "https://sample-amazon-chime-webhoook" -} -"webhook": { - "url": "https://custom-webhook-test-url.com:8888/test-path?params1=value1¶ms2=value2" -} -"smtp_account": { - "host": "test-host.com", - "port": 123, - "method": "start_tls", - "from_address": "test@email.com" -} -"ses_account": { - "region": "us-east-1", - "role_arn": "arn:aws:iam::012345678912:role/NotificationsSESRole", - "from_address": "test@email.com" -} -"email_group": { //Email recipient group - "recipient_list": [ - { - "recipient": "test-email1@test.com" - }, - { - "recipient": "test-email2@test.com" +POST /_plugins/_notifications/configs +{ + "config_id": "sample-webhook-id", + "config": { + "name": "Sample Webhook Channel", + "config_type": "webhook", + "webhook": { + "url": "https://custom-webhook-test-url.com:8888/test-path?params1=value1¶ms2=value2", + "header_params": { + "Content-Type": "application/json" + }, + "method": "POST" } - ] -} -"email": { //The channel that sends emails - "email_account_id": "<smtp or ses account config id>", - "recipient_list": [ - { - "recipient": "custom.email@test.com" - } - ], - "email_group_id_list": [] + } } ``` +{% include copy-curl.html %} -The following example demonstrates how to create a channel using email as a `config_type`: +### Example: Creating an email channel + +An email channel requires an email sender. The following request creates an SMTP sender: ```json -POST /_plugins/_notifications/configs/ +POST /_plugins/_notifications/configs { - "id": "sample-email-id", - "name": "sample-name", + "config_id": "sample-smtp-id", + "config": { + "name": "sample-smtp-sender", + "config_type": "smtp_account", + "smtp_account": { + "host": "smtp.example.com", + "port": 587, + "method": "start_tls", + "from_address": "alerts@example.com" + } + } +} +``` +{% include copy-curl.html %} + +The following request creates an email recipient group: + +```json +POST /_plugins/_notifications/configs +{ + "config_id": "sample-email-group-id", + "config": { + "name": "sample-email-group", + "config_type": "email_group", + "email_group": { + "recipient_list": [ + { + "recipient": "test-email1@test.com" + }, + { + "recipient": "test-email2@test.com" + } + ] + } + } +} +``` +{% include copy-curl.html %} + +The following request creates an email channel that sends messages through the SMTP sender to one recipient and to the recipient group: + +```json +POST /_plugins/_notifications/configs +{ + "config_id": "sample-email-id", "config": { "name": "Sample Email Channel", "description": "Sample email description", "config_type": "email", "is_enabled": true, "email": { - "email_account_id": "<email_account_id>", + "email_account_id": "sample-smtp-id", "recipient_list": [ - "sample@email.com" - ] + { + "recipient": "sample@email.com" + } + ], + "email_group_id_list": ["sample-email-group-id"] } } } ``` +{% include copy-curl.html %} -#### Example response +To use an Amazon SES sender, create an `ses_account` configuration and specify its ID in `email_account_id`. The following request creates an Amazon SES sender: + +```json +POST /_plugins/_notifications/configs +{ + "config_id": "sample-ses-id", + "config": { + "name": "sample-ses-sender", + "config_type": "ses_account", + "ses_account": { + "region": "us-east-1", + "role_arn": "arn:aws:iam::012345678912:role/NotificationsSESRole", + "from_address": "test@email.com" + } + } +} +``` +{% include copy-curl.html %} + +### Example: Creating an Amazon SNS channel + +```json +POST /_plugins/_notifications/configs +{ + "config_id": "sample-sns-id", + "config": { + "name": "Sample SNS Channel", + "config_type": "sns", + "sns": { + "topic_arn": "arn:aws:sns:us-east-1:012345678912:sample-topic", + "role_arn": "arn:aws:iam::012345678912:role/NotificationsSNSRole" + } + } +} +``` +{% include copy-curl.html %} + +### Example response + +The response contains the configuration ID: ```json { - "config_id" : "<config_id>" + "config_id" : "sample-id" } ``` - ## Get channel configuration -To get a channel configuration by `config_id`, send a GET request and specify the `config_id` as a path parameter. +To get a notification configuration by its ID, send a GET request and specify the `config_id` as a path parameter. -#### Example request +### Endpoints ```json -GET _plugins/_notifications/configs/<config_id> +GET /_plugins/_notifications/configs/{config_id} ``` -#### Example response +### Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id` | String | The configuration ID. Required. + +### Example request + +```json +GET /_plugins/_notifications/configs/sample-id +``` +{% include copy-curl.html %} + +### Example response + +The response has the same format as the [List all notification configurations](#list-all-notification-configurations) response: ```json { @@ -273,7 +547,7 @@ GET _plugins/_notifications/configs/<config_id> "config_type" : "slack", "is_enabled" : true, "slack" : { - "url" : "https://sample-slack-webhook" + "url" : "https://hooks.slack.com/services/<webhook-path>" } } } @@ -281,15 +555,31 @@ GET _plugins/_notifications/configs/<config_id> } ``` - ## Update channel configuration -To update a channel configuration, send a POST request to the `configs` resource and specify the channel's `config_id` as a path parameter. Specify the new configuration details in the request body. +To update an existing notification configuration, send a PUT request to the `configs` resource and specify the configuration's `config_id` as a path parameter. The request body contains the `config` object, which has the same fields as in the [create request](#create-channel-configuration). The update replaces the entire configuration, so specify all fields, including the ones you don't change. Fields that you omit are reset to their default values. -#### Example request +You cannot change the `config_type` of an existing configuration. A request that specifies a different `config_type` fails with a `409 Conflict` status. If the `config_id` does not exist, the request fails with a `404 Not Found` status. To create a configuration, use the [Create channel configuration](#create-channel-configuration) API. +{: .note} + +### Endpoints ```json -PUT _plugins/_notifications/configs/<config_id> +PUT /_plugins/_notifications/configs/{config_id} +``` + +### Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id` | String | The ID of the configuration to update. Required. + +### Example request + +```json +PUT /_plugins/_notifications/configs/sample-id { "config": { "name": "Slack Channel", @@ -297,106 +587,279 @@ PUT _plugins/_notifications/configs/<config_id> "config_type": "slack", "is_enabled": true, "slack": { - "url": "https://hooks.slack.com/sample-url" + "url": "https://hooks.slack.com/services/<webhook-path>" } } } ``` +{% include copy-curl.html %} -#### Example response +### Example response ```json { - "config_id" : "<config_id>" + "config_id" : "sample-id" } ``` - ## Delete channel configuration -To delete a channel configuration, send a DELETE request to the `configs` resource and specify the `config_id` as a path parameter. +To delete one or more notification configurations, send a DELETE request to the `configs` resource. Specify one ID as a path parameter or specify a comma-separated list of IDs in the `config_id_list` query parameter. If any of the specified configurations does not exist, the request fails and OpenSearch does not delete any of them. -#### Example request +OpenSearch does not check whether other configurations use the configuration you delete. For example, you can delete an email sender that an email channel uses. + +### Endpoints ```json -DELETE /_plugins/_notifications/configs/<config_id> +DELETE /_plugins/_notifications/configs/{config_id} +DELETE /_plugins/_notifications/configs?config_id_list=<config_id1>,<config_id2> ``` +### Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id` | String | The ID of the configuration to delete. + +### Query parameters + +The following table lists the available query parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id_list` | String | A comma-separated list of the IDs of the configurations to delete. If you specify this parameter, OpenSearch ignores the `config_id` path parameter. + +### Example request + +```json +DELETE /_plugins/_notifications/configs/sample-id +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "delete_response_list" : { + "sample-id" : "OK" + } +} +``` + +### Example: Deleting multiple configurations + +```json +DELETE /_plugins/_notifications/configs?config_id_list=sample-id,sample-id2,sample-id3 +``` +{% include copy-curl.html %} + #### Example response ```json { "delete_response_list" : { - "<config_id>" : "OK" + "sample-id" : "OK", + "sample-id2" : "OK", + "sample-id3" : "OK" } } ``` -You can also submit a comma-separated list of channel IDs you want to delete, and OpenSearch deletes all of the specified notification channels. - -#### Example request - -```json -DELETE /_plugins/_notifications/configs/?config_id_list=<config_id1>,<config_id2>,<config_id3>... -``` - -#### Example response - -```json -{ - "delete_response_list" : { - "<config_id1>" : "OK", - "<config_id2>" : "OK", - "<config_id3>" : "OK" - } -} -``` - - ## Send test notification -To send a test notification, send a GET request to `/feature/test/` and specify the channel configuration's `config_id` as a path parameter. +To send a test message to a channel, send a POST request to the `feature/test` resource and specify the channel's `config_id` as a path parameter. The channel must be enabled and must be of the `slack`, `chime`, `microsoft_teams`, `webhook`, `email`, or `sns` type. Email senders and email recipient groups cannot receive test messages. -#### Example request +The test message title is `Test Message Title-<config_id>`, and the message body is `Test message content body for config id <config_id>`. + +If OpenSearch delivers the message, the request returns a `200 OK` status. If delivery fails, for example, because the destination is unreachable or rejects the message, the request returns an error. The error contains the delivery status that the destination returned. + +### Endpoints ```json -GET _plugins/_notifications/feature/test/<config_id> +POST /_plugins/_notifications/feature/test/{config_id} ``` -#### Example response +### Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id` | String | The ID of the channel to send the test message to. Required. + +### Example request + +```json +POST /_plugins/_notifications/feature/test/sample-webhook-id +``` +{% include copy-curl.html %} + +### Example response ```json { "event_source" : { - "title" : "Test Message Title-0Jnlh4ABa4TCWn5C5H2G", - "reference_id" : "0Jnlh4ABa4TCWn5C5H2G", + "title" : "Test Message Title-sample-webhook-id", + "reference_id" : "sample-webhook-id", "severity" : "info", "tags" : [ ] }, "status_list" : [ { - "config_id" : "0Jnlh4ABa4TCWn5C5H2G", - "config_type" : "slack", - "config_name" : "sample-id", + "config_id" : "sample-webhook-id", + "config_type" : "webhook", + "config_name" : "Sample Webhook Channel", "email_recipient_status" : [ ], "delivery_status" : { "status_code" : "200", - "status_text" : """<!doctype html> -<html> -<head> -</head> -<body> -<div> - <h1>Example Domain</h1> - <p>Sample paragraph.</p> - <p><a href="sample.example.com">TO BE OR NOT TO BE, THAT IS THE QUESTION</a></p> -</div> -</body> -</html> -""" + "status_text" : "ok" } } ] } - ``` + +### Response body fields + +The following table lists all response body fields. + +Field | Data type | Description +:--- | :--- | :--- +`event_source` | Object | Information about the test message. +`status_list` | Array of objects | The delivery status for each channel. + +The `event_source` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`title` | String | The message title. +`reference_id` | String | The ID of the message source. For a test message, this is the channel ID. +`severity` | String | The message severity. +`tags` | Array of strings | The message tags. + +Each object in the `status_list` array contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`config_id` | String | The channel ID. +`config_type` | String | The channel type. +`config_name` | String | The channel name. +`email_recipient_status` | Array of objects | For an email channel, the delivery status for each recipient. Each object contains a `recipient` field and a `delivery_status` object. Empty for other channel types. +`delivery_status` | Object | The delivery status. + +The `delivery_status` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`status_code` | String | The status code that the destination returned. +`status_text` | String | The response text that the destination returned. + +## Send notification +**Introduced 3.10** +{: .label .label-purple } + +To send a message to an existing channel, send a POST request to the `feature/send` resource and specify the channel's `config_id` as a path parameter. Delivery uses the channel's configuration, so the message is formatted and sent the same way as an alert notification. To send to several channels, send one request per channel. + +### Endpoints + +```json +POST /_plugins/_notifications/feature/send/{config_id} +``` + +### Path parameters + +The following table lists the available path parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`config_id` | String | The ID of the channel to send the message to. Required. + +### Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`event_source` | Object | The message source. Required. +`channel_message` | Object | The message content. Required. + +The `event_source` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`title` | String | The message title. Required. +`reference_id` | String | An identifier of the event that the message reports, such as a job ID. Required. +`severity` | String | The message severity. Valid values are `critical`, `high`, `info`, and `none`. Optional. Default is `info`. +`tags` | Array of strings | The tags for the message. Optional. + +The `channel_message` object contains the following fields. + +Field | Data type | Description +:--- | :--- | :--- +`text_description` | String | The message body. Required. +`html_description` | String | An HTML message body, used by email channels. Optional. + +The message is always sent on behalf of the authenticated user. You cannot specify another user in the request. + +### Example request + +```json +POST /_plugins/_notifications/feature/send/sample-id +{ + "event_source": { + "title": "Weekly sales report", + "reference_id": "report-123", + "severity": "info", + "tags": ["scheduled-report"] + }, + "channel_message": { + "text_description": "Your report is ready: https://dashboards.example.com/reports/abc" + } +} +``` +{% include copy-curl.html %} + +### Example response + +The response contains the channel's delivery status: + +```json +{ + "event_source": { + "title": "Weekly sales report", + "reference_id": "report-123", + "severity": "info", + "tags": ["scheduled-report"] + }, + "status_list": [ + { + "config_id": "sample-id", + "config_type": "slack", + "config_name": "Sample Slack Channel", + "email_recipient_status": [], + "delivery_status": { + "status_code": "200", + "status_text": "ok" + } + } + ] +} +``` + +If delivery fails, the request returns the error status of the channel. A muted channel returns `423`. + +### Response body fields + +The response contains the same fields as the [Send test notification](#send-test-notification) response. + +### Permissions + +If you use the Security plugin, the caller needs the `cluster:admin/opensearch/notifications/channel/send` permission, which is granted by the `notifications_send_access` and `notifications_full_access` roles. The caller must also have access to the channel: + +- When [resource sharing]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/notification-access-control/) is enabled, the channel must be shared with the caller at an access level that includes `cluster:admin/opensearch/notifications/channel/send`, such as `notifications_read_write` or `notifications_full_access`. For an email channel, the caller also needs the same access to the channel's sender account and recipient groups. If it does not, the request is rejected with `403`. +- When filtering by backend roles is enabled, the caller's backend roles must match the channel's backend roles. + +If you don't use the Security plugin, any user that can reach the cluster can send messages through any channel. +{: .warning} diff --git a/_observing-your-data/notifications/index.md b/_observing-your-data/notifications/index.md index b352988c..74820dc6 100644 --- a/_observing-your-data/notifications/index.md +++ b/_observing-your-data/notifications/index.md @@ -1,70 +1,49 @@ --- layout: default title: Notifications -nav_order: 90 +nav_order: 140 has_children: true redirect_from: - /notifications-plugin/ - /notifications-plugin/index/ + - /observing-your-data/notifications/ --- # Notifications -The Notifications plugin provides a central location for all of your notifications from OpenSearch plugins. Using the plugin, you can configure which communication service you want to use and see relevant statistics and troubleshooting information. Currently, the Alerting and ISM plugins have integrated with the Notifications plugin. +Notifications provides a central location for configuring the channels that OpenSearch plugins, such as Alerting and Index State Management (ISM), use to send notifications. Supported channel types are Amazon Chime, Amazon Simple Notification Service (Amazon SNS), email through SMTP or Amazon Simple Email Service (Amazon SES), Slack, Microsoft Teams, and custom webhooks. -You can use either OpenSearch Dashboards or the REST API to configure notifications. Dashboards offers a more organized way of selecting a channel type and selecting which OpenSearch plugin sources you want to use, whereas the REST API lets you programmatically define your notification channels for better versioning and reuse later on. +## Configuring notifications -1. Use the Dashboards UI to first create a channel that receives notifications from other plugins. Supported communication channels include Amazon Chime, Amazon Simple Notification Service (Amazon SNS), Amazon Simple Email Service (Amazon SES), email through SMTP, Slack, Microsoft Teams, and custom webhooks. After you’ve configured your channel and plugin sources, send messages and start tracking your notifications from the Notifications plugin's dashboard. - -2. Use the Notifications REST API to configure all of your channel's settings. To use the API, you must have your notification's name, description, channel type, which OpenSearch plugins to use as sources, and other associated URLs or groups. +Use OpenSearch Dashboards or the REST API to configure notifications. Dashboards guides you through selecting a channel type and entering its settings. The REST API lets you define channels programmatically so that you can version and reuse them. For more information about the API, see [Notifications API]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/api/). ## Create a channel -In OpenSearch Dashboards, choose **Notifications**, **Channels**, and **Create channel**. +To create a channel in OpenSearch Dashboards, follow these steps: -1. In the **Name and description** section, specify a name and optional description for your channel. -2. In the **Configurations** section, select the channel type and enter the necessary information for each type. For more information about configuring a channel that uses Amazon SNS or email, refer to the sections below. If you want to use Amazon Chime or Slack, you need to specify the webhook URL. For more information about using webhooks, see the documentation for [Slack](https://api.slack.com/messaging/webhooks), [Microsoft Teams](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors), or [Amazon Chime](https://docs.aws.amazon.com/chime/latest/ug/webhooks.html). +1. On the top menu, go to **Management** > **Notifications**. +1. Select **Channels**, and then select **Create channel**. +1. In the **Name and description** section, enter a name and an optional description for the channel. +1. In the **Configurations** section, select the **Channel type** and enter the settings for that type. You cannot change the channel type after you create the channel. For Slack, Amazon Chime, and Microsoft Teams, enter the webhook URL. For more information about obtaining a webhook URL, see the documentation for [Slack](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/), [Microsoft Teams](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors), or [Amazon Chime](https://docs.aws.amazon.com/chime/latest/ug/webhooks.html). For other channel types, see the following sections. +1. (Optional) To verify the configuration, select **Send test message**. +1. Select **Create**. -If you want to use custom webhooks, you must specify more information: parameters and headers. For example, if your endpoint requires basic authentication, you might need to add a header with an authorization key and a value of `Basic <Base64-encoded-credential-string>`. You might also need to change `Content-Type` to whatever your webhook requires. Popular values are `application/json`, `application/xml`, and `text/plain`. +### Custom webhooks -This information is stored in plain text in the OpenSearch cluster. We will improve this design in the future, but for now, the encoded credentials (which are neither encrypted nor hashed) might be visible to other OpenSearch users. +For a custom webhook, in **Define endpoints by**, select **Webhook URL** to enter the full URL or **Custom attributes URL** to enter the type, host, port, and path separately. Then select the HTTP **Method** and add any **Query parameters** and **Webhook headers** that your endpoint requires. For example, if your endpoint requires basic authentication, add an `Authorization` header with a value of `Basic <Base64-encoded-credential-string>`. You might also need to set `Content-Type` to the value your webhook requires, such as `application/json`, `application/xml`, or `text/plain`. -1. In the **Availability** section, select the OpenSearch plugins you want to use with the notification channel. -2. Choose **Create**. +Webhook settings, including headers, are stored in plain text in the OpenSearch cluster. Encoded credentials in headers are neither encrypted nor hashed and might be visible to other OpenSearch users. +{: .warning} ### Amazon SNS as a channel type -OpenSearch supports Amazon SNS for notifications. This integration with Amazon SNS means that, in addition to the other channel types, the Notifications plugin can send email messages, text messages, and even run AWS Lambda functions using SNS topics. For more information about Amazon SNS, see the [Amazon Simple Notification Service Developer Guide](https://docs.aws.amazon.com/sns/latest/dg/welcome.html). +Notifications can publish messages to Amazon SNS topics. Through SNS topic subscriptions, you can deliver notifications as email messages or text messages or use them to invoke AWS Lambda functions. For more information about Amazon SNS, see the [Amazon Simple Notification Service Developer Guide](https://docs.aws.amazon.com/sns/latest/dg/welcome.html). -The Notifications plugin currently supports two ways to authenticate users: +To create an Amazon SNS channel, enter the **SNS topic ARN** and, optionally, the **IAM role ARN**. OpenSearch uses the AWS credentials available on each node through the default AWS credential provider chain, for example, environment variables or an Amazon EC2 instance profile. If you don't specify an IAM role ARN, these credentials must grant permission to publish to the topic. If you specify an IAM role ARN, OpenSearch uses these credentials to assume the role and then publishes to the topic using the role's permissions. -1. Provide the user with full access to Amazon SNS. -2. Let the user assume an AWS Identity and Access Management (IAM) role that has permissions to access Amazon SNS. Once you configure the notification channel to use the right Amazon SNS permissions, select the OpenSearch plugins that can trigger notifications. +#### Publishing using the node credentials -### Provide full Amazon SNS access permissions - -If you want to provide full Amazon SNS access to the IAM user, ensure that the user has the following permissions: - -```json -{ - "Version": "2012-10-17", - "Statement": [ - { - "Action": [ - "sns:*" - ], - "Effect": "Allow", - "Resource": "*" - } - ] -} -``` - -### Assuming an IAM role with Amazon SNS permissions - -If you want to let the user send notifications without directly having full permissions to Amazon SNS, let the user assume a role that does have the necessary permissions. - -The IAM user must have the following permissions to assume a role: +To publish to the topic using the node credentials, grant the IAM user or role whose credentials the nodes use the following permissions: ```json { @@ -72,69 +51,134 @@ The IAM user must have the following permissions to assume a role: "Statement": [ { "Effect": "Allow", - "Action": [ - "ec2:Describe*", - "iam:ListRoles", - "sts:AssumeRole" - ], - "Resource": "*" + "Action": "sns:Publish", + "Resource": "arn:aws:sns:<region>:<account_id>:<topic_name>" } ] } ``` -Then add this policy into the IAM user’s trust relationship to actually assume the role: +#### Publishing by assuming an IAM role + +To publish to the topic without granting the node credentials direct access to Amazon SNS, create an IAM role that has the `sns:Publish` permission shown in the preceding section, and enter its ARN in **IAM role ARN**. + +The IAM user or role whose credentials the nodes use must have permission to assume the role: ```json { "Version": "2012-10-17", "Statement": [ - { - "Effect": "Allow", - "Principal": { - "AWS": "arn:aws:iam::<arn_number>:user/<iam_username>", - }, - "Action": "sts:AssumeRole" - } + { + "Effect": "Allow", + "Action": "sts:AssumeRole", + "Resource": "arn:aws:iam::<account_id>:role/<role_name>" + } ] } ``` -### Host deny list +The role's trust policy must allow that user or role to assume it. In `Principal`, specify the ARN of the IAM user (`arn:aws:iam::<account_id>:user/<user_name>`) or role (`arn:aws:iam::<account_id>:role/<role_name>`) whose credentials the nodes use: -Define IP ranges or hostnames where OpenSearch nodes should not initiate requests. +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "AWS": "<node_principal_arn>" + }, + "Action": "sts:AssumeRole" + } + ] +} +``` ## Email as a channel type -To send or receive notifications with email, choose **Email** as the channel type. Next, select at least one sender and default recipient. To send notifications to more than a few people at a time, specify multiple email addresses or select a recipient group. If the Notifications plugin doesn’t currently have the necessary senders or groups, you can add them by first selecting **SMTP sender** and then choosing **Create SMTP sender** or **Create recipient group**. Choose **SES sender** to use Amazon Simple Email Service (Amazon SES). +To send notifications by email, select **Email** as the channel type. Then select a **Sender type**, a sender, and at least one default recipient. A channel uses one sender, either an **SMTP sender** or an **SES sender** that sends email through Amazon SES. In **Default recipients**, enter email addresses or select a recipient group to send notifications to multiple people. If the sender or recipient group doesn't exist yet, select **Create SMTP sender**, **Create SES sender**, or **Create recipient group** to create one. + +You can also manage senders and recipient groups on the **Email senders** and **Email recipient groups** pages in Notifications. ### Create email sender -1. Specify a unique name to associate with the sender. -2. Enter an email address and, if applicable, its host (for example, smtp.gmail.com) and the port. If you're using Amazon SES, enter the IAM role Amazon Resource Name (ARN) of the AWS account to send notifications from, along with the AWS Region. -3. Choose an encryption method. Most email providers require Secure Sockets Layer (SSL) or Transport Layer Security (TLS), which require a user name and password in the OpenSearch keystore. See [Authenticate sender account](#authenticate-sender-account) to learn more. Selecting an encryption method is only applicable if you're creating an SMTP sender. -4. Choose **Create** to save the configuration and create the sender. You can create a sender before you add your credentials to the OpenSearch keystore; however, you must [authenticate each sender account](#authenticate-sender-account) before you use the sender in your channel configuration. +To create an email sender, follow these steps: + +1. Enter a **Sender name**. The name must contain 2 to 50 characters. Valid characters are lowercase letters, digits, hyphens (`-`), and underscores (`_`). For SMTP senders, this name is also part of the keystore setting names described in [Authenticate sender account](#authenticate-sender-account). +1. Enter the sender's **Email address**. +1. For an SMTP sender, enter the **Host** (for example, `smtp.gmail.com`) and **Port**, and then select an **Encryption method**: **SSL/TLS**, **STARTTLS**, or **None**. Most email providers require SSL/TLS or STARTTLS. To use either one, you must add the sender's user name and password to the OpenSearch keystore. For more information, see [Authenticate sender account](#authenticate-sender-account). +1. For an SES sender, enter the **IAM Role ARN** of the role that OpenSearch assumes to send email and the **AWS region**. +1. Select **Create**. + +You can create an SMTP sender before you add its credentials to the OpenSearch keystore. However, you must [authenticate the sender account](#authenticate-sender-account) before a channel can send email through it. + +An SES sender's email address must be a verified identity in Amazon SES in the sender's AWS Region. If your account is in the Amazon SES sandbox, recipient addresses must also be verified. OpenSearch sends email using the `ses:SendRawEmail` action. The IAM role that you specify in **IAM Role ARN** must have the following permission, and its trust policy must allow the node credentials to assume it, as described in [Publishing by assuming an IAM role](#publishing-by-assuming-an-iam-role): + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "ses:SendRawEmail", + "Resource": "arn:aws:ses:<region>:<account_id>:identity/<sender_email_address>" + } + ] +} +``` ### Create email recipient group -1. After choosing **Create recipient group**, enter a unique name to associate with the email group and an optional description. -2. Select or enter the email addresses you want to add to the recipient group. -3. Choose **Create**. +To create an email recipient group, follow these steps: + +1. Select **Create recipient group**. +1. Enter a unique **Name** for the group and an optional description. +1. In **Emails**, select or enter the email addresses that you want to add to the group. +1. Select **Create**. ### Authenticate sender account -If your email provider requires SSL or TLS, you must authenticate each sender account before you can send an email. Enter the sender account credentials in the OpenSearch keystore using the command line interface (CLI). Run the following commands (in your OpenSearch directory) to enter your user name and password. The <sender_name> is the name you entered for **Sender** earlier. +If an SMTP sender uses the SSL/TLS or STARTTLS encryption method, you must add the sender account's credentials to the OpenSearch keystore before the sender can send email. OpenSearch does not use keystore credentials for senders whose encryption method is None. -```json -/usr/share/opensearch/bin/opensearch-keystore add opensearch.notifications.core.email.<sender_name>.username -/usr/share/opensearch/bin/opensearch-keystore add opensearch.notifications.core.email.<sender_name>.password +On every node, run the following commands from the OpenSearch home directory, replacing `<sender_name>` with the sender name that you entered when creating the sender. Each command prompts you for the value: + +```bash +./bin/opensearch-keystore add opensearch.notifications.core.email.<sender_name>.username +./bin/opensearch-keystore add opensearch.notifications.core.email.<sender_name>.password ``` -To change or update your credentials (after you’ve added them to the keystore on every node), call the reload API to automatically update those credentials without restarting OpenSearch. +To apply new or updated credentials without restarting OpenSearch, call the Nodes Reload Secure Settings API after you update the keystore on every node: + +```json +POST _nodes/reload_secure_settings +``` +{% include copy-curl.html %} + +If your keystore is password protected, provide the password in the request body: ```json POST _nodes/reload_secure_settings { - "secure_settings_password": "1234" + "secure_settings_password": "<keystore_password>" } ``` + +For more information, see [Nodes Reload Secure Settings API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-reload-secure/). + +## Host deny list + +To prevent OpenSearch nodes from sending notifications to specific hosts, add the hosts to the `opensearch.notifications.core.http.host_deny_list` setting. The deny list applies to channels that send HTTP requests: Slack, Amazon Chime, Microsoft Teams, and custom webhooks. Each entry can be a hostname, an IP address, or an IP address range in CIDR notation. OpenSearch rejects a message if the destination hostname matches an entry or if any IP address that the hostname resolves to falls within an entry. The setting is dynamic and is empty by default. + +The following request adds an IP address range and a hostname to the deny list: + +```json +PUT _cluster/settings +{ + "persistent": { + "opensearch.notifications.core.http.host_deny_list": ["10.0.0.0/8", "internal.example.com"] + } +} +``` +{% include copy-curl.html %} + +For more information about Notifications plugin settings, see [Notifications plugin settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/plugin-settings/#notifications-plugin-settings). diff --git a/_observing-your-data/notifications/notification-access-control.md b/_observing-your-data/notifications/notification-access-control.md new file mode 100644 index 00000000..8dd8ba1a --- /dev/null +++ b/_observing-your-data/notifications/notification-access-control.md @@ -0,0 +1,147 @@ +--- +layout: default +title: Notification access control +nav_order: 30 +parent: Notifications +has_children: false +--- + +# Notification access control + +Notifications integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for notification configurations. A notification configuration is the underlying document for a channel, so sharing a configuration controls access to the corresponding channel. Resource sharing replaces the legacy `opensearch.notifications.general.filter_by_backend_roles` setting and lets resource owners grant specific access levels to users, roles, or backend roles. + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +The following table describes the notification configuration resource. + +| Field | Value | +| :--- | :--- | +| Resource type | `notification_config` | +| System index | `.opensearch-notifications-config` | +| Onboarded version | OpenSearch 3.9 | + +When resource-level authorization is enabled, each notification configuration's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. When a user lists notification configurations or channels, the response contains only the configurations that the user owns or that are shared with the user. + +## Enable notification resource sharing + +To enable resource sharing for notifications, add the notification configuration resource type to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators who have permission to update cluster settings. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for notifications: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "notification_config" +``` +{% include copy.html %} + +Settings added to `opensearch.yml` take effect after a cluster restart. + +### Configuration using the Cluster Settings API + +To enable resource sharing without restarting the cluster, use the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["notification_config"] + } +} +``` +{% include copy-curl.html %} + +The `plugins.security.system_indices.enabled` setting cannot be updated using the Cluster Settings API, so set it in `opensearch.yml`. + +When adding the notification configuration resource type to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Notification access levels + +Notifications provides three predefined access levels for notification configuration documents. Each access level determines the operations that a user can perform on a notification configuration shared with them. + +### notifications_read_only + +The `notifications_read_only` read-only access level grants users the ability to view shared notification configurations and channels but not modify them. This access level includes the following permissions: + +```yaml +- 'cluster:admin/opensearch/notifications/configs/get' +- 'cluster:admin/opensearch/notifications/channels/get' +- 'cluster:admin/opensearch/notifications/features' +``` +{% include copy.html %} + +### notifications_read_write + +The `notifications_read_write` read-write access level grants users full access to notification configuration operations except for sharing capabilities. This access level includes all read permissions plus write and send operations: + +```yaml +- 'cluster:admin/opensearch/notifications/configs/*' +- 'cluster:admin/opensearch/notifications/channels/get' +- 'cluster:admin/opensearch/notifications/features' +- 'cluster:admin/opensearch/notifications/feature/send' +- 'cluster:admin/opensearch/notifications/test_notification' +``` +{% include copy.html %} + +### notifications_full_access + +The `notifications_full_access` full access level grants users complete control over a notification configuration, including owner-like permissions such as sharing the resource with other users. This access level includes all notification operations plus resource sharing permissions: + +```yaml +- 'cluster:admin/opensearch/notifications/configs/*' +- 'cluster:admin/opensearch/notifications/channels/get' +- 'cluster:admin/opensearch/notifications/features' +- 'cluster:admin/opensearch/notifications/feature/send' +- 'cluster:admin/opensearch/notifications/test_notification' +- 'cluster:admin/security/resource/share' +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Notifications GitHub repository](https://github.com/opensearch-project/notifications/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking the notification configuration resource type as protected, cluster administrators must run the migration API to transfer existing notification sharing information from the legacy framework to the new resource sharing system. Until you run the migration, existing notification configurations have no sharing record, so they are inaccessible to all users, including the users who created them. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Notification configuration documents track their authorized backend roles under `metadata.access` and do not store a per-user owner. Set `backend_roles_path` to `/metadata/access`. The `username_path` parameter is required and cannot be empty, so point it to a field that notification documents do not contain, such as `/metadata/owner`. The path resolves to no value, so ownership falls back to `default_owner`. + +Use the following API call to migrate legacy notification sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opensearch-notifications-config", + "username_path": "/metadata/owner", + "backend_roles_path": "/metadata/access", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "notification_config": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Replace `<replace-with-existing-user>` with the username of an existing user who should own notification configurations. Because notification documents do not carry an owner name, every migrated configuration is attributed to this user. Replace `<select-appropriate-access-level>` with one of the available notification access levels: `notifications_read_only`, `notifications_read_write`, or `notifications_full_access`. The migration shares each configuration with the backend roles stored in its `metadata.access` field at this access level. If you omit `default_access_level`, the migration uses `notifications_read_only`. Configurations that have no backend roles are migrated without sharing, so only the default owner can access them. + +## Related documentation + +The following pages provide more information about resource sharing: + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) diff --git a/_observing-your-data/observability-security.md b/_observing-your-data/observability-security.md index 55a93559..916e595e 100644 --- a/_observing-your-data/observability-security.md +++ b/_observing-your-data/observability-security.md @@ -1,7 +1,7 @@ --- layout: default title: Observability security -nav_order: 5 +nav_order: 160 has_children: false redirect_from: - /observing-your-data/security/ @@ -33,7 +33,7 @@ PUT _plugins/_security/api/roles/observability_full_access } ``` -If these roles don't meet your needs, mix and match individual Observability [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/) to suit your use case. For example, the `cluster:admin/opensearch/observability/create` permission lets you create Observability objects (visualizations, operational panels, notebooks, etc.). +If these roles don't meet your needs, mix and match individual Observability [permissions]({{site.url}}{{site.baseurl}}/security/access-control/permissions/) to suit your use case. For example, the `cluster:admin/opensearch/observability/create` permission lets you create Observability objects (visualizations, operational panels, and notebooks). The following is an example role that provides access to Observability: diff --git a/_observing-your-data/operational-panels.md b/_observing-your-data/operational-panels.md index 8e669a7d..f1fd39a3 100644 --- a/_observing-your-data/operational-panels.md +++ b/_observing-your-data/operational-panels.md @@ -1,28 +1,42 @@ --- layout: default title: Operational panels -nav_order: 60 +parent: Classic observability apps +nav_order: 50 redirect_from: - - /observing-your-data/operational-panels/ - /observability-plugin/operational-panels/ --- # Operational panels -Operational panels in OpenSearch Dashboards are collections of visualizations generated using [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index) (PPL) queries. +Operational panels are dashboards that contain visualizations created using [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) (PPL) queries. You create the visualizations in [Event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics/), [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/), or [Application analytics]({{site.url}}{{site.baseurl}}/observing-your-data/app-analytics/) and then add them to a panel. In OpenSearch Dashboards, operational panels are called **Observability dashboards**. -## Get started with operational panels +Operational panels are a [classic observability app]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/). They are not available when multiple data sources or the new home page are enabled. -If you want to start using operational panels without adding any data, expand the **Action** menu, choose **Add samples**, and Dashboards adds a set of operational panels with saved visualizations for you to explore. +To view operational panels, on the top menu, go to **Observability** > **Dashboards**. To explore a set of sample panels and visualizations without adding your own data, select **Add samples**. -## Create an operational panel +## Creating an operational panel -To create an operational panel and add visualizations: +To create an operational panel, follow these steps: -1. From the **Add Visualization** dropdown menu, choose **Select Existing Visualization** or **Create New Visualization**, which takes you to the [event analytics]({{site.url}}{{site.baseurl}}/observing-your-data/event-analytics) explorer, where you can use PPL to create visualizations. -1. If you're adding already existing visualizations, choose a visualization from the dropdown menu. -1. Choose **Add**. +1. On the top menu, go to **Observability** > **Dashboards**. +1. Select **Create Dashboard**. +1. In **Name**, enter a name for the panel, and then select **Create**. -![Sample operational panel]({{site.url}}{{site.baseurl}}/images/operational-panel.png) +## Adding visualizations -To search for a particular visualization in your operation panels, use PPL queries to search for data you've already added to your panel. +To add a visualization to a panel, open the panel, select **Add visualization**, and then select one of the following options: + +- **Select existing visualization**: Select a saved visualization from the list, and then select **Add**. +- **Create new visualization**: Opens the Event analytics explorer. Enter a PPL query, select **Run**, and then select the **Visualizations** tab. To save the visualization to the panel, select **Save**, select the panel in **Custom operational dashboards/application**, enter a **Name**, and then select **Save**. + +Operational panels filter every visualization by time, so the index that a visualization queries must contain a field of the `date` type. If the index has no `date` field, the visualization is empty. +{: .note} + +## Filtering visualizations + +To filter all visualizations in a panel, enter a PPL `where` clause in the search bar at the top of the panel, for example, `where response = '404'`. To change the time range for all visualizations, use the time picker. Then select **Refresh**. + +## Managing panels + +To reload, rename, duplicate, or delete a panel, open the panel and select **Dashboard Actions**. To delete a panel, enter `delete` in the confirmation dialog. diff --git a/_observing-your-data/prometheusmetrics.md b/_observing-your-data/prometheusmetrics.md index 592d851a..667207ef 100644 --- a/_observing-your-data/prometheusmetrics.md +++ b/_observing-your-data/prometheusmetrics.md @@ -1,28 +1,42 @@ --- layout: default -title: Metrics analytics -nav_order: 40 -redirect_from: - - /observing-your-data/prometheusmetrics/ +title: Metric analytics +parent: Classic observability apps +nav_order: 30 --- -# Metrics analytics +# Metric analytics Introduced 2.4 {: .label .label-purple } -Starting with OpenSearch 2.4, you can ingest and visualize metric data from log data aggregated within OpenSearch, allowing you to analyze and correlate data across logs, traces, and metrics. Previously, you could ingest and visualize only logs and traces from your monitored environments. With this feature, you can observe your digital assets with more granularity, gain deeper insight into the health of your infrastructure, and better inform your root cause analysis. +You can ingest and visualize metric data stored directly in OpenSearch using the **Metrics** tool. This equips you with tools to analyze and correlate data across logs, traces, and metrics. -The following image shows the process of ingesting metrics from Prometheus and visualizing them in a dashboard. +Metric analytics is a [classic observability app]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/). To explore metrics in an Observability workspace, see [Metrics]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-metrics/). -![Prometheus and Metrics]({{site.url}}{{site.baseurl}}/images/metrics/metricsgif.gif) +Before the introduction of this feature, you could only ingest and visualize logs and traces from your monitored environments. With the **Metrics** tool, you can observe your digital assets with more granularity, gain deeper insight into the health of your infrastructure, and better inform your root cause analysis. -## Configuring a data source connection from Prometheus to OpenSearch +The **Metrics** tool offers federated visualization capabilities in addition to the following: -You can view metrics collected from Prometheus in OpenSearch Dashboards by first creating a connection from [Prometheus](https://prometheus.io/) to OpenSearch using the SQL plugin. + - An OpenSearch cluster containing an [OpenTelemetry (OTel)-compatible metrics index](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/schema/observability/metrics) with OTel-based signals. See [What is OpenTelemetry?](https://opentelemetry.io/docs/what-is-opentelemetry/) for an overview of OTel. + - An OpenSearch cluster containing a [Prometheus data source](https://github.com/opensearch-project/sql/blob/{{site.opensearch_major_minor_version}}/docs/dev/datasource-prometheus.md) connected to a Prometheus server. -To configure a connection to Prometheus, you can use the `_datasources` configuration API endpoint. +The following image displays the flow for retrieving metrics from Prometheus and displaying them on a visualization dashboard. -The following example request configures a Prometheus data source with no authentication: +![Prometheus data source]({{site.url}}{{site.baseurl}}/images/metrics/prom-metrics.png){: width="700" } + +The following image displays an observability dashboard that visualizes metric data from the OpenSearch index using OTel queries. + +![OTel data source]({{site.url}}{{site.baseurl}}/images/metrics/otel-metrics.png){: width="700" } + +--- + +## Configuring a Prometheus connection using the API + +OpenSearch doesn't ingest Prometheus metrics. Instead, the [SQL plugin](https://github.com/opensearch-project/sql) queries [Prometheus](https://prometheus.io/) directly each time you view or query the metrics. To connect OpenSearch to a Prometheus server, create a Prometheus data source using the `_datasources` API endpoint. The Prometheus URI must be reachable from the OpenSearch nodes. + +Before you create a data source, set the `plugins.query.datasources.encryption.masterkey` setting on all OpenSearch nodes. For more information, see [Prerequisites]({{site.url}}{{site.baseurl}}/dashboards/management/data-sources/#prerequisites). You can also create the connection in OpenSearch Dashboards. For more information, see [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/). + +The following example shows a request that configures a Prometheus data source without any authentication: ```json POST _plugins/_query/_datasources @@ -34,8 +48,9 @@ POST _plugins/_query/_datasources } } ``` +{% include copy-curl.html %} -The following example request configures a Prometheus data source with AWS SigV4 authentication: +The following example shows how to configure a Prometheus data source using AWS Signature Version 4 authentication: ```json POST _plugins/_query/_datasources @@ -46,53 +61,155 @@ POST _plugins/_query/_datasources "prometheus.uri" : "http://localhost:8080", "prometheus.auth.type" : "awssigv4", "prometheus.auth.region" : "us-east-1", - "prometheus.auth.access_key" : "{{accessKey}}" - "prometheus.auth.secret_key" : "{{secretKey}}" + "prometheus.auth.access_key" : "<access_key>", + "prometheus.auth.secret_key" : "<secret_key>" } } ``` +{% include copy-curl.html %} -After configuring the connection from Prometheus to OpenSearch, Prometheus metrics are displayed in Dashboards in the **Observability** > **Metrics analytics** window, as shown in the following image. +After configuring the connection, you can view Prometheus metrics in OpenSearch Dashboards by going to the **Observability** > **Metrics** page, as shown in the following image. -![Metrics UI example 1]({{site.url}}{{site.baseurl}}/images/metrics/metrics1.png) +![Prometheus metrics displayed on a dashboard]({{site.url}}{{site.baseurl}}/images/metrics/metrics1.png){: width="700" } -* For more information about authentication and authorization of data source APIs, see [data source documentation on GitHub](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/datasources.rst). -* For more information about the Prometheus connector, see the [Prometheus Connector](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/connectors/prometheus_connector.rst) GitHub page. +### Developer resources -## Creating visualizations based on metrics +See the following developer resources for sample code, articles, tutorials, and API references: -You can create visualizations based on Prometheus metrics and other metrics collected by your OpenSearch cluster. +* [Data source settings](https://github.com/opensearch-project/sql/blob/{{site.opensearch_major_minor_version}}/docs/user/ppl/admin/datasources.md), which contains information about authentication and authorization of data source APIs. +* [Prometheus Connector](https://github.com/opensearch-project/sql/blob/{{site.opensearch_major_minor_version}}/docs/user/ppl/admin/connectors/prometheus_connector.md), which contains configuration information. +* [Simple Schema for Observability](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/schema/observability), which contains information about the OTel schema and ingest pipeline. +* [OTel Metrics Source](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/otel-metrics-source), which contains information about the Data Prepper metrics pipeline and ingestion. -To create a visualization, do the following: +--- -1. In **Observability** > **Metrics analytics** > **Available Metrics**, select the metrics you would like to include in your visualization. -1. These visualizations can now be saved. -1. From the **Metrics analytics** window, select **Save**. -1. When prompted for a **Custom operational dashboards/application**, choose one of the available options. -1. Optionally, you can edit the predefined name values under the **Metric Name** fields to suit your needs. -1. Select **Save**. +## Experimenting with OpenTelemetry Metrics in the OpenSearch demo environment -The following image shows an example of the visualizations that are displayed in the **Observability** > **Metrics analytics** window. +The OpenSearch [`opentelemetry-demo` repository](https://github.com/opensearch-project/opentelemetry-demo) provides a practical demonstration of collecting, processing, and visualizing metric data through **OpenTelemetry Metrics** from OpenTelemetry and using the **Metrics** tool in OpenSearch Dashboards. -![Metrics UI example 2]({{site.url}}{{site.baseurl}}/images/metrics/metrics2.png) +### Visualizing OTel metrics in OpenSearch -## Defining PPL queries for use with Prometheus +To visualize OTel metric data in OpenSearch, follow these steps: -You can define [Piped Processing Language]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index) (PPL) queries against metrics collected by Prometheus. The following example shows a metric-selecting query with specific dimensions: +1. Install the [`opentelemetry-demo` repository](https://github.com/opensearch-project/opentelemetry-demo). See [Quick start](https://github.com/opensearch-project/opentelemetry-demo/blob/main/README.md#quick-start) for instructions. +2. Collect the OTel signals, including metric signals. See the [OTel Collector](https://opentelemetry.io/docs/collector/) guide for instructions. +3. Configure the OTel pipeline to emit metric signals. See the [OTel Collector Pipeline](https://github.com/opensearch-project/opentelemetry-demo/tree/main/src/otel-collector) guide for instructions. + +#### Example YAML config file + +```yaml + service: + extensions: [basicauth/client] + pipelines: + traces: + receivers: [otlp] + processors: [batch] + exporters: [otlp, debug, spanmetrics, otlp/traces, opensearch/traces] + metrics: + receivers: [otlp, spanmetrics] + processors: [filter/ottl, transform, batch] + exporters: [otlphttp/prometheus, otlp/metrics, debug] + logs: + receivers: [otlp] + processors: [batch] + exporters: [otlp/logs, opensearch/logs, debug] +``` +{% include copy.html %} + +4. Configure the [Data Prepper pipeline](https://github.com/opensearch-project/opentelemetry-demo/blob/main/src/dataprepper/README.md) to emit the collected metric signals into the OpenSearch metrics index. + +#### Example YAML config file + +```yaml + otel-metrics-pipeline: + workers: 8 + delay: 3000 + source: + otel_metrics_source: + health_check_service: true + ssl: false + buffer: + bounded_blocking: + buffer_size: 1024 # max number of records the buffer accepts + batch_size: 1024 # max number of records the buffer drains after each read + processor: + - otel_metrics: + calculate_histogram_buckets: true + calculate_exponential_histogram_buckets: true + exponential_histogram_max_allowed_scale: 10 + flatten_attributes: false + sink: + - opensearch: + hosts: ["https://opensearch-node1:9200"] + username: "admin" + password: "my_%New%_passW0rd!@#" + insecure: true + index_type: custom + template_file: "templates/ss4o_metrics.json" + index: ss4o_metrics-otel-%{yyyy.MM.dd} + bulk_size: 4 +``` +{% include copy.html %} + +5. Ingest metric data into OpenSearch. As the demo starts generating data, the metric signals will be added to the OpenSearch index that supports the OpenTelemetry Metrics schema format. +6. On the **Metrics** page, choose `Otel-Index` from the **Data sources** dropdown menu and `Simple Schema for Observability Index` from the **OTel index** dropdown menu. A visualization is displayed, as shown in the following image. + +![OTel metrics dashboard]({{site.url}}{{site.baseurl}}/images/metrics/otel-metrics.png){: width="700" } + +--- + +## Visualizing metrics in remote clusters +Introduced 2.14 +{: .label .label-purple } + +You can view metrics from remote OpenSearch clusters by using the **Metrics** tool. Select the database icon on the upper-right toolbar and choose a cluster from the **DATA SOURCES** dropdown menu, as shown in the following image. You can switch from a local cluster to a remote cluster. + +![Switching clusters using the Metrics analytics tool]({{site.url}}{{site.baseurl}}/images/metrics/remote-cluster-selection.png){: width="700" } + +You can also view metric visualizations from other sources alongside local metric visualizations. From the **DATA SOURCES** dropdown menu, choose the remote metric visualization to add it to the group of visualizations already shown on the dashboard. An example dashboard is shown in the following image. + +![Metrics dashboard]({{site.url}}{{site.baseurl}}/images/metrics/otel-metrics-remote-cluster-selection.png){: width="700" } + +To learn about multi-cluster support for data sources, see [Enable OpenSearch Dashboards to support multiple OpenSearch clusters](https://github.com/opensearch-project/OpenSearch-Dashboards/issues/1388). + +## Creating visualizations based on custom metrics + +You can create visualizations using the metric data collected by your OpenSearch cluster, including Prometheus metrics and custom metrics. + +To create these visualizations, follow these steps: + +1. On the top menu, go to **Observability** > **Metrics**. +2. In the **Metrics source** list, select **Prometheus** or **OpenTelemetry**. +3. In the **Available Metrics** list, select the metrics to add to your visualization. If you have more than one Prometheus connection, each connection's metrics are listed separately. The visualization title shows the connection and metric name, for example, `my_prometheus.go_goroutines`. +4. Select **Save as visualization**. +5. Optionally, edit the metric name and select the operational dashboards or applications to which to add the visualization. +6. Select **Save** to save your visualization. An example visualization is shown in the following image. + +![Metrics analytics dashboard with visualizations]({{site.url}}{{site.baseurl}}/images/metrics/metrics2.png){: width="700" } + +## Defining PPL queries for Prometheus metrics + +You can define [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/sql-and-ppl/ppl/index/) queries to interact with metrics collected by Prometheus. The following is an example PPL query for a Prometheus metric: ``` source = my_prometheus.prometheus_http_requests_total | stats avg(@value) by span(@timestamp,15s), handler, code ``` +{% include copy.html %} -Additionally, you can create a custom visualization by performing the following steps: +### Creating a custom visualization based on the PPL query -1. From the **Events Analytics** window, enter your PPL query and select **Refresh**. The **Explorer page** is now displayed. -1. From the **Explorer page**, select **Save**. -1. When prompted for a **Custom operational dashboards/application**, choose one of the available options. -1. Optionally, you can edit the predefined name values under the **Metric Name** fields to suit your needs. -1. Optionally, you can choose to save the visualization as a metric. -1. Select **Save**. +To create a custom visualization based on the PPL query, follow these steps: -Note: Only queries that include a time-series visualization and stats/span can be saved as a metric, as shown in the following image. +1. On the top menu, go to **Observability** > **Logs**, and then select **Event Explorer**. +2. Enter your PPL query and select **Run**. +3. Select the **Visualizations** tab, and then select **Save**. +4. Optionally, in the **Custom operational dashboards/application** list, select the dashboards or applications to which to add the visualization. Enter a **Name** for the visualization. To save the visualization as a metric, turn on **Save as Metric**. +5. Select **Save** to save your custom visualization. -![Metrics UI example 3]({{site.url}}{{site.baseurl}}/images/metrics/metrics3.png) +Only queries that include a time-series visualization and statistics or span information can be saved as a metric, as shown in the following image. + +![Saving queries as metrics]({{site.url}}{{site.baseurl}}/images/metrics/metrics3.png){: width="700" } + +## Related documentation + +- [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/) diff --git a/_observing-your-data/slo/index.md b/_observing-your-data/slo/index.md new file mode 100644 index 00000000..433327d7 --- /dev/null +++ b/_observing-your-data/slo/index.md @@ -0,0 +1,183 @@ +--- +layout: default +title: SLOs +parent: Application performance monitoring +grand_parent: Observability workspace apps +nav_order: 60 +has_children: false +redirect_from: + - /observing-your-data/slo/ +--- + +# Service-level objectives +**Introduced 3.7** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, join the discussion on the [OpenSearch forum](https://forum.opensearch.org/). +{: .warning} + +Service-level objectives (SLOs) let you define availability and latency targets for your services, deploy supporting recording and alerting rules to a Prometheus-compatible ruler, and track application health, error budgets, and budget consumption rates (burn rates) from a dedicated view in OpenSearch Dashboards. + +SLOs consolidate alerts from OpenSearch monitors and Prometheus alerting rules, so you can monitor service health across data sources without switching between tools. + +When you create an SLO, OpenSearch Dashboards generates Prometheus recording and alerting rules based on your configuration and deploys them to your Prometheus-compatible ruler. The rules track health, attainment, and remaining error budget for each objective. + +The following table defines the SLO and SLI terms. + +| Term | Definition | +| :--- | :--- | +| Service-level indicator (SLI) | A quantitative measurement of service performance, such as availability or latency. Supported SLI types are `availability`, `latency_threshold`, and `custom`. | +| Service-level objective (SLO) | A target attainment level for one or more SLIs, evaluated over a single time window. Each SLO contains one or more objectives. | +| Objective | A target value for an SLI, expressed as a decimal between `0.5` and `0.99999` (for example, `0.999`). Each objective generates its own set of recording and alerting rules. | +| Time window | The rolling period over which the SLO is evaluated (for example, `7d`, `28d`, `30d`). Calendar windows are not yet supported. | +| Error budget | The allowable fraction of failed events within the time window. When the error budget drops below zero, the objective is breached. | +| Burn rate | The rate at which the error budget is being consumed relative to the time window. Used to trigger alerts at different severity tiers. | +| SLO mode | Controls whether alerting is active. In `active` mode, both recording and alerting rules are deployed. In `shadow` mode, only recording rules are deployed, which is useful for validating an SLO before enabling alerts. | +| Data source | The `DirectQuery` Prometheus connection that the SLO uses. Each SLO is bound to a single data source. | +| Workspace | The OpenSearch Dashboards workspace that the SLO belongs to. Each workspace has its own set of SLOs and ruler namespace. | + +## Prerequisites + +Before using SLOs, complete the following setup steps. + +### Enabling the feature + +SLOs are disabled by default. To enable them, add the following settings to `opensearch_dashboards.yml`: + +```yaml +workspace.enabled: true +explore.enabled: true +explore.discoverTraces.enabled: true +observability.slo.enabled: true +``` +{% include copy.html %} + +Then restart OpenSearch Dashboards. + +### Observability workspace + +The SLO feature is available within an Observability [workspace]({{site.url}}{{site.baseurl}}/dashboards/workspace/). To create a workspace, follow these steps: + +1. Navigate to the OpenSearch Dashboards home page. +2. Select **Create workspace**. +3. Enter a workspace name. +4. Select the **Observability** use case. +5. Select **Create workspace**. + +### Prometheus-compatible ruler + +SLOs deploy recording and alerting rules to a Prometheus-compatible ruler (Cortex or Grafana Mimir) through the `DirectQuery` resource proxy. The ruler must support the following API endpoints: + +- `POST /api/v1/rules/{namespace}` -- Creates or updates a rule group. +- `DELETE /api/v1/rules/{namespace}/{groupName}` -- Deletes a rule group. + +Rule groups for a given workspace are written to the namespace `slo-generated-<workspace-id>`. Tenant identity (for example, `X-Scope-OrgID`) is configured in the [Prometheus connector]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/) settings. + +### Data source + +Each SLO is bound to a single data source, which must be a registered `DirectQuery` Prometheus connection. For information about configuring a Prometheus data source, see [Connecting Prometheus to OpenSearch]({{site.url}}{{site.baseurl}}/dashboards/management/connect-prometheus/). + +### Data prerequisites + +The SLI definition determines what data the ruler must be able to query: + +- **Availability and latency-threshold SLIs** require the named Prometheus counter or histogram metric to be present in the configured backend. Application Performance Monitoring (APM) service templates expect span-derived Rate, Error, Duration (RED) metrics produced by [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/). OpenTelemetry (OTel) semantic convention templates expect the corresponding HTTP, RPC, database client, messaging, or generative AI metrics. +- **Custom SLIs** require your PromQL expression to evaluate successfully against the backend. + +## Accessing SLOs + +To access SLOs, select your Observability workspace from the home page, or create one if you don't have one (see [Observability workspace](#observability-workspace)). Then, in the left navigation, select **Application performance** > **SLOs**. + + +## Creating an SLO + +To create an SLO, follow these steps: + +1. In the **SLOs** view, choose **Create SLO**. +2. Select a template. Templates are grouped into the following categories: + - **APM service SLOs**: SLIs based on RED metrics from [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/). Templates include **APM service availability**, **APM service latency**, **APM dependency availability**, and **APM dependency latency**. + - **OTel semantic convention metrics**: SLIs based on standard OTel metrics. Templates include **HTTP availability**, **HTTP latency**, **RPC/gRPC availability**, **RPC/gRPC latency**, **Database client latency**, **Messaging processing latency**, and **GenAI invocation availability**. + - **Custom**: A blank **Custom PromQL** template for custom PromQL expressions. +3. Configure the SLO in the wizard. The wizard contains the following sections: + - **Identity**: A unique name, description, and data source (a registered DirectQuery Prometheus connection). + - **Window & mode**: A rolling window (for example, `28d`) and an optional shadow mode that deploys recording rules without alerting. + - **Service & owner**: The service name and owner team. + - **SLI**: For prebuilt templates, the SLI type and metric are preconfigured. You can optionally add dimensions (label filters) to narrow the query. For the **Custom PromQL** template, you provide your own PromQL expressions---either separate good-events and total-events queries, or a single pre-computed error-ratio query. + - **Probe SLI**: Tests the proposed query against the Prometheus backend over a configurable look-back period (`1h`, `24h`, or `7d`) so you can verify the query returns data before creating the SLO. + - **Objectives**: One or more target values between `0.5` and `0.99999` (for example, `99.9%`). For latency SLIs, each objective also sets a latency bound. + - **Advanced**: Burn rate alerting tiers, budget warnings, and supplemental alarms. + - **Exclusion windows**: Time periods during which the SLO ignores measurements (for example, maintenance windows or deploy freezes). + - **Labels & annotations**: Optional metadata that propagates to the generated rules. + - **Rule preview**: A read-only preview of the recording and alerting rules that will be deployed to the ruler. +4. Choose **Create SLO**. The rules are validated and deployed to the ruler. If the ruler rejects the rules, the error is displayed and the SLO is not saved. + +## Monitoring SLOs + +The **SLOs** listing displays each SLO with its current state, attainment percentage, remaining error budget, and a sparkline. + + +The following table describes the SLO states. + +| State | Description | +| :--- | :--- | +| `ok` | All objectives are above target. | +| `warning` | At least one objective is consuming budget faster than expected. | +| `breached` | At least one objective has exhausted its error budget. | +| `no_data` | The SLI query returned no data in the evaluation window. | +| `stale` | The latest data sample is older than expected, which may indicate a problem with the data source connection. | +| `disabled` | The SLO has been disabled. | +| `rules_missing` | The expected recording rules are not present on the ruler. | + +To view details for a specific SLO, select it in the listing. The detail page shows per-objective attainment, remaining error budget, budget consumption rate, and the deployed recording and alerting rules. + +## Editing an SLO + +To update an SLO, select the SLO in the list and choose **Edit**. Only the fields you change are updated. After a successful update, the rule group is regenerated and redeployed to the ruler. + +You can also change the SLO mode without editing the full configuration: + +- **Disable**: Removes the rule group from the ruler and stops alerting. +- **Enable**: Redeploys the rule group and resumes status computation. +- **Shadow mode**: Keeps recording rules in place but stops alerting. Use this to validate a new SLO before enabling alerts. + +## Deleting an SLO + +To delete an SLO, select it from the listing and choose **Delete** from the detail page or the row actions menu. The associated rule group is removed from the ruler and the SLO configuration is deleted. + +If the SLO shares recording rules with other SLOs (when rule deduplication is enabled), only the reference is released. The shared rules are removed automatically after the grace window (24 hours by default). + +## Configuration settings + +The following table lists the SLO configuration settings. + +| Setting | Default | Description | +| :--- | :--- | :--- | +| `observability.slo.enabled` | `false` | Enables SLOs. Requires an OpenSearch Dashboards restart. | +| `observability.slo.ruleDedup.enabled` | `true` | Allows multiple SLOs that use the same query to share a single set of recording rules on the ruler, reducing duplicate evaluations. | +| `observability.slo.reconciler.enabled` | `true` | Enables automatic cleanup of shared recording rules that are no longer referenced by any SLO. | +| `observability.slo.reconciler.intervalMs` | `300000` (5 minutes) | How often the cleanup process runs, in milliseconds. | +| `observability.slo.reconciler.graceMs` | `86400000` (24 hours) | The amount of time to wait after all references to a shared rule are removed before deleting the rule from the ruler, in milliseconds. | + +## Troubleshooting + +The following table describes common issues and their solutions. + +| Problem | Solution | +| :--- | :--- | +| The ruler returns an error when creating or updating an SLO. | The error details are displayed in the wizard. Correct the underlying issue (for example, an authentication failure or malformed PromQL) and resubmit. | +| An SLO shows `rules_missing` or `no_data`. | Use the **Rule health** action on the detail page to check the ruler and the SLI query. Use **Repair** to redeploy missing rule groups. | + +## Limitations + +SLOs have the following limitations: + +- Only Prometheus data sources are supported for SLI evaluation. +- Only single SLIs are supported. Composite SLOs that combine multiple SLOs are not yet available. +- Only rolling time windows are supported. Calendar windows (`week`, `month`, `quarter`) are not yet available. +- Only the multi-window, multi-burn-rate (MWMBR) alerting strategy is supported. +- Exclusion windows can be configured but are not yet evaluated. + +## Related documentation + +- [Application Performance Monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/apm/) +- [Alerting]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/) diff --git a/_observing-your-data/ss4o.md b/_observing-your-data/ss4o.md index 92fc239e..5391c81b 100644 --- a/_observing-your-data/ss4o.md +++ b/_observing-your-data/ss4o.md @@ -1,9 +1,9 @@ --- layout: default title: Simple Schema for Observability -nav_order: 120 +nav_order: 170 redirect_from: -- /observing-your-data/ssfo/ +- /observing-your-data/ssfo/ --- # Simple Schema for Observability @@ -14,9 +14,6 @@ Introduced 2.6 The Simple Schema for Observability is inspired by both [OpenTelemetry](https://opentelemetry.io/docs/) and the Elastic Common Schema (ECS) and uses Amazon Elastic Container Service ([Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html)) event logs and OpenTelemetry (OTel) metadata. -Alerts will be supported in a future release. -{: .note } - ## Use cases Use cases for the Simple Schema for Observability include: @@ -25,12 +22,12 @@ Use cases for the Simple Schema for Observability include: * Moving from proprietary configurations that are non-transferable to a consolidated, sharable observability solution that allows users to ingest and display an analysis of any type of telemetry data from any type of provider. * Conforming dashboards to the schema to align with the data structure so that you can design and organize the dashboard components and visualizations in a way that effectively represents your data. -Data Prepper conforms to the schema for metrics and will gradually support traces and logs. Data Prepper's [trace mapping]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) currently provides `service-map` data in a different way than `ss4o` traces. To make the trace mapping compatible with Observability, it will be integrated with the `ss4o` traces schema and will introduce `service-map` as an enriched field. +Data Prepper's [trace analytics pipelines]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) write spans and service map data to the `otel-v1-apm-span` and `otel-v1-apm-service-map` indexes, which do not use the `ss4o` index naming convention. To write metrics using the schema, use an index template that follows the `ss4o` metrics schema, as shown in the Data Prepper pipeline example in [Metric analytics]({{site.url}}{{site.baseurl}}/observing-your-data/prometheusmetrics/). {: .note } ## Traces and metrics -Schema definitions for traces and metrics are defined and supported by the Observability plugin. These schema definitions include: +Schema definitions for traces and metrics are defined and supported by Observability. These schema definitions include: - The index structure (mapping). - The [index naming conventions](https://github.com/opensearch-project/observability/issues/1405). diff --git a/_observing-your-data/trace/getting-started.md b/_observing-your-data/trace/getting-started.md index d1bffb70..abcfec11 100644 --- a/_observing-your-data/trace/getting-started.md +++ b/_observing-your-data/trace/getting-started.md @@ -1,84 +1,245 @@ --- layout: default -title: Getting Started -parent: Trace Analytics +title: Getting started +parent: Trace analytics +grand_parent: Classic observability apps nav_order: 1 redirect_from: - /observability-plugin/trace/get-started/ - /monitoring-plugins/trace/get-started/ --- -# Getting started with Trace Analytics +# Getting started with trace analytics -OpenSearch Trace Analytics consists of two components---Data Prepper and the Trace Analytics OpenSearch Dashboards plugin. The Data Prepper repository contains several [sample applications](https://github.com/opensearch-project/data-prepper/tree/main/examples) that you can use to get started. +Trace analytics uses [OpenSearch Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) to ingest trace data into OpenSearch and [Trace analytics in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/trace/ta-dashboards/) to visualize it. In this tutorial, you'll run a sample application that generates traces, send the traces to OpenSearch, and view them in OpenSearch Dashboards. + +If you already use Jaeger with OpenSearch as its storage backend, see [Analyzing Jaeger trace data]({{site.url}}{{site.baseurl}}/observing-your-data/trace/trace-analytics-jaeger/) instead. ## Basic flow of data +The following diagram shows how trace data flows from an application to OpenSearch. + ![Data flow diagram from a distributed application to OpenSearch]({{site.url}}{{site.baseurl}}/images/ta.svg) -1. Trace Analytics relies on you adding instrumentation to your application and generating trace data. The [OpenTelemetry documentation](https://opentelemetry.io/docs/) contains example applications for many programming languages that can help you get started, including Java, Python, Go, and JavaScript. +1. You instrument your application to generate trace data. The [OpenTelemetry documentation](https://opentelemetry.io/docs/) contains example applications for many programming languages, including Java, Python, Go, and JavaScript. +1. The [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) receives trace data from the application using the OpenTelemetry Protocol (OTLP) and sends it to Data Prepper. +1. Data Prepper processes the trace data and writes spans to the `otel-v1-apm-span-*` indexes and service relationships to the `otel-v1-apm-service-map` index. +1. Trace analytics in OpenSearch Dashboards displays the data as charts and tables that show service dependencies, latency, error rate, and throughput. - (In the [Jaeger HotROD](#jaeger-hotrod) example below, an extra component, the Jaeger agent, runs alongside the application and sends the data to the OpenTelemetry Collector, but the concept is similar.) +## Running the Jaeger HotROD example -1. The [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/getting-started/) receives data from the application and formats it into OpenTelemetry data. +The following example uses Docker Compose to run a single-node OpenSearch cluster, OpenSearch Dashboards, Data Prepper, the OpenTelemetry Collector, and the [Jaeger HotROD](https://github.com/jaegertracing/jaeger/tree/main/examples/hotrod) sample application, which simulates a ride-sharing service made up of several microservices. -1. [Data Prepper]({{site.url}}{{site.baseurl}}/clients/data-prepper/index/) processes the OpenTelemetry data, transforms it for use in OpenSearch, and indexes it on an OpenSearch cluster. +### Step 1: Set the admin password -1. The [Trace Analytics OpenSearch Dashboards plugin]({{site.url}}{{site.baseurl}}/observing-your-data/trace/ta-dashboards/) displays the data in near real-time as a series of charts and tables, with an emphasis on service architecture, latency, error rate, and throughput. - -## Jaeger HotROD - -One Trace Analytics sample application is the Jaeger HotROD demo, which mimics the flow of data through a distributed application. - -Download or clone the [Data Prepper repository](https://github.com/opensearch-project/data-prepper). Then navigate to `examples/jaeger-hotrod/` and open `docker-compose.yml` in a text editor. This file contains a container for each element from [Basic flow of data](#basic-flow-of-data): - -- A distributed application (`jaeger-hot-rod`) with the Jaeger agent (`jaeger-agent`) -- The [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/getting-started/) (`otel-collector`) -- Data Prepper (`data-prepper`) -- A single-node OpenSearch cluster (`opensearch`) -- OpenSearch Dashboards (`opensearch-dashboards`). - -Close the file and run `docker-compose up --build`. After the containers start, navigate to `http://localhost:8080` in a web browser. - -![HotROD web interface]({{site.url}}{{site.baseurl}}/images/hot-rod.png) - -Click one of the buttons in the web interface to send a request to the application. Each request starts a series of operations across the services that make up the application. From the console logs, you can see that these operations share the same `trace-id`, which lets you track all of the operations in the request as a single *trace*: - -``` -jaeger-hot-rod | http://0.0.0.0:8081/customer?customer=392 -jaeger-hot-rod | 2020-11-19T16:29:53.425Z INFO frontend/server.go:92 HTTP request received {"service": "frontend", "trace_id": "12091bd60f45ea2c", "span_id": "12091bd60f45ea2c", "method": "GET", "url": "/dispatch?customer=392&nonse=0.6509021735471818"} -jaeger-hot-rod | 2020-11-19T16:29:53.426Z INFO customer/client.go:54 Getting customer{"service": "frontend", "component": "customer_client", "trace_id": "12091bd60f45ea2c", "span_id": "12091bd60f45ea2c", "customer_id": "392"} -jaeger-hot-rod | 2020-11-19T16:29:53.430Z INFO customer/server.go:67 HTTP request received {"service": "customer", "trace_id": "12091bd60f45ea2c", "span_id": "252ff7d0e1ac533b", "method": "GET", "url": "/customer?customer=392"} -jaeger-hot-rod | 2020-11-19T16:29:53.430Z INFO customer/database.go:73 Loading customer{"service": "customer", "component": "mysql", "trace_id": "12091bd60f45ea2c", "span_id": "252ff7d0e1ac533b", "customer_id": "392"} -``` - -These operations also have a `span_id`. *Spans* are units of work from a single service. Each trace contains some number of spans. Shortly after the application starts processing the request, you can see the OpenTelemetry Collector starts exporting the spans: - -``` -otel-collector | 2020-11-19T16:29:53.781Z INFO loggingexporter/logging_exporter.go:296 TraceExporter {"#spans": 1} -otel-collector | 2020-11-19T16:29:53.787Z INFO loggingexporter/logging_exporter.go:296 TraceExporter {"#spans": 3} -``` - -Then Data Prepper processes the data from the OpenTelemetry Collector and indexes it: - -``` -data-prepper | 1031918 [service-map-pipeline-process-worker-2-thread-1] INFO com.amazon.dataprepper.pipeline.ProcessWorker – service-map-pipeline Worker: Processing 3 records from buffer -data-prepper | 1031923 [entry-pipeline-process-worker-1-thread-1] INFO com.amazon.dataprepper.pipeline.ProcessWorker – entry-pipeline Worker: Processing 1 records from buffer -``` - -Finally, you can see the OpenSearch node responding to the indexing request. - -``` -node-0.example.com | [2020-11-19T16:29:55,064][INFO ][o.e.c.m.MetadataMappingService] [9fb4fb37a516] [otel-v1-apm-span-000001/NGYbmVD9RmmqnxjfTzBQsQ] update_mapping [_doc] -node-0.example.com | [2020-11-19T16:29:55,267][INFO ][o.e.c.m.MetadataMappingService] [9fb4fb37a516] [otel-v1-apm-span-000001/NGYbmVD9RmmqnxjfTzBQsQ] update_mapping [_doc] -``` - -In a new terminal window, run the following command to see one of the raw documents in the OpenSearch cluster: +OpenSearch requires a custom password for the `admin` user. In an empty directory, create a file named `.env` containing the following line, replacing `<custom-admin-password>` with a strong password: ```bash -curl -X GET -u 'admin:<custom-admin-password>' -k 'https://localhost:9200/otel-v1-apm-span-000001/_search?pretty&size=1' +OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> ``` +{% include copy.html %} -Navigate to `http://localhost:5601` in a web browser and choose **Trace Analytics**. You can see the results of your single click in the Jaeger HotROD web interface: the number of traces per API and HTTP method, latency trends, a color-coded map of the service architecture, and a list of trace IDs that you can use to drill down on individual operations. +Docker Compose reads this file and passes the password to OpenSearch. For more information, see [Admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). -If you don't see your trace, adjust the timeframe in OpenSearch Dashboards. For more information on using the plugin, see [OpenSearch Dashboards plugin]({{site.url}}{{site.baseurl}}/observing-your-data/trace/ta-dashboards/). +### Step 2: Configure the OpenTelemetry Collector + +In the same directory, create a file named `otel-collector-config.yaml` containing the following configuration. The Collector receives OTLP data from HotROD and sends traces to Data Prepper: + +```yaml +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +processors: + batch: + +exporters: + otlp_grpc/data-prepper: + endpoint: data-prepper:21890 + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [otlp] + processors: [batch] + exporters: [otlp_grpc/data-prepper] +``` +{% include copy.html %} + +### Step 3: Configure the Data Prepper pipelines + +In the same directory, create a file named `pipelines.yaml` containing the following configuration, replacing both instances of `<custom-admin-password>` with the password that you set in Step 1. The `entry-pipeline` receives trace data and passes it to two pipelines: `raw-trace-pipeline` writes spans to OpenSearch, and `service-map-pipeline` writes the relationships between services. For more information, see [Trace analytics]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/). + +```yaml +entry-pipeline: + source: + otel_trace_source: + ssl: false + sink: + - pipeline: + name: raw-trace-pipeline + - pipeline: + name: service-map-pipeline + +raw-trace-pipeline: + source: + pipeline: + name: entry-pipeline + processor: + - otel_traces: + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true # The demo security configuration uses self-signed certificates + username: admin + password: <custom-admin-password> + index_type: trace-analytics-raw + +service-map-pipeline: + source: + pipeline: + name: entry-pipeline + processor: + - service_map: + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: <custom-admin-password> + index_type: trace-analytics-service-map +``` +{% include copy.html %} + +### Step 4: Create the Docker Compose file + +In the same directory, create a file named `docker-compose.yml` containing the following configuration: + +```yaml +services: + opensearch: + image: opensearchproject/opensearch:latest + environment: + - discovery.type=single-node + - bootstrap.memory_lock=true + - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" + - OPENSEARCH_INITIAL_ADMIN_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} + ulimits: + memlock: + soft: -1 + hard: -1 + nofile: + soft: 65536 + hard: 65536 + volumes: + - opensearch-data:/usr/share/opensearch/data + ports: + - "9200:9200" + healthcheck: # Data Prepper starts only after the cluster is available + test: ["CMD-SHELL", "curl -sk -u admin:$$OPENSEARCH_INITIAL_ADMIN_PASSWORD https://localhost:9200/_cluster/health | grep -qE '\"status\":\"(green|yellow)\"'"] + interval: 10s + timeout: 5s + retries: 30 + networks: + - opensearch-net + + opensearch-dashboards: + image: opensearchproject/opensearch-dashboards:latest + ports: + - "5601:5601" + environment: + OPENSEARCH_HOSTS: '["https://opensearch:9200"]' + networks: + - opensearch-net + depends_on: + - opensearch + + data-prepper: + image: opensearchproject/data-prepper:latest + volumes: + - ./pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml:ro + networks: + - opensearch-net + depends_on: + opensearch: + condition: service_healthy + + otel-collector: + image: otel/opentelemetry-collector:latest + command: ["--config=/etc/otelcol/config.yaml"] + volumes: + - ./otel-collector-config.yaml:/etc/otelcol/config.yaml:ro + networks: + - opensearch-net + depends_on: + - data-prepper + + hotrod: + image: jaegertracing/example-hotrod:latest + command: ["all"] + environment: + - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 + ports: + - "8080:8080" + networks: + - opensearch-net + depends_on: + - otel-collector + +volumes: + opensearch-data: + +networks: + opensearch-net: +``` +{% include copy.html %} + +### Step 5: Start the containers + +To start the containers, run the following command: + +```bash +docker compose up -d +``` +{% include copy.html %} + +Data Prepper starts after the OpenSearch cluster reports a `green` or `yellow` health status, which can take a minute or longer. To confirm that Data Prepper is ready to receive trace data, run the following command until the output contains a line similar to `Started otel_trace_source on port 21890`: + +```bash +docker compose logs data-prepper | grep "Started otel_trace_source" +``` +{% include copy.html %} + +### Step 6: Generate trace data + +To open the HotROD sample application, go to [http://localhost:8080](http://localhost:8080). Each time you select a customer, HotROD sends a request through its services and generates a trace. Some requests fail intentionally, so the error views in trace analytics display data. + +Select several customers. Data Prepper writes spans after it receives the complete trace, so the data can take up to three minutes to appear. To verify that OpenSearch contains the trace data, run the following command: + +```bash +curl -sk -u admin:<custom-admin-password> "https://localhost:9200/_cat/indices/otel-v1-apm-*?v" +``` +{% include copy.html %} + +The response lists the `otel-v1-apm-span-000001` and `otel-v1-apm-service-map` indexes. The `docs.count` column shows a nonzero number of documents for each index. + +### Step 7: View trace data in OpenSearch Dashboards + +Go to [http://localhost:5601](http://localhost:5601) and log in as the `admin` user with the password that you set in Step 1. On the top menu, go to **Observability** > **Traces**. Make sure that **Data Prepper** is selected as the data source. + +The **Traces** page lists the spans and traces from HotROD, and the **Services** page shows each service and a map of the dependencies between them. If you don't see any data, use the time picker to select a time range that includes the time at which you generated the traces. For more information, see [Trace analytics in OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/observing-your-data/trace/ta-dashboards/). + +### Step 8: Clean up + +To stop the containers and delete their data, run the following command: + +```bash +docker compose down -v +``` +{% include copy.html %} diff --git a/_observing-your-data/trace/index.md b/_observing-your-data/trace/index.md index e6077a00..a9970828 100644 --- a/_observing-your-data/trace/index.md +++ b/_observing-your-data/trace/index.md @@ -1,26 +1,32 @@ --- layout: default -title: Trace Analytics -nav_order: 40 +title: Trace analytics +parent: Classic observability apps +nav_order: 20 has_children: true has_toc: false redirect_from: - /observability-plugin/trace/index/ - /monitoring-plugins/trace/index/ + - /observing-your-data/trace/ --- -# Trace Analytics +# Trace analytics -Trace Analytics provides a way to ingest and visualize [OpenTelemetry](https://opentelemetry.io/) data in OpenSearch. This data can help you find and fix performance problems in distributed applications. +Trace analytics provides a way to ingest and visualize [OpenTelemetry](https://opentelemetry.io/) data in OpenSearch. This data can help you find and fix performance problems in distributed applications. + +Trace analytics is a [classic observability app]({{site.url}}{{site.baseurl}}/observing-your-data/classic-observability-apps/). In an Observability workspace, Trace analytics is not available when both APM and Discover Traces are enabled. To analyze traces in an Observability workspace, see [Traces]({{site.url}}{{site.baseurl}}/observing-your-data/exploring-observability-data/discover-traces/) and [Application performance monitoring]({{site.url}}{{site.baseurl}}/observing-your-data/apm/index/). A single operation, such as a user choosing a button, can trigger an extended series of events. The frontend might call a backend service, which calls another service, which queries a database, processes the data, and sends it to the original service, which sends a confirmation to the frontend. -Trace Analytics can help you visualize this flow of events and identify performance problems, as shown in the following image. +Trace analytics can help you visualize this flow of events and identify performance problems, as shown in the following image. ![Detailed trace view]({{site.url}}{{site.baseurl}}/images/ta-trace.png) -## Trace Analytics with Jaeger data +Trace analytics analyzes traces from your applications. OpenSearch can also generate traces for the requests that it processes. For more information, see [Distributed tracing]({{site.url}}{{site.baseurl}}/tuning-your-cluster/monitoring/telemetry/distributed-tracing/). -Trace Analytics supports Jaeger trace data in the OpenSearch Observability plugin. If you use OpenSearch as the backend for Jaeger trace data, you can use the built-in Trace Analytics capabilities. +## Trace analytics with Jaeger data -To set up your environment to use Trace Analytics, see [Analyze Jaeger trace data]({{site.url}}{{site.baseurl}}/observability-plugin/trace/trace-analytics-jaeger/). +Trace analytics supports Jaeger trace data. If you use OpenSearch as the backend for Jaeger trace data, you can use the built-in Trace analytics capabilities. + +To set up your environment to use Trace analytics, see [Analyzing Jaeger trace data]({{site.url}}{{site.baseurl}}/observing-your-data/trace/trace-analytics-jaeger/). diff --git a/_observing-your-data/trace/ta-dashboards.md b/_observing-your-data/trace/ta-dashboards.md index 3186093b..9974ba3b 100644 --- a/_observing-your-data/trace/ta-dashboards.md +++ b/_observing-your-data/trace/ta-dashboards.md @@ -1,25 +1,215 @@ --- layout: default -title: OpenSearch Dashboards plugin -parent: Trace Analytics +title: Trace analytics in OpenSearch Dashboards +parent: Trace analytics +grand_parent: Classic observability apps nav_order: 50 redirect_from: - /observability-plugin/trace/ta-dashboards/ - /monitoring-plugins/trace/ta-dashboards/ --- -# Trace Analytics OpenSearch Dashboards plugin +# Trace analytics in OpenSearch Dashboards -The Trace Analytics plugin for OpenSearch Dashboards provides at-a-glance visibility into your application performance, along with the ability to drill down on individual traces. For installation instructions, see [Standalone OpenSearch Dashboards plugin install]({{site.url}}{{site.baseurl}}/install-and-configure/install-dashboards/plugins/). +Trace analytics offers at-a-glance visibility into application performance based on [OpenTelemetry (OTel)](https://opentelemetry.io/) protocol data that standardizes instrumentation for collecting telemetry data from cloud-native software. -The **Dashboard** view groups traces together by HTTP method and path so that you can see the average latency, error rate, and trends associated with a particular operation. For a more focused view, try filtering by trace group name. +## Setting up the OpenTelemetry demo -![Dashboard view]({{site.url}}{{site.baseurl}}/images/ta-dashboard.png) +The [OpenTelemetry Demo with OpenSearch](https://github.com/opensearch-project/opentelemetry-demo) simulates a distributed application generating real-time telemetry data, providing you with a practical environment in which to explore features available in Trace analytics before implementing it in your environment. -To drill down on the traces that make up a trace group, choose the number of traces in the column on the right. Then choose an individual trace for a detailed summary. +### Step 1: Set up the OpenTelemetry Demo -![Detailed trace view]({{site.url}}{{site.baseurl}}/images/ta-trace.png) +- Clone the [OpenTelemetry Demo with OpenSearch](https://github.com/opensearch-project/opentelemetry-demo) repository: `git clone https://github.com/opensearch-project/opentelemetry-demo`. +- Follow the [Getting Started](https://github.com/opensearch-project/opentelemetry-demo/tree/main?tab=readme-ov-file#running-this-demo) instructions to deploy the demo application using Docker, which runs multiple microservices generating telemetry data. + +### Step 2: Ingest telemetry data + +- Configure the OTel collectors to send telemetry data (traces, metrics, logs) to your OpenSearch cluster, using the [preexisting setup](https://github.com/opensearch-project/opentelemetry-demo/tree/main/src/otel-collector). +- Confirm that [Data Prepper](https://github.com/opensearch-project/opentelemetry-demo/tree/main/src/dataprepper) is set up to process the incoming data, handle trace analytics and service map pipelines, submit data to required indexes, and perform preaggregated calculations. + +### Step 3: Explore trace analytics in OpenSearch Dashboards + +The **Trace Analytics** application includes two options: **Services** and **Traces**: + +- **Services** lists all services in the application and provides an interactive map that shows how the various services connect to each other. In contrast to the dashboard (which helps identify problems by operation), the **Service map** helps you identify problems by service based on error rates and latency. To access this option, go to **Trace Analytics** > **Services**. +- **Traces** groups traces together by HTTP method and path so that you can see the average latency, error rate, and trends associated with a particular operation. For a more focused view, try filtering by trace group name. To access this option, go to **Trace Analytics** > **Traces**. From the **Trace Groups** panel, you can review the traces in a trace group. From the **Traces** panel you can analyze individual traces to get a detailed summary. + +### Step 4: Perform correlation analysis + +Select **Services correlation** to display relationships between telemetry signals. This feature helps you navigate from the logical service level to associated metrics and logs for a specific service. + +Trace analytics supports correlating spans, traces, and services with their corresponding logs. This lets you move directly from a trace or span to relevant log entries, or from a service to its correlated logs, within the Trace Analytics interface. Correlation streamlines troubleshooting by offering a unified view of telemetry data, making it easier to identify root causes and understand application context. + +Use the following options to perform correlation: + +- **Trace-to-log correlation**: On the trace details page, select **View associated logs**. +- **Span-to-log correlation**: In the span details flyout (opened by selecting a span ID in the Gantt chart or span table), select **View associated logs**. +- **Service-to-log correlation**: On the services page, select the **Discover** icon next to the desired service. +- **Service-to-service correlation**: On the services page, use the **Focus on** option in the service map to view a service and its dependencies. + +--- + +## Schema dependencies and assumptions + +Trace analytics requires you to use [Data Prepper]({{site.url}}{{site.baseurl}}/data-prepper/) to process and visualize OTel data and relies on the following Data Prepper pipelines for OTel correlations and service map calculations: + +- [Trace analytics pipeline]({{site.url}}{{site.baseurl}}/data-prepper/common-use-cases/trace-analytics/) +- [Service map pipeline]({{site.url}}{{site.baseurl}}/data-prepper/pipelines/configuration/processors/service-map/) + +### Standardized telemetry data + +Trace analytics requires telemetry data to follow the OTel schema conventions, including the structure and naming of spans, traces, and metrics as specified by OTel, and to be implemented using the [Simple Schema for Observability]({{site.url}}{{site.baseurl}}/observing-your-data/ss4o/). + +### Service names and dependency map + +For accurate service mapping and correlation analysis, adhere to the following guidelines: + +- Service names must be unique and used consistently across application components. +- The `serviceName` field must be populated using the Data Prepper pipeline. +- Services must be ingested with predefined upstream and downstream dependencies to construct accurate service maps and understand service relationships. + +### Trace and span IDs + +Traces and spans must have consistently generated and maintained unique identifiers across distributed systems to enable end-to-end tracing and accurate performance insights. + +### RED metrics adherence + +Trace analytics expects metric data to include rate, error, and duration (RED) indicators for each service, either preaggregated using the Data Prepper pipeline or calculated dynamically based on spans. This allows you to effectively compute and display key performance indicators. + +### Correlation fields + +Certain fields, such as `serviceName`, must be present to perform correlation analysis. These fields enable trace analytics to link related telemetry data and provide a holistic view of service interactions and dependencies. + +### Correlation indexes + +Navigating from the service dialog to its corresponding traces or logs requires the existence of correlating fields and that the target indexes (for example, logs) follow the specified naming conventions, as described at [Simple Schema for Observability]({{site.url}}{{site.baseurl}}/observing-your-data/ss4o/). + +--- + +## Trace analytics with OTel protocol analytics + +Introduced 2.15 +{: .label .label-purple } + +Trace analytics with OTel protocol analytics provide comprehensive insights into distributed systems. You can visualize and analyze the following assets: + +- [Service](https://opentelemetry.io/docs/specs/semconv/resource/#service): The components of a distributed application. These components are significant logical terms used to measure and monitor the application's building blocks in order to validate the system's health. +- [Traces](https://opentelemetry.io/docs/concepts/signals/traces/): A visual representation of a request's path across services into requests' journeys across services, offering insights into latency and performance issues. +- [RED metrics](https://opentelemetry.io/docs/specs/otel/metrics/api/): Metrics for service health and performance, measured as requests per second (rate), failed requests (errors), and request processing time (duration). + +### Trace analytics visualizations + +**Services** visualizations, such as a table or map, help you logically analyze service behavior and accuracy. The following visualizations can help you identify anomalies and errors: + +- **Services table** + + - A RED indicator, along with connected upstream and downstream services and other actions, is indicated in each table column. An example **Services** table is shown in the following image. + + ![Services table]({{site.url}}{{site.baseurl}}/images/trace-analytics/services-table.png) + + - General-purpose filter selection is used for field or filter composition. The following image shows this filter. + + ![Services filter selection]({{site.url}}{{site.baseurl}}/images/trace-analytics/services-filter-selection.png) + + - The **Services** throughput tooltip provides an at-a-glance overview of a service's incoming request trend for the past 24 hours. The following image shows an example tooltip. + + ![Services throughput tooltip ]({{site.url}}{{site.baseurl}}/images/trace-analytics/service-throughput-tooltip.png) + + - The **Services** correlation dialog window provides an at-a-glance overview of a service's details, including its 24-hour throughput trend. You can use these details to analyze correlated logs or traces by filtering based on the `serviceName` field. The following image shows this window. + + ![Services correlation dialog window]({{site.url}}{{site.baseurl}}/images/trace-analytics/single-service-correlation-dialog.png) + + - The **Services** RED metrics dialog window provides an at-a-glance overview of a service's RED metrics indicators, including 24-hour error, duration, and throughput rate. The following image shows this window. + + ![Services RED metrics for duration]({{site.url}}{{site.baseurl}}/images/trace-analytics/single-service-RED-metrics.png) + + - The **Span details** dialog window provides the details of a trace. You can use this information to further analyze a trace's elements, such as attributes and associated logs. The following image shows this window. + + ![Services Span details dialog window]({{site.url}}{{site.baseurl}}/images/trace-analytics/span-details-fly-out.png) + +- **Service map** + + - The **Service map** displays nodes, each representing a service. The node color indicates the RED indicator severity for that service and its dependencies. The following image shows a map. + + ![Services map tooltip]({{site.url}}{{site.baseurl}}/images/trace-analytics/service-details-tooltip.png) + + - You can select a node to open a detailed dialog window for its associated service. This interactive map visualizes service interconnections, helping identify problems by service, unlike dashboards that identify issues by operation. You can sort by error rate or latency to pinpoint potential problem areas. + + - In the **Service map** dialog window, nodes represent connected downstream services dependent on the selected service. The node color indicates the RED indicator severity for that service and its downstream dependencies. The following image shows this dialog window. + + ![Service map dialog window]({{site.url}}{{site.baseurl}}/images/trace-analytics/single-service-fly-out.png) + +- **Trace groups** + + - Traces are grouped by their HTTP API name, allowing clustering based on their business functional unit. Traces are grouped by HTTP method and path, displaying the average latency, error rate, and trends associated with a particular operation. You can filter by trace group name. The following image shows the **Trace Groups** window. + + ![Trace Groups window]({{site.url}}{{site.baseurl}}/images/trace-analytics/trace-group-RED-metrics.png) + + - In the **Trace Groups** window, you can filter by group name and other filters. You can also analyze associated traces. To drill down on the traces that comprise a group, select the number of traces in the right-hand column and then choose an individual trace to see a detailed summary. + + ![Trace group dialog window]({{site.url}}{{site.baseurl}}/images/ta-dashboard.png) + + - The **Trace details** window displays a breakdown of a single trace, including its corresponding spans, associated service names, and a waterfall chart of the spans' time and duration interactions. The following image shows this view. + + ![Trace details window]({{site.url}}{{site.baseurl}}/images/ta-trace.png) + +## Support for custom index names and cross-cluster indexes + +Introduced 3.1 +{: .label .label-purple } + +Trace Analytics in OpenSearch 3.1 includes expanded support for custom index names and cross-cluster indexes, offering greater flexibility and scalability for distributed environments. The following enhancements are now available: + +- You can configure custom index names for Observability span, service, and log indexes. This allows you to align index naming with your organization's conventions and manage data across multiple environments more effectively. You can also configure correlated log indexes and map their corresponding fields for `timestamp`, `serviceName`, `spanId`, and `traceId`. This feature is particularly useful if your logs do not follow the OpenTelemetry (OTel) format and require custom field mappings. Custom span indexes must follow Data Prepper span index mappings. + + The following image shows the custom index name configuration interface in the Observability settings panel. + + ![Custom index name configuration UI]({{site.url}}{{site.baseurl}}/images/ta-index-settings.png) + +- The **Trace details** page now includes an associated logs panel, which helps you analyze logs correlated with specific traces to improve troubleshooting and root cause analysis. The following image shows the logs panel. + + ![Trace detail page with associated logs panel]({{site.url}}{{site.baseurl}}/images/ta-trace-logs-correlation.png) + +- A new dropdown menu lets you view all spans, root spans, service entry spans, or traces. The custom data grid provides advanced sorting and display options, including a full-screen mode for easier data exploration, as shown in the following image. + + ![Drop-down menu and custom data grid in Trace Analytics]({{site.url}}{{site.baseurl}}/images/ta-span-kind.png) + +- The service map now appears under the traces table on the **Trace Analytics** page, providing immediate visual context for service relationships and dependencies as you analyze trace data. + + ![Service map displayed below traces table]({{site.url}}{{site.baseurl}}/images/ta-traces-page.png) + +- The **Trace details** page features a new tree view that displays a hierarchical breakdown of spans. The layout has been updated to position the pie chart next to the overview panel for a more intuitive summary of trace metrics, as shown in the following image. + + ![Gantt chart with tree view and pie chart layout]({{site.url}}{{site.baseurl}}/images/ta-hierarchial-view.png) + +- The Gantt chart now includes a selectable mini-map, allowing you to quickly navigate to and focus on specific sections of the trace timeline, as shown in the following image. + + ![Gantt chart with selectable mini-map]({{site.url}}{{site.baseurl}}/images/ta-gantt-mini-map.png) + +- The service map has been redesigned to better support large node groups, making it easier to visualize complex service topologies. You can now focus on a specific service to view its dependencies and reset the map as needed, as shown in the following image. + + ![Redesigned service map with large node groups]({{site.url}}{{site.baseurl}}/images/ta-service-map-dependencies.png) + +- The service view table now includes more quick-select icons, allowing you to view correlated traces and logs in their corresponding views with the correct context passed and to view service details in context without leaving the page, as shown in the following image. + + ![Service table quick select icons]({{site.url}}{{site.baseurl}}/images/ta-service-table-icons.png) + +## Configurable service map limits +Introduced 3.2 +{: .label .label-purple } + +OpenSearch provides default limits for service map rendering. You can increase these limits to render large topologies more completely or lower them to improve client-side performance when focusing on smaller views. This is especially important in environments with many services or dense interconnections, for which the default limits may result in incomplete maps. + + +### Service map configuration settings + +Two **Advanced Settings** control the size and complexity of service maps generated by service map queries: + +- `observability:traceAnalyticsServiceMapMaxNodes`: The maximum number of service nodes displayed. Default is 500. +- `observability:traceAnalyticsServiceMapMaxEdges`: The maximum number of edges (service-to-service connections) displayed. Default is 1,000. + +To configure these settings in OpenSearch Dashboards, follow these steps: +1. From the main menu, select **Management** > **Dashboard Management** > **Advanced Settings**. +1. In the search box, search for `Observability`. In the **Observability** section, locate the **Trace analytics service map maximum edges** and *Trace analytics service map maximum nodes** settings. Adjust the values according to your environment and performance requirements, then save your changes. Higher values can increase browser memory and CPU usage. -The **Services** view lists all services in the application, plus an interactive map that shows how the various services connect to each other. In contrast to the dashboard, which helps identify problems by operation, the service map helps identify problems by service. Try sorting by error rate or latency to get a sense of potential problem areas of your application. -![Service view]({{site.url}}{{site.baseurl}}/images/ta-services.png) diff --git a/_observing-your-data/trace/trace-analytics-jaeger.md b/_observing-your-data/trace/trace-analytics-jaeger.md index 37aed09a..4b60a4e1 100644 --- a/_observing-your-data/trace/trace-analytics-jaeger.md +++ b/_observing-your-data/trace/trace-analytics-jaeger.md @@ -1,7 +1,8 @@ --- layout: default title: Analyzing Jaeger trace data -parent: Trace Analytics +parent: Trace analytics +grand_parent: Classic observability apps nav_order: 55 redirect_from: - /observability-plugin/trace/trace-analytics-jaeger/ @@ -12,83 +13,98 @@ redirect_from: Introduced 2.5 {: .label .label-purple } -The trace analytics functionality in the OpenSearch Observability plugin now supports Jaeger trace data. If you use OpenSearch as the backend for Jaeger trace data, you can use the built-in trace analytics capabilities. This provides support for OpenTelemetry (OTel) trace data. +If you use OpenSearch as the storage backend for [Jaeger](https://www.jaegertracing.io/), you can analyze Jaeger trace data using trace analytics in OpenSearch Dashboards. Trace analytics shows the error rates and latency of your services and operations. You can filter traces and examine the spans of an individual trace to locate service issues. -When you perform trace analytics, you can select from two data sources: +Trace analytics supports two data sources. Select **Data Prepper** to analyze trace data that OpenSearch Data Prepper ingested into OpenSearch. Select **Jaeger** to analyze trace data that Jaeger stored in OpenSearch. -- **Data Prepper** – Data ingested into OpenSearch through Data Prepper -- **Jaeger** – Trace data stored within OpenSearch as its backend +To ingest trace data using Data Prepper instead, see [Getting started with trace analytics]({{site.url}}{{site.baseurl}}/observing-your-data/trace/getting-started/). -If you store your Jaeger trace data in OpenSearch, you can now use the built-in trace analytics capabilities to analyze the error rates and latency. You can also filter the traces and analyze the span details of a trace to pinpoint any service issues. +## Jaeger indexes -When you ingest Jaeger data into OpenSearch, it gets stored in a different index than the OTel-generated index that gets created when you run data through Data Prepper. Use the data source selector in OpenSearch Dashboards to indicate the data source on which you want to perform trace analytics. +Jaeger and Data Prepper store trace data in different indexes. Data Prepper writes to indexes named `otel-v1-apm-span-*` and `otel-v1-apm-service-map*`. Jaeger writes to indexes named `jaeger-span-*` and `jaeger-service-*`. By default, Jaeger creates a new span index and a new service index each day. -Jaeger trace data that you can analyze includes span data as well as service and operation endpoint data. <!-- Need more info for next release. add how to configure for span analysis. Jaeger span data analysis requires some configuration.--> +## Error data requirements -By default, each time you ingest data for Jaeger, it creates a separate index for that day. +Trace analytics identifies spans that contain errors using the `tag.error` field. Jaeger v2 always stores the `error` tag as a field in the span document, so error data is available without additional configuration. -To learn more about Jaeger data tracing, see the [Jaeger](https://www.jaegertracing.io/) documentation. - -## Data ingestion requirements - -To perform trace analytics on Jaeger data, you need to configure error capability. - -Jaeger data that is ingested into OpenSearch must have the environment variable `ES_TAGS_AS_FIELDS_ALL` set to `true` for errors. If data is not ingested in this format, it will not work for errors, and error data will not be available for traces in trace analytics with OpenSearch. - -### About data ingestion with Jaeger indexes - -Trace analytics for non-Jaeger data uses OTel indexes with the naming conventions `otel-v1-apm-span-*` or `otel-v1-apm-service-map*`. - -Jaeger indexes follow the naming conventions `jaeger-span-*` or `jaeger-service-*`. +Earlier Jaeger collectors store tags in a nested array by default. If you use one of these collectors, set the `ES_TAGS_AS_FIELDS_ALL` environment variable to `true`. Otherwise, error data is not available in trace analytics. ## Setting up OpenSearch to use Jaeger data -The following section provides a sample Docker Compose file that contains the configuration required to enable errors for trace analytics. +The following example uses Docker Compose to run a single-node OpenSearch cluster, OpenSearch Dashboards, Jaeger, and the Jaeger HotROD sample application. HotROD sends trace data to Jaeger using the OpenTelemetry Protocol (OTLP), and Jaeger stores the data in OpenSearch. -### Step 1: Run the Docker Compose file +### Step 1: Set the admin password -Use the following Docker Compose file to enable Jaeger data for trace analytics. Set the `ES_TAGS_AS_FIELDS_ALL` environment variable set to `true` to enable errors to be added to trace data. - -Copy the following Docker Compose file and save it as `docker-compose.yml`: +OpenSearch requires a custom password for the `admin` user. In an empty directory, create a file named `.env` containing the following line, replacing `<custom-admin-password>` with a strong password: +```bash +OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> ``` -version: '3' -services: - opensearch-node1: # This is also the hostname of the container within the Docker network (i.e. https://opensearch-node1/) - image: opensearchproject/opensearch:latest # Specifying the latest available image - modify if you want a specific version - container_name: opensearch-node1 - environment: - - cluster.name=opensearch-cluster # Name the cluster - - node.name=opensearch-node1 # Name the node that will run in this container - - discovery.seed_hosts=opensearch-node1,opensearch-node2 # Nodes to look for when discovering the cluster - - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 # Nodes eligible to serve as cluster manager - - bootstrap.memory_lock=true # Disable JVM heap memory swapping - - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # Set min and max JVM heap sizes to at least 50% of system RAM - ulimits: - memlock: - soft: -1 # Set memlock to unlimited (no soft or hard limit) - hard: -1 - nofile: - soft: 65536 # Maximum number of open files for the opensearch user - set to at least 65536 - hard: 65536 - volumes: - - opensearch-data1:/usr/share/opensearch/data # Creates volume called opensearch-data1 and mounts it to the container - ports: - - "9200:9200" - - "9600:9600" - networks: - - opensearch-net # All of the containers will join the same Docker bridge network +{% include copy.html %} - opensearch-node2: - image: opensearchproject/opensearch:latest # This should be the same image used for opensearch-node1 to avoid issues - container_name: opensearch-node2 +Docker Compose reads this file and passes the password to both OpenSearch and Jaeger. For more information, see [Admin password requirements]({{site.url}}{{site.baseurl}}/security/configuration/demo-configuration/#admin-password-requirements). + +### Step 2: Configure Jaeger + +In the same directory, create a file named `jaeger-config.yaml` containing the following configuration. It configures Jaeger to receive OTLP data and store it in OpenSearch: + +```yaml +service: + extensions: [jaeger_storage, jaeger_query] + pipelines: + traces: + receivers: [otlp] + processors: [batch] + exporters: [jaeger_storage_exporter] + +extensions: + jaeger_query: + storage: + traces: opensearch_storage + + jaeger_storage: + backends: + opensearch_storage: + opensearch: + server_urls: + - https://opensearch:9200 + tls: + insecure_skip_verify: true # The demo security configuration uses self-signed certificates + auth: + basic: + username: admin + password: ${env:OPENSEARCH_PASSWORD} + +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +processors: + batch: + +exporters: + jaeger_storage_exporter: + trace_storage: opensearch_storage +``` +{% include copy.html %} + +### Step 3: Create the Docker Compose file + +In the same directory, create a file named `docker-compose.yml` containing the following configuration: + +```yaml +services: + opensearch: + image: opensearchproject/opensearch:latest environment: - - cluster.name=opensearch-cluster - - node.name=opensearch-node2 - - discovery.seed_hosts=opensearch-node1,opensearch-node2 - - cluster.initial_cluster_manager_nodes=opensearch-node1,opensearch-node2 + - discovery.type=single-node - bootstrap.memory_lock=true - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" + - OPENSEARCH_INITIAL_ADMIN_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} ulimits: memlock: soft: -1 @@ -97,155 +113,138 @@ services: soft: 65536 hard: 65536 volumes: - - opensearch-data2:/usr/share/opensearch/data + - opensearch-data:/usr/share/opensearch/data + ports: + - "9200:9200" + healthcheck: # Jaeger starts only after the cluster is available + test: ["CMD-SHELL", "curl -sk -u admin:$$OPENSEARCH_INITIAL_ADMIN_PASSWORD https://localhost:9200/_cluster/health | grep -qE '\"status\":\"(green|yellow)\"'"] + interval: 10s + timeout: 5s + retries: 30 networks: - opensearch-net + opensearch-dashboards: - image: opensearchproject/opensearch-dashboards:latest # Make sure the version of opensearch-dashboards matches the version of opensearch installed on other nodes - container_name: opensearch-dashboards + image: opensearchproject/opensearch-dashboards:latest ports: - - 5601:5601 # Map host port 5601 to container port 5601 - expose: - - "5601" # Expose port 5601 for web access to OpenSearch Dashboards + - "5601:5601" environment: - OPENSEARCH_HOSTS: '["https://opensearch-node1:9200","https://opensearch-node2:9200"]' # Define the OpenSearch nodes that OpenSearch Dashboards will query + OPENSEARCH_HOSTS: '["https://opensearch:9200"]' networks: - opensearch-net - - jaeger-collector: - image: jaegertracing/jaeger-collector:latest - ports: - - "14269:14269" - - "14268:14268" - - "14267:14267" - - "14250:14250" - - "9411:9411" - networks: - - opensearch-net - restart: on-failure - environment: - - SPAN_STORAGE_TYPE=opensearch - - ES_TAGS_AS_FIELDS_ALL=true - - ES_USERNAME=admin - - ES_PASSWORD=admin - - ES_TLS_SKIP_HOST_VERIFY=true - command: [ - "--es.server-urls=https://opensearch-node1:9200", - "--es.tls.enabled=true", - ] depends_on: - - opensearch-node1 + - opensearch - jaeger-agent: - image: jaegertracing/jaeger-agent:latest - hostname: jaeger-agent - command: ["--reporter.grpc.host-port=jaeger-collector:14250"] + jaeger: + image: jaegertracing/jaeger:latest + command: ["--config", "/etc/jaeger/config.yaml"] + environment: + - OPENSEARCH_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} + volumes: + - ./jaeger-config.yaml:/etc/jaeger/config.yaml:ro ports: - - "5775:5775/udp" - - "6831:6831/udp" - - "6832:6832/udp" - - "5778:5778" + - "16686:16686" # Jaeger UI + - "4317:4317" # OTLP over gRPC + - "4318:4318" # OTLP over HTTP networks: - opensearch-net - restart: on-failure - environment: - - SPAN_STORAGE_TYPE=opensearch depends_on: - - jaeger-collector + opensearch: + condition: service_healthy hotrod: image: jaegertracing/example-hotrod:latest - ports: - - "8080:8080" command: ["all"] environment: - - JAEGER_AGENT_HOST=jaeger-agent - - JAEGER_AGENT_PORT=6831 + - OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318 + ports: + - "8080:8080" networks: - opensearch-net depends_on: - - jaeger-agent + - jaeger volumes: - opensearch-data1: - opensearch-data2: + opensearch-data: networks: opensearch-net: ``` +{% include copy.html %} -### Step 2: Start the cluster +### Step 4: Start the containers -Run the following command to deploy the Docker compose YAML file: +To start the containers, run the following command: -``` +```bash docker compose up -d ``` -To stop the cluster, run the following command: +{% include copy.html %} -``` -docker compose down +Jaeger and HotROD start after the OpenSearch cluster reports a `green` or `yellow` health status, which can take a minute or longer. + +To stop the containers and delete their data, run the following command: + +```bash +docker compose down -v ``` +{% include copy.html %} -### Step 3: Generate sample data +### Step 5: Generate sample data -Use the sample app provided with the Docker file to generate data. After you run the Docker Compose file, it runs the sample app on local host port 8080. To open the app, go to http://localhost:8080. +To open the HotROD sample application, go to [http://localhost:8080](http://localhost:8080). Each time you select a customer, HotROD generates a trace. Some of the traces contain errors, so the error views in trace analytics display data. -![Services list]({{site.url}}{{site.baseurl}}/images/trace-analytics/sample-app.png) +![HotROD sample application]({{site.url}}{{site.baseurl}}/images/trace-analytics/sample-app.png) -In the sample app, Hot R.O.D., select any button to generate data. Now you can view trace data in Dashboards. +To confirm that Jaeger stored the trace data in OpenSearch, list the Jaeger indexes: -### Step 4: View trace data in OpenSearch Dashboards +```bash +curl -sk -u admin:<custom-admin-password> "https://localhost:9200/_cat/indices/jaeger-*?v" +``` +{% include copy.html %} -After you generate Jaeger trace data, you can view it in Dashboards. +The response contains a `jaeger-span-*` index and a `jaeger-service-*` index for the current day. -Go to **Trace analytics** at [http://localhost:5601/app/observability-dashboards#/trace_analytics/home](http://localhost:5601/app/observability-dashboards#/trace_analytics/home). +### Step 6: View trace data in OpenSearch Dashboards -## Using trace analytics in OpenSearch Dashboards +Go to [http://localhost:5601](http://localhost:5601) and log in as the `admin` user with the password you set in Step 1. On the top menu, go to **Observability** > **Traces**. -To analyze the Jaeger trace data in Dashboards, first set up the trace analytics functionality. To get started, see [Get started with trace analytics]({{site.url}}{{site.baseurl}}/observability-plugin/trace/get-started/). +## Selecting the data source -### Data sources +To analyze Jaeger data, select **Jaeger** from the data source selector at the top of the **Trace analytics** page. -You can specify either Data Prepper or Jaeger as the data source when you perform trace analytics. -From Dashboards, go to **Observability > Trace analytics** and select Jaeger. +![Selecting Jaeger as the trace analytics data source]({{site.url}}{{site.baseurl}}/images/trace-analytics/select-data.png) -![Select data source]({{site.url}}{{site.baseurl}}/images/trace-analytics/select-data.png) - -## Dashboard view - -After you select Jaeger as the data source, you can view all of the indexed data in **Dashboard** view, including **Error rate** and **Throughput**. - -### Error rate - -You can view the trace error count over time in **Dashboard** view and also see the top five combinations of services and operations that have a non-zero error rate. - -![Error rate]({{site.url}}{{site.baseurl}}/images/trace-analytics/error-rate.png) - -### Throughput - -With **Throughput** selected, you can see the throughput of Jaeger index traces over time. - -You can select an individual trace from the **Top 5 Service and Operation Latency** list and view the detailed trace data. - -![Throughput]({{site.url}}{{site.baseurl}}/images/trace-analytics/throughput.png) - -You can also see the combinations of services and operations that have the highest latency. - -If you select one of the entries for Service and Operation Name and go to the **Traces** column to select a trace, it will automatically add the service and operation as filters. +Trace analytics displays data only for the selected time range. The default time range is the last 5 minutes. If no traces appear, generate new data in the sample application or select a longer time range. ## Traces -In **Traces**, you can see the latency and errors for the filtered service and operation for each individual trace ID in the list. +The **Traces** page lists the traces in the selected time range. For each trace, the list shows the trace ID, latency, whether the trace contains errors, and the time it was last updated. -![Select data source]({{site.url}}{{site.baseurl}}/images/trace-analytics/service-trace-data.png) +![Jaeger traces list]({{site.url}}{{site.baseurl}}/images/trace-analytics/service-trace-data.png) -If you select an individual trace ID, you can see more detailed information about the trace, such as **Time spent by the service** and **Spans**. You can also view the index payload in JSON format. +### Error rate -![Select data source]({{site.url}}{{site.baseurl}}/images/trace-analytics/trace-details.png) +To view error data, expand **Service and Operations** below the traces list and select **Errors**. The chart shows the trace error rate over time. The **Top 5 Service and Operation Errors** table lists the service and operation combinations that have the highest error rates. + +![Trace error rate over time]({{site.url}}{{site.baseurl}}/images/trace-analytics/error-rate.png) + +### Request rate + +To view throughput, select **Request rate**. The chart shows the number of traces over time. The **Top 5 Service and Operation Latency** table lists the service and operation combinations that have the highest latency. + +![Traces over time and the operations that have the highest latency]({{site.url}}{{site.baseurl}}/images/trace-analytics/throughput.png) + +In either table, select a service and operation name to filter the traces list by that service and operation. + +### Trace details + +To view the details of a trace, select its trace ID. The trace details page shows the time spent by each service and the spans of the trace as a timeline, a list, or a tree. The **Payload** section shows the span documents in JSON format. + +![Jaeger trace details]({{site.url}}{{site.baseurl}}/images/trace-analytics/trace-details.png) ## Services -You can also view the individual error rates and latency for each individual service. Go to **Observability > Trace analytics > Services**. In **Services**, you can see the average latency, error rate, throughput and trace for each service in the list. +To view the average duration, error rate, request rate, and number of traces for each service, select **Services**. -![Services list]({{site.url}}{{site.baseurl}}/images/trace-analytics/services-jaeger.png) +![Jaeger services list]({{site.url}}{{site.baseurl}}/images/trace-analytics/services-jaeger.png) diff --git a/_query-dsl/ai-vector-search/index.md b/_query-dsl/ai-vector-search/index.md new file mode 100644 index 00000000..a585a969 --- /dev/null +++ b/_query-dsl/ai-vector-search/index.md @@ -0,0 +1,21 @@ +--- +layout: default +title: AI and vector search queries +has_children: true +nav_order: 55 +has_toc: false +redirect_from: + - /query-dsl/ai-vector-search/ +--- + +# AI and vector search queries + +AI and vector search queries use machine learning models to transform or enhance search operations. These queries convert text or other input into vector representations for similarity search, or use AI services to generate query parameters at runtime. + +| Query type | Description | +| :--- | :--- | +| [Agentic]({{site.url}}{{site.baseurl}}/query-dsl/specialized/agentic/) | Uses AI agents to dynamically plan and execute search strategies. | +| [k-NN]({{site.url}}{{site.baseurl}}/query-dsl/specialized/k-nn/) | Performs approximate or exact nearest-neighbor search using vector embeddings. | +| [Neural]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/) | Converts text to dense vector embeddings at query time for semantic search. | +| [Neural sparse]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural-sparse/) | Converts text to sparse vector embeddings at query time for semantic search. | +| [Template]({{site.url}}{{site.baseurl}}/query-dsl/specialized/template/) | Contains placeholder variables resolved by ML inference processors at query time. | diff --git a/_query-dsl/compound/bool.md b/_query-dsl/compound/bool.md index 12caea2f..6a8938f3 100644 --- a/_query-dsl/compound/bool.md +++ b/_query-dsl/compound/bool.md @@ -2,7 +2,6 @@ layout: default title: Boolean parent: Compound queries -grand_parent: Query DSL nav_order: 10 redirect_from: - /opensearch/query-dsl/compound/bool/ @@ -19,9 +18,11 @@ Use the following query clauses within a `bool` query: Clause | Behavior :--- | :--- `must` | Logical `and` operator. The results must match all queries in this clause. -`must_not` | Logical `not` operator. All matches are excluded from the results. -`should` | Logical `or` operator. The results must match at least one of the queries. Matching more `should` clauses increases the document's relevance score. You can set the minimum number of queries that must match using the [`minimum_should_match`]({{site.url}}{{site.baseurl}}/query-dsl/query-dsl/minimum-should-match/) parameter. If a query contains a `must` or `filter` clause, the default `minimum_should_match` value is 0. Otherwise, the default `minimum_should_match` value is 1. -`filter` | Logical `and` operator that is applied first to reduce your dataset before applying the queries. A query within a filter clause is a yes or no option. If a document matches the query, it is returned in the results; otherwise, it is not. The results of a filter query are generally cached to allow for a faster return. Use the filter query to filter the results based on exact matches, ranges, dates, or numbers. +`must_not` | Logical `not` operator. All matches are excluded from the results. If `must_not` has multiple clauses, only documents that do not match any of those clauses are returned. For example, `"must_not":[{clause_A}, {clause_B}]` is equivalent to `NOT(A OR B)`. +`should` | Logical `or` operator. Matching more `should` clauses increases the document's relevance score. You can set the minimum number of queries that must match using the [`minimum_should_match`]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/) parameter. If a query contains a `must` or `filter` clause, the default `minimum_should_match` value is 0, so documents are not required to match any `should` clause. Otherwise, the default `minimum_should_match` value is 1, so the results must match at least one of the queries. +`filter` | Logical `and` operator that does not affect the relevance score. A query within a filter clause is a yes or no option. If a document matches the query, it is returned in the results; otherwise, it is not. The results of a filter query are generally cached to allow for a faster return. Use the filter query to filter the results based on exact matches, ranges, dates, or numbers. + +The `must` and `should` clauses run in [query context]({{site.url}}{{site.baseurl}}/query-dsl/query-filter-context/), so the scores of all matching `must` and `should` clauses are added together to produce the document's relevance score. A document that matches more clauses therefore ranks higher. The `filter` and `must_not` clauses run in filter context: they determine whether a document matches but do not contribute to its score, and OpenSearch can cache their results. A Boolean query has the following structure: @@ -45,6 +46,21 @@ GET _search } ``` +## Parameters + +The `bool` query accepts the following parameters. All parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`must` | Object or array of objects | Queries that documents must match. Matching queries contribute to the relevance score. +`should` | Object or array of objects | Queries that documents should match. Each matching query adds to the relevance score. Whether a document must match any of these queries depends on `minimum_should_match`. +`filter` | Object or array of objects | Queries that documents must match. These queries run in filter context and do not contribute to the relevance score. +`must_not` | Object or array of objects | Queries that documents must not match. These queries run in filter context and do not contribute to the relevance score. +`minimum_should_match` | Integer or string | The number or percentage of `should` clauses that a document must match. Default is `0` if the query contains a `must` or `filter` clause and `1` otherwise. For valid values, see [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). +`boost` | Floating-point | A multiplier applied to the relevance score of the whole `bool` query. Values between 0 and 1 decrease relevance, and values greater than 1 increase relevance. Because `filter` and `must_not` clauses do not contribute to the score, `boost` has no effect on a query that contains only these clauses. Default is `1.0`. + +## Example + For example, assume you have the complete works of Shakespeare indexed in an OpenSearch cluster. You want to construct a single query that meets the following requirements: 1. The `text_entry` field must contain the word `love` and should contain either `life` or `grace`. @@ -94,16 +110,17 @@ GET shakespeare/_search } } ``` +{% include copy-curl.html %} The response contains matching documents: ```json { - "took": 12, + "took": 8, "timed_out": false, "_shards": { - "total": 4, - "successful": 4, + "total": 1, + "successful": 1, "skipped": 0, "failed": 0 }, @@ -112,12 +129,12 @@ The response contains matching documents: "value": 1, "relation": "eq" }, - "max_score": 11.356054, + "max_score": 5.1232996, "hits": [ { "_index": "shakespeare", "_id": "88020", - "_score": 11.356054, + "_score": 5.1232996, "_source": { "type": "line", "line_id": 88021, @@ -133,7 +150,7 @@ The response contains matching documents: } ``` -If you want to identify which of these clauses actually caused the matching results, name each query with the `_name` parameter. +If you want to identify which of these clauses actually caused the matching results, name each query with the `_name` parameter. For more information, see [Named queries]({{site.url}}{{site.baseurl}}/query-dsl/named-queries/). To add the `_name` parameter, change the field name in the `match` query to an object: ```json @@ -189,6 +206,7 @@ GET shakespeare/_search } } ``` +{% include copy-curl.html %} OpenSearch returns a `matched_queries` array that lists the queries that matched these results: @@ -221,7 +239,7 @@ GET shakespeare/_search }, { "match": { - "text": "hate" + "text_entry": "hate" } } ] @@ -237,7 +255,7 @@ GET shakespeare/_search }, { "match": { - "text": "grace" + "text_entry": "grace" } } ] @@ -253,28 +271,45 @@ GET shakespeare/_search } } ``` +{% include copy-curl.html %} -The response contains matching documents: +The response contains three matching lines: ```json { - "took": 10, + "took": 6, "timed_out": false, "_shards": { - "total": 2, - "successful": 2, + "total": 1, + "successful": 1, "skipped": 0, "failed": 0 }, "hits": { - "total": 1, - "max_score": 11.37006, + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 5.557603, "hits": [ { "_index": "shakespeare", - "_type": "doc", + "_id": "86436", + "_score": 5.557603, + "_source": { + "type": "line", + "line_id": 86437, + "play_name": "Romeo and Juliet", + "speech_number": 16, + "line_number": "2.3.88", + "speaker": "ROMEO", + "text_entry": "Doth grace for grace and love for love allow;" + } + }, + { + "_index": "shakespeare", "_id": "88020", - "_score": 11.37006, + "_score": 5.1232996, "_source": { "type": "line", "line_id": 88021, @@ -284,8 +319,113 @@ The response contains matching documents: "speaker": "PARIS", "text_entry": "O love! O life! not life, but love in death!" } + }, + { + "_index": "shakespeare", + "_id": "86214", + "_score": 5.0415897, + "_source": { + "type": "line", + "line_id": 86215, + "play_name": "Romeo and Juliet", + "speech_number": 17, + "line_number": "2.2.81", + "speaker": "ROMEO", + "text_entry": "My life were better ended by their hate," + } } ] } } ``` + +## Scoring with filter clauses + +Queries in a `filter` clause decide which documents match but do not add to the relevance score. The score depends only on the scoring clauses (`must` and `should`) in the query. The following examples use a `support_tickets` index. Create the index and map the `status` field as a `keyword` field so that the `term` query matches it exactly: + +```json +PUT support_tickets +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "status": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents: + +```json +POST support_tickets/_bulk?refresh +{ "index": { "_id": "1" } } +{ "title": "Login page times out", "status": "open" } +{ "index": { "_id": "2" } } +{ "title": "Password reset email not received", "status": "open" } +{ "index": { "_id": "3" } } +{ "title": "Dashboard loads slowly", "status": "closed" } +``` +{% include copy-curl.html %} + +Each of the following three queries returns the two open tickets. They differ only in the scores they assign. + +The following query contains only a `filter` clause. Because there is no scoring clause, every matching document receives a score of `0`: + +```json +GET support_tickets/_search +{ + "query": { + "bool": { + "filter": { + "term": { + "status": "open" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The following query adds a `match_all` query in a `must` clause. The `match_all` query assigns a score of `1` to every document, so both open tickets receive a score of `1`: + +```json +GET support_tickets/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "term": { + "status": "open" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The following [`constant_score`]({{site.url}}{{site.baseurl}}/query-dsl/compound/constant-score/) query returns the same results as the preceding query. It assigns a score of `1` to every document that matches its filter: + +```json +GET support_tickets/_search +{ + "query": { + "constant_score": { + "filter": { + "term": { + "status": "open" + } + } + } + } +} +``` +{% include copy-curl.html %} + +When the `must` clause contains a full-text query, the filter still does not change the score. For example, a `match` query for `login` in the `title` field assigns ticket 1 a score of `0.44583148`, whether or not the query also contains the `status` filter. diff --git a/_query-dsl/compound/boosting.md b/_query-dsl/compound/boosting.md index 7aa9c6c0..ede7eb3d 100644 --- a/_query-dsl/compound/boosting.md +++ b/_query-dsl/compound/boosting.md @@ -2,7 +2,6 @@ layout: default title: Boosting parent: Compound queries -grand_parent: Query DSL nav_order: 30 redirect_from: - /query-dsl/query-dsl/compound/boosting/ diff --git a/_query-dsl/compound/constant-score.md b/_query-dsl/compound/constant-score.md index ed12e33e..bb5af380 100644 --- a/_query-dsl/compound/constant-score.md +++ b/_query-dsl/compound/constant-score.md @@ -2,7 +2,6 @@ layout: default title: Constant score parent: Compound queries -grand_parent: Query DSL nav_order: 40 redirect_from: - /query-dsl/query-dsl/compound/constant-score/ diff --git a/_query-dsl/compound/disjunction-max.md b/_query-dsl/compound/disjunction-max.md index 8dd9e41d..5450efe5 100644 --- a/_query-dsl/compound/disjunction-max.md +++ b/_query-dsl/compound/disjunction-max.md @@ -2,7 +2,6 @@ layout: default title: Disjunction max parent: Compound queries -grand_parent: Query DSL nav_order: 50 redirect_from: - /query-dsl/query-dsl/compound/disjunction-max/ @@ -21,8 +20,8 @@ Consider an index with two documents that you index as follows: ```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" + "title": "The Top 10 Shakespeare Poems", + "body": "Top 10 sonnets of England's national poet and the Bard of Avon" } ``` {% include copy-curl.html %} @@ -31,12 +30,12 @@ PUT testindex1/_doc/1 PUT testindex1/_doc/2 { "title": "Sonnets of the 16th Century", - "body": "The poems written by various 16-th century poets" + "body": "The poems written by various 16th-century poets" } ``` {% include copy-curl.html %} -Use a `dis_max` query to search for documents that contain the words "Shakespeare poems": +Use a `dis_max` query to search the `title` and `body` fields for the words "Shakespeare poems": ```json GET testindex1/_search @@ -53,11 +52,11 @@ GET testindex1/_search ``` {% include copy-curl.html %} -The response contains both documents: +The response contains both documents. Document 1 receives a higher relevance score because its `title` field matches both words, whereas document 2 matches only the word "poems": ```json { - "took": 8, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -70,24 +69,24 @@ The response contains both documents: "value": 2, "relation": "eq" }, - "max_score": 1.3862942, + "max_score": 0.63013375, "hits": [ { "_index": "testindex1", "_id": "1", - "_score": 1.3862942, + "_score": 0.63013375, "_source": { - "title": " The Top 10 Shakespeare Poems", - "description": "Top 10 sonnets of England's national poet and the Bard of Avon" + "title": "The Top 10 Shakespeare Poems", + "body": "Top 10 sonnets of England's national poet and the Bard of Avon" } }, { "_index": "testindex1", "_id": "2", - "_score": 0.2876821, + "_score": 0.34314215, "_source": { "title": "Sonnets of the 16th Century", - "body": "The poems written by various 16-th century poets" + "body": "The poems written by various 16th-century poets" } } ] diff --git a/_query-dsl/compound/function-score.md b/_query-dsl/compound/function-score.md index 8180058a..00d55547 100644 --- a/_query-dsl/compound/function-score.md +++ b/_query-dsl/compound/function-score.md @@ -2,7 +2,6 @@ layout: default title: Function score parent: Compound queries -grand_parent: Query DSL nav_order: 60 has_math: true redirect_from: @@ -11,14 +10,29 @@ redirect_from: # Function score query -Use a `function_score` query if you need to alter the relevance scores of documents returned in the results. A `function_score` query defines a query and one or more functions that can be applied to all results or subsets of the results to recalculate their relevance scores. +Use a `function_score` query if you need to alter the relevance scores of documents returned in the results. A `function_score` query defines a query and one or more functions that can be applied to all results or subsets of the results to recalculate their relevance scores. A `function_score` query changes how documents are ranked, not which documents are returned. If you omit the top-level `query` parameter, `function_score` runs on `match_all`, so every document in the index matches and receives a base query score of `1`. To limit which documents are returned, provide an explicit top-level `query`, wrap `function_score` in a [`bool` query](#returning-only-documents-that-match-a-function-filter), or specify a [`min_score`](#filtering-documents-that-dont-meet-a-threshold). + +The examples in this section use a `blogs` index containing the following documents: + +```json +POST _bulk +{ "index": { "_index": "blogs", "_id": "1" } } +{ "name": "Semantic search in OpenSearch", "views": 1200, "likes": 150, "comments": 16, "date_posted": "2022-04-17" } +{ "index": { "_index": "blogs", "_id": "2" } } +{ "name": "Get started with OpenSearch 2.7", "views": 1400, "likes": 100, "comments": 20, "date_posted": "2022-05-02" } +{ "index": { "_index": "blogs", "_id": "3" } } +{ "name": "Distributed tracing with Data Prepper", "views": 800, "likes": 50, "comments": 5, "date_posted": "2022-04-25" } +{ "index": { "_index": "blogs", "_id": "4" } } +{ "name": "A very old blog", "views": 100, "likes": 20, "comments": 3, "date_posted": "2000-04-25" } +``` +{% include copy-curl.html %} ## Using one scoring function -The most basic example of a `function_score` query uses one function to recalculate the score. The following query uses a `weight` function to double all relevance scores. This function applies to all documents in the results because there is no `query` parameter specified within `function_score`: +The most basic example of a `function_score` query uses one function to recalculate the score. The following query uses a `weight` function to double all relevance scores. This function applies to all documents in the results because there is no top-level `query` parameter specified, so `function_score` runs on `match_all`: ```json -GET shakespeare/_search +GET blogs/_search { "query": { "function_score": { @@ -29,18 +43,18 @@ GET shakespeare/_search ``` {% include copy-curl.html %} -## Applying the scoring function to a subset of documents +## Limiting which documents are scored -To apply the scoring function to a subset of documents, provide a query within the function: +Use the top-level `query` parameter to define which documents `function_score` runs on. Only documents matching this query are returned. The following query limits results to blog posts matching `OpenSearch` and then doubles their relevance scores: ```json -GET shakespeare/_search +GET blogs/_search { "query": { "function_score": { "query": { "match": { - "play_name": "Hamlet" + "name": "OpenSearch" } }, "weight": "2" @@ -50,6 +64,59 @@ GET shakespeare/_search ``` {% include copy-curl.html %} +## Applying a scoring function to a subset of documents + +To apply a scoring function to only a subset of the matching documents, specify a `filter` for a function in the `functions` array. The function contributes to the score only for documents matching its filter. Omitting a `filter` is equivalent to specifying `match_all`, so the function applies to every document. The relevance score produced by the filter query is not used in the calculation. + +A function `filter` determines which documents a function scores, not which documents are returned. Documents that match the top-level query (or the implicit `match_all`) but match none of the function filters are still returned. +{: .important} + +The following query adds `0.5` to the score of blog posts with at least 1,000 views and `1` to the score of blog posts with at least 150 likes. Because no top-level `query` is specified, `function_score` runs on `match_all` and returns every document in the index: + +```json +GET blogs/_search +{ + "query": { + "function_score": { + "score_mode": "sum", + "functions": [ + { + "filter": { + "range": { + "views": { + "gte": 1000 + } + } + }, + "weight": 0.5 + }, + { + "filter": { + "range": { + "likes": { + "gte": 150 + } + } + }, + "weight": 1 + } + ] + } + } +} +``` +{% include copy-curl.html %} + +All four blog posts are returned: + +- Document 1 matches both filters and receives a score of `1.5` (the function factor `0.5 + 1` multiplied by the `match_all` query score of `1`). +- Document 2 matches only the `views` filter and receives a score of `0.5`. +- Documents 3 and 4 match neither filter and each receive a score of `1`. The implicit `match_all` query contributes `1`, and because no function matched, the function factor is also `1`: + +$$ \text{final score} = \text{query score} \times \text{function factor} = 1 \times 1 = 1 $$ + +Documents that match no function filters can therefore rank above documents that do. In the preceding results, documents 3 and 4 score `1` while document 2 scores `0.5`. To confirm that this is the cause of an unexpected score, set `explain` to `true` and look for a `No function matched` entry in the explanation. To exclude these documents, see [Returning only documents that match a function filter](#returning-only-documents-that-match-a-function-filter). + ## Supported functions The `function_score` query type supports the following functions: @@ -67,7 +134,7 @@ The `function_score` query type supports the following functions: When you use the `weight` function, the original relevance score is multiplied by the floating-point value of `weight`: ```json -GET shakespeare/_search +GET blogs/_search { "query": { "function_score": { @@ -80,9 +147,11 @@ GET shakespeare/_search Unlike the `boost` value, the `weight` function is not normalized. +When you specify `weight` without any other function, it acts as a function that returns the `weight` value. When you specify it alongside another function in the `functions` array, it multiplies the score that the other function produces. + ## The random score function -The `random_score` function provides a random score that is consistent for a single user but different between users. The score is a floating-point number in the [0, 1) range. By default, the `random_score` function uses internal Lucene document IDs as seed values, making random values irreproducible because documents can be renumbered after merges. To achieve consistency in generating random values, you can provide `seed` and `field` parameters. The `field` must be a field for which `fielddata` is enabled (commonly, a numeric field). The score is calculated using the `seed`, the `fielddata` values for the `field`, and a salt calculated using the index name and shard ID. Because the index name and shard ID are the same for documents that reside in the same shard, documents with the same `field` values will be assigned the same score. To ensure different scores for all documents in the same shard, use a `field` that has unique values for all documents. One option is to use the `_seq_no` field. However, if you choose this field, the scores can change if the document is updated because of the corresponding `_seq_no` update. +The `random_score` function provides a random score that is consistent for a single user but different between users. The score is a floating-point number in the [0, 1) range. If you don't provide a `seed`, OpenSearch derives one from the current time and scores documents using internal Lucene document IDs. The resulting scores are not reproducible: they change between requests, and documents can also be renumbered after segment merges. To achieve consistency in generating random values, provide the `seed` and `field` parameters. The `field` must be a field for which `fielddata` is enabled (commonly, a numeric field). The score is calculated using the `seed`, the `fielddata` values for the `field`, and a salt calculated using the index name and shard ID. Because the index name and shard ID are the same for documents that reside in the same shard, documents with the same `field` values will be assigned the same score. To ensure different scores for all documents in the same shard, use a `field` that has unique values for all documents. One option is to use the `_seq_no` field. However, if you choose this field, the scores can change if the document is updated because of the corresponding `_seq_no` update. The following query uses the `random_score` function with a `seed` and `field`: @@ -101,6 +170,9 @@ GET blogs/_search ``` {% include copy-curl.html %} +Specifying a `seed` without a `field` is deprecated. In this case, OpenSearch uses the `_id` field, which requires loading its `fielddata` and consumes a large amount of memory. Always provide a `field` when you specify a `seed`. +{: .warning} + ## The field value factor function The `field_value_factor` function recalculates the score using the value of the specified document field. If the field is a multi-valued field, only its first value is used for calculations, and the others are not considered. @@ -115,10 +187,10 @@ The `field_value_factor` function supports the following options: Modifier | Formula | Description :--- | :--- | :--- - `log`| $$\log v$$ | Take the base-10 logarithm of the value. Taking a logarithm of a non-positive number is an illegal operation and will result in an error. For values between 0 (exclusive) and 1 (inclusive), this function returns non-negative values that will result in an error. We recommend using `log1p` or `log2p` instead of `log`. + `log`| $$\log v$$ | Take the base-10 logarithm of the value. Taking a logarithm of a non-positive number is an illegal operation and will result in an error. For values between 0 (exclusive) and 1 (exclusive), this function returns negative values that result in an error. A value of 1 produces a score of 0, which, with the default `boost_mode` of `multiply`, sets the document's final score to 0. We recommend using `log1p` or `log2p` instead of `log`. `log1p`| $$\log (1 + v)$$ | Take the base-10 logarithm of the sum of 1 and the value. `log2p`| $$\log (2 + v)$$ | Take the base-10 logarithm of the sum of 2 and the value. - `ln`| $$\ln v$$ | Take the natural logarithm of the value. Taking a logarithm of a non-positive number is an illegal operation and will result in an error. For values between 0 (exclusive) and 1 (inclusive), this function returns non-negative values that will result in an error. We recommend using `ln1p` or `ln2p` instead of `ln`. + `ln`| $$\ln v$$ | Take the natural logarithm of the value. Taking a logarithm of a non-positive number is an illegal operation and will result in an error. For values between 0 and 1 (both exclusive), this function returns negative values that will result in an error. A value of 1 produces a score of 0, which, with the default `boost_mode` of `multiply`, sets the document's final score to 0. We recommend using `ln1p` or `ln2p` instead of `ln`. `ln1p`| $$\ln (1 + v)$$ | Take the natural logarithm of the sum of 1 and the value. `ln2p`| $$\ln (2 + v)$$ | Take the natural logarithm of the sum of 2 and the value. `reciprocal`| $$\frac {1}{v}$$ | Take the reciprocal of the value. @@ -199,16 +271,18 @@ GET blogs/_search ``` {% include copy-curl.html %} +By default, the query score is multiplied by the script result. To use the script result as the final score, set `boost_mode` to `replace`. For more information, see [Combining the score for all functions with the query score](#combining-the-score-for-all-functions-with-the-query-score). + ## Decay functions For many applications, you need to sort the results based on proximity or recency. You can do this with decay functions. Decay functions calculate a document score using one of three decay curves: Gaussian, exponential, or linear. -Decay functions operate only on [numeric]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/numeric/), [date]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/dates/), and [geopoint]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/geo-point/) fields. +Decay functions operate only on [numeric]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/numeric/), [date]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/dates/), and [geopoint]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/) fields. {: .important} Decay functions calculate scores based on the `origin`, `scale`, `offset`, and `decay`, as shown in the following figure. -<img src="{{site.url}}{{site.baseurl}}/images/decay-functions.png" alt="Decay function curves" width="600"> +![Decay function curves]({{site.url}}{{site.baseurl}}/images/decay-functions.png){: width="600" } ### Example: Geopoint fields @@ -342,9 +416,9 @@ The following table lists all parameters supported by the `gauss`, `exp`, and `l Parameter | Description :--- | :--- -`origin` | The point from which to calculate the distance. Must be provided as a number for numeric fields, a date for date fields, or a geopoint for geopoint fields. Required for geopoint and numeric fields. Optional for date fields (defaults to `now`). For date fields, date math is supported (for example, `now-2d`). +`origin` | The point from which to calculate the distance. Must be provided as a number for numeric fields, a date for date fields, or a geopoint for geopoint fields. Required for geopoint and numeric fields. Optional for date fields (defaults to `now`). For date fields, the `origin` must use the date `format` defined in the field mapping, and date math is supported (for example, `now-2d`). `offset` | Defines the distance from the origin within which documents are given a score of 1. Optional. Default is 0. -`scale` | Documents at the distance of `scale` + `offset` from the `origin` are assigned a score of `decay`. Required. <br>For numeric fields, `scale` can be any number. <br>For date fields, `scale` can be defined as a number with [units]({{site.url}}{{site.baseurl}}/api-reference/units/) (`5h`, `1d`). If units are not provided, `scale` defaults to milliseconds. <br>For geopoint fields, `scale` can be defined as a number with [units]({{site.url}}{{site.baseurl}}/api-reference/units/) (`1mi`, `5km`). If units are not provided, `scale` defaults to meters. +`scale` | Documents at the distance of `scale` + `offset` from the `origin` are assigned a score of `decay`. Required. <br>For numeric fields, `scale` can be any number. <br>For date fields, `scale` must be defined as a number with [units]({{site.url}}{{site.baseurl}}/api-reference/units/) (for example, `5h`, `1d`, or `1000ms`). <br>For geopoint fields, `scale` can be defined as a number with [units]({{site.url}}{{site.baseurl}}/api-reference/units/) (for example, `1mi` or `5km`). If units are not provided, `scale` defaults to meters. `decay` | Defines the score of a document at the distance of `scale` + `offset` from the `origin`. Optional. Default is 0.5. For fields that are missing from the document, decay functions return a score of 1. @@ -457,7 +531,7 @@ The first two blog posts in the results have a score of 1 because one is at the ### Example: Date fields -The following query uses the Gaussian decay function to prioritize blog posts published around 04/24/2002: +The following query uses the Gaussian decay function to prioritize blog posts published around 04/24/2022: ```json GET blogs/_search @@ -664,19 +738,21 @@ $$\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), $$ +$$ \text{score} = \max \left(0, \frac {s - \max(0, \lvert v - \text{origin} \rvert - \text{offset})} {s} \right), $$ where $$s$$ is calculated to ensure that the score is equal to `decay` at the distance `offset` + `scale` from the `origin`: $$s = \frac {\text{scale}} {1 - \text{decay}}$$ +The linear function assigns a score of 0 to documents whose distance from the `origin` is at least `offset` + $$s$$. With the default `decay` of 0.5, $$s$$ equals twice the `scale`. + ## Using multiple scoring functions You can specify multiple scoring functions in a function score query by listing them in the `functions` array. ### Combining scores from multiple functions -Different functions can use different scales for scoring. For example, the `random_score` function provides a score between 0 and 1, but the `field_value_factor` does not have a specific scale for the score. Additionally, you may want to weigh scores given by different functions differently. To adjust scores for different functions, you can specify the `weight` parameter for each function. The score given by each function is then multiplied by the `weight` to produce the final score for that function. The `weight` parameter must be provided in the `functions` array in order to differentiate it from the [weight function](#the-weight-function), +Different functions can use different scales for scoring. For example, the `random_score` function provides a score between 0 and 1, but the `field_value_factor` does not have a specific scale for the score. Additionally, you may want to weigh scores given by different functions differently. To adjust scores for different functions, you can specify the `weight` parameter for each function. The score given by each function is then multiplied by the `weight` to produce the final score for that function. The `weight` parameter must be provided in the `functions` array in order to differentiate it from the [weight function](#the-weight-function). The scores given by each function are combined using the `score_mode` parameter, which takes one of the following values: @@ -687,10 +763,19 @@ The scores given by each function are combined using the `score_mode` parameter, - `max`: The maximum score is taken. - `min`: The minimum score is taken. +If a document matches none of the function filters, the function score remains at the neutral value `1` for all `score_mode` values. + ### Specifying an upper limit for a score You can specify an upper limit for a function score in the `max_boost` parameter. The default upper limit is the maximum magnitude for a `float` value: (2 − 2<sup>−23</sup>) · 2<sup>127</sup>. +### Boosting the whole query + +Use the top-level `boost` parameter to boost the `function_score` query as a whole. The `boost` value multiplies the query score, including the score of the implicit `match_all` query when no top-level `query` is specified. Default is `1`. + +Because `max_boost` caps the combined function score and not the final score, a `boost` value greater than `1` can produce scores that exceed `max_boost`. For example, a query with a `weight` of `10`, a `max_boost` of `2`, and a `boost` of `5` returns a score of `10`: the function score is capped at `2` and then multiplied by the boosted query score of `5`. +{: .note} + ### Combining the score for all functions with the query score You can specify how the score computed using all functions is combined with the query score in the `boost_mode` parameter, which takes one of the following values: @@ -702,13 +787,42 @@ You can specify how the score computed using all functions is combined with the - `max`: Take the greater of the query score and the function score. - `min`: Take the lesser of the query score and the function score. +With the default `boost_mode` of `multiply` and an implicit `match_all` query, a document that matches no functions receives a score of `1`. + ### Filtering documents that don't meet a threshold Changing the relevance score does not change the list of matching documents. To exclude some documents that don't meet a threshold, specify the threshold value in the `min_score` parameter. All documents returned by the query are then scored and filtered using the threshold value. +To apply `min_score`, OpenSearch must first calculate the final score of every document that matches the query and then remove the low-scoring documents one by one. A `min_score` threshold reduces the number of results but not the scoring work, so it does not make a query that matches many documents faster. + +Because `min_score` is applied after scoring, it doesn't exclude documents based on the function filters they matched. In the [preceding example](#applying-a-scoring-function-to-a-subset-of-documents), setting `min_score` to `0.9` excludes document 2, which matched the `views` filter and scored `0.5`, but retains documents 3 and 4, which matched no filters and scored `1`. +{: .note} + +### Returning only documents that match a function filter + +To return only the documents matching at least one function filter, use a [`bool` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/) with `minimum_should_match` instead of relying on function filters: + +```json +GET blogs/_search +{ + "query": { + "bool": { + "should": [ + { "range": { "views": { "gte": 1000 } } }, + { "range": { "likes": { "gte": 150 } } } + ], + "minimum_should_match": 1 + } + } +} +``` +{% include copy-curl.html %} + +Only documents 1 and 2 are returned. To rank those documents using scoring functions, provide the `bool` query as the top-level `query` in a `function_score` query. + ### Example -The following request searches for blog posts that include the words "OpenSearch Data Prepper", preferring the posts published around 04/24/2022. Additionally, the number of views and likes are taken into consideration. Finally, the cutoff threshold is set at the score of 10: +The following request searches for blog posts that include the words "OpenSearch Data Prepper", preferring the posts published around 04/24/2022. Additionally, the number of views and likes are taken into consideration. Finally, the cutoff threshold is set at the score of 6: ```json GET blogs/_search @@ -754,14 +868,122 @@ GET blogs/_search "max_boost": 10, "score_mode": "max", "boost_mode": "multiply", - "min_score": 10 + "min_score": 6 } } } ``` {% include copy-curl.html %} -The results contain the three matching blog posts: +Three blog posts match the query, but the `min_score` threshold of `6` excludes the lowest-scoring one, so the response contains two blog posts: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 14.178148, + "hits": [ + { + "_index": "blogs", + "_id": "3", + "_score": 14.178148, + "_source": { + "name": "Distributed tracing with Data Prepper", + "views": 800, + "likes": 50, + "comments": 5, + "date_posted": "2022-04-25" + } + }, + { + "_index": "blogs", + "_id": "1", + "_score": 6.321524, + "_source": { + "name": "Semantic search in OpenSearch", + "views": 1200, + "likes": 150, + "comments": 16, + "date_posted": "2022-04-17" + } + } + ] + } +} +``` +</details> + +## Named functions + +When defining a function, you can specify its name using the `_name` parameter at the top level. This name is useful for debugging and understanding the scoring process. Once specified, the function name is included in the score calculation explanation whenever possible (this applies to functions, filters, and queries). You can identify the function by its `_name` in the response. + +### Example + +The following request sets `explain` to `true` for debugging purposes in order to obtain a scoring explanation in the response. Each function contains a `_name` parameter so that you can identify the function unambiguously: + +```json +GET blogs/_search +{ + "explain": true, + "size": 1, + "query": { + "function_score": { + "functions": [ + { + "_name": "likes_function", + "script_score": { + "script": { + "lang": "painless", + "source": "return doc['likes'].value * 2;" + } + }, + "weight": 0.6 + }, + { + "_name": "views_function", + "field_value_factor": { + "field": "views", + "factor": 1.5, + "modifier": "log1p", + "missing": 1 + }, + "weight": 0.3 + }, + { + "_name": "comments_function", + "gauss": { + "comments": { + "origin": 1000, + "scale": 800 + } + }, + "weight": 0.1 + } + ] + } + } +} +``` +{% include copy-curl.html %} + +The response explains the scoring process. For each function, the explanation contains the function `_name` in its `description`. The `*:*` entry with a value of `1` is the score of the implicit `match_all` query because no top-level `query` is specified. <details open markdown="block"> <summary> @@ -781,49 +1003,122 @@ The results contain the three matching blog posts: }, "hits": { "total": { - "value": 3, + "value": 4, "relation": "eq" }, - "max_score": 31.191923, + "max_score": 6.1600614, "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" - } - }, - { + "_shard": "[blogs][0]", + "_node": "_yndTaZHQWimcDgAfOfRtQ", "_index": "blogs", "_id": "1", - "_score": 13.907352, + "_score": 6.1600614, "_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" + }, + "_explanation": { + "value": 6.1600614, + "description": "function score, product of:", + "details": [ + { + "value": 1, + "description": "*:*", + "details": [] + }, + { + "value": 6.1600614, + "description": "min of:", + "details": [ + { + "value": 6.1600614, + "description": "function score, score mode [multiply]", + "details": [ + { + "value": 180, + "description": "product of:", + "details": [ + { + "value": 300, + "description": "script score function(_name: likes_function), computed with script:\"Script{type=inline, lang='painless', idOrCode='return doc['likes'].value * 2;', options={}, params={}}\"", + "details": [ + { + "value": 1, + "description": "_score: ", + "details": [ + { + "value": 1, + "description": "*:*", + "details": [] + } + ] + } + ] + }, + { + "value": 0.6, + "description": "weight", + "details": [] + } + ] + }, + { + "value": 0.9766541, + "description": "product of:", + "details": [ + { + "value": 3.2555137, + "description": "field value function(_name: views_function): log1p(doc['views'].value?:1.0 * factor=1.5)", + "details": [] + }, + { + "value": 0.3, + "description": "weight", + "details": [] + } + ] + }, + { + "value": 0.035040613, + "description": "product of:", + "details": [ + { + "value": 0.35040614, + "description": "Function for field comments:", + "details": [ + { + "value": 0.35040614, + "description": "exp(-0.5*pow(MIN[Math.max(Math.abs(16.0(=doc value) - 1000.0(=origin))) - 0.0(=offset), 0)],2.0)/461662.4130844683, _name: comments_function)", + "details": [] + } + ] + }, + { + "value": 0.1, + "description": "weight", + "details": [] + } + ] + } + ] + }, + { + "value": 3.4028235e+38, + "description": "maxBoost", + "details": [] + } + ] + } + ] } } ] } } ``` -</details> \ No newline at end of file +</details> + diff --git a/_query-dsl/compound/hybrid.md b/_query-dsl/compound/hybrid.md index e573d176..4d90253f 100644 --- a/_query-dsl/compound/hybrid.md +++ b/_query-dsl/compound/hybrid.md @@ -2,7 +2,6 @@ layout: default title: Hybrid parent: Compound queries -grand_parent: Query DSL nav_order: 70 --- @@ -10,15 +9,13 @@ nav_order: 70 You can use a hybrid query to combine relevance scores from multiple queries into one score for a given document. A hybrid query contains a list of one or more queries and independently calculates document scores at the shard level for each subquery. The subquery rewriting is performed at the coordinating node level in order to avoid duplicate computations. +To normalize and combine the subquery scores, either attach a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) to the request or add a `fusion` parameter to the query. For more information, see [Fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/). + ## Example -Before using a `hybrid` query, you must set up a machine learning (ML) model, ingest documents, and configure a search pipeline with a [`normalization-processor`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/). +Learn how to use the `hybrid` query by following the steps in [Hybrid search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/index/). -To learn how to set up an ML model, see [Choosing a model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/#choosing-a-model). - -Once you set up an ML model, learn how to use the `hybrid` query by following the steps in [Using hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/hybrid-search/#using-hybrid-search). - -For a comprehensive example, follow the [Neural search tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/semantic-search#tutorial). +For a comprehensive example, follow the [Getting started with semantic and hybrid search]({{site.url}}{{site.baseurl}}/ml-commons-plugin/semantic-search#tutorial). ## Parameters @@ -26,8 +23,246 @@ The following table lists all top-level parameters supported by `hybrid` queries Parameter | Description :--- | :--- -`queries` | An array of one or more query clauses that are used to match documents. A document must match at least one query clause in order to be returned in the results. The documents' relevance scores from all query clauses are combined into one score by applying a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/). The maximum number of query clauses is 5. Required. +`queries` | An array of one or more query clauses that are used to match documents. A document must match at least one query clause in order to be returned in the results. The documents' relevance scores from all query clauses are combined into one score, either by applying a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) or by specifying the `fusion` parameter. The maximum number of query clauses is 5. Required. +`weights` | An array of numbers that weight the query clauses when their scores are combined, one for each query clause, in the same order as the `queries` array. Each weight must be in the 0.0--1.0 range, and the weights must sum to `1.0`, within a tolerance of `0.01`. Applies both to queries that use a search pipeline and to queries in fusion mode. Optional. If not provided, all query clauses are weighted equally. For more information, see [Weighting subqueries](#weighting-subqueries). +`filter` | A filter to apply to all the subqueries of the hybrid query. The filter must be a single query object. To apply multiple filter conditions, combine them in a [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/). For more information, see [Hybrid search with pre-filtering]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/pre-filtering/). +`pagination_depth` | The maximum number of search results that each subquery returns from each shard. This bounds the set of documents that the search pipeline normalizes and combines, so it affects both the depth to which you can paginate and the resulting order. Valid values are integers from `1` to the value of [`index.max_result_window`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/) (10000 by default). Required if `from` is greater than `0`; otherwise optional. If not provided, each subquery returns up to `size` results from each shard. For more information, see [Paginating hybrid query results]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/pagination/). In fusion mode, this parameter is optional regardless of `from`; if specified without `fusion.window_size`, it raises the number of results that each subquery contributes to fusion. For more information, see [Candidate window size]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/#candidate-window-size). +`fusion` | Runs the query in fusion mode, in which OpenSearch normalizes and combines the subquery scores on the coordinating node. Contains the `normalization`, `combination`, `window_size`, and `source` parameters. A hybrid query that specifies `fusion` does not require a search pipeline. Optional. For more information, see [Fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/). -## Disabling hybrid queries +### Weighting subqueries +**Introduced 3.10** +{: .label .label-purple } -By default, hybrid queries are enabled. To disable hybrid queries in your cluster, set the `plugins.neural_search.hybrid_search_disabled` setting to `true` in `opensearch.yml`. \ No newline at end of file +By default, all query clauses contribute equally to the combined score. To weight them differently, add a `weights` array to the top-level `hybrid` query, containing one weight for each query clause, in the same order as the `queries` array. Each weight must be in the 0.0--1.0 range, and the weights must add to `1.0`. + +If the query uses a search pipeline, the pipeline must contain a normalization processor or a score ranker processor, and only the top-level `hybrid` query in the request's `query` field can specify `weights`. A `hybrid` query elsewhere in the request, such as in a `post_filter`, cannot. If the pipeline contains neither processor, add one or run the query in fusion mode. + +You can specify weights in the following locations. + +Location | Effect +:--- | :--- +`weights` in the `hybrid` query (recommended) | Applies to this request only, using a search pipeline or in fusion mode. Overrides the pipeline's weights. +`combination.parameters.weights` in the pipeline's [normalization processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/) or [score ranker processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/score-ranker-processor/) | Applies to every request that uses the pipeline. +`combination.parameters.weights` in the `fusion` object | Fusion mode only. Has the same effect as `weights` in the `hybrid` query. Specify one or the other, not both. + +The following request uses the search pipeline created in [Hybrid search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/index/#step-3-configure-a-search-pipeline) and assigns a weight of `0.3` to the `match` query and `0.7` to the `neural` query: + +```json +GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline +{ + "_source": { + "exclude": [ + "passage_embedding" + ] + }, + "query": { + "hybrid": { + "weights": [ + 0.3, + 0.7 + ], + "queries": [ + { + "match": { + "passage_text": { + "query": "Hi world" + } + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "bQ1J8ooBpBj3wT4HVUsb", + "k": 5 + } + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +The weights apply to the `arithmetic_mean`, `geometric_mean`, `harmonic_mean`, and `rrf` combination techniques in the same way as the processor's own `weights` parameter. For fusion mode examples, see [Weighting subqueries]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/#weighting-subqueries). + +When `explain` is set to `true`, the explanation lists the applied weights for the `arithmetic_mean`, `geometric_mean`, and `harmonic_mean` techniques. For more information, see [Hybrid search explain]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/explain/). + +### Rescoring hybrid queries +**Introduced 2.18** +{: .label .label-purple } + +You can use the [`rescore`]({{site.url}}{{site.baseurl}}/query-dsl/rescore/) parameter with hybrid queries. How rescoring interacts with a hybrid query depends on whether the query uses a search pipeline or runs in fusion mode. + +With standard queries, each shard applies the rescore query to its top results after the query runs, and the coordinating node merges the rescored results. With hybrid queries that use a search pipeline, rescoring is applied at the **shard level** to each subquery's results **independently**, before the normalization and combination pipeline runs. With hybrid queries in [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/#rescoring), rescoring is applied to the combined ranking after normalization and combination, as it is for standard queries. + +The processing order for hybrid queries that use a search pipeline with rescoring is as follows: + +1. Each subquery in the hybrid query executes on the shard, producing separate result sets. +2. The rescore query is applied to each subquery's results independently. +3. The rescored results are sent to the coordinating node. +4. The search pipeline (normalization processor or score ranker processor) normalizes and combines the rescored subquery scores. + +When using rescoring with hybrid queries that use a search pipeline, note the following considerations: + +- The `window_size` applies to each subquery's results individually, not to the combined result. +- You cannot use explicit sorting with rescoring. If you attempt to combine sorting with a rescore query in a hybrid search, OpenSearch returns an error. +- Rescoring is compatible with all score-based and rank-based normalization and combination techniques supported by the [normalization processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/) and [score ranker processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/score-ranker-processor/). + +The following example uses a `match_phrase` rescore query to boost documents containing the exact phrase "search engine" within a hybrid search that combines keyword matches across two fields: + +```json +POST /my-index/_search?search_pipeline=nlp-search-pipeline +{ + "query": { + "hybrid": { + "queries": [ + { + "match": { + "title": "search engine" + } + }, + { + "match": { + "description": "search engine" + } + } + ] + } + }, + "rescore": { + "window_size": 50, + "query": { + "rescore_query": { + "match_phrase": { + "title": { + "query": "search engine", + "slop": 2 + } + } + }, + "query_weight": 0.7, + "rescore_query_weight": 1.2 + } + } +} +``` +{% include copy-curl.html %} + +The response contains documents whose scores reflect both the initial hybrid query matching and the rescore boost: + +```json +{ + "took": 30, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.95, + "hits": [ + { + "_index": "my-index", + "_id": "1", + "_score": 0.95, + "_source": { + "title": "Building a search engine", + "description": "A guide to modern search engine architecture" + } + }, + { + "_index": "my-index", + "_id": "2", + "_score": 0.67, + "_source": { + "title": "Introduction to search", + "description": "Learn about search engine basics" + } + }, + { + "_index": "my-index", + "_id": "3", + "_score": 0.42, + "_source": { + "title": "Database engine tuning", + "description": "How to optimize your search queries" + } + } + ] + } +} +``` + +In this example, Document 1 ranks highest because the rescore `match_phrase` query boosts its score (its `title` field contains the exact phrase "search engine"). Document 2 contains the phrase only in the `description` field, so it receives a lower boost from the phrase match on `title`. Document 3 matches the individual terms "search" and "engine" across different fields but not as an exact phrase, so it receives the smallest boost. Because the rescore query is applied independently to each subquery's results at the shard level before normalization, the phrase boost influences the final combined scores. + +<!-- vale off --> +### min_score support for hybrid queries +<!-- vale on --> + +Starting with OpenSearch 3.5, the [`min_score`]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#request-body) parameter is applied after score normalization and combination. It can be used only when sorting by `_score` or when no explicit sort order is specified. If `min_score` is used with any other sorting criteria, the request results in an error. +{: .note} + +Starting with OpenSearch 3.5, you can use hybrid queries on indexes with more than 512 shards. OpenSearch automatically disables batched reduction to ensure proper score normalization across all shards. No configuration is required. Note that memory usage on the coordinating node may be higher for indexes with a large number of shards. The `_msearch` endpoint does not support automatic handling of batched reduction. For multi-search requests with hybrid queries across many shards, use the `_search` endpoint with index patterns or aliases instead. +{: .note} + +## Limitations + +Hybrid query is designed to be a top-level query in a search request. It cannot be nested inside other compound or wrapper queries such as `function_score`, `constant_score`, `script_score`, or `boosting`. This restriction also applies to multilevel nesting, for example, a `bool` query containing a `function_score` query that itself contains a `hybrid` query. Nesting a hybrid query inside these wrapper queries may produce a runtime error or silently bypass the normalization pipeline. In [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/#nesting-a-hybrid-query), a hybrid query can be nested inside a `bool` query, a `dis_max` query, or another hybrid query in fusion mode. + +Hybrid query uses a specialized scoring mechanism that is incompatible with wrapper queries. Wrapper queries use a different internal scorer that bypasses the hybrid query's per-subquery score collection, which is required for the normalization and combination pipeline to function correctly. + +To apply score-boosting functions to hybrid search results, replace the `hybrid` query with a `bool` query and move your subqueries into `should` clauses. This alternative works in all OpenSearch versions that support hybrid queries. + +For example, the following query is unsupported: + +```json +GET /my-index/_search?search_pipeline=my-pipeline +{ + "query": { + "function_score": { + "query": { + "hybrid": { + "queries": [ + {"match": {"title": "search terms"}}, + {"term": {"category": "books"}} + ] + } + }, + "functions": [{"field_value_factor": {"field": "popularity"}}] + } + } +} +``` + +Instead, use the following equivalent query: + +```json +GET /my-index/_search +{ + "query": { + "function_score": { + "query": { + "bool": { + "should": [ + {"match": {"title": "search terms"}}, + {"term": {"category": "books"}} + ] + } + }, + "functions": [{"field_value_factor": {"field": "popularity"}}] + } + } +} +``` +{% include copy-curl.html %} + +When using a `bool` query containing `should` clauses instead of a `hybrid` query, the search pipeline's normalization and combination processors are not applied. Instead, scores from the subqueries are combined using standard Boolean scoring (sum of matching clauses). The `function_score` functions are then applied to the combined score. +{: .note} diff --git a/_query-dsl/compound/index.md b/_query-dsl/compound/index.md index d1ad1e26..fcf048d4 100644 --- a/_query-dsl/compound/index.md +++ b/_query-dsl/compound/index.md @@ -3,10 +3,11 @@ layout: default title: Compound queries has_children: true has_toc: false -nav_order: 40 -redirect_from: - - /query-dsl/compound/index/ +nav_order: 50 +redirect_from: + - /opensearch/query-dsl/compound/index/ - /query-dsl/query-dsl/compound/ + - /query-dsl/compound/ --- # Compound queries diff --git a/_query-dsl/full-text/combined-fields.md b/_query-dsl/full-text/combined-fields.md new file mode 100644 index 00000000..c5ebeda8 --- /dev/null +++ b/_query-dsl/full-text/combined-fields.md @@ -0,0 +1,333 @@ +--- +layout: default +title: Combined fields +parent: Full-text queries +nav_order: 60 +--- + +# Combined fields query +**Introduced 3.2** +{: .label .label-purple } + +The `combined_fields` query treats multiple text fields as a unified field, using the BM25F algorithm for consistent relevance scoring. Unlike the [`cross_fields`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/multi-match/#cross-fields) type of `multi_match`, which executes separate queries per field, `combined_fields` processes all fields together, resulting in better performance and more accurate scoring. You can apply different field weights while maintaining unified scoring across all fields. + +All fields in a `combined_fields` query must be `text` fields and must use the same text analyzer. +{: .note } + +## Setup + +To follow along with the examples, index some sample documents: + +```json +POST /books/_bulk +{"index":{"_id":"1"}} +{"title":"Database Systems","description":"A comprehensive guide to database design and implementation"} +{"index":{"_id":"2"}} +{"title":"Introduction to Systems","description":"This book covers database architectures and distributed systems"} +``` +{% include copy-curl.html %} + +## Example + +The following example demonstrates field weights in a `combined_fields` query. The query searches for "database systems" across the `title` and `description` fields, with the `title` field weighted four times as heavily as the `description` field: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "database systems", + "fields": ["title^4", "description"] + } + } +} +``` +{% include copy-curl.html %} + +The response shows that "Database Systems" scores significantly higher than "Introduction to Systems" because both query terms appear in the heavily weighted `title` field: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.2924412, + "hits": [ + { + "_index": "books", + "_id": "1", + "_score": 0.2924412, + "_source": { + "title": "Database Systems", + "description": "A comprehensive guide to database design and implementation" + } + }, + { + "_index": "books", + "_id": "2", + "_score": 0.2239699, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +## Parameters + +The following table lists the parameters for the `combined_fields` query. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `query` | String | The query string to search for. Required. | +| `fields` | Array of strings | The fields to search. Supports field name patterns and field weights using the `^` syntax (for example, `title^2`). Required. | +| `operator` | String | The Boolean logic used to interpret the query string. Valid values are `OR` (default) and `AND`. Optional. | +| `minimum_should_match` | String | The minimum number of terms that must match for a document to be returned. Can be an absolute number, a percentage, or a combination. For more information, see [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). Optional. | +| `boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field's relevance. Values between 0.0 and 1.0 decrease the field's relevance. Default is 1.0. Optional. | +| `_name` | String | A name for the query that can be used to identify it in the response. Optional. | + +## Using the AND operator + +By default, the query uses the `OR` operator, meaning that documents matching any term in the query will be returned. You can change this to `AND` to require all terms to match: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "introduction systems", + "fields": ["title", "description"], + "operator": "AND" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the only document in which both terms ("introduction" and "systems") appear in the combined fields: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.4214915, + "hits": [ + { + "_index": "books", + "_id": "2", + "_score": 0.4214915, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +## Using minimum_should_match + +The `minimum_should_match` parameter lets you specify the minimum number of terms that must match for a document to be returned. For example, the following query requires at least 75% of the terms to match: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "comprehensive database architectures book", + "fields": ["title", "description"], + "minimum_should_match": "75%" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the only document matching at least 3 of the 4 query terms (75%): + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.6993829, + "hits": [ + { + "_index": "books", + "_id": "2", + "_score": 0.6993829, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +## Comparison with multi_match cross_fields + +The `combined_fields` query differs from `multi_match` with `type: cross_fields` in how it calculates relevance scores. While both query types search across multiple fields, `combined_fields` uses the BM25F algorithm to treat all fields as a single unified field for scoring purposes. This means that inverse document frequency (IDF) is calculated globally across all fields rather than per field, and term frequency normalization accounts for the combined length of all fields. This approach is particularly beneficial when you have fields of very different lengths, such as a short title field and a long body field, because it prevents shorter fields from being overweighted in the relevance calculation. Additionally, `combined_fields` uses term-centric matching, where query terms can be satisfied across any combination of fields, rather than requiring all terms to match within individual fields. + +The following example compares the two approaches using the same query. + +**Combined fields query**: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "database systems", + "fields": ["title", "description"] + } + } +} +``` +{% include copy-curl.html %} + +The `combined_fields` query calculates term frequency across all fields together, providing more accurate BM25F scoring: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.20001775, + "hits": [ + { + "_index": "books", + "_id": "1", + "_score": 0.20001775, + "_source": { + "title": "Database Systems", + "description": "A comprehensive guide to database design and implementation" + } + }, + { + "_index": "books", + "_id": "2", + "_score": 0.19373488, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +**Multi_match cross_fields query**: + +```json +GET /books/_search +{ + "query": { + "multi_match": { + "query": "database systems", + "fields": ["title", "description"], + "type": "cross_fields" + } + } +} +``` +{% include copy-curl.html %} + +The `cross_fields` approach executes separate queries per field and then combines the results, which can lead to less precise scoring: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.18051638, + "hits": [ + { + "_index": "books", + "_id": "1", + "_score": 0.18051638, + "_source": { + "title": "Database Systems", + "description": "A comprehensive guide to database design and implementation" + } + }, + { + "_index": "books", + "_id": "2", + "_score": 0.16574687, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +Notice that the `combined_fields` query produces higher relevance scores (0.20001775 compared to 0.18051638 for the top result). + +## Limitations + +Note the following limitations of the `combined_fields` query: + +- All fields must have the same text analyzer. +- The query only works with `text` fields. +- The query does not support per-field boosts in the same way as `multi_match`; instead, use field weights. diff --git a/_query-dsl/full-text/index.md b/_query-dsl/full-text/index.md index e1f5ab5f..556161e1 100644 --- a/_query-dsl/full-text/index.md +++ b/_query-dsl/full-text/index.md @@ -13,23 +13,24 @@ redirect_from: # Full-text queries -This page lists all full-text query types and common options. There are many optional fields that you can use to create subtle search behaviors, so we recommend that you test out some basic query types against representative indexes and verify the output before you perform more advanced or complex searches with multiple options. +Full-text queries analyze the query string before searching, making them suitable for natural language search on text fields. There are many optional fields that you can use to create subtle search behaviors, so we recommend that you test out some basic query types against representative indexes and verify the output before you perform more advanced or complex searches with multiple options. OpenSearch uses the Apache Lucene search library, which provides highly efficient data structures and algorithms for ingesting, indexing, searching, and aggregating data. -To learn more about search query classes, see [Lucene query JavaDocs](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/Query.html). +To learn more about search query classes, see [Lucene query JavaDocs](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/Query.html). The full-text query types shown in this section use the standard analyzer, which analyzes text automatically when the query is submitted. The following table lists all full-text query types. Query type | Description -:--- | :--- -[`intervals`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/intervals/) | Allows fine-grained control of the matching terms' proximity and order. +:--- | :--- [`match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/) | The default full-text query, which can be used for fuzzy matching and phrase or proximity searches. -[`match_bool_prefix`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-bool-prefix/) | Creates a [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/) that matches all terms in any position, treating the last term as a prefix. [`match_phrase`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) | Similar to the `match` query but matches a whole phrase up to a configurable slop. [`match_phrase_prefix`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase-prefix/) | Similar to the `match_phrase` query but matches terms as a whole phrase, treating the last term as a prefix. +[`match_bool_prefix`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-bool-prefix/) | Creates a [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/) that matches all terms in any position, treating the last term as a prefix. [`multi_match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/multi-match/) | Similar to the `match` query but is used on multiple fields. -[`query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | Uses a strict syntax to specify Boolean conditions and multi-field search within a single query string. -[`simple_query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/simple-query-string/) | A simpler, less strict version of `query_string` query. +[`combined_fields`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/combined-fields/) | Treats multiple text fields as a single field for better relevance scoring using BM25F. +[`simple_query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/simple-query-string/) | A simpler, less strict version of `query_string` query. +[`query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | Uses a strict syntax to specify Boolean conditions and multi-field search within a single query string. +[`intervals`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/intervals/) | Allows fine-grained control of the matching terms' proximity and order. diff --git a/_query-dsl/full-text/intervals.md b/_query-dsl/full-text/intervals.md index 082f8fbe..c57536c0 100644 --- a/_query-dsl/full-text/intervals.md +++ b/_query-dsl/full-text/intervals.md @@ -1,9 +1,8 @@ --- layout: default title: Intervals -nav_order: 80 +nav_order: 90 parent: Full-text queries -grand_parent: Query DSL --- # Intervals query @@ -143,6 +142,7 @@ Rule | Description [`match`](#the-match-rule) | Matches analyzed text. [`prefix`](#the-prefix-rule) | Matches terms that start with a specified set of characters. [`wildcard`](#the-wildcard-rule) | Matches terms using a wildcard pattern. +[`regexp`](#the-regexp-rule) | Matches terms using a regular expression. [`fuzzy`](#the-fuzzy-rule) | Matches terms that are similar to the provided term within a specified edit distance. [`all_of`](#the-all_of-rule) | Combines multiple rules using a conjunction (`AND`). [`any_of`](#the-any_of-rule) | Combines multiple rules using a disjunction (`OR`). @@ -183,6 +183,92 @@ Parameter | Required/Optional | Data type | Description Specifying patterns that start with `*` or `?` can hinder search performance because it increases the number of iterations required to match terms. {: .important} +## The `regexp` rule + +The `regexp` rule matches terms using a [regular expression]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/). The regular expression must match an entire term. By default, the regular expression can expand to match at most 128 terms in each index segment. If it matches more terms than the limit in a segment, an error is returned. To change the limit, specify the `max_expansions` parameter. The following table lists all parameters the `regexp` rule supports. + +Parameter | Required/Optional | Data type | Description +:--- | :--- | :--- | :--- +`pattern` | Required | String | The [regular expression]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/) used to match terms. +`flags` | Optional | String | Enables optional regular expression operators. Separate multiple operators with a vertical bar. For valid values, see [Optional operators]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/#optional-operators). Default is `ALL`. +`flags_value` | Optional | Integer | The `flags` expressed as an integer bit mask of Lucene regular expression syntax flags. If you specify both `flags` and `flags_value`, `flags_value` takes precedence. +`case_insensitive` | Optional | Boolean | If `true`, the `pattern` matches terms regardless of letter case. Default is `false`. +`max_expansions` | Optional | Integer | The maximum number of terms that the regular expression can expand to in each index segment. If the regular expression matches more terms in a segment, an error is returned. If the value is `0` or less, the default is used. The value cannot exceed the value of the [`indices.query.bool.max_clause_count`]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/) setting (default is `1024`). Default is `128`. +`use_field` | Optional | String | The field to search instead of the top-level `<field>`. The `pattern` is matched against the terms indexed in this field. + +The `regexp` rule does not accept an `analyzer` parameter, so the `pattern` is not analyzed or normalized. The pattern is matched exactly as written against the terms stored in the index. For example, a field that uses the `standard` analyzer stores lowercase terms, so the pattern `Stor(e|ed)` returns no results unless `case_insensitive` is set to `true`. + +### Example: Match word variants + +The following query uses the documents indexed at the beginning of this page. It searches for documents in which a term matching the regular expression `stor(e|ed)` (either `store` or `stored`) and the term `hash` have at most three positions between them: + +```json +GET /testindex/_search +{ + "query": { + "intervals": { + "title": { + "all_of": { + "max_gaps": 3, + "intervals": [ + { + "regexp": { + "pattern": "stor(e|ed)" + } + }, + { + "match": { + "query": "hash" + } + } + ] + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains only document 1. In document 1, the terms `stored` and `hash` have two terms between them (`in` and `a`). In document 2, the terms `store` and `hash` have five terms between them (`key`, `value`, `pairs`, `in`, and `a`), which exceeds the `max_gaps` value of `3`: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```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": "1", + "_score": 0.25, + "_source": { + "title": "key-value pairs are efficiently stored in a hash table" + } + } + ] + } +} +``` +</details> + ## The `fuzzy` rule The `fuzzy` rule matches terms that are similar to the provided term within a specified edit distance. The fuzzy pattern can expand to match at most 128 terms. If the pattern matches more than 128 terms, an error is returned. The following table lists all parameters the `fuzzy` rule supports. @@ -191,7 +277,7 @@ Parameter | Required/Optional | Data type | Description :--- | :--- | :--- | :--- `term` | Required | String | The term to match. `analyzer` | Optional | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to normalize the `term`. Default is the analyzer specified for the `<field>`. -`fuzziness` | Optional | String | The number of character edits (insert, delete, substitute) that it takes to change one word to another when determining whether a term matched a value. For example, the distance between `wined` and `wind` is 1. Valid values are non-negative integers or `AUTO`. The default, `AUTO`, chooses a value based on the length of each term and is a good choice for most use cases. +`fuzziness` | Optional | String | The maximum number of edits allowed when matching the term, specified as `0`, `1`, `2`, `AUTO`, or `AUTO:<low>,<high>`. Default is `AUTO`. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). `transpositions` | Optional | Boolean | Setting `transpositions` to `true` (default) adds swaps of adjacent characters to the insert, delete, and substitute operations of the `fuzziness` option. For example, the distance between `wind` and `wnid` is 1 if `transpositions` is true (swap "n" and "i") and 2 if it is false (delete "n", insert "n"). If `transpositions` is `false`, `rewind` and `wnid` have the same distance (2) from `wind`, despite the more human-centric opinion that `wnid` is an obvious typo. The default is a good choice for most use cases. `prefix_length`| Optional | Integer | The number of beginning characters left unchanged for fuzzy matching. Default is 0. `use_field` | Optional | String | Specifies to search this field instead of the top-level <field>. The `term` is normalized using the search analyzer specified for this field, unless you specify an `analyzer`. @@ -232,7 +318,7 @@ Parameter | Required/Optional | Data type | Description `overlapping` | Optional | Query object | A query used to return intervals that overlap with an interval specified in the filter rule. `script` | Optional | Script object | A script used to match documents. This script must return `true` or `false`. -#### Example: Filters +### Example: Filters The following query searches for documents containing the words `pairs` and `hash` that are within five positions of each other and don't contain the word `efficiently` between them: @@ -299,7 +385,7 @@ The response contains only document 2: ``` </details> -#### Example: Script filters +### Example: Script filters Alternatively, you can write your own script filter to include with the `intervals` query using the following variables: diff --git a/_query-dsl/full-text/match-bool-prefix.md b/_query-dsl/full-text/match-bool-prefix.md index 3a0d304c..d42d9f86 100644 --- a/_query-dsl/full-text/match-bool-prefix.md +++ b/_query-dsl/full-text/match-bool-prefix.md @@ -2,8 +2,7 @@ layout: default title: Match Boolean prefix parent: Full-text queries -grand_parent: Query DSL -nav_order: 20 +nav_order: 40 --- # Match Boolean prefix query @@ -217,8 +216,8 @@ The `<field>` accepts the following parameters. All parameters except `query` ar Parameter | Data type | Description :--- | :--- | :--- `query` | String | The text, number, Boolean value, or date to use for search. Required. -`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. -`fuzziness` | `AUTO`, `0`, or a positive integer | The number of character edits (insert, delete, substitute) that it takes to change one word to another when determining whether a term matched a value. For example, the distance between `wined` and `wind` is 1. The default, `AUTO`, chooses a value based on the length of each term and is a good choice for most use cases. +`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. For more information about `index.query.default_field`, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). +`fuzziness` | `AUTO`, `0`, or a positive integer | The maximum number of edits allowed when matching each term except the last, specified as `0`, `1`, `2`, `AUTO`, or `AUTO:<low>,<high>`. If not specified, terms must match exactly. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). `fuzzy_rewrite` | String | Determines how OpenSearch rewrites the query. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. If the `fuzziness` parameter is not `0`, the query uses a `fuzzy_rewrite` method of `top_terms_blended_freqs_${max_expansions}` by default. Default is `constant_score`. `fuzzy_transpositions` | Boolean | Setting `fuzzy_transpositions` to `true` (default) adds swaps of adjacent characters to the insert, delete, and substitute operations of the `fuzziness` option. For example, the distance between `wind` and `wnid` is 1 if `fuzzy_transpositions` is true (swap "n" and "i") and 2 if it is false (delete "n", insert "n"). If `fuzzy_transpositions` is false, `rewind` and `wnid` have the same distance (2) from `wind`, despite the more human-centric opinion that `wnid` is an obvious typo. The default is a good choice for most use cases. `max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. diff --git a/_query-dsl/full-text/match-phrase-prefix.md b/_query-dsl/full-text/match-phrase-prefix.md index 354dd35c..c87f89c8 100644 --- a/_query-dsl/full-text/match-phrase-prefix.md +++ b/_query-dsl/full-text/match-phrase-prefix.md @@ -2,15 +2,19 @@ layout: default title: Match phrase prefix parent: Full-text queries -grand_parent: Query DSL -nav_order: 40 +nav_order: 30 --- # Match phrase prefix query -Use the `match_phrase_prefix` query to specify a phrase to match in order. The documents that contain the phrase you specify will be returned. The last partial term in the phrase is interpreted as a prefix, so any documents that contain phrases that begin with the phrase and prefix of the last term will be returned. +Use the `match_phrase_prefix` query to search for documents that contain the terms of a phrase in the order you specify. The last term in the phrase is interpreted as a prefix, so the query matches any phrase that begins with the preceding terms and continues with a word that starts with the last term. For example, `chocolate chip c` matches `chocolate chip cookies` and `mint chocolate chip cake` but not `cookies with chocolate chip`. -Similar to [match phrase]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/), but creates a [prefix query](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PrefixQuery.html) out of the last term in the query string. +The `match_phrase_prefix` query works similarly to the [match phrase]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) query but creates a [prefix query](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/PrefixQuery.html) out of the last term in the query string. If the query string contains only one term, the query is a prefix query on that term. + +Use the `match_phrase_prefix` query in the following scenarios: + +- Finding documents that contain a known phrase when only the beginning of its last word is available. +- Adding basic search-as-you-type functionality to a text field without changing the mapping. For differences between the `match_phrase_prefix` and the `match_bool_prefix` queries, see [The `match_bool_prefix` and `match_phrase_prefix` queries]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-bool-prefix/#the-match_bool_prefix-and-match_phrase_prefix-queries). @@ -90,7 +94,7 @@ The response contains the matching document: ```json { - "took": 6, + "took": 4, "timed_out": false, "_shards": { "total": 1, @@ -103,12 +107,12 @@ The response contains the matching document: "value": 1, "relation": "eq" }, - "max_score": 0.92980814, + "max_score": 0.42264006, "hits": [ { "_index": "testindex", "_id": "1", - "_score": 0.92980814, + "_score": 0.42264006, "_source": { "title": "The wind rises" } @@ -127,7 +131,7 @@ The query accepts the name of the field (`<field>`) as a top-level parameter: GET _search { "query": { - "match_phrase": { + "match_phrase_prefix": { "<field>": { "query": "text to search for", ... @@ -142,7 +146,26 @@ The `<field>` accepts the following parameters. All parameters except `query` ar Parameter | Data type | Description :--- | :--- | :--- -`query` | String | The query string to use for search. Required. -`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query. -`max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. -`slop` | `0` (default) or a positive integer | Controls the degree to which words in a query can be misordered and still be considered a match. From the [Lucene documentation](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html#getSlop--): "The number of other words permitted between words in query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit reorderings of phrases, the slop must be at least two. A value of zero requires an exact match." \ No newline at end of file +`query` | String | The query string to use for search. OpenSearch analyzes the query string into terms and treats the last term as a prefix. Required. +`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string. Default is the search analyzer mapped for the `<field>`. If no analyzer is mapped, the index's default analyzer is used. +`max_expansions` | Positive integer | The maximum number of terms to which the last term in the query string can expand. For more information, see [Using the match phrase prefix query for autocomplete](#using-the-match-phrase-prefix-query-for-autocomplete). Default is `50`. +`slop` | `0` (default) or a positive integer | Controls the degree to which words in a query can be misordered and still be considered a match. From the [Lucene documentation](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/PhraseQuery.html#getSlop--): "The number of other words permitted between words in query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit reorderings of phrases, the slop must be at least two. A value of zero requires an exact match." For example, the query `wind the` matches the title `Gone with the wind` only if `slop` is at least `2`. +`zero_terms_query` | String | In some cases, the analyzer removes all terms from a query string. For example, the `stop` analyzer removes all terms from the string `the`. In those cases, `zero_terms_query` specifies whether to match no documents (`none`) or all documents (`all`). Valid values are `none` and `all`. Default is `none`. + +The `match_phrase_prefix` query does not support the `fuzziness` parameter. +{: .note} + +## Using the match phrase prefix query for autocomplete + +The `match_phrase_prefix` query requires no special mapping, which makes it a quick way to add autocomplete to a search box. However, it can return incomplete results because of the way it expands the last term. + +For the query `chocolate chip c`, OpenSearch builds a phrase query that requires `chocolate` to be followed by `chip` and then expands the prefix `c` to the first `max_expansions` terms that start with `c` in the field's term dictionary. These terms are selected in alphabetical order, not by relevance, so if many terms that start with `c` sort before `cookies`, documents containing `chocolate chip cookies` are not returned. + +In a search-as-you-type experience, this is usually acceptable because each additional letter narrows the prefix until the missing term appears. Increasing `max_expansions` returns more matches but makes the query more expensive to run. + +For autocomplete that is both complete and efficient, use one of the following approaches, which prepare prefixes at index time: + +- The [completion suggester]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/#completion-suggester), which uses the [`completion`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/completion/) field type to return suggestions quickly from an in-memory data structure. +- The [`search_as_you_type`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/search-as-you-type/) field type, which indexes shingles and edge n-grams of a text field so that prefix matches do not need to be expanded at query time. + +For a comparison of autocomplete approaches, see [Autocomplete]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/). diff --git a/_query-dsl/full-text/match-phrase.md b/_query-dsl/full-text/match-phrase.md index 18dd6a85..2caceae9 100644 --- a/_query-dsl/full-text/match-phrase.md +++ b/_query-dsl/full-text/match-phrase.md @@ -2,15 +2,14 @@ layout: default title: Match phrase parent: Full-text queries -grand_parent: Query DSL -nav_order: 30 +nav_order: 20 --- # Match phrase query Use the `match_phrase` query to match documents that contain an exact phrase in a specified order. You can add flexibility to phrase matching by providing the `slop` parameter. -The `match_phrase` query creates a [phrase query](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html) that matches a sequence of terms. +The `match_phrase` query creates a [phrase query](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/PhraseQuery.html) that matches a sequence of terms. The following example shows a basic `match_phrase` query: @@ -269,6 +268,6 @@ The `<field>` accepts the following parameters. All parameters except `query` ar Parameter | Data type | Description :--- | :--- | :--- `query` | String | The query string to use for search. Required. -`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. -`slop` | `0` (default) or a positive integer | Controls the degree to which words in a query can be misordered and still be considered a match. From the [Lucene documentation](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html#getSlop--): "The number of other words permitted between words in query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit reorderings of phrases, the slop must be at least two. A value of zero requires an exact match." +`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. For more information about `index.query.default_field`, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). +`slop` | `0` (default) or a positive integer | Controls the degree to which words in a query can be misordered and still be considered a match. From the [Lucene documentation](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/PhraseQuery.html#getSlop--): "The number of other words permitted between words in query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit reorderings of phrases, the slop must be at least two. A value of zero requires an exact match." `zero_terms_query` | String | In some cases, the analyzer removes all terms from a query string. For example, the `stop` analyzer removes all terms from the string `an but this`. In those cases, `zero_terms_query` specifies whether to match no documents (`none`) or all documents (`all`). Valid values are `none` and `all`. Default is `none`. \ No newline at end of file diff --git a/_query-dsl/full-text/match.md b/_query-dsl/full-text/match.md index 746a4cf5..3ef1c4df 100644 --- a/_query-dsl/full-text/match.md +++ b/_query-dsl/full-text/match.md @@ -2,13 +2,12 @@ layout: default title: Match parent: Full-text queries -grand_parent: Query DSL nav_order: 10 --- # Match query -Use the `match` query for full-text search on a specific document field. If you run a `match` query on a [`text`]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) field, the `match` query [analyzes]({{site.url}}{{site.baseurl}}/analyzers/index/) the provided search string and returns documents that match any of the string's terms. If you run a `match` query on an exact-value field, it returns documents that match the exact value. The preferred way to search exact-value fields is to use a filter because, unlike a query, a filter is cached. +Use the `match` query for full-text search on a specific document field. If you run a `match` query on a [`text`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) field, the `match` query [analyzes]({{site.url}}{{site.baseurl}}/analyzers/index/) the provided search string and returns documents that match any of the string's terms. If you run a `match` query on an exact-value field, it returns documents that match the exact value. To search exact-value fields, use a [`term`]({{site.url}}{{site.baseurl}}/query-dsl/term/term/) query in a filter context, which does not calculate relevance scores. For more information, see [Query and filter context]({{site.url}}{{site.baseurl}}/query-dsl/query-filter-context/). The following example shows a basic `match` query for the word `wind` in the `title`: @@ -99,7 +98,7 @@ The query is constructed as `wind AND rise` and returns document 1 as the matchi ```json { - "took": 17, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -112,12 +111,12 @@ The query is constructed as `wind AND rise` and returns document 1 as the matchi "value": 1, "relation": "eq" }, - "max_score": 1.2667098, + "max_score": 0.41195536, "hits": [ { "_index": "testindex", "_id": "1", - "_score": 1.2667098, + "_score": 0.41195536, "_source": { "title": "Let the wind rise" } @@ -159,7 +158,7 @@ Now documents are required to match both terms, so only document 1 is returned ( ```json { - "took": 23, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -172,12 +171,12 @@ Now documents are required to match both terms, so only document 1 is returned ( "value": 1, "relation": "eq" }, - "max_score": 1.2667098, + "max_score": 0.41195536, "hits": [ { "_index": "testindex", "_id": "1", - "_score": 1.2667098, + "_score": 0.41195536, "_source": { "title": "Let the wind rise" } @@ -190,7 +189,7 @@ Now documents are required to match both terms, so only document 1 is returned ( ## Analyzer -Because in this example you didn't explicitly specify the analyzer, the default `standard` analyzer is used. The default analyzer does not perform stemming, so if you run a query `the wind rises`, you receive no results because the token `rises` does not match the token `rise`. To change the search analyzer, specify it in the `analyzer` field. For example, the following query uses the `english` analyzer: +Because in this example you didn't explicitly specify the analyzer, the default `standard` analyzer is used. The default analyzer does not perform stemming, so with the `and` operator, the query `the wind rises` returns no results because the token `rises` does not match the token `rise`. To change the search analyzer, specify it in the `analyzer` field. For example, the following query uses the `english` analyzer: ```json GET testindex/_search @@ -208,7 +207,7 @@ GET testindex/_search ``` {% include copy-curl.html %} -The `english` analyzer removes the stopword `the` and performs stemming, producing the tokens `wind` and `rise`. The latter token matches document 1, which is returned in the results: +The `english` analyzer removes the stopword `the` and performs stemming, producing the tokens `wind` and `rise`. Both tokens are in document 1, so it is returned in the results: <details markdown="block"> <summary> @@ -218,7 +217,7 @@ The `english` analyzer removes the stopword `the` and performs stemming, produci ```json { - "took": 19, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -231,12 +230,12 @@ The `english` analyzer removes the stopword `the` and performs stemming, produci "value": 1, "relation": "eq" }, - "max_score": 1.2667098, + "max_score": 0.41195536, "hits": [ { "_index": "testindex", "_id": "1", - "_score": 1.2667098, + "_score": 0.41195536, "_source": { "title": "Let the wind rise" } @@ -288,15 +287,9 @@ GET testindex/_search ## Fuzziness -To account for typos, you can specify `fuzziness` for your query as either of the following: +To account for typos, specify `fuzziness` in the query. For information about the supported values, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). -- An integer that specifies the maximum allowed [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) for this edit. -- `AUTO`: - - Strings of 0–2 characters must match exactly. - - Strings of 3–5 characters allow 1 edit. - - Strings longer than 5 characters allow 2 edits. - -Setting `fuzziness` to the default `AUTO` value works best in most cases: +Setting `fuzziness` to the `AUTO` value works best in most cases: ```json GET testindex/_search @@ -323,7 +316,7 @@ The token `wnid` matches `wind` and the query returns documents 1 and 2: ```json { - "took": 31, + "took": 2, "timed_out": false, "_shards": { "total": 1, @@ -336,12 +329,12 @@ The token `wnid` matches `wind` and the query returns documents 1 and 2: "value": 2, "relation": "eq" }, - "max_score": 0.47501624, + "max_score": 0.15448327, "hits": [ { "_index": "testindex", "_id": "1", - "_score": 0.47501624, + "_score": 0.15448327, "_source": { "title": "Let the wind rise" } @@ -349,7 +342,7 @@ The token `wnid` matches `wind` and the query returns documents 1 and 2: { "_index": "testindex", "_id": "2", - "_score": 0.47501624, + "_score": 0.15448327, "_source": { "title": "Gone with the wind" } @@ -404,19 +397,76 @@ GET testindex/_search Now the query returns no results. +### Fuzziness and synonyms + +Fuzzy matching is not applied to query terms that have synonyms or to any other terms for which the analyzer produces several tokens at the same position. OpenSearch combines these tokens into a synonym query, which blends their term frequencies and does not support fuzzy expansion. For an example, see [Synonyms](#synonyms). + ## Synonyms -If you use a `synonym_graph` filter and `auto_generate_synonyms_phrase_query` is set to `true` (default), OpenSearch parses the query into terms and then combines the terms to generate a [phrase query](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html) for multi-term synonyms. For example, if you specify `ba,batting average` as synonyms and search for `ba`, OpenSearch searches for `ba OR "batting average"`. +If the search analyzer of a field contains a [`synonym_graph`]({{site.url}}{{site.baseurl}}/analyzers/token-filters/synonym-graph/) token filter, the `match` query expands query terms into their synonyms. For multi-term synonyms, the `auto_generate_synonyms_phrase_query` parameter determines whether the terms of the synonym must appear together as a phrase. -To match multi-term synonyms with conjunctions, set `auto_generate_synonyms_phrase_query` to `false`: +The following request creates a `furniture` index whose `name` field uses a search analyzer containing two synonym rules: `sofa, couch` and the multi-term synonym `sleeper, sofa bed`: ```json -GET /testindex/_search +PUT furniture +{ + "settings": { + "analysis": { + "filter": { + "furniture_synonyms": { + "type": "synonym_graph", + "synonyms": [ + "sofa, couch", + "sleeper, sofa bed" + ] + } + }, + "analyzer": { + "synonym_search": { + "tokenizer": "standard", + "filter": [ "lowercase", "furniture_synonyms" ] + } + } + } + }, + "mappings": { + "properties": { + "name": { + "type": "text", + "search_analyzer": "synonym_search" + } + } + } +} +``` +{% include copy-curl.html %} + +Index the following documents: + +```json +POST furniture/_bulk?refresh +{ "index": { "_id": "1" } } +{ "name": "Leather sofas" } +{ "index": { "_id": "2" } } +{ "name": "Velvet couch" } +{ "index": { "_id": "3" } } +{ "name": "Convertible sofa bed" } +{ "index": { "_id": "4" } } +{ "name": "Bed frame" } +{ "index": { "_id": "5" } } +{ "name": "Bed with sofa cushions" } +``` +{% include copy-curl.html %} + +By default, `auto_generate_synonyms_phrase_query` is `true`, so a search for `sleeper` matches `sleeper` or the phrase `"sofa bed"` and returns only document 3. To match the terms of a multi-term synonym in any position, set `auto_generate_synonyms_phrase_query` to `false`: + +```json +GET furniture/_search { "query": { "match": { - "text": { - "query": "good ba", + "name": { + "query": "sleeper", "auto_generate_synonyms_phrase_query": false } } @@ -425,7 +475,46 @@ GET /testindex/_search ``` {% include copy-curl.html %} -The query produced is `ba OR (batting AND average)`. +The query is rewritten as `sleeper OR (sofa AND bed)`, so it returns document 3 and document 5, which contains both `sofa` and `bed` but not as a phrase. To see how OpenSearch rewrites a query, use the [Validate Query API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/validate/) with the `explain` parameter. For the preceding query, the explanation is `((+name:sofa +name:bed) name:sleeper)`. + +Because `sofa` has a synonym, a fuzzy search for `sofa` does not match the plural `sofas` in document 1, even though `sofas` is within one edit of `sofa`: + +```json +GET furniture/_validate/query?explain +{ + "query": { + "match": { + "name": { + "query": "sofa", + "fuzziness": "AUTO" + } + } + } +} +``` +{% include copy-curl.html %} + +The explanation shows a synonym query for `sofa` and `couch` with no fuzzy expansion: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true, + "explanations": [ + { + "index": "furniture", + "valid": true, + "explanation": "Synonym(name:couch name:sofa)" + } + ] +} +``` + +Fuzziness still applies to the other terms in the query. For example, in the query `leathr sofa`, the term `leathr` is expanded to `leathr~2`, while `sofa` is expanded only to its synonyms. ## Parameters @@ -444,7 +533,6 @@ GET _search } } ``` -{% include copy-curl.html %} The `<field>` accepts the following parameters. All parameters except `query` are optional. @@ -452,15 +540,15 @@ Parameter | Data type | Description :--- | :--- | :--- `query` | String | The query string to use for search. Required. `auto_generate_synonyms_phrase_query` | Boolean | Specifies whether to create a [match phrase query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) automatically for multi-term synonyms. For example, if you specify `ba,batting average` as synonyms and search for `ba`, OpenSearch searches for `ba OR "batting average"` (if this option is `true`) or `ba OR (batting AND average)` (if this option is `false`). Default is `true`. -`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. +`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the search analyzer mapped for the `<field>`. If no analyzer is mapped for the `<field>`, the default analyzer for the index is used. `boost` | Floating-point | Boosts the clause by the given multiplier. Useful for weighing clauses in compound queries. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. `enable_position_increments` | Boolean | When `true`, resulting queries are aware of position increments. This setting is useful when the removal of stop words leaves an unwanted "gap" between terms. Default is `true`. -`fuzziness` | String | The number of character edits (insert, delete, substitute) that it takes to change one word to another when determining whether a term matched a value. For example, the distance between `wined` and `wind` is 1. Valid values are non-negative integers or `AUTO`. The default, `AUTO`, chooses a value based on the length of each term and is a good choice for most use cases. -`fuzzy_rewrite` | String | Determines how OpenSearch rewrites the query. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. If the `fuzziness` parameter is not `0`, the query uses a `fuzzy_rewrite` method of `top_terms_blended_freqs_${max_expansions}` by default. Default is `constant_score`. +`fuzziness` | String | The maximum number of edits allowed when matching each term, specified as `0`, `1`, `2`, `AUTO`, or `AUTO:<low>,<high>`. If not specified, terms must match exactly. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). +`fuzzy_rewrite` | String | Determines how OpenSearch rewrites the query. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. If the `fuzziness` parameter is not `0`, the query uses a `fuzzy_rewrite` method of `top_terms_blended_freqs_${max_expansions}` by default. `fuzzy_transpositions` | Boolean | Setting `fuzzy_transpositions` to `true` (default) adds swaps of adjacent characters to the insert, delete, and substitute operations of the `fuzziness` option. For example, the distance between `wind` and `wnid` is 1 if `fuzzy_transpositions` is true (swap "n" and "i") and 2 if it is false (delete "n", insert "n"). If `fuzzy_transpositions` is false, `rewind` and `wnid` have the same distance (2) from `wind`, despite the more human-centric opinion that `wnid` is an obvious typo. The default is a good choice for most use cases. `lenient` | Boolean | Setting `lenient` to `true` ignores data type mismatches between the query and the document field. For example, a query string of `"8.2"` could match a field of type `float`. Default is `false`. `max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. `minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | If the query string contains multiple search terms and you use the `or` operator, the number of terms that need to match for the document to be considered a match. For example, if `minimum_should_match` is 2, `wind often rising` does not match `The Wind Rises.` If `minimum_should_match` is `1`, it matches. For details, see [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). `operator` | String | If the query string contains multiple search terms, whether all terms need to match (`AND`) or only one term needs to match (`OR`) for a document to be considered a match. Valid values are:<br>- `OR`: The string `to be` is interpreted as `to OR be`<br>- `AND`: The string `to be` is interpreted as `to AND be`<br> Default is `OR`. `prefix_length` | Non-negative integer | The number of leading characters that are not considered in fuzziness. Default is `0`. -`zero_terms_query` | String | In some cases, the analyzer removes all terms from a query string. For example, the `stop` analyzer removes all terms from the string `an but this`. In those cases, `zero_terms_query` specifies whether to match no documents (`none`) or all documents (`all`). Valid values are `none` and `all`. Default is `none`. \ No newline at end of file +`zero_terms_query` | String | In some cases, the analyzer removes all terms from a query string. For example, the `stop` analyzer removes all terms from the string `an but this`. In those cases, `zero_terms_query` specifies whether to match no documents (`none`) or all documents (`all`). Valid values are `none` and `all`. Default is `none`. diff --git a/_query-dsl/full-text/multi-match.md b/_query-dsl/full-text/multi-match.md index 7450b747..f2711f2c 100644 --- a/_query-dsl/full-text/multi-match.md +++ b/_query-dsl/full-text/multi-match.md @@ -2,15 +2,21 @@ layout: default title: Multi-match parent: Full-text queries -grand_parent: Query DSL nav_order: 50 --- # Multi-match queries -A multi-match operation functions similarly to the [match]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/) operation. You can use a `multi_match` query to search multiple fields. +A `multi_match` query runs a [`match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/) query against several fields at once and combines the per-field results into one score. The `type` parameter controls how the fields are combined. -The `^` "boosts" certain fields. Boosts are multipliers that weigh matches in one field more heavily than matches in other fields. In the following example, a match for "wind" in the title field influences `_score` four times as much as a match in the plot field: +Use a `multi_match` query in the following scenarios: + +- Searching a title and a body field, where a match in the title should count for more. +- Searching the same text indexed using several analyzers, such as a stemmed and an unstemmed subfield. +- Searching structured data in which one concept is split across fields, such as a first name and a last name. +- Building search-as-you-type experiences across several fields by using the `phrase_prefix` or `bool_prefix` type. + +Use the `^` operator to boost certain fields. Boosts are multipliers that weigh matches in one field more heavily than matches in other fields. In the following example, a match for "wind" in the title field influences `_score` four times as much as a match in the plot field: ```json GET _search @@ -27,7 +33,7 @@ GET _search The result is that films like *The Wind Rises* and *Gone with the Wind* are near the top of the search results, and films like *Twister*, which presumably have "wind" in their plot summaries, are near the bottom. -You can use wildcards in the field name. For example, the following query will search the `speaker` field and all fields that start with `play_`, for example, `play_name` or `play_title`: +You can use wildcards in the field name. For example, the following query searches the `speaker` field and all fields that start with `play_`, for example, `play_name` or `play_title`: ```json GET _search @@ -42,9 +48,9 @@ GET _search ``` {% include copy-curl.html %} -If you don't provide the `fields` parameter, `multi_match` query searches the fields specified in the `index.query. Default_field` setting, which defaults to `*`. The default behavior is to extract all fields in the mapping that are eligible for [term-level queries]({{site.url}}{{site.baseurl}}/query-dsl/term/index/), filter the metadata fields, and combine all extracted fields to build a query. +If you don't provide the `fields` parameter, the `multi_match` query searches the fields specified in the `index.query.default_field` setting, which defaults to `*`. The `*` value selects all fields in the mapping that are eligible for [term-level queries]({{site.url}}{{site.baseurl}}/query-dsl/term/index/), excluding metadata fields, and the query searches all of them. -The maximum number of clauses in a query is defined in the `indices.query.bool.max_clause_count` setting, which defaults to 1,024. +Each field adds at least one clause to the query, and the total number of clauses is limited by the `indices.query.bool.max_clause_count` setting, which defaults to 1,024. Searching many fields, either explicitly or by using a wildcard pattern such as `*`, can exceed this limit. {: .note} ## Multi-match query types @@ -52,15 +58,17 @@ The maximum number of clauses in a query is defined in the `indices.query.bool.m OpenSearch supports the following multi-match query types, which differ in the way the query is executed internally: - [`best_fields`](#best-fields) (default): Returns documents that match any field. Uses the `_score` of the best-matching field. -- [`most_fields`](#most-fields): Returns documents that match any field. Uses a combined score of each matching field. -- [`cross_fields`](#cross-fields): Treats all fields as if they were one field. Processes fields with the same `analyzer` and matches words in any field. +- [`most_fields`](#most-fields): Returns documents that match any field. Uses the sum of the scores of all matching fields. +- [`cross_fields`](#cross-fields): Treats fields that have the same analyzer as one field and searches for each term in any of them. - [`phrase`](#phrase): Runs a `match_phrase` query on each field. Uses the `_score` of the best-matching field. - [`phrase_prefix`](#phrase-prefix): Runs a `match_phrase_prefix` query on each field. Uses the `_score` of the best-matching field. -- [`bool_prefix`](#boolean-prefix): Runs a `match_bool_prefix` query on each field. Uses a combined score of each matched field. +- [`bool_prefix`](#boolean-prefix): Runs a `match_bool_prefix` query on each field. Uses the sum of the scores of all matching fields. + +The `best_fields` and `most_fields` types are field centric: they build one query for each field and then combine the per-field scores. The `cross_fields` type is term centric: it looks up each query term across all fields together. Not every parameter applies to every type. For more information, see [Parameter support by type](#parameter-support-by-type). ## Best fields -If you're searching for two words that specify a concept, you want the results where the two words are next to each other to score higher. +Use the `best_fields` type when the query terms are most meaningful if they appear together in the same field. For example, `northern lights` in a single field is a stronger match than `northern` in one field and `lights` in another. For example, consider an index that contains the following scientific articles: @@ -120,7 +128,7 @@ The results contain both documents, but document 1 is scored higher because both ```json { - "took": 30, + "took": 5, "timed_out": false, "_shards": { "total": 1, @@ -133,12 +141,12 @@ The results contain both documents, but document 1 is scored higher because both "value": 2, "relation": "eq" }, - "max_score": 0.84407747, + "max_score": 0.38367155, "hits": [ { "_index": "articles", "_id": "1", - "_score": 0.84407747, + "_score": 0.38367155, "_source": { "title": "Aurora borealis", "description": "Northern lights, or aurora borealis, explained" @@ -147,7 +155,7 @@ The results contain both documents, but document 1 is scored higher because both { "_index": "articles", "_id": "2", - "_score": 0.6322521, + "_score": 0.2873873, "_source": { "title": "Sun deprivation in the Northern countries", "description": "Using fluorescent lights for therapy" @@ -164,10 +172,12 @@ Take the score of the best-matching field and add (`tie_breaker` * `_score`) for ## Most fields -Use the `most_fields` query for multiple fields that contain the same text that is analyzed in different ways. For example, the original field may contain text analyzed with the `standard` analyzer and another field may contain the same text analyzed with the `english` analyzer, which performs stemming: +Use the `most_fields` query for multiple fields that contain the same text that is analyzed in different ways. For example, the original field may contain text analyzed with the `standard` analyzer and another field may contain the same text analyzed with the `english` analyzer, which performs stemming. The stemmed field matches the most documents, and the unstemmed field moves the closest matches to the top of the results. + +The following request creates a `recipes` index in which the `title` field has an `english` subfield: ```json -PUT /articles +PUT /recipes { "mappings": { "properties": { @@ -186,10 +196,10 @@ PUT /articles ``` {% include copy-curl.html %} -Consider the following two documents that are indexed in the `articles` index: +Consider the following two documents that are indexed in the `recipes` index: ```json -PUT /articles/_doc/1 +PUT /recipes/_doc/1 { "title": "Buttered toasts" } @@ -197,19 +207,19 @@ PUT /articles/_doc/1 {% include copy-curl.html %} ```json -PUT /articles/_doc/2 +PUT /recipes/_doc/2 { "title": "Buttering a toast" } ``` {% include copy-curl.html %} -The `standard` analyzer analyzes the title `Buttered toast` into [`buttered`, `toasts`] and the title `Buttering a toast` into [`buttering`, `a`, `toast`]. On the other hand, the `english` analyzer produces the same token list [`butter`, `toast`] for both titles because of stemming. +The `standard` analyzer analyzes the title `Buttered toasts` into [`buttered`, `toasts`] and the title `Buttering a toast` into [`buttering`, `a`, `toast`]. On the other hand, the `english` analyzer produces the same token list [`butter`, `toast`] for both titles because it applies stemming and removes the stopword `a`. -You can use the `most_fields` query in order to return as many documents as possible: +The following `most_fields` query searches both the `title` field and its `english` subfield: ```json -GET /articles/_search +GET /recipes/_search { "query": { "multi_match": { @@ -228,26 +238,26 @@ GET /articles/_search The preceding query is executed as the following Boolean query: ```json -GET articles/_search +GET recipes/_search { "query": { "bool": { "should": [ - { "match": { "title": "buttered toasts" }}, - { "match": { "title.english": "buttered toasts" }} + { "match": { "title": "buttered toast" }}, + { "match": { "title.english": "buttered toast" }} ] } } } ``` -To calculate the relevance score, a document's scores for all `match` clauses are added together and then the result is divided by the number of `match` clauses. +To calculate the relevance score, OpenSearch adds together the scores of all `match` clauses that match the document. -Including the `title.english` field retrieves the second document that matches the stemmed tokens: +Both documents match the `title.english` field equally because their stemmed tokens are identical. In the `title` field, document 1 matches the term `buttered` and document 2 matches the term `toast`. Each term appears in only one document, but the `title` field of document 1 contains fewer tokens, so its match scores higher. Without the `title.english` field, documents that use a different form of a word, such as `buttering`, would match only on the remaining terms: ```json { - "took": 9, + "took": 2, "timed_out": false, "_shards": { "total": 1, @@ -260,20 +270,20 @@ Including the `title.english` field retrieves the second document that matches t "value": 2, "relation": "eq" }, - "max_score": 1.4418206, + "max_score": 0.508889, "hits": [ { - "_index": "articles", + "_index": "recipes", "_id": "1", - "_score": 1.4418206, + "_score": 0.508889, "_source": { "title": "Buttered toasts" } }, { - "_index": "articles", + "_index": "recipes", "_id": "2", - "_score": 0.09304003, + "_score": 0.4569852, "_source": { "title": "Buttering a toast" } @@ -283,7 +293,7 @@ Including the `title.english` field retrieves the second document that matches t } ``` -Because both `title` and `title.english` fields match for the first document, it has a higher relevance score. +Document 1 scores `0.34314215` for the `title` field and `0.16574687` for the `title.english` field, and its final score is the sum of the two, `0.508889`. ## Operator and minimum should match @@ -312,7 +322,7 @@ PUT customers/_doc/2 If you're searching for `John Doe` in the `customers` index, you might construct the following query: ```json -GET customers/_validate/query?explain +GET customers/_search { "query": { "multi_match" : { @@ -326,7 +336,7 @@ GET customers/_validate/query?explain ``` {% include copy-curl.html %} -The intent of the `and` operator in this query is to find a document that matches `John` and `Doe`. However, the query does not return any results. You can learn how the query is executed by running the Validate API: +The intent of the `and` operator in this query is to find a document that matches `John` and `Doe`. However, the query does not return any results. You can learn how the query is executed by running the [Validate Query API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/validate/): ```json GET customers/_validate/query?explain @@ -357,7 +367,7 @@ From the response, you can see that the query is trying to match both `John` and { "index": "customers", "valid": true, - "explanation": "((+first_name:john +first_name:doe) | (+last_name:john +last_name:doe))" + "explanation": "((+last_name:john +last_name:doe) | (+first_name:john +first_name:doe))" } ] } @@ -365,7 +375,7 @@ From the response, you can see that the query is trying to match both `John` and Because neither field contains both words, no results are returned. -A better alternative for searching across fields is to use the [`cross_fields`](#cross-fields) query. Unlike the field-centric `best_fields` and `most_fields` queries, `cross_fields` query is term-centric. +A better alternative for searching across fields is to use the [`cross_fields`](#cross-fields) query. Unlike the field-centric `best_fields` and `most_fields` queries, the `cross_fields` query is term centric. ## Cross fields @@ -376,6 +386,8 @@ The `most_fields` query does not work in this case because of the following prob - The [`operator` and `minimum_should_match`](#operator-and-minimum-should-match) parameters are applied on a field basis instead of on a term basis. - Term frequencies in the `first_name` and `last_name` fields can lead to unexpected results. For example, if someone's first name happens to be `Doe`, a document with this name will be presumed a better match because this first name will not appear in any other documents. +One way to avoid both problems is to copy the values of `first_name` and `last_name` into a single `full_name` field at index time by using the [`copy_to`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/copy-to/) mapping parameter and then search that field. The `cross_fields` query solves the same problems at query time, without changes to the mapping. + The `cross_fields` query analyzes the query string into individual terms and then searches for each of the terms in any of the fields, as if they were one field. The following is the `cross_fields` query for `John Doe`: @@ -399,7 +411,7 @@ The response contains the only document in which both `John` and `Doe` are prese ```json { - "took": 19, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -412,12 +424,12 @@ The response contains the only document in which both `John` and `Doe` are prese "value": 1, "relation": "eq" }, - "max_score": 0.8754687, + "max_score": 0.3979403, "hits": [ { "_index": "customers", "_id": "1", - "_score": 0.8754687, + "_score": 0.3979403, "_source": { "first_name": "John", "last_name": "Doe" @@ -428,7 +440,7 @@ The response contains the only document in which both `John` and `Doe` are prese } ``` -You can use the Validate API operation to gain insight into how the preceding query is executed: +Use the Validate Query API to see how the preceding query is executed: ```json GET /customers/_validate/query?explain @@ -445,7 +457,7 @@ GET /customers/_validate/query?explain ``` {% include copy-curl.html %} -From the response, you can see that the query is searching for all terms in at least one field: +From the response, you can see that each term must be present in at least one of the fields: ```json { @@ -465,29 +477,22 @@ From the response, you can see that the query is searching for all terms in at l } ``` -Thus, blending the term frequencies for all fields solves the problem of differing term frequencies by correcting for the differences. +Each `blended` clause scores a term as if all of its fields were one field. To do this, OpenSearch adjusts the document frequency of the term in each field. The field in which the term is most common keeps its document frequency, and every other field receives that frequency plus one. For example, if `doe` appears in the `last_name` field of 3 documents and in the `first_name` field of 1 document, the [Explain API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/explain/) reports a document frequency of 3 for `last_name:doe` and 4 for `first_name:doe`. As a result, a rare occurrence of `doe` in the `first_name` field no longer outscores the common occurrence in the `last_name` field, and matches in `last_name`, the field most likely to contain `doe`, score slightly higher. The `cross_fields` query is usually only useful on short string fields with a `boost` of 1. In other cases, the score does not produce a meaningful blend of term statistics because of the way boosts, term frequencies, and length normalization contribute to the score. {: .note} -The `fuzziness` parameter is not supported for `cross_fields` queries. +The `fuzziness` parameter is not supported for `cross_fields` queries. For more information, see [Parameter support by type](#parameter-support-by-type). {: .note} ### Analysis -The `cross_fields` query only works as a term-centric query on fields with the same analyzer. Fields with the same analyzer are grouped together and these groups are combined with a Boolean query. +The `cross_fields` query blends terms only across fields that use the same search analyzer, because only those fields produce the same terms from the query string. OpenSearch groups the fields by analyzer, builds one set of `blended` clauses for each group, and then combines the groups in a [`dis_max`]({{site.url}}{{site.baseurl}}/query-dsl/compound/disjunction-max/) query. The best-scoring group determines the score, and the `tie_breaker` parameter controls how much the other groups contribute. -For example, consider an index where the `first_name` and `last_name` fields are analyzed with the default `standard` - analyzer and their `.edge` subfields are analyzed with an edge n-gram analyzer: - -<details markdown="block"> - <summary> - Response - </summary> - {: .text-delta} +For example, the following request creates a `customer_names` index in which the `first_name` and `last_name` fields use the default `standard` analyzer and their `edge` subfields use an edge n-gram analyzer: ```json -PUT customers +PUT customer_names { "settings": { "analysis": { @@ -531,23 +536,21 @@ PUT customers ``` {% include copy-curl.html %} -</details> - -You index one document in the `customers` index: +Index one document into the `customer_names` index: ```json -PUT /customers/_doc/1 +PUT /customer_names/_doc/1 { - "first": "John", - "last": "Doe" + "first_name": "John", + "last_name": "Doe" } ``` {% include copy-curl.html %} -You can use a `cross_fields` query to search across the fields for `John Doe`: +The following `cross_fields` query searches for `John` in all four fields: ```json -GET /customers/_search +GET /customer_names/_search { "query": { "multi_match" : { @@ -563,10 +566,10 @@ GET /customers/_search ``` {% include copy-curl.html %} -To see how the query is executed, you can run the Validate API: +To see how the query is executed, run the Validate Query API: ```json -GET /customers/_validate/query?explain +GET /customer_names/_validate/query?explain { "query": { "multi_match" : { @@ -582,7 +585,7 @@ GET /customers/_validate/query?explain ``` {% include copy-curl.html %} -The response shows that the `last_name` and `first_name` fields are grouped together and treated as a single field. Similarly, the `last_name.edge` and `first_name.edge` fields are grouped together and treated as a single field: +The response shows two groups separated by the `|` (`dis_max`) operator. The `last_name` and `first_name` fields form one group, and the `last_name.edge` and `first_name.edge` fields form another. Within the second group, the edge n-gram analyzer splits `John` into the terms `Jo`, `Joh`, and `John`. Because the custom analyzer has no `lowercase` filter, these terms keep their original case: ```json { @@ -594,7 +597,7 @@ The response shows that the `last_name` and `first_name` fields are grouped toge "valid": true, "explanations": [ { - "index": "customers", + "index": "customer_names", "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])))" } @@ -602,10 +605,14 @@ The response shows that the `last_name` and `first_name` fields are grouped toge } ``` -Using the `operator` or `minimum_should_match` parameters with multiple field groups like the preceding ones can lead to the problem described in the [previous section](#operator-and-minimum-should-match). To avoid it, you can rewrite the previous query as two `cross_fields` subqueries combined with a Boolean query and apply the `minimum_should_match` to one of the subqueries: +#### Combining field groups with operator and minimum should match + +The `operator` and `minimum_should_match` parameters apply to each field group separately. When groups produce different numbers of terms, this can lead to the problem described in [`operator` and `minimum_should_match`](#operator-and-minimum-should-match). For example, with `"operator": "and"`, the query `John Doe` requires the `edge` group to match every n-gram of `John Doe`, including `John D` and `John Do`, which never occur in the index. The document can then match only through the `standard` group. + +To control each group independently, rewrite the query as two `cross_fields` subqueries combined in a `bool` query, and apply `minimum_should_match` to only one of the subqueries: ```json -GET /customers/_search +GET /customer_names/_search { "query": { "bool": { @@ -638,10 +645,12 @@ GET /customers/_search ``` {% include copy-curl.html %} -To create one group for all fields, specify an analyzer in your query: +#### Forcing all fields into one group + +To place all fields in one group, specify an `analyzer` in the query. OpenSearch then analyzes the query string once using that analyzer and searches for the resulting terms in every field: ```json -GET customers/_search +GET customer_names/_search { "query": { "multi_match" : { @@ -655,7 +664,7 @@ GET customers/_search ``` {% include copy-curl.html %} -Running the Validate API on the previous query shows how the query is executed: +Running the Validate Query API on the preceding query shows one `blended` clause for each term, covering all four fields: ```json { @@ -667,7 +676,7 @@ Running the Validate API on the previous query shows how the query is executed: "valid": true, "explanations": [ { - "index": "customers", + "index": "customer_names", "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])" } @@ -675,6 +684,9 @@ Running the Validate API on the previous query shows how the query is executed: } ``` +When you override the analyzer, the query terms no longer match the way the subfields were indexed. In this example, the `standard` analyzer produces the lowercase term `jo` for the query `Jo`, but the `edge` subfields contain only `Jo`. As a result, a search for `Jo` using `"analyzer": "standard"` returns no documents, while the same search without the `analyzer` parameter matches document 1 through the `edge` subfields. Override the analyzer only when all grouped fields can match the terms it produces. +{: .important} + ## Phrase The `phrase` query behaves similarly to the [`best_fields`](#best-fields) query but uses a `match_phrase` query instead of a `match` query. @@ -711,7 +723,7 @@ GET articles/_search } ``` -Because by default a `phrase` query matches text only when the terms appear in the same order, only document 1 is returned in the results: +By default, a `phrase` query matches only when the terms appear next to each other in the same order. Document 2 contains both terms but not as a phrase, so only document 1 is returned in the results: <details markdown="block"> <summary> @@ -721,7 +733,7 @@ Because by default a `phrase` query matches text only when the terms appear in t ```json { - "took": 3, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -734,12 +746,12 @@ Because by default a `phrase` query matches text only when the terms appear in t "value": 1, "relation": "eq" }, - "max_score": 0.84407747, + "max_score": 0.38367155, "hits": [ { "_index": "articles", "_id": "1", - "_score": 0.84407747, + "_score": 0.38367155, "_source": { "title": "Aurora borealis", "description": "Northern lights, or aurora borealis, explained" @@ -751,7 +763,7 @@ Because by default a `phrase` query matches text only when the terms appear in t ``` </details> -You can use the `slop` parameter to allow other words between words in query phrase. For example, the following query accepts text as a match if up to two words are between `flourescent` and `therapy`: +Use the `slop` parameter to allow other words between the words in the query phrase. For example, the following query accepts text as a match if up to two words are between `fluorescent` and `therapy`: ```json GET articles/_search @@ -778,7 +790,7 @@ The response contains document 2: ```json { - "took": 3, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -791,12 +803,12 @@ The response contains document 2: "value": 1, "relation": "eq" }, - "max_score": 0.7003825, + "max_score": 0.31835568, "hits": [ { "_index": "articles", "_id": "2", - "_score": 0.7003825, + "_score": 0.31835568, "_source": { "title": "Sun deprivation in the Northern countries", "description": "Using fluorescent lights for therapy" @@ -810,7 +822,7 @@ The response contains document 2: For `slop` values less than 2, no documents are returned. -The `fuzziness` parameter is not supported for `phrase` queries. +The `fuzziness` parameter is not supported for `phrase` queries. For more information, see [Parameter support by type](#parameter-support-by-type). {: .note} ## Phrase prefix @@ -849,14 +861,14 @@ GET articles/_search } ``` -You can use the `slop` parameter to allow other words between words in query phrase. +The `phrase_prefix` type accepts the `slop` parameter, which works the same way as for the `phrase` type. It also accepts the `max_expansions` parameter, which limits the number of terms to which the last term in the query is expanded. Default is `50`. -The `fuzziness` parameter is not supported for `phrase_prefix` queries. +The `fuzziness` parameter is not supported for `phrase_prefix` queries. For more information, see [Parameter support by type](#parameter-support-by-type). {: .note} ## Boolean prefix -The `bool_prefix` query scores documents similarly to the [`most_fields`](#most-fields) query but uses a [`match_bool_prefix`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-bool-prefix/) query instead of a `match` query. +The `bool_prefix` query scores documents similarly to the [`most_fields`](#most-fields) query but uses a [`match_bool_prefix`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-bool-prefix/) query instead of a `match` query. The `match_bool_prefix` query matches every term except the last one exactly and treats the last term as a prefix, which makes it useful for search-as-you-type experiences. The following is an example `bool_prefix` query for the index described in the [`best_fields`](#best-fields) section: @@ -865,7 +877,7 @@ GET articles/_search { "query": { "multi_match" : { - "query": "li northern", + "query": "northern li", "type": "bool_prefix", "fields": [ "title", "description" ] } @@ -874,23 +886,72 @@ GET articles/_search ``` {% include copy-curl.html %} -The preceding query is executed as the following [`dis_max`]({{site.url}}{{site.baseurl}}/query-dsl/compound/disjunction-max/) query with a `match_bool_prefix` query for each field: +The preceding query is executed as the following Boolean query with a `match_bool_prefix` query for each field. The scores of all matching clauses are added together: ```json GET articles/_search { "query": { - "dis_max": { - "queries": [ - { "match_bool_prefix": { "title": "li northern" }}, - { "match_bool_prefix": { "description": "li northern" }} + "bool": { + "should": [ + { "match_bool_prefix": { "title": "northern li" }}, + { "match_bool_prefix": { "description": "northern li" }} ] } } } ``` -The `fuzziness`, `prefix_length`, `max_expansions`, `fuzzy_rewrite`, and `fuzzy_transpositions` parameters are supported for the terms that are used to construct term queries, but they do not have an effect on the prefix query constructed from the final term. +Both documents are returned. Document 1 matches `northern` and the prefix `li` (`lights`) in the `description` field. Document 2 matches `northern` in the `title` field and the prefix `li` in the `description` field: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.3037697, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 1.3037697, + "_source": { + "title": "Aurora borealis", + "description": "Northern lights, or aurora borealis, explained" + } + }, + { + "_index": "articles", + "_id": "2", + "_score": 1.261565, + "_source": { + "title": "Sun deprivation in the Northern countries", + "description": "Using fluorescent lights for therapy" + } + } + ] + } +} +``` +</details> + +The `fuzziness`, `prefix_length`, `max_expansions`, `fuzzy_rewrite`, and `fuzzy_transpositions` parameters are supported for the terms that are used to construct term queries, but they do not have an effect on the prefix query constructed from the final term. The `slop` parameter is not supported for `bool_prefix` queries. {: .note} ## Parameters @@ -901,31 +962,47 @@ Parameter | Data type | Description :--- | :--- | :--- `query` | String | The query string to use for search. Required. `auto_generate_synonyms_phrase_query` | Boolean | Specifies whether to create a [match phrase query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) automatically for multi-term synonyms. For example, if you specify `ba,batting average` as synonyms and search for `ba`, OpenSearch searches for `ba OR "batting average"` (if this option is `true`) or `ba OR (batting AND average)` (if this option is `false`). Default is `true`. -`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. +`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. For more information about `index.query.default_field`, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). `boost` | Floating-point | Boosts the clause by the given multiplier. Useful for weighing clauses in compound queries. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. -`fields` | Array of strings | The list of fields in which to search. If you don't provide the `fields` parameter, `multi_match` query searches the fields specified in the `index.query. Default_field` setting, which defaults to `*`. -`fuzziness` | String | The number of character edits (insert, delete, substitute) that it takes to change one word to another when determining whether a term matched a value. For example, the distance between `wined` and `wind` is 1. Valid values are non-negative integers or `AUTO`. The default, `AUTO`, chooses a value based on the length of each term and is a good choice for most use cases. Not supported for `phrase`, `phrase_prefix`, and `cross_fields` queries. -`fuzzy_rewrite` | String | Determines how OpenSearch rewrites the query. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. If the `fuzziness` parameter is not `0`, the query uses a `fuzzy_rewrite` method of `top_terms_blended_freqs_${max_expansions}` by default. Default is `constant_score`. +`fields` | Array of strings | The list of fields in which to search. If you don't provide the `fields` parameter, `multi_match` query searches the fields specified in the `index.query.default_field` setting, which defaults to `*`. +`fuzziness` | String | The maximum number of edits allowed when matching each term, specified as `0`, `1`, `2`, `AUTO`, or `AUTO:<low>,<high>`. If not specified, terms must match exactly. Not supported for the `cross_fields`, `phrase`, and `phrase_prefix` types. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). +`fuzzy_rewrite` | String | Determines how OpenSearch rewrites the query. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. If the `fuzziness` parameter is not `0`, the query uses a `fuzzy_rewrite` method of `top_terms_blended_freqs_${max_expansions}` by default. `fuzzy_transpositions` | Boolean | Setting `fuzzy_transpositions` to `true` (default) adds swaps of adjacent characters to the insert, delete, and substitute operations of the `fuzziness` option. For example, the distance between `wind` and `wnid` is 1 if `fuzzy_transpositions` is true (swap "n" and "i") and 2 if it is false (delete "n", insert "n"). If `fuzzy_transpositions` is false, `rewind` and `wnid` have the same distance (2) from `wind`, despite the more human-centric opinion that `wnid` is an obvious typo. The default is a good choice for most use cases. `lenient` | Boolean | Setting `lenient` to `true` ignores data type mismatches between the query and the document field. For example, a query string of `"8.2"` could match a field of type `float`. Default is `false`. `max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. `minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | If the query string contains multiple search terms and you use the `or` operator, the number of terms that need to match for the document to be considered a match. For example, if `minimum_should_match` is 2, `wind often rising` does not match `The Wind Rises.` If `minimum_should_match` is `1`, it matches. For details, see [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). `operator` | String | If the query string contains multiple search terms, whether all terms need to match (`AND`) or only one term needs to match (`OR`) for a document to be considered a match. Valid values are:<br>- `OR`: The string `to be` is interpreted as `to OR be`<br>- `AND`: The string `to be` is interpreted as `to AND be`<br> Default is `OR`. `prefix_length` | Non-negative integer | The number of leading characters that are not considered in fuzziness. Default is `0`. -`slop` | `0` (default) or a positive integer | Controls the degree to which words in a query can be misordered and still be considered a match. From the [Lucene documentation](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/search/PhraseQuery.html#getSlop--): "The number of other words permitted between words in query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit reorderings of phrases, the slop must be at least two. A value of zero requires an exact match." Supported for `phrase` and `phrase_prefix` query types. -`tie_breaker` | Floating-point | A factor between 0 and 1.0 that is used to give more weight to documents that match multiple query clauses. For more information, see [The `tie_breaker` parameter`](#the-tie_breaker-parameter). +`slop` | `0` (default) or a positive integer | Controls the degree to which words in a query can be misordered and still be considered a match. From the [Lucene documentation](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/search/PhraseQuery.html#getSlop--): "The number of other words permitted between words in query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit reorderings of phrases, the slop must be at least two. A value of zero requires an exact match." Supported for `phrase` and `phrase_prefix` query types. +`tie_breaker` | Floating-point | A factor between 0 and 1.0 that is used to give more weight to documents that match multiple query clauses. For more information, see [The `tie_breaker` parameter](#the-tie_breaker-parameter). `type` | String | The multi-match query type. Valid values are `best_fields`, `most_fields`, `cross_fields`, `phrase`, `phrase_prefix`, `bool_prefix`. Default is `best_fields`. `zero_terms_query` | String | In some cases, the analyzer removes all terms from a query string. For example, the `stop` analyzer removes all terms from the string `an but this`. In those cases, `zero_terms_query` specifies whether to match no documents (`none`) or all documents (`all`). Valid values are `none` and `all`. Default is `none`. -The `fuzziness` parameter is not supported for `phrase`, `phrase_prefix`, and `cross_fields` queries. -{: .note} +### Parameter support by type -The `slop` parameter is only supported for `phrase` and `phrase_prefix` queries. -{: .note} +Not every parameter applies to every query type. OpenSearch rejects the following combinations with a `400` error. -### The `tie_breaker` parameter +Parameter | Query types | Error +:--- | :--- | :--- +`fuzziness` | `cross_fields`, `phrase`, `phrase_prefix` | `Fuzziness not allowed for type [<type>]` +`slop` | `bool_prefix` | `[slop] not allowed for type [bool_prefix]` -Each term-level blended query calculates the document score as the best score returned by any field in a group. The scores from all blended queries are added together to produce the final score. You can change the way the score is calculated by using the `tie_breaker` parameter. The `tie_breaker` parameter accepts the following values: +Other parameters that a query type does not use are ignored without an error. For example, the `slop` parameter has no effect on `best_fields` or `most_fields` queries. The following table lists the parameters that have an effect for each query type, in addition to `query`, `fields`, `type`, `analyzer`, `boost`, `lenient`, and `zero_terms_query`, which apply to all types. + +Query type | Additional supported parameters +:--- | :--- +`best_fields` | `auto_generate_synonyms_phrase_query`, `fuzziness`, `fuzzy_rewrite`, `fuzzy_transpositions`, `max_expansions`, `minimum_should_match`, `operator`, `prefix_length`, `tie_breaker` +`most_fields` | `auto_generate_synonyms_phrase_query`, `fuzziness`, `fuzzy_rewrite`, `fuzzy_transpositions`, `max_expansions`, `minimum_should_match`, `operator`, `prefix_length`, `tie_breaker` +`cross_fields` | `auto_generate_synonyms_phrase_query`, `minimum_should_match`, `operator`, `tie_breaker` +`phrase` | `slop`, `tie_breaker` +`phrase_prefix` | `max_expansions`, `slop`, `tie_breaker` +`bool_prefix` | `auto_generate_synonyms_phrase_query`, `fuzziness`, `fuzzy_rewrite`, `fuzzy_transpositions`, `max_expansions`, `minimum_should_match`, `operator`, `prefix_length`, `tie_breaker` + +For the `bool_prefix` type, the fuzzy parameters apply to every term except the last one, which is always matched as a prefix. + +### The tie_breaker parameter + +The `tie_breaker` parameter determines how the scores of matching fields are combined. For the `cross_fields` type, it also determines how the scores of the fields within each `blended` clause and of the field groups are combined. The `tie_breaker` parameter accepts the following values: - 0.0 (default for `best_fields`, `cross_fields`, `phrase`, and `phrase_prefix` queries): Take the single best score returned by any field in a group. - 1.0 (default for `most_fields` and `bool_prefix` queries): Add the scores for all fields in a group. diff --git a/_query-dsl/full-text/query-string.md b/_query-dsl/full-text/query-string.md index 12609e29..7ee90830 100644 --- a/_query-dsl/full-text/query-string.md +++ b/_query-dsl/full-text/query-string.md @@ -2,9 +2,7 @@ layout: default title: Query string parent: Full-text queries -grand_parent: Query DSL -nav_order: 60 - +nav_order: 80 redirect_from: - /opensearch/query-dsl/full-text/query-string/ - /query-dsl/query-dsl/full-text/query-string/ @@ -14,7 +12,7 @@ redirect_from: A `query_string` query parses the query string based on the [query string syntax](#query-string-syntax). It provides for creating powerful yet concise queries that can incorporate wildcards and search multiple fields. -Searches with `query_string` queries do not return nested documents. To search nested fields, use the [`nested` query]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/nested/). +Searches with `query_string` queries do not return nested documents. To search nested fields, use the [`nested` query]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/). {: .note} Query string query has a strict syntax and returns an error in case of invalid syntax. Therefore, it does not work well for search box applications. For a less strict alternative, consider using [`simple_query_string` query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/simple-query-string/). If you don't need query syntax support, use the [`match` query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/). @@ -22,7 +20,7 @@ Query string query has a strict syntax and returns an error in case of invalid s ## Query string syntax -Query string syntax is based on [Apache Lucene query syntax](https://lucene.apache.org/core/2_9_4/queryparsersyntax.html). +Query string syntax is based on [Apache Lucene query syntax](https://lucene.apache.org/core/{{site.lucene_version}}/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description). You can use query string syntax in the following cases: @@ -42,8 +40,8 @@ You can use query string syntax in the following cases: 1. In the OpenSearch Dashboards Discover or Dashboard apps, if you turn off DQL, as shown in the following image. ![Using query string syntax in OpenSearch Dashboards Discover]({{site.url}}{{site.baseurl}}/images/discover-lucene-syntax.png) - DQL and Query string query (Lucene) language are the two search bar language options in Discover and Dashboards. To compare these language options, see [Discover and Dashboard search bar]({{site.url}}{{site.baseurl}}/dashboards/index/#discover-and-dashboard-search-bar). - {: .tip} + DQL and Query string query (Lucene) language are the two search bar language options in Discover and Dashboards. To compare these language options, see [DQL and query string query quick reference]({{site.url}}{{site.baseurl}}/dashboards/dql/#dql-and-query-string-query-quick-reference). + {: .tip} 1. If you search using the HTTP request query parameters, for example: ```json @@ -625,18 +623,18 @@ Parameter | Data type | Description `query` | String | The text that may contain expressions in the [query string syntax](#query-string-syntax) to use for search. Required. `allow_leading_wildcard` | Boolean | Specifies whether `*` and `?` are allowed as first characters of a search term. Default is `true`. `analyze_wildcard` | Boolean | Specifies whether OpenSearch should attempt to analyze wildcard terms. Default is `false`. -`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. +`analyzer` | String | The [analyzer]({{site.url}}{{site.baseurl}}/analyzers/index/) used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. For more information about `index.query.default_field`, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). `auto_generate_synonyms_phrase_query` | Boolean | Specifies whether to create a [match phrase query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-phrase/) automatically for multi-term synonyms. For example, if you specify `ba, batting average` as synonyms and search for `ba`, OpenSearch searches for `ba OR "batting average"` (if this option is `true`) or `ba OR (batting AND average)` (if this option is `false`). Default is `true`. `boost` | Floating-point | Boosts the clause by the given multiplier. Useful for weighing clauses in compound queries. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. `default_field` | String | The field in which to search if the field is not specified in the query string. Supports wildcards. Defaults to the value specified in the `index.query. Default_field` index setting. By default, the `index.query. Default_field` is `*`, which means extract all fields eligible for term query and filter the metadata fields. The extracted fields are combined into a query if the `prefix` is not specified. Eligible fields do not include nested documents. Searching all eligible fields could be a resource-intensive operation. The `indices.query.bool.max_clause_count` search setting defines the maximum value for the product of the number of fields and the number of terms that can be queried at one time. The default value for `indices.query.bool.max_clause_count` is 1,024. `default_operator`| String | If the query string contains multiple search terms, whether all terms need to match (`AND`) or only one term needs to match (`OR`) for a document to be considered a match. Valid values are:<br>- `OR`: The string `to be` is interpreted as `to OR be`<br>- `AND`: The string `to be` is interpreted as `to AND be`<br> Default is `OR`. `enable_position_increments` | Boolean | When `true`, resulting queries are aware of position increments. This setting is useful when the removal of stop words leaves an unwanted "gap" between terms. Default is `true`. `fields` | String array | The list of fields to search (for example, `"fields": ["title^4", "description"]`). Supports wildcards. If unspecified, defaults to the `index.query. Default_field` setting, which defaults to `["*"]`. -`fuzziness` | String | The number of character edits (insert, delete, substitute) that it takes to change one word to another when determining whether a term matched a value. For example, the distance between `wined` and `wind` is 1. Valid values are non-negative integers or `AUTO`. The default, `AUTO`, chooses a value based on the length of each term and is a good choice for most use cases. +`fuzziness` | String | The maximum number of edits allowed for terms followed by the `~` operator, specified as `0`, `1`, `2`, `AUTO`, or `AUTO:<low>,<high>`. Default is `AUTO`. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). `fuzzy_max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. `fuzzy_transpositions` | Boolean | Setting `fuzzy_transpositions` to `true` (default) adds swaps of adjacent characters to the insert, delete, and substitute operations of the `fuzziness` option. For example, the distance between `wind` and `wnid` is 1 if `fuzzy_transpositions` is true (swap "n" and "i") and 2 if it is false (delete "n", insert "n"). If `fuzzy_transpositions` is false, `rewind` and `wnid` have the same distance (2) from `wind`, despite the more human-centric opinion that `wnid` is an obvious typo. The default is a good choice for most use cases. `lenient` | Boolean | Setting `lenient` to `true` ignores data type mismatches between the query and the document field. For example, a query string of `"8.2"` could match a field of type `float`. Default is `false`. -`max_determinized_states` | Positive integer | The maximum number of "[states](https://lucene.apache.org/core/8_9_0/core/org/apache/lucene/util/automaton/Operations.html#DEFAULT_MAX_DETERMINIZED_STATES)" (a measure of complexity) that Lucene can create for query strings that contain regular expressions (for example, `"query": "/wind.+?/"`). Larger numbers allow for queries that use more memory. Default is 10,000. +`max_determinized_states` | Positive integer | The maximum number of "[states](https://lucene.apache.org/core/{{site.lucene_version}}/core/org/apache/lucene/util/automaton/Operations.html#DEFAULT_MAX_DETERMINIZED_STATES)" (a measure of complexity) that Lucene can create for query strings that contain regular expressions (for example, `"query": "/wind.+?/"`). Larger numbers allow for queries that use more memory. Default is 10,000. `minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | If the query string contains multiple search terms and you use the `or` operator, the number of terms that need to match for the document to be considered a match. For example, if `minimum_should_match` is 2, `wind often rising` does not match `The Wind Rises.` If `minimum_should_match` is `1`, it matches. For details, see [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). `phrase_slop` | Integer | The maximum number of words that are allowed between the matched words. If `phrase_slop` is 2, a maximum of two words is allowed between matched words in a phrase. Transposed words have a slop of 2. Default is `0` (an exact phrase match where matched words must be next to each other). `quote_analyzer` | String | The analyzer used to tokenize quoted text in the query string. Overrides the `analyzer` parameter for quoted text. Default is the `search_quote_analyzer` specified for the `default_field`. diff --git a/_query-dsl/full-text/simple-query-string.md b/_query-dsl/full-text/simple-query-string.md index fbf37f58..4ba0567e 100644 --- a/_query-dsl/full-text/simple-query-string.md +++ b/_query-dsl/full-text/simple-query-string.md @@ -2,7 +2,6 @@ layout: default title: Simple query string parent: Full-text queries -grand_parent: Query DSL nav_order: 70 --- @@ -42,7 +41,7 @@ Operator | Description `*` | When used at the end of a term, signifies a prefix query. `"` | Wraps several terms into a phrase (for example, `"wind rises"`). `(`, `)` | Wrap a clause for precedence (for example, `wind + (rises | rising)`). -`~n` | When used after a term (for example, `wnid~3`), sets `fuzziness`. When used after a phrase, sets `slop`. +`~n` | When used after a term (for example, `wnid~2`), sets `fuzziness`. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). When used after a phrase, sets `slop`. `-` | Negates the term. All of the preceding operators are reserved characters. To refer to them as raw characters and not operators, escape any of them with a backslash. When sending a JSON request, use `\\` to escape reserved characters (because the backslash character is itself reserved, you must escape the backslash with another backslash). @@ -356,14 +355,14 @@ Parameter | Data type | Description :--- | :--- | :--- `query`| String | The text that may contain expressions in the [simple query string syntax](#simple-query-string-syntax) to use for search. Required. `analyze_wildcard` | Boolean | Specifies whether OpenSearch should attempt to analyze wildcard terms. Default is `false`. -`analyzer` | String | The analyzer used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. +`analyzer` | String | The analyzer used to tokenize the query string text. Default is the index-time analyzer specified for the `default_field`. If no analyzer is specified for the `default_field`, the `analyzer` is the default analyzer for the index. For more information about `index.query.default_field`, see [Dynamic index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/#dynamic-index-settings). `auto_generate_synonyms_phrase_query` | Boolean | Specifies whether to create [match_phrase queries]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/) automatically for multi-term synonyms. Default is `true`. `default_operator`| String | If the query string contains multiple search terms, whether all terms need to match (`AND`) or only one term needs to match (`OR`) for a document to be considered a match. Valid values are:<br>- `OR`: The string `to be` is interpreted as `to OR be`<br>- `AND`: The string `to be` is interpreted as `to AND be`<br> Default is `OR`. -`fields` | String array | The list of fields to search (for example, `"fields": ["title^4", "description"]`). Supports wildcards. If unspecified, defaults to the `index.query. Default_field` setting, which defaults to `["*"]`. The maximum number of fields that can be searched at the same time is defined by `indices.query.bool.max_clause_count`, which is 1,024 by default. -`flags` | String | A `|`-delimited string of [flags]({{site.baseurl}}/query-dsl/full-text/simple-query-string/) to enable (for example, `AND|OR|NOT`). Default is `ALL`. You can explicitly set the value for `default_field`. For example, to return all titles, set it to `"default_field": "title"`. +`fields` | String array | The list of fields to search (for example, `"fields": ["title^4", "description"]`). Supports wildcards. You can boost relevance for matches in specific fields using the caret (`^`) notation. If unspecified, the query defaults to the `index.query.default_field` setting, which defaults to `["*"]` (all fields eligible for term queries are included, while metadata fields are filtered out). You can override the index setting or explicitly set `default_field` in the query. For example, to return all titles, set `"default_field": "title"`. The maximum number of fields that can be searched at once is defined by `indices.query.bool.max_clause_count`, which defaults to 1,024. +`flags` | String | A `|`-delimited string of [flags](#limit-operators) to enable (for example, `AND|OR|NOT`). Default is `ALL`. `fuzzy_max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. `fuzzy_transpositions` | Boolean | Setting `fuzzy_transpositions` to `true` (default) adds swaps of adjacent characters to the insert, delete, and substitute operations of the `fuzziness` option. For example, the distance between `wind` and `wnid` is 1 if `fuzzy_transpositions` is true (swap "n" and "i") and 2 if it is false (delete "n", insert "n"). If `fuzzy_transpositions` is false, `rewind` and `wnid` have the same distance (2) from `wind`, despite the more human-centric opinion that `wnid` is an obvious typo. The default is a good choice for most use cases. `fuzzy_prefix_length`| Integer | The number of beginning characters left unchanged for fuzzy matching. Default is 0. `lenient` | Boolean | Setting `lenient` to `true` ignores data type mismatches between the query and the document field. For example, a query string of `"8.2"` could match a field of type `float`. Default is `false`. `minimum_should_match` | Positive or negative integer, positive or negative percentage, combination | If the query string contains multiple search terms and you use the `or` operator, the number of terms that need to match for the document to be considered a match. For example, if `minimum_should_match` is 2, `wind often rising` does not match `The Wind Rises.` If `minimum_should_match` is `1`, it matches. For details, see [Minimum should match]({{site.url}}{{site.baseurl}}/query-dsl/minimum-should-match/). -`quote_field_suffix` | String | This option supports searching for exact matches (surrounded with quotation marks) using a different analysis method than non-exact matches use. For example, if `quote_field_suffix` is `.exact` and you search for `\"lightly\"` in the `title` field, OpenSearch searches for the word `lightly` in the `title.exact` field. This second field might use a different type (for example, `keyword` rather than `text`) or a different analyzer. \ No newline at end of file +`quote_field_suffix` | String | This option supports searching for exact matches (surrounded with quotation marks) using a different analysis method than non-exact matches use. For example, if `quote_field_suffix` is `.exact` and you search for `\"lightly\"` in the `title` field, OpenSearch searches for the word `lightly` in the `title.exact` field. This second field might use a different type (for example, `keyword` rather than `text`) or a different analyzer. diff --git a/_query-dsl/fuzziness.md b/_query-dsl/fuzziness.md new file mode 100644 index 00000000..c2e69e42 --- /dev/null +++ b/_query-dsl/fuzziness.md @@ -0,0 +1,216 @@ +--- +layout: default +title: Fuzziness +nav_order: 82 +--- + +# Fuzziness + +The `fuzziness` parameter lets a query match terms that differ slightly from the search term, so searches still return results when the user makes a typo. For example, with fuzziness enabled, a search for `lantren` matches documents containing `lantern`. + +Fuzziness is measured in edits. An edit is one of the following single-character changes: + +- Inserting a character, for example, `tnt` to `tent` +- Deleting a character, for example, `tennt` to `tent` +- Substituting one character for another, for example, `tant` to `tent` +- Swapping two adjacent characters (a _transposition_), for example, `tnet` to `tent` + +The number of edits needed to change one term into another is called the [Damerau–Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance). A term matches if its distance from the search term is no greater than the allowed number of edits. + +The following queries and features support `fuzziness`: + +- The [`fuzzy`]({{site.url}}{{site.baseurl}}/query-dsl/term/fuzzy/) query, for which fuzziness is enabled by default (`AUTO`) +- The [`match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match/), [`multi_match`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/multi-match/), and [`match_bool_prefix`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/match-bool-prefix/) queries, for which fuzziness is disabled unless you specify it +- The `fuzzy` rule of the [`intervals`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/intervals/) query +- The [`query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) and [`simple_query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/simple-query-string/) queries, which use the `~` operator, for example, `tnt~` or `tnt~1` +- The [completion]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/completion/) suggester + +## Fuzziness values + +The following table lists the values that you can specify for `fuzziness`. + +Value | Description +:--- | :--- +`0`, `1`, or `2` | The maximum number of edits allowed. `0` requires an exact match. OpenSearch supports at most 2 edits: a larger integer is treated as `2`. +`AUTO` | Sets the number of allowed edits based on the length of the search term. Terms of 0--2 characters must match exactly, terms of 3--5 characters allow 1 edit, and terms of 6 or more characters allow 2 edits. Recommended for most searches. +`AUTO:<low>,<high>` | Works like `AUTO` but uses custom length thresholds. Terms shorter than `<low>` characters must match exactly, terms shorter than `<high>` characters allow 1 edit, and longer terms allow 2 edits. For example, `AUTO:4,7` requires an exact match for terms of 0--3 characters, allows 1 edit for terms of 4--6 characters, and allows 2 edits for terms of 7 or more characters. `AUTO` is equivalent to `AUTO:3,6`. + +`AUTO` depends on the length of the search term, not on the length of the indexed term. For example, the 5-character search term `lntrn` allows only 1 edit, so it does not match `lantern`, which requires 2 edits. To allow 2 edits for 5-character terms, lower the high threshold, for example, to `AUTO:3,5`. + +## Related parameters + +The following parameters control how fuzzy matching is applied. Some queries use different names for the same parameter. The following table lists all names for each parameter. + +Parameter | Description +:--- | :--- +`fuzzy_transpositions`, `transpositions` | Whether a swap of two adjacent characters counts as one edit. If `false`, a transposition counts as two edits, and the distance is the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance), which does not include transpositions. Default is `true`. +`fuzzy_prefix_length`, `prefix_length` | The number of leading characters that must match exactly. Edits are allowed only after this prefix. For example, with `prefix_length` set to `1`, `xent` does not match `tent`. Increasing `prefix_length` reduces the number of candidate terms and speeds up the query. Default is `0`. +`fuzzy_max_expansions`, `max_expansions` | The maximum number of candidate terms that the query expands to. Default is `50`. Lower values make the query faster but may skip matching terms. +`fuzzy_rewrite`, `rewrite` | Determines how OpenSearch converts the candidate terms into a query, which affects how matching documents are scored. Accepts the same values as the `rewrite` parameter of other multi-term queries, such as `constant_score` or `top_terms_N`. For a description of each value, see [Rewrite]({{site.url}}{{site.baseurl}}/query-dsl/rewrite-parameter/). By default, fuzzy matches are scored based on the frequency of the matching terms (`top_terms_blended_freqs_N`, where `N` is the `max_expansions` value). Setting `fuzzy_rewrite` to `constant_score` gives all matching documents a score of `1.0`. + +## Example: Matching a misspelled term + +Index a document into the `fuzzy-test` index: + +```json +PUT /fuzzy-test/_doc/1?refresh=true +{ + "product": "lantern" +} +``` +{% include copy-curl.html %} + +Search for the misspelled term `lamtrn` using `AUTO` fuzziness. The term is 2 edits from `lantern`: `m` replaces `n`, and `e` is missing. Because the term contains 6 characters, `AUTO` allows 2 edits: + +```json +GET /fuzzy-test/_search +{ + "query": { + "match": { + "product": { + "query": "lamtrn", + "fuzziness": "AUTO" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.08717638, + "hits": [ + { + "_index": "fuzzy-test", + "_id": "1", + "_score": 0.08717638, + "_source": { + "product": "lantern" + } + } + ] + } +} +``` + +With `fuzziness` set to `1`, the same query returns no results. + +## Example: Matching swapped characters + +By default, swapping two adjacent characters counts as one edit. The following request searches for `lantren`, in which `e` and `r` are swapped, and allows only 1 edit: + +```json +GET /fuzzy-test/_search +{ + "query": { + "match": { + "product": { + "query": "lantren", + "fuzziness": 1 + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document because the transposition counts as 1 edit: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.11208393, + "hits": [ + { + "_index": "fuzzy-test", + "_id": "1", + "_score": 0.11208393, + "_source": { + "product": "lantern" + } + } + ] + } +} +``` + +If you set `fuzzy_transpositions` to `false` in the same request, the transposition counts as 2 edits, and the query returns no results. + +## Example: Allowing more edits for short terms + +With `AUTO`, the 5-character search term `lntrn` allows only 1 edit and does not match `lantern`, which requires 2 edits. The following request lowers the high threshold to 5 so that 5-character terms allow 2 edits: + +```json +GET /fuzzy-test/_search +{ + "query": { + "match": { + "product": { + "query": "lntrn", + "fuzziness": "AUTO:3,5" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.07845875, + "hits": [ + { + "_index": "fuzzy-test", + "_id": "1", + "_score": 0.07845875, + "_source": { + "product": "lantern" + } + } + ] + } +} +``` diff --git a/_query-dsl/geo-and-xy/geo-bounding-box.md b/_query-dsl/geo-and-xy/geo-bounding-box.md index a0ee85f0..11836a66 100644 --- a/_query-dsl/geo-and-xy/geo-bounding-box.md +++ b/_query-dsl/geo-and-xy/geo-bounding-box.md @@ -2,7 +2,6 @@ layout: default title: Geo-bounding box parent: Geographic and xy queries -grand_parent: Query DSL nav_order: 10 redirect_from: - /opensearch/query-dsl/geo-and-xy/geo-bounding-box/ @@ -31,6 +30,7 @@ PUT testindex1 } } ``` +{% include copy-curl.html %} Index three geopoints as objects with latitudes and longitudes: @@ -42,7 +42,10 @@ PUT testindex1/_doc/1 "lon": 40.71 } } +``` +{% include copy-curl.html %} +```json PUT testindex1/_doc/2 { "point": { @@ -50,7 +53,10 @@ PUT testindex1/_doc/2 "lon": 22.62 } } +``` +{% include copy-curl.html %} +```json PUT testindex1/_doc/3 { "point": { @@ -59,6 +65,7 @@ PUT testindex1/_doc/3 } } ``` +{% include copy-curl.html %} Search for all documents and filter the documents whose points lie within the rectangle defined in the query: @@ -88,6 +95,7 @@ GET testindex1/_search } } ``` +{% include copy-curl.html %} The response contains the matching document: @@ -133,12 +141,18 @@ Geopoint coordinates are always rounded down at index time. At query time, the u ## Specifying the bounding box -You can specify the bounding box by providing any of the following combinations of its vertex coordinates: +You can specify the bounding box by providing vertex coordinates, a geohash, or a [Well-Known Text (WKT)](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) string. + +### Using vertex coordinates to specify the bounding box + +Provide any of the following combinations of vertex coordinates: - `top_left` and `bottom_right` - `top_right` and `bottom_left` - `top`, `left`, `bottom`, and `right` +Specify the coordinate values in any [format]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) that the geopoint field type accepts. + The following example shows how to specify the bounding box using the `top`, `left`, `bottom`, and `right` coordinates: ```json @@ -163,21 +177,7 @@ GET testindex1/_search } } ``` - -## Request fields - -Geo-bounding box queries accept the following fields. - -Field | Data type | Description -:--- | :--- | :--- -`_name` | String | The name of the filter. Optional. -`validation_method` | String | The validation method. Valid values are `IGNORE_MALFORMED` (accept geopoints with invalid coordinates), `COERCE` (try to coerce coordinates to valid values), and `STRICT` (return an error when coordinates are invalid). Default is `STRICT`. -`type` | String | Specifies how to execute the filter. Valid values are `indexed` (index the filter) and `memory` (execute the filter in memory). Default is `memory`. -`ignore_unmapped` | Boolean | Specifies whether to ignore an unmapped field. If set to `true`, the query does not return any documents that have an unmapped field. If set to `false`, an exception is thrown when the field is unmapped. Default is `false`. - -## Accepted formats - -You can specify coordinates of the bounding box vertices in any [format]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) that the geopoint field type accepts. +{% include copy-curl.html %} ### Using a geohash to specify the bounding box @@ -205,6 +205,7 @@ GET testindex1/_search } } ``` +{% include copy-curl.html %} To specify a bounding box that covers the whole area of a geohash, provide that geohash as both `top_left` and `bottom_right` parameters of the bounding box: @@ -227,4 +228,44 @@ GET testindex1/_search } } } -``` \ No newline at end of file +``` +{% include copy-curl.html %} + +### Using WKT to specify the bounding box + +To define the bounding box in WKT format, provide the `wkt` parameter with a bounding rectangle in the form `BBOX (minLon, maxLon, maxLat, minLat)`. `BBOX` is the only WKT geometry that a geo-bounding box query accepts. + +The following example shows how to use WKT to specify the same bounding box as the previous examples: + +```json +GET testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_bounding_box": { + "point": { + "wkt": "BBOX (28, 41, 75, 73)" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Parameters + +Geo-bounding box queries accept the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`_name` | String | The name of the filter. Optional. +`validation_method` | String | The validation method. Valid values are `IGNORE_MALFORMED` (accept geopoints with invalid coordinates), `COERCE` (try to coerce coordinates to valid values), and `STRICT` (return an error when coordinates are invalid). Default is `STRICT`. +`type` | String | Specifies how to execute the filter. Valid values are `indexed` (index the filter) and `memory` (execute the filter in memory). Default is `memory`. +`ignore_unmapped` | Boolean | Specifies whether to ignore an unmapped field. If set to `true`, the query does not return any documents that have an unmapped field. If set to `false`, an exception is thrown when the field is unmapped. Default is `false`. + diff --git a/_query-dsl/geo-and-xy/geodistance.md b/_query-dsl/geo-and-xy/geodistance.md new file mode 100644 index 00000000..c23bb845 --- /dev/null +++ b/_query-dsl/geo-and-xy/geodistance.md @@ -0,0 +1,120 @@ +--- +layout: default +title: Geodistance +parent: Geographic and xy queries +nav_order: 20 +--- + +# Geodistance query + +A geodistance query returns documents with geopoints that are within a specified distance from the provided geopoint. A document with multiple geopoints matches the query if at least one geopoint matches the query. + +The searched document field must be mapped as `geo_point`. +{: .note} + +## Example + +Create a mapping with the `point` field mapped as `geo_point`: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` +{% include copy-curl.html %} + +Index a geopoint, specifying its latitude and longitude: + +```json +PUT testindex1/_doc/1 +{ + "point": { + "lat": 74.00, + "lon": 40.71 + } +} +``` +{% include copy-curl.html %} + +Search for documents whose `point` objects are within the specified `distance` from the specified `point`: + +```json +GET /testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_distance": { + "distance": "50mi", + "point": { + "lat": 73.5, + "lon": 40.5 + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "point": { + "lat": 74, + "lon": 40.71 + } + } + } + ] + } +} +``` + +## Parameters + +Geodistance queries accept the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`_name` | String | The name of the filter. Optional. +`distance` | String | The distance within which to match the points. This distance is the radius of a circle centered at the specified point. For supported distance units, see [Distance units]({{site.url}}{{site.baseurl}}/api-reference/units/#distance-units). Required. +`distance_type` | String | Specifies how to calculate the distance. Valid values are `arc` or `plane` (faster but inaccurate for long distances or points close to the poles). Optional. Default is `arc`. +`validation_method` | String | The validation method. Valid values are `IGNORE_MALFORMED` (accept geopoints with invalid coordinates), `COERCE` (try to coerce coordinates to valid values), and `STRICT` (return an error when coordinates are invalid). Optional. Default is `STRICT`. +`ignore_unmapped` | Boolean | Specifies whether to ignore an unmapped field. If set to `true`, then the query does not return any documents that contain an unmapped field. If set to `false`, then an exception is thrown when the field is unmapped. Optional. Default is `false`. + +## Accepted formats + +You can specify the geopoint coordinates when indexing a document and searching for documents in any [format]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) accepted by the geopoint field type. \ No newline at end of file diff --git a/_query-dsl/geo-and-xy/geopolygon.md b/_query-dsl/geo-and-xy/geopolygon.md new file mode 100644 index 00000000..810e48f2 --- /dev/null +++ b/_query-dsl/geo-and-xy/geopolygon.md @@ -0,0 +1,176 @@ +--- +layout: default +title: Geopolygon +parent: Geographic and xy queries +nav_order: 30 +--- + +# Geopolygon query + +A geopolygon query returns documents containing geopoints that are within the specified polygon. A document containing multiple geopoints matches the query if at least one geopoint matches the query. + +A polygon is specified by a list of vertices in coordinate form. Unlike specifying a polygon for a geoshape field, the polygon does not have to be closed (specifying the first and last points at the same is unnecessary). Though points do not have to follow either clockwise or counterclockwise order, it is recommended that you list them in either of these orders. This will ensure that the correct polygon is captured. + +The searched document field must be mapped as `geo_point`. +{: .note} + +## Example + +Create a mapping with the `point` field mapped as `geo_point`: + +```json +PUT /testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` +{% include copy-curl.html %} + +Index a geopoint, specifying its latitude and longitude: + +```json +PUT testindex1/_doc/1 +{ + "point": { + "lat": 73.71, + "lon": 41.32 + } +} +``` +{% include copy-curl.html %} + +Search for documents whose `point` objects are within the specified `geo_polygon`: + +```json +GET /testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 73.7562, "lon": 42.6526 }, + { "lat": 73.3245, "lon": 41.6189 }, + { "lat": 74.0060, "lon": 40.7128 } + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The polygon specified in the preceding request is the quadrilateral depicted in the following image. The matching document is within this quadrilateral. The coordinates of the quadrilateral vertices are specified in `(latitude, longitude)` format. + +![Search for points within the specified quadrilateral]({{site.url}}{{site.baseurl}}/images/geopolygon-query.png) + +The response contains the matching document: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "point": { + "lat": 73.71, + "lon": 41.32 + } + } + } + ] + } +} +``` + +In the preceding search request, you specified the polygon vertices in clockwise order: + +```json +"geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 73.7562, "lon": 42.6526 }, + { "lat": 73.3245, "lon": 41.6189 }, + { "lat": 74.0060, "lon": 40.7128 } + ] + } +} +``` + +Alternatively, you can specify the vertices in counterclockwise order: + +```json +"geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 74.0060, "lon": 40.7128 }, + { "lat": 73.3245, "lon": 41.6189 }, + { "lat": 73.7562, "lon": 42.6526 } + ] + } +} +``` + +The resulting query response contains the same matching document. + +However, if you specify the vertices in the following order: + +```json +"geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 74.0060, "lon": 40.7128 }, + { "lat": 73.7562, "lon": 42.6526 }, + { "lat": 73.3245, "lon": 41.6189 } + ] + } +} +``` + +The response returns no results. + +## Parameters + +Geopolygon queries accept the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`_name` | String | The name of the filter. Optional. +`validation_method` | String | The validation method. Valid values are `IGNORE_MALFORMED` (accept geopoints with invalid coordinates), `COERCE` (try to coerce coordinates to valid values), and `STRICT` (return an error when coordinates are invalid). Optional. Default is `STRICT`. +`ignore_unmapped` | Boolean | Specifies whether to ignore an unmapped field. If set to `true`, then the query does not return any documents that contain an unmapped field. If set to `false`, then an exception is thrown when the field is unmapped. Optional. Default is `false`. + +## Accepted formats + +You can specify the geopoint coordinates when indexing a document and searching for documents in any [format]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point#formats) accepted by the geopoint field type. \ No newline at end of file diff --git a/_query-dsl/geo-and-xy/geoshape.md b/_query-dsl/geo-and-xy/geoshape.md new file mode 100644 index 00000000..2bf3bd52 --- /dev/null +++ b/_query-dsl/geo-and-xy/geoshape.md @@ -0,0 +1,736 @@ +--- +layout: default +title: Geoshape +parent: Geographic and xy queries +nav_order: 40 +--- + +# Geoshape query + +Use a geoshape query to search for documents that contain [geopoint]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point/) or [geoshape]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-shape/) fields. You can filter documents using a [geoshape that is defined within a query](#using-a-new-shape-definition) or use a [pre-indexed geoshape](#using-a-pre-indexed-shape-definition). + +The searched document field must be mapped as `geo_point` or `geo_shape`. +{: .note} + +## Spatial relations + +When you provide a geoshape to the geoshape query, the geopoint and geoshape fields in the documents are matched using the following spatial relations to the provided shape. + +Relation | Description | Supporting geographic field type +:--- | :--- | :--- +`INTERSECTS` | (Default) Matches documents whose geopoint or geoshape intersects with the shape provided in the query. | `geo_point`, `geo_shape` +`DISJOINT` | Matches documents whose geoshape does not intersect with the shape provided in the query. | `geo_shape` +`WITHIN` | Matches documents whose geoshape is completely within the shape provided in the query. | `geo_shape` +`CONTAINS` | Matches documents whose geoshape completely contains the shape provided in the query. | `geo_shape` + +## Defining the shape in a geoshape query + +You can define the shape to filter documents in a geoshape query either by [providing a new shape definition at query time](#using-a-new-shape-definition) or by [referencing the name of a shape pre-indexed in another index](#using-a-pre-indexed-shape-definition). + +## Using a new shape definition + +To provide a new shape to a geoshape query, define it in the `geo_shape` field. You can define the geoshape in [GeoJSON format](https://geojson.org/) or [Well-Known Text (WKT) format](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html). + +The following example illustrates searching for documents containing geoshapes that match a geoshape defined at query time. + +### Step 1: Create an index + +First, create an index and map the `location` field as a `geo_shape`: + +```json +PUT /testindex +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape" + } + } + } +} +``` +{% include copy-curl.html %} + +### Step 2: Index documents + +Index one document containing a point and another containing a polygon: + +```json +PUT testindex/_doc/1 +{ + "location": { + "type": "point", + "coordinates": [ 73.0515, 41.5582 ] + } +} +``` +{% include copy-curl.html %} + +```json +PUT testindex/_doc/2 +{ + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } +} +``` +{% include copy-curl.html %} + +### Step 3: Run a geoshape query + +Finally, define a geoshape to filter the documents. The following sections illustrate providing various geoshapes in a query. For more information about various geoshape formats, see [Geoshape field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape/). + +#### Envelope + +An [`envelope`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape#envelope) is a bounding rectangle in the `[[minLon, maxLat], [maxLon, minLat]]` format. Search for documents containing geoshape fields that intersect with the provided envelope: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "envelope", + "coordinates": [ + [ + 71.0589, + 42.3601 + ], + [ + 74.006, + 40.7128 + ] + ] + }, + "relation": "WITHIN" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains both documents: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0, + "_source": { + "location": { + "type": "point", + "coordinates": [ + 73.0515, + 41.5582 + ] + } + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 0, + "_source": { + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } + } + } + ] + } +} +``` + +#### Point + +Search for documents whose geoshape fields contain the provided point: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "point", + "coordinates": [ + 72.8000, + 41.6300 + ] + }, + "relation": "CONTAINS" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Linestring + +Search for documents whose geoshape fields do not intersect with the provided linestring: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "linestring", + "coordinates": [[74.0060, 40.7128], [71.0589, 42.3601]] + }, + "relation": "DISJOINT" + } + } + } +} +``` +{% include copy-curl.html %} + +Linestring geoshape queries do not support the `WITHIN` relation. +{: .note} + +#### Polygon + +In GeoJSON format, you must list the vertices of the polygon in counterclockwise order and close the polygon so that the first vertex and the last vertex are the same. + +Search for documents whose geoshape fields are within the provided polygon: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "polygon", + "coordinates": [ + [ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ] + ] + }, + "relation": "WITHIN" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Multipoint + +Search for documents whose geoshape fields do not intersect with the provided points: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "multipoint", + "coordinates" : [ + [74.0060, 40.7128], + [71.0589, 42.3601] + ] + }, + "relation": "DISJOINT" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Multilinestring + +Search for documents whose geoshape fields do not intersect with the provided lines: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "multilinestring", + "coordinates" : [ + [[74.0060, 40.7128], [71.0589, 42.3601]], + [[73.7562, 42.6526], [72.6734, 41.7658]] + ] + }, + "relation": "disjoint" + } + } + } +} +``` +{% include copy-curl.html %} + +Multilinestring geoshape queries do not support the `WITHIN` relation. +{: .note} + +#### Multipolygon + +Search for documents whose geoshape fields are within the provided multipolygon: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type" : "multipolygon", + "coordinates" : [ + [ + [ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ], + [ + [73.0515, 41.5582], + [72.6506, 41.5623], + [72.6734, 41.7658], + [73.0515, 41.5582] + ] + ], + [ + [ + [73.9146, 40.8252], + [73.8871, 41.0389], + [73.6853, 40.9747], + [73.9146, 40.8252] + ] + ] + ] + }, + "relation": "WITHIN" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Geometry collection + +Search for documents whose geoshape fields are within the provided polygons: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "geometrycollection", + "geometries": [ + { + "type": "polygon", + "coordinates": [[ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ]] + }, + { + "type": "polygon", + "coordinates": [[ + [73.0515, 41.5582], + [72.6506, 41.5623], + [72.6734, 41.7658], + [73.0515, 41.5582] + ]] + } + ] + }, + "relation": "WITHIN" + } + } + } +} +``` +{% include copy-curl.html %} + +Geoshape queries whose geometry collection contains a linestring or a multilinestring do not support the `WITHIN` relation. +{: .note} + +## Using a pre-indexed shape definition + +When constructing a geoshape query, you can also reference the name of a shape pre-indexed in another index. Using this method, you can define a geoshape at index time and refer to it by name at search time. + +You can define a pre-indexed geoshape in [GeoJSON](https://geojson.org/) or [Well-Known Text (WKT)](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) format. For more information about various geoshape formats, see [Geoshape field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape/). + +The `indexed_shape` object supports the following parameters. + +Parameter | Required/Optional | Description +:--- | :--- | :--- +`id` | Required | The document ID of the document containing the pre-indexed shape. +`index` | Optional | The name of the index containing the pre-indexed shape. Default is `shapes`. +`path` | Optional | The field name of the field containing the pre-indexed shape as a path. Default is `shape`. +`routing` | Optional | The routing value of the document containing the pre-indexed shape. Required if the shape document was indexed with a custom routing value. + +The following example illustrates how to reference the name of a shape pre-indexed in another index. In this example, the index `pre-indexed-shapes` contains the shape that defines the boundaries, and the index `testindex` contains the shapes that are checked against those boundaries. + +First, create the `pre-indexed-shapes` index and map the `boundaries` field for this index as a `geo_shape`: + +```json +PUT /pre-indexed-shapes +{ + "mappings": { + "properties": { + "boundaries": { + "type": "geo_shape", + "orientation" : "left" + } + } + } +} +``` +{% include copy-curl.html %} + +For more information about specifying a different vertex orientation for polygons, see [Polygon]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-shape/#polygon). + +Index a polygon specifying the search boundaries into the `pre-indexed-shapes` index. The polygon's ID is `search_triangle`. In this example, you'll index the polygon in WKT format: + +```json +PUT /pre-indexed-shapes/_doc/search_triangle +{ + "boundaries": + "POLYGON ((74.0060 40.7128, 71.0589 42.3601, 73.7562 42.6526, 74.0060 40.7128))" +} +``` +{% include copy-curl.html %} + +If you haven't already done so, index one document containing a point and another document containing a polygon into the `testindex` index: + +```json +PUT /testindex/_doc/1 +{ + "location": { + "type": "point", + "coordinates": [ 73.0515, 41.5582 ] + } +} +``` +{% include copy-curl.html %} + +```json +PUT /testindex/_doc/2 +{ + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } +} +``` +{% include copy-curl.html %} + +Search for documents whose geoshapes are within the `search_triangle`: + +```json +GET /testindex/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_shape": { + "location": { + "indexed_shape": { + "index": "pre-indexed-shapes", + "id": "search_triangle", + "path": "boundaries" + }, + "relation": "WITHIN" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains both documents: + +```json +{ + "took": 11, + "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": { + "location": { + "type": "point", + "coordinates": [ + 73.0515, + 41.5582 + ] + } + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 1, + "_source": { + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } + } + } + ] + } +} +``` + +## Querying geopoints + +You can also use a geoshape query to search for documents containing geopoints. + +Geoshape queries on geopoint fields only support the default `INTERSECTS` spatial relation, so you don't need to provide the `relation` parameter. +{: .note} + +{: .important } +> Geoshape queries on geopoint fields do not support the following geoshapes: +> +> - Points +> - Linestrings +> - Multipoints +> - Multilinestrings +> - Geometry collections containing one of the preceding geoshape types + +Create a mapping where `location` is a `geo_point`: + +```json +PUT /testindex1 +{ + "mappings": { + "properties": { + "location": { + "type": "geo_point" + } + } + } +} +``` +{% include copy-curl.html %} + +Index two points into the index. In this example, you'll provide the geopoint coordinates as strings: + +```json +PUT /testindex1/_doc/1 +{ + "location": "41.5623, 72.6506" +} +``` +{% include copy-curl.html %} + +```json +PUT /testindex1/_doc/2 +{ + "location": "76.0254, 39.2467" +} +``` +{% include copy-curl.html %} + + For information about providing geopoint coordinates in various formats, see [Formats]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/#formats). + +Search for geopoints that intersect with the provided polygon: + +```json +GET /testindex1/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "polygon", + "coordinates": [ + [ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ] + ] + } + } + } + } +} + +``` +{% include copy-curl.html %} + +The response returns document 1: + +```json +{ + "took": 21, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 0, + "_source": { + "location": "41.5623, 72.6506" + } + } + ] + } +} +``` + +Note that when you indexed the geopoints, you specified their coordinates in `"latitude, longitude"` format. When you search for matching documents, the coordinate array is in `[longitude, latitude]` format. Thus, document 1 is returned in the results but document 2 is not. + +## Parameters + +Geoshape queries accept the following parameters. + +Parameter | Data type | Description +:--- | :--- | :--- +`ignore_unmapped` | Boolean | Specifies whether to ignore an unmapped field. If set to `true`, then the query does not return any documents that contain an unmapped field. If set to `false`, then an exception is thrown when the field is unmapped. Optional. Default is `false`. + +## Expensive queries + +Geoshape fields store shapes in a BKD tree by default, and queries on those fields run regardless of the [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) setting. + +A geoshape field mapped with the `tree` or `strategy` parameter stores shapes in a prefix tree instead. Queries on a prefix tree field run only when `search.allow_expensive_queries` is `true`. \ No newline at end of file diff --git a/_query-dsl/geo-and-xy/index.md b/_query-dsl/geo-and-xy/index.md index a1d76f04..c18815a6 100644 --- a/_query-dsl/geo-and-xy/index.md +++ b/_query-dsl/geo-and-xy/index.md @@ -2,16 +2,17 @@ layout: default title: Geographic and xy queries has_children: true -nav_order: 50 +nav_order: 65 redirect_from: - /opensearch/query-dsl/geo-and-xy/index/ - /query-dsl/query-dsl/geo-and-xy/ - /query-dsl/query-dsl/geo-and-xy/index/ + - /query-dsl/geo-and-xy/ --- # Geographic and xy queries -Geographic and xy queries let you search fields that contain points and shapes on a map or coordinate plane. Geographic queries work on geospatial data, while xy queries work on two-dimensional coordinate data. Out of all geographic queries, the geoshape query is very similar to the xy query, but the former searches [geographic fields]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geographic), while the latter searches [Cartesian fields]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy). +Geographic and xy queries let you search fields that contain points and shapes on a map or coordinate plane. Geographic queries work on geospatial data, while xy queries work on two-dimensional coordinate data. Out of all geographic queries, the geoshape query is very similar to the xy query, but the former searches [geographic fields]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geographic/), while the latter searches [Cartesian fields]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy). ## xy queries @@ -23,13 +24,13 @@ xy queries return documents that contain: ## Geographic queries -Geographic queries search for documents that contain geospatial geometries. These geometries can be specified in [`geo_point`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point) fields, which support points on a map, and [`geo_shape`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-shape) fields, which support points, lines, circles, and polygons. +Geographic queries search for documents that contain geospatial geometries. These geometries can be specified in [`geo_point`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point/) fields, which support points on a map, and [`geo_shape`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-shape/) fields, which support points, lines, circles, and polygons. OpenSearch provides the following geographic query types: -- [**Geo-bounding box queries**]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/geo-and-xy/geo-bounding-box/): Return documents with geopoint field values that are within a bounding box. -- **Geodistance queries** return documents with geopoints that are within a specified distance from the provided geopoint. -- **Geopolygon queries** return documents with geopoints that are within a polygon. -- **Geoshape queries** return documents that contain: - - geoshapes and geopoints that have one of four spatial relations to the provided shape: `INTERSECTS`, `DISJOINT`, `WITHIN`, or `CONTAINS`. - - geopoints that intersect the provided shape. \ No newline at end of file +| Query type | Description | +| :--- | :--- | +| [Geo-bounding box]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/geo-and-xy/geo-bounding-box/) | Returns documents with geopoint field values that are within a bounding box. | +| [Geodistance]({{site.url}}{{site.baseurl}}/query-dsl/geo-and-xy/geodistance/) | Returns documents with geopoints that are within a specified distance from the provided geopoint. | +| [Geopolygon]({{site.url}}{{site.baseurl}}/query-dsl/geo-and-xy/geopolygon/) | Returns documents containing geopoints that are within a polygon. | +| [Geoshape]({{site.url}}{{site.baseurl}}/query-dsl/geo-and-xy/geoshape/) | Returns documents containing geoshapes and geopoints that have one of four spatial relations to the provided shape (`INTERSECTS`, `DISJOINT`, `WITHIN`, or `CONTAINS`) or geopoints that intersect the provided shape. | diff --git a/_query-dsl/geo-and-xy/xy.md b/_query-dsl/geo-and-xy/xy.md index 3db05c01..8db6dae4 100644 --- a/_query-dsl/geo-and-xy/xy.md +++ b/_query-dsl/geo-and-xy/xy.md @@ -2,9 +2,7 @@ layout: default title: xy parent: Geographic and xy queries -grand_parent: Query DSL nav_order: 50 - redirect_from: - /opensearch/query-dsl/geo-and-xy/xy/ - /query-dsl/query-dsl/geo-and-xy/xy/ @@ -12,13 +10,13 @@ redirect_from: # xy query -To search for documents that contain [xy point]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy-point) and [xy shape]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy-shape) fields, use an xy query. +To search for documents that contain [xy point]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy-point/) or [xy shape]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy-shape/) fields, use an xy query. ## Spatial relations -When you provide an xy shape to the xy query, the xy fields are matched using the following spatial relations to the provided shape. +When you provide an xy shape to the xy query, the xy fields in the documents are matched using the following spatial relations to the provided shape. -Relation | Description | Supporting xy Field Type +Relation | Description | Supporting xy field type :--- | :--- | :--- `INTERSECTS` | (Default) Matches documents whose xy point or xy shape intersects the shape provided in the query. | `xy_point`, `xy_shape` `DISJOINT` | Matches documents whose xy shape does not intersect with the shape provided in the query. | `xy_shape` @@ -35,7 +33,7 @@ You can define the shape in an xy query either by providing a new shape definiti To provide a new shape to an xy query, define it in the `xy_shape` field. -The following example illustrates searching for documents with xy shapes that match an xy shape defined at query time. +The following example illustrates how to search for documents containing xy shapes that match an xy shape defined at query time. First, create an index and map the `geometry` field as an `xy_shape`: @@ -51,6 +49,7 @@ PUT testindex } } ``` +{% include copy-curl.html %} Index a document with a point and a document with a polygon: @@ -62,7 +61,10 @@ PUT testindex/_doc/1 "coordinates": [0.5, 3.0] } } +``` +{% include copy-curl.html %} +```json PUT testindex/_doc/2 { "geometry" : { @@ -77,6 +79,7 @@ PUT testindex/_doc/2 } } ``` +{% include copy-curl.html %} Define an [`envelope`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/xy-shape#envelope)—a bounding rectangle in the `[[minX, maxY], [maxX, minY]]` format. Search for documents with xy points or shapes that intersect that envelope: @@ -96,10 +99,11 @@ GET testindex/_search } } ``` +{% include copy-curl.html %} The following image depicts the example. Both the point and the polygon are within the bounding envelope. -<img src="{{site.url}}{{site.baseurl}}/images/xy_query.png" alt="xy shape query" width="250"> +![xy shape query]({{site.url}}{{site.baseurl}}/images/xy_query.png){: width="250" } The response contains both documents: @@ -183,6 +187,7 @@ Parameter | Description `index` | The name of the index that contains the pre-indexed shape. `id` | The document ID of the document that contains the pre-indexed shape. `path` | The field name of the field that contains the pre-indexed shape as a path. +`routing` | The routing value of the document that contains the pre-indexed shape. Required if the shape document was indexed with a custom routing value. The following example illustrates referencing the name of a shape pre-indexed in another index. In this example, the index `pre-indexed-shapes` contains the shape that defines the boundaries, and the index `testindex` contains the shapes whose locations are checked against those boundaries. @@ -200,6 +205,7 @@ PUT pre-indexed-shapes } } ``` +{% include copy-curl.html %} Index an envelope that specifies the boundaries and name it `rectangle`: @@ -212,6 +218,7 @@ PUT pre-indexed-shapes/_doc/rectangle } } ``` +{% include copy-curl.html %} Index a document with a point and a document with a polygon into the index `testindex`: @@ -223,7 +230,10 @@ PUT testindex/_doc/1 "coordinates": [0.5, 3.0] } } +``` +{% include copy-curl.html %} +```json PUT testindex/_doc/2 { "geometry" : { @@ -238,6 +248,7 @@ PUT testindex/_doc/2 } } ``` +{% include copy-curl.html %} Search for documents with shapes that intersect `rectangle` in the index `testindex` using a filter: @@ -261,6 +272,7 @@ GET testindex/_search } } ``` +{% include copy-curl.html %} The preceding query uses the default spatial relation `INTERSECTS` and returns both the point and the polygon: @@ -352,6 +364,7 @@ PUT testindex1 } } ``` +{% include copy-curl.html %} Index three points: @@ -360,17 +373,24 @@ PUT testindex1/_doc/1 { "point": "1.0, 1.0" } +``` +{% include copy-curl.html %} +```json PUT testindex1/_doc/2 { "point": "2.0, 0.0" } +``` +{% include copy-curl.html %} +```json PUT testindex1/_doc/3 { "point": "-2.0, 2.0" } ``` +{% include copy-curl.html %} Search for points that lie within the circle with the center at (0, 0) and a radius of 2: @@ -390,13 +410,14 @@ GET testindex1/_search } } ``` +{% include copy-curl.html %} xy point only supports the default `INTERSECTS` spatial relation, so you don't need to provide the `relation` parameter. {: .note} The following image depicts the example. Points 1 and 2 are within the circle, and point 3 is outside the circle. -<img src="{{site.url}}{{site.baseurl}}/images/xy_query_point.png" alt="xy point query" width="300"> +![xy point query]({{site.url}}{{site.baseurl}}/images/xy_query_point.png){: width="300" } The response returns documents 1 and 2: diff --git a/_query-dsl/index.md b/_query-dsl/index.md index bf75d899..0e1c4055 100644 --- a/_query-dsl/index.md +++ b/_query-dsl/index.md @@ -44,7 +44,7 @@ Broadly, you can classify queries into two categories---*leaf queries* and *comp - [Geographic and xy queries]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/geo-and-xy/index/): Use geographic queries to search documents that include geographic data. Use xy queries to search documents that include points and shapes in a two-dimensional coordinate system. - - Joining queries: Use joining queries to search nested fields or return parent and child documents that match a specific query. Types of joining queries include `nested`, `has_child`, `has_parent`, and `parent_id` queries. + - [Joining queries]({{site.url}}{{site.baseurl}}/query-dsl/joining/): Use joining queries to search nested fields or return parent and child documents that match a specific query. Types of joining queries include `nested`, `has_child`, `has_parent`, and `parent_id` queries. - [Span queries]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/span-query/): Use span queries to perform precise positional searches. Span queries are low-level, specific queries that provide control over the order and proximity of specified query terms. They are primarily used to search legal documents. @@ -92,10 +92,11 @@ Expensive queries can consume a lot of memory and lead to a decline in cluster p - [`fuzzy`]({{site.url}}{{site.baseurl}}/query-dsl/term/fuzzy/) queries - [`prefix`]({{site.url}}{{site.baseurl}}/query-dsl/term/prefix/) queries -- [`range`]({{site.url}}{{site.baseurl}}/query-dsl/term/range/) queries on [`text`]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/text/) and [`keyword`]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/keyword/) fields +- [`range`]({{site.url}}{{site.baseurl}}/query-dsl/term/range/) queries on [`text`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) and [`keyword`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/keyword/) fields - [`regexp`]({{site.url}}{{site.baseurl}}/query-dsl/term/regexp/) queries - [`wildcard`]({{site.url}}{{site.baseurl}}/query-dsl/term/wildcard/) queries - [`query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) queries that are internally transformed into prefix queries +- [`geo_shape`]({{site.url}}{{site.baseurl}}/query-dsl/geo-and-xy/geoshape/) queries on geoshape fields that store shapes in a prefix tree To disallow expensive queries, you can disable the `search.allow_expensive_queries` cluster setting as follows: @@ -109,5 +110,5 @@ PUT _cluster/settings ``` {% include copy-curl.html %} -To track expensive queries, enable [shard slow logs]({{site.url}}{{site.baseurl}}/monitoring-your-cluster/logs/#shard-slow-logs). +To track expensive queries, enable [shard slow logs]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/logs/#shard-slow-logs). {: .tip} \ No newline at end of file diff --git a/_query-dsl/joining/has-child.md b/_query-dsl/joining/has-child.md new file mode 100644 index 00000000..df5e124b --- /dev/null +++ b/_query-dsl/joining/has-child.md @@ -0,0 +1,398 @@ +--- +layout: default +title: Has child +parent: Joining queries +nav_order: 10 +--- + +# Has child query + +The `has_child` query returns parent documents whose child documents match a specific query. You can establish parent/child relationships between documents in the same index by using a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field type. + +The `has_child` query is slower than other queries because of the join operation it performs. Performance decreases as the number of matching child documents pointing to different parent documents increases. Each `has_child` query in your search may significantly impact query performance. If you prioritize speed, avoid using this query or limit its usage as much as possible. +{: .warning} + +## Example + +Before you can run a `has_child` query, your index must contain a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field in order to establish parent/child relationships. The index mapping request uses the following format: + +```json +PUT /example_index +{ + "mappings": { + "properties": { + "relationship_field": { + "type": "join", + "relations": { + "parent_doc": "child_doc" + } + } + } + } +} +``` +{% include copy-curl.html %} + +In this example, you'll configure an index that contains documents representing products and their brands. + +First, create the index and establish the parent/child relationship between `brand` and `product`: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "product_to_brand": { + "type": "join", + "relations": { + "brand": "product" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index two parent (brand) documents: + +```json +PUT testindex1/_doc/1 +{ + "name": "Luxury brand", + "product_to_brand" : "brand" +} +``` +{% include copy-curl.html %} + +```json +PUT testindex1/_doc/2 +{ + "name": "Economy brand", + "product_to_brand" : "brand" +} +``` +{% include copy-curl.html %} + +Index three child (product) documents: + +```json +PUT testindex1/_doc/3?routing=1 +{ + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } +} +``` +{% include copy-curl.html %} + +```json +PUT testindex1/_doc/4?routing=2 +{ + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } +} +``` +{% include copy-curl.html %} + +```json +PUT testindex1/_doc/5?routing=2 +{ + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } +} +``` +{% include copy-curl.html %} + +To search for the parent of a child, use a `has_child` query. The following query returns parent documents (brands) that make watches: + +```json +GET testindex1/_search +{ + "query" : { + "has_child": { + "type":"product", + "query": { + "match" : { + "name": "watch" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response returns both brands: + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "name": "Luxury brand", + "product_to_brand": "brand" + } + }, + { + "_index": "testindex1", + "_id": "2", + "_score": 1, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + } + ] + } +} +``` + +## Retrieving inner hits + +To return child documents that matched the query, provide the `inner_hits` parameter: + +```json +GET testindex1/_search +{ + "query" : { + "has_child": { + "type":"product", + "query": { + "match" : { + "name": "watch" + } + }, + "inner_hits": {} + } + } +} +``` +{% include copy-curl.html %} + +The response contains child documents in the `inner_hits` field: + +```json +{ + "took": 52, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "name": "Luxury brand", + "product_to_brand": "brand" + }, + "inner_hits": { + "product": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.53899646, + "hits": [ + { + "_index": "testindex1", + "_id": "3", + "_score": 0.53899646, + "_routing": "1", + "_source": { + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } + } + } + ] + } + } + } + }, + { + "_index": "testindex1", + "_id": "2", + "_score": 1, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + }, + "inner_hits": { + "product": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.53899646, + "hits": [ + { + "_index": "testindex1", + "_id": "4", + "_score": 0.53899646, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 0.53899646, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + } + ] + } + } + } + } + ] + } +} +``` + +For more information about retrieving inner hits, see [Inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). + +## Parameters + +The following table lists all top-level parameters supported by `has_child` queries. + +| Parameter | Required/Optional | Description | +|:---|:---|:---| +| `type` | Required | Specifies the name of the child relationship as defined in the `join` field mapping. | +| `query` | Required | The query to run on child documents. If a child document matches the query, the parent document is returned. | +| `ignore_unmapped` | Optional | Indicates whether to ignore unmapped `type` fields and not return documents instead of throwing an error. You can provide this parameter when querying multiple indexes, some of which may not contain the `type` field. Default is `false`. | +| `max_children` | Optional | The maximum number of matching child documents for a parent document. If exceeded, the parent document is excluded from the search results. | +| `min_children` | Optional | The minimum number of matching child documents required for a parent document to be included in the results. If not met, the parent is excluded. Default is `1`.| +| `score_mode` | Optional | Defines how scores of matching child documents influence the parent document's score. Valid values are: <br> - `none`: Ignores the relevance scores of child documents and assigns a score of `0` to the parent document. <br> - `avg`: Uses the average relevance score of all matching child documents. <br> - `max`: Assigns the highest relevance score from the matching child documents to the parent. <br> - `min`: Assigns the lowest relevance score from the matching child documents to the parent. <br> - `sum`: Sums the relevance scores of all matching child documents. <br> Default is `none`. | +| `inner_hits` | Optional | If provided, returns the underlying hits (child documents) that matched the query. | + + +## Sorting limitations + +The `has_child` query does not support [sorting results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/) using standard sorting options. If you need to sort parent documents by fields in their child documents, you can use a [`function_score` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score/) and sort by the parent document's score. + +In the preceding example, you can sort parent documents (brands) based on the `sales_count` of their child products. This query multiplies the score by the `sales_count` field of the child documents and assigns the highest relevance score from the matching child documents to the parent: + +```json +GET testindex1/_search +{ + "query": { + "has_child": { + "type": "product", + "query": { + "function_score": { + "script_score": { + "script": "_score * doc['sales_count'].value" + } + } + }, + "score_mode": "max" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the brands sorted by the highest child `sales_count`: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 300, + "hits": [ + { + "_index": "testindex1", + "_id": "2", + "_score": 300, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + }, + { + "_index": "testindex1", + "_id": "1", + "_score": 150, + "_source": { + "name": "Luxury brand", + "product_to_brand": "brand" + } + } + ] + } +} +``` + +## Next steps + +- Learn more about [retrieving inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). \ No newline at end of file diff --git a/_query-dsl/joining/has-parent.md b/_query-dsl/joining/has-parent.md new file mode 100644 index 00000000..a0eea0f5 --- /dev/null +++ b/_query-dsl/joining/has-parent.md @@ -0,0 +1,358 @@ +--- +layout: default +title: Has parent +parent: Joining queries +nav_order: 20 +--- + +# Has parent query + +The `has_parent` query returns child documents whose parent documents match a specific query. You can establish parent/child relationships between documents in the same index by using a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field type. + +The `has_parent` query is slower than other queries because of the join operation it performs. Performance decreases as the number of matching parent documents increases. Each `has_parent` query in your search may significantly impact query performance. If you prioritize speed, avoid using this query or limit its usage as much as possible. +{: .warning} + +## Example + +Before you can run a `has_parent` query, your index must contain a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field in order to establish parent/child relationships. The index mapping request uses the following format: + +```json +PUT /example_index +{ + "mappings": { + "properties": { + "relationship_field": { + "type": "join", + "relations": { + "parent_doc": "child_doc" + } + } + } + } +} +``` +{% include copy-curl.html %} + +For this example, first configure an index that contains documents representing products and their brands as described in the [`has_child` query example]({{site.url}}{{site.baseurl}}/query-dsl/joining/has-child/). + +To search for the child of a parent, use a `has_parent` query. The following query returns child documents (products) made by the brand matching the query `economy`: + +```json +GET testindex1/_search +{ + "query" : { + "has_parent": { + "parent_type":"brand", + "query": { + "match" : { + "name": "economy" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response returns all products made by the brand: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "4", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + } + ] + } +} +``` + +## Retrieving inner hits + +To return parent documents that matched the query, provide the `inner_hits` parameter: + +```json +GET testindex1/_search +{ + "query" : { + "has_parent": { + "parent_type":"brand", + "query": { + "match" : { + "name": "economy" + } + }, + "inner_hits": {} + } + } +} +``` +{% include copy-curl.html %} + +The response contains parent documents in the `inner_hits` field: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "4", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + }, + "inner_hits": { + "brand": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.3862942, + "hits": [ + { + "_index": "testindex1", + "_id": "2", + "_score": 1.3862942, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + } + ] + } + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + }, + "inner_hits": { + "brand": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.3862942, + "hits": [ + { + "_index": "testindex1", + "_id": "2", + "_score": 1.3862942, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + } + ] + } + } + } + } + ] + } +} +``` + +For more information about retrieving inner hits, see [Inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). + +## Parameters + +The following table lists all top-level parameters supported by `has_parent` queries. + +| Parameter | Required/Optional | Description | +|:---|:---|:---| +| `parent_type` | Required | Specifies the name of the parent relationship as defined in the `join` field mapping. | +| `query` | Required | The query to run on parent documents. If a parent document matches the query, the child document is returned. | +| `ignore_unmapped` | Optional | Indicates whether to ignore unmapped `parent_type` fields and not return documents instead of throwing an error. You can provide this parameter when querying multiple indexes, some of which may not contain the `parent_type` field. Default is `false`. | +| `score` | Optional | Indicates whether the relevance score of a matching parent document is aggregated into its child documents. If `false`, then the relevance score of the parent document is ignored, and each child document is assigned a relevance score equal to the query's `boost`, which defaults to `1`. If `true`, then the relevance score of the matching parent document is aggregated into the relevance scores of its child documents. Default is `false`. | +| `inner_hits` | Optional | If provided, returns the underlying hits (parent documents) that matched the query. | + + +## Sorting limitations + +The `has_parent` query does not support [sorting results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/) using standard sorting options. If you need to sort child documents by fields in their parent documents, you can use a [`function_score` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score/) and sort by the child document's score. + +For the preceding example, first add a `customer_satisfaction` field by which you'll sort the child documents belonging to the parent (brand) documents: + +```json +PUT testindex1/_doc/1 +{ + "name": "Luxury watch brand", + "product_to_brand" : "brand", + "customer_satisfaction": 4.5 +} +``` +{% include copy-curl.html %} + +```json +PUT testindex1/_doc/2 +{ + "name": "Economy watch brand", + "product_to_brand" : "brand", + "customer_satisfaction": 3.9 +} +``` +{% include copy-curl.html %} + +Now you can sort child documents (products) based on the `customer_satisfaction` field of their parent brands. This query multiplies the score by the `customer_satisfaction` field of the parent documents: + +```json +GET testindex1/_search +{ + "query": { + "has_parent": { + "parent_type": "brand", + "score": true, + "query": { + "function_score": { + "script_score": { + "script": "_score * doc['customer_satisfaction'].value" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the products, sorted by the highest parent `customer_satisfaction`: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 4.5, + "hits": [ + { + "_index": "testindex1", + "_id": "3", + "_score": 4.5, + "_routing": "1", + "_source": { + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } + } + }, + { + "_index": "testindex1", + "_id": "4", + "_score": 3.9, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 3.9, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + } + ] + } +} +``` + +## Next steps + +- Learn more about [retrieving inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). \ No newline at end of file diff --git a/_query-dsl/joining/index.md b/_query-dsl/joining/index.md new file mode 100644 index 00000000..21995012 --- /dev/null +++ b/_query-dsl/joining/index.md @@ -0,0 +1,23 @@ +--- +layout: default +title: Joining queries +has_children: true +nav_order: 70 +has_toc: false +redirect_from: + - /query-dsl/joining/ +--- + +# Joining queries + +OpenSearch is a distributed system in which data is spread across multiple nodes. Thus, running a SQL-like JOIN operation in OpenSearch is resource intensive. As an alternative, OpenSearch provides the following queries that perform join operations and are optimized for scaling across multiple nodes: + +| Query type | Description | +| :--- | :--- | +| [`nested`]({{site.url}}{{site.baseurl}}/query-dsl/joining/nested/) | Acts as a wrapper for other queries to search [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) fields. The nested field objects are searched as though they were indexed as separate documents. | +| [`has_child`]({{site.url}}{{site.baseurl}}/query-dsl/joining/has-child/) | Searches for parent documents whose child documents match the query. Requires a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field type. | +| [`has_parent`]({{site.url}}{{site.baseurl}}/query-dsl/joining/has-parent/) | Searches for child documents whose parent documents match the query. Requires a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field type. | +| [`parent_id`]({{site.url}}{{site.baseurl}}/query-dsl/joining/parent-id/) | Searches for child documents that are joined to a specific parent document. Requires a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field type. | + +If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, then joining queries are not executed. +{: .important} \ No newline at end of file diff --git a/_query-dsl/joining/nested.md b/_query-dsl/joining/nested.md new file mode 100644 index 00000000..a56ea4a0 --- /dev/null +++ b/_query-dsl/joining/nested.md @@ -0,0 +1,371 @@ +--- +layout: default +title: Nested +parent: Joining queries +nav_order: 5 +--- + +# Nested query + +The `nested` query acts as a wrapper for other queries to search [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) fields. The nested field objects are searched as though they were indexed as separate documents. If an object matches the search, the `nested` query returns the parent document at the root level. + +## Example + +Before you can run a `nested` query, your index must contain a [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) field. + +To configure an example index containing nested fields, send the following request: + +```json +PUT /testindex +{ + "mappings": { + "properties": { + "patient": { + "type": "nested", + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Next, index a document into the example index: + +```json +PUT /testindex/_doc/1 +{ + "patient": { + "name": "John Doe", + "age": 56 + } +} +``` +{% include copy-curl.html %} + +To search the nested `patient` field, wrap your query in a `nested` query and provide the `path` to the nested field: + +```json +GET /testindex/_search +{ + "query": { + "nested": { + "path": "patient", + "query": { + "match": { + "patient.name": "John" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The query returns the matching document: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.13076457, + "_source": { + "patient": { + "name": "John Doe", + "age": 56 + } + } + } + ] + } +} +``` + +## Retrieving inner hits + +To return inner hits that matched the query, provide the `inner_hits` parameter: + +```json +GET /testindex/_search +{ + "query": { + "nested": { + "path": "patient", + "query": { + "match": { + "patient.name": "John" + } + }, + "inner_hits": {} + } + } +} +``` +{% include copy-curl.html %} + +The response contains the additional `inner_hits` field. The `_nested` field identifies the specific inner object from which the inner hit originated. It contains the nested hit and the offset relative to its position in the `_source`. Because of sorting and scoring, the position of the hit objects in `inner_hits` often differs from their original location in the nested object. + +By default, the `_source` of the hit objects within `inner_hits` is returned relative to the `_nested` field. In this example, the `_source` within `inner_hits` contains the `name` and `age` fields as opposed to the top-level `_source`, which contains the whole `patient` object: + +```json +{ + "took": 38, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.13076457, + "_source": { + "patient": { + "name": "John Doe", + "age": 56 + } + }, + "inner_hits": { + "patient": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_nested": { + "field": "patient", + "offset": 0 + }, + "_score": 0.13076457, + "_source": { + "name": "John Doe", + "age": 56 + } + } + ] + } + } + } + } + ] + } +} +``` + +You can disable returning `_source` by configuring the `_source` field in the mappings. For more information, see [Source]({{site.url}}{{site.baseurl}}/mappings/metadata-fields/source/). +{: .tip} + +For more information about retrieving inner hits, see [Inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). + +## Multi-level nested queries + +You can search documents that have nested objects inside other nested objects using multi-level nested queries. In this example, you'll query multiple layers of nested fields by specifying a nested query for each level of the hierarchy. + +First, create an index with multi-level nested fields: + +```json +PUT /patients +{ + "mappings": { + "properties": { + "patient": { + "type": "nested", + "properties": { + "name": { + "type": "text" + }, + "contacts": { + "type": "nested", + "properties": { + "name": { + "type": "text" + }, + "relationship": { + "type": "text" + }, + "phone": { + "type": "keyword" + } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Next, index two documents into the example index: + +```json +PUT /patients/_doc/1 +{ + "patient": { + "name": "John Doe", + "contacts": [ + { + "name": "Jane Doe", + "relationship": "mother", + "phone": "5551111" + }, + { + "name": "Joe Doe", + "relationship": "father", + "phone": "5552222" + } + ] + } +} +``` +{% include copy-curl.html %} + +```json +PUT /patients/_doc/2?refresh +{ + "patient": { + "name": "Mary Major", + "contacts": [ + { + "name": "Jane Major", + "relationship": "sister", + "phone": "5553333" + }, + { + "name": "Paula Major", + "relationship": "mother", + "phone": "5554444" + } + ] + } +} +``` +{% include copy-curl.html %} + +To search the nested `patient` field, use a multi-level `nested` query. The following query searches for patients whose contact information includes a person named `Jane` with a relationship of `mother`: + +```json +GET /patients/_search +{ + "query": { + "nested": { + "path": "patient", + "query": { + "nested": { + "path": "patient.contacts", + "query": { + "bool": { + "must": [ + { "match": { "patient.contacts.relationship": "mother" } }, + { "match": { "patient.contacts.name": "Jane" } } + ] + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Both conditions in the inner `bool` query must match the same contact object. Document 2 has a contact named `Jane` and a contact whose relationship is `mother`, but they are different contacts, so only document 1 is returned. If `contacts` were mapped as an `object` field instead of `nested`, the contact values would be flattened into arrays, and the same conditions would match both documents. + +The query returns the patient who has a contact entry matching these details: + +```json +{ + "took": 9, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.63013375, + "hits": [ + { + "_index": "patients", + "_id": "1", + "_score": 0.63013375, + "_source": { + "patient": { + "name": "John Doe", + "contacts": [ + { + "name": "Jane Doe", + "relationship": "mother", + "phone": "5551111" + }, + { + "name": "Joe Doe", + "relationship": "father", + "phone": "5552222" + } + ] + } + } + } + ] + } +} +``` + +## Parameters + +The following table lists all top-level parameters supported by `nested` queries. + +| Parameter | Required/Optional | Description | +|:---|:---|:---| +| `path` | Required | Specifies the path to the nested object that you want to search. | +| `query` | Required | The query to run on the nested objects within the specified `path`. If a nested object matches the query, the root parent document is returned. You can search nested fields using dot notation, such as `nested_object.subfield`. Multi-level nesting is supported and automatically detected. Thus, an inner `nested` query within another nested query automatically matches the correct nesting level, instead of the root. | +| `ignore_unmapped` | Optional | Indicates whether to ignore unmapped `path` fields and not return documents instead of throwing an error. You can provide this parameter when querying multiple indexes, some of which may not contain the `path` field. Default is `false`. | +| `score_mode` | Optional | Defines how scores of matching inner documents influence the parent document's score. Valid values are: <br> - `avg`: Uses the average relevance score of all matching inner documents. <br> - `max`: Assigns the highest relevance score from the matching inner documents to the parent. <br> - `min`: Assigns the lowest relevance score from the matching inner documents to the parent. <br> - `sum`: Sums the relevance scores of all matching inner documents. <br> - `none`: Ignores the relevance scores of inner documents and assigns a score of `0` to the parent document. <br> Default is `avg`. | +| `inner_hits` | Optional | If provided, returns the underlying hits that matched the query. | + +## Next steps + +- Learn more about [retrieving inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). \ No newline at end of file diff --git a/_query-dsl/joining/parent-id.md b/_query-dsl/joining/parent-id.md new file mode 100644 index 00000000..2e20e620 --- /dev/null +++ b/_query-dsl/joining/parent-id.md @@ -0,0 +1,96 @@ +--- +layout: default +title: Parent ID +parent: Joining queries +nav_order: 40 +--- + +# Parent ID query + +The `parent_id` query returns child documents whose parent document has the specified ID. You can establish parent/child relationships between documents in the same index by using a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field type. + +## Example + +Before you can run a `parent_id` query, your index must contain a [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) field in order to establish parent/child relationships. This example uses the `testindex1` index, whose `product_to_brand` join field defines `brand` documents as parents and `product` documents as children: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "product_to_brand": { + "type": "join", + "relations": { + "brand": "product" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index the brand and product documents as described in the [`has_child` query example]({{site.url}}{{site.baseurl}}/query-dsl/joining/has-child/). + +To search for child documents of a specific parent document, use a `parent_id` query. The following query returns child documents (products) whose parent document has the ID `1`: + +```json +GET testindex1/_search +{ + "query": { + "parent_id": { + "type": "product", + "id": "1" + } + } +} +``` +{% include copy-curl.html %} + +The response returns the child product: + +```json +{ + "took": 57, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.87546873, + "hits": [ + { + "_index": "testindex1", + "_id": "3", + "_score": 0.87546873, + "_routing": "1", + "_source": { + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } + } + } + ] + } +} +``` + +## Parameters + +The following table lists all top-level parameters supported by `parent_id` queries. + +| Parameter | Required/Optional | Description | +|:---|:---|:---| +| `type` | Required | Specifies the name of the child relationship as defined in the `join` field mapping. | +| `id` | Required | The ID of the parent document. The query returns child documents associated with this parent document. | +| `ignore_unmapped` | Optional | Indicates whether to ignore unmapped `type` fields and not return documents instead of throwing an error. You can provide this parameter when querying multiple indexes, some of which may not contain the `type` field. Default is `false`. | \ No newline at end of file diff --git a/_query-dsl/match-all.md b/_query-dsl/match-all.md index 274111f0..5f0b31ad 100644 --- a/_query-dsl/match-all.md +++ b/_query-dsl/match-all.md @@ -1,7 +1,7 @@ --- layout: default title: Match all queries -nav_order: 65 +nav_order: 20 --- # Match all queries @@ -28,4 +28,14 @@ GET _search } } ``` -{% include copy-curl.html %} \ No newline at end of file +{% include copy-curl.html %} + + +## Parameters + +Both the `match_all` and `match_none` queries accept the following parameters. All parameters are optional. + +Parameter | Data type | Description +:--- | :--- | :--- +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. +`_name` | String | The name of the query for query tagging. Optional. diff --git a/_query-dsl/minimum-should-match.md b/_query-dsl/minimum-should-match.md index 9ec65431..673a27e2 100644 --- a/_query-dsl/minimum-should-match.md +++ b/_query-dsl/minimum-should-match.md @@ -1,7 +1,7 @@ --- layout: default title: Minimum should match -nav_order: 70 +nav_order: 80 redirect_from: - /query-dsl/query-dsl/minimum-should-match/ --- @@ -26,7 +26,7 @@ GET /shakespeare/_search } ``` -In this example, the query has three optional clauses that are combined with an `OR`, so the document must match either `prince`, `king`, or `star`. +In this example, the query has three optional clauses that are combined with an `OR`, so the document must match either `prince` and `king`, or `prince` and `star`, or `king` and `star`. ## Valid values @@ -448,4 +448,4 @@ The results contain only four documents that match at least one of the optional ] } } -``` \ No newline at end of file +``` diff --git a/_query-dsl/named-queries.md b/_query-dsl/named-queries.md new file mode 100644 index 00000000..74be20d6 --- /dev/null +++ b/_query-dsl/named-queries.md @@ -0,0 +1,104 @@ +--- +layout: default +title: Named queries +nav_order: 77 +--- + +# Named queries + +Any query clause can include a `_name` parameter that assigns a label to it. When a document matches, the response includes a `matched_queries` array listing the names of all query clauses that contributed to the match. This is useful for identifying the parts of a complex query that matched a given document. + +## Example + +The following query uses two named `match` clauses inside a `bool` query. Each clause has a `_name` that identifies it: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 2, + "_source": ["products.product_name", "customer_full_name"], + "query": { + "bool": { + "should": [ + {"match": {"products.product_name": {"query": "shirt", "_name": "shirt_query"}}}, + {"match": {"products.product_name": {"query": "dress", "_name": "dress_query"}}} + ] + } + } +} +``` +{% include copy-curl.html %} + +## Example response + +The `matched_queries` array in each hit shows which named clauses matched that document: + +```json +{ + "took": 16, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1746, + "relation": "eq" + }, + "max_score": 1.8150847, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "aoN5u50BpPQaFxRehbyq", + "_score": 1.8150847, + "_source": { + "customer_full_name": "Stephanie Reyes", + "products": [ + { + "product_name": "Shirt - black/white" + }, + { + "product_name": "Cocktail dress / Party dress - navy" + } + ] + }, + "matched_queries": [ + "shirt_query", + "dress_query" + ] + }, + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "fYN5u50BpPQaFxRehLqd", + "_score": 1.6545942, + "_source": { + "customer_full_name": "Clarice Daniels", + "products": [ + { + "product_name": "Summer dress - grey" + }, + { + "product_name": "Shirt - black/white" + } + ] + }, + "matched_queries": [ + "shirt_query", + "dress_query" + ] + } + ] + } +} +``` + +## Response body fields + +The following table lists the response fields specific to named queries. + +| Field | Description | +| :--- | :--- | +| `matched_queries` | An array of strings listing the `_name` values of all query clauses that matched this document. Only present when at least one named clause matches. | \ No newline at end of file diff --git a/_query-dsl/query-filter-context.md b/_query-dsl/query-filter-context.md index 6985822e..e294f8bf 100644 --- a/_query-dsl/query-filter-context.md +++ b/_query-dsl/query-filter-context.md @@ -3,7 +3,8 @@ layout: default title: Query and filter context nav_order: 5 redirect_from: -- /query-dsl/query-dsl/query-filter-context/ + - /opensearch/query-dsl/query-filter-context/ + - /query-dsl/query-dsl/query-filter-context/ --- # Query and filter context @@ -15,77 +16,356 @@ Queries consist of query clauses, which can be run in a [_filter context_](#filt A _relevance score_ measures how well a document matches a query. It is a positive floating-point number that OpenSearch records in the `_score` metadata field for each document: ```json -"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!" - } - }, -... +"hits": [ + { + "_index": "blog-posts", + "_id": "1", + "_score": 0.16890505, + "_source": { + "title": "Getting started with vector search", + "content": "Vector search finds documents with similar meaning by comparing embeddings.", + "status": "published", + "publish_date": "2025-03-10" + } + }, + ... +] ``` -A higher score indicates a more relevant document. While different query types calculate relevance scores differently, all query types take into account whether a query clause is run in a filter or query context. +A higher score indicates a more relevant document. While different query types calculate relevance scores differently, all query types take into account whether a query clause is run in a filter or query context. Use query clauses that you want to affect the relevance score in a query context, and use all other query clauses in a filter context. {: .tip} -## Filter context +## Sample data -A query clause in a filter context asks the question "_Does_ the document match the query clause?", which has a binary answer. For example, if you have an index with student data, you might use a filter context to answer the following questions about a student: - -- Is the student's `honors` status set to `true`? -- Is the student's `graduation_year` in the 2020--2022 range? - -With a filter context, OpenSearch returns matching documents without calculating a relevance score. Thus, you should use a filter context for fields with exact values. - -To run a query clause in a filter context, pass it to a `filter` parameter. For example, the following Boolean query searches for students who graduated with honors in 2020--2022: +The examples on this page use an index of blog posts. To try the examples, create the index: ```json -GET students/_search +PUT blog-posts { - "query": { - "bool": { - "filter": [ - { "term": { "honors": true }}, - { "range": { "graduation_year": { "gte": 2020, "lte": 2022 }}} + "mappings": { + "properties": { + "title": { "type": "text" }, + "content": { "type": "text" }, + "status": { "type": "keyword" }, + "publish_date": { "type": "date" } + } + } +} +``` +{% include copy-curl.html %} + +Add sample documents to the index: + +```json +POST blog-posts/_bulk?refresh=true +{ "index": { "_id": "1" } } +{ "title": "Getting started with vector search", "content": "Vector search finds documents with similar meaning by comparing embeddings.", "status": "published", "publish_date": "2025-03-10" } +{ "index": { "_id": "2" } } +{ "title": "Tuning vector search performance", "content": "Learn how to tune vector search using quantization and caching.", "status": "published", "publish_date": "2025-06-02" } +{ "index": { "_id": "3" } } +{ "title": "Keyword search basics", "content": "Keyword search matches the exact terms in your query.", "status": "published", "publish_date": "2025-01-20" } +{ "index": { "_id": "4" } } +{ "title": "Hybrid search explained", "content": "Hybrid search combines keyword search and vector search results.", "status": "draft", "publish_date": "2025-08-15" } +{ "index": { "_id": "5" } } +{ "title": "A year of vector search", "content": "A look back at the vector search features released in 2024.", "status": "published", "publish_date": "2024-11-05" } +``` +{% include copy-curl.html %} + +## Filter context + +A query clause in a filter context asks the question "_Does_ the document match the query clause?", which has a binary answer. For example, you might use a filter context to answer the following questions about a blog post: + +- Is the post's `status` set to `published`? +- Is the post's `publish_date` in 2025? + +With a filter context, OpenSearch returns matching documents without calculating a relevance score. Thus, you should use a filter context for fields with exact values. + +To run a query clause in a filter context, pass it to a `filter` parameter. For example, the following Boolean query searches for posts published in 2025: + +```json +GET blog-posts/_search +{ + "query": { + "bool": { + "filter": [ + { "term": { "status": "published" }}, + { "range": { "publish_date": { "gte": "2025-01-01", "lte": "2025-12-31" }}} ] } } } ``` +{% include copy-curl.html %} + +The response contains the three published posts from 2025. Every document has a `_score` of `0.0` because filter clauses do not calculate relevance: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.0, + "hits": [ + { + "_index": "blog-posts", + "_id": "1", + "_score": 0.0, + "_source": { + "title": "Getting started with vector search", + "content": "Vector search finds documents with similar meaning by comparing embeddings.", + "status": "published", + "publish_date": "2025-03-10" + } + }, + { + "_index": "blog-posts", + "_id": "2", + "_score": 0.0, + "_source": { + "title": "Tuning vector search performance", + "content": "Learn how to tune vector search using quantization and caching.", + "status": "published", + "publish_date": "2025-06-02" + } + }, + { + "_index": "blog-posts", + "_id": "3", + "_score": 0.0, + "_source": { + "title": "Keyword search basics", + "content": "Keyword search matches the exact terms in your query.", + "status": "published", + "publish_date": "2025-01-20" + } + } + ] + } +} +``` +</details> To improve performance, OpenSearch caches frequently used filters. ## Query context -A query clause in a query context asks the question "_How well_ does the document match the query clause?", which does not have a binary answer. A query context is suitable for a full-text search, where you not only want to receive matching documents but also to determine the relevance of each document. For example, if you have an index with the complete works of Shakespeare, you might use a query context for the following searches: +A query clause in a query context asks the question "_How well_ does the document match the query clause?", which does not have a binary answer. A query context is suitable for a full-text search, where you not only want to receive matching documents but also to determine the relevance of each document. For example, you might use a query context to find blog posts about vector search. -- Find documents that contain the word `dream`, including its various forms (`dreaming` or `dreams`) and synonyms (`contemplate`). -- Find documents that match the words `long live king`. +With a query context, every matching document contains a relevance score in the `_score` field, which you can use to [sort]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/) documents by relevance. -With a query context, every matching document contains a relevance score in the `_score` field, which you can use to [sort]({{site.url}}{{site.baseurl}}/opensearch/search/sort) documents by relevance. - -To run a query clause in a query context, pass it to a `query` parameter. For example, the following query searches for documents that match the words `long live king` in the `shakespeare` index: +To run a query clause in a query context, pass it to a `query` parameter. For example, the following query searches for posts whose content matches the words `vector search`: ```json -GET shakespeare/_search +GET blog-posts/_search { "query": { "match": { - "text_entry": "long live king" + "content": "vector search" } } } ``` +{% include copy-curl.html %} + +The response contains all five posts because each one contains at least one of the words. The posts are sorted by relevance score. Document 4 has the highest score because it contains `search` three times, and document 3 has the lowest score because it contains only `search`: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 0.1985399, + "hits": [ + { + "_index": "blog-posts", + "_id": "4", + "_score": 0.1985399, + "_source": { + "title": "Hybrid search explained", + "content": "Hybrid search combines keyword search and vector search results.", + "status": "draft", + "publish_date": "2025-08-15" + } + }, + { + "_index": "blog-posts", + "_id": "1", + "_score": 0.16890505, + "_source": { + "title": "Getting started with vector search", + "content": "Vector search finds documents with similar meaning by comparing embeddings.", + "status": "published", + "publish_date": "2025-03-10" + } + }, + { + "_index": "blog-posts", + "_id": "2", + "_score": 0.16890505, + "_source": { + "title": "Tuning vector search performance", + "content": "Learn how to tune vector search using quantization and caching.", + "status": "published", + "publish_date": "2025-06-02" + } + }, + { + "_index": "blog-posts", + "_id": "5", + "_score": 0.16219063, + "_source": { + "title": "A year of vector search", + "content": "A look back at the vector search features released in 2024.", + "status": "published", + "publish_date": "2024-11-05" + } + }, + { + "_index": "blog-posts", + "_id": "3", + "_score": 0.040917058, + "_source": { + "title": "Keyword search basics", + "content": "Keyword search matches the exact terms in your query.", + "status": "published", + "publish_date": "2025-01-20" + } + } + ] + } +} +``` +</details> Relevance scores are single-precision floating-point numbers with 24-bit significand precision. A loss of precision may occur if a score calculation exceeds the significand precision. -{: .note} \ No newline at end of file +{: .note} + +## Combining query and filter contexts + +A single Boolean query can contain clauses in both contexts. Clauses in the `must` and `should` parameters run in a query context and contribute to the `_score`. Clauses in the `filter` and `must_not` parameters run in a filter context and only include or exclude documents. For more information, see [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/). + +The following query combines the two preceding examples. The `match` clause in the `must` parameter calculates the relevance score, and the `term` and `range` clauses in the `filter` parameter limit the results to posts published in 2025: + +```json +GET blog-posts/_search +{ + "query": { + "bool": { + "must": [ + { "match": { "content": "vector search" }} + ], + "filter": [ + { "term": { "status": "published" }}, + { "range": { "publish_date": { "gte": "2025-01-01", "lte": "2025-12-31" }}} + ] + } + } +} +``` +{% include copy-curl.html %} + +The response contains the same three documents as the filter context example, sorted by relevance. Document 4 is excluded because it is a draft, and document 5 is excluded because it was published in 2024. Each document has the same `_score` as in the query context example because the filter clauses do not affect the score: + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.16890505, + "hits": [ + { + "_index": "blog-posts", + "_id": "1", + "_score": 0.16890505, + "_source": { + "title": "Getting started with vector search", + "content": "Vector search finds documents with similar meaning by comparing embeddings.", + "status": "published", + "publish_date": "2025-03-10" + } + }, + { + "_index": "blog-posts", + "_id": "2", + "_score": 0.16890505, + "_source": { + "title": "Tuning vector search performance", + "content": "Learn how to tune vector search using quantization and caching.", + "status": "published", + "publish_date": "2025-06-02" + } + }, + { + "_index": "blog-posts", + "_id": "3", + "_score": 0.040917058, + "_source": { + "title": "Keyword search basics", + "content": "Keyword search matches the exact terms in your query.", + "status": "published", + "publish_date": "2025-01-20" + } + } + ] + } +} +``` +</details> + +## Related documentation + +- [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/) +- [Constant score query]({{site.url}}{{site.baseurl}}/query-dsl/compound/constant-score/) +- [Term-level queries]({{site.url}}{{site.baseurl}}/query-dsl/term/index/) +- [Full-text queries]({{site.url}}{{site.baseurl}}/query-dsl/full-text/index/) +- [Sort results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/) diff --git a/_query-dsl/regex-syntax.md b/_query-dsl/regex-syntax.md new file mode 100644 index 00000000..271bd6a5 --- /dev/null +++ b/_query-dsl/regex-syntax.md @@ -0,0 +1,312 @@ +--- +layout: default +title: Regular expression syntax +nav_order: 95 +--- + +# Regular expression syntax + +A [regular expression](https://en.wikipedia.org/wiki/Regular_expression) (regex) is a way to define search patterns using special symbols and operators. These patterns let you match sequences of characters in strings. + +In OpenSearch, you can use regular expressions in the following query types: + +* [`regexp`]({{site.url}}{{site.baseurl}}/query-dsl/term/regexp/) +* [`query_string`]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) + +OpenSearch uses the [Apache Lucene](https://lucene.apache.org/core/) regex engine, which has its own syntax and limitations. It does **not** use [Perl Compatible Regular Expressions (PCRE)](https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions), so some familiar regex features might behave differently or be unsupported. +{: .note} + +## Choosing between regexp and query_string queries + +Both `regexp` and `query_string` queries support regular expressions, but they behave differently and serve different use cases. + +| Feature | `regexp` query | `query_string` query | +| ------------------------- | -------------------------------------------------- | --------------------------------------------------- | +| Pattern matching | Regex pattern must match the entire field value | Regex pattern can match any part of the field | +| `flags` support | `flags` enables optional regex operators | `flags` not supported | +| Query type | Term-level query (not scored) | Full-text query (scored and parsed) | +| Best use case | Strict pattern matching on keyword or exact fields | Search within analyzed fields using a flexible query string that supports regex patterns | +| Complex query composition | Limited to regex patterns | Supports `AND`, `OR`, wildcards, fields, boosts, and other features. See [Query string query]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/). | + + +## Reserved characters + +Lucene's regex engine supports all Unicode characters. However, the following characters are treated as special operators: + +``` +. ? + * | { } [ ] ( ) " \ +``` + +Depending on the enabled `flags` that specify [optional operators](#optional-operators), the following characters may also be reserved: + +``` +@ & ~ < > +``` + +To match these characters literally, either escape them with a backslash (`\`) or wrap the entire string in double quotation marks: + +- `\&`: Matches a literal `&` +- `\\`: Matches a literal backslash (`\`) +- `"hello@world"`: Matches the full string `hello@world` + + +## Standard regex operators + +Lucene supports a core set of regex operators: + +- `.` – Matches any single character. **Example**: `f.n` matches `f` followed by any character and then `n` (for example, `fan` or `fin`). + +- `?` – Matches zero or one of the preceding characters. **Example**: `colou?r` matches `color` and `colour`. + +- `+` – Matches one or more of the preceding characters. **Example**: `go+` matches `g` followed by one or more `o`s (`go`, `goo`, `gooo`, and so on). + +- `*` – Matches zero or more of the preceding characters. **Example**: `lo*se` matches `l` followed by zero or more `o`s and then `se` (`lse`, `lose`, `loose`, `loooose`, and so on). + +- `{min,max}` – Matches a specific range of repetitions. If `max` is omitted, there is no upper limit on the number of characters matched. **Example**: `x{3}` matches exactly 3 `x`s (`xxx`); `x{2,4}` matches from 2 to 4 `x`s (`xx`, `xxx`, or `xxxx`); `x{3,}` matches 3 or more `x`s (`xxx`, `xxxx`, `xxxxx`, and so on). + +- `|` – Acts as a logical `OR`. **Example**: `apple|orange` matches `apple` or `orange`. + +- `( )` – Groups characters into a subpattern. **Example**: `ab(cd)?` matches `ab` and `abcd`. + +- `[ ]` – Matches one character from a set or range. **Example**: `[aeiou]` matches any vowel. + - `-` – When provided within the brackets, indicates a range unless escaped or is the first character within the brackets. **Example**: `[a-z]` matches any lowercase letter; `[-az]` matches `-`, `a`, or `z`; `[a\\-z]` matches `a`, `-`, or `z`. + - `^` – When provided within the brackets, acts a logical `NOT`, negating a range of characters or any character in the set. **Example**: `[^az]` matches any character except `a` or `z`; `[^a-z]` matches any character except lowercase letters; `[^-az]` matches any character except `-`, `a`, and `z`; `[^a\\-z]` matches any character except `a`, `-`, and `z`. + + +## Optional operators + +You can enable additional regex operators using the `flags` parameter. Separate multiple flags with `|`. + +The following are the available flags: + +- `ALL` (default) – Enables all optional operators. + +{% comment %} +<!-- COMPLEMENT is deprecated and doesn't work. Leaving it here until https://github.com/opensearch-project/OpenSearch/issues/18397 is resolved. --> +{% endcomment %} + +- `COMPLEMENT` – Enables `~`, which negates the shortest following expression. **Example**: `d~ef` matches `dgf`, `dxf`, but not `def`. + +- `INTERSECTION` – Enables `&` as an `AND` logical operator. **Example**: `ab.+&.+cd` matches strings containing `ab` at the beginning and `cd` at the end. + +- `INTERVAL` – Enables `<min-max>` syntax to match numeric ranges. **Example**: `id<10-12>` matches `id10`, `id11`, and `id12`. + +- `ANYSTRING` – Enables `@` to match any string. You can combine this with `~` and `&` for exclusions. **Example**: `@&.*error.*&.*[0-9]{3}.*` matches strings containing both the word "error" and a sequence of three digits. + +## Unsupported features + +Lucene's engine does not support the following commonly used regex anchors: + +- `^` – Start of line +- `$` – End of line + +Instead, your pattern must match the entire string to produce a match. + +## Example + +To try regular expressions, index the following documents into the `logs` index: + +```json +PUT /logs/_doc/1 +{ + "message": "error404" +} +``` +{% include copy-curl.html %} + +```json +PUT /logs/_doc/2 +{ + "message": "error500" +} +``` +{% include copy-curl.html %} + +```json +PUT /logs/_doc/3 +{ + "message": "error1a" +} +``` +{% include copy-curl.html %} + +### Example: Basic query containing regular expressions + +The following `regexp` query returns documents in which the entire value of the `message` field matches the pattern "error" followed by one or more digits. A value does not match if it only contains the pattern as a substring: + +```json +GET /logs/_search +{ + "query": { + "regexp": { + "message": { + "value": "error[0-9]+" + } + } + } +} +``` +{% include copy-curl.html %} + +This query matches `error404` and `error500`: + + +```json +{ + "took": 28, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1, + "_source": { + "message": "error404" + } + }, + { + "_index": "logs", + "_id": "2", + "_score": 1, + "_source": { + "message": "error500" + } + } + ] + } +} +``` + +### Example: Using optional operators + +The following query matches documents in which the `message` field exactly matches a string that starts with "error" followed by a number from 400 to 500, inclusive. The `INTERVAL` flag enables the use of `<min-max>` syntax for numeric ranges: + +```json +GET /logs/_search +{ + "query": { + "regexp": { + "message": { + "value": "error<400-500>", + "flags": "INTERVAL" + } + } + } +} +``` +{% include copy-curl.html %} + +This query matches `error404` and `error500`: + +```json +{ + "took": 22, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1, + "_source": { + "message": "error404" + } + }, + { + "_index": "logs", + "_id": "2", + "_score": 1, + "_source": { + "message": "error500" + } + } + ] + } +} +``` + +### Example: Using ANYSTRING + +When the `ANYSTRING` flag is enabled, the `@` operator matches an entire string. This is useful when combined with intersection (`&`) because it allows you to construct queries that match full strings under specific conditions. + +The following query matches messages that contain both the word "error" and a sequence of three digits. Use `ANYSTRING` to assert that the entire field must match the intersection of both patterns: + +```json +GET /logs/_search +{ + "query": { + "regexp": { + "message.keyword": { + "value": "@&.*error.*&.*[0-9]{3}.*", + "flags": "ANYSTRING|INTERSECTION" + } + } + } +} +``` +{% include copy-curl.html %} + +This query matches `error404` and `error500`: + +```json +{ + "took": 20, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1, + "_source": { + "message": "error404" + } + }, + { + "_index": "logs", + "_id": "2", + "_score": 1, + "_source": { + "message": "error500" + } + } + ] + } +} +``` + +Note that this query will also match `xerror500`, `error500x`, and `errorxx500`. \ No newline at end of file diff --git a/_query-dsl/rescore.md b/_query-dsl/rescore.md new file mode 100644 index 00000000..1c3d67aa --- /dev/null +++ b/_query-dsl/rescore.md @@ -0,0 +1,141 @@ +--- +layout: default +title: Rescore +nav_order: 90 +--- + +# Rescore parameter + +The `rescore` parameter improves search precision by reordering only the highest-ranked documents returned from your initial query. Rather than applying an expensive algorithm to all documents in the index, rescoring focuses computational resources on reranking a smaller window of top results using a secondary scoring method. + +When you include a `rescore` parameter in your search request, OpenSearch processes the results in the following sequence: + +1. **Initial search**: The primary query and any post-filters execute across all relevant documents. +2. **Shard-level rescoring**: Each shard applies the rescoring algorithm to its top results. +3. **Final coordination**: The coordinating node combines rescored results from all shards. + +This approach provides better relevance while maintaining acceptable performance. + +When using the `rescore` parameter, note the following important considerations: + +- You cannot use explicit sorting (other than `_score` in descending order) with rescoring. OpenSearch returns an error if you attempt to combine custom sorting with a rescore query. + +- When implementing pagination, maintain the same `window_size` across all pages. Changing the window size between pages can cause result inconsistencies as users navigate through search results. + +- When using rescoring with [hybrid queries]({{site.url}}{{site.baseurl}}/query-dsl/compound/hybrid/#rescoring-hybrid-queries) that run through a search pipeline, the rescore query is applied independently to each subquery's results at the shard level, before normalization and combination. When the hybrid query runs in [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/#rescoring), the rescore query is applied to the combined ranking, after normalization and combination. + +## Query rescoring + +Query rescoring applies a secondary query to refine the scores of top-ranked documents. You can control how many documents each shard examines using the `window_size` parameter (default is `10`). + +### Basic rescoring syntax + +```json +POST /_search +{ + "query": { + "match": { + "content": { + "query": "OpenSearch query optimization", + "operator": "or" + } + } + }, + "rescore": { + "window_size": 100, + "query": { + "rescore_query": { + "match_phrase": { + "content": { + "query": "OpenSearch query optimization", + "slop": 1 + } + } + }, + "query_weight": 0.8, + "rescore_query_weight": 1.3 + } + } +} +``` +{% include copy-curl.html %} + +### Rescore parameters + +The `rescore` object supports the following parameters. + +Parameter | Type | Description +--- | --- | --- +`window_size` | Integer | Number of top documents to rescore per shard. Default is `10`. +`query_weight` | Float | Weight applied to the original query score. Default is `1.0`. +`rescore_query_weight` | Float | Weight applied to the rescore query score. Default is `1.0`. +`score_mode` | String | Method for combining original and rescore query scores. Default is `total`. See [Score combination modes](#score-combination-modes). + +### Score combination modes + +The `score_mode` parameter determines how OpenSearch combines the original score with the rescore query score. This parameter accepts the following values. + +Mode | Description | Use case +--- | --- | --- +`total` | Adds original score + rescore score | General relevance improvement (default) +`multiply` | Multiplies original score × rescore score | Effective with function queries that return values between 0 and 1 +`avg` | Averages the two scores | Balanced approach when both scores are equally important +`max` | Uses the higher of the two scores | Ensures documents with high scores in either query rank well +`min` | Uses the lower of the two scores | Conservative approach that requires both queries to agree + +## Multiple rescoring stages + +You can chain multiple rescoring operations to apply increasingly sophisticated ranking algorithms: + +```json +POST /_search +{ + "query": { + "match": { + "title": { + "query": "search engine technology", + "operator": "or" + } + } + }, + "rescore": [ + { + "window_size": 200, + "query": { + "rescore_query": { + "match_phrase": { + "title": { + "query": "search engine technology", + "slop": 2 + } + } + }, + "query_weight": 0.6, + "rescore_query_weight": 1.4 + } + }, + { + "window_size": 50, + "query": { + "score_mode": "multiply", + "rescore_query": { + "function_score": { + "script_score": { + "script": { + "source": "Math.log10(doc['popularity'].value + 2)" + } + } + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +In this multi-stage example: +1. The **first rescoring stage** examines 200 documents per shard, applying phrase matching to improve relevance. +2. The **second rescoring stage** takes the top 50 results from the first stage and applies popularity-based scoring using a logarithmic function. + +Each stage processes the results from the previous stage, creating a refinement pipeline where computationally expensive operations only operate on the most promising candidates. diff --git a/_query-dsl/rewrite-parameter.md b/_query-dsl/rewrite-parameter.md new file mode 100644 index 00000000..2fbb19df --- /dev/null +++ b/_query-dsl/rewrite-parameter.md @@ -0,0 +1,253 @@ +--- +layout: default +title: Rewrite +nav_order: 85 +--- + +# Rewrite parameter + +Multi-term queries like `wildcard`, `prefix`, `regexp`, `fuzzy`, and `range` expand internally into sets of terms. The `rewrite` parameter allows you to control how these term expansions are executed and scored. + +When a multi-term query expands into many terms (for example, `prefix: "error*"` matching hundreds of terms), they are internally converted into `term` queries. This process can have the following drawbacks: + +* Exceed the `indices.query.bool.max_clause_count` limit (default is `1024`). +* Affect how scores are calculated for matching documents. +* Impact memory and latency depending on the rewrite method used. + +The `rewrite` parameter gives you control over how multi-term queries behave internally. + +| Mode | Scores | Performance | Notes | +| --------------------------- | -------------------------------------- | ----------- | --------------------------------------------- | +| `constant_score` | Same score for all matches | Best | Default mode, ideal for filters | +| `scoring_boolean` | TF/IDF-based | Moderate | Full relevance scoring | +| `constant_score_boolean` | Same score but with Boolean structure | Moderate | Use with `must_not` or `minimum_should_match` | +| `top_terms_N` | TF/IDF on top N terms | Efficient | Truncates expansion | +| `top_terms_boost_N` | Static boosts | Fast | Less accurate | +| `top_terms_blended_freqs_N` | Blended score | Balanced | Best scoring/efficiency trade-off | + + +## Available rewrite methods + +The following table summarizes the available rewrite methods. + +| Rewrite method | Description | +| [`constant_score`](#constant-score) | (Default) All expanded terms are evaluated together as a single unit, assigning the same score to every match. Matching documents are not scored individually, making it very efficient for filtering use cases. | +| [`scoring_boolean`](#scoring-boolean) | Breaks the query into a Boolean `should` clause with one term query per match. Each result is scored individually based on relevance. | +| [`constant_score_boolean`](#constant-score-boolean) | Similar to `scoring_boolean`, but all documents receive a fixed score regardless of term frequency. Maintains Boolean structure without TF/IDF weighting. | +| [`top_terms_N`](#top-terms-n) | Restricts scoring and execution to the N most frequent terms. Reduces resource usage and prevents clause overload. | +| [`top_terms_boost_N`](#top-terms-boost-n) | Like `top_terms_N` but uses static boosting instead of full scoring. Offers performance improvements with simplified relevance. | +| [`top_terms_blended_freqs_N`](#top-terms-blended-frequencies-n) | Chooses the top N matching terms and averages their document frequencies for scoring. Produces balanced scores without full term explosion. | + +## Boolean-based rewrite limits + +All Boolean-based rewrites, such as `scoring_boolean`, `constant_score_boolean`, and `top_terms_*`, are subject to the following dynamic [cluster settings for indexes]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings-for-indexes/#dynamic-settings): + +```json +indices.query.bool.max_clause_count +``` + +This setting controls the maximum number of allowed Boolean `should` clauses (default is `1024`). If your query expands to a number of clauses greater than this limit, it is rejected with a `too_many_clauses` error returned as a HTTP 400 Bad Request response. Similarly, if your query _and all its children cumulatively_ expands to a total number of clauses greater than this limit, it is rejected with a `too_many_nested_clauses` error returned as a HTTP 400 Bad Request response. + +For example, a wildcard, such as "error*", might expand to hundreds or thousands of matching terms, which could include "error", "errors", "error_log", "error404", and others. Each of these terms turns into a separate `term` query. If the number of terms exceeds the `indices.query.bool.max_clause_count` limit, the query fails: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "error*", + "rewrite": "scoring_boolean" + } + } + } +} +``` +{% include copy-curl.html %} + +The query is expanded internally as follows: + +```json +{ + "bool": { + "should": [ + { "term": { "message": "error" } }, + { "term": { "message": "errors" } }, + { "term": { "message": "error_log" } }, + { "term": { "message": "error404" } }, + ... + ] + } +} +``` + +## Constant score + +The default `constant_score` rewrite method wraps all expanded terms into a single query and skips the scoring phase entirely. This approach has the following characteristics: + +* Executes all term matches as a single [bit array](https://en.wikipedia.org/wiki/Bit_array) query. +* Ignores scoring altogether; every document gets a `_score` of `1.0`. +* Fastest option; ideal for filtering. + +The following example runs a `wildcard` query using the default `constant_score` rewrite method to efficiently filter documents matching the pattern `warning*` in the `message` field: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*" + } + } + } +} +``` +{% include copy-curl.html %} + +## Scoring Boolean + +The `scoring_boolean` rewrite method breaks the expanded terms into separate `term` queries combined under a Boolean `should` clause. This approach works as follows: + +* Expands the wildcard into individual `term` queries inside a Boolean `should` clause. +* Each document's score reflects how many terms it matches and the terms' frequency. + +The following example uses a `scoring_boolean` rewrite configuration: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "scoring_boolean" + } + } + } +} +``` +{% include copy-curl.html %} + +## Constant score Boolean + +The `constant_score_boolean` rewrite method uses the same Boolean structure as `scoring_boolean` but disables scoring, making it useful when clause logic is needed without relevance ranking. This method has the following characteristics: + +* Similar structure to `scoring_boolean`, but documents are not ranked. +* All matching documents receive the same score. +* Retains Boolean clause flexibility, such as using `must_not`, without ranking. + +The following example query uses a `must_not` Boolean clause: + +```json +POST /logs/_search +{ + "query": { + "bool": { + "must_not": { + "wildcard": { + "message": { + "value": "error*", + "rewrite": "constant_score_boolean" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +This query is internally expanded as follows: + +```json +{ + "bool": { + "must_not": { + "bool": { + "should": [ + { "term": { "message": "error" } }, + { "term": { "message": "errors" } }, + { "term": { "message": "error_log" } }, + ... + ] + } + } + } +} +``` + +## Top terms N + +The `top_terms_N` method is one of several rewrite options designed to balance scoring accuracy and performance when expanding multi-term queries. It works as follows: + +* Only the N most frequently matching terms are selected and scored. +* Useful when you expect a large term expansion and want to limit the load. +* Other valid terms are ignored to preserve performance. + +The following query uses the `top_terms_2` rewrite method to score only the two most frequent terms that match the `warning*` pattern in the `message` field: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "top_terms_2" + } + } + } +} +``` +{% include copy-curl.html %} + +## Top terms boost N + +The `top_terms_boost_N` rewrite method selects the top N matching terms and applies static `boost` values instead of computing full relevance scores. It works as follows: + +* Limits expansion to the top N terms like `top_terms_N`. +* Rather than computing TF/IDF, it assigns a preset boost to each term. +* Provides faster execution with predictable relevance weights. + +The following example uses a `top_terms_boost_2` rewrite parameter: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "top_terms_boost_2" + } + } + } +} +``` +{% include copy-curl.html %} + +## Top terms blended frequencies N + +The `top_terms_blended_freqs_N` rewrite method selects the top N matching terms and blends their document frequencies to produce more balanced relevance scores. This approach has the following characteristics: + +* Picks the top N matching terms and applies a blended frequency to all. +* Blending makes scoring smoother across terms that differ in frequency. +* Good trade-off when you want performance with realistic scoring. + +The following example uses a `top_terms_blended_freqs_2` rewrite parameter: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "top_terms_blended_freqs_2" + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_query-dsl/span/index.md b/_query-dsl/span/index.md new file mode 100644 index 00000000..aa69aee4 --- /dev/null +++ b/_query-dsl/span/index.md @@ -0,0 +1,96 @@ +--- +layout: default +title: Span queries +has_children: true +has_toc: false +nav_order: 75 +redirect_from: + - /opensearch/query-dsl/span-query/ + - /query-dsl/query-dsl/span-query/ + - /query-dsl/span-query/ + - /query-dsl/span/ +--- + +# Span queries + +You can use span queries to perform precise positional searches. Span queries are low-level, specific queries that provide control over the order and proximity of specified query terms. They are primarily used to search legal documents and patents. + +Span queries include the following query types: + +| Query type | Description | +| :--- | :--- | +| [Span containing]({{site.url}}{{site.baseurl}}/query-dsl/span/span-containing/) | Returns larger spans that contain smaller spans within them. The opposite of the `span_within` query. | +| [Span field masking]({{site.url}}{{site.baseurl}}/query-dsl/span/span-field-masking/) | Allows span queries to work across different fields by making one field appear as another. Useful when the same text is indexed using different analyzers. | +| [Span first]({{site.url}}{{site.baseurl}}/query-dsl/span/span-first/) | Matches terms or phrases that appear within a specified number of positions from the start of a field. | +| [Span multi-term]({{site.url}}{{site.baseurl}}/query-dsl/span/span-multi-term/) | Enables multi-term queries (like `prefix`, `wildcard`, or `fuzzy`) to work within span queries. | +| [Span near]({{site.url}}{{site.baseurl}}/query-dsl/span/span-near/) | Finds terms or phrases that appear within a specified distance of each other. Supports requiring matches to appear in a specific order. | +| [Span not]({{site.url}}{{site.baseurl}}/query-dsl/span/span-not/) | Excludes matches that overlap with another span query. | +| [Span or]({{site.url}}{{site.baseurl}}/query-dsl/span/span-or/) | Matches documents that satisfy any of the provided span queries. | +| [Span term]({{site.url}}{{site.baseurl}}/query-dsl/span/span-term/) | Matches a single term while maintaining position information for use in other span queries. | +| [Span within]({{site.url}}{{site.baseurl}}/query-dsl/span/span-within/) | Returns smaller spans that are enclosed by larger spans. The opposite of the `span_containing` query. | + +## Setup + +To try the examples in this section, use the following steps to configure an example index. + +### Step 1: Create an index + +First, create an index for an e-commerce clothing website. The `description` field uses the default `standard` analyzer, while the `description.stemmed` subfield applies the `english` analyzer to enable stemming: + +```json +PUT /clothing +{ + "mappings": { + "properties": { + "description": { + "type": "text", + "analyzer": "standard", + "fields": { + "stemmed": { + "type": "text", + "analyzer": "english" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Step 2: Index data + +Index sample documents into the index: + +```json +POST /clothing/_doc/1 +{ + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " +} + +``` +{% include copy-curl.html %} + +```json +POST /clothing/_doc/2 +{ + "description": "Beautiful long dress in red silk, perfect for formal events." +} +``` +{% include copy-curl.html %} + +```json +POST /clothing/_doc/3 +{ + "description": "Short-sleeved shirt with a button-down collar, can be dressed up or down." +} +``` +{% include copy-curl.html %} + +```json +POST /clothing/_doc/4 +{ + "description": "A set of two midi silk shirt dresses with long sleeves in black. " +} +``` +{% include copy-curl.html %} diff --git a/_query-dsl/span/span-containing.md b/_query-dsl/span/span-containing.md new file mode 100644 index 00000000..432e69a7 --- /dev/null +++ b/_query-dsl/span/span-containing.md @@ -0,0 +1,112 @@ +--- +layout: default +title: Span containing +parent: Span queries +grand_parent: Query DSL +nav_order: 10 +--- + +# Span containing query + +The `span_containing` query finds matches where a larger text pattern (like a phrase or a set of words) contains a smaller text pattern within its boundaries. Think of it as finding a word or phrase but only when it appears within a specific larger context. + +For example, you can use the `span_containing` query to perform the following searches: + +- Find the word "quick" but only when it appears in sentences that mention both foxes and behavior. +- Ensure that certain terms appear within the context of other terms---not anywhere in the document. +- Search for specific words that appear within larger meaningful phrases. + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for occurrences of the word "red" that appear within a larger span containing the words "silk" and "dress" (not necessarily in that order) within 5 words of each other: + +```json +GET /clothing/_search +{ + "query": { + "span_containing": { + "little": { + "span_term": { + "description": "red" + } + }, + "big": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "silk" + } + }, + { + "span_term": { + "description": "dress" + } + } + ], + "slop": 5, + "in_order": false + } + } + } + } +} +``` +{% include copy-curl.html %} + +The query matches document 1 because: + +- It finds a span in which "silk" and "dress" appear within at most 5 words of each other ("...dress in red silk..."). The terms "silk" and "dress" are within 2 words of each other (there are 2 words between them). +- Within this larger span, it finds the term "red". + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.1577396, + "hits": [ + { + "_index": "clothing", + "_id": "2", + "_score": 1.1577396, + "_source": { + "description": "Beautiful long dress in red silk, perfect for formal events." + } + } + ] + } +} +``` + +</details> + +Both `little` and `big` parameters can contain any type of span query, allowing for complex nested span queries when needed. + +## Parameters + +The following table lists all top-level parameters supported by `span_containing` queries. All parameters are required. + +| Parameter | Data type | Description | +|:-----------|:------|:-------------| +| `little` | Object | The span query that must be contained within the `big` span. This defines the span you're searching for within a larger context. | +| `big` | Object | The containing span query that defines the boundaries within which the `little` span must appear. This establishes the context for your search. | \ No newline at end of file diff --git a/_query-dsl/span/span-field-masking.md b/_query-dsl/span/span-field-masking.md new file mode 100644 index 00000000..78105b50 --- /dev/null +++ b/_query-dsl/span/span-field-masking.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Span field masking +parent: Span queries +grand_parent: Query DSL +nav_order: 20 +--- + +# Span field masking query + +The `field_masking_span` query allows span queries to match across different fields by "masking" the true field of a query. This is particularly useful when working with multi-fields (the same content indexed with different analyzers) or when you need to run span queries like `span_near` or `span_or` across different fields (which is normally not allowed). + +For example, you can use the `field_masking_span` query to: +- Match terms across a raw field and its stemmed version. +- Combine span queries on different fields in a single span operation. +- Work with the same content indexed using different analyzers. + +When using field masking, the relevance score is calculated using the characteristics (norms) of the masked field rather than the actual field being searched. This means that if the masked field has different properties (like length or boost values) than the field being searched, you might receive unexpected scoring results. +{: .note} + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for the word "long" near variations of the word "sleeve" in the stemmed field: + +```json +GET /clothing/_search +{ + "query": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "long" + } + }, + { + "field_masking_span": { + "query": { + "span_term": { + "description.stemmed": "sleev" + } + }, + "field": "description" + } + } + ], + "slop": 1, + "in_order": true + } + } +} + +``` +{% include copy-curl.html %} + +The query matches documents 1 and 4: +- The term "long" appears in the `description` field in both documents. +- Document 1 contains the word "sleeved", and document 4 contains the word "sleeves". +- The `field_masking_span` makes the stemmed field match appear as if it were in the raw field. +- The terms appear within 1 position of each other in the specified order ("long" must appear before "sleeve"). + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.7444251, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 0.7444251, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "4", + "_score": 0.4291246, + "_source": { + "description": "A set of two midi silk shirt dresses with long fluttered sleeves in black. " + } + } + ] + } +} +``` + +## Parameters + +The following table lists all top-level parameters supported by `field_masking_span` queries. All parameters are required. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `query` | Object | The span query to execute on the actual field. | +| `field` | String | The field name used to mask the query. Other span queries will treat this query as if it were executing on this field. | diff --git a/_query-dsl/span/span-first.md b/_query-dsl/span/span-first.md new file mode 100644 index 00000000..7192157d --- /dev/null +++ b/_query-dsl/span/span-first.md @@ -0,0 +1,102 @@ +--- +layout: default +title: Span first +parent: Span queries +grand_parent: Query DSL +nav_order: 30 +--- + +# Span first query + +The `span_first` query matches spans that begin at the start of a field and end within a specified number of positions. This query is useful when you want to find terms or phrases that appear near the beginning of a document. + +For example, you can use the `span_first` query to perform the following searches: + +- Find documents in which specific terms appear in the first few words of a field. +- Ensure certain phrases occur at or near the beginning of a text +- Match patterns only when they appear within a specified distance from the start + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for the stemmed word "dress" appearing within the first 4 positions of the description: + +```json +GET /clothing/_search +{ + "query": { + "span_first": { + "match": { + "span_term": { + "description.stemmed": "dress" + } + }, + "end": 4 + } + } +} +``` +{% include copy-curl.html %} + +The query matches documents 1 and 2: +- Documents 1 and 2 contain the word `dress` at the third position ("Long-sleeved dress..." and "Beautiful long dress"). Indexing of the words starts with 0, so the word "dress" is at position 2. +- The position of the word `dress` must be less than `4`, as specified by the `end` parameter. + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.110377684, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 0.110377684, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "2", + "_score": 0.110377684, + "_source": { + "description": "Beautiful long dress in red silk, perfect for formal events." + } + } + ] + } +} +``` + +</details> + +The `match` parameter can contain any type of span query, allowing for more complex patterns to be matched at the beginning of fields. + +## Parameters + +The following table lists all top-level parameters supported by `span_first` queries. All parameters are required. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `match` | Object | The span query to match. This defines the pattern you're searching for at the start of the field. | +| `end` | Integer | The maximum end position (exclusive) allowed for the span query match. For example, `end: 4` matches terms at positions 0--3. | diff --git a/_query-dsl/span/span-multi-term.md b/_query-dsl/span/span-multi-term.md new file mode 100644 index 00000000..aff0057f --- /dev/null +++ b/_query-dsl/span/span-multi-term.md @@ -0,0 +1,134 @@ +--- +layout: default +title: Span multi-term +parent: Span queries +grand_parent: Query DSL +nav_order: 40 +--- + +# Span multi-term query + +The `span_multi` query allows you to wrap a multi-term query (like `wildcard`, `fuzzy`, `prefix`, `range`, or `regexp`) as a span query. This enables you to use these more flexible matching queries within other span queries. + +For example, you can use the `span_multi` query to: +- Find words with common prefixes near other terms. +- Match fuzzy variations of words within spans. +- Use regular expressions in span queries. + +>`span_multi` queries can potentially match many terms. To avoid excessive memory usage, you can: +>- Set the `rewrite` parameter for the multi-term query. +>- Use the `top_terms_*` rewrite method. +>- Consider enabling the `index_prefixes` option for the text field if you use `span_multi` only for a `prefix` query. This automatically rewrites any `prefix` query on the field into a single-term query that matches the indexed prefix. +{: .note} + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/index/#setup). +{: .tip} + +The `span_multi` query uses the following syntax to wrap the `prefix` query: + +```json +"span_multi": { + "match": { + "prefix": { + "description": { + "value": "flutter" + } + } + } +} +``` + +The following query searches for words starting with "dress" near any form of "sleeve" within at most 5 words of each other: + +```json +GET /clothing/_search +{ + "query": { + "span_near": { + "clauses": [ + { + "span_multi": { + "match": { + "prefix": { + "description": { + "value": "dress" + } + } + } + } + }, + { + "field_masking_span": { + "query": { + "span_term": { + "description.stemmed": "sleev" + } + }, + "field": "description" + } + } + ], + "slop": 5, + "in_order": false + } + } +} +``` +{% include copy-curl.html %} + +The query matches documents 1 ("Long-sleeved dress...") and 4 ("...dresses with long fluttered sleeves...") because "dress" and "long" occur within the maximum distance in both documents. + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.7590723, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 1.7590723, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "4", + "_score": 0.84792376, + "_source": { + "description": "A set of two midi silk shirt dresses with long fluttered sleeves in black. " + } + } + ] + } +} +``` +</details> + +## Parameters + +The following table lists all top-level parameters supported by `span_multi` queries. All parameters are required. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `match` | Object | The multi-term query to wrap (can be `prefix`, `wildcard`, `fuzzy`, `range`, or `regexp`). | diff --git a/_query-dsl/span/span-near.md b/_query-dsl/span/span-near.md new file mode 100644 index 00000000..6a103cda --- /dev/null +++ b/_query-dsl/span/span-near.md @@ -0,0 +1,104 @@ +--- +layout: default +title: Span near +parent: Span queries +grand_parent: Query DSL +nav_order: 50 +--- + +# Span near query + +The `span_near` query matches spans that are near one another. You can specify how far apart the spans can be and whether they need to appear in a specific order. + +For example, you can use the `span_near` query to: +- Find terms that appear within a certain distance of each other. +- Match phrases in which words appear in a specific order. +- Find related concepts that appear close to each other in text. + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for any forms of "sleeve" and "long" appearing next to each other, in any order: + +```json +GET /clothing/_search +{ + "query": { + "span_near": { + "clauses": [ + { + "span_term": { + "description.stemmed": "sleev" + } + }, + { + "span_term": { + "description.stemmed": "long" + } + } + ], + "slop": 1, + "in_order": false + } + } +} +``` +{% include copy-curl.html %} + +The query matches documents 1 ("Long-sleeved...") and 2 ("...long fluttered sleeves..."). In document 1, the words are next to each other, while in document 2, they are within the specified slop distance of `1` (there is 1 word between them). + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.36496973, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 0.36496973, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "4", + "_score": 0.25312424, + "_source": { + "description": "A set of two midi silk shirt dresses with long fluttered sleeves in black. " + } + } + ] + } +} +``` + +## Parameters + +The following table lists all top-level parameters supported by `span_near` queries. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `clauses` | An array of span queries that define the terms or phrases to match. All specified terms must appear within the defined slop distance. Required. | +| `slop` | Integer | The maximum number of intervening unmatched positions between spans. Required. | +| `in_order` | Boolean | Whether spans need to appear in the same order as in the `clauses` array. Optional. Default is `false`. | diff --git a/_query-dsl/span/span-not.md b/_query-dsl/span/span-not.md new file mode 100644 index 00000000..6b5b5d64 --- /dev/null +++ b/_query-dsl/span/span-not.md @@ -0,0 +1,82 @@ +--- +layout: default +title: Span not +parent: Span queries +grand_parent: Query DSL +nav_order: 60 +--- + +# Span not query + +The `span_not` query excludes spans that overlap with another span query. You can also specify the distance before or after the excluded spans within which matches cannot occur. + +For example, you can use the `span_not` query to: +- Find terms except when they appear in certain phrases. +- Match spans unless they are near specific terms. +- Exclude matches that occur within a certain distance of other patterns. + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for the word "dress" but not when it appears in the phrase "dress shirt": + +```json +GET /clothing/_search +{ + "query": { + "span_not": { + "include": { + "span_term": { + "description": "dress" + } + }, + "exclude": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "dress" + } + }, + { + "span_term": { + "description": "shirt" + } + } + ], + "slop": 0, + "in_order": true + } + } + } + } +} +``` +{% include copy-curl.html %} + +The query matches document 2 because it contains the word "dress" ("Beautiful long dress..."). Document 1 is not matched because it contains the phrase "dress shirt", which is excluded. Documents 3 and 4 are not matched because they contain variations of the word "dress" ("dressed" and "dresses"), and the query is searching the raw field. + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json + +``` +</details> + +## Parameters + +The following table lists all top-level parameters supported by `span_not` queries. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `include` | Object | The span query whose matches you want to find. Required. | +| `exclude` | Object | The span query whose matches should be excluded. Required. | +| `pre` | Integer | Specifies that the `exclude` span cannot appear within the given number of token positions before the `include` span. Optional. Default is `0`. | +| `post` | Integer | Specifies that the `exclude` span cannot appear within the given number of token positions after the `include` span. Optional. Default is `0`. | +| `dist` | Integer | Equivalent to setting both `pre` and `post` to the same value. Optional. | diff --git a/_query-dsl/span/span-or.md b/_query-dsl/span/span-or.md new file mode 100644 index 00000000..706623a5 --- /dev/null +++ b/_query-dsl/span/span-or.md @@ -0,0 +1,127 @@ +--- +layout: default +title: Span or +parent: Span queries +grand_parent: Query DSL +nav_order: 70 +--- + +# Span or query + +The `span_or` query combines multiple span queries and matches the union of their spans. A match occurs if at least one of the contained span queries matches. + +For example, you can use the `span_or` query to: +- Find spans matching any of several patterns. +- Combine different span patterns as alternatives. +- Match multiple span variations in a single query. + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for either "formal collar" or "button collar" appearing within 2 words of each other: + +```json +GET /clothing/_search +{ + "query": { + "span_or": { + "clauses": [ + { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "formal" + } + }, + { + "span_term": { + "description": "collar" + } + } + ], + "slop": 0, + "in_order": true + } + }, + { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "button" + } + }, + { + "span_term": { + "description": "collar" + } + } + ], + "slop": 2, + "in_order": true + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +The query matches documents 1 ("...formal collar...") and 3 ("...button-down collar...") within the specified slop distance. + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 2.170027, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 2.170027, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "3", + "_score": 1.2509141, + "_source": { + "description": "Short-sleeved shirt with a button-down collar, can be dressed up or down." + } + } + ] + } +} +``` +</details> + +## Parameters + +The following table lists all top-level parameters supported by `span_or` queries. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `clauses` | Array | The array of span queries to match. The query matches if any of these span queries match. Must contain at least one span query. Required. | diff --git a/_query-dsl/span/span-term.md b/_query-dsl/span/span-term.md new file mode 100644 index 00000000..95f1fd31 --- /dev/null +++ b/_query-dsl/span/span-term.md @@ -0,0 +1,123 @@ +--- +layout: default +title: Span term +parent: Span queries +grand_parent: Query DSL +nav_order: 80 +--- + +# Span term query + +The `span_term` query is the most basic span query that matches spans containing a single term. It serves as a building block for more complex span queries. + +For example, you can use the `span_term` query to: +- Find exact term matches that can be used in other span queries. +- Match specific words while maintaining position information. +- Create basic spans that can be combined with other span queries. + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for the exact term "formal": + +```json +GET /clothing/_search +{ + "query": { + "span_term": { + "description": "formal" + } + } +} +``` +{% include copy-curl.html %} + +Alternatively, you can specify the search term in the `value` parameter: + +```json +GET /clothing/_search +{ + "query": { + "span_term": { + "description": { + "value": "formal" + } + } + } +} +``` +{% include copy-curl.html %} + +You can also specify a `boost` value in order to boost the document score: + +```json +GET /clothing/_search +{ + "query": { + "span_term": { + "description": { + "value": "formal", + "boost": 2 + } + } + } +} +``` +{% include copy-curl.html %} + +The query matches documents 1 and 2 because they contain the exact term "formal". Position information is preserved for use in other span queries. + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.498922, + "hits": [ + { + "_index": "clothing", + "_id": "2", + "_score": 1.498922, + "_source": { + "description": "Beautiful long dress in red silk, perfect for formal events." + } + }, + { + "_index": "clothing", + "_id": "1", + "_score": 1.4466847, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + } + ] + } +} +``` +</details> + +## Parameters + +The following table lists all top-level parameters supported by `span_term` queries. + +| Parameter | Data type | Description | +|:----------------|:------------|:--------| +| `<field>` | String or object | The name of the field in which to search. | diff --git a/_query-dsl/span/span-within.md b/_query-dsl/span/span-within.md new file mode 100644 index 00000000..4f6b740e --- /dev/null +++ b/_query-dsl/span/span-within.md @@ -0,0 +1,107 @@ +--- +layout: default +title: Span within +parent: Span queries +grand_parent: Query DSL +nav_order: 90 +--- + +# Span within query + +The `span_within` query matches spans that are enclosed by another span query. It is the opposite of [`span_containing`]({{site.url}}{{site.baseurl}}/query-dsl/span/span-containing/): `span_containing` returns larger spans containing smaller ones, whereas `span_within` returns smaller spans enclosed by larger ones. + +For example, you can use the `span_within` query to: +- Find shorter phrases that appear within longer phrases. +- Match terms that occur within specific contexts. +- Identify smaller patterns enclosed by larger patterns. + +## Example + +To try the examples in this section, complete the [setup steps]({{site.url}}{{site.baseurl}}/query-dsl/span/#setup). +{: .tip} + +The following query searches for the word "dress" when it appears within a span containing "shirt" and "long": + +```json +GET /clothing/_search +{ + "query": { + "span_within": { + "little": { + "span_term": { + "description": "dress" + } + }, + "big": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "shirt" + } + }, + { + "span_term": { + "description": "long" + } + } + ], + "slop": 2, + "in_order": false + } + } + } + } +} +``` +{% include copy-curl.html %} + +The query matches document 1 because: +- The word "dress" appears within a larger span ("Long-sleeved dress shirt..."). +- The larger span contains "shirt" and "long" within 2 words of each other (there are 2 words between them). + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.4677674, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 1.4677674, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + } + ] + } +} +``` +</details> + +## Parameters + +The following table lists all top-level parameters supported by `span_within` queries. All parameters are required. + +| Parameter | Data type | Description | +|:----------|:-----|:------------| +| `little` | Object | The span query that must be contained within the `big` span. This defines the span you're searching for within a larger context. | +| `big` | Object | The containing span query that defines the boundaries within which the `little` span must appear. This establishes the context for your search. | \ No newline at end of file diff --git a/_query-dsl/specialized/agentic.md b/_query-dsl/specialized/agentic.md new file mode 100644 index 00000000..10146911 --- /dev/null +++ b/_query-dsl/specialized/agentic.md @@ -0,0 +1,64 @@ +--- +layout: default +title: Agentic +parent: AI and vector search queries +nav_order: 2 +--- + +# Agentic query +**Introduced 3.2** +{: .label .label-purple } + +Use the `agentic` query to ask questions in natural language and have OpenSearch automatically plan and execute the retrieval. The `agentic` query works in conjunction with a preconfigured agent that reads the question, plans the search, and returns relevant results. For more information about agentic search, see [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/). + +## Prerequisite + +Before using an `agentic` query, you must fulfill the following prerequisites: + +1. Configure an agent with the [`QueryPlanningTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/). The `QueryPlanningTool` is required for generating query domain-specific language (DSL) queries from natural language questions. Optionally, you can configure the agent with additional tools for enhanced functionality. +1. Create a search pipeline with an [`agentic_query_translator` search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-query-translator-processor/). + +For detailed setup instructions, see [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/). + +## Request body fields + +The `agentic` query accepts the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`query_text` | String | Required | The natural language question to be answered by the agent. +`query_fields` | Array | Optional | A list of index fields that the agent should consider when generating the search query. If omitted, the agent infers the applicable fields based on the index mappings and content. +`memory_id` | String | Optional | Applicable for `conversational` agents only. Provides a memory ID from a previous response to continue the conversation with prior context. See [Using conversational agents for agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/agent-converse/). | + +## Example + +The following example uses an `agentic` query that asks a natural language question about flowers in an `iris` dataset. In this example, `query_text` contains the natural language question, `query_fields` specifies the fields to use when generating the query, and the `search-pipeline` query parameter specifies the search pipeline containing the agentic query translator processor: + +```json +GET /iris-index/_search?search_pipeline=agentic-pipeline +{ + "query": { + "agentic": { + "query_text": "List all the flowers present", + "query_fields": ["species", "petal_length_in_cm"] + } + } +} +``` +{% include copy-curl.html %} + +When executed, the agentic search request performs the following steps: + +1. Sends the natural language question, along with the index mapping and a default prompt, to a large language model (LLM). +2. The LLM generates a query domain-specific language (DSL) query based on the input. +3. The generated DSL query is executed as a search request in OpenSearch. +4. Returns the search results based on the generated query. + +For a complete example, see [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/). + +## Next steps + +- Learn how to configure agentic search in [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/). +- Learn about agent types in [Agent types]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/#agent-types). +- Learn about the [`QueryPlanningTool`]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/tools/query-planning-tool/). +- View the reference documentation for the [`agentic_query_translator` search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-query-translator-processor/). \ No newline at end of file diff --git a/_query-dsl/specialized/distance-feature.md b/_query-dsl/specialized/distance-feature.md new file mode 100644 index 00000000..69283432 --- /dev/null +++ b/_query-dsl/specialized/distance-feature.md @@ -0,0 +1,223 @@ +--- +layout: default +title: Distance feature +parent: Specialized queries +nav_order: 5 +has_math: true +--- + +# Distance feature query + +Use the `distance_feature` query to boost the relevance of documents that are closer to a specific date or geographic point. This can help you prioritize more recent or nearby content in your search results. For example, you can assign more weight to products manufactured more recently or boost items closest to a user-specified location. + +You can apply this query to fields containing date or location data. It's commonly used within a `bool` query `should` clause to improve relevance scoring without filtering out results. + +## Configuring the index + +Before using the `distance_feature` query, ensure that your index contains at least one of the following field types: + +- [`date`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/) +- [`date_nanos`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date-nanos/) +- [`geo_point`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/) + +In this example, you'll configure the `opening_date` and `coordinates` fields that you can use to run distance feature queries: + +```json +PUT /stores +{ + "mappings": { + "properties": { + "opening_date": { + "type": "date" + }, + "coordinates": { + "type": "geo_point" + } + } + } +} +``` +{% include copy-curl.html %} + +Add sample documents to the index: + +```json +PUT /stores/_doc/1 +{ + "store_name": "Green Market", + "opening_date": "2025-03-10", + "coordinates": [74.00, 40.70] +} +``` +{% include copy-curl.html %} + +```json +PUT /stores/_doc/2 +{ + "store_name": "Fresh Foods", + "opening_date": "2025-04-01", + "coordinates": [73.98, 40.75] +} +``` +{% include copy-curl.html %} + +```json +PUT /stores/_doc/3 +{ + "store_name": "City Organics", + "opening_date": "2021-04-20", + "coordinates": [74.02, 40.68] +} +``` +{% include copy-curl.html %} + +## Example: Boost scores based on recency + +The following query searches for documents with a `store_name` matching `market` and boosts recently opened stores: + +```json +GET /stores/_search +{ + "query": { + "bool": { + "must": { + "match": { + "store_name": "market" + } + }, + "should": { + "distance_feature": { + "field": "opening_date", + "origin": "2025-04-07", + "pivot": "10d" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2372394, + "hits": [ + { + "_index": "stores", + "_id": "1", + "_score": 1.2372394, + "_source": { + "store_name": "Green Market", + "opening_date": "2025-03-10", + "coordinates": [ + 74, + 40.7 + ] + } + } + ] + } +} +``` + +### Example: Boost scores based on geographic proximity + +The following query searches for documents with a `store_name` matching `market` and boosts results closer to the given origin point: + +```json +GET /stores/_search +{ + "query": { + "bool": { + "must": { + "match": { + "store_name": "market" + } + }, + "should": { + "distance_feature": { + "field": "coordinates", + "origin": [74.00, 40.71], + "pivot": "500m" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2910118, + "hits": [ + { + "_index": "stores", + "_id": "1", + "_score": 1.2910118, + "_source": { + "store_name": "Green Market", + "opening_date": "2025-03-10", + "coordinates": [ + 74, + 40.7 + ] + } + } + ] + } +} +``` + +## Parameters + +The following table lists all top-level parameters supported by `distance_feature` queries. + +| Parameter | Required/Optional | Description | +|-----------|-------------------|-------------| +| `field` | Required | The name of the field used to calculate distances. Must be a `date`, `date_nanos`, or `geo_point` field with `index: true` (default) and `doc_values: true` (default). | +| `origin` | Required | The point of origin used to calculate distances. Use a [date]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/) or [date math expression]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#date-math) (for example, `now-1h`) for `date` fields or a [geopoint]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/) for `geo_point` fields. | +| `pivot` | Required | The distance from the `origin` at which scores receive half of the `boost` value. Use a time unit (for example, `10d`) for date fields or a distance unit (for example, `1km`) for geographic fields. For more information, see [Units]({{site.url}}{{site.baseurl}}/api-reference/units/).| +| `boost` | Optional | A multiplier for the relevance score of matching documents. Must be a non-negative float. Default is `1.0`. | + +## How scores are calculated + +The `distance_feature` query calculates a document's relevance score using the following formula: + +$$ \text{score} = \text{boost} \cdot \frac {\text{pivot}} {\text{pivot} + \text{distance}} $$, + +where $$\text{distance}$$ is the absolute difference between the `origin` and the field's value. + +## Skipping non-competitive hits + +Unlike other score-modifying queries like the `function_score` query, the `distance_feature` query is optimized to efficiently skip non-competitive hits when total hit tracking (`track_total_hits`) is disabled. diff --git a/_query-dsl/specialized/index.md b/_query-dsl/specialized/index.md index 8a4cd81a..b1199899 100644 --- a/_query-dsl/specialized/index.md +++ b/_query-dsl/specialized/index.md @@ -2,28 +2,24 @@ layout: default title: Specialized queries has_children: true -nav_order: 65 +nav_order: 60 has_toc: false +redirect_from: + - /query-dsl/specialized/ --- # Specialized queries -OpenSearch supports the following specialized queries: +Specialized queries provide advanced scoring, filtering, and utility functions beyond standard full-text and term queries. -- `distance_feature`: Calculates document scores based on the dynamically calculated distance between the origin and a document's `date`, `date_nanos`, or `geo_point` fields. This query can skip non-competitive hits. +For AI and vector search queries (k-NN, Neural, Neural sparse, Agentic, Template), see [AI and vector search queries]({{site.url}}{{site.baseurl}}/query-dsl/ai-vector-search/). -- `more_like_this`: Finds documents similar to the provided text, document, or collection of documents. - -- [`neural`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/): Used for vector field search in [neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/). - -- [`neural_sparse`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural-sparse/): Used for vector field search in [sparse neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). - -- `percolate`: Finds queries (stored as documents) that match the provided document. - -- `rank_feature`: Calculates scores based on the values of numeric features. This query can skip non-competitive hits. - -- `script`: Uses a script as a filter. - -- [`script_score`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/script-score/): Calculates a custom score for matching documents using a script. - -- `wrapper`: Accepts other queries as JSON or YAML strings. +| Query type | Description | +| :--- | :--- | +| [`distance_feature`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/distance-feature/) | Calculates document scores based on the dynamically calculated distance between the origin and a document's `date`, `date_nanos`, or `geo_point` fields. This query can skip non-competitive hits. | +| [`more_like_this`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/more-like-this/) | Finds documents similar to the provided text, document, or collection of documents. | +| [`percolate`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/percolate/) | Finds queries (stored as documents) that match the provided document. | +| [`rank_feature`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/rank-feature/) | Calculates scores based on the values of numeric features. This query can skip non-competitive hits. | +| [`script`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/script/) | Uses a script as a filter. | +| [`script_score`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/script-score/) | Calculates a custom score for matching documents using a script. | +| [`wrapper`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/wrapper/) | Accepts other queries as JSON or YAML strings. | diff --git a/_query-dsl/specialized/k-nn/index.md b/_query-dsl/specialized/k-nn/index.md new file mode 100644 index 00000000..c576897a --- /dev/null +++ b/_query-dsl/specialized/k-nn/index.md @@ -0,0 +1,221 @@ +--- +layout: default +title: k-NN +parent: AI and vector search queries +has_children: true +nav_order: 15 +redirect_from: + - /query-dsl/specialized/k-nn/ +--- + +# k-NN query + +Use the `knn` query for running nearest neighbor searches on vector fields. + +## Transport protocols + +k-NN queries can be executed using two transport protocols: + +- **HTTP/REST API**: The standard approach documented in this section. +- **gRPC API** (Generally available 3.2): High-performance binary protocol with the [k-NN (gRPC) API]({{site.url}}{{site.baseurl}}/api-reference/grpc-apis/knn/). + +For high-throughput vector search applications, consider using the gRPC k-NN API, which provides lower latency and higher throughput compared to HTTP-based queries. + +## Request body fields + +Provide a vector field in the `knn` query and specify additional request fields in the vector field object: + +```json +"knn": { + "<vector_field>": { + "vector": [<vector_values>], + "k": <k_value>, + ... + } +} +``` + +The top-level `vector_field` specifies the vector field against which to run a search query. The following table lists all supported request fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`vector` | Array of floats or bytes | Required | The query vector to use for vector search. The data type of the vector elements must match the data type of vectors indexed in the [`knn_vector` field]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-vector/) searched. +`k` | Integer | Optional | The number of nearest neighbors to return. Valid values are in the [1, 10,000] range. Required if either `max_distance` or `min_score` is not specified. +`max_distance` | Float | Optional | The maximum distance threshold for search results. Only one of `k`, `max_distance`, or `min_score` can be specified. For more information, see [Radial search]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/radial-search-knn/). +`min_score` | Float | Optional | The minimum score threshold for search results. Only one of `k`, `max_distance`, or `min_score` can be specified. For more information, see [Radial search]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/radial-search-knn/). +`filter` | Object | Optional | A filter to apply to the k-NN search. For more information, see [Vector search with filters]({{site.url}}{{site.baseurl}}/vector-search/filter-search-knn/). **Important**: A filter can only be used with the `faiss` or `lucene` engines. +`method_parameters` | Object | Optional | Additional parameters for fine-tuning the search:<br>- `ef_search` (Integer): The number of vectors to examine (for the `hnsw` method)<br>- `nprobes` (Integer): The number of buckets to examine (for the `ivf` method). For more information, see [Specifying method parameters in the query](#specifying-method-parameters-in-the-query). +`rescore` | Object or Boolean | Optional | Parameters for configuring rescoring functionality:<br>- `oversample_factor` (Float): Controls how many candidate vectors are retrieved before rescoring. Valid values are in the `[1.0, 100.0]` range. Default is `false` for fields with `in_memory` mode (no rescoring) and enabled (with dynamic values) for fields with `on_disk` mode. In `on_disk` mode, the default `oversample_factor` is determined by the `compression_level`. For more information, see the [compression level table]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-memory-optimized/#rescoring-quantized-results-to-full-precision). To explicitly enable rescoring with the default `oversample_factor` of `1.0`, set `rescore` to `true`. For more information, see [Rescoring results](#rescoring-results). +`expand_nested_docs` | Boolean | Optional | When `true`, retrieves scores for all nested field documents within each parent document. Used with nested queries. For more information, see [Vector search with nested fields]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/nested-search-knn/). + +## Example request + +```json +GET /my-vector-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [1.5, 2.5], + "k": 3 + } + } + } +} +``` +{% include copy-curl.html %} + +## Example request: Nested fields + +```json +GET /my-vector-index/_search +{ + "_source": false, + "query": { + "nested": { + "path": "nested_field", + "query": { + "knn": { + "nested_field.my_vector": { + "vector": [1,1,1], + "k": 2, + "expand_nested_docs": true + } + } + }, + "inner_hits": { + "_source": false, + "fields":["nested_field.color"] + }, + "score_mode": "max" + } + } +} +``` +{% include copy-curl.html %} + +## Example request: Radial search with max_distance + +The following example shows a radial search performed with `max_distance`: + +```json +GET /my-vector-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [ + 7.1, + 8.3 + ], + "max_distance": 2 + } + } + } +} +``` +{% include copy-curl.html %} + + +## Example request: Radial search with min_score + +The following example shows a radial search performed with `min_score`: + +```json +GET /my-vector-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [7.1, 8.3], + "min_score": 0.95 + } + } + } +} +``` +{% include copy-curl.html %} + +## Specifying method parameters in the query + +You can provide `method_parameters` in a search request: + +```json +GET /my-vector-index/_search +{ + "size": 2, + "query": { + "knn": { + "target-field": { + "vector": [2, 3, 5, 6], + "k": 2, + "method_parameters" : { + "ef_search": 100 + } + } + } + } +} +``` +{% include copy-curl.html %} + +These parameters are dependent on the combination of engine and method used to create the index. The following sections provide information about the supported `method_parameters`. + +### ef_search + +You can provide the `ef_search` parameter when searching an index created using the `hnsw` method. The `ef_search` parameter specifies the number of vectors to examine in order to find the top k nearest neighbors. Higher `ef_search` values improve recall at the cost of increased search latency. The value must be positive. + +The following table provides information about the `ef_search` parameter for the supported engines. + +Engine | Radial query support | Notes +:--- | :--- | :--- +`nmslib` (Deprecated) | No | If `ef_search` is present in a query, it overrides the `index.knn.algo_param.ef_search` index setting. +`faiss` | Yes | If `ef_search` is present in a query, it overrides the `index.knn.algo_param.ef_search` index setting. +`lucene` | No | When creating a search query, you must specify `k`. If you provide both `k` and `ef_search`, then the larger value is passed to the engine. If `ef_search` is larger than `k`, you can provide the `size` parameter to limit the final number of results to `k`. + +<!-- vale off --> +### nprobes +<!-- vale on --> + +You can provide the `nprobes` parameter when searching an index created using the `ivf` method. The `nprobes` parameter specifies the number of buckets to examine in order to find the top k nearest neighbors. Higher `nprobes` values improve recall at the cost of increased search latency. The value must be positive. + +The following table provides information about the `nprobes` parameter for the supported engines. + +Engine | Notes +:--- | :--- +`faiss` | If `nprobes` is present in a query, it overrides the value provided when creating the index. + +## Rescoring results + +You can fine-tune search by providing the `ef_search` and `oversample_factor` parameters. + +The `oversample_factor` parameter controls the factor by which the search oversamples the candidate vectors before ranking them. Using a higher oversample factor means that more candidates will be considered before ranking, improving accuracy but also increasing search time. When selecting the `oversample_factor` value, consider the trade-off between accuracy and efficiency. For example, setting the `oversample_factor` to `2.0` will double the number of candidates considered during the ranking phase, which may help achieve better results. + +The following request specifies the `ef_search` and `oversample_factor` parameters: + +```json +GET /my-vector-index/_search +{ + "size": 2, + "query": { + "knn": { + "my_vector_field": { + "vector": [1.5, 5.5, 1.5, 5.5, 1.5, 5.5, 1.5, 5.5], + "k": 10, + "method_parameters": { + "ef_search": 10 + }, + "rescore": { + "oversample_factor": 10.0 + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Next steps + +- [k-NN vector]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-vector/) +- [Rescoring quantized results to full precision]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-memory-optimized/#rescoring-quantized-results-to-full-precision) diff --git a/_query-dsl/specialized/k-nn/k-nn-explain.md b/_query-dsl/specialized/k-nn/k-nn-explain.md new file mode 100644 index 00000000..b4382a89 --- /dev/null +++ b/_query-dsl/specialized/k-nn/k-nn-explain.md @@ -0,0 +1,658 @@ +--- +layout: default +title: k-NN query explain +parent: k-NN +grand_parent: AI and vector search queries +nav_order: 10 +--- + +# k-NN query explain +**Introduced 3.0** +{: .label .label-purple } + +You can provide the `explain` parameter to understand how scores are calculated, normalized, and combined in `knn` queries. When enabled, it provides detailed information about the scoring process for each search result. This includes revealing the score normalization techniques used, how different scores were combined, and the calculations for individual subquery scores. This comprehensive insight makes it easier to understand and optimize your `knn` query results. For more information about `explain`, see [Explain API]({{site.url}}{{site.baseurl}}/api-reference/explain/). + +`explain` is an expensive operation in terms of both resources and time. For production clusters, we recommend using it sparingly for the purpose of troubleshooting. +{: .warning } + +You can provide the `explain` parameter in a URL when running a complete `knn` query for the Faiss engine using the following syntax: + +```json +GET {index}/_search?explain=true +POST {index}/_search?explain=true +``` + +`explain` for k-NN search for all types of queries with the Lucene engine does not return a detailed explanation as with the Faiss engine. +{: .note } + +The `explain` parameter works for the following types of k-NN search with the Faiss engine: + +- [Approximate k-NN search]({{site.url}}{{site.baseurl}}/vector-search/vector-search-techniques/approximate-knn/) +- Approximate k-NN search with [exact search]({{site.url}}{{site.baseurl}}/vector-search/vector-search-techniques/knn-score-script/) +- [Disk-based search]({{site.url}}{{site.baseurl}}/vector-search/optimizing-storage/disk-based-vector-search/) +- [k-NN search with efficient filtering]({{site.url}}{{site.baseurl}}/vector-search/filter-search-knn/efficient-knn-filtering/) +- [Radial search]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/radial-search-knn/) +- k-NN search with a `term` query + +`explain` for k-NN search with nested fields does not return a detailed explanation as with other searches. +{: .note } + +You can provide the `explain` parameter as a query parameter: + +```json +GET my-knn-index/_search?explain=true +{ + "query": { + "knn": { + "my_vector": { + "vector": [2, 3, 5, 7], + "k": 2 + } + } + } +} +``` +{% include copy-curl.html %} + +Alternatively, you can provide the `explain` parameter in the request body: + +```json +GET my-knn-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [2, 3, 5, 7], + "k": 2 + } + } + }, + "explain": true +} +``` +{% include copy-curl.html %} + +## Example: Approximate k-NN search + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took": 216038, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 88.4, + "hits": [ + { + "_shard": "[my-knn-index-1][0]", + "_node": "VHcyav6OTsmXdpsttX2Yug", + "_index": "my-knn-index-1", + "_id": "5", + "_score": 88.4, + "_source": { + "my_vector1": [ + 2.5, + 3.5, + 5.5, + 7.4 + ], + "price": 8.9 + }, + "_explanation": { + "value": 88.4, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 88.4, + "description": "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details": [ + { + "value": -87.4, + "description": "rawScore, returned from FAISS library", + "details": [] + } + ] + } + ] + } + }, + { + "_shard": "[my-knn-index-1][0]", + "_node": "VHcyav6OTsmXdpsttX2Yug", + "_index": "my-knn-index-1", + "_id": "2", + "_score": 84.7, + "_source": { + "my_vector1": [ + 2.5, + 3.5, + 5.6, + 6.7 + ], + "price": 5.5 + }, + "_explanation": { + "value": 84.7, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 84.7, + "description": "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details": [ + { + "value": -83.7, + "description": "rawScore, returned from FAISS library", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` +</details> + +## Example: Approximate k-NN search with exact search + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took": 87, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 84.7, + "hits": [ + { + "_shard": "[my-knn-index-1][0]", + "_node": "MQVux8dZRWeznuEYKhMq0Q", + "_index": "my-knn-index-1", + "_id": "7", + "_score": 84.7, + "_source": { + "my_vector2": [ + 2.5, + 3.5, + 5.6, + 6.7 + ], + "price": 5.5 + }, + "_explanation": { + "value": 84.7, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 84.7, + "description": "the type of knn search executed at leaf was Exact with spaceType = INNER_PRODUCT, vectorDataType = FLOAT, queryVector = [2.0, 3.0, 5.0, 6.0]", + "details": [] + } + ] + } + }, + { + "_shard": "[my-knn-index-1][0]", + "_node": "MQVux8dZRWeznuEYKhMq0Q", + "_index": "my-knn-index-1", + "_id": "8", + "_score": 82.2, + "_source": { + "my_vector2": [ + 4.5, + 5.5, + 6.7, + 3.7 + ], + "price": 4.4 + }, + "_explanation": { + "value": 82.2, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 82.2, + "description": "the type of knn search executed at leaf was Exact with spaceType = INNER_PRODUCT, vectorDataType = FLOAT, queryVector = [2.0, 3.0, 5.0, 6.0]", + "details": [] + } + ] + } + } + ] + } +``` +</details> + +## Example: Disk-based search + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 381.0, + "hits" : [ + { + "_shard" : "[my-vector-index][0]", + "_node" : "pLaiqZftTX-MVSKdQSu7ow", + "_index" : "my-vector-index", + "_id" : "9", + "_score" : 381.0, + "_source" : { + "my_vector_field" : [ + 9.5, + 9.5, + 9.5, + 9.5, + 9.5, + 9.5, + 9.5, + 9.5 + ], + "price" : 8.9 + }, + "_explanation" : { + "value" : 381.0, + "description" : "the type of knn search executed was Disk-based and the first pass k was 100 with vector dimension of 8, over sampling factor of 5.0, shard level rescoring enabled", + "details" : [ + { + "value" : 381.0, + "description" : "the type of knn search executed at leaf was Approximate-NN with spaceType = HAMMING, vectorDataType = FLOAT, queryVector = [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]", + "details" : [ ] + } + ] + } + } + ] + } +} +``` +</details> + +## Example: k-NN search with efficient filtering + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took" : 51, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.8620689, + "hits" : [ + { + "_shard" : "[products-shirts][0]", + "_node" : "9epk8WoFT8yvnUI0tAaJgQ", + "_index" : "products-shirts", + "_id" : "8", + "_score" : 0.8620689, + "_source" : { + "item_vector" : [ + 2.4, + 4.0, + 3.0 + ], + "size" : "small", + "rating" : 8 + }, + "_explanation" : { + "value" : 0.8620689, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 0.8620689, + "description" : "the type of knn search executed at leaf was Exact since filteredIds = 2 is less than or equal to K = 10 with spaceType = L2, vectorDataType = FLOAT, queryVector = [2.0, 4.0, 3.0]", + "details" : [ ] + } + ] + } + }, + { + "_shard" : "[products-shirts][0]", + "_node" : "9epk8WoFT8yvnUI0tAaJgQ", + "_index" : "products-shirts", + "_id" : "6", + "_score" : 0.029691212, + "_source" : { + "item_vector" : [ + 6.4, + 3.4, + 6.6 + ], + "size" : "small", + "rating" : 9 + }, + "_explanation" : { + "value" : 0.029691212, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 0.029691212, + "description" : "the type of knn search executed at leaf was Exact since filteredIds = 2 is less than or equal to K = 10 with spaceType = L2, vectorDataType = FLOAT, queryVector = [2.0, 4.0, 3.0]", + "details" : [ ] + } + ] + } + } + ] + } +} +``` +</details> + +## Example: Radial search + +```json +GET my-knn-index/_search?explain=true +{ + "query": { + "knn": { + "my_vector": { + "vector": [7.1, 8.3], + "max_distance": 2 + } + } + } +} +``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took" : 376529, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.98039204, + "hits" : [ + { + "_shard" : "[knn-index-test][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "knn-index-test", + "_id" : "1", + "_score" : 0.98039204, + "_source" : { + "my_vector" : [ + 7.0, + 8.2 + ], + "price" : 4.4 + }, + "_explanation" : { + "value" : 0.98039204, + "description" : "the type of knn search executed was Radial with the radius of 2.0", + "details" : [ + { + "value" : 0.98039204, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = l2 where score is computed as `1 / (1 + rawScore)` from:", + "details" : [ + { + "value" : 0.020000057, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + } + }, + { + "_shard" : "[knn-index-test][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "knn-index-test", + "_id" : "3", + "_score" : 0.9615384, + "_source" : { + "my_vector" : [ + 7.3, + 8.3 + ], + "price" : 19.1 + }, + "_explanation" : { + "value" : 0.9615384, + "description" : "the type of knn search executed was Radial with the radius of 2.0", + "details" : [ + { + "value" : 0.9615384, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = l2 where score is computed as `1 / (1 + rawScore)` from:", + "details" : [ + { + "value" : 0.040000115, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + } + } + ] + } +} + +``` +</details> + +## Example: k-NN search with a term query + +```json +GET my-knn-index/_search?explain=true +{ + "query": { + "bool": { + "should": [ + { + "knn": { + "my_vector2": { // vector field name + "vector": [2, 3, 5, 6], + "k": 2 + } + } + }, + { + "term": { + "price": "4.4" + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took" : 51, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 84.7, + "hits" : [ + { + "_shard" : "[my-knn-index-1][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "my-knn-index-1", + "_id" : "7", + "_score" : 84.7, + "_source" : { + "my_vector2" : [ + 2.5, + 3.5, + 5.6, + 6.7 + ], + "price" : 5.5 + }, + "_explanation" : { + "value" : 84.7, + "description" : "sum of:", + "details" : [ + { + "value" : 84.7, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 84.7, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details" : [ + { + "value" : -83.7, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + } + ] + } + }, + { + "_shard" : "[my-knn-index-1][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "my-knn-index-1", + "_id" : "8", + "_score" : 83.2, + "_source" : { + "my_vector2" : [ + 4.5, + 5.5, + 6.7, + 3.7 + ], + "price" : 4.4 + }, + "_explanation" : { + "value" : 83.2, + "description" : "sum of:", + "details" : [ + { + "value" : 82.2, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 82.2, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details" : [ + { + "value" : -81.2, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + }, + { + "value" : 1.0, + "description" : "price:[1082969293 TO 1082969293]", + "details" : [ ] + } + ] + } + } + ] + } +} +``` + +</details> + +## Response body fields + +Field | Description +:--- | :--- +`explanation` | The `explanation` object contains the following fields: <br> - `value`: Contains the calculation result.<br> - `description`: Explains what type of calculation was performed. For score normalization, the information in the `description` field includes the technique used for normalization or combination and the corresponding score. <br> - `details`: Shows any subcalculations performed. + diff --git a/_query-dsl/specialized/more-like-this.md b/_query-dsl/specialized/more-like-this.md new file mode 100644 index 00000000..7af8ced6 --- /dev/null +++ b/_query-dsl/specialized/more-like-this.md @@ -0,0 +1,290 @@ +--- +layout: default +title: More like this +parent: Specialized queries +nav_order: 45 +has_math: false +--- + +# More like this + +Use a `more_like_this` query to find documents that are similar to one or more given documents. This is useful for recommendation engines, content discovery, and identifying related items in a dataset. + +The `more_like_this` query analyzes the input documents or texts and selects terms that best characterize them. It then searches for other documents that contain those significant terms. + +## Prerequisites + +Before you use a `more_like_this` query, ensure that the fields you target are indexed and their data type is either [`text`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/text/) or [`keyword`]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/keyword/). + +If you reference documents in the `like` section, OpenSearch needs access to their content. This is typically done through the `_source` field, which is enabled by default. If `_source` is disabled, you must either store the fields individually or configure them to save [`term_vector`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/term-vector/) data. + +Saving [`term_vector`]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/term-vector/) information when indexing documents can greatly accelerate `more_like_this` queries because the engine can directly retrieve the important terms without reanalyzing the field text at query time. +{: .note} + +## Example: No term vector optimization + +Create an index named `articles-basic` using the following mapping: + +```json +PUT /articles-basic +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "content": { "type": "text" } + } + } +} +``` +{% include copy-curl.html %} + +Add sample documents: + +```json +POST /articles-basic/_bulk +{ "index": { "_id": 1 }} +{ "title": "Exploring the Sahara Desert", "content": "Sand dunes and vast landscapes." } +{ "index": { "_id": 2 }} +{ "title": "Amazon Rainforest Tour", "content": "Dense jungle and exotic wildlife." } +{ "index": { "_id": 3 }} +{ "title": "Mountain Adventures", "content": "Snowy peaks and hiking trails." } +``` +{% include copy-curl.html %} + +Query using the following request: + +```json +GET /articles-basic/_search +{ + "query": { + "more_like_this": { + "fields": ["content"], + "like": "jungle wildlife", + "min_term_freq": 1, + "min_doc_freq": 1 + } + } +} +``` +{% include copy-curl.html %} + +The `more_like_this` query searches for the terms `jungle` and `wildlife` in the `content` field, which matches only one document: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.9616582, + "hits": [ + { + "_index": "articles-basic", + "_id": "2", + "_score": 1.9616582, + "_source": { + "title": "Amazon Rainforest Tour", + "content": "Dense jungle and exotic wildlife." + } + } + ] + } +} +``` + +## Example: Term vector optimization + +Create an index named `articles-optimized` using the following mapping: + +```json +PUT /articles-optimized +{ + "mappings": { + "properties": { + "name": { + "type": "text", + "term_vector": "with_positions_offsets" + }, + "alias": { + "type": "text", + "term_vector": "with_positions_offsets" + }, + "quote": { + "type": "text", + "term_vector": "with_positions_offsets" + } + } + } +} +``` +{% include copy-curl.html %} + +Insert sample documents into the optimized index: + +```json +POST /articles-optimized/_bulk +{ "index": { "_id": "a1" } } +{ "name": "Diana", "alias": "Wonder Woman", "quote": "Justice will come when it is deserved." } +{ "index": { "_id": "a2" } } +{ "name": "Clark", "alias": "Superman", "quote": "Even in the darkest times, hope cuts through." } +{ "index": { "_id": "a3" } } +{ "name": "Bruce", "alias": "Batman", "quote": "I am vengeance. I am the night. I am Batman!" } +``` +{% include copy-curl.html %} + +Find documents in which the `quote` field contains terms similar to "dark" and "night": + +```json +GET /articles-optimized/_search +{ + "query": { + "more_like_this": { + "fields": ["quote"], + "like": "dark night", + "min_term_freq": 1, + "min_doc_freq": 1 + } + } +} +``` +{% include copy-curl.html %} + +The `more_like_this` query searches for the terms `dark` and `night` and returns the following hit: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2363393, + "hits": [ + { + "_index": "articles-optimized", + "_id": "a3", + "_score": 1.2363393, + "_source": { + "name": "Bruce", + "alias": "Batman", + "quote": "I am vengeance. I am the night. I am Batman!" + } + } + ] + } +} +``` + +## Example: Using multiple documents and text input + +The `more_like_this` query allows you to provide multiple sources in the `like` parameter. You can combine free text with documents from the index. This is useful if you want the search to combine relevance signals from several examples. + +In the following example, a custom document is provided directly. Additionally, an existing document with the ID `5` from the `heroes` index is included: + +```json +GET /articles-optimized/_search +{ + "query": { + "more_like_this": { + "fields": ["name", "alias"], + "like": [ + { + "doc": { + "name": "Diana", + "alias": "Wonder Woman", + "quote": "Courage is not the absence of fear, but the triumph over it." + } + }, + { + "_index": "heroes", + "_id": "5" + } + ], + "min_term_freq": 1, + "min_doc_freq": 1, + "max_query_terms": 25 + } + } +} +``` +{% include copy-curl.html %} + +The returned results contain articles most similar to the `name` and `alias` fields provided in the query: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 2.140194, + "hits": [ + { + "_index": "articles-optimized", + "_id": "a1", + "_score": 2.140194, + "_source": { + "name": "Diana", + "alias": "Wonder Woman", + "quote": "Justice will come when it is deserved." + } + }, + { + "_index": "articles-optimized", + "_id": "a2", + "_score": 1.1596459, + "_source": { + "name": "Clark", + "alias": "Superman", + "quote": "Even in the darkest times, hope cuts through." + } + } + ] + } +} +``` + +Use this pattern when you want to boost results based on a new concept that is not yet fully indexed but also want to combine it with knowledge from existing indexed documents. +{: .note} + +# Parameters + +The only required parameter for a `more_like_this` query is `like`. The rest of the parameters have default values but allow fine-tuning. The following are the main parameter categories. + +## Document input parameters + +The following table specifies document input parameters. + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `like`| Required| Array of strings or objects | Defines the text or documents for which to find similar documents. You can input free text, real documents from the index, or artificial documents. The analyzer associated with the field processes the text unless overridden. | +| `unlike`| Optional| Array of strings or objects | Provides text or documents whose terms should be *excluded* from influencing the query. Useful for specifying negative examples.| +| `fields`| Optional| Array of strings| Lists fields to use when analyzing text. If not specified, all fields are used. | + +## Term selection parameters + +| Parameter | Required/Optional | Data type| Description| +| :--- | :--- | :--- | :--- | +| `max_query_terms` | Optional| Integer| Sets the maximum number of terms to select from the input. A higher value increases precision but slows down execution. Default is `25`. | +| `min_term_freq` | Optional| Integer| Terms appearing fewer times than this in the input will be ignored. Default is `2`.| +| `min_doc_freq`| Optional| Integer| Terms appearing in fewer documents than this value will be ignored. Default is `5`.| +| `max_doc_freq`| Optional| Integer| Terms appearing in more documents than this limit are ignored. Useful for avoiding very common words. Default is unlimited (2<sup>31</sup> - 1). | +| `min_word_length` | Optional| Integer| Ignore words shorter than this value. Default is `0`.| +| `max_word_length` | Optional| Integer| Ignore words longer than this value. Default is unlimited. | +| `stop_words`| Optional| Array of strings | Defines a list of words that are ignored completely when selecting terms.| +| `analyzer`| Optional| String | The custom analyzer to use for processing input text. Defaults to the analyzer of the first field listed in `fields`.| + +## Query formation parameters + +| Parameter | Required/Optional | Data type | Description | +| :--- | :--- | :--- | :--- | +| `minimum_should_match`| Optional | String | Specifies the minimum number of terms that must match in the final query. The value can be a percentage or a fixed number. Helps fine-tune the balance between recall and precision. Default is `30%` | +| `fail_on_unsupported_field` | Optional | Boolean | Determines whether to throw an error if one of the target fields is not of a compatible type (`text` or `keyword`). Set to `false` to silently skip unsupported fields. Default is `true`. | +| `boost_terms` | Optional | Float | Applies a boost to selected terms based on their term frequency–inverse document frequency (TF–IDF) weight. Any value greater than `0` activates term boosting using the specified factor. Default is `0`. | +| `include` | Optional | Boolean | If `true`, the source documents provided in `like` are included in the result hits. Default is `false`. | +| `boost` | Optional | Float | Multiplies the relevance score of the entire `more_like_this` query. Default is `1.0`. | diff --git a/_query-dsl/specialized/neural-sparse/index.md b/_query-dsl/specialized/neural-sparse/index.md new file mode 100644 index 00000000..a100c464 --- /dev/null +++ b/_query-dsl/specialized/neural-sparse/index.md @@ -0,0 +1,295 @@ +--- +layout: default +title: Neural sparse +parent: AI and vector search queries +has_children: true +nav_order: 55 +redirect_from: + - /query-dsl/specialized/neural-sparse/ +--- + +# Neural sparse query +**Introduced 2.11** +{: .label .label-purple } + +The `neural_sparse` query performs vector field search for neural sparse functionality. You can run this query on two types of vector fields: + +- **`rank_features` fields**: For traditional [neural sparse search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-search/) +- **`sparse_vector` fields**: For [neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/) + +## Neural sparse search + +Use neural sparse search on `rank_features` fields for traditional sparse vector search with inverted index efficiency. + +You can run a neural sparse search either using raw sparse vectors or text. The text can be tokenized by built-in analyzers or tokenizer models. + +### Using raw sparse vectors + +Provide sparse vector embeddings directly for matching: + +```json +"neural_sparse": { + "<rank_features_field>": { + "query_tokens": { + "<token>": <weight>, + ... + } + } +} +``` + +For more information, see [Neural sparse search using raw vectors]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-with-raw-vectors/). + +### Using text with built-in analyzers + +Provide text to tokenize using a built-in DL model analyzer: + +```json +"neural_sparse": { + "<rank_features_field>": { + "query_text": "<input text>", + "analyzer": "bert-uncased" + } +} +``` + +### Using text with custom models + +Provide text to tokenize using a custom tokenizer model: + +```json +"neural_sparse": { + "<rank_features_field>": { + "query_text": "<input text>", + "model_id": "<model ID>" + } +} +``` + +For more information, see [Generating sparse vector embeddings automatically]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-with-pipelines/). + +## Neural sparse ANN search +**Introduced 3.3** +{: .label .label-purple } + +Use neural sparse ANN search on `sparse_vector` fields for improved query performance with high recall. For more information, see [Neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/). + +Neural sparse ANN search supports two engines: the Lucene engine and the native engine. You select the engine in the field mapping by setting `method.engine`. The query syntax and all supported query parameters are the same for both engines. For more information, see [Engines]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/#engines). + +You can run a neural sparse search either using raw sparse vectors or text. + +### Using raw sparse vectors + +```json +"neural_sparse": { + "<sparse_vector_field>": { + "query_tokens": { + "<token>": <weight>, + ... + }, + "method_parameters": { + "top_n": 10, + "heap_factor": 1.0, + "k": 10 + } + } +} +``` + +### Using text with models + +```json +"neural_sparse": { + "<sparse_vector_field>": { + "query_text": "<input text>", + "model_id": "<model ID>", + "method_parameters": { + "top_n": 10, + "heap_factor": 1.0, + "k": 10 + } + } +} +``` + +## Request body fields + +The top-level field name specifies the vector field against which to run a search query. You must specify either `query_text` or `query_tokens` to define the input. + +### Common fields + +These fields are supported for both `rank_features` and `sparse_vector` field types. + +| Field | Data type | Required/Optional | Description | +|:--- |:--- |:--- |:--- | +| `query_text` | String | Optional | The query text to convert into sparse vector embeddings. Either `query_text` or `query_tokens` must be specified. | +| `query_tokens` | Map of token (string) to weight (float) | Optional | A raw sparse vector in the form of tokens and their weights. Used as an alternative to `query_text` for direct vector input. Either `query_text` or `query_tokens` must be specified. | +| `model_id` | String | Optional | Used with `query_text`. The ID of the sparse encoding model (for bi-encoder mode) or tokenizer (for doc-only mode) used to generate vector embeddings from the query text. The model/tokenizer must be deployed in OpenSearch before it can be used in neural sparse search. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Generating sparse vector embeddings automatically]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-with-pipelines/). For information about setting a default model ID in a neural sparse query, see [`neural_query_enricher`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/neural-query-enricher/). Cannot be specified at the same time as `analyzer`. | +| `max_token_score` | Float | Optional | (Deprecated) This parameter has been deprecated since OpenSearch 2.12. It is maintained only for backward compatibility and no longer affects functionality. The parameter can still be provided in requests, but its value has no impact. Previously used as the theoretical upper bound of the score for all tokens in the vocabulary.| + +### Fields for rank_features only + +| Field | Data type | Required/Optional | Description | +|:--- |:--- |:--- |:--- | +| `analyzer` | String | Optional | Used with `query_text`. Specifies a built-in DL model analyzer for tokenizing query text. Valid values are `bert-uncased` and `mbert-uncased`. Default is `bert-uncased`. If neither `model_id` nor `analyzer` are specified, the default analyzer (`bert-uncased`) is used to tokenize the text. Cannot be specified at the same time as `model_id`. For more information, see [DL model analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/dl-model-analyzers/). | + +### Fields for sparse_vector only + +| Field | Data type | Required/Optional | Description | +|:--- |:--- |:--- |:--- | +| `method_parameters.top_n` | Integer | Optional | Specifies the number of query tokens with the highest weights to retain for approximate sparse queries. | +| `method_parameters.heap_factor` | Float | Optional | Controls the trade-off between recall and performance. Higher values increase recall but reduce query speed; lower values decrease recall but improve query speed. | +| `method_parameters.k` | Integer | Optional | Specifies the number of top results that [neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/) returns. | +| `method_parameters.filter` | Object | Optional | Applies filters to the query results. How the filter is applied depends on the engine configured for the field. See [Filtering in neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/filter-search-knn/filtering-in-sparse-search/). | + +If the filter matches fewer documents than `k`, both engines run an exact search over the filtered documents. Beyond that point, the Lucene engine applies the filter after approximate retrieval, so a selective filter can produce fewer than `k` results, whereas the native engine retrieves within the filtered set and can return the full `k` results. This difference is determined by the engine configured in the field mapping. +{: .note} + +## Examples + +The following examples demonstrate using a `neural_sparse` query. + +### Neural sparse search on rank_features fields + +You can run a neural sparse search on a `rank_features` field using text tokenized by an analyzer or a model or using raw vectors. + +#### Using text tokenized by an analyzer + +To run a search using text tokenized by an analyzer, specify an `analyzer` in the request. The analyzer must be compatible with the model that you used for text analysis at ingestion time: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "analyzer": "bert-uncased" + } + } + } +} +``` +{% include copy-curl.html %} + +For more information, see [DL model analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/dl-model-analyzers/). + +If you don't specify an analyzer, the default `bert-uncased` analyzer is used: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Using text tokenized by a model + +To search using text tokenized by a tokenizer model, provide the model ID in the request: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "aP2Q8ooBpBj3wT4HVS8a" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Using raw vectors + +To search using a sparse vector, provide the sparse vector in the `query_tokens` parameter: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_tokens": { + "hi" : 4.338913, + "planets" : 2.7755864, + "planet" : 5.0969057, + "mars" : 1.7405145, + "earth" : 2.6087382, + "hello" : 3.3210192 + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Neural sparse ANN search on sparse_vector fields + +You can run a neural sparse ANN search on a `sparse_vector` field using text or raw vectors. + +#### Using text + +To search using natural language, provide the `query_text` and a deployed sparse encoding model ID: + +```json +GET sparse-vector-index/_search +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_text": "<input text>", + "model_id": "<model ID>", + "method_parameters": { + "k": 10, + "top_n": 10, + "heap_factor": 1.0 + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Using raw vectors with method parameters + +To search using a precomputed sparse vector, provide the vector in the `query_tokens` field: + +```json +GET sparse-vector-index/_search +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "1055": 5.5 + }, + "method_parameters": { + "heap_factor": 1.0, + "top_n": 10, + "k": 10 + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Next steps + +- For more information about neural sparse search, see [Neural sparse search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-search/). +- For more information about neural sparse ANN search, see [Neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/). +- For field type information, see [Rank features]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/rank/) and [Sparse vector]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/sparse-vector/). +- For information about filtering `neural_sparse` query results, see [Filtering in neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/filter-search-knn/filtering-in-sparse-search/). diff --git a/_query-dsl/specialized/neural-sparse/neural-sparse-explain.md b/_query-dsl/specialized/neural-sparse/neural-sparse-explain.md new file mode 100644 index 00000000..2117a7b2 --- /dev/null +++ b/_query-dsl/specialized/neural-sparse/neural-sparse-explain.md @@ -0,0 +1,390 @@ +--- +layout: default +title: Neural sparse ANN explain +parent: Neural sparse +grand_parent: AI and vector search queries +nav_order: 10 +--- + +# Neural sparse ANN query explain +**Introduced 3.5** +{: .label .label-purple } + +You can provide the `explain` parameter to understand how scores are calculated in neural sparse approximate nearest neighbor (ANN) queries. When enabled, it provides detailed information about the scoring process for each search result, including query token pruning, quantized dot product calculations, quantization rescaling, and filter application. This comprehensive insight makes it easier to understand and optimize your neural sparse ANN query results. For more information about `explain`, see [Explain API]({{site.url}}{{site.baseurl}}/api-reference/explain/). + +`explain` is an expensive operation in terms of both resources and time. For production clusters, we recommend using it sparingly for the purpose of troubleshooting. +{: .warning } + +The examples and field descriptions on this page describe the explanation output of the Lucene engine, which is the default engine for a `sparse_vector` field. The native engine's explanation reports query token pruning and an exact dot product score and doesn't include a quantization rescaling component. Both engines quantize token weights to 8 bits using the `quantization_ceiling_ingest` and `quantization_ceiling_search` mapping parameters, so both parameters are meaningful for either engine. The engines differ only in the explanation breakdown. For more information about engines, see [Engines]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/#engines). + +The explanation includes the neural sparse ANN components described on this page only for segments containing at least `approximate_threshold` documents (by default, `1000000`). Queries against smaller segments return the standard `rank_features` explanation. For more information, see [Hybrid indexing]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/#hybrid-indexing). +{: .note} + +You can provide the `explain` parameter in a URL when running a neural sparse ANN query using the following syntax: + +```json +GET {index}/_search?explain=true +POST {index}/_search?explain=true +``` + +The `explain` parameter works for the following types of neural sparse ANN search: + +- Basic neural sparse ANN search +- Neural sparse ANN search with filters + +You can provide the `explain` parameter as a query parameter: + +```json +GET my-sparse-index/_search?explain=true +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "7001": 6.25, + "3509": 5.57 + }, + "method_parameters": { + "k": 5, + "top_n": 6 + } + } + } + } +} +``` +{% include copy-curl.html %} + +Alternatively, you can provide the `explain` parameter in the request body: + +```json +GET my-sparse-index/_search +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "7001": 6.25, + "3509": 5.57 + }, + "method_parameters": { + "k": 5, + "top_n": 3 + } + } + } + }, + "explain": true +} +``` +{% include copy-curl.html %} + +## Example: Basic neural sparse ANN search + +```json +GET my-sparse-index/_search?explain=true +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "13723": 0.75, + "9266": 0.61, + "2078": 0.35, + "2365": 0.41 + }, + "method_parameters": { + "k": 10, + "top_n": 6 + } + } + } + } +} +``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 16.059792, + "hits": [ + { + "_shard": "[my-sparse-index][0]", + "_node": "iId6ipt-SCWA-7vHLh981Q", + "_index": "my-sparse-index", + "_id": "1", + "_score": 16.059792, + "_source": { + "sparse_embedding": { + "13723": 3.16, + "9266": 2.85, + "2078": 1.09, + "2365": 0.22 + } + }, + "_explanation": { + "value": 16.059792, + "description": "sparse_ann score for doc 94830 in field 'sparse_embedding'", + "details": [ + { + "value": 6, + "description": "query token pruning: kept top 6 of 33 tokens", + "details": [] + }, + { + "value": 21756, + "description": "raw dot product score (quantized): 21756", + "details": [ + { + "value": 9494, + "description": "token '13723' contribution: query_weight=47 * doc_weight=202", + "details": [] + }, + { + "value": 7098, + "description": "token '9266' contribution: query_weight=39 * doc_weight=182", + "details": [] + }, + { + "value": 1540, + "description": "token '2078' contribution: query_weight=22 * doc_weight=70", + "details": [] + }, + { + "value": 364, + "description": "token '2365' contribution: query_weight=26 * doc_weight=14", + "details": [] + } + ] + }, + { + "value": 0.0007381776, + "description": "quantization rescaling: 1.0000 * 3.00 * 16.00 / 255 / 255 = 0.000738", + "details": [ + { + "value": 1, + "description": "original boost: 1.0000", + "details": [] + }, + { + "value": 3, + "description": "ceiling_ingest (quantization parameter): 3.00", + "details": [] + }, + { + "value": 16, + "description": "ceiling_search (quantization parameter): 16.00", + "details": [] + }, + { + "value": 255, + "description": "MAX_UNSIGNED_BYTE_VALUE: 255", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` +</details> + +## Example: Neural sparse ANN search with filter + +```json +GET hotels-index/_search?explain=true +{ + "query": { + "neural_sparse": { + "name_embedding": { + "query_tokens": { + "7001": 6.25, + "3509": 5.57 + }, + "method_parameters": { + "k": 5, + "filter": { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Example response + </summary> + {: .text-delta} + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 70.55404, + "hits": [ + { + "_shard": "[hotels-index][0]", + "_node": "iId6ipt-SCWA-7vHLh981Q", + "_index": "hotels-index", + "_id": "8", + "_score": 70.55404, + "_source": { + "parking": true, + "name": "Crystal Beach Resort", + "rating": 9, + "name_embedding": { + "3509": 5.5722017, + "6121": 6.5081306, + "7001": 6.25483 + } + }, + "_explanation": { + "value": 70.55404, + "description": "sparse_ann score for doc 7 in field 'name_embedding'", + "details": [ + { + "value": 2, + "description": "query token pruning: kept all 2 tokens (no pruning occurred)", + "details": [] + }, + { + "value": 17921, + "description": "raw dot product score (quantized): 17921", + "details": [ + { + "value": 10000, + "description": "token '7001' contribution: query_weight=100 * doc_weight=100", + "details": [] + }, + { + "value": 7921, + "description": "token '3509' contribution: query_weight=89 * doc_weight=89", + "details": [] + } + ] + }, + { + "value": 0.003936948, + "description": "quantization rescaling: 1.0000 * 16.00 * 16.00 / 255 / 255 = 0.003937", + "details": [ + { + "value": 1, + "description": "original boost: 1.0000", + "details": [] + }, + { + "value": 16, + "description": "ceiling_ingest (quantization parameter): 16.00", + "details": [] + }, + { + "value": 16, + "description": "ceiling_search (quantization parameter): 16.00", + "details": [] + }, + { + "value": 255, + "description": "MAX_UNSIGNED_BYTE_VALUE: 255", + "details": [] + } + ] + }, + { + "value": 1, + "description": "document passed filter with exact search mode (filter matched 4 documents <= k=5, all filtered documents scored exactly)", + "details": [ + { + "value": 1, + "description": "filter criteria: +ApproximateScoreQuery(originalQuery=IndexOrDocValuesQuery(indexQuery=rating:[8 TO 10], dvQuery=rating:[8 TO 10]), approximationQuery=Approximate(rating:[8 TO 10]))", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` +</details> + +## Response body fields + +The following table describes the fields in the explanation response. + +Field | Description +:--- | :--- +`explanation` | The `explanation` object contains the following fields: <br> - `value`: Contains the calculation result.<br> - `description`: Explains what type of calculation was performed. <br> - `details`: Shows any subcalculations performed. + +### Explanation components + +The `details` array in the explanation contains the following components based on the neural sparse ANN scoring process. + +Component | Description +:--- | :--- +Query token pruning | Shows the number of query tokens retained after pruning based on the `top_n` parameter. If no pruning occurs, indicates that all tokens were kept. +Raw dot product score | The quantized dot product score before rescaling. Contains nested details showing each token's contribution as `query_weight * doc_weight`. +Quantization rescaling | (Lucene engine only) Explains how the raw quantized score is converted to the final float score using the formula: `boost * ceiling_ingest * ceiling_search / 255 / 255`. Contains details about each parameter used in the calculation. +Filter explanation | (When filters are applied) Shows filter criteria and search mode. Indicates whether exact search mode was used when the number of filtered documents is fewer than or equal to `k`. + +### Quantization parameters + +Neural sparse ANN search uses unsigned byte quantization to reduce memory usage and improve search performance. The Lucene engine's quantization rescaling section includes the following parameters. The native engine applies the same quantization but reports an exact dot product score, so this section doesn't appear in its explanations. + +Parameter | Description +:--- | :--- +`original boost` | The boost value applied to the query. Default is 1.0. +`ceiling_ingest` | The quantization ceiling parameter used during document ingestion. +`ceiling_search` | The quantization ceiling parameter used during search. +`MAX_UNSIGNED_BYTE_VALUE` | The maximum value for unsigned byte quantization (255). + +During ingestion, float token weights are converted to unsigned bytes (0--255) by dividing each weight by `ceiling_ingest` and scaling to the byte range. Similarly, during search, query token weights are quantized using `ceiling_search`. The raw dot product is computed using these quantized byte values. To recover the approximate original score, the result is rescaled using the formula `final_score = raw_quantized_score * boost * ceiling_ingest * ceiling_search / 255 / 255`. The ceiling parameters determine the maximum weight value that can be represented without clipping---weights exceeding the ceiling are capped at 255. + +## Next steps + +- For more information about neural sparse ANN search, see [Neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/neural-sparse-ann/). +- For more information about the Explain API, see [Explain API]({{site.url}}{{site.baseurl}}/api-reference/explain/). +- For information about filtering in neural sparse ANN search, see [Filtering in neural sparse ANN search]({{site.url}}{{site.baseurl}}/vector-search/filter-search-knn/filtering-in-sparse-search/). diff --git a/_query-dsl/specialized/neural.md b/_query-dsl/specialized/neural.md index a4b2ad7f..39a83c9e 100644 --- a/_query-dsl/specialized/neural.md +++ b/_query-dsl/specialized/neural.md @@ -1,16 +1,15 @@ --- layout: default title: Neural -parent: Specialized queries -grand_parent: Query DSL +parent: AI and vector search queries nav_order: 50 --- # Neural query -Use the `neural` query for vector field search in [neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/). +Use the `neural` query for vector field search by text or image in [vector search]({{site.url}}{{site.baseurl}}/vector-search/). -## Request fields +## Request body fields Include the following request fields in the `neural` query: @@ -25,18 +24,27 @@ Include the following request fields in the `neural` query: } ``` -The top-level `vector_field` specifies the vector field against which to run a search query. The following table lists the other neural query fields. +The top-level `vector_field` specifies the vector or semantic field against which to run a search query. The following table lists the other neural query fields. Field | Data type | Required/Optional | Description :--- | :--- | :--- `query_text` | String | Optional | The query text from which to generate vector embeddings. You must specify at least one `query_text` or `query_image`. -`query_image` | String | Optional | A base-64 encoded string that corresponds to the query image from which to generate vector embeddings. You must specify at least one `query_text` or `query_image`. -`model_id` | String | Required if the default model ID is not set. For more information, see [Setting a default model on an index or field]({{site.url}}{{site.baseurl}}/search-plugins/neural-text-search/#setting-a-default-model-on-an-index-or-field). | The ID of the model that will be used to generate vector embeddings from the query text. The model must be deployed in OpenSearch before it can be used in neural search. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/). -`k` | Integer | Optional | The number of results returned by the k-NN search. Default is 10. -`filter` | Object | Optional | A query that can be used to reduce the number of documents considered. For more information about filter usage, see [k-NN search with filters]({{site.url}}{{site.baseurl}}/search-plugins/knn/filter-search-knn/). **Important**: Filter can only be used with the `faiss` or `lucene` engines. +`query_image` | String | Optional | A Base64-encoded string that corresponds to the query image from which to generate vector embeddings. You must specify at least one `query_text` or `query_image`. +`model_id` | String | Optional if the target field is a semantic field. Required if the target field is a `knn_vector` field and the default model ID is not set. For more information, see [Setting a default model on an index or field]({{site.url}}{{site.baseurl}}/search-plugins/neural-text-search/#setting-a-default-model-on-an-index-or-field). | The ID of the model that will be used to generate vector embeddings from the query text. The model must be deployed in OpenSearch before it can be used. For more information, see [Using custom models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [AI search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/index/). Cannot be provided together with the `semantic_field_search_analyzer`. +`k` | Integer | Optional | The number of results returned by the k-NN search. Only one variable, either `k`, `min_score`, or `max_distance`, can be specified. If a variable is not specified, the default is `k` with a value of `10`. +`min_score` | Float | Optional | The minimum score threshold for the search results. Only one variable, either `k`, `min_score`, or `max_distance`, can be specified. For more information, see [Radial search]({{site.url}}{{site.baseurl}}/search-plugins/knn/radial-search-knn/). +`max_distance` | Float | Optional | The maximum distance threshold for the search results. Only one variable, either `k`, `min_score`, or `max_distance`, can be specified. For more information, see [Radial search]({{site.url}}{{site.baseurl}}/search-plugins/knn/radial-search-knn/). +`filter` | Object | Optional | A query that can be used to reduce the number of documents considered. For more information about filter usage, see [Vector search with filters]({{site.url}}{{site.baseurl}}/search-plugins/knn/filter-search-knn/). +`method_parameters` | Object | Optional | Additional parameters for fine-tuning the search:<br>- `ef_search` (Integer): The number of vectors to examine (for the `hnsw` method)<br>- `nprobes` (Integer): The number of buckets to examine (for the `ivf` method). For more information, see [Specifying method parameters in the query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/k-nn/index/#specifying-method-parameters-in-the-query). +`rescore` | Object or Boolean | Optional | Parameters for configuring rescoring functionality:<br>- `oversample_factor` (Float): Controls how many candidate vectors are retrieved before rescoring. Valid values are in the `[1.0, 100.0]` range. Default is `false` for fields with `in_memory` mode (no rescoring) and `enabled` (with dynamic values) for fields with `on_disk` mode. In `on_disk` mode, the default `oversample_factor` is determined by the `compression_level`. For more information, see the [compression level table]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/knn-memory-optimized/#rescoring-quantized-results-to-full-precision). To explicitly enable rescoring with the default `oversample_factor` of `1.0`, set `rescore` to `true`. For more information, see [Rescoring results]({{site.url}}{{site.baseurl}}/query-dsl/specialized/k-nn/index/#rescoring-results). +`expand_nested_docs` | Boolean | Optional | When `true`, retrieves scores for all nested field documents within each parent document. Used with nested queries. For more information, see [Vector search with nested fields]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/nested-search-knn/). +`semantic_field_search_analyzer` | String | Optional | Specifies an analyzer for tokenizing the `query_text` when using a sparse encoding model. Valid values are `standard`, `bert-uncased`, and `mbert-uncased`. Cannot be used together with `model_id`. For more information, see [Analyzers]({{site.url}}{{site.baseurl}}/analyzers/supported-analyzers/). +`query_tokens` | Map of token (string) to weight (float) | Optional | A raw sparse vector in the form of tokens and their weights. Used as an alternative to `query_text` for direct vector input. Either `query_text` or `query_tokens` must be specified. #### Example request +The following example shows a search with a `k` value of `100` and a filter that includes a range query and a term query: + ```json GET /my-nlp-index/_search { @@ -70,4 +78,115 @@ GET /my-nlp-index/_search } } ``` -{% include copy-curl.html %} \ No newline at end of file +{% include copy-curl.html %} + +The following search query includes a k-NN radial search `min_score` of `0.95` and a filter that includes a range query and a term query: + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "query_image": "iVBORw0KGgoAAAAN...", + "min_score": 0.95, + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + }, + { + "term": { + "parking": "true" + } + } + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The following search query includes a k-NN radial search `max_distance` of `10` and a filter that includes a range query and a term query: + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural": { + "passage_embedding": { + "query_text": "Hi world", + "query_image": "iVBORw0KGgoAAAAN...", + "max_distance": 10, + "filter": { + "bool": { + "must": [ + { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + }, + { + "term": { + "parking": "true" + } + } + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The following example shows a search against a `semantic` field using a dense model. A `semantic` field stores model information in its configuration. The `neural` query automatically retrieves the `model_id` from the `semantic` field's configuration in the index mapping and rewrites the query to target the corresponding embedding field: + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural": { + "passage": { + "query_text": "Hi world" + "k": 100 + } + } + } +} +``` +{% include copy-curl.html %} + +The following example shows a search against a `semantic` field using a sparse encoding model. This search uses sparse embeddings: + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural": { + "passage": { + "query_tokens": { + "worlds": 0.57605183 + } + } + } + } +} +``` +{% include copy-curl.html %} + +For more information, see [Semantic field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/semantic/). \ No newline at end of file diff --git a/_query-dsl/specialized/percolate.md b/_query-dsl/specialized/percolate.md new file mode 100644 index 00000000..dd204870 --- /dev/null +++ b/_query-dsl/specialized/percolate.md @@ -0,0 +1,814 @@ +--- +layout: default +title: Percolate +parent: Specialized queries +nav_order: 55 +--- + +# Percolate query + +Use the `percolate` query to find saved queries that match a given document. This operation is the opposite of a regular search: instead of finding documents that match a query, you find queries that match a document. `percolate` queries are often used for alerting, notifications, and reverse search use cases. + +When working with `percolate` queries, consider the following key points: + +- You can percolate a document provided inline or fetch an existing document from an index. +- The document and the stored queries must use the same field names and types. +- You can combine percolation with filtering and scoring to build complex matching systems. +- `percolate` queries are considered [expensive queries]({{site.url}}{{site.baseurl}}/query-dsl/#expensive-queries) and run only if the cluster setting `search.allow_expensive_queries` is set to `true` (default). If this setting is `false`, OpenSearch rejects `percolate` queries. + +`percolate` queries are useful in a variety of real-time matching scenarios. Some common use cases include: + +- Users register interest in products, for example, "Notify me when new Apple laptops are in stock." When new product documents are indexed, the system finds all users with matching saved queries and sends them notifications. +- Job seekers save queries based on preferred job titles or locations, and new job postings are matched against these queries to trigger alerts. +- Incoming log or event data is percolated against saved security rules or anomaly patterns. +- Incoming news articles are matched against saved topic profiles to categorize them or deliver them to interested readers. + +Saved queries are stored in a [`percolator` field]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/percolator/). When you run a `percolate` query, OpenSearch compares the document against the saved queries and returns each matching query, identified by its `_id`. If you enable highlighting, the response also contains the matching text from the document. If you percolate multiple documents, the `_percolator_document_slot` field identifies the documents that each query matched. + +## Example + +The following examples demonstrate how to save queries and test documents against them using different methods. + +### Create an index for storing saved queries + +First, create an index and configure its `mappings` with a [`percolator` field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/percolator/) to store the saved queries: + +```json +PUT /my_percolator_index +{ + "mappings": { + "properties": { + "query": { + "type": "percolator" + }, + "title": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +The index must also map every field that the saved queries search---in this example, `title`. OpenSearch uses these mappings to parse each saved query and the percolated document. If a field isn't mapped, saving a query that searches it fails with a `No field mapping can be found for the field with name [title]` error. + +Add a query matching "apple" in the `title` field: + +```json +POST /my_percolator_index/_doc/1 +{ + "query": { + "match": { + "title": "apple" + } + } +} +``` +{% include copy-curl.html %} + +Add a query matching "banana" in the `title` field: + +```json +POST /my_percolator_index/_doc/2 +{ + "query": { + "match": { + "title": "banana" + } + } +} +``` +{% include copy-curl.html %} + +### Percolate an inline document + +Test an inline document against the saved queries: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "document": { + "title": "Fresh Apple Harvest" + } + } + } +} +``` +{% include copy-curl.html %} + +The response provides the saved query that searches for documents containing the word "apple" in the `title` field, identified by `_id`: `1`: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + } + } + ] + } +} +``` + +### Percolate in a filter context + +By default, OpenSearch calculates a relevance score for each matching query. Whether a saved query matches can often be decided from its extracted terms alone, but scoring requires a full evaluation of each candidate query against the document. If you don't need scores, wrap the `percolate` query in a `constant_score` query or in the `filter` clause of a `bool` query: + +```json +POST /my_percolator_index/_search +{ + "query": { + "constant_score": { + "filter": { + "percolate": { + "field": "query", + "document": { + "title": "Fresh Apple Harvest" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +The same query matches, but each hit receives a constant score of `1.0`: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 1.0, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + } + } + ] + } +} +``` + +The query cache never stores a `percolate` query or any compound query that contains one because these queries use a large amount of memory. +{: .note} + +### Percolate with multiple documents + +To test multiple documents in the same query, use the following request: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "documents": [ + { "title": "Banana flavoured ice-cream" }, + { "title": "Apple pie recipe" }, + { "title": "Banana bread instructions" }, + { "title": "Cherry tart" } + ] + } + } +} +``` +{% include copy-curl.html %} + +The `_percolator_document_slot` field identifies each document that a saved query matched by the document's position in the `documents` array, starting at `0`: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.54726034, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.54726034, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 1 + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.31506687, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0, + 2 + ] + } + } + ] + } +} +``` + +### Percolate an existing indexed document + +You can reference an existing document already stored in another index to check for matching saved queries. + +Create a separate index for your documents: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +Add a document: + +```json +POST /products/_doc/1 +{ + "title": "Banana Smoothie Special" +} +``` +{% include copy-curl.html %} + +Check whether the stored queries match the indexed document: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "index": "products", + "id": "1" + } + } +} +``` +{% include copy-curl.html %} + +You must provide both `index` and `id` when using a stored document. +{: .note} + +The corresponding query is returned: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + } + } + ] + } +} +``` + +To make sure that you percolate the version of the document you expect, specify the `version` parameter. For example, to percolate the document only if it is still at version `1`, add `"version": 1` to the `percolate` query. If the document has been updated since then, the request fails with a `version_conflict_engine_exception` and a `409` status code. + +### Percolate multiple documents in separate clauses + +To percolate several documents with a separate `percolate` clause for each one, combine the clauses in a `bool` query and give each clause a `name`: + +```json +GET /my_percolator_index/_search +{ + "query": { + "bool": { + "should": [ + { + "percolate": { + "field": "query", + "document": { + "title": "Apple pie recipe" + }, + "name": "apple_doc" + } + }, + { + "percolate": { + "field": "query", + "document": { + "title": "Banana bread instructions" + }, + "name": "banana_doc" + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +OpenSearch appends each clause's `name` to the `_percolator_document_slot` field, so the field name shows which clause, and therefore which document, each saved query matched: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot_apple_doc": [ + 0 + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot_banana_doc": [ + 0 + ] + } + } + ] + } +} +``` + +If you omit `name` from multiple `percolate` clauses, OpenSearch appends the `field` value to the slot field name instead. In this example, both clauses would report matches in the same `_percolator_document_slot_query` field, so you couldn't tell which document each query matched. + +Because each document has its own clause, you can also weight documents differently. In the following example, each `percolate` clause is wrapped in a `constant_score` query that assigns a different `boost`, so matches for the second document score higher: + +```json +GET /my_percolator_index/_search +{ + "query": { + "bool": { + "should": [ + { + "constant_score": { + "filter": { + "percolate": { + "field": "query", + "document": { + "title": "Apple pie recipe" + }, + "name": "apple_doc" + } + }, + "boost": 1.0 + } + }, + { + "constant_score": { + "filter": { + "percolate": { + "field": "query", + "document": { + "title": "Banana bread with honey" + }, + "name": "banana_doc" + } + }, + "boost": 3.0 + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +The query that matches the second document receives the higher score: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 3.0, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 3.0, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot_banana_doc": [ + 0 + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 1.0, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot_apple_doc": [ + 0 + ] + } + } + ] + } +} +``` + + +## Batch percolation compared to separate clauses + +Both batch percolation (using `documents`) and separate clauses (using `bool` with a named `percolate` clause for each document) percolate multiple documents and return the same matches. The following table compares how each approach structures the request, identifies matched documents, and supports per-document scoring. + +| Feature | Batch (`documents`) | Separate clauses (`bool` + `percolate` + `name`) | +|-------------------------------|------------------------------------------------|--------------------------------------------------| +| Input format | One `percolate` clause containing an array of documents | One `percolate` clause per document | +| Document identification | By position in the `documents` array (`0`, `1`, ...) | By clause name (`apple_doc`, `banana_doc`) | +| Response field for match slot | `_percolator_document_slot: [0]` | `_percolator_document_slot_<name>: [0]` | +| Highlight prefix | `0_title`, `1_title` | `apple_doc_title`, `banana_doc_title` | +| Boosts | One boost for the whole clause, applied to all documents | A separate boost for each document's clause | +| Query parsing | Each saved query is parsed and matched once for all documents | Each clause matches its document separately | +| Use case | Bulk matching jobs, large event streams | Per-document tracing, testing, per-document weighting | + + +## Highlighting matches + +Highlights in a `percolate` response mark terms in the document you submitted. Each hit's highlight shows the terms that its saved query matched, so two saved queries that match the same document can highlight different parts of it. + +### Highlighting a single document + +This example uses the saved queries in `my_percolator_index`. Use the following request to highlight matches in the `title` field: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "document": { + "title": "Apple banana smoothie" + } + } + }, + "highlight": { + "fields": { + "title": {} + } + } +} +``` +{% include copy-curl.html %} + +Each hit highlights the terms that its saved query matched: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + }, + "highlight": { + "title": [ + "<em>Apple</em> banana smoothie" + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + }, + "highlight": { + "title": [ + "Apple <em>banana</em> smoothie" + ] + } + } + ] + } +} +``` + +### Highlighting multiple documents + +When percolating multiple documents using the `documents` array, the highlight keys take the following form, where `<slot>` is the document's position in the `documents` array, starting at `0`: + +```json +"<slot>_<fieldname>": [ ... ] +``` + +Use the following command to percolate two documents with highlighting: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "documents": [ + { "title": "Apple pie recipe" }, + { "title": "Banana smoothie ideas" } + ] + } + }, + "highlight": { + "fields": { + "title": {} + } + } +} +``` +{% include copy-curl.html %} + +The response contains highlighting fields prefixed with document slots, such as `0_title` and `1_title`: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.31506687, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.31506687, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + }, + "highlight": { + "0_title": [ + "<em>Apple</em> pie recipe" + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.31506687, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 1 + ] + }, + "highlight": { + "1_title": [ + "<em>Banana</em> smoothie ideas" + ] + } + } + ] + } +} +``` + +## Performance considerations + +When you index a saved query, OpenSearch extracts the query's terms and indexes them alongside the query. At search time, OpenSearch places the percolated document in a temporary in-memory index and uses the extracted terms to select candidate queries. Only these candidates are then run against the document, so most saved queries are never evaluated. + +Terms can't be extracted from some query types, such as `wildcard` and `geo_shape` queries. For a `bool` query, extraction fails if the unsupported query is the only `must` or `filter` clause, or if it is one of the `should` clauses in a query that has no `must` or `filter` clause. If another required clause, such as a `match` query in `must` or `filter`, has extractable terms, OpenSearch selects candidates using those terms instead. A saved query whose terms can't be extracted is evaluated against every percolated document, which slows down percolation as the number of such queries grows. These queries still match correctly. + +To find saved queries whose terms couldn't be extracted, search for the `failed` value in the `extraction_result` subfield of the `percolator` field. The following example adds a `wildcard` query and then searches for queries that failed term extraction: + +```json +POST /my_percolator_index/_doc/3?refresh=true +{ + "query": { + "wildcard": { + "title": "cher*" + } + } +} +``` +{% include copy-curl.html %} + +```json +GET /my_percolator_index/_search +{ + "query": { + "term": { + "query.extraction_result": "failed" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the `wildcard` query: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "3", + "_score": 1.0, + "_source": { + "query": { + "wildcard": { + "title": "cher*" + } + } + } + } + ] + } +} +``` + +Store saved queries and percolated documents in separate indexes, as the preceding examples do. Separate indexes provide the following advantages: + +- Documents in each index share the same fields, so OpenSearch stores them more compactly. +- You can configure the saved query index's settings, such as the number of primary shards, independently of the document index. This matters because percolation performance scales differently from regular search performance. + +## Parameters + +The `percolate` query supports the following parameters. Provide the document to percolate either inline (using `document` or `documents`) or by reference (using `index` and `id`). + +| Parameter | Required/Optional | Description | +|-----------|-------------------|-------------| +| `field` | Required | The `percolator` field containing the saved queries. | +| `document` | Optional | A single inline document to match against saved queries. | +| `documents` | Optional | An array of inline documents to match against saved queries. | +| `index` | Optional | The index containing the stored document to percolate. Required if `id` is specified. | +| `id` | Optional | The ID of the stored document to percolate. Required if `index` is specified. | +| `routing` | Optional | The routing value to use when fetching the stored document. | +| `preference` | Optional | The shard preference to use when fetching the stored document. | +| `version` | Optional | The expected version of the stored document. If the document's current version is different, the request fails with a version conflict error. | +| `name` | Optional | A name for the `percolate` clause. OpenSearch appends the name to the `_percolator_document_slot` field in the response. Use `name` to distinguish matches when a search contains multiple `percolate` clauses. | diff --git a/_query-dsl/specialized/rank-feature.md b/_query-dsl/specialized/rank-feature.md new file mode 100644 index 00000000..65f48482 --- /dev/null +++ b/_query-dsl/specialized/rank-feature.md @@ -0,0 +1,546 @@ +--- +layout: default +title: Rank feature +parent: Specialized queries +nav_order: 75 +--- + +# Rank feature + +Use the `rank_feature` query to boost document scores based on numeric values in a document, such as relevance scores, popularity, or freshness. This query is ideal if you want to fine-tune relevance ranking using numerical features. Unlike [full-text queries]({{site.url}}{{site.baseurl}}/query-dsl/full-text/index/), `rank_feature` focuses solely on a numeric signal; it is most effective when combined with other queries in a compound query like `bool`. + +The `rank_feature` query expects the target field to be mapped as a [`rank_feature` field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/rank/). This enables internally optimized scoring for fast and efficient boosting. + +The score impact depends on the field value and the optional `saturation`, `log`, or `sigmoid` function used. These functions are applied dynamically at query time to compute the final document score; they do not alter or store any values in the document itself. + +## Parameters + +The `rank_feature` query supports the following parameters. + +| Parameter | Data type | Required/Optional | Description | +| ----------------------- | --------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `field` | String | Required | A `rank_feature` or `rank_features` field that contributes to document scoring. | +| `boost` | Float | Optional | A multiplier applied to the score. Default is `1.0`. Values between 0 and 1 reduce the score; values above 1 amplify it. | +| `saturation` | Object | Optional | Applies a saturation function to the feature value. Boost grows with value but levels off beyond the `pivot`. Default function if no other function is provided. Only one function out of `saturation`, `log`, or `sigmoid` may be used at a time.| +| `log` | Object | Optional | Uses a logarithmic scoring function based on the field value. Best for large ranges of values. Only one function out of `saturation`, `log`, or `sigmoid` may be used at a time. | +| `sigmoid` | Object | Optional | Applies a sigmoid (S-shaped) curve to score impact, controlled by `pivot` and `exponent`. Only one function out of `saturation`, `log`, or `sigmoid` may be used at a time. | +| `positive_score_impact` | Boolean | Optional | When `false`, lower values score higher. Useful for features like price, for which smaller is better. Defined as part of the mapping. Default is `true`. | + +## Example + +The following examples demonstrate how to define and use a `rank_feature` field to influence document scoring. + +### Create an index with a rank feature field + +Define an index with a `rank_feature` field to represent a signal like `popularity`: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "popularity": { "type": "rank_feature" } + } + } +} +``` +{% include copy-curl.html %} + +### Index example documents + +Add sample products with varying popularity values: + +```json +POST /products/_bulk +{ "index": { "_id": 1 } } +{ "title": "Wireless Earbuds", "popularity": 1 } +{ "index": { "_id": 2 } } +{ "title": "Bluetooth Speaker", "popularity": 10 } +{ "index": { "_id": 3 } } +{ "title": "Portable Charger", "popularity": 25 } +{ "index": { "_id": 4 } } +{ "title": "Smartwatch", "popularity": 50 } +{ "index": { "_id": 5 } } +{ "title": "Noise Cancelling Headphones", "popularity": 100 } +{ "index": { "_id": 6 } } +{ "title": "Gaming Laptop", "popularity": 250 } +{ "index": { "_id": 7 } } +{ "title": "4K Monitor", "popularity": 500 } +``` +{% include copy-curl.html %} + +### Basic rank feature query + +You can boost results based on the `popularity` score using `rank_feature`: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity" + } + } +} +``` +{% include copy-curl.html %} + +This query alone does not perform filtering. Rather, it scores all documents based on the value of `popularity`. Higher values yield higher scores: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": 0.9252834, + "hits": [ + { + "_index": "products", + "_id": "7", + "_score": 0.9252834, + "_source": { + "title": "4K Monitor", + "popularity": 500 + } + }, + { + "_index": "products", + "_id": "6", + "_score": 0.86095566, + "_source": { + "title": "Gaming Laptop", + "popularity": 250 + } + }, + { + "_index": "products", + "_id": "5", + "_score": 0.71237755, + "_source": { + "title": "Noise Cancelling Headphones", + "popularity": 100 + } + }, + { + "_index": "products", + "_id": "4", + "_score": 0.5532503, + "_source": { + "title": "Smartwatch", + "popularity": 50 + } + }, + { + "_index": "products", + "_id": "3", + "_score": 0.38240916, + "_source": { + "title": "Portable Charger", + "popularity": 25 + } + }, + { + "_index": "products", + "_id": "2", + "_score": 0.19851118, + "_source": { + "title": "Bluetooth Speaker", + "popularity": 10 + } + }, + { + "_index": "products", + "_id": "1", + "_score": 0.024169207, + "_source": { + "title": "Wireless Earbuds", + "popularity": 1 + } + } + ] + } +} +``` + +### Combine with full-text search + +To filter relevant results and boost them based on popularity, use the following request. This query ranks all documents matching "headphones" and boosts those with higher popularity: + +```json +POST /products/_search +{ + "query": { + "bool": { + "must": { + "match": { + "title": "headphones" + } + }, + "should": { + "rank_feature": { + "field": "popularity" + } + } + } + } +} +``` +{% include copy-curl.html %} + + +### Boost parameter + +The `boost` parameter allows you to scale the score contribution of the rank_feature clause. It's especially useful in compound queries such as `bool`, where you want to control how much influence a numeric field (such as popularity, freshness, or relevance score) has on the final document ranking. + +In the following example, the `bool` query matches documents with the term "headphones" in the `title` and boosts more popular results using a `rank_feature` clause with a `boost` of `2.0`. This doubles the contribution of the `rank_feature` score to the overall document score: + +```json +POST /products/_search +{ + "query": { + "bool": { + "must": { + "match": { + "title": "headphones" + } + }, + "should": { + "rank_feature": { + "field": "popularity", + "boost": 2.0 + } + } + } + } +} +``` +{% include copy-curl.html %} + + +### Configure score function + +By default, the `rank_feature` query uses a `saturation` function with a `pivot` value derived from the field. You can explicitly set the function to `saturation`, `log` or `sigmoid`. + +#### Saturation function + +The `saturation` function is the default scoring method used in `rank_feature` queries. It assigns higher scores to documents with larger feature values, but the increase in score becomes more gradual as the value exceeds a specified `pivot`. This is useful when you want to give diminishing returns to very large values, for example, boosting `popularity` while avoiding over-rewarding extremely high numbers. The formula for calculating score is `value of the rank_feature field / (value of the rank_feature field + pivot)`. The produced score is always between `0` and `1`. If the `pivot` is not provided, the approximate geometric mean of all `rank_feature` values in the index is used. + +The following example uses `saturation` with a `pivot` of `50`: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity", + "saturation": { + "pivot": 50 + } + } + } +} +``` +{% include copy-curl.html %} + +The `pivot` defines the point at which the scoring growth slows down. Values higher than `pivot` still increase the score, but with diminishing returns, as can be seen in the returned hits: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": 0.9090909, + "hits": [ + { + "_index": "products", + "_id": "7", + "_score": 0.9090909, + "_source": { + "title": "4K Monitor", + "popularity": 500 + } + }, + { + "_index": "products", + "_id": "6", + "_score": 0.8333333, + "_source": { + "title": "Gaming Laptop", + "popularity": 250 + } + }, + { + "_index": "products", + "_id": "5", + "_score": 0.6666666, + "_source": { + "title": "Noise Cancelling Headphones", + "popularity": 100 + } + }, + { + "_index": "products", + "_id": "4", + "_score": 0.5, + "_source": { + "title": "Smartwatch", + "popularity": 50 + } + }, + { + "_index": "products", + "_id": "3", + "_score": 0.3333333, + "_source": { + "title": "Portable Charger", + "popularity": 25 + } + }, + { + "_index": "products", + "_id": "2", + "_score": 0.16666669, + "_source": { + "title": "Bluetooth Speaker", + "popularity": 10 + } + }, + { + "_index": "products", + "_id": "1", + "_score": 0.019607842, + "_source": { + "title": "Wireless Earbuds", + "popularity": 1 + } + } + ] + } +} +``` + +#### Log function + +The `log` function is helpful when the `rank_feature` field contains a significant range of values. It applies a logarithmic scale to the `score`, which reduces the effect of extremely high values and helps normalize scoring across wide value distributions. This is especially useful when a small difference between low values should be more impactful than a large difference between high values. The score is calculated using the formula `log(scaling_factor + rank_feature field)`. The following example uses a `scaling_factor` of `2`: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity", + "log": { + "scaling_factor": 2 + } + } + } +} +``` +{% include copy-curl.html %} + +In the example dataset, the `popularity` field ranges from `1` to `500`. The `log` function compresses the `score` contribution from large values like `250` and `500` while still allowing documents with `10` or `25` to have meaningful scores. In contrast, if you applied the `saturation` function, documents above the `pivot` would rapidly approach the same maximum score: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": 6.2186003, + "hits": [ + { + "_index": "products", + "_id": "7", + "_score": 6.2186003, + "_source": { + "title": "4K Monitor", + "popularity": 500 + } + }, + { + "_index": "products", + "_id": "6", + "_score": 5.529429, + "_source": { + "title": "Gaming Laptop", + "popularity": 250 + } + }, + { + "_index": "products", + "_id": "5", + "_score": 4.624973, + "_source": { + "title": "Noise Cancelling Headphones", + "popularity": 100 + } + }, + { + "_index": "products", + "_id": "4", + "_score": 3.9512436, + "_source": { + "title": "Smartwatch", + "popularity": 50 + } + }, + { + "_index": "products", + "_id": "3", + "_score": 3.295837, + "_source": { + "title": "Portable Charger", + "popularity": 25 + } + }, + { + "_index": "products", + "_id": "2", + "_score": 2.4849067, + "_source": { + "title": "Bluetooth Speaker", + "popularity": 10 + } + }, + { + "_index": "products", + "_id": "1", + "_score": 1.0986123, + "_source": { + "title": "Wireless Earbuds", + "popularity": 1 + } + } + ] + } +} +``` + +#### Sigmoid function + +The `sigmoid` function provides a smooth, S-shaped scoring curve, which is especially useful when you want to control the steepness and midpoint of the scoring impact. The score is derived using the formula `rank feature field value^exp / (rank feature field value^exp + pivot^exp)`. The following example uses a `sigmoid` function with a configured `pivot` and `exponent`. The `pivot` defines the value at which the score is 0.5. The `exponent` controls how steep the curve is. Lower values result in a sharper transition around the `pivot`: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity", + "sigmoid": { + "pivot": 50, + "exponent": 0.5 + } + } + } +} +``` +{% include copy-curl.html %} + + +The `sigmoid` function smoothly boosts scores around the `pivot` (in this example,`50`), giving moderate preference to values near the `pivot` while flattening out both high and low extremes: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": 0.7597469, + "hits": [ + { + "_index": "products", + "_id": "7", + "_score": 0.7597469, + "_source": { + "title": "4K Monitor", + "popularity": 500 + } + }, + { + "_index": "products", + "_id": "6", + "_score": 0.690983, + "_source": { + "title": "Gaming Laptop", + "popularity": 250 + } + }, + { + "_index": "products", + "_id": "5", + "_score": 0.58578646, + "_source": { + "title": "Noise Cancelling Headphones", + "popularity": 100 + } + }, + { + "_index": "products", + "_id": "4", + "_score": 0.5, + "_source": { + "title": "Smartwatch", + "popularity": 50 + } + }, + { + "_index": "products", + "_id": "3", + "_score": 0.41421357, + "_source": { + "title": "Portable Charger", + "popularity": 25 + } + }, + { + "_index": "products", + "_id": "2", + "_score": 0.309017, + "_source": { + "title": "Bluetooth Speaker", + "popularity": 10 + } + }, + { + "_index": "products", + "_id": "1", + "_score": 0.12389934, + "_source": { + "title": "Wireless Earbuds", + "popularity": 1 + } + } + ] + } +} +``` + +#### Invert score impact + +By default, higher values lead to higher scores. If you want lower values to yield higher scores (for example, lower prices are more relevant), set `positive_score_impact` to `false` during index creation: + +```json +PUT /products_new +{ + "mappings": { + "properties": { + "popularity": { + "type": "rank_feature", + "positive_score_impact": false + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_query-dsl/specialized/script-score.md b/_query-dsl/specialized/script-score.md index d09158f2..92341389 100644 --- a/_query-dsl/specialized/script-score.md +++ b/_query-dsl/specialized/script-score.md @@ -2,17 +2,23 @@ layout: default title: Script score parent: Specialized queries -grand_parent: Query DSL nav_order: 60 --- # Script score query -Use a `script_score` query to customize the score calculation by using a script. For an expensive scoring function, you can use a `script_score` query to calculate the score only for the returned documents that have been filtered. +Use a `script_score` query to replace the relevance score of each matching document with a value computed by a script. The wrapped query determines which documents match, and the script runs only on those documents. This makes the `script_score` query a good fit for scoring logic that is too expensive to run against the whole index. + +Use a `script_score` query in the following scenarios: + +- Combining text relevance with a numeric signal stored in the document, such as popularity, rating, or rank. +- Favoring documents whose dates, locations, or numeric values are close to a target value by using a decay function. +- Implementing a custom ranking formula based on term statistics or vector similarity. +- Reproducing the scoring functions of a [`function_score`]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score/) query in a single script. ## Example -For example, the following request creates an index containing one document: +The following request creates an index containing one document: ```json PUT testindex1/_doc/1 @@ -23,7 +29,7 @@ PUT testindex1/_doc/1 ``` {% include copy-curl.html %} -You can use a `match` query to return all documents that contain `John` in the `name` field: +The following `match` query returns all documents that contain `John` in the `name` field: ```json GET testindex1/_search @@ -37,11 +43,11 @@ GET testindex1/_search ``` {% include copy-curl.html %} -In the response, document 1 has a score of `0.2876821`: +In the response, document 1 has a score of `0.13076457`: ```json { - "took": 7, + "took": 1, "timed_out": false, "_shards": { "total": 1, @@ -54,12 +60,12 @@ In the response, document 1 has a score of `0.2876821`: "value": 1, "relation": "eq" }, - "max_score": 0.2876821, + "max_score": 0.13076457, "hits": [ { "_index": "testindex1", "_id": "1", - "_score": 0.2876821, + "_score": 0.13076457, "_source": { "name": "John Doe", "multiplier": 0.5 @@ -70,7 +76,7 @@ In the response, document 1 has a score of `0.2876821`: } ``` -Now let's change the document score by using a script that calculates the score as the value of the `_score` field multiplied by the value of the `multiplier` field. In the following query, you can access the current relevance score of a document in the `_score` variable and the `multiplier` value as `doc['multiplier'].value`: +To change the document score, wrap the `match` query in a `script_score` query. Inside the script, the `_score` variable holds the relevance score calculated by the wrapped query, and `doc['multiplier'].value` reads the `multiplier` field value. The following query multiplies the two values: ```json GET testindex1/_search @@ -95,7 +101,7 @@ In the response, the score for document 1 is half of the original score: ```json { - "took": 8, + "took": 2, "timed_out": false, "_shards": { "total": 1, @@ -108,12 +114,12 @@ In the response, the score for document 1 is half of the original score: "value": 1, "relation": "eq" }, - "max_score": 0.14384104, + "max_score": 0.06538229, "hits": [ { "_index": "testindex1", "_id": "1", - "_score": 0.14384104, + "_score": 0.06538229, "_source": { "name": "John Doe", "multiplier": 0.5 @@ -130,17 +136,23 @@ The `script_score` query supports the following top-level parameters. Parameter | Data type | Description :--- | :--- | :--- -`query` | Object | The query used for search. Required. -`script` | Object | The script used to calculate the score of the documents returned by the `query`. Required. -`min_score` | Float | Excludes documents with a score lower than `min_score` from the results. Optional. -`boost` | Float | Boosts the documents' scores by the given multiplier. Values less than 1.0 decrease relevance, and values greater than 1.0 increase relevance. Default is 1.0. +`query` | Object | The query that selects the documents to score. Required. +`script` | Object | The script used to calculate the score of the documents returned by the `query`. Supports inline and stored scripts. For more information, see [How to use scripts]({{site.url}}{{site.baseurl}}/scripting/using-scripts/). Required. +`min_score` | Float | Excludes documents with a score lower than `min_score` from the results. The score is compared to `min_score` after `boost` is applied. Optional. +`boost` | Float | Multiplies the score returned by the script. Values less than 1.0 decrease relevance, and values greater than 1.0 increase relevance. Default is 1.0. -The relevance scores calculated by the `script_score` query cannot be negative. +Pass changing values to the script in the `params` object and keep them out of `source`. OpenSearch caches compiled scripts by their source, so a script whose source stays the same is compiled only once, even when its parameter values change. For more information, see [Compilation limits and caching]({{site.url}}{{site.baseurl}}/scripting/using-scripts/#compilation-limits-and-caching). + +The relevance scores calculated by the `script_score` query cannot be negative. If a script returns a negative value, the search fails with an error similar to `script_score script returned an invalid score [-1.0] for doc [0]. Must be a non-negative score!`. {: .important} +If a script reads a field that is missing from a document, `doc['<field>'].value` throws an error. To handle missing values, check `doc['<field>'].size() == 0` before reading the value. For an example, see [The field value factor function](#the-field-value-factor-function). + ## Customizing score calculation with built-in functions -To customize score calculation, you can use one of the built-in Painless functions. For every function, OpenSearch provides one or more Painless methods you can access in the script score context. You can call the Painless methods listed in the following sections directly without using a class name or instance name qualifier. +To customize score calculation, you can use one of the built-in Painless functions. For every function, OpenSearch provides one or more Painless methods you can access in the script score context. You can call the Painless methods listed in the following sections directly without using a class name or instance name qualifier. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +When a built-in function covers your use case, prefer it to an equivalent formula written in Painless. The built-in functions are implemented in Java, and the decay functions parse their origin, scale, and offset once and do not repeat this work for every document. ### Saturation @@ -200,8 +212,14 @@ GET articles/_search The random score function generates uniformly distributed random scores in the [0, 1) range. To learn how the function works, see [The random score function]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score#the-random-score-function). To apply a random score function, call one of the following Painless methods: -- `double randomScore(int <seed>)`: Uses the internal Lucene document IDs as seed values. -- `double randomScore(int <seed>, String <field-name>)` +- `double randomScore(int <seed>)`: Uses the internal Lucene document IDs as the source of randomness. +- `double randomScore(int <seed>, String <field-name>)`: Uses the values of the specified field as the source of randomness. + +Choose the source of randomness based on the following considerations: + +- Internal Lucene document IDs are fast to read, but segment merges can renumber them. As a result, the same seed can produce a different order over time. +- Documents in the same shard that have the same field value receive the same score, so choose a field whose values are unique within each shard. +- The `_seq_no` field is unique within a shard, but its value changes each time a document is updated. An updated document therefore receives a new random score. #### Example @@ -228,15 +246,15 @@ GET articles/_search With decay functions, you can score results based on proximity or recency. To learn more, see [Decay functions]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score#decay-functions). You can calculate scores using an exponential, Gaussian, or linear decay curve. To apply a decay function, call one of the following Painless methods, depending on the field type: -- [Numeric]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/numeric/) fields: +- [Numeric]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/numeric/) fields: - `double decayNumericGauss(double <origin>, double <scale>, double <offset>, double <decay>, double <field-value>)` - `double decayNumericExp(double <origin>, double <scale>, double <offset>, double <decay>, double <field-value>)` - `double decayNumericLinear(double <origin>, double <scale>, double <offset>, double <decay>, double <field-value>)` -- [Geopoint]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/geo-point/) fields: +- [Geopoint]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/) fields: - `double decayGeoGauss(String <origin>, String <scale>, String <offset>, double <decay>, GeoPoint <field-value>)` - `double decayGeoExp(String <origin>, String <scale>, String <offset>, double <decay>, GeoPoint <field-value>)` - `double decayGeoLinear(String <origin>, String <scale>, String <offset>, double <decay>, GeoPoint <field-value>)` -- [Date]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/date/) fields: +- [Date]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/) fields: - `double decayDateGauss(String <origin>, String <scale>, String <offset>, double <decay>, JodaCompatibleZonedDateTime <field-value>)` - `double decayDateExp(String <origin>, String <scale>, String <offset>, double <decay>, JodaCompatibleZonedDateTime <field-value>)` - `double decayDateLinear(String <origin>, String <scale>, String <offset>, double <decay>, JodaCompatibleZonedDateTime <field-value>)` @@ -328,44 +346,50 @@ GET blogs/_search ``` {% include copy-curl.html %} +The date decay functions have the following limitations: + +- The origin must be a fixed date. Date math expressions that use `now` are not supported and cause the search to fail with a `could not read the current timestamp` error. To score by recency, calculate the current date in your application and pass it in `params.origin`. +- The origin must use the default `strict_date_optional_time||epoch_millis` format, even if the date field is mapped using a custom `format`. An origin without a time zone offset is interpreted as UTC. + +### Vector functions + +The k-NN plugin provides Painless functions that calculate the distance or similarity between a query vector and a vector field, such as `l2Squared`, `cosineSimilarity`, and `hamming`. Use these functions in a `script_score` query to run an exact k-NN search on the documents returned by the wrapped query. For more information, see [Painless extensions]({{site.url}}{{site.baseurl}}/vector-search/vector-search-techniques/painless-functions/). + ### Term frequency functions Term frequency functions expose term-level statistics in the score script source. You can use these statistics to implement custom information retrieval and ranking algorithms, like query-time multiplicative or additive score boosting by popularity. To apply a term frequency function, call one of the following Painless methods: -- `int termFreq(String <field-name>, String <term>)`: Retrieves the term frequency within a field for a specific term. -- `long totalTermFreq(String <field-name>, String <term>)`: Retrieves the total term frequency within a field for a specific term. -- `long sumTotalTermFreq(String <field-name>)`: Retrieves the sum of total term frequencies within a field. +- `int termFreq(String <field-name>, String <term>)`: Retrieves the number of times the term appears in the field of the current document. +- `long totalTermFreq(String <field-name>, String <term>)`: Retrieves the number of times the term appears in the field across all documents in the shard. This value is the same for every document in the shard. +- `long sumTotalTermFreq(String <field-name>)`: Retrieves the total number of terms in the field across all documents in the shard. This value is the same for every document in the shard. #### Example -The following query calculates the score as the total term frequency for each field in the `fields` list multiplied by the `multiplier` value: +The following query iterates through the `fields` list and finds the first field name that is not `null`. It then calculates the score as the total term frequency of the term `ai` in that field multiplied by the `multiplier` value. If no field name is found, the script returns `default_value`: ```json GET /demo_index_v1/_search { "query": { - "function_score": { + "script_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); - } + "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 } + return params.default_value; + """, + "params": { + "fields": ["title", "description"], + "term": "ai", + "multiplier": 2, + "default_value": 1 } } } @@ -374,5 +398,202 @@ GET /demo_index_v1/_search ``` {% include copy-curl.html %} +### Late interaction score + +The `lateInteractionScore` function is a Painless script scoring function that calculates document relevance using token-level vector matching. It compares each query vector against all document vectors, finds the maximum similarity for each query vector, and sums these maximum scores to produce the final document score. + +**Example score calculation**: +- Query vectors: `[[0.8, 0.1], [0.2, 0.9]]` +- Document vectors: `[[0.7, 0.2], [0.1, 0.8], [0.3, 0.4]]` +- Query vector 1 → finds best match among document vectors → score A +- Query vector 2 → finds best match among document vectors → score B +- Final score = A + B + +This approach enables fine-grained semantic matching between queries and documents, making it particularly effective for reranking search results. + +#### Index mapping requirements + +The vector field must be mapped as either an `object` (recommended) or `float` type. + +We recommend mapping the vector field as an `object` with `"enabled": false` because it stores raw vectors without parsing, improving performance: + +```json +{ + "mappings": { + "properties": { + "my_vector": { + "type": "object", + "enabled": false + } + } + } +} +``` + +Alternatively, you can map the vector field as a `float`: + +```json +{ + "mappings": { + "properties": { + "my_vector": { + "type": "float" + } + } + } +} +``` + +#### Example + +The following example demonstrates using the `lateInteractionScore` function with cosine similarity to measure vector similarity based on direction rather than distance: + +```json +GET my_index/_search +{ + "query": { + "script_score": { + "query": { "match_all": {} }, + "script": { + "source": "lateInteractionScore(params.query_vectors, 'my_vector', params._source, params.space_type)", + "params": { + "query_vectors": [[1.0, 0.0], [0.0, 1.0]], + "space_type": "cosinesimil" + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Parameters + +The `lateInteractionScore` function supports the following parameters. + +| Parameter | Data type | Required | Description | +| :--- | :--- | :--- | :--- | +| `query_vectors` | Array of arrays | Yes | Query vectors for similarity matching. | +| `vector_field` | String | Yes | The name of the document field containing vectors. | +| `doc` | Map | Yes | Document source (use `params._source`). | +| `space_type` | String | No | The similarity metric. Default is `l2`. | + +The `space_type` parameter determines how similarity is calculated and accepts the following valid values. + +| Space type | Description | Higher score means | +| :--- | :--- | :--- | +| `innerproduct` | Dot product | More similar vectors | +| `cosinesimil` | Cosine similarity | More similar direction | +| `l2` (default) | Euclidean distance | Closer vectors (inverted) | + +For a complete example, see [Reranking by a field using an externally hosted late interaction model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-late-interaction/). + +## Replicating function score functions + +Each scoring function of the [`function_score`]({{site.url}}{{site.baseurl}}/query-dsl/compound/function-score/) query has a `script_score` equivalent. Use the following mappings when you need to combine several of these functions in one formula: + +- `script_score`: Copy the script from the `script_score` function into the `script` parameter of the `script_score` query without changes. +- `weight`: Multiply the relevance score by a constant, for example, `params.weight * _score`. +- `random_score`: Call the [`randomScore` function](#random-score). +- `field_value_factor`: Read the field value and apply the factor and modifier in Painless. For more information, see [The field value factor function](#the-field-value-factor-function). +- Decay functions: Call the corresponding [decay function](#decay-functions). + +### The field value factor function + +The following query reproduces a `field_value_factor` function that has a `factor` of `5`, a `log` modifier, and a `missing` value of `1`. For documents that have no `likes` value, the script uses `1`: + +```json +GET articles/_search +{ + "query": { + "script_score": { + "query": { + "match": { + "article_name": "neural search" + } + }, + "script": { + "source": "Math.log10((doc['likes'].size() == 0 ? 1 : doc['likes'].value) * params.factor)", + "params": { + "factor": 5 + } + } + } + } +} +``` +{% include copy-curl.html %} + +The `field_value_factor` function multiplies the field value by `factor` and then applies the modifier. The following table lists the Painless expression that corresponds to each modifier, where `v` is `params.factor * doc['<field>'].value`. + +Modifier | Painless expression +:--- | :--- +`none` | `v` +`log` | `Math.log10(v)` +`log1p` | `Math.log10(v + 1)` +`log2p` | `Math.log10(v + 2)` +`ln` | `Math.log(v)` +`ln1p` | `Math.log(v + 1)` +`ln2p` | `Math.log(v + 2)` +`square` | `Math.pow(v, 2)` +`sqrt` | `Math.sqrt(v)` +`reciprocal` | `1.0 / v` + +## Explaining script scores + +The [Explain API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/explain/) shows how the score of a document was calculated. By default, the explanation for a `script_score` query contains only the script source. To add a readable description of the calculation, call `explanation.set()` in the script. + +The `explanation` variable is set only in an explain request. In a regular search request, it is `null`, and calling `explanation.set()` causes the search to fail. Always check for `null` before calling `explanation.set()`. + +The following request explains the score of article 1: + +```json +GET articles/_explain/1 +{ + "query": { + "script_score": { + "query": { + "match": { + "article_name": "neural search" + } + }, + "script": { + "source": """ + long likes = doc['likes'].value; + double normalizedLikes = likes / 10.0; + if (explanation != null) { + explanation.set('normalized likes = likes / 10 = ' + likes + ' / 10 = ' + normalizedLikes); + } + return normalizedLikes; + """ + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the description set by the script: + +```json +{ + "_index" : "articles", + "_id" : "1", + "matched" : true, + "explanation" : { + "value" : 12.0, + "description" : "normalized likes = likes / 10 = 120 / 10 = 12.0", + "details" : [ ] + } +} +``` + +## Faster alternatives + +The `script_score` query runs its script for every document that matches the wrapped query. The following queries can skip documents that cannot reach the top results, so they are faster for common boosting tasks: + +- To boost documents based on a static numeric value, such as popularity or page rank, use the [`rank_feature`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/rank-feature/) query. +- To boost documents that are close to a date or geographic point, use the [`distance_feature`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/distance-feature/) query. + If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, `script_score` queries are not executed. {: .important} \ No newline at end of file diff --git a/_query-dsl/specialized/script.md b/_query-dsl/specialized/script.md new file mode 100644 index 00000000..4a45fb4b --- /dev/null +++ b/_query-dsl/specialized/script.md @@ -0,0 +1,218 @@ +--- +layout: default +title: Script query +parent: Specialized queries +nav_order: 58 +--- + +# Script query + +Use the `script` query to filter documents based on a custom condition written in the Painless scripting language. This query returns documents for which the script evaluates to `true`, enabling advanced filtering logic that can't be expressed using standard queries. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). + +The `script` query is computationally expensive and should be used sparingly. Only use it when necessary and ensure `search.allow_expensive_queries` is enabled (default is `true`). For more information, see [Expensive queries]({{site.url}}{{site.baseurl}}/query-dsl/#expensive-queries). +{: .important } + +## Example + +Create an index named `products` with the following mappings: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "price": { "type": "float" }, + "rating": { "type": "float" } + } + } +} +``` +{% include copy-curl.html %} + +Index example documents using the following request: + +```json +POST /products/_bulk +{ "index": { "_id": 1 } } +{ "title": "Wireless Earbuds", "price": 99.99, "rating": 4.5 } +{ "index": { "_id": 2 } } +{ "title": "Bluetooth Speaker", "price": 79.99, "rating": 4.8 } +{ "index": { "_id": 3 } } +{ "title": "Noise Cancelling Headphones", "price": 199.99, "rating": 4.7 } +``` +{% include copy-curl.html %} + +## Basic script query + +Return products with a rating higher than `4.6`: + +```json +POST /products/_search +{ + "query": { + "script": { + "script": { + "source": "doc['rating'].value > 4.6" + } + } + } +} +``` +{% include copy-curl.html %} + +The returned hits only include documents with a `rating` higher than `4.6`: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "products", + "_id": "2", + "_score": 1, + "_source": { + "title": "Bluetooth Speaker", + "price": 79.99, + "rating": 4.8 + } + }, + { + "_index": "products", + "_id": "3", + "_score": 1, + "_source": { + "title": "Noise Cancelling Headphones", + "price": 199.99, + "rating": 4.7 + } + } + ] + } +} +``` + +## Parameters + +The `script` query takes the following top-level parameters. + +| Parameter | Required/Optional | Description | +| --------------- | ----------------- | ----------------------------------------------------- | +| `script.source` | Required | The script code that evaluates to `true` or `false`. | +| `script.params` | Optional | User-defined parameters referenced inside the script. | + +## Using script parameters + +You can use `params` to safely inject values, taking advantage of script compilation caching: + +```json +POST /products/_search +{ + "query": { + "script": { + "script": { + "source": "doc['price'].value < params.max_price", + "params": { + "max_price": 100 + } + } + } + } +} +``` +{% include copy-curl.html %} + +The returned hits only include documents with a `price` of less than `100`: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "products", + "_id": "1", + "_score": 1, + "_source": { + "title": "Wireless Earbuds", + "price": 99.99, + "rating": 4.5 + } + }, + { + "_index": "products", + "_id": "2", + "_score": 1, + "_source": { + "title": "Bluetooth Speaker", + "price": 79.99, + "rating": 4.8 + } + } + ] + } +} +``` + +## Combining multiple conditions + +Use the following query to search for products with a `rating` higher than `4.5` and a `price` lower than `100`: + +```json +POST /products/_search +{ + "query": { + "script": { + "script": { + "source": "doc['rating'].value > 4.5 && doc['price'].value < 100" + } + } + } +} +``` +{% include copy-curl.html %} + +Only the documents that match the requirements are returned: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "products", + "_id": "2", + "_score": 1, + "_source": { + "title": "Bluetooth Speaker", + "price": 79.99, + "rating": 4.8 + } + } + ] + } +} +``` diff --git a/_query-dsl/specialized/template.md b/_query-dsl/specialized/template.md new file mode 100644 index 00000000..7a6eb588 --- /dev/null +++ b/_query-dsl/specialized/template.md @@ -0,0 +1,104 @@ +--- +layout: default +title: Template +parent: AI and vector search queries +nav_order: 70 +--- + +# Template query +Introduced 2.19 +{: .label .label-purple } + +Use a `template` query to create search queries that contain placeholder variables. Placeholders are specified using the `"${variable_name}"` syntax (note that the variables must be enclosed in quotation marks). When you submit a search request, these placeholders remain unresolved until they are processed by search request processors. This approach is particularly useful when your initial search request contains data that needs to be transformed or generated at runtime. + +For example, you might use a template query when working with the [ml_inference search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-request/), which converts text input into vector embeddings during the search process. The processor will replace the placeholders with the generated values before the final query is executed. + +For a complete example, see [Query rewriting using template queries]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/template-query/). + +This page documents the `template` query, which uses placeholder variables resolved by search request processors (such as ML inference) at runtime. If you want to create reusable, parameterized queries using Mustache syntax (`{{variable}}`), see [Search Template API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/). +{: .note} + +## Example + +The following example shows a template k-NN query with a `"vector": "${text_embedding}"` placeholder. The placeholder `"${text_embedding}"` will be replaced with embeddings generated by the `ml_inference` search request processor from the `text` input field: + +```json +GET /template-knn-index/_search?search_pipeline=my_knn_pipeline +{ + "query": { + "template": { + "knn": { + "text_embedding": { + "vector": "${text_embedding}", // Placeholder for the vector field + "k": 2 + } + } + } + }, + "ext": { + "ml_inference": { + "text": "sneakers" // Input text for the ml_inference processor + } + } +} +``` +{% include copy-curl.html %} + +To use a template query with a search request processor, you need to configure a search pipeline. The following is an example configuration for the `ml_inference` search request processor. The `input_map` maps document fields to model inputs. In this example, the `ext.ml_inference.text` source field in a document is mapped to the `inputText` field---the expected input field for the model. The `output_map` maps model outputs to document fields. In this example, the `embedding` output field from the model is mapped to the `text_embedding` destination field in your document: + +```json +PUT /_search/pipeline/my_knn_pipeline +{ + "request_processors": [ + { + "ml_inference": { + "model_id": "Sz-wFZQBUpPSu0bsJTBG", + "input_map": [ + { + "inputText": "ext.ml_inference.text" // Map input text from the request + } + ], + "output_map": [ + { + "text_embedding": "embedding" // Map output to the placeholder + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +After the `ml_inference` search request processor runs, the search request is rewritten. The `vector` field contains the embeddings generated by the processor, and the `text_embedding` field contains the processor output: + +```json +GET /template-knn-1/_search +{ + "query": { + "template": { + "knn": { + "text_embedding": { + "vector": [0.6328125, 0.26953125, ...], + "k": 2 + } + } + } + }, + "ext": { + "ml_inference": { + "text": "sneakers", + "text_embedding": [0.6328125, 0.26953125, ...] + } + } +} +``` +{% include copy-curl.html %} + +## Limitations + +Template queries require at least one search request processor in order to resolve placeholders. Search request processors must be configured to produce the variables expected in the pipeline. + +## Next steps + +- For a complete example, see [Template queries]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/template-query/). \ No newline at end of file diff --git a/_query-dsl/specialized/wrapper.md b/_query-dsl/specialized/wrapper.md new file mode 100644 index 00000000..95f2b394 --- /dev/null +++ b/_query-dsl/specialized/wrapper.md @@ -0,0 +1,96 @@ +--- + +layout: default +title: Wrapper +parent: Specialized queries +nav_order: 80 +--- + +# Wrapper query + +The `wrapper` query lets you submit a complete query in Base64-encoded JSON format. It is useful when the query must be embedded in contexts that only support string values. + +Use this query only when you need to manage system constraints. For readability and maintainability, it's better to use standard JSON-based queries when possible. + +## Example + +Create an index named `products` with the following mappings: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { "type": "text" } + } + } +} +``` +{% include copy-curl.html %} + +Index sample documents: + +```json +POST /products/_bulk +{ "index": { "_id": 1 } } +{ "title": "Wireless headphones with noise cancellation" } +{ "index": { "_id": 2 } } +{ "title": "Bluetooth speaker" } +{ "index": { "_id": 3 } } +{ "title": "Over-ear headphones with rich bass" } +``` +{% include copy-curl.html %} + +Encode the following query in Base64 format: + +```bash +echo -n '{ "match": { "title": "headphones" } }' | base64 +``` +{% include copy.html %} + +Execute the encoded query: + +```json +POST /products/_search +{ + "query": { + "wrapper": { + "query": "eyAibWF0Y2giOiB7ICJ0aXRsZSI6ICJoZWFkcGhvbmVzIiB9IH0=" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the two matching documents: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.20098841, + "hits": [ + { + "_index": "products", + "_id": "1", + "_score": 0.20098841, + "_source": { + "title": "Wireless headphones with noise cancellation" + } + }, + { + "_index": "products", + "_id": "3", + "_score": 0.18459359, + "_source": { + "title": "Over-ear headphones with rich bass" + } + } + ] + } +} +``` diff --git a/_query-dsl/term-vs-full-text.md b/_query-dsl/term-vs-full-text.md index e5019c4e..42ef7578 100644 --- a/_query-dsl/term-vs-full-text.md +++ b/_query-dsl/term-vs-full-text.md @@ -3,7 +3,8 @@ layout: default title: Term-level and full-text queries compared nav_order: 10 redirect_from: -- /query-dsl/query-dsl/term-vs-full-text + - /query-dsl/query-dsl/term-vs-full-text/ + - /opensearch/query-dsl/term-vs-full-text/ --- # Term-level and full-text queries compared @@ -14,13 +15,13 @@ You can use both term-level and full-text queries to search text, but while term :--- | :--- | :--- *Description* | Term-level queries answer which documents match a query. | Full-text queries answer how well the documents match a query. *Analyzer* | The search term isn't analyzed. This means that the term query searches for your search term as it is. | The search term is analyzed by the same analyzer that was used for the specific document field at the time it was indexed. This means that your search term goes through the same analysis process as the document's field. -*Relevance* | Term-level queries simply return documents that match without sorting them based on the relevance score. They still calculate the relevance score, but this score is the same for all the documents that are returned. | Full-text queries calculate a relevance score for each match and sort the results by decreasing order of relevance. +*Relevance* | Term-level queries return documents that match without sorting them based on the relevance score. They still calculate the relevance score, but this score is the same for all the documents that are returned. | Full-text queries calculate a relevance score for each match and sort the results by decreasing order of relevance. *Use Case* | Use term-level queries when you want to match exact values such as numbers, dates, or tags and don't need the matches to be sorted by relevance. | Use full-text queries to match text fields and sort by relevance after taking into account factors like casing and stemming variants. OpenSearch uses the BM25 ranking algorithm to calculate relevance scores. To learn more, see [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25). {: .note } -## Should I use a full-text or a term-level query? +## Should I use a full-text or a term-level query To clarify the difference between full-text and term-level queries, consider the following two examples that search for a specific text phrase. The complete works of Shakespeare are indexed in an OpenSearch cluster. @@ -79,7 +80,7 @@ GET shakespeare/_search } ``` -The search query “To be, or not to be” is analyzed and tokenized into an array of tokens just like the `text_entry` field of the documents. The full-text query takes an intersection of tokens between the search query and the `text_entry` fields for all the documents, and then sorts the results by relevance score: +The search query “To be, or not to be” is analyzed and tokenized into an array of tokens, the same as the `text_entry` field of the documents. The full-text query takes an intersection of tokens between the search query and the `text_entry` fields for all the documents and then sorts the results by relevance score: ```json { @@ -146,7 +147,7 @@ The search query “To be, or not to be” is analyzed and tokenized into an arr ... ``` -For a list of all full-text queries, see [Full-text queries]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/full-text/index). +For a list of all full-text queries, see [Full-text queries]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/full-text/index/). ### Example: Exact term search diff --git a/_query-dsl/term/exists.md b/_query-dsl/term/exists.md index a62dda98..d97590eb 100644 --- a/_query-dsl/term/exists.md +++ b/_query-dsl/term/exists.md @@ -2,8 +2,7 @@ layout: default title: Exists parent: Term-level queries -grand_parent: Query DSL -nav_order: 10 +nav_order: 70 --- # Exists query @@ -146,4 +145,8 @@ The response contains the matching document: ## Parameters -The query accepts the name of the field (`<field>`) as a top-level parameter. \ No newline at end of file +The query accepts the name of the field (`<field>`) as a top-level parameter. + +Parameter | Data type | Description +:--- | :--- | :--- +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. diff --git a/_query-dsl/term/fuzzy.md b/_query-dsl/term/fuzzy.md index f5a9773a..933b96a8 100644 --- a/_query-dsl/term/fuzzy.md +++ b/_query-dsl/term/fuzzy.md @@ -2,20 +2,19 @@ layout: default title: Fuzzy parent: Term-level queries -grand_parent: Query DSL -nav_order: 20 +nav_order: 80 --- # Fuzzy query -A fuzzy query searches for documents containing terms that are similar to the search term within the maximum allowed [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). The Levenshtein distance measures the number of one-character changes needed to change one term to another term. These changes include: +A fuzzy query searches for documents containing terms that are similar to the search term within the maximum allowed [Damerau–Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance). The Damerau–Levenshtein distance measures the number of one-character changes needed to change one term to another term. These changes include: - Replacements: **c**at to **b**at - Insertions: cat to cat**s** - Deletions: **c**at to at - Transpositions: **ca**t to **ac**t -A fuzzy query creates a list of all possible expansions of the search term that fall within the Levenshtein distance. You can specify the maximum number of such expansions in the `max_expansions` field. Then it searches for documents that match any of the expansions. +A fuzzy query creates a list of all possible expansions of the search term that fall within the Damerau-Levenshtein distance. You can specify the maximum number of such expansions in the `max_expansions` field. The query then searches for documents that match any of the expansions. If you set the `transpositions` parameter to `false`, then your search will use the classic [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). The following example query searches for the speaker `HALET` (misspelled `HAMLET`). The maximum edit distance is not specified, so the default `AUTO` edit distance is used: @@ -67,7 +66,7 @@ GET _search "fuzzy": { "<field>": { "value": "sample", - ... + ... } } } @@ -80,14 +79,15 @@ The `<field>` accepts the following parameters. All parameters except `value` ar Parameter | Data type | Description :--- | :--- | :--- `value` | String | The term to search for in the field specified in `<field>`. -`fuzziness` | `AUTO`, `0`, or a positive integer | The number of character edits (insert, delete, substitute) needed to change one word to another when determining whether a term matched a value. For example, the distance between `wined` and `wind` is 1. The default, `AUTO`, chooses a value based on the length of each term and is a good choice for most use cases. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. +`fuzziness` | `AUTO`, `0`, or a positive integer | The maximum number of edits allowed when matching the term, specified as `0`, `1`, `2`, `AUTO`, or `AUTO:<low>,<high>`. Default is `AUTO`. For more information, see [Fuzziness]({{site.url}}{{site.baseurl}}/query-dsl/fuzziness/). `max_expansions` | Positive integer | The maximum number of terms to which the query can expand. Fuzzy queries “expand to” a number of matching terms that are within the distance specified in `fuzziness`. Then OpenSearch tries to match those terms. Default is `50`. `prefix_length` | Non-negative integer | The number of leading characters that are not considered in fuzziness. Default is `0`. `rewrite` | String | Determines how OpenSearch rewrites and scores multi-term queries. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. Default is `constant_score`. -`transpositions` | Boolean | Specifies whether to allow transpositions of two adjacent characters (`ab` to `ba`) as edits. Default is `true`. +`transpositions` | Boolean | Specifies whether to allow transpositions of two adjacent characters (`ab` to `ba`) as edits. Default is `true`. Specifying a large value in `max_expansions` can lead to poor performance, especially if `prefix_length` is set to `0`, because of the large number of variations of the word that OpenSearch tries to match. {: .warning} -If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, fuzzy queries are not run. -{: .important} \ No newline at end of file +If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, then fuzzy queries are not executed. +{: .important} diff --git a/_query-dsl/term/ids.md b/_query-dsl/term/ids.md index a1a098f5..6182d58d 100644 --- a/_query-dsl/term/ids.md +++ b/_query-dsl/term/ids.md @@ -2,8 +2,7 @@ layout: default title: IDs parent: Term-level queries -grand_parent: Query DSL -nav_order: 30 +nav_order: 40 --- # IDs query @@ -32,3 +31,4 @@ The query accepts the following parameter. Parameter | Data type | Description :--- | :--- | :--- `values` | Array of strings | The document IDs to search for. Required. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. diff --git a/_query-dsl/term/index.md b/_query-dsl/term/index.md index 594ece3f..a4e0de6b 100644 --- a/_query-dsl/term/index.md +++ b/_query-dsl/term/index.md @@ -3,7 +3,10 @@ layout: default title: Term-level queries has_children: true has_toc: false -nav_order: 20 +nav_order: 40 +redirect_from: + - /opensearch/query-dsl/term/ + - /query-dsl/term/ --- # Term-level queries @@ -27,6 +30,6 @@ Query type | Description [`range`]({{site.url}}{{site.baseurl}}/query-dsl/term/range/) | Searches for documents with field values in a specific range. [`prefix`]({{site.url}}{{site.baseurl}}/query-dsl/term/prefix/) | Searches for documents containing terms that begin with a specific prefix. [`exists`]({{site.url}}{{site.baseurl}}/query-dsl/term/exists/) | Searches for documents with any indexed value in a specific field. -[`fuzzy`]({{site.url}}{{site.baseurl}}/query-dsl/term/fuzzy/) | Searches for documents containing terms that are similar to the search term within the maximum allowed [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). The Levenshtein distance measures the number of one-character changes needed to change one term to another term. +[`fuzzy`]({{site.url}}{{site.baseurl}}/query-dsl/term/fuzzy/) | Searches for documents containing terms that are similar to the search term within the maximum allowed [Damerau–Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance). The Damerau–Levenshtein distance measures the number of one-character changes needed to change one term to another term. [`wildcard`]({{site.url}}{{site.baseurl}}/query-dsl/term/wildcard/) | Searches for documents containing terms that match a wildcard pattern. -[`regexp`]({{site.url}}{{site.baseurl}}/query-dsl/term/regexp/) | Searches for documents containing terms that match a regular expression. \ No newline at end of file +[`regexp`]({{site.url}}{{site.baseurl}}/query-dsl/term/regexp/) | Searches for documents containing terms that match a regular expression. diff --git a/_query-dsl/term/prefix.md b/_query-dsl/term/prefix.md index 14f208f3..5e3c8422 100644 --- a/_query-dsl/term/prefix.md +++ b/_query-dsl/term/prefix.md @@ -2,8 +2,7 @@ layout: default title: Prefix parent: Term-level queries -grand_parent: Query DSL -nav_order: 40 +nav_order: 60 --- # Prefix query @@ -50,7 +49,7 @@ GET _search "prefix": { "<field>": { "value": "sample", - ... + ... } } } @@ -63,8 +62,9 @@ The `<field>` accepts the following parameters. All parameters except `value` ar Parameter | Data type | Description :--- | :--- | :--- `value` | String | The term to search for in the field specified in `<field>`. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. `case_insensitive` | Boolean | If `true`, allows case-insensitive matching of the value with the indexed field values. Default is `false` (case sensitivity is determined by the field's mapping). `rewrite` | String | Determines how OpenSearch rewrites and scores multi-term queries. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. Default is `constant_score`. -If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, prefix queries are not run. If `index_prefixes` is enabled, the `search.allow_expensive_queries` setting is ignored and an optimized query is built and run. -{: .important} \ No newline at end of file +If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, then prefix queries are not executed. If `index_prefixes` is enabled, then the `search.allow_expensive_queries` setting is ignored and an optimized query is built and run. +{: .important} diff --git a/_query-dsl/term/range.md b/_query-dsl/term/range.md index 076ab5ad..1e6fece2 100644 --- a/_query-dsl/term/range.md +++ b/_query-dsl/term/range.md @@ -2,7 +2,6 @@ layout: default title: Range parent: Term-level queries -grand_parent: Query DSL nav_order: 50 --- @@ -90,7 +89,7 @@ OpenSearch populates missing date components with the following values: - `SECOND_OF_MINUTE`: `59` - `NANO_OF_SECOND`: `999_999_999` -If the year is missing, it is not populated. +If the year is missing, it is not populated. For example, consider the following request that specifies only the year in the start date: @@ -131,7 +130,7 @@ GET products/_search ``` {% include copy-curl.html %} -In the preceding example, `2019/01/01` is the anchor date (the starting point) for the date math. After the two pipe characters (`||`), you are specifying a mathematical expression relative to the anchor date. In this example, you are subtracting 1 year (`-1y`) and 1 day (`-1d`). +In the preceding example, `2019/01/01` is the anchor date (the starting point) for the date math. After the two pipe characters (`||`), you are specifying a mathematical expression relative to the anchor date. In this example, you are subtracting 1 year (`-1y`) and 1 day (`-1d`). You can also round off dates by adding a forward slash to the date or time unit. @@ -175,8 +174,8 @@ GET /products/_search "query": { "range": { "created": { - "time_zone": "-04:00", - "gte": "2022-04-17T06:00:00" + "time_zone": "-04:00", + "gte": "2022-04-17T06:00:00" } } } @@ -184,7 +183,7 @@ GET /products/_search ``` {% include copy-curl.html %} -The `gte` parameter in the preceding query is converted to `2022-04-17T10:00:00 UTC`, which is the UTC equivalent of `2022-04-17T06:00:00-04:00`. +The `gte` parameter in the preceding query is converted to `2022-04-17T10:00:00 UTC`, which is the UTC equivalent of `2022-04-17T06:00:00-04:00`. The `time_zone` parameter does not affect the `now` value because `now` always corresponds to the current system time in UTC. {: .note} @@ -200,7 +199,7 @@ GET _search "range": { "<field>": { "gt": 10, - ... + ... } } } @@ -215,8 +214,8 @@ Parameter | Data type | Description :--- | :--- | :--- `format` | String | A [format]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/date/#formats) for dates in this query. Default is the field's mapped format. `relation` | String | Indicates how the range query matches values for [`range`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/range/) fields. Valid values are:<br> - `INTERSECTS` (default): Matches documents whose `range` field value intersects the range provided in the query. <br> - `CONTAINS`: Matches documents whose `range` field value contains the entire range provided in the query. <br> - `WITHIN`: Matches documents whose `range` field value is entirely within the range provided in the query. -`boost` | Floating-point | Boosts the query by the given multiplier. Useful for searches that contain more than one query. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. `time_zone` | String | The time zone used to convert [`date`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/date/) values to UTC in the query. Valid values are ISO 8601 [UTC offsets](https://en.wikipedia.org/wiki/List_of_UTC_offsets) and [IANA time zone IDs](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). For more information, see [Time zone](#time-zone). -If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, range queries on [`text`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/text/) and [`keyword`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/keyword/) fields are not run. +If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, then range queries on [`text`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/text/) and [`keyword`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/keyword/) fields are not executed. {: .important} diff --git a/_query-dsl/term/regexp.md b/_query-dsl/term/regexp.md index 31bc6460..15cca563 100644 --- a/_query-dsl/term/regexp.md +++ b/_query-dsl/term/regexp.md @@ -2,13 +2,14 @@ layout: default title: Regexp parent: Term-level queries -grand_parent: Query DSL -nav_order: 60 +nav_order: 100 --- # Regexp query -Use the `regexp` query to search for terms that match a regular expression. +Use the `regexp` query to search for terms that match a regular expression. For more information about writing regular expressions, see [Regular expression syntax]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/). + +To search for terms that match a regular expression and appear near other terms, use the `regexp` rule of the `intervals` query. For more information, see [The `regexp` rule]({{site.url}}{{site.baseurl}}/query-dsl/full-text/intervals/#the-regexp-rule). The following query searches for any term that starts with any uppercase or lowercase letter followed by `amlet`: @@ -28,9 +29,95 @@ Note the following important considerations: - Regular expressions are applied to the terms (that is, tokens) in the field---not to the entire field. - By default, the maximum length of a regular expression is 1,000 characters. To change the maximum length, update the `index.max_regex_length` setting. -- Regular expressions use the Lucene syntax, which differs from more standardized implementations. Test thoroughly to ensure that you receive the results you expect. To learn more, see [the Lucene documentation](https://lucene.apache.org/core/8_9_0/core/index.html). +- Regular expressions use the Lucene syntax, which differs from more standardized implementations. Test thoroughly to ensure that you receive the results you expect. To learn more, see [the Lucene documentation](https://lucene.apache.org/core/{{site.lucene_version}}/core/index.html). - To improve regexp query performance, avoid wildcard patterns without a prefix or suffix, such as `.*` or `.*?+`. -- `regexp` queries can be expensive operations and require the [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) setting to be set to `true`. Before making frequent `regexp` queries, test their impact on cluster performance and examine alternative queries that may achieve similar results. +- `regexp` queries can be expensive operations and require the [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/#expensive-queries) setting to be set to `true`. Before making frequent `regexp` queries, test their impact on cluster performance and examine alternative queries that may achieve similar results. +- The [wildcard field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/wildcard/) builds an index that is specially designed to be very efficient for wildcard and regular expression queries. + +## Matching terms instead of field values + +A `regexp` query is not analyzed, but the field it searches might be. When a `text` field is indexed, the standard analyzer splits its value into lowercase terms, and the regular expression must match one of those terms. As a result, a pattern containing uppercase letters or spaces returns no results for a `text` field. + +To try this, index a document into an index that uses dynamic mapping. The `title` field is mapped as `text` and has a `title.keyword` subfield: + +```json +PUT my-index/_doc/1?refresh=true +{ + "title": "Henry IV" +} +``` +{% include copy-curl.html %} + +The `title` field contains the terms `henry` and `iv`, so the following query returns no results: + +```json +GET my-index/_search +{ + "query": { + "regexp": { + "title": "Henry.*" + } + } +} +``` +{% include copy-curl.html %} + +To match the original field value, including its capitalization and spaces, search the `keyword` subfield: + +```json +GET my-index/_search +{ + "query": { + "regexp": { + "title.keyword": "Henry I.*" + } + } +} +``` +{% include copy-curl.html %} + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my-index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "Henry IV" + } + } + ] + } +} +``` +</details> + +If a `regexp` query returns no results, also check the following: + +- The pattern must match the entire term. For example, `hen` does not match the term `henry`, but `hen.*` does. +- The `^` and `$` anchors are not supported. For example, `^Henry.*` does not match `Henry IV` in a `keyword` field. For more information, see [Unsupported features]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/#unsupported-features). +- Matching is case sensitive by default. To match terms regardless of case, set `case_insensitive` to `true`. For example, `henry iv` matches `Henry IV` in the `title.keyword` field when `case_insensitive` is `true`. ## Parameters @@ -43,7 +130,7 @@ GET _search "regexp": { "<field>": { "value": "[Ss]ample", - ... + ... } } } @@ -56,11 +143,11 @@ The `<field>` accepts the following parameters. All parameters except `value` ar Parameter | Data type | Description :--- | :--- | :--- `value` | String | The regular expression used for matching terms in the field specified in `<field>`. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. `case_insensitive` | Boolean | If `true`, allows case-insensitive matching of the regular expression value with the indexed field values. Default is `false` (case sensitivity is determined by the field's mapping). -`flags` | String | Enables optional operators for Lucene’s regular expression engine. +`flags` | String | Enables optional operators for Lucene's regular expression engine. For valid values, see [Optional operators]({{site.url}}{{site.baseurl}}/query-dsl/regex-syntax/#optional-operators). `max_determinized_states` | Integer | Lucene converts a regular expression to an automaton with a number of determinized states. This parameter specifies the maximum number of automaton states the query requires. Use this parameter to prevent high resource consumption. To run complex regular expressions, you may need to increase the value of this parameter. Default is 10,000. `rewrite` | String | Determines how OpenSearch rewrites and scores multi-term queries. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. Default is `constant_score`. -If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, `regexp` queries are not run. +If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, then `regexp` queries are not executed. {: .important} - diff --git a/_query-dsl/term/term.md b/_query-dsl/term/term.md index 20694fb4..50b94156 100644 --- a/_query-dsl/term/term.md +++ b/_query-dsl/term/term.md @@ -2,8 +2,7 @@ layout: default title: Term parent: Term-level queries -grand_parent: Query DSL -nav_order: 70 +nav_order: 10 --- # Term query @@ -43,6 +42,9 @@ GET shakespeare/_search ``` {% include copy-curl.html %} +In OpenSearch 2.x and earlier, complexity can increase exponentially with the number of characters, leading to high heap memory usage and reduced performance. To avoid this, do not use case-insensitive searches. Instead, apply a [lowercase token filter]({{site.url}}{{site.baseurl}}/analyzers/token-filters/lowercase/) in the indexed field's analyzer and use lowercase query terms. +{: .warning} + The response contains the matching documents despite any differences in case: ```json @@ -82,7 +84,7 @@ GET _search "term": { "<field>": { "value": "sample", - ... + ... } } } @@ -95,5 +97,6 @@ The `<field>` accepts the following parameters. All parameters except `value` ar Parameter | Data type | Description :--- | :--- | :--- `value` | String | The term to search for in the field specified in `<field>`. A document is returned in the results only if its field value exactly matches the term, with the correct spacing and capitalization. -`boost` | Floating-point | Boosts the query by the given multiplier. Useful for searches that contain more than one query. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. -`case_insensitive` | Boolean | If `true`, allows case-insensitive matching of the value with the indexed field values. Default is `false` (case sensitivity is determined by the field's mapping). \ No newline at end of file +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. +`_name` | String | The name of the query for query tagging. Optional. +`case_insensitive` | Boolean | If `true`, allows case-insensitive matching of the value with the indexed field values. Default is `false` (case sensitivity is determined by the field's mapping). diff --git a/_query-dsl/term/terms-set.md b/_query-dsl/term/terms-set.md index 452cae66..0216d060 100644 --- a/_query-dsl/term/terms-set.md +++ b/_query-dsl/term/terms-set.md @@ -2,8 +2,7 @@ layout: default title: Terms set parent: Term-level queries -grand_parent: Query DSL -nav_order: 90 +nav_order: 30 --- # Terms set query @@ -153,7 +152,7 @@ GET _search "terms_set": { "<field>": { "terms": [ "term1", "term2" ], - ... + ... } } } @@ -166,5 +165,6 @@ The `<field>` accepts the following parameters. All parameters except `terms` ar Parameter | Data type | Description :--- | :--- | :--- `terms` | Array of strings | The array of terms to search for in the field specified in `<field>`. A document is returned in the results only if the required number of terms matches the document's field values exactly, with the correct spacing and capitalization. -`minimum_should_match_field` | String | The name of the [numeric]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/numeric/) field that specifies the number of matching terms required in order to return a document in the results. -`minimum_should_match_script` | String | A script that returns the number of matching terms required in order to return a document in the results. \ No newline at end of file +`minimum_should_match_field` | String | The name of the [numeric]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/numeric/) field that specifies the number of matching terms required in order to return a document in the results. You must specify either `minimum_should_match_field` or `minimum_should_match_script`, but not both. +`minimum_should_match_script` | String | A script that returns the number of matching terms required in order to return a document in the results. You must specify either `minimum_should_match_field` or `minimum_should_match_script`, but not both. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. diff --git a/_query-dsl/term/terms.md b/_query-dsl/term/terms.md index 5e5524e6..61ef5c6b 100644 --- a/_query-dsl/term/terms.md +++ b/_query-dsl/term/terms.md @@ -2,8 +2,7 @@ layout: default title: Terms parent: Term-level queries -grand_parent: Query DSL -nav_order: 80 +nav_order: 20 --- # Terms query @@ -29,6 +28,10 @@ A document is returned if it matches any of the terms in the array. By default, the maximum number of terms allowed in a `terms` query is 65,536. To change the maximum number of terms, update the `index.max_terms_count` setting. +For better query performance, pass long arrays containing terms in sorted order (ordered by UTF-8 byte values, ascending). +{: .tip} + + The ability to [highlight results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) for terms queries may not be guaranteed, depending on the highlighter type and the number of terms in the query. {: .note} @@ -39,7 +42,9 @@ The query accepts the following parameters. All parameters are optional. Parameter | Data type | Description :--- | :--- | :--- `<field>` | String | The field in which to search. A document is returned in the results only if its field value exactly matches at least one term, with the correct spacing and capitalization. -`boost` | Floating-point | Boosts the query by the given multiplier. Useful for searches that contain more than one query. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. +`_name` | String | The name of the query for query tagging. Optional. +`value_type` | String | Specifies the types of values used for filtering. Valid values are `default` and `bitmap`. If omitted, the value defaults to `default`. ## Terms lookup @@ -183,7 +188,7 @@ PUT classes/_doc/102 To search for students enrolled in `CS102`, use the dot path notation to specify the full path to the field in the `path` parameter: ```json -ET students/_search +GET students/_search { "query": { "terms": { @@ -248,5 +253,325 @@ Parameter | Data type | Description :--- | :--- | :--- `index` | String | The name of the index in which to fetch field values. Required. `id` | String | The document ID of the document from which to fetch field values. Required. +`query` | Object | A query object used to select multiple documents from which to fetch field values. Required if `id` is not supplied. `path` | String | The name of the field from which to fetch field values. Specify nested fields using dot path notation. Required. -`routing` | String | Custom routing value of the document from which to fetch field values. Optional. Required if a custom routing value was provided when the document was indexed. \ No newline at end of file +`routing` | String | Custom routing value of the document from which to fetch field values. Optional. Required if a custom routing value was provided when the document was indexed. +`store` | Boolean | Whether to perform the lookup on the stored field instead of `_source`. Optional. + +## Terms lookup by query +**Introduced 3.2** +{: .label .label-purple} + +You can use a query to dynamically extract values from multiple documents and use them in a `terms` query. Instead of specifying a document ID, the `query` parameter lets you match documents and collect all values for a specified field across those matches. + +This is useful when you want to search one index based on field values from documents in another index. + +For a list of supported parameters, see [terms lookup parameters](#parameters-1). To use terms lookup by query, you must provide the `query` parameter instead of `id` in the terms lookup object. + +### How values are collected + +The behavior of the terms lookup depends on how the target field appears in the matched documents: + +- If a document matching the query does not contain the specified field, the document is ignored for terms extraction. +- If the field is a list, all its items are collected. +- If the field is a scalar, its value is collected. +- If the same field is a single value or a list for different documents, all values are flattened into a single list and deduplicated. +- Multiple lists are flattened into a single list. +- If the field is missing, `null`, or an empty list, it is skipped. +- Duplicates from multiple documents are deduplicated. +- If no documents match the query, the `terms` query acts as if no values were specified (typically, matches nothing). +- If none of the matched documents contain the field, the query does not match anything. + +### Example + +First, create an index named `users`, which contains user information: + +```json +PUT /users +{ + "mappings": { + "properties": { + "username": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Add user data to the index: + +```json +PUT users/_doc/u1 +{ "username": "alice" } +``` +{% include copy-curl.html %} + +```json +PUT users/_doc/u2 +{ "username": "bob" } +``` +{% include copy-curl.html %} + +```json +PUT users/_doc/u3 +{ "username": "carol" } +``` +{% include copy-curl.html %} + +```json +PUT users/_doc/u4 +{ "username": "dave" } +``` +{% include copy-curl.html %} + +Next, create an index containing group memberships: + +```json +PUT groups +{ + "mappings": { + "properties": { + "group": { "type": "keyword" }, + "members": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +Add group membership data to the index: + +```json +PUT groups/_doc/1 +{ + "group": "g1", + "members": ["alice", "bob"] +} +``` +{% include copy-curl.html %} + +```json +PUT groups/_doc/2 +{ + "group": "g1", + "members": "carol" +} +``` +{% include copy-curl.html %} + +```json +PUT groups/_doc/3 +{ + "group": "g1" +} +``` +{% include copy-curl.html %} + +```json +PUT groups/_doc/4 +{ + "group": "g1", + "members": [] +} +``` +{% include copy-curl.html %} + +```json +PUT groups/_doc/5 +{ + "group": "g1", + "members": null +} +``` +{% include copy-curl.html %} + +```json +PUT groups/_doc/6 +{ + "group": "g2", + "members": "carol" +} +``` +{% include copy-curl.html %} + +To search the `users` index for all users who are members of the `g1` group, use the following request: + +```json +GET /users/_search +{ + "query": { + "terms": { + "username": { + "index": "groups", + "path": "members", + "query": { + "term": { "group": "g1" } + } + } + } + } +} +``` +{% include copy-curl.html %} + +This query collects all values from the `members` field of documents in `groups` whose `group` is set to `g1` and uses them as terms for the `username` field in the `users` index: + +```json +{ + "hits": { + "total": { "value": 3, "relation": "eq" }, + "hits": [ + { "_index": "users", "_id": "u1", "_score": 1.0, "_source": { "username": "alice" } }, + { "_index": "users", "_id": "u2", "_score": 1.0, "_source": { "username": "bob" } }, + { "_index": "users", "_id": "u3", "_score": 1.0, "_source": { "username": "carol" } } + ] + } +} +``` + +This query processes matching documents as follows: + +- The lookup query matches documents 1, 2, 3, 4, and 5 (all specify group `g1`). +- Doc 6 (using a different group, `g2`) is ignored by the query. +- The `members` field for each matching document is processed as follows: + - Doc 1: `["alice", "bob"]` (list) → both `alice` and `bob` are collected. + - Doc 2: `"carol"` (scalar) → `carol` is collected. + - Doc 3: missing `members` field → ignored. + - Doc 4: empty list → ignored. + - Doc 5: null → ignored. +- All collected values are flattened and deduplicated, so the final result is `["alice", "bob", "carol"]`. + +## Bitmap filtering +**Introduced 2.17** +{: .label .label-purple } + +The `terms` query can filter for multiple terms simultaneously. However, when the number of terms in the input filter increases to a large value (around 10,000), the resulting network and memory overhead can become significant, making the query inefficient. In such cases, consider encoding your large terms filter using a [roaring bitmap](https://github.com/RoaringBitmap/RoaringBitmap) for more efficient filtering. + +The following example assumes that you have two indexes: a `products` index, which contains all the products sold by a company, and a `customers` index, which stores filters representing customers who own specific products. + +First, create a `products` index and map `product_id` as an integer: + +```json +PUT /products +{ + "mappings": { + "properties": { + "product_id": { "type": "integer" } + } + } +} +``` +{% include copy-curl.html %} + +Next, index three documents that correspond to products: + +```json +PUT /products/_doc/1 +{ + "name": "Product 1", + "product_id" : 111 +} +``` +{% include copy-curl.html %} + +```json +PUT /products/_doc/2 +{ + "name": "Product 2", + "product_id" : 222 +} +``` +{% include copy-curl.html %} + +```json +PUT /products/_doc/3 +{ + "name": "Product 3", + "product_id" : 333 +} +``` +{% include copy-curl.html %} + +To store customer bitmap filters, you'll create a `customer_filter` [binary field]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/binary/) in the `customers` index. Specify `store` as `true` to store the field: + +```json +PUT /customers +{ + "mappings": { + "properties": { + "customer_filter": { + "type": "binary", + "store": true + } + } + } +} +``` +{% include copy-curl.html %} + +For each customer, you need to generate a bitmap that represents the product IDs of the products the customer owns. This bitmap effectively encodes the filter criteria for that customer. In this example, you'll create a `terms` filter for a customer whose ID is `customer123` and who owns products `111`, `222`, and `333`. + +To encode a `terms` filter for the customer, first create a roaring bitmap for the filter. This example creates a bitmap using the [PyRoaringBitMap] library, so first run `pip install pyroaring` to install the library. Then serialize the bitmap and encode it using a [Base64](https://en.wikipedia.org/wiki/Base64) encoding scheme: + +```py +from pyroaring import BitMap +import base64 + +# Create a bitmap, serialize it into a byte string, and encode into Base64 +bm = BitMap([111, 222, 333]) # product ids owned by a customer +encoded = base64.b64encode(BitMap.serialize(bm)) + +# Convert the Base64-encoded bytes to a string for storage or transmission +encoded_bm_str = encoded.decode('utf-8') + +# Print the encoded bitmap +print(f"Encoded Bitmap: {encoded_bm_str}") +``` +{% include copy.html %} + +Next, index the customer filter into the `customers` index. The document ID for the filter is the same as the ID for the corresponding customer (in this example, `customer123`). The `customer_filter` field contains the bitmap you generated for this customer: + +```json +POST customers/_doc/customer123 +{ + "customer_filter": "OjAAAAEAAAAAAAIAEAAAAG8A3gBNAQ==" +} +``` +{% include copy-curl.html %} + +Now you can run a `terms` query on the `products` index to look up a specific customer in the `customers` index. Because you're looking up a stored field instead of `_source`, set `store` to `true`. In the `value_type` field, specify the data type of the `terms` input as `bitmap`: + +```json +POST /products/_search +{ + "query": { + "terms": { + "product_id": { + "index": "customers", + "id": "customer123", + "path": "customer_filter", + "store": true + }, + "value_type": "bitmap" + } + } +} +``` +{% include copy-curl.html %} + +You can also directly pass the bitmap to the `terms` query. In this example, the `product_id` field contains the customer filter bitmap for the customer whose ID is `customer123`: + +```json +POST /products/_search +{ + "query": { + "terms": { + "product_id": [ + "OjAAAAEAAAAAAAIAEAAAAG8A3gBNAQ==" + ], + "value_type": "bitmap" + } + } +} +``` +{% include copy-curl.html %} diff --git a/_query-dsl/term/wildcard.md b/_query-dsl/term/wildcard.md index 897ab6ed..0dfcd483 100644 --- a/_query-dsl/term/wildcard.md +++ b/_query-dsl/term/wildcard.md @@ -2,8 +2,7 @@ layout: default title: Wildcard parent: Term-level queries -grand_parent: Query DSL -nav_order: 100 +nav_order: 90 --- # Wildcard query @@ -37,6 +36,8 @@ If you change `*` to `?`, you get no matches because `?` refers to a single char Wildcard queries tend to be slow because they need to iterate over a lot of terms. Avoid placing wildcard characters at the beginning of a query because it could be a very expensive operation in terms of both resources and time. +The [wildcard field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/wildcard/) builds an index that is specially designed to be very efficient for wildcard and regular expression queries. + ## Parameters The query accepts the name of the field (`<field>`) as a top-level parameter: @@ -61,9 +62,9 @@ The `<field>` accepts the following parameters. All parameters except `value` ar Parameter | Data type | Description :--- | :--- | :--- `value` | String | The wildcard pattern used for matching terms in the field specified in `<field>`. -`boost` | Floating-point | Boosts the query by the given multiplier. Useful for searches that contain more than one query. Values in the [0, 1) range decrease relevance, and values greater than 1 increase relevance. Default is `1`. +`boost` | Floating-point | A floating-point value that specifies the weight of this field toward the relevance score. Values above 1.0 increase the field’s relevance. Values between 0.0 and 1.0 decrease the field’s relevance. Default is 1.0. `case_insensitive` | Boolean | If `true`, allows case-insensitive matching of the value with the indexed field values. Default is `false` (case sensitivity is determined by the field's mapping). `rewrite` | String | Determines how OpenSearch rewrites and scores multi-term queries. Valid values are `constant_score`, `scoring_boolean`, `constant_score_boolean`, `top_terms_N`, `top_terms_boost_N`, and `top_terms_blended_freqs_N`. Default is `constant_score`. -If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/index/#expensive-queries) is set to `false`, wildcard queries are not run. +If [`search.allow_expensive_queries`]({{site.url}}{{site.baseurl}}/query-dsl/#expensive-queries) is set to `false`, then wildcard queries are not executed. {: .important} diff --git a/_search-plugins/async/index.md b/_search-plugins/async/index.md index a663e7fa..b1f2b1fc 100644 --- a/_search-plugins/async/index.md +++ b/_search-plugins/async/index.md @@ -1,7 +1,7 @@ --- layout: default title: Asynchronous search -nav_order: 51 +nav_order: 40 parent: Improving search performance has_children: true redirect_from: @@ -31,6 +31,7 @@ Options | Description | Default value | Required `wait_for_completion_timeout` | The amount of time that you plan to wait for the results. You can see whatever results you get within this time just like in a normal search. You can poll the remaining results based on an ID. The maximum value is 300 seconds. | 1 second | No `keep_on_completion` | Whether you want to save the results in the cluster after the search is complete. You can examine the stored results at a later time. | `false` | No `keep_alive` | The amount of time that the result is saved in the cluster. For example, `2d` means that the results are stored in the cluster for 48 hours. The saved search results are deleted after this period or if the search is canceled. Note that this includes the query execution time. If the query overruns this time, the process cancels this query automatically. | 12 hours | No +`index` | The name of the index to be searched. Can be an individual name, a comma-separated list of indexes, or a wildcard expression of index names. | All indexes in the cluster | No #### Example request @@ -52,7 +53,7 @@ POST _plugins/_asynchronous_search/?pretty&size=10&wait_for_completion_timeout=1 ```json { - "*id*": "FklfVlU4eFdIUTh1Q1hyM3ZnT19fUVEUd29KLWZYUUI3TzRpdU5wMjRYOHgAAAAAAAAABg==", + "id": "FklfVlU4eFdIUTh1Q1hyM3ZnT19fUVEUd29KLWZYUUI3TzRpdU5wMjRYOHgAAAAAAAAABg==", "state": "RUNNING", "start_time_in_millis": 1599833301297, "expiration_time_in_millis": 1600265301297, @@ -120,7 +121,7 @@ Introduced 1.0 After you submit an asynchronous search request, you can request partial responses with the ID that you see in the asynchronous search response. ```json -GET _plugins/_asynchronous_search/<ID>?pretty +GET _plugins/_asynchronous_search/{ID}?pretty ``` #### Example response @@ -197,7 +198,7 @@ Introduced 1.0 To delete an asynchronous search: ``` -DELETE _plugins/_asynchronous_search/<ID>?pretty +DELETE _plugins/_asynchronous_search/{ID}?pretty ``` - If the search is still running, OpenSearch cancels it. @@ -261,5 +262,5 @@ Options | Description `search_failed` | The number of asynchronous search requests that completed with a failed response. `persisted` | The number of asynchronous search requests whose final result successfully persisted in the cluster. `persist_failed` | The number of asynchronous search requests whose final result failed to persist in the cluster. -`running_current` | The number of asynchronous search requests that are running on a given coordinator node. +`running_current` | The number of asynchronous search requests that are running on a given coordinating node. `cancelled` | The number of asynchronous search requests that were canceled while the search was running. diff --git a/_search-plugins/async/security.md b/_search-plugins/async/security.md index 128f6bfc..bf9275e9 100644 --- a/_search-plugins/async/security.md +++ b/_search-plugins/async/security.md @@ -5,8 +5,6 @@ nav_order: 2 parent: Asynchronous search grand_parent: Improving search performance has_children: false -redirect_from: - - /search-plugins/async/security/ --- # Asynchronous search security @@ -23,9 +21,9 @@ The Security plugin has two built-in roles that cover most asynchronous search u If these roles don’t meet your needs, mix and match individual asynchronous search permissions to suit your use case. Each action corresponds to an operation in the REST API. For example, the `cluster:admin/opensearch/asynchronous_search/delete` permission lets you delete a previously submitted asynchronous search. -### A note on Asynchronous Search and fine-grained access control +### A note on asynchronous search and fine-grained access control -By design, the Asynchronous Search plugin extracts data from a target index and stores the data in a separate index to make search results available to users with the proper permissions. Although a user with either the `asynchronous_search_read_access` or `cluster:admin/opensearch/asynchronous_search/get` permission cannot submit the asynchronous search request itself, that user can get and view the search results using the associated search ID. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security) (FLS) access controls are designed to protect the data in the target index. But once the data is stored outside this index, users with these access permissions are able to use search IDs to get and view asynchronous search results, which may include data that is otherwise concealed by DLS and FLS access control in the target index. +By design, the Asynchronous Search plugin extracts data from a target index and stores the data in a separate index to make search results available to users with the proper permissions. Although a user with either the `asynchronous_search_read_access` or `cluster:admin/opensearch/asynchronous_search/get` permission cannot submit the asynchronous search request itself, that user can get and view the search results using the associated search ID. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security/) (FLS) access controls are designed to protect the data in the target index. But once the data is stored outside this index, users with these access permissions are able to use search IDs to get and view asynchronous search results, which may include data that is otherwise concealed by DLS and FLS access control in the target index. To reduce the chances of unintended users viewing search results that could describe an index, we recommend that administrators enable role-based access control and keep these kinds of design elements in mind when assigning permissions to the intended group of users. See [Limit access by backend role](#advanced-limit-access-by-backend-role) for details. @@ -33,7 +31,7 @@ To reduce the chances of unintended users viewing search results that could desc Use backend roles to configure fine-grained access to asynchronous searches based on roles. For example, users of different departments in an organization can view asynchronous searches owned by their own department. -First, make sure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/access-control/api#create-user). +First, make sure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/api/users/create-user/). Now when users view asynchronous search resources in OpenSearch Dashboards (or make REST API calls), they only see asynchronous searches submitted by users who have a subset of the backend role. For example, consider two users: `judy` and `elon`. @@ -78,7 +76,7 @@ PUT _plugins/_security/api/rolesmapping/async_full_access } ``` -Because they have different backend roles, an asynchronous search submitted by `judy` will not be visible to `elon` and vice versa. +Because they have different backend roles, an asynchronous search submitted by `judy` will not be visible to `elon` and the other way around. `judy` needs to have at least the superset of all roles that `elon` has to see `elon`'s asynchronous searches. diff --git a/_search-plugins/async/settings.md b/_search-plugins/async/settings.md index f153401e..044da081 100644 --- a/_search-plugins/async/settings.md +++ b/_search-plugins/async/settings.md @@ -6,7 +6,7 @@ grand_parent: Improving search performance nav_order: 4 --- -# Asynchronous Search settings +# Asynchronous search settings The Asynchronous Search plugin adds several settings to the standard OpenSearch cluster settings. They are dynamic, so you can change the default behavior of the plugin without restarting your cluster. To learn more about static and dynamic settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). @@ -26,7 +26,7 @@ PUT _cluster/settings Setting | Default | Description :--- | :--- | :--- `plugins.asynchronous_search.max_search_running_time` | 12 hours | The maximum running time for the search beyond which the search is terminated. -`plugins.asynchronous_search.node_concurrent_running_searches` | 20 | The concurrent searches running per coordinator node. +`plugins.asynchronous_search.node_concurrent_running_searches` | 20 | The concurrent searches running per coordinating node. `plugins.asynchronous_search.max_keep_alive` | 5 days | The maximum amount of time that search results can be stored in the cluster. `plugins.asynchronous_search.max_wait_for_completion_timeout` | 1 minute | The maximum value for the `wait_for_completion_timeout` parameter. `plugins.asynchronous_search.persist_search_failures` | false | Persist asynchronous search results that end with a search failure in the system index. diff --git a/_search-plugins/caching/field-data-cache.md b/_search-plugins/caching/field-data-cache.md new file mode 100644 index 00000000..5761ec1f --- /dev/null +++ b/_search-plugins/caching/field-data-cache.md @@ -0,0 +1,68 @@ +--- +layout: default +title: Field data cache +parent: Caching +grand_parent: Improving search performance +nav_order: 20 +--- + +# Field data cache + +The field data cache is a node-level in-memory cache that stores field data and global ordinals. These are data structures that enable aggregations and sorting on analyzed text fields. Since they can be expensive to compute, they are cached after creation in case they need to be reused. + +## What is field data + +Field data is a data structure that enables quick sorting and aggregation on text fields. Text fields are stored in an inverted index, which is optimized for quick searching for specific terms, not iterating through individual documents. As this is necessary for aggregations or sorting, OpenSearch must process the inverted index into another data structure that is optimized for individual document access. + +## What are global ordinals + +When computing aggregations on a given field, each Lucene segment assigns a unique ordinal to each unique term, enabling things like bucket aggregations. When computing an aggregation across the whole cluster, it's necessary to create a global ordinal for each globally unique term and to store a mapping between these global ordinals and the segment ordinals. This enables combining the aggregation results from each segment. This mapping is then stored in the field data cache for reuse in future aggregations. + +If the field has the mapping parameter `"eager_global_ordinals": true`, which defaults to `false`, global ordinals are computed and stored at index refresh rather than lazily at query time. + +For more information about global ordinals, see [Eager global ordinals]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/eager_global_ordinals/). + +## Best practices + +By default, field data is disabled on text fields because it can consume large amounts of heap memory. If you want to sort or aggregate on text fields, we recommend instead creating a keyword subfield. Keyword fields are not analyzed and therefore do not get stored in an inverted index or require building a separate data structure for aggregations. + +If you want to enable sorting or aggregation directly on the text field, set `"fielddata": true` in the field's mapping. + +## Configuring the field data cache + +Setting | Data type | Default | Level | Static/Dynamic | Description +:--- |:-----------|:--------| :--- | :--- | :--- +`indices.breaker.fielddata.limit` | Percentage | `40%` | Cluster | Dynamic | Sets the field data cache size limit, beyond which incoming requests that would require more entries in the cache will be stopped by the circuit breaker. +`indices.fielddata.cache.size` | Byte size or percentage of total heap size | `35%` | Cluster | Dynamic | Sets the maximum field data cache size, beyond which evictions will occur. Must be smaller than the circuit breaker limit. With a value of -1, this limit does not apply and only the circuit breaker limit will be relevant. + +## Monitoring the field data cache + +The [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/) returns cache statistics for all nodes in a cluster: + +```json +GET /_nodes/stats/indices/fielddata +``` +{% include copy-curl.html %} + +The response contains the cache statistics: + +```json +{ + "nodes" : { + "oeR83dkUSPmnQqzBEGc4fQ" : { + "indices" : { + "fielddata" : { + "memory_size_in_bytes" : 0, + "evictions" : 0, + "item_count" : 0 + } + } + } + } +} +``` +{% include copy-curl.html %} + +You can aggregate the values by index by providing the parameter `level=indices`. + +You can also use the [Cat Field Data API]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-field-data/) to get a list of field data sizes for each field on each node. \ No newline at end of file diff --git a/_search-plugins/caching/index.md b/_search-plugins/caching/index.md new file mode 100644 index 00000000..880069f8 --- /dev/null +++ b/_search-plugins/caching/index.md @@ -0,0 +1,36 @@ +--- +layout: default +title: Caching +parent: Improving search performance +has_children: true +nav_order: 10 +redirect_from: + - /search-plugins/caching/ +--- + +# Caching + +OpenSearch relies on different on-heap cache types to accelerate data retrieval, providing significant improvement in search latency. However, cache size is limited by the amount of memory available on a node. When processing a larger dataset that can potentially be cached, the cache size limit can result in many pieces of data either being removed from the cache or not being cached, causing an incomplete query. This impacts performance because OpenSearch needs to process the query again, causing high resource consumption. + +Understanding how your data uses the cache can help improve your cluster's performance and prevent you from using too much memory, reducing the cost of querying your data. + +## Supported on-heap cache types + +OpenSearch supports the following on-heap cache types: + +- [**Index request cache**]({{site.url}}{{site.baseurl}}/search-plugins/caching/request-cache/): Caches the local results on each shard. This allows frequently used and potentially resource-heavy search requests to return results almost instantaneously. +- **Query cache**: Caches common data from similar queries at the shard level. The query cache is more granular than the request cache and can cache data to be reused in different queries. +- [**Field data cache**]({{site.url}}{{site.baseurl}}/search-plugins/caching/field-data-cache/): Caches field data and global ordinals, which are both used to support aggregations on certain field types. + +## Additional cache stores + +**Introduced 2.14** +{: .label .label-purple } + +In addition to existing custom OpenSearch on-heap cache stores, cache plugins provide the following cache stores: + +- **Disk cache**: Stores the precomputed result of a query on disk. Use a disk cache to cache much larger datasets, provided that the disk's latency is within an acceptable range. +- **Tiered cache**: A multi-level cache in which each tier has its own characteristics and performance levels. For example, a tiered cache can contain both on-heap and disk tiers. By combining different tiers, you can achieve a balance between cache performance and size. To learn more, see [Tiered cache]({{site.url}}{{site.baseurl}}/search-plugins/caching/tiered-cache/). + +In OpenSearch 2.14, the request cache is integrated with cache plugins. You can use a tiered or disk cache as a request-level cache. +{: .note} diff --git a/_search-plugins/caching/request-cache.md b/_search-plugins/caching/request-cache.md new file mode 100644 index 00000000..3b1e98c0 --- /dev/null +++ b/_search-plugins/caching/request-cache.md @@ -0,0 +1,163 @@ +--- +layout: default +title: Index request cache +parent: Caching +grand_parent: Improving search performance +nav_order: 5 +--- + +# Index request cache + +The OpenSearch index request cache is a specialized caching mechanism designed to enhance search performance by storing the results of frequently executed search queries at the shard level. This reduces cluster load and improves response times for repeated searches. This cache is enabled by default and is particularly useful for read-heavy workloads where certain queries are executed frequently. + +The cache is automatically invalidated at the configured refresh interval. The invalidation includes document updates (including document deletions) and changes to index settings. This ensures that stale results are never returned from the cache. When the cache size exceeds its configured limit, the least recently used entries are evicted to make room for new entries. + +Some queries are ineligible for the request cache. These include profiled queries, scroll queries, and search requests with non-deterministic characteristics (such as those using `Math.random()` or DFS queries) or relative times (such as `now` or `new Date()`). By default, only requests with `size=0` are cacheable. In OpenSearch 2.19 and later, this behavior can be changed using `indices.requests.cache.maximum_cacheable_size`. +{: .note} + +## Configuring request caching + +You can configure the index request cache by setting the parameters in the `opensearch.yml` configuration file or using the REST API. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +### Settings + +The following table lists the index request cache settings. For more information about dynamic settings, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). + +Setting | Data type | Default | Level | Static/Dynamic | Description +:--- |:-----------|:--------| :--- | :--- | :--- +`indices.cache.cleanup_interval` | Time unit | `1m` (1 minute) | Cluster | Static | Schedules a recurring background task that cleans up expired entries from the cache at the specified interval. +`indices.requests.cache.size` | Percentage | `1%` | Cluster | Static | The cache size as a percentage of the heap size (for example, to use 1% of the heap, specify `1%`). +`index.requests.cache.enable` | Boolean | `true` | Index | Dynamic | Enables or disables the request cache. +`indices.requests.cache.maximum_cacheable_size` | Integer | `0` | Cluster | Dynamic | Sets the maximum `size` of queries to be added to the request cache. + +### Example + +To disable the request cache for an index, send the following request: + +```json +PUT /my_index/_settings +{ + "index.requests.cache.enable": false +} +``` +{% include copy-curl.html %} + +## Caching specific requests + +In addition to providing index-level or cluster-level settings for the request cache, you can also cache specific search requests selectively by setting the `request_cache` query parameter to `true`: + +```json +GET /students/_search?request_cache=true +{ + "query": { + "match": { + "name": "doe john" + } + } +} +``` +{% include copy-curl.html %} + +## Matching requests to cached results + +The request cache stores results for each shard. To find a cached result, OpenSearch compares the parsed search request, so requests that differ only in formatting share a cached result. For example, requests that differ only in white space or in the order of JSON keys return the same cached result. So do two `terms` aggregations that differ only in whether they specify the default `size` of `10`. Requests that differ in content, such as an aggregation with a different name, are cached separately. + +## Monitoring the request cache + +Monitoring cache usage and performance is crucial to maintaining an efficient caching strategy. OpenSearch provides several APIs to help monitor the cache. + +### Retrieving cache statistics for all nodes + +The [Nodes Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/) returns cache statistics for all nodes in a cluster: + +```json +GET /_nodes/stats/indices/request_cache +``` +{% include copy-curl.html %} + +The response contains the request cache statistics: + +```json +{ + "nodes": { + "T7aqO6zaQX-lt8XBWBYLsA": { + "indices": { + "request_cache": { + "memory_size_in_bytes": 10240, + "evictions": 0, + "hit_count": 50, + "miss_count": 10 + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Retrieving cache statistics for a specific index + +The [Index Stats API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/stats/) returns cache statistics for a specific index: + +```json +GET /my_index/_stats/request_cache +``` +{% include copy-curl.html %} + +The response contains the request cache statistics: + +```json +{ + "_shards": { + "total": 5, + "successful": 5, + "failed": 0 + }, + "_all": { + "primaries": { + "request_cache": { + "memory_size_in_bytes": 2048, + "evictions": 1, + "hit_count": 30, + "miss_count": 5 + } + }, + "total": { + "request_cache": { + "memory_size_in_bytes": 4096, + "evictions": 2, + "hit_count": 60, + "miss_count": 10 + } + } + }, + "indices": { + "my_index": { + "primaries": { + "request_cache": { + "memory_size_in_bytes": 2048, + "evictions": 1, + "hit_count": 30, + "miss_count": 5 + } + }, + "total":{ + "request_cache": { + "memory_size_in_bytes": 4096, + "evictions": 2, + "hit_count": 60, + "miss_count": 10 + } + } + } + } +} +``` + +## Best practices + +When using the index request cache, consider the following best practices: + +- **Appropriate cache size**: Configure the cache size based on your query patterns. A larger cache can store more results but may consume significant resources. +- **Query optimization**: Ensure that frequently executed queries are optimized so that they can benefit from caching. +- **Monitoring**: Regularly monitor cache hit and cache miss rates to understand cache efficiency and make necessary adjustments. \ No newline at end of file diff --git a/_search-plugins/caching/tiered-cache.md b/_search-plugins/caching/tiered-cache.md new file mode 100644 index 00000000..d2ea31ea --- /dev/null +++ b/_search-plugins/caching/tiered-cache.md @@ -0,0 +1,110 @@ +--- +layout: default +title: Tiered cache +parent: Caching +grand_parent: Improving search performance +nav_order: 10 +--- + +# Tiered cache + +A tiered cache is a multi-level cache in which each tier has its own characteristics and performance levels. By combining different tiers, you can achieve a balance between cache performance and size. + +## Types of tiered caches + +OpenSearch provides one implementation of a tiered spillover cache. It is called `tiered_spillover`, and its implementation is stored in the `cache-common` module. It has two tiers: an upper tier and a lower tier. While any pluggable cache implementation can be used for each tier, typically the upper tier would be a smaller and faster on-heap tier, such as `opensearch_onheap`, and the lower tier would be a larger and slower disk tier, such as `ehcache_disk`. This lower tier can be dynamically enabled and disabled with the setting `indices.requests.cache.tiered_spillover.disk.store.enabled`. + +Items entering the cache will first go into the upper, on-heap tier. Once the upper tier is full, it evicts items (typically in LRU order, although cache implementations can evict items in any order). Those evicted items enter the lower, disk tier. When the disk tier is full, the items it evicts are removed from the cache entirely. If the lower tier is disabled, items evicted from the upper tier will leave the cache. + +Note that a given key can only be in one tier at a time; the upper tier does not contain a subset of the lower tier. When getting a key, each tier is checked in turn. + +You can use `tiered_spillover` to make the disk tier very large---larger than it could be if it was in memory. This allows you to cache many more items without using additional heap space. + +## Installing required plugins + +To use tiered caching, install the `cache-ehcache` plugin. This plugin provides a disk cache implementation, `ehcache_disk`, that can be used as a disk tier within a tiered cache. For more information about installing non-bundled plugins, see [Additional plugins]({{site.url}}{{site.baseurl}}/install-and-configure/plugins/#additional-plugins). + +A tiered cache will fail to initialize if the `cache-ehcache` plugin is not installed or if disk cache properties are not set. +{: .warning} + +## Tiered cache settings + +In OpenSearch 2.14 and later, the request cache can use the `tiered_spillover` cache or any other pluggable cache implementation. To begin, configure the following settings in the `opensearch.yml` file. + +### Cache store name + +To use the OpenSearch-provided tiered spillover cache implementation, set the cache store name to `tiered_spillover`, as shown in the following example: + +```yaml +indices.requests.cache.store.name: tiered_spillover +``` +{% include copy.html %} + +### Setting on-heap and disk store tiers + +Set the on-heap and disk store tiers to `opensearch_onheap` and `ehcache_disk`, as shown in the following example: + +```yaml +indices.requests.cache.tiered_spillover.onheap.store.name: opensearch_onheap +indices.requests.cache.tiered_spillover.disk.store.name: ehcache_disk +``` +The `opensearch_onheap` setting uses the built-in on-heap cache available in OpenSearch. + +The `ehcache_disk` setting is the disk cache implementation based on [Ehcache](https://www.ehcache.org/) and requires installing the `cache-ehcache` plugin. + +{% include copy.html %} + +### Configuring on-heap and disk stores + +The following table lists the cache store settings for the `opensearch_onheap` store. + +Setting | Data type | Default | Description +:--- | :--- | :--- | :--- +`indices.requests.cache.opensearch_onheap.size` | Percentage | 1% of the heap size | The size of the on-heap cache. Optional. +`indices.requests.cache.opensearch_onheap.expire` | Time unit | `MAX_VALUE` (disabled) | Specifies a time-to-live (TTL) for the cached results. Optional. + +The following table lists the disk cache store settings for the `ehcache_disk` store. + +Setting | Data type | Default | Description +:--- | :--- | :--- | :--- +`indices.requests.cache.ehcache_disk.max_size_in_bytes` | Long | `1073741824` (1 GB) | Defines the size of the disk cache. Optional. +`indices.requests.cache.ehcache_disk.storage.path` | String | `{data.paths}/nodes/{node.id}/request_cache` | Defines the storage path for the disk cache. Optional. +`indices.requests.cache.ehcache_disk.expire_after_access` | Time unit | `MAX_VALUE` (disabled) | Specifies a TTL for the cached results. Optional. +`indices.requests.cache.ehcache_disk.alias` | String | `ehcacheDiskCache#INDICES_REQUEST_CACHE` | Specifies an alias for the disk cache. Optional. +`indices.requests.cache.ehcache_disk.segments` | Integer | `16` | Defines the number of segments into which the disk cache is separated. Used for concurrency. Optional. +`indices.requests.cache.ehcache_disk.concurrency` | Integer | `1` | Defines the number of distinct write queues created for the disk store, where a group of segments shares a write queue. Optional. +`indices.requests.cache.ehcache_disk.min_threads` | Integer | `2` | Defines the minimum number of Ehcache disk threads for the pool. Optional. +`indices.requests.cache.ehcache_disk.max_threads` | Integer | The number of CPU cores | Defines the maximum number of Ehcache disk threads for the pool. The maximum allowed value is `10 * num_cpu_cores`. Disk operations are typically I/O bound rather than CPU bound, so you can set this value to a number greater than the number of CPU cores. Optional. + +### Additional settings for the `tiered_spillover` store + +The following table lists additional settings for the `tiered_spillover` store setting. + +Setting | Data type | Default | Description +:--- | :--- | :--- | :--- +`indices.requests.cache.tiered_spillover.policies.took_time.threshold` | Time unit | `0ms` | A policy used to determine whether to cache a query into the cache based on its query phase execution time. This is a dynamic setting. Optional. +`indices.requests.cache.tiered_spillover.disk.store.policies.took_time.threshold` | Time unit | `10ms` | A policy used to determine whether to cache a query into the disk tier of the cache based on its query phase execution time. This is a dynamic setting. Optional. +`indices.requests.cache.tiered_spillover.disk.store.enabled` | Boolean | `True` | Enables or disables the disk cache dynamically within a tiered spillover cache. Note: After disabling a disk cache, entries are not removed automatically and requires the cache to be manually cleared. Optional. +`indices.requests.cache.tiered_spillover.onheap.store.size` | Percentage | 1% of the heap size | Defines the size of the on-heap cache within a tiered cache. This setting overrides any size setting for the on-heap cache implementation itself, such as `indices.requests.cache.opensearch_onheap.size`. Optional. +`indices.requests.cache.tiered_spillover.disk.store.size` | Long | `1073741824` (1 GB) | Defines the size of the disk cache within a tiered cache. This setting overrides any size setting for the disk cache implementation itself, such as `indices.requests.cache.ehcache_disk.max_size_in_bytes`. Optional. +`indices.requests.cache.tiered_spillover.segments` | Integer | `2 ^ (ceil(log2(CPU_CORES * 1.5)))` | This determines the number of segments in the tiered cache, with each segment secured by a re-entrant read/write lock. These locks enable multiple concurrent readers without contention, while the segmentation allows multiple writers to operate simultaneously, resulting in higher write throughput. Optional. + +### Delete stale entries settings + +The following table lists the settings related to the deletion of stale entries from the cache. + +Setting | Data type | Default | Description +:--- | :--- |:--------| :--- +`indices.requests.cache.cleanup.staleness_threshold` | String | `0%` | Defines the percentage of stale keys in the cache post. After identification, all stale cache entries are deleted. Optional. +`indices.requests.cache.cleanup.interval` | Time unit | `1m` | Defines the frequency at which the request cache's stale entries are deleted. Optional. + +## Getting statistics for the `tiered_spillover` store + +To assess the impact of using the tiered spillover cache, use the [Node Stats API]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/nodes-stats/#caches), as shown in the following example: + +```json +GET /_nodes/stats/caches/request_cache?level=tier +``` + +The `tier` level is only valid if the `tiered_spillover` cache is in use, and it aggregates stats by upper and lower cache tier. + diff --git a/_search-plugins/concurrent-segment-search.md b/_search-plugins/concurrent-segment-search.md index 58b8d9a8..21aa0899 100644 --- a/_search-plugins/concurrent-segment-search.md +++ b/_search-plugins/concurrent-segment-search.md @@ -2,7 +2,7 @@ layout: default title: Concurrent segment search parent: Improving search performance -nav_order: 53 +nav_order: 20 --- # Concurrent segment search @@ -22,16 +22,50 @@ Without concurrent segment search, Lucene executes a request sequentially across ## Enabling concurrent segment search at the index or cluster level -By default, concurrent segment search is disabled on the cluster. You can enable concurrent segment search at two levels: +Starting with OpenSearch version 3.0, concurrent segment search is enabled at the cluster level by default. The default concurrent segment search mode is `auto`. After upgrading, aggregation workloads may experience increased CPU utilization. We recommend monitoring your cluster's resource usage and adjusting your infrastructure capacity as needed to maintain optimal performance. +{: .important} + +To configure concurrent segment search on your cluster, use the `search.concurrent_segment_search.mode` setting. The older `search.concurrent_segment_search.enabled` setting will be deprecated in future version releases in favor of the new setting. + +You can enable concurrent segment search at two levels: - Cluster level - Index level -The index-level setting takes priority over the cluster-level setting. Thus, if the cluster setting is enabled but the index setting is disabled, then concurrent segment search will be disabled for that index. +The index-level setting takes priority over the cluster-level setting. Thus, if the cluster setting is enabled but the index setting is disabled, then concurrent segment search will be disabled for that index. Because of this, the index-level setting is not evaluated unless it is explicitly set, regardless of the default value configured for the setting. You can retrieve the current value of the index-level setting by calling the [Index Settings API]({{site.url}}{{site.baseurl}}/api-reference/index-apis/get-settings/) and omitting the `?include_defaults` query parameter. {: .note} -To enable concurrent segment search for all indexes in the cluster, set the following dynamic cluster setting: +Both the cluster- and index-level `search.concurrent_segment_search.mode` settings accept the following values: +- `auto` (Default): In this mode, OpenSearch will use the pluggable _concurrent search decider_ to decide whether to use a concurrent or sequential path for the search request based on the query evaluation and the presence of aggregations in the request. By default, if there are no deciders configured by any plugin, then the decision to use concurrent search will be made based on the presence of aggregations in the request. For more information about the pluggable decider semantics, see [Pluggable concurrent search deciders](#pluggable-concurrent-search-deciders-concurrentsearchrequestdecider). + +- `all`: Enables concurrent segment search across all search requests. This is equivalent to setting `search.concurrent_segment_search.enabled` to `true`. + +- `none`: Disables concurrent segment search for all search requests, effectively turning off the feature. This is equivalent to setting `search.concurrent_segment_search.enabled` to `false`. + +To enable concurrent segment search for all search requests across every index in the cluster, send the following request: + +```json +PUT _cluster/settings +{ + "persistent":{ + "search.concurrent_segment_search.mode": "all" + } +} +``` +{% include copy-curl.html %} + +To enable concurrent segment search for all search requests on a particular index, specify the index name in the endpoint: + +```json +PUT {index-name}/_settings +{ + "index.search.concurrent_segment_search.mode": "all" +} +``` +{% include copy-curl.html %} + +You can continue to use the existing `search.concurrent_segment_search.enabled` setting to enable concurrent segment search for all indexes in the cluster as follows: ```json PUT _cluster/settings { @@ -45,44 +79,102 @@ PUT _cluster/settings To enable concurrent segment search for a particular index, specify the index name in the endpoint: ```json -PUT <index-name>/_settings +PUT {index-name}/_settings { "index.search.concurrent_segment_search.enabled": true } ``` {% include copy-curl.html %} + +When evaluating whether concurrent segment search is enabled on a cluster, the `search.concurrent_segment_search.mode` setting takes precedence over the `search.concurrent_segment_search.enabled` setting. +If the `search.concurrent_segment_search.mode` setting is not explicitly set, then the `search.concurrent_segment_search.enabled` setting will be evaluated to determine whether to enable concurrent segment search. + +When upgrading a cluster from an earlier version that specifies the older `search.concurrent_segment_search.enabled` setting, this setting will continue to be honored. However, once the `search.concurrent_segment_search.mode` is set, it will override the previous setting, enabling or disabling concurrent search based on the specified mode. +We recommend setting `search.concurrent_segment_search.enabled` to `null` on your cluster once you configure `search.concurrent_segment_search.mode`: + +```json +PUT _cluster/settings +{ + "persistent":{ + "search.concurrent_segment_search.enabled": null + } +} +``` +{% include copy-curl.html %} + +To disable the old setting for a particular index, specify the index name in the endpoint: +```json +PUT {index-name}/_settings +{ + "index.search.concurrent_segment_search.enabled": null +} +``` +{% include copy-curl.html %} + ## Slicing mechanisms -You can choose one of two available mechanisms for assigning segments to slices: the default [Lucene mechanism](#the-lucene-mechanism) or the [max slice count mechanism](#the-max-slice-count-mechanism). - -### The Lucene mechanism - -By default, Lucene assigns a maximum of 250K documents or 5 segments (whichever is met first) to each slice in a shard. For example, consider a shard with 11 segments. The first 5 segments have 250K documents each, and the next 6 segments have 20K documents each. The first 5 segments will be assigned to 1 slice each because they each contain the maximum number of documents allowed for a slice. Then the next 5 segments will all be assigned to another single slice because of the maximum allowed segment count for a slice. The 11th slice will be assigned to a separate slice. +You can choose one of two available mechanisms for assigning segments to slices: the default [max slice count mechanism](#the-max-slice-count-mechanism) or the [Lucene mechanism](#the-lucene-mechanism). ### The max slice count mechanism -The _max slice count_ mechanism is an alternative slicing mechanism that uses a statically configured maximum number of slices and divides segments among the slices in a round-robin fashion. This is useful when there are already too many top-level shard requests and you want to limit the number of slices per request in order to reduce competition between the slices. +The _max slice count_ mechanism is a slicing mechanism that uses a dynamically configurable maximum number of slices and divides segments among the slices in a round-robin fashion. This is useful when there are already too many top-level shard requests and you want to limit the number of slices per request in order to reduce competition between the slices. + +Starting with OpenSearch version 3.0, concurrent segment search uses the max slice count mechanism by default. The max slice count is calculated at the cluster startup time using the formula `Math.max(1, Math.min(Runtime.getRuntime().availableProcessors() / 2, 4))`. You can override this value by explicitly setting the `max_slice_count` parameter at either the cluster level or index level. For more information about updating `max_slice_count`, see [Setting the slicing mechanism](#setting-the-slicing-mechanism). To revert back to the default calculated value, set `max_slice_count` to `null`. + +### The Lucene mechanism + +The Lucene mechanism is an alternative to the max slice count mechanism. By default, Lucene assigns a maximum of 250K documents or 5 segments (whichever is met first) to each slice in a shard. For example, consider a shard with 11 segments. The first 5 segments have 250K documents each, and the next 6 segments have 20K documents each. The first 5 segments will be assigned to 1 slice each because they each contain the maximum number of documents allowed for a slice. Then the next 5 segments will all be assigned to another single slice because of the maximum allowed segment count for a slice. The 11th slice will be assigned to a separate slice. ### Setting the slicing mechanism -By default, concurrent segment search uses the Lucene mechanism to calculate the number of slices for each shard-level request. To use the max slice count mechanism instead, configure the `search.concurrent.max_slice_count` static setting in the `opensearch.yml` config file: +You can set the slicing mechanism at the cluster level or index level by updating the `search.concurrent.max_slice_count` setting. -```yaml -search.concurrent.max_slice_count: 2 -``` -{% include copy.html %} +Both the cluster- and index-level `search.concurrent.max_slice_count` settings can take the following valid values: -The `search.concurrent.max_slice_count` setting can take the following valid values: -- `0`: Use the default Lucene mechanism. - Positive integer: Use the max target slice count mechanism. Usually, a value between 2 and 8 should be sufficient. +- `0`: Use the Lucene mechanism. + +To configure the slice count for all indexes in a cluster, use the following dynamic cluster setting: + +```json +PUT _cluster/settings +{ + "persistent":{ + "search.concurrent.max_slice_count": 2 + } +} +``` +{% include copy-curl.html %} + +To configure the slice count for a particular index, specify the index name in the endpoint: + +```json +PUT {index-name}/_settings +{ + "index.search.concurrent.max_slice_count": 2 +} +``` +{% include copy-curl.html %} + +## General guidelines + +Concurrent segment search helps to improve the performance of search requests at the cost of consuming more resources, such as CPU or JVM heap. It is important to test your workload in order to understand whether the cluster is sized correctly for concurrent segment search. We recommend adhering to the following concurrent segment search guidelines: + +* Start with a slice count of 2 and measure the performance of your workload. If resource utilization exceeds the recommended values, then consider scaling your cluster. Based on our testing, we have observed that if your workload is already consuming more than 50% of your CPU resources, then you need to scale your cluster for concurrent segment search. +* If your slice count is 2 and you still have available resources in the cluster, then you can increase the slice count to a higher number, such as 4 or 6, while monitoring search latency and resource utilization in the cluster. +* When many clients send search requests in parallel, a lower slice count usually works better. This is reflected in CPU utilization because a higher number of clients leads to more queries per second, which translates to higher resource usage. + +When upgrading to OpenSearch 3.0, be aware that workloads with aggregations may experience higher CPU utilization because concurrent search is enabled by default in `auto` mode. If your OpenSearch 2.x cluster's CPU utilization exceeds 25% when running aggregation workloads, consider the following options before upgrading: + +- Plan to scale your cluster's resources to accommodate the increased CPU demand. +- Prepare to disable concurrent search if scaling is not feasible for your use case. ## Limitations The following aggregations do not support the concurrent search model. If a search request contains one of these aggregations, the request will be executed using the non-concurrent path even if concurrent segment search is enabled at the cluster level or index level. -- Parent aggregations on [join]({{site.url}}{{site.baseurl}}/field-types/supported-field-types/join/) fields. See [this GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/9316) for more information. +- Parent aggregations on [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) fields. See [this GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/9316) for more information. - `sampler` and `diversified_sampler` aggregations. See [this GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/11075) for more information. -- Composite aggregations. See [this GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/12331) for more information. ## Other considerations @@ -90,7 +182,7 @@ The following sections provide additional considerations for concurrent segment ### The `terminate_after` search parameter -The [`terminate_after` search parameter]({{site.url}}{{site.baseurl}}/api-reference/search/#url-parameters) is used to terminate a search request once a specified number of documents has been collected. If you include the `terminate_after` parameter in a request, concurrent segment search is disabled and the request is run in a non-concurrent manner. +The [`terminate_after` search parameter]({{site.url}}{{site.baseurl}}/api-reference/search/#query-parameters) is used to terminate a search request once a specified number of matching documents has been collected. If you include the `terminate_after` parameter in a request, concurrent segment search is disabled and the request is run in a non-concurrent manner. Typically, queries are used with smaller `terminate_after` values and thus complete quickly because the search is performed on a reduced dataset. Therefore, concurrent search may not further improve performance in this case. Moreover, when `terminate_after` is used with other search request parameters, such as `track_total_hits` or `size`, it adds complexity and changes the expected query behavior. Falling back to a non-concurrent path for search requests that include `terminate_after` ensures consistent results between concurrent and non-concurrent requests. @@ -105,8 +197,20 @@ Non-concurrent search calculates the document count error and returns it in the For more information about how `shard_size` can affect both `doc_count_error_upper_bound` and collected buckets, see [this GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/11680#issuecomment-1885882985). -## Developer information: AggregatorFactory changes +## Developer information -Because of implementation details, not all aggregator types can support concurrent segment search. To accommodate this, we have introduced a [`supportsConcurrentSegmentSearch()`](https://github.com/opensearch-project/OpenSearch/blob/bb38ed4836496ac70258c2472668325a012ea3ed/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactory.java#L121) method in the `AggregatorFactory` class to indicate whether a given aggregation type supports concurrent segment search. By default, this method returns `false`. Any aggregator that needs to support concurrent segment search must override this method in its own factory implementation. +The following sections provide additional information for developers. -To ensure that a custom plugin-based `Aggregator` implementation works with the concurrent search path, plugin developers can verify their implementation with concurrent search enabled and then update the plugin to override the [`supportsConcurrentSegmentSearch()`](https://github.com/opensearch-project/OpenSearch/blob/bb38ed4836496ac70258c2472668325a012ea3ed/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactory.java#L121) method to return `true`. +### AggregatorFactory changes + +Because of implementation details, not all aggregator types can support concurrent segment search. To accommodate this, we have introduced a [`supportsConcurrentSegmentSearch()`](https://github.com/opensearch-project/OpenSearch/blob/2.x/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactory.java#L123) method in the `AggregatorFactory` class to indicate whether a given aggregation type supports concurrent segment search. By default, this method returns `false`. Any aggregator that needs to support concurrent segment search must override this method in its own factory implementation. + +To ensure that a custom plugin-based `Aggregator` implementation functions with the concurrent search path, plugin developers can verify their implementation with concurrent search enabled and then update the plugin to override the [`supportsConcurrentSegmentSearch()`](https://github.com/opensearch-project/OpenSearch/blob/2.x/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactory.java#L123) method to return `true`. + +### Pluggable concurrent search deciders: ConcurrentSearchRequestDecider + +Introduced 2.17 +{: .label .label-purple } + +Plugin developers can customize the concurrent search decision-making for `auto` mode by extending [`ConcurrentSearchRequestDecider`](https://github.com/opensearch-project/OpenSearch/blob/2.x/server/src/main/java/org/opensearch/search/deciders/ConcurrentSearchRequestDecider.java) and registering its factory through [`SearchPlugin#getConcurrentSearchRequestFactories()`](https://github.com/opensearch-project/OpenSearch/blob/2.x/server/src/main/java/org/opensearch/plugins/SearchPlugin.java#L148). The deciders are evaluated only if a request does not belong to any category listed in the [Limitations](#limitations) and [Other considerations](#other-considerations) sections. For more information about the decider implementation, see [the corresponding GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/15259). +The search request is parsed using a `QueryBuilderVisitor`, which calls the [`ConcurrentSearchRequestDecider#evaluateForQuery()`](https://github.com/opensearch-project/OpenSearch/blob/2.x/server/src/main/java/org/opensearch/search/deciders/ConcurrentSearchRequestDecider.java#L36) method of all the configured deciders for every node of the `QueryBuilder` tree in the search request. The final concurrent search decision is obtained by combining the decision from each decider returned by the [`ConcurrentSearchRequestDecider#getConcurrentSearchDecision()`](https://github.com/opensearch-project/OpenSearch/blob/2.x/server/src/main/java/org/opensearch/search/deciders/ConcurrentSearchRequestDecider.java#L44) method. diff --git a/_search-plugins/cross-cluster-search.md b/_search-plugins/cross-cluster-search.md new file mode 100644 index 00000000..91305bde --- /dev/null +++ b/_search-plugins/cross-cluster-search.md @@ -0,0 +1,404 @@ +--- +layout: default +title: Cross-cluster search +nav_order: 230 +redirect_from: + - /security/access-control/cross-cluster-search/ + - /security-plugin/access-control/cross-cluster-search/ +--- + +# Cross-cluster search + +You can use cross-cluster search (CCS) in OpenSearch to search and analyze data across multiple clusters, enabling you to gain insights from distributed data sources. Cross-cluster search is available by default with the Security plugin, but you need to configure each cluster to allow remote connections from other clusters. This involves setting up remote cluster connections and configuring access permissions. + +--- + +#### Table of contents +1. TOC +{:toc} + + +--- + +## Prerequisite + +Before configuring cross-cluster search, ensure that the following prerequisite is met: + +- If you've overridden `node.roles` in `opensearch.yml` for any node in a cluster participating in cross-cluster search, ensure that the `node.roles` setting includes the `remote_cluster_client` role: + + ```yaml + node.roles: [<other_roles>, remote_cluster_client] + ``` + {% include copy.html %} + +## Authentication flow + +The following sequence describes the authentication flow when using cross-cluster search to access a *remote cluster* from a *coordinating cluster*. You can have different authentication and authorization configurations on the remote and coordinating clusters, but we recommend using the same settings on both. + +1. The Security plugin authenticates the user on the coordinating cluster. +1. The Security plugin fetches the user's backend roles on the coordinating cluster. +1. The call, including the authenticated user, is forwarded to the remote cluster. +1. The user's permissions are evaluated on the remote cluster. + +## Remote cluster role evaluation +**Introduced 3.9** +{: .label .label-purple } + +By default, the remote cluster evaluates permissions using a combination of the security roles propagated from the coordinating cluster and its own role mappings. As a result, a user who has broad permissions on the coordinating cluster (for example, `all_access`) receives those same permissions on the remote cluster. + +To give the remote cluster independent control over the permissions that CCS users receive, set the following cluster setting on the remote cluster: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.security.ccs.ignore_source_security_roles": true + } +} +``` +{% include copy-curl.html %} + +When `plugins.security.ccs.ignore_source_security_roles` is `true`, the remote cluster strips the security roles propagated from the coordinating cluster and evaluates access exclusively through its own `roles_mapping.yml` configuration. You can then define CCS user permissions independently on each cluster. The setting is `false` by default, so existing CCS deployments are unaffected. + +### Limitations + +The setting has the following limitations: + +- The remote cluster doesn't re-authenticate CCS users, so it doesn't consult the role assignments in `internal_users.yml`. When this setting is enabled, you must use `roles_mapping.yml` to grant CCS users access to the remote cluster. Role assignments made using `opendistro_security_roles` in `internal_users.yml` have no effect on CCS user authorization. +- The setting applies only to cross-cluster search requests. Other cross-cluster operations aren't affected. + +## Setting permissions + +To query indexes on remote clusters, users must have `READ` or `SEARCH` permissions. Furthermore, when the search request includes the query parameter `ccs_minimize_roundtrips=false`---which tells OpenSearch not to minimize outgoing and incoming requests to remote clusters---users need to have the following additional index permission: + +``` +indices:admin/shards/search_shards +``` + +For more information about the `ccs_minimize_roundtrips` parameter, see the list of [parameters]({{site.url}}{{site.baseurl}}/api-reference/search/#query-parameters) for the Search API. + +#### Example roles.yml configuration + +```yml +humanresources: + cluster: + - CLUSTER_COMPOSITE_OPS_RO + indices: + 'humanresources': + '*': + - READ + - indices:admin/shards/search_shards # needed when the search request includes parameter setting 'ccs_minimize_roundtrips=false'. +``` + + +#### Example role in OpenSearch Dashboards + +![OpenSearch Dashboards panel for creating a cross-cluster search role]({{site.url}}{{site.baseurl}}/images/security-ccs.png) + + +## Sample Docker setup + +To define Docker permissions, save the following sample file as `docker-compose.yml` and run `docker compose up` to start two single-node clusters on the same network: + +```yml +version: '3' +services: + opensearch-ccs-node1: + image: opensearchproject/opensearch:{{site.opensearch_version}} + container_name: opensearch-ccs-node1 + environment: + - cluster.name=opensearch-ccs-cluster1 + - discovery.type=single-node + - bootstrap.memory_lock=true # along with the memlock settings below, disables swapping + - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM + - "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" # The initial admin password used by the demo configuration + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - opensearch-data1:/usr/share/opensearch/data + ports: + - 9200:9200 + networks: + - opensearch-net + + opensearch-ccs-node2: + image: opensearchproject/opensearch:{{site.opensearch_version}} + container_name: opensearch-ccs-node2 + environment: + - cluster.name=opensearch-ccs-cluster2 + - discovery.type=single-node + - bootstrap.memory_lock=true # along with the memlock settings below, disables swapping + - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM + - "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" # The initial admin password used by the demo configuration + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - opensearch-data2:/usr/share/opensearch/data + ports: + - 9250:9200 + networks: + - opensearch-net + +volumes: + opensearch-data1: + opensearch-data2: + +networks: + opensearch-net: +``` + +After the clusters start, verify the names of each cluster using the following commands: + +```json +curl -XGET -u 'admin:<custom-admin-password>' -k 'https://localhost:9200' +{ + "cluster_name" : "opensearch-ccs-cluster1", + ... +} + +curl -XGET -u 'admin:<custom-admin-password>' -k 'https://localhost:9250' +{ + "cluster_name" : "opensearch-ccs-cluster2", + ... +} +``` + +Both clusters run on `localhost`, so the important identifier is the port number. In this case, use port 9200 (`opensearch-ccs-node1`) as the remote cluster, and port 9250 (`opensearch-ccs-node2`) as the coordinating cluster. + +To get the IP address for the remote cluster, first identify its container ID: + +```bash +docker ps +CONTAINER ID IMAGE PORTS NAMES +6fe89ebc5a8e opensearchproject/opensearch:{{site.opensearch_version}} 0.0.0.0:9200->9200/tcp, 9600/tcp, 9300/tcp opensearch-ccs-node1 +2da08b6c54d8 opensearchproject/opensearch:{{site.opensearch_version}} 9300/tcp, 0.0.0.0:9250->9200/tcp, 9600/tcp opensearch-ccs-node2 +``` + +Then get that container's IP address: + +```bash +docker inspect --format='{% raw %}{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}{% endraw %}' 6fe89ebc5a8e +172.31.0.3 +``` + +On the coordinating cluster, add the remote cluster name and the IP address (with port 9300) for each "seed node." In this case, you only have one seed node: + +```json +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://localhost:9250/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-ccs-cluster1": { + "seeds": ["172.31.0.3:9300"] + } + } + } +}' +``` +All of the cURL requests can also be sent using OpenSearch Dashboards Dev Tools. +{: .tip } +The following image shows an example of a cURL request using Dev Tools. +![OpenSearch Dashboards Dev Tools request for configuring remote cluster for Cross-cluster search]({{site.url}}{{site.baseurl}}/images/ccs-devtools.png) + +On the remote cluster, index a document: + +```bash +curl -XPUT -k -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://localhost:9200/books/_doc/1' -d '{"Dracula": "Bram Stoker"}' +``` + +At this point, cross-cluster search works. You can test it using the `admin` user: + +```bash +curl -XGET -k -u 'admin:<custom-admin-password>' 'https://localhost:9250/opensearch-ccs-cluster1:books/_search?pretty' +{ + ... + "hits": [{ + "_index": "opensearch-ccs-cluster1:books", + "_id": "1", + "_score": 1.0, + "_source": { + "Dracula": "Bram Stoker" + } + }] +} +``` + +To continue testing, create a new user on both clusters: + +```bash +curl -XPUT -k -u 'admin:<custom-admin-password>' 'https://localhost:9200/_plugins/_security/api/internalusers/booksuser' -H 'Content-Type: application/json' -d '{"password":"password"}' +curl -XPUT -k -u 'admin:<custom-admin-password>' 'https://localhost:9250/_plugins/_security/api/internalusers/booksuser' -H 'Content-Type: application/json' -d '{"password":"password"}' +``` + +Then run the same search as before with `booksuser`: + +```json +curl -XGET -k -u booksuser:password 'https://localhost:9250/opensearch-ccs-cluster1:books/_search?pretty' +{ + "error" : { + "root_cause" : [ + { + "type" : "security_exception", + "reason" : "no permissions for [indices:admin/shards/search_shards, indices:data/read/search] and User [name=booksuser, roles=[], requestedTenant=null]" + } + ], + "type" : "security_exception", + "reason" : "no permissions for [indices:admin/shards/search_shards, indices:data/read/search] and User [name=booksuser, roles=[], requestedTenant=null]" + }, + "status" : 403 +} +``` + +Note the permissions error. On the remote cluster, create a role with the appropriate permissions, and map `booksuser` to that role: + +```bash +curl -XPUT -k -u 'admin:<custom-admin-password>' -H 'Content-Type: application/json' 'https://localhost:9200/_plugins/_security/api/roles/booksrole' -d '{"index_permissions":[{"index_patterns":["books"],"allowed_actions":["indices:admin/shards/search_shards","indices:data/read/search"]}]}' +curl -XPUT -k -u 'admin:<custom-admin-password>' -H 'Content-Type: application/json' 'https://localhost:9200/_plugins/_security/api/rolesmapping/booksrole' -d '{"users" : ["booksuser"]}' +``` + +Both clusters must have the user role, but only the remote cluster needs both the role and mapping. In this case, the coordinating cluster handles authentication (that is, "Does this request include valid user credentials?"), and the remote cluster handles authorization (that is, "Can this user access this data?"). +{: .tip } + +Finally, repeat the search: + +```bash +curl -XGET -k -u booksuser:password 'https://localhost:9250/opensearch-ccs-cluster1:books/_search?pretty' +{ + ... + "hits": [{ + "_index": "opensearch-ccs-cluster1:books", + "_id": "1", + "_score": 1.0, + "_source": { + "Dracula": "Bram Stoker" + } + }] +} +``` + +## Sample bare metal/virtual machine setup + +If you are running OpenSearch on a bare metal server or using a virtual machine, you can run the same commands, specifying the IP (or domain) of the OpenSearch cluster. +For example, in order to configure a remote cluster for cross-cluster search, find the IP of the remote node or domain of the remote cluster and run the following command: + +```json +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://opensearch-domain-1:9200/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-ccs-cluster2": { + "seeds": ["opensearch-domain-2:9300"] + } + } + } +}' +``` +It is sufficient to point to only one of the node IPs on the remote cluster because all nodes in the cluster will be queried as part of the node discovery process. +{: .tip } + +You can now run queries across both clusters: + +```bash +curl -XGET -k -u 'admin:<custom-admin-password>' 'https://opensearch-domain-1:9200/opensearch-ccs-cluster2:books/_search?pretty' +{ + ... + "hits": [{ + "_index": "opensearch-ccs-cluster2:books", + "_id": "1", + "_score": 1.0, + "_source": { + "Dracula": "Bram Stoker" + } + }] +} +``` + +## Sample Kubernetes/Helm setup +If you are using Kubernetes clusters to deploy OpenSearch, you need to configure the remote cluster using either the `LoadBalancer` or `Ingress`. The Kubernetes services created using the following [Helm]({{site.url}}{{site.baseurl}}/install-and-configure/install-opensearch/helm/) example are of the `ClusterIP` type and are only accessible from within the cluster; therefore, you must use an externally accessible endpoint: + +```bash +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://opensearch-domain-1:9200/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-ccs-cluster2": { + "seeds": ["ingress:9300"] + } + } + } +}' +``` + +## Proxy settings + +You can configure cross-cluster search on a cluster running behind a proxy. There are many ways to configure a reverse proxy and various proxies to choose from. The following example demonstrates the basic NGINX reverse proxy configuration without TLS termination, though there are many proxies and reverse proxies to choose from. For this example to work, OpenSearch must have both transport and HTTP TLS encryption enabled. For more information about configuring TLS encryption, see [Configuring TLS certificates]({{site.url}}{{site.baseurl}}/security/configuration/tls/). + +### Prerequisites + +To use proxy mode, fulfill the following prerequisites: + +- Make sure that the source cluster's nodes are able to connect to the configured `proxy_address`. +- Make sure that the proxy can route connections to the remote cluster nodes. + +### Proxy configuration + +The following is the basic NGINX configuration for HTTP and transport communication: + +``` +stream { + upstream opensearch-transport { + server <opensearch>:9300; + } + upstream opensearch-http { + server <opensearch>:9200; + } + server { + listen 8300; + ssl_certificate /.../{{site.opensearch_version}}/config/esnode.pem; + ssl_certificate_key /.../{{site.opensearch_version}}/config/esnode-key.pem; + ssl_trusted_certificate /.../{{site.opensearch_version}}/config/root-ca.pem; + proxy_pass opensearch-transport; + ssl_preread on; + } + server { + listen 443; + listen [::]:443; + ssl_certificate /.../{{site.opensearch_version}}/config/esnode.pem; + ssl_certificate_key /.../{{site.opensearch_version}}/config/esnode-key.pem; + ssl_trusted_certificate /.../{{site.opensearch_version}}/config/root-ca.pem; + proxy_pass opensearch-http; + ssl_preread on; + } +} +``` + +The listening ports for HTTP and transport communication are set to `443` and `8300`, respectively. + +### OpenSearch configuration + +The remote cluster can be configured to point to the `proxy` by using the following command: + +```bash +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://opensearch:9200/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-remote-cluster": { + "mode": "proxy", + "proxy_address": "<remote-cluster-proxy>:8300" + } + } + } +}' +``` + +Note the previously configured port `8300` in the [Proxy configuration]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/#proxy-configuration) section. + +## Related documentation + +- To query remote clusters using PPL in Event analytics or in an Observability workspace, see [Using observability apps for cross-cluster search]({{site.url}}{{site.baseurl}}/observing-your-data/cross-cluster-search/). +- To obtain information about the remote clusters connected to a cluster, see [Remote cluster information]({{site.url}}{{site.baseurl}}/api-reference/cluster-api/remote-info/). diff --git a/_search-plugins/filter-search.md b/_search-plugins/filter-search.md new file mode 100644 index 00000000..0f6455c9 --- /dev/null +++ b/_search-plugins/filter-search.md @@ -0,0 +1,140 @@ +--- +layout: default +title: Filter results +parent: Customizing search results +nav_order: 36 +--- + +# Filter search results + +You can filter searches using different methods, each suited to specific scenarios. You can apply filters at the query level, using `boolean` query clauses and `post_filter` and `aggregation` level filters, as follows: + +- **Query-level filtering:** Apply `boolean` query filter clauses to filter search hits and aggregations, such as to narrow results to specific categories or brands. +- **Post-filter filtering:** Use `post_filter` to refine search hits based on user selections while preserving all aggregation options. +- **Aggregation-level filtering:** Adjust specific aggregations based on selected filters without impacting other aggregations. + +## Query-level filtering with Boolean queries + +Use a `boolean` query with a filter clause to apply filters to both search hits and aggregations. For example, if a shopper searches for `smartphones` from `BrandA`, a Boolean query can restrict results to only those smartphones from `BrandA`. The following steps guide you through query-level filtering. + +1. Create an index `electronics` and provide the mapping using the following request: + +```json +PUT /electronics +{ + "mappings": { + "properties": { + "brand": { "type": "keyword" }, + "category": { "type": "keyword" }, + "price": { "type": "float" }, + "features": { "type": "keyword" } + } + } +} +``` +{% include copy-curl.html %} + +2. Add documents to the `electronics` index using the following request: + +```json +POST /_bulk?refresh +{ "index": { "_index": "electronics", "_id": "1" } } +{ "brand": "BrandA", "category": "Smartphone", "price": 699.99, "features": ["5G", "Dual Camera"] } +{ "index": { "_index": "electronics", "_id": "2" } } +{ "brand": "BrandA", "category": "Laptop", "price": 1199.99, "features": ["Touchscreen", "16GB RAM"] } +{ "index": { "_index": "electronics", "_id": "3" } } +{ "brand": "BrandB", "category": "Smartphone", "price": 799.99, "features": ["5G", "Triple Camera"] } +``` +{% include copy-curl.html %} + +3. Apply a `boolean` filter query to display only `smartphones` from `BrandA` using the following request: + +```json +GET /electronics/_search +{ + "query": { + "bool": { + "filter": [ + { "term": { "brand": "BrandA" }}, + { "term": { "category": "Smartphone" }} + ] + } + } +} +``` +{% include copy-curl.html %} + +## Narrowing results using `post-filter` while preserving aggregation visibility + +Use `post_filter` to limit search hits while preserving all aggregation options. For example, if a shopper selects `BrandA`, results are filtered to show only `BrandA` products while maintaining the visibility of all brand options in the aggregations, as shown in the following example request: + +```json +GET /electronics/_search +{ + "query": { + "bool": { + "filter": { "term": { "category": "Smartphone" }} + } + }, + "aggs": { + "brands": { + "terms": { "field": "brand" } + } + }, + "post_filter": { + "term": { "brand": "BrandA" } + } +} +``` +{% include copy-curl.html %} + +The result should show `BrandA` smartphones in the search hits and all brands in the aggregations. + +To keep facet options visible while users apply filters, combine `post_filter` with filter aggregations. For more information, see [Maintaining facet options during filtering]({{site.url}}{{site.baseurl}}/tutorials/faceted-search/#maintaining-facet-options-during-filtering). + +## Refining aggregations with aggregation-level filtering + +You can use aggregation-level filtering to apply filters to specific aggregations without affecting the main aggregation to which they belong. + +For example, you can use aggregation-level filtering to filter the `price_ranges` aggregation based on selected brands, `BrandA` and `BrandB`, without affecting the main `price_ranges` aggregation, as shown in the following example request. This displays price ranges relevant to the selected brands while also displaying overall price ranges for all products. + +```json +GET /electronics/_search +{ + "query": { + "bool": { + "filter": { "term": { "category": "Smartphone" }} + } + }, + "aggs": { + "price_ranges": { + "range": { + "field": "price", + "ranges": [ + { "to": 500 }, + { "from": 500, "to": 1000 }, + { "from": 1000 } + ] + } + }, + "filtered_brands": { + "filter": { + "terms": { "brand": ["BrandA", "BrandB"] } + }, + "aggs": { + "price_ranges": { + "range": { + "field": "price", + "ranges": [ + { "to": 500 }, + { "from": 500, "to": 1000 }, + { "from": 1000 } + ] + } + } + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_search-plugins/improving-search-performance.md b/_search-plugins/improving-search-performance.md index 4a0ffafe..f0aa8150 100644 --- a/_search-plugins/improving-search-performance.md +++ b/_search-plugins/improving-search-performance.md @@ -3,12 +3,21 @@ layout: default title: Improving search performance nav_order: 220 has_children: true +has_toc: false --- # Improving search performance -OpenSearch offers several ways to improve search performance: +OpenSearch offers several ways to improve search performance, from foundational optimizations to specialized techniques: -- Run resource-intensive queries asynchronously with [asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/). +- Store frequently accessed data in memory with [caching]({{site.url}}{{site.baseurl}}/search-plugins/caching/) for faster retrieval. -- Search segments concurrently using [concurrent segment search]({{site.url}}{{site.baseurl}}/search-plugins/concurrent-segment-search/). \ No newline at end of file +- Search segments concurrently using [concurrent segment search]({{site.url}}{{site.baseurl}}/search-plugins/concurrent-segment-search/) for better resource utilization. + +- Control shard selection for optimized query routing with [search shard routing]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/search-shard-routing/). + +- Skip indexes that cannot contain matching documents using [index-level search pruning]({{site.url}}{{site.baseurl}}/search-plugins/index-level-search-pruning/) for time-series workloads. + +- Run resource-intensive queries asynchronously with [asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/) to avoid timeouts. + +- Improve aggregation performance using a [star-tree index]({{site.url}}{{site.baseurl}}/search-plugins/star-tree-index/) for analytical workloads. diff --git a/_search-plugins/index-level-search-pruning.md b/_search-plugins/index-level-search-pruning.md new file mode 100644 index 00000000..98d51eab --- /dev/null +++ b/_search-plugins/index-level-search-pruning.md @@ -0,0 +1,86 @@ +--- +layout: default +title: Index-level search pruning +parent: Improving search performance +nav_order: 35 +has_children: false +--- + +# Index-level search pruning +**Introduced 3.9** +{: .label .label-purple } + +Index-level search pruning lets OpenSearch rule out whole indexes before it sends requests to their shards. + +Consider a time-series workload in which `logs-*` expands to 90 daily indexes and a dashboard queries the last 5 minutes. OpenSearch initially considers the shards of all 90 indexes. The `can_match` phase filters out shards that cannot hold a matching document, but it determines this by sending a request to each shard, so the search still requires a round trip per shard, even though only one of the 90 indexes can hold matching documents. + +Index-level search pruning makes this determination on the coordinating node. If an index has a recorded range for the queried field---for example, `logs-2026-06-01` holds only timestamps from June 1---OpenSearch excludes that index from a query for the last 5 minutes without sending a request to any of its shards. + +Pruning depends on the recorded range, called a _field domain_. A field domain contains the minimum and maximum values for a `date` or `date_nanos` field in an index, so it is always a time range. For `@timestamp` in a daily index, the field domain is the earliest and latest timestamp in that index. OpenSearch stores each field domain in cluster state, which the coordinating node already keeps in memory, so it can compare ranges locally. + +Because a field domain is a snapshot of an index's values, it is valid only while the index remains write blocked. If an index still accepted writes, a new document could fall outside the field domain, and pruning would skip an index that holds matching documents, silently dropping results from the search. This makes pruning particularly useful for time-series data, where older indexes are typically write blocked after rollover. + +A _shard group_ is the set of copies of one shard that a search can target, including a primary shard and its replicas. A search reads from one copy in each group. For example, an index with 5 primary shards and 1 replica per shard has 10 shard copies but 5 shard groups. Pruning skips the shard groups of indexes whose field domains fall entirely outside the query's range. When an index has no field domain or its field domain is unusable, OpenSearch searches the shard group. + + +## Configuring search pruning + +To use pruning, first enable the cluster settings. Then publish field domains for the indexes that you want to prune. + +### Enabling search pruning + +Index-level search pruning is disabled by default. To enable it, configure the pruning settings using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "persistent": { + "search.index_pruning.enabled": true, + "search.index_pruning.min_shards": 32, + "search.index_pruning.fields": ["@timestamp"] + } +} +``` +{% include copy-curl.html %} + +For more information about pruning settings, see [Search settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/search-settings/#index-pruning-settings). + +### Publishing field domains + +Each index that you want OpenSearch to prune must have a field domain for the field that your queries filter on, and that field must be listed in `search.index_pruning.fields`. To publish one, add the Index State Management (ISM) [`publish_field_domains`]({{site.url}}{{site.baseurl}}/im-plugin/ism/policies-operations/#publish-field-domains) action to a policy state, after a `read_only` action. ISM then computes the field's minimum and maximum values for that index and stores them. + +Publish field domains only for indexes that remain write blocked. +{: .important} + +## Limitations + +Pruning does not apply to searches that use Point in Time (PIT) or to shard groups on remote clusters. As a result, pruning does not reduce the number of remote shard groups searched in a cross-cluster search. + +If pruning would exclude every shard group, OpenSearch searches all shard groups instead. + +## Query constraints + +Pruning applies to `range` queries in `must` and `filter` clauses on the configured fields. Optional and negative clauses, such as `should` and `must_not`, do not trigger pruning because matching documents are not required to satisfy them. + +The following query is eligible for pruning when `@timestamp` is configured in `search.index_pruning.fields`. OpenSearch resolves date math expressions, such as `now-2m`, once (at the request start time) and uses that value for every index it evaluates: + +```json +GET logs-*/_search +{ + "query": { + "bool": { + "filter": [ + { + "range": { + "@timestamp": { + "gte": "now-2m", + "lte": "now" + } + } + } + ] + } + } +} +``` +{% include copy-curl.html %} diff --git a/_search-plugins/index.md b/_search-plugins/index.md index fca30667..0820012d 100644 --- a/_search-plugins/index.md +++ b/_search-plugins/index.md @@ -8,79 +8,57 @@ nav_exclude: true permalink: /search-plugins/ redirect_from: - /search-plugins/index/ +search_methods: + - heading: "Keyword (BM25) search" + description: "Lexical text search using the BM25 algorithm to match and rank documents based on term frequency and document length. Find exact and close matches using traditional text search." + link: "/search-plugins/keyword-search/" + - heading: "Vector search" + description: "Similarity (k-nearest neighbor) search using dense and sparse vector embeddings to power semantic search, retrieval-augmented generation, and multimodal image search." + link: "/vector-search/" + - heading: "AI search" + description: "AI-powered search capabilities beyond vector embeddings. Enrich search and ingestion flows with any AI service to power the full range of AI-enhanced search use cases." + link: "/vector-search/ai-search/" --- # Search -OpenSearch provides many features for customizing your search use cases and improving search relevance. +OpenSearch supports keyword (BM25) search, vector search, and AI-powered search, along with tools for tuning relevance, reranking results, and building custom search pipelines. ## Search methods -OpenSearch supports the following search methods: +OpenSearch supports multiple search methods to meet different use cases and requirements. -- **Traditional lexical search** - - - [Keyword (BM25) search]({{site.url}}{{site.baseurl}}/search-plugins/keyword-search/): Searches the document corpus for words that appear in the query. - -- **Machine learning (ML)-powered search** - - - **Vector search** - - - [k-NN search]({{site.url}}{{site.baseurl}}/search-plugins/knn/): Searches for k-nearest neighbors to a search term across an index of vectors. - - - **Neural search**: [Neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/) facilitates generating vector embeddings at ingestion time and searching them at search time. Neural search lets you integrate ML models into your search and serves as a framework for implementing other search methods. The following search methods are built on top of neural search: - - - [Semantic search]({{site.url}}{{site.baseurl}}/search-plugins/semantic-search/): Considers the meaning of the words in the search context. Uses dense retrieval based on text embedding models to search text data. - - - [Multimodal search]({{site.url}}{{site.baseurl}}/search-plugins/multimodal-search/): Uses multimodal embedding models to search text and image data. - - - [Neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/): Uses sparse retrieval based on sparse embedding models to search text data. - - - [Hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/hybrid-search/): Combines traditional search and vector search to improve search relevance. - - - [Conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/): Implements a retrieval-augmented generative search. +{% include cards.html cards=page.search_methods %} ## Query languages -In OpenSearch, you can use the following query languages to search your data: +In OpenSearch, you can use the following query languages to retrieve your data. -- [Query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/index/): The primary OpenSearch query language that supports creating complex, fully customizable queries. +Language | Where you can use it | Description +:--- | :--- | :--- +[Query domain-specific language (DSL)]({{site.url}}{{site.baseurl}}/query-dsl/index/) | Search API, Dev Tools | The primary OpenSearch query language that supports creating complex, fully customizable queries. +[Query string query language]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/) | Search API `q` parameter, Discover and Dashboard search bar | A scaled-down query language whose syntax is based on Apache Lucene. +[SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/sql/index/) | SQL API, Query Workbench | A traditional query language that bridges the gap between relational database concepts and the flexibility of OpenSearch's document-oriented data storage. +[Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/) | PPL API, Query Workbench | The primary language used with observability in OpenSearch. PPL uses a pipe syntax that chains commands into a query. -- [Query string query language]({{site.url}}{{site.baseurl}}/query-dsl/full-text/query-string/): A scaled-down query language that you can use in a query parameter of a search request or in OpenSearch Dashboards. +For information about querying data in OpenSearch Dashboards, including the Dashboards Query Language (DQL), see [Analyzing data with Discover]({{site.url}}{{site.baseurl}}/dashboards/discover/index-discover/). -- [SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/sql/index/): A traditional query language that bridges the gap between traditional relational database concepts and the flexibility of OpenSearch’s document-oriented data storage. +## Customizing search results -- [Piped Processing Language (PPL)]({{site.url}}{{site.baseurl}}/search-plugins/sql/ppl/index/): The primary language used with observability in OpenSearch. PPL uses a pipe syntax that chains commands into a query. +OpenSearch provides fundamental result handling capabilities that work with all search types. You can customize result navigation (pagination, sorting), result formatting (highlighting, field selection), query enhancement (autocomplete, did-you-mean), and result filtering. For more information, see [Customizing search results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/). -- [Dashboards Query Language (DQL)]({{site.url}}{{site.baseurl}}/dashboards/dql/): A simple text-based query language for filtering data in OpenSearch Dashboards. +## Optimizing search quality -## Search performance - -OpenSearch offers several ways to improve search performance: - -- [Asynchronous search]({{site.url}}{{site.baseurl}}/search-plugins/async/): Runs resource-intensive queries asynchronously. - -- [Concurrent segment search]({{site.url}}{{site.baseurl}}/search-plugins/concurrent-segment-search/): Searches segments concurrently. - -## Search relevance - -OpenSearch provides the following search relevance features: - -- [Compare Search Results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-search-results/): A search comparison tool in OpenSearch Dashboards that you can use to compare results from two queries side by side. - -- [Querqy]({{site.url}}{{site.baseurl}}/search-plugins/querqy/): Offers query rewriting capability. - -## Search results - -OpenSearch supports the following commonly used operations on search results: - -- [Paginate]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/) -- [Paginate with Point in Time]({{site.url}}{{site.baseurl}}/search-plugins/point-in-time/) -- [Sort]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/) -- [Highlight search terms]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) -- [Autocomplete]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/) -- [Did-you-mean]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/) +OpenSearch provides comprehensive tools and features to help you measure, analyze, and improve the quality of your search results. These integrated features work together to optimize search relevance based on user behavior and machine learning. For more information, see [Optimizing search quality]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/). ## Search pipelines -You can process search queries and search results with [search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/). +Search pipelines are the foundational infrastructure that enables OpenSearch's AI and vector search capabilities. They provide modular processors that can transform queries (text-to-vector conversion, ML inference, query rewriting), enhance results (reranking, RAG, field manipulation), and orchestrate complex AI workflows. For more information, see [Search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/). + +## Improving search performance + +OpenSearch provides various features to optimize search performance from foundational caching techniques to specialized optimizations. For more information, see [Improving search performance]({{site.url}}{{site.baseurl}}/search-plugins/improving-search-performance/). + +## Cross-cluster search + +OpenSearch supports searching across multiple clusters to scale your search infrastructure for large deployments. For more information, see [Cross-cluster search]({{site.url}}{{site.baseurl}}/search-plugins/cross-cluster-search/). diff --git a/_search-plugins/keyword-search.md b/_search-plugins/keyword-search.md index 25055ead..f23aa9c2 100644 --- a/_search-plugins/keyword-search.md +++ b/_search-plugins/keyword-search.md @@ -118,8 +118,27 @@ The following table lists the supported similarity algorithms. Algorithm | Description `BM25` | The default OpenSearch [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) similarity algorithm. +`LegacyBM25` (Deprecated) | The older [LegacyBM25Similarity](https://github.com/opensearch-project/OpenSearch/blob/main/server/src/main/java/org/opensearch/lucene/similarity/LegacyBM25Similarity.java) implementation. Kept for backward compatibility. `boolean` | Assigns terms a score equal to their boost value. Use `boolean` similarity when you want the document scores to be based on the binary value of whether the terms match. + +### Important changes to BM25 scoring in OpenSearch 3.0 + +In OpenSearch 3.0, the default similarity algorithm changed from `LegacyBM25Similarity` to Lucene's native `BM25Similarity`. + +This change improves alignment with Lucene standards and simplifies scoring behavior, but it introduces an important difference: + +- In `LegacyBM25Similarity`, scores included an extra constant factor of `k₁ + 1` in the numerator of the `BM25` formula. + +- In `BM25Similarity`, this constant was removed for cleaner normalization (see [BM25](https://en.wikipedia.org/wiki/Okapi_BM25) and the corresponding [Lucene GitHub issue](https://github.com/apache/lucene/issues/9609)). + +- Scores produced by `BM25Similarity` are lower than those produced by `LegacyBM25Similarity`, typically by a factor of about `2.2`. + +- Ranking is unaffected because the constant factor does not change the relative order of documents. + +- To retain the old scoring behavior, explicitly configure your field or index to use `LegacyBM25` (see [Configuring legacy BM25 similarity](#configuring-legacy-bm25-similarity)). + + ## Specifying similarity You can specify the similarity algorithm in the `similarity` parameter when configuring mappings at the field level. @@ -173,6 +192,29 @@ Parameter | Data type | Description `b` | Float | Determines the degree to which document length normalizes TF values. The default value is `0.75`. `discount_overlaps` | Boolean | Determines whether overlap tokens (tokens with zero position increment) are ignored when computing the norm. Default is `true` (overlap tokens do not count when computing the norm). + +## Configuring legacy BM25 similarity + +If you want to retain the older similarity behavior, specify `LegacyBM25` as the similarity `type`: + +```json +PUT /testindex +{ + "settings": { + "index": { + "similarity": { + "default": { + "type": "LegacyBM25", + "k1": 1.2, + "b": 0.75 + } + } + } + } +} +``` +{% include copy-curl.html %} + --- ## Next steps diff --git a/_search-plugins/ltr/advanced-functionality.md b/_search-plugins/ltr/advanced-functionality.md new file mode 100644 index 00000000..1ea54bcc --- /dev/null +++ b/_search-plugins/ltr/advanced-functionality.md @@ -0,0 +1,560 @@ +--- +layout: default +title: Advanced functionality +nav_order: 80 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Advanced LTR functionality + +OpenSearch Learning to Rank (LTR) offers additional functionality. It is recommended that you have a foundational understanding of OpenSearch LTR before working with these features. + +## Reusable features + +[Building features]({{site.url}}{{site.baseurl}}/search-plugins/ltr/working-with-features/) involves uploading a list of features. To avoid repeating common features across multiple sets, you can maintain a library of reusable features. + +For example, if a title field query is frequently used in your feature sets, then you can create a reusable title query using the feature API: + +```json + POST _ltr/_feature/titleSearch + { + "feature": + { + "params": [ + "keywords" + ], + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + } +``` +{% include copy-curl.html %} + +Normal CRUD operations apply, so you can delete a feature by using the following operation: + +```json +DELETE _ltr/_feature/titleSearch +``` +{% include copy-curl.html %} + + +To fetch an individual feature, you can use the following request: + +```json +GET _ltr/_feature/titleSearch +``` +{% include copy-curl.html %} + +To view a list of all features filtered by name prefix, you can use the following request: + +```json +GET /_ltr/_feature?prefix=t +``` +{% include copy-curl.html %} + +To create or update a feature set, you can refer to the `titleSearch` feature by using the following request: + +```json +POST /_ltr/_featureset/my_featureset/_addfeatures/titleSearch +``` +{% include copy-curl.html %} + +This adds the `titleSearch` feature to the next ordinal position within the `my_featureset` feature set. + +## Derived features + +Derived features are those that build upon other features. These can be expressed as [Lucene expressions](http://lucene.apache.org/core/{{site.lucene_version}}/expressions/index.html?org/apache/lucene/expressions/js/package-summary.html) and are identified by the `"template_language": "derived_expression"`. + +Additionally, derived features can accept query-time variables of type [`Number`](https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html), as described in [Creating feature sets]({{site.url}}{{site.baseurl}}/search-plugins/ltr/working-with-features#creating-feature-sets). + +### Script features + +Script features are a type of [derived feature](#derived-features). These features have access to the `feature_vector`, but they are implemented as native or Painless OpenSearch scripts rather than as [Lucene +expressions](http://lucene.apache.org/core/{{site.lucene_version}}/expressions/index.html?org/apache/lucene/expressions/js/package-summary.html). + +To identify these features, set the `"template_language": "script_feature""`. The custom script can access the `feature_vector` through the [Java Map](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html), as described in [Create a feature set]({{site.url}}{{site.baseurl}}/search-plugins/ltr/working-with-features#creating-feature-sets). + +Script-based features may impact the performance of your OpenSearch cluster, so it is best to avoid them if you require highly performant queries. +{: .warning} + +### Script feature parameters + +Script features are native or Painless scripts within the context of LTR. For more information, see [Painless scripting language]({{site.url}}{{site.baseurl}}/scripting/painless/). These script features can accept parameters as described in the [OpenSearch script documentation]({{site.url}}{{site.baseurl}}/api-reference/script-apis/index/). When working with LTR scripts, you can override parameter values and names. The priority for parameterization, in increasing order, is as follows: + +- The parameter name and value are passed directly to the source script, but not in the LTR script parameters. These cannot be configured at query time. +- The parameter name is passed to both the `sltr` query and the source script, allowing the script parameter values to be overridden at query time. +- The LTR script parameter name to native script parameter name indirection allows you to use different parameter names in your LTR feature definition than those in the underlying native script. This gives you flexibility in how you define and use scripts within the LTR context. + +For example, to set up a customizable way to rank movies in search results, considering both the title match and other adjustable factors, you can use the following request: + +```json +POST _ltr/_featureset/more_movie_features +{ + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{{keywords}}" + } + } + }, + { + "name": "custom_title_query_boost", + "params": [ + "some_multiplier", + "ltr_param_foo" + ], + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "(long)params.default_param * params.feature_vector.get('title_query') * (long)params.some_multiplier * (long) params.param_foo", + "params": { + "default_param": 10, + "some_multiplier": "some_multiplier", + "extra_script_params": { + "ltr_param_foo": "param_foo" + } + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +## Multiple feature stores + +A feature store corresponds to an independent LTR system, including features, feature sets, and models backed by a single index and cache. A feature store typically represents a single search problem or application, like Wikipedia or Wiktionary. To use multiple feature stores in your OpenSearch cluster, you can create and manage them using the provided API. + +For example, first create the `wikipedia` feature store: + +```json +PUT _ltr/wikipedia +``` +{% include copy-curl.html %} + +Then create a feature set in that store: + +```json +POST _ltr/wikipedia/_featureset/attempt_1 +{ + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +When logging features, you can specify the feature store using the `store` parameter in the `sltr` section of your query, as shown in the following example structure. If you do not provide a `store` parameter, the default store is used to look up the feature set. + +```json +{ + "sltr": { + "_name": "logged_featureset", + "featureset": "attempt_1", + "store": "wikipedia", + "params": { + "keywords": "star" + } + } +} +``` +{% include copy-curl.html %} + +To delete the feature set, you can use the following operation: + +```json +DELETE _ltr/wikipedia/_featureset/attempt_1 +``` +{% include copy-curl.html %} + +## Model caching + +The Model Caching plugin uses an internal cache for compiled models. To force the models to be recompiled, you can clear the cache for a feature store: + +```json +POST /_ltr/_clearcache +``` +{% include copy-curl.html %} + +To get cluster-wide cache statistics for a specific store, use the following request: + +```json +GET /_ltr/_cachestats +``` +{% include copy-curl.html %} + +You can control the characteristics of the internal cache by using the following node settings: + +``` +# limit cache usage to 12 megabytes (defaults to 10mb or max_heap/10 if lower) ltr.caches.max_mem: 12mb +# Evict cache entries 10 minutes after insertion (defaults to 1hour, set to 0 to disable) ltr.caches.expire_after_write: 10m +# Evict cache entries 10 minutes after access (defaults to 1hour, set to 0 to disable) ltr.caches.expire_after_read: 10m +``` +{% include copy.html %} + +## Extra logging + +As described in [Logging features]({{site.url}}{{site.baseurl}}/search-plugins/ltr/logging-features/), you can use the logging extension to return feature values with each document. For native scripts, you can also return additional arbitrary information along with the logged features. + +For native scripts, the `extra_logging` parameter is injected into the script parameters. This parameter is a [`Supplier<Map<String,Object>>`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html), which provides a non-null `Map<String,Object>` only during the logging fetch phase. Any values you add to this map are returned alongside the logged features: + +```java +{ + @Override + public double runAsDouble() { + ... + Map<String,Object> extraLoggingMap = ((Supplier<Map<String,Object>>) getParams().get("extra_logging")).get(); + if (extraLoggingMap != null) { + extraLoggingMap.put("extra_float", 10.0f); + extraLoggingMap.put("extra_string", "additional_info"); + } + ... + } +} +``` +{% include copy-curl.html %} + +If the extra logging map is accessed, it is returned as an additional entry with the logged features. The format of the logged features, including the extra logging information, will appear similar to the following example: + +```json + { + "log_entry1": [ + { + "name": "title_query", + "value": 9.510193 + }, + { + "name": "body_query", + "value": 10.7808075 + }, + { + "name": "user_rating", + "value": 7.8 + }, + { + "name": "extra_logging", + "value": { + "extra_float": 10.0, + "extra_string": "additional_info" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Feature score caching + +By default, the Feature Score Caching plugin calculates feature scores for both model inference and feature score logging. For example, if you write a query to rescore the top 100 documents and return the top 10 with feature scores, then the plugin calculates the feature scores of the top 100 documents for model inference and then calculates and logs the scores for the top 10 documents. + +The following query shows this behavior: + +```json +POST tmdb/_search +{ + "size": 10, + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "window_size" : 100, + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } + }, + "ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "rescore_index": 0 + } + } + } +} +``` +{% include copy-curl.html %} + +In some environments, it may be faster to cache the feature scores for model inference and reuse them for logging. To enable feature score caching, add the `cache: "true"` +flag to the `sltr` query that is the target of feature score logging, as shown in the following example: + +```json +{ + "sltr":{ + "cache":true, + "params":{ + "keywords":"rambo" + }, + "model":"my_model" + } +} +``` +{% include copy-curl.html %} + +## Stats + +You can use the Stats API to retrieve the plugin's overall status and statistics. To do this, send the following request: + +```json +GET /_plugins/_ltr/stats +``` +{% include copy-curl.html %} + +The response includes information about the cluster, configured stores, cache statistics for various plugin components, and request counts: + +```json +{ + "_nodes":{ + "total":1, + "successful":1, + "failed":0 + }, + "cluster_name":"es-cluster", + "stores":{ + "_default_":{ + "model_count":10, + "featureset_count":1, + "feature_count":0, + "status":"green" + } + }, + "status":"green", + "nodes":{ + "2QtMvxMvRoOTymAsoQbxhw":{ + "cache":{ + "feature":{ + "eviction_count":0, + "miss_count":0, + "hit_count":0, + "entry_count":0, + "memory_usage_in_bytes":0 + }, + "featureset":{ + "eviction_count":0, + "miss_count":0, + "hit_count":0, + "entry_count":0, + "memory_usage_in_bytes":0 + }, + "model":{ + "eviction_count":0, + "miss_count":0, + "hit_count":0, + "entry_count":0, + "memory_usage_in_bytes":0 + } + }, + "request_total_count": 0, + "request_error_count": 0 + } + } +} +``` +{% include copy-curl.html %} + +You can use filters to retrieve a single statistic by sending the following request: + +```json +GET /_plugins/_ltr/stats/{stat} +``` +{% include copy-curl.html %} + +The following table lists the available `stat` values. + +Stat | Description +:--- | :--- +`stores` | Information about configured feature stores. +`status` | The overall plugin status. +`cache` | Per-node cache statistics for various plugin components (features, feature sets, and models). +`request_total_count` | Per-node counter of the number of LTR queries executed. +`request_error_count` | Per-node counter of the number of LTR queries that failed. + +You can limit the information to a single node in the cluster by sending the following requests: + +```json +GET /_plugins/_ltr/{nodeId}/stats +GET /_plugins/_ltr/{nodeId}/stats/{stat} +``` + +## TermStat query +Experimental +{: .label .label-red } + +The `TermStatQuery` is in an experimental stage, and the Domain-Specific Language (DSL) may change as the code advances. For stable term-statistic access, see [`ExplorerQuery`]({{site.url}}{{site.baseurl}}/search-plugins/ltr/feature-engineering/#getting-raw-term-statistics). + +The `TermStatQuery` is a redesigned version of the legacy `ExplorerQuery`. It provides a clearer way to specify terms and offers more flexibility for experimentation. This query returns the same data as the `ExplorerQuery` but allows you to specify a custom Lucene expression to retrieve the desired data, such as in the following example: + +```json +POST tmdb/_search +{ + "query": { + "term_stat": { + "expr": "df", + "aggr": "max", + "terms": ["rambo", "rocky"], + "fields": ["title"] + } + } +} +``` +{% include copy-curl.html %} + +The `expr` parameter is used to specify a Lucene expression. This expression is run on a per-term basis. The expression can be a simple stat type or a custom formula with multiple stat types, such as `(tf * idf) / 2`. Available stat types in the Lucene expression context are listed in the following table. + +Type | Description +:---| :--- +`df` | The direct document frequency for a term. For example, if `rambo` occurs in three movie titles across multiple documents, then the value would be `3`. +`idf` | The inverse document frequency (IDF) calculation using the formula `log((NUM_DOCS+1)/(raw_df+1)) + 1`. +`tf` | The term frequency for a document. For example, if `rambo` occurs three times in a movie synopsis in the same document, then the value would be `3`. +`tp` | The term positions for a document. Multiple positions can be returned for a single term, so you should review the behavior of the `pos_aggr` parameter. +`ttf` | The total term frequency for a term across an index. For example, if `rambo` is mentioned a total of 100 times in the `overview` field across all documents, then the value would be `100`. + +The `aggr` parameter specifies the type of aggregation to be applied to the collected statistics from the `expr`. For example, if you specify the terms `rambo` and `rocky`, then the query gathers statistics for both terms. Because you can only return a single value, you need to decide which statistical calculation to use. The available aggregation types are `min`, `max`, `avg`, `sum`, and `stddev`. The query also provides the following counts: `matches` (the number of terms that matched in the current document) and `unique` (the unique number of terms that were passed in the query). + +The `terms` parameter specifies an array of terms for which you want to gather statistics. Only single terms are supported, with no support for phrases or span queries. If your field is tokenized, you can pass multiple terms in one string in the array. + +The `fields` parameter specifies the fields to check for the specified `terms`. If no `analyzer` is specified, then the configured `search_analyzer` for each field is used. + +The optional parameters are listed in the following table. + +Type | Description +:---| :--- +`analyzer` | If specified, this analyzer is used instead of the configured `search_analyzer` for each field. +`pos_aggr` | Because each term can have multiple positions, you can use this parameter to specify the aggregation to apply to the term positions. This supports the same values as the `aggr` parameter and defaults to `avg`. + +### Script injection + +Script injection provides the ability to inject term statistics into a scripting context. When working with `ScriptFeatures`, you can pass a `term_stat` object with the `terms`, `fields`, and `analyzer` parameters. An injected variable named `termStats` then provides access to the raw values in your custom script. This enables advanced feature engineering by giving you access to all the underlying data. + +To access the count of matched tokens, use `params.matchCount.get`. To access the unique token count, use `params.uniqueTerms`. + +You can either hardcode the `term_stat` parameter in your script definition or pass the parameter to be set at query time. For example, the following example query defines a feature set with a script feature that uses hardcoded `term_stat` parameters: + +```json +POST _ltr/_featureset/test +{ + "featureset": { + "features": [ + { + "name": "injection", + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "params.termStats['df'].size()", + "params": { + "term_stat": { + "analyzer": "!standard", + "terms": ["rambo rocky"], + "fields": ["overview"] + } + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +Analyzer names must be prefixed with a bang(!) when specifying them locally. Otherwise, they are treated as the parameter lookup value. +{: .note} + +To set parameter lookups, you can pass the name of the parameter from which you want to pull the value, as shown in the following example request: + +```json +POST _ltr/_featureset/test +{ + "featureset": { + "features": [ + { + "name": "injection", + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "params.termStats['df'].size()", + "params": { + "term_stat": { + "analyzer": "analyzerParam", + "terms": "termsParam", + "fields": "fieldsParam" + } + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +Alternatively, you can pass the `term_stat` parameters as query-time parameters, as shown in the following request: + +```json +POST tmdb/_search +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "_id": ["7555", "1370", "1369"] + } + }, + { + "sltr": { + "_name": "logged_featureset", + "featureset": "test", + "params": { + "analyzerParam": "standard", + "termsParam": ["troutman"], + "fieldsParam": ["overview"] + } + }} + ] + } + }, + "ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "named_query": "logged_featureset" + } + } + } +} +``` +{% include copy-curl.html %} diff --git a/_search-plugins/ltr/core-concepts.md b/_search-plugins/ltr/core-concepts.md new file mode 100644 index 00000000..7ede2e44 --- /dev/null +++ b/_search-plugins/ltr/core-concepts.md @@ -0,0 +1,142 @@ +--- +layout: default +title: ML ranking core concepts +nav_order: 10 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# ML ranking core concepts + +This guide is intended for OpenSearch developers and data scientist who are interested in adding machine learning (ML) ranking capabilities to their OpenSearch system. + +## What is LTR + +Learning to Rank (LTR) applies ML to search relevance ranking. This differs from other classic ML problems, such as the following: + +- **Regression:** The goal is to predict a variable, such as a stock price, as a function of known information, such as number of employees or revenue. The output is a direct prediction. +- **Classification:** The goal is to categorize an entity into predefined classes, for example, profitable or not profitable. The output is a category. + +The objective of LTR is not to make a direct prediction but rather to learn a function (`f`) that can rank documents in an order that best matches your perception of relevance for a given query. The output `f` does not represent a literal value but rather a prediction of the document's relative usefulness. + +For comprehensive information about LTR, see [How is Search Different From Other Machine Learning Problems?](http://opensourceconnections.com/blog/2017/08/03/search-as-machine-learning-prob/) and [What is Learning to Rank?](http://opensourceconnections.com/blog/2017/02/24/what-is-learning-to-rank/). + +## Defining the ideal ordering with judgment lists + +Judgment lists, also known as golden sets, provide a way to grade individual search results for a keyword search. These lists express the ideal ordering of search results based on your expectations. + +For example, using the [demo on GitHub](http://github.com/opensearch-project/opensearch-learning-to-rank-base/tree/main/demo/), in a search for `Rambo`, the judgment list may appear similar to the following: + +``` +grade,keywords,movie +4,Rambo,First Blood # Exactly Relevant +4,Rambo,Rambo +3,Rambo,Rambo III # Fairly Relevant +3,Rambo,Rambo First Blood Part II +2,Rambo,Rocky # Tangentially Relevant +2,Rambo,Cobra +0,Rambo,Bambi # Not even close... +0,Rambo,First Daughter +``` + +This judgment list establishes the ideal ordering of search results for the query `Rambo`. Metrics like [Normalized Discounted Cumulative Gain (NDCG)](https://en.wikipedia.org/wiki/Discounted_cumulative_gain) and [Expected Reciprocal Rank (ERR)](https://dl.acm.org/doi/abs/10.1145/1645953.1646033) can then be used to evaluate how closely the actual search results match this ideal ordering. + +The ranking function `f` aims to generate results closely aligned with the judgment list, maximizing quality metrics across various training queries. This ensures maximally useful search results. + +## Understanding features as building blocks of relevance + +The ranking function `f` uses input variables to arrive at a predicted output. For example, in stock price forecasting, input variables may encompass company-specific data like employee count and revenue. Likewise, in search relevance, the predictive model must leverage features that characterize the document, the query, and their associations, such as the [term frequency–inverse document frequency (TF–IDF)](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) score of the query keywords in a field. + +Similarly, in the context of searching for movies, the ranking function must use relevant features to determine the most relevant results. These features may include: + +- Whether and to what degree the search keywords match the title field, such as `titleScore`. +- Whether and to what degree the search keywords match the description field, such as `descScore`. +- The movie's popularity, such as `popularity`. +- The movie's rating, such as `rating`. +- The number of keywords used during the search, such as `numKeywords*)`. + +The ranking function would become `f(titleScore, descScore, popularity, rating, numKeywords)`. The goal is to use the features in a way that maximizes the likelihood of the search results being useful. + +For example, in the `Rambo` use case, it seems intuitive that `titleScore` would be important. However, for the top movie _First Blood_, the keyword `Rambo` is likely only mentioned in the description. In this case, the `descScore` would become relevant. Additionally, the `popularity` and `rating` features could help differentiate between sequels and originals. If the existing features do not work for this purpose, then a new feature `isSequel` could be introduced. This new feature could then be used to make better ranking decisions. + +Selecting and experimenting with features is fundamental to LTR. Using features that fail to help predict patterns in the target variable can result in an unsatisfactory search experience, following the principle of "garbage in, garbage out" that applies to any ML problem. + +## Completing the training set by logging features + +When you have a set of defined features, the next step is to annotate the judgment list with each feature's values. These values are used when the training process begins. For example, consider the following judgment list: + +``` +grade,keywords,movie +4,Rambo,First Blood +4,Rambo,Rambo +3,Rambo,Rambo III +... +``` + +To complete the training set, add the following features: + +``` +grade,keywords,movie,titleScore,descScore,popularity,... +4,Rambo,First Blood,0.0,21.5,100,... +4,Rambo,Rambo,42.5,21.5,95,... +3,Rambo,Rambo III,53.1,40.1,50,... +``` + +The `titleScore` represents the relevance score of the `Rambo` keyword in the title field of the document, and so on. + +Many LTR models are familiar with a file format introduced by Support Vector Machine for Ranking (SVMRank), an early LTR method. In this format, queries are given IDs, and the actual document identifier can be removed from the training process. Features are labeled with ordinals starting at `1`. For the preceding example, the file format would be: + +``` +4 qid:1 1:0.0 2:21.5 3:100,... +4 qid:1 1:42.5 2:21.5 3:95,... +3 qid:1 1:53.1 2:40.1 3:50,... +... +``` + +In actual systems, you might log these values and then use them later to annotate a judgment list. In other cases, the judgment list might come from user analytics, so the feature values are logged as you interact with the search application. See [Logging features]({{site.url}}{{site.baseurl}}/search-plugins/ltr/logging-features/) for more information. + +## Training a ranking function + +The following are key considerations for training a ranking function: + +- **Ranking models:** Several models, such as the following, are available for training, each with pros and cons: + + - **Tree-based models** (for example, LambdaMART, MART, Random Forests) + - Generally the most accurate. + - Large and complex, making them expensive to train. + - Tools such as [RankLib](https://sourceforge.net/p/lemur/wiki/RankLib/) and [XGBoost](https://github.com/dmlc/xgboost) focus on tree-based models. + + - **SVM-based models (SVMRank)** + - Less accurate but less expensive to train. + - See [Support Vector Machine for Ranking](https://www.cs.cornell.edu/people/tj/svm_light/svm_rank.html) for more information. + + - **Linear models** + - Perform basic linear regression on the judgment list. + - Tend to not be useful outside of the examples. + - See [Learning to Rank 101 — Linear Models](http://opensourceconnections.com/blog/2017/04/01/learning-to-rank-linear-models/) for more information. + +- **Model selection:** The choice of model can depend not only on performance but also on your level of experience and familiarity with the different approaches. + +## Testing: Is the model any good + +When testing the quality of the ranking model, consider the following: + +- **Judgment list limitations:** A judgment list cannot include every possible query that a model may encounter in the real world. It is important to test the model on a variety of queries in order to assess its ability to generalize beyond the training data. +- **Overfitting:** A model that is overfit to the training data does not perform well on new, unseen data. To avoid this, consider doing the following: + - Preserving some judgment lists as a _test set_ that is not used during the training process. + - Evaluating the model's performance on the test set, which reflects how it may perform in unfamiliar scenarios. + - Monitoring the _test NDCG_ metric, which should remain high as the model is trained. +- **Temporal generalization:** Even after deploying the model, you should continue testing the model's performance using more recent judgment lists to ensure that it does not become overfit to seasonal or temporal situations. + +## Real-world concerns + +The following are practical considerations for using the Learning to Rank plugin: + +- **Accurate judgment lists:** How can you create judgment lists that reflect your users' perception of search quality? +- **Measuring search quality:** What metrics should you use to determine whether the search results are useful to your users? +- **Data collection infrastructure:** What kind of infrastructure do you need in order to collect and log user behavior and feature data? +- **Model retraining:** How will you know when your model needs to be retrained? +- **A/B testing:** How will you compare your new model to your current search solution? What key performance indicators (KPIs) will you use to determine the success of your search system? + +See [How does the plugin fit in?]({{site.url}}{{site.baseurl}}/search-plugins/ltr/fits-in/) to learn more about how the Learning to Rank plugin's functionality fits into a complete LTR system. diff --git a/_search-plugins/ltr/faq.md b/_search-plugins/ltr/faq.md new file mode 100644 index 00000000..ae9c7956 --- /dev/null +++ b/_search-plugins/ltr/faq.md @@ -0,0 +1,24 @@ +--- +layout: default +title: Common issues +nav_order: 1000 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Common issues + +To make the most of Learning to Rank (LTR), consider these helpful insights. + +## Negative scores + +Lucene does not allow for negative query scores. This can be problematic if your raw features include negative values. To address this, confirm that your features are non-negative _before_ training your model. You can achieve this by creating normalized fields with values shifted by the minimum value or by passing the scores through a function that produces a value greater than or equal to `0`. + +## Bugs + +If you encounter a bug while working with the plugin, you can open an issue in the [`opensearch-learning-to-rank-base` repository](https://github.com/opensearch-project/opensearch-learning-to-rank-base/issues). The project team regularly investigates and resolves issues. If you are seeking general support, the issue may be closed and you may be directed to the relevant support channel(s). + +## Further assistance + +If you need further assistance, join the [Relevance Slack Community](https://opensourceconnections.com/slack) and participate in the `#opensearch-learn-to-rank` channel to receive guidance and support from the community. diff --git a/_search-plugins/ltr/feature-engineering.md b/_search-plugins/ltr/feature-engineering.md new file mode 100644 index 00000000..8efdb874 --- /dev/null +++ b/_search-plugins/ltr/feature-engineering.md @@ -0,0 +1,89 @@ +--- +layout: default +title: Feature engineering +nav_order: 40 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Feature engineering + +Common feature engineering tasks that you may encounter while developing a learning to rank (LTR) solution are described in the following sections. + +## Getting raw term statistics + +Many LTR solutions use raw term statistics in their training, such as the following: +- **Total term frequency (`raw_ttf`):** The total number of times that a term appears across an entire index. +- **Document frequency (`raw_df`):** The number of documents in which a term appears. +- **Term frequency (`raw_tf`):** The number of times that a term appears in a specific document. +- **Classic IDF (`classic_idf`):** The inverse document frequency (IDF) calculation `log((NUM_DOCS+1)/(raw_df+1)) + 1`. + +The Learning to Rank plugin provides a `match_explorer` query primitive that can extract these statistics for you, as shown in the following example: + +```json +POST tmdb/_search +{ + "query": { + "match_explorer": { + "type": "max_raw_df", + "query": { + "match": { + "title": "rambo rocky" + } + } + } + } +} +``` +{% include copy-curl.html %} + +The query returns the highest document frequency between the terms `rambo ` and `rocky`. + +You can use operations such as `max`, `min`, `sum`, and `stddev` with the statistics to get the information you need. + +### Term position statistics + +You can prepend the `type` with the desired operation (`min`, `max`, `avg`) to calculate the corresponding statistic across the term positions. If the terms are not present in the document, then the result will be `0`. + +The available statistics include the following: + +- `min_raw_tp` (minimum raw term position): This statistic finds the earliest position of any search term in the document. For example, with the query `dance monkey`, if `dance` occurs at positions [2, 5, 9] and `monkey` occurs at [1, 4], then the minimum is 1. +- `max_raw_tp` (maximum raw term position): This statistic finds the latest position of any search term in the document. Using the preceding example, the maximum is 9. +- `avg_raw_tp` (average raw term position): This statistic calculates the average term position for any of the query terms. Using the preceding example, the average for `dance` is 5.33 [(2+5+9)/3)] and the average for `monkey` is 2.5 [(1+4)/2], with an overall average of 3.91. +- `unique_terms_count`: Provides a count of the unique search terms in the query. + +## Document-specific features + +When working on an LTR solution, you may need to incorporate features that are specific to the document rather than to the relationship between the query and the document. These document-specific features can include metrics related to popularity or recency. + +The `function_score` query provides the functionality to extract these document-specific features. The following example query shows how you can use it to incorporate the `vote_average` field as a feature: + +```json +{ + "query": { + "function_score": { + "functions": [{ + "field_value_factor": { + "field": "vote_average", + "missing": 0 + } + }], + "query": { + "match_all": {} + } + } + } +} +``` +{% include copy-curl.html %} + +In the example, the score of the query is determined by the value of the `vote_average` field, which could be a measure of document popularity or quality. + +## Index drift + +When working with an index that is regularly updated, it is important to consider that the trends and patterns you observe may not remain constant over time. Your index can drift as user behavior, content, and other factors change. For example, on an e-commerce store, you may find that sandals are popular during summer months but become almost impossible to find in the winter. Similarly, the features that drive purchases or engagement during one time period may not be as important during another. + +## Next steps + +Learn about [logging feature scores]({{site.url}}{{site.baseurl}}/search-plugins/ltr/logging-features/). diff --git a/_search-plugins/ltr/fits-in.md b/_search-plugins/ltr/fits-in.md new file mode 100644 index 00000000..18b7f698 --- /dev/null +++ b/_search-plugins/ltr/fits-in.md @@ -0,0 +1,30 @@ +--- +layout: default +title: Scope of the plugin +nav_order: 20 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Scope of the plugin + +The Learning to Rank plugin for OpenSearch helps you develop and use machine learning (ML)-based ranking models for your application search operations. The following sections describe how the plugin fits into the overall LTR process. + +## What the plugin does + +The plugin provides the building blocks to develop and use LTR models, giving you the following capabilities: + +1. **Developing query-dependent features:** Create custom features that capture the relationship between a search query and a document. These features can be stored in OpenSearch. +2. **Logging feature values:** Record the feature values for documents returned in search results. Once you have logged the feature sets for your documents, you can combine this data with the judgment lists you have developed. This will give you a complete training set that you can use to test and train your ranking models. Tools such as RankLib or XGBoost can then be used to develop a satisfactory model. +3. **Deploying and using models:** Upload trained ranking models to the plugin and use them to rerank search results. The plugin offers a custom OpenSearch query domain-specific language (DSL) primitive that allows you to execute the model during the search process. + +## What the plugin does not do + +The plugin does not support the creation of judgment lists. This is a task you must handle yourself because it is domain specific. See the [Wikimedia Foundation blog](https://blog.wikimedia.org/2017/09/19/search-relevance-survey/) for an example approach to developing judgment lists for searching articles. Some domains, such as e-commerce, may focus more on conversion-related signals, while others may involve human relevance assessors (either internal experts or crowdsourced workers). + +The plugin does not handle model training or testing. This is an offline process that should be handled using the appropriate tools, such as [XGBoost](https://xgboost.ai/) and [RankLib](https://lemurproject.org/ranklib.php). The plugin integrates with these external model-building workflows. Training and testing ranking models can be a CPU-intensive task that requires data science expertise and offline testing. Most organizations prefer to have data scientists oversee the model development process rather than running it directly in their production environment. + +## Next steps + +Learn about [working with features]({{site.url}}{{site.baseurl}}/search-plugins/ltr/working-with-features/). diff --git a/_search-plugins/ltr/index.md b/_search-plugins/ltr/index.md new file mode 100644 index 00000000..f9a6d4e7 --- /dev/null +++ b/_search-plugins/ltr/index.md @@ -0,0 +1,51 @@ +--- +layout: default +title: Learning to Rank +parent: Optimizing search quality +nav_order: 40 +has_children: true +has_toc: false +redirect_from: + - /search-plugins/ltr/ +--- + +<!-- vale off --> +# Learning to Rank +<!-- vale on --> + +The Learning to Rank plugin for OpenSearch enables you to use machine learning (ML) and behavioral data to fine-tune the relevance of documents. It uses models from the [XGBoost](https://xgboost.ai/) and [RankLib](https://lemurproject.org/ranklib.php) libraries. These models rescore the search results, considering query-dependent features such as click-through data or field matches, which can further improve relevance. + +The term _learning to rank_ is abbreviated as LTR throughout the OpenSearch documentation when the term is used in a general sense. For the plugin developer documentation, see [`opensearch-learning-to-rank-base`](https://github.com/opensearch-project/opensearch-learning-to-rank-base). +{: .note} + +## Getting started + +The following resources can help you get started: + +- If you are new to LTR, start with the [ML ranking core concepts]({{site.url}}{{site.baseurl}}/search-plugins/ltr/core-concepts/) documentation. +- For a quick introduction, see the demo in [hello-ltr](https://github.com/o19s/hello-ltr). +- If you are familiar with LTR, start with the [Scope of the plugin]({{site.url}}{{site.baseurl}}/search-plugins/ltr/fits-in/) documentation. + +## Core concepts and setup + +Before implementing LTR, familiarize yourself with the foundational concepts and architecture: + +- [ML ranking core concepts]({{site.url}}{{site.baseurl}}/search-plugins/ltr/core-concepts/): Understand the fundamental concepts behind Learning to Rank. +- [Scope of the plugin]({{site.url}}{{site.baseurl}}/search-plugins/ltr/fits-in/): Learn how LTR integrates with your OpenSearch infrastructure. + +## Feature engineering and model development + +Create and train your ranking models using the following workflow: + +- [Feature engineering]({{site.url}}{{site.baseurl}}/search-plugins/ltr/feature-engineering/): Design effective features for your ranking models. +- [Working with features]({{site.url}}{{site.baseurl}}/search-plugins/ltr/working-with-features/): Create and manage feature sets. +- [Logging feature scores]({{site.url}}{{site.baseurl}}/search-plugins/ltr/logging-features/): Collect feature data for model training. +- [Uploading trained models]({{site.url}}{{site.baseurl}}/search-plugins/ltr/training-models/): Build and train your ranking models. + +## Deployment and advanced topics + +Once your models are trained, deploy them in production and explore advanced features: + +- [Optimizing search with LTR]({{site.url}}{{site.baseurl}}/search-plugins/ltr/searching-with-your-model/): Deploy models in production search. +- [Advanced functionality]({{site.url}}{{site.baseurl}}/search-plugins/ltr/advanced-functionality/): Explore advanced LTR features and techniques. +- [Common issues]({{site.url}}{{site.baseurl}}/search-plugins/ltr/faq/): Common questions and troubleshooting. diff --git a/_search-plugins/ltr/logging-features.md b/_search-plugins/ltr/logging-features.md new file mode 100644 index 00000000..f9e58f96 --- /dev/null +++ b/_search-plugins/ltr/logging-features.md @@ -0,0 +1,421 @@ +--- +layout: default +title: Logging feature scores +nav_order: 50 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Logging feature scores + +Feature values need to be logged in order to train a model. This is a crucial component of the Learning to Rank plugin---as you search, feature values from the feature sets are logged so that they can be used for training. This allows models that effectively predict relevance using that set of features to be discovered. + +<!-- vale off --> +## sltr query +<!-- vale on --> + +The `sltr` query is the primary method for running features and evaluating models. When logging, an `sltr` query is used to execute each feature query and retrieve the feature scores. A feature set structure that works with the [`hello-ltr`](https://github.com/o19s/hello-ltr) demo schema is shown in the following example request: + +```json +PUT _ltr/_featureset/more_movie_features +{ + "name": "more_movie_features", + "features": [ + { + "name": "body_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "overview": "{% raw %}{{keywords}}{% endraw %}" + } + } + }, + { + "name": "title_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "title": "{% raw %}{{keywords}}{% endraw %}" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +## Common use cases + +Common use cases for logging feature sets are described in the following sections. + +### Joining feature values with a judgment list + +If the judgment list is already available, you can join feature values for each keyword/document pair to create a complete training set. For example, consider the following judgment list: + +``` +grade,keywords,docId +4,rambo,7555 +3,rambo,1370 +3,rambo,1369 +4,rocky,4241 +``` +{% include copy-curl.html %} + +The feature values need to be retrieved for all documents that have a judgment for each search term, one search term at a time. For example, starting with a `rambo` search, a filter can be created for the associated document as follows: + +```json +{ + "filter": [ + {"terms": { + "_id": ["7555", "1370", "1369"] + }} + ] +} +``` +{% include copy-curl.html %} + +The Learning to Rank plugin must point to the features to be logged. The `sltr` query, which is part of the plugin, can be used for this purpose. The `sltr` query has a `_name` (the named queries feature) used to reference it, refers to the previously created feature set `more_movie_features`, and passes the search keyword `rambo` and any other required parameters, as shown in the following example query: + +```json +{ + "sltr": { + "_name": "logged_featureset", + "featureset": "more_movie_features", + "params": { + "keywords": "rambo" + } + } +} +``` +{% include copy-curl.html %} + +[Searching with LTR]({{site.url}}{{site.baseurl}}/search-plugins/ltr/searching-with-your-model/) provides an `sltr` query to use for executing a model. This `sltr` query is used as a mechanism to direct the Learning to Rank plugin to the feature set requiring logging. +{: .note} + +To avoid influencing the score, the `sltr` query is injected as a filter, as shown in the following example: + +```json +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "_id": [ + "7555", + "1370", + "1369" + ] + } + }, + { + "sltr": { + "_name": "logged_featureset", + "featureset": "more_movie_features", + "params": { + "keywords": "rambo" + } + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +Executing this query returns the three expected hits. The next step is to enable feature logging to refer to the `sltr` query to be logged. + +The logging identifies the `sltr` query, runs the feature set's queries, scores each document, and returns those scores as computed fields for each document, as shown in the following example logging structure: + +```json +"ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "named_query": "logged_featureset" + } + } +} +``` +{% include copy-curl.html %} + +The log extension supports the following arguments: + +- `name`: The name of the log entry to fetch from each document. +- `named_query`: The named query that corresponds to an `sltr` query. +- `rescore_index`: If the `sltr` query is in a rescore phase, then this is the index of the query in the rescore list. +- `missing_as_zero`: Produces a `0` for missing features (when the feature does not match). Default is `false`. + +To enable the log to locate an `sltr` query, either during the normal query phase or during rescoring, either `named_query` or `rescore_index` must be set. +{: .note} + +The full example request is as follows: + +```json +POST tmdb/_search +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "_id": ["7555", "1370", "1369"] + } + }, + { + "sltr": { + "_name": "logged_featureset", + "featureset": "more_movie_features", + "params": { + "keywords": "rambo" + } + }} + ] + } + }, + "ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "named_query": "logged_featureset" + } + } + } +} +``` +{% include copy-curl.html %} + +Each document now contains a log entry, as shown in the following example: + +```json +{ + "_index": "tmdb", + "_type": "movie", + "_id": "1370", + "_score": 20.291, + "_source": { + ... + }, + "fields": { + "_ltrlog": [ + { + "log_entry1": [ + {"name": "title_query" + "value": 9.510193}, + {"name": "body_query + "value": 10.7808075} + ] + } + ] + }, + "matched_queries": [ + "logged_featureset" + ] +} +``` +{% include copy-curl.html %} + +The judgment list can be joined with the feature values to produce a training set. For the line corresponding to document `1370` with keyword `rambo`, the following can be added: + +``` +> 4 qid:1 1:9.510193 2:10.7808075 +``` +{% include copy-curl.html %} + +Repeat this process for all of your queries. + +For large judgment lists, it is recommended to batch the logs for multiple queries. You can use [multi-search]({{site.url}}{{site.baseurl}}/api-reference/multi-search/) capabilities for this purpose. +{: .note} + +### Logging values for a live feature set + +If you are running in production with a model being executed within an `sltr` query, a live model may appear similar to the following example request: + +```json +POST tmdb/_search +{ + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } + } +} +``` +{% include copy-curl.html %} + +See [Searching with LTR]({{site.url}}{{site.baseurl}}/search-plugins/ltr/searching-with-your-model/) for information about model execution. +{: .note} + +To log the feature values for the query, apply the appropriate logging spec to reference the `sltr` query, as shown in the following example: + +```json +"ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "rescore_index": 0 + } + } +} +``` +{% include copy-curl.html %} + +The example logs the features in the response, enabling future model retraining using the same feature set. + +### Modifying and logging an existing feature set + +Feature sets can be expanded. For example, as shown in the following example request, if a new feature, such as `user_rating`, needs to be incorporated, it can be added to the existing feature set `more_movie_features`: + +``` json +PUT _ltr/_feature/user_rating/_addfeatures +{ + "features": [ + "name": "user_rating", + "params": [], + "template_language": "mustache", + "template" : { + "function_score": { + "functions": { + "field": "vote_average" + }, + "query": { + "match_all": {} + } + } + } + ] +} +``` +{% include copy-curl.html %} + +See [Working with features]({{site.url}}{{site.baseurl}}/search-plugins/ltr/working-with-features/) for more information. +{: .note} + +When logging is performed, the new feature is included in the output, as shown in the following example: + +``` json +{ + "log_entry1": [ + { + "name": "title_query", + "value": 9.510193 + }, + { + "name": "body_query", + "value": 10.7808075 + }, + { + "name": "user_rating", + "value": 7.8 + } + ] +} +``` +{% include copy-curl.html %} + +### Logging values for a proposed feature set + +You can create a completely new feature set for experimental purposes, for example, `other_movie_features`, as shown in the following example request: + +```json +PUT _ltr/_featureset/other_movie_features +{ + "name": "other_movie_features", + "features": [ + { + "name": "cast_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "cast.name": "{% raw %}{{keywords}}{% endraw %}" + } + } + }, + { + "name": "genre_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "genres.name": "{% raw %}{{keywords}}{% endraw %}" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The feature set, `other_movie_features`, can be logged alongside the live production set, `more_movie_features`, by appending it as another filter, as shown in the following example request: + +```json +POST tmdb/_search +{ +"query": { + "bool": { + "filter": [ + { "sltr": { + "_name": "logged_featureset", + "featureset": "other_movie_features", + "params": { + "keywords": "rambo" + } + }}, + {"match": { + "_all": "rambo" + }} + ] + } +}, +"rescore": { + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } +} +} +``` +{% include copy-curl.html %} + +You can continue adding as many feature sets as needed for logging. + +## Logging scenarios + +Once you have covered the basics, you can consider some real-life feature logging scenarios. + +First, logging is used to develop judgment lists from user analytics to capture the exact value of a feature at the precise time of interaction. For instance, you may want to know the recency, title score, and other values at the precise time of a user's interaction. This would help you analyze which features or factors had relevance while training. To achieve this, you can build a comprehensive feature set for future experimentation. + +Second, logging can be used to retrain a model in which you already have confidence. You may want to keep your models up to date with a shifting index because models can lose their effectiveness over time. You may have A/B testing in place or be monitoring business metrics and notice gradual degradation in model performance. + +Third, logging is used during model development. You may have a judgment list but want to iterate heavily with a local copy of OpenSearch. This allows for extensive experimentation with new features, adding and removing them from the feature sets as needed. While this process may result in being slightly out of sync with the live index, the goal is to arrive at a set of satisfactory model parameters. Once this is achieved, the model can be trained with production data to confirm that the level of performance remains acceptable. + +## Next steps + +Learn more about training models in the [Uploading a trained model]({{site.url}}{{site.baseurl}}/search-plugins/ltr/training-models/) documentation. diff --git a/_search-plugins/ltr/searching-with-your-model.md b/_search-plugins/ltr/searching-with-your-model.md new file mode 100644 index 00000000..5cf8b823 --- /dev/null +++ b/_search-plugins/ltr/searching-with-your-model.md @@ -0,0 +1,103 @@ +--- +layout: default +title: Optimizing search with LTR +nav_order: 70 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Optimizing search with LTR + +After you have trained a model, you can use the `sltr` query to execute it. However, directly running the query on the entire index is not recommended because it can be CPU intensive and impact the performance of your OpenSearch cluster. The query allows you to apply your trained model to search results, as shown in the following example: + +```json + POST tmdb/_search + { + "query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } +``` +{% include copy-curl.html %} + +## Rescoring top N + +To execute your model more efficiently, you can use the built-in rescore functionality to apply your model to the top N results of a baseline relevance query, as shown in the following example query: + +```json + POST tmdb/_search + { + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "window_size": 1000, + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } + } + } +``` +{% include copy-curl.html %} + +A `match` is first executed for the term `rambo` and then `my_model` is applied to the top 1,000 results. This baseline query is used to generate an initial set of results that are then scored using the default similarity BM25 probabilistic ranking framework to calculate relevance scores. + +## Rescoring a subset of features + +You can selectively score a subset of features by specifying the `active_features` in the `sltr` query, as shown in the following example. This allows you to focus the model's scoring on the selected features, while any unspecified features are marked as missing. You only need to specify the `params` relevant to the `active_features`. If you request a feature name that is not part of the assigned feature set, then the query throws an error. + +```json + POST tmdb/_search + { + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "window_size": 1000, + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model", + "active_features": ["title_query"] + } + } + } + } + } +``` +{% include copy-curl.html %} + +The `my_model` model is applied but only scores the `title_query` feature. + +## Combining `sltr` with other OpenSearch features + +The `sltr` query can be integrated with the following OpenSearch features and functionalities to create more sophisticated and tailored search solutions that go beyond applying a model to your results: + +- Filtering out results based on business rules using OpenSearch filters before applying the model +- Chaining multiple rescores to refine the relevance of your results +- Rescoring once to address relevance with `sltr` and a second time for business concerns +- Down-boosting relevant but low-quality content in the baseline query to prevent it from being rescored + +## Next steps + +Learn about [advanced functionality]({{site.url}}{{site.baseurl}}/search-plugins/ltr/advanced-functionality/). diff --git a/_search-plugins/ltr/training-models.md b/_search-plugins/ltr/training-models.md new file mode 100644 index 00000000..98fa6ac1 --- /dev/null +++ b/_search-plugins/ltr/training-models.md @@ -0,0 +1,336 @@ +--- +layout: default +title: Uploading trained models +nav_order: 60 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Uploading trained models + +While model training occurs outside of the Learning to Rank plugin, you can use the plugin for [logging feature scores]({{site.url}}{{site.baseurl}}/search-plugins/ltr/logging-features/). After you have trained a model, you can upload it to the plugin in the available serialization formats, such as RankLib and XGBoost. + +## RankLib model training + +The feature logging process generates a RankLib-comsumable judgment file. In the following judgment file, the query with ID 1 `rambo` includes the logged features 1 (a title `TF*IDF` +score) and 2 (a description `TF*IDF` score) for a set of documents: + +``` +4 qid:1 1:9.8376875 2:12.318446 # 7555 rambo +3 qid:1 1:10.7808075 2:9.510193 # 1370 rambo +3 qid:1 1:10.7808075 2:6.8449354 # 1369 rambo +3 qid:1 1:10.7808075 2:0.0 # 1368 rambo +``` + +The RankLib library can be called using the following command: + + ``` + cmd = "java -jar RankLib-2.8.jar -ranker %s -train%rs -save %s -frate 1.0" % (whichModel, judgmentsWithFeaturesFile, modelOutput) +``` + +The `judgmentsWithFeatureFile` is the input provided to RankLib for training. Additional parameters can be passed. See the [RankLib documentation](https://sourceforge.net/p/lemur/wiki/RankLib/) for more information. + +RankLib outputs the model in its own serialization format. As shown in the following example, a LambdaMART model is an ensemble of regression trees: + +``` +## LambdaMART +## No. of trees = 1000 +## No. of leaves = 10 +## No. of threshold candidates = 256 +## Learning rate = 0.1 +## Stop early = 100 + + <ensemble> + <tree id="1" weight="0.1"> + <split> + <feature> 2 </feature> + ... +``` + +Within the RankLib model, each tree in the ensemble examines feature values, makes decisions based on these feature values, and outputs the relevance scores. The features are referred to by their ordinal position, starting from 1, which corresponds to the 0th feature in the original feature set. RankLib does not use feature names during model training. + +### Other RankLib models + +RankLib is a library that implements several other model types in addition to LambdaMART, such as MART, +RankNet, RankBoost, AdaRank, Coordinate Ascent, ListNet, and Random Forests. Each of these models has its own set of parameters and training process. + +For example, the RankNet model is a neural network that learns to predict the probability of a document being more relevant than another document. The model is trained using a pairwise loss function that compares the predicted relevance of two documents with the actual relevance. The model is serialized in a format similar to the following example: + +``` +## RankNet +## Epochs = 100 +## No. of features = 5 +## No. of hidden layers = 1 +... +## Layer 1: 10 neurons +1 2 +1 +10 +0 0 -0.013491530393429608 0.031183180961270988 0.06558792020112071 -0.006024092627087733 0.05729619574181734 -0.0017010373987742411 0.07684848696852313 -0.06570387602230028 0.04390491141617467 0.013371636736099578 +... +``` + +All these models can be used with the Learning to Rank plugin, provided that the model is serialized in the RankLib format. + +## XGBoost model training + +Unlike the RankLib model, the XGBoost model is serialized in a format specific to gradient-boosted decision trees, as shown in the following example: + +```json + [ { "nodeid": 0, "depth": 0, "split": "tmdb_multi", "split_condition": 11.2009, "yes": 1, "no": 2, "missing": 1, "children": [ + { "nodeid": 1, "depth": 1, "split": "tmdb_title", "split_condition": 2.20631, "yes": 3, "no": 4, "missing": 3, "children": [ + { "nodeid": 3, "leaf": -0.03125 }, + ... +``` + +## XGBoost parameters + +Optional parameters can be specified for an XGBoost model. These parameters are specified as an object, with the decision trees specified in the `splits` field. The supported parameters include `objective`, which defines the model learning objective as described in the [XGBoost documentation](https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters). This parameter can transform the final model prediction. The supported values include `binary:logistic`, `binary:logitraw`, `rank:ndcg`, `rank:map`, `rank:pairwise`, `reg:linear`, and `reg:logistic`. + +## Simple linear models + +Machine learning (ML) models, such as Support Vector Machines (SVMs), output linear weights for each feature. The LTR model supports representing these linear weights in a simple format, such as those learned from an SVM or linear regression model. In the following example output, the weights indicate the relative importance of the features in the model's prediction: + +```json +{ + "title_query" : 0.3, + "body_query" : 0.5, + "recency" : 0.1 +} +``` + +## Feature normalization + +Feature normalization is used to convert feature values to a consistent range, typically between 0 and 1 or -1 and 1. This is done during the training phase to better understand the relative impact of each feature. Some models, especially linear ones such as SVMRank, rely on normalization to function correctly. + +## Model upload process + +After training your model, the next step is to make it available for search operations. This involves uploading the model to the Learning to Rank plugin. When uploading a model, you must provide the following information: + +- Feature set used during training +- Model type, for example, RankLib or XGBoost +- Model content + +The following example request shows how to upload a RankLib model that was trained using the `more_movie_features` feature set: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_ranklib_model", + "model": { + "type": "model/ranklib", + "definition": "## LambdaMART\n + ## No. of trees = 1000 + ## No. of leaves = 10 + ## No. of threshold candidates = 256 + ## Learning rate = 0.1 + ## Stop early = 100 + + <ensemble> + <tree id="1" weight="0.1"> + <split> + <feature> 2 </feature> + ... + " + } + } + } +``` + +The following example request shows how to upload an XGBoost model that was trained using the `more_movie_features` feature set: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_xgboost_model", + "model": { + "type": "model/xgboost+json", + "definition": "[ { \"nodeid\": 0, \"depth\": 0, \"split\": \"tmdb_multi\", \"split_condition\": 11.2009, \"yes\": 1, \"no\": 2, \"missing\": 1, \"children\": [ + { \"nodeid\": 1, \"depth\": 1, \"split\": \"tmdb_title\", \"split_condition\": 2.20631, \"yes\": 3, \"no\": 4, \"missing\": 3, \"children\": [ + { \"nodeid\": 3, \"leaf\": -0.03125 }, + ..." + } + } + } +``` + +The following example request shows how to upload an XGBoost model that was trained using the `more_movie_features` feature set with parameters: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_xgboost_model", + "model": { + "type": "model/xgboost+json", + "definition": "{ + \"objective\": \"reg:logistic\", + \"splits\": [ { \"nodeid\": 0, \"depth\": 0, \"split\": \"tmdb_multi\", \"split_condition\": 11.2009, \"yes\": 1, \"no\": 2, \"missing\": 1, \"children\": [ + { \"nodeid\": 1, \"depth\": 1, \"split\": \"tmdb_title\", \"split_condition\": 2.20631, \"yes\": 3, \"no\": 4, \"missing\": 3, \"children\": [ + { \"nodeid\": 3, \"leaf\": -0.03125 }, + ... + ] + }" + } + } + } +```` + +The following example request shows how to upload a simple linear model that was trained using the `more_movie_features` feature set: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_linear_model", + "model": { + "type": "model/linear", + "definition": """ + { + "title_query" : 0.3, + "body_query" : 0.5, + "recency" : 0.1 + } + """ + } + } + } +``` + +## Creating a model with feature normalization + +Feature normalization is a crucial preprocessing step that can be applied before model evaluation. LTR supports two types of feature normalization: min-max and standard normalization. + +### Standard normalization + +Standard normalization transforms features as follows: + +- Maps the mean value to 0 +- Maps one standard deviation above the mean to 1 +- Maps one standard deviation below the mean to -1 + +The following example request shows how to create a model with standard feature normalization: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_linear_model", + "model": { + "type": "model/linear", + "feature_normalizers": { + "release_year": { + "standard": { + "mean": 1970, + "standard_deviation": 30 + } + } + }, + "definition": """ + { + "release_year" : 0.3, + "body_query" : 0.5, + "recency" : 0.1 + } + """ + } + } + } +``` + +### Min-max normalization + +Min-max normalization scales features to a fixed range, typically between 0 and 1. Min-max normalization transforms features as follows: + +- Maps the specified minimum value to 0 +- Maps the specified maximum value to 1 +- Scales the values between 0 and 1 linearly + +The following example request shows how to implement min-max normalization: + +```json + "feature_normalizers": { + "vote_average": { + "min_max": { + "minimum": 0, + "maximum": 10 + } + } + } +``` + +## Model independence from feature sets + +Models are initially created with reference to a feature set. After their creation, they exist as independent top-level entities. + +### Accessing models + +To retrieve a model, use a GET request: + +``` +GET _ltr/_model/my_linear_model +``` + +To delete a model, use a DELETE request: + +``` +DELETE _ltr/_model/my_linear_model +``` + +Model names must be globally unique across all feature sets. +{: .note} + +### Model persistence + +When a model is created, its features are copied. This prevents changes to the original features from affecting existing models or model production. For example, if the feature set used to create the model is deleted, you can still access and use the model. + +### Model response + +When retrieving a model, you receive a response that includes the features used to create it, as shown in the following example: + +```json + { + "_index": ".ltrstore", + "_type": "store", + "_id": "model-my_linear_model", + "_version": 1, + "found": true, + "_source": { + "name": "my_linear_model", + "type": "model", + "model": { + "name": "my_linear_model", + "feature_set": { + "name": "more_movie_features", + "features": [ + { + "name": "body_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "overview": "{{keywords}}" + } + } + }, + { + "name": "title_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + ]}}} +``` + +## Next steps + +Learn about [searching with LTR]({{site.url}}{{site.baseurl}}/search-plugins/ltr/searching-with-your-model/). diff --git a/_search-plugins/ltr/working-with-features.md b/_search-plugins/ltr/working-with-features.md new file mode 100644 index 00000000..f0bf6110 --- /dev/null +++ b/_search-plugins/ltr/working-with-features.md @@ -0,0 +1,271 @@ +--- +layout: default +title: Working with features +nav_order: 30 +parent: Learning to Rank +grand_parent: Optimizing search quality +has_children: false +--- + +# Working with features + +The following sections describe the specific functionality provided by the Learning to Rank plugin. This information will help you build and upload features for your learning to rank (LTR) system. See [ML ranking core concepts]({{site.url}}{{site.baseurl}}/search-plugins/ltr/core-concepts/) and [Scope of the plugin]({{site.url}}{{site.baseurl}}/search-plugins/ltr/fits-in/) for more information about the Learning to Rank plugin's roles and functionality. + +## Understanding the role of features in the Learning to Rank plugin + +The Learning to Rank plugin defines a _feature_ as an _OpenSearch query_. When you execute an OpenSearch query using your search terms and other relevant parameters, the resulting score is the value that can be used in your training data. For example, a feature may include basic `match` queries on fields such as `title`: + +```json +{ + "query": { + "match": { + "title": "{% raw %}{{keywords}}{% endraw %}" + } + } +} +``` +{% include copy-curl.html %} + +In addition to simple query-based features, you can also use document properties, such as `popularity`, as features. For example, you can use a function score query to get the average movie rating: + +```json +{ + "query": { + "function_score": { + "functions": { + "field": "vote_average" + }, + "query": { + "match_all": {} + } + } + } +} +``` +{% include copy-curl.html %} + +Another example is a query based on location, such as a geodistance filter: + +```json +{ + "query": { + "bool" : { + "must" : { + "match_all" : {} + }, + "filter" : { + "geo_distance" : { + "distance" : "200km", + "pin.location" : { + "lat" : "{% raw %}{{users_lat}}{% endraw %}", + "lon" : "{% raw %}{{users_lon}}{% endraw %}" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +These types of queries are the building blocks that the ranking `f` function you are training combines mathematically to determine a relevance score. + +## Using Mustache templates in LTR queries + +The features in LTR queries use Mustache templates. This allows you to insert variables into your search queries. For example, you could have a query that uses `{% raw %}{{keywords}}{% endraw %}` to insert your search terms. Or you could use `{% raw %}{{users_lat}}{% endraw %}` and `{% raw %}{{users_lon}}{% endraw %}` to include the location. This gives you the flexibility to personalize your search. + +## Uploading and naming features + +The Learning to Rank plugin enables you to create and modify features. After you define your features, you can log them for use in model training. By combining the logged feature data with your judgment list, you can train a model. Once the model is ready, you can upload it and then apply it to your search queries. + +## Initializing the default feature store + +The Learning to Rank plugin uses a feature store to store metadata about your features and models. Typically, there is one feature store per major search implementation, for example, [Wikipedia](http://wikipedia.org) as compared to [Wikitravel](http://wikitravel.org). + +For most uses cases, you can use the default feature store and avoid managing multiple feature stores. To initialize the default feature store, run the following request: + +``` +PUT _ltr +``` +{% include copy-curl.html %} + +If you need to start again from the beginning, you can delete the default feature store by using the following operation: + +``` +DELETE _ltr +``` +{% include copy-curl.html %} + +Deleting the feature store removes all existing feature and model data. +{: .warning} + +The default feature store is used throughout the rest of this guide. + +## Working with features and feature sets + +A _feature set_ is a collection of features that have been grouped together. You can use feature sets to log multiple feature values for offline training. When creating a new model, you copy the relevant feature set into the model definition. + +## Creating feature sets + +To create a feature set, you can send a POST request. When creating the feature set, you provide a name and an optional list of features, as shown in the following example request: + +```json +POST _ltr/_featureset/more_movie_features +{ + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{% raw %}{{keywords}}{% endraw %}" + } + } + }, + { + "name": "title_query_boost", + "params": [ + "some_multiplier" + ], + "template_language": "derived_expression", + "template": "title_query * some_multiplier" + }, + { + "name": "custom_title_query_boost", + "params": [ + "some_multiplier" + ], + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "params.feature_vector.get('title_query') * (long)params.some_multiplier", + "params": { + "some_multiplier": "some_multiplier" + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +## Managing feature sets + +To fetch a specific feature set, you can use the following request: + +``` +GET _ltr/_featureset/more_movie_features +``` +{% include copy-curl.html %} + +To see a list of all defined feature sets, you can use the following request: + +``` +GET _ltr/_featureset +``` +{% include copy-curl.html %} + +If you have many feature sets, you can filter the list by using a prefix, as shown in the following example request: + +``` +GET _ltr/_featureset?prefix=mor +``` +{% include copy-curl.html %} + +This returns only the feature sets with names starting with `mor`. + +If you need to start over, you can delete a feature set using the following request: + +``` +DELETE _ltr/_featureset/more_movie_features +``` +{% include copy-curl.html %} + +## Validating features + +When adding new features, you should validate that the features work as expected. You can do this by adding a `validation` block in your feature creation request. This allows the Learning to Rank plugin to run the query before adding the feature, catching any issues early. If you do not run this validation, you may not discover until later that the query, while valid JSON, contains a malformed OpenSearch query. + +To run validation, you can specify the test parameters and the index to use, as shown in the following example validation block: + +```json +"validation": { + "params": { + "keywords": "rambo" + }, + "index": "tmdb" +}, +``` +{% include copy-curl.html %} + +Place the validation block alongside your feature set definition. In the following example, the `match` query is malformed (curly brackets are missing in the Mustache template). The validation fails, returning an error: + +```json +{ + "validation": { + "params": { + "keywords": "rambo" + }, + "index": "tmdb" + }, + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{% raw %}{{keywords{% endraw %}" + } + } + } + ] + } +} +``` +{% include copy-curl.html %} + +## Expanding feature sets + +You may not initially know which features are the most useful. In these cases, you can later add new features to an existing feature set for logging and model evaluation. For example, if you want to create a `user_rating` feature, you can use the Feature Set Append API, as shown in the following example request: + +```json +POST /_ltr/_featureset/my_featureset/_addfeatures +{ + "features": [{ + "name": "user_rating", + "params": [], + "template_language": "mustache", + "template" : { + "function_score": { + "functions": { + "field": "vote_average" + }, + "query": { + "match_all": {} + } + } + } + }] +} +``` +{% include copy-curl.html %} + +## Enforcing unique feature names + +The Learning to Rank plugin enforces unique names for each feature. This is because some model training libraries refer to features by name. In the preceding example, you could not add a new `user_rating` feature without causing an error because that feature name is already in use. + +## Treating feature sets as lists + +Feature sets are more like ordered lists than simple sets. Each feature has both a name and an ordinal position. Some LTR training applications, such as RankLib, refer to features by their ordinal position (for example, 1st feature, 2nd feature). Others may use the feature name. When working with logged features, you may need to handle both the ordinal and the name because the ordinal is preserved to maintain the list order. + +## Next steps + +Learn about [feature engineering]({{site.url}}{{site.baseurl}}/search-plugins/ltr/feature-engineering/) and [advanced functionality]({{site.url}}{{site.baseurl}}/search-plugins/ltr/advanced-functionality/). diff --git a/_search-plugins/querqy/index.md b/_search-plugins/querqy/index.md index 4ec0c8eb..4157f318 100644 --- a/_search-plugins/querqy/index.md +++ b/_search-plugins/querqy/index.md @@ -1,34 +1,37 @@ --- layout: default title: Querqy -parent: Search relevance +parent: Query rewriting +grand_parent: Optimizing search quality has_children: false redirect_from: - /search-plugins/querqy/ -nav_order: 210 +nav_order: 60 --- # Querqy -Querqy is a community plugin for query rewriting that helps to solve relevance issues, making search engines more precise regarding matching and scoring. +Querqy for OpenSearch is a community plugin for query rewriting that improves search relevance. It makes OpenSearch more precise in matching and scoring by applying rules for boosting, burying, filtering, and redirecting search results, among other capabilities. + +Querqy supports OpenSearch versions up to 3.8.0. For a list of supported OpenSearch versions, see [Querqy for OpenSearch releases](https://github.com/querqy/querqy-opensearch/releases). +{: .note } + +For more information, see the [Querqy documentation](https://docs.querqy.org/querqy/index.html). -Querqy is currently only supported in OpenSearch 2.3. -{: .warning } ## Querqy plugin installation -The Querqy plugin is now available for OpenSearch 2.3.0. Run the following command to install the Querqy plugin. +The Querqy plugin is now available for OpenSearch 2.19.2. Run the following command to install the Querqy plugin: ````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" + "https://repo1.maven.org/maven2/org/querqy/opensearch-querqy/1.1.os2.19.2/opensearch-querqy-1.1.os2.19.2.zip" ```` Answer `yes` to the security prompts during the installation as Querqy requires additional permissions to load query rewriters. -After installing the Querqy plugin you can find comprehensive documentation on the Querqy.org site: [Querqy](https://docs.querqy.org/querqy/index.html) -## Path and HTTP methods +## Endpoints ``` POST /myindex/_search @@ -47,4 +50,4 @@ POST /myindex/_search } } } -```` \ No newline at end of file +```` diff --git a/_search-plugins/search-pipelines/agentic-context-processor.md b/_search-plugins/search-pipelines/agentic-context-processor.md new file mode 100644 index 00000000..fefba032 --- /dev/null +++ b/_search-plugins/search-pipelines/agentic-context-processor.md @@ -0,0 +1,105 @@ +--- +layout: default +title: Agentic context +nav_order: 2 +has_children: false +parent: Search processors +grand_parent: Search pipelines +--- + +# Agentic context processor +**Introduced 3.3** +{: .label .label-purple } + +The `agentic_context` search response processor adds agent execution context information to search response extensions. This processor works in conjunction with the [agentic query translator]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-query-translator-processor/) to expose the agent's query translation process and maintain conversation continuity: + +1. The processor retrieves agent context information from the pipeline processing context. +2. Based on the processor configuration, it selectively includes the agent steps summary and the query domain-specific language (DSL) query in the response. +3. The memory ID is always included, when available, for conversation continuity. +4. The context information is added to the search response extensions. +5. Type validation ensures that all context attributes are strings. + +This processor works with both conversational and flow agents, but the available context information differs by agent type. Flow agents provide `dsl_query` (the generated DSL) only, while conversational agents provide `dsl_query`, `memory_id`, and `agent_steps_summary`. For more information, see [Agent types]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/#agent-types). + +## Request body fields + +The following table lists all available request fields. + +Field | Data type | Description +:--- | :--- | :--- +`agent_steps_summary` | Boolean | Whether to include the agent's execution step summary in the response. Available for conversational agents only. Optional. Default is `false`. +`dsl_query` | Boolean | Whether to include the generated DSL query in the response. Available for both conversational and flow agents. Optional. Default is `false`. + +## Response fields + +When enabled, the processor adds the following fields to the search response extensions. + +Field | Description +:--- | :--- +`agent_steps_summary` | A summary of the steps that the agent took to translate the natural language query (included when `agent_steps_summary` is `true`). Available for conversational agents only. +`memory_id` | The conversation memory ID for maintaining context across queries. Available for conversational agents only. Only provide this in the `agentic` query if you want to continue the previous conversation. +`dsl_query` | The generated DSL query that was executed (included when `dsl_query` is `true`). Available for both conversational and flow agents. + +## Example + +The following example request creates a search pipeline with an `agentic_context` response processor: + +```json +PUT /_search/pipeline/agentic_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "your-agent-id" + } + } + ], + "response_processors": [ + { + "agentic_context": { + "agent_steps_summary": true, + "dsl_query": true + } + } + ] +} +``` +{% include copy-curl.html %} + +Perform a search using the configured pipeline: + +```json +POST /your-index/_search?search_pipeline=agentic_search_pipeline +{ + "query": { + "agentic": { + "query_text": "Show me shoes in white color", + "memory_id": "your memory id" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the steps taken by the agent to translate the query, the memory ID, and the rewritten DSL query: + +```json +{ + "took": 15, + "hits": { + "_shards": {...}, + "hits": [...] + }, + "ext": { + "agent_steps_summary": "I have these tools available: [ListIndexTool, IndexMappingTool, query_planner_tool]\\nFirst I used: ListIndexTool — input: \"\"; context gained: \"Discovered products-index which seems relevant for products and pricing context\"\\nSecond I used: IndexMappingTool — input: \"products-index\"; context gained: \"Confirmed presence of category and price fields in products-index\"\\nThird I used: query_planner_tool — qpt.question: \"Show me shoes that cost exactly 100 dollars.\"; index_name_provided: \"products-index\"\\nValidation: qpt output is valid and accurately reflects the request for shoes priced at 100 dollars.", + "memory_id": "WVhHiJkBnqovov2plcDH", + "dsl_query": "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"category\":\"shoes\"}},{\"term\":{\"price\":100.0}}]}}}" + } +} +``` + +## Related documentation + +- [Agentic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/) +- [Agentic query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/agentic/) +- [Agentic query translator processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-query-translator-processor/) \ No newline at end of file diff --git a/_search-plugins/search-pipelines/agentic-query-translator-processor.md b/_search-plugins/search-pipelines/agentic-query-translator-processor.md new file mode 100644 index 00000000..3c02a18b --- /dev/null +++ b/_search-plugins/search-pipelines/agentic-query-translator-processor.md @@ -0,0 +1,151 @@ +--- +layout: default +title: Agentic query translator +nav_order: 5 +has_children: false +parent: Search processors +grand_parent: Search pipelines +--- + +# Agentic query translator processor +**Introduced 3.2** +{: .label .label-purple } + +The `agentic_query_translator` search request processor enables natural language search by translating user queries into OpenSearch query domain-specific language (DSL) queries using machine learning (ML) agents. It works with [agentic search queries]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/) to provide conversational search capabilities: + +1. The processor sends the user's natural language query to the specified ML agent. +2. The agent translates the query into OpenSearch DSL. +3. The original query is replaced with the generated DSL query. + +This processor only works with the `agentic` query type as the top-level query. +{: .note} + +## Prerequisites + +Before using the `agentic_query_translator` processor, you must have either a conversational or flow agent configured. For more information, see [Agents]({{site.url}}{{site.baseurl}}/ml-commons-plugin/agents-tools/agents/index/). + +## Request body fields + +The following table lists all available request fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`agent_id` | String | Required | The ID of the ML agent that will translate natural language queries into DSL queries. +`embedding_model_id` | String | Optional | The ID of the embedding model that generates vector embeddings for semantic search using `neural` queries. This parameter takes precedence over the `embedding_model_id` specified in the agent configuration. For more information, see [Configuring agents for semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/neural-search/). + + +## Example + +The following example request creates a search pipeline with an `agentic_query_translator` processor: + +```json +PUT /_search/pipeline/agentic_search_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "your-agent-id-here" + } + } + ] +} +``` +{% include copy-curl.html %} + +To enable semantic search capabilities, you can optionally specify an `embedding_model_id` for the text embedding model that converts queries into vector embeddings: + +```json +PUT /_search/pipeline/agentic_search_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "your-agent-id-here", + "embedding_model_id": "your-embedding-model-id" + } + } + ] +} +``` +{% include copy-curl.html %} + +## Usage + +To use the processor, run an `agentic` query: + +```json +POST /your-index/_search?search_pipeline=agentic_search_pipeline +{ + "query": { + "agentic": { + "query_text": "Show me shoes in white color" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching documents: + +```json +{ + "took": 6031, + "timed_out": false, + "_shards": { + "total": 8, + "successful": 8, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 8, + "relation": "eq" + }, + "max_score": 0.0, + "hits": [ + { + "_index": "products-index", + "_id": "43", + "_score": 0.0, + "_source": { + "product_name": "Nike Air Max white", + "description": "Red cushioned sneakers", + "price": 140.0, + "currency": "USD", + "in_stock": true, + "color": "white", + "size": "10", + "product_id": "P6001", + "category": "shoes", + "brand": "Nike" + } + }, + { + "_index": "products-index", + "_id": "45", + "_score": 0.0, + "_source": { + "product_name": "Adidas Superstar white", + "description": "Classic black sneakers", + "price": 100.0, + "currency": "USD", + "in_stock": true, + "color": "white", + "size": "8", + "product_id": "P6003", + "category": "shoes", + "brand": "Adidas" + } + } + ] + } +} +``` + +## Related documentation + +- [Agentic search queries]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/index/) +- [Agentic query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/agentic/) +- [Configuring agents for semantic search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/neural-search/) +- [Agentic context processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-context-processor/) \ No newline at end of file diff --git a/_search-plugins/search-pipelines/collapse-processor.md b/_search-plugins/search-pipelines/collapse-processor.md index cea0a153..4865a68d 100644 --- a/_search-plugins/search-pipelines/collapse-processor.md +++ b/_search-plugins/search-pipelines/collapse-processor.md @@ -1,13 +1,15 @@ --- layout: default title: Collapse -nav_order: 7 +nav_order: 10 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Collapse processor +Introduced 2.12 +{: .label .label-purple } The `collapse` response processor discards hits that have the same value for a particular field as a previous document in the result set. This is similar to passing the `collapse` parameter in a search request, but the response processor is applied to the @@ -18,7 +20,7 @@ Using the `collapse` response processor will likely result in fewer than `size` from a set whose size is already less than or equal to `size`. To increase the likelihood of returning `size` hits, use the `oversample` request processor and `truncate_hits` response processor, as shown in [this example]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/truncate-hits-processor/#oversample-collapse-and-truncate-hits). -## Request fields +## Request body fields The following table lists all request fields. diff --git a/_search-plugins/search-pipelines/creating-search-pipeline.md b/_search-plugins/search-pipelines/creating-search-pipeline.md index c33a763e..dc39e95b 100644 --- a/_search-plugins/search-pipelines/creating-search-pipeline.md +++ b/_search-plugins/search-pipelines/creating-search-pipeline.md @@ -4,7 +4,6 @@ title: Creating a search pipeline nav_order: 10 has_children: false parent: Search pipelines -grand_parent: Search --- # Creating a search pipeline diff --git a/_search-plugins/search-pipelines/debugging-search-pipeline.md b/_search-plugins/search-pipelines/debugging-search-pipeline.md new file mode 100644 index 00000000..30d81e26 --- /dev/null +++ b/_search-plugins/search-pipelines/debugging-search-pipeline.md @@ -0,0 +1,229 @@ +--- +layout: default +title: Debugging a search pipeline +nav_order: 25 +has_children: false +parent: Search pipelines +--- + + +# Debugging a search pipeline + +The `verbose_pipeline` parameter provides detailed information about the data flow and transformations for the search request, search response, and search phase processors in the search pipeline. It helps with troubleshooting and optimizing the pipeline and ensures transparency in handling search requests and responses. + +## Enabling debugging + +To enable pipeline debugging, specify `verbose_pipeline=true` as a query parameter in your search request. This functionality is available for all three search pipeline methods: + +- [Default search pipeline](#default-search-pipeline) +- [Specific search pipeline](#specific-search-pipeline) +- [Temporary search pipeline](#temporary-search-pipeline) + +### Default search pipeline + +To use `verbose_pipeline` with a default search pipeline, set the pipeline as the default in the index settings and include `verbose_pipeline=true` in the query: + +```json +PUT /my_index/_settings +{ + "index.search.default_pipeline": "my_pipeline" +} +``` +{% include copy-curl.html %} + +```json +GET /my_index/_search?verbose_pipeline=true +``` +{% include copy-curl.html %} + +For more information about default search pipelines, see [Setting a default pipeline for all requests in an index]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/using-search-pipeline/#default-search-pipeline). + +### Specific search pipeline + +To use `verbose_pipeline` with a specific search pipeline, specify the pipeline ID and include `verbose_pipeline=true` in the query: + +```json +GET /my_index/_search?search_pipeline=my_pipeline&verbose_pipeline=true +``` +{% include copy-curl.html %} + +For more information about using specific search pipelines, see [Specifying an existing pipeline for a request]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/using-search-pipeline/#specifying-an-existing-search-pipeline-for-a-request). + +### Temporary search pipeline + +To use `verbose_pipeline` with a temporary search pipeline, define the pipeline directly in the request body and include `verbose_pipeline=true` in the query: + +```json +POST /my_index/_search?verbose_pipeline=true +{ + "query": { + "match": { "text_field": "some search text" } + }, + "search_pipeline": { + "request_processors": [ + { + "filter_query": { + "query": { "term": { "visibility": "public" } } + } + } + ], + "response_processors": [ + { + "collapse": { + "field": "category" + } + } + ] + } +} +``` +{% include copy-curl.html %} + +For more information about using a temporary search pipeline, see [Using a temporary pipeline for a request]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/using-search-pipeline/#using-a-temporary-search-pipeline-for-a-request). + +## Example response + +When the `verbose_pipeline` parameter is enabled, the response contains an additional `processor_results` field that provides information about the transformations applied by each processor in the pipeline: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 27, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.18232156, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.18232156, + "_source": { + "notification": "This is a public message", + "visibility": "public" + } + } + ] + }, + "processor_results": [ + { + "processor_name": "filter_query", + "tag": "tag1", + "duration_millis": 288541, + "status": "success", + "input_data": { + "verbose_pipeline": true, + "query": { + "bool": { + "adjust_pure_negative": true, + "must": [ + { + "match": { + "message": { + "auto_generate_synonyms_phrase_query": true, + "query": "this", + "zero_terms_query": "NONE", + "fuzzy_transpositions": true, + "boost": 1.0, + "prefix_length": 0, + "operator": "OR", + "lenient": false, + "max_expansions": 50 + } + } + } + ], + "boost": 1.0 + } + } + }, + "output_data": { + "verbose_pipeline": true, + "query": { + "bool": { + "filter": [ + { + "term": { + "visibility": { + "boost": 1.0, + "value": "public" + } + } + } + ], + "adjust_pure_negative": true, + "must": [ + { + "bool": { + "adjust_pure_negative": true, + "must": [ + { + "match": { + "message": { + "auto_generate_synonyms_phrase_query": true, + "query": "this", + "zero_terms_query": "NONE", + "fuzzy_transpositions": true, + "boost": 1.0, + "prefix_length": 0, + "operator": "OR", + "lenient": false, + "max_expansions": 50 + } + } + } + ], + "boost": 1.0 + } + } + ], + "boost": 1.0 + } + } + } + }, + { + "processor_name": "rename_field", + "duration_millis": 250042, + "status": "success", + "input_data": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.18232156, + "_source": { + "message": "This is a public message", + "visibility": "public" + } + } + ], + "output_data": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.18232156, + "_source": { + "notification": "This is a public message", + "visibility": "public" + } + } + ] + } + ] +} +``` +</details> \ No newline at end of file diff --git a/_search-plugins/search-pipelines/deleting-search-pipeline.md b/_search-plugins/search-pipelines/deleting-search-pipeline.md new file mode 100644 index 00000000..d00ba53d --- /dev/null +++ b/_search-plugins/search-pipelines/deleting-search-pipeline.md @@ -0,0 +1,25 @@ +--- +layout: default +title: Deleting search pipelines +nav_order: 30 +has_children: false +parent: Search pipelines +--- + +# Deleting search pipelines + +Use the following request to delete a pipeline. + +To delete a specific search pipeline, pass the pipeline ID as a parameter: + +```json +DELETE /_search/pipeline/{pipeline-id} +``` +{% include copy-curl.html %} + +To delete all search pipelines in a cluster, use the wildcard character (`*`): + +```json +DELETE /_search/pipeline/* +``` +{% include copy-curl.html %} diff --git a/_search-plugins/search-pipelines/explanation-processor.md b/_search-plugins/search-pipelines/explanation-processor.md new file mode 100644 index 00000000..0edb6bf7 --- /dev/null +++ b/_search-plugins/search-pipelines/explanation-processor.md @@ -0,0 +1,223 @@ +--- +layout: default +title: Hybrid score explanation +nav_order: 15 +has_children: false +parent: User-defined search processors +grand_parent: Search pipelines +--- + +# Hybrid score explanation processor +Introduced 2.19 +{: .label .label-purple } + +The `hybrid_score_explanation` response processor adds the normalization and combination results to the returned search response. You can use it as a debugging tool to understand the score normalization process. For more information, see [Hybrid query]({{site.url}}{{site.baseurl}}/query-dsl/compound/hybrid/). + +To use the `explain` parameter with a hybrid query that runs through a search pipeline, you must configure the `hybrid_score_explanation` response processor in that pipeline. +{: .important} + +A hybrid query running in [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/) does not require this processor. In fusion mode, `explain` describes the normalization and combination without a search pipeline, using the same descriptions shown on this page. +{: .note} + +## Request body fields + +The following table lists all request fields. + +Field | Data type | Description +:--- | :--- | :--- +`tag` | String | The processor's identifier. Optional. +`description` | String | A description of the processor. Optional. +`ignore_failure` | Boolean | If `true`, OpenSearch [ignores any failure]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/#ignoring-processor-failures) of this processor and continues to run the remaining processors in the search pipeline. Optional. Default is `false`. + +## Example + +The following example demonstrates using a search pipeline with a `hybrid_score_explanation` processor. + +For a comprehensive example, follow the [Getting started with semantic and hybrid search]({{site.url}}{{site.baseurl}}/ml-commons-plugin/semantic-search#tutorial). + +### Creating a search pipeline + +The following request creates a search pipeline containing a `normalization-processor` and a `hybrid_score_explanation` processor: + +```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" + } + } + } + ], + "response_processors": [ + { + "hybrid_score_explanation": {} + } + ] +} +``` +{% include copy-curl.html %} + +### Using a search pipeline + +To see explanation information, specify `explain=true` in your search request: + +```json +GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline&explain=true +{ + "_source": { + "exclude": [ + "passage_embedding" + ] + }, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "text": { + "query": "horse" + } + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "wild west", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "took": 54, + "timed_out": false, + "_shards": { + "total": 2, + "successful": 2, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 0.9251075, + "hits": [ + { + "_shard": "[my-nlp-index][0]", + "_node": "IsuzeVYdSqKUfy0qfqil2w", + "_index": "my-nlp-index", + "_id": "5", + "_score": 0.9251075, + "_source": { + "text": "A rodeo cowboy , wearing a cowboy hat , is being thrown off of a wild white horse .", + "id": "2691147709.jpg" + }, + "_explanation": { + "value": 0.9251075, + "description": "arithmetic_mean combination of:", + "details": [ + { + "value": 1.0, + "description": "min_max normalization of:", + "details": [ + { + "value": 1.2336599, + "description": "weight(text:horse in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 1.2336599, + "description": "score(freq=1.0), computed as boost * idf * tf from:", + "details": [ + { + "value": 2.2, + "description": "boost", + "details": [] + }, + { + "value": 1.2039728, + "description": "idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:", + "details": [ + { + "value": 1, + "description": "n, number of documents containing term", + "details": [] + }, + { + "value": 4, + "description": "N, total number of documents with field", + "details": [] + } + ] + }, + { + "value": 0.46575344, + "description": "tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl)) from:", + "details": [ + { + "value": 1.0, + "description": "freq, occurrences of term within document", + "details": [] + }, + { + "value": 1.2, + "description": "k1, term saturation parameter", + "details": [] + }, + { + "value": 0.75, + "description": "b, length normalization parameter", + "details": [] + }, + { + "value": 16.0, + "description": "dl, length of field", + "details": [] + }, + { + "value": 17.0, + "description": "avgdl, average length of field", + "details": [] + } + ] + } + ] + } + ] + } + ] + }, + { + "value": 0.8503647, + "description": "min_max normalization of:", + "details": [ + { + "value": 0.015177966, + "description": "within top 5", + "details": [] + } + ] + } + ] +... +``` + +For more information about setting up hybrid search, see [Hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/hybrid-search/). \ No newline at end of file diff --git a/_search-plugins/search-pipelines/filter-query-processor.md b/_search-plugins/search-pipelines/filter-query-processor.md index 6c68821a..8eb69e64 100644 --- a/_search-plugins/search-pipelines/filter-query-processor.md +++ b/_search-plugins/search-pipelines/filter-query-processor.md @@ -1,17 +1,19 @@ --- layout: default title: Filter query -nav_order: 10 +nav_order: 20 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Filter query processor +Introduced 2.8 +{: .label .label-purple } The `filter_query` search request processor intercepts a search request and applies an additional query to the request, filtering the results. This is useful when you don't want to rewrite existing queries in your application but need additional filtering of the results. -## Request fields +## Request body fields The following table lists all available request fields. diff --git a/_search-plugins/search-pipelines/index.md b/_search-plugins/search-pipelines/index.md index d4edc289..f553b43a 100644 --- a/_search-plugins/search-pipelines/index.md +++ b/_search-plugins/search-pipelines/index.md @@ -4,31 +4,28 @@ title: Search pipelines nav_order: 100 has_children: true has_toc: false +redirect_from: + - /search-plugins/search-pipelines/ --- # Search pipelines -You can use _search pipelines_ to build new or reuse existing result rerankers, query rewriters, and other components that operate on queries or results. Search pipelines make it easier for you to process search queries and search results within OpenSearch. Moving some of your application functionality into an OpenSearch search pipeline reduces the overall complexity of your application. As part of a search pipeline, you specify a list of processors that perform modular tasks. You can then easily add or reorder these processors to customize search results for your application. +You can use _search pipelines_ to build new or reuse existing result rerankers, query rewriters, and other components that operate on queries or results. Search pipelines make it easier for you to process search queries and search results within OpenSearch. Moving some of your application functionality into an OpenSearch search pipeline reduces the overall complexity of your application. As part of a search pipeline, you specify a list of search processors that perform modular tasks. You can then easily add or reorder these processors to customize search results for your application. -## Terminology - -The following is a list of search pipeline terminology: - -* [_Search request processor_]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors#search-request-processors): A component that intercepts a search request (the query and the metadata passed in the request), performs an operation with or on the search request, and returns the search request. -* [_Search response processor_]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors#search-response-processors): A component that intercepts a search response and search request (the query, results, and metadata passed in the request), performs an operation with or on the search response, and returns the search response. -* [_Search phase results processor_]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors#search-phase-results-processors): A component that runs between search phases at the coordinating node level. A search phase results processor intercepts the results retrieved from one search phase and transforms them before passing them to the next search phase. -* [_Processor_]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors/): Either a search request processor or a search response processor. -* _Search pipeline_: An ordered list of processors that is integrated into OpenSearch. The pipeline intercepts a query, performs processing on the query, sends it to OpenSearch, intercepts the results, performs processing on the results, and returns them to the calling application, as shown in the following diagram. +When defined, a search pipeline is an ordered list of search processors that is integrated into OpenSearch. The pipeline shown in the following diagram intercepts a query, performs processing on the query, sends it to OpenSearch, intercepts the results, performs processing on the results, and returns them to the calling application. ![Search processor diagram]({{site.url}}{{site.baseurl}}/images/search-pipelines.png) -Both request and response processing for the pipeline are performed on the coordinator node, so there is no shard-level processing. +Both request and response processing for the pipeline are performed on the coordinating node, so there is no shard-level processing. {: .note} -## Processors +## Search processors -To learn more about available search processors, see [Search processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors/). +Search processors can be classified by **execution phase** (when they run): +- [Search request processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors#search-request-processors): A _search request processor_ intercepts a search request (the query and the metadata passed in the request), performs an operation with or on the search request, and submits the search request to the index. +- [Search response processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors#search-response-processors): A _search response processor_ intercepts a search response and search request (the query, results, and metadata passed in the request), performs an operation with or on the search response, and returns the search response. +- [Search phase results processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors#search-phase-results-processors): A _search phase results processor_ runs between search phases at the coordinating node level. It intercepts the results retrieved from one search phase and transforms them before passing them to the next search phase. ## Example @@ -75,6 +72,16 @@ Alternatively, you can use a temporary pipeline with a request or set a default To learn about retrieving details for an existing search pipeline, see [Retrieving search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/retrieving-search-pipeline/). +For information about troubleshooting search pipelines, see [Debugging search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/debugging-search-pipeline/). + +To delete an existing search pipeline, see [Deleting search pipelines]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/deleting-search-pipeline/). + +## Manual and automatic processor creation + +Search processors can be created manually or automatically: + +- [User-defined processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors/): Processors configured manually in search pipelines, like in the preceding [example](#example). +- [System-generated processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/system-generated-search-processors/): Processors automatically created by OpenSearch based on search request parameters. ## Search pipeline metrics diff --git a/_search-plugins/search-pipelines/ml-inference-search-request.md b/_search-plugins/search-pipelines/ml-inference-search-request.md new file mode 100644 index 00000000..ace1dc12 --- /dev/null +++ b/_search-plugins/search-pipelines/ml-inference-search-request.md @@ -0,0 +1,539 @@ +--- +layout: default +title: ML inference (request) +nav_order: 30 +has_children: false +parent: User-defined search processors +grand_parent: Search pipelines +--- + +# ML inference search request processor +Introduced 2.16 +{: .label .label-purple } + +The `ml_inference` search request processor is used to invoke registered machine learning (ML) models in order to rewrite queries using the model output. + +**PREREQUISITE**<br> +Before using the `ml_inference` search request processor, you must have either a local ML model hosted on your OpenSearch cluster or an externally hosted model connected to your OpenSearch cluster through the ML Commons plugin. For more information about local models, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). +For more information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). +{: .note} + +## Syntax + +The following is the syntax for the `ml-inference` search request processor: + +```json +{ + "ml_inference": { + "model_id": "<model_id>", + "function_name": "<function_name>", + "full_response_path": "<full_response_path>", + "query_template": "<query_template>", + "model_config": { + "<model_config_field>": "<config_value>" + }, + "model_input": "<model_input>", + "input_map": [ + { + "<model_input_field>": "<query_input_field>" + } + ], + "output_map": [ + { + "<query_output_field>": "<model_output_field>" + } + ] + } +} +``` +{% include copy-curl.html %} + +## Configuration parameters + +The following table lists the required and optional parameters for the `ml-inference` search request processor. + +| Parameter | Data type | Required/Optional | Description | +|:--| :--- |:---|:---| +| `model_id`| String | Required | The ID of the ML model used by the processor. | +| `query_template` | String | Optional | A query string template used to construct a new query containing a `new_document_field`. Often used when rewriting a search query to a new query type. | +| `function_name` | String | Optional for externally hosted models<br/><br/>Required for local models | The function name of the ML model configured in the processor. For local models, valid values are `sparse_encoding`, `sparse_tokenize`, `text_embedding`, and `text_similarity`. For externally hosted models, valid value is `remote`. Default is `remote`. | +| `model_config` | Object | Optional | Custom configuration options for the ML model. For externally hosted models, if set, this configuration overrides the default connector parameters. For local models, you can add `model_config` to `model_input` to override the model configuration set during registration. For more information, see [The `model_config` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-model_config-object). | +| `model_input` | String | Optional for externally hosted models<br/><br/>Required for local models | A template that defines the input field format expected by the model. Each local model type might use a different set of inputs. For externally hosted models, default is `"{ \"parameters\": ${ml_inference.parameters} }`. | +| `input_map` | Array | Required if `optional_input_map` is not specified | An array specifying how to map query string fields to the model input fields. Each element of the array is a map in the `"<model_input_field>": "<query_input_field>"` format and corresponds to one model invocation of a document field. If no input mapping is specified for an externally hosted model, then all document fields are passed to the model directly as input. The `input_map` size indicates the number of times the model is invoked (the number of Predict API requests). | +| `<model_input_field>` | String | Required | The model input field name. | +| `<query_input_field>` | String | Required | The name or JSON path of the query field used as the model input. | +| `output_map` | Array | Required if `optional_output_map` is not specified | An array specifying how to map the model output fields to new fields in the query string. Each element of the array is a map in the `"<query_output_field>": "<model_output_field>"` format. | +| `<query_output_field>` | String | Required | The name of the query field in which the model's output (specified by `model_output`) is stored. | +| `<model_output_field>` | String | Required | The name or JSON path of the field in the model output to be stored in the `query_output_field`. | +| `optional_input_map` | Array | Optional | An array specifying query fields to map to the model input when they are present in the query, in the same format as `input_map`. If a field is missing from the query, it is not passed to the model. The processor invokes the model even if none of the optional fields are present, in which case the model receives no input from this mapping and may return an error. Each element is merged with the `input_map` element at the same position, and together they define one model invocation. Use this option when the model accepts several inputs and a query contains only some of them, for example, text, an image, or both. | +| `optional_output_map` | Array | Optional | An array specifying additional mappings from model output fields to query fields, in the same format as `output_map`. Each element is merged with the `output_map` element at the same position. | +| `full_response_path` | Boolean | Optional | Set this parameter to `true` if the `model_output_field` contains a full JSON path to the field instead of the field name. The model output will then be fully parsed to get the value of the field. Default is `true` for local models and `false` for externally hosted models. | +| `ignore_missing` | Boolean | Optional | If `true` and any of the input fields defined in the `input_map` or `output_map` are missing, then this processor is ignored. Otherwise, a missing field causes a failure. Default is `false`. | +| `ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If `true`, then this processor is ignored and the search continues. If `false`, then any failure causes the search to be canceled. Default is `false`. | +| `max_prediction_tasks` | Integer | Optional | The maximum number of concurrent model invocations that can run during query search. Default is `10`. | +| `description` | String | Optional | A brief description of the processor. | +| `tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | + +The `input_map` and `output_map` mappings support standard [JSON path](https://github.com/json-path/JsonPath) notation for specifying complex data structures. +{: .note} + +## Using the processor + +Follow these steps to use the processor in a pipeline. You must provide a model ID, an `input_map` or `optional_input_map`, and an `output_map` or `optional_output_map` when creating the processor. Before testing a pipeline using the processor, make sure that the model is successfully deployed. You can check the model state using the [Get Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/get-model/). + +For local models, you must provide a `model_input` field that specifies the model input format. Add any input fields in `model_config` to `model_input`. + +For externally hosted models, the `model_input` field is optional, and its default value +is `"{ \"parameters\": ${ml_inference.parameters} }`. + +### Setup + +Create an index named `my_index` and index two documents: + +```json +POST /my_index/_doc/1 +{ + "passage_text": "I am excited", + "passage_language": "en", + "label": "POSITIVE", + "passage_embedding": [ + 2.3886719, + 0.032714844, + -0.22229004 + ...] +} +``` +{% include copy-curl.html %} + +```json +POST /my_index/_doc/2 +{ + "passage_text": "I am sad", + "passage_language": "en", + "label": "NEGATIVE", + "passage_embedding": [ + 1.7773438, + 0.4309082, + 1.8857422, + 0.95996094, + ...] +} +``` +{% include copy-curl.html %} + +When you run a term query on the created index without a search pipeline, the query searches for documents that contain the exact term specified in the query. The following query does not return any results because the query text does not match any of the documents in the index: + +```json +GET /my_index/_search +{ + "query": { + "term": { + "passage_text": { + "value": "happy moments", + "boost": 1 + } + } + } +} +``` + +By using a model, the search pipeline can dynamically rewrite the term value to enhance or alter the search results based on the model inference. This means the model takes an initial input from the search query, processes it, and then updates the query term to reflect the model inference, potentially improving the relevance of the search results. + +### Example: Externally hosted model + +The following example configures an `ml_inference` processor with an externally hosted model. + +**Step 1: Create a pipeline** + +This example demonstrates how to create a search pipeline for an externally hosted sentiment analysis model that rewrites the term query value. The model requires an `inputs` field and produces results in a `label` field. Because the `function_name` is not specified, it defaults to `remote`, indicating an externally hosted model. + +The term query value is rewritten based on the model's output. The `ml_inference` processor in the search request needs an `input_map` to retrieve the query field value for the model input and an `output_map` to assign the model output to the query string. + +In this example, an `ml_inference` search request processor is used for the following term query: + +```json + { + "query": { + "term": { + "label": { + "value": "happy moments", + "boost": 1 + } + } + } +} +``` + +The following request creates a search pipeline that rewrites the preceding term query: + +```json +PUT /_search/pipeline/ml_inference_pipeline +{ + "description": "Generate passage_embedding for searched documents", + "request_processors": [ + { + "ml_inference": { + "model_id": "<your model id>", + "input_map": [ + { + "inputs": "query.term.label.value" + } + ], + "output_map": [ + { + "query.term.label.value": "label" + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +When making a Predict API request to an externally hosted model, all necessary fields and parameters are usually contained within a `parameters` object: + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict +{ + "parameters": { + "inputs": [ + { + ... + } + ] + } +} +``` + +Thus, to use an externally hosted sentiment analysis model, send a Predict API request in the following format: + +```json +POST /_plugins/_ml/models/cywgD5EB6KAJXDLxyDp1/_predict +{ + "parameters": { + "inputs": "happy moments" + } +} +``` +{% include copy-curl.html %} + +The model processes the input and generates a prediction based on the sentiment of the input text. In this case, the sentiment is positive: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "label": "POSITIVE", + "score": "0.948" + } + } + ], + "status_code": 200 + } + ] +} +``` + +When specifying the `input_map` for an externally hosted model, you can directly reference the `inputs` field instead of providing its dot path `parameters.inputs`: + +```json +"input_map": [ + { + "inputs": "query.term.label.value" + } +] +``` + +**Step 2: Run the pipeline** + +Once you have created a search pipeline, you can run the same term query with the search pipeline: + +```json +GET /my_index/_search?search_pipeline=my_pipeline_request_review +{ + "query": { + "term": { + "label": { + "value": "happy moments", + "boost": 1 + } + } + } +} +``` +{% include copy-curl.html %} + +The query term value is rewritten based on the model's output. The model determines that the sentiment of the query term is positive, so the rewritten query appears as follows: + +```json +{ + "query": { + "term": { + "label": { + "value": "POSITIVE", + "boost": 1 + } + } + } +} +``` + +The response includes the document whose `label` field has the value `POSITIVE`: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "3", + "_score": 0.00009405752, + "_source": { + "passage_text": "I am excited", + "passage_language": "en", + "label": "POSITIVE" + } + } + ] + } +} +``` + +### Example: Local model + +The following example shows you how to configure an `ml_inference` processor with a local model to rewrite a term query into a k-NN query. + +**Step 1: Create a pipeline** + +The following example shows you how to create a search pipeline for the `huggingface/sentence-transformers/all-distilroberta-v1` local model. The model is a [pretrained sentence transformer model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#sentence-transformers) +hosted in your OpenSearch cluster. + +If you invoke the model using the Predict API, then the request appears as follows: + +```json +POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs": [ + "today is sunny" + ], + "return_number": true, + "target_response": [ + "sentence_embedding" + ] +} +``` + +Using this schema, specify the `model_input` as follows: + +```json + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }" +``` + +In the `input_map`, map the `query.term.passage_embedding.value` query field to the `text_docs` field expected by the model: + +```json +"input_map": [ + { + "text_docs": "query.term.passage_embedding.value" + } +] +``` + +Because you specified the field to be converted into embeddings as a JSON path, you need to set the `full_response_path` to `true`. Then the full JSON document is parsed in order to obtain the input field: + +```json +"full_response_path": true +``` + +The text in the `query.term.passage_embedding.value` field will be used to generate embeddings: + +```json +{ + "text_docs": "happy passage" +} +``` + +The Predict API request returns the following response: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [ + 768 + ], + "data": [ + 0.25517133, + -0.28009856, + 0.48519906, + ... + ] + } + ] + } + ] +} +``` + +The model generates embeddings in the `$.inference_results.*.output.*.data` field. The `output_map` maps this field to the query field in the query template: + +```json +"output_map": [ + { + "modelPredictionOutcome": "$.inference_results.*.output.*.data" + } +] +``` + +To configure an `ml_inference` search request processor with a local model, specify the `function_name` explicitly. In this example, the `function_name` is `text_embedding`. For information about valid `function_name` values, see [Configuration parameters](#configuration-parameters). + +The following is the final configuration of the `ml_inference` processor with the local model: + +```json +PUT /_search/pipeline/ml_inference_pipeline_local +{ + "description": "searchs reviews and generates embeddings", + "request_processors": [ + { + "ml_inference": { + "function_name": "text_embedding", + "full_response_path": true, + "model_id": "<your model id>", + "model_config": { + "return_number": true, + "target_response": [ + "sentence_embedding" + ] + }, + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }", + "query_template": """{ + "size": 2, + "query": { + "knn": { + "passage_embedding": { + "vector": ${modelPredictionOutcome}, + "k": 5 + } + } + } + }""", + "input_map": [ + { + "text_docs": "query.term.passage_embedding.value" + } + ], + "output_map": [ + { + "modelPredictionOutcome": "$.inference_results.*.output.*.data" + } + ], + "ignore_missing": true, + "ignore_failure": true + } + } + ] +} +``` +{% include copy-curl.html %} + +**Step 2: Run the pipeline** + +Run the following query, providing the pipeline name in the request: + +```json +GET /my_index/_search?search_pipeline=ml_inference_pipeline_local +{ +"query": { + "term": { + "passage_embedding": { + "value": "happy passage" + } + } + } +} +``` +{% include copy-curl.html %} + +The response confirms that the processor ran a k-NN query, which returned document 1 with a higher score: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.00009405752, + "_source": { + "passage_text": "I am excited", + "passage_language": "en", + "label": "POSITIVE", + "passage_embedding": [ + 2.3886719, + 0.032714844, + -0.22229004 + ...] + } + }, + { + "_index": "my_index", + "_id": "2", + "_score": 0.00001405052, + "_source": { + "passage_text": "I am sad", + "passage_language": "en", + "label": "NEGATIVE", + "passage_embedding": [ + 1.7773438, + 0.4309082, + 1.8857422, + 0.95996094, + ... + ] + } + } + ] + } +} +``` + +## Next steps + +- For a complete example of searching by text and image, see [Multimodal search using ML inference processors]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-search/multimodal-search-ml-inference/). +- For a complete example of rewriting a query into a vector search, see [Semantic search using text chunking]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-search/long-document/). +- For a complete example that uses compressed embeddings at search time, see [Optimizing vector search using Cohere compressed embeddings]({{site.url}}{{site.baseurl}}/tutorials/vector-search/vector-operations/optimize-compression/). diff --git a/_search-plugins/search-pipelines/ml-inference-search-response.md b/_search-plugins/search-pipelines/ml-inference-search-response.md new file mode 100644 index 00000000..6c1920c5 --- /dev/null +++ b/_search-plugins/search-pipelines/ml-inference-search-response.md @@ -0,0 +1,759 @@ +--- +layout: default +title: ML inference (response) +nav_order: 40 +has_children: false +parent: User-defined search processors +grand_parent: Search pipelines +--- + +# ML inference search response processor +Introduced 2.16 +{: .label .label-purple } + +The `ml_inference` search response processor is used to invoke registered machine learning (ML) models in order to incorporate their outputs as new fields in documents within search results. + +**PREREQUISITE**<br> +Before using the `ml_inference` search response processor, you must have either a local ML model hosted on your OpenSearch cluster or an externally hosted model connected to your OpenSearch cluster through the ML Commons plugin. For more information about local models, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). For more information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). +{: .note} + +## Syntax + +The following is the syntax for the `ml-inference` search response processor: + +```json +{ + "ml_inference": { + "model_id": "<model_id>", + "function_name": "<function_name>", + "full_response_path": "<full_response_path>", + "model_config":{ + "<model_config_field>": "<config_value>" + }, + "model_input": "<model_input>", + "input_map": [ + { + "<model_input_field>": "<document_field>" + } + ], + "output_map": [ + { + "<new_document_field>": "<model_output_field>" + } + ], + "override": "<override>", + "one_to_one": false + } +} +``` +{% include copy-curl.html %} + +## Request body fields + +The following table lists the required and optional parameters for the `ml-inference` search response processor. + +| Parameter | Data type | Required/Optional | Description | +|:--| :--- | :--- |:---| +| `model_id` | String | Required | The ID of the ML model used by the processor. | +| `function_name` | String | Optional for externally hosted models<br/><br/>Required for local models | The function name of the ML model configured in the processor. For local models, valid values are `sparse_encoding`, `sparse_tokenize`, `text_embedding`, and `text_similarity`. For externally hosted models, valid value is `remote`. Default is `remote`. | +| `model_config` | Object | Optional | Custom configuration options for the ML model. For externally hosted models, if set, this configuration overrides the default connector parameters. For local models, you can add `model_config` to `model_input` to override the model configuration set during registration. For more information, see [The `model_config` object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/register-model/#the-model_config-object). | +| `model_input` | String | Optional for externally hosted models<br/><br/>Required for local models | A template that defines the input field format expected by the model. Each local model type might use a different set of inputs. For externally hosted models, default is `"{ \"parameters\": ${ml_inference.parameters} }`. | +| `input_map` | Array | Optional for externally hosted models<br/><br/>Required for local models | An array specifying how to map document fields in the search response to the model input fields. Each element of the array is a map in the `"<model_input_field>": "<document_field>"` format and corresponds to one model invocation of a document field. If no input mapping is specified for an externally hosted model, then all document fields are passed to the model directly as input. The `input_map` size indicates the number of times the model is invoked (the number of Predict API requests). | +| `<model_input_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The model input field name. | +| `<document_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The name or JSON path of the document field in the search response used as the model input. | +| `output_map` | Array | Optional for externally hosted models<br/><br/>Required for local models | An array specifying how to map the model output fields to new fields in the search response document. Each element of the array is a map in the `"<new_document_field>": "<model_output_field>"` format. | +| `<new_document_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The name of the new field in the document in which the model's output (specified by `model_output`) is stored. If no output mapping is specified for externally hosted models, then all fields from the model output are added to the new document field. | +| `<model_output_field>` | String | Optional for externally hosted models<br/><br/>Required for local models | The name or JSON path of the field in the model output to be stored in the `new_document_field`. | +| `full_response_path` | Boolean | Optional | Set this parameter to `true` if the `model_output_field` contains a full JSON path to the field instead of the field name. The model output will then be fully parsed to get the value of the field. Default is `true` for local models and `false` for externally hosted models. | +| `ignore_missing` | Boolean | Optional | If `true` and any of the input fields defined in the `input_map` or `output_map` are missing, then this processor is ignored. Otherwise, a missing field causes a failure. Default is `false`. | +| `ignore_failure` | Boolean | Optional | Specifies whether the processor continues execution even if it encounters an error. If `true`, then this processor is ignored and the search continues. If `false`, then any failure causes the search to be canceled. Default is `false`. | +| `override` | Boolean | Optional | Relevant if a document in the response already contains a field with the name specified in `<new_document_field>`. If `override` is `false`, then the input field is skipped. If `true`, then the existing field value is overridden by the new model output. Default is `false`. | +| `max_prediction_tasks` | Integer | Optional | The maximum number of concurrent model invocations that can run during document search. Default is `10`. | +| `one_to_one` | Boolean | Optional | Set this parameter to `true` to invoke the model once (make one Predict API request) for each document. Default value (`false`) specifies to invoke the model with all documents from the search response, making one Predict API request. | +| `description` | String | Optional | A brief description of the processor. | +| `tag` | String | Optional | An identifier tag for the processor. Useful for debugging to distinguish between processors of the same type. | + +The `input_map` and `output_map` mappings support standard [JSON path](https://github.com/json-path/JsonPath) notation for specifying complex data structures. +{: .note} + +### Setup + +Create an index named `my_index` and index one document to explain the mappings: + +```json +POST /my_index/_doc/1 +{ + "passage_text": "hello world" +} +``` +{% include copy-curl.html %} + +## Using the processor + +Follow these steps to use the processor in a pipeline. You must provide a model ID when creating the processor. Before testing a pipeline using the processor, make sure that the model is successfully deployed. You can check the model state using the [Get Model API]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/model-apis/get-model/). + +For local models, you must provide a `model_input` field that specifies the model input format. Add any input fields in `model_config` to `model_input`. + +For remote models, the `model_input` field is optional, and its default value is `"{ \"parameters\": ${ml_inference.parameters} }`. + +### Example: Local model + +The following example shows you how to configure an `ml_inference` search response processor with a local model. + +**Step 1: Create a pipeline** + +The following example shows you how to create a search pipeline for the `huggingface/sentence-transformers/all-distilroberta-v1` local model. The model is a [pretrained sentence transformer model]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#sentence-transformers) hosted in your OpenSearch cluster. + +If you invoke the model using the Predict API, then the request appears as follows: + +```json +POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs":[ "today is sunny"], + "return_number": true, + "target_response": ["sentence_embedding"] +} +``` + +Using this schema, specify the `model_input` as follows: + +```json + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }" +``` + +In the `input_map`, map the `passage_text` document field to the `text_docs` field expected by the model: + +```json +"input_map": [ + { + "text_docs": "passage_text" + } +] +``` + +Because you specified the field to be converted into embeddings as a JSON path, you need to set the `full_response_path` to `true`. Then the full JSON document is parsed in order to obtain the input field: + +```json +"full_response_path": true +``` + +The text in the `passage_text` field will be used to generate embeddings: + +```json +{ + "passage_text": "hello world" +} +``` + +The Predict API request returns the following response: + +```json +{ + "inference_results" : [ + { + "output" : [ + { + "name" : "sentence_embedding", + "data_type" : "FLOAT32", + "shape" : [ + 768 + ], + "data" : [ + 0.25517133, + -0.28009856, + 0.48519906, + ... + ] + } + ] + } + ] +} +``` + +The model generates embeddings in the `$.inference_results.*.output.*.data` field. The `output_map` maps this field to the newly created `passage_embedding` field in the search response document: + +```json +"output_map": [ + { + "passage_embedding": "$.inference_results.*.output.*.data" + } +] +``` + +To configure an `ml_inference` search response processor with a local model, specify the `function_name` explicitly. In this example, the `function_name` is `text_embedding`. For information about valid `function_name` values, see [Request fields](#request-body-fields). + +The following is the final configuration of the `ml_inference` search response processor with the local model: + +```json +PUT /_search/pipeline/ml_inference_pipeline_local +{ + "description": "search passage and generates embeddings", + "response_processors": [ + { + "ml_inference": { + "function_name": "text_embedding", + "full_response_path": true, + "model_id": "<your model id>", + "model_config": { + "return_number": true, + "target_response": ["sentence_embedding"] + }, + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }", + "input_map": [ + { + "text_docs": "passage_text" + } + ], + "output_map": [ + { + "passage_embedding": "$.inference_results.*.output.*.data" + } + ], + "ignore_missing": true, + "ignore_failure": true + } + } + ] +} +``` +{% include copy-curl.html %} + +**Step 2: Run the pipeline** + +Run the following query, providing the pipeline name in the request: + +```json +GET /my_index/_search?search_pipeline=ml_inference_pipeline_local +{ +"query": { + "term": { + "passage_text": { + "value": "hello" + } + } + } +} +``` +{% include copy-curl.html %} + +#### Response + +The response confirms that the processor has generated text embeddings in the `passage_embedding` field: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.00009405752, + "_source": { + "passage_text": "hello world", + "passage_embedding": [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ...] + } + } + ] + } +} +``` + +### Example: Externally hosted text embedding model + +The following example shows you how to configure an `ml_inference` search response processor with an externally hosted model. + +**Step 1: Create a pipeline** + +The following example shows you how to create a search pipeline for an externally hosted text embedding model. The model requires an `input` field and generates results in a `data` field. It converts the text in the `passage_text` field into text embeddings and stores the embeddings in the `passage_embedding` field. The `function_name` is not explicitly specified in the processor configuration, so it defaults to `remote`, signifying an externally hosted model: + +```json +PUT /_search/pipeline/ml_inference_pipeline +{ + "description": "Generate passage_embedding when search documents", + "response_processors": [ + { + "ml_inference": { + "model_id": "<your model id>", + "input_map": [ + { + "input": "passage_text" + } + ], + "output_map": [ + { + "passage_embedding": "data" + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +When making a Predict API request to an externally hosted model, all necessary fields and parameters are usually contained within a `parameters` object: + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict +{ + "parameters": { + "input": [ + { + ... + } + ] + } +} +``` + +When specifying the `input_map` for an externally hosted model, you can directly reference the `input` field instead of providing its dot path `parameters.input`: + +```json +"input_map": [ + { + "input": "passage_text" + } +] +``` + +**Step 2: Run the pipeline** + +Run the following query, providing the pipeline name in the request: + +```json +GET /my_index/_search?search_pipeline=ml_inference_pipeline_local +{ + "query": { + "match_all": { + } + } +} +``` +{% include copy-curl.html %} + +The response confirms that the processor has generated text embeddings in the `passage_embedding` field. The document within `_source` now contains both the `passage_text` and `passage_embedding` fields: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.00009405752, + "_source": { + "passage_text": "hello world", + "passage_embedding": [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ...] + } + } + } + ] + } +} +``` + +### Example: Externally hosted large language model + +This example demonstrates how to configure an `ml_inference` search response processor to work with an externally hosted large language model (LLM) and map the model's response to the search extension object. Using the `ml_inference` processor, you can enable an LLM to summarize search results directly within the response. The summary is included in the `ext` field of the search response, providing seamless access to AI-generated insights alongside the original search results. + +**Prerequisite** + +You must configure an externally hosted LLM for this use case. For more information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). Once you register the LLM, you can use the following request to test it. This request requires providing the `prompt` and `context` fields: + +```json +POST /_plugins/_ml/models/KKne6JIBAs32TwoK-FFR/_predict +{ + "parameters": { + "prompt":"\n\nHuman: You are a professional data analysist. You will always answer question: Which month had the lowest customer acquisition cost per new customer? based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say I don't know. Context: ${parameters.context.toString()}. \n\n Assistant:", + "context":"Customer acquisition cost: January: $50, February: $45, March: $40. New customers: January: 500, February: 600, March: 750" + } +} +``` +{% include copy-curl.html %} + +The response contains the model output in the `inference_results` field: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": """ Based on the data provided: + + - Customer acquisition cost in January was $50 and new customers were 500. So cost per new customer was $50/500 = $0.10 + - Customer acquisition cost in February was $45 and new customers were 600. So cost per new customer was $45/600 = $0.075 + - Customer acquisition cost in March was $40 and new customers were 750. So cost per new customer was $40/750 = $0.053 + + Therefore, the month with the lowest customer acquisition cost per new customer was March, at $0.053.""" + } + } + ], + "status_code": 200 + } + ] +} +``` + +**Step 1: Create a pipeline** + +Create a search pipeline for the registered model. The model requires a `context` field as input. The model response summarizes the text in the `review` field and stores the summary in the `ext.ml_inference.llm_response` field of the search response: + +```json +PUT /_search/pipeline/my_pipeline_request_review_llm +{ + "response_processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "This processor is going to run llm", + "model_id": "EOF6wJIBtDGAJRTD4kNg", + "function_name": "REMOTE", + "input_map": [ + { + "context": "review" + } + ], + "output_map": [ + { + "ext.ml_inference.llm_response": "response" + } + ], + "model_config": { + "prompt": "\n\nHuman: You are a professional data analysist. You will always answer question: Which month had the lowest customer acquisition cost per new customer? based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say I don't know. Context: ${parameters.context.toString()}. \n\n Assistant:" + }, + "ignore_missing": false, + "ignore_failure": false + } + } + ] +} +``` +{% include copy-curl.html %} + +In this configuration, you've provided the following parameters: + +- The `model_id` parameter specifies the ID of the generative AI model. +- The `function_name` parameter is set to `REMOTE`, indicating that the model is hosted externally. +- The `input_map` parameter maps the review field from the document to the context field expected by the model. +- The `output_map` parameter specifies that the model's response should be stored in `ext.ml_inference.llm_response` in the search response. +- The `model_config` parameter includes a prompt that tells the model how to process the input and generate a summary. + +**Step 2: Index sample documents** + +Index some sample documents to test the pipeline: + +```json +POST /_bulk +{"index":{"_index":"review_string_index","_id":"1"}} +{"review":"Customer acquisition cost: January: $50, New customers: January: 500."} +{"index":{"_index":"review_string_index","_id":"2"}} +{"review":"Customer acquisition cost: February: $45, New customers: February: 600."} +{"index":{"_index":"review_string_index","_id":"3"}} +{"review":"Customer acquisition cost: March: $40, New customers: March: 750."} +``` +{% include copy-curl.html %} + +**Step 3: Run the pipeline** + +Run a search query using the pipeline: + +```json +GET /review_string_index/_search?search_pipeline=my_pipeline_request_review_llm +{ + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +The response includes the original documents and the generated summary in the `ext.ml_inference.llm_response` field: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "review_string_index", + "_id": "1", + "_score": 1, + "_source": { + "review": "Customer acquisition cost: January: $50, New customers: January: 500." + } + }, + { + "_index": "review_string_index", + "_id": "2", + "_score": 1, + "_source": { + "review": "Customer acquisition cost: February: $45, New customers: February: 600." + } + }, + { + "_index": "review_string_index", + "_id": "3", + "_score": 1, + "_source": { + "review": "Customer acquisition cost: March: $40, New customers: March: 750." + } + } + ] + }, + "ext": { + "ml_inference": { + "llm_response": """ Based on the context provided: + + - Customer acquisition cost in January was $50 and new customers were 500. So the cost per new customer was $50/500 = $0.10 + + - Customer acquisition cost in February was $45 and new customers were 600. So the cost per new customer was $45/600 = $0.075 + + - Customer acquisition cost in March was $40 and new customers were 750. So the cost per new customer was $40/750 = $0.053 + + Therefore, the month with the lowest customer acquisition cost per new customer was March, as it had the lowest cost per customer of $0.053.""" + } + } +} +``` + +### Example: Reranking search results using a text similarity model + +The following example shows you how to configure an `ml_inference` search response processor with a text similarity model. + +**Prerequisite** + +You must configure an externally hosted text similarity model for this use case. For more information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). Once you register the text similarity model, you can use the following request to test it. This request requires that you provide the `text` and `text_pair` fields within the `inputs` field: + +```json +POST /_plugins/_ml/models/Ialx65IBAs32TwoK1lXf/_predict +{ + "parameters": { + "inputs": + { + "text": "I like you", + "text_pair": "I hate you" + } + } +} +``` +{% include copy-curl.html %} + +The model returns similarity scores for each input document: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "label": "LABEL_0", + "score": 0.022704314440488815 + } + } + ], + "status_code": 200 + } + ] +} +``` +{% include copy-curl.html %} + +**Step 1: Index sample documents** + +Create an index and add some sample documents: + +```json +POST _bulk +{"index":{"_index":"demo-index-0","_id":"1"}} +{"diary":"I hate you"} +{"index":{"_index":"demo-index-0","_id":"2"}} +{"diary":"I love you"} +{"index":{"_index":"demo-index-0","_id":"3"}} +{"diary":"I dislike you"} +``` +{% include copy-curl.html %} + +**Step 2: Create a search pipeline** + +For this example, you'll create a search pipeline that uses a text similarity model in a `one-to-one` inference mode, processing each document in the search results individually. This setup allows the model to make one prediction request per document, providing specific relevance insights for each search hit. When using `input_map` to map the search request to query text, the JSON path must start with `$._request` or `_request`: + +```json +PUT /_search/pipeline/my_rerank_pipeline +{ + "response_processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "This processor runs ml inference during search response", + "model_id": "Ialx65IBAs32TwoK1lXf", + "model_input":"""{"parameters":{"inputs":{"text":"${input_map.text}","text_pair":"${input_map.text_pair}"}}}""", + "function_name": "REMOTE", + "input_map": [ + { + "text": "diary", + "text_pair":"$._request.query.term.diary.value" + } + ], + "output_map": [ + { + "rank_score": "$.score" + } + ], + "full_response_path": false, + "model_config": {}, + "ignore_missing": false, + "ignore_failure": false, + "one_to_one": true + }, + "rerank": { + "by_field": { + "target_field": "rank_score", + "remove_target_field": true + } + } + } + ] +} +``` +{% include copy-curl.html %} + +In this configuration, you've provided the following parameters: + +- The `model_id` parameter specifies the unique identifier of the text similarity model. +- The `function_name` parameter is set to `REMOTE`, indicating that the model is hosted externally. +- The `input_map` parameter maps the `diary` field from each document to the `text` input of the model and the search query term to the `text_pair` input. The `$._request` prefix makes the JSON path read from the search request instead of the document, so `$._request.query.term.diary.value` resolves to the `value` of the `term` query on the `diary` field. For the search request in Step 3, this value is `today`. +- The `output_map` parameter maps the model's score to a field named `rank_score` in each document. +- The `model_input` parameter formats the input for the model, ensuring that it matches the structure expected by the Predict API. +- The `one_to_one` parameter is set to `true`, ensuring that the model processes each document individually rather than batching multiple documents together. +- The `ignore_missing` parameter is set to `false`, causing the processor to fail if the mapped fields are missing from a document. +- The `ignore_failure` parameter is set to `false`, causing the entire pipeline to fail if the ML inference processor encounters an error. + +The `rerank` processor is applied after ML inference. It reorders the documents based on the `rank_score` field generated by the ML model and then removes this field from the final results. + +**Step 3: Run the pipeline** + +Now perform a search using the created pipeline: + +```json +GET /demo-index-0/_search?search_pipeline=my_rerank_pipeline +{ + "query": { + "term": { + "diary": { + "value": "today" + } + } + } +} +``` +{% include copy-curl.html %} + +The response includes the original documents and their reranked scores: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.040183373, + "hits": [ + { + "_index": "demo-index-0", + "_id": "1", + "_score": 0.040183373, + "_source": { + "diary": "I hate you" + } + }, + { + "_index": "demo-index-0", + "_id": "2", + "_score": 0.022628736, + "_source": { + "diary": "I love you" + } + }, + { + "_index": "demo-index-0", + "_id": "3", + "_score": 0.0073115323, + "_source": { + "diary": "I dislike you" + } + } + ] + }, + "profile": { + "shards": [] + } +} +``` + +## Next steps + +- See a comprehensive example of [reranking by a field using an externally hosted cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-cross-encoder/). +- For a tutorial that reranks results by a field using Cohere Rerank, see [Reranking search results by a field using Cohere Rerank]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-by-field/). diff --git a/_search-plugins/search-pipelines/neural-query-enricher.md b/_search-plugins/search-pipelines/neural-query-enricher.md index e187ea17..46b4f913 100644 --- a/_search-plugins/search-pipelines/neural-query-enricher.md +++ b/_search-plugins/search-pipelines/neural-query-enricher.md @@ -1,17 +1,19 @@ --- layout: default title: Neural query enricher -nav_order: 12 +nav_order: 50 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Neural query enricher processor +Introduced 2.11 +{: .label .label-purple } -The `neural_query_enricher` search request processor is designed to set a default machine learning (ML) model ID at the index or field level for [neural search]({{site.url}}{{site.baseurl}}/search-plugins/neural-search/) queries. To learn more about ML models, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Connecting to remote models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). +The `neural_query_enricher` search request processor is designed to set a default machine learning (ML) model ID at the index or field level for [`neural`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural/) and [`neural_sparse`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/neural-sparse/) queries. To learn more about ML models, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/) and [Connecting to remote models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). -## Request fields +## Request body fields The following table lists all available request fields. diff --git a/_search-plugins/search-pipelines/neural-sparse-query-two-phase-processor.md b/_search-plugins/search-pipelines/neural-sparse-query-two-phase-processor.md new file mode 100644 index 00000000..6ce8c246 --- /dev/null +++ b/_search-plugins/search-pipelines/neural-sparse-query-two-phase-processor.md @@ -0,0 +1,151 @@ +--- +layout: default +title: Neural sparse query two-phase +nav_order: 60 +parent: User-defined search processors +grand_parent: Search pipelines +--- + +# Neural sparse query two-phase processor +Introduced 2.15 +{: .label .label-purple } + +The `neural_sparse_two_phase_processor` search processor is designed to provide faster search pipelines for [neural sparse search]({{site.url}}{{site.baseurl}}/search-plugins/neural-sparse-search/). It accelerates the neural sparse query by dividing the original method of scoring all documents with all tokens into two steps: + +1. High-weight tokens score the documents and filter out the top documents. +2. Low-weight tokens rescore the top documents. + +## Request body fields + +The following table lists all available request fields. + +Field | Data type | Description +:--- | :--- | :--- +`enabled` | Boolean | Controls whether the two-phase processor is enabled. Default is `true`. +`two_phase_parameter` | Object | A map of key-value pairs representing the two-phase parameters and their associated values. You can specify the value of `prune_ratio`, `expansion_rate`, `max_window_size`, or any combination of these three parameters. Optional. +`two_phase_parameter.prune_type` | String | The pruning strategy for separating high-weight and low-weight tokens. Default is `max_ratio`. For valid values, see [Pruning sparse vectors]({{site.url}}{{site.baseurl}}/api-reference/ingest-apis/processors/sparse-encoding/#pruning-sparse-vectors). +`two_phase_parameter.prune_ratio` | Float | This ratio defines how high-weight and low-weight tokens are separated. The threshold is calculated by multiplying the token's maximum score by its `prune_ratio`. Valid values are in the [0,1] range for `prune_type` set to `max_ratio`. Default is `0.4`. +`two_phase_parameter.expansion_rate` | Float | The rate at which documents will be fine-tuned during the second phase. The second-phase document number equals the query size (default is 10) multiplied by its expansion rate. Valid range is greater than 1.0. Default is `5.0` +`two_phase_parameter.max_window_size` | Int | The maximum number of documents that can be processed using the two-phase processor. Valid range is greater than 50. Default is `10000`. +`tag` | String | The processor's identifier. Optional. +`description` | String | A description of the processor. Optional. + +## Example + +The following example creates a search pipeline with a `neural_sparse_two_phase_processor` search request processor. + +### Create search pipeline + +The following example request creates a search pipeline with a `neural_sparse_two_phase_processor` search request processor. The processor sets a custom model ID at the index level and provides different default model IDs for two specific index fields: + +```json +PUT /_search/pipeline/two_phase_search_pipeline +{ + "request_processors": [ + { + "neural_sparse_two_phase_processor": { + "tag": "neural-sparse", + "description": "This processor is making two-phase processor.", + "enabled": true, + "two_phase_parameter": { + "prune_ratio": custom_prune_ratio, + "expansion_rate": custom_expansion_rate, + "max_window_size": custom_max_window_size + } + } + } + ] +} +``` +{% include copy-curl.html %} + +### Set search pipeline + +After the two-phase pipeline is created, set the `index.search.default_pipeline` setting to the name of the pipeline for the index on which you want to use the two-phase pipeline: + +```json +PUT /index-name/_settings +{ + "index.search.default_pipeline" : "two_phase_search_pipeline" +} +``` +{% include copy-curl.html %} + +## Limitation + +The `neural_sparse_two_phase_processor` has the following limitations. + +### Version support + +The `neural_sparse_two_phase_processor` can only be used with OpenSearch 2.15 or later. + +### Compound query support + +Only the Boolean [compound query]({{site.url}}{{site.baseurl}}/query-dsl/compound/index/) is supported. + +Neural sparse queries and Boolean queries with a boost parameter (not boosting queries) are also supported. + +## Examples + +The following examples show neural sparse queries with the supported query types. + +### Single neural sparse query + +``` +GET /my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world" + "model_id": <model-id> + } + } + } +} +``` +{% include copy-curl.html %} + +### Neural sparse query nested in a Boolean query + +``` +GET /my-nlp-index/_search +{ + "query": { + "bool": { + "should": [ + { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": <model-id> + }, + "boost": 2.0 + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +## P99 latency metrics +Using an OpenSearch cluster set up on three m5.4xlarge Amazon Elastic Compute Cloud (Amazon EC2) instances, OpenSearch conducts neural sparse query P99 latency tests on indexes corresponding to more than 10 datasets. + +### Doc-only mode latency metric + +In doc-only mode, the two-phase processor can significantly decrease query latency, as shown by the following latency metrics: + +- Average latency without the two-phase processor: 53.56 ms +- Average latency with the two-phase processor: 38.61 ms + +This results in an overall latency reduction of approximately 27.92%. Most indexes show a significant latency reduction when using the two-phase processor, with reductions ranging from 5.14 to 84.6%. The specific latency optimization values depend on the data distribution within the indexes. + +### Bi-encoder mode latency metric + +In bi-encoder mode, the two-phase processor can significantly decrease query latency, as shown by the following latency metrics: +- Average latency without the two-phase processor: 300.79 ms +- Average latency with the two-phase processor: 121.64 ms + +This results in an overall latency reduction of approximately 59.56%. Most indexes show a significant latency reduction when using the two-phase processor, with reductions ranging from 1.56 to 82.84%. The specific latency optimization values depend on the data distribution within the indexes. diff --git a/_search-plugins/search-pipelines/normalization-processor.md b/_search-plugins/search-pipelines/normalization-processor.md index a8fad2e4..12971c6b 100644 --- a/_search-plugins/search-pipelines/normalization-processor.md +++ b/_search-plugins/search-pipelines/normalization-processor.md @@ -1,19 +1,228 @@ --- layout: default title: Normalization -nav_order: 15 +nav_order: 70 has_children: false -parent: Search processors +has_math: true +parent: User-defined search processors grand_parent: Search pipelines --- # Normalization processor +Introduced 2.10 +{: .label .label-purple } The `normalization-processor` is a search phase results processor that runs between the query and fetch phases of search execution. It intercepts the query phase results and then normalizes and combines the document scores from different query clauses before passing the documents to the fetch phase. +You can apply the same normalization and combination techniques without a search pipeline by running the `hybrid` query in [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/), which configures them in the query itself. + ## Score normalization and combination -Many applications require both keyword matching and semantic understanding. For example, BM25 accurately provides relevant search results for a query containing keywords, and neural networks perform well when a query requires natural language understanding. Thus, you might want to combine BM25 search results with the results of a k-NN or neural search. However, BM25 and k-NN search use different scales to calculate relevance scores for the matching documents. Before combining the scores from multiple queries, it is beneficial to normalize them so that they are on the same scale, as shown by experimental data. For further reading about score normalization and combination, including benchmarks and various techniques, see [this semantic search blog post](https://opensearch.org/blog/semantic-science-benchmarks/). +Many applications require both keyword matching and semantic understanding. For example, BM25 accurately provides relevant search results for a query containing keywords, and neural networks perform well when a query requires natural language understanding. Thus, you might want to combine BM25 search results with vector search results. However, BM25 and vector search use different scales to calculate relevance scores for the matching documents. Before combining the scores from multiple queries, it is beneficial to normalize them so that they are on the same scale, as shown by experimental data. For further reading about score normalization and combination, including benchmarks and various techniques, see [this semantic search blog post](https://opensearch.org/blog/semantic-science-benchmarks/). + +## Normalization techniques + +OpenSearch normalizes each query clause independently. For a given clause, it calculates the statistics that the technique requires from that clause's own results only, and then rescales every score in the clause. Documents that the clause did not return contribute nothing to its statistics. + +Because the statistics are derived from the returned results rather than from the whole index, the normalized scores depend on how many results each clause returns. For more information, see [Search tuning recommendations](#search-tuning-recommendations). + +### Min-max normalization + +Min-max normalization rescales the scores of a query clause to the [0.0, 1.0] range by subtracting the clause's minimum score and dividing by the clause's score range: + +$$\text{n_score} = \frac {\text{score} - \text{min_score}} {\text{max_score} - \text{min_score}}$$ + +The highest-scoring document in the clause receives a score of `1.0`. OpenSearch replaces a normalized score of exactly `0.0` with `0.001` because a score of `0.0` has the special meaning of `match_none`, so the lowest-scoring document in the clause receives `0.001`. If every document in a clause has the same score, including a clause that returns only one document, then the clause's minimum and maximum scores are equal and every document in the clause receives `1.0`. + +Because only an exact `0.0` is replaced, this substitution can reorder the low-scoring documents in a clause. Any document whose normalized score is less than `0.001` ranks below the lowest-scoring document, which receives exactly `0.001`. For example, a clause that returns the raw scores `10000`, `9`, and `8` normalizes them to `1.0`, `0.00010008`, and `0.001`, so the document scoring `8` ranks above the document scoring `9`. A document is affected when its score exceeds the clause minimum by less than 0.1% of the clause's score range, which occurs when one score in the clause is roughly 1,000 times larger than the others. + +To normalize against fixed thresholds instead of the minimum and maximum scores of the returned results, set the `lower_bounds` and `upper_bounds` parameters. For more information, see [Request body fields](#request-body-fields). + +### L2 normalization + +L2 normalization divides each score in a query clause by the Euclidean norm of all scores in that clause: + +$$\text{n_score}_i = \frac {\text{score}_i} {\sqrt{\text{score}_1^2 + \text{score}_2^2 + \dots + \text{score}_n^2}}$$ + +The normalized scores preserve the ratios of the original scores, so a document that scored twice as high as another document in the same clause still scores twice as high after normalization. Because every score is divided by the same norm, and no single score can exceed the norm, the normalized scores fall in the [0.0, 1.0] range. Unlike min-max normalization, L2 normalization does not assign `1.0` to the highest-scoring document. Each additional result that a clause returns increases the norm and therefore reduces the normalized score of every other document in the clause. Only when a clause returns a single document does the norm equal that document's score, and the document receives `1.0`. + +### Z-score normalization + +Z-score normalization subtracts the mean of the query clause's scores from each score and divides the result by the sample standard deviation of those scores: + +$$\text{n_score} = \frac {\text{score} - \text{mean}} {\text{sd}}$$ + +A document that scores below the mean of its clause produces a negative z-score. Because a negative value is not a valid relevance score, OpenSearch replaces every normalized score less than or equal to `0.0` with `0.001`. All documents that score below the mean of a query clause therefore receive the same normalized score, and their relative order within that clause is lost. Documents that score above the mean are not confined to a fixed range and can receive normalized scores greater than `1.0`. + +A document whose score is exactly equal to the mean of its clause is a special case: it receives the highest raw score in the clause rather than a z-score. If every document in a clause has the same score, including a clause that returns only one document, then every document matches the mean, so the clause's scores are not rescaled at all. + +The `z_score` technique supports only the `arithmetic_mean` combination technique. + +### Choosing a normalization technique + +Use the following table to compare the three techniques. + +| | `min_max` | `l2` | `z_score` | +| :--- | :--- | :--- | :--- | +| Output range | [0.0, 1.0], with `0.0` replaced by `0.001` | [0.0, 1.0] | Not a fixed range, with all values less than or equal to `0.0` replaced by `0.001` | +| Score of the highest-scoring document in a clause | Always `1.0` | Less than `1.0`, unless the clause returns a single document | Varies, and can exceed `1.0` | +| Score ratios within a clause | Not preserved | Preserved | Not preserved | +| Statistics used | Lowest and highest scores | All scores | All scores | +| Effect of a single outlier on the other documents in a clause | Compresses their scores but keeps them distinct | Compresses their scores but keeps them distinct | Pushes them below the clause mean, so they all collapse to `0.001` | +| Ordering of documents within a clause | Preserved, except that documents with normalized scores below `0.001` rank below the lowest-scoring document | Preserved | Lost for every document that scores below the clause mean | +| Supported combination techniques | All | All | `arithmetic_mean` | + +The following guidance applies to each technique: + +- Use `min_max`, the default, when you want normalized scores on a predictable scale that you can reason about directly, or when you want to normalize against fixed thresholds through the `lower_bounds` and `upper_bounds` parameters. +- Use `l2` when the ratios between the scores within a query clause carry information that the final ranking should reflect. Note that `l2` does not spread out the remaining documents more than `min_max` does: because a clause's L2 norm is always greater than or equal to its score range, `l2` separates any two documents by less than or equal to the amount that `min_max` separates them. +- Use `z_score` when the query clauses produce score distributions that differ mainly in spread. Avoid it when a clause returns few results or contains an outlier, because every document that scores below the clause mean collapses to `0.001`. A single high outlier can pull the mean above all remaining scores and erase the ordering of every other document in the clause. + +### Example: Comparing normalization techniques + +The following example applies all three techniques to the same data so that you can compare their output. It uses two-dimensional vectors specified directly in each document so that you can verify the arithmetic manually, and a single shard so that the scores are reproducible. + +The example uses the same index and query as [Reciprocal rank fusion]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/rrf/), so you can also compare these results to those of rank-based combination. +{: .note} + +Create an index with a text field for keyword matching and a vector field for semantic matching: + +```json +PUT /products +{ + "settings": { + "index.knn": true, + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "item_name": { + "type": "text" + }, + "item_vector": { + "type": "knn_vector", + "dimension": 2, + "space_type": "l2", + "method": { + "name": "hnsw", + "engine": "lucene" + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index five products: + +```json +POST /_bulk?refresh=true +{ "index": { "_index": "products", "_id": "1" } } +{ "item_name": "kids running shoes", "item_vector": [0.2, 0.8] } +{ "index": { "_index": "products", "_id": "2" } } +{ "item_name": "mens lightweight running shoes for road racing", "item_vector": [0.9, 0.1] } +{ "index": { "_index": "products", "_id": "3" } } +{ "item_name": "trail runners", "item_vector": [0.8, 0.2] } +{ "index": { "_index": "products", "_id": "4" } } +{ "item_name": "athletic socks", "item_vector": [0.5, 0.5] } +{ "index": { "_index": "products", "_id": "5" } } +{ "item_name": "winter parka", "item_vector": [0.0, 1.0] } +``` +{% include copy-curl.html %} + +Run separately, the two query clauses produce scores on different scales. The `match` clause on `running shoes` returns two documents, and a `knn` clause on `[0.9, 0.1]` with `k` set to `3` returns three documents: + +| Document ID | `item_name` | Keyword score | Vector score | +| :--- | :--- | :--- | :--- | +| `1` | `kids running shoes` | 0.8167638 | -- | +| `2` | `mens lightweight running shoes for road racing` | 0.5356597 | 1.0 | +| `3` | `trail runners` | -- | 0.98039216 | +| `4` | `athletic socks` | -- | 0.7575758 | + +Create one search pipeline for each normalization technique, replacing `min_max` with `l2` and `z_score` to create the other two: + +```json +PUT /_search/pipeline/min-max-pipeline +{ + "description": "Normalize with min_max and combine with arithmetic_mean", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": { + "technique": "min_max" + }, + "combination": { + "technique": "arithmetic_mean" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +Combine both query clauses in a [`hybrid` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/hybrid/) and apply one of the pipelines: + +```json +GET /products/_search?search_pipeline=min-max-pipeline +{ + "_source": { + "excludes": ["item_vector"] + }, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "item_name": "running shoes" + } + }, + { + "knn": { + "item_vector": { + "vector": [0.9, 0.1], + "k": 3 + } + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +Because the `weights` parameter is omitted, `arithmetic_mean` weights both clauses equally. A document that one clause did not return contributes `0` to the numerator but still counts in the denominator, so a document matching only one of the two clauses has its normalized score halved. + +With `min_max`, document `1` normalizes to `1.0` because it is the highest-scoring document of the keyword clause, and document `2` normalizes to `0.001` because it is the lowest-scoring document of that clause. Document `2` still ranks first overall, but only narrowly: + +| Document ID | Keyword normalized | Vector normalized | `_score` | +| :--- | :--- | :--- | :--- | +| `2` | 0.001 | 1.0 | 0.5005 | +| `1` | 1.0 | -- | 0.5 | +| `3` | -- | 0.9191176 | 0.4595588 | +| `4` | -- | 0.001 | 0.0005 | + +With `l2`, each clause is divided by its own norm: 0.97674686 for the keyword clause and 1.5921966 for the vector clause. No score is forced to an endpoint, so document `2` retains a larger share of its keyword contribution and its lead over document `1` widens: + +| Document ID | Keyword normalized | Vector normalized | `_score` | +| :--- | :--- | :--- | :--- | +| `2` | 0.54841197 | 0.62806314 | 0.5882375 | +| `1` | 0.8362083 | -- | 0.41810414 | +| `3` | -- | 0.61574817 | 0.30787408 | +| `4` | -- | 0.47580546 | 0.23790273 | + +With `z_score`, documents `2` and `4` fall at or below the mean of their respective clauses, so both receive `0.001` in that clause. Document `2` loses most of its keyword contribution as a result, and document `1` ranks first: + +| Document ID | Keyword normalized | Vector normalized | `_score` | +| :--- | :--- | :--- | :--- | +| `1` | 0.70710695 | -- | 0.35355347 | +| `2` | 0.001 | 0.6486226 | 0.32481128 | +| `3` | -- | 0.5030134 | 0.2515067 | +| `4` | -- | 0.001 | 0.0005 | + +The three techniques produce three different rankings from identical input, and `z_score` promotes a different document to the top. Evaluate the techniques against your own data and judgment lists rather than choosing one from these results. For more information, see [Optimizing hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/optimize-hybrid-search/). ## Query then fetch @@ -23,28 +232,37 @@ OpenSearch supports two search types: `query_then_fetch` and `dfs_query_then_fet When you send a search request to a node, the node becomes a _coordinating node_. During the first phase of search, the _query phase_, the coordinating node routes the search request to all shards in the index, including primary and replica shards. Each shard then runs the search query locally and returns metadata about the matching documents, which includes their document IDs and relevance scores. The `normalization-processor` then normalizes and combines scores from different query clauses. The coordinating node merges and sorts the local lists of results, compiling a global list of top documents that match the query. After that, search execution enters a _fetch phase_, in which the coordinating node requests the documents in the global list from the shards where they reside. Each shard returns the documents' `_source` to the coordinating node. Finally, the coordinating node sends a search response containing the results back to you. -## Request fields +## Request body fields The following table lists all available request fields. Field | Data type | Description :--- | :--- | :--- -`normalization.technique` | String | The technique for normalizing scores. Valid values are [`min_max`](https://en.wikipedia.org/wiki/Feature_scaling#Rescaling_(min-max_normalization)) and [`l2`](https://en.wikipedia.org/wiki/Cosine_similarity#L2-normalized_Euclidean_distance). Optional. Default is `min_max`. -`combination.technique` | String | The technique for combining scores. Valid values are [`arithmetic_mean`](https://en.wikipedia.org/wiki/Arithmetic_mean), [`geometric_mean`](https://en.wikipedia.org/wiki/Geometric_mean), and [`harmonic_mean`](https://en.wikipedia.org/wiki/Harmonic_mean). Optional. Default is `arithmetic_mean`. -`combination.parameters.weights` | Array of floating-point values | Specifies the weights to use for each query. Valid values are in the [0.0, 1.0] range and signify decimal percentages. The closer the weight is to 1.0, the more weight is given to a query. The number of values in the `weights` array must equal the number of queries. The sum of the values in the array must equal 1.0. Optional. If not provided, all queries are given equal weight. +`normalization.technique` | String | The technique for normalizing scores. Valid values are [`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), and [`z_score`](https://en.wikipedia.org/wiki/Standard_score). Optional. Default is `min_max`. + `normalization.parameters.lower_bounds` | Array of objects | Defines the lower bound values (the minimum threshold scores) for each query. The array must contain the same number of objects as the number of queries. Optional. Applies only when the normalization technique is [`min_max`](https://en.wikipedia.org/wiki/Feature_scaling#Rescaling_(min-max_normalization)). If not provided, OpenSearch does not apply a lower bound to any subquery and uses the actual minimum score from the retrieved results for normalization. +`normalization.parameters.lower_bounds.mode` | String | Specifies how the lower bound is applied to a query. Valid values are: <br> - `apply`: Uses `min_score` for normalization without modifying the original scores. Formula: `min_max_score = if (score < lowerBoundScore) then (score - minScore) / (maxScore - minScore) else (score - lowerBoundScore) / (maxScore - lowerBoundScore)`. <br> - `clip`: Replaces scores below the lower bound with `min_score`. Formula: `min_max_score = if (score < lowerBoundScore) then 0.0 else (score - lowerBoundScore) / (maxScore - lowerBoundScore)`. <br> - `ignore`: Does not apply a lower bound to this query and uses the standard `min_max` formula instead. <br> Optional. Default is `apply`. +`normalization.parameters.lower_bounds.min_score` | Float | The lower bound threshold. Valid values are in the [-10000.0, 10000.0] range. If `mode` is set to `ignore`, then this value has no effect. Optional. Default is `0.0`. +`normalization.parameters.upper_bounds` | Array of objects | Defines the upper bound values (the maximum threshold scores) for each query. The array must contain the same number of objects as the number of queries. Optional. Applies only when the `normalization.technique` is set to `min_max`. If not provided, OpenSearch does not apply an upper bound to any subquery and uses the actual maximum score from the retrieved results for normalization. +`normalization.parameters.upper_bounds.mode` | String | Specifies how the upper bound is applied to a query. Valid values are: <br> - `apply`: Uses `max_score` for normalization without modifying the original scores. Formula: `min_max_score = if (score > upperBoundScore) then (score - minScore) / (maxScore - minScore) else (score - minScore) / (upperBoundScore - minScore)`. <br> - `clip`: Replaces scores above the upper bound with `max_score`. Formula: `min_max_score = if (score > upperBoundScore) then 1.0 else (score - minScore) / (upperBoundScore - minScore)`. <br> - `ignore`: Does not apply an upper bound to this query and uses the standard `min_max` formula instead. <br> Optional. Default is `apply`. +`normalization.parameters.upper_bounds.max_score` | Float | The upper bound threshold. Valid values are in the [-10000.0, 10000.0] range. If `mode` is set to `ignore`, then this value has no effect. Optional. Default is `1.0`. +`combination.technique` | String | The technique for combining scores. Valid values are [`arithmetic_mean`](https://en.wikipedia.org/wiki/Arithmetic_mean), [`geometric_mean`](https://en.wikipedia.org/wiki/Geometric_mean), and [`harmonic_mean`](https://en.wikipedia.org/wiki/Harmonic_mean). Optional. Default is `arithmetic_mean`. `z_score` supports only `arithmetic_mean`. +`combination.parameters.weights` | Array of floating-point values | Specifies the weights to use for each query. Valid values are in the [0.0, 1.0] range and signify decimal percentages. The closer the weight is to 1.0, the more weight is given to a query. The number of values in the `weights` array must equal the number of queries. The sum of the values in the array must equal 1.0. Optional. If not provided, all queries are given equal weight. To override these weights for a single request, specify the `weights` parameter in the [`hybrid` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/hybrid/#weighting-subqueries). `tag` | String | The processor's identifier. Optional. `description` | String | A description of the processor. Optional. `ignore_failure` | Boolean | For this processor, this value is ignored. If the processor fails, the pipeline always fails and returns an error. +The `lower_bounds` and `upper_bounds` parameters are supported only in a search pipeline. A `hybrid` query running in [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/) does not support them. To use score bounds, configure the normalization in a search pipeline, as described on this page. +{: .note} + ## Example The following example demonstrates using a search pipeline with a `normalization-processor`. -For a comprehensive example, follow the [Neural search tutorial]({{site.url}}{{site.baseurl}}/ml-commons-plugin/semantic-search#tutorial). +For a comprehensive example, follow the [Getting started with semantic and hybrid search]({{site.url}}{{site.baseurl}}/ml-commons-plugin/semantic-search#tutorial). ### Creating a search pipeline -The following request creates a search pipeline containing a `normalization-processor` that uses the `min_max` normalization technique and the `arithmetic_mean` combination technique: +The following request creates a search pipeline containing a `normalization-processor` that uses the `min_max` normalization technique and the `arithmetic_mean` combination technique. The combination technique assigns a weight of 30% to the first query and 70% to the second query: ```json PUT /_search/pipeline/nlp-search-pipeline @@ -72,6 +290,48 @@ PUT /_search/pipeline/nlp-search-pipeline ``` {% include copy-curl.html %} +The following example demonstrates using the `lower_bounds` and `upper_bounds` parameters with the `min_max` normalization technique. It omits the `weights` parameter in the combination technique, causing the queries to be weighted equally by default. In this example, the `lower_bounds` parameter is used to set different lower bounds for each query in a hybrid search, and the `upper_bounds` parameter is used to set different upper bounds. For the first query, a lower bound of 0.5 is applied and an upper bound of 0.8 is clipped. For the second query, both the lower bound and the upper bound are ignored. This allows for fine-tuning of the normalization process for each individual query in a hybrid search: + +```json +PUT /_search/pipeline/nlp-search-pipeline +{ + "description": "Post processor for hybrid search", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": { + "technique": "min_max", + "parameters": { + "lower_bounds": [ + { + "mode": "apply", + "min_score": 0.5 + }, + { + "mode": "ignore" + } + ], + "upper_bounds": [ + { + "mode": "clip", + "max_score": 0.8 + }, + { + "mode": "ignore" + } + ] + } + }, + "combination": { + "technique": "arithmetic_mean" + } + } + } + ] +} +``` +{% include copy-curl.html %} + ### Using a search pipeline Provide the query clauses that you want to combine in a `hybrid` query and apply the search pipeline created in the previous section so that the scores are combined using the chosen techniques: @@ -110,7 +370,7 @@ GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline ``` {% include copy-curl.html %} -For more information about setting up hybrid search, see [Using hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/hybrid-search/#using-hybrid-search). +For more information about setting up hybrid search, see [Hybrid search]({{site.url}}{{site.baseurl}}/search-plugins/hybrid-search/). ## Search tuning recommendations diff --git a/_search-plugins/search-pipelines/oversample-processor.md b/_search-plugins/search-pipelines/oversample-processor.md index 698d9572..9c82e325 100644 --- a/_search-plugins/search-pipelines/oversample-processor.md +++ b/_search-plugins/search-pipelines/oversample-processor.md @@ -1,17 +1,19 @@ --- layout: default title: Oversample -nav_order: 17 +nav_order: 80 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Oversample processor +Introduced 2.12 +{: .label .label-purple } The `oversample` request processor multiplies the `size` parameter of the search request by a specified `sample_factor` (>= 1.0), saving the original value in the `original_size` pipeline variable. The `oversample` processor is designed to work with the [`truncate_hits` response processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/truncate-hits-processor/) but may be used on its own. -## Request fields +## Request body fields The following table lists all request fields. diff --git a/_search-plugins/search-pipelines/personalize-search-ranking.md b/_search-plugins/search-pipelines/personalize-search-ranking.md index c7a7dd8d..31c2dd89 100644 --- a/_search-plugins/search-pipelines/personalize-search-ranking.md +++ b/_search-plugins/search-pipelines/personalize-search-ranking.md @@ -1,27 +1,29 @@ --- layout: default title: Personalize search ranking -nav_order: 18 +nav_order: 85 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Personalize search ranking processor +Introduced 2.9 +{: .label .label-purple } The `personalize_search_ranking` search response processor intercepts a search response and uses [Amazon Personalize](https://aws.amazon.com/personalize/) to rerank search results according to their Amazon Personalize ranking. This ranking is based on the user's past behavior and metadata about the search items and the user. To use the `personalize_search_ranking` processor, you must first install the Amazon Personalize Search Ranking (`opensearch-search-processor`) plugin. For detailed instructions, see [Installing and configuring the Amazon Personalize Search Ranking plugin](https://docs.aws.amazon.com/personalize/latest/dg/opensearch-install.html). {: .important} -## Request fields +## Request body fields The following table lists all available request fields. Field | Data type | Description :--- | :--- | :--- `campaign_arn` | String | The Amazon Resource Name (ARN) of the Amazon Personalize campaign used to personalize results. Required. -`recipe` | String | The name of the Amazon Personalize recipe to use. Currently, the only supported value for this field is `aws-personalized-ranking`. Required. +`recipe` | String | The name of the Amazon Personalize recipe to use. The only supported value is `aws-personalized-ranking`. Required. `weight` | Float | The weight to use with rankings provided by OpenSearch and Amazon Personalize. Valid values are in the [0.0, 1.0] range. The closer the weight is to 1.0, the more weight is given to Amazon Personalize as opposed to OpenSearch when calculating the ranking. If you specify 0.0, OpenSearch rankings are used. If you specify 1.0, Amazon Personalize rankings are used. Required. `item_id_field` | String | If the `_id` field for an indexed document in OpenSearch doesn't correspond with your Amazon Personalize `itemId`, specify the name of the field that does. By default, the plugin assumes the `_id` data matches the `itemId` in your Amazon Personalize data. `iam_role_arn` | String | If you use multiple roles to restrict permissions for different groups of users in your organization, specify the ARN of the role that has permission to access Amazon Personalize. If you use only the AWS credentials in your OpenSearch keystore, you can omit this field. Optional. diff --git a/_search-plugins/search-pipelines/rag-processor.md b/_search-plugins/search-pipelines/rag-processor.md index 7137134a..1e55b455 100644 --- a/_search-plugins/search-pipelines/rag-processor.md +++ b/_search-plugins/search-pipelines/rag-processor.md @@ -1,20 +1,22 @@ --- layout: default title: Retrieval-augmented generation -nav_order: 18 +nav_order: 115 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Retrieval-augmented generation processor +Introduced 2.12 +{: .label .label-purple } The `retrieval_augmented_generation` processor is a search results processor that you can use in [conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/) for retrieval-augmented generation (RAG). The processor intercepts query results, retrieves previous messages from the conversation from the conversational memory, and sends a prompt to a large language model (LLM). After the processor receives a response from the LLM, it saves the response in conversational memory and returns both the original OpenSearch query results and the LLM response. -As of OpenSearch 2.12, the `retrieval_augmented_generation` processor supports only OpenAI and Amazon Bedrock models. +The `retrieval_augmented_generation` processor supports OpenAI, Amazon Bedrock, and Cohere models. To use an Amazon Bedrock or Cohere model, prefix the `llm_model` value with `bedrock/`, `bedrock-converse/`, or `cohere/`. A value without a prefix is treated as an OpenAI model. To use another model, set the `llm_response_field` parameter. For more information, see [Step 6: Use the pipeline for RAG]({{site.url}}{{site.baseurl}}/vector-search/ai-search/conversational-search/#step-6-use-the-pipeline-for-rag). {: .note} -## Request fields +## Request body fields The following table lists all available request fields. @@ -85,7 +87,7 @@ GET /my_rag_test_data/_search?search_pipeline=rag_pipeline }, "ext": { "generative_qa_parameters": { - "llm_model": "gpt-3.5-turbo", + "llm_model": "gpt-4o-mini", "llm_question": "Was Abraham Lincoln a good politician", "memory_id": "iXC4bI0BfUsSoeNTjS30", "context_size": 5, @@ -97,4 +99,6 @@ GET /my_rag_test_data/_search?search_pipeline=rag_pipeline ``` {% include copy-curl.html %} -For more information about setting up conversational search, see [Using conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/#using-conversational-search). +For more information about setting up conversational search, see [Conversational search with RAG]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/). + +For tutorials that configure RAG using specific models, see [RAG tutorials]({{site.url}}{{site.baseurl}}/tutorials/gen-ai/rag/). diff --git a/_search-plugins/search-pipelines/rename-field-processor.md b/_search-plugins/search-pipelines/rename-field-processor.md index cb01125d..dbba700b 100644 --- a/_search-plugins/search-pipelines/rename-field-processor.md +++ b/_search-plugins/search-pipelines/rename-field-processor.md @@ -1,17 +1,19 @@ --- layout: default title: Rename field -nav_order: 20 +nav_order: 100 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Rename field processor +Introduced 2.8 +{: .label .label-purple } The `rename_field` search response processor intercepts a search response and renames the specified field. This is useful when your index and your application use different names for the same field. For example, if you rename a field in your index, the `rename_field` processor can change the new name to the old one before sending the response to your application. -## Request fields +## Request body fields The following table lists all available request fields. diff --git a/_search-plugins/search-pipelines/rerank-processor.md b/_search-plugins/search-pipelines/rerank-processor.md index 73bacd35..d545d444 100644 --- a/_search-plugins/search-pipelines/rerank-processor.md +++ b/_search-plugins/search-pipelines/rerank-processor.md @@ -1,41 +1,59 @@ --- layout: default title: Rerank -nav_order: 25 +nav_order: 110 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Rerank processor +Introduced 2.12 +{: .label .label-purple } -The `rerank` search request processor intercepts search results and passes them to a cross-encoder model to be reranked. The model reranks the results, taking into account the scoring context. Then the processor orders documents in the search results based on their new scores. +The `rerank` search response processor intercepts and reranks search results. The processor orders documents in the search results based on their new scores. -## Request fields +OpenSearch supports the following rerank types. + +Type | Description | Earliest available version +:--- | :--- | :--- +[`ml_opensearch`](#the-ml_opensearch-rerank-type) | Applies an OpenSearch-provided cross-encoder model. | 2.12 +[`by_field`](#the-by_field-rerank-type) | Applies reranking based on a user-provided field. | 2.18 + +## Request body fields The following table lists all available request fields. -Field | Data type | Description -:--- | :--- | :--- -`<reranker_type>` | Object | The reranker type provides the rerank processor with static information needed across all reranking calls. Required. -`context` | Object | Provides the rerank processor with information necessary for generating reranking context at query time. -`tag` | String | The processor's identifier. Optional. -`description` | String | A description of the processor. Optional. -`ignore_failure` | Boolean | If `true`, OpenSearch [ignores any failure]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/#ignoring-processor-failures) of this processor and continues to run the remaining processors in the search pipeline. Optional. Default is `false`. +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`rerank_type` | Object | Required | The rerank type for document reranking. Valid values are `ml-opensearch` and `by_field`. +`context` | Object | Required for the `ml_opensearch` rerank type. Optional and does not affect the results for the `by_field` rerank type. | Provides the `rerank` processor with information necessary for reranking at query time. +`tag` | String | Optional | The processor's identifier. +`description` | String | Optional | A description of the processor. +`ignore_failure` | Boolean | Optional | If `true`, OpenSearch [ignores any failure]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/#ignoring-processor-failures) of this processor and continues to run the remaining processors in the search pipeline. Default is `false`. -### The `ml_opensearch` reranker type +<!-- vale off --> +## The ml_opensearch rerank type +<!-- vale on --> +Introduced 2.12 +{: .label .label-purple } -The `ml_opensearch` reranker type is designed to work with the cross-encoder model provided by OpenSearch. For this reranker type, specify the following fields. +To rerank results using a cross-encoder model, specify the `ml_opensearch` rerank type. + +### Prerequisite + +Before using the `ml_opensearch` rerank type, you must configure a cross-encoder model. For information about using an OpenSearch-provided model, see [Cross-encoder models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#cross-encoder-models). For information about using a custom model, see [Custom local models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). + +The `ml_opensearch` rerank type supports the following fields. All fields are required. Field | Data type | Description :--- | :--- | :--- -`ml_opensearch` | Object | Provides the rerank processor with model information. Required. -`ml_opensearch.model_id` | String | The model ID for the cross-encoder model. Required. For more information, see [Using ML models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). -`context.document_fields` | Array | An array of document fields that specifies the fields from which to retrieve context for the cross-encoder model. Required. +`ml_opensearch.model_id` | String | The model ID of the cross-encoder model for reranking. For more information, see [Using ML models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). +`context.document_fields` | Array | An array of document fields that specifies the fields from which to retrieve context for the cross-encoder model. -## Example +### Example -The following example demonstrates using a search pipeline with a `rerank` processor. +The following example demonstrates using a search pipeline with a `rerank` processor implemented using the `ml_opensearch` rerank type. For a complete example, see [Reranking using a cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-cross-encoder/). ### Creating a search pipeline @@ -106,11 +124,78 @@ POST /_search?search_pipeline=rerank_pipeline ``` {% include copy-curl.html %} -The `query_context` object contains the following fields. +The `query_context` object contains the following fields. You must provide either `query_text` or `query_text_path` but cannot provide both simultaneously. -Field name | Description -:--- | :--- -`query_text` | The natural language text of the question that you want to use to rerank the search results. Either `query_text` or `query_text_path` (not both) is required. -`query_text_path` | The full JSON path to the text of the question that you want to use to rerank the search results. Either `query_text` or `query_text_path` (not both) is required. The maximum number of characters in the path is `1000`. +Field name | Required/Optional | Description +:--- | :--- | :--- +`query_text` | Exactly one of `query_text` or `query_text_path` is required. | The natural language text of the question that you want to use to rerank the search results. +`query_text_path` | Exactly one of `query_text` or `query_text_path` is required. | The full JSON path to the text of the question that you want to use to rerank the search results. The maximum number of characters allowed in the path is `1000`. -For more information about setting up reranking, see [Reranking search results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/reranking-search-results/). \ No newline at end of file + +<!-- vale off --> +## The by_field rerank type +<!-- vale on --> +Introduced 2.18 +{: .label .label-purple } + +To rerank results by a document field, specify the `by_field` rerank type. + +The `by_field` object supports the following fields. + +Field | Data type | Required/Optional | Description +:--- | :--- | :--- | :--- +`target_field` | String | Required | Specifies the field name or a dot path to the field containing the score to use for reranking. +`remove_target_field` | Boolean | Optional | If `true`, the response does not include the `target_field` used to perform reranking. Default is `false`. +`keep_previous_score` | Boolean | Optional | If `true`, the response includes a field containing the score calculated before reranking. The field name is specified by `previous_score_field`. This can be useful when debugging. Default is `false`. +`previous_score_field` | String | Optional | The field name used to store the score calculated before reranking when `keep_previous_score` is `true`. Default is `previous_score`. Only used when `keep_previous_score` is `true`. + +If your index already defines a `previous_score` document field, set `previous_score_field` to a different name (for example, `original_query_score`) to avoid overwriting the existing field value in search results. +{: .note} + + +### Example + +The following example demonstrates using a search pipeline with a `rerank` processor implemented using the `by_field` rerank type. For a complete example, see [Reranking by a document field]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field/). + +### Creating a search pipeline + +The following request creates a search pipeline with a `by_field` rerank type response processor that ranks the documents by the `reviews.stars` field and specifies to return the original document score: + +```json +PUT /_search/pipeline/rerank_byfield_pipeline +{ + "response_processors": [ + { + "rerank": { + "by_field": { + "target_field": "reviews.stars", + "keep_previous_score" : true + } + } + } + ] +} +``` +{% include copy-curl.html %} + +### Using the search pipeline + +To apply the search pipeline to a query, provide the search pipeline name in the query parameter: + +```json +POST /book-index/_search?search_pipeline=rerank_byfield_pipeline +{ + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +## Next steps + +- Learn more about [reranking search results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/reranking-search-results/). +- See a complete example of [reranking using a cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-cross-encoder/). +- See a complete example of [reranking by a document field]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field/). +- See a comprehensive example of [reranking by a field using an externally hosted cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-cross-encoder/). +- For tutorials that rerank results using models hosted on Amazon Bedrock, Amazon SageMaker, and Cohere, see [Reranking search results tutorials]({{site.url}}{{site.baseurl}}/tutorials/reranking/). \ No newline at end of file diff --git a/_search-plugins/search-pipelines/retrieving-search-pipeline.md b/_search-plugins/search-pipelines/retrieving-search-pipeline.md index 41b213e5..45d343d9 100644 --- a/_search-plugins/search-pipelines/retrieving-search-pipeline.md +++ b/_search-plugins/search-pipelines/retrieving-search-pipeline.md @@ -4,7 +4,6 @@ title: Retrieving search pipelines nav_order: 25 has_children: false parent: Search pipelines -grand_parent: Search --- # Retrieving search pipelines diff --git a/_search-plugins/search-pipelines/score-ranker-processor.md b/_search-plugins/search-pipelines/score-ranker-processor.md new file mode 100644 index 00000000..79d4f1e5 --- /dev/null +++ b/_search-plugins/search-pipelines/score-ranker-processor.md @@ -0,0 +1,108 @@ +--- +layout: default +title: Score ranker +has_children: false +parent: User-defined search processors +grand_parent: Search pipelines +nav_order: 117 +--- + +# Score ranker processor +Introduced 2.19 +{: .label .label-purple } + +The `score-ranker-processor` is a rank-based search phase results processor that runs between the query and fetch phases of search execution. It intercepts the query phase results and then uses the reciprocal rank fusion (RRF) algorithm to combine the query clauses of a [`hybrid` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/hybrid/) into a final ranked list of search results. RRF scores each document based on the reciprocal of its rank in each query clause's results and then adds these scores together, so the relevance scores of the individual query clauses never need to be on comparable scales. For more information, see [Reciprocal rank fusion]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/rrf/). + +You can also combine query clauses using RRF without a search pipeline by running the `hybrid` query in [fusion mode]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/fusion-mode/) and setting both the normalization and combination techniques to `rrf`. + +## Request body fields + +The following table lists all available request fields. + +Field | Data type | Description +:--- | :--- | :--- +`combination.technique` | String | The technique used for combining scores. Valid value is `rrf`. Optional. Default is `rrf`. +`combination.rank_constant` | Integer | A constant added to each document's rank before calculating the reciprocal score. Valid values are in the [1, 10000] range. A larger rank constant makes the scores more uniform, reducing the influence of top-ranked results. A smaller rank constant creates a greater score difference between ranks, giving more weight to top-ranked items. Optional. Default is `60`. +`combination.parameters.weights` | Array of floating-point values | Specifies the weights to use for each query clause. Valid values are in the [0.0, 1.0] range and signify decimal percentages. The closer the weight is to 1.0, the more weight is given to a query clause. The number of values in the `weights` array must equal the number of query clauses. The sum of the values in the array must equal 1.0. Optional. If not provided, all query clauses are given equal weight. To override these weights for a single request, specify the `weights` parameter in the [`hybrid` query]({{site.url}}{{site.baseurl}}/query-dsl/compound/hybrid/#weighting-subqueries). + +## Example + +The following request creates a search pipeline containing a `score-ranker-processor` that uses the `rrf` combination technique with the default rank constant of `60`: + +```json +PUT /_search/pipeline/rrf-pipeline +{ + "description": "Post processor for hybrid RRF search", + "phase_results_processors": [ + { + "score-ranker-processor": { + "combination": { + "technique": "rrf" + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The following request sets `rank_constant` to `40` and applies custom weights to each query clause. Query clause 1 has a weight of 0.7, and query clause 2 has a weight of 0.3: + +```json +PUT /_search/pipeline/rrf-pipeline +{ + "description": "Post processor for hybrid RRF search", + "phase_results_processors": [ + { + "score-ranker-processor": { + "combination": { + "technique": "rrf", + "rank_constant": 40, + "parameters": { + "weights": [ + 0.7, + 0.3 + ] + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +To use the pipeline, specify it in a search request containing a `hybrid` query: + +```json +GET /my-nlp-index/_search?search_pipeline=rrf-pipeline +{ + "query": { + "hybrid": { + "queries": [ + { + "match": { + "passage_text": "running shoes" + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "running shoes", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` +{% include copy-curl.html %} + +## Related documentation + +- [Reciprocal rank fusion]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/rrf/) +- [Hybrid search]({{site.url}}{{site.baseurl}}/vector-search/ai-search/hybrid-search/) +- [Normalization processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/) diff --git a/_search-plugins/search-pipelines/script-processor.md b/_search-plugins/search-pipelines/script-processor.md index e1e629e3..903c1556 100644 --- a/_search-plugins/search-pipelines/script-processor.md +++ b/_search-plugins/search-pipelines/script-processor.md @@ -1,15 +1,17 @@ --- layout: default title: Script -nav_order: 30 +nav_order: 120 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- -# Script processor +# Script search processor +Introduced 2.8 +{: .label .label-purple } -The `script` search request processor intercepts a search request and adds an inline Painless script that is run on incoming requests. The script can only run on the following request fields: +The `script` search request processor intercepts a search request and adds an inline [Painless]({{site.url}}{{site.baseurl}}/scripting/painless/) script that is run on incoming requests. The script can only run on the following request fields: - `from` - `size` @@ -24,7 +26,7 @@ The `script` search request processor intercepts a search request and adds an in For request field definitions, see [search request fields]({{site.url}}{{site.baseurl}}/api-reference/search#request-body). -## Request fields +## Request body fields The following table lists all available request fields. diff --git a/_search-plugins/search-pipelines/search-pipeline-metrics.md b/_search-plugins/search-pipelines/search-pipeline-metrics.md index 85d9e8e7..9d72ecc8 100644 --- a/_search-plugins/search-pipelines/search-pipeline-metrics.md +++ b/_search-plugins/search-pipelines/search-pipeline-metrics.md @@ -1,10 +1,9 @@ --- layout: default title: Search pipeline metrics -nav_order: 50 +nav_order: 60 has_children: false parent: Search pipelines -grand_parent: Search --- # Search pipeline metrics diff --git a/_search-plugins/search-pipelines/search-processors.md b/_search-plugins/search-pipelines/search-processors.md index 36b848e6..b808a7a6 100644 --- a/_search-plugins/search-pipelines/search-processors.md +++ b/_search-plugins/search-pipelines/search-processors.md @@ -1,52 +1,56 @@ --- layout: default -title: Search processors +title: User-defined search processors nav_order: 40 has_children: true parent: Search pipelines -grand_parent: Search --- -# Search processors +# User-defined search processors -Search processors can be of the following types: +**User-defined search processors** are processors that you manually configure in search pipelines to customize search behavior. You define these processors in your pipeline configuration and control their parameters, execution order, and conditions. -- [Search request processors](#search-request-processors) -- [Search response processors](#search-response-processors) -- [Search phase results processors](#search-phase-results-processors) +The following sections list all user-defined search processors available in OpenSearch. OpenSearch can also create processors automatically based on search request parameters. For more information, see [System-generated search processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/system-generated-search-processors/). ## Search request processors -A search request processor intercepts a search request (the query and the metadata passed in the request), performs an operation with or on the search request, and submits the search request to the index. +A _search request processor_ intercepts a search request (the query and the metadata passed in the request), performs an operation with or on the search request, and submits the search request to the index. The following table lists all supported search request processors. Processor | Description | Earliest available version :--- | :--- | :--- +[`agentic_query_translator`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-query-translator-processor/) | Translates `agentic` queries into OpenSearch query domain-specific language (DSL) and executes an agent to process the query. | 3.2 [`filter_query`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/filter-query-processor/) | Adds a filtering query that is used to filter requests. | 2.8 -[`neural_query_enricher`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/neural-query-enricher/) | Sets a default model for neural search at the index or field level. | 2.11 -[`script`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/script-processor/) | Adds a script that is run on newly indexed documents. | 2.8 +[`ml_inference`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-request/) | Invokes registered machine learning (ML) models in order to rewrite queries. | 2.16 +[`neural_query_enricher`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/neural-query-enricher/) | Sets a default model for neural search and neural sparse search at the index or field level. | 2.11 (neural), 2.13 (neural sparse) +[`neural_sparse_two_phase_processor`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/neural-sparse-query-two-phase-processor/) | Accelerates the neural sparse query. | 2.15 [`oversample`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/oversample-processor/) | Increases the search request `size` parameter, storing the original value in the pipeline state. | 2.12 - +[`script`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/script-processor/) | Adds a script that is run on newly indexed documents. | 2.8 ## Search response processors -A search response processor intercepts a search response and search request (the query, results, and metadata passed in the request), performs an operation with or on the search response, and returns the search response. +A _search response processor_ intercepts a search response and search request (the query, results, and metadata passed in the request), performs an operation with or on the search response, and returns the search response. The following table lists all supported search response processors. Processor | Description | Earliest available version :--- | :--- | :--- +[`agentic_context`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/agentic-context-processor/)| Returns the agent summary, generated query, and memory ID for an `agentic` query. | 3.3 +[`collapse`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/collapse-processor/)| Deduplicates search hits based on a field value, similarly to `collapse` in a search request. | 2.12 +[`hybrid_score_explanation`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/explanation-processor/)| Adds detailed scoring information to search results when the `explain` parameter is enabled, providing information about score normalization, combination techniques, and individual score calculations in hybrid queries. | 2.19 +[`ml_inference`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-response/) | Invokes registered machine learning (ML) models in order to incorporate model output as additional search response fields. | 2.16 [`personalize_search_ranking`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/personalize-search-ranking/) | Uses [Amazon Personalize](https://aws.amazon.com/personalize/) to rerank search results (requires setting up the Amazon Personalize service). | 2.9 -[`retrieval_augmented_generation`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rag-processor/) | Used for retrieval-augmented generation (RAG) in [conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/). | 2.10 (generally available in 2.12) [`rename_field`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rename-field-processor/)| Renames an existing field. | 2.8 [`rerank`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/)| Reranks search results using a cross-encoder model. | 2.12 -[`collapse`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/collapse-processor/)| Deduplicates search hits based on a field value, similarly to `collapse` in a search request. | 2.12 +[`retrieval_augmented_generation`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rag-processor/) | Used for retrieval-augmented generation (RAG) in [conversational search]({{site.url}}{{site.baseurl}}/search-plugins/conversational-search/). | 2.10 (generally available in 2.12) +[`sort`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/sort-processor/)| Sorts an array of items in either ascending or descending order. | 2.16 +[`split`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/split-processor/)| Splits a string field into an array of substrings based on a specified delimiter. | 2.17 [`truncate_hits`]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/truncate-hits-processor/)| Discards search hits after a specified target count is reached. Can undo the effect of the `oversample` request processor. | 2.12 ## Search phase results processors -A search phase results processor runs between search phases at the coordinating node level. It intercepts the results retrieved from one search phase and transforms them before passing them to the next search phase. +A _search phase results processor_ runs between search phases at the coordinating node level. It intercepts the results retrieved from one search phase and transforms them before passing them to the next search phase. The following table lists all supported search phase results processors. @@ -121,3 +125,7 @@ The response contains the `search_pipelines` object that lists the available req In addition to the processors provided by OpenSearch, additional processors may be provided by plugins. {: .note} + +## Selectively enabling processors + +Processors defined by the [search-pipeline-common module](https://github.com/opensearch-project/OpenSearch/blob/2.x/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/SearchPipelineCommonModulePlugin.java) are selectively enabled through the following cluster settings: `search.pipeline.common.request.processors.allowed`, `search.pipeline.common.response.processors.allowed`, or `search.pipeline.common.search.phase.results.processors.allowed`. If unspecified, then all processors are enabled. An empty list disables all processors. Removing enabled processors causes pipelines using them to fail after a node restart. \ No newline at end of file diff --git a/_search-plugins/search-pipelines/sort-processor.md b/_search-plugins/search-pipelines/sort-processor.md new file mode 100644 index 00000000..5db1ed62 --- /dev/null +++ b/_search-plugins/search-pipelines/sort-processor.md @@ -0,0 +1,253 @@ +--- +layout: default +title: Sort +nav_order: 130 +has_children: false +parent: User-defined search processors +grand_parent: Search pipelines +--- + +# Sort search processor +Introduced 2.16 +{: .label .label-purple } + +The `sort` processor sorts an array of items in either ascending or descending order. Numeric arrays are sorted numerically, while string or mixed arrays (strings and numbers) are sorted lexicographically. The processor throws an error if the input is not an array. + +## Request body fields + +The following table lists all available request fields. + +Field | Data type | Description +:--- | :--- | :--- +`field` | String | The field to be sorted. Must be an array. Required. +`order` | String | The sort order to apply. Accepts `asc` for ascending or `desc` for descending. Default is `asc`. +`target_field` | String | The name of the field in which the sorted array is stored. If not specified, then the sorted array is stored in the same field as the original array (the `field` variable). +`tag` | String | The processor's identifier. +`description` | String | A description of the processor. +`ignore_failure` | Boolean | If `true`, then OpenSearch [ignores any failure]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/#ignoring-processor-failures) of this processor and continues to run the remaining processors in the search pipeline. Optional. Default is `false`. + +## Example + +The following example demonstrates using a search pipeline with a `sort` processor. + +### Setup + +Create an index named `my_index` and index a document with the field `message` that contains an array of strings: + +```json +POST /my_index/_doc/1 +{ + "message": ["one", "two", "three", "four"], + "visibility": "public" +} +``` +{% include copy-curl.html %} + +### Creating a search pipeline + +Create a search pipeline with a `sort` response processor that sorts the `message` field and stores the sorted results in the `sorted_message` field: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "sort": { + "field": "message", + "target_field": "sorted_message" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Using a search pipeline + +Search for documents in `my_index` without a search pipeline: + +```json +GET /my_index/_search +``` +{% include copy-curl.html %} + +The response contains the field `message`: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "message": [ + "one", + "two", + "three", + "four" + ], + "visibility": "public" + } + } + ] + } +} +``` +</details> + +To search with a pipeline, specify the pipeline name in the `search_pipeline` query parameter: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` +{% include copy-curl.html %} + +The `sorted_message` field contains the strings from the `message` field sorted alphabetically: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```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": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "sorted_message": [ + "four", + "one", + "three", + "two" + ], + "message": [ + "one", + "two", + "three", + "four" + ] + } + } + ] + } +} +``` +</details> + +You can also use the `fields` option to search for specific fields in a document: + +```json +POST /my_index/_search?pretty&search_pipeline=my_pipeline +{ + "fields": ["visibility", "message"] +} +``` +{% include copy-curl.html %} + +In the response, the `message` field is sorted and the results are stored in the `sorted_message` field: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "sorted_message": [ + "four", + "one", + "three", + "two" + ], + "message": [ + "one", + "two", + "three", + "four" + ] + }, + "fields": { + "visibility": [ + "public" + ], + "sorted_message": [ + "four", + "one", + "three", + "two" + ], + "message": [ + "one", + "two", + "three", + "four" + ] + } + } + ] + } +} +``` +</details> \ No newline at end of file diff --git a/_search-plugins/search-pipelines/split-processor.md b/_search-plugins/search-pipelines/split-processor.md new file mode 100644 index 00000000..756f7d62 --- /dev/null +++ b/_search-plugins/search-pipelines/split-processor.md @@ -0,0 +1,236 @@ +--- +layout: default +title: Split +nav_order: 140 +has_children: false +parent: User-defined search processors +grand_parent: Search pipelines +--- + +# Split search processor +Introduced 2.17 +{: .label .label-purple } + +The `split` processor splits a string field into an array of substrings based on a specified delimiter. + +## Request body fields + +The following table lists all available request fields. + +Field | Data type | Description +:--- | :--- | :--- +`field` | String | The field containing the string to be split. Required. +`separator` | String | The delimiter used to split the string. Specify either a single separator character or a regular expression pattern. Required. +`preserve_trailing` | Boolean | If set to `true`, preserves empty trailing fields (for example, `''`) in the resulting array. If set to `false`, then empty trailing fields are removed from the resulting array. Default is `false`. +`target_field` | String | The field in which the array of substrings is stored. If not specified, then the field is updated in place. +`tag` | String | The processor's identifier. +`description` | String | A description of the processor. +`ignore_failure` | Boolean | If `true`, then OpenSearch [ignores any failure]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/#ignoring-processor-failures) of this processor and continues to run the remaining processors in the search pipeline. Optional. Default is `false`. + +## Example + +The following example demonstrates using a search pipeline with a `split` processor. + +### Setup + +Create an index named `my_index` and index a document containing the field `message`: + +```json +POST /my_index/_doc/1 +{ + "message": "ingest, search, visualize, and analyze data", + "visibility": "public" +} +``` +{% include copy-curl.html %} + +### Creating a search pipeline + +The following request creates a search pipeline with a `split` response processor that splits the `message` field and stores the results in the `split_message` field: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "split": { + "field": "message", + "separator": ", ", + "target_field": "split_message" + } + } + ] +} +``` +{% include copy-curl.html %} + +### Using a search pipeline + +Search for documents in `my_index` without a search pipeline: + +```json +GET /my_index/_search +``` +{% include copy-curl.html %} + +The response contains the field `message`: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} +```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": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "message": "ingest, search, visualize, and analyze data", + "visibility": "public" + } + } + ] + } +} +``` +</details> + +To search with a pipeline, specify the pipeline name in the `search_pipeline` query parameter: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` +{% include copy-curl.html %} + +The `message` field is split and the results are stored in the `split_message` field: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "message": "ingest, search, visualize, and analyze data", + "split_message": [ + "ingest", + "search", + "visualize", + "and analyze data" + ] + } + } + ] + } +} +``` +</details> + +You can also use the `fields` option to search for specific fields in a document: + +```json +POST /my_index/_search?pretty&search_pipeline=my_pipeline +{ + "fields": ["visibility", "message"] +} +``` +{% include copy-curl.html %} + +In the response, the `message` field is split and the results are stored in the `split_message` field: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "message": "ingest, search, visualize, and analyze data", + "split_message": [ + "ingest", + "search", + "visualize", + "and analyze data" + ] + }, + "fields": { + "visibility": [ + "public" + ], + "message": [ + "ingest, search, visualize, and analyze data" + ], + "split_message": [ + "ingest", + "search", + "visualize", + "and analyze data" + ] + } + } + ] + } +} +``` +</details> \ No newline at end of file diff --git a/_search-plugins/search-pipelines/system-generated-search-processors.md b/_search-plugins/search-pipelines/system-generated-search-processors.md new file mode 100644 index 00000000..61e53b65 --- /dev/null +++ b/_search-plugins/search-pipelines/system-generated-search-processors.md @@ -0,0 +1,70 @@ +--- +layout: default +title: System-generated search processors +nav_order: 50 +has_children: false +parent: Search pipelines +--- + +# System-generated search processors +**Introduced 3.3** +{: .label .label-purple } + +System-generated search processors are processors that OpenSearch creates automatically based on the search request. Unlike [user-defined processors]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/search-processors/) that you manually configure in pipelines, system-generated processors are triggered automatically when certain features are used, eliminating the need for manual processor configuration. + +## Enabling system-generated search processors + +To enable system-generated search processor creation, set the `cluster.search.enabled_system_generated_factories` cluster setting to `*` (all factories) or explicitly list the factories you want to enable. The following example enables `mmr_over_sample_factory`, `mmr_rerank_factory`, and `semantic-highlighter`: + +```json +PUT _cluster/settings +{ + "persistent": { + "cluster.search.enabled_system_generated_factories": [ + "mmr_over_sample_factory", + "mmr_rerank_factory", + "semantic-highlighter" + ] + } +} +``` +{% include copy-curl.html %} + +## Processor types + +OpenSearch supports the following types of system-generated processors: + +* [Search request processors](#system-generated-search-request-processors) +* [Search response processors](#system-generated-search-response-processors) + +Each system-generated processor runs at a fixed execution stage, either before or after user-defined processors of the same type. +{: .note} + +### System-generated search request processors + +The following table lists the available system-generated search request processors. + +| Processor name | Processor factory name | Execution stage | Trigger condition | Description | +| ----------------- | ------------------------- | ------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mmr_over_sample` | `mmr_over_sample_factory` | Runs after any user-defined request processors. | Triggered when a search request includes the `mmr` parameter in the `ext` object. See [Vector search with MMR reranking]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/vector-search-mmr/). | Adjusts the query size and `k` value of the `knn` or `neural` query to oversample candidates for maximal marginal relevance (MMR) reranking. | +| `knn_default_excludes` | `knn_default_excludes_factory` | Runs before any user-defined request processors. | Triggered for every search request, except when the request already specifies how to return the source by setting `_source` to `true` or `false` or by setting `stored_fields` to `_none_`. Applies only to indexes containing `knn_vector` fields with `_source` enabled. See [Automatically exclude vectors from search results]({{site.url}}{{site.baseurl}}/vector-search/performance-tuning-search/#automatically-exclude-vectors-from-search-results). | Adds all `knn_vector` fields to `_source.excludes` so that vectors are omitted from the search response by default. Fields already listed in the request's `_source.includes` or `_source.excludes` remain unchanged. | + +### System-generated search response processors + +The following table lists the available system-generated search response processors. + +| Processor name | Processor factory name | Execution stage | Trigger condition | Description | +| -------------- | ---------------------- | ------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `mmr_rerank` | `mmr_rerank_factory` | Runs before any user-defined response processors. | Triggered when a search request includes the `mmr` parameter in the `ext` object. See [Vector search with MMR reranking]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/vector-search-mmr/). | Reranks the oversampled results using MMR and reduces them to the original query size. | +| `semantic-highlighter` | `semantic-highlighter` | Runs after any user-defined response processors. | Triggered when a search request contains a `highlight` object with `type` set to `semantic` and includes the `semantic_highlighting_batch` parameter in the `ext` object. See [The `semantic` highlighter]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/#the-semantic-highlighter). | Performs batch inference processing for semantic highlighting. | + +## Limitations + +The following limitations apply to system-generated processors: + +- OpenSearch supports only **one system-generated processor per processor type and execution stage** for a given search request. Since each processor type (request and response) can run at two execution stages (before or after user-defined processors), a single search request can include multiple system-generated processors, as long as they are of different types or run at different execution stages. This limitation ensures deterministic execution order and predictable behavior. + +## Related documentation + +- [Vector search with MMR reranking]({{site.url}}{{site.baseurl}}/vector-search/specialized-operations/vector-search-mmr/) +- [Automatically exclude vectors from search results]({{site.url}}{{site.baseurl}}/vector-search/performance-tuning-search/#automatically-exclude-vectors-from-search-results) \ No newline at end of file diff --git a/_search-plugins/search-pipelines/truncate-hits-processor.md b/_search-plugins/search-pipelines/truncate-hits-processor.md index 871879ef..927650c9 100644 --- a/_search-plugins/search-pipelines/truncate-hits-processor.md +++ b/_search-plugins/search-pipelines/truncate-hits-processor.md @@ -1,13 +1,15 @@ --- layout: default title: Truncate hits -nav_order: 35 +nav_order: 150 has_children: false -parent: Search processors +parent: User-defined search processors grand_parent: Search pipelines --- # Truncate hits processor +Introduced 2.12 +{: .label .label-purple } The `truncate_hits` response processor discards returned search hits after a given hit count is reached. The `truncate_hits` processor is designed to work with the [`oversample` request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/oversample-processor/) but may be used on its own. @@ -20,7 +22,7 @@ The following is a common usage pattern: 1. In the response pipeline, apply a reranking processor (which may promote results from beyond the originally requested top N) or the `collapse` processor (which may discard results after deduplication). 1. Apply the `truncate` processor to return (at most) the originally requested number of hits. -## Request fields +## Request body fields The following table lists all request fields. diff --git a/_search-plugins/search-pipelines/using-search-pipeline.md b/_search-plugins/search-pipelines/using-search-pipeline.md index 882c94d9..21feb1a1 100644 --- a/_search-plugins/search-pipelines/using-search-pipeline.md +++ b/_search-plugins/search-pipelines/using-search-pipeline.md @@ -4,7 +4,6 @@ title: Using a search pipeline nav_order: 20 has_children: false parent: Search pipelines -grand_parent: Search --- # Using a search pipeline @@ -17,14 +16,45 @@ You can use a search pipeline in the following ways: ## Specifying an existing search pipeline for a request -After you [create a search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/), you can use the pipeline with a query by specifying the pipeline name in the `search_pipeline` query parameter: +After you [create a search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/creating-search-pipeline/), you can use the pipeline with a query in the following ways. For a complete example of using a search pipeline with a `filter_query` processor, see [`filter_query` processor example]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/filter-query-processor#example). + +### Specifying the pipeline in a query parameter + +You can specify the pipeline name in the `search_pipeline` query parameter as follows: ```json GET /my_index/_search?search_pipeline=my_pipeline ``` {% include copy-curl.html %} -For a complete example of using a search pipeline with a `filter_query` processor, see [`filter_query` processor example]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/filter-query-processor#example). +### Specifying the pipeline in the request body + +You can provide a search pipeline ID in the search request body as follows: + +```json +GET /my-index/_search +{ + "query": { + "match_all": {} + }, + "from": 0, + "size": 10, + "search_pipeline": "my_pipeline" +} +``` +{% include copy-curl.html %} + +For multi-search, you can provide a search pipeline ID in the search request body as follows: + +```json +GET /_msearch +{ "index": "test"} +{ "query": { "match_all": {} }, "from": 0, "size": 10, "search_pipeline": "my_pipeline"} +{ "index": "test-1", "search_type": "dfs_query_then_fetch"} +{ "query": { "match_all": {} }, "search_pipeline": "my_pipeline1" } + +``` +{% include copy-curl.html %} ## Using a temporary search pipeline for a request @@ -130,6 +160,53 @@ The response contains only the public document, indicating that the pipeline was ``` </details> +You can search across multiple indexes that share the same default pipeline. For example, `alias1` has two indexes, `my_index1` and `my_index2`, both of which have the default pipeline `my_pipeline` attached to them: + +```json +GET /alias1/_search +``` +{% include copy-curl.html %} + +The response includes only the public version of the document, confirming that the default pipeline was successfully applied: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 59, + "timed_out": false, + "_shards": { + "total": 2, + "successful": 2, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.0, + "hits": [ + { + "_index": "my_index1", + "_id": "1", + "_score": 0.0, + "_source": { + "message": "This is a public message", + "visibility": "public" + } + } + ] + } +} +``` +</details> + ### Disabling the default pipeline for a request If you want to run a search request without applying the default pipeline, you can set the `search_pipeline` query parameter to `_none`: diff --git a/_search-plugins/search-relevance/compare-query-sets.md b/_search-plugins/search-relevance/compare-query-sets.md new file mode 100644 index 00000000..471bffad --- /dev/null +++ b/_search-plugins/search-relevance/compare-query-sets.md @@ -0,0 +1,252 @@ +--- +layout: default +title: Comparing query sets +nav_order: 12 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Comparing search configurations + +To compare the results of two different search configurations, you can run a pairwise experiment. To achieve this, you need two search configurations and a query set to use for the search configuration. + +For more information about creating a query set, see [Query Sets]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/query-sets/). + +For more information about creating search configurations, see [Search Configurations]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/). + +## Creating a pairwise experiment + +An experiment is used to compare the metrics between two different search configurations. An experiment shows you the top N results for every query based on the specified search configurations. In the dashboard, you can view the returned documents from any of the queries in the query set and determine which search configuration returns more relevant results. Additionally, you can measure the similarity between the two returned search result lists using the provided similarity metrics. + +### Example + +To create a pairwise comparison experiment for the specified query set and search configurations, send the following request: + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "8368a359-146b-4690-b756-40591b2fcddb", + "searchConfigurationList": ["a5acc9f3-6ad7-43f4-9651-fe118c499bc6", "26c7255c-c36e-42fb-b5b2-633dbf8e53b6"], + "size": 10, + "type": "PAIRWISE_COMPARISON" +} +``` +{% include copy-curl.html %} + +### Request body fields + +The following table lists the available input parameters. + +Field | Data type | Description +:--- | :--- | :--- +`querySetId` | String | The query set ID. +`searchConfigurationList` | List | A list of search configuration IDs to use for comparison. +`size` | Integer | The number of documents to return in the results. +`type` | String | Defines the type of experiment to run. Valid values are `PAIRWISE_COMPARISON`, `HYBRID_OPTIMIZER`, or `POINTWISE_EVALUATION`. Depending on the experiment type, you must provide different body fields in the request. `PAIRWISE_COMPARISON` is for comparing two search configurations against a query set and is used [here]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-query-sets/). `HYBRID_OPTIMIZER` is for combining results and is used [here]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/optimize-hybrid-search/). `POINTWISE_EVALUATION` is for evaluating a search configuration against judgments and is used [here]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/evaluate-search-quality/). + +The response contains the experiment ID of the created experiment: + +```json +{ + "experiment_id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "experiment_result": "CREATED" +} +``` +## Interpreting the experiment results +To interpret the experiment results, use the following operations. + +### Retrieving the experiment results + +Use the following API to retrieve the result of a specific experiment. + +#### Endpoints + +```json +GET _plugins/_search_relevance/experiments +GET _plugins/_search_relevance/experiments/{experiment_id} +``` + +#### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `experiment_id` | String | The ID of the experiment to retrieve. Retrieves all experiments when empty. | + +#### Example request + +```json +GET _plugins/_search_relevance/experiments/cbd2c209-96d1-4012-aa73-e524b7a1b11a +``` + +#### Example response + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "_score": 1, + "_source": { + "id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "timestamp": "2025-06-11T23:24:26.792Z", + "type": "PAIRWISE_COMPARISON", + "status": "PROCESSING", + "querySetId": "8368a359-146b-4690-b756-40591b2fcddb", + "searchConfigurationList": [ + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6", + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6" + ], + "judgmentList": [], + "size": 10, + "results": {} + } + } + ] + } +} +``` + +Once the experiment finishes running, the results are available: + +<details open markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 34, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "_score": 1.0, + "_source": { + "id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "timestamp": "2025-06-12T04:18:37.284Z", + "type": "PAIRWISE_COMPARISON", + "status": "COMPLETED", + "querySetId": "7889ffe9-835e-4f48-a9cd-53905bb967d3", + "searchConfigurationList": [ + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6", + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6" + ], + "judgmentList": [], + "size": 10, + "results": { + "tv": { + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6": [ + "B07X3S9RTZ", + "B07WVZFKLQ", + "B00GXD4NWE", + "B07ZKCV5K5", + "B07ZKDVHFB", + "B086VKT9R8", + "B08XLM8YK1", + "B07FPP6TB5", + "B07N1TMNHB", + "B09CDHM8W7" + ], + "pairwiseComparison": { + "jaccard": 0.11, + "rbo90": 0.16, + "frequencyWeighted": 0.2, + "rbo50": 0.07 + }, + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6": [ + "B07Q7VGW4Q", + "B00GXD4NWE", + "B07VML1CY1", + "B07THVCJK3", + "B07RKSV7SW", + "B010EAW8UK", + "B07FPP6TB5", + "B073G9ZD33", + "B07VXRXRJX", + "B07Q45SP9P" + ] + }, + "led tv": { + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6": [ + "B01M1D0KL1", + "B07YSMD3Z9", + "B07V4CY9GZ", + "B074KFP426", + "B07S8XNWWF", + "B07XBJR7GY", + "B075FDWSHT", + "B01N2Z17MS", + "B07F1T4JFB", + "B07S658ZLH" + ], + "pairwiseComparison": { + "jaccard": 0.11, + "rbo90": 0.13, + "frequencyWeighted": 0.2, + "rbo50": 0.03 + }, + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6": [ + "B07Q45SP9P", + "B074KFP426", + "B07JKVKZX8", + "B07THVCJK3", + "B0874XJYW8", + "B08LVPWQQP", + "B07V4CY9GZ", + "B07X3BS3DF", + "B074PDYLCZ", + "B08CD9MKLZ" + ] + } + } + } + } + ] + } +} +``` + +</details> + +### Interpreting the results + +As shown in the preceding response, both search configurations return the top N documents, with `size` set to 10 in the search request. In addition to the results, the response also includes metrics from the pairwise comparison. + +### Response body fields + +Field | Description +:--- | :--- +`jaccard` | Shows the similarity score by dividing the intersection cardinality by the union cardinality of the returned documents. +`rbo` | The Rank-Biased Overlap (RBO) metric compares the returned result sets at each ranking depth—for example, the top 1 document, top 2 documents, and so on. It places greater importance on higher-ranked results, giving more weight to earlier positions in the list. +`frequencyWeighted` | Similar to the Jaccard metric, the frequency-weighted metric calculates the ratio of the weighted intersection to the weighted union of two sets. However, unlike standard Jaccard, it gives more weight to documents with higher frequencies, skewing the result toward more frequently occurring items. diff --git a/_search-plugins/search-relevance/compare-search-results.md b/_search-plugins/search-relevance/compare-search-results.md index 9e34b7cf..3820b89a 100644 --- a/_search-plugins/search-relevance/compare-search-results.md +++ b/_search-plugins/search-relevance/compare-search-results.md @@ -1,17 +1,15 @@ --- layout: default -title: Comparing search results -nav_order: 55 -parent: Search relevance -has_children: true -has_toc: false -redirect_from: - - /search-plugins/search-relevance/ +title: Comparing single queries +nav_order: 10 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false --- -# Comparing search results +# Comparing single queries -With Compare Search Results in OpenSearch Dashboards, you can compare results from two queries side by side to determine whether one query produces better results than the other. Using this tool, you can evaluate search quality by experimenting with queries. +With Compare Search Results in OpenSearch Dashboards, you can compare results from two queries side by side to determine whether one query produces better results than the other. Using this tool, you can evaluate search quality by experimenting with queries. For example, you can see how results change when you apply one of the following query changes: @@ -21,24 +19,26 @@ For example, you can see how results change when you apply one of the following ## Prerequisites -Before you get started, you must index data in OpenSearch. To learn how to create a new index, see [Index data]({{site.url}}{{site.baseurl}}/opensearch/index-data/). +Before you get started, you must index data in OpenSearch. To learn how to create a new index, see [Indexing data]({{site.url}}{{site.baseurl}}/im-plugin/indexing-data/). Alternatively, you can add sample data in OpenSearch Dashboards using the following steps: 1. On the top menu bar, go to **OpenSearch Dashboards > Overview**. 1. Select **View app directory**. -1. Select **Add sample data**. +1. Select **Add sample data**. 1. Choose one of the built-in datasets and select **Add data**. +<!-- vale off --> ## Using Compare Search Results in OpenSearch Dashboards +<!-- vale on --> To compare search results in OpenSearch Dashboards, perform the following steps. -**Step 1:** On the top menu bar, go to **OpenSearch Plugins > Search Relevance**. +**Step 1:** On the top menu bar, go to **OpenSearch Plugins > Search Relevance**. **Step 2:** Enter the search text in the search bar. -**Step 3:** Select an index for **Query 1** and enter a query (request body only) in [OpenSearch Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). The `GET` HTTP method and the `_search` endpoint are implicit. Use the `%SearchText%` variable to refer to the text in the search bar. +**Step 3:** Select an index for **Query 1** and enter a query (request body only) in [OpenSearch Query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/). The `GET` HTTP method and the `_search` endpoint are implicit. Use the `%queryText%` variable to refer to the text in the search bar. The following is an example query: @@ -46,7 +46,7 @@ The following is an example query: { "query": { "multi_match": { - "query": "%SearchText%", + "query": "%queryText%", "fields": [ "description", "item_name" ] } } @@ -61,7 +61,7 @@ The following example query boosts the `title` field in the search results: { "query": { "multi_match": { - "query": "%SearchText%", + "query": "%queryText%", "fields": [ "description", "item_name^3" ] } } @@ -72,9 +72,9 @@ The following example query boosts the `title` field in the search results: The following example screen shows a search for the word "cup" in the `description` and `item_name` fields with and without boosting the `item_name`. -<img src="{{site.url}}{{site.baseurl}}/images/search_relevance.png" alt="Compare search results"/>{: .img-fluid } +![Compare search results]({{site.url}}{{site.baseurl}}/images/search_relevance.png) -If a result in Result 1 appears in Result 2, the `Up` and `Down` indicators below the result number signify how many places the result moved up or down compared to the same result in Result 2. In this example, the document with the ID 2 is `Up 1` place in Result 2 compared to Result 1 and `Down 1` place in Result 1 compared to Result 2. +If a result in Result 1 appears in Result 2, the `Up` and `Down` indicators below the result number signify how many positions the result moved up or down compared to the same result in Result 2. In this example, the document with the ID 2 is `Up 1` position in Result 2 compared to Result 1 and `Down 1` position in Result 1 compared to Result 2. ## Changing the number of results @@ -85,7 +85,7 @@ By default, OpenSearch returns the top 10 results. To change the number of retur "size": 15, "query": { "multi_match": { - "query": "%SearchText%", + "query": "%queryText%", "fields": [ "title^3", "text" ] } } @@ -95,9 +95,30 @@ By default, OpenSearch returns the top 10 results. To change the number of retur Setting `size` to a high value (for example, larger than 250 documents) may degrade performance. {: .note} -You cannot save a given comparison for future use, so Compare Search Results is not suitable for systematic testing. +You cannot save a given comparison for future use, so Compare Search Results is not suitable for systematic testing. Instead, review the [Search result comparison]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/comparing-search-results/) experiment. {: .note} +## Comparing OpenSearch search results using Search Relevance Workbench + +[Search Relevance Workbench]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/) provides richer visualization options for examining the difference between two queries. + +To use Search Relevance Workbench, follow steps 1--4. The displayed results and the options for viewing the differences are shown in the following image. + +![Compare search results]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/comparing_search_results.png) + +The top section provides a summary of the results: how many of the retrieved results are unique to the query on the left, how many are unique to the query on the right, and how many are part of both queries? + +What follows is a visual representation of the retrieved results. By default the unique identifier field (`_id`) is shown. You can change this by selecting a different field in the **Display Field** dropdown list. +In the side-by-side view, you can see the positional changes for all common documents among the two result lists. +Selecting one item shows all stored fields in the index to facilitate easier document identification. + +Lastly, Search Relevance Workbench allows you to choose among different visualization styles from a dropdown list: + +* **Default style**: Different colors are used for the two result list documents (unique results are on the left in yellow and on the right in purple, and common results are displayed in green). +* **Ranking change color coding**: All unique documents are purple, and common results are green to focus on ranking changes. +* **Ranking change color coding 2**: All unique documents are gray, and common results are green to focus on ranking changes. +* **Venn diagram color coding**: All unique documents are purple, and common results are blue as in the Venn diagram at the top of the two result lists. + ## Comparing OpenSearch search results with reranked results One use case for Compare Search Results is the comparison of raw OpenSearch results with the same results processed by a reranking application. OpenSearch currently integrates with the following two rerankers: @@ -105,7 +126,9 @@ One use case for Compare Search Results is the comparison of raw OpenSearch resu - [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) +<!-- vale off --> ### Reranking results with Amazon Kendra Intelligent Ranking for OpenSearch +<!-- vale on --> An example of a reranker is **Amazon Kendra Intelligent Ranking for OpenSearch**, contributed by the Amazon Kendra team. This plugin takes search results from OpenSearch and applies Amazon Kendra’s semantic relevance rankings calculated using vector embeddings and other semantic search techniques. For many applications, this provides better result rankings. @@ -115,9 +138,9 @@ To try Amazon Kendra Intelligent Ranking, you must first set up the Amazon Kendr To compare search results with reranked results in OpenSearch Dashboards, enter a query in **Query 1** and enter the same query using a reranker in **Query 2**. Then compare the OpenSearch results with the reranked results. -The following example demonstrates searching for the text "snacking nuts" in the `abo` index. The documents in the index contain snack descriptions in the `bullet_point` array. +The following example demonstrates searching for the text "snacking nuts" in the `abo` index. The documents in the index contain snack descriptions in the `bullet_point` array. -<img src="{{site.url}}{{site.baseurl}}/images/kendra_query.png" alt="OpenSearch Intelligent Ranking query"/>{: .img-fluid } +![OpenSearch Intelligent Ranking query]({{site.url}}{{site.baseurl}}/images/kendra_query.png) 1. Enter `snacking nuts` in the search bar. 1. Enter the following query, which searches the `bullet_point` field for the search text "snacking nuts", in **Query 1**: @@ -126,7 +149,7 @@ The following example demonstrates searching for the text "snacking nuts" in the { "query": { "match": { - "bullet_point": "%SearchText%" + "bullet_point": "%queryText%" } }, "size": 25 @@ -138,7 +161,7 @@ The following example demonstrates searching for the text "snacking nuts" in the { "query" : { "match" : { - "bullet_point": "%SearchText%" + "bullet_point": "%queryText%" } }, "size": 25, @@ -161,7 +184,9 @@ The following example demonstrates searching for the text "snacking nuts" in the In the preceding query, `body_field` refers to the body field of the documents in the index, which Amazon Kendra Intelligent Ranking uses to rank the results. The `body_field` is required, while the `title_field` is optional. 1. Select **Search** and compare the results in **Result 1** and **Result 2**. +<!-- vale off --> ### Personalizing search results with Amazon Personalize Search Ranking +<!-- vale on --> Another example of a reranker is **Amazon Personalize Search Ranking**, contributed by the Amazon Personalize team. Amazon Personalize uses machine learning (ML) techniques to generate custom recommendations for your users. The plugin takes OpenSearch search results and applies a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) to rerank them according to their Amazon Personalize ranking. The Amazon Personalize rankings are based on the user's past behavior and metadata about the search items and the user. This workflow improves the search experience for your users by personalizing their search results. diff --git a/_search-plugins/search-relevance/comparing-search-results.md b/_search-plugins/search-relevance/comparing-search-results.md new file mode 100644 index 00000000..efd91760 --- /dev/null +++ b/_search-plugins/search-relevance/comparing-search-results.md @@ -0,0 +1,33 @@ +--- +layout: default +title: Comparing search results +nav_order: 11 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +--- + +# Comparing search results + +Comparing search results, also called a _pairwise experiment_, in OpenSearch Dashboards allows you to compare results of multiple search configurations. Using this tool helps assess how results change when applying different search configurations to queries. + +For example, you can see how results change when you apply one of the following query changes: + +- Weighting fields differently +- Different stemming or lemmatization strategies +- Shingling + +## Comparing search results of a single query + +The UI for comparing the search results of a single query lets you define two different search configurations for an individual query in order to view and compare the results side by side. Specifically, you can determine how many shared and unique documents are contained in the result lists and how their positions changed, as shown in the following image. + +![Compare search results]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/comparing_search_results.png) + +For more information about using the search result comparison tool for a single query, see [Comparing single queries]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-search-results/). + +## Comparing search results of a query set + +Typically, viewing search result changes for two configurations is the first step in the testing process. You can then scale from one query to many in Search Relevance Workbench. You can group queries into a query set, create [search configurations]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/), and compare search results on a larger scale by looking at aggregate metrics across all queries, as shown in the following image. + +![Compare search results]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/comparing-search-results-query-sets.png) + +For more information about using the search result comparison tool for a query set, see [Comparing single queries]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-query-sets/). diff --git a/_search-plugins/search-relevance/evaluate-search-quality.md b/_search-plugins/search-relevance/evaluate-search-quality.md new file mode 100644 index 00000000..828128e3 --- /dev/null +++ b/_search-plugins/search-relevance/evaluate-search-quality.md @@ -0,0 +1,212 @@ +--- +layout: default +title: Evaluating search quality +nav_order: 50 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Evaluating search quality + +Search Relevance Workbench can run pointwise experiments to evaluate search configuration quality using provided queries and relevance judgments. + +For more information about creating a query set, see [Query sets]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/query-sets/). + +For more information about creating search configurations, see [Search Configurations]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/). + +For more information about creating judgments, see [Judgments]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/judgments/). + +## Creating a pointwise experiment + +A pointwise experiment compares your search configuration results against provided relevance judgments to evaluate search quality. + +### Example request + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "a02cedc2-249d-41de-be3e-662f6f221689", + "searchConfigurationList": ["4f90e474-0806-4dd2-a8dd-0fb8a5f836eb"], + "judgmentList": ["d3d93bb3-2cf4-4da0-8d31-c298427c2756"], + "size": 8, + "type": "POINTWISE_EVALUATION" +} +``` + +### Request body fields + +The following table lists the available input parameters. + +Field | Data type | Description +:--- | :--- | :--- +`querySetId` | String | The ID of the query set. +`searchConfigurationList` | List | A list of search configuration IDs to use for comparison. +`judgmentList` | Array[String] | A list of judgment IDs to use for evaluating search accuracy. +`size` | Integer | The number of documents to return in the results. +`type` | String | The type of experiment to run. Valid values are `PAIRWISE_COMPARISON`, `HYBRID_OPTIMIZER`, or `POINTWISE_EVALUATION`. Depending on the experiment type, you must provide different body fields in the request. `PAIRWISE_COMPARISON` is for comparing two search configurations against a query set and is used [here]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-query-sets/). `HYBRID_OPTIMIZER` is for combining results and is used [here]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/optimize-hybrid-search/). `POINTWISE_EVALUATION` is for evaluating a search configuration against judgments and is used [here]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/evaluate-search-quality/). + +### Example response + +```json +{ + "experiment_id": "d707fa0f-3901-4c8b-8645-9a17e690722b", + "experiment_result": "CREATED" +} +``` + +## Managing the results + +To retrieve experiment results, follow the same process used for [comparing query sets]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-query-sets/) in pairwise experiments. + +The following is an example completed response: + +<details open markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 140, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "bb609dc9-e357-42ec-a956-92b43be0a3ab", + "_score": 1.0, + "_source": { + "id": "bb609dc9-e357-42ec-a956-92b43be0a3ab", + "timestamp": "2025-06-13T08:06:46.046Z", + "type": "POINTWISE_EVALUATION", + "status": "COMPLETED", + "querySetId": "a02cedc2-249d-41de-be3e-662f6f221689", + "searchConfigurationList": [ + "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb" + ], + "judgmentList": [ + "d3d93bb3-2cf4-4da0-8d31-c298427c2756" + ], + "size": 8, + "results": [ + { + "evaluationId": "10c60fee-11ca-49b0-9e8a-82cb7b2c044b", + "searchConfigurationId": "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb", + "queryText": "tv" + }, + { + "evaluationId": "c03a5feb-8dc2-4f7f-9d31-d99bfb392116", + "searchConfigurationId": "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb", + "queryText": "led tv" + } + ] + } + } + ] + } +} +``` + +</details> + +The results include an evaluation result ID for each search configuration. To view detailed results, query the `search-relevance-evaluation-result` index using this ID. + +The following is an example of the detailed results: + +<details open markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 59, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "search-relevance-evaluation-result", + "_id": "10c60fee-11ca-49b0-9e8a-82cb7b2c044b", + "_score": 1.0, + "_source": { + "id": "10c60fee-11ca-49b0-9e8a-82cb7b2c044b", + "timestamp": "2025-06-13T08:06:40.869Z", + "searchConfigurationId": "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb", + "searchText": "tv", + "judgmentIds": [ + "d3d93bb3-2cf4-4da0-8d31-c298427c2756" + ], + "documentIds": [ + "B07Q7VGW4Q", + "B00GXD4NWE", + "B07VML1CY1", + "B07THVCJK3", + "B07RKSV7SW", + "B010EAW8UK", + "B07FPP6TB5", + "B073G9ZD33" + ], + "metrics": [ + { + "metric": "Coverage@8", + "value": 0.0 + }, + { + "metric": "Precision@8", + "value": 0.0 + }, + { + "metric": "MAP@8", + "value": 0.0 + }, + { + "metric": "NDCG@8", + "value": 0.0 + } + ] + } + } + ] + } +} +``` + +</details> + +The results include the original request parameters along with the following metric values: + +- `Coverage@k`: The proportion of scored documents from the judgment set, calculated as the number of documents with scores divided by the total number of documents. + + +- `Precision@k`: The proportion of documents with nonzero judgment scores out of k (or out of the total number of returned documents, if lower). + +- `MAP@k`: The Mean Average Precision, which calculates the average precision across all documents. For more information, see [Average precision](https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision). + +- `NDCG@k`: The Normalized Discounted Cumulative Gain, which compares the actual ranking of results against a perfect ranking, with higher weights given to top results. This measures the quality of result ordering. + +To review these results visually, see [Exploring search evaluation results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/explore-experiment-results/). + +To schedule automatic evaluations, see [Monitoring search quality]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/regularly-scheduled-experiments/). diff --git a/_search-plugins/search-relevance/experiments.md b/_search-plugins/search-relevance/experiments.md new file mode 100644 index 00000000..068e4629 --- /dev/null +++ b/_search-plugins/search-relevance/experiments.md @@ -0,0 +1,400 @@ +--- +layout: default +title: Experiments +nav_order: 9 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +has_toc: false +--- + +# Experiments + +An _experiment_ is a controlled test designed to assess the effectiveness, relevance, or performance of a search engine or its algorithms. These experiments are typically conducted in order to evaluate how well a search system delivers useful results for specific queries. + +Search Relevance Workbench offers multiple types of experiments. For more information, see [Available search result quality experiments]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/#available-search-result-quality-experiments). + +## Creating experiments + +You can create an experiment to test search configurations using the following API. + +### Endpoint + +```json +POST _plugins/_search_relevance/experiment +``` + +### Request body fields + +The following table lists the available request body fields. + +Field | Data type | Description +:--- | :--- | :--- +`name` | String | The name of the experiment. +`description` | String | A description of the experiment. +`type` | String | The experiment type. Valid values are `PAIRWISE_COMPARISON`, `POINTWISE_EVALUATION`, and `HYBRID_OPTIMIZER`. +`querySetId` | String | The ID of the query set to use in the experiment. +`searchConfigurationList` | Array | A list of search configuration IDs to use in the experiment. +`judgmentList` | Array | A list of judgment IDs to use for evaluation. Optional. +`size` | Integer | The number of results to retrieve for each query. Default is `10`. +`isScheduled` | Boolean | Whether the experiment is scheduled to run periodically. Default is `false`. + +### Example request + +```json +POST _plugins/_search_relevance/experiment +{ + "type": "PAIRWISE_COMPARISON", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1", + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e", + "050b8c98-ba63-4c75-89cb-75f379b0d66e" + ], + "size": 10 +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "experiment_id": "1777a6e8-1dcc-4e23-be4a-9ee27586c0fd", + "experiment_result": "CREATED" +} +``` + +## Managing experiments + +You can retrieve or delete experiments using the following APIs. + +### View an experiment + +You can retrieve an experiment using the experiment ID. + +#### Endpoint + +```json +GET _plugins/_search_relevance/experiments/{experiment_id} +``` + +### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `experiment_id` | String | The ID of the experiment to retrieve. | + +#### Example request + +```json +GET _plugins/_search_relevance/experiments/b54f791a-3b02-49cb-a06c-46ab650b2ade +``` +{% include copy-curl.html %} + +#### Example response + +<details open markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "_score": 1, + "_source": { + "id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "timestamp": "2026-01-28T18:16:44.548Z", + "type": "PAIRWISE_COMPARISON", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1", + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e", + "050b8c98-ba63-4c75-89cb-75f379b0d66e" + ], + "judgmentList": [], + "size": 10, + "isScheduled": false, + "scheduledExperimentJobId": null, + "results": [ + { + "snapshots": [ + { + "searchConfigurationId": "85f31a87-2833-4d4a-89d2-cc83248f410e", + "docIds": [ + "B07K1H1G3M", + "B07THVCJK3", + "B07FPP6TB5", + "B07Q7Z9DJ3", + "B07PYPCX21", + "B07WLRKCNW", + "B01HE1IVNA", + "B07ZKDVHFB", + "B071D41YC3", + "B07B6L2QCF" + ] + }, + { + "searchConfigurationId": "050b8c98-ba63-4c75-89cb-75f379b0d66e", + "docIds": [ + "B07ZKDVHFB", + "B07FPP6TB5", + "B07THVCJK3", + "B071D41YC3", + "B07JD5RT4D", + "B079QHML21", + "B07ZZVX1F2", + "B07YNLBS7R", + "B01N1SSOUC", + "B07WLRKCNW" + ] + } + ], + "metrics": [ + { + "metric": "jaccard", + "value": 0.33 + }, + { + "metric": "rbo50", + "value": 0.14 + }, + { + "metric": "rbo90", + "value": 0.32 + }, + { + "metric": "frequencyWeighted", + "value": 0.5 + } + ], + "query_text": "tv" + }, + { + "snapshots": [ + { + "searchConfigurationId": "85f31a87-2833-4d4a-89d2-cc83248f410e", + "docIds": [ + "B07THVCJK3", + "B07FPP6TB5", + "B07PP4882Q", + "B07K1H1G3M", + "B091KB3W63", + "B07JN28KP3", + "B07Q7SGS6Z", + "B07SJZ9X6J", + "B07VNG9ZLM", + "B00DTOAWZ2" + ] + }, + { + "searchConfigurationId": "050b8c98-ba63-4c75-89cb-75f379b0d66e", + "docIds": [ + "B07THVCJK3", + "B091KB3W63", + "B07PP4882Q", + "B07RFFJ7YL", + "B08HGQ7H8F", + "B083BNQYBP", + "B07ZKDVHFB", + "B07N1CMGQQ", + "B07FPP6TB5", + "B071D41YC3" + ] + } + ], + "metrics": [ + { + "metric": "jaccard", + "value": 0.25 + }, + { + "metric": "rbo50", + "value": 0.77 + }, + { + "metric": "rbo90", + "value": 0.58 + }, + { + "metric": "frequencyWeighted", + "value": 0.4 + } + ], + "query_text": "led tv" + } + ] + } + } + ] + } +} +``` + +</details> + +### Delete an experiment + +You can delete an experiment using the experiment ID. + +#### Endpoint + +```json +DELETE _plugins/_search_relevance/experiments/{experiment_id} +``` + +#### Example request + +```json +DELETE _plugins/_search_relevance/experiments/47cc3861-c37b-43cc-99c4 +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_index": ".plugins-search-relevance-experiment", + "_id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "_version": 3, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 1 +} +``` + +### Search for an experiment + +You can search for available experiments using query domain-specific language (DSL). By default, the `results` data is not returned in the response. To include the `results` data, specify the `_source` field in the query. + +#### Endpoints + +```json +GET _plugins/_search_relevance/experiments/_search +POST _plugins/_search_relevance/experiments/_search +``` + +#### Example request + +Search for experiments that use a specific query set in order to measure search relevance performance: + +```json +GET _plugins/_search_relevance/experiments/_search +{ + "query": { + "term": { "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" } + } +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "_score": 1, + "_source": { + "judgmentList": [], + "size": 10, + "scheduledExperimentJobId": null, + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e", + "050b8c98-ba63-4c75-89cb-75f379b0d66e" + ], + "isScheduled": false, + "id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "type": "PAIRWISE_COMPARISON", + "timestamp": "2026-01-28T18:16:44.548Z", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" + } + }, + { + "_index": ".plugins-search-relevance-experiment", + "_id": "90e4a31b-3b4a-4b2e-b492-0399358961cc", + "_score": 1, + "_source": { + "judgmentList": [ + "505d00cf-2fce-422b-bb97-2e3a95ce9446" + ], + "size": 8, + "scheduledExperimentJobId": null, + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e" + ], + "isScheduled": false, + "id": "90e4a31b-3b4a-4b2e-b492-0399358961cc", + "type": "POINTWISE_EVALUATION", + "timestamp": "2026-01-28T18:16:45.696Z", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" + } + }, + { + "_index": ".plugins-search-relevance-experiment", + "_id": "71608f58-4827-4cd3-b6a6-61a527975a23", + "_score": 1, + "_source": { + "judgmentList": [ + "505d00cf-2fce-422b-bb97-2e3a95ce9446" + ], + "size": 10, + "scheduledExperimentJobId": null, + "searchConfigurationList": [ + "97f5b450-9571-469d-9dbb-347f94d164ba" + ], + "isScheduled": false, + "id": "71608f58-4827-4cd3-b6a6-61a527975a23", + "type": "HYBRID_OPTIMIZER", + "timestamp": "2026-01-28T18:17:00.811Z", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" + } + } + ] + } +} +``` diff --git a/_search-plugins/search-relevance/explore-experiment-results.md b/_search-plugins/search-relevance/explore-experiment-results.md new file mode 100644 index 00000000..a6a25392 --- /dev/null +++ b/_search-plugins/search-relevance/explore-experiment-results.md @@ -0,0 +1,71 @@ +--- +layout: default +title: Exploring search evaluation results +nav_order: 65 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Exploring search evaluation results +**Introduced 3.2** +{: .label .label-purple } + +In addition to retrieving the experiment results using the API, you can explore the results visually. The Search Relevance Workbench comes with dashboards that you can install to review search evaluation and hybrid search optimization experiment results. + +## Installing the dashboards + +You can install the dashboards in one of the following ways: + +* In the **Actions** column, select a visualization icon in the experiment overview. + +* Select the **Install Dashboards** button in the upper-right corner of the experiment overview. + +![Experiment overview of the Search Relevance Workbench including dashboard installation options]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/experiment_overview_dashboard_installation_options.png) + +The modal offers to install the dashboards for the user. + +![Modal to install dashboards]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/install_dashboards_modal.png) + +## Using the dashboards + +Once you install the dashboards, in the **Actions** column, select the visualization icon in the experiment overview. This opens the experiment result dashboard. The view presented depends on the type of experiment you chose: + +* The search evaluation dashboard focuses on the individual query level and provides insights about well-performing queries and queries with open relevance potential. + +* The hybrid search dashboard provides an overview of how the different hybrid search parameter configurations performed and lets you identify candidate queries for further exploration and experimentation. + +### Search evaluation dashboard + +The search evaluation dashboard, shown in the following image, aggregates performance metrics across all queries in your selected experiment. Use the search evaluation dashboard to get a high-level view of overall experiment performance and identify the queries that need attention. + +![Search evaluation dashboard with visualizations]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/search_evaluation_dashboard.png) + +The **Deep Dive Summary** panel shows the aggregate metrics for NDCG, MAP, precision, and coverage (see [Evaluating search quality]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/)). + +The **Deep Dive Query Scores** pane shows individual query performance ranked by NDCG score (highest to lowest). Use this pane to identify your best- and worst-performing queries. + +The **Deep Dive Score Densities** pane shows how metric values are distributed across your query set. Use this pane to understand whether poor performance is widespread or concentrated in specific queries. The x-axis shows metric values, while the y-axis shows how frequently those values occur. + +The **Deep Dive Score Scatter Plot** pane shows an interactive view of the preceding distribution data, with each query shown as a separate point. Use this pane to investigate specific queries at performance extremes. Points are scattered vertically to prevent overlap while maintaining the same x-axis metric values as the preceding distribution view. + +### Hybrid search evaluation dashboard + +Use the hybrid search evaluation dashboard, shown in the following image, to compare experiment variants and identify the optimal parameter configurations for your hybrid experiment. + +![Hybrid search optimization evaluation dashboard with visualizations]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/hybrid_search_optimizer_dashboard.png) + +The **Variant Performance Chart** shows your experiment variants arranged visually from best to worst performing (left to right, by decreasing NDCG). Use this chart to quickly identify your top-performing queries and view performance patterns across different parameter combinations at a glance. + +The **Variant Performance** pane shows the same variant data in a sortable table format with all metrics visible. Use this pane to compare specific metric values across variants and customize your analysis by sorting on different performance measures. To sort by a column, select the column header. + + +### Customizing the dashboards + +The dashboards are installed as saved objects. After installing them, you can edit the dashboards or clone and customize them to your specific requirements. + +To learn how to customize the source files, see [Updating the default dashboards](https://github.com/opensearch-project/dashboards-search-relevance/blob/main/DEVELOPER_GUIDE.md#updating-default-dashboards). + +### Resetting dashboards + +To reset the dashboards, select the **Install Dashboards** button in the upper-right corner of the experiment overview. This will reinstall the dashboards. diff --git a/_search-plugins/search-relevance/index.md b/_search-plugins/search-relevance/index.md index f0c5a2e4..c7e2ac6d 100644 --- a/_search-plugins/search-relevance/index.md +++ b/_search-plugins/search-relevance/index.md @@ -1,21 +1,43 @@ --- layout: default -title: Search relevance -nav_order: 80 +title: Optimizing search quality +nav_order: 75 has_children: true has_toc: false redirect_from: - /search-plugins/search-relevance/ --- -# Search relevance +# Optimizing search quality -Search relevance evaluates the accuracy of the search results returned by a query. The higher the relevance, the better the search engine. +_Search quality_ refers to how well search results match user intent and expectations. OpenSearch provides several features and tools to help you measure, analyze, and improve the quality of your search results. -OpenSearch provides the following search relevance features: +OpenSearch offers the following features to help you optimize search quality: -- [Comparing search results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-search-results/) from two queries side by side in OpenSearch Dashboards. +- **[User Behavior Insights (UBI)]({{site.url}}{{site.baseurl}}/search-plugins/ubi/)**: Capture and analyze user behavior data to understand how users interact with search results and identify areas for improvement. -- [Reranking search results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/reranking-search-results/) using a cross-encoder reranker. +- **[Search Relevance Workbench]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/)**: A comprehensive suite of tools for experimenting with and improving search relevance through query comparison, result evaluation, and A/B testing. -- Rewriting queries using [Querqy]({{site.url}}{{site.baseurl}}/search-plugins/querqy/). \ No newline at end of file +- **[Relevance agent]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/relevance-agent/)**: A specialized agent designed to continuously improve search relevance. + +- **[Query rewriting]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/query-rewriting/)**: Transform user queries to improve search accuracy and handle synonyms, misspellings, and other query variations. + +- **[Learning to Rank (LTR)]({{site.url}}{{site.baseurl}}/search-plugins/ltr/)**: Use machine learning models trained on behavioral data to improve the ranking of search results. + +- **[Reranking search results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/reranking-search-results/)**: Apply machine learning models to reorder search results for improved relevance. + +## Search quality workflow + +A typical search quality improvement workflow involves: + +1. **Data collection**: Use UBI to capture user behavior and interaction data. +2. **Analysis**: Analyze user behavior patterns to identify search quality issues. +3. **Experimentation**: Use the Search Relevance Workbench to test different approaches. +4. **Model training**: Train LTR models using behavioral data to improve ranking. +5. **Query enhancement**: Apply query rewriting rules to improve query understanding. +6. **Reranking**: Apply ML-based reranking to further optimize results. +7. **Evaluation**: Continuously monitor and evaluate search performance. + +## Related documentation + +- [Reranking search results tutorials]({{site.url}}{{site.baseurl}}/tutorials/reranking/): Learn how to implement search result reranking using various machine learning models and platforms. diff --git a/_search-plugins/search-relevance/judgments.md b/_search-plugins/search-relevance/judgments.md new file mode 100644 index 00000000..8dce04fc --- /dev/null +++ b/_search-plugins/search-relevance/judgments.md @@ -0,0 +1,596 @@ +--- +layout: default +title: Judgments +nav_order: 8 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Judgments + +A judgment is a relevance rating assigned to a specific document in the context of a particular query. Multiple judgments are grouped together into judgment lists. +Typically, judgments are categorized as two types---implicit and explicit: + +- Implicit judgments are ratings derived from user behavior (for example, what did the user see and select after searching?). +- Humans have traditionally produced explicit judgments, but large language models (LLMs) are increasingly used for this task. + +Search Relevance Workbench (SRW) supports all types of judgments: + +- Using LLMs as automated judges (an approach known as LLM-as-a-Judge) to generate judgments by evaluating search results using a prompt. +- Generating implicit judgments based on data that adheres to the User Behavior Insights (UBI) schema specification. +- Importing judgments that were collected using a process outside of SRW. + +## Using LLM-as-a-Judge + +Generate explicit judgments with an LLM in SRW when you don't have human annotators available, or you need to scale up the number of judgments beyond what humans can provide. + +For step-by-step instructions, see [Using LLM-as-a-Judge for search relevance]({{site.url}}{{site.baseurl}}/tutorials/llm-as-a-judge-tutorial/). + +### Prerequisites + +To use LLM-as-a-Judge, configure the following components: + +- A connector to an LLM to use for generating the judgments. For more information, see [Connectors]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). +- A query set: Together with the `size` parameter, the query set defines the scope for generating judgments. For each query, the top k documents are retrieved from the specified index, in which k is defined by the `size` parameter. +- A search configuration: A search configuration defines how documents are retrieved for use in query-document pairs. + +The AI-assisted judgment process consists of the following steps: + +- For each query, the top k documents are retrieved using the defined search configuration, which includes the index information. The query and each document from the result list create a query-document pair. +- The LLM is then called with a predefined prompt to generate a judgment for each query-document pair. +- All generated judgments are stored in the judgment list. + +To create a judgment list, provide the model ID of the LLM, an available query set, and a created search configuration. + +The following example uses a generic prompt template with a scale of 0.0 to 1.0. To reduce the volume of data sent to the LLM (and therefore the cost), use the `contextFields` parameter to specify which fields from each result to include: + +```json +PUT _plugins/_search_relevance/judgments +{ + "name":"AI-assisted judgment list", + "description": "Uses gpt-4o-mini to evaluate product search results", + "type":"LLM_JUDGMENT", + "modelId":"N8AE1osB0jLkkocYjz7D", + "querySetId":"5f0115ad-94b9-403a-912f-3e762870ccf6", + "searchConfigurationList":["2f90d4fd-bd5e-450f-95bb-eabe4a740bd1"], + "size":5, + "contextFields": ["title", "description", "category"], + "llmJudgmentRatingType": "SCORE0_1", + "promptTemplate": "Rate the relevance of these search results {% raw %}{{hits}}{% endraw %} for the query '{% raw %}{{queryText}}{% endraw %}' on a scale of 0-1, where 0 is completely irrelevant and 1 is perfectly relevant. Consider the product title, description, and category." +} +``` +{% include copy-curl.html %} + +### Request body fields + +The following table lists the parameters for creating LLM-based judgments. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `name` | String | The name of the judgment list. | +| `description` | String | Optional. A description of the judgment list. | +| `type` | String | Set to `LLM_JUDGMENT`. | +| `modelId` | String | The ID of the deployed machine learning (ML) model to use for generating judgments. Must be a remote model connected to an external LLM service. | +| `querySetId` | String | The ID of the query set containing the queries to evaluate. | +| `searchConfigurationList` | Array of strings | The list of search configuration IDs to use for retrieving documents to evaluate. | +| `size` | Integer | The number of top documents to retrieve and evaluate for each query. Default is `10`. | +| `tokenLimit` | Integer | The maximum number of tokens to send to the LLM in a single request. Used to batch documents when the total content exceeds this limit. Default is `4,000`. | +| `contextFields` | Array of strings | Optional. Specifies which document fields to include when sending content to the LLM. If not specified, the entire document source is sent. Use this parameter to reduce costs and focus the LLM on relevant fields. | +| `ignoreFailure` | Boolean | Whether to continue processing other documents if the LLM fails to generate a judgment for some documents. Default is `false`. | +| `llmJudgmentRatingType` | String | The type of rating scale to use. Valid values are `SCORE0_1` (numeric scale 0--1) and `RELEVANT_IRRELEVANT` (binary relevant/irrelevant). Use `SCORE0_1` for graded relevance metrics such as NDCG. Use `RELEVANT_IRRELEVANT` for binary metrics such as precision and recall. | +| `promptTemplate` | String | Optional. A custom prompt template for the LLM. Supports {% raw %}`{{queryText}}`{% endraw %} and {% raw %}`{{hits}}`{% endraw %} placeholders. If not provided, the default template is used. | +| `existingJudgments` | Array of strings | Optional. A list of up to 5 existing judgment IDs whose ratings are reused. For each query-document pair, SRW checks these judgments in order, using the rating from the first match found. Only pairs without an existing rating in any of these judgments are sent to the LLM for evaluation. | +| `overwriteCache` | Boolean | Optional. Deprecated. Accepted but ignored. The global judgment cache has been removed. | + +### Retrying failed judgment requests + +Generating a judgment sends one LLM request for every query-document pair. Occasional failures are expected at scale: for example, the provider might throttle a request or a request might time out. To retry these requests automatically, configure retries on the connector you use for the judgment, using the connector's `client_config` settings (`max_retry_times`, `retry_backoff_policy`, and related options). For more information, see [The client_config object]({{site.url}}{{site.baseurl}}/ml-commons-plugin/api/connector-apis/create-connector/#the-client_config-object). + +### Retrying failed documents + +This section applies only to `LLM_JUDGMENT` lists. + +A judgment list can finish with a `status` of `COMPLETED` even if some documents didn't receive a rating, for example because the LLM provider throttled or timed out on those requests. Unrated documents appear in each query's `failures` array, and the run's overall counts appear in the judgment list's `metadata` field, as shown in [Viewing a judgment list](#viewing-a-judgment-list). Rather than regenerating the entire judgment list, you can retry only the documents that failed by sending a `POST` request to the `_retry` endpoint with the judgment list's ID. + +#### Endpoint + +```json +POST _plugins/_search_relevance/judgments/{judgment_list_id}/_retry +``` + +#### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `judgment_list_id` | String | The ID of the judgment list whose failed documents you want to retry. | + +#### Example request + +```json +POST _plugins/_search_relevance/judgments/b54f791a-3b02-49cb-a06c-46ab650b2ade/_retry +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "judgment_id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "status": "RETRYING", + "message": "Retrying failed documents" +} +``` + +The retry runs asynchronously and generates new ratings for only the previously failed documents; ratings that already succeeded are left unchanged. The response returns immediately with a `status` of `RETRYING`. To track progress, retrieve the judgment list and check its `status`, as described in [Viewing a judgment list](#viewing-a-judgment-list). If individual documents still fail to get rated (for example, because the LLM provider is still throttling requests), the judgment list's `status` returns to `COMPLETED`---check the `failures` array and `metadata` field to see which documents are still unrated. If the retry process itself fails (for example, due to an internal error), the judgment list's `status` becomes `ERROR`. + +#### Status values + +The following table lists the possible `status` values for a judgment list. + +| Status | Description | +| :--- | :--- | +| `PROCESSING` | The judgment list is being generated. | +| `COMPLETED` | Generation (or a retry) has finished. Some documents may still be unrated: check the `failures` array and `metadata` field to verify the document ratings. | +| `RETRYING` | A retry of previously failed documents is in progress. | +| `ERROR` | The retry process itself failed internally. This is separate from individual documents failing to get rated, which still results in a `COMPLETED` status. | + +### Custom prompt templates + +You can customize the prompt template to focus on specific aspects of relevance: + +```json +PUT /_plugins/_search_relevance/judgments +{ + "name": "Custom Prompt Judgment", + "type": "LLM_JUDGMENT", + "modelId": "MODEL_ID_HERE", + "querySetId": "QUERY_SET_ID_HERE", + "searchConfigurationList": ["SEARCH_CONFIGURATION_ID_HERE"], + "promptTemplate": "As an e-commerce search expert, evaluate how well these products {% raw %}{{hits}}{% endraw %} match the user's search for '{% raw %}{{queryText}}{% endraw %}'. Consider product relevance, brand reputation, and price competitiveness. Rate each result from 0-1.", + "llmJudgmentRatingType": "SCORE0_1" +} +``` +{% include copy-curl.html %} + +### Binary relevance judgments + +For simpler relevance assessment, you can use binary (relevant/irrelevant) judgments: + +```json +PUT /_plugins/_search_relevance/judgments +{ + "name": "Binary LLM Judgment", + "type": "LLM_JUDGMENT", + "modelId": "MODEL_ID_HERE", + "querySetId": "QUERY_SET_ID_HERE", + "searchConfigurationList": ["SEARCH_CONFIGURATION_ID_HERE"], + "llmJudgmentRatingType": "RELEVANT_IRRELEVANT", + "promptTemplate": "Determine if these search results {% raw %}{{hits}}{% endraw %} are relevant or irrelevant for the query '{% raw %}{{queryText}}{% endraw %}'. Consider exact matches and semantic relevance." +} +``` +{% include copy-curl.html %} + +### Using different LLM providers + +LLM-as-a-Judge works with any LLM provider to which you can connect using an [ML Commons connector]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/connectors/). Blueprints are available for OpenAI, Azure OpenAI, DeepSeek, Ollama, Google Gemini, and Amazon Bedrock. For more information, see [OpenSearch-provided connector blueprints]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/supported-connectors/#llm-judgment-blueprints-for-search-relevance-workbench). + +#### Amazon Bedrock example + +The following example creates a connector for an Anthropic Claude model on Amazon Bedrock: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Amazon Bedrock Anthropic Claude", + "description": "Anthropic Claude via Bedrock for SRW LLM judgments", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<YOUR AWS ACCESS KEY>", + "secret_key": "<YOUR AWS SECRET KEY>" + }, + "parameters": { + "region": "<YOUR AWS REGION>", // example: us-east-1 + "service_name": "bedrock", + "anthropic_version": "bedrock-2023-05-31", + "max_tokens": 8000, + "model": "<INFERENCE_PROFILE_ID>" // example: us.anthropic.claude-haiku-4-5-20251001-v1:0 + }, + "client_config": { + "max_retry_times": 3, + "retry_backoff_policy": "exponential_full_jitter" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/invoke", + "request_body": "{\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens},\"system\":\"${parameters.system_prompt}\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.user_prompt}\"}]}]}", + "post_process_function": "def text = params.content[0].text; return '{\"name\":\"response\",\"dataAsMap\":{\"response\":\"' + escape(text) + '\"}}'" + } + ] +} +``` +{% include copy-curl.html %} + +## Implicit judgments + +Implicit judgments are derived from past user interactions. SRW supports the Clicks Over Expected Clicks (COEC) click model, which uses *impression* and *click* signals to calculate judgments. + +Input data must follow the [UBI index schemas]({{site.url}}{{site.baseurl}}/search-plugins/ubi/schemas/). COEC uses every event in the `ubi_events` index with an `action_name` of `impression` or `click`. Use the `ubiEventsIndex` parameter to read from a differently named index. + +COEC calculates an expected click-through rate (CTR) for each rank by dividing the total number of clicks by the total number of impressions observed at that rank, based on all events in `ubi_events`. This ratio represents the expected CTR for that position. + +For each document displayed in a hit list after a query, the average CTR at that rank serves as the expected value for the query-document pair. COEC calculates the actual CTR for the query-document pair and divides it by this expected rank-based CTR. Consequently, query-document pairs with a higher CTR than the average for that rank have a judgment value greater than 1. Conversely, if the CTR is lower than average, the judgment value is lower than 1. + +Depending on the tracking implementation, multiple clicks for a single query can be recorded in the `ubi_events` index. Consequently, the average CTR can sometimes exceed 1 (or 100%). +{: .note} + +For query-document observations that occur at different positions, all impressions and clicks are assumed to have occurred at the lowest (best) position. This aggregation approach biases the final judgment toward lower values, reflecting the common trend that higher-ranked results typically receive higher CTRs. +{: .note} + +### Example request + +The following example creates an implicit judgment list using the COEC click model: + +```json +PUT _plugins/_search_relevance/judgments +{ + "name": "Implicit Judgments", + "clickModel": "coec", + "type": "UBI_JUDGMENT", + "maxRank": 20 +} +``` +{% include copy-curl.html %} + +### Request body fields + +The following table lists the parameters for creating implicit judgments. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `name` | String | The name of the judgment list. | +| `clickModel` | String | The model used to calculate implicit judgments. Only `coec` (Clicks Over Expected Clicks) is supported. | +| `type` | String | Set to `UBI_JUDGMENT`. | +| `maxRank` | Integer | The maximum rank to consider when including events in the judgment calculation. | +| `startDate` | Date | An optional starting date from which behavioral data events are considered for implicit judgment generation. The format is `yyyy-MM-dd`. | +| `endDate` | Date | An optional end date until which behavioral data events are considered for implicit judgment generation. The format is `yyyy-MM-dd`. | +| `ubiEventsIndex` | String | An optional name of the index containing the UBI events to analyze. Default is `ubi_events`. Specify this parameter when your UBI events are stored in an index with a different name. | + +## Importing judgments + +You may already have external processes for generating judgments. Regardless of the judgment type or the way they were generated, you can import them into SRW. + +### Example request + +The following example imports a set of judgments for two queries: + +```json +PUT _plugins/_search_relevance/judgments +{ + "name": "Imported Judgments", + "description": "Judgments generated outside SRW", + "type": "IMPORT_JUDGMENT", + "judgmentRatings": [ + { + "query": "red dress", + "ratings": [ + { + "docId": "B077ZJXCTS", + "rating": "3.000" + }, + { + "docId": "B071S6LTJJ", + "rating": "2.000" + }, + { + "docId": "B01IDSPDJI", + "rating": "2.000" + }, + { + "docId": "B07QRCGL3G", + "rating": "0.000" + }, + { + "docId": "B074V6Q1DR", + "rating": "1.000" + } + ] + }, + { + "query": "blue jeans", + "ratings": [ + { + "docId": "B07L9V4Y98", + "rating": "0.000" + }, + { + "docId": "B01N0DSRJC", + "rating": "1.000" + }, + { + "docId": "B001CRAWCQ", + "rating": "1.000" + }, + { + "docId": "B075DGJZRM", + "rating": "2.000" + }, + { + "docId": "B009ZD297U", + "rating": "2.000" + } + ] + } + ] +} +``` +{% include copy-curl.html %} + +### Request body fields + +The following table lists the parameters for importing judgments. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `name` | String | The name of the judgment list. | +| `description` | String | An optional description of the judgment list. | +| `type` | String | Set to `IMPORT_JUDGMENT`. | +| `judgmentRatings` | Array | A list of JSON objects containing the judgments. Judgments are grouped by query, each containing a nested map in which document IDs (`docId`) serve as keys and their floating-point ratings serve as values. | + +## Managing judgment lists + +You can retrieve or delete judgment lists using the following APIs. + +### Viewing a judgment list + +Retrieve a judgment list by its ID. + +#### Endpoint + +```json +GET _plugins/_search_relevance/judgments/{judgment_list_id} +``` + +#### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `judgment_list_id` | String | The ID of the judgment list to retrieve. | + +#### Example request + +```json +GET _plugins/_search_relevance/judgments/b54f791a-3b02-49cb-a06c-46ab650b2ade +``` +{% include copy-curl.html %} + +#### Example response + +<details open markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 36, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "search-relevance-judgment", + "_id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "_score": 1, + "_source": { + "id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "timestamp": "2025-06-11T06:07:23.766Z", + "name": "LLM Judgments", + "status": "COMPLETED", + "type": "LLM_JUDGMENT", + "metadata": { + "totalQueries": 2, + "successfulQueries": 1, + "failedQueries": 1, + "lastFailureReason": "Rate limit exceeded" + }, + "judgmentRatings": [ + { + "query": "red dress", + "ratings": [ + { + "rating": "3.000", + "docId": "B077ZJXCTS" + }, + { + "rating": "2.000", + "docId": "B071S6LTJJ" + }, + { + "rating": "0.000", + "docId": "B07QRCGL3G" + }, + { + "rating": "1.000", + "docId": "B074V6Q1DR" + } + ], + "failures": [ + { + "docId": "B01IDSPDJI" + } + ] + }, + { + "query": "blue jeans", + "ratings": [ + { + "rating": "0.000", + "docId": "B07L9V4Y98" + }, + { + "rating": "1.000", + "docId": "B01N0DSRJC" + }, + { + "rating": "1.000", + "docId": "B001CRAWCQ" + }, + { + "rating": "2.000", + "docId": "B075DGJZRM" + }, + { + "rating": "2.000", + "docId": "B009ZD297U" + } + ] + } + ] + } + } + ] + } +} +``` + +</details> + +Unrated documents appear in each query's `failures` array. The run's overall counts appear in the judgment list's `metadata` field. To retry only the failed documents in an `LLM_JUDGMENT` list, see [Retrying failed documents](#retrying-failed-documents). + +### Deleting a judgment list + +Delete a judgment list by its ID. + +#### Endpoint + +```json +DELETE _plugins/_search_relevance/judgments/{judgment_list_id} +``` + +#### Example request + +```json +DELETE _plugins/_search_relevance/judgments/b54f791a-3b02-49cb-a06c-46ab650b2ade +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_index": "search-relevance-judgment", + "_id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "_version": 3, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 156, + "_primary_term": 1 +} +``` + +### Searching for a judgment list + +Search for judgment lists using query domain-specific language (DSL). The response excludes `judgmentRatings.ratings` by default; to include it, specify the `_source` field in the query. + +#### Endpoints + +```json +GET _plugins/_search_relevance/judgments/_search +POST _plugins/_search_relevance/judgments/_search +``` + +#### Example request + +The following example searches for judgment lists that include the exact query `red dress`: + +```json +GET _plugins/_search_relevance/judgments/_search +{ + "query": { + "nested": { + "path": "judgmentRatings", + "query": { + "match_phrase": { + "judgmentRatings.query": "red dress" + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "took": 29, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 4.5558767, + "hits": [ + { + "_index": "search-relevance-judgment", + "_id": "505d00cf-2fce-422b-bb97-2e3a95ce9446", + "_score": 4.5558767, + "_source": { + "metadata": {}, + "name": "Imported Judgments", + "judgmentRatings": [ + { + "query": "red dress" + }, + { + "query": "blue jeans" + } + ], + "id": "505d00cf-2fce-422b-bb97-2e3a95ce9446", + "type": "IMPORT_JUDGMENT", + "timestamp": "2026-01-28T18:16:44.218Z", + "status": "COMPLETED" + } + } + ] + } +} +``` + +## Related documentation + +- [Using LLM-as-a-Judge for search relevance]({{site.url}}{{site.baseurl}}/tutorials/llm-as-a-judge-tutorial/) \ No newline at end of file diff --git a/_search-plugins/search-relevance/optimize-hybrid-search.md b/_search-plugins/search-relevance/optimize-hybrid-search.md new file mode 100644 index 00000000..96816463 --- /dev/null +++ b/_search-plugins/search-relevance/optimize-hybrid-search.md @@ -0,0 +1,116 @@ +--- +layout: default +title: Optimizing hybrid search +nav_order: 60 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Optimizing hybrid search + +A key challenge of using hybrid search in OpenSearch is combining results from lexical and vector-based search effectively. OpenSearch provides different techniques and various parameters you can experiment with to find the best setup for your application. What works best, however, depends heavily on your data, user behavior, and application domain—there is no one-size-fits-all solution. + +Search Relevance Workbench helps you systematically find the ideal set of parameters for your needs. + +## Requirements + +Internally, optimizing hybrid search involves running multiple search quality evaluation experiments. For these experiments, you need a query set, judgments, and a search configuration. +Search Relevance Workbench supports hybrid search optimization with exactly two query clauses. While hybrid search typically combines vector and lexical queries, you can run hybrid search optimization with two lexical query clauses: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "hybrid_query_lexical", + "query": "{\"query\":{\"hybrid\":{\"queries\":[{\"match\":{\"title\":\"%queryText%\"}},{\"match\":{\"category\":\"%queryText%\"}}]}}}", + "index": "ecommerce" +} +``` +{% include copy-curl.html %} + +Hybrid search optimization is most valuable when combining lexical and vector-based search results. For optimal results, configure your hybrid search query with two clauses: one textual query clause and one neural query clause. You don't need to configure the search pipeline to combine results because the hybrid search optimization process handles this automatically. The following is an example of a search configuration suitable for hybrid search optimization: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "hybrid_query_text", + "query": "{\"query\":{\"hybrid\":{\"queries\":[{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title\",\"category\",\"bullets\",\"description\",\"attrs.Brand\\\",\"attrs.Color\"]}},{\"neural\":{\"title_embedding\":{\"query_text\":\"%queryText%\",\"k\":100,\"model_id\":\"lRFFb5cBHkapxdNcFFkP\"}}}]}},\"size\":10}", + "index": "ecommerce" +} +``` +{% include copy-curl.html %} + +The model ID specified in the `query` must be a valid model ID for a model deployed in OpenSearch. The target index must contain the field that stores the embeddings (in this example, `title_embedding`). + +For an end-to-end example, see the [`search-relevance` repository](https://github.com/opensearch-project/search-relevance). + +## Running a hybrid search optimization experiment + +You can create a hybrid search optimization experiment by calling the Search Relevance Workbench `experiments` endpoint. + +### Endpoint + +```json +PUT _plugins/_search_relevance/experiments +``` + +### Example request + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "b16a6a2b-ed6e-49af-bb2b-fc739dcf24e6", + "searchConfigurationList": ["508a8812-27c9-45fc-999a-05f859f9b210"], + "judgmentList": ["1b944d40-e95a-43f6-9e92-9ce00f70de79"], + "size": 10, + "type": "HYBRID_OPTIMIZER" +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "experiment_id": "0f4eff05-fd14-4e85-ab5e-e8e484cdac73", + "experiment_result": "CREATED" +} +``` + +## Experimentation process + +The hybrid search optimization experiment evaluates all combinations of the following parameter variants for each query in the query set and scores the results against the judgment list: + +- Score-based variants: + - Normalization techniques: `l2`, `min_max`, and `z_score`. The `z_score` technique can be combined only with `arithmetic_mean` because of a [normalization processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/#request-body-fields) restriction. + - Combination techniques: `arithmetic_mean`, `harmonic_mean`, and `geometric_mean`. + - Lexical and vector search weights ranging from `0.0` to `1.0`, in `0.1` increments. + +- Rank-based variants: + - The `rrf` ([Reciprocal Rank Fusion (RRF)]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/score-ranker-processor/)) combination technique, evaluated using `rank_constant` values of `1`, `5`, `10`, `20`, and `60`. RRF variants use equal weights in all subqueries. + +## Evaluating the results + +The results for each evaluation are stored. You can view the results in OpenSearch Dashboards by selecting the corresponding experiment in the overview of past experiments, as shown in the following image. + +![Compare search results]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/experiment_overview_hybrid_search_optimization.png) + +All executed queries and their calculated search metrics are displayed, as shown in the following image. + +![Compare search results]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/hybrid_search_optimization_query_overview.png) + +To view query variants, select one of the queries, as shown in the following image. + +![Compare search results]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/hybrid_search_optimization_variant_parameters.png) + +You can also retrieve this information by using the following SQL search statement and providing your `experimentId`: + +```json +POST _plugins/_sql +{ + "query": "SELECT ev.parameters.normalization, ev.parameters.combination, ev.parameters.weights, ev.results.evaluationResultId, ev.experimentId, er.id, er.metrics, er.searchText FROM search-relevance-experiment-variant ev JOIN search-relevance-evaluation-result er ON ev.results.evaluationResultId = er.id WHERE ev.experimentId = '814e2378-901c-4273-9873-9b758a33089d'" +} +``` +{% include copy-curl.html %} + +To review these results visually, see [Exploring search evaluation results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/explore-experiment-results/). diff --git a/_search-plugins/search-relevance/query-rewriting.md b/_search-plugins/search-relevance/query-rewriting.md new file mode 100644 index 00000000..d02d0a4e --- /dev/null +++ b/_search-plugins/search-relevance/query-rewriting.md @@ -0,0 +1,18 @@ +--- +layout: default +title: Query rewriting +parent: Optimizing search quality +has_children: true +nav_order: 30 +has_toc: false +--- + +# Query rewriting + +Query rewriting is the process of transforming or modifying a user query before it is executed. The goal of query rewriting is to improve search accuracy, relevance, or performance by addressing issues such as misspellings, synonyms, ambiguous terms, or inefficient query structure. Query rewriting is commonly used in search systems to enhance the quality of search results. + +You can perform query rewriting in OpenSearch using the following features: + +- [Template queries]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/template-query/): Create queries with dynamic placeholders that are resolved during query execution, useful for machine learning inference and runtime parameter generation. + +- [Querqy]({{site.url}}{{site.baseurl}}/search-plugins/querqy/): A community plugin for advanced query rewriting with rules for boosting, burying, filtering, and redirecting search results. diff --git a/_search-plugins/search-relevance/query-sets.md b/_search-plugins/search-relevance/query-sets.md new file mode 100644 index 00000000..62adf49d --- /dev/null +++ b/_search-plugins/search-relevance/query-sets.md @@ -0,0 +1,316 @@ +--- +layout: default +title: Query sets +nav_order: 3 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Query sets + +A query set is a collection of queries. These queries are used in experiments for search relevance evaluation. Search Relevance Workbench offers different sampling techniques for creating query sets from real user data that adheres to the [User Behavior Insights (UBI)]({{site.url}}{{site.baseurl}}/search-plugins/ubi/schemas/) specification. +Additionally, Search Relevance Workbench allows you to import a query set. + +## Creating query sets + +If you're tracking user behavior with the UBI specification, you can choose from different sampling methods that can create query sets based on real user queries stored in the `ubi_queries` index. Use the `ubiQueriesIndex` parameter to sample from a differently named index. + +Search Relevance Workbench supports three sampling methods: +* Random: Takes a random sample of all queries. +* [Probability-Proportional-to-Size Sampling](https://opensourceconnections.com/blog/2022/10/13/how-to-succeed-with-explicit-relevance-evaluation-using-probability-proportional-to-size-sampling/): Takes a frequency-weighted sample of all queries to obtain a representative sample. +* Top N: Takes the most frequent N queries. + +### Endpoint + +```json +POST _plugins/_search_relevance/query_sets +``` + +### Request body fields + +The following table lists the available input parameters. + +Field | Data type | Description +:--- | :--- | :--- +`name` | String | The name of the query set. The maximum length is 50 characters. +`description` | String | A short description of the query set. The maximum length is 250 characters. +`sampling` | String | Defines which sampler to use. Valid values are `pptss` (Probability-Proportional-to-Size-Sampling), `random`, `topn` (most frequent queries), and `manual`. +`querySetSize` | Integer | The target number of queries in the query set. Depending on the number of unique queries in `ubi_queries`, the resulting query set may contain fewer queries. Must be a positive integer. +`ubiQueriesIndex` | String | An optional name of the index containing the UBI queries to sample. Default is `ubi_queries`. Specify this parameter when your UBI queries are stored in an index with a different name. + +### Example request: Sampling 20 queries with the Top N sampler + +```json +POST _plugins/_search_relevance/query_sets +{ + "name": "Top 20", + "description": "Top 20 most frequent queries sourced from user searches.", + "sampling": "topn", + "querySetSize": 20 +} +``` + +### Example request: Uploading a query set manually + +```json +PUT _plugins/_search_relevance/query_sets +{ + "name": "TVs", + "description": "TV queries", + "sampling": "manual", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "led tv" + } + ] +} +``` + +## Query set formats + +Search Relevance Workbench supports two formats for query sets, each designed for different use cases. Both formats are a collection of user queries, but they differ in whether they include an expected answer. + +* **Basic query set**: A list of user queries without any additional information. This is useful for general relevance testing where no specific answer is expected. + +* **Query set with reference answers**: A list of user queries, in which each query is paired with its expected answer. This format is particularly useful for evaluating applications designed to provide a specific answer, such as question-answering systems. + +### Fields + +All query sets comprise one or more entries. Each entry is a JSON object containing the following fields. + +| Field | Data type | Description | +| :--- | :--- | :--- | +| `queryText` | String | The user query string. Required. | +| `referenceAnswer` | String | The expected or correct answer to the user query. This field is used for generating judgments, especially with large language models (LLMs). Optional. | +| Custom fields | String | Any field other than `queryText` and `referenceAnswer` is stored as a custom field in the entry. You can reference a custom field by its name as a [Mustache template variable]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/#using-mustache-templates) in a search configuration. Optional. | + +### Basic query set example + +A basic query set contains only the `queryText` field for each entry. It is suitable for general relevance tests where no single "correct" answer exists. + +#### Example query set without reference answers + +```json +{"queryText": "t towels kitchen"} +{"queryText": "table top bandsaw for metal"} +{"queryText": "tan strappy heels for women"} +{"queryText": "tank top plus size women"} +{"queryText": "tape and mudding tools"} +``` + +### Query set with reference answers example + +In this format, each entry pairs a `queryText` with a `referenceAnswer`. Use it to evaluate applications that return a specific answer, such as chatbots or question-answering systems. + +#### Example query set with reference answers + +```json +{"queryText": "What is the capital of France?", "referenceAnswer": "Paris"} +{"queryText": "Who wrote 'Romeo and Juliet'?", "referenceAnswer": "William Shakespeare"} +{"queryText": "What is the chemical symbol for water?", "referenceAnswer": "H2O"} +{"queryText": "What is the highest mountain in the world?", "referenceAnswer": "Mount Everest"} +{"queryText": "When was the first iPhone released?", "referenceAnswer": "June 29, 2007"} +``` + +The `referenceAnswer` field is particularly useful when using [LLMs to generate judgments]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/judgments/). The LLM can use the reference answer as a ground truth to compare against the retrieved search results, allowing it to accurately score the relevance of the response. + +### Query set with custom fields example + +In addition to `queryText`, each entry can include custom fields. You can reference these fields as Mustache template variables in a [search configuration]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/#using-mustache-templates) so that one search configuration applies different filters or parameters to each query. + +#### Example query set with custom fields + +In the following example, each entry includes a `category` custom field. If a search configuration references `{{category}}` in its query, it filters the results for each query by the `category` value in the corresponding entry: + +```json +{"queryText": "phone", "category": "electronics"} +{"queryText": "steel", "category": "materials"} +{"queryText": "keyboard", "category": "electronics"} +``` + +## Managing query sets + +You can retrieve or delete query sets using the following APIs. + +### Retrieve query sets + +This API retrieves available query sets. + +#### Endpoints + +```json +GET _plugins/_search_relevance/query_sets +GET _plugins/_search_relevance/query_sets/{query_set_id} +``` + +#### Example response + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "search-relevance-queryset", + "_id": "bb45c4c4-48ce-461b-acbc-f154c0a17ec9", + "_score": null, + "_source": { + "id": "bb45c4c4-48ce-461b-acbc-f154c0a17ec9", + "name": "TVs", + "description": "Some TVs that people might want", + "sampling": "manual", + "timestamp": "2025-06-11T13:43:26.676Z", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "led tv" + } + ] + }, + "sort": [ + 1749649406676 + ] + } + ] + } +} +``` + +### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `query_set_id` | String | The ID of the query set to retrieve. Retrieves all query sets when empty. | + +### Delete a query set + +You can delete a query set using the query set ID. + +#### Endpoint + +```json +DELETE _plugins/_search_relevance/query_sets/{query_set_id} +``` + +#### Example request + +```json +DELETE _plugins/_search_relevance/query_sets/bb45c4c4-48ce-461b-acbc-f154c0a17ec9 +``` + +#### Example response + +```json +{ + "_index": "search-relevance-queryset", + "_id": "bb45c4c4-48ce-461b-acbc-f154c0a17ec9", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 17, + "_primary_term": 1 +} +``` + +### Search for a query set + +You can search for available query sets using query DSL. + +#### Endpoints + +```json +GET _plugins/_search_relevance/query_sets/_search +POST _plugins/_search_relevance/query_sets/_search +``` + +#### Example request + +Search for query sets containing queries that include the phrase `lamp without cord`: + +```json +GET _plugins/_search_relevance/query_sets/_search +{ + "query": { + "nested": { + "path": "querySetQueries", + "query": { + "match_phrase": { + "querySetQueries.queryText": "lamp without cord" + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Example response + +The response contains the matching query set because `wall lamp without cord` contains the partial search term `lamp without cord`: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "search-relevance-queryset", + "_id": "4622775e-9099-4375-af7f-f970dae25f09", + "_score": 1, + "_source": { + "id": "4622775e-9099-4375-af7f-f970dae25f09", + "name": "ESCI Queries", + "description": "Queries from the ESCI ranking task", + "sampling": "manual", + "timestamp": "2026-01-20T12:49:35.940Z", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "wall lamp without cord" + } + ] + } + } + ] + } +} +``` diff --git a/_search-plugins/search-relevance/regularly-scheduled-experiments.md b/_search-plugins/search-relevance/regularly-scheduled-experiments.md new file mode 100644 index 00000000..6b8f8ce6 --- /dev/null +++ b/_search-plugins/search-relevance/regularly-scheduled-experiments.md @@ -0,0 +1,188 @@ +--- +layout: default +title: Monitoring search quality +nav_order: 70 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Monitoring search quality +**Introduced 3.4** +{: .label .label-purple } + +Search quality is not static. Even if your ranking algorithms remain unchanged, the indexed data evolves, signals such as popularity and recency fluctuate, and user queries shift over time. + +To detect and prevent unintended changes in relevance, you should monitor search quality on an ongoing basis. You can configure a cron schedule to run a search evaluation experiment at regular intervals. + + +Each job can have only one schedule. To modify the schedule, delete the existing schedule and create a new one. Deleting a schedule also removes its associated historical data. + +## Scheduling a search evaluation using Search Relevance Workbench + +After you successfully run a search evaluation for the first time, a clock icon appears that allows you to schedule the experiment, as shown in the following image. + +![Schedule a Experiment to Run]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/experiment_scheduled_icon.png) + +On the scheduling page, configure how frequently you want the experiment to run, as shown in the following image. + +![Setting the schedule of how often to run]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/experiment_scheduled_modal.png) + +### Evaluating search quality + +Once an experiment is scheduled, a new dashboard icon lets you monitor the search results over time. Because the dashboard evaluates results daily, it may take up to 24 hours for the data to populate and display meaningful insights. + +![Review search quality over time]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/experiment_scheduled_dashboard.png) + + +## Scheduling a search evaluation using the API + +You can create regularly scheduled experiments using the API. The experiment you are scheduling must already exist. + +### Endpoint + +```json +POST _plugins/_search_relevance/experiments/schedule +``` + +### Request body fields + +The following table lists the available input parameters. + +Field | Data type | Description +:--- | :--- | :--- +`experimentId` | String | The experiment ID to rerun. +`cronExpression` | String | A cron schedule for running the evaluation in UTC. + +### Example request + +The following request schedules the experiment to run every night at 1 AM: + +```json +POST _plugins/_search_relevance/experiments/schedule +{ + "experimentId": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "cronExpression": "0 1 * * *" +} +``` +{% include copy-curl.html %} + +## Managing scheduled experiments + +You can retrieve or delete scheduled experiments using the following APIs. + +### Retrieve scheduled experiments + +This API retrieves the available scheduled experiments. + +#### Endpoints + +```json +GET _plugins/_search_relevance/experiments/schedule +GET _plugins/_search_relevance/experiments/schedule/{experiment_id} +``` + +#### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `experiment_id` | String | The ID of the scheduled experiment to retrieve. If not provided, retrieves all scheduled experiments. | + +#### Example request + +```json +GET _plugins/_search_relevance/experiments/schedule/6282afa6-fa14-49c8-a627-ac1d5204d357 +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": ".search-relevance-scheduled-experiment-jobs", + "_id": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "_score": null, + "_source": { + "id": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "enabled": true, + "schedule": { + "cron": { + "expression": "0 0 * * *", + "timezone": "America/Los_Angeles" + } + }, + "enabledTime": 1758320475601, + "lastUpdateTime": 1758320475601, + "timestamp": "2025-09-19T00:00:00.602Z" + }, + "sort": [ + "2025-09-19T00:00:00.602Z" + ] + } + ] + } +} +``` + +### Delete a scheduled experiment + +You can delete a scheduled experiment using the scheduled experiment ID. + +#### Endpoint + +```json +DELETE _plugins/_search_relevance/experiments/schedule/<experiment_id> +``` + +### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `experiment_id` | String | The ID of the scheduled experiment to delete. | + + +#### Example request + +```json +DELETE _plugins/_search_relevance/experiments/schedule/6282afa6-fa14-49c8-a627-ac1d5204d357 +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_index": ".search-relevance-scheduled-experiment-jobs", + "_id": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 17, + "_primary_term": 1 +} +``` diff --git a/_search-plugins/search-relevance/relevance-agent.md b/_search-plugins/search-relevance/relevance-agent.md new file mode 100644 index 00000000..7e436051 --- /dev/null +++ b/_search-plugins/search-relevance/relevance-agent.md @@ -0,0 +1,63 @@ +--- +layout: default +title: Relevance agent +nav_order: 100 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_toc: false +--- + +# Relevance agent +**Introduced 3.6** +{: .label .label-purple } + +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/20602). +{: .warning} + +The OpenSearch relevance agent helps you identify and resolve search relevance issues through natural language conversation. Using a chat interface embedded in OpenSearch Dashboards, you can interactively diagnose problems, receive step-by-step tuning guidance, and execute complex workflows. The agent leverages the tools provided by the [Search Relevance Workbench]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/). + +The agent is part of the [OpenSearch Agent Server](https://github.com/opensearch-project/opensearch-agent-server), a standalone service that hosts and orchestrates AI-powered agents for OpenSearch workflows. + +## How it works + +When you submit a message through the chat interface, a **router** analyzes the context and directs the request to the relevance agent when appropriate. The router activates the relevance agent when you're on Search Relevance Workbench pages or the search workspace homepage. + +The relevance agent operates as a multi-agent system. An internal orchestrator interprets your intent and delegates work to specialized subagents, each responsible for a specific part of the relevance tuning process. The orchestrator synthesizes results from the subagents and streams them back to you in real time. + +## Specialized agents + +The relevance agent orchestrator coordinates three specialized subagents. These subagents are invoked automatically based on your questions and do not require separate configuration. + +### User behavior analysis agent + +The user behavior analysis agent analyzes [User Behavior Insights (UBI)]({{site.url}}{{site.baseurl}}/search-plugins/ubi/) data to examine engagement patterns and click-through rates. It identifies high-performing and poorly performing queries, correlates user behavior with search quality issues, and provides metrics-driven insights to inform tuning decisions. + +### Hypothesis generation agent + +The hypothesis generation agent examines query structure and DSL configurations to analyze search quality issues. It uses UBI data to identify patterns and generates testable hypotheses for improvements, such as field weight adjustments or query boosting strategies. Before recommending configuration changes, it validates hypotheses using [pairwise comparison experiments]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/comparing-search-results/). + +### Evaluation agent + +The evaluation agent designs and executes offline relevance evaluation experiments. It creates [judgment lists]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/judgments/) from UBI click data when sufficient event data is available or from LLM-generated relevance ratings when click data is limited. The agent then runs experiments using your [search configurations]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/) and computes search quality metrics (NDCG, MAP, and Precision@K) to compare their performance. + +## Prerequisites + +Before using the relevance agent, ensure that you have the following components: + +- **OpenSearch Agent Server** -- The agent server must be running and connected to your OpenSearch cluster. For setup instructions, see the [OpenSearch Agent Server repository](https://github.com/opensearch-project/opensearch-agent-server). +- **OpenSearch Dashboards** -- The chat interface is embedded in OpenSearch Dashboards. You must configure OpenSearch Dashboards to point to the running agent server. +- **A large language model (LLM) provider** -- Configure an LLM for the agent server. The only provider supported is [Amazon Bedrock](https://aws.amazon.com/bedrock/). +- **User Behavior Insights (UBI)** (Optional) -- For behavior-driven analysis and judgment generation from click data, [enable UBI]({{site.url}}{{site.baseurl}}/search-plugins/ubi/) and configure it to collect events on your cluster. + +## Accessing the agent + +After the agent server is running and Dashboards is configured, access the relevance agent by selecting the chat icon in the OpenSearch Dashboards header. Navigate to a Search Relevance Workbench page or the search workspace homepage to activate the agent. + +The agent responds in real time and may request your confirmation before executing experiment steps. + +## Next steps + +- [Setting up the OpenSearch Agent Server](https://github.com/opensearch-project/opensearch-agent-server) +- [Search Relevance Workbench]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/) +- [User Behavior Insights]({{site.url}}{{site.baseurl}}/search-plugins/ubi/) +- [Experiments]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/experiments/) diff --git a/_search-plugins/search-relevance/rerank-by-field-cross-encoder.md b/_search-plugins/search-relevance/rerank-by-field-cross-encoder.md new file mode 100644 index 00000000..b0c3fd97 --- /dev/null +++ b/_search-plugins/search-relevance/rerank-by-field-cross-encoder.md @@ -0,0 +1,283 @@ +--- +layout: default +title: Reranking by a field using a cross-encoder +parent: Reranking search results +grand_parent: Optimizing search quality +has_children: false +nav_order: 30 +--- + +# Reranking by a field using a cross-encoder model +**Introduced 2.18** +{: .label .label-purple } + +In this tutorial, you'll learn how to use a cross-encoder model hosted on Amazon SageMaker to rerank search results and improve search relevance. + +To rerank documents, you'll configure a search pipeline that processes search results at query time. The pipeline intercepts search results and passes them to the [`ml_inference` search response processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-response/), which invokes the cross-encoder model. The model generates scores used to rerank the matching documents [`by_field`]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field/). + +## Prerequisite: Deploy a model on Amazon SageMaker + +Run the following code to deploy a model on Amazon SageMaker. For this example, you'll use the [`ms-marco-MiniLM-L-6-v2`](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-6-v2) Hugging Face cross-encoder model hosted on Amazon SageMaker. We recommend using a GPU for better performance: + +```python +import sagemaker +import boto3 +from sagemaker.huggingface import HuggingFaceModel + +sess = sagemaker.Session() +role = sagemaker.get_execution_role() + +hub = { + 'HF_MODEL_ID':'cross-encoder/ms-marco-MiniLM-L-6-v2', + 'HF_TASK':'text-classification' +} +huggingface_model = HuggingFaceModel( + transformers_version='4.37.0', + pytorch_version='2.1.0', + py_version='py310', + env=hub, + role=role, +) +predictor = huggingface_model.deploy( + initial_instance_count=1, # number of instances + instance_type='ml.m5.xlarge' # ec2 instance type +) +``` +{% include copy.html %} + +After deploying the model, you can find the model endpoint by going to the Amazon SageMaker console in the AWS Management Console and selecting **Inference > Endpoints** on the left tab. Note the URL for the created model; you'll use it to create a connector. + +## Running a search with reranking + +To run a search with reranking, follow these steps: + +1. [Create a connector](#step-1-create-a-connector). +1. [Register the model](#step-2-register-the-model). +1. [Ingest documents into an index](#step-3-ingest-documents-into-an-index). +1. [Create a search pipeline](#step-4-create-a-search-pipeline). +1. [Search using reranking](#step-5-search-using-reranking). + +## Step 1: Create a connector + +Create a connector to the cross-encoder model by providing the model URL in the `actions.url` parameter: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "SageMaker cross-encoder model", + "description": "Test connector for SageMaker cross-encoder hosted model", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "parameters": { + "region": "<REGION>", + "service_name": "sagemaker" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "<YOUR_SAGEMAKER_ENDPOINT_URL>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"inputs\": { \"text\": \"${parameters.text}\", \"text_pair\": \"${parameters.text_pair}\" }}" + } + ] +} +``` +{% include copy-curl.html %} + +Note the connector ID contained in the response; you'll use it in the following step. + +## Step 2: Register the model + +To register the model, provide the connector ID in the `connector_id` parameter: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Cross encoder model", + "version": "1.0.1", + "function_name": "remote", + "description": "Using a SageMaker endpoint to apply a cross encoder model", + "connector_id": "<YOUR_CONNECTOR_ID>" +} +``` +{% include copy-curl.html %} + + +## Step 3: Ingest documents into an index + +Create an index and ingest sample documents containing facts about the New York City boroughs: + +```json +POST /nyc_areas/_bulk +{ "index": { "_id": 1 } } +{ "borough": "Queens", "area_name": "Astoria", "description": "Astoria is a neighborhood in the western part of Queens, New York City, known for its diverse community and vibrant cultural scene.", "population": 93000, "facts": "Astoria is home to many artists and has a large Greek-American community. The area also boasts some of the best Mediterranean food in NYC." } +{ "index": { "_id": 2 } } +{ "borough": "Queens", "area_name": "Flushing", "description": "Flushing is a neighborhood in the northern part of Queens, famous for its Asian-American population and bustling business district.", "population": 227000, "facts": "Flushing is one of the most ethnically diverse neighborhoods in NYC, with a large Chinese and Korean population. It is also home to the USTA Billie Jean King National Tennis Center." } +{ "index": { "_id": 3 } } +{ "borough": "Brooklyn", "area_name": "Williamsburg", "description": "Williamsburg is a trendy neighborhood in Brooklyn known for its hipster culture, vibrant art scene, and excellent restaurants.", "population": 150000, "facts": "Williamsburg is a hotspot for young professionals and artists. The neighborhood has seen rapid gentrification over the past two decades." } +{ "index": { "_id": 4 } } +{ "borough": "Manhattan", "area_name": "Harlem", "description": "Harlem is a historic neighborhood in Upper Manhattan, known for its significant African-American cultural heritage.", "population": 116000, "facts": "Harlem was the birthplace of the Harlem Renaissance, a cultural movement that celebrated Black culture through art, music, and literature." } +{ "index": { "_id": 5 } } +{ "borough": "The Bronx", "area_name": "Riverdale", "description": "Riverdale is a suburban-like neighborhood in the Bronx, known for its leafy streets and affluent residential areas.", "population": 48000, "facts": "Riverdale is one of the most affluent areas in the Bronx, with beautiful parks, historic homes, and excellent schools." } +{ "index": { "_id": 6 } } +{ "borough": "Staten Island", "area_name": "St. George", "description": "St. George is the main commercial and cultural center of Staten Island, offering stunning views of Lower Manhattan.", "population": 15000, "facts": "St. George is home to the Staten Island Ferry terminal and is a gateway to Staten Island, offering stunning views of the Statue of Liberty and Ellis Island." } +``` +{% include copy-curl.html %} + +## Step 4: Create a search pipeline + +Next, create a search pipeline for reranking. In the search pipeline configuration, the `input_map` and `output_map` define how the input data is prepared for the cross-encoder model and how the model's output is interpreted for reranking: + +- The `input_map` specifies which fields in the search documents and the query should be used as model inputs: + - The `text` field maps to the `facts` field in the indexed documents. It provides the document-specific content that the model will analyze. + - The `text_pair` field dynamically retrieves the search query text (`multi_match.query`) from the search request. + + The combination of `text` (document `facts`) and `text_pair` (search `query`) allows the cross-encoder model to compare the relevance of the document to the query, considering their semantic relationship. + +- The `output_map` field specifies how the output of the model is mapped to the fields in the response: + - The `rank_score` field in the response will store the model's relevance score, which will be used to perform reranking. + +When using the `by_field` rerank type, the `rank_score` field will contain the same score as the `_score` field. To remove the `rank_score` field from the search results, set `remove_target_field` to `true`. + +Comparing the original and reranked scores can help you evaluate improvements in search relevance. To compare the original BM25 score with the reranked score, set `keep_previous_score` to `true`. The original score is included in the search results for debugging purposes and is stored in the `previous_score` field by default. If your index already contains a document field named `previous_score`, set `previous_score_field` to a different name so that the rerank processor does not overwrite the existing field. + + +To create the search pipeline, send the following request: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "This processor runs ml inference during search response", + "model_id": "<model_id_from_step_3>", + "function_name": "REMOTE", + "input_map": [ + { + "text": "facts", + "text_pair":"$._request.query.multi_match.query" + } + ], + "output_map": [ + { + "rank_score": "$.score" + } + ], + "full_response_path": false, + "model_config": {}, + "ignore_missing": false, + "ignore_failure": false, + "one_to_one": true + }, + + "rerank": { + "by_field": { + "target_field": "rank_score", + "remove_target_field": true, + "keep_previous_score": true, + "previous_score_field": "original_query_score" + } + } + + } + ] +} +``` +{% include copy-curl.html %} + +## Step 5: Search using reranking + +Use the following request to search indexed documents and rerank them using the cross-encoder model. The request retrieves documents containing any of the specified terms in the `description` or `facts` fields. These terms are then used to compare and rerank the matched documents: + +```json +POST /nyc_areas/_search?search_pipeline=my_pipeline +{ + "query": { + "multi_match": { + "query": "artists art creative community", + "fields": ["description", "facts"] + } + } +} +``` +{% include copy-curl.html %} + +In the response, the `original_query_score` field contains the document's BM25 score, which it would have received if you hadn't applied the pipeline. Note that while BM25 ranked "Astoria" the highest, the cross-encoder model prioritized "Harlem" because it matched more search terms: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.03418137, + "hits": [ + { + "_index": "nyc_areas", + "_id": "4", + "_score": 0.03418137, + "_source": { + "area_name": "Harlem", + "description": "Harlem is a historic neighborhood in Upper Manhattan, known for its significant African-American cultural heritage.", + "original_query_score": 1.6489418, + "borough": "Manhattan", + "facts": "Harlem was the birthplace of the Harlem Renaissance, a cultural movement that celebrated Black culture through art, music, and literature.", + "population": 116000 + } + }, + { + "_index": "nyc_areas", + "_id": "1", + "_score": 0.0090838, + "_source": { + "area_name": "Astoria", + "description": "Astoria is a neighborhood in the western part of Queens, New York City, known for its diverse community and vibrant cultural scene.", + "original_query_score": 2.519608, + "borough": "Queens", + "facts": "Astoria is home to many artists and has a large Greek-American community. The area also boasts some of the best Mediterranean food in NYC.", + "population": 93000 + } + }, + { + "_index": "nyc_areas", + "_id": "3", + "_score": 0.0032599436, + "_source": { + "area_name": "Williamsburg", + "description": "Williamsburg is a trendy neighborhood in Brooklyn known for its hipster culture, vibrant art scene, and excellent restaurants.", + "original_query_score": 1.5632852, + "borough": "Brooklyn", + "facts": "Williamsburg is a hotspot for young professionals and artists. The neighborhood has seen rapid gentrification over the past two decades.", + "population": 150000 + } + } + ] + }, + "profile": { + "shards": [] + } +} +``` + +## Next steps + +- For a tutorial that reranks results by a field using Cohere Rerank, see [Reranking search results by a field using Cohere Rerank]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-by-field/). diff --git a/_search-plugins/search-relevance/rerank-by-field-late-interaction.md b/_search-plugins/search-relevance/rerank-by-field-late-interaction.md new file mode 100644 index 00000000..ce7264ce --- /dev/null +++ b/_search-plugins/search-relevance/rerank-by-field-late-interaction.md @@ -0,0 +1,716 @@ +--- +layout: default +title: Reranking by a field using a late interaction model +parent: Reranking search results +grand_parent: Optimizing search quality +has_children: false +nav_order: 40 +--- + +# Reranking by a field using a late interaction model +**Introduced 3.3** +{: .label .label-purple } + +In this tutorial, you'll learn how to use a late interaction model (such as ColBERT or ColPali) hosted on Amazon SageMaker to rerank search results and improve search relevance for multimodal content. + +Late interaction models balance speed and accuracy by generating multiple vectors per document and query, then performing fine-grained token-level matching during search. This approach is particularly effective for multimodal content (such as images with text, technical diagrams, and complex documents), for which detailed semantic analysis improves relevance. By combining fast k-NN retrieval with token-level reranking, late interaction models efficiently handle complex queries and capture nuanced semantic relationships across text and other content types. + +To implement late interaction reranking, you'll configure both ingest and search pipelines: +- **Ingest pipeline**: Generates multi-vectors and single k-NN vectors during document indexing using the [`ml_inference` ingest processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/ml-inference/). +- **Search pipeline**: Processes queries at search time, generating query vectors for both k-NN retrieval and late interaction reranking using the [`ml_inference` search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-request/) and the [`lateInteractionScore`]({{site.url}}{{site.baseurl}}/query-dsl/specialized/script-score/#late-interaction-score) function. + +## Prerequisite: Deploy a ColPali model on Amazon SageMaker + +The following is a sample deployment script for the [`vidore/colpali-v1.3-hf`](https://huggingface.co/vidore/colpali-v1.3-hf) model on Amazon SageMaker. You can use any late interaction model and deployment method of your choice. Because ColPali requires custom inference logic to handle both text queries and Base64-encoded images, this example uses a custom inference script rather than the standard Hugging Face task interface. Run the following steps in a SageMaker notebook. + +### Step 1: Create a custom inference script + +The following script handles both query (text list) and image (Base64 list) inputs, returning multi-vector token-level embeddings. It downloads model weights from Hugging Face Hub at container startup: + +```python +import os +os.makedirs('colpali_code', exist_ok=True) + +inference_code = r''' +# Requires Python >= 3.12 and transformers >= 4.51.3 +import torch +import base64 +from io import BytesIO +from PIL import Image +from transformers import ColPaliForRetrieval, ColPaliProcessor + +def model_fn(model_dir): + device = "cuda" if torch.cuda.is_available() else "cpu" + model = ColPaliForRetrieval.from_pretrained( + "vidore/colpali-v1.3-hf", torch_dtype=torch.float32, + ).to(device).eval() + processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.3-hf") + return {"model": model, "processor": processor, "device": device} + +def predict_fn(data, model_dict): + model = model_dict["model"] + processor = model_dict["processor"] + device = model_dict["device"] + queries = data.get("queries", []) + images_b64 = data.get("images", []) + result = {} + if queries: + inputs = processor(text=queries, return_tensors="pt", padding=True) + inputs = {k: v.to(device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + result["query_embeddings"] = outputs.embeddings.cpu().tolist() + if images_b64: + pil_images = [] + for b64 in images_b64: + pil_images.append(Image.open(BytesIO(base64.b64decode(b64))).convert("RGB")) + inputs = processor(images=pil_images, return_tensors="pt", padding=True) + inputs = {k: v.to(device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + result["image_embeddings"] = outputs.embeddings.cpu().tolist() + return result + +def input_fn(request_body, request_content_type): + import json + if request_content_type == "application/json": + return json.loads(request_body) + raise ValueError(f"Unsupported content type: {request_content_type}") + +def output_fn(prediction, accept): + import json + return json.dumps(prediction) +'''.strip() + +with open('colpali_code/inference.py', 'w') as f: + f.write(inference_code) +print('Created colpali_code/inference.py') +``` +{% include copy.html %} + +### Step 2: Package the script and upload it to Amazon S3 + +Package the `inference.py` script and upload it to Amazon S3 by using the following code: + +```python +import subprocess +import sagemaker +import boto3 + +subprocess.run(['tar', '-czf', 'model.tar.gz', '-C', 'colpali_code', 'inference.py'], check=True) +print('Created model.tar.gz') + +session = sagemaker.Session() +region = session.boto_region_name +account_id = boto3.client('sts').get_caller_identity()['Account'] +bucket = f'sagemaker-{region}-{account_id}' +s3_key = 'colpali-custom/model.tar.gz' + +s3 = boto3.client('s3', region_name=region) +s3.upload_file('model.tar.gz', bucket, s3_key) +model_data_url = f's3://{bucket}/{s3_key}' +print(f'Uploaded to {model_data_url}') +``` +{% include copy.html %} + +### Step 3: Deploy the SageMaker endpoint + +The following code deploys the model to a GPU instance (this process takes approximately 5--10 minutes): + +```python +import time +from datetime import datetime + +role = sagemaker.get_execution_role() + +# HuggingFace PyTorch Inference DLC - GPU, Python 3.12, Transformers 4.51.3 +# Replace 123456789012 with your AWS Deep Learning Containers account ID for your region. +# See https://github.com/aws/deep-learning-containers/blob/master/available_images.md +dlc_account_id = '123456789012' +image_uri = ( + f'{dlc_account_id}.dkr.ecr.{region}.amazonaws.com/' + 'huggingface-pytorch-inference:2.6.0-transformers4.51.3-gpu-py312-cu124-ubuntu22.04' +) + +sm = boto3.client('sagemaker', region_name=region) +ts = datetime.now().strftime('%Y%m%d%H%M%S') + +model_name = f'colpali-custom-{ts}' +epc_name = f'colpali-custom-epc-{ts}' +ep_name = f'colpali-custom-ep-{ts}' + +sm.create_model( + ModelName=model_name, + PrimaryContainer={ + 'Image': image_uri, + 'ModelDataUrl': model_data_url, + 'Environment': { + 'SAGEMAKER_PROGRAM': 'inference.py', + 'SAGEMAKER_SUBMIT_DIRECTORY': model_data_url, + }, + }, + ExecutionRoleArn=role, +) +print(f'Model created: {model_name}') + +sm.create_endpoint_config( + EndpointConfigName=epc_name, + ProductionVariants=[{ + 'VariantName': 'AllTraffic', + 'ModelName': model_name, + 'InstanceType': 'ml.g4dn.xlarge', + 'InitialInstanceCount': 1, + }], +) +print(f'Endpoint config created: {epc_name}') + +sm.create_endpoint(EndpointName=ep_name, EndpointConfigName=epc_name) +print(f'Creating endpoint: {ep_name} (takes 5-10 min)...') + +while True: + resp = sm.describe_endpoint(EndpointName=ep_name) + status = resp['EndpointStatus'] + print(f' Status: {status}') + if status == 'InService': + break + if status == 'Failed': + print(f' FAILED: {resp.get("FailureReason")}') + break + time.sleep(30) + +print(f'\nEndpoint ready: {ep_name}') +``` +{% include copy.html %} + +After deployment, find your endpoint name in the Amazon SageMaker console under **Inference > Endpoints**. You'll use this endpoint URL in the connector configuration. + +## Running a search with late interaction reranking + +To implement late interaction reranking, follow these steps: + +1. [Register the model](#step-1-register-the-model). +1. [Create an index with appropriate mappings](#step-2-create-an-index). +1. [Create an ingest pipeline](#step-3-create-an-ingest-pipeline). +1. [Ingest documents](#step-4-ingest-documents). +1. [Create a search pipeline](#step-5-create-a-search-pipeline). +1. [Search using late interaction reranking](#step-6-search-using-late-interaction-reranking). + +## Step 1: Register the model + +Register the ColPali model by creating a connector and registering it with OpenSearch: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "ColPali model", + "function_name": "remote", + "description": "ColPali model for multimodal search", + "connector": { + "name": "Amazon SageMaker connector", + "description": "Connector for ColPali in SageMaker", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "sagemaker" + }, + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "<YOUR_SAGEMAKER_ENDPOINT>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"queries\": ${parameters.queries:-[]}, \"images\": ${parameters.images:-[]} }" + } + ] + } +} +``` +{% include copy-curl.html %} + +Note the `model_id` from the response; you'll use it in subsequent steps. + +## Step 2: Create an index + +Create an index with mappings optimized for storing both multi-vectors and single k-NN vectors. The `colbert_vectors` field is stored as an `object` with `enabled: false` for optimal performance. The `knn_vector` field is configured for the `hnsw` algorithm, with the number of dimensions matching the model's number of dimensions. The `image` field stores Base64-encoded image data as a `keyword`: + + +```json +PUT /multimodal_docs +{ + "settings": { + "index.knn": true, + "index.knn.algo_param.ef_search": 100 + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "description": { + "type": "text" + }, + "image": { + "type": "keyword" + }, + "colbert_vectors": { + "type": "object", + "enabled": false + }, + "knn_vector": { + "type": "knn_vector", + "dimension": 128, + "method": { + "name": "hnsw", + "engine": "lucene" + } + } + } + } +} +``` +{% include copy-curl.html %} + +## Step 3: Create an ingest pipeline + +Create an ingest pipeline that generates both multi-vectors for late interaction and single vectors for k-NN search: + +```json +PUT /_ingest/pipeline/colpali_pipeline +{ + "processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "Generate multi-vectors and mean pooling vector for multimodal content", + "model_id": "<YOUR_MODEL_ID>", + "input_map": [ + { + "images": "$..image" + } + ], + "output_map": [ + { + "colbert_vectors": "image_embeddings[0]", + "knn_vector": "image_embeddings[0].meanPooling()" + } + ], + "ignore_missing": false, + "ignore_failure": false + } + } + ] +} +``` +{% include copy-curl.html %} + +## Step 4: Ingest documents + +Ingest sample documents containing Base64-encoded images and descriptive content: + +```json +PUT /multimodal_docs/_doc/1?pipeline=colpali_pipeline +{ + "title": "Data Visualization Chart", + "description": "A comprehensive bar chart showing quarterly sales performance with multiple data series and trend analysis", + "image": "iVBORw0KGgoAAAANSUhEUgAAAMwAAAAgCAYAAABepJcLAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAAzKADAAQAAAABAAAAIAAAAABBU0NJSQAAAFNjcmVlbnNob3SjVaBQAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4zMjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yMDQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4K23hIHgAAC3pJREFUeAHtXAl0jlcafhLZEJKISIg9lliGhIptLKOxDLGvpSVqKYo0nTqtGkuHU13o4BQdjK1qjS1irZ0oofa1xBZECLFLSGTuc5PvP/+S/P/304yeuq/z59ve+977Pffdv3M4JCXfzYQihYBCQBcCjrq4FJNCQCEgEVAGoxRBIWAHAspg7ABLsSoElMEoHVAI2IGAMhg7wFKsCgFlMEoHFAJ2IKAMxg6wFKtCQBmM0gGFgB0IKIOxAyzFqhBQBqN0QCFgBwLKYOwAS7EqBJTBKB1QCNiBgDIYO8BSrAoBZTBKBxQCdiDwRhhManoa7qU+sAOW34c1Lf0ZbjxMMvyepqdaFfy61mm+qJuPbiNT/PujEddEPInr6yLH9ssH4tbjO3J+btjG+F3yt/3yL7h87xpeZL54qbVpyvJSg20M+jXxJPgzpwPXj+J08gXz2+i+ahgCZ4biyfOnFs/y8sbhmydRa05bwy/qzEar0+X1Ou+nPsTdp/esriE24VcEzW6DKQfmWeXLy4fPM54j7sYxzD6yFNRDzUDSM9IllocST+Tl9AbZV+5fR/qLDMM1TxypZGkZWRZLL9w3egS+2/9fjNs9BfXmdULbZf1x6V6CySA9FwduHEXXlR/qYbWbJzbhEPpE/8PECz5/kY5eaz7CiaSzFvI6Vm6B8Jqdkd/ZzeJZXt6oX7IWbkbGyV8ZD3+bU+X1OmcdWYJJ++dYXUeAV2m0qxSKev5BVvny6iEjSPCcMLRbNgBbL8Vi+OZxCBM6SCP6fxKzgbpzOyL5yV2TaZ14VdjV3eTmd81H4S/FKsvw9+6aSAxcPwqbe86Ho4P+DO5B2kMTmb/nRYuARvgydgZO376Aaj4VpejDIuI8evYEb5draDFVeM0uFvf+iDfyep0pOtJSP3cfzGrz5WuBh0pKfSvvWRoH+61Ffic3PEh7hF1XDsA5n7PBaBwc8n55nDcnkgbj4Voop2coUcgXkXX7YcD6kdgrvHrj0iF4/PwJFp1Yg/Xnd8iw+bcy9dCzenu0rfS2lMGQ/vW+H5DwIBGJj26h2Y89DbJnh01EgFcZaYgMt9su78Nvdy6he7UwhNfojGC/agZeayeB3gGgx94uxmsGw9BdV3jFogW85NC5R5fLdWpyfAsWxZJO07RLeYxPuYLph37Elot7wHS0nn8wBtd+Fw1L1ZbPm//UGxOafizl8gZz+56rI/BTxyko7l4MGSJd3XhhJxafjBZYHJV49RJY9BHv4ubkKmXY+qNnnUM2jsbZ5HgLUYs7TgUVnF7ZGp7/ObwY0b9txbk7F6WM/dcOyyMj7voec2WqGra0n4n8TxsMQsuAxib3Ys5vw6zDS+W+/7XUWxgeEi51gkyM8C0FXlNajMH3hxbKvSGew+r0MeBnIiyHC6bZTKk1YyELnbmmW9qQ24/vYtCGf4oItFfumfEctvSTMo4lncHUuHmYFPo5JsbOFCXITrn/K7vMRGmPEuiz9hPcS8uqeTtHDYZrPhc59bCQPnBiCLZGNBLShbuXJTjXHySBRvFR3b4o51lKWH+cNKgjJdYLJfJBVZ8KGNckAjHCoJafjsGk5p8bxJcsVFye7xXjnwoFnRw6Cl5uheVmD900FrHhUQZeWycdRJq1SdRbBIvEl6bRadSifCME+VWVl1svxmLhiVXaI8MxcssEFMnvKZWG0XPbpX3SyDWGE7fO4uGzx9qlWHOq3NBn2ekBc+qlp9ahY2ALjG8aKZzETfSP+RQl3H0tNtkgxOxEzzr5jlrDgHn14A2j8X5QN2ksFGcLz1YBTVCnRA1M2DNdKuBwsfEkLWNwEQphvE/dVg7FfTMPG3N+u3i3kYgI6YuxjSOw6uwmkG911x/A1BOZmRKbTlGD8EWTSPQP7o5pcfMxdtcUbBLZiR6iItMRliqcpSe5jflgwyhMFlnQ+0FdLeawpZ+UyT3dfTUOHVZ8gEal6mB2m4nS+VUoUgYujs5Sfy+mJIA6OabRcPgULCKX4l/ID05RXWbkti5538OtkPSmd7KLxUre5bCw/WQ5QcL9GyhZ2A/uLgWwOX63rBO83Dzg5eeB40nnwMhVy6+6hfxuVVuDPxZz8feuivQvEAuOr8IZ4V2qFK1gwZ/TjVbC+9FLJD9JEd4hVUaq5sJINCopQOePdP7OZXk0/8PNOXbrDM4LZ8CowjrHHnJ1csGiDv+WQ5IeJ8PZ0QlBvlURfX6rboPRs04NkztPUzBs0zhZY4wXkU8jW3jyPfnzLuAJnwLeFnvi5JjP5F5O0ZFRNFSkuyMbDpbT1i5eHb+ISLXizIYsg8lezLSW49C6QlN5Nah2L3SJGoKU1PvCMXpkc+R+uCqcQVnPkrkzZD+Z2/abXOewpZ+acKbv7SqG4pP6A7RbhiN1lukgqaZvFYNj4rUTUwtrRI/G1IrWRWKn6SuRci0+uVakQ5UQ6F0ehVzcLYojWzLpefYmHERIiSCU9yol2an8eokvwvRr19UDMpzS6Gx5JnPZjITTDy0S4X2UrH/o7enN6Y310rxjK4SXWyAjJfFg9El6lKx3uG4+phq9VkdKJ/B9q3HIZ1RPco9eFU9bC2HKyTTNmJqVayDTWeN7xum9v0jpSezO6TGYwKIBWH9hh7G4HM+tzWGPfkaILMlekjWMtUE7Lu+Xj4Oz0xumIIwmu3ovNRhRfMoQCxFuwvvS67ItrYV+jemL3VNFEeeEowM2yOjE1t2cI8u0x7qOlNkpsBV+vrhXGnHbis10jTNm8s7vJULuMIxuNFTm97MOL5FdwXNDtsnoSF7jLomWimkyTtw6h5Hbv8XabrMMeTrbsaytzIlePF3k+S9D7BD1X/eZjOpzwr4CUyhj0ounWz5Xk/cxlmHrnM7gyM1TJmwHbxxHdXH/96IaxarIjIGRS6Z5LyFYr35StIP4lxu5ZtegrGVYJ2qUY9uL6RcLRKZJn23/WhSxnQyp0oWUq2Aq4u5SUHrl+ceiZENAE6gdKxYpJ5+vOrtZFoRsWTMMkiibXsJFGA0L6TG7stIabazeY8vyjbHm3Bbp5dg5s4cYzZjesNCkwVbwKgtuGClT5OOkMGGE/HZCD07jGCwKTWPifZKnqMNY9NJQFhxfacxiOGeRzEYJuy9s05NfD9HhRP48AQcTj2NqyzEyjeXa+dNk6MWTHpxrPC5a7/wIyMaMXmLLm3u57FSMnJuRlZ8kwipmNXv0yrHGR6fcpcrf8d7aj7FBNFP4fZDNnIbzu8g9sDZWe6ZXPzX+3I5atrLk5DpRzz2UuHM9JhFGiwQ9xIc+EvPxic1GyK6PJrifKLS2if545RlZQL1TrZ3M1x3Men3McQfWekcWTiyeSPPbfQsWoKOFVw8X33vYbWP9M7xOuKyTzGVoc+Z2DPGvKcczUrBzZo2cRTFnTDT6ciIV5PccLRXkWqaKLg8NgDQguIeIIN/IfjzTP+bn7JJpnqlZ2fpgl7DJwh6Sv0HJ2ugqarP9147Ia+M/vap3wNDNY1FpRlYk3NJzIWr4BhqzyHPzde68sl8aLR8adxx5Hd19tkhpa+rGkzUaO4ItFvfmcIndnj7LJfbyhtEfR7P9ZMubxj5q5yREbPmXTIfZZdLqFWTzm48zEmnzlPrHTxp0xvz+QgfLPWGnlt0r7SOitTn06qetxbAendl6PEZsnQh2GUkfvvUeHF7mf76kd6K1FRGFHPvj1uiZ+Ch6W3z8oVIbF5N8eaY7vu5FDQpoTU5ePmP0y8jMkGvMaR4alNauzuk5c3RHR0dRyxXM6bHJvUQRUT1FI0UrKk0evsKFPXhyP8jvU6AImCraQ4x43Pu83jfOw3UWK+htt37Yo5+23p3rYBZEI2aL+6UMxtYk6rlC4M+KQI41zJ/1ZdV7KQReFQFlMK+KoBr/RiGgDOaN2m71sq+KgDKYV0VQjX+jEPgf9X05Z4Ml7BIAAAAASUVORK5CYII=" +} + +``` +{% include copy-curl.html %} + +```json +PUT /multimodal_docs/_doc/2?pipeline=colpali_pipeline +{ + "title": "Technical Architecture Diagram", + "description": "System architecture diagram showing microservices, databases, and API connections with detailed component relationships", + "image": "iVBORw0KGgoAAAANSUhEUgAAAP4AAAAaCAYAAACXQ+HFAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAA/qADAAQAAAABAAAAGgAAAABBU0NJSQAAAFNjcmVlbnNob3TZrl9HAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4yNjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KbSuS3AAADEZJREFUeAHtXAdUFVca/oEnIGADxYIFOyqKvUWNJZZoYl17PfboumssscU91lijx7JRE9t6ErP23rsiKooFG6igIIiiYAEEFGH/78K8fQ8ezDzfLHr2ze8ZZt6dW7/79ztHm8eRT9NIIw0BDQGrQsDWqlarLVZDQENAIKAJvsYIGgJWiIAm+Fa46dqSNQQ0wdd4QEPAChHQBN8KN11bsoaAJvgaD2gIWCECmuBb4aZrS9YQ0ARf4wENAStEIFcE/8XbWIp7F68avM8SXlAa/1OT0N+T+Gj99To5Ts3uVe3LHDxT01IJeGmkDgL/L3jaVevaYEbIq3DKfCWmJFFR58KqoDVg/wSKSXpFDUvUsrg/v8ir1HbLQNLZ6KhBiZoW9yd18O7De/JZ357W3tgirsj4Z9S+fHPptdl334grFJ0QQyXyFTW7rVwDc/BcFrCRBh+cRI09alPJfMWMuk7+8I6i38ZQPntno3K1f4S/eULOeZzI1iZX7IzZ08de3Y0JobDXkfSOMcnvkI/sbO1M9pMTniYbfGaFO+8doelnl5JuzfXNYmpBL0LE3atweXFv7dmEqhep/JlNm6h8wdL0TYWWVL+Ej6pzc7Czp/BRvqLPaWd/Jkss/suk19Rn71hyYWa/MeQA5bHNo+pczemsEStb4FWmgEeWZpejAulHXuvpPn9meadWAQxIk9970OWBu1UzJGrNTeoHGKSkfqBCjgXoRvRdcstbiJZ9NZ2alaovVdHfc8JTX+kzfnjO3rd/1A3S7eyySkxz6KEpVIwt/Jxm4z/jaZNgnl/azPqs53j80XmqXbQahbGlOx9xlZqXbvDJ5guvKDvP6E0uhDNx7xI+2drNGXioT08aVL0bJaUk0+TTC6nfvnEmlVVOeJoz3qeqW9Ahvxhap2QCV5/dpuVX/kUnw/youIu7AGh4zd5kZ+C6wYXYevcg+UUGULmCpahnlW9omE8v0mW4TGlpaTTvwiraGnSQ3J1cCUB392ovhoeWXXZlI42q1Y8W+f9KN6ODqWPFr2hMnQHkwe7p2/dJ1GXnCKOpTmgwjOCVGBJi34WXfuU5XKXYRA4tPGrRpIYjqLJrOVHtevQd2hi4gy48ucYu3XvqweNjs7EmNWnvgxPUskxjFvxIOhByMovg/3BqvlgfvIoNgduFBoZVNlRoluAZ8PQmTT2z2GhJGzss0q8T+Cz2/40i455RFOc1EDpJ9Evb2cKrwm9L9h05nSGHJtPrpPRcSc89YwheFWhU7f7Uifd3G/PCmcf+tLL1DFGOP0svryfwyrj6Q0RZYHQQrby6ieY3n0QLL66hIw/PUTIL5787Laca7l6ijpJ5iooK/jjqHGhKo+8I+P9xe4+Yhxye6FYJbx0OPcvrWyfCioqFPPWysYLXX8m1LMmtFTmo9YFb6VTYRbr/8pGQn/7enamme1WxMvBVPnsX2s885+7kRoNrdKdZ51dQveLVBW/pbHXk7uwm6soK/rVnd6jzjhE0mjdrKgOCASeenEcFOA7qU7Wj6GTVtT+EUMNbmNtsHCE+/vPOPkr6kEwutk6iDjb0u1p9aX37BXQo9DSNP/kTtS3bjOMpFyHYsJKIsaY1HkU2rFCmn11CBR3z0+SGI8neLo/YeNER/+nLbvSbZONkIRJYHXcMp7IFStHillOpcN6CtOf+cQGmJPi7go9SZbdyBKWFJM2UM4so4f1bVb2cGFY4Z8Iv0aQGIygi7imNOzGHMZkg1iDN/8GrMFrCDADlBFxnNPm7mI/03lI8KzBTQVBAUbwXI49MF4pO6r+KW3ma3niM2IdtQYf0dfFeygNYvO/2TmKMh68f09jjs3lfR/OeuIopeGTkPV4kvqRQzi8ZEjCztbHRF8W/TyDfx1eo+67R1KRkXVrFiik17QOVL1RG1FEyT31nCh+Q2/IuUomCYtPDXzk80a0cbyGHNvzwVFrYYrIwBDN9l9PN58EEoYdxA8mt9QIrbHgkC1tMIljudYHbBLZSqBb+JoqCY0OFIh3GHvzKgE30c8spNOjADxTIY8ELLeZcRBgAWcHfHnyIwCgQWhAadq7UhvbePyEEHwK0gr0BMO8A7y6iDjYlc3w0xKeH0KSoAEFcfW0zXYq6bmS1t3ZeIeIr1OlWuR0dDj0jBB9eQ62i6VoN7xxYK2cmKI44VgYbOiygvDpH8Xp8/aFG1WY2HSt+wxrdfxlGtYt507a7B2hm0++NvBejRmb+OPbIV6yhWpGKVJY9n3hWLL4Rl4UHYNjVw1cRtL/7WvJwMU7+qYEnlLKEVyFWnpkJsSyuW8wMBVjxSnUN66mx7+g3b8Ze1Sji9dExPjCER/R9vcGGUxTPcvPM0kBhgXfhSgQFDZLDE3XkeOvW83uoJqw0POXuXl+zN3iKfNhrMUx65rRWyAQuJGVDXz0Wyun327spiBOTXiyjoH7VOtEXJesIxdi76reC75BrevQ6Qgg+PI1dXVeTrOBf4QQQMp7e69qJjqU/0IggZGwx2brFqkuvTN4BnkROeRyFcGS22nBTJILliWbXXSkFPL0lXHtJ6E21Ox8RQPMvrhaZbGg/G7YsmPt7dvvtTCgTU33Ile1jNz+GLVm7LYP0VQ+EnM4i+AgxMgs9GqiJp34CH/Gg1r5/xNAmmyDsM0Vy8zTVRq4MR7sIQZDIU0pyvCWFJXDVYRQ33dpNTUvVMxJ6aazs1gregOvux3xcr3gN8mTDAoKXKZGkRKBcpGdDQwkjWoJDW1nB9+bMvjO7bVISUBpAuktu2wO2oNLipHe5eUeMtOHmduEySws2HB8xPdyfv9UdRMNq9hIWHtnN/Q9OGlYTzwANxzrmEnIM5x5fZvdqKlV09RTNwRALODady2EQ4keJbOi/7qxUhntu4umgsxdHjvAyMmOm1r5LTPcq+U0Wiw8lHRX/3HD5wppJXoLRi2zwkpuncR/KfgXHhIrcR12OjZWQEt5yZQ+rdP4SdOLRBdrO4VVdFtyJnKcyTaZ5Y47fSj4h0pH/oN3ixAgnERvY3f8YspVr9G2FVnQl6iYh7kQcnZKaQqfCL1IICzoIR1W9OJGHI5GzrCXhhohYnX8/TTDeVLmxLHnf2vMLsVnIyCJhhWMkuFJrrqcfVYHxYN3dOPYHwYtZ4r/e5JDwXhBXIlcB6422Sugou/lwq7pUaisSLki69M7Ig0ABKKHcxBOxKzDZff+Y2FcJI8xTrX0vlRG/buGQCh4e+ANHSiBkyIHvXs7F4A4ew7M5JDdPpX1h7eDbo5w8xAkXXOKeVTooai7hlhNvXXxynfNJibSk1TQ63HOjMARShl3RIFzpXuxDEXbYs8xBFmedX660aZZ6RhY/s9ZHbRxFrWk3l+b6/VMk8FCGrP1PX07UJ1jw7MIfgYw8/KNgJNQBaJKFs7O1ZX2dVYvB1QZJyRyDnI4oR1IvO5LaSu+RV9j3l98Imc0Gm7qKYmhY5B5AyHIikYakIi68g+XHKUTmvpqXbkh1WNs32tRNtJ3NCcuB3ul9ioJs/kDRIP8hnWSgGjR9Y486dJATmq08G2fT0rjYUjyNe0v/ZWpvEe4g94LkGy7Q2q/nUZuyTVXZd/SHTDISWFNYIePjKBDyRcice3GitV+1zvTXYzNEedfKbUUcD8WtlJTwp5K+lvivY0OwTgg81o9ThZy+vzDEUwlvwTWHcmuYwZuYE5RLdrkLU3Oe2miUUEqb7+wVBmZ0nf4iUWcoNxIv27LMGVJm+bMx5//ci+UPU+AGG8brhp0jNoImgubLCTTDNv+LZ1ix5JR3eutuOAaOBhNTEkWOwbDc1LPcek21UbMst/CEq/o8MZbcHAvqlbXhOuRwUDJPhBNPmTfycdhomMvBOPDOUvkIzzlPXsNhzX6Wm6fZHZrZICfeQmwey1+vwhABb+SVkEeAh3qu7xaTH1iZGh7uPRQIjuUyC7Op+tmVGVn87CpJ5bBeOREmgqz/pya427hMERKLuJSQ3HqV9GFJndzCE56VqUSjNHc5HJTMExYSSSVTlFNC1lT97Mrk5pldO7XKc+ItHIODJ2E44SHAQCIbjzJzviOBN6nGp/RmWXy1ANL60RCwNgTuvHhA/zi3VHysBWGHV9qCQ0p834DEdG6TJvi5jbg2nlUjEM+fML/l0KYIf71qiatuKYhmufqWDqa11xCwdgSQBMf1qck49fepZ6ONryGgIZArCPwHHEgr5h2DjhkAAAAASUVORK5CYII=" +} +``` +{% include copy-curl.html %} + +```json +PUT /multimodal_docs/_doc/3?pipeline=colpali_pipeline +{ + "title": "Financial Report Summary", + "description": "Quarterly financial report with revenue charts, expense breakdowns, and profit margin analysis across different business units", + "image": "iVBORw0KGgoAAAANSUhEUgAAANAAAAAZCAYAAABAQ6AIAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAA0KADAAQAAAABAAAAGQAAAABBU0NJSQAAAFNjcmVlbnNob3Q2LTWaAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4yNTwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yMDg8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4K9xJAjQAADF9JREFUeAHtWwlYVdUW/kEGAVERxXnEOZxQe5mKQzkEipSWOJQ+U1PLtHzVs7TnVJqmllIOmRo4JOaY5ZiaOX2IWjiBYyo44KwoMqhv/Vv25RJwuV0wh+8sP+45Z09nnbXX8K91jnan487dg0GGBAwJ2CQBe5tmGZMMCRgSUBIwDMhQBEMCuZCAYUC5EJ4x1ZCAYUCGDhgSyIUEDAPKhfCMqYYEDAMydMCQQC4kYBhQLoRnTDUk4GCrCG6nJuH2nSQUdi5o6xL/yDxb+LyHezibcMHEn5ujCwo5u5uujRNDAloCDhduXUYx1yLq+s9rsYi5fEL3mY71iz+FomljdGP3H99FxNk/EN1nA1wd8+vmR+5oC5/Jd1LwTOhLpmcJrPI8QlqNMF1be7Lx5Hak3L2jhrs7uaJS4XIo4VbM2un/6LikO8m4lHgVpQp42Xzfk9fiEHluHxJSbsGnaBX4lvCBnfx70mjUtqk4df0MZr0wFg5JEkU0bTy5AyO2fokGJWvpJnX87zP9MhkQlaqaZyW4ODpnGPuoXdjCp3M+J5wasFU9ykdbJuJa0g2bHuutdSPg5eaJ0u4lsPfcAaVY7zTsBf49arTrbBSGybNu7rrQJtbWnfgNvVcPFSdRVpyEF4ZvmYTnKzRWSmZv92RlCseunETUhRglJ4eCThmhSbmCpbD0xWk5CvE1nxdzHPMoDHjYfL7doCdeqtpGQOE9fPtHOOi9/l270yMHfa/b6CT0Hk/dHYqgKq0wpdX/VNPZhHjQKJ804+HDebgUQpH8hdRzOhR0LqBOrPmZu28JFh5caRrq5VYUYe0mmq5T76YiYPHr+Lzlh5i2dz42n9yJp0vVxZu+3dGwZG017owIdnZUODZJ35Erf+Ll6v541ScIdb1qqv4/4g/hy8i5GFCvOyZEzMS++Bgwigys/5ry5PpmSw+vRfihn7E9brfyep1rtEOfOsFwsM+HnPjkGr/HH8TcqCXYcWYvCNleET561uqIkrmAMJq3rI6EMi3KPaMM6MTVWNQrfv9595w/gCmR34Fwj/cmD33rdkE+8dpanv3qdUPYgWWIPLsPPsWqYlyz91Hbq7q6zd17dxGyOwxLD69B/M1LaFbuX/iw0QCULVjSxMYC2TNGUb+yDZVs1xzfou61pdv32H1uPz6P+AZxN85L3hePNot6mOZ93WY0vAV2WkNXbl9DrWLVTEP5LNw3Tf6Le2FEk0F4umQd1XT+5kW8tmoI5gZMULy8v2kc3J0KYNWxjfBy9USv2i8rWTUUNPR161EIj/4Z+y8cxj7x/LE3zuETvyGYGDELzg5Oqr9CoTK4mZKo9PPn45uVrCiLYNGLAO8Wmg1ExUcjZE8oxjX/AON3zsBaiZxJks9/32GK6I4D3vllNOa3n5wBcVEfb8naQxv1V+sQhl9xv6bOM8XWFDGCE5IL6T/iYk2tJCTzxvxrXbGpeiDdxyO97KFLx9B5+UA0LdMQoWnGRa+raUfcHjCxH9/iA2zqMh+ES4M3jNbdwuhtbPhzGz7Y/BneEEX6qs0obI2NFAVabhpD4+Qcf+/mao1RTd9RgmFRg5QTnxyzLGadgqBz/McrJ7Bd+PpqTxi7HghdlFzzu/1LUcDRVRStqrrH3vMHEbTkDdTw9MaG4DB83HggpooxLTq0SvVreVJR3vJ9FQsDv4Srgwve2zTWxONIke2cfT+gd53OmOU/TsHEwCV9wftporIuP7wO3X8cgvolamFlp5mY1PIjJXvee/izA9FBlN3TxcO0v9zjMgI9raUB4iTnyR4FrxiknMEdMWxzovInJN80NSWm3la6Qn0jnbp+VpzAWsUXIVKIRLSJLYeCxk64dCnxilq/b91gZdT91g7DsMZv4XpSAlYf/1WtcSbhvDjUPeJse4DOoXWFJui/djjO3UwvCCWk3MTW05F4edmb6vmniZOY5T8W3h7lUaOot1pn3sEV6sgf8jlj7wI0LlPf1EbnoB1tpiocvVBAeDpGf6laG4wRaycRy/OPdFSiR3Y06blhaFvJT3X3rdtZCZUeykPCXsdqbdUfk9bjV08rj0rBR4vhVZfN1BQeNFVtKK85Z40IibkYPS6VjN5MwzM+vF/Zp/VUq/gc2XSwGn8jOUEi4UmV8C4+9BNGijHS++cVDft1IkZvC1EKQAWdIEpBT0f6IWa1Mp7+EmFI9GxBVVtj5ZFf0LVmoGrjD53Ns6Xvb6C7kxva/dAbjOTFXD0wJ2oxhosidX8qSI2nDOvODsCW2F0KOupF6NjmtZ+UQU7s457wb78oaSFBIzoy6nnWHslvtSIVxQnNQ8+f3leo4NNm7wnfvtYuIc/QQSkq97NLzfZoWf5Z5XBY3CL5SjGrfeXncPDiUVXsYERn2wnRI1IVjwqY7f8ZaLyxYpCl3Yur+etPbBWUk55ysMjRrnLLLHPRQQK5/7NxrHLeLg75sfrYryjiUlj4aqDuwR/qY3LlFHWdyYCYA23tHm4abMuJOSwsVaC4WoKeghvF6gUj0vbY3QrWVZCkk2Qe6XjNcK6JnjA+zaNyPgXQQDxpbmib3H/czumy7iW1CXZ2dmrdFIFz+RzyrjDS37ebRMQm6LJyMF4U4zCHE5GSI1Cxfb5tm+FRCNMyUnoli8pFIpQpL3tFalQqXUmJzTmfHp+5l6ZGpetlMh7dl1dHRjcqMNHLJ9u/Esf5Nnb1WI7iAvWtIZ0v0YHpc2ezvbC3v+/Y8slR9+s2rk/0Qti/6OAq1JQqYFUxaHdxChclev2VmBJkRa0r+onBTMPSmLXoJgYdKqiBsNrcqRJFwPH+7EwGlNWiedk2ZnsIHMUDR/RcrrxDqpR56UWtJXoV0lGJGjoPsHauHsecp49UjJjg9xFIQOGwJL/q6EY9xHRkX7JES1uJEZtRYYzfuwpOdK4RIJ66klrOR3IGNylvW1O00fffLWViUmXJTUqlySLqQrQyGrbTudB4dERimzXEXII5FCO8Vk5r5ukxhDr02KSKko+MlkjOylzM5eMmAzJXZO5BXlN49E9gtFnfJQyl0xw3IWXWlO6UzPuZQzMKMe9hGZ456uyA8eZDMpznHVbJsGz2F4flPRNfSjrZO4LYfNS2KdkPzqLHUeYxMWTJdcvpCBAK8v0Dy83mWDeLqaamq0nXlaJ5SmgmMQpMipht6jc/YaQjZo4TfE0czrm2EPM1JtAf/zZZ5Ypcg3CEhQHmdJQFiwabTu0EcwBzWhKzRuU0jDpfRM5R8KiiRG4qLCPazN8XqjwxTpLrMQIXSSwY/B2qLPCHxrf8yHrFh5aRNWsQftefE6iqjNwLQq7pkjeQ6njVUEc+/1LJO4kgDlw8jIHrR6j2vPw5fvWUymvcHd3Us4TuX6aKTH/3Hh2kmsiCxOANo0CHpytuWa2TyYBogdaSU760OJY2Qb80s+TBWCFiVajyjBZosaCr8k5MyARBKbJPO9HXmhfzexFbBwtG7rdmGKrMaImm8zurKJHfLNzreTyaz+U1qzxvSlI+ZOOnqDjNT0WjF7ybsUv4SGNEXQHNBWfXl0pQo9COqDenPVYc2ZDWY91By4THkU0HYUfcXoWrObu5VIlmtP0E8w+sQMPvglBpenOMlPdw5wVWmhPzR9+5garCmXInFQukmKBlPOm5j1C7WHV0FYjYKKwTdkpVcUXHmVIASK/Cma+V3TlzidfrvKKKM+Sj9rf+CmZnN968ne8DmVOymMG98JsfjF+kqhgeFGL6goNVtSu3r6LJvFdUMWOo6AFJy0edp8neHJbpMRwnwI2XpqM+17LoIVCLDpWQuOY3rQXmRisH89c9VYtY+KG+vN2gh3KshHGWyO5h/JduwjZ6c75kNBegJUaz6mOVip6bkYSR6e8SMXNiaqKpWGFp/mVRYsK5B/VJT1brp9xNgff0FljUYapK7i19OkXFSUi+pWRh6Tly6iO0upB4GZ75CyM7h2RpDZbLuS/ZfeLFfWcx5UER782vazzyF7RJJzRfk3fNlmriDvzY6RvdlOXxH8+ByAWjnLWJZZZcpzXS+HLzaQw/QbL2MyRLYdwSj9b2WVqfSkFltqTQfB3g7OJk7e2yHUfvq/OHbAdZ6MjJwTxI4yFb1AkiDFuJ7wcJq2lACwK/yHGZh2JAOXJlDFASIGjhpzE6OTfE8mAlwPdU+vOr6W3GoIlZ6Tq7Oz8UCJcdM0a7IYHHTQKZigiP2wMY/BoSeJgSMAzoYUrfuPdjL4H/AzhAzGbMOihRAAAAAElFTkSuQmCC" +} +``` +{% include copy-curl.html %} + +## Step 5: Create a search pipeline + +Create a search pipeline that generates query vectors and performs both k-NN retrieval and late interaction reranking: + +```json +PUT /_search/pipeline/colpali_search_pipeline +{ + "description": "Generate query vectors for KNN search and late interaction reranking", + "request_processors": [ + { + "ml_inference": { + "model_id": "<YOUR_MODEL_ID>", + "query_template": "{\n \"query\": {\n \"knn\": {\n \"knn_vector\": {\n \"vector\": ${query_knn_vector},\n \"k\": 100\n }\n }\n },\n \"rescore\": {\n \"query\": {\n \"rescore_query\": {\n \"script_score\": {\n \"query\": {\n \"match_all\": {}\n }, \n \"script\": {\n \"source\": \"lateInteractionScore(params.query_vector, 'colbert_vectors', params._source)\",\n \"params\": {\n \"query_vector\": ${query_colbert_vectors}\n }\n }\n }\n }\n }\n },\n \"size\": 10,\n \"_source\": {\n \"excludes\": [\"knn_vector\"]\n }\n}", + "input_map": [ + { + "queries": "$..query.term.search_text.value" + } + ], + "output_map": [ + { + "query_colbert_vectors": "query_embeddings[0]", + "query_knn_vector": "query_embeddings[0].meanPooling()" + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +The following is the `query_template` from the preceding search pipeline, formatted for clarity. The template defines how the original search query is rewritten: + +```json +{ + "query": { + "knn": { + "knn_vector": { + "vector": ${query_knn_vector}, + "k": 100 + } + } + }, + "rescore": { + "query": { + "rescore_query": { + "script_score": { + "query": { + "match_all": {} + }, + "script": { + "source": "lateInteractionScore(params.query_vector, 'colbert_vectors', params._source)", + "params": { + "query_vector": ${query_colbert_vectors} + } + } + } + } + } + }, + "size": 10, + "_source": { + "excludes": ["knn_vector"] + } +} +``` + +Note the following components of the query template: + +- Template variables: + - `${query_knn_vector}`: Mean-pooled vector for fast k-NN retrieval + - `${query_colbert_vectors}`: Multi-vectors for precise late interaction scoring +- Rewritten query structure: + - `knn` query: Uses `query_knn_vector` to find the top 100 candidates quickly + - `rescore_query`: Uses `query_colbert_vectors` with the `lateInteractionScore` function for precise reranking + - `_source` filtering: Excludes vector fields from the response to reduce payload size + +## Step 6: Search using late interaction reranking + +Now you can search for documents using k-NN retrieval and late interaction reranking: + +```json +GET /multimodal_docs/_search?search_pipeline=colpali_search_pipeline +{ + "query": { + "term": { + "search_text": { + "value": "financial report" + } + } + } +} +``` +{% include copy-curl.html %} + +When you run this search request, OpenSearch executes the following steps: + +1. **Query processing**: The search text (`"financial data charts"`) is sent to the ColPali model, which generates query vectors. + +1. **k-NN retrieval**: The mean-pooled query vector (`query_knn_vector`) performs approximate k-NN search to retrieve the top 100 candidate documents. This step prioritizes speed. + +1. **Late interaction reranking**: Multi-vectors (`query_colbert_vectors`) are used with the `lateInteractionScore` function to rerank results based on fine-grained token-level matching. This step prioritizes accuracy. + +1. **Final results**: The top 10 documents are returned, ranked by their late interaction scores. + +This hybrid approach balances speed and accuracy, making it suitable for production search systems. The response contains documents reranked based on their semantic similarity to the query, with late interaction scoring providing more nuanced relevance than traditional vector search alone: + +<details open markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "took": 2135, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 11.68498, + "hits": [ + { + "_index": "multimodal_docs", + "_id": "3", + "_score": 11.68498, + "_source": { + "image": "iVBORw0KGgoAAAANSUhEUgAAANAAAAAZCAYAAABAQ6AIAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAA0KADAAQAAAABAAAAGQAAAABBU0NJSQAAAFNjcmVlbnNob3Q2LTWaAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4yNTwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yMDg8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4K9xJAjQAADF9JREFUeAHtWwlYVdUW/kEGAVERxXnEOZxQe5mKQzkEipSWOJQ+U1PLtHzVs7TnVJqmllIOmRo4JOaY5ZiaOX2IWjiBYyo44KwoMqhv/Vv25RJwuV0wh+8sP+45Z09nnbXX8K91jnan487dg0GGBAwJ2CQBe5tmGZMMCRgSUBIwDMhQBEMCuZCAYUC5EJ4x1ZCAYUCGDhgSyIUEDAPKhfCMqYYEDAMydMCQQC4kYBhQLoRnTDUk4GCrCG6nJuH2nSQUdi5o6xL/yDxb+LyHezibcMHEn5ujCwo5u5uujRNDAloCDhduXUYx1yLq+s9rsYi5fEL3mY71iz+FomljdGP3H99FxNk/EN1nA1wd8+vmR+5oC5/Jd1LwTOhLpmcJrPI8QlqNMF1be7Lx5Hak3L2jhrs7uaJS4XIo4VbM2un/6LikO8m4lHgVpQp42Xzfk9fiEHluHxJSbsGnaBX4lvCBnfx70mjUtqk4df0MZr0wFg5JEkU0bTy5AyO2fokGJWvpJnX87zP9MhkQlaqaZyW4ODpnGPuoXdjCp3M+J5wasFU9ykdbJuJa0g2bHuutdSPg5eaJ0u4lsPfcAaVY7zTsBf49arTrbBSGybNu7rrQJtbWnfgNvVcPFSdRVpyEF4ZvmYTnKzRWSmZv92RlCseunETUhRglJ4eCThmhSbmCpbD0xWk5CvE1nxdzHPMoDHjYfL7doCdeqtpGQOE9fPtHOOi9/l270yMHfa/b6CT0Hk/dHYqgKq0wpdX/VNPZhHjQKJ804+HDebgUQpH8hdRzOhR0LqBOrPmZu28JFh5caRrq5VYUYe0mmq5T76YiYPHr+Lzlh5i2dz42n9yJp0vVxZu+3dGwZG017owIdnZUODZJ35Erf+Ll6v541ScIdb1qqv4/4g/hy8i5GFCvOyZEzMS++Bgwigys/5ry5PpmSw+vRfihn7E9brfyep1rtEOfOsFwsM+HnPjkGr/HH8TcqCXYcWYvCNleET561uqIkrmAMJq3rI6EMi3KPaMM6MTVWNQrfv9595w/gCmR34Fwj/cmD33rdkE+8dpanv3qdUPYgWWIPLsPPsWqYlyz91Hbq7q6zd17dxGyOwxLD69B/M1LaFbuX/iw0QCULVjSxMYC2TNGUb+yDZVs1xzfou61pdv32H1uPz6P+AZxN85L3hePNot6mOZ93WY0vAV2WkNXbl9DrWLVTEP5LNw3Tf6Le2FEk0F4umQd1XT+5kW8tmoI5gZMULy8v2kc3J0KYNWxjfBy9USv2i8rWTUUNPR161EIj/4Z+y8cxj7x/LE3zuETvyGYGDELzg5Oqr9CoTK4mZKo9PPn45uVrCiLYNGLAO8Wmg1ExUcjZE8oxjX/AON3zsBaiZxJks9/32GK6I4D3vllNOa3n5wBcVEfb8naQxv1V+sQhl9xv6bOM8XWFDGCE5IL6T/iYk2tJCTzxvxrXbGpeiDdxyO97KFLx9B5+UA0LdMQoWnGRa+raUfcHjCxH9/iA2zqMh+ES4M3jNbdwuhtbPhzGz7Y/BneEEX6qs0obI2NFAVabhpD4+Qcf+/mao1RTd9RgmFRg5QTnxyzLGadgqBz/McrJ7Bd+PpqTxi7HghdlFzzu/1LUcDRVRStqrrH3vMHEbTkDdTw9MaG4DB83HggpooxLTq0SvVreVJR3vJ9FQsDv4Srgwve2zTWxONIke2cfT+gd53OmOU/TsHEwCV9wftporIuP7wO3X8cgvolamFlp5mY1PIjJXvee/izA9FBlN3TxcO0v9zjMgI9raUB4iTnyR4FrxiknMEdMWxzovInJN80NSWm3la6Qn0jnbp+VpzAWsUXIVKIRLSJLYeCxk64dCnxilq/b91gZdT91g7DsMZv4XpSAlYf/1WtcSbhvDjUPeJse4DOoXWFJui/djjO3UwvCCWk3MTW05F4edmb6vmniZOY5T8W3h7lUaOot1pn3sEV6sgf8jlj7wI0LlPf1EbnoB1tpiocvVBAeDpGf6laG4wRaycRy/OPdFSiR3Y06blhaFvJT3X3rdtZCZUeykPCXsdqbdUfk9bjV08rj0rBR4vhVZfN1BQeNFVtKK85Z40IibkYPS6VjN5MwzM+vF/Zp/VUq/gc2XSwGn8jOUEi4UmV8C4+9BNGijHS++cVDft1IkZvC1EKQAWdIEpBT0f6IWa1Mp7+EmFI9GxBVVtj5ZFf0LVmoGrjD53Ns6Xvb6C7kxva/dAbjOTFXD0wJ2oxhosidX8qSI2nDOvODsCW2F0KOupF6NjmtZ+UQU7s457wb78oaSFBIzoy6nnWHslvtSIVxQnNQ8+f3leo4NNm7wnfvtYuIc/QQSkq97NLzfZoWf5Z5XBY3CL5SjGrfeXncPDiUVXsYERn2wnRI1IVjwqY7f8ZaLyxYpCl3Yur+etPbBWUk55ysMjRrnLLLHPRQQK5/7NxrHLeLg75sfrYryjiUlj4aqDuwR/qY3LlFHWdyYCYA23tHm4abMuJOSwsVaC4WoKeghvF6gUj0vbY3QrWVZCkk2Qe6XjNcK6JnjA+zaNyPgXQQDxpbmib3H/czumy7iW1CXZ2dmrdFIFz+RzyrjDS37ebRMQm6LJyMF4U4zCHE5GSI1Cxfb5tm+FRCNMyUnoli8pFIpQpL3tFalQqXUmJzTmfHp+5l6ZGpetlMh7dl1dHRjcqMNHLJ9u/Esf5Nnb1WI7iAvWtIZ0v0YHpc2ezvbC3v+/Y8slR9+s2rk/0Qti/6OAq1JQqYFUxaHdxChclev2VmBJkRa0r+onBTMPSmLXoJgYdKqiBsNrcqRJFwPH+7EwGlNWiedk2ZnsIHMUDR/RcrrxDqpR56UWtJXoV0lGJGjoPsHauHsecp49UjJjg9xFIQOGwJL/q6EY9xHRkX7JES1uJEZtRYYzfuwpOdK4RIJ66klrOR3IGNylvW1O00fffLWViUmXJTUqlySLqQrQyGrbTudB4dERimzXEXII5FCO8Vk5r5ukxhDr02KSKko+MlkjOylzM5eMmAzJXZO5BXlN49E9gtFnfJQyl0xw3IWXWlO6UzPuZQzMKMe9hGZ456uyA8eZDMpznHVbJsGz2F4flPRNfSjrZO4LYfNS2KdkPzqLHUeYxMWTJdcvpCBAK8v0Dy83mWDeLqaamq0nXlaJ5SmgmMQpMipht6jc/YaQjZo4TfE0czrm2EPM1JtAf/zZZ5Ypcg3CEhQHmdJQFiwabTu0EcwBzWhKzRuU0jDpfRM5R8KiiRG4qLCPazN8XqjwxTpLrMQIXSSwY/B2qLPCHxrf8yHrFh5aRNWsQftefE6iqjNwLQq7pkjeQ6njVUEc+/1LJO4kgDlw8jIHrR6j2vPw5fvWUymvcHd3Us4TuX6aKTH/3Hh2kmsiCxOANo0CHpytuWa2TyYBogdaSU760OJY2Qb80s+TBWCFiVajyjBZosaCr8k5MyARBKbJPO9HXmhfzexFbBwtG7rdmGKrMaImm8zurKJHfLNzreTyaz+U1qzxvSlI+ZOOnqDjNT0WjF7ybsUv4SGNEXQHNBWfXl0pQo9COqDenPVYc2ZDWY91By4THkU0HYUfcXoWrObu5VIlmtP0E8w+sQMPvglBpenOMlPdw5wVWmhPzR9+5garCmXInFQukmKBlPOm5j1C7WHV0FYjYKKwTdkpVcUXHmVIASK/Cma+V3TlzidfrvKKKM+Sj9rf+CmZnN968ne8DmVOymMG98JsfjF+kqhgeFGL6goNVtSu3r6LJvFdUMWOo6AFJy0edp8neHJbpMRwnwI2XpqM+17LoIVCLDpWQuOY3rQXmRisH89c9VYtY+KG+vN2gh3KshHGWyO5h/JduwjZ6c75kNBegJUaz6mOVip6bkYSR6e8SMXNiaqKpWGFp/mVRYsK5B/VJT1brp9xNgff0FljUYapK7i19OkXFSUi+pWRh6Tly6iO0upB4GZ75CyM7h2RpDZbLuS/ZfeLFfWcx5UER782vazzyF7RJJzRfk3fNlmriDvzY6RvdlOXxH8+ByAWjnLWJZZZcpzXS+HLzaQw/QbL2MyRLYdwSj9b2WVqfSkFltqTQfB3g7OJk7e2yHUfvq/OHbAdZ6MjJwTxI4yFb1AkiDFuJ7wcJq2lACwK/yHGZh2JAOXJlDFASIGjhpzE6OTfE8mAlwPdU+vOr6W3GoIlZ6Tq7Oz8UCJcdM0a7IYHHTQKZigiP2wMY/BoSeJgSMAzoYUrfuPdjL4H/AzhAzGbMOihRAAAAAElFTkSuQmCC", + "description": "Quarterly financial report with revenue charts, expense breakdowns, and profit margin analysis across different business units", + "title": "Financial Report Summary" + } + }, + { + "_index": "multimodal_docs", + "_id": "1", + "_score": 9.761469, + "_source": { + "image": "iVBORw0KGgoAAAANSUhEUgAAAMwAAAAgCAYAAABepJcLAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAAzKADAAQAAAABAAAAIAAAAABBU0NJSQAAAFNjcmVlbnNob3SjVaBQAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4zMjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yMDQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4K23hIHgAAC3pJREFUeAHtXAl0jlcafhLZEJKISIg9lliGhIptLKOxDLGvpSVqKYo0nTqtGkuHU13o4BQdjK1qjS1irZ0oofa1xBZECLFLSGTuc5PvP/+S/P/304yeuq/z59ve+977Pffdv3M4JCXfzYQihYBCQBcCjrq4FJNCQCEgEVAGoxRBIWAHAspg7ABLsSoElMEoHVAI2IGAMhg7wFKsCgFlMEoHFAJ2IKAMxg6wFKtCQBmM0gGFgB0IKIOxAyzFqhBQBqN0QCFgBwLKYOwAS7EqBJTBKB1QCNiBgDIYO8BSrAoBZTBKBxQCdiDwRhhManoa7qU+sAOW34c1Lf0ZbjxMMvyepqdaFfy61mm+qJuPbiNT/PujEddEPInr6yLH9ssH4tbjO3J+btjG+F3yt/3yL7h87xpeZL54qbVpyvJSg20M+jXxJPgzpwPXj+J08gXz2+i+ahgCZ4biyfOnFs/y8sbhmydRa05bwy/qzEar0+X1Ou+nPsTdp/esriE24VcEzW6DKQfmWeXLy4fPM54j7sYxzD6yFNRDzUDSM9IllocST+Tl9AbZV+5fR/qLDMM1TxypZGkZWRZLL9w3egS+2/9fjNs9BfXmdULbZf1x6V6CySA9FwduHEXXlR/qYbWbJzbhEPpE/8PECz5/kY5eaz7CiaSzFvI6Vm6B8Jqdkd/ZzeJZXt6oX7IWbkbGyV8ZD3+bU+X1OmcdWYJJ++dYXUeAV2m0qxSKev5BVvny6iEjSPCcMLRbNgBbL8Vi+OZxCBM6SCP6fxKzgbpzOyL5yV2TaZ14VdjV3eTmd81H4S/FKsvw9+6aSAxcPwqbe86Ho4P+DO5B2kMTmb/nRYuARvgydgZO376Aaj4VpejDIuI8evYEb5draDFVeM0uFvf+iDfyep0pOtJSP3cfzGrz5WuBh0pKfSvvWRoH+61Ffic3PEh7hF1XDsA5n7PBaBwc8n55nDcnkgbj4Voop2coUcgXkXX7YcD6kdgrvHrj0iF4/PwJFp1Yg/Xnd8iw+bcy9dCzenu0rfS2lMGQ/vW+H5DwIBGJj26h2Y89DbJnh01EgFcZaYgMt9su78Nvdy6he7UwhNfojGC/agZeayeB3gGgx94uxmsGw9BdV3jFogW85NC5R5fLdWpyfAsWxZJO07RLeYxPuYLph37Elot7wHS0nn8wBtd+Fw1L1ZbPm//UGxOafizl8gZz+56rI/BTxyko7l4MGSJd3XhhJxafjBZYHJV49RJY9BHv4ubkKmXY+qNnnUM2jsbZ5HgLUYs7TgUVnF7ZGp7/ObwY0b9txbk7F6WM/dcOyyMj7voec2WqGra0n4n8TxsMQsuAxib3Ys5vw6zDS+W+/7XUWxgeEi51gkyM8C0FXlNajMH3hxbKvSGew+r0MeBnIiyHC6bZTKk1YyELnbmmW9qQ24/vYtCGf4oItFfumfEctvSTMo4lncHUuHmYFPo5JsbOFCXITrn/K7vMRGmPEuiz9hPcS8uqeTtHDYZrPhc59bCQPnBiCLZGNBLShbuXJTjXHySBRvFR3b4o51lKWH+cNKgjJdYLJfJBVZ8KGNckAjHCoJafjsGk5p8bxJcsVFye7xXjnwoFnRw6Cl5uheVmD900FrHhUQZeWycdRJq1SdRbBIvEl6bRadSifCME+VWVl1svxmLhiVXaI8MxcssEFMnvKZWG0XPbpX3SyDWGE7fO4uGzx9qlWHOq3NBn2ekBc+qlp9ahY2ALjG8aKZzETfSP+RQl3H0tNtkgxOxEzzr5jlrDgHn14A2j8X5QN2ksFGcLz1YBTVCnRA1M2DNdKuBwsfEkLWNwEQphvE/dVg7FfTMPG3N+u3i3kYgI6YuxjSOw6uwmkG911x/A1BOZmRKbTlGD8EWTSPQP7o5pcfMxdtcUbBLZiR6iItMRliqcpSe5jflgwyhMFlnQ+0FdLeawpZ+UyT3dfTUOHVZ8gEal6mB2m4nS+VUoUgYujs5Sfy+mJIA6OabRcPgULCKX4l/ID05RXWbkti5538OtkPSmd7KLxUre5bCw/WQ5QcL9GyhZ2A/uLgWwOX63rBO83Dzg5eeB40nnwMhVy6+6hfxuVVuDPxZz8feuivQvEAuOr8IZ4V2qFK1gwZ/TjVbC+9FLJD9JEd4hVUaq5sJINCopQOePdP7OZXk0/8PNOXbrDM4LZ8CowjrHHnJ1csGiDv+WQ5IeJ8PZ0QlBvlURfX6rboPRs04NkztPUzBs0zhZY4wXkU8jW3jyPfnzLuAJnwLeFnvi5JjP5F5O0ZFRNFSkuyMbDpbT1i5eHb+ISLXizIYsg8lezLSW49C6QlN5Nah2L3SJGoKU1PvCMXpkc+R+uCqcQVnPkrkzZD+Z2/abXOewpZ+acKbv7SqG4pP6A7RbhiN1lukgqaZvFYNj4rUTUwtrRI/G1IrWRWKn6SuRci0+uVakQ5UQ6F0ehVzcLYojWzLpefYmHERIiSCU9yol2an8eokvwvRr19UDMpzS6Gx5JnPZjITTDy0S4X2UrH/o7enN6Y310rxjK4SXWyAjJfFg9El6lKx3uG4+phq9VkdKJ/B9q3HIZ1RPco9eFU9bC2HKyTTNmJqVayDTWeN7xum9v0jpSezO6TGYwKIBWH9hh7G4HM+tzWGPfkaILMlekjWMtUE7Lu+Xj4Oz0xumIIwmu3ovNRhRfMoQCxFuwvvS67ItrYV+jemL3VNFEeeEowM2yOjE1t2cI8u0x7qOlNkpsBV+vrhXGnHbis10jTNm8s7vJULuMIxuNFTm97MOL5FdwXNDtsnoSF7jLomWimkyTtw6h5Hbv8XabrMMeTrbsaytzIlePF3k+S9D7BD1X/eZjOpzwr4CUyhj0ounWz5Xk/cxlmHrnM7gyM1TJmwHbxxHdXH/96IaxarIjIGRS6Z5LyFYr35StIP4lxu5ZtegrGVYJ2qUY9uL6RcLRKZJn23/WhSxnQyp0oWUq2Aq4u5SUHrl+ceiZENAE6gdKxYpJ5+vOrtZFoRsWTMMkiibXsJFGA0L6TG7stIabazeY8vyjbHm3Bbp5dg5s4cYzZjesNCkwVbwKgtuGClT5OOkMGGE/HZCD07jGCwKTWPifZKnqMNY9NJQFhxfacxiOGeRzEYJuy9s05NfD9HhRP48AQcTj2NqyzEyjeXa+dNk6MWTHpxrPC5a7/wIyMaMXmLLm3u57FSMnJuRlZ8kwipmNXv0yrHGR6fcpcrf8d7aj7FBNFP4fZDNnIbzu8g9sDZWe6ZXPzX+3I5atrLk5DpRzz2UuHM9JhFGiwQ9xIc+EvPxic1GyK6PJrifKLS2if545RlZQL1TrZ3M1x3Men3McQfWekcWTiyeSPPbfQsWoKOFVw8X33vYbWP9M7xOuKyTzGVoc+Z2DPGvKcczUrBzZo2cRTFnTDT6ciIV5PccLRXkWqaKLg8NgDQguIeIIN/IfjzTP+bn7JJpnqlZ2fpgl7DJwh6Sv0HJ2ugqarP9147Ia+M/vap3wNDNY1FpRlYk3NJzIWr4BhqzyHPzde68sl8aLR8adxx5Hd19tkhpa+rGkzUaO4ItFvfmcIndnj7LJfbyhtEfR7P9ZMubxj5q5yREbPmXTIfZZdLqFWTzm48zEmnzlPrHTxp0xvz+QgfLPWGnlt0r7SOitTn06qetxbAendl6PEZsnQh2GUkfvvUeHF7mf76kd6K1FRGFHPvj1uiZ+Ch6W3z8oVIbF5N8eaY7vu5FDQpoTU5ePmP0y8jMkGvMaR4alNauzuk5c3RHR0dRyxXM6bHJvUQRUT1FI0UrKk0evsKFPXhyP8jvU6AImCraQ4x43Pu83jfOw3UWK+htt37Yo5+23p3rYBZEI2aL+6UMxtYk6rlC4M+KQI41zJ/1ZdV7KQReFQFlMK+KoBr/RiGgDOaN2m71sq+KgDKYV0VQjX+jEPgf9X05Z4Ml7BIAAAAASUVORK5CYII=", + "description": "A comprehensive bar chart showing quarterly sales performance with multiple data series and trend analysis", + "title": "Data Visualization Chart" + } + }, + { + "_index": "multimodal_docs", + "_id": "2", + "_score": 9.619822, + "_source": { + "image": "iVBORw0KGgoAAAANSUhEUgAAAP4AAAAaCAYAAACXQ+HFAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAA/qADAAQAAAABAAAAGgAAAABBU0NJSQAAAFNjcmVlbnNob3TZrl9HAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4yNjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KbSuS3AAADEZJREFUeAHtXAdUFVca/oEnIGADxYIFOyqKvUWNJZZoYl17PfboumssscU91lijx7JRE9t6ErP23rsiKooFG6igIIiiYAEEFGH/78K8fQ8ezDzfLHr2ze8ZZt6dW7/79ztHm8eRT9NIIw0BDQGrQsDWqlarLVZDQENAIKAJvsYIGgJWiIAm+Fa46dqSNQQ0wdd4QEPAChHQBN8KN11bsoaAJvgaD2gIWCECmuBb4aZrS9YQ0ARf4wENAStEIFcE/8XbWIp7F68avM8SXlAa/1OT0N+T+Gj99To5Ts3uVe3LHDxT01IJeGmkDgL/L3jaVevaYEbIq3DKfCWmJFFR58KqoDVg/wSKSXpFDUvUsrg/v8ir1HbLQNLZ6KhBiZoW9yd18O7De/JZ357W3tgirsj4Z9S+fHPptdl334grFJ0QQyXyFTW7rVwDc/BcFrCRBh+cRI09alPJfMWMuk7+8I6i38ZQPntno3K1f4S/eULOeZzI1iZX7IzZ08de3Y0JobDXkfSOMcnvkI/sbO1M9pMTniYbfGaFO+8doelnl5JuzfXNYmpBL0LE3atweXFv7dmEqhep/JlNm6h8wdL0TYWWVL+Ej6pzc7Czp/BRvqLPaWd/Jkss/suk19Rn71hyYWa/MeQA5bHNo+pczemsEStb4FWmgEeWZpejAulHXuvpPn9meadWAQxIk9970OWBu1UzJGrNTeoHGKSkfqBCjgXoRvRdcstbiJZ9NZ2alaovVdHfc8JTX+kzfnjO3rd/1A3S7eyySkxz6KEpVIwt/Jxm4z/jaZNgnl/azPqs53j80XmqXbQahbGlOx9xlZqXbvDJ5guvKDvP6E0uhDNx7xI+2drNGXioT08aVL0bJaUk0+TTC6nfvnEmlVVOeJoz3qeqW9Ahvxhap2QCV5/dpuVX/kUnw/youIu7AGh4zd5kZ+C6wYXYevcg+UUGULmCpahnlW9omE8v0mW4TGlpaTTvwiraGnSQ3J1cCUB392ovhoeWXXZlI42q1Y8W+f9KN6ODqWPFr2hMnQHkwe7p2/dJ1GXnCKOpTmgwjOCVGBJi34WXfuU5XKXYRA4tPGrRpIYjqLJrOVHtevQd2hi4gy48ucYu3XvqweNjs7EmNWnvgxPUskxjFvxIOhByMovg/3BqvlgfvIoNgduFBoZVNlRoluAZ8PQmTT2z2GhJGzss0q8T+Cz2/40i455RFOc1EDpJ9Evb2cKrwm9L9h05nSGHJtPrpPRcSc89YwheFWhU7f7Uifd3G/PCmcf+tLL1DFGOP0svryfwyrj6Q0RZYHQQrby6ieY3n0QLL66hIw/PUTIL5787Laca7l6ijpJ5iooK/jjqHGhKo+8I+P9xe4+Yhxye6FYJbx0OPcvrWyfCioqFPPWysYLXX8m1LMmtFTmo9YFb6VTYRbr/8pGQn/7enamme1WxMvBVPnsX2s885+7kRoNrdKdZ51dQveLVBW/pbHXk7uwm6soK/rVnd6jzjhE0mjdrKgOCASeenEcFOA7qU7Wj6GTVtT+EUMNbmNtsHCE+/vPOPkr6kEwutk6iDjb0u1p9aX37BXQo9DSNP/kTtS3bjOMpFyHYsJKIsaY1HkU2rFCmn11CBR3z0+SGI8neLo/YeNER/+nLbvSbZONkIRJYHXcMp7IFStHillOpcN6CtOf+cQGmJPi7go9SZbdyBKWFJM2UM4so4f1bVb2cGFY4Z8Iv0aQGIygi7imNOzGHMZkg1iDN/8GrMFrCDADlBFxnNPm7mI/03lI8KzBTQVBAUbwXI49MF4pO6r+KW3ma3niM2IdtQYf0dfFeygNYvO/2TmKMh68f09jjs3lfR/OeuIopeGTkPV4kvqRQzi8ZEjCztbHRF8W/TyDfx1eo+67R1KRkXVrFiik17QOVL1RG1FEyT31nCh+Q2/IuUomCYtPDXzk80a0cbyGHNvzwVFrYYrIwBDN9l9PN58EEoYdxA8mt9QIrbHgkC1tMIljudYHbBLZSqBb+JoqCY0OFIh3GHvzKgE30c8spNOjADxTIY8ELLeZcRBgAWcHfHnyIwCgQWhAadq7UhvbePyEEHwK0gr0BMO8A7y6iDjYlc3w0xKeH0KSoAEFcfW0zXYq6bmS1t3ZeIeIr1OlWuR0dDj0jBB9eQ62i6VoN7xxYK2cmKI44VgYbOiygvDpH8Xp8/aFG1WY2HSt+wxrdfxlGtYt507a7B2hm0++NvBejRmb+OPbIV6yhWpGKVJY9n3hWLL4Rl4UHYNjVw1cRtL/7WvJwMU7+qYEnlLKEVyFWnpkJsSyuW8wMBVjxSnUN66mx7+g3b8Ze1Sji9dExPjCER/R9vcGGUxTPcvPM0kBhgXfhSgQFDZLDE3XkeOvW83uoJqw0POXuXl+zN3iKfNhrMUx65rRWyAQuJGVDXz0Wyun327spiBOTXiyjoH7VOtEXJesIxdi76reC75BrevQ6Qgg+PI1dXVeTrOBf4QQQMp7e69qJjqU/0IggZGwx2brFqkuvTN4BnkROeRyFcGS22nBTJILliWbXXSkFPL0lXHtJ6E21Ox8RQPMvrhaZbGg/G7YsmPt7dvvtTCgTU33Ile1jNz+GLVm7LYP0VQ+EnM4i+AgxMgs9GqiJp34CH/Gg1r5/xNAmmyDsM0Vy8zTVRq4MR7sIQZDIU0pyvCWFJXDVYRQ33dpNTUvVMxJ6aazs1gregOvux3xcr3gN8mTDAoKXKZGkRKBcpGdDQwkjWoJDW1nB9+bMvjO7bVISUBpAuktu2wO2oNLipHe5eUeMtOHmduEySws2HB8xPdyfv9UdRMNq9hIWHtnN/Q9OGlYTzwANxzrmEnIM5x5fZvdqKlV09RTNwRALODady2EQ4keJbOi/7qxUhntu4umgsxdHjvAyMmOm1r5LTPcq+U0Wiw8lHRX/3HD5wppJXoLRi2zwkpuncR/KfgXHhIrcR12OjZWQEt5yZQ+rdP4SdOLRBdrO4VVdFtyJnKcyTaZ5Y47fSj4h0pH/oN3ixAgnERvY3f8YspVr9G2FVnQl6iYh7kQcnZKaQqfCL1IICzoIR1W9OJGHI5GzrCXhhohYnX8/TTDeVLmxLHnf2vMLsVnIyCJhhWMkuFJrrqcfVYHxYN3dOPYHwYtZ4r/e5JDwXhBXIlcB6422Sugou/lwq7pUaisSLki69M7Ig0ABKKHcxBOxKzDZff+Y2FcJI8xTrX0vlRG/buGQCh4e+ANHSiBkyIHvXs7F4A4ew7M5JDdPpX1h7eDbo5w8xAkXXOKeVTooai7hlhNvXXxynfNJibSk1TQ63HOjMARShl3RIFzpXuxDEXbYs8xBFmedX660aZZ6RhY/s9ZHbRxFrWk3l+b6/VMk8FCGrP1PX07UJ1jw7MIfgYw8/KNgJNQBaJKFs7O1ZX2dVYvB1QZJyRyDnI4oR1IvO5LaSu+RV9j3l98Imc0Gm7qKYmhY5B5AyHIikYakIi68g+XHKUTmvpqXbkh1WNs32tRNtJ3NCcuB3ul9ioJs/kDRIP8hnWSgGjR9Y486dJATmq08G2fT0rjYUjyNe0v/ZWpvEe4g94LkGy7Q2q/nUZuyTVXZd/SHTDISWFNYIePjKBDyRcice3GitV+1zvTXYzNEedfKbUUcD8WtlJTwp5K+lvivY0OwTgg81o9ThZy+vzDEUwlvwTWHcmuYwZuYE5RLdrkLU3Oe2miUUEqb7+wVBmZ0nf4iUWcoNxIv27LMGVJm+bMx5//ci+UPU+AGG8brhp0jNoImgubLCTTDNv+LZ1ix5JR3eutuOAaOBhNTEkWOwbDc1LPcek21UbMst/CEq/o8MZbcHAvqlbXhOuRwUDJPhBNPmTfycdhomMvBOPDOUvkIzzlPXsNhzX6Wm6fZHZrZICfeQmwey1+vwhABb+SVkEeAh3qu7xaTH1iZGh7uPRQIjuUyC7Op+tmVGVn87CpJ5bBeOREmgqz/pya427hMERKLuJSQ3HqV9GFJndzCE56VqUSjNHc5HJTMExYSSSVTlFNC1lT97Mrk5pldO7XKc+ItHIODJ2E44SHAQCIbjzJzviOBN6nGp/RmWXy1ANL60RCwNgTuvHhA/zi3VHysBWGHV9qCQ0p834DEdG6TJvi5jbg2nlUjEM+fML/l0KYIf71qiatuKYhmufqWDqa11xCwdgSQBMf1qck49fepZ6ONryGgIZArCPwHHEgr5h2DjhkAAAAASUVORK5CYII=", + "description": "System architecture diagram showing microservices, databases, and API connections with detailed component relationships", + "title": "Technical Architecture Diagram" + } + } + ] + } +} +``` + +</details> + +## Debugging and testing + +You can perform the following actions to debug and test the search. + +### Simulating the ingest pipeline + +Before ingesting documents, test the ingest pipeline to verify it processes documents correctly: + +```json +POST /_ingest/pipeline/colpali_pipeline/_simulate?verbose=true +{ + "docs": [ + { + "_index": "multimodal_docs", + "_id": "test_1", + "_source": { + "title": "Test Chart", + "description": "Sample chart for testing pipeline", + "image": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAoADwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAooooAKKKKACiiigAooooAKKKKACiiigD//2Q==" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response shows how the document will be processed and includes the generated `colbert_vectors` and `knn_vector` fields: + +```json +{ + "docs": [ + { + "processor_results": [ + { + "processor_type": "ml_inference", + "status": "success", + "description": "Generate multi-vectors and mean pooling vector for multimodal content", + "tag": "ml_inference", + "doc": { + "_index": "multimodal_docs", + "_id": "test_1", + "_source": { + "title": "Test Chart", + "description": "Sample chart for testing pipeline", + "image": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAoADwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAooooAKKKKACiiigAooooAKKKKACiiigD//2Q==", + "colbert_vectors": [ + [ + -0.0653999000787735, + 0.1100006103515625, + 0.2052547186613083 + ], + [ + 0.0234567890123456, + -0.0987654321098765, + 0.1357924680135792 + ] + ], + "knn_vector": [ + 0.025610961, + 0.045123789, + 0.067891234 + ] + }, + "_ingest": { + "pipeline": "colpali_pipeline", + "timestamp": "2025-10-02T23:17:01.615598095Z" + } + } + } + ] + } + ] +} +``` + +### Debugging the search pipeline + +Test the search pipeline with verbose output to see how queries are rewritten: + +```json +GET /multimodal_docs/_search?search_pipeline=colpali_search_pipeline&verbose_pipeline=true +{ + "query": { + "term": { + "search_text": { + "value": "financial data charts" + } + } + } +} +``` +{% include copy-curl.html %} + +The response provides a complete view of the query transformation process captured in the `processor_results` section. It shows the original query text ("financial data charts") submitted as input, the generated query vectors (both multi-vectors and mean-pooled vector), and the rewritten query structure using k-NN search with late interaction rescoring. Processing times for each step are also included, providing detailed information for debugging and performance optimization: + +```json +{ + "took": 1835, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 8.247408, + "hits": [ + { + "_index": "multimodal_docs", + "_id": "3", + "_score": 8.247408, + "_source": { + "title": "Financial Report Summary", + "description": "Quarterly financial report with revenue charts, expense breakdowns, and profit margin analysis across different business units" + } + } + ] + }, + "processor_results": [ + { + "processor_name": "ml_inference", + "duration_millis": 1200, + "status": "success", + "input_data": { + "query": { + "term": { + "search_text": { + "boost": 1, + "value": "financial data charts" + } + } + } + }, + "output_data": { + "size": 10, + "query": { + "knn": { + "knn_vector": { + "vector": [ + -0.06357764, + 0.021222984, + 0.06605018, + 0.07643713 + ], + "boost": 1, + "k": 100 + } + } + }, + "_source": { + "excludes": [ + "knn_vector" + ] + }, + "rescore": [ + { + "query": { + "rescore_query": { + "script_score": { + "query": { + "match_all": { + "boost": 1 + } + }, + "script": { + "source": "lateInteractionScore(params.query_vector, 'colbert_vectors', params._source)", + "params": { + "query_vector": [ + [ + -0.0024404169525951147, + 0.14708828926086426, + 0.15877428650856018 + ], + [ + 0.08923456789012346, + -0.03456789012345679, + 0.20123456789012345 + ] + ] + } + } + } + } + } + } + ] + } + } + ] +} +``` + +## Related documentation + +- [Late interaction score function]({{site.url}}{{site.baseurl}}/query-dsl/specialized/script-score/#late-interaction-score) + diff --git a/_search-plugins/search-relevance/rerank-by-field.md b/_search-plugins/search-relevance/rerank-by-field.md new file mode 100644 index 00000000..7d953f31 --- /dev/null +++ b/_search-plugins/search-relevance/rerank-by-field.md @@ -0,0 +1,212 @@ +--- +layout: default +title: Reranking by a field +parent: Reranking search results +grand_parent: Optimizing search quality +has_children: false +nav_order: 20 +--- + +# Reranking search results by a field +**Introduced 2.18** +{: .label .label-purple } + +You can use a `by_field` rerank type to rerank search results by a document field. Reranking search results by a field is useful if a model has already run and produced a numerical score for your documents or if a previous search response processor was applied and you want to rerank documents differently based on an aggregated field. + +To implement reranking, you need to configure a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) that runs at search time. The search pipeline intercepts search results and applies the [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/) to them. The `rerank` processor evaluates the search results and sorts them based on the new scores obtained from a document field. + +## Running a search with reranking + +To run a search with reranking, follow these steps: + +1. [Configure a search pipeline](#step-1-configure-a-search-pipeline). +1. [Create an index for ingestion](#step-2-create-an-index-for-ingestion). +1. [Ingest documents into the index](#step-3-ingest-documents-into-the-index). +1. [Search using reranking](#step-4-search-using-reranking). + +## Step 1: Configure a search pipeline + +Configure a search pipeline with a [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/) and specify the `by_field` rerank type. The pipeline sorts by the `reviews.stars` field (specified by a complete dot path to the field) and returns the original query scores for all documents along with their new scores: + +```json +PUT /_search/pipeline/rerank_byfield_pipeline +{ + "response_processors": [ + { + "rerank": { + "by_field": { + "target_field": "reviews.stars", + "keep_previous_score" : true + } + } + } + ] +} +``` +{% include copy-curl.html %} + +For more information about the request fields, see [Request fields]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/#request-body-fields). + +When `keep_previous_score` is `true`, the pre-rerank score is stored in `previous_score` by default. Use `previous_score_field` to choose a different field name if `previous_score` already exists in your documents. + +## Step 2: Create an index for ingestion + +In order to use the `rerank` processor defined in your pipeline, create an OpenSearch index and add the pipeline created in the previous step as the default pipeline: + +```json +PUT /book-index +{ + "settings": { + "index.search.default_pipeline" : "rerank_byfield_pipeline" + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "author": { + "type": "text" + }, + "genre": { + "type": "keyword" + }, + "reviews": { + "properties": { + "stars": { + "type": "float" + } + } + }, + "description": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +## Step 3: Ingest documents into the index + +To ingest documents into the index created in the previous step, send the following bulk request: + +```json +POST /_bulk +{ "index": { "_index": "book-index", "_id": "1" } } +{ "title": "The Lost City", "author": "Jane Doe", "genre": "Adventure Fiction", "reviews": { "stars": 4.2 }, "description": "An exhilarating journey through a hidden civilization in the Amazon rainforest." } +{ "index": { "_index": "book-index", "_id": "2" } } +{ "title": "Whispers of the Past", "author": "John Smith", "genre": "Historical Mystery", "reviews": { "stars": 4.7 }, "description": "A gripping tale set in Victorian England, unraveling a century-old mystery." } +{ "index": { "_index": "book-index", "_id": "3" } } +{ "title": "Starlit Dreams", "author": "Emily Clark", "genre": "Science Fiction", "reviews": { "stars": 4.5 }, "description": "In a future where dreams can be shared, one girl discovers her imaginations power." } +{ "index": { "_index": "book-index", "_id": "4" } } +{ "title": "The Enchanted Garden", "author": "Alice Green", "genre": "Fantasy", "reviews": { "stars": 4.8 }, "description": "A magical garden holds the key to a young girls destiny and friendship." } + +``` +{% include copy-curl.html %} + +## Step 4: Search using reranking + +As an example, run a `match_all` query on your index: + +```json +POST /book-index/_search +{ + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +The response contains documents sorted in descending order based on the `reviews.stars` field. Each document contains the original query score in the `previous_score` field: + +```json +{ + "took": 33, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 4.8, + "hits": [ + { + "_index": "book-index", + "_id": "4", + "_score": 4.8, + "_source": { + "reviews": { + "stars": 4.8 + }, + "author": "Alice Green", + "genre": "Fantasy", + "description": "A magical garden holds the key to a young girls destiny and friendship.", + "previous_score": 1, + "title": "The Enchanted Garden" + } + }, + { + "_index": "book-index", + "_id": "2", + "_score": 4.7, + "_source": { + "reviews": { + "stars": 4.7 + }, + "author": "John Smith", + "genre": "Historical Mystery", + "description": "A gripping tale set in Victorian England, unraveling a century-old mystery.", + "previous_score": 1, + "title": "Whispers of the Past" + } + }, + { + "_index": "book-index", + "_id": "3", + "_score": 4.5, + "_source": { + "reviews": { + "stars": 4.5 + }, + "author": "Emily Clark", + "genre": "Science Fiction", + "description": "In a future where dreams can be shared, one girl discovers her imaginations power.", + "previous_score": 1, + "title": "Starlit Dreams" + } + }, + { + "_index": "book-index", + "_id": "1", + "_score": 4.2, + "_source": { + "reviews": { + "stars": 4.2 + }, + "author": "Jane Doe", + "genre": "Adventure Fiction", + "description": "An exhilarating journey through a hidden civilization in the Amazon rainforest.", + "previous_score": 1, + "title": "The Lost City" + } + } + ] + }, + "profile": { + "shards": [] + } +} +``` + +## Next steps + +- Learn more about the [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/). +- See a comprehensive example of [reranking by a field using an externally hosted cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-cross-encoder/). +- For a tutorial that reranks results by a field using Cohere Rerank, see [Reranking search results by a field using Cohere Rerank]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-by-field/). \ No newline at end of file diff --git a/_search-plugins/search-relevance/rerank-cross-encoder.md b/_search-plugins/search-relevance/rerank-cross-encoder.md new file mode 100644 index 00000000..c3203919 --- /dev/null +++ b/_search-plugins/search-relevance/rerank-cross-encoder.md @@ -0,0 +1,127 @@ +--- +layout: default +title: Reranking using a cross-encoder model +parent: Reranking search results +grand_parent: Optimizing search quality +has_children: false +nav_order: 10 +--- + +# Reranking search results using a cross-encoder model +**Introduced 2.12** +{: .label .label-purple } + +You can rerank search results using a cross-encoder model in order to improve search relevance. To implement reranking, you need to configure a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) that runs at search time. The search pipeline intercepts search results and applies the [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/) to them. The `rerank` processor evaluates the search results and sorts them based on the new scores provided by the cross-encoder model. + +**PREREQUISITE**<br> +Before configuring a reranking pipeline, you must set up a cross-encoder model. For information about using an OpenSearch-provided model, see [Cross-encoder models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#cross-encoder-models). For information about using a custom model, see [Custom local models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). +{: .note} + +## Running a search with reranking + +To run a search with reranking, follow these steps: + +1. [Configure a search pipeline](#step-1-configure-a-search-pipeline). +1. [Create an index for ingestion](#step-2-create-an-index-for-ingestion). +1. [Ingest documents into the index](#step-3-ingest-documents-into-the-index). +1. [Search using reranking](#step-4-search-using-reranking). + +## Step 1: Configure a search pipeline + +Next, configure a search pipeline with a [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/) and specify the `ml_opensearch` rerank type. In the request, provide a model ID for the cross-encoder model and the document fields to use as context: + +```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" + ] + } + } + } + ] +} +``` +{% include copy-curl.html %} + +For more information about the request fields, see [Request fields]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/#request-body-fields). + +## Step 2: Create an index for ingestion + +In order to use the `rerank` processor defined in your pipeline, create an OpenSearch index and add the pipeline created in the previous step as the default pipeline: + +```json +PUT /my-index +{ + "settings": { + "index.search.default_pipeline" : "my_pipeline" + }, + "mappings": { + "properties": { + "passage_text": { + "type": "text" + } + } + } +} +``` +{% include copy-curl.html %} + +## Step 3: Ingest documents into the index + +To ingest documents into the index created in the previous step, send the following bulk request: + +```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" } + +``` +{% include copy-curl.html %} + +## Step 4: Search using reranking + +To perform a reranking search on your index, use any OpenSearch query and provide an additional `ext.rerank` field: + +```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" + } + } + } +} +``` +{% include copy-curl.html %} + +Alternatively, you can provide the full path to the field containing the context. For more information, see [Rerank processor example]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/#example). + +## Next steps + +- Learn more about the [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/). +- See a comprehensive example of [reranking by a field using an externally hosted cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-cross-encoder/). +- For a tutorial that uses a cross-encoder model hosted in Amazon SageMaker, see [Reranking search results using a cross-encoder in Amazon SageMaker]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-cross-encoder/). +- For a tutorial that uses a reranker model hosted in Amazon SageMaker, see [Reranking search results using a reranker in Amazon SageMaker]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-sagemaker/). +- For a tutorial that uses reranking models hosted on Amazon Bedrock, see [Reranking search results using Amazon Bedrock models]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-bedrock/). +- For a tutorial that uses Cohere Rerank on Amazon Bedrock, see [Reranking search results using Cohere Rerank on Amazon Bedrock]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-cohere-bedrock/). +- For a tutorial that uses the Cohere Rerank API, see [Reranking search results using Cohere Rerank]({{site.url}}{{site.baseurl}}/tutorials/reranking/reranking-cohere/). \ No newline at end of file diff --git a/_search-plugins/search-relevance/reranking-search-results.md b/_search-plugins/search-relevance/reranking-search-results.md index 14c41802..ea6e4dcd 100644 --- a/_search-plugins/search-relevance/reranking-search-results.md +++ b/_search-plugins/search-relevance/reranking-search-results.md @@ -1,118 +1,42 @@ --- layout: default title: Reranking search results -parent: Search relevance -has_children: false -nav_order: 60 +parent: Optimizing search quality +has_children: true +nav_order: 50 --- # Reranking search results -Introduced 2.12 +**Introduced 2.12** {: .label .label-purple } -You can rerank search results using a cross-encoder reranker in order to improve search relevance. To implement reranking, you need to configure a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) that runs at search time. The search pipeline intercepts search results and applies the [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/) to them. The `rerank` processor evaluates the search results and sorts them based on the new scores provided by the cross-encoder model. +You can rerank search results using a [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/) in order to improve search relevance. To implement reranking, you need to configure a [search pipeline]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/index/) that runs at search time. The search pipeline intercepts search results and applies the `rerank` processor to them. The `rerank` processor evaluates the search results and sorts them based on the new scores. -**PREREQUISITE**<br> -Before configuring a reranking pipeline, you must set up a cross-encoder model. For information about using an OpenSearch-provided model, see [Cross-encoder models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#cross-encoder-models). For information about using a custom model, see [Custom local models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/custom-local-models/). +You can rerank results in the following ways: + +- [Using a cross-encoder model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-cross-encoder/) +- [By a document field]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field/) +- [By a field using a cross-encoder]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-cross-encoder/) +- [By a field using a late interaction model]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/rerank-by-field-late-interaction/) + +For tutorials that rerank results using models hosted on Amazon Bedrock, Amazon SageMaker, and Cohere, see [Reranking search results tutorials]({{site.url}}{{site.baseurl}}/tutorials/reranking/). + +## Reranking in agentic search + +If you're using agentic search, see [Reranking agentic search results]({{site.url}}{{site.baseurl}}/vector-search/ai-search/agentic-search/rerank-agentic-search-results/) for information about reranking search results within agentic search pipelines. + +## Using rerank and normalization processors together + +When you use a rerank processor in conjunction with a [normalization processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/) and a hybrid query, the rerank processor alters the final document scores. This is because the rerank processor operates after the normalization processor in the search pipeline. {: .note} -## Running a search with reranking +The processing order is as follows: -To run a search with reranking, follow these steps: +- Normalization processor: This processor normalizes the document scores based on the configured normalization method. For more information, see [Normalization processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/normalization-processor/). +- Rerank processor: Following normalization, the rerank processor further adjusts the document scores. This adjustment can significantly impact the final ordering of search results. -1. [Configure a search pipeline](#step-1-configure-a-search-pipeline). -1. [Create an index for ingestion](#step-2-create-an-index-for-ingestion). -1. [Ingest documents into the index](#step-3-ingest-documents-into-the-index). -1. [Search using reranking](#step-4-search-using-reranking). +This processing order has the following implications: -## Step 1: Configure a search pipeline +- Score modification: The rerank processor modifies the scores that were initially adjusted by the normalization processor, potentially leading to different ranking results than initially expected. +- Hybrid queries: In the context of hybrid queries, where multiple types of queries and scoring mechanisms are combined, this behavior is particularly noteworthy. The combined scores from the initial query are normalized first and then reranked, resulting in a two-phase scoring modification. -Next, configure a search pipeline with a [`rerank` processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/). - -The following example request creates a search pipeline with an `ml_opensearch` rerank processor. In the request, provide a model ID for the cross-encoder model and the document fields to use as context: - -```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" - ] - } - } - } - ] -} -``` -{% include copy-curl.html %} - -For more information about the request fields, see [Request fields]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/#request-fields). - -## Step 2: Create an index for ingestion - -In order to use the rerank processor defined in your pipeline, create an OpenSearch index and add the pipeline created in the previous step as the default pipeline: - -```json -PUT /my-index -{ - "settings": { - "index.search.default_pipeline" : "my_pipeline" - }, - "mappings": { - "properties": { - "passage_text": { - "type": "text" - } - } - } -} -``` -{% include copy-curl.html %} - -## Step 3: Ingest documents into the index - -To ingest documents into the index created in the previous step, send the following bulk request: - -```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" } - -``` -{% include copy-curl.html %} - -## Step 4: Search using reranking - -To perform reranking search on your index, use any OpenSearch query and provide an additional `ext.rerank` field: - -```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" - } - } - } -} -``` -{% include copy-curl.html %} - -Alternatively, you can provide the full path to the field containing the context. For more information, see [Rerank processor example]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/rerank-processor/#example). \ No newline at end of file diff --git a/_search-plugins/search-relevance/search-configurations.md b/_search-plugins/search-relevance/search-configurations.md new file mode 100644 index 00000000..b0736846 --- /dev/null +++ b/_search-plugins/search-relevance/search-configurations.md @@ -0,0 +1,293 @@ +--- +layout: default +title: Search configurations +nav_order: 5 +parent: Search Relevance Workbench +grand_parent: Optimizing search quality +has_children: false +--- + +# Search configurations + +A search configuration defines the query pattern used to run experiments, specifying how queries should be constructed and executed. + +## Creating search configurations + +You can define a search configuration to describe how every query of a query set is run. Every search configuration has a name and consists of a query body (a query in OpenSearch query domain-specific language [DSL]) and the target index. You can optionally define a search pipeline for the search configuration. + +### Endpoint + +```json +PUT _plugins/_search_relevance/search_configurations +``` + +### Request body fields + +The following table lists the available input parameters. + +Field | Data type | Description +:--- | :--- | :--- +`name` | String | The name of the search configuration. +`description` | String | Description of the search configuration. +`query` | Object | Defines the query in OpenSearch query DSL, provided as a JSON string with the inner quotation marks escaped (for example, `"query": "{\"query\":{\"multi_match\":{...}}}"`). Use the `%queryText%` placeholder or [Mustache](https://mustache.github.io/) template variables (such as {% raw %}`{{queryText}}`{% endraw %}) to substitute query set values at runtime. For more information, see [Using Mustache templates](#using-mustache-templates). +`index` | String | The target index queried by this search configuration. +`searchPipeline` | String | Specifies an existing search pipeline. Optional. + +### Example request: Creating a search configuration + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "baseline", + "query": "{\"query\":{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title\",\"category\",\"bullets\",\"description\",\"attrs.Brand\",\"attrs.Color\"]}}}", + "description": "Current production algorithm", + "index": "ecommerce" +} +``` + +### Using Mustache templates + +Instead of the `%queryText%` placeholder, you can use [Mustache](https://mustache.github.io/) template variables in a query. If the `query` parameter contains double curly braces ({% raw %}`{{}}`{% endraw %}), OpenSearch renders the `query` as a Mustache template; otherwise, OpenSearch substitutes the `%queryText%` placeholder. Existing `%queryText%` configurations continue to work unchanged. + +When OpenSearch renders a template, the following variables are available: + +- {% raw %}`{{queryText}}`{% endraw %}: The `queryText` value from the current query set entry. +- {% raw %}`{{<field_name>}}`{% endraw %}: Any custom field from the query set entry, referenced by its field name (for example, {% raw %}`{{category}}`{% endraw %}). For more information, see [Query sets]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/query-sets/). + +OpenSearch automatically escapes substituted values, so query text that contains quotation marks or other special characters remains valid in JSON. + +Mustache partials ({% raw %}`{{>...}}`{% endraw %}) are not supported and cause the query to be rejected. +{: .note} + +For example, the following request creates a search configuration that matches the user query against the `title` field and filters the results by the `category` custom field from each query set entry: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "mustache_filter", + "query": "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"title\":\"{% raw %}{{queryText}}{% endraw %}\"}}],\"filter\":[{\"term\":{\"category\":\"{% raw %}{{category}}{% endraw %}\"}}]}}}", + "description": "Title match filtered by a category custom field", + "index": "ecommerce" +} +``` +{% include copy-curl.html %} + +## Managing search configurations + +You can retrieve or delete configurations using the following APIs. + +### Retrieve search configurations + + This API retrieves search configurations. + +#### Endpoint + +```json +GET _plugins/_search_relevance/search_configurations +GET _plugins/_search_relevance/search_configurations/{search_configuration_id} +``` + +#### Example response + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "search-relevance-search-config", + "_id": "92810080-9c5a-470f-a0ff-0eb85e7b818c", + "_score": null, + "_source": { + "id": "92810080-9c5a-470f-a0ff-0eb85e7b818c", + "name": "baseline", + "description": "Current production algorithm", + "timestamp": "2025-06-12T08:23:03.305Z", + "index": "ecommerce", + "query": """{"query":{"multi_match":{"query":"%queryText%","fields":["id","title","category","bullets","description","attrs.Brand","attrs.Color"]}}}""", + "searchPipeline": "" + }, + "sort": [ + 1749716583305 + ] + } + ] + } +} +``` + +### Path parameters + +The following table lists the available path parameters. + +| Parameter | Data type | Description | +| :--- | :--- | :--- | +| `search_configuration_id` | String | The ID of the search configuration to retrieve. Retrieves all search configurations when empty. | + +### Delete a search configuration + +You can delete a search configuration using the search configuration ID. + +#### Endpoint + +```json +DELETE _plugins/_search_relevance/search_configurations/{search_configuration_id} +``` + +#### Example request + +```json +DELETE _plugins/_search_relevance/search_configurations/bb45c4c4-48ce-461b-acbc-f154c0a17ec9 +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "_index": "search-relevance-search-config", + "_id": "92810080-9c5a-470f-a0ff-0eb85e7b818c", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 9, + "_primary_term": 1 +} +``` + +### Search for a search configuration + +You can search for available search configurations using query DSL. + +#### Endpoint + +```json +GET _plugins/_search_relevance/search_configurations/_search +POST _plugins/_search_relevance/search_configurations/_search +``` + +#### Example request: Searching for all search configurations + +```json +GET _plugins/_search_relevance/search_configurations/_search +{ + "query": + { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +#### Example request: Searching for a search configuration by name + +```json +GET _plugins/_search_relevance/search_configurations/_search +{ + "query": { + "match": { + "name": "baseline" + } + } +} +``` +{% include copy-curl.html %} + +Note that the index storing the search configurations contains several fields of the type `keyword` that require exact matching. +{: .note} + +#### Example request: Searching for a search configuration using multiple criteria + +Search for a search configuration by a specific target index and query pattern: + +```json +GET _plugins/_search_relevance/search_configurations/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "index": "ecommerce" + } + }, + { + "match": { + "query": "multi_match" + } + } + ] + } + }, + "size": 10 +} +``` +{% include copy-curl.html %} + +#### Example response + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.2086178, + "hits": [ + { + "_index": "search-relevance-search-config", + "_id": "c86af6ed-a91e-450d-a630-aa2a3c525618", + "_score": 1.2086178, + "_source": { + "id": "c86af6ed-a91e-450d-a630-aa2a3c525618", + "name": "baseline", + "description": "Current production algorithm", + "timestamp": "2026-01-26T12:11:47.657Z", + "index": "ecommerce", + "query": """{"query":{"multi_match":{"query":"%queryText%","fields":["asin","title","category","bullet_points","description","brand","color"]}}}""", + "searchPipeline": "" + } + }, + { + "_index": "search-relevance-search-config", + "_id": "a4697191-744e-404a-b869-bbefb7e753ed", + "_score": 1.2015147, + "_source": { + "id": "a4697191-744e-404a-b869-bbefb7e753ed", + "name": "baseline with title weight", + "timestamp": "2026-01-26T12:11:48.199Z", + "index": "ecommerce", + "query": """{"query":{"multi_match":{"query":"%queryText%","fields":["asin","title^25","category","bullet_points","description","brand","color"]}}}""", + "searchPipeline": "" + } + } + ] + } +} +``` diff --git a/_search-plugins/search-relevance/stats-api.md b/_search-plugins/search-relevance/stats-api.md index 3be40c70..c78a03b1 100644 --- a/_search-plugins/search-relevance/stats-api.md +++ b/_search-plugins/search-relevance/stats-api.md @@ -3,7 +3,7 @@ layout: default title: Search Relevance Stats API nav_order: 65 parent: Compare Search Results -grand_parent: Search relevance +grand_parent: Optimizing search quality has_children: false --- @@ -11,7 +11,7 @@ has_children: false Introduced 2.7 {: .label .label-purple } -The Search Relevance Stats API provides information about [Search Relevance plugin](https://github.com/opensearch-project/dashboards-search-relevance) operations. The Search Relevance plugin processes operations sent by the [Compare Search Results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance) Dashboards tool. +The Search Relevance Stats API provides information about [Search Relevance plugin](https://github.com/opensearch-project/dashboards-search-relevance) operations. The Search Relevance plugin processes operations sent by the [Compare Search Results]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/) Dashboards tool. The Search Relevance Stats API captures statistics for a one-minute interval during which it receives a request. For example, if a request is received at 23:59:59.004, statistics are collected for the 23:58:00.000--23:58:59.999 time interval. @@ -83,7 +83,7 @@ The following is the response for the preceding request: } ``` -## Response fields +## Response body fields The following table lists all response fields. diff --git a/_search-plugins/search-relevance/template-query.md b/_search-plugins/search-relevance/template-query.md new file mode 100644 index 00000000..a6457069 --- /dev/null +++ b/_search-plugins/search-relevance/template-query.md @@ -0,0 +1,215 @@ +--- +layout: default +title: Template queries +nav_order: 70 +parent: Query rewriting +grand_parent: Optimizing search quality +has_children: false +has_toc: false +--- + +# Template queries +**Introduced 2.19** +{: .label .label-purple } + +A template query allows you to create queries with dynamic placeholders that are resolved by search request processors during query execution. This is particularly useful when your query parameters need to be generated or transformed during the search process, such as when using machine learning (ML) inference to convert text into vector embeddings. + +The following search implementations benefit from using template queries: + +- Converting text input into vector embeddings for vector search +- Dynamic query parameter generation based on runtime calculations +- Complex query transformations that require intermediate processing + +Placeholders are defined using the `"${variable_name}"` syntax (note that the variables must be enclosed in quotation marks). Search request processors can generate or transform data to fill these placeholders before the query is processed. The template query acts as a container for the final executable query. + +## Example + +The following example demonstrates using a template query with an [`ml_inference` search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-request/) for semantic search. + +### Prerequisite + +Before using an `ml_inference` search request processor, you must configure an ML model. For more information about local models, see [Using ML models within OpenSearch]({{site.url}}{{site.baseurl}}/ml-commons-plugin/using-ml-models/). For more information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). + +Once you configure a model, you can test the model by sending a Predict API request: + +```json +POST /_plugins/_ml/models/mBGzipQB2gmRjlv_dOoB/_predict +{ + "parameters": { + "inputText": "happy moments" + } +} +``` +{% include copy-curl.html %} + +The response contains an `embedding` field with vector embeddings generated from the `inputText`: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "embedding": [ + 0.6328125, + 0.26953125, + 0.41796875, + -0.00579833984375, + 1.859375, + 0.2734375, + 0.130859375, + -0.001007080078125, + 0.138671875, + ...], + "inputTextTokenCount": 2 + } + } + ], + "status_code": 200 + } + ] +} +``` + +### Step 1: Create an ingest pipeline + +Create an ingest pipeline to generate vector embeddings from text fields during document indexing. The `input_map` maps document fields to model inputs. In this example, the `text` source field in a document is mapped to the `inputText` field---the expected input field for the model. The `output_map` maps model outputs to document fields. In this example, the `embedding` output field from the model is mapped to the `text_embedding` destination field in your document: + +```json +PUT /_ingest/pipeline/knn_pipeline +{ + "description": "knn_pipeline", + "processors": [ + { + "ml_inference": { + "model_id": "Sz-wFZQBUpPSu0bsJTBG", + "input_map": [ + { + "inputText": "text" + } + ], + "output_map": [ + { + "text_embedding": "embedding" + } + ] + } + } + ] +} +``` +{% include copy-curl.html %} + +### Step 2: Index a document + +Index the following document into a `template-knn-1` index: + +```json +PUT /template-knn-1/_doc/1 +{ + "text": "red shoes" +} +``` +{% include copy-curl.html %} + +To view the document, send a GET request: + +```json +GET /template-knn-1/_doc/1 +``` +{% include copy-curl.html %} + +The response shows that the embeddings generated by the model are stored in the `text_embedding` field along with the original `text`: + +```json +{ + "_index": "template-knn-1", + "_id": "1", + "_version": 2, + "_seq_no": 1, + "_primary_term": 1, + "found": true, + "_source": { + "text_embedding": [ + -0.69140625, + 0.8125, + 0.51953125, + -0.7421875, + 0.6875, + 0.4765625, + -0.34375, + ...], + "text": "red shoes" + } +} +``` + +### Step 3: Search using a template query + +Use the following template query to search the index. The `ml_inference` processor generates a vector embedding from the input text `sneakers`, replaces `${text_embedding}` with the generated vector, and searches for documents closest to the vector: + +```json +GET /template-knn-1/_search?search_pipeline=my_knn_pipeline +{ + "query": { + "template": { + "knn": { + "text_embedding": { + "vector": "${text_embedding}", + "k": 2 + } + } + } + }, + "ext": { + "ml_inference": { + "text": "sneakers" + } + } +} +``` +{% include copy-curl.html %} + +The response contains the matching document: + +```json +{ + "took": 611, + "timed_out": false, + "_shards": { + "total": 5, + "successful": 5, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.0019327316, + "hits": [ + { + "_index": "template-knn-1", + "_id": "1", + "_score": 0.0019327316, + "_source": { + "text_embedding": [ + -0.69140625, + 0.8125, + 0.51953125, + ..], + "text": "red shoes" + } + } + ] + } +} +``` + +## Related documentation + +- [Template query]({{site.url}}{{site.baseurl}}/query-dsl/specialized/template/) +- [ML inference search request processor]({{site.url}}{{site.baseurl}}/search-plugins/search-pipelines/ml-inference-search-request/) \ No newline at end of file diff --git a/_search-plugins/search-relevance/using-search-relevance-workbench.md b/_search-plugins/search-relevance/using-search-relevance-workbench.md new file mode 100644 index 00000000..1bfba502 --- /dev/null +++ b/_search-plugins/search-relevance/using-search-relevance-workbench.md @@ -0,0 +1,333 @@ +--- +layout: default +title: Search Relevance Workbench +nav_order: 20 +parent: Optimizing search quality +has_children: true +--- + +# Search Relevance Workbench +Introduced 3.1 +{: .label .label-purple } + +In search applications, tuning relevance is a constant, iterative exercise intended to provide the right search results to your end users. The tooling in Search Relevance Workbench helps search relevance engineers and business users create the best search experience possible for application users. It does this without hiding internal information, enabling engineers to experiment and investigate details as necessary. + +Search Relevance Workbench consists of a [frontend component](https://github.com/opensearch-project/dashboards-search-relevance) that simplifies the process of evaluating search quality. +The frontend uses the [OpenSearch Search Relevance plugin](https://github.com/opensearch-project/search-relevance) as a backend to manage the resources for each tool provided. For example, most use cases involve creating and using search configurations, query sets, and judgment lists. All of these resources are created, updated, deleted, and maintained by the Search Relevance plugin. When you are satisfied with the relevance improvements, you can take the output of the experimentation and manually deploy the changes into your search application. + +You can quickly analyze a single query using the [Single query comparison UI]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/compare-search-results/) before moving to more structured experiments. + +## Key relevance concepts + +Search Relevance Workbench relies on different components for the different kinds of experiments that it offers: + +* [Query set]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/query-sets/): A _query set_ is a collection of queries. These queries are used in experiments for search relevance evaluation. +* [Search configuration]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/search-configurations/): A _search configuration_ describes the pattern to use to run queries for experiments. +* [Judgment list]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/judgments/): A _judgment_ is a rating that describes the relevance of one particular document for a given query. Multiple judgments are grouped together into judgment lists. +* [Experiments]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/experiments/): An _experiment_ is a controlled test designed to assess the effectiveness of an algorithm. There are multiple types of experiments offered. + +## Available search result quality experiments + +Search Relevance Workbench offers three types of experiments: + +* [Search result comparison]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/comparing-search-results/): Compare results of two search configurations. +* [Search quality evaluation]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/evaluate-search-quality/): Evaluate the retrieval quality for one particular search configuration by calculating search quality metrics based on retrieved results and a judgment list. +* [Hybrid search optimization]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/optimize-hybrid-search/): Identify the best parameter set for your hybrid search query. + +## Creating a query set + +To compare search configurations, create a set of queries to run the search. If you have access to search behavior data adhering to the User Behavior Insights (UBI) specification, you can send a request to the `_plugins/search_relevance/query_sets/create` endpoint. + +The following example request uploads a manually defined query set to Search Relevance Workbench: + + +```json +PUT _plugins/_search_relevance/query_sets +{ + "name": "TVs", + "description": "TV queries", + "sampling": "manual", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "led tv" + } + ] +} +``` +{% include copy-curl.html %} + + +The response contains the `query_set_id` of the query set with which you'll experiment: + +```json +{ + "query_set_id": "1856093f-9245-449c-b54d-9aae7650551a", + "query_set_result": "CREATED" +} +``` + +## Creating search configurations + +Search configurations specify how each query of the query set is run. To create a search configuration, you can send a search request to the `_plugins/search_relevance/search_configurations` endpoint. +Every search configuration contains a `search_configuration_name` and a `query_body`. + +### Example: Creating two search configurations + +For your first experiment, you'll explore how adding a weight of `10` to the `title` field affects your search configuration. First, upload your current search configuration to OpenSearch: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "my_production_config", + "query": "{\"query\":{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title\",\"category\",\"bullets\",\"description\",\"attrs.Brand\",\"attrs.Color\"]}}}", + "index": "ecommerce" +} +``` +{% include copy-curl.html %} + +The response contains the search configuration ID: + +```json +{ + "search_configuration_id": "122fbde8-d593-4d71-96d4-cbe3b4977468", + "search_configuration_result": "CREATED" +} +``` + +Next, create another search configuration and apply a weight of `10` to the `title` field: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "title_boost", + "query": "{\"query\":{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title^10\",\"category\",\"bullets\",\"description\",\"attrs.Brand\",\"attrs.Color\"]}}}", + "index": "ecommerce" +} +``` +{% include copy-curl.html %} + +The response contains the ID of the boosted search configuration and indicates whether it was created successfully: + +```json +{ + "search_configuration_id": "0d687614-df5b-4b6b-8110-9d8c6d407963", + "search_configuration_result": "CREATED" +} +``` + +## Running the search result list comparison experiment + +To run your first experiment, you need a query set and two search configurations (and a corresponding index). By comparing search results, you can gauge how modifying the search configurations affects the search results. To create an experiment, send a request to the `_plugins/search_relevance/experiments` endpoint: + + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "1856093f-9245-449c-b54d-9aae7650551a", + "searchConfigurationList": ["122fbde8-d593-4d71-96d4-cbe3b4977468", "0d687614-df5b-4b6b-8110-9d8c6d407963"], + "size": 10, + "type": "PAIRWISE_COMPARISON" +} +``` +{% include copy-curl.html %} + +The response contains the experiment ID: + +```json +{ + "experiment_id": "dbae9786-6ea0-413d-a500-a14ef69ef7e1", + "experiment_result": "CREATED" +} +``` + +To retrieve the experiment results, use the returned `experiment_id`: + +```json +GET _plugins/_search_relevance/experiments/dbae9786-6ea0-413d-a500-a14ef69ef7e1 +``` +{% include copy-curl.html %} + +The response provides the detailed experiment results: + +<details open markdown="block"> + <summary> + Response + </summary> + +```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": ".plugins-search-relevance-experiment", + "_id": "dbae9786-6ea0-413d-a500-a14ef69ef7e1", + "_score": 1, + "_source": { + "id": "dbae9786-6ea0-413d-a500-a14ef69ef7e1", + "timestamp": "2025-06-14T14:02:17.347Z", + "type": "PAIRWISE_COMPARISON", + "status": "COMPLETED", + "querySetId": "1856093f-9245-449c-b54d-9aae7650551a", + "searchConfigurationList": [ + "122fbde8-d593-4d71-96d4-cbe3b4977468", + "0d687614-df5b-4b6b-8110-9d8c6d407963" + ], + "judgmentList": [], + "size": 10, + "results": [ + { + "snapshots": [ + { + "searchConfigurationId": "0d687614-df5b-4b6b-8110-9d8c6d407963", + "docIds": [ + "B01M1D0KL1", + "B07YSMD3Z9", + "B07V4CY9GZ", + "B074KFP426", + "B07S8XNWWF", + "B07XBJR7GY", + "B075FDWSHT", + "B01N2Z17MS", + "B07F1T4JFB", + "B07S658ZLH" + ] + }, + { + "searchConfigurationId": "122fbde8-d593-4d71-96d4-cbe3b4977468", + "docIds": [ + "B07Q45SP9P", + "B074KFP426", + "B07JKVKZX8", + "B07THVCJK3", + "B0874XJYW8", + "B08LVPWQQP", + "B07V4CY9GZ", + "B07X3BS3DF", + "B074PDYLCZ", + "B08CD9MKLZ" + ] + } + ], + "queryText": "led tv", + "metrics": [ + { + "metric": "jaccard", + "value": 0.11 + }, + { + "metric": "rbo50", + "value": 0.03 + }, + { + "metric": "rbo90", + "value": 0.13 + }, + { + "metric": "frequencyWeighted", + "value": 0.2 + } + ] + }, + { + "snapshots": [ + { + "searchConfigurationId": "0d687614-df5b-4b6b-8110-9d8c6d407963", + "docIds": [ + "B07X3S9RTZ", + "B07WVZFKLQ", + "B00GXD4NWE", + "B07ZKCV5K5", + "B07ZKDVHFB", + "B086VKT9R8", + "B08XLM8YK1", + "B07FPP6TB5", + "B07N1TMNHB", + "B09CDHM8W7" + ] + }, + { + "searchConfigurationId": "122fbde8-d593-4d71-96d4-cbe3b4977468", + "docIds": [ + "B07Q7VGW4Q", + "B00GXD4NWE", + "B07VML1CY1", + "B07THVCJK3", + "B07RKSV7SW", + "B010EAW8UK", + "B07FPP6TB5", + "B073G9ZD33", + "B07VXRXRJX", + "B07Q45SP9P" + ] + } + ], + "queryText": "tv", + "metrics": [ + { + "metric": "jaccard", + "value": 0.11 + }, + { + "metric": "rbo50", + "value": 0.07 + }, + { + "metric": "rbo90", + "value": 0.16 + }, + { + "metric": "frequencyWeighted", + "value": 0.2 + } + ] + } + ] + } + } + ] + } +} +``` + +</details> + +## Using Search Relevance Workbench in OpenSearch Dashboards + +You can create all Search Relevance Workbench components and visualize the experiment results in OpenSearch Dashboards. +In this example, you'll create the same experiment and review its results. + +In the left navigation pane, select **OpenSearch Plugins** > **Search Relevance** and then select **Query Set Comparison**, as shown in the following image. + +![Select Query Set Comparison Experiment]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/select_query_set_comparison.png) + +Select the query set you created (`TVs`) and the search configurations (`my_production_config`, `title_boost`), and then select **Start Evaluation**, as shown in the following image. + +![Define Query Set Comparison Experiment]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/query_set_comparison_experiment_definition.png) + +You are automatically directed to the experiment overview table, shown in the following image. + +![Experiment Overview Table]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/experiment_table_overview.png) + +To review the results, select the topmost (most recent) experiment. The experiment view page shows three elements: +1. The experiment parameters. +2. The aggregate metrics resulting from the experiment, shown in the following image. +![Aggregate Metrics for Comparison Experiment]({{site.url}}{{site.baseurl}}/images/search-relevance-workbench/aggregate_metrics_comparison_experiment.png) +3. The individual metrics per query. + +To visually assess the differences between two result sets, select a query event. diff --git a/_search-plugins/searching-data/autocomplete.md b/_search-plugins/searching-data/autocomplete.md index ecbb4ddc..8780d7f1 100644 --- a/_search-plugins/searching-data/autocomplete.md +++ b/_search-plugins/searching-data/autocomplete.md @@ -1,13 +1,13 @@ --- layout: default title: Autocomplete -parent: Searching data -nav_order: 24 +parent: Customizing search results +nav_order: 80 redirect_from: - /opensearch/search/autocomplete/ --- -# Autocomplete functionality +# Autocomplete Autocomplete shows suggestions to users while they type. @@ -250,7 +250,7 @@ As the user types, the completion suggester moves through the FST graph one char The completion suggester makes your autocomplete solution as efficient as possible and lets you have explicit control over its suggestions. -Use a dedicated field type called [`completion`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/completion), which stores the FST-like data structures in the index: +Use a dedicated field type called [`completion`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/completion/), which stores the FST-like data structures in the index: ```json PUT shakespeare @@ -685,11 +685,11 @@ GET shakespeare/_search } ``` -For more information, see the [`completion` field type documentation]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/completion). +For more information, see the [`completion` field type documentation]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/completion/). ## Search as you type -OpenSearch has a dedicated [`search_as_you_type`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/search-as-you-type) field type that is optimized for search-as-you-type functionality and can match terms using both prefix and infix completion. The `search_as_you_type` field does not require you to set up a custom analyzer or index suggestions beforehand. +OpenSearch has a dedicated [`search_as_you_type`]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/search-as-you-type/) field type that is optimized for search-as-you-type functionality and can match terms using both prefix and infix completion. The `search_as_you_type` field does not require you to set up a custom analyzer or index suggestions beforehand. First, map the field as `search_as_you_type`: @@ -1030,4 +1030,4 @@ The result is empty: } ``` -For more information, see the [`search_as_you_type` field type documentation]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/search-as-you-type). \ No newline at end of file +For more information, see the [`search_as_you_type` field type documentation]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/search-as-you-type/). \ No newline at end of file diff --git a/_search-plugins/searching-data/collapse-search.md b/_search-plugins/searching-data/collapse-search.md new file mode 100644 index 00000000..6e363693 --- /dev/null +++ b/_search-plugins/searching-data/collapse-search.md @@ -0,0 +1,403 @@ +--- +layout: default +title: Collapse search results +parent: Customizing search results +nav_order: 40 +redirect_from: + - /search-plugins/collapse-search/ +--- + +# Collapse search results + +The `collapse` parameter groups search results by a particular field value. This returns only the top document within each group, which helps reduce redundancy by eliminating duplicates. + +The `collapse` parameter requires the field being collapsed to be of either a `keyword` or a `numeric` type, have [doc values]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/doc-values/) enabled, and contain a single value in each document. OpenSearch rejects a collapse search if any matching document contains several values for the field. + +You cannot use `collapse` in a [scroll]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/#scroll-search) search or together with [`rescore`]({{site.url}}{{site.baseurl}}/query-dsl/rescore/). OpenSearch rejects these requests. To page through collapsed results, use [`search_after`](#collapse-with-search_after). +{: .note} + +--- + +## Collapsing search results + +To populate an index with data, define the index mappings and an `item` field indexed as a `keyword`. The following example request shows you how to define index mappings, populate an index, and then search it. + +#### Define index mappings + +```json +PUT /bakery-items +{ + "mappings": { + "properties": { + "item": { + "type": "keyword" + }, + "category": { + "type": "keyword" + }, + "price": { + "type": "float" + }, + "baked_date": { + "type": "date" + } + } + } +} +``` + +#### Populate an index + +```json +POST /bakery-items/_bulk +{ "index": {} } +{ "item": "Chocolate Cake", "category": "cakes", "price": 15, "baked_date": "2023-07-01T00:00:00Z" } +{ "index": {} } +{ "item": "Chocolate Cake", "category": "cakes", "price": 18, "baked_date": "2023-07-04T00:00:00Z" } +{ "index": {} } +{ "item": "Vanilla Cake", "category": "cakes", "price": 12, "baked_date": "2023-07-02T00:00:00Z" } +``` + +#### Search the index, returning all results + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "sort": ["price"] +} +``` + +This query returns the non-collapsed search results, showing all documents, including both entries for "Chocolate Cake". + +#### Search the index and collapse the results + +To group search results by the `item` field and sort them by `price`, you can use the following query: + +**Collapsed `item` field search results** + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item" + }, + "sort": ["price"] +} +``` + +**Response** + +```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": [ + { + "_index": "bakery-items", + "_id": "mISga5EB2HLDXHkv9kAr", + "_score": null, + "_source": { + "item": "Vanilla Cake", + "category": "cakes", + "price": 12, + "baked_date": "2023-07-02T00:00:00Z" + }, + "fields": { + "item": [ + "Vanilla Cake" + ] + }, + "sort": [ + 12 + ] + }, + { + "_index": "bakery-items", + "_id": "loSga5EB2HLDXHkv9kAr", + "_score": null, + "_source": { + "item": "Chocolate Cake", + "category": "cakes", + "price": 15, + "baked_date": "2023-07-01T00:00:00Z" + }, + "fields": { + "item": [ + "Chocolate Cake" + ] + }, + "sort": [ + 15 + ] + } + ] + } +} +``` + +The collapsed search results will show only one "Chocolate Cake" entry, demonstrating how the `collapse` parameter reduces redundancy. + +The `collapse` parameter affects only the top search results and does not change any aggregation results. The total number of hits shown in the response reflects all matching documents before the parameter is applied, including duplicates. However, the response doesn't indicate the exact number of unique groups formed by the operation. + +--- + +## Collapse with search_after + +The `from` and `size` parameters apply to the collapsed groups, so you can page through groups using them. For example, with `from` set to `1` and `size` set to `2`, the search skips the first group and returns the second and third groups. You can also paginate collapsed search results using the `search_after` parameter. The collapsed field and sort field must be the same, and only one sort field can be specified. + +The following example shows how to use `collapse` with `search_after`: + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item" + }, + "sort": [ + { + "item": "asc" + } + ], + "search_after": ["Chocolate Cake"] +} +``` +{% include copy-curl.html %} + +## Expanding collapsed results + +You can expand each collapsed top hit with the `inner_hits` property. For all options that you can specify in `inner_hits`, see [Inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/). + +The following example request applies `inner_hits` to retrieve the lowest-priced and most recent item, for each type of cake: + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item", + "inner_hits": [ + { + "name": "cheapest_items", + "size": 1, + "sort": ["price"] + }, + { + "name": "newest_items", + "size": 1, + "sort": [{ "baked_date": "desc" }] + } + ] + }, + "sort": ["price"] +} + +``` + +### Multiple inner hits for each collapsed hit + +To obtain several groups of inner hits for each collapsed result, you can set different criteria for each group. For example, lets request the three most recent items for every bakery item: + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item", + "inner_hits": [ + { + "name": "cheapest_items", + "size": 1, + "sort": ["price"] + }, + { + "name": "newest_items", + "size": 3, + "sort": [{ "baked_date": "desc" }] + } + ] + }, + "sort": ["price"] +} +``` + +This query searches for documents in the `cakes` category and groups the search results by the `item_name` field. For each `item_name`, it retrieves the top three lowest-priced items and the top three most recent items, sorted by `baked_date` in descending order. + +You can expand the groups by sending an additional query for each inner hit request corresponding to each collapsed hit in the response. This can significantly slow down the process if there are too many groups or inner hit requests. The `max_concurrent_group_searches` request parameter can be used to control the maximum number of concurrent searches allowed in this phase. The default is based on the number of data nodes and the default search thread pool size. + +### Second-level collapsing + +You can also collapse the inner hits of each group by specifying a `collapse` object in `inner_hits`. This returns the top document for each combination of the two fields. To demonstrate, add two kinds of cookies to the `bakery-items` index: + +```json +POST /bakery-items/_bulk?refresh=true +{ "index": {} } +{ "item": "Oatmeal Cookie", "category": "cookies", "price": 3, "baked_date": "2023-07-03T00:00:00Z" } +{ "index": {} } +{ "item": "Oatmeal Cookie", "category": "cookies", "price": 4, "baked_date": "2023-07-05T00:00:00Z" } +{ "index": {} } +{ "item": "Sugar Cookie", "category": "cookies", "price": 2, "baked_date": "2023-07-05T00:00:00Z" } +``` +{% include copy-curl.html %} + +The following request collapses the results by `category` and, within each category, collapses the inner hits by `item`. As a result, each category contains the cheapest document for each of its items: + +```json +GET /bakery-items/_search +{ + "_source": ["item", "price"], + "sort": ["price"], + "collapse": { + "field": "category", + "inner_hits": { + "name": "cheapest_per_item", + "size": 3, + "_source": ["item", "price"], + "sort": ["price"], + "collapse": { + "field": "item" + } + } + } +} +``` +{% include copy-curl.html %} + +In the response, the `cookies` group contains one document for each cookie, and the `cakes` group contains one document for each cake. The more expensive `Oatmeal Cookie` and `Chocolate Cake` documents are omitted: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + ... + "_source": { + "item": "Sugar Cookie", + "price": 2 + }, + "fields": { + "category": [ + "cookies" + ] + }, + "inner_hits": { + "cheapest_per_item": { + "hits": { + ... + "hits": [ + { + ... + "_source": { + "item": "Sugar Cookie", + "price": 2 + }, + "fields": { + "item": [ + "Sugar Cookie" + ] + } + }, + { + ... + "_source": { + "item": "Oatmeal Cookie", + "price": 3 + }, + "fields": { + "item": [ + "Oatmeal Cookie" + ] + } + } + ] + } + } + } + }, + { + ... + "_source": { + "item": "Vanilla Cake", + "price": 12 + }, + "fields": { + "category": [ + "cakes" + ] + }, + "inner_hits": { + "cheapest_per_item": { + "hits": { + ... + "hits": [ + { + ... + "_source": { + "item": "Vanilla Cake", + "price": 12 + }, + "fields": { + "item": [ + "Vanilla Cake" + ] + } + }, + { + ... + "_source": { + "item": "Chocolate Cake", + "price": 15 + }, + "fields": { + "item": [ + "Chocolate Cake" + ] + } + } + ] + } + } + } + } + ] + } +} +``` + +A second-level `collapse` object cannot contain `inner_hits`, so you cannot collapse results on more than two levels. diff --git a/_search-plugins/searching-data/did-you-mean.md b/_search-plugins/searching-data/did-you-mean.md index d88fdef9..ccc53ae3 100644 --- a/_search-plugins/searching-data/did-you-mean.md +++ b/_search-plugins/searching-data/did-you-mean.md @@ -1,29 +1,28 @@ --- layout: default title: Did-you-mean -parent: Searching data -nav_order: 25 +parent: Customizing search results +nav_order: 90 redirect_from: - /opensearch/search/did-you-mean/ --- # Did-you-mean -The `Did-you-mean` suggester shows suggested corrections for misspelled search terms. +Did-you-mean suggestions show corrections for misspelled search terms. -For example, if a user types "fliud," OpenSearch suggests a corrected search term like "fluid." You can then suggest the corrected term to the user or even automatically correct the search term. +For example, if a user types `fliud`, OpenSearch suggests a corrected search term like `fluid`. You can then suggest the corrected term to the user or even automatically correct the search term. -You can implement the `did-you-mean` suggester using one of the following methods: +You can implement did-you-mean suggestions using one of the following suggesters: - Use a [term suggester](#term-suggester) to suggest corrections for individual words. - Use a [phrase suggester](#phrase-suggester) to suggest corrections for phrases. ## Term suggester -Use the term suggester to suggest corrected spellings for individual words. -The term suggester uses an [edit distance](https://en.wikipedia.org/wiki/Edit_distance) to compute suggestions. +Use the term suggester to suggest corrected spellings for individual words. The term suggester analyzes the input text into tokens and returns suggestions separately for each token. It uses only the suggestion settings: the `query` in the same search request does not affect the suggestions. -The edit distance is the number of single-character insertions, deletions, or substitutions that need to be performed for a term to match another term. For example, to change the word "cat" to "hats", you need to substitute "h" for "c" and insert an "s", so the edit distance in this case is 2. +The term suggester uses an [_edit distance_](https://en.wikipedia.org/wiki/Edit_distance) to compute suggestions. The edit distance is the number of single-character insertions, deletions, or substitutions that need to be performed for a term to match another term. For example, to change the word "cat" to "hats", you need to substitute "h" for "c" and insert an "s", so the edit distance in this case is 2. To use the term suggester, you don't need any special field mappings for your index. By default, string field types are mapped as `text`. A `text` field is analyzed, so the `title` in the following example is tokenized into individual words. Indexing the following documents creates a `books` index where `title` is a `text` field: @@ -32,12 +31,16 @@ PUT books/_doc/1 { "title": "Design Patterns (Object-Oriented Software)" } +``` +{% include copy-curl.html %} +```json PUT books/_doc/2 { "title": "Software Architecture Patterns Explained" } ``` +{% include copy-curl.html %} To check how a string is split into tokens, you can use the `_analyze` endpoint. To apply the same analyzer that the field uses, you can specify the field's name in the `field` parameter: @@ -48,46 +51,47 @@ GET books/_analyze "field": "title" } ``` +{% include copy-curl.html %} The default analyzer (`standard`) splits a string at word boundaries, removes punctuation, and lowercases the tokens: ```json { - "tokens" : [ + "tokens": [ { - "token" : "design", - "start_offset" : 0, - "end_offset" : 6, - "type" : "<ALPHANUM>", - "position" : 0 + "token": "design", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 }, { - "token" : "patterns", - "start_offset" : 7, - "end_offset" : 15, - "type" : "<ALPHANUM>", - "position" : 1 + "token": "patterns", + "start_offset": 7, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 }, { - "token" : "object", - "start_offset" : 17, - "end_offset" : 23, - "type" : "<ALPHANUM>", - "position" : 2 + "token": "object", + "start_offset": 17, + "end_offset": 23, + "type": "<ALPHANUM>", + "position": 2 }, { - "token" : "oriented", - "start_offset" : 24, - "end_offset" : 32, - "type" : "<ALPHANUM>", - "position" : 3 + "token": "oriented", + "start_offset": 24, + "end_offset": 32, + "type": "<ALPHANUM>", + "position": 3 }, { - "token" : "software", - "start_offset" : 33, - "end_offset" : 41, - "type" : "<ALPHANUM>", - "position" : 4 + "token": "software", + "start_offset": 33, + "end_offset": 41, + "type": "<ALPHANUM>", + "position": 4 } ] } @@ -108,38 +112,39 @@ GET books/_search } } ``` +{% include copy-curl.html %} The term suggester returns a list of corrections for the input text in the `options` array: ```json { - "took" : 2, - "timed_out" : false, - "_shards" : { - "total" : 1, - "successful" : 1, - "skipped" : 0, - "failed" : 0 + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 }, - "hits" : { - "total" : { - "value" : 0, - "relation" : "eq" + "hits": { + "total": { + "value": 0, + "relation": "eq" }, - "max_score" : null, - "hits" : [ ] + "max_score": null, + "hits": [] }, - "suggest" : { - "spell-check" : [ + "suggest": { + "spell-check": [ { - "text" : "patern", - "offset" : 0, - "length" : 6, - "options" : [ + "text": "patern", + "offset": 0, + "length": 6, + "options": [ { - "text" : "patterns", - "score" : 0.6666666, - "freq" : 2 + "text": "patterns", + "score": 0.6666666, + "freq": 2 } ] } @@ -156,44 +161,47 @@ You can include several suggestions in one request. The following example uses t GET books/_search { "suggest": { - "spell-check1" : { - "text" : "patern", - "term" : { - "field" : "title" + "spell-check1": { + "text": "patern", + "term": { + "field": "title" } }, - "spell-check2" : { - "text" : "desing", - "term" : { - "field" : "title" + "spell-check2": { + "text": "desing", + "term": { + "field": "title" } } } } ``` +{% include copy-curl.html %} -To receive suggestions for the same input text in multiple fields, you can define the text globally to avoid duplication: +To run several suggesters on the same input text, define the text globally to avoid duplication. The following example returns suggestions for `patern` sorted in two different ways: ```json GET books/_search { "suggest": { - "text" : "patern", - "spell-check1" : { - "term" : { - "field" : "title" + "text": "patern", + "by-score": { + "term": { + "field": "title", + "sort": "score" } }, - "spell-check2" : { - "term" : { - "field" : "subject" + "by-frequency": { + "term": { + "field": "title", + "sort": "frequency" } } } } ``` +{% include copy-curl.html %} -If `text` is specified both at the global and individual suggestion levels, the suggestion-level value overrides the global value. ### Term suggester options @@ -201,23 +209,73 @@ You can specify the following options to the term suggester. Option | Description :--- | :--- -field | The field from which to source suggestions. Required. Can be set for each suggestion or globally. -analyzer | The analyzer with which to analyze the input text. Defaults to the analyzer configured for the `field`. -size | The maximum number of suggestions to return for each token in the input text. -sort | Specifies how suggestions should be sorted in the response. Valid values are:<br>- `score`: Sort by similarity score, then document frequency, and then the term itself.<br>- `frequency`: Sort by document frequency, then similarity score, and then the term itself. -suggest_mode | The suggest mode specifies the terms for which suggestions should be included in the response. Valid values are:<br>- `missing`: Return suggestions only for the input text terms that are not in the index. <br>- `popular`: Return suggestions only if they occur in the documents more frequently than in the original input text.<br> - `always`: Always return suggestions for each term in the input text.<br>Default is `missing`. -max_edits | The maximum edit distance for suggestions. Valid values are in the [1, 2] range. Default is 2. -prefix_length | An integer that specifies the minimum length the matched prefix must be to start returning suggestions. If the prefix of `prefix_length` is not matched, but the search term is still within the edit distance, no suggestions are returned. Default is 1. Higher values improve spellcheck performance because misspellings don’t tend to occur in the beginning of words. -min_word_length | The minimum length a suggestion must be in order to be included in the response. Default is 4. -shard_size | The maximum number of candidate suggestions to obtain from each shard. After all candidate suggestions are considered, the top `shard_size` suggestions are returned. Default is equal to the `size` value. Shard-level document frequencies may not be exact because terms may reside in different shards. If `shard_size` is larger than `size`, the document frequencies for suggestions are more accurate, at the cost of decreased performance. -max_inspections | The multiplication factor for `shard_size`. The maximum number of candidate suggestions OpenSearch inspects to find suggestions is calculated as `shard_size` multiplied by `max_inspection`. May improve accuracy at the cost of decreased performance. Default is 5. -min_doc_freq | The minimum number or percentage of documents in which a suggestion should appear for it to be returned. May improve accuracy by returning only suggestions with high shard-level document frequencies. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0 (feature disabled). -max_term_freq | The maximum number of documents in which a suggestion should appear in order for it to be returned. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0.01. Excluding high-frequency terms improves spellcheck performance because high-frequency terms are usually spelled correctly. Uses shard-level document frequencies. -string_distance | The edit distance algorithm to use to determine similarity. Valid values are:<br>- `internal`: The default algorithm that is based on the [Damerau-Levenshtein algorithm](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) but is highly optimized for comparing edit distances for terms in the index.<br> - `damerau_levenshtein`: The edit distance algorithm based on the [Damerau-Levenshtein algorithm](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance). <br>- `levenshtein`: The edit distance algorithm based on the [Levenshtein edit distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance).<br> - `jaro_winkler`: The edit distance algorithm based on the [Jaro-Winkler algorithm](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance).<br> - `ngram`: The edit distance algorithm based on character n-grams. +`field` | The field from which to source suggestions. Required. +`text` | The input text for which to return suggestions. Required. Can be set for each suggestion or globally for all suggestions in the request. If specified at both levels, the suggestion-level value is used. +`analyzer` | The analyzer with which to analyze the input text. Defaults to the analyzer configured for the `field`. +`size` | The maximum number of suggestions to return for each token in the input text. +`sort` | Specifies how suggestions should be sorted in the response. Valid values are:<br>- `score`: Sort by similarity score, then document frequency, and then the term itself.<br>- `frequency`: Sort by document frequency, then similarity score, and then the term itself. +`suggest_mode` | The suggest mode specifies the terms for which suggestions should be included in the response. Valid values are:<br>- `missing`: Return suggestions only for input terms that have zero occurrences in the specified field of the index. This check is field specific: if a term appears in other fields but not in the targeted field, it is still considered missing. Note that this mode does not consider term frequency across the entire index---only the specified field. <br>- `popular`: Return suggestions only if they occur in the documents more frequently than in the original input text.<br> - `always`: Always return suggestions for each term in the input text.<br>Default is `missing`. +`max_edits` | The maximum edit distance for suggestions. Valid values are in the [1, 2] range. Default is 2. +`prefix_length` | An integer that specifies the minimum length the matched prefix must be to start returning suggestions. If the prefix of `prefix_length` is not matched, but the search term is still within the edit distance, no suggestions are returned. Default is 1. Higher values improve spellcheck performance because misspellings don’t tend to occur in the beginning of words. +`min_word_length` | The minimum length of an input term for which suggestions are returned. Shorter input terms receive no suggestions. Default is 4. +`shard_size` | The maximum number of candidate suggestions to obtain from each shard. The top `size` suggestions from all shards are returned in the response. Default is equal to the `size` value. Shard-level document frequencies may not be exact because terms may reside in different shards. If `shard_size` is larger than `size`, the document frequencies for suggestions are more accurate, at the cost of decreased performance. +`max_inspections` | The multiplication factor for `shard_size`. The maximum number of candidate suggestions OpenSearch inspects to find suggestions is calculated as `shard_size` multiplied by `max_inspections`. May improve accuracy at the cost of decreased performance. Default is 5. +`min_doc_freq` | The minimum number or percentage of documents in which a suggestion should appear for it to be returned. May improve accuracy by returning only suggestions with high shard-level document frequencies. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0 (feature disabled). +`max_term_freq` | The maximum number of documents in which a suggestion should appear in order for it to be returned. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0.01. Excluding high-frequency terms improves spellcheck performance because high-frequency terms are usually spelled correctly. Uses shard-level document frequencies. +`string_distance` | The edit distance algorithm to use to determine similarity. Valid values are:<br>- `internal`: The default algorithm that is based on the [Damerau-Levenshtein algorithm](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) but is highly optimized for comparing edit distances for terms in the index.<br> - `damerau_levenshtein`: The edit distance algorithm based on the [Damerau-Levenshtein algorithm](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance). <br>- `levenshtein`: The edit distance algorithm based on the [Levenshtein edit distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance).<br> - `jaro_winkler`: The edit distance algorithm based on the [Jaro-Winkler algorithm](https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance).<br> - `ngram`: The edit distance algorithm based on character n-grams. + +### Requesting term suggestions using query parameters + +You can also request term suggestions using query parameters instead of a `suggest` object in the request body. Specify the field in `suggest_field`, the input text in `suggest_text`, and the suggest mode in `suggest_mode`. In this form, `suggest_mode` has no default value, so you must specify it. If you omit `suggest_text`, OpenSearch uses the value of the `q` parameter. For the full list of parameters, see [Search API query parameters]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#query-parameters). + +The following request returns suggestions for the misspelled term `patern` from the `title` field of the `books` index: + +```json +GET /books/_search?suggest_field=title&suggest_text=patern&suggest_mode=missing&size=0 +``` +{% include copy-curl.html %} + +The response contains the suggestions in a `suggest` object named after the field: + +```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": { + "title": [ + { + "text": "patern", + "offset": 0, + "length": 6, + "options": [ + { + "text": "patterns", + "score": 0.6666666, + "freq": 2 + } + ] + } + ] + } +} +``` ## Phrase suggester -To implement `did-you-mean`, use a phrase suggester. The phrase suggester is similar to the term suggester, except it uses n-gram language models to suggest whole phrases instead of individual words. To set up a phrase suggester, create a custom analyzer called `trigram` that uses a `shingle` filter and lowercases tokens. This filter is similar to the `edge_ngram` filter, but it applies to words instead of letters. Then configure the field from which you'll be sourcing suggestions with the custom analyzer you created: @@ -232,10 +290,7 @@ PUT books2 "trigram": { "type": "custom", "tokenizer": "standard", - "filter": [ - "lowercase", - "shingle" - ] + "filter": ["lowercase", "shingle"] } }, "filter": { @@ -263,6 +318,7 @@ PUT books2 } } ``` +{% include copy-curl.html %} Index the documents into the new index: @@ -271,12 +327,16 @@ PUT books2/_doc/1 { "title": "Design Patterns" } +``` +{% include copy-curl.html %} +```json PUT books2/_doc/2 { "title": "Software Architecture Patterns Explained" } ``` +{% include copy-curl.html %} Suppose the user searches for an incorrect phrase: @@ -293,37 +353,38 @@ GET books2/_search } } ``` +{% include copy-curl.html %} The phrase suggester returns the corrected phrase: ```json { - "took" : 4, - "timed_out" : false, - "_shards" : { - "total" : 1, - "successful" : 1, - "skipped" : 0, - "failed" : 0 + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 }, - "hits" : { - "total" : { - "value" : 0, - "relation" : "eq" + "hits": { + "total": { + "value": 0, + "relation": "eq" }, - "max_score" : null, - "hits" : [ ] + "max_score": null, + "hits": [] }, - "suggest" : { - "phrase-check" : [ + "suggest": { + "phrase-check": [ { - "text" : "design paterns", - "offset" : 0, - "length" : 14, - "options" : [ + "text": "design paterns", + "offset": 0, + "length": 14, + "options": [ { - "text" : "design patterns", - "score" : 0.31666178 + "text": "design patterns", + "score": 0.31666178 } ] } @@ -332,7 +393,7 @@ The phrase suggester returns the corrected phrase: } ``` -To highlight suggestions, set up the [`highlight`]({{site.url}}{{site.baseurl}}/opensearch/search/highlight) field for the phrase suggester: +To highlight suggestions, set up the [`highlight`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) field for the phrase suggester: ```json GET books2/_search @@ -352,38 +413,39 @@ GET books2/_search } } ``` +{% include copy-curl.html %} The results contain the highlighted text: ```json { - "took" : 2, - "timed_out" : false, - "_shards" : { - "total" : 1, - "successful" : 1, - "skipped" : 0, - "failed" : 0 + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 }, - "hits" : { - "total" : { - "value" : 0, - "relation" : "eq" + "hits": { + "total": { + "value": 0, + "relation": "eq" }, - "max_score" : null, - "hits" : [ ] + "max_score": null, + "hits": [] }, - "suggest" : { - "phrase-check" : [ + "suggest": { + "phrase-check": [ { - "text" : "design paterns", - "offset" : 0, - "length" : 14, - "options" : [ + "text": "design paterns", + "offset": 0, + "length": 14, + "options": [ { - "text" : "design patterns", - "highlighted" : "design <em>patterns</em>", - "score" : 0.31666178 + "text": "design patterns", + "highlighted": "design <em>patterns</em>", + "score": 0.31666178 } ] } @@ -398,27 +460,28 @@ You can specify the following options to the phrase suggester. Option | Description :--- | :--- -field | The field to use for n-gram lookups. The phrase suggester uses this field to calculate suggestion scores. Required. -gram_size | The maximum size `n` of the n-grams (shingles) in the field. If the field does not contain n-grams (shingles), omit this option or set it to 1. If the field uses a shingle filter, and `gram_size` is not set, `gram_size` is set to `max_shingle_size`. -real_word_error_likelihood | The probability that a term is misspelled, even if it exists in the dictionary. Default is 0.95 (5% of the words in the dictionary are misspelled). -confidence | The confidence level is a float factor that is multiplied by the input phrase's score to calculate a threshold score for other suggestions. Only suggestions with higher scores than the threshold are returned. A confidence level of 1.0 will only return suggestions that score higher than the input phrase. If `confidence` is set to 0, the top `size` candidates are returned. Default is 1. -max_errors | The maximum number or percentage of the terms that can be erroneous (spelled incorrectly) in order to return a suggestion. Valid values are integers that represent the number of terms or floats in the (0, 1) range that represent the percentage of the terms. Default is 1 (return only suggestions with at most one misspelled term). Setting this value to a high number can decrease performance. We recommend setting `max_errors` to a low number like 1 or 2 to reduce the time spent in suggest calls relative to the time spent in query execution. -separator | The separator for the terms in the bigram field. Defaults to the space character. -size | The number of candidate suggestions to generate for each query term. Specifying a higher value can result in terms with higher edit distances being returned. Default is 5. -analyzer | The analyzer with which to analyze the suggestion text. Defaults to the analyzer configured for the `field`. -shard_size | The maximum number of candidate suggestions to obtain from each shard. After all candidate suggestions are considered, the top `shard_size` suggestions are returned. Default is 5. -[collate](#collate-field)| Used to prune suggestions for which there are no matching documents in the index. -collate.query | Specifies a query against which suggestions are checked to prune the suggestions for which there are no matching documents in the index. -collate.prune | Specifies whether to return all suggestions. If `prune` is set to `false`, only those suggestions that have matching documents are returned. If `prune` is set to `true`, all suggestions are returned; each suggestion has an additional `collate_match` field that is `true` if the suggestion has matching documents and is `false` otherwise. Default is `false`. -highlight | Configures suggestion highlighting. Both `pre_tag` and `post_tag` values are required. -highlight.pre_tag | The starting tag for highlighting. -highlight.post_tag | The ending tag for highlighting. -[smoothing](#smoothing-models) | Smoothing model to balance the weight of the shingles that exist in the index frequently with the weight of the shingles that exist in the index infrequently. +`field` | The field to use for n-gram lookups. The phrase suggester uses this field to calculate suggestion scores. Required. +`text` | The input text for which to return suggestions. Required. Can be set for each suggestion or globally for all suggestions in the request. If specified at both levels, the suggestion-level value is used. +`gram_size` | The maximum size `n` of the n-grams (shingles) in the field. If the field does not contain n-grams (shingles), omit this option or set it to 1. If the field uses a shingle filter, and `gram_size` is not set, `gram_size` is set to `max_shingle_size`. +`real_word_error_likelihood` | The probability that a term is misspelled, even if it exists in the dictionary. Default is 0.95 (5% of the words in the dictionary are misspelled). +`confidence` | The confidence level is a float factor that is multiplied by the input phrase's score to calculate a threshold score for other suggestions. Only suggestions with higher scores than the threshold are returned. A confidence level of 1.0 will only return suggestions that score higher than the input phrase. If `confidence` is set to 0, the top `size` candidates are returned. Default is 1. +`max_errors` | The maximum number or percentage of the terms that can be erroneous (spelled incorrectly) in order to return a suggestion. Valid values are integers that represent the number of terms or floats in the (0, 1) range that represent the percentage of the terms. Default is 0.5, which allows up to half of a query's terms to be treated as misspelled. Setting this value to a high number can decrease performance. We recommend setting `max_errors` to a low number like 1 or 2 to reduce the time spent in suggest calls relative to the time spent in query execution. +`separator` | The separator for the terms in the bigram field. Defaults to the space character. +`size` | The number of candidate suggestions to generate for each query term. Specifying a higher value can result in terms with higher edit distances being returned. Default is 5. +`analyzer` | The analyzer with which to analyze the suggestion text. Defaults to the analyzer configured for the `field`. +`shard_size` | The maximum number of candidate suggestions to obtain from each shard. The top `size` suggestions from all shards are returned in the response. Default is 5. +[`collate`](#collate-field) | Used to prune suggestions for which there are no matching documents in the index. +`collate.query` | Specifies a query against which suggestions are checked to prune the suggestions for which there are no matching documents in the index. +`collate.prune` | Specifies whether to return all suggestions. If `prune` is set to `false`, only those suggestions that have matching documents are returned. If `prune` is set to `true`, all suggestions are returned; each suggestion has an additional `collate_match` field that is `true` if the suggestion has matching documents and is `false` otherwise. Default is `false`. +`highlight` | Configures suggestion highlighting. Both `pre_tag` and `post_tag` values are required. The tags are placed around each changed token. If several consecutive tokens are changed, the tags are placed around the whole group, for example, `<em>design patterns</em>`. +`highlight.pre_tag` | The starting tag for highlighting. +`highlight.post_tag` | The ending tag for highlighting. +[`smoothing`](#smoothing-models) | Smoothing model to balance the weight of the shingles that exist in the index frequently with the weight of the shingles that exist in the index infrequently. ### Collate field -To filter out spellchecked suggestions that will not return any results, you can use the `collate` field. This field contains a scripted query that is run for each returned suggestion. See [Search templates]({{site.url}}{{site.baseurl}}/opensearch/search-template) for information on constructing a templated query. You can specify the current suggestion using the `{% raw %}{{suggestion}}{% endraw %}` variable, or you can pass your own template parameters in the `params` field (the suggestion value will be added to the variables you specify). +To filter out spellchecked suggestions that will not return any results, you can use the `collate` field. This field contains a scripted query that is run for each returned suggestion. See [Search templates]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search-template/) for information about constructing a templated query. You can specify the current suggestion using the `{% raw %}{{suggestion}}{% endraw %}` variable, or you can pass your own template parameters in the `params` field (the suggestion value will be added to the variables you specify). The collate query for a suggestion is run only on the shard from which the suggestion was sourced. The query is required. @@ -434,10 +497,10 @@ GET books2/_search "text": "design paterns", "phrase": { "field": "title.trigram", - "collate" : { - "query" : { + "collate": { + "query": { "source": { - "match_phrase" : { + "match_phrase": { "title": "{{suggestion}}" } } @@ -449,38 +512,39 @@ GET books2/_search } } ``` +{% include copy-curl.html %} The resulting suggestion contains the `collate_match` field set to `true`, which means the `match_phrase` query will return matching documents for the suggestion: ```json { - "took" : 7, - "timed_out" : false, - "_shards" : { - "total" : 1, - "successful" : 1, - "skipped" : 0, - "failed" : 0 + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 }, - "hits" : { - "total" : { - "value" : 0, - "relation" : "eq" + "hits": { + "total": { + "value": 0, + "relation": "eq" }, - "max_score" : null, - "hits" : [ ] + "max_score": null, + "hits": [] }, - "suggest" : { - "phrase-check" : [ + "suggest": { + "phrase-check": [ { - "text" : "design paterns", - "offset" : 0, - "length" : 14, - "options" : [ + "text": "design paterns", + "offset": 0, + "length": 14, + "options": [ { - "text" : "design patterns", - "score" : 0.56759655, - "collate_match" : true + "text": "design patterns", + "score": 0.56759655, + "collate_match": true } ] } @@ -498,12 +562,16 @@ The following smoothing models are supported. Model | Description :--- | :--- -stupid_backoff | Backs off to lower-order n-gram models if the higher-order n-gram count is 0 and multiplies the lower-order n-gram model by a constant factor (`discount`). This is the default smoothing model. -stupid.backoff.discount | The factor by which to multiply the lower-order n-gram model. Optional. Default is 0.4. -laplace | Uses additive smoothing, adding a constant `alpha` to all counts to balance weights. -laplace.alpha | The constant added to all counts to balance weights, typically 1.0 or smaller. Optional. Default is 0.5. +`stupid_backoff` | Backs off to lower-order n-gram models if the higher-order n-gram count is 0 and multiplies the lower-order n-gram model by a constant factor (`discount`). This is the default smoothing model. +`stupid_backoff.discount` | The factor by which to multiply the lower-order n-gram model. Optional. Default is 0.4. +`laplace` | Uses additive smoothing, adding a constant `alpha` to all counts to balance weights. +`laplace.alpha` | The constant added to all counts to balance weights, typically 1.0 or smaller. Optional. Default is 0.5. +`linear` | Calculates the score as a weighted average of the trigram, bigram, and unigram scores. Specify the weights in `trigram_lambda`, `bigram_lambda`, and `unigram_lambda`. The weights must add up to 1. A weight that you omit is set to 0. +`linear.trigram_lambda` | The weight of trigrams. +`linear.bigram_lambda` | The weight of bigrams. +`linear.unigram_lambda` | The weight of unigrams. -By default, OpenSearch uses the Stupid Backoff model—a simple algorithm that starts with the shingles of the highest order and takes lower-order shingles if higher-order shingles are not found. For example, if you set up the phrase suggester to have 3-grams, 2-grams, and 1-grams, the Stupid Backoff model first inspects the 3-grams. If there are no 3-grams, it inspects 2-grams but multiplies the score by the `discount` factor. If there are no 2-grams, it inspects 1-grams but again multiplies the score by the `discount` factor. The Stupid Backoff model works well in most cases. If you need to choose the Laplace smoothing model, specify it in the `smoothing` parameter: +By default, OpenSearch uses the Stupid Backoff model---a simple algorithm that starts with the shingles of the highest order and takes lower-order shingles if higher-order shingles are not found. For example, if you set up the phrase suggester to have 3-grams, 2-grams, and 1-grams, the Stupid Backoff model first inspects the 3-grams. If there are no 3-grams, it inspects 2-grams but multiplies the score by the `discount` factor. If there are no 2-grams, it inspects 1-grams but again multiplies the score by the `discount` factor. The Stupid Backoff model works well in most cases. If you need to choose the Laplace smoothing model, specify it in the `smoothing` parameter: ```json GET books2/_search @@ -513,10 +581,10 @@ GET books2/_search "text": "design paterns", "phrase": { "field": "title.trigram", - "size" : 1, - "smoothing" : { - "laplace" : { - "alpha" : 0.7 + "size": 1, + "smoothing": { + "laplace": { + "alpha": 0.7 } } } @@ -524,6 +592,7 @@ GET books2/_search } } ``` +{% include copy-curl.html %} ### Candidate generators @@ -552,19 +621,225 @@ GET books2/_search } } ``` +{% include copy-curl.html %} -You can specify the following direct generator options. +Direct generators require a constant prefix: by default, the first character of a term must be spelled correctly for the generator to suggest a correction (`prefix_length` is `1`). To also correct misspellings at the beginning of a word, add a second generator that uses a field indexed with the `reverse` token filter. The `pre_filter` reverses the characters of each input term before the generator searches for candidates, so the generator compares terms starting from their last character. The `post_filter` then restores the original character order of each candidate. -Option | Description +Create a `books3` index that contains a `title.trigram` subfield for the phrase suggester and a `title.reverse` subfield indexed with a `reverse` analyzer: + +```json +PUT books3 +{ + "settings": { + "index": { + "analysis": { + "analyzer": { + "trigram": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "shingle"] + }, + "reverse": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "reverse"] + } + }, + "filter": { + "shingle": { + "type": "shingle", + "min_shingle_size": 2, + "max_shingle_size": 3 + } + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "fields": { + "trigram": { + "type": "text", + "analyzer": "trigram" + }, + "reverse": { + "type": "text", + "analyzer": "reverse" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index the documents into the new index: + +```json +PUT books3/_doc/1 +{ + "title": "Design Patterns" +} +``` +{% include copy-curl.html %} + +```json +PUT books3/_doc/2?refresh=true +{ + "title": "Software Architecture Patterns Explained" +} +``` +{% include copy-curl.html %} + +The following request contains the misspelling `esign`, which is missing its first letter. A single generator on `title.trigram` returns no suggestions for this text. The second generator finds `design` by searching for the reversed term: + +```json +GET books3/_search +{ + "suggest": { + "text": "esign patterns", + "phrase-check": { + "phrase": { + "field": "title.trigram", + "size": 1, + "direct_generator": [ + { + "field": "title.trigram", + "suggest_mode": "always" + }, + { + "field": "title.reverse", + "suggest_mode": "always", + "pre_filter": "reverse", + "post_filter": "reverse" + } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the corrected phrase: + +```json +{ + ... + "suggest": { + "phrase-check": [ + { + "text": "esign patterns", + "offset": 0, + "length": 14, + "options": [ + { + "text": "design patterns", + "score": 0.33112788 + } + ] + } + ] + } +} +``` + +You can specify the following fields in the `direct_generator` object. + +Field | Description :--- | :--- -field | The field from which to source suggestions. Required. Can be set for each suggestion or globally. -size | The maximum number of suggestions to return for each token in the input text. -suggest_mode | The suggest mode specifies the terms for which suggestions generated on each shard should be included. The suggest mode is applied to suggestions for each shard and is not checked when combining suggestions from different shards. Therefore, if the suggest mode is `missing`, suggestions will be returned if the term is missing from one shard but exists on another shard. Valid values are:<br>- `missing`: Return suggestions only for the input text terms that are not in the shard. <br>- `popular`: Return suggestions only if they occur in the documents more frequently than in the original input text on the shard.<br>- `always`: Always return suggestions.<br>Default is `missing`. -max_edits | The maximum edit distance for suggestions. Valid values are in the [1, 2] range. Default is 2. -prefix_length | An integer that specifies the minimum length the matched prefix must be to start returning suggestions. If the prefix of `prefix_length` is not matched but the search term is still within the edit distance, no suggestions are returned. Default is 1. Higher values improve spellcheck performance because misspellings don’t tend to occur in the beginning of words. -min_word_length | The minimum length a suggestion must be in order to be included. Default is 4. -max_inspections | The multiplication factor for `shard_size`. The maximum number of candidate suggestions OpenSearch inspects to find suggestions is calculated as `shard_size` multiplied by `max_inspection`. May improve accuracy at the cost of decreased performance. Default is 5. -min_doc_freq | The minimum number or percentage of documents in which a suggestion should appear in order for it to be returned. May improve accuracy by returning only suggestions with high shard-level document frequencies. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0 (feature disabled). -max_term_freq | The maximum number of documents in which a suggestion should appear in order for it to be returned. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0.01. Excluding high-frequency terms improves spellcheck performance because high-frequency terms are usually spelled correctly. Uses shard-level document frequencies. -pre_filter | An analyzer that is applied to each input text token passed to the generator before a suggestion is generated. -post_filter | An analyzer that is applied to each generated suggestion before it is passed to the phrase scorer. +`field` | The field from which to source suggestions. Required. +`size` | The maximum number of suggestions to return for each token in the input text. +`suggest_mode` | The suggest mode specifies the terms for which suggestions generated on each shard should be included. The suggest mode is applied to suggestions for each shard and is not checked when combining suggestions from different shards. Therefore, if the suggest mode is `missing`, suggestions will be returned if the term is missing from one shard but exists on another shard. Valid values are:<br>- `missing`: Return suggestions only for the input text terms that are not in the shard. <br>- `popular`: Return suggestions only if they occur in the documents more frequently than in the original input text on the shard.<br>- `always`: Always return suggestions.<br>Default is `missing`. +`max_edits` | The maximum edit distance for suggestions. Valid values are in the [1, 2] range. Default is 2. +`prefix_length` | An integer that specifies the minimum length the matched prefix must be to start returning suggestions. If the prefix of `prefix_length` is not matched but the search term is still within the edit distance, no suggestions are returned. Default is 1. Higher values improve spellcheck performance because misspellings don’t tend to occur in the beginning of words. +`min_word_length` | The minimum length of an input term for which candidates are generated. Default is 4. +`max_inspections` | The multiplication factor for `shard_size`. The maximum number of candidate suggestions OpenSearch inspects to find suggestions is calculated as `shard_size` multiplied by `max_inspections`. May improve accuracy at the cost of decreased performance. Default is 5. +`min_doc_freq` | The minimum number or percentage of documents in which a suggestion should appear in order for it to be returned. May improve accuracy by returning only suggestions with high shard-level document frequencies. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0 (feature disabled). +`max_term_freq` | The maximum number of documents in which a suggestion should appear in order for it to be returned. Valid values are integers that represent the document frequency or floats in the [0, 1] range that represent the percentage of documents. Default is 0.01. Excluding high-frequency terms improves spellcheck performance because high-frequency terms are usually spelled correctly. Uses shard-level document frequencies. +`pre_filter` | An analyzer that is applied to each input text token passed to the generator before a suggestion is generated. +`post_filter` | An analyzer that is applied to each generated suggestion before it is passed to the phrase scorer. + +## Including suggester types in the response + +By default, each suggestion in the response is identified only by the name that you give the suggester in the request. If your application needs to know which type of suggester produced a result, for example, to choose how to parse it, add the `typed_keys` query parameter to the request. OpenSearch then prefixes each suggestion name with the suggester type and a `#` separator. + +The following request runs a term suggester and a phrase suggester on the same input text and includes the suggester types in the response: + +```json +GET /books/_search?typed_keys=true +{ + "suggest": { + "text": "desing paterns", + "title-terms": { + "term": { + "field": "title" + } + }, + "title-phrase": { + "phrase": { + "field": "title" + } + } + } +} +``` +{% include copy-curl.html %} + +In the response, the suggestions are named `term#title-terms` and `phrase#title-phrase`: + +```json +{ + ... + "suggest": { + "phrase#title-phrase": [ + { + "text": "desing paterns", + "offset": 0, + "length": 14, + "options": [ + { + "text": "desing patterns", + "score": 0.13261011 + }, + { + "text": "design paterns", + "score": 0.109846905 + } + ] + } + ], + "term#title-terms": [ + { + "text": "desing", + "offset": 0, + "length": 6, + "options": [ + { + "text": "design", + "score": 0.8333333, + "freq": 1 + } + ] + }, + { + "text": "paterns", + "offset": 7, + "length": 7, + "options": [ + { + "text": "patterns", + "score": 0.85714287, + "freq": 2 + } + ] + } + ] + } +} +``` + +The `typed_keys` parameter also adds type prefixes to aggregation names in the response. diff --git a/_search-plugins/searching-data/highlight.md b/_search-plugins/searching-data/highlight.md index 97d2b0a3..dea0f072 100644 --- a/_search-plugins/searching-data/highlight.md +++ b/_search-plugins/searching-data/highlight.md @@ -1,8 +1,8 @@ --- layout: default title: Highlight query matches -parent: Searching data -nav_order: 23 +parent: Customizing search results +nav_order: 70 redirect_from: - /opensearch/search/highlight/ --- @@ -120,15 +120,95 @@ The `highlight` parameter highlights the original terms even when using synonyms To highlight the search terms, the highlighter needs the start and end character offsets of each term. The offsets mark the term's position in the original text. The highlighter can obtain the offsets from the following sources: -- **Postings**: When documents are indexed, OpenSearch creates an inverted search index—a core data structure used to search for documents. Postings represent the inverted search index and store the mapping of each analyzed term to the list of documents in which it occurs. If you set the `index_options` parameter to `offsets` when mapping a [text field]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/text), OpenSearch adds each term's start and end character offsets to the inverted index. During highlighting, the highlighter reruns the original query directly on the postings to locate each term. Thus, storing offsets makes highlighting more efficient for large fields because it does not require reanalyzing the text. Storing term offsets requires additional disk space, but uses less disk space than storing term vectors. +- **Postings**: When documents are indexed, OpenSearch creates an inverted search index—a core data structure used to search for documents. Postings represent the inverted search index and store the mapping of each analyzed term to the list of documents in which it occurs. If you set the `index_options` parameter to `offsets` when mapping a [text field]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/text/), OpenSearch adds each term's start and end character offsets to the inverted index. During highlighting, the highlighter reruns the original query directly on the postings to locate each term. Thus, storing offsets makes highlighting more efficient for large fields because it does not require reanalyzing the text. Storing term offsets requires additional disk space, but uses less disk space than storing term vectors. - [**Term vectors**]: If you set the [`term_vector` parameter]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/text#term-vector-parameter) to `with_positions_offsets` when mapping a text field, the highlighter uses the `term_vector` to highlight the field. Storing term vectors requires the most disk space. However, it makes highlighting faster for fields larger than 1 MB and for multi-term queries like prefix or wildcard because term vectors provide access to the dictionary of terms for each document. -- **Text reanalysis**: In the absence of both postings and term vectors, the highlighter reanalyzes text in order to highlight it. For every document and every field that needs highlighting, the highlighter creates a small in-memory index and reruns the original query through Lucene’s query execution planner to access low-level match information for the current document. Reanalyzing the text works well in most use cases. However, this method is more memory and time intensive for large fields. +- **Text reanalysis**: In the absence of both postings and term vectors, the highlighter reanalyzes text in order to highlight it. For every document and every field that needs highlighting, the highlighter creates a small in-memory index and reruns the original query through Lucene's query execution planner to access low-level match information for the current document. Reanalyzing the text works well in most use cases. However, this method is more memory and time intensive for large fields. + +## Fragmenting and scoring text + +To build a highlight, a highlighter splits the field text into fragments, scores the fragments against the query, and returns the best-scoring fragments with the matching terms enclosed in the highlighting tags. The highlighter types differ in the following ways: + +- Splitting text into fragments: The `plain` highlighter splits the text purely by length: it starts a new fragment each time the text exceeds the next multiple of `fragment_size`. As a result, a fragment can start or end in the middle of a sentence or with a punctuation mark. The `unified` and `fvh` highlighters use sentence boundaries, so a fragment contains whole sentences when `fragment_size` allows. +- Scoring fragments: The `plain` highlighter scores a fragment by the number of unique query terms it contains, where each term contributes its boost (by default, 1). The `fvh` highlighter counts every occurrence of a query term, not only unique terms. The `unified` highlighter scores fragments using the BM25 algorithm. Use the `number_of_fragments` option to specify how many of the best fragments to return. +- Highlighting terms: Highlighters extract the individual terms, phrases, and prefixes from the query and highlight them in the selected fragments. They do not evaluate the Boolean logic of the query. For more information, see [Query limitations](#query-limitations). + +For example, create an index containing a product review: + +```json +PUT /product-reviews +{ + "mappings": { + "properties": { + "review": { + "type": "text", + "analyzer": "english" + } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /product-reviews/_doc/1?refresh=true +{ + "review": "The tent kept us dry during two nights of heavy rain. Setting it up took ten minutes. The only problem was the zipper on the tent door, which jammed twice. Overall, a great tent for the price." +} +``` +{% include copy-curl.html %} + +The following request highlights `tent` using the `plain` highlighter with a `fragment_size` of 40 characters: + +```json +GET /product-reviews/_search +{ + "query": { + "match": { + "review": "tent" + } + }, + "highlight": { + "number_of_fragments": 3, + "fields": { + "review": { + "type": "plain", + "fragment_size": 40 + } + } + } +} +``` +{% include copy-curl.html %} + +The `plain` highlighter splits the text by length, so the third fragment starts with the period that ends the preceding sentence: + +```json +"highlight": { + "review": [ + "The <em>tent</em> kept us dry during two nights", + " on the <em>tent</em> door, which jammed twice", + ". Overall, a great <em>tent</em> for the price." + ] +} +``` + +If you run the same request using the `unified` highlighter, each fragment starts at the beginning of a sentence: + +```json +"highlight": { + "review": [ + "The <em>tent</em> kept us dry during two nights of", + "The only problem was the zipper on the <em>tent</em>", + "Overall, a great <em>tent</em> for the price." + ] +} +``` ## Highlighter types -OpenSearch supports three highlighter implementations: `plain`, `unified`, and `fvh` (Fast Vector Highlighter). +OpenSearch supports four highlighter implementations: `plain`, `unified`, `fvh` (Fast Vector Highlighter), and `semantic`. The following table lists the methods of obtaining the offsets for each highlighter. @@ -137,6 +217,7 @@ Highlighter | Method of obtaining offsets [`unified`](#the-unified-highlighter) | Term vectors if `term_vector` is set to `with_positions_offsets`,<br> postings if `index_options` is set to `offsets`, <br> text reanalysis otherwise. [`fvh`](#the-fvh-highlighter) | Term vectors. [`plain`](#the-plain-highlighter) | Text reanalysis. +[`semantic`](#the-semantic-highlighter) | Model inference. ### Setting the highlighter type @@ -164,47 +245,222 @@ The `unified` highlighter is based on the Lucene Unified Highlighter and is the ### The `fvh` highlighter -The `fvh` highlighter is based on the Lucene Fast Vector Highlighter. To use this highlighter, you need to store term vectors with positions offsets, which increases the index size. The `fvh` highlighter can combine matched terms from multiple fields into one result. It can also assign weights to matches depending on their positions; thus, you can sort phrase matches above term matches when highlighting a query that boosts phrase matches over term matches. Additionally, you can configure the `fvh` highlighter to select the boundaries of a returned text fragment, and you can highlight multiple words with different tags. +The `fvh` highlighter is based on the Lucene Fast Vector Highlighter. To use this highlighter, you need to store term vectors with positions offsets, which increases the index size. The `fvh` highlighter can combine matched terms from multiple fields into one result. It can also assign weights to matches depending on their positions; thus, you can sort phrase matches higher than term matches when highlighting a query that boosts phrase matches over term matches. Additionally, you can configure the `fvh` highlighter to select the boundaries of a returned text fragment, and you can highlight multiple words with different tags. ### The `plain` highlighter The `plain` highlighter is based on the standard Lucene highlighter. It requires the highlighted fields to be stored either individually or in the `_source` field. The `plain` highlighter mirrors the query matching logic, in particular word importance and positions in phrase queries. It works for most use cases but may be slow for large fields because it has to reanalyze the text to be highlighted. +### The `semantic` highlighter +**Introduced 3.0** +{: .label .label-purple } + +The `semantic` highlighter uses machine learning (ML) models to identify and highlight the most semantically relevant sentences or passages within a text field, based on the query's meaning. This goes beyond traditional lexical matching offered by other highlighters. It does not rely on offsets from postings or term vectors but instead uses a deployed ML model (specified by the `model_id`) to perform inference on the field content. This approach allows you to highlight contextually relevant text even when exact terms don't match the query. Highlighting is performed at the sentence level. + +The `semantic` highlighter supports two processing modes: + +- **Single inference mode (default)**: Processes each document individually using one ML inference call per document. Supports both local and externally hosted models. +- [**Batch inference mode**](#batch-inference-mode): Processes all documents in a single ML inference call, significantly improving performance for multi-document results. + +For production environments, we recommend using externally hosted models with batch inference enabled for optimal performance and scalability. +{: .tip} + +Before using the `semantic` highlighter, you must configure and deploy a sentence highlighting model. For more information about using ML models in OpenSearch, see [Integrating ML models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/integrating-ml-models/). For information about OpenSearch-provided sentence highlighting models, see [Semantic sentence highlighting models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/pretrained-models/#semantic-sentence-highlighting-models). +{: .note} + +#### Basic usage (single inference mode) + +To use the `semantic` highlighter, set the `type` to `semantic` in the `fields` object and provide the `model_id` of the deployed sentence transformer or question-answering model within the global `highlight.options` object. The following example uses a `neural` query to find documents related to "treatments for neurodegenerative diseases" and then applies semantic highlighting using the specified `sentence_model_id`: + +```json +POST /neural-search-index/_search +{ + "_source": { + "excludes": ["text_embedding"] + }, + "query": { + "neural": { + "text_embedding": { + "query_text": "treatments for neurodegenerative diseases", + "model_id": "your-text-embedding-model-id", + "k": 5 + } + } + }, + "highlight": { + "fields": { + "text": { + "type": "semantic" + } + }, + "options": { + "model_id": "your-sentence-model-id" + } + } +} +``` +{% include copy-curl.html %} + +The response includes a `highlight` object for each hit, indicating the most semantically relevant sentence by emphasizing it with <em> tags: + +```json +{ + "took": 628, + "timed_out": false, + "_shards": { ... }, + "hits": { + "total": { "value": 5, "relation": "eq" }, + "max_score": 0.4841726, + "hits": [ + { + "_index": "neural-search-index", + "_id": "srL7G5YBmDiZSe-G2pDc", + "_score": 0.4841726, + "_source": { + "text": "Alzheimer's disease is a progressive neurodegenerative disorder characterized by accumulation of amyloid-beta plaques and neurofibrillary tangles in the brain. Early symptoms include short-term memory impairment, followed by language difficulties, disorientation, and behavioral changes. While traditional treatments such as cholinesterase inhibitors and memantine provide modest symptomatic relief, they do not alter disease progression. Recent clinical trials investigating monoclonal antibodies targeting amyloid-beta, including aducanumab, lecanemab, and donanemab, have shown promise in reducing plaque burden and slowing cognitive decline. Early diagnosis using biomarkers such as cerebrospinal fluid analysis and PET imaging may facilitate timely intervention and improved outcomes." + }, + "highlight": { + "text": [ + "Alzheimer's disease is a progressive neurodegenerative disorder ... <em>Recent clinical trials investigating monoclonal antibodies targeting amyloid-beta, including aducanumab, lecanemab, and donanemab, have shown promise in reducing plaque burden and slowing cognitive decline.</em> Early diagnosis using biomarkers ..." + ] + } + }, + // ... other hits with highlighted sentences ... + ] + } +} +``` + +For a step-by-step guide, see [Using semantic highlighting]({{site.url}}{{site.baseurl}}/tutorials/vector-search/semantic-highlighting-tutorial/). + +#### Batch inference mode +**Introduced 3.3** +{: .label .label-purple } + +To improve performance when highlighting multiple documents, enable batch inference mode. Batch inference mode processes all matching documents in a single ML model inference call, reducing latency and improving throughput compared to single inference mode (which makes one call per document). + +Batch inference mode requires an externally hosted model with batch processing capabilities. Local models do not support batch inference. For information about externally hosted models, see [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/). +{: .note} + +First, configure the cluster setting (one-time setup): + +```json +PUT _cluster/settings +{ + "persistent": { + "search.pipeline.enabled_system_generated_factories": ["semantic-highlighter"] + } +} +``` +{% include copy-curl.html %} + +Then set `ext.semantic_highlighting_batch` to `true` at the request level. This enables batch inference for every highlight field configured as `type: semantic` in the request. + +The following example enables batch semantic highlighting for a top-level field: + +```json +POST /neural-search-index/_search +{ + "_source": { + "excludes": ["text_embedding"] + }, + "query": { + "neural": { + "text_embedding": { + "query_text": "treatments for neurodegenerative diseases", + "model_id": "your-text-embedding-model-id", + "k": 5 + } + } + }, + "highlight": { + "fields": { + "text": { + "type": "semantic" + } + }, + "options": { + "model_id": "your-remote-semantic-highlighting-model-id" + } + }, + "ext": { + "semantic_highlighting_batch": true + } +} +``` +{% include copy-curl.html %} + +The following example enables batch semantic highlighting for a field inside `inner_hits`: + +```json +POST /neural-search-index/_search +{ + "query": { + "nested": { + "path": "chunks", + "query": { + "match": { "chunks.text": "treatments for neurodegenerative diseases" } + }, + "inner_hits": { + "size": 5, + "highlight": { + "fields": { + "chunks.text": { "type": "semantic" } + }, + "options": { + "model_id": "your-remote-semantic-highlighting-model-id" + } + } + } + } + }, + "ext": { + "semantic_highlighting_batch": true + } +} +``` +{% include copy-curl.html %} + +Batch inference provides responses in the same format as single inference. + ## Highlighting options The following table describes the highlighting options you can specify on a global or field level. Field-level settings override global settings. Option | Description :--- | :--- -type | Specifies the highlighter to use. Valid values are `unified`, `fvh`, and `plain`. Default is `unified`. -fields | Specifies the fields to search for text to be highlighted. Supports wildcard expressions. If you use wildcards, only `text` and `keyword` fields are highlighted. For example, you can set `fields` to `my_field*` to include all `text` and `keyword` fields that start with the prefix `my_field`. -force_source | Specifies that field values for highlighting should be obtained from the `_source` field rather than from stored field values. Default is `false`. -require_field_match | Specifies whether to highlight only fields that contain a search query match. Default is `true`. To highlight all fields, set this option to `false`. -pre_tags | Specifies the HTML start tags for the highlighted text as an array of strings. -post_tags | Specifies the HTML end tags for the highlighted text as an array of strings. -tags_schema | If you set this option to `styled`, OpenSearch uses the built-in tag schema. In this schema, the `pre_tags` are `<em class="hlt1">`, `<em class="hlt2">`, `<em class="hlt3">`, `<em class="hlt4">`, `<em class="hlt5">`, `<em class="hlt6">`, `<em class="hlt7">`, `<em class="hlt8">`, `<em class="hlt9">`, and `<em class="hlt10">`, and the `post_tags` is `</em>`. -boundary_chars | All boundary characters combined in a string.<br> Default is `".,!? \t\n"`. -boundary_scanner | Valid only for the `unified` and `fvh` highlighters. Specifies whether to split the highlighted fragments into sentences, words, or characters. Valid values are the following:<br>- `sentence`: Split highlighted fragments at sentence boundaries, as defined by the [BreakIterator](https://docs.oracle.com/javase/8/docs/api/java/text/BreakIterator.html). You can specify the BreakIterator's locale in the `boundary_scanner_locale` option. <br>- `word`: Split highlighted fragments at word boundaries, as defined by the [BreakIterator](https://docs.oracle.com/javase/8/docs/api/java/text/BreakIterator.html). You can specify the BreakIterator's locale in the `boundary_scanner_locale` option.<br>- `chars`: Split highlighted fragments at any character listed in `boundary_chars`. Valid only for the `fvh` highlighter. -boundary_scanner_locale | Provides a [locale](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html) for the `boundary_scanner`. Valid values are language tags (for example, `"en-US"`). Default is [Locale.ROOT](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#ROOT). -boundary_max_scan | Controls how far to scan for boundary characters when the `boundary_scanner` parameter for the `fvh` highlighter is set to `chars`. Default is 20. -encoder | Specifies whether the highlighted fragment should be HTML encoded before it is returned. Valid values are `default` (no encoding) or `html` (first escape the HTML text and then insert the highlighting tags). For example, if the field text is `<h3>Hamlet</h3>` and the `encoder` is set to `html`, the highlighted text is `"<h3><em>Hamlet</em></h3>"`. -fragmenter | Specifies how to split text into highlighted fragments. Valid only for the `plain` highlighter. Valid values are the following:<br>- `span` (default): Splits text into fragments of the same size but tries not to split text between highlighted terms. <br>- `simple`: Splits text into fragments of the same size. -fragment_offset | Specifies the character offset from which you want to start highlighting. Valid for the `fvh` highlighter only. -fragment_size | The size of a highlighted fragment, specified as the number of characters. If `number_of_fragments` is set to 0, `fragment_size` is ignored. Default is 100. -number_of_fragments| The maximum number of returned fragments. If `number_of_fragments` is set to 0, OpenSearch returns the highlighted contents of the entire field. Default is 5. -order | The sort order for the highlighted fragments. Set `order` to `score` to sort fragments by relevance. Each highlighter has a different algorithm for calculating relevance scores. Default is `none`. -highlight_query | Specifies that matches for a query other than the search query should be highlighted. The `highlight_query` option is useful when you use a faster query to get document matches and a slower query (for example, `rescore_query`) to refine the results. We recommend to include the search query as part of the `highlight_query`. -matched_fields | Combines matches from different fields to highlight one field. The most common use case for this functionality is highlighting text that is analyzed in different ways and kept in multi-fields. All fields in the `matched_fields` list must have the `term_vector` field set to `with_positions_offsets`. The field in which the matches are combined is the only loaded field, so it is beneficial to set its `store` option to `yes`. Valid only for the `fvh` highlighter. -no_match_size | Specifies the number of characters, starting from the beginning of the field, to return if there are no matching fragments to highlight. Default is 0. -phrase_limit | The number of matching phrases in a document that are considered. Limits the number of phrases to analyze by the `fvh` highlighter to avoid consuming a lot of memory. If `matched_fields` are used, `phrase_limit` specifies the number of phrases for each matched field. A higher `phrase_limit` leads to increased query time and more memory consumption. Valid only for the `fvh` highlighter. Default is 256. -max_analyzer_offset | Specifies the maximum number of characters to be analyzed by a highlight request. The remaining text will not be processed. If the text to be highlighted exceeds this offset, then an empty highlight is returned. The maximum number of characters that will be analyzed for a highlight request is defined by `index.highlight.max_analyzed_offset`. When this limit is reached, an error is returned. Set the `max_analyzer_offset` to a lower value than `index.highlight.max_analyzed_offset` to avoid the error. +`type` | Specifies the highlighter to use. Valid values are `unified`, `fvh`, `plain`, and `semantic`. Default is `unified`. +`fields` | Specifies the fields to search for text to be highlighted. Supports wildcard expressions. If you use wildcards, only `text` and `keyword` fields are highlighted. For example, you can set `fields` to `my_field*` to include all `text` and `keyword` fields that start with the prefix `my_field`. +`force_source` | Specifies that field values for highlighting should be obtained from the `_source` field rather than from stored field values. Default is `false`. +`require_field_match` | Specifies whether to highlight only fields that contain a search query match. Default is `true`. To highlight all fields, set this option to `false`. +`pre_tags` | Specifies the HTML start tags for the highlighted text as an array of strings. +`post_tags` | Specifies the HTML end tags for the highlighted text as an array of strings. +`tags_schema` | If you set this option to `styled`, OpenSearch uses the built-in tag schema. In this schema, the `pre_tags` are `<em class="hlt1">`, `<em class="hlt2">`, `<em class="hlt3">`, `<em class="hlt4">`, `<em class="hlt5">`, `<em class="hlt6">`, `<em class="hlt7">`, `<em class="hlt8">`, `<em class="hlt9">`, and `<em class="hlt10">`, and the `post_tags` is `</em>`. +`boundary_chars` | All boundary characters combined in a string.<br> Default is `".,!? \t\n"`. +`boundary_scanner` | Valid only for the `unified` and `fvh` highlighters. Specifies whether to split the highlighted fragments into sentences, words, or characters. Valid values are the following:<br>- `sentence`: Split highlighted fragments at sentence boundaries, as defined by the [BreakIterator](https://docs.oracle.com/javase/8/docs/api/java/text/BreakIterator.html). You can specify the BreakIterator's locale in the `boundary_scanner_locale` option. <br>- `word`: Split highlighted fragments at word boundaries, as defined by the [BreakIterator](https://docs.oracle.com/javase/8/docs/api/java/text/BreakIterator.html). You can specify the BreakIterator's locale in the `boundary_scanner_locale` option.<br>- `chars`: Split highlighted fragments at any character listed in `boundary_chars`. Valid only for the `fvh` highlighter. +`boundary_scanner_locale` | Provides a [locale](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html) for the `boundary_scanner`. Valid values are language tags (for example, `"en-US"`). Default is [Locale.ROOT](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#ROOT). +`boundary_max_scan` | Controls how far to scan for boundary characters when the `boundary_scanner` parameter for the `fvh` highlighter is set to `chars`. Default is 20. +`encoder` | Specifies whether the highlighted fragment should be HTML encoded before it is returned. Valid values are `default` (no encoding) or `html` (first escape the HTML text and then insert the highlighting tags). For example, if the field text is `<h3>Hamlet</h3>` and the `encoder` is set to `html`, the highlighted text is `"<h3><em>Hamlet</em></h3>"`. +`fragmenter` | Specifies how to split text into highlighted fragments. Valid only for the `plain` highlighter. Valid values are the following:<br>- `span` (default): Splits text into fragments of the same size but tries not to split text between highlighted terms. <br>- `simple`: Splits text into fragments of the same size. +`fragment_offset` | Specifies the character offset from which you want to start highlighting. Valid for the `fvh` highlighter only. +`fragment_size` | The size of a highlighted fragment, specified as the number of characters. If `number_of_fragments` is set to 0, `fragment_size` is ignored. Default is 100. +`number_of_fragments`| The maximum number of returned fragments. If `number_of_fragments` is set to 0, OpenSearch returns the highlighted contents of the entire field. Default is 5. +`order` | The sort order for the highlighted fragments. Set `order` to `score` to sort fragments by relevance. Each highlighter uses a different algorithm to calculate relevance scores. Default is `none`. +`highlight_query` | Specifies that matches for a query other than the search query should be highlighted. The `highlight_query` option is useful when using a faster query to get document matches and a slower query (for example, `rescore_query`) to refine the results. OpenSearch does not check that `highlight_query` matches the search query. If `highlight_query` doesn't include the search query, terms that matched the document may not be highlighted, and terms that didn't match may be highlighted. We recommend including the search query as part of the `highlight_query`. +`matched_fields` | Combines matches from different fields to highlight one field. The most common use case for this functionality is highlighting text that is analyzed in different ways and kept in multi-fields. If using `fvh`, all fields in the `matched_fields` list must have the `term_vector` field set to `with_positions_offsets`. The field in which the matches are combined is the only loaded field, so it is beneficial to set its `store` option to `yes`. Valid only for the `fvh` and `unified` highlighters. +`no_match_size` | Specifies the number of characters, starting from the beginning of the field, to return if there are no matching fragments to highlight. Default is 0. +`phrase_limit` | The number of matching phrases in a document that are considered. Limits the number of phrases to be analyzed by the `fvh` highlighter in order to avoid consuming a lot of memory. If `matched_fields` are used, `phrase_limit` specifies the number of phrases for each matched field. A higher `phrase_limit` leads to increased query time and more memory consumption. Valid only for the `fvh` highlighter. Default is 256. +`max_analyzer_offset` | Specifies the maximum number of characters to be analyzed by a highlight request. The remaining text will not be processed. If the text to be highlighted exceeds this offset, then an empty highlight is returned. The maximum number of characters that will be analyzed for a highlight request is defined by the `index.highlight.max_analyzed_offset` index setting, which defaults to `1000000`. If a field that must be reanalyzed is longer than this limit, the entire search request fails. Fields indexed with offsets or term vectors are not reanalyzed by the `unified` and `fvh` highlighters, so the limit does not apply to them. The `plain` highlighter always reanalyzes text. Set the `max_analyzer_offset` to a lower value than `index.highlight.max_analyzed_offset` to avoid the error. +`options` | A global object containing highlighter-specific options. +`options.max_inference_batch_size` | Specifies the maximum number of documents to include in each inference request to the model server when using batch inference mode. If the number of documents to process exceeds this value, the documents are processed iteratively in batches of this size. Default is `100`. Valid only for the `semantic` highlighter when batch inference mode is enabled. +`options.model_id` | The ID of the deployed ML model to use for highlighting. Required for the `semantic` highlighter. When batch inference mode is enabled, the model must be an externally hosted model with batch processing capabilities. See [Connecting to externally hosted models]({{site.url}}{{site.baseurl}}/ml-commons-plugin/remote-models/index/). The unified highlighter's sentence scanner splits sentences larger than `fragment_size` at the first word boundary after `fragment_size` is reached. To return whole sentences without splitting them, set `fragment_size` to 0. {: .note} ## Changing the highlighting tags -Design your application code to parse the results from the `highlight` object and perform an action on the search terms, such as changing their color, bolding, italicizing, and so on. +Design your application code to parse the results from the `highlight` object and perform an action on the search terms, such as changing their color or applying bold or italic formatting. To change the default `em` tags, specify the new tags in the `pretag` and `posttag` parameters: @@ -314,7 +570,7 @@ The play name is highlighted by the new tags in the response: ## Specifying a highlight query -By default, OpenSearch only considers the search query for highlighting. If you use a fast query to get document matches and a slower query like `rescore_query` to refine the results, it is useful to highlight the refined results. You can do this by adding a `highlight_query`: +By default, OpenSearch only considers the search query for highlighting. If you use a fast query to get document matches and a slower query like `rescore_query` to refine the results, it is useful to highlight the refined results. You can do this by adding a `highlight_query`. Include the search query in the `highlight_query`, as in the following example, because OpenSearch highlights only the terms of the `highlight_query`: ```json GET shakespeare/_search @@ -963,5 +1219,6 @@ The response lists documents that contain the word "bragging" first: Note the following limitations: -- When extracting terms to highlight, highlighters don’t reflect the Boolean logic of a query. Therefore, for some complex Boolean queries, such as nested Boolean queries and queries using `minimum_should_match`, OpenSearch may highlight terms that don’t correspond to query matches. -- The `fvh` highlighter does not support span queries. \ No newline at end of file +- When extracting terms to highlight, highlighters don't reflect the Boolean logic of a query. Therefore, for some complex Boolean queries, such as nested Boolean queries and queries using `minimum_should_match`, OpenSearch may highlight terms that don't correspond to query matches. +- The `fvh` highlighter does not support span queries. +- The `semantic` highlighter requires a deployed ML model specified by `model_id` in the `highlight.options`. It does not use traditional offset methods (postings and term vectors) and relies solely on model inference. For batch inference mode, you must use an externally hosted model with batch processing capabilities. \ No newline at end of file diff --git a/_search-plugins/searching-data/index.md b/_search-plugins/searching-data/index.md index 6781b5a5..51a9a6cf 100644 --- a/_search-plugins/searching-data/index.md +++ b/_search-plugins/searching-data/index.md @@ -1,20 +1,50 @@ --- layout: default -title: Searching data -nav_order: 5 +title: Customizing search results +nav_order: 15 has_children: true has_toc: false -redirect_from: /opensearch/ux/ +redirect_from: + - /opensearch/ux/ + - /search-plugins/searching-data/ + - /search-plugins/search-options/ --- -# Searching data +# Customizing search results -What users expect from search engines has evolved over the years. Just returning relevant results quickly is no longer enough for most users. Now users seek methods that allow them to get even more relevant results, to sort and organize results, and to highlight their queries. OpenSearch includes many features, described in the following table, that enhance the search experience. +OpenSearch provides fundamental search capabilities and options that form the foundation of most search applications. These features work with all search types including keyword, vector, and AI search. -Feature | Description -:--- | :--- -[Autocomplete functionality]({{site.url}}{{site.baseurl}}/opensearch/search/autocomplete/) | Suggest phrases as the user types. -[Did-you-mean functionality]({{site.url}}{{site.baseurl}}/opensearch/search/did-you-mean/) | Check spelling of phrases as the user types. -[Paginate results]({{site.url}}{{site.baseurl}}/opensearch/search/paginate/) | Rather than a single, long list, separate search results into pages. -[Sort results]({{site.url}}{{site.baseurl}}/opensearch/search/sort/) | Allow sorting of results by different criteria. -[Highlight query matches]({{site.url}}{{site.baseurl}}/opensearch/search/highlight/) | Highlight the search term in the results. +## Pagination + +Control how search results are accessed across large result sets: + +- [Paginate results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/paginate/): Rather than a single, long list, separate search results into pages. +- [Point in Time]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/): Run different queries against a dataset that is fixed in time. + +## Sort and filter + +Apply the most common result refinements: + +- [Sort results]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/sort/): Allow sorting of results by different criteria. +- [Filter results]({{site.url}}{{site.baseurl}}/search-plugins/filter-search/): Filter search results based on specific criteria. + +## Result processing + +Control what data is returned and how it's organized: + +- [Collapse results]({{site.url}}{{site.baseurl}}/search-plugins/collapse-search/): Collapse search results to show only unique values for a specified field. +- [Retrieve specific fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/): Retrieve only the specific fields you need. +- [Retrieve inner hits]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/inner-hits/): Retrieve underlying hits in nested and parent-join objects. + +## Result formatting + +Customize how search results are visually presented: + +- [Highlight query matches]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/): Highlight the search term in the results. + +## Query enhancement + +Enhance user queries in real-time to improve search accuracy and user experience: + +- [Autocomplete functionality]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/autocomplete/): Suggest phrases as the user types. +- [Did-you-mean functionality]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/did-you-mean/): Check spelling of phrases as the user types. diff --git a/_search-plugins/searching-data/inner-hits.md b/_search-plugins/searching-data/inner-hits.md new file mode 100644 index 00000000..97cb13ec --- /dev/null +++ b/_search-plugins/searching-data/inner-hits.md @@ -0,0 +1,988 @@ +--- +layout: default +title: Retrieve inner hits +parent: Customizing search results +has_children: false +nav_order: 60 +--- + +# Retrieve inner hits + +In OpenSearch, when you perform a search using [nested objects]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) or [parent-join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/), the underlying hits (nested inner objects or child documents) are hidden by default. You can retrieve inner hits by using the `inner_hits` parameter in the search query. + +Use inner hits in the following scenarios: + +- Identifying which nested objects or child documents caused a document to match, for example, the comments on a blog post that contain the search terms or the update on a support ticket that matches a query. +- Retrieving documents together with their matching nested objects or child documents in one request, for example, products with their matching reviews or job postings with their matching applications. This avoids sending a separate query for the related documents. + +You can also use `inner_hits` with the following features: + + - [Highlight query matches]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/) + - [Explain]({{site.url}}{{site.baseurl}}/api-reference/explain/) + +## Inner hits with nested objects + +Nested objects allow you to index an array of objects and maintain their relationship within the same document. The following example request uses the `inner_hits` parameter to retrieve the underlying inner hits. + +1. Create an index mapping with a nested object: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "user": { + "type": "nested", + "properties": { + "name": { "type": "text" }, + "age": { "type": "integer" } + } + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index data: + + ```json + POST /my_index/_doc/1 + { + "group": "fans", + "user": [ + { + "name": "John Doe", + "age": 28 + }, + { + "name": "Jane Smith", + "age": 34 + } + ] + } + ``` + {% include copy-curl.html %} + +3. Query with `inner_hits`: + + ```json + GET /my_index/_search + { + "query": { + "nested": { + "path": "user", + "query": { + "bool": { + "must": [ + { "match": { "user.name": "John" } } + ] + } + }, + "inner_hits": {} + } + } + } + ``` + {% include copy-curl.html %} + +The preceding query searches for nested user objects containing the name John and returns the matching nested documents in the `inner_hits` section of the response: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 0.6931471, + "_source" : { + "group" : "fans", + "user" : [ + { + "name" : "John Doe", + "age" : 28 + }, + { + "name" : "Jane Smith", + "age" : 34 + } + ] + }, + "inner_hits" : { + "user" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_nested" : { + "field" : "user", + "offset" : 0 + }, + "_score" : 0.6931471, + "_source" : { + "name" : "John Doe", + "age" : 28 + } + } + ] + } + } + } + } + ] + } +} +``` +### Identifying the matched nested object + +Each inner hit for a nested object contains a `_nested` object that identifies the nested object that matched. The `field` property contains the name of the nested field, and the `offset` property contains the position of the object in that field's array in the original document, starting at `0`. In the preceding response, the `offset` of `0` means that the inner hit is the first object in the `user` array. Because inner hits are sorted by score or by the sort order you specify, the order of inner hits usually differs from the order of the objects in the document, so use `offset` to identify the original object. + +By default, the `_source` of each inner hit contains only the matched nested object, not the entire source document. You can change the returned fields using [source filtering]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-source-filtering), disable `_source` for inner hits, or return the [stored fields]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/store/) of the nested object by specifying them in `stored_fields` in `inner_hits`. + +### Retrieving nested inner hits without the source + +Nested objects are not stored separately: their source is part of the source of the parent document. To return the `_source` of a nested inner hit, OpenSearch parses the parent document's source and extracts the matching object. Doing this for every inner hit increases the search time, especially if you increase `size` for the search or for `inner_hits`. To avoid this cost, disable `_source` for inner hits and retrieve the field values from doc values instead. + +The following example uses an `articles` index containing nested `comments`. Create the index and add a document: + +```json +PUT /articles +{ + "mappings": { + "properties": { + "comments": { + "type": "nested", + "properties": { + "author": { "type": "keyword" }, + "text": { "type": "text" }, + "reactions": { + "type": "nested", + "properties": { + "user": { "type": "keyword" }, + "emoji": { "type": "keyword" } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /articles/_doc/1?refresh=true +{ + "title": "Choosing a backpacking tent", + "comments": [ + { + "author": "ana", + "text": "Great overview of tent weights", + "reactions": [] + }, + { + "author": "ben", + "text": "Which tent survives strong wind?", + "reactions": [ + { "user": "ana", "emoji": "thumbs_up" }, + { "user": "chen", "emoji": "heart" } + ] + } + ] +} +``` +{% include copy-curl.html %} + +The following request finds comments that mention `wind` and returns only the `author` of each matching comment from doc values: + +```json +GET /articles/_search +{ + "_source": false, + "query": { + "nested": { + "path": "comments", + "query": { + "match": { "comments.text": "wind" } + }, + "inner_hits": { + "_source": false, + "docvalue_fields": ["comments.author"] + } + } + } +} +``` +{% include copy-curl.html %} + +The inner hit contains the `fields` object in place of `_source`: + +```json +"inner_hits": { + "comments": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.31506687, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1 + }, + "_score": 0.31506687, + "fields": { + "comments.author": [ + "ben" + ] + } + } + ] + } + } +} +``` + +### Inner hits for multi-level nested objects + +If nested objects contain other nested objects, you can return inner hits from any level by specifying the full dotted path in the `nested` query. The following request returns the reactions by the user `ana`, which are nested in `comments.reactions`: + +```json +GET /articles/_search +{ + "_source": false, + "query": { + "nested": { + "path": "comments.reactions", + "query": { + "term": { "comments.reactions.user": "ana" } + }, + "inner_hits": {} + } + } +} +``` +{% include copy-curl.html %} + +The inner hits are named after the full path. The `_nested` object of each inner hit contains another `_nested` object for each level. In this response, the reaction is the first object (`offset` `0`) in the `reactions` array of the second comment (`offset` `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, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 1, + "inner_hits": { + "comments.reactions": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1, + "_nested": { + "field": "reactions", + "offset": 0 + } + }, + "_score": 1, + "_source": { + "emoji": "thumbs_up", + "user": "ana" + } + } + ] + } + } + } + } + ] + } +} +``` + +## Inner hits with parent/child objects + +Parent-join relationships allow you to create relationships between documents of different types within the same index. The following example request searches with `inner_hits` using parent/child objects. + +1. Create an index with a parent-join field: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "my_join_field": { + "type": "join", + "relations": { + "parent": "child" + } + }, + "text": { + "type": "text" + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index data: + + ```json + # Index a parent document + PUT /my_index/_doc/1 + { + "text": "This is a parent document", + "my_join_field": "parent" + } + + # Index a child document + PUT /my_index/_doc/2?routing=1 + { + "text": "This is a child document", + "my_join_field": { + "name": "child", + "parent": "1" + } + } + ``` + {% include copy-curl.html %} + +3. Search with `inner_hits`: + + ```json + GET /my_index/_search + { + "query": { + "has_child": { + "type": "child", + "query": { + "match": { + "text": "child" + } + }, + "inner_hits": {} + } + } + } + ``` + {% include copy-curl.html %} + +The preceding query searches for parent documents that have child documents matching the query criteria (in this case, containing the term `"child"`). It returns the matching child documents in the `inner_hits` section of the response: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "text" : "This is a parent document", + "my_join_field" : "parent" + }, + "inner_hits" : { + "child" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "2", + "_score" : 0.6931471, + "_routing" : "1", + "_source" : { + "text" : "This is a child document", + "my_join_field" : { + "name" : "child", + "parent" : "1" + } + } + } + ] + } + } + } + } + ] + } +} +``` + +You can also specify `inner_hits` in a [`has_parent`]({{site.url}}{{site.baseurl}}/query-dsl/joining/has-parent/) query. In this case, the query returns the child documents, and the inner hits of each child contain its matching parent document. + +## Using inner hits with both parent-join and nested objects + +The following example demonstrates using both parent-join and nested objects with `inner_hits`. + +1. Create an index with the following mapping: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "my_join_field": { + "type": "join", + "relations": { + "parent": "child" + } + }, + "text": { + "type": "text" + }, + "comments": { + "type": "nested", + "properties": { + "user": { "type": "text" }, + "message": { "type": "text" } + } + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index data: + + ```json + # Index a parent document + PUT /my_index/_doc/1 + { + "text": "This is a parent document", + "my_join_field": "parent" + } + + # Index a child document with nested comments + PUT /my_index/_doc/2?routing=1 + { + "text": "This is a child document", + "my_join_field": { + "name": "child", + "parent": "1" + }, + "comments": [ + { + "user": "John", + "message": "This is a comment" + }, + { + "user": "Jane", + "message": "Another comment" + } + ] + } + ``` + {% include copy-curl.html %} + +3. Query with `inner_hits`: + + ```json + GET /my_index/_search + { + "query": { + "has_child": { + "type": "child", + "query": { + "nested": { + "path": "comments", + "query": { + "bool": { + "must": [ + { "match": { "comments.user": "John" } } + ] + } + }, + "inner_hits": {} + } + }, + "inner_hits": {} + } + } + } + ``` + {% include copy-curl.html %} + +The preceding query searches for parent documents that have child documents containing comments made by John. Specifying `inner_hits` ensures that the matching child documents and their nested comments are returned: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "text" : "This is a parent document", + "my_join_field" : "parent" + }, + "inner_hits" : { + "child" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "2", + "_score" : 0.6931471, + "_routing" : "1", + "_source" : { + "text" : "This is a child document", + "my_join_field" : { + "name" : "child", + "parent" : "1" + }, + "comments" : [ + { + "user" : "John", + "message" : "This is a comment" + }, + { + "user" : "Jane", + "message" : "Another comment" + } + ] + }, + "inner_hits" : { + "comments" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "2", + "_nested" : { + "field" : "comments", + "offset" : 0 + }, + "_score" : 0.6931471, + "_source" : { + "message" : "This is a comment", + "user" : "John" + } + } + ] + } + } + } + } + ] + } + } + } + } + ] + } +} +``` + +## Inner hits parameters + +The following table lists the parameters that you can specify in `inner_hits` for both nested objects and parent-join relationships. + +Parameter | Description +:--- | :--- +`from` | The offset from which to start returning inner hits. Default is `0`. +`size` | The maximum number of inner hits to return. Default is `3`. +`sort` | The sort order for the inner hits. By default, inner hits are sorted by relevance score. +`name` | A custom name for the inner hits in the response. Useful for differentiating between multiple inner hits in a single query. By default, the name is the nested `path` for a `nested` query, the child relation name for a `has_child` query, and the parent relation name for a `has_parent` query. + +Inner hits also accept many of the options that you can specify for the hits of a search request, including [`highlight`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/highlight/), `explain`, [source filtering]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-source-filtering), [`script_fields`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#using-scripted-fields), [`docvalue_fields`]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-doc-value-fields), `version`, and `seq_no_primary_term`. Nested objects are not assigned sequence numbers, so OpenSearch rejects `seq_no_primary_term` in the inner hits of a `nested` query. + +### Example: Inner hits parameters with nested objects + +1. Create an index with the following mappings: + + ```json + PUT /products + { + "mappings": { + "properties": { + "product_name": { "type": "text" }, + "reviews": { + "type": "nested", + "properties": { + "user": { "type": "text" }, + "comment": { "type": "text" }, + "rating": { "type": "integer" } + } + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index data: + + ```json + POST /products/_doc/1 + { + "product_name": "Smartphone", + "reviews": [ + { "user": "Alice", "comment": "Great phone", "rating": 5 }, + { "user": "Bob", "comment": "Not bad", "rating": 3 }, + { "user": "Charlie", "comment": "Excellent", "rating": 4 } + ] + } + ``` + {% include copy-curl.html %} + + ```json + POST /products/_doc/2 + { + "product_name": "Laptop", + "reviews": [ + { "user": "Dave", "comment": "Very good", "rating": 5 }, + { "user": "Eve", "comment": "Good value", "rating": 4 } + ] + } + ``` + {% include copy-curl.html %} + +3. Query with `inner_hits` and provide additional parameters: + + ```json + GET /products/_search + { + "query": { + "nested": { + "path": "reviews", + "query": { + "match": { "reviews.comment": "Good" } + }, + "inner_hits": { + "from": 0, + "size": 2, + "sort": [ + { "reviews.rating": { "order": "desc" } } + ], + "name": "top_reviews" + } + } + } + } + ``` + {% include copy-curl.html %} + +The following is the expected result: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.83740485, + "hits" : [ + { + "_index" : "products", + "_id" : "2", + "_score" : 0.83740485, + "_source" : { + "product_name" : "Laptop", + "reviews" : [ + { + "user" : "Dave", + "comment" : "Very good", + "rating" : 5 + }, + { + "user" : "Eve", + "comment" : "Good value", + "rating" : 4 + } + ] + }, + "inner_hits" : { + "top_reviews" : { + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "products", + "_id" : "2", + "_nested" : { + "field" : "reviews", + "offset" : 0 + }, + "_score" : null, + "_source" : { + "rating" : 5, + "comment" : "Very good", + "user" : "Dave" + }, + "sort" : [ + 5 + ] + }, + { + "_index" : "products", + "_id" : "2", + "_nested" : { + "field" : "reviews", + "offset" : 1 + }, + "_score" : null, + "_source" : { + "rating" : 4, + "comment" : "Good value", + "user" : "Eve" + }, + "sort" : [ + 4 + ] + } + ] + } + } + } + } + ] + } +} +``` + +### Example: Inner hits parameters with a parent-join relationship + +1. Create an index with the following mappings: + + ```json + PUT /company + { + "mappings": { + "properties": { + "my_join_field": { + "type": "join", + "relations": { + "employee": "task" + } + }, + "name": { "type": "text" }, + "description": { + "type": "text", + "fields": { + "keyword": { "type": "keyword" } + } + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index data: + + ```json + # Index a parent document + PUT /company/_doc/1 + { + "name": "Alice", + "my_join_field": "employee" + } + ``` + {% include copy-curl.html %} + + ```json + # Index child documents + PUT /company/_doc/2?routing=1 + { + "description": "Complete the project", + "my_join_field": { + "name": "task", + "parent": "1" + } + } + ``` + {% include copy-curl.html %} + + ```json + PUT /company/_doc/3?routing=1 + { + "description": "Prepare the report", + "my_join_field": { + "name": "task", + "parent": "1" + } + } + ``` + {% include copy-curl.html %} + + ```json + PUT /company/_doc/4?routing=1 + { + "description": "Update project", + "my_join_field": { + "name": "task", + "parent": "1" + } + } + ``` + {% include copy-curl.html %} + +3. Query with `inner_hits` parameters: + + ```json + GET /company/_search + { + "query": { + "has_child": { + "type": "task", + "query": { + "match": { "description": "project" } + }, + "inner_hits": { + "from": 0, + "size": 10, + "sort": [ + { "description.keyword": { "order": "asc" } } + ], + "name": "related_tasks" + } + } + } + } + ``` + {% include copy-curl.html %} + +The following is the expected result: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits": [ + { + "_index": "company", + "_id": "1", + "_score": 1, + "_source": { + "name": "Alice", + "my_join_field": "employee" + }, + "inner_hits": { + "related_tasks": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "company", + "_id": "2", + "_score": null, + "_routing": "1", + "_source": { + "description": "Complete the project", + "my_join_field": { + "name": "task", + "parent": "1" + } + }, + "sort": [ + "Complete the project" + ] + }, + { + "_index": "company", + "_id": "4", + "_score": null, + "_routing": "1", + "_source": { + "description": "Update project", + "my_join_field": { + "name": "task", + "parent": "1" + } + }, + "sort": [ + "Update project" + ] + } + ] + } + } + } + } + ] + } +} +``` +## Next steps + +- Learn about [joining queries]({{site.url}}{{site.baseurl}}/query-dsl/joining/) on [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) or [join]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/join/) fields. \ No newline at end of file diff --git a/_search-plugins/searching-data/paginate.md b/_search-plugins/searching-data/paginate.md index e6434a54..3adf93bf 100644 --- a/_search-plugins/searching-data/paginate.md +++ b/_search-plugins/searching-data/paginate.md @@ -1,14 +1,13 @@ --- layout: default title: Paginate results -parent: Searching data -has_children: true +parent: Customizing search results nav_order: 10 redirect_from: - /opensearch/search/paginate/ --- -## Paginate results +# Paginate results You can use the following methods to paginate search results in OpenSearch: @@ -52,9 +51,11 @@ You can also specify the `from` and `size` parameters in the search URI: GET shakespeare/_search?from=0&size=10 ``` -If you only specify the `size` parameter, the `from` parameter defaults to 0. +If you don't specify `size`, a search returns 10 hits. If you only specify the `size` parameter, the `from` parameter defaults to 0. -Querying for pages deep in your results can have a significant performance impact, so OpenSearch limits this approach to 10,000 results. +Querying for pages deep in your results is expensive. To return results starting at `from`, each shard must find and sort its top `from` + `size` results, and the coordinating node must then merge and sort the results from all shards. Memory use and latency therefore grow with the value of `from`. To protect the cluster, OpenSearch rejects requests in which `from` + `size` exceeds the `index.max_result_window` index setting. Default is `10000`. To page through more results, use [`search_after`](#the-search_after-parameter) or a [scroll](#scroll-search). + +If several documents have the same sort values, for example, the same relevance score, their order can differ between requests. This happens because requests can be served by different shard copies, which store documents in a different internal order. A document can then appear on two pages or on none. To keep the order stable, add a field with a unique value per document as the last sort field, or send all requests from a user to the same shard copies using the [`preference`]({{site.url}}{{site.baseurl}}/api-reference/search-apis/search/#the-preference-query-parameter) parameter with a value such as the user's session ID. The `from` and `size` parameters are stateless, so the results are based on the latest available data. This can cause inconsistent pagination. @@ -65,9 +66,7 @@ Use the `scroll` operation for consistent pagination. The `scroll` operation kee ## Scroll search -The `from` and `size` parameters allow you to paginate your search results but with a limit of 10,000 results at a time. - -If you need to request volumes of data larger than 1 PB from, for example, a machine learning job, use the `scroll` operation instead. The `scroll` operation allows you to request an unlimited number of results. +The `from` and `size` parameters cannot return results past the `index.max_result_window` limit (by default, 10,000). To retrieve a larger result set, for example, to export all documents that match a query or to process them in a batch job, use the `scroll` operation. The `scroll` operation can return any number of results. To use the scroll operation, add a `scroll` parameter to the request header with a search context telling OpenSearch for how long you need to keep scrolling. This search context needs to be long enough to process a single batch of results. @@ -86,7 +85,7 @@ OpenSearch caches the results and returns a scroll ID that you can use to access "_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" ``` -Pass this scroll ID to the `scroll` operation to obtain the next batch of results: +Pass this scroll ID to the `scroll` operation to obtain the next batch of results. Do not include an index name in the path: the scroll ID already identifies the indexes of the initial search, and OpenSearch rejects a request to `<index>/_search/scroll`: ```json GET _search/scroll @@ -98,38 +97,84 @@ GET _search/scroll Using this scroll ID, you get results in batches of 10,000 as long as the search context is still open. Typically, the scroll ID does not change between requests, but it *can* change, so make sure to always use the latest scroll ID. If you don't send the next scroll request within the set search context, the `scroll` operation does not return any results. -If you expect billions of results, use a sliced scroll. Slicing allows you to perform multiple scroll operations for the same request but in parallel. -Set the ID and the maximum number of slices for the scroll: +Continue sending scroll requests until a response contains an empty `hits.hits` array, which means that all results were returned. If the initial search request contains aggregations, they are returned only in the first response. + +Each scroll request resets the expiration time of the search context to the `scroll` value specified in that request, so the value must cover only the time needed to process one batch. If a scroll request does not contain a `scroll` value, OpenSearch returns the batch and then closes the search context. The `scroll` value cannot exceed the `search.max_keep_alive` cluster setting. Default is `24h`. + +If you need all matching documents and their order does not matter, sort by `_doc`. This is the most efficient sort order for scrolling: + +```json +GET shakespeare/_search?scroll=10m +{ + "size": 10000, + "sort": ["_doc"] +} +``` +{% include copy-curl.html %} + +To retrieve a large result set faster, use a sliced scroll. Slicing splits one scroll into several independent scrolls, called _slices_, that you can process in parallel. In each request, set `slice.max` to the total number of slices and `slice.id` to the slice that the request retrieves, from `0` to `max` minus 1. The following request retrieves the first of two slices: ```json GET shakespeare/_search?scroll=10m { "slice": { "id": 0, - "max": 10 + "max": 2 }, "query": { "match_all": {} } } ``` +{% include copy-curl.html %} -With a single scroll ID, you receive 10 results. -You can have up to 10 IDs. -Perform the same command with the ID equal to 1: +To retrieve the second slice, send the same request with `id` set to `1`: ```json GET shakespeare/_search?scroll=10m { "slice": { "id": 1, - "max": 10 + "max": 2 }, "query": { "match_all": {} } } ``` +{% include copy-curl.html %} + +Each request returns its own scroll ID, which you use to page through that slice. Together, the slices contain the same documents as an unsliced scroll, and each document belongs to exactly one slice. In the `shakespeare` index, the two slices contain 55,635 and 55,761 of the 111,396 documents. + +By default, OpenSearch assigns documents to slices first by shard and then by a hash of the document `_id` within each shard. If you request more slices than there are shards, the first requests for each slice are slow and use memory proportional to the number of documents in the shard, until OpenSearch caches the slice filter. Limit the number of slices that you query in parallel. + +To avoid this cost, you can assign documents to slices based on the doc values of another field by specifying the field in `slice.field`. The field must meet the following requirements: + +- The field must be a numeric field with [doc values]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/doc-values/) enabled. OpenSearch rejects requests that slice on `keyword`, `text`, or other non-numeric fields or on fields with doc values disabled. +- Each document must contain exactly one value. A document whose field contains several values can be returned in more than one slice. +- The value must not change after the document is indexed, so that each document stays in the same slice for the duration of the scroll. +- The field should have many distinct values so that documents are distributed evenly across slices. For example, a timestamp in an index to which you only add documents is a good choice. + +The following request splits the results into two slices based on the `line_id` field: + +```json +GET shakespeare/_search?scroll=10m +{ + "slice": { + "field": "line_id", + "id": 0, + "max": 2 + }, + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +You can also slice a [Point in Time]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/point-in-time/) (PIT) search using the same `slice` object. OpenSearch rejects a `slice` in a search that uses neither a scroll nor a PIT. + +The maximum number of slices is controlled by the `index.max_slices_per_scroll` index setting for scrolls and by the `index.max_slices_per_pit` index setting for PIT searches. Default is `1024` for both settings. OpenSearch rejects a request whose `slice.max` value exceeds the limit. For more information, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). Close the search context when you’re done scrolling, because it continues to consume computing resources until the timeout: @@ -137,7 +182,7 @@ Close the search context when you’re done scrolling, because it continues to c DELETE _search/scroll/DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ== ``` -#### Sample Response +#### Example response ```json { @@ -146,6 +191,20 @@ DELETE _search/scroll/DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUG } ``` +To close several scroll contexts at once, specify their IDs in the request body as an array: + +```json +DELETE _search/scroll +{ + "scroll_id": [ + "<scroll_id_1>", + "<scroll_id_2>" + ] +} +``` + +You can also specify a single ID in the `scroll_id` field or provide a comma-separated list of IDs in the request path, for example, `DELETE _search/scroll/<scroll_id_1>,<scroll_id_2>`. + Use the following request to close all open scroll contexts: ```json @@ -154,13 +213,20 @@ DELETE _search/scroll/_all The `scroll` operation corresponds to a specific timestamp. It doesn't consider documents added after that timestamp as potential results. -Because open search contexts consume a lot of memory, we suggest you don't use the `scroll` operation for frequent user queries that don't need the search context to be open. Instead, use the `sort` parameter with the `search_after` parameter to scroll responses for user queries. +An open search context consumes resources until it is closed or expires. While a scroll is open, OpenSearch cannot delete the old segments that were merged into new segments, because the scroll still reads them. This uses more disk space and file handles. On indexes that receive ongoing updates or deletes, an open scroll also uses more heap memory. Each node allows at most `search.max_open_scroll_context` open scroll contexts. Default is `500`. To check the number of open scroll contexts, use the Nodes Stats API and look at the `scroll_current` value: + +```json +GET _nodes/stats/indices/search +``` +{% include copy-curl.html %} + +Because of this cost, don't use the `scroll` operation for frequent user queries. For user-facing pagination, use the `sort` parameter with the `search_after` parameter. If users must see consistent results across pages, combine `search_after` with a [Point in Time](#point-in-time-with-search_after) (PIT). A PIT also keeps a search context open, so set its `keep_alive` to the shortest period that your application needs and delete the PIT when you no longer need it. ## The `search_after` parameter -The `search_after` parameter provides a live cursor that uses the previous page's results to obtain the next page's results. It is similar to the `scroll` operation in that it is meant to scroll many queries in parallel. +The `search_after` parameter provides a live cursor that uses the previous page's results to obtain the next page's results. It is similar to the `scroll` operation in that it is meant to scroll many queries in parallel. You can use `search_after` only when sorting is applied. -For example, the following query sorts all lines from the play "Hamlet" by the speech number and then the ID and retrieves the first three results: +For example, the following query sorts all lines from the play "Hamlet" by the speech number and then the line ID and retrieves the first three results: ```json GET shakespeare/_search @@ -173,7 +239,7 @@ GET shakespeare/_search }, "sort": [ { "speech_number": "asc" }, - { "_id": "asc" } + { "line_id": "asc" } ] } ``` @@ -212,7 +278,7 @@ The response contains the `sort` array of values for each document: }, "sort" : [ 1, - "32435" + 32436 ] }, { @@ -230,7 +296,7 @@ The response contains the `sort` array of values for each document: }, "sort" : [ 1, - "32634" + 32635 ] }, { @@ -248,7 +314,7 @@ The response contains the `sort` array of values for each document: }, "sort" : [ 1, - "32635" + 32636 ] } ] @@ -267,16 +333,22 @@ GET shakespeare/_search "play_name": "Hamlet" } }, - "search_after": [ 1, "32635"], + "search_after": [ 1, 32636], "sort": [ { "speech_number": "asc" }, - { "_id": "asc" } + { "line_id": "asc" } ] } ``` -Unlike the `scroll` operation, the `search_after` parameter is stateless, so the document order may change because of documents being indexed or deleted. +Unlike the `scroll` operation, the `search_after` parameter is stateless, so the document order may change because of documents being indexed or deleted. Because each request depends on the `sort` values of the previous page, `search_after` can only move forward one page at a time. You cannot use it to jump to an arbitrary page. + +When you use `search_after`, the `from` parameter must be `0` or omitted. OpenSearch rejects requests that specify any other value. + +Include a field that has a unique value for each document as the last field in the `sort` array. This field acts as a _tiebreaker_: without it, documents that have the same values for all other sort fields have no defined order, and pages can skip or repeat them. In the preceding example, `line_id` is unique for each line, so it acts as the tiebreaker for documents that have the same `speech_number`. + +Avoid using the `_id` field as the tiebreaker. The `_id` field has no doc values, so sorting on it loads all document IDs into memory. It is also unique only within an index, so it cannot break ties for documents from different indexes. Instead, copy the document ID into a `keyword` field when you index the document, either in your application or using a [`set` ingest processor]({{site.url}}{{site.baseurl}}/ingest-pipelines/processors/set/), and sort on that field. ## Point in Time with `search_after` -Point in Time (PIT) with `search_after` is the preferred pagination method in OpenSearch, especially for deep pagination. It bypasses the limitations of all other methods because it operates on a dataset that is frozen in time, it is not bound to a query, and it supports consistent pagination going forward and backward. To learn more, see [Point in Time]({{site.url}}{{site.baseurl}}/opensearch/point-in-time). \ No newline at end of file +Point in Time (PIT) with `search_after` is the preferred pagination method in OpenSearch, especially for deep pagination. It bypasses the limitations of all other methods because it operates on a dataset that is frozen in time, it is not bound to a query, and it supports consistent pagination going forward and backward. To learn more, see [Point in Time]({{site.url}}{{site.baseurl}}/opensearch/point-in-time/). \ No newline at end of file diff --git a/_search-plugins/searching-data/point-in-time.md b/_search-plugins/searching-data/point-in-time.md index ee09354c..38f21bc0 100644 --- a/_search-plugins/searching-data/point-in-time.md +++ b/_search-plugins/searching-data/point-in-time.md @@ -1,10 +1,8 @@ --- layout: default title: Point in Time -parent: Searching data +parent: Customizing search results nav_order: 20 -has_children: true -has_toc: false redirect_from: - /opensearch/point-in-time/ - /search-plugins/point-in-time/ @@ -14,13 +12,13 @@ redirect_from: Point in Time (PIT) lets you run different queries against a dataset that is fixed in time. -Normally, if you run a query on an index multiple times, the same query may return different results because documents are continually indexed, updated, and deleted. If you need to run a query against the same data, you can preserve that data's state by creating a PIT. The main use of the PIT feature is to couple it with the `search_after` functionality for deep pagination of search results. +Normally, if you run a query on an index multiple times, the same query may return different results because documents are continually indexed, updated, and deleted. If you need to run a query against the same data, you can preserve the state of that data by creating a PIT. The main use of the PIT feature is to couple it with the `search_after` functionality for deep pagination of search results. ## Paginating search results -Besides the PIT functionality, there are three ways to [paginate search results]({{site.url}}{{site.baseurl}}/opensearch/search/paginate) in OpenSearch: using the Scroll API, specifying `from` and `size` parameters for your search, and using the `search_after` functionality. However, all three have limitations: +Besides the PIT functionality, there are three ways to [paginate search results]({{site.url}}{{site.baseurl}}/opensearch/search/paginate/) in OpenSearch: using the Scroll API, specifying `from` and `size` parameters for your search, and using the `search_after` functionality. However, all three have limitations: -- The Scroll API's search results are frozen at the moment of the request, but they are bound to a particular query. Additionally, scroll can only move forward in the search, so if a request for a page fails, the subsequent request skips that page and returns the following one. +- The Scroll API search results are frozen at the moment of the request, but they are bound to a particular query. Additionally, scroll can only move forward in the search, so if a request for a page fails, the subsequent request skips that page and returns the following one. - If you specify the `from` and `size` parameters for your search, the search results are not frozen in time, so they may be inconsistent because of documents being indexed or deleted. The `from` and `size` feature is not recommended for deep pagination because every page request requires processing of all results and filtering them for the requested page. - The `search_after` search results are not frozen in time, so they may be inconsistent because of concurrent document indexing or deletion. @@ -30,13 +28,17 @@ The PIT functionality does not have the limitations of other pagination methods, PIT search has the same capabilities as regular search, except PIT search acts on an older dataset, while a regular search acts on a live dataset. PIT search is not bound to a query, so you can run different queries on the same dataset, which is frozen in time. -You can use the [Create PIT API]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api#create-a-pit) to create a PIT. When you create a PIT for a set of indexes, OpenSearch locks a set of segments for those indexes, freezing them in time. On a lower level, none of the resources required for this PIT are modified or deleted. If the segments that are part of a PIT are merged, OpenSearch retains a copy of those segments for the period of time specified at PIT creation by the `keep_alive` parameter. +You can use the [Create PIT API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/#create-a-pit) to create a PIT. When you create a PIT for a set of indexes, OpenSearch locks a set of segments for those indexes, freezing them in time. On a lower level, none of the resources required for this PIT are modified or deleted. If the segments that are part of a PIT are merged, OpenSearch retains a copy of those segments for the period of time specified at PIT creation by the `keep_alive` parameter. The create PIT operation returns a PIT ID, which you can use to run multiple queries on the frozen dataset. Even though the indexes continue to ingest data and modify or delete documents, the PIT references the data that has not changed since the PIT creation. When your query contains a PIT ID, you don't need to pass the indexes to the search because it will use that PIT. A search with a PIT ID will produce exactly the same result when you run it multiple times. In case of a cluster or node failure, all PIT data is lost. {: .note} +### PIT in SQL + +The [SQL plugin]({{site.url}}{{site.baseurl}}/search-plugins/sql/index/) also supports pagination using PIT. When the `plugin.sql.pagination.api` setting is enabled (the default), SQL search queries in OpenSearch automatically use PIT internally. For more information, see [Pagination in SQL]({{site.url}}{{site.baseurl}}/search-plugins/sql/sql-ppl-api/#paginating-results). + ## Pagination with PIT and search_after When you run a query with a PIT ID, you can use the `search_after` parameter to retrieve the next page of results. This gives you control over the order of documents in the pages of results. @@ -90,21 +92,23 @@ GET /_search Using `search_after` with PIT for pagination gives you control over ordering of the results. If you don't need results in any specific order, or if you want the ability to jump from a page to a non-consecutive page, you can use search slicing. Search slicing splits a PIT search into multiple slices that can be consumed independently by a client application. -For example, if you have a PIT search query that has 1,000,000 results and you want to return 50,000 results at a time, your client application has to make 20 consecutive calls to receive each batch of results. If you use search slicing, you can parallelize these 20 calls. In your multithreaded client application you can use five slices for each PIT. As a result, you will have 5 10,000-hit slices that can be consumed by five different threads in your client, instead of having a single thread consume 50,000 results. +For example, a PIT search that matches 1,000,000 documents can be split into 2 slices of about 500,000 documents each, which two threads in your client application can read in parallel. Each thread pages through its own slice using `search_after`. All slices use the same PIT ID. -To use search slicing, you have to specify two parameters: -- `slice.id` is the slice ID you are requesting. -- `slice.max` is the number of slices to break the search response into. +To use search slicing, specify the following parameters in the `slice` object: -The following PIT search query illustrates search slicing: +- `slice.max` is the number of slices into which to split the search. It cannot exceed the `index.max_slices_per_pit` index setting (default `1024`). +- `slice.id` is the ID of the slice you are requesting, from `0` to `slice.max` - 1. + +OpenSearch assigns each document to a slice based on its shard and document ID, so slices contain roughly, but not exactly, the same number of documents. + +The following request returns the first of two slices: ```json - GET /_search { "slice": { - "id": 0, // id is the slice (page) number being requested. In every request we can only query for one slice - "max": 2 // max is the total number of slices (pages) the search response will be broken down into + "id": 0, + "max": 2 }, "query": { "match": { @@ -116,44 +120,31 @@ GET /_search } } ``` +{% include copy-curl.html %} -In every request you can only query for one slice, so the next query will be the same as the previous one, except the `slice.id` will be `1`. +Each request returns one slice. To request the second slice, send the same request with `slice.id` set to `1`. -## Security model +Each slice is paginated like any other search. Paging through a slice using `from` and `size` is limited by the `index.max_result_window` index setting (default `10000`): the sum of `from` and `size` cannot exceed this value. To read more documents from a slice, add a `sort` to the request and paginate using `search_after`, as described in [Pagination with PIT and `search_after`](#pagination-with-pit-and-search_after). For more information about index settings, see [Index settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index-settings/). -This section describes the permissions needed to use PIT API operations if you are running OpenSearch with the Security plugin enabled. - -Users can access all PIT API operations using the `point_in_time_full_access` role. If this role doesn't meet your needs, mix and match individual PIT permissions to suit your use case. Each action corresponds to an operation in the REST API. For example, the `indices:data/read/point_in_time/create` permission lets you create a PIT. The following are the possible permissions: - -- `indices:data/read/point_in_time/create` – Create API -- `indices:data/read/point_in_time/delete` – Delete API -- `indices:data/read/point_in_time/readall` – List All PITs API -- `indices:data/read/search` – Search API -- `indices:monitor/point_in_time/segments` – PIT Segments API - -For `all` API operations, such as list all and delete all, the user needs the all indexes (*) permission. For API operations such as search, create PIT, or delete list, the user only needs individual index permissions. - -The PIT IDs always contain the underlying (resolved) indexes when saved. The following sections describe the required permissions for aliases and data streams. - -### Alias permissions - -For aliases, users must have either index **or** alias permissions for any PIT operation. - -### Data stream permissions - -For data streams, users must have both the data stream **and** the data stream's backing index permissions for any PIT operation. For example, the user must have permissions for the `data-stream-11` data stream and for its backing index `.ds-my-data-stream11-000001`. - -If users have the data stream permissions only, they will be able to create a PIT, but they will not be able to use the PIT ID for other operations, such as search, without the backing index permissions. ## API -The following table lists all [Point in Time API]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api) functions. +The following table lists all [Point in Time API]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/) functions. Function | API | Description :--- | :--- | :--- -[Create PIT]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api#create-a-pit) | `POST /<target_indexes>/_search/point_in_time?keep_alive=1h` | Creates a PIT. -[List PIT]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api#list-all-pits) | `GET /_search/point_in_time/_all` | Lists all PITs. -[Delete PIT]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api#delete-pits) | `DELETE /_search/point_in_time`<br> `DELETE /_search/point_in_time/_all` | Deletes a PIT or all PITs. -[PIT segments]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api#pit-segments) | `GET /_cat/pit_segments/_all` | Provides information about the disk utilization of a PIT by describing its Lucene segments. +[Create PIT]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/#create-a-pit) | `POST /<target_indexes>/_search/point_in_time?keep_alive=1h` | Creates a PIT. +[List PIT]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/#list-all-pits) | `GET /_search/point_in_time/_all` | Lists all PITs. +[Delete PIT]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api/#delete-pits) | `DELETE /_search/point_in_time`<br> `DELETE /_search/point_in_time/_all` | Deletes a PIT or all PITs. +[CAT PIT segments]({{site.url}}{{site.baseurl}}/api-reference/cat/cat-pit-segments/) | `GET /_cat/pit_segments/_all` | Provides information about the disk utilization of a PIT by describing its Lucene segments. -For information about the relevant cluster and node settings, see [PIT Settings]({{site.url}}{{site.baseurl}}/opensearch/point-in-time-api#pit-settings). +For required permissions, see [Security model]({{site.url}}{{site.baseurl}}/api-reference/search-apis/point-in-time-api#security-model). + +## PIT settings + +You can specify the following settings for a PIT. + +Setting | Description | Default +:--- | :--- | :--- +`point_in_time.max_keep_alive` | A cluster-level setting that specifies the maximum value for the `keep_alive` parameter. | `24h` +`search.max_open_pit_context` | A node-level setting that specifies the maximum number of open PIT contexts for the node. | `300` diff --git a/_search-plugins/searching-data/retrieve-specific-fields.md b/_search-plugins/searching-data/retrieve-specific-fields.md new file mode 100644 index 00000000..589d0345 --- /dev/null +++ b/_search-plugins/searching-data/retrieve-specific-fields.md @@ -0,0 +1,1191 @@ +--- +layout: default +parent: Customizing search results +title: Retrieve specific fields +nav_order: 50 +--- + +# Retrieve specific fields + +When you run a basic search in OpenSearch, by default, the original JSON objects that were used during indexing are also returned in the response for each hit in the `_source` object. This can lead to large amounts of data being transferred through the network, increasing latency and costs. There are several ways to limit the responses to only the required information. + +<!-- vale off --> +## Disabling _source +<!-- vale on --> +You can set `_source` to `false` in a search request to exclude the `_source` field from the response: + +```json +GET /index1/_search +{ + "_source": false, + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +Because no fields were selected in the preceding search, the retrieved hits will only include the `_index`, `_id` and `_score` of the hits: + +```json +{ + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "index1", + "_id" : "41", + "_score" : 1.0 + }, + { + "_index" : "index1", + "_id" : "51", + "_score" : 1.0 + } + ] + } +} +``` + +The `_source` can also be disabled in index mappings by using the following configuration: + +```json +"mappings": { + "_source": { + "enabled": false + } +} +``` + +<!-- vale off --> +If `_source` is disabled in the index mappings, [searching with docvalue fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-doc-value-fields) and [searching with stored fields]({{site.url}}{{site.baseurl}}/search-plugins/searching-data/retrieve-specific-fields/#searching-with-stored-fields) become extremely useful. +<!-- vale on --> + +## Specifying the fields to retrieve + +You can list the fields you want to retrieve in the `fields` parameter. Wildcard patterns are also accepted: + +```json +GET /index1/_search +{ + "_source": false, + "fields": ["age", "nam*"], + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +The response contains the `name` and `age` fields: + +```json +{ + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "index1", + "_id" : "41", + "_score" : 1.0, + "fields" : { + "name" : [ + "John Doe" + ], + "age" : [ + 30 + ] + } + }, + { + "_index" : "index1", + "_id" : "51", + "_score" : 1.0, + "fields" : { + "name" : [ + "Jane Smith" + ], + "age" : [ + 25 + ] + } + } + ] + } +} +``` + +### Extracting fields with a custom format + +You can also use object notation to apply a custom format to the chosen field. + +If you have the following document: + +```json +{ + "_index": "my_index", + "_type": "_doc", + "_id": "1", + "_source": { + "title": "Document 1", + "date": "2023-07-04T12:34:56Z" + } +} +``` + +Then you can query using the `fields` parameter and a custom format: + +```json +GET /my_index/_search +{ + "query": { + "match_all": {} + }, + "fields": [ + { + "field": "date", + "format": "yyyy-MM-dd" + } + ], + "_source": false +} +``` +{% include copy-curl.html %} + +Additionally, you can use [most fields]({{site.url}}{{site.baseurl}}/query-dsl/full-text/multi-match/#most-fields) and [field aliases]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/alias/) in the `fields` parameter because it queries both the document `_source` and `_mappings` of the index. + +## Searching with doc value fields + +To retrieve specific fields from the index, you can also use the `docvalue_fields` parameter. This parameter works slightly differently as compared to the `fields` parameter. It retrieves information from doc values rather than from the `_source` field, which is more efficient for fields that are not analyzed, like keyword, date, and numeric fields. Doc values have a columnar storage format optimized for efficient sorting and aggregations. It stores the values on disk in a way that is easy to read. When you use `docvalue_fields`, OpenSearch reads the values directly from this optimized storage format. It is useful for retrieving values of fields that are primarily used for sorting, aggregations, and for use in scripts. + +Because `text` fields do not have doc values, OpenSearch rejects a `docvalue_fields` request for a `text` field unless [field data]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/field-data/) is enabled for that field. If field data is enabled, OpenSearch loads the field's terms into the field data cache in heap memory to return them, which increases memory use. The returned values are the analyzed terms, for example, `["great", "tent"]`, not the original text. To return the original text of a `text` field, use the `fields` parameter or `_source`. +{: .warning} + +The following example demonstrates how to use the `docvalue_fields` parameter. + + +1. Create an index with the following mappings: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "keyword" }, + "publication_date": { "type": "date" }, + "price": { "type": "double" } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index the following documents into the newly created index: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2021-01-01", + "price": 29.99 + } + ``` + {% include copy-curl.html %} + + ```json + POST /my_index/_doc/2 + { + "title": "Advanced OpenSearch", + "author": "Jane Smith", + "publication_date": "2022-01-01", + "price": 39.99 + } + ``` + {% include copy-curl.html %} + +3. Retrieve only the `author` and `publication_date` fields using `docvalue_fields`: + + ```json + POST /my_index/_search + { + "_source": false, + "docvalue_fields": ["author", "publication_date"], + "query": { + "match_all": {} + } + } + ``` + {% include copy-curl.html %} + +The response contains the `author` and `publication_date` fields: + +```json +{ + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "fields": { + "author": ["John Doe"], + "publication_date": ["2021-01-01T00:00:00.000Z"] + } + }, + { + "_index": "my_index", + "_id": "2", + "_score": 1.0, + "fields": { + "author": ["Jane Smith"], + "publication_date": ["2022-01-01T00:00:00.000Z"] + } + } + ] + } +} +``` +### Using wildcards and custom formats with doc value fields + +The `docvalue_fields` parameter accepts wildcard patterns, such as `*_date`, that match several fields. To format the returned values, specify an object containing the `field` and a `format`. For `date` fields, the format is a [date format]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/date/#formats). For numeric fields, the format is a [Java `DecimalFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html) pattern, such as `#.00`. + +For example, create an index containing an order with two date fields and a numeric total: + +```json +PUT /orders-dv +{ + "mappings": { + "properties": { + "order_date": { "type": "date" }, + "ship_date": { "type": "date" }, + "total": { "type": "double" } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /orders-dv/_doc/1?refresh=true +{ + "order_date": "2026-10-01T09:30:00Z", + "ship_date": "2026-10-03", + "total": 42.5 +} +``` +{% include copy-curl.html %} + +The following request returns both date fields formatted as `yyyy-MM-dd` and the total with two decimal places: + +```json +GET /orders-dv/_search +{ + "_source": false, + "docvalue_fields": [ + { + "field": "*_date", + "format": "yyyy-MM-dd" + }, + { + "field": "total", + "format": "#.00" + } + ] +} +``` +{% include copy-curl.html %} + +The response contains the formatted values: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + "_index": "orders-dv", + "_id": "1", + "_score": 1, + "fields": { + "order_date": [ + "2026-10-01" + ], + "total": [ + "42.50" + ], + "ship_date": [ + "2026-10-03" + ] + } + } + ] + } +} +``` + +<!-- vale off --> +### Retrieving vector fields using docvalue_fields +<!-- vale on --> +**Introduced 3.7** +{: .label .label-purple } + +You can retrieve `knn_vector` fields using `docvalue_fields` instead of the `_source`. This is faster because OpenSearch reads the vector directly from `doc_values` rather than parsing the full `_source` document. + +Retrieving `knn_vector` fields from `doc_values` supports all vector data types (`float`, `byte`, and `binary`), all compression levels, and all k-NN engines (Lucene, Faiss, and NMSLIB). You can use it on existing indexes without reindexing. + +For performance tuning guidance, see [Retrieve vectors using doc values]({{site.url}}{{site.baseurl}}/vector-search/performance-tuning-search/#retrieve-vectors-using-doc-values). + +The following output formats are supported. + +| Format | Description | +| :--- | :--- | +| `binary` (Default) | Returns vectors as Base64-encoded little-endian byte strings. Provides approximately 2x throughput improvement over the `array` format for JSON transport and reduces response payload size by 30--40%. | +| `array` | Returns vectors as JSON numeric arrays. | + +To retrieve a vector field using `docvalue_fields`, follow these steps: + +1. Create an index with a `knn_vector` field: + + ```json + PUT /my_vector_index + { + "settings": { + "index.knn": true + }, + "mappings": { + "properties": { + "my_vector": { + "type": "knn_vector", + "dimension": 4 + }, + "title": { + "type": "text" + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index a document: + + ```json + POST /my_vector_index/_doc/1 + { + "my_vector": [1.0, 2.0, 3.0, 4.0], + "title": "Sample document" + } + ``` + {% include copy-curl.html %} + +3. Retrieve the vector using `docvalue_fields` using the default `binary` format: + + ```json + POST /my_vector_index/_search + { + "_source": false, + "docvalue_fields": ["my_vector"], + "query": { + "knn": { + "my_vector": { + "vector": [1.0, 2.0, 3.0, 4.0], + "k": 5 + } + } + } + } + ``` + {% include copy-curl.html %} + + The response returns the vector as a Base64-encoded string: + + ```json + { + "hits": { + "hits": [ + { + "_id": "1", + "_score": 1.0, + "fields": { + "my_vector": ["AACAPwAAAEAAAEBAAACAQA=="] + } + } + ] + } + } + ``` + +4. To retrieve the vector as a JSON numeric array, specify the `array` format: + + ```json + POST /my_vector_index/_search + { + "_source": false, + "docvalue_fields": [{"field": "my_vector", "format": "array"}], + "query": { + "knn": { + "my_vector": { + "vector": [1.0, 2.0, 3.0, 4.0], + "k": 5 + } + } + } + } + ``` + {% include copy-curl.html %} + + The response returns the vector as a numeric array: + + ```json + { + "hits": { + "hits": [ + { + "_id": "1", + "_score": 1.0, + "fields": { + "my_vector": [[1.0, 2.0, 3.0, 4.0]] + } + } + ] + } + } + ``` + +To retrieve other document fields from the `_source` while retrieving vectors using `doc_values`, exclude the vector field from the `_source`: + +```json +POST /my_vector_index/_search +{ + "_source": { + "excludes": ["my_vector"] + }, + "docvalue_fields": [{"field": "my_vector", "format": "array"}], + "query": { + "knn": { + "my_vector": { + "vector": [1.0, 2.0, 3.0, 4.0], + "k": 5 + } + } + } +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +### Using docvalue_fields with nested objects +<!-- vale on --> + +In OpenSearch, if you want to retrieve doc values for nested objects, you cannot directly use the `docvalue_fields` parameter because it will return an empty array. Instead, you should use the `inner_hits` parameter with its own `docvalue_fields` property, as shown in the following example. + +1. Define the index mappings: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "keyword" }, + "comments": { + "type": "nested", + "properties": { + "username": { "type": "keyword" }, + "content": { "type": "text" }, + "created_at": { "type": "date" } + } + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index your data: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "comments": [ + { + "username": "alice", + "content": "Great article!", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "username": "bob", + "content": "Very informative.", + "created_at": "2023-01-02T12:00:00Z" + } + ] + } + ``` + {% include copy-curl.html %} + +3. Perform a search with `inner_hits` and `docvalue_fields`: + + ```json + POST /my_index/_search + { + "query": { + "nested": { + "path": "comments", + "query": { + "match_all": {} + }, + "inner_hits": { + "docvalue_fields": ["username", "created_at"] + } + } + } + } + ``` + {% include copy-curl.html %} + +The following is the expected response: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "OpenSearch Basics", + "author": "John Doe", + "comments": [ + { + "username": "alice", + "content": "Great article!", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "username": "bob", + "content": "Very informative.", + "created_at": "2023-01-02T12:00:00Z" + } + ] + }, + "inner_hits": { + "comments": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 0 + }, + "docvalue_fields": { + "username": ["alice"], + "created_at": ["2023-01-01T12:00:00Z"] + } + }, + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1 + }, + "docvalue_fields": { + "username": ["bob"], + "created_at": ["2023-01-02T12:00:00Z"] + } + } + ] + } + } + } + } + ] + } +} +``` + +## Searching with stored fields + +By default, OpenSearch stores the entire document in the `_source` field and uses it to return document contents in search results. However, you might also want to store certain fields separately for more efficient retrieval. You can explicitly store and retrieve specific document fields separately from the `_source` field by using `stored_fields`. + +Unlike `_source`, `stored_fields` must be explicitly defined in the mappings for fields you want to store separately. It can be useful if you frequently need to retrieve only a small subset of fields and want to avoid retrieving the entire `_source` field. The following example demonstrates how to use the `stored_fields` parameter. + +1. Create an index with the following mappings: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { + "type": "text", + "store": true // Store the title field separately + }, + "author": { + "type": "keyword", + "store": true // Store the author field separately + }, + "publication_date": { + "type": "date" + }, + "price": { + "type": "double" + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index your data: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2022-01-01", + "price": 29.99 + } + ``` + {% include copy-curl.html %} + + ```json + POST my_index/_doc/2 + { + "title": "Advanced OpenSearch", + "author": "Jane Smith", + "publication_date": "2023-01-01", + "price": 39.99 + } + ``` + {% include copy-curl.html %} + +3. Perform a search with `stored_fields`: + + ```json + POST /my_index/_search + { + "_source": false, + "stored_fields": ["title", "author"], + "query": { + "match_all": {} + } + } + ``` + {% include copy-curl.html %} + +The following is the expected response: + +```json +{ + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "fields": { + "title": ["OpenSearch Basics"], + "author": ["John Doe"] + } + }, + { + "_index": "my_index", + "_id": "2", + "_score": 1.0, + "fields": { + "title": ["Advanced OpenSearch"], + "author": ["Jane Smith"] + } + } + ] + } +} +``` + +Note the following behavior of the `stored_fields` parameter: + +- To return all stored fields, set `stored_fields` to `"*"`. +- To return only the hit metadata, such as `_index` and `_id`, without `_source` or any stored fields, set `stored_fields` to an empty array (`[]`). +- If you request a field that is not stored, OpenSearch omits it from the response without an error. +- Stored field values are returned as arrays. Metadata fields, such as `_routing`, are returned as single values. +- You can request only leaf fields, such as `address.city`. OpenSearch rejects a request that specifies an object field, such as `address`. + +To disable stored fields completely, set `stored_fields` to `_none_`. Each hit then contains no stored fields, no `_source`, and no `_id`. OpenSearch rejects requests that set `stored_fields` to `_none_` and also request `_source`. +{: .note} +### Searching stored fields with nested objects + +In OpenSearch, if you want to retrieve `stored_fields` for nested objects, you cannot directly use the `stored_fields` parameter because no data will be returned. Instead, you should use the `inner_hits` parameter with its own `stored_fields` property, as shown in the following example. + +1. Create an index with the following mappings: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "keyword" }, + "comments": { + "type": "nested", + "properties": { + "username": { "type": "keyword", "store": true }, + "content": { "type": "text", "store": true }, + "created_at": { "type": "date", "store": true } + } + } + } + } + } + ``` + {% include copy-curl.html %} + +2. Index your data: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "comments": [ + { + "username": "alice", + "content": "Great article!", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "username": "bob", + "content": "Very informative.", + "created_at": "2023-01-02T12:00:00Z" + } + ] + } + ``` + {% include copy-curl.html %} + +3. Perform a search with `inner_hits` and `stored_fields`: + + ```json + POST /my_index/_search + { + "_source": false, + "query": { + "nested": { + "path": "comments", + "query": { + "match_all": {} + }, + "inner_hits": { + "stored_fields": ["comments.username", "comments.content", "comments.created_at"] + } + } + } + } + ``` + {% include copy-curl.html %} + +The following is the expected response: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "inner_hits": { + "comments": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 0 + }, + "fields": { + "comments.username": ["alice"], + "comments.content": ["Great article!"], + "comments.created_at": ["2023-01-01T12:00:00.000Z"] + } + }, + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1 + }, + "fields": { + "comments.username": ["bob"], + "comments.content": ["Very informative."], + "comments.created_at": ["2023-01-02T12:00:00.000Z"] + } + } + ] + } + } + } + } + ] + } +} +``` + +## Using source filtering + +Source filtering is a way to control which parts of the `_source` field are included in the search response. Including only the necessary fields in the response can help reduce the amount of data transferred over the network and improve performance. + +You can include or exclude specific fields from the `_source` field in the search response using complete field names or simple wildcard patterns. The following example demonstrates how to include specific fields. + +1. Index your data: + + ```json + PUT /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2021-01-01", + "price": 29.99 + } + ``` + {% include copy-curl.html %} + +2. Perform a search using source filtering: + + ```json + POST /my_index/_search + { + "_source": ["title", "author"], + "query": { + "match_all": {} + } + } + ``` + {% include copy-curl.html %} + +The following is the expected response: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "OpenSearch Basics", + "author": "John Doe" + } + } + ] + } +} +``` + +### Excluding fields with source filtering + +You can choose to exclude fields by using the `"excludes"` parameter in a search request, as shown in the following example: + +```json +POST /my_index/_search +{ + "_source": { + "excludes": ["price"] + }, + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + +The following is the expected response: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2021-01-01" + } + } + ] + } +} +``` + +### Including and excluding fields in the same search + +In some cases, both the `include` and `exclude` parameters may be necessary. When a field matches a pattern in both lists, OpenSearch omits the field because `excludes` takes precedence over `includes`. The following examples demonstrate how to include and exclude fields in the same search. + +Consider a `products` index containing the following document: + +```json +{ + "product_id": "123", + "name": "Smartphone", + "category": "Electronics", + "price": 699.99, + "description": "A powerful smartphone with a sleek design.", + "reviews": [ + { + "user": "john_doe", + "rating": 5, + "comment": "Great phone!", + "date": "2023-01-01" + }, + { + "user": "jane_doe", + "rating": 4, + "comment": "Good value for money.", + "date": "2023-02-15" + } + ], + "supplier": { + "name": "TechCorp", + "contact_email": "support@techcorp.com", + "address": { + "street": "123 Tech St", + "city": "Techville", + "zipcode": "12345" + } + }, + "inventory": { + "stock": 50, + "warehouse_location": "A1" + } +} +``` + +To perform a search on this index while including only the `name`, `price`, `reviews`, and `supplier` fields in the response, and excluding the `contact_email` field from the `supplier` object and the `comment` field from the `reviews` object, execute the following search: + +```json +GET /products/_search +{ + "_source": { + "includes": ["name", "price", "reviews.*", "supplier.*"], + "excludes": ["reviews.comment", "supplier.contact_email"] + }, + "query": { + "match": { + "category": "Electronics" + } + } +} +``` +{% include copy-curl.html %} + +The following is the expected response: + +```json +{ + "hits": { + "hits": [ + { + "_source": { + "name": "Smartphone", + "price": 699.99, + "reviews": [ + { + "user": "john_doe", + "rating": 5, + "date": "2023-01-01" + }, + { + "user": "jane_doe", + "rating": 4, + "date": "2023-02-15" + } + ], + "supplier": { + "name": "TechCorp", + "address": { + "street": "123 Tech St", + "city": "Techville", + "zipcode": "12345" + } + } + } + } + ] + } +} +``` + +### Source filtering limitations + +Source filtering matches the field names in the original JSON document, so it cannot return values that OpenSearch derives during indexing. Multi-fields, [field aliases]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/alias/), and fields populated by `copy_to` are not part of the source, and a request for those fields returns an empty `_source` object. + +OpenSearch loads and parses the entire source document even when the request asks for only a few fields, so source filtering reduces network transfer but not disk reads. To read individual fields directly from the index, use [`docvalue_fields`](#searching-with-doc-value-fields) or [`stored_fields`](#searching-with-stored-fields). + +## Using scripted fields + +The `script_fields` parameter allows you to include custom fields whose values are computed using scripts in your search results. This can be useful for calculating values dynamically based on the document data. You can also retrieve `derived fields` by using a similar approach. For more information, see [Retrieving fields]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/derived/#retrieving-fields). + +If you have an index of products, where each product document contains the `price` and `discount_percentage` fields. You can use `script_fields` parameter to include a custom field in the search results that displays the discounted price of each product. The following example demonstrates how to use the `script_fields` parameter: + + +1. Index the data: + + ```json + PUT /products/_doc/123 + { + "product_id": "123", + "name": "Smartphone", + "price": 699.99, + "discount_percentage": 10, + "category": "Electronics", + "description": "A powerful smartphone with a sleek design." + } + ``` + {% include copy-curl.html %} + +2. Use the `script_fields` parameter to include a custom field called `discounted_price` in the search results. This field will be calculated based on the `price` and `discount_percentage` fields using a script: + + ```json + GET /products/_search + { + "_source": ["product_id", "name", "price", "discount_percentage"], + "query": { + "match": { + "category": "Electronics" + } + }, + "script_fields": { + "discounted_price": { + "script": { + "lang": "painless", + "source": "doc[\"price\"].value * (1 - doc[\"discount_percentage\"].value / 100)" + } + } + } + } + ``` + {% include copy-curl.html %} + +You should receive the following response: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "products", + "_id": "123", + "_score": 1.0, + "_source": { + "product_id": "123", + "name": "Smartphone", + "price": 699.99, + "discount_percentage": 10 + }, + "fields": { + "discounted_price": [629.991] + } + } + ] + } +} +``` + +Scripts can access field values in two ways: + +- `doc['<field>'].value` reads the value from doc values. This is fast but works only for fields that have doc values, such as `keyword`, numeric, and `date` fields, or for `text` fields that have field data enabled. +- `params['_source']['<field>']` reads the value from the document `_source`. This works for any field, including `text` fields, but is slower because OpenSearch must load and parse the source of each document. + +For example, the `name` field in the preceding example is mapped as `text`, so `doc['name']` is not available. The following request calculates the length of the product name using `params['_source']`: + +```json +GET /products/_search +{ + "_source": false, + "script_fields": { + "name_length": { + "script": { + "source": "params['_source']['name'].length()" + } + } + } +} +``` +{% include copy-curl.html %} + +The response contains the length of `Smartphone`: + +```json +"fields": { + "name_length": [10] +} +``` diff --git a/_search-plugins/searching-data/search-shard-routing.md b/_search-plugins/searching-data/search-shard-routing.md new file mode 100644 index 00000000..5fb7ce45 --- /dev/null +++ b/_search-plugins/searching-data/search-shard-routing.md @@ -0,0 +1,236 @@ +--- +layout: default +parent: Improving search performance +title: Search shard routing +nav_order: 30 +--- + +# Search shard routing + +To ensure redundancy and improve search performance, OpenSearch distributes index data across multiple primary shards, with each primary shard having one or more replica shards. When a search query is executed, OpenSearch routes the request to a node containing either a primary or replica index shard. This technique is known as _search shard routing_. + + +## Adaptive replica selection + +In order to improve latency, search requests are routed using _adaptive replica selection_, which chooses the nodes based on the following factors: + +- The amount of time it took a particular node to run previous requests. +- The latency between the coordinating node and the selected node. +- The queue size of the node's search thread pool. + +OpenSearch uses adaptive replica selection only for searches that do not specify a [`preference`](#node-and-shard-selection-during-searches) value. Adaptive replica selection is also not used if weighted shard routing is configured or if shard allocation awareness attributes are set and the `cluster.search.ignore_awareness_attributes` setting is `false`. In these cases, OpenSearch routes searches based on the routing weights or awareness attributes. For more information, see [Cluster-level search settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/cluster-settings/#cluster-level-search-settings). + +If you have permissions to call the OpenSearch REST APIs, you can turn off search shard routing. For more information about REST API user access, see [REST management API settings]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/security-settings/#rest-management-api-settings). To disable search shard routing, update the cluster settings as follows: + +```json +PUT /_cluster/settings +{ + "persistent": { + "cluster.routing.use_adaptive_replica_selection": false + } +} +``` +{% include copy-curl.html %} + +If you turn off search shard routing, OpenSearch will use round-robin routing, which can negatively impact search latency. +{: .note} + +## Node and shard selection during searches + +OpenSearch uses all nodes to choose the best routing for search requests. However, in some cases you may want to manually select the nodes or shards to which the search request is sent, including the following: + +- Using cached previous searches. +- Dedicating specific hardware to searches. +- Using only local nodes for searches. + +Routing searches to specific shard copies can create hotspots because the search load is no longer distributed evenly across the cluster. Use the `preference` parameter only when the benefits, such as better cache use, outweigh this cost. + +You can use the `preference` parameter in the search query to indicate the search destination. The following is a complete list of available options: + +1. `_primary`: Forces the search to execute only on primary shards. + + ```json + GET /my-index/_search?preference=_primary + ``` + {% include copy-curl.html %} + +2. `_primary_first`: Prefers primary shards but will use replica shards if the primary shards are not available. + + ```json + GET /my-index/_search?preference=_primary_first + ``` + {% include copy-curl.html %} + +3. `_replica`: Forces the search to execute only on replica shards. + + ```json + GET /my-index/_search?preference=_replica + ``` + {% include copy-curl.html %} + +4. `_replica_first`: Prefers replica shards but will use primary shards if no replica shards are available. + + ```json + GET /my-index/_search?preference=_replica_first + ``` + {% include copy-curl.html %} + +5. `_only_nodes:<node-id>,<node-id>`: Limits the search to execute only on specific nodes. You can specify nodes using any [node specification]({{site.url}}{{site.baseurl}}/api-reference/nodes-apis/index/#node-filters), such as node IDs, node names, wildcard patterns like `data-node-*`, or node attributes like `zone:us-east-1a`. If none of the specified nodes contain a copy of a shard, the search fails. + + ```json + GET /my-index/_search?preference=_only_nodes:node-1,node-2 + ``` + {% include copy-curl.html %} + +6. `_prefer_nodes:<node-id>,<node-id>`: Prefers to execute the search on specific nodes but will use other nodes if the preferred nodes are not available. + + ```json + GET /my-index/_search?preference=_prefer_nodes:node-1,node-2 + ``` + {% include copy-curl.html %} + +7. `_shards:<shard-id>,<shard-id>`: Limits the search to specific shards. You can combine `_shards` with another preference value by separating them with a pipe character (`|`), for example, `_shards:0,1|_local`. The `_shards` value must come first. + + ```json + GET /my-index/_search?preference=_shards:0,1 + ``` + {% include copy-curl.html %} + +8. `_local`: Executes the search on the local node if possible, which can reduce latency. + + ```json + GET /my-index/_search?preference=_local + ``` + {% include copy-curl.html %} + +9. `_only_local`: Executes the search only on shard copies allocated to the local node. + + ```json + GET /my-index/_search?preference=_only_local + ``` + {% include copy-curl.html %} + +10. `_search_replica`: Executes the search only on [search replicas]({{site.url}}{{site.baseurl}}/tuning-your-cluster/performance-tuning/separate-index-and-search-workloads/), which are hosted on nodes with the `search` role. If the index has no search replicas, the search fails. + + ```json + GET /my-index/_search?preference=_search_replica + ``` + {% include copy-curl.html %} + +11. Custom string: You can use any custom string as the preference value. OpenSearch routes requests that contain the same string to the same shard copies, which can be useful for caching. The string must not start with an underscore (`_`). A session ID or user name is a good choice so that each user's searches use the same shard copies. The routing stays consistent only while the cluster state doesn't change: if shards are relocated or a node fails, the same string can be routed to different shard copies. + + ```json + GET /my-index/_search?preference=custom_string + ``` + {% include copy-curl.html %} + +The `_only_local` value guarantees that the search uses only the shard copies on the local node, which makes it useful for troubleshooting a specific node. Other `preference` values do not fully guarantee which shard copies serve the search. Because shard copies can be in different refresh states, repeating a search on an index that is being updated can return different results if the search is served by different copies. +{: .note} + +## Custom routing during index and search + +You can specify routing during both indexing and search operations. + +### Routing during indexing + +When you index a document, OpenSearch calculates a hash of the routing value and uses this hash to determine the shard on which the document will be stored. If you don't specify a routing value, OpenSearch uses the document ID to calculate the hash. + +The following is an example index operation with a routing value: + +```json +POST /index1/_doc/1?routing=user1 +{ + "name": "John Doe", + "age": 20 +} +``` +{% include copy-curl.html %} + +In this example, the document with ID `1` is indexed with the routing value `user1`. All documents with the same routing value will be stored on the same shard. + +### Routing during searches + +When you search for documents, specifying the same routing value ensures that the search request is routed to the appropriate shard. This can significantly improve performance by reducing the number of shards that need to be queried. + +The following example request searches with a specific routing value: + +```json +GET /index1/_search?routing=user1 +{ + "query": { + "match": { + "name": "John Doe" + } + } +} +``` +{% include copy-curl.html %} + +In this example, the search query is routed to the shard containing documents indexed with the routing value `user1`. + +Caution needs to be exercised when using custom routing in order to prevent hot spots and data skew: + + - A _hot spot_ occurs when a disproportionate number of documents are routed to a single shard. This can lead to that shard becoming a bottleneck because it will have to handle more read and write operations compared to other shards. Consequently, this shard may experience higher CPU, memory, and I/O usage, leading to performance degradation. + + - _Data skew_ refers to an uneven distribution of data across shards. If routing values are not evenly distributed, some shards may end up storing significantly more data than others. This can result in imbalanced storage usage, where certain nodes have a much higher disk utilization compared to others. + +## Concurrent shard request + +Hitting a large number of shards simultaneously during a search can significantly impact CPU and memory consumption. By default, OpenSearch does not reject these requests. However, there are a number of methods that you can use to mitigate this risk. The following sections describe these methods. + +### Limiting the number of shards that can be queried concurrently + +You can use the `max_concurrent_shard_requests` parameter in the search request to limit the number of shards that can be queried concurrently. For example, the following request limits the number of concurrent shard requests to `12`: + +```json +GET /index1/_search?max_concurrent_shard_requests=12 +{ + "query": { + "match_all": {} + } +} +``` +{% include copy-curl.html %} + + +### Defining a search shard count limit + +You can define the dynamic `action.search.shard_count.limit` setting either in your `opensearch.yml` file or by using the REST API. Any search request that exceeds this limit will be rejected and throw an error. This helps to prevent a single search request from consuming too many resources, which can degrade the performance of the entire cluster. The following example request updates this cluster setting using the API: + +```json +PUT /_cluster/settings +{ + "transient": { + "action.search.shard_count.limit": 1000 + } +} +``` +{% include copy-curl.html %} + +### Configuring the search thread pool + +OpenSearch uses thread pools to manage the execution of various tasks, including search operations. The search thread pool is specifically used for search requests. You can adjust the size and queue capacity of the search thread pool by adding the following settings to `opensearch.yml`: + +```yaml +thread_pool.search.size: 100 +thread_pool.search.queue_size: 1000 +``` + +This setting is static. For more information about how to configure dynamic and static settings, see [Configuring OpenSearch]({{site.url}}{{site.baseurl}}/install-and-configure/configuring-opensearch/index/). + +#### Thread pool states + +The following three states describe thread pool operations: + + - _Thread assignment_: If there are available threads in the search thread pool, then the request is immediately assigned to a thread and begins processing. + + - _Queueing_: If all threads in the search thread pool are busy, then the request is placed in the queue. + + - _Rejection_: If the queue is full (for example, the number of queued requests reaches the queue size limit), then additional incoming search requests are rejected until there is space available in the queue. + +You can check the current configuration of the search thread pool by running the following request: + +```json +GET /_cat/thread_pool/search?v&h=id,name,active,rejected,completed,size,queue_size +``` +{% include copy-curl.html %} diff --git a/_search-plugins/searching-data/sort.md b/_search-plugins/searching-data/sort.md index fa4875d3..896693b2 100644 --- a/_search-plugins/searching-data/sort.md +++ b/_search-plugins/searching-data/sort.md @@ -1,18 +1,18 @@ --- layout: default title: Sort results -parent: Searching data -nav_order: 22 +parent: Customizing search results +nav_order: 30 redirect_from: - /opensearch/search/sort/ --- -## Sort results +# Sort results Sorting allows your users to sort results in a way that’s most meaningful to them. By default, full-text queries sort results by the relevance score. -You can choose to sort the results by any field value in either ascending or descending order by setting the `order` parameter to `asc` or `desc`. +You can choose to sort the results by any field value in either ascending or descending order by setting the `order` parameter to `asc` or `desc`. If you don't specify `order`, results are sorted in descending order when you sort by `_score` and in ascending order when you sort by any other field. For example, to sort results by descending order of a `line_id` value, use the following query: @@ -35,6 +35,7 @@ GET shakespeare/_search ] } ``` +{% include copy-curl.html %} The results are sorted by `line_id` in descending order: @@ -258,8 +259,9 @@ GET shakespeare/_search ] } ``` +{% include copy-curl.html %} -You can continue to sort by any number of field values to get the results in just the right order. It doesn’t have to be a numerical value—you can also sort by date or timestamp fields: +You can continue to sort by any number of field values to get the results in the right order. It doesn’t have to be a numerical value—you can also sort by date or timestamp fields: ```json "sort": [ @@ -270,6 +272,7 @@ You can continue to sort by any number of field values to get the results in jus } ] ``` +{% include copy-curl.html %} A text field that is analyzed cannot be used to sort documents, because the inverted index only contains the individual tokenized terms and not the entire string. So you cannot sort by the `play_name`, for example. @@ -294,6 +297,7 @@ GET shakespeare/_search ] } ``` +{% include copy-curl.html %} The results are sorted by the `play_name` field in alphabetical order. @@ -331,6 +335,7 @@ GET shakespeare/_search ] } ``` +{% include copy-curl.html %} ## Sort mode @@ -348,17 +353,21 @@ PUT students/_doc/1 "name": "John Doe", "grades": [70, 90] } +``` +{% include copy-curl.html %} +```json PUT students/_doc/2 { "name": "Mary Major", "grades": [80, 100] } ``` +{% include copy-curl.html %} Sort all students by highest grade average using the `avg` mode: -``` +```json GET students/_search { "query" : { @@ -369,6 +378,7 @@ GET students/_search ] } ``` +{% include copy-curl.html %} The response contains students sorted by `grades` in descending order: @@ -424,9 +434,248 @@ The response contains students sorted by `grades` in descending order: } ``` +## Sorting numeric fields across indexes + +When you search several indexes, the same field can be mapped as a different numeric or date type in each index. Use the `numeric_type` option to convert the sort values from all indexes to one type. Valid values are `double`, `long`, `date`, and `date_nanos`. + +For example, the `prices-eu` index maps `price` as `double`, and the `prices-us` index maps it as `long`: + +```json +PUT /prices-eu +{ + "mappings": { + "properties": { + "product": { "type": "keyword" }, + "price": { "type": "double" } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /prices-us +{ + "mappings": { + "properties": { + "product": { "type": "keyword" }, + "price": { "type": "long" } + } + } +} +``` +{% include copy-curl.html %} + +Index documents into both indexes: + +```json +POST /_bulk?refresh=true +{ "index": { "_index": "prices-eu", "_id": "1" } } +{ "product": "tent", "price": 129.5 } +{ "index": { "_index": "prices-eu", "_id": "2" } } +{ "product": "lantern", "price": 24.99 } +{ "index": { "_index": "prices-us", "_id": "1" } } +{ "product": "stove", "price": 60 } +{ "index": { "_index": "prices-us", "_id": "2" } } +{ "product": "backpack", "price": 95 } +``` +{% include copy-curl.html %} + +Without `numeric_type`, each hit's sort value keeps the type of its index, for example, `24.99` from `prices-eu` and `60` from `prices-us`. The following request converts all sort values to `double`: + +```json +GET /prices-eu,prices-us/_search +{ + "sort": [ + { + "price": { + "order": "asc", + "numeric_type": "double" + } + } + ] +} +``` +{% include copy-curl.html %} + +The sort values of the `prices-us` documents are returned as `60.0` and `95.0`: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + "_index": "prices-eu", + "_id": "2", + "_score": null, + "_source": { + "product": "lantern", + "price": 24.99 + }, + "sort": [ + 24.99 + ] + }, + { + "_index": "prices-us", + "_id": "1", + "_score": null, + "_source": { + "product": "stove", + "price": 60 + }, + "sort": [ + 60.0 + ] + }, + { + "_index": "prices-us", + "_id": "2", + "_score": null, + "_source": { + "product": "backpack", + "price": 95 + }, + "sort": [ + 95.0 + ] + }, + { + "_index": "prices-eu", + "_id": "1", + "_score": null, + "_source": { + "product": "tent", + "price": 129.5 + }, + "sort": [ + 129.5 + ] + } + ] + } +} +``` + +If you specify `long`, decimal values are truncated. For example, `129.5` and `24.99` are returned as `129` and `24`, and documents that differ only in their decimal part sort as equal. + +### Sorting date and date nanosecond fields + +A `date` field stores values in milliseconds, while a `date_nanos` field stores values in nanoseconds. If the sort field is mapped as `date` in one index and as `date_nanos` in another, OpenSearch compares the raw values without converting them to the same resolution. As a result, documents from the `date_nanos` index sort after all documents from the `date` index in ascending order, regardless of their timestamps. + +For example, create an `events-ms` index that maps `ts` as `date` and an `events-ns` index that maps it as `date_nanos`: + +```json +PUT /events-ms +{ + "mappings": { + "properties": { + "ts": { "type": "date" } + } + } +} +``` +{% include copy-curl.html %} + +```json +PUT /events-ns +{ + "mappings": { + "properties": { + "ts": { "type": "date_nanos" } + } + } +} +``` +{% include copy-curl.html %} + +Index three events. The `upload` event in `events-ns` occurred at 11:00, between the `login` (10:00) and `logout` (12:00) events in `events-ms`: + +```json +POST /_bulk?refresh=true +{ "index": { "_index": "events-ms", "_id": "1" } } +{ "event": "login", "ts": "2026-10-13T10:00:00Z" } +{ "index": { "_index": "events-ms", "_id": "2" } } +{ "event": "logout", "ts": "2026-10-13T12:00:00Z" } +{ "index": { "_index": "events-ns", "_id": "1" } } +{ "event": "upload", "ts": "2026-10-13T11:00:00.123456789Z" } +``` +{% include copy-curl.html %} + +A default ascending sort on `ts` returns `login`, `logout`, and then `upload`. + +To sort the events in chronological order, set `numeric_type` to `date` or `date_nanos`. The `date` value converts all values to milliseconds, and `date_nanos` converts them to nanoseconds: + +```json +GET /events-ms,events-ns/_search +{ + "_source": ["event"], + "sort": [ + { + "ts": { + "order": "asc", + "numeric_type": "date_nanos" + } + } + ] +} +``` +{% include copy-curl.html %} + +The response returns the events in chronological order: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + "_index": "events-ms", + "_id": "1", + "_score": null, + "_source": { + "event": "login" + }, + "sort": [ + 1791885600000000000 + ] + }, + { + "_index": "events-ns", + "_id": "1", + "_score": null, + "_source": { + "event": "upload" + }, + "sort": [ + 1791889200123456789 + ] + }, + { + "_index": "events-ms", + "_id": "2", + "_score": null, + "_source": { + "event": "logout" + }, + "sort": [ + 1791892800000000000 + ] + } + ] + } +} +``` + +Nanosecond values can represent only dates between 1970 and 2262. If a `date` field contains a value outside this range, converting it using `date_nanos` fails for the shard containing that document. The search then returns partial results, and the failure is reported in the `_shards.failures` array of the response. To sort data containing such dates, use `"numeric_type": "date"`. +{: .warning} + ## Sorting nested objects -When sorting [nested]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/nested) objects, provide the `path` parameter specifying the path to the field on which to sort. +When sorting [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) objects, provide the `path` parameter specifying the path to the field on which to sort. For example, in the index `students`, map the variable `first_sem` as `nested`: @@ -442,6 +691,7 @@ PUT students } } ``` +{% include copy-curl.html %} Index two documents with nested fields: @@ -453,7 +703,10 @@ PUT students/_doc/1 "grades": [70, 90] } } +``` +{% include copy-curl.html %} +```json PUT students/_doc/2 { "name": "Mary Major", @@ -462,6 +715,7 @@ PUT students/_doc/2 } } ``` +{% include copy-curl.html %} When sorting by grade average, provide the path to the nested field: @@ -483,6 +737,106 @@ GET students/_search ] } ``` +{% include copy-curl.html %} + +The `nested` object accepts the following parameters. + +Parameter | Description +:--- | :--- +`path` | The path to the nested object that contains the sort field. Required. +`filter` | A query that selects the nested objects whose values are used for sorting. Nested objects that don't match the filter are ignored. Typically, you repeat the nested condition of the search query here so that documents are sorted by the values of the matching nested objects only. +`max_children` | The maximum number of nested objects per document to consider when calculating the sort value. By default, all nested objects are considered. +`nested` | A `nested` object for sorting on a field inside a nested object that is itself inside a nested object. Specify the inner `path` and, optionally, its own `filter` and `max_children`. + +For example, in the following index, each product contains a nested `offers` object with a region and price, and each offer contains a nested `discounts` object: + +```json +PUT sort-offers +{ + "mappings": { + "properties": { + "product": { "type": "keyword" }, + "offers": { + "type": "nested", + "properties": { + "region": { "type": "keyword" }, + "price": { "type": "double" }, + "discounts": { + "type": "nested", + "properties": { + "percent": { "type": "integer" } + } + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +Index two products: + +```json +POST _bulk?refresh=true +{ "index": { "_index": "sort-offers", "_id": "1" } } +{ "product": "tent", "offers": [ { "region": "eu", "price": 120, "discounts": [ { "percent": 5 }, { "percent": 15 } ] }, { "region": "us", "price": 90, "discounts": [ { "percent": 10 } ] } ] } +{ "index": { "_index": "sort-offers", "_id": "2" } } +{ "product": "stove", "offers": [ { "region": "eu", "price": 100, "discounts": [ { "percent": 20 } ] }, { "region": "us", "price": 140, "discounts": [ { "percent": 0 } ] } ] } +``` +{% include copy-curl.html %} + +The following request sorts the products by their lowest price in the `eu` region. The `filter` excludes the `us` offers, so the `tent` is sorted by its `eu` price of 120, not by its lower `us` price of 90: + +```json +GET sort-offers/_search +{ + "_source": ["product"], + "sort": [ + { + "offers.price": { + "order": "asc", + "mode": "min", + "nested": { + "path": "offers", + "filter": { + "term": { "offers.region": "eu" } + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The `stove` is returned first, with a sort value of `100.0`, followed by the `tent`, with a sort value of `120.0`. + +To sort on a field in a multi-level nested object, specify a `nested` object inside the outer `nested` object. The following request sorts the products by their highest discount in any offer: + +```json +GET sort-offers/_search +{ + "_source": ["product"], + "sort": [ + { + "offers.discounts.percent": { + "order": "desc", + "mode": "max", + "nested": { + "path": "offers", + "nested": { + "path": "offers.discounts" + } + } + } + } + ] +} +``` +{% include copy-curl.html %} + +The `stove` is returned first, with a sort value of `20`, followed by the `tent`, with a sort value of `15`. ## Handling missing values @@ -496,12 +850,16 @@ PUT students/_doc/1 "name": "John Doe", "average": 80 } +``` +{% include copy-curl.html %} +```json PUT students/_doc/2 { "name": "Mary Major" } ``` +{% include copy-curl.html %} Sort the documents, ordering the document with a missing field first: @@ -521,6 +879,7 @@ GET students/_search ] } ``` +{% include copy-curl.html %} The response lists document 2 first: @@ -582,6 +941,7 @@ PUT students/_doc/1 "average": 80 } ``` +{% include copy-curl.html %} Index a document that does not contain an `average` field in the second index: @@ -591,6 +951,7 @@ PUT students_no_map/_doc/2 "name": "Mary Major" } ``` +{% include copy-curl.html %} Search for all documents in both indexes and sort them by the `average` field: @@ -609,6 +970,7 @@ GET students*/_search ] } ``` +{% include copy-curl.html %} By default, the second index produces an error because the `average` field is not mapped: @@ -677,6 +1039,7 @@ GET students*/_search ] } ``` +{% include copy-curl.html %} The response contains both documents: @@ -725,6 +1088,103 @@ The response contains both documents: } ``` +## Sorting using a script + +To sort by a value that is not stored in a single field, calculate the value using a script. In the `sort` array, specify a `_script` object. The `_script` object accepts the following parameters. + +Parameter | Description +:--- | :--- +`type` | The type of the value returned by the script. Valid values are `number` and `string`. Required. +`script` | The script that calculates the sort value. For more information, see [How to use scripts]({{site.url}}{{site.baseurl}}/scripting/using-scripts/). +`order` | The sort order. Valid values are `asc` and `desc`. Default is `asc`. +`mode` | The value to use for sorting if the script returns multiple values. For more information, see [Sort mode](#sort-mode). +`nested` | The nested object in which to run the script when the script reads fields of [nested]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/nested/) objects. Specify the path to the nested object in `nested.path`. For more information, see [Sorting nested objects](#sorting-nested-objects). + +The following request sorts products by price converted to another currency using an exchange rate passed in `params`: + +```json +GET /prices-eu,prices-us/_search +{ + "_source": ["product", "price"], + "sort": { + "_script": { + "type": "number", + "script": { + "source": "doc['price'].value * params.exchange_rate", + "params": { + "exchange_rate": 0.92 + } + }, + "order": "desc" + } + } +} +``` +{% include copy-curl.html %} + +The `sort` array of each hit contains the value calculated by the script: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + "_index": "prices-eu", + "_id": "1", + "_score": null, + "_source": { + "product": "tent", + "price": 129.5 + }, + "sort": [ + 119.14 + ] + }, + { + "_index": "prices-us", + "_id": "2", + "_score": null, + "_source": { + "product": "backpack", + "price": 95 + }, + "sort": [ + 87.4 + ] + }, + { + "_index": "prices-us", + "_id": "1", + "_score": null, + "_source": { + "product": "stove", + "price": 60 + }, + "sort": [ + 55.2 + ] + }, + { + "_index": "prices-eu", + "_id": "2", + "_score": null, + "_source": { + "product": "lantern", + "price": 24.99 + }, + "sort": [ + 22.9908 + ] + } + ] + } +} +``` + +Script-based sorting runs the script for every matching document, so it is slower than sorting by a field. If you sort by the same calculated value often, consider calculating it at index time and storing it in a field. + ## Tracking scores By default, scores are not computed when sorting on a field. You can set `track_scores` to `true` to compute and track scores: @@ -745,34 +1205,57 @@ GET students/_search "track_scores": true } ``` +{% include copy-curl.html %} -## Sorting by geo distance +## Sorting by geodistance You can sort documents by `_geo_distance`. The following parameters are supported. Parameter | Description :--- | :--- -distance_type | Specifies the method of computing the distance. Valid values are `arc` and `plane`. The `plane` method is faster but less accurate for long distances or close to the poles. Default is `arc`. -mode | Specifies how to handle a field with several geopoints. By default, documents are sorted by the shortest distance when the sort order is ascending and by the longest distance when the sort order is descending. Valid values are `min`, `max`, `median`, and `avg`. -unit | Specifies the units used to compute sort values. Default is meters (`m`). -ignore_unmapped | Specifies how to treat an unmapped field. Set `ignore_unmapped` to `true` to ignore unmapped fields. Default is `false` (produce an error when encountering an unmapped field). +`distance_type` | Specifies the method of computing the distance. Valid values are `arc` and `plane`. The `plane` method is faster but less accurate for long distances or close to the poles. Default is `arc`. +`mode` | Specifies how to handle a field with several geopoints. By default, documents are sorted by the shortest distance when the sort order is ascending and by the longest distance when the sort order is descending. Valid values are `min`, `max`, `median`, and `avg`. +`unit` | Specifies the units used to compute sort values. Default is meters (`m`). +`ignore_unmapped` | Specifies how to treat an unmapped field. Set `ignore_unmapped` to `true` to ignore unmapped fields, which has the same effect as setting `unmapped_type` in a field sort. Default is `false` (produce an error when encountering an unmapped field). For more information, see [Ignoring unmapped fields](#ignoring-unmapped-fields). + +You can specify the reference point in any [geopoint format]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/geo-point/#formats), for example, as an object containing `lat` and `lon`, a `"lat,lon"` string, a geohash, or a `[lon, lat]` array. The `_geo_distance` parameter does not support `missing_values`. The distance is always considered to be `infinity` when a document does not contain the field used for computing distance. {: .note} -For example, index two documents with geopoints: +For example, create an index and map the `point` field as a `geo_point`: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` +{% include copy-curl.html %} + +Index two documents containing geopoints: ```json PUT testindex1/_doc/1 { "point": [74.00, 40.71] } +``` +{% include copy-curl.html %} +```json PUT testindex1/_doc/2 { "point": [73.77, -69.63] } ``` +{% include copy-curl.html %} Search for all documents and sort them by the distance from the provided point: @@ -796,6 +1279,7 @@ GET testindex1/_search } } ``` +{% include copy-curl.html %} The response contains the sorted documents: @@ -849,7 +1333,7 @@ The response contains the sorted documents: } ``` -You can provide coordinates in any format supported by the geopoint field type. For a description of all formats, see the [geopoint field type documentation]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point). +You can provide coordinates in any format supported by the geopoint field type. For a description of all formats, see the [geopoint field type documentation]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/geo-point/). {: .note} To pass multiple geopoints to `_geo_distance`, use an array: @@ -874,9 +1358,13 @@ GET testindex1/_search } } ``` +{% include copy-curl.html %} For each document, the sorting distance is calculated as the minimum, maximum, or average (as specified by the `mode`) of the distances from all points provided in the search to all points in the document. ## Performance considerations -Sorted field values are loaded into memory for sorting. Therefore, for minimum overhead we recommend mapping [numeric types]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/numeric) to the smallest acceptable types, like `short`, `integer`, and `float`. [String types]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/string) should not have the sorted field analyzed or tokenized. \ No newline at end of file +Sorted field values are loaded into memory for sorting. Therefore, for minimum overhead we recommend mapping [numeric types]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/numeric/) to the smallest acceptable types, like `short`, `integer`, and `float`. [String types]({{site.url}}{{site.baseurl}}/opensearch/supported-field-types/string/) should not have the sorted field analyzed or tokenized. + +The `_id` field is restricted from use in sorting operations. If you need to sort by document ID, consider duplicating the ID value into another field with `doc_values` enabled. For more information about `_id` field limitations, see [ID field type]({{site.url}}{{site.baseurl}}/field-types/metadata-fields/id/). +{: .note} \ No newline at end of file diff --git a/_search-plugins/star-tree-index.md b/_search-plugins/star-tree-index.md new file mode 100644 index 00000000..c611f17d --- /dev/null +++ b/_search-plugins/star-tree-index.md @@ -0,0 +1,518 @@ +--- +layout: default +title: Star-tree index +parent: Improving search performance +nav_order: 50 +--- + +# Star-tree index + +A _star-tree index_ is a specialized index structure designed to improve aggregation performance by precomputing and storing aggregated values at different levels of granularity. This indexing technique enables faster aggregation execution, especially for multi-field aggregations. + +Once you enable star-tree indexes, OpenSearch automatically builds and uses star-tree indexes to optimize supported aggregations if the filter fields match the defined dimensions and the aggregation fields match the defined metrics in the star-tree mapping configuration. No changes to your query syntax or request parameters are required. + +Use a star-tree index when you want to speed up aggregations: + +- Star-tree indexes natively support multi-field aggregations. +- Star-tree indexes are created in real time as part of the indexing process, so the data in a star-tree is always current. +- A star-tree index aggregates data to improve paging efficiency and reduce disk I/O during search queries. + +## Star-tree index structure + +A star-tree index organizes and aggregates data across combinations of dimension fields and precomputes metric values for all the dimension combinations every time a segment is flushed or refreshed during ingestion. This structure enables OpenSearch to process aggregation queries quickly without scanning every document. + +The following is an example star-tree configuration: + +```json +"ordered_dimensions": [ + { + "name": "status" + }, + { + "name": "port" + } +], +"metrics": [ + { + "name": "size", + "stats": [ + "sum" + ] + }, + { + "name": "latency", + "stats": [ + "avg" + ] + } +] +``` + +This configuration defines the following: + +* Two dimension fields: `status` and `port`. The `ordered_dimension` field specifies how data is sorted (first by `status`, then by `port`). +* Two metric fields: `size` and `latency` with their corresponding aggregations (`sum` and `avg`). For each unique dimension combination, metric values (`Sum(size)` and `Avg(latency)`) are pre-aggregated and stored in the star-tree structure. + +OpenSearch creates a star-tree index structure based on this configuration. Each node in the tree corresponds to a value (or wildcard `*`) for a dimension. At query time, OpenSearch traverses the tree based on the dimension values provided in the query. + +### Leaf nodes + +Leaf nodes contain the precomputed metric aggregations for specific combinations of dimensions. These are stored as doc values and referenced by star-tree nodes. + +The `max_leaf_docs` setting controls how many documents each leaf node can reference, which helps keep query latency predictable by limiting how many documents are scanned for any given node. + +### Star nodes + +A _star node_ (marked as `*` in the following diagram) aggregates all values for a particular dimension. If a query doesn't specify a filter for that dimension, OpenSearch retrieves the precomputed aggregation from the star node instead of iterating over multiple leaf nodes. For example, if a query filters on `port` but not `status`, OpenSearch can use a star node that aggregates data for all status values. + +### How queries use the star-tree + +The following diagram shows a star-tree index created for this example and three example query paths. In the diagram, notice that each branch corresponds to a dimension (`status` and `port`). Some nodes contain precomputed aggregation values (for example, `Sum(size)`), allowing OpenSearch to skip unnecessary calculations at query time. + +![A star-tree index containing two dimensions and two metrics]({{site.url}}{{site.baseurl}}/images/star-tree-index.png) + +The colored arrows show three query examples: + +* **Blue arrow**: Multi-term query with metric aggregation + The query filters on both `status = 200` and `port = 5600` and calculates the sum of request sizes. + + * OpenSearch follows this path: `Root → 200 → 5600` + * It retrieves the metric from Doc ID 1, where `Sum(size) = 988` + +* **Green arrow**: Single-term query with metric aggregation + The query filters on `status = 200` only and computes the average request latency. + + * OpenSearch follows this path: `Root → 200 → *` + * It retrieves the metric from Doc ID 5, where `Avg(latency) = 70` + +* **Red arrow**: Single-term query with metric aggregation + The query filters on `port = 8443` only and calculates the sum of request sizes. + + * OpenSearch follows this path: `Root → * → 8443` + * It retrieves the metric from Doc ID 7, where `Sum(size) = 1111` + +These examples show how OpenSearch selects the shortest path in the star-tree and uses pre-aggregated values to process queries efficiently. + +## Limitations + +Note the following limitations of star-tree indexes: + +- Star-tree indexes do not support updates or deletions. To use a star-tree index, data should be append-only. See [Enabling a star-tree index](#enabling-a-star-tree-index). +- A star-tree index only works for aggregation queries that filter on dimension fields and aggregate metric fields defined in the index's star-tree configuration. +- Any changes to a star-tree configuration require reindexing. +- [Array values]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/index/#arrays) are not supported. +- Only [specific queries and aggregations](#supported-queries-and-aggregations) are supported. +- Avoid using high-cardinality fields like `_id` as dimensions because they can significantly increase storage use and query latency. + +## Enabling a star-tree index + +Star-tree indexing behavior is controlled by the following cluster-level and index-level settings. Index-level settings take precedence over cluster settings. + +| Setting | Scope | Default | Purpose | +| ------------------------------------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `indices.composite_index.star_tree.enabled` | Cluster | `true` | Enables or disables star-tree search optimization across the cluster. | +| `index.composite_index` | Index | None | Enables star-tree indexing for a specific index. Must be set when creating the index. | +| `index.append_only.enabled` | Index | None | Required for star-tree indexes. Prevents updates and deletions. Must be `true`. | +| `index.search.star_tree_index.enabled` | Index | `true` | Enables or disables use of the star-tree index for search queries on the index. | + +Setting `indices.composite_index.star_tree.enabled` to `false` prevents OpenSearch from using star-tree optimization during searches, but the star-tree index structures are still created. To completely remove star-tree structures, you must reindex your data without the star-tree mapping. +{: .note} + +## Advanced star-tree index settings + +The following index-level settings provide fine-grained control over star-tree index behavior. These settings are static, meaning they must be configured when creating the index and cannot be changed afterward. + +| Setting | Default | Range | Purpose | +| ---------------------------------------------------------- | ------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `index.composite_index.star_tree.default.max_leaf_docs` | `10000` | Min: `1` | Sets the maximum number of documents allowed in a leaf node. Lower values improve query latency but increase storage requirements. | +| `index.composite_index.star_tree.field.default.metrics` | `["value_count", "sum"]` | N/A | Defines the default metrics computed for star-tree aggregations. These metrics are pre-calculated to speed up aggregation queries. | +| `index.composite_index.star_tree.field.max_base_metrics` | `100` | `4` to `100` | Controls the maximum number of base metrics that can be configured for star-tree fields. More metrics provide more aggregation options but increase index size. | +| `index.composite_index.star_tree.field.max_dimensions` | `10` | `2` to `10` | Sets the maximum number of dimensions that can be part of a star-tree index field. Affects star-tree index size and query performance. | +| `index.composite_index.star_tree.field.max_date_intervals` | `3` | `1` to `3` | Specifies the maximum number of date intervals that can be configured for star-tree date fields. Controls temporal granularity options. | +| `index.composite_index.star_tree.max_fields` | `1` | `1` to `1` | Controls the maximum number star-tree fields per index. Only one star-tree field per index is supported. | + + +To create an index that uses a star-tree index, send the following request: + +```json +PUT /logs +{ + "settings": { + "index.composite_index": true, + "index.append_only.enabled": true + } +} +``` +{% include copy-curl.html %} + +Ensure that the `doc_values` parameter is enabled for the dimension and metric fields used in your star-tree mapping. This is enabled by default for most field types. For more information, see [Doc values]({{site.url}}{{site.baseurl}}/mappings/mapping-parameters/doc-values/). + +### Disabling star-tree usage + +By default, both the `indices.composite_index.star_tree.enabled` cluster setting and the `index.search.star_tree_index.enabled` index setting are set to `true`. To disable search using star-tree indexes, set both of these settings to `false`. Note that index settings take precedence over cluster settings. + +## Example mapping + +The following example shows how to create a star-tree index that precomputes aggregations in the `logs` index. The `sum` and `average` aggregations are calculated on the `size` and `latency` fields , respectively, for all combinations of values in the dimension fields. The dimensions are ordered by `status`, then `port`, and finally `method`, which determines how the data is organized in the tree structure: + +```json +PUT /logs +{ + "settings": { + "index.number_of_shards": 1, + "index.number_of_replicas": 0, + "index.composite_index": true, + "index.append_only.enabled": true + }, + "mappings": { + "composite": { + "request_aggs": { + "type": "star_tree", + "config": { + "date_dimension" : { + "name": "@timestamp", + "calendar_intervals": [ + "month", + "day" + ] + }, + "ordered_dimensions": [ + { + "name": "status" + }, + { + "name": "port" + }, + { + "name": "method" + } + ], + "metrics": [ + { + "name": "size", + "stats": [ + "sum" + ] + }, + { + "name": "latency", + "stats": [ + "avg" + ] + } + ] + } + } + }, + "properties": { + "status": { + "type": "integer" + }, + "port": { + "type": "integer" + }, + "size": { + "type": "integer" + }, + "method" : { + "type": "keyword" + }, + "latency": { + "type": "scaled_float", + "scaling_factor": 10 + } + } + } +} +``` +{% include copy.html %} + +For more information about star-tree index mappings and parameters, see [Star-tree field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/star-tree/). + +## Supported queries and aggregations + +Star-tree indexes optimize aggregations. Every query must include at least one supported aggregation in order to use the star-tree optimization. + +### Supported queries + +Queries without aggregations cannot use star-tree optimization. The query's fields must be present in the `ordered_dimensions` section of the star-tree configuration. The following queries are supported: + +- [Term query]({{site.url}}{{site.baseurl}}/query-dsl/term/term/) +- [Terms query]({{site.url}}{{site.baseurl}}/query-dsl/term/terms/) +- [Match all docs query]({{site.url}}{{site.baseurl}}/query-dsl/match-all/) +- [Range query]({{site.url}}{{site.baseurl}}/query-dsl/term/range/) +- [Boolean query]({{site.url}}{{site.baseurl}}/query-dsl/compound/bool/) + +#### Boolean query restrictions + +Boolean queries in star-tree indexes follow specific rules for each clause type: + +* `must` and `filter` clauses: + - Are both supported and treated the same way because `filter` does not affect scoring. + - Can operate across different dimensions. + - Allow only one condition per dimension across all `must`/`filter` clauses, including nested ones. + - Support term, terms, and range queries. + +* `should` clauses: + - Must operate on the same dimension and cannot operate across different dimensions + - Can only use term, terms, and range queries. + +* `should` clauses inside `must` clauses: + - Act as a required condition. + - When operating on the same dimension as outer `must`: The union of `should` conditions is intersected with the outer `must` conditions. + - When operating on a different dimension: Processed normally as a required condition. + +* `must_not` clauses are not supported. +* Queries with the `minimum_should_match` parameter are not supported. + +The following Boolean query is **supported** because it follows these restrictions: + +```json +{ + "bool": { + "must": [ + {"term": {"method": "GET"}} + ], + "filter": [ + {"range": {"status": {"gte": 200, "lt": 300}}} + ], + "should": [ + {"term": {"port": 443}}, + {"term": {"port": 8443}} + ] + } +} +``` +{% include copy.html %} + +The following Boolean queries are **not** supported because they violate these restrictions: + +```json +{ + "bool": { + "should": [ + {"term": {"status": 200}}, + {"term": {"method": "GET"}} // SHOULD across different dimensions + ] + } +} +``` + +```json +{ + "bool": { + "must": [ + {"term": {"status": 200}} + ], + "must_not": [ // MUST_NOT not supported + {"term": {"method": "DELETE"}} + ] + } +} +``` + +### Supported aggregations + +The following aggregations are supported by star-tree indexes. + +#### Metric aggregations + +The following metric aggregations are supported: + +- [Sum]({{site.url}}{{site.baseurl}}/aggregations/metric/sum/) +- [Minimum]({{site.url}}{{site.baseurl}}/aggregations/metric/minimum/) +- [Maximum]({{site.url}}{{site.baseurl}}/aggregations/metric/maximum/) +- [Value count]({{site.url}}{{site.baseurl}}/aggregations/metric/value-count/) +- [Average]({{site.url}}{{site.baseurl}}/aggregations/metric/average/) + +To use searchable aggregations with a star-tree index, make sure you fulfill the following prerequisites: + +- The fields must be present in the `metrics` section of the star-tree configuration. +- The metric aggregation type must be part of the `stats` parameter. + +The following example gets the sum of all the values in the `size` field for all error logs with `status=500`, using the [example mapping](#example-mapping): + +```json +POST /logs/_search +{ + "query": { + "term": { + "status": "500" + } + }, + "aggs": { + "sum_size": { + "sum": { + "field": "size" + } + } + } +} +``` +{% include copy.html %} + +Using a star-tree index, the result will be retrieved from a single aggregated document as it traverses the `status=500` node, as opposed to scanning through all of the matching documents. This results in lower query latency. + +#### Date histograms with metric aggregations + +You can use [date histograms]({{site.url}}{{site.baseurl}}/aggregations/bucket/date-histogram/) on calendar intervals with metric sub-aggregations. + +To use date histogram aggregations and make them searchable in a star-tree index, remember the following requirements: + +- The calendar intervals in a star-tree mapping configuration can use either the request's calendar field or a field of lower granularity than the request field. For example, if an aggregation uses the `month` field, the star-tree search can still use lower-granularity fields such as `day`. +- A metric subaggregation must be part of the aggregation request. + +The following example filters logs to include only those with status codes between `200` and `400` and sets the `size` of the response to `0`, so that only aggregated results are returned. It then aggregates the filtered logs by calendar month and calculates the total `size` of the requests for each month: + +```json +POST /logs/_search +{ + "size": 0, + "query": { + "range": { + "status": { + "gte": "200", + "lte": "400" + } + } + }, + "aggs": { + "by_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "sum_size": { + "sum": { + "field": "size" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Keyword and numeric terms aggregations + +You can use [terms aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/terms/) on both keyword and numeric fields with star-tree index search. + +For star-tree search compatibility with terms aggregations, remember the following behaviors: + +- The fields used in the terms aggregation should be part of the dimensions defined in the star-tree index. +- Metric sub-aggregations are optional as long as the relevant metrics are part of the star-tree configuration. + +The following example aggregates logs by the `user_id` field and returns the counts for each unique user: + +```json +POST /logs/_search +{ + "size": 0, + "aggs": { + "users": { + "terms": { + "field": "user_id" + } + } + } +} +``` +{% include copy-curl.html %} + +The following example aggregates orders by the `order_quantity` and calculates the average `total_price` for each quantity: + +```json +POST /orders/_search +{ + "size": 0, + "aggs": { + "quantities": { + "terms": { + "field": "order_quantity" + }, + "aggs": { + "avg_total_price": { + "avg": { + "field": "total_price" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Range aggregations + +You can use [range aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/range/) on numeric fields with star-tree index search. + +For range aggregations to work effectively with a star-tree index, remember the following behaviors: + +- The field used in the range aggregation should be part of the dimensions defined in the star-tree index. +- You can include metric sub-aggregations to compute metrics within each defined range, as long as the relevant metrics are part of the star-tree configuration. + +The following example aggregates documents based on predefined ranges of the `temperature` field: + +```json +POST /sensors/_search +{ + "size": 0, + "aggs": { + "temperature_ranges": { + "range": { + "field": "temperature", + "ranges": [ + { "to": 20 }, + { "from": 20, "to": 30 }, + { "from": 30 } + ] + } + } + } +} +``` +{% include copy-curl.html %} + +The following example aggregates sales data by price ranges and calculates the total `quantity` sold within each range: + +```json +POST /sales/_search +{ + "size": 0, + "aggs": { + "price_ranges": { + "range": { + "field": "price", + "ranges": [ + { "to": 100 }, + { "from": 100, "to": 500 }, + { "from": 500 } + ] + }, + "aggs": { + "total_quantity": { + "sum": { + "field": "quantity" + } + } + } + } + } +} +``` +{% include copy-curl.html %} + +#### Nested aggregations + +You can combine multiple supported bucket aggregations (such as `terms` and `range`) in a nested structure, and the star-tree index will optimize these nested aggregations. For more information about nested aggregations, see [Nested aggregations]({{site.url}}{{site.baseurl}}/aggregations/#nested-aggregations). + +#### Multi-terms aggregations + +A star-tree index optimizes `multi_terms` aggregations when the aggregation fields are defined as dimensions in the star-tree configuration. For more information about multi-terms aggregations, see [Multi-terms aggregations]({{site.url}}{{site.baseurl}}/aggregations/bucket/multi-terms/). + +## Next steps + +- [Star-tree field type]({{site.url}}{{site.baseurl}}/mappings/supported-field-types/star-tree/) diff --git a/_search-plugins/ubi/dsl-queries.md b/_search-plugins/ubi/dsl-queries.md new file mode 100644 index 00000000..34391824 --- /dev/null +++ b/_search-plugins/ubi/dsl-queries.md @@ -0,0 +1,99 @@ +--- +layout: default +title: Example UBI query DSL queries +parent: User Behavior Insights +grand_parent: Optimizing search quality +has_children: false +nav_order: 15 +--- + +# Example UBI query DSL queries + +You can use the OpenSearch search query language, [query DSL]({{site.url}}{{site.baseurl}}/opensearch/query-dsl/), to write User Behavior Insights (UBI) queries. The following example returns the number of times that each `action_name` event occurs. +For more extensive analytic queries, see [Example UBI SQL queries]({{site.url}}{{site.baseurl}}/search-plugins/ubi/sql-queries/). +#### Example request +```json +GET ubi_events/_search +{ + "size":0, + "aggs":{ + "event_types":{ + "terms": { + "field":"action_name", + "size":10 + } + } + } +} +``` +{% include copy.html %} + +#### Example response + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "event_types": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "brand_filter", + "doc_count": 3084 + }, + { + "key": "product_hover", + "doc_count": 3068 + }, + { + "key": "button_click", + "doc_count": 3054 + }, + { + "key": "product_sort", + "doc_count": 3012 + }, + { + "key": "on_search", + "doc_count": 3010 + }, + { + "key": "type_filter", + "doc_count": 2925 + }, + { + "key": "login", + "doc_count": 2433 + }, + { + "key": "logout", + "doc_count": 1447 + }, + { + "key": "new_user_entry", + "doc_count": 207 + } + ] + } + } +} +``` +{% include copy.html %} + +You can run the preceding queries in the OpenSearch Dashboards [Dev Tools]({{site.url}}{{site.baseurl}}/dashboards/dev-tools/index/) console. diff --git a/_search-plugins/ubi/index.md b/_search-plugins/ubi/index.md new file mode 100644 index 00000000..9ee4dbd8 --- /dev/null +++ b/_search-plugins/ubi/index.md @@ -0,0 +1,89 @@ +--- +layout: default +title: User Behavior Insights +parent: Optimizing search quality +has_children: true +nav_order: 10 +description: "User Behavior Insights (UBI) is a schema for capturing user search behavior, including the queries users submit, the results shown, and the actions they take." +redirect_from: + - /search-plugins/ubi/ +--- +# User Behavior Insights + +**Introduced 2.15** +{: .label .label-purple } + +**References UBI Specification 1.3.0** +{: .label .label-purple } + +User Behavior Insights (UBI) is a schema for capturing user search behavior. Search behavior consists of the queries that the user submits, the results that are presented to them, and the actions they take on those results. The UBI schema links all user interactions (events) to the search result they were performed on. That is, it not only captures the chronological sequence of events but also captures the causal links between events. Analysis of this behavior is used for improving the quality of search results. + +Client applications such as web pages or apps capture user behavior and send UBI data to a UBI endpoint. For web pages, this is typically handled by JavaScript code. + +In principle, queries sent to the server and results returned by the server can be sent to the UBI endpoint from the client. But as an optimization, they can instead be sent directly to the UBI endpoint from the server, without incurring a round-trip to the client. That is the function of the UBI plugin and is not a requirement to adopt UBI. + + +> "how our users are using our product, whether search results were useful for them and whether they clicked on top-n results we gave and all related stuff" -- Data scientist working on search. + +UBI includes the following elements: +* A machine-readable [schema](https://github.com/o19s/ubi) that facilitates interoperability of the UBI specification. +* [ubi.js](https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js): An (optional) client-side JavaScript library for capturing searches and events. +* An (optional) OpenSearch [plugin](https://github.com/opensearch-project/user-behavior-insights) that streamlines the recording of query data. + +Advanced features in OpenSearch, such as the [Search Relevance Workbench]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/using-search-relevance-workbench/) and the [Hybrid Search Optimizer]({{site.url}}{{site.baseurl}}/search-plugins/search-relevance/optimize-hybrid-search/), build on the data collected according to the UBI specification. + +<!-- vale off --> + +<table> + <tr style="vertical-align: top;"> + <td> + <h2>Tutorials</h2> + <ul> + <li><a href="{{site.url}}{{site.baseurl}}/search-plugins/ubi/ubi-aws-managed-services-tutorial/">Learn to use Amazon OpenSearch Ingestion</a> pipelines for gathering UBI-formatted data in Amazon OpenSearch Service.</li> + <li><a href="{{site.url}}{{site.baseurl}}/search-plugins/ubi/ubi-dashboard-tutorial/">Learn to create custom dashboards</a> for visualizing UBI data.</li> + <li> Based on <a href="https://github.com/o19s/chorus-opensearch-edition">Chorus for OpenSearch</a> demo: + <ul> + <li><a href="https://github.com/o19s/chorus-opensearch-edition/blob/main/katas/002_derive_interaction_data.md">Derive Interaction Data from User Clicks.</a></li> + <li><a href="https://github.com/o19s/chorus-opensearch-edition/blob/main/katas/006_protecting_sensitive_information.md">Protecting sensistive information when using UBI.</a></li> + <li><a href="https://github.com/o19s/chorus-opensearch-edition/blob/main/katas/007_configure_AB_with_TDI.md">Configuring an A/B test with Team Draft Interleaving</a></li> + </ul> + </li> + </ul> + </td> + <td> + <h2>How To Guides</h2> + <ul> + <li>How to <a href="https://github.com/opensearch-project/user-behavior-insights?tab=readme-ov-file#user-quick-start">install and use the UBI plugin</a> in OpenSearch.</li> + <li>How to use <a href="{{site.url}}{{site.baseurl}}/search-plugins/ubi/ubi-javascript-collector/">ubi.js</a>, a client-side JavaScript library for capturing events.</li> + <li>How to <a href="{{site.url}}{{site.baseurl}}/search-plugins/ubi/dsl-queries/">write queries for UBI data using OpenSearch query DSL.</a></li> + <li>How to <a href="{{site.url}}{{site.baseurl}}/search-plugins/ubi/sql-queries/">write analytic queries for UBI data using SQL.</a></li> + </ul> + </td> + </tr> + <tr style="vertical-align: top;"> + <td> + <h2>Explanation</h2> + <ul> + <li><a href="https://docs.google.com/presentation/d/e/2PACX-1vTJ9wYhhRG2sHxB-pm2Pfcqv0AzwRzSgTn-VyKTV6bL4PyXQC9C9kE6Oyrkag2_Olb6Ugevs_kbflId/pub?start=true&loop=false&delayms=3000">Why UBI?</a> presentation.</li> + <li>Learn more about this standard via <a href="https://www.UBISearch.dev">https://www.UBISearch.dev</a>, the community clearinghouse.</li> + <li>Watch <a href="https://youtu.be/0chun264PRQ">Leveraging UBI to enhance Search Relevance</a> talk to understand how to use this data to improve search quality.</li> + <li>Go deeper with UBI. Watch <a href="https://www.youtube.com/watch?v=xi261oUamXc">You’ve Deployed User Behavior Insights. Now What?</a> to see what else you can do.</li> + </ul> + </td> + <td> + <h2>Reference</h2> + <ul> + <li><a href="https://github.com/opensearch-project/user-behavior-insights">UBI Plugin for OpenSearch</a></li> + <li><a href="{{site.url}}{{site.baseurl}}/search-plugins/ubi/schemas/">UBI Schema in OpenSearch</a></li> + <li>Repository for the <a href="https://github.com/o19s/ubi">UBI Schema</a>.</li> + <li><a href="https://o19s.github.io/ubi/docs/html/1.3.0/query.request.schema.html">Query Tracking Specification</a></li> + <li><a href="https://o19s.github.io/ubi/docs/html/1.3.0/event.schema.html">Event Tracking Specification</a></li> + + </ul> + </td> + </tr> +</table> + +<!-- vale on --> +The documentation categories were adapted using concepts based on [Diátaxis](https://diataxis.fr/). +{: .tip } diff --git a/_search-plugins/ubi/schemas.md b/_search-plugins/ubi/schemas.md new file mode 100644 index 00000000..f149c869 --- /dev/null +++ b/_search-plugins/ubi/schemas.md @@ -0,0 +1,220 @@ +--- +layout: default +title: UBI index schemas +parent: User Behavior Insights +grand_parent: Optimizing search quality +has_children: false +nav_order: 5 +redirect_from: + - /search-plugins/ubi/data-structures/ +--- + +# UBI index schemas + +The User Behavior Insights (UBI) data collection process involves tracking and recording the queries submitted by users as well as monitoring and logging their subsequent actions or events after receiving the search results. There are two UBI index schemas involved in the data collection process: +* The [query index](#ubi-queries-index), which stores the searches and results. +* The [event index](#ubi-events-index), which stores all subsequent user actions after the user's query. + +## Key identifiers + +For UBI to function properly, the connections between the following fields must be consistently maintained within an application that has UBI enabled: + +- [`object_id`](#object_id) represents an ID for whatever object the user receives in response to a query. For example, if you search for books, it might be an ISBN for a book, such as `978-3-16-148410-0`. +- [`query_id`](#query_id) is a unique ID for the raw query executed, while the `object_id` maps to the primary identifier of the _hits_ returned by the user's query. +- [`client_id`](#client_id) represents a unique query source. This is typically a web browser used by a unique user. +- [`object_id_field`](#object_id_field) specifies the name of the field in your index that provides the `object_id`. For example, if you search for books, the value might be `isbn_code`. +- [`action_name`](#action_name), though not technically an ID, specifies the exact user action (such as `click`, `add_to_cart`, `watch`, `view`, or `purchase`) that was taken (or not taken) for an object with a given `object_id`. + +To summarize, the `query_id` signals the beginning of a unique search for a client tracked through a `client_id`. The search returns various objects, each with a unique `object_id`. The `action_name` specifies what action the user is performing and is connected to the objects, each with a specific `object_id`. You can differentiate between types of objects by inspecting the `object_id_field`. + +Typically, you can infer the user's overall search history by retrieving all the data for the user's `client_id` and inspecting the individual `query_id` data. Each application determines what constitutes a search session by examining the backend data + +## Important UBI roles + +The following diagram illustrates the process by which the **user** interacts with the **Search client** and **UBI client** +and how those, in turn, interact with the **OpenSearch cluster**, which houses the **UBI events** and **UBI queries** indexes. + +Blue arrows illustrate standard search, bold, dashed lines illustrate UBI-specific additions, and +red arrows illustrate the flow of the `query_id` to and from OpenSearch. + +![]({{site.url}}{{site.baseurl}}/images/ubi/ubi-schema-interactions_legend.png) +![]({{site.url}}{{site.baseurl}}/images/ubi/ubi-schema-interactions.png) + +{% comment %} +The mermaid source below is converted into a PNG under +.../images/ubi/ubi-schema-interactions.png + + +```mermaid +graph LR +style L fill:none,stroke-dasharray: 5 5 +subgraph L["`*Legend*`"] + style ss height:150px + subgraph ss["Standard Search"] + direction LR + + style ln1a fill:blue + ln1a[ ]--->ln1b[ ]; + end + subgraph ubi-leg["UBI data flow"] + direction LR + + ln2a[ ].->|"`**UBI interaction**`"|ln2b[ ]; + style ln1c fill:red + ln1c[ ]-->|<span style="font-family:Courier New">query_id</span> flow|ln1d[ ]; + end +end +linkStyle 0 stroke-width:2px,stroke:#0A1CCF +linkStyle 2 stroke-width:2px,stroke:red +``` +```mermaid +%%{init: { + "flowchart": {"htmlLabels": false}, + + } +}%% +graph TB + +User--1) <i>raw search string</i>-->Search; +Search--2) <i>search string</i>-->Docs +style OS stroke-width:2px, stroke:#0A1CCF, fill:#62affb, opacity:.5 +subgraph OS[OpenSearch Cluster fa:fa-database] + style E stroke-width:1px,stroke:red + E[( <b>UBI Events</b> )] + style Docs stroke-width:1px,stroke:#0A1CCF + style Q stroke-width:1px,stroke:red + Docs[(Document Index)] -."3) {<i>DSL</i>...} & [<i>object_id's</i>,...]".-> Q[( <b>UBI Queries</b> )]; + Q -.4) <span style="font-family:Courier New">query_id</span>.-> Docs ; +end + +Docs -- "5) <i>return</i> both <span style="font-family:Courier New">query_id</span> & [<i>objects</i>,...]" --->Search ; +Search-.6) <span style="font-family:Courier New">query_id</span>.->U; +Search --7) [<i>results</i>, ...]--> User + +style *client-side* stroke-width:1px, stroke:#D35400 +subgraph "`*client-side*`" + style User stroke-width:4px, stroke:#EC636 + User["`**User**`" fa:fa-user] + App + Search + U + style App fill:#D35400,opacity:.35, stroke:#0A1CCF, stroke-width:2px + subgraph App[       UserApp fa:fa-store] + style Search stroke-width:2px, stroke:#0A1CCF + Search( Search Client ) + style U stroke-width:1px,stroke:red + U( <b>UBI Client</b> ) + end +end + +User -.8) <i>selects</i> <span style="font-family:Courier New">object_id:123</span>.->U; +U-."9) <i>index</i> event:{<span style="font-family:Courier New">query_id, onClick, object_id:123</span>}".->E; + +linkStyle 1,2,0,6 stroke-width:2px,fill:none,stroke:#0A1CCF +linkStyle 3,4,5,8 stroke-width:2px,fill:none,stroke:red +``` +{% endcomment %} +Here are some key points regarding the roles: +- The **Search client** is in charge of searching and then receiving *objects* from an OpenSearch document index (1, 2, **5**, and 7 in the preceding diagram). + +Step **5** is in bold because it denotes UBI-specific additions, like `query_id`, to standard OpenSearch interactions. + {: .note} +- If activated in the `ext.ubi` stanza of the search request, the **User Behavior Insights** plugin manages the **UBI queries** store in the background, indexing each query, ensuring a unique `query_id` for all returned `object_id` values, and then passing the `query_id` back to the **Search client** so that events can be linked to the query (3, 4, and **5** in preceding diagram). +- **Objects** represent the items that the user searches for using the queries. Activating UBI involves mapping your real-world objects (using their identifiers, such as an `isbn` or `sku`) to the `object_id` fields in the index that is searched. +- The **Search client**, if separate from the **UBI client**, forwards the indexed `query_id` to the **UBI client**. + Even though the *search* and *UBI event indexing* roles are separate in this diagram, many implementations can use the same OpenSearch client instance for both roles (6 in the preceding diagram). +- The **UBI client** then indexes all user events with the specified `query_id` until a new search is performed. At this time, a new `query_id` is generated by the **User Behavior Insights** plugin and passed back to the **UBI client**. +- If the **UBI client** interacts with a result **object**, such as during an **add to cart** event, then the `object_id`, `add_to_cart` `action_name`, and `query_id` are all indexed together, signaling the causal link between the *search* and the *object* (8 and 9 in the preceding diagram). + + + +## UBI stores + +There are two separate stores involved in supporting UBI data collection: +* UBI queries +* UBI events + +### UBI queries index + +All underlying query information and results (`object_ids`) are stored in the `ubi_queries` index and remain largely invisible in the background. + + +The `ubi_queries` index [schema](https://github.com/OpenSearch-project/user-behavior-insights/tree/main/src/main/resources/queries-mapping.json) includes the following fields: + +- `timestamp` (events and queries): An ISO 8601--formatted timestamp indicating when the query was received. + +- `query_id` (events and queries): The unique ID of the query provided by the client or generated by the search engine. Different queries with the same text generate different `query_id` values. + +- `client_id` (events and queries): A client ID provided by the client application. + +- `query_response_hit_ids` (queries): An array of object IDs. An ID can have the same value as the `_id`, but it is meant to be the externally valid ID of a document, item, or product. + +Because UBI manages the `ubi_queries` index, you should never have to write directly to this index (except when importing data). + +### UBI events index + +The client side directly indexes events to the `ubi_events` index, linking the event [`action_name`](#action_name), objects (each with an `object_id`), and queries (each with a `query_id`), along with any other important event information. +Because this schema is dynamic, you can add any new fields or structures (such as user information or geolocation information) that are not in the current **UBI events** [schema](https://github.com/opensearch-project/user-behavior-insights/tree/main/src/main/resources/events-mapping.json) at index time. + +Developers may define new fields under [`event_attributes`](#event_attributes). +{: .note} + +The following are the predefined, minimal fields in the `ubi_events` index: + + <p id="application"> </p> + +- `application` (size 100): The name of the application that tracks UBI events (for example, `amazon-shop` or `ABC-microservice`). + + <p id="action_name"> </p> + +- `action_name` (size 100): The name of the action that triggered the event. The UBI specification defines some common action names, but you can use any name. + + <p id="query_id"> </p> + +- `query_id` (size 100): The unique identifier of a query, which is typically a UUID but can be any string. + The `query_id` is either provided by the client or generated at query time by the UBI plugin. The `query_id` values in both the **UBI queries** and **UBI events** indexes must be consistent. + +<p id="client_id"> </p> + +- `client_id`: The client that issues the query. This is typically a web browser used by a unique user. + The `client_id` in both the **UBI queries** and **UBI events** indexes must be consistent. + +- `timestamp`: The time at which the event occurred in ISO 8601 format, such as `2018-11-13T20:20:39+00:00Z`. + +- `message_type` (size 100): A logical bin for grouping actions (each with an `action_name`). For example, `QUERY` or `CONVERSION`. + +- `message` (size 1,024): An optional text message for the log entry. For example, for a `message_type` `QUERY`, the `message` can contain the text related to a user's search. + + <p id="event_attributes"> </p> + +- `event_attributes`: An extensible structure that describes important context about the event. This structure consists of two primary structures: `position` and `object`. The structure is extensible, so you can add custom information about the event, such as the event's timing, user, or session. + + Because the `ubi_events` index is configured to perform dynamic mapping, the index can become bloated with many new fields. + {: .warning} + + - `event_attributes.position`: A structure that contains information about the location of the event origin, such as screen x, y coordinates, or the object's position in the list of results: + + - `event_attributes.position.ordinal`: Tracks the list position that a user can select (for example, selecting the third element can be described as `event{onClick, results[4]}`). + + - `event_attributes.position.xy.{x,y}`: Tracks x and y values defined by the client. + + - `event_attributes.object`: Contains identifying information about the object returned by the query (for example, a book, product, or post). + The `object` structure can refer to the object by internal ID or object ID. The `object_id` is the ID that links prior queries to this object. This field comprises the following subfields: + + - `event_attributes.object.internal_id`: The unique ID that OpenSearch uses to internally index the object, for example, the `_id` field in the indexes. + + <p id="object_id"> + + - `event_attributes.object.object_id`: An ID by which a user can find the object instance in the **document corpus**. Examples include `ssn`, `isbn`, or `ean`. Variants need to be incorporated in the `object_id`, so a red T-shirt's `object_id` should be its SKU. + Initializing UBI requires mapping the document index's primary key to this `object_id`. + </p> + + <p id="object_id_field"> + + - `event_attributes.object.object_id_field`: Indicates the type/class of the object and the name of the search index field that contains the `object_id`, such as `ssn`, `isbn`, or `ean`. + + - `event_attributes.object.description`: An optional description of the object. + + - `event_attributes.object.object_detail`: Optional additional information about the object. + + - *extensible fields*: Be aware that any new indexed fields in the `object` will dynamically expand this schema. diff --git a/_search-plugins/ubi/sql-queries.md b/_search-plugins/ubi/sql-queries.md new file mode 100644 index 00000000..fbf3abd8 --- /dev/null +++ b/_search-plugins/ubi/sql-queries.md @@ -0,0 +1,409 @@ +--- +layout: default +title: Sample UBI SQL queries +parent: User Behavior Insights +grand_parent: Optimizing search quality +has_children: false +nav_order: 20 +--- + +# Sample UBI SQL queries + +You can run sample User Behavior Insights (UBI) SQL queries through the OpenSearch Dashboards [Query Workbench]({{site.url}}{{site.baseurl}}/dashboards/query-workbench/). + +## Queries with zero results + +Queries can be executed on events on either the queries index (`ubi_queries`) or events index (`ubi_events`). + +### Server-side queries + +A UBI-enabled search server logs the queries and their results as they are made, so in order to find all queries with *no* results, search for empty `query_response_hit_ids`: + +```sql +select + count(*) +from ubi_queries +where query_response_hit_ids is null + +``` + +### Client-side events + +Although it's relatively straightforward to find queries with no results on the server side, you can also get the same result by querying the *event attributes* that were logged on the client side. +Both client- and server-side queries return the same results. Use the following query to search for queries with no results: + +```sql +select + count(0) +from ubi_events +where event_attributes.result_count > 0 +``` + + + + +## Trending queries + +Trending queries can be found by using either of the following queries. + +### Server-side + +```sql +select + user_query, count(0) Total +from ubi_queries +group by user_query +order by Total desc +``` + +### Client-side + +```sql +select + message, count(0) Total +from ubi_events +where + action_name='on_search' +group by message +order by Total desc +``` + +Both queries return the distribution of search strings, as shown in the following table. + +<!-- vale off --> + +Message|Total +|---|---| +User Behavior Insights|127 +best Laptop|78 +`camera`|21 +`backpack`|17 +`briefcase`|14 +`camcorder`|11 +`cabinet`|9 +`bed`|9 +`box`|8 +`bottle`|8 +`calculator`|8 +`armchair`|7 +`bench`|7 +`blackberry`|6 +`bathroom`|6 +User Behavior Insights Mac|5 +best Laptop Dell|5 +User Behavior Insights VTech|5 +`ayoolaolafenwa`|5 +User Behavior Insights Dell|4 +best Laptop Vaddio|4 +agrega modelos intuitivas|4 +bеуоnd|4 +abraza metodologías B2C|3 + +<!-- vale on --> + + + +## Event type distribution counts + +To create a pie chart widget visualizing the most common events, run the following query: + +```sql +select + action_name, count(0) Total +from ubi_events +group by action_name +order by Total desc +``` + +The results include a distribution across actions, as shown in the following table. + +<!-- vale off --> + +`action_name`|Total +|---|---| +`on_search`|5425 +`brand_filter`|3634 +`global_click`|3571 +`view_search_results`|3565 +`product_sort`|3558 +`type_filter`|3505 +`product_hover`|820 +`item_click`|708 +`purchase`|407 +`declined_product`|402 +`add_to_cart`|373 +`page_exit`|142 +`user_feedback`|123 +404_redirect|123 + +<!-- vale on --> + +The following query shows the distribution of margins across user actions: + + +```sql +select + action_name, + count(0) total, + AVG( event_attributes.object.object_detail.cost ) average_cost, + AVG( event_attributes.object.object_detail.margin ) average_margin +from ubi_events +group by action_name +order by average_cost desc +``` + +The results include actions and the distribution across average costs and margins, as shown in the following table. + +<!-- vale off --> + +`action_name`|total|average_cost|average_margin +---|---|---|--- +`declined_product`|395|8457.12|6190.96 +`item_click`|690|7789.40|5862.70 +`add_to_cart`|374|6470.22|4617.09 +`purchase`|358|5933.83|5110.69 +`global_click`|3555|| +`product_sort`|3711|| +`product_hover`|779|| +`page_exit`|107|| +`on_search`|5438|| +`brand_filter`|3722|| +`user_feedback`|120|| +404_redirect|110|| +`view_search_results`|3639|| +`type_filter`|3691|| + +<!-- vale on --> + +## Sample search journey + +To find a search in the query log, run the following query: + +```sql +select + client_id, query_id, user_query, query_response_hit_ids, query_response_id, timestamp +from ubi_queries where query_id = '7ae52966-4fd4-4ab1-8152-0fd0b52bdadf' +``` + +The following table shows the results of the preceding query. + +<!-- vale off --> + +`client_id`|query_id|user_query|query_response_hit_ids|query_response_id|timestamp +---|---|---|---|---|--- +`a15f1ef3-6bc6-4959-9b83-6699a4d29845`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|notebook|0882780391659|6e92c90c-1eee-4dd6-b820-c522fd4126f3|2024-06-04 19:02:45.728 + +<!-- vale on --> + +The `query` field in `query_id` has the following nested structure: + +```json +{ + "query": { + "size": 25, + "query": { + "query_string": { + "query": "(title:\"notebook\" OR attr_t_device_type:\"notebook\" OR name:\"notebook\")", + "fields": [], + "type": "best_fields", + "default_operator": "or", + "max_determinized_states": 10000, + "enable_position_increments": true, + "fuzziness": "AUTO", + "fuzzy_prefix_length": 0, + "fuzzy_max_expansions": 50, + "phrase_slop": 0, + "analyze_wildcard": false, + "escape": false, + "auto_generate_synonyms_phrase_query": true, + "fuzzy_transpositions": true, + "boost": 1.0 + } + }, + "ext": { + "query_id": "7ae52966-4fd4-4ab1-8152-0fd0b52bdadf", + "user_query": "notebook", + "client_id": "a15f1ef3-6bc6-4959-9b83-6699a4d29845", + "object_id_field": "primary_ean", + "query_attributes": { + "application": "ubi-demo" + } + } + } +} +``` + +In the event log, `ubi_events`, search for the events that correspond to the preceding query (whose query ID is `7ae52966-4fd4-4ab1-8152-0fd0b52bdadf`): + +```sql +select + application, query_id, action_name, message_type, message, client_id, timestamp +from ubi_events +where query_id = '7ae52966-4fd4-4ab1-8152-0fd0b52bdadf' +order by timestamp +``` + +<!-- vale off --> + +The results include all events associated with the user's query, as shown in the following table. + +`application`|query_id|action_name|message_type|message|client_id|timestamp +---|---|---|---|---|---|--- +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|on_search|QUERY|notebook|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.777 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|product_hover|INFO|orquesta soluciones uno-a-uno|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.816 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|item_click|INFO|innova relaciones centrado al usuario|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.86 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|add_to_cart|CONVERSION|engineer B2B platforms|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.905 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|purchase|CONVERSION|Purchase item 0884420136132|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.913 + +<!-- vale on --> + + +## User sessions + +To find more of the same user's sessions (with the client ID `a15f1ef3-6bc6-4959-9b83-6699a4d29845`), run the following query: + +```sql +select + application, event_attributes.session_id, query_id, + action_name, message_type, event_attributes.dwell_time, + event_attributes.object.object_id, + event_attributes.object.description, + timestamp +from ubi_events +where client_id = 'a15f1ef3-6bc6-4959-9b83-6699a4d29845' +order by query_id, timestamp +``` + +The results are truncated to show a sample of sessions, as shown in the following table. + +<!-- vale off --> + +`application`|event_attributes.session_id|query_id|action_name|message_type|event_attributes.dwell_time|event_attributes.object.object_id|event_attributes.object.description|timestamp +---|---|---|---|---|---|---|---|--- +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|on_search|QUERY|46.6398|||2024-06-04 19:06:36.239 +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|product_hover|INFO|53.681877|0065030834155|USB 2.0 S-Video and Composite Video Capture Cable|2024-06-04 19:06:36.284 +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|item_click|INFO|40.699997|0065030834155|USB 2.0 S-Video and Composite Video Capture Cable|2024-06-04 19:06:36.334 +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|declined_product|REJECT|5.0539055|0065030834155|USB 2.0 S-Video and Composite Video Capture Cable|2024-06-04 19:06:36.373 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|on_search|QUERY|26.422775|||2024-06-04 19:04:40.832 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|on_search|QUERY|17.1094|||2024-06-04 19:04:40.837 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|brand_filter|FILTER|40.090374|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:04:40.852 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|type_filter|INFO|37.658962|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:04:40.856 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|product_sort|SORT|3.6380951|||2024-06-04 19:04:40.923 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|view_search_results|INFO|46.436115|||2024-06-04 19:04:40.942 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|view_search_results|INFO|46.436115|||2024-06-04 19:04:40.959 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|type_filter|INFO|37.658962|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:04:40.972 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|brand_filter|FILTER|40.090374|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:04:40.997 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|type_filter|INFO|37.658962|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:04:41.006 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|product_sort|SORT|3.6380951|||2024-06-04 19:04:41.031 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|product_sort|SORT|3.6380951|||2024-06-04 19:04:41.091 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|type_filter|INFO|37.658962|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:04:41.164 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|brand_filter|FILTER|40.090374|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:04:41.171 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|view_search_results|INFO|46.436115|||2024-06-04 19:04:41.179 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|global_click|INFO|42.45651|OBJECT-d350cc2d-b979-4aca-bd73-71709832940f|(96, 127)|2024-06-04 19:04:41.224 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|view_search_results|INFO|46.436115|||2024-06-04 19:04:41.24 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|view_search_results|INFO|46.436115|||2024-06-04 19:04:41.285 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|global_click|INFO|42.45651|OBJECT-d350cc2d-b979-4aca-bd73-71709832940f|(96, 127)|2024-06-04 19:04:41.328 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|on_search|QUERY|52.721157|||2024-06-04 19:03:50.8 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|view_search_results|INFO|26.600422|||2024-06-04 19:03:50.802 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|product_sort|SORT|14.839713|||2024-06-04 19:03:50.875 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|brand_filter|FILTER|20.876852|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:03:50.927 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|type_filter|INFO|15.212905|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:03:50.997 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|view_search_results|INFO|26.600422|||2024-06-04 19:03:51.033 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|global_click|INFO|11.710514|OBJECT-d350cc2d-b979-4aca-bd73-71709832940f|(96, 127)|2024-06-04 19:03:51.108 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|product_sort|SORT|14.839713|||2024-06-04 19:03:51.144 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|global_click|INFO|11.710514|OBJECT-d350cc2d-b979-4aca-bd73-71709832940f|(96, 127)|2024-06-04 19:03:51.17 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|brand_filter|FILTER|20.876852|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:03:51.205 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|type_filter|INFO|15.212905|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:03:51.228 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|product_sort|SORT|14.839713|||2024-06-04 19:03:51.232 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|type_filter|INFO|15.212905|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:03:51.292 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|2071e273-513f-46be-b835-89f452095053|type_filter|INFO|15.212905|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:03:51.301 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|23f0149a-13ae-4977-8dc9-ef61c449c140|on_search|QUERY|16.93674|||2024-06-04 19:03:50.62 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|23f0149a-13ae-4977-8dc9-ef61c449c140|global_click|INFO|25.897957|OBJECT-d350cc2d-b979-4aca-bd73-71709832940f|(96, 127)|2024-06-04 19:03:50.624 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|23f0149a-13ae-4977-8dc9-ef61c449c140|product_sort|SORT|44.345097|||2024-06-04 19:03:50.688 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|23f0149a-13ae-4977-8dc9-ef61c449c140|brand_filter|FILTER|19.54417|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:03:50.696 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|23f0149a-13ae-4977-8dc9-ef61c449c140|type_filter|INFO|48.79312|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:03:50.74 +`ubi-demo`|33bd0ee2-60b7-4c25-b62c-1aa1580da73c|23f0149a-13ae-4977-8dc9-ef61c449c140|brand_filter|FILTER|19.54417|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:03:50.802 + +<!-- vale on --> + + +## List user sessions for users who logged out without submitting any queries + +The following query searches for users who don't have an associated `query_id`. Note that this may happen if the client side does not pass the returned query to other events. + +```sql +select + client_id, session_id, count(0) EventTotal +from ubi_events +where action_name='logout' and query_id is null +group by client_id, session_id +order by EventTotal desc +``` + +<!-- vale off --> + +The following table shows the client ID, session ID, and that there was 1 event,`logout`. + +`client_id`|session_id|EventTotal +---|---|--- +100_15c182f2-05db-4f4f-814f-46dc0de6b9ea|1c36712c-44b8-4fdd-8f0d-fdfeab5bd794_1290|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|816f94d6-8966-4a8b-8984-a2641d5865b2_2251|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|314dc1ff-ef38-4da4-b4b1-061f62dddcbb_2248|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|1ce5dc30-31bb-4759-9451-5a99b28ba91b_2255|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|10ac0fc0-409e-4ba0-98e9-edb323556b1a_2249|1 +174_ab59e589-1ae4-40be-8b29-8efd9fc15380|dfa8b38a-c451-4190-a391-2e1ec3c8f196_2228|1 +174_ab59e589-1ae4-40be-8b29-8efd9fc15380|68666e11-087a-4978-9ca7-cbac6862273e_2233|1 +174_ab59e589-1ae4-40be-8b29-8efd9fc15380|5ca7a0df-f750-4656-b9a5-5eef1466ba09_2234|1 +174_ab59e589-1ae4-40be-8b29-8efd9fc15380|228c1135-b921-45f4-b087-b3422e7ed437_2236|1 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|f9795e2e-ad92-4f15-8cdd-706aa1a3a17b_2206|1 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|f3c18b61-2c8a-41b3-a023-11eb2dd6c93c_2207|1 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|e12f700c-ffa3-4681-90d9-146022e26a18_2210|1 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|da1ff1f6-26f1-49d4-bd0d-d32d199e270e_2208|1 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|a1674e9d-d2dd-4da9-a4d1-dd12a401e8e7_2216|1 +172_875f04d6-2c35-45f4-a8ac-bc5b675425f6|cc8e6174-5c1a-48c5-8ee8-1226621fe9f7_2203|1 +171_7d810730-d6e9-4079-ab1c-db7f98776985|927fcfed-61d2-4334-91e9-77442b077764_2189|1 +16_581fe410-338e-457b-a790-85af2a642356|83a68f57-0fbb-4414-852b-4c4601bf6cf2_156|1 +16_581fe410-338e-457b-a790-85af2a642356|7881141b-511b-4df9-80e6-5450415af42c_162|1 +16_581fe410-338e-457b-a790-85af2a642356|1d64478e-c3a6-4148-9a64-b6f4a73fc684_158|1 + +<!-- vale on --> + +You may want to identify users who logged out multiple times without submitting a query. The following query lets you see which users do this the most: + +```sql +select + client_id, count(0) EventTotal +from ubi_events +where action_name='logout' and query_id is null +group by client_id +order by EventTotal desc +``` + +The following table shows user client IDs and the number of logouts without any queries. + +<!-- vale off --> + +`client_id`|EventTotal +---|--- +87_5a6e1f8c-4936-4184-a24d-beddd05c9274|8 +127_829a4246-930a-4b24-8165-caa07ee3fa47|7 +49_5da537a3-8d94-48d1-a0a4-dcad21c12615|6 +56_6c7c2525-9ca5-4d5d-8ac0-acb43769ac0b|6 +140_61192c8e-c532-4164-ad1b-1afc58c265b7|6 +149_3443895e-6f81-4706-8141-1ebb0c2470ca|6 +196_4359f588-10be-4b2c-9e7f-ee846a75a3f6|6 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|5 +52_778ac7f3-8e60-444e-ad40-d24516bf4ce2|5 +51_6335e0c3-7bea-4698-9f83-25c9fb984e12|5 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|5 +61_feb3a495-c1fb-40ea-8331-81cee53a5eb9|5 +181_f227264f-cabd-4468-bfcc-4801baeebd39|5 +185_435d1c63-4829-45f3-abff-352ef6458f0e|5 +100_15c182f2-05db-4f4f-814f-46dc0de6b9ea|5 +113_df32ed6e-d74a-4956-ac8e-6d43d8d60317|5 +151_0808111d-07ce-4c84-a0fd-7125e4e33020|5 +204_b75e374c-4813-49c4-b111-4bf4fdab6f26|5 +29_ec2133e5-4d9b-4222-aa7c-2a9ae0880ddd|5 +41_f64abc69-56ea-4dd3-a991-7d1fd292a530|5 + +<!-- vale on --> diff --git a/_search-plugins/ubi/ubi-aws-managed-services-tutorial.md b/_search-plugins/ubi/ubi-aws-managed-services-tutorial.md new file mode 100644 index 00000000..fa2b9ba1 --- /dev/null +++ b/_search-plugins/ubi/ubi-aws-managed-services-tutorial.md @@ -0,0 +1,298 @@ +--- +layout: default +title: Collecting UBI-formatted data in Amazon OpenSearch Service +parent: User Behavior Insights +grand_parent: Optimizing search quality +has_children: false +nav_order: 30 +--- + + +# Collecting UBI-formatted data in Amazon OpenSearch Service + +This tutorial shows you how to collect queries and events in the User Behavior Insights (UBI) format when using Amazon OpenSearch Service. + +The native UBI plugin is only available in open-source OpenSearch distributions and is not part of Amazon OpenSearch Service. If you're using OpenSearch Service and want to implement UBI-style data collection, this tutorial demonstrates an alternative approach for implementing this. +{: .important} + +After following this tutorial, you'll be able to send authenticated queries and events to both Amazon Simple Storage Service (Amazon S3) for long-term storage and OpenSearch for real-time processing using the `curl` command-line tool. + +This tutorial assumes the following: + +1. You are using Amazon OpenSearch Service. +2. You are not using the UBI plugin for OpenSearch. The UBI plugin is only available in the open-source version of OpenSearch and is not included in Amazon OpenSearch Service. +3. You are writing UBI data to OpenSearch using [Amazon OpenSearch Ingestion](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/ingestion.html), the managed version of OpenSearch Data Prepper. +4. You have already configured permissions between OpenSearch Ingestion and your managed clusters by following the instructions found in [Tutorial: Ingesting data into a domain using Amazon OpenSearch Ingestion](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/osis-get-started.html), specifically the *Required permissions* step. + +## Step 1: Set up OpenSearch indexes for UBI + +Follow these steps to create the indexes needed for UBI data: + +1. Log in to OpenSearch Dashboards in Amazon OpenSearch Service. +1. On the main menu, select **Management > Dev Tools** to open the **Dev Tools** console. +1. Create two new indexes: `ubi_events` and `ubi_queries`. + + 1. First, start creating the mappings for the `ubi_events` index: + + ```json + PUT /ubi_events + { + "mappings": + } + ``` + + A syntax warning will appear at this point. That's expected; you'll enter the mappings next. + + Open the [events-mapping.json](https://github.com/opensearch-project/user-behavior-insights/blob/main/src/main/resources/events-mapping.json) file, copy its contents, and paste them after the `"mappings":` line: + + ```json + PUT ubi_events + { + "mappings": { + "properties": { + "application": { + "type": "keyword", + "ignore_above": 256 + }, + "action_name": { + "type": "keyword", + "ignore_above": 100 + }, + ... + } + } + } + ``` + + Run the command and verify that it succeeds. + + 1. Next, create the `ubi_queries` index in a similar way. Set up the mappings: + + ```json + PUT ubi_queries + { + "mappings": + } + ``` + + Open the [queries-mapping.json](https://github.com/opensearch-project/user-behavior-insights/blob/main/src/main/resources/queries-mapping.json?utm_source=chatgpt.com) file, copy its contents, and paste them after the `"mappings":` line. Run the command and verify that it succeeds. + +## Step 2: Set up Amazon S3 storage + +For long-term storage of UBI data, use Amazon S3. + +Before proceeding, create an S3 bucket in which the query and event data will be stored. You can do this in the AWS Management Console. Note the bucket name and the AWS Region in which it is created; you'll need this information for the following steps. + +## Step 3: Set up query and event ingest pipelines + +Follow these steps to set up query and event ingest pipelines. + +### Required permissions + +To complete this tutorial, your user or role must have an attached identity-based policy with the following minimum permissions. These permissions allow you to create a pipeline role and attach a policy (`iam:Create*` and `iam:Attach*`), create or modify a domain (`es:*`), and work with pipelines (`osis:*`): + +```json +{ + "Version":"2012-10-17", + "Statement":[ + { + "Effect":"Allow", + "Resource":"*", + "Action":[ + "osis:*", + "iam:Create*", + "iam:Attach*", + "es:*" + ] + }, + { + "Resource":[ + "arn:aws:iam::111122223333:role/OpenSearchIngestion-PipelineRole" + ], + "Effect":"Allow", + "Action":[ + "iam:CreateRole", + "iam:AttachRolePolicy", + "iam:PassRole" + ] + } + ] +} +``` +{% include copy.html %} + +Your `DataPrepperOpenSearchRole` must have permissions similar to the following: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "es:ESHttpPost", + "es:ESHttpPut", + "es:ESHttpGet", + "es:ESHttpHead" + ], + "Resource": "arn:aws:es:*:<YOUR_AWS_ACCOUNT_NUMBER>:*" + }, + { + "Effect": "Allow", + "Action": [ + "s3:PutObject" + ], + "Resource": "arn:aws:s3:::<YOUR-BUCKET>/*" + } + ] +} +``` +{% include copy.html %} + +### Step 3(a): Create a query pipeline + +Follow these steps to create a pipeline for UBI query data: + +1. In the Amazon OpenSearch Service console, select **Pipelines** from the left navigation pane. +1. Select **Create pipeline**. +1. Select a **Blank** pipeline, then select **Select blueprint**. +1. Configure the pipeline to use the **HTTP** source plugin, which accepts UBI query data in JSON array format. Set the OpenSearch Service domain as the sink, directing all data into the `ubi_queries` index. Additionally, log all events to an S3 bucket in `.ndjson` format. +1. In the **Source** menu, select **HTTP**. For **Path**, enter `/ubi/queries`. +1. For **Source network options**, select **Public access** to allow the posting of data from your application. +1. Select **Next**. +1. Skip intermediate **Processor** steps by selecting **Next** on the **Processor** screen. +1. Configure the first sink: + * In **OpenSearch resource type**, select **Managed cluster**. + * Select the OpenSearch Service domain you created earlier. + * In **Index name**, enter `ubi_queries`. Make sure this index exists with the required UBI schema. +1. Configure the second sink: + * Select **Add Sink**. + * Select **Amazon S3**. + * Enter the bucket name and AWS Region you created previously. + * In **Event Collection Timeout**, enter `60s` to observe data flow quickly. + * Select **NDJSON** as the format. +1. Select **Next**. +1. Name the pipeline `ubi-queries-pipeline` and leave the capacity settings at their defaults. +1. Select **Next**, then **Create Pipeline**. + +### Step 3(b): Test the query pipeline + +When the pipeline status is `Active`, you can start ingesting data into it. You must sign all HTTP requests to the pipeline using [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). Use an HTTP tool such as [Postman](https://www.getpostman.com/) or [`awscurl`](https://github.com/okigan/awscurl) to send some data to the pipeline. As with indexing data directly to a domain, ingesting data into a pipeline always requires either an AWS Identity and Access Management (IAM) role or an [IAM access key and secret key](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html). + +To test the pipeline, use these steps: + +1. Retrieve the ingestion URL from the **Pipeline settings** page, shown in the following image. + + ![Pipeline Settings]({{site.url}}{{site.baseurl}}/images/ubi/opensearch-ingestion-pipeline.png "Pipeline Settings") + +1. Post a UBI query to the ingest pipeline. The following is an example of posting a query using [`awscurl`](https://github.com/okigan/awscurl): + + ```bash + awscurl --service osis --region us-east-1 \ + -X POST \ + -H "Content-Type: application/json" \ + -d '[{ + "query_response_id": "117d75fb-ea76-41dc-9d1d-1d7bba548bd8", + "user_query": "laptop", + "query_id": "d194b734-70a4-41dc-b103-b26a56a277b5", + "application": "Chorus", + "query_response_hit_ids": [ + "B076YX2LML", + "B07S3T59VP", + "B075ZGJSL1", + "B07FMGGRGG", + "B07KN5JP3H", + "B07FM8BNBC", + "B007OYLNGA", + "B07P75NDMB", + "B004HJ1ZB8", + "B01M69KU15", + "B072ZW6NBL", + "B07R7NL612", + "B083GH3L2N", + "B06XNQDR8J", + "B07ZQJQ4HV", + "B07YZHH5WY", + "B07F822FND", + "B004XAVT8K", + "B07F5JN761", + "B087RNZT41" + ], + "query_attributes": {}, + "client_id": "CLIENT-9a9968ac-664b-42d7-9a9e-96f412b5ab49", + "timestamp": "2025-01-23T13:18:22.274+0000" + }]' \ + https://ubi-queries-pipeline-il3g3pwe4ve4nov4bwhnzlrm4q.us-east-1.osis.amazonaws.com/ubi/queries + ``` + {% include copy.html %} + + You should receive a `200 OK` response. + +1. Query for the event data that you posted using the Dev Tools console. Note that it may take some time for the data to flow through OpenSearch Ingestion into the `ubi_queries` index: + + ```json + GET /ubi_queries/_search + { + "query": { + "match_all": {} + }, + "sort": [ + { "timestamp": { "order": "desc" } } + ] + } + ``` + {% include copy-curl.html %} + + If you want the newly written data to appear immediately, run the following request: + + ```json + POST /ubi_queries/_refresh + ``` + {% include copy-curl.html %} + +### Step 3(c): Create an event pipeline + +Repeat [Step 3(a)](#step-3a-create-a-query-pipeline) to set up a pipeline for the UBI event data. Use the following table to replace query-specific values with their event equivalents. + +| Setting | Query pipeline | Event pipeline | +|--------------------------|------------------------|------------------------| +| Path | `/ubi/queries` | `/ubi/events` | +| Index name | `ubi_queries` | `ubi_events` | +| Pipeline name | `ubi-queries-pipeline` | `ubi-events-pipeline` | +| S3 path prefix pattern | `ubi_queries/` | `ubi_events/` | +| Dev Tools search | `GET ubi_queries/_search` | `GET ubi_events/_search` | +| Refresh command | `POST ubi_queries/_refresh` | `POST ubi_events/_refresh` | + +### Step 3(d): Test the event pipeline + +Test the event pipeline by following [Step 3(b)](#step-3b-test-the-query-pipeline). The following is an example of posting a query using [`awscurl`](https://github.com/okigan/awscurl): + +```bash +awscurl --service osis --region us-east-1 \ + -X POST \ + -H "Content-Type: application/json" \ + -d '[ + { + "action_name": "product_hover", + "client_id": "CLIENT-9a9968ac-664b-42d7-9a9e-96f412b5ab49", + "query_id": "d194b734-70a4-41dc-b103-b26a56a277b5", + "page_id": "/", + "message_type": "INFO", + "message": "Integral 2GB SD Card memory card (undefined)", + "timestamp": 1724944081669, + "event_attributes": { + "object": { + "object_id_field": "product", + "object_id": "1625640", + "description": "Integral 2GB SD Card memory card", + "object_detail": null + } + } + } +] +' \ +https://ubi-events-pipeline-il3g3pwe4ve4nov4bwhnzlrm4q.us-east-1.osis.amazonaws.com/ubi/events +``` +{% include copy.html %} + +Now you're ready to start collecting UBI data for your applications. diff --git a/_search-plugins/ubi/ubi-dashboard-tutorial.md b/_search-plugins/ubi/ubi-dashboard-tutorial.md new file mode 100644 index 00000000..2380b982 --- /dev/null +++ b/_search-plugins/ubi/ubi-dashboard-tutorial.md @@ -0,0 +1,95 @@ +--- +layout: default +title: UBI dashboard tutorial +parent: User Behavior Insights +grand_parent: Optimizing search quality +has_children: false +nav_order: 25 +--- + + +# UBI dashboard tutorial + +Whether you've been collecting user events and queries for a while or [you've uploaded some sample events](https://github.com/o19s/chorus-OpenSearch-edition/blob/main/katas/003_import_preexisting_event_data.md), you're now ready to visualize the data collected through User Behavior Insights (UBI) in a dashboard in OpenSearch. + +> This tutorial is a nice way to learn how to make custom dashboards. + +To quickly view a dashboard without completing the full tutorial, do the following: +1. Download and save the [sample UBI dashboard]({{site.url}}{{site.baseurl}}/assets/examples/ubi-dashboard.ndjson). +1. On the top menu, go to **Management > Dashboard Management**. +1. In the **Dashboards** panel, choose **Saved objects**. +1. In the upper-right corner, select **Import**. +1. In the **Select file** panel, choose **Import**. +1. Select the UBI dashboard file that you downloaded and select the **Import** button. + +## 1. Start OpenSearch Dashboards + +Start OpenSearch Dashboards. For example, go to `http://{server}:5601/app/home#/`. For more information, see [OpenSearch Dashboards]({{site.url}}{{site.baseurl}}/dashboards/). The following image shows the home page. +![Dashboard Home]({{site.url}}{{site.baseurl}}/images/ubi/home.png) + +## 2. Create an index pattern + +In OpenSearch Management, navigate to **Dashboards Management > Index patterns** or navigate using a URL, such as `http://{server}:5601/app/management/OpenSearch-dashboards/indexPatterns`. + +OpenSearch Dashboards accesses your indexes using index patterns. To visualize your users' online search behavior, you must create an index pattern in order to access the indexes that UBI creates. For more information, see [Index patterns]({{site.url}}{{site.baseurl}}/dashboards/management/index-patterns/). + +After you select **Create index pattern**, a list of indexes in your OpenSearch instance is displayed. The UBI stores may be hidden by default, so make sure to select **Include system and hidden indexes**, as shown in the following image. +![Index Patterns]({{site.url}}{{site.baseurl}}/images/ubi/index_pattern2.png) + +You can group indexes into the same data source for your dashboard using wildcards. For this tutorial you'll combine the query and event stores into the `ubi_*` pattern. + +OpenSearch Dashboards prompts you to filter on any `date` field in your schema so that you can look at things like trending queries over the last 15 minutes. However, for your first dashboard, select **I don't want to use the time filter**, as shown in the following image. +![Index Patterns]({{site.url}}{{site.baseurl}}/images/ubi/index_pattern3.png){: width="400" } + + +After selecting **Create index pattern**, you're ready to start building a dashboard that displays the UBI store data. + +## 3. Create a new dashboard + +To create a new dashboard, on the top menu, select **OpenSearch Dashboards > Dashboards** and then **Create > Dashboard** > **Create new**. +If you haven't previously created a dashboard, you are presented with the option to create a new dashboard. Otherwise, previously created dashboards are displayed. + + +In the **New Visualization** window, select **Pie** to create a new pie chart. Then select the index pattern you created in step 2. + +Most visualizations require some sort of aggregate function on a bucket/facet/aggregatable field (numeric or keyword). You'll add a `Terms` aggregation to the `action_name` field so that you can view the distribution of event names. Change the **Size** to the number of slices you want to display, as shown in the following image. +![Pie Chart]({{site.url}}{{site.baseurl}}/images/ubi/pie.png) + +Save the visualization so that it's added to your new dashboard. Now that you have a visualization displayed on your dashboard, you can save the dashboard. + +## 4. Add a tag cloud visualization + +Now you'll add a word cloud for trending searches by creating a new visualization, similarly to the previous step. + +In the **New Visualization** window, select **Tag Cloud**, and then select the index pattern you created in Step 2. Choose the tag cloud visualization of the terms in the `message` field where the JavaScript client logs the raw search text. Note: The true query, as processed by OpenSearch with filters, boosting, and so on, resides in the `ubi_queries` index. However, you'll view the `message` field of the `ubi_events` index, where the JavaScript client captures the text that the user actually typed. + +The following image shows the tag cloud visualization on the `message` field. +![Word Cloud]({{site.url}}{{site.baseurl}}/images/ubi/tag_cloud1.png) + +The underlying queries can be found at [SQL trending queries]({{site.url}}{{site.baseurl}}/search-plugins/ubi/sql-queries/#trending-queries). +{: .note} + + +The resulting visualization may contain different information than you're looking for. The `message` field is updated with every event, and as a result, it can contain error messages, debug messages, click information, and other unwanted data. +To view only search terms for query events, you need to add a filter to your visualization. Because during setup you provided a `message_type` of `QUERY` for each search event, you can filter by that message type to isolate the specific users' searches. To do this, select **Add filter** and then select **QUERY** in the **Edit filter** panel, as shown in the following image. +![Word Cloud]({{site.url}}{{site.baseurl}}/images/ubi/tag_cloud2.png) + +There should now be two visualizations (the pie chart and the tag cloud) displayed on your dashboard, as shown in the following image. +![UBI Dashboard]({{site.url}}{{site.baseurl}}/images/ubi/dashboard2.png) + +## 5. Add a histogram of item clicks + +Now you'll add a histogram visualization to your dashboard, similarly to the previous step. In the **New Visualization** window, select **Vertical Bar**. Then select the index pattern you created in Step 2. + +Examine the `event_attributes.position.ordinal` data field. This field contains the position of the item in a list selected by the user. For the histogram visualization, the x-axis represents the ordinal number of the selected item (n). The y-axis represents the number of times that the nth item was clicked, as shown in the following image. + +![Vertical Bar Chart]({{site.url}}{{site.baseurl}}/images/ubi/histogram.png) + +## 6. Filter the displayed data + +Now you can further filter the displayed data. For example, you can see how the click position changes when a purchase occurs. Select **Add filter** and then select the `action_name:product_purchase` field, as shown in the following image. +![Product Purchase]({{site.url}}{{site.baseurl}}/images/ubi/product_purchase.png) + + +You can filter event messages containing the word `*laptop*` by adding wildcards, as shown in the following image. +![Laptop]({{site.url}}{{site.baseurl}}/images/ubi/laptop.png "Laptop"). diff --git a/_search-plugins/ubi/ubi-javascript-collector.md b/_search-plugins/ubi/ubi-javascript-collector.md new file mode 100644 index 00000000..16850b02 --- /dev/null +++ b/_search-plugins/ubi/ubi-javascript-collector.md @@ -0,0 +1,124 @@ +--- +layout: default +title: UBI JavaScript Collector +parent: User Behavior Insights +grand_parent: Optimizing search quality +has_children: false +nav_order: 10 +--- + +# How to use UBI JavaScript collector + +UBI comes with a very basic JavaScript client that manages the lifecycle of the `query_id` for a specific search and can create UBI event data structures and store them for specific actions. + +For more information about the schema, see [UBI index schemas]({{site.url}}{{site.baseurl}}/search-plugins/ubi/schemas/). + +We recommend using the client as a starting point to address your specific needs. + +## Installation + +The client is a single file ([ubi.js](https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js)) and only has a dependency on the `axios` library. +<!-- vale off --> +Download it from [https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js](https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js). +<!-- vale on --> + +To reference the events and create the client, use the following code: + +```js +import { UbiEvent } from './ubi'; +import { UbiEventAttributes } from './ubi' +import { UbiClient } from './ubi' + +const ubiClient = new UbiClient('http://localhost:9200'); +``` +{% include copy.html %} + + +## Creating an event + +The following code tracks adding an item to a shopping cart in an e-commerce application. It uses the `UbiEvent` and `UbiEventAttributes` classes to encapsulate event details, which can then be sent to the tracking system: +```js +var event = new UbiEvent( + 'add_to_cart', + client_id, + session_id, + getQueryId(), + new UbiEventAttributes('product', item.primary_ean, item.title, item), + item.title + ' (' + item.id + ')' +); +``` +{% include copy.html %} + +### Parameters + +1. **Event Name**: + - `'add_to_cart'` -- This string indicates the type of event being tracked. + +2. **Client ID**: + - `client_id` -- A variable that holds the unique identifier for the client. This helps in distinguishing between different users or sessions. + +3. **Session ID**: + - `session_id` -- A variable that contains the unique identifier for the user session. This is used to track user interactions within a specific session. + +4. **Query ID**: + - `getQueryId()` -- A function call that retrieves the current query ID, which may represent a specific search or interaction context. + +5. **UbiEventAttributes**: + - This is an instance of the `UbiEventAttributes` class, which encapsulates additional details about the event: + - **Type**: + - `'product'` -- Specifies that the attribute type is related to a product. + - **Primary EAN**: + - `item.primary_ean` -- This is the product's unique identifier in EAN format. + - **Title**: + - `item.title` -- The name or description of the product. + - **Item**: + - `item` -- The complete product object containing all relevant details. + +6. **Event Label**: + - `item.title + ' (' + item.id + ')'` -- This creates a descriptive label for the event that includes the product title and its unique identifier (ID). + +The method `getQueryId()` refers to a helper method that generates a unique query ID (and stores it in the session). +The following is a sample method: + +```js +function generateQueryId(){ + const query_id = generateGuid(); + sessionStorage.setItem('query_id', query_id); + return query_id; +} + +function generateGuid() { + let id = ''; + try{ + id = crypto.randomUUID(); + } + catch(error){ + // crypto.randomUUID only works in https, not http context, so fallback. + id ='10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c => + (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) + ); + } + return id; +}; +``` +{% include copy.html %} + +## Tracking the event + +You can send the event to the backend by calling the `trackEvent` method: + +```js +ubiClient.trackEvent(event); +``` + + +## Tracking queries + +You can optionally track queries using the client (instead of using the UBI plugin for OpenSearch). + +The code is similar to that used for tracking events: + +```js +const query = new UbiQuery(APPLICATION, client_id, query_id, value, "_id", {}); +ubiClient.trackQuery(query) +``` diff --git a/_security-analytics/api-tools/alert-finding-api.md b/_security-analytics/api-tools/alert-finding-api.md index a22b601b..29fef326 100644 --- a/_security-analytics/api-tools/alert-finding-api.md +++ b/_security-analytics/api-tools/alert-finding-api.md @@ -1,7 +1,7 @@ --- layout: default title: Alerts and findings APIs -parent: API tools +parent: Security Analytics APIs nav_order: 50 --- @@ -71,7 +71,7 @@ GET /_plugins/_security_analytics/alerts?detectorType=windows } ``` -#### Response fields +#### Response body fields Alerts persist until you resolve the root cause and have the following states: @@ -87,12 +87,12 @@ State | Description ## Acknowledge alerts -Sends an acknowledgement when an alert is triggered. +Sends an acknowledgment when an alert is triggered. ### Example request ```json -POST /_plugins/_security_analytics/<detector_id>/_acknowledge/alerts +POST /_plugins/_security_analytics/detectors/{detector_id}/_acknowledge/alerts {"alerts":["4dc7f5a9-2c82-4786-81ca-433a209d5205"]} ``` @@ -141,7 +141,7 @@ POST /_plugins/_security_analytics/<detector_id>/_acknowledge/alerts ## Get findings -The Get findings API returns findings based on the detector attributes. +The Get Findings API returns findings based on the detector attributes. ### Parameters @@ -149,13 +149,230 @@ You can specify the following parameters when getting findings. Parameter | Description :--- | :--- -`detector_id` | The ID of the detector used to fetch alerts. Optional when the `detectorType` is specified. Otherwise required. -`detectorType` | The type of detector used to fetch alerts. Optional when the `detector_id` is specified. Otherwise required. +`detector_id` | The ID of the detector used to fetch alerts. Optional. +`detectorType` | The type of detector used to fetch alerts. Optional. `sortOrder` | The order used to sort the list of findings. Possible values are `asc` or `desc`. Optional. `size` | An optional limit for the maximum number of results returned in the response. Optional. +`startIndex` | The pagination indicator. Optional. +`detectionType` | The detection rule type that dictates the retrieval type for the findings. When the detection type is `threat`, it fetches threat intelligence feeds. When the detection type is `rule`, findings are fetched based on the detector's rule. Optional. +`severity` | The severity of the detector rule used to fetch alerts. Severity can be `critical`, `high`, `medium`, or `low`. Optional. ### Example request +```json +GET /_plugins/_security_analytics/findings/_search +{ + "total_findings": 2, + "findings": [ + { + "detectorId": "b9ZN040Bjlggkcgx1d1W", + "id": "35efb736-c5d9-499d-b9b5-31f0a7d61251", + "related_doc_ids": [ + "1" + ], + "index": "smallidx", + "queries": [ + { + "id": "QdZN040Bjlggkcgxdd3X", + "name": "QdZN040Bjlggkcgxdd3X", + "fields": [], + "query": "field1: *value1*", + "tags": [ + "high", + "ad_ldap" + ] + } + ], + "timestamp": 1708647166500, + "document_list": [ + { + "index": "smallidx", + "id": "1", + "found": true, + "document": "{\n \"field1\": \"value1\"\n}\n" + } + ] + }, + { + "detectorId": "O9ZM040Bjlggkcgx6N1S", + "id": "a5022930-4503-4ca8-bf0a-320a2b1fb433", + "related_doc_ids": [ + "1" + ], + "index": "smallidx", + "queries": [ + { + "id": "KtZM040Bjlggkcgxkd04", + "name": "KtZM040Bjlggkcgxkd04", + "fields": [], + "query": "field1: *value1*", + "tags": [ + "critical", + "ad_ldap" + ] + } + ], + "timestamp": 1708647166500, + "document_list": [ + { + "index": "smallidx", + "id": "1", + "found": true, + "document": "{\n \"field1\": \"value1\"\n}\n" + } + ] + } + ] +} + +``` + +```json +GET /_plugins/_security_analytics/findings/_search?severity=high +{ + "total_findings": 1, + "findings": [ + { + "detectorId": "b9ZN040Bjlggkcgx1d1W", + "id": "35efb736-c5d9-499d-b9b5-31f0a7d61251", + "related_doc_ids": [ + "1" + ], + "index": "smallidx", + "queries": [ + { + "id": "QdZN040Bjlggkcgxdd3X", + "name": "QdZN040Bjlggkcgxdd3X", + "fields": [], + "query": "field1: *value1*", + "tags": [ + "high", + "ad_ldap" + ] + } + ], + "timestamp": 1708647166500, + "document_list": [ + { + "index": "smallidx", + "id": "1", + "found": true, + "document": "{\n \"field1\": \"value1\"\n}\n" + } + ] + } + ] +} + +``` + +```json +GET /_plugins/_security_analytics/findings/_search?detectionType=rule +{ + "total_findings": 2, + "findings": [ + { + "detectorId": "b9ZN040Bjlggkcgx1d1W", + "id": "35efb736-c5d9-499d-b9b5-31f0a7d61251", + "related_doc_ids": [ + "1" + ], + "index": "smallidx", + "queries": [ + { + "id": "QdZN040Bjlggkcgxdd3X", + "name": "QdZN040Bjlggkcgxdd3X", + "fields": [], + "query": "field1: *value1*", + "tags": [ + "high", + "ad_ldap" + ] + } + ], + "timestamp": 1708647166500, + "document_list": [ + { + "index": "smallidx", + "id": "1", + "found": true, + "document": "{\n \"field1\": \"value1\"\n}\n" + } + ] + }, + { + "detectorId": "O9ZM040Bjlggkcgx6N1S", + "id": "a5022930-4503-4ca8-bf0a-320a2b1fb433", + "related_doc_ids": [ + "1" + ], + "index": "smallidx", + "queries": [ + { + "id": "KtZM040Bjlggkcgxkd04", + "name": "KtZM040Bjlggkcgxkd04", + "fields": [], + "query": "field1: *value1*", + "tags": [ + "critical", + "ad_ldap" + ] + } + ], + "timestamp": 1708647166500, + "document_list": [ + { + "index": "smallidx", + "id": "1", + "found": true, + "document": "{\n \"field1\": \"value1\"\n}\n" + } + ] + } + ] +} + + +``` +```json +GET /_plugins/_security_analytics/findings/_search?detectionType=rule&severity=high +{ + "total_findings": 1, + "findings": [ + { + "detectorId": "b9ZN040Bjlggkcgx1d1W", + "id": "35efb736-c5d9-499d-b9b5-31f0a7d61251", + "related_doc_ids": [ + "1" + ], + "index": "smallidx", + "queries": [ + { + "id": "QdZN040Bjlggkcgxdd3X", + "name": "QdZN040Bjlggkcgxdd3X", + "fields": [], + "query": "field1: *value1*", + "tags": [ + "high", + "ad_ldap" + ] + } + ], + "timestamp": 1708647166500, + "document_list": [ + { + "index": "smallidx", + "id": "1", + "found": true, + "document": "{\n \"field1\": \"value1\"\n}\n" + } + ] + } + ] +} + +``` + ```json GET /_plugins/_security_analytics/findings/_search?*detectorType*= { diff --git a/_security-analytics/api-tools/correlation-eng.md b/_security-analytics/api-tools/correlation-eng.md index 81f73315..b723fca2 100644 --- a/_security-analytics/api-tools/correlation-eng.md +++ b/_security-analytics/api-tools/correlation-eng.md @@ -1,33 +1,53 @@ --- layout: default title: Correlation engine APIs -parent: API tools +parent: Security Analytics APIs nav_order: 55 --- - # Correlation engine APIs Correlation engine APIs allow you to create new correlation rules, view findings and correlations within a certain time window, and perform other tasks. --- + ## Create correlation rules between log types -This API is used to create correlation rules: +Creates a correlation rule that correlates findings from two or more log sources. + +### Endpoints ```json POST /_plugins/_security_analytics/correlation/rules ``` -### Request fields +### Request body fields -| Field | Type | Description | +The following table lists the available request body fields. + +| Field | Data type | Description | | :--- | :--- |:--- | -| `index` | String | The name of the index used as the log source. | -| `query` | String | The query used to filter security logs for correlation. | -| `category` | String | The log type associated with the log source. | +| `name` | String | The name of the correlation rule. Optional. | +| `correlate` | Array | The log sources to correlate. Provide at least two. Required. | +| `correlate.index` | String | The name of the index used as the log source. | +| `correlate.query` | String | The query used to filter security logs for correlation. | +| `correlate.category` | String | The log type associated with the log source. | +| `time_window` | Long | The window, in milliseconds, within which findings must occur to be correlated. Optional. If not specified, the `plugins.security_analytics.correlation_time_window` cluster setting applies. | +| `trigger` | Object | Generates a correlation alert and sends notifications when the rule correlates findings. Optional. | +| `trigger.name` | String | The name of the trigger. | +| `trigger.severity` | String | Severity level for the trigger expressed as an integer: 1 = highest; 2 = high; 3 = medium; 4 = low; 5 = lowest. | +| `trigger.actions` | Array | The notifications to send when the trigger generates an alert. | +| `trigger.actions.name` | String | The name of the action. Required for each action. | +| `trigger.actions.destination_id` | String | The ID of the notification channel that receives the message. | +| `trigger.actions.subject_template.source` | String | The subject of the notification message. Can include [correlation rule trigger variables](#correlation-rule-trigger-variables). | +| `trigger.actions.subject_template.lang` | String | The scripting language used to define the subject. Must be `mustache`. | +| `trigger.actions.message_template.source` | String | The body of the notification message. Can include [correlation rule trigger variables](#correlation-rule-trigger-variables). | +| `trigger.actions.message_template.lang` | String | The scripting language used to define the message. Must be `mustache`. | +| `trigger.actions.throttle_enabled` | Boolean | Whether to limit the number of notifications sent within a span of time. Default is `false`. | +| `trigger.actions.throttle.unit` | String | The unit of time used for throttling. | +| `trigger.actions.throttle.value` | Integer | The number of units of time used for throttling. | -#### Example request +### Example request ```json POST /_plugins/_security_analytics/correlation/rules @@ -58,7 +78,7 @@ POST /_plugins/_security_analytics/correlation/rules ``` {% include copy-curl.html %} -#### Example response +### Example response ```json { @@ -92,36 +112,235 @@ POST /_plugins/_security_analytics/correlation/rules } ``` -### Response fields +### Response body fields -| Field | Type | Description | +The following table lists all response body fields. + +| Field | Data type | Description | | :--- | :--- |:--- | -| `_id` | String | The Id for the new rule. | +| `_id` | String | The ID for the new rule. | ---- -## List all findings and their correlations within a time window +### Correlation rule triggers -This API provides a list of all findings and their correlations within a specified time window: +Add a `trigger` to a correlation rule to generate a correlation alert and send a notification each time the rule correlates findings. The following request creates a rule with a trigger that notifies a channel when a network finding correlates with an Active Directory finding: ```json -GET /_plugins/_security_analytics/correlations?start_timestamp=<start time in milliseconds>&end_timestamp=<end time in milliseconds> +POST /_plugins/_security_analytics/correlation/rules +{ + "name": "network-ad-correlation", + "time_window": 300000, + "correlate": [ + { + "index": "vpc_flow", + "query": "dstaddr:4.5.6.7", + "category": "network" + }, + { + "index": "ad_logs", + "query": "ResultType:50126", + "category": "ad_ldap" + } + ], + "trigger": { + "name": "correlation-trigger", + "severity": "1", + "actions": [ + { + "name": "notify-security-team", + "destination_id": "6r8ZBoQBKW_6dKriacQb", + "subject_template": { + "source": {% raw %}"Correlation alert: {{ctx.correlationRuleName}}"{% endraw %}, + "lang": "mustache" + }, + "message_template": { + "source": {% raw %}"Rule {{ctx.correlationRuleName}} correlated finding {{ctx.sourceFinding}} with findings {{ctx.correlatedFindingIds}} within {{ctx.timeWindow}} ms."{% endraw %}, + "lang": "mustache" + }, + "throttle_enabled": false + } + ] + } +} +``` +{% include copy-curl.html %} + +The response contains the generated trigger and action IDs: + +```json +{ + "_id": "7mBjhqABedeO5z2szdu9", + "_version": 1, + "rule": { + "name": "network-ad-correlation", + "correlate": [ + { + "index": "vpc_flow", + "category": "network", + "query": "dstaddr:4.5.6.7" + }, + { + "index": "ad_logs", + "category": "ad_ldap", + "query": "ResultType:50126" + } + ], + "time_window": 300000, + "trigger": { + "id": "62BjhqABedeO5z2szdss", + "name": "correlation-trigger", + "severity": "1", + "actions": [ + { + "id": "6mBjhqABedeO5z2szdsr", + "name": "notify-security-team", + "destination_id": "6r8ZBoQBKW_6dKriacQb", + "message_template": { + "source": {% raw %}"Rule {{ctx.correlationRuleName}} correlated finding {{ctx.sourceFinding}} with findings {{ctx.correlatedFindingIds}} within {{ctx.timeWindow}} ms."{% endraw %}, + "lang": "mustache" + }, + "throttle_enabled": false, + "subject_template": { + "source": {% raw %}"Correlation alert: {{ctx.correlationRuleName}}"{% endraw %}, + "lang": "mustache" + } + } + ] + } + } +} +``` + +Each action requires a `name`. A request that omits it fails with an `uninitialized_property_access_exception` error. +{: .note} + +### Correlation rule trigger variables + +The following table lists the variables available in the `subject_template` and `message_template` of a correlation rule trigger action. These variables differ from the ones available in alerting monitors, which are described in [Monitor variables]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/#monitor-variables). + +| Variable | Data type | Description | +| :--- | :--- | :--- | +| `ctx.correlationRuleName` | String | The name of the correlation rule that generated the alert. | +| `ctx.sourceFinding` | String | The ID of the finding that initiated the correlation. | +| `ctx.correlatedFindingIds` | Array | The IDs of the findings correlated with the source finding. | +| `ctx.timeWindow` | Long | The correlation time window, in milliseconds. | + +To see the entire context object, add {% raw %}`{{ctx}}`{% endraw %} to the message body. + +--- + +## Search for correlation rules + +Searches for correlation rules using a query. The request body requires a search query. For query options, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +### Endpoints + +```json +POST /_plugins/_security_analytics/correlation/rules/_search +``` + +### Example request + +The `correlate` field is mapped as a `nested` field, so use a `nested` query to search the log sources in a rule. The following request searches for correlation rules that correlate `network` logs: + +```json +POST /_plugins/_security_analytics/correlation/rules/_search +{ + "query": { + "nested": { + "path": "correlate", + "query": { + "term": { + "correlate.category": "network" + } + } + } + } +} +``` +{% include copy-curl.html %} + +### Example response + +Each hit's `_source` contains the correlation rule definition: + +```json +{ + "took": 31, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.31506687, + "hits": [ + { + "_index": ".opensearch-sap-correlation-rules-config", + "_id": "ArQirKEBASjcpUUjnqb9", + "_version": 1, + "_seq_no": 1, + "_primary_term": 18, + "_score": 0.31506687, + "_source": { + "name": "network-windows", + "correlate": [ + { + "index": "vpc_flow", + "category": "network", + "query": "dstaddr:4.5.6.7" + }, + { + "index": "windows", + "category": "windows", + "query": "winlog.event_data.SubjectDomainName:NTAUTHORI*" + } + ], + "time_window": 300000, + "trigger": null + } + } + ] + } +} +``` + +For descriptions of the rule fields, see [Request body fields](#request-body-fields). + +--- + +## List all findings and correlations within a certain time window + +Lists all findings and their correlations within a certain time window. + +### Endpoints + +```json +GET /_plugins/_security_analytics/correlations ``` ### Query parameters -| Parameter | Type | Description | +The following table lists the available query parameters. Both query parameters are required. + +| Parameter | Data type | Description | | :--- | :--- |:--- | | `start_timestamp` | Number | Start time for the time window, in milliseconds. | | `end_timestamp` | Number | End time for the time window, in milliseconds. | -#### Example request +### Example request ```json GET /_plugins/_security_analytics/correlations?start_timestamp=1689289210000&end_timestamp=1689300010000 ``` {% include copy-curl.html %} -#### Example response +### Example response ```json { @@ -139,43 +358,49 @@ GET /_plugins/_security_analytics/correlations?start_timestamp=1689289210000&end } ``` -### Response fields +### Response body fields -| Field | Type | Description | +The following table lists all response body fields. + +| Field | Data type | Description | | :--- | :--- |:--- | -| `finding1` | String | The Id for a first finding in the correlation. | +| `finding1` | String | The ID for a first finding in the correlation. | | `logType1` | String | The log type associated with the first finding. | -| `finding2` | String | The Id for a second finding in the correlation. | +| `finding2` | String | The ID for a second finding in the correlation. | | `logType2` | String | The log type associated with the second finding. | | `rules` | Array | A list of correlation rule IDs associated with the correlated findings. | --- + ## List correlations for a finding belonging to a log type -This API is used to list correlations for specific findings and the log types associated with them: +Lists the findings correlated with a given finding. + +### Endpoints ```json -GET /_plugins/_security_analytics/findings/correlate?finding=425dce0b-f5ee-4889-b0c0-7d15669f0871&detector_type=ad_ldap&nearby_findings=20&time_window=10m +GET /_plugins/_security_analytics/findings/correlate ``` ### Query parameters -| Parameter | Type | Description | +The following table lists the available query parameters. + +| Parameter | Data type | Description | | :--- | :--- |:--- | -| `finding` | String | The finding ID. | -| `detector_type` | String | The log type for the detector. | -| `nearby_findings` | Number | The number of nearby findings with respect to the given finding Id. | -| `time_window` | String | Sets a time window in which all of the correlations must have occurred together. | +| `finding` | String | The finding ID. Required. | +| `detector_type` | String | The log type for the detector. Required. | +| `nearby_findings` | Number | The number of nearby findings with respect to the given finding ID. Optional. | +| `time_window` | String | Sets a time window in which all of the correlations must have occurred together. Optional. | - -#### Example request +### Example request ```json GET /_plugins/_security_analytics/findings/correlate?finding=425dce0b-f5ee-4889-b0c0-7d15669f0871&detector_type=ad_ldap&nearby_findings=20&time_window=10m ``` {% include copy-curl.html %} -#### Example response +### Example response ```json { @@ -214,11 +439,212 @@ GET /_plugins/_security_analytics/findings/correlate?finding=425dce0b-f5ee-4889- } ``` -### Response fields +### Response body fields -| Field | Type | Description | +The following table lists all response body fields. + +| Field | Data type | Description | | :--- | :--- |:--- | | `finding` | String | The finding ID. | | `detector_type` | String | The log type associated with the finding. | | `score` | Number | The correlation score for the correlated finding. The score is based on the proximity of relevant findings in the threat scenario defined by the correlation rule. | +--- + +## List correlation alerts + +Lists the alerts generated by correlation rule triggers. + +### Endpoints + +```json +GET /_plugins/_security_analytics/correlationAlerts +``` + +### Query parameters + +The following table lists the available query parameters. All query parameters are optional. + +| Parameter | Data type | Description | +| :--- | :--- |:--- | +| `correlation_rule_id` | String | The correlation rule ID. | + +### Example request + +```json +GET /_plugins/_security_analytics/correlationAlerts?correlation_rule_id=VjY0MpABPzR_pcEveVRq +``` +{% include copy-curl.html %} + +### Example response + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "correlationAlerts": [ + { + "correlated_finding_ids": [ + "4f867df9-c9cb-4dc1-84bb-6c8b575f1a54" + ], + "correlation_rule_id": "VjY0MpABPzR_pcEveVRq", + "correlation_rule_name": "rule-corr", + "user": null, + "id": "8532c08b-3ab5-4e95-a1c2-5884c4cd41a5", + "version": 1, + "schema_version": 1, + "trigger_name": "trigger1", + "state": "ACTIVE", + "error_message": null, + "severity": "1", + "action_execution_results": [], + "start_time": "2024-06-19T20:37:08.257Z", + "end_time": "2024-06-19T20:42:08.257Z", + "acknowledged_time": null + }, + { + "correlated_finding_ids": [ + "30d2109f-76bb-44ad-8f68-6daa905e018d" + ], + "correlation_rule_id": "VjY0MpABPzR_pcEveVRq", + "correlation_rule_name": "rule-corr", + "user": null, + "id": "8bba85d9-a7fc-4c87-b35e-a7236b87159f", + "version": 1, + "schema_version": 1, + "trigger_name": "trigger1", + "state": "ACTIVE", + "error_message": null, + "severity": "1", + "action_execution_results": [], + "start_time": "2024-06-19T20:43:08.208Z", + "end_time": "2024-06-19T20:48:08.208Z", + "acknowledged_time": null + } + ], + "total_alerts": 2 +} +``` +</details> + +### Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- |:--- | +| `correlationAlerts` | Array | The correlation alerts that match the request. | +| `correlationAlerts.correlated_finding_ids` | Array | The IDs of the findings correlated by the rule. | +| `correlationAlerts.correlation_rule_id` | String | The ID of the correlation rule that generated the alert. | +| `correlationAlerts.correlation_rule_name` | String | The name of the correlation rule that generated the alert. | +| `correlationAlerts.user` | Object | The user associated with the correlation rule. | +| `correlationAlerts.id` | String | The alert ID. | +| `correlationAlerts.version` | Integer | The alert version. | +| `correlationAlerts.schema_version` | Integer | The version of the alert index schema. | +| `correlationAlerts.trigger_name` | String | The name of the trigger that generated the alert. | +| `correlationAlerts.state` | String | The alert state. Valid values are `ACTIVE`, `ACKNOWLEDGED`, `COMPLETED`, `ERROR`, and `DELETED`. | +| `correlationAlerts.error_message` | String | The error message for the alert, if any. | +| `correlationAlerts.severity` | String | The severity level of the trigger that generated the alert. | +| `correlationAlerts.action_execution_results` | Array | The results of the notification actions that the trigger ran. | +| `correlationAlerts.start_time` | String | The time at which the alert was generated. | +| `correlationAlerts.end_time` | String | The time at which the correlation time window ended. | +| `correlationAlerts.acknowledged_time` | String | The time at which the alert was acknowledged. `null` if the alert has not been acknowledged. | +| `total_alerts` | Integer | The total number of alerts returned. | + +--- + +## Acknowledge correlation alerts + +Acknowledges one or more correlation alerts. + +### Endpoints + +```json +POST /_plugins/_security_analytics/_acknowledge/correlationAlerts +``` + +### Request body fields + +The following table lists the available request body fields. + +| Field | Data type | Description | +| :--- | :--- |:--- | +| `alertIds` | Array | The IDs of the correlation alerts to acknowledge. Required. | + +### Example request + +```json +POST /_plugins/_security_analytics/_acknowledge/correlationAlerts +{ + "alertIds": ["8532c08b-3ab5-4e95-a1c2-5884c4cd41a5", "8bba85d9-a7fc-4c87-b35e-a7236b87159f"] +} +``` +{% include copy-curl.html %} + +### Example response + +<details markdown="block"> + <summary> + Response + </summary> + {: .text-delta} + +```json +{ + "acknowledged": [ + { + "correlated_finding_ids": [ + "4f867df9-c9cb-4dc1-84bb-6c8b575f1a54" + ], + "correlation_rule_id": "VjY0MpABPzR_pcEveVRq", + "correlation_rule_name": "rule-corr", + "user": null, + "id": "8532c08b-3ab5-4e95-a1c2-5884c4cd41a5", + "version": 1, + "schema_version": 1, + "trigger_name": "trigger1", + "state": "ACTIVE", + "error_message": null, + "severity": "1", + "action_execution_results": [], + "start_time": "2024-06-19T20:37:08.257Z", + "end_time": "2024-06-19T20:42:08.257Z", + "acknowledged_time": null + }, + { + "correlated_finding_ids": [ + "30d2109f-76bb-44ad-8f68-6daa905e018d" + ], + "correlation_rule_id": "VjY0MpABPzR_pcEveVRq", + "correlation_rule_name": "rule-corr", + "user": null, + "id": "8bba85d9-a7fc-4c87-b35e-a7236b87159f", + "version": 1, + "schema_version": 1, + "trigger_name": "trigger1", + "state": "ACTIVE", + "error_message": null, + "severity": "1", + "action_execution_results": [], + "start_time": "2024-06-19T20:43:08.208Z", + "end_time": "2024-06-19T20:48:08.208Z", + "acknowledged_time": null + } + ], + "failed": [] +} +``` +</details> + +### Response body fields + +The following table lists all response body fields. + +| Field | Data type | Description | +| :--- | :--- |:--- | +| `acknowledged` | Array | The correlation alerts that were acknowledged. | +| `failed` | Array | The correlation alerts that could not be acknowledged. | diff --git a/_security-analytics/api-tools/detector-api.md b/_security-analytics/api-tools/detector-api.md index e9de8698..2d36398e 100644 --- a/_security-analytics/api-tools/detector-api.md +++ b/_security-analytics/api-tools/detector-api.md @@ -1,16 +1,16 @@ --- layout: default title: Detector APIs -parent: API tools +parent: Security Analytics APIs nav_order: 35 --- # Detector APIs -The following APIs can be used for a number of tasks related to detectors, from creating detectors to updating and searching for detectors. Many API calls use the detector ID in the request, which can be retrieved using the [Search Detector API](#search-detector-api). +The following APIs can be used for a number of tasks related to detectors, from creating detectors to updating and searching for detectors. Many API calls use the detector ID in the request, which can be retrieved using the [Search detector API](#search-detector). --- -## Create Detector API +## Create detector Creates a new detector. @@ -18,33 +18,33 @@ Creates a new detector. POST _plugins/_security_analytics/detectors ``` -### Request fields +### Request body fields You can specify the following fields when creating a detector. Field | Type | Description :--- | :--- |:--- | `enabled` | Boolean | Sets the detector as either active (true) or inactive (false). Default is `true` when a new detector is created. Required. -`name` | String | Name of the detector. Name should only consist of upper and lowercase letters, numbers 0-9, hyphens, spaces, and underscores. Use between 5 and 50 characters. Required. +`name` | String | Name of the detector. Name should only consist of upper and lowercase letters, numbers 0--9, hyphens, spaces, and underscores. Use 5--50 characters. Required. `detector_type` | String | The log type that defines the detector. Options are `linux`, `network` ,`windows`, `ad_ldap`, `apache_access`, `cloudtrail`, `dns`, and `s3`. Required. -`schedule` | Object | The schedule that determines how often the detector runs. For information about specifying fixed intervals in the API, see the [Cron expression reference]({{site.url}}{{site.baseurl}}/monitoring-plugins/alerting/cron/). +`schedule` | Object | The schedule that determines how often the detector runs. For information about specifying fixed intervals in the API, see [Cron expressions]({{site.url}}{{site.baseurl}}/api-reference/cron-expressions/). `schedule.period` | Object | Details for the frequency of the schedule. `schedule.period.interval` | Integer | The interval at which the detector runs. `schedule.period.unit` | String | The interval's unit of time. `inputs` | Object | Detector inputs. -`inputs.detector_input` | Array | An array that contains the index and definition used to create the detector. Currently, only one log data source is allowed for the detector. +`inputs.detector_input` | Array | An array that contains the index and definition used to create the detector. Only one log data source is allowed for the detector. `inputs.detector_input.description` | String | Description of the detector. Optional. `inputs.detector_input.custom_rules` | Array | Detector inputs for custom rules. At least one rule must be specified for a detector. Optional if pre-packaged rules are specified. `inputs.detector_input.custom_rules.id` | String | A valid rule ID for the custom rule generated by the user. Valid rules are formatted as a globally, or, universally unique identifier (UUID) See [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier) for more information. -`inputs.detector_input.indices` | Array | The log data source used for the detector, which can be either an index name or index pattern. Currently, only one entry is supported with plans to support multiple indexes in a future release. Required. +`inputs.detector_input.indices` | Array | The log data source used for the detector, which can be either an index name or index pattern. Only one entry is supported. Required. `inputs.detector_input.pre_packaged_rules` | Array | Detector inputs for pre-packaged rules (as opposed to custom rules). At least one rule must be specified for a detector. Optional if custom rules are specified. -`inputs.detector_input.pre_packaged_rules.id` | String | The rule ID for pre-packaged rules. See [Search Pre-Packaged Rules]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/rule-api/#search-pre-packaged-rules) for information on how to use the API to search for rules and obtain rule IDs in results. +`inputs.detector_input.pre_packaged_rules.id` | String | The rule ID for pre-packaged rules. See [Search Pre-Packaged Rules]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/rule-api/#search-pre-packaged-rules) for information about using the API to search for rules and obtain rule IDs in results. `triggers` | Array | Trigger settings for alerts. `triggers.ids` | Array | A list of rule IDs that become part of the trigger condition. `triggers.tags` | Array | Tags are specified in a security rule. Tags can then be selected and applied to the alert trigger to focus the trigger conditions for alerts. See an example of how tags are used in a Sigma rule in Sigma's [Rule Creation Guide](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#tags). `triggers.id` | String | The unique ID for the trigger. `triggers.sev_levels` | Array | Sigma rule severity levels: `informational`; `low`; `medium`; `high`; `criticial`. See [Level](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#level) in the Sigma Rule Creation Guide. -`triggers.name` | String | The name of the trigger. Name should only consist of upper and lowercase letters, numbers 0-9, hyphens, spaces, and underscores. Use between 5 and 50 characters. Required. +`triggers.name` | String | The name of the trigger. Name should only consist of upper and lowercase letters, numbers 0--9, hyphens, spaces, and underscores. Use 5--50 characters. Required. `triggers.severity` | Integer | Severity level for the trigger expressed as an integer: 1 = highest; 2 = high; 3 = medium; 4 = low; 5 = lowest. Trigger severity is part of the alert definition. `triggers.actions` | Object | Actions send notifications when trigger conditions are met. Optional, as a notification message is not required as part of an alert. `triggers.actions.id` | String | Unique ID for the action. User generated. @@ -52,7 +52,7 @@ Field | Type | Description `triggers.actions.subject_template` | Object | Contains the information for the subject field of the notification message. Optional. `triggers.actions.subject_template.source` | String | The subject for the notification message. `triggers.actions.subject_template.lang` | String | The scripting language used to define the subject. Must be Mustache. See the [Mustache Manual](https://mustache.github.io/mustache.5.html) for more information about templates. -`triggers.actions.name` | String | Name for the trigger alert. Name should only consist of upper and lowercase letters, numbers 0-9, hyphens, spaces, and underscores. Use between 5 and 50 characters. +`triggers.actions.name` | String | Name for the trigger alert. Name should only consist of upper and lowercase letters, numbers 0--9, hyphens, spaces, and underscores. Use 5--50 characters. `triggers.actions.message_template` | String | Contains the information for the body of the notification message. Optional. `triggers.actions.message_template.source` | String | The body of the notification message. `triggers.actions.message_template.lang` | String | The scripting language used to define the message. Must be `Mustache`. @@ -216,31 +216,31 @@ POST _plugins/_security_analytics/detectors ``` --- -## Update Detector API +## Update detector -The Update Detector API can be used to update a detector definition. It requires the detector ID to specify the detector. +Updates a detector definition. Requires the detector ID to specify the detector. ```json -PUT /_plugins/_security_analytics/detectors/<detector_Id> +PUT /_plugins/_security_analytics/detectors/{detector_Id} ``` -### Request fields +### Request body fields You can specify the following fields when updating a detector. Field | Type | Description :--- | :--- |:--- | `detector_type` | String | The log type that defines the detector. Options are `linux`, `network` ,`windows`, `ad_ldap`, `apache_access`, `cloudtrail`, `dns`, and `s3`. -`name` | String | The name of the detector. Name should only consist of upper and lowercase letters, numbers 0-9, hyphens, spaces, and underscores. Use between 5 and 50 characters. Required. +`name` | String | The name of the detector. Name should only consist of upper and lowercase letters, numbers 0--9, hyphens, spaces, and underscores. Use 5--50 characters. Required. `enabled` | Boolean | Sets the detector as either Active (true) or Inactive (false). `schedule.period.interval` | Integer | The interval at which the detector runs. `schedule.period.unit` | String | The interval's unit of time. `inputs.input.description` | String | Description of the detector. -`inputs.input.indices` | Array | The log data source used for the detector. Only one source is allowed at this time. +`inputs.input.indices` | Array | The log data source used for the detector. Only one source is allowed. `inputs.input.rules.id` | Array | A list of security rules for the detector definition. `triggers.sev_levels` | Array | Sigma rule severity levels: `informational`; `low`; `medium`; `high`; `criticial`. See [Level](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#level) in the Sigma Rule Creation Guide. `triggers.tags` | Array | Tags are specified in a security rule. Tags can then be selected and applied to the alert trigger to focus the trigger conditions for alerts. See an example of how tags are used in a Sigma rule in Sigma's [Rule Creation Guide](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#tags). -`triggers.actions` | Object | Actions send notifications when trigger conditions are met. See trigger actions for [Create Detector API]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/detector-api/#create-detector-api). +`triggers.actions` | Object | Actions send notifications when trigger conditions are met. See trigger actions for [Create detector]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/detector-api/#create-detector). ### Example request @@ -332,7 +332,7 @@ PUT /_plugins/_security_analytics/detectors/J1RX1IMByX0LvTiGTddR } ``` -#### Response fields +#### Response body fields Field | Type | Description :--- | :--- |:--- | @@ -341,11 +341,11 @@ Field | Type | Description `detector.enabled_time` | String | Date and time when the detector was last enabled. --- -## Delete Detector API +## Delete detector -This API uses the detector ID to specify and delete a detector. +Deletes a detector using the detector ID. -### Path and HTTP methods +### Endpoints ```json DELETE /_plugins/_security_analytics/detectors/IJAXz4QBrmVplM4JYxx_ @@ -368,11 +368,11 @@ DELETE /_plugins/_security_analytics/detectors/<detector Id> ``` --- -## Get Detector API +## Get detector -The Get Detector API retrieves the detector details. Use the detector ID in the call to fetch detector details. +Retrieves detector details using the detector ID. -### Path and HTTP methods +### Endpoints ```json GET /_plugins/_security_analytics/detectors/x-dwFIYBT6_n8WeuQjo4 @@ -424,11 +424,11 @@ GET /_plugins/_security_analytics/detectors/<detector Id> ``` --- -## Search Detector API +## Search detector -The Search Detector API searches for detector matches by detector ID, detector name, or detector type. +Searches for detector matches by detector ID, detector name, or detector type. -### Request fields +### Request body fields Field | Type | Description :--- | :--- |:--- | diff --git a/_security-analytics/api-tools/index.md b/_security-analytics/api-tools/index.md index 8209756e..c656732a 100644 --- a/_security-analytics/api-tools/index.md +++ b/_security-analytics/api-tools/index.md @@ -1,6 +1,6 @@ --- layout: default -title: API tools +title: Security Analytics APIs nav_order: 30 has_children: true has_toc: false @@ -8,7 +8,7 @@ redirect_from: - /security-analytics/api-tools/ --- -# API tools +# Security Analytics APIs Security Analytics includes a number of APIs to help administrators maintain and update an implementation. The APIs often mimic the same controls available for setting up Security Analytics in OpenSearch Dashboards, and they provide another option for administering the plugin. diff --git a/_security-analytics/api-tools/log-type-api.md b/_security-analytics/api-tools/log-type-api.md index ed8c0fba..a07cb540 100644 --- a/_security-analytics/api-tools/log-type-api.md +++ b/_security-analytics/api-tools/log-type-api.md @@ -1,7 +1,7 @@ --- layout: default title: Log type APIs -parent: API tools +parent: Security Analytics APIs nav_order: 56 --- @@ -170,7 +170,7 @@ POST /_plugins/_security_analytics/logtype/_search This API allows you to update existing custom log types. Use the log type's ID in the route to specify the log type, as shown in the following example: ```json -PUT /_plugins/_security_analytics/logtype/<log_type_id> +PUT /_plugins/_security_analytics/logtype/{log_type_id} ``` @@ -210,7 +210,7 @@ PUT /_plugins/_security_analytics/logtype/m98uk4kBlb9cbROIpEj2 This API is used to delete a custom log type. Specify the log type's ID in the route to run the operation: ```json -DELETE /_plugins/_security_analytics/logtype/<log_type_id> +DELETE /_plugins/_security_analytics/logtype/{log_type_id} ``` diff --git a/_security-analytics/api-tools/mappings-api.md b/_security-analytics/api-tools/mappings-api.md index b1e8ab2c..68ca08c6 100644 --- a/_security-analytics/api-tools/mappings-api.md +++ b/_security-analytics/api-tools/mappings-api.md @@ -1,7 +1,7 @@ --- layout: default title: Mappings APIs -parent: API tools +parent: Security Analytics APIs nav_order: 45 --- @@ -10,11 +10,11 @@ nav_order: 45 The following APIs can be used for a number of tasks related to mappings, from creating to getting and updating mappings. --- -## Get Mappings View +## Get mappings view -This API returns a view of the fields contained in an index used as a log source. +Returns a view of the fields contained in an index used as a log source. -### Request fields +### Request body fields The following fields are used to get field mappings. @@ -76,7 +76,9 @@ GET /_plugins/_security_analytics/mappings/view ``` --- -## Create Mappings +## Create mappings + +Creates field alias mappings for a specified index. #### Example request @@ -107,9 +109,11 @@ POST /_plugins/_security_analytics/mappings ``` --- -## Get Mappings +## Get mappings -### Path options +Retrieves field alias mappings for a specified index. + +### Path parameters Field | Type | Description :--- | :--- |:--- @@ -143,7 +147,9 @@ GET /_plugins/_security_analytics/mappings?index_name=windows ``` --- -## Update Mappings +## Update mappings + +Updates the field alias mapping for a specified index. #### Example request diff --git a/_security-analytics/api-tools/rule-api.md b/_security-analytics/api-tools/rule-api.md index d9de875d..6cfddbdb 100644 --- a/_security-analytics/api-tools/rule-api.md +++ b/_security-analytics/api-tools/rule-api.md @@ -1,7 +1,7 @@ --- layout: default title: Rule APIs -parent: API tools +parent: Security Analytics APIs nav_order: 40 --- @@ -10,9 +10,9 @@ nav_order: 40 The following APIs can be used for a number of tasks related to rules, from searching for pre-packaged rules to creating and updating custom rules. --- -## Create Custom Rule +## Create custom rule -The Create Custom Rule API uses Sigma security rule formatting to create a custom rule. For information about how to write a rule in Sigma format, see information provided at [Sigma's GitHub repository](https://github.com/SigmaHQ/sigma). +Creates a custom rule using Sigma security rule formatting. For information about how to write a rule in Sigma format, see information provided at [Sigma's GitHub repository](https://github.com/SigmaHQ/sigma). ```json POST /_plugins/_security_analytics/rules?category=windows @@ -111,7 +111,7 @@ falsepositives: "reason": "{\"error\":\"Sigma rule must have a log source\",\"error\":\"Sigma rule must have a detection definitions\"}", "caused_by": { "type": "exception", - "reason": "java.util.Arrays$ArrayList: {\"error\":\"Sigma rule must have a log source\",\"error\":\"Sigma rule must have a detection definitions\"}" + "reason": "{\"error\":\"Sigma rule must have a log source\",\"error\":\"Sigma rule must have a detection definitions\"}" } }, "status": 400 @@ -119,7 +119,9 @@ falsepositives: ``` --- -## Update Custom Rule (not forced) +## Update custom rule (not forced) + +Updates a custom rule. If the rule is actively used by detectors, the update is rejected unless the `forced` flag is set to `true`. ### Example request @@ -180,7 +182,9 @@ falsepositives: ``` --- -## Update Custom Rule (forced) +## Update custom rule (forced) + +Forces an update to a custom rule, even if it is actively used by detectors. ### Example request @@ -260,7 +264,9 @@ falsepositives: ``` --- -## Search Pre-Packaged Rules +## Search pre-packaged rules + +Searches for pre-packaged rules by category or other criteria. ### Example request @@ -355,7 +361,9 @@ POST /_plugins/_security_analytics/rules/_search?pre_packaged=true ``` --- -## Search Custom Rules +## Search custom rules + +Searches for custom rules by category or other criteria. ### Example request @@ -452,7 +460,9 @@ Body: ``` --- -## Delete Custom Rule (not forced) +## Delete custom rule (not forced) + +Deletes a custom rule. If the rule is actively used by detectors, the deletion is rejected unless the `forced` flag is set to `true`. ### Example request @@ -483,7 +493,9 @@ DELETE /_plugins/_security_analytics/rules/ZaFv1IMBdLpXWBiBa1XI ``` --- -## Delete Custom Rule (forced) +## Delete custom rule (forced) + +Forces deletion of a custom rule, even if it is actively used by detectors. ### Example request diff --git a/_security-analytics/index.md b/_security-analytics/index.md index c4bdae97..81e00768 100644 --- a/_security-analytics/index.md +++ b/_security-analytics/index.md @@ -14,7 +14,9 @@ redirect_from: # About Security Analytics -Security Analytics is a security information and event management (SIEM) solution for OpenSearch, designed to investigate, detect, analyze, and respond to security threats that can jeopardize the success of businesses and organizations and their online operations. These threats include the potential exposure of confidential data, cyber attacks, and other adverse security events. Security Analytics provides an out-of-the-box solution that installs automatically with any OpenSearch distribution. It includes the tools and features necessary for defining detection parameters, generating alerts, and responding effectively to potential threats. +Security Analytics is a security information and event management (SIEM) solution for OpenSearch. It analyzes the log data you ingest from your hosts, network devices, and cloud services, matches that data against threat detection rules, and alerts you to intrusions, data exposure, and other adverse security events in those systems. Security Analytics is available with any OpenSearch distribution and includes the tools and features necessary for defining detection parameters, generating alerts, and responding effectively to potential threats. + +To control who can access an OpenSearch cluster and the data in it, see [Security in OpenSearch]({{site.url}}{{site.baseurl}}/security/). ### Resources and information @@ -39,7 +41,7 @@ For information about configuring detectors, see [Creating detectors]({{site.url ### Log types -Log types provide the data used to evaluate events occurring in a system. OpenSearch supports several types of logs and provides out-of-the-box mappings for the most common log sources. See [Supported log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/) for a list of log types currently supported by Security Analytics. +[Log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/) provide the data used to evaluate events occurring in a system. OpenSearch supports several types of logs and provides out-of-the-box mappings for the most common log sources. Log types are specified during the creation of detectors, including steps for mapping log fields to the detector. Security Analytics also automatically selects an appropriate set of rules based on a specific log type and populates them for the detector. diff --git a/_security-analytics/log-types-reference/ad-ldap.md b/_security-analytics/log-types-reference/ad-ldap.md new file mode 100644 index 00000000..625eeac8 --- /dev/null +++ b/_security-analytics/log-types-reference/ad-ldap.md @@ -0,0 +1,114 @@ +--- +layout: default +title: AD LDAP +parent: Supported log types +nav_order: 20 +--- + +# AD LDAP log type + +The `ad_ldap` log type tracks Active Directory logs, such as: + +- Lightweight Directory Access Protocol (LDAP) queries. +- Errors from the LDAP server. +- Timeout events. +- Unsecured LDAP binds. + +The following code snippet contains all `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"TargetUserName", + "ecs":"azure.signinlogs.properties.user_id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"Category", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"OperationName", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ModifiedProperties_NewValue", + "ecs":"modified_properties.new_value" + }, + { + "raw_field":"ResourceProviderValue", + "ecs":"azure.resource.provider" + }, + { + "raw_field":"conditionalAccessStatus", + "ecs":"azure.signinlogs.properties.conditional_access_status" + }, + { + "raw_field":"SearchFilter", + "ecs":"SearchFilter" + }, + { + "raw_field":"Operation", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResultType", + "ecs":"azure.platformlogs.result_type" + }, + { + "raw_field":"DeviceDetail_isCompliant", + "ecs":"azure.signinlogs.properties.device_detail.is_compliant" + }, + { + "raw_field":"ResourceDisplayName", + "ecs":"resource_display_name" + }, + { + "raw_field":"AuthenticationRequirement", + "ecs":"azure.signinlogs.properties.authentication_requirement" + }, + { + "raw_field":"TargetResources", + "ecs":"target_resources" + }, + { + "raw_field":"Workload", + "ecs":"workload" + }, + { + "raw_field":"DeviceDetail.deviceId", + "ecs":"azure.signinlogs.properties.device_detail.device_id" + }, + { + "raw_field":"OperationNameValue", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResourceId", + "ecs":"azure.signinlogs.properties.resource_id" + }, + { + "raw_field":"ResultDescription", + "ecs":"azure.signinlogs.result_description" + }, + { + "raw_field":"EventID", + "ecs":"EventID" + }, + { + "raw_field":"NetworkLocationDetails", + "ecs":"azure.signinlogs.properties.network_location_details" + }, + { + "raw_field":"CategoryValue", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"ActivityDisplayName", + "ecs":"azure.auditlogs.properties.activity_display_name" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/apache-access.md b/_security-analytics/log-types-reference/apache-access.md new file mode 100644 index 00000000..4cf73321 --- /dev/null +++ b/_security-analytics/log-types-reference/apache-access.md @@ -0,0 +1,10 @@ +--- +layout: default +title: Apache Access +parent: Supported log types +nav_order: 25 +--- + +# Apache Access log type + +The `apache_access` log type records data for all requests processed by Apache HTTP servers. It contains no `raw_field` or `ecs` mappings. \ No newline at end of file diff --git a/_security-analytics/log-types-reference/azure.md b/_security-analytics/log-types-reference/azure.md new file mode 100644 index 00000000..a0075977 --- /dev/null +++ b/_security-analytics/log-types-reference/azure.md @@ -0,0 +1,225 @@ +--- +layout: default +title: Azure +parent: Supported log types +nav_order: 29 +--- + +# Azure log type + +The `azure` log type monitors log data for cloud applications managed by Azure Cloud Services. + +The following code snippet contains all `raw_field` and `ecs` mappings for this log type: + +```json +"mappings": [ + { + "raw_field":"Resultdescription", + "ecs":"azure.signinlogs.result_description" + }, + { + "raw_field":"eventSource", + "ecs":"eventSource" + }, + { + "raw_field":"eventName", + "ecs":"eventName" + }, + { + "raw_field":"Status", + "ecs":"azure.platformlogs.status" + }, + { + "raw_field":"LoggedByService", + "ecs":"azure.auditlogs.properties.logged_by_service" + }, + { + "raw_field":"properties_message", + "ecs":"properties_message" + }, + { + "raw_field":"status", + "ecs":"azure.platformlogs.status" + }, + { + "raw_field":"TargetUserName", + "ecs":"azure.signinlogs.properties.user_id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"Category", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"OperationName", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ModifiedProperties_NewValue", + "ecs":"modified_properties.new_value" + }, + { + "raw_field":"ResourceProviderValue", + "ecs":"azure.resource.provider" + }, + { + "raw_field":"conditionalAccessStatus", + "ecs":"azure.signinlogs.properties.conditional_access_status" + }, + { + "raw_field":"SearchFilter", + "ecs":"search_filter" + }, + { + "raw_field":"Operation", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResultType", + "ecs":"azure.platformlogs.result_type" + }, + { + "raw_field":"DeviceDetail_isCompliant", + "ecs":"azure.signinlogs.properties.device_detail.is_compliant" + }, + { + "raw_field":"ResourceDisplayName", + "ecs":"resource_display_name" + }, + { + "raw_field":"AuthenticationRequirement", + "ecs":"azure.signinlogs.properties.authentication_requirement" + }, + { + "raw_field":"TargetResources", + "ecs":"target_resources" + }, + { + "raw_field":"Workload", + "ecs":"Workload" + }, + { + "raw_field":"DeviceDetail_deviceId", + "ecs":"azure.signinlogs.properties.device_detail.device_id" + }, + { + "raw_field":"OperationNameValue", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResourceId", + "ecs":"azure.signinlogs.properties.resource_id" + }, + { + "raw_field":"ResultDescription", + "ecs":"azure.signinlogs.result_description" + }, + { + "raw_field":"EventID", + "ecs":"EventID" + }, + { + "raw_field":"NetworkLocationDetails", + "ecs":"azure.signinlogs.properties.network_location_details" + }, + { + "raw_field":"CategoryValue", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"ActivityDisplayName", + "ecs":"azure.auditlogs.properties.activity_display_name" + }, + { + "raw_field":"Initiatedby", + "ecs":"azure.activitylogs.identity.claims_initiated_by_user.name" + }, + { + "raw_field":"Count", + "ecs":"Count" + }, + { + "raw_field":"ResourceTenantId", + "ecs":"azure.signinlogs.properties.resource_tenant_id" + }, + { + "raw_field":"failure_status_reason", + "ecs":"failure_status_reason" + }, + { + "raw_field":"AppId", + "ecs":"azure.signinlogs.properties.app_id" + }, + { + "raw_field":"properties.message", + "ecs":"properties.message" + }, + { + "raw_field":"ClientApp", + "ecs":"azure.signinlogs.properties.client_app_used" + }, + { + "raw_field":"ActivityDetails", + "ecs":"ActivityDetails" + }, + { + "raw_field":"Target", + "ecs":"Target" + }, + { + "raw_field":"DeviceDetail.trusttype", + "ecs":"azure.signinlogs.properties.device_detail.trust_type" + }, + { + "raw_field":"HomeTenantId", + "ecs":"azure.signinlogs.properties.home_tenant_id" + }, + { + "raw_field":"ConsentContext.IsAdminConsent", + "ecs":"ConsentContext.IsAdminConsent" + }, + { + "raw_field":"InitiatedBy", + "ecs":"InitiatedBy" + }, + { + "raw_field":"ActivityType", + "ecs":"azure.auditlogs.properties.activity_display_name" + }, + { + "raw_field":"operationName", + "ecs":"azure.activitylogs.operation_name" + }, + { + "raw_field":"ModifiedProperties{}.NewValue", + "ecs":"modified_properties.new_value" + }, + { + "raw_field":"userAgent", + "ecs":"user_agent.name" + }, + { + "raw_field":"RiskState", + "ecs":"azure.signinlogs.properties.risk_state" + }, + { + "raw_field":"Username", + "ecs":"azure.activitylogs.identity.claims_initiated_by_user.name" + }, + { + "raw_field":"DeviceDetail.deviceId", + "ecs":"azure.signinlogs.properties.device_detail.device_id" + }, + { + "raw_field":"DeviceDetail.isCompliant", + "ecs":"azure.signinlogs.properties.device_detail.is_compliant" + }, + { + "raw_field":"Location", + "ecs":"azure.signinlogs.properties.network_location_details" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/cloudtrail.md b/_security-analytics/log-types-reference/cloudtrail.md new file mode 100644 index 00000000..573fa510 --- /dev/null +++ b/_security-analytics/log-types-reference/cloudtrail.md @@ -0,0 +1,232 @@ +--- +layout: default +title: AWS CloudTrail +parent: Supported log types +nav_order: 28 +--- + +# AWS CloudTrail log type + +The `cloudtrail` log type monitors events from the [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) accounts. OpenSearch can ingest AWS CloudTrail log data from both [Amazon Simple Storage Service](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) (Amazon S3) accounts and [Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) accounts. + +The following code snippet contains all the `raw_field`, `ecs`, and `ocsf` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"eventName", + "ecs":"aws.cloudtrail.event_name", + "ocsf": "api.operation" + }, + { + "raw_field":"eventSource", + "ecs":"aws.cloudtrail.event_source", + "ocsf": "api.service.name" + }, + { + "raw_field":"eventVersion", + "ecs":"aws.cloudtrail.event_version", + "ocsf": "metadata.product.version" + }, + { + "raw_field":"eventID", + "ecs":"aws.cloudtrail.event_id", + "ocsf": "metadata.uid" + }, + { + "raw_field":"eventType", + "ecs":"aws.cloudtrail.event_type", + "ocsf": "unmapped.eventType" + }, + { + "raw_field":"eventCategory", + "ecs":"aws.cloudtrail.event_category", + "ocsf": "metadata.product.feature.name" + }, + { + "raw_field":"errorMessage", + "ecs":"aws.cloudtrail.error_message", + "ocsf": "api.response.message" + }, + { + "raw_field":"errorCode", + "ecs":"aws.cloudtrail.error_code", + "ocsf": "api.response.error" + }, + { + "raw_field":"apiVersion", + "ecs":"aws.cloudtrail.api_version", + "ocsf": "api.version" + }, + { + "raw_field":"awsRegion", + "ecs":"aws.cloudtrail.aws_region", + "ocsf": "cloud.region" + }, + { + "raw_field":"additionalEventData.LoginTo", + "ecs":"aws.cloudtrail.additional_event_data.loginTo", + "ocsf": "dst_endpoint.svc_name" + }, + { + "raw_field":"additionalEventData.MFAUsed", + "ecs":"aws.cloudtrail.additional_event_data.mfaUsed", + "ocsf": "mfa" + }, + { + "raw_field":"responseElements", + "ecs":"aws.cloudtrail.response_elements.text", + "ocsf": "unmapped.responseElements" + }, + { + "raw_field":"requestID", + "ecs":"aws.cloudtrail.request_id", + "ocsf": "api.request.uid" + }, + { + "raw_field":"sourceIPAddress", + "ecs":"aws.cloudtrail.source_ip_address", + "ocsf": "src_endpoint.ip" + }, + { + "raw_field":"userAgent", + "ecs":"aws.cloudtrail.user_agent", + "ocsf": "http_request.user_agent" + }, + { + "raw_field":"vpcEndpointId", + "ecs":"aws.cloudtrail.vpc_endpoint_id", + "ocsf": "src_endpoint.uid" + }, + { + "raw_field":"responseElements.pendingModifiedValues.masterUserPassword", + "ecs":"aws.cloudtrail.response_elements.pending_modified_values.master_user_password", + "ocsf": "unmapped.responseElements.pendingModifiedValues.masterUserPassword" + }, + { + "raw_field":"responseElements.publiclyAccessible", + "ecs":"aws.cloudtrail.response_elements.publicly_accessible", + "ocsf": "unmapped.responseElements.publiclyAccessible" + }, + { + "raw_field":"responseElements.ConsoleLogin", + "ecs":"aws.cloudtrail.response_elements.publicly_accessible", + "ocsf": "status_id" + }, + { + "raw_field":"requestParameters.arn", + "ecs":"aws.cloudtrail.request_parameters.arn", + "ocsf": "unmapped.requestParameters.arn" + }, + { + "raw_field":"requestParameters.attribute", + "ecs":"aws.cloudtrail.request_parameters.attribute", + "ocsf": "unmapped.requestParameters.attribute" + }, + { + "raw_field":"requestParameters.userName", + "ecs":"aws.cloudtrail.request_parameters.username", + "ocsf": "unmapped.requestParameters.userName" + }, + { + "raw_field":"requestParameters.roleArn", + "ecs":"aws.cloudtrail.request_parameters.roleArn", + "ocsf": "user.uuid" + }, + { + "raw_field":"requestParameters.roleSessionName", + "ecs":"aws.cloudtrail.request_parameters.roleSessionName", + "ocsf": "user.name" + }, + { + "raw_field":"requestParameters.containerDefinitions.command", + "ecs":"aws.cloudtrail.request_parameters.container_definitions.command", + "ocsf": "unmapped.requestParameters.containerDefinitions.command" + }, + { + "raw_field":"userIdentity.type", + "ecs":"aws.cloudtrail.user_identity.type", + "ocsf": "actor.user.type" + }, + { + "raw_field":"userIdentity.principalId", + "ecs":"aws.cloudtrail.user_identity.principalId", + "ocsf": "actor.user.uid" + }, + { + "raw_field":"userIdentity.arn", + "ecs":"aws.cloudtrail.user_identity.arn", + "ocsf": "actor.user.uuid" + }, + { + "raw_field":"userIdentity.accountId", + "ecs":"aws.cloudtrail.user_identity.accountId", + "ocsf": "actor.user.account_uid" + }, + { + "raw_field":"userIdentity.accessKeyId", + "ecs":"aws.cloudtrail.user_identity.accessKeyId", + "ocsf": "actor.user.credential_uid" + }, + { + "raw_field":"userIdentity.identityProvider", + "ecs":"aws.cloudtrail.user_identity.identityProvider", + "ocsf": "actor.idp.name" + }, + { + "raw_field":"userIdentity.userName", + "ecs":"aws.cloudtrail.user_identity.userName", + "ocsf": "actor.user.name" + }, + { + "raw_field":"userIdentity.invokedBy", + "ecs":"aws.cloudtrail.user_identity.invokedBy", + "ocsf": "actor.invoked_by" + }, + { + "raw_field":"userIdentity.sessionContext.sessionIssuer.type", + "ecs":"aws.cloudtrail.user_identity.session_context.session_issuer.type", + "ocsf": "unmapped.userIdentity.sessionContext.sessionIssuer.type" + }, + { + "raw_field":"userIdentity.sessionContext.sessionIssuer.arn", + "ecs":"aws.cloudtrail.user_identity.session_context.session_issuer.arn", + "ocsf": "actor.session.issuer" + }, + { + "raw_field":"userIdentity.sessionContext.attributes.creationDate", + "ecs":"aws.cloudtrail.user_identity.session_context.attributes.creationDate", + "ocsf": "actor.session.created_time" + }, + { + "raw_field":"userIdentity.sessionContext.attributes.mfaAuthenticated", + "ecs":"aws.cloudtrail.user_identity.session_context.attributes.mfaAuthenticated", + "ocsf": "actor.session.mfa" + }, + { + "raw_field":"userIdentity.webIdFederationData.federatedProvider", + "ecs":"aws.cloudtrail.user_identity.web_id_federation_data.federatedProvider", + "ocsf": "actor.idp.name" + }, + { + "raw_field":"resources[].ARN", + "ecs":"aws.cloudtrail.resources.ARN", + "ocsf": "resources[].uid" + }, + { + "raw_field":"resources[].accountId", + "ecs":"aws.cloudtrail.resources.account_uid", + "ocsf": "resources[].account_uid" + }, + { + "raw_field":"resources[].type", + "ecs":"aws.cloudtrail.resources.type", + "ocsf": "resources[].type" + }, + { + "raw_field":"eventTime", + "ecs":"timestamp", + "ocsf": "time" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/dns.md b/_security-analytics/log-types-reference/dns.md new file mode 100644 index 00000000..192d0dfb --- /dev/null +++ b/_security-analytics/log-types-reference/dns.md @@ -0,0 +1,127 @@ +--- +layout: default +title: DNS +parent: Supported log types +nav_order: 35 +--- + +# DNS log type + +The `dns` log type stores DNS activity. + +The following code snippet contains all the `raw_field`, `ecs`, and `ocsf` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"record_type", + "ecs":"dns.answers.type", + "ocsf": "unmapped.record_type" + }, + { + "raw_field":"answers[].Type", + "ecs":"aws.route53.answers.Type", + "ocsf": "answers[].type" + }, + { + "raw_field":"answers[].Rdata", + "ecs":"aws.route53.answers.Rdata", + "ocsf": "answers[].rdata" + }, + { + "raw_field":"answers[].Class", + "ecs":"aws.route53.answers.Class", + "ocsf": "answers[].class" + }, + { + "raw_field":"query", + "ecs":"dns.question.name", + "ocsf": "unmapped.query" + }, + { + "raw_field":"query_name", + "ecs":"aws.route53.query_name", + "ocsf": "query.hostname" + }, + { + "raw_field":"parent_domain", + "ecs":"dns.question.registered_domain", + "ocsf": "unmapped.parent_domain" + }, + { + "raw_field":"version", + "ecs":"aws.route53.version", + "ocsf": "metadata.product.version" + }, + { + "raw_field":"account_id", + "ecs":"aws.route53.account_id", + "ocsf": "cloud.account_uid" + }, + { + "raw_field":"region", + "ecs":"aws.route53.region", + "ocsf": "cloud.region" + }, + { + "raw_field":"vpc_id", + "ecs":"aws.route53.vpc_id", + "ocsf": "src_endpoint.vpc_uid" + }, + { + "raw_field":"query_timestamp", + "ecs":"aws.route53.query_timestamp", + "ocsf": "time" + }, + { + "raw_field":"query_class", + "ecs":"aws.route53.query_class", + "ocsf": "query.class" + }, + { + "raw_field":"query_type", + "ecs":"aws.route53.query_type", + "ocsf": "query.type" + }, + { + "raw_field":"srcaddr", + "ecs":"aws.route53.srcaddr", + "ocsf": "src_endpoint.ip" + }, + { + "raw_field":"srcport", + "ecs":"aws.route53.srcport", + "ocsf": "src_endpoint.port" + }, + { + "raw_field":"transport", + "ecs":"aws.route53.transport", + "ocsf": "connection_info.protocol_name" + }, + { + "raw_field":"srcids.instance", + "ecs":"aws.route53.srcids.instance", + "ocsf": "src_endpoint.instance_uid" + }, + { + "raw_field":"srcids.resolver_endpoint", + "ecs":"aws.route53.srcids.resolver_endpoint", + "ocsf": "dst_endpoint.instance_uid" + }, + { + "raw_field":"srcids.resolver_network_interface", + "ecs":"aws.route53.srcids.resolver_network_interface", + "ocsf": "dst_endpoint.interface_uid" + }, + { + "raw_field":"firewall_rule_action", + "ecs":"aws.route53.srcids.firewall_rule_action", + "ocsf": "disposition_id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp", + "ocsf": "unmapped.creationTime" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/github.md b/_security-analytics/log-types-reference/github.md new file mode 100644 index 00000000..ad47c30e --- /dev/null +++ b/_security-analytics/log-types-reference/github.md @@ -0,0 +1,21 @@ +--- +layout: default +title: GitHub +parent: Supported log types +nav_order: 40 +--- + +# GitHub log type + +The `github` log type monitors workflows created by [GitHub Actions](https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions). + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"action", + "ecs":"github.action" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/gworkspace.md b/_security-analytics/log-types-reference/gworkspace.md new file mode 100644 index 00000000..7e145456 --- /dev/null +++ b/_security-analytics/log-types-reference/gworkspace.md @@ -0,0 +1,33 @@ +--- +layout: default +title: Google Workspace +parent: Supported log types +nav_order: 45 +--- + +# Google Workspace log type + +The `gworkspace` log type monitors Google Workspace log entries, such as the following: + +- Admin actions +- Group and group membership actions +- Events related to logins + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"eventSource", + "ecs":"google_workspace.admin.service.name" + }, + { + "raw_field":"eventName", + "ecs":"google_workspace.event.name" + }, + { + "raw_field":"new_value", + "ecs":"google_workspace.admin.new_value" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/index.md b/_security-analytics/log-types-reference/index.md new file mode 100644 index 00000000..d56e16fb --- /dev/null +++ b/_security-analytics/log-types-reference/index.md @@ -0,0 +1,18 @@ +--- +layout: default +title: Supported log types +has_children: yes +nav_order: 16 +redirect_from: + - /security-analytics/sec-analytics-config/log-types/ + - /security-analytics/log-types-reference/ +--- + +# Supported log types + +Logs contain raw data about events that happen throughout a system and within its separate parts. This reference describes the standard log types supported by Security Analytics and the automatic mappings they contain. + +For more information about field mappings, refer to the [About field mappings]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types#about-field-mappings) section in the [Working with log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/) documentation. + +For more information about log types and detectors, refer to the [Creating detectors]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/detectors-config/) documentation. + diff --git a/_security-analytics/log-types-reference/linux.md b/_security-analytics/log-types-reference/linux.md new file mode 100644 index 00000000..5c32c253 --- /dev/null +++ b/_security-analytics/log-types-reference/linux.md @@ -0,0 +1,73 @@ +--- +layout: default +title: Linux +parent: Supported log types +nav_order: 50 +--- + +# Linux log type + +The `linux` log type records Linux syslog events. + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"name", + "ecs":"user.filesystem.name" + }, + { + "raw_field":"a0", + "ecs":"auditd.log.a0" + }, + { + "raw_field":"comm", + "ecs":"auditd.log.comm" + }, + { + "raw_field":"exe", + "ecs":"auditd.log.exe" + }, + { + "raw_field":"uid", + "ecs":"auditd.log.uid" + }, + { + "raw_field":"USER", + "ecs":"system.auth.user" + }, + { + "raw_field":"User", + "ecs":"system.auth.user" + }, + { + "raw_field":"Image", + "ecs":"process.exe" + }, + { + "raw_field":"DestinationHostname", + "ecs":"rsa.web.remote_domain" + }, + { + "raw_field":"CommandLine", + "ecs":"process.command_line" + }, + { + "raw_field":"ParentImage", + "ecs":"process.parent.executable" + }, + { + "raw_field":"CurrentDirectory", + "ecs":"process.working_directory" + }, + { + "raw_field":"LogonId", + "ecs":"process.real_user.id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/m365.md b/_security-analytics/log-types-reference/m365.md new file mode 100644 index 00000000..5d616016 --- /dev/null +++ b/_security-analytics/log-types-reference/m365.md @@ -0,0 +1,39 @@ +--- +layout: default +title: Microsoft 365 +parent: Supported log types +nav_order: 55 +--- + +# Microsoft 365 log type + +The `m365` log type collects a range of data for Microsoft 365, such as the following: + +- Records from call details +- Performance data +- SQL Server events +- Security events +- Access control activity + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json +"mappings": [ + { + "raw_field":"eventSource", + "ecs":"rsa.misc.event_source" + }, + { + "raw_field":"eventName", + "ecs":"rsa.misc.event_desc" + }, + { + "raw_field":"status", + "ecs":"rsa.misc.status" + }, + { + "raw_field":"Payload", + "ecs":"rsa.misc.payload_dst" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/netflow.md b/_security-analytics/log-types-reference/netflow.md new file mode 100644 index 00000000..e738aa8c --- /dev/null +++ b/_security-analytics/log-types-reference/netflow.md @@ -0,0 +1,45 @@ +--- +layout: default +title: NetFlow +parent: Supported log types +nav_order: 60 +--- + +# NetFlow log type + +The `netflow` log type records NetFlow events used during integration testing. + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json +"mappings": [ + { + "raw_field":"netflow.source_ipv4_address", + "ecs":"source.ip" + }, + { + "raw_field":"netflow.source_transport_port", + "ecs":"source.port" + }, + { + "raw_field":"netflow.destination_ipv4_address", + "ecs":"destination.ip" + }, + { + "raw_field":"netflow.destination_transport_port", + "ecs":"destination.port" + }, + { + "raw_field":"http.request.method", + "ecs":"http.request.method" + }, + { + "raw_field":"http.response.status_code", + "ecs":"http.response.status_code" + }, + { + "raw_field":"timestamp", + "ecs":"timestamp" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/network.md b/_security-analytics/log-types-reference/network.md new file mode 100644 index 00000000..29289967 --- /dev/null +++ b/_security-analytics/log-types-reference/network.md @@ -0,0 +1,145 @@ +--- +layout: default +title: Network +parent: Supported log types +nav_order: 70 +--- + +# Network log type + +The `network` log type records events that happen in a system's network, such as login attempts and application events. + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"action", + "ecs":"netflow.firewall_event" + }, + { + "raw_field":"certificate.serial", + "ecs":"zeek.x509.certificate.serial" + }, + { + "raw_field":"name", + "ecs":"zeek.smb_files.name" + }, + { + "raw_field":"path", + "ecs":"zeek.smb_files.path" + }, + { + "raw_field":"dst_port", + "ecs":"destination.port" + }, + { + "raw_field":"qtype_name", + "ecs":"zeek.dns.qtype_name" + }, + { + "raw_field":"operation", + "ecs":"zeek.dce_rpc.operation" + }, + { + "raw_field":"endpoint", + "ecs":"zeek.dce_rpc.endpoint" + }, + { + "raw_field":"zeek.dce_rpc.endpoint", + "ecs":"zeek.dce_rpc.endpoint" + }, + { + "raw_field":"answers", + "ecs":"zeek.dns.answers" + }, + { + "raw_field":"query", + "ecs":"zeek.dns.query" + }, + { + "raw_field":"client_header_names", + "ecs":"zeek.http.client_header_names" + }, + { + "raw_field":"resp_mime_types", + "ecs":"zeek.http.resp_mime_types" + }, + { + "raw_field":"cipher", + "ecs":"zeek.kerberos.cipher" + }, + { + "raw_field":"request_type", + "ecs":"zeek.kerberos.request_type" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"method", + "ecs":"http.request.method" + }, + { + "raw_field":"id.resp_p", + "ecs":"id.resp_p" + }, + { + "raw_field":"blocked", + "ecs":"blocked-flag" + }, + { + "raw_field":"id.orig_h", + "ecs":"id.orig_h" + }, + { + "raw_field":"Z", + "ecs":"Z-flag" + }, + { + "raw_field":"id.resp_h", + "ecs":"id.resp_h" + }, + { + "raw_field":"uri", + "ecs":"url.path" + }, + { + "raw_field":"c-uri", + "ecs":"url.path" + }, + { + "raw_field":"c-useragent", + "ecs":"user_agent.name" + }, + { + "raw_field":"status_code", + "ecs":"http.response.status_code" + }, + { + "raw_field":"rejected", + "ecs":"rejected" + }, + { + "raw_field":"dst_ip", + "ecs":"destination.ip" + }, + { + "raw_field":"src_ip", + "ecs":"source.ip" + }, + { + "raw_field":"user_agent", + "ecs":"user_agent.name" + }, + { + "raw_field":"request_body_len", + "ecs":"http.request.body.bytes" + }, + { + "raw_field":"service", + "ecs":"service" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/okta.md b/_security-analytics/log-types-reference/okta.md new file mode 100644 index 00000000..ea540d1b --- /dev/null +++ b/_security-analytics/log-types-reference/okta.md @@ -0,0 +1,25 @@ +--- +layout: default +title: Okta +parent: Supported log types +nav_order: 80 +--- + +# Okta log type + +The `okta` log type records Okta events generated from a range of actions, such as downloading an export file, requesting application access, or revoking privileges. + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"eventtype", + "ecs":"okta.event_type" + }, + { + "raw_field":"displaymessage", + "ecs":"okta.display_message" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/other.md b/_security-analytics/log-types-reference/other.md new file mode 100644 index 00000000..acf23c10 --- /dev/null +++ b/_security-analytics/log-types-reference/other.md @@ -0,0 +1,40 @@ +--- +layout: default +title: Other log type mappings +parent: Supported log types +nav_order: 110 +--- + +# Other log type mappings + +Security Analytics supports field mappings that are not specific to a single service or system. These mapping types are separated into the following categories: + +- Application: Records application logs. +- Advanced Persistent Threat (APT): Records logs commonly associated with APT attacks. +- Compliance: Records logs related to compliance. +- macOS: Records event logs when using a Mac device to access a network. +- Proxy: Records logs related to proxy events. +- Web: Records logs related to network access from the web. + +Each log type contains the same field mappings, as shown in the following code snippet: + +```json + "mappings": [ + { + "raw_field":"record_type", + "ecs":"dns.answers.type" + }, + { + "raw_field":"query", + "ecs":"dns.question.name" + }, + { + "raw_field":"parent_domain", + "ecs":"dns.question.registered_domain" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/s3.md b/_security-analytics/log-types-reference/s3.md new file mode 100644 index 00000000..b1804660 --- /dev/null +++ b/_security-analytics/log-types-reference/s3.md @@ -0,0 +1,29 @@ +--- +layout: default +title: Amazon S3 +parent: Supported log types +nav_order: 24 +--- + +# Amazon S3 log type + +The `s3` log type tracks network requests for access to Amazon S3 buckets. + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"eventName", + "ecs":"aws.cloudtrail.event_name" + }, + { + "raw_field":"eventSource", + "ecs":"aws.cloudtrail.event_source" + }, + { + "raw_field":"eventTime", + "ecs":"timestamp" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/vpc.md b/_security-analytics/log-types-reference/vpc.md new file mode 100644 index 00000000..cd705422 --- /dev/null +++ b/_security-analytics/log-types-reference/vpc.md @@ -0,0 +1,145 @@ +--- +layout: default +title: VPC Flow +parent: Supported log types +nav_order: 90 +--- + +<!-- vale off --> +# VPC Flow log type +<!-- vale on --> + +The `vpcflow` log type records data about the IP traffic flowing to and from the network interfaces within a virtual private cloud (VPC). This data is stored using the [VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html) feature. + +The following code snippet contains all the `raw_field`, `ecs`, and `ocsf` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"version", + "ecs":"netflow.version", + "ocsf": "metadata.product.version" + }, + { + "raw_field":"account_id", + "ecs":"netflow.account_id", + "ocsf": "cloud.account_uid" + }, + { + "raw_field":"region", + "ecs":"netflow.region", + "ocsf": "cloud.region" + }, + { + "raw_field":"az_id", + "ecs":"netflow.az_id", + "ocsf": "cloud.zone" + }, + { + "raw_field":"srcport", + "ecs":"netflow.srcport", + "ocsf": "src_endpoint.port" + }, + { + "raw_field":"dstport", + "ecs":"netflow.dstport", + "ocsf": "dst_endpoint.port" + }, + { + "raw_field":"protocol", + "ecs":"netflow.protocol", + "ocsf": "connection_info.protocol_num" + }, + { + "raw_field":"packets", + "ecs":"netflow.packets", + "ocsf": "traffic.packets" + }, + { + "raw_field":"bytes", + "ecs":"netflow.bytes", + "ocsf": "traffic.bytes" + }, + { + "raw_field":"end", + "ecs":"netflow.end", + "ocsf": "end_time" + }, + { + "raw_field":"tcp_flags", + "ecs":"netflow.tcp_flags", + "ocsf": "connection_info.tcp_flags" + }, + { + "raw_field":"protocol_ver", + "ecs":"netflow.protocol_ver", + "ocsf": "connection_info.protocol_ver" + }, + { + "raw_field":"pkt_src_aws_service", + "ecs":"netflow.pkt_src_aws_service", + "ocsf": "src_endpoint.svc_name" + }, + { + "raw_field":"pkt_dst_aws_service", + "ecs":"netflow.pkt_dst_aws_service", + "ocsf": "dst_endpoint.svc_name" + }, + { + "raw_field":"log_status", + "ecs":"netflow.log_status", + "ocsf": "status_code" + }, + { + "raw_field":"action", + "ecs":"netflow.action", + "ocsf": "disposition_id" + }, + { + "raw_field":"traffic_path", + "ecs":"netflow.traffic_path", + "ocsf": "boundary_id" + }, + { + "raw_field":"flow_direction", + "ecs":"netflow.flow_direction", + "ocsf": "connection_info.direction_id" + }, + { + "raw_field":"dstaddr", + "ecs":"netflow.dstaddr", + "ocsf": "dst_endpoint.ip" + }, + { + "raw_field":"srcaddr", + "ecs":"netflow.srcaddr", + "ocsf": "src_endpoint.ip" + }, + { + "raw_field":"interface_id", + "ecs":"netflow.interface_id", + "ocsf": "dst_endpoint.interface_uid" + }, + { + "raw_field":"vpc_id", + "ecs":"netflow.vpc_id", + "ocsf": "dst_endpoint.vpc_uid" + }, + { + "raw_field":"instance_id", + "ecs":"netflow.instance_id", + "ocsf": "dst_endpoint.instance_uid" + }, + { + "raw_field":"subnet_id", + "ecs":"netflow.subnet_id", + "ocsf": "dst_endpoint.subnet_uid" + }, + { + "raw_field":"start", + "ecs":"timestamp", + "ocsf": "time" + } + ] +``` + diff --git a/_security-analytics/log-types-reference/waf.md b/_security-analytics/log-types-reference/waf.md new file mode 100644 index 00000000..c4bf5881 --- /dev/null +++ b/_security-analytics/log-types-reference/waf.md @@ -0,0 +1,65 @@ +--- +layout: default +title: WAF +parent: Supported log types +nav_order: 95 +--- + +# WAF log type + +The `waf` log type monitors web application firewall (WAF) logs. The role of a WAF is to monitor and filter HTTP traffic flowing between a web application and the internet. A WAF prevents common security attacks, such as cross-site scripting (XSS) and SQL injection (SQLi). + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings": [ + { + "raw_field":"cs-method", + "ecs":"waf.request.method" + }, + { + "raw_field":"httpRequest.httpMethod", + "ecs":"waf.request.method" + }, + { + "raw_field":"cs-uri-query", + "ecs":"waf.request.uri_query" + }, + { + "raw_field":"httpRequest.uri", + "ecs":"waf.request.uri_query" + }, + { + "raw_field":"httpRequest.args", + "ecs":"waf.request.uri_query" + }, + { + "raw_field":"cs-user-agent", + "ecs":"waf.request.headers.user_agent" + }, + { + "raw_field":"httpRequest.headers", + "ecs":"waf.request.headers" + }, + { + "raw_field":"sc-status", + "ecs":"waf.response.code" + }, + { + "raw_field":"responseCodeSent", + "ecs":"waf.response.code" + }, + { + "raw_field":"timestamp", + "ecs":"timestamp" + }, + { + "raw_field":"httpRequest.headers.value", + "ecs":"waf.request.headers.value" + }, + { + "raw_field":"httpRequest.headers.name", + "ecs":"waf.request.headers.name" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/log-types-reference/windows.md b/_security-analytics/log-types-reference/windows.md new file mode 100644 index 00000000..bc1d2c4e --- /dev/null +++ b/_security-analytics/log-types-reference/windows.md @@ -0,0 +1,845 @@ +--- +layout: default +title: Windows +parent: Supported log types +nav_order: 100 +--- + +# Windows log type + +The `windows` log type records events that happen in Windows applications, system services, and the Windows operating system. + +The following code snippet contains all the `raw_field` and `ecs` mappings for this log type: + +```json + "mappings":[ + { + "raw_field":"AccountName", + "ecs":"winlog.computerObject.name" + }, + { + "raw_field":"AuthenticationPackageName", + "ecs":"winlog.event_data.AuthenticationPackageName" + }, + { + "raw_field":"Channel", + "ecs":"winlog.channel" + }, + { + "raw_field":"Company", + "ecs":"winlog.event_data.Company" + }, + { + "raw_field":"ComputerName", + "ecs":"winlog.computer_name" + }, + { + "raw_field":"Description", + "ecs":"winlog.event_data.Description" + }, + { + "raw_field":"Details", + "ecs":"winlog.event_data.Detail" + }, + { + "raw_field":"Device", + "ecs":"winlog.event_data.Device" + }, + { + "raw_field":"FileName", + "ecs":"winlog.event_data.FileName" + }, + { + "raw_field":"FileVersion", + "ecs":"winlog.event_data.FileVersion" + }, + { + "raw_field":"IntegrityLevel", + "ecs":"winlog.event_data.IntegrityLevel" + }, + { + "raw_field":"IpAddress", + "ecs":"winlog.event_data.IpAddress" + }, + { + "raw_field":"KeyLength", + "ecs":"winlog.event_data.KeyLength" + }, + { + "raw_field":"Keywords", + "ecs":"winlog.keywords" + }, + { + "raw_field":"LogonId", + "ecs":"winlog.event_data.LogonId" + }, + { + "raw_field":"LogonProcessName", + "ecs":"winlog.event_data.LogonProcessName" + }, + { + "raw_field":"LogonType", + "ecs":"winlog.event_data.LogonType" + }, + { + "raw_field":"OriginalFilename", + "ecs":"winlog.event_data.OriginalFileName" + }, + { + "raw_field":"Path", + "ecs":"winlog.event_data.Path" + }, + { + "raw_field":"PrivilegeList", + "ecs":"winlog.event_data.PrivilegeList" + }, + { + "raw_field":"ProcessId", + "ecs":"winlog.event_data.ProcessId" + }, + { + "raw_field":"Product", + "ecs":"winlog.event_data.Product" + }, + { + "raw_field":"Provider", + "ecs":"winlog.provider_name" + }, + { + "raw_field":"ProviderName", + "ecs":"winlog.provider_name" + }, + { + "raw_field":"ScriptBlockText", + "ecs":"winlog.event_data.ScriptBlockText" + }, + { + "raw_field":"ServerName", + "ecs":"winlog.event_data.TargetServerName" + }, + { + "raw_field":"Service", + "ecs":"winlog.event_data.ServiceName" + }, + { + "raw_field":"Signed", + "ecs":"winlog.event_data.Signed" + }, + { + "raw_field":"State", + "ecs":"winlog.event_data.State" + }, + { + "raw_field":"Status", + "ecs":"winlog.event_data.Status" + }, + { + "raw_field":"SubjectDomainName", + "ecs":"winlog.event_data.SubjectDomainName" + }, + { + "raw_field":"SubjectLogonId", + "ecs":"winlog.event_data.SubjectLogonId" + }, + { + "raw_field":"SubjectUserName", + "ecs":"winlog.event_data.SubjectUserName" + }, + { + "raw_field":"SubjectUserSid", + "ecs":"winlog.event_data.SubjectUserSid" + }, + { + "raw_field":"TargetLogonId", + "ecs":"winlog.event_data.TargetLogonId" + }, + { + "raw_field":"TargetName", + "ecs":"winlog.event_data.TargetUserName" + }, + { + "raw_field":"TargetServerName", + "ecs":"winlog.event_data.TargetServerName" + }, + { + "raw_field":"TargetUserName", + "ecs":"winlog.event_data.TargetUserName" + }, + { + "raw_field":"TargetUserSid", + "ecs":"winlog.event_data.TargetUserSid" + }, + { + "raw_field":"TaskName", + "ecs":"winlog.task" + }, + { + "raw_field":"Type", + "ecs":"winlog.user.type" + }, + { + "raw_field":"User", + "ecs":"winlog.user.name" + }, + { + "raw_field":"UserName", + "ecs":"winlog.user.name" + }, + { + "raw_field":"Workstation", + "ecs":"winlog.event_data.Workstation" + }, + { + "raw_field":"WorkstationName", + "ecs":"winlog.event_data.Workstation" + }, + { + "raw_field":"event_uid", + "ecs":"winlog.event_id" + }, + { + "raw_field":"CommandLine", + "ecs":"process.command_line" + }, + { + "raw_field":"hostname", + "ecs":"host.hostname" + }, + { + "raw_field":"message", + "ecs":"windows.message" + }, + { + "raw_field":"Provider_Name", + "ecs":"winlog.provider_name" + }, + { + "raw_field":"EventId", + "ecs":"winlog.event_id" + }, + { + "raw_field":"processPath", + "ecs":"winlog.event_data.ProcessPath" + }, + { + "raw_field":"ProcessName", + "ecs":"winlog.event_data.ProcessName" + }, + { + "raw_field":"ObjectName", + "ecs":"winlog.computerObject.name" + }, + { + "raw_field":"param1", + "ecs":"winlog.event_data.param1" + }, + { + "raw_field":"param2", + "ecs":"winlog.event_data.param2" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"Origin", + "ecs":"winlog.event_data.Origin" + }, + { + "raw_field":"ParentImage", + "ecs":"winlog.event_data.ParentImage" + }, + { + "raw_field":"TargetPort", + "ecs":"winlog.event_data.TargetPort" + }, + { + "raw_field":"Query", + "ecs":"winlog.event_data.Query" + }, + { + "raw_field":"DestinationPort", + "ecs":"destination.port" + }, + { + "raw_field":"StartAddress", + "ecs":"winlog.event_data.StartAddress" + }, + { + "raw_field":"TicketOptions", + "ecs":"winlog.event_data.TicketOptions" + }, + { + "raw_field":"ParentCommandLine", + "ecs":"winlog.event_data.ParentCommandLine" + }, + { + "raw_field":"AllowedToDelegateTo", + "ecs":"winlog.event_data.AllowedToDelegateTo" + }, + { + "raw_field":"HostApplication", + "ecs":"winlog.event_data.HostApplication" + }, + { + "raw_field":"AccessMask", + "ecs":"winlog.event_data.AccessMask" + }, + { + "raw_field":"Hashes", + "ecs":"winlog.event_data.Hashes" + }, + { + "raw_field":"SidHistory", + "ecs":"winlog.event_data.SidHistory" + }, + { + "raw_field":"Initiated", + "ecs":"winlog.event_data.Initiated" + }, + { + "raw_field":"DestinationIp", + "ecs":"destination.ip" + }, + { + "raw_field":"RelativeTargetName", + "ecs":"winlog.event_data.RelativeTargetName" + }, + { + "raw_field":"Source_Name", + "ecs":"winlog.event_data.Source_Name" + }, + { + "raw_field":"AttributeLDAPDisplayName", + "ecs":"winlog.event_data.AttributeLDAPDisplayName" + }, + { + "raw_field":"DeviceDescription", + "ecs":"winlog.event_data.DeviceDescription" + }, + { + "raw_field":"AttributeValue", + "ecs":"winlog.event_data.AttributeValue" + }, + { + "raw_field":"ObjectValueName", + "ecs":"winlog.event_data.ObjectValueName" + }, + { + "raw_field":"QueryStatus", + "ecs":"winlog.event_data.QueryStatus" + }, + { + "raw_field":"TargetParentProcessId", + "ecs":"winlog.event_data.TargetParentProcessId" + }, + { + "raw_field":"OldUacValue", + "ecs":"winlog.event_data.OldUacValue" + }, + { + "raw_field":"FailureCode", + "ecs":"winlog.event_data.FailureCode" + }, + { + "raw_field":"OldTargetUserName", + "ecs":"winlog.event_data.OldTargetUserName" + }, + { + "raw_field":"NewUacValue", + "ecs":"winlog.event_data.NewUacValue" + }, + { + "raw_field":"ServiceName", + "ecs":"winlog.event_data.ServiceName" + }, + { + "raw_field":"Imphash", + "ecs":"winlog.event_data.Imphash" + }, + { + "raw_field":"NewValue", + "ecs":"winlog.event_data.NewValue" + }, + { + "raw_field":"Action", + "ecs":"winlog.event_data.Action" + }, + { + "raw_field":"SourceImage", + "ecs":"winlog.event_data.SourceImage" + }, + { + "raw_field":"QNAME", + "ecs":"winlog.event_data.QNAME" + }, + { + "raw_field":"Properties", + "ecs":"winlog.event_data.Properties" + }, + { + "raw_field":"AuditPolicyChanges", + "ecs":"winlog.event_data.AuditPolicyChanges" + }, + { + "raw_field":"Accesses", + "ecs":"winlog.event_data.Accesses" + }, + { + "raw_field":"ClassName", + "ecs":"winlog.event_data.ClassName" + }, + { + "raw_field":"ObjectClass", + "ecs":"winlog.event_data.ObjectClass" + }, + { + "raw_field":"PipeName", + "ecs":"winlog.event_data.PipeName" + }, + { + "raw_field":"HiveName", + "ecs":"winlog.event_data.HiveName" + }, + { + "raw_field":"StartModule", + "ecs":"winlog.event_data.StartModule" + }, + { + "raw_field":"HostVersion", + "ecs":"winlog.event_data.HostVersion" + }, + { + "raw_field":"DestinationHostname", + "ecs":"winlog.event_data.DestinationHostname" + }, + { + "raw_field":"QueryName", + "ecs":"winlog.event_data.QueryName" + }, + { + "raw_field":"RemoteName", + "ecs":"winlog.event_data.RemoteName" + }, + { + "raw_field":"PasswordLastSet", + "ecs":"winlog.event_data.PasswordLastSet" + }, + { + "raw_field":"ErrorCode", + "ecs":"winlog.event_data.ErrorCode" + }, + { + "raw_field":"AccessList", + "ecs":"winlog.event_data.AccessList" + }, + { + "raw_field":"Address", + "ecs":"winlog.event_data.Address" + }, + { + "raw_field":"PossibleCause", + "ecs":"winlog.event_data.PossibleCause" + }, + { + "raw_field":"DestPort", + "ecs":"destination.port" + }, + { + "raw_field":"Image", + "ecs":"winlog.event_data.Image" + }, + { + "raw_field":"CertThumbprint", + "ecs":"winlog.event_data.CertThumbprint" + }, + { + "raw_field":"TicketEncryptionType", + "ecs":"winlog.event_data.TicketEncryptionType" + }, + { + "raw_field":"ServiceType", + "ecs":"winlog.event_data.ServiceType" + }, + { + "raw_field":"ObjectServer", + "ecs":"winlog.event_data.ObjectServer" + }, + { + "raw_field":"ImagePath", + "ecs":"winlog.event_data.ImagePath" + }, + { + "raw_field":"NewName", + "ecs":"winlog.event_data.NewName" + }, + { + "raw_field":"CallTrace", + "ecs":"winlog.event_data.CallTrace" + }, + { + "raw_field":"SamAccountName", + "ecs":"winlog.event_data.SamAccountName" + }, + { + "raw_field":"GrantedAccess", + "ecs":"winlog.event_data.GrantedAccess" + }, + { + "raw_field":"EngineVersion", + "ecs":"winlog.event_data.EngineVersion" + }, + { + "raw_field":"OriginalName", + "ecs":"winlog.event_data.OriginalName" + }, + { + "raw_field":"AuditSourceName", + "ecs":"winlog.event_data.AuditSourceName" + }, + { + "raw_field":"sha1", + "ecs":"hash.sha1" + }, + { + "raw_field":"SourceIp", + "ecs":"source.ip" + }, + { + "raw_field":"Payload", + "ecs":"winlog.event_data.Payload" + }, + { + "raw_field":"Level", + "ecs":"winlog.event_data.Level" + }, + { + "raw_field":"Application", + "ecs":"winlog.event_data.Application" + }, + { + "raw_field":"RemoteAddress", + "ecs":"winlog.event_data.RemoteAddress" + }, + { + "raw_field":"SearchFilter", + "ecs":"winlog.event_data.SearchFilter" + }, + { + "raw_field":"ApplicationPath", + "ecs":"winlog.event_data.ApplicationPath" + }, + { + "raw_field":"TargetFilename", + "ecs":"winlog.event_data.TargetFilename" + }, + { + "raw_field":"CurrentDirectory", + "ecs":"winlog.event_data.CurrentDirectory" + }, + { + "raw_field":"ObjectType", + "ecs":"winlog.event_data.ObjectType" + }, + { + "raw_field":"ServicePrincipalNames", + "ecs":"winlog.event_data.ServicePrincipalNames" + }, + { + "raw_field":"TemplateContent", + "ecs":"winlog.event_data.TemplateContent" + }, + { + "raw_field":"QueryResults", + "ecs":"winlog.event_data.QueryResults" + }, + { + "raw_field":"ServiceStartType", + "ecs":"winlog.event_data.ServiceStartType" + }, + { + "raw_field":"EventType", + "ecs":"winlog.event_data.EventType" + }, + { + "raw_field":"TargetSid", + "ecs":"winlog.event_data.TargetSid" + }, + { + "raw_field":"ParentUser", + "ecs":"winlog.event_data.ParentUser" + }, + { + "raw_field":"NewTargetUserName", + "ecs":"winlog.event_data.NewTargetUserName" + }, + { + "raw_field":"DestAddress", + "ecs":"winlog.event_data.DestAddress" + }, + { + "raw_field":"ContextInfo", + "ecs":"winlog.event_data.ContextInfo" + }, + { + "raw_field":"HostName", + "ecs":"host.name" + }, + { + "raw_field":"NewTemplateContent", + "ecs":"winlog.event_data.NewTemplateContent" + }, + { + "raw_field":"LayerRTID", + "ecs":"winlog.event_data.LayerRTID" + }, + { + "raw_field":"ImageFileName", + "ecs":"winlog.event_data.ImageFileName" + }, + { + "raw_field":"StartFunction", + "ecs":"winlog.event_data.StartFunction" + }, + { + "raw_field":"Value", + "ecs":"winlog.event_data.Value" + }, + { + "raw_field":"ModifyingApplication", + "ecs":"winlog.event_data.ModifyingApplication" + }, + { + "raw_field":"Destination", + "ecs":"winlog.event_data.Destination" + }, + { + "raw_field":"Commandline", + "ecs":"winlog.event_data.Commandline" + }, + { + "raw_field":"Message", + "ecs":"winlog.event_data.Message" + }, + { + "raw_field":"ShareName", + "ecs":"winlog.event_data.ShareName" + }, + { + "raw_field":"SourcePort", + "ecs":"source.port" + }, + { + "raw_field":"CallerProcessName", + "ecs":"winlog.event_data.CallerProcessName" + }, + { + "raw_field":"ServiceFileName", + "ecs":"winlog.event_data.ServiceFileName" + }, + { + "raw_field":"DestinationIsIpv6", + "ecs":"winlog.event_data.DestinationIsIpv6" + }, + { + "raw_field":"TargetImage", + "ecs":"winlog.event_data.TargetImage" + }, + { + "raw_field":"SourceAddress", + "ecs":"source.ip" + }, + { + "raw_field":"TargetObject", + "ecs":"winlog.event_data.TargetObject" + }, + { + "raw_field":"Caption", + "ecs":"winlog.event_data.Caption" + }, + { + "raw_field":"LocalName", + "ecs":"winlog.event_data.LocalName" + }, + { + "raw_field":"ImageLoaded", + "ecs":"winlog.event_data.ImageLoaded" + }, + { + "raw_field":"EventID", + "ecs":"winlog.event_id" + }, + { + "raw_field":"sha256", + "ecs":"hash.sha256" + }, + { + "raw_field":"ScriptBlockLogging", + "ecs":"winlog.event_data.ScriptBlockLogging" + }, + { + "raw_field":"SourceParentImage", + "ecs":"winlog.event_data.SourceParentImage" + }, + { + "raw_field":"SourceFilename", + "ecs":"winlog.event_data.SourceFilename" + }, + { + "raw_field":"Protocol", + "ecs":"winlog.event_data.Protocol" + }, + { + "raw_field":"ValidatedPolicy", + "ecs":"winlog.event_data.ValidatedPolicy" + }, + { + "raw_field":"ProcessPath", + "ecs":"winlog.event_data.ProcessPath" + }, + { + "raw_field":"OldValue", + "ecs":"winlog.event_data.OldValue" + }, + { + "raw_field":"ParentProcessId", + "ecs":"winlog.event_data.ParentProcessId" + }, + { + "raw_field":"TaskContentNew", + "ecs":"winlog.event_data.TaskContentNew" + }, + { + "raw_field":"Name", + "ecs":"winlog.event_data.Name" + }, + { + "raw_field":"payload", + "ecs":"winlog.event_data.payload" + }, + { + "raw_field":"SourceHostname", + "ecs":"winlog.event_data.SourceHostname" + }, + { + "raw_field":"ClientProcessId", + "ecs":"winlog.event_data.ClientProcessId" + }, + { + "raw_field":"TargetParentImage", + "ecs":"winlog.event_data.TargetParentImage" + }, + { + "raw_field":"ImpersonationLevel", + "ecs":"winlog.event_data.ImpersonationLevel" + }, + { + "raw_field":"ExceptionCode", + "ecs":"winlog.event_data.ExceptionCode" + }, + { + "raw_field":"FilterOrigin", + "ecs":"winlog.event_data.FilterOrigin" + }, + { + "raw_field":"PackagePath", + "ecs":"winlog.event_data.PackagePath" + }, + { + "raw_field":"SignatureStatus", + "ecs":"winlog.event_data.SignatureStatus" + }, + { + "raw_field":"Hash", + "ecs":"winlog.event_data.Hash" + }, + { + "raw_field":"AppID", + "ecs":"winlog.event_data.AppID" + }, + { + "raw_field":"SidList", + "ecs":"winlog.event_data.SidList" + }, + { + "raw_field":"ProcessNameBuffer", + "ecs":"winlog.event_data.ProcessNameBuffer" + }, + { + "raw_field":"PreviousCreationUtcTime", + "ecs":"winlog.event_data.PreviousCreationUtcTime" + }, + { + "raw_field":"Contents", + "ecs":"winlog.event_data.Contents" + }, + { + "raw_field":"TargetOutboundUserName", + "ecs":"winlog.event_data.TargetOutboundUserName" + }, + { + "raw_field":"ImageName", + "ecs":"winlog.event_data.ImageName" + }, + { + "raw_field":"md5", + "ecs":"hash.md5" + }, + { + "raw_field":"DeviceName", + "ecs":"winlog.event_data.DeviceName" + }, + { + "raw_field":"RequestedPolicy", + "ecs":"winlog.event_data.RequestedPolicy" + }, + { + "raw_field":"FileNameBuffer", + "ecs":"winlog.event_data.FileNameBuffer" + }, + { + "raw_field":"TaskContent", + "ecs":"winlog.event_data.TaskContent" + }, + { + "raw_field":"SourceCommandLine", + "ecs":"winlog.event_data.SourceCommandLine" + }, + { + "raw_field":"CreationUtcTime", + "ecs":"winlog.event_data.CreationUtcTime" + }, + { + "raw_field":"AppName", + "ecs":"winlog.event_data.AppName" + }, + { + "raw_field":"subjectName", + "ecs":"winlog.event_data.subjectName" + }, + { + "raw_field":"process", + "ecs":"winlog.event_data.process" + }, + { + "raw_field":"PackageFullName", + "ecs":"winlog.event_data.PackageFullName" + }, + { + "raw_field":"SourceName", + "ecs":"winlog.event_data.SourceName" + }, + { + "raw_field":"Data", + "ecs":"winlog.event_data.Data" + }, + { + "raw_field":"param3", + "ecs":"winlog.event_data.param3" + }, + { + "raw_field":"Signature", + "ecs":"winlog.event_data.Signature" + } + ] +``` \ No newline at end of file diff --git a/_security-analytics/resource-access-control.md b/_security-analytics/resource-access-control.md new file mode 100644 index 00000000..feef198a --- /dev/null +++ b/_security-analytics/resource-access-control.md @@ -0,0 +1,159 @@ +--- +layout: default +title: Security Analytics resource access control +nav_order: 3 +has_children: false +--- + +# Security Analytics resource access control + +Security Analytics integrates with the Security plugin's resource sharing and access control framework to provide document-level authorization for detectors and correlation rules. This replaces the legacy `plugins.security_analytics.filter_by_backend_roles` setting with a more flexible sharing system that allows resource owners to grant specific access levels to users, roles, or backend roles. + +For the end-to-end framework concepts and APIs, see [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/). +{: .note} + +## Resource configuration + +Security Analytics registers two resource types. The following table describes the Security Analytics resource configuration. + +| Resource type | System index | Onboarded version | +| :--- | :--- | :--- | +| `detector` | `.opensearch-sap-detectors-config` | OpenSearch 3.8 | +| `correlation-rule` | `.opensearch-sap-correlation-rules-config` | OpenSearch 3.8 | + +When resource-level authorization is enabled, each detector's and correlation rule's visibility is governed by a central sharing record. Resource owners and users with sharing capabilities can grant or revoke access permissions for specific users, roles, or backend roles. + +## Enable Security Analytics resource sharing + +To enable resource sharing for Security Analytics, add the Security Analytics resource types to the protected types list and enable resource sharing cluster-wide. + +Admin-only: These settings can be configured only by cluster administrators with superadmin privileges. +{: .important } + +### Configuration using opensearch.yml + +Add the following settings to your `opensearch.yml` configuration file to enable resource sharing for Security Analytics: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "detector" + - "correlation-rule" +``` +{% include copy.html %} + +### Configuration using the Cluster Settings API + +Alternatively, you can enable resource sharing dynamically using the Cluster Settings API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["detector", "correlation-rule"] + } +} +``` +{% include copy-curl.html %} + +When adding the Security Analytics resource types to an existing configuration, include all previously configured resource types in the `protected_types` array. +{: .note} + +## Security Analytics access levels + +Security Analytics provides three predefined access levels that apply to both the `detector` and `correlation-rule` resource types. These access levels determine the specific permissions granted to users who have been granted access to a detector or correlation rule resource. + +### sa_read_only + +The `sa_read_only` read-only access level grants users the ability to view and search shared resources but not modify them. For detectors, this access level includes the following permissions: + +```yaml +- 'cluster:admin/opensearch/securityanalytics/detector/get' +- 'cluster:admin/opensearch/securityanalytics/detector/search' +- 'cluster:admin/opensearch/securityanalytics/alerts/get' +- 'cluster:admin/opensearch/securityanalytics/findings/get' +- 'cluster:admin/opensearch/securityanalytics/mapping/get' +- 'cluster:admin/opensearch/securityanalytics/mapping/view/get' +``` +{% include copy.html %} + +For correlation rules, this access level includes the following permissions: + +```yaml +- 'cluster:admin/opensearch/securityanalytics/correlation/rule/search' +- 'cluster:admin/opensearch/securityanalytics/correlations/list' +- 'cluster:admin/opensearch/securityanalytics/correlations/findings' +- 'cluster:admin/opensearch/securityanalytics/correlationAlerts/get' +``` +{% include copy.html %} + +### sa_read_write + +The `sa_read_write` read-write access level grants users full access to resource operations except for sharing capabilities. For detectors, this access level includes the following permissions: + +```yaml +- 'cluster:admin/opensearch/securityanalytics/detector/*' +- 'cluster:admin/opensearch/securityanalytics/alerts/*' +- 'cluster:admin/opensearch/securityanalytics/findings/*' +- 'cluster:admin/opensearch/securityanalytics/mapping/*' +- 'cluster:admin/opensearch/securityanalytics/rule/*' +``` +{% include copy.html %} + +For correlation rules, this access level includes the following permissions: + +```yaml +- 'cluster:admin/index/correlation/rules/*' +- 'cluster:admin/opensearch/securityanalytics/correlation/rule/search' +- 'cluster:admin/opensearch/securityanalytics/correlations/*' +- 'cluster:admin/opensearch/securityanalytics/correlationAlerts/*' +``` +{% include copy.html %} + +### sa_full_access + +The `sa_full_access` full access level grants users complete control over a resource, including owner-like permissions such as sharing the resource with other users. This access level includes all read-write permissions for the resource type plus the resource sharing permission: + +```yaml +- 'cluster:admin/security/resource/share' +``` +{% include copy.html %} + +These access levels are predefined and cannot be modified. To request additional access levels, create an issue in the [Security Analytics GitHub repository](https://github.com/opensearch-project/security-analytics/). +{: .note} + +## Migrating from the legacy framework + +After enabling resource sharing and marking the Security Analytics resource types as protected, cluster administrators must run the migration API to transfer existing detector and correlation rule sharing information from the legacy framework to the new resource sharing system. Run the migration once per resource index. + +Admin-only: The Migrate API can only be executed by cluster administrators with superadmin or REST admin privileges. +{: .important } + +Use the following API call to migrate legacy detector sharing data to the resource sharing framework: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opensearch-sap-detectors-config", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "detector": "<select-appropriate-access-level>" + } +} +``` +{% include copy-curl.html %} + +Run the migration again for the correlation rule index, using `.opensearch-sap-correlation-rules-config` as the `source_index` and `correlation-rule` as the `default_access_level` key. + +Replace `<replace-with-existing-user>` with the username of an existing user who should own resources without explicit ownership information. Replace `<select-appropriate-access-level>` with one of the available Security Analytics access levels: `sa_read_only`, `sa_read_write`, or `sa_full_access`. + +## Related documentation + +- [Resource sharing and access control]({{site.url}}{{site.baseurl}}/security/access-control/resources/) -- Backend concepts, configuration, and setup +- [Resource sharing APIs]({{site.url}}{{site.baseurl}}/security/access-control/resource-sharing-api/) -- REST API reference for programmatic management +- [Resource access management]({{site.url}}{{site.baseurl}}/dashboards/management/resource-sharing/) -- UI workflows and user guidance +- [OpenSearch security for Security Analytics]({{site.url}}{{site.baseurl}}/security-analytics/security/) -- Basic permissions and legacy backend role filtering diff --git a/_security-analytics/sec-analytics-config/correlation-config.md b/_security-analytics/sec-analytics-config/correlation-config.md index 8b49e5c0..2a350178 100644 --- a/_security-analytics/sec-analytics-config/correlation-config.md +++ b/_security-analytics/sec-analytics-config/correlation-config.md @@ -16,25 +16,25 @@ Having at least two data sources in the rule configuration is the basis for maki 1. Begin by selecting **Security Analytics** in the OpenSearch Dashboards main menu. Then select **Correlation rules** from the Security Analytics menu on the left side of the screen. The **Correlation rules** page is displayed, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/create-corr-rule.png" alt="The correlation rules page" width="85%"> + ![The correlation rules page]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/create-corr-rule.png){: width="85%" } 1. Select **Create correlation rule**. The **Create correlation rule** window opens. 1. In the **Correlation rule details** field, enter a name for the rule, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config1.png" alt="The correlation rule name" width="50%"> + ![The correlation rule name]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config1.png){: width="50%" } 1. The **Correlation queries** field contains two dropdown lists. In the **Select index** dropdown list, specify an index or index pattern for the data source. In the **Log type** dropdown list, specify the log type associated with the index, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config2.png" alt="The data source and log type for the query" width="45%"> + ![The data source and log type for the query]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config2.png){: width="45%" } 1. In the **Field** dropdown list, specify a log field. In the **Field value** text box, enter a value for the field, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config3.png" alt="The field and field value for the query" width="45%"> + ![The field and field value for the query]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config3.png){: width="45%" } 1. To add more fields to the query, select **Add field**. 1. After configuring the first query, repeat the previous step to configure a second query. You can select **Add query** at the bottom of the window to add more queries for the rule, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config4.png" alt="A second query for the correlation rule" width="50%"> + ![A second query for the correlation rule]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-rule-config4.png){: width="50%" } 1. Once the rule is complete, select **Create correlation rule** in the lower-right corner of the window. OpenSearch creates a new rule, the screen returns to the **Correlation rules** window, and the new rule appears in the table of correlation rules. To edit the rule, select the rule name in the **Name** column. The **Edit correlation rule** window opens. @@ -62,3 +62,5 @@ PUT /_cluster/settings After creating detectors and correlation rules, you can use the correlation graph to observe the correlations between findings from different log sources. For information about working with the correlation graph, see [Working with the correlation graph]({{site.url}}{{site.baseurl}}/security-analytics/usage/correlation-graph/). +You can also add a trigger to a correlation rule so that it generates an alert and sends a notification when it correlates findings. For more information, see [Correlation rule triggers]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/correlation-eng/#correlation-rule-triggers). + diff --git a/_security-analytics/sec-analytics-config/detectors-config.md b/_security-analytics/sec-analytics-config/detectors-config.md index d58721bf..366037d1 100644 --- a/_security-analytics/sec-analytics-config/detectors-config.md +++ b/_security-analytics/sec-analytics-config/detectors-config.md @@ -20,10 +20,13 @@ To define a detector: 1. On the **Security Analytics** home page or the **Detectors** page, choose **Create detector**. 1. Give the detector a name and, optionally, a description. -1. In the **Data source** section, select one or more sources for the log data. Use an asterisk (*) to indicate a wildcard pattern. When selecting multiple data sources, their logs must be of the same type. It is good practice to create separate detectors for different log types. Security Analytics also supports the following: +1. In the **Data source** section, select one or more sources for the log data. When selecting multiple data sources, they must all contain logs of the same log type (for example, all Amazon S3 logs or all Windows logs). It is good practice to create separate detectors for different log types. In addition to indexes, Security Analytics supports the following data source types: - - [Aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/): When configuring an alias as the data source, it must be attached to a **Write** index alias. When using an alias, ensure that your documents are ingested through the alias and **not** through the index for which the alias was created. - - [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/): A set of time-series data stored across multiple indexes but called using a single named resource. + - [Aliases]({{site.url}}{{site.baseurl}}/im-plugin/index-alias/): When configuring an alias as the data source, it must be attached to a **Write** index alias. When using an alias, ensure that your documents are ingested through the alias and **not** through the index for which the alias was created. + - [Data streams]({{site.url}}{{site.baseurl}}/im-plugin/data-streams/): A set of time-series data stored across multiple indexes but called using a single named resource. + + Using an asterisk (*) to indicate a wildcard pattern for data sources is not recommended. + {: .note} 1. In the **Detection** section, select a log type for the data source. For a list of supported log types, see [Supported log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/). To create your own log types, see [Creating custom log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/custom-log-type/). @@ -32,7 +35,7 @@ To define a detector: 1. Expand **Detection rules** to show the list of available detection rules for the selected log type. Initially, all rules are selected by default. The following example shows the rules associated with the **windows** log type. - <img src="{{site.url}}{{site.baseurl}}/images/Security/detector-rules.png" alt="Selecting threat detector log type to auto-populate rules" width="100%"> + ![Selecting threat detector log type to auto-populate rules]({{site.url}}{{site.baseurl}}/images/Security/detector-rules.png){: width="100%" } You can perform the following actions when viewing rules: @@ -43,13 +46,13 @@ To define a detector: To quickly select one or more known rules and dismiss others, first deselect all rules by turning off the **Rule name** toggle, then search for your target rule names and select each individually by turning its toggle on. {: .tip } -1. Review the field mappings. Field mappings allow the system to accurately pass event data from the log to the detector and then use the data to trigger alerts. For more information about field mappings, see [A note on field names](#a-note-on-field-names). +1. Review the field mappings. Field mappings allow the system to accurately pass event data from the log to the detector and then use the data to trigger alerts. For more information about field mappings, refer to the [A note on field mappings](#a-note-on-field-names) section. 1. Choose whether to enable [threat intelligence]({{site.url}}{{site.baseurl}}/security-analytics/usage/detectors#threat-intelligence-feeds) feeds. Threat intelligence feeds only work with **standard** log types. 1. In the **Detector schedule** section, create a schedule for how often to run the detector. Specify a unit of time and a corresponding number to set the interval. The following image shows that the detector runs every 3 minutes. - <img src="{{site.url}}{{site.baseurl}}/images/Security/detector-schedule.png" alt="Detector schedule settings to determine how often the detector runs" width="40%"> + ![Detector schedule settings to determine how often the detector runs]({{site.url}}{{site.baseurl}}/images/Security/detector-schedule.png){: width="40%" } 1. Select **Next**. The **Set up alerts** page appears and displays settings for an alert trigger. @@ -69,18 +72,18 @@ To set up an alert for a detector, continue with the following steps: 1. In the **Trigger name** box, optionally enter a name for the trigger or edit the default name. 1. To define rule matches for the alert, select security rules, severity levels, and tags. - <img src="{{site.url}}{{site.baseurl}}/images/Security/alert_rules.png" alt="Defining an alert" width="70%"> + ![Defining an alert]({{site.url}}{{site.baseurl}}/images/Security/alert_rules.png){: width="70%" } * Select one rule or multiple rules that will trigger the alert. Put the cursor in the **Rule names** box and type a name to search for it. To remove a rule name, select the **X** beside the name. To remove all rule names, select the **X** beside the dropdown list's down arrow. - <img src="{{site.url}}{{site.baseurl}}/images/Security/rule_name_delete.png" alt="Deletes all selected rules" width="45%"> + ![Deletes all selected rules]({{site.url}}{{site.baseurl}}/images/Security/rule_name_delete.png){: width="45%" } * Select one or more rule severity levels as conditions for the alert. * Select from a list of tags to include as conditions for the alert. 1. To define a notification for the alert, assign an alert severity, select a channel for the notification, and customize a message generated for the alert. - <img src="{{site.url}}{{site.baseurl}}/images/Security/alert_notify.png" alt="Notification settings for the alert" width="45%"> + ![Notification settings for the alert]({{site.url}}{{site.baseurl}}/images/Security/alert_notify.png){: width="45%" } * Assign a level of severity for the alert to give the recipient an indication of its urgency. * Select a channel for the notification from the **Select channel to notify** dropdown list. Examples include Slack, Chime, or email. To create a new channel, select the **Manage channels** link to the right of the field. The **Channels** page for Notifications opens in a new tab where you can edit and create new channels. For more information about notifications, see the [Notifications]({{site.url}}{{site.baseurl}}/observing-your-data/notifications/index/) documentation. @@ -104,15 +107,17 @@ For more information about composite monitors and their workflows, see [Composit Once you select a data source and log type, the system attempts to automatically map fields between the log and rule fields. Switch to the **Mapped fields** tab to show the list of these mappings. When the field names are similar to one another, the system can successfully match the two, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/automatic-mappings.png" alt="Field mapping example for automatic mappings" width="85%"> +![Field mapping example for automatic mappings]({{site.url}}{{site.baseurl}}/images/Security/automatic-mappings.png){: width="85%" } Although these automatic matches are normally dependable, it's still a good idea to review the mappings in the **Mapped fields** table and verify that they are correct and matched as expected. If you find a mapping that doesn't appear to be accurate, you can use the dropdown list to search for and select the correct field name. For more information about matching field names, see the following section. +For more information about field mappings, refer to the [About field mappings]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types#about-field-mappings) section within the [Working with log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types) documentation. + ## Available fields The field names that are not automatically mapped appear in the **Available fields** table. In this table you can manually map detection rule fields to data source fields, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/pending-mappings.png" alt="Field mapping example for available mappings" width="85%"> +![Field mapping example for available mappings]({{site.url}}{{site.baseurl}}/images/Security/pending-mappings.png){: width="85%" } While mapping fields, consider the following: * The **Detection rule field** column lists field names based on all of the prepackaged rules associated with the selected log type. @@ -126,29 +131,41 @@ While mapping fields, consider the following: If you choose to perform manual field mapping, you should be familiar with the field names in the log index and have an understanding of the data contained in those fields. If you have an understanding of the log source fields in the index, the mapping is typically a straightforward process. -Security Analytics takes advantage of prepackaged Sigma rules for security event detection. Therefore, the field names are derived from a Sigma rule field standard. To make them easier to identify, however, we have created aliases for the Sigma rule fields based on the following specifications: +Security Analytics takes advantage of prepackaged Sigma rules for security event detection. Therefore, the field names are derived from a Sigma rule field standard. To make them more identifiable, aliases for the Sigma rule fields have been created based on the following specifications: -- For all log types, go to the open-source Elastic Common Schema (ECS) specification. -- For AWS CloudTrail, Domain Name System (DNS) log types, and virtual private network (VPC) flow logs, go to the [Open Cybersecurity Framework](https://github.com/ocsf/ocsf-schema). +- For all log types, the open-source Elastic Common Schema (ECS) +- For AWS CloudTrail and DNS log types, the [Open Cybersecurity Schema Framework](https://github.com/ocsf/ocsf-schema) (OCSF) -These alias rule field names are the field names used in these steps. They appear in the **Detector field name** column of the mapping tables. +The field names for alias rules are used in the following steps and are listed in the **Detector field name** column within the mapping tables. -In the following locations, you can find predefined mappings of the Sigma rule field names to the ECS rule field names for all supported log types: +Predefined mappings that correlate the field names from Sigma rules to those of ECS rules for all supported log types are available in the following resources: + +- The [Supported log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/) reference documentation +- The GitHub Security Analytics repository. To find the field mappings: + 1. Navigate to the [`OSMappings`](https://github.com/opensearch-project/security-analytics/tree/main/src/main/resources/OSMapping) folder. + 2. Select the file for the specific log type. For example, for the `windows` log type, to view field names that correlate from Sigma rules to those of ECS rules, select the [`windows_logtype.json`](https://github.com/opensearch-project/security-analytics/blob/main/src/main/resources/OSMapping/windows_logtype.json) file. The `raw_field` value represents the field name for the Sigma rule in the mapping. + +## Amazon Security Lake logs + +[Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) converts security log and event data to the [OCSF](https://docs.aws.amazon.com/security-lake/latest/userguide/open-cybersecurity-schema-framework.html) format to normalize combined data and facilitate its management. OpenSearch supports ingestion of log data from Amazon Security Lake in the OCSF format. Security Analytics can automatically map fields from OCSF to ECS (the default field mapping schema). + +The Amazon Security Lake log types that can be used as log sources for detector creation include AWS CloudTrail, Amazon Route 53, and VPC Flow Logs. Because Amazon Route 53 logs capture DNS activity, the log type must be specified as **dns** when [defining a detector](#step-1-define-a-detector). Because AWS CloudTrail logs can be captured in both raw format and OCSF, you should name indexes distinctly and identifiably. This can be helpful when specifying an index name in an API associated with Security Analytics. + +Supported log types are available in the following resources: + +- For all log types, see the open-source ECS specification. +- For AWS CloudTrail, DNS log types, and VPC Flow Logs, see the [OCSF](https://github.com/ocsf/ocsf-schema). + + +The field names for alias rules are used in the following steps and are listed in the **Detector field name** column in the mapping tables. + +Predefined mappings that correlate the field names from Sigma rules to those of ECS rules for all supported log types are available in the following resources: - The [Supported log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/) reference documentation. - The [GitHub Security Analytics](https://github.com/opensearch-project/security-analytics) repository. To find the field mappings: - 1. Navigate to the [OSMappings](https://github.com/opensearch-project/security-analytics/tree/main/src/main/resources/OSMapping) folder. -2. Select the file for the log type. For example, to view the Sigma rule fields that correspond to the ECS rule fields for the Windows log type, select the [`windows_logtype.json` file](https://github.com/opensearch-project/security-analytics/blob/main/src/main/resources/OSMapping/windows_logtype.json). The `raw_field` value in the file represents the Sigma rule field name in the mapping. - -## Amazon Security Lake logs - -[Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) converts security log and event data to the [Open Cybersecurity Schema Framework](https://docs.aws.amazon.com/security-lake/latest/userguide/open-cybersecurity-schema-framework.html) (OCSF) in order to normalize combined data and facilitate its management. OpenSearch supports ingestion of log data from Security Lake in the OCSF format, and Security Analytics can automatically map fields from OCSF to ECS (the default field mapping schema). - -The Security Lake log types that can be used as log sources for detector creation include AWS CloudTrail, Amazon Route 53, and Amazon VPC Flow Logs. Given that Amazon Route 53 captures DNS activity, its log type should be specified as **dns** when [defining a detector](#step-1-define-a-detector). Furthermore, because logs such as AWS CloudTrail logs can conceivably be captured in both raw format and OCSF format, it is good practice to name indexes in a way that keeps these logs separate and easily identifiable. This becomes helpful when specifying an index name in any of the APIs associated with Security Analytics. - -To reveal fields for a log index in either raw format or OCSF format, use the [Get Mappings View]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/mappings-api/#get-mappings-view) API and specify the index in the `index_name` field of the request. -{: .tip } + 1. Navigate to the [`OSMappings`](https://github.com/opensearch-project/security-analytics/tree/main/src/main/resources/OSMapping) folder. + 2. Select the file for the specific log type. For example, for the `windows` log type, to view field names that correlate from Sigma rules to those of ECS rules, select the [`windows_logtype.json`](https://github.com/opensearch-project/security-analytics/blob/main/src/main/resources/OSMapping/windows_logtype.json) file. The `raw_field` value represents the field name for the Sigma rule in the mapping. ## What's next diff --git a/_security-analytics/sec-analytics-config/index.md b/_security-analytics/sec-analytics-config/index.md index 3b4902ca..21653bae 100644 --- a/_security-analytics/sec-analytics-config/index.md +++ b/_security-analytics/sec-analytics-config/index.md @@ -22,4 +22,4 @@ Before Security Analytics can begin generating findings and sending alerts, admi 1. To get started, select the top menu on the Dashboards home page and then select **Security Analytics**. The Overview page for Security Analytics is displayed. 1. From the options on the left side of the page, select **Detectors** to begin creating a detector. -<img src="{{site.url}}{{site.baseurl}}/images/Security/secanalytics-det-nav.png" alt="Navigating to create a detector page" width="70%"> +![Navigating to create a detector page]({{site.url}}{{site.baseurl}}/images/Security/secanalytics-det-nav.png){: width="70%" } diff --git a/_security-analytics/sec-analytics-config/log-types.md b/_security-analytics/sec-analytics-config/log-types.md index fc016556..fa9bb732 100644 --- a/_security-analytics/sec-analytics-config/log-types.md +++ b/_security-analytics/sec-analytics-config/log-types.md @@ -1,51 +1,79 @@ --- layout: default -title: Supported log types +title: Working with log types parent: Setting up Security Analytics -nav_order: 16 +nav_order: 14 +redirect_from: + - /security-analytics/sec-analytics-config/custom-log-type/ --- +# Working with log types -# Supported log types +Log types represent the different data sources used for threat detection in Security Analytics. Log types are useful for categorizing or prepopulating [detection rules]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/detectors-config/) when creating detectors from your source. -Logs contain raw data about events that happen throughout a system and in its separate parts. As of OpenSearch 2.11, log types are grouped by category to help select, filter, and search the log types. +Security Analytics supports the following log types: -To navigate to the **Log types** page, select **Log types** under **Detectors** in the **Security Analytics** navigation menu. The page shows the name of the log type, its description, its category, and identifies whether it's a standard OpenSearch-defined log type or a custom log type. The following image shows the **Log types** landing page with the Category column selected and the **Category** filter you can use to filter the list by the category. - -<img src="{{site.url}}{{site.baseurl}}/images/Security/c-log-type.png" alt="The Log types landing page." width="85%"> - -The following table shows the log types that are currently supported by Security Analytics for ingestion, mapping, and monitoring. - -| Category | Log type | Description | -| :--- |:--- |:--- | -| Access Management | `Ad_ldap` | Active Directory logs that track LDAP queries, errors from the LDAP server, timeout events, and unsecure LDAP binds. | -| Access Management | `Apache_access` | Apache access logs that record data for all requests processed by an Apache HTTP server. | -| Access Management | `Okta` | Okta logs that record Okta events from a range of actions, such as downloading an export file, requesting application access, or revoking privileges. | -| Applications | `GitHub` | GitHub logs that monitor workflows created by [GitHub Actions](https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions). | -| Applications| `Gworkspace` | Google Workspace logs that monitor log entries such as admin actions, group and group membership actions, and events related to logging in. | -| Applications| `M365` | Microsoft 365 audit logs that collect a range of data for Microsoft 365, including records from call details, performance data, SQL Server, security events, and access control activity. | -| Cloud Services | `Azure` | Microsoft Azure logs that monitor log data for cloud applications managed by Azure Cloud Services. | -| Cloud Services | `CloudTrail` | AWS CloudTrail logs that monitor events for an AWS CloudTrail account. OpenSearch can ingest CloudTrail log data from both [Amazon Simple Storage Service](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) (Amazon S3) accounts and [Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) service accounts. | -| Cloud Services | `S3` | Amazon S3 logs that track requests for access to an S3 bucket. | -| Network Activity| `Dns` | DNS logs that store DNS activity. | -| Network Activity | `Network` | Network logs that record events that happen in a system's network, such as login attempts and application events. | -| Network Activity | `vpcflow` | [VPC Flow Logs](https://docs.aws.amazon.com/prescriptive-guidance/latest/logging-monitoring-for-application-owners/vpc-flow-logs.html) that capture information about the IP traffic going to and from network interfaces in your virtual private cloud (VPC). | -| Security | `Waf` | Web Application Firewall (WAF) logs (introduced in OpenSearch 2.11) for users that require monitoring of the WAF use case that's provided out of the box with Security Analytics. The role of WAF is to monitor and filter HTTP traffic between a web application and the internet. WAF prevents common security attacks, such as cross-site scripting (XSS) and SQL Injection (SQi). | -| System Activity | `Linux` | Linux system logs that record Linux syslog events. | -| System Activity | `Windows` | Windows logs that record events that have happened in the operating system, applications, and other Windows system services. | -| Other | `Email` | Logs that record email activity. | +- [Standard log types](#standard-log-types): Security Analytics automatically generates a list of data sources, along with their field mappings and rules, based on the data indexed from each source. +- [Custom log types](#creating-custom-log-types): When your data cannot be categorized as one of the [standard log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/), you can create a user-defined log type. For enhanced threat detection, Security Analytics supports the integration of custom log types. +To navigate to the **Log types** page, select **Log types** under **Detectors** in the **Security Analytics** navigation menu. ## Page actions -The following list describes the main features found on the **Log types** page and the actions you can take: +The main **Log types** UI features and actions are shown in the following image. These features are described in the list following the image. + +![The Log types landing page.]({{site.url}}{{site.baseurl}}/images/Security/c-log-type.png){: width="85%" } + + +1. Search **Standard** and **Custom** log types. + - For a list of **Standard** log types, see [Supported log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/). +2. Create a [custom log type](#creating-custom-log-types). +3. Select the log type **Name** to open the details page. The **Details** tab is shown by default. This tab includes the log type's ID. You can also select the **Detection rules** tab to show all detection rules associated with the log type. +4. Select the **Category** or **Source** dropdown menu to sort by log type category or source. +5. From the **Actions** column, select the {::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/alerting/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/} icon to delete a custom log type (you cannot delete a standard OpenSearch-defined log type). Then follow the prompts to confirm and delete it. + +## Standard log types + +All standard log types are grouped by the following categories: + +- **Access Management** includes [AD/LDAP]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/ad-ldap/), [Apache Access]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/apache-access/), and [Okta]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/okta/). +- **Applications** includes [GitHub]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/github/), [Google Workspace]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/gworkspace/), and [Microsoft 365]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/m365/). +- **Cloud Services** includes [Azure]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/azure/), [AWS CloudTrail]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/cloudtrail/), and [Amazon S3]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/s3/). +- **Network Activity** includes [DNS]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/dns/), [Network]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/network/), [NetFlow]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/netflow/), and [VPC Flow]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/vpc/). +- **Security** includes [WAF]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/waf/). +- **System Activity** includes [Linux]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/linux/) and [Windows]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/windows/). +- **Other** includes accounts for log types that are not contained in a specific category. For more information, refer to [Other log types]({{site.url}}{{site.baseurl}}/security-analytics/log-types-reference/other/). + + +## Creating custom log types + +When connecting to a data source not supported by a standard log type, create a custom log type by following these steps: + +1. In OpenSearch Dashboards, select **OpenSearch Plugins** > **Security Analytics**, and then select **Detectors** > **Log types**. +1. Select **Create log type**. +1. Enter a name and, optionally, a description for the log type. + + The log type name supports characters a--z (lowercase), 0--9, hyphens, and underscores. + {: .note } + +1. Select a category. The categories are listed in the [Supported log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/log-types/) documentation. +1. Select **Create log type** in the lower-right corner of the screen. The screen returns to the **Log types** page. The new log type appears in the list. Note that the source for the new log type indicates **Custom**. + +## About field mappings + +The log type specified when creating a detector determines which fields are available for mapping. For example, when **Windows logs** is selected, this parameter and the specific detection rules determine the list of detection field names available for the mapping. Similarly, the selected data source determines the list of log source field names that are available for the mapping. + +Security Analytics uses prepackaged Sigma rules for detector creation. It can automatically map important fields of a particular log type to the relevant fields in Sigma rules. The **Field Mappings** section shows fields that have been mapped automatically. In this section, you can customize, change, or add new field mappings. When a detector includes customized rules, you can manually map detector rule field names to log source field names. + +Because the system can automatically map field names, it is optional to manually map the fields when `ecs` fields exist in a document. Detector rules, however, require certain mappings in order to operate. These mapping depend on the detector rule. The more fields that can be mapped between detector fields and log source fields, the greater the accuracy of generated findings. + + + +## Log type APIs + +Use the log type APIs to perform custom log type operations using the REST API. For more information, refer to the [log type APIs]({{site.url}}{{site.baseurl}}/security-analytics/api-tools/log-type-api/) documentation. + + -* Select the log type **Name** to open the log type's details page. The **Details** tab is shown by default. This tab includes the log type's ID. You can also select the **Detection rules** tab to show all detection rules associated with the log type. -* In the **Actions** column, you can select the trash can icon ({::nomarkdown}<img src="{{site.url}}{{site.baseurl}}/images/alerting/trash-can-icon.png" class="inline-icon" alt="trash can icon"/>{:/}) to delete a custom log type (you cannot delete a standard OpenSearch-defined log type). Follow the prompts to confirm and safely remove the custom log type. -* Select **Create log type** in the upper-right corner of the screen to begin creating a custom log type. The **Create log type** page opens. Continue with the steps in the section that follows to create a custom log type. -* Using the **Category** and **Source** dropdowns, you can sort by the log type category or source, respectively. - -## Related articles -[Creating custom log types]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/custom-log-type/) diff --git a/_security-analytics/security.md b/_security-analytics/security.md index 7bbe147a..479c5150 100644 --- a/_security-analytics/security.md +++ b/_security-analytics/security.md @@ -1,13 +1,15 @@ --- layout: default -title: OpenSearch Security for Security Analytics +title: OpenSearch security for Security Analytics nav_order: 2 has_children: false --- -# OpenSearch Security for Security Analytics +<!-- vale off --> +# OpenSearch security for Security Analytics +<!-- vale on --> -You can use OpenSearch Security with Security Analytics to assign user permissions and manage the actions that users can and cannot perform. For example, you might want one group of users to be able to create, update, or delete detectors and another group of users to only view detectors. You may want still another group to be able to receive and acknowledge alerts but to be prevented from performing other tasks. The OpenSearch Security framework allows you to control the level of access users have to Security Analytics functionality. +You can use OpenSearch security with Security Analytics to assign user permissions and manage the actions that users can and cannot perform. For example, you might want one group of users to be able to create, update, or delete detectors and another group of users to only view detectors. You may want still another group to be able to receive and acknowledge alerts but to be prevented from performing other tasks. The OpenSearch Security framework allows you to control the level of access users have to Security Analytics functionality. --- ## Security Analytics system indexes @@ -28,7 +30,7 @@ If these roles don't meet your needs, mix and match individual Security Analytic You can use backend roles to configure fine-grained access to individual detectors based on roles. For example, backend roles can be assigned to users working in different departments of an organization so that they can view only those detectors owned by the departments in which they work. -First, make sure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/access-control/api#create-user). +First, make sure your users have the appropriate [backend roles]({{site.url}}{{site.baseurl}}/security/access-control/index/). Backend roles usually come from an [LDAP server]({{site.url}}{{site.baseurl}}/security/configuration/ldap/) or [SAML provider]({{site.url}}{{site.baseurl}}/security/configuration/saml/). However, if you use the internal user database, you can use the REST API to [add them manually]({{site.url}}{{site.baseurl}}/security/api/users/create-user/). Next, enable the following setting: @@ -93,6 +95,6 @@ However, because they have different backend roles, `alice` and `bob` cannot vie --- ## A note on using fine-grained access control with the plugin -When a trigger generates an alert, the detector configurations, the alert itself, and any notifications that are sent to a channel may include metadata describing the index being queried. By design, the plugin must extract the data and store it as metadata outside of the index. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security) (FLS) access controls are designed to protect the data in the index. But once the data is stored outside the index as metadata, users with access to the detector and monitor configurations, alerts, and their notifications will be able to view this metadata and possibly infer the contents and quality of data in the index, which would otherwise be concealed by DLS and FLS access control. +When a trigger generates an alert, the detector configurations, the alert itself, and any notifications that are sent to a channel may include metadata describing the index being queried. By design, the plugin must extract the data and store it as metadata outside of the index. [Document-level security]({{site.url}}{{site.baseurl}}/security/access-control/document-level-security/) (DLS) and [field-level security]({{site.url}}{{site.baseurl}}/security/access-control/field-level-security/) (FLS) access controls are designed to protect the data in the index. But once the data is stored outside the index as metadata, users with access to the detector and monitor configurations, alerts, and their notifications will be able to view this metadata and possibly infer the contents and quality of data in the index, which would otherwise be concealed by DLS and FLS access control. To reduce the chances of unintended users viewing metadata that could describe an index, we recommend that administrators enable role-based access control and keep these kinds of design elements in mind when assigning permissions to the intended group of users. See [Limit access by backend role](#advanced-limit-access-by-backend-role) for more information. diff --git a/_security-analytics/settings.md b/_security-analytics/settings.md index 20eb6aa1..ecbd845d 100644 --- a/_security-analytics/settings.md +++ b/_security-analytics/settings.md @@ -5,7 +5,9 @@ nav_order: 100 has_children: false --- +<!-- vale off --> # Security Analytics settings +<!-- vale on --> The Security Analytics plugin supports the following settings. All settings in this list are dynamic: @@ -49,7 +51,7 @@ The Security Analytics plugin supports the following settings. All settings in t `plugins.security_analytics.correlation_time_window` (Time value): Security Analytics generates correlations within a time window. This setting specifies the time window within which documents must be indexed into the index in order to be included in the same correlation. Default is 5 minutes. -`plugins.security_analytics.mappings.default_schema` (String): The default mapping schema used for configuring a field mapping for a security analytics detector. Default is `ecs`. +`plugins.security_analytics.mappings.default_schema` (String): The default mapping schema used for configuring a field mapping for a Security Analytics detector. Default is `ecs`. `plugins.security_analytics.threatintel.tifjob.update_interval` (Time value): The threat intelligence feature uses a job runner to periodically fetch new feeds. This setting is the rate at which the runner fetches and updates these new feeds. Default is 1440 minutes. diff --git a/_security-analytics/threat-intelligence/api/findings.md b/_security-analytics/threat-intelligence/api/findings.md new file mode 100644 index 00000000..12566310 --- /dev/null +++ b/_security-analytics/threat-intelligence/api/findings.md @@ -0,0 +1,267 @@ +--- +layout: default +title: Alerts and Findings API +parent: Threat intelligence APIs +grand_parent: Threat intelligence +nav_order: 50 +--- + + +# Alerts and Findings API + +The threat intelligence Alerts and Findings API retrieves information about alerts and findings from threat intelligence feeds. + + +--- + +## Get threat intelligence alerts + +Retrieves any alerts related to threat intelligence monitors. + +### Endpoints + +```json +GET /_plugins/_security_analytics/threat_intel/alerts +``` +{% include copy-curl.html %} + + +### Path parameters + +You can specify the following parameters when requesting an alert. + +Parameter | Description +:--- | :---- +`severityLevel` | Filter alerts by severity level. Optional. +`alertState` | Used to filter by alert state. Possible values are `ACTIVE`, `ACKNOWLEDGED`, `COMPLETED`, `ERROR`, or `DELETED`. Optional. +`sortString` | The string Security Analytics uses to sort the alerts. Optional. +`sortOrder` | The order used to sort the list of alerts. Possible values are `asc` or `desc`. Optional. +`missing` | A list of fields for which no alias mappings were found. Optional. +`size` | An optional maximum number of results to be returned in the response. Optional. +`startIndex` | The pagination indicator. Optional. +`searchString` | The alert attribute you want returned in the search. Optional. + +### Example request + +```json +GET /_plugins/_security_analytics/threat_intel/alerts +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "alerts": [{ + "id": "906669ee-56e8-4f40-a12f-ab4c274d7521", + "version": 1, + "schema_version": 0, + "seq_no": 0, + "primary_term": 1, + "trigger_id": "regwarg", + "trigger_name": "regwarg", + "state": "ACTIVE", + "error_message": null, + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "severity": "high", + "finding_ids": [ + "a9c10094-6139-42b3-81a8-867dffbe381d" + ], + "acknowledged_time": 1722038395105, + "last_updated_time": null, + "start_time": 1722038395105, + "end_time": null + }], + "total_alerts": 1 +} +``` + +### Response body fields + +A threat intelligence alert can have one of the following states. + +| State | Description | +| :---- | :--- | +| `ACTIVE` | The alert is ongoing and unacknowledged. Alerts remain in this state until they are acknowledged, the trigger associated with the alert is deleted, or the threat intelligence monitor is deleted entirely. | +| `ACKNOWLEDGED` | The alert is acknowledged, but the root cause of the alert has not been addressed. | +| `COMPLETED` | The alert is no longer ongoing. Alerts enter this state after the corresponding trigger evaluates to `false`. | +| `DELETED` | The monitor or trigger for the alert was deleted while the alert was active. | + +--- + +## Update Alerts Status API + +Updates the status of the specified alerts to `ACKNOWLEDGED` or `COMPLETED`. Only alerts in the `ACTIVE` state can be updated. + +### Endpoints + +```json +PUT /plugins/security_analytics/threat_intel/alerts/status +``` + +### Example requests + +The following example updates the status of the specified alerts to `ACKNOWLEDGED`: + +```json +PUT /plugins/security_analytics/threat_intel/alerts/status?state=ACKNOWLEDGED&alert_ids={alert-id},{alert-id} +``` + +The following example updates the status of the specified alerts to `COMPLETED`: + +```json +PUT /plugins/security_analytics/threat_intel/alerts/status?state=COMPLETED&alert_ids=alert_ids={alert-id},{alert-id} +``` + +### Example response + +```json +{ + "updated_alerts": [ + { + "id": "906669ee-56e8-4f40-a12f-ab4c274d7521", + "version": 1, + "schema_version": 0, + "seq_no": 2, + "primary_term": 1, + "trigger_id": "regwarg", + "trigger_name": "regwarg", + "state": "ACKNOWLEDGED", + "error_message": null, + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "severity": "high", + "finding_ids": [ + "a9c10094-6139-42b3-81a8-867dffbe381d" + ], + "acknowledged_time": 1722039091209, + "last_updated_time": 1722039091209, + "start_time": 1722038395105, + "end_time": null + }, + { + "id": "56e8-4f40-a12f-ab4c274d7521-906669ee", + "version": 1, + "schema_version": 0, + "seq_no": 2, + "primary_term": 1, + "trigger_id": "regwarg", + "trigger_name": "regwarg", + "state": "ACKNOWLEDGED", + "error_message": null, + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "severity": "high", + "finding_ids": [ + "a9c10094-6139-42b3-81a8-867dffbe381d" + ], + "acknowledged_time": 1722039091209, + "last_updated_time": 1722039091209, + "start_time": 1722038395105, + "end_time": null + } + ], + "failure_messages": [] +} +``` + + + +--- + +## Get findings + +Returns threat intelligence indicator of compromise (IOC) findings. When the threat intelligence monitor finds a malicious IOC during a data scan, a finding is automatically generated. + +### Endpoints + +```json +GET /_plugins/_security_analytics/threat_intel/findings/ +``` + +### Path parameters + +| Parameter | Description | +|:---------------|:--------------------------------------------------------------------------------------------| +| `sortString` | Specifies which string Security Analytics uses to sort the alerts. Optional. | +| `sortOrder` | The order used to sort the list of findings. Possible values are `asc` or `desc`. Optional. | +| `missing` | A list of fields for which there were no alias mappings found. Optional. | +| `size` | The maximum number of results to be returned in the response. Optional. | +| `startIndex` | The pagination indicator. Optional. | +| `searchString` | The alert attribute you want returned in the search. Optional. | + +### Example request + +```json +GET /_plugins/_security_analytics/threat_intel/findings/_search?size=3 +``` + +```json +{ + "total_findings": 10, + "ioc_findings": [ + { + "id": "a9c10094-6139-42b3-81a8-867dffbe381d", + "related_doc_ids": [ + "Ccp88ZAB1vBjq44wmTEu:windows" + ], + "ioc_feed_ids": [ + { + "ioc_id": "2", + "feed_id": "Bsp88ZAB1vBjq44wiDGo", + "feed_name": "my_custom_feed", + "index": "" + } + ], + "monitor_id": "B8p88ZAB1vBjq44wkjEy", + "monitor_name": "Threat intelligence monitor", + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "timestamp": 1722038394501, + "execution_id": "01cae635-93dc-4f07-9e39-31076b9535d1" + }, + { + "id": "8d87aee0-aaa4-4c12-b4e2-b4b1f4ec80f9", + "related_doc_ids": [ + "GsqI8ZAB1vBjq44wXTHa:windows" + ], + "ioc_feed_ids": [ + { + "ioc_id": "2", + "feed_id": "Bsp88ZAB1vBjq44wiDGo", + "feed_name": "my_custom_feed", + "index": "" + } + ], + "monitor_id": "B8p88ZAB1vBjq44wkjEy", + "monitor_name": "Threat intelligence monitor", + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "timestamp": 1722039165824, + "execution_id": "54899e32-aeeb-401e-a031-b1728772f0aa" + }, + { + "id": "2419f624-ba1a-4873-978c-760183b449b7", + "related_doc_ids": [ + "H8qI8ZAB1vBjq44woDHU:windows" + ], + "ioc_feed_ids": [ + { + "ioc_id": "2", + "feed_id": "Bsp88ZAB1vBjq44wiDGo", + "feed_name": "my_custom_feed", + "index": "" + } + ], + "monitor_id": "B8p88ZAB1vBjq44wkjEy", + "monitor_name": "Threat intelligence monitor", + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "timestamp": 1722039182616, + "execution_id": "32ad2544-4b8b-4c9b-b2b4-2ba6d31ece12" + } + ] +} + +``` diff --git a/_security-analytics/threat-intelligence/api/monitor.md b/_security-analytics/threat-intelligence/api/monitor.md new file mode 100644 index 00000000..ef078e99 --- /dev/null +++ b/_security-analytics/threat-intelligence/api/monitor.md @@ -0,0 +1,326 @@ +--- +layout: default +title: Monitor API +parent: Threat intelligence APIs +grand_parent: Threat intelligence +nav_order: 35 +--- + +# Monitor API + +You can use the threat intelligence Monitor API to create, search, and update [monitors]({{site.url}}{{site.baseurl}}/observing-your-data/alerting/monitors/) for your threat intelligence feeds. + + +--- +## Create or update a threat intelligence monitor + +Creates or updates a threat intelligence monitor. + +### Endpoints + +The `POST` method creates a new monitor. The `PUT` method updates a monitor. + +```json +POST _plugins/_security_analytics/threat_intel/monitors +PUT _plugins/_security_analytics/threat_intel/monitors/{monitor_id} +``` + +### Request body fields + +You can specify the following fields in the request body. + +| Field | Type | Description | +| :--- | :--- | :--- | +| `name` | String | The name of the monitor. Required. | +| `schedule` | Object | The schedule that determines how often the monitor runs. Required. | +| `schedule.period` | Object | Information about the frequency of the schedule. Required. | +| `schedule.period.interval` | Integer | The interval at which the monitor runs. Required. | +| `schedule.period.unit` | String | The unit of time for the interval. | +| `enabled` | Object | Information about the user who created the monitor. Required. | +| `user.backend_roles` | Array | The backend roles associated with the user. Optional. | +| `user.roles` | Array | The roles associated with the user. Optional. | +| `user.custom_attribute_names` | Array | Custom attribute names associated with the user. Optional. | +| `user.user_requested_tenant` | String | The tenant requested by the user. Optional. | +| `indices` | Array | The log data sources used for the monitor. Required. | +| `per_ioc_type_scan_input_list` | Array | A list of inputs to scan based on the indicator of compromise (IOC) types. Required. | +| `per_ioc_type_scan_input_list.ioc_type` | String | The type of IOC (for example, hashes). Required. | +| `per_ioc_type_scan_input_list.index_to_fields_map` | Object |The index field mappings that contain values for the given IOC type. Required. | +| `per_ioc_type_scan_input_list.index_to_fields_map.<index>` | Array | A list of fields contained in the specified index. Required. | +| `triggers` | Array | The trigger settings for alerts. Required. | +| `triggers.data_sources` | Array | A list of data sources associated with the trigger. Required. | +| `triggers.name` | String | The name of the trigger. Required. | +| `triggers.severity` | String | The severity level of the trigger (for example, high, medium, or low). Required. | + +### Example requests + +The following section provides example requests for the Monitor API. + + +#### Create a monitor + +```json +{ + "name": "Threat intel monitor", + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "name": "regwarg", + "severity": "high" + } + ] +} +``` + +### Update a monitor + +```json +{ + "name": "Threat intel monitor", + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "name": "regwarg", + "severity": "high" + } + ] +} +``` + + +### Example response + +```json +{ + "id": "B8p88ZAB1vBjq44wkjEy", + "name": 1, + "seq_no": 0, + "primary_term": 1, + "monitor": { + "id": "B8p88ZAB1vBjq44wkjEy", + "name": "Threat intel monitor", + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "ioc_types": [], + "actions": [], + "id": "afdd80cc-a669-4487-98a0-d84bea8e1e39", + "name": "regwarg", + "severity": "high" + } + ] + } +} +``` +--- + +## Delete a monitor + +Deletes an existing threat intelligence monitor. + +### Endpoints + +```json +DELETE /_plugins/_security_analytics/threat_intel/monitors/{monitor_id} +``` + +### Example request + +```json +DELETE /_plugins/_security_analytics/threat_intel/monitors/B8p88ZAB1vBjq44wkjEy +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "_id" : "B8p88ZAB1vBjq44wkjEy", + "_version" : 1 +} +``` + +## Search for a monitor + +Searches for an existing monitor using a query. The request body expects a search query. For query options, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + +### Example request + +The following example request using a match query with the monitor's ID to search for the monitor: + +```json +POST /_plugins/_security_analytics/detectors/_search +{ + "query": { + "match": { + "_id": "HMqq_5AB1vBjq44wpTIN" + } + } +} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 2.0, + "hits": [ + { + "_index": ".opendistro-alerting-config", + "_id": "HMqq_5AB1vBjq44wpTIN", + "_version": 1, + "_seq_no": 8, + "_primary_term": 1, + "_score": 2.0, + "_source": { + "id": "HMqq_5AB1vBjq44wpTIN", + "name": "Threat intel monitor", + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "ioc_types": [], + "actions": [], + "id": "63426758-c82d-4c87-a52c-f86ee6a8a06d", + "name": "regwarg", + "severity": "high" + } + ] + } + } + ] + } +} +``` \ No newline at end of file diff --git a/_security-analytics/threat-intelligence/api/source.md b/_security-analytics/threat-intelligence/api/source.md new file mode 100644 index 00000000..01197c6b --- /dev/null +++ b/_security-analytics/threat-intelligence/api/source.md @@ -0,0 +1,596 @@ +--- +layout: default +title: Source API +parent: Threat intelligence APIs +grand_parent: Threat intelligence +nav_order: 50 +--- + +# Source API + +The threat intelligence Source API updates and returns information about tasks related to threat intelligence source configurations. + +## Create or update a threat intelligence source + +Creates or updates a threat intelligence source and loads indicators of compromise (IOCs) from that source. + +You can create sources of type `S3_CUSTOM` and `IOC_UPLOAD`. The `URL_DOWNLOAD` type is reserved for built-in feeds that OpenSearch creates automatically and cannot be created using this API. For more information, see [URL_DOWNLOAD type sources](#url_download-type-sources). + +### Endpoints + +```json +POST _plugins/_security_analytics/threat_intel/sources +PUT _plugins/_security_analytics/threat_intel/sources/{source_id} +``` + +### Request body fields + +| Field | Type | Description | +| :--- | :--- | :---- | +| `type` | String | The type of threat intelligence source. Valid values are `S3_CUSTOM` and `IOC_UPLOAD`. | +| `name` | String | The name of the threat intelligence source. | +| `format` | String | The format of the threat intelligence data, such as `STIX2`. | +| `description` | String | A description of the threat intelligence source. | +| `enabled` | Boolean | Indicates whether the scheduled refresh of IOCs from the source is enabled. | +| `ioc_types` | Array of strings | The `STIX2` types of IOCs that the source supports, for example, `hashes`, `domain-name`, `ipv4-addr`, or `ipv6-addr`. | +| `source` | Object | The source information for the threat intelligence data. | +| `source.ioc_upload` | Object | Information about the IOC upload. Applicable to the `IOC_UPLOAD` type. | +| `source.ioc_upload.file_name` | String | The name of the file containing IOCs, such as `test`. Applicable to the`IOC_UPLOAD` type. | +| `source.ioc_upload.iocs` | Array of objects | A list of IOCs in `STIX2` format. Applicable to the `IOC_UPLOAD` type. | +| `source_config.source.s3` | Object | Information about the Amazon Simple Storage Service (Amazon S3) source. Applicable to the `S3_CUSTOM` type. | +| `source_config.source.s3.bucket_name` | String | The name of the S3 bucket, such as `threat-intel-s3-test-bucket`. Applicable to the `S3_CUSTOM` type. | +| `source_config.source.s3.object_key` | String | The key for the object in the S3 bucket, such `alltypess3object`. Applicable to the `S3_CUSTOM` type. | +| `source_config.source.s3.region` | String | The AWS Region in which the S3 bucket is located. Example: `us-west-2`. Applicable to the `S3_CUSTOM` type. | +| `source_config.source.s3.role_arn` | String | The Amazon Resource Name (ARN) of the role used to access the S3 bucket, such as `arn:aws:iam::248279774929:role/threat_intel_s3_test_role`. Applicable to the `S3_CUSTOM` type. | +| `source_config.source.url_download` | Object | Information about the URL from which IOCs are downloaded. Applicable to the `URL_DOWNLOAD` type. | +| `source_config.source.url_download.url` | String | The URL from which IOCs are downloaded. Only the `http` and `https` protocols are supported. Applicable to the `URL_DOWNLOAD` type. | +| `source_config.source.url_download.feed_format` | String | The format of the downloaded feed. The only supported value is `csv`. Applicable to the `URL_DOWNLOAD` type. | +| `source_config.source.url_download.has_csv_header_field` | Boolean | Whether the first row of the CSV file is a header row. Default is `false`. Applicable to the `URL_DOWNLOAD` type. | +| `source_config.source.url_download.csv_ioc_value_colum_num` | Integer | The zero-based index of the CSV column containing the IOC value. Applicable to the `URL_DOWNLOAD` type. | + +#### IOC fields (STIX2) + +The following fields modify the `ioc_types` option. + +| Field | Type | Description | +| :--- | :---- | :---- | +| `id` | String | A unique identifier for the IOC, such as `1`. | +| `name` | String | A human-readable name for the IOC, such as `ioc-name`. | +| `type` | String | The type of IOC, such as `hashes`. | +| `value` | String | The value of the IOC, which can be a hash value, such as `gof`. | +| `severity` | String | The severity level of the IOC. Example: `thvvz`. | +| `created` | Integer/String | The timestamp indicating when the IOC was created, either in UNIX epoch format or ISO_8601 format, for example, `1719519073` or `2024-06-20T01:06:20.562008Z`. | +| `modified` | Integer/String | The timestamp indicating when the IOC was last modified, either in UNIX epoch format or ISO_8601 format, for example, `1719519073` or `2024-06-20T01:06:20.562008Z.` | +| `description` | String | A description of the IOC. | +| `labels` | Array of strings | Any labels or tags associated with the IOC. | +| `feed_id` | String | A unique identifier for the feed to which the IOC belongs. | +| `spec_version` | String | The specification version used for the IOC. | +| `version` | Integer | A version number for the IOC. | + +### Response body fields + +| Field | Data type | Description | +| :---- | :--- |:----- | +| `_id` | String | The unique identifier for the threat intelligence source. | +| `_version` | Integer | The version number of the threat intelligence source. | +| `source_config` | Object | The configuration details of the threat intelligence source. | +| `source_config.name` | String | The name of the threat intelligence source. | +| `source_config.format` | String | The format of the threat intelligence data. | +| `source_config.type` | String | The type of the threat intelligence source. | +| `source_config.ioc_types` | Array of strings | The types of IOCs supported by the source. | +| `source_config.description` | String | A description of the threat intelligence source. | +| `source_config.created_by_user` | String or null | The user who created the threat intelligence source. | +| `source_config.created_at` | String (DateTime) | The date and time when the threat intelligence source was created. | +| `source_config.source` | Object | Contains information about the source of the threat intelligence data. | +| `source_config.source.ioc_upload` | Object | Information about the IOC upload. | +| `source_config.source.ioc_upload.file_name` | String | The name of the uploaded file. Example: `test`. | +| `source_config.source.ioc_upload.iocs` | Array of objects | Any additional information about the IOC upload. When the IOC is stored successfully, this appears as an empty array. | +| `source_config.enabled` | Boolean | Indicates whether the threat intelligence source is enabled. | +| `source_config.enabled_time` | String or null | The date and time when the source was enabled. | +| `source_config.last_update_time` | String (DateTime) | The date and time when the threat intelligence source was last updated. | +| `source_config.schedule` | String or null | The schedule for the threat intelligence source. | +| `source_config.state` | String | The current state of the threat intelligence source. | +| `source_config.refresh_type` | String | The type of refresh applied to the source. | +| `source_config.last_refreshed_user` | String or null | The user who last refreshed the source. | +| `source_config.last_refreshed_time` | String (DateTime) | The date and time when the source was last refreshed. | + +### Example requests + +The following example requests show you how to use the Source API. + +#### IOC_UPLOAD type + +```json +POST _plugins/_security_analytics/threat_intel/sources/ +{ + "type": "IOC_UPLOAD", + "name": "my_custom_feed", + "format": "STIX2", + "description": "this is the description", + "store_type": "OS", + "enabled": "false", + "ioc_types": [ + "hashes" + ], + "source": { + "ioc_upload": { + "file_name": "test", + "iocs": [ + { + "id": "1", + "name": "uldzafothwgik", + "type": "hashes", + "value": "gof", + "severity": "thvvz", + "created": 1719519073, + "modified": 1719519073, + "description": "first one here", + "labels": [ + "ik" + ], + "feed_id": "jl", + "spec_version": "gavvnespe", + "version": -4356924786557562654 + }, + { + "id": "2", + "name": "uldzafothwgik", + "type": "hashes", + "value": "example-has00001", + "severity": "thvvz", + "created": "2024-06-20T01:06:20.562008Z", + "modified": "2024-06-20T02:06:20.56201Z", + "description": "first one here", + "labels": [ + "ik" + ], + "feed_id": "jl", + "spec_version": "gavvnespe", + "version": -4356924786557562654 + } + ] + } + } +} +``` +{% include copy-curl.html %} + +<!-- vale off --> +#### S3_CUSTOM type source +<!-- vale on --> + +```json +POST _plugins/_security_analytics/threat_intel/sources/ +{ + "type": "S3_CUSTOM", + "name": "example-ipv4-from-SAP-account", + "format": "STIX2", + "store_type": "OS", + "enabled": "true", + "schedule": { + "interval": { + "start_time": 1717097122, + "period": "10", + "unit": "DAYS" + } + }, + "source": { + "s3": { + "bucket_name": "threat-intel-s3-test-bucket", + "object_key": "alltypess3object", + "region": "us-west-2", + "role_arn": "arn:aws:iam::248279774929:role/threat_intel_s3_test_role" + } + }, + "ioc_types": [ + "domain-name", + "ipv4-addr" + ] +} +``` +{% include copy-curl.html %} + +### Example responses + +The following example responses show what OpenSearch returns after a successful request. + + +#### IOC_UPLOAD type + +```json +{ + "_id": "2c0u7JAB9IJUg27gcjUp", + "_version": 2, + "source_config": { + "name": "my_custom_feed", + "format": "STIX2", + "type": "IOC_UPLOAD", + "ioc_types": [ + "hashes" + ], + "description": "this is the description", + "created_by_user": null, + "created_at": "2024-07-25T23:16:25.257697Z", + "source": { + "ioc_upload": { + "file_name": "test", + "iocs": [] + } + }, + "enabled": false, + "enabled_time": null, + "last_update_time": "2024-07-25T23:16:26.011774Z", + "schedule": null, + "state": "AVAILABLE", + "refresh_type": "FULL", + "last_refreshed_user": null, + "last_refreshed_time": "2024-07-25T23:16:25.522735Z" + } +} +``` + +<!-- vale off --> +#### S3_CUSTOM type source +<!-- vale on --> + +```json +{ + "id": "rGO5zJABLVyN2kq1wbFS", + "version": 206, + "name": "example-ipv4-from-SAP-account", + "format": "STIX2", + "type": "S3_CUSTOM", + "ioc_types": [ + "domain-name", + "ipv4-addr" + ], + "created_by_user": { + "name": "admin", + "backend_roles": [], + "roles": [ + "security_manager", + "all_access" + ], + "custom_attribute_names": [] + }, + "created_at": "2024-07-19T20:40:44.114Z", + "source": { + "s3": { + "bucket_name": "threat-intel-s3-test-bucket", + "object_key": "alltypess3object", + "region": "us-west-2", + "role_arn": "arn:aws:iam::248279774929:role/threat_intel_s3_test_role" + } + }, + "enabled": true, + "enabled_time": "2024-07-19T20:40:44.114Z", + "last_update_time": "2024-07-25T20:58:18.213Z", + "schedule": { + "interval": { + "start_time": 1717097122, + "period": 10, + "unit": "Days" + } + }, + "state": "AVAILBLE", + "refresh_type": "FULL", + "last_refreshed_user": { + "name": "admin", + "backend_roles": [], + "roles": [ + "security_manager", + "all_access" + ], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "last_refreshed_time": "2024-07-25T20:58:17.131Z" +} +``` + +--- + +## URL_DOWNLOAD type sources + +A `URL_DOWNLOAD` source downloads IOCs from an HTTP or HTTPS URL. OpenSearch creates these sources automatically for built-in threat intelligence feeds, so you cannot create one using the Source API. A request that specifies `URL_DOWNLOAD` in a `POST` request returns the following error: + +``` +URL_DOWNLOAD source type cannot be created via the REST API. It is reserved for internal use only. +``` + +To list the `URL_DOWNLOAD` sources in your cluster, search for them by type: + +```json +POST _plugins/_security_analytics/threat_intel/sources/_search +{ + "query": { + "match": { + "source_config.type": "URL_DOWNLOAD" + } + } +} +``` +{% include copy-curl.html %} + +The `source.url_download` object in the response describes the feed: + +```json +{ + "_id": "alienvault_reputation_ip_database", + "_version": 2, + "source_config": { + "name": "Alienvault IP Reputation", + "format": "STIX2", + "type": "URL_DOWNLOAD", + "description": "Alienvault IP Reputation threat intelligence feed managed by AlienVault", + "created_by_user": null, + "source": { + "url_download": { + "url": "https://reputation.alienvault.com/reputation.generic", + "feed_format": "csv", + "has_csv_header_field": false, + "csv_ioc_value_colum_num": 0 + } + }, + "enabled": true, + "enabled_for_scan": true, + "ioc_types": [ + "ipv4-addr" + ] + } +} +``` + +Only the `csv` feed format is supported for `URL_DOWNLOAD` sources. A source configured with any other format fails to refresh with an `unsupported feed format for url download` error. +{: .note} + +### Activating or deactivating a URL_DOWNLOAD source + +Because `URL_DOWNLOAD` sources are built in, the only field you can change is `enabled_for_scan`, which activates or deactivates the feed. Update requests that change any other field return an `Unsupported Threat intel Source Config Type passed` error. You must include the `schedule` field in the request, otherwise the request fails validation. + +The following request deactivates a built-in feed: + +```json +PUT _plugins/_security_analytics/threat_intel/sources/alienvault_reputation_ip_database +{ + "type": "URL_DOWNLOAD", + "name": "Alienvault IP Reputation", + "format": "STIX2", + "description": "Alienvault IP Reputation threat intelligence feed managed by AlienVault", + "schedule": { + "interval": { + "start_time": 1786030387187, + "period": 1, + "unit": "DAYS" + } + }, + "source": { + "url_download": { + "url": "https://reputation.alienvault.com/reputation.generic", + "feed_format": "csv", + "has_csv_header_field": false, + "csv_ioc_value_colum_num": 0 + } + }, + "ioc_types": [ + "ipv4-addr" + ], + "enabled_for_scan": false +} +``` +{% include copy-curl.html %} + +To activate the feed again, send the same request with `enabled_for_scan` set to `true`. + +You cannot delete a `URL_DOWNLOAD` source. A delete request returns a `Cannot delete built-in tif source config` error. +{: .note} + +--- + +## Get threat intelligence source configuration details + +Retrieves the threat intelligence source configuration details. + +### Endpoints + + +```json +GET /_plugins/_security_analytics/threat_intel/sources/{source-id} +``` + +### Example request + +```json +GET /_plugins/_security_analytics/threat_intel/sources/{source-id} +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "_id": "a-jnfjkAF_uQjn8Weo4", + "_version": 2, + "source_config": { + "name": "my_custom_feed_2", + "format": "STIX2", + "type": "S3_CUSTOM", + "ioc_types": [ + "ipv4_addr", + "hashes" + ], + "description": "this is the description", + "created_by_user": null, + "created_at": "2024-06-27T00:52:56.373Z", + "source": { + "s3": { + "bucket_name": "threat-intel-s3-test-bucket", + "object_key": "bd", + "region": "us-west-2", + "role_arn": "arn:aws:iam::540654354201:role/threat_intel_s3_test_role" + } + }, + "enabled": true, + "enabled_time": "2024-06-27T00:52:56.373Z", + "last_update_time": "2024-06-27T00:52:57.824Z", + "schedule": { + "interval": { + "start_time": 1717097122, + "period": 1, + "unit": "Days" + } + }, + "state": "AVAILABLE", + "refresh_type": "FULL", + "last_refreshed_user": null, + "last_refreshed_time": "2024-06-27T00:52:56.533Z" + } +} +``` +--- + +## Search for a threat intelligence source + +Searches for threat intelligence source matches based on the search query. The request body expects a search query. For query options, see [Query DSL]({{site.url}}{{site.baseurl}}/query-dsl/). + + +### Endpoints + +```json +POST /_plugins/_security_analytics/threat_intel/sources/_search +``` + +### Example request + +```json +POST /_plugins/_security_analytics/threat_intel/sources/_search +{ + "query": { + "match": { + "source_config.type": "S3_CUSTOM" + } + } +} +``` +{% include copy-curl.html %} + +### Example response + +```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": ".opensearch-sap--job", + "_id": "YEAuV5ABx0lQn6qhY5C1", + "_version": 2, + "_seq_no": 1, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "source_config": { + "name": "my_custom_feed_2", + "format": "STIX2", + "type": "S3_CUSTOM", + "description": "this is the description", + "created_by_user": null, + "source": { + "s3": { + "bucket_name": "threat-intelligence-s3-test-bucket", + "object_key": "bd", + "region": "us-west-2", + "role_arn": "arn:aws:iam::540654354201:role/threat_intel_s3_test_role" + } + }, + "created_at": 1719449576373, + "enabled_time": 1719449576373, + "last_update_time": 1719449577824, + "schedule": { + "interval": { + "start_time": 1717097122, + "period": 1, + "unit": "Days" + } + }, + "state": "AVAILABLE", + "refresh_type": "FULL", + "last_refreshed_time": 1719449576533, + "last_refreshed_user": null, + "enabled": true, + "ioc_types": [ + "ip", + "hash" + ] + } + } + } + ] + } +} +``` + +--- + +## Delete Threat Intelligence Source API + +Deletes a threat intelligence source. + +### Endpoints + +```json +DELETE /_plugins/_security_analytics/threat_intel/sources/{source-id} +``` + +### Example request + +```json +DELETE /_plugins/_security_analytics/threat_intel/sources/2c0u7JAB9IJUg27gcjUp +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "_id": "2c0u7JAB9IJUg27gcjUp" +} +``` +--- + +## Refresh the source + +Downloads any IOCs from the threat intelligence source. Supports the `S3_CUSTOM` and `URL_DOWNLOAD` type sources. Refreshing an `IOC_UPLOAD` source is not supported because its IOCs are supplied directly in the create request. + +### Endpoints + +```json +POST /_plugins/_security_analytics/threat_intel/sources/{source-id}/_refresh +``` + +### Example request + +```json +POST /_plugins/_security_analytics/threat_intel/sources/IJAXz4QBrmVplM4JYxx_/_refresh +``` +{% include copy-curl.html %} + +### Example response + +```json +{ + "acknowledged": true +} +``` diff --git a/_security-analytics/threat-intelligence/api/threat-intel-api.md b/_security-analytics/threat-intelligence/api/threat-intel-api.md new file mode 100644 index 00000000..c87133b7 --- /dev/null +++ b/_security-analytics/threat-intelligence/api/threat-intel-api.md @@ -0,0 +1,14 @@ +--- +layout: default +title: Threat intelligence APIs +nav_order: 50 +parent: Threat intelligence +has_children: true +has_toc: true +--- + +# Threat intelligence APIs + +OpenSearch provides several APIs that allow you to set up and interact with your threat intelligence feeds. + + diff --git a/_security-analytics/threat-intelligence/getting-started.md b/_security-analytics/threat-intelligence/getting-started.md new file mode 100644 index 00000000..ead605ab --- /dev/null +++ b/_security-analytics/threat-intelligence/getting-started.md @@ -0,0 +1,138 @@ +--- +layout: default +title: Getting started +parent: Threat intelligence +nav_order: 41 +--- + +# Getting started with threat intelligence + +To get started with threat intelligence, you'll need to set up your threat intelligence sources and set up monitors to scan your log sources. The following tutorial shows you how to get started using OpenSearch Dashboards. Alternatively, you can use the [API]({{site.url}}{{site.baseurl}}/security-analytics/threat-intelligence/api/threat-intel-api/). + +## Threat intelligence view + +To access threat intelligence, log in to OpenSearch Dashboards and select **Security Analytics** > **Threat Intelligence**. + +In the threat intelligence view, you can access the following tabs: + +- **Threat intel sources**: Shows a list of all active and inactive threat intelligence sources, including the default IP reputation feed, [AlienVault OTX](https://otx.alienvault.com/), which comes prepackaged when downloading OpenSearch. +- **Scan configuration**: Shows an overview of your scan configuration, including the configured **Log sources**, **Scan schedule**, and **Alert triggers**. From the **Actions** dropdown list, you can also **Stop scan**, **Edit scan configuration**, or **Delete scan configuration**. + + +## Step 1: Set up threat intelligence sources + +To add a threat intelligence source, select **Add threat intel source** from the threat intelligence page. The **Add custom threat intelligence source** page appears. + +On the threat intelligence source page, add the following information: + +- **Name**: A name for the source. +- **Description**: An optional description of the source. +- **Threat intel source type**: The source type determines where the `STIX2` file is stored. You can choose one of the following options: + - **Remote data store location**: Connects to a custom data store. The only supported type is `S3_SOURCE`. This setting also gives you the ability to set a download schedule, where OpenSearch downloads the newest `STIX2` file from the data store. For more information, see [S3_SOURCE connection details](#s3_source-connection-information). + - **Local file upload**: Uploads a custom threat intelligence IOC file. Custom files cannot be downloaded based on a schedule and must be uploaded manually in order to update the IOCs. For more information, see [Local file upload](#local-file-upload). +- **Types of malicious indicators**: Determines the types of malicious IOCs to pull from the `STIX2` file. The following IOCs are supported: + - IPv4-Address + - IPv6-Address + - Domains + - File hash + +After all the relevant information has been entered, select **Add threat intel source**. + +### Local file upload + +Local files uploaded as the threat intelligence source must use the following specifications: + +- Upload as a JSON file in the `STIX2` format. For an example `STIX2` file, download [this file]({{site.url}}{{site.baseurl}}/assets/examples/all-ioc-type-examples.json), which contains example formatting for all supported IOC types. +- Be less than 500 kB. + + +<!-- vale off --> +### S3_SOURCE connection information +<!-- vale on --> + +When using the `S3_SOURCE` as a remote store, the following connection information must be provided: + +- **IAM Role ARN**: The Amazon Resource Name (ARN) for an AWS Identity and Access Management (IAM) role. When using the AWS OpenSearch Service, the role ARN needs to be in the same account as the OpenSearch domain. For more information about adding a new role for the AWS OpenSearch Service, see [Add service ARN](#add-aws-opensearch-service-arn). +- **S3 bucket directory**: The name of the Amazon Simple Storage Service (Amazon S3) bucket in which the `STIX2` file is stored. To access an S3 bucket in a different AWS account, see the [Cross-account S3 bucket connection](#cross-account-s3-bucket-connection) section for more details. +- **Specify a file**: The object key for the `STIX2` file in the S3 bucket. +- **Region**: The AWS Region for the S3 bucket. + +You can also set the **Download schedule**, which determines to where OpenSearch downloads an updated `STIX2` file from the connected S3 bucket. The default interval is once a day. Only daily intervals are supported. + +Alternatively, you can check the **Download on demand** option, which prevents new data from the bucket from being automatically downloaded. + +<!-- vale off --> +#### Add AWS OpenSearch Service ARN +<!-- vale on --> + +If you're using the AWS OpenSearch Service, create a new ARN role with a custom trust policy. For instructions on how to create the role, see [Creating a role for an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#roles-creatingrole-service-console). + +When creating the role, customize the following settings: + +- Add the following custom trust policy: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Service": [ + "opensearchservice.amazonaws.com" + ] + }, + "Action": "sts:AssumeRole" + } + ] +} +``` + +- On the Permissions policies page, add the `AmazonS3ReadOnlyAccess` permission. + + +#### Cross-account S3 bucket connection + +Because the role ARN needs to be in the same account as the OpenSearch domain, a trust policy needs to be configured that allows the OpenSearch domain to download from S3 buckets from the same account. + +To download from an S3 bucket in another account, the trust policy for that bucket needs to give the role ARN permission to read from the object, as shown in the following example: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::123456789012:role/account-1-threat-intel-role" + }, + "Action": "s3:*", + "Resource": "arn:aws:s3:::account-2-threat-intel-bucket/*" + } + ] +} +``` + +## Step 2: Set up scanning for your log sources + +You can configure threat intelligence monitors to scan your aliases and data streams. The monitor scans for newly ingested data from your indexes and matches that data against any IOCs present in the threat intelligence sources. The scan applies to all threat intelligence sources added to OpenSearch. By default, the scan runs once each minute. + +To add or edit a scan configuration: + +1. From the threat intelligence view, select **Add scan configuration** or **Edit scan configuration**. +2. Select the indexes or aliases to scan. +3. Select the **fields** from your indexes or aliases to scan based on their IOC type. For example, if an alias has two fields called `src_ip` and `dst_ip` that contain `ipv4` addresses, then those fields must be entered into the `ipv4-addr` section of the monitor request. +4. Determine a **Scan schedule** for the indicated indexes or aliases. By default, OpenSearch scans for IOCs once each minute. +5. Set up any alert triggers and trigger conditions. You can add multiple triggers: + 1. Add a name for the trigger. + 2. Choose an indicator type. The indicator type matches the IOC type. + 3. Select a severity for the alert. + 4. Select whether to send a notification when the alert is triggered. When enabled, you can customize which channels the notification is sent to as well as the notification message. The notification message can be customized using a [Mustache template](https://mustache.github.io/mustache.5.html). +6. Once your settings have been entered, select **Save and start monitoring**. + +When malicious IOCs are found, OpenSearch creates **findings**, which provide information about the threat. You can also configure triggers to create alerts, which send notifications to configured webhooks or endpoints. + + +## Viewing alerts and findings + +You can view the alerts and findings generated by threat intelligence monitors to analyze which malicious indicators have occurred in their security logs. To view alerts or findings, select **View findings** or **View alerts** from the threat intelligence view. diff --git a/_security-analytics/threat-intelligence/index.md b/_security-analytics/threat-intelligence/index.md new file mode 100644 index 00000000..e70e61cf --- /dev/null +++ b/_security-analytics/threat-intelligence/index.md @@ -0,0 +1,18 @@ +--- +layout: default +title: Threat intelligence +nav_order: 40 +has_children: true +redirect_from: + - /security-analytics/threat-intelligence/ +--- + +# Threat intelligence + +Threat intelligence in Security Analytics offers the capability to integrate your threat intelligence feeds. Feeds comprise indicators of compromise (IOCs), which search for malicious indicators in your data by setting up threat intelligence monitors. These monitors generate findings and can send notifications when malicious IPs, domains, or hashes from the threat intelligence feeds match your data. + + +You can interact with threat intelligence in the following ways: + +- Threat intelligence APsI: To configure threat intelligence using API operations, see [Threat Intelligence APIs]({{site.url}}{{site.baseurl}}/security-analytics/threat-intelligence/api/threat-intel-api/). +- OpenSearch Dashboards: To configure and use threat intelligence through the OpenSearch Dashboards interface, see [Getting started]({{site.url}}{{site.baseurl}}/security-analytics/threat-intelligence/getting-started/). \ No newline at end of file diff --git a/_security-analytics/usage/alerts.md b/_security-analytics/usage/alerts.md index a4a4541f..86f7bbb9 100644 --- a/_security-analytics/usage/alerts.md +++ b/_security-analytics/usage/alerts.md @@ -7,41 +7,54 @@ nav_order: 46 # Working with alerts -The Alerts window includes features for viewing and working with alerts. The two main features are: -* The bar graph with alert information arranged by count, date, and alert status or alert severity. -* The Alerts list arranged by time of the alert, the alert's trigger name, which detector triggered it, and other details. +The **Alerts** window provides features for viewing and managing alerts. It consists of: -You can select the **Refresh** button at any time to refresh information on the Alerts page. +- A bar graph displaying alert counts, dates, and status or severity levels. +- Two tabs: + - **Findings**: Lists detector-generated alerts, showing details such as alert time, trigger name, and the detector that triggered the alert. + - **Correlations**: Lists correlation-rule-generated alerts, showing details such as alert time, trigger name, and the correlation rule that triggered the alert. + +You can select the **Refresh** button to refresh information on the **Alerts** page. --- -## The Alerts graph -The Alerts graph can display alerts by their status or severity. Use the **Group by** dropdown list to specify either Alert status or Alert severity. +## Alerts graph -To specify the date range you would like the graph to display, first select the calendar dropdown arrow. The date selector window opens. -<br><img src="{{site.url}}{{site.baseurl}}/images/Security/find-date-pick.png" alt="Date selector for findings graph" width="55%"> +The **Alerts** graph displays alerts by their status or severity. Use the **Group by** dropdown menu to specify either **Alert status** or **Alert severity**. -You can use the **Quick select** settings to specify an exact window of time. -* Select either **Last** or **Next** in the first dropdown list to set the window of time behind the current setting or ahead of the current setting. -* Select a number in the second dropdown list to define a value for the range. -* Select a unit of time in the third dropdown list. Available options are seconds, minutes, hours, days, weeks, months, and years. -Select the **Apply** button to apply the range of dates to the graph. Information on the graph changes accordingly. +To specify a date range, select the calendar icon to activate the dropdown menu. The date selector window opens. An example window is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/quickset.png" alt="Quick select settings example" width="40%"> +![Date selector for findings graph]({{site.url}}{{site.baseurl}}/images/Security/find-date-pick.png){: width="55%" } -You can use the left and right arrows to move the window of time behind the current range of dates or ahead of the current range of dates. When you use these arrows, the start date and end date appear in the date range field. You can then select each one to set an absolute, relative, or current date and time. For absolute and relative changes, select the **Update** button to apply the changes. +You can use the **Quick select** settings to specify a date range: +* Select either **Last** or **Next** from the first dropdown menu to set the date range to either behind the current setting or ahead of the current setting. +* Select a number from the second dropdown menu to define a value for the range. +* Select a unit of time from the third dropdown menu. Available options are seconds, minutes, hours, days, weeks, months, and years. +* Select the **Apply** button to apply the time range to the graph. The graph is immediately updated. -<img src="{{site.url}}{{site.baseurl}}/images/Security/date-pick.png" alt="Altering date range" width="55%"> +An example window is shown in the following image. -As an alternative, you can select an option in the **Commonly used** section (see the preceding image of the calendar dropdown list) to conveniently set a window of time. Options include date ranges such as **Today**, **Yesterday**, **this week**, and **week to date**. +![Quick select settings example]({{site.url}}{{site.baseurl}}/images/Security/quickset.png){: width="40%" } -When one of the commonly used windows of time is selected, you can select the **Show dates** label in the date range field to populate the range of dates. Following that, you can select either the start date or end date to specify by an absolute, relative, or current date and time setting. For absolute and relative changes, select the **Update** button to apply the changes. +You can use the left and right arrows in the upper-left corner to shift the time range backward or forward, respectively. When you use these arrows, the start date and end date appear in the date range field. You can then select each one to set an absolute, relative, or current date and time. For absolute and relative changes, select the **Update** button to apply the changes. -As one more alternative, you can select an option from the **Recently used date ranges** section to go back to a previous setting. +An example window is shown in the following image. + +![Altering date range]({{site.url}}{{site.baseurl}}/images/Security/date-pick.png){: width="55%" } + +As an alternative, you can select an option in the **Commonly used** section (see the preceding image of the calendar dropdown menu) to conveniently set a date range. Options include **Today**, **Yesterday**, **this week**, and **week to date**. + +When a commonly used date range is selected, you can select the **Show dates** label in the date range field to populate the ranges. You can then select either the start date or end date to specify an absolute, relative, or current date and time setting. For absolute and relative changes, select the **Update** button to apply the changes. + +You can also select an option from the **Recently used date ranges** section to revert to a previous setting. --- -## The Alerts list -The Alerts list displays all findings according to the time when the alert was triggered, the alert's trigger name, the detector that triggered the alert, the alert status, and alert severity. -Use the **Alert severity** dropdown list to filter the list of alerts by severity. Use the **Status** dropdown list to filter the list by alert status. +## Alerts list +The **Alerts list** displays all alerts, with two tabs for different types of alerts: + +- **Findings**: The **Alerts list** displays all findings according to the time when the alert was triggered, the alert's trigger name, the detector that triggered the alert, the alert status, and the alert severity. +- **Correlations**: The **Alerts list** displays all correlations, including the correlation rule and time window, the alert's trigger name, the correlation rule name that triggered the alert, the alert status, and the alert severity. + +Use the **Alert severity** dropdown menu to filter the list of alerts by severity. Use the **Status** dropdown menu to filter the list by alert status. diff --git a/_security-analytics/usage/correlation-graph.md b/_security-analytics/usage/correlation-graph.md index db421831..f8347eff 100644 --- a/_security-analytics/usage/correlation-graph.md +++ b/_security-analytics/usage/correlation-graph.md @@ -10,18 +10,18 @@ nav_order: 45 The correlation graph is a security findings knowledge graph. It provides a visualization of information generated by the correlation engine and allows you to focus on specific correlations and inspect them in greater detail. Information on the graph includes findings by log type, the severity levels for the findings, the correlations drawn between findings, and the relevance of the correlations, among other details. You can also manipulate the graph to gain further insight into specific events of interest. This includes filtering findings by date and time, zooming in on the relationship between specific findings and their correlations, and filtering by log type and severity level. Use this section to learn more about using the graph. --- -## Acccessing the graph +## Accessing the graph Begin by selecting **Security Analytics** in the OpenSearch Dashboards main menu. Then select **Correlations** from the Security Analytics menu on the left side of the screen. The **Correlations** page is displayed, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-graph.png" alt="The correlation graph" width="85%"> +![The correlation graph]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-graph.png){: width="85%" } --- ## Interpreting the graph The graph displays findings as nodes with colored borders expressing their severity level. A three-letter abbreviation inside the node indicates the log type. The lines that connect the findings represent the correlations between them. A heavy line indicates a strong correlation, while a light line shows a weaker connection. -<img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-graph-detail.png" alt="The correlation graph" width="40%"> +![The correlation graph]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-graph-detail.png){: width="40%" } --- ## Using the graph @@ -34,11 +34,11 @@ You can control which findings are displayed on the graph by filtering by severi You can focus on a particular area of the graph to look at correlations associated with a specific finding by selecting the finding on the graph. The graph then changes to show only the selected finding along with the constellation of findings correlated to it, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-drill-dn.png" alt="Zooming in on a specific finding on the graph" width="40%"> +![Zooming in on a specific finding on the graph]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-drill-dn.png){: width="40%" } After narrowing the focus of the graph, informational cards for each of the findings appear on the right-hand side of the screen. The selected finding appears at the top of the cards, and the correlated findings are listed underneath it in order of their correlation relevance, represented by a correlation score, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-cards.png" alt="Zooming in on a specific finding on the graph" width="30%"> +![Zooming in on a specific finding on the graph]({{site.url}}{{site.baseurl}}/images/Security/sec-analytics/corr-cards.png){: width="30%" } You can select one of the correlated findings on the graph to shift the perspective of the correlation relationships. This sends the newly selected finding to the top of the informational cards and displays the other findings as relative correlations. diff --git a/_security-analytics/usage/detectors.md b/_security-analytics/usage/detectors.md index bd7868bc..6d050557 100644 --- a/_security-analytics/usage/detectors.md +++ b/_security-analytics/usage/detectors.md @@ -9,7 +9,7 @@ nav_order: 30 After creating a detector, it appears on the Threat detectors page along with others saved to the system. You can then perform a number of actions for each detector, from editing its details to changing its status. See the following sections for description of the available actions. -<img src="{{site.url}}{{site.baseurl}}/images/Security/threat-detector.png" alt="Threat detector page" width="60%"> +![Threat detector page]({{site.url}}{{site.baseurl}}/images/Security/threat-detector.png){: width="60%" } --- ## Threat detector list @@ -23,23 +23,23 @@ The list of threat detectors includes the search bar, the **Status** dropdown li To edit a detector, begin by selecting the link to the detector in the Detector name column of the list. The detector's details window opens and shows details about the detector's configuration. -<img src="{{site.url}}{{site.baseurl}}/images/Security/detector-details.png" alt="Detector details window for editig the detector" width="50%"> +![Detector details window for editing the detector]({{site.url}}{{site.baseurl}}/images/Security/detector-details.png){: width="50%" } * In the upper-left portion of the window, the details window shows the name of the detector and its status, either Active or Inactive. * In the upper-right corner of the window, you can select **View alerts** to go to the Alerts window or **View findings** to go to the Findings window. You can also select **Actions** to perform actions for the detector. See [Detector actions]({{site.url}}{{site.baseurl}}/security-analytics/usage/detectors/#detector-actions). * In the lower portion of the window, select the **Edit** button for either Detector details or Detection rules to make changes accordingly. * Finally, you can select the **Field mappings** tab to edit field mappings for the detector, or select the **Alert triggers** tab to make edits to alerts associated with the detector. -<img src="{{site.url}}{{site.baseurl}}/images/Security/detector-details2.png" alt="Field mappings and Alert triggers tabs" width="40%"> +![Field mappings and Alert triggers tabs]({{site.url}}{{site.baseurl}}/images/Security/detector-details2.png){: width="40%" } After you select the **Alert triggers** tab, you also have the option to add additional alerts for the detector by selecting **Add another alert condition** at the bottom of the page. {: .tip } ### Threat intelligence feeds -A threat intelligence feed is a real-time, continuous data stream that gathers information related to risks or threats. A piece of information in the tactical threat intelligence feed suggesting that your cluster may have been compromised, such as a login from an unknown user or location or anomalous activity like an increase in read volume, is called an *indicator of compromise* (IoC). These IoCs can be used by investigators to help isolate security incidents. +A threat intelligence feed is a real-time, continuous data stream that gathers information related to risks or threats. A piece of information in the tactical threat intelligence feed suggesting that your cluster may have been compromised, such as a login from an unknown user or location or anomalous activity like an increase in read volume, is called an *indicator of compromise (IOC)*. These IOCs can be used by investigators to help isolate security incidents. -As of OpenSearch 2.12, you can enable threat intelligence for Sigma rules related to malicious IP addresses. +You can enable threat intelligence for Sigma rules related to malicious IP addresses. To enable threat intelligence feeds, select the **Enable threat intelligence-based detection** option. @@ -50,7 +50,7 @@ Threat intelligence feeds only work with **standard** log types. Threat detector actions allow you to stop and start detectors or delete a detector. To enable actions, first select the checkbox beside one or more detectors in the list. -<img src="{{site.url}}{{site.baseurl}}/images/Security/detector-action.png" alt="Threat detector actions" width="50%"> +![Threat detector actions]({{site.url}}{{site.baseurl}}/images/Security/detector-action.png){: width="50%" } ### Changing detector status @@ -63,5 +63,5 @@ Threat detector actions allow you to stop and start detectors or delete a detect 1. Select **Delete** in the dropdown list. The Delete detector popup window opens and asks you to verify that you want to delete the detector or detectors. 1. Select **Cancel** to decline the action. Select **Delete detector** to delete the detector or detectors permanently from the list. -## Related articles +## Related documentation [Creating detectors]({{site.url}}{{site.baseurl}}/security-analytics/sec-analytics-config/detectors-config/) \ No newline at end of file diff --git a/_security-analytics/usage/findings.md b/_security-analytics/usage/findings.md index 7850ecb6..c47a163d 100644 --- a/_security-analytics/usage/findings.md +++ b/_security-analytics/usage/findings.md @@ -14,13 +14,13 @@ The **Findings** window includes features for viewing and working with findings. You can choose **Refresh** at any time to refresh information on the **Findings** page. --- -## The Findings graph +## The findings graph The findings graph can display findings by log type or rule severity. Use the **Group by** dropdown list to specify either log type or rule severity. To specify the date range you would like the graph to display, first select the calendar dropdown list. The date selector window opens. -<img src="{{site.url}}{{site.baseurl}}/images/Security/find-date-pick.png" alt="Date selector for findings graph" width="55%"> +![Date selector for findings graph]({{site.url}}{{site.baseurl}}/images/Security/find-date-pick.png){: width="55%" } You can use the **Quick select** settings to specify an exact window of time. * Select either **Last** or **Next** in the first dropdown list to set the window of time behind the current setting or ahead of the current setting. @@ -28,11 +28,11 @@ You can use the **Quick select** settings to specify an exact window of time. * Select a unit of time in the third dropdown list. Available options are seconds, minutes, hours, days, weeks, months, and years. Choose **Apply** to apply the range of dates to the graph. Information on the graph changes accordingly, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/quickset.png" alt="Quick select settings example" width="40%"> +![Quick select settings example]({{site.url}}{{site.baseurl}}/images/Security/quickset.png){: width="40%" } You can use the left and right arrows to move the window of time behind the current range of dates or ahead of the current range of dates. When you use these arrows, the start and end dates appear in the date range field. You can then select each one to set an absolute, relative, or current date and time. For absolute and relative changes, choose **Update** to apply the changes. -<img src="{{site.url}}{{site.baseurl}}/images/Security/date-pick.png" alt="Altering date range" width="55%"> +![Altering date range]({{site.url}}{{site.baseurl}}/images/Security/date-pick.png){: width="55%" } As an alternative, you can select an option in the **Commonly used** section (see the preceding image of the calendar dropdown list) to conveniently set a window of time. Options include date ranges such as **Today**, **Yesterday**, **this week**, and **week to date**. @@ -41,11 +41,11 @@ When one of the commonly used windows of time is selected, you can choose **Show As one more alternative, you can select an option from the **Recently used date ranges** section to go back to a previous setting. --- -## The Findings list +## The findings list The **Findings** list displays all findings according to the time of the finding, the finding ID, the rule name that generated the finding, the detector that captured the finding, and other details, as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/finding-list.png" alt="A list of all findings" width="85%"> +![A list of all findings]({{site.url}}{{site.baseurl}}/images/Security/finding-list.png){: width="85%" } Use the **Rule severity** dropdown list to filter the list of findings by severity. Use the **log type** dropdown list to filter the list by log type. @@ -58,7 +58,7 @@ For information about setting up alerts, see [Step 2. Set up alerts]({{site.url} Each finding in the list also includes a **Finding ID**. In addition to using the diagonal arrow in **Actions**, you can select the ID to open the **Finding details** pane. An example of **Finding details** is shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/findings1.png" alt="Finding details pane" width="60%"> +![Finding details pane]({{site.url}}{{site.baseurl}}/images/Security/findings1.png){: width="60%" } #### Viewing surrounding documents @@ -67,12 +67,12 @@ The **Finding details** pane contains specific information about the finding, in 1. Open **Finding details** by selecting the **Finding ID** in the **Findings** list. 1. In the **Documents** section, select **View surrounding documents**. If an index pattern already exists for the document, the **Discover** panel opens and displays the document. If an index pattern does not exist, the **Create index pattern to view documents** window opens and prompts you to create an index pattern, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/findings2.png" alt="popup window prompting users to create an index pattern" width="60%"> + ![popup window prompting users to create an index pattern]({{site.url}}{{site.baseurl}}/images/Security/findings2.png){: width="60%" } 1. In the **Create index pattern to view documents** window, the index pattern name is automatically populated. Enter the appropriate time field from the log index used to determine the timing for log events. Choose **Create index pattern**. The **Create index pattern to view documents** confirmation window opens. 1. Select **View surrounding documents** in the confirmation window. The **Discover** panel opens, as shown in the following image. - <img src="{{site.url}}{{site.baseurl}}/images/Security/findings4.png" alt="Discover panel with surrounding documents" width="85%"> + ![Discover panel with surrounding documents]({{site.url}}{{site.baseurl}}/images/Security/findings4.png){: width="85%" } The **Discover** panel displays the document that generated the finding with a highlighted background. Other documents that came either before or after the event are also displayed. @@ -82,6 +82,6 @@ For details about working with **Discover** in OpenSearch Dashboards, see [Explo To see how the finding is correlated with other findings, select the **Correlations** tab. Correlations are relationships between findings that express a particular threat scenario involving multiple log types. Information in the **Correlated findings** table shows the time at which a correlated finding was generated, a finding's ID, the log type used to generate the finding, its threat severity, and the correlation score---a measure of its proximity to the reference finding---as shown in the following image. -<img src="{{site.url}}{{site.baseurl}}/images/Security/corr-details-findings.png" alt="A table of correlated findings with respect to the reference finding" width="60%"> +![A table of correlated findings with respect to the reference finding]({{site.url}}{{site.baseurl}}/images/Security/corr-details-findings.png){: width="60%" } You can select **View correlations graph** to visualize correlations between the findings. For more information about using the correlation graph, see [Working with the correlation graph]({{site.url}}{{site.baseurl}}/security-analytics/usage/correlation-graph/). diff --git a/_security-analytics/usage/index.md b/_security-analytics/usage/index.md index 1bf1073c..0a59e8fe 100644 --- a/_security-analytics/usage/index.md +++ b/_security-analytics/usage/index.md @@ -8,9 +8,11 @@ redirect_from: - /security-analytics/usage/ --- +<!-- vale off --> # Using Security Analytics +<!-- vale on --> -After creating detectors and generating findings, functionality within the several Security Analytics windows offers visualizations and tools to help you investigate and manage findings, create focused alerts and notifications, import or customize rules, and edit detectors, among other tasks. This section discusses available features, their uses, and general navigation while working in the various windows. You can use the following links to go directly to information on a specific window: +Security Analytics provides visualizations and tools to investigate and manage findings, create alerts and notifications, import or customize detection rules, and edit detectors. Use the following links to learn about each feature: * [The Overview page]({{site.url}}{{site.baseurl}}/security-analytics/usage/overview/) * [Working with detectors]({{site.url}}{{site.baseurl}}/security-analytics/usage/detectors/) diff --git a/_security-analytics/usage/overview.md b/_security-analytics/usage/overview.md index 3d74c6d4..6e9b0c5d 100644 --- a/_security-analytics/usage/overview.md +++ b/_security-analytics/usage/overview.md @@ -5,9 +5,11 @@ parent: Using Security Analytics nav_order: 25 --- +<!-- vale off --> # The Overview page +<!-- vale on --> -When you select **Security Analytics** from the top menu, the Overview page is displayed. The Overview page consists of five sections: +When you select **Security Analytics** from the top menu, the **Overview** page is displayed. The **Overview** page consists of five sections: * Findings and alert count * Recent alerts * Recent findings @@ -19,11 +21,11 @@ Each section provides a summary description for each element of Security Analyti --- ## Overview and getting started -The upper portion of the Overview page contains two control buttons for refreshing information and getting started with Security Analytics. You can select the **Refresh** button to refresh all of the information on the page. +The upper portion of the **Overview** page contains two control buttons for refreshing information and getting started with Security Analytics. You can select the **Refresh** button to refresh all of the information on the page. You can also select the **Getting started** link to expand the Get started with Security Analytics window, which includes a summary of the setup steps as well as control buttons that allow you to jump to any of the steps. -<img src="{{site.url}}{{site.baseurl}}/images/Security/overview.png" alt="The overview page with getting started quick launch window" width="85%"> +![The overview page with getting started quick launch window]({{site.url}}{{site.baseurl}}/images/Security/overview.png){: width="85%" } * In step 1 of setup, select **Create detector** to define a detector. * In step 2, select **View findings** to go to the Findings page. For details about this page, see [Working with findings]({{site.url}}{{site.baseurl}}/security-analytics/usage/findings/). @@ -35,33 +37,33 @@ You can also select the **Getting started** link to expand the Get started with The Findings and alert count section provides a graph showing data on the latest findings. Use the **Group by** dropdown list to select either **All findings** or **Log type**. -<img src="{{site.url}}{{site.baseurl}}/images/Security/count.png" alt="A graph showing counts for findings and alerts." width="75%"> +![A graph showing counts for findings and alerts.]({{site.url}}{{site.baseurl}}/images/Security/count.png){: width="75%" } --- ## Recent alerts The Recent alerts table displays recent alerts by time, trigger name, and alert severity. Select **View alerts** to go to the Alerts page. -<img src="{{site.url}}{{site.baseurl}}/images/Security/recent-alerts.png" alt="A table showing the most recent alerts." width="50%"> +![A table showing the most recent alerts.]({{site.url}}{{site.baseurl}}/images/Security/recent-alerts.png){: width="50%" } --- ## Recent findings The Recent findings table displays recent findings by time, rule name, rule severity, and detector. Select **View all findings** to go to the Findings page. -<img src="{{site.url}}{{site.baseurl}}/images/Security/recent-findings.png" alt="A table showing the most recent findings." width="50%"> +![A table showing the most recent findings.]({{site.url}}{{site.baseurl}}/images/Security/recent-findings.png){: width="50%" } --- ## Most frequent detection rules This section provides a graphical representation of detection rules that trigger findings most often and how they compare to others as a percentage of the whole. The rule names represented by the graph are listed to the right. You can hover over each color on the graph to see details about the detection rule it represents. -<img src="{{site.url}}{{site.baseurl}}/images/Security/rule_graph.png" alt="The detection rule graph on the Overview page" width="50%"> +![The detection rule graph on the Overview page]({{site.url}}{{site.baseurl}}/images/Security/rule_graph.png){: width="50%" } --- ## Detectors The Detectors section displays a list of available detectors by detector name, status (active/inactive), and log type. Select **View all detectors** to go to the Detectors page. Select **Create detector** to go directly to the Define detector page. -<img src="{{site.url}}{{site.baseurl}}/images/Security/detector-overview.png" alt="A table showing available detectors." width="50%"> +![A table showing available detectors.]({{site.url}}{{site.baseurl}}/images/Security/detector-overview.png){: width="50%" } diff --git a/_security-analytics/usage/rules.md b/_security-analytics/usage/rules.md index e5d60fa6..375a4280 100644 --- a/_security-analytics/usage/rules.md +++ b/_security-analytics/usage/rules.md @@ -9,7 +9,7 @@ nav_order: 40 The **Detection rules** window lists all security rules used for detection creation and provides options for filtering the list and viewing details for each rule. Further options allow you to import rules and create new rules by first duplicating a Sigma rule and then modifying it. This section covers navigation of the **Rules** page and provides descriptions of the actions you can perform. -<img src="{{site.url}}{{site.baseurl}}/images/Security/Rules.png" alt="The Rules page" width="90%"> +![The Rules page]({{site.url}}{{site.baseurl}}/images/Security/Rules.png){: width="90%" } --- ## Viewing and filtering rules @@ -18,17 +18,17 @@ When you open the **Detection rules** page, all rules are listed in the table. U Alternatively, you can use the **Rule type**, **Rule severity**, and **Source** dropdown lists to drill down in the alerts and filter for preferred results. You can select multiple options from each list and use all three in combination to narrow results. -<img src="{{site.url}}{{site.baseurl}}/images/Security/rule-menu.png" alt="Rule menus for filtering results" width="40%"> +![Rule menus for filtering results]({{site.url}}{{site.baseurl}}/images/Security/rule-menu.png){: width="40%" } ### Rule details To see rule details, select the rule in the Rule name column of the list. The rule details pane opens. -<img src="{{site.url}}{{site.baseurl}}/images/Security/Rule_details.png" alt="The rule details pane" width="50%"> +![The rule details pane]({{site.url}}{{site.baseurl}}/images/Security/Rule_details.png){: width="50%" } In Visual view, rule details are arranged in fields, and the links are active. Select **YAML** to display the rule in YAML file format. -<img src="{{site.url}}{{site.baseurl}}/images/Security/rule_detail_yaml.png" alt="The rule details pane in YAML file view" width="50%"> +![The rule details pane in YAML file view]({{site.url}}{{site.baseurl}}/images/Security/rule_detail_yaml.png){: width="50%" } * Rule details are formatted as a YAML file according to the Sigma rule specification. * To copy the rule, select the copy icon in the upper-right corner of the rule. To quickly create a new, customized rule, you can paste the rule into the YAML editor and make any modifications before saving it. See [Customizing rules](#customizing-rules) for more information. @@ -45,17 +45,19 @@ The first method of rule creation is to create a custom rule by manually filling If you choose to create the rule manually, you can refer to Sigma's [Rule Creation Guide](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide) for more information about the details of each field. {: .tip } +<!-- vale off --> #### The Visual Editor +<!-- vale on --> When the **Create detection rule** window opens, the **Visual Editor** is displayed by default. The required fields in the **Visual Editor** correspond to the basic fields found in a YAML file formatted as a Sigma rule. The descriptions in these steps mention this correspondence when it might not be immediately obvious. 1. In the **Rule overview** section, enter a name for the rule, a description (optional), and the author of the rule. The **Rule name** corresponds to [title](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#title) in a Sigma rule formatted in a YAML file. The following image provides an example of the populated fields. - <img src="{{site.url}}{{site.baseurl}}/images/Security/overview-rule.png" alt="The Rule overview fields in the Create detection rule window, which include the rule name, description, and author fields." width="50%"> + ![The Rule overview fields in the Create detection rule window, which include the rule name, description, and author fields.]({{site.url}}{{site.baseurl}}/images/Security/overview-rule.png){: width="50%" } 1. In the **Details** section, enter the log type for the data source, the rule level, and the rule status. The **Log type** corresponds to the [`logsource`](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#log-source) field (specifically, the `logsource: product` field), while the rule level and rule status correspond to [`level`](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#level) and [`status`](https://github.com/SigmaHQ/sigma/wiki/Rule-Creation-Guide#status), respectively. Levels in Sigma rules include *informational*, *low*, *medium*, *high*, and *critical*. The following image provides an example. - <img src="{{site.url}}{{site.baseurl}}/images/Security/details-rule.png" alt="The Details fields in the Create detection rule window, which include the log type, rule level, and rule status fields." width="40%"> + ![The Details fields in the Create detection rule window, which include the log type, rule level, and rule status fields.]({{site.url}}{{site.baseurl}}/images/Security/details-rule.png){: width="40%" } 1. In the **Detection** section, specify key-value pairs to represent the fields and their values in the log source, which will be the target for detection. These key-value pairs define the detection. You can represent key values as either a single value or as a list containing multiple values. @@ -69,7 +71,7 @@ When the **Create detection rule** window opens, the **Visual Editor** is displa You can add fields for mapping a second key-value pair by selecting **Add map**. Follow the previous guidance in this step to map the key-value pair. The following image shows how this definition for two key-value pairs appears in the **Create detection rule** window. - <img src="{{site.url}}{{site.baseurl}}/images/Security/detection1.png" alt="An example of the Detection fields." width="50%"> + ![An example of the Detection fields.]({{site.url}}{{site.baseurl}}/images/Security/detection1.png){: width="50%" } To see how this definition compares to how it would be configured in the YAML file, refer to the following example: @@ -87,7 +89,7 @@ When the **Create detection rule** window opens, the **Visual Editor** is displa You can upload an existing list of values in either .csv or .txt format. Select **Upload file** and follow the prompts to upload a file's content into the text field. As an alternative, you can manually compose the list directly in the text field. The following image shows how a key-value pair mapping including a list of values appears. - <img src="{{site.url}}{{site.baseurl}}/images/Security/detection2.png" alt="An example of the Detection fields." width="50%"> + ![An example of the Detection fields.]({{site.url}}{{site.baseurl}}/images/Security/detection2.png){: width="50%" } To see how the definition with both of the preceding selections compares to how it would be configured in the YAML file, refer to the following example: @@ -115,7 +117,7 @@ When the **Create detection rule** window opens, the **Visual Editor** is displa Select the `+` sign beside **Select** to add the first selection. Select the `+` sign again to add further selections from the detection definition. Once two selections are present as conditions, the Boolean operator AND appears between them, indicating that both will be used in the detection rule query. You can select the operator's label to open the operator dropdown list and choose from the options `AND`, `OR`, and `NOT`. The following image shows how this option appears. - <img src="{{site.url}}{{site.baseurl}}/images/Security/condition1.png" alt="specifying the conditions for the selections in the detection definition." width="50%"> + ![specifying the conditions for the selections in the detection definition.]({{site.url}}{{site.baseurl}}/images/Security/condition1.png){: width="50%" } 1. Specify optional fields for the detection rule. @@ -125,7 +127,9 @@ When the **Create detection rule** window opens, the **Visual Editor** is displa 1. Once the rule is complete and meets your requirements, select **Create detection rule** in the lower-right corner of the window to save the rule. A rule ID is automatically assigned to the new rule and appears in the list of detection rules. +<!-- vale off --> #### The YAML Editor +<!-- vale on --> The **Create detection rule** window also contains the YAML Editor so that you can create a new rule directly in a YAML file format. Select **YAML Editor** and then enter information for the pre-populated field types. The rule's `id` is provided and assigned when the rule is saved. The following example shows the basic elements of a typical rule: @@ -177,20 +181,20 @@ Security Analytics also supports the importing of Sigma rules in YAML format. In Another option for creating a new detection rule is duplicating a Sigma rule and then modifying it to create a custom rule. First search for or filter rules in the **Rule name** list to locate the rule you want to duplicate. The following image shows the list filtered with a keyword. -<img src="{{site.url}}{{site.baseurl}}/images/Security/rules-dup1.png" alt="Selecting a rule in the Rules name list" width="75%"> +![Selecting a rule in the Rules name list]({{site.url}}{{site.baseurl}}/images/Security/rules-dup1.png){: width="75%" } 1. To begin, select the rule in the **Rule name** column. The rule details are displayed. - <img src="{{site.url}}{{site.baseurl}}/images/Security/rule-dup2.png" alt="Opening the rule details pane" width="50%"> + ![Opening the rule details pane]({{site.url}}{{site.baseurl}}/images/Security/rule-dup2.png){: width="50%" } 1. Select the **Duplicate** button in the upper-right corner of the pane. The Duplicate rule window opens in Visual Editor view and all of the fields are automatically populated with the rule's details. Details are also populated in YAML Editor view. - <img src="{{site.url}}{{site.baseurl}}/images/Security/dupe-rule.png" alt="Selecting the duplicate button opens the Duplicate rule window" width="50%"> + ![Selecting the duplicate button opens the Duplicate rule window]({{site.url}}{{site.baseurl}}/images/Security/dupe-rule.png){: width="50%" } 1. In either Visual Editor view or YAML Editor view, modify any of the fields to customize the rule. 1. After performing any modifications to the rule, select **Create detection rule** in the lower-right corner of the window. A new, customized rule is created. It appears in the list of rules on the main page of the **Detection rules** window. - <img src="{{site.url}}{{site.baseurl}}/images/Security/custom-rule.png" alt="The custom rule now appears in the list of rules." width="70%"> + ![The custom rule now appears in the list of rules.]({{site.url}}{{site.baseurl}}/images/Security/custom-rule.png){: width="70%" } You cannot modify the Sigma rule itself. The original Sigma rule always remains in the system. Its duplicate, after modification, becomes the custom rule that is added to the list of rules. {: .note } diff --git a/i18n/zh/about/breaking-changes.md b/i18n/zh/about/breaking-changes.md new file mode 100644 index 00000000..5424b3f6 --- /dev/null +++ b/i18n/zh/about/breaking-changes.md @@ -0,0 +1,246 @@ +--- +title: 重大变更 +--- + +# 重大变更 + +OpenSearch 使用[语义化版本控制](https://semver.org/),这意味着重大变更仅在主要版本发布之间引入。以下部分列出了 OpenSearch 中引入的重大变更,按版本组织。 + +<!-- vale off --> +## 1.x +<!-- vale on --> + +以下重大变更在 OpenSearch 1.x 中引入。 + +### 迁移到 OpenSearch 和嵌套 JSON 对象数量限制 + +当集群包含任何跨所有字段包含超过 10,000 个嵌套 JSON 对象的文档时,从 Elasticsearch OSS 6.8 版本迁移到 OpenSearch 1.x 版本将失败。Elasticsearch 7.0 版本引入了 `index.mapping.nested_objects.limit` 设置以防止内存溢出错误,并将该设置的默认值设为 `10000`。OpenSearch 在其初始版本中采用了此设置并强制执行对嵌套 JSON 对象的限制。但是,由于该设置在 Elasticsearch 6.8 中不存在且不被此版本识别,因此当任何文档中的嵌套 JSON 对象数量超过默认限制时,迁移到 OpenSearch 1.x 可能会导致不兼容问题,从而阻止 Elasticsearch 6.8 和 OpenSearch 1.x 版本之间的分片重新分配。 + +因此,我们建议在尝试从 Elasticsearch 6.8 迁移之前评估您的数据是否存在这些限制。 + +## 2.0.0 + +以下重大变更在 OpenSearch 2.0.0 中引入。 + +### 移除映射类型参数 + +`type` 参数已从所有 OpenSearch API 端点中移除。相反,索引可以按文档类型进行分类。有关更多详细信息,请参阅问题 [#1940](https://github.com/opensearch-project/opensearch/issues/1940)。 + +### 弃用非包容性术语 + +非包容性术语在 2.x 版本中已弃用,并将在 OpenSearch 3.0 中永久移除。我们使用以下替代术语: + +<!-- vale off --> +- "Whitelist" 现在是 "Allow list" +- "Blacklist" 现在是 "Deny list" +- "Master" 现在是 "Cluster Manager" +<!-- vale on --> + +<!-- vale off --> +### 添加 OpenSearch Notifications 插件 +<!-- vale on --> + +在 OpenSearch 2.0 中,Alerting 插件现在与新的 Notifications 插件集成。如果您想继续在 Alerting 插件中使用通知操作,请安装新的后端插件 `notifications-core` 和 `notifications`。如果您想在 OpenSearch Dashboards 中管理通知,请使用新的 `notificationsDashboards` 插件。有关更多信息,请参阅 OpenSearch 文档页面上的 [Notifications](/observing-your-data/notifications/)。 + +### 停止支持 JDK 8 + +Lucene 升级迫使 OpenSearch 停止支持 JDK 8。因此,Java 高级 REST 客户端不再支持 JDK 8。恢复 JDK 8 支持目前是 `opensearch-java` 提案 [#156](https://github.com/opensearch-project/opensearch-java/issues/156),并且需要从 Java 客户端中移除 OpenSearch 核心作为依赖项(问题 [#262](https://github.com/opensearch-project/opensearch-java/issues/262))。 + +## 2.5.0 + +以下重大变更在 OpenSearch 2.5.0 中引入。 + +### 文本字段的通配符查询行为 + +OpenSearch 2.5 包含一个错误修复,该修复纠正了文本字段上 `wildcard` 查询的 `case_insensitive` 参数的行为。因此,在错误修复之前忽略大小写敏感性并错误地返回结果的文本字段上的通配符查询将不会返回相同的结果。有关更多信息,请参阅问题 [#8711](https://github.com/opensearch-project/OpenSearch/issues/8711)。 + +## 2.18.0 + +以下重大变更在 OpenSearch 2.18.0 中引入。 + +### 默认 k-NN 引擎更改 + +默认 k-NN 引擎从 NMSLIB 更改为 Faiss。如果您使用 `space_type: "cosinesimil"` 而没有明确指定引擎,您的向量现在会在索引期间自动归一化为单位长度。这是因为 Faiss 本身不支持余弦相似度,而是对归一化向量使用内积。因此,存储的向量值将与输入值不同,这可能会影响检索和比较向量的代码。如果您的向量已经归一化,请考虑将 `space_type` 设置为 `innerproduct` 而不是 `cosinesimil`,以获得数学上等效的结果并显式控制归一化。有关更多信息,请参阅拉取请求 [#2221](https://github.com/opensearch-project/k-NN/pull/2221)。 + +## 2.19.0 + +以下重大变更在 OpenSearch 2.19.0 中引入。 + +### 文本嵌入处理器中的嵌套值支持 +`text_embedding` 处理器在评估类似 `title_tmp:_ingest._value.title_embedding` 的字段时不再替换嵌套值(如 `_ingest._value`)。相反,您必须直接将嵌套键指定为 `books.title:title_embedding` 以实现所需的输出。有关更多信息,请参阅问题 [#1243](https://github.com/opensearch-project/neural-search/issues/1243)。 + +## 3.0.0 + +以下重大变更在 OpenSearch 3.0.0 中引入。 + +### JDK 要求 + +支持的最低 JDK 版本是 JDK 21。 + +### 版本兼容性设置 + +`compatibility.override_main_response_version` 设置已被移除。此功能在 OpenSearch 1.x 中已弃用,不再受支持。 + +有关更多信息,请参阅问题 [#18228](https://github.com/opensearch-project/OpenSearch/issues/18228)。 + +有关替代方法,请参阅 [Agents and ingestion tools](/tools/#agents-and-ingestion-tools)。 + +### 索引版本 + +不支持在早于 `2.x.x` 的版本中创建的索引(包括系统索引)。这些索引必须在**升级之前**重新索引。有关重新索引的信息,请参阅 [Reindex data](/im-plugin/reindex-data)。 + +有关更多信息,请参阅问题 [#18717](https://github.com/opensearch-project/OpenSearch/issues/18717)。 + +### 系统索引访问 + +不再通过 REST API 提供对系统索引的访问。此功能自 OpenSearch 1.x 以来已被弃用。有关更多信息,请参阅问题 [#7936](https://github.com/opensearch-project/OpenSearch/issues/7936)。 + +### 文档 ID 长度限制 + +现在所有 API(包括 Bulk API)都一致地强制执行 512 字节的文档 ID 长度限制。以前,Bulk API 允许文档 ID 超过 512 字节。有关更多信息,请参阅问题 [#6595](https://github.com/opensearch-project/OpenSearch/issues/6595)。 + +### 节点角色配置 + +使用环境变量配置空节点角色已得到修复。使用环境变量设置 `node.roles=` 现在可以正确配置仅协调节点,与 `opensearch.yml` 配置一致。有关更多信息,请参阅问题 [#3412](https://github.com/opensearch-project/OpenSearch/issues/3412)。 + +### JSON 处理限制 + +在整个 OpenSearch 中引入了用于 JSON 处理(使用 Jackson 库)的新默认限制: + +- JSON 对象和数组的最大嵌套深度限制为 1,000 层。 +- JSON 属性名称的最大长度限制为 50,000 个单位(字节或字符,取决于输入源)。 + +这些限制有助于防止潜在的内存问题和拒绝服务攻击。有关更多信息,请参阅问题 [#11278](https://github.com/opensearch-project/OpenSearch/issues/11278)。 + +### 嵌套查询深度 + +引入了新的 `index.query.max_nested_depth` 设置,默认值为 `20`,最小值为 `1`,限制 `nested` 查询的最大嵌套层数。有关更多信息,请参阅问题 [#3268](https://github.com/opensearch-project/OpenSearch/issues/3268)。 + +### 线程池设置 + +以下已弃用的线程池设置已被移除: +- `thread_pool.test.max_queue_size` +- `thread_pool.test.min_queue_size` +有关更多信息,请参阅问题 [#2595](https://github.com/opensearch-project/OpenSearch/issues/2595)。 + +### 索引存储设置 + +作为改进 `hybridfs` 文件处理的一部分,`index.store.hybrid.mmap.extensions` 设置已被移除。有关更多信息,请参阅拉取请求 [#9392](https://github.com/opensearch-project/OpenSearch/pull/9392)。 + +### Transport NIO 插件 + +`transport-nio` 插件已被移除。Netty 仍然是节点到节点和客户端到服务器通信的标准网络框架。有关更多信息,请参阅问题 [#16887](https://github.com/opensearch-project/OpenSearch/issues/16887)。 + +### Nodes API 响应格式 + +Nodes API 响应中的索引缓冲区值格式已更改: + +- `total_indexing_buffer_in_bytes` 现在显示原始字节(例如,`53687091`)。 +- `total_indexing_buffer` 现在显示可读格式(例如,`51.1mb`)。 + +有关更多信息,请参阅拉取请求 [#17070](https://github.com/opensearch-project/OpenSearch/pull/17070)。 + +### PathHierarchy 分词器 + +驼峰式 `PathHierarchy` 分词器名称已被弃用,改为使用蛇形式 `path_hierarchy`。有关更多信息,请参阅拉取请求 [#10894](https://github.com/opensearch-project/OpenSearch/pull/10894)。 + +### Security 插件 + +Blake2b 哈希实现现在正确使用盐参数,这将导致与以前版本相比产生不同(尽管正确)的哈希值。有关更多信息,请参阅拉取请求 [#5089](https://github.com/opensearch-project/security/pull/5089)。 + +### k-NN 插件 + +以下已弃用的设置已从 k-NN 插件中移除: + +- `knn.plugin.enabled` 设置 +- `index.knn.algo_param.ef_construction` 索引设置 +- `index.knn.algo_param.m` 索引设置 +- `index.knn.space_type` 索引设置 + +NMSLIB 引擎现已弃用。我们建议改用 Faiss 或 Lucene 引擎。 + +有关更多信息,请参阅拉取请求 [#2564](https://github.com/opensearch-project/k-NN/pull/2564)。 + +### Performance Analyzer 插件 + +`performance-analyzer-rca` 代理已被移除。该代理在端口 9600 上提供 Performance Analyzer API 服务,因此指标、批量指标和根本原因分析 (RCA) API 以及 PerfTop 仪表板不再可用。Performance Analyzer 插件默认保持安装,并且可以使用[指标框架](/tuning-your-cluster/monitoring/telemetry/metrics/)发布其指标,该框架使用 OpenTelemetry 导出指标。有关更多信息,请参阅 [Performance Analyzer](/tuning-your-cluster/monitoring/telemetry/performance-analyzer/) 和问题 [#591](https://github.com/opensearch-project/performance-analyzer-rca/issues/591)。 + +### SQL 插件 + +- OpenSearch 查询领域特定语言 (DSL) 响应格式已被移除。 +- `DELETE` 语句支持已被移除。 +- `plugins.sql.delete.enabled` 设置已被移除。 +- 旧版 Spark Connector 模块已被弃用。有关连接到 Spark 的信息,请参阅 [`async-query-core`](https://github.com/opensearch-project/sql/blob/main/async-query-core/README.md)。 +- 已移除已弃用的 OpenDistro 端点和带有 `opendistro` 前缀的旧版设置。 +- `plugins.sql.pagination.api` 已被移除,Scroll API 已被弃用。分页现在默认使用 Point in Time。 + +有关更多信息,请参阅问题 [#3248](https://github.com/opensearch-project/sql/issues/3248)。 + +### OpenSearch Dashboards + +- Discover 体验: + + - `discover:newExperience` 设置已被移除。 + - DataGrid 表格功能已被移除。 + + 有关更多信息,请参阅拉取请求 [#9511](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/9511)。 + +- 可视化:`dashboards-visualizations` 插件(包括甘特图可视化)已被移除。我们建议过渡到: + + - Vega 可视化用于灵活的可视化需求。 + - 追踪分析用于追踪相关的用例。 + + 有关更多信息,请参阅问题 [#430](https://github.com/opensearch-project/dashboards-visualizations/issues/430)。 + +### Dashboards Observability 插件 + +旧版笔记本功能已从 `dashboards-observability` 中移除。主要变更包括: + +- 旧版笔记本(以前存储在 `.opensearch-observability` 索引中)不再受支持。 +- 仅支持存储在 `.kibana` 索引中的笔记本(在 2.17 版本中引入)。 +- 您必须在升级到 3.0 版本之前将笔记本迁移到新的存储系统。 + +有关更多信息,请参阅问题 [#2350](https://github.com/opensearch-project/dashboards-observability/issues/2350)。 + +### 可搜索快照节点角色 + +使用可搜索快照的节点必须具有 `warm` 节点角色。主要变更包括: + +- `search` 角色不再支持可搜索快照。 +- 处理可搜索快照分片的节点必须分配 warm 角色。 +- 如果您的集群使用可搜索快照,则必须在升级到 3.0 版本之前更新节点角色配置。 + +有关更多信息,请参阅拉取请求 [#17573](https://github.com/opensearch-project/OpenSearch/pull/17573)。 + +### 查询组 + +查询组已重命名为**工作负载组**。主要变更包括: + +- `wlm/query_group` 端点现在是 `wlm/workload_group` 端点。 +- API 响应使用 `workloadGroupID` 而不是 `queryGroupID`。 +- 所有工作负载管理集群设置现在都以 `wlm.workload_group` 为前缀。 + +有关更多信息,请参阅拉取请求 [#9813](https://github.com/opensearch-project/OpenSearch/pull/17901)。 + +### ML Commons 插件 + +- `CatIndexTool` 已被移除,改用 `ListIndexTool`。 +- 异步批量摄取 API(`POST /_plugins/_ml/_batch_ingestion`)已被移除。要获得类似功能,请使用 [OpenSearch Data Prepper](/data-prepper/)。有关更多信息,请参阅拉取请求 [#3688](https://github.com/opensearch-project/ml-commons/pull/3688)。 + +### 罗马尼亚语分析 + +`romanian` 分析器现在支持现代 Unicode 形式的罗马尼亚语,并将带下加符的字符归一化为基于逗号的等效字符。由于这两种形式仍在使用,我们建议重新索引现有的罗马尼亚语文档以确保一致的分析和搜索行为。 + +## 3.10.0 + +以下重大变更在 OpenSearch 3.10.0 中引入。 + +### ML Commons 插件 + +私有和内部 IP 地址的验证已更新如下: + +- 链路本地地址(`169.254.0.0/16` 和 `fe80::/10`)和云实例元数据地址(`fd00:ec2::/32`、`fd20:ce::254` 和 `100.100.100.200`)始终被拒绝,无论 `plugins.ml_commons.connector.private_ip_enabled` 设置如何。对这些地址的请求将失败,并显示错误 `Remote inference host name has restricted ip address: <host>`。任何使用此类端点的连接器都需要使用不同的端点。 +- IPv6 唯一本地地址(`fc00::/7`)和本地使用 NAT64 范围(`64:ff9b:1::/48`)是私有地址。使用它们的连接器需要将 `plugins.ml_commons.connector.private_ip_enabled` 设置为 `true`,如果 `plugins.ml_commons.trusted_connector_private_endpoints_regex` 不为空,则需要在该列表中有匹配的表达式。 +- `plugins.ml_commons.connector.private_ip_enabled`、`plugins.ml_commons.trusted_connector_private_endpoints_regex` 和 `plugins.ml_commons.connector.restricted_ip_patterns` 设置也适用于使用 `openai/v1/chat/completions` 或 `gemini/v1beta/generatecontent` 接口的流式预测请求。这些请求直接连接,不使用 JVM 范围的 HTTP 代理,也不遵循重定向。 + +有关更多信息,请参阅 [Connector endpoint settings](/ml-commons-plugin/cluster-settings#connector-endpoint-settings) 和拉取请求 [#5204](https://github.com/opensearch-project/ml-commons/pull/5204) 和 [#5206](https://github.com/opensearch-project/ml-commons/pull/5206)。 diff --git a/i18n/zh/about/intro.md b/i18n/zh/about/intro.md new file mode 100644 index 00000000..62b4ebbc --- /dev/null +++ b/i18n/zh/about/intro.md @@ -0,0 +1,106 @@ +--- +title: OpenSearch 简介 +--- + +# OpenSearch 简介 + +OpenSearch 是一个基于 [Apache Lucene](https://lucene.apache.org/) 的分布式搜索和分析引擎。将数据添加到 OpenSearch 后,您可以使用所有您可能期望的功能对其进行全文搜索:按字段搜索、搜索多个索引、提升字段、按分数对结果排名、按字段对结果排序以及聚合结果。 + +不出所料,人们经常将 OpenSearch 这样的搜索引擎用作搜索应用程序的后端——想想 [Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:FAQ/Technical#What_software_is_used_to_run_Wikipedia?) 或在线商店。它提供出色的性能,并可以随着应用程序需求的增长或缩减而扩展或收缩。 + +一个同样受欢迎但不太明显的用例是日志分析,您可以从应用程序中获取日志,将它们输入到 OpenSearch,并使用丰富的搜索和可视化功能来识别问题。例如,出现故障的 Web 服务器可能在 0.5% 的时间内抛出 500 错误,除非您有一个实时图表显示服务器在过去四个小时内抛出的所有 HTTP 状态代码,否则很难注意到这一点。您可以使用 [OpenSearch Dashboards](/dashboards/) 从 OpenSearch 中的数据构建这些类型的可视化。 + +## 集群和节点 + +其分布式设计意味着您与 OpenSearch *集群*进行交互。每个集群是一个或多个*节点*的集合,这些节点是存储您的数据并处理搜索请求的服务器。 + +您可以在笔记本电脑上本地运行 OpenSearch——其系统要求很低——但您也可以将单个集群扩展到数据中心中的数百台强大机器。 + +在单节点集群中,例如笔记本电脑,一台机器必须完成所有工作:管理集群状态、索引和搜索数据,以及在索引数据之前执行任何数据预处理。然而,随着集群的增长,您可以细分职责。具有快速磁盘和大量 RAM 的节点可能非常适合索引和搜索数据,而具有大量 CPU 能力和小磁盘的节点可以管理集群状态。有关设置节点类型的更多信息,请参阅 [Cluster formation](/tuning-your-cluster/)。 + +## 索引和文档 + +OpenSearch 将数据组织成*索引*。每个索引是 JSON *文档*的集合。如果您有一组原始百科全书文章或日志行想要添加到 OpenSearch,您必须首先将它们转换为 [JSON](https://www.json.org/)。一个简单的电影 JSON 文档可能如下所示: + +```json +{ + "title": "The Wind Rises", + "release_date": "2013-07-20" +} +``` + +当您将文档添加到索引时,OpenSearch 会添加一些元数据,例如唯一的文档 *ID*: + +```json +{ + "_index": "<index-name>", + "_type": "_doc", + "_id": "<document-id>", + "_version": 1, + "_source": { + "title": "The Wind Rises", + "release_date": "2013-07-20" + } +} +``` + +索引还包含映射和设置: + +- *映射*是索引中文档具有的*字段*的集合。在这种情况下,这些字段是 `title` 和 `release_date`。 +- 设置包括索引名称、创建日期和分片数量等数据。 + +## 主分片和副本分片 + +OpenSearch 将索引拆分为*分片*,以便在集群中的节点之间均匀分布。例如,400 GB 的索引可能对集群中的任何单个节点来说都太大而无法处理,但拆分成十个分片,每个 40 GB,OpenSearch 可以将分片分布到十个节点上,并单独处理每个分片。 + +默认情况下,OpenSearch 为每个*主*分片创建一个*副本*分片。例如,如果您将索引拆分为十个分片,OpenSearch 还会创建十个副本分片。这些副本分片在节点故障时充当备份——OpenSearch 将副本分片分布到与其对应主分片不同的节点上——但它们还提高了集群处理搜索请求的速度和速率。对于搜索密集型工作负载,您可能会为每个索引指定多个副本。 + +尽管是 OpenSearch 索引的一部分,但每个分片实际上是一个完整的 Lucene 索引——我们知道这很令人困惑。但是,这个细节很重要,因为 Lucene 的每个实例都是一个消耗 CPU 和内存的运行进程。更多的分片不一定更好。例如,将 400 GB 的索引拆分为 1,000 个分片会给集群带来不必要的压力。一个好的经验法则是将分片大小保持在 10-50 GB 之间。 + +## REST API + +您使用 REST API 与 OpenSearch 集群交互,这提供了很大的灵活性。您可以使用像 [curl](https://curl.se/) 这样的客户端或任何可以发送 HTTP 请求的编程语言。要将 JSON 文档添加到 OpenSearch 索引(即索引文档),您需要发送 HTTP 请求: + +```json +PUT https://<host>:<port>/<index-name>/_doc/<document-id> +{ + "title": "The Wind Rises", + "release_date": "2013-07-20" +} +``` + +要运行文档搜索: + +```json +GET https://<host>:<port>/<index-name>/_search?q=wind +``` + +要删除文档: + +```json +DELETE https://<host>:<port>/<index-name>/_doc/<document-id> +``` + +您可以使用 REST API 更改大多数 OpenSearch 设置、修改索引、检查集群的健康状况、获取统计信息——几乎所有操作。 + +## 高级概念 + +以下部分描述了更高级的 OpenSearch 概念。 + +### 事务日志 + +任何索引更改(例如文档索引或删除)都会在 Lucene 提交期间写入磁盘。但是,Lucene 提交是昂贵的操作,因此无法在索引的每次更改后执行。相反,每个分片将每个索引操作记录在称为 _translog_ 的事务日志中。当文档被索引时,它会被添加到内存缓冲区并记录在事务日志中。进程或主机重新启动后,内存缓冲区中的任何数据都会丢失。在事务日志中记录文档可确保持久性,因为事务日志会写入磁盘。 + +频繁的刷新操作将内存缓冲区中的文档写入段,然后清除内存缓冲区。定期,[flush](#flush) 执行 Lucene 提交,其中包括使用 `fsync` 将段写入磁盘、清除旧的事务日志并启动新的事务日志。因此,事务日志包含所有尚未刷新的操作。 + +### 刷新 + +OpenSearch 定期执行 _refresh_ 操作,将文档从内存中的 Lucene 索引写入文件。这些文件不保证是持久的,因为不执行 `fsync`。刷新使文档可供搜索。 + +### 刷写 + +_flush_ 操作使用 `fsync` 将文件持久化到磁盘,确保持久性。刷写确保仅存储在事务日志中的数据记录在 Lucene 索引中。OpenSearch 根据需要执行刷写,以确保事务日志不会变得太大。 + +### 合并 + +在 OpenSearch 中,分片是一个 Lucene 索引,它由_段_(或段文件)组成。段存储索引数据且是不可变的。较小的段会定期合并为较大的段。合并减少了每个分片上段的总数,释放磁盘空间,并提高搜索性能。最终,段达到合并策略中指定的最大大小,不再合并为更大的段。合并策略还指定合并的执行频率。 diff --git a/i18n/zh/about/quickstart.md b/i18n/zh/about/quickstart.md new file mode 100644 index 00000000..edbff322 --- /dev/null +++ b/i18n/zh/about/quickstart.md @@ -0,0 +1,161 @@ +--- +title: 快速入门 +--- + +# 快速入门 + +通过使用 [Docker](https://www.docker.com/) 部署容器来开始使用 OpenSearch 和 OpenSearch Dashboards。在继续之前,您需要在本地计算机上安装 [Docker](https://docs.docker.com/get-docker/) 和 [Docker Compose](https://github.com/docker/compose)。 + +::: info NOTE +本指南中使用的 Docker Compose 命令使用连字符编写(例如,`docker-compose`)。如果您在计算机上安装了 Docker Desktop(它会自动安装捆绑版本的 Docker Compose),那么您应该删除连字符。例如,将 `docker-compose` 更改为 `docker compose`。 +::: + +## 启动集群 + +您需要一个特殊的文件,称为 Compose 文件,Docker Compose 使用它来定义和创建集群中的容器。OpenSearch 项目提供了一个示例 Compose 文件,您可以使用它来开始。通过查看官方 [Compose 规范](https://docs.docker.com/compose/compose-file/)了解有关使用 Compose 文件的更多信息。 + +1. 在您的计算机上运行 OpenSearch 之前,您应该禁用主机上的内存分页和交换性能以提高性能,并增加 OpenSearch 可用的内存映射数量。有关更多信息,请参阅[重要系统设置](/install-and-configure/install-opensearch/)。 + ```bash + # 禁用内存分页和交换。 + sudo swapoff -a + + # 编辑定义主机最大映射计数的 sysctl 配置文件。 + sudo vi /etc/sysctl.conf + + # 将最大映射计数设置为推荐值 262144。 + vm.max_map_count=262144 + + # 重新加载内核参数。 + sudo sysctl -p + ``` +1. 将示例 Compose 文件下载到您的主机。您可以使用 `curl` 和 `wget` 等命令行实用程序下载文件,或者您可以使用 Web 浏览器从 OpenSearch 项目 documentation-website 存储库手动复制 [docker-compose.yml](https://github.com/opensearch-project/documentation-website/blob/2.12/assets/examples/docker-compose.yml)。 + ```bash + # 使用 cURL: + curl -O https://raw.githubusercontent.com/opensearch-project/documentation-website/2.12/assets/examples/docker-compose.yml + + # 使用 wget: + wget https://raw.githubusercontent.com/opensearch-project/documentation-website/2.12/assets/examples/docker-compose.yml + ``` +1. 在您的终端应用程序中,导航到包含您刚刚下载的 `docker-compose.yml` 文件的目录,并运行以下命令以作为后台进程创建并启动集群。 + ```bash + docker-compose up -d + ``` +1. 使用命令 `docker-compose ps` 确认容器正在运行。您应该看到类似以下的输出: + ```bash + $ docker-compose ps + NAME COMMAND SERVICE STATUS PORTS + opensearch-dashboards "./opensearch-dashbo…" opensearch-dashboards running 0.0.0.0:5601->5601/tcp + opensearch-node1 "./opensearch-docker…" opensearch-node1 running 0.0.0.0:9200->9200/tcp, 9300/tcp, 0.0.0.0:9600->9600/tcp, 9650/tcp + opensearch-node2 "./opensearch-docker…" opensearch-node2 running 9200/tcp, 9300/tcp, 9600/tcp, 9650/tcp + ``` +1. 查询 OpenSearch REST API 以验证服务是否正在运行。您应该使用 `-k`(也写作 `--insecure`)来禁用主机名检查,因为默认安全配置使用演示证书。使用 `-u` 传递默认用户名和密码(`admin:<custom-admin-password>`)。 + ```bash + curl https://localhost:9200 -ku admin:<custom-admin-password> + ``` + 示例响应: + ```json + { + "name" : "opensearch-node1", + "cluster_name" : "opensearch-cluster", + "cluster_uuid" : "W0B8gPotTAajhMPbC9D4ww", + "version" : { + "distribution" : "opensearch", + "number" : "2.6.0", + "build_type" : "tar", + "build_hash" : "7203a5af21a8a009aece1474446b437a3c674db6", + "build_date" : "2023-02-24T18:58:37.352296474Z", + "build_snapshot" : false, + "lucene_version" : "9.5.0", + "minimum_wire_compatibility_version" : "7.10.0", + "minimum_index_compatibility_version" : "7.0.0" + }, + "tagline" : "The OpenSearch Project: https://opensearch.org/" + } + ``` +1. 通过在运行 OpenSearch 集群的同一主机上的 Web 浏览器中打开 `http://localhost:5601/` 来探索 OpenSearch Dashboards。默认用户名是 `admin`,默认密码在您的 `docker-compose.yml` 文件中的 `OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>` 设置中设置。 + +## 使用示例数据创建索引和字段映射 + +使用 OpenSearch 项目提供的数据集创建索引并定义字段映射。相同的虚构电子商务数据也用于 OpenSearch Dashboards 中的示例可视化。要了解更多信息,请参阅 [Getting started with OpenSearch Dashboards](/dashboards/)。 + +1. 下载 [ecommerce-field_mappings.json](https://github.com/opensearch-project/documentation-website/blob/2.12/assets/examples/ecommerce-field_mappings.json)。此文件为您将使用的示例数据定义了[映射](/field-types/)。 + ```bash + # 使用 cURL: + curl -O https://raw.githubusercontent.com/opensearch-project/documentation-website/2.12/assets/examples/ecommerce-field_mappings.json + + # 使用 wget: + wget https://raw.githubusercontent.com/opensearch-project/documentation-website/2.12/assets/examples/ecommerce-field_mappings.json + ``` +1. 下载 [ecommerce.json](https://github.com/opensearch-project/documentation-website/blob/2.12/assets/examples/ecommerce.json)。此文件包含格式化的索引数据,以便批量 API 可以摄取它。要了解更多信息,请参阅[索引数据](/im-plugin/indexing-data)和 [Bulk](/api-reference/document-apis/bulk)。 + ```bash + # 使用 cURL: + curl -O https://raw.githubusercontent.com/opensearch-project/documentation-website/2.12/assets/examples/ecommerce.json + + # 使用 wget: + wget https://raw.githubusercontent.com/opensearch-project/documentation-website/2.12/assets/examples/ecommerce.json + ``` +1. 使用映射文件定义字段映射。 + ```bash + curl -H "Content-Type: application/x-ndjson" -X PUT "https://localhost:9200/ecommerce" -ku admin:<custom-admin-password> --data-binary "@ecommerce-field_mappings.json" + ``` +1. 将索引上传到批量 API。 + ```bash + curl -H "Content-Type: application/x-ndjson" -X PUT "https://localhost:9200/ecommerce/_bulk" -ku admin:<custom-admin-password> --data-binary "@ecommerce.json" + ``` +1. 使用搜索 API 查询数据。以下命令提交一个查询,该查询将返回 `customer_first_name` 为 `Sonya` 的文档。 + ```bash + curl -H 'Content-Type: application/json' -X GET "https://localhost:9200/ecommerce/_search?pretty=true" -ku admin:<custom-admin-password> -d' {"query":{"match":{"customer_first_name":"Sonya"}}}' + ``` + 提交到 OpenSearch REST API 的查询通常默认返回扁平的 JSON。要获得可读的响应正文,请使用查询参数 `pretty=true`。有关 `pretty` 和其他有用查询参数的更多信息,请参阅 [Common REST parameters](/api-reference/common-parameters)。 +1. 通过在运行 OpenSearch 集群的同一主机上的 Web 浏览器中打开 `http://localhost:5601/` 来访问 OpenSearch Dashboards。默认用户名是 `admin`,密码在您的 `docker-compose.yml` 文件中的 `OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>` 设置中设置。 +1. 在顶部菜单栏上,转到 **Management > Dev Tools**。 +1. 在控制台的左侧窗格中,输入以下内容: + ```json + GET ecommerce/_search + { + "query": { + "match": { + "customer_first_name": "Sonya" + } + } + } + ``` +1. 选择请求右上角的三角形图标以提交查询。您也可以通过按 `Ctrl+Enter`(或 Mac 用户的 `Cmd+Enter`)来提交请求。要了解有关使用 OpenSearch Dashboards 控制台提交查询的更多信息,请参阅 [Running queries in the console](/dashboards/dev-tools/)。 + +## 后续步骤 + +您已成功部署了自己的 OpenSearch 集群和 OpenSearch Dashboards,并添加了一些示例数据。现在您已准备好更详细地了解配置和功能。以下是一些建议的起点: +- [About the Security plugin](/security/) +- [OpenSearch configuration](/install-and-configure/configuring-opensearch/) +- [OpenSearch plugin installation](/install-and-configure/plugins) +- [Getting started with OpenSearch Dashboards](/dashboards/) +- [OpenSearch tools](/tools/) +- [Index APIs](/api-reference/index-apis/) + +## 常见问题 + +如果您的容器无法启动或意外退出,请查看这些常见问题和建议的解决方案。 + +### Docker 命令需要提升权限 + +通过将您的用户添加到 `docker` 用户组来消除使用 `sudo` 运行 Docker 命令的需要。有关更多信息,请参阅 Docker 的 [Post-installation steps for Linux](https://docs.docker.com/engine/install/linux-postinstall/)。 +```bash +sudo usermod -aG docker $USER +``` + +### 错误消息:"-bash: docker-compose: command not found" + +如果您安装了 Docker Desktop,那么 Docker Compose 已安装在您的计算机上。请尝试 `docker compose`(不带连字符)而不是 `docker-compose`。请参阅 [Use Docker Compose](https://docs.docker.com/get-started/08_using_compose/)。 + +### 错误消息:"docker: 'compose' is not a docker command." + +如果您安装了 Docker Engine,那么您必须单独安装 Docker Compose,并且您将使用命令 `docker-compose`(带连字符)。请参阅 [Docker Compose](https://github.com/docker/compose)。 + +### 错误消息:"max virtual memory areas vm.max_map_count [65530] is too low" + +如果您的主机的 `vm.max_map_count` 太低,OpenSearch 将无法启动。如果您在服务日志中看到以下错误,请查看[重要系统设置](/install-and-configure/install-opensearch/),并适当设置 `vm.max_map_count`。 +```bash +opensearch-node1 | ERROR: [1] bootstrap checks failed +opensearch-node1 | [1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] +opensearch-node1 | ERROR: OpenSearch did not exit normally - check the logs at /usr/share/opensearch/logs/opensearch-cluster.log +``` diff --git a/i18n/zh/about/version-history.md b/i18n/zh/about/version-history.md new file mode 100644 index 00000000..e8bab9ca --- /dev/null +++ b/i18n/zh/about/version-history.md @@ -0,0 +1,86 @@ +--- +title: 版本历史 +description: "OpenSearch 版本发布历史,包含每个版本的发布亮点、发布日期以及完整发行说明的链接。" +--- + +# 版本历史 + +OpenSearch 版本 | 发布亮点 | 发布日期 +:--- | :--- | :--- +[3.10.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.1.md) | 将捆绑的 JDK 更新到 25.0.5.1+2 以解决 CVE-2026-114938,这是 OpenJDK 17 及更高版本中的远程代码执行漏洞。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.1.md)。 | 2026 年 11 月 24 日 +[3.10.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.0.md) | 为 `hybrid` 查询引入融合模式,使分数归一化和组合能够直接在查询体中进行,无需搜索管道,并使混合查询可以嵌套在 `bool` 和 `dis_max` 查询中。将基于拉取的摄取扩展到对象存储中的静态数据(Amazon S3、Google Cloud Storage 和 Azure Blob Storage),并添加恢复后钩子,以便 Alerting 和 ISM 从快照状态恢复而不是重新启动。引入实验性代理搜索模板、为 Gemini 更新的 Google Cloud 连接器蓝图以及工作负载组的请求限制。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.10.0.md)。 | 2026 年 11 月 16 日 +[3.9.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.9.0.md) | 添加 `half_float` 向量数据类型、`bf16` 标量量化编码器、2 位和 4 位标量量化以及 `knn_vector` 字段的动态映射。引入机器学习模型的服务器端批量推理和自适应每操作并发限制。将异常检测和预测引入统一警报视图,并使资源共享和访问控制框架正式可用。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.9.0.md)。 | 2026 年 9 月 29 日 +[3.8.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.8.0.md) | 通过 Base64 编码向量提供高达 4.2 倍的向量摄取速度,通过改进的召回率提供高达 2.1 倍的径向搜索吞吐量。将模型上下文协议 (MCP) 支持扩展到流和对话流代理,添加列表工具 API 和连接器级工具描述覆盖,并引入代理内存的实验性保留策略。为 ML 预测和代理执行添加 gRPC 流,将搜索相关性工作台中的 LLM-as-a-Judge 扩展到其他模型,并在 OpenSearch Dashboards 中添加 Grok 调试器。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.8.0.md)。 | 2026 年 8 月 4 日 +[3.7.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.7.0.md) | 添加原生 Prometheus 集成,支持 PromQL 以实现跨日志、追踪和指标的统一可观测性。使用文档值提供高达 5.5 倍的向量检索速度,并通过 z_score 归一化和倒数排名融合扩展混合搜索优化。引入具有范围权限的 API 密钥、用于安全预览索引生命周期更改的 ISM 策略模拟以及 OpenSearch Dashboards 中的查询分析器工具。使统一代理注册和 conversational_v2 代理类型正式可用于生产 AI 工作负载。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.7.0.md)。 | 2026 年 6 月 9 日 +[3.6.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.6.0.md) | 引入具有令牌使用跟踪、可观测性追踪和相关性调整功能的 Agent-v2。将应用程序性能监控 (APM) 添加到可观测性中,包括服务依赖关系和性能指标。使基于拉取的摄取正式可用,具有预热设置和自适应分片选择。通过 1 位标量量化扩展向量搜索,并通过详细分组和故障跟踪增强查询洞察。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.6.0.md)。 | 2026 年 4 月 7 日 +[3.5.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.5.0.md) | 为智能 AI 应用程序引入代理对话内存和上下文管理。通过 FP16 操作的批量 SIMD 实现提供 58% 的向量搜索吞吐量改进。通过原生 Discover 体验和用于可观测性工作负载的增强 PPL 函数扩展 Prometheus 支持。使搜索相关性工作台正式可用,具有 LLM 驱动的评估功能。包括通过自动用户跟踪和实验性 HTTP/3 传输支持增强查询洞察。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.5.0.md)。 | 2026 年 2 月 10 日 +[3.4.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.4.0.md) | 引入具有监控执行和统计管理的 PPL 警报功能。添加异常检测每日洞察页面和流框架增强功能,包括代理摘要和 MCP 服务器支持。包括 k-NN 内存优化搜索预热、原生 FP16 向量评分和增强的资源共享框架。包含基础设施升级,包括 JDK 25 和改进的访问控制。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.4.0.md)。 | 2025 年 12 月 16 日 +[3.3.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.2.md) | 包括 OpenSearch 核心引擎以及 ML Commons、Neural Search、Skills、k-NN 和 Security 插件的维护更改和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.2.md)。 | 2025 年 10 月 30 日 +[3.3.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.1.md) | 修复日期字段的向后兼容性处理,同时保持性能优化。对于自 3.3.0 以来创建的新 `@timestamp` 字段,`skip_list` 参数现在自动设置为 `true`,同时对于具有 `@timestamp` 或索引排序日期字段的现有索引保留 `skip_list=false`。这种方法确保了新索引的日期直方图聚合性能优势,同时保持与现有工作负载的兼容性。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.1.md)。 | 2025 年 10 月 22 日 +[3.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.0.md) | 引入重新设计的 Discover 界面,具有日志分析和分布式追踪功能,以及 Apache Calcite 作为默认 PPL 查询引擎,具有扩展功能。使代理搜索和代理内存 API 正式可用于 AI 应用程序。为神经稀疏搜索性能改进实现 Seismic 算法,为数据转换管道实现处理器链。扩展 gRPC 对其他查询类型的支持,并添加使用 Apache Arrow Flight 的实验性流式传输。包括通过基于规则的自动标记和查询监控功能增强工作负载管理。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.3.0.md)。 | 2025 年 10 月 14 日 +[3.2.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.2.0.md) | 更新搜索相关性工作台。使 gRPC API 正式可用。引入派生源,更新工作负载管理、语义字段和星树功能。添加实验性代理内存 API 和作业调度器 API。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.2.0.md)。 | 2025 年 8 月 19 日 +[3.1.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.1.0.md) | 使 GPU 加速用于向量索引构建正式可用。引入使用 Lucene HNSW 的 Faiss 索引的内存优化搜索、用于简化语义搜索的语义字段类型以及用于搜索质量优化的搜索相关性工作台。使星树索引正式可用,支持全面的查询类型。通过 ML Commons 指标集成、OpenTelemetry 数据的自定义索引支持以及用于 JSON 操作的新 PPL 命令增强可观测性。通过 Update Agent API 和持久化 MCP 工具改进代理管理。包括不可变用户对象和新资源共享框架的安全增强。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.1.0.md)。 | 2025 年 6 月 24 日 +[3.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.0.0.md) | 升级到 Lucene 10 以改进索引和向量搜索。添加实验性 gRPC 支持和从 Kafka 和 Kinesis 进行基于拉取的摄取。引入用于向量操作的 GPU 加速和语义句子突出显示。改进范围查询性能和通过 z-score 归一化的混合搜索。添加计划-执行-反思代理和用于代理工作流的原生 MCP 协议支持。通过替换安全管理器的新 Java 代理增强安全性。包括通过查找、连接和子搜索命令改进 PPL 查询。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.0.0.md)。 | 2025 年 5 月 6 日 +[2.19.8](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.8.md) | 将捆绑的 JDK 更新到 21.0.13.1+2 以解决 CVE-2026-114938,这是 OpenJDK 17 及更高版本中的远程代码执行漏洞。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.8.md)。 | 2026 年 11 月 23 日 +[2.19.7](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.7.md) | 修复警报、作业调度、查询洞察、安全和安全分析中的错误。更新 OpenSearch Dashboards 依赖项以解决 CVE,并包括跨多个组件的基础设施和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.7.md)。 | 2026 年 10 月 20 日 +[2.19.6](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.6.md) | 包括跨多个组件的错误修复、安全更新和基础设施维护。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.6.md)。 | 2026 年 7 月 2 日 +[2.19.5](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.5.md) | 修复多个 CVE 更新的安全漏洞,涵盖包括 Assistant、Notifications、Observability 和 Reporting 在内的 Dashboards 插件。解决 Alerting、Flow Framework、Security 和 k-NN 中的错误。包括跨多个组件的基础设施和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.5.md)。 | 2026 年 3 月 10 日 +[2.19.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.4.md) | 修复包括 ML Commons、Query Insights Dashboards 和 SQL 在内的多个组件中的关键安全漏洞。解决 Flow Framework 多租户、Security 通配符匹配和 Query Insights 时间验证中的错误。包括大量 CVE 修复和跨 dashboards 插件的依赖项更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.4.md)。 | 2025 年 11 月 6 日 +[2.19.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.3.md) | 通过增强的内存处理和工作流步骤处理改进 Flow Framework。修复多个 Query Insights 和 Query Insights Dashboards 问题。跨多个组件实施安全更新。更新跨多个插件的基础设施组件和文档。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.3.md)。 | 2025 年 7 月 22 日 +[2.19.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.2.md) | 通过更好的索引处理、新的详细 API 参数和默认索引模板改进查询洞察。修复跨 Query Insights、Observability、Flow Framework 和 Dashboards 的错误。包括多个 CVE 修复、测试增强和用于工件验证的新 PGP 密钥。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.2.md)。 | 2025 年 4 月 29 日 +[2.19.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.1.md) | 为基数聚合器添加执行提示。包括 ML Commons、Query Insights Dashboards 和 Remote Metadata SDK 的错误修复。包含多个组件的维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.1.md)。 | 2025 年 2 月 27 日 +[2.19.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.0.md) | 添加工作负载管理、额外的查询洞察和模板查询。向 OpenSearch Dashboards 引入查询洞察页面。包括快照、搜索统计、星树搜索和索引管理的改进和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.19.0.md)。 | 2025 年 2 月 11 日 +[2.18.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.18.0.md) | 向 OpenSearch Dashboards 添加重新设计的主页、更新的 Discover 界面和协作工作区。包括对 ML 推理处理器和查询分组的改进。引入按字段重新排序和分页的 CAT API。包括实验性 OpenSearch Dashboards Assistant 功能。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.18.0.md)。 | 2024 年 11 月 5 日 +[2.17.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.1.md) | 包括 ML Commons、异常检测、k-NN 和 Security Analytics 的错误修复。添加各种基础设施和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.1.md)。 | 2024 年 10 月 1 日 +[2.17.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.0.md) | 包括 k-NN 中的磁盘优化向量搜索、二进制量化和字节向量编码。添加 ML 任务的异步批量摄取。提供搜索和查询性能增强以及追踪分析中的新自定义追踪源。包括基于应用程序的配置模板。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.17.0.md)。 | 2024 年 9 月 17 日 +[2.16.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.16.0.md) | 包括 k-NN 中的内置字节向量量化和二进制向量支持。为搜索管道添加新的排序、拆分和 ML 推理搜索处理器。提供基于应用程序的配置模板和其他插件以在 OpenSearch Dashboards 中集成多个数据源。包括实验性 Batch Predict ML Commons API。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.16.0.md)。 | 2024 年 8 月 6 日 +[2.15.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.15.0.md) | 包括并行摄取处理、精确搜索的 SIMD 支持以及禁用 k-NN 字段的文档值的能力。添加通配符和派生字段类型。改进单基数聚合、远程支持集群的滚动升级以及前 N 个查询的更多指标的性能。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.15.0.md)。 | 2024 年 6 月 25 日 +[2.14.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.14.0.md) | 包括通过多范围遍历对混合搜索和日期直方图查询的性能改进、Ingest API 中的 ML 模型集成、LangChain 应用程序的语义缓存、神经稀疏查询的低级向量查询接口以及改进的 k-NN 搜索过滤。提供实验性分层缓存功能。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.14.0.md)。 | 2024 年 5 月 14 日 +[2.13.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.13.0.md) | 使代理和工具以及 OpenSearch Assistant Toolkit 正式可用。在 OpenSearch 中引入向量量化。添加 LLM 防护栏和具有聚合的混合搜索。为 Apache Spark 数据源添加 Bloom 过滤器跳过索引、基于 I/O 的准入控制以及添加管理所有警报任务的警报集群的能力。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.13.0.md)。 | 2024 年 4 月 2 日 +[2.12.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.12.0.md) | 使并发段搜索和对话搜索正式可用。提供实验性 OpenSearch Assistant Toolkit,包括代理和工具、工作流自动化以及用于 OpenSearch Dashboards UI 的 OpenSearch Assistant。添加新的仅匹配文本字段、用于监控前 N 个查询的查询洞察以及嵌套字段上的 k-NN 搜索。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.12.0.md)。 | 2024 年 2 月 20 日 +[2.11.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.1.md) | 包括跨集群复制、警报、可观测性、OpenSearch Dashboards、索引管理、机器学习、安全和 Security Analytics 的维护更改和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.1.md)。 | 2023 年 11 月 30 日 +[2.11.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.0.md) | 添加多模态和稀疏神经搜索功能以及采用引用远程支持存储中存储的数据的浅快照的能力。使搜索比较工具正式可用。包括 Security Analytics 中创建威胁检测器的简化工作流以及 OpenSearch Dashboards 中改进的安全性。实验性功能包括用于分布式追踪的新框架和工具集以及对话搜索的更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.11.0.md)。 | 2023 年 10 月 16 日 +[2.10.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.10.0.md) | 使远程支持存储正式可用。添加混合搜索功能、Security Analytics 的自定义日志类型、IP2Geo 摄取处理器和分隔词频令牌过滤器。包括 OpenSearch Dashboards 的新外观和感觉以及更新 Discover 工具。添加通知的 Microsoft Teams webhook 支持。实验性功能包括并发段搜索和对话搜索。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.10.0.md)。 | 2023 年 9 月 25 日 +[2.9.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.9.0.md) | 使搜索管道和 Neural Search 插件正式可用。添加 ML 模型访问控制和与外部 ML 工具的集成。使用 Faiss 引擎实现 k-NN 字节向量和高效过滤。将警报和异常检测与 OpenSearch Dashboards 集成并添加复合监视器。添加两个新的索引编解码器算法选项。包括 Security Analytics 的新摄取架构、地理形状聚合和扩展——一种扩展 OpenSearch 功能的新机制。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.9.0.md)。 | 2023 年 7 月 24 日 +[2.8.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.8.0.md) | 添加使用 PPL 的跨集群查询、搜索管道、将段复制作为默认复制类型的选项、改进的可搜索快照性能以及使用 SigV4 身份验证的 Amazon OpenSearch Serverless 支持以支持多个数据源。包括 OpenSearch Dashboards 中的刷新、刷新和清除缓存操作的 UI。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.8.0.md)。 | 2023 年 6 月 6 日 +[2.7.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.7.0.md) | 包括可搜索快照和段复制,它们现已正式可用。添加多个数据源、可观测性功能、动态租户管理、组件模板和 OpenSearch Dashboards 中基于形状的地图过滤器。包括扁平对象字段类型、热分片识别和用于 ML 模型的新自动重新加载机制。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.7.0.md)。 | 2023 年 5 月 2 日 +[2.6.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.6.0.md) | 包括可观测性的简单架构、索引管理 UI 增强、Security Analytics 增强、协调节点级别的搜索反压以及向仪表板添加地图的能力。实验性功能包括新的 ML 模型健康仪表板、ML 中的新文本嵌入模型以及 Dashboards 中的 SigV4 身份验证。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.6.0.md)。 | 2023 年 2 月 28 日 +[2.5.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.5.0.md) | 包括索引管理 UI 增强、多层地图、可观测性的 Jaeger 支持、Debian 分发、按感知属性返回集群健康状况、集群管理器任务限制、加权区域搜索请求路由策略以及索引汇总中的查询字符串支持。实验性功能包括远程支持存储中的请求级持久性和 ML 节点的 GPU 加速。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.5.0.md)。 | 2023 年 1 月 24 日 +[2.4.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.1.md) | 包括 Gradle 检查和索引压力测试的维护更改和错误修复。添加跳过变更日志的支持。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.1.md)。 | 2022 年 12 月 13 日 +[2.4.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.0.md) | 包括 Windows 支持、时间点搜索、自定义 k-NN 过滤、笛卡尔坐标的 xy_point 和 xy_shape 字段类型、GeoHex 网格聚合以及弹性增强,包括搜索反压。在 OpenSearch Dashboards 中,此版本添加快照恢复功能、多个身份验证和保存对象的聚合视图。此版本包括以下实验性功能:可搜索快照、比较搜索结果、OpenSearch Dashboards 中的多个数据源、ML Commons 中的新模型服务框架、支持语义搜索的新 Neural Search 插件以及用于分析安全日志的新 Security Analytics 插件。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.4.0.md)。 | 2022 年 11 月 15 日 +[2.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.3.0.md) | 此版本包括以下实验性功能:段复制、远程支持存储以及 OpenSearch Dashboards 的拖放功能。实验性功能允许您测试 OpenSearch 中的新功能。由于这些功能仍在开发中,您的测试和反馈可以帮助在功能正式发布之前塑造功能的开发。我们不建议在生产中使用实验性功能。此外,此版本为 SQL 插件添加 `maketime` 和 `makedate` `datetime` 函数。为 OpenSearch Dashboards 创建新的 [OpenSearch Playground](https://playground.opensearch.org) 演示站点。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.3.0.md)。 | 2022 年 9 月 14 日 +[2.2.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.1.md) | 包括 Gradle 更新和 Gradle 检查的错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.1.md)。 | 2022 年 9 月 1 日 +[2.2.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.0.md) | 包括 ML Commons 中的 Logistic Regression 和 RCF Summarize 机器学习算法的支持、用于近似 k-NN 搜索的基于 Lucene 或 C 的 NMSLIB 和 Faiss 库、使用 SQL 和 PPL 查询按相关性搜索、可视化的自定义区域地图以及汇总增强。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.2.0.md)。 | 2022 年 8 月 11 日 +[2.1.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.1.0.md) | 包括 ML Commons 插件中专用 ML 节点的支持、SQL 中的相关性搜索和其他功能、多词聚合和快照管理。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.1.0.md)。 | 2022 年 7 月 7 日 +[2.0.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.1.md) | 包括 Alerting 和 Anomaly Detection 的错误修复和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.1.md)。 | 2022 年 6 月 16 日 +[2.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0.md) | 包括用于警报的文档级监视器、OpenSearch Notifications 插件以及 OpenSearch Dashboards 中的 Geo Map Tiles。还添加了对 Lucene 9 的支持和所有 OpenSearch 插件的错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0.md)。 | 2022 年 5 月 26 日 +[2.0.0-rc1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0-rc1.md) | 2.0.0 的候选版本。此版本允许您在 GA 版本之前预览即将发布的 2.0.0 版本。预览版本添加文档级警报、对 Lucene 9 的支持以及在文档级安全性中使用词条查找查询的能力。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-2.0.0-rc1.md)。 | 2022 年 5 月 3 日 +[1.3.20](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.20.md) | 包括 Anomaly Detection Dashboards 的增强、Alerting 和 Dashboards Reports 的错误修复以及多个 OpenSearch 组件的维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.20.md)。 | 2024 年 12 月 11 日 +[1.3.19](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.19.md) | 包括 OpenSearch 安全、OpenSearch 安全 Dashboards 和异常检测的错误修复和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.19.md)。 | 2024 年 8 月 27 日 +[1.3.18](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.18.md) | 包括 OpenSearch 安全的维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.18.md)。 | 2024 年 7 月 16 日 +[1.3.17](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.17.md) | 包括 OpenSearch 安全和 OpenSearch Dashboards 安全的维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.17.md)。 | 2024 年 6 月 6 日 +[1.3.16](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.16.md) | 包括 OpenSearch 安全、索引管理、Performance Analyzer 和报告的错误修复和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.16.md)。 | 2024 年 4 月 23 日 +[1.3.15](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.15.md) | 包括跨集群复制、SQL、OpenSearch Dashboards 报告和警报的错误修复和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.15.md)。 | 2024 年 3 月 5 日 +[1.3.14](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.14.md) | 包括 OpenSearch 安全和 OpenSearch Dashboards 安全的错误修复和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.14.md)。 | 2023 年 12 月 12 日 +[1.3.13](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.13.md) | 包括 Anomaly Detection 的错误修复,添加维护更新和基础设施增强。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.13.md)。 | 2023 年 9 月 21 日 +[1.3.12](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.12.md) | 添加 OpenSearch 安全和 OpenSearch Dashboards 可观测性的维护更新。包括可观测性、OpenSearch Dashboards 可视化和 OpenSearch 安全的错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.12.md)。 | 2023 年 8 月 10 日 +[1.3.11](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.11.md) | 添加 OpenSearch 安全、OpenSearch Dashboards 安全和 ML Commons 的维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.11.md)。 | 2023 年 6 月 29 日 +[1.3.10](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.10.md) | 添加基础设施增强以及异常检测、可观测性和安全的维护更新。包括索引管理和 OpenSearch 安全的错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.10.md)。 | 2023 年 5 月 18 日 +[1.3.9](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.9.md) | 添加 Debian 支持。包括 OpenSearch 核心、k-NN 和 OpenSearch 安全的升级、增强和维护更新。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.9.md)。 | 2023 年 3 月 16 日 +[1.3.8](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.8.md) | 添加 OpenSearch 安全增强。更新工具脚本以在 Windows 上运行。包括 Anomaly Detection 和 OpenSearch 安全的维护更新和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.8.md)。 | 2023 年 2 月 2 日 +[1.3.7](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.7.md) | 添加 Windows 支持。包括错误处理的维护更新和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.7.md)。 | 2022 年 12 月 13 日 +[1.3.6](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.6.md) | 包括 OpenSearch Security Dashboards 插件中租户的维护更新和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.6.md)。 | 2022 年 10 月 6 日 +[1.3.5](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.5.md) | 包括 Gradle 检查和 OpenSearch 安全的维护更新和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.5.md)。 | 2022 年 9 月 1 日 +[1.3.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.4.md) | 包括 OpenSearch 和 OpenSearch Dashboards 的维护更新和错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.4.md)。 | 2022 年 7 月 14 日 +[1.3.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.3.md) | 添加 Anomaly Detection 和 ML Commons 的增强。Anomaly Detection、Observability 和 k-NN 的错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.3.md)。 | 2022 年 6 月 9 日 +[1.3.2](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.2.md) | Anomaly Detection 和 Security Dashboards Plugin 的错误修复,添加使用 RPM 安装 OpenSearch 的选项,以及 ML Commons 执行任务的增强,以及在 Anomaly Detection 中移除 job-scheduler zip。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.2.md)。 | 2022 年 5 月 5 日 +[1.3.1](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.1.md) | 使用文档级安全性时的错误修复,并调整 ML Commons 以使用最新的 RCF jar 和 `protostuff` 到 RCF 模型序列化。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.1.md)。 | 2022 年 3 月 30 日 +[1.3.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.0.md) | 向 Validate Detector API 添加模型类型验证、连续转换、自定义操作、应用策略参数到 Explain API、默认操作重试以及新的滚动和转换条件到索引管理,新的 ML Commons 插件、解析命令到 SQL、应用程序分析、实时尾部、相关性和事件弹出到可观测性,以及自动回移和对 Performance Analyzer 的 OPENSEARCH_JAVA_HOME 的支持。错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.3.0.md)。 | 2022 年 3 月 17 日 +[1.2.4](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.4.md) | 将 Performance Analyzer、SQL 和 Security 插件更新到 Log4j 2.17.1,将 Alerting 和 Job Scheduler 更新到 cron-utils 9.1.6,并更新 Anomaly Detection 和 SQL 中的 `gson`。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.4.md)。 | 2022 年 1 月 18 日 +[1.2.3](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.3.md) | 按照 [CVE-2021-45105](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45105) 中的建议将 OpenSearch 中使用的 Log4j 版本更新到 Log4j 2.17.0。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-1.2.3.md)。 | 2021 年 12 月 22 日 +[1.2.0](https://github.com/opensearch-project/OpenSearch/blob/main/release-notes/opensearch.release-notes-1.2.0.md) | 添加可观测性、Anomaly Detection 的新验证 API、分片级索引反压、SQL 和 PPL 的新 `match` 查询类型、k-NN 中对 Faiss 库的支持以及自定义 Dashboards 品牌。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/OpenSearch/blob/main/release-notes/opensearch.release-notes-1.2.0.md)。 | 2021 年 11 月 23 日 +[1.1.0](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.1.0.md) | 添加跨集群复制、索引管理的安全性、存储桶级警报、帮助从 Elasticsearch OSS 升级到 OpenSearch 的 CLI,以及 Anomaly Detection 插件中高基数数据的增强。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.1.0.md)。 | 2021 年 10 月 5 日 +[1.0.1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.1.md) | 错误修复。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.1.md)。 | 2021 年 9 月 1 日 +[1.0.0](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0.md) | 正式发布版本。为需要在连接前进行版本检查的客户端添加兼容性设置。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0.md)。 | 2021 年 7 月 12 日 +[1.0.0-rc1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-rc1.md) | 首个候选版本。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-rc1.md)。 | 2021 年 6 月 7 日 +[1.0.0-beta1](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-beta1.md) | 初始 beta 版本。重构插件以与 OpenSearch 配合使用。有关完整的发布亮点列表,请参阅[发行说明](https://github.com/opensearch-project/opensearch-build/tree/main/release-notes/opensearch-release-notes-1.0.0-beta1.md)。 | 2021 年 5 月 13 日 diff --git a/i18n/zh/aggregations/bucket/auto-interval-date-histogram.md b/i18n/zh/aggregations/bucket/auto-interval-date-histogram.md new file mode 100644 index 00000000..c39c4744 --- /dev/null +++ b/i18n/zh/aggregations/bucket/auto-interval-date-histogram.md @@ -0,0 +1,365 @@ +--- +title: 自动间隔日期直方图 +--- + +# 自动间隔日期直方图聚合 + +与[日期直方图聚合](/aggregations/bucket/date-histogram)类似(在日期直方图聚合中必须指定间隔),`auto_date_histogram` 是一种多桶聚合,它根据您提供的桶数量和数据的时间范围自动创建日期直方图桶。返回的实际桶数量始终小于或等于您指定的桶数量。这种聚合在处理时间序列数据时特别有用,可以在不同时间间隔上可视化或分析数据,而无需手动指定间隔大小。 + +## 间隔 + +桶间隔是根据收集的数据选择的,以确保返回的桶数量小于或等于请求的数量。 + +下表列出了每个时间单位可能返回的间隔。 + +| 单位 | 间隔 | +| :--- | :---| +| 秒| 1、5、10 和 30 的倍数 | +| 分钟| 1、5、10 和 30 的倍数 | +| 小时 | 1、3 和 12 的倍数 | +| 天 | 1 和 7 的倍数 | +| 月 | 1 和 3 的倍数 | +| 年 | 1、5、10、20、50 和 100 的倍数 | + +如果聚合返回太多桶(例如,每日桶),OpenSearch 将自动减少桶的数量以确保可管理的结果。它不会返回确切请求数量的每日桶,而是将它们减少约 1/7 的倍数。例如,如果您请求 70 个桶,但数据包含太多每日间隔,OpenSearch 可能只返回 10 个桶,将数据分组到更大的间隔(例如周)中,以避免结果数量过多。这有助于优化聚合,并在数据过多时防止过度详细。 + +## 参数 + +自动间隔日期直方图聚合接受以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`field` | String | 要聚合的字段。该字段必须包含日期或时间戳值。`field` 或 `script` 二者必须指定其一。 +`buckets` | Integer | 所需的桶数量。返回的桶数量小于或等于所需数量。可选。默认值为 `10`。 +`minimum_interval` | String | 要使用的最小间隔。指定最小间隔可以使聚合过程更高效。有效值为 `year`、`month`、`day`、`hour`、`minute` 和 `second`。可选。 +`time_zone` | String | 指定使用默认时区(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`。可选。默认值为 `UTC`。有关更多信息,请参阅[时区](#时区)。 +`format` | String | 返回表示桶键的日期的格式。可选。默认值为字段映射中指定的格式。有关更多信息,请参阅[日期格式](#日期格式)。 +`script` | String | 用于将值聚合到桶中的文档级或值级脚本。`field` 或 `script` 二者必须指定其一。 +`missing` | String | 指定如何处理字段值缺失的文档。默认情况下,这些文档会被忽略。如果在 `missing` 参数中指定日期值,则字段值缺失的所有文档都将被收集到具有指定日期的桶中。 + +## 示例 + +在以下示例中,您将搜索包含博客文章的索引。 + +首先,为此索引创建映射并将 `date_posted` 字段指定为 `date` 类型: + +```json +PUT blogs +{ + "mappings" : { + "properties" : { + "date_posted" : { + "type" : "date", + "format" : "yyyy-MM-dd" + } + } + } +} +``` + +接下来,将以下文档索引到 `blogs` 索引中: + +```json +PUT blogs/_doc/1 +{ + "name": "Semantic search in OpenSearch", + "date_posted": "2022-04-17" +} +``` + +```json +PUT blogs/_doc/2 +{ + "name": "Sparse search in OpenSearch", + "date_posted": "2022-05-02" +} +``` + +```json +PUT blogs/_doc/3 +{ + "name": "Distributed tracing with Data Prepper", + "date_posted": "2022-04-25" +} +``` + +```json +PUT blogs/_doc/4 +{ + "name": "Observability in OpenSearch", + "date_posted": "2023-03-23" +} + +``` + +要使用 `auto_date_histogram` 聚合,请指定包含日期或时间戳值的字段。例如,要将博客文章按 `date_posted` 聚合到两个桶中,请发送以下请求: + +```json +GET /blogs/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "buckets": 2 + } + } + } +} +``` + +## 示例响应 + +响应显示博客文章被聚合到两个桶中。间隔自动设置为 1 年,所有三篇 2022 年的博客文章收集在一个桶中,2023 年的博客文章在另一个桶中: + +```json +{ + "took": 20, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "histogram": { + "buckets": [ + { + "key_as_string": "2022-01-01", + "key": 1640995200000, + "doc_count": 3 + }, + { + "key_as_string": "2023-01-01", + "key": 1672531200000, + "doc_count": 1 + } + ], + "interval": "1y" + } + } +} +``` + +## 返回的桶 + +每个桶包含以下信息: + +```json +{ + "key_as_string": "2023-01-01", + "key": 1672531200000, + "doc_count": 1 +} +``` + +在 OpenSearch 中,日期在内部存储为 64 位整数,表示自纪元以来的时间戳(以毫秒为单位)。在聚合响应中,每个桶的 `key` 都作为这样的时间戳返回。`key_as_string` 值显示相同的时间戳,但根据 [`format`](#日期格式) 参数格式化为日期字符串。`doc_count` 字段包含桶中的文档数量。 + +## 日期格式 + +如果不指定 `format` 参数,则使用字段映射中定义的格式(如前面的响应中所示)。要修改格式,请指定 `format` 参数: + +```json +GET /blogs/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "format": "yyyy-MM-dd HH:mm:ss" + } + } + } +} +``` + +`key_as_string` 字段现在以指定的格式返回: + +```json +{ + "key_as_string": "2023-01-01 00:00:00", + "key": 1672531200000, + "doc_count": 1 +} +``` + +或者,您可以指定内置日期[格式](/mappings/supported-field-types/date/#formats)之一: + +```json +GET /blogs/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "format": "basic_date_time_no_millis" + } + } + } +} +``` + +`key_as_string` 字段现在以指定的格式返回: + +```json +{ + "key_as_string": "20230101T000000Z", + "key": 1672531200000, + "doc_count": 1 +} +``` + +## 时区 + +默认情况下,日期以 UTC 存储和处理。`time_zone` 参数允许您指定不同的时区进行分桶。您可以将 `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`。 + +例如,将以下文档索引到索引中: + +```json +PUT blogs1/_doc/1 +{ + "name": "Semantic search in OpenSearch", + "date_posted": "2022-04-17T01:00:00.000Z" +} +``` + +```json +PUT blogs1/_doc/2 +{ + "name": "Sparse search in OpenSearch", + "date_posted": "2022-04-17T04:00:00.000Z" +} +``` + +首先,在不指定时区的情况下运行聚合: + +```json +GET /blogs1/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "buckets": 2, + "format": "yyyy-MM-dd HH:mm:ss" + } + } + } +} +``` + +响应包含两个 3 小时的桶,从 2022 年 4 月 17 日午夜 UTC 开始: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "histogram": { + "buckets": [ + { + "key_as_string": "2022-04-17 01:00:00", + "key": 1650157200000, + "doc_count": 1 + }, + { + "key_as_string": "2022-04-17 04:00:00", + "key": 1650168000000, + "doc_count": 1 + } + ], + "interval": "3h" + } + } +} +``` + +现在,指定 `time_zone` 为 `-02:00`: + +```json +GET /blogs1/_search +{ + "size": 0, + "aggs": { + "histogram": { + "auto_date_histogram": { + "field": "date_posted", + "buckets": 2, + "format": "yyyy-MM-dd HH:mm:ss", + "time_zone": "-02:00" + } + } + } +} +``` + +响应包含两个桶,其中开始时间偏移了 2 小时,从 2022 年 4 月 16 日 23:00 开始: + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "histogram": { + "buckets": [ + { + "key_as_string": "2022-04-16 23:00:00", + "key": 1650157200000, + "doc_count": 1 + }, + { + "key_as_string": "2022-04-17 02:00:00", + "key": 1650168000000, + "doc_count": 1 + } + ], + "interval": "3h" + } + } +} +``` + +::: info NOTE +在使用带有夏令时 (DST) 更改的时区时,接近过渡的桶的大小可能与相邻桶的大小略有不同。 +::: diff --git a/i18n/zh/aggregations/bucket/children.md b/i18n/zh/aggregations/bucket/children.md new file mode 100644 index 00000000..9e1cfe3a --- /dev/null +++ b/i18n/zh/aggregations/bucket/children.md @@ -0,0 +1,151 @@ +--- +title: 子文档 +--- + +# 子文档聚合 + +`children` 聚合是一种桶聚合,它根据索引中定义的父子关系创建包含子文档的单个桶。 + +`children` 聚合与[联接字段类型](/mappings/supported-field-types/join/)一起使用,以聚合与父文档关联的子文档。 + +`children` 聚合标识与特定子关系名称匹配的子文档,而 [`parent` 聚合](/aggregations/bucket/parent)则标识具有匹配子文档的父文档。两种聚合都将子关系名称作为输入。 + +## 参数 + +`children` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `type` | 必需 | String | 联接字段中子类型的名称。这标识要使用的父子关系。 | + +## 示例 + +以下示例构建了一个包含三名员工的小型公司数据库。每个员工记录都与父部门记录具有子 `join` 关系。 + +首先,创建一个带有 `join` 字段的 `company` 索引,该字段将部门(父)映射到员工(子): + +```json +PUT /company +{ + "mappings": { + "properties": { + "join_field": { + "type": "join", + "relations": { + "department": "employee" + } + }, + "department_name": { + "type": "keyword" + }, + "employee_name": { + "type": "keyword" + }, + "salary": { + "type": "double" + }, + "hire_date": { + "type": "date" + } + } + } +} +``` + +接下来,使用三个部门和三名员工填充数据。父子分配如下表所示。 + +| 部门(父) | 员工(子) | +| :-- | :-- | +| `Accounting` | `Abel Anderson`、`Betty Billings` | +| `Engineering` | `Carl Carter` | +| `HR` | 无 | + +`routing` 参数确保父文档和子文档都存储在同一分片上,这是 OpenSearch 中父子关系正常运行所必需的: + +```json +POST _bulk?routing=1 +{ "create": { "_index": "company", "_id": "1" } } +{ "type": "department", "department_name": "Accounting", "join_field": "department" } +{ "create": { "_index": "company", "_id": "2" } } +{ "type": "department", "department_name": "Engineering", "join_field": "department" } +{ "create": { "_index": "company", "_id": "3" } } +{ "type": "department", "department_name": "HR", "join_field": "department" } +{ "create": { "_index": "company", "_id": "4" } } +{ "type": "employee", "employee_name": "Abel Anderson", "salary": 120000, "hire_date": "2024-04-04", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "5" } } +{ "type": "employee", "employee_name": "Betty Billings", "salary": 140000, "hire_date": "2023-05-05", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "6" } } +{ "type": "employee", "employee_name": "Carl Carter", "salary": 140000, "hire_date": "2020-06-06", "join_field": { "name": "employee", "parent": "2" } } +``` + +以下请求查询所有部门,然后过滤名为 `Accounting` 的部门。然后使用 `children` 聚合选择与 `Accounting` 部门具有子关系的两个文档。最后,`avg` 子聚合返回 `Accounting` 员工薪水的平均值: + +```json +GET /company/_search +{ + "size": 0, + "query": { + "bool": { + "filter": [ + { + "term": { + "join_field": "department" + } + }, + { + "term": { + "department_name": "Accounting" + } + } + ] + } + }, + "aggs": { + "acc_employees": { + "children": { + "type": "employee" + }, + "aggs": { + "avg_salary": { + "avg": { + "field": "salary" + } + } + } + } + } +} +``` + +## 示例响应 + +响应返回选定的部门桶,找到该部门的 `employee` 类型子项,并计算他们薪水的 `avg`: + +```json +{ + "took": 379, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "acc_employees": { + "doc_count": 2, + "avg_salary": { + "value": 130000 + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/composite.md b/i18n/zh/aggregations/bucket/composite.md new file mode 100644 index 00000000..ea08bd58 --- /dev/null +++ b/i18n/zh/aggregations/bucket/composite.md @@ -0,0 +1,817 @@ +--- +title: 复合 +--- + +# 复合聚合 + +`composite` 聚合基于一个或多个文档字段或源创建桶。`composite` 聚合为各个源值的每种组合创建一个桶。默认情况下,结果中会省略一个或多个单独字段中具有缺失值的组合。 + +每个源具有以下四种聚合类型之一: + +- `terms` 类型按唯一(通常是 `String`)值分组。 +- `histogram` 类型按指定宽度的桶进行数值分组。 +- `date_histogram` 类型按指定宽度的日期或时间范围分组。 +- `geotile_grid` 类型将地理点分组到具有指定分辨率的网格中。 + +`composite` 聚合通过将其源键组合成桶来工作。生成的桶是有序的,包括跨源和源内: + +- **跨源**:桶按聚合请求中源的顺序嵌套。 +- **源内**:每个源中值的顺序决定该源的桶顺序。排序可以是字母、数字、日期时间或地理瓦片,具体取决于源类型。 + +考虑来自马拉松参赛者索引的这些字段: + +```json +{... "city": "Albuquerque", "place": "Bronze" ...} +{... "city": "Boston", ...} +{... "city": "Chicago", "place": "Bronze" ...} +{... "city": "Albuquerque", "place": "Gold" ...} +{... "city": "Chicago", "place": "Silver" ...} +{... "city": "Boston", "place": "Bronze" ...} +{... "city": "Chicago", "place": "Gold" ...} +``` + +假设请求指定源如下: + +```json + ... + "sources": [ + { "marathon_city": { "terms": { "field": "city" }}}, + { "participant_medal": { "terms": { "field": "place" }}} + ], + ... +``` + +::: warning IMPORTANT +您必须为每个源分配一个唯一的键名。 +::: + +生成的 `composite` 包含以下桶,按顺序排列: + +```json +{ "city": "Albuquerque", "place": "Bronze" } +{ "city": "Albuquerque", "place": "Gold" } +{ "city": "Boston", "place": "Bronze" } +{ "city": "Boston", "place": "Silver" } +{ "city": "Chicago", "place": "Bronze" } +{ "city": "Chicago", "place": "Gold" } +{ "city": "Chicago", "place": "Silver" } +``` + +请注意,`city` 和 `place` 字段都按字母顺序排序。 + +## 参数 + +`composite` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `sources` | 必需 | Array | 源对象数组。有效类型为 [`terms`](#terms)、[`histogram`](#histogram)、[`date_histogram`](#date-histogram) 和 [`geotile_grid`](#geotile-grid)。 | +| `size` | 可选 | Numeric | 要在结果中返回的 `composite` 桶数量。默认值为 `10`。请参阅[分页复合结果](#分页复合结果)。 | +| `after` | 可选 | String | 一个键,指定从何处恢复显示分页的 `composite` 桶。请参阅[分页复合结果](#分页复合结果)。 | +| `order` | 可选 | String | 对于每个源,是按升序还是降序排列值。有效值为 `asc` 和 `desc`。默认值为 `asc`。 | +| `missing_bucket` | 可选 | Boolean | 对于每个源,是否包含具有缺失值的文档。默认值为 `false`。如果设置为 `true`,OpenSearch 将包含这些文档,并提供 `null` 作为字段的键。空值在升序中排名第一。 | + +::: info NOTE +有关聚合特定参数,请参阅相应的聚合文档。 +::: + +## Terms + +使用 `terms` 聚合来聚合字符串或布尔数据。有关更多信息,请参阅 [Terms 聚合](/aggregations/bucket/terms)。 + +::: info NOTE +您可以使用 `terms` 源为任何类型的数据创建复合桶。但是,由于 `terms` 源为每个唯一值创建桶,因此您通常会为数值数据使用 `histogram` 源。 +::: + +以下示例请求返回 OpenSearch Dashboards 示例电子商务数据中星期几和客户性别的前 `4` 个复合桶: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "day": { "terms": { "field": "day_of_week" }}}, + { "gender": { "terms": { "field": "customer_gender" }}} + ], + "size": 4 + } + } + } +} +``` + +由于此示例的数据集包含每个桶的有效数据,因此聚合为性别和星期几的每种组合生成一个桶,总共产生 14 个桶。 + +由于请求指定 `size` 为 `4`,因此响应包含前四个复合桶。由于源是 `terms`,桶按升序字母顺序排序,包括跨源和源内: + +```json +{ + "took": 51, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "day": "Monday", + "gender": "MALE" + }, + "buckets": [ + { + "key": { + "day": "Friday", + "gender": "FEMALE" + }, + "doc_count": 399 + }, + { + "key": { + "day": "Friday", + "gender": "MALE" + }, + "doc_count": 371 + }, + { + "key": { + "day": "Monday", + "gender": "FEMALE" + }, + "doc_count": 320 + }, + { + "key": { + "day": "Monday", + "gender": "MALE" + }, + "doc_count": 259 + } + ] + } + } +} +``` + +您可以使用响应中返回的 `after_key` 查看更多结果。请参阅下一节中的示例。 + +## Histogram + +使用 `histogram` 源创建数值数据的复合聚合。有关更多信息,请参阅[直方图聚合](/aggregations/bucket/histogram)。 + +对于 `histogram` 源,每个 `composite` 桶键中使用的名称是键的直方图间隔中的最低值。每个源直方图间隔包含 `[lower_bound, lower_bound + interval)` 范围内的值。第一个间隔的名称是源字段中的最低值(对于升序值源)。 + +以下示例请求根据桶宽度分别为 `1` 和 `50`,返回 OpenSearch Dashboards 示例电子商务数据中数量和基本单价的前 `6` 个复合桶: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "quantity": { "histogram": { "field": "products.quantity", "interval": 1 }}}, + { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 50 }}} + ], + "size": 6 + } + } + } +} +``` + +聚合返回两个 `histogram` 源的前 `6` 个桶键和文档计数。与 `terms` 示例一样,桶在源字段内和跨源字段排序。但是,在这种情况下,顺序是数值的,并且基于每个直方图宽度的包含下界: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "quantity": 2, + "unit_price": 150 + }, + "buckets": [ + { + "key": { + "quantity": 1, + "unit_price": 0 + }, + "doc_count": 17691 + }, + { + "key": { + "quantity": 1, + "unit_price": 50 + }, + "doc_count": 5014 + }, + { + "key": { + "quantity": 1, + "unit_price": 100 + }, + "doc_count": 482 + }, + { + "key": { + "quantity": 1, + "unit_price": 150 + }, + "doc_count": 148 + }, + { + "key": { + "quantity": 1, + "unit_price": 200 + }, + "doc_count": 32 + }, + { + "key": { + "quantity": 2, + "unit_price": 150 + }, + "doc_count": 4 + } + ] + } + } +} +``` + +每个字段的桶键是字段间隔的下界。例如,第一个 `composite` 桶的 `unit_price` 键为 `0`。 + +要检索接下来的 `6` 个桶,请使用响应中的 `after_key` 对象提供 `after` 参数,如下所示: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "quantity": { "histogram": { "field": "products.quantity", "interval": 1 }}}, + { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 50 }}} + ], + "size": 6, + "after": { + "quantity": 2, + "unit_price": 150 + } + } + } + } +} +``` + +只剩下两个桶: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "quantity": 2, + "unit_price": 500 + }, + "buckets": [ + { + "key": { + "quantity": 2, + "unit_price": 200 + }, + "doc_count": 8 + }, + { + "key": { + "quantity": 2, + "unit_price": 500 + }, + "doc_count": 4 + } + ] + } + } +} +``` + +## Date histogram + +要创建日期范围的复合聚合,请使用 `date_histogram` 聚合。有关更多信息,请参阅[日期直方图聚合](/aggregations/bucket/date-histogram)。 + +OpenSearch 将日期(包括 `date_interval` 桶键)表示为 `long` 整数,表示 [Unix 时间](https://en.wikipedia.org/wiki/Unix_time)中自纪元以来的毫秒数。您可以使用 `format` 参数格式化日期输出。这不会改变键的顺序。 + +OpenSearch 以 UTC 存储日期时间。您可以使用 `time_zone` 参数在不同时区显示输出结果。 + +以下示例请求根据桶宽度分别为 1 年和 1 天,返回 OpenSearch Dashboards 示例电子商务数据中每个售出产品创建的年份和售出日期的前 `4` 个复合桶: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "product_creation_date": { "date_histogram": { "field": "products.created_on", "calendar_interval": "1y", "format": "yyyy" }}}, + { "order_date": { "date_histogram": { "field": "order_date", "calendar_interval": "1d", "format": "yyyy-MM-dd" }}} + ], + "size": 4 + } + } + } +} +``` + +聚合返回格式化的基于日期的桶键和计数。对于 `date_interval` 复合聚合,字段排序按日期: + +```json +{ + "took": 21, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "product_creation_date": "2016", + "order_date": "2025-02-23" + }, + "buckets": [ + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-20" + }, + "doc_count": 146 + }, + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-21" + }, + "doc_count": 153 + }, + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-22" + }, + "doc_count": 143 + }, + { + "key": { + "product_creation_date": "2016", + "order_date": "2025-02-23" + }, + "doc_count": 140 + } + ] + } + } +} +``` + +## Geotile grid + +使用 `geotile_grid` 源将 `geo_point` 值聚合到表示地图瓦片的桶中。与其他复合聚合源一样,默认情况下,结果仅包含包含数据的桶。有关更多信息,请参阅[地理瓦片网格聚合](/aggregations/bucket/geotile-grid)。 + +每个单元对应一个[地图瓦片](https://en.wikipedia.org/wiki/Tiled_web_map)。单元标签使用 `{zoom}/{x}/{y}` 格式。 + +以下示例请求返回精度为 `8` 的 `geoip.location` 字段中包含位置的前 `6` 个瓦片: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "tile": { "geotile_grid": { "field": "geoip.location", "precision": 8 } } } + ], + "size": 6 + } + } + } +} +``` + +聚合返回指定的 `geo_tiles` 和点计数: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "tile": "8/122/104" + }, + "buckets": [ + { + "key": { + "tile": "8/43/102" + }, + "doc_count": 310 + }, + { + "key": { + "tile": "8/75/96" + }, + "doc_count": 896 + }, + { + "key": { + "tile": "8/75/124" + }, + "doc_count": 178 + }, + { + "key": { + "tile": "8/122/104" + }, + "doc_count": 408 + } + ] + } + } +} +``` + +## 组合源 + +您可以组合两个或多个不同类型的源。 + +以下示例请求返回由三种不同源类型组成的桶: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "order_date": { "date_histogram": { "field": "order_date", "calendar_interval": "1M", "format": "yyyy-MM" }}}, + { "gender": { "terms": { "field": "customer_gender" }}}, + { "unit_price": { "histogram": { "field": "products.base_unit_price", "interval": 200 }}} + ], + "size": 10 + } + } + } +} +``` + +聚合返回混合类型的 `composite` 桶和文档计数: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "order_date": "2025-03", + "gender": "MALE", + "unit_price": 200 + }, + "buckets": [ + { + "key": { + "order_date": "2025-02", + "gender": "FEMALE", + "unit_price": 0 + }, + "doc_count": 1517 + }, + { + "key": { + "order_date": "2025-02", + "gender": "MALE", + "unit_price": 0 + }, + "doc_count": 1369 + }, + { + "key": { + "order_date": "2025-02", + "gender": "MALE", + "unit_price": 200 + }, + "doc_count": 6 + }, + { + "key": { + "order_date": "2025-02", + "gender": "MALE", + "unit_price": 400 + }, + "doc_count": 1 + }, + { + "key": { + "order_date": "2025-03", + "gender": "FEMALE", + "unit_price": 0 + }, + "doc_count": 3656 + }, + { + "key": { + "order_date": "2025-03", + "gender": "FEMALE", + "unit_price": 200 + }, + "doc_count": 1 + }, + { + "key": { + "order_date": "2025-03", + "gender": "MALE", + "unit_price": 0 + }, + "doc_count": 3530 + }, + { + "key": { + "order_date": "2025-03", + "gender": "MALE", + "unit_price": 200 + }, + "doc_count": 7 + } + ] + } + } +} +``` + +## 子聚合 + +复合聚合与揭示 `composite` 桶中文档信息的子聚合结合使用时最有用。 + +以下示例请求比较 OpenSearch Dashboards 示例电子商务数据中每周每天基于性别的平均支出: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "composite_buckets": { + "composite": { + "sources": [ + { "weekday": { "terms": { "field": "day_of_week" }}}, + { "gender": { "terms": { "field": "customer_gender" }}} + ], + "size": 6 + }, + "aggs": { + "avg_spend": { + "avg": { "field": "taxful_total_price" } + } + } + } + } +} +``` + +聚合返回前 `6` 个桶的平均 `taxful_total_price`: + +```json +{ + "took": 30, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "composite_buckets": { + "after_key": { + "weekday": "Saturday", + "gender": "MALE" + }, + "buckets": [ + { + "key": { + "weekday": "Friday", + "gender": "FEMALE" + }, + "doc_count": 399, + "avg_spend": { + "value": 71.7733395989975 + } + }, + { + "key": { + "weekday": "Friday", + "gender": "MALE" + }, + "doc_count": 371, + "avg_spend": { + "value": 79.72514108827494 + } + }, + { + "key": { + "weekday": "Monday", + "gender": "FEMALE" + }, + "doc_count": 320, + "avg_spend": { + "value": 72.1588623046875 + } + }, + { + "key": { + "weekday": "Monday", + "gender": "MALE" + }, + "doc_count": 259, + "avg_spend": { + "value": 86.1754946911197 + } + }, + { + "key": { + "weekday": "Saturday", + "gender": "FEMALE" + }, + "doc_count": 365, + "avg_spend": { + "value": 73.53236301369863 + } + }, + { + "key": { + "weekday": "Saturday", + "gender": "MALE" + }, + "doc_count": 371, + "avg_spend": { + "value": 72.78092360175202 + } + } + ] + } + } +} +``` + +## 分页复合结果 + +如果请求产生的桶数量超过 `size`,则返回 `size` 个桶。在这种情况下,结果包含一个 `after_key` 对象,其中包含列表中下一个桶的键。要检索请求的接下来的 `size` 个桶,请再次发送请求,在 `after` 参数中提供 `after_key`。有关示例,请参阅 [Histogram](#histogram) 中的请求。 + +::: warning IMPORTANT +始终使用 `after_key` 而不是复制最后一个桶来继续分页响应。两者有时不同。 +::: + +## 通过索引排序提高性能 + +要加速大型数据集上的复合聚合,您可以使用聚合源中使用的相同字段和顺序对索引进行排序。当 `index.sort.field` 和 `index.sort.order` 与复合聚合中使用的源字段和顺序匹配时,OpenSearch 可以更高效地返回结果,并使用更少的内存。虽然索引排序在索引期间会增加少量开销,但复合聚合的查询性能提升是显著的。 + +以下示例请求为 `my-sorted-index` 索引中的每个字段设置排序字段和排序顺序: + +```json +PUT /my-sorted-index +{ + "settings": { + "index": { + "sort.field": ["customer_id", "timestamp"], + "sort.order": ["asc", "desc"] + } + }, + "mappings": { + "properties": { + "customer_id": { + "type": "keyword" + }, + "timestamp": { + "type": "date" + }, + "price": { + "type": "double" + } + } + } +} +``` + +以下请求在 `my-sorted-index` 索引上创建复合聚合。由于索引按 `customer_id` 升序和 `timestamp` 降序排序,并且聚合源与该排序顺序匹配,因此此查询运行更快,内存压力更小: + +```json +GET /my-sorted-index/_search +{ + "size": 0, + "aggs": { + "my_buckets": { + "composite": { + "size": 1000, + "sources": [ + { "customer": { "terms": { "field": "customer_id", "order": "asc" } } }, + { "time": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } } + ] + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/parent.md b/i18n/zh/aggregations/bucket/parent.md new file mode 100644 index 00000000..5153e866 --- /dev/null +++ b/i18n/zh/aggregations/bucket/parent.md @@ -0,0 +1,146 @@ +--- +title: 父文档 +--- + +# 父文档聚合 + +`parent` 聚合是一种桶聚合,它根据索引中定义的父子关系创建包含父文档的单个桶。此聚合使您能够对具有相同匹配子文档的父文档执行分析,从而实现强大的分层数据分析。 + +`parent` 聚合与 [`join` 字段类型](/mappings/supported-field-types/join/)一起使用,该类型在同一索引内的文档之间建立父子关系。 + +`parent` 聚合标识具有匹配子文档的父文档,而 [`children` 聚合](/aggregations/bucket/children)则标识与特定子关系匹配的子文档。两种聚合都将子关系名称作为输入。 + +## 参数 + +`parent` 聚合接受以下参数: + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `type` | 必需 | String | `join` 字段中子类型的名称。 | + +## 示例 + +以下示例构建了一个包含三名员工的小型公司数据库。每个员工记录都与父部门记录具有子 `join` 关系。 + +首先,创建一个带有 `join` 字段的 `company` 索引,该字段将部门(父)映射到员工(子): + +```json +PUT /company +{ + "mappings": { + "properties": { + "join_field": { + "type": "join", + "relations": { + "department": "employee" + } + }, + "department_name": { + "type": "keyword" + }, + "employee_name": { + "type": "keyword" + }, + "salary": { + "type": "double" + }, + "hire_date": { + "type": "date" + } + } + } +} +``` + +接下来,使用三个部门和三名员工填充数据。父子分配如下表所示。 + +| 部门(父) | 员工(子) | +| :-- | :-- | +| `Accounting` | `Abel Anderson`、`Betty Billings` | +| `Engineering` | `Carl Carter` | +| `HR` | 无 | + +`routing` 参数确保父文档和子文档都存储在同一分片上,这是 OpenSearch 中父子关系正常运行所必需的: + +```json +POST _bulk?routing=1 +{ "create": { "_index": "company", "_id": "1" } } +{ "type": "department", "department_name": "Accounting", "join_field": "department" } +{ "create": { "_index": "company", "_id": "2" } } +{ "type": "department", "department_name": "Engineering", "join_field": "department" } +{ "create": { "_index": "company", "_id": "3" } } +{ "type": "department", "department_name": "HR", "join_field": "department" } +{ "create": { "_index": "company", "_id": "4" } } +{ "type": "employee", "employee_name": "Abel Anderson", "salary": 120000, "hire_date": "2024-04-04", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "5" } } +{ "type": "employee", "employee_name": "Betty Billings", "salary": 140000, "hire_date": "2023-05-05", "join_field": { "name": "employee", "parent": "1" } } +{ "create": { "_index": "company", "_id": "6" } } +{ "type": "employee", "employee_name": "Carl Carter", "salary": 140000, "hire_date": "2020-06-06", "join_field": { "name": "employee", "parent": "2" } } +``` + +最后,运行对所有与一个或多个员工具有父关系的部门的聚合: + +```json +GET /company/_search +{ + "size": 0, + "aggs": { + "all_departments": { + "parent": { + "type": "employee" + }, + "aggs": { + "departments": { + "terms": { + "field": "department_name" + } + } + } + } + } +} +``` + +## 示例响应 + +`all_departments` 父聚合返回所有具有员工子文档的部门。请注意,HR 部门未表示: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 6, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "all_departments": { + "doc_count": 2, + "departments": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "Accounting", + "doc_count": 1 + }, + { + "key": "Engineering", + "doc_count": 1 + } + ] + } + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/rare-terms.md b/i18n/zh/aggregations/bucket/rare-terms.md new file mode 100644 index 00000000..31f24d0d --- /dev/null +++ b/i18n/zh/aggregations/bucket/rare-terms.md @@ -0,0 +1,335 @@ +--- +title: 稀有词 +--- + +# 稀有词聚合 + +`rare_terms` 聚合是一种桶聚合,用于识别数据集中不频繁的词项。与查找最常见词项的 `terms` 聚合相反,`rare_terms` 聚合查找出现频率最低的词项。`rare_terms` 聚合适用于异常检测、长尾分析和异常报告等应用。 + +::: danger WARNING +可以使用 `terms` 通过按升序计数排序返回的值(`"order": {"count": "asc"}`)来搜索不频繁的值。但是,我们强烈不建议这种做法,因为在涉及多个分片时可能导致不准确的结果。全局不频繁的词项可能不会在每个单独的分片上显示为不频繁,或者可能完全不在某些分片返回的最不频繁结果中。相反,在一个分片上不频繁出现的词项可能在另一个分片上很常见。在这两种情况下,稀有词都可能在分片级聚合期间被遗漏,导致整体结果不正确。我们建议使用专门设计来更准确地处理这些情况的 `rare_terms` 聚合,而不是 `terms` 聚合。 +::: + +## 近似结果 + +为 `rare_terms` 聚合计算精确结果需要编译所有分片上值的完整映射,这需要过多的运行时内存。因此,`rare_terms` 聚合结果是近似的。 + +`rare_terms` 计算中的大多数错误都是_假阴性_或"遗漏"值,这定义了聚合检测测试的_灵敏度_。`rare_terms` 聚合使用 CuckooFilter 算法来实现适当灵敏度和可接受内存使用之间的平衡。有关 CuckooFilter 算法的描述,请参阅[本文](https://www.cs.cmu.edu/~dga/papers/cuckoo-conext2014.pdf)。 + +## 控制灵敏度 + +`rare_terms` 聚合算法中的灵敏度误差以遗漏的稀有值的分数来衡量,即 `假阴性/目标值`。例如,如果聚合在包含 5,000 个稀有值的数据集中遗漏了 100 个稀有值,则灵敏度误差为 `100/5000 = 0.02`,即 2%。 + +您可以调整 `rare_terms` 聚合中的 `precision` 参数来控制灵敏度和内存使用之间的权衡。 + +这些因素也会影响灵敏度-内存权衡: + +- 唯一值的总数 +- 数据集中稀有项的分数 + +以下指南可以帮助您决定使用哪个 `precision` 值。 + +### 计算内存使用 + +运行时内存使用以绝对术语描述,通常以 MB RAM 为单位。 + +内存使用随唯一项数量线性增加。线性缩放因子根据 `precision` 参数从每百万个唯一值大约 1.0 到 2.5 MB 不等。对于默认 `precision` 为 `0.001`,内存成本约为每百万个唯一值 1.75 MB。 + +### 管理灵敏度误差 + +灵敏度误差随唯一值的总数线性增加。有关估计唯一值数量的信息,请参阅[基数聚合](/aggregations/metric/cardinality)。 + +即使对于具有 10-20 百万个唯一值的数据集,在默认 `precision` 下,灵敏度误差也很少超过 2.5%。对于 `precision` 为 `0.00001`,灵敏度误差很少高于 0.6%。但是,非常低的绝对稀有值数量可能会导致错误率出现大的差异(如果只有两个稀有值,遗漏其中一个会导致 50% 的错误率)。 + +## 与其他聚合的兼容性 + +`rare_terms` 聚合使用广度优先收集模式,与某些需要在某些子聚合和嵌套配置中使用深度优先收集模式的聚合不兼容。 + +有关 OpenSearch 中广度优先搜索的更多信息,请参阅[收集模式](/aggregations/bucket/terms#collect-mode)。 + +## 参数 + +`rare_terms` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `field` | 必需 | String | 要分析稀有词的字段。必须是数值类型或具有 `keyword` 映射的文本类型。 | +| `max_doc_count` | 可选 | Integer | 为了使词项被视为稀有所需的最大文档计数。默认值为 `1`。最大值为 `100`。 | +| `precision` | 可选 | Integer | 控制用于识别稀有词的算法的精度。较高的值提供更精确的结果,但消耗更多内存。默认值为 `0.001`。最小值(允许的最精确)为 `0.00001`。 | +| `include` | 可选 | Array/regex | 要包含在结果中的词项。可以是正则表达式或值数组。 | +| `exclude` | 可选 | Array/regex | 要从结果中排除的词项。可以是正则表达式或值数组。 | +| `missing` | 可选 | String | 用于没有被聚合字段值的文档的值。 | + +## 示例 + +以下请求返回 OpenSearch Dashboards 示例航班数据中仅出现一次的所有目的地机场代码: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 1 + } + } + } +} +``` + +## 示例响应 + +响应显示有两个机场符合在数据中仅出现一次的标准: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "BUF", + "doc_count": 1 + } + ] + } + } +} +``` + +## 文档计数限制 + +使用 `max_doc_count` 参数指定 `rare_terms` 聚合可以返回的最大文档计数。`rare_terms` 返回的词项数量没有限制,因此大的 `max_doc_count` 值可能会返回非常大的结果集。因此,`100` 是允许的最大 `max_doc_count`。 + +以下请求返回 OpenSearch Dashboards 示例航班数据中最多出现两次的所有目的地机场代码: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2 + } + } + } +} +``` + +响应显示有七个目的地机场代码符合出现在两个或更少文档中的标准,包括前面示例中的两个: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "BUF", + "doc_count": 1 + }, + { + "key": "ABQ", + "doc_count": 2 + }, + { + "key": "AUH", + "doc_count": 2 + }, + { + "key": "BIL", + "doc_count": 2 + }, + { + "key": "BWI", + "doc_count": 2 + }, + { + "key": "MAD", + "doc_count": 2 + } + ] + } + } +} +``` + +## 过滤(包含和排除) + +使用 `include` 和 `exclude` 参数过滤 `rare_terms` 聚合返回的值。两个参数都可以包含在同一聚合中。`exclude` 过滤器优先;任何排除的值都会从结果中删除,无论它们是否被明确包含。 + +`include` 和 `exclude` 的参数可以是正则表达式(regex),包括字符串字面量或数组。混合正则表达式和数组参数会导致错误。例如,不允许以下组合: + +```json +"rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2, + "exclude": ["ABQ", "AUH"], + "include": "A.*" +} +``` + +### 示例:过滤 + +以下示例修改了前面的示例,以包含所有以"A"开头的机场代码,但排除"ABQ"机场代码: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2, + "include": "A.*", + "exclude": "ABQ" + } + } + } +} +``` + +响应显示符合过滤要求的两个机场代码: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "AUH", + "doc_count": 2 + } + ] + } + } +} +``` + +### 示例:使用数组输入进行过滤 + +以下示例返回 OpenSearch Dashboards 示例航班数据中最多出现两次的所有目的地机场代码,但指定要排除的机场代码数组: + +```json +GET /opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "rare_destination": { + "rare_terms": { + "field": "DestAirportID", + "max_doc_count": 2, + "exclude": ["ABQ", "BIL", "MAD"] + } + } + } +} +``` + +响应省略了排除的机场代码: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "rare_destination": { + "buckets": [ + { + "key": "ADL", + "doc_count": 1 + }, + { + "key": "BUF", + "doc_count": 1 + }, + { + "key": "AUH", + "doc_count": 2 + }, + { + "key": "BWI", + "doc_count": 2 + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/bucket/variable-width-histogram.md b/i18n/zh/aggregations/bucket/variable-width-histogram.md new file mode 100644 index 00000000..87b981e7 --- /dev/null +++ b/i18n/zh/aggregations/bucket/variable-width-histogram.md @@ -0,0 +1,203 @@ +--- +title: 可变宽度直方图 +--- + +# 可变宽度直方图聚合 + +`variable_width_histogram` 聚合将数值字段的值划分为目标数量的桶,其宽度适应数据。桶边界通过聚类值得出,因此值范围的密集部分被分成窄桶,而稀疏部分则由宽桶覆盖。对于分布不均匀的数据,使用此聚合,因为在 [`histogram`](/aggregations/bucket/histogram) 聚合中使用固定 `interval` 会产生许多几乎为空的桶或少数几个包含几乎所有文档的桶。 + +每个分片缓冲它收集的前 `initial_buffer` 个值,对它们进行排序,并将它们划分为等于 `shard_size` 四分之三的初始簇数。它将每个剩余值分配给最近的簇,除非该值距离所有簇的距离超过相邻簇质心之间平均距离的两倍,并且分片持有的簇数少于 `shard_size`,在这种情况下,分片开始一个新簇。协调节点从所有分片收集簇,并重复合并质心最近的两个簇,直到剩余 `buckets` 个。 + +## 参数 + +`variable_width_histogram` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `field` | 必需 | String | 要聚合的数值字段。提供 `field` 或 `script` 之一。 | +| `buckets` | 可选 | Integer | 目标桶数量。必须大于 `0`,并且不能超过 `search.max_buckets` 设置。当值无法分成那么多簇时,响应可能包含比请求更少的桶。默认值为 `10`。 | +| `shard_size` | 可选 | Integer | 每个分片在将其结果发送到协调节点之前构建的簇数。必须大于 `1`。较大的值在每个分片上产生较小的簇,这减少了最终桶之间的重叠并更准确地放置它们的边界,但增加了分片上使用的内存和传输到协调节点的数据量。默认值为 `buckets` 乘以 `50`。 | +| `initial_buffer` | 可选 | Integer | 每个分片在计算初始簇边界之前缓冲的值数量。必须大于或等于 `buckets`。较大的缓冲区从更具代表性的数据样本中得出初始边界,但使用更多内存。默认值为 `shard_size` 乘以 `10` 和 `50000` 中的较小值。 | +| `script` | 可选 | Object | 生成要聚合的数值的脚本。提供 `field` 或 `script` 之一。 | +| `missing` | 可选 | Number | 分配给缺少目标字段的文档的值。默认情况下,忽略缺失的文档。 | +| `format` | 可选 | String | 应用于 `min`、`key` 和 `max` 的 [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在附加的 `min_as_string`、`key_as_string` 和 `max_as_string` 响应字段中返回格式化的输出。 | + +## 示例 + +以下示例将电子商务订单总额分成五个可变宽度的桶: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_buckets": { + "variable_width_histogram": { + "field": "taxful_total_price", + "buckets": 5 + } + } + } +} +``` + +## 示例响应 + +```json +{ + "took": 17, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "price_buckets": { + "buckets": [ + { + "min": 6.98828125, + "key": 59.14907207464146, + "max": 105.46875, + "doc_count": 3835 + }, + { + "min": 105.46875, + "key": 139.096796875, + "max": 229.5, + "doc_count": 800 + }, + { + "min": 229.5, + "key": 247.11111111111111, + "max": 304.0, + "doc_count": 27 + }, + { + "min": 304.0, + "key": 318.4, + "max": 308.0, + "doc_count": 5 + }, + { + "min": 308.0, + "key": 563.25, + "max": 2250.0, + "doc_count": 8 + } + ] + } + } +} +``` + +覆盖价格范围拥挤低端的桶宽度为几十美元,而最后一个桶跨越近 $2,000 以覆盖少数最高订单。 + +## 示例:嵌套子聚合 + +与其他桶聚合一样,`variable_width_histogram` 接受子聚合。以下示例计算每个价格桶中订购的平均项数: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "price_buckets": { + "variable_width_histogram": { + "field": "taxful_total_price", + "buckets": 3 + }, + "aggs": { + "avg_quantity": { + "avg": { + "field": "total_quantity" + } + } + } + } + } +} +``` + +响应在每个桶中包含子聚合结果: + +```json +{ + "aggregations": { + "price_buckets": { + "buckets": [ + { + "min": 6.98828125, + "key": 73.45130757286513, + "max": 246.0, + "doc_count": 4649, + "avg_quantity": { + "value": 2.1559475155947516 + } + }, + { + "min": 246.0, + "key": 281.9166666666667, + "max": 370.0, + "doc_count": 24, + "avg_quantity": { + "value": 2.7083333333333335 + } + }, + { + "min": 393.0, + "key": 1321.5, + "max": 2250.0, + "doc_count": 2, + "avg_quantity": { + "value": 1.5 + } + } + ] + } + } +} +``` + +## 响应正文字段 + +下表列出了响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `buckets` | Array | 可变宽度桶,按 `key` 升序排序。 | +| `buckets.min` | Double | 桶的下界。 | +| `buckets.key` | Double | 桶中值的平均值。 | +| `buckets.max` | Double | 桶的上界。 | +| `buckets.doc_count` | Integer | 桶中的文档数量。 | +| `buckets.min_as_string` | String | 桶的下界,根据 `format` 格式化。仅在设置 `format` 时返回。 | +| `buckets.key_as_string` | String | 桶中值的平均值,根据 `format` 格式化。仅在设置 `format` 时返回。 | +| `buckets.max_as_string` | String | 桶的上界,根据 `format` 格式化。仅在设置 `format` 时返回。 | + +## 限制 + +`variable_width_histogram` 聚合具有以下限制: + +- 该聚合不能嵌套在收集多个桶的父聚合内部。[`terms`](/aggregations/bucket/terms)、[`histogram`](/aggregations/bucket/histogram)、[`range`](/aggregations/bucket/range) 或 [`filters`](/aggregations/bucket/filters) 父级返回以下错误: + + ``` + [variable_width_histogram] cannot be nested inside an aggregation that collects more than a single bucket. + ``` + + 支持单桶父级,例如 [`filter`](/aggregations/bucket/filter)、[`global`](/aggregations/bucket/global) 和 [`nested`](/aggregations/bucket/nested)。 +- 当该聚合具有需要文档分数的子聚合(例如 [`top_hits`](/aggregations/metric/top-hits))时,该聚合不能作为 [`nested`](/aggregations/bucket/nested) 聚合的子级运行。此组合返回错误。 +- 不支持 `keyed` 参数,因此桶始终作为数组返回。 +- `min` 和 `max` 界限是近似的。在合并簇时,如果两个簇的质心相距很远,OpenSearch 可以将边界重叠的两个簇保留为单独的桶。然后,它将两个桶之间的边界设置为重叠的中点,因此边界不一定是数据中存在的值,并且较低的桶包含的值多于其边界指示的值,而较高的桶包含的值较少。以这种方式降低桶的 `max` 可以将其置于桶自己的 `key` 之下,`key` 是桶中值的平均值。第一个示例响应中的第四个桶报告 `key` 为 `318.4`,而 `max` 为 `308.0`,原因就在于此。此合并步骤在单分片索引以及多分片索引上运行。 +- 桶不是连续的。每个桶的边界是它持有的最小值和最大值,因此数据中的间隙显示为相邻桶之间的间隙。在子聚合示例响应中,一个桶在 `370.0` 结束,下一个桶在 `393.0` 开始。 +- 桶边界对异常值敏感。少数极端值将桶延伸到很宽的数据范围:第一个示例响应中的最后一个桶跨越 `308.0` 到 `2250.0` 以保存 8 个订单。 +- 桶边界取决于每个分片收集值的顺序,因此即使值分布保持不变,它们也可能随着段合并或添加文档而改变。 diff --git a/i18n/zh/aggregations/metric/geocentroid.md b/i18n/zh/aggregations/metric/geocentroid.md new file mode 100644 index 00000000..fd60827e --- /dev/null +++ b/i18n/zh/aggregations/metric/geocentroid.md @@ -0,0 +1,192 @@ +--- +title: 地理中心点 +--- + +# 地理中心点聚合 + +`geo_centroid` 聚合计算一组 `geo_point` 值的地理中心或焦点。它将质心位置作为纬度-经度对返回。 + +## 参数 + +`geo_centroid` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `field` | 必需 | String | 包含要计算地理中心点的地理点的字段名称。 | + +## 示例 + +以下示例返回电子商务示例数据中每个订单的 `geoip.location` 的 `geo_centroid`。每个 `geoip.location` 都是一个地理点: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "centroid": { + "geo_centroid": { + "field": "geoip.location" + } + } + } +} +``` + +## 示例响应 + +响应包含一个 `centroid` 对象,其中包含表示所有索引数据点的质心位置的 `lat` 和 `lon` 属性: + +```json +{ + "took": 35, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "centroid": { + "location": { + "lat": 35.54990372113027, + "lon": -9.079764742533712 + }, + "count": 4675 + } + } +} +``` + +质心位置位于摩洛哥北部的大西洋。鉴于数据库中订单的广泛地理分散性,这并不是很有意义。 + +## 嵌套在其他聚合下 + +您可以将 `geo_centroid` 聚合嵌套在桶聚合内部,以计算数据子集的质心。 + +### 示例:嵌套在 terms 聚合下 + +您可以将 `geo_centroid` 聚合嵌套在字符串字段的 `terms` 桶下。 + +要查找每个大陆订单的 `geoip` 质心位置,请在 `geoip.continent_name` 字段内子聚合质心: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "continents": { + "terms": { + "field": "geoip.continent_name" + }, + "aggs": { + "centroid": { + "geo_centroid": { + "field": "geoip.location" + } + } + } + } + } +} +``` + +这将为每个大陆的桶返回一个质心位置: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 34, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "continents": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "Asia", + "doc_count": 1220, + "centroid": { + "location": { + "lat": 28.023606536509163, + "lon": 47.83377046025068 + }, + "count": 1220 + } + }, + { + "key": "North America", + "doc_count": 1206, + "centroid": { + "location": { + "lat": 39.06542286878007, + "lon": -85.36152573149485 + }, + "count": 1206 + } + }, + { + "key": "Europe", + "doc_count": 1172, + "centroid": { + "location": { + "lat": 48.125767892293325, + "lon": 2.7529009746915243 + }, + "count": 1172 + } + }, + { + "key": "Africa", + "doc_count": 899, + "centroid": { + "location": { + "lat": 30.780756367941297, + "lon": 13.464182392125318 + }, + "count": 899 + } + }, + { + "key": "South America", + "doc_count": 178, + "centroid": { + "location": { + "lat": 4.599999985657632, + "lon": -74.10000007599592 + }, + "count": 178 + } + } + ] + } + } +} +``` +</details> diff --git a/i18n/zh/aggregations/metric/median-absolute-deviation.md b/i18n/zh/aggregations/metric/median-absolute-deviation.md new file mode 100644 index 00000000..cf5f2f1c --- /dev/null +++ b/i18n/zh/aggregations/metric/median-absolute-deviation.md @@ -0,0 +1,132 @@ +--- +title: 中位数绝对偏差 +--- + +# 中位数绝对偏差聚合 + +`median_absolute_deviation` 聚合是一种单值指标聚合。中位数绝对偏差是一种可变性指标,用于测量与中位数的离散程度。 + +中位数绝对偏差受异常值的影响比标准差小,标准差依赖于平方误差项,适用于描述非正态分布的数据。 + +中位数绝对偏差的计算公式如下: + +``` +median_absolute_deviation = median( | x<sub>i</sub> - median(x<sub>i</sub>) | ) +``` + +由于内存限制,OpenSearch 估计 `median_absolute_deviation`,而不是直接计算它。这种估计的计算成本很高。您可以调整估计准确性和性能之间的权衡。有关更多信息,请参阅[调整估计准确性](#调整估计准确性)。 + +## 参数 + +`median_absolute_deviation` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `field` | 必需 | String | 要计算中位数绝对偏差的数值字段的名称。 | +| `missing` | 可选 | Numeric | 分配给字段缺失实例的值。如果未提供,则从估计中省略缺失值的文档。 | +| `compression` | 可选 | Numeric | [调整估计准确性和性能之间平衡](#调整估计准确性)的参数。`compression` 的值必须大于 `0`。默认值为 `1000`。 | + +## 示例 + +以下示例计算 `opensearch_dashboards_sample_data_flights` 数据集中 `DistanceMiles` 字段的中位数绝对偏差: + +```json +GET opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "median_absolute_deviation_DistanceMiles": { + "median_absolute_deviation": { + "field": "DistanceMiles" + } + } + } +} +``` + +## 示例响应 + +如以下示例响应所示,聚合在 `median_absolute_deviation_DistanceMiles` 变量中返回中位数绝对偏差的估计值: + +```json +{ + "took": 490, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "median_absolute_deviation_DistanceMiles": { + "value": 1830.917892238693 + } + } +} +``` + +## 缺失值 + +OpenSearch 在计算 `median_absolute_deviation` 时会忽略缺失值和空值。 + +您可以为聚合字段的缺失实例分配一个值。有关更多信息,请参阅[缺失聚合](/aggregations/bucket/missing)。 + +## 调整估计准确性 + +中位数绝对偏差使用 [t-digest](https://github.com/tdunning/t-digest/tree/main) 数据结构计算,该数据结构采用 `compression` 参数来平衡性能和估计准确性。较低的 `compression` 值可以提高性能,但可能会降低估计准确性,如以下请求所示: + +```json +GET opensearch_dashboards_sample_data_flights/_search +{ + "size": 0, + "aggs": { + "median_absolute_deviation_DistanceMiles": { + "median_absolute_deviation": { + "field": "DistanceMiles", + "compression": 10 + } + } + } +} +``` + +估计误差取决于数据集,但即使对于低至 `100` 的 `compression` 值,通常也低于 5%。(此处使用的低示例值 `10` 是为了说明权衡效果,不建议使用。) + +请注意以下响应中减少的计算时间(`took` 时间)和估计参数的略低准确性值。 + +作为参考,OpenSearch 对 `DistanceMiles` 中位数绝对偏差的最佳估计(将 `compression` 设置为任意高值)为 `1831.076904296875`: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "median_absolute_deviation_DistanceMiles": { + "value": 1836.265614211182 + } + } +} +``` diff --git a/i18n/zh/aggregations/metric/weighted-avg.md b/i18n/zh/aggregations/metric/weighted-avg.md new file mode 100644 index 00000000..e5b310e2 --- /dev/null +++ b/i18n/zh/aggregations/metric/weighted-avg.md @@ -0,0 +1,213 @@ +--- +title: 加权平均 +--- + +# 加权平均聚合 + +`weighted_avg` 聚合计算从文档中提取的数值的加权平均值。与每个数据点贡献相等的常规平均值不同,加权平均值根据相应的权重值为每个数据点分配不同的重要性。 + +加权平均值使用公式 $$ \frac{\sum_{i=1}^n \text{value}_i \cdot \text{weight}_i}{\sum_{i=1}^n \text{weight}_i} $$ 计算。 + +在常规平均值中,每个数据点贡献相等,这相当于为所有值分配权重 `1`。 + +## 参数 + +`weighted_avg` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 描述 | +|---------------|----------|-------------| +| `value` | 必需 | 定义如何获取要平均的数值。需要 `field` 或 `script`。 | +| `weight` | 必需 | 定义如何获取每个值的权重。需要 `field` 或 `script`。 | +| `format` | 可选 | 一个 [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化的输出。 | +| `value_type` | 可选 | 使用脚本或未映射字段时值的类型提示。 | + +您可以在 `value` 或 `weight` 中指定以下参数。 + +| 参数 | 必需/可选 | 描述 | +|------------|----------|-------------| +| `field` | 可选 | 用于值或权重的文档字段。 | +| `missing` | 可选 | 字段缺失时使用的默认值或权重。请参阅[缺失值](#缺失值)。| +| `script` | 可选 | 提供值或权重的脚本。与 `field` 互斥。 | + +## 示例 + +首先,创建一个索引并添加一些数据。产品 C 缺少 `rating` 和 `num_reviews` 字段: + +```json +POST _bulk +{ "index": { "_index": "products" } } +{ "name": "Product A", "rating": 4.5, "num_reviews": 100 } +{ "index": { "_index": "products" } } +{ "name": "Product B", "rating": 3.8, "num_reviews": 50 } +{ "index": { "_index": "products" } } +{ "name": "Product C"} +``` + +以下请求计算加权平均产品评分,其中每个产品的评分由其 `num_reviews` 加权。评论数量较多的产品对最终平均值的影响更大: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "field": "rating" + }, + "weight": { + "field": "num_reviews" + }, + "format": "#.##" + } + } + } +} +``` + +## 示例响应 + +响应包含 `weighted_rating`,计算为 `(4.5 * 100 + 3.8 * 50) / (100 + 50) = 4.27`。只有包含 `rating` 和 `num_reviews` 值的文档才包含在计算中: + +```json +{ + "took": 21, + "timed_out": false, + "terminated_early": true, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "weighted_rating": { + "value": 4.266666650772095, + "value_as_string": "4.27" + } + } +} +``` + +## 多值字段 + +`value` 字段可以包含每个文档的多个值,但 `weight` 字段必须恰好解析为一个值。具有多个权重的文档会导致错误。要处理多值权重字段,请使用将它们减少为单个数字的 `script`。 + +当文档包含多个值时,单个权重独立应用于每个值。以下示例索引 `rating` 为多值字段的文档,然后运行聚合: + +```json +POST /products/_doc?refresh=true +{ + "name": "Product D", + "rating": [1, 2, 3], + "num_reviews": 2 +} +``` + +```json +GET /products/_search +{ + "size": 0, + "query": { + "term": { "name.keyword": "Product D" } + }, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "field": "rating" + }, + "weight": { + "field": "num_reviews" + } + } + } + } +} +``` + +三个值(`1`、`2` 和 `3`)每个都由 `2` 加权,结果为 `((1*2) + (2*2) + (3*2)) / (2+2+2) = 2.0`: + +```json +{ + ... + "aggregations": { + "weighted_rating": { + "value": 2.0 + } + } +} +``` + +## 使用脚本 + +您可以为值、权重或两者提供脚本,以动态计算派生量。以下示例在计算加权平均值之前为每个评分和权重添加 `1`: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "script": "if (doc['rating'].size() == 0) return 0; return doc['rating'].value + 1" + }, + "weight": { + "script": "if (doc['num_reviews'].size() == 0) return 0; return doc['num_reviews'].value + 1" + } + } + } + } +} +``` + +## 缺失值 + +默认情况下,缺少 `value` 字段的文档将从计算中排除。缺少 `weight` 字段的文档仍然包括在内,隐式权重为 `1`。 + +`missing` 参数通过为缺少字段的文档指定替代值来覆盖这些默认值。以下示例为缺少这些字段的文档分配默认评分 `3.0` 和默认评论计数 `1`: + +```json +GET /products/_search +{ + "size": 0, + "aggs": { + "weighted_rating": { + "weighted_avg": { + "value": { + "field": "rating", + "missing": 3.0 + }, + "weight": { + "field": "num_reviews", + "missing": 1 + }, + "format": "#.##" + } + } + } +} +``` + +应用缺失值后,加权平均值计算为 `(4.5 * 100 + 3.8 * 50 + 3.0 * 1) / (100 + 50 + 1) = 4.26`: + +```json +{ + ... + "aggregations": { + "weighted_rating": { + "value": 4.258278129906055, + "value_as_string": "4.26" + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/avg-bucket.md b/i18n/zh/aggregations/pipeline/avg-bucket.md new file mode 100644 index 00000000..c549c85d --- /dev/null +++ b/i18n/zh/aggregations/pipeline/avg-bucket.md @@ -0,0 +1,108 @@ +--- +title: 平均桶 +--- + +# 平均桶聚合 + +`avg_bucket` 聚合是一种同级聚合,它计算前一个聚合的每个桶中指标的平均值。 + +指定的指标必须是数值,同级聚合必须是多桶聚合。 + +## 参数 + +`avg_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#桶路径)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#数据间隙)。| +| `format` | 可选 | String | 一个 [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化的输出。 | + +## 示例 + +以下示例从 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`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" + } + } + } +} +``` + +## 示例响应 + +聚合返回月度桶的平均字节数: + +```json +{ + "took": 43, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "avg_monthly_bytes": { + "value": 26575229.666666668 + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/bucket-script.md b/i18n/zh/aggregations/pipeline/bucket-script.md new file mode 100644 index 00000000..b17f7196 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/bucket-script.md @@ -0,0 +1,154 @@ +--- +title: 桶脚本 +--- + +# 桶脚本聚合 + +`bucket_script` 聚合是一种父管道聚合,它执行脚本以跨一组桶执行每桶数值计算。使用 `bucket_script` 聚合对分桶聚合中的多个指标执行自定义数值计算。例如,您可以: + +- 计算派生和复合指标。 +- 使用 if/else 语句应用条件逻辑。 +- 计算特定于业务的 KPI,例如自定义评分指标。 + +## 参数 + +`bucket_script` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | Object | 变量名称到分桶指标的映射,用于标识要在脚本中使用的指标。指标必须是数值。请参阅[脚本变量](#脚本变量)。 | +| `script` | 必需 | String 或 Object | 要执行的脚本。可以是内联脚本、存储脚本或脚本文件。脚本可以访问在 `buckets_path` 参数中定义的变量名称。必须返回数值。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#数据间隙)。 | +| `format` | 可选 | String | 一个 [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 参数中返回格式化的输出。 | + +## 脚本变量 + +`buckets_path` 参数将脚本变量名称映射到父聚合的指标。然后可以在脚本中使用这些变量。 + +::: info NOTE +对于 `bucket_script` 和 `bucket_selector` 聚合,`buckets_path` 参数是对象而不是字符串,因为它必须引用多个桶指标。有关 `buckets_path` 的字符串版本的描述,请参阅[管道聚合](/aggregations/pipeline/#桶路径)页面。 +::: + +以下 `buckets_path` 将 `sales_sum` 指标映射到 `total_sales` 脚本变量,并将 `item_count` 指标映射到 `item_count` 脚本变量: + +```json +"buckets_path": { + "total_sales": "sales_sum", + "item_count": "item_count" +} +``` + +可以从 `params` 上下文访问映射的变量。例如: + +- `params.total_sales` +- `params.item_count` + +## 启用内联脚本 + +使用 `script` 参数添加您的脚本。脚本可以是内联的、在文件中或在索引中。要启用内联脚本,`config` 文件夹中的 `opensearch.yml` 文件必须包含以下内容: + +```yml +script.inline: on +``` + +## 示例 + +以下示例从 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`total_sales` 子聚合对每个月销售的所有商品的含税价格求和。`vendor_count` 聚合计算每个月的唯一供应商总数。最后,`avg_vendor_spend` 聚合使用内联脚本计算每个月每个供应商的平均支出金额: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "sales_per_month": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "month" + }, + "aggs": { + "total_sales": { + "sum": { + "field": "taxful_total_price" + } + }, + "vendor_count": { + "cardinality": { + "field": "products.manufacturer.keyword" + } + }, + "avg_vendor_spend": { + "bucket_script": { + "buckets_path": { + "sales": "total_sales", + "vendors": "vendor_count" + }, + "script": "params.sales / params.vendors", + "format": "$#,###.00" + } + } + } + } + } +} +``` + +## 示例响应 + +聚合返回格式化的月度平均供应商支出: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 721, + "vendor_count": { + "value": 21 + }, + "total_sales": { + "value": 53468.1484375 + }, + "avg_vendor_spend": { + "value": 2546.1023065476193, + "value_as_string": "$2,546.10" + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 3954, + "vendor_count": { + "value": 21 + }, + "total_sales": { + "value": 297415.98046875 + }, + "avg_vendor_spend": { + "value": 14162.665736607143, + "value_as_string": "$14,162.67" + } + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/bucket-selector.md b/i18n/zh/aggregations/pipeline/bucket-selector.md new file mode 100644 index 00000000..8e7ca4f9 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/bucket-selector.md @@ -0,0 +1,116 @@ +--- +title: 桶选择器 +--- + +# 桶选择器聚合 + +`bucket_selector` 聚合是一种父管道聚合,它评估脚本以确定 `histogram`(或 `date_histogram`)聚合返回的桶是否应包含在最终结果中。 + +与创建新值的管道聚合不同,`bucket_selector` 聚合充当过滤器,根据指定的标准保留或删除整个桶。使用此聚合根据桶的计算指标过滤桶。 + +## 参数 + +`bucket_selector` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | Object | 变量名称到分桶指标的映射,用于标识要在脚本中使用的指标。指标必须是数值。请参阅[脚本变量](/aggregations/pipeline/bucket-script#脚本变量)。 | +| `script` | 必需 | String 或 Object | 要执行的脚本。可以是内联脚本、存储脚本或脚本文件。脚本可以访问在 `buckets_path` 参数中定义的变量名称。必须返回布尔值。返回 `false` 的桶将从最终输出中删除。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#数据间隙)。 | + +## 示例 + +以下示例从 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一周的日期直方图。`sum` 子聚合计算每周所有销售额的总和。最后,`bucket_selector` 聚合过滤生成的周桶,删除总和不超过 $75,000 的所有桶: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "sales_per_week": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "weekly_sales": { + "sum": { + "field": "taxful_total_price", + "format": "$#,###.00" + } + }, + "avg_vendor_spend": { + "bucket_selector": { + "buckets_path": { + "weekly_sales": "weekly_sales" + }, + "script": "params.weekly_sales > 75000" + } + } + } + } + } +} +``` + +## 示例响应 + +聚合返回符合脚本标准的 `sales_per_week` 桶: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_week": { + "buckets": [ + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "weekly_sales": { + "value": 79448.60546875, + "value_as_string": "$79,448.61" + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "weekly_sales": { + "value": 78208.4296875, + "value_as_string": "$78,208.43" + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "weekly_sales": { + "value": 81277.296875, + "value_as_string": "$81,277.30" + } + } + ] + } + } +} +``` + +::: info NOTE +因为它返回布尔值而不是数值,`buckets_selector` 聚合不接受 `format` 参数。在此示例中,格式化的指标在 `sum` 子聚合的 `value_as_string` 结果中返回。将此与 [`bucket_script` 聚合中的示例](/aggregations/pipeline/bucket-script#示例)进行对比。 +::: diff --git a/i18n/zh/aggregations/pipeline/bucket-sort.md b/i18n/zh/aggregations/pipeline/bucket-sort.md new file mode 100644 index 00000000..fa868288 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/bucket-sort.md @@ -0,0 +1,224 @@ +--- +title: 桶排序 +--- + +# 桶排序聚合 + +`bucket_sort` 聚合是一种父聚合,用于对其父级多桶聚合生成的桶进行排序或截断。 + +在 `bucket_sort` 聚合中,您可以按多个字段对桶进行排序,每个字段都有自己的排序顺序。桶可以按其键、文档计数或子聚合的值进行排序。您还可以使用 `from` 和 `size` 参数来截断结果,无论是否进行排序。 + +有关指定排序顺序的信息,请参阅[排序结果](/search-plugins/searching-data/sort)。 + +## 参数 + +`bucket_sort` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `sort` | 可选 | String | 用于排序的字段列表。请参阅[排序结果](/search-plugins/searching-data/sort)。 | +| `from` | 可选 | String | 要返回的第一个结果的索引。必须是非负整数。默认值为 `0`。请参阅[`from` 和 `size` 参数](/search-plugins/searching-data/paginate#the-from-and-size-parameters)。 | +| `size` | 可选 | String | 要返回的最大结果数。必须是正整数。请参阅[`from` 和 `size` 参数](/search-plugins/searching-data/paginate#the-from-and-size-parameters)。| + +::: info NOTE +您必须至少提供 `sort`、`from` 和 `size` 中的一个。 +::: + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,聚合按字节数以降序对桶进行排序: + +```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" } } + ] + } + } + } + } + } +} +``` + +## 示例响应 + +聚合按总字节数以降序重新排列桶: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 7072, + "total_bytes": { + "value": 40124337 + } + }, + { + "key_as_string": "2025-06-01T00:00:00.000Z", + "key": 1748736000000, + "doc_count": 6056, + "total_bytes": { + "value": 34123131 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 946, + "total_bytes": { + "value": 5478221 + } + } + ] + } + } +} +``` + +## 示例:截断结果 + +要截断结果,请提供 `from` 和/或 `size` 参数。以下示例执行相同的排序,但返回两个桶,从第二个桶开始: + +```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" } } + ], + "from": 1, + "size": 2 + } + } + } + } + } +} +``` + +聚合返回两个已排序的桶: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-06-01T00:00:00.000Z", + "key": 1748736000000, + "doc_count": 6056, + "total_bytes": { + "value": 34123131 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 946, + "total_bytes": { + "value": 5478221 + } + } + ] + } + } +} +``` + +要在不排序的情况下截断结果,请省略 `sort` 参数: + +```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": { + "from": 1, + "size": 2 + } + } + } + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/cumulative-sum.md b/i18n/zh/aggregations/pipeline/cumulative-sum.md new file mode 100644 index 00000000..3830de44 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/cumulative-sum.md @@ -0,0 +1,111 @@ +--- +title: 累积求和 +--- + +# 累积求和聚合 + +`cumulative_sum` 聚合是一种父聚合,用于计算先前聚合的桶之间的累积和。 + +累积和是给定序列的部分和序列。例如,序列 `{a,b,c,…}` 的累积和为 `a`、`a+b`、`a+b+c`,依此类推。您可以使用累积和来可视化字段随时间的变化率。 + +## 参数 + +`cumulative_sum` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,`cumulative_sum` 聚合计算每个月桶的累积字节数: + +```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" + } + } + } + } + } +} +``` + +## 示例响应 + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "no-of-bytes": { + "value": 2804103 + }, + "cumulative_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "no-of-bytes": { + "value": 39103067 + }, + "cumulative_bytes": { + "value": 41907170 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "no-of-bytes": { + "value": 37818519 + }, + "cumulative_bytes": { + "value": 79725689 + } + } + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/derivative.md b/i18n/zh/aggregations/pipeline/derivative.md new file mode 100644 index 00000000..055e05cf --- /dev/null +++ b/i18n/zh/aggregations/pipeline/derivative.md @@ -0,0 +1,213 @@ +--- +title: 导数 +--- + +# 导数聚合 + +`derivative` 聚合是一种父聚合,用于计算聚合的每个桶的一阶导数和二阶导数。"一阶导数"和"二阶导数"通常缩写为"一阶导"和"二阶导"。本页使用缩写术语。 + +对于有序的桶系列,`derivative` 将一阶导数近似为当前桶和前一个桶中指标值之间的差值。 + +## 参数 + +`derivative` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | + +## 示例:一阶导数 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,`derivative` 聚合计算 `sum` 子聚合的一阶导数。一阶导数被估计为当前月份和前一个月份的字节数之间的差值: + +```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" + } + } + } + } + } +} +``` + +## 示例响应:一阶导数 + +响应显示为第二个和第三个桶计算的导数: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "number_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "number_of_bytes": { + "value": 39103067 + }, + "bytes_deriv": { + "value": 36298964 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "number_of_bytes": { + "value": 37818519 + }, + "bytes_deriv": { + "value": -1284548 + } + } + ] + } + } +} +``` + +第一个桶没有计算导数,因为该桶没有可用的前一个桶。 + +## 示例:二阶导数 + +要计算二阶导数,请将一个导数聚合链接到另一个导数聚合: + +```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_1st_deriv": { + "derivative": { + "buckets_path": "number_of_bytes" + } + }, + "bytes_2nd_deriv": { + "derivative": { + "buckets_path": "bytes_1st_deriv" + } + } + } + } + } +} +``` + +## 示例响应:二阶导数 + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "sales_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "number_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "number_of_bytes": { + "value": 39103067 + }, + "bytes_1st_deriv": { + "value": 36298964 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "number_of_bytes": { + "value": 37818519 + }, + "bytes_1st_deriv": { + "value": -1284548 + }, + "bytes_2nd_deriv": { + "value": -37583512 + } + } + ] + } + } +} +``` + +第一个桶没有计算一阶导数,因为该桶没有可用的前一个桶。类似地,第一个和第二个桶也没有计算二阶导数。 diff --git a/i18n/zh/aggregations/pipeline/extended-stats.md b/i18n/zh/aggregations/pipeline/extended-stats.md new file mode 100644 index 00000000..1d355877 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/extended-stats.md @@ -0,0 +1,175 @@ +--- +title: 扩展统计桶 +--- + +# 扩展统计桶聚合 + +`extended_stats_bucket` 聚合是 [`stats_bucket`](/aggregations/pipeline/stats-bucket) 同级聚合的更全面版本。除了 `stats_bucket` 提供的基本统计度量外,`extended_stats_bucket` 还计算以下指标: + +- 平方和 +- 方差 +- 总体方差 +- 样本方差 +- 标准差 +- 总体标准差 +- 样本标准差 +- 标准差边界: + - 上界 + - 下界 + - 总体上界 + - 总体下界 + - 样本上界 + - 样本下界 + +标准差和方差是总体统计量;它们始终分别等于总体标准差和总体方差。 + +`std_deviation_bounds` 对象定义了一个范围,该范围跨越平均值上下指定数量的标准差(默认为两个标准差)。此对象始终包含在输出中,但仅对正态分布的数据有意义。在解释这些值之前,请验证您的数据集是否遵循正态分布。 + +指定的指标必须是数值类型,并且同级聚合必须是多桶聚合。 + +## 参数 + +`extended_stats_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。| +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `<stat>_as_string` 属性中返回格式化输出。 | +| `sigma` | 可选 | Double(非负) | 用于计算 `std_deviation_bounds` 区间的平均值上下的标准差数量。默认值为 `2`。请参阅 `extended_stats` 中的[定义边界](/aggregations/metric/extended-stats#defining-bounds)。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,`extended_stats_bucket` 聚合返回这些总和的扩展统计信息: + +```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": { + "extended_stats_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes", + "sigma": 3, + "format": "0.##E0" + } + } + } +} +``` + +## 示例响应 + +响应包含所选桶的扩展统计信息。请注意,标准差边界为三西格玛范围;更改 `sigma`(或让其默认为 `2`)会返回不同的结果: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "stats_monthly_bytes": { + "count": 3, + "min": 2804103, + "max": 39103067, + "avg": 26575229.666666668, + "sum": 79725689, + "min_as_string": "2.8E6", + "max_as_string": "3.91E7", + "avg_as_string": "2.66E7", + "sum_as_string": "7.97E7", + "sum_of_squares": 2967153221794459, + "variance": 282808242095406.25, + "variance_population": 282808242095406.25, + "variance_sampling": 424212363143109.4, + "std_deviation": 16816903.46334325, + "std_deviation_population": 16816903.46334325, + "std_deviation_sampling": 20596416.2694171, + "std_deviation_bounds": { + "upper": 77025940.05669643, + "lower": -23875480.72336309, + "upper_population": 77025940.05669643, + "lower_population": -23875480.72336309, + "upper_sampling": 88364478.47491796, + "lower_sampling": -35214019.141584635 + }, + "sum_of_squares_as_string": "2.97E15", + "variance_as_string": "2.83E14", + "variance_population_as_string": "2.83E14", + "variance_sampling_as_string": "4.24E14", + "std_deviation_as_string": "1.68E7", + "std_deviation_population_as_string": "1.68E7", + "std_deviation_sampling_as_string": "2.06E7", + "std_deviation_bounds_as_string": { + "upper": "7.7E7", + "lower": "-2.39E7", + "upper_population": "7.7E7", + "lower_population": "-2.39E7", + "upper_sampling": "8.84E7", + "lower_sampling": "-3.52E7" + } + } + } +} +``` + +</details> diff --git a/i18n/zh/aggregations/pipeline/index.md b/i18n/zh/aggregations/pipeline/index.md new file mode 100644 index 00000000..76d6b8e2 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/index.md @@ -0,0 +1,239 @@ +--- +title: 管道聚合 +--- + +# 管道聚合 + +管道聚合通过使用一个聚合的输出作为另一个聚合的输入,将多个聚合链接在一起。它们计算复杂的统计和数学度量,如导数、移动平均和累积求和。一些管道聚合复制了指标和桶聚合的功能,但在许多情况下,使用起来更直观。 + +::: info NOTE +管道聚合在所有其他同级聚合之后执行。这会对性能产生影响。例如,使用 `bucket_selector` 管道聚合缩小桶列表不会减少对省略桶执行的计算数量。 +::: + +管道聚合不能是子聚合,但可以链接到其他管道聚合。例如,您可以通过链接两个连续的 `derivative` 聚合来计算二阶导数。请记住,管道聚合会附加到现有输出。例如,通过链接 `derivative` 聚合计算二阶导数会同时输出一阶导数和二阶导数。 + +## 管道聚合类型 + +管道聚合有两种类型:[同级](#同级聚合)和[父级](#父级聚合)。 + +### 同级聚合 + +_同级_管道聚合获取嵌套聚合的输出,并在与嵌套桶相同的级别上生成新桶或新聚合。 + +同级聚合必须是多桶聚合(对某个字段具有多个分组值),并且指标必须是数值。 + +### 父级聚合 + +_父级_聚合获取外部聚合的输出,并在与现有桶相同的级别上生成新桶或新聚合。与跨所有桶操作并产生单个输出的同级管道聚合不同,父级管道聚合单独处理每个桶,并将结果写回每个桶。 + +父级聚合的指定指标必须是数值。 + +::: warning IMPORTANT +我们强烈建议为父级聚合将 `min_doc_count` 设置为 `0`(`histogram` 聚合的默认值)。如果 `min_doc_count` 大于 `0`,则聚合会省略桶,这可能导致结果不正确。 +::: + +## 支持的管道聚合 + +OpenSearch 支持以下管道聚合。 + +| 名称 | 类型 | 描述 | +|------|------|-------------| +| [`avg_bucket`](/aggregations/pipeline/avg-bucket) | 同级 | 计算前一个聚合的每个桶中指标的平均值。 | +| [`bucket_script`](/aggregations/pipeline/bucket-script) | 父级 | 执行脚本以跨一组桶执行每桶数值计算。 | +| [`bucket_selector`](/aggregations/pipeline/bucket-selector) | 父级 | 评估脚本以确定 `histogram`(或 `date_histogram`)聚合返回的桶是否应包含在最终结果中。 | +| [`bucket_sort`](/aggregations/pipeline/bucket-selector) | 父级 | 对其父多桶聚合生成的桶进行排序或截断。 | +| [`cumulative_sum`](/aggregations/pipeline/cumulative-sum) | 父级 | 计算前一个聚合的桶的累积求和。 | +| [`derivative`](/aggregations/pipeline/derivative) | 父级 | 计算聚合的每个桶的一阶导数和二阶导数。 | +| [`extended_stats`](/aggregations/pipeline/extended-stats) | 同级 | `stats_bucket` 聚合的更全面版本,提供额外的指标。 | +| [`max_bucket`](/aggregations/pipeline/max-bucket) | 同级 | 计算前一个聚合的每个桶中指标的最大值。 | +| [`min_bucket`](/aggregations/pipeline/min-bucket) | 同级 | 计算前一个聚合的每个桶中指标的最小值。 | +| [`moving_avg`](/aggregations/pipeline/moving-avg) *(已弃用)* | 父级 | 计算有序数据集的窗口(相邻子集)中包含的指标的平均值序列。 | +| [`moving_fn`](/aggregations/pipeline/moving-function) | 父级 | 在滑动窗口上执行脚本。 | +| [`percentiles_bucket`](/aggregations/pipeline/percentiles-bucket) | 同级 | 计算分桶指标的百分位数放置。 | +| [`serial_diff`](/aggregations/pipeline/serial-diff) | 父级 | 计算当前桶和前一个桶中指标值之间的差异。它将结果存储在当前桶中。 | +| [`stats_bucket`](/aggregations/pipeline/stats-bucket) | 同级 | 返回前一个聚合的桶的各种统计信息(`count`、`min`、`max`、`avg` 和 `sum`)。 | +| [`sum_bucket`](/aggregations/pipeline/sum-bucket) | 同级 | 计算前一个聚合的每个桶中指标的总和。 | + +## 桶路径 + +管道聚合使用 `buckets_path` 参数引用其他聚合的输出。 +`buckets_path` 参数具有以下语法: + +```r +buckets_path = <agg_name>[ > <agg_name> ... ][ .<metric_name> ] +``` + +此语法使用以下元素。 + +| 元素 | 描述 | +| :-- | :-- | +| `<agg_name>` | 聚合的名称。 | +| `>` | 子选择器,用于从一个聚合(父)导航到另一个嵌套聚合(子)。 | +| `.<metric_name>` | 指定要从多值聚合中检索的指标。仅当目标聚合产生多个指标时才需要。 | + +要可视化桶路径,假设您具有以下聚合结构: + +```json +"aggs": { + "parent_agg": { + "terms": { + "field": "category" + }, + "aggs": { + "child_agg": { + "stats": { + "field": "price" + } + } + } + } +} +``` + +要引用嵌套在 `parent_agg` 中的 `child_agg` 的平均价格,请使用 `parent_agg>child_agg.avg`。 + +示例: + +- `my_sum.sum`:引用 `my_sum` 聚合的总和指标。 + +- `popular_tags>my_sum.sum`:引用嵌套在 `popular_tags` 聚合下的 `my_sum` 聚合的 `sum` 指标。 + +::: tip TIP +对于多值指标聚合(如 `stats` 或 `percentiles`),您必须在路径中包含指标名称(例如,`.min`)。对于单值指标(如 `sum` 或 `avg`),如果不会产生歧义,则指标名称是可选的。 +::: + +### 桶路径示例 + +以下示例对 OpenSearch Dashboards 日志示例数据进行操作。它创建 `bytes` 字段中值的直方图,对每个直方图桶中的 `phpmemory` 字段求和,最后使用 `sum_bucket` 管道聚合对桶求和。`buckets_path` 遵循从 `number_of_bytes` 父聚合到 `sum_total_memory` 子聚合的 `number_of_bytes>sum_total_memory` 路径: + +```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" + } + } + } +} +``` + +请注意,`buckets_path` 包含组件聚合的名称。路径是有向的,意味着它们以一种方式级联,从父级向下到子级。 + +管道聚合返回从所有桶求和的总内存: + +```json +{ + ... + "aggregations": { + "number_of_bytes": { + "buckets": [ + { + "key": 0, + "doc_count": 13372, + "sum_total_memory": { + "value": 91266400 + } + }, + { + "key": 10000, + "doc_count": 702, + "sum_total_memory": { + "value": 0 + } + } + ] + }, + "sum_copies": { + "value": 91266400 + } + } +} +``` + +### 计数路径 + +您可以指示 `buckets_path` 使用计数而不是值作为其输入。为此,请使用 `_count` 桶路径变量。 + +以下示例计算 OpenSearch Dashboards 日志示例数据中字节数直方图的基本统计信息。它创建 `bytes` 字段中值的直方图,然后计算直方图桶中计数的统计信息。 + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "number_of_bytes": { + "histogram": { + "field": "bytes", + "interval": 10000 + } + }, + "count_stats": { + "stats_bucket": { + "buckets_path": "number_of_bytes>_count" + } + } + } +} +``` + +结果显示有关桶*文档计数*的统计信息: + +```json +{ +... + "aggregations": { + "number_of_bytes": { + "buckets": [ + { + "key": 0, + "doc_count": 13372 + }, + { + "key": 10000, + "doc_count": 702 + } + ] + }, + "count_stats": { + "count": 2, + "min": 702, + "max": 13372, + "avg": 7037, + "sum": 14074 + } + } +} +``` + +## 数据间隙 + +由于多种原因,实际数据可能会从嵌套聚合中丢失,包括: + +- 文档中的缺失值。 +- 聚合链中任何位置的空桶。 +- 计算桶值所需的缺失数据(例如,滚动函数(如 `derivative`)需要一个或多个先前的值才能开始)。 + +您可以使用 `gap_policy` 属性指定处理缺失数据的策略:跳过缺失数据或用零替换缺失数据。 + +`gap_policy` 参数对所有管道聚合都有效。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。 | +| `format` | 可选 | String | 一个 [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化的输出。 | diff --git a/i18n/zh/aggregations/pipeline/max-bucket.md b/i18n/zh/aggregations/pipeline/max-bucket.md new file mode 100644 index 00000000..924e151e --- /dev/null +++ b/i18n/zh/aggregations/pipeline/max-bucket.md @@ -0,0 +1,111 @@ +--- +title: 最大桶 +--- + +# 最大桶聚合 + +`max_bucket` 聚合是一种同级聚合,用于计算先前聚合的每个桶中指标的最大值。 + +指定的指标必须是数值类型,并且同级聚合必须是多桶聚合。 + +## 参数 + +`max_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。| +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月的字节总和。最后,`max_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" + } + } + } + }, + "max_monthly_bytes": { + "max_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` + +## 示例响应 + +`max_bucket` 聚合返回多个桶中指定指标的最大值。在此示例中,它从 `visits_per_month` 内的 `sum_of_bytes` 指标计算每月的最大字节数。`value` 字段显示在所有桶中找到的最大值。`keys` 数组包含观察到此最大值的桶的键。它是一个数组,因为多个桶可能具有相同的最大值。在这种情况下,包含所有匹配的桶键。这确保即使多个时间段(或术语)具有相同的最大值,结果也是准确的: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "max_monthly_bytes": { + "value": 39103067, + "keys": [ + "2025-04-01T00:00:00.000Z" + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/min-bucket.md b/i18n/zh/aggregations/pipeline/min-bucket.md new file mode 100644 index 00000000..1d4604db --- /dev/null +++ b/i18n/zh/aggregations/pipeline/min-bucket.md @@ -0,0 +1,111 @@ +--- +title: 最小桶 +--- + +# 最小桶聚合 + +`min_bucket` 聚合是一种同级聚合,用于计算先前聚合的每个桶中指标的最小值。 + +指定的指标必须是数值类型,并且同级聚合必须是多桶聚合。 + +## 参数 + +`min_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。| +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月的字节总和。最后,`min_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" + } + } + } + }, + "min_monthly_bytes": { + "min_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` + +## 示例响应 + +`max_bucket` 聚合返回多个桶中指定指标的最小值。在此示例中,它从 `visits_per_month` 内的 `sum_of_bytes` 指标计算每月的最小字节数。`value` 字段显示在所有桶中找到的最小值。`keys` 数组包含观察到此最小值的桶的键。它是一个数组,因为多个桶可能具有相同的最小值。在这种情况下,包含所有匹配的桶键。这确保即使多个时间段(或术语)具有相同的最小值,结果也是准确的: + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "min_monthly_bytes": { + "value": 2804103, + "keys": [ + "2025-03-01T00:00:00.000Z" + ] + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/moving-avg.md b/i18n/zh/aggregations/pipeline/moving-avg.md new file mode 100644 index 00000000..76202e1b --- /dev/null +++ b/i18n/zh/aggregations/pipeline/moving-avg.md @@ -0,0 +1,560 @@ +--- +title: 移动平均 +--- + +# 移动平均聚合 +<Badge type="danger" text="已弃用" /> + +::: warning IMPORTANT +`moving_avg` 聚合已被弃用,推荐使用 `moving_fn` 聚合。 +::: + +`moving_avg` 聚合是一种父管道聚合,用于计算有序数据集的窗口(相邻子集)中包含的指标的一系列平均值。 + +要创建 `moving_avg` 聚合,首先创建一个 `histogram` 或 `date_histogram` 聚合。然后,可选地在直方图聚合中嵌入一个指标聚合。最后,在直方图中嵌入 `moving_avg` 聚合,并将 `buckets_path` 参数设置为要跟踪的嵌入指标。 + +窗口的大小是窗口中连续数据值的数量。在每次迭代期间,算法计算窗口中所有数据点的平均值,然后向前滑动一个数据值,排除前一个窗口的第一个值并包含下一个窗口的第一个值。 + +例如,给定数据 `[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 +依此类推... +``` + +`moving_avg` 聚合通常应用于时间序列数据,以平滑噪声或短期波动并识别趋势。 +指定较小的窗口大小以平滑小规模波动。指定较大的窗口大小以平滑高频波动或随机噪声,使低频趋势更加明显。 + +有关移动平均的更多信息,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Moving_average)。 + +## 参数 + +`moving_avg` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | +| `window` | 可选 | Numerical | 窗口中包含的数据点数量。默认值为 `5`。 | +| `model` | 可选 | String | 要使用的加权移动平均模型。选项为 `ewma`、`holt`、`holt_winters`、`linear` 和 `simple`。默认值为 `simple`。请参阅[模型](#models)。 | +| `settings` | 可选 | Object | 用于调整窗口的参数。请参阅[模型](#models)。 | +| `predict` | 可选 | Numerical | 要追加到结果末尾的预测值数量。默认值为 `0`。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 日志示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,`moving_avg` 聚合根据这些总和计算每月字节的移动平均值: + +```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" + } + } + } + } + } +} +``` + +## 示例响应 + +聚合从第二个桶开始返回 `moving_avg` 值。第一个桶没有移动平均值,因为没有足够的先前数据点来计算它: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + }, + "moving_avg_of_sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + }, + "moving_avg_of_sum_of_bytes": { + "value": 20953585 + } + } + ] + } + } +} +``` + +## 示例:预测 + +您可以使用 `moving_avg` 聚合来预测未来的桶。 + +以下示例将前一个示例的间隔减少到一周,并在响应末尾追加五个预测的一周桶: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "week" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "predict": 5 + } + } + } + } + } +} +``` + +响应包含五个预测。请注意,预测桶的 `doc_count` 为 `0`: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "sum_of_bytes": { + "value": 9213161 + }, + "moving_avg_of_sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9188671 + }, + "moving_avg_of_sum_of_bytes": { + "value": 5372327 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9244851 + }, + "moving_avg_of_sum_of_bytes": { + "value": 6644441.666666667 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "sum_of_bytes": { + "value": 9061045 + }, + "moving_avg_of_sum_of_bytes": { + "value": 7294544 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "sum_of_bytes": { + "value": 8713507 + }, + "moving_avg_of_sum_of_bytes": { + "value": 7647844.2 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "sum_of_bytes": { + "value": 9544718 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9084247 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9155820 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9150558.4 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9025078 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9143988.2 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "sum_of_bytes": { + "value": 5047345 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9100033.6 + } + }, + { + "key_as_string": "2025-06-02T00:00:00.000Z", + "key": 1748822400000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-09T00:00:00.000Z", + "key": 1749427200000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-16T00:00:00.000Z", + "key": 1750032000000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-23T00:00:00.000Z", + "key": 1750636800000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + }, + { + "key_as_string": "2025-06-30T00:00:00.000Z", + "key": 1751241600000, + "doc_count": 0, + "moving_avg_of_sum_of_bytes": { + "value": 8297293.6 + } + } + ] + } + } +} +``` +</details> + +## 模型 + +`moving_avg` 聚合支持五种模型,它们在如何对移动窗口中的值进行加权方面有所不同。 + +使用 `model` 参数指定要使用的模型。 + +| 模型 | 模型关键字 | 加权 | +|-------|---------------|-------------| +| 简单 | `simple` | 窗口中所有值的未加权平均值。 | +| 线性 | `linear` | 使用权重的线性衰减,更重视最近的值。 | +| 指数加权移动平均 | `ewma` | 使用指数递减权重,更重视最近的值。 | +| Holt | `holt` | 使用第二个指数项来平滑长期趋势。 | +| Holt-Winters | `holt_winters` | 使用第三个指数项来平滑周期性(季节性)效应。 | + +使用 `settings` 对象设置模型的属性。下表显示了每个模型的可用设置。 + +| 模型 | 参数 | 允许值 | 默认值 | 描述 | +| :-- | :-- | :-- | :-- | :-- | +| `simple` | None | Numeric array | None | 窗口中所有值的算术平均值。 | +| `linear` | None | Numeric array | None | 窗口中所有值的加权平均值,最近的值权重更高。| +| `ewma` | `alpha` | [0, 1] | 0.3 | 衰减参数。较高的值会给最近的数据点更多权重。 | +| `holt` | `alpha` | [0, 1] | 0.3 | 水平分量的衰减参数。 | +| | `beta` | [0, 1] | 0.1 | 趋势分量的衰减参数。| +| `holt_winters` | `alpha` | [0, 1] | 0.3 | 水平分量的衰减参数。 | +| | `beta` | [0, 1] | 0.3 | 趋势分量的衰减参数。 | +| | `gamma` | [0, 1] | 0.3 | 季节分量的衰减参数。 | +| | `type` | `add`, `mult` | `add` | 定义季节性如何建模:加法或乘法。 | +| | `period` | Integer | 1 | 组成周期的桶数量。 | +| | `pad` | Boolean | `true` | 对于 `mult` 类型模型,是否向 `0` 值添加小偏移量以避免除以零错误。 | + +有关这些模型及其参数的讨论,请参阅 [Wikipedia](https://en.wikipedia.org/wiki/Moving_average)。 + +### 示例:Holt 模型 + +`holt` 模型使用由 `alpha` 和 `beta` 参数控制的指数衰减来计算权重。 + +以下请求使用 Holt 模型计算每周总字节数据的移动平均值,`window` 大小为 `6`,`alpha` 值为 `0.4`,`beta` 值为 `0.2`: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "week" + }, + "aggs": { + "sum_of_bytes": { + "sum": { + "field": "bytes" + } + }, + "moving_avg_of_sum_of_bytes": { + "moving_avg": { + "buckets_path": "sum_of_bytes", + "window": 6, + "model": "holt", + "settings": { "alpha": 0.4, "beta": 0.2 } + } + } + } + } + } +} +``` + +移动平均从第二个桶开始: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "sum_of_bytes": { + "value": 9213161 + }, + "moving_avg_of_sum_of_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9188671 + }, + "moving_avg_of_sum_of_bytes": { + "value": 4604160.2 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9244851 + }, + "moving_avg_of_sum_of_bytes": { + "value": 6806684.584000001 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "sum_of_bytes": { + "value": 9061045 + }, + "moving_avg_of_sum_of_bytes": { + "value": 8341230.127680001 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "sum_of_bytes": { + "value": 8713507 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9260724.7236736 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "sum_of_bytes": { + "value": 9544718 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9657431.903375873 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9155820 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9173999.55240704 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "sum_of_bytes": { + "value": 9025078 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9172040.511275519 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "sum_of_bytes": { + "value": 5047345 + }, + "moving_avg_of_sum_of_bytes": { + "value": 9108804.964619776 + } + } + ] + } + } +} +``` +</details> diff --git a/i18n/zh/aggregations/pipeline/moving-function.md b/i18n/zh/aggregations/pipeline/moving-function.md new file mode 100644 index 00000000..d048fd34 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/moving-function.md @@ -0,0 +1,600 @@ +--- +title: 移动函数 +--- + +# 移动函数聚合 + +`moving_fn` 聚合是一种父管道聚合,它在滑动窗口上执行脚本。滑动窗口在从父 `histogram` 或 `date histogram` 聚合中提取的值序列上移动。窗口从左向右每次移动一个桶;`moving_fn` 在窗口每次移动时运行脚本。 + +使用 `moving_fn` 聚合可以在滑动窗口内的数据上编写任何数值计算脚本。您可以将 `moving_fn` 用于以下目的: + +- 趋势分析 +- 异常值检测 +- 自定义时间序列分析 +- 自定义平滑算法 +- 数字信号处理(DSP) + +## 参数 + +`moving_fn` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 包含要处理的指标值的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `script` | 必需 | String 或 Object | 为每个数据窗口计算值的脚本。可以是内联脚本、存储脚本或脚本文件。脚本可以访问 `buckets_path` 参数中定义的变量名称。 | +| `window` | 必需 | Integer | 滑动窗口中的桶数量。必须是正整数。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | +| `shift` | 可选 | Integer | 窗口移动的桶数。可以是正数(向右移动到未来的桶)或负数(向过去的桶)。默认值为 `0`,它将窗口放置在当前桶的左侧。请参阅[移动窗口](#shifting-the-window)。 | + +## 移动函数的工作原理 + +`moving_fn` 聚合在有序的桶序列上的滑动窗口上操作。从父聚合中的第一个桶开始,`moving_fn` 执行以下操作: + +1. 收集由 `window` 和 `shift` 参数指定的桶中的子序列(窗口)值。 +2. 将这些值作为数组传递给 `script` 指定的函数。 +3. 使用 `script` 从数组中计算单个值。 +4. 将此值作为当前桶的结果返回。 +5. 向前移动一个桶并重复此过程。 + +::: info NOTE +"过去"和"未来"值暗示时间序列数据,这是移动窗口函数最常见的用例。更一般地说,它们分别指任何有序数据序列中的先前和即将到来的值。 +::: + +`moving_fn` 应用的脚本可以是[预定义函数](#predefined-functions)或[自定义脚本](#custom-scripts)。桶值在 `values` 数组中提供给脚本。脚本返回一个双精度值作为结果。允许结果值 `NaN` 和 `+/- Inf`,但不允许 `null`。 + +### 窗口大小 + +`window` 参数指定定义窗口大小的桶数量。 + +传递给 `script` 函数的数组是零索引的。其值在脚本中作为 `values[0]` 到 `values[n]` 访问,其中 `n = values.length - 1`。 + +### 移动窗口 + +`shift` 参数控制移动窗口相对于当前桶的位置。根据您的分析是否需要历史上下文、当前数据或未来预测来设置 `shift`。默认值为 `0`,它仅显示过去的值(不包括当前桶)。 + +`shift` 的一些常用值如下: + +| `shift` | 窗口描述 | | +| :-- | :-- | :-- | +| `0` | 仅过去的值。不包括当前值。 | `--[-----]x----` | +| `1` | 过去的值,包括当前值。 | `--[----x]-----` | +| `window/2` | 将窗口居中于当前值周围。 | `--[--x--]-----` | +| `window` | 未来的值,包括当前值。 | `--[x----]-----` | + +当窗口在序列开头或结尾超出可用数据时,`window` 会自动缩小以仅使用可用点: + +``` +[x----]-- +-[x----]- +--[x----] +---[x---] +----[x--] +-----[x-] +------[x] +``` + +## 预定义函数 + +`moving_fn` 聚合支持许多预定义函数,可以使用这些函数代替自定义脚本。这些函数可从 `MovingFunctions` 上下文访问。例如,您可以通过 `MovingFunctions.max(values)` 访问 `max` 函数。 + +下表描述了预定义函数。 + +| 函数 | 模型关键字 | 描述 | +|:-- | :-- |:-- | +| Max | `max` | 窗口中的最大值。 | +| Min | `min` | 窗口中的最小值。 | +| Sum | `sum` | 窗口中值的总和。 | +| Unweighted average | `unweightedAvg` | 窗口中所有值的未加权平均值,等于 `sum` / `window`。 | +| Linear weighted average | `linearWeightedAvg` | 使用权重线性衰减的加权平均值,更重视最近的值。 | +| Exponentially Weighted Moving Average | `ewma` | 使用指数衰减权重的加权平均值,更重视最近的值。 | +| Holt | `holt` | 使用第二个指数项来平滑长期趋势的加权平均值。 | +| Holt-Winters | `holt_wimnters` | 使用第三个指数项来平滑周期性(季节性)效应的加权平均值。 | +| Standard deviation | `stdDev` | 窗口中值的总和。 | + +所有预定义函数都将 `values` 数组作为第一个参数。对于接受额外参数的函数,请在 `values` 之后按顺序传递这些参数。例如,通过将 `script` 值设置为 `MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))` 来调用 `stdDev` 函数。 + +下表显示了每个模型所需的设置。 + +| 函数 | 额外参数 | 允许值 | 默认值 | 描述 | +| :-- | :-- | :-- | :-- | :-- | +| `max` | None | Numeric array | None | 窗口的最大值。 | +| `min` | None | Numeric array | None | 窗口的最小值。 | +| `sum` | None | Numeric array | None | 窗口中所有值的总和。 | +| `unweightedAvg` | None | Numeric array | None | 窗口中所有值的算术平均值。 | +| `linearWeightedAvg` | None | Numeric array | None | 窗口中所有值的加权平均值,最近的值权重更高。| +| `ewma` | `alpha` | [0, 1] | 0.3 | 衰减参数。较高的值会给最近的数据点更多权重。 | +| `holt` | `alpha` | [0, 1] | 0.3 | 水平分量的衰减参数。 | +| | `beta` | [0, 1] | 0.1 | 趋势分量的衰减参数。| +| `holt_winters` | `alpha` | [0, 1] | 0.3 | 水平分量的衰减参数。 | +| | `beta` | [0, 1] | 0.3 | 趋势分量的衰减参数。 | +| | `gamma` | [0, 1] | 0.3 | 季节分量的衰减参数。 | +| | `type` | `add`, `mult` | `add` | 定义季节性如何建模:加法或乘法。 | +| | `period` | Integer | 1 | 组成周期的桶数量。 | +| | `pad` | Boolean | true | 对于 `mult` 类型模型,是否向 `0` 值添加小偏移量以避免除以零错误。 | +| `stdDev` | `avg` | Any double | None | 窗口的标准差。要计算有意义的标准差,请使用滑动窗口数组的平均值,通常为 `MovingFunctions.unweightedAvg(values)`。 | + +::: warning IMPORTANT +预定义函数不支持缺少参数的函数签名。因此,即使使用默认值,您也必须提供额外的参数。 +::: + +### 示例:预定义函数 + +以下示例使用 OpenSearch Dashboards 日志示例数据创建一个间隔为一周的日期直方图。`sum` 子聚合计算每周记录的所有字节的总和。最后,`moving_fn` 聚合使用 `window` 大小为 `5`、默认 `shift` 为 `0` 和未加权平均值来计算字节总和的标准差: + +```json +POST /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histo": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "week" + }, + "aggs": { + "the_sum": { + "sum": { "field": "bytes" } + }, + "the_movavg": { + "moving_fn": { + "buckets_path": "the_sum", + "window": 5, + "script": "MovingFunctions.stdDev(values, MovingFunctions.unweightedAvg(values))" + } + } + } + } + } +} +``` + +## 示例响应 + +响应显示从第二个桶开始的移动窗口的标准差,初始值为零。`stdDev` 函数对于空窗口或仅包含无效值(`null` 或 `NaN`)的窗口返回 `0`: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histo": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "the_sum": { + "value": 1531493 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "the_sum": { + "value": 9213161 + }, + "the_movavg": { + "value": 0 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "the_sum": { + "value": 9188671 + }, + "the_movavg": { + "value": 3840834 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "the_sum": { + "value": 9244851 + }, + "the_movavg": { + "value": 3615414.498228507 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "the_sum": { + "value": 9061045 + }, + "the_movavg": { + "value": 3327358.65618917 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "the_sum": { + "value": 8713507 + }, + "the_movavg": { + "value": 3058812.9440705855 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "the_sum": { + "value": 9544718 + }, + "the_movavg": { + "value": 195603.33146038183 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "the_sum": { + "value": 9155820 + }, + "the_movavg": { + "value": 270085.92336040025 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "the_sum": { + "value": 9025078 + }, + "the_movavg": { + "value": 269477.75659701484 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "the_sum": { + "value": 5047345 + }, + "the_movavg": { + "value": 267356.5422566652 + } + } + ] + } + } +} +``` +</details> + +## 自定义脚本 + +您可以提供任意自定义脚本来计算 `moving_fn` 结果。自定义脚本使用 Painless 脚本语言。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。 + +### 示例:自定义脚本 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一周的日期直方图。`sum` 子聚合计算每周所有应税收入的总和。然后 `moving_fn` 脚本返回当前值之前的两个值中较大的一个,或者如果两个值不可用则返回 `NaN`: + +```json +POST /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "my_date_histo": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "the_sum": { + "sum": { "field": "taxful_total_price" } + }, + "the_movavg": { + "moving_fn": { + "buckets_path": "the_sum", + "window": 2, + "script": "return (values.length < 2 ? Double.NaN : (values[0]>values[1] ? values[0] : values[1]))" + } + } + } + } + } +} +``` + +该示例从第三个桶开始返回计算结果,此时存在足够的先前数据来执行计算: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histo": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 582, + "the_sum": { + "value": 41455.5390625 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "the_sum": { + "value": 79448.60546875 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "the_sum": { + "value": 78208.4296875 + }, + "the_movavg": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "the_sum": { + "value": 81277.296875 + }, + "the_movavg": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 924, + "the_sum": { + "value": 70494.2578125 + }, + "the_movavg": { + "value": 81277.296875 + } + } + ] + } + } +} +``` +</details> + +## 示例:移动平均 + +`moving_fn` 聚合替代了已弃用的 `moving_avg` 聚合。`moving_fn` 聚合与 `moving_avg` 聚合类似,但更通用,因为它计算任意函数而不仅仅是平均值。所有预定义的 `moving_avg` 函数也在 `moving_fn` 中实现。 + +`holt` 模型是一种移动平均值,使用由 `alpha` 和 `beta` 参数控制的指数衰减权重。以下示例使用 OpenSearch Dashboards 日志示例数据创建一个间隔为一周的日期直方图。`sum` 子聚合计算每周所有字节的总和。最后,`moving_fn` 聚合使用 Holt 模型计算字节总和的加权平均值,`window` 大小为 `6`,默认 `shift` 为 `0`,`alpha` 值为 `0.3`,`beta` 值为 `0.1`: + +```json +POST /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "my_date_histogram": { + "date_histogram": { + "field": "timestamp", + "calendar_interval": "week" + }, + "aggs": { + "the_sum": { + "sum": { "field": "bytes" } + }, + "the_movavg": { + "moving_fn": { + "buckets_path": "the_sum", + "window": 6, + "script": "MovingFunctions.holt(values, 0.3, 0.1)" + } + } + } + } + } +} +``` + +聚合从第二个桶开始返回移动 `holt` 平均值: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 16, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "my_date_histogram": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "the_sum": { + "value": 1531493 + }, + "the_movavg": { + "value": null + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "the_sum": { + "value": 9213161 + }, + "the_movavg": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "the_sum": { + "value": 9188671 + }, + "the_movavg": { + "value": 3835993.3999999994 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "the_sum": { + "value": 9244851 + }, + "the_movavg": { + "value": 5603111.707999999 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "the_sum": { + "value": 9061045 + }, + "the_movavg": { + "value": 6964515.302359998 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "the_sum": { + "value": 8713507 + }, + "the_movavg": { + "value": 7930766.089341199 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "the_sum": { + "value": 9544718 + }, + "the_movavg": { + "value": 8536788.607547803 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "the_sum": { + "value": 9155820 + }, + "the_movavg": { + "value": 9172269.837272028 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "the_sum": { + "value": 9025078 + }, + "the_movavg": { + "value": 9166173.88436614 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "the_sum": { + "value": 5047345 + }, + "the_movavg": { + "value": 9123157.830417283 + } + } + ] + } + } +} +``` +</details> diff --git a/i18n/zh/aggregations/pipeline/percentiles-bucket.md b/i18n/zh/aggregations/pipeline/percentiles-bucket.md new file mode 100644 index 00000000..280803f6 --- /dev/null +++ b/i18n/zh/aggregations/pipeline/percentiles-bucket.md @@ -0,0 +1,280 @@ +--- +title: 百分位数桶 +--- + +# 百分位数桶聚合 + +`percentiles_bucket` 聚合是一种同级聚合,用于计算桶化指标的百分位数位置。 + +`percentiles_bucket` 聚合精确计算百分位数,不进行近似或插值。每个百分位数作为小于或等于目标百分位数的最接近值返回。 + +`percentiles_bucket` 聚合要求将整个值列表临时保存在内存中,即使对于大型数据集也是如此。相比之下,[`percentiles` 指标聚合](/aggregations/metric/percentile)使用更少的内存,但会近似百分比。 + +指定的指标必须是数值类型,并且同级聚合必须是多桶聚合。 + +## 参数 + +`avg_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | +| `percents` | 可选 | List | 包含要包含在输出中的任意数量的数值百分比值的列表。有效值在 0.0 到 100.0 之间(包括两端)。默认值为 `[1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]`。 | +| `keyed` | 可选 | Boolean | 是否将输出格式化为字典而不是键值对对象数组。默认值为 `true`(将输出格式化为键值对)。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一周的日期直方图。`sum` 子聚合将每周的 `taxful_total_price` 相加。最后,`percentiles_bucket` 聚合根据这些总和计算每周的百分位数值: + +```json +POST /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "weekly_sales": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "total_price": { + "sum": { + "field": "taxful_total_price" + } + } + } + }, + "percentiles_monthly_sales": { + "percentiles_bucket": { + "buckets_path": "weekly_sales>total_price" + } + } + } +} +``` + +## 示例响应 + +聚合返回每周价格总计的默认百分位数值: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "weekly_sales": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 582, + "total_price": { + "value": 41455.5390625 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "total_price": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "total_price": { + "value": 78208.4296875 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "total_price": { + "value": 81277.296875 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 924, + "total_price": { + "value": 70494.2578125 + } + } + ] + }, + "percentiles_monthly_sales": { + "values": { + "1.0": 41455.5390625, + "5.0": 41455.5390625, + "25.0": 70494.2578125, + "50.0": 78208.4296875, + "75.0": 79448.60546875, + "95.0": 81277.296875, + "99.0": 81277.296875 + } + } + } +} +``` +</details> + +## 示例:选项 + +下一个示例使用与前一个示例相同的数据计算百分位数,但有以下差异: + +- `percents` 参数指定仅计算第 25、50 和 75 百分位数。 +- 使用 `format` 参数追加字符串格式化输出。 +- 通过将 `keyed` 参数设置为 `false`,将结果显示为键值对对象(附加字符串值)。 + +示例如下: + +```json +POST /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "weekly_sales": { + "date_histogram": { + "field": "order_date", + "calendar_interval": "week" + }, + "aggs": { + "total_price": { + "sum": { + "field": "taxful_total_price" + } + } + } + }, + "percentiles_monthly_sales": { + "percentiles_bucket": { + "buckets_path": "weekly_sales>total_price", + "percents": [25.0, 50.0, 75.0], + "format": "$#,###.00", + "keyed": false + } + } + } +} +``` + +## 示例响应:选项 + +这些选项修改了聚合的输出: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4675, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "weekly_sales": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 582, + "total_price": { + "value": 41455.5390625 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1048, + "total_price": { + "value": 79448.60546875 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1048, + "total_price": { + "value": 78208.4296875 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1073, + "total_price": { + "value": 81277.296875 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 924, + "total_price": { + "value": 70494.2578125 + } + } + ] + }, + "percentiles_monthly_sales": { + "values": [ + { + "key": 25, + "value": 70494.2578125, + "25.0_as_string": "$70,494.26" + }, + { + "key": 50, + "value": 78208.4296875, + "50.0_as_string": "$78,208.43" + }, + { + "key": 75, + "value": 79448.60546875, + "75.0_as_string": "$79,448.61" + } + ] + } + } +} +``` +</details> diff --git a/i18n/zh/aggregations/pipeline/serial-diff.md b/i18n/zh/aggregations/pipeline/serial-diff.md new file mode 100644 index 00000000..815b098f --- /dev/null +++ b/i18n/zh/aggregations/pipeline/serial-diff.md @@ -0,0 +1,284 @@ +--- +title: 序列差分 +--- + +# 序列差分聚合 + +`serial_diff` 聚合是一种父管道聚合,用于计算当前桶和前一个桶中指标值之间的差异。它将结果存储在当前桶中。 + +使用 `serial_diff` 聚合来计算具有指定滞后的时间段之间的变化。`lag` 参数(正整数值)指定从当前桶减去哪个前一个桶的值。默认 `lag` 值为 `1`,这意味着 `serial_diff` 从当前桶的值中减去紧邻前一个桶的值。 + +## 参数 + +`serial_diff` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | +| `lag` | 可选 | Integer | 要从当前桶减去的历史桶。必须是正整数。默认值为 `1`。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 日志示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,`serial_diff` 聚合根据这些总和计算月度总字节数的月度差异: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "monthly_bytes": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "total_bytes": { + "sum": { + "field": "bytes" + } + }, + "monthly_bytes_change": { + "serial_diff": { + "buckets_path": "total_bytes", + "lag": 1 + } + } + } + } + } +} +``` + +响应包含第二个月和第三个月的月度差异。(第一个月的 `serial_diff` 无法计算,因为没有前一个月可以进行比较): + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "monthly_bytes": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "total_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "total_bytes": { + "value": 39103067 + }, + "monthly_bytes_change": { + "value": 36298964 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "total_bytes": { + "value": 37818519 + }, + "monthly_bytes_change": { + "value": -1284548 + } + } + ] + } + } +} +``` + +以下折线图显示了 `serial_diff` 聚合的结果。x 轴表示时间,y 轴显示总传输字节数的月度变化。线上的每个数据点反映该月份总字节数与前一个月份之间的差异。例如,值为 5,000,000 意味着系统传输的字节数比上个月多 500 万;负值表示减少。第一个月从线上排除,因为没有前一个桶可以进行比较(差异未定义)。该线从第二个月开始,并在所有可用数据中继续。 + +*示例序列差分聚合可视化* + +此可视化有助于您快速发现随时间推移的数据量的峰值、下降或趋势。 + +## 示例:多周期差异 + +使用较大的 `lag` 值将每个桶与更早发生的桶进行比较。以下示例计算每周字节数据的差异,滞后为 4(这意味着每个桶与 4 周前的桶进行比较)。这样做的效果是消除任何周期为 4 周的变化: + +```json +GET opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "monthly_bytes": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "week" + }, + "aggs": { + "total_bytes": { + "sum": { + "field": "bytes" + } + }, + "monthly_bytes_change": { + "serial_diff": { + "buckets_path": "total_bytes", + "lag": 4 + } + } + } + } + } +} +``` + +## 示例响应 + +响应包含每周桶的列表。请注意,`serial_diff` 聚合直到第五个桶才开始,此时具有 `4` 滞后的桶变得可用: + +<details open markdown="block"> +<summary> + 响应 +</summary> + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "monthly_bytes": { + "buckets": [ + { + "key_as_string": "2025-03-24T00:00:00.000Z", + "key": 1742774400000, + "doc_count": 249, + "total_bytes": { + "value": 1531493 + } + }, + { + "key_as_string": "2025-03-31T00:00:00.000Z", + "key": 1743379200000, + "doc_count": 1617, + "total_bytes": { + "value": 9213161 + } + }, + { + "key_as_string": "2025-04-07T00:00:00.000Z", + "key": 1743984000000, + "doc_count": 1610, + "total_bytes": { + "value": 9188671 + } + }, + { + "key_as_string": "2025-04-14T00:00:00.000Z", + "key": 1744588800000, + "doc_count": 1610, + "total_bytes": { + "value": 9244851 + } + }, + { + "key_as_string": "2025-04-21T00:00:00.000Z", + "key": 1745193600000, + "doc_count": 1609, + "total_bytes": { + "value": 9061045 + }, + "monthly_bytes_change": { + "value": 7529552 + } + }, + { + "key_as_string": "2025-04-28T00:00:00.000Z", + "key": 1745798400000, + "doc_count": 1554, + "total_bytes": { + "value": 8713507 + }, + "monthly_bytes_change": { + "value": -499654 + } + }, + { + "key_as_string": "2025-05-05T00:00:00.000Z", + "key": 1746403200000, + "doc_count": 1710, + "total_bytes": { + "value": 9544718 + }, + "monthly_bytes_change": { + "value": 356047 + } + }, + { + "key_as_string": "2025-05-12T00:00:00.000Z", + "key": 1747008000000, + "doc_count": 1610, + "total_bytes": { + "value": 9155820 + }, + "monthly_bytes_change": { + "value": -89031 + } + }, + { + "key_as_string": "2025-05-19T00:00:00.000Z", + "key": 1747612800000, + "doc_count": 1610, + "total_bytes": { + "value": 9025078 + }, + "monthly_bytes_change": { + "value": -35967 + } + }, + { + "key_as_string": "2025-05-26T00:00:00.000Z", + "key": 1748217600000, + "doc_count": 895, + "total_bytes": { + "value": 5047345 + }, + "monthly_bytes_change": { + "value": -3666162 + } + } + ] + } + } +} +``` +</details> diff --git a/i18n/zh/aggregations/pipeline/stats-bucket.md b/i18n/zh/aggregations/pipeline/stats-bucket.md new file mode 100644 index 00000000..f5867d1d --- /dev/null +++ b/i18n/zh/aggregations/pipeline/stats-bucket.md @@ -0,0 +1,112 @@ +--- +title: 统计桶 +--- + +# 统计桶聚合 + +`stats_bucket` 聚合是一种同级聚合,用于返回先前聚合的桶的各种统计信息(`count`、`min`、`max`、`avg` 和 `sum`)。 + +指定的指标必须是数值类型,并且同级聚合必须是多桶聚合。 + +## 参数 + +`stats_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。 | +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `<stat>_as_string` 属性中返回格式化输出。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月所有字节的总和。最后,`stats_bucket` 聚合从这些总和返回 `count`、`avg`、`sum`、`min` 和 `max` 统计信息: + +```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" + } + } + } +} +``` + +## 示例响应 + +聚合返回桶的所有五个基本统计信息: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "stats_monthly_bytes": { + "count": 3, + "min": 2804103, + "max": 39103067, + "avg": 26575229.666666668, + "sum": 79725689 + } + } +} +``` diff --git a/i18n/zh/aggregations/pipeline/sum-bucket.md b/i18n/zh/aggregations/pipeline/sum-bucket.md new file mode 100644 index 00000000..b961035f --- /dev/null +++ b/i18n/zh/aggregations/pipeline/sum-bucket.md @@ -0,0 +1,108 @@ +--- +title: 求和桶 +--- + +# 求和桶聚合 + +`sum_bucket` 聚合是一种同级聚合,用于计算先前聚合的每个桶中指标的总和。 + +指定的指标必须是数值类型,并且同级聚合必须是多桶聚合。 + +## 参数 + +`sum_bucket` 聚合接受以下参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :-- | :-- | :-- | :-- | +| `buckets_path` | 必需 | String | 要聚合的聚合桶的路径。请参阅[桶路径](/aggregations/pipeline/#buckets-path)。 | +| `gap_policy` | 可选 | String | 应用于缺失数据的策略。有效值为 `skip` 和 `insert_zeros`。默认值为 `skip`。请参阅[数据间隙](/aggregations/pipeline/#data-gaps)。| +| `format` | 可选 | String | [DecimalFormat](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) 格式化字符串。在聚合的 `value_as_string` 属性中返回格式化输出。 | + +## 示例 + +以下示例使用 OpenSearch Dashboards 电子商务示例数据创建一个间隔为一个月的日期直方图。`sum` 子聚合计算每个月的字节总和。最后,`sum_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" + } + } + } + }, + "sum_monthly_bytes": { + "sum_bucket": { + "buckets_path": "visits_per_month>sum_of_bytes" + } + } + } +} +``` + +## 示例响应 + +聚合返回所有月度桶的字节总和: + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "visits_per_month": { + "buckets": [ + { + "key_as_string": "2025-03-01T00:00:00.000Z", + "key": 1740787200000, + "doc_count": 480, + "sum_of_bytes": { + "value": 2804103 + } + }, + { + "key_as_string": "2025-04-01T00:00:00.000Z", + "key": 1743465600000, + "doc_count": 6849, + "sum_of_bytes": { + "value": 39103067 + } + }, + { + "key_as_string": "2025-05-01T00:00:00.000Z", + "key": 1746057600000, + "doc_count": 6745, + "sum_of_bytes": { + "value": 37818519 + } + } + ] + }, + "sum_monthly_bytes": { + "value": 79725689 + } + } +} +``` diff --git a/i18n/zh/analyzers/character-filters/html-character-filter.md b/i18n/zh/analyzers/character-filters/html-character-filter.md new file mode 100644 index 00000000..59d377c3 --- /dev/null +++ b/i18n/zh/analyzers/character-filters/html-character-filter.md @@ -0,0 +1,170 @@ +--- +title: HTML 剥离 +--- + +# HTML 剥离字符过滤器 + +`html_strip` 字符过滤器从输入文本中删除 HTML 标签(例如 `<div>`、`<p>` 和 `<a>`)并呈现纯文本。可以配置该过滤器以保留某些标签或将特定 HTML 实体(例如 ` `)解码为空格。 + +## 示例 + +以下请求将 `html_strip` 字符过滤器应用于提供的文本: + +```json +GET /_analyze +{ + "tokenizer": "keyword", + "char_filter": [ + "html_strip" + ], + "text": "<p>Commonly used calculus symbols include α, β and θ </p>" +} +``` + +响应包含 HTML 字符已转换为其解码值的词元: + +```json +{ + "tokens": [ + { + "token": """ +Commonly used calculus symbols include α, β and θ +""", + "start_offset": 0, + "end_offset": 74, + "type": "word", + "position": 0 + } + ] +} +``` + +## 参数 + +`html_strip` 字符过滤器可以使用以下参数进行配置。 + +| 参数 | 是否必需 | 数据类型 | 描述 | +|:---|:---|:---|:---| +| `escaped_tags` | 可选 | 字符串数组 | HTML 元素名称数组,不包含尖括号(`< >`)。从文本中剥离 HTML 时,过滤器不会删除此列表中的元素。例如,将数组设置为 `["b", "i"]` 将防止剥离 `<b>` 和 `<i>` 元素。| + +## 示例:带有小写过滤器的自定义分析器 + +以下示例请求创建一个自定义分析器,该分析器使用 `html_strip` 分析器和 `lowercase` 过滤器剥离 HTML 标签并将纯文本转换为小写: + +```json +PUT /html_strip_and_lowercase_analyzer +{ + "settings": { + "analysis": { + "char_filter": { + "html_filter": { + "type": "html_strip" + } + }, + "analyzer": { + "html_strip_analyzer": { + "type": "custom", + "char_filter": ["html_filter"], + "tokenizer": "standard", + "filter": ["lowercase"] + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /html_strip_and_lowercase_analyzer/_analyze +{ + "analyzer": "html_strip_analyzer", + "text": "<h1>Welcome to <strong>OpenSearch</strong>!</h1>" +} +``` + +在响应中,HTML 标签已被删除,纯文本已转换为小写: + +```json +{ + "tokens": [ + { + "token": "welcome", + "start_offset": 4, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "to", + "start_offset": 12, + "end_offset": 14, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "opensearch", + "start_offset": 23, + "end_offset": 42, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` + +## 示例:保留 HTML 标签的自定义分析器 + +以下示例请求创建一个保留 HTML 标签的自定义分析器: + +```json +PUT /html_strip_preserve_analyzer +{ + "settings": { + "analysis": { + "char_filter": { + "html_filter": { + "type": "html_strip", + "escaped_tags": ["b", "i"] + } + }, + "analyzer": { + "html_strip_analyzer": { + "type": "custom", + "char_filter": ["html_filter"], + "tokenizer": "keyword" + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /html_strip_preserve_analyzer/_analyze +{ + "analyzer": "html_strip_analyzer", + "text": "<p>This is a <b>bold</b> and <i>italic</i> text.</p>" +} +``` + +在响应中,`italic` 和 `bold` 标签已保留,如自定义分析器请求中所指定: + +```json +{ + "tokens": [ + { + "token": """ +This is a <b>bold</b> and <i>italic</i> text. +""", + "start_offset": 0, + "end_offset": 52, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/character-filters/icu-normalization.md b/i18n/zh/analyzers/character-filters/icu-normalization.md new file mode 100644 index 00000000..52f315f2 --- /dev/null +++ b/i18n/zh/analyzers/character-filters/icu-normalization.md @@ -0,0 +1,168 @@ +--- +title: ICU 规范化 +--- + +# ICU 规范化字符过滤器 + +`icu_normalizer` 字符过滤器通过应用 [Unicode 标准附件 #15](http://unicode.org/reports/tr15/) 中定义的规范化模式之一,将文本转换为规范的 Unicode 形式。此过程在分词之前标准化字符表示,确保等效字符被一致地处理。 + +## 安装 + +`icu_normalizer` 字符过滤器需要 `analysis-icu` 插件。有关安装说明,请参阅 [ICU 分析器](/analyzers/language-analyzers/icu)。 + +## 规范化模式 + +该字符过滤器支持以下 Unicode 规范化形式: + +- `nfc`(规范分解,然后规范组合):分解组合字符,然后按标准顺序重新组合它们。这是最常见的规范化形式。 +- `nfd`(规范分解):将组合字符分解为其组成部分。例如,`é` 变成 `e` + 组合尖音符。 +- `nfkc`(兼容性分解,然后规范组合):应用兼容性分解(将视觉上相似的字符转换为标准形式),然后规范组合。 +- `nfkc_cf`(默认):应用带有大小写折叠的 NFKC 规范化。此模式规范化字符表示和大小写。 + +## 参数 + +下表列出了 `icu_normalizer` 字符过滤器的参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`name` | 字符串 | 要应用的 Unicode 规范化形式。有效值为 `nfc`、`nfd`、`nfkc` 和 `nfkc_cf`。默认值为 `nfkc_cf`。 +`mode` | 字符串 | 规范化模式。有效值为 `compose`(默认)和 `decompose`。当指定 `decompose` 时,`nfc` 变为 `nfd`,`nfkc` 变为 `nfkd`。 +`unicode_set_filter` | 字符串 | 指定要规范化哪些字符的 [UnicodeSet](https://unicode-org.github.io/icu/userguide/strings/unicodeset.html) 表达式。可选。如果未指定,则规范化所有字符。 + +## 示例:默认规范化 + +以下示例演示使用默认的 `nfkc_cf` 规范化: + +```json +PUT /icu-norm-default +{ + "settings": { + "analysis": { + "analyzer": { + "default_icu_normalizer": { + "tokenizer": "keyword", + "char_filter": ["icu_normalizer"] + } + } + } + } +} +``` + +使用包含连字和大小写变体的文本测试规范化器: + +```json +POST /icu-norm-default/_analyze +{ + "analyzer": "default_icu_normalizer", + "text": "financial AFFAIRS" +} +``` + +响应显示规范化和大小写折叠: + +```json +{ + "tokens": [ + { + "token": "financial affairs", + "start_offset": 0, + "end_offset": 16, + "type": "word", + "position": 0 + } + ] +} +``` + +## 示例:NFD(分解)规范化 + +以下示例通过将 `mode` 设置为 `decompose` 来配置 NFD 规范化: + +```json +PUT /icu-norm-nfd +{ + "settings": { + "analysis": { + "char_filter": { + "nfd_normalizer": { + "type": "icu_normalizer", + "name": "nfc", + "mode": "decompose" + } + }, + "analyzer": { + "nfd_analyzer": { + "tokenizer": "keyword", + "char_filter": ["nfd_normalizer"] + } + } + } + } +} +``` + +使用重音字符测试: + +```json +POST /icu-norm-nfd/_analyze +{ + "analyzer": "nfd_analyzer", + "text": "café" +} +``` + +NFD 规范化分解重音字符: + +```json +{ + "tokens": [ + { + "token": "café", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + } + ] +} +``` + +::: info NOTE +注意:虽然视觉表示看起来相同,但底层字符编码已从单个预组合字符更改为单独的基本字符和组合字符。 +::: + +## 示例:使用 unicode_set_filter 的选择性规范化 + +您可以使用 `unicode_set_filter` 参数将规范化限制为特定字符范围: + +```json +PUT /icu-norm-selective +{ + "settings": { + "analysis": { + "char_filter": { + "latin_only_normalizer": { + "type": "icu_normalizer", + "name": "nfkc_cf", + "unicode_set_filter": "[\\u0000-\\u024F]" + } + }, + "analyzer": { + "selective_normalizer": { + "tokenizer": "keyword", + "char_filter": ["latin_only_normalizer"] + } + } + } + } +} +``` + +此配置仅规范化拉丁字符(Unicode 范围 U+0000 至 U+024F),使其他脚本保持不变。 + +## 相关文档 + +- [ICU 分析器](/analyzers/language-analyzers/icu) +- [ICU 分词器](/analyzers/tokenizers/icu-tokenizer) +- [ICU 折叠词元过滤器](/analyzers/token-filters/icu-folding) diff --git a/i18n/zh/analyzers/character-filters/index.md b/i18n/zh/analyzers/character-filters/index.md new file mode 100644 index 00000000..72f9493e --- /dev/null +++ b/i18n/zh/analyzers/character-filters/index.md @@ -0,0 +1,17 @@ +--- +title: 字符过滤器 +--- + +# 字符过滤器 + +字符过滤器在分词之前处理文本,以准备进一步分析。 + +与对词元(单词或术语)进行操作的词元过滤器不同,字符过滤器在分词之前处理原始输入文本。它们对于清理或转换包含不需要的字符(例如 HTML 标签或特殊符号)的结构化文本特别有用。字符过滤器有助于去除或替换这些元素,以便正确格式化文本以进行分析。 + +字符过滤器的用例包括: + +- **HTML 剥离**:[`html_strip`](/analyzers/character-filters/html-character-filter) 字符过滤器从内容中删除 HTML 标签,以便仅索引纯文本。 +- **模式替换**:[`pattern_replace`](/analyzers/character-filters/pattern-replace-character-filter) 字符过滤器替换或删除文本中不需要的字符或模式,例如,将连字符转换为空格。 +- **自定义映射**:[`mapping`](/analyzers/character-filters/mapping-character-filter) 字符过滤器将特定字符或序列替换为其他值,例如,将货币符号转换为其文本等价物。 +- **ICU 规范化**:[`icu_normalizer`](/analyzers/character-filters/icu-normalization) 字符过滤器在分词之前将文本转换为规范的 Unicode 形式,确保等效字符被一致地处理。需要 `analysis-icu` 插件。 +- **日文迭代标记**:[`kuromoji_iteration_mark`](/analyzers/character-filters/kuromoji-iteration-mark) 字符过滤器将日文迭代标记扩展为它们所代表的字符,在分词之前规范化文本。需要 `analysis-kuromoji` 插件。 diff --git a/i18n/zh/analyzers/character-filters/kuromoji-iteration-mark.md b/i18n/zh/analyzers/character-filters/kuromoji-iteration-mark.md new file mode 100644 index 00000000..b0e1081f --- /dev/null +++ b/i18n/zh/analyzers/character-filters/kuromoji-iteration-mark.md @@ -0,0 +1,115 @@ +--- +title: Kuromoji 迭代标记 +--- + +# Kuromoji 迭代标记字符过滤器 + +`kuromoji_iteration_mark` 字符过滤器通过用每个标记重复的字符替换标记来规范化日文水平迭代标记(odoriji)。日文书写使用迭代标记作为重复字符的简写: + +- 々(汉字迭代标记)-- 不加更改地重复前面的汉字字符,因此 佐々木 变成 佐佐木。 +- ゝ(平假名迭代标记)-- 不加更改地重复前面的平假名字符,因此 かゝ 变成 かか。 +- ゞ(平假名浊音迭代标记)-- 重复前面的平假名字符并应用浊音(浊点)。前面的字符必须是清音,因此 みすゞ 变成 みすず,其中 す 被浊化为 ず。 +- ヽ(片假名迭代标记)-- 不加更改地重复前面的片假名字符,因此 コヽア 变成 ココア。 +- ヾ(片假名浊音迭代标记)-- 重复前面的片假名字符并应用浊音(浊点)。前面的字符必须是清音,因此 カヾ 变成 カガ。 + +在分词之前扩展这些标记可确保生成的词元是一致的,无论原始文本使用迭代标记还是拼写出重复的字符。 + +## 安装 + +`kuromoji_iteration_mark` 字符过滤器需要 `analysis-kuromoji` 插件。有关安装说明,请参阅 [Kuromoji 分析器](/analyzers/language-analyzers/kuromoji)。 + +## 参数 + +下表列出了 `kuromoji_iteration_mark` 字符过滤器的参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`normalize_kanji` | 布尔值 | 当为 `true` 时,规范化汉字迭代标记(々)。默认值为 `true`。 +`normalize_kana` | 布尔值 | 当为 `true` 时,规范化假名迭代标记(ゞ、ヾ、ゝ 和 ヽ)。默认值为 `true`。 + +## 示例 + +以下示例创建一个带有使用 `kuromoji_iteration_mark` 字符过滤器的自定义分析器的索引: + +```json +PUT /iteration-mark-index +{ + "settings": { + "analysis": { + "char_filter": { + "iteration_mark_filter": { + "type": "kuromoji_iteration_mark", + "normalize_kanji": true, + "normalize_kana": true + } + }, + "analyzer": { + "iteration_mark_analyzer": { + "type": "custom", + "char_filter": ["iteration_mark_filter"], + "tokenizer": "kuromoji_tokenizer" + } + } + } + } +} +``` + +使用包含汉字迭代标记的文本测试分析器。名称 佐々木(Sasaki)使用 々 重复前面的汉字 佐: + +```json +POST /iteration-mark-index/_analyze +{ + "analyzer": "iteration_mark_analyzer", + "text": "佐々木さんは元気です" +} +``` + +字符过滤器在分词之前将 佐々木 扩展为 佐佐木: + +```json +{ + "tokens": [ + { + "token": "佐佐木", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "さん", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 1 + }, + { + "token": "は", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "元気", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 3 + }, + { + "token": "です", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 4 + } + ] +} +``` + +## 相关文档 + +- [Kuromoji 分析器](/analyzers/language-analyzers/kuromoji) +- [Kuromoji 分词器](/analyzers/tokenizers/kuromoji) diff --git a/i18n/zh/analyzers/character-filters/mapping-character-filter.md b/i18n/zh/analyzers/character-filters/mapping-character-filter.md new file mode 100644 index 00000000..955db8da --- /dev/null +++ b/i18n/zh/analyzers/character-filters/mapping-character-filter.md @@ -0,0 +1,119 @@ +--- +title: 映射 +--- + +# 映射字符过滤器 + +`mapping` 字符过滤器接受键值对映射用于字符替换。每当过滤器遇到与键匹配的字符串时,它就会将其替换为相应的值。替换值可以是空字符串。 + +过滤器应用贪婪匹配,这意味着匹配最长的匹配模式。 + +`mapping` 字符过滤器在分词之前需要特定文本替换的场景中很有帮助。 + +## 示例 + +以下请求配置一个 `mapping` 字符过滤器,将罗马数字(例如 I、II 或 III)转换为其相应的阿拉伯数字(1、2 和 3): + +```json +GET /_analyze +{ + "tokenizer": "keyword", + "char_filter": [ + { + "type": "mapping", + "mappings": [ + "I => 1", + "II => 2", + "III => 3", + "IV => 4", + "V => 5" + ] + } + ], + "text": "I have III apples and IV oranges" +} +``` + +响应包含一个词元,其中罗马数字已被阿拉伯数字替换: + +```json +{ + "tokens": [ + { + "token": "1 have 3 apples and 4 oranges", + "start_offset": 0, + "end_offset": 32, + "type": "word", + "position": 0 + } + ] +} +``` + +## 参数 + +您可以使用以下任一参数来配置键值映射。 + +| 参数 | 是否必需 | 数据类型 | 描述 | +|:---|:---|:---|:---| +| `mappings` | 可选 | 数组 | 格式为 `key => value` 的键值对数组。在输入文本中找到的每个键都将被其相应的值替换。 | +| `mappings_path` | 可选 | 字符串 | 包含键值映射的 UTF-8 编码文件的路径。每个映射应以 `key => value` 格式出现在新行上。路径可以是绝对路径或相对于 OpenSearch 配置目录的相对路径。 | + +### 使用自定义映射字符过滤器 + +您可以通过定义自己的映射集来创建自定义映射字符过滤器。以下请求创建一个自定义字符过滤器,用于替换文本中的常见缩写: + +```json +PUT /test-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_abbr_analyzer": { + "tokenizer": "standard", + "char_filter": [ + "custom_abbr_filter" + ] + } + }, + "char_filter": { + "custom_abbr_filter": { + "type": "mapping", + "mappings": [ + "BTW => By the way", + "IDK => I don't know", + "FYI => For your information" + ] + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /text-index/_analyze +{ + "tokenizer": "keyword", + "char_filter": [ "custom_abbr_filter" ], + "text": "FYI, updates to the workout schedule are posted. IDK when it takes effect, but we have some details. BTW, the finalized schedule will be released Monday." +} +``` + +响应显示缩写已被替换: + +```json +{ + "tokens": [ + { + "token": "For your information, updates to the workout schedule are posted. I don't know when it takes effect, but we have some details. By the way, the finalized schedule will be released Monday.", + "start_offset": 0, + "end_offset": 153, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/character-filters/pattern-replace-character-filter.md b/i18n/zh/analyzers/character-filters/pattern-replace-character-filter.md new file mode 100644 index 00000000..d71e5d70 --- /dev/null +++ b/i18n/zh/analyzers/character-filters/pattern-replace-character-filter.md @@ -0,0 +1,238 @@ +--- +title: 模式替换 +--- + +# 模式替换字符过滤器 + +`pattern_replace` 字符过滤器允许您使用正则表达式来定义匹配和替换输入文本中字符的模式。对于高级文本转换,特别是在处理复杂字符串模式时,它是一个灵活的工具。 + +此过滤器用指定的替换字符串替换模式的所有实例,从而允许轻松替换、删除或复杂修改输入文本。您可以使用它在分词之前规范化输入。 + +## 示例 + +要标准化电话号码,您将使用正则表达式 `[\\s()-]+`: + +- `[ ]`:定义**字符类**,这意味着它将匹配括号内的**任何一个**字符。 +- `\\s`:匹配任何**空白**字符,例如空格、制表符或换行符。 +- `()`:匹配文字**括号**(`(` 或 `)`)。 +- `-`:匹配文字**连字符**(`-`)。 +- `+`:指定模式应匹配前面字符的**一次或多次**出现。 + +模式 `[\\s()-]+` 将匹配一个或多个空白字符、括号或连字符的任何序列,并将其从输入文本中删除。这确保电话号码被规范化并且只包含数字。 + +以下请求通过删除空格、破折号和括号来标准化电话号码: + +```json +GET /_analyze +{ + "tokenizer": "standard", + "char_filter": [ + { + "type": "pattern_replace", + "pattern": "[\\s()-]+", + "replacement": "" + } + ], + "text": "(555) 123-4567" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "5551234567", + "start_offset": 1, + "end_offset": 14, + "type": "<NUM>", + "position": 0 + } + ] +} +``` + +## 参数 + +`pattern_replace` 字符过滤器支持以下参数。 + +| 参数 | 是否必需 | 数据类型 | 描述 | +|:---|:---|:---|:---| +| `pattern` | 必需 | 字符串 | 用于匹配输入文本部分的正则表达式。过滤器识别并匹配此模式以执行替换。 | +| `replacement` | 可选 | 字符串 | 替换模式匹配的字符串。使用空字符串(`""`)删除匹配的文本。替换可以将 `pattern` 中的捕获组引用为 `$1`、`$2` 等。有关示例,请参阅[使用捕获组](#using-capturing-groups)。默认值为空字符串(`""`)。 | +| `flags` | 可选 | 字符串 | 一个或多个修改 `pattern` 匹配方式的 [Java 正则表达式标志](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#field.summary),例如 `CASE_INSENSITIVE`。要指定多个标志,请用管道字符(`\|`)分隔它们,例如 `"CASE_INSENSITIVE\|COMMENTS"`。 | + +::: danger WARNING +编写不当的正则表达式可能会使分析非常慢,在极端情况下会导致 `StackOverflowError` 停止节点。避免可以以多种方式匹配相同文本的模式,例如嵌套量词如 `(a+)+`,并使用 [Analyze API](/api-reference/analyze-apis) 在代表性文本上测试新模式。 +::: + +::: info NOTE +如果替换更改了文本的长度,搜索结果不受影响,但[高亮显示](/search-plugins/searching-data/highlight)可能不准确。OpenSearch 调整词元的字符偏移量以匹配原始文本,但对于替换旁边的词元,调整可能不精确。例如,如果过滤器从 `Call (555) 123-4567 today` 中删除括号和连字符,对 `555` 的搜索会高亮显示 `(<em>555)</em>`,包括右括号。如果您需要精确的高亮显示,请在您的数据上测试结果。 +::: + +## 创建自定义分析器 + +以下请求创建一个带有配置了 `pattern_replace` 字符过滤器的自定义分析器的索引。该过滤器从数字中删除货币符号和千位分隔符(欧洲 `.` 和美国 `,`): + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "char_filter": [ + "pattern_char_filter" + ] + } + }, + "char_filter": { + "pattern_char_filter": { + "type": "pattern_replace", + "pattern": "[$€,.]", + "replacement": "" + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "Total: $ 1,200.50 and € 1.100,75" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "Total", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "120050", + "start_offset": 9, + "end_offset": 17, + "type": "<NUM>", + "position": 1 + }, + { + "token": "and", + "start_offset": 18, + "end_offset": 21, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "110075", + "start_offset": 24, + "end_offset": 32, + "type": "<NUM>", + "position": 3 + } + ] +} +``` + +## 使用捕获组 + +您可以在 `replacement` 参数中使用捕获组。例如,以下请求创建一个自定义分析器,该分析器使用 `pattern_replace` 字符过滤器将电话号码中的连字符替换为点: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "char_filter": [ + "pattern_char_filter" + ] + } + }, + "char_filter": { + "pattern_char_filter": { + "type": "pattern_replace", + "pattern": "(\\d+)-(?=\\d)", + "replacement": "$1." + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "Call me at 555-123-4567 or 555-987-6543" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "Call", + "start_offset": 0, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "me", + "start_offset": 5, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "at", + "start_offset": 8, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "555.123.4567", + "start_offset": 11, + "end_offset": 23, + "type": "<NUM>", + "position": 3 + }, + { + "token": "or", + "start_offset": 24, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "555.987.6543", + "start_offset": 27, + "end_offset": 39, + "type": "<NUM>", + "position": 5 + } + ] +} +``` diff --git a/i18n/zh/analyzers/custom-analyzer.md b/i18n/zh/analyzers/custom-analyzer.md new file mode 100644 index 00000000..e4bbc4fd --- /dev/null +++ b/i18n/zh/analyzers/custom-analyzer.md @@ -0,0 +1,364 @@ +--- +title: 创建自定义分析器 +--- + +# 创建自定义分析器 + +要创建自定义分析器,请指定以下组件的组合: + +- 字符过滤器(零个或多个) + +- 分词器(一个) + +- 词元过滤器(零个或多个) + +## 配置 + +以下参数可用于配置自定义分析器。 + +| 参数 | 是否必需 | 描述 | +|:--- | :--- | :--- | +| `type` | 可选 | 分析器类型。默认为 `custom`。您也可以使用此参数指定预构建的分析器。 | +| `tokenizer` | 必需 | 要包含在分析器中的分词器。 | +| `char_filter` | 可选 | 要包含在分析器中的字符过滤器列表。 | +| `filter` | 可选 | 要包含在分析器中的词元过滤器列表。 | +| `position_increment_gap` | 可选 | 索引具有多个值的文本字段时在值之间应用的额外间距。有关详细信息,请参阅[位置增量间隙](#position-increment-gap)。默认值为 `100`。 | + +## 示例 + +以下示例演示了各种自定义分析器配置。 + +### 带有 HTML 剥离字符过滤器的自定义分析器 + +以下示例分析器在分词之前从文本中删除 HTML 标签: + +```json +PUT simple_html_strip_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "html_strip_analyzer": { + "type": "custom", + "char_filter": ["html_strip"], + "tokenizer": "whitespace", + "filter": ["lowercase"] + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +GET simple_html_strip_analyzer_index/_analyze +{ + "analyzer": "html_strip_analyzer", + "text": "<p>OpenSearch is <strong>awesome</strong>!</p>" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 3, + "end_offset": 13, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 14, + "end_offset": 16, + "type": "word", + "position": 1 + }, + { + "token": "awesome!", + "start_offset": 25, + "end_offset": 42, + "type": "word", + "position": 2 + } + ] +} +``` + +### 带有映射字符过滤器用于同义词替换的自定义分析器 + +以下示例分析器在应用同义词过滤器之前替换特定字符和模式: + +```json +PUT mapping_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "synonym_mapping_analyzer": { + "type": "custom", + "char_filter": ["underscore_to_space"], + "tokenizer": "standard", + "filter": ["lowercase", "stop", "synonym_filter"] + } + }, + "char_filter": { + "underscore_to_space": { + "type": "mapping", + "mappings": ["_ => ' '"] + } + }, + "filter": { + "synonym_filter": { + "type": "synonym", + "synonyms": [ + "quick, fast, speedy", + "big, large, huge" + ] + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +GET mapping_analyzer_index/_analyze +{ + "analyzer": "synonym_mapping_analyzer", + "text": "The slow_green_turtle is very large" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "slow","start_offset": 4,"end_offset": 8,"type": "<ALPHANUM>","position": 1}, + {"token": "green","start_offset": 9,"end_offset": 14,"type": "<ALPHANUM>","position": 2}, + {"token": "turtle","start_offset": 15,"end_offset": 21,"type": "<ALPHANUM>","position": 3}, + {"token": "very","start_offset": 25,"end_offset": 29,"type": "<ALPHANUM>","position": 5}, + {"token": "large","start_offset": 30,"end_offset": 35,"type": "<ALPHANUM>","position": 6}, + {"token": "big","start_offset": 30,"end_offset": 35,"type": "SYNONYM","position": 6}, + {"token": "huge","start_offset": 30,"end_offset": 35,"type": "SYNONYM","position": 6} + ] +} +``` + +### 带有自定义基于模式的字符过滤器用于数字规范化的自定义分析器 + +以下示例分析器通过删除破折号和空格来规范化电话号码,并对规范化的文本应用边缘 n-gram 以支持部分匹配: + +```json +PUT advanced_pattern_replace_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "phone_number_analyzer": { + "type": "custom", + "char_filter": ["phone_normalization"], + "tokenizer": "standard", + "filter": ["lowercase", "edge_ngram"] + } + }, + "char_filter": { + "phone_normalization": { + "type": "pattern_replace", + "pattern": "[-\\s]", + "replacement": "" + } + }, + "filter": { + "edge_ngram": { + "type": "edge_ngram", + "min_gram": 3, + "max_gram": 10 + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +GET advanced_pattern_replace_analyzer_index/_analyze +{ + "analyzer": "phone_number_analyzer", + "text": "123-456 7890" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "123","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "1234","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "12345","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "123456","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "1234567","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "12345678","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "123456789","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0}, + {"token": "1234567890","start_offset": 0,"end_offset": 12,"type": "<NUM>","position": 0} + ] +} +``` + +## 处理正则表达式模式中的特殊字符 + +在分析器中使用自定义正则表达式模式时,请确保正确处理特殊字符或非英语字符。默认情况下,Java 的正则表达式仅将 `[A-Za-z0-9_]` 视为单词字符(`\w`)。这可能会在使用 `\w` 或 `\b`(匹配单词和非单词字符之间的边界)时导致意外行为。 + +例如,以下分析器尝试使用模式 `(\b\p{L}+\b)` 来匹配被单词边界包围的一个或多个任何语言的字母字符(`\p{L}`): + +```json +PUT /buggy_custom_analyzer +{ + "settings": { + "analysis": { + "filter": { + "capture_words": { + "type": "pattern_capture", + "patterns": [ + "(\\b\\p{L}+\\b)" + ] + } + }, + "analyzer": { + "filter_only_analyzer": { + "type": "custom", + "tokenizer": "keyword", + "filter": [ + "capture_words" + ] + } + } + } + } +} +``` + +然而,该分析器会错误地将 `él-empezó-a-reír` 分词为 `l`、`empez`、`a` 和 `reír`,因为 `\b` 不匹配重音字符与字符串开头或结尾之间的边界。 + +要正确处理特殊字符,请在您的模式中添加 Unicode 大小写标志 `(?U)`: + +```json +PUT /fixed_custom_analyzer +{ + "settings": { + "analysis": { + "filter": { + "capture_words": { + "type": "pattern_capture", + "patterns": [ + "(?U)(\\b\\p{L}+\\b)" + ] + } + }, + "analyzer": { + "filter_only_analyzer": { + "type": "custom", + "tokenizer": "keyword", + "filter": [ + "capture_words" + ] + } + } + } + } +} +``` + +## 位置增量间隙 + +`position_increment_gap` 参数在索引多值字段(如数组)时设置词元之间的位置间隙。此间隙确保短语查询不会匹配跨越不同值的词元,除非明确允许。例如,默认间隙为 100 表示不同数组条目中的词元相距 100 个位置,从而防止短语搜索中的意外匹配。您可以调整此值或将其设置为 `0` 以允许短语跨越数组值。 + +以下示例使用 `match_phrase` 查询演示了 `position_increment_gap` 的效果。 + +1. 在 `test-index` 中索引文档: + + ```json + PUT test-index/_doc/1 + { + "names": [ "Slow green", "turtle swims"] + } + ``` + +1. 使用 `match_phrase` 查询查询文档: + + ```json + GET test-index/_search + { + "query": { + "match_phrase": { + "names": { + "query": "green turtle" + } + } + } + } + ``` + + 响应不返回任何命中,因为词元 `green` 和 `turtle` 之间的距离为 `100`(默认 `position_increment_gap`)。 + +1. 现在使用 `match_phrase` 查询和高于 `position_increment_gap` 的 `slop` 参数查询文档: + + ```json + GET test-index/_search + { + "query": { + "match_phrase": { + "names": { + "query": "green turtle", + "slop": 101 + } + } + } + } + ``` + + 响应包含匹配的文档: + + ```json + { + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.010358453, + "hits": [ + { + "_index": "test-index", + "_id": "1", + "_score": 0.010358453, + "_source": { + "names": [ + "Slow green", + "turtle swims" + ] + } + } + ] + } + } + ``` diff --git a/i18n/zh/analyzers/language-analyzers/arabic.md b/i18n/zh/analyzers/language-analyzers/arabic.md new file mode 100644 index 00000000..5029bdef --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/arabic.md @@ -0,0 +1,174 @@ +--- +title: 阿拉伯语 +--- + +# 阿拉伯语分析器 + +可以使用以下命令将内置的 `arabic` 分析器应用于文本字段: + +```json +PUT /arabic-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "arabic" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_arabic +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_arabic_analyzer":{ + "type":"arabic", + "stem_exclusion":["تكنولوجيا","سلطة "] + } + } + } + } +} +``` + +## 阿拉伯语分析器内部组件 + +`arabic` 分析器使用以下组件构建: + +- 分词器:`standard` + +- 词元过滤器: + - lowercase + - decimal_digit + - stop (Arabic) + - normalization (Arabic) + - keyword + - stemmer (Arabic) + +## 自定义阿拉伯语分析器 + +您可以使用以下命令创建自定义阿拉伯语分析器: + +```json +PUT /arabic-index +{ + "settings": { + "analysis": { + "filter": { + "arabic_stop": { + "type": "stop", + "stopwords": "_arabic_" + }, + "arabic_stemmer": { + "type": "stemmer", + "language": "arabic" + }, + "arabic_normalization": { + "type": "arabic_normalization" + }, + "decimal_digit": { + "type": "decimal_digit" + }, + "arabic_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "arabic_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "decimal_digit", + "arabic_stop", + "arabic_normalization", + "arabic_keywords", + "arabic_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "arabic_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /arabic-index/_analyze +{ + "field": "content", + "text": "الطلاب يدرسون في الجامعات العربية. أرقامهم ١٢٣٤٥٦." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "طلاب", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "يدرس", + "start_offset": 7, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "جامع", + "start_offset": 17, + "end_offset": 25, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "عرب", + "start_offset": 26, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "ارقامهم", + "start_offset": 35, + "end_offset": 42, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "123456", + "start_offset": 43, + "end_offset": 49, + "type": "<NUM>", + "position": 6 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/armenian.md b/i18n/zh/analyzers/language-analyzers/armenian.md new file mode 100644 index 00000000..6ed9f730 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/armenian.md @@ -0,0 +1,129 @@ +--- +title: 亚美尼亚语 +--- + +# 亚美尼亚语分析器 + +可以使用以下命令将内置的 `armenian` 分析器应用于文本字段: + +```json +PUT /arabic-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "armenian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_armenian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_armenian_analyzer": { + "type": "armenian", + "stem_exclusion": ["բարև", "խաղաղություն"] + } + } + } + } +} +``` + +## 亚美尼亚语分析器 internals + +`armenian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Armenian) + - keyword + - stemmer (Armenian) + +## 自定义亚美尼亚语分析器 + +您可以使用以下命令创建自定义亚美尼亚语分析器: + +```json +PUT /armenian-index +{ + "settings": { + "analysis": { + "filter": { + "armenian_stop": { + "type": "stop", + "stopwords": "_armenian_" + }, + "armenian_stemmer": { + "type": "stemmer", + "language": "armenian" + }, + "armenian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "armenian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "armenian_stop", + "armenian_keywords", + "armenian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "armenian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET armenian-index/_analyze +{ + "analyzer": "stem_exclusion_armenian_analyzer", + "text": "բարև բոլորին, մենք խաղաղություն ենք ուզում և նոր օր ենք սկսել" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "բարև","start_offset": 0,"end_offset": 4,"type": "<ALPHANUM>","position": 0}, + {"token": "բոլոր","start_offset": 5,"end_offset": 12,"type": "<ALPHANUM>","position": 1}, + {"token": "խաղաղություն","start_offset": 19,"end_offset": 31,"type": "<ALPHANUM>","position": 3}, + {"token": "ուզ","start_offset": 36,"end_offset": 42,"type": "<ALPHANUM>","position": 5}, + {"token": "նոր","start_offset": 45,"end_offset": 48,"type": "<ALPHANUM>","position": 7}, + {"token": "օր","start_offset": 49,"end_offset": 51,"type": "<ALPHANUM>","position": 8}, + {"token": "սկսել","start_offset": 56,"end_offset": 61,"type": "<ALPHANUM>","position": 10} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/basque.md b/i18n/zh/analyzers/language-analyzers/basque.md new file mode 100644 index 00000000..b63749a8 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/basque.md @@ -0,0 +1,129 @@ +--- +title: 巴斯克语 +--- + +# 巴斯克语分析器 + +可以使用以下命令将内置的 `basque` 分析器应用于文本字段: + +```json +PUT /basque-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "basque" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_basque_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_basque_analyzer": { + "type": "basque", + "stem_exclusion": ["autoritate", "baldintza"] + } + } + } + } +} +``` + +## 巴斯克语分析器 internals + +`basque` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Basque) + - keyword + - stemmer (Basque) + +## 自定义巴斯克语分析器 + +您可以使用以下命令创建自定义巴斯克语分析器: + +```json +PUT /basque-index +{ + "settings": { + "analysis": { + "filter": { + "basque_stop": { + "type": "stop", + "stopwords": "_basque_" + }, + "basque_stemmer": { + "type": "stemmer", + "language": "basque" + }, + "basque_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "basque_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "basque_stop", + "basque_keywords", + "basque_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "basque_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /basque-index/_analyze +{ + "field": "content", + "text": "Ikasleek euskal unibertsitateetan ikasten dute. Haien zenbakiak 123456 dira." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "ikasle","start_offset": 0,"end_offset": 8,"type": "<ALPHANUM>","position": 0}, + {"token": "euskal","start_offset": 9,"end_offset": 15,"type": "<ALPHANUM>","position": 1}, + {"token": "unibertsi","start_offset": 16,"end_offset": 33,"type": "<ALPHANUM>","position": 2}, + {"token": "ikas","start_offset": 34,"end_offset": 41,"type": "<ALPHANUM>","position": 3}, + {"token": "haien","start_offset": 48,"end_offset": 53,"type": "<ALPHANUM>","position": 5}, + {"token": "zenba","start_offset": 54,"end_offset": 63,"type": "<ALPHANUM>","position": 6}, + {"token": "123456","start_offset": 64,"end_offset": 70,"type": "<NUM>","position": 7} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/bengali.md b/i18n/zh/analyzers/language-analyzers/bengali.md new file mode 100644 index 00000000..222b690a --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/bengali.md @@ -0,0 +1,134 @@ +--- +title: 孟加拉语 +--- + +# 孟加拉语分析器 + +可以使用以下命令将内置的 `bengali` 分析器应用于文本字段: + +```json +PUT /bengali-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bengali" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_bengali_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_bengali_analyzer": { + "type": "bengali", + "stem_exclusion": ["কর্তৃপক্ষ", "অনুমোদন"] + } + } + } + } +} +``` + +## 孟加拉语分析器 internals + +`bengali` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - decimal_digit + - indic_normalization + - normalization (Bengali) + - stop (Bengali) + - keyword + - stemmer (Bengali) + +## 自定义孟加拉语分析器 + +您可以使用以下命令创建自定义孟加拉语分析器: + +```json +PUT /bengali-index +{ + "settings": { + "analysis": { + "filter": { + "bengali_stop": { + "type": "stop", + "stopwords": "_bengali_" + }, + "bengali_stemmer": { + "type": "stemmer", + "language": "bengali" + }, + "bengali_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "bengali_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "decimal_digit", + "bengali_keywords", + "indic_normalization", + "bengali_normalization", + "bengali_stop", + "bengali_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bengali_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /bengali-index/_analyze +{ + "field": "content", + "text": "ছাত্ররা বিশ্ববিদ্যালয়ে পড়াশোনা করে। তাদের নম্বরগুলি ১২৩৪৫৬।" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "ছাত্র","start_offset": 0,"end_offset": 7,"type": "<ALPHANUM>","position": 0}, + {"token": "বিসসবিদালয়","start_offset": 8,"end_offset": 23,"type": "<ALPHANUM>","position": 1}, + {"token": "পরাসোন","start_offset": 24,"end_offset": 32,"type": "<ALPHANUM>","position": 2}, + {"token": "তা","start_offset": 38,"end_offset": 43,"type": "<ALPHANUM>","position": 4}, + {"token": "নমমর","start_offset": 44,"end_offset": 53,"type": "<ALPHANUM>","position": 5}, + {"token": "123456","start_offset": 54,"end_offset": 60,"type": "<NUM>","position": 6} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/brazilian.md b/i18n/zh/analyzers/language-analyzers/brazilian.md new file mode 100644 index 00000000..caafde1f --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/brazilian.md @@ -0,0 +1,129 @@ +--- +title: 巴西葡萄牙语 +--- + +# 巴西葡萄牙语分析器 + +可以使用以下命令将内置的 `brazilian` 分析器应用于文本字段: + +```json +PUT /brazilian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "brazilian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_brazilian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_brazilian_analyzer": { + "type": "brazilian", + "stem_exclusion": ["autoridade", "aprovação"] + } + } + } + } +} +``` + +## 巴西葡萄牙语分析器 internals + +`brazilian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Brazilian) + - keyword + - stemmer (Brazilian) + +## 自定义巴西葡萄牙语分析器 + +您可以使用以下命令创建自定义巴西葡萄牙语分析器: + +```json +PUT /brazilian-index +{ + "settings": { + "analysis": { + "filter": { + "brazilian_stop": { + "type": "stop", + "stopwords": "_brazilian_" + }, + "brazilian_stemmer": { + "type": "stemmer", + "language": "brazilian" + }, + "brazilian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "brazilian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "brazilian_stop", + "brazilian_keywords", + "brazilian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "brazilian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /brazilian-index/_analyze +{ + "field": "content", + "text": "Estudantes estudam em universidades brasileiras. Seus números são 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "estudant","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0}, + {"token": "estud","start_offset": 11,"end_offset": 18,"type": "<ALPHANUM>","position": 1}, + {"token": "univers","start_offset": 22,"end_offset": 35,"type": "<ALPHANUM>","position": 3}, + {"token": "brasileir","start_offset": 36,"end_offset": 47,"type": "<ALPHANUM>","position": 4}, + {"token": "numer","start_offset": 54,"end_offset": 61,"type": "<ALPHANUM>","position": 6}, + {"token": "sao","start_offset": 62,"end_offset": 65,"type": "<ALPHANUM>","position": 7}, + {"token": "123456","start_offset": 66,"end_offset": 72,"type": "<NUM>","position": 8} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/bulgarian.md b/i18n/zh/analyzers/language-analyzers/bulgarian.md new file mode 100644 index 00000000..eb83a1b7 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/bulgarian.md @@ -0,0 +1,129 @@ +--- +title: 保加利亚语 +--- + +# 保加利亚语分析器 + +可以使用以下命令将内置的 `bulgarian` 分析器应用于文本字段: + +```json +PUT /bulgarian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bulgarian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_bulgarian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_bulgarian_analyzer": { + "type": "bulgarian", + "stem_exclusion": ["авторитет", "одобрение"] + } + } + } + } +} +``` + +## 保加利亚语分析器 internals + +`bulgarian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Bulgarian) + - keyword + - stemmer (Bulgarian) + +## 自定义保加利亚语分析器 + +您可以使用以下命令创建自定义保加利亚语分析器: + +```json +PUT /bulgarian-index +{ + "settings": { + "analysis": { + "filter": { + "bulgarian_stop": { + "type": "stop", + "stopwords": "_bulgarian_" + }, + "bulgarian_stemmer": { + "type": "stemmer", + "language": "bulgarian" + }, + "bulgarian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "bulgarian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "bulgarian_stop", + "bulgarian_keywords", + "bulgarian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "bulgarian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /bulgarian-index/_analyze +{ + "field": "content", + "text": "Студентите учат в българските университети. Техните номера са 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "студент","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0}, + {"token": "учат","start_offset": 11,"end_offset": 15,"type": "<ALPHANUM>","position": 1}, + {"token": "българск","start_offset": 18,"end_offset": 29,"type": "<ALPHANUM>","position": 3}, + {"token": "университят","start_offset": 30,"end_offset": 42,"type": "<ALPHANUM>","position": 4}, + {"token": "техн","start_offset": 44,"end_offset": 51,"type": "<ALPHANUM>","position": 5}, + {"token": "номер","start_offset": 52,"end_offset": 58,"type": "<ALPHANUM>","position": 6}, + {"token": "123456","start_offset": 62,"end_offset": 68,"type": "<NUM>","position": 8} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/catalan.md b/i18n/zh/analyzers/language-analyzers/catalan.md new file mode 100644 index 00000000..ac49a32f --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/catalan.md @@ -0,0 +1,135 @@ +--- +title: 加泰罗尼亚语 +--- + +# 加泰罗尼亚语分析器 + +可以使用以下命令将内置的 `catalan` 分析器应用于文本字段: + +```json +PUT /catalan-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "catalan" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_catalan_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_catalan_analyzer": { + "type": "catalan", + "stem_exclusion": ["autoritat", "aprovació"] + } + } + } + } +} +``` + +## 加泰罗尼亚语分析器 internals + +`catalan` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - elision (Catalan) + - lowercase + - stop (Catalan) + - keyword + - stemmer (Catalan) + +## 自定义加泰罗尼亚语分析器 + +您可以使用以下命令创建自定义加泰罗尼亚语分析器: + +```json +PUT /catalan-index +{ + "settings": { + "analysis": { + "filter": { + "catalan_stop": { + "type": "stop", + "stopwords": "_catalan_" + }, + "catalan_elision": { + "type": "elision", + "articles": [ "d", "l", "m", "n", "s", "t"], + "articles_case": true + }, + "catalan_stemmer": { + "type": "stemmer", + "language": "catalan" + }, + "catalan_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "catalan_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "catalan_elision", + "lowercase", + "catalan_stop", + "catalan_keywords", + "catalan_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "catalan_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /catalan-index/_analyze +{ + "field": "content", + "text": "Els estudiants estudien a les universitats catalanes. Els seus números són 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "estud","start_offset": 4,"end_offset": 14,"type": "<ALPHANUM>","position": 1}, + {"token": "estud","start_offset": 15,"end_offset": 23,"type": "<ALPHANUM>","position": 2}, + {"token": "univer","start_offset": 30,"end_offset": 42,"type": "<ALPHANUM>","position": 5}, + {"token": "catalan","start_offset": 43,"end_offset": 52,"type": "<ALPHANUM>","position": 6}, + {"token": "numer","start_offset": 63,"end_offset": 70,"type": "<ALPHANUM>","position": 9}, + {"token": "123456","start_offset": 75,"end_offset": 81,"type": "<NUM>","position": 11} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/cjk.md b/i18n/zh/analyzers/language-analyzers/cjk.md new file mode 100644 index 00000000..c1f7a7f1 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/cjk.md @@ -0,0 +1,144 @@ +--- +title: 中日韩 +--- + +# CJK 分析器 + +内置的 `cjk` 分析器专为中文、日文和韩文(CJK)文本设计。它使用二元分词将 CJK 文本分解为重叠的双字符序列,这对于不使用空格分隔单词的语言非常有效。 + +::: info NOTE +您可能会发现 ICU 分析插件中的 `icu_analyzer` 对于 CJK 文本比 `cjk` 分析器效果更好。请使用您的文本和查询进行实验。 +::: + +可以使用以下命令将 `cjk` 分析器应用于文本字段: + +```json +PUT /cjk-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "cjk" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_cjk_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_cjk_analyzer": { + "type": "cjk", + "stem_exclusion": ["example", "words"] + } + } + } + } +} +``` + +## CJK 分析器内部组件 + +`cjk` 分析器使用以下组件构建: + +- 分词器:`standard` + +- 词元过滤器: + - cjk_width + - lowercase + - cjk_bigram + - stop(类似于英语) + +## 自定义 CJK 分析器 + +您可以使用以下命令创建自定义 CJK 分析器: + +```json +PUT /cjk-index +{ + "settings": { + "analysis": { + "filter": { + "english_stop": { + "type": "stop", + "stopwords": [ + "a", "and", "are", "as", "at", "be", "but", "by", "for", + "if", "in", "into", "is", "it", "no", "not", "of", "on", + "or", "s", "such", "t", "that", "the", "their", "then", + "there", "these", "they", "this", "to", "was", "will", + "with", "www" + ] + } + }, + "analyzer": { + "cjk_custom_analyzer": { + "tokenizer": "standard", + "filter": [ + "cjk_width", + "lowercase", + "cjk_bigram", + "english_stop" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "cjk_custom_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /cjk-index/_analyze +{ + "field": "content", + "text": "学生们在中国、日本和韩国的大学学习。123456" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "学生","start_offset": 0,"end_offset": 2,"type": "<DOUBLE>","position": 0}, + {"token": "生们","start_offset": 1,"end_offset": 3,"type": "<DOUBLE>","position": 1}, + {"token": "们在","start_offset": 2,"end_offset": 4,"type": "<DOUBLE>","position": 2}, + {"token": "在中","start_offset": 3,"end_offset": 5,"type": "<DOUBLE>","position": 3}, + {"token": "中国","start_offset": 4,"end_offset": 6,"type": "<DOUBLE>","position": 4}, + {"token": "日本","start_offset": 7,"end_offset": 9,"type": "<DOUBLE>","position": 5}, + {"token": "本和","start_offset": 8,"end_offset": 10,"type": "<DOUBLE>","position": 6}, + {"token": "和韩","start_offset": 9,"end_offset": 11,"type": "<DOUBLE>","position": 7}, + {"token": "韩国","start_offset": 10,"end_offset": 12,"type": "<DOUBLE>","position": 8}, + {"token": "国的","start_offset": 11,"end_offset": 13,"type": "<DOUBLE>","position": 9}, + {"token": "的大","start_offset": 12,"end_offset": 14,"type": "<DOUBLE>","position": 10}, + {"token": "大学","start_offset": 13,"end_offset": 15,"type": "<DOUBLE>","position": 11}, + {"token": "学学","start_offset": 14,"end_offset": 16,"type": "<DOUBLE>","position": 12}, + {"token": "学习","start_offset": 15,"end_offset": 17,"type": "<DOUBLE>","position": 13}, + {"token": "123456","start_offset": 18,"end_offset": 24,"type": "<NUM>","position": 14} + ] +} +``` + +## 相关文档 + +- [ICU 分析器](/analyzers/language-analyzers/icu) -- CJK 文本的替代方案 diff --git a/i18n/zh/analyzers/language-analyzers/czech.md b/i18n/zh/analyzers/language-analyzers/czech.md new file mode 100644 index 00000000..e9dd89f7 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/czech.md @@ -0,0 +1,164 @@ +--- +title: 捷克语 +--- + +# 捷克语分析器 + +可以使用以下命令将内置的 `czech` 分析器应用于文本字段: + +```json +PUT /czech-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "czech" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_czech_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_czech_analyzer": { + "type": "czech", + "stem_exclusion": ["autorita", "schválení"] + } + } + } + } +} +``` + +## 捷克语分析器 internals + +`czech` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Czech) + - keyword + - stemmer (Czech) + +## 自定义捷克语分析器 + +您可以使用以下命令创建自定义捷克语分析器: + +```json +PUT /czech-index +{ + "settings": { + "analysis": { + "filter": { + "czech_stop": { + "type": "stop", + "stopwords": "_czech_" + }, + "czech_stemmer": { + "type": "stemmer", + "language": "czech" + }, + "czech_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "czech_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "czech_stop", + "czech_keywords", + "czech_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "czech_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /czech-index/_analyze +{ + "field": "content", + "text": "Studenti studují na českých univerzitách. Jejich čísla jsou 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "studuj", + "start_offset": 9, + "end_offset": 16, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "česk", + "start_offset": 20, + "end_offset": 27, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "univerzit", + "start_offset": 28, + "end_offset": 40, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "čísl", + "start_offset": 49, + "end_offset": 54, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "123456", + "start_offset": 60, + "end_offset": 66, + "type": "<NUM>", + "position": 8 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/danish.md b/i18n/zh/analyzers/language-analyzers/danish.md new file mode 100644 index 00000000..6c859ea8 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/danish.md @@ -0,0 +1,164 @@ +--- +title: 丹麦语 +--- + +# 丹麦语分析器 + +可以使用以下命令将内置的 `danish` 分析器应用于文本字段: + +```json +PUT /danish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "danish" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_danish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_danish_analyzer": { + "type": "danish", + "stem_exclusion": ["autoritet", "godkendelse"] + } + } + } + } +} +``` + +## 丹麦语分析器 internals + +`danish` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Danish) + - keyword + - stemmer (Danish) + +## 自定义丹麦语分析器 + +您可以使用以下命令创建自定义丹麦语分析器: + +```json +PUT /danish-index +{ + "settings": { + "analysis": { + "filter": { + "danish_stop": { + "type": "stop", + "stopwords": "_danish_" + }, + "danish_stemmer": { + "type": "stemmer", + "language": "danish" + }, + "danish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "danish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "danish_stop", + "danish_keywords", + "danish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "danish_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /danish-index/_analyze +{ + "field": "content", + "text": "Studerende studerer på de danske universiteter. Deres numre er 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "stud", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "stud", + "start_offset": 11, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "dansk", + "start_offset": 26, + "end_offset": 32, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "universitet", + "start_offset": 33, + "end_offset": 46, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "numr", + "start_offset": 54, + "end_offset": 59, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "123456", + "start_offset": 63, + "end_offset": 69, + "type": "<NUM>", + "position": 9 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/dutch.md b/i18n/zh/analyzers/language-analyzers/dutch.md new file mode 100644 index 00000000..2e9d37b0 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/dutch.md @@ -0,0 +1,140 @@ +--- +title: 荷兰语 +--- + +# 荷兰语分析器 + +可以使用以下命令将内置的 `dutch` 分析器应用于文本字段: + +```json +PUT /dutch-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "dutch" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_dutch_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_dutch_analyzer": { + "type": "dutch", + "stem_exclusion": ["autoriteit", "goedkeuring"] + } + } + } + } +} +``` + +## 荷兰语分析器 internals + +`dutch` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Dutch) + - keyword + - stemmer_override + - stemmer (Dutch) + +## 自定义荷兰语分析器 + +您可以使用以下命令创建自定义荷兰语分析器: + +```json +PUT /dutch-index +{ + "settings": { + "analysis": { + "filter": { + "dutch_stop": { + "type": "stop", + "stopwords": "_dutch_" + }, + "dutch_stemmer": { + "type": "stemmer", + "language": "dutch" + }, + "dutch_keywords": { + "type": "keyword_marker", + "keywords": [] + }, + "dutch_override": { + "type": "stemmer_override", + "rules": [ + "fiets=>fiets", + "bromfiets=>bromfiets", + "ei=>eier", + "kind=>kinder" + ] + } + }, + "analyzer": { + "dutch_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "dutch_stop", + "dutch_keywords", + "dutch_override", + "dutch_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "dutch_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /dutch-index/_analyze +{ + "field": "content", + "text": "De studenten studeren in Nederland en bezoeken Amsterdam. Hun nummers zijn 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 3,"end_offset": 12,"type": "<ALPHANUM>","position": 1}, + {"token": "studer","start_offset": 13,"end_offset": 21,"type": "<ALPHANUM>","position": 2}, + {"token": "nederland","start_offset": 25,"end_offset": 34,"type": "<ALPHANUM>","position": 4}, + {"token": "bezoek","start_offset": 38,"end_offset": 46,"type": "<ALPHANUM>","position": 6}, + {"token": "amsterdam","start_offset": 47,"end_offset": 56,"type": "<ALPHANUM>","position": 7}, + {"token": "nummer","start_offset": 62,"end_offset": 69,"type": "<ALPHANUM>","position": 9}, + {"token": "123456","start_offset": 75,"end_offset": 81,"type": "<NUM>","position": 11} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/english.md b/i18n/zh/analyzers/language-analyzers/english.md new file mode 100644 index 00000000..32414d29 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/english.md @@ -0,0 +1,135 @@ +--- +title: 英语 +--- + +# 英语分析器 + +可以使用以下命令将内置的 `english` 分析器应用于文本字段: + +```json +PUT /english-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "english" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_english_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_english_analyzer": { + "type": "english", + "stem_exclusion": ["authority", "authorization"] + } + } + } + } +} +``` + +## 英语分析器内部组件 + +`english` 分析器使用以下组件构建: + +- 分词器:`standard` + +- 词元过滤器: + - stemmer (possessive_english) + - lowercase + - stop (English) + - keyword + - stemmer (English) + +## 自定义英语分析器 + +您可以使用以下命令创建自定义英语分析器: + +```json +PUT /english-index +{ + "settings": { + "analysis": { + "filter": { + "english_stop": { + "type": "stop", + "stopwords": "_english_" + }, + "english_stemmer": { + "type": "stemmer", + "language": "english" + }, + "english_keywords": { + "type": "keyword_marker", + "keywords": [] + }, + "english_possessive_stemmer": { + "type": "stemmer", + "language": "possessive_english" + } + }, + "analyzer": { + "english_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "english_possessive_stemmer", + "lowercase", + "english_stop", + "english_keywords", + "english_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "english_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /english-index/_analyze +{ + "field": "content", + "text": "The students study in the USA and work at NASA. Their numbers are 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 4,"end_offset": 12,"type": "<ALPHANUM>","position": 1}, + {"token": "studi","start_offset": 13,"end_offset": 18,"type": "<ALPHANUM>","position": 2}, + {"token": "usa","start_offset": 26,"end_offset": 29,"type": "<ALPHANUM>","position": 5}, + {"token": "work","start_offset": 34,"end_offset": 38,"type": "<ALPHANUM>","position": 7}, + {"token": "nasa","start_offset": 42,"end_offset": 46,"type": "<ALPHANUM>","position": 9}, + {"token": "number","start_offset": 54,"end_offset": 61,"type": "<ALPHANUM>","position": 11}, + {"token": "123456","start_offset": 66,"end_offset": 72,"type": "<NUM>","position": 13} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/estonian.md b/i18n/zh/analyzers/language-analyzers/estonian.md new file mode 100644 index 00000000..1ac12e99 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/estonian.md @@ -0,0 +1,131 @@ +--- +title: 爱沙尼亚语 +--- + +# 爱沙尼亚语分析器 + +可以使用以下命令将内置的 `estonian` 分析器应用于文本字段: + +```json +PUT /estonian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "estonian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_estonian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_estonian_analyzer": { + "type": "estonian", + "stem_exclusion": ["autoriteet", "kinnitus"] + } + } + } + } +} +``` + +## 爱沙尼亚语分析器 internals + +`estonian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Estonian) + - keyword + - stemmer (Estonian) + +## 自定义爱沙尼亚语分析器 + +您可以使用以下命令创建自定义爱沙尼亚语分析器: + +```json +PUT /estonian-index +{ + "settings": { + "analysis": { + "filter": { + "estonian_stop": { + "type": "stop", + "stopwords": "_estonian_" + }, + "estonian_stemmer": { + "type": "stemmer", + "language": "estonian" + }, + "estonian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "estonian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "estonian_stop", + "estonian_keywords", + "estonian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "estonian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /estonian-index/_analyze +{ + "field": "content", + "text": "Õpilased õpivad Tallinnas ja Eesti ülikoolides. Nende numbrid on 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "õpilase","start_offset": 0,"end_offset": 8,"type": "<ALPHANUM>","position": 0}, + {"token": "õpi","start_offset": 9,"end_offset": 15,"type": "<ALPHANUM>","position": 1}, + {"token": "tallinna","start_offset": 16,"end_offset": 25,"type": "<ALPHANUM>","position": 2}, + {"token": "eesti","start_offset": 29,"end_offset": 34,"type": "<ALPHANUM>","position": 4}, + {"token": "ülikooli","start_offset": 35,"end_offset": 46,"type": "<ALPHANUM>","position": 5}, + {"token": "nende","start_offset": 48,"end_offset": 53,"type": "<ALPHANUM>","position": 6}, + {"token": "numbri","start_offset": 54,"end_offset": 61,"type": "<ALPHANUM>","position": 7}, + {"token": "on","start_offset": 62,"end_offset": 64,"type": "<ALPHANUM>","position": 8}, + {"token": "123456","start_offset": 65,"end_offset": 71,"type": "<NUM>","position": 9} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/finnish.md b/i18n/zh/analyzers/language-analyzers/finnish.md new file mode 100644 index 00000000..ea3a8620 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/finnish.md @@ -0,0 +1,129 @@ +--- +title: 芬兰语 +--- + +# 芬兰语分析器 + +可以使用以下命令将内置的 `finnish` 分析器应用于文本字段: + +```json +PUT /finnish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "finnish" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_finnish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_finnish_analyzer": { + "type": "finnish", + "stem_exclusion": ["valta", "hyväksyntä"] + } + } + } + } +} +``` + +## 芬兰语分析器 internals + +`finnish` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Finnish) + - keyword + - stemmer (Finnish) + +## 自定义芬兰语分析器 + +您可以使用以下命令创建自定义芬兰语分析器: + +```json +PUT /finnish-index +{ + "settings": { + "analysis": { + "filter": { + "finnish_stop": { + "type": "stop", + "stopwords": "_finnish_" + }, + "finnish_stemmer": { + "type": "stemmer", + "language": "finnish" + }, + "finnish_keywords": { + "type": "keyword_marker", + "keywords": ["Helsinki", "Suomi"] + } + }, + "analyzer": { + "finnish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "finnish_stop", + "finnish_keywords", + "finnish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "finnish_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /finnish-index/_analyze +{ + "field": "content", + "text": "Opiskelijat opiskelevat Helsingissä ja Suomen yliopistoissa. Heidän numeronsa ovat 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "opiskelij","start_offset": 0,"end_offset": 11,"type": "<ALPHANUM>","position": 0}, + {"token": "opiskelev","start_offset": 12,"end_offset": 23,"type": "<ALPHANUM>","position": 1}, + {"token": "helsing","start_offset": 24,"end_offset": 35,"type": "<ALPHANUM>","position": 2}, + {"token": "suome","start_offset": 39,"end_offset": 45,"type": "<ALPHANUM>","position": 4}, + {"token": "yliopisto","start_offset": 46,"end_offset": 59,"type": "<ALPHANUM>","position": 5}, + {"token": "numero","start_offset": 68,"end_offset": 77,"type": "<ALPHANUM>","position": 7}, + {"token": "123456","start_offset": 83,"end_offset": 89,"type": "<NUM>","position": 9} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/french.md b/i18n/zh/analyzers/language-analyzers/french.md new file mode 100644 index 00000000..cdc4db44 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/french.md @@ -0,0 +1,140 @@ +--- +title: 法语 +--- + +# 法语分析器 + +可以使用以下命令将内置的 `french` 分析器应用于文本字段: + +```json +PUT /french-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "french" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_french_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_french_analyzer": { + "type": "french", + "stem_exclusion": ["autorité", "acceptation"] + } + } + } + } +} +``` + +## 法语分析器 internals + +`french` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - elision (French) + - lowercase + - stop (French) + - keyword + - stemmer (French) + +## 自定义法语分析器 + +您可以使用以下命令创建自定义法语分析器: + +```json +PUT /french-index +{ + "settings": { + "analysis": { + "filter": { + "french_stop": { + "type": "stop", + "stopwords": "_french_" + }, + "french_elision": { + "type": "elision", + "articles_case": true, + "articles": [ + "l", "m", "t", "qu", "n", "s", + "j", "d", "c", "jusqu", "quoiqu", + "lorsqu", "puisqu" + ] + }, + "french_stemmer": { + "type": "stemmer", + "language": "light_french" + }, + "french_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "french_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "french_elision", + "lowercase", + "french_stop", + "french_keywords", + "french_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "french_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /french-index/_analyze +{ + "field": "content", + "text": "Les étudiants étudient à Paris et dans les universités françaises. Leurs numéros sont 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "etudiant","start_offset": 4,"end_offset": 13,"type": "<ALPHANUM>","position": 1}, + {"token": "etudient","start_offset": 14,"end_offset": 22,"type": "<ALPHANUM>","position": 2}, + {"token": "pari","start_offset": 25,"end_offset": 30,"type": "<ALPHANUM>","position": 4}, + {"token": "universit","start_offset": 43,"end_offset": 54,"type": "<ALPHANUM>","position": 8}, + {"token": "francais","start_offset": 55,"end_offset": 65,"type": "<ALPHANUM>","position": 9}, + {"token": "numero","start_offset": 73,"end_offset": 80,"type": "<ALPHANUM>","position": 11}, + {"token": "123456","start_offset": 86,"end_offset": 92,"type": "<NUM>","position": 13} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/galician.md b/i18n/zh/analyzers/language-analyzers/galician.md new file mode 100644 index 00000000..d30b06ea --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/galician.md @@ -0,0 +1,130 @@ +--- +title: 加利西亚语 +--- + +# 加利西亚语分析器 + +可以使用以下命令将内置的 `galician` 分析器应用于文本字段: + +```json +PUT /galician-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "galician" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_galician_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_galician_analyzer": { + "type": "galician", + "stem_exclusion": ["autoridade", "aceptación"] + } + } + } + } +} +``` + +## 加利西亚语分析器 internals + +`galician` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Galician) + - keyword + - stemmer (Galician) + +## 自定义加利西亚语分析器 + +您可以使用以下命令创建自定义加利西亚语分析器: + +```json +PUT /galician-index +{ + "settings": { + "analysis": { + "filter": { + "galician_stop": { + "type": "stop", + "stopwords": "_galician_" + }, + "galician_stemmer": { + "type": "stemmer", + "language": "galician" + }, + "galician_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "galician_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "galician_stop", + "galician_keywords", + "galician_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "galician_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /galician-index/_analyze +{ + "field": "content", + "text": "Os estudantes estudan en Santiago e nas universidades galegas. Os seus números son 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "estud","start_offset": 3,"end_offset": 13,"type": "<ALPHANUM>","position": 1}, + {"token": "estud","start_offset": 14,"end_offset": 21,"type": "<ALPHANUM>","position": 2}, + {"token": "santiag","start_offset": 25,"end_offset": 33,"type": "<ALPHANUM>","position": 4}, + {"token": "univers","start_offset": 40,"end_offset": 53,"type": "<ALPHANUM>","position": 7}, + {"token": "galeg","start_offset": 54,"end_offset": 61,"type": "<ALPHANUM>","position": 8}, + {"token": "numer","start_offset": 71,"end_offset": 78,"type": "<ALPHANUM>","position": 11}, + {"token": "son","start_offset": 79,"end_offset": 82,"type": "<ALPHANUM>","position": 12}, + {"token": "123456","start_offset": 83,"end_offset": 89,"type": "<NUM>","position": 13} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/german.md b/i18n/zh/analyzers/language-analyzers/german.md new file mode 100644 index 00000000..b2f3f362 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/german.md @@ -0,0 +1,166 @@ +--- +title: 德语 +--- + +# 德语分析器 + +可以使用以下命令将内置的 `german` 分析器应用于文本字段: + +```json +PUT /german-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "german" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_german_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_german_analyzer": { + "type": "german", + "stem_exclusion": ["Autorität", "Genehmigung"] + } + } + } + } +} +``` + +## 德语分析器 internals + +`german` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (German) + - keyword + - normalization (German) + - stemmer (German) + +## 自定义德语分析器 + +您可以使用以下命令创建自定义德语分析器: + +```json +PUT /german-index +{ + "settings": { + "analysis": { + "filter": { + "german_stop": { + "type": "stop", + "stopwords": "_german_" + }, + "german_stemmer": { + "type": "stemmer", + "language": "light_german" + }, + "german_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "german_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "german_stop", + "german_keywords", + "german_normalization", + "german_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "german_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /german-index/_analyze +{ + "field": "content", + "text": "Die Studenten studieren an den deutschen Universitäten. Ihre Nummern sind 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 4, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "studi", + "start_offset": 14, + "end_offset": 23, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "deutsch", + "start_offset": 31, + "end_offset": 40, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "universitat", + "start_offset": 41, + "end_offset": 54, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "numm", + "start_offset": 61, + "end_offset": 68, + "type": "<ALPHANUM>", + "position": 8 + }, + { + "token": "123456", + "start_offset": 74, + "end_offset": 80, + "type": "<NUM>", + "position": 10 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/greek.md b/i18n/zh/analyzers/language-analyzers/greek.md new file mode 100644 index 00000000..8cf56300 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/greek.md @@ -0,0 +1,182 @@ +--- +title: 希腊语 +--- + +# 希腊语分析器 + +可以使用以下命令将内置的 `greek` 分析器应用于文本字段: + +```json +PUT /greek-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "greek" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_greek_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_greek_analyzer": { + "type": "greek", + "stem_exclusion": ["αρχή", "έγκριση"] + } + } + } + } +} +``` + +## 希腊语分析器 internals + +`greek` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Greek) + - keyword + - stemmer (Greek) + +## 自定义希腊语分析器 + +您可以使用以下命令创建自定义希腊语分析器: + +```json +PUT /greek-index +{ + "settings": { + "analysis": { + "filter": { + "greek_stop": { + "type": "stop", + "stopwords": "_greek_" + }, + "greek_lowercase": { + "type": "lowercase", + "language": "greek" + }, + "greek_stemmer": { + "type": "stemmer", + "language": "greek" + }, + "greek_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "greek_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "greek_lowercase", + "greek_stop", + "greek_keywords", + "greek_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "greek_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /greek-index/_analyze +{ + "field": "content", + "text": "Οι φοιτητές σπουδάζουν στα ελληνικά πανεπιστήμια. Οι αριθμοί τους είναι 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "φοιτητ", + "start_offset": 3, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "σπουδαζ", + "start_offset": 12, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "στα", + "start_offset": 23, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "ελλην", + "start_offset": 27, + "end_offset": 35, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "πανεπιστημ", + "start_offset": 36, + "end_offset": 48, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "αριθμ", + "start_offset": 53, + "end_offset": 60, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "τ", + "start_offset": 61, + "end_offset": 65, + "type": "<ALPHANUM>", + "position": 8 + }, + { + "token": "123456", + "start_offset": 72, + "end_offset": 78, + "type": "<NUM>", + "position": 10 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/hindi.md b/i18n/zh/analyzers/language-analyzers/hindi.md new file mode 100644 index 00000000..cbf31ef0 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/hindi.md @@ -0,0 +1,170 @@ +--- +title: 印地语 +--- + +# 印地语分析器 + +可以使用以下命令将内置的 `hindi` 分析器应用于文本字段: + +```json +PUT /hindi-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hindi" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_hindi_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_hindi_analyzer": { + "type": "hindi", + "stem_exclusion": ["अधिकार", "अनुमोदन"] + } + } + } + } +} +``` + +## 印地语分析器 internals + +`hindi` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - decimal_digit + - keyword + - normalization (indic) + - normalization (Hindi) + - stop (Hindi) + - stemmer (Hindi) + +## 自定义印地语分析器 + +您可以使用以下命令创建自定义印地语分析器: + +```json +PUT /hindi-index +{ + "settings": { + "analysis": { + "filter": { + "hindi_stop": { + "type": "stop", + "stopwords": "_hindi_" + }, + "hindi_stemmer": { + "type": "stemmer", + "language": "hindi" + }, + "hindi_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "hindi_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "decimal_digit", + "hindi_keywords", + "indic_normalization", + "hindi_normalization", + "hindi_stop", + "hindi_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hindi_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /hindi-index/_analyze +{ + "field": "content", + "text": "छात्र भारतीय विश्वविद्यालयों में पढ़ते हैं। उनके नंबर १२३४५६ हैं।" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "छातर", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "भारतिय", + "start_offset": 6, + "end_offset": 12, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "विशवविदयालय", + "start_offset": 13, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "पढ", + "start_offset": 33, + "end_offset": 38, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "नंबर", + "start_offset": 49, + "end_offset": 53, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "123456", + "start_offset": 54, + "end_offset": 60, + "type": "<NUM>", + "position": 8 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/hungarian.md b/i18n/zh/analyzers/language-analyzers/hungarian.md new file mode 100644 index 00000000..8ec0d026 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/hungarian.md @@ -0,0 +1,164 @@ +--- +title: 匈牙利语 +--- + +# 匈牙利语分析器 + +可以使用以下命令将内置的 `hungarian` 分析器应用于文本字段: + +```json +PUT /hungarian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hungarian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_hungarian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_hungarian_analyzer": { + "type": "hungarian", + "stem_exclusion": ["hatalom", "jóváhagyás"] + } + } + } + } +} +``` + +## 匈牙利语分析器 internals + +`hungarian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Hungarian) + - keyword + - stemmer (Hungarian) + +## 自定义匈牙利语分析器 + +您可以使用以下命令创建自定义匈牙利语分析器: + +```json +PUT /hungarian-index +{ + "settings": { + "analysis": { + "filter": { + "hungarian_stop": { + "type": "stop", + "stopwords": "_hungarian_" + }, + "hungarian_stemmer": { + "type": "stemmer", + "language": "hungarian" + }, + "hungarian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "hungarian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "hungarian_stop", + "hungarian_keywords", + "hungarian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "hungarian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /hungarian-index/_analyze +{ + "field": "content", + "text": "A diákok a magyar egyetemeken tanulnak. A számaik 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "diák", + "start_offset": 2, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "magyar", + "start_offset": 11, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "egyetem", + "start_offset": 18, + "end_offset": 29, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "tanul", + "start_offset": 30, + "end_offset": 38, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "szám", + "start_offset": 42, + "end_offset": 49, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "123456", + "start_offset": 50, + "end_offset": 56, + "type": "<NUM>", + "position": 8 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/icu.md b/i18n/zh/analyzers/language-analyzers/icu.md new file mode 100644 index 00000000..167e683c --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/icu.md @@ -0,0 +1,273 @@ +--- +title: ICU +--- + +# ICU 分析器 + +`icu_analyzer` 使用国际化 Unicode 组件(ICU)库为多语言内容提供高级文本分析。通过 `analysis-icu` 插件提供,此分析器擅长处理具有复杂书写系统的语言,包括中文、日文、韩文、泰语、阿拉伯语和希伯来语。 + +与标准分析器不同,`icu_analyzer` 应用 Unicode 感知的文本分割,可以识别不使用空格作为分隔符的语言中的单词边界。该分析器将 ICU 分词与字符规范化和大小写折叠相结合,以在不同语言家族中生成一致的、可搜索的词元。 + +## 安装 ICU 插件 + +在使用 `icu_analyzer` 之前,您必须安装 `analysis-icu` 插件: + +```bash +bin/opensearch-plugin install analysis-icu +``` + +安装后,重新启动您的 OpenSearch 集群以使插件生效。 + +有关安装插件的更多信息,请参阅[管理 OpenSearch 插件](/install-and-configure/plugins)。 + +## ICU 插件组件 + +`analysis-icu` 插件提供多个组件,可以独立使用或组合在自定义分析器中。内置的 `icu_analyzer` 使用这些组件的组合。 + +### 分词器 + +- [`icu_tokenizer`](/analyzers/tokenizers/icu-tokenizer):使用 ICU Unicode 文本分割规则对文本进行分词。对于单词之间没有空格的语言,比标准分词器更准确。 + +### 字符过滤器 + +- [`icu_normalizer`](/analyzers/character-filters/icu-normalization):将字符规范化为其规范的 Unicode 形式。可以配置不同的规范化模式(NFC、NFD、NFKC、NFKD)。 + +### 词元过滤器 + +- `icu_normalizer`:将词元规范化为规范的 Unicode 形式(与字符过滤器相同,但对词元进行操作)。 +- [`icu_folding`](/analyzers/token-filters/icu-folding):执行 Unicode 规范化和大小写折叠,包括删除变音符号。比 `asciifolding` 过滤器更全面。 +- [`icu_transform`](/analyzers/token-filters/icu-transform):应用 ICU 转换进行音译,例如在脚本之间转换(例如,从西里尔字母到拉丁字母)。 + +### 字段类型 + +- [`icu_collation_keyword`](/mappings/supported-field-types/icu-collation-keyword/):为排序和范围查询提供特定语言的排序规则。 + +## ICU 分析器的工作原理 + +`icu_analyzer` 对输入文本应用一系列转换: + +- **分词**:使用 ICU Unicode 文本分割算法将文本分解为词元。这种方法可以准确识别中文、日文、韩文和泰语等语言中的单词边界,这些语言不使用空格分隔单词。 +- **规范化**:将字符转换为规范的 Unicode 形式,解决变音符号、连字和复合字符表示方式的变化。 +- **大小写折叠**:应用全面的大小写转换,比基本的小写转换更有效地处理特定语言的规则,例如土耳其语的 İ/i 区分。 +- **字符过滤**:标准化等效的 Unicode 表示并从词元流中删除非文本元素。 + +## 何时使用 ICU 分析器 + +考虑在以下用例中使用 `icu_analyzer`: + +- **CJK 内容**:中文、日文和韩文文本受益于 ICU 单词分割功能,它比二元分词方法更准确地识别自然单词边界。 +- **东南亚语言**:泰语、高棉语、老挝语和类似需要基于词典或基于规则的单词边界检测的语言。 +- **从右到左的脚本**:阿拉伯语、希伯来语和其他 RTL 书写系统,其中正确的字符规范化至关重要。 +- **变音符号**:包含重音字符、元音变音或其他需要一致规范化的变音符号的内容。 +- **多语言应用程序**:包含需要统一文本处理的多种语言的搜索索引。 +- **Unicode 密集内容**:包含特殊 Unicode 字符、连字或组合标记的文档。 + +::: info NOTE +与 `cjk` 分析器的二元分词方法相比,`icu_analyzer` 为 CJK 文本提供了更好的单词边界检测。 +::: + +## 与其他分析器的比较 + +下表将 ICU 分析器与其他分析器进行比较。 + +| 分析器 | 最适合 | 分词方法 | +|:---------|:---------|:-------------------| +| `standard` | 通用、欧洲语言 | Unicode 文本分割(基于空格) | +| `cjk` | 中文、日文、韩文 | 二元分词(重叠的 2 字符序列) | +| `icu_analyzer` | 多语言、复杂脚本、CJK | ICU Unicode 文本分割(语言感知) | + +## 性能注意事项 + +由于其复杂的 Unicode 处理和语言感知分词,`icu_analyzer` 比基本分析器使用更多的计算资源。与 `standard` 或 `cjk` 分析器相比,该分析器需要额外的内存来存储 ICU 数据表,并且在文本分析期间消耗更多的 CPU 周期。 + +对于大多数搜索应用程序,准确性改进证明了性能开销是合理的,特别是在处理非拉丁脚本或多语言内容时。影响在索引期间最为明显;查询时分析对搜索延迟的影响很小。 + +::: tip TIP +使用您用例中的代表性数据评估 `icu_analyzer`,以验证性能是否满足您的要求。 +::: + +## 示例:使用 ICU 分析器 + +创建索引时,您可以将 `icu_analyzer` 分配给文本字段: + +```json +PUT /multilingual-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "icu_analyzer" + } + } + } +} +``` + +## 示例:使用 ICU 分析器分析文本 + +使用以下请求查看 `icu_analyzer` 如何处理多语言文本: + +```json +POST /_analyze +{ + "analyzer": "icu_analyzer", + "text": "東京は日本の首都です。OpenSearch supports advanced Unicode processing with café and naïve!" +} +``` + +分析器在自然单词边界处对日文字符进行分词,并规范化带重音的拉丁字符。在此示例中,`café` 通过 Unicode 大小写折叠变为 `cafe`,`naïve` 变为 `naive`。响应演示了日文和英文文本的正确分割: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "<IDEOGRAPHIC>", + "position": 0 + }, + { + "token": "は", + "start_offset": 2, + "end_offset": 3, + "type": "<IDEOGRAPHIC>", + "position": 1 + }, + { + "token": "日本", + "start_offset": 3, + "end_offset": 5, + "type": "<IDEOGRAPHIC>", + "position": 2 + }, + { + "token": "の", + "start_offset": 5, + "end_offset": 6, + "type": "<IDEOGRAPHIC>", + "position": 3 + }, + { + "token": "首都", + "start_offset": 6, + "end_offset": 8, + "type": "<IDEOGRAPHIC>", + "position": 4 + }, + { + "token": "てす", + "start_offset": 8, + "end_offset": 10, + "type": "<IDEOGRAPHIC>", + "position": 5 + }, + { + "token": "opensearch", + "start_offset": 11, + "end_offset": 21, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "supports", + "start_offset": 22, + "end_offset": 30, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "advanced", + "start_offset": 31, + "end_offset": 39, + "type": "<ALPHANUM>", + "position": 8 + }, + { + "token": "unicode", + "start_offset": 40, + "end_offset": 47, + "type": "<ALPHANUM>", + "position": 9 + }, + { + "token": "processing", + "start_offset": 48, + "end_offset": 58, + "type": "<ALPHANUM>", + "position": 10 + }, + { + "token": "with", + "start_offset": 59, + "end_offset": 63, + "type": "<ALPHANUM>", + "position": 11 + }, + { + "token": "cafe", + "start_offset": 64, + "end_offset": 68, + "type": "<ALPHANUM>", + "position": 12 + }, + { + "token": "and", + "start_offset": 69, + "end_offset": 72, + "type": "<ALPHANUM>", + "position": 13 + }, + { + "token": "naive", + "start_offset": 73, + "end_offset": 78, + "type": "<ALPHANUM>", + "position": 14 + } + ] +} +``` + +## 自定义 ICU 分析器 + +您可以使用具有特定配置的 ICU 组件创建自定义分析器: + +```json +PUT /custom-icu-index +{ + "settings": { + "analysis": { + "analyzer": { + "my_icu_analyzer": { + "type": "custom", + "tokenizer": "icu_tokenizer", + "filter": [ + "icu_normalizer", + "icu_folding" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_icu_analyzer" + } + } + } +} +``` + +## 相关文档 + +- [ICU 分词器](/analyzers/tokenizers/icu-tokenizer) -- Unicode 文本分割 +- [ICU 规范化字符过滤器](/analyzers/character-filters/icu-normalization) -- 字符级 Unicode 规范化 +- [ICU 折叠词元过滤器](/analyzers/token-filters/icu-folding) -- 大小写折叠和变音符号删除 +- [ICU 转换词元过滤器](/analyzers/token-filters/icu-transform) -- 音译和文本转换 +- [ICU 排序规则关键字字段](/mappings/supported-field-types/icu-collation-keyword/) -- 特定语言的排序 +- [CJK 分析器](/analyzers/language-analyzers/cjk) -- CJK 文本的替代方案 +- [管理 OpenSearch 插件](/install-and-configure/plugins#installing-plugins) -- 插件安装指南 diff --git a/i18n/zh/analyzers/language-analyzers/index.md b/i18n/zh/analyzers/language-analyzers/index.md new file mode 100644 index 00000000..00ab3a1c --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/index.md @@ -0,0 +1,126 @@ +--- +title: 语言分析器 +--- + +# 语言分析器 + +OpenSearch 支持以下语言分析器: +`arabic`、`armenian`、`basque`、`bengali`、`brazilian`、`bulgarian`、`catalan`、`czech`、`danish`、`dutch`、`english`、`estonian`、`finnish`、`french`、`galician`、`german`、`greek`、`hindi`、`hungarian`、`indonesian`、`irish`、`italian`、[`kuromoji`](/analyzers/language-analyzers/kuromoji)(日语分析器;需要插件)、`latvian`、`lithuanian`、`norwegian`、`persian`、[`polish`](/analyzers/language-analyzers/polish)(需要插件)、`portuguese`、`romanian`、`russian`、`sorani`、`spanish`、`swedish`、`thai`、`turkish` 和 [`ukrainian`](/analyzers/language-analyzers/ukrainian)(需要插件)。 + +对于具有高级 Unicode 支持的多语言文本处理,OpenSearch 还提供 [`icu_analyzer`](/analyzers/language-analyzers/icu),它为具有复杂脚本的语言(例如中文、日语、韩语、泰语和阿拉伯语)提供卓越的文本分割(需要 `analysis-icu` 插件)。 + +要在映射索引时使用分析器,请在查询中指定值。例如,要使用法语分析器映射索引,请在分析器字段中指定 `french` 值: + +```json + "analyzer": "french" +``` + +#### 示例请求 + +以下查询指定一个索引 `my-index`,其中 `content` 字段配置为多字段,子字段名为 `french`,并使用 `french` 语言分析器配置: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "fields": { + "french": { + "type": "text", + "analyzer": "french" + } + } + } + } + } +} +``` + +也可以使用以下查询为整个索引配置默认 `french` 分析器: + +```json +PUT my-index +{ + "settings": { + "analysis": { + "analyzer": { + "default": { + "type": "french" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text" + }, + "title": { + "type": "text" + }, + "description": { + "type": "text" + } + } + } +} +``` + +要搜索用多种语言编写的文档,您可以在摄取期间检测每个文档的语言,并将其文本复制到使用匹配语言分析器的字段。有关完整示例,请参阅[识别多语言搜索的文档语言](/tutorials/language-identification/)。 + +## 词干排除 + +您可以通过提供应从词干提取中排除的小写单词列表,将词干排除应用于任何语言分析器。在内部,OpenSearch 使用 `keyword_marker` 词元过滤器将这些单词标记为关键词,确保它们不会被词干提取。 + +## 词干排除示例 + +使用以下请求配置 `stem_exclusion`: + +```json +PUT index_with_stem_exclusion_english_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_english_analyzer":{ + "type":"english", + "stem_exclusion": ["manager", "management"] + } + } + } + } +} +``` + +## 自定义分析器的词干排除 + +所有语言分析器都由特定于特定语言的分词器和词元过滤器组成。如果您想实现带有词干排除的语言分析器的自定义版本,则需要配置 `keyword_marker` 词元过滤器,并在 `keywords` 参数中列出从词干提取中排除的单词: + +```json +PUT index_with_keyword_marker_analyzer +{ + "settings": { + "analysis": { + "filter": { + "protected_keywords_filter": { + "type": "keyword_marker", + "keywords": ["Apple", "OpenSearch"] + } + }, + "analyzer": { + "custom_english_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "protected_keywords_filter", + "english_stemmer" + ] + } + } + } + } +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/indonesian.md b/i18n/zh/analyzers/language-analyzers/indonesian.md new file mode 100644 index 00000000..cf205775 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/indonesian.md @@ -0,0 +1,164 @@ +--- +title: 印度尼西亚语 +--- + +# 印度尼西亚语分析器 + +可以使用以下命令将内置的 `indonesian` 分析器应用于文本字段: + +```json +PUT /indonesian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "indonesian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_indonesian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_indonesian_analyzer": { + "type": "indonesian", + "stem_exclusion": ["otoritas", "persetujuan"] + } + } + } + } +} +``` + +## 印度尼西亚语分析器 internals + +`indonesian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Indonesian) + - keyword + - stemmer (Indonesian) + +## 自定义印度尼西亚语分析器 + +您可以使用以下命令创建自定义印度尼西亚语分析器: + +```json +PUT /indonesian-index +{ + "settings": { + "analysis": { + "filter": { + "indonesian_stop": { + "type": "stop", + "stopwords": "_indonesian_" + }, + "indonesian_stemmer": { + "type": "stemmer", + "language": "indonesian" + }, + "indonesian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "indonesian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "indonesian_stop", + "indonesian_keywords", + "indonesian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "indonesian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /indonesian-index/_analyze +{ + "field": "content", + "text": "Mahasiswa belajar di universitas Indonesia. Nomor mereka adalah 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "mahasiswa", + "start_offset": 0, + "end_offset": 9, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "ajar", + "start_offset": 10, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "universitas", + "start_offset": 21, + "end_offset": 32, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "indonesia", + "start_offset": 33, + "end_offset": 42, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "nomor", + "start_offset": 44, + "end_offset": 49, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "123456", + "start_offset": 64, + "end_offset": 70, + "type": "<NUM>", + "position": 8 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/irish.md b/i18n/zh/analyzers/language-analyzers/irish.md new file mode 100644 index 00000000..83ea83a6 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/irish.md @@ -0,0 +1,149 @@ +--- +title: 爱尔兰语 +--- + +# 爱尔兰语分析器 + +可以使用以下命令将内置的 `irish` 分析器应用于文本字段: + +```json +PUT /irish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "irish" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_irish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_irish_analyzer": { + "type": "irish", + "stem_exclusion": ["údarás", "faomhadh"] + } + } + } + } +} +``` + +## 爱尔兰语分析器 internals + +`irish` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - hyphenation (Irish) + - elision (Irish) + - lowercase (Irish) + - stop (Irish) + - keyword + - stemmer (Irish) + +## 自定义爱尔兰语分析器 + +您可以使用以下命令创建自定义爱尔兰语分析器: + +```json +PUT /irish-index +{ + "settings": { + "analysis": { + "filter": { + "irish_stop": { + "type": "stop", + "stopwords": "_irish_" + }, + "irish_elision": { + "type": "elision", + "articles": [ "d", "m", "b" ], + "articles_case": true + }, + "irish_hyphenation": { + "type": "stop", + "stopwords": [ "h", "n", "t" ], + "ignore_case": true + }, + "irish_lowercase": { + "type": "lowercase", + "language": "irish" + }, + "irish_stemmer": { + "type": "stemmer", + "language": "irish" + }, + "irish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "irish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "irish_hyphenation", + "irish_elision", + "irish_lowercase", + "irish_stop", + "irish_keywords", + "irish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "irish_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /irish-index/_analyze +{ + "field": "content", + "text": "Tá mic léinn ag staidéar in ollscoileanna na hÉireann. Is iad a gcuid uimhreacha ná 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "tá","start_offset": 0,"end_offset": 2,"type": "<ALPHANUM>","position": 0}, + {"token": "mic","start_offset": 3,"end_offset": 6,"type": "<ALPHANUM>","position": 1}, + {"token": "léinn","start_offset": 7,"end_offset": 12,"type": "<ALPHANUM>","position": 2}, + {"token": "staidéar","start_offset": 16,"end_offset": 24,"type": "<ALPHANUM>","position": 4}, + {"token": "ollscoileanna","start_offset": 28,"end_offset": 41,"type": "<ALPHANUM>","position": 6}, + {"token": "héireann","start_offset": 45,"end_offset": 53,"type": "<ALPHANUM>","position": 8}, + {"token": "cuid","start_offset": 64,"end_offset": 69,"type": "<ALPHANUM>","position": 12}, + {"token": "uimhreacha","start_offset": 70,"end_offset": 80,"type": "<ALPHANUM>","position": 13}, + {"token": "123456","start_offset": 84,"end_offset": 90,"type": "<NUM>","position": 15} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/italian.md b/i18n/zh/analyzers/language-analyzers/italian.md new file mode 100644 index 00000000..3def1818 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/italian.md @@ -0,0 +1,140 @@ +--- +title: 意大利语 +--- + +# 意大利语分析器 + +可以使用以下命令将内置的 `italian` 分析器应用于文本字段: + +```json +PUT /italian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "italian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_italian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_italian_analyzer": { + "type": "italian", + "stem_exclusion": ["autorità", "approvazione"] + } + } + } + } +} +``` + +## 意大利语分析器 internals + +`italian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - elision (Italian) + - lowercase + - stop (Italian) + - keyword + - stemmer (Italian) + +## 自定义意大利语分析器 + +您可以使用以下命令创建自定义意大利语分析器: + +```json +PUT /italian-index +{ + "settings": { + "analysis": { + "filter": { + "italian_stop": { + "type": "stop", + "stopwords": "_italian_" + }, + "italian_elision": { + "type": "elision", + "articles": [ + "c", "l", "all", "dall", "dell", + "nell", "sull", "coll", "pell", + "gl", "agl", "dagl", "degl", "negl", + "sugl", "un", "m", "t", "s", "v", "d" + ], + "articles_case": true + }, + "italian_stemmer": { + "type": "stemmer", + "language": "light_italian" + }, + "italian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "italian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "italian_elision", + "lowercase", + "italian_stop", + "italian_keywords", + "italian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "italian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /italian-index/_analyze +{ + "field": "content", + "text": "Gli studenti studiano nelle università italiane. I loro numeri sono 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 4,"end_offset": 12,"type": "<ALPHANUM>","position": 1}, + {"token": "studian","start_offset": 13,"end_offset": 21,"type": "<ALPHANUM>","position": 2}, + {"token": "universit","start_offset": 28,"end_offset": 38,"type": "<ALPHANUM>","position": 4}, + {"token": "italian","start_offset": 39,"end_offset": 47,"type": "<ALPHANUM>","position": 5}, + {"token": "numer","start_offset": 56,"end_offset": 62,"type": "<ALPHANUM>","position": 8}, + {"token": "123456","start_offset": 68,"end_offset": 74,"type": "<NUM>","position": 10} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/kuromoji.md b/i18n/zh/analyzers/language-analyzers/kuromoji.md new file mode 100644 index 00000000..8164181c --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/kuromoji.md @@ -0,0 +1,376 @@ +--- +title: Kuromoji (Japanese) +--- + +# Kuromoji分析器 + +The `kuromoji` analyzer provides morphological analysis for Japanese text using the Kuromoji library backed by the IPAdic dictionary. It segments Japanese sentences into meaningful tokens, removes common stop words and grammatical particles, and returns tokens in their dictionary base form. + +To use the `kuromoji` analyzer or any Kuromoji components, you must first install the `analysis-kuromoji` plugin. + +## Installing the plugin + +Install the plugin on all nodes and then restart the cluster: + +```bash +bin/opensearch-plugin install analysis-kuromoji +``` + +For more information about installing plugins, see [Managing OpenSearch plugins](/install-and-configure/plugins). + +## Kuromoji plugin components + +The `analysis-kuromoji` plugin provides the following components that you can use independently or combine in custom analyzers. + +### Analyzers + +| Analyzer | Description | +|:---------|:------------| +| [`kuromoji`](#analysis-pipeline) | Built-in Japanese analyzer. Segments text, removes stop words, and normalizes tokens to their base form. | +| [`kuromoji_completion`](#kuromoji-completion-analyzer) | Analyzer designed for autocomplete of Japanese text. Generates the original Japanese tokens along with their romaji reading variants. | + +### Tokenizer + +| Tokenizer | Description | +|:----------|:------------| +| [`kuromoji_tokenizer`](/analyzers/tokenizers/kuromoji) | Dictionary-based Japanese tokenizer with configurable segmentation modes. | + +### Character filter + +| Character filter | Description | +|:----------------|:------------| +| [`kuromoji_iteration_mark`](/analyzers/character-filters/kuromoji-iteration-mark) | Normalizes Japanese iteration marks (々, ゝ, ゞ, ヽ, and ヾ) by expanding them to the character they repeat. | + +### Token filters + +| Token filter | Description | +|:------------|:------------| +| [`kuromoji_baseform`](/analyzers/token-filters/kuromoji-baseform) | Replaces inflected tokens with their dictionary base form. | +| [`kuromoji_part_of_speech`](/analyzers/token-filters/kuromoji-part-of-speech) | Removes tokens whose part-of-speech tag is in a configured stop-tag list. | +| [`kuromoji_readingform`](/analyzers/token-filters/kuromoji-readingform) | Replaces each token with its katakana or romaji reading. | +| [`kuromoji_stemmer`](/analyzers/token-filters/kuromoji-stemmer) | Removes trailing long vowel marks (ー) from katakana words. | +| [`ja_stop`](/analyzers/token-filters/ja-stop) | Removes Japanese stop words from the token stream. | +| [`kuromoji_number`](/analyzers/token-filters/kuromoji-number) | Converts Japanese numeral expressions to standard Arabic numerals. | +| [`kuromoji_completion`](/analyzers/token-filters/kuromoji-completion) | Generates romaji reading variants for katakana tokens to support autocomplete. | + +## Analysis pipeline + +The `kuromoji` analyzer applies the following components to input text, in order: + +1. The `cjk_width` character filter converts full-width ASCII variants to their standard ASCII equivalents and half-width katakana variants to full-width katakana before tokenization. +2. The `kuromoji_tokenizer` in `search` mode segments text using the IPAdic dictionary, splitting long compound words into their sub-tokens. +3. The `kuromoji_baseform` token filter replaces inflected verb and adjective forms with their dictionary forms (for example, 食べた becomes 食べる). +4. The `kuromoji_part_of_speech` token filter removes grammatical particles (助詞), auxiliary verbs (助動詞), punctuation (記号), and other stop tags. +5. The `ja_stop` token filter removes common Japanese stop words. +6. The `kuromoji_stemmer` token filter removes trailing long vowel marks (ー) from katakana words of four or more characters (for example, コンピューター becomes コンピュータ). +7. The `lowercase` token filter converts any Latin characters to lowercase. + +## Parameters + +The following table lists the parameters for the `kuromoji` analyzer. + +Parameter | Data type | Description +:--- | :--- | :--- +`mode` | String | Tokenization mode. Valid values are `normal`, `search` (default), and `extended`. See [Tokenization modes](#tokenization-modes) for details. +`user_dictionary` | String | Path to a custom user dictionary file (CSV format) placed in the OpenSearch config directory. Optional. +`user_dictionary_rules` | Array of strings | Inline custom dictionary rules in CSV format. Each entry is `<text>,<subtokens>,<readings>,<part of speech>`. Optional. Cannot be used together with `user_dictionary`. +`stopwords` | String or array of strings | Stop words to use. Accepts `_japanese_` (the built-in Japanese stop set), an array of explicit stop words, or a path to a stop word file. Default is `_japanese_`. + +For the full list of stop words in the built-in stop set, see [stopwords.txt](https://github.com/apache/lucene/blob/main/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stopwords.txt) in the Lucene repository. + +## Tokenization modes + +The tokenizer mode controls how compound and unknown words are segmented. + +| Mode | Effect | +|:-----|:-------| +| `normal` | Standard dictionary-based segmentation. Compound words are kept as a single token. Unknown words are kept as a single token. | +| `search` (default) | Like `normal`, but compound words (for example, place names) are also split into their sub-components, improving recall for search queries. | +| `extended` | Like `normal`, but unknown words are split into unigrams (individual characters), ensuring that every character is indexed. | + +## Example: Basic usage + +The following example creates an index that uses the built-in `kuromoji` analyzer: + +```json +PUT /japanese-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "kuromoji" + } + } + } +} +``` + +Test the analyzer with a Japanese sentence meaning "I studied at the Tokyo library": + +```json +POST /_analyze +{ + "analyzer": "kuromoji", + "text": "東京の図書館で勉強しました" +} +``` + +The analyzer returns base-form tokens with particles and auxiliary verbs removed: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "図書館", + "start_offset": 3, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "勉強", + "start_offset": 7, + "end_offset": 9, + "type": "word", + "position": 4 + } + ] +} +``` + +## Example: Custom Kuromoji analyzer + +The following example creates a custom `kuromoji` analyzer that uses `user_dictionary_rules` to register inline custom terms: + +```json +PUT /japanese-custom-index +{ + "settings": { + "analysis": { + "analyzer": { + "my_kuromoji": { + "type": "kuromoji", + "mode": "search", + "user_dictionary_rules": [ + "東京スカイツリー,東京 スカイツリー,トウキョウ スカイツリー,カスタム名詞" + ] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "my_kuromoji" + } + } + } +} +``` + +Test the custom analyzer with a sentence containing the registered term ("I went to Tokyo Skytree"): + +```json +POST /japanese-custom-index/_analyze +{ + "analyzer": "my_kuromoji", + "text": "東京スカイツリーに行きました" +} +``` + +The analyzer uses the custom dictionary rule to segment `東京スカイツリー` into `東京` and `スカイツリー`. The default katakana stemmer (`kuromoji_stemmer`) removes the trailing long vowel mark from `スカイツリー` to produce `スカイツリ`. The `kuromoji_part_of_speech` filter removes the particle `に` and the auxiliary verbs `まし` and `た`, and `kuromoji_baseform` normalizes `行き` to its base form `行く`: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "スカイツリ", + "start_offset": 2, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "行く", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 3 + } + ] +} +``` + +## Kuromoji completion analyzer + +The `kuromoji_completion` analyzer is designed for autocomplete use cases. It generates both the original Japanese tokens and their romaji (Latin script) reading variants, allowing users to search for Japanese content by typing in either Japanese characters or their romanized equivalents. In `query` mode, the analyzer also assembles partial input from an input method editor (IME) into a single token before romanizing it. + +The following table lists the parameters for the `kuromoji_completion` analyzer. + +Parameter | Data type | Description +:--- | :--- | :--- +`mode` | String | Controls how tokens are generated. Valid values are `index` (default) and `query`. Both modes expand katakana tokens into their original form plus all romaji variants. The `query` mode applies two additional rules for handling partial IME input: it concatenates consecutive kana tokens into a single token before romanizing, and it merges a kana token with a trailing lowercase alphabet token that represents a partially typed IME keystroke (for example, `サッ` followed by `k` becomes `サッk`). +`user_dictionary` | String | Path to a custom user dictionary file. Optional. +`user_dictionary_rules` | Array of strings | Inline custom dictionary rules. Optional. + +::: tip TIP +Use `query` mode in the search analyzer so that partial IME input typed by a user is correctly assembled before romanization. +::: + +### Example: Autocomplete using the Kuromoji completion analyzer + +The following example configures an index with different completion analyzers used at index time and search time: + +```json +PUT /autocomplete-index +{ + "settings": { + "analysis": { + "analyzer": { + "kuromoji_index_analyzer": { + "type": "kuromoji_completion", + "mode": "index" + }, + "kuromoji_search_analyzer": { + "type": "kuromoji_completion", + "mode": "query" + } + } + } + }, + "mappings": { + "properties": { + "suggest": { + "type": "text", + "analyzer": "kuromoji_index_analyzer", + "search_analyzer": "kuromoji_search_analyzer" + } + } + } +} +``` + +For more details about the completion token filter, see [Kuromoji completion token filter](/analyzers/token-filters/kuromoji-completion). + +## Using the Kuromoji and ICU plugins together + +For the most thorough Japanese text analysis, combine the `analysis-kuromoji` and `analysis-icu` plugins. ICU contributes Unicode normalization of full-width and half-width characters and comprehensive character folding that the Kuromoji components alone do not provide. + +::: info NOTE +Both `analysis-kuromoji` and `analysis-icu` must be installed before creating an index that uses components from both plugins. +::: + +The following example creates a custom analyzer combining both plugins. The `icu_normalizer` character filter converts full-width characters to their ASCII equivalents before tokenization (for example, `300` becomes `300`), keeping numeric sequences as single tokens. The `kuromoji_iteration_mark` character filter expands Japanese iteration marks (for example, `時々` becomes `時時`) so the tokenizer can look them up in the dictionary correctly: + +```json +PUT /japanese-icu-index +{ + "settings": { + "index": { + "analysis": { + "analyzer": { + "japanese_icu_analyzer": { + "char_filter": [ + "icu_normalizer", + "kuromoji_iteration_mark" + ], + "tokenizer": "kuromoji_tokenizer", + "filter": [ + "kuromoji_baseform", + "kuromoji_part_of_speech", + "ja_stop", + "kuromoji_stemmer", + "lowercase" + ] + } + } + } + } + } +} +``` + +Test the combined analyzer with a sentence containing full-width digits and a long vowel mark ("The computer processes 300 documents"): + +```json +POST /japanese-icu-index/_analyze +{ + "analyzer": "japanese_icu_analyzer", + "text": "コンピューターは300件の文書を処理します" +} +``` + +The analyzer applies the following transformations: + +- `icu_normalizer` converts the full-width digits `300` to `300` before tokenization. +- `kuromoji_stemmer` removes the trailing long vowel mark, converting `コンピューター` to `コンピュータ`. +- `kuromoji_part_of_speech` removes the particles `は`, `の`, and `を`, along with the auxiliary verb `ます`. +- `ja_stop` removes `し` because it appears in the `_japanese_` stop set. +- `300` is kept as a single token, and `文書` and `処理` are returned in base form. + +The response appears as follows: + +```json +{ + "tokens": [ + { + "token": "コンピュータ", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "300", + "start_offset": 8, + "end_offset": 11, + "type": "word", + "position": 2 + }, + { + "token": "件", + "start_offset": 11, + "end_offset": 12, + "type": "word", + "position": 3 + }, + { + "token": "文書", + "start_offset": 13, + "end_offset": 15, + "type": "word", + "position": 5 + }, + { + "token": "処理", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 7 + } + ] +} +``` + +## Related documentation + +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji iteration mark character filter](/analyzers/character-filters/kuromoji-iteration-mark) +- [ICU analyzer](/analyzers/language-analyzers/icu) +- [CJK width token filter](/analyzers/token-filters/cjk-width) diff --git a/i18n/zh/analyzers/language-analyzers/latvian.md b/i18n/zh/analyzers/language-analyzers/latvian.md new file mode 100644 index 00000000..8b01b035 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/latvian.md @@ -0,0 +1,171 @@ +--- +title: 拉脱维亚语 +--- + +# 拉脱维亚语分析器 + +可以使用以下命令将内置的 `latvian` 分析器应用于文本字段: + +```json +PUT /latvian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "latvian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_latvian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_latvian_analyzer": { + "type": "latvian", + "stem_exclusion": ["autoritāte", "apstiprinājums"] + } + } + } + } +} +``` + +## 拉脱维亚语分析器 internals + +`latvian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Latvian) + - keyword + - stemmer (Latvian) + +## 自定义拉脱维亚语分析器 + +您可以使用以下命令创建自定义拉脱维亚语分析器: + +```json +PUT /latvian-index +{ + "settings": { + "analysis": { + "filter": { + "latvian_stop": { + "type": "stop", + "stopwords": "_latvian_" + }, + "latvian_stemmer": { + "type": "stemmer", + "language": "latvian" + }, + "latvian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "latvian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "latvian_stop", + "latvian_keywords", + "latvian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "latvian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /latvian-index/_analyze +{ + "field": "content", + "text": "Studenti mācās Latvijas universitātēs. Viņu numuri ir 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "māc", + "start_offset": 9, + "end_offset": 14, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "latvij", + "start_offset": 15, + "end_offset": 23, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "universitāt", + "start_offset": 24, + "end_offset": 37, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "vin", + "start_offset": 39, + "end_offset": 43, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "numur", + "start_offset": 44, + "end_offset": 50, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "123456", + "start_offset": 54, + "end_offset": 60, + "type": "<NUM>", + "position": 7 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/lithuanian.md b/i18n/zh/analyzers/language-analyzers/lithuanian.md new file mode 100644 index 00000000..0071098a --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/lithuanian.md @@ -0,0 +1,128 @@ +--- +title: 立陶宛语 +--- + +# 立陶宛语分析器 + +可以使用以下命令将内置的 `lithuanian` 分析器应用于文本字段: + +```json +PUT /lithuanian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "lithuanian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_lithuanian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_lithuanian_analyzer": { + "type": "lithuanian", + "stem_exclusion": ["autoritetas", "patvirtinimas"] + } + } + } + } +} +``` + +## 立陶宛语分析器 internals + +`lithuanian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Lithuanian) + - keyword + - stemmer (Lithuanian) + +## 自定义立陶宛语分析器 + +您可以使用以下命令创建自定义立陶宛语分析器: + +```json +PUT /lithuanian-index +{ + "settings": { + "analysis": { + "filter": { + "lithuanian_stop": { + "type": "stop", + "stopwords": "_lithuanian_" + }, + "lithuanian_stemmer": { + "type": "stemmer", + "language": "lithuanian" + }, + "lithuanian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "lithuanian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "lithuanian_stop", + "lithuanian_keywords", + "lithuanian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "lithuanian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /lithuanian-index/_analyze +{ + "field": "content", + "text": "Studentai mokosi Lietuvos universitetuose. Jų numeriai yra 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 0,"end_offset": 9,"type": "<ALPHANUM>","position": 0}, + {"token": "mok","start_offset": 10,"end_offset": 16,"type": "<ALPHANUM>","position": 1}, + {"token": "lietuv","start_offset": 17,"end_offset": 25,"type": "<ALPHANUM>","position": 2}, + {"token": "universitet","start_offset": 26,"end_offset": 41,"type": "<ALPHANUM>","position": 3}, + {"token": "num","start_offset": 46,"end_offset": 54,"type": "<ALPHANUM>","position": 5}, + {"token": "123456","start_offset": 59,"end_offset": 65,"type": "<NUM>","position": 7} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/norwegian.md b/i18n/zh/analyzers/language-analyzers/norwegian.md new file mode 100644 index 00000000..fdedbbda --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/norwegian.md @@ -0,0 +1,129 @@ +--- +title: 挪威语 +--- + +# 挪威语分析器 + +可以使用以下命令将内置的 `norwegian` 分析器应用于文本字段: + +```json +PUT /norwegian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "norwegian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_norwegian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_norwegian_analyzer": { + "type": "norwegian", + "stem_exclusion": ["autoritet", "godkjenning"] + } + } + } + } +} +``` + +## 挪威语分析器 internals + +`norwegian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Norwegian) + - keyword + - stemmer (Norwegian) + +## 自定义挪威语分析器 + +您可以使用以下命令创建自定义挪威语分析器: + +```json +PUT /norwegian-index +{ + "settings": { + "analysis": { + "filter": { + "norwegian_stop": { + "type": "stop", + "stopwords": "_norwegian_" + }, + "norwegian_stemmer": { + "type": "stemmer", + "language": "norwegian" + }, + "norwegian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "norwegian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "norwegian_stop", + "norwegian_keywords", + "norwegian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "norwegian_analyzer" + } + } + } +} + +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /norwegian-index/_analyze +{ + "field": "content", + "text": "Studentene studerer ved norske universiteter. Deres nummer er 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "student","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0}, + {"token": "studer","start_offset": 11,"end_offset": 19,"type": "<ALPHANUM>","position": 1}, + {"token": "norsk","start_offset": 24,"end_offset": 30,"type": "<ALPHANUM>","position": 3}, + {"token": "universitet","start_offset": 31,"end_offset": 44,"type": "<ALPHANUM>","position": 4}, + {"token": "numm","start_offset": 52,"end_offset": 58,"type": "<ALPHANUM>","position": 6}, + {"token": "123456","start_offset": 62,"end_offset": 68,"type": "<NUM>","position": 8} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/persian.md b/i18n/zh/analyzers/language-analyzers/persian.md new file mode 100644 index 00000000..d6d07bd5 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/persian.md @@ -0,0 +1,137 @@ +--- +title: 波斯语 +--- + +# 波斯语分析器 + +可以使用以下命令将内置的 `persian` 分析器应用于文本字段: + +```json +PUT /persian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "persian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_persian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_persian_analyzer": { + "type": "persian", + "stem_exclusion": ["حکومت", "تأیید"] + } + } + } + } +} +``` + +## 波斯语分析器 internals + +`persian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- Char filter: `mapping` + +- 词元过滤器: + - lowercase + - decimal_digit + - normalization (Arabic) + - normalization (Persian) + - stop (Persian) + - keyword + +## 自定义波斯语分析器 + +您可以使用以下命令创建自定义波斯语分析器: + +```json +PUT /persian-index +{ + "settings": { + "analysis": { + "filter": { + "persian_stop": { + "type": "stop", + "stopwords": "_persian_" + }, + "persian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "char_filter": { + "null_width_replace_with_space": { + "type": "mapping", + "mappings": [ "\\u200C=>\\u0020"] + } + }, + "analyzer": { + "persian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "char_filter": [ "null_width_replace_with_space" ], + "filter": [ + "lowercase", + "decimal_digit", + "arabic_normalization", + "persian_normalization", + "persian_stop", + "persian_keywords" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "persian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /persian-index/_analyze +{ + "field": "content", + "text": "دانشجویان در دانشگاه‌های ایرانی تحصیل می‌کنند. شماره‌های آن‌ها ۱۲۳۴۵۶ است." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "دانشجويان","start_offset": 0,"end_offset": 9,"type": "<ALPHANUM>","position": 0}, + {"token": "دانشگاه","start_offset": 13,"end_offset": 20,"type": "<ALPHANUM>","position": 2}, + {"token": "ايراني","start_offset": 25,"end_offset": 31,"type": "<ALPHANUM>","position": 4}, + {"token": "تحصيل","start_offset": 32,"end_offset": 37,"type": "<ALPHANUM>","position": 5}, + {"token": "شماره","start_offset": 47,"end_offset": 52,"type": "<ALPHANUM>","position": 8}, + {"token": "123456","start_offset": 63,"end_offset": 69,"type": "<NUM>","position": 12} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/polish.md b/i18n/zh/analyzers/language-analyzers/polish.md new file mode 100644 index 00000000..3f0926ce --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/polish.md @@ -0,0 +1,122 @@ +--- +title: 波兰语 +--- + +# 波兰语分析器 + +The Polish language analyzer (`polish`) provides analysis for Polish text. This analyzer is part of the `analysis-stempel` plugin, which must be installed before use. + +## Installing the plugin + +Before you can use the Polish analyzer, you must install the `analysis-stempel` plugin by running the following command: + +```bash +./bin/opensearch-plugin install analysis-stempel +``` + +For more information, see [Additional plugins](/install-and-configure/additional-plugins/): Complete list of available OpenSearch plugins. + +## Using the Polish analyzer + +To use the Polish analyzer when you map an index, specify the `polish` value in the analyzer field: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "polish" + } + } + } +} +``` + +## Configuring a custom Polish analyzer + +You can configure a custom Polish analyzer by creating a custom analyzer that uses the Polish stemmer token filter. The default Polish analyzer applies the following analysis chain: + +1. **Tokenizer**: `standard` +2. **Token filters**: + - `lowercase` + - `polish_stop` (removes Polish stop words) + - `polish_stem` (applies Polish stemming) + +### Example: Custom Polish analyzer + +```json +PUT my-polish-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_polish": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "polish_stop", + "polish_stem" + ] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "custom_polish" + }, + "content": { + "type": "text", + "analyzer": "polish" + } + } + } +} +``` + +## Polish token filters + +The `analysis-stempel` plugin provides the following token filters for Polish language processing. + +<!-- vale off --> +### polish_stop token filter +<!-- vale on --> + +Removes common Polish stop words from the token stream. + +<!-- vale off --> +### polish_stem token filter +<!-- vale on --> + +Applies Polish-specific stemming rules to reduce words to their root forms using the Stempel stemming algorithm. + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST _analyze +{ + "analyzer": "polish", + "text": "Jestem programistą w Polsce i pracuję z OpenSearch" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "jest", "start_offset": 0, "end_offset": 6, "type": "<ALPHANUM>", "position": 0}, + {"token": "prograć", "start_offset": 7, "end_offset": 18, "type": "<ALPHANUM>", "position": 1}, + {"token": "polsce", "start_offset": 21, "end_offset": 27, "type": "<ALPHANUM>", "position": 3}, + {"token": "pracować", "start_offset": 30, "end_offset": 37, "type": "<ALPHANUM>", "position": 5}, + {"token": "opensearch", "start_offset": 40, "end_offset": 50, "type": "<ALPHANUM>", "position": 7} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/portuguese.md b/i18n/zh/analyzers/language-analyzers/portuguese.md new file mode 100644 index 00000000..5e526d56 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/portuguese.md @@ -0,0 +1,164 @@ +--- +title: 葡萄牙语 +--- + +# 葡萄牙语分析器 + +可以使用以下命令将内置的 `portuguese` 分析器应用于文本字段: + +```json +PUT /portuguese-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "portuguese" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_portuguese_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_portuguese_analyzer": { + "type": "portuguese", + "stem_exclusion": ["autoridade", "aprovação"] + } + } + } + } +} +``` + +## 葡萄牙语分析器 internals + +`portuguese` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Portuguese) + - keyword + - stemmer (Portuguese) + +## 自定义葡萄牙语分析器 + +您可以使用以下命令创建自定义葡萄牙语分析器: + +```json +PUT /portuguese-index +{ + "settings": { + "analysis": { + "filter": { + "portuguese_stop": { + "type": "stop", + "stopwords": "_portuguese_" + }, + "portuguese_stemmer": { + "type": "stemmer", + "language": "light_portuguese" + }, + "portuguese_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "portuguese_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "portuguese_stop", + "portuguese_keywords", + "portuguese_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "portuguese_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /portuguese-index/_analyze +{ + "field": "content", + "text": "Os estudantes estudam nas universidades brasileiras. Seus números são 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "estudant", + "start_offset": 3, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "estudam", + "start_offset": 14, + "end_offset": 21, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "universidad", + "start_offset": 26, + "end_offset": 39, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "brasileir", + "start_offset": 40, + "end_offset": 51, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "numer", + "start_offset": 58, + "end_offset": 65, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "123456", + "start_offset": 70, + "end_offset": 76, + "type": "<NUM>", + "position": 9 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/romanian.md b/i18n/zh/analyzers/language-analyzers/romanian.md new file mode 100644 index 00000000..499935dd --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/romanian.md @@ -0,0 +1,164 @@ +--- +title: 罗马尼亚语 +--- + +# 罗马尼亚语分析器 + +可以使用以下命令将内置的 `romanian` 分析器应用于文本字段: + +```json +PUT /romanian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "romanian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_romanian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_romanian_analyzer": { + "type": "romanian", + "stem_exclusion": ["autoritate", "aprobat"] + } + } + } + } +} +``` + +## 罗马尼亚语分析器 internals + +`romanian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Romanian) + - keyword + - stemmer (Romanian) + +## 自定义罗马尼亚语分析器 + +您可以使用以下命令创建自定义罗马尼亚语分析器: + +```json +PUT /romanian-index +{ + "settings": { + "analysis": { + "filter": { + "romanian_stop": { + "type": "stop", + "stopwords": "_romanian_" + }, + "romanian_stemmer": { + "type": "stemmer", + "language": "romanian" + }, + "romanian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "romanian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "romanian_stop", + "romanian_keywords", + "romanian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "romanian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /romanian-index/_analyze +{ + "field": "content", + "text": "Studenții învață la universitățile din România. Numerele lor sunt 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "studenț", + "start_offset": 0, + "end_offset": 9, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "învaț", + "start_offset": 10, + "end_offset": 16, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "universităț", + "start_offset": 20, + "end_offset": 34, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "român", + "start_offset": 39, + "end_offset": 46, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "numer", + "start_offset": 48, + "end_offset": 56, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "123456", + "start_offset": 66, + "end_offset": 72, + "type": "<NUM>", + "position": 9 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/russian.md b/i18n/zh/analyzers/language-analyzers/russian.md new file mode 100644 index 00000000..434d7730 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/russian.md @@ -0,0 +1,164 @@ +--- +title: 俄语 +--- + +# 俄语分析器 + +可以使用以下命令将内置的 `russian` 分析器应用于文本字段: + +```json +PUT /russian-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "russian" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_russian_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_russian_analyzer": { + "type": "russian", + "stem_exclusion": ["авторитет", "одобрение"] + } + } + } + } +} +``` + +## 俄语分析器 internals + +`russian` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Russian) + - keyword + - stemmer (Russian) + +## 自定义俄语分析器 + +您可以使用以下命令创建自定义俄语分析器: + +```json +PUT /russian-index +{ + "settings": { + "analysis": { + "filter": { + "russian_stop": { + "type": "stop", + "stopwords": "_russian_" + }, + "russian_stemmer": { + "type": "stemmer", + "language": "russian" + }, + "russian_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "russian_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "russian_stop", + "russian_keywords", + "russian_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "russian_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /russian-index/_analyze +{ + "field": "content", + "text": "Студенты учатся в университетах России. Их номера 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "студент", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "учат", + "start_offset": 9, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "университет", + "start_offset": 18, + "end_offset": 31, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "росс", + "start_offset": 32, + "end_offset": 38, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "номер", + "start_offset": 43, + "end_offset": 49, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "123456", + "start_offset": 50, + "end_offset": 56, + "type": "<NUM>", + "position": 7 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/sorani.md b/i18n/zh/analyzers/language-analyzers/sorani.md new file mode 100644 index 00000000..f784e378 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/sorani.md @@ -0,0 +1,161 @@ +--- +title: 库尔德语索拉尼方言 +--- + +# 库尔德语索拉尼方言分析器 + +可以使用以下命令将内置的 `sorani` 分析器应用于文本字段: + +```json +PUT /sorani-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "sorani" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_sorani_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_sorani_analyzer": { + "type": "sorani", + "stem_exclusion": ["مؤسسه", "اجازه"] + } + } + } + } +} +``` + +## 库尔德语索拉尼方言分析器 internals + +`sorani` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - normalization (Sorani) + - lowercase + - decimal_digit + - stop (Sorani) + - keyword + - stemmer (Sorani) + +## 自定义库尔德语索拉尼方言分析器 + +您可以使用以下命令创建自定义库尔德语索拉尼方言分析器: + +```json +PUT /sorani-index +{ + "settings": { + "analysis": { + "filter": { + "sorani_stop": { + "type": "stop", + "stopwords": "_sorani_" + }, + "sorani_stemmer": { + "type": "stemmer", + "language": "sorani" + }, + "sorani_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "sorani_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "sorani_normalization", + "lowercase", + "decimal_digit", + "sorani_stop", + "sorani_keywords", + "sorani_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "sorani_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /sorani-index/_analyze +{ + "field": "content", + "text": "خوێندنی فەرمی لە هەولێرەوە. ژمارەکان ١٢٣٤٥٦." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "خوێندن", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "فەرم", + "start_offset": 8, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "هەولێر", + "start_offset": 17, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "ژمار", + "start_offset": 28, + "end_offset": 36, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "123456", + "start_offset": 37, + "end_offset": 43, + "type": "<NUM>", + "position": 5 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/spanish.md b/i18n/zh/analyzers/language-analyzers/spanish.md new file mode 100644 index 00000000..30ec81ca --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/spanish.md @@ -0,0 +1,164 @@ +--- +title: 西班牙语 +--- + +# 西班牙语分析器 + +可以使用以下命令将内置的 `spanish` 分析器应用于文本字段: + +```json +PUT /spanish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "spanish" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_spanish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_spanish_analyzer": { + "type": "spanish", + "stem_exclusion": ["autoridad", "aprobación"] + } + } + } + } +} +``` + +## 西班牙语分析器 internals + +`spanish` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Spanish) + - keyword + - stemmer (Spanish) + +## 自定义西班牙语分析器 + +您可以使用以下命令创建自定义西班牙语分析器: + +```json +PUT /spanish-index +{ + "settings": { + "analysis": { + "filter": { + "spanish_stop": { + "type": "stop", + "stopwords": "_spanish_" + }, + "spanish_stemmer": { + "type": "stemmer", + "language": "light_spanish" + }, + "spanish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "spanish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "spanish_stop", + "spanish_keywords", + "spanish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "spanish_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /spanish-index/_analyze +{ + "field": "content", + "text": "Los estudiantes estudian en universidades españolas. Sus números son 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "estudiant", + "start_offset": 4, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "estudian", + "start_offset": 16, + "end_offset": 24, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "universidad", + "start_offset": 28, + "end_offset": 41, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "español", + "start_offset": 42, + "end_offset": 51, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "numer", + "start_offset": 57, + "end_offset": 64, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "123456", + "start_offset": 69, + "end_offset": 75, + "type": "<NUM>", + "position": 9 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/swedish.md b/i18n/zh/analyzers/language-analyzers/swedish.md new file mode 100644 index 00000000..2d3e5ecb --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/swedish.md @@ -0,0 +1,164 @@ +--- +title: 瑞典语 +--- + +# 瑞典语分析器 + +可以使用以下命令将内置的 `swedish` 分析器应用于文本字段: + +```json +PUT /swedish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "swedish" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_swedish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_swedish_analyzer": { + "type": "swedish", + "stem_exclusion": ["myndighet", "godkännande"] + } + } + } + } +} +``` + +## 瑞典语分析器 internals + +`swedish` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - lowercase + - stop (Swedish) + - keyword + - stemmer (Swedish) + +## 自定义瑞典语分析器 + +您可以使用以下命令创建自定义瑞典语分析器: + +```json +PUT /swedish-index +{ + "settings": { + "analysis": { + "filter": { + "swedish_stop": { + "type": "stop", + "stopwords": "_swedish_" + }, + "swedish_stemmer": { + "type": "stemmer", + "language": "swedish" + }, + "swedish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "swedish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "swedish_stop", + "swedish_keywords", + "swedish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "swedish_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /swedish-index/_analyze +{ + "field": "content", + "text": "Studenter studerar vid svenska universitet. Deras nummer är 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "student", + "start_offset": 0, + "end_offset": 9, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "studer", + "start_offset": 10, + "end_offset": 18, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "svensk", + "start_offset": 23, + "end_offset": 30, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "universitet", + "start_offset": 31, + "end_offset": 42, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "numm", + "start_offset": 50, + "end_offset": 56, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "123456", + "start_offset": 60, + "end_offset": 66, + "type": "<NUM>", + "position": 8 + } + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/thai.md b/i18n/zh/analyzers/language-analyzers/thai.md new file mode 100644 index 00000000..000d2ef2 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/thai.md @@ -0,0 +1,124 @@ +--- +title: 泰语 +--- + +# 泰语分析器 + +可以使用以下命令将内置的 `thai` 分析器应用于文本字段: + +```json +PUT /thai-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "thai" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_thai_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_thai_analyzer": { + "type": "thai", + "stem_exclusion": ["อำนาจ", "การอนุมัติ"] + } + } + } + } +} +``` + +## 泰语分析器 internals + +`thai` 分析器使用以下组件构建: + +- 分词器: `thai` + +- 词元过滤器: + - lowercase + - decimal_digit + - stop (Thai) + - keyword + +## 自定义泰语分析器 + +您可以使用以下命令创建自定义泰语分析器: + +```json +PUT /thai-index +{ + "settings": { + "analysis": { + "filter": { + "thai_stop": { + "type": "stop", + "stopwords": "_thai_" + }, + "thai_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "thai_analyzer": { + "tokenizer": "thai", + "filter": [ + "lowercase", + "decimal_digit", + "thai_stop", + "thai_keywords" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "thai_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /thai-index/_analyze +{ + "field": "content", + "text": "นักเรียนกำลังศึกษาอยู่ที่มหาวิทยาลัยไทย หมายเลข 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "นักเรียน","start_offset": 0,"end_offset": 8,"type": "word","position": 0}, + {"token": "กำลัง","start_offset": 8,"end_offset": 13,"type": "word","position": 1}, + {"token": "ศึกษา","start_offset": 13,"end_offset": 18,"type": "word","position": 2}, + {"token": "มหาวิทยาลัย","start_offset": 25,"end_offset": 36,"type": "word","position": 5}, + {"token": "ไทย","start_offset": 36,"end_offset": 39,"type": "word","position": 6}, + {"token": "หมายเลข","start_offset": 40,"end_offset": 47,"type": "word","position": 7}, + {"token": "123456","start_offset": 48,"end_offset": 54,"type": "word","position": 8} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/turkish.md b/i18n/zh/analyzers/language-analyzers/turkish.md new file mode 100644 index 00000000..e5fb10a1 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/turkish.md @@ -0,0 +1,135 @@ +--- +title: 土耳其语 +--- + +# 土耳其语分析器 + +可以使用以下命令将内置的 `turkish` 分析器应用于文本字段: + +```json +PUT /turkish-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "turkish" + } + } + } +} +``` + +## 词干排除 + +您可以使用以下命令将 `stem_exclusion` 与此语言分析器一起使用: + +```json +PUT index_with_stem_exclusion_turkish_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "stem_exclusion_turkish_analyzer": { + "type": "turkish", + "stem_exclusion": ["otorite", "onay"] + } + } + } + } +} +``` + +## 土耳其语分析器 internals + +`turkish` 分析器使用以下组件构建: + +- 分词器: `standard` + +- 词元过滤器: + - apostrophe + - lowercase (Turkish) + - stop (Turkish) + - keyword + - stemmer (Turkish) + +## 自定义土耳其语分析器 + +您可以使用以下命令创建自定义土耳其语分析器: + +```json +PUT /turkish-index +{ + "settings": { + "analysis": { + "filter": { + "turkish_stop": { + "type": "stop", + "stopwords": "_turkish_" + }, + "turkish_stemmer": { + "type": "stemmer", + "language": "turkish" + }, + "turkish_lowercase": { + "type": "lowercase", + "language": "turkish" + }, + "turkish_keywords": { + "type": "keyword_marker", + "keywords": [] + } + }, + "analyzer": { + "turkish_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "apostrophe", + "turkish_lowercase", + "turkish_stop", + "turkish_keywords", + "turkish_stemmer" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "turkish_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /turkish-index/_analyze +{ + "field": "content", + "text": "Öğrenciler Türk üniversitelerinde öğrenim görüyor. Numara 123456." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "öğrenci","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0}, + {"token": "türk","start_offset": 11,"end_offset": 15,"type": "<ALPHANUM>","position": 1}, + {"token": "üniversite","start_offset": 16,"end_offset": 33,"type": "<ALPHANUM>","position": 2}, + {"token": "öğre","start_offset": 34,"end_offset": 41,"type": "<ALPHANUM>","position": 3}, + {"token": "görüyor","start_offset": 42,"end_offset": 49,"type": "<ALPHANUM>","position": 4}, + {"token": "numar","start_offset": 51,"end_offset": 57,"type": "<ALPHANUM>","position": 5}, + {"token": "123456","start_offset": 58,"end_offset": 64,"type": "<NUM>","position": 6} + ] +} +``` diff --git a/i18n/zh/analyzers/language-analyzers/ukrainian.md b/i18n/zh/analyzers/language-analyzers/ukrainian.md new file mode 100644 index 00000000..5f0cafa2 --- /dev/null +++ b/i18n/zh/analyzers/language-analyzers/ukrainian.md @@ -0,0 +1,71 @@ +--- +title: 乌克兰语 +--- + +# 乌克兰语分析器 + +The Ukrainian language analyzer (`ukrainian`) provides analysis for Ukrainian text. This analyzer is part of the `analysis-ukrainian` plugin, which must be installed before use. + +## Installing the plugin + +Before you can use the Ukrainian analyzer, you must install the `analysis-ukrainian` plugin by running the following command: + +```bash +./bin/opensearch-plugin install analysis-ukrainian +``` + +For more information, see [Additional plugins](/install-and-configure/additional-plugins/): Complete list of available OpenSearch plugins. + +## Using the Ukrainian analyzer + +To use the Ukrainian analyzer when you map an index, specify the `ukrainian` value in the analyzer field: + +```json +PUT my-index +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "ukrainian" + } + } + } +} +``` + +## Ukrainian language processing + +The Ukrainian analyzer processes text using the following approach: + +1. **Tokenization**: Splits text into individual words. +2. **Stop word removal**: Removes common Ukrainian stop words like "і", "в", "з", "для", "та", and so on. +3. **Morphological analysis**: Generates various word forms and stems for Ukrainian words. +4. **Case normalization**: Handles Ukrainian text appropriately. + +The Ukrainian analyzer uses sophisticated morphological analysis that can generate multiple forms of words to improve search recall. Unlike some other language analyzers, the Ukrainian plugin does not expose individual token filters for custom configuration. + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST _analyze +{ + "analyzer": "ukrainian", + "text": "Я програміст і працюю з OpenSearch в Україні" +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + {"token": "програміст", "start_offset": 2, "end_offset": 12, "type": "<ALPHANUM>", "position": 1}, + {"token": "працювати", "start_offset": 15, "end_offset": 21, "type": "<ALPHANUM>", "position": 3}, + {"token": "opensearch", "start_offset": 24, "end_offset": 34, "type": "<ALPHANUM>", "position": 5}, + {"token": "Україна", "start_offset": 37, "end_offset": 44, "type": "<ALPHANUM>", "position": 7} + ] +} +``` diff --git a/i18n/zh/analyzers/stemming.md b/i18n/zh/analyzers/stemming.md new file mode 100644 index 00000000..ba29846a --- /dev/null +++ b/i18n/zh/analyzers/stemming.md @@ -0,0 +1,155 @@ +--- +title: 词干提取 +--- + +# 词干提取 + +词干提取是将单词简化为其词根或基本形式(称为_词干_)的过程。此技术确保在搜索操作期间匹配单词的不同变体。例如,单词"running"、"runner"和"ran"都可以简化为词干"run",从而允许对这些术语中的任何一个的搜索返回相关结果。 + +在自然语言中,由于变位、复数化或派生,单词通常以各种形式出现。词干提取通过以下方式改进搜索操作: + +- **提高搜索召回率**:通过将不同的单词形式匹配到共同的词干,词干提取增加了检索到的相关文档数量。 +- **减少索引大小**:仅存储单词的词干版本可以减少搜索索引的总体大小。 + +词干提取是使用[分析器](/analyzers/#analyzers)中的词元过滤器配置的。分析器包含以下组件: + +1. **字符过滤器**:在分词之前修改字符流。 +2. **分词器**:将文本拆分为词元(通常是单词)。 +3. **词元过滤器**:在分词后修改词元,例如,通过应用词干提取。 + +## 使用内置词元过滤器的词干提取示例 + +要实现词干提取,您可以配置内置词元过滤器,例如 [`porter_stem`](/analyzers/token-filters/porter-stem) 或 [`kstem`](/analyzers/token-filters/kstem) 过滤器。 + +[Porter 词干提取算法](https://snowballstem.org/algorithms/porter/stemmer.html)是用于英语的常见算法词干提取器。 + +### 创建带有自定义分析器的索引 + +以下示例请求创建名为 `my_stemming_index` 的新索引,并使用 [`porter_stem`](/analyzers/token-filters/porter-stem) 词元过滤器配置分析器: + +```json +PUT /my_stemming_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_stemmer_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "porter_stem" + ] + } + } + } + } +} +``` + +此配置包括以下内容: + +- [`standard`](/analyzers/tokenizers/standard) 分词器根据单词边界将文本拆分为术语。 +- [`lowercase`](/analyzers/token-filters/lowercase) 过滤器将所有词元转换为小写。 +- [`porter_stem`](/analyzers/token-filters/porter-stem) 过滤器将单词简化为其词根形式。 + +### 测试分析器 + +要检查词干提取操作,请使用之前配置的自定义分析器分析示例文本: + +```json +POST /my_stemming_index/_analyze +{ + "analyzer": "my_stemmer_analyzer", + "text": "The runners are running swiftly." +} +``` + +响应包含生成的词元: + +```json +{ + "tokens": [ + { + "token": "the", + "start_offset": 0, + "end_offset": 3, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "runner", + "start_offset": 4, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "ar", + "start_offset": 12, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "run", + "start_offset": 16, + "end_offset": 23, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "swiftli", + "start_offset": 24, + "end_offset": 31, + "type": "<ALPHANUM>", + "position": 4 + } + ] +} +``` + +## 词干提取器类别 + +您可以配置属于以下两个类别的词干提取器: + +- [算法词干提取器](/analyzers/stemming#algorithmic-stemmers) +- [词典词干提取器](/analyzers/stemming#dictionary-stemmers) + +### 算法词干提取器 + +算法词干提取器应用预定义的规则来系统地去除单词的词缀(前缀和后缀),将它们简化为词干。以下词元过滤器使用算法词干提取器: + +- [`porter_stem`](/analyzers/token-filters/porter-stem):应用 Porter 词干提取算法来去除常见后缀并将单词简化为其词干。例如,"running"变成"run"。 + +- [`kstem`](/analyzers/token-filters/kstem):为英语设计的轻量级词干提取器,将算法词干提取与内置词典相结合。它将复数形式简化为单数形式,将动词时态转换为其基本形式,并去除常见的派生词尾。 + +- [`stemmer`](/analyzers/token-filters/stemmer):为各种语言(包括英语)提供算法词干提取,并为不同的词干提取算法(如 `light_english`、`minimal_english` 和 `porter2`)提供选项。 + +- [`snowball`](/analyzers/token-filters/snowball):应用 Snowball 算法为多种语言(包括英语、法语、德语和其他语言)提供高效准确的词干提取。 + +### 词典词干提取器 + +词典词干提取器依赖于广泛的词典将单词映射到其词根形式,从而有效地对不规则单词进行词干提取。它们在预编译的列表中查找每个单词以找到其相应的词干。此操作更消耗资源,但对于不规则单词以及可能看起来具有相似词干但含义非常不同的单词,通常会产生更好的结果。 + +词典词干提取器最突出的例子是 [`hunspell`](/analyzers/token-filters/hunspell) 词元过滤器,它使用 Hunspell——一个在许多开源应用程序中使用的拼写检查引擎。 + +### 注意事项 +在选择词干提取器时,请注意以下注意事项: + +- 当处理速度和内存效率是优先事项且语言具有相对规则的形态模式时,算法词干提取器是合适的。 +- 当准确处理不规则单词形式至关重要且有资源支持增加的内存使用量和处理时间时,词典词干提取器是理想的。 + +### 其他词干提取配置 + +尽管"organize"和"organic"共享一个共同的语言词根,导致词干提取器对两者都产生"organ",但它们的概念差异是显著的。在实际搜索场景中,这个共享的词根可能导致搜索结果中返回不相关的匹配项。 + +您可以使用以下方法解决这些挑战: + +- **显式词干提取覆盖**:您可以定义特定的词干提取规则,而不是仅依赖于算法词干提取。使用 [`stemmer_override`](/analyzers/token-filters/stemmer-override) 可以确保"organize"保持不变,而"organic"则简化为"organ"。这提供了对术语最终形式的细粒度控制。 + +- **关键词保留**:为了保持重要术语的完整性,您可以使用 [`keyword_marker`](/analyzers/token-filters/keyword-marker) 词元过滤器。此过滤器将特定单词指定为关键词,防止后续词干提取器过滤器更改它们。在此示例中,您可以将"organize"标记为关键词,确保它按其显示方式精确索引。 + +- **条件词干提取控制**:[condition](/analyzers/token-filters/condition) 词元过滤器使您能够建立规则来确定是否应对术语进行词干提取。这些规则可以基于各种标准,例如术语在预定义列表中的存在。 + +- **特定语言的术语排除**:对于内置语言分析器,[`stem_exclusion`](/analyzers/language-analyzers/english#stem-exclusion) 参数提供了一种指定应免于词干提取的单词的方法。例如,您可以将"organize"添加到 `stem_exclusion` 列表中,防止分析器对其进行词干提取。这对于在给定语言中保留特定术语的不同含义很有用。 diff --git a/i18n/zh/analyzers/supported-analyzers/dl-model-analyzers.md b/i18n/zh/analyzers/supported-analyzers/dl-model-analyzers.md new file mode 100644 index 00000000..a2f0977b --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/dl-model-analyzers.md @@ -0,0 +1,135 @@ +--- +title: 深度学习模型分析器 +--- + +# DL model analyzers + +Deep learning (DL) model analyzers are designed to work with [neural sparse search](/vector-search/ai-search/neural-sparse-search/). They implement the same tokenization rules used by machine learning (ML) models, ensuring compatibility with neural sparse search. While traditional OpenSearch analyzers use standard rule-based tokenization (like white space or word boundaries), DL model analyzers use tokenization rules that match specific ML models (like the BERT WordPiece tokenization scheme). This consistent tokenization between indexed documents and search queries is essential for neural sparse search to work correctly. + +OpenSearch supports the following DL model analyzers: + +* [`bert-uncased`](#the-bert-uncased-analyzer): An analyzer based on the [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) model tokenizer. +* [`mbert-uncased`](#the-mbert-uncased-analyzer): A multilingual analyzer based on the [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased) model tokenizer. + +::: tip TIP +For Japanese text, use the [`mbert-uncased` analyzer](#the-mbert-uncased-analyzer) instead: the `bert-uncased` vocabulary is missing many kana characters, so many Japanese words, such as `パソコン`, are tokenized as `[UNK]` and match no documents. +::: + +## Usage considerations + +When using the DL model analyzers, keep the following considerations in mind: + +* These analyzers use lazy loading. The first call to these analyzers may take longer because dependencies and related resources are loaded. +* The tokenizers follow the same rules as their corresponding model tokenizers. + +## The bert-uncased analyzer + +The `bert-uncased` analyzer is based on the [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) model and tokenizes text according to the BERT WordPiece tokenization scheme. This analyzer is particularly useful for English language text. + +To analyze text with the `bert-uncased` analyzer, specify it in the `analyzer` field: + +```json +POST /_analyze +{ + "analyzer": "bert-uncased", + "text": "It's fun to contribute to OpenSearch!" +} +``` + +## The mbert-uncased analyzer + +The `mbert-uncased` analyzer is based on the [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased) model, which supports tokenization across multiple languages. This makes it suitable for applications dealing with multilingual content. + +To analyze multilingual text, specify the `mbert-uncased` analyzer in the request: + +```json +POST /_analyze +{ + "analyzer": "mbert-uncased", + "text": "It's fun to contribute to OpenSearch!" +} +``` + +### Half-width and full-width characters + +Like the model tokenizer, the `mbert-uncased` analyzer does not normalize half-width and full-width forms. For example, half-width `カメラ` is tokenized as `[UNK]`, so it does not match full-width `カメラ`, and full-width `ABC` does not match `abc`. The analyzer also removes Japanese voiced sound marks (dakuten and handakuten), so `パ` and `ハ` produce the same token. + +To match half-width and full-width forms, apply Unicode Normalization Form Compatibility Composition (NFKC) to both documents and queries. Normalize documents before they are encoded, for example, by using a `script` processor in the ingest pipeline: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline-sparse +{ + "processors": [ + { + "script": { + "source": "ctx.passage_text = Normalizer.normalize(ctx.passage_text, Normalizer.Form.NFKC)" + } + }, + { + "sparse_encoding": { + "model_id": "<model_id>", + "field_map": { + "passage_text": "passage_embedding" + } + } + } + ] +} +``` + +To normalize queries, create a custom analyzer that applies the [ICU normalization character filter](/analyzers/character-filters/icu-normalization) before the `mbert-uncased` tokenizer. The character filter requires the [`analysis-icu` plugin](/analyzers/language-analyzers/icu#installing-the-icu-plugin): + +```json +PUT /my-nlp-index +{ + "settings": { + "default_pipeline": "nlp-ingest-pipeline-sparse", + "analysis": { + "char_filter": { + "nfkc": { + "type": "icu_normalizer", + "name": "nfkc", + "mode": "compose" + } + }, + "analyzer": { + "mbert_nfkc": { + "type": "custom", + "char_filter": ["nfkc"], + "tokenizer": "mbert-uncased" + } + } + } + }, + "mappings": { + "properties": { + "passage_text": { + "type": "text" + }, + "passage_embedding": { + "type": "rank_features" + } + } + } +} +``` + +Then specify the custom analyzer in the `neural_sparse` query: + +```json +GET /my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "カメラ", + "analyzer": "mbert_nfkc" + } + } + } +} +``` + +## 示例 + +For a complete example of using DL model analyzers in neural sparse search queries, see [Generating sparse vector embeddings automatically](/vector-search/ai-search/neural-sparse-with-pipelines/). diff --git a/i18n/zh/analyzers/supported-analyzers/fingerprint.md b/i18n/zh/analyzers/supported-analyzers/fingerprint.md new file mode 100644 index 00000000..b105d1dc --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/fingerprint.md @@ -0,0 +1,108 @@ +--- +title: 指纹 analyzer +--- + +# Fingerprint analyzer + +The `fingerprint` analyzer creates a text fingerprint. The analyzer sorts and deduplicates the terms (tokens) generated from the input and then concatenates them using a separator. It is commonly used for data deduplication because it produces the same output for similar inputs containing the same words, regardless of word order. + +The `fingerprint` analyzer comprises the following components: + +- Standard tokenizer +- Lowercase token filter +- ASCII folding token filter +- Stop token filter +- Fingerprint token filter + +## 参数 + +The `fingerprint` analyzer can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`separator` | 可选 | String | Specifies the character used to concatenate the terms after they have been tokenized, sorted, and deduplicated. Default is an empty space (` `). +`max_output_size` | 可选 | Integer | Defines the maximum size of the output token. If the concatenated fingerprint exceeds this size, it will be truncated. Default is `255`. +`stopwords` | 可选 | String or list of strings | A custom or predefined list of stopwords. Default is `_none_`. +`stopwords_path` | 可选 | String | The path (absolute or relative to the config directory) to the file containing a list of stopwords. + +## 示例 + +Use the following command to create an index named `my_custom_fingerprint_index` with a `fingerprint` analyzer: + +```json +PUT /my_custom_fingerprint_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_fingerprint_analyzer": { + "type": "fingerprint", + "separator": "-", + "max_output_size": 50, + "stopwords": ["to", "the", "over", "and"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_fingerprint_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_custom_fingerprint_index/_analyze +{ + "analyzer": "my_custom_fingerprint_analyzer", + "text": "The slow turtle swims over to the dog" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "dog-slow-swims-turtle", + "start_offset": 0, + "end_offset": 37, + "type": "fingerprint", + "position": 0 + } + ] +} +``` + +## Further customization + +If further customization is needed, you can define an analyzer with additional `fingerprint` analyzer components: + +```json +PUT /custom_fingerprint_analyzer +{ + "settings": { + "analysis": { + "analyzer": { + "custom_fingerprint": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "asciifolding", + "fingerprint" + ] + } + } + } + } +} +``` diff --git a/i18n/zh/analyzers/supported-analyzers/index.md b/i18n/zh/analyzers/supported-analyzers/index.md new file mode 100644 index 00000000..dca5c2b5 --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/index.md @@ -0,0 +1,36 @@ +--- +title: Analyzers +--- + +# Analyzers + +Analyzers transform text into tokens during indexing and search. OpenSearch provides built-in analyzers for common use cases and supports custom analyzers that combine character filters, tokenizers, and token filters. + +## Built-in analyzers + +The following table lists the built-in analyzers that OpenSearch provides. The last column of the table contains the result of applying the analyzer to the string `It’s fun to contribute a brand-new PR or 2 to OpenSearch!`. + +Analyzer | Analysis performed | Analyzer output +:--- | :--- | :--- +[**Standard**](/analyzers/supported-analyzers/standard) (default) | - Parses strings into tokens at word boundaries <br> - Removes most punctuation <br> - Converts tokens to lowercase | [`it’s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] +[**Simple**](/analyzers/supported-analyzers/simple) | - Parses strings into tokens on any non-letter character <br> - Removes non-letter characters <br> - Converts tokens to lowercase | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `to`, `opensearch`] +[**White space**](/analyzers/supported-analyzers/whitespace) | - Parses strings into tokens on white space | [`It’s`, `fun`, `to`, `contribute`, `a`,`brand-new`, `PR`, `or`, `2`, `to`, `OpenSearch!`] +[**Stop**](/analyzers/supported-analyzers/stop) | - Parses strings into tokens on any non-letter character <br> - Removes non-letter characters <br> - Removes stop words <br> - Converts tokens to lowercase | [`s`, `fun`, `contribute`, `brand`, `new`, `pr`, `opensearch`] +[**Keyword**](/analyzers/supported-analyzers/keyword) (no-op) | - Outputs the entire string unchanged | [`It’s fun to contribute a brand-new PR or 2 to OpenSearch!`] +[**Pattern**](/analyzers/supported-analyzers/pattern)| - Parses strings into tokens using regular expressions <br> - Supports converting strings to lowercase <br> - Supports removing stop words | [`it`, `s`, `fun`, `to`, `contribute`, `a`,`brand`, `new`, `pr`, `or`, `2`, `to`, `opensearch`] +[**Language**](/analyzers/language-analyzers/) | Performs analysis specific to a certain language (for example, `english`). | [`fun`, `contribut`, `brand`, `new`, `pr`, `2`, `opensearch`] +[**Fingerprint**](/analyzers/supported-analyzers/fingerprint) | - Parses strings on any non-letter character <br> - Normalizes characters by converting them to ASCII <br> - Converts tokens to lowercase <br> - Sorts, deduplicates, and concatenates tokens into a single token <br> - Supports removing stop words | [`2 a brand contribute fun it's new opensearch or pr to`] <br> Note that the apostrophe was converted to its ASCII counterpart. +[**DL model**](/analyzers/supported-analyzers/dl-model-analyzers) | Use ML model tokenization rules for [neural sparse search](/vector-search/ai-search/neural-sparse-search/). | Model-based tokens + +## Language analyzers + +OpenSearch supports multiple language analyzers. For more information, see [Language analyzers](/analyzers/language-analyzers/). + +## Additional analyzers + +The following table lists the additional analyzers that OpenSearch supports. + +| Analyzer | Analysis performed | +|:---------------|:---------------------------------------------------------------------------------------------------------| +| [`phone`](/analyzers/supported-analyzers/phone-analyzers#the-phone-analyzer) | An [index analyzer](/analyzers/index-analyzers) for parsing phone numbers. | +| [`phone-search`](/analyzers/supported-analyzers/phone-analyzers#the-phone-search-analyzer) | A [search analyzer](/analyzers/search-analyzers) for parsing phone numbers. | diff --git a/i18n/zh/analyzers/supported-analyzers/keyword.md b/i18n/zh/analyzers/supported-analyzers/keyword.md new file mode 100644 index 00000000..7ea0b290 --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/keyword.md @@ -0,0 +1,72 @@ +--- +title: 关键词 analyzer +--- + +# Keyword analyzer + +The `keyword` analyzer doesn't tokenize text at all. Instead, it treats the entire input as a single token and does not break it into individual tokens. The `keyword` analyzer is often used for fields containing email addresses, URLs, or product IDs and in other cases where tokenization is not desirable. + +## 示例 + +Use the following command to create an index named `my_keyword_index` with a `keyword` analyzer: + +```json +PUT /my_keyword_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "keyword" + } + } + } +} +``` + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to the `keyword` analyzer: + +```json +PUT /my_custom_keyword_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_keyword_analyzer": { + "tokenizer": "keyword" + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_custom_keyword_index/_analyze +{ + "analyzer": "my_keyword_analyzer", + "text": "Just one token" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Just one token", + "start_offset": 0, + "end_offset": 14, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/supported-analyzers/pattern.md b/i18n/zh/analyzers/supported-analyzers/pattern.md new file mode 100644 index 00000000..44d16aa1 --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/pattern.md @@ -0,0 +1,225 @@ +--- +title: 模式 analyzer +--- + +# Pattern analyzer + +The `pattern` analyzer allows you to define a custom analyzer that uses a regular expression (regex) to split input text into tokens. The regex matches the separators between tokens, not the tokens themselves. It also provides options for applying regex flags, converting tokens to lowercase, and filtering out stopwords. + +The `pattern` analyzer consists of a [`pattern`](/analyzers/tokenizers/pattern) tokenizer followed by the [`lowercase`](/analyzers/token-filters/lowercase) and [`stop`](/analyzers/token-filters/stop) token filters. The `stop` filter removes no tokens unless you specify `stopwords` or `stopwords_path`. + +## 参数 + +The `pattern` analyzer can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`pattern` | 可选 | String | A [Java regular expression](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) used to tokenize the input. Default is `\W+`. +`flags` | 可选 | String | A string containing pipe-separated [Java regex flags](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#field.summary) that modify the behavior of the regular expression. +`lowercase` | 可选 | Boolean | Whether to convert tokens to lowercase. Default is `true`. +`stopwords` | 可选 | String or list of strings | A string specifying a predefined list of stopwords (such as `_english_`) or an array specifying a custom list of stopwords. Default is `_none_`. +`stopwords_path` | 可选 | String | The path (absolute or relative to the config directory) to the file containing a list of stopwords. + +::: danger WARNING +A poorly written regular expression can make analysis very slow and, in extreme cases, cause a `StackOverflowError` that stops the node. Avoid patterns that can match the same text in many ways, such as nested quantifiers like `(a+)+`, and test new patterns on representative text using the [Analyze API](/api-reference/analyze-apis). +::: + +## 示例 + +Use the following command to create an index named `my_pattern_index` with a `pattern` analyzer: + +```json +PUT /my_pattern_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_pattern_analyzer": { + "type": "pattern", + "pattern": "\\W+", + "lowercase": true, + "stopwords": ["and", "is"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_pattern_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_pattern_index/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "OpenSearch is fast and scalable" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "fast", + "start_offset": 14, + "end_offset": 18, + "type": "word", + "position": 2 + }, + { + "token": "scalable", + "start_offset": 23, + "end_offset": 31, + "type": "word", + "position": 4 + } + ] +} +``` + +## 示例: Splitting camel case identifiers + +Because the regex matches separators, it can also match the zero-width position between two characters. This lets you split identifiers in source code, such as class and method names, into separate words. The following pattern contains five alternatives that split text at runs of characters that are neither letters nor digits, between a lowercase and an uppercase letter, before the last letter of an uppercase acronym that is followed by a lowercase letter, and between letters and digits: + +```json +PUT /source-code +{ + "settings": { + "analysis": { + "analyzer": { + "camel_case_analyzer": { + "type": "pattern", + "pattern": "[^\\p{L}\\p{N}]+|(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})|(?<=\\p{L})(?=\\p{N})|(?<=\\p{N})(?=\\p{L})" + } + } + } + } +} +``` + +In JSON, each backslash in the pattern must be escaped as `\\`. + +Use the following request to analyze a class and method name: + +```json +POST /source-code/_analyze +{ + "analyzer": "camel_case_analyzer", + "text": "XMLHttpRequest2Handler.sendJSONPayload" +} +``` + +响应包含 the individual words, converted to lowercase: + +```json +{ + "tokens": [ + { + "token": "xml", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "http", + "start_offset": 3, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "request", + "start_offset": 7, + "end_offset": 14, + "type": "word", + "position": 2 + }, + { + "token": "2", + "start_offset": 14, + "end_offset": 15, + "type": "word", + "position": 3 + }, + { + "token": "handler", + "start_offset": 15, + "end_offset": 22, + "type": "word", + "position": 4 + }, + { + "token": "send", + "start_offset": 23, + "end_offset": 27, + "type": "word", + "position": 5 + }, + { + "token": "json", + "start_offset": 27, + "end_offset": 31, + "type": "word", + "position": 6 + }, + { + "token": "payload", + "start_offset": 31, + "end_offset": 38, + "type": "word", + "position": 7 + } + ] +} +``` + +## Adding token filters to a pattern analyzer + +To apply token filters that the `pattern` analyzer does not provide, re-create it as a custom analyzer and add the filters to its `filter` array. 以下请求 creates a custom analyzer that produces the same tokens as the default `pattern` analyzer: + +```json +PUT /custom-pattern-index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "\\W+" + } + }, + "analyzer": { + "rebuilt_pattern": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer", + "filter": [ + "lowercase" + ] + } + } + } + } +} +``` + +Add more token filters after `lowercase` in the `filter` array. To remove stopwords, add a [`stop`](/analyzers/token-filters/stop) filter. diff --git a/i18n/zh/analyzers/supported-analyzers/phone-analyzers.md b/i18n/zh/analyzers/supported-analyzers/phone-analyzers.md new file mode 100644 index 00000000..7b99db8c --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/phone-analyzers.md @@ -0,0 +1,120 @@ +--- +title: 电话 number analyzers +--- + +# Phone number analyzers + +The `analysis-phonenumber` plugin provides analyzers and tokenizers for parsing phone numbers. A dedicated analyzer is required because parsing phone numbers is a non-trivial task (even though it might seem trivial at first glance). For common misconceptions regarding phone number parsing, see [Falsehoods programmers believe about phone numbers](https://github.com/google/libphonenumber/blob/master/FALSEHOODS.md). + +OpenSearch supports the following phone number analyzers: + +* [`phone`](#the-phone-analyzer): An [index analyzer](/analyzers/index-analyzers) to use at indexing time. +* [`phone-search`](#the-phone-search-analyzer): A [search analyzer](/analyzers/search-analyzers) to use at search time. + +Internally, the plugin uses the [`libphonenumber`](https://github.com/google/libphonenumber) library and follows its parsing rules. + +::: info NOTE +The phone number analyzers are not meant to find phone numbers in larger texts. Instead, you should use them on fields that only contain phone numbers. +::: + +## Installing the plugin + +Before you can use the phone number analyzers, you must install the `analysis-phonenumber` plugin by running the following command: + +```sh +./bin/opensearch-plugin install analysis-phonenumber +``` + +## Specifying a default region + +You can optionally specify a default region for parsing phone numbers by providing the `phone-region` parameter within the analyzer. Valid phone regions are represented by ISO 3166 country codes. For more information, see [List of ISO 3166 country codes](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes). + +When tokenizing phone numbers containing the international calling prefix `+`, the default region is irrelevant. However, for phone numbers that use a national prefix for international numbers (for example, `001` instead of `+1` to dial Northern America from most European countries), the region needs to be provided. You can also properly index local phone numbers with no international prefix by specifying the region. + +## 示例 + +以下请求 creates an index containing one field that ingests phone numbers for Switzerland (region code `CH`): + +```json +PUT /example-phone +{ + "settings": { + "analysis": { + "analyzer": { + "phone-ch": { + "type": "phone", + "phone-region": "CH" + }, + "phone-search-ch": { + "type": "phone-search", + "phone-region": "CH" + } + } + } + }, + "mappings": { + "properties": { + "phone_number": { + "type": "text", + "analyzer": "phone-ch", + "search_analyzer": "phone-search-ch" + } + } + } +} +``` + +## The phone analyzer + +The `phone` analyzer generates n-grams based on the given phone number. A (fictional) Swiss phone number containing an international calling prefix can be parsed with or without the Swiss-specific phone region. Thus, the following two requests will produce the same result: + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone-ch", + "text" : "+41 60 555 12 34" +} +``` + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone", + "text" : "+41 60 555 12 34" +} +``` + +响应包含 the generated n-grams: + +```json +["+41 60 555 12 34", "6055512", "41605551", "416055512", "6055", "41605551234", ...] +``` + +However, if you specify the phone number without the international calling prefix `+` (either by using `0041` or omitting +the international calling prefix altogether), then only the analyzer configured with the correct phone region can parse the number: + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone-ch", + "text" : "060 555 12 34" +} +``` + +## The phone-search analyzer + +In contrast, the `phone-search` analyzer does not create n-grams and only issues some basic tokens. For example, send the following request and specify the `phone-search` analyzer: + +```json +GET /example-phone/_analyze +{ + "analyzer" : "phone-search", + "text" : "+41 60 555 12 34" +} +``` + +响应包含 the following tokens: + +```json +["+41 60 555 12 34", "41 60 555 12 34", "41605551234", "605551234", "41"] +``` diff --git a/i18n/zh/analyzers/supported-analyzers/simple.md b/i18n/zh/analyzers/supported-analyzers/simple.md new file mode 100644 index 00000000..c35fc3b8 --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/simple.md @@ -0,0 +1,93 @@ +--- +title: 简单 analyzer +--- + +# Simple analyzer + +The `simple` analyzer is a very basic analyzer that breaks text into terms at non-letter characters and lowercases the terms. Unlike the `standard` analyzer, the `simple` analyzer treats everything except for alphabetic characters as delimiters, meaning that it does not recognize numbers, punctuation, or special characters as part of the tokens. + +## 示例 + +Use the following command to create an index named `my_simple_index` with a `simple` analyzer: + +```json +PUT /my_simple_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "simple" + } + } + } +} +``` + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to a `simple` analyzer with an added `html_strip` character filter: + +```json +PUT /my_custom_simple_index +{ + "settings": { + "analysis": { + "char_filter": { + "html_strip": { + "type": "html_strip" + } + }, + "tokenizer": { + "my_lowercase_tokenizer": { + "type": "lowercase" + } + }, + "analyzer": { + "my_custom_simple_analyzer": { + "type": "custom", + "char_filter": ["html_strip"], + "tokenizer": "my_lowercase_tokenizer", + "filter": ["lowercase"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_simple_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_custom_simple_index/_analyze +{ + "analyzer": "my_custom_simple_analyzer", + "text": "<p>The slow turtle swims over to dogs © 2024!</p>" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "the","start_offset": 3,"end_offset": 6,"type": "word","position": 0}, + {"token": "slow","start_offset": 7,"end_offset": 11,"type": "word","position": 1}, + {"token": "turtle","start_offset": 12,"end_offset": 18,"type": "word","position": 2}, + {"token": "swims","start_offset": 19,"end_offset": 24,"type": "word","position": 3}, + {"token": "over","start_offset": 25,"end_offset": 29,"type": "word","position": 4}, + {"token": "to","start_offset": 30,"end_offset": 32,"type": "word","position": 5}, + {"token": "dogs","start_offset": 33,"end_offset": 37,"type": "word","position": 6} + ] +} +``` diff --git a/i18n/zh/analyzers/supported-analyzers/standard.md b/i18n/zh/analyzers/supported-analyzers/standard.md new file mode 100644 index 00000000..916363d3 --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/standard.md @@ -0,0 +1,113 @@ +--- +title: 标准 analyzer +--- + +# Standard analyzer + +The `standard` analyzer is the built-in default analyzer used for general-purpose full-text search in OpenSearch. It is designed to provide consistent, language-agnostic text processing by efficiently breaking down text into searchable terms. + +The `standard` analyzer performs the following operations: + +- **Tokenization**: Uses the [`standard`](/analyzers/tokenizers/standard) tokenizer, which splits text into words based on Unicode text segmentation rules, handling spaces, punctuation, and common delimiters. +- **Lowercasing**: Applies the [`lowercase`](/analyzers/token-filters/lowercase) token filter to convert all tokens to lowercase, ensuring consistent matching regardless of input case. + +This combination makes the `standard` analyzer ideal for indexing a wide range of natural language content without needing language-specific customizations. + +## 示例: Creating an index with the standard analyzer + +You can assign the `standard` analyzer to a text field when creating an index: + +```json +PUT /my_standard_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "standard" + } + } + } +} +``` + +## 参数 + +The `standard` analyzer supports the following optional parameters. + +| 参数 | 数据类型 | Default | 描述 | +|:----------|:-----|:--------|:------------| +| `max_token_length` | Integer | `255` | The maximum length that a token can be before it is split. | +| `stopwords` | String or list of strings | None | A list of stopwords or a [predefined stopword set for a language](/analyzers/token-filters/stop#predefined-stopword-sets-by-language) to remove during analysis. For example, `_english_`. | +| `stopwords_path` | String | None | The path to a file containing stopwords to be used during analysis. | + +::: info NOTE +Only use one of the parameters `stopwords` or `stopwords_path`. If both are used, no error is returned but only the `stopwords` parameter is applied. +::: + +## 示例: Analyzer with parameters + +The following example creates a `products` index and configures the `max_token_length` and `stopwords` parameters: + +```json +PUT /animals +{ + "settings": { + "analysis": { + "analyzer": { + "my_manual_stopwords_analyzer": { + "type": "standard", + "max_token_length": 10, + "stopwords": [ + "the", "is", "and", "but", "an", "a", "it" + ] + } + } + } + } +} +``` + +Use the following `_analyze` API request to see how the `my_manual_stopwords_analyzer` processes text: + +```json +POST /animals/_analyze +{ + "analyzer": "my_manual_stopwords_analyzer", + "text": "The Turtle is Large but it is Slow" +} +``` + +The returned tokens: + +- Have been split on spaces. +- Have been lowercased. +- Have had stopwords removed. + +```json +{ + "tokens": [ + { + "token": "turtle", + "start_offset": 4, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "large", + "start_offset": 14, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "slow", + "start_offset": 30, + "end_offset": 34, + "type": "<ALPHANUM>", + "position": 7 + } + ] +} +``` diff --git a/i18n/zh/analyzers/supported-analyzers/stop.md b/i18n/zh/analyzers/supported-analyzers/stop.md new file mode 100644 index 00000000..257b7c3e --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/stop.md @@ -0,0 +1,169 @@ +--- +title: 停用词 analyzer +--- + +# Stop analyzer + +The `stop` analyzer removes a predefined list of stopwords. This analyzer consists of a `lowercase` tokenizer and a `stop` token filter. + +## 参数 + +You can configure a `stop` analyzer with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`stopwords` | 可选 | String or list of strings | A string specifying a predefined list of stopwords (such as `_english_`) or an array specifying a custom list of stopwords. Default is `_english_`. +`stopwords_path` | 可选 | String | The path (absolute or relative to the config directory) to the file containing a list of stopwords. + +## 示例 + +Use the following command to create an index named `my_stop_index` with a `stop` analyzer: + +```json +PUT /my_stop_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "stop" + } + } + } +} +``` + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to a `stop` analyzer: + +```json +PUT /my_custom_stop_analyzer_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_stop_analyzer": { + "tokenizer": "lowercase", + "filter": [ + "stop" + ] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_stop_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_custom_stop_analyzer_index/_analyze +{ + "analyzer": "my_custom_stop_analyzer", + "text": "The large turtle is green and brown" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "large", + "start_offset": 4, + "end_offset": 9, + "type": "word", + "position": 1 + }, + { + "token": "turtle", + "start_offset": 10, + "end_offset": 16, + "type": "word", + "position": 2 + }, + { + "token": "green", + "start_offset": 20, + "end_offset": 25, + "type": "word", + "position": 4 + }, + { + "token": "brown", + "start_offset": 30, + "end_offset": 35, + "type": "word", + "position": 6 + } + ] +} +``` + +# Specifying stopwords + +The following example request specifies a custom list of stopwords: + +```json +PUT /my_new_custom_stop_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_stop_analyzer": { + "type": "stop", + "stopwords": ["is", "and", "was"] + } + } + } + }, + "mappings": { + "properties": { + "description": { + "type": "text", + "analyzer": "my_custom_stop_analyzer" + } + } + } +} +``` + +The following example request specifies a path to the file containing stopwords: + +```json +PUT /my_new_custom_stop_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_stop_analyzer": { + "type": "stop", + "stopwords_path": "stopwords.txt" + } + } + } + }, + "mappings": { + "properties": { + "description": { + "type": "text", + "analyzer": "my_custom_stop_analyzer" + } + } + } +} +``` + +In this example, the file is located in the config directory. You can also specify a full path to the file. diff --git a/i18n/zh/analyzers/supported-analyzers/whitespace.md b/i18n/zh/analyzers/supported-analyzers/whitespace.md new file mode 100644 index 00000000..d78b0b31 --- /dev/null +++ b/i18n/zh/analyzers/supported-analyzers/whitespace.md @@ -0,0 +1,81 @@ +--- +title: White space analyzer +--- + +# White space analyzer + +The `whitespace` analyzer breaks text into tokens based only on white space characters (for example, spaces and tabs). It does not apply any transformations, such as lowercasing or removing stopwords, so the original case of the text is retained and punctuation is included as part of the tokens. + +## 示例 + +Use the following command to create an index named `my_whitespace_index` with a `whitespace` analyzer: + +```json +PUT /my_whitespace_index +{ + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "whitespace" + } + } + } +} +``` + +## Configuring a custom analyzer + +Use the following command to configure an index with a custom analyzer that is equivalent to a `whitespace` analyzer with an added `lowercase` character filter: + +```json +PUT /my_custom_whitespace_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_whitespace_analyzer": { + "type": "custom", + "tokenizer": "whitespace", + "filter": ["lowercase"] + } + } + } + }, + "mappings": { + "properties": { + "my_field": { + "type": "text", + "analyzer": "my_custom_whitespace_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_custom_whitespace_index/_analyze +{ + "analyzer": "my_custom_whitespace_analyzer", + "text": "The SLOW turtle swims away! 123" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "the","start_offset": 0,"end_offset": 3,"type": "word","position": 0}, + {"token": "slow","start_offset": 4,"end_offset": 8,"type": "word","position": 1}, + {"token": "turtle","start_offset": 9,"end_offset": 15,"type": "word","position": 2}, + {"token": "swims","start_offset": 16,"end_offset": 21,"type": "word","position": 3}, + {"token": "away!","start_offset": 22,"end_offset": 27,"type": "word","position": 4}, + {"token": "123","start_offset": 28,"end_offset": 31,"type": "word","position": 5} + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/apostrophe.md b/i18n/zh/analyzers/token-filters/apostrophe.md new file mode 100644 index 00000000..4c4ec618 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/apostrophe.md @@ -0,0 +1,113 @@ +--- +title: 撇号 +--- + +# Apostrophe token filter + +The `apostrophe` token filter's primary function is to remove possessive apostrophes and anything following them. This can be very useful in analyzing text in languages that rely heavily on apostrophes, such as Turkish, in which apostrophes separate the root word from suffixes, including possessive suffixes, case markers, and other grammatical endings. + +## 示例 + +The following example request creates a new index named `custom_text_index` with a custom analyzer configured in `settings` and used in `mappings`: + +```json +PUT /custom_text_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "apostrophe" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "custom_analyzer" + } + } + } +} +``` + +## 生成的词元 + +Use the following request to examine the tokens generated using the created analyzer: + +```json +POST /custom_text_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "John's car is faster than Peter's bike" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "john", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "car", + "start_offset": 7, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "faster", + "start_offset": 14, + "end_offset": 20, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "than", + "start_offset": 21, + "end_offset": 25, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "peter", + "start_offset": 26, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "bike", + "start_offset": 34, + "end_offset": 38, + "type": "<ALPHANUM>", + "position": 6 + } + ] +} +``` + +::: info NOTE +The built-in `apostrophe` token filter is not suitable for languages such as French, in which apostrophes are used at the beginning of words. For example, `"C'est l'amour de l'école"` will result in four tokens: "C", "l", "de", and "l". +::: diff --git a/i18n/zh/analyzers/token-filters/asciifolding.md b/i18n/zh/analyzers/token-filters/asciifolding.md new file mode 100644 index 00000000..d6d95348 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/asciifolding.md @@ -0,0 +1,128 @@ +--- +title: ASCII 折叠 +--- + +# ASCII folding token filter + +The `asciifolding` token filter converts non-ASCII characters to their closest ASCII equivalents. For example, *é* becomes *e*, *ü* becomes *u*, and *ñ* becomes *n*. This process is known as *transliteration*. + +The `asciifolding` token filter offers a number of benefits: + + - **Enhanced search flexibility**: Users often omit accents or special characters when entering queries. The `asciifolding` token filter ensures that such queries still return relevant results. + - **Normalization**: Standardizes the indexing process by ensuring that accented characters are consistently converted to their ASCII equivalents. + - **Internationalization**: Particularly useful for applications including multiple languages and character sets. + +::: danger WARNING +While the `asciifolding` token filter can simplify searches, it may also lead to the loss of specific information, particularly if the distinction between accented and non-accented characters in the dataset is significant. +::: + +## 参数 + +You can configure the `asciifolding` token filter using the `preserve_original` parameter. Setting this parameter to `true` keeps both the original token and its ASCII-folded version in the token stream. This can be particularly useful when you want to match both the original (with accents) and the normalized (without accents) versions of a term in a search query. Default is `false`. + +## 示例 + +The following example request creates a new index named `example_index` and defines an analyzer with the `asciifolding` filter and `preserve_original` parameter set to `true`: + +```json +PUT /example_index +{ + "settings": { + "analysis": { + "filter": { + "custom_ascii_folding": { + "type": "asciifolding", + "preserve_original": true + } + }, + "analyzer": { + "custom_ascii_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "custom_ascii_folding" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /example_index/_analyze +{ + "analyzer": "custom_ascii_analyzer", + "text": "Résumé café naïve coördinate" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "resume", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "résumé", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "cafe", + "start_offset": 7, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "café", + "start_offset": 7, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "naive", + "start_offset": 12, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "naïve", + "start_offset": 12, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "coordinate", + "start_offset": 18, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "coördinate", + "start_offset": 18, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 3 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/cjk-bigram.md b/i18n/zh/analyzers/token-filters/cjk-bigram.md new file mode 100644 index 00000000..78cebf4b --- /dev/null +++ b/i18n/zh/analyzers/token-filters/cjk-bigram.md @@ -0,0 +1,151 @@ +--- +title: CJK 二元 +--- + +# CJK bigram token filter + +The `cjk_bigram` token filter is designed specifically for processing East Asian languages, such as Chinese, Japanese, and Korean (CJK), which typically don't use spaces to separate words. A bigram is a sequence of two adjacent elements in a string of tokens, which can be characters or words. For CJK languages, bigrams help approximate word boundaries and capture significant character pairs that can convey meaning. + +## 参数 + +The `cjk_bigram` token filter can be configured with two parameters: `ignored_scripts` and `output_unigrams`. + +### ignored_scripts + +The `cjk-bigram` token filter ignores all non-CJK scripts (writing systems like Latin or Cyrillic) and tokenizes only CJK text into bigrams. Use this option to specify CJK scripts to be ignored. This option takes the following valid values: + +- `han`: The `han` script processes Han characters. [Han characters](https://simple.wikipedia.org/wiki/Chinese_characters) are logograms used in the written languages of China, Japan, and Korea. The filter can help with text processing tasks like tokenizing, normalizing, or stemming text written in Chinese, Japanese kanji, or Korean Hanja. + +- `hangul`: The `hangul` script processes Hangul characters, which are unique to the Korean language and do not exist in other East Asian scripts. + +- `hiragana`: The `hiragana` script processes hiragana, one of the two syllabaries used in the Japanese writing system. + Hiragana is typically used for native Japanese words, grammatical elements, and certain forms of punctuation. + +- `katakana`: The `katakana` script processes katakana, the other Japanese syllabary. + Katakana is mainly used for foreign loanwords, onomatopoeia, scientific names, and certain Japanese words. + +### output_unigrams + +This option, when set to `true`, outputs both unigrams (single characters) and bigrams. Default is `false`. + +## 示例 + +The following example request creates a new index named `devanagari_example_index` and defines an analyzer with the `cjk_bigram_filter` filter and `ignored_scripts` parameter set to `katakana`: + +```json +PUT /cjk_bigram_example +{ + "settings": { + "analysis": { + "analyzer": { + "cjk_bigrams_no_katakana": { + "tokenizer": "standard", + "filter": [ "cjk_bigrams_no_katakana_filter" ] + } + }, + "filter": { + "cjk_bigrams_no_katakana_filter": { + "type": "cjk_bigram", + "ignored_scripts": [ + "katakana" + ], + "output_unigrams": true + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /cjk_bigram_example/_analyze +{ + "analyzer": "cjk_bigrams_no_katakana", + "text": "東京タワーに行く" +} +``` + +Sample text: "東京タワーに行く" + + 東京 (Kanji for "Tokyo") + タワー (Katakana for "Tower") + に行く (Hiragana and Kanji for "go to") + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "東", + "start_offset": 0, + "end_offset": 1, + "type": "<SINGLE>", + "position": 0 + }, + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "<DOUBLE>", + "position": 0, + "positionLength": 2 + }, + { + "token": "京", + "start_offset": 1, + "end_offset": 2, + "type": "<SINGLE>", + "position": 1 + }, + { + "token": "タワー", + "start_offset": 2, + "end_offset": 5, + "type": "<KATAKANA>", + "position": 2 + }, + { + "token": "に", + "start_offset": 5, + "end_offset": 6, + "type": "<SINGLE>", + "position": 3 + }, + { + "token": "に行", + "start_offset": 5, + "end_offset": 7, + "type": "<DOUBLE>", + "position": 3, + "positionLength": 2 + }, + { + "token": "行", + "start_offset": 6, + "end_offset": 7, + "type": "<SINGLE>", + "position": 4 + }, + { + "token": "行く", + "start_offset": 6, + "end_offset": 8, + "type": "<DOUBLE>", + "position": 4, + "positionLength": 2 + }, + { + "token": "く", + "start_offset": 7, + "end_offset": 8, + "type": "<SINGLE>", + "position": 5 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/cjk-width.md b/i18n/zh/analyzers/token-filters/cjk-width.md new file mode 100644 index 00000000..2300cdbb --- /dev/null +++ b/i18n/zh/analyzers/token-filters/cjk-width.md @@ -0,0 +1,90 @@ +--- +title: CJK 宽度 +--- + +# CJK width token filter + +The `cjk_width` token filter normalizes Chinese, Japanese, and Korean (CJK) tokens by converting full-width ASCII characters to their standard (half-width) ASCII equivalents and half-width katakana characters to their full-width equivalents. + +### Converting full-width ASCII characters + +In CJK texts, ASCII characters (such as letters and numbers) can appear in full-width form, occupying the space of two half-width characters. Full-width ASCII characters are typically used in East Asian typography for alignment with the width of CJK characters. However, for the purposes of indexing and searching, these full-width characters need to be normalized to their standard (half-width) ASCII equivalents. + +The following example illustrates ASCII character normalization: + +``` + Full-Width: ABCDE 12345 + Normalized (half-width): ABCDE 12345 +``` + +### Converting half-width katakana characters + +The `cjk_width` token filter converts half-width katakana characters to their full-width counterparts, which are the standard form used in Japanese text. This normalization, illustrated in the following example, is important for consistency in text processing and searching: + +``` + Half-Width katakana: カタカナ + Normalized (full-width) katakana: カタカナ +``` + +## 示例 + +The following example request creates a new index named `cjk_width_example_index` and defines an analyzer with the `cjk_width` filter: + +```json +PUT /cjk_width_example_index +{ + "settings": { + "analysis": { + "analyzer": { + "cjk_width_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["cjk_width"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /cjk_width_example_index/_analyze +{ + "analyzer": "cjk_width_analyzer", + "text": "Tokyo 2024 カタカナ" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Tokyo", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "2024", + "start_offset": 6, + "end_offset": 10, + "type": "<NUM>", + "position": 1 + }, + { + "token": "カタカナ", + "start_offset": 11, + "end_offset": 15, + "type": "<KATAKANA>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/classic.md b/i18n/zh/analyzers/token-filters/classic.md new file mode 100644 index 00000000..1b8c929b --- /dev/null +++ b/i18n/zh/analyzers/token-filters/classic.md @@ -0,0 +1,86 @@ +--- +title: 经典 +--- + +# Classic token filter + +The primary function of the classic token filter is to work alongside the classic tokenizer. It processes tokens by applying the following common transformations, which aid in text analysis and search: + - Removal of possessive endings such as *'s*. For example, *John's* becomes *John*. + - Removal of periods from acronyms. For example, *D.A.R.P.A.* becomes *DARPA*. + +## 示例 + +The following example request creates a new index named `custom_classic_filter` and configures an analyzer with the `classic` filter: + +```json +PUT /custom_classic_filter +{ + "settings": { + "analysis": { + "analyzer": { + "custom_classic": { + "type": "custom", + "tokenizer": "classic", + "filter": ["classic"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /custom_classic_filter/_analyze +{ + "analyzer": "custom_classic", + "text": "John's co-operate was excellent." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "John", + "start_offset": 0, + "end_offset": 6, + "type": "<APOSTROPHE>", + "position": 0 + }, + { + "token": "co", + "start_offset": 7, + "end_offset": 9, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "operate", + "start_offset": 10, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "was", + "start_offset": 18, + "end_offset": 21, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "excellent", + "start_offset": 22, + "end_offset": 31, + "type": "<ALPHANUM>", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/common_gram.md b/i18n/zh/analyzers/token-filters/common_gram.md new file mode 100644 index 00000000..bb283109 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/common_gram.md @@ -0,0 +1,89 @@ +--- +title: 常用词组 +--- + +<!-- vale off --> +# Common grams token filter +<!-- vale on --> +The `common_grams` token filter improves search relevance by keeping commonly occurring phrases (common grams) in the text. This is useful when dealing with languages or datasets in which certain word combinations frequently occur as a unit and can impact search relevance if treated as separate tokens. If any common words are present in the input string, this token filter generates both their unigrams and bigrams. + +Using this token filter improves search relevance by keeping common phrases intact. This can help in matching queries more accurately, particularly for frequent word combinations. It also improves search precision by reducing the number of irrelevant matches. + +::: danger WARNING +When using this filter, you must carefully select and maintain the `common_words` list. +::: + +## 参数 + +The `common_grams` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`common_words` | 必需 | List of strings | A list of words that should be treated as words that commonly appear together. These words will be used to generate common grams. If the `common_words` parameter is an empty list, the `common_grams` token filter becomes a no-op filter, meaning that it doesn't modify the input tokens at all. +`ignore_case` | 可选 | Boolean | Indicates whether the filter should ignore case differences when matching common words. Default is `false`. +`query_mode` | 可选 | Boolean | When set to `true`, the following rules are applied:<br>- Unigrams that are generated from `common_words` are not included in the output.<br>- Bigrams in which a non-common word is followed by a common word are retained in the output.<br>- Unigrams of non-common words are excluded if they are immediately followed by a common word.<br>- If a non-common word appears at the end of the text and is preceded by a common word, its unigram is not included in the output. + +## 示例 + +The following example request creates a new index named `my_common_grams_index` and configures an analyzer with the `common_grams` filter: + +```json +PUT /my_common_grams_index +{ + "settings": { + "analysis": { + "filter": { + "my_common_grams_filter": { + "type": "common_grams", + "common_words": ["a", "in", "for"], + "ignore_case": true, + "query_mode": true + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_common_grams_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_common_grams_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "A quick black cat jumps over the lazy dog in the park" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "a_quick","start_offset": 0,"end_offset": 7,"type": "gram","position": 0}, + {"token": "quick","start_offset": 2,"end_offset": 7,"type": "<ALPHANUM>","position": 1}, + {"token": "black","start_offset": 8,"end_offset": 13,"type": "<ALPHANUM>","position": 2}, + {"token": "cat","start_offset": 14,"end_offset": 17,"type": "<ALPHANUM>","position": 3}, + {"token": "jumps","start_offset": 18,"end_offset": 23,"type": "<ALPHANUM>","position": 4}, + {"token": "over","start_offset": 24,"end_offset": 28,"type": "<ALPHANUM>","position": 5}, + {"token": "the","start_offset": 29,"end_offset": 32,"type": "<ALPHANUM>","position": 6}, + {"token": "lazy","start_offset": 33,"end_offset": 37,"type": "<ALPHANUM>","position": 7}, + {"token": "dog_in","start_offset": 38,"end_offset": 44,"type": "gram","position": 8}, + {"token": "in_the","start_offset": 42,"end_offset": 48,"type": "gram","position": 9}, + {"token": "the","start_offset": 45,"end_offset": 48,"type": "<ALPHANUM>","position": 10}, + {"token": "park","start_offset": 49,"end_offset": 53,"type": "<ALPHANUM>","position": 11} + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/condition.md b/i18n/zh/analyzers/token-filters/condition.md new file mode 100644 index 00000000..ac9b1878 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/condition.md @@ -0,0 +1,127 @@ +--- +title: 条件 +--- + +# Condition token filter + +The `condition` token filter is a special type of filter that allows you to apply other token filters conditionally based on certain criteria. This provides more control over when certain token filters should be applied during text analysis. +Multiple filters can be configured and only applied when they meet the conditions you define. +This token filter can be very useful for language-specific processing and handling of special characters. + +## 参数 + +There are two parameters that must be configured in order to use the `condition` token filter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`filter` | 必需 | Array | Specifies which token filters should be applied to the tokens when the specified condition (defined by the `script` parameter) is met. +`script` | 必需 | Object | Configures an [inline script](/api-reference/script-apis/exec-script) that defines the condition that needs to be met in order for the filters specified in the `filter` parameter to be applied (only inline scripts are accepted). + +## 示例 + +The following example request creates a new index named `my_conditional_index` and configures an analyzer with a `condition` filter. This filter applies a `lowercase` filter to any tokens that contain the character sequence "um": + +```json +PUT /my_conditional_index +{ + "settings": { + "analysis": { + "filter": { + "my_conditional_filter": { + "type": "condition", + "filter": ["lowercase"], + "script": { + "source": "token.getTerm().toString().contains('um')" + } + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "my_conditional_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_conditional_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "THE BLACK CAT JUMPS OVER A LAZY DOG" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "THE", + "start_offset": 0, + "end_offset": 3, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "BLACK", + "start_offset": 4, + "end_offset": 9, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "CAT", + "start_offset": 10, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "jumps", + "start_offset": 14, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "OVER", + "start_offset": 20, + "end_offset": 24, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "A", + "start_offset": 25, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "LAZY", + "start_offset": 27, + "end_offset": 31, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "DOG", + "start_offset": 32, + "end_offset": 35, + "type": "<ALPHANUM>", + "position": 7 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/decimal-digit.md b/i18n/zh/analyzers/token-filters/decimal-digit.md new file mode 100644 index 00000000..3a29d57a --- /dev/null +++ b/i18n/zh/analyzers/token-filters/decimal-digit.md @@ -0,0 +1,82 @@ +--- +title: 十进制数字 +--- + +# Decimal digit token filter + +The `decimal_digit` token filter is used to normalize decimal digit characters (0--9) into their ASCII equivalents in various scripts. This is useful when you want to ensure that all digits are treated uniformly in text analysis, regardless of the script in which they are written. + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `decimal_digit` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_decimal_digit_filter": { + "type": "decimal_digit" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["my_decimal_digit_filter"] + } + } + } + } +} + +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "123 ١٢٣ १२३" +} +``` + +`text` breakdown: + + - "123" (ASCII digits) + - "١٢٣" (Arabic-Indic digits) + - "१२३" (Devanagari digits) + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "123", + "start_offset": 0, + "end_offset": 3, + "type": "<NUM>", + "position": 0 + }, + { + "token": "123", + "start_offset": 4, + "end_offset": 7, + "type": "<NUM>", + "position": 1 + }, + { + "token": "123", + "start_offset": 8, + "end_offset": 11, + "type": "<NUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/delimited-payload.md b/i18n/zh/analyzers/token-filters/delimited-payload.md new file mode 100644 index 00000000..87f000bd --- /dev/null +++ b/i18n/zh/analyzers/token-filters/delimited-payload.md @@ -0,0 +1,202 @@ +--- +title: 分隔有效负载 +--- + +# Delimited payload token filter + +The `delimited_payload` token filter is used to parse tokens containing payloads during the analysis process. For example, the string `red|1.5 fast|2.0 car|1.0` is parsed into the tokens `red` (with a payload of `1.5`), `fast` (with a payload of `2.0`), and `car` (with a payload of `1.0`). This is particularly useful when your tokens include additional associated data (like weights, scores, or other numeric values) that you can use for scoring or custom query logic. The filter can handle different types of payloads, including integers, floats, and strings, and attach payloads (extra metadata) to tokens. + +When analyzing text, the `delimited_payload` token filter parses each token, extracts the payload, and attaches it to the token. This payload can later be used in queries to influence scoring, boosting, or other custom behaviors. + +Payloads are stored as Base64-encoded strings. By default, payloads are not returned in the query response along with the tokens. To return the payloads, you must configure additional parameters. For more information, see [Example with a stored payload](/analyzers/token-filters/delimited-payload#example-without-a-stored-payload). + +## 参数 + +The `delimited_payload` token filter has two parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`encoding` | 可选 | String | Specifies the data type of the payload attached to the tokens. This determines how the payload data is interpreted during analysis and querying.<br>Valid values are:<br><br>- `float`: The payload is interpreted as a 32-bit floating-point number using IEEE 754 format (for example, `2.5` in `car|2.5`).<br>- `identity`: The payload is interpreted as a sequence of characters (for example, in `user|admin`, `admin` is interpreted as a string).<br>- `int`: The payload is interpreted as a 32-bit integer (for example, `1` in `priority|1`).<br> Default is `float`. +`delimiter` | 可选 | String | Specifies the character that separates the token from its payload in the input text. Default is the pipe character (`|`). + +## 示例 without a stored payload + +The following example request creates a new index named `my_index` and configures an analyzer with a `delimited_payload` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_payload_filter": { + "type": "delimited_payload", + "delimiter": "|", + "encoding": "float" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "whitespace", + "filter": ["my_payload_filter"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "red|1.5 fast|2.0 car|1.0" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "red", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "fast", + "start_offset": 8, + "end_offset": 16, + "type": "word", + "position": 1 + }, + { + "token": "car", + "start_offset": 17, + "end_offset": 24, + "type": "word", + "position": 2 + } + ] +} +``` + +## 示例 with a stored payload + +To configure the payload to be returned in the response, create an index that stores term vectors and set `term_vector` to `with_positions_payloads` or `with_positions_offsets_payloads` in the index mappings. For example, the following index is configured to store term vectors: + +```json +PUT /visible_payloads +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_payloads", + "analyzer": "custom_analyzer" + } + } + }, + "settings": { + "analysis": { + "filter": { + "my_payload_filter": { + "type": "delimited_payload", + "delimiter": "|", + "encoding": "float" + } + }, + "analyzer": { + "custom_analyzer": { + "tokenizer": "whitespace", + "filter": [ "my_payload_filter" ] + } + } + } + } +} +``` + +You can index a document into this index using the following request: + +```json +PUT /visible_payloads/_doc/1 +{ + "text": "red|1.5 fast|2.0 car|1.0" +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /visible_payloads/_termvectors/1 +{ + "fields": ["text"] +} +``` + +响应包含 the generated tokens, which include payloads: + +```json +{ + "_index": "visible_payloads", + "_id": "1", + "_version": 1, + "found": true, + "took": 3, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 3, + "doc_count": 1, + "sum_ttf": 3 + }, + "terms": { + "brown": { + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 10, + "end_offset": 19, + "payload": "QEAAAA==" + } + ] + }, + "fox": { + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 20, + "end_offset": 27, + "payload": "P8AAAA==" + } + ] + }, + "quick": { + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 9, + "payload": "QCAAAA==" + } + ] + } + } + } + } +} +``` diff --git a/i18n/zh/analyzers/token-filters/dictionary-decompounder.md b/i18n/zh/analyzers/token-filters/dictionary-decompounder.md new file mode 100644 index 00000000..a7d5aa02 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/dictionary-decompounder.md @@ -0,0 +1,96 @@ +--- +title: 词典复合词分解器 +--- + +# Dictionary decompounder token filter + +The `dictionary_decompounder` token filter is used to split compound words into their constituent parts based on a predefined dictionary. This filter is particularly useful for languages like German, Dutch, or Finnish, in which compound words are common, so breaking them down can improve search relevance. The `dictionary_decompounder` token filter determines whether each token (word) can be split into smaller tokens based on a list of known words. If the token can be split into known words, the filter generates the subtokens for the token. + +## 参数 + +The `dictionary_decompounder` token filter has the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`word_list` | 必需 unless `word_list_path` is configured | Array of strings | The dictionary of words that the filter uses to split compound words. +`word_list_path` | 必需 unless `word_list` is configured | String | A file path to a text file containing the dictionary words. Accepts either an absolute path or a path relative to the `config` directory. The dictionary file must be UTF-8 encoded, and each word must be listed on a separate line. +`min_word_size` | 可选 | Integer | The minimum length of the entire compound word that will be considered for splitting. If a compound word is shorter than this value, it is not split. Default is `5`. +`min_subword_size` | 可选 | Integer | The minimum length for any subword. If a subword is shorter than this value, it is not included in the output. Default is `2`. +`max_subword_size` | 可选 | Integer | The maximum length for any subword. If a subword is longer than this value, it is not included in the output. Default is `15`. +`only_longest_match` | 可选 | Boolean | If set to `true`, only the longest matching subword will be returned. Default is `false`. + +## 示例 + +The following example request creates a new index named `decompound_example` and configures an analyzer with the `dictionary_decompounder` filter: + +```json +PUT /decompound_example +{ + "settings": { + "analysis": { + "filter": { + "my_dictionary_decompounder": { + "type": "dictionary_decompounder", + "word_list": ["slow", "green", "turtle"] + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "my_dictionary_decompounder"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /decompound_example/_analyze +{ + "analyzer": "my_analyzer", + "text": "slowgreenturtleswim" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slowgreenturtleswim", + "start_offset": 0, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "green", + "start_offset": 0, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 0, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/edge-ngram.md b/i18n/zh/analyzers/token-filters/edge-ngram.md new file mode 100644 index 00000000..481a7ed9 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/edge-ngram.md @@ -0,0 +1,107 @@ +--- +title: 边缘 n-gram +--- + +# Edge n-gram token filter +The `edge_ngram` token filter is very similar to the `ngram` token filter, where a particular string is split into substrings of different lengths. The `edge_ngram` token filter, however, generates n-grams (substrings) only from the beginning (edge) of a token. It's particularly useful in scenarios like autocomplete or prefix matching, where you want to match the beginning of words or phrases as the user types them. + +## 参数 + +The `edge_ngram` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`min_gram` | 可选 | Integer | The minimum length of the n-grams that will be generated. Default is `1`. +`max_gram` | 可选 | Integer | The maximum length of the n-grams that will be generated. Default is `1` for the `edge_ngram` filter and `2` for custom token filters. Avoid setting this parameter to a low value. If the value is set too low, only very short n-grams will be generated and the search term will not be found. For example, if `max_gram` is set to `3` and you index the word "banana", the longest generated token will be "ban". If the user searches for "banana", no matches will be returned. You can use the `truncate` token filter as a search analyzer to mitigate this risk. +`preserve_original` | 可选 | Boolean | Includes the original token in the output. Default is `false` . + +## 示例 + +The following example request creates a new index named `edge_ngram_example` and configures an analyzer with the `edge_ngram` filter: + +```json +PUT /edge_ngram_example +{ + "settings": { + "analysis": { + "filter": { + "my_edge_ngram": { + "type": "edge_ngram", + "min_gram": 3, + "max_gram": 4 + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "my_edge_ngram"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /edge_ngram_example/_analyze +{ + "analyzer": "my_analyzer", + "text": "slow green turtle" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slo", + "start_offset": 0, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "gre", + "start_offset": 5, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "gree", + "start_offset": 5, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "tur", + "start_offset": 11, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "turt", + "start_offset": 11, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/elision.md b/i18n/zh/analyzers/token-filters/elision.md new file mode 100644 index 00000000..d1f8901a --- /dev/null +++ b/i18n/zh/analyzers/token-filters/elision.md @@ -0,0 +1,120 @@ +--- +title: 省略 +--- + +# Elision token filter + +The `elision` token filter is used to remove elided characters from words in certain languages. Elision typically occurs in languages such as French, in which words are often contracted and combined with the following word, typically by omitting a vowel and replacing it with an apostrophe. + +::: info NOTE +The `elision` token filter is already preconfigured in the following [language analyzers](/analyzers/language-analyzers): `catalan`, `french`, `irish`, and `italian`. +::: + +## 参数 + +The custom `elision` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`articles` | 必需 if `articles_path` is not configured | Array of strings | Defines which articles or short words should be removed when they appear as part of an elision. +`articles_path` | 必需 if `articles` is not configured | String | Specifies the path to a custom list of articles that should be removed during the analysis process. +`articles_case` | 可选 | Boolean | Specifies whether the filter is case sensitive when matching elisions. Default is `false`. + +## 示例 + +The default set of French elisions is `l'`, `m'`, `t'`, `qu'`, `n'`, `s'`, `j'`, `d'`, `c'`, `jusqu'`, `quoiqu'`, `lorsqu'`, and `puisqu'`. You can update this by configuring the `french_elision` token filter. The following example request creates a new index named `french_texts` and configures an analyzer with a `french_elision` filter: + +```json +PUT /french_texts +{ + "settings": { + "analysis": { + "filter": { + "french_elision": { + "type": "elision", + "articles": [ "l", "t", "m", "d", "n", "s", "j" ] + } + }, + "analyzer": { + "french_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "french_elision"] + } + } + } + }, + "mappings": { + "properties": { + "text": { + "type": "text", + "analyzer": "french_analyzer" + } + } + } +} + +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /french_texts/_analyze +{ + "analyzer": "french_analyzer", + "text": "L'étudiant aime l'école et le travail." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "étudiant", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "aime", + "start_offset": 11, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "école", + "start_offset": 16, + "end_offset": 23, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "et", + "start_offset": 24, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "le", + "start_offset": 27, + "end_offset": 29, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "travail", + "start_offset": 30, + "end_offset": 37, + "type": "<ALPHANUM>", + "position": 5 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/fingerprint.md b/i18n/zh/analyzers/token-filters/fingerprint.md new file mode 100644 index 00000000..10716b91 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/fingerprint.md @@ -0,0 +1,81 @@ +--- +title: 指纹 +--- + +# Fingerprint token filter + +The `fingerprint` token filter is used to standardize and deduplicate text. This is particularly useful when consistency in text processing is crucial. The `fingerprint` token filter achieves this by processing text using the following steps: + +1. **Lowercasing**: Converts all text to lowercase. +2. **Splitting**: Breaks the text into tokens. +3. **Sorting**: Arranges the tokens in alphabetical order. +4. **Removing duplicates**: Eliminates repeated tokens. +5. **Joining tokens**: Combines the tokens into a single string, typically joined by a space or another specified separator. + +## 参数 + +The `fingerprint` token filter can be configured with the following two parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`max_output_size` | 可选 | Integer | Limits the length of the generated fingerprint string. If the concatenated string exceeds the `max_output_size`, the filter will not produce any output, resulting in an empty token. Default is `255`. +`separator` | 可选 | String | Defines the character(s) used to join the tokens into a single string after they have been sorted and deduplicated. Default is space (`" "`). + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `fingerprint` token filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_fingerprint": { + "type": "fingerprint", + "max_output_size": 200, + "separator": "-" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_fingerprint" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "OpenSearch is a powerful search engine that scales easily" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "a-easily-engine-is-opensearch-powerful-scales-search-that", + "start_offset": 0, + "end_offset": 57, + "type": "fingerprint", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/flatten-graph.md b/i18n/zh/analyzers/token-filters/flatten-graph.md new file mode 100644 index 00000000..ecce898d --- /dev/null +++ b/i18n/zh/analyzers/token-filters/flatten-graph.md @@ -0,0 +1,105 @@ +--- +title: 扁平化图 +--- + +# Flatten graph token filter + +The `flatten_graph` token filter is used to handle complex token relationships that occur when multiple tokens are generated at the same position in a graph structure. Some token filters, like `synonym_graph` and `word_delimiter_graph`, generate multi-position tokens---tokens that overlap or span multiple positions. These token graphs are useful for search queries but are not directly supported during indexing. The `flatten_graph` token filter resolves multi-position tokens into a linear sequence of tokens. Flattening the graph ensures compatibility with the indexing process. + +::: warning IMPORTANT +Token graph flattening is a lossy process. Whenever possible, avoid using the `flatten_graph` filter. Instead, apply graph token filters exclusively in search analyzers, removing the need for the `flatten_graph` filter. +::: + +## 示例 + +The following example request creates a new index named `test_index` and configures an analyzer with a `flatten_graph` filter: + +```json +PUT /test_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_index_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "my_custom_filter", + "flatten_graph" + ] + } + }, + "filter": { + "my_custom_filter": { + "type": "word_delimiter_graph", + "catenate_all": true + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /test_index/_analyze +{ + "analyzer": "my_index_analyzer", + "text": "OpenSearch helped many employers" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0, + "positionLength": 2 + }, + { + "token": "Open", + "start_offset": 0, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "Search", + "start_offset": 4, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "helped", + "start_offset": 11, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "many", + "start_offset": 18, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "employers", + "start_offset": 23, + "end_offset": 32, + "type": "<ALPHANUM>", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/hunspell.md b/i18n/zh/analyzers/token-filters/hunspell.md new file mode 100644 index 00000000..881b44cc --- /dev/null +++ b/i18n/zh/analyzers/token-filters/hunspell.md @@ -0,0 +1,259 @@ +--- +title: Hunspell +--- + +# Hunspell token filter + +The `hunspell` token filter is used for stemming and morphological analysis of words in a specific language. This filter applies Hunspell dictionaries, which are widely used in spell checkers. It works by breaking down words into their root forms (stemming). + +If an algorithmic stemmer, such as the [`stemmer`](/analyzers/token-filters/stemmer) or [`porter_stem`](/analyzers/token-filters/porter-stem) filter, is available for your language, try it before using `hunspell`. Algorithmic stemmers are faster, use less memory, and require no dictionary files, and they often produce comparable or better search results. For more information, see [Stemming](/analyzers/stemming). + +The Hunspell dictionary files are automatically loaded at startup from the `<OS_PATH_CONF>/hunspell/<locale>` directory. For example, the `en_GB` locale must have at least one `.aff` file and one or more `.dic` files in the `<OS_PATH_CONF>/hunspell/en_GB/` directory. + +Alternatively, you can load dictionaries from a custom directory by using the `ref_path` parameter to maintain multiple independent dictionary sets for the same locale. For more information, see [Custom dictionary loading with ref_path](#custom-dictionary-loading). + +You can also hot-reload Hunspell dictionaries at runtime without restarting the node. For more information, see [Hot-reloading Hunspell dictionaries](#hot-reloading-hunspell-dictionaries). + +You can download these files from [LibreOffice dictionaries](https://github.com/LibreOffice/dictionaries). + +## 参数 + +The `hunspell` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`language/lang/locale` | At least one of the three is required | String | Specifies the language for the Hunspell dictionary. Can contain only alphanumeric characters, hyphens, and underscores (for example, `en_US`, `de_DE`). +`ref_path` | 可选 | String | Specifies a relative path used to load dictionaries from the `<OS_PATH_CONF>/<ref_path>/hunspell/<locale>/` directory instead of the default `<OS_PATH_CONF>/hunspell/<locale>/` directory. When specified, the `locale` parameter is required. The `ref_path` value can contain alphanumeric characters, hyphens, underscores, and forward slashes (for nested paths such as `analyzers/my-dict`). The `locale` value can contain only alphanumeric characters, hyphens, and underscores. See [Custom dictionary loading with ref_path](#custom-dictionary-loading). **Note**: `ref_path` resolves directly under `<OS_PATH_CONF>`. In OpenSearch 3.6 and earlier, it resolved under `<OS_PATH_CONF>/analyzers/`. To preserve the previous layout, prefix your `ref_path` value with `analyzers/` (for example, `analyzers/my-dict`). +`dedup` | 可选 | Boolean | Determines whether to remove multiple duplicate stemming terms for the same token. Default is `true`. +`dictionary` | 可选 | Array of strings | Configures the dictionary files to be used for the Hunspell dictionary. Default is all files in the `<OS_PATH_CONF>/hunspell/<locale>` directory if `ref_path` is not specified or all files in the `<OS_PATH_CONF>/<ref_path>/hunspell/<locale>/` directory when `ref_path` is specified. See [Custom dictionary loading with ref_path](#custom-dictionary-loading). +`longest_only` | 可选 | Boolean | Specifies whether only the longest stemmed version of the token should be returned. Default is `false`. +`updateable` | 可选 | Boolean | When set to `true`, the filter operates in search-time analysis mode, allowing dictionaries to be hot-reloaded by using the [Refresh search analyzer](/im-plugin/refresh-analyzer) API without restarting the node. Default is `false`. **Introduced 3.7.** + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `hunspell` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_hunspell_filter": { + "type": "hunspell", + "lang": "en_GB", + "dedup": true, + "longest_only": true + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_hunspell_filter" + ] + } + } + } + } +} +``` + +## Hunspell node settings + +The following table lists the static node settings that control how OpenSearch loads Hunspell dictionaries from the default `<OS_PATH_CONF>/hunspell/` directory. Configure them in `opensearch.yml`. + +Setting | 数据类型 | Description +:--- | :--- | :--- +`indices.analysis.hunspell.dictionary.lazy` | Boolean | If `false`, OpenSearch loads every dictionary in the `hunspell` directory when the node starts and logs an error for any dictionary that fails to load. If `true`, OpenSearch loads each dictionary the first time a `hunspell` filter uses it, so dictionary errors appear only when an index or analysis request references the locale. Default is `false`. +`indices.analysis.hunspell.dictionary.ignore_case` | Boolean | If `true`, words are matched to dictionary entries regardless of case. For example, if the dictionary contains `Jump` with an `-ing` suffix rule, the text `jumping` is stemmed to `jump` only when `ignore_case` is `true`. This setting applies to all locales. Default is `false`. +`indices.analysis.hunspell.dictionary.<locale>.ignore_case` | Boolean | Sets `ignore_case` for one locale, for example, `indices.analysis.hunspell.dictionary.en_US.ignore_case`. Overrides the global `ignore_case` setting. + +You can also set `ignore_case` for a single dictionary by adding a `settings.yml` file to the locale directory, for example, `<OS_PATH_CONF>/hunspell/en_US/settings.yml` containing `ignore_case: true`. If both the file and the locale-specific node setting specify `ignore_case`, the node setting takes precedence. + +## Custom dictionary loading + +When you specify a `ref_path` parameter, dictionaries are loaded from a custom directory instead of the default directory. This is useful when you need multiple independent dictionary sets for the same locale, for example, when different indexes require different custom dictionaries. + +::: info NOTE +The `ref_path` value is resolved relative to `<OS_PATH_CONF>` and can contain forward slashes for nested paths. In OpenSearch 3.6 and earlier, `ref_path` was resolved relative to `<OS_PATH_CONF>/analyzers/`. To preserve the previous directory layout when upgrading from 3.6 or earlier, prefix your existing `ref_path` value with `analyzers/`. +::: + +Place dictionary files in the following directory structure: + +```xml +<OS_PATH_CONF>/<ref_path>/hunspell/<locale>/ +├── <locale>.aff (exactly one .aff file required) +├── <locale>.dic (one or more .dic files) +└── <locale>_custom.dic +``` + +The following example loads a Hunspell dictionary from `<OS_PATH_CONF>/analyzers/my-dict/hunspell/en_US/`: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_custom_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/my-dict", + "locale": "en_US" + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_custom_hunspell" + ] + } + } + } + } +} +``` + +Multiple indexes can use different `ref_path` directories configured for the same locale. Each `ref_path` maintains its own independent dictionary cache: + +```json +PUT /index_medical +{ + "settings": { + "analysis": { + "filter": { + "medical_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/medical-dict", + "locale": "en_US" + } + } + } + } +} +``` + +```json +PUT /index_legal +{ + "settings": { + "analysis": { + "filter": { + "legal_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/legal-dict", + "locale": "en_US" + } + } + } + } +} +``` + +## Hot-reloading Hunspell dictionaries +<Badge type="tip" text="Introduced 3.7" /> + +You can update Hunspell dictionaries at runtime without restarting the node. To enable this, set the `updateable` parameter to `true` on the Hunspell token filter. This registers the filter in search-time analysis mode, so it can only be used at search time (for example, in a `search_analyzer`), not at index time. + +To hot-reload a Hunspell dictionary, follow these steps: + +1. Configure the Hunspell token filter with `updateable` set to `true`. The following example creates an index that uses a hot-reloadable Hunspell filter as a `search_analyzer`: + + ```json + PUT /my_index + { + "settings": { + "analysis": { + "filter": { + "my_reloadable_hunspell": { + "type": "hunspell", + "ref_path": "analyzers/my-dict", + "locale": "en_US", + "updateable": true + } + }, + "analyzer": { + "my_search_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_reloadable_hunspell" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "standard", + "search_analyzer": "my_search_analyzer" + } + } + } + } + ``` + +1. Replace the `.aff` and `.dic` files on disk on every node that holds a shard for the index. + +1. Call the [Refresh Search Analyzer API](/im-plugin/refresh-analyzer). When `reload_cached_resources` is `false` (the default), the API rebuilds analyzer factories but reuses the previously cached Hunspell dictionary. Specify `reload_cached_resources=true` to force the dictionary to be reloaded from disk: + + ```json + POST /_plugins/_refresh_search_analyzers/my_index?reload_cached_resources=true + ``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "the turtle moves slowly" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "the", + "start_offset": 0, + "end_offset": 3, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 4, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "move", + "start_offset": 11, + "end_offset": 16, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "slow", + "start_offset": 17, + "end_offset": 23, + "type": "<ALPHANUM>", + "position": 3 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/hyphenation-decompounder.md b/i18n/zh/analyzers/token-filters/hyphenation-decompounder.md new file mode 100644 index 00000000..e1188db4 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/hyphenation-decompounder.md @@ -0,0 +1,97 @@ +--- +title: 连字符复合词分解器 +--- + +# Hyphenation decompounder token filter + +The `hyphenation_decompounder` token filter is used to break down compound words into their constituent parts. This filter is particularly useful for languages like German, Dutch, and Swedish, in which compound words are common. The filter uses hyphenation patterns (typically defined in .xml files) to identify the possible locations within a compound word where it can be split into components. These components are then checked against a provided dictionary. If there is a match, those components are treated as valid tokens. For more information about hyphenation pattern files, see [Apache Formatting Objects Processor (FOP) XML Hyphenation Patterns](https://offo.sourceforge.net/#FOP+XML+Hyphenation+Patterns). + +## 参数 + +The `hyphenation_decompounder` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`hyphenation_patterns_path` | 必需 | String | The path (relative to the `config` directory or absolute) to the hyphenation patterns file, which contains the language-specific rules for word splitting. The file is typically in XML format. Sample files can be downloaded from the [OFFO SourceForge project](https://sourceforge.net/projects/offo/). +`word_list` | 必需 if `word_list_path` is not set | Array of strings | A list of words used to validate the components generated by the hyphenation patterns. +`word_list_path` | 必需 if `word_list` is not set | String | The path (relative to the `config` directory or absolute) to a list of subwords. +`max_subword_size` | 可选 | Integer | The maximum subword length. If the generated subword exceeds this length, it will not be added to the generated tokens. Default is `15`. +`min_subword_size` | 可选 | Integer | The minimum subword length. If the generated subword is shorter than the specified length, it will not be added to the generated tokens. Default is `2`. +`min_word_size` | 可选 | Integer | The minimum word character length. Word tokens shorter than this length are excluded from decomposition into subwords. Default is `5`. +`only_longest_match` | 可选 | Boolean | Only includes the longest subword in the generated tokens. Default is `false`. + +## 示例 + +The following example request creates a new index named `test_index` and configures an analyzer with a `hyphenation_decompounder` filter: + +```json +PUT /test_index +{ + "settings": { + "analysis": { + "filter": { + "my_hyphenation_decompounder": { + "type": "hyphenation_decompounder", + "hyphenation_patterns_path": "analysis/hyphenation_patterns.xml", + "word_list": ["notebook", "note", "book"], + "min_subword_size": 3, + "min_word_size": 5, + "only_longest_match": false + } + }, + "analyzer": { + "my_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_hyphenation_decompounder" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /test_index/_analyze +{ + "analyzer": "my_analyzer", + "text": "notebook" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "notebook", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "note", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "book", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/icu-folding.md b/i18n/zh/analyzers/token-filters/icu-folding.md new file mode 100644 index 00000000..550212e4 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/icu-folding.md @@ -0,0 +1,176 @@ +--- +title: ICU 折叠 +--- + +# ICU folding token filter + +The `icu_folding` token filter applies Unicode normalization and case folding to tokens, converting them to a form suitable for case-insensitive matching. This filter provides more comprehensive character folding than the ASCII folding filter, handling characters from all Unicode scripts. + +The filter implements case folding as defined in [Unicode Technical Report #30](https://www.unicode.org/reports/tr30/), which includes: +- Converting uppercase letters to lowercase +- Removing diacritical marks (accents) +- Converting ligatures to their component letters +- Normalizing character width (for example, full-width to half-width) +- Converting certain punctuation and symbols to ASCII equivalents + +## 安装 + +The `icu_folding` token filter requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer](/analyzers/language-analyzers/icu). + +## 参数 + +The following table lists the parameters for the `icu_folding` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`unicode_set_filter` | String | A [UnicodeSet](https://unicode-org.github.io/icu/userguide/strings/unicodeset.html) expression specifying which characters to fold. Characters outside this set are passed through unchanged. Optional. If not specified, all characters are folded. + +## 示例: Basic ICU folding + +The following example demonstrates the default `icu_folding` behavior: + +```json +PUT /icu-folding-index +{ + "settings": { + "analysis": { + "analyzer": { + "icu_folding_analyzer": { + "tokenizer": "icu_tokenizer", + "filter": ["icu_folding"] + } + } + } + } +} +``` + +Test the analyzer with text containing diacritics, ligatures, and mixed case: + +```json +POST /icu-folding-index/_analyze +{ + "analyzer": "icu_folding_analyzer", + "text": "Café RÉSUMÉ Æsop" +} +``` + +The response shows normalization and folding: + +```json +{ + "tokens": [ + { + "token": "cafe", + "start_offset": 0, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "resume", + "start_offset": 5, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "aesop", + "start_offset": 12, + "end_offset": 16, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` + +## Normalization included + +::: info NOTE +The `icu_folding` filter already performs Unicode normalization, so you don't need to add a separate normalization character filter or token filter when using `icu_folding`. +::: + +## 示例: Preserving specific characters + +You can preserve specific characters from folding using the `unicode_set_filter` parameter. The following example preserves German umlauts and the Eszett character: + +```json +PUT /icu-folding-german +{ + "settings": { + "analysis": { + "filter": { + "german_folding": { + "type": "icu_folding", + "unicode_set_filter": "[^äöüÄÖÜß]" + } + }, + "analyzer": { + "german_analyzer": { + "tokenizer": "icu_tokenizer", + "filter": ["german_folding", "lowercase"] + } + } + } + } +} +``` + +The `unicode_set_filter` value `[^äöüÄÖÜß]` means "fold all characters except these German characters." The `lowercase` filter is added afterward to handle the preserved uppercase characters. + +Test the analyzer: + +```json +POST /icu-folding-german/_analyze +{ + "analyzer": "german_analyzer", + "text": "MÜNCHEN Café Größe" +} +``` + +The response preserves German characters while folding others: + +```json +{ + "tokens": [ + { + "token": "münchen", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "cafe", + "start_offset": 8, + "end_offset": 12, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "größe", + "start_offset": 13, + "end_offset": 18, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` + +## Comparison with ASCII folding + +While the `asciifolding` token filter converts non-ASCII characters to ASCII equivalents, `icu_folding` provides more sophisticated normalization: + +- **Broader character support**: Handles all Unicode scripts, not only Latin-based characters +- **Language-aware**: Applies normalization rules appropriate for different writing systems +- **Width normalization**: Converts full-width characters to half-width (important for CJK text) +- **Ligature handling**: Properly decomposes ligatures across all scripts + +## 相关文档 + +- [ICU analyzer](/analyzers/language-analyzers/icu) +- [ICU tokenizer](/analyzers/tokenizers/icu-tokenizer) +- [ICU normalization character filter](/analyzers/character-filters/icu-normalization) +- [ASCII folding token filter](/analyzers/token-filters/asciifolding) diff --git a/i18n/zh/analyzers/token-filters/icu-transform.md b/i18n/zh/analyzers/token-filters/icu-transform.md new file mode 100644 index 00000000..096797ec --- /dev/null +++ b/i18n/zh/analyzers/token-filters/icu-transform.md @@ -0,0 +1,237 @@ +--- +title: ICU 转换 +--- + +# ICU transform token filter + +The `icu_transform` token filter applies ICU text transformations to tokens, enabling operations such as transliteration, case mapping, normalization, and bidirectional text handling. This filter uses transformation rules defined by the [ICU Transform](https://unicode-org.github.io/icu/userguide/transforms/general/) framework. + +Common use cases include: +- **Transliteration**: Converting text from one script to another (for example, Cyrillic to Latin) +- **Script conversion**: Transforming between different writing systems +- **Accent removal**: Separating base characters from diacritics +- **Custom transformations**: Applying user-defined transformation rules + +## 安装 + +The `icu_transform` token filter requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer](/analyzers/language-analyzers/icu). + +## 参数 + +The following table lists the parameters for the `icu_transform` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`id` | String | The ICU transform ID specifying which transformation to apply. Can be a single transform ID or a compound ID with multiple transforms separated by semicolons. Default is `Null` (no transformation). +`dir` | String | The text direction for the transformation. Valid values are `forward` (default, left-to-right) and `reverse` (right-to-left). Default is `forward`. + +## Transform IDs + +You can specify transformations using standard ICU transform IDs. Common transforms include: + +- `Any-Latin`: Transliterates text from any script to Latin characters +- `Latin-Cyrillic`: Converts Latin text to Cyrillic +- `NFD; [:Nonspacing Mark:] Remove; NFC`: Decomposes characters, removes diacritics, then recomposes +- `Lower`: Converts text to lowercase +- `Upper`: Converts text to uppercase +- `Hiragana-Katakana`: Converts Hiragana to Katakana + +You can chain multiple transforms by separating them with semicolons. + +## 示例: Transliterating to Latin + +The following example demonstrates transliteration of multiple scripts to Latin characters: + +```json +PUT /icu-transform-latin +{ + "settings": { + "analysis": { + "filter": { + "latin_transform": { + "type": "icu_transform", + "id": "Any-Latin" + } + }, + "analyzer": { + "latin_analyzer": { + "tokenizer": "keyword", + "filter": ["latin_transform"] + } + } + } + } +} +``` + +Test the analyzer with text in different scripts: + +```json +POST /icu-transform-latin/_analyze +{ + "analyzer": "latin_analyzer", + "text": "Москва" +} +``` + +The Cyrillic text is transliterated to Latin: + +```json +{ + "tokens": [ + { + "token": "Moskva", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0 + } + ] +} +``` + +Test with Japanese text: + +```json +POST /icu-transform-latin/_analyze +{ + "analyzer": "latin_analyzer", + "text": "東京" +} +``` + +The Japanese characters are transliterated: + +```json +{ + "tokens": [ + { + "token": "dōng jīng", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + } + ] +} +``` + +## 示例: Removing accents + +The following example removes diacritical marks from text: + +```json +PUT /icu-transform-no-accents +{ + "settings": { + "analysis": { + "filter": { + "remove_accents": { + "type": "icu_transform", + "id": "NFD; [:Nonspacing Mark:] Remove; NFC" + } + }, + "analyzer": { + "accent_removal_analyzer": { + "tokenizer": "keyword", + "filter": ["remove_accents"] + } + } + } + } +} +``` + +Test the analyzer: + +```json +POST /icu-transform-no-accents/_analyze +{ + "analyzer": "accent_removal_analyzer", + "text": "Ênrique Iglesias" +} +``` + +The accents are removed: + +```json +{ + "tokens": [ + { + "token": "Enrique Iglesias", + "start_offset": 0, + "end_offset": 16, + "type": "word", + "position": 0 + } + ] +} +``` + +## 示例: Script-to-script conversion + +The following example converts Latin text to Cyrillic: + +```json +PUT /icu-transform-cyrillic +{ + "settings": { + "analysis": { + "filter": { + "to_cyrillic": { + "type": "icu_transform", + "id": "Latin-Cyrillic" + } + }, + "analyzer": { + "cyrillic_analyzer": { + "tokenizer": "keyword", + "filter": ["to_cyrillic"] + } + } + } + } +} +``` + +Test with Latin text: + +```json +POST /icu-transform-cyrillic/_analyze +{ + "analyzer": "cyrillic_analyzer", + "text": "Sankt Peterburg" +} +``` + +The text is converted to Cyrillic script: + +```json +{ + "tokens": [ + { + "token": "Санкт Петербург", + "start_offset": 0, + "end_offset": 15, + "type": "word", + "position": 0 + } + ] +} +``` + +## Compound transformations + +You can chain multiple transformations by separating transform IDs with semicolons. The transformations are applied in order from left to right. + +For example, the compound ID `"Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC"` performs the following steps: +1. Transliterates to Latin +2. Applies canonical decomposition (NFD) +3. Removes non-spacing marks (accents) +4. Applies canonical composition (NFC) + +## 相关文档 + +- [ICU analyzer](/analyzers/language-analyzers/icu) +- [ICU tokenizer](/analyzers/tokenizers/icu-tokenizer) +- [ICU folding token filter](/analyzers/token-filters/icu-folding) diff --git a/i18n/zh/analyzers/token-filters/ja-stop.md b/i18n/zh/analyzers/token-filters/ja-stop.md new file mode 100644 index 00000000..9c4e3913 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/ja-stop.md @@ -0,0 +1,155 @@ +--- +title: 日语停用词 +--- + +# Japanese stop token filter + +The `ja_stop` token filter removes Japanese stop words from a token stream. It matches tokens against a word list, either the built-in Japanese stop set or a custom list that you provide. To remove tokens by grammatical category instead, use [`kuromoji_part_of_speech`](/analyzers/token-filters/kuromoji-part-of-speech). + +The filter also supports a suggest-friendly mode (`remove_trailing: false`) in which trailing stop words are preserved. This is important for autocomplete use cases where a user may be in the middle of typing a phrase that ends with a stop word or particle. + +## 安装 + +The `ja_stop` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The following table lists the parameters for the `ja_stop` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`stopwords` | String or array of strings | The stop words to use. Accepts `_japanese_` for the built-in Japanese stop set, an array of explicit stop words, or a path to a file containing one stop word per line. Default is `_japanese_` (the same stop set used by the built-in `kuromoji` analyzer). +`ignore_case` | Boolean | When `true`, stop word matching is case insensitive. Default is `false`. +`remove_trailing` | Boolean | When `true` (default), a stop word at the end of the token stream is removed. When `false`, a trailing stop word is preserved, enabling prefix-match completion queries to work correctly on partially typed input. + +For the full list of stop words in the built-in stop set, see [stopwords.txt](https://github.com/apache/lucene/blob/main/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stopwords.txt) in the Lucene repository. + +## 示例: Minimal usage + +The following example uses `ja_stop` in isolation to show what the filter removes on its own: + +```json +PUT /ja-stop-minimal-index +{ + "settings": { + "analysis": { + "analyzer": { + "ja_stop_minimal_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["ja_stop"] + } + } + } + } +} +``` + +Test the analyzer with the sentence `新聞を読んでいるばかりだ` ("I do nothing but read the newspaper"), which the tokenizer segments into `新聞`, `を`, `読ん`, `で`, `いる`, `ばかり`, and `だ`: + +```json +POST /ja-stop-minimal-index/_analyze +{ + "analyzer": "ja_stop_minimal_analyzer", + "text": "新聞を読んでいるばかりだ" +} +``` + +The filter removes `を`, `で`, `いる`, and `だ` because they are in the `_japanese_` stop set. The inflected stem `読ん` and the adverbial particle `ばかり` are not in the stop set, so they remain unchanged alongside the content token `新聞`, because `ja_stop` does not normalize inflections or filter by grammatical category: + +```json +{ + "tokens": [ + { + "token": "新聞", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "読ん", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "ばかり", + "start_offset": 8, + "end_offset": 11, + "type": "word", + "position": 5 + } + ] +} +``` + +Compare this with the following [full pipeline example](#example-full-analysis-pipeline). Adding `kuromoji_baseform` normalizes `読ん` to its dictionary form `読む`. Adding `kuromoji_part_of_speech` removes the adverbial particle `ばかり`, which is not in the `_japanese_` stop word list and therefore cannot be removed by `ja_stop` alone. + +## 示例: Full analysis pipeline + +This example uses the same sentence `新聞を読んでいるばかりだ` ("I do nothing but read the newspaper") to show how all three filters contribute distinct work when combined: + +- `kuromoji_baseform` normalizes the inflected verb stem `読ん` to its dictionary form `読む`. +- `kuromoji_part_of_speech` removes the adverbial particle `ばかり`, which `ja_stop` does not handle, and the particles `を`, `で`, and `だ`, which `ja_stop` also removes. +- `ja_stop` removes the remaining `いる`, which is listed in the built-in Japanese stop set. + +Create an index with an analyzer that chains all three filters: + +```json +PUT /ja-stop-index +{ + "settings": { + "analysis": { + "analyzer": { + "ja_stop_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_baseform", "kuromoji_part_of_speech", "ja_stop"] + } + } + } + } +} +``` + +Test the analyzer with the same sentence: + +```json +POST /ja-stop-index/_analyze +{ + "analyzer": "ja_stop_analyzer", + "text": "新聞を読んでいるばかりだ" +} +``` + +响应包含 only the two content tokens with the verb in its base form: + +```json +{ + "tokens": [ + { + "token": "新聞", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "読む", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + } + ] +} +``` + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji base form token filter](/analyzers/token-filters/kuromoji-baseform) +- [Kuromoji part-of-speech token filter](/analyzers/token-filters/kuromoji-part-of-speech) diff --git a/i18n/zh/analyzers/token-filters/keep-types.md b/i18n/zh/analyzers/token-filters/keep-types.md new file mode 100644 index 00000000..5a418043 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/keep-types.md @@ -0,0 +1,111 @@ +--- +title: 保留类型 +--- + +# Keep types token filter + +The `keep_types` token filter is a type of token filter used in text analysis to control which token types are kept or discarded. Different tokenizers produce different token types, for example, `<HOST>`, `<NUM>`, or `<ALPHANUM>`. + +::: info NOTE +The `keyword`, `simple_pattern`, and `simple_pattern_split` tokenizers do not support the `keep_types` token filter because these tokenizers do not support token type attributes. +::: + +## 参数 + +The `keep_types` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`types` | 必需 | List of strings | List of token types to be kept or discarded (determined by the `mode`). +`mode`| 可选 | String | Whether to `include` or `exclude` the token types specified in `types`. Default is `include`. + + +## 示例 + +The following example request creates a new index named `test_index` and configures an analyzer with a `keep_types` filter: + +```json +PUT /test_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "keep_types_filter"] + } + }, + "filter": { + "keep_types_filter": { + "type": "keep_types", + "types": ["<ALPHANUM>"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /test_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Hello 2 world! This is an example." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "hello", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "world", + "start_offset": 8, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "this", + "start_offset": 15, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "is", + "start_offset": 20, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "an", + "start_offset": 23, + "end_offset": 25, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "example", + "start_offset": 26, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 6 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/keep-words.md b/i18n/zh/analyzers/token-filters/keep-words.md new file mode 100644 index 00000000..34336050 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/keep-words.md @@ -0,0 +1,87 @@ +--- +title: 保留单词 +--- + +# Keep words token filter + +The `keep_words` token filter is designed to keep only certain words during the analysis process. This filter is useful if you have a large body of text but are only interested in certain keywords or terms. + +## 参数 + +The `keep_words` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`keep_words` | Required if `keep_words_path` is not configured | List of strings | The list of words to keep. +`keep_words_path` | 必需 if `keep_words` is not configured | String | The path to the file containing the list of words to keep. +`keep_words_case` | 可选 | Boolean | Whether to lowercase all words during comparison. Default is `false`. + + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `keep_words` filter: + +```json +PUT my_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_keep_word": { + "tokenizer": "standard", + "filter": [ "keep_words_filter" ] + } + }, + "filter": { + "keep_words_filter": { + "type": "keep", + "keep_words": ["example", "world", "opensearch"], + "keep_words_case": true + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_index/_analyze +{ + "analyzer": "custom_keep_word", + "text": "Hello, world! This is an OpenSearch example." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "world", + "start_offset": 7, + "end_offset": 12, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "OpenSearch", + "start_offset": 25, + "end_offset": 35, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "example", + "start_offset": 36, + "end_offset": 43, + "type": "<ALPHANUM>", + "position": 6 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/keyword-marker.md b/i18n/zh/analyzers/token-filters/keyword-marker.md new file mode 100644 index 00000000..e176461b --- /dev/null +++ b/i18n/zh/analyzers/token-filters/keyword-marker.md @@ -0,0 +1,121 @@ +--- +title: 关键词标记 +--- + +# Keyword marker token filter + +The `keyword_marker` token filter is used to prevent certain tokens from being altered by stemmers or other filters. The `keyword_marker` token filter does this by marking the specified tokens as `keywords`, which prevents any stemming or other processing. This ensures that specific words remain in their original form. + +## 参数 + +The `keyword_marker` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`ignore_case` | 可选 | Boolean | Whether to ignore the letter case when matching keywords. Default is `false`. +`keywords` | 必需 if either `keywords_path` or `keywords_pattern` is not set | List of strings | The list of tokens to mark as keywords. +`keywords_path` | 必需 if either `keywords` or `keywords_pattern` is not set | String | The path (relative to the `config` directory or absolute) to the list of keywords. +`keywords_pattern` | 必需 if either `keywords` or `keywords_path` is not set | String | A [regular expression](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) used for matching tokens to be marked as keywords. + + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `keyword_marker` filter. The filter marks the word `example` as a keyword: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": ["lowercase", "keyword_marker_filter", "stemmer"] + } + }, + "filter": { + "keyword_marker_filter": { + "type": "keyword_marker", + "keywords": ["example"] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Favorite example" +} +``` + +响应包含 the generated tokens. Note that while the word `favorite` was stemmed, the word `example` was not stemmed because it was marked as a keyword: + +```json +{ + "tokens": [ + { + "token": "favorit", + "start_offset": 0, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "example", + "start_offset": 9, + "end_offset": 16, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` + +You can further examine the impact of the `keyword_marker` token filter by adding the following parameters to the `_analyze` query: + +```json +GET /my_index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "This is an OpenSearch example demonstrating keyword marker.", + "explain": true, + "attributes": "keyword" +} +``` + +This will produce additional details in the response similar to the following: + +```json +{ + "name": "porter_stem", + "tokens": [ + ... + { + "token": "example", + "start_offset": 22, + "end_offset": 29, + "type": "<ALPHANUM>", + "position": 4, + "keyword": true + }, + { + "token": "demonstr", + "start_offset": 30, + "end_offset": 43, + "type": "<ALPHANUM>", + "position": 5, + "keyword": false + }, + ... + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/keyword-repeat.md b/i18n/zh/analyzers/token-filters/keyword-repeat.md new file mode 100644 index 00000000..690f0b25 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/keyword-repeat.md @@ -0,0 +1,154 @@ +--- +title: 关键词重复 +--- + +# Keyword repeat token filter + +The `keyword_repeat` token filter emits the keyword version of a token into a token stream. This filter is typically used when you want to retain both the original token and its modified version after further token transformations, such as stemming or synonym expansion. The duplicated tokens allow the original, unchanged version of the token to remain in the final analysis alongside the modified versions. + +::: info NOTE +The `keyword_repeat` token filter should be placed before stemming filters. Stemming is not applied to every token, thus you may have duplicate tokens in the same position after stemming. To remove duplicate tokens, use the `remove_duplicates` token filter after the stemmer. +::: + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `keyword_repeat` filter: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "filter": { + "my_kstem": { + "type": "kstem" + }, + "my_lowercase": { + "type": "lowercase" + } + }, + "analyzer": { + "my_custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "my_lowercase", + "keyword_repeat", + "my_kstem" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "Stopped quickly" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "stopped", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "stop", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "quickly", + "start_offset": 8, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "quick", + "start_offset": 8, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` + +You can further examine the impact of the `keyword_repeat` token filter by adding the following parameters to the `_analyze` query: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "Stopped quickly", + "explain": true, + "attributes": "keyword" +} +``` + +The response includes detailed information, such as tokenization, filtering, and the application of specific token filters: + +```json +{ + "detail": { + "custom_analyzer": true, + "charfilters": [], + "tokenizer": { + "name": "standard", + "tokens": [ + {"token": "OpenSearch","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0}, + {"token": "helped","start_offset": 11,"end_offset": 17,"type": "<ALPHANUM>","position": 1}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "<ALPHANUM>","position": 2}, + {"token": "employers","start_offset": 23,"end_offset": 32,"type": "<ALPHANUM>","position": 3} + ] + }, + "tokenfilters": [ + { + "name": "lowercase", + "tokens": [ + {"token": "opensearch","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0}, + {"token": "helped","start_offset": 11,"end_offset": 17,"type": "<ALPHANUM>","position": 1}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "<ALPHANUM>","position": 2}, + {"token": "employers","start_offset": 23,"end_offset": 32,"type": "<ALPHANUM>","position": 3} + ] + }, + { + "name": "keyword_marker_filter", + "tokens": [ + {"token": "opensearch","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0,"keyword": true}, + {"token": "helped","start_offset": 11,"end_offset": 17,"type": "<ALPHANUM>","position": 1,"keyword": false}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "<ALPHANUM>","position": 2,"keyword": false}, + {"token": "employers","start_offset": 23,"end_offset": 32,"type": "<ALPHANUM>","position": 3,"keyword": false} + ] + }, + { + "name": "kstem_filter", + "tokens": [ + {"token": "opensearch","start_offset": 0,"end_offset": 10,"type": "<ALPHANUM>","position": 0,"keyword": true}, + {"token": "help","start_offset": 11,"end_offset": 17,"type": "<ALPHANUM>","position": 1,"keyword": false}, + {"token": "many","start_offset": 18,"end_offset": 22,"type": "<ALPHANUM>","position": 2,"keyword": false}, + {"token": "employer","start_offset": 23,"end_offset": 32,"type": "<ALPHANUM>","position": 3,"keyword": false} + ] + } + ] + } +} +``` diff --git a/i18n/zh/analyzers/token-filters/kstem.md b/i18n/zh/analyzers/token-filters/kstem.md new file mode 100644 index 00000000..40cc32ae --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kstem.md @@ -0,0 +1,87 @@ +--- +title: KStem +--- + +# KStem token filter + +The `kstem` token filter is a stemming filter used to reduce words to their root forms. The filter is a lightweight algorithmic stemmer designed for the English language that performs the following stemming operations: + +- Reduces plurals to their singular form. +- Converts different verb tenses to their base form. +- Removes common derivational endings, such as "-ing" or "-ed". + +The `kstem` token filter is equivalent to the a `stemmer` filter configured with a `light_english` language. It provides a more conservative stemming compared to other stemming filters like `porter_stem`. + +The `kstem` token filter is based on the Lucene KStemFilter. For more information, see the [Lucene documentation](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/en/KStemFilter.html). + +## 示例 + +The following example request creates a new index named `my_kstem_index` and configures an analyzer with a `kstem` filter: + +```json +PUT /my_kstem_index +{ + "settings": { + "analysis": { + "filter": { + "kstem_filter": { + "type": "kstem" + } + }, + "analyzer": { + "my_kstem_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "kstem_filter" + ] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_kstem_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_kstem_index/_analyze +{ + "analyzer": "my_kstem_analyzer", + "text": "stops stopped" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "stop", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "stop", + "start_offset": 6, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/kuromoji-baseform.md b/i18n/zh/analyzers/token-filters/kuromoji-baseform.md new file mode 100644 index 00000000..848e5722 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kuromoji-baseform.md @@ -0,0 +1,192 @@ +--- +title: Kuromoji 基本形式 +--- + +# Kuromoji base form token filter + +The `kuromoji_baseform` token filter replaces inflected Japanese tokens with their dictionary base form, acting as a lemmatizer. + +The filter applies to tokens that carry dictionary form information from the Kuromoji tokenizer. Tokens without dictionary information (such as unknown words) are passed through unchanged. + +Note that the Kuromoji tokenizer splits some conjugated forms into multiple tokens before this filter runs. For example, the past-tense *i*-adjective 美しかった (was beautiful) is split into 美しかっ and た. The filter normalizes 美しかっ to 美しい, but た remains as a separate token. To remove auxiliary verb tokens such as た, add [`kuromoji_part_of_speech`](/analyzers/token-filters/kuromoji-part-of-speech) and [`ja_stop`](/analyzers/token-filters/ja-stop) to the filter chain. + +## 安装 + +The `kuromoji_baseform` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The `kuromoji_baseform` token filter has no configurable parameters. + +## 示例 + +The following example creates an index with a custom analyzer that uses `kuromoji_baseform`: + +```json +PUT /kuromoji-baseform-index +{ + "settings": { + "analysis": { + "analyzer": { + "baseform_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_baseform"] + } + } + } + } +} +``` + +Test the analyzer with a sentence that includes conjugated verbs (meaning "I ate sushi and drank tea"): + +```json +POST /kuromoji-baseform-index/_analyze +{ + "analyzer": "baseform_analyzer", + "text": "寿司を食べてお茶を飲んだ" +} +``` + +The response shows the conjugated verbs normalized to their base forms. The particles を, て, and the auxiliary verb だ are retained because this analyzer uses only `kuromoji_baseform`: + +```json +{ + "tokens": [ + { + "token": "寿司", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "を", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "食べる", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "て", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 3 + }, + { + "token": "お茶", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "を", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 5 + }, + { + "token": "飲む", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 6 + }, + { + "token": "だ", + "start_offset": 11, + "end_offset": 12, + "type": "word", + "position": 7 + } + ] +} +``` + +The te-form 食べて and past-tense form 飲んだ are replaced with their base forms 食べる and 飲む. The particles を, て, and auxiliary verb だ remain in the token stream because `kuromoji_baseform` only normalizes inflection; it does not remove grammatical tokens. + +## 示例: Combining with part-of-speech and stop filters + +To also remove particles and auxiliary verbs, add `kuromoji_part_of_speech` and `ja_stop` to the filter chain. The following example creates an index with a combined analyzer: + +```json +PUT /kuromoji-baseform-full-index +{ + "settings": { + "analysis": { + "analyzer": { + "baseform_full_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_baseform", "kuromoji_part_of_speech", "ja_stop"] + } + } + } + } +} +``` + +Run the same sentence through the combined analyzer: + +```json +POST /kuromoji-baseform-full-index/_analyze +{ + "analyzer": "baseform_full_analyzer", + "text": "寿司を食べてお茶を飲んだ" +} +``` + +The response shows only the content words. The particles を, て, and the auxiliary verb だ are removed, and position gaps mark where they were: + +```json +{ + "tokens": [ + { + "token": "寿司", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "食べる", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "お茶", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "飲む", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 6 + } + ] +} +``` + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji part-of-speech token filter](/analyzers/token-filters/kuromoji-part-of-speech) +- [Japanese stop token filter](/analyzers/token-filters/ja-stop) diff --git a/i18n/zh/analyzers/token-filters/kuromoji-completion.md b/i18n/zh/analyzers/token-filters/kuromoji-completion.md new file mode 100644 index 00000000..7af1a281 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kuromoji-completion.md @@ -0,0 +1,256 @@ +--- +title: Kuromoji 补全 +--- + +# Kuromoji completion token filter + +The `kuromoji_completion` token filter generates romanized reading variants for Japanese tokens. When used in an index analyzer, it emits both the original token and one or more romanized alternatives at the same position. This allows users to search for Japanese content by typing in either Japanese characters or their phonetic equivalents. + +The filter is designed for use with the `kuromoji_completion` analyzer or in custom analyzers that power autocomplete or suggest fields. Because the filter is applied differently at index time and query time, it exposes a `mode` parameter. + +## 安装 + +The `kuromoji_completion` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The following table lists the parameters for the `kuromoji_completion` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`mode` | String | Controls how tokens are generated. Valid values are `index` (default) and `query`. Both modes expand katakana tokens into their original form plus all romaji variants. The `query` mode applies two additional rules for handling partial input from an input method editor (IME): it concatenates consecutive kana tokens into a single token before romanizing, and it merges a kana token with a trailing lowercase alphabet token that represents a partially typed IME keystroke (for example, `サッ` followed by `k` becomes `サッk`). + +::: tip TIP +Use `query` mode in the search analyzer so that partial IME input typed by a user is correctly assembled before romanization. +::: + +## 示例 + +The following example creates an index named `kuromoji_completion_example` with both an index-time analyzer (using `mode: index`) and a search-time analyzer (using `mode: query`), and maps the `suggest` field to use them: + +```json +PUT /kuromoji_completion_example +{ + "settings": { + "analysis": { + "filter": { + "completion_index_filter": { + "type": "kuromoji_completion", + "mode": "index" + }, + "completion_query_filter": { + "type": "kuromoji_completion", + "mode": "query" + } + }, + "analyzer": { + "completion_index_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["completion_index_filter"] + }, + "completion_query_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["completion_query_filter"] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "completion_index_analyzer", + "search_analyzer": "completion_query_analyzer" + } + } + } +} +``` + +With this configuration, a query containing either `konpyu` or `コンピュ` matches documents indexed with `コンピューター`. + +### Index-time tokens + +Use the following request to examine the tokens generated at index time using text that translates to "use a computer": + +```json +POST /kuromoji_completion_example/_analyze +{ + "analyzer": "completion_index_analyzer", + "text": "コンピューターを使う" +} +``` + +响应包含 the generated tokens. Each source token produces the original form plus one or more romaji variants at the same position. For `コンピューター` (computer), the filter emits the original katakana token and two romaji variants (`konpyuーtaー` and `konnpyuーtaー`). For the particle `を`, it emits the original and two romaji forms (`wo` and `o`). For the verb `使う` (use), it emits the original and two romaji forms (`tukau` and `tsukau`): + +```json +{ + "tokens": [ + { + "token": "コンピューター", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "konpyuーtaー", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "konnpyuーtaー", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "を", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "wo", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "o", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "使う", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 2 + }, + { + "token": "tukau", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 2 + }, + { + "token": "tsukau", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 2 + } + ] +} +``` + +### Query-time tokens + +Both modes expand katakana tokens into the original form plus all romaji variants. The key difference of `query` mode is its handling of partial IME input: when a katakana token is followed by a lowercase alphabet character that represents an in-progress IME keystroke, `query` mode concatenates them into a single token before romanizing. Without this, the partial keystroke would be processed as a separate token and the romanization would not match any indexed variant. + +The following example demonstrates this with the input `コンピュt`, which represents a user who has typed the katakana `コンピュ` and is still composing the next character `t` using an IME: + +```json +POST /kuromoji_completion_example/_analyze +{ + "analyzer": "completion_query_analyzer", + "text": "コンピュt" +} +``` + +The `query` mode recognizes `t` as a partial IME keystroke and merges it with the preceding katakana token before romanizing, producing three tokens for the combined form `コンピュt`: the merged katakana-plus-keystroke token and its two romaji variants (`konpyut` and `konnpyut`): + +```json +{ + "tokens": [ + { + "token": "コンピュt", + "start_offset": 0, + "end_offset": 5, + "type": "word", + "position": 0 + }, + { + "token": "konpyut", + "start_offset": 0, + "end_offset": 5, + "type": "word", + "position": 0 + }, + { + "token": "konnpyut", + "start_offset": 0, + "end_offset": 5, + "type": "word", + "position": 0 + } + ] +} +``` + +With `index` mode, `コンピュ` and `t` would be emitted as two separate tokens at different positions, so the romanized form `konpyut` would never be produced and a search for `konpyut` would not match. + +### Searching with prefix queries + +Because the index stores the original katakana token and all its romaji variants, you can use a `prefix` query directly against the indexed romaji tokens to implement autocomplete. The `prefix` query bypasses the analyzer and matches any indexed token that starts with the given value. + +First, index a sample document: + +```json +POST /kuromoji_completion_example/_doc/1 +{ + "content": "コンピューターを使う" +} +``` + +The following `prefix` query matches the document because `konnp` is a prefix of the indexed romaji token `konnpyuーtaー`: + +```json +GET /kuromoji_completion_example/_search +{ + "query": { + "prefix": { + "content": { + "value": "konnp" + } + } + } +} +``` + +The following `prefix` query matches the document using the katakana prefix `コンピュ`, which is a prefix of the indexed katakana token `コンピューター`: + +```json +GET /kuromoji_completion_example/_search +{ + "query": { + "prefix": { + "content": { + "value": "コンピュ" + } + } + } +} +``` + +::: tip TIP +For a higher-level approach that configures the `mode` at the analyzer level rather than the filter level, use the built-in [`kuromoji_completion` analyzer](/analyzers/language-analyzers/kuromoji#kuromoji-completion-analyzer). +::: + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji reading form token filter](/analyzers/token-filters/kuromoji-readingform) +- [Japanese stop token filter](/analyzers/token-filters/ja-stop) diff --git a/i18n/zh/analyzers/token-filters/kuromoji-number.md b/i18n/zh/analyzers/token-filters/kuromoji-number.md new file mode 100644 index 00000000..062eb4d9 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kuromoji-number.md @@ -0,0 +1,103 @@ +--- +title: Kuromoji 数字 +--- + +# Kuromoji number token filter + +The `kuromoji_number` token filter normalizes Japanese numeral expressions to standard Arabic numerals. Japanese text can represent numbers using kanji numerals (一, 二, 三…), full-width digits (1, 2, 3…), or a mix of both. This filter converts all such expressions to their standard integer or decimal equivalents. + +The filter makes conversions such as the following: + +- 一万二千三百四十五 becomes 12345. +- 3,〇00 becomes 3000. +- 千円 becomes 1000, with the unit 円 remaining as a separate token. + +This filter is useful for faceted search, range queries, and sorting on fields that contain prices, counts, or other quantities written in Japanese notation. + +## 安装 + +The `kuromoji_number` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The `kuromoji_number` token filter has no configurable parameters. + +## 示例 + +The following example creates an index with a custom analyzer that uses `kuromoji_number`: + +```json +PUT /kuromoji-number-index +{ + "settings": { + "analysis": { + "analyzer": { + "number_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_number"] + } + } + } + } +} +``` + +Test the analyzer with text containing kanji numeral expressions (meaning "the price is 12,345 yen"): + +```json +POST /kuromoji-number-index/_analyze +{ + "analyzer": "number_analyzer", + "text": "価格は一万二千三百四十五円です" +} +``` + +The response shows the kanji numeral converted to an Arabic integer. Note that the `12345` token spans over offsets 3–12 because the source kanji numeral `一万二千三百四十五` is 9 characters long: + +```json +{ + "tokens": [ + { + "token": "価格", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "は", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "12345", + "start_offset": 3, + "end_offset": 12, + "type": "word", + "position": 2 + }, + { + "token": "円", + "start_offset": 12, + "end_offset": 13, + "type": "word", + "position": 3 + }, + { + "token": "です", + "start_offset": 13, + "end_offset": 15, + "type": "word", + "position": 4 + } + ] +} +``` + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) diff --git a/i18n/zh/analyzers/token-filters/kuromoji-part-of-speech.md b/i18n/zh/analyzers/token-filters/kuromoji-part-of-speech.md new file mode 100644 index 00000000..d721312e --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kuromoji-part-of-speech.md @@ -0,0 +1,123 @@ +--- +title: Kuromoji 词性 +--- + +# Kuromoji part of speech token filter + +The `kuromoji_part_of_speech` token filter removes tokens whose part-of-speech (POS) tag matches an entry in a configured list of stop tags. The Kuromoji tokenizer assigns each token an IPAdic POS tag. This filter reads that tag and discards tokens that serve a grammatical function (such as particles, auxiliary verbs, and punctuation) rather than a content function. + +## 安装 + +The `kuromoji_part_of_speech` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The following table lists the parameters for the `kuromoji_part_of_speech` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`stoptags` | Array of strings | A list of IPAdic part-of-speech tags to remove. Tokens whose POS tag exactly matches an entry in this list are discarded. Default is the built-in Japanese stop tag set. + +For the full list of available stop tags, see [stoptags.txt](https://github.com/apache/lucene/blob/main/lucene/analysis/kuromoji/src/resources/org/apache/lucene/analysis/ja/stoptags.txt) in the Lucene repository. + +## 示例: Default filter + +The following example creates an index with an analyzer that uses the default stop tag list: + +```json +PUT /kuromoji-pos-index +{ + "settings": { + "analysis": { + "analyzer": { + "pos_filter_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["kuromoji_part_of_speech"] + } + } + } + } +} +``` + +Test the analyzer with a sentence meaning "I eat sushi at the Tokyo restaurant": + +```json +POST /kuromoji-pos-index/_analyze +{ + "analyzer": "pos_filter_analyzer", + "text": "東京のレストランで寿司を食べる" +} +``` + +The response shows the particles の (genitive), で (locative), and を (accusative) removed: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "レストラン", + "start_offset": 3, + "end_offset": 8, + "type": "word", + "position": 2 + }, + { + "token": "寿司", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 4 + }, + { + "token": "食べる", + "start_offset": 12, + "end_offset": 15, + "type": "word", + "position": 6 + } + ] +} +``` + +## 示例: Custom stop tags + +The following example creates a filter that removes only auxiliary verbs (助動詞) while keeping all other grammatical tokens: + +```json +PUT /kuromoji-custom-pos-index +{ + "settings": { + "analysis": { + "filter": { + "auxiliary_verb_filter": { + "type": "kuromoji_part_of_speech", + "stoptags": ["助動詞"] + } + }, + "analyzer": { + "auxiliary_filter_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["auxiliary_verb_filter"] + } + } + } + } +} +``` + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji base form token filter](/analyzers/token-filters/kuromoji-baseform) +- [Japanese stop token filter](/analyzers/token-filters/ja-stop) diff --git a/i18n/zh/analyzers/token-filters/kuromoji-readingform.md b/i18n/zh/analyzers/token-filters/kuromoji-readingform.md new file mode 100644 index 00000000..abf32cb3 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kuromoji-readingform.md @@ -0,0 +1,205 @@ +--- +title: Kuromoji reading form +--- + +# Kuromoji reading form token filter + +The `kuromoji_readingform` token filter replaces each token with its reading form. Japanese characters (kanji) have multiple possible readings; this filter uses the reading information provided by the Kuromoji tokenizer to emit the phonetic form of each token. The filter can output readings in katakana (Japanese phonetic script) or in romaji (Latin script transliteration). + +## 安装 + +The `kuromoji_readingform` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The following table lists the parameters for the `kuromoji_readingform` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`use_romaji` | Boolean | When `false` (default), tokens are replaced with their katakana reading. When `true`, tokens are replaced with their romaji (Latin script) transliteration. + +## 示例: Katakana reading (default) + +The following example creates an index with an analyzer that outputs katakana readings: + +```json +PUT /kuromoji-reading-katakana-index +{ + "settings": { + "analysis": { + "filter": { + "katakana_reading": { + "type": "kuromoji_readingform", + "use_romaji": false + } + }, + "analyzer": { + "katakana_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["katakana_reading"] + } + } + } + } +} +``` + +Test the analyzer with a sentence meaning "Tokyo is the capital of Japan": + +```json +POST /kuromoji-reading-katakana-index/_analyze +{ + "analyzer": "katakana_analyzer", + "text": "東京は日本の首都です" +} +``` + +The response shows kanji tokens replaced with their katakana readings: + +```json +{ + "tokens": [ + { + "token": "トウキョウ", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "ハ", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "ニッポン", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "ノ", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 3 + }, + { + "token": "シュト", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "デス", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 5 + } + ] +} +``` + +## 示例: Romaji reading + +The following example creates an analyzer that outputs romaji transliterations: + +```json +PUT /kuromoji-reading-romaji-index +{ + "settings": { + "analysis": { + "filter": { + "romaji_reading": { + "type": "kuromoji_readingform", + "use_romaji": true + } + }, + "analyzer": { + "romaji_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["romaji_reading"] + } + } + } + } +} +``` + +Test with the same sentence: + +```json +POST /kuromoji-reading-romaji-index/_analyze +{ + "analyzer": "romaji_analyzer", + "text": "東京は日本の首都です" +} +``` + +The response shows Latin-script transliterations: + +```json +{ + "tokens": [ + { + "token": "tōkyō", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "ha", + "start_offset": 2, + "end_offset": 3, + "type": "word", + "position": 1 + }, + { + "token": "nippon", + "start_offset": 3, + "end_offset": 5, + "type": "word", + "position": 2 + }, + { + "token": "no", + "start_offset": 5, + "end_offset": 6, + "type": "word", + "position": 3 + }, + { + "token": "shuto", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "desu", + "start_offset": 8, + "end_offset": 10, + "type": "word", + "position": 5 + } + ] +} +``` + +::: tip TIP +The reading form filter replaces the entire token content. If you need both the original form and the reading, use the `kuromoji_completion` token filter instead, which adds reading variants as additional tokens at the same position. +::: + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji completion token filter](/analyzers/token-filters/kuromoji-completion) diff --git a/i18n/zh/analyzers/token-filters/kuromoji-stemmer.md b/i18n/zh/analyzers/token-filters/kuromoji-stemmer.md new file mode 100644 index 00000000..e4c0bd06 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/kuromoji-stemmer.md @@ -0,0 +1,115 @@ +--- +title: Kuromoji 词干提取器 +--- + +# Kuromoji stemmer token filter + +The `kuromoji_stemmer` token filter normalizes katakana words by removing a trailing long vowel mark (ー) from words that meet a minimum length threshold. Many foreign loanwords in Japanese are written in katakana with a trailing ー that denotes a lengthened final vowel (for example, コンピューター, プリンター). In practice, Japanese speakers often drop the trailing ー in informal or technical writing, resulting in two surface forms for the same word. This filter collapses those variants to a single canonical form. + +The filter makes conversions such as the following: + +- コンピューター (computer) becomes コンピュータ. +- プリンター (printer) becomes プリンタ. + +## 安装 + +The `kuromoji_stemmer` token filter requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The following table lists the parameters for the `kuromoji_stemmer` token filter. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`minimum_length` | Integer | The minimum number of characters a token must have for the trailing long vowel mark to be removed. Tokens shorter than this threshold are passed through unchanged. Default is `4`. + +::: info NOTE +The default minimum length of `4` prevents short words such as カー (car, two characters) from being incorrectly stemmed to カ. +::: + +## 示例 + +The following example creates an index with a custom analyzer that uses `kuromoji_stemmer`: + +```json +PUT /kuromoji-stemmer-index +{ + "settings": { + "analysis": { + "filter": { + "katakana_stemmer": { + "type": "kuromoji_stemmer", + "minimum_length": 4 + } + }, + "analyzer": { + "stemmer_analyzer": { + "type": "custom", + "tokenizer": "kuromoji_tokenizer", + "filter": ["katakana_stemmer"] + } + } + } + } +} +``` + +Test the analyzer with katakana loanwords (meaning "I use a computer and printer"): + +```json +POST /kuromoji-stemmer-index/_analyze +{ + "analyzer": "stemmer_analyzer", + "text": "コンピューターとプリンターを使う" +} +``` + +The response shows the trailing long vowel marks removed from both words: + +```json +{ + "tokens": [ + { + "token": "コンピュータ", + "start_offset": 0, + "end_offset": 7, + "type": "word", + "position": 0 + }, + { + "token": "と", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "プリンタ", + "start_offset": 8, + "end_offset": 13, + "type": "word", + "position": 2 + }, + { + "token": "を", + "start_offset": 13, + "end_offset": 14, + "type": "word", + "position": 3 + }, + { + "token": "使う", + "start_offset": 14, + "end_offset": 16, + "type": "word", + "position": 4 + } + ] +} +``` + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji tokenizer](/analyzers/tokenizers/kuromoji) +- [Kuromoji base form token filter](/analyzers/token-filters/kuromoji-baseform) diff --git a/i18n/zh/analyzers/token-filters/length.md b/i18n/zh/analyzers/token-filters/length.md new file mode 100644 index 00000000..3aa04ea5 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/length.md @@ -0,0 +1,86 @@ +--- +title: 长度 +--- + +# Length token filter + +The `length` token filter is used to remove tokens that don't meet specified length criteria (minimum and maximum values) from the token stream. + +## 参数 + +The `length` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`min` | 可选 | Integer | The minimum token length. Default is `0`. +`max` | 可选 | Integer | The maximum token length. Default is `Integer.MAX_VALUE` (`2147483647`). + + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `length` filter: + +```json +PUT my_index +{ + "settings": { + "analysis": { + "analyzer": { + "only_keep_4_to_10_characters": { + "tokenizer": "whitespace", + "filter": [ "length_4_to_10" ] + } + }, + "filter": { + "length_4_to_10": { + "type": "length", + "min": 4, + "max": 10 + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_index/_analyze +{ + "analyzer": "only_keep_4_to_10_characters", + "text": "OpenSearch is a great tool!" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "great", + "start_offset": 16, + "end_offset": 21, + "type": "word", + "position": 3 + }, + { + "token": "tool!", + "start_offset": 22, + "end_offset": 27, + "type": "word", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/limit.md b/i18n/zh/analyzers/token-filters/limit.md new file mode 100644 index 00000000..76245e94 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/limit.md @@ -0,0 +1,84 @@ +--- +title: Limit +--- + +# Limit token filter + +The `limit` token filter is used to limit the number of tokens passed through the analysis chain. + +## 参数 + +The `limit` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`max_token_count` | 可选 | Integer | The maximum number of tokens to be generated. Default is `1`. +`consume_all_tokens` | 可选 | Boolean | (Expert-level setting) Uses all tokens from the tokenizer, even if the result exceeds `max_token_count`. When this parameter is set, the output still only contains the number of tokens specified by `max_token_count`. However, all tokens generated by the tokenizer are processed. Default is `false`. + +## 示例 + +The following example request creates a new index named `my_index` and configures an analyzer with a `limit` filter: + +```json +PUT my_index +{ + "settings": { + "analysis": { + "analyzer": { + "three_token_limit": { + "tokenizer": "standard", + "filter": [ "custom_token_limit" ] + } + }, + "filter": { + "custom_token_limit": { + "type": "limit", + "max_token_count": 3 + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_index/_analyze +{ + "analyzer": "three_token_limit", + "text": "OpenSearch is a powerful and flexible search engine." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "a", + "start_offset": 14, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/lowercase.md b/i18n/zh/analyzers/token-filters/lowercase.md new file mode 100644 index 00000000..7670ee02 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/lowercase.md @@ -0,0 +1,77 @@ +--- +title: 小写 +--- + +# Lowercase token filter + +The `lowercase` token filter is used to convert all characters in the token stream to lowercase, making searches case insensitive. + +## 参数 + +The `lowercase` token filter can be configured with the following parameter. + +Parameter | 是否必需 | Description +:--- | :--- | :--- + `language` | 可选 | Specifies a language-specific token filter. Valid values are: <br>- [`greek`](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/el/GreekLowerCaseFilter.html) <br>- [`irish`](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/ga/IrishLowerCaseFilter.html) <br>- [`turkish`](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/tr/TurkishLowerCaseFilter.html). <br> Default is the [Lucene LowerCaseFilter](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/core/LowerCaseFilter.html). + +## 示例 + +The following example request creates a new index named `custom_lowercase_example`. It configures an analyzer with a `lowercase` filter and specifies `greek` as the `language`: + +```json +PUT /custom_lowercase_example +{ + "settings": { + "analysis": { + "analyzer": { + "greek_lowercase_example": { + "type": "custom", + "tokenizer": "standard", + "filter": ["greek_lowercase"] + } + }, + "filter": { + "greek_lowercase": { + "type": "lowercase", + "language": "greek" + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /custom_lowercase_example/_analyze +{ + "analyzer": "greek_lowercase_example", + "text": "Αθήνα ΕΛΛΑΔΑ" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "αθηνα", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "ελλαδα", + "start_offset": 6, + "end_offset": 12, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/min-hash.md b/i18n/zh/analyzers/token-filters/min-hash.md new file mode 100644 index 00000000..f38dc967 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/min-hash.md @@ -0,0 +1,152 @@ +--- +title: Min hash +--- + +# Min hash token filter + +The `min_hash` token filter is used to generate hashes for tokens based on a [MinHash](https://en.wikipedia.org/wiki/MinHash) approximation algorithm, which is useful for detecting similarity between documents. The `min_hash` token filter generates hashes for a set of tokens (typically from an analyzed field). + +Finding similar documents by comparing a document to every other document in an index does not scale to large indexes. Locality-sensitive hashing (LSH) reduces the number of comparisons by hashing documents so that similar documents are likely to produce the same hash values and dissimilar documents are not. MinHash is an LSH technique for [Jaccard similarity](https://en.wikipedia.org/wiki/Jaccard_index), which measures the overlap between two sets of tokens: the number of tokens the sets share divided by the number of distinct tokens in both sets. + +MinHash applies a hash function to every token in a document and keeps only the smallest result. Two documents produce the same minimum hash with a probability equal to their Jaccard similarity, so the more minimum hashes two documents share, the more similar they are likely to be. The `min_hash` filter processes a token stream as follows: + +1. Hashes each token using `hash_count` hash functions. +1. Distributes the hashes among `bucket_count` buckets. +1. Emits the `hash_set_size` smallest hashes from each bucket as tokens. + +The emitted tokens form the document's signature. If you index the signature in a field, a full-text query on that field returns the documents that share signature tokens with the query text, which are candidates for near-duplicates. + +## 参数 + +The `min_hash` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`hash_count` | 可选 | Integer | The number of hash values to generate for each token. Increasing this value generally improves the accuracy of similarity estimation but increases the computational cost. Default is `1`. +`bucket_count` | 可选 | Integer | The number of hash buckets to use. This affects the granularity of the hashing. A larger number of buckets provides finer granularity and reduces hash collisions but requires more memory. Default is `512`. +`hash_set_size` | 可选 | Integer | The number of hashes to retain in each bucket. This can influence the hashing quality. Larger set sizes may lead to better similarity detection but consume more memory. Default is `1`. +`with_rotation` | 可选 | Boolean | When set to `true`, the filter populates empty buckets with the value from the first non-empty bucket found to its circular right, provided that the `hash_set_size` is `1`. If the `bucket_count` argument exceeds `1`, this setting automatically defaults to `true`; otherwise, it defaults to `false`. + +## Tuning the min_hash filter + +Consider the following guidelines when configuring the `min_hash` filter: + +- Use word shingles, produced by the [`shingle`](/analyzers/token-filters/shingle) filter, as input to the `min_hash` filter. Comparing sequences of words detects shared passages, while comparing single words only detects shared vocabulary. Choose a shingle size large enough that most shingles are rare across your documents but small enough that the possible shingles can be hashed into 128 bits with few collisions. +- Experiment with the parameter values using your own data. Increasing `bucket_count` or `hash_set_size` keeps more hashes for each document, which makes it less likely that dissimilar documents share tokens and improves precision. Increasing `hash_count` hashes each token in several ways, which produces more candidate matches and improves recall. +- Account for the increase in index size. Each token encodes a 128-bit hash. When `with_rotation` is `true` and `hash_set_size` is `1`, the filter emits `bucket_count` × `hash_count` tokens for every document, regardless of the document's length, so the default settings produce 512 tokens for each document. +- The `min_hash` filter measures whether a token is present, not how often it occurs. A document containing a word once and a document containing the same word many times produce the same hashes. + +## 示例 + +The following example request creates a new index named `minhash_index` and configures an analyzer with a `min_hash` filter: + +```json +PUT /minhash_index +{ + "settings": { + "analysis": { + "filter": { + "minhash_filter": { + "type": "min_hash", + "hash_count": 3, + "bucket_count": 512, + "hash_set_size": 1, + "with_rotation": false + } + }, + "analyzer": { + "minhash_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "minhash_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /minhash_index/_analyze +{ + "analyzer": "minhash_analyzer", + "text": "OpenSearch is very powerful." +} +``` + +响应包含 the generated tokens (the tokens are not human readable because they represent hashes): + +```json +{ + "tokens" : [ + { + "token" : "\u0000\u0000㳠锯ੲ걌䐩䉵", + "start_offset" : 0, + "end_offset" : 27, + "type" : "MIN_HASH", + "position" : 0 + }, + { + "token" : "\u0000\u0000㳠锯ੲ걌䐩䉵", + "start_offset" : 0, + "end_offset" : 27, + "type" : "MIN_HASH", + "position" : 0 + }, + ... +``` + +In order to demonstrate the usefulness of the `min_hash` token filter, you can use the following Python script to compare the two strings using the previously created analyzer: + +```python +from opensearchpy import OpenSearch +from requests.auth import HTTPBasicAuth + +# Initialize the OpenSearch client with authentication +host = 'https://localhost:9200' # Update if using a different host/port +auth = ('admin', 'admin') # Username and password + +# Create the OpenSearch client with SSL verification turned off +client = OpenSearch( + hosts=[host], + http_auth=auth, + use_ssl=True, + verify_certs=False, # Disable SSL certificate validation + ssl_show_warn=False # Suppress SSL warnings in the output +) + +# Analyzes text and returns the minhash tokens +def analyze_text(index, text): + response = client.indices.analyze( + index=index, + body={ + "analyzer": "minhash_analyzer", + "text": text + } + ) + return [token['token'] for token in response['tokens']] + +# Analyze two similar texts +tokens_1 = analyze_text('minhash_index', 'OpenSearch is a powerful search engine.') +tokens_2 = analyze_text('minhash_index', 'OpenSearch is a very powerful search engine.') + +# Calculate Jaccard similarity +set_1 = set(tokens_1) +set_2 = set(tokens_2) +shared_tokens = set_1.intersection(set_2) +jaccard_similarity = len(shared_tokens) / len(set_1.union(set_2)) + +print(f"Jaccard Similarity: {jaccard_similarity}") +``` + +The response should contain the Jaccard similarity score: + +```yaml +Jaccard Similarity: 0.8571428571428571 +``` diff --git a/i18n/zh/analyzers/token-filters/multiplexer.md b/i18n/zh/analyzers/token-filters/multiplexer.md new file mode 100644 index 00000000..1f1afd81 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/multiplexer.md @@ -0,0 +1,162 @@ +--- +title: 多路复用器 +--- + +# Multiplexer token filter + +The `multiplexer` token filter allows you to create multiple versions of the same token by applying different filters. This is useful when you want to analyze the same token in multiple ways. For example, you may want to analyze a token using different stemming, synonyms, or n-gram filters and use all of the generated tokens together. This token filter works by duplicating the token stream and applying different filters to each copy. + +::: warning IMPORTANT +The `multiplexer` token filter removes duplicate tokens from the token stream. +::: + +::: warning IMPORTANT +The `multiplexer` token filter does not support multiword `synonym` or `synonym_graph` token filters or `shingle` token filters because they need to analyze not only the current token but also upcoming tokens in order to determine how to transform the input correctly. +::: + +## 参数 + +The `multiplexer` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`filters` | 可选 | List of strings | A comma-separated list of token filters to apply to each copy of the token stream. Default is an empty list. +`preserve_original` | 可选 | Boolean | Whether to keep the original token as one of the outputs. Default is `true`. + +## 示例 + +The following example request creates a new index named `multiplexer_index` and configures an analyzer with a `multiplexer` filter: + +```json +PUT /multiplexer_index +{ + "settings": { + "analysis": { + "filter": { + "english_stemmer": { + "type": "stemmer", + "name": "english" + }, + "synonym_filter": { + "type": "synonym", + "synonyms": [ + "quick,fast" + ] + }, + "multiplexer_filter": { + "type": "multiplexer", + "filters": ["english_stemmer", "synonym_filter"], + "preserve_original": true + } + }, + "analyzer": { + "multiplexer_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "multiplexer_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /multiplexer_index/_analyze +{ + "analyzer": "multiplexer_analyzer", + "text": "The slow turtle hides from the quick dog" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "The", + "start_offset": 0, + "end_offset": 3, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "slow", + "start_offset": 4, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "turtle", + "start_offset": 9, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "turtl", + "start_offset": 9, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "hides", + "start_offset": 16, + "end_offset": 21, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "hide", + "start_offset": 16, + "end_offset": 21, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "from", + "start_offset": 22, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "the", + "start_offset": 27, + "end_offset": 30, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "quick", + "start_offset": 31, + "end_offset": 36, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "fast", + "start_offset": 31, + "end_offset": 36, + "type": "SYNONYM", + "position": 6 + }, + { + "token": "dog", + "start_offset": 37, + "end_offset": 40, + "type": "<ALPHANUM>", + "position": 7 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/ngram.md b/i18n/zh/analyzers/token-filters/ngram.md new file mode 100644 index 00000000..2f29d4de --- /dev/null +++ b/i18n/zh/analyzers/token-filters/ngram.md @@ -0,0 +1,132 @@ +--- +title: N-gram +--- + +# N-gram token filter + +The `ngram` token filter is a powerful tool used to break down text into smaller components, known as _n-grams_, which can improve partial matching and fuzzy search capabilities. It works by splitting a token into smaller substrings of defined lengths. These filters are commonly used in search applications to support autocomplete, partial matches, and typo-tolerant search. For more information, see [Autocomplete functionality](/search-plugins/searching-data/autocomplete) and [Did-you-mean](/search-plugins/searching-data/did-you-mean). + +## 参数 + +The `ngram` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`min_gram` | 可选 | Integer | The minimum length of the n-grams. Default is `1`. +`max_gram` | 可选 | Integer | The maximum length of the n-grams. Default is `2`. +`preserve_original` | 可选 | Boolean | Whether to keep the original token as one of the outputs. Default is `false`. + +## 示例 + +The following example request creates a new index named `ngram_example_index` and configures an analyzer with an `ngram` filter: + +```json +PUT /ngram_example_index +{ + "settings": { + "analysis": { + "filter": { + "ngram_filter": { + "type": "ngram", + "min_gram": 2, + "max_gram": 3 + } + }, + "analyzer": { + "ngram_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "ngram_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /ngram_example_index/_analyze +{ + "analyzer": "ngram_analyzer", + "text": "Search" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "se", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "sea", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "ea", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "ear", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "ar", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "arc", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "rc", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "rch", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "ch", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/normalization.md b/i18n/zh/analyzers/token-filters/normalization.md new file mode 100644 index 00000000..1e9789e9 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/normalization.md @@ -0,0 +1,82 @@ +--- +title: 规范化 +--- + +# Normalization token filter + +The `normalization` token filter is designed to adjust and simplify text in a way that reduces variations, particularly variations in special characters. It is primarily used to handle variations in writing by standardizing characters in specific languages. + +The following `normalization` token filters are available: + +- [arabic_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/ar/ArabicNormalizationFilter.html) +- [german_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html) +- [hindi_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/hi/HindiNormalizationFilter.html) +- [indic_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/in/IndicNormalizationFilter.html) +- [sorani_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/ckb/SoraniNormalizationFilter.html) +- [persian_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html) +- [scandinavian_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/miscellaneous/ScandinavianNormalizationFilter.html) +- [scandinavian_folding](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/miscellaneous/ScandinavianFoldingFilter.html) +- [serbian_normalization](https://lucene.apache.org/core/9_9_2/analysis/common/org/apache/lucene/analysis/sr/SerbianNormalizationFilter.html) + +## 示例 + +The following example request creates a new index named `german_normalizer_example` and configures an analyzer with a `german_normalization` filter: + +```json +PUT /german_normalizer_example +{ + "settings": { + "analysis": { + "filter": { + "german_normalizer": { + "type": "german_normalization" + } + }, + "analyzer": { + "german_normalizer_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "german_normalizer" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /german_normalizer_example/_analyze +{ + "text": "Straße München", + "analyzer": "german_normalizer_analyzer" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "strasse", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "munchen", + "start_offset": 7, + "end_offset": 14, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/pattern-capture.md b/i18n/zh/analyzers/token-filters/pattern-capture.md new file mode 100644 index 00000000..2ab96370 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/pattern-capture.md @@ -0,0 +1,91 @@ +--- +title: 模式捕获 +--- + +# Pattern capture token filter + +The `pattern_capture` token filter is a powerful filter that uses regular expressions to capture and extract parts of text according to specific patterns. This filter can be useful when you want to extract particular parts of tokens, such as email domains, hashtags, or numbers, and reuse them for further analysis or indexing. + +## 参数 + +The `pattern_capture` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`patterns` | 必需 | Array of strings | An array of regular expressions used to capture parts of text. +`preserve_original` | 必需 | Boolean| Whether to keep the original token in the output. Default is `true`. + +## 示例 + +The following example request creates a new index named `email_index` and configures an analyzer with a `pattern_capture` filter to extract the local part and domain name from an email address: + +```json +PUT /email_index +{ + "settings": { + "analysis": { + "filter": { + "email_pattern_capture": { + "type": "pattern_capture", + "preserve_original": true, + "patterns": [ + "^([^@]+)", + "@(.+)$" + ] + } + }, + "analyzer": { + "email_analyzer": { + "tokenizer": "uax_url_email", + "filter": [ + "email_pattern_capture", + "lowercase" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /email_index/_analyze +{ + "text": "john.doe@example.com", + "analyzer": "email_analyzer" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "john.doe@example.com", + "start_offset": 0, + "end_offset": 20, + "type": "<EMAIL>", + "position": 0 + }, + { + "token": "john.doe", + "start_offset": 0, + "end_offset": 20, + "type": "<EMAIL>", + "position": 0 + }, + { + "token": "example.com", + "start_offset": 0, + "end_offset": 20, + "type": "<EMAIL>", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/pattern-replace.md b/i18n/zh/analyzers/token-filters/pattern-replace.md new file mode 100644 index 00000000..243d7992 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/pattern-replace.md @@ -0,0 +1,110 @@ +--- +title: 模式替换 +--- + +# Pattern replace token filter + +The `pattern_replace` token filter allows you to modify tokens using regular expressions. This filter replaces patterns in tokens with the specified values, giving you flexibility in transforming or normalizing tokens before indexing them. It's particularly useful when you need to clean or standardize text during analysis. + +## 参数 + +The `pattern_replace` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`pattern` | 必需 | String | A regular expression pattern that matches the text that needs to be replaced. +`all` | 可选 | Boolean | Whether to replace all pattern matches. If `false`, only the first match is replaced. Default is `true`. +`replacement` | 可选 | String | A string with which to replace the matched pattern. Default is an empty string. + +## 示例 + +The following example request creates a new index named `text_index` and configures an analyzer with a `pattern_replace` filter to replace tokens containing digits with the string `[NUM]`: + +```json +PUT /text_index +{ + "settings": { + "analysis": { + "filter": { + "number_replace_filter": { + "type": "pattern_replace", + "pattern": "\\d+", + "replacement": "[NUM]" + } + }, + "analyzer": { + "number_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "number_replace_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /text_index/_analyze +{ + "text": "Visit us at 98765 Example St.", + "analyzer": "number_analyzer" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "visit", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "us", + "start_offset": 6, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "at", + "start_offset": 9, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "[NUM]", + "start_offset": 12, + "end_offset": 17, + "type": "<NUM>", + "position": 3 + }, + { + "token": "example", + "start_offset": 18, + "end_offset": 25, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "st", + "start_offset": 26, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 5 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/phonetic.md b/i18n/zh/analyzers/token-filters/phonetic.md new file mode 100644 index 00000000..6ff1f66b --- /dev/null +++ b/i18n/zh/analyzers/token-filters/phonetic.md @@ -0,0 +1,91 @@ +--- +title: 语音 +--- + +# Phonetic token filter + +The `phonetic` token filter transforms tokens into their phonetic representations, enabling more flexible matching of words that sound similar but are spelled differently. This is particularly useful for searching names, brands, or other entities that users might spell differently but pronounce similarly. + +The `phonetic` token filter is not included in OpenSearch distributions by default. To use this token filter, you must first install the `analysis-phonetic` plugin as follows and then restart OpenSearch: + +```bash +./bin/opensearch-plugin install analysis-phonetic +``` + +::: info NOTE +For more information about installing plugins, see [Managing OpenSearch plugins](/install-and-configure/plugins). +::: + +## 参数 + +The `phonetic` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`encoder` | 可选 | String | Specifies the phonetic algorithm to use.<br><br>Valid values are:<br>- `metaphone` (default)<br>- `double_metaphone`<br>- `soundex`<br>- `refined_soundex`<br>- `caverphone1`<br>- `caverphone2`<br>- `cologne`<br>- `nysiis`<br>- `koelnerphonetik`<br>- `haasephonetik`<br>- `beider_morse`<br>- `daitch_mokotoff ` +`replace` | 可选 | Boolean | Whether to replace the original token. If `false`, the original token is included in the output along with the phonetic encoding. Default is `true`. + +## 示例 + +The following example request creates a new index named `names_index` and configures an analyzer with a `phonetic` filter: + +```json +PUT /names_index +{ + "settings": { + "analysis": { + "filter": { + "my_phonetic_filter": { + "type": "phonetic", + "encoder": "double_metaphone", + "replace": true + } + }, + "analyzer": { + "phonetic_analyzer": { + "tokenizer": "standard", + "filter": [ + "my_phonetic_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +Use the following request to examine the tokens generated for the names `Stephen` and `Steven` using the analyzer: + +```json +POST /names_index/_analyze +{ + "text": "Stephen", + "analyzer": "phonetic_analyzer" +} +``` + +```json +POST /names_index/_analyze +{ + "text": "Steven", + "analyzer": "phonetic_analyzer" +} +``` + +In both cases, the response contains the same generated token: + +```json +{ + "tokens": [ + { + "token": "STFN", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/porter-stem.md b/i18n/zh/analyzers/token-filters/porter-stem.md new file mode 100644 index 00000000..5c4dd72a --- /dev/null +++ b/i18n/zh/analyzers/token-filters/porter-stem.md @@ -0,0 +1,77 @@ +--- +title: Porter 词干 +--- + +# Porter stem token filter + +The `porter_stem` token filter reduces words to their base (or _stem_) form and removes common suffixes from words, which helps in matching similar words by their root. For example, the word `running` is stemmed to `run`. This token filter is primarily used for the English language and provides stemming based on the [Porter stemming algorithm](https://snowballstem.org/algorithms/porter/stemmer.html). + +## 示例 + +The following example request creates a new index named `my_stem_index` and configures an analyzer with a `porter_stem` filter: + +```json +PUT /my_stem_index +{ + "settings": { + "analysis": { + "filter": { + "my_porter_stem": { + "type": "porter_stem" + } + }, + "analyzer": { + "porter_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_porter_stem" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_stem_index/_analyze +{ + "text": "running runners ran", + "analyzer": "porter_analyzer" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "run", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "runner", + "start_offset": 8, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "ran", + "start_offset": 16, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/predicate-token-filter.md b/i18n/zh/analyzers/token-filters/predicate-token-filter.md new file mode 100644 index 00000000..0b313799 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/predicate-token-filter.md @@ -0,0 +1,77 @@ +--- +title: 谓词词元过滤器 +--- + +# Predicate token filter + +The `predicate_token_filter` evaluates whether tokens should be kept or discarded, depending on the conditions defined in a custom script. The tokens are evaluated in the analysis predicate context. This filter supports only inline Painless scripts. For more information, see [Painless scripting language](/scripting/painless/). + +## 参数 + +The `predicate_token_filter` has one required parameter: `script`. This parameter provides a condition that is used to evaluate whether the token should be kept. + +## 示例 + +The following example request creates a new index named `predicate_index` and configures an analyzer with a `predicate_token_filter`. The filter specifies to only output tokens if they are longer than 7 characters: + +```json +PUT /predicate_index +{ + "settings": { + "analysis": { + "filter": { + "my_predicate_filter": { + "type": "predicate_token_filter", + "script": { + "source": "token.term.length() > 7" + } + } + }, + "analyzer": { + "predicate_analyzer": { + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_predicate_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /predicate_index/_analyze +{ + "text": "The OpenSearch community is growing rapidly", + "analyzer": "predicate_analyzer" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 4, + "end_offset": 14, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "community", + "start_offset": 15, + "end_offset": 24, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/remove-duplicates.md b/i18n/zh/analyzers/token-filters/remove-duplicates.md new file mode 100644 index 00000000..70f4aa6e --- /dev/null +++ b/i18n/zh/analyzers/token-filters/remove-duplicates.md @@ -0,0 +1,145 @@ +--- +title: 删除重复项 +--- + +# Remove duplicates token filter + +The `remove_duplicates` token filter is used to remove duplicate tokens that are generated in the same position during analysis. + +## 示例 + +The following example request creates an index with a `keyword_repeat` token filter. The filter adds a `keyword` version of each token in the same position as the token itself and then uses a `kstem` to create a stemmed version of the token: + +```json +PUT /example-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "keyword_repeat", + "kstem" + ] + } + } + } + } +} +``` + +Use the following request to analyze the string `Slower turtle`: + +```json +GET /example-index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Slower turtle" +} +``` + +响应包含 the token `turtle` twice in the same position: + +```json +{ + "tokens": [ + { + "token": "slower", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 7, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "turtle", + "start_offset": 7, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` + +The duplicate token can be removed by adding a `remove_duplicates` token filter to the index settings: + +```json +PUT /index-remove-duplicate +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "keyword_repeat", + "kstem", + "remove_duplicates" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /index-remove-duplicate/_analyze +{ + "analyzer": "custom_analyzer", + "text": "Slower turtle" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slower", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "slow", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "turtle", + "start_offset": 7, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/reverse.md b/i18n/zh/analyzers/token-filters/reverse.md new file mode 100644 index 00000000..a71888c6 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/reverse.md @@ -0,0 +1,80 @@ +--- +title: 反转 +--- + +# Reverse token filter + +The `reverse` token filter reverses the order of the characters in each token, making suffix information accessible at the beginning of the reversed tokens during analysis. + +This is useful for suffix-based searches: + +The `reverse` token filter is useful when you need to perform suffix-based searches, such as in the following scenarios: + +- **Suffix matching**: Searching for words based on their suffixes, such as identifying words with a specific ending (for example, `-tion` or `-ing`). +- **File extension searches**: Searching for files by their extensions, such as `.txt` or `.jpg`. +- **Custom sorting or ranking**: By reversing tokens, you can implement unique sorting or ranking logic based on suffixes. +- **Autocomplete for suffixes**: Implementing autocomplete suggestions that use suffixes rather than prefixes. + +## 示例 + +The following example request creates a new index named `my-reverse-index` and configures an analyzer with a `reverse` filter: + +```json +PUT /my-reverse-index +{ + "settings": { + "analysis": { + "filter": { + "reverse_filter": { + "type": "reverse" + } + }, + "analyzer": { + "my_reverse_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "reverse_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-reverse-index/_analyze +{ + "analyzer": "my_reverse_analyzer", + "text": "hello world" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "olleh", + "start_offset": 0, + "end_offset": 5, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "dlrow", + "start_offset": 6, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/shingle.md b/i18n/zh/analyzers/token-filters/shingle.md new file mode 100644 index 00000000..617920fb --- /dev/null +++ b/i18n/zh/analyzers/token-filters/shingle.md @@ -0,0 +1,120 @@ +--- +title: 瓦片 +--- + +# Shingle token filter + +The `shingle` token filter is used to generate word n-grams, or _shingles_, from input text. For example, for the string `slow green turtle`, the `shingle` filter creates the following one- and two-word shingles: `slow`, `slow green`, `green`, `green turtle`, and `turtle`. + +This token filter is often used in conjunction with other filters to enhance search accuracy by indexing phrases rather than individual tokens. For more information, see [Phrase suggester](/search-plugins/searching-data/did-you-mean#phrase-suggester). + +::: tip TIP +To accelerate phrase queries such as [`match_phrase`](/query-dsl/full-text/match-phrase), set the [`index_phrases`](/mappings/mapping-parameters/index-phrases/) mapping parameter on the `text` field. OpenSearch then indexes two-word shingles in a separate subfield and uses them to run phrase queries, so you don't need a custom analyzer containing a `shingle` filter. +::: + +## 参数 + +The `shingle` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`min_shingle_size` | 可选 | Integer | The minimum number of tokens to concatenate. Default is `2`. +`max_shingle_size` | 可选 | Integer | The maximum number of tokens to concatenate. The difference between `max_shingle_size` and `min_shingle_size`, plus 1 if `output_unigrams` is `true`, cannot exceed the [`index.max_shingle_diff`](/install-and-configure/configuring-opensearch/index-settings#dynamic-index-settings) index setting (default `3`). With the default settings, `max_shingle_size` can therefore exceed `min_shingle_size` by at most 2. Default is `2`. +`output_unigrams` | 可选 | Boolean | Whether to include unigrams (individual tokens) as output. Default is `true`. +`output_unigrams_if_no_shingles` | 可选 | Boolean | Whether to output unigrams if no shingles are generated. Default is `false`. +`token_separator` | 可选 | String | A separator used to concatenate tokens into a shingle. Default is a space (`" "`). +`filler_token` | 可选 | String | A token inserted into empty positions or gaps between tokens. Gaps occur when a preceding filter, such as [`stop`](/analyzers/token-filters/stop), removes a token. The filler token appears only within shingles and is never emitted as a separate token. For example, if `on` is a stopword and `filler_token` is `+`, the text `tent on sale` produces the tokens `tent`, `tent +`, `+ sale`, and `sale`. Default is an underscore (`_`). + +::: info NOTE +If `output_unigrams` and `output_unigrams_if_no_shingles` are both set to `true`, `output_unigrams_if_no_shingles` is ignored. +::: + +## 示例 + +The following example request creates a new index named `my-shingle-index` and configures an analyzer with a `shingle` filter: + +```json +PUT /my-shingle-index +{ + "settings": { + "analysis": { + "filter": { + "my_shingle_filter": { + "type": "shingle", + "min_shingle_size": 2, + "max_shingle_size": 2, + "output_unigrams": true + } + }, + "analyzer": { + "my_shingle_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_shingle_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-shingle-index/_analyze +{ + "analyzer": "my_shingle_analyzer", + "text": "slow green turtle" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "slow", + "start_offset": 0, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "slow green", + "start_offset": 0, + "end_offset": 10, + "type": "shingle", + "position": 0, + "positionLength": 2 + }, + { + "token": "green", + "start_offset": 5, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "green turtle", + "start_offset": 5, + "end_offset": 17, + "type": "shingle", + "position": 1, + "positionLength": 2 + }, + { + "token": "turtle", + "start_offset": 11, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/snowball.md b/i18n/zh/analyzers/token-filters/snowball.md new file mode 100644 index 00000000..010da9ef --- /dev/null +++ b/i18n/zh/analyzers/token-filters/snowball.md @@ -0,0 +1,103 @@ +--- +title: Snowball +--- + +# Snowball token filter + +The `snowball` token filter is a stemming filter based on the [Snowball](https://snowballstem.org/) algorithm. It supports many languages and is more efficient and accurate than the Porter stemming algorithm. + +## 参数 + +The `snowball` token filter can be configured with a `language` parameter that accepts the following values: + +- `Arabic` +- `Armenian` +- `Basque` +- `Catalan` +- `Danish` +- `Dutch` +- `English` (default) +- `Estonian` +- `Finnish` +- `French` +- `German` +- `German2` +- `Hungarian` +- `Italian` +- `Irish` +- `Kp` +- `Lithuanian` +- `Lovins` +- `Norwegian` +- `Porter` +- `Portuguese` +- `Romanian` +- `Russian` +- `Spanish` +- `Swedish` +- `Turkish` + +## 示例 + +The following example request creates a new index named `my-snowball-index` and configures an analyzer with a `snowball` filter: + +```json +PUT /my-snowball-index +{ + "settings": { + "analysis": { + "filter": { + "my_snowball_filter": { + "type": "snowball", + "language": "English" + } + }, + "analyzer": { + "my_snowball_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_snowball_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-snowball-index/_analyze +{ + "analyzer": "my_snowball_analyzer", + "text": "running runners" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "run", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "runner", + "start_offset": 8, + "end_offset": 15, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/stemmer-override.md b/i18n/zh/analyzers/token-filters/stemmer-override.md new file mode 100644 index 00000000..089f02c4 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/stemmer-override.md @@ -0,0 +1,134 @@ +--- +title: 词干提取器覆盖 +--- + +# Stemmer override token filter + +The `stemmer_override` token filter allows you to define custom stemming rules that override the behavior of default stemmers like Porter or Snowball. This can be useful when you want to apply specific stemming behavior to certain words that might not be modified correctly by the standard stemming algorithms. + +## 参数 + +The `stemmer_override` token filter must be configured with exactly one of the following parameters. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`rules` | String | Defines the override rules directly in the settings. +`rules_path` | String | Specifies the path to the file containing custom rules (mappings). The path can be either an absolute path or a path relative to the config directory. + +## 示例 + +The following example request creates a new index named `my-index` and configures an analyzer with a `stemmer_override` filter: + +```json +PUT /my-index +{ + "settings": { + "analysis": { + "filter": { + "my_stemmer_override_filter": { + "type": "stemmer_override", + "rules": [ + "running, runner => run", + "bought => buy", + "best => good" + ] + } + }, + "analyzer": { + "my_custom_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stemmer_override_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "I am a runner and bought the best shoes" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "i", + "start_offset": 0, + "end_offset": 1, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "am", + "start_offset": 2, + "end_offset": 4, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "a", + "start_offset": 5, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "run", + "start_offset": 7, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "and", + "start_offset": 14, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "buy", + "start_offset": 18, + "end_offset": 24, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "the", + "start_offset": 25, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "good", + "start_offset": 29, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "shoes", + "start_offset": 34, + "end_offset": 39, + "type": "<ALPHANUM>", + "position": 8 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/stemmer.md b/i18n/zh/analyzers/token-filters/stemmer.md new file mode 100644 index 00000000..f0f1871b --- /dev/null +++ b/i18n/zh/analyzers/token-filters/stemmer.md @@ -0,0 +1,114 @@ +--- +title: 词干提取器 +--- + +# Stemmer token filter + +The `stemmer` token filter reduces words to their root or base form (also known as their _stem_). + +## 参数 + +The `stemmer` token filter can be configured with a `language` parameter that accepts the following values: + +- Arabic: `arabic` +- Armenian: `armenian` +- Basque: `basque` +- Bengali: `bengali` +- Brazilian Portuguese: `brazilian` +- Bulgarian: `bulgarian` +- Catalan: `catalan` +- Czech: `czech` +- Danish: `danish` +- Dutch: `dutch, dutch_kp` +- English: `english` (default), `light_english`, `lovins`, `minimal_english`, `porter2`, `possessive_english` +- Estonian: `estonian` +- Finnish: `finnish`, `light_finnish` +- French: `light_french`, `french`, `minimal_french` +- Galician: `galician`, `minimal_galician` (plural step only) +- German: `light_german`, `german`, `german2`, `minimal_german` +- Greek: `greek` +- Hindi: `hindi` +- Hungarian: `hungarian, light_hungarian` +- Indonesian: `indonesian` +- Irish: `irish` +- Italian: `light_italian, italian` +- Kurdish (Sorani): `sorani` +- Latvian: `latvian` +- Lithuanian: `lithuanian` +- Norwegian (Bokmål): `norwegian`, `light_norwegian`, `minimal_norwegian` +- Norwegian (Nynorsk): `light_nynorsk`, `minimal_nynorsk` +- Portuguese: `light_portuguese`, `minimal_portuguese`, `portuguese`, `portuguese_rslp` +- Romanian: `romanian` +- Russian: `russian`, `light_russian` +- Spanish: `light_spanish`, `spanish` +- Swedish: `swedish`, `light_swedish` +- Turkish: `turkish` + +::: info NOTE +You can also use the `name` parameter as an alias for the `language` parameter. If both are set, the `name` parameter is ignored. +::: + +## 示例 + +The following example request creates a new index named `my-stemmer-index` and configures an analyzer with a `stemmer` filter: + +```json +PUT /my-stemmer-index +{ + "settings": { + "analysis": { + "filter": { + "my_english_stemmer": { + "type": "stemmer", + "language": "english" + } + }, + "analyzer": { + "my_stemmer_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_english_stemmer" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-stemmer-index/_analyze +{ + "analyzer": "my_stemmer_analyzer", + "text": "running runs" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "run", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "run", + "start_offset": 8, + "end_offset": 12, + "type": "<ALPHANUM>", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/stop.md b/i18n/zh/analyzers/token-filters/stop.md new file mode 100644 index 00000000..d1c1ac2a --- /dev/null +++ b/i18n/zh/analyzers/token-filters/stop.md @@ -0,0 +1,150 @@ +--- +title: 停用词 +--- + +# Stop token filter + +The `stop` token filter is used to remove common words (also known as _stopwords_) from a token stream during analysis. Stopwords are typically articles and prepositions, such as `a` or `for`. These words are not significantly meaningful in search queries and are often excluded to improve search efficiency and relevance. + +The default list of English stopwords includes the following words: `a`, `an`, `and`, `are`, `as`, `at`, `be`, `but`, `by`, `for`, `if`, `in`, `into`, `is`, `it`, `no`, `not`, `of`, `on`, `or`, `such`, `that`, `the`, `their`, `then`, `there`, `these`, `they`, `this`, `to`, `was`, `will`, and `with`. + +## 参数 + +The `stop` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`stopwords` | 可选 | String | Specifies either a custom array of stopwords or a [predefined stopword set for a language](#predefined-stopword-sets-by-language). Default is `_english_`. +`stopwords_path` | 可选 | String | Specifies the file path (absolute or relative to the config directory) of the file containing custom stopwords. +`ignore_case` | 可选 | Boolean | If `true`, stopwords will be matched regardless of their case. Default is `false`. +`remove_trailing` | 可选 | Boolean | If `true`, a stopword at the end of the input is removed like any other stopword. If `false`, the last token is kept if it is a stopword that is not followed by a space or other separator, while all other stopwords are removed. Set to `false` when using the filter in a [completion suggester](/search-plugins/searching-data/autocomplete#completion-suggester) analyzer. For more information, see [Using the stop filter with completion suggesters](#using-the-stop-filter-with-completion-suggesters). Default is `true`. + +## 示例 + +The following example request creates a new index named `my-stopword-index` and configures an analyzer with a `stop` filter that uses the predefined stopword list for the English language: + +```json +PUT /my-stopword-index +{ + "settings": { + "analysis": { + "filter": { + "my_stop_filter": { + "type": "stop", + "stopwords": "_english_" + } + }, + "analyzer": { + "my_stop_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stop_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-stopword-index/_analyze +{ + "analyzer": "my_stop_analyzer", + "text": "A quick dog jumps over the turtle" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "quick", + "start_offset": 2, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "dog", + "start_offset": 8, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "jumps", + "start_offset": 12, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "over", + "start_offset": 18, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "turtle", + "start_offset": 27, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 6 + } + ] +} +``` + +## Using the stop filter with completion suggesters + +When a user types a search query, the last word is often incomplete and can match a stopword. For example, when a user types `red on`, the `on` might be the beginning of `onion`. If the analyzer for a `completion` field removes `on`, OpenSearch searches for the prefix `red` and suggests `red cabbage`, `red onion`, and `red pepper`. If you set `remove_trailing` to `false`, the `stop` filter keeps the final `on`, so the same prefix suggests only `red onion`. After the user types a space following `on`, the filter treats `on` as a complete word and removes it. + +## Predefined stopword sets by language + +The following is a list of all available predefined stopword sets by language: + +- [`_arabic_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ar/stopwords.txt) +- [`_armenian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/hy/stopwords.txt) +- [`_basque_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/eu/stopwords.txt) +- [`_bengali_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/bn/stopwords.txt) +- [`_brazilian_` (Brazilian Portuguese)](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/br/stopwords.txt) +- [`_bulgarian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/bg/stopwords.txt) +- [`_catalan_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ca/stopwords.txt) +- [`_cjk_` (Chinese, Japanese, and Korean)](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/cjk/stopwords.txt) +- [`_czech_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/cz/stopwords.txt) +- [`_danish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/danish_stop.txt) +- [`_dutch_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/dutch_stop.txt) +- [`_english_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/java/org/apache/lucene/analysis/en/EnglishAnalyzer.java#L48) +- [`_estonian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/et/stopwords.txt) +- [`_finnish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/finnish_stop.txt) +- [`_french_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/french_stop.txt) +- [`_galician_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/gl/stopwords.txt) +- [`_german_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/german_stop.txt) +- [`_greek_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/el/stopwords.txt) +- [`_hindi_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/hi/stopwords.txt) +- [`_hungarian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/hungarian_stop.txt) +- [`_indonesian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/id/stopwords.txt) +- [`_irish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/irish_stop.txt) +- [`_italian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/italian_stop.txt) +- [`_latvian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/lv/stopwords.txt) +- [`_lithuanian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/lt/stopwords.txt) +- [`_norwegian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/norwegian_stop.txt) +- [`_persian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/fa/stopwords.txt) +- [`_portuguese_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/portuguese_stop.txt) +- [`_romanian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ro/stopwords.txt) +- [`_russian_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/russian_stop.txt) +- [`_sorani_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/ckb/stopwords.txt) +- [`_spanish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/spanish_stop.txt) +- [`_swedish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/snowball/swedish_stop.txt) +- [`_thai_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/th/stopwords.txt) +- [`_turkish_`](https://github.com/apache/lucene/blob/main/lucene/analysis/common/src/resources/org/apache/lucene/analysis/tr/stopwords.txt) diff --git a/i18n/zh/analyzers/token-filters/synonym-graph.md b/i18n/zh/analyzers/token-filters/synonym-graph.md new file mode 100644 index 00000000..9f53b242 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/synonym-graph.md @@ -0,0 +1,272 @@ +--- +title: 同义词图 +--- + +# Synonym graph token filter + +The `synonym_graph` token filter is a more advanced version of the `synonym` token filter. It supports multiword synonyms and processes synonyms across multiple tokens, making it ideal for phrases or scenarios in which relationships between tokens are important. + +::: info NOTE +Use the `synonym_graph` filter only in a [search analyzer](/analyzers/search-analyzers#specifying-a-search-analyzer-in-the-mappings). At index time, OpenSearch ignores the `positionLength` of each token, so a multiword synonym shifts the positions of the tokens that follow it. For example, if an index analyzer maps `ev` to `electric car`, then `charger` in the text `ev charger` is indexed at position 2, and a `match_phrase` query for `ev charger` no longer matches the document. To apply synonyms at index time, use the [`synonym`](/analyzers/token-filters/synonym) token filter. +::: + +## 参数 + +The `synonym_graph` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`synonyms` | Either `synonyms` or `synonyms_path` must be specified | String | A list of synonym rules defined directly in the configuration. +`synonyms_path` | Either `synonyms` or `synonyms_path` must be specified | String | The file path to a file containing synonym rules (either an absolute path or a path relative to the config directory). +`lenient` | 可选 | Boolean | Whether to ignore exceptions when loading the rule configurations. If `true`, OpenSearch skips the synonym terms that cannot be parsed and keeps the rest of the rule. For more information, see [Synonym rules containing stop words](#synonym-rules-containing-stop-words). Default is `false`. +`format` | 可选 | String | Specifies the format used to determine how OpenSearch defines and interprets synonyms. Valid values are:<br>- `solr` <br>- [`wordnet`](https://wordnet.princeton.edu/). <br> Default is `solr`. +`expand` | 可选 | Boolean | Whether to expand equivalent synonym rules. Default is `true`.<br><br>For example: <br>If `synonyms` are defined as `"quick, fast"` and `expand` is set to `true`, then the synonym rules are configured as follows:<br>- `quick => quick`<br>- `quick => fast`<br>- `fast => quick`<br>- `fast => fast`<br><br>If `expand` is set to `false`, the synonym rules are configured as follows:<br>- `quick => quick`<br>- `fast => quick` +`synonym_analyzer` | 可选 | String | The name of the analyzer that parses the synonym rules. Specify any analyzer available to the index: a built-in analyzer (such as `standard`, `simple`, `stop`, `whitespace`, or `keyword`), a language analyzer, an analyzer registered by a plugin, or a custom analyzer defined in the same index. If the named analyzer cannot be resolved, OpenSearch parses the rules using the analysis chain in which this filter is defined and returns no error. By default, the analysis chain is used. For more information, see [Parsing synonym rules](#parsing-synonym-rules). + +## 示例: Solr format + +The following example request creates a new index named `my-index` and configures an analyzer with a `synonym_graph` filter. The filter is configured with the default `solr` rule format: + +```json +PUT /my-index +{ + "settings": { + "analysis": { + "filter": { + "my_synonym_graph_filter": { + "type": "synonym_graph", + "synonyms": [ + "sports car, race car", + "fast car, speedy vehicle", + "luxury car, premium vehicle", + "electric car, EV" + ] + } + }, + "analyzer": { + "my_synonym_graph_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_synonym_graph_filter" + ] + } + } + } + } +} + +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-index/_analyze +{ + "analyzer": "my_synonym_graph_analyzer", + "text": "I just bought a sports car and it is a fast car." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "i","start_offset": 0,"end_offset": 1,"type": "<ALPHANUM>","position": 0}, + {"token": "just","start_offset": 2,"end_offset": 6,"type": "<ALPHANUM>","position": 1}, + {"token": "bought","start_offset": 7,"end_offset": 13,"type": "<ALPHANUM>","position": 2}, + {"token": "a","start_offset": 14,"end_offset": 15,"type": "<ALPHANUM>","position": 3}, + {"token": "race","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4}, + {"token": "sports","start_offset": 16,"end_offset": 22,"type": "<ALPHANUM>","position": 4,"positionLength": 2}, + {"token": "car","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 5,"positionLength": 2}, + {"token": "car","start_offset": 23,"end_offset": 26,"type": "<ALPHANUM>","position": 6}, + {"token": "and","start_offset": 27,"end_offset": 30,"type": "<ALPHANUM>","position": 7}, + {"token": "it","start_offset": 31,"end_offset": 33,"type": "<ALPHANUM>","position": 8}, + {"token": "is","start_offset": 34,"end_offset": 36,"type": "<ALPHANUM>","position": 9}, + {"token": "a","start_offset": 37,"end_offset": 38,"type": "<ALPHANUM>","position": 10}, + {"token": "speedy","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 11}, + {"token": "fast","start_offset": 39,"end_offset": 43,"type": "<ALPHANUM>","position": 11,"positionLength": 2}, + {"token": "vehicle","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 12,"positionLength": 2}, + {"token": "car","start_offset": 44,"end_offset": 47,"type": "<ALPHANUM>","position": 13} + ] +} +``` + +## 示例: WordNet format + +The following example request creates a new index named `my-wordnet-index` and configures an analyzer with a `synonym_graph` filter. The filter is configured with the [`wordnet`](https://wordnet.princeton.edu/) rule format: + +```json +PUT /my-wordnet-index +{ + "settings": { + "analysis": { + "filter": { + "my_synonym_graph_filter": { + "type": "synonym_graph", + "format": "wordnet", + "synonyms": [ + "s(100000001, 1, 'sports car', n, 1, 0).", + "s(100000001, 2, 'race car', n, 1, 0).", + "s(100000001, 3, 'fast car', n, 1, 0).", + "s(100000001, 4, 'speedy vehicle', n, 1, 0)." + ] + } + }, + "analyzer": { + "my_synonym_graph_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_synonym_graph_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-wordnet-index/_analyze +{ + "analyzer": "my_synonym_graph_analyzer", + "text": "I just bought a sports car and it is a fast car." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "i","start_offset": 0,"end_offset": 1,"type": "<ALPHANUM>","position": 0}, + {"token": "just","start_offset": 2,"end_offset": 6,"type": "<ALPHANUM>","position": 1}, + {"token": "bought","start_offset": 7,"end_offset": 13,"type": "<ALPHANUM>","position": 2}, + {"token": "a","start_offset": 14,"end_offset": 15,"type": "<ALPHANUM>","position": 3}, + {"token": "race","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4}, + {"token": "fast","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4,"positionLength": 2}, + {"token": "speedy","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 4,"positionLength": 3}, + {"token": "sports","start_offset": 16,"end_offset": 22,"type": "<ALPHANUM>","position": 4,"positionLength": 4}, + {"token": "car","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 5,"positionLength": 4}, + {"token": "car","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 6,"positionLength": 3}, + {"token": "vehicle","start_offset": 16,"end_offset": 26,"type": "SYNONYM","position": 7,"positionLength": 2}, + {"token": "car","start_offset": 23,"end_offset": 26,"type": "<ALPHANUM>","position": 8}, + {"token": "and","start_offset": 27,"end_offset": 30,"type": "<ALPHANUM>","position": 9}, + {"token": "it","start_offset": 31,"end_offset": 33,"type": "<ALPHANUM>","position": 10}, + {"token": "is","start_offset": 34,"end_offset": 36,"type": "<ALPHANUM>","position": 11}, + {"token": "a","start_offset": 37,"end_offset": 38,"type": "<ALPHANUM>","position": 12}, + {"token": "sports","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 13}, + {"token": "race","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 13,"positionLength": 2}, + {"token": "speedy","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 13,"positionLength": 3}, + {"token": "fast","start_offset": 39,"end_offset": 43,"type": "<ALPHANUM>","position": 13,"positionLength": 4}, + {"token": "car","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 14,"positionLength": 4}, + {"token": "car","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 15,"positionLength": 3}, + {"token": "vehicle","start_offset": 39,"end_offset": 47,"type": "SYNONYM","position": 16,"positionLength": 2}, + {"token": "car","start_offset": 44,"end_offset": 47,"type": "<ALPHANUM>","position": 17} + ] +} +``` + +## Parsing synonym rules + +Unless you specify a `synonym_analyzer`, OpenSearch parses synonym rules using the tokenizer and the token filters that precede `synonym_graph` in the analyzer. This applies the same processing to the rules as to the text. For example, if the `porter_stem` filter precedes `synonym_graph`, the rule `running shoes, trainers` is stored as `run shoe, trainer`. The rule then matches both `running shoes` and `run shoe`. + +A synonym rule can contain only one token at each position, so token filters that produce several tokens at the same position are handled as follows when they precede `synonym_graph`: + +- Some filters produce only one version of each token when parsing rules. For example, the [`asciifolding`](/analyzers/token-filters/asciifolding) filter with `preserve_original` set to `true` produces only the folded token. Given the rule `café, coffee shop`, the text `coffee shop` produces the synonym `cafe`, not `café`. +- The [`word_delimiter_graph`](/analyzers/token-filters/word-delimiter-graph), [`ngram`](/analyzers/token-filters/ngram), [`edge_ngram`](/analyzers/token-filters/edge-ngram), [`shingle`](/analyzers/token-filters/shingle), and [`multiplexer`](/analyzers/token-filters/multiplexer) filters cannot parse synonym rules. If one of them precedes `synonym_graph`, OpenSearch rejects the request to create the index. + +To use one of these filters in the same analyzer as `synonym_graph`, set `synonym_analyzer` to an analyzer that does not contain the filter. OpenSearch then parses the rules using that analyzer and applies the filter only to the text. + +## Synonym rules containing stop words + +If a [`stop`](/analyzers/token-filters/stop) filter precedes `synonym_graph`, it also removes stop words from the synonym rules. By default, OpenSearch rejects the request to create the index if a term in a rule contains a stop word. If you set `lenient` to `true`, OpenSearch skips each term that contains a stop word and keeps the rest of the rule. + +The following example request creates an index containing a `stop` filter that removes `the` and a `synonym_graph` filter whose rule contains the term `the flask`: + +```json +PUT /drinkware +{ + "settings": { + "analysis": { + "filter": { + "my_stop_filter": { + "type": "stop", + "stopwords": ["the"] + }, + "my_synonym_graph_filter": { + "type": "synonym_graph", + "lenient": true, + "synonyms": ["flask, the flask, thermos"] + } + }, + "analyzer": { + "my_synonym_graph_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stop_filter", + "my_synonym_graph_filter" + ] + } + } + } + } +} +``` + +OpenSearch skips `the flask` and keeps `flask` and `thermos` as synonyms. Use the following request to analyze the text `thermos`: + +```json +GET /drinkware/_analyze +{ + "analyzer": "my_synonym_graph_analyzer", + "text": "thermos" +} +``` + +响应包含 the synonym `flask`: + +```json +{ + "tokens": [ + { + "token": "flask", + "start_offset": 0, + "end_offset": 7, + "type": "SYNONYM", + "position": 0 + }, + { + "token": "thermos", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + } + ] +} +``` + +If the skipped term is the one that other terms map to, the rule adds no synonyms. The following table shows how OpenSearch handles other rules when `lenient` is `true` and `the` is a stop word. + +Rule | `expand` | Result +:--- | :--- | :--- +`flask, thermos => the flask` | `true` | No synonyms are added because the replacement term contains a stop word. +`the flask, flask, thermos` | `false` | No synonyms are added because, when `expand` is `false`, all terms map to the first term, which contains a stop word. +`flask, the flask, thermos` | `false` | `thermos` maps to `flask`. + +::: danger WARNING +If a `stop` filter follows `synonym_graph`, the stop words are removed from the synonym graph after synonym matching, which breaks the graph. For example, given the rule `thermos, the flask` and a `stop` filter that follows `synonym_graph`, a `match` query for `the flask` searches only for `thermos` and does not match documents containing `flask`. Remove such words from the synonym rules, or place the `stop` filter before `synonym_graph`. +::: diff --git a/i18n/zh/analyzers/token-filters/synonym.md b/i18n/zh/analyzers/token-filters/synonym.md new file mode 100644 index 00000000..a63e94c1 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/synonym.md @@ -0,0 +1,361 @@ +--- +title: 同义词 +--- + +# Synonym token filter + +The `synonym` token filter allows you to map multiple terms to a single term or create equivalence groups between words, improving search flexibility. + +## 参数 + +The `synonym` token filter can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`synonyms` | Either `synonyms` or `synonyms_path` must be specified | String | A list of synonym rules defined directly in the configuration. +`synonyms_path` | Either `synonyms` or `synonyms_path` must be specified | String | The file path to a file containing synonym rules (either an absolute path or a path relative to the config directory). +`lenient` | 可选 | Boolean | Whether to ignore exceptions when loading the rule configurations. If `true`, OpenSearch skips the synonym terms that cannot be parsed and keeps the rest of the rule. For more information, see [Synonym rules containing stop words](#synonym-rules-containing-stop-words). Default is `false`. +`format` | 可选 | String | Specifies the format used to determine how OpenSearch defines and interprets synonyms. Valid values are:<br>- `solr` <br>- [`wordnet`](https://wordnet.princeton.edu/). <br> Default is `solr`. +`expand` | 可选 | Boolean | Whether to expand equivalent synonym rules. Default is `true`.<br><br>For example: <br>If `synonyms` are defined as `"quick, fast"` and `expand` is set to `true`, then the synonym rules are configured as follows:<br>- `quick => quick`<br>- `quick => fast`<br>- `fast => quick`<br>- `fast => fast`<br><br>If `expand` is set to `false`, the synonym rules are configured as follows:<br>- `quick => quick`<br>- `fast => quick` +`synonym_analyzer` | 可选 | String | The name of the analyzer that parses the synonym rules. Specify any analyzer available to the index: a built-in analyzer (such as `standard`, `simple`, `stop`, `whitespace`, or `keyword`), a language analyzer, an analyzer registered by a plugin, or a custom analyzer defined in the same index. If the named analyzer cannot be resolved, OpenSearch parses the rules using the analysis chain in which this filter is defined and returns no error. By default, the analysis chain is used. For more information, see [Parsing synonym rules](#parsing-synonym-rules). + +## 示例: Solr format + +The following example request creates a new index named `my-synonym-index` and configures an analyzer with a `synonym` filter. The filter is configured with the default `solr` rule format: + +```json +PUT /my-synonym-index +{ + "settings": { + "analysis": { + "filter": { + "my_synonym_filter": { + "type": "synonym", + "synonyms": [ + "car, automobile", + "quick, fast, speedy", + "laptop => computer" + ] + } + }, + "analyzer": { + "my_synonym_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_synonym_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-synonym-index/_analyze +{ + "analyzer": "my_synonym_analyzer", + "text": "The quick dog jumps into the car with a laptop" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "the", + "start_offset": 0, + "end_offset": 3, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "quick", + "start_offset": 4, + "end_offset": 9, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "fast", + "start_offset": 4, + "end_offset": 9, + "type": "SYNONYM", + "position": 1 + }, + { + "token": "speedy", + "start_offset": 4, + "end_offset": 9, + "type": "SYNONYM", + "position": 1 + }, + { + "token": "dog", + "start_offset": 10, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "jumps", + "start_offset": 14, + "end_offset": 19, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "into", + "start_offset": 20, + "end_offset": 24, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "the", + "start_offset": 25, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "car", + "start_offset": 29, + "end_offset": 32, + "type": "<ALPHANUM>", + "position": 6 + }, + { + "token": "automobile", + "start_offset": 29, + "end_offset": 32, + "type": "SYNONYM", + "position": 6 + }, + { + "token": "with", + "start_offset": 33, + "end_offset": 37, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "a", + "start_offset": 38, + "end_offset": 39, + "type": "<ALPHANUM>", + "position": 8 + }, + { + "token": "computer", + "start_offset": 40, + "end_offset": 46, + "type": "SYNONYM", + "position": 9 + } + ] +} +``` + +## 示例: WordNet format + +The following example request creates a new index named `my-wordnet-index` and configures an analyzer with a `synonym` filter. The filter is configured with the [`wordnet`](https://wordnet.princeton.edu/) rule format: + +```json +PUT /my-wordnet-index +{ + "settings": { + "analysis": { + "filter": { + "my_wordnet_synonym_filter": { + "type": "synonym", + "format": "wordnet", + "synonyms": [ + "s(100000001,1,'fast',v,1,0).", + "s(100000001,2,'quick',v,1,0).", + "s(100000001,3,'swift',v,1,0)." + ] + } + }, + "analyzer": { + "my_wordnet_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_wordnet_synonym_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-wordnet-index/_analyze +{ + "analyzer": "my_wordnet_analyzer", + "text": "I have a fast car" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "i", + "start_offset": 0, + "end_offset": 1, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "have", + "start_offset": 2, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "a", + "start_offset": 7, + "end_offset": 8, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "fast", + "start_offset": 9, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "quick", + "start_offset": 9, + "end_offset": 13, + "type": "SYNONYM", + "position": 3 + }, + { + "token": "swift", + "start_offset": 9, + "end_offset": 13, + "type": "SYNONYM", + "position": 3 + }, + { + "token": "car", + "start_offset": 14, + "end_offset": 17, + "type": "<ALPHANUM>", + "position": 4 + } + ] +} +``` + +## Parsing synonym rules + +Unless you specify a `synonym_analyzer`, OpenSearch parses synonym rules using the tokenizer and the token filters that precede `synonym` in the analyzer. This applies the same processing to the rules as to the text. For example, if the `porter_stem` filter precedes `synonym`, the rule `running shoes, trainers` is stored as `run shoe, trainer`. The rule then matches both `running shoes` and `run shoe`. + +A synonym rule can contain only one token at each position, so token filters that produce several tokens at the same position are handled as follows when they precede `synonym`: + +- Some filters produce only one version of each token when parsing rules. For example, the [`asciifolding`](/analyzers/token-filters/asciifolding) filter with `preserve_original` set to `true` produces only the folded token. Given the rule `café, coffee shop`, the text `coffee shop` produces the synonym `cafe`, not `café`. +- The [`word_delimiter`](/analyzers/token-filters/word-delimiter), [`word_delimiter_graph`](/analyzers/token-filters/word-delimiter-graph), [`ngram`](/analyzers/token-filters/ngram), [`edge_ngram`](/analyzers/token-filters/edge-ngram), [`shingle`](/analyzers/token-filters/shingle), and [`multiplexer`](/analyzers/token-filters/multiplexer) filters cannot parse synonym rules. If one of them precedes `synonym`, OpenSearch rejects the request to create the index. + +To use one of these filters in the same analyzer as `synonym`, set `synonym_analyzer` to an analyzer that does not contain the filter. OpenSearch then parses the rules using that analyzer and applies the filter only to the text. + +## Synonym rules containing stop words + +If a [`stop`](/analyzers/token-filters/stop) filter precedes `synonym`, it also removes stop words from the synonym rules. By default, OpenSearch rejects the request to create the index if a term in a rule contains a stop word. If you set `lenient` to `true`, OpenSearch skips each term that contains a stop word and keeps the rest of the rule. + +The following example request creates an index containing a `stop` filter that removes `the` and a `synonym` filter whose rule contains the term `the flask`: + +```json +PUT /kitchenware +{ + "settings": { + "analysis": { + "filter": { + "my_stop_filter": { + "type": "stop", + "stopwords": ["the"] + }, + "my_synonym_filter": { + "type": "synonym", + "lenient": true, + "synonyms": ["flask, the flask, thermos"] + } + }, + "analyzer": { + "my_synonym_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "my_stop_filter", + "my_synonym_filter" + ] + } + } + } + } +} +``` + +OpenSearch skips `the flask` and keeps `flask` and `thermos` as synonyms. Use the following request to analyze the text `thermos`: + +```json +GET /kitchenware/_analyze +{ + "analyzer": "my_synonym_analyzer", + "text": "thermos" +} +``` + +响应包含 the synonym `flask`: + +```json +{ + "tokens": [ + { + "token": "thermos", + "start_offset": 0, + "end_offset": 7, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "flask", + "start_offset": 0, + "end_offset": 7, + "type": "SYNONYM", + "position": 0 + } + ] +} +``` + +If the skipped term is the one that other terms map to, the rule adds no synonyms. The following table shows how OpenSearch handles other rules when `lenient` is `true` and `the` is a stop word. + +Rule | `expand` | Result +:--- | :--- | :--- +`flask, thermos => the flask` | `true` | No synonyms are added because the replacement term contains a stop word. +`the flask, flask, thermos` | `false` | No synonyms are added because, when `expand` is `false`, all terms map to the first term, which contains a stop word. +`flask, the flask, thermos` | `false` | `thermos` maps to `flask`. diff --git a/i18n/zh/analyzers/token-filters/trim.md b/i18n/zh/analyzers/token-filters/trim.md new file mode 100644 index 00000000..9ab00afe --- /dev/null +++ b/i18n/zh/analyzers/token-filters/trim.md @@ -0,0 +1,88 @@ +--- +title: 修剪 +--- + +# Trim token filter + +The `trim` token filter removes leading and trailing white space characters from tokens. + +::: info NOTE +Many popular tokenizers, such as `standard`, `keyword`, and `whitespace` tokenizers, automatically strip leading and trailing white space characters during tokenization. When using these tokenizers, there is no need to configure an additional `trim` token filter. +::: + +## 示例 + +The following example request creates a new index named `my_pattern_trim_index` and configures an analyzer with a `trim` filter and a `pattern` tokenizer, which does not remove leading and trailing white space characters: + +```json +PUT /my_pattern_trim_index +{ + "settings": { + "analysis": { + "filter": { + "my_trim_filter": { + "type": "trim" + } + }, + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "," + } + }, + "analyzer": { + "my_pattern_trim_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer", + "filter": [ + "lowercase", + "my_trim_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my_pattern_trim_index/_analyze +{ + "analyzer": "my_pattern_trim_analyzer", + "text": " OpenSearch , is , powerful " +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 12, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 13, + "end_offset": 18, + "type": "word", + "position": 1 + }, + { + "token": "powerful", + "start_offset": 19, + "end_offset": 32, + "type": "word", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/truncate.md b/i18n/zh/analyzers/token-filters/truncate.md new file mode 100644 index 00000000..179340ab --- /dev/null +++ b/i18n/zh/analyzers/token-filters/truncate.md @@ -0,0 +1,102 @@ +--- +title: 截断 +--- + +# Truncate token filter + +The `truncate` token filter is used to shorten tokens exceeding a specified length. It trims tokens to a maximum number of characters, ensuring that tokens exceeding this limit are truncated. + +## 参数 + +The `truncate` token filter can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`length` | 可选 | Integer | Specifies the maximum length of the generated token. Default is `10`. + +## 示例 + +The following example request creates a new index named `truncate_example` and configures an analyzer with a `truncate` filter: + +```json +PUT /truncate_example +{ + "settings": { + "analysis": { + "filter": { + "truncate_filter": { + "type": "truncate", + "length": 5 + } + }, + "analyzer": { + "truncate_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "truncate_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /truncate_example/_analyze +{ + "analyzer": "truncate_analyzer", + "text": "OpenSearch is powerful and scalable" +} + +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opens", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "power", + "start_offset": 14, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "and", + "start_offset": 23, + "end_offset": 26, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "scala", + "start_offset": 27, + "end_offset": 35, + "type": "<ALPHANUM>", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/unique.md b/i18n/zh/analyzers/token-filters/unique.md new file mode 100644 index 00000000..c90c590c --- /dev/null +++ b/i18n/zh/analyzers/token-filters/unique.md @@ -0,0 +1,101 @@ +--- +title: 唯一 +--- + +# Unique token filter + +The `unique` token filter ensures that only unique tokens are kept during the analysis process, removing duplicate tokens that appear within a single field or text block. + +## 参数 + +The `unique` token filter can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`only_on_same_position` | 可选 | Boolean | If `true`, the token filter acts as a `remove_duplicates` token filter and only removes tokens that are in the same position. Default is `false`. + +## 示例 + +The following example request creates a new index named `unique_example` and configures an analyzer with a `unique` filter: + +```json +PUT /unique_example +{ + "settings": { + "analysis": { + "filter": { + "unique_filter": { + "type": "unique", + "only_on_same_position": false + } + }, + "analyzer": { + "unique_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "unique_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /unique_example/_analyze +{ + "analyzer": "unique_analyzer", + "text": "OpenSearch OpenSearch is powerful powerful and scalable" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "is", + "start_offset": 22, + "end_offset": 24, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "powerful", + "start_offset": 25, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "and", + "start_offset": 43, + "end_offset": 46, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "scalable", + "start_offset": 47, + "end_offset": 55, + "type": "<ALPHANUM>", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/uppercase.md b/i18n/zh/analyzers/token-filters/uppercase.md new file mode 100644 index 00000000..c02628ce --- /dev/null +++ b/i18n/zh/analyzers/token-filters/uppercase.md @@ -0,0 +1,78 @@ +--- +title: 大写 +--- + +# Uppercase token filter + +The `uppercase` token filter is used to convert all tokens (words) to uppercase during analysis. + +## 示例 + +The following example request creates a new index named `uppercase_example` and configures an analyzer with an `uppercase` filter: + +```json +PUT /uppercase_example +{ + "settings": { + "analysis": { + "filter": { + "uppercase_filter": { + "type": "uppercase" + } + }, + "analyzer": { + "uppercase_analyzer": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "uppercase_filter" + ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /uppercase_example/_analyze +{ + "analyzer": "uppercase_analyzer", + "text": "OpenSearch is powerful" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OPENSEARCH", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "IS", + "start_offset": 11, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "POWERFUL", + "start_offset": 14, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 2 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-filters/word-delimiter-graph.md b/i18n/zh/analyzers/token-filters/word-delimiter-graph.md new file mode 100644 index 00000000..1c32658f --- /dev/null +++ b/i18n/zh/analyzers/token-filters/word-delimiter-graph.md @@ -0,0 +1,161 @@ +--- +title: 单词分隔符图 +--- + +# Word delimiter graph token filter + +The `word_delimiter_graph` token filter is used to splits token on predefined characters and also offers optional token normalization based on customizable rules. + +::: info NOTE +The `word_delimiter_graph` filter is used to remove punctuation from complex identifiers like part numbers or product IDs. In such cases, it is best used with the `keyword` tokenizer. For hyphenated words, use the `synonym_graph` token filter instead of the `word_delimiter_graph` filter because users frequently search for these terms both with and without hyphens. +::: + +By default, the filter applies the following rules. + +| 描述 | Input | Output | +|:---|:---|:---| +| Treats non-alphanumeric characters as delimiters. | `ultra-fast` | `ultra`, `fast` | +| Removes delimiters at the beginning or end of tokens. | `Z99++'Decoder'`| `Z99`, `Decoder` | +| Splits tokens when there is a transition between uppercase and lowercase letters. | `OpenSearch` | `Open`, `Search` | +| Splits tokens when there is a transition between letters and numbers. | `T1000` | `T`, `1000` | +| Removes the possessive ('s) from the end of tokens. | `John's` | `John` | + +::: warning IMPORTANT +It's important **not** to use tokenizers that strip punctuation, like the `standard` tokenizer, with this filter. Doing so may prevent proper token splitting and interfere with options like `catenate_all` or `preserve_original`. We recommend using this filter with a `keyword` or `whitespace` tokenizer. +::: + +## 参数 + +You can configure the `word_delimiter_graph` token filter using the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`adjust_offsets` | 可选 | Boolean | Determines whether the token offsets should be recalculated for split or concatenated tokens. When `true`, the filter adjusts the token offsets to accurately represent the token's position within the token stream. This adjustment ensures that the token's location in the text aligns with its modified form after processing, which is particularly useful for applications like highlighting or phrase queries. When `false`, the offsets remain unchanged, which may result in misalignment when the processed tokens are mapped back to their positions in the original text. If your analyzer uses filters like `trim` that change the token lengths without changing their offsets, we recommend setting this parameter to `false`. Default is `true`. +`catenate_all` | 可选 | Boolean | Produces concatenated tokens from a sequence of alphanumeric parts. For example, `"quick-fast-200"` becomes `[ quickfast200, quick, fast, 200 ]`. Default is `false`. +`catenate_numbers` | 可选 | Boolean | Concatenates numerical sequences. For example, `"10-20-30"` becomes `[ 102030, 10, 20, 30 ]`. Default is `false`. +`catenate_words` | 可选 | Boolean | Concatenates alphabetic words. For example, `"high-speed-level"` becomes `[ highspeedlevel, high, speed, level ]`. Default is `false`. +`generate_number_parts` | 可选 | Boolean | If `true`, numeric tokens (tokens consisting of numbers only) are included in the output. Default is `true`. +`generate_word_parts` | 可选 | Boolean | If `true`, alphabetical tokens (tokens consisting of alphabetic characters only) are included in the output. Default is `true`. +`ignore_keywords` | 可选 | Boolean | Whether to process tokens marked as keywords. Default is `false`. +`preserve_original` | 可选 | Boolean | Keeps the original token (which may include non-alphanumeric delimiters) alongside the generated tokens in the output. For example, `"auto-drive-300"` becomes `[ auto-drive-300, auto, drive, 300 ]`. If `true`, the filter generates multi-position tokens not supported by indexing, so do not use this filter in an index analyzer or use the `flatten_graph` filter after this filter. Default is `false`. +`protected_words` | 可选 | Array of strings | Specifies tokens that should not be split. +`protected_words_path` | 可选 | String | Specifies a path (absolute or relative to the config directory) to a file containing tokens that should not be separated by new lines. +`split_on_case_change` | 可选 | Boolean | Splits tokens where consecutive letters have different cases (one is lowercase and the other is uppercase). For example, `"OpenSearch"` becomes `[ Open, Search ]`. Default is `true`. +`split_on_numerics` | 可选 | Boolean | Splits tokens where there are consecutive letters and numbers. For example `"v8engine"` will become `[ v, 8, engine ]`. Default is `true`. +`stem_english_possessive` | 可选 | Boolean | Removes English possessive endings, such as `'s`. Default is `true`. +`type_table` | 可选 | Array of strings | A custom map that specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For example, to treat a hyphen (`-`) as an alphanumeric character, specify `["- => ALPHA"]` so that words are not split on hyphens. Valid types are: <br> - `ALPHA`: alphabetical <br> - `ALPHANUM`: alphanumeric <br> - `DIGIT`: numeric <br> - `LOWER`: lowercase alphabetical <br> - `SUBWORD_DELIM`: non-alphanumeric delimiter <br> - `UPPER`: uppercase alphabetical +`type_table_path` | 可选 | String | Specifies a path (absolute or relative to the config directory) to a file containing a custom character map. The map specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For valid types, see `type_table`. + +## 示例 + +The following example request creates a new index named `my-custom-index` and configures an analyzer with a `word_delimiter_graph` filter: + +```json +PUT /my-custom-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "tokenizer": "keyword", + "filter": [ "custom_word_delimiter_filter" ] + } + }, + "filter": { + "custom_word_delimiter_filter": { + "type": "word_delimiter_graph", + "split_on_case_change": true, + "split_on_numerics": true, + "stem_english_possessive": true + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-custom-index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "FastCar's Model2023" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Fast", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "Car", + "start_offset": 4, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "Model", + "start_offset": 10, + "end_offset": 15, + "type": "word", + "position": 2 + }, + { + "token": "2023", + "start_offset": 15, + "end_offset": 19, + "type": "word", + "position": 3 + } + ] +} +``` + +<!-- vale off--> +## Differences between the word_delimiter_graph and word_delimiter filters +<!-- vale on--> + +Both the `word_delimiter_graph` and `word_delimiter` token filters generate tokens spanning multiple positions when any of the following parameters are set to `true`: + +- `catenate_all` +- `catenate_numbers` +- `catenate_words` +- `preserve_original` + +To illustrate the differences between these filters, consider the input text `Pro-XT500`. + +<!-- vale off--> +### word_delimiter_graph +<!-- vale on--> + +The `word_delimiter_graph` filter assigns a `positionLength` attribute to multi-position tokens, indicating how many positions a token spans. This ensures that the filter always generates valid token graphs, making it suitable for use in advanced token graph scenarios. Although token graphs with multi-position tokens are not supported for indexing, they can still be useful in search scenarios. For example, queries like `match_phrase` can use these graphs to generate multiple subqueries from a single input string. For the example input text, the `word_delimiter_graph` filter generates the following tokens: + +- `Pro` (position 1) +- `XT500` (position 2) +- `ProXT500` (position 1, `positionLength`: 2) + +The `positionLength` attribute the production of a valid graph to be used in advanced queries. + +<!-- vale off--> +### word_delimiter +<!-- vale on--> + +In contrast, the `word_delimiter` filter does not assign a `positionLength` attribute to multi-position tokens, leading to invalid graphs when these tokens are present. For the example input text, the `word_delimiter` filter generates the following tokens: + +- `Pro` (position 1) +- `XT500` (position 2) +- `ProXT500` (position 1, no `positionLength`) + +The lack of a `positionLength` attribute results in a token graph that is invalid for token streams containing multi-position tokens. diff --git a/i18n/zh/analyzers/token-filters/word-delimiter.md b/i18n/zh/analyzers/token-filters/word-delimiter.md new file mode 100644 index 00000000..8e29b009 --- /dev/null +++ b/i18n/zh/analyzers/token-filters/word-delimiter.md @@ -0,0 +1,126 @@ +--- +title: 单词分隔符 +--- + +# Word delimiter token filter + +The `word_delimiter` token filter is used to splits token on predefined characters and also offers optional token normalization based on customizable rules. + +::: warning IMPORTANT +We recommend using the `word_delimiter_graph` filter instead of the `word_delimiter` filter whenever possible because the `word_delimiter` filter sometimes produces invalid token graphs. For more information about the differences between the two filters, see [Differences between the `word_delimiter_graph` and `word_delimiter` filters](/analyzers/token-filters/word-delimiter-graph#differences-between-the-word_delimiter_graph-and-word_delimiter-filters). +::: + +::: info NOTE +The `word_delimiter` filter is used to remove punctuation from complex identifiers like part numbers or product IDs. In such cases, it is best used with the `keyword` tokenizer. For hyphenated words, use the `synonym_graph` token filter instead of the `word_delimiter` filter because users frequently search for these terms both with and without hyphens. +::: + +By default, the filter applies the following rules. + +| 描述 | Input | Output | +|:---|:---|:---| +| Treats non-alphanumeric characters as delimiters. | `ultra-fast` | `ultra`, `fast` | +| Removes delimiters at the beginning or end of tokens. | `Z99++'Decoder'`| `Z99`, `Decoder` | +| Splits tokens when there is a transition between uppercase and lowercase letters. | `OpenSearch` | `Open`, `Search` | +| Splits tokens when there is a transition between letters and numbers. | `T1000` | `T`, `1000` | +| Removes the possessive ('s) from the end of tokens. | `John's` | `John` | + +::: warning IMPORTANT +It's important **not** to use tokenizers that strip punctuation, like the `standard` tokenizer, with this filter. Doing so may prevent proper token splitting and interfere with options like `catenate_all` or `preserve_original`. We recommend using this filter with a `keyword` or `whitespace` tokenizer. +::: + +## 参数 + +You can configure the `word_delimiter` token filter using the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`catenate_all` | 可选 | Boolean | Produces concatenated tokens from a sequence of alphanumeric parts. For example, `"quick-fast-200"` becomes `[ quickfast200, quick, fast, 200 ]`. Default is `false`. +`catenate_numbers` | 可选 | Boolean | Concatenates numerical sequences. For example, `"10-20-30"` becomes `[ 102030, 10, 20, 30 ]`. Default is `false`. +`catenate_words` | 可选 | Boolean | Concatenates alphabetic words. For example, `"high-speed-level"` becomes `[ highspeedlevel, high, speed, level ]`. Default is `false`. +`generate_number_parts` | 可选 | Boolean | If `true`, numeric tokens (tokens consisting of numbers only) are included in the output. Default is `true`. +`generate_word_parts` | 可选 | Boolean | If `true`, alphabetical tokens (tokens consisting of alphabetic characters only) are included in the output. Default is `true`. +`preserve_original` | 可选 | Boolean | Keeps the original token (which may include non-alphanumeric delimiters) alongside the generated tokens in the output. For example, `"auto-drive-300"` becomes `[ auto-drive-300, auto, drive, 300 ]`. If `true`, the filter generates multi-position tokens not supported by indexing, so do not use this filter in an index analyzer or use the `flatten_graph` filter after this filter. Default is `false`. +`protected_words` | 可选 | Array of strings | Specifies tokens that should not be split. +`protected_words_path` | 可选 | String | Specifies a path (absolute or relative to the config directory) to a file containing tokens that should not be separated by new lines. +`split_on_case_change` | 可选 | Boolean | Splits tokens where consecutive letters have different cases (one is lowercase and the other is uppercase). For example, `"OpenSearch"` becomes `[ Open, Search ]`. Default is `true`. +`split_on_numerics` | 可选 | Boolean | Splits tokens where there are consecutive letters and numbers. For example `"v8engine"` will become `[ v, 8, engine ]`. Default is `true`. +`stem_english_possessive` | 可选 | Boolean | Removes English possessive endings, such as `'s`. Default is `true`. +`type_table` | 可选 | Array of strings | A custom map that specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For example, to treat a hyphen (`-`) as an alphanumeric character, specify `["- => ALPHA"]` so that words are not split on hyphens. Valid types are: <br> - `ALPHA`: alphabetical <br> - `ALPHANUM`: alphanumeric <br> - `DIGIT`: numeric <br> - `LOWER`: lowercase alphabetical <br> - `SUBWORD_DELIM`: non-alphanumeric delimiter <br> - `UPPER`: uppercase alphabetical +`type_table_path` | 可选 | String | Specifies a path (absolute or relative to the config directory) to a file containing a custom character map. The map specifies how to treat characters and whether to treat them as delimiters, which avoids unwanted splitting. For valid types, see `type_table`. + +## 示例 + +The following example request creates a new index named `my-custom-index` and configures an analyzer with a `word_delimiter` filter: + +```json +PUT /my-custom-index +{ + "settings": { + "analysis": { + "analyzer": { + "custom_analyzer": { + "tokenizer": "keyword", + "filter": [ "custom_word_delimiter_filter" ] + } + }, + "filter": { + "custom_word_delimiter_filter": { + "type": "word_delimiter", + "split_on_case_change": true, + "split_on_numerics": true, + "stem_english_possessive": true + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +GET /my-custom-index/_analyze +{ + "analyzer": "custom_analyzer", + "text": "FastCar's Model2023" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Fast", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "Car", + "start_offset": 4, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "Model", + "start_offset": 10, + "end_offset": 15, + "type": "word", + "position": 2 + }, + { + "token": "2023", + "start_offset": 15, + "end_offset": 19, + "type": "word", + "position": 3 + } + ] +} +``` diff --git a/i18n/zh/analyzers/token-graph.md b/i18n/zh/analyzers/token-graph.md new file mode 100644 index 00000000..133973dd --- /dev/null +++ b/i18n/zh/analyzers/token-graph.md @@ -0,0 +1,193 @@ +--- +title: 词元图 +--- + +# 词元图 + +词元图显示在文本分析期间词元如何相互关联,特别是在处理多词同义词或复合词时。它们有助于确保准确的查询匹配和短语扩展。 + +每个词元都分配有以下元数据: + +- `position` – 词元在文本中的位置 + +- `positionLength` – 词元跨越多少个位置(用于多词表达) + +词元图使用此信息构建词元关系的图结构,该结构稍后在查询解析期间使用。图感知词元过滤器,例如 [`synonym_graph`](/analyzers/token-filters/synonym-graph) 和 [`word_delimiter_graph`](/analyzers/token-filters/word-delimiter-graph),使您能够更准确地匹配短语。 + +下图描述了使用 [`synonym_graph`](/analyzers/token-filters/synonym-graph) 时 `position` 和 `positionLength` 之间的关系。"NYC"词元被分配了 `position` 为 `0` 和 `positionLength` 为 `3`。 + +*token graph* + +## 在索引和查询期间使用词元图 + +在索引时,`positionLength` 被忽略,不使用词元图。 + +在查询执行期间,各种查询类型可以利用词元图,最常用的包括: + +- [`match`](/query-dsl/full-text/match) +- [`match_phrase`](/query-dsl/full-text/match-phrase) + +## 示例:同义词与同义词图的比较 + +为了更好地理解图感知词元过滤器和标准词元过滤器之间的区别,您可以使用以下步骤比较 [`synonym`](/analyzers/token-filters/synonym) 词元过滤器和 [`synonym_graph`](/analyzers/token-filters/synonym-graph) 词元过滤器: + +1. 创建带有 [`synonym`](/analyzers/token-filters/synonym) 词元过滤器(非图感知)的索引: + + ```json + PUT /synonym_index + { + "settings": { + "analysis": { + "filter": { + "my_synonyms": { + "type": "synonym", + "synonyms": ["ssd => solid state drive"] + } + }, + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "filter": ["lowercase", "my_synonyms"] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_analyzer" + } + } + } + } + ``` + +2. 创建带有 [`synonym_graph`](/analyzers/token-filters/synonym-graph) 词元过滤器(图感知)的索引: + + ```json + PUT /synonym_graph_index + { + "settings": { + "analysis": { + "filter": { + "my_synonyms": { + "type": "synonym_graph", + "synonyms": ["ssd => solid state drive"] + } + }, + "analyzer": { + "my_analyzer": { + "tokenizer": "standard", + "filter": ["lowercase", "my_synonyms"] + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_analyzer" + } + } + } + } + ``` + +3. 在每个索引中创建相同的文档: + + ```json + PUT /synonym_index/_doc/1 + { "content": "ssd is critical" } + ``` + + ```json + PUT /synonym_graph_index/_doc/1 + { "content": "ssd is critical" } + ``` + +4. 搜索非图感知索引: + + ```json + POST /synonym_index/_search + { + "query": { + "match_phrase": { + "content": "solid state drive is critical" + } + } + } + ``` + + 响应不包含任何命中: + + ```json + { + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 0, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } + } + ``` + +5. 搜索图感知索引: + + ```json + POST /synonym_graph_index/_search + { + "query": { + "match_phrase": { + "content": "solid state drive is critical" + } + } + } + ``` + + 响应包含一个命中: + + ```json + { + "took": 9, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.4384103, + "hits": [ + { + "_index": "synonym_graph_index", + "_id": "1", + "_score": 1.4384103, + "_source": { + "content": "ssd is critical" + } + } + ] + } + } + ``` + +使用图感知词元过滤器时会出现命中,因为在 [`match_phrase`](/query-dsl/full-text/match-phrase) 查询期间,使用词元图生成了一个额外的子查询。下图说明了图感知词元过滤器创建的词元图。 + +*token graph* diff --git a/i18n/zh/analyzers/tokenizers/character-group.md b/i18n/zh/analyzers/tokenizers/character-group.md new file mode 100644 index 00000000..9729e23d --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/character-group.md @@ -0,0 +1,117 @@ +--- +title: 字符组 +--- + +# Character group tokenizer + +The `char_group` tokenizer splits text into tokens using specific characters as delimiters. It is suitable for situations requiring straightforward tokenization, offering a simpler alternative to pattern-based tokenizers without the added complexity. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `char_group` tokenizer. The tokenizer splits text on white space, `-`, and `:` characters: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_char_group_tokenizer": { + "type": "char_group", + "tokenize_on_chars": [ + "whitespace", + "-", + ":" + ] + } + }, + "analyzer": { + "my_char_group_analyzer": { + "type": "custom", + "tokenizer": "my_char_group_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_char_group_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_char_group_analyzer", + "text": "Fast-driving cars: they drive fast!" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Fast", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "driving", + "start_offset": 5, + "end_offset": 12, + "type": "word", + "position": 1 + }, + { + "token": "cars", + "start_offset": 13, + "end_offset": 17, + "type": "word", + "position": 2 + }, + { + "token": "they", + "start_offset": 19, + "end_offset": 23, + "type": "word", + "position": 3 + }, + { + "token": "drive", + "start_offset": 24, + "end_offset": 29, + "type": "word", + "position": 4 + }, + { + "token": "fast!", + "start_offset": 30, + "end_offset": 35, + "type": "word", + "position": 5 + } + ] +} +``` + +## 参数 + +The `char_group` tokenizer can be configured with the following parameters. + +| **Parameter** | **Required/Optional** | **Data type** | **Description** | +| :--- | :--- | :--- | :--- | +| `tokenize_on_chars` | 必需 | Array | Specifies a set of characters on which the text should be tokenized. You can specify single characters (for example, `-` or `@`), including escape characters (for example, `\n`), or character classes such as `whitespace`, `letter`, `digit`, `punctuation`, or `symbol`. | +| `max_token_length` | 可选 | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. | diff --git a/i18n/zh/analyzers/tokenizers/classic.md b/i18n/zh/analyzers/tokenizers/classic.md new file mode 100644 index 00000000..777dd1a0 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/classic.md @@ -0,0 +1,220 @@ +--- +title: 经典 +--- + +# Classic tokenizer + +The `classic` tokenizer parses text, applying English language grammatical rules to break the text into tokens. It includes specific logic to handle patterns such as the following: + +- Acronyms +- Email addresses +- Domain names +- Certain types of punctuation + +::: info NOTE +This tokenizer works best with the English language. It may not produce optimal results for other languages, especially those with different grammatical structures. +::: + +The `classic` tokenizer parses text as follows: + +- **Punctuation**: Splits text on most punctuation marks and removes punctuation characters. Dots that aren't followed by spaces are treated as part of the token. +- **Hyphens**: Splits words at hyphens, except when a number is present. When a number is present in a token, the token is not split and is treated like a product number. +- **Email**: Recognizes email addresses and hostnames and keeps them as single tokens. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `classic` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_classic_analyzer": { + "type": "custom", + "tokenizer": "classic" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_classic_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_classic_analyzer", + "text": "For product AB3423, visit X&Y at example.com, email info@example.com, or call the operator's phone number 1-800-555-1234. P.S. 你好." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "For", + "start_offset": 0, + "end_offset": 3, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "product", + "start_offset": 4, + "end_offset": 11, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "AB3423", + "start_offset": 12, + "end_offset": 18, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "visit", + "start_offset": 20, + "end_offset": 25, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "X&Y", + "start_offset": 26, + "end_offset": 29, + "type": "<COMPANY>", + "position": 4 + }, + { + "token": "at", + "start_offset": 30, + "end_offset": 32, + "type": "<ALPHANUM>", + "position": 5 + }, + { + "token": "example.com", + "start_offset": 33, + "end_offset": 44, + "type": "<HOST>", + "position": 6 + }, + { + "token": "email", + "start_offset": 46, + "end_offset": 51, + "type": "<ALPHANUM>", + "position": 7 + }, + { + "token": "info@example.com", + "start_offset": 52, + "end_offset": 68, + "type": "<EMAIL>", + "position": 8 + }, + { + "token": "or", + "start_offset": 70, + "end_offset": 72, + "type": "<ALPHANUM>", + "position": 9 + }, + { + "token": "call", + "start_offset": 73, + "end_offset": 77, + "type": "<ALPHANUM>", + "position": 10 + }, + { + "token": "the", + "start_offset": 78, + "end_offset": 81, + "type": "<ALPHANUM>", + "position": 11 + }, + { + "token": "operator's", + "start_offset": 82, + "end_offset": 92, + "type": "<APOSTROPHE>", + "position": 12 + }, + { + "token": "phone", + "start_offset": 93, + "end_offset": 98, + "type": "<ALPHANUM>", + "position": 13 + }, + { + "token": "number", + "start_offset": 99, + "end_offset": 105, + "type": "<ALPHANUM>", + "position": 14 + }, + { + "token": "1-800-555-1234", + "start_offset": 106, + "end_offset": 120, + "type": "<NUM>", + "position": 15 + }, + { + "token": "P.S.", + "start_offset": 122, + "end_offset": 126, + "type": "<ACRONYM>", + "position": 16 + }, + { + "token": "你", + "start_offset": 127, + "end_offset": 128, + "type": "<CJ>", + "position": 17 + }, + { + "token": "好", + "start_offset": 128, + "end_offset": 129, + "type": "<CJ>", + "position": 18 + } + ] +} +``` + +## Token types + +The `classic` tokenizer produces the following token types. + +| Token type | 描述 | +| :--- | :--- | +| `<ALPHANUM>` | Alphanumeric tokens consisting of letters, numbers, or a combination of both. | +| `<APOSTROPHE>`| Tokens containing an apostrophe, commonly used in possessives or contractions (for example, `John's`). | +| `<ACRONYM>` | Acronyms or abbreviations, often identified by a trailing period (for example, `P.S.` or `U.S.A.`). | +| `<COMPANY>` | Tokens representing company names (for example, `X&Y`). If these tokens aren't produced automatically, you may need custom configurations or filters. | +| `<EMAIL>` | Tokens matching email addresses, containing an `@` symbol and a domain (for example,`support@widgets.co` or `info@example.com`). | +| `<HOST>` | Tokens matching website or host names, often containing `www.` or a domain suffix like `.com` (for example, `www.example.com` or `example.org`). | +| `<NUM>` | Tokens containing only numbers or numeric-like sequences (for example, `1-800`, `12345`, or `3.14`). | +| `<CJ>` | Tokens representing Chinese or Japanese characters. | +| `<ACRONYM_DEP>` | Deprecated acronym handling (for example, acronyms with different parsing rules in older versions). Rarely used---exists primarily for backward compatibility with legacy tokenizer rules. | diff --git a/i18n/zh/analyzers/tokenizers/edge-n-gram.md b/i18n/zh/analyzers/tokenizers/edge-n-gram.md new file mode 100644 index 00000000..657227cb --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/edge-n-gram.md @@ -0,0 +1,195 @@ +--- +title: 边缘 n-gram +--- + +# Edge n-gram tokenizer + +The `edge_ngram` tokenizer generates partial word tokens, or _n-grams_, starting from the beginning of each word. It splits the text based on specified characters and produces tokens within a defined minimum and maximum length range. This tokenizer is particularly useful for implementing search-as-you-type functionality. + +Edge n-grams are ideal for autocomplete searches where the order of the words may vary, such as when searching for product names or addresses. For more information, see [Autocomplete](/search-plugins/searching-data/autocomplete). However, for text with a fixed order, like movie or song titles, the completion suggester may be more accurate. + +By default, the `edge n-gram` tokenizer produces tokens with a minimum length of `1` and a maximum length of `2`. For example, when analyzing the text `OpenSearch`, the default configuration will produce the `O` and `Op` n-grams. These short n-grams often match too many irrelevant terms, so configuring the tokenizer is necessary in order to adjust the n-gram lengths. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with an `edge_ngram` tokenizer. The tokenizer produces tokens 3--6 characters in length, considering both letters and symbols to be valid token characters: + +```json +PUT /edge_n_gram_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_custom_analyzer": { + "tokenizer": "my_custom_tokenizer" + } + }, + "tokenizer": { + "my_custom_tokenizer": { + "type": "edge_ngram", + "min_gram": 3, + "max_gram": 6, + "token_chars": [ + "letter" ] + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /edge_n_gram_index/_analyze +{ + "analyzer": "my_custom_analyzer", + "text": "Code 42 rocks!" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Cod", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "Code", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "roc", + "start_offset": 8, + "end_offset": 11, + "type": "word", + "position": 2 + }, + { + "token": "rock", + "start_offset": 8, + "end_offset": 12, + "type": "word", + "position": 3 + }, + { + "token": "rocks", + "start_offset": 8, + "end_offset": 13, + "type": "word", + "position": 4 + } + ] +} +``` + +## 参数 + +| 参数 | 是否必需 | 数据类型 | 描述 | +|:-------|:--------|:------|:---| +| `min_gram` | 可选 | Integer | The minimum token length. Default is `1`. | +| `max_gram` | 可选 | Integer | The maximum token length. Default is `2`. | +| `custom_token_chars`| 可选 | String | Defines custom characters to be treated as part of a token (for example, `+-_`). | +| `token_chars` | 可选 | Array of strings | Defines character classes to include in tokens. Tokens are split on characters not included in these classes. Default includes all characters. Available classes include: <br> - `letter`: Alphabetic characters (for example, `a`, `ç`, or `京`) <br> - `digit`: Numeric characters (for example, `3` or `7`) <br>- `punctuation`: Punctuation symbols (for example, `!` or `?`) <br> - `symbol`: Other symbols (for example, `$` or `√`) <br> - `whitespace`: Space or newline characters <br> - `custom`: Allows you to specify custom characters in the `custom_token_chars` setting. | + +<!-- vale off --> +## max_gram parameter limitations +<!-- vale on --> + +The `max_gram` parameter sets the maximum length of tokens generated by the tokenizer. When a search query exceeds this length, it may fail to match any terms in the index. + +For example, if `max_gram` is set to `4`, the query `explore` would be tokenized as `expl` during indexing. As a result, a search for the full term `explore` will not match the indexed token `expl`. + +To address this limitation, you can apply a `truncate` token filter to shorten search terms to the maximum token length. However, this approach presents trade-offs. Truncating `explore` to `expl` might lead to matches with unrelated terms like `explosion` or `explicit`, reducing search precision. + +We recommend carefully balancing the `max_gram` value to ensure efficient tokenization while minimizing irrelevant matches. If precision is critical, consider alternative strategies, such as adjusting query analyzers or fine-tuning filters. + +## Best practices + +We recommend using the `edge_ngram` tokenizer only at indexing time in order to ensure that partial word tokens are stored. At search time, a basic analyzer should be used to match all query terms. + +## Configuring search-as-you-type functionality + +To implement search-as-you-type functionality, use the `edge_ngram` tokenizer during indexing and an analyzer that performs minimal processing at search time. The following example demonstrates this approach. + +Create an index with an `edge_ngram` tokenizer: + +```json +PUT /my-autocomplete-index +{ + "settings": { + "analysis": { + "analyzer": { + "autocomplete": { + "tokenizer": "autocomplete", + "filter": [ + "lowercase" + ] + }, + "autocomplete_search": { + "tokenizer": "lowercase" + } + }, + "tokenizer": { + "autocomplete": { + "type": "edge_ngram", + "min_gram": 2, + "max_gram": 10, + "token_chars": [ + "letter" + ] + } + } + } + }, + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "autocomplete", + "search_analyzer": "autocomplete_search" + } + } + } +} +``` + +Index a document containing a `product` field and refresh the index: + +```json +PUT my-autocomplete-index/_doc/1?refresh +{ + "title": "Laptop Pro" +} +``` + +This configuration ensures that the `edge_ngram` tokenizer breaks terms like "Laptop" into tokens such as `La`, `Lap`, and `Lapt`, allowing partial matches during search. At search time, the `standard` tokenizer simplifies queries while ensuring that matches are case-insensitive because of the lowercase filter. + +Searches for `laptop Pr` or `lap pr` now retrieve the relevant document based on partial matches: + +```json +GET my-autocomplete-index/_search +{ + "query": { + "match": { + "title": { + "query": "lap pr", + "operator": "and" + } + } + } +} +``` + +For more information, see [Search as you type](/search-plugins/searching-data/autocomplete#search-as-you-type). diff --git a/i18n/zh/analyzers/tokenizers/icu-tokenizer.md b/i18n/zh/analyzers/tokenizers/icu-tokenizer.md new file mode 100644 index 00000000..f6503a54 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/icu-tokenizer.md @@ -0,0 +1,155 @@ +--- +title: ICU +--- + +# ICU tokenizer + +The `icu_tokenizer` splits text into words using Unicode text segmentation rules defined in [Unicode Standard Annex #29](https://www.unicode.org/reports/tr29/). This tokenizer provides more accurate word boundary detection than the standard tokenizer, particularly for Asian languages that don't use spaces to separate words. + +The `icu_tokenizer` employs dictionary-based tokenization for Chinese, Japanese, Korean, Thai, and Lao text, and applies specialized rules for segmenting Myanmar and Khmer scripts into syllables. + +## 安装 + +The `icu_tokenizer` requires the `analysis-icu` plugin. For installation instructions, see [ICU analyzer](/analyzers/language-analyzers/icu). + +## 示例 + +The following example demonstrates how to use the `icu_tokenizer`: + +```json +PUT /icu-tokenizer-index +{ + "settings": { + "analysis": { + "analyzer": { + "icu_analyzer_custom": { + "tokenizer": "icu_tokenizer" + } + } + } + } +} +``` + +## Testing the tokenizer + +Use the following request to test the `icu_tokenizer`: + +```json +POST /icu-tokenizer-index/_analyze +{ + "tokenizer": "icu_tokenizer", + "text": "สวัสดีOpenSearchเป็นเครื่องมือค้นหา" +} +``` + +The tokenizer correctly segments Thai text without spaces: + +```json +{ + "tokens": [ + { + "token": "สวัสดี", + "start_offset": 0, + "end_offset": 6, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "OpenSearch", + "start_offset": 6, + "end_offset": 16, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "เป็น", + "start_offset": 16, + "end_offset": 20, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "เครื่อง", + "start_offset": 20, + "end_offset": 27, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "มือ", + "start_offset": 27, + "end_offset": 30, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "ค้นหา", + "start_offset": 30, + "end_offset": 35, + "type": "<ALPHANUM>", + "position": 5 + } + ] +} +``` + +## Customizing tokenization rules + +Advanced users can customize the `icu_tokenizer` behavior by specifying per-script rule files using the Resource Bundle Break Iterator (RBBI) syntax. This feature is experimental in Lucene. + +To apply custom rules, use the `rule_files` parameter with a comma-separated list of `script:filename` pairs. Script codes follow the [ISO 15924](https://unicode.org/iso15924/iso15924-codes.html) four-letter standard. + +### 示例 with custom rules + +Save a custom rule file to your OpenSearch config directory (for example, `CustomRules.rbbi`): + +```text +.+ {200}; +``` + +Configure an analyzer to use this rule file: + +```json +PUT /custom-icu-rules +{ + "settings": { + "analysis": { + "tokenizer": { + "custom_icu_tokenizer": { + "type": "icu_tokenizer", + "rule_files": "Latn:CustomRules.rbbi" + } + }, + "analyzer": { + "custom_icu_analyzer": { + "tokenizer": "custom_icu_tokenizer" + } + } + } + } +} +``` + +Test the custom tokenizer: + +```json +POST /custom-icu-rules/_analyze +{ + "analyzer": "custom_icu_analyzer", + "text": "Custom tokenization rules" +} +``` + +## 参数 + +The following table lists the parameters for the `icu_tokenizer`. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`rule_files` | String | Comma-separated list of `script:rulefile` pairs that define custom tokenization rules for specific scripts. Rule files must be placed in the OpenSearch config directory. Optional. + +## 相关文档 + +- [ICU analyzer](/analyzers/language-analyzers/icu) +- [Standard tokenizer](/analyzers/tokenizers/standard) diff --git a/i18n/zh/analyzers/tokenizers/keyword.md b/i18n/zh/analyzers/tokenizers/keyword.md new file mode 100644 index 00000000..ff97e904 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/keyword.md @@ -0,0 +1,112 @@ +--- +title: 关键词 +--- + +# Keyword tokenizer + +The `keyword` tokenizer ingests text and outputs it exactly as a single, unaltered token. This makes it particularly useful when you want the input to remain intact, such as when managing structured data like names, product codes, or email addresses. + +The `keyword` tokenizer can be paired with token filters to process the text, for example, to normalize it or to remove extraneous characters. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `keyword` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_keyword_analyzer": { + "type": "custom", + "tokenizer": "keyword" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_keyword_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_keyword_analyzer", + "text": "OpenSearch Example" +} +``` + +响应包含 the single token representing the original text: + +```json +{ + "tokens": [ + { + "token": "OpenSearch Example", + "start_offset": 0, + "end_offset": 18, + "type": "word", + "position": 0 + } + ] +} +``` + +## 参数 + +The `keyword` token filter can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`buffer_size`| 可选 | Integer | Determines the character buffer size. Default is `256`. There is usually no need to change this setting. + +## Combining the keyword tokenizer with token filters + +To enhance the functionality of the `keyword` tokenizer, you can combine it with token filters. Token filters can transform the text, such as converting it to lowercase or removing unwanted characters. + +### 示例: Using the pattern_replace filter and keyword tokenizer + +In this example, the `pattern_replace` filter uses a regular expression to replace all non-alphanumeric characters with an empty string: + +```json +POST _analyze +{ + "tokenizer": "keyword", + "filter": [ + { + "type": "pattern_replace", + "pattern": "[^a-zA-Z0-9]", + "replacement": "" + } + ], + "text": "Product#1234-XYZ" +} +``` + +The `pattern_replace` filter removes non-alphanumeric characters and returns the following token: + +```json +{ + "tokens": [ + { + "token": "Product1234XYZ", + "start_offset": 0, + "end_offset": 16, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/tokenizers/kuromoji.md b/i18n/zh/analyzers/tokenizers/kuromoji.md new file mode 100644 index 00000000..73c32e25 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/kuromoji.md @@ -0,0 +1,463 @@ +--- +title: Kuromoji +--- + +# Kuromoji tokenizer + +The `kuromoji_tokenizer` performs dictionary-based morphological analysis for Japanese text using the Kuromoji library and the IPAdic dictionary. Unlike tokenizers that split on white space or punctuation, it identifies natural word boundaries in Japanese sentences, which do not use spaces to separate words. + +## 安装 + +The `kuromoji_tokenizer` requires the `analysis-kuromoji` plugin. For installation instructions, see [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji). + +## 参数 + +The following table lists the parameters for the `kuromoji_tokenizer`. + +Parameter | 数据类型 | Description +:--- | :--- | :--- +`mode` | String | Tokenization mode. Valid values are `normal`, `search` (default), and `extended`. See [Tokenization modes](#tokenization-modes) for details. +`discard_punctuation` | Boolean | When `true`, punctuation tokens are discarded from the output. Default is `true`. +`discard_compound_token` | Boolean | When `true`, the compound token produced in `search` mode is discarded and only the sub-tokens are kept. Default is `false`. +`user_dictionary` | String | Path to a custom user dictionary CSV file placed in the OpenSearch config directory. Each line must follow the format `<text>,<subtokens>,<readings>,<part of speech>`. Optional. +`user_dictionary_rules` | Array of strings | Inline custom dictionary rules in the same CSV format as `user_dictionary`. Optional. Cannot be used together with `user_dictionary`. +`nbest_cost` | Integer | When set to a value greater than `-1`, enables n-best segmentation and returns alternative tokenizations whose cost (log probability penalty) is within this value of the best segmentation. Default is `-1` (disabled). +`nbest_examples` | String | A comma-separated list of example words used to automatically calculate `nbest_cost`. When provided, the tokenizer finds the minimum additional cost needed to also produce the given examples as tokens. Optional. + +## Tokenization modes + +The tokenization mode controls how the tokenizer handles compound and unknown words. + +| Mode | Compound words | Unknown words | +|:-----|:---------------|:--------------| +| `normal` | Kept as a single token (for example, 関西国際空港 is one token). | Kept as a single token. | +| `search` (default) | Split into sub-tokens in addition to the compound form (for example, 関西国際空港 produces 関西, 国際, 空港, and 関西国際空港). Improves recall for search queries. | Kept as a single token. | +| `extended` | Kept as a single token (same as `normal`). | Split into unigrams (individual characters), ensuring every character is indexed. | + +## 示例: Basic tokenization + +The following example creates an index with a custom analyzer using `kuromoji_tokenizer` in its default `search` mode: + +```json +PUT /kuromoji-tokenizer-index +{ + "settings": { + "analysis": { + "analyzer": { + "kuromoji_analyzer": { + "tokenizer": "kuromoji_tokenizer" + } + } + } + } +} +``` + +Test the tokenizer with a sentence meaning "Kansai International Airport is a large airport": + +```json +POST /kuromoji-tokenizer-index/_analyze +{ + "analyzer": "kuromoji_analyzer", + "text": "関西国際空港は大きな空港です" +} +``` + +In `search` mode, the compound place name 関西国際空港 (Kansai International Airport) is split into its components and also kept as a compound token: + +```json +{ + "tokens": [ + { + "token": "関西", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0, + "positionLength": 3 + }, + { + "token": "国際", + "start_offset": 2, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "空港", + "start_offset": 4, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "は", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 3 + }, + { + "token": "大きな", + "start_offset": 7, + "end_offset": 10, + "type": "word", + "position": 4 + }, + { + "token": "空港", + "start_offset": 10, + "end_offset": 12, + "type": "word", + "position": 5 + }, + { + "token": "です", + "start_offset": 12, + "end_offset": 14, + "type": "word", + "position": 6 + } + ] +} +``` + +## 示例: Comparing tokenization modes + +The following example shows how the same text is tokenized differently depending on the mode. Create a custom tokenizer for each mode and compare the output: + +```json +PUT /kuromoji-mode-comparison +{ + "settings": { + "analysis": { + "tokenizer": { + "kuromoji_normal": { + "type": "kuromoji_tokenizer", + "mode": "normal" + }, + "kuromoji_search": { + "type": "kuromoji_tokenizer", + "mode": "search" + }, + "kuromoji_extended": { + "type": "kuromoji_tokenizer", + "mode": "extended" + } + } + } + } +} +``` + +Test with text that contains a known compound word (関西国際空港 meaning "Kansai International Airport") and an unknown loanword (アバクロンビー meaning "Abercrombie"): + +**`normal` mode** + +```json +POST /kuromoji-mode-comparison/_analyze +{ + "tokenizer": "kuromoji_normal", + "text": "関西国際空港とアバクロンビー" +} +``` + +In `normal` mode, the compound 関西国際空港 is kept as a single token and the unknown loanword アバクロンビー is also kept as a single token: + +```json +{ + "tokens": [ + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0 + }, + { + "token": "と", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "アバクロンビー", + "start_offset": 7, + "end_offset": 14, + "type": "word", + "position": 2 + } + ] +} +``` + +**`search` mode** + +```json +POST /kuromoji-mode-comparison/_analyze +{ + "tokenizer": "kuromoji_search", + "text": "関西国際空港とアバクロンビー" +} +``` + +In `search` mode, the compound 関西国際空港 is split into sub-tokens (関西, 国際, 空港) while also being retained as a compound token with `positionLength: 3`. The unknown loanword アバクロンビー is kept as a single token, the same as in `normal` mode: + +```json +{ + "tokens": [ + { + "token": "関西", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0, + "positionLength": 3 + }, + { + "token": "国際", + "start_offset": 2, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "空港", + "start_offset": 4, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "と", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 3 + }, + { + "token": "アバクロンビー", + "start_offset": 7, + "end_offset": 14, + "type": "word", + "position": 4 + } + ] +} +``` + +**`extended` mode** + +```json +POST /kuromoji-mode-comparison/_analyze +{ + "tokenizer": "kuromoji_extended", + "text": "関西国際空港とアバクロンビー" +} +``` + +In `extended` mode, the known compound 関西国際空港 is handled the same as in `search` mode. The unknown loanword アバクロンビー is split into individual characters (unigrams), ensuring every character is indexed: + +```json +{ + "tokens": [ + { + "token": "関西", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "関西国際空港", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0, + "positionLength": 3 + }, + { + "token": "国際", + "start_offset": 2, + "end_offset": 4, + "type": "word", + "position": 1 + }, + { + "token": "空港", + "start_offset": 4, + "end_offset": 6, + "type": "word", + "position": 2 + }, + { + "token": "と", + "start_offset": 6, + "end_offset": 7, + "type": "word", + "position": 3 + }, + { + "token": "ア", + "start_offset": 7, + "end_offset": 8, + "type": "word", + "position": 4 + }, + { + "token": "バ", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 5 + }, + { + "token": "ク", + "start_offset": 9, + "end_offset": 10, + "type": "word", + "position": 6 + }, + { + "token": "ロ", + "start_offset": 10, + "end_offset": 11, + "type": "word", + "position": 7 + }, + { + "token": "ン", + "start_offset": 11, + "end_offset": 12, + "type": "word", + "position": 8 + }, + { + "token": "ビ", + "start_offset": 12, + "end_offset": 13, + "type": "word", + "position": 9 + }, + { + "token": "ー", + "start_offset": 13, + "end_offset": 14, + "type": "word", + "position": 10 + } + ] +} +``` + +## 示例: User dictionary + +You can add custom compound terms to the tokenizer's dictionary to control how they are split into sub-tokens. Use `user_dictionary_rules` for inline rules or `user_dictionary` for a file. + +The following example registers 東京スカイツリー (Tokyo Skytree) as a single noun: + +```json +PUT /kuromoji-user-dict-index +{ + "settings": { + "analysis": { + "tokenizer": { + "kuromoji_with_user_dict": { + "type": "kuromoji_tokenizer", + "mode": "search", + "user_dictionary_rules": [ + "東京スカイツリー,東京 スカイツリー,トウキョウ スカイツリー,カスタム名詞" + ] + } + }, + "analyzer": { + "user_dict_analyzer": { + "tokenizer": "kuromoji_with_user_dict" + } + } + } + } +} +``` + +Each `user_dictionary_rules` entry is a CSV string with four comma-separated fields, in the order `<text>,<subtokens>,<readings>,<part of speech>`. The following table describes each field. + +| Field | 描述 | +|:---|:---| +| `<text>` | The text as it appears in the document (for example, `東京スカイツリー`). | +| `<subtokens>` | Space-separated subtokens for segmentatio (for example, `東京 スカイツリー`). | +| `<readings>` | Space-separated katakana readings for each subtoken (for example, `トウキョウ スカイツリー`). | +| `<part of speech>` | The IPAdic part of speech tag assigned to the term (for example, `カスタム名詞`). | + +Use the analyzer to test the user dictionary entry: + +```json +POST /kuromoji-user-dict-index/_analyze +{ + "analyzer": "user_dict_analyzer", + "text": "東京スカイツリーに登る" +} +``` + +The user dictionary controls how the text is segmented. Because the rule defines `東京 スカイツリー` as two sub-tokens, the tokenizer emits 東京 and スカイツリー as separate tokens rather than keeping 東京スカイツリー as a single token: + +```json +{ + "tokens": [ + { + "token": "東京", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": "スカイツリー", + "start_offset": 2, + "end_offset": 8, + "type": "word", + "position": 1 + }, + { + "token": "に", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 2 + }, + { + "token": "登る", + "start_offset": 9, + "end_offset": 11, + "type": "word", + "position": 3 + } + ] +} +``` + +To keep 東京スカイツリー as a single token, define it as a single sub-token in the rule: + +```json +"東京スカイツリー,東京スカイツリー,トウキョウスカイツリー,カスタム名詞" +``` + +## 相关文档 + +- [Kuromoji analyzer](/analyzers/language-analyzers/kuromoji) +- [Kuromoji part-of-speech token filter](/analyzers/token-filters/kuromoji-part-of-speech) diff --git a/i18n/zh/analyzers/tokenizers/letter.md b/i18n/zh/analyzers/tokenizers/letter.md new file mode 100644 index 00000000..a437d212 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/letter.md @@ -0,0 +1,92 @@ +--- +title: 字母 +--- + +# Letter tokenizer + +The `letter` tokenizer splits text into words on any non-letter characters. It works well with many European languages but is ineffective with some Asian languages in which words aren't separated by spaces. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `letter` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_letter_analyzer": { + "type": "custom", + "tokenizer": "letter" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_letter_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST _analyze +{ + "tokenizer": "letter", + "text": "Cats 4EVER love chasing butterflies!" +} + +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "Cats", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "EVER", + "start_offset": 6, + "end_offset": 10, + "type": "word", + "position": 1 + }, + { + "token": "love", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 2 + }, + { + "token": "chasing", + "start_offset": 16, + "end_offset": 23, + "type": "word", + "position": 3 + }, + { + "token": "butterflies", + "start_offset": 24, + "end_offset": 35, + "type": "word", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/tokenizers/lowercase.md b/i18n/zh/analyzers/tokenizers/lowercase.md new file mode 100644 index 00000000..6fb9d5f5 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/lowercase.md @@ -0,0 +1,88 @@ +--- +title: 小写 +--- + +# Lowercase tokenizer + +The `lowercase` tokenizer breaks text into terms at white space and then lowercases all the terms. Functionally, this is identical to configuring a `letter` tokenizer with a `lowercase` token filter. However, using a `lowercase` tokenizer is more efficient because the tokenizer actions are performed in a single step. + +## 示例 usage + +The following example request creates a new index named `my-lowercase-index` and configures an analyzer with a `lowercase` tokenizer: + +```json +PUT /my-lowercase-index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_lowercase_tokenizer": { + "type": "lowercase" + } + }, + "analyzer": { + "my_lowercase_analyzer": { + "type": "custom", + "tokenizer": "my_lowercase_tokenizer" + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my-lowercase-index/_analyze +{ + "analyzer": "my_lowercase_analyzer", + "text": "This is a Test. OpenSearch 123!" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "this", + "start_offset": 0, + "end_offset": 4, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 5, + "end_offset": 7, + "type": "word", + "position": 1 + }, + { + "token": "a", + "start_offset": 8, + "end_offset": 9, + "type": "word", + "position": 2 + }, + { + "token": "test", + "start_offset": 10, + "end_offset": 14, + "type": "word", + "position": 3 + }, + { + "token": "opensearch", + "start_offset": 16, + "end_offset": 26, + "type": "word", + "position": 4 + } + ] +} +``` diff --git a/i18n/zh/analyzers/tokenizers/ngram.md b/i18n/zh/analyzers/tokenizers/ngram.md new file mode 100644 index 00000000..627cf7bd --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/ngram.md @@ -0,0 +1,105 @@ +--- +title: N-gram +--- + +# N-gram tokenizer + +The `ngram` tokenizer splits text into overlapping n-grams (sequences of characters) of a specified length. This tokenizer is particularly useful when you want to perform partial word matching or autocomplete search functionality because it generates substrings (character n-grams) of the original input text. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with an `ngram` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_ngram_tokenizer": { + "type": "ngram", + "min_gram": 3, + "max_gram": 4, + "token_chars": ["letter", "digit"] + } + }, + "analyzer": { + "my_ngram_analyzer": { + "type": "custom", + "tokenizer": "my_ngram_tokenizer" + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_ngram_analyzer", + "text": "OpenSearch" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "Sea","start_offset": 0,"end_offset": 3,"type": "word","position": 0}, + {"token": "Sear","start_offset": 0,"end_offset": 4,"type": "word","position": 1}, + {"token": "ear","start_offset": 1,"end_offset": 4,"type": "word","position": 2}, + {"token": "earc","start_offset": 1,"end_offset": 5,"type": "word","position": 3}, + {"token": "arc","start_offset": 2,"end_offset": 5,"type": "word","position": 4}, + {"token": "arch","start_offset": 2,"end_offset": 6,"type": "word","position": 5}, + {"token": "rch","start_offset": 3,"end_offset": 6,"type": "word","position": 6} + ] +} +``` + +## 参数 + +The `ngram` tokenizer can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`min_gram` | 可选 | Integer | The minimum length of the n-grams. Default is `1`. +`max_gram` | 可选 | Integer | The maximum length of the n-grams. Default is `2`. +`token_chars` | 可选 | List of strings | The character classes to be included in tokenization. Valid values are:<br>- `letter`<br>- `digit`<br>- `whitespace`<br>- `punctuation`<br>- `symbol`<br>- `custom` (You must also specify the `custom_token_chars` parameter)<br>Default is an empty list (`[]`), which retains all the characters. +`custom_token_chars` | 可选 | String | Custom characters to be included in the tokens. + +### Maximum difference between `min_gram` and `max_gram` + +The maximum difference between `min_gram` and `max_gram` is configured using the index-level `index.max_ngram_diff` setting and defaults to `1`. + +The following example request creates an index with a custom `index.max_ngram_diff` setting: + +```json +PUT /my-index +{ + "settings": { + "index.max_ngram_diff": 2, + "analysis": { + "tokenizer": { + "my_ngram_tokenizer": { + "type": "ngram", + "min_gram": 3, + "max_gram": 5, + "token_chars": ["letter", "digit"] + } + }, + "analyzer": { + "my_ngram_analyzer": { + "type": "custom", + "tokenizer": "my_ngram_tokenizer" + } + } + } + } +} +``` diff --git a/i18n/zh/analyzers/tokenizers/path-hierarchy.md b/i18n/zh/analyzers/tokenizers/path-hierarchy.md new file mode 100644 index 00000000..bf8a7eff --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/path-hierarchy.md @@ -0,0 +1,174 @@ +--- +title: 路径层次 +--- + +# Path hierarchy tokenizer + +The `path_hierarchy` tokenizer tokenizes file-system-like paths (or similar hierarchical structures) by breaking them down into tokens at each hierarchy level. This tokenizer is particularly useful when working with hierarchical data such as file paths, URLs, or any other delimited paths. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `path_hierarchy` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_path_tokenizer": { + "type": "path_hierarchy" + } + }, + "analyzer": { + "my_path_analyzer": { + "type": "custom", + "tokenizer": "my_path_tokenizer" + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_path_analyzer", + "text": "/users/john/documents/report.txt" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "/users", + "start_offset": 0, + "end_offset": 6, + "type": "word", + "position": 0 + }, + { + "token": "/users/john", + "start_offset": 0, + "end_offset": 11, + "type": "word", + "position": 0 + }, + { + "token": "/users/john/documents", + "start_offset": 0, + "end_offset": 21, + "type": "word", + "position": 0 + }, + { + "token": "/users/john/documents/report.txt", + "start_offset": 0, + "end_offset": 32, + "type": "word", + "position": 0 + } + ] +} +``` + +## 参数 + +The `path_hierarchy` tokenizer can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`delimiter` | 可选 | String | Specifies the character used to separate path components. Default is `/`. +`replacement` | 可选 | String | Configures the character used to replace the delimiter in the tokens. Default is `/`. +`buffer_size` | 可选 | Integer | Specifies the buffer size. Default is `1024`. +`reverse` | 可选 | Boolean | If `true`, generates tokens in reverse order. Default is `false`. +`skip` | 可选 | Integer | Specifies the number of initial tokens (levels) to skip when tokenizing. Default is `0`. + +## 示例 using delimiter and replacement parameters + +The following example request configures custom `delimiter` and `replacement` parameters: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_path_tokenizer": { + "type": "path_hierarchy", + "delimiter": "\\", + "replacement": "\\" + } + }, + "analyzer": { + "my_path_analyzer": { + "type": "custom", + "tokenizer": "my_path_tokenizer" + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_path_analyzer", + "text": "C:\\users\\john\\documents\\report.txt" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "C:", + "start_offset": 0, + "end_offset": 2, + "type": "word", + "position": 0 + }, + { + "token": """C:\users""", + "start_offset": 0, + "end_offset": 8, + "type": "word", + "position": 0 + }, + { + "token": """C:\users\john""", + "start_offset": 0, + "end_offset": 13, + "type": "word", + "position": 0 + }, + { + "token": """C:\users\john\documents""", + "start_offset": 0, + "end_offset": 23, + "type": "word", + "position": 0 + }, + { + "token": """C:\users\john\documents\report.txt""", + "start_offset": 0, + "end_offset": 34, + "type": "word", + "position": 0 + } + ] +} +``` diff --git a/i18n/zh/analyzers/tokenizers/pattern.md b/i18n/zh/analyzers/tokenizers/pattern.md new file mode 100644 index 00000000..68e3cea6 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/pattern.md @@ -0,0 +1,160 @@ +--- +title: 模式 +--- + +# Pattern tokenizer + +The `pattern` tokenizer is a highly flexible tokenizer that allows you to split text into tokens based on a custom Java regular expression. Unlike the `simple_pattern` and `simple_pattern_split` tokenizers, which use Lucene regular expressions, the `pattern` tokenizer can handle more complex and detailed regex patterns, offering greater control over how the text is tokenized. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `pattern` tokenizer. The tokenizer splits text on `-`, `_`, or `.` characters: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "[-_.]" + } + }, + "analyzer": { + "my_pattern_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_pattern_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "OpenSearch-2024_v1.2" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "2024", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 1 + }, + { + "token": "v1", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 2 + }, + { + "token": "2", + "start_offset": 19, + "end_offset": 20, + "type": "word", + "position": 3 + } + ] +} +``` + +## 参数 + +The `pattern` tokenizer can be configured with the following parameters. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`pattern` | 可选 | String | The pattern used to split text into tokens, specified using a [Java regular expression](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). Default is `\W+`. +`flags` | 可选 | String | Configures pipe-separated [flags](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#field.summary) to apply to the regular expression, for example, `"CASE_INSENSITIVE|MULTILINE|DOTALL"`. +`group` | 可选 | Integer | Specifies the capture group to be used as a token. Default is `-1` (split on a match). + +## 示例 using a group parameter + +The following example request configures a `group` parameter that captures only the second group: + +```json +PUT /my_index_group2 +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "pattern", + "pattern": "([a-zA-Z]+)(\\d+)", + "group": 2 + } + }, + "analyzer": { + "my_pattern_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer" + } + } + } + } +} +``` + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index_group2/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "abc123def456ghi" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "123", + "start_offset": 3, + "end_offset": 6, + "type": "word", + "position": 0 + }, + { + "token": "456", + "start_offset": 9, + "end_offset": 12, + "type": "word", + "position": 1 + } + ] +} +``` diff --git a/i18n/zh/analyzers/tokenizers/simple-pattern-split.md b/i18n/zh/analyzers/tokenizers/simple-pattern-split.md new file mode 100644 index 00000000..9db835e4 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/simple-pattern-split.md @@ -0,0 +1,100 @@ +--- +title: 简单模式分割 +--- + +# Simple pattern split tokenizer + +The `simple_pattern_split` tokenizer uses a regular expression to split text into tokens. The regular expression defines the pattern used to determine where to split the text. Any matching pattern in the text is used as a delimiter, and the text between delimiters becomes a token. Use this tokenizer when you want to define delimiters and tokenize the rest of the text based on a pattern. + +The tokenizer uses the matched parts of the input text (based on the regular expression) only as delimiters or boundaries to split the text into terms. The matched portions are not included in the resulting terms. For example, if the tokenizer is configured to split text at dot characters (`.`) and the input text is `one.two.three`, then the generated terms are `one`, `two`, and `three`. The dot characters themselves are not included in the resulting terms. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `simple_pattern_split` tokenizer. The tokenizer is configured to split text on hyphens: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_split_tokenizer": { + "type": "simple_pattern_split", + "pattern": "-" + } + }, + "analyzer": { + "my_pattern_split_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_split_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_pattern_split_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_pattern_split_analyzer", + "text": "OpenSearch-2024-10-09" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "2024", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 1 + }, + { + "token": "10", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 2 + }, + { + "token": "09", + "start_offset": 19, + "end_offset": 21, + "type": "word", + "position": 3 + } + ] +} +``` + +## 参数 + +The `simple_pattern_split` tokenizer can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`pattern` | 可选 | String | The pattern used to split text into tokens, specified using a [Lucene regular expression](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/util/automaton/RegExp.html). Default is an empty string, which returns the input text as one token. diff --git a/i18n/zh/analyzers/tokenizers/simple-pattern.md b/i18n/zh/analyzers/tokenizers/simple-pattern.md new file mode 100644 index 00000000..86f161e2 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/simple-pattern.md @@ -0,0 +1,83 @@ +--- +title: 简单模式 +--- + +# Simple pattern tokenizer + +The `simple_pattern` tokenizer identifies matching sequences in text based on a regular expression and uses those sequences as tokens. It extracts terms that match the regular expression. Use this tokenizer when you want to directly extract specific patterns as terms. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `simple_pattern` tokenizer. The tokenizer extracts numeric terms from text: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "my_pattern_tokenizer": { + "type": "simple_pattern", + "pattern": "\\d+" + } + }, + "analyzer": { + "my_pattern_analyzer": { + "type": "custom", + "tokenizer": "my_pattern_tokenizer" + } + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_pattern_analyzer", + "text": "OpenSearch-2024-10-09" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "2024", + "start_offset": 11, + "end_offset": 15, + "type": "word", + "position": 0 + }, + { + "token": "10", + "start_offset": 16, + "end_offset": 18, + "type": "word", + "position": 1 + }, + { + "token": "09", + "start_offset": 19, + "end_offset": 21, + "type": "word", + "position": 2 + } + ] +} +``` + +## 参数 + +The `simple_pattern` tokenizer can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`pattern` | 可选 | String | The pattern used to split text into tokens, specified using a [Lucene regular expression](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/util/automaton/RegExp.html). Default is an empty string, which returns the input text as one token. diff --git a/i18n/zh/analyzers/tokenizers/standard.md b/i18n/zh/analyzers/tokenizers/standard.md new file mode 100644 index 00000000..75c1e74d --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/standard.md @@ -0,0 +1,124 @@ +--- +title: 标准 +--- + +# Standard tokenizer + +The `standard` tokenizer is the default tokenizer in OpenSearch. It tokenizes text based on word boundaries using a grammar-based approach that recognizes letters, digits, and other characters like punctuation. It is highly versatile and suitable for many languages because it uses Unicode text segmentation rules ([UAX#29](https://unicode.org/reports/tr29/)) to break text into tokens. + +## Tokenization rules + +The `standard` tokenizer follows the word boundary rules defined in [Unicode Standard Annex #29: Unicode Text Segmentation](https://unicode.org/reports/tr29/). The following table summarizes how these rules apply to common input. + +Input | Rule | Tokens +:--- | :--- | :--- +`fast, and scalable.` | Whitespace and most punctuation, such as commas, hyphens, slashes, `+`, `#`, `%`, and `@`, split text and are removed. | `fast`, `and`, `scalable` +`can't`, `O'Neil` | An apostrophe between two letters does not split the word. | `can't`, `O'Neil` +`end. Next` | A period followed by a space splits the text. | `end`, `Next` +`hello.world`, `U.S.A.` | A period between two letters does not split the word. A trailing period is removed. | `hello.world`, `U.S.A` +`3.5`, `1,000`, `v1.2.3` | A period or comma between two digits does not split the number. | `3.5`, `1,000`, `v1.2.3` +`snake_case` | Underscores do not split words. | `snake_case` +`state-of-the-art` | Hyphens split words. | `state`, `of`, `the`, `art` +`admin@example.com` | Email addresses are split at the `@` sign. | `admin`, `example.com` +`https://opensearch.org/docs` | URLs are split at the colon and slashes. | `https`, `opensearch.org`, `docs` +`東京`, `こんにちは` | Each ideographic and hiragana character becomes a separate token. | `東`, `京`, `こ`, `ん`, `に`, `ち`, `は` + +To keep email addresses and URLs as single tokens, use the [`uax_url_email` tokenizer](/analyzers/tokenizers/uax-url-email). Tokens longer than `max_token_length` are split at that length. For more information, see [Parameters](#parameters). + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `standard` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "analyzer": { + "my_standard_analyzer": { + "type": "standard" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_standard_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_standard_analyzer", + "text": "OpenSearch is powerful, fast, and scalable." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "opensearch", + "start_offset": 0, + "end_offset": 10, + "type": "<ALPHANUM>", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "<ALPHANUM>", + "position": 1 + }, + { + "token": "powerful", + "start_offset": 14, + "end_offset": 22, + "type": "<ALPHANUM>", + "position": 2 + }, + { + "token": "fast", + "start_offset": 24, + "end_offset": 28, + "type": "<ALPHANUM>", + "position": 3 + }, + { + "token": "and", + "start_offset": 30, + "end_offset": 33, + "type": "<ALPHANUM>", + "position": 4 + }, + { + "token": "scalable", + "start_offset": 34, + "end_offset": 42, + "type": "<ALPHANUM>", + "position": 5 + } + ] +} +``` + +## 参数 + +The `standard` tokenizer can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`max_token_length` | 可选 | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. diff --git a/i18n/zh/analyzers/tokenizers/thai.md b/i18n/zh/analyzers/tokenizers/thai.md new file mode 100644 index 00000000..4feb7ef9 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/thai.md @@ -0,0 +1,103 @@ +--- +title: 泰语 +--- + +# Thai tokenizer + +The `thai` tokenizer tokenizes Thai language text. Because words in Thai language are not separated by spaces, the tokenizer must identify word boundaries based on language-specific rules. + +## 示例 usage + +The following example request creates a new index named `thai_index` and configures an analyzer with a `thai` tokenizer: + +```json +PUT /thai_index +{ + "settings": { + "analysis": { + "tokenizer": { + "thai_tokenizer": { + "type": "thai" + } + }, + "analyzer": { + "thai_analyzer": { + "type": "custom", + "tokenizer": "thai_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "thai_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /thai_index/_analyze +{ + "analyzer": "thai_analyzer", + "text": "ฉันชอบไปเที่ยวที่เชียงใหม่" +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "ฉัน", + "start_offset": 0, + "end_offset": 3, + "type": "word", + "position": 0 + }, + { + "token": "ชอบ", + "start_offset": 3, + "end_offset": 6, + "type": "word", + "position": 1 + }, + { + "token": "ไป", + "start_offset": 6, + "end_offset": 8, + "type": "word", + "position": 2 + }, + { + "token": "เที่ยว", + "start_offset": 8, + "end_offset": 14, + "type": "word", + "position": 3 + }, + { + "token": "ที่", + "start_offset": 14, + "end_offset": 17, + "type": "word", + "position": 4 + }, + { + "token": "เชียงใหม่", + "start_offset": 17, + "end_offset": 26, + "type": "word", + "position": 5 + } + ] +} +``` diff --git a/i18n/zh/analyzers/tokenizers/uax-url-email.md b/i18n/zh/analyzers/tokenizers/uax-url-email.md new file mode 100644 index 00000000..02b885c3 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/uax-url-email.md @@ -0,0 +1,78 @@ +--- +title: UAX URL 邮箱 +--- + +# UAX URL email tokenizer + +In addition to regular text, the `uax_url_email` tokenizer is designed to handle URLs, email addresses, and domain names. It is based on the Unicode Text Segmentation algorithm ([UAX #29](https://www.unicode.org/reports/tr29/)), which allows it to correctly tokenize complex text, including URLs and email addresses. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `uax_url_email` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "uax_url_email_tokenizer": { + "type": "uax_url_email" + } + }, + "analyzer": { + "my_uax_analyzer": { + "type": "custom", + "tokenizer": "uax_url_email_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_uax_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_uax_analyzer", + "text": "Contact us at support@example.com or visit https://example.com for details." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + {"token": "Contact","start_offset": 0,"end_offset": 7,"type": "<ALPHANUM>","position": 0}, + {"token": "us","start_offset": 8,"end_offset": 10,"type": "<ALPHANUM>","position": 1}, + {"token": "at","start_offset": 11,"end_offset": 13,"type": "<ALPHANUM>","position": 2}, + {"token": "support@example.com","start_offset": 14,"end_offset": 33,"type": "<EMAIL>","position": 3}, + {"token": "or","start_offset": 34,"end_offset": 36,"type": "<ALPHANUM>","position": 4}, + {"token": "visit","start_offset": 37,"end_offset": 42,"type": "<ALPHANUM>","position": 5}, + {"token": "https://example.com","start_offset": 43,"end_offset": 62,"type": "<URL>","position": 6}, + {"token": "for","start_offset": 63,"end_offset": 66,"type": "<ALPHANUM>","position": 7}, + {"token": "details","start_offset": 67,"end_offset": 74,"type": "<ALPHANUM>","position": 8} + ] +} +``` + +## 参数 + +The `uax_url_email` tokenizer can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`max_token_length` | 可选 | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. diff --git a/i18n/zh/analyzers/tokenizers/whitespace.md b/i18n/zh/analyzers/tokenizers/whitespace.md new file mode 100644 index 00000000..bd438498 --- /dev/null +++ b/i18n/zh/analyzers/tokenizers/whitespace.md @@ -0,0 +1,104 @@ +--- +title: White space +--- + +# White space tokenizer + +The `whitespace` tokenizer splits text on white space characters, such as spaces, tabs, and new lines. It treats each word separated by white space as a token and does not perform any additional analysis or normalization like lowercasing or punctuation removal. + +## 示例 usage + +The following example request creates a new index named `my_index` and configures an analyzer with a `whitespace` tokenizer: + +```json +PUT /my_index +{ + "settings": { + "analysis": { + "tokenizer": { + "whitespace_tokenizer": { + "type": "whitespace" + } + }, + "analyzer": { + "my_whitespace_analyzer": { + "type": "custom", + "tokenizer": "whitespace_tokenizer" + } + } + } + }, + "mappings": { + "properties": { + "content": { + "type": "text", + "analyzer": "my_whitespace_analyzer" + } + } + } +} +``` + +## 生成的词元 + +使用以下请求检查使用该分析器生成的词元: + +```json +POST /my_index/_analyze +{ + "analyzer": "my_whitespace_analyzer", + "text": "OpenSearch is fast! Really fast." +} +``` + +响应包含 the generated tokens: + +```json +{ + "tokens": [ + { + "token": "OpenSearch", + "start_offset": 0, + "end_offset": 10, + "type": "word", + "position": 0 + }, + { + "token": "is", + "start_offset": 11, + "end_offset": 13, + "type": "word", + "position": 1 + }, + { + "token": "fast!", + "start_offset": 14, + "end_offset": 19, + "type": "word", + "position": 2 + }, + { + "token": "Really", + "start_offset": 20, + "end_offset": 26, + "type": "word", + "position": 3 + }, + { + "token": "fast.", + "start_offset": 27, + "end_offset": 32, + "type": "word", + "position": 4 + } + ] +} +``` + +## 参数 + +The `whitespace` tokenizer can be configured with the following parameter. + +Parameter | 是否必需 | 数据类型 | Description +:--- | :--- | :--- | :--- +`max_token_length` | 可选 | Integer | Sets the maximum length of the produced token. If this length is exceeded, the token is split into multiple tokens at the length configured in `max_token_length`. Default is `255`. diff --git a/i18n/zh/api-reference/alias/alias-exists.md b/i18n/zh/api-reference/alias/alias-exists.md new file mode 100644 index 00000000..7d4cc6ea --- /dev/null +++ b/i18n/zh/api-reference/alias/alias-exists.md @@ -0,0 +1,66 @@ +--- +title: 别名是否存在 +--- + +# 索引别名是否存在 API +<Badge type="tip" text="1.0 版本引入" /> + +检查别名是否存在。 + +## 端点 + +```json +HEAD /_alias/{alias} +HEAD /{index}/_alias/{alias} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `<alias>` | String | 要检查的别名名称的逗号分隔列表或通配符表达式。 | +| `<index>` | String | 用于限制请求的索引名称的逗号分隔列表或通配符表达式。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `expand_wildcards` | String | 通配符表达式可以匹配的索引类型。支持逗号分隔的值。有效值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认值为 `all`。 | +| `ignore_unavailable` | Boolean | 是否忽略不可用的索引。默认值为 `false`。 | +| `local` | Boolean | 是否仅从本地节点返回信息,而不是从集群管理器节点返回。默认值为 `false`。 | + +## 响应代码 + +API 返回以下响应代码之一。 + +| 响应代码 | 描述 | +| :--- | :--- | +| `200` | 表示所有指定的别名都存在。 | +| `404` | 表示一个或多个指定的别名不存在。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: HEAD /_alias/2030 +--> + +HEAD /_alias/2030 + +response = client.indices.exists_alias( + name = "2030" +) + +<!-- spec_insert_end --> + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/aliases/get`。 + +## 相关文档 + +有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 diff --git a/i18n/zh/api-reference/alias/aliases-api.md b/i18n/zh/api-reference/alias/aliases-api.md new file mode 100644 index 00000000..2b8a3ac3 --- /dev/null +++ b/i18n/zh/api-reference/alias/aliases-api.md @@ -0,0 +1,489 @@ +--- +title: 管理别名 +--- + +# 管理别名 API +<Badge type="tip" text="1.0 版本引入" /> + +管理别名 API 在单个原子事务中执行多个索引别名操作。当您需要添加或删除多个别名、将别名从一个索引切换到另一个索引,或在管理别名的同时删除索引时,请使用此 API。此 API 接受操作数组,非常适合必须以原子方式执行的复杂别名操作。 + +此 API 与[创建或更新别名 API](/api-reference/alias/create-alias) 不同,后者一次操作单个别名并使用不同的请求参数。对于涉及多个别名或索引的批量操作和原子事务,请使用管理别名 API。 + +有关索引别名的概念信息(包括用例和示例),请参阅[索引别名](/im-plugin/index-alias)。 + +## 端点 + +```json +POST _aliases +``` + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`cluster_manager_timeout` | Time | 等待集群管理器节点响应的时间。默认值为 `30s`。 +`timeout` | Time | 等待集群响应的时间。默认值为 `30s`。 + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 描述 | 必需 +:--- | :--- | :--- | :--- +`actions` | Array | 您想要在索引上执行的操作集。有效选项为:`add`、`remove` 和 `remove_index`。数组中必须至少有一个操作。 | 是 +`add` | N/A | 向指定索引添加别名。 | 否 +`remove` | N/A | 从指定索引删除别名。 | 否 +`remove_index` | N/A | 删除索引。 | 否 +`index` | String | 您想要与别名关联的索引名称。支持通配符表达式。 | 如果您在请求体中不提供 `indices` 字段,则为必需。 +`indices` | Array | 您想要与别名关联的索引名称数组。 | 如果您在请求体中不提供 `index` 字段,则为必需。 +`alias` | String | 别名的名称。 | 如果您在请求体中不提供 `aliases` 字段,则为必需。 +`aliases` | Array | 别名名称数组。 | 如果您在请求体中不提供 `alias` 字段,则为必需。 +`filter` | Object | 要与别名一起使用的过滤器,使别名指向索引的过滤部分。 | 否 +`is_hidden` | Boolean | 指定别名是否应从包含通配符表达式的结果中隐藏 | 否 +`must_exist` | Boolean | 指定要删除的别名是否必须存在。 | 否 +`is_write_index` | Boolean | 指定索引是否应为写入索引。别名一次只能有一个写入索引。如果将写入请求提交到链接到多个索引的别名,OpenSearch 仅在写入索引上执行该请求。**重要提示**:未明确为索引设置 `is_write_index: true` 且仅引用一个索引的别名将使该索引作为写入索引,直到引用另一个索引。此时,将没有写入索引,写入将被拒绝。 | 否 +`routing` | String | 用于将自定义值分配给特定操作的分片。 | 否 +`index_routing` | String | 仅为索引操作将自定义值分配给分片。 | 否 +`search_routing` | String | 仅为搜索操作将自定义值分配给分片。 | 否 + +## 示例:添加别名 + +以下请求创建一个名为 `logs_current` 的别名,指向 `application_logs_2024` 索引: + +<!-- spec_insert_start +component: example_code +rest: POST /_aliases +body: | +{ + "actions": [ + { + "add": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] +} +--> + +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] +} + +response = client.indices.update_aliases( + body = { + "actions": [ + { + "add": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] + } +) + +<!-- spec_insert_end --> + +## 示例:删除别名 + +以下请求从 `application_logs_2024` 索引中删除 `logs_current` 别名: + +<!-- spec_insert_start +component: example_code +rest: POST /_aliases +body: | +{ + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] +} +--> + +POST /_aliases +{ + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] +} + +response = client.indices.update_aliases( + body = { + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current" + } + } + ] + } +) + +<!-- spec_insert_end --> + +## 示例:重命名别名 + +您可以通过在同一请求中从一个索引删除别名并将其添加到另一个索引来原子地重命名别名。以下示例将 `primary_data` 别名从 `dataset_v1` 移动到 `dataset_v2`: + +```json +POST /_aliases +{ + "actions": [ + { + "remove": { + "index": "dataset_v1", + "alias": "primary_data" + } + }, + { + "add": { + "index": "dataset_v2", + "alias": "primary_data" + } + } + ] +} +``` + +::: warning IMPORTANT +别名操作是原子的,这意味着 `primary_data` 不会同时指向两个索引或不指向任何索引。 +::: + +## 示例:向多个索引添加别名 + +您可以使用单独的 `add` 操作将单个别名与多个索引关联: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "products_electronics", + "alias": "all_products" + } + }, + { + "add": { + "index": "products_clothing", + "alias": "all_products" + } + }, + { + "add": { + "index": "products_books", + "alias": "all_products" + } + } + ] +} +``` + +<!-- vale off --> +## 示例:使用 indices 数组 +<!-- vale on --> + +或者,您可以使用 `indices` 数组在单个操作中指定多个索引: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "indices": ["products_electronics", "products_clothing", "products_books"], + "alias": "all_products" + } + } + ] +} +``` + +## 示例:使用通配符模式 + +您可以使用通配符模式添加与命名模式匹配的多个索引。以下示例为所有以 `sales_2024` 开头的索引创建别名: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "sales_2024_*", + "alias": "current_year_sales" + } + } + ] +} +``` + +::: info NOTE +这将创建一个时间点别名,该别名包含创建时与模式匹配的所有索引。它不会自动包含稍后创建的与模式匹配的新索引。 +::: + +::: warning IMPORTANT +写入指向多个索引的别名是错误的,除非您指定写入索引。 +::: + +## 示例:索引交换 + +您可以原子地用新索引替换索引而无需停机。这对于重新索引操作很有用: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "customer_data_new", + "alias": "customer_data" + } + }, + { + "remove_index": { + "index": "customer_data_old" + } + } + ] +} +``` + +此操作在单个原子操作中将新索引添加到别名并删除旧索引。 + +## 示例:过滤别名 + +过滤别名使您能够通过应用查询过滤器来分割索引中的数据。这允许您创建可通过单独的别名名称访问的数据的集中子集。首先,确保您的索引具有必要的字段映射: + +```json +PUT /user_activity +{ + "mappings": { + "properties": { + "user_type": { + "type": "keyword" + }, + "timestamp": { + "type": "date" + }, + "action": { + "type": "keyword" + } + } + } +} +``` + +然后创建过滤别名以分割您的数据: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "user_activity", + "alias": "premium_users", + "filter": { + "term": { + "user_type": "premium" + } + } + } + }, + { + "add": { + "index": "user_activity", + "alias": "recent_activity", + "filter": { + "range": { + "timestamp": { + "gte": "now-7d" + } + } + } + } + } + ] +} +``` + +这些别名会自动将指定的过滤器应用于所有搜索、计数和按查询删除操作。 + +## 示例:基本路由 + +路由允许您将操作定向到特定分片,通过减少需要查询的分片数量来提高性能。 + +以下示例创建一个具有路由值的别名: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "customer_orders", + "alias": "region_east_orders", + "routing": "east" + } + } + ] +} +``` + +## 示例:为索引和搜索操作分别设置路由 + +您可以为索引和搜索指定不同的路由值: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "user_sessions", + "alias": "mobile_sessions", + "index_routing": "mobile", + "search_routing": "mobile,tablet" + } + } + ] +} +``` + +在此示例中,通过别名索引的所有文档都将进入"mobile"分片,但搜索可以查询"mobile"和"tablet"分片。 + +::: info NOTE +当您使用别名路由和路由参数执行搜索时,OpenSearch 使用两个值的交集。例如,如果您搜索 `GET /mobile_sessions/_search?routing=tablet,mobile`,则只会使用"mobile"路由值,因为它是别名路由(`mobile,tablet`)和搜索参数(`tablet,mobile`)的交集。 +::: + +## 示例:设置写入索引 + +当别名指向多个索引时,您必须指定哪个索引应处理写入操作。 + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "logs_2024_01", + "alias": "active_logs", + "is_write_index": true + } + }, + { + "add": { + "index": "logs_2024_02", + "alias": "active_logs", + "is_write_index": false + } + } + ] +} +``` + +现在您可以写入别名,所有写入操作都将进入 `logs_2024_01`: + +```json +POST /active_logs/_doc +{ + "timestamp": "2024-01-15T10:30:00", + "level": "INFO", + "message": "Application started successfully" +} +``` + +## 示例:切换写入索引 + +您可以原子地切换哪个索引充当写入索引: + +```json +POST /_aliases +{ + "actions": [ + { + "add": { + "index": "logs_2024_01", + "alias": "active_logs", + "is_write_index": false + } + }, + { + "add": { + "index": "logs_2024_02", + "alias": "active_logs", + "is_write_index": true + } + } + ] +} +``` + +::: warning IMPORTANT +> 在使用写入索引时,请记住以下重要注意事项: +> - 别名一次只能有一个写入索引。 +> - 如果别名指向多个索引而没有指定的写入索引,写入操作将被拒绝。 +> - 对于指向单个索引的别名,该索引会自动充当写入索引。 +::: + +## 示例:使用 must_exist 参数 + +OpenSearch 为删除操作提供了 `must_exist` 参数,该参数控制删除不存在的别名时的错误处理: + +```json +POST /_aliases +{ + "actions": [ + { + "remove": { + "index": "application_logs_2024", + "alias": "logs_current", + "must_exist": true + } + } + ] +} +``` + +- `must_exist: true` - 如果别名不存在,则抛出错误 +- `must_exist: false` - 即使别名不存在也会静默成功 +- `must_exist: null`(默认)- 仅当所有指定的别名都不存在时才抛出错误 + +## 示例响应 + +所有成功的别名操作都返回相同的响应格式: + +```json +{ + "acknowledged": true +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/aliases/get`。 + +## 相关文档 + +有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 diff --git a/i18n/zh/api-reference/alias/create-alias.md b/i18n/zh/api-reference/alias/create-alias.md new file mode 100644 index 00000000..f839ed67 --- /dev/null +++ b/i18n/zh/api-reference/alias/create-alias.md @@ -0,0 +1,274 @@ +--- +title: 创建或更新别名 +--- + +# 创建或更新索引别名 API +<Badge type="tip" text="1.0 版本引入" /> + +创建或更新别名 API 将一个或多个索引添加到索引别名或更新现有别名的设置。有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 + +::: info NOTE +创建或更新别名 API 与[管理别名 API](/api-reference/alias/aliases-api) 不同,后者支持添加和删除别名以及删除索引及其别名。相比之下,以下 API 仅支持添加或更新别名而不更新索引本身。每个 API 还使用不同的请求体参数。 +::: + +## 端点 + +```json +POST /{target}/_alias/{alias-name} +PUT /{target}/_alias/{alias-name} +POST /_alias/{alias-name} +PUT /_alias/{alias-name} +POST /{target}/_aliases/{alias-name} +PUT /{target}/_aliases/{alias-name} +POST /_aliases/{alias-name} +PUT /_aliases/{alias-name} +PUT /{target}/_alias +PUT /{target}/_aliases +PUT /_alias +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 类型 | 描述 | +:--- | :--- | :--- +| `target` | String | 以逗号分隔的索引列表。支持通配符表达式(`*`)。要定位集群中的所有索引,请使用 `_all` 或 `*`。可选。 | +| `alias-name` | String | 要创建或更新的别名名称。可选。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`cluster_manager_timeout` | Time | 等待集群管理器节点响应的时间。默认值为 `30s`。 +`timeout` | Time | 等待集群响应的时间。默认值为 `30s`。 + +## 请求体 + +下表列出了可用的请求体字段。 + +字段 | 类型 | 描述 +:--- | :--- | :--- | :--- +`index` | String | 您想要与别名关联的索引的逗号分隔列表。如果设置了此字段,它将覆盖 URL 路径中指定的索引名称。 +`alias` | String | 别名的名称。如果设置了此字段,它将覆盖 URL 路径中指定的别名名称。 +`is_write_index` | Boolean | 指定索引是否应为写入索引。别名一次只能有一个写入索引。如果将写入请求提交到链接到多个索引的别名,则 OpenSearch 仅在写入索引上运行该请求。 +`routing` | String | 为特定操作的分片分配自定义值。 +`index_routing` | String | 仅为索引操作的分片分配自定义值。 +`search_routing` | String | 仅为搜索操作的分片分配自定义值。 +`filter` | Object | 要与别名一起使用的过滤器,使别名指向索引的过滤部分。 + +## 示例请求:添加简单别名 + +以下请求为索引创建基本别名: + +<!-- spec_insert_start +component: example_code +rest: PUT /products-2024/_alias/current-products +--> + +PUT /products-2024/_alias/current-products + +response = client.indices.put_alias( + name = "current-products", + index = "products-2024" +) + +<!-- spec_insert_end --> + +## 示例请求:添加基于时间的别名 + +以下请求为 `sales-q1-2024` 索引创建别名 `quarterly-2024`: + +<!-- spec_insert_start +component: example_code +rest: PUT /sales-q1-2024/_alias/quarterly-2024 +--> + +PUT /sales-q1-2024/_alias/quarterly-2024 + +response = client.indices.put_alias( + name = "quarterly-2024", + index = "sales-q1-2024" +) + +<!-- spec_insert_end --> + +## 示例请求:添加带有路由的过滤别名 + +首先,创建具有适当映射的索引: + +<!-- spec_insert_start +component: example_code +rest: PUT /customer-data +body: | +{ + "mappings" : { + "properties" : { + "customer_id" : {"type" : "integer"}, + "region" : {"type" : "keyword"} + } + } +} +--> + +PUT /customer-data +{ + "mappings": { + "properties": { + "customer_id": { + "type": "integer" + }, + "region": { + "type": "keyword" + } + } + } +} + +response = client.indices.create( + index = "customer-data", + body = { + "mappings": { + "properties": { + "customer_id": { + "type": "integer" + }, + "region": { + "type": "keyword" + } + } + } + } +) + +<!-- spec_insert_end --> + +然后为特定客户添加带有路由和过滤的索引别名: + +<!-- spec_insert_start +component: example_code +rest: PUT /customer-data/_alias/customer-123 +body: | +{ + "routing" : "west", + "filter" : { + "term" : { + "customer_id" : 123 + } + } +} +--> + +PUT /customer-data/_alias/customer-123 +{ + "routing": "west", + "filter": { + "term": { + "customer_id": 123 + } + } +} + +response = client.indices.put_alias( + name = "customer-123", + index = "customer-data", + body = { + "routing": "west", + "filter": { + "term": { + "customer_id": 123 + } + } + } +) + +<!-- spec_insert_end --> + +## 示例请求:在索引创建期间添加别名 + +您可以在使用创建索引 API 创建索引时添加别名: + +<!-- spec_insert_start +component: example_code +rest: PUT /inventory-2024 +body: | +{ + "mappings" : { + "properties" : { + "category" : {"type" : "keyword"} + } + }, + "aliases" : { + "current-inventory" : {}, + "electronics" : { + "filter" : { + "term" : {"category" : "electronics" } + } + } + } +} +--> + +PUT /inventory-2024 +{ + "mappings": { + "properties": { + "category": { + "type": "keyword" + } + } + }, + "aliases": { + "current-inventory": {}, + "electronics": { + "filter": { + "term": { + "category": "electronics" + } + } + } + } +} + +response = client.indices.create( + index = "inventory-2024", + body = { + "mappings": { + "properties": { + "category": { + "type": "keyword" + } + } + }, + "aliases": { + "current-inventory": {}, + "electronics": { + "filter": { + "term": { + "category": "electronics" + } + } + } + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/aliases`。 + +## 相关文档 + +有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 diff --git a/i18n/zh/api-reference/alias/delete-alias.md b/i18n/zh/api-reference/alias/delete-alias.md new file mode 100644 index 00000000..7858e2e3 --- /dev/null +++ b/i18n/zh/api-reference/alias/delete-alias.md @@ -0,0 +1,75 @@ +--- +title: 删除别名 +--- + +# 删除索引别名 API +<Badge type="tip" text="1.0 版本引入" /> + +删除现有别名。 + +## 端点 + +```json +DELETE /{index}/_alias/{alias} +DELETE /{index}/_aliases/{alias} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `<index>` | String | 用于限制请求的索引名称的逗号分隔列表或通配符表达式。要包含集群中的所有索引,请使用 `_all` 或 `*`。 | +| `<alias>` | String | 要删除的别名名称的逗号分隔列表或通配符表达式。要删除所有别名,请使用 `_all` 或 `*`。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time | 等待集群管理器节点响应的时间。默认值为 `30s`。 | +| `timeout` | Time | 等待集群响应的时间。默认值为 `30s`。 | + +## 示例请求 + +以下请求从 `logs_20302801` 索引中删除 `alias1` 别名: + +<!-- spec_insert_start +component: example_code +rest: DELETE /logs_20302801/_alias/alias1 +--> + +DELETE /logs_20302801/_alias/alias1 + +response = client.indices.delete_alias( + index = "logs_20302801", + name = "alias1" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | 是否收到请求。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/aliases`。 + +## 相关文档 + +有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 diff --git a/i18n/zh/api-reference/alias/get-alias.md b/i18n/zh/api-reference/alias/get-alias.md new file mode 100644 index 00000000..5fa95abd --- /dev/null +++ b/i18n/zh/api-reference/alias/get-alias.md @@ -0,0 +1,185 @@ +--- +title: 获取别名 +--- + +# 获取索引别名 API +<Badge type="tip" text="1.0 版本引入" /> + +返回有关一个或多个别名的信息。 + +## 端点 + +```json +GET /_alias +GET /_alias/{alias} +GET /{index}/_alias/{alias} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `<alias>` | String | 要检索的别名名称的逗号分隔列表或通配符表达式。要检索所有索引别名的信息,请使用 `_all` 或 `*`。 | +| `<index>` | String | 用于限制请求的索引名称的逗号分隔列表或通配符表达式。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `allow_no_indices` | Boolean | 是否忽略与任何索引都不匹配的通配符。默认值为 `true`。 | +| `expand_wildcards` | String | 通配符表达式可以匹配的索引类型。支持逗号分隔的值。有效值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认值为 `all`。 | +| `ignore_unavailable` | Boolean | 是否忽略不可用的索引。默认值为 `false`。 | +| `local` | Boolean | 是否仅从本地节点返回信息,而不是从集群管理器节点返回。默认值为 `false`。 | + +## 示例请求:获取索引的所有别名 + +您可以在索引创建期间使用创建索引 API 请求添加索引别名。 + +以下创建索引 API 请求创建 `logs_20302801` 索引,并带有两个别名: + +- `current_day` +- `2030`,它仅返回 `logs_20302801` 索引中 `year` 字段值为 `2030` 的文档 + +<!-- spec_insert_start +component: example_code +rest: PUT /logs_20302801 +body: | +{ + "aliases" : { + "current_day" : {}, + "2030" : { + "filter" : { + "term" : {"year" : 2030 } + } + } + } +} +--> + +PUT /logs_20302801 +{ + "aliases": { + "current_day": {}, + "2030": { + "filter": { + "term": { + "year": 2030 + } + } + } + } +} + +response = client.indices.create( + index = "logs_20302801", + body = { + "aliases": { + "current_day": {}, + "2030": { + "filter": { + "term": { + "year": 2030 + } + } + } + } + } +) + +<!-- spec_insert_end --> + +以下获取索引别名 API 请求返回索引 `logs_20302801` 的所有别名: + +<!-- spec_insert_start +component: example_code +rest: GET /logs_20302801/_alias/* +--> + +GET /logs_20302801/_alias/* + +response = client.indices.get_alias( + name = "*", + index = "logs_20302801" +) + +<!-- spec_insert_end --> + +## 示例请求:获取特定别名 + +以下索引别名 API 请求返回 `2030` 别名: + +<!-- spec_insert_start +component: example_code +rest: GET /_alias/2030 +--> + +GET /_alias/2030 + +response = client.indices.get_alias( + name = "2030" +) + +<!-- spec_insert_end --> + +## 示例请求:基于通配符获取别名 + +以下索引别名 API 请求返回以 `20` 开头的任何别名: + +<!-- spec_insert_start +component: example_code +rest: GET /_alias/20* +--> + +GET /_alias/20* + +response = client.indices.get_alias( + name = "20*" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "logs_20302801" : { + "aliases" : { + "current_day" : { + }, + "2030" : { + "filter" : { + "term" : { + "year" : 2030 + } + } + } + } + } +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `<index>` | Object | 包含索引的别名。 | +| `<index>.aliases` | Object | 包含索引的别名信息。 | +| `<index>.aliases.<alias>` | Object | 包含别名的配置。 | +| `<index>.aliases.<alias>.filter` | Object | 用于限制别名可以访问的文档的查询。 | +| `<index>.aliases.<alias>.index_routing` | String | 用于索引操作的路由值。 | +| `<index>.aliases.<alias>.search_routing` | String | 用于搜索操作的路由值。 | +| `<index>.aliases.<alias>.is_write_index` | Boolean | 该索引是否是别名的写入索引。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/aliases/get`。 + +## 相关文档 + +有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 diff --git a/i18n/zh/api-reference/alias/index.md b/i18n/zh/api-reference/alias/index.md new file mode 100644 index 00000000..94b7951d --- /dev/null +++ b/i18n/zh/api-reference/alias/index.md @@ -0,0 +1,26 @@ +--- +title: 别名 API +--- + +# 别名 API + +OpenSearch 索引别名 API 允许您创建、更新、删除和检索有关别名的信息。 + +有关索引别名的概念信息(包括用例和示例),请参阅[索引别名](/im-plugin/index-alias)。 + +## 可用 API + +OpenSearch 支持以下索引别名 API。 + +| API | 描述 | +|-----|-------------| +| [管理别名](/api-reference/alias/aliases-api) | 添加或删除别名。 | +| [创建或更新别名](/api-reference/alias/create-alias) | 创建或更新别名。 | +| [获取索引别名](/api-reference/alias/get-alias) | 返回有关一个或多个别名的信息。 | +| [删除索引别名](/api-reference/alias/delete-alias) | 删除现有别名。 | +| [索引别名是否存在](/api-reference/alias/alias-exists) | 检查别名是否存在。 | +| [CAT 别名](/api-reference/cat/cat-aliases) | 以表格格式列出别名及其路由和过滤信息。 | + +## 相关文档 + +有关索引别名的更多信息,请参阅[索引别名](/im-plugin/index-alias)。 diff --git a/i18n/zh/api-reference/cat/cat-pit-segments.md b/i18n/zh/api-reference/cat/cat-pit-segments.md new file mode 100644 index 00000000..4c399585 --- /dev/null +++ b/i18n/zh/api-reference/cat/cat-pit-segments.md @@ -0,0 +1,117 @@ +--- +title: CAT PIT 分段 +--- + +# CAT Pit Segments API +<Badge type="tip" text="2.4 版本引入" /> + +CAT 时间点(Point in Time,PIT)分段操作通过描述其 Lucene 分段来提供有关 PIT 磁盘利用率的低级信息。PIT Segments API 支持通过 ID 列出特定 PIT 的分段信息,或一次列出所有 PIT 的分段信息。 + +## 端点 + +<!-- spec_insert_start +api: cat.pit_segments +component: endpoints +omit_header: true +--> +```json +GET /_cat/pit_segments +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: cat.all_pit_segments +component: endpoints +omit_header: true +--> +```json +GET /_cat/pit_segments/_all +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: cat.pit_segments +component: query_parameters +columns: Parameter, Data type, Description, Default +include_deprecated: false +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `bytes` | String | 用于显示字节值的单位。<br> 有效值为:`b`、`kb`、`k`、`mb`、`m`、`gb`、`g`、`tb`、`t`、`pb` 和 `p`。 | N/A | +| `format` | String | `Accept` 头的简短版本,例如 `json` 或 `yaml`。<br> 有效值为:`cbor`、`json`、`smile`、`text` 和 `yaml`。 | `text` | +| `h` | List | 要显示的列名的逗号分隔列表。 | N/A | +| `help` | Boolean | 返回帮助信息。 | `false` | +| `limit` | Integer | 返回的最大行数。必须大于 0。在排序(`s`)之后应用。 | N/A | +| `s` | List | 用于排序的列名或列别名的逗号分隔列表。 | N/A | +| `v` | Boolean | 启用详细模式,显示列标题。 | `false` | + +<!-- spec_insert_end --> + +## 请求正文字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`pit_id` | [Base64 编码的二进制](/field-types/supported-field-types/binary)或二进制数组 | 要列出其分段的 PIT 的 PIT ID。必需。 + +## 示例请求:所有 PIT 的 PIT 分段 + +<!-- spec_insert_start +component: example_code +rest: GET /_cat/pit_segments/_all +--> + +GET /_cat/pit_segments/_all + +response = client.cat.all_pit_segments() + +<!-- spec_insert_end --> + +如果没有分段(没有存储的数据),API 不会返回任何信息。 + +## 示例请求:通过 ID 列出 PIT 的 PIT 分段 + +要列出一个或多个 PIT 的分段,请在请求正文中指定它们的 PIT ID: + +<!-- spec_insert_start +component: example_code +rest: GET /_cat/pit_segments +body: | +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} +--> + +GET /_cat/pit_segments +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} + +response = client.cat.pit_segments( + body = { + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +```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 +``` diff --git a/i18n/zh/api-reference/cluster-api/cluster-pending-tasks.md b/i18n/zh/api-reference/cluster-api/cluster-pending-tasks.md new file mode 100644 index 00000000..a7cbe7ea --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/cluster-pending-tasks.md @@ -0,0 +1,87 @@ +--- +title: 集群待处理任务 +--- + +# Cluster Pending Tasks API +<Badge type="tip" text="1.0 版本引入" /> + +`/_cluster/pending_tasks` API 返回尚未执行的集群级更改列表。这些待处理任务通常是排队的操作,例如创建索引、更新模板、分片分配更改和其他集群状态更新。 + +此 API 对于监控集群状态和诊断集群状态更新延迟非常有用,尤其是在任务积压或卡住时。 + +## 端点 + +```json +GET /_cluster/pending_tasks +``` + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------- | +| `local` | Boolean | 是否仅从本地节点返回信息,而不是从选定的集群管理节点返回。默认为 `false`。 | +| `cluster_manager_timeout` | Time | 指定连接到集群管理节点的超时时间。默认为 `30s`。 | + +## 示例请求 + +以下请求返回当前待处理的集群状态更新任务列表: + +<!-- spec_insert_start +component: example_code +rest: GET /_cluster/pending_tasks +--> + +GET /_cluster/pending_tasks + +response = client.cluster.pending_tasks() + +<!-- spec_insert_end --> + +### 示例响应 + +```json +{ + "tasks": [ + { + "insert_order": 1234, + "priority": "HIGH", + "source": "create-index [logs-2025.07.15]", + "executing": false, + "time_in_queue_millis": 28, + "time_in_queue": "28ms" + }, + { + "insert_order": 1235, + "priority": "URGENT", + "source": "shard-started shard id [logs-2025.07.15][0]", + "executing": true, + "time_in_queue_millis": 3, + "time_in_queue": "3ms" + } + ] +} +``` + +::: info NOTE +`_cluster/pending_tasks` API 通常返回一个空数组,因为任务通常处理得太快而无法包含在响应中。 +::: + +## 响应字段 + +下表列出了所有响应字段。 + +| 字段 | 数据类型 | 描述 | +| ------------------------------- | --------- | ------------------------------------------------------------------ | +| `tasks` | Array | 待处理的集群状态更新任务列表。 | +| `tasks[n].insert_order` | Integer | 任务添加到队列中的顺序。 | +| `tasks[n].priority` | String | 任务的优先级级别(例如,`HIGH`、`URGENT`)。 | +| `tasks[n].source` | String | 提交任务的操作的描述。 | +| `tasks[n].executing` | Boolean | 确认任务当前是否正在执行。 | +| `tasks[n].time_in_queue_millis` | Integer | 任务在队列中等待的时间(以毫秒为单位)。 | +| `tasks[n].time_in_queue` | String | `time_in_queue_millis` 的人类可读版本。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:monitor/task`。 diff --git a/i18n/zh/api-reference/cluster-api/cluster-reroute.md b/i18n/zh/api-reference/cluster-api/cluster-reroute.md new file mode 100644 index 00000000..d65f48f8 --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/cluster-reroute.md @@ -0,0 +1,353 @@ +--- +title: 集群重新路由 +--- + +# 集群重新路由 API +<Badge type="tip" text="1.0 版本引入" /> + +`/_cluster/reroute` API 允许您手动控制集群内单个分片的分配。这包括移动、分配或取消分片分配。它通常用于高级场景,例如手动恢复或自定义负载均衡。 + +分片移动受集群分配决策器的约束。在生产环境中应用重新路由命令之前,请始终使用 `dry_run=true` 进行测试。使用 `explain=true` 参数可获得有关分配决策的详细见解,这有助于理解为什么特定的重新路由请求可能被允许或不被允许。如果由于先前的问题或集群不稳定导致分片分配失败,您可以使用 `retry_failed=true` 参数重新尝试分配。 + +有关分片分布和集群健康的更多信息,请参阅[集群健康](/api-reference/cluster-api/cluster-health)和[集群分配说明](/api-reference/cluster-api/cluster-allocation)。 + +## 端点 + +```json +POST /_cluster/reroute +``` + +## 查询参数 + +| 参数 | 数据类型 | 描述 | +| ---------------- | --------- | -------------------------------------------------------------------------------------------------- | +| `dry_run` | Boolean | 如果为 `true`,则验证并模拟重新路由请求而不实际应用。默认为 `false`。 | +| `explain` | Boolean | 如果为 `true`,则返回命令被接受或拒绝原因的解释。默认为 `false`。 | +| `retry_failed` | Boolean | 如果为 `true`,则重试先前失败的分片分配。默认为 `false`。 | +| `metric` | String | 限制返回的元数据。请参阅[指标选项](#metric-options)以获取可用选项列表。默认为 `_all`。 | +| `cluster_manager_timeout` | Time | 连接到集群管理器节点的超时时间。默认为 `30s`。 | +| `timeout` | Time | 整体请求超时时间。默认为 `30s`。 | + +### 指标选项 + +`metric` 参数过滤重新路由 API 返回的集群状态值。这对于减少响应大小或检查集群状态的特定部分很有用。此参数支持以下值: + +- `_all` _(默认)_:返回所有可用的集群状态部分。 +- `blocks`:包含有关集群中读写级别块的信息。 +- `cluster_manager_node`:显示当前充当集群管理器的节点。 +- `metadata`:返回索引设置、映射和别名。如果指定了特定索引,则仅返回它们的元数据。 +- `nodes`:包含集群中所有节点及其元数据。 +- `routing_table`:返回所有分片和副本的路由信息。 +- `version`:显示集群状态版本号。 + +您可以在逗号分隔的列表中组合值,例如 `metric=metadata,nodes,routing_table`。 + +## 请求体字段 + +请求体中的 `commands` 数组定义要应用于分片分配的操作。它支持以下操作。 + +### 移动 + +`move` 命令将已启动的分片(主分片或副本)从一个节点移动到另一个节点。这可用于平衡负载或在维护前清空节点。分片必须处于 `STARTED` 状态。主分片和副本分片都可以使用此命令移动。 + +`move` 命令需要以下参数: + +* `index`:索引的名称。 +* `shard`:分片编号。 +* `from_node`:要从中移动分片的节点名称。 +* `to_node`:要将分片移动到的节点名称。 + +### 取消 + +`cancel` 命令取消分片的分配(包括恢复)。此命令通过取消现有分配并让系统重新初始化它们来强制重新同步。默认情况下可以取消副本分片分配,但取消主分片需要 `allow_primary=true` 以防止意外的数据中断。 + +`cancel` 命令需要以下参数: + +* `index`:索引的名称。 +* `shard`:分片编号。 +* `node`:要在其上执行操作的节点名称或节点 ID。 +* `allow_primary` _(可选)_:如果为 `true`,则允许取消主分片分配。默认为 `false`。 + +### 分配副本 + +`allocate_replica` 命令将未分配的副本分配给指定的节点。此操作遵循分配决策器。当自动分配失败时,使用此命令手动触发副本的分配。 + +`allocate_replica` 命令需要以下参数: + +* `index`:索引的名称。 +* `shard`:分片编号。 +* `node`:要在其上执行操作的节点名称或节点 ID。 + +### 分配陈旧主分片 + +`allocate_stale_primary` 命令强制将主分片分配给持有陈旧副本的节点。 + +::: danger WARNING +此命令应极其谨慎使用。它绕过安全检查,可能导致**数据丢失**,特别是如果另一个暂时离线的节点上存在更新的分片副本。如果该节点稍后重新加入集群,其数据将被删除或替换为被强制提升的陈旧副本。 +::: + +::: tip TIP +仅当没有最新副本可用且您无法恢复原始数据时才使用此命令。 +::: + +`allocate_stale_primary` 命令需要以下参数: + +* `index`:索引的名称。 +* `shard`:分片编号。 +* `node`:要在其上执行操作的节点名称或节点 ID。 +* `accept_data_loss`:必须设置为 `true`。 + +### 分配空主分片 + +`allocate_empty_primary` 命令强制将新的空主分片分配给节点。此操作初始化一个没有任何现有数据的新主分片。 + +::: danger WARNING +分片的任何先前数据都将**永久丢失**。如果稍后具有该分片有效数据的节点重新加入集群,其副本将被擦除。此命令用于灾难恢复,当**不存在有效的分片副本**且无法从备份或快照恢复时使用。 +::: + +`allocate_empty_primary` 命令需要以下参数: + +* `index`:索引的名称。 +* `shard`:分片编号。 +* `node`:要在其上执行操作的节点名称或节点 ID。 +* `accept_data_loss`:必须设置为 `true`。 + +## 示例 + +以下是使用集群重新路由 API 的示例。 + +### 移动分片 + +创建一个示例索引: + +```json +PUT /test-cluster-index +{ + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + } +} +``` + +运行以下重新路由命令,将索引 `test-cluster-index` 的分片 `0` 从节点 `node1` 移动到节点 `node2`: + +<!-- spec_insert_start +component: example_code +rest: POST /_cluster/reroute +body: | +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} +--> + +POST /_cluster/reroute +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} + +response = client.cluster.reroute( + body = { + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] + } +) + +<!-- spec_insert_end --> + +### 模拟重新路由 + +要模拟重新路由而不执行它,请设置 `dry_run=true`: + +<!-- spec_insert_start +component: example_code +rest: POST /_cluster/reroute?dry_run=true +body: | +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} +--> + +POST /_cluster/reroute?dry_run=true +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} + +response = client.cluster.reroute( + params = { "dry_run": "true" }, + body = { + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] + } +) + +<!-- spec_insert_end --> + +### 重试失败的分配 + +如果某些分片由于先前的问题而无法分配,您可以重新尝试分配: + +<!-- spec_insert_start +component: example_code +rest: POST /_cluster/reroute?retry_failed=true +--> + +POST /_cluster/reroute?retry_failed=true + +response = client.cluster.reroute( + params = { "retry_failed": "true" } +) + +<!-- spec_insert_end --> + +### 解释重新路由决策 + +要理解为什么重新路由命令被接受或拒绝,请添加 `explain=true`: + +<!-- spec_insert_start +component: example_code +rest: POST /_cluster/reroute?explain=true +body: | +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} +--> + +POST /_cluster/reroute?explain=true +{ + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] +} + +response = client.cluster.reroute( + params = { "explain": "true" }, + body = { + "commands": [ + { + "move": { + "index": "test-cluster-index", + "shard": 0, + "from_node": "node1", + "to_node": "node2" + } + } + ] + } +) + +<!-- spec_insert_end --> + +这将返回一个 `decisions` 数组来解释结果: + +```json +"decisions": [ + { + "decider": "max_retry", + "decision": "YES", + "explanation": "shard has no previous failures" + }, + { + "decider": "replica_after_primary_active", + "decision": "YES", + "explanation": "shard is primary and can be allocated" + }, + ... + { + "decider": "remote_store_migration", + "decision": "YES", + "explanation": "[none migration_direction]: primary shard copy can be relocated to a non-remote node for strict compatibility mode" + } + ] +``` + +## 响应体字段 + +响应包括集群状态元数据,如果使用了 `explain=true`,还可能包括 `decisions` 数组。 + +| 字段 | 数据类型 | 描述 | +| ---------------------------- | --------- | ----------------------------------------------------------------------- | +| `acknowledged` | Boolean | 说明重新路由请求是否被确认。 | +| `state.cluster_uuid` | String | 集群的唯一标识符。 | +| `state.version` | Integer | 集群状态的版本。 | +| `state.state_uuid` | String | 此特定状态版本的 UUID。 | +| `state.master_node` | String | 与 `cluster_manager_node` 一样,这是为了向后兼容性而保留的。 | +| `state.cluster_manager_node` | String | 当选集群管理器节点的 ID。 | +| `state.blocks` | Object | 任何全局或索引级别的集群块。 | +| `state.nodes` | Object | 集群节点的元数据,包括其名称和地址。 | +| `state.routing_table` | Object | 每个索引的分片路由信息。 | +| `state.routing_nodes` | Object | 按节点组织的分片分配。 | +| `commands` | List | 已处理的重新路由命令列表。 | +| `explanations` | List | 如果为 `explain=true`,则包含结果的详细解释。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/reroute`。 diff --git a/i18n/zh/api-reference/cluster-api/cluster-state.md b/i18n/zh/api-reference/cluster-api/cluster-state.md new file mode 100644 index 00000000..cba72f56 --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/cluster-state.md @@ -0,0 +1,121 @@ +--- +title: 集群状态 +--- + +# Cluster State API +<Badge type="tip" text="1.0 版本引入" /> + +`/_cluster/state` API 检索集群的当前状态,包括元数据、路由表、节点和其他组件。此 API 主要用于监控、调试和内部目的。它提供了集群管理节点维护的集群状态各个部分的快照。 + +## 端点 + +```json +GET /_cluster/state +GET /_cluster/state/{metric} +GET /_cluster/state/{metric}/{target} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| ----------- | ----------------- | ----------- | +| `metric` | String 或 List | 要包含在响应中的指标的逗号分隔列表。有关可用选项列表,请参阅[指标选项](#metric-options)。默认为 `_all`。 | +| `target` | String 或 List | 用于限制响应范围的索引名称、数据流和索引别名的逗号分隔列表。 | + +## 指标选项 + +您可以使用 `metric` 路径参数限制 API 返回的信息。可用选项如下: + +- `_all` _(默认)_:返回所有指标。 +- `blocks`:包含有关索引级和全局块的信息。 +- `metadata`:返回集群元数据,包括设置、索引映射和模板。 +- `nodes`:返回有关集群中节点的信息。 +- `routing_table`:提供所有分片的路由信息。 +- `cluster_manager_node`:显示当前选定的集群管理节点的 ID。 +- `version`:显示当前集群状态版本。 + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| ---------------- | --------- | ----------- | +| `local` | Boolean | 如果为 `true`,则从本地节点而不是集群管理节点检索状态。默认为 `false`。 | +| `cluster_manager_timeout` | Time | 连接到集群管理节点的超时持续时间。默认为 `30s`。 | +| `flat_settings` | Boolean | 如果为 `true`,则以平面格式返回设置。默认为 `false`。 | +| `wait_for_metadata_version` | Integer | 等待直到元数据版本等于或大于此值后再响应。 | +| `wait_for_timeout` | Time | 指定使用 `wait_for_metadata_version` 时等待的时间。默认为 `30s`。 | +| `ignore_unavailable` | Boolean | 是否忽略缺失或关闭的索引。默认为 `false`。 | +| `expand_wildcards` | String | 指定通配符表达式可以匹配的索引类型。支持逗号分隔的值。<br> 有效值为:<br> - `all`:匹配任何索引,包括隐藏索引。<br> - `closed`:匹配关闭的非隐藏索引。<br> - `hidden`:匹配隐藏索引。必须与 `open`、`closed` 或两者结合使用。<br> - `none`:不接受通配符表达式。<br> - `open`:匹配打开的非隐藏索引。<br> 默认为 `open`。 | +| `allow_no_indices` | Boolean | 如果通配符表达式或索引别名未解析为任何索引,是否失败。默认为 `true`。 | + +## 示例请求 + +检索完整的集群状态: + +<!-- spec_insert_start +component: example_code +rest: GET /_cluster/state +--> + +GET /_cluster/state + +response = client.cluster.state() + +<!-- spec_insert_end --> + +检索特定索引的元数据和路由表: + +<!-- spec_insert_start +component: example_code +rest: GET /_cluster/state/metadata,routing_table/my-index +--> + +GET /_cluster/state/metadata,routing_table/my-index + +response = client.cluster.state( + metric = "metadata,routing_table", + index = "my-index" +) + +<!-- spec_insert_end --> + +仅检索当前选定的集群管理节点: + +<!-- spec_insert_start +component: example_code +rest: GET /_cluster/state/cluster_manager_node +--> + +GET /_cluster/state/cluster_manager_node + +response = client.cluster.state( + metric = "cluster_manager_node" +) + +<!-- spec_insert_end --> + +## 响应字段 + +下表列出了所有响应字段。 + +| 字段 | 数据类型 | 描述 | +| ---------------------- | --------- | --------------------------------------------------------------------------------- | +| `cluster_name` | String | 集群的名称。 | +| `cluster_uuid` | String | 集群的唯一标识符。 | +| `version` | Integer | 集群状态的当前版本。 | +| `state_uuid` | String | 此状态版本的唯一标识符。 | +| `master_node` | String | 与 `cluster_manager_node` 一样,为了向后兼容而保留。 | +| `cluster_manager_node` | String | 选定的集群管理节点的节点 ID。 | +| `blocks` | Object | 索引级块设置。 | +| `metadata` | Object | 索引映射、设置和别名。 | +| `nodes` | Object | 集群中所有节点的详细信息。 | +| `routing_table` | Object | 每个索引的分片到节点的分配。 | +| `routing_nodes` | Object | 分配给每个节点的分片列表。 | +| `indices` | Object | 特定于索引的状态元数据。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:monitor/state`。 diff --git a/i18n/zh/api-reference/cluster-api/cluster-voting-configuration-exclusions.md b/i18n/zh/api-reference/cluster-api/cluster-voting-configuration-exclusions.md new file mode 100644 index 00000000..4955ccd2 --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/cluster-voting-configuration-exclusions.md @@ -0,0 +1,97 @@ +--- +title: 投票配置排除 +--- + +# 投票配置排除 API +<Badge type="tip" text="1.0 版本引入" /> + +`_cluster/voting_config_exclusions` API 允许您从投票配置中排除一个或多个节点。当您想要安全地从集群中移除具有集群管理器资格的节点或更改当前集群管理器时,这很有用。 + +## 添加投票配置排除 + +使用 POST 方法添加投票配置排除。 + +### 端点 +```json +POST /_cluster/voting_config_exclusions +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +|:-------------|:---------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `node_ids` | List 或 String | 要从投票配置中排除的节点 ID 的逗号分隔列表。使用此设置时,不能同时指定 `node_names`。要接收有效响应,需要 `node_ids` 或 `node_names` 之一。 | +| `node_names` | List 或 String | 要从投票配置中排除的节点名称的逗号分隔列表。使用此设置时,不能同时指定 `node_ids`。要接收有效响应,需要 `node_ids` 或 `node_names` 之一。 | +| `timeout` | String | 添加投票配置排除时,API 在返回响应之前等待指定的节点从投票配置中排除。如果在满足适当条件之前超时到期,则请求失败并返回错误。 | + +### 示例 + +从投票配置中排除名为 `opensearch-node1` 的节点: + +<!-- spec_insert_start +component: example_code +rest: POST /_cluster/voting_config_exclusions?node_names=opensearch-node1 +body: +--> + +POST /_cluster/voting_config_exclusions?node_names=opensearch-node1 + +response = client.cluster.post_voting_config_exclusions( + params = { "node_names": "opensearch-node1" } +) + +<!-- spec_insert_end --> + +或者,您可以将节点 ID 指定为逗号分隔的列表: + +<!-- spec_insert_start +component: example_code +rest: POST /_cluster/voting_config_exclusions?node_ids=6ITS4DmNR7OJT1G5lyW8Lw,PEEW2S7-Su2XCA4zUE9_2Q +body: +--> + +POST /_cluster/voting_config_exclusions?node_ids=6ITS4DmNR7OJT1G5lyW8Lw,PEEW2S7-Su2XCA4zUE9_2Q + +response = client.cluster.post_voting_config_exclusions( + params = { "node_ids": "6ITS4DmNR7OJT1G5lyW8Lw,PEEW2S7-Su2XCA4zUE9_2Q" } +) + +<!-- spec_insert_end --> + +## 移除投票配置排除 + +使用 DELETE 方法清除先前从投票配置中排除的节点列表。这通常在排除的节点被安全移除或替换后使用。您可以选择在清除排除之前等待节点从集群中移除。 + +### 端点 + +```json +DELETE /_cluster/voting_config_exclusions +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +|:-------------------|:----------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `wait_for_removal` | Boolean | 指定在清除投票配置排除列表之前是否等待所有排除的节点从集群中移除。当为 `true` 时,所有排除的节点在此 API 执行任何操作之前都会从集群中移除。当为 `false` 时,即使某些排除的节点仍然存在于集群中,也会清除投票配置排除列表。_(默认:`true`)_ | + +### 示例 + +使用以下请求在不等待节点移除的情况下移除所有投票配置排除: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_cluster/voting_config_exclusions?wait_for_removal=false +body: +--> + +DELETE /_cluster/voting_config_exclusions?wait_for_removal=false + +response = client.cluster.delete_voting_config_exclusions( + params = { "wait_for_removal": "false" } +) + +<!-- spec_insert_end --> diff --git a/i18n/zh/api-reference/cluster-api/describe-cluster-settings.md b/i18n/zh/api-reference/cluster-api/describe-cluster-settings.md new file mode 100644 index 00000000..56fe944c --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/describe-cluster-settings.md @@ -0,0 +1,102 @@ +--- +title: 描述集群设置 +--- + +# 描述集群设置 API +<Badge type="tip" text="3.10 版本引入" /> + +返回指定集群设置的定义。对于每个设置,响应说明该设置是动态的还是静态的、其默认值以及值类型和边界。动态设置可以在运行的集群上更新。静态设置需要重新启动节点才能更改。有关更多信息,请参阅[静态设置](/install-and-configure/configuring-opensearch/#static-settings)和[动态设置](/install-and-configure/configuring-opensearch/#dynamic-settings)。 + +该 API 不返回配置值,因此不会暴露来自 `opensearch.yml`、密钥库或集群状态的值。 + +由于响应源自设置定义,并且在每个节点上都是相同的,因此任何节点都可以处理该请求。请求不会路由到当选的集群管理器节点。 + +## 端点 + +```json +GET /_cluster/settings/_describe +``` + +## 查询参数 + +下表列出了可用的查询参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `settings` | String | 要描述的设置名称的逗号分隔列表。每个条目要么是精确名称,例如 `cluster.max_shards_per_node`,要么是以 `.*` 结尾的前缀,例如 `cluster.routing.allocation.*`,它描述该前缀下任意深度的每个已注册设置。精确名称和前缀可以在一个请求中混合使用。前缀仅扩展到具有固定名称的设置。它不扩展到安全(密钥库)设置或名称包含可变部分的设置,例如 `cluster.remote.<alias>.seeds`。要描述这些设置,请按精确名称请求它们,例如 `cluster.remote.alpha.seeds`。必需。 | + +## 示例请求 + +以下请求描述 `cluster.max_shards_per_node`、`cluster.blocks.read_only` 和 `cluster.name` 设置: + +```json +GET /_cluster/settings/_describe?settings=cluster.max_shards_per_node,cluster.blocks.read_only,cluster.name +``` + +## 示例响应 + +`cluster.name` 设置是静态的,不声明可读值类型,因此其响应不包含 `validation` 对象: + +```json +{ + "settings": { + "cluster.blocks.read_only": { + "dynamic": true, + "default": "false", + "validation": { + "type": "boolean" + } + }, + "cluster.max_shards_per_node": { + "dynamic": true, + "default": "1000", + "validation": { + "type": "integer", + "min": "1" + } + }, + "cluster.name": { + "dynamic": false, + "default": "opensearch" + } + } +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `settings` | Object | 设置名称到其定义的映射。设置名称按排序顺序返回。 | + +响应会省略任何未知或已过滤的请求设置。已过滤的设置(例如凭据)会从设置 API 中隐藏。包含已知和未知名称的请求返回 `200 OK`,仅描述已知名称。 + +`settings` 中的每个对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `dynamic` | Boolean | 如果为 `true`,则可以使用[集群设置 API](/api-reference/cluster-api/cluster-settings) 在运行的集群上更新该设置。如果为 `false`,则该设置是静态的,只能在节点启动前在 `opensearch.yml` 中设置。此字段仅描述设置定义。它不表示调用用户是否有权更新该设置。此字段始终存在。 | +| `default` | String | 设置定义中声明的默认值,采用集群设置 API 接受的字符串形式,例如 `"30s"`、`"85%"` 或 `"[]"` 表示空列表。对于安全(密钥库)设置和声明空默认值的设置,此字段将被省略。某些默认值由响应请求的节点计算。例如,`node.processors` 默认为该节点的处理器计数。 | +| `validation` | Object | 声明的值类型和边界。仅当使用下表中列出的类型之一定义设置时才存在。使用自定义解析的设置(例如字符串、列表或枚举设置)没有 `validation` 对象。 | +| `description` | String | 设置定义中声明的描述。当定义不包含描述时省略。 | + +`validation` 对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `type` | String | 值类型。有效值为 `boolean`、`integer`、`long`、`float`、`double`、`time`、`byte_size` 和 `memory_size`。此字段始终存在于 `validation` 对象中。 | +| `min` | String | 接受的最小值,采用与 `default` 相同的字符串形式。当定义对值没有下限时省略。 | +| `max` | String | 接受的最大值,采用与 `default` 相同的字符串形式。当定义对值没有上限时省略。 | + +对于 `memory_size` 设置,`min` 和 `max` 描述值的百分比形式(0--100%)。这些设置还接受绝对字节大小,例如 `10gb`,这些边界不会约束它。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:monitor/settings/describe`。 + +## 相关文档 + +- [集群设置 API](/api-reference/cluster-api/cluster-settings) +- [配置 OpenSearch](/install-and-configure/configuring-opensearch/) diff --git a/i18n/zh/api-reference/cluster-api/info.md b/i18n/zh/api-reference/cluster-api/info.md new file mode 100644 index 00000000..92a1d2aa --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/info.md @@ -0,0 +1,67 @@ +--- +title: 集群信息 +--- + +# 集群信息 API +<Badge type="tip" text="1.0 版本引入" /> + +集群信息 API (`/`) 检索有关正在运行的 OpenSearch 集群和节点的信息,包括版本、构建详细信息和集群名称。这是验证集群是否可访问并发现 OpenSearch 版本的最简单方法。 + +## 端点 + +```json +GET / +HEAD / +``` + +- `GET /` 返回包含集群和版本详细信息的 JSON 正文。 +- `HEAD /` 仅返回 HTTP 状态(如果可访问则为 200),用于轻量级健康检查。 + +## 示例请求 + +要获取集群的版本和构建信息,请发送以下请求: + +```json +GET / +``` + +## 示例响应 + +```json +{ + "name": "opensearch-node1", + "cluster_name": "opensearch-cluster", + "cluster_uuid": "sQj1b9cZQICv0b8iYc3y5A", + "version": { + "distribution": "opensearch", + "number": "3.2.0", + "build_type": "tar", + "build_hash": "abc123def456", + "build_date": "2025-06-18T12:34:56.000Z", + "build_snapshot": false, + "lucene_version": "9.10.0", + "minimum_wire_compatibility_version": "7.10.0", + "minimum_index_compatibility_version": "7.0.0" + }, + "tagline": "The OpenSearch Project: https://opensearch.org/" +} +``` + +## 响应体字段 + +字段 | 类型 | 描述 +:--- | :--- | :--- +`name` | String | 处理请求的节点的名称。 +`cluster_name` | String | 集群的名称。 +`cluster_uuid` | String | 集群的通用唯一标识符 (UUID)。 +`tagline` | String | 标语字符串。 +`version` | Object | 包含版本和构建元数据的对象。 +`version.distribution` | String | 分发标识符,通常为 `opensearch`。 +`version.number` | String | OpenSearch 版本号,例如 `3.2.0`。 +`version.build_type` | String | 分发类型。 +`version.build_hash` | String | 创建构建的提交哈希。 +`version.build_date` | String | ISO 8601 格式的构建时间戳。 +`version.build_snapshot` | Boolean | 构建是否为快照构建。 +`version.lucene_version` | String | 此构建使用的 Lucene 版本。 +`version.minimum_wire_compatibility_version` | String | 最小兼容传输协议版本。 +`version.minimum_index_compatibility_version` | String | 可以读取的最小索引版本。 diff --git a/i18n/zh/api-reference/cluster-api/remote-info.md b/i18n/zh/api-reference/cluster-api/remote-info.md new file mode 100644 index 00000000..1ab51fa2 --- /dev/null +++ b/i18n/zh/api-reference/cluster-api/remote-info.md @@ -0,0 +1,104 @@ +--- +title: 远程集群信息 +--- + +# 远程集群信息 API +<Badge type="tip" text="1.0 版本引入" /> + +远程集群信息 API 检索在本地集群上配置的所有远程 OpenSearch 集群的连接详细信息。使用此 API 验证连接状态、检查连接模式(`sniff` 或 `proxy`)以及查看跨集群搜索配置的超时设置。 + +响应提供的详细信息比调用 `_cluster/settings` 更多,后者仅返回集群别名和种子节点地址。此 API 还报告活动连接数、连接模式以及在跨集群搜索期间是否跳过不可用的集群。 + +<!-- spec_insert_start +api: cluster.remote_info +component: endpoints +--> +## 端点 +```json +GET /_remote/info +``` +<!-- spec_insert_end --> + +## 示例请求 + +以下示例检索有关所有已配置远程集群的信息: + +<!-- spec_insert_start +component: example_code +rest: GET /_remote/info +--> + +GET /_remote/info + +response = client.cluster.remote_info() + +<!-- spec_insert_end --> + +## 示例响应 + +当没有配置远程集群时,响应为空对象: + +```json +{ } +``` + +当在 `sniff` 模式下配置一个或多个远程集群时,响应包括由集群别名键入的连接详细信息: + +```json +{ + "opensearch-cluster2": { + "connected": true, + "mode": "sniff", + "seeds": [ + "172.28.0.2:9300" + ], + "num_nodes_connected": 1, + "max_connections_per_cluster": 3, + "initial_connect_timeout": "30s", + "skip_unavailable": false + } +} +``` + +当远程集群配置为 `proxy` 模式时,响应包括代理特定字段,而不是种子节点信息: + +```json +{ + "opensearch-cluster3": { + "connected": true, + "mode": "proxy", + "proxy_address": "192.168.1.50:9443", + "num_proxy_sockets_connected": 5, + "max_proxy_socket_connections": 18, + "initial_connect_timeout": "30s", + "skip_unavailable": true + } +} +``` + +## 响应体字段 + +响应是一个 JSON 对象,其中每个键都是远程集群别名。下表描述了每个集群条目中的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `connected` | Boolean | 指示是否至少存在一个到远程集群的活动连接。 | +| `mode` | String | 为远程集群配置的连接模式。有效值为 `sniff`(通过种子地址发现节点)和 `proxy`(通过单个代理地址路由所有请求)。 | +| `initial_connect_timeout` | String | 建立到远程集群的初始连接的超时时间。 | +| `skip_unavailable` | Boolean | 指示在跨集群搜索请求期间远程集群不可访问时是否跳过它。当为 `true` 时,搜索仅从可用集群返回结果。当为 `false` 时,如果此集群不可用,则整个搜索请求失败。 | + +以下字段仅在 `mode` 为 `sniff` 时出现。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `seeds` | Array of strings | 用于发现远程集群中节点的初始种子传输地址。 | +| `num_nodes_connected` | Integer | 本地集群当前与远程集群打开连接的节点数。 | +| `max_connections_per_cluster` | Integer | 本地集群维护到远程集群的最大连接数。 | + +以下字段仅在 `mode` 为 `proxy` 时出现。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `proxy_address` | String | 路由所有到远程集群的连接的地址(主机和端口)。 | +| `num_proxy_sockets_connected` | Integer | 当前打开到代理地址的套接字连接数。 | +| `max_proxy_socket_connections` | Integer | 允许到代理地址的最大套接字连接数。 | diff --git a/i18n/zh/api-reference/cron-expressions.md b/i18n/zh/api-reference/cron-expressions.md new file mode 100644 index 00000000..91e91603 --- /dev/null +++ b/i18n/zh/api-reference/cron-expressions.md @@ -0,0 +1,52 @@ +--- +title: Cron 表达式 +--- + +# Cron 表达式 + +几个 OpenSearch 功能接受 cron 表达式用于调度,包括[索引状态管理](/im-plugin/ism/policies)、[告警](/observing-your-data/alerting/monitors)和[异常检测](/observing-your-data/ad/)。OpenSearch 使用标准的 UNIX cron 语法。所有调度时间均为 UTC。 + +Cron 表达式具有以下格式: + +``` +<minutes> <hours> <day_of_month> <month> <day_of_week> +``` + +下表描述了每个字段。 + +| 字段 | 值 | 特殊字符 | +| :--- | :--- | :--- | +| 分钟 | 0--59 | `, - * /` | +| 小时 | 0--23 | `, - * /` | +| 日期 | 1--31 | `, - * /` | +| 月份 | 1--12 或 JAN--DEC(不区分大小写) | `, - * /` | +| 星期 | 0--7(0 和 7 都是星期日)或 SUN--SAT(不区分大小写) | `, - * /` | + +下表描述了特殊字符。 + +| 字符 | 描述 | +| :--- | :--- | +| `*` | 匹配所有值。例如,月份字段中的 `*` 匹配每个月。 | +| `-` | 范围。例如,`day_of_week` 中的 `1-5` 匹配星期一到星期五。 | +| `,` | 多个值。例如,`day_of_week` 中的 `1,3,5` 表示星期一、星期三和星期五。 | +| `/` | 增量。例如,分钟中的 `0/15` 表示从第 0 分钟开始每 15 分钟。 | + +两个字段指定日期:`day_of_month` 和 `day_of_week`。如果您在两者中都使用非通配符值,则只要任一字段与时间匹配,调度就会运行。例如,`15 2 1,15 * 1` 在 UTC 时间凌晨 2:15 在每月的第 1 天、第 15 天以及每个星期一运行。要调度单个日期,请设置一个字段并将另一个字段保留为 `*`。 + +## 示例 + +| 表达式 | 描述 | +| :--- | :--- | +| `5 9 * * *` | 每天 UTC 时间上午 9:05 | +| `0/15 9 * * *` | UTC 时间上午 9:00 到 9:45 每 15 分钟 | +| `5 9 * * 1-5` | UTC 时间星期一到星期五上午 9:05 | +| `5 9 * * MON-FRI` | UTC 时间星期一到星期五上午 9:05(使用命名的星期) | +| `45 13 1-31/2 * *` | UTC 时间每隔一天下午 1:45 | +| `0/10 * * * 6-7` | 星期六和星期日每 10 分钟 | +| `0 0-23/3 1 1-12/2 *` | 每隔一个月的第 1 天每 3 小时 | + +## 相关文档 + +- [常用 REST 参数](/api-reference/common-parameters) +- [索引名称语法](/api-reference/index-name-syntax) +- [支持的单位](/api-reference/units) diff --git a/i18n/zh/api-reference/data-stream/create-data-stream.md b/i18n/zh/api-reference/data-stream/create-data-stream.md new file mode 100644 index 00000000..04a01882 --- /dev/null +++ b/i18n/zh/api-reference/data-stream/create-data-stream.md @@ -0,0 +1,82 @@ +--- +title: 创建数据流 +--- + +# 创建数据流 API +<Badge type="tip" text="1.0 版本引入" /> + +创建数据流 API 创建一个数据流。在创建数据流之前,您必须创建一个将一组索引配置为数据流的索引模板。有关更多信息,请参阅[索引数据流](/im-plugin/data-streams)。 + +<!-- spec_insert_start +api: indices.create_data_stream +component: endpoints +--> +## 端点 +```json +PUT /_data_stream/{name} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: indices.create_data_stream +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `name` | **必需** | String | 数据流的名称,必须满足以下条件:仅小写;不能包含 `\`、`/`、`*`、`?`、`"`、`<`、`>`、`\|`、`,`、`#`、`:` 或空格字符;不能以 `-`、`_`、`+` 或 `.ds-` 开头;不能是 `.` 或 `..`;长度不能超过 255 字节。多字节字符会更快地计入此限制。 | + +<!-- spec_insert_end --> + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | 是否包含返回错误的堆栈跟踪。 | `false` | +| `filter_path` | List or String | 用于减少响应。此参数采用以逗号分隔的过滤器列表。它支持使用通配符匹配任何字段或字段名称的一部分。您还可以使用 `-` 排除字段。 | N/A | +| `human` | Boolean | 是否返回统计信息的人类可读值。 | `false` | +| `pretty` | Boolean | 是否对返回的 JSON 响应进行美化格式化。 | `false` | +| `source` | String | URL 编码的请求定义。对于不接受非 POST 请求的请求体的库很有用。 | N/A | + +## 示例请求 + +以下示例请求使用先前创建的匹配索引模板创建 `logs-app` 数据流: + +<!-- spec_insert_start +component: example_code +rest: PUT /_data_stream/logs-app +body: {} +--> + +PUT /_data_stream/logs-app +{} + +response = client.indices.create_data_stream( + name = "logs-app", + body = {} +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/data_stream/create`。 + +## 相关文档 + +- [数据流](/im-plugin/data-streams) +- [获取数据流](/api-reference/data-stream/data-stream-info) +- [删除数据流](/api-reference/data-stream/delete-data-stream) diff --git a/i18n/zh/api-reference/data-stream/data-stream-info.md b/i18n/zh/api-reference/data-stream/data-stream-info.md new file mode 100644 index 00000000..c5a24524 --- /dev/null +++ b/i18n/zh/api-reference/data-stream/data-stream-info.md @@ -0,0 +1,142 @@ +--- +title: 获取数据流 +--- + +# 获取数据流 API +<Badge type="tip" text="1.0 版本引入" /> + +获取数据流 API 返回有关一个或多个数据流的信息,包括它们的后备索引、代数和状态。 + +<!-- spec_insert_start +api: indices.get_data_stream +component: endpoints +--> +## 端点 +```json +GET /_data_stream +GET /_data_stream/{name} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: indices.get_data_stream +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | List or String | 用于限制请求的数据流名称的逗号分隔列表。支持通配符(`*`)表达式。如果省略,则返回所有数据流。 | + +<!-- spec_insert_end --> + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | 是否包含返回错误的堆栈跟踪。 | `false` | +| `filter_path` | List or String | 用于减少响应。此参数采用以逗号分隔的过滤器列表。它支持使用通配符匹配任何字段或字段名称的一部分。您还可以使用 `-` 排除字段。 | N/A | +| `human` | Boolean | 是否返回统计信息的人类可读值。 | `false` | +| `pretty` | Boolean | 是否对返回的 JSON 响应进行美化格式化。 | `false` | +| `source` | String | URL 编码的请求定义。对于不接受非 POST 请求的请求体的库很有用。 | N/A | + +## 示例请求 + +以下示例请求返回集群中所有数据流的信息: + +<!-- spec_insert_start +component: example_code +rest: GET /_data_stream +--> + +GET /_data_stream + +response = client.indices.get_data_stream() + +<!-- spec_insert_end --> + +要返回有关特定数据流的信息,请将其名称作为 `name` 路径参数提供: + +<!-- spec_insert_start +component: example_code +rest: GET /_data_stream/logs-app +--> + +GET /_data_stream/logs-app + +response = client.indices.get_data_stream( + name = "logs-app" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "data_streams": [ + { + "name": "logs-app", + "timestamp_field": { + "name": "@timestamp" + }, + "indices": [ + { + "index_name": ".ds-logs-app-000001", + "index_uuid": "23dD0HE5Sg2kSLLAP_YtNA" + } + ], + "generation": 1, + "status": "YELLOW", + "template": "template-logs-app" + } + ] +} +``` + +## 响应体字段 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `data_streams` | Array | 对象列表,每个数据流一个对象。有关对象字段,请参阅[数据流对象](#数据流对象)。 | + +### 数据流对象 + +每个数据流对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | String | 数据流的名称。 | +| `timestamp_field` | Object | 数据流的时间戳字段配置。 | +| `timestamp_field.name` | String | 时间戳字段的名称,通常为 `@timestamp`。 | +| `indices` | Array | 数据流的后备索引列表。数组中的最后一项是当前写入索引。有关对象字段,请参阅[后备索引对象](#后备索引对象)。 | +| `generation` | Integer | 数据流的当前代数。此数字在每次滚动时增加一。 | +| `status` | String | 数据流的健康状态,基于其后备索引的健康状况。有效值为 `GREEN`、`YELLOW` 和 `RED`。 | +| `template` | String | 用于创建数据流的索引模板的名称。 | +| `hidden` | Boolean | 数据流是否隐藏。 | +| `system` | Boolean | 数据流是否由 OpenSearch 内部管理,不能通过正常用户交互进行修改。 | +| `ilm_policy` | String | 关联的索引状态管理(ISM)策略的名称(如果已配置)。 | +| `allow_custom_routing` | Boolean | 数据流是否允许在写入请求上使用自定义路由。 | +| `_meta` | Object | 附加到数据流的自定义元数据。 | + +### 后备索引对象 + +每个后备索引对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index_name` | String | 后备索引的名称。 | +| `index_uuid` | String | 后备索引的 UUID。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/data_stream/get`。 + +## 相关文档 + +- [数据流](/im-plugin/data-streams) +- [获取数据流统计信息](/api-reference/data-stream/data-stream-stats) diff --git a/i18n/zh/api-reference/data-stream/data-stream-stats.md b/i18n/zh/api-reference/data-stream/data-stream-stats.md new file mode 100644 index 00000000..1923503e --- /dev/null +++ b/i18n/zh/api-reference/data-stream/data-stream-stats.md @@ -0,0 +1,200 @@ +--- +title: 获取数据流统计信息 +--- + +# 数据流统计信息 API +<Badge type="tip" text="1.0 版本引入" /> + +数据流统计信息 API 提供有关一个或多个数据流的统计信息,包括后备索引的数量、存储大小和最大时间戳。使用此 API 监控数据流的存储和索引活动。 + +<!-- spec_insert_start +api: indices.data_streams_stats +component: endpoints +--> +## 端点 +```json +GET /_data_stream/_stats +GET /_data_stream/{name}/_stats +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: indices.data_streams_stats +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | List or String | 用于限制请求的数据流的逗号分隔列表。支持通配符表达式(`*`)。要定位集群中的所有数据流,请省略此参数或使用 `*`。 | + +<!-- spec_insert_end --> + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | 是否包含返回错误的堆栈跟踪。 | `false` | +| `filter_path` | List or String | 用于减少响应。此参数采用以逗号分隔的过滤器列表。它支持使用通配符匹配任何字段或字段名称的一部分。您还可以使用 `-` 排除字段。 | N/A | +| `human` | Boolean | 是否返回统计信息的人类可读值。 | `false` | +| `pretty` | Boolean | 是否对返回的 JSON 响应进行美化格式化。 | `false` | +| `source` | String | URL 编码的请求定义。对于不接受非 POST 请求的请求体的库很有用。 | N/A | + +## 示例请求 + +创建一个具有匹配模式和启用数据流的索引模板: + +<!-- spec_insert_start +component: example_code +rest: PUT /_index_template/template-logs-app +body: | +{ + "index_patterns": ["logs-app*"], + "data_stream": {} +} +--> + +PUT /_index_template/template-logs-app +{ + "index_patterns": [ + "logs-app*" + ], + "data_stream": {} +} + +response = client.indices.put_index_template( + name = "template-logs-app", + body = { + "index_patterns": [ + "logs-app*" + ], + "data_stream": {} + } +) + +<!-- spec_insert_end --> + +创建数据流: + +<!-- spec_insert_start +component: example_code +rest: PUT /_data_stream/logs-app +body: {} +--> + +PUT /_data_stream/logs-app +{} + +response = client.indices.create_data_stream( + name = "logs-app", + body = {} +) + +<!-- spec_insert_end --> + +索引一个文档以生成后备索引: + +<!-- spec_insert_start +component: example_code +rest: POST /logs-app/_doc +body: | +{ + "@timestamp": "2025-06-23T10:00:00Z", + "message": "app started" +} +--> + +POST /logs-app/_doc +{ + "@timestamp": "2025-06-23T10:00:00Z", + "message": "app started" +} + +response = client.index( + index = "logs-app", + body = { + "@timestamp": "2025-06-23T10:00:00Z", + "message": "app started" + } +) + +<!-- spec_insert_end --> + +检索数据流的统计信息: + +<!-- spec_insert_start +component: example_code +rest: GET /_data_stream/logs-app/_stats?human=true +--> + +GET /_data_stream/logs-app/_stats?human=true + +response = client.indices.data_streams_stats( + name = "logs-app", + params = { "human": "true" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "_shards": { + "total": 2, + "successful": 2, + "failed": 0 + }, + "data_stream_count": 1, + "backing_indices": 1, + "total_store_size": "16.8kb", + "total_store_size_bytes": 17304, + "data_streams": [ + { + "data_stream": "logs-app", + "backing_indices": 1, + "store_size": "16.8kb", + "store_size_bytes": 17304, + "maximum_timestamp": 1750673100000 + } + ] +} +``` + +## 响应体字段 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_shards.total` | Integer | 请求涉及的分片总数。 | +| `_shards.successful` | Integer | 成功获取的分片数量。 | +| `_shards.failed` | Integer | 获取失败的分片数量。 | +| `data_stream_count` | Integer | 响应中返回的数据流总数。 | +| `backing_indices` | Integer | 所有数据流的后备索引总数。 | +| `total_store_size` | String | 所有数据流存储的人类可读总大小。仅当 `human=true` 时存在。 | +| `total_store_size_bytes` | Integer | 所有数据流使用的总存储,以字节为单位。 | +| `data_streams` | Array | 对象列表,每个数据流一个对象。有关对象字段,请参阅[数据流对象](#数据流对象)。 | + +### 数据流对象 + +每个数据流对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `data_stream` | String | 数据流的名称。 | +| `backing_indices` | Integer | 数据流的后备索引数量。 | +| `store_size` | String | 数据流使用的人类可读存储。仅当 `human=true` 时存在。 | +| `store_size_bytes` | Integer | 数据流使用的总存储,以字节为单位。 | +| `maximum_timestamp` | Long | 数据流中所有文档的最大时间戳。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:monitor/data_stream/stats`。 + +## 相关文档 + +- [数据流](/im-plugin/data-streams) +- [获取数据流](/api-reference/data-stream/data-stream-info) diff --git a/i18n/zh/api-reference/data-stream/delete-data-stream.md b/i18n/zh/api-reference/data-stream/delete-data-stream.md new file mode 100644 index 00000000..e75a92a9 --- /dev/null +++ b/i18n/zh/api-reference/data-stream/delete-data-stream.md @@ -0,0 +1,78 @@ +--- +title: 删除数据流 +--- + +# 删除数据流 API +<Badge type="tip" text="1.0 版本引入" /> + +删除数据流 API 删除数据流及其后备索引。 + +<!-- spec_insert_start +api: indices.delete_data_stream +component: endpoints +--> +## 端点 +```json +DELETE /_data_stream/{name} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: indices.delete_data_stream +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `name` | **必需** | List or String | 要删除的数据流的逗号分隔列表。支持通配符(`*`)表达式。 | + +<!-- spec_insert_end --> + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `error_trace` | Boolean | 是否包含返回错误的堆栈跟踪。 | `false` | +| `filter_path` | List or String | 用于减少响应。此参数采用以逗号分隔的过滤器列表。它支持使用通配符匹配任何字段或字段名称的一部分。您还可以使用 `-` 排除字段。 | N/A | +| `human` | Boolean | 是否返回统计信息的人类可读值。 | `false` | +| `pretty` | Boolean | 是否对返回的 JSON 响应进行美化格式化。 | `false` | +| `source` | String | URL 编码的请求定义。对于不接受非 POST 请求的请求体的库很有用。 | N/A | + +## 示例请求 + +以下示例请求删除 `logs-app` 数据流及其后备索引: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_data_stream/logs-app +--> + +DELETE /_data_stream/logs-app + +response = client.indices.delete_data_stream( + name = "logs-app" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/data_stream/delete`。 + +## 相关文档 + +- [数据流](/im-plugin/data-streams) +- [创建或更新数据流](/api-reference/data-stream/create-data-stream) diff --git a/i18n/zh/api-reference/data-stream/index.md b/i18n/zh/api-reference/data-stream/index.md new file mode 100644 index 00000000..3189ea5d --- /dev/null +++ b/i18n/zh/api-reference/data-stream/index.md @@ -0,0 +1,23 @@ +--- +title: 数据流 API +--- + +# 数据流 API + +使用数据流 API 创建和删除[数据流](/im-plugin/data-streams),修改其后备索引,并检索有关它们的信息和统计数据。 + +## 可用 API + +OpenSearch 支持以下数据流 API。 + +| API | 描述 | +|-----|-------------| +| [创建数据流](/api-reference/data-stream/create-data-stream) | 创建数据流。 | +| [获取数据流](/api-reference/data-stream/data-stream-info) | 返回有关一个或多个数据流的信息。 | +| [获取数据流统计信息](/api-reference/data-stream/data-stream-stats) | 返回一个或多个数据流的统计信息。 | +| [修改数据流](/api-reference/data-stream/modify-data-stream) | 添加或删除数据流的后备索引。 | +| [删除数据流](/api-reference/data-stream/delete-data-stream) | 删除数据流及其后备索引。 | + +## 相关文档 + +- 有关数据流的更多信息(包括何时使用它们),请参阅[数据流](/im-plugin/data-streams)。 diff --git a/i18n/zh/api-reference/data-stream/modify-data-stream.md b/i18n/zh/api-reference/data-stream/modify-data-stream.md new file mode 100644 index 00000000..445fd48f --- /dev/null +++ b/i18n/zh/api-reference/data-stream/modify-data-stream.md @@ -0,0 +1,97 @@ +--- +title: 修改数据流 +--- + +# 修改数据流 API +<Badge type="tip" text="3.8 版本引入" /> + +::: danger WARNING +这是一项实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/OpenSearch/issues/8271)。 +::: + +修改数据流 API 添加或删除[数据流](/im-plugin/data-streams)的后备索引。使用此 API 将预先存在的常规索引迁移到数据流中,或在不删除其数据的情况下分离后备索引。 + +添加或删除后备索引时,以下行为和限制适用: + +- 添加和删除操作仅更改数据流元数据;索引及其数据保持不变。不会创建、删除、恢复或重新定位分片。 +- 您可以在单个请求中包含多个添加和删除操作。所有操作都在单个集群状态更新中原子应用,结果与操作顺序无关。 +- 数据流代数源自其后备索引(最高的后备索引计数器是写入索引),不能直接设置。 +- 不能删除写入索引,删除最后一个后备索引会被拒绝。 +- 添加的索引必须将数据流的时间戳字段映射为 `date` 或 `date_nanos`。添加的索引被标记为隐藏;删除的索引再次变为可见。 +- 添加的索引不需要遵循 `.ds-<data_stream>-NNNNNN` 命名约定,这允许您将预先存在的常规索引迁移到数据流中。 +- 索引不能是多个数据流的后备索引。 + +## 端点 + +```json +POST /_data_stream/_modify +``` + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time | 等待集群管理器节点响应的时间。默认值为 `30s`。 | +| `timeout` | Time | 等待集群响应的时间。默认值为 `30s`。 | + +## 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `actions` | Array | 要执行的操作列表。您必须提供至少一个操作。必需。 | + +`actions` 数组中的每个元素都是一个单键对象,指定一个操作。下表列出了可用的操作字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `add_backing_index.data_stream` | String | 要修改的数据流的名称。必需。 | +| `add_backing_index.index` | String | 要添加为后备索引的索引的名称。必需。 | +| `remove_backing_index.data_stream` | String | 要修改的数据流的名称。必需。 | +| `remove_backing_index.index` | String | 要删除的后备索引的名称。必需。 | +| `add_backing_index` | Object | 将现有索引添加到数据流作为后备索引。可选。 | +| `remove_backing_index` | Object | 从数据流中删除后备索引。可选。 | + +## 示例请求 + +以下请求从 `logs-foo` 数据流中删除一个后备索引,并在单个原子操作中将预先存在的 `legacy-logs-2023` 索引添加到其中: + +```json +POST /_data_stream/_modify +{ + "actions": [ + { + "remove_backing_index": { + "data_stream": "logs-foo", + "index": ".ds-logs-foo-000001" + } + }, + { + "add_backing_index": { + "data_stream": "logs-foo", + "index": "legacy-logs-2023" + } + } + ] +} +``` + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/data_stream/modify`。 + +## 相关文档 + +- [数据流](/im-plugin/data-streams) +- [数据流统计信息 API](/api-reference/data-stream/data-stream-stats) diff --git a/i18n/zh/api-reference/document-apis/bulk-streaming.md b/i18n/zh/api-reference/document-apis/bulk-streaming.md new file mode 100644 index 00000000..a5b6f6e3 --- /dev/null +++ b/i18n/zh/api-reference/document-apis/bulk-streaming.md @@ -0,0 +1,75 @@ +--- +title: 流式批量操作 +--- + +# 流式批量操作 API +<Badge type="tip" text="2.17.0 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/OpenSearch/issues/9065)。 +::: + +流式批量操作允许您通过流式传输请求并以流式响应获取结果的方式来添加、更新或删除多个文档。与传统的[批量操作 API](/api-reference/document-apis/bulk) 相比,流式摄取消除了估算批次大小的需要(批次大小受任何给定时间集群运行状态的影响),并自然地在多个客户端和集群之间应用背压。流式传输通过 HTTP/2 或 HTTP/1.1(使用分块传输编码)工作,具体取决于客户端和集群的能力。 + +::: info NOTE +默认的 HTTP 传输方法不支持流式传输。您必须安装 [`transport-reactor-netty4`](/install-and-configure/configuring-opensearch/network-settings#selecting-the-transport) HTTP 传输插件并将其用作默认的 HTTP 传输层。`transport-reactor-netty4` 插件和流式批量操作 API 都是实验性的。 +::: + +## 端点 + +```json +POST _bulk/stream +POST {index}/_bulk/stream +``` + +如果您在路径中指定索引,则无需在[请求正文块](/api-reference/document-apis/bulk#request-body)中包含它。 + +::: info NOTE +OpenSearch 也接受对 `_bulk/stream` 路径的 PUT 请求,但我们强烈建议使用 POST。PUT 的公认用法——在给定路径上添加或替换单个资源——对于流式批量请求没有意义。 +::: + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 数据类型 | 说明 +:--- | :--- | :--- +`pipeline` | String | 用于预处理文档的管道 ID。 +`refresh` | Enum | 执行索引操作后是否刷新受影响的分片。默认值为 `false`。`true` 会导致更改立即显示在搜索结果中,但会降低集群性能。`wait_for` 等待刷新。请求返回时间较长,但集群性能不会降低。 +`require_alias` | Boolean | 设置为 `true` 以要求所有操作以索引别名而不是索引为目标。默认值为 `false`。 +`routing` | String | 对于未指定自己路由的操作的默认路由值。 +`timeout` | Time | 等待请求返回的时间。默认值为 `1m`。 +`wait_for_active_shards` | String | 指定在 OpenSearch 处理批量请求之前必须可用的活动分片数。默认值为 `1`(仅主分片)。设置为 `all` 或正整数。大于 1 的值需要副本。例如,如果您指定值为 3,则索引必须在 2 个额外节点上分布有 2 个副本才能使请求成功。 +`batch_interval` | Time | 指定批量操作在发送到数据节点之前应累积到批次中的时间。必须大于 0。如果未指定,则不按时间批处理操作。 +`batch_size` | Integer | 指定在发送到数据节点之前应累积到批次中的批量操作数。必须大于 0。默认值为 `1`。 + +## 请求正文字段 + +流式批量操作 API 请求正文与[批量操作 API 请求正文](/api-reference/document-apis/bulk#request-body)完全兼容,其中每个批量操作(create/index/update/delete)作为单独的块发送。 + +## 示例请求 + +```json +curl -X POST "http://localhost:9200/_bulk/stream" -H "Transfer-Encoding: chunked" -H "Content-Type: application/json" -d' +{ "delete": { "_index": "movies", "_id": "tt2229499" } } +{ "index": { "_index": "movies", "_id": "tt1979320" } } +{ "title": "Rush", "year": 2013 } +{ "create": { "_index": "movies", "_id": "tt1392214" } } +{ "title": "Prisoners", "year": 2013 } +{ "update": { "_index": "movies", "_id": "tt0816711" } } +{ "doc" : { "title": "World War Z" } } +' +``` + +## 示例响应 + +根据批处理设置,每个流式响应块可能报告一个或多个(批量)批量操作的结果。OpenSearch 为其接收的每个 HTTP 块返回结果,因此响应块的数量也取决于客户端如何拆分请求流。 + +以下响应假设 ID 为 `tt1392214` 的文档已存在于 `movies` 索引中,因此 `create` 操作导致版本冲突。ID 为 `tt2229499` 和 `tt0816711` 的文档不存在,因此 `delete` 操作返回 `not_found`,`update` 操作失败。对于没有批处理(默认)的前述请求,流式响应可能如下所示: + +```json +{"took": 4, "errors": false, "items": [ { "delete": { "_index": "movies", "_id": "tt2229499", "_version": 1, "result": "not_found", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 1, "_primary_term": 1, "status": 404 } } ] } +{"took": 11, "errors": false, "items": [ { "index": { "_index": "movies", "_id": "tt1979320", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 2, "_primary_term": 1, "status": 201 } } ] } +{"took": 2, "errors": true, "items": [ { "create": { "_index": "movies", "_id": "tt1392214", "status": 409, "error": { "type": "version_conflict_engine_exception", "reason": "[tt1392214]: version conflict, document already exists (current version [1])", "index": "movies", "shard": "0", "index_uuid": "yhizhusbSWmP0G7OJnmcLg" } } } ] } +{"took": 4, "errors": true, "items": [ { "update": { "_index": "movies", "_id": "tt0816711", "status": 404, "error": { "type": "document_missing_exception", "reason": "[tt0816711]: document missing", "index": "movies", "shard": "0", "index_uuid": "yhizhusbSWmP0G7OJnmcLg" } } } ] } +``` diff --git a/i18n/zh/api-reference/document-apis/mtermvectors.md b/i18n/zh/api-reference/document-apis/mtermvectors.md new file mode 100644 index 00000000..94db8999 --- /dev/null +++ b/i18n/zh/api-reference/document-apis/mtermvectors.md @@ -0,0 +1,441 @@ +--- +title: 多文档词项向量 +--- + +# 多文档词项向量 API +<Badge type="tip" text="1.0 版本引入" /> + +`_mtermvectors` API 在一次请求中检索多个文档的词项向量信息。词项向量提供有关文档中词项(单词)的详细信息,包括词项频率、位置、偏移量和有效负载。这对于相关性评分、高亮显示或相似性计算等应用程序很有用。有关更多信息,请参阅[词项向量参数](/mappings/supported-field-types/text/#term-vector-parameter)。 + +<!-- spec_insert_start +api: mtermvectors +component: endpoints +--> +## 端点 +```json +GET /_mtermvectors +POST /_mtermvectors +GET /{index}/_mtermvectors +POST /{index}/_mtermvectors +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: mtermvectors +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 说明 | +| :--- | :--- | :--- | +| `index` | String | 包含文档的索引名称。 | + +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: mtermvectors +component: query_parameters +columns: Parameter, Data type, Description +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 说明 | +| :--- | :--- | :--- | +| `field_statistics` | Boolean | 如果为 `true`,响应包括文档计数、文档频率总和以及总词项频率总和。_(默认值:`true`)_ | +| `fields` | List or String | 以逗号分隔的列表或通配符表达式,指定要包含在统计信息中的字段。用作默认列表,除非在 `completion_fields` 或 `fielddata_fields` 参数中提供特定字段列表。 | +| `ids` | List | 以逗号分隔的文档 ID 列表。您必须在请求正文中提供 `docs` 字段,或在查询参数或请求正文中指定 `ids`。 | +| `offsets` | Boolean | 如果为 `true`,响应包括词项偏移量。_(默认值:`true`)_ | +| `payloads` | Boolean | 如果为 `true`,响应包括词项有效负载。_(默认值:`true`)_ | +| `positions` | Boolean | 如果为 `true`,响应包括词项位置。_(默认值:`true`)_ | +| `preference` | String | 指定应在哪个节点或分片上执行操作。有关可用选项的列表,请参阅 [preference 查询参数](/api-reference/search-apis/search#the-preference-query-parameter)。默认情况下,请求被随机路由到可用的分片副本(主分片或副本),不保证重复查询之间的一致性。 | +| `realtime` | Boolean | 如果为 `true`,请求是实时的而不是近实时的。_(默认值:`true`)_ | +| `routing` | List or String | 用于将操作路由到特定分片的自定义值。 | +| `term_statistics` | Boolean | 如果为 `true`,响应包括词项频率和文档频率。_(默认值:`false`)_ | +| `version` | Integer | 如果为 `true`,作为命中的一部分返回文档版本。 | +| `version_type` | String | 特定的版本类型。<br> 有效值为:<br> - `external`:版本号必须大于当前版本。<br> - `external_gte`:版本号必须大于或等于当前版本。<br> - `internal`:版本号由 OpenSearch 内部管理。 | + +<!-- spec_insert_end --> + +## 请求正文字段 + +下表列出了可以在请求正文中指定的字段。 + +| 字段 | 数据类型 | 说明 | +| `docs` | Array | 文档规范数组。 | +| `ids` | Array of strings | 要检索的文档 ID 列表。仅当所有文档共享请求路径或查询中指定的相同索引时才使用。 | +| `fields` | Array of strings | 要为其返回词项向量的字段名称列表。 | +| `offsets` | Boolean | 如果为 `true`,响应包括每个词项的字符偏移量。*(默认值:`true`)* | +| `payloads` | Boolean | 如果为 `true`,响应包括每个词项的有效负载。*(默认值:`true`)* | +| `positions` | Boolean | 如果为 `true`,响应包括词元位置。*(默认值:`true`)* | +| `field_statistics` | Boolean | 如果为 `true`,响应包括统计信息,如文档计数、文档频率总和以及总词项频率总和。*(默认值:`true`)* | +| `term_statistics` | Boolean | 如果为 `true`,响应包括词项频率和文档频率。*(默认值:`false`)* | +| `routing` | String | 用于标识分片的自定义路由值。如果在索引期间使用了自定义路由,则为必需。 | +| `version` | Integer | 要检索的文档的特定版本。 | +| `version_type` | String | 要使用的版本控制类型。有效值:`internal`、`external`、`external_gte`。 | +| `filter` | Object | 过滤响应中返回的词元(例如,按频率或位置)。有关支持的字段,请参阅[过滤词项](/api-reference/document-apis/mtermvectors#filtering-terms)。 | +| `per_field_analyzer` | Object | 指定要为每个字段使用的自定义分析器。格式:`{ "field_name": "analyzer_name" }`。 | + +## 过滤词项 + +请求正文中的 `filter` 对象允许您过滤要包含在词项向量响应中的词元。`filter` 对象支持以下字段。 + +| 字段 | 数据类型 | 说明 | +| `max_num_terms` | Integer | 要返回的最大词项数。 | +| `min_term_freq` | Integer | 要包含词项所需的文档中的最小词项频率。 | +| `max_term_freq` | Integer | 要包含词项所需的文档中的最大词项频率。 | +| `min_doc_freq` | Integer | 要包含词项所需的索引中的最小文档频率。 | +| `max_doc_freq` | Integer | 要包含词项所需的索引中的最大文档频率。 | +| `min_word_length` | Integer | 要包含的词项的最小长度。 | +| `max_word_length` | Integer | 要包含的词项的最大长度。 | + +## 示例请求 + +创建启用词项向量的索引: + +```json +PUT /my-index +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_offsets_payloads" + } + } + } +} +``` + +索引第一个文档: + +<!-- spec_insert_start +component: example_code +rest: POST /my-index/_doc/1 +body: | +{ + "text": "OpenSearch is a search engine." +} +--> + +POST /my-index/_doc/1 +{ + "text": "OpenSearch is a search engine." +} + +response = client.index( + index = "my-index", + id = "1", + body = { + "text": "OpenSearch is a search engine." + } +) + +<!-- spec_insert_end --> + +索引第二个文档: + +<!-- spec_insert_start +component: example_code +rest: POST /my-index/_doc/2 +body: | +{ + "text": "OpenSearch provides powerful features." +} +--> + +POST /my-index/_doc/2 +{ + "text": "OpenSearch provides powerful features." +} + +response = client.index( + index = "my-index", + id = "2", + body = { + "text": "OpenSearch provides powerful features." + } +) + +<!-- spec_insert_end --> + +### 示例请求 + +获取多个文档的词项向量: + +<!-- spec_insert_start +component: example_code +rest: POST /_mtermvectors +body: | +{ + "docs": [ + { + "_index": "my-index", + "_id": "1", + "fields": ["text"] + }, + { + "_index": "my-index", + "_id": "2", + "fields": ["text"] + } + ] +} +--> + +POST /_mtermvectors +{ + "docs": [ + { + "_index": "my-index", + "_id": "1", + "fields": [ + "text" + ] + }, + { + "_index": "my-index", + "_id": "2", + "fields": [ + "text" + ] + } + ] +} + +response = client.mtermvectors( + body = { + "docs": [ + { + "_index": "my-index", + "_id": "1", + "fields": [ + "text" + ] + }, + { + "_index": "my-index", + "_id": "2", + "fields": [ + "text" + ] + } + ] + } +) + +<!-- spec_insert_end --> + +或者,您可以将 `ids` 和 `fields` 都指定为查询参数: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/_mtermvectors?ids=1,2&fields=text +--> + +GET /my-index/_mtermvectors?ids=1,2&fields=text + +response = client.mtermvectors( + index = "my-index", + params = { "ids": "1,2", "fields": "text" } +) + +<!-- spec_insert_end --> + +您还可以在 `ids` 数组中提供文档 ID,而不是指定 `docs`: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/_mtermvectors?fields=text +body: | +{ + "ids": [ + "1", "2" + ] +} +--> + +GET /my-index/_mtermvectors?fields=text +{ + "ids": [ + "1", + "2" + ] +} + +response = client.mtermvectors( + index = "my-index", + params = { "fields": "text" }, + body = { + "ids": [ + "1", + "2" + ] + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +响应包含两个文档的词项向量信息: + +```json +{ + "docs": [ + { + "_index": "my-index", + "_id": "1", + "_version": 1, + "found": true, + "took": 10, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 9, + "doc_count": 2, + "sum_ttf": 9 + }, + "terms": { + "a": { + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 14, + "end_offset": 15 + } + ] + }, + "engine": { + "term_freq": 1, + "tokens": [ + { + "position": 4, + "start_offset": 23, + "end_offset": 29 + } + ] + }, + "is": { + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 11, + "end_offset": 13 + } + ] + }, + "opensearch": { + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 10 + } + ] + }, + "search": { + "term_freq": 1, + "tokens": [ + { + "position": 3, + "start_offset": 16, + "end_offset": 22 + } + ] + } + } + } + } + }, + { + "_index": "my-index", + "_id": "2", + "_version": 1, + "found": true, + "took": 0, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 9, + "doc_count": 2, + "sum_ttf": 9 + }, + "terms": { + "features": { + "term_freq": 1, + "tokens": [ + { + "position": 3, + "start_offset": 29, + "end_offset": 37 + } + ] + }, + "opensearch": { + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 10 + } + ] + }, + "powerful": { + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 20, + "end_offset": 28 + } + ] + }, + "provides": { + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 11, + "end_offset": 19 + } + ] + } + } + } + } + } + ] +} +``` + +## 响应正文字段 + +下表列出了所有响应正文字段。 + +| 字段 | 数据类型 | 说明 | +| -------- | --------- | ----------- | +| `docs` | Array | 包含词项向量的请求文档列表。 | + +`docs` 数组的每个元素包含以下字段。 + +| 字段 | 数据类型 | 说明 | +| -------- | --------- | ----------- | +| `term_vectors` | Object | 包含每个字段的词项向量数据。 | +| `term_vectors.<field>.field_statistics` | Object | 包含有关字段的统计信息。 | +| `term_vectors.<field>.field_statistics.doc_count` | Integer | 包含指定字段中至少一个词项的文档数。 | +| `term_vectors.<field>.field_statistics.sum_doc_freq` | Integer | 字段中所有词项的文档频率总和。 | +| `term_vectors.<field>.field_statistics.sum_ttf` | Integer | 字段中所有词项的总词项频率总和。 | +| `term_vectors.<field>.terms` | Object | 字段中词项的映射,其中每个词项包括其频率(`term_freq`)和相关词元信息。 | +| `term_vectors.<field>.terms.<term>.tokens` | Array | 每个词项的词元对象数组,包括词元在文本中的 `position` 及其字符偏移量(`start_offset` 和 `end_offset`)。 | + +## 所需权限 + +如果使用安全插件,请确保您具有适当的权限:`indices:data/read/mtv` 和 `indices:data/read/mtv*`。 diff --git a/i18n/zh/api-reference/document-apis/termvector.md b/i18n/zh/api-reference/document-apis/termvector.md new file mode 100644 index 00000000..e71bc5c1 --- /dev/null +++ b/i18n/zh/api-reference/document-apis/termvector.md @@ -0,0 +1,292 @@ +--- +title: 词项向量 +--- + +# 词项向量 API +<Badge type="tip" text="1.0 版本引入" /> + +`_termvectors` API 检索单个文档的词项向量信息。词项向量提供有关文档中词项(单词)的详细信息,包括词项频率、位置、偏移量和有效负载。这对于相关性评分、高亮显示或相似性计算等应用程序很有用。有关更多信息,请参阅[词项向量参数](/mappings/supported-field-types/text/#term-vector-parameter)。 + +<!-- spec_insert_start +api: termvectors +component: endpoints +--> +## 端点 +```json +GET /{index}/_termvectors +POST /{index}/_termvectors +GET /{index}/_termvectors/{id} +POST /{index}/_termvectors/{id} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: termvectors +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 说明 | +| :--- | :--- | :--- | :--- | +| `index` | **必需** | String | 包含文档的索引名称。 | +| `id` | _可选_ | String | 文档的唯一标识符。 | + +<!-- spec_insert_end --> + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 说明 | +| :--- | :--- | :--- | +| `field_statistics` | Boolean | 如果为 `true`,响应包括文档计数、文档频率总和以及总词项频率总和。*(默认值:`true`)* | +| `fields` | List or String | 以逗号分隔的列表或通配符表达式,指定要包含在统计信息中的字段。用作默认列表,除非在 `completion_fields` 或 `fielddata_fields` 参数中提供特定字段列表。 | +| `offsets` | Boolean | 如果为 `true`,响应包括词项偏移量。*(默认值:`true`)* | +| `payloads` | Boolean | 如果为 `true`,响应包括词项有效负载。*(默认值:`true`)* | +| `positions` | Boolean | 如果为 `true`,响应包括词项位置。*(默认值:`true`)* | +| `preference` | String | 指定应在哪个节点或分片上执行操作。有关可用选项的列表,请参阅 [preference 查询参数](/api-reference/search-apis/search#the-preference-query-parameter)。默认情况下,请求被随机路由到可用的分片副本(主分片或副本),不保证重复查询之间的一致性。 | +| `realtime` | Boolean | 如果为 `true`,请求是实时的而不是近实时的。*(默认值:`true`)* | +| `routing` | List or String | 用于将操作路由到特定分片的自定义值。 | +| `term_statistics` | Boolean | 如果为 `true`,响应包括词项频率和文档频率。*(默认值:`false`)* | +| `version` | Integer | 如果为 `true`,作为命中的一部分返回文档版本。 | +| `version_type` | String | 特定的版本类型。<br> 有效值为:<br> - `external`:版本号必须大于当前版本。<br> - `external_gte`:版本号必须大于或等于当前版本。<br> - `force`:版本号被强制为给定值。<br> - `internal`:版本号由 OpenSearch 内部管理。 | + +## 请求正文字段 + +下表列出了可以在请求正文中指定的字段。 + +| 字段 | 数据类型 | 说明 | +| `doc` | Object | 要分析的文档。如果提供,API 不会从索引中检索现有文档,而是使用提供的内容。 | +| `fields` | Array of strings | 要为其返回词项向量的字段名称列表。 | +| `offsets` | Boolean | 如果为 `true`,响应包括每个词项的字符偏移量。*(默认值:`true`)* | +| `payloads` | Boolean | 如果为 `true`,响应包括每个词项的有效负载。*(默认值:`true`)* | +| `positions` | Boolean | 如果为 `true`,响应包括词元位置。*(默认值:`true`)* | +| `field_statistics` | Boolean | 如果为 `true`,响应包括统计信息,如文档计数、文档频率总和以及总词项频率总和。*(默认值:`true`)* | +| `term_statistics` | Boolean | 如果为 `true`,响应包括词项频率和文档频率。*(默认值:`false`)* | +| `routing` | String | 用于标识分片的自定义路由值。如果在索引期间使用了自定义路由,则为必需。 | +| `version` | Integer | 要检索的文档的特定版本。 | +| `version_type` | String | 要使用的版本控制类型。有效值:`internal`、`external`、`external_gte`、`force`。 | +| `filter` | Object | 允许过滤响应中返回的词元(例如,按频率或位置)。有关可用选项,请参阅[过滤词项](/api-reference/document-apis/termvector#filtering-terms)。 | +| `per_field_analyzer` | Object | 指定要为每个字段使用的自定义分析器。格式:`{ "field_name": "analyzer_name" }`。 | +| `preference` | String | 指定分片或节点路由首选项。请参阅 [preference 查询参数](/api-reference/search-apis/search#the-preference-query-parameter)。| + +## 过滤词项 + +请求正文中的 `filter` 对象允许您过滤要包含在词项向量响应中的词元。`filter` 对象支持以下字段。 + +| 字段 | 数据类型 | 说明 | +| `max_num_terms` | Integer | 要返回的最大词项数。 | +| `min_term_freq` | Integer | 要包含词项所需的文档中的最小词项频率。 | +| `max_term_freq` | Integer | 要包含词项所需的文档中的最大词项频率。 | +| `min_doc_freq` | Integer | 要包含词项所需的索引中的最小文档频率。 | +| `max_doc_freq` | Integer | 要包含词项所需的索引中的最大文档频率。 | +| `min_word_length` | Integer | 要包含的词项的最小长度。 | +| `max_word_length` | Integer | 要包含的词项的最大长度。 | + +## 示例请求 + +创建索引: + +```json +PUT /my-index +{ + "mappings": { + "properties": { + "text": { + "type": "text", + "term_vector": "with_positions_offsets_payloads" + } + } + } +} +``` + +索引文档: + +<!-- spec_insert_start +component: example_code +rest: POST /my-index/_doc/1 +body: | +{ + "text": "OpenSearch is a search engine." +} +--> + +POST /my-index/_doc/1 +{ + "text": "OpenSearch is a search engine." +} + +response = client.index( + index = "my-index", + id = "1", + body = { + "text": "OpenSearch is a search engine." + } +) + +<!-- spec_insert_end --> + +### 示例请求 + +检索词项向量: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/_termvectors/1 +body: | +{ + "fields": ["text"], + "term_statistics": true +} +--> + +GET /my-index/_termvectors/1 +{ + "fields": [ + "text" + ], + "term_statistics": true +} + +response = client.termvectors( + index = "my-index", + id = "1", + body = { + "fields": [ + "text" + ], + "term_statistics": true + } +) + +<!-- spec_insert_end --> + +或者,您可以将 `fields` 和 `term_statistics` 作为查询参数提供: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/_termvectors/1?fields=text&term_statistics=true +--> + +GET /my-index/_termvectors/1?fields=text&term_statistics=true + +response = client.termvectors( + index = "my-index", + id = "1", + params = { "fields": "text", "term_statistics": "true" } +) + +<!-- spec_insert_end --> + +### 示例响应 + +响应显示词项向量信息: + +```json +{ + "_index": "my-index", + "_id": "1", + "_version": 1, + "found": true, + "took": 1, + "term_vectors": { + "text": { + "field_statistics": { + "sum_doc_freq": 5, + "doc_count": 1, + "sum_ttf": 5 + }, + "terms": { + "a": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 2, + "start_offset": 14, + "end_offset": 15 + } + ] + }, + "engine": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 4, + "start_offset": 23, + "end_offset": 29 + } + ] + }, + "is": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 1, + "start_offset": 11, + "end_offset": 13 + } + ] + }, + "opensearch": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 0, + "start_offset": 0, + "end_offset": 10 + } + ] + }, + "search": { + "doc_freq": 1, + "ttf": 1, + "term_freq": 1, + "tokens": [ + { + "position": 3, + "start_offset": 16, + "end_offset": 22 + } + ] + } + } + } + } +} +``` + +## 响应正文字段 + +下表列出了所有响应正文字段。 + +| 字段 | 数据类型 | 说明 | +| `term_vectors` | Object | 包含每个指定字段的词项向量数据。 | +| `term_vectors.text` | Object | 包含 `text` 字段的词项向量详细信息。 | +| `term_vectors.text.field_statistics` | Object | 包含整个字段的统计信息。仅当 `field_statistics` 为 `true` 时才存在。 | +| `term_vectors.text.field_statistics.doc_count` | Integer | 包含指定字段中至少一个词项的文档数。 | +| `term_vectors.text.field_statistics.sum_doc_freq` | Integer | 字段中所有词项的文档频率总和。 | +| `term_vectors.text.field_statistics.sum_ttf` | Integer | 字段中所有词项的总词项频率(包括重复)总和。 | +| `term_vectors.text.terms` | Object | 一个映射,其中每个键是一个词项,每个值包含有关该词项的详细信息。 | +| `term_vectors.text.terms.<term>.term_freq` | Integer | 词项在文档中出现的次数。 | +| `term_vectors.text.terms.<term>.doc_freq` | Integer | 包含该词项的文档数。仅当 `term_statistics` 为 `true` 时才存在。 | +| `term_vectors.text.terms.<term>.ttf` | Integer | 所有文档中的总词项频率。仅当 `term_statistics` 为 `true` 时才存在。 | +| `term_vectors.text.terms.<term>.tokens` | Array | 提供有关各个词项实例信息的词元对象列表。 | +| `term_vectors.text.terms.<term>.tokens[].position` | Integer | 词元在文本中的位置。仅当 `positions` 为 `true` 时才存在。 | +| `term_vectors.text.terms.<term>.tokens[].start_offset` | Integer | 词元的起始字符偏移量。仅当 `offsets` 为 `true` 时才存在。 | +| `term_vectors.text.terms.<term>.tokens[].end_offset` | Integer | 词元的结束字符偏移量。仅当 `offsets` 为 `true` 时才存在。 | +| `term_vectors.text.terms.<term>.tokens[].payload` | String (Base64) | 与词元关联的可选有效负载数据。仅当 `payloads` 为 `true` 且可用时才存在。 | + +## 所需权限 + +如果使用安全插件,请确保您具有适当的权限:`indices:data/read/tv`。 diff --git a/i18n/zh/api-reference/grpc-apis/bulk.md b/i18n/zh/api-reference/grpc-apis/bulk.md new file mode 100644 index 00000000..15bfef2d --- /dev/null +++ b/i18n/zh/api-reference/grpc-apis/bulk.md @@ -0,0 +1,584 @@ +--- +title: Bulk (gRPC) +--- + +# Bulk API (gRPC) +<Badge type="tip" text="3.0 版本引入" /> + +gRPC Bulk API 为 [HTTP Bulk API](/api-reference/document-apis/bulk) 提供了一种高效的二进制编码替代方案,用于在单次调用中执行多个文档操作(如索引、更新和删除)。此服务使用 protocol buffers,并在参数和结构方面与 REST API 保持一致。 + +## 前提条件 + +要提交 gRPC 请求,您必须在客户端拥有一套 protobufs。有关获取 protobufs 的方法,请参阅[使用 gRPC APIs](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 + +## gRPC 服务和方法 + +gRPC Document APIs 位于 [DocumentService](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/document_service.proto#L22) 中。 + +您可以通过调用 [`Bulk`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/document_service.proto#L24) gRPC 方法提交批量请求。该方法接受一个 `DocumentService` 并返回一个 [`BulkRequest`](#bulkrequest-字段) [`BulkResponse`](#bulkresponse-字段)。 + +## 文档格式 + +::: info NOTE +在 gRPC 中,文档必须以字节形式提供和返回。请使用 Base64 编码在 gRPC 请求中提供文档。 +::: + +例如,考虑常规 Bulk API 请求中的以下文档: + +```json +"doc": "{\"title\": \"Inception\", \"year\": 2010}" +``` + +对于 gRPC Bulk API 请求,请使用 Base64 编码提供相同的文档: + +```json +"doc": "eyJ0aXRsZSI6ICJJbmNlcHRpb24iLCAieWVhciI6IDIwMTB9" +``` + +## BulkRequest 字段 + +The [`BulkRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L851) 消息是 gRPC 批量操作的顶级容器。它接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `bulk_request_body` | `repeated `[`BulkRequestBody`](#bulkrequestbody-字段) | 该list of bulk operations, each containing one of the operation types (`index`/`create`/`update`/`delete`)。必需。| +| `index` | `string` | 该default index for all operations unless overridden in `bulk_request_body`。Specifying the `index` 指定为 `BulkRequest` means that you don't need to include it 指定为 [BulkRequestBody](#bulkrequestbody-字段)。可选。| +| `x_source` | [`SourceConfigParam`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1251) | Controls whether to return the full `_source`, no `_source`, or only specific fields from `_source` 指定为 response。可选。| +| `x_source_excludes` | `repeated string` | Fields to exclude from `source`。可选。| +| `x_source_includes` | `repeated string` | Fields to include from `source`。可选。| +| `pipeline` | `string` | 该preprocessing ingest pipeline ID。可选。| +| `refresh` | [`Refresh`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3552) | Whether to refresh shards after indexing。可选。| +| `require_alias` | `bool` | If `true`, actions must target an alias。可选。| +| `routing` | `string` | 该routing value for shard assignment。可选。| +| `timeout` | `string` | 该timeout duration (for example, `1m`)。可选。| +| `type` (Deprecated) | `string` | 该document type (always `_doc`)。可选。| +| `wait_for_active_shards` | [`WaitForActiveShards`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1162) | 该minimum number of active shards to wait for。可选。| +| `global_params` | [`GlobalParams`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1150) | Global parameters for the request。可选。| + +## BulkRequestBody 字段 + +The [`BulkRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L894) 消息表示 `BulkRequest`中的单个文档级操作。它接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `operation_container` | [`OperationContainer`](#operationcontainer-fields) | 该operation to perform (`index`, `create`, `update`, or `delete`)。必需。| +| `update_action` | [`UpdateAction`](#updateaction-fields) | Additional update-specific options。可选。| +| `object` | `bytes` | 该full document content used with `create` and `index` operations。可选。| + +## OperationContainer 字段 + +The [`OperationContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L918) message contains exactly one operation type中的单个文档级操作。它接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `index` | [`IndexOperation`](#index) | Index a document。Replaces the document if it already exists。| +| `create` | [`WriteOperation`](#create) | Create a new document。Fails if the document already exists。| +| `update` | [`UpdateOperation`](#update) | Partially update a document or use upsert/script options。| +| `delete` | [`DeleteOperation`](#delete) | Delete a document by ID。| + +## UpdateAction 字段 + +The [`UpdateAction`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L936) message provides additional options for update operations中的单个文档级操作。它接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `detect_noop` | `bool` | If `true`, skips the update if the document content hasn't changed。Optional。Default is `true`。| +| `doc` | `bytes` | Partial or full document data for `update` operations。可选。| +| `doc_as_upsert` | `bool` | If `true`, treats the document 中将 the full upsert document if the target document doesn't exist。Only valid for the `update` operation。可选。| +| `script` | [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | A script to apply to the document (used with `update`)。可选。| +| `scripted_upsert` | `bool` | If `true`, executes the script whether or not the document exists。可选。| +| `upsert` | `bytes` | 该full document to use if the target does not exist。Used with `script`。可选。| +| `x_source` | [`SourceConfig`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1267) | Controls how the document source is fetched or filtered。可选。| + +### Create + +`WriteOperation` 仅在文档不存在时添加新文档。 + +文档本身必须在 `object` 字段中提供。`BulkRequestBody` 字段中提供。 + +还可以提供以下可选字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `x_id` | `string` | 该document ID。If omitted, one is auto-generated。可选。| +| `x_index` | `string` | 该target index。Required if not set globally 指定为 `BulkRequest`。可选。| +| `routing` | `string` | A custom routing value used to control shard placement。可选。| +| `pipeline` | `string` | 该preprocessing ingest pipeline ID。可选。| +| `require_alias` | `bool` | If `true`, requires that all actions target an index alias rather than an index。Default is `false`。可选。| + +#### 示例请求 + +The following example shows a bulk request with a `create` operation。It creates a document with the ID `tt1375666` 指定为 `movies` index。The document content, provided in Base64 encoding, represents `{"title": "Inception", "year": 2010}`: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "create": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "object": "eyJ0aXRsZSI6ICJJbmNlcHRpb24iLCAieWVhciI6IDIwMTB9" + } + ] +} +``` + +### Delete + +The `DeleteOperation` removes a document by ID中的单个文档级操作。它接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `x_id` | `string` | 该ID of the document to delete。必需。| +| `x_index` | `string` | 该target index。Required if not set globally 指定为 `BulkRequest`。可选。| +| `routing` | `string` | A custom routing value used to control shard placement。可选。| +| `if_primary_term` | `int64` | Used for concurrency control。The operation only runs if the document's primary term matches this value。可选。| +| `if_seq_no` | `int64` | Used for concurrency control。The operation only runs if the document's sequence number matches this value。可选。| +| `version` | `int64` | 该explicit document version for concurrency control。可选。| +| `version_type` | [`VersionType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3544) | Controls version matching behavior。可选。| + +#### 示例请求 + +The following example shows a bulk request with a `delete` operation。It deletes a document with the ID `tt1392214` from the `movies` index: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "delete": { + "x_index": "movies", + "x_id": "tt1392214" + } + } + } + ] +} +``` + +### Index + +The `IndexOperation` 创建或覆盖文档。如果未提供 ID,将生成一个。 + +文档本身在 `object` 字段中提供。`BulkRequestBody` 字段中提供。 + +还可以提供以下可选字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `x_id` | `string` | 该document ID。If omitted, one is auto-generated。可选。| +| `x_index` | `string` | 该target index。Required only if not set globally 指定为 `BulkRequest`。| +| `routing` | `string` | A custom routing value used to control shard placement。可选。| +| `if_primary_term` | `int64` | Used for concurrency control。The operation only runs if the document's primary term matches this value。可选。| +| `if_seq_no` | `int64` | Used for concurrency control。The operation only runs if the document's sequence number matches this value。可选。| +| `op_type` | [`OpType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3538) | 该operation type。Controls the overwriting behavior。Valid values are `index` (default) and `create`。可选。| +| `version` | `int64` | 该explicit document version for concurrency control。可选。| +| `version_type` | [`VersionType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3544) | Controls version matching behavior。可选。| +| `pipeline` | `string` | 该preprocessing ingest pipeline ID。可选。| +| `require_alias` | `bool` | If `true`, requires that all actions target an index alias rather than an index。Default is `false`。可选。| + +#### 示例请求 + +The following example shows a bulk request with an `index` operation。It indexes a Base64-encoded document with the ID `tt0468569` into the `movies` index: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "index": { + "x_index": "movies", + "x_id": "tt0468569" + } + }, + "object": "eyJ0aXRsZSI6ICJUaGUgRGFyayBLbmlnaHQiLCAieWVhciI6IDIwMDh9" + } + ] +} +``` + +### Update + +The `UpdateOperation` 执行部分文档更新。 + +更新选项在 `update_action` 消息中的 `BulkRequestBody` 字段中提供。 + +除了 `UpdateOperation` 之外,以下表中列出的所有 `x_id`。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `x_id` | `string` | 该ID of the document to update。必需。| +| `x_index` | `string` | 该target index。Required if not set globally 指定为 `BulkRequest`。可选。| +| `routing` | `string` | A custom routing value used to control shard placement。可选。| +| `if_primary_term` | `int64` | Used for concurrency control。The operation only runs if the document's primary term matches this value。可选。| +| `if_seq_no` | `int64` | Used for concurrency control。The operation only runs if the document's sequence number matches this value。可选。| +| `require_alias` | `bool` | If `true`, requires that all actions target an index alias rather than an index。Default is `false`。可选。| +| `retry_on_conflict` | `int32` | 该number of times to retry the operation if a version conflict occurs。可选。| + +#### 示例请求 + +The following example shows a bulk request with an `update` operation。It will update a document with the ID `tt1375666` 指定为 `movies` index to `{"year": 2011}`: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "update": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "update_action": { + "doc": "eyJ5ZWFyIjogMjAxMX0=", + "detect_noop": true + } + } + ] +} +``` + +### Upsert + +The `upsert` operation updates the document if it already exists。Otherwise, it creates a new document using the provided document content。 + +要执行 upsert 操作,请提供 `UpdateOperation` 并在 `doc_as_upsert` 中将 `true` 指定为 `BulkRequestBody`。The document to be upserted should be provided 指定为 `doc` field。 + +#### 示例请求 + +The following example shows a bulk request with an `upsert` operation。It updates the `year` 字段中提供。document with ID `tt1375666` 指定为 `movies` index to `{"year": 2012}`: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "update": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "update_action": { + "doc": "eyJ5ZWFyIjogMjAxMn0=", + "doc_as_upsert": true + } + } + ] +} +``` + +### Script + +Run a stored or inline script to modify a document。 + +要指定脚本,请提供 `UpdateOperation` 并在 `script` field 指定为 `BulkRequestBody`。 + +#### 示例请求 + +The following example shows a bulk request with a `script` operation。It increments the `year` 字段中提供。document with the ID `tt1375666` 指定为 `movies` index by 1: + +```json +{ + "index": "movies", + "bulk_request_body": [ + { + "operation_container": { + "update": { + "x_index": "movies", + "x_id": "tt1375666" + } + }, + "update_action": { + "script": { + "inline": { + "source": "ctx。_source。year += 1", + "lang": { + "builtin": "BUILTIN_SCRIPT_LANGUAGE_PAINLESS" + } + } + } + } + } + ] +} +``` + +## 响应字段 + +The gRPC Bulk API provides the following response fields。 + +### BulkResponse 字段 + +The [`BulkResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1059) 消息直接从 `Bulk` gRPC method and provides a summary and per-item result of a bulk operation。It contains the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `errors` | `bool` | Indicates whether any of the operations 指定为 bulk request failed。If any operation fails, the response's `errors` field will be `true`。You can iterate over the individual `Item` actions for more detailed information。| +| `items` | `repeated` [`Item`](#item-fields) | 该result of all operations 指定为 bulk request, 指定为 order they were submitted。| +| `took` | `int64` | 该amount of time taken to process the bulk request, in milliseconds。| +| `ingest_took` | `int64` | 该amount of time taken to process documents through an ingest pipeline, in milliseconds。| + +### Item 字段 + +响应中的每个 `Item` 指定为 response corresponds to a single operation 指定为 request。For each operation, only one of the following fields is provided。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `create` | [`ResponseItem`](#responseitem-fields) | 该result of the `CreateOperation`。| +| `delete` | [`ResponseItem`](#responseitem-fields) | 该result of the `DeleteOperation`。 | +| `index` | [`ResponseItem`](#responseitem-fields) | 该result of the `IndexOperation`。 | +| `update` | [`ResponseItem`](#responseitem-fields) | 该result of the `UpdateOperation`。 | + +### ResponseItem 字段 + +响应中的每个 `ResponseItem` corresponds to a single operation 指定为 request。It contains the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `type` | `string` | 该document type。| +| `id` | `string` | 该document ID associated with the operation。| +| `index` | `string` | 该name of the index associated with the operation。If a data stream was targeted, this is the backing index。| +| `status` | `int32` | 该HTTP status code returned for the operation。*(Note: This field may be replaced with a gRPC code 指定为 future。)* | +| `error` | [`ErrorCause`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1287) | Contains additional information about a failed operation。| +| `primary_term` | `int64` | 该primary term assigned to the document。| +| `result` | `string` | 该operation result。Valid values are `created`, `deleted`, and `updated`。| +| `seq_no` | `int64` | A sequence number assigned to the document to maintain version order。| +| `shards` | [`ShardInfo`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1332) | Shard information for the operation (only returned for successful actions)。| +| `version` | `int64` | 该document version (only returned for successful actions)。| +| `forced_refresh` | `bool` | If `true`, forces the document to become visible immediately after the operation。| +| `get` | [`InlineGetDictUserDefined`](#inlinegetdictuserdefined-fields) | Contains the document `source` returned from an inline get, if requested。| + +### InlineGetDictUserDefined 字段 + +The [`InlineGetDictUserDefined`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1126) message contains the document source returned from an inline get operation。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `metadata_fields` | `optional` [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | 该document's metadata fields。| +| `fields` | `optional` [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | 该document's stored fields。| +| `found` | `bool` | Whether the document exists。| +| `x_seq_no` | `optional int64` | 该document's sequence number。| +| `x_primary_term` | `optional int64` | 该document's primary term。| +| `x_routing` | `optional string` | 该document's routing value。| +| `x_source` | `optional bytes` | 该document's source data。| + +## 示例响应 + +```json +{ + "errors": false, + "items": [ + { + "index": { + "x_id": "2", + "x_index": "my_index", + "status": 201, + "x_primary_term": 1, + "result": "created", + "x_seq_no": 0, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 1, + "forced_refresh": true + } + }, + { + "create": { + "x_id": "1", + "x_index": "my_index", + "status": 201, + "x_primary_term": 1, + "result": "created", + "x_seq_no": 0, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 1, + "forced_refresh": true + } + }, + { + "update": { + "x_id": "2", + "x_index": "my_index", + "status": 200, + "x_primary_term": 1, + "result": "updated", + "x_seq_no": 1, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 2, + "forced_refresh": true, + "get": { + "found": true, + "x_seq_no": 1, + "x_primary_term": 1, + "x_source": "e30=" + } + } + }, + { + "delete": { + "x_id": "2", + "x_index": "my_index", + "status": 200, + "x_primary_term": 1, + "result": "deleted", + "x_seq_no": 2, + "x_shards": { + "successful": 1, + "total": 2 + }, + "x_version": 3, + "forced_refresh": true + } + } + ], + "took": 87, + "ingest_took": 0 +} +``` + +## Java gRPC 客户端示例 + +The following example shows a Java client-side program that submits an example bulk gRPC request and then checks whether there were any errors 指定为 bulk response: + +```java +import org。opensearch.protobufs。*; +import io。grpc。ManagedChannel; +import io。grpc。ManagedChannelBuilder; +import com。google.protobuf。ByteString; + +public class BulkClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder。forAddress("localhost", 9400) + 。usePlaintext() + 。build(); + + DocumentServiceGrpc。DocumentServiceBlockingStub stub = DocumentServiceGrpc。newBlockingStub(channel); + + // Create an index operation + IndexOperation indexOp = IndexOperation。newBuilder() + 。setXIndex("my-index") + 。setXId("1") + 。build(); + + BulkRequestBody indexBody = BulkRequestBody。newBuilder() + 。setOperationContainer(OperationContainer。newBuilder()。setIndex(indexOp)。build()) + 。setObject(ByteString。copyFromUtf8("{\"field\": \"value\"}")) + 。build(); + + // Create a delete operation + DeleteOperation deleteOp = DeleteOperation。newBuilder() + 。setXIndex("my-index") + 。setXId("2") + 。build(); + + BulkRequestBody deleteBody = BulkRequestBody。newBuilder() + 。setOperationContainer(OperationContainer。newBuilder()。setDelete(deleteOp)。build()) + 。build(); + + // Build the bulk request + BulkRequest request = BulkRequest。newBuilder() + 。setIndex("my-index") + 。addBulkRequestBody(indexBody) + 。addBulkRequestBody(deleteBody) + 。build(); + + // Execute the bulk request + try { + BulkResponse response = stub。bulk(request); + + // Handle the response + System。out。println("Bulk errors: " + response。getErrors()); + System。out。println("Bulk took: " + response。getTook() + " ms"); + if (response。hasIngestTook()) { + System。out。println("Ingest took: " + response。getIngestTook() + " ms"); + } + + // Process individual items + for (Item item : response。getItemsList()) { + if (item。hasIndex()) { + System。out。println("Index operation: " + item。getIndex()。getStatus()); + } else if (item。hasDelete()) { + System。out。println("Delete operation: " + item。getDelete()。getStatus()); + } else if (item。hasCreate()) { + System。out。println("Create operation: " + item。getCreate()。getStatus()); + } else if (item。hasUpdate()) { + System。out。println("Update operation: " + item。getUpdate()。getStatus()); + } + } + } catch (io。grpc。StatusRuntimeException e) { + System。err。println("gRPC request failed with status: " + e。getStatus()); + System。err。println("Error message: " + e。getMessage()); + } + + channel。shutdown(); + } +} +``` + +## Python gRPC 客户端示例 + +The following example shows how to send the same request using a Python client application。 + +首先,使用 `opensearch-protobufs` 安装 `pip`: + +```bash +pip install opensearch-protobufs==1。2。0 +``` + +Use the following code to send the request: + +```python +import grpc + +from opensearch.protobufs。schemas import * +from opensearch.protobufs。services import DocumentServiceStub + +channel = grpc。insecure_channel( + target="localhost:9400", +) + +document_stub = DocumentServiceStub(channel) + +# Add documents to a request body +requestBody = BulkRequestBody( + operation_container=OperationContainer(index=IndexOperation()) +) +requestBody。object = "{\"field\": \"value\"}"。encode('utf-8') + +# Append to a bulk request +request = BulkRequest() +request。index = "my-index" +request。bulk_request_body。append(requestBody) + +# Send request and handle response +try: + response = document_stub。Bulk(request=request) + if response。items: + print("Received {} response items"。format(len(response。items))) + print(response。items) +except grpc。RpcError 中将 e: + if e。code() == StatusCode。UNAVAILABLE: + print("Failed to reach server: {}"。format(e)) + elif e。code() == StatusCode。PERMISSION_DENIED: + print("Permission denied: {}"。format(e)) + elif e。code() == StatusCode。INVALID_ARGUMENT: + print("Invalid argument: {}"。format(e)) +finally: + channel。close() +``` diff --git a/i18n/zh/api-reference/grpc-apis/execute-agent-stream.md b/i18n/zh/api-reference/grpc-apis/execute-agent-stream.md new file mode 100644 index 00000000..b34a5453 --- /dev/null +++ b/i18n/zh/api-reference/grpc-apis/execute-agent-stream.md @@ -0,0 +1,188 @@ +--- +title: 流式执行代理(gRPC) +--- + +# 流式执行代理 API(gRPC) +<Badge type="tip" text="3.8 版本引入" /> + +gRPC 流式执行代理 API 提供了一个二进制接口,用于使用 protocol buffers 通过 gRPC 流式执行代理。服务器在代理生成响应块时将其流式传输到客户端,因此客户端可以在执行完成之前开始处理输出。对于从大型语言模型(LLM)生成逐令牌输出的对话代理,请使用流式传输。 + +您可以通过 REST 或 gRPC 流式执行代理。两种传输方式都返回相同的增量生成输出,因此请选择最适合您客户端的方式: + +- **REST 流式传输**使用 HTTP 上的服务器发送事件(SSE),浏览器、标准 HTTP 客户端和命令行工具(如 cURL)都直接支持。这是一个实验性功能,不建议在生产环境中使用。有关更多信息,请参阅[流式执行代理 API](/ml-commons-plugin/api/agent-apis/execute-stream-agent)。 +- **gRPC 流式传输**使用 HTTP/2 上的 protocol buffers。此传输提供更低的序列化开销和更小的有效负载、具有 HTTP/2 流量控制和连接多路复用的原生服务器流式传输语义,以及强类型 schema,您可以从中生成任何 [gRPC 支持语言](https://grpc.io/docs/languages/)的客户端。 + +支持以下外部托管模型的流式代理执行: + +- [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) +- [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +## 先决条件 + +在使用 gRPC 流式执行代理 API 之前,请确保您已满足以下先决条件: + +- 在集群上启用 gRPC 传输。有关更多信息,请参阅[使用 gRPC API](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 +- 在客户端获取 ML Commons protobuf。有关获取 protobuf 的方法,请参阅[使用 gRPC API](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 +- 注册使用支持流式传输模型的代理。有关代理和连接器配置,请参阅[流式执行代理 API](/ml-commons-plugin/api/agent-apis/execute-stream-agent#step-2-register-a-compatible-externally-hosted-model)。 + +## gRPC 服务和方法 + +gRPC 流式执行代理 API 位于 [`MLService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L22) 服务中。 + +您可以通过在 `MLService` 中调用 [`ExecuteAgentStream`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L27) 方法来提交流式代理执行请求。该方法接受一个 [`MlExecuteAgentStreamRequest`](#mlexecuteagentstreamrequest-fields) 并返回一个 [`PredictResponse`](#response-fields) 消息流。 + +::: info NOTE +`ExecuteAgentStream` 是一个服务器流式远程过程调用(RPC):客户端发送单个请求,服务器返回一系列响应消息。最终消息将 `is_last` 设置为 `true`,然后服务器关闭流。 +::: + +## 请求字段 + +gRPC 流式执行代理 API 支持以下请求字段。 + +### MlExecuteAgentStreamRequest 字段 + +[`MlExecuteAgentStreamRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3396) 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 必需 | 描述 | +| :---- | :---- | :---- | :---- | +| `agent_id` | `string` | 必需 | 要执行的代理的 ID。 | +| `ml_execute_agent_stream_request_body` | [`MLExecuteAgentStreamRequestBody`](#mlexecuteagentstreamrequestbody-fields) | 必需 | 包含执行参数的请求有效负载。 | + +<!-- vale off --> +### MLExecuteAgentStreamRequestBody 字段 +<!-- vale on --> + +[`MLExecuteAgentStreamRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3318) 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 必需 | 描述 | +| :---- | :---- | :---- | :---- | +| `parameters` | [`Parameters`](#parameters-fields) | 必需 | 传递给代理的输入参数。 | + +### Parameters 字段 + +对于代理执行,[`Parameters`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3356) 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `question` | `string` | 发送给代理的输入问题。 | + +## 响应字段 + +服务器流式传输一系列 [`PredictResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3367) 消息。每条消息携带一个生成输出的块,并提供以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `inference_results` | `repeated InferenceResults` | 该块的推理结果。 | +| `inference_results.output` | `repeated Output` | 每个推理结果的输出对象。 | +| `inference_results.output.name` | `string` | 输出字段的名称(通常是 `response`)。 | +| `inference_results.output.result` | `string` | `memory_id` 和 `parent_interaction_id` 字段的值。 | +| `inference_results.output.data_as_map` | `DataAsMap` | 该块的响应内容和元数据。 | +| `inference_results.output.data_as_map.content` | `string` | 该块的文本内容。连接各块的 `content` 值以重建完整响应。 | +| `inference_results.output.data_as_map.is_last` | `bool` | 这是否是流中的最后一个块。当为 `true` 时,不再发送更多消息。 | + +## 示例请求 + +以下示例显示了 gRPC 请求消息的 JSON 表示形式。将 `agent_id` 和 `question` 替换为与您的代理配置匹配的值: + +```json +{ + "agent_id": "your_agent_id", + "ml_execute_agent_stream_request_body": { + "parameters": { + "question": "List indices in my cluster" + } + } +} +``` + +以下示例显示了流式执行对话代理的 Java gRPC 客户端。将代理 ID 和问题替换为与您的代理配置匹配的值: + +```java +import org.opensearch.protobufs.*; +import org.opensearch.protobufs.services.MLServiceGrpc; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +import java.util.Iterator; + +public class ExecuteAgentStreamClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + // 为 ML 操作创建 gRPC stub + MLServiceGrpc.MLServiceBlockingStub mlStub = MLServiceGrpc.newBlockingStub(channel); + + // 为代理构建请求参数 + Parameters parameters = Parameters.newBuilder() + .setQuestion("List indices in my cluster") + .build(); + + // 创建流式代理执行请求 + MlExecuteAgentStreamRequest request = MlExecuteAgentStreamRequest.newBuilder() + .setAgentId("your_agent_id") + .setMlExecuteAgentStreamRequestBody(MLExecuteAgentStreamRequestBody.newBuilder() + .setParameters(parameters) + .build()) + .build(); + + // 执行请求并读取流式响应 + try { + Iterator<PredictResponse> responses = mlStub.executeAgentStream(request); + while (responses.hasNext()) { + PredictResponse response = responses.next(); + for (InferenceResults results : response.getInferenceResultsList()) { + for (Output output : results.getOutputList()) { + DataAsMap chunk = output.getDataAsMap(); + System.out.print(chunk.getContent()); + if (chunk.getIsLast()) { + System.out.println("\n[stream complete]"); + } + } + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC 执行代理流请求失败,状态: " + e.getStatus()); + System.err.println("错误消息: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` + +## 示例响应 + +服务器返回一系列 `PredictResponse` 消息。每条消息在 `content` 字段中携带一个生成文本块,最终消息将 `isLast` 设置为 `true`。以下示例显示了流式块的 JSON 表示形式: + +```json +{ + "inferenceResults": [ + { + "output": [ + { + "name": "memory_id", + "result": "6CMnkJ8BLGHoqtB13ipp" + }, + { + "name": "parent_interaction_id", + "result": "6SMnkJ8BLGHoqtB13irB" + }, + { + "name": "response", + "dataAsMap": { + "content": "Hello", + "isLast": false + } + } + ] + } + ] +} +``` + +## 相关文档 + +- [流式执行代理 API](/ml-commons-plugin/api/agent-apis/execute-stream-agent) -- 用于流式代理执行的 REST 等效项 +- [使用 gRPC API](/api-reference/grpc-apis/) -- gRPC 传输配置和客户端要求 diff --git a/i18n/zh/api-reference/grpc-apis/index.md b/i18n/zh/api-reference/grpc-apis/index.md new file mode 100644 index 00000000..93e161a5 --- /dev/null +++ b/i18n/zh/api-reference/grpc-apis/index.md @@ -0,0 +1,116 @@ +--- +title: gRPC APIs +description: "OpenSearch gRPC API 参考文档,包括使用 protocol buffers 进行高性能通信的批量操作和 k-NN 搜索操作。" +--- + +# gRPC APIs +<Badge type="tip" text="3.0 版本引入" /> + +<Badge type="tip" text="批量操作和 k-NN 搜索在 3.2 版本正式发布" /> + +::: info NOTE +gRPC [批量 API](/api-reference/grpc-apis/bulk) 和 [k-NN 搜索查询](/api-reference/grpc-apis/knn) 现已正式发布。这些 API 使用 [protobuf 版本 1.2.0](https://github.com/opensearch-project/opensearch-protobufs/releases/tag/1.2.0)。但是,随着功能在未来版本中的成熟,protobuf 结构可能会有更新。其他 gRPC 搜索功能仍处于实验阶段,不建议在生产环境中使用。有关这些功能进展的更新或留下反馈,请参阅相关的 [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/16787)。 +::: + +OpenSearch gRPC 功能提供了一种替代的高性能传输层,使用 [gRPC](https://grpc.io/) 与 OpenSearch 进行通信。它通过 gRPC 使用 protocol buffers,降低开销并加快序列化速度。这减少了开销,加快了序列化,并根据初步基准测试结果改善了请求端延迟。有关更多信息,请参阅[性能优势](#grpc-performance-benefits)。 + +## 支持的 API + +支持以下 gRPC API: +- [批量操作](/api-reference/grpc-apis/bulk) **3.2 版本正式发布** +- [k-NN](/api-reference/grpc-apis/knn) **3.2 版本正式发布** +- [搜索](/api-reference/grpc-apis/search)(针对特定查询类型) +- [流式预测模型](/api-reference/grpc-apis/predict-model-stream) +- [流式执行代理](/api-reference/grpc-apis/execute-agent-stream) + +## 如何使用 gRPC API + +要使用 gRPC API,请按照以下步骤操作: +1. 通过配置必要的 [gRPC 设置](#grpc-settings)启用 gRPC 传输。 + +2. 要提交 gRPC 请求,您必须在客户端拥有一组 protobuf。您可以通过以下方式获取 protobuf。 + +| 语言 | 分发方式 | 说明 | +| :------- | :------------------ | :----------- | +| Java | Maven Central 仓库 | 从 [Maven Central 仓库](https://repo1.maven.org/maven2/org/opensearch/protobufs/1.2.0) 下载 `opensearch-protobufs` jar。 | +| Python | PyPI 仓库 | 从 [PyPI 仓库](https://pypi.org/project/opensearch-protobufs/1.2.0) 下载 `opensearch-protobufs` 包。 | +| 其他语言 | GitHub 仓库(原始 protobuf) | 从 [OpenSearch Protobufs GitHub 仓库 (v1.2.0)](https://github.com/opensearch-project/opensearch-protobufs/releases/tag/1.2.0) 下载原始 protobuf schema。然后,您可以使用 protocol buffer 编译器为[支持的语言](https://grpc.io/docs/languages/)生成客户端代码。 | + +## gRPC 设置 + +`transport-grpc` 模块默认包含在 OpenSearch 安装中。要启用它,请将以下设置添加到 `opensearch.yml`: + +```yaml +aux.transport.types: [transport-grpc] +aux.transport.transport-grpc.port: '9400-9500' // 可选 +``` + +或者,使用以下设置配置安全传输协议: + +```yaml +aux.transport.types: [secure-transport-grpc] +aux.transport.transport-grpc.port: '9400-9500' // 可选 +``` + +如果需要,配置其他设置(参阅[高级 gRPC 设置](#advanced-grpc-settings)): + +```yaml +grpc.host: localhost +grpc.publish_host: 10.74.124.163 +grpc.bind_host: 0.0.0.0 +``` + +### 高级 gRPC 设置 + +OpenSearch 支持以下 gRPC 通信的高级设置。这些设置可以在 `opensearch.yml` 中配置。 + +| 设置名称 | 描述 | 示例值 | 默认值 | +| :---- | :---- | :---- | :---- | +| `grpc.publish_port` | 此节点用于向对等节点发布自身以进行 gRPC 传输的外部端口号。 | `9400` | `-1`(禁用) | +| `grpc.host` | gRPC 服务器将绑定的地址列表。 | `["0.0.0.0"]` | `[]` | +| `grpc.bind_host` | 用于绑定 gRPC 服务器的地址列表。可以与发布主机不同。 | `["0.0.0.0", "::"]` | `grpc.host` 的值 | +| `grpc.publish_host` | 发布给对等节点以供客户端连接的主机名或 IP 列表。 | `["thisnode.example.com"]` | `grpc.host` 的值 | +| `grpc.netty.worker_count` | gRPC 服务器的 Netty 工作线程数。控制并发性和并行性。 | `2` | 处理器数量 | +| `grpc.netty.executor_count` | fork-join 池中用于处理 gRPC 服务调用的线程数。控制请求处理并行性。 | `32` | `2 * 处理器数量` | +| `grpc.netty.max_concurrent_connection_calls` | 每个客户端连接允许的最大同时进行中请求数。 | `200` | `100` | +| `grpc.netty.max_connection_age` | 连接在被优雅关闭之前可以达到的最大存活时间。支持时间单位,如 `ms`、`s` 或 `m`。请参阅[时间单位](/api-reference/units#time-units)。 | `500ms` | 未设置(无限制) | +| `grpc.netty.max_connection_idle` | 连接在被关闭之前可以保持空闲的最大持续时间。支持时间单位,如 `ms`、`s` 或 `m`。请参阅[时间单位](/api-reference/units#time-units)。 | `2m` | 未设置(无限制) | +| `grpc.netty.keepalive_timeout` | 在关闭连接之前等待 `keepalive` ping 确认的时间。支持[时间单位](/api-reference/units#time-units)。 | `1s` | 未设置 | +| `grpc.netty.max_msg_size` | gRPC 请求的最大入站消息大小。支持单位,如 `b`、`kb`、`mb` 或 `gb`。请参阅[支持的单位](/api-reference/units)。 | `10mb` 或 `10485760` | `10mb` | + +### 示例配置 + +以下是 `opensearch.yml` 中完整的 gRPC 配置示例: + +```yaml +# 基本 gRPC 传输配置 +aux.transport.types: [transport-grpc] +aux.transport.transport-grpc.port: '9400-9500' + +# 高级 gRPC 设置 +grpc.host: ["0.0.0.0"] +grpc.bind_host: ["0.0.0.0", "::"] +grpc.publish_host: ["thisnode.example.com"] +grpc.publish_port: 9400 +grpc.netty.worker_count: 4 +grpc.netty.max_concurrent_connection_calls: 200 +grpc.netty.max_connection_age: 500ms +grpc.netty.max_connection_idle: 2m +grpc.netty.keepalive_timeout: 1s +grpc.netty.max_msg_size: 10mb +``` + +这些设置类似于 [HTTP 网络设置](/install-and-configure/configuring-opensearch/network-settings#advanced-http-settings),但专门应用于 gRPC 通信。 + +## gRPC 性能优势 + +使用 gRPC API 相比 HTTP API 具有以下几个优势: + +- **降低延迟**:二进制 protocol buffers 消除了 JSON 解析开销。 +- **更高吞吐量**:对于高频查询更有效地利用网络。 +- **更低的 CPU 使用率**:降低序列化和反序列化成本。 +- **类型安全**:protocol buffer schema 提供编译时验证。 +- **更小的有效负载大小**:二进制编码减少网络流量。 + +### 额外的性能提示 +将文档索引为支持的二进制格式(如 SMILE)通常会比将它们作为 JSON 索引/搜索产生更低的延迟。索引和搜索延迟都应该降低。 diff --git a/i18n/zh/api-reference/grpc-apis/knn.md b/i18n/zh/api-reference/grpc-apis/knn.md new file mode 100644 index 00000000..51b4bbea --- /dev/null +++ b/i18n/zh/api-reference/grpc-apis/knn.md @@ -0,0 +1,153 @@ +--- +title: k-NN(gRPC) +--- + +# k-NN(gRPC)API +<Badge type="tip" text="3.2 版本引入" /> + +gRPC k-NN API 已正式发布。但是,随着功能在未来版本中的成熟,protobuf 结构可能会有更新。 + +gRPC k-NN API 提供了一个高效的二进制编码接口,用于使用 protocol buffers 通过 gRPC 执行 k-近邻搜索。k-NN 插件为向量相似性搜索提供了特定的搜索查询类型。与传统的基于 HTTP 的方法相比,此 API 提供了卓越的性能,非常适合大规模机器学习和向量数据库应用。 + +有关基于 HTTP 的 k-NN 查询的信息,请参阅 [k-NN 查询](/query-dsl/specialized/k-nn/)。 + +## 先决条件 + +要提交 gRPC 请求,您必须在客户端拥有一组 protobuf。有关获取 protobuf 的方法,请参阅[使用 gRPC API](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 + +## gRPC 服务和方法 + +gRPC k-NN API 位于 [`SearchService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L22) 中,这是用于一般搜索操作的相同服务。 + +您可以通过在 `SearchService` 中调用 [`Search`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L23) gRPC 方法,在搜索请求中使用 [`KnnQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2023) 来提交 k-NN 搜索请求。该方法接受一个 [`SearchRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L20) 并返回一个 [`SearchResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L262)。 + +gRPC 实现使用与 HTTP API 相同的底层 k-NN 功能,同时通过 protocol buffer 序列化提供改进的性能。 + +## KnnQuery 字段 + +gRPC k-NN API 在 [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) 中使用 [`KnnQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2023) 消息进行 k-NN 搜索。`KnnQuery` 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 要执行搜索查询的向量字段。必需。 | +| `vector` | `repeated float` | 查询向量。必须与向量字段具有相同的维度数。可选。 | +| `k` | `int32` | 要作为热门结果返回的最近邻数量。可选。 | +| `min_score` | `float` | 邻居被视为匹配项所需的最小相似度分数。可选。 | +| `max_distance` | `float` | 邻居被视为匹配项所需的向量空间中的最大物理距离。可选。 | +| `filter` | [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | k-NN 搜索查询的过滤器。请参阅[过滤器限制](#filter-limitations)。可选。 | +| `boost` | `float` | 用于增加或减少相关性分数的提升值。默认值为 1.0。可选。 | +| `underscore_name` | `string` | 用于查询标记的查询名称(JSON 键:`_name`)。可选。 | +| `method_parameters` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | 特定于算法的参数(例如,`ef_search` 或 `nprobes`)。可选。 | +| `rescore` | [`KnnQueryRescore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2073) | 用于提高准确性的重新评分配置。在 2.17 之后的版本中可用。可选。 | +| `expand_nested_docs` | `bool` | 当为 `true` 时,检索每个父文档中所有嵌套字段文档的分数。与嵌套查询一起使用。可选。 | + +## 示例请求 + +以下示例显示了带有 k-NN 查询的 gRPC 搜索请求。它在 `vector_index` 索引的 `my_vector` 字段中搜索与查询向量 `[0.1, 0.2, 0.3, 0.4]` 最相似的 10 个向量: + +```json +{ + "index": ["vector_index"], + "search_request_body": { + "query": { + "knn": { + "field": "my_vector", + "vector": [0.1, 0.2, 0.3, 0.4], + "k": 10 + } + }, + "size": 10 + } +} +``` + +## Java gRPC 客户端示例 + +以下是使用 gRPC k-NN API 的基本示例(实际实现取决于您的 gRPC 客户端设置): + +```java +import org.opensearch.protobufs.*; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +public class KnnGrpcClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + // 为搜索操作创建 gRPC stub + SearchServiceGrpc.SearchServiceBlockingStub searchStub = + SearchServiceGrpc.newBlockingStub(channel); + + // 使用 protocol buffers 构建 k-NN 查询 + QueryContainer knnQuery = QueryContainer.newBuilder() + .setKnn(KnnQuery.newBuilder() + .setField("my_vector") + .addAllVector(Arrays.asList(0.1f, 0.2f, 0.3f, 0.4f)) + .setK(10) + .build()) + .build(); + + // 创建搜索请求 + SearchRequest request = SearchRequest.newBuilder() + .addIndex("vector_index") + .setSearchRequestBody(SearchRequestBody.newBuilder() + .setQuery(knnQuery) + .setSize(10) + .build()) + .build(); + + // 执行搜索 + try { + SearchResponse response = searchStub.search(request); + + // 处理响应 + System.out.println("搜索耗时: " + response.getTook() + " ms"); + + HitsMetadata hits = response.getHits(); + if (hits.hasTotal()) { + System.out.println("找到 " + hits.getTotal().getTotalHits().getValue() + " 个结果"); + } + + // 处理带有相似度分数的 k-NN 结果 + for (HitsMetadataHitsInner hit : hits.getHitsList()) { + System.out.println("文档 ID: " + hit.getXId()); + if (hit.hasXScore()) { + System.out.println("相似度分数: " + hit.getXScore().getDouble()); + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC k-NN 搜索请求失败,状态: " + e.getStatus()); + System.err.println("错误消息: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` + +## 响应字段 + +k-NN 搜索请求返回与常规搜索操作相同的 [`SearchResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L262) 结构。有关响应字段的信息,请参阅[搜索(gRPC)响应字段](/api-reference/grpc-apis/search#response-fields)。 + +响应包括标准搜索元数据(`took`、`timed_out` 和 `shards`)以及一个包含 k-NN 文档及其相似度分数的 `hits` 数组。 + +## 过滤器限制 + +与 HTTP API 相比,gRPC k-NN API 对 `filter` 子句的支持有限。有关 gRPC 中当前支持的查询类型列表,请参阅[搜索 API QueryContainer 文档](/api-reference/grpc-apis/search#querycontainer-fields)和[支持的查询](/api-reference/grpc-apis/search#supported-queries)。 + +对于复杂的过滤要求,请考虑使用 HTTP k-NN API,简化过滤逻辑,或等待下一版本的 k-NN gRPC。 + +## 相关 API + +- [搜索(gRPC)](/api-reference/grpc-apis/search) - 一般 gRPC 搜索功能 +- [批量操作(gRPC)](/api-reference/grpc-apis/bulk) - 使用 gRPC 的批量操作 +- [k-NN 查询](/query-dsl/specialized/k-nn/) - 基于 HTTP 的 k-NN 查询文档 + +## 下一步 + +- 了解更多关于 [OpenSearch 中的向量搜索](/search-plugins/knn/)。 +- 探索 [k-NN 索引设置](/search-plugins/knn/knn-index)。 +- 查看 [k-NN 性能调优](/search-plugins/knn/performance-tuning)。 +- 阅读 [gRPC 配置](/api-reference/grpc-apis/#grpc-settings)。 diff --git a/i18n/zh/api-reference/grpc-apis/predict-model-stream.md b/i18n/zh/api-reference/grpc-apis/predict-model-stream.md new file mode 100644 index 00000000..498ac211 --- /dev/null +++ b/i18n/zh/api-reference/grpc-apis/predict-model-stream.md @@ -0,0 +1,240 @@ +--- +title: 流式预测模型(gRPC) +--- + +# 流式预测模型 API(gRPC) +<Badge type="tip" text="3.8 版本引入" /> + +gRPC 流式预测模型 API 提供了一个二进制接口,用于使用 protocol buffers 通过 gRPC 从远程机器学习(ML)模型流式预测。服务器在底层模型生成响应块时将其流式传输到客户端,因此客户端可以在推理完成之前开始处理输出。对于大型语言模型(LLM)的逐令牌生成,请使用流式传输。 + +您可以通过 REST 或 gRPC 流式预测。两种传输方式都返回相同的增量生成模型输出,因此请选择最适合您客户端的方式: + +- **REST 流式传输**使用 HTTP 上的服务器发送事件(SSE),浏览器、标准 HTTP 客户端和命令行工具(如 cURL)都直接支持。这是一个实验性功能,不建议在生产环境中使用。有关更多信息,请参阅[流式预测 API](/ml-commons-plugin/api/train-predict/predict-stream)。 +- **gRPC 流式传输**使用 HTTP/2 上的 protocol buffers。此传输提供更低的序列化开销和更小的有效负载、具有 HTTP/2 流量控制和连接多路复用的原生服务器流式传输语义,以及强类型 schema,您可以从中生成任何 [gRPC 支持语言](https://grpc.io/docs/languages/)的客户端。 + +支持以下外部托管模型的流式预测: + +- [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) +- [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +## 先决条件 + +在使用 gRPC 流式预测模型 API 之前,请确保您已满足以下先决条件: + +- 在集群上启用 gRPC 传输。有关更多信息,请参阅[使用 gRPC API](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 +- 在客户端获取 ML Commons protobuf。有关获取 protobuf 的方法,请参阅[使用 gRPC API](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 +- 为支持的模型类型配置外部托管模型和流式连接器。有关模型和连接器配置,请参阅[流式预测 API](/ml-commons-plugin/api/train-predict/predict-stream#step-2-register-a-compatible-externally-hosted-model)。 + +## gRPC 服务和方法 + +gRPC 流式预测模型 API 位于 [`MLService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L22) 服务中。 + +您可以通过在 `MLService` 中调用 [`PredictModelStream`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/services/ml_service.proto#L24) 方法来提交流式预测请求。该方法接受一个 [`MlPredictModelStreamRequest`](#mlpredictmodelstreamrequest-fields) 并返回一个 [`PredictResponse`](#response-fields) 消息流。 + +::: info NOTE +`PredictModelStream` 是一个服务器流式远程过程调用(RPC):客户端发送单个请求,服务器返回一系列响应消息。最终消息将 `is_last` 设置为 `true`,然后服务器关闭流。 +::: + +## 请求字段 + +gRPC 流式预测模型 API 支持以下请求字段。 + +### MlPredictModelStreamRequest 字段 + +[`MlPredictModelStreamRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3406) 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 必需 | 描述 | +| :---- | :---- | :---- | :---- | +| `model_id` | `string` | 必需 | 要运行预测的模型的 ID。该模型必须是支持的外部托管模型。 | +| `ml_predict_model_stream_request_body` | [`MLPredictModelStreamRequestBody`](#mlpredictmodelstreamrequestbody-fields) | 必需 | 包含预测参数的请求有效负载。 | + +<!-- vale off --> +### MLPredictModelStreamRequestBody 字段 +<!-- vale on --> + +[`MLPredictModelStreamRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3323) 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 必需 | 描述 | +| :---- | :---- | :---- | :---- | +| `parameters` | [`Parameters`](#parameters-fields) | 必需 | 传递给远程模型的输入参数。 | + +### Parameters 字段 + +对于流式预测,[`Parameters`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3356) 消息接受以下字段。提供与您的模型类型匹配的字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `messages` | `repeated` [`Messages`](#messages-fields) | 发送到聊天完成模型的对话消息,例如 OpenAI Chat Completion。 | +| `inputs` | `string` | 发送到模型的输入文本,例如使用 Amazon Bedrock Converse Stream 模型时。 | +| `x_llm_interface` | `string` | 与您的模型类型对应的 LLM 接口。有效值为 `openai/v1/chat/completions` 和 `bedrock/converse/claude`。 | + +### Messages 字段 + +[`Messages`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3328) 消息接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `role` | `string` | 消息发送者的角色,例如 `system` 或 `user`。 | +| `content` | `string` | 消息内容。 | + +## 响应字段 + +服务器流式传输一系列 [`PredictResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.6.0/protos/schemas/common.proto#L3367) 消息。每条消息携带一个生成输出的块,并提供以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `inference_results` | `repeated InferenceResults` | 该块的推理结果。 | +| `inference_results.output` | `repeated Output` | 每个推理结果的输出对象。 | +| `inference_results.output.name` | `string` | 输出字段的名称(通常是 `response`)。 | +| `inference_results.output.data_as_map` | `DataAsMap` | 该块的响应内容和元数据。 | +| `inference_results.output.data_as_map.content` | `string` | 该块的文本内容。连接各块的 `content` 值以重建完整响应。 | +| `inference_results.output.data_as_map.is_last` | `bool` | 这是否是流中的最后一个块。当为 `true` 时,不再发送更多消息。 | + +## 示例请求 + +携带模型输入的字段和 `x_llm_interface` 值都取决于模型类型。以下示例显示了每种支持的模型类型的 gRPC 请求消息的 JSON 表示形式。在两个示例中,将 `model_id` 替换为您注册的模型的 ID。 + +对于 OpenAI Chat Completion 模型,在 `messages` 字段中提供对话,并将 `x_llm_interface` 设置为 `openai/v1/chat/completions`: + +```json +{ + "model_id": "your_model_id", + "ml_predict_model_stream_request_body": { + "parameters": { + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Can you summarize Prince Hamlet of William Shakespeare in around 100 words?" + } + ], + "x_llm_interface": "openai/v1/chat/completions" + } + } +} +``` + +对于 Amazon Bedrock Converse Stream 模型,在 `inputs` 字段中提供输入文本,并将 `x_llm_interface` 设置为 `bedrock/converse/claude`: + +```json +{ + "model_id": "your_model_id", + "ml_predict_model_stream_request_body": { + "parameters": { + "inputs": "Can you summarize Prince Hamlet of William Shakespeare in around 100 words?", + "x_llm_interface": "bedrock/converse/claude" + } + } +} +``` + +以下示例显示了从 OpenAI Chat Completion 模型流式预测的 Java gRPC 客户端。将模型 ID 和消息替换为与您的模型配置匹配的值: + +```java +import org.opensearch.protobufs.*; +import org.opensearch.protobufs.services.MLServiceGrpc; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +import java.util.Iterator; + +public class PredictModelStreamClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9400) + .usePlaintext() + .build(); + + // 为 ML 操作创建 gRPC stub + MLServiceGrpc.MLServiceBlockingStub mlStub = MLServiceGrpc.newBlockingStub(channel); + + // 为 OpenAI Chat Completion 模型构建请求参数 + Parameters parameters = Parameters.newBuilder() + .addMessages(Messages.newBuilder() + .setRole("system") + .setContent("You are a helpful assistant.") + .build()) + .addMessages(Messages.newBuilder() + .setRole("user") + .setContent("Can you summarize Prince Hamlet of William Shakespeare in around 100 words?") + .build()) + .setXLlmInterface("openai/v1/chat/completions") + .build(); + + // 创建流式预测请求 + MlPredictModelStreamRequest request = MlPredictModelStreamRequest.newBuilder() + .setModelId("your_model_id") + .setMlPredictModelStreamRequestBody(MLPredictModelStreamRequestBody.newBuilder() + .setParameters(parameters) + .build()) + .build(); + + // 执行请求并读取流式响应 + try { + Iterator<PredictResponse> responses = mlStub.predictModelStream(request); + while (responses.hasNext()) { + PredictResponse response = responses.next(); + for (InferenceResults results : response.getInferenceResultsList()) { + for (Output output : results.getOutputList()) { + DataAsMap chunk = output.getDataAsMap(); + System.out.print(chunk.getContent()); + if (chunk.getIsLast()) { + System.out.println("\n[stream complete]"); + } + } + } + } + } catch (io.grpc.StatusRuntimeException e) { + System.err.println("gRPC 预测流请求失败,状态: " + e.getStatus()); + System.err.println("错误消息: " + e.getMessage()); + } + + channel.shutdown(); + } +} +``` + +对于 Amazon Bedrock Converse Stream 模型,使用 `setInputs` 而不是 `addMessages` 构建请求参数。其余客户端代码保持不变: + +```java +Parameters parameters = Parameters.newBuilder() + .setInputs("Can you summarize Prince Hamlet of William Shakespeare in around 100 words?") + .setXLlmInterface("bedrock/converse/claude") + .build(); + +MlPredictModelStreamRequest request = MlPredictModelStreamRequest.newBuilder() + .setModelId("your_model_id") + .setMlPredictModelStreamRequestBody(MLPredictModelStreamRequestBody.newBuilder() + .setParameters(parameters) + .build()) + .build(); +``` + +## 示例响应 + +服务器返回一系列 `PredictResponse` 消息。每条消息在 `content` 字段中携带一个生成文本块,最终消息将 `isLast` 设置为 `true`。以下示例显示了流式块的 JSON 表示形式: + +```json +{ + "inferenceResults": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "content": "Hello", + "isLast": false + } + } + ] + } + ] +} +``` + +## 相关文档 + +- [流式预测 API](/ml-commons-plugin/api/train-predict/predict-stream) -- 用于流式预测的 REST 等效项 +- [使用 gRPC API](/api-reference/grpc-apis/) -- gRPC 传输配置和客户端要求 diff --git a/i18n/zh/api-reference/grpc-apis/search.md b/i18n/zh/api-reference/grpc-apis/search.md new file mode 100644 index 00000000..1b03b854 --- /dev/null +++ b/i18n/zh/api-reference/grpc-apis/search.md @@ -0,0 +1,1105 @@ +--- +title: Search (gRPC) +--- + +# Search API (gRPC) +<Badge type="tip" text="3.0 版本引入" /> + +::: danger WARNING +This is an experimental feature and is not recommended for use in a production environment。For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/OpenSearch/issues/16787)。 +::: + +gRPC Search API 通过 gRPC 使用 protocol buffers 提供了一个高性能的二进制接口来运行[查询](/api-reference/search)。它镜像了 HTTP Search API 的功能,同时受益于 protobuf 类型契约和 gRPC 传输。gRPC APIs 是低延迟、高吞吐量应用程序的理想选择。 + +## 前提条件 + +要提交 gRPC 请求,您必须在客户端拥有一套 protobufs。有关获取 protobufs 的方法,请参阅[使用 gRPC APIs](/api-reference/grpc-apis/#how-to-use-grpc-apis)。 + +## gRPC 服务和方法 + +gRPC Document APIs 位于 [`SearchService`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L22) 中。 + +您可以通过调用 [`Search`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/services/search_service.proto#L23) gRPC 方法提交批量请求。该方法接受一个 `SearchService` 并返回一个 [`SearchRequest`](#searchrequest-字段) [`SearchResponse`](#searchresponse-字段)。 + +::: info NOTE +See [Supported Queries](#supported-queries) for supported search queries。Additional query types will be supported in future versions。 +::: + +## 请求字段 + +The gRPC Search API supports the following request fields。 + +### SearchRequest 字段 + +The [`SearchRequest`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L20) message accepts the following fields。除了 fields are optional。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `index` | `repeated string` | A list of indexes to search。If not provided, defaults to all indexes。| +| `x_source` | [`SourceConfigParam`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1251) | Controls whether to return the full `_source`, no `_source`, or only specific fields from `_source` 指定为 response。| +| `x_source_excludes` | `repeated string` | Fields to exclude from `_source`。Ignored if `source` is `false`。| +| `x_source_includes` | `repeated string` | Fields to include in `_source`。Ignored if `source` is `false`。 | +| `allow_no_indices` | `bool` | Whether to ignore wildcards that match no indexes。Default is `true`。| +| `allow_partial_search_results` | `bool` | Whether to return partial results upon an error or timeout。Default is `true`。| +| `analyze_wildcard` | `bool` | Whether to analyze wildcard/prefix queries。Default is `false`。 | +| `batched_reduce_size` | `int32` | 该number of shards to reduce on a node。Default is `512`。 | +| `cancel_after_time_interval` | `string` | 该time after which the request will be canceled。Default is `-1`。| +| `ccs_minimize_roundtrips` | `bool` | Whether to minimize round trips between the node and remote clusters。Default is `true`。 | +| `default_operator` | [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | 该default operator for query strings。Valid values are `AND` or `OR`。Default is `OR`。 | +| `df` | `string` | 该default field for query strings without field prefixes。 | +| `docvalue_fields` | `repeated string` | 该fields to return 中将 doc values。| +| `expand_wildcards` | `repeated` [`ExpandWildcard`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3567) | 该type of index that wildcard expressions can match。Valid values are `all` (match any index), `open` (match open, non-hidden indexes), `closed` (match closed, non-hidden indexes), `hidden` (match hidden indexes), and `none` (deny wildcard expressions)。Default is `open`。| +| `ignore_throttled` | `bool` | Whether to ignore frozen indexes when resolving aliases。Default is `true`。| +| `ignore_unavailable` | `bool` | Whether to ignore unavailable indexes or shards。Default is `false`。| +| `max_concurrent_shard_requests` | `int32` | 该number of concurrent shard requests per node。Default is `5`。| +| `phase_took` | `bool` | Whether to return phase-level `took` values。Default is `false`。| +| `pre_filter_shard_size` | `int32` | 该threshold at which to trigger prefiltering by shard size。Default is `128`。| +| `preference` | `string` | 该shard or node preferences for query execution。| +| `q` | `string` | 该query string in [Lucene syntax](/query-dsl/full-text/query-string#query-string-syntax)。| +| `request_cache` | `bool` | Whether to use the request cache。Defaults to the index's settings。| +| `total_hits_as_int` | `bool` | Whether to return the number of total hits 中将 an integer。Default is `false`。| +| `routing` | `repeated string` | 该routing values used to direct requests to specific shards。| +| `scroll` | `string` | 该amount of time to keep the search context alive for scrolling。| +| `search_type` | [`SearchType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3576) | 该method for calculating relevance scores。Valid values are `QUERY_THEN_FETCH` and `DFS_QUERY_THEN_FETCH`。Default is `QUERY_THEN_FETCH`。| +| `suggest_field` | `string` | 该field on which to base suggestions。| +| `suggest_mode` | [`SuggestMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3582) | 该suggestion mode (for example, `always`, `missing`, `popular`)。| +| `suggest_size` | `int32` | 该number of suggestions to return。| +| `suggest_text` | `string` | 该input text for generating suggestions。| +| `typed_keys` | `bool` | Whether to include type information in aggregation and suggestion keys。Default is `true`。| +| `search_request_body` | [`SearchRequestBody`](#searchrequestbody-fields) | 该main search request payload, including the query and filters。| +| `global_params` | [`GlobalParams`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1150) | Global parameters for the request。可选。| + +### SearchRequestBody 字段 + +The [`SearchRequestBody`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L123) message accepts the following fields。除了 fields are optional。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `collapse` | [`FieldCollapse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1974) | Groups the results by a field。Returns only the top document per group。| +| `explain` | `bool` | Returns scoring explanations for matched documents。| +| `ext` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | Plugin-specific metadata, for example, for extensions like RAG。| +| `from` | `int32` | 该starting index for paginated results。Default is `0`。| +| `highlight` | [`Highlight`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1728) | Highlights matched terms 指定为 result snippets。| +| `track_total_hits` | [`TrackHits`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L252) | Whether to return the total hit count。| +| `indices_boost` | `map<string, float>` | **Deprecated。** Use `indices_boost_2` instead。| +| `docvalue_fields` | `repeated` [`FieldAndFormat`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1965) | 该fields to return in their `doc_values` form。You can include a format for the returned values (for example, a date format)。For `knn_vector` fields, supported formats are `binary` (default, Base64-encoded) and `array` (JSON numeric arrays)。For more information, see [Retrieving vector fields using `docvalue_fields`](/search-plugins/searching-data/retrieve-specific-fields#retrieving-vector-fields-using-docvalue_fields)。| +| `min_score` | `float` | 该minimum score required in order for a document to be included 指定为 results。| +| `post_filter` | [`QueryContainer`](#querycontainer-fields) | Filters hits after aggregations are applied。| +| `profile` | `bool` | Enables profiling to analyze query performance。| +| `search_pipeline` | `string` | 该name of the search pipeline to apply。| +| `verbose_pipeline` | `bool` | Enables verbose logging 指定为 search pipeline。| +| `query` | [`QueryContainer`](#querycontainer-fields) | 该query domain-specific language (DSL) for the search。| +| `rescore` | `repeated` [`Rescore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L504) | Reranks the top N hits to improve precision。| +| `script_fields` | `map<string, `[`ScriptField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1677)`>` | Custom fields whose values are computed by scripts。| +| `search_after` | `repeated` [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | Cursor-based pagination using values from the previous page。| +| `size` | `int32` | 该number of results to return。Default is `10`。| +| `slice` | [`SlicedScroll`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L513) | Splits scroll context into slices for parallel processing。| +| `sort` | `repeated` [`SortCombinations`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1693) | 该sorting rules (for example, by field, score, or custom order)。| +| `x_source` | [`SourceConfig`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1267) | Controls whether to return the full `_source`, no `_source`, or only specific fields from `_source` 指定为 response。| +| `fields` | `repeated` [`FieldAndFormat`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1965) | Additional fields to return, with formatting options。| +| `terminate_after` | `int32` | 该maximum number of matching documents (hits) to process before early termination。Default is `0`。| +| `timeout` | `string` | 该maximum amount of time to wait for query execution。| +| `track_scores` | `bool` | Whether to return document scores 指定为 results。| +| `include_named_queries_score` | `bool` | Whether to include scores for named queries。| +| `version` | `bool` | Whether to include the document version 指定为 response。| +| `seq_no_primary_term` | `bool` | Whether to include the sequence number and primary term for each hit。| +| `stored_fields` | `repeated string` | 该stored fields to return (excludes `_source` unless re-enabled)。| +| `pit` | [`PointInTimeReference`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L612) | 该Point in Time reference used to search a fixed snapshot。| +| `stats` | `repeated string` | 该tagging or logging fields to associate with the request。| +| `derived` | `map<string, `[`DerivedField`](#derivedfield-fields)`>` | Dynamically computed fields returned 指定为 response。| +| `indices_boost_2` | `repeated` [`FloatMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3004) | 该current protobuf representation for per-index boost multipliers。响应中的每个 entry contains an index-to-boost mapping。| +| `aggregations` | `map<string, `[`AggregationContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3026)`>` | Aggregations to compute 中将 part of the search request。| + +### DerivedField 字段 + +The [`DerivedField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L228) message is used for dynamically computed fields that are calculated during search execution中的单个文档级操作。它接受以下字段。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `name` | `string` | 该name of the derived field。必需。| +| `type` | `string` | 该data type of the derived field。必需。| +| `script` | [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | 该script that computes the field value。必需。| +| `prefilter_field` | `string` | 该field to use for prefiltering to optimize script execution。可选。| +| `properties` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | Additional properties for the derived field。可选。| +| `ignore_malformed` | `bool` | Whether to ignore malformed values during field computation。可选。| +| `format` | `string` | 该format to apply to the field value (for example, date formatting)。可选。| + +### QueryContainer 字段 + +`QueryContainer` is the entry point for all supported query types。 + +在每个 `QueryContainer` 字段中提供。 + +::: info NOTE +Note that some query types are currently unsupported。See [Supported queries](#supported-queries) for the current list of implemented query types。 +::: + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `bool` | [`BoolQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2133) | A Boolean query that combines multiple clauses using `AND`, `OR`, or `NOT` logic。Must be the only field set。| +| `constant_score` | [`ConstantScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2171) | Wraps a filter 并在ssigns a constant relevance score to all matching documents。Must be the only field set。| +| `function_score` | [`FunctionScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2183) | Adjusts the scores of the results using custom functions。Must be the only field set。| +| `exists` | [`ExistsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1986) | Matches documents that contain a specific field。Must be the only field set。| +| `fuzzy` | [`FuzzyQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2593) | Matches terms similar to the search term (fuzzy matching)。Must be the only field set。| +| `ids` | [`IdsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2648) | Matches documents by `_id` values。Must be the only field set。| +| `prefix` | [`PrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2309) | Matches terms with a specific prefix。Must be the only field set。| +| `range` | [`RangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2460) | Matches terms within a specified range。Must be the only field set。| +| `regexp` | [`RegexpQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2391) | Matches terms using regular expressions。Must be the only field set。| +| `term` | [`TermQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2421) | Matches exact terms (no analysis)。Must be the only field set。| +| `terms` | [`TermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1587) | Matches any document containing one or more specified terms in a field。Must be the only field set。| +| `terms_set` | [`TermsSetQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2370) | Matches documents containing a minimum number of exact terms in a field。Must be the only field set。| +| `wildcard` | [`WildcardQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1998) | Matches terms using a wildcard pattern。Must be the only field set。| +| `match` | [`MatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2082) | Performs a full-text match on text or exact-value fields。Must be the only field set。| +| `match_bool_prefix` | [`MatchBoolPrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2668) | Matches full words and prefixes in a Boolean-style query。Must be the only field set。| +| `match_phrase` | [`MatchPhraseQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2746) | Matches an exact phrase in order。Must be the only field set。| +| `match_phrase_prefix` | [`MatchPhrasePrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2719) | Matches a phrase in which the last term is treated 中将 a prefix。Must be the only field set。| +| `multi_match` | [`MultiMatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2770) | Searches multiple fields using a single query string。Must be the only field set。| +| `knn` | [`KnnQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2023) | A k-NN query across vector fields。Must be the only field set。| +| `match_all` | [`Match除了Query`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2659) | Matches all documents 指定为 index。Must be the only field set。| +| `match_none` | [`MatchNoneQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2710) | Matches no documents。Must be the only field set。| +| `nested` | [`NestedQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1602) | Wraps a query targeting nested fields。Must be the only field set。| +| `geo_distance` | [`GeoDistanceQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1560) | Returns documents containing geopoints within a specified distance from a provided geopoint。Must be the only field set。| +| `geo_bounding_box` | [`GeoBoundingBoxQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1483) | Returns documents containing geopoints within a specified bounding box。Must be the only field set。| +| `script` | [`ScriptQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1471) | Filters documents based on a custom condition written in Painless scripting language。Must be the only field set。| +| `hybrid` | [`HybridQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1453) | Combines relevance scores from multiple queries into one score。Must be the only field set。| + +## 支持的查询 + +The gRPC Search API supports the following query types: +* Term-level: `exists`, `fuzzy`, `ids`, `prefix`, `range`, `regexp`, `term`, `terms`, `terms_set`, `wildcard` +* Full-text: `match`, `match_bool_prefix`, `match_phrase`, `match_phrase_prefix`, `multi_match` +* Match all: `match_all`, `match_none` +* Compound queries: `bool`, `constant_score`, `function_score`, `hybrid` +* Geographic: `geo_bounding_box`, `geo_distance` +* Joining queries: `nested` +* Specialized queries: `knn`, `script` + +For more information about these query types, see [Query DSL](/query-dsl/)。 + +### Term-level query fields + +The following sections describe the fields for each term-level query 字段中提供。 + +#### ExistsQuery 字段 + +The [`ExistsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1986) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The name of the field to search。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| + +#### FuzzyQuery 字段 + +The [`FuzzyQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2593) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `value` | [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | 必需。The term to search for 指定为 specified field。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `max_expansions` | `optional int32` | 该maximum number of terms to which the query can expand。Default is `50`。| +| `prefix_length` | `optional int32` | 该number of leading characters that are not considered in fuzziness。Default is `0`。| +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `rewrite` instead。| +| `transpositions` | `optional bool` | Specifies whether to allow transpositions of two adjacent characters 中将 edits。Default is `true`。| +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | 该number of character edits (insert, delete, or substitute) that it takes to change one word to another when determining whether a term matched a value。| +| `rewrite` | `optional string` | Determines how OpenSearch rewrites the query。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +#### IdsQuery 字段 + +The [`IdsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2648) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `values` | `repeated string` | 该document IDs to search for。| + +#### PrefixQuery 字段 + +The [`PrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2309) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `value` | `string` | 必需。The term to search for 指定为 specified field。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `rewrite` instead。| +| `case_insensitive` | `optional bool` | 除了ows ASCII case-insensitive matching。Default is `false`。| +| `rewrite` | `optional string` | Determines how OpenSearch rewrites the query。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +#### RangeQuery 字段 + +The [`RangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2460) message is a `oneof` type that can contain either a [`NumberRangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2469) or a [`DateRangeQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2530)。 + +##### NumberRangeQuery 字段 + +The `NumberRangeQuery` message accepts the following fields。 + +he `NumberRangeQuery` message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `relation` | `optional` [`RangeRelation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3589) | Indicates how the range query matches values for range fields。| +| `gt` | `optional double` | Greater than。| +| `gte` | `optional double` | Greater than or equal to。| +| `lt` | `optional double` | Less than。| +| `lte` | `optional double` | Less than or equal to。| +| `from` | `optional` [`NumberRangeQuery除了OfFrom`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2508) | 该starting value for the range。| +| `to` | `optional` [`NumberRangeQuery除了OfTo`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2519) | 该ending value for the range。| +| `include_lower` | `optional bool` | Whether to include the lower bound。| +| `include_upper` | `optional bool` | Whether to include the upper bound。| + +##### DateRangeQuery 字段 + + The `DateRangeQuery` message accepts the following fields。 + +The `DateRangeQuery` message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `relation` | `optional` [`RangeRelation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3589) | Indicates how the range query matches values for range fields。| +| `gt` | `optional string` | Greater than。| +| `gte` | `optional string` | Greater than or equal to。| +| `lt` | `optional string` | Less than。| +| `lte` | `optional string` | Less than or equal to。| +| `from` | `optional` [`DateRangeQuery除了OfFrom`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2575) | 该starting value for the range。| +| `to` | `optional` [`DateRangeQuery除了OfTo`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2584) | 该ending value for the range。| +| `format` | `optional string` | 该date format pattern。| +| `time_zone` | `optional string` | 该time zone identifier。| +| `include_lower` | `optional bool` | Whether to include the lower bound。| +| `include_upper` | `optional bool` | Whether to include the upper bound。| + +#### RegexpQuery 字段 + +The [`RegexpQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2391) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `value` | `string` | 必需。A regular expression for terms to search for 指定为 provided field。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `case_insensitive` | `optional bool` | 除了ows case-insensitive matching of the regular expression。Default is `false`。| +| `flags` | `optional string` | Enables optional operators for the regular expression。| +| `max_determinized_states` | `optional int32` | 该maximum number of automaton states the query requires。Default is `10000`。| +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `rewrite` instead。| +| `rewrite` | `optional string` | Determines how OpenSearch rewrites and scores multi-term queries。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +#### TermQuery 字段 + +The [`TermQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2421) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `value` | [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | 必需。The term to search for 指定为 provided field。Must exactly match the field value。| +| `case_insensitive` | `optional bool` | 除了ows ASCII case-insensitive matching。Default is `false`。| + +#### TermsQuery 字段 + +The [`TermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1587) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `value_type` | `optional` [`TermsQueryValueType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3612) | 该types of values used for filtering。Valid values are `default` and `bitmap`。Default is `default`。| +| `terms` | `map<string, `[`TermsQueryField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2333)`>` | A map of field names to term values or term lookups。| + +#### TermsQueryField 字段 + +The [`TermsQueryField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2333) message accepts one of the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `value` | [`FieldValueArray`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2365) | An explicit list of term values to match。| +| `lookup` | [`TermsLookup`](#termslookup-fields) | Fetches the term values from another document。| + +#### TermsLookup 字段 + +The [`TermsLookup`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2342) message accepts the following fields。Set either `id_2` or `query` to identify the lookup document。If neither is set, the deprecated `id` field is used。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `index` | `string` | 该name of the index from which to fetch the terms。| +| `path` | `string` | 该path to the field 指定为 lookup document that contains the term values。| +| `id_2` | `string` | 该ID of the document from which to fetch the terms。| +| `query` | [`QueryContainer`](#querycontainer-fields) | A query that selects the document or documents from which to fetch the terms。| +| `routing` | `optional string` | 该routing value used to locate the lookup document。| +| `store` | `optional bool` | Whether to read the term values from the stored field instead of `_source`。| +| `id` | `string` | **Deprecated。** Use `id_2` instead。The ID of the document from which to fetch the terms。| + +#### TermsSetQuery 字段 + +The [`TermsSetQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2370) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `terms` | `repeated string` | 必需。The array of terms to search for 指定为 specified field。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `minimum_should_match_field` | `optional string` | 该name of the numeric field that specifies the number of matching terms required。| +| `minimum_should_match_script` | `optional` [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | A script that returns the number of matching terms required。| + +#### WildcardQuery 字段 + +The [`WildcardQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1998) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `case_insensitive` | `optional bool` | 除了ows case-insensitive matching。Default is `false`。| +| `rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `rewrite` instead。| +| `value` | `optional string` | A wildcard pattern used for matching terms 指定为 specified field。Required when `wildcard` is not set。| +| `wildcard` | `optional string` | A wildcard pattern used for matching terms 指定为 specified field。Required when `value` is not set。| +| `rewrite` | `optional string` | Determines how OpenSearch rewrites the query。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +### Full-text query fields + +The following sections describe the fields for each full-text query 字段中提供。 + +The following sections describe the fields for each full-text query 字段中提供。 + +#### MatchQuery 字段 + +The [`MatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2082) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `query` | [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | 必需。The query string to use for search。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `analyzer` | `optional string` | 该analyzer used to tokenize the query string text。| +| `auto_generate_synonyms_phrase_query` | `optional bool` | Specifies whether to create a match phrase query automatically for multi-term synonyms。| +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | 该number of character edits (insertions, deletions, substitutions, or transpositions) that it takes to change one word to another when determining whether a term matched a value。| +| `fuzzy_rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `fuzzy_rewrite` instead。| +| `fuzzy_transpositions` | `optional bool` | Adds swaps of adjacent characters to the fuzziness operations。Default is `true`。| +| `lenient` | `optional bool` | Ignores data type mismatches between the query and the document field。Default is `false`。| +| `max_expansions` | `optional int32` | 该maximum number of terms to which the query can expand。Default is `50`。| +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) | 该number of terms that need to match for the document to be considered a match。| +| `operator` | `optional` [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | Whether all terms need to match (`AND`) or only one term needs to match (`OR`)。Default is `OR`。| +| `prefix_length` | `optional int32` | 该number of leading characters that are not considered in fuzziness。Default is `0`。| +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms。Default is `none`。| +| `fuzzy_rewrite` | `optional string` | Determines how OpenSearch rewrites the query。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +#### MatchBoolPrefixQuery 字段 + +The [`MatchBoolPrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2668) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `query` | `string` | 必需。The terms to search for 指定为 provided field。The last term is used in a prefix query。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `analyzer` | `optional string` | 该analyzer used to tokenize the query string text。| +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | 该number of character edits (insertions, deletions, substitutions, or transpositions) that it takes to change one word to another when determining whether a term matched a value。| +| `fuzzy_rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `fuzzy_rewrite` instead。| +| `fuzzy_transpositions` | `optional bool` | Adds swaps of adjacent characters to the fuzziness operations。Default is `true`。| +| `max_expansions` | `optional int32` | 该maximum number of terms to which the query can expand。Default is `50`。| +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) | 该number of terms that need to match for the document to be considered a match。| +| `operator` | `optional` [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | Whether all terms need to match (`AND`) or only one term needs to match (`OR`)。Default is `OR`。| +| `prefix_length` | `optional int32` | 该number of leading characters that are not considered in fuzziness。Default is `0`。| +| `fuzzy_rewrite` | `optional string` | Determines how OpenSearch rewrites the query。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +#### MatchPhraseQuery 字段 + +The [`MatchPhraseQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2746) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `query` | `string` | 必需。The query string to use for search。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `analyzer` | `optional string` | 该analyzer used to tokenize the query string text。| +| `slop` | `optional int32` | 该number of other words permitted between words 指定为 query phrase。Default is `0` (exact match)。| +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms。Default is `none`。| + +#### MatchPhrasePrefixQuery 字段 + +The [`MatchPhrasePrefixQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2719) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `field` | `string` | 必需。The field against which to run a search query。| +| `query` | `string` | 必需。The query string to use for search。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `analyzer` | `optional string` | 该analyzer used to tokenize the query string text。| +| `max_expansions` | `optional int32` | 该maximum number of terms to which the query can expand。Default is `50`。| +| `slop` | `optional int32` | 该number of other words permitted between words 指定为 query phrase。Default is `0` (exact match)。| +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms。Default is `none`。| + +#### MultiMatchQuery 字段 + +The [`MultiMatchQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2770) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `query` | `string` | 必需。The query string to use for search。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `analyzer` | `optional string` | 该analyzer used to tokenize the query string text。| +| `auto_generate_synonyms_phrase_query` | `optional bool` | Specifies whether to create a match phrase query automatically for multi-term synonyms。Default is `true`。| +| `fields` | `repeated string` | 该list of fields in which to search。| +| `fuzzy_rewrite_deprecated` | `optional` [`MultiTermQueryRewrite`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3652) | **Deprecated。** Use `fuzzy_rewrite` instead。| +| `fuzziness` | `optional` [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) | 该number of character edits (insertions, deletions, substitutions, or transpositions) that it takes to change one word to another when determining whether a term matched a value。| +| `fuzzy_transpositions` | `optional bool` | Adds swaps of adjacent characters to the fuzziness operations。Default is `true`。| +| `lenient` | `optional bool` | Ignores data type mismatches between the query and the document field。Default is `false`。| +| `max_expansions` | `optional int32` | 该maximum number of terms to which the query can expand。Default is `50`。| +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) | 该number of terms that need to match for the document to be considered a match。| +| `operator` | `optional` [`Operator`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3646) | Whether all terms need to match (`AND`) or only one term needs to match (`OR`)。Default is `OR`。| +| `prefix_length` | `optional int32` | 该number of leading characters that are not considered in fuzziness。Default is `0`。| +| `slop` | `optional int32` | 该number of other words permitted between words 指定为 query phrase。Supported for `phrase` and `phrase_prefix` query types。| +| `tie_breaker` | `optional float` | A factor between `0` and `1.0` used to assign more weight to documents matching multiple query clauses。| +| `type` | `optional` [`TextQueryType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3596) | 该multi-match query type。Valid values are `best_fields`, `most_fields`, `cross_fields`, `phrase`, `phrase_prefix`, `bool_prefix`。Default is `best_fields`。| +| `zero_terms_query` | `optional` [`ZeroTermsQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3606) | Specifies whether to match no documents (`none`) or all documents (`all`) when the analyzer removes all terms。Default is `none`。| +| `fuzzy_rewrite` | `optional string` | Determines how OpenSearch rewrites the query。See [Rewrite parameter values](#rewrite-parameter-values)。Default is `constant_score`。| + +#### Match除了Query 字段 + +The [`Match除了Query`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2659) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| + +#### MatchNoneQuery 字段 + +The [`MatchNoneQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2710) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| + +### Compound query fields + +The following sections describe the fields for each compound query 字段中提供。 + +The following sections describe the fields for each compound query 字段中提供。 + +#### BoolQuery 字段 + +The [`BoolQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2133) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `filter` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2142) | 该clause (query) that must appear in matching documents。The query score is ignored。| +| `minimum_should_match` | `optional` [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2145) | 该minimum number of `should` clauses that must match。| +| `must` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2148) | 该clause (query) must appear in matching documents and contributes to the score。| +| `must_not` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2151) | 该clause (query) that must not appear in matching documents。A score of `0` is returned for all documents。| +| `should` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2154) | 该clause (query) that should appear 指定为 matching document。| +| `adjust_pure_negative` | `optional bool` | Ensures correct behavior when a query contains only `must_not` clauses。Default is `true`。| + +#### ConstantScoreQuery 字段 + +The [`ConstantScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2171) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `filter` | [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | 必需。The filter query that a document must match to be returned 指定为 results。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| + +#### FunctionScoreQuery 字段 + +The [`FunctionScoreQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2183) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `boost_mode` | `optional` [`FunctionBoostMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3626) | Determines how the computed function score is combined with the query score。| +| `functions` | `repeated` [`FunctionScoreContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2210) | 该score functions。响应中的每个 entry may set `filter`, `weight`, and one of `exp`, `gauss`, `linear`, `field_value_factor`, `random_score`, or `script_score`。| +| `max_boost` | `optional float` | 该maximum boost value that a function can apply to a document score。| +| `min_score` | `optional float` | Excludes documents with a score below this threshold from the results。| +| `query` | `optional` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | 该query used to select documents before applying score functions。| +| `score_mode` | `optional` [`FunctionScoreMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3636) | Determines how scores from multiple functions are combined into a single score。| + +For more information, see [Function score query](/query-dsl/compound/function-score)。 + +### Joining query fields + +The following sections describe the fields for each joining query 字段中提供。 + +The following sections describe the fields for each joining query 字段中提供。 + +#### NestedQuery 字段 + +The [`NestedQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1602) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `path` | `string` | 必需。The path to a field or an array of paths to fields in which to search。| +| `query` | [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | 必需。The query to run on the nested objects within the specified path。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `ignore_unmapped` | `optional bool` | Set to `true` to ignore an unmapped field and not match any documents。Default is `false`。| +| `inner_hits` | `optional` [`InnerHits`](#innerhits-fields) | If provided, returns the underlying hits that matched the query。| +| `score_mode` | `optional` [`ChildScoreMode`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3800) | Defines how scores of matching inner documents influence the parent document's score。| + +### Geographic query fields + +The following sections describe the fields for each geographic query 字段中提供。 + +The following sections describe the fields for each geographic query 字段中提供。 + +#### GeoBoundingBoxQuery 字段 + +A geo-bounding box query returns documents whose geopoints are within the bounding box specified 指定为 query。The [`GeoBoundingBoxQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1483) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `type` | `optional` [`GeoExecution`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3815) | 该execution type for the geographic query。| +| `validation_method` | `optional` [`GeoValidationMethod`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3662) | 该validation method。Valid values are `IGNORE_MALFORMED`, `COERCE`, and `STRICT`。Default is `STRICT`。| +| `ignore_unmapped` | `optional bool` | Specifies whether to ignore an unmapped field。Default is `false`。| +| `bounding_box` | `map<string, `[`GeoBounds`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1504)`>` | A map of field names to geobounds defining the bounding box。| + +#### GeoDistanceQuery 字段 + +A geodistance query returns documents with geopoints that are within a specified distance from the provided geopoint。The [`GeoDistanceQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1560) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `distance` | `string` | 必需。The distance within which to match the points。This distance is the radius of a circle centered at the specified point。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `distance_type` | `optional` [`GeoDistanceType`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3750) | Specifies how to calculate the distance。Valid values are `arc` and `plane`。Default is `arc`。| +| `validation_method` | `optional` [`GeoValidationMethod`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3662) | 该validation method。Valid values are `IGNORE_MALFORMED`, `COERCE`, and `STRICT`。Default is `STRICT`。| +| `ignore_unmapped` | `optional bool` | Set to `true` to ignore an unmapped field and not match any documents。Default is `false`。| +| `unit` | `optional` [`DistanceUnit`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3787) | 该unit of distance measurement。| +| `location` | `map<string, `[`GeoLocation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1214)`>` | A map of field names to `geolocations` specifying the center point。| + +### Specialized query fields + +The following sections describe the fields for each specialized query 字段中提供。 + +For `knn` query fields, see [k-NN (gRPC)](/api-reference/grpc-apis/knn)。 + +#### ScriptQuery 字段 + +A script query filters documents based on a custom condition written 指定为 Painless scripting language。For more information, see [Painless scripting language](/scripting/painless/)。The [`ScriptQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1471) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `script` | [`Script`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1171) | 必需。The script to execute for filtering documents。| +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| + +#### HybridQuery 字段 + +A hybrid query combines relevance scores from multiple queries into one score for a given document。The [`HybridQuery`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1453) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `boost` | `optional float` | A floating-point number used to decrease or increase the relevance scores of the query。Default is `1.0`。| +| `x_name` | `optional string` | A query name for query tagging。| +| `queries` | `repeated` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | An array of one or more query clauses that are used to match documents。A document must match at least one query clause in order to be returned 指定为 results。The documents' relevance scores from all query clauses are combined into one score by applying a search pipeline。The maximum number of query clauses is 5。| +| `pagination_depth` | `optional int32` | 该pagination depth for the hybrid query。| +| `filter` | `optional` [`QueryContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1368) | A filter to apply to all subqueries of the hybrid query。| + +### AggregationContainer 字段 + +`AggregationContainer` defines the aggregation to run。Specify exactly one of the following fields in each `AggregationContainer` 字段中提供。 + +::: info NOTE +The gRPC Search API supports only the following aggregation types: `max`, `min`, and `terms`。 +::: + +The [`AggregationContainer`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3026) message wraps a single aggregation definition 并在ccepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `meta` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | 可选 custom metadata attached to the aggregation。| +| `max` | [`MaxAggregation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3101) | A [`max`](/aggregations/metric/maximum) metric aggregation。Must be the only aggregation type set。| +| `min` | [`MinAggregation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3115) | A [`min`](/aggregations/metric/minimum) metric aggregation。Must be the only aggregation type set。| +| `terms_aggregation` | [`TermsAggregation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3179) | A [`terms`](/aggregations/bucket/terms) bucket aggregation that groups documents by term values。Must be the only aggregation type set。| + +### Common message values + +The following sections describe the values used by common message types。 + +#### Fuzziness + +The [`Fuzziness`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2626) message is a `oneof` type that accepts the following values。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `string` | `string` | `AUTO` generates an edit distance based on the length of the term。You can optionally provide `AUTO:[low],[high]`。| +| `int32` | `int32` | `0`, `1`, or `2`: The maximum allowed [Damerau–Levenshtein distance](https://en。wikipedia。org/wiki/Damerau%E2%80%93Levenshtein_distance)。For more information, see [Fuzziness](/query-dsl/fuzziness)。| + +#### Rewrite parameter values + +Multi-term queries like `wildcard`, `prefix`, `regexp`, `fuzzy`, and `range` expand internally into sets of terms。The `rewrite` and `fuzzy_rewrite` parameters control how these term expansions are executed and scored。 + +The rewrite parameter gives you control over how multi-term queries behave internally。 + +::: info NOTE +| Value | Scoring | Performance | Notes | +| :---- | :---- | :---- | :---- | +| `constant_score` | Same score for all matches | Best | Default mode, ideal for filters。| +| `scoring_boolean` | TF/IDF-based | Moderate | Full relevance scoring。| +| `constant_score_boolean` | Same score with Boolean structure | Moderate | Use with `must_not` or `minimum_should_match`。| +| `top_terms_<n>` | TF/IDF on top `<n>` terms | Efficient | Truncates expansion to top scoring terms。| +| `top_terms_boost_<n>` | Static boosts | Fast | Less accurate scoring。| +| `top_terms_blended_freqs_<n>` | Blended score | Balanced | Best scoring/efficiency trade-off。| +::: + +#### MinimumShouldMatch + +The [`MinimumShouldMatch`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2160) message is a `oneof` type that accepts the following values。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `int32` | `int32` | An integer specifying the minimum number of terms that should match。| +| `string` | `string` | A string specifying a percentage or combination。See [Minimum should match](/query-dsl/minimum-should-match)。| + +#### FieldValue + +The [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) message represents a field value 并在ccepts the following values。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `bool` | `optional bool` | A Boolean value。| +| `general_number` | `optional` [`GeneralNumber`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3915) | A numeric value。| +| `string` | `optional string` | A string value。| +| `null_value` | `optional` [`NullValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3925) | A null value。| + +#### InnerHits 字段 + +The [`InnerHits`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1626) message accepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `name` | `optional string` | 该name to be used for the particular inner hit definition 指定为 response。| +| `size` | `optional int32` | 该maximum number of hits to return in `inner_hits`。| +| `from` | `optional int32` | 该starting document offset for an inner hit。| +| `collapse` | `optional` [`FieldCollapse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1974) | Groups search results by a particular field value。| +| `docvalue_fields` | `repeated` [`FieldAndFormat`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1965) | 该fields that OpenSearch should return using their `doc_values`。| +| `explain` | `optional bool` | Whether to return details about how OpenSearch computed the document's score。Default is `false`。| +| `highlight` | `optional` [`Highlight`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1728) | Highlighting emphasizes the search term(s) 指定为 results。| +| `ignore_unmapped` | `optional bool` | Specifies how to treat an unmapped field。Default is `false`。| +| `script_fields` | `map<string, `[`ScriptField`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1677)`>` | Custom fields whose values are computed using scripts。| +| `seq_no_primary_term` | `optional bool` | Whether to return sequence number and primary term of the last operation of each document hit。| + +除了 of the following examples show valid request payloads that can be sent to the `SearchService/Search` gRPC method。 + +### Match all query + +A `match_all` query returns all documents 指定为 index。For example, the following request returns a maximum of 50 documents from the index: + +```json +{ + "search_request_body": { + "query": { + "match_all": {} + }, + "size": 50 + } +} +``` + +### Term query + +A `term` query matches a single field with a specific term。For example, the following query searches for titles containing the word `Rush`: + +```json +{ + "index": "my_index", + "search_request_body": { + "query": { + "term": { + "field": "title", + "value": { + "string_value": "Rush" + }, + "case_insensitive": true + } + } + } +} +``` + +### Terms query + +A `terms` query matches documents in which a specific field contains any value from a list。For example, the following query searches for lines with the IDs `61809` and `61810`: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "line_id": { + "value": { + "field_value_array": [ + { "string": "61809" }, + { "string": "61810" } + ] + } + } + } + } + } + } +} +``` + +### Terms query with a terms lookup + +A `terms` query with a `terms` lookup is a specialized form of the `terms` query that allows you to fetch the terms for filtering from another document in your cluster rather than specifying them directly 指定为 query。The lookup document is identified by either `id_2` (a document ID) or `query` (a query that selects the source document or documents)。For example, the following request matches documents 指定为 `students` index whose `_id` matches one of the values 指定为 `enrolled` array of the `classes` document with the ID `class_1`: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "_id": { + "lookup": { + "index": "classes", + "id_2": "class_1", + "path": "enrolled" + } + } + } + } + } + } +} +``` + +To select the lookup document using a query rather than an ID, use the `query` field: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "_id": { + "lookup": { + "index": "classes", + "path": "enrolled", + "query": { + "match_all": {} + } + } + } + } + } + } + } +} +``` + +The deprecated `id` field is still honored for backward compatibility when neither `id_2` nor `query` is set: + +```json +{ + "search_request_body": { + "query": { + "terms": { + "terms": { + "_id": { + "lookup": { + "index": "classes", + "id": "class_1", + "path": "enrolled" + } + } + } + } + } + } +} +``` + +### Match none query + +A `match_none` query matches none of the documents: + +```json +{ + "search_request_body": { + "query": { + "match_none": {} + } + } +} +``` + +## 响应字段 + +The gRPC Search API returns the following response fields。 + +### SearchResponse 字段 + +The following table lists the supported fields for the [`SearchResponse`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L262) 字段中提供。 + +::: info NOTE +The source documents are returned 中将 bytes。Use Base64 decoding to read the `_source` field 指定为 gRPC response。 +::: + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `took` | `int64` | 该amount of time taken to process the search request, in milliseconds。| +| `timed_out` | `bool` | Whether the search timed out。| +| `x_shards` | [`ShardStatistics`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1311) | 该shard-level success/failure/total metadata。| +| `phase_took` | [`PhaseTook`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L330) | 该phase-level `took` time values 指定为 response。| +| `hits` | [`HitsMetadata`](#hitsmetadata-fields) | 该main document results and metadata。| +| `processor_results` | `repeated` [`ProcessorExecutionDetail`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L306) | Processor execution details。| +| `x_clusters` | [`ClusterStatistics`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L471) | Information about the search on each cluster when searching remote clusters。| +| `fields` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | **Deprecated。** Retrieved specific fields 指定为 search response。| +| `num_reduce_phases` | `int32` | 该number of times that the coordinating node aggregates results from batches of shard responses。| +| `profile` | [`Profile`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L483) | Profiling data for query execution (debugging/performance insights)。| +| `pit_id` | `string` | 该Point in Time ID。| +| `x_scroll_id` | `string` | 该identifier for the search and its search context。| +| `terminated_early` | `bool` | Whether the query was terminated early。| +| `aggregations` | `map<string, `[`Aggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3009)`>` | Aggregation results returned with the search response。| + +### Aggregate 字段 + +The [`Aggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3009) message represents a single aggregation result 并在ccepts the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `dterms` | [`DoubleTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3040) | A `terms` aggregation with double-valued bucket keys。| +| `lterms` | [`LongTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3066) | A `terms` aggregation with signed-long bucket keys。| +| `max` | [`SingleMetricAggregateBase`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3129) | 该result of a `max` aggregation。| +| `min` | [`SingleMetricAggregateBase`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3129) | 该result of a `min` aggregation。| +| `sterms` | [`StringTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3155) | A `terms` aggregation with string bucket keys。| +| `ulterms` | [`UnsignedLongTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3268) | A `terms` aggregation with unsigned-long bucket keys。| +| `umterms` | [`UnmappedTermsAggregate`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3256) | A `terms` aggregation result for unmapped fields。| + +### HitsMetadata 字段 + +The `HitsMetadata` object contains information about the search results, including the total number of matching documents 并在n array of individual document matches。It includes the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `total` | [`HitsMetadataTotal`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L351) | Metadata about the total number of matching documents (value \+ relation)。| +| `max_score` | [`HitsMetadataMaxScore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L360) | 该highest relevance score of the returned hits (may be `null`)。| +| `hits` | `repeated` [`HitsMetadataHitsInner`](#hitsmetadatahitsinner-fields) | 该actual list of matched documents。响应中的每个 hit includes core fields like `index`, `id`, `score`, and `source`, along with additional optional fields。| + +### HitsMetadataHitsInner 字段 + +响应中的每个 `HitsMetadataHitsInner` represents a single document matched by the query and contains the following fields。 + +| 字段 | Protobuf 类型 | 描述 | +| :---- | :---- | :---- | +| `x_type` | `string` | 该document type。| +| `x_index` | `string` | 该name of the index containing the returned document。| +| `x_id` | `string` | 该unique ID for the document within the index。| +| `x_score` | [`HitXScore`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L395) | 该relevance score of the hit。| +| `x_explanation` | [`Explanation`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L826) | A text explanation of how the `_score` was calculated。| +| `fields` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | 该document field values。| +| `highlight` | `map<string, `[`StringArray`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1262)`>` | 该highlighted fields and fragments per hit。| +| `inner_hits` | `map<string, `[`InnerHitsResult`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L389)`>` | 该matching nested documents from a different scope that contributed to the overall query result。| +| `matched_queries` | `repeated string` | **Deprecated。** A list of query names matching the document。| +| `x_nested` | [`NestedIdentity`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L838) | 该path to the inner nested object from which the hit originated。| +| `x_ignored` | `repeated string` | A list of ignored fields。| +| `ignored_field_values` | `map<string, `[`StringArray`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L1262)`>` | Raw, unprocessed values from the document's original JSON。| +| `x_shard` | `string` | 该shard ID from which the hit was retrieved。| +| `x_node` | `string` | 该node ID from which the hit was retrieved。| +| `x_routing` | `string` | 该routing value used for custom shard routing。| +| `x_source` | `bytes` | 该Base64-encoded `_source` document。| +| `x_seq_no` | `int64` | 该sequence number (used for indexing history and versioning)。| +| `x_primary_term` | `int64` | 该primary term number (used for optimistic concurrency control)。| +| `x_version` | `int64` | 该document version number。| +| `sort` | `repeated` [`FieldValue`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2637) | 该sort values used for result sorting。| +| `meta_fields` | [`ObjectMap`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L3890) | 该metadata values for the document。| +| `matched_queries_2` | [`HitMatchedQueries`](https://github.com/opensearch-project/opensearch-protobufs/blob/1.7.0/protos/schemas/common.proto#L2851) | 该current protobuf representation of matched query names for the document。| + +::: info NOTE +`source` is Base64 encoded and must be decoded to obtain the JSON document。 +::: + +## 示例响应 + +```json +{ + "response_body": { + "took": 64, + "timed_out": false, + "shards": { + "successful": 1, + "total": 1 + }, + "hits": { + "total": { + "total_hits": { + "relation": "TOTAL_HITS_RELATION_EQ", + "value": 1 + } + }, + "hits": [ + { + "index": "my_index", + "id": "3", + "score": { + "float_value": 1.0 + }, + "source": "eyAidGl0bGUiOiAiUnVzaCIsICJ5ZWFyIjogMjAxM30=", + "meta_fields": {} + } + ], + "max_score": { + "float_value": 1.0 + } + } + } +} +``` + +## Java gRPC 客户端示例 + +The following example shows a Java client-side program that submits an example search term query gRPC request and then prints the number of hits returned 指定为 search response: + +```java +import org。opensearch.protobufs。*; +import io。grpc。ManagedChannel; +import io。grpc。ManagedChannelBuilder; + +public class SearchClient { + public static void main(String[] args) { + ManagedChannel channel = ManagedChannelBuilder。forAddress("localhost", 9400) + 。usePlaintext() + 。build(); + + SearchServiceGrpc。SearchServiceBlockingStub stub = SearchServiceGrpc。newBlockingStub(channel); + + // Create a term query + TermQuery termQuery = TermQuery。newBuilder() + 。setField("director") + 。setValue(FieldValue。newBuilder()。setStringValue("Nolan")。build()) + 。build(); + + // Create query container + QueryContainer queryContainer = QueryContainer。newBuilder() + 。setTerm(termQuery) + 。build(); + + // Create search request body + SearchRequestBody requestBody = SearchRequestBody。newBuilder() + 。setQuery(queryContainer) + 。setSize(5) + 。build(); + + // Create search request + SearchRequest request = SearchRequest。newBuilder() + 。addIndex("movies") + 。setSearchRequestBody(requestBody) + 。build(); + + try { + SearchResponse response = stub。search(request); + + // Handle the response + System。out。println("Search took: " + response。getTook() + " ms"); + System。out。println("Timed out: " + response。getTimedOut()); + + HitsMetadata hits = response。getHits(); + if (hits。hasTotal()) { + System。out。println("Total hits: " + hits。getTotal()。getTotalHits()。getValue()); + } + + // Process individual hits + for (HitsMetadataHitsInner hit : hits。getHitsList()) { + System。out。println("Hit ID: " + hit。getXId()); + System。out。println("Hit Index: " + hit。getXIndex()); + if (hit。hasXScore()) { + System。out。println("Score: " + hit。getXScore()。getDouble()); + } + } + } catch (io。grpc。StatusRuntimeException e) { + System。err。println("gRPC search request failed with status: " + e。getStatus()); + System。err。println("Error message: " + e。getMessage()); + } + + channel。shutdown(); + } +} +``` + +## Python gRPC 客户端示例 + +The following example shows how to send the same request using a Python client application。 + +首先,使用 `opensearch-protobufs` 安装 `pip`: + +```bash +pip install opensearch-protobufs==1。2。0 +``` + +Use the following code to send the request: + +```python +import grpc + +from opensearch.protobufs。schemas import * +from opensearch.protobufs。services import SearchServiceStub + +channel = grpc。insecure_channel( + target="localhost:9400", +) + +search_stub = SearchServiceStub(channel) + +# Create a term query +term_query = TermQuery( + field="field", + value=FieldValue(string="value") +) +query_container = QueryContainer(term=term_query) + +# Create a search request +request = SearchRequest( + search_request_body=SearchRequestBody(query=query_container), + index=["my-index"] +) + +# Send request and handle response +try: + response = search_stub。Search(request=request) + if response。hits: + print("Found {} hits"。format(response。hits。total)) + print(response。hits) + elif response。timed_out or response。terminated_early: + print("Request timed out or terminated early") + elif response。x_shards。failed: + print("Some shards failed to execute the search") + print(response。x_shards。failures) +except grpc。RpcError 中将 e: + if e。code() == StatusCode。UNAVAILABLE: + print("Failed to reach server: {}"。format(e)) + elif e。code() == StatusCode。PERMISSION_DENIED: + print("Permission denied: {}"。format(e)) + elif e。code() == StatusCode。INVALID_ARGUMENT: + print("Invalid argument: {}"。format(e)) +finally: + channel。close() +``` diff --git a/i18n/zh/api-reference/index-apis/blocks.md b/i18n/zh/api-reference/index-apis/blocks.md new file mode 100644 index 00000000..1980ced5 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/blocks.md @@ -0,0 +1,84 @@ +--- +title: 块 +--- + +# 块 API +<Badge type="tip" text="引入版本 1.0" /> + +使用块 API 限制指定索引上的某些操作。不同类型的块允许您限制索引的写入、读取或元数据操作。 +例如,通过 API 添加 `write` 块可确保所有索引分片在返回成功响应之前正确记录该块。对索引的任何正在进行的写入操作必须在 `write` 块生效之前完成。 + +## 端点 + +```json +PUT /{index}/_block/{block} +``` + +## 路径参数 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index` | String | 逗号分隔的索引名称列表。支持通配符表达式(`*`)。要针对集群中的所有索引,请使用 `_all` 或 `*`。不支持数据流名称,并且您不能将块添加到数据流的写入索引。必需。 | +| `block` | String | 要应用于索引的块类型。必需。有效值为:<br> - `metadata`:阻止检索和更改索引元数据。例如,您无法关闭索引或获取其设置。<br> - `read`:阻止读取操作。<br> - `read_only`:阻止写入操作和元数据更改。<br> - `write`:阻止写入操作但允许元数据更改。<br> - `search_only`:阻止索引和写入操作,但允许通过搜索副本进行只读访问。<br> OpenSearch 通过 Scale API 自动管理此块,作为读写分离机制的一部分。因此,请勿手动设置此参数。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `ignore_unavailable` | Boolean | 当为 `false` 时,如果请求针对缺失或关闭的索引,则返回错误。默认为 `false`。 | +| `allow_no_indices` | Boolean | 当为 `false` 时,如果通配符表达式、索引别名或 `_all` 不匹配任何索引,则请求返回错误。默认为 `true`。 | +| `expand_wildcards` | String | 通配符表达式可以匹配的索引类型。支持逗号分隔的值,例如 `open,hidden`。有效值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认为 `open`。 | +| `cluster_manager_timeout` | Time | 等待与集群管理器节点连接的时间量。默认为 `30s`。 | +| `timeout` | Time | 等待请求返回的时间量。默认为 `30s`。 | + +## 示例请求 + +以下示例请求禁用对测试索引的任何 `write` 操作: + +<!-- spec_insert_start +component: example_code +rest: PUT /test-index/_block/write +--> + +PUT /test-index/_block/write + +response = client.indices.add_block( + block = "write", + index = "test-index" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged" : true, + "shards_acknowledged" : true, + "indices" : [ { + "name" : "test-index", + "blocked" : true + } ] +} +``` + +## 移除块 + +块 API 仅添加块。要移除块,请使用更新索引设置 API 将相应的索引设置设为 `false`。设置名称遵循块名称:`index.blocks.read`、`index.blocks.read_only`、`index.blocks.metadata` 或 `index.blocks.write`。有关更多信息,请参阅[更新索引设置 API](/api-reference/index-apis/update-settings)。 + +以下示例请求从测试索引中移除 `write` 块: + +```json +PUT /test-index/_settings +{ + "index.blocks.write": false +} +``` + +如果索引具有 `read_only`、`read_only_allow_delete` 或 `metadata` 块,则移除该块的请求必须仅包含该块设置。在更新任何其他设置之前,在单独的请求中移除该块。 + +OpenSearch 会将 `index.blocks.read_only_allow_delete` 块添加到在磁盘使用率超过洪水阶段水位线的节点上具有分片的索引。当磁盘使用率降至高水位线以下时,OpenSearch 会移除该块。有关更多信息,请参阅[集群级路由和分配设置](/install-and-configure/configuring-opensearch/cluster-settings#cluster-level-routing-and-allocation-settings)。 + +OpenSearch 通过 Scale API 管理 `search_only` 块,因此请勿使用更新索引设置 API 移除它。要禁用仅搜索模式,请参阅 [Scale API](/api-reference/index-apis/scale)。 diff --git a/i18n/zh/api-reference/index-apis/component-template.md b/i18n/zh/api-reference/index-apis/component-template.md new file mode 100644 index 00000000..410c1fd9 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/component-template.md @@ -0,0 +1,399 @@ +--- +title: 组件模板 API +--- + +# 组件模板 API +<Badge type="tip" text="引入版本 1.0" /> + +您可以使用组件模板 API 来创建、检索、更新和删除组件模板。组件模板是可重用的构建块,用于定义可在多个索引模板之间共享的设置、映射和别名。 + +索引模板可以使用多个组件模板构建。要将组件模板合并到索引模板中,您需要在索引模板的 `composed_of` 部分中列出它。组件模板仅应用于与索引模板中指定的条件匹配的新创建的数据流和索引。 + +如果任何设置或映射直接在索引模板或索引创建请求中定义,则这些设置将优先于组件模板中指定的设置或映射。 + +组件模板仅在索引创建过程中使用。对于数据流,这包括创建数据流本身以及创建支持该流的后备索引。对组件模板的修改不会影响现有索引,包括数据流的后备索引。 + +## 端点 + +```json +PUT _component_template/{component-template-name} +GET _component_template/{component-template-name} +DELETE _component_template/{component-template-name} +HEAD _component_template/{component-template-name} +``` + +- `PUT`:创建或更新组件模板。接受查询参数和请求正文。 +- `GET`:检索有关现有组件模板的信息。仅接受查询参数。 +- `DELETE`:删除现有组件模板。仅接受查询参数。 +- `HEAD`:返回组件模板是否存在。仅返回 HTTP 状态码。 + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`component-template-name` | String | 组件模板的名称。对于 PUT、HEAD 和 DELETE 操作为必需。对于 GET 操作为可选。 + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 | 支持的操作 +:--- | :--- | :--- | :--- +`create` | Boolean | 当为 true 时,API 不能替换或更新任何现有组件模板。默认为 `false`。 | PUT +`cluster_manager_timeout` | Time | 等待与集群管理器节点连接的时间量。默认为 `30s`。 | PUT、GET、DELETE + +## 创建或更新组件模板 + +使用 PUT 操作创建新组件模板或更新现有组件模板。 + +### 端点 + +```json +PUT _component_template/{component-template-name} +``` + +### 请求正文字段 + +下表列出了可用的请求正文字段。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`template` | Object | 包含索引的 `aliases`、`mappings` 或 `settings` 的模板。有关更多信息,请参阅 [#template]。必需。 +`version` | Integer | 用于管理索引模板的版本号。版本号不会由 OpenSearch 自动设置。可选。 +`_meta` | Object | 提供有关索引模板的详细信息的元数据。可选。 +`allow_auto_create` | Boolean | 当为 `true` 时,即使禁用了 `actions.auto_create_index`,也可以使用此模板自动创建索引。当为 `false` 时,无法自动创建与模板匹配的索引和数据流。可选。 +`deprecated` | Boolean | 当为 `true` 时,组件模板已弃用。如果已弃用,每当引用该模板时,OpenSearch 都会输出警告。 + +### 模板 + +您可以在请求正文的 `template` 选项中使用以下对象。 + +#### `alias` + +要与模板关联的别名名称作为键。当请求正文中存在 `template` 选项时为必需。此选项支持多个别名。 + +对象正文包含以下可选别名参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`filter` | Query DSL 对象 | 限制别名可以访问的文档数量的查询。 +`index_routing` | String | 将索引操作路由到特定分片的值。指定后,会覆盖索引操作的 `routing` 值。 +`is_hidden` | Boolean | 当为 `true` 时,别名是隐藏的。默认为 false。所有别名索引必须对此设置具有匹配的值。 +`is_write_index` | Boolean | 当为 `true` 时,索引是别名的写入索引。默认为 `false`。 +`routing` | String | 用于将索引和搜索操作路由到特定分片的值。 +`search_routing` | String | 用于将搜索操作写入到特定分片的值。指定后,此选项会覆盖搜索操作的 `routing` 值。 + +#### `mappings` + +索引中存在的字段映射。有关更多信息,请参阅[映射和字段类型](/mappings/)。可选。 + +#### `settings` + +索引的任何配置选项。有关更多信息,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +### 示例请求:创建包含索引别名的组件模板 + +以下示例请求创建包含索引别名的组件模板: + +<!-- spec_insert_start +component: example_code +rest: PUT /_component_template/alias_template +body: | +{ + "template": { + "settings" : { + "number_of_shards" : 1 + }, + "aliases" : { + "alias1" : {}, + "alias2" : { + "filter" : { + "term" : {"user.id" : "hamlet" } + }, + "routing" : "shard-1" + }, + "{index}-alias" : {} + } + } +} +--> + +PUT /_component_template/alias_template +{ + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } +} + +response = client.cluster.put_component_template( + name = "alias_template", + body = { + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } + } +) + +<!-- spec_insert_end --> + +### 示例请求:添加组件版本控制 + +以下示例向组件模板添加 `version` 号,这简化了外部系统的模板管理: + +<!-- spec_insert_start +component: example_code +rest: PUT /_component_template/version_template +body: | +{ + "template": { + "settings" : { + "number_of_shards" : 1 + } + }, + "version": 3 +} +--> + +PUT /_component_template/version_template +{ + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 3 +} + +response = client.cluster.put_component_template( + name = "version_template", + body = { + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 3 + } +) + +<!-- spec_insert_end --> + +### 示例请求:添加模板元数据 + +以下示例请求使用 `_meta` 参数向组件模板添加元数据。所有元数据都存储在集群状态中。 + +<!-- spec_insert_start +component: example_code +rest: PUT /_component_template/meta_template +body: | +{ + "template": { + "settings" : { + "number_of_shards" : 1 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } +} +--> + +PUT /_component_template/meta_template +{ + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } +} + +response = client.cluster.put_component_template( + name = "meta_template", + body = { + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } + } +) + +<!-- spec_insert_end --> + +## 检索组件模板 + +使用 GET 操作检索一个或多个组件模板及其信息。 + +### 端点 + +``` +GET /_component_template/{component-template-name} +GET /_component_template +``` + +### 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`component-template-name` | String | 要检索的组件模板的名称。支持通配符表达式(`*`)。如果未指定,则返回所有组件模板。 + +### 示例请求:按名称检索组件模板 + +<!-- spec_insert_start +component: example_code +rest: GET /_component_template/my_template +--> + +GET /_component_template/my_template + +response = client.cluster.get_component_template( + name = "my_template" +) + +<!-- spec_insert_end --> + +### 示例请求:使用通配符模式检索组件模板 + +<!-- spec_insert_start +component: example_code +rest: GET /_component_template/my_template* +--> + +GET /_component_template/my_template* + +response = client.cluster.get_component_template( + name = "my_template*" +) + +<!-- spec_insert_end --> + +### 示例请求:检索所有组件模板 + +<!-- spec_insert_start +component: example_code +rest: GET /_component_template +--> + +GET /_component_template + +response = client.cluster.get_component_template() + +<!-- spec_insert_end --> + +## 删除组件模板 + +使用 DELETE 操作从集群中移除组件模板。 + +**重要注意事项**: +- 删除组件模板不会影响使用该模板创建的现有索引。 +- 您不能删除当前被索引模板引用的组件模板。 +- 该操作是不可逆的。 + +### 端点 + +``` +DELETE _component_template/{component-template-name} +``` + +### 示例请求 + +<!-- spec_insert_start +component: example_code +rest: DELETE /_component_template/my_template +--> + +DELETE /_component_template/my_template + +response = client.cluster.delete_component_template( + name = "my_template" +) + +<!-- spec_insert_end --> + +## 检查组件模板是否存在 + +使用 HEAD 操作检查组件模板是否存在而不检索其内容。此操作仅返回 HTTP 状态码和标头,没有响应正文。 + +### 端点 + +``` +HEAD _component_template/{component-template-name} +``` + +### 示例请求 + +<!-- spec_insert_start +component: example_code +rest: HEAD /_component_template/my_template +--> + +HEAD /_component_template/my_template + +response = client.cluster.exists_component_template( + name = "my_template" +) + +<!-- spec_insert_end --> + +### 响应代码 + +- `200`:组件模板存在。 +- `404`:组件模板不存在。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限。此 API 需要以下权限: + +- `cluster:admin/component_template/get`:获取组件模板所需 +- `cluster:admin/component_template/put`:创建或更新组件模板所需 +- `cluster:admin/component_template/delete`:删除组件模板所需 diff --git a/i18n/zh/api-reference/index-apis/core-index-apis.md b/i18n/zh/api-reference/index-apis/core-index-apis.md new file mode 100644 index 00000000..9f87cfef --- /dev/null +++ b/i18n/zh/api-reference/index-apis/core-index-apis.md @@ -0,0 +1,21 @@ +--- +title: 核心索引 API +--- + +# 核心索引 API + +核心索引 API 提供用于管理 OpenSearch 集群中索引生命周期的基本操作。这些 API 允许您创建、删除索引以及对索引执行基本操作。 + +## 可用 API + +OpenSearch 支持以下核心索引 API。 + +| API | 描述 | +|-----|-------------| +| [创建索引](/api-reference/index-apis/create-index) | 创建新索引。 | +| [删除索引](/api-reference/index-apis/delete-index) | 删除现有索引。 | +| [获取索引](/api-reference/index-apis/get-index) | 返回有关一个或多个索引的信息。 | +| [索引存在](/api-reference/index-apis/exists) | 检查索引是否存在。 | +| [打开索引](/api-reference/index-apis/open-index) | 打开已关闭的索引。 | +| [关闭索引](/api-reference/index-apis/close-index) | 关闭已打开的索引。 | +| [解析索引](/api-reference/index-apis/resolve-index) | 将索引名称和别名解析为其具体索引。 | diff --git a/i18n/zh/api-reference/index-apis/create-index-template.md b/i18n/zh/api-reference/index-apis/create-index-template.md new file mode 100644 index 00000000..58a79340 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/create-index-template.md @@ -0,0 +1,409 @@ +--- +title: 创建或更新索引模板 +--- + +# 创建或更新索引模板 API +<Badge type="tip" text="引入版本 1.0" /> + +使用创建或更新索引模板 API 创建具有预定义映射和设置的索引以及更新现有索引模板。 + +## 端点 + +```json +PUT _index_template/{template-name} +POST _index_template/{template-name} +``` + +## 路径参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`template-name` | String | 索引模板的名称。 + +## 查询参数 + +支持以下可选查询参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`create` | Boolean | 当为 true 时,API 不能替换或更新任何现有索引模板。默认为 `false`。 +`cause` | String | 创建或更新索引模板的原因。默认为 `api`。 +`cluster_manager_timeout` | Time | 等待与集群管理器节点连接的时间量。默认为 `30s`。 + +## 请求正文字段 + +以下选项可用于请求正文中以自定义索引模板。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`index_patterns` | String 数组 | 用于在创建数据流和索引时匹配其名称的通配符表达式数组。必需。 +`composed_of` | String 数组 | 组件模板名称的有序列表。这些模板使用指定的顺序合并。有关更多信息,请参阅[使用多个组件模板](#使用多个组件模板)。可选。 +`data_stream` | Object | 指定后,索引模板将成为数据流模板,并且可以使用它创建具有匹配名称的数据流。数据流后备索引始终是隐藏的。该对象可以包含 `timestamp_field` 对象,其 `name` 字段指定数据流的时间戳字段。默认 `name` 为 `@timestamp`。可选。 +`_meta` | Object | 提供有关索引模板的详细信息的可选元数据。可选。 +`priority` | Long | 确定在创建新索引或数据流期间哪些索引模板优先的数字。OpenSearch 选择具有最高优先级的模板。当未给出优先级时,模板被分配为 `0`,表示最低优先级。必须为 `0` 或更大。具有重叠索引模式的索引模板不能具有相同的优先级。可选。 +`template` | Object | 包含索引的 `aliases`、`mappings` 或 `settings` 的模板。有关更多信息,请参阅[模板](#模板)。可选。 +`version` | Long | 用于管理索引模板的版本号。版本号不会由 OpenSearch 自动设置。可选。 +`context` | Object | (实验性)`context` 参数提供可应用于索引的用例特定的预定义模板。在为模板声明的所有设置和映射中,上下文模板具有最高优先级。需要将 `cluster.application_templates.enabled` 设置为 `true`。该对象包含上下文的 `name`(String,必需)、上下文模板 `version`(String,默认 `_latest`)和可选 `params`(Object)。有关更多信息,请参阅[索引上下文](/im-plugin/index-context)。可选。 + +### 模板 + +您可以在请求正文的 `template` 选项中使用以下对象。 + +#### `aliases` + +要与模板关联的别名名称作为键。此选项支持多个别名。别名名称可以包含 `{index}`,在创建索引时将替换为索引的名称。 + +对象正文包含以下可选别名参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`filter` | Query DSL 对象 | 限制别名可以访问的文档数量的查询。 +`index_routing` | String | 将索引操作路由到特定分片的值。指定后,会覆盖索引操作的 `routing` 值。 +`is_hidden` | Boolean | 当为 `true` 时,别名是隐藏的。默认为 `false`。所有别名索引必须对此设置具有匹配的值。 +`is_write_index` | Boolean | 当为 `true` 时,索引是别名的写入索引。默认为 `false`。 +`routing` | String | 用于将索引和搜索操作路由到特定分片的值。 +`search_routing` | String | 用于将搜索操作路由到特定分片的值。指定后,此选项会覆盖搜索操作的 `routing` 值。 + +#### `mappings` + +索引中存在的字段映射。有关更多信息,请参阅[映射和字段类型](/mappings/)。可选。 + +#### `settings` + +索引的任何配置选项。有关更多信息,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +## 示例请求 + +以下示例展示如何使用创建或更新索引模板 API。 + +### 包含索引别名的索引模板 + +以下示例请求在模板中包含索引别名: + +<!-- spec_insert_start +component: example_code +rest: PUT /_index_template/alias-template +body: | +{ + "index_patterns" : ["sh*"], + "template": { + "settings" : { + "number_of_shards" : 1 + }, + "aliases" : { + "alias1" : {}, + "alias2" : { + "filter" : { + "term" : {"user.id" : "hamlet" } + }, + "routing" : "shard-1" + }, + "{index}-alias" : {} + } + } +} +--> + +PUT /_index_template/alias-template +{ + "index_patterns": [ + "sh*" + ], + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } +} + +response = client.indices.put_index_template( + name = "alias-template", + body = { + "index_patterns": [ + "sh*" + ], + "template": { + "settings": { + "number_of_shards": 1 + }, + "aliases": { + "alias1": {}, + "alias2": { + "filter": { + "term": { + "user.id": "hamlet" + } + }, + "routing": "shard-1" + }, + "{index}-alias": {} + } + } + } +) + +<!-- spec_insert_end --> + +### 使用多个匹配模板 + +当多个索引模板与新索引或数据流的名称匹配时,使用具有最高优先级的模板。例如,以下两个请求创建具有不同优先级的索引模板。 + +第一个请求创建优先级为 `0` 的模板,该模板匹配以 `h` 开头的索引名称: + +```json +PUT /_index_template/template_one +{ + "index_patterns" : ["h*"], + "priority" : 0, + "template": { + "settings" : { + "number_of_shards" : 1, + "number_of_replicas": 0 + }, + "mappings" : { + "_source" : { "enabled" : false } + } + } +} +``` + +第二个请求创建优先级为 `1` 的模板,该模板匹配以 `ha` 开头的更窄的索引名称集: + +```json +PUT /_index_template/template_two +{ + "index_patterns" : ["ha*"], + "priority" : 1, + "template": { + "settings" : { + "number_of_shards" : 2 + }, + "mappings" : { + "_source" : { "enabled" : true } + } + } +} +``` + +对于以 `ha` 开头的索引,`_source` 被启用。因为仅应用 `template_two`,索引将有两个主分片和一个副本。 + +::: info NOTE +不允许具有相同优先级的重叠索引模式。尝试创建与现有索引模板具有相同优先级的匹配索引模板时会发生错误。 +::: + +### 添加模板版本控制 + +以下示例请求向索引模板添加 `version` 号,这简化了外部系统的模板管理: + +<!-- spec_insert_start +component: example_code +rest: PUT /_index_template/versioned-template +body: | +{ + "index_patterns" : ["mac", "cheese"], + "priority" : 0, + "template": { + "settings" : { + "number_of_shards" : 1 + } + }, + "version": 1 +} +--> + +PUT /_index_template/versioned-template +{ + "index_patterns": [ + "mac", + "cheese" + ], + "priority": 0, + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 1 +} + +response = client.indices.put_index_template( + name = "versioned-template", + body = { + "index_patterns": [ + "mac", + "cheese" + ], + "priority": 0, + "template": { + "settings": { + "number_of_shards": 1 + } + }, + "version": 1 + } +) + +<!-- spec_insert_end --> + +### 添加模板元数据 + +以下示例请求使用 `_meta` 参数向索引模板添加元数据。所有元数据都存储在集群状态中: + +<!-- spec_insert_start +component: example_code +rest: PUT /_index_template/metadata-template +body: | +{ + "index_patterns": ["rom", "juliet"], + "template": { + "settings" : { + "number_of_shards" : 2 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } +} +--> + +PUT /_index_template/metadata-template +{ + "index_patterns": [ + "rom", + "juliet" + ], + "template": { + "settings": { + "number_of_shards": 2 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } +} + +response = client.indices.put_index_template( + name = "metadata-template", + body = { + "index_patterns": [ + "rom", + "juliet" + ], + "template": { + "settings": { + "number_of_shards": 2 + } + }, + "_meta": { + "description": "Where art thou", + "serialization": { + "class": "MyIndexTemplate", + "id": 12 + } + } + } +) + +<!-- spec_insert_end --> + +### 数据流定义 + +包含 `data_stream` 对象以将索引模板用于数据流,如以下示例请求所示: + +<!-- spec_insert_start +component: example_code +rest: PUT /_index_template/logs-template +body: | +{ + "index_patterns": ["logs-*"], + "data_stream": { } +} +--> + +PUT /_index_template/logs-template +{ + "index_patterns": [ + "logs-*" + ], + "data_stream": {} +} + +response = client.indices.put_index_template( + name = "logs-template", + body = { + "index_patterns": [ + "logs-*" + ], + "data_stream": {} + } +) + +<!-- spec_insert_end --> + +## 使用多个组件模板 + +当使用带有 `composed_of` 字段的多个组件模板时,组件模板按指定顺序合并。索引模板自己的 `template` 对象中的设置、映射和别名在组件模板之后合并并覆盖它们。创建索引请求中指定的设置会覆盖两者。 + +在以下示例中,匹配 `my-index-*` 的索引具有两个合并的主分片。如果 `composed_of` 数组中的顺序相反,则索引将具有一个主分片。 + +首先,创建设置一个主分片的组件模板: + +```json +PUT /_component_template/template_with_1_shard +{ + "template": { + "settings": { + "index.number_of_shards": 1 + } + } +} +``` + +接下来,创建设置两个主分片的组件模板: + +```json +PUT /_component_template/template_with_2_shards +{ + "template": { + "settings": { + "index.number_of_shards": 2 + } + } +} +``` + +最后,创建一个按顺序组合两个组件模板的索引模板: + +```json +PUT /_index_template/composed-template +{ + "index_patterns": ["my-index-*"], + "composed_of": ["template_with_1_shard", "template_with_2_shards"] +} +``` + +递归合并用于映射定义和根选项(例如 `dynamic_templates` 和 `meta`),这意味着当较早的组件包含 `meta` 块时,新的 `meta` 条目将添加到索引元数据的末尾。包含预先存在的键的任何条目都会被覆盖。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/index_template/put`。 diff --git a/i18n/zh/api-reference/index-apis/delete-index-template.md b/i18n/zh/api-reference/index-apis/delete-index-template.md new file mode 100644 index 00000000..864ddc04 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/delete-index-template.md @@ -0,0 +1,33 @@ +--- +title: 删除索引模板 +--- + +# 删除索引模板 API +<Badge type="tip" text="引入版本 1.0" /> + +删除索引模板 API 删除一个或多个索引模板。 + +## 端点 + +```json +DELETE /_index_template/{template-name} +``` + +## 路径参数 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`template-name` | String | 索引模板的名称。您可以在一个请求中通过用逗号分隔模板名称来删除多个模板。当请求中使用多个模板名称时,不支持通配符。 + +## 查询参数 + +支持以下可选查询参数。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`cluster_manager_timeout` | Time | 等待与集群管理器节点连接的时间量。默认为 `30s`。 +`timeout` | Time | 操作等待响应的时间量。默认为 `30s`。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/index_template/delete`。 diff --git a/i18n/zh/api-reference/index-apis/delete-template-legacy.md b/i18n/zh/api-reference/index-apis/delete-template-legacy.md new file mode 100644 index 00000000..2c760d52 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/delete-template-legacy.md @@ -0,0 +1,58 @@ +--- +title: 删除模板(已弃用) +--- + +# 删除模板 +<Badge type="tip" text="引入版本 1.0" /> + +::: danger WARNING +删除模板 API 已被弃用。请使用新的[删除索引模板](/api-reference/index-apis/delete-index-template) API。 +::: + +删除模板 API 操作删除使用旧版 `/_template` 端点创建的索引模板。 + +## 端点 + +```json +DELETE /_template/{template-name} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是必需的。 + +| 参数 | 类型 | 描述 | +| :----------- | :----- | :---------------------------------------------------------- | +| `index-name` | String | 要删除的索引的名称。支持通配符表达式。 | + +## 查询参数 + +下表列出了可用的查询参数。所有参数都是可选的。 + +| 参数 | 类型 | 描述 | +| :-------------- | :--- | :------------------------------------------------------------------------------------------- | +| `cluster_manager_timeout` | Time | 指定等待与集群管理器节点连接的时间。默认为 `30s`。 | +| `timeout` | Time | 指定等待操作完成的时间。默认为 `30s`。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: DELETE /_template/logging_template +--> + +DELETE /_template/logging_template + +response = client.indices.delete_template( + name = "logging_template" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` diff --git a/i18n/zh/api-reference/index-apis/flush.md b/i18n/zh/api-reference/index-apis/flush.md new file mode 100644 index 00000000..8aee7e27 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/flush.md @@ -0,0 +1,96 @@ +--- +title: 刷新 +--- + +# 刷新 API + +<Badge type="tip" text="引入版本 1.0" /> + +刷新 API 将所有内存中的操作存储到磁盘上的段中。刷新到索引段的操作在集群重启期间不再需要在事务日志中,因为这些操作现在存储在 Lucene 索引中。 + +OpenSearch 根据事务日志大小等条件在后台自动执行刷新,该条件由 `index.translog.flush_threshold_size` 设置控制。谨慎使用刷新 API,例如用于手动重启或释放内存。 + +有关刷新与事务日志、刷新和合并操作的关系的更多信息,请参阅 OpenSearch 概念中的[刷新](/getting-started/concepts/#flush)。 + +## 端点 + +刷新 API 支持以下路径: + +```json +GET /_flush +POST /_flush +GET /{index}/_flush +POST /{index}/_flush +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `<index>` | String | 应用操作的索引、数据流或索引别名的逗号分隔列表。支持通配符表达式(`*`)。使用 `_all` 或 `*` 指定集群中的所有索引和数据流。 | + +## 查询参数 + +所有参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `allow_no_indices` | Boolean | 当为 `false` 时,如果任何通配符表达式或索引别名针对任何关闭或缺失的索引,则请求返回错误。默认为 `true`。 | +| `expand_wildcards` | String | 指定通配符表达式可以扩展到的索引类型。支持逗号分隔的值。有效值为:<br> - `all`:扩展到所有打开和关闭的索引,包括隐藏索引。<br> - `open`:扩展到打开的索引。<br> - `closed`:扩展到关闭的索引。<br> - `hidden`:在扩展时包括隐藏索引。必须与 `open`、`closed` 或两者结合使用。<br> - `none`:不接受通配符表达式。<br> 默认为 `open`。<br> 刷新 API 无法刷新关闭的索引。如果通配符表达式扩展到关闭的索引,则请求失败,除非 `ignore_unavailable` 为 `true`,在这种情况下会跳过关闭的索引。 | +| `force` | Boolean | 当为 `true` 时,即使索引内存中不存在更改,也强制进行刷新。如果为 `true`,则 `wait_if_ongoing` 也必须为 `true`;否则,请求将被拒绝。默认为 `false`。 | +| `ignore_unavailable` | Boolean | 当为 `true` 时,OpenSearch 忽略缺失或关闭的索引。如果为 `false`,当刷新操作遇到缺失或关闭的索引时,OpenSearch 返回错误。默认为 `false`。 | +| `wait_if_ongoing` | Boolean | 当为 `true` 时,如果正在进行另一个刷新,OpenSearch 会等待其完成,然后执行刷新。当为 `false` 时,如果另一个刷新已经在分片上运行,该分片会跳过刷新而不返回错误。默认为 `true`。 | + +## 示例请求:刷新特定索引 + +以下示例刷新名为 `shakespeare` 的索引: + +<!-- spec_insert_start +component: example_code +rest: POST /shakespeare/_flush +body: +--> + +POST /shakespeare/_flush + +response = client.indices.flush( + index = "shakespeare" +) + +<!-- spec_insert_end --> + +## 示例请求:刷新所有索引 + +以下示例刷新集群中的所有索引: + +<!-- spec_insert_start +component: example_code +rest: POST /_flush +body: +--> + +POST /_flush + +response = client.indices.flush() + +<!-- spec_insert_end --> + +## 示例响应 + +OpenSearch 响应刷新请求针对的分片副本数量(包括未分配的副本)、完成请求的分片副本数量以及失败的分片副本数量: + +```json +{ + "_shards": { + "total": 10, + "successful": 10, + "failed": 0 + } +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/flush` 和 `indices:admin/flush*`。 diff --git a/i18n/zh/api-reference/index-apis/get-field-mapping.md b/i18n/zh/api-reference/index-apis/get-field-mapping.md new file mode 100644 index 00000000..95bc0930 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/get-field-mapping.md @@ -0,0 +1,74 @@ +--- +title: 获取字段映射 +--- + +# 获取字段映射 API +<Badge type="tip" text="引入版本 1.0" /> + +获取字段映射 API 检索一个或多个特定字段的映射定义。当您需要检查特定字段的配置方式而无需检索完整索引映射时,这很有用,尤其是对于具有许多字段的索引。 + +## 端点 + +```json +GET /_mapping/field/{field} +GET /{index}/_mapping/field/{field} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `index` | 可选 | String | 索引名称或通配符表达式的逗号分隔列表。使用 `_all` 或省略以针对所有索引。 | +| `field` | 必需 | String | 字段名称或通配符表达式的逗号分隔列表。对嵌套字段使用点符号(例如,`author.name`)。 | + +## 查询参数 + +下表列出了可用的查询参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `include_defaults` | 可选 | Boolean | 当为 `true` 时,响应包括通常被省略的默认映射参数值。默认为 `false`。 | +| `allow_no_indices` | 可选 | Boolean | 当为 `true` 时,如果通配符表达式或 `_all` 解析为没有索引,则请求不返回错误。默认为 `true`。 | +| `expand_wildcards` | 可选 | String | 控制通配符表达式扩展到的索引类型。有效值为 `open`、`closed`、`hidden`、`none`、`all`。默认为 `open`。 | +| `ignore_unavailable` | 可选 | Boolean | 当为 `true` 时,忽略缺失或关闭的索引而不是返回错误。默认为 `false`。 | + +## 示例请求 + +以下请求检索 `customer_gender` 字段的映射: + +```json +GET /opensearch_dashboards_sample_data_ecommerce/_mapping/field/customer_gender +``` + +## 示例响应 + +响应包含字段的完整名称及其映射配置: + +```json +{ + "opensearch_dashboards_sample_data_ecommerce" : { + "mappings" : { + "customer_gender" : { + "full_name" : "customer_gender", + "mapping" : { + "customer_gender" : { + "type" : "keyword" + } + } + } + } + } +} +``` + +## 响应正文字段 + +下表列出了响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `{index}.mappings` | Object | 指定索引的字段名称到其映射详细信息的映射。 | +| `{field}.full_name` | String | 完全限定的字段名称,包括任何父对象路径。 | +| `{field}.mapping` | Object | 字段的映射配置,包括其类型和任何参数。 | diff --git a/i18n/zh/api-reference/index-apis/get-index-template.md b/i18n/zh/api-reference/index-apis/get-index-template.md new file mode 100644 index 00000000..72536c17 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/get-index-template.md @@ -0,0 +1,174 @@ +--- +title: 获取索引模板 +--- + +# 获取索引模板 API +<Badge type="tip" text="引入版本 1.0" /> + +获取索引模板 API 返回有关一个或多个索引模板的信息。 + +## 端点 + +```json +GET /_index_template +GET /_index_template/{template-name} +HEAD /_index_template/{template-name} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`template-name` | String | 要返回的索引模板的名称。支持通配符表达式(`*`)。不支持逗号分隔的名称列表。如果省略,则返回所有索引模板。 + +## 查询参数 + +支持以下可选查询参数。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`cluster_manager_timeout` | Time | 等待与集群管理器节点连接的时间量。默认为 `30s`。 +`local` | Boolean | 是否仅从本地节点而不是从集群管理器节点返回信息。默认为 `false`。 + +## 示例请求 + +以下请求为名称以 `hotels-` 开头的索引创建名为 `hotels-template` 的索引模板: + +```json +PUT /_index_template/hotels-template +{ + "index_patterns": ["hotels-*"], + "priority": 50, + "version": 1, + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "name": { "type": "text" }, + "city": { "type": "keyword" }, + "rating": { "type": "float" } + } + }, + "aliases": { + "hotels": {} + } + }, + "_meta": { + "description": "Template for hotel listing indexes" + } +} +``` + +以下示例请求使用通配符表达式获取有关索引模板的信息。如果没有索引模板与指定名称匹配,API 将返回 `404` 状态码: + +<!-- spec_insert_start +component: example_code +rest: GET /_index_template/h* +--> + +GET /_index_template/h* + +response = client.indices.get_index_template( + name = "h*" +) + +<!-- spec_insert_end --> + +以下示例请求获取有关所有索引模板的信息: + +<!-- spec_insert_start +component: example_code +rest: GET /_index_template +--> + +GET /_index_template + +response = client.indices.get_index_template() + +<!-- spec_insert_end --> + +## 示例响应 + +以下响应是针对 `GET /_index_template/h*` 请求返回的: + +```json +{ + "index_templates": [ + { + "name": "hotels-template", + "index_template": { + "index_patterns": [ + "hotels-*" + ], + "template": { + "settings": { + "index": { + "number_of_shards": "1", + "number_of_replicas": "1" + } + }, + "mappings": { + "properties": { + "city": { + "type": "keyword" + }, + "name": { + "type": "text" + }, + "rating": { + "type": "float" + } + } + }, + "aliases": { + "hotels": {} + } + }, + "composed_of": [], + "priority": 50, + "version": 1, + "_meta": { + "description": "Template for hotel listing indexes" + } + } + } + ] +} +``` + +## 响应正文字段 + +下表列出了所有响应正文字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`index_templates` | 对象数组 | 与请求匹配的索引模板。数组中的每个对象都包含 `name` 和 `index_template` 字段。 + +`index_templates` 数组中的每个对象都包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`name` | String | 索引模板的名称。 +`index_template` | Object | 索引模板定义。 + +`index_template` 对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`index_patterns` | 字符串数组 | 模板应用到的索引名称模式。 +`template` | Object | 应用于匹配索引的设置、映射和别名。包含 `settings`、`mappings` 和 `aliases` 对象。仅返回模板中定义的对象。仅在设置时返回。 +`composed_of` | 字符串数组 | 用于组成此索引模板的组件模板的名称。如果设置或如果索引模板包含 `template` 对象,则返回。在后一种情况下,它可以是空数组。 +`priority` | Long | 模板的优先级。当多个模板与索引匹配时,应用具有最高优先级的模板。仅在设置时返回。 +`version` | Long | 模板的版本号。仅在设置时返回。 +`_meta` | Object | 与模板一起存储的自定义元数据。仅在设置时返回。 +`data_stream` | Object | 数据流配置,例如 `timestamp_field`。仅在模板创建数据流时返回。 +`context` | Object | 用于将附加设置应用于匹配索引的上下文。仅在设置时返回。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/index_template/get`。 diff --git a/i18n/zh/api-reference/index-apis/get-ingestion-state.md b/i18n/zh/api-reference/index-apis/get-ingestion-state.md new file mode 100644 index 00000000..ff5ba978 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/get-ingestion-state.md @@ -0,0 +1,158 @@ +--- +title: 获取摄取状态 +--- + +# 获取摄取状态 API +<Badge type="tip" text="引入版本 3.0" /> + +返回使用[拉取式摄取](/im-plugin/pull-based-ingestion/)的一个或多个索引中每个分片的当前摄取状态。此 API 支持分页。 + +## 端点 + +```json +GET /{index}/ingestion/_state +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `index` | String | 必需 | 要返回摄取状态的索引。可以是多个索引名称的逗号分隔列表。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `size` | Integer | 每页返回的结果数量。 | +| `next_token` | String | 用于检索下一页结果的令牌。使用前一个响应中的 `next_page_token` 值。 | +| `timeout` | Time units | 等待集群响应的时间量。默认为 `30s`。 | + +## 示例请求:检索摄取状态 + +要获取 `my-index` 的摄取状态,请发送以下请求: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/ingestion/_state +--> + +GET /my-index/ingestion/_state + +response = client.ingestion.get_state( + index = "my-index" +) + +<!-- spec_insert_end --> + +## 示例响应 + +响应包含 `my-index` 中每个分片的摄取状态。如果分片无法返回其状态,则失败将列在 `_shards.failures` 中: + +```json +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "ingestion_state": { + "my-index": [ + { + "shard": 0, + "poller_state": "POLLING", + "error_policy": "DROP", + "poller_paused": false, + "write_block_enabled": false, + "batch_start_pointer": "KafkaOffset{offset=17735361}", + "is_primary": true, + "node": "node-a" + } + ] + } +} +``` + +## 示例请求:分页结果 + +要每页返回 20 个结果,请发送以下请求: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/ingestion/_state?size=20 +--> + +GET /my-index/ingestion/_state?size=20 + +response = client.ingestion.get_state( + index = "my-index", + params = { "size": "20" } +) + +<!-- spec_insert_end --> + +如果有更多可用结果,响应将包含 `next_page_token` 字段。要检索下一页,在 `next_token` 查询参数中提供其值: + +<!-- spec_insert_start +component: example_code +rest: GET /my-index/ingestion/_state?size=20&next_token=<next_page_token> +--> + +GET /my-index/ingestion/_state?size=20&next_token=<next_page_token> + +response = client.ingestion.get_state( + index = "my-index", + params = { "size": "20", "next_token": "<next_page_token>" } +) + +<!-- spec_insert_end --> + +## 响应正文字段 + +下表列出了所有响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_shards` | Object | 返回或未能返回其摄取状态的分片数量。参见[分片](#分片)。 | +| `ingestion_state` | Object | 每个请求索引的摄取状态。每个键都是索引名称,其值是包含该索引中每个分片状态的数组。参见[分片摄取状态](#分片摄取状态)。 | +| `next_page_token` | String | 用于检索下一页结果的令牌。在 `next_token` 查询参数中传递此值。仅在有更多可用结果时返回。 | + +### 分片 + +`_shards` 对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `total` | Integer | 请求摄取状态的分片总数。 | +| `successful` | Integer | 返回其摄取状态的分片数量。 | +| `failed` | Integer | 未能返回其摄取状态的分片数量。 | +| `failures` | 对象数组 | 分片失败列表。仅在至少有一个分片失败时返回。参见[分片失败](#分片失败)。 | + +### 分片失败 + +`_shards.failures` 数组中的每个对象都包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `shard` | Integer | 分片编号。 | +| `index` | String | 包含分片的索引名称。 | +| `status` | String | 失败的 HTTP 状态,例如 `INTERNAL_SERVER_ERROR`。 | +| `reason` | Object | 失败原因,包含错误 `type`(例如,`timeout_exception`)和 `reason` 中的错误消息。 | + +### 分片摄取状态 + +`ingestion_state` 数组中的每个对象都包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `shard` | Integer | 分片编号。 | +| `poller_state` | String | 分片轮询器的当前状态。有效值为 `NONE`、`POLLING`、`PROCESSING`、`PAUSED` 和 `CLOSED`。 | +| `error_policy` | String | 处理失败消息的策略:`DROP` 或 `BLOCK`。参见[更新错误策略](/im-plugin/pull-based-ingestion/#updating-the-error-policy)。 | +| `poller_paused` | Boolean | 分片的摄取是否已暂停。 | +| `write_block_enabled` | Boolean | 是否为分片启用了写入块。 | +| `batch_start_pointer` | String | 源中轮询器在分片恢复期间恢复的位置,例如 Kafka 偏移量或 Kinesis 序列号。 | +| `is_primary` | Boolean | 分片副本是否是主分片。 | +| `node` | String | 托管分片副本的节点名称。 | diff --git a/i18n/zh/api-reference/index-apis/get-mapping.md b/i18n/zh/api-reference/index-apis/get-mapping.md new file mode 100644 index 00000000..bce9001b --- /dev/null +++ b/i18n/zh/api-reference/index-apis/get-mapping.md @@ -0,0 +1,159 @@ +--- +title: 获取索引映射 +--- + +# 获取索引映射 API +<Badge type="tip" text="引入版本 1.0" /> + +获取映射 API 返回一个或多个索引的映射定义。使用此 API 检查索引中字段的配置方式、验证映射更新是否已应用或在重新索引之前查看完整架构。 + +<!-- spec_insert_start +api: indices.get_mapping +component: endpoints +--> +## 端点 +```json +GET /_mapping +GET /{index}/_mapping +``` +<!-- spec_insert_end --> + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index` | String | 要检索映射的索引名称的逗号分隔列表。支持通配符表达式。要检索所有索引的映射,请省略此参数或使用 `_all` 或 `*`。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | 指定是否忽略不匹配任何索引的通配符。如果为 `false`,当通配符不匹配任何索引时,请求将返回错误。 | `true` | +| `cluster_manager_timeout` | String | 等待与集群管理器节点连接的时间量。 | `30s` | +| `expand_wildcards` | String | 指定通配符表达式可以扩展到的索引类型。支持逗号分隔的值。有效值为:<br> - `all`:匹配所有索引,包括隐藏索引。<br> - `open`:匹配打开的索引。<br> - `closed`:匹配关闭的索引。<br> - `hidden`:匹配隐藏索引。必须与 `open`、`closed` 或两者结合使用。<br> - `none`:不接受通配符表达式。 | `open` | +| `ignore_unavailable` | Boolean | 指定是否忽略缺失或关闭的索引。如果为 `true`,缺失或关闭的索引不包括在响应中。 | `false` | +| `local` | Boolean | 指定是否仅从本地节点而不是从集群管理器节点检索信息。 | `false` | + +## 示例:检索单个索引的映射 + +以下示例检索 `products` 索引的映射: + +<!-- spec_insert_start +component: example_code +rest: GET /products/_mapping +--> + +GET /products/_mapping + +response = client.indices.get_mapping( + index = "products" +) + +<!-- spec_insert_end --> + +## 示例:检索多个索引的映射 + +您可以通过指定逗号分隔的列表在单个请求中检索多个索引的映射: + +<!-- spec_insert_start +component: example_code +rest: GET /products,products-us/_mapping +--> + +GET /products,products-us/_mapping + +response = client.indices.get_mapping( + index = "products,products-us" +) + +<!-- spec_insert_end --> + +## 示例:检索所有映射 + +要检索集群中所有索引的映射,请省略索引名称: + +<!-- spec_insert_start +component: example_code +rest: GET /_mapping +--> + +GET /_mapping + +response = client.indices.get_mapping() + +<!-- spec_insert_end --> + +## 示例响应 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "products" : { + "mappings" : { + "properties" : { + "description" : { + "type" : "text" + }, + "item_id" : { + "type" : "alias", + "path" : "product_id" + }, + "manufacturer" : { + "properties" : { + "country" : { + "type" : "keyword" + }, + "name" : { + "type" : "text" + } + } + }, + "price" : { + "type" : "float" + }, + "product_id" : { + "type" : "keyword" + }, + "product_name" : { + "type" : "text", + "fields" : { + "keyword" : { + "type" : "keyword", + "ignore_above" : 256 + } + } + }, + "sku" : { + "type" : "keyword", + "ignore_above" : 50 + }, + "weight" : { + "type" : "integer" + } + } + } + } +} +``` +</details> + +## 响应正文字段 + +响应包含一个 JSON 对象,其中每个键都是索引名称。下表描述了每个索引条目中的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `mappings` | Object | 索引的映射定义。 | +| `mappings.properties` | Object | 字段名称到其映射配置的映射,包括类型、参数和嵌套子字段。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/mappings/get`。 diff --git a/i18n/zh/api-reference/index-apis/get-template-legacy.md b/i18n/zh/api-reference/index-apis/get-template-legacy.md new file mode 100644 index 00000000..7d1cd0f8 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/get-template-legacy.md @@ -0,0 +1,88 @@ +--- +title: 获取模板(已弃用) +--- + +# 获取模板 +<Badge type="tip" text="引入版本 1.0" /> + +::: danger WARNING +获取模板 API 已被弃用。请使用新的[获取索引模板](/api-reference/index-apis/get-index-template) API。 +::: + +获取模板 API 操作用于检索使用旧版 `/_template` 端点创建的一个或多个索引模板。 + +## 端点 + +```json +GET /_template +GET /_template/{template-name} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有参数都是可选的。 + +| 参数 | 类型 | 描述 | +| :-------------- | :----- | :------------------------------------------------------------------------------- | +| `template-name` | String | 要检索的索引模板的名称。接受通配符表达式。 | + +## 查询参数 + +下表列出了可用的查询参数。所有参数都是可选的。 + +| 参数 | 类型 | 描述 | +| :--------------- | :------ | :--------------------------------------------------------------------------------------------------- | +| `flat_settings` | Boolean | 如果为 true,则以扁平格式返回设置。默认为 `false`。 | +| `local` | Boolean | 如果为 true,则请求不从集群管理器节点检索状态。默认为 `false`。 | +| `cluster_manager_timeout` | Time | 指定等待与集群管理器节点连接的时间。默认为 `30s`。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: GET /_template/sample-template +--> + +GET /_template/sample-template + +response = client.indices.get_template( + name = "sample-template" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "sample-template": { + "order": 1, + "index_patterns": [ + "sample-*" + ], + "settings": { + "number_of_shards": "1" + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + } + } + }, + "aliases": {} + } +} +``` + +## 响应字段 + +响应对象包含以下字段。 + +| 字段 | 类型 | 描述 | +| ---------------- | ---------------- | ------------------------------------------------------------------------------ | +| `order` | Integer | 一个整数,确定当多个模板匹配索引时模板的优先级。具有较高 order 值的模板具有较高的优先级并在较低 order 的模板之后应用,从而允许它们覆盖冲突的设置或映射。 | +| `index_patterns` | 字符串数组 | 模板应用到的索引名称模式列表。 | +| `settings` | Object | 模板中定义的索引级设置。 | +| `mappings` | Object | 为匹配模式的索引定义的字段映射。 | +| `aliases` | Object | 要与匹配索引关联的别名。 | diff --git a/i18n/zh/api-reference/index-apis/index-blocks-allocation.md b/i18n/zh/api-reference/index-apis/index-blocks-allocation.md new file mode 100644 index 00000000..5242acb4 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/index-blocks-allocation.md @@ -0,0 +1,16 @@ +--- +title: 索引块和分配 +--- + +# 索引块和分配 + +索引块和分配 API 提供对索引访问限制和分片分配策略的控制。这些 API 帮助您管理集群资源并控制索引如何分布在集群节点上。 + +## 可用 API + +OpenSearch 支持以下索引块和分配 API。 + +| API | 描述 | +|-----|-------------| +| [块](/api-reference/index-apis/blocks) | 添加或移除限制索引操作的索引块。 | +| [分片分配](/api-reference/index-apis/shard-allocation) | 控制索引的分片分配和路由。 | diff --git a/i18n/zh/api-reference/index-apis/index-operations.md b/i18n/zh/api-reference/index-apis/index-operations.md new file mode 100644 index 00000000..d35122f2 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/index-operations.md @@ -0,0 +1,27 @@ +--- +title: 索引操作 +--- + +# 索引操作 + +索引操作 API 提供了用于维护和优化 OpenSearch 集群中索引的高级功能。这些操作帮助您管理索引性能、数据组织和集群效率。 + +## 可用 API + +OpenSearch 支持以下索引操作 API。 + +| API | 描述 | +|-----|-------------| +| [清除索引缓存](/api-reference/index-apis/clear-index-cache) | 清除与一个或多个索引关联的缓存。 | +| [克隆索引](/api-reference/index-apis/clone) | 克隆现有索引。 | +| [刷新](/api-reference/index-apis/flush) | 刷新一个或多个索引。 | +| [强制合并](/api-reference/index-apis/force-merge) | 强制合并一个或多个索引。 | +| [索引恢复](/api-reference/index-apis/recover) | 返回关于正在进行和已完成的分片恢复的信息。 | +| [刷新](/api-reference/index-apis/refresh) | 刷新一个或多个索引。 | +| [滚动](/api-reference/index-apis/rollover) | 当满足特定条件时滚动索引。 | +| [缩放](/api-reference/index-apis/scale) | 缩放一个或多个索引的副本数量。 | +| [索引段](/api-reference/index-apis/segment) | 返回一个或多个索引的段信息。 | +| [索引分片存储](/api-reference/index-apis/shard-stores) | 返回关于分片副本及其存储位置的信息。 | +| [收缩索引](/api-reference/index-apis/shrink-index) | 收缩现有索引。 | +| [拆分](/api-reference/index-apis/split) | 拆分现有索引。 | +| [索引统计](/api-reference/index-apis/stats) | 返回一个或多个索引的统计信息。 | diff --git a/i18n/zh/api-reference/index-apis/index-settings-mappings.md b/i18n/zh/api-reference/index-apis/index-settings-mappings.md new file mode 100644 index 00000000..6383dc30 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/index-settings-mappings.md @@ -0,0 +1,17 @@ +--- +title: 索引设置和映射 +--- + +# 索引设置和映射 + +索引设置和映射 API 允许您配置和修改索引的行为和结构。这些 API 提供对索引级别设置和字段映射的控制,这些设置和映射决定了数据的存储和索引方式。 + +## 可用 API + +OpenSearch 支持以下索引设置和映射 API。 + +| API | 描述 | +|-----|-------------| +| [获取设置](/api-reference/index-apis/get-settings) | 返回一个或多个索引的设置信息。 | +| [更新设置](/api-reference/index-apis/update-settings) | 更新一个或多个索引的设置。 | +| [放置映射](/api-reference/index-apis/put-mapping) | 添加新字段或更新现有字段映射。 | diff --git a/i18n/zh/api-reference/index-apis/index-template-exists.md b/i18n/zh/api-reference/index-apis/index-template-exists.md new file mode 100644 index 00000000..dfd2a36f --- /dev/null +++ b/i18n/zh/api-reference/index-apis/index-template-exists.md @@ -0,0 +1,60 @@ +--- +title: 索引模板存在 +--- + +# 索引模板存在 +<Badge type="tip" text="引入版本 1.0" /> + +索引模板存在 API 操作用于验证索引模板是否存在。 + +## 端点 + +```json +HEAD /_index_template/{template-name} +``` + +## 路径参数 + +所有路径参数都是必需的。 + +| 参数 | 类型 | 描述 | +| --------------- | ------ | -------------------------------------------------- | +| `template-name` | String | 要检查是否存在的索引模板的名称。 | + +## 查询参数 + +所有参数都是可选的。 + +| 参数 | 类型 | 描述 | +| ------------------------- | ------- | ---------------------------------------------------------------------------------------------------- | +| `local` | Boolean | 如果为 true,则请求不从集群管理节点检索状态。默认为 `false`。 | +| `cluster_manager_timeout` | Time | 指定等待与集群管理节点连接的时间。默认为 `30s`。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: HEAD /_index_template/my-template +--> + +HEAD /_index_template/my-template + +response = client.indices.exists_index_template( + name = "my-template" +) + +<!-- spec_insert_end --> + +## 示例响应 + +如果模板存在,响应返回成功代码: + +```json +200 OK +``` + +如果模板不存在,响应返回失败代码: + +```json +404 Not Found +``` diff --git a/i18n/zh/api-reference/index-apis/index-templates.md b/i18n/zh/api-reference/index-apis/index-templates.md new file mode 100644 index 00000000..fe959d21 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/index-templates.md @@ -0,0 +1,34 @@ +--- +title: 索引模板 +--- + +# 索引模板 API + +索引模板 API 允许您创建和管理模板,这些模板会自动将设置、映射和别名应用于与特定模式匹配的新索引。模板提供了一种强大的方式来确保索引之间的一致性。 + +您可以在模板请求正文中添加注释,例如解释为什么使用某个设置。有关更多信息,请参阅[请求正文中的注释](/api-reference/common-parameters#comments-in-request-bodies)。 + +## 可用 API + +OpenSearch 支持以下索引模板 API。 + +| API | 描述 | +|-----|-------------| +| [创建索引模板](/api-reference/index-apis/create-index-template) | 创建或更新索引模板。 | +| [删除索引模板](/api-reference/index-apis/delete-index-template) | 删除索引模板。 | +| [获取索引模板](/api-reference/index-apis/get-index-template) | 返回关于一个或多个索引模板的信息。 | +| [索引模板存在](/api-reference/index-apis/index-template-exists) | 检查索引模板是否存在。 | +| [模拟索引模板](/api-reference/index-apis/simulate-index-template) | 模拟索引模板的应用。 | +| [组件模板](/api-reference/index-apis/component-template) | 管理可在索引模板中重用的组件模板。 | + +## 传统模板 API + +OpenSearch 还支持以下传统模板 API 以实现向后兼容。这些 API 使用较旧的模板格式,已弃用,建议使用前面的索引模板 API。 + +| API | 描述 | +|-----|-------------| +| [发布模板(传统)](/api-reference/index-apis/post-template-legacy) | 使用 POST 创建或更新传统索引模板。 | +| [放置模板(传统)](/api-reference/index-apis/put-template-legacy) | 使用 PUT 创建或更新传统索引模板。 | +| [获取模板(传统)](/api-reference/index-apis/get-template-legacy) | 返回关于一个或多个传统索引模板的信息。 | +| [模板存在(传统)](/api-reference/index-apis/template-exists-legacy) | 检查传统索引模板是否存在。 | +| [删除模板(传统)](/api-reference/index-apis/delete-template-legacy) | 删除传统索引模板。 | diff --git a/i18n/zh/api-reference/index-apis/pause-ingestion.md b/i18n/zh/api-reference/index-apis/pause-ingestion.md new file mode 100644 index 00000000..c00164dc --- /dev/null +++ b/i18n/zh/api-reference/index-apis/pause-ingestion.md @@ -0,0 +1,75 @@ +--- +title: 暂停摄取 +--- + +# 暂停摄取 API +<Badge type="tip" text="引入版本 3.0" /> + +暂停一个或多个索引的摄取。暂停后,OpenSearch 停止从流源消费指定索引中所有分片的数据。要重启摄取,使用[恢复摄取 API](/api-reference/index-apis/resume-ingestion)。 + +## 端点 + +```json +POST /{index}/ingestion/_pause +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `index` | String | 必需 | 要暂停的索引。可以是逗号分隔的多个索引名称列表。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time units | 等待与集群管理节点连接的时间量。默认为 `30s`。 | +| `timeout` | Time units | 等待集群响应的时间量。默认为 `30s`。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: POST /my-index/ingestion/_pause +--> + +POST /my-index/ingestion/_pause + +response = client.ingestion.pause( + index = "my-index" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true, + "shards_acknowledged": true +} +``` + +## 响应正文字段 + +下表列出了所有响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | 是否确认暂停请求。 | +| `shards_acknowledged` | Boolean | 各个分片是否确认暂停请求。 | +| `failures` | Array of objects | 分片级别失败列表。请参阅[失败](#failures)。 | +| `error` | String | 请求级别错误消息(如果有)。 | + +### 失败 + +`failures` 数组中的每个对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `shard` | Integer | 分片编号。 | +| `error` | String | 分片级别错误消息。 | diff --git a/i18n/zh/api-reference/index-apis/post-template-legacy.md b/i18n/zh/api-reference/index-apis/post-template-legacy.md new file mode 100644 index 00000000..a6b519f8 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/post-template-legacy.md @@ -0,0 +1,129 @@ +--- +title: 发布模板(已弃用) +--- + +# 发布模板 +<Badge type="tip" text="引入版本 1.0" /> + +::: danger WARNING +发布模板 API 已被弃用。请使用新的[创建或更新索引模板](/api-reference/index-apis/create-index-template) API。 +::: + +发布模板 API 操作用于创建或更新索引模板。模板定义在创建匹配索引时自动应用的设置、映射和别名。 + +## 端点 + +```json +POST /_template/{template-name} +``` + +## 路径参数 + +所有路径参数都是必需的。 + +| 参数 | 类型 | 描述 | +| :-------------- | :----- | :---------------------------------------------- | +| `template-name` | String | 要创建或更新的索引模板的名称。 | + +## 查询参数 + +所有查询参数都是可选的。 + +| 参数 | 类型 | 描述 | +| :--------------- | :------ | :---------------------------------------------------------------------------------------------------------------- | +| `order` | Integer | 如果多个模板匹配时应用模板的顺序。较高的值最后应用。默认为 `0`。 | +| `create` | Boolean | 如果为 `true`,则如果已存在同名模板,操作将失败。默认为 `false`。 | +| `cluster_manager_timeout` | Time | 指定等待与集群管理节点连接的时间。默认为 `30s`。 | + +## 请求正文 + +请求正文必须定义以下组件中的一个或多个。 + +| 字段 | 类型 | 描述 | +| :--------------- | :----- | :------------------------------------------------------------------- | +| `index_patterns` | Array | 模板应用的索引名称模式列表。必需。 | +| `settings` | Object | 应用于匹配索引的索引设置。 | +| `mappings` | Object | 索引中字段的映射。 | +| `aliases` | Object | 分配给匹配索引的别名。 | +| `version` | Integer | 用于标识模板的可选版本号。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: POST /_template/logs_template +body: | +{ + "index_patterns": ["logs-*"], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { "type": "date" }, + "message": { "type": "text" } + } + }, + "aliases": { + "logs": {} + } +} +--> + +POST /_template/logs_template +{ + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } +} + +response = client.indices.put_template( + name = "logs_template", + body = { + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` diff --git a/i18n/zh/api-reference/index-apis/pull-based-ingestion-management.md b/i18n/zh/api-reference/index-apis/pull-based-ingestion-management.md new file mode 100644 index 00000000..dd65040b --- /dev/null +++ b/i18n/zh/api-reference/index-apis/pull-based-ingestion-management.md @@ -0,0 +1,18 @@ +--- +title: 基于拉取的摄取管理 +--- + +# 基于拉取的摄取管理 +<Badge type="tip" text="引入版本 3.0" /> + +基于拉取的摄取管理 API 控制索引如何从其[基于拉取的摄取](/im-plugin/pull-based-ingestion/)源消费数据。您可以停止和重启摄取,重置分片读取的位置,并检查每个分片轮询器的状态。 + +## 可用 API + +OpenSearch 支持以下基于拉取的摄取管理 API。 + +| API | 描述 | +| :--- | :--- | +| [暂停摄取](/api-reference/index-apis/pause-ingestion) | 停止从源消费一个或多个索引中所有分片的数据。 | +| [恢复摄取](/api-reference/index-apis/resume-ingestion) | 重启消费数据,可选择从特定偏移量或时间戳开始。 | +| [获取摄取状态](/api-reference/index-apis/get-ingestion-state) | 返回一个或多个索引中每个分片的当前摄取状态。 | diff --git a/i18n/zh/api-reference/index-apis/put-template-legacy.md b/i18n/zh/api-reference/index-apis/put-template-legacy.md new file mode 100644 index 00000000..da11cc33 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/put-template-legacy.md @@ -0,0 +1,129 @@ +--- +title: 放置模板(已弃用) +--- + +# 放置模板 +<Badge type="tip" text="引入版本 1.0" /> + +::: danger WARNING +放置模板 API 已被弃用。请使用新的[创建或更新索引模板](/api-reference/index-apis/create-index-template) API。 +::: + +放置模板 API 操作用于创建或更新索引模板。模板定义在创建匹配索引时自动应用的设置、映射和别名。 + +## 端点 + +```json +PUT /_template/{template-name} +``` + +## 路径参数 + +所有路径参数都是必需的。 + +| 参数 | 类型 | 描述 | +| :-------------- | :----- | :---------------------------------------------- | +| `template-name` | String | 要创建或更新的索引模板的名称。 | + +## 查询参数 + +所有查询参数都是可选的。 + +| 参数 | 类型 | 描述 | +| :--------------- | :------ | :---------------------------------------------------------------------------------------------------------------- | +| `order` | Integer | 如果多个模板匹配时应用模板的顺序。较高的值最后应用。默认为 `0`。 | +| `create` | Boolean | 如果为 `true`,则如果已存在同名模板,操作将失败。默认为 `false`。 | +| `cluster_manager_timeout` | Time | 指定等待与集群管理节点连接的时间。默认为 `30s`。 | + +## 请求正文 + +请求正文必须定义以下组件中的一个或多个。 + +| 字段 | 类型 | 描述 | +| :--------------- | :----- | :------------------------------------------------------------------- | +| `index_patterns` | Array | 模板应用的索引名称模式列表。必需。 | +| `settings` | Object | 应用于匹配索引的索引设置。 | +| `mappings` | Object | 索引中字段的映射。 | +| `aliases` | Object | 分配给匹配索引的别名。 | +| `version` | Integer | 用于标识模板的可选版本号。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: PUT /_template/logs_template +body: | +{ + "index_patterns": ["logs-*"], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { "type": "date" }, + "message": { "type": "text" } + } + }, + "aliases": { + "logs": {} + } +} +--> + +PUT /_template/logs_template +{ + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } +} + +response = client.indices.put_template( + name = "logs_template", + body = { + "index_patterns": [ + "logs-*" + ], + "settings": { + "number_of_shards": 1 + }, + "mappings": { + "properties": { + "@timestamp": { + "type": "date" + }, + "message": { + "type": "text" + } + } + }, + "aliases": { + "logs": {} + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` diff --git a/i18n/zh/api-reference/index-apis/recover.md b/i18n/zh/api-reference/index-apis/recover.md new file mode 100644 index 00000000..af3408d3 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/recover.md @@ -0,0 +1,314 @@ +--- +title: 索引恢复 +--- + +# 索引恢复 API +<Badge type="tip" text="引入版本 1.0" /> + +恢复 API 提供关于一个或多个索引的任何已完成或正在进行的分片恢复的信息。如果列出了数据流,API 将返回关于该数据流的后备索引的信息。 + +分片恢复涉及创建分片副本以从快照恢复主分片或同步副本分片。分片恢复过程完成后,恢复的分片可用于搜索和索引操作。 + +分片恢复在以下场景中自动发生: + +- 节点启动,称为本地存储恢复 +- 主分片的复制 +- 将分片重新定位到同一集群内的不同节点 +- 恢复快照 +- 克隆、收缩或拆分操作 + +恢复 API 仅报告当前存储在集群中的分片副本的已完成恢复。它仅报告每个分片副本的最近恢复,不包括关于以前恢复的历史信息或关于不再存在的分片副本的恢复信息。因此,如果分片副本完成恢复后随后被重新定位到不同的节点,则原始恢复的信息不会显示在恢复 API 中。 + +## 端点 + +```json +GET /_recovery +GET /{index}/_recovery/ +``` + +## 路径参数 + +参数 | 数据类型 | 描述 +:--- | :--- +`index` | String | 应用操作的索引、数据流或索引别名的逗号分隔列表。支持通配符表达式(`*`)。使用 `_all` 或 `*` 指定集群中的所有索引和数据流。 | + +## 查询参数 + +以下所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`active_only` | Boolean | 当为 `true` 时,响应仅包括活动分片恢复。默认为 `false`。 +`detailed` | Boolean | 当为 `true` 时,提供关于分片恢复的详细信息。默认为 `false`。 +`index` | String | 用于限制请求的索引名称的逗号分隔列表或通配符表达式。 + +## 示例请求 + +以下示例演示如何使用恢复 API 恢复信息。 + +### 从多个或所有索引恢复信息 + +以下示例请求以[人类可读格式](/api-reference/common-parameters#human-readable-output)返回多个索引的恢复信息: + +<!-- spec_insert_start +component: example_code +rest: GET /index1,index2/_recovery?human +--> + +GET /index1,index2/_recovery?human + +response = client.indices.recovery( + index = "index1,index2", + params = { "human": "true" } +) + +<!-- spec_insert_end --> + +以下示例请求以人类可读格式返回所有索引的恢复信息: + +<!-- spec_insert_start +component: example_code +rest: GET /_recovery?human +--> + +GET /_recovery?human + +response = client.indices.recovery( + params = { "human": "true" } +) + +<!-- spec_insert_end --> + +### 恢复详细信息 + +以下示例请求返回详细的恢复信息: + +<!-- spec_insert_start +component: example_code +rest: GET /_recovery?human&detailed=true +--> + +GET /_recovery?human&detailed=true + +response = client.indices.recovery( + params = { "human": "true", "detailed": "true" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下响应返回关于名为 `shakespeare` 的索引的详细恢复信息: + +```json +{ + "shakespeare": { + "shards": [ + { + "id": 0, + "type": "EXISTING_STORE", + "stage": "DONE", + "primary": true, + "start_time": "2024-07-01T18:06:47.415Z", + "start_time_in_millis": 1719857207415, + "stop_time": "2024-07-01T18:06:47.538Z", + "stop_time_in_millis": 1719857207538, + "total_time": "123ms", + "total_time_in_millis": 123, + "source": { + "bootstrap_new_history_uuid": false + }, + "target": { + "id": "uerS7REgRQCbBF3ImY8wOQ", + "host": "172.18.0.3", + "transport_address": "172.18.0.3:9300", + "ip": "172.18.0.3", + "name": "opensearch-node2" + }, + "index": { + "size": { + "total": "17.8mb", + "total_in_bytes": 18708764, + "reused": "17.8mb", + "reused_in_bytes": 18708764, + "recovered": "0b", + "recovered_in_bytes": 0, + "percent": "100.0%" + }, + "files": { + "total": 7, + "reused": 7, + "recovered": 0, + "percent": "100.0%", + "details": [ + { + "name": "_1.cfs", + "length": "9.8mb", + "length_in_bytes": 10325945, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_0.cfe", + "length": "479b", + "length_in_bytes": 479, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_0.si", + "length": "333b", + "length_in_bytes": 333, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_1.cfe", + "length": "479b", + "length_in_bytes": 479, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_1.si", + "length": "333b", + "length_in_bytes": 333, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "_0.cfs", + "length": "7.9mb", + "length_in_bytes": 8380790, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + }, + { + "name": "segments_3", + "length": "405b", + "length_in_bytes": 405, + "reused": true, + "recovered": "0b", + "recovered_in_bytes": 0 + } + ] + }, + "total_time": "6ms", + "total_time_in_millis": 6, + "source_throttle_time": "-1", + "source_throttle_time_in_millis": 0, + "target_throttle_time": "-1", + "target_throttle_time_in_millis": 0 + }, + "translog": { + "recovered": 0, + "total": 0, + "percent": "100.0%", + "total_on_start": 0, + "total_time": "113ms", + "total_time_in_millis": 113 + }, + "verify_index": { + "check_index_time": "0s", + "check_index_time_in_millis": 0, + "total_time": "0s", + "total_time_in_millis": 0 + } + }, + { + "id": 0, + "type": "PEER", + "stage": "DONE", + "primary": false, + "start_time": "2024-07-01T18:06:47.693Z", + "start_time_in_millis": 1719857207693, + "stop_time": "2024-07-01T18:06:47.744Z", + "stop_time_in_millis": 1719857207744, + "total_time": "50ms", + "total_time_in_millis": 50, + "source": { + "id": "uerS7REgRQCbBF3ImY8wOQ", + "host": "172.18.0.3", + "transport_address": "172.18.0.3:9300", + "ip": "172.18.0.3", + "name": "opensearch-node2" + }, + "target": { + "id": "HFYKietmTO6Ud9COgP0k9Q", + "host": "172.18.0.2", + "transport_address": "172.18.0.2:9300", + "ip": "172.18.0.2", + "name": "opensearch-node1" + }, + "index": { + "size": { + "total": "0b", + "total_in_bytes": 0, + "reused": "0b", + "reused_in_bytes": 0, + "recovered": "0b", + "recovered_in_bytes": 0, + "percent": "0.0%" + }, + "files": { + "total": 0, + "reused": 0, + "recovered": 0, + "percent": "0.0%", + "details": [] + }, + "total_time": "1ms", + "total_time_in_millis": 1, + "source_throttle_time": "-1", + "source_throttle_time_in_millis": 0, + "target_throttle_time": "-1", + "target_throttle_time_in_millis": 0 + }, + "translog": { + "recovered": 0, + "total": 0, + "percent": "100.0%", + "total_on_start": -1, + "total_time": "42ms", + "total_time_in_millis": 42 + }, + "verify_index": { + "check_index_time": "0s", + "check_index_time_in_millis": 0, + "total_time": "0s", + "total_time_in_millis": 0 + } + } + ] + } +} +``` + +## 响应正文字段 + +API 以以下关于恢复分片的信息响应。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`id` | Integer | 分片的 ID。 +`type` | String | 分片的恢复源。返回值包括:<br> - `EMPTY_STORE`:空存储。表示新的主分片或使用集群重新路由 API 强制分配的空主分片。<br> - `EXISTING_STORE`:现有主分片的存储。表示恢复与节点启动或现有主分片的分配有关。<br> - `LOCAL_SHARDS`:属于同一节点上另一个索引的分片。表示恢复与克隆、收缩或拆分操作有关。<br> - `PEER`:另一个节点上的主分片。表示恢复与分片复制有关。<br> - `SNAPSHOT`:快照。表示恢复与快照恢复操作有关。 +`STAGE` | String | 恢复阶段。返回值可以包括:<br> - `INIT`:恢复未开始。<br> - `INDEX`:读取索引元数据并从源复制字节到目标。<br> - `VERIFY_INDEX`:验证索引的完整性。<br> - `TRANSLOG`:重放事务日志。<br> - `FINALIZE`:清理。<br> - `DONE`:完成。 +`primary` | Boolean | 当为 `true` 时,分片是主分片。 +`start_time` | String | 表示恢复开始时间的时间戳。 +`stop_time` | String | 表示恢复完成时间的时间戳。 +`total_time_in_millis` | String | 恢复分片所用的总时间量(以毫秒为单位)。 +`source` | Object | 恢复源。这可以包括仓库的描述(如果恢复来自快照)或源节点的描述。 +`target` | Object | 目标节点。 +`index` | Object | 关于物理索引恢复的统计信息。 +`translog` | Object | 关于事务日志恢复的统计信息。 + `start` | Object | 关于打开和启动索引所用时间量的统计信息。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:monitor/recovery`。 diff --git a/i18n/zh/api-reference/index-apis/refresh.md b/i18n/zh/api-reference/index-apis/refresh.md new file mode 100644 index 00000000..4e0747fb --- /dev/null +++ b/i18n/zh/api-reference/index-apis/refresh.md @@ -0,0 +1,105 @@ +--- +title: 刷新索引 +--- + +# 刷新索引 API +<Badge type="tip" text="引入版本 1.0" /> + +刷新索引 API 刷新一个或多个索引,使自上次刷新以来对这些索引执行的所有操作可用于搜索。当您索引文档时,它首先写入事务日志并添加到内存缓冲区。文档在刷新操作将这些内存结构转换为磁盘上的可搜索段之前是不可搜索的。对于数据流,刷新索引 API 刷新流的后备索引。 + +有关刷新操作在 OpenSearch 中如何工作的概念性概述,请参阅[刷新](/getting-started/concepts/#refresh)。 + +## 刷新间隔 + +`index.refresh_interval` 设置控制索引自动刷新的频率。OpenSearch 的刷新行为取决于是否设置了 `index.refresh_interval`: + +- 设置时,索引根据 `index.refresh_interval` 设置(以秒为单位)刷新。有关 `index.refresh_interval` 设置的更多信息,请参阅[动态索引设置](/install-and-configure/configuring-opensearch/index-settings#dynamic-index-settings)。 +- 未设置时,每秒刷新一次,直到分片至少在 `index.search.idle.after` 设置(以秒为单位)指定的时间内没有收到搜索请求。默认为 `30s`。 + +分片空闲后,索引在下一个搜索请求或刷新索引 API 请求发送之前不会刷新。空闲分片上的第一个搜索请求将等待刷新操作完成。 + +要使用刷新索引 API,您必须对要刷新的索引具有写访问权限。 + +## 刷新请求行为 + +刷新索引 API 调用是同步的。仅在所有目标分片都已刷新后才返回响应。 + +## 最佳实践 + +刷新操作是资源密集型的,可能会影响集群性能。为确保最佳集群性能,我们建议以下最佳实践: + +- **依赖自动刷新**:尽可能等待 OpenSearch 的定期刷新(由 `index.refresh_interval` 控制),而不是执行显式刷新。 +- **对索引工作流使用 `refresh=wait_for`**:如果您的应用程序索引文档然后立即搜索它们,请在索引操作上使用 `refresh=wait_for` 查询参数,而不是调用刷新 API。此选项确保索引操作在返回之前等待定期刷新,而不会强制立即刷新。有关更多信息,请参阅[`refresh` 查询参数](#the-refresh-query-parameter)。 +- **在生产中避免 `refresh=true`**:在索引、更新或删除操作上使用 `refresh=true` 会强制立即刷新并创建低效的索引结构(小段),这些结构稍后必须合并,从而影响索引和搜索性能。 + +## 端点 + +```json +POST /_refresh +GET /_refresh +POST /{index}/_refresh +GET /{index}/_refresh +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index` | String | 要刷新的索引名称的逗号分隔列表。接受通配符。| + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `ignore_unavailable` | Boolean | 当为 `false` 时,如果请求针对缺失或关闭的索引,则返回错误。默认为 `false`。 +| `allow_no_indices` | Boolean | 当为 `false` 时,如果通配符表达式、索引别名或 `_all` 仅针对关闭或缺失的索引,即使请求针对打开的索引,刷新索引 API 也会返回错误。默认为 `true`。 | +| `expand_wildcards` | String | 通配符模式可以匹配的索引类型。如果请求针对数据流,此参数确定通配符表达式是否匹配任何隐藏的数据流。支持逗号分隔的值,例如 `open,hidden`。有效值为 `all`、`open`、`closed`、`hidden` 和 `none`。 + +## 示例请求:刷新多个数据流或索引 + +以下示例请求刷新名为 `my-index-A` 和 `my-index-B` 的两个索引: + +<!-- spec_insert_start +component: example_code +rest: POST /my-index-A,my-index-B/_refresh +--> + +POST /my-index-A,my-index-B/_refresh + +response = client.indices.refresh( + index = "my-index-A,my-index-B" +) + +<!-- spec_insert_end --> + +## 示例请求:刷新所有数据流和索引 + +以下请求刷新集群中的所有数据流和索引: + +```json +POST /_refresh +``` + +## 示例请求:使用 GET 方法刷新 + +您也可以使用 `GET` 方法刷新索引。以下示例使用 `GET` 刷新特定索引: + +```json +GET /my-index/_refresh +``` + +`GET` 方法与 `POST` 方法工作方式相同,在限制 `POST` 请求的环境中很有用,或者当您更喜欢对类似读取的操作使用 `GET` 时。 + +## refresh 查询参数 + +文档 API(如索引、更新、删除和批量 API)支持 `refresh` 查询参数,该参数控制请求所做的更改何时对搜索可见。此参数提供了显式调用刷新索引 API 的替代方法。 + +有关 `refresh` 参数的更多信息,请参阅[索引文档 API](/api-reference/document-apis/index-document)、[更新文档 API](/api-reference/document-apis/update-document)、[删除文档 API](/api-reference/document-apis/delete-document) 和[批量 API](/api-reference/document-apis/bulk) 文档。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/refresh` 和 `indices:admin/refresh*`。 diff --git a/i18n/zh/api-reference/index-apis/resolve-index.md b/i18n/zh/api-reference/index-apis/resolve-index.md new file mode 100644 index 00000000..99e7f6bf --- /dev/null +++ b/i18n/zh/api-reference/index-apis/resolve-index.md @@ -0,0 +1,128 @@ +--- +title: 解析索引 +--- + +# 解析索引 API +<Badge type="tip" text="引入版本 1.0" /> + +解析索引 API 帮助您了解 OpenSearch 如何解析匹配指定名称或通配符表达式的别名、数据流和具体索引。 + +## 端点 + +```json +GET /_resolve/index/{name} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | String | 要解析的名称、别名、数据流或通配符表达式。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `expand_wildcards` | String | 控制通配符表达式如何扩展到匹配的索引。可以使用逗号组合多个值。有效值为:<br>• `all` – 扩展到打开和关闭的索引,包括隐藏的索引。<br>• `open` – 仅扩展到打开的索引。<br>• `closed` – 仅扩展到关闭的索引。<br>• `hidden` – 包括隐藏的索引(必须与 `open`、`closed` 或两者一起使用)。<br>• `none` – 不接受通配符表达式。<br>**默认值**:`open`。 | + +## 示例请求 + +以下部分提供了解析 API 请求的示例。 + +### 解析具体索引 + +<!-- spec_insert_start +component: example_code +rest: GET /_resolve/index/my-index-001 +--> + +GET /_resolve/index/my-index-001 + +response = client.indices.resolve_index( + name = "my-index-001" +) + +<!-- spec_insert_end --> + +### 使用通配符解析索引 + +<!-- spec_insert_start +component: example_code +rest: GET /_resolve/index/my-index-* +--> + +GET /_resolve/index/my-index-* + +response = client.indices.resolve_index( + name = "my-index-*" +) + +<!-- spec_insert_end --> + +### 解析数据流或别名 + +如果存在名为 `logs-app` 的别名或数据流,使用以下请求解析它: + +<!-- spec_insert_start +component: example_code +rest: GET /_resolve/index/logs-app +--> + +GET /_resolve/index/logs-app + +response = client.indices.resolve_index( + name = "logs-app" +) + +<!-- spec_insert_end --> + +### 在远程集群中使用通配符解析隐藏索引 + +以下示例显示使用通配符、远程集群和配置为 `hidden` 的 `expand_wildcards` 的 API 请求: + +<!-- spec_insert_start +component: example_code +rest: GET /_resolve/index/my-index-*,remote-cluster:my-index-*?expand_wildcards=hidden +--> + +GET /_resolve/index/my-index-*,remote-cluster:my-index-*?expand_wildcards=hidden + +response = client.indices.resolve_index( + name = "my-index-*,remote-cluster:my-index-*", + params = { "expand_wildcards": "hidden" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "indices": [ + { + "name": "my-index-001", + "attributes": [ + "open" + ] + } + ], + "aliases": [], + "data_streams": [] +} +``` + +## 响应正文字段 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `indices` | Array | 已解析的具体索引列表。 | +| `aliases` | Array | 已解析的索引别名列表。 | +| `data_streams` | Array | 匹配的数据流列表。 | + +## 所需权限 + +如果您使用安全插件,运行这些查询的用户需要对已解析的索引至少具有 `read` 权限。 diff --git a/i18n/zh/api-reference/index-apis/resume-ingestion.md b/i18n/zh/api-reference/index-apis/resume-ingestion.md new file mode 100644 index 00000000..68ae3de0 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/resume-ingestion.md @@ -0,0 +1,142 @@ +--- +title: 恢复摄取 +--- + +# 恢复摄取 API +<Badge type="tip" text="引入版本 3.0" /> + +恢复使用[暂停摄取 API](/api-reference/index-apis/pause-ingestion) 暂停的一个或多个索引的摄取。恢复后,OpenSearch 继续从流源消费指定索引中所有分片的数据。 + +作为恢复操作的一部分,您可以选择重置流消费者以从特定偏移量或时间戳开始读取。如果指定了重置设置,所选分片的所有消费者在恢复操作应用于索引之前都会被重置。重置消费者还会触发内部刷新以保留更改。 + +## 端点 + +```json +POST /{index}/ingestion/_resume +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `index` | String | 必需 | 要恢复摄取的索引。可以是逗号分隔的多个索引名称列表。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time units | 等待与集群管理节点连接的时间量。默认为 `30s`。 | +| `timeout` | Time units | 等待集群响应的时间量。默认为 `30s`。 | + +## 请求正文字段 + +下表列出了可用的请求正文字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `reset_settings` | Array of objects | 可选 | 重置设置列表,每个要重置的分片一个。如果未提供,OpenSearch 从指定索引中每个分片的当前位置恢复摄取。请参阅[重置设置](#reset-settings)。 | + +### 重置设置 + +`reset_settings` 数组中的每个对象包含以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `shard` | Integer | 必需 | 要重置的分片。 | +| `mode` | String | 必需 | 重置模式。有效值为 `offset`(正整数偏移量)和 `timestamp`(Unix 时间戳,以毫秒为单位)。 | +| `value` | String | 必需 |  • `offset`:Apache Kafka 偏移量或 Amazon Kinesis 序列号<br> • `timestamp`:Unix 时间戳(以毫秒为单位)。 | + +## 示例请求:从当前位置恢复摄取 + +要在不指定重置设置的情况下恢复摄取,发送以下请求: + +<!-- spec_insert_start +component: example_code +rest: POST /my-index/ingestion/_resume +--> + +POST /my-index/ingestion/_resume + +response = client.ingestion.resume( + index = "my-index" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "acknowledged": true, + "shards_acknowledged": true +} +``` + +## 示例请求:从特定偏移量恢复摄取 + +要在恢复摄取时将分片 `0` 重置为偏移量 `1`,发送以下请求: + +<!-- spec_insert_start +component: example_code +rest: POST /my-index/ingestion/_resume +body: | +{ + "reset_settings": [ + { + "shard": 0, + "mode": "offset", + "value": "1" + } + ] +} +--> + +POST /my-index/ingestion/_resume +{ + "reset_settings": [ + { + "shard": 0, + "mode": "offset", + "value": "1" + } + ] +} + +response = client.ingestion.resume( + index = "my-index", + body = { + "reset_settings": [ + { + "shard": 0, + "mode": "offset", + "value": "1" + } + ] + } +) + +<!-- spec_insert_end --> + +## 响应正文字段 + +下表列出了所有响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `acknowledged` | Boolean | 是否确认恢复请求。 | +| `shards_acknowledged` | Boolean | 各个分片是否确认恢复请求。 | +| `failures` | Array of objects | 分片级别失败列表。请参阅[失败](#failures)。 | +| `error` | String | 请求级别错误消息(如果有)。 | + +### 失败 + +`failures` 数组中的每个对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `shard` | Integer | 分片编号。 | +| `error` | String | 分片级别错误消息。 | diff --git a/i18n/zh/api-reference/index-apis/rollover.md b/i18n/zh/api-reference/index-apis/rollover.md new file mode 100644 index 00000000..a0d076d8 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/rollover.md @@ -0,0 +1,270 @@ +--- +title: 滚动索引 +--- + +# 滚动索引 API +<Badge type="tip" text="引入版本 1.0" /> + +滚动索引 API 为数据流或索引别名创建新索引,可以是无条件的,也可以在当前写索引满足指定条件时创建。 + +## 端点 + +```json +POST /{rollover-target}/_rollover/ +POST /{rollover-target}/_rollover/{target-index} +``` + +## 滚动类型 + +您可以滚动数据流、具有一个索引的索引别名或具有写索引的索引别名。 + +### 数据流 + +当您对数据流执行滚动操作时,API 为该流生成一个新的写索引。同时,流的前一个写索引转换为常规后备索引。此外,滚动过程会增加数据流的代数计数。数据流滚动不支持 `target-index` 路径参数或 `aliases`、`mappings` 和 `settings` 请求正文字段,因为数据流命名其后备索引,其索引模板配置它们。 + +### 具有一个索引的索引别名 + +当对与单个索引关联的索引别名发起滚动时,API 生成新索引并将原始索引与别名解除关联。 + +### 具有写索引的索引别名 + +当索引别名引用多个索引时,必须将一个索引指定为写索引。在滚动期间,API 创建一个新的写索引,其 `is_write_index` 属性设置为 `true`,同时更新前一个写索引,将其 `is_write_index` 属性设置为 `false`。 + +## 为别名递增索引名称 + +在索引别名滚动过程中,如果您不指定自定义名称并且当前索引的名称以连字符后跟数字结尾(例如,`my-index-000001` 或 `my-index-3`),则滚动操作将自动为新索引的名称递增该数字。例如,滚动 `my-index-000001` 将生成 `my-index-000002`。数字部分始终用前导零填充以确保一致的六个字符长度。 + +## 在索引滚动中使用日期数学 + +当将索引别名用于时间序列数据时,您可以在索引名称中使用[日期数学](/mappings/supported-field-types/date/)来跟踪滚动日期。例如,您可以创建一个指向 `my-index-{now/d}-000001` 的别名。如果您在 2029 年 6 月 11 日创建别名,则索引名称将为 `my-index-2029.06.11-000001`。对于 2029 年 6 月 12 日的滚动,新索引将命名为 `my-index-2029.06.12-000002`。有关实际示例,请参阅[滚动具有写索引的索引别名](#rolling-over-an-index-alias-with-a-write-index)。有关完整的日期数学索引名称语法以及必须在请求 URL 中编码的字符,请参阅[索引名称中的日期数学](/api-reference/index-name-syntax#date-math-in-index-names)。 + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`rollover-target` | String | 要滚动的数据流或索引别名的名称。必需。 | +`target-index` | String | 要创建的索引的名称。支持日期数学。数据流不支持此参数。如果别名的当前写索引的名称不以 `-` 和数字结尾,例如 `my-index-000001` 或 `my-index-2`,则该参数是必需的。 + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`cluster_manager_timeout` | Time | 等待与集群管理节点连接的时间量。默认为 `30s`。 +`dry_run` | Boolean | 如果为 `true`,OpenSearch 检查当前索引是否满足滚动条件并返回将创建的索引的名称,但不执行滚动。默认为 `false`。 +`timeout` | Time | 等待响应的时间量。默认为 `30s`。 +`wait_for_active_shards` | String | 在 OpenSearch 返回响应之前必须处于活动状态的新索引的分片副本数。默认为 `1`(仅主分片)。您还可以设置为 `all` 或正整数。大于 `1` 的值需要副本。例如,如果您指定值 `3`,则新索引必须有两个副本分布在两个附加节点上。无论此设置如何,都会执行滚动。如果所需的分片在 `cluster_manager_timeout` 期间内未处于活动状态,则响应包含 `"shards_acknowledged": false`。 + +## 请求正文字段 + +以下请求正文字段受支持。 + +### `aliases` + +`aliases` 参数指定要添加到新索引的别名。它是可选的。`aliases` 对象按别名名称键控。每个别名对象支持以下可选参数。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`filter` | Query DSL object | 限制别名可以访问的文档数量的查询。 +`index_routing` | String | 将索引操作路由到特定分片的值。指定时,覆盖索引操作的 `routing` 值。 +`is_hidden` | Boolean | 隐藏或显示别名。当为 `true` 时,别名是隐藏的。默认为 `false`。别名的索引必须具有此设置的匹配值。 +`is_write_index` | Boolean | 指定写索引。当为 `true` 时,索引是别名的写索引。默认为 `false`。 +`routing` | String | 用于将索引和搜索操作路由到特定分片的值。 +`search_routing` | String | 将搜索操作路由到特定分片。指定时,它覆盖搜索操作的 `routing`。 + +### `mappings` + +`mappings` 参数指定索引字段映射。它是可选的。有关更多信息,请参阅[映射和字段类型](/mappings/)。 + +### `conditions` + +`conditions` 参数是一个可选对象,定义触发滚动的标准。提供时,OpenSearch 仅在当前索引满足一个或多个指定条件时滚动。如果省略,则无条件发生滚动,没有先决条件。 + +对象正文支持以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`max_age` | Time units | 在达到自索引创建以来的最大经过时间后触发滚动。可选。 | +`max_docs` | Integer | 在达到指定的最大文档数后触发滚动,不包括自上次刷新以来添加的文档和副本分片中的文档。可选。 +`max_size` | Byte units | 当索引达到指定大小时触发滚动,计算为所有主分片的总大小。不计算副本。使用 `_cat indices` API 并检查 `pri.store.size` 值以查看当前索引大小。可选。 + +### `settings` + +`settings` 参数指定索引配置选项。有关更多信息,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +## 示例请求 + +以下示例说明了使用滚动索引 API。当满足以下一个或多个指定条件时发生滚动: + +- 索引是在 5 天或更早之前创建的。 +- 索引包含 500 个或更多文档。 +- 索引为 100 GB 或更大。 + +### 滚动数据流 + +要创建数据流,首先创建一个为匹配 `my-data-stream*` 模式的索引启用数据流的索引模板: + +```json +PUT _index_template/my-data-stream-template +{ + "index_patterns": ["my-data-stream*"], + "data_stream": {} +} +``` + +然后创建数据流: + +```json +PUT _data_stream/my-data-stream +``` + +有关更多信息,请参阅[数据流](/im-plugin/data-streams)。 + +如果当前写索引满足任何指定条件,以下请求将滚动数据流: + +<!-- spec_insert_start +component: example_code +rest: POST /my-data-stream/_rollover +body: | +{ + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } +} +--> + +POST /my-data-stream/_rollover +{ + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } +} + +response = client.indices.rollover( + alias = "my-data-stream", + body = { + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } + } +) + +<!-- spec_insert_end --> + +### 滚动具有写索引的索引别名 + +以下请求创建一个日期时间索引并将其设置为 `my-alias` 的写索引。索引名称必须进行 URL 编码:`%3Cmy-index-%7Bnow%2Fd%7D-000001%3E` 是 `<my-index-{now/d}-000001>` 的编码形式,`{now/d}` 解析为当前日期: + +```json +PUT %3Cmy-index-%7Bnow%2Fd%7D-000001%3E +{ + "aliases": { + "my-alias": { + "is_write_index": true + } + } +} +``` + +下一个请求使用别名执行滚动: + +<!-- spec_insert_start +component: example_code +rest: POST /my-alias/_rollover +body: | +{ + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } +} +--> + +POST /my-alias/_rollover +{ + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } +} + +response = client.indices.rollover( + alias = "my-alias", + body = { + "conditions": { + "max_age": "5d", + "max_docs": 500, + "max_size": "100gb" + } + } +) + +<!-- spec_insert_end --> + +### 在滚动期间指定设置 + +在大多数情况下,您可以使用索引模板自动配置在滚动操作期间创建的索引。但是,当滚动索引别名时,您可以使用滚动索引 API 通过发送以下请求来引入额外的索引设置或覆盖模板中定义的设置: + +<!-- spec_insert_start +component: example_code +rest: POST /my-alias/_rollover +body: | +{ + "settings": { + "index.number_of_shards": 4 + } +} +--> + +POST /my-alias/_rollover +{ + "settings": { + "index.number_of_shards": 4 + } +} + +response = client.indices.rollover( + alias = "my-alias", + body = { + "settings": { + "index.number_of_shards": 4 + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下数据流滚动的示例响应显示除 `max_size` 之外的所有条件都已满足。如果写索引是新创建的并且不满足任何条件,则响应包含 `"rolled_over": false`,OpenSearch 不创建新索引: + +```json +{ + "acknowledged": true, + "shards_acknowledged": true, + "old_index": ".ds-my-data-stream-000001", + "new_index": ".ds-my-data-stream-000002", + "rolled_over": true, + "dry_run": false, + "conditions": { + "[max_age: 5d]": true, + "[max_docs: 500]": true, + "[max_size: 100gb]": false + } +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/rollover`。 diff --git a/i18n/zh/api-reference/index-apis/scale.md b/i18n/zh/api-reference/index-apis/scale.md new file mode 100644 index 00000000..e2ebafe1 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/scale.md @@ -0,0 +1,68 @@ +--- +title: 缩放 +--- + +# 缩放 API +<Badge type="tip" text="引入版本 3.0" /> + +缩放 API 允许您在索引上启用或禁用 `search_only` 模式。当索引处于 `search_only` 模式时,它仅保留其搜索副本,并缩减主分片和常规副本分片。这种优化有助于在低写入活动期间减少资源消耗,同时保持搜索能力。 + +此功能支持诸如零扩展部署和读写器分离模式等场景,这可以显著提高生产环境中的资源利用率并降低成本。 + +::: info NOTE +如果您使用安全插件,则必须具有 `manage index` 权限。 +::: + +## 端点 + +```json +POST /{index}/_scale +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `index` | **必需** | String | 要缩放的索引名称。不支持通配符。 | + +## 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `search_only` | **必需** | Boolean | 当为 `true` 时,在索引上启用仅搜索模式。当为 `false` 时,禁用仅搜索模式并将索引恢复到正常操作。 | + +## 示例请求:启用仅搜索模式 + +以下请求为名为 `my-index` 的索引启用仅搜索模式: + +```json +POST /my-index/_scale +{ + "search_only": true +} +``` + +## 示例请求:禁用仅搜索模式 + +以下请求禁用仅搜索模式并将索引恢复到正常操作: + +```json +POST /my-index/_scale +{ + "search_only": false +} +``` + +## 示例响应 + +API 返回以下响应: + +```json +{ + "acknowledged": true +} +``` diff --git a/i18n/zh/api-reference/index-apis/segment.md b/i18n/zh/api-reference/index-apis/segment.md new file mode 100644 index 00000000..c26a8abb --- /dev/null +++ b/i18n/zh/api-reference/index-apis/segment.md @@ -0,0 +1,141 @@ +--- +title: 索引段 +--- + +# 索引段 API +<Badge type="tip" text="引入版本 1.0" /> + +段 API 提供有关索引分片内 Lucene 段的详细信息以及数据流的后备索引信息。 + +## 端点 + +```json +GET /{index}/_segments +GET /_segments +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`index` | String | 应用该操作的索引、数据流或索引别名的逗号分隔列表。支持通配符表达式(`*`)。使用 `_all` 或 `*` 指定集群中的所有索引和数据流。 | + +## 查询参数 + +所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`allow_no_indices` | Boolean | 是否忽略不匹配任何索引的通配符。默认值为 `true`。 +`expand_wildcards` | String | 指定通配符表达式可以匹配的索引类型。支持逗号分隔的值。有效值为 `all`(匹配任何索引)、`open`(匹配打开的非隐藏索引)、`closed`(匹配关闭的非隐藏索引)、`hidden`(匹配隐藏索引)和 `none`(拒绝通配符表达式)。默认值为 `open`。 +`ignore_unavailable` | Boolean | 当为 `true` 时,OpenSearch 忽略缺失或关闭的索引。如果为 `false`,则强制合并操作遇到缺失或关闭的索引时,OpenSearch 返回错误。默认值为 `false`。 +`verbose` | Boolean | 当为 `true` 时,提供有关 Lucene 内存使用情况的信息。默认值为 `false`。 + +## 示例请求 + +以下示例请求展示了如何使用段 API。 + +### 特定数据流或索引 + +<!-- spec_insert_start +component: example_code +rest: GET /index1/_segments +--> + +GET /index1/_segments + +response = client.indices.segments( + index = "index1" +) + +<!-- spec_insert_end --> + +### 多个数据流和索引 + +<!-- spec_insert_start +component: example_code +rest: GET /index1,index2/_segments +--> + +GET /index1,index2/_segments + +response = client.indices.segments( + index = "index1,index2" +) + +<!-- spec_insert_end --> + +### 集群中的所有数据流和索引 + +<!-- spec_insert_start +component: example_code +rest: GET /_segments +--> + +GET /_segments + +response = client.indices.segments() + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "_shards": ... + "indices": { + "test": { + "shards": { + "0": [ + { + "routing": { + "state": "STARTED", + "primary": true, + "node": "zDC_RorJQCao9xf9pg3Fvw" + }, + "num_committed_segments": 0, + "num_search_segments": 1, + "segments": { + "_0": { + "generation": 0, + "num_docs": 1, + "deleted_docs": 0, + "size_in_bytes": 3800, + "memory_in_bytes": 1410, + "committed": false, + "search": true, + "version": "7.0.0", + "compound": true, + "attributes": { + } + } + } + } + ] + } + } + } +} +``` + +## 响应体字段 + +参数 | 数据类型 | 描述 + :--- | :--- | :--- +`segment` | String | 用于在分片目录中创建内部文件名的段名称。 +`generation` | Integer | 生成编号,例如 `0`,为每个写入的段递增,并用于命名段。 +`num_docs` | Integer | 从 Lucene 获取的文档数量。嵌套文档与其父文档分开计数。已删除的文档以及尚未分配给段的最近索引的文档被排除在外。 +`deleted_docs` | Integer | 从 Lucene 获取的已删除文档数量,可能与执行的实际删除操作数量不匹配。尚未分配给段的最近删除的文档被排除在外。已删除的文档会在适当时自动合并。OpenSearch 偶尔会删除额外的文档以跟踪最近的分片操作。 +`size_in_bytes` | Integer | 段使用的磁盘空间量,例如 `50kb`。 +`memory_in_bytes` | Integer | 保存在内存中以促进高效搜索操作的段数据量(以字节为单位),例如 `1264`。值 `-1` 表示 OpenSearch 无法计算此数字。 +`committed` | Boolean | 当为 `true` 时,段已同步到磁盘。同步到磁盘的段可以在硬重启后存活。如果为 `false`,则未提交的段数据也存储在事务日志中,以便在下次启动时可以重放更改。 +`search` | Boolean | 当为 `true` 时,段搜索已启用。当为 `false` 时,段可能已写入磁盘,需要刷新才能可搜索。 +`version` | String | 用于写入段的 Lucene 版本。 +`compound` | Boolean | 当为 `true` 时,表示 Lucene 将所有段文件合并为一个文件,以节省文件描述符。 +`attributes` | Object | 显示是否启用了高压缩。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:monitor/segments`。 diff --git a/i18n/zh/api-reference/index-apis/shard-allocation.md b/i18n/zh/api-reference/index-apis/shard-allocation.md new file mode 100644 index 00000000..c3beb4d9 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/shard-allocation.md @@ -0,0 +1,117 @@ +--- +title: 分片分配 +--- + +# 分片分配过滤 +<Badge type="tip" text="引入版本 1.0" /> + +分片分配过滤允许您通过匹配节点属性来约束索引分片的放置位置。您可以使用它将分片固定到某些节点、避开节点或要求特定的硬件或区域。分片仅分配给满足所有活动过滤器的节点,包括索引级分片分配过滤和[集群级路由感知](/api-reference/cluster-api/cluster-awareness)。 + +## 端点 + +```json +PUT /{index}/_settings +GET /{index}/_settings +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`index` | String | 要更新或读取设置的一个或多个逗号分隔的索引。使用 `_all` 或 `*` 定位所有索引。 | + +## 内置和自定义属性 + +您可以过滤内置属性或您定义的任何自定义节点属性。例如,可以通过在 `opensearch.yml` 中添加 `node.attr.zone: zone-a` 来定义自定义属性。支持以下内置属性。 + +属性 | 描述 +:--- | :--- +`_name` | 按节点名称匹配。 +`_host_ip` | 按主机 IP 地址匹配。 +`_publish_ip` | 按发布 IP 地址匹配。 +`_ip` | 匹配 `_host_ip` 或 `_publish_ip`。 +`_host` | 按主机名匹配。 +`_id` | 按节点 ID 匹配。 +`_tier` | 按数据层角色匹配节点。 + +## 过滤器类型 + +使用以下索引设置。 + +设置 | 效果 +:--- | :--- +`index.routing.allocation.include.<attr>` | 将分片分配给匹配**任何**提供的值的节点。 +`index.routing.allocation.exclude.<attr>` | **不**将分片分配给匹配**任何**提供的值的节点。 +`index.routing.allocation.require.<attr>` | **仅**将分片分配给匹配**所有**提供的值的节点。 + +## 示例请求 + +以下示例展示了使用分片分配过滤器的不同方式。 + +### 仅将索引分配给特定区域 + +使用以下命令将索引分配给 `zone-a` 中的节点: + +```json +PUT /test-index/_settings +{ + "index.routing.allocation.require.zone": "zone-a" +} +``` + +### 按 IP 分配给节点子集 + +```json +PUT /test-index/_settings +{ + "index.routing.allocation.include._ip": "10.0.0.12,10.0.0.13" +} +``` + +### 从节点中排除索引 + +以下命令从节点 `data-node-3` 中排除索引: + +```json +PUT /test-index/_settings +{ + "index.routing.allocation.exclude._name": "data-node-3" +} +``` + +### 组合过滤器 + +以下命令配置所需的机架但排除节点 `data-node-7`: + +```json +PUT /test-index/_settings +{ + "index": { + "routing.allocation.require.rack": "r1", + "routing.allocation.exclude._name": "data-node-7" + } +} +``` + +### 清除过滤器 + +要清除过滤器,将其值设置为 `null` 或空字符串 `""`: + +```json +PUT /test-index/settings +{ + "persistent": { + "index.routing.allocation.exclude._host_ip": null + } +} +``` + +## 示例响应 + +```json +{ + "acknowledged": true +} +``` diff --git a/i18n/zh/api-reference/index-apis/shard-stores.md b/i18n/zh/api-reference/index-apis/shard-stores.md new file mode 100644 index 00000000..c54a9d97 --- /dev/null +++ b/i18n/zh/api-reference/index-apis/shard-stores.md @@ -0,0 +1,149 @@ +--- +title: 索引分片存储 +--- + +# 索引分片存储 API +<Badge type="tip" text="引入版本 1.0" /> + +`_shard_stores` API 提供有关一个或多个索引的分片副本的信息。此 API 通过指示分片未分配的原因并提供其当前状态来帮助诊断未分配分片的问题。 + +## 端点 +```json +GET /_shard_stores +GET /{index}/_shard_stores +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index` | List 或 String | 用于限制请求的数据流、索引和别名列表。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| `allow_no_indices` | Boolean | 如果为 `false`,则当任何通配符表达式、索引别名或 `_all` 值仅针对缺失或关闭的索引时,请求返回错误。即使请求针对其他打开的索引,此行为也适用。 | `false` | +| `expand_wildcards` | List 或 String | 通配符模式可以匹配的索引类型。如果请求可以针对数据流,则此参数确定通配符表达式是否匹配隐藏的数据流。<br> 有效值为:<br> - `all`:匹配任何索引,包括隐藏的索引。<br> - `closed`:匹配关闭的非隐藏索引。<br> - `hidden`:匹配隐藏索引。必须与 open、closed 或两者结合使用。<br> - `none`:不接受通配符表达式。<br> - `open`:匹配打开的非隐藏索引。 | `open` | +| `ignore_unavailable` | Boolean | 如果为 `true`,则响应中不包括缺失或关闭的索引。 | `false` | +| `status` | List 或 String | 用于限制请求的分片健康状态列表。<br> 有效值为:<br> - `all`:返回所有分片,无论健康状态如何。<br> - `green`:主分片和所有副本分片均已分配。<br> - `red`:主分片未分配。<br> - `yellow`:一个或多个副本分片未分配。 | `yellow,red` | + +## 示例请求 + +在单节点集群上创建具有多个主分片的索引: + +```json +PUT /logs-shardstore +{ + "settings": { + "number_of_shards": 2, + "number_of_replicas": 0 + }, + "mappings": { + "properties": { + "timestamp": { "type": "date" }, + "message": { "type": "text" } + } + } +} +``` + +索引一个文档: + +<!-- spec_insert_start +component: example_code +rest: POST /logs-shardstore/_doc +body: | +{ + "timestamp": "2025-06-20T12:00:00Z", + "message": "Log message 1" +} +--> + +POST /logs-shardstore/_doc +{ + "timestamp": "2025-06-20T12:00:00Z", + "message": "Log message 1" +} + +response = client.index( + index = "logs-shardstore", + body = { + "timestamp": "2025-06-20T12:00:00Z", + "message": "Log message 1" + } +) + +<!-- spec_insert_end --> + +获取 `logs-shardstore` 索引的分片存储状态: + +<!-- spec_insert_start +component: example_code +rest: GET /logs-shardstore/_shard_stores?status=all +--> + +GET /logs-shardstore/_shard_stores?status=all + +response = client.indices.shard_stores( + index = "logs-shardstore", + params = { "status": "all" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +响应列出了分配给每个分片的存储。如果分片没有分配的存储,则标记为 `unassigned`: + +```json +{ + "indices": { + "logs-shardstore": { + "shards": { + "0": { + "stores": [ + { + "UFyVYVMCSDOObiRwPxSW5w": { + "name": "opensearch-node1", + "ephemeral_id": "vkSB_-M7QVyFXvgda6oRZg", + "transport_address": "172.19.0.2:9300", + "attributes": { + "shard_indexing_pressure_enabled": "true" + } + }, + "allocation_id": "PEM5YjEWSz-jJEj-Not6Aw", + "allocation": "primary" + } + ] + }, + "1": { + "stores": [] + } + } + } + } +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述| +| `indices` | Object | 包含每个索引的分片存储信息。 | +| `indices.<index>.shards` | Object | 包含索引中每个分片的存储数据。 | +| `shards.<shard_id>.stores` | Array | 分片的存储条目列表。| +| `stores[n].<node_id>` | Object | 节点元数据,包括名称、传输地址和属性。 | +| `stores[n].allocation` | String | 此节点上的分片角色(`primary` 或 `replica`)。 | +| `stores[n].allocation_id` | String | 此分片副本的唯一分配 ID。| +| `stores[n].store_exception` | Object(可选) | 读取分片存储时遇到的存储异常。 | +| `stores[n].store_exception.type` | String | 异常类型。| +| `stores[n].store_exception.reason` | String | 异常的原因消息。| + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:monitor/shard_stores`。 diff --git a/i18n/zh/api-reference/index-apis/simulate-index-template.md b/i18n/zh/api-reference/index-apis/simulate-index-template.md new file mode 100644 index 00000000..f5f0046a --- /dev/null +++ b/i18n/zh/api-reference/index-apis/simulate-index-template.md @@ -0,0 +1,253 @@ +--- +title: 模拟索引模板 +--- + +# 模拟索引模板 API +<Badge type="tip" text="引入版本 1.0" /> + +您可以使用模拟索引模板 API 来预览索引模板将如何应用于索引,或在创建索引模板之前模拟它。 + +## 端点 + +```json +POST /_index_template/_simulate +POST /_index_template/_simulate/{template_name} +POST /_index_template/_simulate_index/{index_name} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `template_name` | String | 要模拟的索引模板的名称。 | +| `index_name` | String | 用于模拟模板解析的索引名称。 | + +## 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index_patterns` | Array | 模板应用的索引模式。 | +| `template` | Object | 模板定义。 | +| `template.settings` | Object | 要应用的索引设置。 | +| `template.mappings` | Object | 要应用的字段映射。 | +| `template.aliases` | Object | 要应用的别名。 | +| `priority` | Integer | 模板的优先级值,用于确定当多个模板匹配索引时应用哪个模板。较高的值优先。 | +| `version` | Integer | 模板版本。 | +| `_meta` | Object | 模板的元数据。 | + +### 示例请求:模拟模板 + +使用以下请求在不创建模板的情况下模拟它: + +<!-- spec_insert_start +component: example_code +rest: POST /_index_template/_simulate_index/logs-sim-1 +--> + +POST /_index_template/_simulate_index/logs-sim-1 + +response = client.indices.simulate_index_template( + name = "logs-sim-1" +) + +<!-- spec_insert_end --> + +### 示例请求:模拟命名模板 +<!-- spec_insert_start +component: example_code +rest: POST /_index_template/_simulate/template_for_simulation +--> + +POST /_index_template/_simulate/template_for_simulation + +response = client.indices.simulate_template( + name = "template_for_simulation" +) + +<!-- spec_insert_end --> +您可以通过指定模板名称来模拟特定模板。 + +首先,使用以下请求创建一个名为 `template_for_simulation` 的模板: + +<!-- spec_insert_start +component: example_code +rest: PUT /_index_template/template_for_simulation +body: | +{ + "index_patterns": ["logs-sim-*"], + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + }, + "message": { + "type": "text" + }, + "level": { + "type": "keyword" + } + } + } + }, + "priority": 10, + "version": 1, + "_meta": { + "description": "Template used for simulation example", + "owner": "Docs Team" + } +} +--> + +PUT /_index_template/template_for_simulation +{ + "index_patterns": [ + "logs-sim-*" + ], + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + }, + "message": { + "type": "text" + }, + "level": { + "type": "keyword" + } + } + } + }, + "priority": 10, + "version": 1, + "_meta": { + "description": "Template used for simulation example", + "owner": "Docs Team" + } +} + +response = client.indices.put_index_template( + name = "template_for_simulation", + body = { + "index_patterns": [ + "logs-sim-*" + ], + "template": { + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + }, + "message": { + "type": "text" + }, + "level": { + "type": "keyword" + } + } + } + }, + "priority": 10, + "version": 1, + "_meta": { + "description": "Template used for simulation example", + "owner": "Docs Team" + } + } +) + +<!-- spec_insert_end --> + +现在您可以模拟名为 `template_for_simulation` 的模板: + +<!-- spec_insert_start +component: example_code +rest: POST /_index_template/_simulate/template_for_simulation +--> + +POST /_index_template/_simulate/template_for_simulation + +response = client.indices.simulate_template( + name = "template_for_simulation" +) + +<!-- spec_insert_end --> + +### 示例请求:在特定索引上模拟模板 + +在特定索引名称上模拟模板对于解决冲突或调试模板之间的优先级问题特别有用。 +以下请求演示了如何将所有适用的模板(具有重叠的索引模式)应用于名为 `logs-sim-1` 的索引: + +<!-- spec_insert_start +component: example_code +rest: POST /_index_template/_simulate_index/logs-sim-1 +--> + +POST /_index_template/_simulate_index/logs-sim-1 + +response = client.indices.simulate_index_template( + name = "logs-sim-1" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "template": { + "settings": { + "index": { + "number_of_shards": "1", + "number_of_replicas": "1" + } + }, + "mappings": { + "properties": { + "level": { + "type": "keyword" + }, + "message": { + "type": "text" + }, + "timestamp": { + "type": "date" + } + } + }, + "aliases": {} + }, + "overlapping": [] +} +``` + +## 响应体字段 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `template` | Object | 应用的模板。 | +| `template.settings` | Object | 解析的索引设置。 | +| `template.mappings` | Object | 解析的字段映射。 | +| `template.aliases` | Object | 解析的别名。 | +| `overlapping` | Array | 匹配相同索引模式但未应用的其他索引模板列表。 | + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/index_template/simulate`。 diff --git a/i18n/zh/api-reference/index-apis/template-exists-legacy.md b/i18n/zh/api-reference/index-apis/template-exists-legacy.md new file mode 100644 index 00000000..12f3559f --- /dev/null +++ b/i18n/zh/api-reference/index-apis/template-exists-legacy.md @@ -0,0 +1,55 @@ +--- +title: 模板存在(已弃用) +--- + +# 模板存在 +<Badge type="tip" text="引入版本 1.0" /> + +::: danger WARNING +模板存在 API 已被弃用。请使用新的[索引模板存在](/api-reference/index-apis/index-template-exists) API。 +::: + +模板存在 API 操作用于验证使用旧版 `/_template` 端点创建的一个或多个索引模板是否存在。 + +## 端点 + +```json +HEAD /_template/{template-name} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有参数都是必需的。 + +| 参数 | 类型 | 描述 | +| :-------------- | :----- | :------------------------------------------------------------------------------- | +| `template-name` | String | 要检查的索引模板的名称。接受通配符表达式。 | + +## 查询参数 + +下表列出了可用的查询参数。所有参数都是可选的。 + +| 参数 | 类型 | 描述 | +| :------------------------- | :------ | :--------------------------------------------------------------------------------------------------- | +| `flat_settings` | Boolean | 如果为 `true`,则以扁平格式返回设置。默认值为 `false`。 | +| `local` | Boolean | 如果为 `true`,则请求不从集群管理节点检索状态。默认值为 `false`。 | +| `cluster_manager_timeout` | Time | 指定等待与集群管理节点连接的时间。默认值为 `30s`。 | + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: HEAD /_template/logging_template +--> + +HEAD /_template/logging_template + +response = client.indices.exists_template( + name = "logging_template" +) + +<!-- spec_insert_end --> + +## 示例响应 + +如果模板存在,则返回 `200 OK` 状态且没有响应体。如果模板不存在,则返回 `404 Not Found`。 diff --git a/i18n/zh/api-reference/index-name-syntax.md b/i18n/zh/api-reference/index-name-syntax.md new file mode 100644 index 00000000..f874264d --- /dev/null +++ b/i18n/zh/api-reference/index-name-syntax.md @@ -0,0 +1,120 @@ +--- +title: 索引名称语法 +--- + +# 索引名称语法 + +许多 OpenSearch REST API 在请求路径中接受一个或多个索引名称。您可以在一个请求中定位多个索引,使用日期数学按日期选择索引,并防止请求在请求体中指定索引。 + +## 定位多个索引 + +大多数在路径中接受索引名称的 API 可以一次在多个索引上运行。通过以下方式之一指定目标索引: + +- 逗号分隔的名称列表,例如 `app-logs-2026.10.12,app-logs-2026.10.13`。 +- 通配符模式,例如 `app-logs-*` 或 `*-logs-*`。 +- `_all` 或 `*` 以定位所有索引。 +- 排除,从前面的模式中删除索引。在名称或模式前加上 `-`,例如 `app-logs-*,-app-logs-2026.10.11`。排除必须跟在至少一个包含的名称或模式之后。仅包含 `-app-logs-2026.10.11` 的路径被解释为字面索引名称 `-app-logs-2026.10.11`。 + +以下请求计算 2026 年创建的所有 `app-logs-` 索引中的文档,但 `app-logs-2026.10.11` 除外: + +```json +GET /app-logs-2026*,-app-logs-2026.10.11/_count +``` + +在单个文档或单个索引上操作的 API,例如[索引文档 API](/api-reference/document-apis/index-document),不接受多个索引。这些 API 路径中的逗号分隔列表被拒绝为无效的索引名称。 + +支持多个索引的 API 接受以下查询参数,这些参数控制 OpenSearch 如何解析目标索引。默认值取决于 API。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`ignore_unavailable` | Boolean | 如果为 `true`,OpenSearch 忽略按名称列出的缺失或关闭的索引。如果为 `false`,命名缺失或关闭索引的请求将失败。 +`allow_no_indices` | Boolean | 如果为 `true`,当通配符模式、别名或 `_all` 不匹配任何索引时,请求成功。如果为 `false`,请求失败。例如,使用默认的 `true`,对 `nomatch-*` 的计数 API 请求返回计数 `0`。 +`expand_wildcards` | String | 通配符模式可以匹配的索引类型。接受以下值的逗号分隔列表:<br> - `open`:打开的索引。<br> - `closed`:关闭的索引。<br> - `hidden`:隐藏的索引,它们启用了 [`index.hidden`](/install-and-configure/configuring-opensearch/index-settings) 设置。必须与 `open`、`closed` 或两者结合使用。<br> - `all`:所有索引,包括隐藏索引。<br> - `none`:没有索引。通配符模式不会展开。<br><br>对于大多数 API,默认值为 `open`,因此通配符模式不匹配隐藏索引,例如名称以 `.` 开头的索引。指定 `expand_wildcards=open,hidden` 以包含它们。 + +## 索引名称中的日期数学 + +如果您为时间序列数据每天或每月创建一个索引,则可以在请求路径中使用日期数学按日期选择索引。例如,请求可以仅定位本月和上月的销售索引,而无需客户端计算它们的名称,OpenSearch 只读取这些索引。大多数在路径中接受索引名称的 API 都支持日期数学。例如,您可以使用日期数学来命名滚动创建的索引。有关更多信息,请参阅[在索引滚动中使用日期数学](/api-reference/index-apis/rollover#using-date-math-with-index-rollovers)。 + +日期数学索引名称具有以下格式: + +``` +<static_name{date_math_expression{date_format|time_zone}}> +``` + +下表描述了日期数学索引名称的组成部分。 + +组成部分 | 描述 +:--- | :--- +`static_name` | 名称的固定部分,例如 `app-logs-`。 +`date_math_expression` | 相对于 `now` 计算日期的表达式,例如 `now/d`(今天向下舍入到一天的开始)或 `now/d-1d`(昨天)。有关表达式语法,请参阅[日期数学](/mappings/supported-field-types/date/#date-math)。 +`date_format` | 可选。计算的日期写入索引名称的格式。默认为 `yyyy.MM.dd`。格式模式区分大小写:`MM` 是月份,`mm` 是分钟,而 `HH` 是 24 小时制的小时,`hh` 是 12 小时制的小时。有关更多信息,请参阅[自定义格式](/mappings/supported-field-types/date/#custom-formats)。 +`time_zone` | 可选。用于计算日期的时区,作为偏移量,例如 `+12:00`,或 ID,例如 `America/Los_Angeles`。默认为 UTC。 + +整个表达式必须用尖括号括起来。要在名称的静态部分使用 `{` 或 `}`,请使用反斜杠(`\`)转义字符。 + +如果当前时间是 2026 年 10 月 13 日 UTC 时间 18:00,下表显示表达式如何解析。 + +表达式 | 解析为 +:--- | :--- +`<app-logs-{now/d}>` | `app-logs-2026.10.13` +`<app-logs-{now/d-1d}>` | `app-logs-2026.10.12` +`<app-logs-{now/w}>` | `app-logs-2026.10.12`(周从星期一开始) +`<app-logs-{now-1h/h{yyyy.MM.dd.HH}}>` | `app-logs-2026.10.13.17` +`<app-logs-{now/d{yyyy.MM.dd\|Asia/Tokyo}}>` | `app-logs-2026.10.14` +`<sales-{now/M{yyyy-MM}}>` | `sales-2026-10` +`<app\{prod\}-{now/M}>` | `app{prod}-2026.10.01` + +OpenSearch 使用公历解析日期数学,不管语言环境如何。 + +在请求 URL 中,您必须对日期数学表达式中的特殊字符进行百分比编码。OpenSearch 拒绝包含这些字符而不编码的 URL。下表列出了每个字符的编码值。 + +字符 | 编码值 +:--- | :--- +`<` | `%3C` +`>` | `%3E` +`/` | `%2F` +`{` | `%7B` +`}` | `%7D` +`\|` | `%7C` +`+` | `%2B` +`:` | `%3A` +`,` | `%2C` + +以下请求计算当前月和上个月的月度 `sales-` 索引中 `west` 地区的总销售额。在编码之前,路径的索引部分是 `<sales-{now/M-1M{yyyy-MM}}>,<sales-{now/M{yyyy-MM}}>`: + +```json +GET /%3Csales-%7Bnow%2FM-1M%7Byyyy-MM%7D%7D%3E%2C%3Csales-%7Bnow%2FM%7Byyyy-MM%7D%7D%3E/_search +{ + "size": 0, + "query": { + "term": { + "region": "west" + } + }, + "aggs": { + "total_sales": { + "sum": { + "field": "amount" + } + } + } +} +``` + +## 限制请求体中的索引 + +批量、多获取和多搜索 API 允许请求体中的每个项目指定自己的目标索引,覆盖请求路径中的索引。如果您根据请求 URL 控制对索引的访问,例如使用代理,则用户可以通过在请求体中命名不同的索引来绕过该控制。 + +为了防止这种情况,请在每个节点的 `opensearch.yml` 中将 `rest.action.multi.allow_explicit_index` 设置为 `false`。这是一个静态设置,因此您必须重新启动节点才能使其生效。默认为 `true`。当设置为 `false` 时,这些 API 拒绝任何其正文指定索引的请求,即使它与路径中的索引匹配。在请求路径中指定目标索引: + +```json +POST /orders/_bulk +{ "index": {} } +{ "product": "Trail running shoes" } +``` + +## 相关文档 + +- [常用 REST 参数](/api-reference/common-parameters) +- [支持的单位](/api-reference/units) +- [Cron 表达式](/api-reference/cron-expressions) diff --git a/i18n/zh/api-reference/list/index.md b/i18n/zh/api-reference/list/index.md new file mode 100644 index 00000000..750f5698 --- /dev/null +++ b/i18n/zh/api-reference/list/index.md @@ -0,0 +1,239 @@ +--- +title: List API +--- + +# List API +<Badge type="tip" text="2.18 版本引入" /> + +List API 以分页格式检索有关索引和分片的统计信息。这简化了处理包含许多索引的响应的任务。 + +List API 支持两种操作: + +- [列出索引](/api-reference/list/list-indices) +- [列出分片](/api-reference/list/list-shards) + +## 共享查询参数 + +所有 List API 操作都支持以下可选查询参数。 + +参数 | 描述 +:--- | :--- | +`v` | 通过向列添加标题来提供详细输出。 +`help` | 列出给定操作的默认和其他可用标题。 +`h` | 将输出限制为特定标题。 +`format` | 返回结果的格式。有效值为 `json`、`yaml`、`cbor` 和 `smile`。 +`s` | 按指定列对输出进行排序。 +`next_token` | 用于获取下一页结果的令牌。每个分页响应都以 `next_token` 值结束。在下一个请求中传递此值以检索下一页。当 `next_token` 为 `null` 时,表示所有结果都已返回。 +`size` | 单页返回的最大条目数。 +`sort` | 基于索引创建时间返回条目的顺序。有效值为 `asc`(最旧的优先)和 `desc`(最近创建的优先)。默认为 `asc`。 + +`size` 的默认值和允许值因操作而异。有关更多信息,请参阅[列出索引](/api-reference/list/list-indices)和[列出分片](/api-reference/list/list-shards)。 + +## 示例 + +以下示例展示如何使用可选查询参数来自定义所有 List API 响应。 + +### 获取详细输出 + +要查询索引及其统计信息并获得包含响应中所有列标题的详细输出,请使用 `v` 查询参数,如以下示例所示。 + +#### 请求 + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices?v +--> + +GET /_list/indices?v + +response = client.list.indices( + params = { "v": "true" } +) + +<!-- spec_insert_end --> + +#### 响应 + +```json +health status index uuid pri rep docs.count docs.deleted store.size pri.store.size +green open sample-index-1 L4tj1plyQLCjGegvdEI16A 1 0 3 0 4.7kb 4.7kb +yellow open sample-index-2 n9sq3RtJR2mMmTqJF2Xh6w 1 1 5 0 4.8kb 4.8kb +next_token null +``` + +### 获取所有可用标题 + +要查看所有可用标题,请使用 `help` 参数,语法如下: + +```json +GET _list/{operation_name}?help +``` + +#### 请求 + +以下示例列出索引操作返回所有可用标题: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices?help +--> + +GET /_list/indices?help + +response = client.list.indices( + params = { "help": "true" } +) + +<!-- spec_insert_end --> + +#### 响应 + +响应列出每个可用标题,后跟其别名和描述。以下示例响应已截断: + +```json +health | h | current health status +status | s | open/close status +index | i,idx | index name +uuid | id,uuid | index uuid +pri | p,shards.primary,shardsPrimary | number of primary shards +rep | r,shards.replica,shardsReplica | number of replica shards +docs.count | dc,docsCount | available docs +docs.deleted | dd,docsDeleted | deleted docs +creation.date | cd | index creation date (millisecond value) +creation.date.string | cds | index creation date (as string) +store.size | ss,storeSize | store size of primaries & replicas +pri.store.size | | store size of primaries +``` + +### 获取标题子集 + +要将输出限制为标题子集,请使用 `h` 参数,语法如下: + +```json +GET _list/{operation_name}?h={header_name_1},{header_name_2}&v +``` + +对于任何操作,您可以使用 `help` 参数确定哪些标题可用,然后使用 `h` 参数将输出限制为仅标题子集。 + +#### 请求 + +以下示例将响应中的索引限制为仅索引名称和健康状态标题: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices?h=health,index +--> + +GET /_list/indices?h=health,index + +response = client.list.indices( + params = { "h": "health,index" } +) + +<!-- spec_insert_end --> + +#### 响应 + +```json +green sample-index-1 +yellow sample-index-2 +next_token null +``` + +### 按标题排序 + +要在单个页面上按标题对输出进行排序,请使用 `s` 参数,语法如下: + +```json +GET _list/{operation_name}?s={header_name_1},{header_name_2} +``` + +#### 请求 + +以下示例请求先按健康状态然后按索引名称对索引进行排序,并将输出限制为健康状态和索引名称标题: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices?s=h,i&h=health,index +--> + +GET /_list/indices?s=h,i&h=health,index + +response = client.list.indices( + params = { "s": "h,i", "h": "health,index" } +) + +<!-- spec_insert_end --> + +#### 响应 + +```json +green sample-index-1 +yellow sample-index-2 +next_token null +``` + +### 以 JSON 格式检索数据 + +默认情况下,List API 以 `text/plain` 格式返回数据。其他支持的格式有 [YAML](https://yaml.org/)、[CBOR](https://cbor.io/) 和 [Smile](https://github.com/FasterXML/smile-format-specification)。 + +要以 JSON 格式检索数据,请使用 `format=json` 参数,语法如下: + +```json +GET _list/{operation_name}?format=json +``` + +::: info NOTE +如果您使用 Security 插件,请确保您具有适当的权限。 +::: + +#### 请求 + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices?format=json +--> + +GET /_list/indices?format=json + +response = client.list.indices( + params = { "format": "json" } +) + +<!-- spec_insert_end --> + +#### 响应 + +响应包含 JSON 格式的数据: + +```json +{ + "next_token": null, + "indices": [ + { + "health": "green", + "status": "open", + "index": "sample-index-1", + "uuid": "L4tj1plyQLCjGegvdEI16A", + "pri": "1", + "rep": "0", + "docs.count": "3", + "docs.deleted": "0", + "store.size": "4.7kb", + "pri.store.size": "4.7kb" + }, + { + "health": "yellow", + "status": "open", + "index": "sample-index-2", + "uuid": "n9sq3RtJR2mMmTqJF2Xh6w", + "pri": "1", + "rep": "1", + "docs.count": "5", + "docs.deleted": "0", + "store.size": "4.8kb", + "pri.store.size": "4.8kb" + } + ] +} +``` diff --git a/i18n/zh/api-reference/list/list-indices.md b/i18n/zh/api-reference/list/list-indices.md new file mode 100644 index 00000000..d2ded289 --- /dev/null +++ b/i18n/zh/api-reference/list/list-indices.md @@ -0,0 +1,116 @@ +--- +title: List indices +--- + +# List Indices API +<Badge type="tip" text="2.18 版本引入" /> + +列出索引操作以分页格式提供以下索引信息: + +- 索引使用的磁盘空间量。 +- 索引中包含的分片数。 +- 索引的健康状态。 + +## 端点 + +```json +GET _list/indices +GET _list/indices/{index} +``` + +## 查询参数 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`bytes` | 字节大小 | 指定字节大小的单位,例如 `7kb` 或 `6gb`。有关更多信息,请参阅[支持的单位](/api-reference/units)。 +`health` | 字符串 | 根据健康状态限制索引。支持的值为 `green`、`yellow` 和 `red`。 +`include_unloaded_segments` | 布尔值 | 是否包含未加载到内存中的段的信息。默认为 `false`。 +`cluster_manager_timeout` | 时间 | 等待连接到集群管理器节点的时间量。默认为 `30s`。 +`pri` | 布尔值 | 是否仅返回主分片的信息。默认为 `false`。 +`time` | 时间 | 指定时间单位,例如 `5d` 或 `7h`。有关更多信息,请参阅[支持的单位](/api-reference/units)。 +`expand_wildcards` | 枚举 | 将通配符表达式扩展为具体索引。使用逗号组合多个值。支持的值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认为 `open`。 +`next_token` | 字符串 | 获取下一页索引。当为 `null` 时,仅提供第一页索引。默认为 `null`。 +`size` | 整数 | 单个页面上显示的最大索引数。响应单页上的索引数不总是等于指定的 `size`。默认为 `500`。最小为 `1`,最大为 `5000`。 +`sort` | 字符串 | 显示索引的顺序,基于索引创建时间。如果为 `desc`,则首先显示最近创建的索引。如果为 `asc`,则首先显示最旧的索引。默认为 `asc`。 + +::: tip TIP +使用 `next_token` 查询参数时,使用响应生成的令牌来查看下一页索引。在 API 返回 `null` 后,API 中包含的所有索引都已返回。 +::: + +## 示例请求 + +要获取所有索引的信息,请发送以下请求: + +```json +GET /_list/indices?v +``` + +要获取下一页索引,请传递上一个响应中的 `next_token` 值。重复此请求,直到响应返回 `null` 的 `next_token`: + +```json +GET /_list/indices?v&next_token=<next_token> +``` + +要将信息限制为特定索引,请在查询后添加索引名称,如以下示例所示: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices/<index>?v +--> + +GET /_list/indices/<index>?v + +response = client.list.indices( + index = "<index>", + params = { "v": "true" } +) + +<!-- spec_insert_end --> + +要获取多个索引的信息,请用逗号分隔索引,如以下示例所示: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/indices/index1,index2,index3?v +--> + +GET /_list/indices/index1,index2,index3?v + +response = client.list.indices( + index = "index1,index2,index3", + params = { "v": "true" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +**纯文本格式** + +```json +health | status | index | uuid | pri | rep | docs.count | docs.deleted | store.size | pri.store.size +green | open | movies | UZbpfERBQ1-3GSH2bnM3sg | 1 | 1 | 1 | 0 | 7.7kb | 3.8kb +next_token MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw== +``` + +**JSON 格式** + +```json +{ + "next_token": "MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw==", + "indices": [ + { + "health": "green", + "status": "open", + "index": "movies", + "uuid": "UZbpfERBQ1-3GSH2bnM3sg", + "pri": "1", + "rep": "1", + "docs.count": "1", + "docs.deleted": "0", + "store.size": "7.7kb", + "pri.store.size": "3.8kb" + } + ] +} +``` diff --git a/i18n/zh/api-reference/list/list-shards.md b/i18n/zh/api-reference/list/list-shards.md new file mode 100644 index 00000000..0b2a4f08 --- /dev/null +++ b/i18n/zh/api-reference/list/list-shards.md @@ -0,0 +1,123 @@ +--- +title: List shards +--- + +# List Shards API +<Badge type="tip" text="2.18 版本引入" /> + +列出分片操作以分页格式输出所有主分片和副本分片的状态及其分布方式。 + +## 端点 + +```json +GET _list/shards +GET _list/shards/{index} +``` + +## 查询参数 + +所有参数都是可选的。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`bytes` | 字节大小 | 指定字节大小单位,例如 `7kb` 或 `6gb`。有关更多信息,请参阅[支持的单位](/api-reference/units)。 +`local` | 布尔值 | 是否仅从本地节点返回信息,而不是从集群管理器节点返回。默认为 `false`。 +`cluster_manager_timeout` | 时间 | 等待连接到集群管理器节点的时间量。默认为 `30s`。 +`cancel_after_time_interval` | 时间 | 分片请求取消后的时间量。默认为 `-1`(无超时)。 +`time` | 时间 | 指定时间单位,例如 `5d` 或 `7h`。有关更多信息,请参阅[支持的单位](/api-reference/units)。 +`next_token` | 字符串 | 获取下一页索引。当为 `null` 时,仅提供第一页索引。默认为 `null`。 +`size` | 整数 | 单个页面上显示的最大索引数。响应单页上的索引数不总是等于指定的 `size`。默认和最小值为 `2000`。最大值为 `20000`。 +`sort` | 字符串 | 显示索引的顺序。如果为 `desc`,则首先显示最近创建的索引。如果为 `asc`,则首先显示最旧的索引。默认为 `asc`。 + +::: tip TIP +使用 `next_token` 查询参数时,使用响应生成的令牌来查看下一页索引。在 API 返回 `null` 后,API 中包含的所有索引都已返回。 +::: + +## 示例请求 + +要获取所有索引和分片的信息,请发送以下请求: + +```json +GET /_list/shards?v +``` + +要获取下一页分片,请传递上一个响应中的 `next_token` 值。重复此请求,直到响应返回 `null` 的 `next_token`: + +```json +GET /_list/shards?v&next_token=<next_token> +``` + +要将信息限制为特定索引,请在查询后添加索引名称,如以下示例所示: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/shards/<index>?v +--> + +GET /_list/shards/<index>?v + +response = client.list.shards( + index = "<index>", + params = { "v": "true" } +) + +<!-- spec_insert_end --> + +如果您想要获取多个索引的信息,请用逗号分隔索引,如以下示例所示: + +<!-- spec_insert_start +component: example_code +rest: GET /_list/shards/index1,index2,index3?v +--> + +GET /_list/shards/index1,index2,index3?v + +response = client.list.shards( + index = "index1,index2,index3", + params = { "v": "true" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +**纯文本格式** + +```json +index | shard | prirep | state | docs | store | ip | | node +plugins | 0 | p | STARTED | 0 | 208b | 172.18.0.4 | odfe-node1 +plugins | 0 | r | STARTED | 0 | 208b | 172.18.0.3 | odfe-node2 +.... +.... +next_token MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw== +``` + +**JSON 格式** + +```json +{ + "next_token": "MTcyOTE5NTQ5NjM5N3wub3BlbnNlYXJjaC1zYXAtbG9nLXR5cGVzLWNvbmZpZw==", + "shards": [ + { + "index": "plugins", + "shard": "0", + "prirep": "p", + "state": "STARTED", + "docs": "0", + "store": "208B", + "ip": "172.18.0.4", + "node": "odfe-node1" + }, + { + "index": "plugins", + "shard": "0", + "prirep": "r", + "state": "STARTED", + "docs": "0", + "store": "208B", + "ip": "172.18.0.3", + "node": "odfe-node2" + } + ] +} +``` diff --git a/i18n/zh/api-reference/multi-search.md b/i18n/zh/api-reference/multi-search.md index 53363db6..1a20a06a 100644 --- a/i18n/zh/api-reference/multi-search.md +++ b/i18n/zh/api-reference/multi-search.md @@ -2,15 +2,93 @@ title: 多重搜索 --- -# 多重搜索 +# 多重搜索 API <Badge type="tip" text="1.0 版本引入" /> -顾名思义,多重搜索操作允许你将多个搜索请求捆绑到单个请求中。然后 OpenSearch 并行执行搜索,因此与每次搜索发送一个请求相比,你可以更快地获得响应。OpenSearch 独立执行每个搜索,因此一个搜索的失败不会影响其他搜索。 +顾名思义,多重搜索操作允许你将多个搜索请求打包到单个请求中。然后 OpenSearch 并行执行这些搜索,因此与每次搜索发送一个请求相比,你可以更快地获得响应。OpenSearch 独立执行每个搜索,因此一个搜索的失败不会影响其他搜索。 -## 示例 +## 端点 +```json +GET /_msearch +POST /_msearch +GET /{index}/_msearch +POST /{index}/_msearch +``` + +在路径中指定索引会为元数据行中不包含 `index` 字段的任何搜索设置默认目标。如果你省略路径参数且搜索的元数据行也未指定 `index`,则搜索将针对所有索引运行。 + +## 查询参数和元数据选项 + +所有参数都是可选的。某些参数也可以作为每个元数据行的一部分按搜索应用。 + +参数 | 类型 | 描述 | 元数据行支持 +:--- | :--- | :--- | :--- +`allow_no_indices` | 布尔值 | 是否忽略不匹配任何索引的通配符。默认为 `true`。 | 是 +`cancel_after_time_interval` | 时间 | 搜索请求将被取消的时间。支持父级和子级请求级别。优先级顺序为:<br> 1. 子级参数<br> 2. 父级参数<br> 3. [集群设置](/api-reference/cluster-api/cluster-settings)。<br>默认为 -1。 | 是 +`ccs_minimize_roundtrips` | 布尔值 | OpenSearch 是否应尝试最小化协调节点和远程集群之间的网络往返次数(仅适用于跨集群搜索请求)。默认为 `true`。 | 否 +`expand_wildcards` | 枚举 | 将通配符表达式扩展为具体索引。用逗号组合多个值。支持的值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认为 `open`。 | 是 +`ignore_unavailable` | 布尔值 | 如果索引列表中的索引或分片不存在,是否忽略它而不是使查询失败。默认为 `false`。 | 是 +`include_named_queries_score` | 布尔值 | 是否返回命名查询的分数。默认为 `false`。 | 否 +`max_concurrent_searches` | 整数 | 最大并发搜索数。默认值取决于你的节点数和搜索线程池大小。较高的值可以提高性能,但有使集群过载的风险。 | 否 +`max_concurrent_shard_requests` | 整数 | 每个搜索在每个节点上执行的最大并发分片请求数。默认为 5。较高的值可以提高性能,但有使集群过载的风险。 | 否 +`pre_filter_shard_size` | 整数 | 触发预过滤往返的阈值,用于消除无法匹配查询的分片(例如,因为日期范围过滤器超出了分片的边界)。未指定时,如果请求针对超过 128 个分片、针对只读索引或按索引字段排序,则运行预过滤阶段。默认为 `128`。 | 否 +`rest_total_hits_as_int` | 字符串 | `hits.total` 属性是作为整数(`true`)还是对象(`false`)返回。默认为 `false`。 | 否 +`routing` | 字符串 | 逗号分隔的自定义路由值,用于将请求中的所有搜索路由到特定分片。要为单个搜索设置路由,请改用元数据行中的 `routing` 选项。 | 否 +`search_type` | 字符串 | 影响相关性分数。有效选项为 `query_then_fetch` 和 `dfs_query_then_fetch`。`query_then_fetch` 使用分片的词项和文档频率对文档评分(更快,准确性较低),而 `dfs_query_then_fetch` 使用所有分片的词项和文档频率(较慢,准确性较高)。默认为 `query_then_fetch`。 | 是 +`typed_keys` | 布尔值 | 是否在响应中为聚合名称添加其内部类型前缀。默认为 `false`。 | 否 + +## 仅元数据选项 + +某些选项不能作为参数应用于整个请求。相反,你可以将它们作为每个元数据行的一部分按搜索应用。所有选项都是可选的。 + +选项 | 类型 | 描述 +:--- | :--- | :--- +`index` | 字符串、字符串数组 | 如果你未在 URL 中指定一个或多个索引(或想要覆盖单个搜索的 URL 值),可以在此处包含它。示例包括 `"logs-*"` 和 `["my-store", "sample_data_ecommerce"]`。 +`preference` | 字符串 | 你希望执行搜索的节点或分片。此设置对于测试很有用,但在大多数情况下,默认行为提供最佳的搜索延迟。选项包括 `_local`、`_only_local`、`_prefer_nodes`、`_only_nodes` 和 `_shards`。后三个选项接受节点或分片列表。示例包括 `"_only_nodes:data-node1,data-node2"` 和 `"_shards:0,1`。 +`request_cache` | 布尔值 | 是否缓存结果,这可以改善重复搜索的延迟。默认使用索引的 `index.requests.cache.enable` 设置(对于新索引默认为 `true`)。 +`routing` | 字符串 | 逗号分隔的自定义路由值,例如 `"routing": "value1,value2,value3"`。与查询参数级别的 `routing`(适用于请求中的所有搜索)不同,此选项仅针对单个搜索的路由。 + +## 请求体 + +多重搜索请求体使用换行符分隔的 JSON(NDJSON)格式,在元数据行和查询行之间交替: + +``` +Metadata\n +Query\n +Metadata\n +Query\n + +``` + +- 元数据行包含选项,例如要搜索哪些索引以及搜索类型。如果不需要按搜索覆盖,元数据行可以为空(`{}`)。 +- 查询行使用[查询 DSL](/query-dsl/)。 + +与[批量](/api-reference/document-apis/bulk)操作一样,JSON 不需要压缩——空格是可以的——但它确实需要在单行上。OpenSearch 使用换行符来解析多重搜索请求,并要求请求体以换行符结尾。 + +::: info NOTE +向此端点发送请求时,请将 `Content-Type` 标头设置为 `application/x-ndjson`。 +::: + +### 查询体字段 + +每个查询行接受与[搜索 API](/api-reference/search) 请求体相同的参数。下表列出了最常用的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `query` | 对象 | 要执行的查询 DSL 表达式。请参见[查询 DSL](/query-dsl/)。 | +| `aggregations` | 对象 | 与搜索一起运行的聚合。请参见[聚合](/aggregations/)。 | +| `from` | 整数 | 返回命中的起始偏移量。默认为 `0`。 | +| `size` | 整数 | 要返回的命中数。默认为 `10`。 | +| `sort` | 数组或对象 | 用于排序结果的字段和顺序。 | +| `_source` | 布尔值、字符串或对象 | 控制每个命中的 `_source` 中包含哪些字段。 | +| `highlight` | 对象 | 匹配字段的高亮配置。 | + +## 示例:搜索多个索引 + +以下示例针对多个索引运行查询,在每个元数据行中指定目标索引: ```json -GET _msearch +GET /_msearch { "index": "opensearch_dashboards_sample_data_logs"} { "query": { "match_all": {} }, "from": 0, "size": 10} { "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} @@ -18,62 +96,90 @@ GET _msearch ``` -## 路径和 HTTP 方法 +## 示例:使用默认索引 -``` -GET _msearch -GET <indices>/_msearch -POST _msearch -POST <indices>/_msearch -``` +当你在 URL 路径中指定索引时,该索引将作为元数据行中不包含 `index` 字段的任何搜索的默认值。以下示例针对 `products` 索引运行两个查询,而无需在每个元数据行中重复索引名称: -## 请求正文 - -多重搜索请求正文遵循以下模式: - -``` -元数据\n -查询\n -元数据\n -查询\n +```json +GET /products/_msearch +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} ``` -- 元数据行包括选项,例如要搜索哪些索引和搜索类型。 -- 查询行使用[查询 DSL](/query-dsl/)。 +## 使用搜索模板 -与 [bulk](/api-reference/document-apis/bulk) 操作一样,JSON 不需要压缩——空格没问题——但它确实需要在单行上。OpenSearch 使用换行符来解析多重搜索请求,并要求请求正文以换行符结尾。 +多重搜索 API 通过 `_msearch/template` 端点支持[搜索模板](/api-reference/search-apis/search-template/)。这允许你执行参数化搜索,将查询结构与搜索时传递的值分开。 -## URL 参数和元数据选项 +### 示例:内联模板 -所有多重搜索 URL 参数都是可选的。某些参数也可以作为每个元数据行的一部分按搜索应用。 +以下请求使用内联模板在单个调用中运行两个参数化搜索: -参数 | 类型 | 描述 | 在元数据行中支持 -:--- | :--- | :--- -allow_no_indices | 布尔值 | 是否忽略不匹配任何索引的通配符。默认为 `true`。 | 是 -cancel_after_time_interval | 时间 | 搜索请求将被取消的时间。在父级和子级请求级别都支持。优先级顺序为:<br> 1. 子级参数<br> 2. 父级参数<br> 3. [集群设置](/api-reference/cluster-api/cluster-settings)。<br>默认为 -1。 | 是 -css_minimize_roundtrips | 布尔值 | OpenSearch 是否应尝试最小化协调节点和远程集群之间的网络往返次数(仅适用于跨集群搜索请求)。默认为 `true`。 | 否 -expand_wildcards | 枚举 | 将通配符表达式展开为具体索引。用逗号组合多个值。支持的值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认为 `open`。 | 是 -ignore_unavailable | 布尔值 | 如果索引列表中的索引不存在,是否忽略它而不是使查询失败。默认为 `false`。 | 是 -max_concurrent_searches | 整数 | 最大并发搜索数。默认值取决于你的节点数和搜索线程池大小。较高的值可以提高性能,但有使集群过载的风险。 | 否 -max_concurrent_shard_requests | 整数 | 每个搜索在每个节点上执行的最大并发分片请求数。默认为 5。较高的值可以提高性能,但有使集群过载的风险。 | 否 -pre_filter_shard_size | 整数 | 默认为 128。 | 否 -rest_total_hits_as_int | 字符串 | `hits.total` 属性是作为整数(`true`)还是对象(`false`)返回。默认为 `false`。 | 否 -search_type | 字符串 | 影响相关性分数。有效选项为 `query_then_fetch` 和 `dfs_query_then_fetch`。`query_then_fetch` 使用分片的词项和文档频率对文档进行评分(更快,不太准确),而 `dfs_query_then_fetch` 使用所有分片的词项和文档频率(更慢,更准确)。默认为 `query_then_fetch`。 | 是 -typed_keys | 布尔值 | 是否在响应中为聚合名称添加其内部类型前缀。默认为 `false`。 | 否 +```json +GET _msearch/template +{"index": "products"} +{"source": {"query": {"match": {"product_name": "{{search_term}}"}}}, "params": {"search_term": "wireless"}} +{"index": "products"} +{"source": {"query": {"range": {"price": {"lte": "{{max_price}}"}}}}, "params": {"max_price": "75"}} -## 仅元数据选项 +``` -某些选项不能作为 URL 参数应用于整个请求。相反,你可以将它们作为每个元数据行的一部分按搜索应用。所有选项都是可选的。 +### 示例:存储模板 -选项 | 类型 | 描述 -:--- | :--- | :--- -index | 字符串,字符串数组 | 如果你没有将索引或多个索引指定为 URL 的一部分(或想要覆盖单个搜索的 URL 值),你可以在此处包含它。示例包括 `"logs-*"` 和 `["my-store", "sample_data_ecommerce"]`。 -preference | 字符串 | 你希望执行搜索的节点或分片。此设置对于测试可能很有用,但在大多数情况下,默认行为提供最佳搜索延迟。选项包括 `_local`、`_only_local`、`_prefer_nodes`、`_only_nodes` 和 `_shards`。最后三个选项接受节点或分片列表。示例包括 `"_only_nodes:data-node1,data-node2"` 和 `"_shards:0,1`。 -request_cache | 布尔值 | 是否缓存结果,这可以提高重复搜索的延迟。默认使用索引的 `index.requests.cache.enable` 设置(对于新索引默认为 `true`)。 -routing | 字符串 | 逗号分隔的自定义路由值,例如 `"routing": "value1,value2,value3"`。 +你也可以通过 ID 引用预先注册的模板。首先,创建存储的模板: -## 响应 +```json +POST _scripts/product_search_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "multi_match": { + "query": "{{query_text}}", + "fields": ["product_name", "description"] + } + }, + "size": "{{result_count}}" + } + } +} +``` + +```json +POST _scripts/price_range_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "range": { + "price": { + "gte": "{{min_price}}", + "lte": "{{max_price}}" + } + } + }, + "size": "{{result_count}}" + } + } +} +``` + +然后在多重搜索请求中使用存储的模板: + +```json +GET _msearch/template +{"index": "products"} +{"id": "product_search_template", "params": {"query_text": "bluetooth speaker", "result_count": "5"}} +{"index": "products"} +{"id": "price_range_template", "params": {"min_price": "20", "max_price": "100", "result_count": "3"}} + +``` + +## 示例响应 OpenSearch 返回一个数组,其中包含每个搜索的结果,顺序与多重搜索请求相同。 @@ -260,3 +366,30 @@ OpenSearch 返回一个数组,其中包含每个搜索的结果,顺序与多 ] } ``` + +## 响应体字段 + +下表列出了顶级响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `took` | 整数 | OpenSearch 处理请求中所有搜索的总时间(毫秒)。 | +| `responses` | 数组 | 搜索响应对象数组,返回顺序与请求中相应搜索的顺序相同。如果特定搜索完全失败,该搜索的数组条目将包含 `error` 对象和 `status` 代码,而不是正常的搜索响应。 | + +下表列出了 `responses` 数组中每个条目内的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `took` | 整数 | OpenSearch 处理单个搜索的时间(毫秒)。 | +| `timed_out` | 布尔值 | 搜索是否在完成前超时。 | +| `_shards` | 对象 | 有关搜索涉及的分片数量的信息,包括 `total`、`successful`、`skipped` 和 `failed` 计数。 | +| `hits` | 对象 | 搜索结果,包括 `total` 命中计数、`max_score` 和匹配的 `hits` 数组。 | +| `status` | 整数 | 单个搜索结果的 HTTP 状态代码。值为 `200` 表示成功。 | + +## 部分响应 + +如果一个或多个分片在执行期间失败,多重搜索 API 仍会返回成功分片的结果。`responses` 数组中的每个单独搜索响应都包含一个 `_shards` 对象,报告有多少分片成功和多少分片失败,允许你确定结果是否完整。 + +## 所需权限 + +如果你使用安全插件,请确保你拥有适当的权限:`indices:data/read/msearch`。 diff --git a/i18n/zh/api-reference/search-apis/count.md b/i18n/zh/api-reference/search-apis/count.md new file mode 100644 index 00000000..4aa31e18 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/count.md @@ -0,0 +1,253 @@ +--- +title: Count +--- + +# Count API +<Badge type="tip" text="引入版本 1.0" /> + +Count API 返回与查询匹配的文档数量。您可以使用它来检索索引、数据流或集群的文档数量。常见的使用场景包括: + +- 在不检索实际文档的情况下检索索引或数据流中的文档总数。 +- 通过统计匹配特定条件的文档来验证数据是否已正确索引。 +- 通过跟踪不同时间段的文档数量来监控数据增长。 +- 在运行昂贵的搜索操作之前,通过首先检索匹配的文档数量来验证查询结果。 + +当您只需要文档计数时,Count API 比使用 `size: 0` 的 Search API 更高效,因为它专门针对计数操作进行了优化。为了提高性能,OpenSearch 会将计数查询并行分发到所有分片。每个分片使用其一个可用副本处理请求,允许随着副本数量的增加进行水平扩展。 + +::: info NOTE +或者,您可以使用 [CAT Indices API](/api-reference/cat/cat-indices) 或 [CAT Count API](/api-reference/cat/cat-count) 来检索每个索引或数据流中的文档数量。 +::: + +<!-- spec_insert_start +api: count +component: endpoints +--> +## 端点 +```json +GET /_count +POST /_count +GET /{index}/_count +POST /{index}/_count +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: count +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index` | 列表或字符串 | 要搜索的数据流、索引和别名的逗号分隔列表。支持通配符 (`*`)。要搜索所有数据流和索引,请省略此参数或使用 `*` 或 `_all`。 | + +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: count +component: query_parameters +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `allow_no_indices` | Boolean | 如果为 `false`,当任何通配符表达式、索引别名或 `_all` 值仅针对缺失或关闭的索引时,请求会返回错误。即使请求针对其他开放索引,此行为也适用。 | N/A | +| `analyze_wildcard` | Boolean | 如果为 `true`,则分析通配符和前缀查询。此参数只能在指定 `q` 查询字符串参数时使用。 | `false` | +| `analyzer` | String | 用于查询字符串的分析器。此参数只能在指定 `q` 查询字符串参数时使用。 | N/A | +| `default_operator` | String | 查询字符串查询的默认运算符:`AND` 或 `OR`。此参数只能在指定 `q` 查询字符串参数时使用。<br> 有效值为:`and`、`AND`、`or` 和 `OR`。 | N/A | +| `df` | String | 当查询字符串中未给出字段前缀时用作默认字段。此参数只能在指定 `q` 查询字符串参数时使用。 | N/A | +| `expand_wildcards` | 列表或字符串 | 指定通配符表达式可以匹配的索引类型。支持逗号分隔的值。<br> 有效值为:<br> - `all`:匹配任何索引,包括隐藏索引。<br> - `closed`:匹配关闭的非隐藏索引。<br> - `hidden`:匹配隐藏索引。必须与 `open`、`closed` 或两者结合使用。<br> - `none`:不接受通配符表达式。<br> - `open`:匹配开放的非隐藏索引。 | N/A | +| `ignore_throttled` | Boolean | 如果为 `true`,当冻结时忽略具体的、扩展的或别名索引。 | N/A | +| `ignore_unavailable` | Boolean | 如果为 `false`,当请求针对缺失或关闭的索引时返回错误。 | N/A | +| `lenient` | Boolean | 如果为 `true`,查询字符串中基于格式的查询失败(例如向数值字段提供文本)将被忽略。 | N/A | +| `min_score` | Float | 设置文档必须具有的最小 `_score` 值才能包含在结果中。 | N/A | +| `preference` | String | 指定应在其上执行操作的节点或分片。默认为随机。 | `random` | +| `q` | String | Lucene 查询字符串语法中的查询。 | N/A | +| `routing` | 列表或字符串 | 用于将操作路由到特定分片的自定义值。 | N/A | +| `terminate_after` | Integer | 每个分片要收集的最大文档数。如果查询达到此限制,OpenSearch 会提前终止查询。OpenSearch 在排序之前收集文档。 | N/A | + +<!-- spec_insert_end --> + +## 请求正文字段 + +请求正文是可选的。您可以使用它通过 Query DSL 定义的查询来限制结果。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | Object | 用于过滤文档的查询。如果未指定,将使用 `match_all` 查询来计数目标中的所有文档。有关 OpenSearch 查询的更多信息,请参阅 [Query DSL](/query-dsl/)。 + +## 示例:统计集群中的所有文档 + +以下示例请求返回整个集群中所有文档的总计数: + +<!-- spec_insert_start +component: example_code +rest: GET /_count +--> + +GET /_count + +response = client.count() + +<!-- spec_insert_end --> + +## 示例:统计多个索引中的所有文档 + +以下示例请求返回 `movies` 和 `tv_shows` 索引中所有文档的总计数: + +<!-- spec_insert_start +component: example_code +rest: GET /movies,tv_shows/_count +--> + +GET /movies,tv_shows/_count + +response = client.count( + index = "movies,tv_shows" +) + +<!-- spec_insert_end --> + +## 示例:统计匹配查询的文档 + +以下示例请求统计 `movies` 索引中 `genre` 字段为 `drama` 的文档: + +<!-- spec_insert_start +component: example_code +rest: POST /movies/_count +body: | +{ + "query": { + "term": { + "genre": "drama" + } + } +} +--> + +POST /movies/_count +{ + "query": { + "term": { + "genre": "drama" + } + } +} + +response = client.count( + index = "movies", + body = { + "query": { + "term": { + "genre": "drama" + } + } + } +) + +<!-- spec_insert_end --> + +## 示例:使用查询字符串统计文档 + +以下示例请求使用 `q` 查询参数来统计 `genre` 字段为 `drama` 的文档: + +<!-- spec_insert_start +component: example_code +rest: GET /movies/_count?q=genre:drama +--> + +GET /movies/_count?q=genre:drama + +response = client.count( + index = "movies", + params = { "q": "genre:drama" } +) + +<!-- spec_insert_end --> + +## 示例:提前终止的文档统计 + +以下示例请求使用 `terminate_after` 参数在找到三个匹配文档后停止计数: + +<!-- spec_insert_start +component: example_code +rest: POST /movies/_count?terminate_after=3 +body: | +{ + "query": { + "match_all": {} + } +} +--> + +POST /movies/_count?terminate_after=3 +{ + "query": { + "match_all": {} + } +} + +response = client.count( + index = "movies", + params = { "terminate_after": "3" }, + body = { + "query": { + "match_all": {} + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下示例响应显示文档计数和分片信息: + +```json +{ + "count" : 7, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + } +} +``` + +使用 `terminate_after` 参数时,响应包含一个 `terminated_early` 字段: + +```json +{ + "terminated_early" : true, + "count" : 7, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + } +} +``` + +## 响应正文字段 + +Count API 响应包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`count` | Integer | 匹配查询的文档总数。如果未提供查询,这表示指定目标中的所有文档。 +`_shards` | Object | 包含有关计数操作中涉及的分片的信息。 +`_shards.total` | Integer | 为计数操作查询的分片总数。 +`_shards.successful` | Integer | 成功执行计数操作的分片数量。 +`_shards.skipped` | Integer | 计数操作期间跳过的分片数量。如果分片不包含任何匹配查询的文档,则可能会被跳过。 +`_shards.failed` | Integer | 未能执行计数操作的分片数量。如果此值大于 0,请检查集群健康状况和分片分配。 +`terminated_early` | Boolean | 仅在使用 `terminate_after` 查询参数时出现。当为 `true` 时,表示计数操作在统计所有匹配文档之前被终止。 + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`indices:data/read/search`。 diff --git a/i18n/zh/api-reference/search-apis/explain.md b/i18n/zh/api-reference/search-apis/explain.md new file mode 100644 index 00000000..76cc033a --- /dev/null +++ b/i18n/zh/api-reference/search-apis/explain.md @@ -0,0 +1,240 @@ +--- +title: Explain +--- + +# Explain API +<Badge type="tip" text="引入版本 1.0" /> + +Explain API 返回有关特定文档为何匹配或不匹配查询的详细信息。此 API 帮助您了解 OpenSearch 如何计算每个搜索结果的相关性分数 (`_score`),使其成为调试搜索相关性问题和优化查询的重要工具。 + +OpenSearch 使用名为 [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) 的概率排名框架来计算相关性分数。Okapi BM25 基于 Apache Lucene 使用的原始[词频/逆文档频率 (TF/IDF)](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/package-summary.html#scoring) 框架。 + +::: danger WARNING +在资源和时间方面,使用 Explain API 的成本都很高。对于生产集群,我们建议仅将其用于故障排除目的。 +::: + +## 限制 + +Explain API 不支持 `search_pipeline` 参数。发送带有内联或命名搜索管道的请求会导致 `parsing_exception` 错误。这适用于所有查询类型。 + +要在 `explain` 中使用搜索管道处理器,请向 [Search API](/api-reference/search) 提供 `explain=true` 查询参数。有关在混合查询中使用 `explain` 的更多信息,请参阅[混合搜索解释](/vector-search/ai-search/hybrid-search/explain/)。 + +<!-- spec_insert_start +api: explain +component: endpoints +--> +## 端点 +```json +GET /{index}/_explain/{id} +POST /{index}/_explain/{id} +``` +<!-- spec_insert_end --> + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `id` | **必需** | String | 文档 ID。 | +| `index` | **必需** | String | 要搜索的索引。只能指定单个索引名称。 | + +## 查询参数 + +您必须指定索引和文档 ID。所有其他参数都是可选的。 + +参数 | 类型 | 描述 | 必需 +:--- | :--- | :--- | :--- +`analyzer` | String | 用于 `q` 查询字符串的分析器。仅在使用 `q` 时有效。 | 否 +`analyze_wildcard` | Boolean | 是否分析 `q` 字符串中的通配符和前缀查询。仅在使用 `q` 时有效。默认值为 `false`。 | 否 +`default_operator` | String | `q` 查询字符串的默认布尔运算符(`AND` 或 `OR`)。仅在使用 `q` 时有效。默认值为 `OR`。 | 否 +`df` | String | 如果 `q` 字符串中未指定字段,则搜索的默认字段。仅在使用 `q` 时有效。 | 否 +`lenient` | Boolean | 指定 OpenSearch 是否应忽略基于格式的查询失败(例如,查询文本字段以查找整数)。默认值为 `false`。 | 否 +`preference` | String | 指定从哪个分片检索结果的偏好。可用选项为 `_local`(告诉操作从本地分配的分片副本检索结果)和分配给特定分片副本的自定义字符串值。默认情况下,OpenSearch 在随机分片上执行解释操作。 | 否 +`q` | String | [Lucene 语法](/query-dsl/full-text/query-string#query-string-syntax)中的查询字符串。使用时,您可以使用 `analyzer`、`analyze_wildcard`、`default_operator`、`df` 和 `stored_fields` 参数配置查询行为。 | 否 +`stored_fields` | String | 要返回的存储字段的逗号分隔列表。如果省略,仅返回 `_source`。 | 否 +`routing` | String | 用于将操作路由到特定分片的值。 | 否 +`_source` | String | 是否在响应正文中包含 `_source` 字段。有效值为 `true`(包含完整的 `_source`)、`false`(排除 `_source`)或要在查询响应中包含的源字段的逗号分隔列表。默认情况下,当未指定时,Explain API 响应中不返回 `_source` 字段。 | 否 +`_source_excludes` | String | 要在查询响应中排除的源字段的逗号分隔列表。 | 否 +`_source_includes` | String | 要在查询响应中包含的源字段的逗号分隔列表。 | 否 + +## 请求正文字段 + +请求正文包含要针对指定文档解释的查询。下表列出了可用的请求正文字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`query` | Object | 要针对文档执行的查询。使用与 [Search API](/api-reference/search) 相同的查询语法。有关查询类型的更多信息,请参阅 [Query DSL](/query-dsl/)。 + +## 示例:解释匹配查询 + +以下示例解释了为什么 `products` 索引中的文档 `1` 与 `name` 字段中术语 "computer" 的查询匹配: + +<!-- spec_insert_start +component: example_code +rest: POST /products/_explain/1 +body: | +{ + "query": { + "match": { + "name": "computer" + } + } +} +--> + +POST /products/_explain/1 +{ + "query": { + "match": { + "name": "computer" + } + } +} + +response = client.explain( + id = "1", + index = "products", + body = { + "query": { + "match": { + "name": "computer" + } + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +Explain API 返回一个响应,其中包括文档是否匹配查询以及分数计算的详细分解。解释包括 BM25 评分公式组成部分:词频 (`tf`)、逆文档频率 (`idf`) 和字段长度归一化: + +<details markdown="block"> + <summary> + 解释匹配查询的响应 + </summary> + +```json +{ + "_index": "products", + "_id": "1", + "matched": true, + "explanation": { + "value": 0.31506687, + "description": "weight(name:computer in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 0.31506687, + "description": "score(freq=1.0), computed as boost * idf * tf from:", + "details": [ + { + "value": 0.6931472, + "description": "idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:", + "details": [ + { + "value": 2, + "description": "n, number of documents containing term", + "details": [] + }, + { + "value": 4, + "description": "N, total number of documents with field", + "details": [] + } + ] + }, + { + "value": 0.45454544, + "description": "tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl)) from:", + "details": [ + { + "value": 1.0, + "description": "freq, occurrences of term within document", + "details": [] + }, + { + "value": 1.2, + "description": "k1, term saturation parameter", + "details": [] + }, + { + "value": 0.75, + "description": "b, length normalization parameter", + "details": [] + }, + { + "value": 2.0, + "description": "dl, length of field", + "details": [] + }, + { + "value": 2.0, + "description": "avgdl, average length of field", + "details": [] + } + ] + } + ] + } + ] + } +} +``` + +</details> + +## 示例:使用查询字符串参数 + +您可以使用 `q` 参数使用 Lucene 查询字符串语法指定查询,而不是提供请求正文。以下示例解释了为什么文档 `1` 匹配查询字符串 "name:laptop": + +<!-- spec_insert_start +component: example_code +rest: GET /products/_explain/1?q=name:laptop +--> + +GET /products/_explain/1?q=name:laptop + +response = client.explain( + id = "1", + index = "products", + params = { "q": "name:laptop" } +) + +<!-- spec_insert_end --> + +## 响应正文字段 + +响应包含有关文档是否匹配查询以及相关性分数如何计算的详细信息。下表列出了响应正文字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`_index` | String | 包含文档的索引名称。 +`_id` | String | 文档 ID。 +`matched` | Boolean | 文档是否匹配查询。如果为 `true`,则文档匹配并具有相关性分数。如果为 `false`,则文档不匹配查询。 +`explanation` | Object | 分数计算的解释。包含以下嵌套字段:`value`(计算的分数或分数组成部分)、`description`(计算的人类可读描述)和 `details`(嵌套计算的子解释数组)。 +`explanation.value` | Float | 分数计算的数值结果。对于顶级解释,这是最终相关性分数。对于嵌套解释,这表示中间计算值。 +`explanation.description` | String | 正在执行的计算的描述。对于 BM25 评分,这通常描述评分公式组成部分,例如词频 (`tf`)、逆文档频率 (`idf`) 和归一化因子。 +`explanation.details` | Array of objects | 将分数计算分解为组成部分的嵌套解释对象数组。每个详细对象具有与解释对象相同的结构(带有 `value`、`description` 和 `details` 字段)。 +`get` | Object | 文档元数据和源数据。仅在使用 `_source` 或 `stored_fields` 参数时包含。包含诸如 `_seq_no`、`_primary_term`、`found` 和 `_source` 等字段。 +`get._source` | Object | 文档的原始 JSON 内容。仅在指定 `_source` 参数时包含。 + +## BM25 评分组成部分 + +解释详细信息包括以下 BM25 评分组成部分。 + +字段 | 描述 +:--- | :--- +`idf` | 逆文档频率。衡量术语在索引中所有文档中的稀有程度或常见程度。计算为 `log(1 + (N - n + 0.5) / (n + 0.5))`,其中 `N` 是具有该字段的文档总数,`n` 是包含该术语的文档数量。稀有术语具有较高的 IDF 值,对相关性分数的贡献更大。 +`tf` | 词频。衡量术语在文档字段中出现的频率。计算为 `freq / (freq + k1 * (1 - b + b * dl / avgdl))`,其中 `freq` 是术语出现的次数,`k1` 是术语饱和参数(默认为 1.2),`b` 是长度归一化参数(默认为 0.75),`dl` 是字段长度,`avgdl` 是所有文档的平均字段长度。更频繁的术语对相关性分数的贡献更大,但收益递减。 +`k1` | 术语饱和参数。控制随着词频增加分数增加的速度。默认值为 1.2。较低的值导致分数更快地饱和,而较高的值允许词频对分数产生更大的影响。 +`b` | 长度归一化参数。控制字段长度对分数的影响程度。默认值为 0.75。值为 0 禁用长度归一化,而值为 1 完全按字段长度归一化。具有匹配术语的较短字段通常会获得较高的分数。 +`dl` | 文档字段长度。此特定文档的字段中的标记数。 +`avgdl` | 平均文档字段长度。索引中所有文档的字段中的平均标记数。 +`boost` | 查询提升值。应用于分数的乘数。当在查询中未明确指定时,默认提升为 1.0。 + +最终相关性分数是通过将这些组成部分相乘计算得出的:`score = boost * idf * tf`。这些值在添加或更新文档时在索引时计算和存储,并且可能基于分片级统计信息具有小的不准确性。 + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`indices:data/read/explain`。 diff --git a/i18n/zh/api-reference/search-apis/field-caps.md b/i18n/zh/api-reference/search-apis/field-caps.md new file mode 100644 index 00000000..75ac4cc9 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/field-caps.md @@ -0,0 +1,230 @@ +--- +title: Field capabilities +--- + +# Field capabilities API +<Badge type="tip" text="引入版本 1.0" /> + +`_field_caps` API 提供有关一个或多个索引中字段功能的信息。它通常由客户端用于确定字段的映射方式以及它们是否可用于跨多个索引的搜索、排序和聚合。 + +当索引具有不同的映射且查询需要评估这些索引之间的字段兼容性时,此 API 特别有用。 + +## 端点 + +```json +GET /_field_caps +POST /_field_caps +GET /{index}/_field_caps +POST /{index}/_field_caps +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `index` | 列表或字符串 | 用于限制请求的数据流、索引和别名的逗号分隔列表。支持通配符 (*)。要针对所有数据流和索引,请省略此参数或使用 * 或 `_all`。_可选_。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `allow_no_indices` | Boolean | 如果为 `false`,当任何通配符表达式、索引别名或 `_all` 值仅针对缺失或关闭的索引时,请求会返回错误。即使请求针对其他开放索引,此行为也适用。例如,如果索引以 foo 开头但没有索引以 bar 开头,则针对 `foo*,bar*` 的请求会返回错误。默认值为 `true`。 | +| `expand_wildcards` | 列表或字符串 | 通配符模式可以匹配的索引类型。如果请求可以针对数据流,此参数确定通配符表达式是否匹配隐藏数据流。支持逗号分隔的值,例如 `open,hidden`。<br> 有效值为:<br> - `all`:匹配任何索引,包括隐藏索引。<br> - `closed`:匹配关闭的非隐藏索引。<br> - `hidden`:匹配隐藏索引。必须与 `open`、`closed` 或两者结合使用。<br> - `none`:不接受通配符表达式。<br> - `open`:匹配开放的非隐藏索引。<br> 默认值为 `open`。 | +| `fields` | 列表或字符串 | 要检索功能的字段的逗号分隔列表。支持通配符 (`*`) 表达式。 | +| `ignore_unavailable` | Boolean | 如果为 `true`,则响应中不包含缺失或关闭的索引。默认值为 `false`。 | +| `include_unmapped` | Boolean | 如果为 `true`,则响应中包含未映射的字段。默认值为 `false`。 | + +## 请求正文字段 + +下表列出了可用的请求正文字段。 + +| 字段 | 数据类型 | 描述 | +| :------------- | :-------- | :---------------------------------------------------------------------- | +| `index_filter` | Object | 用于过滤请求中包含的索引的查询 DSL 对象。请参阅[示例:使用索引过滤器](#example-using-an-index-filter)。_可选_。| + +## 示例请求 + +为同一字段创建具有不同映射的两个索引: + +```json +PUT /store-west +{ + "mappings": { + "properties": { + "product": { "type": "text" }, + "price": { "type": "float" } + } + } +} +``` + +```json +PUT /store-east +{ + "mappings": { + "properties": { + "product": { "type": "keyword" }, + "price": { "type": "float" } + } + } +} +``` + +查询两个索引的字段功能: + +<!-- spec_insert_start +component: example_code +rest: GET /store-west,store-east/_field_caps?fields=product,price +--> + +GET /store-west,store-east/_field_caps?fields=product,price + +response = client.field_caps( + index = "store-west,store-east", + params = { "fields": "product,price" } +) + +<!-- spec_insert_end --> + +### 示例响应 + +响应提供可用字段的功能: + +```json +{ + "indices": [ + "store-east", + "store-west" + ], + "fields": { + "product": { + "text": { + "type": "text", + "searchable": true, + "aggregatable": false, + "indices": [ + "store-west" + ] + }, + "keyword": { + "type": "keyword", + "searchable": true, + "aggregatable": true, + "indices": [ + "store-east" + ] + } + }, + "price": { + "float": { + "type": "float", + "searchable": true, + "aggregatable": true + } + } + } +} +``` + +## 示例:使用索引过滤器 + +您可以使用 `index_filter` 限制考虑的索引。`index_filter` 根据字段级元数据(而不是实际文档内容)过滤索引。以下请求将索引选择限制为那些包含包含 `product` 字段的映射的索引,即使没有索引文档: + +<!-- spec_insert_start +component: example_code +rest: POST /_field_caps?fields=product,price +body: | +{ + "index_filter": { + "term": { + "product": "notebook" + } + } +} +--> + +POST /_field_caps?fields=product,price +{ + "index_filter": { + "term": { + "product": "notebook" + } + } +} + +response = client.field_caps( + params = { "fields": "product,price" }, + body = { + "index_filter": { + "term": { + "product": "notebook" + } + } + } +) + +<!-- spec_insert_end --> + +### 示例响应 + +响应仅包括来自包含值为 `notebook` 的 `product` 字段的索引的字段: + +```json +{ + "indices": [ + "store-east", + "store-west" + ], + "fields": { + "product": { + "text": { + "type": "text", + "searchable": true, + "aggregatable": false, + "indices": [ + "store-west" + ] + }, + "keyword": { + "type": "keyword", + "searchable": true, + "aggregatable": true, + "indices": [ + "store-east" + ] + } + }, + "price": { + "float": { + "type": "float", + "searchable": true, + "aggregatable": true + } + } + } +} +``` + +### 响应正文字段 + +下表列出了所有响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :----------------------------------------------- | :----------- | :----------------------------------------------------------------------------------------------------------------------- | +| `indices` | 列表 | 响应中包含的索引列表。 | +| `fields` | Object | 类型到字段功能的映射,其中每个键是字段名称,其值是一个对象。 | +| `fields.<field>.<type>.type` | String | 字段的数据类型(例如,`float`、`text`、`keyword`)。 | +| `fields.<field>.<type>.searchable` | Boolean | 字段是否可搜索。在使用可插拔数据格式的索引中,数值、`date`、`date_nanos`、`ip` 和 `boolean` 字段不被索引,但 OpenSearch 仍然可以使用 doc values 对它们运行 `range`、`term` 和 `terms` 查询。从 OpenSearch 3.10 开始,当启用 `doc_values` 时,这些字段的 `searchable` 为 `true`。有关更多信息,请参阅[可插拔数据格式索引](/mappings/mapping-parameters/index-parameter/#pluggable-data-format-indexes)。 | +| `fields.<field>.<type>.aggregatable` | Boolean | 字段是否可用于聚合,如 `sum` 或 `terms`。 | +| `fields.<field>.<type>.indices` | 列表 | 此字段以相应类型出现的索引列表。 | +| `fields.<field>.<type>.non_searchable_indices` | 列表或 null | 字段*不*可搜索的索引列表。`null` 表示该字段在任何索引中都不可搜索。 | +| `fields.<field>.<type>.non_aggregatable_indices` | 列表或 null | 字段*不*可聚合的索引列表。`null` 表示该字段在任何索引中都不可聚合。 | +| `fields.<field>.<type>.meta` | Object | 来自所有映射的合并元数据值。键是自定义元数据键,值是跨索引的值数组。 | + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`indices:data/read/field_caps` 和 `indices:data/read/field_caps*`。 diff --git a/i18n/zh/api-reference/search-apis/index.md b/i18n/zh/api-reference/search-apis/index.md new file mode 100644 index 00000000..f3df4e97 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/index.md @@ -0,0 +1,41 @@ +--- +title: Search APIs +--- + +# Search APIs +<Badge type="tip" text="引入版本 1.0" /> + +OpenSearch 提供了一套全面的搜索相关 API,允许您执行各种搜索操作、测试和验证您的搜索以及使用搜索模板。OpenSearch 支持以下搜索 API。 + +::: info NOTE +此页面上列出的端点路径(例如,`GET /{index}/_search`)相对于您的 OpenSearch 主机和端口。完整的 URL 格式为 `https://<host>:<port>/{index}/_search`,其中默认端口为 `9200`。有关连接到 OpenSearch 的更多信息,请参阅[与 OpenSearch 通信](/getting-started/communicate/)。 +::: + +## 核心搜索 API + +这些 API 构成了 OpenSearch 搜索功能的基础: + +- **[Search](/api-reference/search-apis/search)**:跨一个或多个索引运行搜索查询。 +- **[Multi-search](/api-reference/search-apis/multi-search)**:在单个 API 调用中运行多个搜索请求。 +- **[Point in Time](/api-reference/search-apis/point-in-time-api)**:创建索引的一致视图以进行搜索操作。 +- **[Scroll](/api-reference/search-apis/scroll)**:从搜索查询中检索大量结果。 +- **[Count](/api-reference/search-apis/count)**:获取与查询匹配的文档数量。 + +## 搜索测试 API + +这些 API 帮助您测试、调试和优化搜索操作: + +- **[Explain](/api-reference/search-apis/explain)**:解释特定文档如何匹配(或不匹配)查询。 +- **[Field capabilities](/api-reference/search-apis/field-caps)**:获取跨多个索引的字段功能。 +- **[Profile](/api-reference/search-apis/profile)**:分析搜索请求的执行。 +- **[Ranking evaluation](/api-reference/search-apis/rank-eval)**:评估搜索结果的质量。 +- **[Search shards](/api-reference/search-apis/search-shards)**:获取有关将在其上执行搜索请求的分片的信息。 +- **[Validate](/api-reference/search-apis/validate)**:在执行潜在昂贵的查询之前验证它。 + +## 搜索模板 API + +这些 API 允许您使用搜索模板: + +- **[Search template](/api-reference/search-apis/search-template/)**:使用搜索模板运行参数化搜索查询。 +- **[Multi-search template](/api-reference/search-apis/search-template/msearch-template)**:在单个 API 调用中执行多个搜索模板请求。 +- **[Render template](/api-reference/search-apis/search-template/render-template)**:通过替换参数来预览从搜索模板生成的最终查询,而不执行搜索。 diff --git a/i18n/zh/api-reference/search-apis/multi-search.md b/i18n/zh/api-reference/search-apis/multi-search.md new file mode 100644 index 00000000..3377a789 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/multi-search.md @@ -0,0 +1,437 @@ +--- +title: Multi-search +--- + +# Multi-Search API +<Badge type="tip" text="引入版本 1.0" /> + +顾名思义,multi-search 操作允许您将多个搜索请求捆绑到单个请求中。然后,OpenSearch 并行执行搜索,因此与每次搜索发送一个请求相比,您可以更快地获得响应。OpenSearch 独立执行每个搜索,因此一个搜索的失败不会影响其他搜索。 + +<!-- spec_insert_start +api: msearch +component: endpoints +--> +## 端点 +```json +GET /_msearch +POST /_msearch +GET /{index}/_msearch +POST /{index}/_msearch +``` +<!-- spec_insert_end --> + +在路径中指定索引会为其元数据行不包含 `index` 字段的任何搜索设置默认目标。如果您省略路径参数且搜索的元数据行也未指定 `index`,则搜索将针对所有索引运行。 + +## 查询参数和元数据选项 + +所有参数都是可选的。某些参数也可以作为每个元数据行的一部分应用于每次搜索。 + +参数 | 类型 | 描述 | 在元数据行中支持 +:--- | :--- | :--- | :--- +`allow_no_indices` | Boolean | 是否忽略不匹配任何索引的通配符。默认值为 `true`。 | 是 +`cancel_after_time_interval` | Time | 搜索请求将被取消的时间。在父级和子级请求级别都支持。优先顺序为:<br> 1. 子级参数<br> 2. 父级参数<br> 3. [集群设置](/api-reference/cluster-api/cluster-settings)。<br>默认值为 -1。 | 是 +`ccs_minimize_roundtrips` | Boolean | OpenSearch 是否应尝试最小化协调节点和远程集群之间的网络往返次数(仅适用于跨集群搜索请求)。默认值为 `true`。 | 否 +`expand_wildcards` | Enum | 将通配符表达式扩展为具体索引。将多个值与逗号组合。支持的值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认值为 `open`。 | 是 +`ignore_unavailable` | Boolean | 如果索引列表中的索引或分片不存在,是否忽略它而不是使查询失败。默认值为 `false`。 | 是 +`include_named_queries_score` | Boolean | 是否返回命名查询的分数。默认值为 `false`。 | 否 +`max_concurrent_searches` | Integer | 最大并发搜索数。默认值取决于您的节点数量和搜索线程池大小。较高的值可以提高性能,但有使集群过载的风险。 | 否 +`max_concurrent_shard_requests` | Integer | 每个搜索在每个节点上执行的最大并发分片请求数。默认值为 5。较高的值可以提高性能,但有使集群过载的风险。 | 否 +`pre_filter_shard_size` | Integer | 触发预过滤往返以消除无法匹配查询的分片(例如,因为日期范围过滤器超出分片的边界)的阈值。当未指定时,如果请求针对超过 128 个分片、针对只读索引或在索引字段上排序,则运行预过滤阶段。默认值为 `128`。 | 否 +`rest_total_hits_as_int` | String | `hits.total` 属性是否作为整数 (`true`) 或对象 (`false`) 返回。默认值为 `false`。 | 否 +`routing` | String | 用于将请求中的所有搜索路由到特定分片的逗号分隔的自定义路由值。要为各个搜索设置路由,请改用元数据行中的 `routing` 选项。 | 否 +`search_type` | String | 影响相关性分数。有效选项为 `query_then_fetch` 和 `dfs_query_then_fetch`。`query_then_fetch` 使用分片的术语和文档频率对文档进行评分(更快,不太准确),而 `dfs_query_then_fetch` 使用所有分片的术语和文档频率(更慢,更准确)。默认值为 `query_then_fetch`。 | 是 +`typed_keys` | Boolean | 是否在响应中为聚合名称添加其内部类型前缀。默认值为 `false`。 | 否 + +## 仅元数据选项 + +某些选项不能作为参数应用于整个请求。相反,您可以将它们作为每个元数据行的一部分应用于每次搜索。所有选项都是可选的。 + +选项 | 类型 | 描述 +:--- | :--- | :--- +`index` | String、string array | 如果您未将索引或多个索引指定为 URL 的一部分(或想要覆盖单个搜索的 URL 值),您可以在此处包含它。示例包括 `"logs-*"` 和 `["my-store", "sample_data_ecommerce"]`。 +`preference` | String | 您希望执行搜索的节点或分片。此设置对于测试很有用,但在大多数情况下,默认行为提供最佳搜索延迟。选项包括 `_local`、`_only_local`、`_prefer_nodes`、`_only_nodes` 和 `_shards`。最后三个选项接受节点或分片列表。示例包括 `"_only_nodes:data-node1,data-node2"` 和 `"_shards:0,1`。 +`request_cache` | Boolean | 是否缓存结果,这可以提高重复搜索的延迟。默认情况下使用索引的 `index.requests.cache.enable` 设置(对于新索引默认为 `true`)。 +`routing` | String | 逗号分隔的自定义路由值,例如 `"routing": "value1,value2,value3"`。与查询参数级别的 `routing`(适用于请求中的所有搜索)不同,此选项仅针对单个搜索的路由。 + +## 请求正文 + +multi-search 请求正文使用换行符分隔的 JSON (NDJSON) 格式,在元数据和查询行之间交替: + +``` +Metadata\n +Query\n +Metadata\n +Query\n + +``` + +- 元数据行包括选项,例如要搜索哪些索引和搜索类型。如果不需要每次搜索覆盖,元数据行可以为空 (`{}`)。 +- 查询行使用[查询 DSL](/query-dsl/)。 + +与[批量](/api-reference/document-apis/bulk)操作一样,JSON 不需要最小化---空格可以---但它确实需要在单行上。OpenSearch 使用换行符来解析 multi-search 请求,并要求请求正文以换行符结束。 + +::: info NOTE +向此端点发送请求时,将 `Content-Type` 标头设置为 `application/x-ndjson`。 +::: + +### 查询正文字段 + +每个查询行接受与 [Search API](/api-reference/search) 请求正文相同的参数。下表列出了最常用的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `query` | Object | 要执行的查询 DSL 表达式。请参阅[查询 DSL](/query-dsl/)。 | +| `aggregations` | Object | 与搜索一起运行的聚合。请参阅[聚合](/aggregations/)。 | +| `from` | Integer | 返回命中的起始偏移量。默认值为 `0`。 | +| `size` | Integer | 要返回的命中数。默认值为 `10`。 | +| `sort` | Array or Object | 对结果进行排序的字段和顺序。 | +| `_source` | Boolean、String 或 Object | 控制在每个命中的 `_source` 中包含哪些字段。 | +| `highlight` | Object | 匹配字段的突出显示配置。 | + +## 示例:搜索多个索引 + +以下示例针对多个索引运行查询,在每个元数据行中指定目标索引: + +<!-- spec_insert_start +component: example_code +rest: GET /_msearch +body: | +{ "index": "opensearch_dashboards_sample_data_logs"} +{ "query": { "match_all": {} }, "from": 0, "size": 10} +{ "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} +{ "query": { "match_all": {} } } +--> + +GET /_msearch +{ "index": "opensearch_dashboards_sample_data_logs"} +{ "query": { "match_all": {} }, "from": 0, "size": 10} +{ "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} +{ "query": { "match_all": {} } } + +response = client.msearch( + body = ''' +{ "index": "opensearch_dashboards_sample_data_logs"} +{ "query": { "match_all": {} }, "from": 0, "size": 10} +{ "index": "opensearch_dashboards_sample_data_ecommerce", "search_type": "dfs_query_then_fetch"} +{ "query": { "match_all": {} } } +''' +) + +<!-- spec_insert_end --> + +## 示例:使用默认索引 + +当您在 URL 路径中指定索引时,该索引将作为其元数据行不包含 `index` 字段的任何搜索的默认索引。以下示例针对 `products` 索引运行两个查询,而无需在每个元数据行中重复索引名称: + +<!-- spec_insert_start +component: example_code +rest: GET /products/_msearch +body: | +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} +--> + +GET /products/_msearch +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} + +response = client.msearch( + index = "products", + body = ''' +{} +{"query": {"match": {"product_name": "headphones"}}, "size": 1} +{} +{"query": {"range": {"price": {"gte": 30, "lte": 50}}}} +''' +) + +<!-- spec_insert_end --> + +## 使用搜索模板 + +multi-search API 通过 `_msearch/template` 端点支持[搜索模板](/api-reference/search-apis/search-template/)。这使您可以执行参数化搜索,将查询结构与搜索时传递的值分开。 + +### 示例:内联模板 + +以下请求使用内联模板在单个调用中运行两个参数化搜索: + +```json +GET _msearch/template +{"index": "products"} +{"source": {"query": {"match": {"product_name": "{{search_term}}"}}}, "params": {"search_term": "wireless"}} +{"index": "products"} +{"source": {"query": {"range": {"price": {"lte": "{{max_price}}"}}}}, "params": {"max_price": "75"}} + +``` + +### 示例:存储的模板 + +您还可以按 ID 引用预先注册的模板。首先,创建存储的模板: + +```json +POST _scripts/product_search_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "multi_match": { + "query": "{{query_text}}", + "fields": ["product_name", "description"] + } + }, + "size": "{{result_count}}" + } + } +} +``` + +```json +POST _scripts/price_range_template +{ + "script": { + "lang": "mustache", + "source": { + "query": { + "range": { + "price": { + "gte": "{{min_price}}", + "lte": "{{max_price}}" + } + } + }, + "size": "{{result_count}}" + } + } +} +``` + +然后在 multi-search 请求中使用存储的模板: + +```json +GET _msearch/template +{"index": "products"} +{"id": "product_search_template", "params": {"query_text": "bluetooth speaker", "result_count": "5"}} +{"index": "products"} +{"id": "price_range_template", "params": {"min_price": "20", "max_price": "100", "result_count": "3"}} + +``` + +## 示例响应 + +OpenSearch 以与 multi-search 请求相同的顺序返回一个包含每个搜索结果的数组。 + +```json +{ + "took" : 2150, + "responses" : [ + { + "took" : 2149, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10000, + "relation" : "gte" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "opensearch_dashboards_sample_data_logs", + "_id" : "_fnhBXsBgv2Zxgu9dZ8Y", + "_score" : 1.0, + "_source" : { + "agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)", + "bytes" : 4657, + "clientip" : "213.116.129.196", + "extension" : "zip", + "geo" : { + "srcdest" : "CN:US", + "src" : "CN", + "dest" : "US", + "coordinates" : { + "lat" : 42.35083333, + "lon" : -86.25613889 + } + }, + "host" : "artifacts.opensearch.org", + "index" : "opensearch_dashboards_sample_data_logs", + "ip" : "213.116.129.196", + "machine" : { + "ram" : 16106127360, + "os" : "ios" + }, + "memory" : null, + "message" : "213.116.129.196 - - [2018-07-30T14:12:11.387Z] \"GET /opensearch_dashboards/opensearch_dashboards-1.0.0-windows-x86_64.zip HTTP/1.1\" 200 4657 \"-\" \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\"", + "phpmemory" : null, + "referer" : "http://twitter.com/success/ellison-onizuka", + "request" : "/opensearch_dashboards/opensearch_dashboards-1.0.0-windows-x86_64.zip", + "response" : 200, + "tags" : [ + "success", + "info" + ], + "timestamp" : "2021-08-02T14:12:11.387Z", + "url" : "https://artifacts.opensearch.org/downloads/opensearch_dashboards/opensearch_dashboards-1.0.0-windows-x86_64.zip", + "utc_time" : "2021-08-02T14:12:11.387Z", + "event" : { + "dataset" : "sample_web_logs" + } + } + }, + ... + ] + }, + "status" : 200 + }, + { + "took" : 1473, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 4675, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "opensearch_dashboards_sample_data_ecommerce", + "_id" : "efnhBXsBgv2Zxgu9ap7e", + "_score" : 1.0, + "_source" : { + "category" : [ + "Women's Clothing" + ], + "currency" : "EUR", + "customer_first_name" : "Gwen", + "customer_full_name" : "Gwen Dennis", + "customer_gender" : "FEMALE", + "customer_id" : 26, + "customer_last_name" : "Dennis", + "customer_phone" : "", + "day_of_week" : "Tuesday", + "day_of_week_i" : 1, + "email" : "gwen@dennis-family.zzz", + "manufacturer" : [ + "Tigress Enterprises", + "Gnomehouse mom" + ], + "order_date" : "2021-08-10T16:24:58+00:00", + "order_id" : 576942, + "products" : [ + { + "base_price" : 32.99, + "discount_percentage" : 0, + "quantity" : 1, + "manufacturer" : "Tigress Enterprises", + "tax_amount" : 0, + "product_id" : 22182, + "category" : "Women's Clothing", + "sku" : "ZO0036600366", + "taxless_price" : 32.99, + "unit_discount_amount" : 0, + "min_price" : 14.85, + "_id" : "sold_product_576942_22182", + "discount_amount" : 0, + "created_on" : "2016-12-20T16:24:58+00:00", + "product_name" : "Jersey dress - black/red", + "price" : 32.99, + "taxful_price" : 32.99, + "base_unit_price" : 32.99 + }, + { + "base_price" : 28.99, + "discount_percentage" : 0, + "quantity" : 1, + "manufacturer" : "Gnomehouse mom", + "tax_amount" : 0, + "product_id" : 14230, + "category" : "Women's Clothing", + "sku" : "ZO0234902349", + "taxless_price" : 28.99, + "unit_discount_amount" : 0, + "min_price" : 13.05, + "_id" : "sold_product_576942_14230", + "discount_amount" : 0, + "created_on" : "2016-12-20T16:24:58+00:00", + "product_name" : "Blouse - june bug", + "price" : 28.99, + "taxful_price" : 28.99, + "base_unit_price" : 28.99 + } + ], + "sku" : [ + "ZO0036600366", + "ZO0234902349" + ], + "taxful_total_price" : 61.98, + "taxless_total_price" : 61.98, + "total_quantity" : 2, + "total_unique_products" : 2, + "type" : "order", + "user" : "gwen", + "geoip" : { + "country_iso_code" : "US", + "location" : { + "lon" : -118.2, + "lat" : 34.1 + }, + "region_name" : "California", + "continent_name" : "North America", + "city_name" : "Los Angeles" + }, + "event" : { + "dataset" : "sample_ecommerce" + } + } + }, + ... + ] + }, + "status" : 200 + } + ] +} +``` + +## 响应正文字段 + +下表列出了顶级响应正文字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `took` | Integer | OpenSearch 处理请求中所有搜索的总时间(以毫秒为单位)。 | +| `responses` | Array | 搜索响应对象数组,按请求中相应搜索的顺序返回。如果特定搜索完全失败,该搜索的数组条目包含 `error` 对象和 `status` 代码,而不是正常的搜索响应。 | + +下表列出了 `responses` 数组每个条目中的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `took` | Integer | OpenSearch 处理单个搜索的时间(以毫秒为单位)。 | +| `timed_out` | Boolean | 搜索是否在完成之前超时。 | +| `_shards` | Object | 有关搜索中涉及的分片数量的信息,包括 `total`、`successful`、`skipped` 和 `failed` 计数。 | +| `hits` | Object | 搜索结果,包括 `total` 命中计数、`max_score` 和匹配的 `hits` 数组。 | +| `status` | Integer | 单个搜索结果的 HTTP 状态代码。值 `200` 表示成功。 | + +## 部分响应 + +如果一个或多个分片在执行期间失败,multi-search API 仍会返回成功分片的结果。`responses` 数组中的每个单独搜索响应都包含一个 `_shards` 对象,该对象报告有多少分片成功以及有多少分片失败,从而允许您确定结果是否完整。 + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`indices:data/read/msearch`。 diff --git a/i18n/zh/api-reference/search-apis/point-in-time-api.md b/i18n/zh/api-reference/search-apis/point-in-time-api.md new file mode 100644 index 00000000..a60c4343 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/point-in-time-api.md @@ -0,0 +1,300 @@ +--- +title: Point in Time +--- + +# Point in Time API + +使用 [Point in Time (PIT)](/search-plugins/searching-data/point-in-time) API 来管理 PIT。 + +--- + +#### 目录 +- TOC + +--- + +## 创建 PIT +<Badge type="tip" text="引入版本 2.4" /> + +创建一个 PIT。`keep_alive` 查询参数是必需的;它指定保持 PIT 的时间长度。 + +每个节点可以保存有限数量的开放 PIT,由 `search.max_open_pit_context` 设置设置(默认为 `300`)。有关更多信息,请参阅 [PIT 设置](/search-plugins/searching-data/point-in-time#pit-settings)。 + +### 端点 + +```json +POST /{target_indexes}/_search/point_in_time +``` + +### 路径参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`target_indexes` | String | PIT 的目标索引的名称。可以包含逗号分隔的列表或通配符索引模式。 + +### 查询参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`keep_alive` | Time | 保持 PIT 的时间量。每次搜索使用 PIT 时都会重新启动倒计时。如果搜索指定了 `keep_alive` 值,PIT 的 keep-alive 变为当前值和新值中的较大值,因此较短的值不会缩短它。最大值由 `point_in_time.max_keep_alive` 集群设置设置(默认为 `24h`)。必需。 +`preference` | String | 用于执行搜索的节点或分片。可选。 +`routing` | String | 将 PIT 路由到指定路由值的分片。可选。默认情况下,使用所有分片。 +`expand_wildcards` | String | 可以匹配通配符模式的索引类型。支持逗号分隔的值。有效值为以下值:<br>- `all`:匹配任何索引或数据流,包括隐藏索引或数据流。<br>- `open`:匹配开放的非隐藏索引或非隐藏数据流。<br>- `hidden`:匹配隐藏索引或数据流。必须与 `open` 组合。<br>- `none`:不接受通配符模式。<br>关闭的索引不能是 PIT 目标,因此不支持 `closed` 值。可选。默认值为 `open`。 +`ignore_unavailable` | Boolean | 创建 PIT 时是否忽略缺失或关闭的索引。如果为 `false`,当任何目标索引缺失或关闭时,请求失败。可选。默认值为 `false`。 +`allow_partial_pit_creation` | Boolean | 指定是否创建具有部分故障的 PIT。如果为 `false`,当任何分片不可用时请求失败。可选。默认值为 `true`。 + +#### 示例请求 + +<!-- spec_insert_start +component: example_code +rest: POST /my-index-1/_search/point_in_time?keep_alive=100m +--> + +POST /my-index-1/_search/point_in_time?keep_alive=100m + +response = client.create_pit( + index = "my-index-1", + params = { "keep_alive": "100m" } +) + +<!-- spec_insert_end --> + +#### 示例响应 + +```json +{ + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAIWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "creation_time": 1658146050064 +} +``` + +### 响应正文字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`pit_id` | [Base64 编码的二进制](/field-types/supported-field-types/binary) | PIT ID。 +`_shards` | Object | 有关创建 PIT 的分片的信息。 +`creation_time` | `long` | 创建 PIT 的时间(自 epoch 以来的毫秒数)。 + +`_shards` 对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`total` | Integer | PIT 针对的分片总数。 +`successful` | Integer | 成功创建 PIT 的分片数量。 +`skipped` | Integer | 跳过的分片数量。 +`failed` | Integer | 无法创建 PIT 的分片数量。 + +## 扩展 PIT 时间 + +要使用 PIT 进行搜索,请在搜索请求的 `pit` 对象中提供 PIT ID。不要在请求路径中指定索引,因为 PIT 已经确定了目标索引;同时指定索引和 PIT 的搜索将被拒绝。有关更多信息,请参阅[使用 PIT 和 search_after 进行分页](/search-plugins/searching-data/point-in-time#pagination-with-pit-and-search_after)。 + +您可以在执行搜索时通过在 `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 NOTE +搜索请求中的 `keep_alive` 参数是可选的。每次使用 PIT 的搜索都会重新启动 keep-alive 倒计时。如果指定 `keep_alive`,PIT 的 keep-alive 变为当前值和新值中的较大值。 +::: + +## 列出所有 PIT +<Badge type="tip" text="引入版本 2.4" /> + +返回 OpenSearch 集群中的所有 PIT。 + +### 跨集群行为 + +List All PITs API 仅返回本地 PIT 或混合 PIT(在本地和远程集群中创建的 PIT)。它不返回完全远程的 PIT。 + +#### 示例请求 + +<!-- spec_insert_start +component: example_code +rest: GET /_search/point_in_time/_all +--> + +GET /_search/point_in_time/_all + +response = client.get_all_pits() + +<!-- spec_insert_end --> + +#### 示例响应 + +```json +{ + "pits": [ + { + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAEWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "creation_time": 1658146048666, + "keep_alive": 6000000 + }, + { + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFnNOWU43ckt3U3IyaFVpbGE1UWEtMncAFjFyeXBsRGJmVFM2RTB6eVg1aVVqQncAAAAAAAAAAAIWcDVrM3ZIX0pRNS1XejE5YXRPRFhzUQEWc05ZTjdyS3dTcjJoVWlsYTVRYS0ydwAA", + "creation_time": 1658146050064, + "keep_alive": 6000000 + } + ] +} +``` + +### 响应正文字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`pits` | Array of JSON objects | 所有 PIT 的列表。 + +每个 PIT 对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`pit_id` | [Base64 编码的二进制](/field-types/supported-field-types/binary) | PIT ID。 +`creation_time` | `long` | 创建 PIT 的时间(自 epoch 以来的毫秒数)。 +`keep_alive` | `long` | 保持 PIT 的时间量(以毫秒为单位)。 + +## 删除 PIT +<Badge type="tip" text="引入版本 2.4" /> + +删除一个、多个或所有 PIT。当 `keep_alive` 时间段过去时,PIT 会自动删除。但是,要释放资源,您可以使用 Delete PIT API 删除 PIT。Delete PIT API 支持按 ID 删除 PIT 列表或一次删除所有 PIT。 + +### 跨集群行为 + +Delete PITs by ID API 完全支持删除跨集群 PIT。 + +Delete All PITs API 仅删除本地 PIT 或混合 PIT(在本地和远程集群中创建的 PIT)。它不删除完全远程的 PIT。 + +#### 示例请求:删除所有 PIT + +::: danger WARNING +Delete All PITs API 删除集群中的每个 PIT,包括其他用户和应用程序创建的 PIT。使用已删除 PIT 的搜索将失败。 +::: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_search/point_in_time/_all +--> + +DELETE /_search/point_in_time/_all + +response = client.delete_all_pits() + +<!-- spec_insert_end --> + +如果您想删除一个或多个 PIT,请在请求正文中指定它们的 PIT ID。 + +### 请求正文字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`pit_id` | [Base64 编码的二进制](/field-types/supported-field-types/binary)或二进制数组 | 要删除的 PIT 的 PIT ID。必需。 + +#### 示例请求:按 ID 删除 PIT + +<!-- spec_insert_start +component: example_code +rest: DELETE /_search/point_in_time +body: | +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} +--> + +DELETE /_search/point_in_time +{ + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] +} + +response = client.delete_pit( + body = { + "pit_id": [ + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA", + "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + ] + } +) + +<!-- spec_insert_end --> + +#### 示例响应 + +对于每个 PIT,响应包含一个带有 PIT ID 和 `successful` 字段的 JSON 对象,该字段指定删除是否成功。部分失败被视为失败。 + +```json +{ + "pits": [ + { + "successful": true, + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAEWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + }, + { + "successful": false, + "pit_id": "o463QQEPbXktaW5kZXgtMDAwMDAxFkhGN09fMVlPUkVPLXh6MUExZ1hpaEEAFjBGbmVEZHdGU1EtaFhhUFc4ZkR5cWcAAAAAAAAAAAIWaXBPNVJtZEhTZDZXTWFFR05waXdWZwEWSEY3T18xWU9SRU8teHoxQTFnWGloQQAA" + } + ] +} +``` + +### 响应正文字段 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`successful` | Boolean | 删除操作是否成功。 +`pit_id` | [Base64 编码的二进制](/field-types/supported-field-types/binary) | 要删除的 PIT 的 PIT ID。 + +## 安全模型 + +本节描述在启用 Security 插件的情况下运行 OpenSearch 时使用 PIT API 操作所需的权限。 + +您可以使用 `point_in_time_full_access` 角色访问所有 PIT API 操作。如果此角色不能满足您的需求,请混合和匹配单个 PIT 权限以适应您的用例。每个操作对应于 REST API 中的一个操作。例如,`indices:data/read/point_in_time/create` 权限允许您创建 PIT。以下是可能的权限: + +- `indices:data/read/point_in_time/create` – Create API +- `indices:data/read/point_in_time/delete` – Delete API +- `indices:data/read/point_in_time/readall` – List All PITs API +- `indices:data/read/search` – Search API +- `indices:monitor/point_in_time/segments` – PIT Segments API + +对于 `all` API 操作,例如 list all 和 delete all,用户需要所有索引 (*) 权限。对于 API 操作(如 search、create PIT 或 delete list),用户只需要单个索引权限。 + +PIT ID 在保存时始终包含底层(已解析)索引。以下部分描述别名和数据流所需的权限。 + +### 别名权限 + +对于别名,用户必须对任何 PIT 操作具有索引**或**别名权限。 + +### 数据流权限 + +对于数据流,用户必须对任何 PIT 操作同时具有数据流**和**数据流的后备索引权限。例如,用户必须对 `data-stream-11` 数据流及其后备索引 `.ds-my-data-stream11-000001` 具有权限。 + +如果用户仅具有数据流权限,他们将能够创建 PIT,但如果没有后备索引权限,他们将无法将 PIT ID 用于其他操作(如搜索)。 diff --git a/i18n/zh/api-reference/search-apis/profile.md b/i18n/zh/api-reference/search-apis/profile.md new file mode 100644 index 00000000..1adec262 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/profile.md @@ -0,0 +1,1156 @@ +--- +title: Profile +--- + +# Profile API +<Badge type="tip" text="1.0 版本引入" /> + +Profile API 提供有关搜索请求各个组件执行的时间信息。使用 Profile API,您可以调试慢速请求并了解如何提高其性能。Profile API 不测量以下内容: + +- 网络延迟 +- 请求在队列中花费的时间 +- 在协调节点上合并分片响应时的空闲时间 + +::: danger WARNING +Profile API 是一项资源密集型操作,会为搜索操作增加开销。 +::: + +## 端点 + +```json +GET /testindex/_search +{ + "profile": true, + "query" : { + "match" : { "title" : "wind" } + } +} +``` + +## 并发段搜索 + +[并发段搜索](/search-plugins/concurrent-segment-search)允许每个分片级请求在查询阶段并行搜索段。Profile API 响应包含几个关于_切片_的统计信息的附加字段。 + +A slice is the unit of work that can be executed by a thread。响应中的每个 query can be partitioned into multiple slices, with each slice containing one or more segments。除了 the slices can be executed either in parallel or in some order depending on the available threads 指定为 pool。 + +In general, the max/min/avg slice time captures statistics across all slices for a timing type。For example, when profiling aggregations, the `max_slice_time_in_nanos` field 指定为 `aggregations` section shows the maximum time consumed by the aggregation operation and its children across all slices。 + +## 示例请求:非并发搜索 + +要使用 Profile API,请在发送到 `profile` 参数设置为 `true` 指定为 search request sent to the `_search` endpoint: + +<!-- spec_insert_start +component: example_code +rest: GET /testindex/_search +body: | +{ + "profile": true, + "query" : { + "match" : { "title" : "wind" } + } +} +--> + +GET /testindex/_search +{ + "profile": true, + "query": { + "match": { + "title": "wind" + } + } +} + +response = client。search( + index = "testindex", + body = { + "profile": true, + "query": { + "match": { + "title": "wind" + } + } + } +) + +<!-- spec_insert_end --> + +要开启人类可读格式,请在请求中包含 `?human=true` query parameter 指定为 request: + +<!-- spec_insert_start +component: example_code +rest: GET /testindex/_search?human=true +body: | +{ + "profile": true, + "query" : { + "match" : { "title" : "wind" } + } +} +--> + +GET /testindex/_search?human=true +{ + "profile": true, + "query": { + "match": { + "title": "wind" + } + } +} + +response = client。search( + index = "testindex", + params = { "human": "true" }, + body = { + "profile": true, + "query": { + "match": { + "title": "wind" + } + } + } +) + +<!-- spec_insert_end --> + +响应包含一个附加的 `time` field with human-readable units, for example: + +```json +"collector": [ + { + "name": "SimpleTopScoreDocCollector", + "reason": "search_top_hits", + "time": "113。7micros", + "time_in_nanos": 113711 + } +] +``` + +::: tip TIP +Profile API 响应非常详细,因此如果您通过 `curl` 命令运行请求,请包含 `?pretty` query parameter to make the response easier to understand。 +::: + +## 示例请求:聚合 + +要分析聚合,请发送聚合请求并提供 `profile` 参数设置为 `true`。 + +### 全局聚合 + +<!-- spec_insert_start +component: example_code +rest: GET /opensearch_dashboards_sample_data_ecommerce/_search +body: | +{ + "profile": "true", + "size": 0, + "query": { + "match": { "manufacturer": "Elitelligence" } + }, + "aggs": { + "all_products": { + "global": {}, + "aggs": { + "avg_price": { "avg": { "field": "taxful_total_price" } } + } + }, + "elitelligence_products": { "avg": { "field": "taxful_total_price" } } + } +} +--> + +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "profile": "true", + "size": 0, + "query": { + "match": { + "manufacturer": "Elitelligence" + } + }, + "aggs": { + "all_products": { + "global": {}, + "aggs": { + "avg_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + }, + "elitelligence_products": { + "avg": { + "field": "taxful_total_price" + } + } + } +} + +response = client。search( + index = "opensearch_dashboards_sample_data_ecommerce", + body = { + "profile": "true", + "size": 0, + "query": { + "match": { + "manufacturer": "Elitelligence" + } + }, + "aggs": { + "all_products": { + "global": {}, + "aggs": { + "avg_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + }, + "elitelligence_products": { + "avg": { + "field": "taxful_total_price" + } + } + } + } +) + +<!-- spec_insert_end --> + +### 非全局聚合 + +<!-- spec_insert_start +component: example_code +rest: GET /opensearch_dashboards_sample_data_ecommerce/_search +body: | +{ + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } +} +--> + +GET /opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } +} + +response = client。search( + index = "opensearch_dashboards_sample_data_ecommerce", + body = { + "size": 0, + "aggs": { + "avg_taxful_total_price": { + "avg": { + "field": "taxful_total_price" + } + } + } + } +) + +<!-- spec_insert_end --> + +## 示例响应:非并发搜索 + +The response contains profiling information: + +<details markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 21, + "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", + "description": "A 1939 American epic historical film" + } + } + ] + }, + "profile": { + "shards": [ + { + "id": "[LidyZ1HVS-u93-73Z49dQg][testindex][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "BooleanQuery", + "description": "title:wind title:rise", + "time_in_nanos": 2473919, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 5209, + "match": 0, + "next_doc_count": 2, + "score_count": 2, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 9209, + "advance_count": 2, + "score": 20751, + "build_scorer_count": 4, + "create_weight": 1404458, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 1034292 + }, + "children": [ + { + "type": "TermQuery", + "description": "title:wind", + "time_in_nanos": 813581, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 3291, + "match": 0, + "next_doc_count": 2, + "score_count": 2, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 7208, + "advance_count": 2, + "score": 18666, + "build_scorer_count": 6, + "create_weight": 616375, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 168041 + } + }, + { + "type": "TermQuery", + "description": "title:rise", + "time_in_nanos": 191083, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 0, + "match": 0, + "next_doc_count": 0, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 0, + "advance_count": 0, + "score": 0, + "build_scorer_count": 2, + "create_weight": 188625, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 2458 + } + } + ] + } + ], + "rewrite_time": 192417, + "collector": [ + { + "name": "SimpleTopScoreDocCollector", + "reason": "search_top_hits", + "time_in_nanos": 77291 + } + ] + } + ], + "aggregations": [] + } + ] + } +} +``` +</details> + +### 并发段搜索 + +The following is an example response for a concurrent segment search with three segment slices: + +<details markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + 。。。 + ] + }, + "aggregations": { + 。。。 + }, + "profile": { + "shards": [ + { + "id": "[9Y7lbpaWRhyr5Y-41Zl48g][idx][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "Match除了DocsQuery", + "description": "*:*", + "time_in_nanos": 868000, + "max_slice_time_in_nanos": 19376, + "min_slice_time_in_nanos": 12250, + "avg_slice_time_in_nanos": 16847, + "breakdown": { + "max_match": 0, + "set_min_competitive_score_count": 0, + "match_count": 0, + "avg_score_count": 1, + "shallow_advance_count": 0, + "next_doc": 29708, + "min_build_scorer": 3125, + "score_count": 5, + "compute_max_score_count": 0, + "advance": 0, + "min_set_min_competitive_score": 0, + "min_advance": 0, + "score": 29250, + "avg_set_min_competitive_score_count": 0, + "min_match_count": 0, + "avg_score": 333, + "max_next_doc_count": 3, + "max_compute_max_score_count": 0, + "avg_shallow_advance": 0, + "max_shallow_advance_count": 0, + "set_min_competitive_score": 0, + "min_build_scorer_count": 2, + "next_doc_count": 8, + "min_match": 0, + "avg_next_doc": 888, + "compute_max_score": 0, + "min_set_min_competitive_score_count": 0, + "max_build_scorer": 5791, + "avg_match_count": 0, + "avg_advance": 0, + "build_scorer_count": 6, + "avg_build_scorer_count": 2, + "min_next_doc_count": 2, + "min_shallow_advance_count": 0, + "max_score_count": 2, + "avg_match": 0, + "avg_compute_max_score": 0, + "max_advance": 0, + "avg_shallow_advance_count": 0, + "avg_set_min_competitive_score": 0, + "avg_compute_max_score_count": 0, + "avg_build_scorer": 4027, + "max_set_min_competitive_score_count": 0, + "advance_count": 0, + "max_build_scorer_count": 2, + "shallow_advance": 0, + "min_compute_max_score": 0, + "max_match_count": 0, + "create_weight_count": 1, + "build_scorer": 32459, + "max_set_min_competitive_score": 0, + "max_compute_max_score": 0, + "min_shallow_advance": 0, + "match": 0, + "max_shallow_advance": 0, + "avg_advance_count": 0, + "min_next_doc": 708, + "max_advance_count": 0, + "min_score": 291, + "max_next_doc": 999, + "create_weight": 1834, + "avg_next_doc_count": 2, + "max_score": 376, + "min_compute_max_score_count": 0, + "min_score_count": 1, + "min_advance_count": 0 + } + } + ], + "rewrite_time": 8126, + "collector": [ + { + "name": "QueryCollectorManager", + "reason": "search_multi", + "time_in_nanos": 564708, + "reduce_time_in_nanos": 1251042, + "max_slice_time_in_nanos": 121959, + "min_slice_time_in_nanos": 28958, + "avg_slice_time_in_nanos": 83208, + "slice_count": 3, + "children": [ + { + "name": "SimpleTopDocsCollectorManager", + "reason": "search_top_hits", + "time_in_nanos": 500459, + "reduce_time_in_nanos": 840125, + "max_slice_time_in_nanos": 22168, + "min_slice_time_in_nanos": 5792, + "avg_slice_time_in_nanos": 12084, + "slice_count": 3 + }, + { + "name": "NonGlobalAggCollectorManager: [histo]", + "reason": "aggregation", + "time_in_nanos": 552167, + "reduce_time_in_nanos": 311292, + "max_slice_time_in_nanos": 95333, + "min_slice_time_in_nanos": 18416, + "avg_slice_time_in_nanos": 66249, + "slice_count": 3 + } + ] + } + ] + } + ], + "aggregations": [ + { + "type": "NumericHistogramAggregator", + "description": "histo", + "time_in_nanos": 2847834, + "max_slice_time_in_nanos": 117374, + "min_slice_time_in_nanos": 20624, + "avg_slice_time_in_nanos": 75597, + "breakdown": { + "min_build_leaf_collector": 9500, + "build_aggregation_count": 3, + "post_collection": 3209, + "max_collect_count": 2, + "initialize_count": 3, + "reduce_count": 0, + "avg_collect": 17055, + "max_build_aggregation": 26000, + "avg_collect_count": 1, + "max_build_leaf_collector": 64833, + "min_build_leaf_collector_count": 1, + "build_aggregation": 41125, + "min_initialize": 583, + "max_reduce": 0, + "build_leaf_collector_count": 3, + "avg_reduce": 0, + "min_collect_count": 1, + "avg_build_leaf_collector_count": 1, + "avg_build_leaf_collector": 45000, + "max_collect": 24625, + "reduce": 0, + "avg_build_aggregation": 12013, + "min_post_collection": 292, + "max_initialize": 1333, + "max_post_collection": 750, + "collect_count": 5, + "avg_post_collection": 541, + "avg_initialize": 986, + "post_collection_count": 3, + "build_leaf_collector": 86833, + "min_collect": 6250, + "min_build_aggregation": 3541, + "initialize": 2786791, + "max_build_leaf_collector_count": 1, + "min_reduce": 0, + "collect": 29834 + }, + "debug": { + "total_buckets": 1 + } + } + ] + } + ] + } +} +``` +</details> + +## 响应正文字段 + +The response includes the following fields。 + +Field | Data type | Description +:--- | :--- | :--- +`profile` | Object | Contains profiling information。 +`profile。shards` | Array of objects | A search request can be executed against one or more shards 指定为 index, 并在 search may involve one or more indexes。Thus, the `profile。shards` array contains profiling information for each shard that was involved 指定为 search。 +`profile。shards。id` | String | 该shard ID of the shard 指定为 `[node-ID][index-name][shard-ID]` format。 +`profile。shards。searches` | Array of objects | A search represents a query executed against the underlying Lucene index。Most search requests execute a single search against a Lucene index, but some search requests can execute more than one search。For example, including a global aggregation results in a secondary `match_all` query for the global context。The `profile。shards` array contains profiling information about each search execution。 +[`profile。shards。searches。query`](#the-query-array) | Array of objects | Profiling information about the query execution。 +`profile。shards。searches。rewrite_time` | Integer | 除了 Lucene queries are rewritten。A query and its children may be rewritten more than once, until the query stops changing。The rewriting process involves performing optimizations, such 中将 removing redundant clauses or replacing a query path with a more efficient one。After the rewriting process, the original query may change significantly。The `rewrite_time` field contains the cumulative total rewrite time for the query 并在ll its children, in nanoseconds。 +[`profile。shards。searches。collector`](#the-collector-array) | Array of objects | Profiling information about the Lucene collectors that ran the search。 +[`profile。shards。aggregations`](#aggregation-responses) | Array of objects | Profiling information about the aggregation execution。 + +### `query` 数组 + +The `query` array contains objects with the following fields。 + +Field | Data type | Description +:--- | :--- | :--- +`type` | String | 该Lucene query type into which the search query was rewritten。Corresponds to the Lucene class name (which often has the same name in OpenSearch)。 +`description` | String | Contains a Lucene explanation of the query。Helps differentiate queries with the same type。 +`time_in_nanos` | Long | 该total elapsed time for this query, in nanoseconds。For concurrent segment search, `time_in_nanos` is the total time spent across all the slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`max_slice_time_in_nanos` | Long | 该maximum amount of time taken by any slice to run a query, in nanoseconds。This field is included only if you enable concurrent segment search。 +`min_slice_time_in_nanos` | Long | 该minimum amount of time taken by any slice to run a query, in nanoseconds。This field is included only if you enable concurrent segment search。 +`avg_slice_time_in_nanos` | Long | 该average amount of time taken by any slice to run a query, in nanoseconds。This field is included only if you enable concurrent segment search。 +[`breakdown`](#the-breakdown-object) | Object | Contains timing statistics about low-level Lucene execution。 +`children` | Array of objects | If a query has subqueries (children), this field contains information about the subqueries。 + +### `breakdown` 对象 + +The `breakdown` object represents the timing statistics about low-level Lucene execution, broken down by method。Timings are listed in wall-clock nanoseconds 并在re not normalized。The `breakdown` timings are inclusive of all child times。The `breakdown` object comprises the following fields。除了 fields contain integer values。 + +Field | Description +:--- | :--- +`create_weight` | A `Query` object in Lucene is immutable。Yet, Lucene should be able to reuse `Query` objects in multiple `IndexSearcher` objects。Thus, `Query` objects need to keep temporary state and statistics associated with the index in which the query is executed。To achieve reuse, every `Query` object generates a `Weight` object, which keeps the temporary context (state) associated with the `<IndexSearcher, Query>` tuple。The `create_weight` field contains the amount of time spent creating the `Weight` object。 +`build_scorer` | A `Scorer` iterates over matching documents and generates a score for each document。The `build_scorer` field contains the amount of time spent generating the `Scorer` object。This does not include the time spent scoring the documents。The `Scorer` initialization time depends on the optimization and complexity of a particular query。The `build_scorer` parameter also includes the amount of time associated with caching, if caching is applicable and enabled for the query。 +`next_doc` | 该`next_doc` Lucene method returns the document ID of the next document that matches the query。This method is a special type of the `advance` method and is equivalent to `advance(docId() + 1)`。The `next_doc` method is more convenient for many Lucene queries。The `next_doc` field contains the amount of time required to determine the next matching document, which varies depending on the query type。 +`advance` | 该`advance` method is a lower-level version of the `next_doc` method in Lucene。It also finds the next matching document but necessitates that the calling query perform additional tasks, such 中将 identifying skips。Some queries, such 中将 conjunctions (`must` clauses in Boolean queries), cannot use `next_doc`。For those queries, `advance` is timed。 +`match` | For some queries, document matching is performed in two steps。First, the document is matched approximately。Second, those documents that are approximately matched are examined through a more comprehensive process。For example, a phrase query first checks whether a document contains all terms 指定为 phrase。Next, it verifies that the terms are in order (which is a more expensive process)。The `match` field is non-zero only for those queries that use the two-step verification process。 +`score` | Contains the time taken for a `Scorer` to score a particular document。 +`shallow_advance` | Contains the amount of time required to execute the `advanceShallow` Lucene method。 +`compute_max_score` | Contains the amount of time required to execute the `getMaxScore` Lucene method。 +`set_min_competitive_score` | Contains the amount of time required to execute the `setMinCompetitiveScore` Lucene method。 +`<method>_count` | Contains the number of invocations of a `<method>`。For example, `advance_count` contains the number of invocations of the `advance` method。Different invocations of the same method occur because the method is called on different documents。You can determine the selectivity of a query by comparing counts in different query components。 +`max_<method>` | 该maximum amount of time taken by any slice to run a query method。Breakdown stats for the `create_weight` method do not include profiled `max` time because the method runs at the query level rather than the slice level。This field is included only if you enable concurrent segment search。 +`min_<method>` | 该minimum amount of time taken by any slice to run a query method。Breakdown stats for the `create_weight` method do not include profiled `min` time because the method runs at the query level rather than the slice level。This field is included only if you enable concurrent segment search。 +`avg_<method>` | 该average amount of time taken by any slice to run a query method。Breakdown stats for the `create_weight` method do not include profiled `avg` time because the method runs at the query level rather than the slice level。This field is included only if you enable concurrent segment search。 +`max_<method>_count` | 该maximum number of invocations of a `<method>` on any slice。Breakdown stats for the `create_weight` method do not include profiled `max` count because the method runs at the query level rather than the slice level。This field is included only if you enable concurrent segment search。 +`min_<method>_count` | 该minimum number of invocations of a `<method>` on any slice。Breakdown stats for the `create_weight` method do not include profiled `min` count because the method runs at the query level rather than the slice level。This field is included only if you enable concurrent segment search。 +`avg_<method>_count` | 该average number of invocations of a `<method>` on any slice。Breakdown stats for the `create_weight` method do not include profiled `avg` count because the method runs at the query level rather than the slice level。This field is included only if you enable concurrent segment search。 + +### `collector` 数组 + +The `collector` array contains information about Lucene Collectors。A Collector is responsible for coordinating document traversal and scoring and collecting matching documents。Using Collectors, individual queries can record aggregation results and execute global queries or post-query filters。 + +Field | Description +:--- | :--- +`name` | 该collector name。In the [example response](#example-response-non-concurrent-search), the `collector` is a single `SimpleTopScoreDocCollector`---the default scoring and sorting collector。 +`reason` | Contains a description of the collector。For possible field values, see [Collector reasons](#collector-reasons)。 +`time_in_nanos` | 该total elapsed time for this collector, in nanoseconds。For concurrent segment search, `time_in_nanos` is the total amount of time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`children` | If a collector has subcollectors (children), this field contains information about the subcollectors。 +`max_slice_time_in_nanos` | 该maximum amount of time taken by any slice, in nanoseconds。 This field is included only if you enable concurrent segment search。 +`min_slice_time_in_nanos` | 该minimum amount of time taken by any slice, in nanoseconds。 This field is included only if you enable concurrent segment search。 +`avg_slice_time_in_nanos` | 该average amount of time taken by any slice, in nanoseconds。 This field is included only if you enable concurrent segment search。 +`slice_count` | 该total slice count for this query。This field is included only if you enable concurrent segment search。 +`reduce_time_in_nanos` | 该amount of time taken to reduce results for all slice collectors, in nanoseconds。 This field is included only if you enable concurrent segment search。 + +::: info NOTE +Collector times are calculated, combined, and normalized independently, so they are independent of query times。 +::: + +#### Collector 原因 + +The following table describes all available collector reasons。 + +Reason | Description +:--- | :--- +`search_sorted` | A collector that scores and sorts documents。Present in most simple searches。 +`search_count` | A collector that counts the number of matching documents but does not fetch the source。Present when `size: 0` is specified。 +`search_terminate_after_count` | A collector that searches for matching documents and terminates the search when it finds a specified number of documents。Present when the `terminate_after_count` query parameter is specified。 +`search_min_score` | A collector that returns matching documents that have a score greater than a minimum score。Present when the `min_score` parameter is specified。 +`search_multi` | A wrapper collector for other collectors。Present when search, aggregations, global aggregations, and post filters are combined in a single search。 +`search_timeout` | A collector that stops running after a specified period of time。Present when a `timeout` parameter is specified。 +`aggregation` | A collector for aggregations that is run against the specified query scope。OpenSearch uses a single `aggregation` collector to collect documents for all aggregations。 +`global_aggregation` | A collector that is run against the global query scope。Global scope is different from a specified query scope, so in order to collect the entire dataset, a `match_all` query must be run。 + +### 聚合响应 + +The following examples show profiling responses for different aggregation types。 + +#### 响应:全局聚合 + +The response contains profiling information: + +<details markdown="block"> + <summary> + Response + </summary> + +```json +{ + "took": 10, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1370, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "all_products": { + "doc_count": 4675, + "avg_price": { + "value": 75。05542864304813 + } + }, + "elitelligence_products": { + "value": 68。4430200729927 + } + }, + "profile": { + "shards": [ + { + "id": "[LidyZ1HVS-u93-73Z49dQg][opensearch_dashboards_sample_data_ecommerce][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "ConstantScoreQuery", + "description": "ConstantScore(manufacturer:elitelligence)", + "time_in_nanos": 1367487, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 634321, + "match": 0, + "next_doc_count": 1370, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 173250, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 132458, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 427458 + }, + "children": [ + { + "type": "TermQuery", + "description": "manufacturer:elitelligence", + "time_in_nanos": 1174794, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 470918, + "match": 0, + "next_doc_count": 1370, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 172084, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 114041, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 417751 + } + } + ] + } + ], + "rewrite_time": 42542, + "collector": [ + { + "name": "MultiCollector", + "reason": "search_multi", + "time_in_nanos": 778406, + "children": [ + { + "name": "EarlyTerminatingCollector", + "reason": "search_count", + "time_in_nanos": 70290 + }, + { + "name": "ProfilingAggregator: [elitelligence_products]", + "reason": "aggregation", + "time_in_nanos": 502780 + } + ] + } + ] + }, + { + "query": [ + { + "type": "ConstantScoreQuery", + "description": "ConstantScore(*:*)", + "time_in_nanos": 995345, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 930803, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 2209, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 23875, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 38458 + }, + "children": [ + { + "type": "Match除了DocsQuery", + "description": "*:*", + "time_in_nanos": 431375, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 389875, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 1167, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 9458, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 30875 + } + } + ] + } + ], + "rewrite_time": 8792, + "collector": [ + { + "name": "ProfilingAggregator: [all_products]", + "reason": "aggregation_global", + "time_in_nanos": 1310536 + } + ] + } + ], + "aggregations": [ + { + "type": "AvgAggregator", + "description": "elitelligence_products", + "time_in_nanos": 319918, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 130709, + "build_aggregation": 2709, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 584, + "initialize": 4750, + "initialize_count": 1, + "reduce_count": 0, + "collect": 181166, + "collect_count": 1370 + } + }, + { + "type": "GlobalAggregator", + "description": "all_products", + "time_in_nanos": 1519340, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 134625, + "build_aggregation": 59291, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 5041, + "initialize": 24500, + "initialize_count": 1, + "reduce_count": 0, + "collect": 1295883, + "collect_count": 4675 + }, + "children": [ + { + "type": "AvgAggregator", + "description": "avg_price", + "time_in_nanos": 775967, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 98999, + "build_aggregation": 33083, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 2209, + "initialize": 1708, + "initialize_count": 1, + "reduce_count": 0, + "collect": 639968, + "collect_count": 4675 + } + } + ] + } + ] + } + ] + } +} +``` +</details> + +#### 响应:非全局聚合 + +The response contains profiling information: + +<details markdown="block"> + <summary> + Response + </summary> + +```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": { + "avg_taxful_total_price": { + "value": 75。05542864304813 + } + }, + "profile": { + "shards": [ + { + "id": "[LidyZ1HVS-u93-73Z49dQg][opensearch_dashboards_sample_data_ecommerce][0]", + "inbound_network_time_in_millis": 0, + "outbound_network_time_in_millis": 0, + "searches": [ + { + "query": [ + { + "type": "ConstantScoreQuery", + "description": "ConstantScore(*:*)", + "time_in_nanos": 1690820, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 1614112, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 2708, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 20250, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 53750 + }, + "children": [ + { + "type": "Match除了DocsQuery", + "description": "*:*", + "time_in_nanos": 770902, + "breakdown": { + "set_min_competitive_score_count": 0, + "match_count": 0, + "shallow_advance_count": 0, + "set_min_competitive_score": 0, + "next_doc": 721943, + "match": 0, + "next_doc_count": 4675, + "score_count": 0, + "compute_max_score_count": 0, + "compute_max_score": 0, + "advance": 1042, + "advance_count": 2, + "score": 0, + "build_scorer_count": 4, + "create_weight": 5041, + "shallow_advance": 0, + "create_weight_count": 1, + "build_scorer": 42876 + } + } + ] + } + ], + "rewrite_time": 22000, + "collector": [ + { + "name": "MultiCollector", + "reason": "search_multi", + "time_in_nanos": 3672676, + "children": [ + { + "name": "EarlyTerminatingCollector", + "reason": "search_count", + "time_in_nanos": 78626 + }, + { + "name": "ProfilingAggregator: [avg_taxful_total_price]", + "reason": "aggregation", + "time_in_nanos": 2834566 + } + ] + } + ] + } + ], + "aggregations": [ + { + "type": "AvgAggregator", + "description": "avg_taxful_total_price", + "time_in_nanos": 1973702, + "breakdown": { + "reduce": 0, + "post_collection_count": 1, + "build_leaf_collector": 199292, + "build_aggregation": 13584, + "build_aggregation_count": 1, + "build_leaf_collector_count": 2, + "post_collection": 6125, + "initialize": 6916, + "initialize_count": 1, + "reduce_count": 0, + "collect": 1747785, + "collect_count": 4675 + } + } + ] + } + ] + } +} +``` +</details> + +#### 响应正文字段 + +The `aggregations` array contains aggregation objects with the following fields。 + +Field | Data type | Description +:--- | :--- | :--- +`type` | String | 该aggregator type。In the [non-global aggregation example response](#response-non-global-aggregation), the aggregator type is `AvgAggregator`。[Global aggregation example response](#response-global-aggregation) contains a `GlobalAggregator` with an `AvgAggregator` child。 +`description` | String | Contains a Lucene explanation of the aggregation。Helps differentiate aggregations with the same type。 +`time_in_nanos` | Long | 该total elapsed time for this aggregation, in nanoseconds。For concurrent segment search, `time_in_nanos` is the total amount of time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +[`breakdown`](#the-breakdown-object-1) | Object | Contains timing statistics about low-level Lucene execution。 +`children` | Array of objects | If an aggregation has subaggregations (children), this field contains information about the subaggregations。 +`debug` | Object | Some aggregations return a `debug` object that describes the details of the underlying execution。 +`max_slice_time_in_nanos` |Long | 该maximum amount of time taken by any slice to run an aggregation, in nanoseconds。This field is included only if you enable concurrent segment search。 +`min_slice_time_in_nanos` |Long | 该minimum amount of time taken by any slice to run an aggregation, in nanoseconds。This field is included only if you enable concurrent segment search。 +`avg_slice_time_in_nanos` |Long | 该average amount of time taken by any slice to run an aggregation, in nanoseconds。This field is included only if you enable concurrent segment search。 + +#### `breakdown` 对象 + +The `breakdown` object represents the timing statistics about low-level Lucene execution, broken down by method。响应中的每个 field 指定为 `breakdown` object represents an internal Lucene method executed within the aggregation。Timings are listed in wall-clock nanoseconds 并在re not normalized。The `breakdown` timings are inclusive of all child times。The `breakdown` object is comprised of the following fields。除了 fields contain integer values。 + +Field | Description +:--- | :--- +`initialize` | Contains the amount of time taken to execute the `preCollection()` callback method during `AggregationCollectorManager` creation。For concurrent segment search, the `initialize` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`build_leaf_collector`| Contains the time spent running the aggregation's `getLeafCollector()` method, which creates a new collector to collect the given context。For concurrent segment search, the `build_leaf_collector` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`collect`| Contains the time spent collecting the documents into buckets。For concurrent segment search, the `collect` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`post_collection`| Contains the time spent running the aggregation’s `postCollection()` callback method。For concurrent segment search, the `post_collection` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`build_aggregation`| Contains the time spent running the aggregation’s `buildAggregations()` method, which builds the results of this aggregation。For concurrent segment search, the `build_aggregation` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`reduce`| Contains the time spent 指定为 `reduce` phase。For concurrent segment search, the `reduce` method contains the total elapsed time across all slices (the difference between the last completed slice execution end time and the first slice execution start time)。 +`<method>_count` | Contains the number of invocations of a `<method>`。For example, `build_leaf_collector_count` contains the number of invocations of the `build_leaf_collector` method。 +`max_<method>` | 该maximum amount of time taken by any slice to run an aggregation method。This field is included only if you enable concurrent segment search。 +`min_<method>`| 该minimum amount of time taken by any slice to run an aggregation method。This field is included only if you enable concurrent segment search。 +`avg_<method>` | 该average amount of time taken by any slice to run an aggregation method。This field is included only if you enable concurrent segment search。 +`<method>_count` | 该total method count across all slices。For example, for the `collect` method, it is the total number of invocations of this method needed to collect documents into buckets across all slices。 +`max_<method>_count` | 该maximum number of invocations of a `<method>` on any slice。This field is included only if you enable concurrent segment search。 +`min_<method>_count` | 该minimum number of invocations of a `<method>` on any slice。This field is included only if you enable concurrent segment search。 +`avg_<method>_count` | 该average number of invocations of a `<method>` on any slice。This field is included only if you enable concurrent segment search。 diff --git a/i18n/zh/api-reference/search-apis/rank-eval.md b/i18n/zh/api-reference/search-apis/rank-eval.md new file mode 100644 index 00000000..5b43b3a5 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/rank-eval.md @@ -0,0 +1,219 @@ +--- +title: Ranking evaluation +--- + +# Ranking Evaluation API +<Badge type="tip" text="引入版本 1.0" /> + +Rank Evaluation API 评估排名搜索结果的质量。 + +## 端点 + +```json +GET {index_name}/_rank_eval +POST {index_name}/_rank_eval +``` + +## 查询参数 + +查询参数是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`ignore_unavailable` | Boolean | 默认为 `false`。当设置为 `false` 时,如果索引关闭或缺失,响应正文将返回错误。 +`allow_no_indices` | Boolean | 默认为 `true`。当设置为 `false` 时,如果通配符表达式指向关闭或缺失的索引,响应正文将返回错误。 +`expand_wildcards` | String | 将通配符表达式扩展为 `open`、`closed`、`hidden`、`none` 或 `all` 的索引。 +`search_type` | String | 将搜索类型设置为 `query_then_fetch` 或 `dfs_query_then_fetch`。 + +## 请求正文字段 + +请求正文必须至少包含一个参数。 + +字段类型 | 描述 +:--- | :--- +`id` | 文档或模板 ID。 +`requests` | 在请求字段部分内设置多个搜索请求。 +`ratings` | 文档相关性分数。 +k | 每个查询返回的文档数。默认设置为 10。 +`relevant_rating_threshold` | 文档被视为相关的阈值。默认设置为 1。 +`normalize` | 当设置为 `true` 时将计算折扣累积增益。 +`maximum_relevance` | 使用预期倒数排名指标时设置最大相关性分数。 +`ignore_unlabeled` | 默认为 `false`。当设置为 `true` 时忽略未标记的文档。 +`template_id` | 模板 ID。 +`params` | 模板中使用的参数。 + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_rank_eval +body: | +{ + "requests": [ + { + "id": "books_query", + "request": { + "query": { "match": { "text": "thou" } } + }, + "ratings": [ + { "_index": "shakespeare", "_id": "80", "rating": 0 }, + { "_index": "shakespeare", "_id": "115", "rating": 1 }, + { "_index": "shakespeare", "_id": "117", "rating": 2 } + ] + }, + { + "id": "words_query", + "request": { + "query": { "match": { "text": "art" } } + }, + "ratings": [ + { "_index": "shakespeare", "_id": "115", "rating": 2 } + ] + } + ] +} +--> + +GET /shakespeare/_rank_eval +{ + "requests": [ + { + "id": "books_query", + "request": { + "query": { + "match": { + "text": "thou" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "80", + "rating": 0 + }, + { + "_index": "shakespeare", + "_id": "115", + "rating": 1 + }, + { + "_index": "shakespeare", + "_id": "117", + "rating": 2 + } + ] + }, + { + "id": "words_query", + "request": { + "query": { + "match": { + "text": "art" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "115", + "rating": 2 + } + ] + } + ] +} + +response = client.rank_eval( + index = "shakespeare", + body = { + "requests": [ + { + "id": "books_query", + "request": { + "query": { + "match": { + "text": "thou" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "80", + "rating": 0 + }, + { + "_index": "shakespeare", + "_id": "115", + "rating": 1 + }, + { + "_index": "shakespeare", + "_id": "117", + "rating": 2 + } + ] + }, + { + "id": "words_query", + "request": { + "query": { + "match": { + "text": "art" + } + } + }, + "ratings": [ + { + "_index": "shakespeare", + "_id": "115", + "rating": 2 + } + ] + } + ] + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +````json +{ + "rank_eval": { + "metric_score": 0.7, + "details": { + "query_1": { + "metric_score": 0.9, + "unrated_docs": [ + { + "_index": "shakespeare", + "_id": "1234567" + }, ... + ], + "hits": [ + { + "hit": { + "_index": "shakespeare", + "_type": "page", + "_id": "1234567", + "_score": 5.123456789 + }, + "rating": 1 + }, ... + ], + "metric_details": { + "precision": { + "relevant_docs_retrieved": 3, + "docs_retrieved": 6 + } + } + }, + "query_2": { [... ] } + }, + "failures": { [... ] } + } +} +```` diff --git a/i18n/zh/api-reference/search-apis/scroll.md b/i18n/zh/api-reference/search-apis/scroll.md new file mode 100644 index 00000000..7608ca3b --- /dev/null +++ b/i18n/zh/api-reference/search-apis/scroll.md @@ -0,0 +1,284 @@ +--- +title: 滚动查询 +--- + +# 滚动查询 API +<Badge type="tip" text="引入版本 1.0" /> + +您可以使用 `scroll` 操作检索大量结果。例如,对于机器学习作业,您可以批量请求无限数量的结果。 + +要使用 `scroll` 操作,请在请求头中添加 `scroll` 参数和搜索上下文,以告知 OpenSearch 您需要保持滚动多长时间。此搜索上下文需要足够长,以便处理单个批次的结果。 + +::: info NOTE +由于搜索上下文会消耗大量内存,我们建议您不要对频繁的用户查询使用 `scroll` 操作。相反,对用户查询使用 `sort` 参数配合 `search_after` 参数来滚动响应。 +::: + +请注意以下性能考虑因素: + +- 对于最高效的滚动,当您不需要相关性评分时,请按 `_doc` 排序。这会禁用评分,并按其自然索引顺序返回文档,这是遍历索引中所有文档的最快方式。 +- 只有初始搜索响应包含聚合结果。后续滚动请求只返回下一批命中结果。 +- 每个打开的滚动上下文会阻止关联分片上的段合并,并消耗文件句柄和堆内存。请在不再需要时立即关闭滚动上下文。 +- 打开滚动上下文的最大数量由 `search.max_open_scroll_context` 集群设置控制,默认为 500。 + +<!-- spec_insert_start +api: scroll +component: endpoints +--> +## 端点 +```json +GET /_search/scroll +POST /_search/scroll +GET /_search/scroll/{scroll_id} +POST /_search/scroll/{scroll_id} +``` +<!-- spec_insert_end --> + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `scroll_id` | 字符串 | 搜索的滚动 ID。我们建议在请求体中指定滚动 ID,而不是作为路径参数,因为滚动 ID 可能非常长。| + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `scroll` | 字符串 | 延长搜索上下文的时间量。此值覆盖原始搜索请求的 `scroll` 参数中设置的持续时间。不能超过 `search.max_keep_alive` 集群设置。| 无 | +| `scroll_id` | 字符串 | 搜索的滚动 ID。我们建议在请求体中指定滚动 ID,而不是作为查询参数,因为滚动 ID 可能非常长。| 无 | +| `rest_total_hits_as_int` | 布尔值 | `hits.total` 属性是作为整数 (`true`) 还是对象 (`false`) 返回。| `false` | + +## 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `scroll` | 字符串 | 为下一个滚动请求延长搜索上下文的时间量。如果同时指定了查询参数和请求体字段,则查询参数优先。| +| `scroll_id` | 字符串 | 必需。初始搜索请求或上一个滚动请求返回的滚动 ID。| + +## 示例请求 + +以下示例演示了从启动滚动操作到检索所有结果的滚动工作流程。 + +### 步骤 1:启动滚动操作 + +要开始滚动,请发送一个包含 `scroll` 参数的初始搜索查询,该参数指定保持搜索上下文活动的时间(例如,`10m` 表示 10 分钟)。使用 `size` 参数设置每批返回的结果数量: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search?scroll=10m +body: | +{ + "size": 10000 +} +--> + +GET /shakespeare/_search?scroll=10m +{ + "size": 10000 +} + +response = client.search( + index = "shakespeare", + params = { "scroll": "10m" }, + body = { + "size": 10000 + } +) + +<!-- spec_insert_end --> + +OpenSearch 缓存结果并返回一个滚动 ID 以批量访问它们: + +```json +"_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +``` + +### 步骤 2:检索后续批次 + +将此滚动 ID 传递给 `scroll` 操作以获取下一批结果: + +<!-- spec_insert_start +component: example_code +rest: GET /_search/scroll +body: | +{ + "scroll": "10m", + "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +} +--> + +GET /_search/scroll +{ + "scroll": "10m", + "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +} + +response = client.scroll( + body = { + "scroll": "10m", + "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" + } +) + +<!-- spec_insert_end --> + +使用此滚动 ID,只要搜索上下文仍处于打开状态,您就可以以 10,000 的批次获取结果。通常,滚动 ID 在请求之间不会改变,但它*可能*会改变,因此请确保始终使用最新的滚动 ID。如果您没有在设置的搜索上下文内发送下一个滚动请求,则 `scroll` 操作不会返回任何结果。 + +### 检测结果结束 + +当您滚动完所有结果后,最后一批包含一个空的 `hits` 数组: + +```json +{ + "_scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAUWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==", + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } +} +``` + +当 `hits.hits` 是一个空数组时,表示您已检索到所有可用结果,应该停止滚动。请确保关闭滚动上下文以释放资源。 + +### 使用切片滚动 + +如果您预期有数十亿的结果,请使用切片滚动。切片允许您对同一请求执行多个滚动操作,但是并行执行。 +设置滚动的 ID 和最大切片数: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search?scroll=10m +body: | +{ + "slice": { + "id": 0, + "max": 10 + }, + "query": { + "match_all": {} + } +} +--> + +GET /shakespeare/_search?scroll=10m +{ + "slice": { + "id": 0, + "max": 10 + }, + "query": { + "match_all": {} + } +} + +response = client.search( + index = "shakespeare", + params = { "scroll": "10m" }, + body = { + "slice": { + "id": 0, + "max": 10 + }, + "query": { + "match_all": {} + } + } +) + +<!-- spec_insert_end --> + +每个切片产生自己独立的滚动 ID。使用 `"max": 10`,您可以启动 10 个独立的滚动操作(ID 0 到 9),每个返回数据的不同子集。然后您独立地滚动每个切片,直到所有切片都耗尽。切片数量受 `index.max_slices_per_scroll` 设置限制,默认为 `1024`。 + +### 步骤 3:关闭滚动上下文 + +完成滚动后关闭搜索上下文,因为 `scroll` 操作会继续消耗计算资源直到超时: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_search/scroll/DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ== +--> + +DELETE /_search/scroll/DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ== + +response = client.clear_scroll( + scroll_id = "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAAcWdmpUZDhnRFBUcWFtV21nMmFwUGJEQQ==" +) + +<!-- spec_insert_end --> + +要关闭所有打开的滚动上下文: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_search/scroll/_all +--> + +DELETE /_search/scroll/_all + +response = client.clear_scroll( + scroll_id = "_all" +) + +<!-- spec_insert_end --> + +::: warning IMPORTANT +滚动搜索的结果反映了初始搜索请求时索引的状态。在滚动启动后索引或修改的文档不会出现在滚动结果中,即使它们匹配查询。 +::: + +## 示例响应 + +滚动操作返回与搜索 API 相同的响应结构,包括 `_scroll_id`、`hits`、`_shards` 和时间信息。 + +清除滚动操作返回以下响应: + +```json +{ + "succeeded": true, + "num_freed": 1 +} +``` + +## 响应体字段 + +下表列出了滚动操作的响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_scroll_id` | 字符串 | 用于下一个滚动请求的滚动 ID。此值可能在请求之间改变,因此请始终使用最新返回的 ID。| +| `took` | 整数 | 请求完成所需的时间(以毫秒为单位)。| +| `timed_out` | 布尔值 | 请求在完成之前是否超时。| +| `_shards` | 对象 | 有关涉及的分片的信息,包括 `total`、`successful`、`skipped` 和 `failed` 计数。| +| `hits` | 对象 | 搜索结果,包括 `total` 命中计数和匹配文档数组。滚动完成时,`hits.hits` 是一个空数组。| + +下表列出了清除滚动操作的响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `succeeded` | 布尔值 | 滚动上下文是否成功释放。| +| `num_freed` | 整数 | 释放的滚动上下文数量。| + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:data/read/scroll` 和 `indices:data/read/scroll/clear`。 + +## 相关文档 + +- [分页结果](/search-plugins/searching-data/paginate) +- [时间点 API](/search-plugins/searching-data/point-in-time-api) diff --git a/i18n/zh/api-reference/search-apis/search-shards.md b/i18n/zh/api-reference/search-apis/search-shards.md new file mode 100644 index 00000000..4f9669b2 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/search-shards.md @@ -0,0 +1,232 @@ +--- +title: 搜索分片 +--- + +# 搜索分片 API +<Badge type="tip" text="引入版本 1.0" /> + +`_search_shards` API 提供有关如果执行搜索请求时 OpenSearch 会将其路由到哪些分片的信息。这有助于您了解 OpenSearch 如何计划在分片之间分配查询,而无需实际运行搜索。此 API 不执行搜索,但允许您检查路由决策、分片分布以及将处理请求的节点。 + +## 端点 + +```json +GET /_search_shards +GET /{index}/_search_shards +POST /_search_shards +POST /{index}/_search_shards +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| --------- | ------ | ------------------------------------------------------ | +| `<index>` | 字符串 | 目标索引名称的逗号分隔列表。| + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| `allow_no_indices` | 布尔值 | 如果为 `true`,当通配符表达式或索引别名解析为没有具体索引时,请求不会失败。默认为 `true`。| +| `expand_wildcards` | 字符串 | 控制如何扩展通配符表达式。选项包括:`open`(默认)、`closed`、`hidden`、`none` 或 `all`。| +| `ignore_unavailable` | 布尔值 | 如果为 `true`,则忽略缺失或关闭的索引。默认为 `false`。| +| `local` | 布尔值 | 如果为 `true`,则操作仅在本地节点上执行,而不从集群管理节点检索状态。默认为 `false`。| +| `preference` | 字符串 | 在选择要定位的分片或节点时指定首选项。有关更多信息,请参阅 [`preference` 查询参数](/api-reference/search-apis/search#the-preference-query-parameter)。| +| `routing` | 字符串 | 用于分片选择的特定路由值的逗号分隔列表。| + +## 请求体字段 + +请求体可以包含完整的搜索查询以模拟请求将如何路由: + +```json +{ + "query": { + "term": { + "user": "alice" + } + } +} +``` + +## 示例 + +创建索引: + +```json +PUT /logs-demo +{ + "settings": { + "number_of_shards": 3, + "number_of_replicas": 0 + }, + "mappings": { + "properties": { + "user": { "type": "keyword" }, + "message": { "type": "text" }, + "@timestamp": { "type": "date" } + } + } +} +``` + +使用 `routing=user1` 索引第一个文档: + +<!-- spec_insert_start +component: example_code +rest: POST /logs-demo/_doc?routing=user1 +body: | +{ + "@timestamp": "2025-05-23T10:00:00Z", + "user": "user1", + "message": "User login successful" +} +--> + +POST /logs-demo/_doc?routing=user1 +{ + "@timestamp": "2025-05-23T10:00:00Z", + "user": "user1", + "message": "User login successful" +} + +response = client.index( + index = "logs-demo", + params = { "routing": "user1" }, + body = { + "@timestamp": "2025-05-23T10:00:00Z", + "user": "user1", + "message": "User login successful" + } +) + +<!-- spec_insert_end --> + +使用 `routing=user2` 索引第二个文档: + +<!-- spec_insert_start +component: example_code +rest: POST /logs-demo/_doc?routing=user2 +body: | +{ + "@timestamp": "2025-05-23T10:01:00Z", + "user": "user2", + "message": "User login failed" +} +--> + +POST /logs-demo/_doc?routing=user2 +{ + "@timestamp": "2025-05-23T10:01:00Z", + "user": "user2", + "message": "User login failed" +} + +response = client.index( + index = "logs-demo", + params = { "routing": "user2" }, + body = { + "@timestamp": "2025-05-23T10:01:00Z", + "user": "user2", + "message": "User login failed" + } +) + +<!-- spec_insert_end --> + +### 示例请求 + +使用 `_search_shards` 模拟路由: + +<!-- spec_insert_start +component: example_code +rest: POST /logs-demo/_search_shards?routing=user1 +body: | +{ + "query": { + "term": { + "user": "user1" + } + } +} +--> + +POST /logs-demo/_search_shards?routing=user1 +{ + "query": { + "term": { + "user": "user1" + } + } +} + +response = client.search_shards( + index = "logs-demo", + params = { "routing": "user1" }, + body = { + "query": { + "term": { + "user": "user1" + } + } + } +) + +<!-- spec_insert_end --> + +### 示例响应 + +响应显示如果执行搜索将搜索的节点和分片: + +```json +{ + "nodes": { + "12ljrWLsQyiWHLzhFZgL9Q": { + "name": "opensearch-node3", + "ephemeral_id": "-JPvYKPMSGubd0VmSEzlbw", + "transport_address": "172.18.0.4:9300", + "attributes": { + "shard_indexing_pressure_enabled": "true" + } + } + }, + "indices": { + "logs-demo": {} + }, + "shards": [ + [ + { + "state": "STARTED", + "primary": true, + "node": "12ljrWLsQyiWHLzhFZgL9Q", + "relocating_node": null, + "shard": 1, + "index": "logs-demo", + "allocation_id": { + "id": "HwEjTdYQQJuULdQn10FRBw" + } + } + ] + ] +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| `nodes` | 对象 | 包含节点 ID 到节点元数据的映射,例如名称和传输地址。| +| `indices` | 对象 | 包含请求中包含的索引名称的映射。| +| `shards` | 数组的数组 | 表示请求的分片副本(主分片/副本分片)的嵌套数组。| +| `shards.index` | 字符串 | 索引名称。| +| `shards.shard` | 整数 | 分片编号。| +| `shards.node` | 字符串 | 包含此分片的节点的节点 ID。| +| `shards.primary` | 布尔值 | 这是否是主分片。| +| `shards.state` | 字符串 | 当前分片状态。| +| `shards.allocation_id.id` | 字符串 | 此分片分配的唯一 ID。| + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/shards/search_shards`。 diff --git a/i18n/zh/api-reference/search-apis/search-template/index.md b/i18n/zh/api-reference/search-apis/search-template/index.md new file mode 100644 index 00000000..1dbd643c --- /dev/null +++ b/i18n/zh/api-reference/search-apis/search-template/index.md @@ -0,0 +1,896 @@ +--- +title: 搜索模板 +--- + +# 搜索模板 API + +您可以将全文查询转换为搜索模板,以接受用户输入并动态将其插入到查询中。 + +例如,如果您将 OpenSearch 用作应用程序或网站的后端搜索引擎,您可以从搜索栏或表单字段接受用户查询,并将它们作为参数传递到搜索模板中。这样,创建 OpenSearch 查询的语法就从您的最终用户中抽象出来了。 + +当您编写代码将用户输入转换为 OpenSearch 查询时,可以使用搜索模板简化代码。如果您需要向搜索查询添加字段,可以修改模板而无需更改代码。 + +::: info NOTE +搜索模板使用 Mustache 语言。有关所有语法选项的列表,请参阅 [Mustache 手册](https://mustache.github.io/mustache.5.html)。 +::: + +## 查询参数 + +`_search/template` 端点接受与搜索 API 相同的查询参数,包括 `typed_keys` 和 `rest_total_hits_as_int`。有关更多信息,请参阅[搜索 API](/api-reference/search-apis/search)。 + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`id` | 字符串 | 要运行的已存储搜索模板的 ID。如果未指定 `source`,则为必需。 +`source` | 对象或字符串 | 内联搜索模板。如果模板包含使 JSON 无效的 Mustache 标签,则将模板指定为字符串。如果未指定 `id`,则为必需。 +`params` | 对象 | 替换模板中变量的值。 +`explain` | 布尔值 | 是否返回有关每个命中得分如何计算的详细信息。默认为 `false`。 +`profile` | 布尔值 | 是否返回有关查询执行的时间信息。默认为 `false`。 +`search_pipeline` | 字符串 | 要应用于搜索请求的搜索管道的名称。 + +## 创建搜索模板 + +搜索模板有两个组件:查询和参数。参数是用户输入的值,这些值被放入变量中。变量在 Mustache 表示法中用双大括号表示。当在查询中遇到像 `{{var}}` 这样的变量时,OpenSearch 会转到 `params` 部分,查找名为 `var` 的参数,并用指定的值替换它。 + +您可以编写应用程序代码来询问用户想要搜索什么,然后在运行时将该值插入到 `params` 对象中。 + +此页面上的示例使用 `shakespeare` 索引。要尝试它们,首先创建索引: + +```json +PUT /shakespeare +{ + "mappings": { + "properties": { + "line_id": { "type": "integer" }, + "play_name": { "type": "keyword" }, + "speech_number": { "type": "integer" }, + "speaker": { "type": "keyword" }, + "text_entry": { "type": "text" } + } + } +} +``` + +然后将戏剧中的一些台词添加到索引中: + +```json +POST /_bulk +{ "index": { "_index": "shakespeare", "_id": "1" } } +{ "line_id": 1, "play_name": "Henry IV", "speech_number": 1, "speaker": "KING HENRY IV", "text_entry": "So shaken as we are, so wan with care," } +{ "index": { "_index": "shakespeare", "_id": "2" } } +{ "line_id": 2, "play_name": "Henry IV", "speech_number": 1, "speaker": "KING HENRY IV", "text_entry": "Find we a time for frighted peace to pant," } +{ "index": { "_index": "shakespeare", "_id": "3" } } +{ "line_id": 3, "play_name": "Henry IV", "speech_number": 1, "speaker": "KING HENRY IV", "text_entry": "And breathe short-winded accents of new broils" } +{ "index": { "_index": "shakespeare", "_id": "4" } } +{ "line_id": 4, "play_name": "Othello", "speech_number": 1, "speaker": "IAGO", "text_entry": "I am not what I am." } +{ "index": { "_index": "shakespeare", "_id": "5" } } +{ "line_id": 5, "play_name": "Hamlet", "speech_number": 1, "speaker": "HAMLET", "text_entry": "To be, or not to be: that is the question:" } +{ "index": { "_index": "shakespeare", "_id": "6" } } +{ "line_id": 6, "play_name": "Romeo and Juliet", "speech_number": 1, "speaker": "ROMEO", "text_entry": "Did my heart love till now? forswear it, sight!" } +{ "index": { "_index": "shakespeare", "_id": "7" } } +{ "line_id": 7, "play_name": "As You Like It", "speech_number": 1, "speaker": "JAQUES", "text_entry": "Then a soldier, full of strange oaths," } +``` + +此命令定义了一个搜索模板,通过剧本名称查找剧本。查询中的 `{{play_name}}` 被值 `Henry IV` 替换: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search/template +body: | +{ + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +--> + +GET /shakespeare/_search/template +{ + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} + +response = client.search_template( + index = "shakespeare", + body = { + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } + } +) + +<!-- spec_insert_end --> + +此模板在 `shakespeare` 索引上运行搜索。要在集群中的所有索引上运行搜索,请从请求中省略索引名称: + +<!-- spec_insert_start +component: example_code +rest: GET /_search/template +body: | +{ + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +--> + +GET /_search/template +{ + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} + +response = client.search_template( + body = { + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } + } +) + +<!-- spec_insert_end --> + +指定 `from` 和 `size` 参数: + +<!-- spec_insert_start +component: example_code +rest: GET /_search/template +body: | +{ + "source": { + "from": "{{from}}", + "size": "{{size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV", + "from": 10, + "size": 10 + } +} +--> + +GET /_search/template +{ + "source": { + "from": "{{from}}", + "size": "{{size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV", + "from": 10, + "size": 10 + } +} + +response = client.search_template( + body = { + "source": { + "from": "{{from}}", + "size": "{{size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV", + "from": 10, + "size": 10 + } + } +) + +<!-- spec_insert_end --> + +为了改善搜索体验,您可以定义默认值,这样用户就不必指定每个可能的参数。如果参数未在 `params` 部分定义,OpenSearch 使用默认值。 + +为变量 `var` 定义默认值的语法如下: + +``` +{{var}}{{^var}}default value{{/var}} +``` + +此命令将 `from` 的默认值设置为 10,`size` 的默认值设置为 10: + +<!-- spec_insert_start +component: example_code +rest: GET /_search/template +body: | +{ + "source": { + "from": "{{from}}{{^from}}10{{/from}}", + "size": "{{size}}{{^size}}10{{/size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +--> + +GET /_search/template +{ + "source": { + "from": "{{from}}{{^from}}10{{/from}}", + "size": "{{size}}{{^size}}10{{/size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} + +response = client.search_template( + body = { + "source": { + "from": "{{from}}{{^from}}10{{/from}}", + "size": "{{size}}{{^size}}10{{/size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } + } +) + +<!-- spec_insert_end --> + +## 保存和执行搜索模板 + +在搜索模板按您想要的方式工作后,您可以将该模板的源保存为脚本,使其可用于不同的输入参数。 + +将搜索模板保存为脚本时,您需要将 `lang` 参数指定为 `mustache`: + +```json +POST _scripts/play_search_template +{ + "script": { + "lang": "mustache", + "source": { + "from": "{{from}}{{^from}}0{{/from}}", + "size": "{{size}}{{^size}}10{{/size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + } + } +} +``` + +存储的脚本不保留默认参数值。如果在保存脚本时包含 `params` 对象,OpenSearch 会丢弃它。要在存储的模板中设置默认值,请在模板源中使用 `{{var}}{{^var}}default value{{/var}}` 语法,如前面请求中的 `from` 和 `size` 所示。 + +现在您可以通过引用其 `id` 参数来重用模板。您可以为不同的输入值重用此源模板: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search/template +body: | +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV", + "from": 0, + "size": 1 + } +} +--> + +GET /shakespeare/_search/template +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV", + "from": 0, + "size": 1 + } +} + +response = client.search_template( + index = "shakespeare", + body = { + "id": "play_search_template", + "params": { + "play_name": "Henry IV", + "from": 0, + "size": 1 + } + } +) + +<!-- spec_insert_end --> + +响应包含第一个匹配的文档: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "shakespeare", + "_id": "1", + "_score": 1.0, + "_source": { + "line_id": 1, + "play_name": "Henry IV", + "speech_number": 1, + "speaker": "KING HENRY IV", + "text_entry": "So shaken as we are, so wan with care," + } + } + ] + }, + "status": 200 +} +``` + +如果您有存储的模板并想要验证它,请使用 `render` 操作: + +<!-- spec_insert_start +component: example_code +rest: POST /_render/template +body: | +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } +} +--> + +POST /_render/template +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } +} + +response = client.render_search_template( + body = { + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } + } +) + +<!-- spec_insert_end --> + +有关更多信息,请参阅[渲染模板 API](/api-reference/search-apis/search-template/render-template)。 + +## 使用搜索模板进行高级参数转换 + +Mustache 中有许多不同的语法选项可将输入参数转换为查询。 +您可以指定条件、运行循环、连接数组、将数组转换为 JSON 等。 + +### 条件 + +在 Mustache 中使用节标签表示条件: + +```json +{{#var}}var{{/var}} +``` + +当 `var` 是布尔值时,此语法充当 `if` 条件。`{{#var}}` 和 `{{/var}}` 标签仅在 `var` 计算为 `true` 时插入它们之间放置的值。 + +使用节标签会使您的 JSON 无效,因此您必须以字符串格式编写查询。 + +此命令仅在 `limit` 参数设置为 `true` 时才在查询中包含 `size` 参数。 +在以下示例中,`limit` 参数为 `true`,因此渲染的查询包括 `size` 设置为 `2`: + +<!-- spec_insert_start +component: example_code +rest: POST /_render/template +body: | +{ + "source": "{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}", + "params": { + "play_name": "Henry IV", + "limit": true, + "size": 2 + } +} +--> + +POST /_render/template +{ + "source": "{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}", + "params": { + "play_name": "Henry IV", + "limit": true, + "size": 2 + } +} + +response = client.render_search_template( + body = { + "source": "{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}", + "params": { + "play_name": "Henry IV", + "limit": true, + "size": 2 + } + } +) + +<!-- spec_insert_end --> + +您还可以设计 `if-else` 条件。如果 `limit` 为 `true`,此命令将 `size` 设置为 `2`。否则,它将 `size` 设置为 `10`: + +<!-- spec_insert_start +component: example_code +rest: GET /_search/template +body: | +{ + "source": "{ {{#limit}} \"size\": \"2\", {{/limit}} {{^limit}} \"size\": \"10\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}", + "params": { + "play_name": "Henry IV", + "limit": true + } +} +--> + +GET /_search/template +{ + "source": "{ {{#limit}} \"size\": \"2\", {{/limit}} {{^limit}} \"size\": \"10\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}", + "params": { + "play_name": "Henry IV", + "limit": true + } +} + +response = client.search_template( + body = { + "source": "{ {{#limit}} \"size\": \"2\", {{/limit}} {{^limit}} \"size\": \"10\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}", + "params": { + "play_name": "Henry IV", + "limit": true + } + } +) + +<!-- spec_insert_end --> + +### 循环 + +您还可以使用节标签实现 for-each 循环: + +``` +{{#var}}{{.}}{{/var}} +``` + +当 `var` 是数组时,标签之间的内容对每个数组元素重复,`{{.}}` 引用当前元素。写入每个元素后跟逗号的循环会在最后一个元素后留下尾随逗号,这使查询成为无效的 JSON。要将值数组传递给 `terms` 查询,请使用 `toJson` 标签,它将数组转换为 JSON 数组: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search/template +body: | +{ + "source": "{\"query\":{\"terms\":{\"play_name\":{{#toJson}}play_name{{/toJson}}}}}", + "params": { + "play_name": [ + "Henry IV", + "Othello" + ] + } +} +--> + +GET /shakespeare/_search/template +{ + "source": "{\"query\":{\"terms\":{\"play_name\":{{#toJson}}play_name{{/toJson}}}}}", + "params": { + "play_name": [ + "Henry IV", + "Othello" + ] + } +} + +response = client.search_template( + index = "shakespeare", + body = { + "source": "{\"query\":{\"terms\":{\"play_name\":{{#toJson}}play_name{{/toJson}}}}}", + "params": { + "play_name": [ + "Henry IV", + "Othello" + ] + } + } +) + +<!-- spec_insert_end --> + +当您将此模板发送到[渲染模板 API](/api-reference/search-apis/search-template/render-template) 时,响应包含以下查询: + +```json +{ + "template_output": { + "query": { + "terms": { + "play_name": [ + "Henry IV", + "Othello" + ] + } + } + } +} +``` + +### Join + +使用 `join` 标签连接数组的值。默认情况下,值用逗号分隔,没有空格: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search/template +body: | +{ + "source": { + "query": { + "match": { + "text_entry": "{{#join}}text_entry{{/join}}" + } + } + }, + "params": { + "text_entry": [ + "To be", + "or not to be" + ] + } +} +--> + +GET /shakespeare/_search/template +{ + "source": { + "query": { + "match": { + "text_entry": "{{#join}}text_entry{{/join}}" + } + } + }, + "params": { + "text_entry": [ + "To be", + "or not to be" + ] + } +} + +response = client.search_template( + index = "shakespeare", + body = { + "source": { + "query": { + "match": { + "text_entry": "{{#join}}text_entry{{/join}}" + } + } + }, + "params": { + "text_entry": [ + "To be", + "or not to be" + ] + } + } +) + +<!-- spec_insert_end --> + +模板渲染以下查询: + +```json +{ + "template_output": { + "query": { + "match": { + "text_entry": "To be,or not to be" + } + } + } +} +``` + +要使用不同的分隔符,请在开始和结束标签中指定它。以下标签用空格分隔值并渲染 `To be or not to be`: + +``` +{{#join delimiter=' '}}text_entry{{/join delimiter=' '}} +``` + +### 转换为 JSON + +使用 `toJson` 标签将参数转换为其 JSON 表示形式。以下请求将 `match` 查询数组作为 `bool` 查询的 `should` 子句传递: + +<!-- spec_insert_start +component: example_code +rest: GET /shakespeare/_search/template +body: | +{ + "source": "{\"query\":{\"bool\":{\"should\":{{#toJson}}clauses{{/toJson}}}}}", + "params": { + "clauses": [ + { "match": { "text_entry": "love" } }, + { "match": { "text_entry": "soldier" } } + ] + } +} +--> + +GET /shakespeare/_search/template +{ + "source": "{\"query\":{\"bool\":{\"should\":{{#toJson}}clauses{{/toJson}}}}}", + "params": { + "clauses": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text_entry": "soldier" + } + } + ] + } +} + +response = client.search_template( + index = "shakespeare", + body = { + "source": "{\"query\":{\"bool\":{\"should\":{{#toJson}}clauses{{/toJson}}}}}", + "params": { + "clauses": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text_entry": "soldier" + } + } + ] + } + } +) + +<!-- spec_insert_end --> + +模板渲染以下查询: + +```json +{ + "template_output": { + "query": { + "bool": { + "should": [ + { + "match": { + "text_entry": "love" + } + }, + { + "match": { + "text_entry": "soldier" + } + } + ] + } + } + } +} +``` + +### URL 编码 + +使用 `url` 标签对标签之间的内容进行 URL 编码。当模板从用户输入构建 URL 时这很有用: + +```json +POST /_render/template +{ + "source": { + "query": { + "term": { + "source_url": "https://example.com/plays?name={{#url}}{{play_name}}{{/url}}" + } + } + }, + "params": { + "play_name": "Romeo and Juliet" + } +} +``` + +模板渲染以下查询: + +```json +{ + "template_output": { + "query": { + "term": { + "source_url": "https://example.com/plays?name=Romeo+and+Juliet" + } + } + } +} +``` + +## 多个搜索模板 + +您可以将多个搜索模板捆绑在一起,并使用 `msearch` 操作在单个请求中将它们发送到 OpenSearch 集群。 +这节省了网络往返时间,因此与独立请求相比,您可以更快地获得响应。 + +以下示例运行两个存储的模板。首先,将[条件](#conditions)部分中的条件模板存储为 `if_search_template`: + +```json +POST _scripts/if_search_template +{ + "script": { + "lang": "mustache", + "source": "{ {{#limit}} \"size\": \"{{size}}\", {{/limit}} \"query\":{\"match\":{\"play_name\": \"{{play_name}}\"}}}" + } +} +``` + +然后在单个请求中运行 `if_search_template` 和 `play_search_template`: + +```json +GET _msearch/template +{"index":"shakespeare"} +{"id":"if_search_template","params":{"play_name":"Henry IV","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} +``` + +有关更多信息,请参阅[多搜索模板 API](/api-reference/search-apis/search-template/msearch-template)。 + +## 管理搜索模板 + +要列出所有脚本,请运行以下命令: + +<!-- spec_insert_start +component: example_code +rest: GET /_cluster/state/metadata?pretty&filter_path=**.stored_scripts +--> + +GET /_cluster/state/metadata?pretty&filter_path=**.stored_scripts + +response = client.cluster.state( + metric = "metadata", + params = { "pretty": "true", "filter_path": "**.stored_scripts" } +) + +<!-- spec_insert_end --> + +要检索特定的搜索模板,请运行以下命令: + +<!-- spec_insert_start +component: example_code +rest: GET /_scripts/<name_of_search_template> +--> + +GET /_scripts/<name_of_search_template> + +response = client.get_script( + id = "<name_of_search_template>" +) + +<!-- spec_insert_end --> + +要删除搜索模板,请运行以下命令: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_scripts/<name_of_search_template> +--> + +DELETE /_scripts/<name_of_search_template> + +response = client.delete_script( + id = "<name_of_search_template>" +) + +<!-- spec_insert_end --> + +## 搜索模板 API 操作 + +以下搜索模板 API 操作可用: + +- [多搜索模板](/api-reference/search-apis/search-template/msearch-template) +- [渲染模板](/api-reference/search-apis/search-template/render-template) + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:data/read/search/template`。 diff --git a/i18n/zh/api-reference/search-apis/search-template/msearch-template.md b/i18n/zh/api-reference/search-apis/search-template/msearch-template.md new file mode 100644 index 00000000..638c4fbe --- /dev/null +++ b/i18n/zh/api-reference/search-apis/search-template/msearch-template.md @@ -0,0 +1,147 @@ +--- +title: 多搜索模板 +--- + +# 多搜索模板 API + +<Badge type="tip" text="引入版本 1.0" /> + +多搜索模板 API 在单个 API 请求中运行多个搜索模板请求。 + +## 端点 + +多搜索模板 API 使用以下路径: + +```json +GET /_msearch/template +POST /_msearch/template +GET /{index}/_msearch/template +POST /{index}/_msearch/template +``` + +## 查询参数和元数据选项 + +所有参数都是可选的。某些参数也可以作为每个元数据行的一部分应用于每个搜索。 + +参数 | 类型 | 描述 | 在元数据中支持 +:--- | :--- | :--- | :--- +`allow_no_indices` | 布尔值 | 指定是否忽略不匹配任何索引的通配符。默认为 `true`。| 是 +`cancel_after_time_interval` | 时间 | 搜索请求将被取消的时间间隔。在父级和子级请求级别都支持。优先级顺序为子级参数、父级参数和[集群设置](/api-reference/cluster-api/cluster-settings)。默认为 `-1`。| 是 +`css_minimize_roundtrips` | 布尔值 | 指定 OpenSearch 是否应尝试最小化协调节点和远程集群之间的网络往返次数(仅适用于跨集群搜索请求)。默认为 `true`。| 否 +`expand_wildcards` | 枚举 | 将通配符表达式扩展为具体索引。用逗号组合多个值。支持的值为 `all`、`open`、`closed`、`hidden` 和 `none`。默认为 `open`。| 是 +`ignore_unavailable` | 布尔值 | 如果索引列表中的索引或分片不存在,则此设置指定是否忽略缺失的索引或分片,而不是使查询失败。默认为 `false`。| 是 +`max_concurrent_searches` | 整数 | 最大并发搜索数。默认值取决于您的节点数和搜索线程池大小。较高的值可以提高性能,但可能存在使集群过载的风险。| 否 +`max_concurrent_shard_requests` | 整数 | 每个搜索在每个节点上执行的最大并发分片请求数。默认为 `5`。较高的值可以提高性能,但可能存在使集群过载的风险。| 否 +`pre_filter_shard_size` | 整数 | 默认为 `128`。| 否 +`rest_total_hits_as_int` | 字符串 | 指定 `hits.total` 属性是作为整数 (`true`) 还是对象 (`false`) 返回。默认为 `false`。| 否 +`search_type` | 字符串 | 影响相关性分数。有效选项为 `query_then_fetch` 和 `dfs_query_then_fetch`。`query_then_fetch` 使用单个分片的词项和文档频率对文档进行评分(更快,不太准确),而 `dfs_query_then_fetch` 使用所有分片的词项和文档频率(较慢,更准确)。默认为 `query_then_fetch`。| 是 +`typed_keys` | 布尔值 | 指定是否在响应中为聚合名称添加其内部类型前缀。默认为 `false`。| 否 + +### 仅元数据选项 + +某些选项不能作为参数应用于整个请求。相反,您可以将它们作为每个元数据行的一部分应用于每个搜索。所有选项都是可选的。 + +选项 | 类型 | 描述 +:--- | :--- | :--- +`index` | 字符串、字符串数组 | 如果您没有在 URL 中指定索引或多个索引(或者想要覆盖单个搜索的 URL 值),您可以在此选项下包含它。示例包括 `"logs-*"` 和 `["my-store", "sample_data_ecommerce"]`。 +`preference` | 字符串 | 指定要在其上执行搜索的节点或分片。此设置对于测试很有用,但在大多数情况下,默认行为提供最佳搜索延迟。选项包括 `_local`、`_only_local`、`_prefer_nodes`、`_only_nodes` 和 `_shards`。最后三个选项接受节点或分片列表。示例包括 `"_only_nodes:data-node1,data-node2"` 和 `"_shards:0,1`。 +`request_cache` | 布尔值 | 指定是否缓存结果,这可以提高重复搜索的延迟。默认为使用索引的 `index.requests.cache.enable` 设置(对于新索引默认为 `true`)。 +`routing` | 字符串 | 逗号分隔的自定义路由值,例如 `"routing": "value1,value2,value3"`。 + +## 请求体 + +多搜索模板请求体遵循此模式,类似于[多搜索 API](/api-reference/multi-search) 模式: + +``` +Metadata\n +Query\n +Metadata\n +Query\n + +``` + +- 元数据行包含选项,例如要搜索的索引和搜索类型。 +- 查询行使用[查询 DSL](/query-dsl/)。 + +与 [bulk](/api-reference/document-apis/bulk) 操作一样,JSON 不需要最小化---空格是可以的---但它确实需要在单行上。OpenSearch 使用换行符来解析多搜索请求,并要求请求体以换行符结束。 + +## 示例请求 + +以下示例 `msearch/template` API 请求使用名为 `line_search_template` 和 `play_search_template` 的多个模板对单个索引运行查询: + +<!-- spec_insert_start +component: example_code +rest: GET /_msearch/template +body: | +{"index":"shakespeare"} +{"id":"line_search_template","params":{"text_entry":"All the world's a stage","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} +--> + +GET /_msearch/template +{"index":"shakespeare"} +{"id":"line_search_template","params":{"text_entry":"All the world's a stage","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} + +response = client.msearch_template( + body = ''' +{"index":"shakespeare"} +{"id":"line_search_template","params":{"text_entry":"All the world's a stage","limit":false,"size":2}} +{"index":"shakespeare"} +{"id":"play_search_template","params":{"play_name":"Henry IV"}} +''' +) + +<!-- spec_insert_end --> + +## 示例响应 + +OpenSearch 返回一个数组,其中包含每个搜索的结果,顺序与多搜索模板请求中的顺序相同: + +```json +{ + "took": 5, + "responses": [ + { + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 0, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "status": 200 + }, + { + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 0, + "relation": "eq" + }, + "max_score": null, + "hits": [] + }, + "status": 200 + } + ] +} +``` diff --git a/i18n/zh/api-reference/search-apis/search-template/render-template.md b/i18n/zh/api-reference/search-apis/search-template/render-template.md new file mode 100644 index 00000000..486c2ffa --- /dev/null +++ b/i18n/zh/api-reference/search-apis/search-template/render-template.md @@ -0,0 +1,128 @@ +--- +title: 渲染模板 +--- + +# 渲染模板 API +<Badge type="tip" text="引入版本 1.0" /> + +渲染模板 API 通过替换参数来预览从[搜索模板](/api-reference/search-apis/search-template/)生成的最终查询,而不执行搜索。 + +## 端点 + +```json +GET /_render/template +POST /_render/template +GET /_render/template/{id} +POST /_render/template/{id} +``` + +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `id` | 字符串 | 要渲染的搜索模板的 ID。| + +## 请求体字段 + +下表列出了可用的请求体字段。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `id` | 条件性 | 字符串 | 要渲染的搜索模板的 ID。如果 ID 在路径中提供或通过 `source` 指定内联模板,则不需要。| +| `params` | 否 | 对象 | 替换模板中找到的 Mustache 变量的值列表(键值对)。键值对必须存在于要搜索的文档中。| +| `source` | 条件性 | 对象 | 如果未指定搜索模板,则要渲染的内联搜索模板。支持与[搜索](/api-reference/search) API 请求和 [Mustache](https://mustache.github.io/mustache.5.html) 变量相同的参数。| + +## 示例请求 + +以下两个示例请求都使用模板 ID 为 `play_search_template` 的搜索模板: + +```json +{ + "source": { + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +``` + +### 使用模板 ID 渲染模板 + +以下示例请求验证 ID 为 `play_search_template` 的搜索模板: + +<!-- spec_insert_start +component: example_code +rest: POST /_render/template +body: | +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } +} +--> + +POST /_render/template +{ + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } +} + +response = client.render_search_template( + body = { + "id": "play_search_template", + "params": { + "play_name": "Henry IV" + } + } +) + +<!-- spec_insert_end --> + +### 使用 `_source` 渲染模板 + +如果您不想使用已保存的模板,或者想在保存之前测试模板,您可以使用 `_source` 参数使用 [Mustache](https://mustache.github.io/mustache.5.html) 变量测试模板,如以下示例所示: + +```json +{ + "source": { + "from": "{{from}}{{^from}}0{{/from}}", + "size": "{{size}}{{^size}}10{{/size}}", + "query": { + "match": { + "play_name": "{{play_name}}" + } + } + }, + "params": { + "play_name": "Henry IV" + } +} +``` + +## 示例响应 + +OpenSearch 响应有关模板输出的信息: + +```json +{ + "template_output": { + "from": "0", + "size": "10", + "query": { + "match": { + "play_name": "Henry IV" + } + } + } +} +``` diff --git a/i18n/zh/api-reference/search-apis/search.md b/i18n/zh/api-reference/search-apis/search.md new file mode 100644 index 00000000..bcaf0f89 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/search.md @@ -0,0 +1,557 @@ +--- +title: 搜索 +--- + +# 搜索 API +<Badge type="tip" text="引入版本 1.0" /> + +搜索 API 操作允许您搜索集群中的数据。 + +## 端点 + +```json +GET /{index}/_search +GET /_search + +POST /{index}/_search +POST /_search +``` + +## 查询参数 + +::: info NOTE +许多参数仅在您使用 URL `q=` 参数或 `query_string` 查询时适用。有关更多信息,请参阅[查询字符串查询](/query-dsl/full-text/query-string)。 +::: + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 类型 | 描述 +:--- | :--- | :--- +`allow_no_indices` | 布尔值 | 是否忽略不匹配任何索引的通配符。默认为 `true`。示例:`GET test-index-*/_search?allow_no_indices=true`。有关更多信息,请参阅[定位多个索引](/api-reference/index-name-syntax#targeting-multiple-indexes)。| +`allow_partial_search_results` | 布尔值 | 如果请求遇到错误或超时,是否返回部分结果。默认为 `true`。示例:`GET test-index/_search?allow_partial_search_results=false`。| +`analyzer` | 字符串 | 在查询字符串中使用的分析器。需要 `q=` 或 `query_string` 体。示例:`GET test-index/_search?q=title:test&analyzer=standard`。有关更多信息,请参阅[文本分析](/analyzers/)。| +`analyze_wildcard` | 布尔值 | 是否分析查询字符串中的通配符和前缀查询。默认为 `false`。需要 `q=` 或 `query_string`。示例:`GET test-index/_search?q=title:te*&analyze_wildcard=true`。| +`batched_reduce_size` | 整数 | 在返回最终搜索结果之前,协调节点上将多少个分片结果组合成一个批次的数量。限制一起处理的分片结果数量,有助于在搜索请求跨越许多分片时减少内存使用。默认为 `512`。示例:`GET test-index/_search?batched_reduce_size=2`。| +`cancel_after_time_interval` | 时间 | 搜索请求将被取消的时间。请求级参数优先于 `cancel_after_time_interval` [集群设置](/api-reference/cluster-api/cluster-settings)。默认为 `-1`。示例:`GET test-index/_search?cancel_after_time_interval=10ms`。| +`ccs_minimize_roundtrips` | 布尔值 | 是否最小化节点和远程集群之间的往返次数。默认为 `true`。示例:`GET test-index/_search?ccs_minimize_roundtrips=true`。| +`default_operator` | 字符串 | 字符串查询的默认运算符。有效值为 `AND` 和 `OR`。默认为 `OR`。需要 `q=` 或 `query_string`。示例:`GET test-index/_search?q=title:test one&default_operator=AND`。| +`df` | 字符串 | 如果查询字符串中没有提供字段前缀,则使用的默认字段。需要 `q=` 或 `query_string`。示例:`GET test-index/_search?q=test&df=title`。| +`docvalue_fields` | 字符串 | 应从其文档值表示形式返回其值的字段的逗号分隔列表。文档值是一种优化的列式格式,可提高聚合、排序和脚本编写的性能。示例:`GET test-index/_search?docvalue_fields=ts,views`。有关更多信息,请参阅[使用文档值字段搜索](/search-plugins/searching-data/retrieve-specific-fields#searching-with-doc-value-fields)。| +`expand_wildcards` | 字符串 | 指定通配符表达式可以匹配的索引类型。支持逗号分隔的值。<br> 有效值为:<br> - `all`:匹配任何索引,包括隐藏索引。<br> - `closed`:匹配关闭的非隐藏索引。<br> - `hidden`:匹配隐藏索引。必须与 `open`、`closed` 或两者结合使用。<br> - `none`:不接受通配符表达式。<br> - `open`:匹配开放的非隐藏索引。<br> 默认为 `open`。示例:`GET test-index-*/_search?expand_wildcards=open`。有关更多信息,请参阅[定位多个索引](/api-reference/index-name-syntax#targeting-multiple-indexes)。| +`explain` | 布尔值 | 如果为 `true`,则返回有关 OpenSearch 如何计算每个文档的相关性得分的详细信息。默认为 `false`。仅在搜索响应中包含 `hits` 时适用。示例:`GET test-index/_search?explain=true&size=1&q=title:test`。有关更多信息,请参阅 [Explain API](/api-reference/search-apis/explain)。| +`from` | 整数 | 返回结果之前要跳过的命中数。与 `size` 一起使用以对结果进行分页。默认为 `0`。示例:`GET test-index/_search?from=5&size=5`。有关更多信息,请参阅 [from 和 size 参数](/search-plugins/searching-data/paginate#the-from-and-size-parameters)。| +`ignore_throttled` | 布尔值 | 如果它们被冻结,是否忽略具体索引、扩展索引或具有别名的索引。默认为 `true`。示例:`GET test-index/_search?ignore_throttled=true`。| +`ignore_unavailable` | 布尔值 | 如果为 `true`,OpenSearch 在搜索期间会忽略缺失或关闭的索引以及不可用的分片。如果为 `false`,则在定位缺失或关闭的索引时请求返回错误。默认为 `false`。示例:`GET test-index-*/_search?ignore_unavailable=true`。有关更多信息,请参阅[定位多个索引](/api-reference/index-name-syntax#targeting-multiple-indexes)。| +`include_named_queries_score` | 布尔值 | 是否为每个命中返回命名查询(使用 `_name` 的查询)的得分贡献。默认为 `false`。需要使用 `_name` 命名的查询。示例:`POST test-index/_search?include_named_queries_score=true {"size":1,"query":{"match":{"title":{"query":"test","_name":"q1"}}}}`。有关更多信息,请参阅[命名查询](/query-dsl/named-queries)。| +`lenient` | 布尔值 | OpenSearch 是否应该接受具有格式错误的查询的请求(例如,使用文本查询数字字段)而不是返回错误。默认为 `false`。需要 `q=` 或 `query_string`。示例:`GET test-index/_search?q=views:abc&lenient=true`。| +`max_concurrent_shard_requests` | 整数 | 此请求应在每个节点上执行的最大并发分片请求数。默认为 `5`。示例:`GET test-index/_search?max_concurrent_shard_requests=2`。| +`node_level_query_fanout` | 布尔值 | 是否对此搜索请求使用节点级查询扇出,在提供时覆盖 `search.node_level_query_fanout.enabled` 集群设置。节点级查询扇出按目标数据节点对分片级 `query_then_fetch` 查询和 `can_match` 请求进行分组。默认为 `false`。示例:`POST index1/_search?node_level_query_fanout=true`。| +`phase_took` | 布尔值 | 是否在响应中返回阶段级 `took` 时间值。默认为 `false`。示例:`GET test-index/_search?phase_took=true`。| +`pre_filter_shard_size` | 整数 | 触发搜索分片上的预过滤操作的预过滤大小阈值。如果搜索请求扩展到的分片数超过此值,OpenSearch 会执行预过滤操作,以根据查询重写消除无法匹配文档的分片。默认为 `128`。示例:`GET test-index/_search?pre_filter_shard_size=1`。| +`preference` | 字符串 | 指定 OpenSearch 应在哪些分片或节点上执行搜索。示例:`GET test-index/_search?preference=_local`。有关有效值,请参阅 [preference 查询参数](/api-reference/search-apis/search#the-preference-query-parameter)。| +`q` | 字符串 | Lucene 查询字符串查询。启用查询字符串助手。优先于请求体中的 `query` 参数。如果同时指定了两者,则只返回匹配此参数的文档;忽略请求体中的查询。示例:`GET test-index/_search?q=title:test&size=5`。有关更多信息,请参阅[查询字符串查询](/query-dsl/full-text/query-string)。| +`request_cache` | 布尔值 | 如果指定了 `size=0`,OpenSearch 是否应该对请求使用搜索结果缓存。默认为索引级 `request_cache` 设置。示例:`GET test-index/_search?request_cache=true`。有关更多信息,请参阅[索引请求缓存](/search-plugins/caching/request-cache)。| +`rest_total_hits_as_int` | 布尔值 | 是否将 `hits.total` 作为整数返回。否则返回对象。默认为 `false`。与 `track_total_hits` 设置为 `true` 一起使用。示例:`GET test-index/_search?track_total_hits=true&rest_total_hits_as_int=true`。| +`routing` | 字符串 | 用于将搜索路由到特定分片的自定义值。示例:`GET test-index/_search?routing=user-42`。有关更多信息,请参阅[路由](/mappings/metadata-fields/routing/)。| +`scroll` | 时间 | 保持搜索上下文打开的时间量。需要 `size` 大于 `0` 以及后续的 `_search/scroll`。示例:`GET test-index/_search?scroll=1m&size=2`。有关更多信息,请参阅[滚动搜索](/search-plugins/searching-data/paginate#scroll-search)。| +`search_type` | 字符串 | OpenSearch 在计算相关性分数时是否应该使用全局词项和文档频率。有效值为 `query_then_fetch` 和 `dfs_query_then_fetch`。`query_then_fetch` 使用分片的本地词项和文档频率对文档进行评分。它通常更快但不太准确。`dfs_query_then_fetch` 使用所有分片的全局词项和文档频率对文档进行评分。它通常较慢但更准确。默认为 `query_then_fetch`。示例:`GET test-index/_search?search_type=dfs_query_then_fetch`。| +`seq_no_primary_term` | 布尔值 | 是否返回每个文档命中的最后一次操作的序列号和主词项。示例:`GET test-index/_search?seq_no_primary_term=true&size=1&q=title:test`。| +`size` | 整数 | 要返回的最大结果数。与 `from` 一起使用以对结果进行分页。默认为 `10`。示例:`GET test-index/_search?size=3`。有关更多信息,请参阅 [from 和 size 参数](/search-plugins/searching-data/paginate#the-from-and-size-parameters)。| +`sort` | 列表 | 要排序的 `<field>:<direction>` 对的逗号分隔列表。如果您在按非分数字段排序时想要分数,请使用 `track_scores=true`。示例:`GET test-index/_search?sort=views:desc&track_scores=true&size=3`。有关更多信息,请参阅[排序结果](/search-plugins/searching-data/sort)。| +`_source` | 字符串或布尔值 | 控制响应中提供的 `_source` 字段。有效值为 `true`(返回文档源)、`false`(不返回文档源)和 `<string>`(要返回的源中的字段或字段,作为列表或通配符模式提供)。示例:`GET test-index/_search?_source=false&size=1`、`GET test-index/_search?_source=titl*&size=1`、`GET test-index/_search?_source=title,description&size=1`。有关更多信息,请参阅[源过滤](#source-filtering)。| +`_source_excludes` | 列表 | 要从响应中排除的源字段的逗号分隔列表。如果 `_source` 参数为 `false`,则忽略此参数。示例:`GET test-index/_search?_source_excludes=title&size=1`。有关更多信息,请参阅[源过滤](#source-filtering)。| +`_source_includes` | 列表 | 要包含在响应中的源字段的逗号分隔列表。如果 `_source` 参数为 `false`,则忽略此参数。示例:`GET test-index/_search?_source_includes=title&size=1`。有关更多信息,请参阅[源过滤](#source-filtering)。| +`stats` | 字符串 | 与请求关联的[搜索统计组](#search-stats-groups)的逗号分隔列表。示例:`GET test-index/_search?stats=group1`。| +`stored_fields` | 列表 | 为每个命中返回的存储字段的逗号分隔列表。示例:`GET test-index-stored/_search?stored_fields=note&size=1`。有关更多信息,请参阅[使用存储字段搜索](/search-plugins/searching-data/retrieve-specific-fields#searching-with-stored-fields)。| +`suggest_field` | 字符串 | 用于词项建议的字段。需要 `suggest_mode` 和 `suggest_text` 或 `q`。要在请求体中配置建议,请使用 `suggest` 字段。有关更多信息,请参阅 [Did-you-mean](/search-plugins/searching-data/did-you-mean)。 +`suggest_mode` | 字符串 | 搜索时使用的模式。有效值为 `always`(根据 `suggest_text` 中的词项提供建议)、`popular`(提供在分片上比搜索词项出现在更多文档中的建议)和 `missing`(为分片上不存在的词项提供建议)。当您使用 `suggest_field` 时需要。 +`suggest_size` | 整数 | 要返回的建议数。需要 `suggest_field` 和 `suggest_mode`。 +`suggest_text` | 字符串 | OpenSearch 应该为其返回建议的输入文本。需要 `suggest_field` 和 `suggest_mode`。如果省略,OpenSearch 使用 `q` 的值。 +`terminate_after` | 整数 | OpenSearch 在终止请求之前应处理的最大匹配文档数(命中数)。默认为 `0`(无最大值)。示例:`GET test-index/_search?terminate_after=1&size=10`。| +`timeout` | 时间 | 操作应该等待活动分片响应的时间。默认为 `1m`(1 分钟)。示例:`GET test-index/_search?timeout=10ms`。| +`track_scores` | 布尔值 | 是否返回文档分数。默认为 `false`。与 `sort` 一起使用。示例:`GET test-index/_search?sort=views:desc&track_scores=true&size=3`。有关更多信息,请参阅[跟踪分数](/search-plugins/searching-data/sort#tracking-scores)。| +`track_total_hits` | 布尔值或整数 | 要计数的匹配文档数。默认为 `10000`。示例:`GET test-index/_search?track_total_hits=2`。有关更多信息,请参阅[跟踪总命中数](#track-total-hits)。| +`typed_keys` | 布尔值 | 返回的聚合和建议词项是否应在响应中包含其类型。默认为 `false`。仅适用于聚合或建议器。示例:`POST test-index/_search?typed_keys=true {"size":0,"aggs":{"a":{"terms":{"field":"views"}}}}`。有关更多信息,请参阅[在响应中包含建议器类型](/search-plugins/searching-data/did-you-mean#including-suggester-types-in-the-response)。| +`version` | 布尔值 | 是否将文档版本作为匹配包含。示例:`GET test-index/_search?version=true&size=1&q=title:test`。| + +### `preference` 查询参数 + +`preference` 查询参数指定 OpenSearch 应在哪些分片或节点上执行搜索。以下是有效值: + +- `_primary`:仅在主分片上执行搜索。 +- `_replica`:仅在副本分片上执行搜索。 +- `_primary_first`:在主分片上执行搜索,但如果主分片不可用,则故障转移到其他可用分片。 +- `_replica_first`:在副本分片上执行搜索,但如果副本分片不可用,则故障转移到其他可用分片。 +- `_local`:如果可能,在本地节点的分片上执行搜索。 +- `_prefer_nodes:<node-id-1>,<node-id-2>`:如果可能,在指定的节点上执行搜索。使用逗号分隔的列表指定多个节点。 +- `_shards:<shard-id-1>,<shard-id-2>`:仅在指定的分片上执行搜索。使用逗号分隔的列表指定多个分片。与其他首选项结合使用时,`_shards` 首选项必须首先列出。例如,`_shards:1,2|_replica`。 +- `_only_nodes:<node-id-1>,<node-id-2>`:仅在指定的节点上执行搜索。使用逗号分隔的列表指定多个节点。 +- `<string>`:指定用于搜索的自定义字符串。字符串不能以下划线字符 (`_`) 开头。具有相同自定义字符串的搜索被路由到相同的分片。 + +## 请求体 + +下表列出了可用的请求体字段。所有请求体字段都是可选的。 + +字段 | 类型 | 描述 +:--- | :--- | :--- +`aggregations`、`aggs` | 对象 | 在可选的 `aggregations` 参数(或其简写形式 `aggs`)中,您可以定义任意数量的聚合。每个聚合由其名称和 OpenSearch 支持的聚合类型之一定义。有关更多信息,请参阅[聚合](/aggregations/)。 +`collapse` | 对象 | 折叠搜索结果,以便仅返回指定字段的每个值的顶部文档。有关更多信息,请参阅[折叠搜索结果](/search-plugins/searching-data/collapse-search)。 +`derived` | 对象 | 定义派生字段,这些字段在搜索时由脚本计算,并且可以像索引字段一样被查询、聚合和返回。有关更多信息,请参阅[派生字段](/mappings/supported-field-types/derived/)。 +`docvalue_fields` | 对象数组 | 要以其 `doc_values` 形式返回的字段。您可以为返回的值包含格式(例如,日期格式)。对于 `knn_vector` 字段,支持的格式为 `binary`(默认,Base64 编码)和 `array`(JSON 数字数组)。有关更多信息,请参阅[使用 `docvalue_fields` 检索向量字段](/search-plugins/searching-data/retrieve-specific-fields#retrieving-vector-fields-using-docvalue_fields)。 +`explain` | 布尔值 | 是否返回有关 OpenSearch 如何计算文档得分的详细信息。默认为 `false`。 +`ext` | 对象 | 插件使用的设置,例如搜索管道处理器。有关更多信息,请参阅 [ext 对象](#the-ext-object)。 +`fields` | 数组 | 要在每个命中的 `fields` 对象中返回的字段。您可以使用通配符模式并为日期字段指定格式。有关更多信息,请参阅[检索特定字段](/search-plugins/searching-data/retrieve-specific-fields)。 +`from` | 整数 | 返回结果之前要跳过的结果数。与 `size` 一起使用以对结果进行分页。默认为 `0`。有关更多信息,请参阅 [from 和 size 参数](/search-plugins/searching-data/paginate#the-from-and-size-parameters)。 +`highlight` | 对象 | 返回突出显示搜索词项的匹配文本片段。有关更多信息,请参阅[突出显示查询匹配](/search-plugins/searching-data/highlight)。 +`include_named_queries_score` | 布尔值 | 是否返回命名查询的分数。 +`indices_boost` | 对象数组 | 提升来自特定索引的文档的 `_score`。每个条目以 `<index>: <boost-multiplier>` 格式指定索引和提升因子。大于 `1.0` 的提升会增加分数,而 `0` 和 `1.0` 之间的提升会降低分数。 +`min_score` | 浮点数 | 文档必须具有的最低分数才能在结果中返回。 +`pit` | 对象 | 要搜索的时间点 (PIT)。当您搜索 PIT 时,不要在请求路径中指定索引。有关更多信息,请参阅[时间点](/search-plugins/searching-data/point-in-time)。 +`post_filter` | 对象 | 在计算聚合后过滤结果的查询。聚合包括匹配 `query` 的所有文档,而结果仅包括也匹配 `post_filter` 的文档。有关更多信息,请参阅[过滤搜索结果](/search-plugins/filter-search#narrowing-results-using-post-filter-while-preserving-aggregation-visibility)。 +`profile` | 布尔值 | 是否返回有关查询的每个部分如何执行的详细时间信息。默认为 `false`。有关更多信息,请参阅 [Profile API](/api-reference/search-apis/profile)。 +`query` | 对象 | 请求中使用的 [DSL 查询](/query-dsl/)。 +`rescore` | 对象或对象数组 | 使用第二个通常更昂贵的查询重新排序 `query` 返回的顶部结果。有关更多信息,请参阅 [Rescore](/query-dsl/rescore)。 +`script_fields` | 对象 | 其值由脚本为每个命中计算并在 `fields` 对象中返回的字段。有关更多信息,请参阅[使用脚本字段](/search-plugins/searching-data/retrieve-specific-fields#using-scripted-fields)。 +`search_after` | 数组 | 上一页上最后一次命中的排序值。返回排序顺序中跟在它后面的结果。需要 `sort`。有关更多信息,请参阅 [search_after 参数](/search-plugins/searching-data/paginate#the-search_after-parameter)。 +`search_pipeline` | 对象 | 仅应用于此请求的临时搜索管道。有关更多信息,请参阅[搜索管道](/search-plugins/search-pipelines/)。 +`seq_no_primary_term` | 布尔值 | 是否返回每个文档命中的最后一次操作的序列号和主词项。 +`size` | 整数 | 要返回的最大结果数。与 `from` 一起使用以对结果进行分页。默认为 `10`。有关更多信息,请参阅 [from 和 size 参数](/search-plugins/searching-data/paginate#the-from-and-size-parameters)。 +`slice` | 对象 | 将滚动或 PIT 搜索拆分为可以独立处理的切片。有关更多信息,请参阅[滚动搜索](/search-plugins/searching-data/paginate#scroll-search)。 +`sort` | 对象或字符串数组 | 指定如何排序结果。可以是字段名称、具有字段和排序选项的对象或这些的数组。请参阅[排序结果](/search-plugins/searching-data/sort)。 +`_source` | 布尔值、字符串、字符串数组或对象 | 要在每个命中中返回的文档源字段。默认为 `true`(返回完整文档)。有关更多信息,请参阅[源过滤](#source-filtering)。 +`stats` | 字符串数组 | 与请求关联的[搜索统计组](#search-stats-groups)列表。 +`stored_fields` | 字符串数组 | 为每个命中返回的存储字段。如果指定 `stored_fields`,则不返回 `_source`,除非您请求它。有关更多信息,请参阅[使用存储字段搜索](/search-plugins/searching-data/retrieve-specific-fields#searching-with-stored-fields)。 +`suggest` | 对象 | 返回与提供的文本相似的建议词项或短语。有关更多信息,请参阅 [Did-you-mean](/search-plugins/searching-data/did-you-mean)。 +`terminate_after` | 整数 | OpenSearch 在终止请求之前应处理的最大匹配文档数(命中数)。默认为 0。 +`timeout` | 时间 | 等待响应的时间。默认为无超时。 +`track_scores` | 布尔值 | 在按 `_score` 以外的字段排序时是否计算和返回文档分数。默认为 `false`,在这种情况下,排序结果中的 `_score` 为 `null`。 +`track_total_hits` | 布尔值或整数 | 要准确计数的匹配文档数。默认为 `10000`。有关更多信息,请参阅[跟踪总命中数](#track-total-hits)。 +`verbose_pipeline` | 布尔值 | 是否返回有关为请求运行的每个搜索管道处理器的信息。默认为 `false`。有关更多信息,请参阅[调试搜索管道](/search-plugins/search-pipelines/debugging-search-pipeline)。 +`version` | 布尔值 | 是否在响应中包含文档版本。 + +### 搜索统计组 + +您可以通过在请求体的 `stats` 字段中指定组名称或作为查询参数,将搜索请求与一个或多个统计组关联。OpenSearch 维护每组搜索统计信息,您可以使用[索引统计 API](/api-reference/index-apis/stats#specific-search-groups) 检索。 + +以下示例将搜索请求与两个组关联: + +```json +POST /my-index/_search +{ + "query": { + "match_all": {} + }, + "stats": ["group1", "group2"] +} +``` + +要检索特定组的搜索统计信息,请使用索引统计 API 的 `groups` 查询参数: + +```json +GET /my-index/_stats/search?groups=group1,group2 +``` + +要返回所有组的统计信息,请使用 `_all`: + +```json +GET /my-index/_stats/search?groups=_all +``` + +## 示例请求 + +<!-- spec_insert_start +component: example_code +rest: GET /movies/_search +body: | +{ + "query": { + "match": { + "director": "Christopher Nolan" + } + } +} +--> + +GET /movies/_search +{ + "query": { + "match": { + "director": "Christopher Nolan" + } + } +} + +response = client.search( + index = "movies", + body = { + "query": { + "match": { + "director": "Christopher Nolan" + } + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下示例响应显示了搜索响应的结构: + +```json +{ + "took": 14, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.42727602, + "hits": [ + { + "_index": "movies", + "_id": "1", + "_score": 0.42727602, + "_source": { + "title": "The Dark Knight", + "director": "Christopher Nolan", + "year": 2008, + "genre": "Action" + } + }, + { + "_index": "movies", + "_id": "2", + "_score": 0.42727602, + "_source": { + "title": "Inception", + "director": "Christopher Nolan", + "year": 2010, + "genre": "Science Fiction" + } + } + ] + } +} +``` + +## 响应体字段 + +下表列出了顶级响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `took` | 整数 | OpenSearch 运行搜索所花费的时间(以毫秒为单位)。这是从协调节点接收请求到它准备发送响应的时刻测量的,因此它包括协调节点和数据节点之间的通信、在 `search` 线程池中排队的时间以及搜索本身。它不包括通过网络传输请求或响应所花费的时间。| +| `phase_took` | 对象 | 在每个搜索阶段(`can_match`、`dfs_pre_query`、`query`、`dfs_query`、`fetch` 和 `expand`)中花费的时间(以毫秒为单位)。仅当 `phase_took` 查询参数为 `true` 时返回。| +| `timed_out` | 布尔值 | 搜索在完成之前是否超时。如果为 `true`,返回的结果可能是部分的或空的。| +| `terminated_early` | 布尔值 | OpenSearch 是否在收集了 `terminate_after` 中指定的文档数后提前停止搜索。仅当设置了 `terminate_after` 时返回。| +| `_shards` | 对象 | 搜索运行的分片数以及每组分片的结果。| +| `hits` | 对象 | 匹配的文档及其元数据。| +| `aggregations` | 对象 | 聚合结果,按聚合名称键入。仅当请求体包含 `aggs` 对象时返回。| +| `suggest` | 对象 | 建议结果,按建议器名称键入。仅当请求体包含 `suggest` 对象时返回。| +| `profile` | 对象 | 查询和获取阶段的每分片时间详细信息。仅当请求体将 `profile` 设置为 `true` 时返回。有关更多信息,请参阅 [Profile API](/api-reference/search-apis/profile)。| +| `_scroll_id` | 字符串 | 标识搜索上下文的滚动 ID。将此值传递给[滚动 API](/api-reference/search-apis/scroll) 以检索下一批结果。仅当请求包含 `scroll` 查询参数时返回。| +| `pit_id` | 字符串 | 标识搜索上下文的时间点 (PIT) ID。仅当请求搜索 PIT 时返回。有关更多信息,请参阅[时间点 API](/api-reference/search-apis/point-in-time-api)。| +| `_clusters` | 对象 | 跨集群搜索运行的集群数以及每组集群的结果。仅对跨集群搜索返回。| +| `num_reduce_phases` | 整数 | OpenSearch 为了将部分分片结果组合到最终结果集中而执行的归约阶段数。仅当搜索使用多个归约阶段时返回。| + +下表列出了 `_shards` 对象中的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `total` | 整数 | 搜索需要查询的分片数,包括未分配的分片。| +| `successful` | 整数 | 成功运行搜索的分片数。| +| `skipped` | 整数 | 跳过搜索的分片数,因为初步检查确定分片上没有文档可以匹配。这通常发生在搜索包含范围过滤器且分片上的所有值都在该范围之外时。| +| `failed` | 整数 | 未能运行搜索的分片数。未分配的分片既不计为成功也不计为失败,因此如果 `successful` 和 `failed` 加起来小于 `total`,则某些分片未分配。| + +下表列出了 `hits` 对象中的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `total` | 对象 | 匹配文档的数量。包含计数的 `value` 字段和在计数精确时为 `eq` 或在计数为下限时为 `gte` 的 `relation` 字段。当 `track_total_hits` 为 `false` 时省略。| +| `max_score` | 浮点数 | 匹配文档中最高的 `_score`。当搜索不按 `_score` 排序时为 `null`。| +| `hits` | 对象数组 | 匹配的文档,按相关性或指定的排序顺序排序。| + +下表列出了 `hits.hits` 数组中每个对象的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_index` | 字符串 | 包含文档的索引的名称。| +| `_id` | 字符串 | 文档 ID。此 ID 仅在返回的索引内是唯一的。| +| `_score` | 浮点数 | 文档的相关性分数。当搜索不按 `_score` 排序时为 `null`。| +| `_source` | 对象 | 索引时提供的原始 JSON 文档。要省略此字段或仅返回特定字段,请参阅[源过滤](#source-filtering)。| +| `fields` | 对象 | 由 `docvalue_fields` 或 `stored_fields` 检索的字段值。仅当请求指定这两个参数之一时返回。| +| `sort` | 数组 | 文档的排序值。仅当请求体包含 `sort` 数组时返回。将最后一个命中的值作为 `search_after` 传递以检索下一页结果。| +| `highlight` | 对象 | 突出显示的片段,按字段名称键入。仅当请求体包含 `highlight` 对象时返回。| +| `matched_queries` | 字符串数组 | 文档匹配的命名查询的名称。仅当搜索使用 `_name` 参数时返回。| +| `inner_hits` | 对象 | 匹配的嵌套、子或父文档。仅当请求体包含 `inner_hits` 对象时返回。| +| `_explanation` | 对象 | OpenSearch 如何计算文档相关性分数的分解。仅当 `explain` 为 `true` 时返回。| +| `_shard` | 字符串 | 返回文档的分片。仅当 `explain` 为 `true` 时返回。| +| `_node` | 字符串 | 返回文档的节点。仅当 `explain` 为 `true` 时返回。| + +## 源过滤 + +响应中的每个命中都包含一个 `_source` 对象,其中包含原始 JSON 文档。为每个命中返回完整文档会传输比大多数应用程序所需更多的数据。源过滤限制 OpenSearch 在 `_source` 中返回的字段。 + +下表列出了 `_source` 请求体参数的接受值。 + +| 值 | 描述 | +| :--- | :--- | +| `true` | 返回完整文档。这是默认值。| +| `false` | 从每个命中中省略 `_source` 对象。| +| 字符串 | 字段名称或通配符模式,例如 `details.*`。OpenSearch 仅返回匹配的字段。| +| 字符串数组 | 字段名称或通配符模式的列表,例如 `["name", "details.*"]`。| +| 对象 | 包含 `includes` 和 `excludes` 列表的对象。在两个列表中都匹配模式的字段不会返回,因为 `excludes` 优先。| + +要在请求 URL 而不是请求体中过滤源,请使用 `_source`、`_source_includes` 和 `_source_excludes` 查询参数。 + +有关示例和限制,请参阅[使用源过滤](/search-plugins/searching-data/retrieve-specific-fields#using-source-filtering)。 + +## 跟踪总命中数 + +准确计数匹配文档需要访问每个匹配,这对于匹配许多文档的查询来说很昂贵。`track_total_hits` 参数限制 OpenSearch 计数的匹配数。将其指定为查询参数或在请求体中。 + +默认情况下,OpenSearch 准确计数匹配,最多 `10000`。当有更多文档匹配时,`hits.total.value` 报告 `10000`,`hits.total.relation` 为 `gte`,表示查询至少匹配了那么多文档。 + +下表列出了 `track_total_hits` 的接受值。 + +| 值 | 描述 | +| :--- | :--- | +| `true` | 计数每个匹配的文档。`hits.total.relation` 始终为 `eq`。| +| `false` | 禁用命中计数。响应不包含 `hits.total` 对象。| +| 整数 | 准确计数匹配文档,最多指定的数量。当有更多文档匹配时,`hits.total.value` 报告阈值,`hits.total.relation` 为 `gte`。| + +计数每个匹配会减慢匹配许多文档的搜索。一旦计数达到阈值,OpenSearch 可以跳过无法进入顶部结果的文档,这使得按相关性排序的搜索更快。仅当您的应用程序需要精确计数时才增加阈值,并在您根本不显示计数时将 `track_total_hits` 设置为 `false`。 + +`rest_total_hits_as_int` 查询参数需要精确计数。OpenSearch 拒绝将 `rest_total_hits_as_int` 设置为 `true` 并将 `track_total_hits` 设置为整数的请求。 + +### 示例:默认命中计数 + +以下示例搜索包含 10,500 个文档的 `logs` 索引,而不指定 `track_total_hits`: + +```json +GET /logs/_search +{ + "size": 0, + "query": { + "match_all": {} + } +} +``` + +因为 `relation` 为 `gte`,索引至少包含 10,000 个匹配文档: + +```json +{ + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + } +} +``` + +### 示例:计数每个匹配的文档 + +要计数每个匹配,请将 `track_total_hits` 设置为 `true`: + +```json +GET /logs/_search +{ + "size": 0, + "track_total_hits": true, + "query": { + "match_all": {} + } +} +``` + +因为 `relation` 为 `eq`,`value` 是匹配文档的确切数量: + +```json +{ + "hits": { + "total": { + "value": 10500, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } +} +``` + +### 示例:计数到自定义阈值 + +整数阈值在较少文档匹配时返回精确计数,否则返回下限。在 `logs` 索引中,35 个文档的 `level` 值为 `error`,其余文档的值为 `info`。以下请求计数 `error` 文档,阈值为 50: + +```json +GET /logs/_search +{ + "size": 0, + "track_total_hits": 50, + "query": { + "term": { + "level": "error" + } + } +} +``` + +少于 50 个文档匹配,因此计数是精确的: + +```json +{ + "hits": { + "total": { + "value": 35, + "relation": "eq" + }, + "max_score": null, + "hits": [] + } +} +``` + +如果您使用 `"level": "info"` 运行相同的请求,则有超过 50 个文档匹配。OpenSearch 在阈值处停止计数并返回下限: + +```json +{ + "hits": { + "total": { + "value": 50, + "relation": "gte" + }, + "max_score": null, + "hits": [] + } +} +``` + +### 示例:禁用命中计数 + +如果您的应用程序不显示匹配数,请将 `track_total_hits` 设置为 `false`: + +```json +GET /logs/_search +{ + "size": 2, + "_source": false, + "track_total_hits": false, + "query": { + "term": { + "level": "error" + } + } +} +``` + +`hits` 对象包含匹配的文档但没有 `total` 对象: + +```json +{ + "hits": { + "max_score": 1.0, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1.0 + }, + { + "_index": "logs", + "_id": "301", + "_score": 1.0 + } + ] + } +} +``` + +## `ext` 对象 +<Badge type="tip" text="引入版本 2.10" /> + +插件作者可以向搜索请求和搜索响应添加 `ext` 对象。`ext` 对象包含特定于插件的字段,允许插件在请求中传递其他参数或在响应中返回其他信息。 + +### 在搜索响应中使用 `ext` + +插件可以向搜索响应添加 `ext` 对象以包含特定于插件的响应字段。例如,在对话式搜索中,检索增强生成 (RAG) 的结果是单个"命中"(答案)。插件作者可以将此答案作为 `ext` 对象的一部分包含在搜索响应中,使其与搜索命中分开。在以下示例响应中,RAG 结果位于 `ext.retrieval_augmented_generation.answer` 字段中: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 3, + "successful": 3, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 110, + "relation": "eq" + }, + "max_score": 0.55129033, + "hits": [ + { + "_index": "...", + "_id": "...", + "_score": 0.55129033, + "_source": { + "text": "...", + "title": "..." + } + }, + { + ... + } + ... + { + ... + } + ], + }, // end of hits + "ext": { + "retrieval_augmented_generation": { // a search response processor + "answer": "RAG answer" + } + } +} +``` + +### 在搜索请求中使用 `ext` + +插件还可以在搜索请求中接受 `ext` 对象以提供特定于插件的参数。请求中 `ext` 对象的结构和内容取决于插件实现。有关请求 `ext` 对象中支持的特定字段,请查阅您的插件文档。 + +以下示例显示了包含 `ext` 对象的搜索请求。`ext` 中的确切字段取决于安装了哪些插件以及它们接受哪些参数: + +```json +POST /my-index/_search +{ + "query": { + "match": { + "field": "value" + } + }, + "ext": { + "my_plugin": { + "custom_parameter": "value" + } + } +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:data/read/search`。 diff --git a/i18n/zh/api-reference/search-apis/validate.md b/i18n/zh/api-reference/search-apis/validate.md new file mode 100644 index 00000000..ed2e6a26 --- /dev/null +++ b/i18n/zh/api-reference/search-apis/validate.md @@ -0,0 +1,295 @@ +--- +title: 验证查询 +--- + +# 验证查询 API +<Badge type="tip" text="引入版本 1.0" /> + +您可以使用验证查询 API 来验证查询而不运行它。查询可以作为路径参数发送或包含在请求体中。 + +## 端点 + +验证查询 API 包含以下路径: + +```json +GET {index}/_validate/query +``` + +## 路径参数 + +所有路径参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`index` | 字符串 | 要验证查询的索引。如果您没有在 URL 中指定索引或多个索引(或想要覆盖单个搜索的 URL 值),您可以在此处包含它。示例包括 `"logs-*"` 和 `["my-store", "sample_data_ecommerce"]`。 +`query` | 查询对象 | 使用[查询 DSL](/query-dsl/) 的查询。 + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`all_shards` | 布尔值 | 当为 `true` 时,对[所有分片](#rewrite-and-all_shards)而不是每个索引的一个分片运行验证。默认为 `false`。 +`allow_no_indices` | 布尔值 | 是否忽略不匹配任何索引的通配符。默认为 `true`。 +`allow_partial_search_results` | 布尔值 | 如果请求遇到错误或超时,是否返回部分结果。默认为 `true`。 +`analyzer` | 字符串 | 在查询字符串中使用的分析器。这应该只与 `q` 选项一起使用。 +`analyze_wildcard` | 布尔值 | 指定是否分析通配符和前缀查询。默认为 `false`。 +`default_operator` | 字符串 | 指示字符串查询的默认运算符应该是 `AND` 还是 `OR`。默认为 `OR`。 +`df` | 字符串 | 如果查询字符串中没有提供字段前缀,则使用的默认字段。 +`expand_wildcards` | 字符串 | 指定通配符表达式可以匹配的索引类型。支持逗号分隔的值。有效值为 `all`(匹配任何索引)、`open`(匹配开放的非隐藏索引)、`closed`(匹配关闭的非隐藏索引)、`hidden`(匹配隐藏索引)和 `none`(拒绝通配符表达式)。默认为 `open`。 +`explain` | 布尔值 | 是否返回有关 OpenSearch 如何计算[文档得分](#explain)的信息。默认为 `false`。 +`ignore_unavailable` | 布尔值 | 指定是否在响应中包含缺失或关闭的索引,并在搜索请求期间忽略不可用的分片。默认为 `false`。 +`lenient` | 布尔值 | 指定 OpenSearch 是否应该接受基于格式的查询失败的请求(例如,使用文本查询数字字段)。默认为 `false`。 +`rewrite` | 确定 OpenSearch 如何[重写](#rewrite)和评分多词项查询。有效值为 `constant_score`、`scoring_boolean`、`constant_score_boolean`、`top_terms_N`、`top_terms_boost_N` 和 `top_terms_blended_freqs_N`。默认为 `constant_score`。 +`q` | 字符串 | Lucene 字符串语法中的查询。 + +## 示例请求 + +以下示例请求使用通过 `bulk` 请求创建的名为 `Hamlet` 的索引: + +<!-- spec_insert_start +component: example_code +rest: PUT /hamlet/_bulk?refresh +body: | +{"index":{"_id":1}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:12", "message" : "To Search or Not To Search"} +{"index":{"_id":2}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:13", "message" : "My dad says that I'm such a ham."} +--> + +PUT /hamlet/_bulk?refresh +{"index":{"_id":1}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:12", "message" : "To Search or Not To Search"} +{"index":{"_id":2}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:13", "message" : "My dad says that I'm such a ham."} + +response = client.bulk( + index = "hamlet", + params = { "refresh": "true" }, + body = ''' +{"index":{"_id":1}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:12", "message" : "To Search or Not To Search"} +{"index":{"_id":2}} +{"user" : { "id": "hamlet" }, "@timestamp" : "2099-11-15T14:12:13", "message" : "My dad says that I'm such a ham."} +''' +) + +<!-- spec_insert_end --> + +然后,您可以使用验证查询 API 来验证索引查询,如以下示例所示: + +<!-- spec_insert_start +component: example_code +rest: GET /hamlet/_validate/query?q=user.id:hamlet +--> + +GET /hamlet/_validate/query?q=user.id:hamlet + +response = client.indices.validate_query( + index = "hamlet", + params = { "q": "user.id:hamlet" } +) + +<!-- spec_insert_end --> + +查询也可以作为请求体发送,如以下示例所示: + +<!-- spec_insert_start +component: example_code +rest: GET /hamlet/_validate/query +body: | +{ + "query" : { + "bool" : { + "must" : { + "query_string" : { + "query" : "*:*" + } + }, + "filter" : { + "term" : { "user.id" : "hamlet" } + } + } + } +} +--> + +GET /hamlet/_validate/query +{ + "query": { + "bool": { + "must": { + "query_string": { + "query": "*:*" + } + }, + "filter": { + "term": { + "user.id": "hamlet" + } + } + } + } +} + +response = client.indices.validate_query( + index = "hamlet", + body = { + "query": { + "bool": { + "must": { + "query_string": { + "query": "*:*" + } + }, + "filter": { + "term": { + "user.id": "hamlet" + } + } + } + } + } +) + +<!-- spec_insert_end --> + +## 示例响应 + +如果查询通过验证,则响应指示查询为 `true`,如以下示例响应所示,其中 `valid` 参数为 `true`: + +``` +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": true +} +``` + +如果查询未通过验证,则 OpenSearch 响应查询为 `false`。以下示例请求查询包含未在 `hamlet` 索引中配置的动态映射: + +<!-- spec_insert_start +component: example_code +rest: GET /hamlet/_validate/query +body: | +{ + "query": { + "query_string": { + "query": "@timestamp:foo", + "lenient": false + } + } +} +--> + +GET /hamlet/_validate/query +{ + "query": { + "query_string": { + "query": "@timestamp:foo", + "lenient": false + } + } +} + +response = client.indices.validate_query( + index = "hamlet", + body = { + "query": { + "query_string": { + "query": "@timestamp:foo", + "lenient": false + } + } + } +) + +<!-- spec_insert_end --> + +OpenSearch 响应如下,其中 `valid` 参数为 `false`: + +``` +{ + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "valid": false +} +``` + +某些查询参数也可以影响响应中包含的内容。以下示例显示 [Explain](#explain)、[Rewrite](#rewrite) 和 [all_shards](#rewrite-and-all_shards) 查询选项如何影响响应。 + +### Explain + +`explain` 选项在 `explanations` 字段中返回有关查询失败的信息,如以下示例响应所示: + +``` +{ + "valid" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "failed" : 0 + }, + "explanations" : [ { + "index" : "_shakespeare", + "valid" : false, + "error" : "shakespeare/IAEc2nIXSSunQA_suI0MLw] QueryShardException[failed to create query:...failed to parse date field [foo]" + } ] +} +``` + +### Rewrite + +当请求中的 `rewrite` 选项设置为 `true` 时,`explanations` 选项将执行的 Lucene 查询显示为字符串,如以下响应所示: + +``` +{ + "valid": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "explanations": [ + { + "index": "", + "valid": true, + "explanation": "((user:hamlet^4.256753 play:hamlet^6.863601 play:romeo^2.8415773 plot:puck^3.4193945 plot:othello^3.8244398 ... )~4) -ConstantScore(_id:2) #(ConstantScore(_type:_doc))^0.0" + } + ] +} +``` + +### Rewrite 和 all_shards + +当 `rewrite` 和 `all_shards` 选项都设置为 `true` 时,验证查询 API 会响应来自所有可用分片的详细信息,而不是只来自一个分片(默认),如以下响应所示: + +``` +{ + "valid": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "explanations": [ + { + "index": "my-index-000001", + "shard": 0, + "valid": true, + "explanation": "(user.id:hamlet)^0.6333333" + } + ] +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`indices:admin/validate/query`。 diff --git a/i18n/zh/api-reference/snapshots/cleanup-snapshot-repository.md b/i18n/zh/api-reference/snapshots/cleanup-snapshot-repository.md new file mode 100644 index 00000000..1ba6e11e --- /dev/null +++ b/i18n/zh/api-reference/snapshots/cleanup-snapshot-repository.md @@ -0,0 +1,68 @@ +--- +title: Clean up snapshot repository +--- + +# 清理快照存储库 API +<Badge type="tip" text="引入版本 1.0" /> + +清理快照存储库 API 用于清除快照存储库中不再被任何现有快照引用的数据。 + +## 端点 + +```json +POST /_snapshot/{repository}/_cleanup +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `repository` | String | 快照存储库的名称。 | + +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | Time | 等待集群管理器节点响应的时间。以前称为 `master_timeout`。可选。默认值为 30 秒。 | +| `timeout` | Time | 等待操作完成的时间。可选。| + +## 示例请求 + +以下请求从存储库 `my_backup` 中删除所有过期数据: + +<!-- spec_insert_start +component: example_code +rest: POST /_snapshot/my_backup/_cleanup +--> + +POST /_snapshot/my_backup/_cleanup + +response = client.snapshot.cleanup_repository( + repository = "my_backup" +) + +<!-- spec_insert_end --> + +## 示例响应 + +```json +{ + "results":{ + "deleted_bytes":40, + "deleted_blobs":8 + } +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `deleted_bytes` | Integer | 删除数据后在快照中释放的字节数。 | +| `deleted_blobs` | Integer | 请求从存储库中清除的二进制大对象(BLOB)数量。 | diff --git a/i18n/zh/api-reference/snapshots/clone-snapshot.md b/i18n/zh/api-reference/snapshots/clone-snapshot.md new file mode 100644 index 00000000..04be43af --- /dev/null +++ b/i18n/zh/api-reference/snapshots/clone-snapshot.md @@ -0,0 +1,94 @@ +--- +title: Clone snapshot +--- + +# 克隆快照 API +<Badge type="tip" text="引入版本 1.0" /> + +在原始快照所在的同一存储库中创建快照的全部或部分克隆。 + +<!-- spec_insert_start +api: snapshot.clone +component: endpoints +--> +## 端点 +```json +PUT /_snapshot/{repository}/{snapshot}/_clone/{target_snapshot} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: snapshot.clone +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `repository` | **必需** | String | 包含快照克隆的存储库名称。 | +| `snapshot` | **必需** | String | 原始快照的名称。 | +| `target_snapshot` | **必需** | String | 克隆快照的名称。 | + +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: snapshot.clone +component: query_parameters +include_deprecated: false +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cluster_manager_timeout` | String | 等待集群管理器节点响应的时间。有关支持的时间单位的更多信息,请参阅[通用参数](/api-reference/units#time-units)。 | + +<!-- spec_insert_end --> + +## 示例请求 + +以下请求将索引 `index_a` 和 `index_b` 从 `my_snapshot`(位于快照存储库 `my-opensearch-repo` 中的快照)克隆到同一存储库中名为 `my_new_snapshot` 的新快照: + +<!-- spec_insert_start +component: example_code +rest: PUT /_snapshot/my-opensearch-repo/my_snapshot/_clone/my_new_snapshot +body: | +{ + "indices" : "index_a,index_b" +} +--> + +PUT /_snapshot/my-opensearch-repo/my_snapshot/_clone/my_new_snapshot +{ + "indices" : "index_a,index_b" +} + +response = client.snapshot.clone( + repository = "my-opensearch-repo", + snapshot = "my_snapshot", + target_snapshot = "my_new_snapshot", + body = ''' +{ + "indices" : "index_a,index_b" +} +''' +) + +<!-- spec_insert_end --> + +## 示例响应 + +成功创建快照克隆后,返回以下响应: + +```json +{ + "acknowledged" : true +} +``` + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`cluster:admin/snapshot/clone`。 diff --git a/i18n/zh/api-reference/tasks/cancel-tasks.md b/i18n/zh/api-reference/tasks/cancel-tasks.md new file mode 100644 index 00000000..b1630632 --- /dev/null +++ b/i18n/zh/api-reference/tasks/cancel-tasks.md @@ -0,0 +1,137 @@ +--- +title: Cancel tasks +--- + +# 取消任务 API +<Badge type="tip" text="引入版本 1.0" /> + +取消任务 API 用于取消任务,停止其在集群中运行。并非所有任务都可以取消。要确定任务是否可取消,请检查取消任务 API 响应中的 `cancellable` 字段。 + +<!-- spec_insert_start +api: tasks.cancel +component: endpoints +--> +## 端点 +```json +POST /_tasks/_cancel +POST /_tasks/{task_id}/_cancel +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: tasks.cancel +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。所有路径参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `task_id` | String | 任务 ID。 | + +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: tasks.cancel +component: query_parameters +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `actions` | List or String | 应返回的以逗号分隔的操作列表。保持为空以返回所有操作。 | +| `nodes` | List | 用于限制返回信息的以逗号分隔的节点 ID 或名称列表。使用 `_local` 返回您正在连接的节点的信息,指定节点名称以获取特定节点的信息,或保持参数为空以获取所有节点的信息。 | +| `parent_task_id` | String | 返回具有指定父任务 ID(`node_id:task_number`)的任务。保持为空或设置为 -1 以返回所有任务。 | +| `wait_for_completion` | Boolean | 等待匹配的任务完成。当为 `true` 时,请求将被阻塞,直到任务完成。_(默认值:`false`)_ | + +<!-- spec_insert_end --> + +## 示例请求 + +以下请求取消当前在 `opensearch-node1` 和 `opensearch-node2` 上运行的任何任务: + +<!-- spec_insert_start +component: example_code +rest: POST /_tasks/_cancel?nodes=opensearch-node1,opensearch-node2 +--> + +POST /_tasks/_cancel?nodes=opensearch-node1,opensearch-node2 + +response = client.tasks.cancel( + params = { "nodes": "opensearch-node1,opensearch-node2" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下响应显示批量写入和更新任务已取消,没有节点失败,并提供有关已取消任务的其他信息: + +```json +{ + "node_failures": [], + "nodes": { + "JzrCxdtFTCO_RaINw8ckNA": { + "name": "opensearch-node1", + "transport_address": "127.0.0.1:9300", + "host": "127.0.0.1", + "ip": "127.0.0.1:9300", + "roles": [ + "data", + "ingest", + "cluster_manager", + "remote_cluster_client" + ], + "attributes": {}, + "tasks": { + "JzrCxdtFTCO_RaINw8ckNA:54": { + "node": "JzrCxdtFTCO_RaINw8ckNA", + "id": 54, + "type": "transport", + "action": "indices:data/write/bulk", + "status": "cancelled", + "description": "bulk request to [test_index]", + "start_time_in_millis": 1625145678901, + "running_time_in_nanos": 2345678, + "cancellable": true, + "cancelled": true + } + } + }, + "K8iyDdtGQCO_SbJNw9dkMB": { + "name": "opensearch-node2", + "transport_address": "127.0.0.1:9301", + "host": "127.0.0.1", + "ip": "127.0.0.1:9301", + "roles": [ + "data", + "ingest", + "master", + "remote_cluster_client" + ], + "attributes": {}, + "tasks": { + "K8iyDdtGQCO_SbJNw9dkMB:78": { + "node": "K8iyDdtGQCO_SbJNw9dkMB", + "id": 78, + "type": "transport", + "action": "indices:data/write/update", + "status": "cancelled", + "description": "updating document in [another_index]", + "start_time_in_millis": 1625145679012, + "running_time_in_nanos": 1234567, + "cancellable": true, + "cancelled": true + } + } + } + } +} +``` + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`cluster:admin/tasks/cancel`。 diff --git a/i18n/zh/api-reference/tasks/delete-task.md b/i18n/zh/api-reference/tasks/delete-task.md new file mode 100644 index 00000000..0d5f46c3 --- /dev/null +++ b/i18n/zh/api-reference/tasks/delete-task.md @@ -0,0 +1,85 @@ +--- +title: Delete task +--- + +# 删除任务 API +<Badge type="tip" text="引入版本 3.9" /> + +使用删除任务 API 删除已完成任务的存储结果。例如,当您运行受支持的操作并设置 `wait_for_completion=false` 时,OpenSearch 会存储任务结果,以便您稍后可以使用[获取任务 API](/api-reference/tasks/get-tasks) 检索它。当您不再需要该结果时,请将其删除以释放相关存储空间。 + +::: warning IMPORTANT +删除任务 API 不会取消或删除正在运行的任务。要停止正在运行的任务,请使用[取消任务 API](/api-reference/tasks/cancel-tasks)。 +::: + +<!-- spec_insert_start +api: tasks.delete +component: endpoints +--> +## 端点 +```json +DELETE /_tasks/{task_id} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: tasks.delete +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `task_id` | **必需** | String | 要删除的已存储的已完成任务结果的 ID(`node_id:task_number`)。 | + +<!-- spec_insert_end --> + +## 示例请求 + +以下请求删除任务 `JzrCxdtFTCO_RaINw8ckNA:54321` 的存储结果: + +<!-- spec_insert_start +component: example_code +rest: DELETE /_tasks/JzrCxdtFTCO_RaINw8ckNA:54321 +--> + +DELETE /_tasks/JzrCxdtFTCO_RaINw8ckNA:54321 + +response = client.tasks.delete( + task_id = "JzrCxdtFTCO_RaINw8ckNA:54321" +) + +<!-- spec_insert_end --> + +## 示例响应 + +OpenSearch 在删除存储的结果后返回确认: + +```json +{ + "acknowledged": true +} +``` + +成功删除后,获取任务 API 对该任务返回 `404 Not Found` 响应。 + +## 父任务和子任务 + +在任务具有正在运行的子任务或已存储的子任务结果时,您无法删除已存储的任务结果。在已存储任务结果的层次结构中,从叶子向根删除结果。例如,在删除其父结果之前删除孙结果,然后删除根结果。 + +如果任务具有正在运行的子任务或已存储的子任务结果,OpenSearch 将返回 `409 Conflict` 响应。 + +## 响应代码 + +下表列出了常见的响应代码。 + +| HTTP 状态码 | 描述 | +| :--- | :--- | +| `200 OK` | 已存储的已完成任务结果已删除。 | +| `404 Not Found` | 任务未运行且没有存储的结果。 | +| `409 Conflict` | 任务仍在运行、未标记为已完成、具有正在运行的子任务或具有已存储的子任务结果。 | + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`cluster:admin/tasks/delete`。 diff --git a/i18n/zh/api-reference/tasks/get-tasks.md b/i18n/zh/api-reference/tasks/get-tasks.md new file mode 100644 index 00000000..ea214037 --- /dev/null +++ b/i18n/zh/api-reference/tasks/get-tasks.md @@ -0,0 +1,272 @@ +--- +title: Get task +--- + +# 获取任务 API +<Badge type="tip" text="引入版本 1.0" /> + +获取任务 API 返回单个一般 OpenSearch 任务(例如搜索、重新索引或批量操作)的详细信息。 + +::: warning IMPORTANT +此 API 与[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 不同,后者跟踪机器学习任务并具有不同的响应格式。 +::: + +<!-- spec_insert_start +api: tasks.get +component: endpoints +--> +## 端点 +```json +GET /_tasks/{task_id} +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: tasks.get +component: path_parameters +--> +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 必需 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `task_id` | **必需** | String | 任务 ID。 | + +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: tasks.get +component: query_parameters +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `timeout` | String | 等待响应的时间。 | `30s` | +| `wait_for_completion` | Boolean | 等待匹配的任务完成。当为 `true` 时,请求将被阻塞,直到任务完成。 | `false` | + +<!-- spec_insert_end --> + +API 返回当前正在运行的任务的信息。任务完成后,仅当任务结果存储在 `.tasks` 索引中时,API 才会返回其信息。OpenSearch 仅为使用 `wait_for_completion=false` 启动的操作存储任务结果。对于已完成但未存储其结果的任务,API 会返回错误。 + +## 示例请求 + +要获取任务 ID,请使用 `wait_for_completion=false` 启动长时间运行的操作,例如重新索引或按查询更新。以下请求启动限流重新索引操作: + +```json +POST /_reindex?wait_for_completion=false&requests_per_second=50 +{ + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-dest-index" + } +} +``` + +响应包含任务 ID: + +```json +{ + "task": "6It0uQ1AR06IDC4nMstPQw:1822891" +} +``` + +或者,使用[列出任务 API](/api-reference/tasks/list-tasks) 查找正在运行的任务的 ID,例如 `GET /_tasks?actions=*reindex`。 + +以下请求返回有关该任务的信息: + +```json +GET /_tasks/<task_id> +``` + +## 示例响应 + +当任务正在运行时,响应包含 `"completed": false` 和当前任务状态: + +```json +{ + "completed": false, + "task": { + "node": "6It0uQ1AR06IDC4nMstPQw", + "id": 1822891, + "type": "transport", + "action": "indices:data/write/reindex", + "status": { + "total": 2000, + "updated": 0, + "created": 1000, + "deleted": 0, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": 50.0, + "throttled_until_millis": 16963 + }, + "description": "reindex from [my-source-index] to [my-dest-index]", + "start_time_in_millis": 1792185761839, + "running_time_in_nanos": 3241833543, + "cancellable": true, + "cancelled": false, + "headers": {}, + "resource_stats": { + "average": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "total": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "min": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "max": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "thread_info": { + "thread_executions": 0, + "active_threads": 0 + } + } + } +} +``` + +任务完成后,响应包含 `"completed": true` 和 `response` 对象中操作的存储结果: + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "completed": true, + "task": { + "node": "6It0uQ1AR06IDC4nMstPQw", + "id": 1822891, + "type": "transport", + "action": "indices:data/write/reindex", + "status": { + "total": 2000, + "updated": 0, + "created": 2000, + "deleted": 0, + "batches": 2, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 39999, + "requests_per_second": 50.0, + "throttled_until_millis": 0 + }, + "description": "reindex from [my-source-index] to [my-dest-index]", + "start_time_in_millis": 1792185761839, + "running_time_in_nanos": 40289441643, + "cancellable": true, + "cancelled": false, + "headers": {} + }, + "response": { + "took": 40286, + "timed_out": false, + "total": 2000, + "updated": 0, + "created": 2000, + "deleted": 0, + "batches": 2, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled": "39.9s", + "throttled_millis": 39999, + "requests_per_second": 50.0, + "throttled_until": "0s", + "throttled_until_millis": 0, + "failures": [] + } +} +``` +</details> + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `completed` | Boolean | 任务是否已完成。 | +| `task` | Object | 有关任务的信息。请参阅 [`task` 对象](#the-task-object)。 | +| `response` | Object | 操作的结果。仅对已完成或已取消且其结果已存储的任务返回。对象内容取决于操作。例如,重新索引任务返回与[重新索引 API](/api-reference/document-apis/reindex) 响应相同的字段。对于已取消的任务,该对象还包含一个 `canceled` 字段,指定取消的原因。 | +| `error` | Object | 导致任务失败的错误。仅对失败且其结果已存储的任务返回。 | + +### `task` 对象 + +`task` 对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `node` | String | 运行任务的节点的 ID。 | +| `id` | Integer | 节点上的任务 ID。完整任务 ID 的格式为 `<node>:<id>`。 | +| `type` | String | 任务类型,例如 `transport`。 | +| `action` | String | 任务执行的操作,例如 `indices:data/write/reindex`。 | +| `status` | Object | 任务的当前状态。对象内容取决于操作。例如,重新索引任务报告已处理的文档数和限流信息。并非所有操作都返回。 | +| `description` | String | 任务的描述,例如重新索引操作的源索引和目标索引。 | +| `start_time_in_millis` | Long | 任务开始的时间,以自纪元以来的毫秒数表示。 | +| `running_time_in_nanos` | Long | 任务已运行的时间,以纳秒为单位。 | +| `cancellable` | Boolean | 任务是否可以取消。 | +| `cancelled` | Boolean | 任务是否已被取消。 | +| `cancellation_time_millis` | Long | 任务被取消的时间,以自纪元以来的毫秒数表示。仅对已取消的任务返回。 | +| `parent_task_id` | String | 父任务的 ID。仅对子任务返回,例如切片重新索引操作的切片。 | +| `headers` | Object | 启动任务的请求的跟踪请求标头,例如 `X-Opaque-Id`。不包括其他请求标头。 | +| `resource_stats` | Object | 任务的资源使用统计信息。仅对支持资源跟踪的正在运行的任务返回。请参阅 [`resource_stats` 对象](#the-resource_stats-object)。 | + +### `resource_stats` 对象 + +`resource_stats` 对象仅对支持资源跟踪的任务更新。这些统计信息是基于已调度的线程执行计算的,包括已完成任务工作的线程和当前正在处理任务的线程。由于同一线程可能被多次调度来处理同一任务,因此将给定线程被调度来处理给定任务的每个实例视为单个线程执行。 + +`resource_stats` 对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `average` | Object | 所有已调度线程执行的平均资源使用量。 | +| `total` | Object | 所有已调度线程执行的总资源使用量。 | +| `min` | Object | 所有已调度线程执行的最小资源使用量。 | +| `max` | Object | 所有已调度线程执行的最大资源使用量。 | +| `thread_info` | Object | 与线程计数相关的统计信息。 | + +每个 `average`、`total`、`min` 和 `max` 对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `cpu_time_in_nanos` | Long | 使用的 CPU 时间,以纳秒为单位。 | +| `memory_in_bytes` | Long | 使用的内存量,以字节为单位。 | + +`thread_info` 对象包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `thread_executions` | Integer | 已被调度来处理任务的线程数。 | +| `active_threads` | Integer | 当前正在处理任务的线程数。 | + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`cluster:monitor/tasks/get`。 diff --git a/i18n/zh/api-reference/tasks/list-tasks.md b/i18n/zh/api-reference/tasks/list-tasks.md new file mode 100644 index 00000000..eb48cbfe --- /dev/null +++ b/i18n/zh/api-reference/tasks/list-tasks.md @@ -0,0 +1,121 @@ +--- +title: List tasks +--- + +# 列出任务 API +<Badge type="tip" text="引入版本 1.0" /> + +列出任务 API 返回集群中正在运行的任务列表。 + +<!-- spec_insert_start +api: tasks.list +component: endpoints +--> +## 端点 +```json +GET /_tasks +``` +<!-- spec_insert_end --> + +<!-- spec_insert_start +api: tasks.list +component: query_parameters +--> +## 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | 默认值 | +| :--- | :--- | :--- | :--- | +| `actions` | List or String | 应返回的以逗号分隔的操作列表。保持为空以返回所有操作。 | 无 | +| `detailed` | Boolean | 当为 `true` 时,响应包含有关分片恢复的详细信息。 | `false` | +| `group_by` | String | 按父/子关系或节点对任务进行分组。<br>有效值为:`nodes`、`none` 和 `parents`。 | `nodes` | +| `nodes` | List | 用于限制返回信息的以逗号分隔的节点 ID 或名称列表。使用 `_local` 返回您正在连接的节点的信息,指定节点名称以获取特定节点的信息,或保持参数为空以获取所有节点的信息。 | 无 | +| `parent_task_id` | String | 返回具有指定父任务 ID(`node_id:task_number`)的任务。保持为空或设置为 -1 以返回所有任务。 | 无 | +| `timeout` | String | 等待响应的时间。 | 无 | +| `wait_for_completion` | Boolean | 等待匹配的任务完成。当为 `true` 时,请求将被阻塞,直到任务完成。 | `false` | + +<!-- spec_insert_end --> + +## 示例请求 + +以下请求返回当前在名为 `opensearch-node1` 的节点上运行的任务: + +<!-- spec_insert_start +component: example_code +rest: GET /_tasks?nodes=opensearch-node1 +--> + +GET /_tasks?nodes=opensearch-node1 + +response = client.tasks.list( + params = { "nodes": "opensearch-node1" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下响应提供有关正在运行的任务的信息: + +```json +{ + "nodes": { + "Mgqdm0r9SEGClWxp_RbnaQ": { + "name": "opensearch-node1", + "transport_address": "sample_address", + "host": "sample_host", + "ip": "sample_ip", + "roles": [ + "data", + "ingest", + "master", + "remote_cluster_client" + ], + "tasks": { + "Mgqdm0r9SEGClWxp_RbnaQ:24578": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 24578, + "type": "transport", + "action": "cluster:monitor/tasks/lists", + "start_time_in_millis": 1611612517044, + "running_time_in_nanos": 638700, + "cancellable": false, + "headers": {} + }, + "Mgqdm0r9SEGClWxp_RbnaQ:24579": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 24579, + "type": "direct", + "action": "cluster:monitor/tasks/lists[n]", + "start_time_in_millis": 1611612517044, + "running_time_in_nanos": 222200, + "cancellable": false, + "parent_task_id": "Mgqdm0r9SEGClWxp_RbnaQ:24578", + "headers": {} + } + } + } + } +} +``` + +### `resource_stats` 对象 + +`resource_stats` 对象仅对支持资源跟踪的任务更新。这些统计信息是基于已调度的线程执行计算的,包括已完成任务工作的线程和当前正在处理任务的线程。由于同一线程可能被多次调度来处理同一任务,因此将给定线程被调度来处理给定任务的每个实例视为单个线程执行。 + +下表列出了 `resource_stats` 对象中的所有响应字段。 + +响应字段 | 描述 | +:--- | :--- | +`average` | 所有已调度线程执行的平均资源使用量。 | +`total` | 所有已调度线程执行的总资源使用量。 | +`min` | 所有已调度线程执行的最小资源使用量。 | +`max` | 所有已调度线程执行的最大资源使用量。 | +`thread_info` | 与线程计数相关的统计信息。| +`thread_info.active_threads` | 当前正在处理任务的线程数。 | +`thread_info.thread_executions` | 已被调度来处理任务的线程数。 | + +## 所需权限 + +如果您使用 Security 插件,请确保您具有适当的权限:`cluster:monitor/tasks/list`。 diff --git a/i18n/zh/api-reference/tasks/rethrottle.md b/i18n/zh/api-reference/tasks/rethrottle.md new file mode 100644 index 00000000..4ab24b5a --- /dev/null +++ b/i18n/zh/api-reference/tasks/rethrottle.md @@ -0,0 +1,192 @@ +--- +title: Rethrottle task +--- + +# 重新限流任务 API +<Badge type="tip" text="引入版本 1.0" /> + +您可以使用以下 API 动态更改已经运行的 [`_reindex`](/api-reference/document-apis/reindex)、[`_update_by_query`](/api-reference/document-apis/update-by-query) 或 [`_delete_by_query`](/api-reference/document-apis/delete-by-query) 操作的 `requests_per_second`。 + +## 端点 + +```json +POST /_delete_by_query/{task_id}/_rethrottle +POST /_reindex/{task_id}/_rethrottle +POST /_update_by_query/{task_id}/_rethrottle +``` + +## 路径参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`task_id` | String | 要重新限流的正在运行的任务的唯一标识符。 + +## 查询参数 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`requests_per_second` | Float | 要应用于任务的新限流值。使用 `-1` 禁用限流。可选。 + +### 示例请求:重新限流正在运行的按查询删除任务 + +<!-- spec_insert_start +component: example_code +rest: POST /_delete_by_query/<YOUR_TASK_ID>/_rethrottle?requests_per_second=10 +--> + +POST /_delete_by_query/<YOUR_TASK_ID>/_rethrottle?requests_per_second=10 + +response = client.delete_by_query_rethrottle( + task_id = "<YOUR_TASK_ID>", + params = { "requests_per_second": "10" } +) + +<!-- spec_insert_end --> + +### 示例请求:重新限流正在运行的重新索引任务 + +<!-- spec_insert_start +component: example_code +rest: POST /_reindex/<YOUR_TASK_ID>/_rethrottle?requests_per_second=20 +--> + +POST /_reindex/<YOUR_TASK_ID>/_rethrottle?requests_per_second=20 + +response = client.reindex_rethrottle( + task_id = "<YOUR_TASK_ID>", + params = { "requests_per_second": "20" } +) + +<!-- spec_insert_end --> + +### 示例请求:重新限流正在运行的按查询更新任务 + +<!-- spec_insert_start +component: example_code +rest: POST /_update_by_query/<YOUR_TASK_ID>/_rethrottle?requests_per_second=5 +--> + +POST /_update_by_query/<YOUR_TASK_ID>/_rethrottle?requests_per_second=5 + +response = client.update_by_query_rethrottle( + task_id = "<YOUR_TASK_ID>", + params = { "requests_per_second": "5" } +) + +<!-- spec_insert_end --> + +## 示例响应 + +以下响应提供有关活动的 `update_by_query` 任务的详细信息: + +``` +{ + "nodes": { + "bvv8SKpiRhOhF9_Bu8gZ7w": { + "name": "opensearch-node1", + "transport_address": "172.18.0.4:9300", + "host": "172.18.0.4", + "ip": "172.18.0.4:9300", + "roles": [ + "cluster_manager", + "data", + "ingest", + "remote_cluster_client" + ], + "attributes": { + "shard_indexing_pressure_enabled": "true" + }, + "tasks": { + "bvv8SKpiRhOhF9_Bu8gZ7w:640": { + "node": "bvv8SKpiRhOhF9_Bu8gZ7w", + "id": 640, + "type": "transport", + "action": "indices:data/write/update/byquery", + "status": { + "total": 4785, + "updated": 1000, + "created": 0, + "deleted": 0, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": 50, + "throttled_until_millis": 2146 + }, + "description": "update-by-query [test-rethrottle] updated with Script{type=inline, lang='painless', idOrCode='ctx._source.new_field = 'updated'', options={}, params={}}", + "start_time_in_millis": 1751310547697, + "running_time_in_nanos": 9567425129, + "cancellable": true, + "cancelled": false, + "headers": { + "X-Opaque-Id": "1b911516-44cd-4920-8c1e-79368ea7cdfd" + }, + "resource_stats": { + "average": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "total": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "min": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "max": { + "cpu_time_in_nanos": 0, + "memory_in_bytes": 0 + }, + "thread_info": { + "thread_executions": 0, + "active_threads": 0 + } + } + } + } + } + } +} +``` + +## 响应体字段 + +响应提供有关重新限流操作的详细任务和节点级别信息。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `nodes` | Object | 节点 ID 到每个节点上任务详细信息的映射。 | +| `nodes.<node_id>.name` | String | 运行任务的节点的名称。 | +| `nodes.<node_id>.transport_address` | String | 节点的传输地址。 | +| `nodes.<node_id>.host` | String | 主机 IP 地址。 | +| `nodes.<node_id>.ip` | String | IP 地址和端口。 | +| `nodes.<node_id>.roles` | Array | 分配给节点的角色。 | +| `nodes.<node_id>.attributes` | Object | 节点级别的属性。 | +| `nodes.<node_id>.tasks` | Object | 任务 ID 到每个任务详细信息的映射。 | +| `nodes.<node_id>.tasks.<task_id>.type` | String | 任务类型,例如 `transport`。 | +| `nodes.<node_id>.tasks.<task_id>.action` | String | 正在执行的特定操作(例如,`reindex`)。 | +| `nodes.<node_id>.tasks.<task_id>.status` | Object | 任务的当前状态。 | +| `nodes.<node_id>.tasks.<task_id>.status.total` | Integer | 要处理的文档总数。 | +| `nodes.<node_id>.tasks.<task_id>.status.created` | Integer | 创建的文档数。 | +| `nodes.<node_id>.tasks.<task_id>.status.updated` | Integer | 更新的文档数。 | +| `nodes.<node_id>.tasks.<task_id>.status.deleted` | Integer | 删除的文档数。 | +| `nodes.<node_id>.tasks.<task_id>.status.batches` | Integer | 已处理的批次数。 | +| `nodes.<node_id>.tasks.<task_id>.status.version_conflicts` | Integer | 版本冲突的数量。 | +| `nodes.<node_id>.tasks.<task_id>.status.noops` | Integer | 无操作更新的数量。 | +| `nodes.<node_id>.tasks.<task_id>.status.retries` | Object | 批量和搜索操作的重试统计信息。 | +| `nodes.<node_id>.tasks.<task_id>.status.requests_per_second` | Float | 当前每秒请求数的限流速率。 | +| `nodes.<node_id>.tasks.<task_id>.status.throttled_millis` | Integer | 任务被限流的时间(以毫秒为单位)。 | +| `nodes.<node_id>.tasks.<task_id>.status.throttled_until_millis` | Integer | 任务预计保持限流的时间(以毫秒为单位)。 | +| `nodes.<node_id>.tasks.<task_id>.description` | String | 任务的人类可读描述。 | +| `nodes.<node_id>.tasks.<task_id>.start_time_in_millis` | Integer | 任务开始时间(纪元毫秒)。 | +| `nodes.<node_id>.tasks.<task_id>.running_time_in_nanos` | Integer | 任务运行时间(纳秒)。 | +| `nodes.<node_id>.tasks.<task_id>.cancellable` | Boolean | 任务是否可以取消。 | +| `nodes.<node_id>.tasks.<task_id>.cancelled` | Boolean | 任务是否已被取消。 | +| `nodes.<node_id>.tasks.<task_id>.headers` | Object | 与任务关联的可选 HTTP 标头。 | +| `nodes.<node_id>.tasks.<task_id>.resource_stats` | Object | 有关资源使用的统计信息。 | diff --git a/i18n/zh/api-reference/tasks/tasks.md b/i18n/zh/api-reference/tasks/tasks.md new file mode 100644 index 00000000..dc979383 --- /dev/null +++ b/i18n/zh/api-reference/tasks/tasks.md @@ -0,0 +1,76 @@ +--- +title: Tasks APIs +--- + +# 任务 API +<Badge type="tip" text="引入版本 1.0" /> + +_任务_是您在集群中运行的任何操作。例如,在您的图书数据集合中搜索书名或作者名称就是一个任务。当您运行 OpenSearch 时,会自动创建一个任务来监控集群的运行状况和性能。有关集群中当前执行的所有任务的更多信息,您可以使用 `tasks` API 操作。 + +## 将标头附加到任务 + +为了更好地跟踪,将请求与任务关联,您可以在 `curl` 命令的 HTTPS 请求读取器中提供 `X-Opaque-Id:<ID_number>` 标头。API 将在返回的结果中附加指定的标头。 + +以下请求返回 `X-Opaque-Id` 为 `111111` 的任务: + +```bash +curl -i -H "X-Opaque-Id: 111111" "https://localhost:9200/_tasks" -u 'admin:<custom-admin-password>' --insecure +``` + +`_tasks` 操作返回以下结果: + +```json +HTTP/1.1 200 OK +X-Opaque-Id: 111111 +content-type: application/json; charset=UTF-8 +content-length: 768 + +{ + "nodes": { + "Mgqdm0r9SEGClWxp_RbnaQ": { + "name": "opensearch-node1", + "transport_address": "172.18.0.4:9300", + "host": "172.18.0.4", + "ip": "172.18.0.4:9300", + "roles": [ + "data", + "ingest", + "master", + "remote_cluster_client" + ], + "tasks": { + "Mgqdm0r9SEGClWxp_RbnaQ:30072": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 30072, + "type": "direct", + "action": "cluster:monitor/tasks/lists[n]", + "start_time_in_millis": 1613166701725, + "running_time_in_nanos": 245400, + "cancellable": false, + "parent_task_id": "Mgqdm0r9SEGClWxp_RbnaQ:30071", + "headers": { + "X-Opaque-Id": "111111" + } + }, + "Mgqdm0r9SEGClWxp_RbnaQ:30071": { + "node": "Mgqdm0r9SEGClWxp_RbnaQ", + "id": 30071, + "type": "transport", + "action": "cluster:monitor/tasks/lists", + "start_time_in_millis": 1613166701725, + "running_time_in_nanos": 658200, + "cancellable": false, + "headers": { + "X-Opaque-Id": "111111" + } + } + } + } + } +} +``` +此操作支持与 `tasks` 操作相同的参数。以下示例显示如何将 `X-Opaque-Id` 与特定任务关联: + +```bash +curl -i -H "X-Opaque-Id: 123456" "https://localhost:9200/_tasks?nodes=opensearch-node1" -u 'admin:<custom-admin-password>' --insecure +``` diff --git a/i18n/zh/benchmark/FAQs.md b/i18n/zh/benchmark/FAQs.md new file mode 100644 index 00000000..5ed30e9d --- /dev/null +++ b/i18n/zh/benchmark/FAQs.md @@ -0,0 +1,23 @@ +--- +title: 常见问题 +--- + +# OpenSearch Benchmark 常见问题 + +本节提供常见问题的解答。 + +## 如何获取有关遇到的错误的更多信息? + +查看 OpenSearch Benchmark 日志文件的末尾,查看最近一次运行的消息。 + +如果您需要更多帮助,可以: +- [在 OpenSearch Benchmark Slack 频道发布问题](https://opensearch.slack.com/archives/C082PLA3VPW)。 +- [参加社区会议、办公时间或问题分类会议](https://www.meetup.com/opensearch/events/309982456/?eventOrigin=group_upcoming_events)。 + +## OpenSearch Benchmark 日志文件位于何处? + +默认情况下,OpenSearch Benchmark 日志文件位于您的主目录下,路径为 `$HOME/.osb/osb.log`。 + +## 我正在寻找 OpenSearch Benchmark 的最新更新。在哪里可以找到 OpenSearch Benchmark 的最新增量构建? + +当有任何新更改合并到代码库时,会生成 OpenSearch Benchmark 增量构建的 Docker 镜像。这些镜像可在 [OpenSearch Benchmark Docker Hub 页面](https://hub.docker.com/r/opensearchstaging/opensearch-benchmark/tags)获取。 diff --git a/i18n/zh/benchmark/anatomy-of-a-workload.md b/i18n/zh/benchmark/anatomy-of-a-workload.md new file mode 100644 index 00000000..5b1b28f0 --- /dev/null +++ b/i18n/zh/benchmark/anatomy-of-a-workload.md @@ -0,0 +1,806 @@ +--- +title: 工作负载剖析 +--- + +# 工作负载剖析 + +工作负载是一个或多个基准测试场景的规范。所有工作负载都包含以下文件和目录: + +- [`workload.json`](#workloadjson): 包含所有工作负载设置。 +- [`index.json`](#indexjson): 包含文档映射和参数以及索引设置。 +- [`files.txt`](#filestxt): 包含数据语料库文件名。 +- [`_test-procedures`](#_operations-和-_test-procedures): 大多数工作负载只包含一个默认测试程序,该程序在 `default.json` 中配置。 +- [`_operations`](#_operations-和-_test-procedures): 包含测试程序中使用的所有操作。 +- `workload.py`: 为测试添加更多动态功能。 + +<!-- vale off --> +## workload.json +<!-- vale on --> + +`workload.json` 文件通常包含以下元素: + +- [`indices`](/benchmark/reference/workloads/indices): 定义工作负载使用的相关索引和索引模板。要创建索引,请指定其 `name`。要向索引添加定义,请使用 `body` 选项并将其指向包含索引定义的 JSON 文件。 +- [`corpora`](/benchmark/reference/workloads/corpora): 定义工作负载使用的所有文档语料库,包括包含文档的源文件以及每个文件中的文档数量。 +- [`operations`](/benchmark/reference/workloads/operations): **可选**。列出工作负载执行的 OpenSearch API 操作以及它们的参数化方式。例如,您可以列出一个名为 `create-index` 的操作,该操作在基准测试集群中创建一个索引,OpenSearch Benchmark 可以向其中写入文档。 +- [`schedule`](/benchmark/reference/workloads/schedule): 内联定义操作及其运行顺序。或者,您可以使用 `operations` 对操作进行分组,并使用 [`test_procedures`](/benchmark/reference/workloads/test-procedures) 参数指定操作顺序。 + +以下示例工作负载展示了这些元素如何协同工作。您可以在自己的基准测试配置中运行此工作负载: + +```json +{ + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "iterations": 1000, + "target-throughput": 100 + } + ] +} +``` + +<!-- vale off --> +## index.json +<!-- vale on --> + +`index.json` 文件定义了工作负载文档在 `create-index` 操作期间的数据映射、索引参数和索引设置。 + +当 OpenSearch Benchmark 为工作负载创建索引时,它使用 `index.json` 文件中的索引设置和映射模板。`index.json` 文件中的映射基于工作负载语料库中单个文档的映射,该语料库存储在 `files.txt` 文件中。以下是 `nyc_taxis` 工作负载的 `index.json` 文件示例。您可以自定义字段,例如 `number_of_shards`、`number_of_replicas`、`query_cache_enabled` 和 `requests_cache_enabled`。 + +```json +{ + "settings": { + "index.number_of_shards": {{number_of_shards | default(1)}}, + "index.number_of_replicas": {{number_of_replicas | default(0)}}, + "index.queries.cache.enabled": {{query_cache_enabled | default(false) | tojson}}, + "index.requests.cache.enable": {{requests_cache_enabled | default(false) | tojson}} + }, + "mappings": { + "_source": { + "enabled": {{ source_enabled | default(true) | tojson }} + }, + "properties": { + "surcharge": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "dropoff_datetime": { + "type": "date", + "format": "yyyy-MM-dd HH:mm:ss" + }, + "trip_type": { + "type": "keyword" + }, + "mta_tax": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "rate_code_id": { + "type": "keyword" + }, + "passenger_count": { + "type": "integer" + }, + "pickup_datetime": { + "type": "date", + "format": "yyyy-MM-dd HH:mm:ss" + }, + "tolls_amount": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "tip_amount": { + "type": "half_float" + }, + "payment_type": { + "type": "keyword" + }, + "extra": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "vendor_id": { + "type": "keyword" + }, + "store_and_fwd_flag": { + "type": "keyword" + }, + "improvement_surcharge": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "fare_amount": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "ehail_fee": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "cab_color": { + "type": "keyword" + }, + "dropoff_location": { + "type": "geo_point" + }, + "vendor_name": { + "type": "text" + }, + "total_amount": { + "scaling_factor": 100, + "type": "scaled_float" + }, + "trip_distance": {%- if trip_distance_mapping is defined %} {{ trip_distance_mapping | tojson }} {%- else %} { + "scaling_factor": 100, + "type": "scaled_float" + }{%- endif %}, + "pickup_location": { + "type": "geo_point" + } + }, + "dynamic": "strict" + } +} +``` + +<!-- vale off --> +## files.txt +<!-- vale on --> + +`files.txt` 文件列出存储工作负载数据的文件,这些文件通常存储在压缩的 JSON 文件中。 + +<!-- vale off --> +## _operations 和 _test-procedures +<!-- vale on --> + +为了使工作负载更具可读性,`_operations` 和 `_test-procedures` 被分成两个目录。 + +`_operations` 目录包含一个 `default.json` 文件,该文件列出测试程序可以使用的所有支持的操作。某些工作负载,例如 `nyc_taxis`,包含额外的 `.json` 文件,该文件列出特定功能的操作,例如 `snapshot` 操作。以下 JSON 示例显示了来自 `nyc_taxis` 工作负载的操作列表: + +```json + { + "name": "index", + "operation-type": "bulk", + "bulk-size": {{bulk_size | default(10000)}}, + "ingest-percentage": {{ingest_percentage | default(100)}} + }, + { + "name": "update", + "operation-type": "bulk", + "bulk-size": {{bulk_size | default(10000)}}, + "ingest-percentage": {{ingest_percentage | default(100)}}, + "conflicts": "{{conflicts | default('random')}}", + "on-conflict": "{{on_conflict | default('update')}}", + "conflict-probability": {{conflict_probability | default(25)}}, + "recency": {{recency | default(0)}} + }, + { + "name": "wait-until-merges-finish", + "operation-type": "index-stats", + "index": "_all", + "condition": { + "path": "_all.total.merges.current", + "expected-value": 0 + }, + "retry-until-success": true, + "include-in-reporting": false + }, + { + "name": "default", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + { + "name": "range", + "operation-type": "search", + "body": { + "query": { + "range": { + "total_amount": { + "gte": 5, + "lt": 15 + } + } + } + } + }, + { + "name": "distance_amount_agg", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "bool": { + "filter": { + "range": { + "trip_distance": { + "lt": 50, + "gte": 0 + } + } + } + } + }, + "aggs": { + "distance_histo": { + "histogram": { + "field": "trip_distance", + "interval": 1 + }, + "aggs": { + "total_amount_stats": { + "stats": { + "field": "total_amount" + } + } + } + } + } + } + }, + { + "name": "autohisto_agg", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "01/01/2015", + "lte": "21/01/2015", + "format": "dd/MM/yyyy" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": 20 + } + } + } + } + }, + { + "name": "date_histogram_agg", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "01/01/2015", + "lte": "21/01/2015", + "format": "dd/MM/yyyy" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "calendar_interval": "day" + } + } + } + } + }, + { + "name": "date_histogram_calendar_interval", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "calendar_interval": "month" + } + } + } + } + }, + { + "name": "date_histogram_calendar_interval_with_tz", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "calendar_interval": "month", + "time_zone": "America/New_York" + } + } + } + } + }, + { + "name": "date_histogram_fixed_interval", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "fixed_interval": "60d" + } + } + } + } + }, + { + "name": "date_histogram_fixed_interval_with_tz", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "fixed_interval": "60d", + "time_zone": "America/New_York" + } + } + } + } + }, + { + "name": "date_histogram_fixed_interval_with_metrics", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "date_histogram": { + "field": "dropoff_datetime", + "fixed_interval": "60d" + }, + "aggs": { + "total_amount": { "stats": { "field": "total_amount" } }, + "tip_amount": { "stats": { "field": "tip_amount" } }, + "trip_distance": { "stats": { "field": "trip_distance" } } + } + } + } + } + }, + { + "name": "auto_date_histogram", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": "12" + } + } + } + } + }, + { + "name": "auto_date_histogram_with_tz", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": "13", + "time_zone": "America/New_York" + } + } + } + } + }, + { + "name": "auto_date_histogram_with_metrics", + "operation-type": "search", + "body": { + "size": 0, + "query": { + "range": { + "dropoff_datetime": { + "gte": "2015-01-01 00:00:00", + "lt": "2016-01-01 00:00:00" + } + } + }, + "aggs": { + "dropoffs_over_time": { + "auto_date_histogram": { + "field": "dropoff_datetime", + "buckets": "12" + }, + "aggs": { + "total_amount": { "stats": { "field": "total_amount" } }, + "tip_amount": { "stats": { "field": "tip_amount" } }, + "trip_distance": { "stats": { "field": "trip_distance" } } + } + } + } + } + }, + { + "name": "desc_sort_tip_amount", + "operation-type": "search", + "index": "nyc_taxis", + "body": { + "query": { + "match_all": {} + }, + "sort" : [ + {"tip_amount" : "desc"} + ] + } + }, + { + "name": "asc_sort_tip_amount", + "operation-type": "search", + "index": "nyc_taxis", + "body": { + "query": { + "match_all": {} + }, + "sort" : [ + {"tip_amount" : "asc"} + ] + } + } +``` + +`_test-procedures` 目录包含一个 `default.json` 文件,该文件设置工作负载执行的操作顺序。与 `_operations` 目录类似,`_test-procedures` 目录还可以包含特定功能的测试程序,例如 `nyc_taxis` 的 `searchable_snapshots.json`。以下示例显示了 `nyc_taxis` 的可搜索快照测试程序: + +```json + { + "name": "searchable-snapshot", + "description": "Measuring performance for Searchable Snapshot feature. Based on the default test procedure 'append-no-conflicts'.", + "schedule": [ + { + "operation": "delete-index" + }, + { + "operation": { + "operation-type": "create-index", + "settings": {%- if index_settings is defined %} {{ index_settings | tojson }} {%- else %}{ + "index.codec": "best_compression", + "index.refresh_interval": "30s", + "index.translog.flush_threshold_size": "4g" + }{%- endif %} + } + }, + { + "name": "check-cluster-health", + "operation": { + "operation-type": "cluster-health", + "index": "nyc_taxis", + "request-params": { + "wait_for_status": "{{ cluster_health | default('green') }}", + "wait_for_no_relocating_shards": "true" + }, + "retry-until-success": true + } + }, + { + "operation": "index", + "warmup-time-period": 240, + "clients": {{ bulk_indexing_clients | default(8) }}, + "ignore-response-error-level": "{{ error_level | default('non-fatal') }}" + }, + { + "name": "refresh-after-index", + "operation": "refresh" + }, + { + "operation": { + "operation-type": "force-merge", + "request-timeout": 7200 + {%- if force_merge_max_num_segments is defined %}, + "max-num-segments": {{ force_merge_max_num_segments | tojson }} + {%- endif %} + } + }, + { + "name": "refresh-after-force-merge", + "operation": "refresh" + }, + { + "operation": "wait-until-merges-finish" + }, + { + "operation": "create-snapshot-repository" + }, + { + "operation": "delete-snapshot" + }, + { + "operation": "create-snapshot" + }, + { + "operation": "wait-for-snapshot-creation" + }, + { + "operation": { + "name": "delete-local-index", + "operation-type": "delete-index" + } + }, + { + "operation": "restore-snapshot" + }, + { + "operation": "default", + "warmup-iterations": 50, + "iterations": 100 + {%- if not target_throughput %} + ,"target-throughput": 3 + {%- elif target_throughput is string and target_throughput.lower() == 'none' %} + {%- else %} + ,"target-throughput": {{ target_throughput | tojson }} + {%- endif %} + {%-if search_clients is defined and search_clients %} + ,"clients": {{ search_clients | tojson}} + {%- endif %} + }, + { + "operation": "range", + "warmup-iterations": 50, + "iterations": 100 + {%- if not target_throughput %} + ,"target-throughput": 0.7 + {%- elif target_throughput is string and target_throughput.lower() == 'none' %} + {%- else %} + ,"target-throughput": {{ target_throughput | tojson }} + {%- endif %} + {%-if search_clients is defined and search_clients %} + ,"clients": {{ search_clients | tojson}} + {%- endif %} + }, + { + "operation": "distance_amount_agg", + "warmup-iterations": 50, + "iterations": 50 + {%- if not target_throughput %} + ,"target-throughput": 2 + {%- elif target_throughput is string and target_throughput.lower() == 'none' %} + {%- else %} + ,"target-throughput": {{ target_throughput | tojson }} + {%- endif %} + {%-if search_clients is defined and search_clients %} + ,"clients": {{ search_clients | tojson}} + {%- endif %} + }, + { + "operation": "autohisto_agg", + "warmup-iterations": 50, + "iterations": 100 + {%- if not target_throughput %} + ,"target-throughput": 1.5 + {%- elif target_throughput is string and target_throughput.lower() == 'none' %} + {%- else %} + ,"target-throughput": {{ target_throughput | tojson }} + {%- endif %} + {%-if search_clients is defined and search_clients %} + ,"clients": {{ search_clients | tojson}} + {%- endif %} + }, + { + "operation": "date_histogram_agg", + "warmup-iterations": 50, + "iterations": 100 + {%- if not target_throughput %} + ,"target-throughput": 1.5 + {%- elif target_throughput is string and target_throughput.lower() == 'none' %} + {%- else %} + ,"target-throughput": {{ target_throughput | tojson }} + {%- endif %} + {%-if search_clients is defined and search_clients %} + ,"clients": {{ search_clients | tojson}} + {%- endif %} + } + ] + } +``` + +## 工作负载示例 + +以下示例显示了完整的 `workload.json` 文件,您可以将其改编为自己的工作负载。 + +### 运行无限制 + +在以下示例中,OpenSearch Benchmark 对 `movies` 索引运行无限制批量索引操作 1 小时: + +```json +{ + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": "bulk", + "warmup-time-period": 120, + "time-period": 3600, + "clients": 8 + } +] +} +``` + +### 具有单个任务的工作负载 + +以下工作负载运行具有单个任务的基准测试: `match_all` 查询。由于没有指示 `clients`,因此只使用一个客户端。根据 [`schedule`](/benchmark/reference/workloads/schedule),工作负载以 10 次操作/秒的速度使用 1 个客户端运行 `match_all` 查询,使用 100 次迭代进行预热,并使用接下来的 100 次迭代来衡量基准测试: + +```json +{ + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "search", + "index": "_all", + "body": { + "query": { + "match_all": {} + } + } + }, + "warmup-iterations": 100, + "iterations": 100, + "target-throughput": 10 + } + ] +} +``` + +## 下一步 + +- 有关每个预打包工作负载的数据、集群要求和查询类型,请参阅[工作负载类型](/benchmark/workload-types)。 +- 有关创建自己的工作负载的信息,请参阅[创建自定义工作负载](/benchmark/creating-custom-workloads)。 diff --git a/i18n/zh/benchmark/choosing-a-workload.md b/i18n/zh/benchmark/choosing-a-workload.md new file mode 100644 index 00000000..d168af3a --- /dev/null +++ b/i18n/zh/benchmark/choosing-a-workload.md @@ -0,0 +1,22 @@ +--- +title: 选择工作负载 +--- + +# 选择工作负载 + +[`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) 存储库包含可用于运行基准测试的工作负载列表。使用与集群用例类似的工作负载可以在评估集群性能时节省时间和精力。 + +例如,假设您是一家拼车公司的系统架构师。作为拼车公司,您根据行程时间、位置和每次拼车相关的其他数据收集和存储数据。您可以使用 [nyc_taxis](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/nyc_taxis) 工作负载来对集群进行基准测试,因为工作负载中的数据与您收集的数据类似,而不是构建自定义工作负载并使用自己的数据,这需要额外的时间、精力和成本。 + +## 选择工作负载的标准 + +在决定哪个工作负载最适合对集群进行基准测试时,请考虑以下标准: + +- 集群的用例和集群的大小。小型集群通常包含 1--10 个节点,适用于开发环境。中型集群通常包含 11--50 个节点,用于更接近生产集群的测试环境。 +- 集群使用的数据类型与工作负载中包含的文档的数据结构的比较。每个工作负载都包含一个示例文档,以便您可以比较数据类型,或者您可以在 `index.json` 文件中查看索引映射和数据类型。 +- 集群内最常用的查询类型。`operations/default.json` 文件包含有关查询类型和工作负载操作的信息。有关常见操作的列表,请参阅[常见操作](/benchmark/common-operations)。 + +## 后续步骤 + +- 有关每个预打包工作负载的数据、集群要求和查询类型,请参阅[工作负载类型](/benchmark/workload-types)。 +- 如果找不到适合您需求的官方工作负载,可以创建自定义工作负载。有关更多信息,请参阅[创建自定义工作负载](/benchmark/creating-custom-workloads)。 diff --git a/i18n/zh/benchmark/common-operations.md b/i18n/zh/benchmark/common-operations.md new file mode 100644 index 00000000..1f5af8d4 --- /dev/null +++ b/i18n/zh/benchmark/common-operations.md @@ -0,0 +1,172 @@ +--- +title: 常见操作 +--- + +# 常见操作 + +[测试程序](/benchmark/reference/workloads/test-procedures)使用各种操作,这些操作位于工作负载的 `operations` 目录中。本页详细介绍了 OpenSearch Benchmark 工作负载中最常见的操作。 + +- [常见操作](#常见操作) + - [bulk](#bulk) + - [create-index](#create-index) + - [delete-index](#delete-index) + - [cluster-health](#cluster-health) + - [refresh](#refresh) + - [search](#search) + +<!-- vale off --> +## bulk +<!-- vale on --> + +`bulk` 操作类型允许您将[批量](/api-reference/document-apis/bulk)请求作为任务运行。 + +以下示例显示了 `bulk-size` 为 `5000` 个文档的 `bulk` 操作类型: + +```yml +{ + "name": "index-append", + "operation-type": "bulk", + "bulk-size": 5000 +} +``` + +<!-- vale off --> +## create-index +<!-- vale on --> + +`create-index` 操作运行[创建索引 API](/api-reference/index-apis/create-index)。它支持以下两种索引创建模式: + +- 创建工作负载 `indices` 部分中指定的所有索引 +- 创建在操作本身中定义的一个特定索引 + +以下示例创建工作负载的 `indices` 部分中定义的所有索引。它使用工作负载中定义的所有索引设置,但覆盖分片数量: + +```yml +{ + "name": "create-all-indices", + "operation-type": "create-index", + "settings": { + "index.number_of_shards": 1 + }, + "request-params": { + "wait_for_active_shards": "true" + } +} +``` + +以下示例创建一个新索引,其中所有索引设置都在操作主体中指定: + +```yml +{ + "name": "create-an-index", + "operation-type": "create-index", + "index": "people", + "body": { + "settings": { + "index.number_of_shards": 0 + }, + "mappings": { + "docs": { + "properties": { + "name": { + "type": "text" + } + } + } + } + } +} +``` + +<!-- vale off --> +## delete-index +<!-- vale on --> + +`delete-index` 操作运行[删除索引 API](/api-reference/index-apis/delete-index)。与 [`create-index`](#create-index) 操作类似,您可以删除工作负载的 `indices` 部分中找到的所有索引,或根据 `index` 设置中传递的字符串删除一个或多个索引。 + +以下示例删除工作负载的 `indices` 部分中找到的所有索引: + +```yml +{ + "name": "delete-all-indices", + "operation-type": "delete-index" +} +``` + +以下示例删除所有 `logs_*` 索引: + +```yml +{ + "name": "delete-logs", + "operation-type": "delete-index", + "index": "logs-*", + "only-if-exists": false, + "request-params": { + "expand_wildcards": "all", + "allow_no_indices": "true", + "ignore_unavailable": "true" + } +} +``` + +<!-- vale off --> +## cluster-health +<!-- vale on --> + +`cluster-health` 操作运行[集群健康 API](/api-reference/cluster-api/cluster-health),它检查集群健康状态,并根据为 `request-params` 设置的参数返回预期状态。如果返回意外的集群健康状态,操作将报告失败。您可以在 OpenSearch Benchmark `run` 命令中使用 `--on-error` 选项来控制健康检查失败时 OpenSearch Benchmark 的行为。 + +以下示例创建一个 `cluster-health` 操作,检查任何 `log-*` 索引上的 `green` 健康状态: + +```yml +{ + "name": "check-cluster-green", + "operation-type": "cluster-health", + "index": "logs-*", + "request-params": { + "wait_for_status": "green", + "wait_for_no_relocating_shards": "true" + }, + "retry-until-success": true +} + +``` + +<!-- vale off --> +## refresh +<!-- vale on --> + +`refresh` 操作运行刷新 API。该 `operation` 不返回元数据。 + +以下示例刷新所有 `logs-*` 索引: + +```yml +{ + "name": "refresh", + "operation-type": "refresh", + "index": "logs-*" +} +``` + +<!-- vale off --> +## search +<!-- vale on --> + +`search` 操作运行[搜索 API](/api-reference/search),您可以使用它在 OpenSearch Benchmark 索引中运行查询。 + +以下示例在 `search` 操作中运行 `match_all` 查询: + +```yml +{ + "name": "default", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + }, + "request-params": { + "_source_include": "some_field", + "analyze_wildcard": "false" + } +} +``` diff --git a/i18n/zh/benchmark/contributing-workloads.md b/i18n/zh/benchmark/contributing-workloads.md new file mode 100644 index 00000000..6a3ff059 --- /dev/null +++ b/i18n/zh/benchmark/contributing-workloads.md @@ -0,0 +1,54 @@ +--- +title: 共享自定义工作负载 +--- + +# 共享自定义工作负载 + +您可以通过将自定义工作负载上传到 GitHub 上的[工作负载仓库](https://github.com/opensearch-project/opensearch-benchmark-workloads/)来与其他 OpenSearch 用户共享。 + +确保工作负载数据集中包含的任何数据不包含专有数据或个人身份信息 (PII)。 + +要共享自定义工作负载,请按照以下步骤操作。 + +## 创建 README.md + +提供详细的 `README.MD` 文件,其中包括以下内容: + +- 工作负载的用途。在为工作负载创建描述时,请考虑其具体用途以及该用例与[工作负载仓库](https://github.com/opensearch-project/opensearch-benchmark-workloads/)中其他用例的区别。 +- 来自数据集的示例文档,帮助用户了解数据结构。 +- 可用于自定义工作负载的工作负载参数。 +- 工作负载中包含的默认测试程序列表以及工作负载可以运行的其他测试程序。 +- 测试运行后工作负载产生的输出示例。 +- 开源许可证副本,该许可证授予用户和 OpenSearch Benchmark 使用数据集的权限。 + +有关示例工作负载 `README` 文件,请转到 `http_logs` [`README`](https://github.com/opensearch-project/opensearch-benchmark-workloads/blob/main/http_logs/README.md)。 + +## 验证工作负载的结构 + +工作负载必须包含以下文件: + +- `workload.json` +- `index.json` +- `files.txt` +- `test_procedures/default.json` +- `operations/default.json` + +两个 `default.json` 文件名都可以自定义为具有描述性的名称。工作负载可以包含可选的 `workload.py` 文件以添加更多动态功能。有关文件内容的更多信息,请转到[工作负载剖析](/benchmark/anatomy-of-a-workload)。 + +## 测试工作负载 + +贡献给 OpenSearch Benchmark 的所有工作负载必须满足以下测试要求: + +- 运行以探索和生成工作负载示例的所有测试都必须针对 OpenSearch 集群。 +- 工作负载必须通过所有集成测试。按照以下步骤确保工作负载通过集成测试: + 1. 将工作负载添加到[工作负载仓库](https://github.com/opensearch-project/opensearch-benchmark-workloads/)的分支副本中。确保您已经分支了 `opensearch-benchmark-workloads` 仓库和 [OpenSeach Benchmark](https://github.com/opensearch-project/opensearch-benchmark) 仓库。 + 3. 在您分支的 OpenSearch Benchmark 仓库中,更新 `/osbenchmark/it/resources` 目录中的 `benchmark-os-it.ini` 和 `benchmark-in-memory.ini` 文件,使其指向包含您的工作负载的分支工作负载仓库。 + 4. 修改 `.ini` 文件后,将更改提交到分支以进行测试。 + 6. 通过选择您提交更改的分支,使用 GitHub actions 运行集成测试。验证测试是否按预期运行。 + 7. 如果集成测试按预期运行,请转到分支的工作负载仓库,并将工作负载更改合并到分支 `1` 和 `2`。这允许您的工作负载出现在 OpenSearch Benchmark 的两个主要版本中。 + +## 创建 PR + +测试工作负载后,从您的分支创建一个拉取请求 (PR) 到 `opensearch-project` [工作负载仓库](https://github.com/opensearch-project/opensearch-benchmark-workloads/)。将示例输出和摘要结果添加到 PR 描述中。OpenSearch Benchmark 维护者将审查 PR。 + +PR 获得批准后,您必须共享数据集的数据语料库。然后,OpenSearch Benchmark 团队可以将数据集添加到共享的 S3 存储桶中。如果您的数据语料库存储在 S3 存储桶中,则可以使用 [AWS DataSync](https://docs.aws.amazon.com/datasync/latest/userguide/create-s3-location.html) 共享数据语料库。否则,您必须告知维护者数据语料库的位置。 diff --git a/i18n/zh/benchmark/creating-custom-workloads.md b/i18n/zh/benchmark/creating-custom-workloads.md new file mode 100644 index 00000000..4940d1fc --- /dev/null +++ b/i18n/zh/benchmark/creating-custom-workloads.md @@ -0,0 +1,373 @@ +--- +title: 创建自定义工作负载 +--- + +# 创建自定义工作负载 + +OpenSearch Benchmark 包含一组[工作负载](https://github.com/opensearch-project/opensearch-benchmark-workloads),您可以使用它们对集群中的数据进行基准测试。您还可以使用以下选项之一创建针对您自己的数据量身定制的工作负载: + +- [从现有集群创建工作负载](#从现有集群创建工作负载) +- [在没有现有集群的情况下创建工作负载](#在没有现有集群的情况下创建工作负载) + +## 从现有集群创建工作负载 + +如果您已经有一个包含索引数据的 OpenSearch 集群,请使用以下步骤为您的集群创建自定义工作负载。 + +### 先决条件 + +在创建自定义 OpenSearch Benchmark 工作负载之前,请确保您具备以下先决条件: + +- 一个包含至少 1000 个文档的索引的 OpenSearch 集群。如果您的集群索引不包含至少 1000 个文档,工作负载仍然可以运行测试,但是,您不能使用 `--test-mode` 运行工作负载。 +- 您必须具有访问 OpenSearch 集群的正确权限。有关集群权限的更多信息,请参阅[权限](/security/access-control/permissions)。 + +### 自定义工作负载 + +要开始创建自定义 OpenSearch Benchmark 工作负载,请使用 `opensearch-benchmark create-workload` 命令。 + +```bash +opensearch-benchmark create-workload \ +--workload="<WORKLOAD NAME>" \ +--target-hosts="<CLUSTER ENDPOINT>" \ +--client-options="basic_auth_user:'<USERNAME>',basic_auth_password:'<PASSWORD>'" \ +--indices="<INDEXES TO GENERATE WORKLOAD FROM>" \ +--output-path="<LOCAL DIRECTORY PATH TO STORE WORKLOAD>" +``` + +在前面的示例中,将以下选项替换为特定于您现有集群的信息: + +- `--workload`: 自定义工作负载的自定义名称。 +- `--target-hosts:` 一个以逗号分隔的 host:port 对列表,集群从中提取数据。 +- `--client-options`: OpenSearch Benchmark 用于访问集群的基本身份验证客户端选项。 +- `--indices`: OpenSearch 集群中包含数据的一个或多个索引。 +- `--output-path`: OpenSearch Benchmark 创建工作负载及其配置文件的目录。 + +以下示例响应从包含名为 `movies-info` 的索引的集群创建名为 `movies` 的工作负载。`movies-info` 索引包含超过 2,000 个文档。 + +```bash + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +[INFO] You did not provide an explicit timeout in the client options. Assuming default of 10 seconds. +[INFO] Connected to OpenSearch cluster [380d8fd64dd85b5f77c0ad81b0799e1e] version [1.1.0]. + +Extracting documents for index [movies] for test mode... 1000/1000 docs [100.0% done] +Extracting documents for index [movies]... 2000/2000 docs [100.0% done] + +[INFO] Workload movies has been created. Run it with: opensearch-benchmark --workload-path=/Users/hoangia/Desktop/workloads/movies + +----------------------------------- +[INFO] ✅ SUCCESS (took 2 seconds) +----------------------------------- +``` + +作为工作负载创建的一部分,OpenSearch Benchmark 生成以下文件。您可以在 `--output-path` 选项指定的目录中访问它们。 + +- `workload.json`: 包含一般工作负载规范。 +- `<index>.json`: 包含提取的索引的映射和设置。 +- `<index>-documents.json`: 包含提取的索引中每个文档的源。任何带有 `-1k` 后缀的源仅包含工作负载的文档语料库的一小部分,仅在测试模式下运行工作负载时使用。 + +默认情况下,OpenSearch Benchmark 不包含用于生成查询的引用。由于您最了解您的数据,我们建议向 `workload.json` 添加与索引规范匹配的查询。使用以下 `match_all` 查询作为添加到工作负载的查询示例: + +```json +{ + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } +``` + +### 在没有现有集群的情况下创建工作负载 + +如果您想创建自定义工作负载但没有包含索引数据的现有 OpenSearch 集群,则可以通过直接构建工作负载源文件来创建工作负载。您所需要的只是可以导出为 JSON 格式的数据。 + +要使用源文件构建工作负载,请为工作负载创建一个目录并执行以下步骤: + +1. 构建一个 `<index>-documents.json` 文件,其中包含构成工作负载的文档语料库的文档行,并存储要提取并查询到集群中的所有数据。以下示例显示了 `movies-documents.json` 文件的前几行,其中包含有关著名电影的文档行: + + ```json + {"title": "Back to the Future", "director": "Robert Zemeckis", "revenue": "$212,259,762 USD", "rating": "8.5 out of 10", "image_url": "https://imdb.com/images/32"} + {"title": "Avengers: Endgame", "director": "Anthony and Joe Russo", "revenue": "$2,800,000,000 USD", "rating": "8.4 out of 10", "image_url": "https://imdb.com/images/2"} + {"title": "The Grand Budapest Hotel", "director": "Wes Anderson", "revenue": "$173,000,000 USD", "rating": "8.1 out of 10", "image_url": "https://imdb.com/images/65"} + {"title": "The Godfather: Part II", "director": "Francis Ford Coppola", "revenue": "$48,000,000 USD", "rating": "9 out of 10", "image_url": "https://imdb.com/images/7"} + ``` + +2. 在同一目录中,构建一个 `index.json` 文件。工作负载使用此文件作为 `<index>-documents.json` 中包含的文档的数据映射和索引设置的引用。以下示例创建特定于上一步骤中 `movie-documents.json` 数据的映射和设置: + + ```json + { + "settings": { + "index.number_of_replicas": 0 + }, + "mappings": { + "dynamic": "strict", + "properties": { + "title": { + "type": "text" + }, + "director": { + "type": "text" + }, + "revenue": { + "type": "text" + }, + "rating": { + "type": "text" + }, + "image_url": { + "type": "text" + } + } + } + } + ``` + +3. 接下来,构建一个 `workload.json` 文件,该文件提供工作负载的高级概述并确定工作负载如何运行基准测试。`workload.json` 文件包含以下部分: + + - `indices`: 定义要在 OpenSearch 集群中创建的索引的名称,使用上一步骤中创建的工作负载的 `index.json` 文件中的映射。 + - `corpora`: 定义语料库和源文件,包括: + - `document-count`: `<index>-documents.json` 中的文档数量。要获得准确的文档数量,请运行 `wc -l <index>-documents.json`。 + - `uncompressed-bytes`: 索引内的字节数。要获得准确的字节数,请在 macOS 上运行 `stat -f %z <index>-documents.json` 或在 GNU/Linux 上运行 `stat -c %s <index>-documents.json`。或者,运行 `ls -lrt | grep <index>-documents.json`。 + - `schedule`: 定义操作顺序和工作负载的可用测试程序。 + +以下示例 `workload.json` 文件提供了 `movies` 工作负载的入口点。`indices` 部分创建一个名为 `movies` 的索引。corpora 部分引用第一步中创建的源文件 `movie-documents.json`,并提供文档计数和未压缩字节数。最后,schedule 部分定义了调用工作负载时执行的一些操作,包括: + +- 删除任何名为 `movies` 的当前索引。 +- 基于 `movie-documents.json` 中的数据和 `index.json` 中的映射创建名为 `movies` 的索引。 +- 验证集群处于良好状态并且可以提取新索引。 +- 将 `workload.json` 中的数据语料库提取到集群中。 +- 查询结果。 + + ```json + { + "version": 2, + "description": "Tutorial benchmark for OpenSearch Benchmark", + "indices": [ + { + "name": "movies", + "body": "index.json" + } + ], + "corpora": [ + { + "name": "movies", + "documents": [ + { + "source-file": "movies-documents.json", + "document-count": 11658903, # Fetch document count from command line + "uncompressed-bytes": 1544799789 # Fetch uncompressed bytes from command line + } + ] + } + ], + "schedule": [ + { + "operation": { + "operation-type": "delete-index" + } + }, + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "operation-type": "force-merge" + } + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } + ``` + +corpora 部分引用第一步中创建的源文件 `movie-documents.json`,并提供文档计数和未压缩字节数。最后,schedule 部分定义了调用工作负载时执行的一些操作,包括: + +- 删除任何名为 `movies` 的当前索引。 +- 基于 `movie-documents.json` 中的数据和 `index.json` 中的映射创建名为 `movies` 的索引。 + - 验证集群处于良好状态并且可以提取新索引。 + - 将 `workload.json` 中的数据语料库提取到集群中。 + - 查询结果。 + +对于创建的所有工作负载文件,通过运行测试来验证工作负载是否正常工作。要验证工作负载,请运行以下命令,将 `--workload-path` 替换为工作负载目录的路径: + +```bash +opensearch-benchmark list workloads --workload-path=</path/to/workload/> +``` + +## 调用自定义工作负载 + +使用 `opensearch-benchmark run` 命令调用新工作负载并对 OpenSearch 集群运行基准测试,如以下示例所示。将 `--workload-path` 替换为自定义工作负载的路径,将 `--target-host` 替换为集群的 `host:port` 对,将 `--client-options` 替换为访问集群所需的任何授权选项。 + +```bash +opensearch-benchmark run \ +--pipeline="benchmark-only" \ +--workload-path="<PATH OUTPUTTED IN THE OUTPUT OF THE CREATE-WORKLOAD COMMAND>" \ +--target-host="<CLUSTER ENDPOINT>" \ +--client-options="basic_auth_user:'<USERNAME>',basic_auth_password:'<PASSWORD>'" +``` + +测试结果显示在 `workloads.json` 中由 `--output-path` 选项设置的目录中。 + +## 高级选项 + +您可以使用以下高级选项增强自定义工作负载的功能。 + +### 测试模式 + +如果您想在测试模式下运行测试以确保工作负载按预期运行,请将 `--test-mode` 选项添加到 `run` 命令。测试模式仅从提供的每个索引中提取前 1,000 个文档,并对它们运行查询操作。 + +要使用测试模式,请使用以下命令创建一个包含 `<index>-documents.json` 中前 1000 个文档的 `<index>-documents-1k.json` 文件: + +```bash +head -n 1000 <index>-documents.json > <index>-documents-1k.json +``` + +然后,使用 `--test-mode` 选项运行 `opensearch-benchmark run`。测试模式运行工作负载测试的快速版本。 + +```bash +opensearch-benchmark run \ +--pipeline="benchmark-only" \ +--workload-path="<PATH OUTPUTTED IN THE OUTPUT OF THE CREATE-WORKLOAD COMMAND>" \ +--target-host="<CLUSTER ENDPOINT>" \ +--client-options"basic_auth_user:'<USERNAME>',basic_auth_password:'<PASSWORD>'" \ +--test-mode +``` + +### 向测试程序添加变化 + +在多次使用自定义工作负载后,您可能希望使用相同的工作负载,但以不同的顺序执行工作负载的操作。与其创建新的工作负载或直接重组程序,不如提供测试程序来改变工作负载操作。 + +要为工作负载操作添加变化,请转到 `workload.json` 文件并将 `schedule` 部分替换为 `test_procedures` 数组,如以下示例所示。数组中的每个项目包含以下内容: + +- `name`: 测试程序的名称。 +- `default`: 当设置为 `true` 时,如果没有指定其他测试程序,OpenSearch Benchmark 默认为工作负载中指定为 `default` 的测试程序。 +- `schedule`: 测试程序将运行的所有操作。 + +```json +"test_procedures": [ + { + "name": "index-and-query", + "default": true, + "schedule": [ + { + "operation": { + "operation-type": "delete-index" + } + }, + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "operation-type": "force-merge" + } + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 8, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] + } + ] +} +``` + +### 分离操作和测试程序 + +如果您想使 `workload.json` 文件更具可读性,可以将操作和测试程序分离到不同的目录中,并在 `workload.json` 中引用每个目录的路径。要分离操作和程序,请执行以下步骤: + +1. 将所有测试程序添加到单个文件中。您可以为文件指定任何名称。由于前面的 `movies` 工作负载包含索引任务和查询,因此此步骤将测试程序文件命名为 `index-and-query.json`。 +2. 将所有操作添加到名为 `operations.json` 的文件中。 +3. 通过添加以下语法在 `workloads.json` 中引用新文件,将 `parts` 替换为每个文件的相对路径,如以下示例所示: + + ```json + "operations": [ + {{ benchmark.collect(parts="operations/*.json") }} + ] + # Reference test procedure files in workload.json + "test_procedures": [ + {{ benchmark.collect(parts="test_procedures/*.json") }} + ] + ``` + +## 下一步 + +- 要调整工作负载以使其更接近您的生产环境,请参阅[微调自定义工作负载](/benchmark/finetune-workloads)。 +- 要将您的工作负载贡献给 OpenSearch 项目,请参阅[共享自定义工作负载](/benchmark/contributing-workloads)。 +- 有关配置 OpenSearch Benchmark 的更多信息,请参阅[配置 OpenSearch Benchmark](/benchmark/user-guide/configuring-benchmark)。 +- 要显示 OpenSearch Benchmark 的预打包工作负载列表,请参阅 [`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) 仓库。 diff --git a/i18n/zh/benchmark/distributed-load.md b/i18n/zh/benchmark/distributed-load.md new file mode 100644 index 00000000..8b8ed5e7 --- /dev/null +++ b/i18n/zh/benchmark/distributed-load.md @@ -0,0 +1,66 @@ +--- +title: 运行分布式负载 +--- + +# 运行分布式负载 + +OpenSearch Benchmark 负载始终在启动基准测试的同一台机器上运行。但是,您可以使用多个负载驱动程序来生成额外的基准测试负载,特别是对于跨多台机器的大型集群。本教程描述如何在单个集群中跨多台机器分布基准测试负载。 + +## 系统架构 + +以下教程使用三节点架构;每个节点在 [Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/ec2/?nc2=h_ql_doc_ec2) 中生成: + +- **节点 1**: 节点 1 充当_协调节点_,启用其他两个节点之间的分布和通信。 +- **节点 2** 和 **节点 3**: 集群中的其余节点用于生成基准测试的负载。 + +必须在所有节点上安装 OpenSearch Benchmark。有关安装说明,请参阅[安装 OpenSearch Benchmark](/benchmark/user-guide/installing-benchmark)。 + +记下每个节点的 IP 地址。本教程使用以下 IP 地址: + +- **节点 1 -- 协调节点**: 192.0.1.0 +- **节点 2 -- 工作节点**: 198.52.100.0 +- **节点 3 -- 工作节点**: 198.53.100.0 + +## 步骤 1: 启用节点通信 + +确保为每个节点启用通信。在 AWS 管理控制台中: + +1. 转到节点的 EC2 主机。 +2. 选择**安全性**,然后选择与节点关联的安全组。 +3. 使用**添加入站规则**根据集群的端口范围和流量类型向节点开放流量。 + +## 步骤 2: 在每个节点上运行守护进程 + +在每个节点上启动 OpenSearch Benchmark,使用 `--node-ip` 在节点本身上初始化 OpenSearch Benchmark,然后使用 `--coordinator-ip` 将每个节点连接到协调节点。 + +对于**节点 1**,以下命令将节点标识为协调节点: + +``` +opensearch-benchmarkd start --node-ip=192.0.1.0 --coordinator-ip=192.0.1.0 +``` + +以下命令使**节点 2** 和**节点 3** 能够侦听协调节点的负载生成指令。 + +**节点 2** + +``` +opensearch-benchmarkd start --node-ip=198.52.100.0 --coordinator-ip=192.0.1.0 +``` + +**节点 3** + +``` +opensearch-benchmarkd start --node-ip=198.53.100.0 --coordinator-ip=192.0.1.0 +``` + +在所有三个节点上运行 OpenSearch Benchmark 并将工作节点设置为侦听协调节点后,您现在可以运行基准测试。 + +## 步骤 3: 运行基准测试 + +在**节点 1** 上,运行基准测试,将 `worker-ips` 设置为工作节点的 IP 地址,如以下示例所示: + +``` +opensearch-benchmark run --pipeline=benchmark-only --workload=eventdata --worker-ips=198.52.100.0,198.53.100.0 --target-hosts=<DOMAIN_ENDPOINT> --client-options=<STANDARD_CLIENT_OPTIONS> --kill-running-processes +``` + +测试完成后,测试生成的日志将显示在工作节点上。 diff --git a/i18n/zh/benchmark/expand-data-corpus.md b/i18n/zh/benchmark/expand-data-corpus.md new file mode 100644 index 00000000..ce34640b --- /dev/null +++ b/i18n/zh/benchmark/expand-data-corpus.md @@ -0,0 +1,79 @@ +--- +title: 扩展工作负载的数据语料库 +--- + +# 扩展工作负载的数据语料库 + +本教程向您展示如何使用 [`expand-data-corpus.py`](https://github.com/opensearch-project/opensearch-benchmark/blob/main/scripts/expand-data-corpus.py) 脚本来增加 OpenSearch Benchmark 工作负载的数据语料库大小。这在针对大型 OpenSearch 集群运行 `http_logs` 工作负载时非常有用。 + +::: danger WARNING +此脚本仅适用于 `http_logs` 工作负载。 +::: + +## 先决条件 + +要使用本教程,请确保满足以下先决条件: + +1. 您已安装 Python 3.x 或更高版本。 +2. `http_logs` 工作负载数据语料库已存储在运行 OpenSearch Benchmark 的负载生成主机上。 + +## 了解脚本 + +`expand-data-corpus.py` 脚本旨在通过复制和修改 `http_logs` 工作负载语料库中的现有文档来生成更大的数据语料库。它主要调整时间戳字段,同时保持其他字段不变。它还生成一个偏移文件,这使得 OpenSearch Benchmark 能够更快地启动。 + +## 使用 `expand-data-corpus.py` + +要使用 `expand-data-corpus.py`,请使用以下语法: + +```bash +./expand-data-corpus.py [options] +``` + +该脚本提供了几个自定义选项。以下是最常用的选项: + +- `--corpus-size`: 所需的语料库大小(以 GB 为单位) +- `--output-file-suffix`: 输出文件名的后缀。 + +## 示例 + +以下示例脚本命令生成 100 GB 的语料库: + +```bash +./expand-data-corpus.py --corpus-size 100 --output-file-suffix 100gb +``` + +脚本将开始生成文档。对于 100 GB 的语料库,生成完整语料库可能需要长达 30 分钟。 + +您可以通过使用不同的输出后缀多次运行脚本来生成多个语料库。脚本生成的所有语料库在注入期间由 OpenSearch Benchmark 按顺序使用。 + +## 验证文档 + +脚本完成后,请检查以下位置的新文件: + +- 在 `http_logs` 的 OpenSearch Benchmark 数据目录中: + - `documents-100gb.json`: 生成的语料库 + - `documents-100gb.json.offset`: 关联的偏移文件 + +- 在 `http_logs` 工作负载目录中: + - `gen-docs-100gb.json`: 生成的语料库的元数据 + - `gen-idx-100gb.json`: 生成的语料库的索引规范 + +## 在测试中使用语料库 + +要在 OpenSearch Benchmark 测试中使用新生成的语料库,请使用以下语法: + +```bash +opensearch-benchmark run --workload http_logs --workload-params=generated_corpus:t [other_options] +``` + +`generated_corpus:t` 参数告诉 OpenSearch Benchmark 使用扩展的语料库。可以使用 `--workload-params` 选项中的逗号附加任何其他工作负载参数。 + +## 专家级设置 + +使用 `--help` 查看脚本支持的所有选项。使用以下专家级设置时要谨慎,因为它们可能会影响语料库结构: + +- `-f`: 指定要用作生成新文档的基础的输入文件 +- `-n`: 设置要生成的文档数量而不是语料库大小 +- `-i`: 定义连续时间戳之间的间隔 +- `-t`: 设置生成的文档的起始时间戳 +- `-b`: 定义写入偏移文件时每批的文档数量 diff --git a/i18n/zh/benchmark/features/index.md b/i18n/zh/benchmark/features/index.md new file mode 100644 index 00000000..e1a7c82f --- /dev/null +++ b/i18n/zh/benchmark/features/index.md @@ -0,0 +1,7 @@ +--- +title: 附加功能 +--- + +# 附加功能 + +除了通用基准测试外,OpenSearch Benchmark 还提供了几个专门的功能。 diff --git a/i18n/zh/benchmark/features/synthetic-data-generation/custom-logic-sdg.md b/i18n/zh/benchmark/features/synthetic-data-generation/custom-logic-sdg.md new file mode 100644 index 00000000..e45348d1 --- /dev/null +++ b/i18n/zh/benchmark/features/synthetic-data-generation/custom-logic-sdg.md @@ -0,0 +1,246 @@ +--- +title: 使用自定义逻辑生成数据 +--- + +# 使用自定义逻辑生成数据 + +您可以使用 Python 模块中定义的自定义逻辑生成合成数据。这种方法为您提供对 OpenSearch 基准测试中合成数据生成方式的最细粒度控制。如果您了解数据的分布和不同字段之间的关系,这将特别有用。 + +## generate_synthetic_document 函数 + +提供给 OpenSearch 基准测试的每个自定义模块都必须定义 `generate_synthetic_document(providers, **custom_lists)` 函数。此函数定义 OpenSearch 基准测试如何生成每个合成文档。 + +### 函数参数 + +| 参数 | 必需/可选 | 描述 | +|---|---|---| +| `providers` | 必需 | 包含数据生成工具的字典。可用的提供者包括 `generic`(Mimesis [Generic provider](https://mimesis.name/master/api.html#generic-providers))和 `random`(Mimesis [Random class](https://mimesis.name/master/random_and_seed.html))。要添加自定义提供者,请参阅[高级配置](#advanced-configuration)。 | +| `custom_lists` | 可选 | 包含预定义值列表的关键字参数,您可以在数据生成逻辑中使用这些值。这些值在 YAML 配置文件的 `custom_lists` 下定义,允许您将数据值与 Python 代码分离。例如,如果您在 YAML 中定义 `dog_names: [Buddy, Max, Luna]`,您可以在函数中通过 `custom_lists['dog_names']` 访问它。这样可以轻松修改数据值而无需更改 Python 代码。 | + +### 基本函数模板 + +```python +def generate_synthetic_document(providers, **custom_lists): + # 访问可用的提供者 + generic = providers['generic'] + random_provider = providers['random'] + + # 使用提供者生成文档 + document = { + 'name': generic.person.full_name(), + 'age': random_provider.randint(18, 80), + 'email': generic.person.email(), + 'timestamp': generic.datetime.datetime() + } + + # 如果提供了自定义列表,可选择使用 + if 'categories' in custom_lists: + document['category'] = random_provider.choice(custom_lists['categories']) + + return document +``` + +有关更多信息,请参阅 [Mimesis 文档](https://mimesis.name/master/api.html)。 + +## Python 模块示例 + +以下示例 Python 模块演示了为虚构的拼车公司 *Pawber* 生成狗司机文档的自定义逻辑,该公司使用 OpenSearch 存储和搜索大量拼车数据。 + +此示例展示了几个高级概念: +- **[自定义提供者类](#advanced-configuration)**(`NumericString`、`MultipleChoices`),扩展 Mimesis 功能 +- 用于数据值(如狗名、品种和零食)的**[自定义列表](#advanced-configuration)**(作为 `custom_lists['dog_names']` 引用) +- 用于真实位置数据的**地理聚类**逻辑 +- 具有嵌套对象和关系的**复杂文档结构** + +将此代码保存到您所需目录中名为 `pawber.py` 的文件(例如 `~/pawber.py`): + +```python +from mimesis.providers.base import BaseProvider +from mimesis.enums import TimestampFormat + +import random + +GEOGRAPHIC_CLUSTERS = { + 'Manhattan': { + 'center': {'lat': 40.7831, 'lon': -73.9712}, + 'radius': 0.05 # degrees + }, + 'Brooklyn': { + 'center': {'lat': 40.6782, 'lon': -73.9442}, + 'radius': 0.05 + }, + 'Austin': { + 'center': {'lat': 30.2672, 'lon': -97.7431}, + 'radius': 0.1 # Increased radius to cover more of Austin + } +} + +def generate_location(cluster): + """Generate a random location within a cluster""" + center = GEOGRAPHIC_CLUSTERS[cluster]['center'] + radius = GEOGRAPHIC_CLUSTERS[cluster]['radius'] + lat = center['lat'] + random.uniform(-radius, radius) + lon = center['lon'] + random.uniform(-radius, radius) + return {'lat': lat, 'lon': lon} + +class NumericString(BaseProvider): + class Meta: + name = "numeric_string" + + @staticmethod + def generate(length=5) -> str: + return ''.join([str(random.randint(0, 9)) for _ in range(length)]) + +class MultipleChoices(BaseProvider): + class Meta: + name = "multiple_choices" + + @staticmethod + def generate(choices, num_of_choices=5) -> str: + import logging + logger = logging.getLogger(__name__) + logger.info("Choices: %s", choices) + logger.info("Length: %s", num_of_choices) + total_choices_available = len(choices) - 1 + + return [choices[random.randint(0, total_choices_available)] for _ in range(num_of_choices)] + +def generate_synthetic_document(providers, **custom_lists): + generic = providers['generic'] + random_mimesis = providers['random'] + + first_name = generic.person.first_name() + last_name = generic.person.last_name() + city = random.choice(list(GEOGRAPHIC_CLUSTERS.keys())) + + # Driver Document + document = { + "dog_driver_id": f"DD{generic.numeric_string.generate(length=4)}", + "dog_name": random_mimesis.choice(custom_lists['dog_names']), + "dog_breed": random_mimesis.choice(custom_lists['dog_breeds']), + "license_number": f"{random_mimesis.choice(custom_lists['license_plates'])}{generic.numeric_string.generate(length=4)}", + "favorite_treats": random_mimesis.choice(custom_lists['treats']), + "preferred_tip": random_mimesis.choice(custom_lists['tips']), + "vehicle_type": random_mimesis.choice(custom_lists['vehicle_types']), + "vehicle_make": random_mimesis.choice(custom_lists['vehicle_makes']), + "vehicle_model": random_mimesis.choice(custom_lists['vehicle_models']), + "vehicle_year": random_mimesis.choice(custom_lists['vehicle_years']), + "vehicle_color": random_mimesis.choice(custom_lists['vehicle_colors']), + "license_plate": random_mimesis.choice(custom_lists['license_plates']), + "current_location": generate_location(city), + "status": random.choice(['available', 'busy', 'offline']), + "current_ride": f"R{generic.numeric_string.generate(length=6)}", + "account_status": random_mimesis.choice(custom_lists['account_status']), + "join_date": generic.datetime.formatted_date(), + "total_rides": generic.numeric.integer_number(start=1, end=200), + "rating": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "earnings": { + "today": { + "amount": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "currency": "USD" + }, + "this_week": { + "amount": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "currency": "USD" + }, + "this_month": { + "amount": generic.numeric.float_number(start=1.0, end=5.0, precision=2), + "currency": "USD" + } + }, + "last_grooming_check": "2023-12-01", + "owner": { + "first_name": first_name, + "last_name": last_name, + "email": f"{first_name}{last_name}@gmail.com" + }, + "special_skills": generic.multiple_choices.generate(custom_lists['skills'], num_of_choices=3), + "bark_volume": generic.numeric.float_number(start=1.0, end=10.0, precision=2), + "tail_wag_speed": generic.numeric.float_number(start=1.0, end=10.0, precision=1) + } + + return document +``` + +## 生成数据 + +要使用自定义逻辑生成合成数据,请使用 `generate-data` 子命令并提供所需的自定义 Python 模块、索引名称、输出路径和要生成的数据总量: + +```shell +osb generate-data --custom-module ~/pawber.py --index-name pawber-data --output-path ~/Desktop/sdg_outputs/ --total-size 2 +``` + +有关可用参数及其描述的完整列表,请参阅 [`generate-data` 命令参考](/benchmark/reference/commands/generate-data)。 + +## 示例输出 + +以下是生成 100 GB 数据时的示例输出: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +[NOTE] ✨ Dashboard link to monitor processes and task streams: [http://127.0.0.1:8787/status] +[NOTE] ✨ For users who are running generation on a virtual machine, consider SSH port forwarding (tunneling) to localhost to view dashboard. +[NOTE] Example of localhost command for SSH port forwarding (tunneling) from an AWS EC2 instance: +ssh -i <PEM_FILEPATH> -N -L localhost:8787:localhost:8787 ec2-user@<DNS> + +Total GB to generate: [1] +Average document size in bytes: [412] +Max file size in GB: [40] + +100%|███████████████████████████████████████████████████████████████████| 100.07G/100.07G [3:35:29<00:00, 3.98MB/s] + +Generated 24271844660 docs in 12000 seconds. Total dataset size is 100.21GB. +✅ Visit the following path to view synthetically generated data: /home/ec2-user/ + +----------------------------------- +[INFO] ✅ SUCCESS (took 272 seconds) +----------------------------------- +``` + +## 高级配置 + +您可以选择创建 YAML 配置文件来存储自定义数据和提供者。配置文件必须定义 `CustomGenerationValues` 参数。 + +`CustomGenerationValues` 中可以使用以下参数。这两个参数都是可选的。 + +| 参数 | 必需/可选 | 描述 | +|---|---|---| +| `custom_lists` | 可选 | 预定义的值数组,您可以在 Python 模块中使用 `custom_lists['list_name']` 引用它们。这允许您将数据值与代码逻辑分离,使修改数据值变得容易而无需更改 Python 文件。例如,`dog_names: [Buddy, Max, Luna]` 可以通过 `custom_lists['dog_names']` 访问。 | +| `custom_providers` | 可选 | 扩展 Mimesis 功能的自定义数据生成类。这些应该在您的 Python 模块中定义为类(如[示例](#python-module-example)中的 `NumericString` 或 `MultipleChoices`),然后在此参数中按名称列出。这允许您创建超出 Mimesis 默认提供的专门数据生成器。 | + +### 示例配置文件 + +将您的配置保存在 YAML 文件中: + +```yml +CustomGenerationValues: + # 使用自定义 Python 模块生成数据 + custom_lists: + # 自定义列表,用于在此 YAML 文件中整合所有值 + dog_names: [Hana, Youpie, Charlie, Lucy, Cooper, Luna, Rocky, Daisy, Buddy, Molly] + dog_breeds: [Jindo, Labrador, German Shepherd, Golden Retriever, Bulldog, Poodle, Beagle, Rottweiler, Boxer, Dachshund, Chihuahua] + treats: [cookies, pup_cup, jerky] + custom_providers: + # OSB 的合成数据生成器使用 Mimesis;自定义提供者本质上是为 Mimesis 添加更多功能的自定义 Python 类 + - NumericString + - MultipleChoices +``` + +### 使用配置 + +要使用您的配置文件,请将 `--custom-config` 参数添加到 `generate-data` 命令: + +```shell +osb generate-data --custom-module ~/pawber.py --index-name pawber-data --output-path ~/Desktop/sdg_outputs/ --total-size 2 --custom-config ~/Desktop/sdg-config.yml +``` + +## 相关文档 + +- [`generate-data` 命令参考](/benchmark/reference/commands/generate-data) +- [使用索引映射生成数据](/benchmark/features/synthetic-data-generation/mapping-sdg) diff --git a/i18n/zh/benchmark/features/synthetic-data-generation/generating-vectors.md b/i18n/zh/benchmark/features/synthetic-data-generation/generating-vectors.md new file mode 100644 index 00000000..8ea290b7 --- /dev/null +++ b/i18n/zh/benchmark/features/synthetic-data-generation/generating-vectors.md @@ -0,0 +1,535 @@ +--- +title: 生成向量 +--- + +# 生成向量 + +您可以使用 OpenSearch 基准测试的合成数据生成器从映射生成合成密集向量和稀疏向量。 + +## 密集向量 + +密集向量(在 OpenSearch 中由 [`knn_vector`](/field-types/supported-field-types/knn-vector) 字段类型表示)是数据(如文本或图像)的数值表示,其中大多数或所有维度都具有非零值。这些向量通常包含 -1.0 和 1.0 之间的浮点数,每个维度都对整体意义有贡献。 + +单词"dog"的嵌入示例: + +```json +{ + "embedding": [0.234, -0.567, 0.123, 0.891, -0.234, 0.456, ..., 0.789] +} +``` + +## 稀疏向量 + +稀疏向量(在 OpenSearch 中由 [`sparse_vector`](/field-types/supported-field-types/sparse-vector/) 字段类型表示)是大多数维度为零的向量,表示为非零令牌 ID 及其权重的键值对。 + +示例文本:`Korean jindos are hunting dogs that have a reputation for being loyal, independent, and confident`。 + +示例文本的稀疏向量表示: + +```json +{ + "5432": 0.85, // "korean" - 非常重要(特定描述符) + "7821": 0.78, // "jindos" - 非常重要(品种名称) + "2": 0.45, // "dog" - 中等重要(一般类别) + "9999": 0.32, // "loyal" - 有些重要(特征) + "1111": 0.12 // "things" - 不太重要(常见词) +} +``` +--- + +## 基本用法 + +以下示例展示了如何仅使用 OpenSearch 索引映射以最少的配置生成向量。 + +### 生成密集向量 + +以最小配置生成随机的 128 维向量。 + +**1. 创建映射文件**(`simple-knn-mapping.json`): + +```json +{ + "settings": { + "index.knn": true + }, + "mappings": { + "properties": { + "title": {"type": "text"}, + "my_embedding": { + "type": "knn_vector", + "dimension": 128 + } + } + } +} +``` + +**2. 生成数据**: + +```bash +opensearch-benchmark generate-data \ + --index-name my-vectors \ + --index-mappings simple-knn-mapping.json \ + --output-path ./output \ + --total-size 1 +``` + +#### 生成的输出 + +在每个生成的文档中,`my_embedding` 字段可能如下所示: + +```json +{ + "title": "Sample text 42", + "my_embedding": [0.234, -0.567, 0.123, ..., 0.891] // 128 个随机浮点数 [-1.0, 1.0] +} +``` + +### 生成稀疏向量 + +使用默认配置(10 个令牌)生成稀疏向量。 + +**1. 创建映射文件**(`simple-sparse-mapping.json`): + +```json +{ + "mappings": { + "properties": { + "content": {"type": "text"}, + "sparse_embedding": { + "type": "sparse_vector" + } + } + } +} +``` + +**2. 生成数据**(相同的命令模式): + +```bash +opensearch-benchmark generate-data \ + --index-name my-sparse \ + --index-mappings simple-sparse-mapping.json \ + --output-path ./output \ + --total-size 1 +``` + +#### 生成的输出 + +在每个生成的文档中,`sparse_embedding` 字段可能如下所示: + +```json +{ + "content": "Sample text content", + "sparse_embedding": { + "1000": 0.3421, + "1100": 0.5234, + "1200": 0.7821, + "1300": 0.1523, + "1400": 0.9102, + "1500": 0.4567, + "1600": 0.2341, + "1700": 0.6789, + "1800": 0.8123, + "1900": 0.3456 + } +} +``` + +仅使用 OpenSearch 索引映射,OpenSearch 基准测试可以生成合成的密集和稀疏向量。但是,这会产生基本的合成向量。为了获得更真实的分布和聚类,我们建议配置下一节中描述的参数。 + +--- + +## 密集向量(k-NN 向量)参数 + +以下是您可以添加到合成数据生成配置文件(YAML 配置)以微调密集向量生成的参数。这些参数在 `field_overrides` 部分与 `generate_knn_vector` 生成器一起使用。有关完整配置详细信息,请参阅[高级配置](/benchmark/features/synthetic-data-generation/mapping-sdg#advanced-configuration)。 + +<!-- vale off --> +#### dimension +<!-- vale on --> + +此参数指定向量中的维数。可选。 + +**如何指定**:必须在 OpenSearch 索引映射文件中定义 `dimension`。您可以选择在 YAML 配置中使用 `field_overrides` 中的 `dimension` 参数覆盖此值。 + +**影响**: +- **内存**:更高的维度 = 更多存储 + - 128 维 ≈ 每个向量 0.5 KB + - 768 维 ≈ 每个向量 3 KB + - 1536 维 ≈ 每个向量 6 KB +- **性能**:更多维度 = 更慢的索引和搜索 +- **质量**:必须匹配实际嵌入模型的输出 + +下表显示了常见的维度值及其典型用例。 + +| 维度 | 用例 | 示例模型 | +|-----------|----------|----------------| +| 128 | 轻量级、自定义模型 | 自定义嵌入、快速搜索 | +| 384 | 通用 | sentence-transformers/all-MiniLM-L6-v2 | +| 768 | 标准 NLP | BERT-Base、DistilBERT、MPNet | +| 1,024 | 高质量 NLP | BERT-Large | +| 1,536 | OpenAI 标准 | text-embedding-ada-002、text-embedding-3-small | +| 3,072 | OpenAI 高级 | text-embedding-3-large | + +**示例**: + +```yaml +field_overrides: + my_embedding: + generator: generate_knn_vector + params: + dimension: 768 # 如果需要,覆盖映射维度 +``` + +**最佳实践**:此参数必须与您的嵌入模型的维度匹配。 + +--- + +#### sample_vectors + +此参数提供基础向量,生成器会向其添加噪声,创建真实的变化和聚类。可选但强烈推荐。 + +如果没有样本向量,OpenSearch 基准测试的合成数据生成器会在整个空间中生成随机均匀向量,这是不现实的,并且搜索质量较差。提供样本向量允许 OpenSearch 基准测试的合成数据生成器创建更真实和自然的聚类。 + +准备好样本向量列表后,将其作为**列表的列表**插入,其中每个内部列表是一个完整的向量。以下示例在合成数据生成配置文件中提供样本向量: + +```yaml +field_overrides: + product_embedding: + generator: generate_knn_vector + params: + dimension: 768 + sample_vectors: + - [0.12, -0.34, 0.56, ..., 0.23] # 向量 1(768 个值) + - [-0.23, 0.45, -0.12, ..., -0.15] # 向量 2(768 个值) + - [0.34, 0.21, -0.45, ..., 0.42] # 向量 3(768 个值) +``` + +使用以下指南确定您提供的向量数量: + +- **最小值**:3-5 个用于基本聚类 +- **推荐**:5-10 个用于真实分布 +- **最大值**:20+ 个用于复杂的多聚类场景 + +**如何获取样本向量**: + +**选项 1(推荐):使用来自您领域的实际嵌入**:使用来自您领域的实际嵌入,代表不同的语义聚类。没有样本向量的随机生成会产生不适合搜索质量测试的不现实数据。 + +**选项 2:在 Python 中使用 sentence-transformers**: + +```python +from sentence_transformers import SentenceTransformer + +model = SentenceTransformer('all-MiniLM-L6-v2') + +# 从不同类别创建代表性文本 +texts = [ + "Electronics and gadgets", + "Clothing and fashion", + "Home and kitchen appliances", + "Books and literature", + "Sports and outdoor equipment" +] + +embeddings = model.encode(texts) +print(embeddings.tolist()) # 复制到您的合成数据生成配置文件(YAML 配置) +``` + +--- + +#### distribution_type + +此参数指定噪声分布的类型。可选。默认为 `gaussian`。 + +**有效值**: +- `gaussian`:正态分布 N(0, `noise_factor`) + - 最真实(带有偶尔异常值的自然变化) + - 产生平滑的聚类 + - 某些值可能超出预期范围 + +- `uniform`:均匀分布 [-`noise_factor`, +`noise_factor`] + - 有界变化(无极端异常值) + - 更可预测的结果 + - 整个范围内的平坦概率 + +**配置**: +```yaml +field_overrides: + realistic_embedding: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.1 + distribution_type: gaussian # 更真实 + + controlled_embedding: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.1 + distribution_type: uniform # 更可预测 +``` + +**最佳实践**:对于类似生产的基准测试,使用 `gaussian`。 + +--- + +<!-- vale off --> +#### noise_factor +<!-- vale on --> + +此参数控制添加到基础向量的噪声量: +- 对于 `gaussian`:正态分布的标准差 +- 对于 `uniform`:均匀分布的范围(±`noise_factor`) + +可选。默认为 `0.1`。 + +下表显示了不同 `noise_factor` 值如何影响生成的数据。 + +| `noise_factor` | 效果 | 用例 | +|--------------|--------|----------| +| 0.01-0.05 | 紧密聚类,最小变化 | 重复检测、近似精确匹配 | +| 0.1-0.2 | 主题内的自然变化 | 一般语义搜索、推荐 | +| 0.3-0.5 | 广泛分散,多样化概念 | 广泛主题匹配、发现 | +| > 0.5 | 非常分散,重叠聚类 | 测试边缘情况、压力测试 | + +**配置**: + +```yaml +field_overrides: + tight_clustering: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.05 # 紧密聚类 + + diverse_results: + generator: generate_knn_vector + params: + sample_vectors: [...] + noise_factor: 0.2 # 更多变化 +``` + +**最佳实践**:从 `0.1` 开始,然后根据搜索召回率或精确度要求进行调整。 + +--- + +<!-- vale off --> +#### normalize +<!-- vale on --> + +此参数在噪声添加后对向量进行归一化,使其大小(长度)恰好为 `1.0`。可选。默认为 `false`。 + +下表显示何时根据您的索引配置将 `normalize` 设置为 `true`。 + +| 索引映射中的 `space_type` | `normalize` 值 | 解释 | +| --------------------------------- | ----------------- | --------------------------------------------------------------------------------------- | +| `cosinesimil` | `true` | 余弦相似度仅取决于向量方向。预归一化可提高性能,因为点积直接表示余弦相似度。 | +| `l2` | `false` | L2 距离依赖于向量大小。归一化会删除大小信息并降低准确性。 | +| `innerproduct` | `false` | 内积将向量大小纳入相似度分数,因此归一化会改变预期的评分行为。 | + +**真实世界模型指南**: + +* **OpenAI 嵌入**:这些向量已经过预归一化,因此将 `normalize` 设置为 `true`。 +* **sentence-transformers**:许多模型输出归一化向量。查看模型文档;在大多数情况下,`normalize` 应设置为 `true`。 +* **BERT(原始输出)**:原始 BERT 嵌入未归一化。将 `normalize` 设置为 `false`,并依赖索引配置在需要时执行归一化。 + +**配置**: + +```yaml +field_overrides: + # 用于余弦相似度搜索 + cosine_embedding: + generator: generate_knn_vector + params: + dimension: 384 + sample_vectors: [...] + normalize: true # 准确的余弦相似度所需 + + # 用于 L2 距离搜索 + l2_embedding: + generator: generate_knn_vector + params: + dimension: 768 + sample_vectors: [...] + normalize: false # 保持原始大小 +``` + +**最佳实践**:匹配 OpenSearch 索引的 `space_type` 设置。 + +--- + +## 稀疏向量参数 + +以下是您可以添加到合成数据生成配置文件以微调稀疏向量生成方式的参数。这些参数在 `field_overrides` 部分与 `generate_sparse_vector` 生成器一起使用。有关完整配置详细信息,请参阅[高级配置](/benchmark/features/synthetic-data-generation/mapping-sdg#advanced-configuration)。 + +<!-- vale off --> +#### num_tokens +<!-- vale on --> + +此参数指定每个向量要生成的令牌-权重对的数量。可选。默认为 `10`。 + +**影响**: +- **低(5-10)**:非常稀疏,快速搜索;可能会遗漏一些相关文档 +- **中(10-25)**:平衡的性能和召回率 +- **高(50-100)**:密集的稀疏表示;全面但较慢 + +下表显示了不同模型和方法的典型 `num_tokens` 值。 + +| 模型/方法 | 典型 `num_tokens` | 用例 | +|----------------|-------------------|----------| +| SPLADE v1 | 10-15 | 标准神经稀疏搜索 | +| SPLADE v2 | 15-25 | 改进的召回率 | +| DeepImpact | 8-12 | 高效稀疏搜索 | +| 自定义/混合 | 20-50 | 丰富的表示 | + +**配置**: + +```yaml +field_overrides: + sparse_standard: + generator: generate_sparse_vector + params: + num_tokens: 15 # 类似标准 SPLADE + + sparse_rich: + generator: generate_sparse_vector + params: + num_tokens: 30 # 更丰富的表示 +``` + +**最佳实践**:从 `10-15` 开始;如果召回率不足则增加。 + +--- + +<!-- vale off --> +#### min_weight and max_weight +<!-- vale on --> + +这些参数定义令牌重要性权重的范围。可选。默认 `min_weight` 为 `0.01`;默认 `max_weight` 为 `1.0`。 + +**影响**: +- `min_weight`:从生成中排除低重要性令牌。不包括权重低于此值的令牌。 +- `max_weight`:限制令牌影响的上限,以防止任何单个令牌支配向量。 + +下表显示了常见的权重范围配置及其用例。 + +| 配置 | `min_weight` | `max_weight` | 用例 | +|---------------|-----|-----|----------| +| 标准 SPLADE | `0.01` | `1.0` | 默认,平衡的重要性 | +| 窄范围 | `0.1` | `0.9` | 更均匀的重要性 | +| 宽范围 | `0.01` | `2.0` | 强重要性信号 | +| 高阈值 | `0.05` | `1.0` | 过滤低置信度令牌 | + +**配置**: + +```yaml +field_overrides: + sparse_balanced: + generator: generate_sparse_vector + params: + num_tokens: 15 + min_weight: 0.01 + max_weight: 1.0 + + sparse_uniform: + generator: generate_sparse_vector + params: + num_tokens: 20 + min_weight: 0.2 # 更高的最小值 + max_weight: 0.8 # 更低的最大值 +``` + +**约束**: +- `min_weight` 必须 > `0.0`(OpenSearch 需要正权重)。 +- `max_weight` 必须 > `min_weight`。 +- 权重四舍五入到 `4` 位小数。 + +**最佳实践**:保持 `min_weight` 较小(`0.01-0.05`)以允许细微的权重。 + +--- + +<!-- vale off --> +#### token_id_start and token_id_step +<!-- vale on --> + +这些参数定义向量生成期间如何分配令牌 ID: + +- `token_id_start`:设置生成序列中的起始令牌 ID。默认为 `1000`。 + +- `token_id_step`:指定每个连续令牌 ID 之间应用的增量。默认为 `100`。 + +**生成的序列**:`start, start+step, start+2*step, ...` + +**示例**,使用 `start=1000`、`step=100`、`num_tokens=5`: + +```json +{ + "1000": 0.3421, // token_id_start + "1100": 0.5234, // start + 1*step + "1200": 0.7821, // start + 2*step + "1300": 0.1523, // start + 3*step + "1400": 0.9102 // start + 4*step +} +``` + +下表显示了不同的令牌 ID 配置及其用例。 + +| 配置 | `token_id_start` | `token_id_step` | 用例 | +| --------------------------- | ----------------- | --------------- | ------------------------------------------------------------------ | +| 默认测试 | `1000` | `100` | 有助于在视觉上区分生成的令牌范围。 | +| 真实词汇表 | `0` | `1` | 使令牌 ID 与真实模型的词汇表索引对齐。 | +| 多字段生成 | `1000`、`5000`、`10000` | `1` | 在不同字段之间保持令牌 ID 范围分离。 | +| 大词汇表模拟 | `0` | `1` | 支持具有 `50,000`+ 令牌词汇表的生成场景。 | + +**配置**: + +```yaml +field_overrides: + # 默认:易于调试 + sparse_debug: + generator: generate_sparse_vector + params: + num_tokens: 10 + token_id_start: 1000 + token_id_step: 100 + + # 真实:实际词汇索引 + sparse_realistic: + generator: generate_sparse_vector + params: + num_tokens: 15 + token_id_start: 0 + token_id_step: 1 + + # 多字段:分离的范围 + sparse_field1: + generator: generate_sparse_vector + params: + token_id_start: 1000 + + sparse_field2: + generator: generate_sparse_vector + params: + token_id_start: 5000 +``` + +**注意**:生成的数据中的令牌 ID 是顺序的。在真实的稀疏向量中,ID 可能基于实际词汇表而不是顺序的。这种差异不会影响 OpenSearch 索引或搜索功能。 + +**最佳实践**:使用更大的 `token_id_step`(例如 `100`)进行调试,并将 `token_id_step` 设置为 `1` 用于类似生产的数据。 + +--- + +## 选择简单或复杂的生成方法 + +下表概述了何时根据您的测试目标使用简单生成与更复杂、可配置的方法。 + +| 场景 | 推荐方法 | 理由 | +| ------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------- | +| 学习或快速测试 | 简单生成(无额外配置) | 提供最快的设置,足以进行基本验证。 | +| 负载测试 | 简单生成 | 优先考虑数据量和吞吐量而不是向量真实性。 | +| 真实基准测试 | 复杂生成(带配置) | 需要真实的向量聚类和分布以反映真实世界的行为。 | +| 生产模拟 | 复杂生成 | 需要与实际嵌入模型产生的向量特征密切匹配的向量特征。 | +| 搜索质量测试 | 复杂生成 | 需要有意义的向量聚类以准确评估召回率和精确度。 | + +**推荐**:对于搜索质量测试或算法比较,使用带有样本向量的复杂配置以确保真实的数据分布。 diff --git a/i18n/zh/benchmark/features/synthetic-data-generation/index.md b/i18n/zh/benchmark/features/synthetic-data-generation/index.md new file mode 100644 index 00000000..4926cfc0 --- /dev/null +++ b/i18n/zh/benchmark/features/synthetic-data-generation/index.md @@ -0,0 +1,19 @@ +--- +title: 合成数据生成 +--- + +# 合成数据生成 +<Badge type="tip" text="2.0 版本引入" /> + +OpenSearch Benchmark 提供内置的合成数据生成器,可以为任何用例以任何规模创建数据集。它支持两种生成方法: + +* **随机数据生成**生成具有随机值的字段。这对于压力测试和评估负载下的系统性能很有用。 +* **基于规则的数据生成**根据用户定义的规则创建数据。这有助于测试特定场景、对查询行为进行基准测试或模拟领域特定的模式。 + +## 数据生成方法 + +OpenSearch Benchmark 支持以下数据生成方法。 + +对于高级合成数据生成功能,请探索向量生成。 + +## 提示和最佳实践 diff --git a/i18n/zh/benchmark/features/synthetic-data-generation/mapping-sdg.md b/i18n/zh/benchmark/features/synthetic-data-generation/mapping-sdg.md new file mode 100644 index 00000000..d9093818 --- /dev/null +++ b/i18n/zh/benchmark/features/synthetic-data-generation/mapping-sdg.md @@ -0,0 +1,423 @@ +--- +title: 使用索引映射生成数据 +--- + +# 使用索引映射生成数据 + +您可以使用 OpenSearch 索引映射生成合成数据。这种方法在自动化和自定义之间提供了平衡。 + +要使用此方法,请将您的 OpenSearch 索引映射保存到 JSON 文件: + +```json +{ + "mappings": { + "properties": { + "title": { + "type": "text", + "analyzer": "standard", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "description": { + "type": "text" + }, + "price": { + "type": "float" + }, + "created_at": { + "type": "date", + "format": "strict_date_optional_time||epoch_millis" + }, + "is_available": { + "type": "boolean" + }, + "category_id": { + "type": "integer" + }, + "tags": { + "type": "keyword" + } + } + }, + "settings": { + "number_of_shards": 1, + "number_of_replicas": 1 + } +} +``` + +OpenSearch 基准测试适用于任何有效的索引映射,无论复杂程度如何。您可以提供类似以下的更复杂的映射: + +<details markdown="block"> + <summary> + 映射 + </summary> + +```json +{ + "mappings": { + "dynamic": "strict", + "properties": { + "user": { + "type": "object", + "properties": { + "id": { + "type": "keyword" + }, + "email": { + "type": "keyword" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + }, + "completion": { + "type": "completion" + } + }, + "analyzer": "standard" + }, + "address": { + "type": "object", + "properties": { + "street": { + "type": "text" + }, + "city": { + "type": "keyword" + }, + "state": { + "type": "keyword" + }, + "zip": { + "type": "keyword" + }, + "location": { + "type": "geo_point" + } + } + }, + "preferences": { + "type": "object", + "dynamic": true + } + } + }, + "orders": { + "type": "nested", + "properties": { + "id": { + "type": "keyword" + }, + "date": { + "type": "date", + "format": "strict_date_optional_time||epoch_millis" + }, + "amount": { + "type": "scaled_float", + "scaling_factor": 100 + }, + "status": { + "type": "keyword" + }, + "items": { + "type": "nested", + "properties": { + "product_id": { + "type": "keyword" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "quantity": { + "type": "short" + }, + "price": { + "type": "float" + }, + "categories": { + "type": "keyword" + } + } + }, + "shipping_address": { + "type": "object", + "properties": { + "street": { + "type": "text" + }, + "city": { + "type": "keyword" + }, + "state": { + "type": "keyword" + }, + "zip": { + "type": "keyword" + }, + "location": { + "type": "geo_point" + } + } + } + } + }, + "activity_log": { + "type": "nested", + "properties": { + "timestamp": { + "type": "date" + }, + "action": { + "type": "keyword" + }, + "ip_address": { + "type": "ip" + }, + "details": { + "type": "object", + "enabled": false + } + } + }, + "metadata": { + "type": "object", + "properties": { + "created_at": { + "type": "date" + }, + "updated_at": { + "type": "date" + }, + "tags": { + "type": "keyword" + }, + "source": { + "type": "keyword" + }, + "version": { + "type": "integer" + } + } + }, + "description": { + "type": "text", + "analyzer": "english", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + }, + "standard": { + "type": "text", + "analyzer": "standard" + } + } + }, + "ranking_scores": { + "type": "object", + "properties": { + "popularity": { + "type": "float" + }, + "relevance": { + "type": "float" + }, + "quality": { + "type": "float" + } + } + }, + "permissions": { + "type": "nested", + "properties": { + "user_id": { + "type": "keyword" + }, + "role": { + "type": "keyword" + }, + "granted_at": { + "type": "date" + } + } + } + } + }, + "settings": { + "number_of_shards": 3, + "number_of_replicas": 2, + "analysis": { + "analyzer": { + "email_analyzer": { + "type": "custom", + "tokenizer": "uax_url_email", + "filter": ["lowercase", "stop"] + } + } + } + } +} +``` + +</details> + +## 生成数据 + +要使用索引映射生成合成数据,请使用 `generate-data` 子命令并提供所需的索引映射文件、索引名称、输出路径和要生成的数据总量: + +```shell +osb generate-data --index-name <NAME_OF_DATA_CORPORA> --index-mappings <PATH_TO_INDEX_MAPPINGS> --output-path <DESIRED_OUTPUT_PATH> --total-size <TOTAL_SIZE_OF_DATA_CORPORA_GENERATED_IN_GB> +``` + +有关可用参数及其描述的完整列表,请参阅 [`generate-data` 命令参考](/benchmark/reference/commands/generate-data)。 + +## 示例输出 + +以下是生成 100 GB 数据时的示例输出: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +[NOTE] ✨ Dashboard link to monitor processes and task streams: [http://127.0.0.1:8787/status] +[NOTE] ✨ For users who are running generation on a virtual machine, consider SSH port forwarding (tunneling) to localhost to view dashboard. +[NOTE] Example of localhost command for SSH port forwarding (tunneling) from an AWS EC2 instance: +ssh -i <PEM_FILEPATH> -N -L localhost:8787:localhost:8787 ec2-user@<DNS> + +Total GB to generate: [1] +Average document size in bytes: [412] +Max file size in GB: [40] + +100%|███████████████████████████████████████████████████████████████████| 100.07G/100.07G [3:35:29<00:00, 3.98MB/s] + +Generated 24271844660 docs in 12000 seconds. Total dataset size is 100.21GB. +✅ Visit the following path to view synthetically generated data: /home/ec2-user/ + +----------------------------------- +[INFO] ✅ SUCCESS (took 272 seconds) +----------------------------------- +``` + +## 高级配置 + +您可以通过创建 YAML 配置文件来控制合成数据的生成方式。以下是在 `MappingGenerationValues` 参数中定义自定义规则的示例配置文件: + +```yml +MappingGenerationValues: + # 对于希望在提供 OpenSearch 映射时对数据生成方式进行更细粒度控制的用户 + generator_overrides: + # 使用这些设置覆盖所有生成器实例。指定类型和参数 + integer: + min: 0 + max: 20 + long: + min: 0 + max: 1000 + float: + min: 0.0 + max: 1.0 + double: + min: 0.0 + max: 2000.0 + date: + start_date: "2020-01-01" + end_date: "2023-01-01" + format: "yyyy-mm-dd" + text: + must_include: ["lorem", "ipsum"] + keyword: + choices: ["alpha", "beta", "gamma"] + + field_overrides: + # 将字段名称指定为字典的键。对于其值,指定生成器及其参数。参数必须遵循每个生成器的现有参数 + # 对于嵌套字段,使用点表示法:例如 preferences.allergies,如果 allergies 是 preferences 对象的子字段 + title: + generator: generate_keyword + params: + choices: ["Helly R", "Mark S", "Irving B"] + + promo_codes: + generator: generate_keyword + params: + choices: ["HOT_SUMMER", "TREATSYUM!"] + + # 嵌套字段,使用点表示法 + orders.items.product_id: + generator: generate_keyword + params: + choices: ["Python", "English"] +``` + +`MappingGenerationValues` 支持以下参数。 + +| 参数 | 描述 | +|---|---| +| `generator_overrides` | 为特定 OpenSearch 字段类型定义自定义生成器规则。任何使用相应类型的字段都将遵循这些规则。请参阅[生成器覆盖参数](#generator-overrides-parameters)。 | +| `field_overrides` | 按字段名称为各个字段定义生成器规则。这些仅适用于明确列出的字段。对于嵌套字段,使用点表示法(例如 `orders.items.product_id`)。请参阅[字段覆盖参数](#field-overrides-parameters)。 | + +::: warning IMPORTANT +如果 `generator_overrides` 和 `field_overrides` 都存在,则 `field_overrides` 优先。 +::: + +#### 生成器覆盖参数 + +以下参数可用于 `generator_overrides` 中的每种 OpenSearch 字段类型。 + +| 字段类型 | 参数 | +|---|---| +| `integer`、`long`、`short`、`byte` | `min`、`max` | +| `float`、`double` | `min`、`max`、`round`(要四舍五入到的小数位数) | +| `date` | `start_date`、`end_date`、`format` | +| `text` | `must_include`(要包含在生成的文本中的术语数组) | +| `keyword` | `choices`(要随机选择的关键字数组) | + +#### 字段覆盖参数 + +以下生成器及其参数可用于 `field_overrides`。 + +| 生成器 | 参数 | +|---|---| +| `generate_text` | `must_include`(要包含在生成的文本中的术语数组) | +| `generate_keyword` | `choices`(要随机选择的关键字数组) | +| `generate_integer` | `min`、`max` | +| `generate_long` | `min`、`max` | +| `generate_short` | `min`、`max` | +| `generate_byte` | `min`、`max` | +| `generate_float` | `min`、`max`、`round`(要四舍五入到的小数位数) | +| `generate_double` | `min`、`max` | +| `generate_boolean` | 不适用 | +| `generate_date` | `format`、`start_date`、`end_date` | +| `generate_ip` | 不适用 | +| `generate_geo_point` | 不适用 | +| `generate_knn_vector` | `dimension`、`sample_vectors`、`noise_factor`、`distribution_type`、`normalize`。请参阅[生成向量](/benchmark/features/synthetic-data-generation/generating-vectors)。 | +| `generate_sparse_vector` | `num_tokens`、`min_weight`、`max_weight`、`token_id_start`、`token_id_step`。请参阅[生成向量](/benchmark/features/synthetic-data-generation/generating-vectors)。 | + +### 使用配置 + +要使用您的配置文件,请在 `--custom-config` 参数中提供其完整路径: + +```shell +osb generate-data --index-name <NAME_OF_DATA_CORPORA> --index-mappings <PATH_TO_INDEX_MAPPINGS> --output-path <DESIRED_OUTPUT_PATH> --total-size <TOTAL_SIZE_OF_DATA_CORPORA_GENERATED_IN_GB> --custom-config ~/Desktop/sdg-config.yml +``` + +## 相关文档 + +- [`generate-data` 命令参考](/benchmark/reference/commands/generate-data) +- [使用自定义逻辑生成数据](/benchmark/features/synthetic-data-generation/custom-logic-sdg) diff --git a/i18n/zh/benchmark/features/synthetic-data-generation/tips.md b/i18n/zh/benchmark/features/synthetic-data-generation/tips.md new file mode 100644 index 00000000..f9948426 --- /dev/null +++ b/i18n/zh/benchmark/features/synthetic-data-generation/tips.md @@ -0,0 +1,19 @@ +--- +title: 提示和最佳实践 +--- + +# 提示和最佳实践 + +以下提示可帮助您高效生成合成数据并在过程中监控性能。 + +### 可视化生成 + +生成的 URL 会打开一个 [Dask 仪表板](https://docs.dask.org/en/latest/dashboard.html),该仪表板可视化数据生成过程。您可以监控每个工作进程的 CPU 和内存使用情况,并查看生成工作流程的 CPU 火焰图。这有助于跟踪资源使用情况并优化性能,特别是在使用[自定义 Python 模块](/benchmark/features/synthetic-data-generation/custom-logic-sdg)时。 + +### 使用默认设置 + +我们建议从默认的合成数据生成设置开始。这些指南可帮助您选择适当的设置,以实现高效可靠的合成数据生成: + +* 将工作进程数设置为**不超过负载生成主机上的 CPU 数量**。 +* 使用**每块 10,000 个文档**的块大小。 +* 根据需要调整 `max_file_size_gb` 设置,以控制写入每个生成文件的数据量。 diff --git a/i18n/zh/benchmark/finetune-workloads.md b/i18n/zh/benchmark/finetune-workloads.md new file mode 100644 index 00000000..948e8444 --- /dev/null +++ b/i18n/zh/benchmark/finetune-workloads.md @@ -0,0 +1,48 @@ +--- +title: 微调自定义工作负载 +--- + +# 微调自定义工作负载 + +虽然自定义工作负载可以帮助使基准测试更符合应用程序的具体需求,但有时需要额外的调整以确保它们与生产集群紧密相似。 + +您可以使用 `create-workload` 功能来微调自定义工作负载,使其更符合基准测试需求。`create-workload` 可以从所有索引或用户选择的特定索引中提取文档。 + +## 需要考虑的特征 + +在开始使用 `create-workload` 微调自定义工作负载时,请考虑工作负载的以下特征: + +1. **查询** -- 考虑查询目标的文档类型以及索引,以及查询调用的字段。 +2. **分片大小** -- 将工作负载的分片大小与集群的分片大小相匹配,否则基准测试将无法模拟应用程序的行为。Lucene 基于分片大小运行,而不是索引。为要包含在自定义工作负载中的任何索引计算分片大小。 +3. **分片数量** -- 根据要如何调整工作负载大小和提高查询性能来选择分片数量。由于每个用例都不同,您可以通过两种方式确定分片数量: + 1. 将理想的索引大小除以在步骤 2 中找到的分片大小。 + 2. 将理想的分片数量乘以在步骤 2 中找到的分片大小。 +4. **决定要提取多少文档(推荐)** -- 现在分片大小已设定,最终索引中所需的分片数量也已确定,您可以确定要提取多少文档。在某些情况下,用户不需要从索引中检索整个文档语料库,因为语料库可能太大。相反,您可能希望生成一个较小的语料库。但是,生成的索引语料库应该能够*代表*生产工作负载中的索引。换句话说,它应该包含来自整个索引的文档,而不仅仅是来自某个特定区域的文档,例如索引的前半部分或后三分之一。要决定提取多少文档: + 1. 将分片数量乘以分片大小。由于每个文档的创建方式不同,因此在此数字上添加一个缓冲区——任意数量的附加文档。当提取的文档数量低于预期数量时,缓冲区会提供帮助,这将无法帮助您保持分片大小。分片大小应低于提取的文档数量。 + 2. 将存储大小除以上一步的乘积。该倍数的值用于设置参考索引中的样本文档数量。 +5. **目标集群配置** -- 在生成工作负载时,考虑目标集群的配置和特征。 + +## 示例 + +以下示例包含一个名为 `stocks` 的索引。`stocks` 索引包含纽约证券交易所 (NYSE) 交易的所有股票的统计文档。OpenSearch Dashboards 提供有关 `stocks` 索引的信息,如以下代码示例所示: + +``` +health status index uuid pri rep docs.count docs.deleted store.size pri.store.size +green open stocks asjdkfjacklajldf 12 1 997818020 232823733 720gb 360gb +``` + +使用这些信息,您可以开始根据您的规格调整工作负载,如以下步骤所示: + +1. **获取与此索引关联的查询** -- 获取向 `stocks` 索引发出请求所需的查询。 +2. **查找索引的分片大小** -- 要获取索引的分片大小,请将存储大小除以索引中的分片数量:`720 / (12 + (12 * 1)) = 30`。30 GB 是分片大小。您可以通过将主分片存储大小值除以主分片数量来验证这一点。 +3. **确定索引分片数量** -- 确定索引中需要多少分片来代表生产负载下的应用程序。例如,如果您希望索引保存 300 GB 的文档,但 300 GB 对于基准测试来说太多,请确定一个合理的数字。例如,300 GB 的文档除以上一步确定的 30 GB 分片大小,或 `300 / 30 = 10`,产生 10 个分片。这 10 个分片可以是 10 个主分片和 0 个副本、5 个主分片和 1 个副本,或 2 个主分片和 4 个副本。分片配置取决于集群的索引需求。 +4. **决定要提取多少文档** -- 要保留 30 GB 并拥有 10 个分片,您需要提取至少 300 GB 的文档。要确定要提取的文档数量,请将存储大小值除以索引大小值,在本例中为 `720 / 300 = 2.4`。由于您希望确保达到每个分片 30 GB 的值,最好向下舍入并选择 2 作为提取倍数,这意味着 OpenSearch Benchmark 将提取每隔一个文档。 +5. **考虑目标集群配置** -- 评估您计划使用的集群。考虑用例、集群大小和节点数量。在微调工作负载时,这可能是一个迭代过程,根据工作负载运行的结果对集群进行小的调整。 + +## 复制指标 + +在许多情况下,工作负载无法完全复制生产集群的精确指标。但是,您可以通过复制以下指标来尽可能接近理想的集群指标: + +* CPU 利用率 +* 搜索请求速率 +* 索引速率 diff --git a/i18n/zh/benchmark/glossary.md b/i18n/zh/benchmark/glossary.md new file mode 100644 index 00000000..62f4d49f --- /dev/null +++ b/i18n/zh/benchmark/glossary.md @@ -0,0 +1,19 @@ +--- +title: 术语表 +--- + +# OpenSearch Benchmark 术语表 + +以下术语在 OpenSearch Benchmark 中常用: + +- **语料库 (Corpora)**:文档集合。 +- **延迟 (Latency)**:如果禁用 `target-throughput`(没有值或值为 `0`),则延迟等于服务时间。如果启用 `target-throughput`(值为 1 或更大),则延迟等于服务时间加上请求在发送前在队列中等待的时间。 +- **指标键 (Metric keys)**:OpenSearch Benchmark 存储的指标,基于[指标记录](/benchmark/reference/metrics/metric-records)中的配置。 +- **操作 (Operations)**:在工作负载中,由工作负载执行的 API 操作列表。 +- **管道 (Pipeline)**:在运行工作负载之前和之后发生的一系列步骤,这些步骤决定基准测试结果。 +- **调度 (Schedule)**:在运行工作负载时按照出现顺序执行的两个或多个操作的列表。 +- **服务时间 (Service time)**:OpenSearch Benchmark 的主要客户端 `opensearch-py` 发送请求并从 OpenSearch 集群接收响应所花费的时间。它包括服务器处理请求所花费的时间以及网络延迟、负载均衡器开销和反序列化/序列化的时间。 +- **摘要报告 (Summary report)**:基于工作负载中定义的指标键在测试结束时生成的报告。 +- **测试 (Test)**:一次 OpenSearch Benchmark 二进制文件的调用。 +- **吞吐量 (Throughput)**:在给定时间段内完成的操作数量。 +- **工作负载 (Workload)**:一个或多个基准测试的集合,使用特定的文档语料库对集群执行基准测试。文档语料库包含在工作负载运行时调用的任何索引、数据文件或操作。 diff --git a/i18n/zh/benchmark/migration-assistance.md b/i18n/zh/benchmark/migration-assistance.md new file mode 100644 index 00000000..79e2b6da --- /dev/null +++ b/i18n/zh/benchmark/migration-assistance.md @@ -0,0 +1,53 @@ +--- +title: 迁移协助 +--- + +# 从 1.X 迁移到 2.X + +对于已经拥有与 OpenSearch Benchmark 集成的系统的用户,我们建议执行以下步骤以平滑过渡到 OpenSearch Benchmark 2.0。 + +## 更新 Benchmark.ini +OpenSearch Benchmark 依赖于 `benchmark.ini`,默认情况下可以在 `~/.benchmark` 目录中找到。此配置文件提供与指标报告位置、工作负载获取方式等相关的配置。OpenSearch Benchmark 2.0 将 `[results_publishing]` 重命名为 `[reporting]`。 + +配置文件应如下所示: +```ini +[reporting] +datastore.type = in-memory +datastore.host = <host-url> +datastore.port = <host-port> +datastore.secure = False +datastore.ssl.verification_mode = <ssl-verification-details> +datastore.user = <username> +datastore.password = <password> +... +``` + +有关如何配置 OpenSearch Benchmark 的信息,请参阅[配置 OpenSearch Benchmark](/benchmark/user-guide/configuring-benchmark)。 + +## 更新外部指标数据存储 + +许多用户使用外部指标数据存储来存储先前测试运行的结果和指标。 + +OpenSearch Benchmark `1.X` 将测试详细信息存储在具有 `benchmark-test-executions-*` 索引模式的索引中。但是,在 `2.X` 中,它将它们存储在具有 `benchmark-test-runs-*` 索引模式的索引中。我们建议在您的指标数据存储中添加这个新的索引模式,并更新可能仍在使用旧索引模式的仪表板。 + +旧索引模式 | 新索引模式 | +:--- | :--- | +benchmark-test-executions-* | benchmark-test-runs-* | + +## 更新脚本 + +一些用户使用自定义脚本包装 OpenSearch Benchmark 以运行夜间性能测试。这些脚本可能依赖于在 `2.X` 中已弃用的一些术语。 + +**查看以下术语并相应地调整您的脚本。** + +1.X 术语 | 2.X 术语 | +:--- | :--- | +execute-test, test-execution-id, TestExecution | run, test-run, TestRun | +results_publishing, results_publisher | reporting, publisher | +provision-configs, provision-config-instances | cluster-configs, cluster-config-instances +load-worker-coordinator-hosts | worker-ips | + +如果您在将 OpenSearch Benchmark 从 `1.X` 迁移到 `2.X` 时遇到任何问题,请通过以下任何方式联系 OpenSearch Benchmark 维护人员: +- [在 OpenSearch Benchmark Slack 频道中发布问题](https://opensearch.slack.com/archives/C082PLA3VPW)。 +- [参加社区会议、办公时间和问题分类](https://www.meetup.com/opensearch/events/309982456/?eventOrigin=group_upcoming_events)。 +- [在 OpenSearch Benchmark GitHub 存储库中创建问题](https://github.com/opensearch-project/opensearch-benchmark/issues)。 diff --git a/i18n/zh/benchmark/performance-testing-best-practices.md b/i18n/zh/benchmark/performance-testing-best-practices.md new file mode 100644 index 00000000..a3d433d6 --- /dev/null +++ b/i18n/zh/benchmark/performance-testing-best-practices.md @@ -0,0 +1,250 @@ +--- +title: 性能测试最佳实践 +--- + +# 性能测试最佳实践 + +在使用 OpenSearch Benchmark 进行性能测试时,遵循一些关键的最佳实践以确保准确、可靠和有意义的结果至关重要。这些实践有助于创建真实的测试场景,最小化可能影响结果的外部因素,并生成可比较和可重现的基准测试。通过遵循这些指南,您可以获得有关集群性能的宝贵见解,包括识别瓶颈并就集群配置和优化做出明智的决策。 + +## 环境设置 + +性能测试需要仔细注意测试环境。正确配置的环境对于获得可靠和可重现的结果至关重要。 + +在设置测试环境时,使用与生产环境密切匹配的硬件至关重要。使用开发或性能不足的硬件将无法提供可转换为生产性能的有意义结果。本地机器通常具有有限的硬件,本地开发库可能会与工作负载的库冲突,从而阻止基准测试有效运行。 + +为了获得最佳结果,请确保您的负载生成主机或运行 OpenSearch Benchmark 的机器遵循最低硬件要求: + +- CPU:8+ 核心 +- RAM:32+ GB +- 存储:固态硬盘 (SSD)/NVMe +- 网络:10 Gbps + +我们建议配置测试集群并配置其设置以反映您最有可能在生产中部署的内容。 + +## 测试配置 + +正确的测试配置包括为测试场景设置适当的参数,并确保您的集群已优化配置。 + +### 基本设置 + +以下示例显示了基本的基准测试配置文件。此配置包括基本参数,例如预热时间、测试持续时间和客户端数量: + +```json + { + "name": "my-benchmark-test-procedure", + "description": "This test procedure runs term query against a cluster. It includes a 300-second warm-up, followed by a 3600-second benchmark using 8 concurrent clients.", + "schedule": [ + { + "operation": "term", + "warmup-time=period": 300, + "time-period": 3600, + "clients": 8 + } + ] + } +``` + +### 索引设置 + +您的 OpenSearch 索引设置应针对您的特定用例进行优化。尝试设置每个索引的分片数量以匹配您的生产集群。但是,如果您是希望专注于单个分片性能并限制影响性能的变量的开发人员,请使用单个主分片,如以下示例 `index_settings` 所示: + +```json +{ + "index_settings": { + "number_of_shards": 1, + "number_of_replicas": 0, + "refresh_interval": "30s" + } +} +``` + +这些设置为您的文档和测试结果提供了充足的存储空间,每个索引有 3 个分片和 1 个副本。 + +## 运行测试 + +运行基准测试涉及在测试期间监控系统并确保测试运行之间的条件一致。 + +虽然您可以运行基本测试,但您也可以使用其他[基准测试命令选项](/benchmark/reference/commands/)自定义测试运行。以下示例运行针对特定主机的 `geonames` 工作负载测试,并将测试结果输出为 `csv`,可用于进一步分析基准测试的指标: + +```bash +opensearch-benchmark run \ + --workload=geonames \ + --target-hosts=localhost:9200 \ + --pipeline=benchmark-only \ + --test-procedure=default \ + --report-format=csv \ + --report-file=benchmark-results.csv +``` + +### 测试期间的监控 + +在测试运行期间,监控各种系统指标以确保测试正确运行并识别任何潜在的瓶颈至关重要。以下命令可帮助您监控系统性能的不同方面: + +```bash +# 监控系统资源 +vmstat 1 + +# 监控 OpenSearch 指标 +curl localhost:9200/_cat/nodes?v +curl localhost:9200/_cat/indices?v + +# 监控集群健康状况 +curl localhost:9200/_cluster/health?pretty +``` + +## 收集指标 + +收集和存储适当的指标对于分析测试结果和就性能优化做出明智决策非常重要。 + +### 基本指标 + +配置您的基准测试以收集全面的指标。以下示例配置向您展示如何使用文件存储设置指标收集: + +```json +{ + "metrics": { + "store_metrics": true, + "detailed": true, + "metrics_store": { + "type": "file", + "location": "/path/to/metrics" + } + } +} +``` + +### 要跟踪的示例指标 + +以下 Python 结构可用作模板,包括在性能测试期间应跟踪的指标列表: + +```python +metrics_to_track = { + 'latency': { + 'mean': 'ms', + 'median': 'ms', + 'p95': 'ms', + 'p99': 'ms' + }, + 'throughput': { + 'ops/sec': 'count', + 'mb/sec': 'bytes' + }, + 'system': { + 'cpu_usage': '%', + 'memory_used': 'bytes', + 'disk_io': 'iops' + } +} +``` + +### 计算指标 + +OpenSearch Benchmark 计算指标的方式与传统的客户端-服务器系统不同。有关如何计算指标的详细信息,请参阅 [OpenSearch Benchmark 与传统客户端-服务器系统之间的差异](/benchmark/user-guide/concepts#differences-between-opensearch-benchmark-and-a-traditional-client-server-system)。 + +## 与 OpenSearch Dashboards 集成 + +要将 OpenSearch Benchmark 结果与 OpenSearch Dashboards 集成,请使用以下步骤: + +1. [配置 OpenSearch Benchmark](/benchmark/user-guide/install-and-configure/configuring-benchmark) 以将结果存储在 OpenSearch 中。 +2. 在 OpenSearch Dashboards 中为基准测试结果创建索引模式。 +3. 创建可视化和仪表板以分析基准测试数据。 + +## 常见陷阱 + +在使用 OpenSearch Benchmark 进行性能测试时,了解一些可能导致不准确或误导性结果的常见陷阱非常重要。 + +### 预热间隔 + +适当的预热对于准确的性能测试至关重要。如果没有足够的预热期,您的测试结果可能会因初始系统不稳定性或缓存效应而产生偏差。 + +不要在没有预热期的情况下运行测试。 + +相反,始终在测试中包括充分的预热期。这使系统在开始测量之前达到稳定状态。在以下示例中,`geonames` 运行被赋予 `300s` 的预热期: + +```python +opensearch-benchmark run --workload=geonames --workload-params="warmup_time_period:300" +``` + +适当的预热期可能因您的特定工作负载和系统配置而异。从至少 5 分钟(300 秒)开始,并根据您的观察进行调整。 + +### 比较来自不同环境的结果 + +性能测试中最常见的错误之一是比较来自不同环境的结果。由于硬件、网络条件和其他环境因素的差异,从笔记本电脑或开发机器获得的结果与生产服务器的结果不可比。 + +相反,确保所有比较都使用相同或相同的环境进行。如果您需要比较不同的配置,请确保一次只更改一个变量,同时保持环境一致。 + +### 记录测试环境 + +正确记录测试环境对于可重现性和准确分析至关重要。如果没有详细的环境信息,很难解释结果或在未来重现测试。 + +不要在测试报告中省略环境详细信息。 + +相反,始终全面记录测试环境的详细信息。这应该包括硬件规格、软件版本和任何相关的配置设置。以下示例向您展示如何在使用 Python 脚本运行 OpenSearch Benchmark 时添加环境详细信息: + +```python +# DO: Document environment details +def run_benchmark(): + environment = { + 'hardware': 'AWS m5.2xlarge', + 'os': 'Ubuntu 20.04', + 'kernel': '5.4.0-1018-aws', + 'opensearch': '2.0.0', + 'java': 'OpenJDK 11.0.11', + 'benchmark_version': '1.0.0' + } + results = opensearch_benchmark.run() + return {'environment': environment, 'results': results} +``` + +通过记录这些详细信息,您可以确保正确解释测试结果,并且在必要时可以重现测试。 + +### 使用日志进行故障排除 + +遇到问题或意外结果时,OpenSearch Benchmark 日志可以提供有价值的见解。以下是如何有效使用日志进行故障排除: + +1. 导航到日志文件。主日志文件通常位于 `~/.osb/logs/benchmark.log`。 + +2. 查找错误消息。搜索包含"ERROR"或"WARNING"的行以识别潜在问题。 + +3. 检查性能瓶颈。查找指示操作缓慢或资源限制的条目。 + +4. 检查配置详细信息,例如日志。日志通常包含有关测试配置的信息,可以帮助验证您的预期设置是否正确应用。 + +5. 注意基准测试不同阶段的持续时间,包括预热和测量期。 + +通过仔细检查这些日志,您通常可以确定性能问题或意外基准测试结果的根本原因。如果您遇到无法识别的日志错误,请在 [OpenSearch Benchmark 存储库](https://github.com/opensearch-project/opensearch-benchmark)中创建问题。 + +## 安全注意事项 + +在大多数情况下,基本的身份验证协议应该足以进行测试。但是,您可以使用 SSL 在基准测试期间进行安全通信,如以下示例 `opensearch.yml` 配置所示: + +```yaml +security: + ssl: true + verification_mode: full + certificate_authorities: + - /path/to/ca.crt + client_certificate: /path/to/client.crt + client_key: /path/to/client.key +``` + +## 维护 + +定期维护基准测试环境和工具对于长期保持一致和可靠的测试至关重要。 + +使用以下命令使您的基准测试工具和工作负载保持最新: + +```bash +# 更新 OpenSearch Benchmark +pip install --upgrade opensearch-benchmark + +# 更新工作负载 +opensearch-benchmark update-workload geonames + +# 清理旧数据 +opensearch-benchmark clean +``` + +## Amazon OpenSearch Serverless 注意事项 + +在使用 Amazon OpenSearch Serverless 进行测试时,请注意并非所有测试过程都可能受支持。始终检查您正在使用的[工作负载](https://github.com/opensearch-project/opensearch-benchmark-workloads)的 `README.md` 文件,以确认它是否与 OpenSearch Serverless 兼容。如果未提供兼容性信息,您可能需要单独测试这些过程以确定哪些受支持。 diff --git a/i18n/zh/benchmark/randomizing-queries.md b/i18n/zh/benchmark/randomizing-queries.md new file mode 100644 index 00000000..936d9c43 --- /dev/null +++ b/i18n/zh/benchmark/randomizing-queries.md @@ -0,0 +1,135 @@ +--- +title: 随机化查询 +--- + +# 随机化查询 + +默认情况下,OpenSearch Benchmark 在多次基准测试迭代中运行相同的查询。但是,重复运行相同的查询并不适用于每种测试场景。例如,对相同查询进行多次迭代来模拟真实世界的缓存会导致一次缓存未命中,然后是多次命中。OpenSearch Benchmark 允许您以可配置的方式随机化查询。 + +例如,更改以下 `nyc_taxis` 操作中的 `"gte"` 和 `"lt"` 会创建不同的查询,从而产生唯一的缓存条目: + +```json +{ + "name": "range", + "operation-type": "search", + "body": { + "query": { + "range": { + "total_amount": { + "gte": 5, + "lte": 15 + } + } + } + } +} +``` + +您不能完全随机化值,因为缓存不会获得任何命中。要在随机化的同时获得缓存命中,缓存有时必须遇到相同的值。为了在随机化时考虑相同的值,OpenSearch Benchmark 在基准测试开始时为每个随机化操作生成数量为 $$N$$ 的值对。OpenSearch Benchmark 将这些值存储在已保存的列表中,其中每对被分配一个从 $$1$$ 到 $$N$$ 的索引。 + +每次 OpenSearch 发送查询时,OpenSearch Benchmark 都会决定是否在查询中使用此已保存列表中的一对值。它在称为_重复频率_ (`rf`) 的可配置时间分数内执行此操作。如果 OpenSearch 之前遇到过该值对,这可能会导致缓存命中。例如,如果 `rf` = 0.7,缓存命中率可能高达 70%。此比率是否会导致命中取决于基准测试的持续时间和缓存大小。 + +OpenSearch Benchmark 使用 Zipf 概率分布选择已保存的值对,其中选择对 $$i$$ 的概率与 $$1 \over i^\alpha$$ 成正比。在此公式中,$$i$$ 表示已保存值对的索引,$$\alpha$$ 控制分布的集中程度。此分布反映在实际缓存中观察到的使用模式。具有较低 $$i$$ 值(接近 $$1$$)的对被选择得更频繁,而具有较高 $$i$$ 值(接近 $$N$$)的对被选择得较少。 + +在其他 $$1 -$$ `rf` 时间分数内,会生成新的随机值对。由于 OpenSearch Benchmark 之前没有遇到过这些值对,因此这些对应该错过缓存。 + +## 用法 + +要在工作负载中使用此功能,您必须对 `workload.py` 进行一些更改,并在运行 OpenSearch Benchmark 时提供一些 CLI 标志。 + +### 修改 `workload.py` + +通过为每个操作注册"标准值源"来指定如何生成已保存的值对。此 Python 函数不接受任何参数并返回一个字典。这些键镜像输入查询中的键但被随机化。最后,更改 `register()` 方法,使其使用操作名称和字段名称(已随机化)注册此函数。 + +例如,用于随机化前述 `"range"` 操作中的 `"total_amount"` 字段的标准值源可能类似于以下函数: + +```py +def random_money_values(max_value): + gte_cents = random.randrange(0, max_value*100) + lte_cents = random.randrange(gte_cents, max_value*100) + return { + "gte":gte_cents/100, + "lte":lte_cents/100 + } + +def range_query_standard_value_source(): + return random_money_values(120.00) +``` + +同样,您可以使用以下函数随机化注册行为: + +```py +def register(registry): + registry.register_standard_value_source("range", "total_amount", range_query_standard_value_source) +``` + +此函数可能已经包含代码。如果是这样,请保留它。如果 `workload.py` 不存在或缺少 `register(registry)` 函数,您可以创建它们。 + +#### 随机化非范围查询 + +默认情况下,OpenSearch Benchmark 假设要随机化的查询是具有值 `"gte"`/`"gt"`、`"lte"`/`"lt"` 和可选的 `"format"` 的 `"range"` 查询。如果不是这种情况,您可以配置它以使用不同的查询类型名称和不同的值。 + +例如,要随机化以下工作负载操作: + +```json +{ + "name": "bbox", + "operation-type": "search", + "index": "nyc_taxis", + "body": { + "size": 0, + "query": { + "geo_bounding_box": { + "pickup_location": { + "top_left": [-74.27, 40.92], + "bottom_right": [-73.68, 40.49] + } + } + } + } +} +``` + +您将在 `workload.py` 中注册以下函数: + +```py +registry.register_query_randomization_info("bbox", "geo_bounding_box", [["top_left"], ["bottom_right"]], []) +``` + +第一个参数 `"bbox"` 是操作的名称。 + +第二个参数 `"geo_bounding_box"` 是查询类型名称。 + +第三个参数是一个列表的列表:`[["top_left"], ["bottom_right"]]`。外部列表的条目指定用于随机化的参数,因为可能存在表示大致相同参数的相同名称的不同版本,例如 `"gte"` 或 `"gt"`。这里,每个参数名称只有一个选项。为了随机化查询,原始查询中必须存在每个参数名称的至少一个版本。 + +最后一个参数是可选参数列表。如果随机标准值源中存在可选参数,则 OpenSearch Benchmark 将该参数插入查询的随机化版本中。如果它不在源中,则会被忽略。以下示例中没有可选参数,但典型的用例是范围查询中的 `"format"`。 + +如果没有注册,则使用默认注册:`registry.register_query_randomization_info(<operation_name>, "range", [["gte", "gt"], ["lte", "lt"]], ["format"])`。 + +标准值源返回的 `dict` 应该与您要随机化的参数名称匹配。例如,以下是前述示例的标准值源: + +```py +def bounding_box_source(): + top_longitude = random.uniform(-74.27, -73.68) + top_latitude = random.uniform(40.49, 40.92) + + bottom_longitude = random.uniform(top_longitude, -73.68) + bottom_latitude = random.uniform(40.49, top_latitude) + + return { + "top_left":[top_longitude, top_latitude], + "bottom_right":[bottom_longitude, bottom_latitude] + } +``` + +### CLI 标志 + +使用以下 CLI 标志自定义随机化: + +- `--randomization-enabled` 打开和关闭随机化。如果未启用随机化,则不会应用任何随机化标志。 + +- `--randomization-repeat-frequency` 或 `-rf` 设置从基准测试开始时生成的已保存值对中抽取的对的分数。该值应介于 `0.0` 和 `1.0` 之间。默认值为 `0.3`。 + +- `--randomization-n` 设置为每个操作生成的值对的数量 `N`。默认值为 `5000`。 + +- `--randomization-alpha` 设置控制 `Zipf` 分布扩散的 `alpha` 参数。该值应该 `>=0`。较低的值会增加分布的扩散。默认值为 `1.0`。 diff --git a/i18n/zh/benchmark/reference/commands/aggregate.md b/i18n/zh/benchmark/reference/commands/aggregate.md new file mode 100644 index 00000000..a509fae2 --- /dev/null +++ b/i18n/zh/benchmark/reference/commands/aggregate.md @@ -0,0 +1,92 @@ +--- +title: aggregate +--- + +<!-- vale off --> +# aggregate 命令 +<!-- vale on --> + +`aggregate` 命令将多个测试运行合并为单个聚合结果,提供了一种更简化的方式来执行和分析多个测试运行。有两种聚合方法: + +- [自动聚合](#auto-aggregation) +- [手动聚合](#manual-aggregation) + +## 自动聚合 + +自动聚合方法运行多次基准测试迭代并自动聚合结果,所有这些都在单个命令中完成。您可以将本节中概述的标志与 `execute` 命令一起使用。 + +### 用法 + +以下示例运行 `geonames` 工作负载并聚合结果两次: + +```bash +opensearch-benchmark execute --test-iterations=2 --aggregate=true --workload=geonames --target-hosts=127.0.0.1:9200 +``` + +### 自动聚合标志 + +以下新标志可用于自定义自动聚合方法: + +- `--test-iterations`:指定运行工作负载的次数(默认为 `1`)。 +- `--aggregate`:确定是否聚合多个测试运行的结果(默认为 `true`)。 +- `--sleep-timer`:指定在开始下一次测试运行之前休眠的秒数(默认为 `5`)。 +- `--cancel-on-error`:设置后,如果其中一个测试迭代中发生错误,则停止执行测试(默认为 `false`)。 + +## 手动聚合 + +您可以使用 `aggregate` 命令手动聚合来自多个测试运行的结果。 + +### 用法 + +要手动聚合多个测试运行,请指定要聚合的 `test_run_ids`,如以下示例所示: + +```bash +opensearch-benchmark aggregate --test-executions=<test_run_id1>,<test_run_id2>,... +``` + +### 响应 + +OpenSearch Benchmark 响应如下: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +Aggregate test run ID: aggregate_results_geonames_9aafcfb8-d3b7-4583-864e-4598b5886c4f + +---------------------------------- +[INFO] ✅ SUCCESS (took 1 seconds) +---------------------------------- +``` + +结果将聚合为一个测试运行,并存储在输出中显示的 ID 下。 + +### 其他选项 +- `--test-execution-id`:为聚合的测试运行定义唯一 ID。 +- `--results-file`:将聚合结果写入提供的文件。 +- `--workload-repository`:定义 OpenSearch Benchmark 将从中加载工作负载的存储库(默认为 `default`)。 + +## 聚合结果 + +聚合结果包括以下信息: + +- **相对标准偏差(RSD)**:对于每个指标,额外的 `mean_rsd` 值显示测试运行中结果的分布。 +- **总体最小值/最大值**:聚合结果包括 `overall_min` 和 `overall_max`,它们反映所有测试运行中的真实最小值/最大值,而不是平均最小值和最大值。 +- **存储**:聚合的测试结果存储在单独的 `aggregated_results` 文件夹中,与 `test-runs` 文件夹并排。 + +以下示例显示了聚合结果: + +```json + "throughput": { + "overall_min": 29056.890292903263, + "mean": 50115.8603858536, + "median": 50099.54349684457, + "overall_max": 72255.15946248993, + "unit": "docs/s", + "mean_rsd": 59.426059705973664 + }, +``` diff --git a/i18n/zh/benchmark/reference/commands/generate-data.md b/i18n/zh/benchmark/reference/commands/generate-data.md new file mode 100644 index 00000000..60db11a8 --- /dev/null +++ b/i18n/zh/benchmark/reference/commands/generate-data.md @@ -0,0 +1,86 @@ +--- +title: generate-data +--- + +<!-- vale off --> +# generate-data 命令 +<!-- vale on --> + +`generate-data` 命令为基准测试和测试创建合成数据集。OpenSearch Benchmark 支持两种数据生成方法:使用 OpenSearch 索引映射或使用用户定义逻辑的自定义 Python 模块。有关更多信息,请参阅[合成数据生成](/benchmark/features/synthetic-data-generation/)。 + +## 用法 + +```shell +osb generate-data --index-name <INDEX_NAME> --output-path <OUTPUT_PATH> --total-size <SIZE_GB> [OPTIONS] +``` + +**要求**: + +- 必须指定 `--index-mappings` 或 `--custom-module`,但不能同时指定两者。 +- 使用 `--custom-module` 时,您的 Python 模块必须包含 `generate_synthetic_document(providers, **custom_lists)` 函数。 + +## 数据生成方法 + +选择以下方法之一: + +**方法 1:使用索引映射**: + +```shell +osb generate-data --index-name my-index --index-mappings mapping.json --output-path ./data --total-size 1 +``` + +**方法 2:使用自定义 Python 模块**: + +```shell +osb generate-data --index-name my-index --custom-module custom.py --output-path ./data --total-size 1 +``` + +## 选项 + +将以下选项与 `generate-data` 命令一起使用。 + +| 选项 | 必需/可选 | 描述 | +|---|---|---| +| `--index-name` 或 `-n` | 必需 | 要生成的数据语料库的名称。 | +| `--output-path` 或 `-p` | 必需 | 要生成数据的路径。 | +| `--total-size` 或 `-s` | 必需 | 要生成的数据总量,以 GB 为单位。 | +| `--index-mappings` 或 `-i` | 有条件(必须指定 `--index-mappings` 或 `--custom-module`)| 要使用的 OpenSearch 索引映射的路径。使用基于映射的生成时必需。不能与 `--custom-module` 一起使用。 | +| `--custom-module` 或 `-m` | 有条件(必须指定 `--index-mappings` 或 `--custom-module`)| 包含自定义逻辑的 Python 模块的路径。使用自定义逻辑生成时必需。不能与 `--index-mappings` 一起使用。Python 模块必须包含 `generate_synthetic_document(providers, **custom_lists)` 函数。 | +| `--custom-config` 或 `-c` | 可选 | YAML 配置文件的路径,定义要如何生成数据的规则。 | +| `--test-document` 或 `-t` | 可选 | 存在此标志时,OpenSearch Benchmark 生成单个合成文档并将其输出到控制台。这为您提供了一种验证生成的示例文档是否符合您的期望的方法。不存在标志时,将生成整个数据语料库。 | + +## 示例输出 + +以下是生成合成数据时的示例输出: + +``` + ____ _____ __ ____ __ __ + / __ \____ ___ ____ / ___/___ ____ ___________/ /_ / __ )___ ____ _____/ /_ ____ ___ ____ ______/ /__ + / / / / __ \/ _ \/ __ \\__ \/ _ \/ __ `/ ___/ ___/ __ \ / __ / _ \/ __ \/ ___/ __ \/ __ `__ \/ __ `/ ___/ //_/ +/ /_/ / /_/ / __/ / / /__/ / __/ /_/ / / / /__/ / / / / /_/ / __/ / / / /__/ / / / / / / / / /_/ / / / ,< +\____/ .___/\___/_/ /_/____/\___/\__,_/_/ \___/_/ /_/ /_____/\___/_/ /_/\___/_/ /_/_/ /_/ /_/\__,_/_/ /_/|_| + /_/ + +[NOTE] ✨ Dashboard link to monitor processes and task streams: [http://127.0.0.1:8787/status] +[NOTE] ✨ For users who are running generation on a virtual machine, consider SSH port forwarding (tunneling) to localhost to view dashboard. +[NOTE] Example of localhost command for SSH port forwarding (tunneling) from an AWS EC2 instance: +ssh -i <PEM_FILEPATH> -N -L localhost:8787:localhost:8787 ec2-user@<DNS> + +Total GB to generate: [1] +Average document size in bytes: [412] +Max file size in GB: [40] + +100%|███████████████████████████████████████████████████████████████████| 100.07G/100.07G [3:35:29<00:00, 3.98MB/s] + +Generated 24271844660 docs in 12000 seconds. Total dataset size is 100.21GB. +✅ Visit the following path to view synthetically generated data: /home/ec2-user/ + +----------------------------------- +[INFO] ✅ SUCCESS (took 272 seconds) +----------------------------------- +``` + +## 相关文档 + +- [使用索引映射生成数据](/benchmark/features/synthetic-data-generation/mapping-sdg) +- [使用自定义逻辑生成数据](/benchmark/features/synthetic-data-generation/custom-logic-sdg) diff --git a/i18n/zh/benchmark/reference/commands/redline-test.md b/i18n/zh/benchmark/reference/commands/redline-test.md new file mode 100644 index 00000000..3081b036 --- /dev/null +++ b/i18n/zh/benchmark/reference/commands/redline-test.md @@ -0,0 +1,114 @@ +--- +title: redline-test +--- + +# 红线测试 + +`--redline-test` 命令使 OpenSearch Benchmark 能够在增加负载的情况下自动确定 OpenSearch 集群可以处理的最大请求吞吐量。它根据实时集群性能动态调整活动客户端的数量,有助于容量规划和识别性能回归。 + +使用 `--redline-test` 标志时,OpenSearch Benchmark 执行以下步骤: + +1. **客户端初始化**:OpenSearch Benchmark 初始化大量客户端(默认:1,000)。您可以使用可选的 `--redline-max-clients=<int>` 标志覆盖此设置。 +2. **反馈机制**:OpenSearch Benchmark 增加活动客户端的数量。FeedbackActor 监控实时请求失败并相应地调整客户端数量。 +3. **共享状态协调**:OpenSearch Benchmark 使用 Python 的多进程库来管理用于进程间通信的共享字典和队列: + - **工作进程**创建并与 WorkerCoordinatorActor 共享客户端状态映射。 + - **WorkerCoordinatorActor** 聚合客户端状态并将其转发给 FeedbackActor。 + - **FeedbackActor** 增加客户端数量,直到检测到请求错误,然后暂停客户端,等待 30 秒,并恢复测试。 + +下图提供了红线测试架构的可视化概述。 + +*红线概述* + +## 用法 + +要执行红线测试,请使用带有 `--redline-test` 标志和定时测试程序的 `run` 命令。 + +此测试程序使用 keyword-terms 操作定义定时工作负载。它分两个阶段运行: + +- **预热阶段**:测试开始时有一个预热期(`warmup-time-period`),以在开始测量之前稳定性能指标。这有助于避免冷启动效应扭曲结果。 +- **测量阶段**:在 `time-period` 期间,OpenSearch Benchmark 使用指定数量的客户端以 `target-throughput`(每秒请求数)发送请求。红线测试逻辑将从此基线扩展活动客户端的数量,以确定集群的最大可持续负载。 + +以下示例定时测试程序用作红线测试的输入,然后动态调整客户端负载以找到集群在没有错误的情况下可以处理的最大请求吞吐量: + +```json +{ + "name": "timed-mode-test-procedure", + "schedule": [ + { + "operation": "keyword-terms", + "warmup-time-period": {{ warmup_time | default(300) | tojson }}, + "time-period": {{ time_period | default(900) | tojson }}, + "target-throughput": {{ target_throughput | default(20) | tojson }}, + "clients": {{ search_clients | default(20) }} + } + ] +} +``` + +运行以下命令以使用针对 OpenSearch 集群的定时测试程序启动红线测试: + +```bash +opensearch-benchmark run \ + --pipeline=benchmark-only \ + --target-hosts=<your-opensearch-cluster> \ + --workload=<workload> \ + --test-procedure=timed-mode-test-procedure \ + --redline-test +``` + +## 基于延迟或 CPU 的反馈 + +OpenSearch Benchmark 支持每个请求的 `timeout` 值,如果请求超过指定的持续时间,则会取消该请求。您可以使用 `--client-options=timeout:<int>` 标志设置此值。默认值为 10 秒。 + +您可以调整此值以定义 OpenSearch Benchmark 在红线测试期间应容忍的最大请求延迟。例如,要确定集群在不超过 15 秒延迟的情况下可以处理的最高负载,请将客户端选项中的超时设置为 `15`。 + +除了延迟和请求错误监控之外,红线测试还支持基于 CPU 的反馈。这有助于防止超过集群的安全利用率限制。 + +### 要求 + +要在红线测试期间使用基于 CPU 的反馈,您的设置必须满足以下要求: + +- 必须配置指标存储。使用内存存储会导致以下错误: + + ```bash + [ERROR] Cannot run. Error in worker_coordinator (CPU-based feedback requires a metrics store. You are using an in-memory metrics store) + ``` + +- 需要 `--redline-cpu-max-usage` 标志。此标志设置测试期间每个节点允许的最大 CPU 使用率(百分比)。 +- 当基于 CPU 的反馈处于活动状态时,会自动启用 `node-stats` 遥测设备。 + +### 行为 + +红线 CPU 反馈循环具有以下行为: + +- `FeedbackActor` 定期查询指标存储以检索每个节点的平均 CPU 使用率。 +- 如果任何节点超过 `--redline-cpu-max-usage` 设置的阈值,系统会启动缩减。 +- 缩减后,参与者会在尝试再次扩展之前等待。 + +## 结果 + +在红线测试期间,OpenSearch Benchmark 提供详细的日志,记录测试期间的扩展决策和请求失败。在红线测试结束时,OpenSearch Benchmark 会记录集群支持的最大客户端数量,而不会出现请求错误。 + +以下示例日志输出表明红线测试检测到 keyword-terms 操作的 `15%` 错误率,并确定集群在出现错误之前的最大稳定客户端负载为 `410`: + +``` +[WARNING] Error rate is 15.0 for operation 'keyword-terms'. Please check the logs. +Redline test finished. Maximum stable client number reached: 410 +``` + +## 配置提示和测试行为 + +使用以下可选命令标志可更好地理解和自定义红线测试运行: + +- `--redline-scale-step`:指定每次扩展迭代中要恢复的客户端数。 +- `--redline-scaledown-percentage`:指定发生错误时要暂停的客户端百分比。 +- `--redline-post-scaledown-sleep`:指定反馈参与者在缩减后启动扩展之前等待的秒数。 +- `--redline-max-clients`:指定红线测试期间允许的最大客户端数。如果未设置,OpenSearch Benchmark 默认为测试程序中定义的客户端数。 + +### 对于基于 CPU 的反馈 + +使用以下附加标志来配置基于 CPU 的反馈: + +- `--redline-cpu-max-usage`:(必需)每个节点允许的最大 CPU 负载(百分比),超过该值将触发缩减。 +- `--redline-cpu-window-seconds`:平均每个节点 CPU 使用率的持续时间(以秒为单位)。默认为 30 秒。 +- `--redline-cpu-check-interval`:CPU 使用率检查之间的间隔(以秒为单位)。默认为 30 秒。 diff --git a/i18n/zh/benchmark/reference/commands/run.md b/i18n/zh/benchmark/reference/commands/run.md new file mode 100644 index 00000000..d1cc048b --- /dev/null +++ b/i18n/zh/benchmark/reference/commands/run.md @@ -0,0 +1,172 @@ +--- +title: run +--- + +<!-- vale off --> +# run 命令 +<!-- vale on --> + +无论您使用的是随附的 [OpenSearch 基准测试工作负载](https://github.com/opensearch-project/opensearch-benchmark-workloads)还是[自定义工作负载](/benchmark/creating-custom-workloads),请使用 `run` 命令根据所选工作负载收集有关 OpenSearch 集群性能的数据。 + +## 用法 + +以下示例在测试模式下使用 `geonames` 工作负载运行测试: + +``` +opensearch-benchmark run --workload=geonames --test-mode +``` + +测试运行后,OpenSearch 基准测试会响应基准测试指标的摘要: + +``` +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|-------------------------------:|---------------------:|----------:|-------:| +| Total indexing time | | 28.0997 | min | +| Total merge time | | 6.84378 | min | +| Total refresh time | | 3.06045 | min | +| Total flush time | | 0.106517 | min | +| Total merge throttle time | | 1.28193 | min | +| Median CPU usage | | 471.6 | % | +| Total Young Gen GC | | 16.237 | s | +| Total Old Gen GC | | 1.796 | s | +| Index size | | 2.60124 | GB | +| Total written | | 11.8144 | GB | +| Heap used for segments | | 14.7326 | MB | +| Heap used for doc values | | 0.115917 | MB | +| Heap used for terms | | 13.3203 | MB | +| Heap used for norms | | 0.0734253 | MB | +| Heap used for points | | 0.5793 | MB | +| Heap used for stored fields | | 0.643608 | MB | +| Segment count | | 97 | | +| Min Throughput | index-append | 31925.2 | docs/s | +| Median Throughput | index-append | 39137.5 | docs/s | +| Max Throughput | index-append | 39633.6 | docs/s | +| 50.0th percentile latency | index-append | 872.513 | ms | +| 90.0th percentile latency | index-append | 1457.13 | ms | +| 99.0th percentile latency | index-append | 1874.89 | ms | +| 100th percentile latency | index-append | 2711.71 | ms | +| 50.0th percentile service time | index-append | 872.513 | ms | +| 90.0th percentile service time | index-append | 1457.13 | ms | +| 99.0th percentile service time | index-append | 1874.89 | ms | +| 100th percentile service time | index-append | 2711.71 | ms | +| ... | ... | ... | ... | +| ... | ... | ... | ... | +| Min Throughput | painless_dynamic | 2.53292 | ops/s | +| Median Throughput | painless_dynamic | 2.53813 | ops/s | +| Max Throughput | painless_dynamic | 2.54401 | ops/s | +| 50.0th percentile latency | painless_dynamic | 172208 | ms | +| 90.0th percentile latency | painless_dynamic | 310401 | ms | +| 99.0th percentile latency | painless_dynamic | 341341 | ms | +| 99.9th percentile latency | painless_dynamic | 344404 | ms | +| 100th percentile latency | painless_dynamic | 344754 | ms | +| 50.0th percentile service time | painless_dynamic | 393.02 | ms | +| 90.0th percentile service time | painless_dynamic | 407.579 | ms | +| 99.0th percentile service time | painless_dynamic | 430.806 | ms | +| 99.9th percentile service time | painless_dynamic | 457.352 | ms | +| 100th percentile service time | painless_dynamic | 459.474 | ms | + +------------------------------------- +[INFO] ✅ SUCCESS (took 2634 seconds) +------------------------------------- +``` + +## 选项 + +使用以下选项可针对您的用例自定义 `run` 命令。本节中的选项按其用例分类。 + +## 常规设置 + +以下选项定义每个测试的运行方式以及结果的显示方式: + +- `--test-mode`:在测试模式下运行给定的工作负载,这在检查工作负载是否有错误时很有用。 +- `--user-tag`:定义要在指标记录中用作元信息的用户特定键值对,例如 `intention:baseline-ticket-12345`。 +- `--results-format`:定义命令行结果的输出格式,可以是 `markdown` 或 `csv`。默认为 `markdown`。 +- `--results-number-align`:定义 `compare` 命令输出结果时的列数字对齐方式。默认为 `right`。 +- `--results-file`:当提供文件路径时,将比较结果写入路径中指示的文件。 +- `--show-in-results`:确定是否在结果文件中包含比较。 + +### 分发 + +以下选项设置基准测试使用的 OpenSearch 和 OpenSearch 插件的版本: + +- `--distribution-version`:根据版本号下载指定的 OpenSearch 分发。有关已发布的 OpenSearch 版本的列表,请参阅[版本历史](https://opensearch.isharkfly.com{{site.latesturl}}/version-history/)。 +- `--distribution-repository`:定义应从中下载 OpenSearch 分发的存储库。默认为 `release`。 +- `--revision`:定义用于运行基准测试的当前源代码修订版本。默认为 `current`。 + - `current`:根据您的 OpenSearch 分发使用源树的当前修订版本。 + - `latest`:从源树的主分支获取最新的修订版本。 + - 您还可以使用源树中的时间戳或提交 ID。使用时间戳时,指定 `@ts`,其中"ts"是有效的 ISO 8601 时间戳,例如 `@2013-07-27T10:37:00Z`。 +- `--opensearch-plugins`:定义要安装的 [OpenSearch 插件](/install-and-configure/plugins)。默认情况下,不安装插件。 +- `--plugin-params:`:定义一个逗号分隔的 key:value 对列表,这些对逐字注入到所有插件中作为变量。 +- `--runtime-jdk`:要使用的 JDK 的主要版本。 +- `--client-options`:定义要使用的以逗号分隔的客户端列表。所有选项都传递给 OpenSearch Python 客户端。默认为 `timeout:60`。 + +### 集群 + +以下选项与基准测试的目标集群相关。 + +- `--target-hosts`:定义在使用管道 `benchmark-only` 时应针对的以逗号分隔的主机-端口对列表。默认为 `localhost:9200`。 + +### 分布式工作负载生成 + +以下选项帮助想要使用多个主机向基准测试集群生成负载的用户: + +- `--worker-ips`:定义协调负载的以逗号分隔的主机列表。默认为 `localhost`。 +- `--enable-worker-coordinator-profiling`:启用对 OpenSearch 基准测试工作器协调器性能的分析。默认为 `false`。 + +### 配置 + +以下选项有助于自定义 OpenSearch 基准测试如何配置 OpenSearch 和工作负载: + +- `--cluster-config-repository`:定义 OpenSearch 基准测试从中加载 `cluster-configs` 和 `cluster-config-instances` 的存储库。 +- `--cluster-config-path`:定义 `--cluster-config-instance` 和任何 OpenSearch 插件配置的路径。 +- `--cluster-config-revision`:定义 OpenSearch 基准测试应使用的 `cluster-config` 中的特定 Git 修订版本。 +- `--cluster-config-instance`:定义要使用的 `--cluster-config-instance`。您可以使用命令 `opensearch-benchmark list cluster-config-instances` 查看可能的配置实例。 +- `--cluster-config-instance-params`:作为变量逐字注入到 `cluster-config-instance` 的以逗号分隔的键值对列表。 + +### 工作负载 + +以下选项确定使用哪个工作负载来运行测试: + +- `--workload-repository`:定义 OpenSearch 基准测试从中加载工作负载的存储库。 +- `--workload-path`:定义下载或自定义工作负载的路径。 +- `--workload-revision`:定义 OpenSearch 基准测试应使用的工作负载源树中的特定修订版本。 +- `--workload`:根据工作负载的名称定义要使用的工作负载。您可以使用 `opensearch-benchmark list workloads` 找到预加载工作负载的列表。 + +### 测试程序 + +以下选项定义测试使用的测试程序以及程序中包含的操作: + +- `--test-execution-id`:为此测试运行定义唯一的 ID。 +定义每个工作负载使用的测试程序。您可以通过在 `info` 命令中指定工作负载来查找工作负载支持的测试程序列表,例如 `opensearch-benchmark info --workload=<workload_name>`。要查找有关特定测试程序的信息,请使用命令 `opensearch-benchmark info --workload=<workload_name> --test-procedure=<test-procedure>`。 +- `--include-tasks`:定义要运行的以逗号分隔的测试程序任务列表。默认情况下,运行测试程序数组中列出的所有任务。 +- `--exclude-tasks`:定义不运行的以逗号分隔的测试程序任务列表。 +- `--enable-assertions`:启用任务的断言检查。默认为 `false`。 + +### 管道 + +`--pipeline` 选项选择要运行的管道。您可以通过运行 `opensearch-benchmark list pipelines` 来查找 OpenSearch 基准测试支持的管道列表。 + +### 遥测 + +以下选项在 OpenSearch 基准测试上启用遥测设备: + +- `--telemetry`:当使用逗号分隔列表提供设备时,启用提供的遥测设备。您可以使用 `opensearch-benchmark list telemetry` 找到可能的遥测设备列表。 +- `--telemetry-params`:定义作为参数逐字注入到遥测设备中的以逗号分隔的键值对列表。 + +### 错误 + +以下选项设置 OpenSearch 基准测试在运行测试时如何处理错误: + +- `--on-error`:控制 OpenSearch 基准测试如何响应错误。默认为 `continue`。 + - `continue`:尽管出现错误,仍继续运行测试。 + - `abort`:发生错误时中止测试。 +- `--preserve-install`:保留基准测试候选及其索引。默认为 `false`。 +- `--kill-running-processes`:设置为 `true` 时,停止当前正在运行的任何 OpenSearch 基准测试进程,并允许 OpenSearch 基准测试继续运行。默认为 `false`。 diff --git a/i18n/zh/benchmark/reference/workloads/parameters.md b/i18n/zh/benchmark/reference/workloads/parameters.md new file mode 100644 index 00000000..7a50fc99 --- /dev/null +++ b/i18n/zh/benchmark/reference/workloads/parameters.md @@ -0,0 +1,370 @@ +--- +title: 工作负载参数 +--- + +# 工作负载参数 + +工作负载参数允许您自定义工作负载行为,而无需直接编辑工作负载文件。您可以通过在运行时传递参数来控制诸如批量大小、分片数、索引名称和搜索配置等设置。 + +OpenSearch 基准测试工作负载使用 [Jinja2](https://jinja.palletsprojects.com/) 模板。当您使用 `--workload-params` 标志传递参数时,OpenSearch 基准测试会在执行前将它们注入到工作负载 JSON 文件中。 + +例如,工作负载的 `index.json` 可能包含以下设置: + +```json +{ + "settings": { + "index.number_of_shards": {{ number_of_shards | default(1) }}, + "index.number_of_replicas": {{ number_of_replicas | default(0) }} + } +} +``` + +当您使用 `--workload-params='{"number_of_shards": 3}'` 运行基准测试时,OpenSearch 基准测试会将 `{{ number_of_shards | default(1) }}` 替换为 `3`。您不覆盖的参数使用其默认值。 + +## 传递参数 + +您可以通过以下方式传递参数。 + +### JSON 文件(推荐用于多个参数) + +创建一个包含参数的 JSON 文件: + +```json +{ + "number_of_shards": 3, + "number_of_replicas": 1, + "bulk_size": 5000, + "target_index_name": "my_index" +} +``` + +然后按如下方式引用它: + +```bash +opensearch-benchmark run --workload=geonames --workload-params=my-params.json +``` + +### 内联 JSON + +直接在命令行上传递参数: + +```bash +opensearch-benchmark run --workload=geonames --workload-params='{"number_of_shards": 3, "bulk_size": 5000}' +``` + +### 逗号分隔的键值对 + +使用以下格式传递键值对: + +```bash +opensearch-benchmark run --workload=geonames --workload-params="number_of_shards:3,bulk_size:5000" +``` + +::: info NOTE +逗号分隔的格式仅支持字符串值。对于数字、布尔值或嵌套对象,请使用 JSON 文件或内联 JSON。 +::: + +## 参数优先级 + +当在多个来源中定义相同的参数时,OpenSearch 基准测试按以下顺序应用它们(优先级最高的优先): + +1. **`--workload-params`**(CLI 标志):覆盖所有其他值。 +1. **工作负载模板默认值**:在工作负载 JSON 文件中的 `{{ var | default(value) }}` 表达式中指定的默认值(例如 `{{ number_of_shards | default(1) }}`)。 +1. **未定义**:如果未指定默认值且未提供参数,OpenSearch 基准测试会引发模板渲染错误。 + +## 模板语法 + +本节介绍工作负载文件中使用的最常见模板模式。 + +### 带默认值的变量 + +使用 `default` 过滤器在未提供参数时指定回退值。例如,如果在 `--workload-params` 中未提供 `bulk_size`,则表达式将计算为 `5000`: + +```json +{{ bulk_size | default(5000) }} +``` + +### 布尔值 + +对布尔值使用 `tojson` 过滤器以确保正确的 JSON 输出。例如,以下表达式计算为 `false`(不带引号),而不是 `"false"`: + +```json +{{ query_cache_enabled | default(false) | tojson }} +``` + +### 字符串值 + +用引号包裹字符串变量: + +```json +"{{ conflicts | default('random') }}" +``` + +### 条件部分 + +使用 `{% if %}` 块根据参数是否定义或参数值来包含或排除部分。 + +#### 仅在定义时包含字段 + +以下模板有条件地包含 `target-throughput` 字段。如果未使用 `--workload-params` 提供 `target_throughput`,则整个字段将从渲染输出中省略: + +```json +{% if target_throughput is defined %} +"target-throughput": {{ target_throughput }}, +{% endif %} +``` + +<!-- vale off --> +#### If/else 用于替代值 +<!-- vale on --> + +使用 `{% else %}` 提供回退。例如,如果在 `--workload-params` 中将 `use_zstd` 设置为 `true`,则渲染的输出会将 `source-file` 参数设置为 `documents.json.zst`。否则,它将 `source-file` 设置为 `documents.json.bz2`: + +```json +{% if use_zstd %} +"source-file": "documents.json.zst", +{% else %} +"source-file": "documents.json.bz2", +{% endif %} +``` + +#### 有条件地添加索引字段 + +此模式通常用于在 `vectorsearch` 工作负载模板中定义可选字段。`{%- endif %}`(带破折号)修剪尾随空格和换行符,防止出现空行并避免无效的 JSON 格式(如尾随逗号或错位的结构): + +```json +"properties": { + {% if id_field_name is defined and id_field_name != "_id" %} + "{{ id_field_name }}": { + "type": "keyword" + }, + {%- endif %} + "embedding": { + "type": "knn_vector", + "dimension": {{ target_index_dimension }} + } +} +``` + +#### 基于版本的条件 + +一些工作负载根据 `distribution_version` 调整其行为,OpenSearch 基准测试根据目标集群自动设置该版本。此模式允许单个工作负载通过有条件地包含特定于版本的操作或设置来支持多个 OpenSearch 版本: + +```json +{% if distribution_version is not defined %} + {% set distribution_version = "2.11.0" %} +{% endif %} + +{% if distribution_version.split('.') | map('int') | list >= "2.19.1".split('.') | map('int') | list %} + {# 包含 2.19.1+ 中可用的功能 #} +{% endif %} +``` + +#### For 循环 + +使用 `{% for %}` 循环生成重复的结构: + +```json +{% for i in range(1, 101) %} +{ + "name": "query-{{ i }}", + "operation-type": "search", + "body": { ... } +}, +{% endfor %} +``` + +### 整数转换 + +当参数必须是整数时,使用 `int` 过滤器: + +```json +{{ target_index_dimension | default(768) | int }} +``` + +### 包含外部文件 + +工作负载通常被组织成多个文件以提高可读性。`{{ benchmark.collect }}` 助手在渲染时从多个 JSON 文件组成单个工作负载定义。 + +#### 导入助手 + +每个使用 `benchmark.collect` 的 `workload.json` 都必须在文件顶部导入它: + +```json +{% import "benchmark.helpers" as benchmark with context %} +``` + +`with context` 子句确保所有工作负载参数在包含的文件中可用。 + +#### 收集操作和测试程序 + +典型的 `workload.json` 将其操作和测试程序委托给单独的文件: + +```json +{% import "benchmark.helpers" as benchmark with context %} +{ + "version": 2, + "description": "My workload", + "indices": [ ... ], + "corpora": [ ... ], + "operations": [ + {{ benchmark.collect(parts="operations/*.json") }} + ], + "test_procedures": [ + {{ benchmark.collect(parts="test_procedures/*.json") }} + ] +} +``` + +`parts` 参数接受 glob 模式。模式 `operations/*.json` 匹配 `operations/` 目录中的所有 JSON 文件,并包含其内容,用逗号分隔。这使主 `workload.json` 保持简洁,而操作和测试程序定义则在单独的文件中定义。 + +#### 从共享部分组合调度 + +测试程序可以重用常见的调度片段。例如,`vectorsearch` 工作负载在 `test_procedures/common/` 下有共享的调度: + +``` +test_procedures/ + common/ + index-only-schedule.json + search-only-schedule.json + force-merge-schedule.json + vespa-search-only-schedule.json + default.json +``` + +`default.json` 中的测试程序从这些部分组成其调度: + +```json +{ + "name": "no-train-test", + "default": true, + "schedule": [ + {{ benchmark.collect(parts="common/index-only-schedule.json") }}, + {{ benchmark.collect(parts="common/force-merge-schedule.json") }}, + {{ benchmark.collect(parts="common/search-only-schedule.json") }} + ] +} +``` + +每个收集的文件都包含一个或多个调度条目。这些文件中的参数(如 `{{ target_index_name }}`)从在命令行上传递的相同 `--workload-params` 中解析,因为 `with context` 导入会将所有参数传播到包含的文件。 + +#### 索引主体文件 + +索引定义中的 `body` 字段引用映射和设置的单独 JSON 文件: + +```json +"indices": [ + { + "name": "geonames", + "body": "index.json" + } +] +``` + +`index.json` 文件是一个 Jinja2 模板,就像任何其他工作负载文件一样,因此它可以使用参数: + +```json +{ + "settings": { + "index.number_of_shards": {{ number_of_shards | default(1) }} + }, + "mappings": { ... } +} +``` + +## 发现可用参数 + +要查看工作负载支持的参数,请使用 `info` 命令。此命令列出工作负载的测试程序及其可配置参数和默认值: + +```bash +opensearch-benchmark info --workload=geonames +``` + +您还可以直接检查工作负载源。参数在工作负载 JSON 文件中显示为 `{{ variable_name | default(value) }}`。主要工作负载文件如下: + +- `workload.json` -- 顶级工作负载定义。 +- `index.json` -- 索引设置和映射。 +- `test_procedures/default.json` -- 测试程序调度。 +- `_operations/default.json` -- 操作定义。 + +## 常见参数 + +以下参数由大多数官方工作负载支持。 + +| 参数 | 描述 | 默认值 | +|-----------|-------------|-----------------| +| `number_of_shards` | 创建的索引的主分片数。 | `1` | +| `number_of_replicas` | 创建的索引的副本数。 | `0` | +| `bulk_size` | 每个批量请求的文档数。 | `5000` 或 `10000` | +| `bulk_indexing_clients` | 并发批量索引客户端的数量。 | `8` | +| `ingest_percentage` | 要摄取的文档语料库的百分比。 | `100` | +| `target_throughput` | 每个客户端每秒的目标操作数。 | 无限制 | +| `search_clients` | 并发搜索客户端的数量。 | `1` | +| `cluster_health` | 继续之前所需的集群健康状态。 | `green` | +| `source_enabled` | 是否存储 `_source` 字段。 | `true` | + +## 向量搜索工作负载参数 + +`vectorsearch` 工作负载支持用于向量搜索基准测试的其他参数。 + +| 参数 | 描述 | 默认值 | +|-----------|-------------|---------| +| `target_index_name` | 向量索引名称。 | `target_index` | +| `target_field_name` | 向量字段名称。| `target_field` | +| `target_index_dimension` | 向量维数。 | `768` | +| `target_index_space_type` | 距离度量。有效值为 `l2`、`innerproduct` 和 `cosinesimil`。 | 变化 | +| `target_index_body` | 索引设置文件的路径。 | `indices/faiss-index.json` | +| `target_index_bulk_size` | 每个批量请求的文档数。 | `500` | +| `target_index_bulk_index_data_set_format` | 语料库格式。有效值为 `hdf5` 和 `bigann`。 | `hdf5` | +| `target_index_bulk_index_data_set_corpus` | 语料库名称(例如 `cohere-1m`)。 | 变化 | +| `target_index_bulk_indexing_clients` | 并发索引客户端的数量。 | `10` | +| `target_index_max_num_segments` | 强制合并后的段数。 | `1` | +| `hnsw_ef_construction` | HNSW 图构建时探索因子。 | `256` | +| `hnsw_ef_search` | HNSW 搜索时探索因子。 | `256` | +| `query_k` | 要检索的最近邻的数量。 | `100` | +| `query_count` | 要运行的查询数。使用 `-1` 表示所有查询。 | `-1` | +| `query_data_set_format` | 查询向量格式。有效值为 `hdf5` 和 `bigann`。 | `hdf5` | +| `query_data_set_corpus` | 查询向量语料库名称。 | 变化 | +| `search_clients` | 并发搜索客户端的数量。 | `1` | +| `neighbors_data_set_corpus` | 用于召回评估的真实邻居语料库。| 变化 | +| `neighbors_data_set_format` | 邻居数据集格式。 | `hdf5` | + +### 向量搜索参数文件示例 + +以下示例显示了 `vectorsearch` 工作负载的完整参数文件: + +```json +{ + "target_index_name": "vector_1m", + "target_field_name": "embedding", + "target_index_body": "indices/faiss-index.json", + "target_index_primary_shards": 1, + "target_index_replica_shards": 0, + "target_index_dimension": 768, + "target_index_space_type": "innerproduct", + "target_index_bulk_size": 500, + "target_index_bulk_index_data_set_format": "hdf5", + "target_index_bulk_index_data_set_corpus": "cohere-1m", + "target_index_bulk_indexing_clients": 10, + "target_index_max_num_segments": 1, + "hnsw_ef_construction": 200, + "hnsw_ef_search": 256, + "query_k": 100, + "query_data_set_format": "hdf5", + "query_data_set_corpus": "cohere-1m", + "query_count": 10000, + "search_clients": 1, + "neighbors_data_set_corpus": "cohere-1m", + "neighbors_data_set_format": "hdf5" +} +``` + +要使用此参数文件,请将其保存为 `params.json` 并使用 `--workload-params` 标志运行基准测试: + +```bash +opensearch-benchmark run \ + --pipeline=benchmark-only \ + --workload-path=/path/to/vectorsearch \ + --workload-params=params.json \ + --target-hosts=localhost:9200 +``` diff --git a/i18n/zh/benchmark/reference/workloads/schedule.md b/i18n/zh/benchmark/reference/workloads/schedule.md new file mode 100644 index 00000000..c5beac9a --- /dev/null +++ b/i18n/zh/benchmark/reference/workloads/schedule.md @@ -0,0 +1,235 @@ +--- +title: schedule +--- + +<!-- vale off --> +# schedule 元素 +<!-- vale on --> + +`schedule` 元素包含在基准测试期间按指定顺序运行的任务列表。每个任务都是 OpenSearch 基准测试支持的操作。 + +您可以在以下任一位置定义 `schedule`: + +- 在 `workload.json` 的顶层。当工作负载定义单个基准测试场景时使用此形式。OpenSearch 基准测试将调度视为隐式默认测试程序。 +- 在测试程序内部,在 [`test_procedures`](/benchmark/reference/workloads/test-procedures) 元素中。当工作负载定义多个场景时使用此形式,每个场景都有自己的名称、描述和调度。 + +## 示例 + +以下 `schedule` 创建索引,等待集群变为健康,批量索引文档,然后运行 `match_all` 查询: + +```json + "schedule": [ + { + "operation": { + "operation-type": "create-index" + } + }, + { + "operation": { + "operation-type": "cluster-health", + "request-params": { + "wait_for_status": "green" + }, + "retry-until-success": true + } + }, + { + "operation": { + "operation-type": "bulk", + "bulk-size": 5000 + }, + "warmup-time-period": 120, + "clients": 8 + }, + { + "operation": { + "name": "query-match-all", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "iterations": 1000, + "target-throughput": 100 + } + ] +``` + +根据此 `schedule`,操作按以下顺序运行: + +1. `create-index` 操作创建索引。索引保持为空,直到 `bulk` 操作添加包含基准测试数据的文档。 +2. `cluster-health` 操作在运行工作负载之前评估集群的健康状况。在此示例中,工作负载等待直到集群的健康状态为 `green`。 + - `bulk` 操作运行 `bulk` API 以同时索引 `5000` 个文档。 + - 在基准测试之前,工作负载等待直到指定的 `warmup-time-period` 过去。在此示例中,预热期为 `120` 秒。 +3. `clients` 字段定义并发运行批量索引操作的客户端数量,在此示例中为 8 个。 +4. `search` 操作在文档使用指定的客户端通过 `bulk` API 索引后运行 `match_all` 查询以匹配所有文档。 + - `iterations` 字段定义每个客户端运行 `search` 操作的次数。基准测试报告会根据此数字自动调整百分位数。要生成精确的百分位数,基准测试需要至少运行 1,000 次迭代。 + - `target-throughput` 字段定义每个客户端每秒执行的请求数。此设置可以帮助降低基准测试延迟。例如,100 个请求的 `target-throughput` 除以 8 个客户端意味着每个客户端每秒发出 12 个请求。有关如何在 OpenSearch 基准测试中定义目标吞吐量的更多信息,请参阅[目标吞吐量](/benchmark/target-throughput)。 + +## 定义任务 + +`schedule` 元素使用本节中描述的方法定义任务。 + +### 使用 operations 元素 + +以下示例使用 `operations` 元素定义 `force-merge` 和 `match-all` 查询任务。`force-merge` 操作不使用任何参数,因此只需要 `name` 和 `operation-type`。`match-all-query` 参数需要查询 `body` 和 `operation-type`。 + +在 `operations` 元素中定义的操作可以在调度中重用多次: + +```yml +{ + "operations": [ + { + "name": "force-merge", + "operation-type": "force-merge" + }, + { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + } + ], + "schedule": [ + { + "operation": "force-merge", + "clients": 1 + }, + { + "operation": "match-all-query", + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] +} +``` + +有关可用操作类型的完整列表,请参阅 [`operations`](/benchmark/reference/workloads/operations)。 + +### 内联定义操作 + +如果您不想在调度中重用操作,可以在 `schedule` 元素内部定义操作,如以下示例所示: + +```yml +{ + "schedule": [ + { + "operation": { + "name": "force-merge", + "operation-type": "force-merge" + }, + "clients": 1 + }, + { + "operation": { + "name": "match-all-query", + "operation-type": "search", + "body": { + "query": { + "match_all": {} + } + } + }, + "clients": 4, + "warmup-iterations": 1000, + "iterations": 1000, + "target-throughput": 100 + } + ] +} +``` + +## 任务选项 + +每个任务都包含以下选项。 + +参数 | 必需 | 类型 | 描述 +:--- | :--- | :--- | :--- +`operation` | 是 | 列表 | 引用在 `operations` 元素中定义的操作的名称,或内联包含整个操作。 +`name` | 否 | 字符串 | 当多个任务使用同一操作时,指定任务的唯一名称。 +`tags` | 否 | 字符串 | 可用于在 `tasks.clients` 或应同时执行任务的客户端数之间进行筛选的唯一标识符。默认为 1。 +`clients` | 否 | 整数 | 指定将同时运行任务的客户端数。默认为 `1`。 + +## 目标选项 + +OpenSearch 基准测试在运行任务时需要以下选项之一。 + +参数 | 必需 | 类型 | 描述 +:--- | :--- | :--- | :--- +`target-throughput` | 否 | 整数 | 定义基准测试模式。未定义时,OpenSearch 基准测试假定它是吞吐量基准测试,并尽可能快地运行任务。这对于批处理操作很有用,在批处理操作中,实现更好的吞吐量优于更好的延迟。定义后,目标指定所有客户端每秒的请求数。例如,如果您指定 `target-throughput: 1000` 和 8 个客户端,每个客户端每秒发出 125(= 1000 / 8)个请求。 +`target-interval` | 否 | 间隔 | 当 `target-throughput` 小于每秒 1 次操作时,定义 1 除以 `target-throughput`(以秒为单位)的间隔。定义 `target-throughput` 或 `target-interval` 中的一个,但不能同时定义两者,否则 OpenSearch 基准测试会引发错误。 +`ignore-response-error-level` | 否 | 布尔值 | 控制当使用 `on-error=abort` 命令标志运行基准测试时是否忽略任务期间遇到的错误。 + +## 基于迭代的选项 + +基于迭代的选项确定操作应运行的次数。它们还可以在任务[并行](#parallel-tasks)运行时定义迭代运行的次数。要配置基于迭代的调度,请使用以下选项。 + +参数 | 必需 | 类型 | 描述 +:--- | :--- | :--- | :--- +`iterations` | 否 | 整数 | 指定客户端应执行操作的次数。所有迭代都包含在测量结果中。默认为 `1`。 +`warmup-iterations` | 否 | 整数 | 指定客户端应执行操作的次数,以便预热基准测试候选。`warmup-iterations` 不会出现在测量结果中。默认为 `0`。 + +## 基于时间的选项 + +基于时间的选项确定操作应运行的持续时间(以秒为单位)。这对于批处理样式的操作非常理想,这些操作可能需要额外的预热期。 + +要配置基于时间的调度,请使用以下选项。 + +参数 | 必需 | 类型 | 描述 +:--- | :--- | :--- | :--- +`time-period` | 否 | 整数 | 指定 OpenSearch 基准测试考虑用于测量的时间段(以秒为单位)。这对于批量索引不是必需的,因为 OpenSearch 基准测试批量索引所有文档,并自然地在指定的 `warmup-time-period` 之后测量所有样本。 +`ramp-up-time-period` | 否 | 整数 | 指定 OpenSearch 基准测试逐渐添加客户端并达到为操作指定的客户端总数的时间段(以秒为单位)。 +`warmup-time-period` | 否 | 整数 | 指定预热基准测试候选的时间量(以秒为单位)。预热期间捕获的响应数据都不会出现在测量结果中。 + +## 并行任务 + +`parallel` 元素同时运行包装在元素内的任务。 + +并行运行任务时,每个任务都需要 `client` 选项,以确保为该任务保留基准测试中的客户端。否则,当在 `parallel` 元素内部指定 `client` 选项而没有连接到任务时,基准测试将该数量的客户端用于所有任务。 + +在以下示例中,`parallel-task-1` 和 `parallel-task-2` 同时执行 `bulk` 操作: + +```yml +{ + "name": "parallel-any", + "description": "Workload completed-by property", + "schedule": [ + { + "parallel": { + "tasks": [ + { + "name": "parellel-task-1", + "operation": { + "operation-type": "bulk", + "bulk-size": 1000 + }, + "clients": 8 + }, + { + "name": "parellel-task-2", + "operation": { + "operation-type": "bulk", + "bulk-size": 500 + }, + "clients": 8 + } + ] + } + } + ] +} +``` + +`parallel` 元素支持所有 `schedule` 参数,以及以下选项。 + +参数 | 必需 | 类型 | 描述 +:--- | :--- | :--- | :--- +`tasks` | 是 | 数组 | 定义应同时执行的任务列表。 +`completed-by` | 否 | 字符串 | 允许您定义任务列表中一个任务的名称或值 `any`。如果 `completed-by` 设置为列表中一个任务的名称,则 `parallel-task` 结构在该特定任务完成后即被视为完成。如果 `completed-by` 设置为 `any`,则 `parallel-task` 结构在列表中的任何一个任务完成后即被视为完成。如果未显式定义 `completed-by`,则 `parallel-task` 结构在列表中的所有任务完成后即被视为完成。 diff --git a/i18n/zh/benchmark/running-workloads.md b/i18n/zh/benchmark/running-workloads.md new file mode 100644 index 00000000..d8b1cc65 --- /dev/null +++ b/i18n/zh/benchmark/running-workloads.md @@ -0,0 +1,184 @@ +--- +title: 运行工作负载 +--- + +# 运行工作负载 + +一旦您完全了解 OpenSearch Benchmark [工作负载](/benchmark/anatomy-of-a-workload)的各个组成部分,您就可以运行您的第一个工作负载。 + +## 步骤 1:查找工作负载名称 + +要了解有关 OpenSearch Benchmark 中包含的标准工作负载的更多信息,请使用以下命令: + +``` +opensearch-benchmark list workloads +``` + +将显示 OpenSearch Benchmark 支持的所有工作负载的列表。查看该列表并选择最类似于您的集群用例的工作负载。 + +## 步骤 2:运行测试 + +选择工作负载后,您可以使用 `opensearch-benchmark run` 命令调用该工作负载。将 `--target-host` 替换为集群的 `host:port` 对,将 `--client-options` 替换为访问集群所需的任何授权选项。以下示例在本地主机上运行 `nyc_taxis` 工作负载以进行测试。 + +如果您想在外部集群上运行测试,请参阅[在您自己的集群上运行工作负载](#运行外部集群上的工作负载)。 + +```bash +opensearch-benchmark run --pipeline=benchmark-only --workload=nyc_taxis --target-host=https://localhost:9200 --client-options=basic_auth_user:admin,basic_auth_password:admin,verify_certs:false +``` + +测试结果将显示在 `run` 命令中 `--output-path` 选项设置的目录中。 + +### 测试模式 + +如果您想在测试模式下运行测试以确保您的工作负载按预期运行,请在 `run` 命令中添加 `--test-mode` 选项。测试模式仅从提供的每个索引中提取前 1,000 个文档,并对它们运行查询操作。 + +### 使用 `--workload-params` + +您可以通过使用 `--workload-params` 选项传递特定于工作负载的参数来自定义工作负载的行为。此标志接受以逗号分隔的键值对列表,这些键值对会覆盖工作负载的 `workload.json` 文件中定义的默认值。 + +例如,某些工作负载允许您配置索引的文档数量、用于查询执行的客户端数量或索引名称。这些参数对于根据您的特定用例或基础设施约束定制基准测试至关重要。 + +要传递工作负载参数,请使用以下语法: + +```bash +--workload-params="number_of_documents:100000,index_name:custom-index" +``` + +将此选项添加到您的 `run` 命令中,如以下示例所示: + +```bash +opensearch-benchmark run \ +--pipeline=benchmark-only \ +--workload=nyc_taxis \ +--target-host=https://localhost:9200 \ +--client-options=basic_auth_user:admin,basic_auth_password:admin,verify_certs:false \ +--workload-params="bulk_size:500,index_name:nyc_custom" +``` + +::: tip TIP +可用的工作负载参数可以在 [OpenSearch Benchmark Workloads GitHub 存储库](https://github.com/opensearch-project/opensearch-benchmark-workloads)中每个工作负载的 `README` 中找到。 +::: + +## 步骤 3:验证测试 + +运行 OpenSearch Benchmark 测试后,请采取以下步骤验证它是否正确运行: + +1. 记下您计划对其运行基准测试的 OpenSearch 或 OpenSearch Dashboards 索引中的文档数量。 +2. 在 OpenSearch Benchmark 返回的结果中,比较您特定工作负载的 `workload.json` 文件,并验证文档计数是否与文档数量匹配。例如,根据 [nyc_taxis](https://github.com/opensearch-project/opensearch-benchmark-workloads/blob/main/nyc_taxis/workload.json#L20) `workload.json` 文件,您应该期望在集群中看到 `165346692` 个文档。 + +## 预期结果 + +基准测试完成后,OSB 返回以下响应: + +```bash +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 0.02655 | min | +| Min cumulative indexing time across primary shards | | 0 | min | +| Median cumulative indexing time across primary shards | | 0.00176667 | min | +| Max cumulative indexing time across primary shards | | 0.0140333 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 0.0102333 | min | +| Cumulative merge count of primary shards | | 3 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0 | min | +| Max cumulative merge time across primary shards | | 0.0102333 | min | +| Cumulative merge throttle time of primary shards | | 0 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0 | min | +| Cumulative refresh time of primary shards | | 0.0709333 | min | +| Cumulative refresh count of primary shards | | 118 | | +| Min cumulative refresh time across primary shards | | 0 | min | +| Median cumulative refresh time across primary shards | | 0.00186667 | min | +| Max cumulative refresh time across primary shards | | 0.0511667 | min | +| Cumulative flush time of primary shards | | 0.00963333 | min | +| Cumulative flush count of primary shards | | 4 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0 | min | +| Max cumulative flush time across primary shards | | 0.00398333 | min | +| Total Young Gen GC time | | 0 | s | +| Total Young Gen GC count | | 0 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 0.000485923 | GB | +| Translog size | | 2.01873e-05 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 32 | | +| Min Throughput | index | 3008.97 | docs/s | +| Mean Throughput | index | 3008.97 | docs/s | +| Median Throughput | index | 3008.97 | docs/s | +| Max Throughput | index | 3008.97 | docs/s | +| 50th percentile latency | index | 351.059 | ms | +| 100th percentile latency | index | 365.058 | ms | +| 50th percentile service time | index | 351.059 | ms | +| 100th percentile service time | index | 365.058 | ms | +| error rate | index | 0 | % | +| Min Throughput | wait-until-merges-finish | 28.41 | ops/s | +| Mean Throughput | wait-until-merges-finish | 28.41 | ops/s | +| Median Throughput | wait-until-merges-finish | 28.41 | ops/s | +| Max Throughput | wait-until-merges-finish | 28.41 | ops/s | +| 100th percentile latency | wait-until-merges-finish | 34.7088 | ms | +| 100th percentile service time | wait-until-merges-finish | 34.7088 | ms | +| error rate | wait-until-merges-finish | 0 | % | +| Min Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| Mean Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| Median Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| Max Throughput | percolator_with_content_president_bush | 36.09 | ops/s | +| 100th percentile latency | percolator_with_content_president_bush | 35.9822 | ms | +| 100th percentile service time | percolator_with_content_president_bush | 7.93048 | ms | +| error rate | percolator_with_content_president_bush | 0 | % | + +[...] + +| Min Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| Mean Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| Median Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| Max Throughput | percolator_with_content_ignore_me | 16.1 | ops/s | +| 100th percentile latency | percolator_with_content_ignore_me | 131.798 | ms | +| 100th percentile service time | percolator_with_content_ignore_me | 69.5237 | ms | +| error rate | percolator_with_content_ignore_me | 0 | % | +| Min Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| Mean Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| Median Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| Max Throughput | percolator_no_score_with_content_ignore_me | 29.37 | ops/s | +| 100th percentile latency | percolator_no_score_with_content_ignore_me | 45.5703 | ms | +| 100th percentile service time | percolator_no_score_with_content_ignore_me | 11.316 | ms | +| error rate | percolator_no_score_with_content_ignore_me | 0 | % | + +----------------------------------- +[INFO] ✅ SUCCESS (took 18 seconds) +----------------------------------- +``` + +## 运行外部集群上的工作负载 + +现在您已经熟悉了在本地集群上运行 OpenSearch Benchmark,您可以在外部集群上运行它,如以下步骤所述: + +1. 将 `https://localhost:9200` 替换为您的目标集群端点。这可以是统一资源标识符 (URI),例如 `https://search.mydomain.com`,或 `HOST:PORT` 规范。 +2. 如果集群配置了基本身份验证,请将命令行中的用户名和密码替换为适当的凭据。 +3. 如果您没有将 `localhost` 指定为目标集群,请删除 `verify_certs:false` 指令。此指令仅对没有 SSL 证书的集群是必需的。 +4. 如果您使用 `HOST:PORT` 规范并计划使用 SSL 或 TLS,请指定 `https://` 或将 `use_ssl:true` 指令添加到 `--client-options` 字符串选项。 +5. 删除 `--test-mode` 标志以运行完整的工作负载而不是缩写测试。 + +您可以复制以下命令模板以在您自己的终端中使用它: + +```bash +opensearch-benchmark run --pipeline=benchmark-only --workload=nyc_taxis --target-host=<OpenSearch Cluster Endpoint> --client-options=basic_auth_user:admin,basic_auth_password:admin +``` diff --git a/i18n/zh/benchmark/target-throughput.md b/i18n/zh/benchmark/target-throughput.md new file mode 100644 index 00000000..6374ede3 --- /dev/null +++ b/i18n/zh/benchmark/target-throughput.md @@ -0,0 +1,79 @@ +--- +title: 目标吞吐量 +--- + +# 目标吞吐量 + +目标吞吐量是理解 OpenSearch Benchmark 对*延迟*定义的关键。目标吞吐量是 OpenSearch Benchmark 发出请求的速率,假设响应会立即返回。`target-throughput` 是一个常见的工作负载参数,可以为每个测试设置,以每秒操作数为单位进行测量。 + +OpenSearch Benchmark 有两种测试模式,它们都与吞吐量、延迟和服务时间相关: + +- [基准测试模式](#benchmarking-mode):延迟的测量方式与服务时间相同。 +- [吞吐量限制模式](#throughput-throttled-mode):延迟测量为服务时间加上请求在队列中等待的时间。 + +## 基准测试模式 + +当 `target-throughput` 设置为 `0` 时,OpenSearch Benchmark 延迟测试以*基准测试模式*执行。在此模式下,OpenSearch 客户端尽可能快地向 OpenSearch 集群发送请求。在集群从上一个请求收到响应后,OpenSearch Benchmark 会立即向 OpenSearch 客户端发送下一个请求。在此测试模式下,延迟与服务时间相同。 + +OpenSearch Benchmark 一次为单个客户端发出一个请求。客户端数量由工作负载参数中的 `search-clients` 设置确定。 + +## 吞吐量限制模式 + +如果 `target-throughput` 未设置为 `0`,则 OpenSearch Benchmark 会根据 `target-throughput` 发出下一个请求,假设响应会立即返回。 + +**吞吐量**测量 OpenSearch Benchmark 发出请求的速率,假设响应会立即返回。要配置请求速率,您可以将 `target-throughput` 工作负载参数设置为每个测试所需的每秒操作数。 + +当您想要模拟部署生产集群时可能遇到的流量类型时,请将基准测试中的 `target-throughput` 设置为与您估计生产集群可能接收的请求数相匹配。以下示例展示了 `target-throughput` 设置如何影响延迟测量。 + +### 示例 A + +以下图表说明了如何计算延迟,预期请求响应时间为 200 毫秒,并具有以下设置: + +- `search-clients` 设置为 `1`。 +- `target-throughput` 设置为每秒 `1` 次操作。 + +![显示每秒 1 次操作时预期 200 毫秒响应时间的请求调度](/images/benchmark/latency-explanation-1.png) + +当请求花费的时间超过 200 毫秒时,例如当请求花费 1110 毫秒而不是 400 毫秒时,OpenSearch Benchmark 会发送原本应该在 4.00 秒时基于 `target-throughput` 发生的下一个请求,改为在 4.10 秒时发送。4.10 秒请求之后的所有后续请求都会尝试重新与 `target-throughput` 设置同步,如下图所示: + +![显示延迟请求与目标吞吐量重新同步的请求调度](/images/benchmark/latency-explanation-2.png) + +在测量总体延迟时,OpenSearch Benchmark 包括所有执行的请求。所有请求的延迟都为 200 毫秒,除了以下两个请求: + +- 持续 1100 毫秒的请求。 +- 应该在 4.00 秒开始的后续请求。此请求延迟了 100 毫秒,在下图中用橙色区域表示,响应时间为 200 毫秒。在计算此请求的延迟时,OpenSearch Benchmark 考虑了延迟的开始时间并将其与响应时间相结合。此请求的延迟为 **300 毫秒**。 + +![显示延迟请求的延迟计算,包含等待时间和响应时间](/images/benchmark/latency-explanation-3.png) + +### 示例 B + +在此示例中,OpenSearch Benchmark 假设延迟为 200 毫秒,并使用以下延迟设置: + +- `search_clients` 设置为 `1`。 +- `target-throughput` 设置为每秒 `10` 次操作。 + +下图显示了 OpenSearch Benchmark 使用预期响应时间构建的调度。 + +![目标吞吐量为每秒 10 次操作和预期 200 毫秒响应时间的请求调度](/images/benchmark/b-latency-explanation-1.png) + +但是,如果假设所有响应的延迟都为 200 毫秒,那么每秒 10 次操作是不可能的。因此,OpenSearch Benchmark 可以达到的最高吞吐量是每秒 5 次操作,如下图所示。 + +![由于 200 毫秒响应时间,实际吞吐量限制为每秒 5 次操作](/images/benchmark/b-latency-explanation-2.png) + +OpenSearch Benchmark 不考虑此限制,继续尝试达到每秒 10 次操作的 `target-throughput`。因此,每个请求的延迟开始级联,如下图所示。 + +![OpenSearch Benchmark 尝试维持超出容量的目标吞吐量时的级联延迟](/images/benchmark/b-latency-explanation-3.png) + +通过组合每个操作的服务时间和延迟,为每个操作提供以下延迟测量: + +- 操作 1 为 200 毫秒 +- 操作 2 为 300 毫秒 +- 操作 3 为 400 毫秒 +- 操作 4 为 500 毫秒 +- 操作 5 为 600 毫秒 + +这种延迟级联持续下去,每个后续请求的延迟增加 100 毫秒。 + +### 建议 + +如前面的示例所示,您应该了解每个任务的平均服务时间,并提供考虑服务时间的 `target-throughput`。OpenSearch Benchmark 延迟是根据用户设置的 `target-throughput` 计算的;因此,*延迟*可以重新定义为*基于吞吐量的延迟*。 diff --git a/i18n/zh/benchmark/user-guide/install-and-configure/configuring-benchmark.md b/i18n/zh/benchmark/user-guide/install-and-configure/configuring-benchmark.md new file mode 100644 index 00000000..114c9e98 --- /dev/null +++ b/i18n/zh/benchmark/user-guide/install-and-configure/configuring-benchmark.md @@ -0,0 +1,297 @@ +--- +title: 配置 +--- + +# 配置 OpenSearch 基准测试 + +OpenSearch 基准测试配置数据存储在 `~/.benchmark/benchmark.ini` 中,该文件在 OpenSearch 基准测试首次运行时自动创建。 + +该文件分为以下部分,您可以根据集群的需要进行自定义。 + +## client_options + +本节说明如何在基准测试执行期间使用 `--client-options` 命令行标志自定义客户端级别的设置。 + +您可以使用 `--client-options` 标志向 OpenSearch 基准测试传递特定于客户端的参数。这些参数允许您控制低级客户端行为,例如超时、身份验证方法和 SSL 设置。 + +`--client-options` 标志接受以逗号分隔的键值对列表,如以下示例所示: + +```bash +--client-options=timeout:120,verify_certs:false +``` + +您可以使用以下设置自定义 `--client-options`。 + +| 选项 | 类型 | 描述 | +| :---- | :---- | :---- | +| `timeout` | 整数 | 设置请求超时值(以秒为单位)。 | +| `verify_certs` | 布尔值 | 确定连接到 OpenSearch 集群时是否验证 SSL 证书。 | +| `basic_auth_user` | 字符串 | 用于对 OpenSearch 集群进行身份验证的用户名(如果启用了身份验证)。 | +| `basic_auth_password` | 字符串 | 用于对 OpenSearch 集群进行身份验证的密码(如果启用了身份验证)。 | + +此示例使用 2 分钟超时和禁用证书验证运行基准测试: + +```bash +opensearch-benchmark run \ +--target-hosts=https://localhost:9200 \ +--pipeline=benchmark-only \ +--workload=geonames \ +--client-options=timeout:120,verify_certs:false +``` + +<!-- vale off --> +## meta +<!-- vale on --> + +本节包含有关配置文件的元信息。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `config.version` | 整数 | 配置文件格式的版本。此属性由 OpenSearch 基准测试管理,不应更改。 | + +<!-- vale off --> +## system +<!-- vale on --> + +本节包含当前基准测试环境的全局信息。此信息在安装 OpenSearch 基准测试的所有机器上应该相同。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `env.name` | 字符串 | 配置 OpenSearch 指标存储时用作指标文档中的元数据的基准测试环境的名称。仅允许字母数字字符。默认为 `local`。 | +| `available.cores` | 整数 | 确定可用 CPU 核心的数量。OpenSearch 基准测试旨在为每个核心创建一个 `asyncio` 事件循环,并将其均匀分配给客户端。默认为集群的逻辑 CPU 核心数。 | +| `async.debug` | 布尔值 | 在 OpenSearch 基准测试的 `asyncio` 事件循环上启用调试模式。默认为 `false`。 | +| `passenv` | 字符串 | 应传递给 OpenSearch 进行处理的环境变量名称的逗号分隔列表。 | + +<!-- vale off --> +## node +<!-- vale on --> + +本节包含特定于节点的信息,可以根据集群的需要进行自定义。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `root.dir` | 字符串 | 存储所有 OpenSearch 基准测试数据的目录。OpenSearch 基准测试假定控制此目录及其所有子目录。 | +| `src.root.dir` | 字符串 | 从中调用 OpenSearch 源代码和任何 OpenSearch 插件的目录。仅与[源](#source)的基准测试相关。 | + +<!-- vale off --> +## source +<!-- vale on --> + +本节包含有关 OpenSearch 源树的更多详细信息。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `remote.repo.url` | URL | 从中检出 OpenSearch 的 URL。默认为 `https://github.com/opensearch-project/OpenSearch.git`。 +| `opensearch.src.subdir` | 字符串 | OpenSearch 搜索树的 `src.root.dir` 相对的本地路径。默认为 `OpenSearch`。 +| `cache` | 布尔值 | 启用 OpenSearch 的内部源工件缓存、`opensearch*.tar.gz` 和任何插件 zip 文件。工件根据其 Git 修订版本缓存。默认为 `true`。 | +| `cache.days` | 整数 | 工件应保留在源工件缓存中的天数。默认为 `7`。 | + +<!-- vale off --> +## benchmarks +<!-- vale on --> + +本节包含可以在 OpenSearch 基准测试数据目录中自定义的设置。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `local.dataset.cache` | 字符串 | 存储基准测试数据集的目录。根据运行的基准测试,此目录可能包含数百 GB 的数据。默认路径为 `$HOME/.benchmark/benchmarks/data`。 | + +<!-- vale off --> +## reporting +<!-- vale on --> + +本节定义如何存储基准测试指标。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `datastore.type` | 字符串 | 如果设置为 `in-memory`,则在运行基准测试时将所有指标保存在内存中。如果设置为 `opensearch`,则所有指标都会写入持久指标存储,并且数据可用于进一步分析。默认为 `in-memory`。 | +| `sample.queue.size` | 函数 | 可以存储在 OpenSearch 基准测试内存队列中的指标样本数。默认为 `2^20`。 | +| metrics.request.downsample.factor | 整数 |(默认值:1):确定在指标存储中保存多少服务时间和延迟样本。默认情况下,保存所有值。例如,如果您想只保留每 100 个样本,请指定 `100`。这对于避免在具有许多客户端的基准测试中使指标存储不堪重负很有用。默认为 `1`。 | +| `output.processingtime` | 布尔值 | 如果设置为 `true`,OpenSearch 在命令行报告中显示额外的指标处理时间。默认为 `false`。 | + +<!-- vale off --> +### `datastore.type` 参数 +<!-- vale on --> + +当 `datastore.type` 设置为 `opensearch` 时,可以自定义以下报告设置。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `datastore.host` | IP 地址 | 指标存储的主机名,例如 `124.340.200.22`。 | +| `datastore.port`| 端口 | 指标存储的端口号,例如 `9200`。 | +| `datastore.secure` | 布尔值 | 如果设置为 `false`,OpenSearch 假定 HTTP 连接。如果设置为 true,则假定 HTTPS 连接。 | +| `datastore.ssl.verification_mode` | 字符串 | 当设置为默认值 `full` 时,会检查指标存储的 SSL 证书。要禁用证书验证,请将此值设置为 `none`。 | +| `datastore.ssl.certificate_authorities` | 字符串 | 确定证书颁发机构签名证书的本地文件系统路径。 +| `datastore.user` | 用户名 | 设置指标存储的用户名 | +| `datastore.password` | 字符串 | 设置指标存储的密码。或者,可以使用 `OSB_DATASTORE_PASSWORD` 环境变量配置此密码,这样可以避免在纯文本文件中存储凭据。如果两者都定义了密码,则环境变量优先于配置文件。 | +| `datastore.probe.cluster_version` | 字符串 | 启用指标存储版本的自动检测。默认为 `true`。 | +| `datastore.number_of_shards` | 整数 | `opensearch-*` 索引应具有的主分片数。初始索引创建后对此设置的任何更新仅适用于新的 `opensearch-*` 索引。默认为 [OpenSearch 静态索引值](/install-and-configure/configuring-opensearch/index-settings#static-index-settings)。 | +| `datastore.number_of_replicas` | 整数 | 数据存储中每个主分片包含的副本数。初始索引创建后对此设置的任何更新仅适用于新的 `opensearch-*` 索引。默认为 [OpenSearch 静态索引值](/install-and-configure/configuring-opensearch/index-settings#static-index-settings)。 | + +### 示例 + +您可以使用以下示例在集群中设置报告值。 + +此示例定义本地网络中不受保护的指标存储: + +``` +[reporting] +datastore.type = opensearch +datastore.host = 192.168.10.17 +datastore.port = 9200 +datastore.secure = false +datastore.user = +datastore.password = +``` + +此示例定义到本地网络中具有自签名证书的指标存储的安全连接: + +``` +[reporting] +datastore.type = opensearch +datastore.host = 192.168.10.22 +datastore.port = 9200 +datastore.secure = true +datastore.ssl.verification_mode = none +datastore.user = user-name +datastore.password = the-password-to-your-cluster +``` + +<!-- vale off --> +## workloads +<!-- vale on --> + +本节定义如何检索工作负载。所有键都由 OpenSearch 使用语法 `<<workload-repository-name>>.url` 读取,您可以使用 OpenSearch 基准测试 CLI `--workload-repository=workload-repository-name"` 选项进行选择。默认情况下,OpenSearch 使用 `default.url` `https://github.com/opensearch-project/opensearch-benchmark-workloads` 选择工作负载存储库。 + +<!-- vale off --> +## defaults +<!-- vale on --> + +本节定义某些 OpenSearch 基准测试 CLI 参数的默认值。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `preserve_benchmark_candidate` | 布尔值 | 确定 OpenSearch 安装在基准测试后默认是保留还是擦除。要保留单个基准测试的安装,请使用命令行标志 `--preserve-install`。默认为 `false`。 + +<!-- vale off --> +## distributions +<!-- vale on --> + +本节定义如何分发 OpenSearch 版本。 + +| 参数 | 类型 | 描述 | +| :---- | :---- | :---- | +| `release.cache` | 布尔值 | 确定是否应在本地缓存新发布的 OpenSearch 版本。 | + +## 使用 AWS 签名版本 4 运行 OpenSearch 基准测试 + +OpenSearch 基准测试支持 AWS 签名版本 4 身份验证。要使用 AWS 签名版本 4 运行 OpenSearch 基准测试,您需要设置 [AWS 身份和访问管理(IAM)用户或角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html),并使用 AWS 签名版本 4 身份验证为其提供对 OpenSearch 集群的访问权限。 + +是使用 IAM 角色还是用户取决于测试集群的访问管理要求。有关是使用 IAM 角色还是用户的更多信息,请参阅[何时创建 IAM 用户(而不是角色)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html#id_which-to-choose)。 + +### OpenSearch 基准测试版本 1.15.0 及更高版本 + +从 OpenSearch 基准测试版本 1.15.0 开始,您可以使用基于会话的身份验证,该身份验证会自动处理临时凭据生成和刷新。此方法无需手动导出 AWS 凭据: + +1. 在 AWS 管理控制台中创建 IAM 角色或用户,该角色或用户具有访问 OpenSearch 集群的必要权限。确保该角色或用户具有附加的 OpenSearch 访问所需的策略。 + +2. 使用 `--client-options=amazon_aws_log_in:session` 标志运行以下 `execute-test` 命令。OpenSearch 基准测试将自动生成临时凭据并处理自动刷新: + + ```bash + opensearch-benchmark execute-test \ + --target-hosts=<CLUSTER ENDPOINT> \ + --pipeline=benchmark-only \ + --workload=geonames \ + --client-options=timeout:120,amazon_aws_log_in:session,region:<region>,service:<aoss for serverless, es for managed service> + ``` + +### OpenSearch 基准测试版本 1.14.0 及更早版本 + +对于 1.15.0 之前的 OpenSearch 基准测试版本,请使用环境变量方法: + +1. 在 AWS 管理控制台中创建 IAM 角色或用户。 + +2. 设置环境变量。如果您使用 Amazon OpenSearch Serverless 进行测试,请将 `OSB_SERVICE` 设置为 `aoss`。 + + - 对于 IAM 用户,配置以下环境变量: + + ```bash + export OSB_AWS_ACCESS_KEY_ID=<IAM USER AWS ACCESS KEY ID> + export OSB_AWS_SECRET_ACCESS_KEY=<IAM USER AWS SECRET ACCESS KEY> + export OSB_REGION=<YOUR REGION> + export OSB_SERVICE=es + ``` + + - 对于 IAM 角色,配置以下环境变量: + + ```bash + export OSB_AWS_ACCESS_KEY_ID=<IAM Role AWS ACCESS KEY ID> + export OSB_AWS_SECRET_ACCESS_KEY=<IAM Role AWS SECRET ACCESS KEY> + export OSB_AWS_SESSION_TOKEN=<IAM Role SESSION TOKEN> + export OSB_REGION=<YOUR REGION> + export OSB_SERVICE=es + ``` + +3. 使用 `--client-options=amazon_aws_log_in:environment` 标志自定义并运行以下 `run` 命令。此标志将导出的凭据的位置提供给 OpenSearch 基准测试。 + + ```bash + opensearch-benchmark run \ + --target-hosts=<CLUSTER ENDPOINT> \ + --pipeline=benchmark-only \ + --workload=geonames \ + --client-options=timeout:120,amazon_aws_log_in:environment + ``` + +## 代理配置 + +OpenSearch 会自动为您下载所有必要的代理数据,包括: + +- OpenSearch 分发,当您指定 `--distribution-version=<OPENSEARCH-VERSION>` 时。 +- OpenSearch 源代码,当您指定 Git 修订号时,例如 `--revision=1e04b2w`。 +- 从 [OpenSearch GitHub 存储库](https://github.com/opensearch-project/OpenSearch)跟踪的任何元数据。 + +::: danger WARNING +从 OpenSearch 基准测试 0.5.0 开始,仅支持 `http_proxy`。 +::: + +您可以使用 `http_proxy` 将 OpenSearch 基准测试连接到特定代理,并将代理连接到基准测试工作负载。要添加代理: + +1. 将代理 URL 添加到 shell 配置文件: + + ``` + export http_proxy=http://proxy.proxy.org:4444/ + ``` + +2. 获取 shell 配置文件并验证代理 URL 是否设置正确: + + ``` + source ~/.bash_profile ; echo $http_proxy + ``` + +3. 使用以下命令配置 Git 以连接到代理。有关更多信息,请参阅 [Git 文档](https://git-scm.com/docs/git-config)。 + + ``` + git config --global http_proxy $http_proxy + ``` + +4. 使用 `git clone` 通过以下命令克隆工作负载存储库。如果代理配置正确,克隆将成功。 + + ``` + git clone http://github.com/opensearch-project/opensearch-benchmark-workloads.git + ``` + +5. 最后,通过检查 `/.benchmark/logs/benchmark.log` 日志来验证 OpenSearch 基准测试是否可以连接到代理服务器。当 OpenSearch 基准测试启动时,您应该在日志顶部看到以下内容: + + ``` + Connecting via proxy URL [http://proxy.proxy.org:4444/] to the Internet (picked up from the environment variable [http_proxy]). + ``` + +## 日志记录 + +OpenSearch 基准测试的日志可以在 `~/.benchmark/logging.json` 文件中配置。有关如何格式化日志文件的更多信息,请参阅以下 Python 文档: + +- 有关一般提示和技巧,请使用 [Python 日志记录 Cookbook](https://docs.python.org/3/howto/logging-cookbook.html)。 +- 有关文件格式,请参阅 Python [日志记录配置架构](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema)。 +- 有关如何自定义日志输出写入位置的说明,请参阅[日志记录处理程序文档](https://docs.python.org/3/library/logging.handlers.html)。 + +默认情况下,OpenSearch 基准测试将所有输出记录到 `~/.benchmark/logs/benchmark.log`。 diff --git a/i18n/zh/benchmark/user-guide/install-and-configure/index.md b/i18n/zh/benchmark/user-guide/install-and-configure/index.md new file mode 100644 index 00000000..889d2822 --- /dev/null +++ b/i18n/zh/benchmark/user-guide/install-and-configure/index.md @@ -0,0 +1,7 @@ +--- +title: 安装和配置 OpenSearch Benchmark +--- + +# 安装和配置 OpenSearch Benchmark + +可以使用 `pip` 安装 OpenSearch Benchmark。安装后,您可以配置到 OpenSearch 集群的连接并自定义基准测试行为。 diff --git a/i18n/zh/benchmark/user-guide/install-and-configure/installing-benchmark.md b/i18n/zh/benchmark/user-guide/install-and-configure/installing-benchmark.md new file mode 100644 index 00000000..976c3678 --- /dev/null +++ b/i18n/zh/benchmark/user-guide/install-and-configure/installing-benchmark.md @@ -0,0 +1,209 @@ +--- +title: 安装 +--- + +# 安装 OpenSearch 基准测试 + +您可以直接在运行 Linux 或 macOS 的主机上安装 OpenSearch 基准测试,也可以在任何兼容主机上的 Docker 容器中运行 OpenSearch 基准测试。本页提供了 OpenSearch 基准测试主机的一般注意事项以及安装 OpenSearch 基准测试的说明。 + +## 选择合适的硬件 + +OpenSearch 基准测试可用于配置 OpenSearch 节点以进行测试。如果您打算使用 OpenSearch 基准测试在您的环境中配置节点,则直接在集群中的每个主机上安装 OpenSearch 基准测试。此外,您必须为 OpenSearch 配置集群中的每个主机。有关重要主机设置的指导,请参阅[安装 OpenSearch](/install-and-configure/install-opensearch/)。 + +::: warning IMPORTANT +请记住,当您在 Docker 容器中运行 OpenSearch 基准测试时,OpenSearch 基准测试无法用于配置 OpenSearch 节点。如果您想使用 OpenSearch 基准测试配置节点,或者如果您想使用 OpenSearch 基准测试守护程序分发基准测试工作负载,则必须使用 Python 和 pip 直接在每个主机上安装 OpenSearch 基准测试。 +::: + +选择主机时,您还应该考虑要运行哪些工作负载。要查看默认基准测试工作负载的列表,请访问 GitHub 上的 [`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) 存储库。作为一般规则,请确保 OpenSearch 基准测试主机具有足够的可用存储空间来存储压缩数据和完全解压缩的数据语料库。 + +如果您想使用默认工作负载进行基准测试,则使用以下表格通过将压缩大小与未压缩大小相加来确定所需的大约最小可用空间量。 + +| 工作负载名称 | 文档数 | 压缩大小 | 未压缩大小 | +| :----: | :----: | :----: | :----: | +| `eventdata` | 20,000,000 | 756.0 MB | 15.3 GB | +| `geonames` | 11,396,503 | 252.9 MB | 3.3 GB | +| `geopoint` | 60,844,404 | 482.1 MB | 2.3 GB | +| `geopointshape` | 60,844,404 | 470.8 MB | 2.6 GB | +| `geoshape` | 60,523,283 | 13.4 GB | 45.4 GB | +| `http_logs` | 247,249,096 | 1.2 GB | 31.1 GB | +| `nested` | 11,203,029 | 663.3 MB | 3.4 GB | +| `noaa` | 33,659,481 | 949.4 MB | 9.0 GB | +| `nyc_taxis` | 165,346,692 | 4.5 GB | 74.3 GB | +| `percolator` | 2,000,000 | 121.1 kB | 104.9 MB | +| `pmc` | 574,199 | 5.5 GB | 21.7 GB | +| `so` | 36,062,278 | 8.9 GB | 33.1 GB | + +::: tip TIP +您的 OpenSearch 基准测试主机应使用固态硬盘(SSD)进行存储,因为它们执行读写操作的速度明显快于传统的旋转磁盘硬盘。旋转磁盘硬盘可能会引入性能瓶颈,这可能使基准测试结果不可靠且不一致。 +::: + +## 在 Linux 和 macOS 上安装 + +::: warning IMPORTANT +如果您想在 Docker 容器中运行 OpenSearch 基准测试,请参阅[使用 Docker 安装](#installing-with-docker)。OpenSearch 基准测试 Docker 镜像包括所有必需的软件,因此不需要其他步骤。 +::: + +要直接在 UNIX 主机(例如 Linux 或 macOS)上安装 OpenSearch 基准测试,请确保已安装 **Python 3.8 或更高版本**。 + +如果您需要有关安装 Python 的帮助,请参阅官方的 [Python 设置和使用](https://docs.python.org/3/using/index.html)文档。 + +### 检查软件依赖项 + +在开始安装 OpenSearch 基准测试之前,请检查以下软件依赖项。 + +::: tip TIP +使用 [`pyenv`](https://github.com/pyenv/pyenv) 管理主机上的多个 Python 版本。如果您的"系统"Python 版本早于 3.8 版本,这将特别有用。 +::: + +- 检查是否安装了 Python 3.8 或更高版本: + + ```bash + python3 --version + ``` + +- 检查 `pip` 是否已安装并正常工作: + + ```bash + pip --version + ``` + +- _可选_:使用以下命令检查已安装的 `git` 版本是否为 **Git 1.9 或更高版本**。OpenSearch 基准测试安装不需要 `git`,但在您想要执行测试时从存储库获取基准测试工作负载资源时需要它。有关安装 Git 的帮助,请参阅官方 Git [文档](https://git-scm.com/doc)。 + + ```bash + git --version + ``` + +### 完成安装 + +安装所需软件后,您可以使用以下命令安装 OpenSearch 基准测试: + +```bash +pip install opensearch-benchmark +``` + +安装完成后,您可以使用以下命令显示帮助信息: + +```bash +opensearch-benchmark -h +``` + +现在 OpenSearch 基准测试已安装在您的主机上,您可以了解[配置 OpenSearch 基准测试](/benchmark/user-guide/configuring-benchmark)。 + +## 使用 Docker 安装 + +您可以在 [Docker Hub](https://hub.docker.com/r/opensearchproject/opensearch-benchmark) 或 [Amazon ECR Public Gallery](https://gallery.ecr.aws/opensearchproject/opensearch-benchmark) 上找到 OpenSearch 基准测试的官方 Docker 镜像。 + +### Docker 限制 + +当您在 Docker 容器中运行 OpenSearch 基准测试时,某些 OpenSearch 基准测试功能不可用。具体来说,以下限制适用: + +- OpenSearch 基准测试无法从多个主机分发负载,例如负载工作器协调器主机。 +- OpenSearch 基准测试无法配置 OpenSearch 节点,只能在先前存在的集群上运行测试。您只能使用 `benchmark-only` 管道调用 OpenSearch 基准测试命令。 + +### 拉取 Docker 镜像 + +要从 Docker Hub 拉取镜像,请运行以下命令: + +```bash +docker pull opensearchproject/opensearch-benchmark:latest +``` + +要从 Amazon Elastic Container Registry(Amazon ECR)拉取镜像: + +```bash +docker pull public.ecr.aws/opensearchproject/opensearch-benchmark:latest +``` + +### 使用 Docker 运行 OpenSearch 基准测试 + +要运行 OpenSearch 基准测试,请使用 `docker run` 启动容器。OpenSearch 基准测试子命令作为启动容器时的参数传递。然后 OpenSearch 基准测试处理命令,并在请求的操作完成后停止容器。 + +例如,以下命令将 OpenSearch 基准测试的帮助文本打印到命令行,然后停止容器: + +```bash +docker run opensearchproject/opensearch-benchmark -h +``` + +### 在 Docker 容器中建立卷持久性 + +要确保基准测试数据和日志在 Docker 容器停止后持久存在,您必须在 Docker 中运行 OpenSearch 基准测试时将本地目录挂载为卷。 + +使用 `-v` 选项指定要挂载的本地目录以及容器中附加卷的目录。 + +以下示例从用户的主目录挂载卷到 OpenSearch 基准测试容器的默认基准测试数据路径 `/opensearch-benchmark/.benchmark`,然后使用 `geonames` 工作负载运行测试基准测试: + +```bash +docker run -v $HOME/benchmarks:/opensearch-benchmark/.benchmark opensearchproject/opensearch-benchmark run --target-hosts https://198.51.100.25:9200 --pipeline benchmark-only --workload geonames --client-options basic_auth_user:admin,basic_auth_password:admin,verify_certs:false --test-mode +``` + +::: info NOTE +默认情况下,OpenSearch 基准测试容器以 `benchmark` 用户身份运行,主目录为 `/opensearch-benchmark`,因此 `$HOME/.benchmark` 解析为 `/opensearch-benchmark/.benchmark`。 +::: + +#### 以 root 用户身份运行 OpenSearch 基准测试 + +如果您以 `root` 用户身份运行容器,则有效的主目录变为 `/root`,基准测试路径变为 `/root/.benchmark`。在这种情况下,请相应地指定卷挂载: + +```bash +docker run -v $HOME/benchmarks:/root/.benchmark opensearchproject/opensearch-benchmark run --target-hosts https://198.51.100.25:9200 --pipeline benchmark-only --workload geonames --client-options basic_auth_user:admin,basic_auth_password:admin,verify_certs:false --test-mode +``` + +要了解有关位于 `/opensearch-benchmark/.benchmark` 中的文件和子目录的更多信息,请参阅[配置 OpenSearch 基准测试](/benchmark/user-guide/configuring-benchmark)。 + +## 使用测试配置 OpenSearch 集群 + +::: info NOTE +OpenSearch 基准测试与 JDK 版本 17、16、15、14、13、12、11 和 8 兼容。 +::: + +如果您使用 PyPi 安装了 OpenSearch,您还可以通过在 `run` 命令中指定 `distribution-version` 来配置新的 OpenSearch 集群。 + +如果您计划让基准测试配置集群,您需要告知基准测试基准测试集群的 `JAVA_HOME` 路径的位置。要设置 `JAVA_HOME` 路径并配置集群: + +1. 查找您当前使用的 `JAVA_HOME` 路径。打开终端并输入 `/usr/libexec/java_home`。 + +2. 通过输入上一步中的路径来设置相应的 JDK 版本环境变量。输入 `export JAVA17_HOME=<Java Path>`。 + +3. 运行 `run` 命令并指示您要使用的 OpenSearch 分发版本: + + ```bash + opensearch-benchmark run --distribution-version=2.3.0 --workload=geonames --test-mode + ``` + +## 目录结构 + +首次运行 OpenSearch 基准测试后,您可以在 `~/.benchmark` 目录中搜索所有相关文件,包括配置文件。该目录包括以下文件树: + +``` +# ~/.benchmark Tree +. +├── benchmark.ini +├── benchmarks +│ ├── data +│ │ └── geonames +│ ├── distributions +│ │ ├── opensearch-1.0.0-linux-x64.tar.gz +│ │ └── opensearch-2.3.0-linux-x64.tar.gz +│ ├── test-runs +│ │ ├── 0279b13b-1e54-49c7-b1a7-cde0b303a797 +│ │ └── 0279c542-a856-4e88-9cc8-04306378cd38 +│ └── workloads +│ └── default +│ └── geonames +├── logging.json +├── logs +│ └── benchmark.log +``` + +* `benchmark.ini`:包含测试的任何可调整配置。有关如何配置 OpenSearch 基准测试的信息,请参阅[配置 OpenSearch 基准测试](/benchmark/user-guide/configuring-benchmark)。 +* `data`:包含与 OpenSearch 基准测试的[官方工作负载](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/geonames)相关的所有数据语料库和文档。 +* `distributions`:包含从 [OpenSearch.org](http://opensearch.org/) 下载并用于配置集群的所有 OpenSearch 分发。 +* `test-runs`:包含来自先前 OpenSearch 基准测试运行的每个测试 `execution_id`。 +* `workloads`:包含与工作负载相关的所有文件,数据语料库除外。 +* `logging.json`:包含与 OpenSearch 基准测试中如何执行日志记录相关的所有配置选项。 +* `logs`:包含来自 OpenSearch 基准测试运行的所有日志。当您在运行期间遇到错误时,这会很有帮助。 + +## 下一步 + +- [配置 OpenSearch 基准测试](/benchmark/user-guide/configuring-benchmark) +- [创建自定义工作负载](/benchmark/creating-custom-workloads) diff --git a/i18n/zh/benchmark/user-guide/understanding-workloads/anatomy-of-a-workload.md b/i18n/zh/benchmark/user-guide/understanding-workloads/anatomy-of-a-workload.md index ef13b751..2ab36cbf 100644 --- a/i18n/zh/benchmark/user-guide/understanding-workloads/anatomy-of-a-workload.md +++ b/i18n/zh/benchmark/user-guide/understanding-workloads/anatomy-of-a-workload.md @@ -247,10 +247,10 @@ title: 工作负载解析 "scaling_factor": 100, "type": "scaled_float" }, - "trip_distance": {%- if trip_distance_mapping is defined %} {{ trip_distance_mapping | tojson }} {%- else %} { + "trip_distance": {{ trip_distance_mapping | tojson }} { "scaling_factor": 100, "type": "scaled_float" - }{%- endif %}, + }, "pickup_location": { "type": "geo_point" } @@ -371,11 +371,11 @@ title: 工作负载解析 { "operation": { "operation-type": "create-index", - "settings": {%- if index_settings is defined %} {{ index_settings | tojson }} {%- else %}{ + "settings": {{ index_settings | tojson }} { "index.codec": "best_compression", "index.refresh_interval": "30s", "index.translog.flush_threshold_size": "4g" - }{%- endif %} + } } }, ... diff --git a/i18n/zh/benchmark/version-history.md b/i18n/zh/benchmark/version-history.md new file mode 100644 index 00000000..c51aa927 --- /dev/null +++ b/i18n/zh/benchmark/version-history.md @@ -0,0 +1,25 @@ +--- +title: 版本历史 +--- + +# OpenSearch Benchmark 版本历史 + +本页详细介绍了 OpenSearch Benchmark 各版本的高级变更。 + +## OpenSearch Benchmark 2.0 中更新的术语 + +OpenSearch Benchmark 2.0 引入了更新的术语,以增强用户体验并提供更直观的基准测试工作流程。 + +1.X 术语 | 2.X 术语 | +:--- | :--- | +execute-test, test-execution-id, TestExecution | run, test-run, TestRun | +results_publishing, results_publisher | reporting, publisher | +provision-configs, provision-config-instances | cluster-configs, cluster-config-instances +load-worker-coordinator-hosts | worker-ips | + +## 版本历史 + +OpenSearch Benchmark 版本 | 发布要点 | 发布日期 +:--- | :--- | :--- +[2.0.0](https://github.com/opensearch-project/opensearch-build/blob/main/release-notes/opensearch-release-notes-3.1.0.md) | 引入新机制以增强用户体验和直观的基准测试工作流程。添加新功能,如合成数据生成、数据流式传输和可视化。 | 2025年8月21日 +[1.15.0](https://github.com/opensearch-project/opensearch-benchmark/releases/tag/1.15.0) | 使用户能够使用基于会话的身份验证,该身份验证可自动处理临时凭证生成和刷新,从而无需手动导出 AWS 凭证。向 compare 命令添加百分比差异。解决 execute-test 的错误 | 2025年8月7日 diff --git a/i18n/zh/benchmark/workload-types.md b/i18n/zh/benchmark/workload-types.md new file mode 100644 index 00000000..0c1c1ebe --- /dev/null +++ b/i18n/zh/benchmark/workload-types.md @@ -0,0 +1,83 @@ +--- +title: 工作负载类型 +--- + +# 工作负载类型 + +[`opensearch-benchmark-workloads`](https://github.com/opensearch-project/opensearch-benchmark-workloads) 存储库包含可以针对您的集群运行的预打包工作负载。本页介绍每个工作负载的数据、集群要求和查询类型。要确定哪个适合您的集群,请参阅[选择工作负载](/benchmark/choosing-a-workload)。 + +## 通用搜索用例:`nyc_taxis` + +对于为通用搜索用例构建的基准测试集群,请从 [nyc_taxis](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/nyc_taxis) 工作负载开始。它包含以下内容: + +- **数据类型**:2015 年纽约市黄色出租车的乘车数据。 +- **集群要求**:适用于中小型集群。 + +此工作负载测试以下查询和搜索功能: + +- 范围查询 +- 对各种字段的术语查询 +- 地理距离查询 +- 聚合 + +## 向量数据:`vectorsearch` + +[`vectorsearch`](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/vectorsearch) 工作负载旨在对向量搜索功能(包括性能和准确性)进行基准测试。它包含以下内容: + +- **数据类型**:高维向量数据,通常表示文本或图像的嵌入。 +- **集群要求**:需要启用了[向量搜索功能](/vector-search/)的集群。 + +此工作负载测试以下查询和搜索功能: + +- k-NN 向量搜索 +- 结合向量相似性和元数据过滤的混合搜索 +- 高维向量数据的索引性能 + +有关支持的参数、测试程序和示例结果,请参阅[向量搜索工作负载](/benchmark/workloads/vectorsearch)。 + +## 综合搜索解决方案:`big5` + +[big5](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/big5) 工作负载是一个综合基准测试套件,用于测试搜索引擎性能的各个方面,包括跨多个用例的整体搜索引擎性能。它包含以下内容: + +- **数据类型**:混合不同数据类型,包括文本、数字和结构化数据。 +- **集群要求**:适用于中型到大型集群,因为它旨在对各种组件进行压力测试。 + +此工作负载测试以下查询和搜索功能: + +- 全文搜索性能 +- 聚合性能 +- 复杂的布尔查询 +- 排序和分页 +- 各种数据类型的索引性能 + +## Percolator 查询:`percolator` + +[percolator](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/percolator) 工作负载旨在测试 `percolator` 查询类型的性能。它包含以下内容: + +- **数据类型**:一组存储的查询和要与这些查询匹配的文档。 +- **集群要求**:适用于大量使用 [percolator](/mappings/supported-field-types/percolator/) 功能的集群。 + +此工作负载测试以下查询和搜索功能: + +- 存储查询的索引性能 +- percolator 查询的匹配性能 +- 随着存储查询数量增加的可扩展性 + +## 日志数据:`http_logs` + +对于使用日志数据进行索引和搜索的基准测试集群,请使用 [http_logs](https://github.com/opensearch-project/opensearch-benchmark-workloads/tree/main/http_logs) 工作负载。它包含以下内容: + +- **数据类型**:来自 1998 年世界杯网站的 HTTP 访问日志。 +- **集群要求**:适用于针对时间序列数据和日志分析优化的集群。 + +此工作负载测试以下查询和搜索功能: + +- 时间范围查询 +- 对 `status-code` 或 `user-agent` 等字段的术语查询 +- 请求计数和平均响应大小等指标的聚合 +- 对 `ip-address` 等字段的基数聚合。 + +## 后续步骤 + +- 要将这些工作负载与集群的用例进行比较,请参阅[选择工作负载](/benchmark/choosing-a-workload)。 +- 要为没有预打包工作负载匹配的数据构建工作负载,请参阅[创建自定义工作负载](/benchmark/creating-custom-workloads)。 diff --git a/i18n/zh/benchmark/workloads/vectorsearch.md b/i18n/zh/benchmark/workloads/vectorsearch.md new file mode 100644 index 00000000..38a94b3c --- /dev/null +++ b/i18n/zh/benchmark/workloads/vectorsearch.md @@ -0,0 +1,316 @@ +--- +title: 向量搜索 +--- + +# 向量搜索工作负载 + +向量搜索工作负载对 OpenSearch 的向量引擎功能进行索引和搜索操作的基准测试。它测试各种向量搜索算法、量化方法和索引配置,以测量吞吐量、延迟和召回准确率等性能指标。该工作负载支持不同的数据集,可以评估经过训练和未经训练的向量搜索方法。 + +此工作负载支持 `HDF5` 或 `BIG-ANN` 格式的数据集。要下载数据集,请使用[此链接](http://corpus-texmex.irisa.fr/)。 + +## 支持的工作负载参数 + +向量搜索工作负载支持以下工作负载参数。 + +| 名称 | 描述 | +| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `target_index_name` | 要向其添加向量的索引的名称。 | +| `target_field_name` | 要向其添加向量的字段的名称。使用"."表示嵌套字段。 | +| `target_index_body` | 目标索引定义的路径。 | +| `target_index_primary_shards` | 目标索引的主分片。 | +| `target_index_replica_shards` | 目标索引的副本分片。 | +| `target_index_dimension` | 目标索引的维度。 | +| `target_index_space_type` | 目标索引空间类型。 | +| `target_index_bulk_size` | 目标索引批量大小。 | +| `target_index_bulk_index_data_set_format` | 向量数据集的格式。 | +| `target_index_bulk_index_data_set_path` | 索引中向量数据集的路径。 | +| `target_index_bulk_index_data_set_corpus` | 向量数据集的语料库名称。 | +| `target_index_bulk_index_clients` | 用于批量摄取的客户端。必须是数据集大小的除数。 | +| `target_index_max_num_segments` | 在开始搜索之前合并到目标索引的段数。 | +| `target_index_force_merge_timeout` | 强制合并请求之前等待的时间量(以秒为单位)。 | +| `hnsw_ef_search ` | `HNSW ef` 搜索参数。 | +| `hnsw_ef_construction` | `HNSW ef` 构造参数。 | +| `id_field_name` | 将用于识别索引中文档的字段的名称。 | +| `hnsw_m ` | `HNSW m` 参数。 | +| `query_k` | 要为搜索返回的邻居数。只能提供 `query_k`、`query_max_distance` 或 `query_min_score` 中的一个。 | +| `query_max_distance ` | 要为向量搜索返回的最大距离。只能提供 `query_k`、`query_max_distance` 或 `query_min_score` 中的一个。 | +| `query_min_score` | 要为向量搜索返回的最小分数。只能提供 `query_k`、`query_max_distance` 或 `query_min_score` 中的一个。 | +| `query_data_set_format` | 用于查询的向量数据集的格式。只能提供 `query_k`、`query_max_distance` 或 `query_min_score` 中的一个。 | +| `query_data_set_path` | 用于查询的向量数据集的路径。 | +| `query_count` | 用于搜索操作的查询数。 | +| `query_body` | 将与搜索主体合并的 JSON 属性。 | +| `search_clients` | 用于运行查询的客户端数。 | +| `repetitions` | 在数据集耗尽之前完成的重复次数。默认为 `1`。 | +| `target_throughput` | 每个查询操作的目标吞吐量,以每秒请求数为单位。默认为 `10`。 | +| `time_period` | 专用于运行基准测试的时间段,以秒为单位。默认为 `900`。 | + +## 测试程序 + +向量搜索工作负载支持以下测试程序。 + +### 无训练测试程序 + +无训练测试程序测试不需要训练的向量搜索索引。您可以将向量搜索算法的基础配置(例如指定特定引擎或空间类型)定义为方法定义。 + +### 无训练测试(仅索引)程序 + +无训练测试(仅索引)程序用于索引不需要训练的向量搜索索引。当您只想对索引操作进行基准测试时,这可能特别有用。 + +### 无训练测试(Amazon OpenSearch Serverless) + +Amazon OpenSearch Serverless 的无训练测试程序专门用于 OpenSearch Serverless 向量搜索集合。此程序不包括 **refresh** 和 **warmup** 等操作,因为向量搜索集合不支持它们。 + +### 强制合并索引程序 + +强制合并索引程序通过执行强制合并操作来优化向量搜索索引,最多达到给定的最大段数。对于大型数据集,强制合并是一项成本高昂的操作。因此,我们建议使用单独的程序根据用户要求偶尔触发强制合并操作。 + +### 训练测试程序 + +训练测试程序对需要训练步骤的近似 k-NN 搜索算法进行基准测试。例如,Faiss 倒排文件索引(IVF)技术需要训练步骤才能检索聚类向量。执行该步骤后,基准测试可以搜索较少数量的聚类质心,而不是整个数据集。 + +### 搜索程序 + +搜索程序对先前索引的向量搜索索引进行基准测试。当您想要对大型向量搜索索引进行基准测试而无需每次重新索引时,这可能很有用,因为大型数据集的加载时间可能相当长。此程序包括预热操作,旨在避免向量搜索期间的冷启动问题。 + +## 自定义运行器 + +向量搜索工作负载仅支持一个自定义运行器 `warmup-knn-indices`。此运行器将预热 k-NN 索引并重试预热直到成功。 + +## 运行工作负载 + +要运行向量搜索工作负载,请使用以下命令: + +```bash +export ENDPOINT=<cluster-endpoint> +export PARAMS_FILE=<params-file-path> + +opensearch-benchmark run \ + --target-hosts $ENDPOINT \ + --workload vectorsearch \ + --workload-params ${PARAMS_FILE} \ + --pipeline benchmark-only \ + --kill-running-processes +``` + +## 示例结果 + +使用向量搜索工作负载时,您可以期望类似于以下内容的结果。 + +### 训练测试程序 + +以下示例提供了训练测试程序的结果: + +``` +------------------------------------------------------ + _______ __ _____ + / ____(_)___ ____ _/ / / ___/_________ ________ + / /_ / / __ \/ __ `/ / \__ \/ ___/ __ \/ ___/ _ \ + / __/ / / / / / /_/ / / ___/ / /__/ /_/ / / / __/ +/_/ /_/_/ /_/\__,_/_/ /____/\___/\____/_/ \___/ +------------------------------------------------------ + +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 0.00946667 | min | +| Min cumulative indexing time across primary shards | | 0 | min | +| Median cumulative indexing time across primary shards | | 0.00298333 | min | +| Max cumulative indexing time across primary shards | | 0.00336667 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 0 | min | +| Cumulative merge count of primary shards | | 0 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0 | min | +| Max cumulative merge time across primary shards | | 0 | min | +| Cumulative merge throttle time of primary shards | | 0 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0 | min | +| Cumulative refresh time of primary shards | | 0.00861667 | min | +| Cumulative refresh count of primary shards | | 33 | | +| Min cumulative refresh time across primary shards | | 0 | min | +| Median cumulative refresh time across primary shards | | 0.00268333 | min | +| Max cumulative refresh time across primary shards | | 0.00291667 | min | +| Cumulative flush time of primary shards | | 0.000183333 | min | +| Cumulative flush count of primary shards | | 2 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0 | min | +| Max cumulative flush time across primary shards | | 0.000183333 | min | +| Total Young Gen GC time | | 0.075 | s | +| Total Young Gen GC count | | 17 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 0.00869293 | GB | +| Translog size | | 2.56114e-07 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 9 | | +| Min Throughput | custom-vector-bulk | 25527 | docs/s | +| Mean Throughput | custom-vector-bulk | 25527 | docs/s | +| Median Throughput | custom-vector-bulk | 25527 | docs/s | +| Max Throughput | custom-vector-bulk | 25527 | docs/s | +| 50th percentile latency | custom-vector-bulk | 36.3095 | ms | +| 90th percentile latency | custom-vector-bulk | 52.2662 | ms | +| 100th percentile latency | custom-vector-bulk | 68.6513 | ms | +| 50th percentile service time | custom-vector-bulk | 36.3095 | ms | +| 90th percentile service time | custom-vector-bulk | 52.2662 | ms | +| 100th percentile service time | custom-vector-bulk | 68.6513 | ms | +| error rate | custom-vector-bulk | 0 | % | +| Min Throughput | prod-queries | 211.26 | ops/s | +| Mean Throughput | prod-queries | 213.85 | ops/s | +| Median Throughput | prod-queries | 213.48 | ops/s | +| Max Throughput | prod-queries | 216.49 | ops/s | +| 50th percentile latency | prod-queries | 3.43393 | ms | +| 90th percentile latency | prod-queries | 4.01881 | ms | +| 99th percentile latency | prod-queries | 5.56238 | ms | +| 99.9th percentile latency | prod-queries | 9.95666 | ms | +| 99.99th percentile latency | prod-queries | 39.7922 | ms | +| 100th percentile latency | prod-queries | 62.415 | ms | +| 50th percentile service time | prod-queries | 3.43405 | ms | +| 90th percentile service time | prod-queries | 4.0191 | ms | +| 99th percentile service time | prod-queries | 5.56316 | ms | +| 99.9th percentile service time | prod-queries | 9.95666 | ms | +| 99.99th percentile service time | prod-queries | 39.7922 | ms | +| 100th percentile service time | prod-queries | 62.415 | ms | +| error rate | prod-queries | 0 | % | + +------------------------------------ +[INFO] ✅ SUCCESS (took 119 seconds) +------------------------------------ +``` + +### Faiss 结果 + +以下示例输出是使用 Faiss IVF 基准测试程序生成的。为简洁起见,测试使用了 100 个搜索查询,而不是参数文件中指定的 10,000 个。所有其他参数与 `params/train` 文件夹中的参数保持相同。第一次运行演示了没有量化的结果,第二次运行演示了标量量化,第三次运行演示了乘积量化。请注意,量化可能导致搜索召回率下降。 + +#### Faiss IVF 无量化/平面编码 + +``` +| Metric | Task | Value | Unit | +|---------------------------------------------------------------:|-------------------------:|------------:|-------:| +| Cumulative indexing time of primary shards | | 11.7662 | min | +| Min cumulative indexing time across primary shards | | 0.000266667 | min | +| Median cumulative indexing time across primary shards | | 0.1423 | min | +| Max cumulative indexing time across primary shards | | 11.6236 | min | +| Cumulative indexing throttle time of primary shards | | 0 | min | +| Min cumulative indexing throttle time across primary shards | | 0 | min | +| Median cumulative indexing throttle time across primary shards | | 0 | min | +| Max cumulative indexing throttle time across primary shards | | 0 | min | +| Cumulative merge time of primary shards | | 1.09872 | min | +| Cumulative merge count of primary shards | | 21 | | +| Min cumulative merge time across primary shards | | 0 | min | +| Median cumulative merge time across primary shards | | 0.00045 | min | +| Max cumulative merge time across primary shards | | 1.09827 | min | +| Cumulative merge throttle time of primary shards | | 0.872417 | min | +| Min cumulative merge throttle time across primary shards | | 0 | min | +| Median cumulative merge throttle time across primary shards | | 0 | min | +| Max cumulative merge throttle time across primary shards | | 0.872417 | min | +| Cumulative refresh time of primary shards | | 0.113733 | min | +| Cumulative refresh count of primary shards | | 59 | | +| Min cumulative refresh time across primary shards | | 0.00235 | min | +| Median cumulative refresh time across primary shards | | 0.00516667 | min | +| Max cumulative refresh time across primary shards | | 0.106217 | min | +| Cumulative flush time of primary shards | | 0.01685 | min | +| Cumulative flush count of primary shards | | 8 | | +| Min cumulative flush time across primary shards | | 0 | min | +| Median cumulative flush time across primary shards | | 0.00791667 | min | +| Max cumulative flush time across primary shards | | 0.00893333 | min | +| Total Young Gen GC time | | 5.442 | s | +| Total Young Gen GC count | | 3739 | | +| Total Old Gen GC time | | 0 | s | +| Total Old Gen GC count | | 0 | | +| Store size | | 1.3545 | GB | +| Translog size | | 0.0304573 | GB | +| Heap used for segments | | 0 | MB | +| Heap used for doc values | | 0 | MB | +| Heap used for terms | | 0 | MB | +| Heap used for norms | | 0 | MB | +| Heap used for points | | 0 | MB | +| Heap used for stored fields | | 0 | MB | +| Segment count | | 14 | | +| Min Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| Mean Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| Median Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| Max Throughput | custom-vector-bulk-train | 32222.6 | docs/s | +| 50th percentile latency | custom-vector-bulk-train | 26.5199 | ms | +| 90th percentile latency | custom-vector-bulk-train | 34.9823 | ms | +| 99th percentile latency | custom-vector-bulk-train | 196.712 | ms | +| 100th percentile latency | custom-vector-bulk-train | 230.342 | ms | +| 50th percentile service time | custom-vector-bulk-train | 26.5158 | ms | +| 90th percentile service time | custom-vector-bulk-train | 34.9823 | ms | +| 99th percentile service time | custom-vector-bulk-train | 196.712 | ms | +| 100th percentile service time | custom-vector-bulk-train | 230.342 | ms | +| error rate | custom-vector-bulk-train | 0 | % | +| Min Throughput | delete-model | 10.58 | ops/s | +| Mean Throughput | delete-model | 10.58 | ops/s | +| Median Throughput | delete-model | 10.58 | ops/s | +| Max Throughput | delete-model | 10.58 | ops/s | +| 100th percentile latency | delete-model | 93.6958 | ms | +| 100th percentile service time | delete-model | 93.6958 | ms | +| error rate | delete-model | 0 | % | +| Min Throughput | train-knn-model | 0.63 | ops/s | +| Mean Throughput | train-knn-model | 0.63 | ops/s | +| Median Throughput | train-knn-model | 0.63 | ops/s | +| Max Throughput | train-knn-model | 0.63 | ops/s | +| 100th percentile latency | train-knn-model | 1577.49 | ms | +| 100th percentile service time | train-knn-model | 1577.49 | ms | +| error rate | train-knn-model | 0 | % | +| Min Throughput | custom-vector-bulk | 11055 | docs/s | +| Mean Throughput | custom-vector-bulk | 14163.8 | docs/s | +| Median Throughput | custom-vector-bulk | 12878.9 | docs/s | +| Max Throughput | custom-vector-bulk | 33841.3 | docs/s | +| 50th percentile latency | custom-vector-bulk | 81.6677 | ms | +| 90th percentile latency | custom-vector-bulk | 117.848 | ms | +| 99th percentile latency | custom-vector-bulk | 202.484 | ms | +| 99.9th percentile latency | custom-vector-bulk | 406.209 | ms | +| 99.99th percentile latency | custom-vector-bulk | 458.823 | ms | +| 100th percentile latency | custom-vector-bulk | 459.417 | ms | +| 50th percentile service time | custom-vector-bulk | 81.6621 | ms | +| 90th percentile service time | custom-vector-bulk | 117.843 | ms | +| 99th percentile service time | custom-vector-bulk | 202.294 | ms | +| 99.9th percentile service time | custom-vector-bulk | 406.209 | ms | +| 99.99th percentile service time | custom-vector-bulk | 458.823 | ms | +| 100th percentile service time | custom-vector-bulk | 459.417 | ms | +| error rate | custom-vector-bulk | 0 | % | +| Min Throughput | force-merge-segments | 0.1 | ops/s | +| Mean Throughput | force-merge-segments | 0.1 | ops/s | +| Median Throughput | force-merge-segments | 0.1 | ops/s | +| Max Throughput | force-merge-segments | 0.1 | ops/s | +| 100th percentile latency | force-merge-segments | 10017.4 | ms | +| 100th percentile service time | force-merge-segments | 10017.4 | ms | +| error rate | force-merge-segments | 0 | % | +| Min Throughput | warmup-indices | 9.63 | ops/s | +| Mean Throughput | warmup-indices | 9.63 | ops/s | +| Median Throughput | warmup-indices | 9.63 | ops/s | +| Max Throughput | warmup-indices | 9.63 | ops/s | +| 100th percentile latency | warmup-indices | 103.228 | ms | +| 100th percentile service time | warmup-indices | 103.228 | ms | +| error rate | warmup-indices | 0 | % | +| Min Throughput | prod-queries | 120.06 | ops/s | +| Mean Throughput | prod-queries | 120.06 | ops/s | +| Median Throughput | prod-queries | 120.06 | ops/s | +| Max Throughput | prod-queries | 120.06 | ops/s | +| 50th percentile latency | prod-queries | 1.75219 | ms | +| 90th percentile latency | prod-queries | 2.29527 | ms | +| 99th percentile latency | prod-queries | 50.4419 | ms | +| 100th percentile latency | prod-queries | 97.9905 | ms | +| 50th percentile service time | prod-queries | 1.75219 | ms | +| 90th percentile service time | prod-queries | 2.29527 | ms | +| 99th percentile service time | prod-queries | 50.4419 | ms | +| 100th percentile service time | prod-queries | 97.9905 | ms | +| error rate | prod-queries | 0 | % | +| Mean recall@k | prod-queries | 0.96 | | +| Mean recall@1 | prod-queries | 0.99 | | + +------------------------------------ +[INFO] ✅ SUCCESS (took 218 seconds) +------------------------------------ +``` + +(注:由于篇幅限制,这里省略了标量量化和乘积量化的完整结果输出。实际翻译文件中应包含所有三种结果。) diff --git a/i18n/zh/clients/hadoop.md b/i18n/zh/clients/hadoop.md new file mode 100644 index 00000000..eefc59de --- /dev/null +++ b/i18n/zh/clients/hadoop.md @@ -0,0 +1,379 @@ +--- +title: Hadoop 连接器 +--- + +# Hadoop 连接器 + +OpenSearch Hadoop 连接器允许您在 [Apache Spark](http://spark.apache.org)、[Apache Hive](http://hive.apache.org)、Hadoop MapReduce 和 OpenSearch 之间读写数据。它使 Spark 作业能够直接将数据索引到 OpenSearch 并对其运行查询,通过跨 Spark 分区和 OpenSearch 分片的并行读写实现高效的分布式处理。 + +有关源代码,请参阅 [OpenSearch Hadoop](https://github.com/opensearch-project/opensearch-hadoop) 仓库。 + +## 设置 + +使用 `--packages` 将连接器添加到您的 Spark 应用程序: + +- 对于 Spark 3.4.x,运行以下命令: + +```bash +pyspark --packages org.opensearch.client:opensearch-spark-30_2.12:2.0.0 +``` + +- 对于 Spark 3.5.x,运行以下命令: + +```bash +pyspark --packages org.opensearch.client:opensearch-spark-35_2.12:2.0.0 +``` + +- 对于 Spark 4.x,运行以下命令: + +```bash +pyspark --packages org.opensearch.client:opensearch-spark-40_2.13:2.0.0 +``` + +或者,在您的构建文件中将 Spark 添加为依赖项: + +```xml +<dependency> + <groupId>org.opensearch.client</groupId> + <artifactId>opensearch-spark-30_2.12</artifactId> + <version>2.0.0</version> +</dependency> +``` + +选择与您的 Spark 和 Scala 版本匹配的构件,如下表所列。 + +Spark 版本 | Scala 版本 | 构件 +:--- | :--- | :--- +3.4.x | 2.12 | `org.opensearch.client:opensearch-spark-30_2.12:2.0.0` +3.4.x | 2.13 | `org.opensearch.client:opensearch-spark-30_2.13:2.0.0` +3.5.x | 2.12 | `org.opensearch.client:opensearch-spark-35_2.12:2.0.0` +3.5.x | 2.13 | `org.opensearch.client:opensearch-spark-35_2.13:2.0.0` +4.x | 2.13 | `org.opensearch.client:opensearch-spark-40_2.13:2.0.0` + +## 基本用法 + +以下示例演示了使用连接器与不同 Spark API 进行的基本读写操作。 + +### PySpark + +无需额外的 Python 包。Java 连接器使用 `--packages` 或 `spark.jars` 加载: + +```python +# 写入(将文档索引到 OpenSearch) +df = spark.createDataFrame([("John", 30), ("Jane", 25)], ["name", "age"]) +df.write.format("opensearch").save("people") + +# 读取(从 OpenSearch 查询文档) +df = spark.read.format("opensearch").load("people") +df.show() + +# 使用查询读取(仅将匹配的文档传输到 Spark) +filtered = spark.read \ + .format("opensearch") \ + .option("opensearch.query", '{"query":{"match":{"name":"John"}}}') \ + .load("people") +``` + +### Scala + +使用 Scala API 访问辅助方法,如 `saveToOpenSearch`,以获得更简洁的语法: + +```scala +import org.opensearch.spark.sql._ + +// 写入(将文档索引到 OpenSearch) +val df = spark.createDataFrame(Seq(("John", 30), ("Jane", 25))).toDF("name", "age") +df.saveToOpenSearch("people") + +// 读取(从 OpenSearch 查询文档) +val result = spark.read.format("opensearch").load("people") +result.show() + +// 使用查询读取 +val filtered = spark.read + .format("opensearch") + .option("opensearch.query", """{"query":{"match":{"name":"John"}}}""") + .load("people") +``` + +### Java + +使用 `JavaOpenSearchSparkSQL` 包装器用于 Java 应用程序: + +```java +import org.opensearch.spark.sql.api.java.JavaOpenSearchSparkSQL; + +// 写入 +Dataset<Row> df = spark.createDataFrame(data, schema); +JavaOpenSearchSparkSQL.saveToOpenSearch(df, "people"); + +// 读取 +Dataset<Row> result = spark.read().format("opensearch").load("people"); +result.show(); +``` + +### Spark SQL + +您可以将 OpenSearch 索引注册为临时视图并使用 SQL 查询它: + +```python +spark.sql(""" + CREATE TEMPORARY VIEW people + USING opensearch + OPTIONS (resource 'people') +""") + +spark.sql("SELECT * FROM people WHERE age > 25").show() +``` + +## 写入操作 + +配置如何将文档写入 OpenSearch 索引,包括文档 ID、写入模式和路由策略。 + +### 指定文档 ID + +使用 `opensearch.mapping.id` 控制每个文档的 `_id`: + +```python +df.write.format("opensearch") \ + .option("opensearch.mapping.id", "id") \ + .save("my-index") +``` + +### 写入模式 + +使用 Spark 的写入模式控制数据如何写入 OpenSearch: + +```python +# 追加(默认):将文档添加到索引 +df.write.format("opensearch").mode("append").save("my-index") + +# 覆盖:删除索引并使用新数据重新创建它 +df.write.format("opensearch").mode("overwrite").save("my-index") +``` + +### Upsert + +如果文档存在则更新文档,如果不存在则将其插入为新文档。此操作需要指定文档 ID 字段: + +```python +df.write.format("opensearch") \ + .option("opensearch.mapping.id", "id") \ + .option("opensearch.write.operation", "upsert") \ + .save("my-index") +``` + +### 动态索引路由 + +在索引名称中使用占位符根据字段值将文档路由到不同的索引。此功能需要 Scala `saveToOpenSearch` 方法: + +```scala +import org.opensearch.spark.sql._ + +// 按字段值路由:{"category": "electronics", "name": "TV"} -> 索引 "electronics" +df.saveToOpenSearch("{category}") + +// 前缀 + 字段值:{"env": "prod", "msg": "ok"} -> 索引 "logs-prod" +df.saveToOpenSearch("logs-{env}") + +// 日期格式化:{"timestamp": "2026-02-16T10:30:00.000Z", "msg": "ok"} -> 索引 "logs-2026.02.16" +df.saveToOpenSearch("logs-{timestamp|yyyy.MM.dd}") +``` + +## 读取操作 + +通过过滤查询和选择特定字段来优化从 OpenSearch 检索数据,以减少数据传输。 + +### 使用查询读取 + +在 OpenSearch 级别过滤数据,以便仅将匹配的文档加载到 Spark: + +```python +# Query DSL +df = spark.read.format("opensearch") \ + .option("opensearch.query", '{"query":{"range":{"age":{"gte":25}}}}') \ + .load("my-index") + +# URI 查询 +df = spark.read.format("opensearch") \ + .option("opensearch.query", "?q=name:John") \ + .load("my-index") +``` + +### 选择字段 + +仅加载特定字段以减少数据传输: + +```python +df = spark.read.format("opensearch") \ + .option("opensearch.read.field.include", "name,age") \ + .load("my-index") +``` + +## 安全性 + +使用身份验证和加密保护与 OpenSearch 集群的连接。 + +### 基本身份验证 + +为启用了身份验证的 OpenSearch 集群提供凭据: + +```python +df.write.format("opensearch") \ + .option("opensearch.net.http.auth.user", "<username>") \ + .option("opensearch.net.http.auth.pass", "<password>") \ + .save("my-index") +``` + +### HTTPS + +启用 SSL/TLS 加密以实现安全连接: + +```python +df.write.format("opensearch") \ + .option("opensearch.net.ssl", "true") \ + .save("my-index") +``` + +## 高级 Spark 功能 + +访问低级 Spark API 和流式处理功能以满足特定用例。 + +### Spark 弹性分布式数据集 + +对于低级访问,连接器提供基于弹性分布式数据集(RDD)的读写方法: + +```scala +import org.opensearch.spark._ + +// 写入 +val data = sc.makeRDD(Seq( + Map("name" -> "John", "age" -> 30), + Map("name" -> "Jane", "age" -> 25) +)) +data.saveToOpenSearch("people") + +// 读取 +val rdd = sc.opensearchRDD("people") +rdd.collect().foreach(println) + +// 使用查询读取 +val filtered = sc.opensearchRDD("people", "?q=name:John") +``` + +### Spark Structured Streaming + +连接器支持 Spark Structured Streaming 作为接收器: + +```scala +val query = streamingDF.writeStream + .format("opensearch") + .option("checkpointLocation", "/tmp/checkpoint") + .start("streaming-index") +``` + +## 替代接口 + +将连接器与 Hadoop MapReduce 和 Apache Hive 一起使用以实现替代工作流程。 + +### Hadoop MapReduce + +对于 Hadoop MapReduce 作业,连接器提供 `OpenSearchInputFormat` 和 `OpenSearchOutputFormat`。将 `opensearch-hadoop-mr-2.0.0.jar` 添加到您的作业 `classpath`。 + +```java +// 写入 +Configuration conf = new Configuration(); +conf.set("opensearch.resource", "my-index"); +Job job = new Job(conf); +job.setOutputFormatClass(OpenSearchOutputFormat.class); +job.waitForCompletion(true); + +// 读取 +Configuration conf = new Configuration(); +conf.set("opensearch.resource", "my-index"); +Job job = new Job(conf); +job.setInputFormatClass(OpenSearchInputFormat.class); +job.waitForCompletion(true); +``` + +### Apache Hive + +连接器提供 Apache Hive 存储处理程序。将 `opensearch-hadoop-hive-2.0.0.jar` 添加到您的 Hive classpath: + +```sql +ADD JAR /path/opensearch-hadoop-hive-2.0.0.jar; + +CREATE EXTERNAL TABLE people ( + name STRING, + age INT) +STORED BY 'org.opensearch.hadoop.hive.OpenSearchStorageHandler' +TBLPROPERTIES('opensearch.resource' = 'people'); + +SELECT * FROM people; +``` + +## 连接到 Amazon OpenSearch Service + +要使用 IAM 身份验证连接到 Amazon OpenSearch Service,请启用 AWS Signature Version 4 签名和 HTTPS: + +```python +df.write.format("opensearch") \ + .option("opensearch.nodes", "https://search-xxx.us-east-1.es.amazonaws.com") \ + .option("opensearch.port", "443") \ + .option("opensearch.net.ssl", "true") \ + .option("opensearch.nodes.wan.only", "true") \ + .option("opensearch.aws.sigv4.enabled", "true") \ + .option("opensearch.aws.sigv4.region", "us-east-1") \ + .save("my-index") +``` + +`classpath` 上需要以下 AWS SDK v2 依赖项: +- `software.amazon.awssdk:auth:2.31.59`(或更高版本) +- `software.amazon.awssdk:regions:2.31.59`(或更高版本) +- `software.amazon.awssdk:http-client-spi:2.31.59`(或更高版本) +- `software.amazon.awssdk:identity-spi:2.31.59`(或更高版本) +- `software.amazon.awssdk:sdk-core:2.31.59`(或更高版本) +- `software.amazon.awssdk:utils:2.31.59`(或更高版本) + +## 连接到 Amazon OpenSearch Serverless + +要连接到 Amazon OpenSearch Serverless,请添加 `opensearch.serverless` 并将 Signature Version 4 服务名称设置为 `aoss`: + +```python +df.write.format("opensearch") \ + .option("opensearch.nodes", "https://xxx.us-east-1.aoss.amazonaws.com") \ + .option("opensearch.port", "443") \ + .option("opensearch.net.ssl", "true") \ + .option("opensearch.nodes.wan.only", "true") \ + .option("opensearch.aws.sigv4.enabled", "true") \ + .option("opensearch.aws.sigv4.region", "us-east-1") \ + .option("opensearch.aws.sigv4.service.name", "aoss") \ + .option("opensearch.serverless", "true") \ + .save("my-index") +``` + +## 配置属性 + +所有配置属性都以 `opensearch` 前缀开头。可以使用 Spark 配置(`--conf`)、作为 `DataFrame` 读取器/写入器的选项或在 Hadoop 配置中设置属性。 + +属性 | 默认值 | 描述 +:--- | :--- | :--- +`opensearch.resource` | (无) | OpenSearch 索引名称。也可以指定为 `saveToOpenSearch()` 或 `load()` 的参数。 +`opensearch.nodes` | `localhost` | OpenSearch 主机地址。 +`opensearch.port` | `9200` | OpenSearch REST 端口。 +`opensearch.nodes.wan.only` | `false` | 通过负载均衡器或代理连接时设置为 `true`。 +`opensearch.query` | match all | 用于读取的查询 DSL 或统一资源标识符(URI)查询。 +`opensearch.net.ssl` | `false` | 启用 HTTPS。 +`opensearch.mapping.id` | (无) | 用作 `_id` 的文档字段。 +`opensearch.write.operation` | `index` | 写入操作:`index`、`create`、`update` 或 `upsert`。 +`opensearch.scroll.size` | `1000` | 读取时每批获取的文档数。 +`opensearch.read.field.include` | (无) | 要读取的字段的逗号分隔列表。 + +## 兼容性 + +下表列出了连接器版本及其兼容的运行时版本。 + +客户端版本 | 最低 Java 运行时版本 | OpenSearch 版本 | Spark 版本 +:--- | :--- | :--- | :--- +1.0.0--1.3.0 | Java 8 | 1.x, 2.x | 3.4.x +2.0.0 | Java 11 | 1.x, 2.x, 3.x | 3.4.x, 3.5.x, 4.x diff --git a/i18n/zh/dashboards/compression.md b/i18n/zh/dashboards/compression.md new file mode 100644 index 00000000..bd83e0ea --- /dev/null +++ b/i18n/zh/dashboards/compression.md @@ -0,0 +1,170 @@ +--- +title: 网络压缩 +--- + +# 网络压缩 +<Badge type="tip" text="1.0 版本引入" /> + +OpenSearch Dashboards 支持自动压缩 JavaScript 和 CSS 包以减少网络传输大小。当将 OpenSearch Dashboards 部署在具有响应大小限制的代理、网关或负载均衡器后面时,此功能特别有用。 + +## 压缩方法 + +OpenSearch Dashboards 使用以下压缩算法生成所有插件包的预压缩版本: + +- **Brotli (`br`)**: 现代压缩算法,提供最佳压缩比 +- **gzip (`gz`)**: 广泛支持的压缩算法,具有良好的兼容性 + +当客户端请求包文件时,如果客户端发送适当的 `Accept-Encoding` 标头,OpenSearch Dashboards 会自动提供压缩版本。如果未指定压缩编码,OpenSearch Dashboards 将提供未压缩的文件。 + +## 压缩效果 + +下表显示了大型插件包的典型压缩比,以 Observability 插件为例: + +| 压缩方法 | 文件大小 | 压缩比 | +|:---|:---|:---| +| Brotli (`br`) | ~1.8 MB | ~86% 缩减 | +| gzip (`gz`) | ~2.5 MB | ~80% 缩减 | +| 未压缩 | ~12.6 MB | 基准线 | + +实际压缩比取决于插件及其依赖项。 + +## 配置 + +压缩默认启用。您可以在 `opensearch_dashboards.yml` 中使用以下设置来控制压缩行为。 + +### `server.compression.enabled` + +启用或禁用所有响应的 HTTP 压缩。当设置为 `false` 时,无论客户端标头如何,OpenSearch Dashboards 仅提供未压缩的内容。 + +- **类型**: 布尔值 +- **默认值**: `true` +- **示例**: + + ```yaml + server: + compression: + enabled: true + ``` + +### `server.compression.referrerWhitelist` + +将压缩限制为来自特定引用者主机名的请求。配置此设置后,OpenSearch Dashboards 仅压缩来自指定引用者的请求的响应。此设置仅在 `server.compression.enabled` 为 `true` 时有效。 + +- **类型**: 字符串数组 +- **默认值**: 未设置(为所有引用者启用压缩) +- **示例**: + + ```yaml + server: + compression: + enabled: true + referrerWhitelist: + - trusted-proxy.example.com + - api-gateway.example.com + ``` + +## 在代理中使用压缩 + +在代理、网关或负载均衡器后面部署 OpenSearch Dashboards 时,请配置您的代理以通过在上游请求中包含 `Accept-Encoding` 标头来请求压缩内容。 + +### 示例: 请求 Brotli 压缩 + +```bash +curl -H 'Accept-Encoding: br' \ + https://your-dashboards-host/bundles/plugin/observabilityDashboards/observabilityDashboards.plugin.js +``` + +响应包含 `Content-Encoding: br` 标头,表示已应用 Brotli 压缩: + +```bash +HTTP/1.1 200 OK +content-type: application/javascript; charset=utf-8 +cache-control: max-age=31536000 +content-encoding: br +osd-name: dashboards-opensearch-dashboards-55cf49965-9bcwz +vary: accept-encoding +Date: Wed, 08 May 2024 00:01:14 GMT +Connection: keep-alive +Keep-Alive: timeout=120 +Transfer-Encoding: chunked +``` + +### 示例: 请求 gzip 压缩 + +```bash +curl -H 'Accept-Encoding: gzip' \ + https://your-dashboards-host/bundles/plugin/observabilityDashboards/observabilityDashboards.plugin.js +``` + +响应包含 `Content-Encoding: gzip` 标头: + +```bash +HTTP/1.1 200 OK +content-type: application/javascript; charset=utf-8 +cache-control: max-age=31536000 +content-encoding: gzip +osd-name: dashboards-opensearch-dashboards-55cf49965-9bcwz +vary: accept-encoding +Date: Wed, 08 May 2024 00:01:14 GMT +Connection: keep-alive +Keep-Alive: timeout=120 +Transfer-Encoding: chunked +``` + +### 示例: 无压缩 + +如果您不指定 `Accept-Encoding` 标头(或禁用了压缩),OpenSearch Dashboards 将提供未压缩的文件: + +```bash +curl https://your-dashboards-host/bundles/plugin/observabilityDashboards/observabilityDashboards.plugin.js +``` + +### 代理配置示例 + +以下示例显示如何配置不同的代理服务器以请求压缩内容。 + +#### NGINX + +配置 NGINX 以从 OpenSearch Dashboards 请求压缩内容: + +```json +location / { + proxy_pass http://opensearch-dashboards:5601; + proxy_set_header Accept-Encoding "br, gzip"; + proxy_set_header Host $host; +} +``` + +#### Apache + +配置 Apache 以从 OpenSearch Dashboards 请求压缩内容: + +```xml +<Location /> + ProxyPass http://opensearch-dashboards:5601/ + ProxyPassReverse http://opensearch-dashboards:5601/ + RequestHeader set Accept-Encoding "br, gzip" +</Location> +``` + +## 代理响应大小限制 + +如果您的代理或网关有响应大小限制(例如 10 MB),请按照以下步骤解决: + +1. 配置您的代理首先请求 Brotli 压缩(最佳压缩比): + ``` + Accept-Encoding: br, gzip + ``` + +2. 验证压缩包的大小是否在代理限制范围内。大多数 OpenSearch Dashboards 插件包使用 Brotli 压缩后小于 3 MB。 + +3. 如果问题仍然存在,请考虑增加代理的响应大小限制或将大型插件分解为较小的组件。 + +## 浏览器支持 + +所有现代浏览器都会自动在其请求中包含 `Accept-Encoding` 标头,并透明地解压缩响应。压缩在浏览器端自动处理,无需任何配置。 + +压缩方法的浏览器支持: + +- **Brotli**: 所有现代浏览器都支持(Chrome、Firefox、Safari、Edge) +- **gzip**: 所有浏览器普遍支持 diff --git a/i18n/zh/dashboards/csp/csp-dynamic-configuration.md b/i18n/zh/dashboards/csp/csp-dynamic-configuration.md new file mode 100644 index 00000000..c827a2ff --- /dev/null +++ b/i18n/zh/dashboards/csp/csp-dynamic-configuration.md @@ -0,0 +1,73 @@ +--- +title: CSP 规则 +--- + +# CSP 规则 +<Badge type="tip" text="2.13 版本引入" /> + +内容安全策略 (CSP) 是一种旨在防止跨站点脚本 (XSS)、点击劫持和其他代码注入攻击的安全标准。OpenSearch Dashboards 通过在每次页面加载时发送 `Content-Security-Policy` 响应标头来执行 CSP。 + +## 配置 + +要配置 CSP,请将以下键添加到 `opensearch_dashboards.yml`。所有 `allowed*Sources` 值都会附加到该指令的严格策略默认值: + +```yaml +# 启用严格的 CSP 执行。 +csp.enable: true + +# 将受信任的源附加到 frame-ancestors(控制 iframe 嵌入)。 +csp.allowedFrameAncestorSources: ["https://portal.example.com"] + +# 将受信任的源附加到 connect-src(来自浏览器的 fetch/XHR 调用)。 +csp.allowedConnectSources: ["https://api.example.com"] + +# 将受信任的源附加到 img-src。 +csp.allowedImgSources: ["https://cdn.example.com"] + +# 将特定指令放宽回其非严格默认值 +# 同时保持策略的其余部分严格。 +csp.loosenCspDirectives: ["style-src"] +``` + +然后重新启动 OpenSearch 以使更改生效。 + +## CSP 设置 + +下表描述了可用的 CSP 设置。 + +设置 | 类型 | 描述 +:--- | :--- | :--- +`csp.enable` | 布尔值 | 启用严格的 CSP 执行。默认值为 `true`。 +`csp.allowedFrameAncestorSources` | 字符串数组 | 附加到 `frame-ancestors` 指令的源。用于允许在 iframe 中嵌入 Dashboards。 +`csp.allowedConnectSources` | 字符串数组 | 附加到 `connect-src` 的源。用于允许浏览器发起的对外部端点的请求(fetch、XHR 或 WebSocket)。 +`csp.allowedImgSources` | 字符串数组 | 附加到 `img-src` 的源。用于允许来自外部 CDN 或图块服务器的图像。 +`csp.loosenCspDirectives` | 字符串数组 | 要放宽回其非严格默认值的指令名称。 + +## 启用站点嵌入 + +要在另一个站点上的 iframe 中嵌入 OpenSearch Dashboards,请将该站点添加到 `csp.allowedFrameAncestorSources`: + +```yaml +csp.allowedFrameAncestorSources: ["https://portal.example.com"] +``` + +这会在响应标头中生成以下 `frame-ancestors` 指令: + +``` +frame-ancestors 'self' https://portal.example.com +``` + +## 仅报告模式 + +要在不执行新 CSP 策略的情况下审核它,请启用 `Content-Security-Policy-Report-Only` 标头。违规会被报告,但不会阻止任何内容: + +```yaml +csp-report-only.isEmitting: true +csp-report-only.allowedFrameAncestorSources: ["https://portal.example.com"] +csp-report-only.allowedConnectSources: ["https://api.example.com"] +csp-report-only.allowedImgSources: ["https://cdn.example.com"] +``` + +## 使用 applicationConfig 配置 CSP 规则(已弃用) + +**已弃用。** 在 OpenSearch Dashboards 2.13--2.16 中,您可以通过使用 `applicationConfig` 和 `cspHandler` 插件通过 REST API 动态设置 `frame-ancestors` 指令。此方法不再有效。请改用 `csp.*` 设置。 diff --git a/i18n/zh/dashboards/dashboard/adding-a-viz.md b/i18n/zh/dashboards/dashboard/adding-a-viz.md new file mode 100644 index 00000000..41a3f8ed --- /dev/null +++ b/i18n/zh/dashboards/dashboard/adding-a-viz.md @@ -0,0 +1,76 @@ +--- +title: 向仪表板添加可视化 +--- + +# 向仪表板添加可视化 + +您可以将现有面板添加到仪表板或直接在仪表板中创建新的可视化。 + +## 前提条件 + +只有在打开仪表板进行编辑时才能向仪表板添加可视化。请参阅[打开仪表板](/dashboards/dashboard/opening-a-dashboard)。 + +## 在仪表板中创建新可视化 + +您可以创建新的可视化,但不能在仪表板中创建新搜索。 + +::: info NOTE +要向仪表板添加搜索,您必须在发现应用程序中创建它,然后添加它。请参阅[使用发现探索数据](/dashboards/discover/index-discover)。 +::: + +要在仪表板中创建新可视化,请执行以下步骤: + +1. 从应用程序工具栏中,选择**创建新**。 + +1. 从**新可视化**窗口中,选择可视化类型。 + +1. 在**新 _\<类型\>_/选择源**对话框中,选择索引模式。 + + ::: info NOTE + 在此时,像 Maps 和 VisBuilder 这样的高级可视化工具不会显示源选择对话框,而是在工具中内置了源选择。 + ::: + +1. Dashboards 应用程序打开可视化编辑器并显示默认(计数)可视化。 + +<!-- 按照[构建可视化](/dashboards/visualize/viz-index#building-visualizations)中的描述编辑可视化。 --> + +1. 保存可视化。 + +<!-- 请参阅[保存新可视化](/dashboards/visualize/saving-a-viz/#saving-a-new-visualization)。 --> + + 确保在**保存可视化**对话框中选中**保存后添加到仪表板**切换按钮。 + + + ::: info NOTE + 当您通过在仪表板中创建可视化来添加可视化时,**保存可视化**对话框中的**保存**按钮显示为**保存并返回**。 + ::: + +## 向仪表板添加面板 + +要向仪表板添加可视化或搜索,请执行以下步骤: + +1. 在应用程序菜单中,选择**添加**。 + + 应用程序显示**添加面板**对话框。 + +1. (可选)在**搜索**框中,输入术语以过滤面板列表。 + + 搜索_不_区分大小写。不允许使用特殊字符,即使面板名称中允许它们。 + +1. (可选)在排序下拉菜单中,选择升序或降序以选择字母顺序或反向字母顺序排序。 + + 排序_是_区分大小写的。排序中包含特殊字符。例如,搜索 `ecommerce` 将在过滤列表中包含所有这些可视化:`[eCommerce] Markdown`、`[Ecommerce] Order Count` 和 `eCommerce Orders`。 + +1. (可选)在**类型**下拉菜单中,选择一个或多个面板类型。下拉菜单包括可视化、搜索和特殊可视化类型,如**Maps** 和 **VisBuilder** 面板。如果未选择任何项,默认情况下过滤器包括所有类型。 + +1. (可选)在每页行数下拉菜单中,选择每个对话框页面要列出的面板数。默认为 10。 + +1. (可选)从页码列表中选择要跳转到的页码,或使用 右箭头图标 (右)和 左箭头图标 (左)图标滚动浏览页面。 + +1. 从列表中选择一个或多个面板。 + + ::: info NOTE + 对话框保持活动状态,以便您可以选择多个面板添加到仪表板。 + ::: + +1. 选择 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="关闭图标"/> (关闭)图标以关闭对话框。 diff --git a/i18n/zh/dashboards/dashboard/customizing-a-dash.md b/i18n/zh/dashboards/dashboard/customizing-a-dash.md new file mode 100644 index 00000000..7058add2 --- /dev/null +++ b/i18n/zh/dashboards/dashboard/customizing-a-dash.md @@ -0,0 +1,121 @@ +--- +title: 自定义仪表板 +--- + +# 自定义仪表板 + +您可以通过以下方式自定义仪表板: + +- [调整面板大小](#resizing-a-panel)。 +- [移动面板](#moving-a-panel)。 +- [在全屏模式下查看面板](#using-full-screen-mode) +- [自定义](#customizing-a-visualization-panel)可视化中的标题、图例或颜色。 + +## 前提条件 + +只有在打开仪表板进行编辑时才能自定义仪表板。请参阅[打开仪表板](/dashboards/dashboard/opening-a-dashboard)。 + +### 调整面板大小 + +要调整面板大小,请执行以下步骤: + +1. 选择并按住面板右下角的 调整大小图标 (调整大小)图标。 + +1. 拖动到新尺寸。 + + 其他面板会移开以适应新的面板大小。 + +### 移动面板 + +要移动面板,请执行以下步骤: + +1. 选择并按住面板标题或面板顶部,如下图所示,位置在 选项图标 (选项)图标的左侧。 + +*在 Dashboards 中拖动面板* + +1. 将面板拖动到新位置。 + + 其他面板会移开以适应新的面板位置。 + +## 使用全屏模式 + +您可以在全屏模式下查看单个可视化面板,然后返回仪表板模式。 + +### 在全屏模式下查看面板 + +要在全屏模式下查看面板,请执行以下步骤: + +1. 选择面板右上角的 省略号图标 (省略号)图标。 + + ::: info NOTE + 省略号图标 (省略号)图标仅在您将鼠标指向可视化面板时可见。 + ::: + +1. 在**选项**下拉菜单中,选择 最大化图标 (最大化)**最大化面板**。 + +### 从全屏模式还原面板 + +要从全屏模式还原面板,请执行以下步骤: + +1. 选择面板右上角的 省略号图标 (省略号)图标。 + + ::: info NOTE + 省略号图标 (省略号)图标仅在您将鼠标指向可视化面板时可见。 + ::: + +1. 选择 <img src="/images/icons/minimize-icon.png" class="inline-icon" alt="最小化图标"/> (最小化)**最小化**。 + +## 自定义可视化面板 + +您可以在仪表板中自定义可视化面板的以下方面: + +- [隐藏或显示图例](#hiding-and-displaying-the-legend)。 +- [更改可视化中的颜色](#changing-a-color)。 +- [更改或隐藏面板标题](#changing-or-hiding-the-panel-title)。 + +### 隐藏和显示图例 + +要显示或隐藏面板图例: + +- 选择面板左下角的 列表图标 (列表)图标。 + +### 更改颜色 + +要更改可视化中的颜色,请执行以下步骤: + +1. 从可视化图例中,选择一个类别。 + +1. 从弹出窗口中,选择一种颜色。 + + 可视化图形会使用您的更改进行更新。 + + 颜色更改仅保存到当前面板和仪表板。它不会影响保存的可视化。 + + + ::: info NOTE +<!-- 要更改可视化中的颜色,请参阅[可视化颜色](/dashboards/visualize/visualize-app/configuring-viz#visualization-colors)。 + ::: + + --> + +### 更改或隐藏面板标题 + +要显示、隐藏或自定义面板标题,请执行以下步骤: + +1. 选择 齿轮图标 (齿轮)图标。 + +1. 从**选项**窗口中,选择**编辑面板标题**。 + +1. 从**自定义面板**对话框中,在**面板标题**下输入标题。 + +1. (可选)切换**显示面板标题**以隐藏标题。 + +1. 选择**保存**。 + + ::: info NOTE + 更改面板标题仅影响当前仪表板上的面板。更改不会影响任何其他仪表板上的可视化,也不会影响包含该可视化的任何其他面板。 + ::: + +## 后续步骤 + +如果您对仪表板进行了要保留的更改,请保存仪表板。请参阅[保存仪表板](/dashboards/dashboard/managing-a-dash#saving-a-dashboard)。 diff --git a/i18n/zh/dashboards/dashboard/dash-tutorial.md b/i18n/zh/dashboards/dashboard/dash-tutorial.md new file mode 100644 index 00000000..4c4c7950 --- /dev/null +++ b/i18n/zh/dashboards/dashboard/dash-tutorial.md @@ -0,0 +1,132 @@ +--- +title: 仪表板教程 +--- + +# 教程: 创建仪表板 + +您可以使用 OpenSearch Dashboards 中的**仪表板**应用程序构建包含数据多个可视化表示的页面。 + +使用以下教程学习使用**仪表板**应用程序和 OpenSearch 示例数据创建仪表板。示例数据集具有可用于仪表板的现有示例可视化,或者您可以创建自己的可视化。教程演示如何做这两种操作。 + +有关仪表板 UI 的概述,请参阅[导航仪表板应用程序 UI](/dashboards/dashboard/#navigating-the-dashboards-application-ui)。 + +## 前提条件 + +此页面上的教程使用 [OpenSearch Playground](https://playground.opensearch.org/app/home#/) 中已安装的[**示例电商数据**](https://playground.opensearch.org/app/home#/tutorial_directory)数据集。 + +如果您使用 OpenSearch Dashboards 的本地安装并且尚未添加示例数据,请参阅[准备数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +::: info NOTE +以下教程假设您使用现有的 OpenSearch Dashboards 安装或使用 [OpenSearch Playground](https://playground.opensearch.org/app/home#/)。根据您使用的是哪一个,某些功能可能不可用。例如,示例数据集可能不包含在您现有的安装中,并且在 OpenSearch Playground 中保存仪表板不是一个选项。 +::: + +## 创建仪表板 + +要创建新仪表板,请执行以下步骤: + +1. | 在经典导航中 | 在工作区导航中 | + | :-- | :-- | + | - 选择 **OpenSearch Dashboards** > **仪表板**。<br/>- 选择**仪表板**。 | 选择**仪表板**。 | + +1. | 在经典导航中 | 在工作区导航中 | + | :-- | :-- | + | - 在仪表板面板中,选择**创建**。<br/>- 从下拉菜单中,选择**仪表板**。 | 从应用程序菜单中,选择**创建仪表板**。 | + +## 添加现有可视化 + +要将保存的可视化添加到仪表板,请执行以下步骤: + +1. 从应用程序面板中,选择**添加现有**。 + +1. 在**添加面板**对话框中,在**搜索**框中键入 `ecommerce` 以过滤可用可视化列表。 + +1. 从**添加面板**对话框中,选择 **[eCommerce] Sales by Category**。 + +1. 选择 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="关闭图标"/> (关闭)图标以关闭对话框。 + +1. 使用[时间过滤器](/dashboards/discover/time-filter)选择 `Last 2 years` 作为时间窗口,如下图所示。 + +*时间过滤器设置为过去 2 年* + +1. 拖动选择面积图中的窄数据带,如下图所示。 + + *显示拖动选择的可视化* + + 数据调整为跨越数据显示的宽度,刻度自动调整,如下图所示。 + + *按类别销售的面积可视化* + + ::: info NOTE + 交互式选择日期范围会导致绝对时间间隔。 + ::: + +您已创建了一个包含单个面板的仪表板,您将在本教程中继续修改它。按照以下部分所述保存仪表板。 + +## 保存仪表板 + +要保存新仪表板,请执行以下步骤: + +1. 在**仪表板**工具栏中,选择**保存**。 + +1. 在**保存仪表板**对话框中,在**标题**框中输入 `[Ecommerce] tutorial dashboard`。 + +1. 通过选择**将时间与仪表板一起存储**来保存时间过滤器与仪表板。 + +1. 选择**保存**。 + +1. 从应用程序菜单中选择**编辑**以继续编辑仪表板。 + +## 创建可视化 + +要在**仪表板**中创建新可视化,请执行以下步骤: + +1. 从应用程序工具栏中,选择**创建新**。 + +1. 从**新可视化**窗口中,选择**指标**。 + +1. 在**新指标/选择源**对话框中,选择索引模式 **opensearch_dashboards_sample_data_ecommerce**。 + +1. 从工具栏中,选择**保存**。 + +1. 在**保存可视化**对话框中,输入可视化的标题。对于本教程,输入 `[eCommerce] Order Count`。 + +1. 选择**保存并返回**。 + + **仪表板**应用程序保存指标可视化并将其添加到仪表板,如下图所示。 + + *包含按类别销售和订单计数指标面板的仪表板* + +## 添加后续面板 + +向仪表板添加 Markdown 可视化。请执行以下步骤: + +1. 从仪表板工具栏中,选择**添加**。 + +1. 从**添加面板**对话框中,选择 **[eCommerce] Markdown**。 + +1. 选择 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="关闭图标"/> (关闭)图标以关闭对话框。 + + **仪表板**应用程序将 Markdown 面板添加到仪表板,如下图所示。 + + *示例仪表板* + +## 组织仪表板 + +您可以通过调整大小和重新排列面板来组织仪表板。移动和调整 Markdown 面板的大小以作为仪表板的标题和描述。请执行以下步骤: + +1. 选择并按住面板顶部 选项图标 (选项)图标左侧的任何位置。 + +1. 将面板拖动到应用程序面板的顶部。 + + 当您向上移动时,销售按类别面板会自动与 Markdown 面板交换位置。 +1. 选择并按住面板右下角的 调整大小图标 (调整大小)图标。 + +1. 拖动以使面板更长更窄,以便它作为仪表板整个上部的横幅。 + + 指标面板会自动向下移动以为调整大小的 Markdown 面板留出空间。 + + 生成的仪表板应如下图所示。 + + *示例仪表板* + +1. 保存您的仪表板。请参阅[保存仪表板](#saving-a-dashboard)。 diff --git a/i18n/zh/dashboards/dashboard/dashboard-sections.md b/i18n/zh/dashboards/dashboard/dashboard-sections.md new file mode 100644 index 00000000..b254489c --- /dev/null +++ b/i18n/zh/dashboards/dashboard/dashboard-sections.md @@ -0,0 +1,174 @@ +--- +title: 仪表板分区 +--- + +# 仪表板分区 +<Badge type="tip" text="3.9 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +仪表板分区是可折叠的容器,用于将可视化面板分组到仪表板中的命名类别中。使用分区来组织包含许多面板的仪表板,并通过将其保存为折叠很少使用的分区来减少其初始加载时间。 + +下图显示了包含可视化分区的仪表板。 + +*包含四个可视化面板的分区的仪表板* + +## 启用仪表板分区 + +要启用仪表板分区,请将以下设置添加到您的 `opensearch_dashboards.yml` 文件中: + +```yaml +uiSettings.overrides.home:useNewHomePage: true +dashboard.allowDashboardSections: true +``` + +然后重新启动 OpenSearch Dashboards 以使更改生效。 + +## 创建和管理分区 + +除了折叠和展开外,所有分区操作都需要[编辑模式](/dashboards/dashboard/opening-a-dashboard)。在编辑模式下,选择分区标题上的 垂直省略号图标 (垂直省略号)图标以打开分区上下文菜单,或选择面板上的 齿轮图标 (齿轮)图标以打开面板上下文菜单。 + +在分区内,面板有自己的网格布局,因此您可以像在没有分区的仪表板上一样拖动和调整它们的大小。分区会调整其高度以适应其内容。 + +### 创建分区 + +当您在仪表板上创建第一个分区时,所有现有面板都会分组到该分区中,以便保留当前布局。以后的分区从空开始。 + +要创建分区,请执行以下步骤: + +1. 在编辑模式下打开仪表板。 +2. 在工具栏中,选择**添加**。 +3. 选择**分区**。 + +分区被添加到仪表板。 + +### 重命名分区 + +要重命名分区,请执行以下步骤: + +1. 选择分区标题上的 垂直省略号图标 (垂直省略号)图标。 +2. 选择**重命名**。 +3. 在**重命名分区**对话框中,输入分区的名称。 +4. 选择**保存**。 + +::: tip TIP +分区名称不需要是唯一的,但不同的名称使在分区之间移动面板更容易。 +::: + +### 折叠和展开分区 + +要折叠分区,选择分区标题左侧的箭头。分区标题保持可见,面板被隐藏。要展开折叠的分区,再次选择箭头。 + +### 重新排序分区 + +要重新排序分区,请执行以下步骤: + +1. 选择并按住分区标题,它充当拖动手柄。 +2. 将分区拖动到新位置。 +3. 释放分区以将其放置到位。 + +### 将面板移动到另一个分区 + +您可以将面板从一个分区移动到另一个分区,或从**未分组**区域移动到分区中。 + +要移动面板,请执行以下步骤: + +1. 选择面板右上角的 齿轮图标 (齿轮)图标。 +2. 选择**移动到分区**。 +3. 在**移动到分区**对话框中,选择目标分区。 +4. 选择**移动**。 + +面板从其当前分区中删除并添加到目标分区。 + +### 向分区添加新可视化 + +要创建可视化并将其添加到分区,请执行以下步骤: + +1. 选择分区标题上的 垂直省略号图标 (垂直省略号)图标。 +2. 选择**创建新可视化**。 +3. 在可视化编辑器中构建可视化。 +4. 选择**保存并返回**。 + +可视化作为面板添加到分区。 + +### 向分区添加保存的可视化 + +要从库中添加现有可视化,请执行以下步骤: + +1. 选择分区标题上的 垂直省略号图标 (垂直省略号)图标。 +2. 选择**从库添加**。 +3. 搜索并选择保存的可视化。 + +可视化被添加到分区。 + +### 删除分区 + +要删除分区,请执行以下步骤: + +1. 选择分区标题上的 垂直省略号图标 (垂直省略号)图标。 +2. 选择**删除分区**。 +3. 在确认对话框中,确认删除。 + +::: danger WARNING +删除分区会永久删除其中的所有面板。在保存仪表板后,您无法撤消此操作。要保留面板,请先将它们移动到另一个分区。 +::: + +### 删除所有分区 + +您可以将所有面板返回到单个网格并从仪表板中删除分区结构。 + +要删除所有分区,请执行以下步骤: + +1. 选择任何分区标题上的 垂直省略号图标 (垂直省略号)图标。 +2. 选择**取消所有分区分组**。 +3. 在确认对话框中,确认操作。 + +所有面板返回到单个网格,分区被删除。 + +## 未分组面板 + +未分配给分区的面板出现在仪表板底部的**未分组**区域中。要将未分组的面板移动到分区中,请在面板上下文菜单中使用**移动到分区**。您不能将面板移回**未分组**区域。 + +## 折叠的分区和数据加载 + +折叠分区会隐藏其面板但不会删除它们。尚未显示的面板在其分区折叠时不请求数据;它在您展开分区并将面板滚动到视图中时获取数据。已经显示的面板即使在分区折叠时也会继续与仪表板的其余部分一起刷新。 + +::: tip TIP +在具有许多可视化的仪表板上,保存已折叠很少使用的分区的仪表板可以减少初始页面加载时间和对 OpenSearch 集群的负载。 +::: + +## 示例: 将仪表板组织成分区 + +要继续操作,请转到 OpenSearch Dashboards 主页,选择**添加示例数据**,然后为**示例电商订单**选择**添加数据**。 + +以下步骤将示例电商仪表板组织成两个分区: + +1. 在顶部菜单上,选择**仪表板**,然后选择 **[eCommerce] Revenue Dashboard**。 +2. 选择工具栏中的**编辑**切换以进入编辑模式。 +3. 在工具栏中,选择**添加** > **分区**。所有现有面板都分组到名为**分区 1** 的分区中。 +4. 选择**分区 1** 标题上的 垂直省略号图标 (垂直省略号)图标,选择**重命名**,输入 `Revenue and trends`,然后选择**保存**。 +5. 在工具栏中,再次选择**添加** > **分区**。在第一个分区下方出现一个空分区,也名为**分区 1**,因为第一个分区已重命名。将此分区重命名为 `Customer breakdown`。 +6. 在 **[eCommerce] Sales by Gender** 面板上,选择 齿轮图标 (齿轮)图标,然后选择**移动到分区**,如下图所示。 + *面板选项菜单,突出显示移动到分区操作* +7. 在**移动到分区**对话框中,选择 **Customer breakdown**,然后选择**移动**。 +8. 对 **[eCommerce] Sales Count Map** 和 **[eCommerce] Top Selling Products** 面板重复前两个步骤。 +9. 选择 **Customer breakdown** 标题左侧的箭头以折叠分区。 +10. 选择**保存**。 + +仪表板现在包含两个可以独立折叠、展开和重新排序的分区,折叠的 **Customer breakdown** 分区在您展开它之前不会加载数据。 + +## 限制 + +仪表板分区具有以下限制: + +- 不支持将面板从一个分区拖动到另一个分区。要移动面板,请在面板上下文菜单中使用**移动到分区**。 +- 不支持分区范围的过滤器和变量。所有过滤器都适用于整个仪表板。 +- 添加、重命名、重新排序和删除分区需要编辑模式。在查看模式下,您只能折叠和展开分区。 + +## 相关文档 + +- [创建仪表板](/dashboards/dashboard/) +- [自定义仪表板](/dashboards/dashboard/customizing-a-dash) +- [向仪表板添加可视化](/dashboards/dashboard/adding-a-viz) diff --git a/i18n/zh/dashboards/dashboard/managing-a-dash.md b/i18n/zh/dashboards/dashboard/managing-a-dash.md new file mode 100644 index 00000000..cf62ea5f --- /dev/null +++ b/i18n/zh/dashboards/dashboard/managing-a-dash.md @@ -0,0 +1,90 @@ +--- +title: 管理仪表板 +--- + +# 管理仪表板 + +从**仪表板**应用程序主页管理 OpenSearch Dashboards 中的仪表板,如下图所示。 + +*仪表板登录页面* + +您可以执行以下操作: + +- [保存仪表板](#saving-a-dashboard)。 +- 创建和编辑仪表板。请参阅[打开仪表板](/dashboards/dashboard/opening-a-dashboard)。 +- [将仪表板导出到文件](#exporting-a-dashboard)。 +- [删除仪表板](#deleting-dashboards)。 + +## 保存仪表板 + +您可以保存新创建的仪表板或保存对现有仪表板的更改。 + +### 保存新仪表板 + +要保存新仪表板,请执行以下步骤: + +1. 在应用程序菜单中,选择**保存**。 + + 应用程序显示**保存仪表板**对话框。 + +1. 在**标题**框中输入仪表板的标题。 + +1. (可选)输入**描述**。 + +1. (可选)要保存当前时间过滤器以便在重新打开仪表板时应用,请选择**将时间与仪表板一起存储**。 + +1. 选择**保存**。 + +### 保存现有仪表板 + +您可以随时保存仪表板。 + +要保存现有仪表板: + +1. 在**创建**面板的右上角选择**保存**。 + + 应用程序显示**保存仪表板**对话框。如果您之前保存过仪表板,**标题**框将包含仪表板标题。 + +1. (可选)要更改仪表板名称,请在**标题**框中输入仪表板的新标题。 + + ::: danger WARNING + 保存现有仪表板而不选择**另存为新仪表板**会覆盖仪表板的先前状态,即使您已重命名仪表板。 + ::: + +1. (可选)更新**描述**。 + +1. (可选)要保持保存的仪表板处于当前状态并将更改另存为新仪表板,请选择**另存为新仪表板**。您可以选择**复制面板**,以便对新仪表板中的面板的编辑不会影响原始仪表板。有关更多信息,请参阅[复制面板](/dashboards/dashboard/opening-a-dashboard#copying-panels)。 + +1. (可选)要保存当前时间过滤器以便在重新打开仪表板时应用,请选择**将时间与仪表板一起存储**。 + +1. 选择**保存**按钮。 + +## 导出仪表板 + +您可以将仪表板导出为 PDF 文件或 PNG 图像文件。 + +::: info NOTE +导出仪表板是报告功能。您必须激活报告插件才能导出文件。 +::: + +此功能需要报告插件。有关报告的更多信息,请参阅[使用 OpenSearch Dashboards 报告](/dashboards/reporting/report-dashboard-index)。 + +1. 从应用程序菜单中选择**报告**。 + +1. 从下拉菜单中,选择**下载 PDF** 或**下载 PNG**。 + + 应用程序显示**生成报告**对话框。报告可能需要几秒钟才能生成。 + +1. 报告会在浏览器中打开或下载,具体取决于您的浏览器首选项。 + +## 删除仪表板 + +要删除一个或多个仪表板,请执行以下步骤: + +1. 在[导航面板](/dashboards/navigating-ui#the-left-navigation-panel)中,选择 **OpenSearch Dashboards** > **仪表板**。 + +1. 从**仪表板**表中的列表中,选中要删除的所有仪表板旁边的复选框。 + +1. 选择**仪表板**面板中**搜索**框左侧的**删除 N 个仪表板**按钮(其中 **N** 是选中的复选框数)。 + +1. 在确认对话框中,选择**删除**。 diff --git a/i18n/zh/dashboards/dashboard/opening-a-dashboard.md b/i18n/zh/dashboards/dashboard/opening-a-dashboard.md new file mode 100644 index 00000000..21ac3558 --- /dev/null +++ b/i18n/zh/dashboards/dashboard/opening-a-dashboard.md @@ -0,0 +1,66 @@ +--- +title: 打开仪表板 +--- + +# 打开仪表板 + +要打开仪表板进行编辑,您可以执行以下操作之一: + +- [创建新的空仪表板](#creating-a-new-dashboard)。 +- [复制现有仪表板](#copying-a-dashboard)。 +- [编辑现有仪表板](#editing-an-existing-dashboard)。 + +## 创建新仪表板 + +要创建新仪表板,请执行以下步骤: + +1. 在[导航面板](/dashboards/navigating-ui#the-left-navigation-panel)中,选择 **OpenSearch Dashboards** > **仪表板**。 + +1. 从**仪表板**应用程序面板中,选择**创建**。 + +1. 从下拉菜单中,选择**仪表板**。 + + Dashboards 应用程序在编辑模式下打开一个空仪表板,如下图所示。 + +## 复制仪表板 + +要复制仪表板,请执行以下步骤: + +1. 在[导航面板](/dashboards/navigating-ui#the-left-navigation-panel)中,选择 **OpenSearch Dashboards** > **仪表板**。 + +1. 从**仪表板**表中的列表中,通过从表中选择其标题来选择仪表板。 + +1. 从工具栏中的菜单中,选择**克隆**。 + +1. 在**克隆仪表板**对话框中,输入复制的仪表板的名称。 + +1. (可选)要将面板从原始仪表板复制到复制的仪表板,请选择**复制面板**。有关更多信息,请参阅[复制面板](#copying-panels)。 + +1. 选择**确认克隆**。 + +### 复制面板 +<Badge type="tip" text="3.11 版本引入" /> + +默认情况下,复制的仪表板与原始仪表板共享其面板。两个仪表板引用相同的保存的可视化和保存的搜索,因此编辑副本中的面板也会在原始仪表板中更改它。 + +要将面板复制到新仪表板,请执行以下步骤: + +1. 在**克隆仪表板**或**保存仪表板**对话框中选择**复制面板**。 + +1. (可选)在**复制的面板标题**框中,自定义复制的面板的标题模板。因为一次复制多个面板,所以每个面板标题在复制时都是从模板生成的。模板必须包含 `{{panelTitle}}`,它将被替换为原始面板标题。您还可以包含 `{{dashboardTitle}}`,它将被替换为新仪表板标题。例如,如果您使用模板 `{{panelTitle}} ({{dashboardTitle}})` 将名为 `Errors by host` 的面板从名为 `Logs` 的仪表板复制到名为 `Logs archive` 的新仪表板,则该面板将复制为 `Errors by host (Logs archive)`。 + +仅复制面板。共享数据(如索引模式和数据源)保持共享。 + +::: info NOTE +如果无法复制面板,例如,因为其可视化已被删除,新仪表板仍会被保存。该面板继续使用原始对象,警告会列出未复制的面板。 +::: + +## 编辑现有仪表板 + +要编辑现有仪表板,请执行以下步骤: + +1. 在[导航面板](/dashboards/navigating-ui#the-left-navigation-panel)中,选择 **OpenSearch Dashboards** > **仪表板**。 + +1. 从**仪表板**表中的列表中,通过从表中选择其标题来选择仪表板。 + +1. 从工具栏中的菜单中,选择**编辑**。 diff --git a/i18n/zh/dashboards/dashboards-assistant/alert-insight.md b/i18n/zh/dashboards/dashboards-assistant/alert-insight.md new file mode 100644 index 00000000..9bcb5219 --- /dev/null +++ b/i18n/zh/dashboards/dashboards-assistant/alert-insight.md @@ -0,0 +1,308 @@ +--- +title: 警报洞察 +--- + +# 警报洞察 + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +OpenSearch Dashboards Assistant 警报洞察功能帮助生成警报摘要,并根据触发警报的日志提供日志模式。 + +## 配置警报洞察 + +要配置警报洞察,请使用以下步骤。 + +### 前提条件 + +在使用警报洞察之前,您必须在集群上安装 `alerting` 和 `alerting-dashboards` 插件。默认情况下,这些插件作为标准 OpenSearch 发行版的一部分安装。有关更多信息,请参阅[管理 OpenSearch 插件](/install-and-configure/plugins)。 + +### 步骤 1: 启用警报洞察 + +要启用警报洞察,请配置以下 `opensearch_dashboards.yml` 设置: + +```yaml +assistant.alertInsight.enabled: true +``` + +### 步骤 2: 创建代理 + +要编排警报洞察,您需要创建必要的[代理](/ml-commons-plugin/agents-tools/agents/)。通过发送以下请求创建用于创建所有必要代理的工作流模板: + +<details markdown="block"> + <summary> + 请求 + </summary> + +```json +POST /_plugins/_flow_framework/workflow?provision=true +{ + "name": "Alert Summary Agent", + "description": "Create Alert Summary Agent using Claude on BedRock", + "use_case": "REGISTER_AGENT", + "version": { + "template": "1.0.0", + "compatibility": ["2.17.0", "3.0.0"] + }, + "workflows": { + "provision": { + "user_params": {}, + "nodes": [ + { + "id": "create_claude_connector", + "type": "create_connector", + "previous_node_inputs": {}, + "user_inputs": { + "version": "1", + "name": "Claude Sonnet 4.6 runtime Connector", + "protocol": "aws_sigv4", + "description": "The connector to BedRock service for Claude model", + "actions": [ + { + "headers": { + "x-amz-content-sha256": "required", + "content-type": "application/json" + }, + "method": "POST", + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.prompt}\"}]}],\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens},\"temperature\":${parameters.temperature}}", + "action_type": "predict", + "url": "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" + } + ], + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "parameters": { + "region": "us-west-2", + "endpoint": "bedrock-runtime.us-west-2.amazonaws.com", + "content_type": "application/json", + "auth": "Sig_V4", + "max_tokens": "8000", + "service_name": "bedrock", + "temperature": "0.0001", + "response_filter": "$.content[0].text", + "anthropic_version": "bedrock-2023-05-31" + } + } + }, + { + "id": "register_claude_model", + "type": "register_remote_model", + "previous_node_inputs": { + "create_claude_connector": "connector_id" + }, + "user_inputs": { + "description": "Claude model", + "deploy": true, + "name": "claude-sonnet-4-6" + } + }, + { + "id": "create_alert_summary_ml_model_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You are an OpenSearch Alert Assistant to help summarize the alerts.\n Here is the detail of alert: ${parameters.context};\n The question is: ${parameters.question}." + }, + "name": "MLModelTool", + "type": "MLModelTool" + } + }, + { + "id": "create_alert_summary_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_alert_summary_ml_model_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "Alert Summary Agent", + "description": "this is an alert summary agent" + } + } + ] + } + } +} +``` + +</details> + +有关示例代理模板,请参阅 [Flow Framework 示例模板](https://github.com/opensearch-project/flow-framework/tree/2.x/sample-templates)。记下代理 ID;您将在以下步骤中使用它。 + +对于此示例,使用模板创建以下代理: +- 警报洞察代理,请参阅[流程模板](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/create-knowledge-base-alert-agent.json) +- 两个摘要代理: + - 基本警报摘要代理,请参阅[流程模板](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/alert-summary-agent-claude-tested.json) + - 包含日志模式的警报摘要代理,请参阅[流程模板](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/alert-summary-log-pattern-agent.json) + + 这些代理需要不同的提示。日志模式摘要的提示必须包含占位符 `${parameters.topNLogPatternData}` 和指导 LLM 有效使用此信息的附加说明。请注意,日志模式仅适用于使用 OpenSearch Dashboards 创建的查询监视器。 + +### 步骤 3: 创建根代理 + +接下来,为上一步创建的代理创建[根代理](/vector-search/ai-search/workflows/workflow-tutorial/#root_agent)。 + +为警报摘要代理创建根代理: + +```json +POST /.plugins-ml-config/_doc/os_summary +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "<SUMMARY_AGENT_ID>" + } +} +``` + +为包含日志模式的警报摘要代理创建根代理: + +```json +POST /.plugins-ml-config/_doc/os_summary_with_log_pattern +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "<SUMMARY_WITH_LOG_PATTERNS_AGENT_ID>" + } +} +``` + +为警报洞察代理创建根代理: + +```json +POST /.plugins-ml-config/_doc/os_insight +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "<ALERT_INSIGHTS_AGENT_ID>" + } +} +``` + +::: info NOTE +创建的 `os_insight` 代理提供与 OpenSearch 集群指标相关的警报洞察。对于与 OpenSearch 集群指标无关的警报洞察,您需要使用[此模板](https://github.com/opensearch-project/flow-framework/blob/2.x/sample-templates/create-knowledge-base-alert-agent.json)注册代理,并将代理名称更改为 `KB_For_Alert_Insight`。 +::: + +::: danger WARNING +此示例演示了系统索引。在启用安全的域中,只有超级管理员有权执行此代码。有关进行超级管理员调用的信息,请参阅[系统索引](/security/configuration/system-indices)。有关访问权限,请联系您的系统管理员。 +::: + +### 步骤 4: 测试代理 + +您可以通过使用示例负载调用代理来验证代理是否创建成功。 + +要测试警报摘要代理,请发送以下请求: + +```json +POST /_plugins/_ml/agents/{SUMMARY_AGENT_ID}/_execute +{ + "parameters": { + "question": "Please summarize this alert, do not use any tool.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n" + } +} +``` + +要测试包含日志模式的警报摘要代理,请发送以下请求: + +```json +POST /_plugins/_ml/agents/{SUMMARY_WITH_LOG_PATTERNS_AGENT_ID}/_execute +{ + "parameters": { + "question": "Please summarize this alert, do not use any tool.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "topNLogPatternData": "[[539,["[Sun Dec 04 07:12:44 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 06:19:18 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:59:47 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:11:22 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:31:12 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 05:04:04 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 20:24:49 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 06:16:23 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 20:47:17 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:30:43 2005] [error] mod_jk child workerEnv in error state 6","[Mon Dec 05 06:35:27 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:07:30 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 16:32:56 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 8"],"[ :: ] [] _ "],[32,["[Sun Dec 04 14:29:00 2005] [error] [client 4.245.93.87] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 08:54:17 2005] [error] [client 147.31.138.75] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:34:57 2005] [error] [client 61.138.216.82] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 07:45:45 2005] [error] [client 63.13.186.196] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 10:53:30 2005] [error] [client 218.76.139.20] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:48:48 2005] [error] [client 67.166.248.235] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:18:36 2005] [error] [client 67.154.58.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 01:30:32 2005] [error] [client 211.62.201.48] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 16:45:04 2005] [error] [client 216.216.185.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 17:31:39 2005] [error] [client 218.75.106.250] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:00:56 2005] [error] [client 68.228.3.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:14:09 2005] [error] [client 61.220.139.68] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 09:35:12 2005] [error] [client 207.203.80.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:28:44 2005] [error] [client 198.232.168.9] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 16:24:05 2005] [error] [client 58.225.62.140] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:53:43 2005] [error] [client 218.39.132.175] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 12:33:13 2005] [error] [client 208.51.151.210] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:59:01 2005] [error] [client 24.83.37.136] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 11:42:43 2005] [error] [client 216.127.124.16] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 05:15:09 2005] [error] [client 222.166.160.184] Directory index forbidden by rule: /var/www/html/"],"[ :: ] [] [ ...] : ////"],[12,["[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:16 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2"],"[ :: ] [] _ -"]]" + } +} +``` + +要测试警报洞察代理,请发送以下请求: + +```json +POST /_plugins/_ml/agents/{ALERT_INSIGHTS_AGENT_ID}/_execute +{ + "parameters": { + "question": "Please provide your insight on this alerts.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "summary": "<OUTPUT FROM ALERT SUMMARY AGENT>" + } +} +``` + +## 生成警报摘要 + +您可以通过调用 `/api/assistant/summary` API 端点来生成警报摘要。要生成警报摘要,`index`、`dsl` 和 `topNLogPatternData` 字段是可选的。如果提供了所有三个字段,代理将提供带有日志模式分析的摘要;否则,它将提供一般摘要: + +```json +POST /api/assistant/summary +{ + "summaryType": "alerts", + "question": "Please summarize this alert, do not use any tool.", + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "index": "loghub-apache-new", + "dsl": "{\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}", + "topNLogPatternData": "[[539,["[Sun Dec 04 07:12:44 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 06:19:18 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:59:47 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:11:22 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:31:12 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 05:04:04 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 20:24:49 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 06:16:23 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 20:47:17 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 06:30:43 2005] [error] mod_jk child workerEnv in error state 6","[Mon Dec 05 06:35:27 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 07:07:30 2005] [error] mod_jk child workerEnv in error state 8","[Sun Dec 04 07:18:00 2005] [error] mod_jk child workerEnv in error state 7","[Sun Dec 04 16:32:56 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 17:01:47 2005] [error] mod_jk child workerEnv in error state 6","[Sun Dec 04 16:52:49 2005] [error] mod_jk child workerEnv in error state 8"],"[ :: ] [] _ "],[32,["[Sun Dec 04 14:29:00 2005] [error] [client 4.245.93.87] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 08:54:17 2005] [error] [client 147.31.138.75] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:34:57 2005] [error] [client 61.138.216.82] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 07:45:45 2005] [error] [client 63.13.186.196] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 10:53:30 2005] [error] [client 218.76.139.20] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:48:48 2005] [error] [client 67.166.248.235] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:18:36 2005] [error] [client 67.154.58.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 01:30:32 2005] [error] [client 211.62.201.48] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 16:45:04 2005] [error] [client 216.216.185.130] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 17:31:39 2005] [error] [client 218.75.106.250] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:00:56 2005] [error] [client 68.228.3.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 19:14:09 2005] [error] [client 61.220.139.68] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 09:35:12 2005] [error] [client 207.203.80.15] Directory index forbidden by rule: /var/www/html/","[Mon Dec 05 10:28:44 2005] [error] [client 198.232.168.9] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 16:24:05 2005] [error] [client 58.225.62.140] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 17:53:43 2005] [error] [client 218.39.132.175] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 12:33:13 2005] [error] [client 208.51.151.210] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 15:59:01 2005] [error] [client 24.83.37.136] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 11:42:43 2005] [error] [client 216.127.124.16] Directory index forbidden by rule: /var/www/html/","[Sun Dec 04 05:15:09 2005] [error] [client 222.166.160.184] Directory index forbidden by rule: /var/www/html/"],"[ :: ] [] [ ...] : ////"],[12,["[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:17 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 20:47:16 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 07:57:02 2005] [error] mod_jk child init 1 -2","[Sun Dec 04 17:43:12 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2","[Mon Dec 05 11:06:52 2005] [error] mod_jk child init 1 -2"],"[ :: ] [] _ -"]]" +} +``` + +下表描述了 Assistant Summary API 参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`summaryType` | 必需 | 指定调用此 API 的应用程序类型。对于警报洞察,使用 `alerts`。 +`question` | 必需 | 指定用户关于警报洞察的问题。默认值为 `Please summarize this alert, do not use any tool.` +`context` | 必需 | 提供警报的上下文,包括警报监视器定义、活动警报和触发值。 +`index` | 可选 | 警报监视的索引。如果不提供此参数,则不返回日志模式分析。 +`dsl` | 可选 | 用于警报监控的 DSL 查询。如果不提供此参数,则不返回日志模式分析。 +`topNLogPatternData` | 可选 | 警报触发数据的日志模式。如果不提供此参数,则不返回日志模式分析。 + +## 生成警报洞察 + +您可以通过调用 `/api/assistant/insight` API 端点来生成警报洞察。要生成警报洞察,以下所有参数都是必需的: + +```json +POST /api/assistant/insight +{ + "summaryType": "alerts", + "insightType": "user_insight" + "context": "\n Here is the detail information about alert Error log over 100\n ### Monitor definition\n {\"type\":\"monitor\",\"schema_version\":8,\"name\":\"loghub-apache-error-log\",\"monitor_type\":\"query_level_monitor\",\"enabled\":false,\"enabled_time\":null,\"schedule\":{\"period\":{\"interval\":1,\"unit\":\"MINUTES\"}},\"inputs\":[{\"search\":{\"indices\":[\"loghub-apache-new\"],\"query\":{\"size\":0,\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"10/12/24 11:21 am CST||-1000000h\",\"to\":\"10/12/24 11:21 am CST\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}}}],\"triggers\":[{\"query_level_trigger\":{\"id\":\"NAq7fpIBRJyww-JMjwP_\",\"name\":\"Error log over 100\",\"severity\":\"1\",\"condition\":{\"script\":{\"source\":\"ctx.results[0].hits.total.value > 100\",\"lang\":\"painless\"}},\"actions\":[]}}],\"last_update_time\":1728714554388,\"owner\":\"alerting\",\"associated_workflows\":[],\"associatedCompositeMonitorCnt\":0,\"item_type\":\"query_level_monitor\",\"id\":\"NQq7fpIBRJyww-JMkAMC\",\"version\":3}\n\n ### Active Alert\n {\"ACTIVE\":1,\"ACKNOWLEDGED\":0,\"ERROR\":0,\"total\":1,\"alerts\":[{\"id\":\"Wgq8fpIBRJyww-JMegNr\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"workflow_id\":\"\",\"workflow_name\":\"\",\"associated_alert_ids\":[],\"schema_version\":5,\"monitor_version\":1,\"monitor_name\":\"loghub-apache-error-log\",\"execution_id\":\"NQq7fpIBRJyww-JMkAMC_2024-10-12T03:18:54.311214115_22d189ce-5e93-4927-b8bb-bcf61b7537e3\",\"trigger_id\":\"NAq7fpIBRJyww-JMjwP_\",\"trigger_name\":\"Error log over 100\",\"finding_ids\":[],\"related_doc_ids\":[],\"state\":\"ACTIVE\",\"error_message\":null,\"alert_history\":[],\"severity\":\"1\",\"action_execution_results\":[],\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"end_time\":null,\"acknowledged_time\":null,\"alert_source\":\"monitor\"}],\"trigger_name\":\"Error log over 100\",\"severity\":\"1\",\"start_time\":\"10/12/24 11:18 am CST\",\"last_notification_time\":\"10/12/24 11:21 am CST\",\"monitor_name\":\"loghub-apache-error-log\",\"monitor_id\":\"NQq7fpIBRJyww-JMkAMC\",\"alert_source\":\"monitor\",\"triggerID\":\"NAq7fpIBRJyww-JMjwP_\"}\n\n ### Value triggers this alert\n 595\n\n ### Alert query DSL {\"query\":{\"bool\":{\"filter\":[{\"range\":{\"Time\":{\"from\":\"2024-10-12T03:21:54+00:00||-1000000h\",\"to\":\"2024-10-12T03:21:54+00:00\",\"include_lower\":true,\"include_upper\":true,\"boost\":1}}},{\"term\":{\"Level\":{\"value\":\"error\",\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}} \n", + "question": "Please provide your insight on this alerts.", + "summary": <OUTPUT FROM ALERT SUMMARY AGENT> +} +``` + +下表描述了 Assistant Insight API 参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`summaryType` | 必需 | 指定调用此 API 的应用程序类型。对于警报洞察,使用 `alerts`。 +`insightType` | 必需 | 定义警报类型。对于集群指标警报使用 `os_insight`,对于其他警报类型使用 `user_insight`。 +`question` | 必需 | 指定用户关于警报洞察的问题。默认值为 `Please provide your insight on this alerts.` +`context` | 必需 | 提供警报的上下文,包括警报监视器定义、活动警报和触发值。 +`summary` | 必需 | 警报摘要代理返回的结果。 + +## 在 OpenSearch Dashboards 中查看警报洞察 + +在查看警报洞察之前,您必须在 OpenSearch Dashboards 中配置警报。有关更多信息,请参阅[警报](/observing-your-data/alerting/)。 + +要在 OpenSearch Dashboards 中查看警报洞察,请使用以下步骤: + +1. 在顶部菜单栏上,转到 **OpenSearch 插件 > 警报**。显示所有警报。 + +1. 将鼠标悬停在所需监视器的警报上。如果您配置了警报洞察,您将在**警报**列中的警报旁边看到一个闪光图标 (闪光图标),如下图所示。 + + *带有闪光图标的警报页面* + +1. 选择警报标签或闪光图标。您将看到生成的摘要,如下图所示。 + + *警报摘要* + +1. 选择信息图标 (<img src="/images/icons/info-icon.png" class="inline-icon" alt="信息图标"/>) 以查看警报洞察。您将看到生成的警报洞察,如下图所示。 + + *警报洞察* diff --git a/i18n/zh/dashboards/dashboards-assistant/data-summary.md b/i18n/zh/dashboards/dashboards-assistant/data-summary.md new file mode 100644 index 00000000..71d28cfb --- /dev/null +++ b/i18n/zh/dashboards/dashboards-assistant/data-summary.md @@ -0,0 +1,211 @@ +--- +title: 数据摘要 +--- + +# 数据摘要 + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +OpenSearch Dashboards Assistant 数据摘要功能使用大型语言模型 (LLM) 帮助您为存储在 OpenSearch 索引中的数据生成摘要。此工具提供了一种从大型数据集获取洞察的高效方式,使您更容易理解和处理 OpenSearch 索引中包含的信息。 + +## 配置 + +要配置数据摘要功能,请使用以下步骤。 + +### 前提条件 + +在使用数据摘要功能之前,请按以下方式在 OpenSearch Dashboards 中启用查询增强: + +1. 在顶部菜单栏上,转到**管理 > Dashboards 管理**。 +1. 在左侧导航窗格中,选择**高级设置**。 +1. 在设置页面上,将**启用查询增强**切换为**开启**。 + +### 步骤 1: 启用数据摘要功能 + +要启用数据摘要功能,请配置以下 `opensearch_dashboards.yml` 设置: + +```yaml +queryEnhancements.queryAssist.summary.enabled: true +``` + +### 步骤 2: 创建数据摘要代理 + +要编排数据摘要,请创建一个数据摘要[代理](/ml-commons-plugin/agents-tools/agents/)。要创建代理,请发送 `POST /_plugins/_flow_framework/workflow?provision=true` 请求并提供代理模板作为负载: + +<details markdown="block"> + <summary> + 请求 + </summary> + +```json +POST /_plugins/_flow_framework/workflow?provision=true +{ + "name": "Query Assist Agent", + "description": "Create a Query Assist Agent using Claude on BedRock", + "use_case": "REGISTER_AGENT", + "version": { + "template": "1.0.0", + "compatibility": ["2.13.0", "3.0.0"] + }, + "workflows": { + "provision": { + "user_params": {}, + "nodes": [ + { + "id": "create_claude_connector", + "type": "create_connector", + "previous_node_inputs": {}, + "user_inputs": { + "version": "1", + "name": "Claude Sonnet 4.6 runtime Connector", + "protocol": "aws_sigv4", + "description": "The connector to BedRock service for Claude model", + "actions": [ + { + "headers": { + "x-amz-content-sha256": "required", + "content-type": "application/json" + }, + "method": "POST", + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.prompt}\"}]}],\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens},\"temperature\":${parameters.temperature}}", + "action_type": "predict", + "url": "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke" + } + ], + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "parameters": { + "region": "us-west-2", + "endpoint": "bedrock-runtime.us-west-2.amazonaws.com", + "content_type": "application/json", + "auth": "Sig_V4", + "max_tokens": "8000", + "service_name": "bedrock", + "temperature": "0.0001", + "response_filter": "$.content[0].text", + "anthropic_version": "bedrock-2023-05-31" + } + } + }, + { + "id": "register_claude_model", + "type": "register_remote_model", + "previous_node_inputs": { + "create_claude_connector": "connector_id" + }, + "user_inputs": { + "description": "Claude model", + "deploy": true, + "name": "claude-sonnet-4-6" + } + }, + { + "id": "create_query_assist_data_summary_ml_model_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You are an assistant that helps to summarize the data and provide data insights.\nThe data are queried from OpenSearch index through user's question which was translated into PPL query.\nHere is a sample PPL query: `source=<index> | where <field> = <value>`.\nNow you are given ${parameters.sample_count} sample data out of ${parameters.total_count} total data.\nThe user's question is `${parameters.question}`, the translated PPL query is `${parameters.ppl}` and sample data are:\n```\n${parameters.sample_data}\n```\nCould you help provide a summary of the sample data and provide some useful insights with precise wording and in plain text format, do not use markdown format.\nYou don't need to echo my requirements in response." + }, + "name": "MLModelTool", + "type": "MLModelTool" + } + }, + { + "id": "create_query_assist_data_summary_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_query_assist_data_summary_ml_model_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "Query Assist Data Summary Agent", + "description": "this is an query assist data summary agent" + } + } + ] + } + } +} +``` + +</details> + +有关示例代理模板,请参阅 [Flow Framework 示例模板](https://github.com/opensearch-project/flow-framework/tree/2.x/sample-templates)。记下代理 ID;您将在以下步骤中使用它。 + +### 步骤 3: 创建根代理 + +接下来,为上一步创建的数据摘要代理创建[根代理](/vector-search/ai-search/workflows/workflow-tutorial/#root_agent): + +```json +POST /.plugins-ml-config/_doc/os_data2summary +{ + "type": "os_root_agent", + "configuration": { + "agent_id": "<DATA_SUMMARY_AGENT_ID>" + } +} +``` + +::: danger WARNING +此示例演示了系统索引。在启用安全的域中,只有超级管理员有权执行此代码。有关进行超级管理员调用的信息,请参阅[系统索引](/security/configuration/system-indices)。有关访问权限,请联系您的系统管理员。 +::: + +### 步骤 4: 测试代理 + +您可以通过使用示例负载调用代理来验证数据摘要代理是否创建成功: + +```json +POST /_plugins/_ml/agents/{DATA_SUMMARY_AGENT_ID}/_execute +{ + "parameters": { + "sample_data":"'[{\"_index\":\"90943e30-9a47-11e8-b64d-95841ca0b247\",\"_source\":{\"referer\":\"http://twitter.com/success/gemini-9a\",\"request\":\"/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\",\"extension\":\"deb\",\"memory\":null,\"ip\":\"239.67.210.53\",\"index\":\"opensearch_dashboards_sample_data_logs\",\"message\":\"239.67.210.53 - - [2018-08-30T15:29:01.686Z] \\\"GET /beats/metricbeat/metricbeat-6.3.2-amd64.deb HTTP/1.1\\\" 404 2633 \\\"-\\\" \\\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\\\"\",\"url\":\"https://artifacts.opensearch.org/downloads/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"tags\":\"success\",\"geo\":{\"srcdest\":\"CN:PL\",\"src\":\"CN\",\"coordinates\":{\"lat\":44.91167028,\"lon\":-108.4455092},\"dest\":\"PL\"},\"utc_time\":\"2024-09-05 15:29:01.686\",\"bytes\":2633,\"machine\":{\"os\":\"win xp\",\"ram\":21474836480},\"response\":\"404\",\"clientip\":\"239.67.210.53\",\"host\":\"artifacts.opensearch.org\",\"event\":{\"dataset\":\"sample_web_logs\"},\"phpmemory\":null,\"timestamp\":\"2024-09-05 15:29:01.686\"}}]'", + "sample_count":1, + "total_count":383, + "question":"Are there any errors in my logs?", + "ppl":"source=opensearch_dashboards_sample_data_logs| where QUERY_STRING(['response'], '4* OR 5*')"} +} +``` + +## 生成数据摘要 + +您可以通过调用 `/api/assistant/data2summary` API 端点来生成数据摘要。`sample_count`、`total_count`、`question` 和 `ppl` 参数是可选的: + +```json +POST /api/assistant/data2summary +{ + "sample_data":"'[{\"_index\":\"90943e30-9a47-11e8-b64d-95841ca0b247\",\"_source\":{\"referer\":\"http://twitter.com/success/gemini-9a\",\"request\":\"/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"agent\":\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\",\"extension\":\"deb\",\"memory\":null,\"ip\":\"239.67.210.53\",\"index\":\"opensearch_dashboards_sample_data_logs\",\"message\":\"239.67.210.53 - - [2018-08-30T15:29:01.686Z] \\\"GET /beats/metricbeat/metricbeat-6.3.2-amd64.deb HTTP/1.1\\\" 404 2633 \\\"-\\\" \\\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\\\"\",\"url\":\"https://artifacts.opensearch.org/downloads/beats/metricbeat/metricbeat-6.3.2-amd64.deb\",\"tags\":\"success\",\"geo\":{\"srcdest\":\"CN:PL\",\"src\":\"CN\",\"coordinates\":{\"lat\":44.91167028,\"lon\":-108.4455092},\"dest\":\"PL\"},\"utc_time\":\"2024-09-05 15:29:01.686\",\"bytes\":2633,\"machine\":{\"os\":\"win xp\",\"ram\":21474836480},\"response\":\"404\",\"clientip\":\"239.67.210.53\",\"host\":\"artifacts.opensearch.org\",\"event\":{\"dataset\":\"sample_web_logs\"},\"phpmemory\":null,\"timestamp\":\"2024-09-05 15:29:01.686\"}}]'", + "sample_count":1, + "total_count":383, + "question":"Are there any errors in my logs?", + "ppl":"source=opensearch_dashboards_sample_data_logs| where QUERY_STRING(['response'], '4* OR 5*')" +} +``` + +下表描述了 Assistant 数据摘要 API 参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`sample_data` | 必需 | 由指定查询返回的数据样本,用作摘要的输入。 +`question` | 可选 | 用户关于数据的自然语言问题,用于指导摘要生成。 +`ppl` | 可选 | 用于检索数据的管道处理语言 (PPL) 查询;在查询辅助中,这是由 LLM 使用用户的自然语言问题生成的。 +`sample_count` | 可选 | 包含在 sample_data 中的条目数。 +`total_count` | 可选 | 完整查询结果集中的条目总数。 + +## 在 OpenSearch Dashboards 中查看数据摘要 + +要在 OpenSearch Dashboards 中查看警报洞察,请使用以下步骤: + +1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > 发现**。 + +1. 从查询语言下拉列表中,选择 **PPL**。您将在查询文本后看到生成的数据摘要,如下图所示。 + + *数据摘要* diff --git a/i18n/zh/dashboards/dashboards-assistant/suggest-anomaly-detector.md b/i18n/zh/dashboards/dashboards-assistant/suggest-anomaly-detector.md new file mode 100644 index 00000000..b1d20927 --- /dev/null +++ b/i18n/zh/dashboards/dashboards-assistant/suggest-anomaly-detector.md @@ -0,0 +1,84 @@ +--- +title: 异常检测器建议 +--- + +# 异常检测器建议 + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +OpenSearch Dashboards Assistant 可以使用大型语言模型 (LLM) 建议创建异常检测器。LLM 分析 OpenSearch 索引中的数据模式,并为异常检测器推荐配置设置,使您更容易识别数据中的异常活动或趋势。 + +## 配置 + +要配置异常检测器建议,请使用以下步骤。 + +### 前提条件 + +在使用异常检测器建议之前,请按以下方式在 OpenSearch Dashboards 中启用查询增强: + +1. 在顶部菜单栏上,转到**管理 > Dashboards 管理**。 +1. 在左侧导航窗格中,选择**高级设置**。 +1. 在设置页面上,将**启用查询增强**切换为**开启**。 + +### 步骤 1: 启用异常检测器建议 + +要启用异常检测器建议,请配置以下 `opensearch_dashboards.yml` 设置: + +```yaml +assistant.smartAnomalyDetector.enabled: true +``` + +### 步骤 2: 创建异常检测器建议代理 + +要编排异常检测器建议,请创建一个异常检测器建议[代理](/ml-commons-plugin/agents-tools/agents/)。要创建代理,请发送 `POST /_plugins/_flow_framework/workflow?provision=true` 请求并提供代理模板作为负载。有关更多信息,请参阅[配置 OpenSearch Assistant](/dashboards/dashboards-assistant/#configuring-opensearch-assistant)。 + +有关示例代理模板,请参阅 [Flow Framework 示例模板](https://github.com/opensearch-project/flow-framework/tree/2.x/sample-templates)。记下代理 ID;您将在以下步骤中使用它。 + +### 步骤 3: 配置代理 + +接下来,配置上一步创建的异常检测器建议代理: + +```json +POST /.plugins-ml-config/_doc/os_suggest_ad +{ + "type": "suggest_anomaly_detector_agent", + "configuration": { + "agent_id": "<SUGGEST_ANOMALY_DETECTOR_AGENT_ID>" + } +} +``` + +::: danger WARNING +此示例演示了系统索引。在启用安全的域中,只有超级管理员有权执行此代码。有关进行超级管理员调用的信息,请参阅[系统索引](/security/configuration/system-indices)。有关访问权限,请联系您的系统管理员。 +::: + +### 步骤 4: 测试代理 + +您可以通过使用示例负载调用代理来验证代理是否创建成功: + +```json +POST /_plugins/_ml/agents/{SUGGEST_ANOMALY_DETECTOR_AGENT_ID}/_execute +{ + "parameters": { + "index":"sample_weblogs_test" + } +} +``` + +## 在 OpenSearch Dashboards 中查看异常检测器建议 + +要在 OpenSearch Dashboards 中查看异常检测器建议,请使用以下步骤: + +1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > 发现**。 + +1. 从索引模式下拉列表中,选择一个索引模式。 + +1. 选择 **AI 助手**下拉列表,然后选择**建议异常检测器**,如下图所示。 + + *点击建议异常检测器操作* + +1. 等待 LLM 填充将用于为索引模式创建异常检测器的**建议异常检测器**字段。然后选择**创建检测器**按钮创建异常检测器,如下图所示。 + + *建议的异常检测器* diff --git a/i18n/zh/dashboards/dashboards-assistant/text-to-visualization.md b/i18n/zh/dashboards/dashboards-assistant/text-to-visualization.md new file mode 100644 index 00000000..01c403c1 --- /dev/null +++ b/i18n/zh/dashboards/dashboards-assistant/text-to-visualization.md @@ -0,0 +1,272 @@ +--- +title: 文本到可视化 +--- + +# 文本到可视化 + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +OpenSearch Dashboards Assistant 可以使用自然语言指令创建可视化。 + +## 配置 + +要配置文本到可视化,请使用以下步骤。 + +### 步骤 1: 启用文本到可视化 + +要启用文本到可视化,请配置以下 `opensearch_dashboards.yml` 设置: + +```yaml +assistant.text2viz.enabled: true +``` + +### 步骤 2: 创建代理 + +要编排文本到可视化,您需要创建必要的[代理](/ml-commons-plugin/agents-tools/agents/)。通过发送以下请求创建用于创建所有必要文本到可视化代理的工作流模板: + +<details markdown="block"> + <summary> + 请求 + </summary> + +```json +POST /_plugins/_flow_framework/workflow +{ + "name": "Text to visualization agents", + "description": "This template is to create all Agents required for text to visualization", + "use_case": "REGISTER_AGENTS", + "version": { + "template": "1.0.0", + "compatibility": [ + "2.18.0", + "3.0.0" + ] + }, + "workflows": { + "provision": { + "user_params": {}, + "nodes": [ + { + "id": "create_claude_connector", + "type": "create_connector", + "previous_node_inputs": {}, + "user_inputs": { + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "parameters": { + "endpoint": "bedrock-runtime.us-east-1.amazonaws.com", + "content_type": "application/json", + "auth": "Sig_V4", + "max_tokens_to_sample": "8000", + "service_name": "bedrock", + "temperature": "0.0000", + "response_filter": "$.content[0].text", + "region": "us-east-1", + "anthropic_version": "bedrock-2023-05-31" + }, + "version": "1", + "name": "Claude Sonnet 4.6 runtime Connector", + "protocol": "aws_sigv4", + "description": "The connector to BedRock service for claude model", + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.prompt}\"}]}],\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens_to_sample}}" + } + ] + } + }, + { + "id": "register_claude_model", + "type": "register_remote_model", + "previous_node_inputs": { + "create_claude_connector": "connector_id" + }, + "user_inputs": { + "name": "claude-sonnet-4-6", + "description": "Claude model", + "deploy": true + } + }, + { + "id": "create_t2vega_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You're an expert at creating vega-lite visualization. No matter what the user asks, you should reply with a valid vega-lite specification in json.\nYour task is to generate Vega-Lite specification in json based on the given sample data, the schema of the data, the PPL query to get the data and the user's input.\nLet's start from dimension and metric/date. Now I have a question, I already transfer it to PPL and query my Opensearch cluster. \nThen I get data. For the PPL, it will do aggregation like \"stats AVG(field_1) as avg, COUNT(field_2) by field_3, field_4, field_5\". \nIn this aggregation, the metric is [avg, COUNT(field_2)] , and then we judge the type of field_3,4,5. If only field_5 is type related to date, the dimension is [field_3, field_4], and date is [field_5]\nFor example, stats SUM(bytes) by span(timestamp, 1w), machine.os, response, then SUM(bytes) is metric and span(timestamp, 1w) is date, while machine.os, response are dimensions.\nNotice: Some fields like 'span()....' will be the date, but not metric and dimension. \nAnd one field will only count once in dimension count. You should always pick field name from schema\nTo summarize,\nA dimension is a categorical variable that is used to group, segment, or categorize data. It is typically a qualitative attribute that provides context for metrics and is used to slice and dice data to see how different categories perform in relation to each other.\nThe dimension is not date related fields. The dimension and date are very closed. The only difference is date is related to datetime, while dimension is not.\nA metric is a quantitative measure used to quantify or calculate some aspect of the data. Metrics are numerical and typically represent aggregated values like sums, averages, counts, or other statistical calculations.\n\nIf a ppl doesn't have aggregation using 'stats', then each field in output is dimension.\nOtherwise, if a ppl use aggregation using 'stats' but doesn't group by using 'by', then each field in output is metric.\n\nThen for each given PPL, you could give the metric and dimension and date. One field will in only one of the metric, dimension or date.\n\nThen according to the metric number and dimension number of PPL result, you should first format the entrance code by metric_number, dimension_number, and date_number. For example, if metric_number = 1, dimension_number = 2, date_number=1, then the entrance code is 121.\nI define several use case categories here according to the entrance code.\nFor each category, I will define the entrance condition (number of metric and dimension)\nI will also give some defined attribute of generated vega-lite. Please refer to it to generate vega-lite.\n\nType 1:\nEntrance code: <1, 1, 0>\nDefined Attributes:\n {\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<metric name>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<dimension name>\",\n \"type\": \"nominal\"\n }\n },\n }\n\nType 2:\nEntrance code: <1, 2, 0>\nDefined Attributes:\n{\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n },\n \"color\": {\n \"field\": \"<dimension 2>\",\n \"type\": \"nominal\"\n }\n }\n }\n\n\nType 3\nEntrance code: <3, 1, 0>\nDefined Attributes:\n{\n \"mark\": \"point\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<metric 2>\",\n \"type\": \"quantitative\"\n },\n \"size\": {\n \"field\": \"<metric 3>\",\n \"type\": \"quantitative\"\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n}\n\nType 4\nEntrance code: <2, 1, 0>\nDefined Attributes:\n{\n \"mark\": \"point\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<mtric 1>\",\n \"type\": \"quantitative\"\n },\n \"y\": {\n \"field\": \"<metric 2>\",\n \"type\": \"quantitative\"\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n}\n\nType 5:\nEntrance code: <2, 1, 1>\nDefined Attributes:\n{\n \"layer\": [\n {\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 1 name>\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n },\n {\n \"mark\": {\n \"type\": \"line\",\n \"color\": \"red\"\n },\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"<metric 2>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 2 name>\",\n \"orient\": \"right\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\"\n }\n }\n }\n ],\n \"resolve\": {\n \"scale\": {\n \"y\": \"independent\"\n }\n }\n }\n\nType 6:\nEntrance code: <2, 0, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"layer\": [\n {\n \"mark\": \"area\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 1 name>\"\n }\n }\n }\n },\n {\n \"mark\": {\n \"type\": \"line\",\n \"color\": \"black\"\n },\n \"encoding\": {\n \"x\": {\n \"field\": \"date\",\n \"type\": \"temporal\"\n },\n \"y\": {\n \"field\": \"metric 2\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 2 name>\",\n \"orient\": \"right\"\n }\n }\n }\n }\n ],\n \"resolve\": {\n \"scale\": {\n \"y\": \"independent\"\n }\n }\n }\n \nType 7:\nEntrance code: <1, 0, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"line\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\",\n \"axis\": {\n \"title\": \"<date name>\"\n }\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric name>\"\n }\n }\n }\n }\n\nType 8:\nEntrance code: <1, 1, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"line\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\",\n \"axis\": {\n \"title\": \"<date name>\"\n }\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric name>\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\",\n \"legend\": {\n \"title\": \"<dimension name>\"\n }\n }\n }\n }\n\nType 9:\nEntrance code: <1, 2, 1>\nDefined Attributes:\n{\n \"title\": \"<title>\",\n \"description\": \"<description>\",\n \"mark\": \"line\",\n \"encoding\": {\n \"x\": {\n \"field\": \"<date 1>\",\n \"type\": \"temporal\",\n \"axis\": {\n \"title\": \"<date name>\"\n }\n },\n \"y\": {\n \"field\": \"<metric 1>\",\n \"type\": \"quantitative\",\n \"axis\": {\n \"title\": \"<metric 1>\"\n }\n },\n \"color\": {\n \"field\": \"<dimension 1>\",\n \"type\": \"nominal\",\n \"legend\": {\n \"title\": \"<dimension 1>\"\n }\n },\n \"facet\": {\n \"field\": \"<dimension 2>\",\n \"type\": \"nominal\",\n \"columns\": 2\n }\n }\n }\n\nType 10:\nEntrance code: all other code\nAll others type.\nUse a table to show the result\n\n\nBesides, here are some requirements:\n1. Do not contain the key called 'data' in vega-lite specification.\n2. If mark.type = point and shape.field is a field of the data, the definition of the shape should be inside the root \"encoding\" object, NOT in the \"mark\" object, for example, {\"encoding\": {\"shape\": {\"field\": \"field_name\"}}}\n3. Please also generate title and description\n\nThe sample data in json format:\n${parameters.sampleData}\n\nThis is the schema of the data:\n${parameters.dataSchema}\n\nThe user used this PPL query to get the data: ${parameters.ppl}\n\nThe user's question is: ${parameters.input_question}\n\nNotice: Some fields like 'span()....' will be the date, but not metric and dimension. \nAnd one field will only count once in dimension count. You should always pick field name from schema.\n And when you code is <2, 1, 0>, it belongs type 4.\n And when you code is <1, 2, 0>, it belongs type 9.\n\n\nNow please reply a valid vega-lite specification in json based on above instructions.\nPlease return the number of dimension, metric and date. Then choose the type. \nPlease also return the type.\nFinally return the vega-lite specification according to the type.\nPlease make sure all the key in the schema matches the word I given. \nYour answer format should be:\nNumber of metrics:[list the metric name here, Don't use duplicate name] <number of metrics {a}> \nNumber of dimensions:[list the dimension name here] <number of dimension {b}> \nNumber of dates:[list the date name here] <number of dates {c}> \nThen format the entrance code by: <Number of metrics, Number of dimensions, Number of dates>\nType and its entrance code: <type number>: <its entrance code>\nThen apply the vega-lite requirements of the type.\n<vega-lite> {here is the vega-lite json} </vega-lite>\n\nAnd don't use 'transformer' in your vega-lite and wrap your vega-lite json in <vega-lite> </vega-lite> tags\n" + }, + "name": "Text2Vega", + "type": "MLModelTool" + } + }, + { + "id": "create_instruction_based_t2vega_tool", + "type": "create_tool", + "previous_node_inputs": { + "register_claude_model": "model_id" + }, + "user_inputs": { + "parameters": { + "prompt": "You're an expert at creating vega-lite visualization. No matter what the user asks, you should reply with a valid vega-lite specification in json.\nYour task is to generate Vega-Lite specification in json based on the given sample data, the schema of the data, the PPL query to get the data and the user's input.\n\nBesides, here are some requirements:\n1. Do not contain the key called 'data' in vega-lite specification.\n2. If mark.type = point and shape.field is a field of the data, the definition of the shape should be inside the root \"encoding\" object, NOT in the \"mark\" object, for example, {\"encoding\": {\"shape\": {\"field\": \"field_name\"}}}\n3. Please also generate title and description\n\nThe sample data in json format:\n${parameters.sampleData}\n\nThis is the schema of the data:\n${parameters.dataSchema}\n\nThe user used this PPL query to get the data: ${parameters.ppl}\n\nThe user's input question is: ${parameters.input_question}\nThe user's instruction on the visualization is: ${parameters.input_instruction}\n\nNow please reply a valid vega-lite specification in json based on above instructions.\nPlease only contain vega-lite in your response.\n" + }, + "name": "Text2Vega", + "type": "MLModelTool" + } + }, + { + "id": "t2vega_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_t2vega_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "t2vega agent", + "description": "this is the t2vega agent that has a set of rules to generate the visualizations" + } + }, + { + "id": "t2vega_instruction_based_agent", + "type": "register_agent", + "previous_node_inputs": { + "create_instruction_based_t2vega_tool": "tools" + }, + "user_inputs": { + "parameters": {}, + "type": "flow", + "name": "t2vega instruction based agent", + "description": "this is the t2vega agent that supports instructions" + } + } + ] + } + } +} +``` + +</details> + +使用响应中返回的工作流 ID 来配置资源: + +```json +POST /_plugins/_flow_framework/workflow/{workflow_id}/_provision +``` + +要查看工作流的状态和所有创建的资源,请发送以下请求: + +```json +GET /_plugins/_flow_framework/workflow/{workflow_id}/_status +``` + +### 步骤 3: 配置根代理 + +接下来,为文本到可视化配置根代理: + +```json +POST /.plugins-ml-config/_doc/os_text2vega +{ + "type": "os_chat_root_agent", + "configuration": { + "agent_id": "<ROOT_AGENT_ID>" + } +} +``` + +配置代理以接收用户创建可视化的指令: + +```json +POST /.plugins-ml-config/_doc/os_text2vega_with_instructions +{ + "type": "os_chat_root_agent", + "configuration": { + "agent_id": "<ROOT_AGENT_ID>" + } +} +``` + +::: danger WARNING +此示例演示了系统索引。在启用安全的域中,只有超级管理员有权执行此代码。有关进行超级管理员调用的信息,请参阅[系统索引](/security/configuration/system-indices)。有关访问权限,请联系您的系统管理员。 +::: + +### 步骤 4: 测试代理 + +您可以通过使用示例负载调用代理来验证代理是否创建成功: + +```json +POST /_plugins/_ml/agents/{ROOT_AGENT_ID}/_execute +{ + "parameters": { + "input_question": "find unique visitors and average bytes every 3 hours", + "input_instruction": "display with different layers, use independent scale for different layers, display unique visitors with light blue bar chart", + "ppl": "source=opensearch_dashboards_sample_data_ecommerce| stats DISTINCT_COUNT(user) as unique_visitors, AVG(taxful_total_price) as avg_bytes by span(order_date, 3h)", + "sampleData": """[{\"unique_visitors\":15,\"avg_bytes\":90.98684210526316,\"span(order_date,3h)\":\"2024-04-25 00:00:00\"},{\"unique_visitors\":14,\"avg_bytes\":72.72083333333333,\"span(order_date,3h)\":\"2024-04-25 03:00:00\"}]""", + "dataSchema": """[{\"name\":\"unique_visitors\",\"type\":\"integer\"},{\"name\":\"avg_bytes\",\"type\":\"double\"},{\"name\":\"span(order_date,3h)\",\"type\":\"timestamp\"}]""" + } +} +``` + +## 从文本生成可视化 + +您可以通过调用 `/api/assistant/text2vega` API 端点从文本生成可视化。`input_instruction` 参数是可选的: + +```json +POST /api/assistant/text2vega +{ + "input_instruction": "<input_instruction>", + "input_question": "<input_question>", + "ppl": "<ppl_query>", + "dataSchema": "<data_schema_of_ppl_response>", + "sampleData": "<sample_data_of_ppl_response>" +} +``` + +下表描述了文本到可视化 API 参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`input_question` | 必需 | 用户用于生成相应管道处理语言 (PPL) 查询的原始问题。 +`ppl` | 必需 | 生成的 PPL 查询,用于检索可视化所需的数据。 +`dataSchema` | 必需 | 描述可视化输出中数据字段的结构和类型,基于 PPL 响应。 +`sampleData` | 必需 | 提供将填充可视化的数据样本条目。 +`input_instruction` | 可选 | 指定可视化的样式说明,例如颜色。 + +## 在 OpenSearch Dashboards 中从文本生成可视化 + +要在 OpenSearch Dashboards 中从文本生成可视化,请使用以下步骤: + +1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > 可视化**,然后选择**创建可视化**。 + +1. 在**新建可视化**对话框中,选择**自然语言**,如下图所示。 + + *通过选择自然语言创建可视化* + +1. 从数据源下拉列表中,选择一个数据源,如下图所示。 + + *通过选择自然语言创建可视化* + +1. 在右上角的文本框中,使用自然语言输入问题。将生成新的可视化,如下图所示。 + + *通过选择自然语言创建可视化* + +1. 要修改生成的可视化,选择**编辑可视化**。在**编辑可视化**对话框中,输入所需的修改,然后选择**应用**,如下图所示。 + + *通过选择自然语言创建可视化* + + 可视化已更新,如下图所示。 + + *通过选择自然语言创建可视化* diff --git a/i18n/zh/dashboards/dev-tools/console.md b/i18n/zh/dashboards/dev-tools/console.md new file mode 100644 index 00000000..2e3a27da --- /dev/null +++ b/i18n/zh/dashboards/dev-tools/console.md @@ -0,0 +1,189 @@ +--- +title: 控制台 +--- + +# 开发工具控制台 + +使用**开发工具**中的**控制台**选项卡向 OpenSearch 发送 REST API 请求,包括 [Query DSL](/query-dsl/) 搜索查询、索引管理操作和集群管理命令。 + +控制台支持所有 OpenSearch REST API。例如,您可以使用控制台执行以下常见操作: + +- 使用 [`match`](/query-dsl/full-text/match)、[`term`](/query-dsl/term/term)、[`range`](/query-dsl/term/range) 和其他查询类型搜索文档。 +- 使用 [`match_all`](/query-dsl/match-all) 查询从索引中检索所有文档。 +- 使用 [`_count`](/api-reference/search-apis/count) 端点计算匹配文档的数量而不检索它们。 +- 使用[聚合](/aggregations/)计算数据的指标、统计数据和摘要。 +- 通过[将查询与过滤器组合](/query-dsl/query-filter-context)来缩小搜索结果范围。 + +## 编写和发送请求 + +在控制台左侧的编辑器窗格中编写查询。例如,输入以下请求,将一个文档索引到 `students` 索引中: + +```json +PUT students/_doc/1 +{ + "name": "John Doe", + "gpa": 3.89, + "grad_year": 2022 +} +``` + +::: tip TIP +对于长查询,您可以通过选择行号旁边的小三角形来折叠和展开查询的部分。 +::: + +要向 OpenSearch 发送查询,请通过将光标放在查询文本中的任意位置来选择查询。然后选择请求右上角的播放图标 (<img src="/images/dev-tools/play-icon.png" class="inline-icon" alt="播放图标"/>) 或按 `Ctrl/Cmd+Enter`,如下图所示。 + +![发送请求](/images/dev-tools/dev-tools-send.png) + +OpenSearch 在控制台右侧的响应窗格中显示响应。对于索引请求,响应确认文档已创建,如下图所示。 + +![响应窗格](/images/dev-tools/dev-tools-response.png) + +要搜索您索引的文档,请输入以下请求: + +```json +GET students/_search +{ + "query": { + "match": { + "name": "John Doe" + } + } +} +``` + +响应在 `hits` 数组中包含匹配的文档,如下图所示。 + +*搜索响应* + +### 使用 cURL 和控制台格式 + +控制台使用比 `curl` 命令更简单的语法来格式化 REST 请求。 + +例如,以下 `curl` 命令运行搜索查询: + +```bash +curl -XGET http://localhost:9200/students/_search?pretty -H 'Content-Type: application/json' -d' +{ + "query": { + "match": { + "name": "John Doe" + } + } +}' +``` + +相同的查询在控制台格式中有更简单的语法: + +```json +GET students/_search +{ + "query": { + "match": { + "name": "John Doe" + } + } +} +``` + +如果您直接将 `curl` 命令粘贴到控制台中,该命令会自动转换为控制台使用的格式。要将控制台中的查询转换为 cURL 格式,请参阅[将查询复制为 cURL](#copying-a-query-as-curl)。 + +### 在查询中使用三引号 + +在编写包含引号 (`"`) 和反斜杠 (`\`) 字符的查询时,您可以使用三引号 (`"""`) 来避免转义字符。这种格式提高了可读性,并有助于在编写大型或复杂字符串时避免转义字符,尤其是在处理深度嵌套的 JSON 字符串时。 + +您可以通过用反斜杠转义每个特殊字符来索引包含特殊字符的文档: + +```json +PUT /testindex/_doc/1 +{ + "test_query": "{ \"query\": { \"query_string\": { \"query\": \"host:\\\"127.0.0.1\\\"\" } } }" +} +``` + +或者,您可以使用三引号获得更简单的格式: + +```json +PUT /testindex/_doc/1 +{ + "test_query": """{ "query": { "query_string": { "query": "host:\"127.0.0.1\"" } } }""" +} +``` + +::: tip TIP +三引号仅在控制台中支持---在 `curl` 或其他 HTTP 客户端中不支持。要将包含三引号的查询转换为其他客户端接受的格式,请使用**复制为 cURL**。 +::: + +::: tip TIP +如果响应包含 `\n`、`\t`、`\` 或 `"` 特殊字符,控制台会使用三引号格式化响应。要关闭此行为,请从顶部菜单中选择**设置**并切换 **JSON 语法**。 +::: + +### 提交长时间运行的操作 + +在向 OpenSearch 提交长时间运行的操作(如重新索引或快照创建)时,您可以通过提供 `wait_for_completion=false` 查询参数使请求异步。如果未指定此参数,请求将同步运行。在这种情况下,如果操作超过 OpenSearch 请求超时值,客户端可能会发送新请求,这可能导致意外行为。如果 API 不支持通过查询参数进行异步执行,请考虑使用 cURL 直接运行请求。 + +## 使用请求选项菜单 + +要打开请求选项菜单,请选择请求右上角的扳手图标 (<img src="/images/dev-tools/wrench-icon.png" class="inline-icon" alt="扳手图标"/>),如下图所示。 + +![控制台工具](/images/dev-tools/dev-tools-tools.png) + +### 将查询复制为 cURL + +要以 cURL 格式复制查询,请选择查询并从请求选项菜单中选择**复制为 cURL**。然后,您可以在终端中运行复制的命令或将其粘贴到另一个 HTTP 客户端中。 + +### 查看文档 + +要查看所选请求的 OpenSearch 文档,请从请求选项菜单中选择**打开文档**。 + +### 自动缩进 + +要使用自动缩进,请选择要格式化的查询并从请求选项菜单中选择**自动缩进**。 + +自动缩进折叠的查询会将其展开。 + +::: tip TIP +自动缩进格式良好的查询会将请求正文放在一行上。这对于使用[批量 API](/api-reference/document-apis/bulk) 很有用。 +::: + +## 使用顶部菜单 + +顶部菜单提供了重用查询、配置编辑器和查看键盘快捷键的选项。 + +### 查看请求历史记录 + +您可以查看 OpenSearch 成功运行的最多 500 个最近的请求。要查看请求历史记录,请从顶部菜单中选择**历史记录**。如果您从左窗格中选择要查看的请求,查询将显示在右窗格中。 + +要将查询复制到编辑器窗格,请选择查询文本,然后选择**应用**。 + +要清除历史记录,请选择**清除**。 + +### 导出和导入查询 + +要将编辑器窗格中的查询保存到文件,请从顶部菜单中选择**导出**。控制台将查询下载为 `sense.json` 文件。 + +要从文件加载查询,请从顶部菜单中选择**导入**,选择文件,然后选择以下导入选项之一: + +- **与现有查询合并**: 将导入的查询添加到编辑器窗格中已有的查询。 +- **覆盖现有查询**: 用导入的查询替换编辑器窗格的内容。 + +选择**导入**以完成导入。 + +### 更新控制台设置 + +要更新您的首选项,请从顶部菜单中选择**设置**。您可以配置以下设置: + +- **字体大小**: 设置编辑器字体大小。 +- **自动换行**: 换行超出编辑器宽度的行。 +- **JSON 语法**: 对于包含特殊字符的响应,在响应窗格中使用三引号。 +- **自动完成**: 打开或关闭**字段**、**索引和别名**以及**模板**的自动完成建议。 +- **自动刷新自动完成建议**: 通过查询 OpenSearch 刷新自动完成建议。如果您有大型集群或网络限制,自动刷新可能会出现问题。要手动刷新建议,请选择**刷新自动完成建议**。 + +### 使用键盘快捷键 + +要查看所有可用的键盘快捷键,请从顶部菜单中选择**帮助**。 + +## 后续步骤 + +- 要尝试在控制台中运行更多查询,请参阅[摄取数据](/getting-started/ingest-data/)和[搜索数据](/getting-started/search-data/)。 +- 有关编写查询的信息,请参阅 [Query DSL](/query-dsl/)。 diff --git a/i18n/zh/dashboards/dev-tools/grok-debugger.md b/i18n/zh/dashboards/dev-tools/grok-debugger.md new file mode 100644 index 00000000..210240bc --- /dev/null +++ b/i18n/zh/dashboards/dev-tools/grok-debugger.md @@ -0,0 +1,46 @@ +--- +title: Grok 调试器 +--- + +# Grok 调试器 + +使用开发工具中的 **Grok 调试器**选项卡在将 [Grok 模式](/ingest-pipelines/processors/grok)用于摄取管道之前构建和测试它们。Grok 模式将非结构化日志数据解析为结构化字段。Grok 调试器根据您提供的示例文本测试模式,因此不需要任何已索引的数据。 + +## 测试 Grok 模式 + +要测试 Grok 模式,请执行以下步骤: + +1. 导航到**开发工具**并在页面顶部选择 **Grok 调试器**。 +1. 在**示例日志**字段中,输入示例日志消息。例如,输入以下 Apache 访问日志条目: + + ``` + 127.0.0.1 - alice [15/Mar/2026:10:32:41 -0700] "GET /products/1234 HTTP/1.1" 200 2326 + ``` + +1. 在 **Grok 模式**字段中,输入要针对示例日志测试的模式: + + ``` + %{IPORHOST:client_ip} - %{USER:user} \[%{HTTPDATE:timestamp}\] "%{WORD:method} %{URIPATHPARAM:request} HTTP/%{NUMBER:http_version}" %{NUMBER:status} %{NUMBER:bytes} + ``` + +1. 选择**模拟**。 + +**结果**窗格显示**模式匹配**并列出提取的字段及其值,如下图所示。 + +*Grok 调试器* + +要清除两个字段和结果,请选择**清除**。 + +要打开 Grok 处理器文档,请选择 **Grok 文档**。 + +## 配置高级设置 + +要定义您自己的模式或返回每个匹配项,请选择**高级设置**。您可以配置以下设置: + +- **自定义模式定义**: 定义内置模式集中不包含的模式。按 `PATTERN_NAME pattern_regex` 格式每行输入一个模式。定义自定义模式后,您可以使用 `%{PATTERN_NAME:field_name}` 语法在 **Grok 模式**字段中引用它。 +- **捕获所有匹配项**: 返回模式的所有匹配项,而不是仅返回第一个匹配项。 + +## 后续步骤 + +- 有关 Grok 处理器和可用内置模式的信息,请参阅 [Grok 处理器](/ingest-pipelines/processors/grok)。 +- 有关创建摄取管道的信息,请参阅[摄取管道](/ingest-pipelines/)。 diff --git a/i18n/zh/dashboards/dev-tools/index.md b/i18n/zh/dashboards/dev-tools/index.md new file mode 100644 index 00000000..30a800ed --- /dev/null +++ b/i18n/zh/dashboards/dev-tools/index.md @@ -0,0 +1,35 @@ +--- +title: 使用开发工具 +--- + +# 使用开发工具 + +OpenSearch Dashboards 中的**开发工具**应用程序提供了查询集群和测试查询及摄取模式的工具。 + +::: tip TIP +如果您是开发工具应用程序的新手,请参阅[在开发工具控制台中运行查询](/dashboards/getting-started/explore-dev-tools)以获取实践介绍。 +::: + +## 导航到开发工具 + +要打开开发工具,请在 OpenSearch Dashboards 主页上选择**开发工具**,如下图所示。 + +![从主页打开开发工具控制台](/images/dev-tools/dev-tools-main.png) + +您可以从任何其他页面打开开发工具,方法是导航到主菜单并选择**管理** > **开发工具**,如下图所示。 + +![从所有页面打开开发工具控制台](/images/dev-tools/dev-tools-left.png) + +在启用了工作区的安装中,选择导航面板左下角的代码图标 (代码图标)。 + +## 使用开发工具 + +**开发工具**应用程序如下图所示。 + +*开发工具控制台应用程序* + +开发工具包含以下应用程序: + +- [**控制台**](/dashboards/dev-tools/console)向 OpenSearch 发送 [Query DSL](/query-dsl/) 查询和其他 REST API 请求,并显示响应。 +- [**Grok 调试器**](/dashboards/dev-tools/grok-debugger)在您将 [Grok 模式](/ingest-pipelines/processors/grok)用于摄取管道之前,针对示例日志数据构建和测试它们。 +- [**查询分析器**](/dashboards/dev-tools/query-profiler)测量搜索查询的每个部分运行需要多长时间,以便您可以识别慢速组件。 diff --git a/i18n/zh/dashboards/dev-tools/query-profiler.md b/i18n/zh/dashboards/dev-tools/query-profiler.md new file mode 100644 index 00000000..a66b5316 --- /dev/null +++ b/i18n/zh/dashboards/dev-tools/query-profiler.md @@ -0,0 +1,116 @@ +--- +title: 查询分析器 +--- + +# 查询分析器 + +使用开发工具中的**查询分析器**选项卡来测量搜索查询的每个组件运行需要多长时间。查询分析器使用 [Profile API](/api-reference/search-apis/profile) 运行您的查询,并以可视化形式呈现结果,以便您可以识别消耗最多时间的查询和聚合。 + +当您打开查询分析器时,编辑器包含以下默认查询,其中包含 `profile` 参数,如下图所示。 + +*查询分析器默认查询* + +::: info NOTE +当您选择**可视化分析**时,即使您的查询不包含 `profile` 参数,查询分析器也会收集分析数据。要在响应窗格中包含分析数据,请在查询中保留 `"profile": true`。 +::: + +## 前提条件 + +此页面上的示例使用**示例电商订单**数据集。如果您使用 OpenSearch Dashboards 的本地安装并且尚未添加示例数据,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 分析查询 + +要分析查询,请执行以下步骤: + +1. 导航到**开发工具**并在页面顶部选择**查询分析器**。 +1. 用要分析的查询替换编辑器窗格中的默认查询。例如,输入以下查询,该查询搜索示例电商数据并计算平均订单总额和按客户性别的细分: + + ```json + GET opensearch_dashboards_sample_data_ecommerce/_search + { + "profile": true, + "query": { + "bool": { + "must": [ + { "match": { "category": "Clothing" } }, + { "match": { "manufacturer": "Elitelligence" } } + ], + "filter": [ + { "range": { "taxful_total_price": { "gte": 50 } } } + ] + } + }, + "aggs": { + "avg_price": { + "avg": { "field": "taxful_total_price" } + }, + "by_gender": { + "terms": { "field": "customer_gender" } + } + } + } + ``` + +1. 选择播放图标 (<img src="/images/dev-tools/play-icon.png" class="inline-icon" alt="播放图标"/>) 或按 `Ctrl/Cmd+Enter` 运行查询。OpenSearch 在右窗格中显示响应。 +1. 选择**可视化分析**。 + +要恢复默认查询并清除结果,请选择播放图标旁边的重置图标。 + +## 查看分片时间 + +**分析结果**部分列出了处理查询的分片,以及每个分片的**搜索时间**和**聚合时间**,如下图所示。 + +*查询分析器分片结果* + +条形颜色表示每个分片消耗的最大时间百分比: + +- 绿色: 50% 或更少(低) +- 橙色: 51--80%(中) +- 红色: 超过 80%(高) + +要更改这些百分比,请选择图例旁边的齿轮图标并更新**红色 (>80%)** 和**橙色 (>50%)** 阈值。要恢复默认值,请选择**重置为默认值**。 + +您还可以在此部分执行以下操作: + +- 要查找特定分片,请在**搜索分片**字段中输入其名称。 +- 要按聚合时间而不是搜索时间对列表进行排序,请选择**排序方式: 搜索时间**,然后选择**排序方式: 聚合时间**。 +- 要更改显示的分片数量,请选择**每页行数**。 + +## 查看查询时间 + +选择一个分片以显示其查询细分。左窗格包含**搜索**选项卡和**聚合**选项卡,每个选项卡列出在该分片上运行的组件以及每个组件花费的时间。选择组件旁边的箭头以展开其子查询。 + +选择一个组件以显示其详细信息,如下图所示。 + +*查询分析器操作细分* + +详细信息窗格包含以下信息: + +- 组件名称、它重写到的 Lucene 查询以及**总时间**。 +- **查询层次结构**: 查询及其子查询的层次结构,以及每个查询占总时间的百分比。 +- **操作细分**: 组件执行的低级 Lucene 操作,如 `Create Weight`、`Build Scorer` 和 `Next Doc`,包括每个操作的时间(以纳秒为单位)和运行次数。 + +要在操作细分的图表视图和表格视图之间切换,请选择**操作细分**标题右侧的**可视化细分**或**原始数据**图标。 + +## 导入和导出分析结果 + +要保存分析结果,请从顶部菜单中选择**导出 JSON**。查询分析器将结果下载为 `profile.json` 文件。 + +要加载查询或之前保存的分析,请从顶部菜单中选择**导入**,在**导入到**中选择以下选项之一,选择文件,然后选择**导入**: + +- **搜索查询**: 将搜索查询加载到编辑器窗格中。 +- **分析 JSON**: 加载分析结果并显示可视化,而不运行查询。 + +## 更新查询分析器设置 + +要更新您的首选项,请从顶部菜单中选择**设置**。您可以配置以下设置: + +- **字体大小**: 设置编辑器字体大小。 +- **自动换行**: 换行超出编辑器宽度的行。 + +要查看查询分析器的帮助,请从顶部菜单中选择**帮助**。 + +## 后续步骤 + +- 有关查询分析器使用的 API 的信息,请参阅 [Profile API](/api-reference/search-apis/profile)。 +- 有关编写查询的信息,请参阅 [Query DSL](/query-dsl/)。 diff --git a/i18n/zh/dashboards/discover/field-select.md b/i18n/zh/dashboards/discover/field-select.md new file mode 100644 index 00000000..18978e1b --- /dev/null +++ b/i18n/zh/dashboards/discover/field-select.md @@ -0,0 +1,114 @@ +--- +title: 字段选择工具 +--- + +# 使用字段选择工具 + +默认情况下,发现应用程序的**结果**表显示表中每个文档的所有字段。在字段选择工具中,您可以选择哪些数据字段出现在**结果**表中。 + +字段选择工具位于[发现](/dashboards/discover/index-discover)应用程序窗格左侧的垂直面板中。它仅在**发现**应用程序中可用。 + +## 导航字段选择工具 + +*字段选择工具* + +以下组件组成字段选择工具。 + +- **索引模式**下拉列表 (A) 显示所有可用的索引模式。所选索引模式决定加载哪些数据,因此决定字段选择工具中可用的字段。 +- **搜索字段名称** (B) 框通过将字段名称与您的搜索字符串匹配来缩小选择工具中可用的字段范围。 +- **按类型过滤**下拉列表 (C) 根据数据类型和可搜索性等数据属性缩小可用字段范围。 +- **已选字段**列表 (D) 是所有已选字段的可折叠列表。 +- **常用字段**列表 (E) 是最近选择的字段的可折叠列表。 +- **可用字段**列表 (F) 是所有未选择字段的可折叠列表。 + +::: warning IMPORTANT +**已选字段**、**常用字段**和**可用字段**列表是互斥的。一个字段只会出现在这些可折叠列表中的一个。 +::: + +## 选择索引模式 + +在探索和可视化数据之前,您必须选择一个索引模式。 + +索引模式相当于传统关系数据库系统中的表视图。它定义了您有兴趣探索和可视化的数据集。有关创建索引模式的信息,请参阅[索引模式](/dashboards/management/index-patterns)。 + +要选择索引模式,请执行以下步骤: + +1. 在字段选择工具中,从**索引模式**下拉列表中选择一个索引模式。 + +## 选择要显示的字段 + +要选择要在**结果**表中显示的字段,请执行以下步骤: + +1. 选择 展开图标 (展开) **可用字段**以展开**可用字段**。 + + ::: info NOTE + 如果该字段最近被使用过,它可能在**常用字段**列表而不是**可用字段**列表中。 + ::: + +1. (可选) [使用 漏斗图标 **按类型过滤**](#filtering-fields-by-type) 弹出窗口按类型缩小可用字段范围。 + +1. (可选) 在**搜索字段名称**框中输入文本以缩小可用字段列表。 + +1. 在**可用字段**或**常用字段**列表中选择一个字段。 + +1. 选择所选字段的 绿色加号图标 (添加) 图标。 + + 该字段作为列添加到**发现**应用程序窗格的**结果**表中。 + +## 删除字段 + +要从**结果**表的显示中删除字段,请执行以下步骤: + +1. 选择 展开图标 (展开) **已选字段**以展开**已选字段**。 + +1. 在**已选字段**列表中选择一个字段。 + +1. 选择所选字段的 红色叉号图标 (删除) 图标。 + + 该字段从**发现**应用程序窗格的**结果**表中删除。 + + ::: info NOTE + 如果删除的字段是最后一个已选字段,**结果**表将默认回显示所有字段。 + ::: + +## 按类型过滤字段 + +通常可用字段列表很长。为了避免滚动列表,请按数据类型以及它们是否可聚合或可搜索来过滤字段选择工具中的字段。 + +::: tip TIP +漏斗图标 **按类型过滤**右侧的数字表示活动类型过滤器的数量。 +::: + +### 按数据类型过滤字段 + +要按数据类型缩小字段选择工具中的字段,请执行以下步骤: + +1. 选择 漏斗图标 **按类型过滤**。 + +1. 在**按类型过滤**弹出窗口中,从**类型**下拉列表中选择数据类型。 + + 字段被限制为所选类型。 + + ::: info NOTE + 字段在所有列表中都受到限制:**已选字段**、**常用字段**和**可用字段**。 + ::: + +### 按属性过滤字段 + +要按属性过滤字段,请执行以下步骤: + +1. 选择 漏斗图标 **按类型过滤**。 + +1. 在**按类型过滤**弹出窗口中,选择**可聚合**选项。例如,选择**是**将过滤掉所有不可聚合的字段。 + +1. 在**按类型过滤**弹出窗口中,选择**可搜索**选项。例如,选择**是**将过滤掉所有不可搜索的字段。 + + 可搜索字段是包含在倒排索引中并可用于搜索的字段。有关更多信息,请参阅[索引](/mappings/mapping-parameters/index-parameter/)。 + +### 过滤缺失字段 + +要过滤掉缺少数据的字段,请执行以下步骤: + +1. 选择 漏斗图标 **按类型过滤**。 + +1. 在**按类型过滤**弹出窗口中,激活**隐藏缺失字段**切换。 diff --git a/i18n/zh/dashboards/discover/filter-tool.md b/i18n/zh/dashboards/discover/filter-tool.md new file mode 100644 index 00000000..c89f8f7b --- /dev/null +++ b/i18n/zh/dashboards/discover/filter-tool.md @@ -0,0 +1,159 @@ +--- +title: 过滤工具 +--- + +# 使用过滤工具 + +过滤工具位于[发现](/dashboards/discover/index-discover)、[仪表板](/dashboards/dashboard/)和[可视化](/dashboards/visualize/visualize-app/)应用程序的顶部,直接在**[搜索](/dashboards/discover/search-bar)**栏下方。使用它来添加和删除这些应用程序中显示的数据的离散过滤器。 + +您可以创建任意数量的过滤器。过滤器列在 过滤器菜单图标 (漏斗) 图标和 添加过滤器图标 (圆圈加号) **添加过滤器**控件之间的过滤器显示区域中。 + +## 导航过滤工具 + +*过滤工具* + +以下组件组成过滤工具。 + +- 过滤器菜单图标 (漏斗) 图标 (A) 提供过滤器选项的下拉菜单。 +- 过滤器列表 (B) 显示当前定义的过滤器。 +- 添加过滤器图标 (圆圈加号) **添加过滤器** (C) 提供添加数据过滤器的弹出菜单。 + +## 添加过滤器 + +要使用**添加过滤器**工具添加过滤器,请执行以下步骤: + +1. 选择 添加过滤器图标 (添加) **添加过滤器**。 + +1. 在**编辑过滤器**弹出窗口中,选择一个数据字段。 + +*编辑过滤器弹出窗口* + +1. 在**运算符**字段中,选择一个运算符。 + + ::: info NOTE + **运算符**下拉选项由所选数据字段的类型决定。 + ::: + + 如果需要,会出现值字段。 + +1. 如果需要,在**值**字段中,输入或选择一个值。 + + ::: info NOTE + **值**输入模式和选项由所选运算符和数据字段类型决定。 + ::: + +1. (可选) 选择**创建自定义标签?**。 + + 自定义标签替换由数据字段名称和运算符组成的默认标签。 + +1. 选择**保存**。 + +## 编辑过滤器 + +要更改现有过滤器,请执行以下步骤: + +1. 在过滤器列表中选择过滤器。 + +1. 在过滤器下拉列表中,选择**编辑过滤器>**。 + +1. 在**编辑过滤器**弹出窗口中,根据需要更改**字段**、**运算符**或**值**。 + +1. (可选) 添加或更改**自定义标签**。 + +1. 选择**保存**。 + +## 删除过滤器 + +要删除过滤器,选择过滤器名称右侧的 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="叉号图标"/> (叉号) 图标。 + +## 禁用过滤器 + +您可以暂时禁用过滤器而不将其从过滤器列表中删除。要禁用过滤器,请执行以下步骤: + +1. 在过滤器列表中选择过滤器。 + +1. 在过滤器下拉列表中,选择**暂时禁用**。 + + ::: info NOTE + 禁用的过滤器名称以~~删除线~~文本显示。 + ::: + +## 重新启用过滤器 + +要启用已禁用的过滤器,请执行以下步骤: + +1. 在过滤器列表中选择~~已禁用~~过滤器。 + +1. 在过滤器下拉列表中,选择**重新启用**。 + +## 固定过滤器 + +您可以固定过滤器,使其应用于 OpenSearch Dashboards 中的所有应用程序(发现、仪表板和可视化)。要固定过滤器,请执行以下步骤: + +1. 在过滤器列表中选择过滤器。 + +1. 在过滤器下拉列表中,选择**在所有应用中固定**。 + +## 取消固定过滤器 + +要取消固定已固定到所有应用程序的过滤器,请执行以下步骤: + +1. 在过滤器列表中选择过滤器。 + +1. 在过滤器下拉列表中,选择**取消固定**。 + +## 作为一组修改所有过滤器 + +您可以使用 过滤器菜单图标 (漏斗) **过滤器**下拉列表以多种方式一次更改所有过滤器。 + +::: info NOTE +使用 过滤器菜单图标 (漏斗) **过滤器**下拉列表所做的修改仅适用于过滤器列表中的过滤器,不适用于**搜索**栏中的查询或时间过滤器。 +::: + +### 启用或禁用所有过滤器 + +要启用或禁用所有过滤器,请执行以下步骤: + +1. 选择 过滤器菜单图标 (漏斗) 图标。 + +1. 在**过滤器**下拉列表中,选择**启用所有**或**禁用所有**。 + +### 反转启用的过滤器 + +要排除所有包含的过滤器并包含所有排除的过滤器,请执行以下步骤: + +1. 选择 过滤器菜单图标 (漏斗) 图标。 + +1. 在**过滤器**下拉列表中,选择**反转启用/禁用**。 + +### 反转所有过滤器的包含意义 + +要否定所有过滤器表达式,使所有包含的文档被排除,所有排除的文档被包含,请执行以下步骤: + +1. 选择 过滤器菜单图标 (漏斗) 图标。 + +1. 在**过滤器**下拉列表中,选择**反转包含**。 + + 排除过滤器的标题附加了 **NOT**,如下所示。第二次反转包含会删除 **NOT** 修饰符。 + + *排除过滤器* + + ::: info NOTE + 禁用的过滤器会被反转,但保持禁用状态。 + ::: + +### 固定或取消固定所有过滤器 + +要在所有 OpenSearch Dashboards 应用程序(发现、仪表板和可视化)中固定或取消固定所有过滤器,请执行以下步骤: + +1. 选择 过滤器菜单图标 (漏斗) 图标。 + +1. 在**过滤器**下拉列表中,选择**固定所有**或**取消固定所有**。 + +### 删除所有过滤器 + +要从过滤器列表中删除所有过滤器,请执行以下步骤: + +1. 选择 过滤器菜单图标 (漏斗) 图标。 + +1. 在**过滤器**下拉列表中,选择**删除所有**。 diff --git a/i18n/zh/dashboards/discover/index.md b/i18n/zh/dashboards/discover/index.md new file mode 100644 index 00000000..ac32ab43 --- /dev/null +++ b/i18n/zh/dashboards/discover/index.md @@ -0,0 +1,18 @@ +--- +title: 探索数据 +--- + +# 探索数据 + +OpenSearch Dashboards 提供了多种探索数据的工具,从基本的一次性查询到可保存的 API 等效查询,应有尽有。您可以执行以下操作: + +- 在**发现**或**仪表板**搜索栏中使用 Dashboards 查询语言 (DQL)(一种用于基本查询的 Dashboards 特定语言)或基于 Apache Lucene 的查询字符串查询语言来探索数据。 +- 使用**查询工作台**工具以 SQL 或管道处理语言 (PPL) 执行查询。 +- 使用**开发工具**控制台以查询领域特定语言 (Query DSL) 运行查询。使用 Query DSL,您可以像从 API 一样运行任何查询。 +- 在**发现**和**可视化**工具中显示和保存查询数据的可视化。 + +要了解更多关于 | 请转到 | 使用的查询语言 +:------------------- | :----- | :----- +快速探索数据 | [使用发现探索数据](/dashboards/discover/index-discover) | [Dashboards 查询语言 (DQL)](/dashboards/dql)<br/>或<br/>[查询字符串查询语言 (Lucene)](/query-dsl/full-text/query-string) +使用 API 查询数据 |[开发工具](/dashboards/dev-tools/) | [查询领域特定语言 (Query DSL)](/query-dsl/) +查询数据 | [使用查询工作台](/dashboards/query-workbench) | [结构化查询语言 (SQL)](/sql-and-ppl/sql/)<br/>或<br/>[管道处理语言 (PPL)](/sql-and-ppl/ppl/) diff --git a/i18n/zh/dashboards/discover/search-bar.md b/i18n/zh/dashboards/discover/search-bar.md new file mode 100644 index 00000000..2a181005 --- /dev/null +++ b/i18n/zh/dashboards/discover/search-bar.md @@ -0,0 +1,141 @@ +--- +title: 搜索栏 +--- + +# 使用搜索栏 + +相同的搜索栏位于[发现](/dashboards/discover/index-discover)、[仪表板](/dashboards/dashboard/)和[可视化](/dashboards/visualize/visualize-app/)应用程序的顶部。使用它来过滤这些应用程序中显示的数据。 + +在搜索栏中,您可以使用以下两种语言之一进行基于文本的搜索: + +- [Dashboards 查询语言 (DQL)](/dashboards/dql): 一种具有嵌套字段查询的基本查询语言。 + +- [查询字符串查询语言 (Lucene)](/query-dsl/full-text/query-string): 一种基于 [Apache Lucene](https://lucene.apache.org/core/9_9_2/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description) 查询语言的查询语言。 + +::: info NOTE +在文档和 UI 中,_查询字符串查询语言_和 _Lucene_ 可互换使用。 +::: + +查询字符串查询语言和 DQL 支持不同的功能。例如,DQL 有嵌套表达式;Lucene 有模糊搜索和正则表达式。有关完整比较,请参阅 [DQL 和查询字符串查询快速参考](/dashboards/dql#dql-and-query-string-query-quick-reference)。 + +## 导航搜索栏 + + *搜索栏界面* + +以下组件组成搜索栏。 + +- <img src="/images/icons/save-icon.png" class="inline-icon" alt="保存图标"/> (保存) 图标 (A) 保存当前查询。 +- **搜索**框 (B) 接受当前选择的查询语言中的查询。 +- 查询语言选择器 (C) 打开用于选择查询语言的**语法选项**弹出窗口。 + +## 更改查询语言 + +当前查询语言,OpenSearch Dashboards 查询语言 (DQL) 或查询字符串查询语言 (Lucene),显示在**搜索**框的右侧。 + +要在 DQL 和查询字符串查询语言之间切换,请执行以下步骤: + +1. 选择查询语言选择器(显示当前查询语言)。 + +1. 在**语法选项**对话框中,打开或关闭 **OpenSearch Dashboards 查询语言**切换。 + + ::: info NOTE + 如果 **OpenSearch Dashboard 查询语言** (DQL) 被**关闭**,查询语言设置为 OpenSearch Dashboards 查询语言,查询语言选择器显示 **Lucene**。 + ::: + + ![在 OpenSearch Dashboards 发现中使用查询字符串语法](/images/discover-lucene-syntax.png) + +## 基于查询过滤 + +要使用**搜索**框过滤,请执行以下步骤: + +1. 在**搜索**框中输入过滤条件。例如,使用 DQL 针对 OpenSearch 电商示例数据,输入 `category: "Men's Clothing"`。 + + 有关在 DQL 中查询的信息,请参阅 [Dashboards 查询语言 (DQL)](/dashboards/dql)。 + + 有关在 Lucene 中查询的信息,请参阅[查询字符串查询语言 (Lucene)](/query-dsl/full-text/query-string)。 + +1. 选择**刷新**。 + + *刷新按钮* + + **结果**表已更新以反映按查询过滤。 + +## 编辑过滤查询 + +要更改查询,请执行以下步骤: + +1. 在**搜索**框中编辑过滤条件。例如,要更改前一个示例中的 DQL 查询,请将查询更改为 `sales_by_category is "Women's Clothing"`。 + +1. 选择**刷新**。 + + *刷新按钮* + + **结果**表已更新以反映更改后的查询。 + +## 保存查询 + +使用此过程保存以下任意组合: + +- DQL 或 Lucene 查询。 +- 过滤器。 +- 时间过滤器。 + +要保存查询,请执行以下步骤: + +1. 选择 <img src="/images/icons/save-icon.png" class="inline-icon" alt="保存图标"/> (保存) 图标。 + +::: info NOTE +**搜索**框中不必有查询。您可以使用此过程保存过滤器和/或时间过滤器而不保存查询。 +::: + +1. 从**保存**弹出窗口中,选择**保存当前查询**或**另存为新**。 + +1. 在**保存查询**对话框中,输入查询的**名称**。 + +1. (可选) 在**描述**框中,输入查询的描述。 + +1. (可选) 激活**包含过滤器**切换以同时保存[过滤器列表](/dashboards/discover/filter-tool)中的过滤器。 + +1. (可选) 激活**包含时间过滤器**切换以同时保存当前活动的[时间过滤器](/dashboards/discover/time-filter)。 + +1. 选择**保存**。 + +## 加载保存的搜索 + +要加载保存的搜索,请执行以下步骤: + +1. 选择 <img src="/images/icons/save-icon.png" class="inline-icon" alt="保存图标"/> (保存) 图标。 + +1. 选择要加载的搜索。 + + 过滤器加载,**发现**应用程序中显示的数据已更新。 + +## 编辑查询 + +要更改现有查询,请执行以下步骤: + +1. 选择 <img src="/images/icons/save-icon.png" class="inline-icon" alt="保存图标"/> (保存) 图标。 + +1. 选择要编辑的查询。 + +1. 使用要更新查询的搜索查询、过滤器和时间过滤器过滤数据。 + +1. 再次选择 <img src="/images/icons/save-icon.png" class="inline-icon" alt="保存图标"/> (保存) 图标。当前保存的查询在列表中被选中。 + +1. 选择**保存更改**。 + +1. (可选) 在**保存查询**对话框中,输入或更改**描述**。 + +1. 选择**保存**。 + +## 删除查询 + +要删除查询,请执行以下步骤: + +1. 选择 <img src="/images/icons/save-icon.png" class="inline-icon" alt="保存图标"/> (保存) 图标。 + +1. 将鼠标悬停在要删除的查询上。 + +1. 选择 垃圾桶图标 (垃圾桶) 图标。 + +1. 在删除确认对话框中,选择**删除**。 diff --git a/i18n/zh/dashboards/exporting-data.md b/i18n/zh/dashboards/exporting-data.md new file mode 100644 index 00000000..12fde47c --- /dev/null +++ b/i18n/zh/dashboards/exporting-data.md @@ -0,0 +1,47 @@ +--- +title: 导出数据 +--- + +# 导出数据 + +OpenSearch Dashboards 提供了多种下载内容的方式。方法取决于您要导出的内容:文档本身、可视化背后的数据、仪表板的渲染副本或您创建的对象的定义。 + +下表列出了导出方法。 + +| 您要导出的内容 | 方法 | 格式 | +| :--- | :--- | :--- | +| 搜索返回的文档 | [从发现下载搜索结果](#exporting-search-results) | CSV | +| 单个文档 | [从发现复制文档](#exporting-search-results) | JSON | +| 可视化显示的数据 | [从检查面板下载数据](#exporting-visualization-data) | CSV | +| 仪表板、可视化、保存的搜索或笔记本作为文件共享,按需或按计划 | [生成报告](#generating-reports) | PDF、PNG、CSV 或 XLSX | +| 仪表板、可视化、索引模式和其他保存的对象,以备份或复制到另一个实例 | [导出保存的对象](#exporting-saved-objects) | NDJSON | + +## 导出搜索结果 + +在**发现**中,过滤文档并选择要导出的字段,然后选择**下载为 CSV**。您可以下载页面上可见的文档或所有匹配的文档,最多 10,000 个。要复制单个文档,请展开文档并复制其 JSON 表示。 + +有关更多信息,请参阅[在发现中导出数据](/dashboards/discover/index-discover#exporting-data)。 + +## 导出可视化数据 + +要下载可视化显示的数据,请执行以下步骤: + +1. 打开可视化: + - 在**可视化**应用程序中,打开可视化并在顶部菜单上选择**检查**。 + - 在仪表板上,打开可视化的面板菜单并选择**检查**。 +1. 选择**下载 CSV**。 +1. 选择以下选项之一: + - **格式化的 CSV**: 使用索引模式的字段格式下载表中显示的数据。 + - **原始 CSV**: 按存储方式下载数据。例如,日期下载为时间戳。 + +## 生成报告 + +报告将仪表板、可视化或笔记本捕获为 PDF 或 PNG 文件,或将保存的搜索结果捕获为 CSV 或 XLSX 文件。生成一次报告或创建按计划生成报告的报告定义。要按计划或从脚本导出搜索结果,请在**发现**中保存搜索并从保存的搜索生成 CSV 或 XLSX 报告。 + +有关更多信息,请参阅[报告](/dashboards/reporting/)。 + +## 导出保存的对象 + +保存的对象是您在 OpenSearch Dashboards 中创建的仪表板、可视化、保存的搜索、索引模式和其他资源的定义。导出保存的对象会下载这些定义,而不是它们显示的数据。使用此方法备份您的对象或将它们导入另一个 OpenSearch Dashboards 实例。 + +有关更多信息,请参阅[保存的对象](/dashboards/management/saved-objects)。 diff --git a/i18n/zh/dashboards/getting-started/access.md b/i18n/zh/dashboards/getting-started/access.md new file mode 100644 index 00000000..63ebcf2b --- /dev/null +++ b/i18n/zh/dashboards/getting-started/access.md @@ -0,0 +1,52 @@ +--- +title: 访问 OpenSearch Dashboards +--- + +# 访问 OpenSearch Dashboards + +一旦 OpenSearch 和 OpenSearch Dashboards 运行起来,打开浏览器并导航到以下 URL: + +- `http://localhost:5601` 或 `https://localhost:5601` 用于本地安装。 +- [https://playground.opensearch.org/app/home#/](https://playground.opensearch.org/app/home#/) 用于 OpenSearch Playground。 + +如果您的集群使用安全插件,OpenSearch Dashboards 会打开登录页面。使用 `admin` 用户和您在安装 OpenSearch 时在 `OPENSEARCH_INITIAL_ADMIN_PASSWORD` 中设置的密码登录。有关更多信息,请参阅[设置初始管理员密码](/security/configuration/passwords/#setting-the-initial-admin-password)。 + +::: info NOTE +>- _OpenSearch Dashboards_ 指的是 OpenSearch 的 Web UI---您在浏览器中看到的应用程序。 +>- **仪表板**应用程序是 OpenSearch Dashboards 中用于将可视化组合到单个页面的工具。 +>- _仪表板_(小写)是在**仪表板**应用程序中创建的单个可视化页面。 +::: + +## 访问本节中使用的应用程序 + +入门教程使用发现、可视化和仪表板应用程序以及开发工具控制台。使用 UI 左侧的_左侧导航面板_选择您要使用的任何应用程序或设置页面。要打开导航面板,请选择页面顶部标题栏中的 <img src="/images/icons/menu-icon.png" class="inline-icon" alt="菜单图标"/> (菜单) 图标。有关主页和左侧导航面板的更多信息,请参阅[导航 OpenSearch Dashboards](/dashboards/navigating-ui)。 + +### 经典导航 + +在未启用工作区的安装中,左侧导航面板直接列出所有应用程序。下图突出显示了教程中使用的应用程序。 + +*带有经典导航的 OpenSearch Dashboards 主页* + +1. 准备您的数据。 +1. 探索发现应用程序。 +1. 探索仪表板应用程序。 +1. 探索可视化应用程序。 +1. 在 OpenSearch Dashboards 中运行查询。 + +本文档中的示例使用经典导航。如果您启用了工作区,菜单结构会有所不同,但相同的应用程序在您的工作区中可用。 + +### 工作区导航 + +如果启用了工作区,请先创建并选择一个工作区。有关更多信息,请参阅[工作区导航](/dashboards/navigating-ui#workspaces-navigation)。下图显示了示例分析工作区中的左侧导航,包括教程中使用的应用程序。 + +*分析工作区中的左侧导航* + +1. 准备您的数据。 +1. 探索发现应用程序。 +1. 探索仪表板应用程序。 +1. 探索可视化应用程序。 +1. 在 OpenSearch Dashboards 中运行查询。 + +## 后续步骤 + +- 要了解每个应用程序的功能,请参阅[了解主要应用程序](/dashboards/getting-started/learn-dashboards)。 diff --git a/i18n/zh/dashboards/getting-started/concepts.md b/i18n/zh/dashboards/getting-started/concepts.md new file mode 100644 index 00000000..61422791 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/concepts.md @@ -0,0 +1,48 @@ +--- +title: 概念 +--- + +# OpenSearch Dashboards 概念 + +本页定义了整个 OpenSearch Dashboards 文档中使用的关键术语。 + +## OpenSearch Dashboards 术语 + +- **_OpenSearch Dashboards_**: OpenSearch 的 Web UI。这是您在浏览器中访问的应用程序。 +- **仪表板**应用程序: OpenSearch Dashboards 中用于将可视化组合到单个页面的应用程序。请参阅[创建仪表板](/dashboards/dashboard/)。 +- _仪表板_(小写): 在**仪表板**应用程序中创建的单个数据可视化页面。 +- **可视化**应用程序: OpenSearch Dashboards 中用于创建单个图表、地图和表格的应用程序。请参阅[在可视化应用程序中创建可视化](/dashboards/visualize/visualize-app/)。 +- _可视化_: 包含图形、图表、地图或其他数据可视化表示的单个面板。 +- **发现**应用程序: OpenSearch Dashboards 中用于搜索、过滤和检查数据的应用程序。请参阅[使用发现探索数据](/dashboards/discover/index-discover)。 +- [**OpenSearch Playground**](https://playground.opensearch.org/app/home#/): 一个只读的、基于 Web 的 OpenSearch Dashboards 实例,带有预加载的示例数据。使用它可以在不安装任何东西的情况下探索 OpenSearch Dashboards。 + +## 数据概念 + +- _索引_: 存储在 OpenSearch 中的相关文档集合。请参阅[索引](/getting-started/intro/#index)。 +- _文档_: OpenSearch 中的基本信息单位,存储为 JSON 对象。请参阅[文档](/getting-started/intro/#document)。 +- _索引模式_: 指向一个或多个索引的视图,您可以将其用作 OpenSearch Dashboards 中的数据源。在某些上下文中也称为_数据源_。请参阅[索引模式](/dashboards/management/index-patterns)。 +- _字段_: 文档中的单个命名值,相当于关系数据库表中的列。 +- _桶_: 基于聚合的字段值分组。桶可以是分类的(基于文本值)、基于范围的(用户定义的数值范围)、基于直方图的(自动调整大小的数值间隔)或基于时间的(时间戳字段的片段)。 +- _聚合_: 跨文档汇总数据的计算,例如计算计数、平均值、总和或将文档分组到桶中。请参阅[聚合](/aggregations/)。 +- _保存的对象_: 您在 OpenSearch Dashboards 中保存的任何项目,包括可视化、仪表板、索引模式和保存的搜索。 + +## 工作区 + +_工作区_是 OpenSearch Dashboards 中按用例(例如,分析或可观测性)组织应用程序和保存对象的隔离环境。请参阅[工作区](/dashboards/workspace/)。 + +## 查询语言 + +OpenSearch Dashboards 支持多种查询语言: + +- [**Dashboards 查询语言 (DQL)**](/dashboards/dql): 一种简单的基于文本的语言,用于在发现和仪表板搜索栏中过滤数据。 +- [**管道处理语言 (PPL)**](/sql-and-ppl/ppl/): 一种基于管道的数据处理和分析语言。用于查询工作台和可视化编辑器。 +- [**Query DSL**](/query-dsl/): 完整的 OpenSearch 查询语言,用于开发工具控制台和 API 请求。 +- [**SQL**](/sql-and-ppl/sql/): 用于查询 OpenSearch 数据的标准 SQL 语法。用于查询工作台。 + +## 后续步骤 + +探索每个应用程序的完整文档: + +- [使用发现探索数据](/dashboards/discover/index-discover) +- [构建数据可视化](/dashboards/visualize/visualize-app/) +- [创建仪表板](/dashboards/dashboard/) diff --git a/i18n/zh/dashboards/getting-started/data-setup.md b/i18n/zh/dashboards/getting-started/data-setup.md new file mode 100644 index 00000000..0e660d73 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/data-setup.md @@ -0,0 +1,67 @@ +--- +title: 准备数据 +--- + +# 准备数据 + +在您可以在 OpenSearch Dashboards 中探索、可视化或创建数据仪表板之前,您需要在 OpenSearch 中有数据和指向它的索引模式。 + +## 步骤 1: 将数据添加到 OpenSearch + +选择以下选项之一将数据添加到 OpenSearch。我们建议从添加示例数据开始。 + +### 添加示例数据 + +示例数据集带有预构建的索引模式、可视化和仪表板。[**示例航班数据**](https://playground.opensearch.org/app/home#/tutorial_directory)数据集已安装在 [OpenSearch Playground](https://playground.opensearch.org/app/home#/) 中。 + +如果您已安装本地 OpenSearch Dashboards 实例,请按照以下步骤添加一个或多个示例数据集: + +**经典导航:** + +1. 在 OpenSearch Dashboards 主页上,选择**添加示例数据**。 +1. 在**添加示例数据**页面上,选择**示例航班数据**图块和您要添加的任何其他图块中的**添加数据**按钮。 + +**工作区导航:** + +1. 在左侧导航面板中,展开**管理工作区**并选择**示例数据**。 +1. 选择**示例航班数据**图块和您要添加的任何其他图块中的**添加数据**按钮。 + +下图显示了可用的示例数据集。 + +![添加示例数据窗口](/images/dashboards/add-sample.png) + +::: info NOTE +如果您安装了示例数据,索引模式会自动创建,您可以开始[探索发现应用程序](/dashboards/getting-started/explore-discover)。 +::: + +### 摄取您自己的数据 + +OpenSearch Dashboards 从 OpenSearch 读取数据,因此您需要将自己的数据添加到 OpenSearch。使用批量 API、Data Prepper 或其他摄取工具将数据加载到 OpenSearch 中。有关更多信息,请参阅[摄取数据](/getting-started/ingest-data/)。 + +要从 OpenSearch Dashboards 发送 API 请求(如批量 API 请求),请使用开发工具控制台。有关更多信息,请参阅[在开发工具控制台中运行查询](/dashboards/getting-started/explore-dev-tools)。 + +摄取数据后,按照[步骤 2](#step-2-create-an-index-pattern) 中的描述为其创建索引模式。 + +## 步骤 2: 创建索引模式 + +索引模式告诉 OpenSearch Dashboards 要查询哪些索引。在使用您自己的数据的发现、可视化或仪表板之前,您至少需要一个索引模式。 + +要创建索引模式,请执行以下步骤: + +1. 在左侧导航菜单中,转到**管理** > **索引模式**。 +2. 选择**创建索引模式**。 +3. 输入索引名称或模式(例如,`my-index-*` 以匹配多个索引)。 +4. 选择**下一步**。 +5. 如果您的索引包含时间戳字段,请从**时间字段**下拉列表中选择它。对于本节中的示例,选择 `timestamp`。这将在发现和可视化中启用基于时间的过滤。 +6. 选择**创建索引模式**。 + +有关更多信息,请参阅[索引模式](/dashboards/management/index-patterns)。 + +## 进一步阅读 + +- 有关索引模式的更多信息,请参阅[索引模式](/dashboards/management/index-patterns)。 +- [连接数据源](/dashboards/management/data-sources)。 + +## 后续步骤 + +- 在[了解主要应用程序](/dashboards/getting-started/learn-dashboards)中了解每个应用程序。 diff --git a/i18n/zh/dashboards/getting-started/explore-dashboards.md b/i18n/zh/dashboards/getting-started/explore-dashboards.md new file mode 100644 index 00000000..3c3d9480 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/explore-dashboards.md @@ -0,0 +1,90 @@ +--- +title: 探索仪表板应用程序 +--- + +# 探索仪表板应用程序 + +**仪表板**应用程序允许您将多个可视化组合到单个页面中进行监控和分析。 + +使用**仪表板**,您可以: + +- 在单个视图中显示多个数据可视化。 +- 构建动态仪表板。 +- 创建和共享报告。 +- 嵌入分析以区分您的应用程序。 + +## 前提条件 + +本页面的示例使用 [**示例航班数据**](https://playground.opensearch.org/app/home#/tutorial_directory) 数据集,该数据集已安装在 [OpenSearch Playground](https://playground.opensearch.org/app/home#/) 中。 + +如果您正在使用本地安装的 OpenSearch Dashboards 且尚未添加示例数据,请参阅[准备数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 试一试: 探索预构建的仪表板 + +1. 在导航面板中,选择 **OpenSearch Dashboards** > **Dashboards**。面板显示现有仪表板的列表。 + +1. 在搜索工具栏中,搜索并选择 **[Flights] Global Flight Dashboard**。 + + 面板显示预加载了可视化的仪表板,包括图表、地图和数据表。 + +1. 要向仪表板添加其他面板,请选择**编辑**按钮,然后从工具栏中选择**添加**。 + +1. 在**添加面板**窗口的搜索工具栏中,输入 `flights`。 + +1. 从缩小的列表中,选择 **[Flights] Delay Buckets**。 + +1. 选择 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="叉号图标"/> (叉号) 退出确认对话框。 + +1. 选择 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="叉号图标"/> (叉号) 退出**添加面板**窗口。 + +1. 向下滚动以确认新添加的面板现在显示为仪表板上的最后一个面板。 + + 结果视图如下图所示。 + + *添加面板视图* + +### 添加您自己的可视化 + +如果您正在使用本地安装并在[探索可视化应用程序](/dashboards/getting-started/explore-visualize)中保存了 `Flight count over time` 可视化,您可以将其添加到此仪表板。由于 OpenSearch Playground 是只读的,因此无法在其中保存可视化。 + +要添加可视化,请执行以下步骤: + +1. 从工具栏选择**添加**。 +1. 在搜索工具栏中,输入 `Flight count over time`。 +1. 从列表中选择可视化。 + + 可视化作为仪表板上的最后一个面板添加,如下图所示。 + + *Flight count over time 面板添加到仪表板末尾* + +## 在仪表板应用程序中过滤数据 + +您可以与可视化交互来过滤数据。 + +使用 **[Flights] Global Flight Dashboard** 仪表板,按照以下步骤过滤示例航班数据: + +1. 在 **[Flights] Airline Carrier** 面板上,选择左下角的**切换图例**图标。然后选择 **OpenSearch-Air**,然后选择 <img src="/images/icons/plus-icon.png" class="inline-icon" alt="加号图标"/> (加号) 图标。 + + 仪表板自动更新,将过滤器 `Carrier: OpenSearch-Air` 添加到左上角的过滤器栏,如下图所示。 + + *按 OpenSearch-Air 航空公司过滤的仪表板* + +1. 选择**保存**以保存仪表板。 + +或者,您可以使用仪表板工具栏应用过滤器: + +1. 如果您使用前面的说明添加了过滤器,请首先选择过滤器栏中 `Carrier: OpenSearch-Air` 过滤器中的 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="叉号图标"/> (叉号) 以移除过滤器。 + +1. 在仪表板工具栏中,选择 **+ 添加过滤器**。 + +1. 从**字段**、**运算符**和**值**下拉列表中,分别选择 **Carrier**、**is** 和 **OpenSearch-Air**。 + +1. 选择**保存**。 + +## 进一步阅读 + +- 有关完整的仪表板参考,请参阅[创建仪表板](/dashboards/dashboard/)。 + +## 后续步骤 + +- 在[在开发工具控制台中运行查询](/dashboards/getting-started/explore-dev-tools)中了解如何运行 API 查询。 diff --git a/i18n/zh/dashboards/getting-started/explore-dev-tools.md b/i18n/zh/dashboards/getting-started/explore-dev-tools.md new file mode 100644 index 00000000..3976b984 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/explore-dev-tools.md @@ -0,0 +1,45 @@ +--- +title: 在开发工具控制台中运行查询 +--- + +# 在开发工具控制台中运行查询 + +开发工具控制台允许您向 OpenSearch 发送 [Query DSL](/query-dsl/) 查询,而不是在终端中使用 cURL。 + +## 试一试: 编写并运行查询 + +1. 要打开开发工具控制台,请在 OpenSearch Dashboards 主页上选择 **Dev Tools**,或从左侧导航菜单选择**管理** > **Dev Tools**。在启用工作区的安装中,选择导航面板左下角的代码图标 (代码图标)。 + +2. 在控制台左侧的编辑器窗格中编写查询。例如,输入以下查询来索引一些文档: + + ```json + POST _bulk + { "create": { "_index": "students", "_id": "2" } } + { "name": "Jonathan Powers", "gpa": 3.85, "grad_year": 2025 } + { "create": { "_index": "students", "_id": "3" } } + { "name": "Jane Doe", "gpa": 3.52, "grad_year": 2024 } + ``` + +3. 要发送查询,将光标放在查询文本中的任意位置,然后选择请求右上角的播放图标 (<img src="/images/dev-tools/play-icon.png" class="inline-icon" alt="播放图标"/>),或按 `Ctrl/Cmd+Enter`。 + + OpenSearch 在控制台右侧的窗格中显示响应。 + + *示例查询* + +4. 尝试搜索查询。输入以下请求以从 `students` 索引检索所有文档: + + ```json + GET students/_search + { + "query": { + "match_all": {} + } + } + ``` + +5. 选择播放图标发送请求并查看结果。 + +## 后续步骤 + +- 有关完整的开发工具参考,请参阅[开发工具](/dashboards/dev-tools/)。 +- 有关完整的查询语言参考,请参阅 [Query DSL](/query-dsl/)。 diff --git a/i18n/zh/dashboards/getting-started/explore-discover.md b/i18n/zh/dashboards/getting-started/explore-discover.md new file mode 100644 index 00000000..7fb975a8 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/explore-discover.md @@ -0,0 +1,58 @@ +--- +title: 探索发现应用程序 +--- + +# 探索发现应用程序 + +**发现**应用程序允许您交互式地搜索、过滤和检查数据。使用它来了解有哪些可用字段、数据如何随时间分布以及存在哪些模式。 + +使用**发现**,您可以: + +- 选择要分析的数据,设置该数据的时间范围,搜索数据并过滤结果。 +- 分析数据: 查询和过滤数据,在表格中查看结果,并检查文档。 +- 创建直方图以显示数据的分布。 + +在发现和仪表板应用程序的搜索栏中,您可以使用 [Dashboards 查询语言 (DQL)](/dashboards/dql) 编写查询---这是一种简单的基于文本的语言,用于使用字段名和值过滤数据。您也可以切换到[查询字符串 (Lucene) 语法](/query-dsl/full-text/query-string)。 + +## 前提条件 + +本页面的示例使用 [**示例航班数据**](https://playground.opensearch.org/app/home#/tutorial_directory) 数据集,该数据集已安装在 [OpenSearch Playground](https://playground.opensearch.org/app/home#/) 中。 + +如果您正在使用本地安装的 OpenSearch Dashboards 且尚未添加示例数据,请参阅[准备数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 试一试: 搜索和过滤航班数据 + +按照以下步骤使用**发现**应用程序: + +1. 在导航面板中,选择 **OpenSearch Dashboards** > **Discover**。 + +1. 在**发现**页面上,从左上角的下拉菜单中选择索引模式 `opensearch_dashboards_sample_data_flights`。 + +1. 选择 <img src="/images/icons/calendar-icon.png" class="inline-icon" alt="日历图标"/> (日历) 图标,将[时间过滤器](/dashboards/discover/time-filter)从默认的**最近 15 分钟**更改为**最近 7 天**。 + +1. 在 DQL 搜索栏中,输入以下查询: + + ```sql + FlightDelay:true AND DestCountry: US AND FlightDelayMin >= 60 + ``` + +1. 选择**更新**。 + + 显示延误 60 分钟或更长时间的美国目的地航班结果。 + +1. 通过从 DQL **搜索栏**选择 <img src="/images/icons/plus-icon.png" class="inline-icon" alt="加号图标"/> (加号) **添加过滤器**来过滤数据,然后从**编辑过滤器**弹出窗口的下拉列表中选择**字段**、**运算符**和**值**。例如,选择 `FlightDelayType`、**is** 和 **Weather Delay**。 + +1. 选择**保存**。 + + 结果视图如下图所示。 + + ![显示过滤后航班数据的发现输出](/images/dashboards/opensearch-dashboards-discover.png) + +## 进一步阅读 + +- 有关完整的发现参考,请参阅[使用发现探索数据](/dashboards/discover/index-discover)。 +- 有关 DQL 参考,请参阅 [Dashboards 查询语言](/dashboards/dql)。 + +## 后续步骤 + +- 使用[探索可视化应用程序](/dashboards/getting-started/explore-visualize)从数据创建可视化。 diff --git a/i18n/zh/dashboards/getting-started/explore-visualize.md b/i18n/zh/dashboards/getting-started/explore-visualize.md new file mode 100644 index 00000000..0010a8f2 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/explore-visualize.md @@ -0,0 +1,48 @@ +--- +title: 探索可视化应用程序 +--- + +# 探索可视化应用程序 + +**可视化**应用程序允许您使用点击式界面创建图表、地图、表格和其他数据的可视化表示。 + +## 前提条件 + +本页面的示例使用 [**示例航班数据**](https://playground.opensearch.org/app/home#/tutorial_directory) 数据集,该数据集已安装在 [OpenSearch Playground](https://playground.opensearch.org/app/home#/) 中。 + +如果您正在使用本地安装的 OpenSearch Dashboards 且尚未添加示例数据,请参阅[准备数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 试一试: 使用示例数据创建折线图 + +按照以下步骤使用**可视化**应用程序创建显示随时间变化的航班数量的折线图: + +1. 在左侧导航菜单中,选择 **OpenSearch Dashboards** > **Visualize**。 +2. 选择**创建可视化**。 +3. 在**新建可视化**对话框中,选择**折线图**。 +4. 在**选择源**对话框中,选择 **opensearch_dashboards_sample_data_flights**。 +5. 将时间过滤器设置为**最近 7 天**。 +6. 在**桶**下,选择**添加** > **X 轴**。 +7. 将**聚合**设置为**日期直方图**,将**字段**设置为 **timestamp**。 +8. 选择**更新**。图表显示每个时间间隔的航班数量,如下图所示。 + + *显示随时间变化的航班数量的折线图* + +9. 从工具栏选择**保存** (磁盘图标)。 + + ::: info NOTE + 由于 OpenSearch Playground 是只读的,因此无法在其中保存。 + ::: + +10. 在**保存可视化**对话框中,输入 `Flight count over time` 作为标题。 +11. 选择**保存**。 + +可视化已保存并显示在**可视化**列表中。 + +## 进一步阅读 + +- 有关完整的可视化参考,请参阅[在可视化应用程序中创建可视化](/dashboards/visualize/visualize-app/)。 +- 有关实践教程,请参阅[创建基于聚合的可视化](/dashboards/visualize/visualize-app/aggregation-based-viz)。 + +## 后续步骤 + +- 使用[探索仪表板应用程序](/dashboards/getting-started/explore-dashboards)将可视化组装到仪表板中。 diff --git a/i18n/zh/dashboards/getting-started/index.md b/i18n/zh/dashboards/getting-started/index.md new file mode 100644 index 00000000..cbc3cdeb --- /dev/null +++ b/i18n/zh/dashboards/getting-started/index.md @@ -0,0 +1,29 @@ +--- +title: 入门指南 +--- + +# OpenSearch Dashboards 入门指南 + +OpenSearch Dashboards 是 OpenSearch 的 Web 界面。使用它来探索数据、构建可视化、组装仪表板和运行查询。 + +::: info NOTE +在开始之前,请确保您熟悉基本的 OpenSearch 概念,如文档和索引。有关更多信息,请参阅 [OpenSearch 简介](/getting-started/intro/)。 +::: + +## 步骤 1: 设置 OpenSearch Dashboards + +选择以下选项之一。 + +### 选项 1: 使用 OpenSearch Playground + +在浏览器中打开 [OpenSearch Playground](https://playground.opensearch.org/app/home#/)。Playground 是只读的,已经包含示例航班数据,因此您可以在[步骤 2](#step-2-explore-opensearch-dashboards-applications) 中开始了解 OpenSearch Dashboards 应用程序。 + +### 选项 2: 使用您自己的安装 + +要安装 OpenSearch Dashboards 并添加示例数据,请执行以下步骤: + +## 步骤 2: 探索 OpenSearch Dashboards 应用程序 + +## 后续步骤 + +一旦您熟悉了应用程序,构建仪表板的标准方法遵循三个步骤:探索数据、构建单个可视化,然后将这些可视化组装到仪表板中。要详细了解每个步骤,请使用以下链接探索完整文档。 diff --git a/i18n/zh/dashboards/getting-started/install.md b/i18n/zh/dashboards/getting-started/install.md new file mode 100644 index 00000000..3d9ce502 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/install.md @@ -0,0 +1,27 @@ +--- +title: 安装 OpenSearch Dashboards +--- + +# 安装 OpenSearch Dashboards + +OpenSearch Dashboards 是 OpenSearch 的用户界面。要使用您自己的实例跟随教程,请按照以下步骤安装 OpenSearch 和 OpenSearch Dashboards。 + +## 步骤 1: 安装 OpenSearch 和 OpenSearch Dashboards + +选择以下选项之一: + +- 要使用 Docker 试用 OpenSearch 和 OpenSearch Dashboards,请按照[安装快速入门](/getting-started/quickstart/)进行操作。 + +- 要为生产环境安装 OpenSearch Dashboards,请首先使用[安装 OpenSearch](/install-and-configure/install-opensearch/) 中的方法之一安装 OpenSearch,然后使用[安装 OpenSearch Dashboards](/install-and-configure/install-dashboards/) 中的方法之一安装 OpenSearch Dashboards。 + +## 步骤 2 (可选): 配置 OpenSearch Dashboards + +您可以在 `opensearch_dashboards.yml` 文件中配置 OpenSearch Dashboards 设置。此文件控制服务器选项、身份验证、插件设置和[工作区](/dashboards/workspace/)等功能。更改配置文件后,重新启动 OpenSearch Dashboards 以使更改生效。 + +有关完整的设置列表,请参阅[配置 OpenSearch Dashboards](/install-and-configure/configuring-dashboards)。 + +某些设置也可以在 OpenSearch Dashboards 中更改,而无需编辑 `opensearch_dashboards.yml`。有关更多信息,请参阅[高级设置](/dashboards/management/advanced-settings)。 + +## 后续步骤 + +- 在[访问 OpenSearch Dashboards](/dashboards/getting-started/access) 中了解如何导航界面。 diff --git a/i18n/zh/dashboards/getting-started/learn-dashboards.md b/i18n/zh/dashboards/getting-started/learn-dashboards.md new file mode 100644 index 00000000..486c53c0 --- /dev/null +++ b/i18n/zh/dashboards/getting-started/learn-dashboards.md @@ -0,0 +1,40 @@ +--- +title: 了解主要应用程序 +--- + +# 了解主要应用程序 + +OpenSearch Dashboards 提供了多个用于处理数据的应用程序。标准工作流程是探索数据、构建单个可视化,然后将这些可视化组装到仪表板中。 + +## 发现应用程序 + +**发现**应用程序允许您交互式地搜索、过滤和检查数据。使用它来了解有哪些可用字段、数据如何随时间分布以及存在哪些模式。 + +![显示按延误过滤的航班数据的发现应用程序](/images/dashboards/opensearch-dashboards-discover.png) + +## 可视化应用程序 + +**可视化**应用程序允许您使用点击式界面创建图表、地图、表格和其他数据的可视化表示。您选择可视化类型,配置指标和桶,并调整显示设置。 + +*在可视化应用程序中创建的折线图* + +## 仪表板应用程序 + +**仪表板**应用程序允许您将多个可视化组合到单个页面中进行监控和分析。您可以添加现有可视化、创建新可视化、调整面板大小和位置,以及应用同时影响所有面板的过滤器。 + +*包含多个可视化面板的仪表板* + +## 开发工具 + +**开发工具**控制台允许您直接使用 [Query DSL](/query-dsl/) 运行 OpenSearch API 查询。使用它来测试查询、管理索引和执行集群操作,而无需离开浏览器。 + +![显示查询和响应的开发工具控制台](/images/dev-tools/dev-tools-response.png) + +## 后续步骤 + +要尝试每个应用程序,请按顺序跟随以下页面或直接转到您想要了解的应用程序: + +1. [探索发现应用程序](/dashboards/getting-started/explore-discover) +1. [探索可视化应用程序](/dashboards/getting-started/explore-visualize) +1. [探索仪表板应用程序](/dashboards/getting-started/explore-dashboards) +1. [在开发工具控制台中运行查询](/dashboards/getting-started/explore-dev-tools) diff --git a/i18n/zh/dashboards/integrations/index.md b/i18n/zh/dashboards/integrations/index.md new file mode 100644 index 00000000..48cd8024 --- /dev/null +++ b/i18n/zh/dashboards/integrations/index.md @@ -0,0 +1,90 @@ +--- +title: 集成 +--- + +# OpenSearch Dashboards 集成 +<Badge type="tip" text="2.9 版本引入" /> + +OpenSearch Dashboards 中的**集成**应用程序提供了一个用户友好的平台,用于数据可视化、查询和投影资源数据,例如流日志。_集成资产_,如 NGINX 或 Amazon Virtual Private Cloud (VPC),包含元数据、数据映射和可视化的捆绑包,简化了资源数据的监控,无需冗余的配置步骤。 + +下图显示了 OpenSearch Dashboards 中可用的集成资产。 + +*OpenSearch Dashboards 中可用的集成资产* + +## 用例 + +**集成**考虑了跨多个领域的既定数据模式,为您提供无缝的数据映射和集成,适用于各种用例,例如电商产品搜索、可观测性监控(例如,跟踪和指标分析)以及安全监控和威胁分析。 + +## 用于可观测性的 OpenTelemetry 协议 + +一致的遥测数据模式对于有效的可观测性至关重要,使跨应用程序、服务和基础设施组件的数据关联和分析成为可能,以提供系统行为和性能的整体视图。 + +OpenSearch 采用 [OpenTelemetry (OTel)](https://opentelemetry.io/) 协议作为其可观测性解决方案的基础。OTel 是一个社区驱动的标准,为指标、日志和跟踪定义了一致的模式和数据收集方法。它得到 API、SDK 和遥测收集器的广泛支持,支持自动仪器化等功能,实现无缝的可观测性集成。 + +这种共享模式允许跨不同数据源的交叉关联和分析。为此,OpenSearch 派生了[简单可观测性模式](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/schema/observability),它将 OTel 标准编码为 OpenSearch 映射。OpenSearch 还支持[管道处理语言 (PPL)](/search-plugins/sql/ppl/),它专为可观测性用例中的高维查询而设计。 + +## 摄取数据 + +摄取到 OpenSearch 的数据必须符合数据集成及其关联仪表板支持的模式。需要兼容的数据管道,例如以下: + +- [Data Prepper](https://github.com/opensearch-project/data-prepper) +- [OpenTelemetry Collector](https://github.com/open-telemetry/opentelemetry-collector) +- [Fluent Bit for OpenSearch](https://docs.fluentbit.io/manual/pipeline/outputs/opensearch) + +这些管道使用 OTel 模式(或简单模式)将信号文档索引到表示观察到的资源信号的正确索引中。有关索引命名约定,请参阅[命名约定](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/schema/observability/Naming-convention.md)。 + +### 摄取结构 + +每个集成资产包含以下元数据和资产: + +* 名称和描述 +* 源 URL 和许可证 +* 模式规范,例如,映射或组件映射 +* 用于测试功能的示例数据 +* 资产,如仪表板、索引模式、查询或警报 + +## 安装集成资产 + +集成资产可以直接从每个 OpenSearch 版本附带的[默认目录](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/integrations/Release.md)安装。 + +要安装资产,请执行以下步骤: + +1. 转到**集成** > **可用**以查看可用选项。 +2. 选择一个工具,例如 **NGINX** 或 **Amazon VPC**。您可以选择**添加**以使用预打包的集成资产添加或配置新的数据集成。您可以选择**试用**以在完全添加之前测试或探索集成。 +3. 在**可用**页面上,选择**类别**下拉菜单以过滤集成列表。 + +### 试用演示 + +要试用预打包的集成资产,请执行以下步骤: + +1. 在**集成**页面上,选择 **NGINX**。 +2. 选择**试用**按钮。**试用**选项会自动创建示例索引模板,向模板添加示例数据,然后基于该数据创建集成。 +3. 从**资产列表**中选择一个资产。资产包括仪表板、索引模式和可视化。 +4. 预览数据可视化和示例数据详细信息。下图显示了一个示例。 + + *带有可视化的集成仪表板* + +## 加载自定义集成资产 + +要加载自定义集成资产,请执行以下步骤: + +1. 从[目录存储库](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/integrations/Release.md)下载集成工件。 +2. 转到 **Dashboards 管理** > **保存的对象**。 +3. 在右上角工具栏菜单上选择**导入**,导航到保存集成工件的文件夹,然后选择文件(扩展名为 .ndjson 的文件)。下图显示了此步骤的示例。 + *导入文件夹窗口* +4. 选择您上传的保存的对象以确认它已上传到**保存的对象**。下图显示了此步骤的示例。 + *集成保存的对象列表* + +## 开发者资源 + +有关示例代码、文章、教程和 API 参考,请参阅以下开发者资源: + +- [OpenSearch 集成存储库](https://github.com/opensearch-project/opensearch-catalog) +- [OpenSearch 集成参考文档](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/integrations) +- [OpenSearch 可观测性目录](https://htmlpreview.github.io/?https://github.com/opensearch-project/opensearch-catalog/blob/main/integrations/observability/catalog.html) +- [OpenSearch 可观测性目录发布页面](https://github.com/opensearch-project/opensearch-catalog/blob/main/docs/integrations/Release.md) +- [简单可观测性模式](https://github.com/opensearch-project/opensearch-catalog/tree/main/docs/schema/observability) + +## 后续步骤 + +- 要请求目录中不可用的集成,请提交[集成请求](https://github.com/opensearch-project/dashboards-observability/issues/new?assignees=&labels=integration%2C+untriaged&projects=&template=integration_request.md&title=%5BIntegration%5D)。 diff --git a/i18n/zh/dashboards/management/acl.md b/i18n/zh/dashboards/management/acl.md new file mode 100644 index 00000000..2ab76c7a --- /dev/null +++ b/i18n/zh/dashboards/management/acl.md @@ -0,0 +1,71 @@ +--- +title: 保存对象的访问控制列表 +--- + +# 保存对象的访问控制列表 +<Badge type="tip" text="2.18 版本引入" /> + +您可以使用访问控制列表 (ACL) 管理保存对象的权限,提供授权 (AuthZ) 功能,而无需后端插件集成。 + +## 了解 ACL 类型 + +ACL 在两个级别应用: + +1. **工作区 ACL:** 工作区对象从其父工作区继承权限。有关更多信息,请参阅[工作区 ACL](/dashboards/workspace/workspace-acl)。 +2. **对象 ACL:** 每个单独的对象可以有自己的 ACL 策略。对这些对象的所有操作都必须通过 ACL 策略验证。 + +## 启用 ACL 功能 + +在定义任何访问控制之前,必须先启用 ACL 功能。通过以下方式启用: + +1. 打开您的 `opensearch_dashboards.yml` 文件。 +2. 使用 `savedObjects.permission.enabled: true` 启用权限。 + +## 定义 ACL 权限 + +使用以下模式定义 ACL 权限: + +```json +{ + "permissions": { + "<permission_type_1>": { + "users": ["<principal_1>", "<principal_2>"], + "groups": ["<principal_3>", "<principal_4>"] + } + } +} +``` + +### 向已认证用户授予权限 + +通配符 (`*`) 向所有已认证用户授予权限。在以下示例中,ACL 向 `finance_manager` 组授予工作区管理权限,向 `finance_analyst` 组授予仪表板创建权限: + +```json +{ + "permissions": { + "write": { + "groups": ["finance_manager"] + }, + "library_write": { + "groups": ["finance_analyst"] + } + } +} +``` + +### 配置混合级别权限 + +要允许一个用户(例如 `user-1`)修改对象,同时为其他用户提供只读访问权限,您可以按如下方式配置 ACL 策略: + +```json +{ + "permissions": { + "read": { + "users": ["*"] + }, + "write": { + "users": ["user-1"] + }, + } +} +``` diff --git a/i18n/zh/dashboards/management/connect-prometheus.md b/i18n/zh/dashboards/management/connect-prometheus.md new file mode 100644 index 00000000..743179f1 --- /dev/null +++ b/i18n/zh/dashboards/management/connect-prometheus.md @@ -0,0 +1,72 @@ +--- +title: 将 Prometheus 连接到 OpenSearch +--- + +# 将 Prometheus 连接到 OpenSearch +<Badge type="tip" text="2.16 版本引入" /> + +您可以将 OpenSearch 连接到 Prometheus 服务器并在 OpenSearch Dashboards 中查询其指标。OpenSearch 不会复制指标。相反,SQL 插件在您运行查询时将每个查询发送到 Prometheus,因此 Prometheus URI 必须可从 OpenSearch 节点访问。 + +## 前提条件 + +在创建连接之前,请确保已完成以下前提条件: + +- 在所有 OpenSearch 节点上设置 `plugins.query.datasources.encryption.masterkey` 设置。OpenSearch 使用此密钥加密存储的连接凭据,如果未设置密钥,则拒绝创建或更新连接的请求。有关更多信息,请参阅[前提条件](/dashboards/management/data-sources#prerequisites)。 +- 确认您具有所需的[权限](/dashboards/management/data-sources#permissions)。 + +## 创建 Prometheus 连接 + +要创建 Prometheus 连接,请执行以下步骤: + +1. 在主菜单中,转到**管理** > **Dashboards 管理** > **数据源**。 +1. 选择**创建直接查询连接** > **Prometheus**。 +1. 在**数据源详情**部分,输入**数据源名称**和可选的描述。您在查询中使用此名称引用连接,例如 `source = my_prometheus.prometheus_http_requests_total`。 +1. 在 **Prometheus 数据位置**部分,输入 **Prometheus URI**,例如 `http://prometheus.example.com:9090`。 +1. 在**身份验证详情**部分,选择**身份验证方法**: + - **无身份验证**: OpenSearch 不使用凭据连接到 Prometheus。 + - **基本身份验证**: 输入**用户名**和**密码**。 + - **AWS 签名版本 4**: 输入**身份验证区域**、**访问密钥**和**密钥**。将此方法用于 Amazon Managed Service for Prometheus。 +1. 在**查询权限**部分,选择**查询访问级别**: + - **仅管理员**: 只有管理员用户可以查询连接。这是默认设置。 + - **受限**: 具有您选择的 OpenSearch 角色的用户可以查询连接。此选项仅在安装了安全插件时可用。 +1. 选择**连接到 Prometheus**。 + +新连接显示在数据源列表中。 + +您也可以使用 `_plugins/_query/_datasources` API 创建连接。有关示例,请参阅[指标分析](/observing-your-data/prometheusmetrics#configuring-a-prometheus-connection-using-the-api)。 + +## 查询 Prometheus 指标 + +要查询指标,请在**数据源**页面上选择连接,然后选择**查询数据**。可观测性中的**指标**页面打开,您可以在其中可视化 Prometheus 指标。您也可以使用管道处理语言 (PPL) 查询它们。有关更多信息,请参阅[指标分析](/observing-your-data/prometheusmetrics)。 + +## 更改连接的访问权限 + +要更改哪些用户可以查询连接,请在**数据源**页面上选择连接。在**访问控制**选项卡上,选择**编辑**,更新**查询访问级别**,然后保存更改。 + +## 更新连接 + +OpenSearch Dashboards 不支持编辑现有连接的 Prometheus URI 或凭据。要更新它们,请向 `_plugins/_query/_datasources` API 发送请求。以下请求更改 `my_prometheus` 连接的 Prometheus URI: + +```json +PATCH _plugins/_query/_datasources +{ + "name": "my_prometheus", + "properties": { + "prometheus.uri": "http://prometheus.example.com:9090" + } +} +``` + +## 删除连接 + +如果在 OpenSearch Dashboards 中启用了[多数据源](/dashboards/management/multi-data-sources),您可以在**数据源**页面上删除连接。在**直接查询连接**选项卡上,选择连接,选择**删除 1 个连接**,然后确认删除。此选项卡仅列出在 OpenSearch Dashboards 中创建的连接。 + +否则,使用 API 删除连接: + +```json +DELETE _plugins/_query/_datasources/my_prometheus +``` + +## 相关文档 + +- [指标分析](/observing-your-data/prometheusmetrics) diff --git a/i18n/zh/dashboards/management/resource-sharing.md b/i18n/zh/dashboards/management/resource-sharing.md new file mode 100644 index 00000000..ce18f96a --- /dev/null +++ b/i18n/zh/dashboards/management/resource-sharing.md @@ -0,0 +1,151 @@ +--- +title: 资源访问管理 +--- + +# 资源访问管理 +<Badge type="tip" text="3.3 版本引入" /> + +OpenSearch Dashboards 中的资源共享为插件定义的各个资源提供细粒度的文档级访问控制。此功能扩展了 OpenSearch 基于角色的访问控制,允许资源所有者指定谁可以访问资源以及他们拥有什么级别的访问权限,包括只读或读写权限。使用 OpenSearch Dashboards 进行日常访问管理,使用**开发工具**控制台进行自动化和批量操作。 + +::: info NOTE +如果资源共享功能在 OpenSearch Dashboards 中不可见,请联系您的 OpenSearch 管理员启用该功能并分配适当的权限。 +::: + +**资源**是插件创建并存储在受保护系统索引中的文档,例如机器学习 (ML) 模型组、异常检测器、报告定义或 Flow Framework 工作流。 + +下表列出了默认资源访问权限,这由用户的角色和与资源的关系决定。 + +| 用户 | 访问权限 | +|---|---| +| 资源创建者 | 完全访问权限(查看、编辑、删除和共享) | +| 超级管理员 | 完全访问权限 | +| 其他用户 | 除非资源与他们共享,否则无访问权限 | + +在您与特定用户、角色或后端角色共享资源后,该资源对这些用户在 OpenSearch Dashboards 中变得可见,OpenSearch Dashboards 根据每个用户的身份、权限和资源共享配置过滤资源列表。 + +## 前提条件 + +要在 OpenSearch Dashboards 中使用资源共享,您必须满足以下前提条件: + +* 管理员已授予您资源插件的集群权限。您需要这些权限来创建资源。 +* 您拥有资源、您是超级管理员,或者所有者已与您共享资源。 +* 管理员已启用以下设置: + ```yaml + plugins.security.resource_sharing.enabled: true + plugins.security.resource_sharing.protected_types: ["<resource-type>"] + plugins.security.system_indices.enabled: true + ``` + + 有关这些设置的更多信息,请参阅[配置资源共享](/security/access-control/resources/#configuring-resource-sharing)。 + +## 管理所有资源类型的访问 + +**资源访问管理**页面列出了您可以访问的任何受保护类型的资源,并允许您在一个地方管理它们的共享。按照以下步骤查看和管理资源的访问: + +1. 在顶部菜单中,转到**管理** > **资源访问管理**。 + +1. 在**资源**面板的右上角,从下拉列表中选择资源类型。表格列出了该类型中您可以访问的资源,并在**所有者**列中显示每个资源的所有者。**共享对象**列列出了资源共享的用户、角色和后端角色及其访问级别,如果资源是私有的则显示**未共享**。如果没有资源显示,请创建资源或请管理员或资源所有者与您共享一个。 + + 下图显示了异常检测器资源类型的**资源**面板。 + + *资源面板列出异常检测器及其资源 ID、所有者以及每个检测器共享的用户和角色* + +1. 在**操作**列中,为私有资源选择**共享**,或为已共享的资源选择**更新访问**。这些选项仅对您拥有的资源或所有者授予您共享权限的资源显示。超级管理员可以共享任何资源。 + +1. 在**共享资源**或**更新访问**对话框中,从**访问级别**下拉列表中选择访问级别。在**共享资源**对话框中,首先选择**添加访问级别**以显示字段。 + +1. 在**用户**、**角色**和**后端角色**字段中输入您要授予此级别访问权限的用户、角色和后端角色。要向所有用户授予访问权限,请在**用户**字段中输入星号 (`*`)。 + +1. 要向另一组用户授予不同级别的访问权限,请选择**添加访问级别**并重复前面两个步骤。要删除访问级别,请选择**移除**。 + +1. 选择**共享**或**更新访问**以应用更改。移除访问权限会立即对受影响的用户隐藏资源。 + +## 从插件页面管理访问 +<Badge type="tip" text="3.9 版本引入" /> + +当为资源类型启用资源共享时,您可以直接从插件的资源列表管理对资源的访问。 + +下表列出了支持从其插件资源列表进行访问管理的资源,并链接到每个资源可用的访问级别。 + +| 插件 | 资源 | +|---|---| +| 告警 | [监控器和工作流](/observing-your-data/alerting/alerting-access-control) | +| 异常检测 | [检测器](/observing-your-data/ad/detector-access-control)和[预测器](/observing-your-data/forecast/forecaster-access-control) | +| Flow Framework | [工作流](/vector-search/ai-search/workflows/workflow-access-control/) | +| ML Commons | [模型组](/ml-commons-plugin/model-sharing-access-control) | +| 通知 | [通道](/observing-your-data/notifications/notification-access-control) | +| 报告 | [报告定义](/dashboards/reporting/report-definition-access-control)和[报告](/dashboards/reporting/report-instance-access-control) | +| 安全分析 | [检测器和关联规则](/security-analytics/resource-access-control) | + +::: info NOTE +只有当您是资源的所有者、超级管理员或所有者授予您共享权限的用户时,您才能共享资源。 +::: + +### 共享资源 + +要从插件页面共享资源,请执行以下步骤: + +1. 打开支持的插件的资源列表。例如,在顶部菜单中,转到 **OpenSearch 插件** > **异常检测**,然后选择**检测器**。 + +1. 在**访问**列中,查看每个资源的共享状态。每个资源显示**私有**或**共享**状态。您有权共享的资源还会显示共享图标,如下图所示。 + + *检测器列表显示访问列,包含私有和共享状态以及共享图标* + +1. 选择要管理的资源的共享图标。 + +1. 在**管理访问**对话框中,配置以下值: + + 1. 从**访问级别**下拉列表中选择访问级别。可用级别因资源类型而异。 + + 1. 在**用户**字段中,输入用户名并按 Enter。要在选定的访问级别与所有用户共享资源,请输入星号 (`*`)。 + + 1. 要与角色或后端角色共享资源,请展开**高级访问选项**并在**角色**或**后端角色**字段中输入角色名称。 + + 1. 要在多个访问级别共享资源,请选择**添加访问级别**并重复前面的步骤。每个级别维护自己的用户、角色和后端角色。要删除级别,请选择**移除级别**。 + + 1. 选择**保存更改**。 + +### 将资源设为私有 + +要停止共享资源,请执行以下步骤: + +1. 在**访问**列中,选择资源的共享图标。 + +1. 在**管理访问**对话框的**移除所有共享**部分中,选择**移除访问**。 + +资源状态返回**私有**,之前共享的用户、角色和后端角色将无法再访问它。 + +## 列出与您共享的资源 + +OpenSearch Dashboards 仅显示您可以访问的资源,因此不需要额外操作。在以下任何情况下,资源都会出现在您的资源列表中: + +* 您拥有该资源。 +* 所有者已明确与您共享该资源。 +* 所有者已与您的角色或后端角色之一共享该资源。 +* 该资源与所有用户共享。 + +在所有情况下,列出资源还需要资源插件的集群权限。 + +## 使用 API 管理资源共享 + +您可以使用 REST API 以编程方式管理资源共享。这些操作只能在您是所有者、超级管理员或拥有资源共享访问权限时执行。您可以使用命令行或**开发工具**控制台发送 API 请求。 + +有关完整的 API 文档,包括端点、参数和示例,请参阅[资源共享 API](/security/access-control/resource-sharing-api/)。 + +## 故障排除 + +使用下表排除常见问题。 + +| 问题 | 可能原因 | 解决方案 | +|---|---|---| +| **资源访问管理**页面不可见。| 该功能已禁用。| 请管理员启用 `plugins.security.resource_sharing.enabled`。| +| 您无法创建资源。| 您没有资源插件的集群权限。| 请管理员将您映射到授予这些权限的角色。| +| 您无法访问资源。| 该资源未与您共享。| 请所有者以适当的访问级别与您共享该资源。| +| API 请求返回 `403` 错误。| 该资源未与您共享。| 请所有者以适当的访问级别与您共享该资源。| +| 资源未在 OpenSearch Dashboards 中列出。| 该资源类型未标记为受保护。| 请管理员将该资源类型添加到 `plugins.security.resource_sharing.protected_types`。| +| 更新访问无效。| 该访问级别对资源类型无效。| 根据资源插件的文档验证访问级别。| + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于编程管理的 REST API 参考 diff --git a/i18n/zh/dashboards/management/saved-objects-api.md b/i18n/zh/dashboards/management/saved-objects-api.md new file mode 100644 index 00000000..f29e8ee2 --- /dev/null +++ b/i18n/zh/dashboards/management/saved-objects-api.md @@ -0,0 +1,605 @@ +--- +title: 保存对象 API +--- + +# 保存对象 API + +使用保存对象 API 列出、检索、创建、更新、导出和导入保存的对象,例如在集群之间复制一组可视化或清点集群包含的可视化。 + +这些端点由 OpenSearch Dashboards 而不是 OpenSearch 提供服务,因此将它们发送到 OpenSearch Dashboards 主机和端口(默认为 `5601`),而不是 OpenSearch REST 端口。使用 `POST`、`PUT` 或 `DELETE` 的请求需要 `osd-xsrf: true` 标头。为 Kibana OSS 编写的脚本会发送 `kbn-xsrf: true` 标头,OpenSearch Dashboards 会拒绝这些请求并显示错误 `Request must contain a osd-xsrf header`。要修复此错误,请在脚本中将 `kbn-xsrf` 替换为 `osd-xsrf`。 + +使用 `curl` 发送这些请求,如本页示例所示。要在没有 `curl` 的情况下运行 `GET` 端点,请在您已登录 OpenSearch Dashboards 的浏览器地址栏中输入其完整 URL。 + +::: info NOTE +开发工具控制台无法调用这些端点,因为它将每个请求转发到 OpenSearch REST 端口,而该端口不存在保存对象路径。 +::: + +如果启用了安全插件,请使用 `-u` 选项传递凭据,如果集群使用自签名证书,请添加 `-k`: + +```bash +curl -k -u admin:<password> "https://localhost:5601/api/saved_objects/_find?type=visualization" +``` + +如果 OpenSearch Dashboards 从基本路径提供服务,例如在代理后面运行或在托管服务上运行时,请在请求中包含该基本路径,例如 `https://<host>/_dashboards/api/saved_objects/_find`。 + +::: info NOTE +这些 API 返回可视化的定义,例如其聚合和索引模式引用。它们不运行可视化或返回其显示的数据。要将保存的搜索的基础行导出为 CSV 或 Excel 文件,请参阅[报告 API](/dashboards/reporting/api)。 +::: + +要从 OpenSearch Dashboards 导出和导入相同的对象,请参阅[导出和导入保存的对象](/dashboards/management/saved-objects)。 + +## 选择租户 + +启用多租户时,每个租户都有自己的保存对象集。在 `securitytenant` 标头中发送租户名称以使用特定租户的保存对象: + +```bash +curl -k -u admin:<password> -H 'securitytenant: global' "https://localhost:5601/api/saved_objects/_find?type=dashboard&fields=title" +``` + +全局租户使用 `global`,请求用户的私有租户使用 `__user__`。 + +省略标头的请求由以下租户中第一个适用的租户提供服务: + +1. 请求会话 cookie 中记录的租户。 +2. 为集群配置的默认租户。 +3. 用户可以访问的首选租户列表中的第一个租户。 +4. 全局租户。 +5. 请求用户的私有租户。 + +`curl` 请求不携带会话 cookie,因此在默认配置下由全局租户提供服务。 + +将租户作为查询参数传递不起作用,因为保存对象端点没有定义: `securitytenant` 或 `security_tenant` 查询参数会被拒绝并返回 `400` 错误。有关租户的更多信息,请参阅 [OpenSearch Dashboards 多租户](/security/multi-tenancy/tenant-index)。 + +## 查找保存的对象 + +查找保存对象 API 搜索一种或多种类型的保存对象。 + +### 端点 + +```json +GET {osd_host}:{port}/api/saved_objects/_find +``` + +### 查询参数 + +下表列出了可用的查询参数。除 `type` 外,所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `type` | String | 要搜索的保存对象类型,例如 `visualization`、`dashboard`、`search` 或 `index-pattern`。重复该参数以搜索多种类型。必需。| +| `search` | String | 用于过滤结果的查询字符串,例如 `Sales*`。| +| `search_fields` | String | 要与 `search` 值匹配的字段,例如 `title`。| +| `fields` | String | 要包含在响应中的对象属性。重复该参数以返回多个属性。仅返回 `title` 可保持响应较小。| +| `per_page` | Integer | 每页结果数。默认为 `20`。| +| `page` | Integer | 要返回的结果页面。默认为 `1`。| +| `sort_field` | String | 用于排序结果的字段,例如 `updated_at`。| + +### 示例请求 + +以下请求列出集群中的可视化并仅返回其标题: + +```bash +curl "http://localhost:5601/api/saved_objects/_find?type=visualization&fields=title&per_page=5" +``` + +### 示例响应 + +```json +{ + "page": 1, + "per_page": 5, + "total": 1, + "saved_objects": [ + { + "type": "visualization", + "id": "test-viz", + "attributes": { + "title": "Sales by customer" + }, + "references": [ + { + "name": "kibanaSavedObjectMeta.searchSourceJSON.index", + "id": "ecommerce-test-pattern", + "type": "index-pattern" + } + ], + "migrationVersion": { + "visualization": "7.10.0" + }, + "updated_at": "2026-09-02T19:35:47.635Z", + "version": "WzI5LDdd", + "namespaces": ["default"], + "score": null + } + ] +} +``` + +### 响应体字段 + +下表列出了响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `total` | Integer | 匹配搜索的保存对象数量。| +| `saved_objects` | Array | 匹配的保存对象。| +| `saved_objects.id` | String | 保存对象的 ID。创建报告定义时,使用此 ID 作为报告源 ID。| +| `saved_objects.type` | String | 保存对象的类型。| +| `saved_objects.attributes` | Object | 保存对象的定义,由 `fields` 参数过滤。| +| `saved_objects.references` | Array | 此对象依赖的其他保存对象,例如其索引模式。| +| `saved_objects.updated_at` | String | 保存对象上次更新的时间。| + +## 获取保存的对象 + +获取保存对象 API 按类型和 ID 检索单个保存对象。 + +### 端点 + +```json +GET {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### 示例请求 + +```bash +curl "http://localhost:5601/api/saved_objects/visualization/test-viz" +``` + +要在一个请求中检索多个保存对象,请将其类型和 ID 发送到 `_bulk_get` 端点: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_bulk_get" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '[{"type": "visualization", "id": "test-viz", "fields": ["title"]}]' +``` + +## 创建保存的对象 + +创建保存对象 API 创建保存的对象。提供 ID 以控制对象的 ID,或省略以自动生成一个。 + +::: info NOTE +使用此 API 创建对象需要拥有类型的应用程序期望的相同属性,这些属性不是公共合同的一部分。从工作实例导出对象并将它们导入到其他地方,而不是手动组合可视化或仪表板。 +::: + +### 端点 + +```json +POST {osd_host}:{port}/api/saved_objects/{type} +POST {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `overwrite` | Boolean | 是否替换已具有指定 ID 的对象。默认为 `false`,当 ID 正在使用时返回 `409` 错误。| + +### 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `attributes` | Object | 对象的定义,采用对象类型期望的格式。必需。| +| `references` | Array | 此对象依赖的其他保存对象,每个都有 `name`、`type` 和 `id`。可选。| + +### 示例请求 + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/visualization/sales-by-region" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{ + "attributes": { + "title": "Sales by region", + "visState": "{\"type\":\"pie\"}", + "kibanaSavedObjectMeta": {"searchSourceJSON": "{}"} + }, + "references": [ + { + "name": "kibanaSavedObjectMeta.searchSourceJSON.index", + "type": "index-pattern", + "id": "ecommerce-test-pattern" + } + ] + }' +``` + +### 示例响应 + +```json +{ + "type": "visualization", + "id": "sales-by-region", + "attributes": { + "title": "Sales by region", + "visState": "{\"type\":\"pie\"}", + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{}" + } + }, + "references": [ + { + "name": "kibanaSavedObjectMeta.searchSourceJSON.index", + "type": "index-pattern", + "id": "ecommerce-test-pattern" + } + ], + "migrationVersion": { + "visualization": "7.10.0" + }, + "updated_at": "2026-09-08T20:30:46.728Z", + "version": "WzcxLDhd", + "namespaces": ["default"] +} +``` + +要在一个请求中创建多个对象,请将它们发送到 `_bulk_create` 端点,该端点接受相同的 `overwrite` 参数: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_bulk_create" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '[{"type": "visualization", "id": "sales-by-day", "attributes": {"title": "Sales by day", "visState": "{}", "kibanaSavedObjectMeta": {"searchSourceJSON": "{}"}}}]' +``` + +响应在 `saved_objects` 数组中包含创建的对象。 + +## 更新保存的对象 + +更新保存对象 API 更新现有保存对象的属性。您发送的字段替换对象的相应字段,您省略的字段保持不变。 + +### 端点 + +```json +PUT {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `attributes` | Object | 要更新的对象字段。必需。| +| `references` | Array | 要替换的引用。发送此字段会替换对象的整个引用列表。可选。| + +### 示例请求 + +```bash +curl -X PUT "http://localhost:5601/api/saved_objects/visualization/sales-by-region" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{"attributes": {"title": "Sales by region and month"}}' +``` + +### 示例响应 + +响应包含更新的字段而不是完整对象: + +```json +{ + "id": "sales-by-region", + "type": "visualization", + "updated_at": "2026-09-08T20:30:47.950Z", + "version": "WzczLDhd", + "namespaces": ["default"], + "attributes": { + "title": "Sales by region and month" + } +} +``` + +## 删除保存的对象 + +删除保存对象 API 删除保存的对象。删除其他对象引用的对象(例如可视化使用的索引模式)会使这些对象缺少引用。在删除对象之前,使用 **Dashboards 管理** > **保存的对象**中的**关系**操作或[查找保存对象 API](#查找保存的对象) 返回的 `references` 字段检查依赖于该对象的内容。 + +### 端点 + +```json +DELETE {osd_host}:{port}/api/saved_objects/{type}/{id} +``` + +### 示例请求 + +```bash +curl -X DELETE "http://localhost:5601/api/saved_objects/visualization/sales-by-day" \ + -H 'osd-xsrf: true' +``` + +### 示例响应 + +```json +{} +``` + +## 导出保存的对象 + +导出保存对象 API 将保存的对象导出为换行符分隔的 JSON (NDJSON)。每行是一个保存对象,最后一行总结导出。 + +导出仅包含服务请求的租户的对象,因此每个租户的备份需要每个租户一个请求。有关更多信息,请参阅[选择租户](#选择租户)。 + +### 端点 + +```json +POST {osd_host}:{port}/api/saved_objects/_export +``` + +### 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `type` | String 或 Array | 要导出的保存对象类型,例如 `visualization`。提供 `type` 或 `objects`。| +| `objects` | Array | 要导出的特定保存对象,每个都有 `type` 和 `id`。提供 `type` 或 `objects`。| +| `includeReferencesDeep` | Boolean | 是否也导出导出对象依赖的对象,例如其索引模式。设置为 `true` 以便可以将导出导入到尚未包含这些引用的集群中。可选。默认为 `false`。| +| `search` | String | 将导出限制为匹配对象的查询字符串,例如 `Sales*`。与 `type` 一起使用。可选。| +| `excludeExportDetails` | Boolean | 是否省略输出末尾的摘要行。可选。默认为 `false`。| +| `workspaces` | Array | 要从中导出对象的工作区。与 `type` 一起使用。可选。| + +发送到工作区路径的请求限于该工作区,即使请求体省略 `workspaces`: + +```json +POST {osd_host}:{port}/w/{workspace_id}/api/saved_objects/_export +``` + +相同的路径前缀将导入的对象与工作区关联,因此您可以使用它代替[导入保存对象 API](#导入保存的对象) 的 `workspaces` 查询参数。 + +发送到工作区路径的请求可以导出该工作区的对象和不属于任何工作区的对象。在 `objects` 中请求不同工作区的对象会返回以下错误: + +```json +{"statusCode": 400, "error": "Bad Request", "message": "Bad Request", "attributes": {"objects": [{"id": "test-viz", "type": "visualization", "attributes": {}, "references": [], "error": {"statusCode": 403, "error": "Forbidden", "message": "Saved object does not belong to the workspace"}}]}} +``` + +### 示例请求 + +以下请求导出一个可视化及其引用的索引模式: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_export" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{"objects": [{"type": "visualization", "id": "test-viz"}], "includeReferencesDeep": true}' \ + -o export.ndjson +``` + +要导出每个可视化而不是特定的,请将 `objects` 替换为 `"type": "visualization"`。 + +### 示例响应 + +NDJSON 输出的最后一行总结导出: + +```json +{"exportedCount": 2, "missingRefCount": 0, "missingReferences": []} +``` + +### 导出所有保存的对象 + +要备份整个 OpenSearch Dashboards 实例,请列出要导出的类型: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_export" \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -d '{"type": ["config", "index-pattern", "search", "visualization", "dashboard", "url", "query"], "includeReferencesDeep": true}' \ + -o backup.ndjson +``` + +启用多租户时,如[选择租户](#选择租户)中所述,对每个租户重复请求。 + +已安装的插件注册其他类型,因此一个实例中可用的类型可能与另一个实例中的不同。要查看实例包含的类型,请查看 **Dashboards 管理** > **保存的对象**中的**类型**过滤器。请求无法导出的类型会返回以下错误: + +```json +{"statusCode": 400, "error": "Bad Request", "message": "Trying to export non-exportable type(s): bogus-type"} +``` + +## 导入保存的对象 + +导入保存对象 API 从[导出保存对象 API](#导出保存的对象) 或从 **Dashboards 管理** > **保存的对象**导出生成的 NDJSON 文件导入保存的对象。将文件作为 `file` 字段中的多部分表单数据发送。文件必须使用 `.ndjson` 扩展名。 + +### 端点 + +```json +POST {osd_host}:{port}/api/saved_objects/_import +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `overwrite` | Boolean | 是否替换已存在的保存对象。默认为 `false`,这会导致冲突的对象被报告为错误而不是导入。不能与 `createNewCopies` 结合使用。| +| `createNewCopies` | Boolean | 是否以新 ID 导入对象,保留现有对象。不能与 `overwrite` 结合使用。| +| `dataSourceId` | String | 启用多数据源时,要将导入对象附加到的数据源 ID。| +| `workspaces` | String 或 Array | 要将对象导入到的工作区。| + +### 示例请求 + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_import?overwrite=true" \ + -H 'osd-xsrf: true' \ + --form file=@export.ndjson +``` + +### 示例响应 + +```json +{ + "successCount": 2, + "success": true, + "successResults": [ + { + "type": "index-pattern", + "id": "ecommerce-test-pattern", + "meta": { + "title": "ecommerce-test", + "icon": "indexPatternApp" + }, + "overwrite": true + }, + { + "type": "visualization", + "id": "test-viz", + "meta": { + "title": "Sales by customer", + "icon": "visualizeApp" + }, + "overwrite": true + } + ] +} +``` + +### 导入错误 + +导入可能对某些对象失败而对其他对象成功。当任何对象失败时,`success` 为 `false`,每个失败都出现在 `errors` 中,带有标识原因的 `error.type` 字段: + +```json +{ + "successCount": 0, + "success": false, + "errors": [ + { + "id": "orphan-viz", + "type": "visualization", + "title": "Orphan", + "meta": { + "title": "Orphan", + "icon": "visualizeApp" + }, + "error": { + "type": "missing_references", + "references": [ + { + "type": "index-pattern", + "id": "does-not-exist" + } + ] + } + } + ] +} +``` + +下表列出了最常见的错误类型。 + +| 错误类型 | 原因 | 解决方案 | +| :--- | :--- | :--- | +| `missing_references` | 对象引用导入不包含且目标实例没有的对象,例如索引模式。| 将 `includeReferencesDeep` 设置为 `true` 再次导出源对象,创建缺失的对象,或使用[解决导入错误 API](#解决导入错误) 忽略引用。| +| `conflict` | 具有相同类型和 ID 的对象已存在。| 使用 `overwrite=true` 或 `createNewCopies=true` 重试。| +| `unsupported_type` | 没有已安装的插件注册该对象的类型。| 安装提供该类型的插件或从文件中删除该对象。| + +::: info NOTE +因为即使对象导入失败,响应也返回 `200` 状态代码,所以在编写导入脚本时检查 `success` 字段而不是状态代码。 +::: + +## 解决导入错误 + +解决导入错误 API 使用每个对象的指令重试失败的导入,例如覆盖特定对象或忽略缺失的引用。发送导入使用的相同 NDJSON 文件,以及列出要重试的对象的 `retries` 字段。 + +### 端点 + +```json +POST {osd_host}:{port}/api/saved_objects/_resolve_import_errors +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `createNewCopies` | Boolean | 是否以新 ID 导入重试的对象。默认为 `false`。| +| `dataSourceId` | String | 要将导入对象附加到的数据源 ID。| +| `workspaces` | String 或 Array | 要将对象导入到的工作区。| + +### 请求体字段 + +将以下字段作为多部分表单数据发送。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `file` | File | 失败导入使用的 NDJSON 文件。必需。| +| `retries` | Array | 要重试的对象。必需。| +| `retries.type` | String | 要重试的对象类型。必需。| +| `retries.id` | String | 要重试的对象 ID。必需。| +| `retries.overwrite` | Boolean | 是否替换现有对象。默认为 `false`。| +| `retries.destinationId` | String | 要分配给导入对象的 ID。| +| `retries.replaceReferences` | Array | 要重定向的引用,每个都有 `type`、`from` ID 和 `to` ID。| +| `retries.ignoreMissingReferences` | Boolean | 即使引用缺失也导入对象。| + +### 示例请求 + +以下请求重试索引模式缺失的可视化,导入它而不带引用: + +```bash +curl -X POST "http://localhost:5601/api/saved_objects/_resolve_import_errors" \ + -H 'osd-xsrf: true' \ + --form file=@export.ndjson \ + --form 'retries=[{"type": "visualization", "id": "orphan-viz", "ignoreMissingReferences": true}]' +``` + +### 示例响应 + +```json +{ + "successCount": 1, + "success": true, + "successResults": [ + { + "type": "visualization", + "id": "orphan-viz", + "meta": { + "title": "Orphan", + "icon": "visualizeApp" + } + } + ] +} +``` + +## 限制 + +以下限制和注意事项适用于保存对象 API。 + +### 文件格式 + +导入端点仅接受扩展名为 `.ndjson` 的文件。具有任何其他扩展名的文件会返回 `{"statusCode": 400, "error": "Bad Request", "message": "Invalid file extension .json"}`。旧版 `/api/opensearch-dashboards/dashboards/export` 端点生成单个 JSON 文档而不是 NDJSON,因此其输出无法使用 `_import` 导入。使用 `_export` 或从 **Dashboards 管理** > **保存的对象**导出对象,然后导入生成的 NDJSON 文件。 + +### 请求大小 + +导入端点受 `savedObjects.maxImportPayloadBytes` 设置限制,默认为 `26214400` (25 MB)。`server.maxPayloadBytes` 设置默认为 `1048576` (1 MB),适用于其他 OpenSearch Dashboards 路由,不会提高或降低导入限制。 + +小于 25 MB 的文件收到 `413 Request Entity Too Large` 响应通常来自 OpenSearch Dashboards 前面的代理,而不是来自 OpenSearch Dashboards 本身。提高代理的正文大小限制,例如 NGINX 中的 `client_max_body_size` 或 NGINX Ingress 控制器中的 `proxy-body-size`。 + +### 对象数量 + +单次导出或导入受 `savedObjects.maxImportExportSize` 设置限制为 `10000` 个对象。按类型或搜索词拆分较大的传输。 + +### 冲突参数 + +`overwrite` 和 `createNewCopies` 参数不能一起使用。同时发送两者会返回以下错误: + +```json +{"statusCode": 400, "error": "Bad Request", "message": "[request query]: cannot use [overwrite] with [createNewCopies]"} +``` + +### 版本兼容性 + +将 NDJSON 文件导入运行与导出它的实例相同版本的 OpenSearch Dashboards 的实例,或更高版本。对象在导入时向前迁移,但不能向后迁移。从较新版本导出的对象会失败并显示类似以下的错误: + +``` +Document "test-viz" has property "visualization" which belongs to a more recent version of OpenSearch Dashboards [7.10.0]. The last known version is [7.9.3] +``` + +## 相关文档 + +- [导出和导入保存的对象](/dashboards/management/saved-objects) +- [报告 API](/dashboards/reporting/api) +- [保存对象的访问控制列表](/dashboards/management/acl) +- [索引模式](/dashboards/management/index-patterns) diff --git a/i18n/zh/dashboards/management/saved-objects.md b/i18n/zh/dashboards/management/saved-objects.md new file mode 100644 index 00000000..e0b0d673 --- /dev/null +++ b/i18n/zh/dashboards/management/saved-objects.md @@ -0,0 +1,68 @@ +--- +title: 保存的对象 +--- + +# 保存的对象 + +_保存的对象_是您创建和重用的 OpenSearch Dashboards 资源,包括可视化、仪表板、保存的搜索、索引模式和地图。将它们导出到文件并将该文件导入到另一个实例,以将仪表板从开发集群复制到生产集群、在租户或工作区之间移动对象,或保留可视化的备份。 + +对象相互依赖: 仪表板引用其可视化,可视化引用其索引模式。将对象与其引用的对象一起导出,以便可以将导出导入到尚未包含这些对象的实例中。 + +要以编程方式执行这些任务,例如作为 CI/CD 管道的一部分,请参阅[保存对象 API](/dashboards/management/saved-objects-api)。 + +## 导出保存的对象 + +要导出特定对象,例如一个仪表板及其显示的所有内容,请执行以下步骤: + +1. 在顶部菜单中,转到**管理** > **Dashboards 管理** > **保存的对象**。 +1. 选中要导出的每个对象的复选框。要缩小列表范围,请在搜索框中输入标题或按**类型**过滤。 +1. 选择**导出**。 +1. 保持选中**包含相关对象**,以便导出还包含所选对象引用的对象。 +1. 选择**导出**以下载文件。 + +要导出实例的全部内容,请选择**导出所有对象**,选择要包含的类型,然后选择**导出**。 + +下载的文件使用 NDJSON 格式,每行一个对象,最后一行是摘要。这与[导出保存对象 API](/dashboards/management/saved-objects-api#export-saved-objects) 生成的格式相同,因此从 OpenSearch Dashboards 导出的文件可以使用 API 导入,使用 API 导出的文件可以从 OpenSearch Dashboards 导入。 + +要在导出之前查看对象引用的内容,请为该对象选择**关系**操作。 + +启用多租户时,每个租户都有自己的保存对象集,导出仅包含您当前使用的租户的对象。这适用于**导出所有对象**,因此要捕获实例中的每个对象,请切换到每个租户并分别导出。启用聚合视图时,列表可以同时显示多个租户的对象,但按租户过滤列表不会更改导出包含的内容。有关更多信息,请参阅 [OpenSearch Dashboards 多租户保存对象聚合视图](/security/multi-tenancy/mt-agg-view)。 + +启用工作区时,您从工作区内部启动的导出仅包含与该工作区关联的对象。您从任何工作区外部的**保存的对象**启动的导出涵盖每个工作区: 列表包括您可以访问的所有工作区的对象,在**工作区**列中标记每个对象,**导出所有对象**将它们全部写入文件。 + +要将对象复制到同一实例中的另一个工作区而不是导出它们,请选择对象,选择**复制到**,然后选择目标工作区。要复制当前工作区中的每个对象,请选择**将所有对象复制到**。要以编程方式执行相同的任务,请参阅[复制保存的对象](/dashboards/workspace/apis#duplicate-saved-objects)。 + +## 导入保存的对象 + +要导入保存的对象,请执行以下步骤: + +1. 在顶部菜单中,转到**管理** > **Dashboards 管理** > **保存的对象**。 +1. 选择**导入**。 +1. 选择**选择文件**并选择要导入的 NDJSON 文件。 +1. 在**导入选项**中,选择如何处理已存在的对象: + - **创建具有唯一 ID 的新对象**将对象作为副本导入并保持现有对象不变。 + - **检查现有对象**将传入对象与实例中已有的对象进行比较。将其与**自动覆盖冲突**结合使用以替换现有对象,或与**在冲突时请求操作**结合使用以决定每个冲突。 +1. 选择**导入**,然后选择**完成**。 + +如果对象引用目标实例没有的索引模式,OpenSearch Dashboards 会列出受影响的对象并提示您选择不同的索引模式或创建一个。 + +启用多租户时,对象会导入到您当前使用的租户中,因此在导入之前切换到目标租户。 + +启用工作区时,**导入**仅在工作区内显示,导入的对象与该工作区关联。在导入之前打开目标工作区。 + +## 将仪表板复制到另一个实例 + +要在两个索引相同数据的实例之间移动仪表板,请执行以下步骤: + +1. 在源实例中,转到**管理** > **Dashboards 管理** > **保存的对象**,然后选中仪表板的复选框。 +1. 选择**导出**,保持选中**包含相关对象**,然后选择**导出**。该文件包含仪表板、其可视化和保存的搜索以及它们的索引模式。 +1. 在目标实例中,转到**管理** > **Dashboards 管理** > **保存的对象**,然后选择**导入**。 +1. 选择下载的文件,选择导入选项,然后选择**导入**。 + +租户和工作区决定每个步骤涵盖哪些对象。在导出之前选择源租户或工作区,在导入之前选择目标租户或工作区。有关更多信息,请参阅[导出保存的对象](#导出保存的对象)和[导入保存的对象](#导入保存的对象)。 + +## 限制 + +从 OpenSearch Dashboards 导入接受 `.ndjson` 文件,它还接受 NDJSON 之前版本的 OpenSearch Dashboards 或 Kibana 导出的旧版 `.json` 文件。对 `.json` 文件的支持已弃用,保存对象 API 仅接受 `.ndjson`。在将旧版文件与 API 一起使用之前,请重新导出它们。 + +单次导出或导入限制为 10,000 个对象和 25 MB 的请求大小。有关控制这些限制的设置以及适用于 OpenSearch Dashboards 和 API 的其他注意事项,请参阅[限制](/dashboards/management/saved-objects-api#limitations)。 diff --git a/i18n/zh/dashboards/management/scheduled-query-acceleration.md b/i18n/zh/dashboards/management/scheduled-query-acceleration.md new file mode 100644 index 00000000..da0b6517 --- /dev/null +++ b/i18n/zh/dashboards/management/scheduled-query-acceleration.md @@ -0,0 +1,193 @@ +--- +title: 计划查询加速 +--- + +# 计划查询加速 +<Badge type="tip" text="2.17 版本引入" /> + +计划查询加速 (SQA) 旨在优化从 OpenSearch 直接发送到外部数据源(如 Amazon Simple Storage Service (Amazon S3))的查询。它使用自动化来解决管理和刷新索引、视图和数据时常见的问题。 + +查询加速通过二级索引(如[跳跃索引](/dashboards/management/accelerate-external-data#skipping-indexes)、[覆盖索引](/dashboards/management/accelerate-external-data#covering-indexes)或[物化视图](/dashboards/management/accelerate-external-data#materialized-views))来实现。当查询运行时,它们使用这些索引而不是直接查询 Amazon S3。 + +二级索引需要定期刷新以保持与 Amazon S3 数据同步。可以使用内部调度程序(在 Spark 内)或外部调度程序来安排此刷新操作。 + +SQA 提供以下优势: + +- **通过优化资源使用降低成本**: SQA 减少了驱动节点上的操作负载,降低了维护索引和视图自动刷新的相关成本。 + +- **改进刷新操作的可观测性**: SQA 提供索引状态和刷新时间的可见性,提供对数据处理和当前系统状态的洞察。 + +- **更好地控制刷新调度**: SQA 允许灵活调度刷新间隔,帮助您根据特定要求管理资源使用和刷新频率。 + +- **简化索引管理**: SQA 允许在单个查询中更新索引设置(如刷新间隔),从而简化工作流程。 + +## 概念 + +在配置 SQA 之前,请熟悉以下主题: + +- [使用 OpenSearch 索引优化查询性能](/dashboards/management/accelerate-external-data) +- [Flint 索引刷新](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#flint-index-refresh) +- [索引状态管理](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#index-state-transition-1) + +## 前提条件 + +在配置 SQA 之前,请验证是否满足以下要求: + +- 确保您正在运行 OpenSearch 2.17 或更高版本。 +- 确保已安装 SQL 插件。大多数 OpenSearch 发行版都包含 SQL 插件。有关更多信息,请参阅[管理 OpenSearch 插件](/install-and-configure/plugins)。 +- 确保已配置数据源(在此示例中为 Amazon S3): 配置跳跃索引、覆盖索引或物化视图。这些二级数据源是额外的数据结构,通过优化发送到外部数据源(如 Amazon S3)的查询来提高查询性能。有关更多信息,请参阅[使用 OpenSearch 索引优化查询性能](/dashboards/management/accelerate-external-data)。 +- 配置 Amazon EMR Serverless(访问 Apache Spark 需要)。 + +## 配置 SQA 设置 + +如果您想覆盖默认配置值,请更改以下集群设置: + +- **启用异步查询执行**: 将 `plugins.query.executionengine.async_query.enabled` 设置为 `true`(默认值): + ```json + PUT /_cluster/settings + { + "transient": { + "plugins.query.executionengine.async_query.enabled": "true" + } + } + ``` + + 有关更多信息,请参阅[设置](https://github.com/opensearch-project/sql/blob/main/docs/user/admin/settings.rst#pluginsqueryexecutionengineasync_queryenabled)。 + +- **配置异步查询的外部调度程序间隔**: 此设置定义外部调度程序检查任务的频率,允许自定义刷新频率。此设置没有默认值: 如果此值为空,默认值来自 `opensearch-spark`,为 `5 minutes`。根据工作负载量调整间隔可以帮助您优化资源和管理成本: + ```json + PUT /_cluster/settings + { + "transient": { + "plugins.query.executionengine.async_query.external_scheduler.interval": "10 minutes" + } + } + ``` + + 有关更多信息,请参阅[设置](https://github.com/opensearch-project/sql/blob/main/docs/user/admin/settings.rst#pluginsqueryexecutionengineasync_queryexternal_schedulerinterval)。 + +## 运行加速查询 + +您可以在[查询工作台](/dashboards/query-workbench)中运行加速查询。要运行加速查询,请使用以下语法: + +```sql +CREATE SKIPPING INDEX example_index +WITH ( + auto_refresh = true, + refresh_interval = '15 minutes' +); +``` + +默认情况下,查询使用外部调度程序。要使用内部调度程序,请将 `scheduler_mode` 设置为 `internal`: + +```sql +CREATE SKIPPING INDEX example_index +WITH ( + auto_refresh = true, + refresh_interval = '15 minutes', + scheduler_mode = 'internal' +); +``` + +## 参数 + +使用加速查询创建索引时,您可以在 `WITH` 子句中指定以下参数来控制刷新行为、调度和时间。 + +| 参数 | 描述 | +|:--- | :--- | +| `auto_refresh` | 为索引启用自动刷新。如果为 `true`,索引会按指定间隔自动刷新。如果为 `false`,必须使用 `REFRESH` 语句手动触发刷新操作。默认为 `false`。| +| `refresh_interval` | 定义索引刷新操作之间的时间量,这决定了新数据摄取到索引的频率。这仅在启用 `auto_refresh` 时适用。间隔决定新数据集成的频率,可以指定为 `1 minute` 或 `10 seconds` 等格式。有关有效的时间单位,请参阅[时间单位](#时间单位)。| +| `scheduler_mode` | 指定自动刷新的调度模式(内部或外部调度)。外部调度程序需要 `checkpoint_location`(刷新作业检查点的路径)进行状态管理。有关更多信息,请参阅[启动流式查询](https://spark.apache.org/docs/latest/streaming/apis-on-dataframes-and-datasets.html#starting-streaming-queries)。有效值为 `internal` 和 `external`。| + +有关更多信息和其他可用参数,请参阅 [Flint 索引刷新](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#flint-index-refresh)。 + +## 时间单位 + +您可以在定义时间间隔时指定以下时间单位: + +- 毫秒: `ms`、`millisecond` 或 `milliseconds` +- 秒: `s`、`second` 或 `seconds` +- 分钟: `m`、`minute` 或 `minutes` +- 小时: `h`、`hour` 或 `hours` +- 天: `d`、`day` 或 `days` + +## 监控索引状态 + +要监控索引状态,请使用以下语句: + +```sql +SHOW FLINT INDEXES IN spark_catalog.default; +``` + +## 管理计划作业 + +使用以下命令管理计划作业。 + +### 启用作业 + +要使用内部或外部调度程序禁用自动刷新,请将 `auto_refresh` 设置为 `false`: + +```sql +ALTER MATERIALIZED VIEW myglue_test.default.count_by_status_v9 WITH (auto_refresh = false); +``` + +### 更新计划 + +要更新计划并修改刷新设置,请在 `WITH` 子句中指定 `refresh_interval`: + +```sql +ALTER INDEX example_index +WITH (refresh_interval = '30 minutes'); +``` + +### 切换调度程序模式 + +要切换调度程序模式,请在 `WITH` 子句中指定 `scheduler_mode`: + +```sql +ALTER MATERIALIZED VIEW myglue_test.default.count_by_status_v9 WITH (scheduler_mode = 'internal'); +``` + +### 检查调度程序元数据 + +要检查调度程序元数据,请使用以下请求: + +```json +GET /.async-query-scheduler/_search +``` + +## 最佳实践 + +我们建议在使用 SQA 时遵循以下最佳实践。 + +### 性能优化 + +- **推荐的刷新间隔**: 选择正确的刷新间隔对于平衡资源使用和系统性能至关重要。在设置间隔时,请考虑您的工作负载要求和所需数据的新鲜度。 + +- **并发作业限制**: 限制并发运行作业的数量以避免系统资源过载。监控系统容量并相应调整作业限制以确保最佳性能。 + +- **资源使用**: 高效的资源分配是最大化性能的关键。根据工作负载和运行的查询类型适当分配内存、CPU 和 I/O。 + +### 成本管理 + +- **使用外部调度程序**: 外部调度程序卸载刷新操作,减少对核心驱动节点的需求。 + +- **为您的用例配置刷新间隔**: 较长的刷新间隔可降低成本,但可能影响数据新鲜度。 + +- **优化刷新计划**: 根据工作负载模式调整刷新间隔,以减少不必要的刷新操作。 + +- **监控成本**: 定期监控与计划查询和刷新操作相关的成本。使用可观测性工具可以帮助您深入了解资源使用和随时间变化的成本。 + +## 验证设置 + +您可以通过运行测试查询并验证调度程序配置来验证您的设置: + +```sql +SHOW FLINT INDEXES EXTENDED +``` + +有关更多信息,请参阅 [OpenSearch Spark 文档](https://github.com/opensearch-project/opensearch-spark/blob/main/docs/index.md#all-indexes)。 + +## 故障排除 + +如果刷新操作未按预期触发,请确保已启用 `auto_refresh` 设置并正确配置了刷新间隔。 diff --git a/i18n/zh/dashboards/navigating-ui.md b/i18n/zh/dashboards/navigating-ui.md new file mode 100644 index 00000000..c4963688 --- /dev/null +++ b/i18n/zh/dashboards/navigating-ui.md @@ -0,0 +1,59 @@ +--- +title: 导航 OpenSearch Dashboards +--- + +# 导航 OpenSearch Dashboards + +您可以从[主页](#the-opensearch-dashboards-home-page)和[左侧导航面板](#the-left-navigation-panel)导航 OpenSearch Dashboards,它提供对所有 OpenSearch Dashboards 应用程序的访问。 + +## OpenSearch Dashboards 主页 + +OpenSearch Dashboards 主页有两个变体:经典主页和工作区主页。 + +### 经典主页 + +下图显示了经典导航中的主页,导航面板处于打开状态。 + +*OpenSearch Dashboards 主页* + +- _标题栏_ (A) 从左到右包含以下元素: + - <img src="/images/icons/menu-icon.png" class="inline-icon" alt="菜单图标"/> (菜单) 菜单图标。 + - 主页图标 (主页) 主页图标。 + - 面包屑显示。在主页上只包含一个标签"Home"。 + - 菜单区域 (B)。此区域是标题栏的右侧部分,当应用程序在主面板中活动时包含上下文相关的_应用程序菜单_。 + - 帮助图标 (帮助) 帮助图标。 +- 导航面板 (C) 是导航 OpenSearch Dashboards 的主要方式。它包含按功能分组的可折叠菜单(**最近查看**、**OpenSearch Dashboards** 应用、**可观测性**等)。请参阅[左侧导航面板](#the-left-navigation-panel)。 +- _面板_或_主面板_ (D) 包含当前应用程序或 UI 页面。 + +### 工作区导航 +<Badge type="tip" text="2.18.0 版本引入" /> + +OpenSearch Dashboards 提供了一种称为工作区导航的替代导航模式。工作区将应用程序分组到专注的环境中,例如分析、可观测性或安全分析。在工作区导航中,主页列出您的工作区,如下图所示,您必须首先选择一个工作区才能访问应用程序。 + +*启用工作区的 OpenSearch Dashboards 主页* + +选择工作区后,左侧导航面板提供对该工作区应用程序的访问,类似于经典导航,如下图所示。某些功能,例如[使用查询创建可视化](/dashboards/visualize/visualization-editor/),仅在工作区中可用。 + +*工作区内的概览页面和左侧导航面板* + +工作区由 OpenSearch Dashboards 管理员启用。有关更多信息,请参阅[工作区](/dashboards/workspace/)。 + +## 左侧导航面板 + +使用 UI 左侧的_左侧导航面板_来选择您要使用的任何应用程序或设置页面。要打开导航面板,请选择页面顶部的 <img src="/images/icons/menu-icon.png" class="inline-icon" alt="菜单图标"/> (菜单) 图标。 + +下图显示了经典导航和工作区导航中最常用的功能。 + +经典导航面板 | 工作区导航面板 +:--: | :--: +*经典导航面板* | *工作区导航面板* + +- _菜单图标_ (A) 打开和关闭导航面板。 +- **发现** (B) 在主面板中打开发现应用程序。请参阅[使用发现探索数据](/dashboards/discover/index-discover)。 +- **仪表板** (C) 在主面板中打开仪表板应用程序。请参阅[创建仪表板](/dashboards/dashboard/)。 +- **可视化** (D) 在主面板中打开可视化应用程序。请参阅[构建数据可视化](/dashboards/visualize/visualize-app/)。 +- **可观测性** (E) 在导航面板中打开可观测性菜单。请参阅[可观测性](/observing-your-data/)。 + +## 相关文档 + +- [访问 OpenSearch Dashboards](/dashboards/getting-started/access) diff --git a/i18n/zh/dashboards/notebooks.md b/i18n/zh/dashboards/notebooks.md new file mode 100644 index 00000000..08a7da87 --- /dev/null +++ b/i18n/zh/dashboards/notebooks.md @@ -0,0 +1,118 @@ +--- +title: 笔记本 +--- + +# 笔记本 + +OpenSearch Dashboards 笔记本是一个界面,可让您在单个笔记本界面中轻松组合代码片段、实时可视化和叙述性文本。 + +笔记本让您可以通过运行不同的可视化来交互式探索数据,您可以与团队成员共享以协作完成项目。 + +笔记本是由两个元素组成的文档:代码块(Markdown/SQL/管道处理语言(PPL))和可视化。选择多个时间线来比较和对比可视化。 + +您还可以直接从笔记本生成[报告](/dashboards/reporting/report-dashboard-index)。 + +常见用例包括创建事后报告、设计运行手册、构建实时基础设施报告和编写文档。 + +::: info NOTE +OpenSearch Dashboards 中的租户是用于保存笔记本和其他 OpenSearch Dashboards 对象的空间。有关更多信息,请参阅 [OpenSearch Dashboards 多租户](/security/multi-tenancy/tenant-index)。 +::: + +## 开始使用笔记本 + +要打开笔记本,在顶部菜单上,转到**可观测性** > **笔记本**。在工作区中,笔记本位于**可视化和报告**菜单类别中。在使用图标侧边导航的可观测性工作区中,笔记本位于**更多**菜单中。 + +### 步骤 1: 创建笔记本 + +笔记本是创建报告的界面。 + +1. 选择**创建笔记本**并输入描述性名称。 +1. 选择**创建**。 + +选择**操作**以重命名、复制或删除笔记本。 + +![创建笔记本](/images/create_notebook.gif) + +### 步骤 2: 添加段落 + +段落结合了代码块和可视化来描述数据。 + +#### 添加代码块 + +代码块支持 Markdown、SQL 和 PPL 语言。 + +使用 `%[语言类型]` 语法在第一行指定输入语言。 +例如,为 Markdown 输入 `%md`,为 SQL 输入 `%sql`,为 PPL 输入 `%ppl`。 + +##### 示例 Markdown 块 + +``` +%md +添加 Markdown 格式的文本。 +``` + +![Markdown 段落](/images/markdown_notebooks.gif) + +##### 示例 SQL 块 + +```sql +%sql +Select * from opensearch_dashboards_sample_data_flights limit 20; +``` + +![SQL 段落](/images/sql_notebooks.gif) + +##### 示例 PPL 块 + +``` +%ppl +source=opensearch_dashboards_sample_data_logs | head 20 +``` + +![PPL 段落](/images/ppl_notebooks.gif) + +#### 添加可视化 + +1. 要添加可视化,选择**添加段落**并选择**可视化**。 +1. 在**标题**中,选择您的可视化并选择日期范围。您可以选择多个时间线来比较和对比可视化。 +1. 要运行和保存段落,选择**运行**。 + +![可视化段落](/images/visualization_notebooks.gif) + +## 段落操作 + +您可以对段落执行以下操作: + +- 在报告顶部添加新段落。 +- 在报告底部添加新段落。 +- 同时运行所有段落。 +- 清除所有段落的输出。 +- 删除所有段落。 + +![示例笔记本](/images/paragraphs_notebooks.gif) + +## 示例笔记本 + +我们准备了以下示例笔记本,展示了各种用例: + +- 使用 SQL 查询 OpenSearch Dashboards 示例航班数据。 +- 使用 PPL 查询 OpenSearch Dashboards 示例网络日志数据。 +- 使用 PPL 和可视化对 OpenSearch Dashboards 示例网络日志数据执行示例根本原因事件分析。 + +要添加示例笔记本,选择**操作**并选择**添加示例笔记本**。 + +![示例笔记本](/images/sample_notebooks.gif) + +## 创建报告 + +您可以使用笔记本创建 PNG 和 PDF 报告: + +1. 从顶部菜单栏,选择**报告操作**。 +1. 您可以选择**下载 PDF** 或**下载 PNG**。 + + 报告在后台异步生成,可能需要几分钟,具体取决于报告的大小。当您的报告准备好下载时,会出现通知。 + +1. 要创建基于计划的报告,选择**创建报告定义**。有关创建报告定义的步骤,请参阅[使用定义创建报告](/dashboards/reporting/report-dashboard-index#creating-reports-using-a-definition)。 +1. 要查看所有报告,选择**查看所有报告**。 + +![报告笔记本](/images/report_notebooks.gif) diff --git a/i18n/zh/dashboards/reporting/api.md b/i18n/zh/dashboards/reporting/api.md new file mode 100644 index 00000000..df82af6c --- /dev/null +++ b/i18n/zh/dashboards/reporting/api.md @@ -0,0 +1,427 @@ +--- +title: 报告 API +--- + +# 报告 API + +使用报告 API 创建和管理报告定义,以及从仪表板、可视化、保存的搜索和笔记本生成报告。报告定义指定要捕获的源对象、文件格式、时间范围和可选计划。从定义生成报告会产生报告实例。 + +报告定义和报告实例通过 OpenSearch 管理,但文件本身由 OpenSearch Dashboards 渲染。创建定义和列出实例使用端口 9200 上的 OpenSearch 端点,下载报告内容使用端口 5601 上的 OpenSearch Dashboards 端点。有关更多信息,请参阅[下载报告内容](#下载报告内容)。 + +有关这些操作的 OpenSearch Dashboards 界面等效项,请参阅[使用 OpenSearch Dashboards 进行报告](/dashboards/reporting/report-dashboard-index)。 + +## 报告源类型和文件格式 + +`Csv` 和 `Xlsx` 文件格式导出保存的搜索的基础行。它们不支持 `Visualization`、`Dashboard` 或 `Notebook` 源类型,这些类型被捕获为渲染图像。要将可视化背后的数据导出为 CSV,请在**发现**中将等效查询保存为保存的搜索,并将该保存的搜索用作报告源。 + +下表列出了每种报告源类型支持的文件格式。 + +| 源类型 | 支持的文件格式 | +| :--- | :--- | +| `SavedSearch` | `Csv`, `Xlsx` | +| `Visualization` | `Pdf`, `Png` | +| `Dashboard` | `Pdf`, `Png` | +| `Notebook` | `Pdf`, `Png` | + +::: danger WARNING +OpenSearch 接受将源类型与不支持的文件格式配对的报告定义,例如 `Visualization` 与 `Csv`,但无法渲染报告。具有不支持配对的定义还会导致 OpenSearch Dashboards 中的**报告**页面无法加载其报告定义列表,直到您删除该定义。 +::: + +## 创建报告定义 API + +创建报告定义。 + +### 端点 + +```json +POST _plugins/_reports/definition +``` + +### 请求体字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `reportDefinition` | Object | 报告定义。必需。| +| `reportDefinition.name` | String | 报告定义的名称。必需。| +| `reportDefinition.isEnabled` | Boolean | 定义的计划是否处于活动状态。必需。| +| `reportDefinition.source` | Object | 要捕获的对象。必需。| +| `reportDefinition.source.type` | String | 源对象的类型。有效值为 `Dashboard`、`Visualization`、`SavedSearch` 和 `Notebook`。必需。| +| `reportDefinition.source.id` | String | 源对象的保存对象 ID。必需。| +| `reportDefinition.source.origin` | String | 渲染报告的 OpenSearch Dashboards 实例的基本 URL,例如 `http://localhost:5601`。必需。| +| `reportDefinition.source.description` | String | 源对象的描述。可选。| +| `reportDefinition.format` | Object | 输出格式。必需。| +| `reportDefinition.format.fileFormat` | String | 生成报告的文件格式。有效值为 `Pdf`、`Png`、`Csv` 和 `Xlsx`。必需。| +| `reportDefinition.format.duration` | String | 要捕获的时间范围,以报告生成时间为结束时间,作为 ISO 8601 持续时间,如 `PT30M` 或 `P60D`。必需。| +| `reportDefinition.format.limit` | Integer | `Csv` 或 `Xlsx` 报告中包含的最大行数。可选。| +| `reportDefinition.format.header` | String | 要添加到报告的页眉。可选。| +| `reportDefinition.trigger` | Object | 指定何时生成报告。必需。| +| `reportDefinition.trigger.triggerType` | String | 有效值为 `OnDemand`、`Download`、`CronSchedule` 和 `IntervalSchedule`。必需。| +| `reportDefinition.trigger.schedule` | Object | 生成报告的计划。当 `triggerType` 为 `CronSchedule` 或 `IntervalSchedule` 时必需。| +| `reportDefinition.delivery` | Object | 生成报告的通知设置。可选。| + +### 示例请求 + +以下请求创建一个按需定义,将保存的搜索的最近 60 天导出为 CSV: + +```json +POST _plugins/_reports/definition +{ + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "<saved_search_id>" + }, + "format": { + "duration": "P60D", + "fileFormat": "Csv", + "limit": 1000, + "header": "" + }, + "trigger": { + "triggerType": "OnDemand" + }, + "delivery": { + "configIds": [], + "title": "", + "textDescription": "", + "htmlDescription": "" + }, + "status": "ACTIVE" + } +} +``` + +### 示例响应 + +```json +{ + "reportDefinitionId": "7f6fY6ABLgrkzSeVjlGr" +} +``` + +### 示例请求: 计划报告 + +要按重复计划生成报告,请将 `triggerType` 设置为 `CronSchedule` 并提供 `schedule` 对象。以下请求每天上午 6:00 生成相同的 CSV 报告: + +```json +POST _plugins/_reports/definition +{ + "reportDefinition": { + "name": "Daily orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "<saved_search_id>" + }, + "format": { + "duration": "P1D", + "fileFormat": "Csv", + "limit": 10000, + "header": "" + }, + "trigger": { + "triggerType": "CronSchedule", + "schedule": { + "cron": { + "expression": "0 6 * * *", + "timezone": "America/Los_Angeles" + } + } + }, + "status": "ACTIVE" + } +} +``` + +有关 cron 表达式的更多信息,请参阅 [Cron 表达式](/api-reference/cron-expressions)。 + +## 列出报告定义 API + +检索所有报告定义。 + +### 端点 + +```json +GET _plugins/_reports/definitions +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `fromIndex` | Integer | 要返回的第一个定义的索引。默认为 `0`。| +| `maxItems` | Integer | 要返回的最大定义数。| + +### 示例请求 + +```json +GET _plugins/_reports/definitions +``` + +### 示例响应 + +```json +{ + "startIndex": 0, + "totalHits": 1, + "totalHitRelation": "eq", + "reportDefinitionDetailsList": [ + { + "id": "7f6fY6ABLgrkzSeVjlGr", + "lastUpdatedTimeMs": 1788377796262, + "createdTimeMs": 1788377796262, + "tenant": "", + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "test-search" + }, + "format": { + "duration": "PT1440H", + "fileFormat": "Csv", + "limit": 1000, + "header": "", + "timeFrom": null, + "timeTo": null + }, + "trigger": { + "triggerType": "OnDemand" + }, + "delivery": { + "title": "", + "textDescription": "", + "htmlDescription": "", + "configIds": [] + } + } + } + ] +} +``` + +## 获取报告定义 API + +检索单个报告定义。 + +### 端点 + +```json +GET _plugins/_reports/definition/{report_definition_id} +``` + +### 示例请求 + +```json +GET _plugins/_reports/definition/7f6fY6ABLgrkzSeVjlGr +``` + +## 更新报告定义 API + +替换现有的报告定义。提供完整的定义,因为您省略的字段不会被保留。 + +### 端点 + +```json +PUT _plugins/_reports/definition/{report_definition_id} +``` + +### 示例请求 + +```json +PUT _plugins/_reports/definition/7f6fY6ABLgrkzSeVjlGr +{ + "reportDefinition": { + "name": "Orders CSV", + "isEnabled": true, + "source": { + "description": "CSV of all orders", + "type": "SavedSearch", + "origin": "http://localhost:5601", + "id": "<saved_search_id>" + }, + "format": { + "duration": "P90D", + "fileFormat": "Csv", + "limit": 5000, + "header": "" + }, + "trigger": { + "triggerType": "OnDemand" + }, + "status": "ACTIVE" + } +} +``` + +### 示例响应 + +```json +{ + "reportDefinitionId": "7f6fY6ABLgrkzSeVjlGr" +} +``` + +## 删除报告定义 API + +删除报告定义。删除定义不会删除已从中生成的报告。 + +### 端点 + +```json +DELETE _plugins/_reports/definition/{report_definition_id} +``` + +### 示例请求 + +```json +DELETE _plugins/_reports/definition/7f6fY6ABLgrkzSeVjlGr +``` + +### 示例响应 + +```json +{ + "reportDefinitionId": "7f6fY6ABLgrkzSeVjlGr" +} +``` + +## 生成按需报告 API + +从现有报告定义创建报告实例。响应记录使用的定义和捕获的时间范围。要检索文件内容,请参阅[下载报告内容](#下载报告内容)。 + +### 端点 + +```json +POST _plugins/_reports/on_demand/{report_definition_id} +``` + +### 示例请求 + +```json +POST _plugins/_reports/on_demand/7f6fY6ABLgrkzSeVjlGr +{} +``` + +### 响应体字段 + +下表列出了响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `reportInstance.id` | String | 报告实例的 ID。| +| `reportInstance.beginTimeMs` | Integer | 捕获的时间范围的开始,自纪元以来的毫秒数。| +| `reportInstance.endTimeMs` | Integer | 捕获的时间范围的结束,自纪元以来的毫秒数。| +| `reportInstance.reportDefinitionDetails` | Object | 用于生成实例的报告定义。| +| `reportInstance.status` | String | 报告实例的状态,如 `Success`。| + +## 列出报告实例 API + +检索集群中生成的报告实例。 + +### 端点 + +```json +GET _plugins/_reports/instances +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `fromIndex` | Integer | 要返回的第一个实例的索引。默认为 `0`。| +| `maxItems` | Integer | 要返回的最大实例数。| + +### 示例请求 + +```json +GET _plugins/_reports/instances?fromIndex=0&maxItems=2 +``` + +## 获取报告实例 API + +检索单个报告实例。 + +### 端点 + +```json +GET _plugins/_reports/instance/{report_instance_id} +``` + +### 示例请求 + +```json +GET _plugins/_reports/instance/7v6fY6ABLgrkzSeVpVGM +``` + +## 下载报告内容 + +OpenSearch 端点管理报告元数据,不返回报告文件。要检索内容,请使用报告定义的 ID 调用 OpenSearch Dashboards 报告端点: + +```json +POST {osd_host}:{port}/api/reporting/generateReport/{report_definition_id} +``` + +此端点需要 `osd-xsrf: true` 标头和以下查询参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `timezone` | String | 用于解释报告时间范围的时区,如 `UTC`。必需。| +| `dateFormat` | String | 应用于输出中日期字段的格式,如 `MMM D, YYYY @ HH:mm:ss.SSS`。必需。| +| `csvSeparator` | String | 用于分隔 `Csv` 输出中值的字符。必需。| +| `allowLeadingWildcards` | Boolean | 保存的搜索查询是否可以以通配符开头。必需。| + +### 示例请求 + +以下请求下载报告定义的 CSV 内容: + +```bash +curl -X POST \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + 'http://localhost:5601/api/reporting/generateReport/7f6fY6ABLgrkzSeVjlGr?timezone=UTC&dateFormat=MMM%20D,%20YYYY%20@%20HH:mm:ss.SSS&csvSeparator=,&allowLeadingWildcards=true' \ + -d '{}' +``` + +### 示例响应 + +对于 `Csv` 报告,`data` 字段包含文件内容作为文本: + +```json +{ + "data": "order_date,customer_name,price\n\"Aug 1, 2026 @ 10:00:00.000\",Alice,24.99\n\"Aug 2, 2026 @ 11:00:00.000\",Bob,13.5\n\"Aug 3, 2026 @ 12:00:00.000\",Carla,99", + "filename": "Orders CSV_2026-09-02T19:34:25.546Z_4e4bc6a0-a705-11f1-b9f2-73596a0bfb5c.csv" +} +``` + +对于 `Xlsx` 报告,`data` 字段包含 Base64 编码的数据 URL 而不是文本。 + +::: tip TIP +如果 `data` 是空字符串,报告定义的 `duration` 没有与任何文档重叠。增加 `duration` 以便以当前时间结束的时间范围包含您的数据。 +::: + +::: info NOTE +在 OpenSearch 2.16 及更早版本中,CSV 报告具有不可配置的 10,000 行限制。从 2.17 版本开始,使用报告定义中的 `limit` 字段设置限制。 +::: + +## 相关文档 + +- [使用 OpenSearch Dashboards 进行报告](/dashboards/reporting/report-dashboard-index) +- [保存对象 API](/dashboards/management/saved-objects-api) +- [报告定义访问控制](/dashboards/reporting/report-definition-access-control) +- [报告实例访问控制](/dashboards/reporting/report-instance-access-control) diff --git a/i18n/zh/dashboards/reporting/index.md b/i18n/zh/dashboards/reporting/index.md new file mode 100644 index 00000000..4094f50d --- /dev/null +++ b/i18n/zh/dashboards/reporting/index.md @@ -0,0 +1,51 @@ +--- +title: 报告 +--- + +# 报告 + +使用报告功能从仪表板、可视化、保存的搜索和笔记本生成 PDF、PNG、CSV 和 XLSX 报告,可以按需生成或按计划生成。OpenSearch Dashboards 渲染每个报告,因此即使您使用 API 或 CLI 生成报告,报告功能也需要一个正在运行的 OpenSearch Dashboards 实例。 + +要下载搜索结果或保存的对象而不创建报告,请参阅[导出数据](/dashboards/exporting-data)。 + +## 报告定义和报告 + +报告使用两个概念: + +- **报告定义**是一个保存的配置,指定要捕获的仪表板、可视化、保存的搜索或笔记本、文件格式、时间范围和可选计划。您可以重用报告定义按需或按重复计划生成报告。 +- **报告**是从报告定义或一次性下载生成的文件。 + +删除报告定义不会删除从中生成的报告。 + +## 报告源和文件格式 + +可用的文件格式取决于报告源。仪表板、可视化和笔记本被捕获为渲染图像。保存的搜索被导出为查询返回的行。 + +| 报告源 | 文件格式 | +| :--- | :--- | +| 仪表板 | PDF, PNG | +| 可视化 | PDF, PNG | +| 笔记本 | PDF, PNG | +| 保存的搜索 | CSV, XLSX | + +要下载可视化背后的数据,请参阅[导出可视化数据](/dashboards/exporting-data#exporting-visualization-data)。 + +::: tip TIP +默认情况下,CSV 和 XLSX 报告最多包含 10,000 行。要更改此限制,请在创建报告定义时设置记录限制。报告没有明确的大小限制,但极大的文档可能会导致 V8 JavaScript 引擎出现内存不足错误而导致报告生成失败。 +::: + +## 选择方法 + +下表列出了生成报告的方法。 + +| 方法 | 用途 | 需要报告插件 | +| :--- | :--- | :--- | +| [OpenSearch Dashboards](/dashboards/reporting/report-dashboard-index) | 从您正在查看的页面生成报告,以及创建和管理报告定义。| 是 | +| [报告 CLI](/dashboards/reporting/rep-cli-index) | 从脚本、cron 作业或 AWS Lambda 函数生成报告,并使用 Amazon SES 或 SMTP 通过电子邮件发送。| 仅用于 CSV 报告 | +| [报告 API](/dashboards/reporting/api) | 以编程方式创建报告定义并生成报告。| 是 | + +## 访问控制 + +要创建报告,您必须具有正确的权限。有关预定义角色及其授予权限的摘要,请参阅[预定义角色](/security/access-control/users-roles#predefined-roles)。 + +当为报告启用资源共享时,报告定义和报告的所有者以及具有共享权限的用户可以向特定用户、角色和后端角色授予访问权限。有关更多信息,请参阅[报告定义访问控制](/dashboards/reporting/report-definition-access-control)和[报告实例访问控制](/dashboards/reporting/report-instance-access-control)。 diff --git a/i18n/zh/dashboards/reporting/rep-cli-create.md b/i18n/zh/dashboards/reporting/rep-cli-create.md new file mode 100644 index 00000000..aab5336d --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-create.md @@ -0,0 +1,92 @@ +--- +title: 创建和请求可视化报告 +--- + +# 创建和请求可视化报告 + +要生成报告,请向报告 CLI 提供要捕获的仪表板、可视化、笔记本或保存的搜索的 OpenSearch Dashboards URL。 + +## 获取 URL + +要获取 URL,请执行以下步骤: + +1. 在 OpenSearch Dashboards 中,打开仪表板、可视化、笔记本或保存的搜索。 +1. 在顶部菜单中,选择**共享** > **永久链接**。 +1. 在**生成链接为**中,选择**保存的对象**。 +1. 选择**复制链接**。 + + ![复制链接](/images/dashboards/dash-url.png) + +**保存的对象**链接是百分比编码的,包含页面的时间范围。**快照**链接还包含当前过滤器和查询,但它可能包含 shell 解释的字符,如 `'` 和 `!`。当您将其传递给 `-u` 选项时,请用单引号将 URL 括起来。要使用包含单引号的快照链接,请将 URL 保存在 `.env` 文件的 `OPENSEARCH_URL` 变量中。有关更多信息,请参阅[在报告 CLI 中使用环境变量](/dashboards/reporting/rep-cli-env-var)。 + +::: info NOTE +不要使用**短 URL**选项生成的链接。报告 CLI 使用 URL 路径确定报告源,因此对于短 URL,报告包括 OpenSearch Dashboards 标题和按钮。 +::: + +如果 URL 不包含时间范围,报告使用 OpenSearch Dashboards 的默认时间范围。 + +## 示例: 下载 PDF 报告 + +以下命令将仪表板的 PDF 报告下载到当前目录: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' +``` + +PDF 是默认格式。如果您不指定文件名,报告将保存为 `opensearch-report-<timestamp>.pdf`。下图显示了 PDF 报告示例。 + +![PDF 示例](/images/dashboards/cli-pdf-report.png) + +## 示例: 下载长仪表板的 PNG 报告 + +OpenSearch Dashboards 仅在仪表板面板在浏览器窗口中可见时才加载它们。默认情况下,窗口高度为 600 像素,因此长仪表板下部的面板在报告中可能显示为空。要捕获所有面板,请将 `-l` 选项设置为适合整个仪表板的高度: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -f png -l 2200 -n web-traffic +``` + +报告保存为 `web-traffic.png`。如果当前目录中已存在同名文件,报告 CLI 不会覆盖它,命令将失败。 + +## 示例: 下载保存的搜索的 CSV 报告 + +CSV 报告仅支持保存的搜索。要下载 CSV 报告,请提供保存的搜索的 URL 并将窗口宽度设置为 `800`: + +```bash +opensearch-reporting-cli -u '<saved-search-url>' -f csv -w 800 -n orders +``` + +::: info NOTE +报告 CLI 通过在**发现**中选择**报告** > **生成 CSV** 来生成 CSV 报告。当页面加载后窗口被调整为任何其他宽度时,**报告**菜单不会显示,命令将失败并显示错误 `No element found for selector: button[id="downloadReport"]`。 +::: + +## 示例: 使用基本身份验证请求报告 + +如果启用了安全插件,请提供身份验证类型和凭据。以下命令使用基本身份验证请求 PDF 报告: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -a basic -c '<username>:<password>' +``` + +为避免在命令行上传递密码,请设置 `OPENSEARCH_USERNAME` 和 `OPENSEARCH_PASSWORD` 环境变量而不是 `-c` 选项。 + +## 示例: 使用 SMTP 通过电子邮件发送报告 + +以下命令生成 PDF 报告并使用 SMTP 服务器将其作为附件发送到指定收件人: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -e smtp --smtphost <smtp-host> --smtpport <smtp-port> --smtpusername <smtp-username> --smtppassword <smtp-password> -s <sender-email> -r <recipient-email> +``` + +电子邮件包含页面的图像、OpenSearch Dashboards 中页面的链接以及报告作为附件。报告也保存到当前目录。要将电子邮件发送给多个收件人,请用逗号分隔地址。要更改电子邮件主题和正文,请使用 `--subject` 和 `--note` 选项。`--note` 选项接受字符串或文本文件的路径。 + +## 示例: 使用 Amazon SES 通过电子邮件发送报告 + +以下命令生成 PNG 报告并使用 Amazon SES 发送: + +```bash +opensearch-reporting-cli -u '<dashboards-url>' -f png -e ses -s <sender-email> -r <recipient-email> +``` + +Amazon SES 需要 AWS 凭据和经过验证的发件人地址。有关更多信息,请参阅[使用 Amazon SES 请求带有报告附件的电子邮件](/dashboards/reporting/rep-cli-env-var#using-amazon-ses-to-request-an-email-with-a-report-attachment)。 + +有关所有可用选项,请参阅[报告 CLI 选项](/dashboards/reporting/rep-cli-options)。 diff --git a/i18n/zh/dashboards/reporting/rep-cli-cron.md b/i18n/zh/dashboards/reporting/rep-cli-cron.md new file mode 100644 index 00000000..9528b94b --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-cron.md @@ -0,0 +1,71 @@ +--- +title: 使用 cron 实用程序计划报告 +--- + +# 使用 cron 实用程序计划报告 + +使用 cron 命令行实用程序按计划运行报告 CLI。每个 cron 条目由指定何时运行的 cron 表达式组成,后跟要运行的命令。 + +要了解 cron 表达式语法,请参阅 [Cron 表达式](/api-reference/cron-expressions)。要获取 cron 帮助,请通过运行以下命令打开手册页: + +```bash +man crontab +``` + +## 前提条件 + +- 安装了 cron 的机器。 +- 报告 CLI。有关说明,请参阅[下载并安装报告 CLI 工具](/dashboards/reporting/rep-cli-install)。 + +## 指定计划 + +Cron 使用最小的 `PATH` 运行命令,该 PATH 通常仅包含 `/usr/bin` 和 `/bin`,因此除非您在 crontab 中设置 `PATH`,否则 cron 无法找到 `node` 和 `opensearch-reporting-cli` 命令。要查找包含这些命令的目录,请运行以下命令: + +```bash +dirname "$(command -v node)" "$(command -v opensearch-reporting-cli)" +``` + +通过运行以下命令打开 crontab 编辑器: + +```bash +crontab -e +``` + +在 crontab 编辑器中,将 `PATH` 设置为包含前面命令返回的目录,然后添加报告请求。以下示例每天上午 8:00 生成报告并使用 Amazon SES 通过电子邮件发送: + +``` +PATH=/usr/local/bin:/usr/bin:/bin +0 8 * * * opensearch-reporting-cli -u '<dashboards-url>' -e ses -s <sender-email> -r <recipient-email> +``` + +::: warning IMPORTANT +Cron 将命令中的每个 `%` 字符转换为新行,OpenSearch Dashboards URL 通常包含 `%` 字符。将 URL 用单引号括起来,并将 URL 中的每个 `%` 字符转义为 `\%`。或者,将 URL 存储在 `.env` 文件中,如以下部分所述。 +::: + +::: info NOTE +如果您使用 `-n` 选项指定文件名,报告 CLI 在第二次运行时会失败,因为已存在同名文件。省略文件名以使用带时间戳的文件名保存每个报告,或在下次运行之前删除上一个报告。 +::: + +## 将报告设置存储在 .env 文件中 + +您可以将 URL 和其他选项存储在 `.env` 文件中,而不是在 cron 命令中提供。`.env` 文件中的值不需要转义。Cron 从您的主目录运行命令,因此在运行报告 CLI 之前切换到包含 `.env` 文件的目录。 + +例如,创建包含以下变量的 `/home/<user>/reports/.env` 文件: + +``` +OPENSEARCH_URL="<dashboards-url>" +OPENSEARCH_TRANSPORT=smtp +OPENSEARCH_SMTP_HOST=<smtp-host> +OPENSEARCH_SMTP_PORT=<smtp-port> +OPENSEARCH_FROM=<sender-email> +OPENSEARCH_TO=<recipient-email> +``` + +然后将以下条目添加到 crontab: + +``` +PATH=/usr/local/bin:/usr/bin:/bin +0 8 * * * cd /home/<user>/reports && opensearch-reporting-cli +``` + +有关更多信息,请参阅[在报告 CLI 中使用环境变量](/dashboards/reporting/rep-cli-env-var)。 diff --git a/i18n/zh/dashboards/reporting/rep-cli-env-var.md b/i18n/zh/dashboards/reporting/rep-cli-env-var.md new file mode 100644 index 00000000..de94062f --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-env-var.md @@ -0,0 +1,104 @@ +--- +title: 在报告 CLI 中使用环境变量 +--- + +# 在报告 CLI 中使用环境变量 + +您可以将值设置为环境变量,而不是在命令行上提供。有关具有对应环境变量的选项列表,请参阅[报告 CLI 选项](/dashboards/reporting/rep-cli-options)。 + +通过以下方式之一设置环境变量: + +- 在 shell 中导出它们,例如 `export OPENSEARCH_FROM=reports@example.com`。 +- 将它们保存在您运行报告 CLI 的目录中名为 `.env` 的文件中。报告 CLI 仅从当前目录读取 `.env` 文件。 + +在 `.env` 文件中,使用 `NAME=VALUE` 格式,每行一个变量。以 `#` 开头的行是注释。要在值中包含 `#`、`'` 或 `!` 等字符,请用双引号将值括起来。引号不包含在值中。 + +当在多个地方设置相同的值时,报告 CLI 使用以下优先级顺序: + +1. 命令行选项 +1. 在 shell 中导出的环境变量 +1. `.env` 文件中的变量 + +例如,如果 `.env` 文件设置 `OPENSEARCH_FILENAME=test` 而您使用 `--filename report` 选项运行命令,报告将保存为 `report.pdf`。 + +## 示例: 使用 .env 文件请求报告 + +以下 `.env` 文件指定 URL、报告文件名和凭据: + +``` +OPENSEARCH_URL="<dashboards-url>" +OPENSEARCH_FILENAME=daily-traffic +OPENSEARCH_USERNAME=<username> +OPENSEARCH_PASSWORD=<password> +``` + +要使用 `.env` 文件中的值请求 PNG 报告,请从包含该文件的目录运行以下命令: + +```bash +opensearch-reporting-cli --format png --auth basic +``` + +报告保存到当前目录为 `daily-traffic.png`。 + +## 使用 SMTP 通过电子邮件发送报告 + +要使用 SMTP 通过电子邮件发送报告,请在 `.env` 文件中设置以下变量: + +``` +OPENSEARCH_TRANSPORT=smtp +OPENSEARCH_SMTP_HOST=<smtp-host> +OPENSEARCH_SMTP_PORT=<smtp-port> +OPENSEARCH_SMTP_SECURE=true +OPENSEARCH_SMTP_USERNAME=<smtp-username> +OPENSEARCH_SMTP_PASSWORD=<smtp-password> +OPENSEARCH_FROM=<sender-email> +OPENSEARCH_TO=<recipient-email> +``` + +然后运行以下命令: + +```bash +opensearch-reporting-cli --url '<dashboards-url>' +``` + +如果您的 SMTP 服务器不需要身份验证,请省略 `OPENSEARCH_SMTP_USERNAME` 和 `OPENSEARCH_SMTP_PASSWORD`。 + +## 使用 Amazon SES 请求带有报告附件的电子邮件 + +要使用 Amazon SES 作为电子邮件传输,适用以下前提条件: + +- 发件人的电子邮件地址必须经过 [Amazon SES](https://aws.amazon.com/ses/) 验证。 +- 报告 CLI 从您的 AWS 配置中读取 AWS 凭据和 AWS 区域。要使用 [AWS 命令行界面 (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 配置它们,请参阅 AWS 命令行界面用户指南中的[使用 `aws configure` 进行快速配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config)。 +- AWS 凭据必须授予 `ses:SendRawEmail` 权限: + + ```json + { + "Statement": [ + { + "Effect": "Allow", + "Action": "ses:SendRawEmail", + "Resource": "*" + } + ] + } + ``` + +以下命令请求带有报告附件的电子邮件: + +```bash +opensearch-reporting-cli --url '<dashboards-url>' --transport ses --from <sender-email> --to <recipient-email> +``` + +或者,在 `.env` 文件中设置 `OPENSEARCH_TRANSPORT`、`OPENSEARCH_FROM` 和 `OPENSEARCH_TO`,然后仅提供 URL: + +```bash +opensearch-reporting-cli --url '<dashboards-url>' +``` + +## 自定义电子邮件 + +要更改电子邮件主题和正文,请使用 `--subject` 和 `--note` 选项或 `OPENSEARCH_EMAIL_SUBJECT` 和 `OPENSEARCH_EMAIL_NOTE` 变量。要更改电子邮件布局,请在报告 CLI 安装目录中编辑 `src/views/index.hbs` 模板。 + +## 故障排除 + +要解决 **MessageRejected: Email address is not verified**,请参阅 AWS 知识中心中的[为什么我从 Amazon SES 收到 400 "message rejected" 错误,消息为 "Email address is not verified"?](https://repost.aws/knowledge-center/ses-554-400-message-rejected-error) diff --git a/i18n/zh/dashboards/reporting/rep-cli-index.md b/i18n/zh/dashboards/reporting/rep-cli-index.md new file mode 100644 index 00000000..d8a3cf41 --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-index.md @@ -0,0 +1,23 @@ +--- +title: 使用 CLI 进行报告 +--- + +# 使用 CLI 进行报告 + +使用报告 CLI 从脚本或调度程序生成报告,而无需在浏览器中打开 OpenSearch Dashboards。报告 CLI 在无头 Chromium 浏览器中打开仪表板、可视化、笔记本或保存的搜索的 URL,捕获页面,然后将报告保存到当前目录或使用 Amazon Simple Email Service (Amazon SES) 或 SMTP 作为电子邮件附件发送。 + +报告 CLI 从正在运行的 OpenSearch Dashboards 实例加载页面,因此该实例必须可从运行报告 CLI 的机器访问。 + +报告 CLI 支持以下报告格式: + +- 仪表板、可视化和笔记本的 PDF 和 PNG 报告。这些报告不需要报告插件。 +- 保存的搜索的 CSV 报告。报告 CLI 使用**发现**中的**报告**菜单生成 CSV 报告,因此 CSV 报告需要在 OpenSearch Dashboards 中安装报告插件。 + +要连接到 OpenSearch Dashboards,报告 CLI 支持以下身份验证类型: + +- 基本 HTTP 身份验证: 指定 `-a basic` 并提供凭据。 +- Amazon Cognito 身份验证: 指定 `-a cognito` 并提供凭据。要了解有关 Amazon Cognito 的更多信息,请参阅[什么是 Amazon Cognito?](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html)。 +- 使用 Okta 作为身份提供者的 SAML 身份验证: 指定 `-a saml` 并提供凭据。 +- 无身份验证: 省略 `-a` 选项。 + +要开始使用,请参阅[下载并安装报告 CLI 工具](/dashboards/reporting/rep-cli-install)。 diff --git a/i18n/zh/dashboards/reporting/rep-cli-install.md b/i18n/zh/dashboards/reporting/rep-cli-install.md new file mode 100644 index 00000000..9f7a8000 --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-install.md @@ -0,0 +1,53 @@ +--- +title: 下载并安装报告 CLI 工具 +--- + +# 下载并安装报告 CLI 工具 + +从 `npm` 软件注册表或从 OpenSearch.org 下载的归档文件安装报告 CLI 工具。报告 CLI 需要 Node.js。 + +要了解有关 `npm` 软件注册表的更多信息,请参阅 [`npm`](https://docs.npmjs.com/about-npm) 文档。 + +## 从 npm 安装报告 CLI + +要从 `npm` 安装报告 CLI,请运行以下命令: + +```bash +npm install -g @opensearch-project/reporting-cli +``` + +`-g` 选项全局安装报告 CLI,以便 `opensearch-reporting-cli` 命令在每个目录中都可用。如果您在没有 `-g` 的情况下安装包,请使用 `npx opensearch-reporting-cli` 从安装目录运行命令。 + +## 从归档文件安装报告 CLI + +下载[报告 CLI 归档文件](https://artifacts.opensearch.org/reporting-cli/opensearch-reporting-cli-1.1.0.tgz),然后通过运行以下命令安装归档文件: + +```bash +npm install -g opensearch-reporting-cli-1.1.0.tgz +``` + +::: warning IMPORTANT +要确认归档文件由 OpenSearch 项目发布且未被修改,请使用[报告 CLI 签名文件](https://artifacts.opensearch.org/reporting-cli/opensearch-reporting-cli-1.1.0.tgz.sig)验证其签名。 +::: + +要了解有关验证签名的更多信息,请参阅[如何验证可下载工件的签名](https://opensearch.org/verify-signatures/)。 + +## 验证安装 + +要验证安装并列出所有可用选项,请运行以下命令: + +```bash +opensearch-reporting-cli -h +``` + +## Chromium + +报告 CLI 使用 Chromium 渲染报告,`npm` 在安装期间运行 Puppeteer 安装脚本时下载 Chromium。如果您的 `npm` 配置跳过安装脚本,则不会下载 Chromium。 + +在所有 macOS 计算机上,下载的 Chromium 是 x86-64 二进制文件。在配备 Apple 芯片的 Mac 上,除非安装了 Rosetta 2,否则报告 CLI 会失败并显示错误 `spawn Unknown system error -86`。 + +要使用不同的 Chromium 或 Chrome 二进制文件,例如 Arm64 版本或包管理器安装的浏览器,请将 `CHROMIUM_PATH` 环境变量设置为浏览器可执行文件的路径: + +```bash +export CHROMIUM_PATH=<path-to-chromium-executable> +``` diff --git a/i18n/zh/dashboards/reporting/rep-cli-lambda.md b/i18n/zh/dashboards/reporting/rep-cli-lambda.md new file mode 100644 index 00000000..64c1cdfd --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-lambda.md @@ -0,0 +1,170 @@ +--- +title: 使用 AWS Lambda 计划报告 +--- + +<!-- vale off --> +# 使用 AWS Lambda 计划报告 +<!-- vale on --> + +使用 AWS Lambda 在响应触发器(如计划)时运行报告 CLI。Lambda 函数从容器镜像运行报告 CLI,因此您报告的 OpenSearch Dashboards URL 必须可从 Lambda 函数访问。 + +容器镜像安装仅适用于 x86-64 架构的 Google Chrome 依赖项。要构建镜像,您需要 Docker。在具有不同架构的计算机上,例如配备 Apple 芯片的 Mac,请使用 `--platform linux/amd64` 选项构建镜像。 + +### 前提条件 + +要将报告 CLI 与 AWS Lambda 一起使用,您需要完成以下准备步骤。 + +- 获取 AWS 账户。有关说明,请参阅 AWS 账户管理参考指南中的[创建 AWS 账户](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html)。 +- 设置 Amazon Elastic Container Registry (Amazon ECR)。有关说明,请参阅[使用 AWS 管理控制台开始使用 Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-console.html)。 + +## 步骤 1: 使用 Dockerfile 创建容器镜像 + +您需要通过运行 Dockerfile 组装容器镜像。运行 Dockerfile 时,它会下载使用报告 CLI 所需的 OpenSearch 工件。要了解有关 Dockerfile 的更多信息,请参阅 [Dockerfile 参考](https://docs.docker.com/engine/reference/builder/)。 + +将以下示例配置复制到 Dockerfile 中: + +```dockerfile +# Define function directory +ARG FUNCTION_DIR="/function" + +# Base image of the docker container +FROM node:lts-slim AS build-image + +# Include global arg in this stage of the build +ARG FUNCTION_DIR + +# AWS Lambda runtime dependencies +RUN apt-get update && \ + apt-get install -y \ + g++ \ + make \ + unzip \ + libcurl4-openssl-dev \ + autoconf \ + automake \ + libtool \ + cmake \ + python3 \ + libkrb5-dev \ + curl + +# Copy function code +WORKDIR ${FUNCTION_DIR} +RUN npm install @opensearch-project/reporting-cli && npm install aws-lambda-ric + +# Build Stage 2: Copy Build Stage 1 files in to Stage 2. Install chrome, then remove chrome to keep the dependencies. +FROM node:lts-slim +# Include global arg in this stage of the build +ARG FUNCTION_DIR +# Set working directory to function root directory +WORKDIR ${FUNCTION_DIR} +# Copy in the build image dependencies +COPY --from=build-image ${FUNCTION_DIR} ${FUNCTION_DIR} + +# Install latest chrome dev package and fonts to support major char sets (Chinese, Japanese, Arabic, Hebrew, Thai and a few others) +# Note: this installs the necessary libs to make the bundled version of Chromium that Puppeteer installs, work. +RUN apt-get update \ + && apt-get install -y wget gnupg \ + && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ + && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \ + && apt-get update \ + && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \ + --no-install-recommends \ + && apt-get remove -y google-chrome-stable \ + && rm -rf /var/lib/apt/lists/* + +ENTRYPOINT ["/usr/local/bin/npx", "aws-lambda-ric"] + +ENV HOME="/tmp" +CMD [ "/function/node_modules/@opensearch-project/reporting-cli/src/index.handler" ] + +``` + +接下来,在包含 Dockerfile 的同一目录中运行以下构建命令: + +```bash +docker build --platform linux/amd64 -t opensearch-reporting-cli . +``` + +## 步骤 2: 使用 Amazon ECR 创建私有仓库 + +您需要按照说明创建镜像仓库,请参阅[使用 AWS 管理控制台开始使用 Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-console.html)。 + +将您的仓库命名为 `opensearch-reporting-cli`。 + +除了 Amazon ECR 说明外,您还需要进行一些调整以使报告 CLI 正常运行,如此过程后续步骤所述。 + +## 步骤 3: 将镜像推送到私有仓库 + +您需要从 AWS ECR 控制台获取几个命令以在 Dockerfile 目录中运行。 + +1. 创建仓库后,从**私有仓库**中选择它。 +1. 选择**查看推送命令**。 +1. 复制并在 Dockerfile 目录中按顺序运行 **opensearch-reporting-cli 的推送命令**中显示的每个命令。 + +有关 Docker 推送命令的更多详细信息,请参阅 Amazon ECR 用户指南中的[推送 Docker 镜像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)。 + +## 步骤 4: 使用容器镜像创建 Lambda 函数 + +现在您已为报告 CLI 创建了容器镜像,您需要创建一个定义为容器镜像的函数。 + +1. 打开 AWS Lambda 控制台并选择 [Functions](https://us-west-2.console.aws.amazon.com/lambda/home?region=us-west-2#/functions)。 +1. 选择**创建函数**,然后选择**容器镜像**并填写函数名称。 +1. 在**容器镜像 URI** 中,选择**浏览镜像**并为镜像仓库选择 `opensearch-reporting-cli`。 +1. 在**镜像**中选择镜像,然后选择**选择镜像**。 +1. 在**架构**中,选择 **x86_64**。 +1. 选择**创建函数**。 +1. 转到 **Lambda** > **函数**并选择您创建的函数。 +1. 选择**配置 > 常规配置 > 编辑超时**并将 Lambda 中的超时设置为 5 分钟,以允许报告 CLI 生成报告。 +1. 将**临时存储**设置更改为至少 1024 MB。默认设置不足以支持报告生成。 +1. 通过在 JSON 测试事件或 Lambda 环境变量中提供值来测试函数。 + +要提供每次运行都相同的值(如电子邮件地址),请在 Lambda 函数配置中设置相应的环境变量,如 `OPENSEARCH_FROM` 和 `OPENSEARCH_TO`。要在测试事件或触发器有效负载中提供值,请使用不带前导破折号的长选项名称作为 JSON 键,例如 `url`、`format`、`transport`、`from` 和 `to`。对于 `credentials` 键,请以 `<username>:<password>` 格式指定值。有关选项和环境变量的列表,请参阅[报告 CLI 选项](/dashboards/reporting/rep-cli-options)。 + +以下示例事件指定 URL、电子邮件传输、发件人和收件人电子邮件地址以及电子邮件主题: + +```json +{ + "url": "https://playground.opensearch.org/app/dashboards#/view/084aed50-6f48-11ed-a3d5-1ddbf0afc873", + "transport": "ses", + "from": "sender@example.com", + "to": "recipient@example.com", + "subject": "Test lambda docker image" +} +``` + +Lambda 函数将报告保存在函数的 `/tmp` 目录中,因此请指定电子邮件传输以接收报告。 + +要了解有关 AWS Lambda 函数的更多信息,请参阅 AWS Lambda 文档中的[将 Lambda 函数部署为容器镜像](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-images.html)。 + +## 步骤 5: 添加触发器以启动 AWS Lambda 函数 + +设置启动报告的触发器。AWS Lambda 可以使用其他 AWS 服务作为触发器,例如 Amazon Simple Notification Service (Amazon SNS)、Amazon S3 或 Amazon EventBridge。 + +1. 在**触发器**部分,选择**添加触发器**。 +1. 从列表中选择触发器。要按计划生成报告,请使用 Amazon EventBridge 计划。有关更多信息,请参阅 AWS Lambda 文档中的[按计划调用 Lambda 函数](https://docs.aws.amazon.com/lambda/latest/dg/with-eventbridge-scheduler.html)。 +1. 选择**测试**以启动函数。 + +## (可选) 步骤 6: 为 Amazon SES 添加角色权限 + +如果您想使用 Amazon SES 作为电子邮件传输,您需要设置权限。 + +1. 选择**配置**并选择**执行角色**。 +1. 在**摘要**中,选择**权限**。 +1. 选择 **{}JSON** 以打开 JSON 策略编辑器。 +1. 为您要使用的 Amazon SES 资源添加权限。 + +以下示例提供发送电子邮件操作的资源 ARN: + +```json +{ +"Effect": "Allow", +"Action": [ + "ses:SendEmail", + "ses:SendRawEmail" + ], +"Resource": "arn:aws:ses:us-west-2:555555511111:identity/sender@example.com" +} +``` + +要了解有关设置角色权限的更多信息,请参阅 AWS Lambda 用户指南中的[权限](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-images.html#gettingstarted-images-permissions)。 diff --git a/i18n/zh/dashboards/reporting/rep-cli-options.md b/i18n/zh/dashboards/reporting/rep-cli-options.md new file mode 100644 index 00000000..0e0f81c0 --- /dev/null +++ b/i18n/zh/dashboards/reporting/rep-cli-options.md @@ -0,0 +1,40 @@ +--- +title: 报告 CLI 选项 +--- + +# 报告 CLI 选项 + +`opensearch-reporting-cli` 工具支持以下选项。选项值区分大小写,必须为小写。命令行上提供的选项优先于环境变量。有关更多信息,请参阅[在报告 CLI 中使用环境变量](/dashboards/reporting/rep-cli-env-var)。 + +| 选项 | 描述 | 环境变量 | +| :--- | :--- | :--- | +| `-u`, `--url` | 仪表板、可视化、笔记本或保存的搜索的 OpenSearch Dashboards URL。要获取 URL,请选择**共享** > **永久链接** > **复制链接**。必需。| `OPENSEARCH_URL` | +| `-a`, `--auth` | 身份验证类型。有效值为 `basic`、`cognito` 和 `saml`。需要凭据。要在没有身份验证的情况下连接,请省略此选项。| N/A | +| `-c`, `--credentials` | OpenSearch Dashboards 登录凭据,格式为 `<username>:<password>`。| `OPENSEARCH_USERNAME` 和 `OPENSEARCH_PASSWORD` | +| `-t`, `--tenant` | 启用多租户时登录后选择的租户。有效值为 `private`、`global` 或自定义租户的名称。URL 中指定的租户优先于此选项。默认为 `private`。| N/A | +| `--multitenancy` | 登录后是否选择租户。有效值为 `true` 和 `false`。默认为 `true`。| N/A | +| `-f`, `--format` | 报告的文件格式。有效值为 `pdf`、`png` 和 `csv`。`csv` 格式仅支持保存的搜索。默认为 `pdf`。| N/A | +| `-w`, `--width` | 浏览器窗口宽度,以像素为单位。默认为 `1680`。| N/A | +| `-l`, `--height` | 浏览器窗口最小高度,以像素为单位。默认为 `600`。| N/A | +| `-n`, `--filename` | 报告的文件名,不带扩展名。默认为 `opensearch-report-<timestamp>`。| `OPENSEARCH_FILENAME` | +| `-e`, `--transport` | 电子邮件传输。有效值为 `ses` (Amazon SES) 和 `smtp`。如果未指定,报告不会通过电子邮件发送。| `OPENSEARCH_TRANSPORT` | +| `-s`, `--from` | 发件人电子邮件地址。| `OPENSEARCH_FROM` | +| `-r`, `--to` | 收件人电子邮件地址。要指定多个收件人,请用逗号分隔地址。| `OPENSEARCH_TO` | +| `--smtphost` | SMTP 服务器的主机名。| `OPENSEARCH_SMTP_HOST` | +| `--smtpport` | SMTP 服务器的端口。| `OPENSEARCH_SMTP_PORT` | +| `--smtpsecure` | 指定 `true` 以在连接到 SMTP 服务器时使用 TLS。任何值都会启用 TLS,包括 `false`,因此要在没有 TLS 的情况下连接,请省略此选项。| `OPENSEARCH_SMTP_SECURE` | +| `--smtpusername` | SMTP 用户名。| `OPENSEARCH_SMTP_USERNAME` | +| `--smtppassword` | SMTP 密码。| `OPENSEARCH_SMTP_PASSWORD` | +| `--selfsignedcerts` | 是否接受来自 SMTP 服务器的自签名证书。有效值为 `true` 和 `false`。默认为 `false`。| N/A | +| `--subject` | 电子邮件主题。默认为 `This is an email containing your opensearch dashboard report`。| `OPENSEARCH_EMAIL_SUBJECT` | +| `--note` | 电子邮件正文,可以是字符串或文本文件的路径。默认为 `Hi,\nHere is the latest report!`。| `OPENSEARCH_EMAIL_NOTE` | +| `--timeout` | 等待页面加载的最长时间,以毫秒为单位。默认为 `300000` (5 分钟)。| `OPENSEARCH_TIMEOUT` | +| `-h`, `--help` | 显示选项列表。| N/A | + +## 获取帮助 + +要获取所有可用选项的列表,请运行以下命令: + +```bash +opensearch-reporting-cli -h +``` diff --git a/i18n/zh/dashboards/reporting/report-dashboard-index.md b/i18n/zh/dashboards/reporting/report-dashboard-index.md new file mode 100644 index 00000000..899243fd --- /dev/null +++ b/i18n/zh/dashboards/reporting/report-dashboard-index.md @@ -0,0 +1,93 @@ +--- +title: 使用 OpenSearch Dashboards 进行报告 +--- + +# 使用 OpenSearch Dashboards 进行报告 + +使用 OpenSearch Dashboards 从您正在查看的页面生成报告,以及创建、管理和删除报告定义。有关报告定义、每种报告源可用的文件格式以及所需权限的信息,请参阅[报告](/dashboards/reporting/)。要以编程方式执行这些操作,请参阅[报告 API](/dashboards/reporting/api)。 + +## 生成报告 + +要从界面生成报告,请执行以下步骤: + +1. 打开要报告的仪表板、可视化、笔记本或保存的搜索。 +1. 在顶部菜单中,选择**报告**。 +1. 选择格式: + - 对于仪表板、可视化和笔记本,选择**下载 PDF** 或**下载 PNG**。 + - 对于**发现**中的保存的搜索,选择**生成 CSV** 或**生成 XLSX**。 + + 报告在后台异步生成,可能需要几分钟,具体取决于报告的大小。当您的报告准备就绪时会出现通知,文件将被下载。 + +要按计划生成报告,请在**报告**菜单中选择**创建报告定义**,然后继续[使用定义创建报告](#使用定义创建报告)。此选项会根据您正在查看的页面填充许多字段。 + +要查看您生成的报告,请在**报告**菜单中选择**查看报告**。 + +## 使用定义创建报告 + +定义允许您按定期计划生成报告。 + +1. 在顶部菜单中,转到 **OpenSearch 插件** > **报告**。 +1. 在**报告定义**部分,选择**创建**。 +1. 在**报告设置**中,输入报告的名称和可选描述。 +1. 选择**报告源**: **仪表板**、**可视化**、**保存的搜索**或**笔记本**。 +1. 选择您的仪表板、可视化、保存的搜索或笔记本。然后为报告选择时间范围。 +1. 为报告选择文件格式。对于保存的搜索,您还可以设置**记录限制**。 +1. (可选) 向报告添加页眉或页脚。页眉和页脚仅适用于仪表板、可视化和笔记本报告。 +1. 在**报告触发器**中,选择**按需**或**计划**。 + + 对于计划报告,选择**重复**或**基于 Cron**。重复报告每天或按指定间隔运行。Cron 表达式为您提供更大的灵活性。有关更多信息,请参阅 [Cron 表达式](/api-reference/cron-expressions)。 + +1. 选择**创建**。 + +## 删除报告定义 + +您可以从 OpenSearch Dashboards 或使用 API 删除报告定义。删除报告定义不会删除之前生成的报告。 + +::: info NOTE +无法单独删除生成的报告。 +::: + +### 从 OpenSearch Dashboards 删除 + +要删除报告定义,请执行以下步骤: + +1. 在顶部菜单中,转到 **OpenSearch 插件** > **报告**。 +1. 在**报告定义**部分,选择要删除的报告定义的名称。 +1. 在报告定义详细信息页面上,选择**删除**。 +1. 在确认对话框中,选择**删除**。 + +### 使用 API 删除 + +要删除报告定义,请发送以下请求: + +```json +DELETE _plugins/_reports/definition/{report_definition_id} +``` + +要查找报告定义 ID,请列出所有定义: + +```json +GET _plugins/_reports/definitions +``` + +有关完整的报告端点集,请参阅[报告 API](/dashboards/reporting/api)。 + +## 故障排除 + +您可以使用以下主题排除和解决报告问题。 + +### Chromium 无法与 OpenSearch Dashboards 一起启动 + +在为仪表板或可视化创建报告时,您可能会看到以下错误: + +![OpenSearch Dashboards 报告弹出错误消息](/images/reporting-error.png) + +此问题可能由于两个原因发生: + +- 您没有与 OpenSearch Dashboards 运行的操作系统匹配的正确版本的 headless-chrome。下载[正确版本](https://github.com/opensearch-project/reporting/releases/tag/chromium-1.12.0.0)。 + +- 您缺少其他依赖项。从[其他库](https://github.com/opensearch-project/dashboards-reports/blob/1.x/dashboards-reports/rendering-engine/headless-chrome/README.md#additional-libaries)部分为您的操作系统安装所需的依赖项。 + +### 报告中字符不加载 + +您可能会遇到 UTF-8 编码字符在浏览器中看起来正常,但在生成的报告中不加载的问题,因为您缺少所需的字体依赖项。安装[字体依赖项](https://github.com/opensearch-project/dashboards-reports#missing-font-dependencies),然后再次生成报告。 diff --git a/i18n/zh/dashboards/reporting/report-definition-access-control.md b/i18n/zh/dashboards/reporting/report-definition-access-control.md new file mode 100644 index 00000000..47c597b3 --- /dev/null +++ b/i18n/zh/dashboards/reporting/report-definition-access-control.md @@ -0,0 +1,134 @@ +--- +title: 报告定义访问控制 +--- + +# 报告定义访问控制 + +报告插件与安全插件的资源共享和访问控制框架集成,为报告定义记录提供文档级授权。这用更灵活的共享系统取代了旧版 plugins.alerting.filter_by_backend_roles 设置,允许资源所有者向用户、角色或后端角色授予特定访问级别。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +下表描述了报告定义资源配置。 + +| 字段 | 值 | +| :--- |:----------------------------------| +| 资源类型 | report-definition | +| 系统索引 | .opendistro-reports-definitions | +| 加入版本 | OpenSearch 3.5 | + +当为报告定义启用资源级授权时,每个报告定义的可见性由中央共享记录管理。资源所有者和具有共享功能的用户可以为特定用户、角色或后端角色授予或撤销访问权限。 + +## 启用报告定义资源共享 + +要启用报告定义的资源共享,您必须将报告定义资源类型添加到受保护类型列表中并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员: 这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 opensearch.yml 配置文件以启用报告定义的资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "report-definition" +``` + +### 使用集群设置 API 配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["report-definition"] + } +} +``` + +::: info NOTE +将报告定义资源类型添加到现有配置时,请在 protected_types 数组中包含所有先前配置的资源类型。 +::: + +## 报告定义访问级别 + +报告提供以下预定义的报告定义文档访问级别。这些访问级别确定授予已被授予报告定义资源访问权限的用户的特定权限。 + +### rd_read_only + +rd_read_only 只读访问级别授予用户查看和搜索共享报告定义的能力,但不能修改它们。此访问级别包括以下权限: + +```yaml +- "cluster:admin/opendistro/reports/definition/get" +- "cluster:admin/opendistro/reports/definition/list" +- "cluster:admin/opendistro/reports/instance/get" +- "cluster:admin/opendistro/reports/instance/list" +- "cluster:admin/opendistro/reports/menu/download" +``` + +### rd_read_write + +rd_read_write 读写访问级别授予用户对报告定义操作的完全访问权限,但不包括共享功能。此访问级别包括所有读取权限加上写入操作: + +```yaml +- "cluster:admin/opendistro/reports/definition/*" +- "cluster:admin/opendistro/reports/instance/*" +- "cluster:admin/opendistro/reports/menu/download" +``` + +### rd_full_access + +rd_full_access 完全访问级别授予用户对报告定义的完全控制,包括类似所有者的权限,如与其他用户共享资源。此访问级别包括所有报告定义操作加上资源共享权限: + +```yaml +- "cluster:admin/opendistro/reports/definition/*" +- "cluster:admin/opendistro/reports/instance/get" +- "cluster:admin/opendistro/reports/instance/list" +- "cluster:admin/opendistro/reports/menu/download" +- "cluster:admin/security/resource/share" +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在[报告 GitHub 仓库](https://github.com/opensearch-project/reporting/)中创建问题。 +::: + +## 从旧版框架迁移 + +启用资源共享并将报告定义标记为受保护资源类型后,集群管理员必须运行迁移 API 以将现有报告定义共享信息从旧版框架传输到新的资源共享系统。 + +::: warning IMPORTANT +仅限管理员: 迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +使用以下 API 调用将旧版报告定义共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-reports-definitions", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "report-definition": "<select-appropriate-access-level>" + } +} +``` + +将 <replace-with-existing-user> 替换为应拥有没有明确所有权信息的报告定义的现有用户的用户名。将 <select-appropriate-access-level> 替换为可用的报告定义访问级别之一: rd_read_only、rd_read_write 或 rd_full_access。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于编程管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流程和用户指南 +- [报告实例访问控制](/dashboards/reporting/report-instance-access-control) -- 报告实例的访问控制 diff --git a/i18n/zh/dashboards/reporting/report-instance-access-control.md b/i18n/zh/dashboards/reporting/report-instance-access-control.md new file mode 100644 index 00000000..e4561cc8 --- /dev/null +++ b/i18n/zh/dashboards/reporting/report-instance-access-control.md @@ -0,0 +1,129 @@ +--- +title: 报告实例访问控制 +--- + +# 报告实例访问控制 + +报告插件与安全插件的资源共享和访问控制框架集成,为报告实例记录提供文档级授权。这用更灵活的共享系统取代了旧版 plugins.alerting.filter_by_backend_roles 设置,允许资源所有者向用户、角色或后端角色授予特定访问级别。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +下表描述了报告实例资源配置。 + +| 字段 | 值 | +| :--- |:----------------------------------| +| 资源类型 | report-instance | +| 系统索引 | .opendistro-reports-instances | +| 加入版本 | OpenSearch 3.5 | + +当为报告实例启用资源级授权时,每个报告实例的可见性由中央共享记录管理。资源所有者和具有共享功能的用户可以为特定用户、角色或后端角色授予或撤销访问权限。 + +## 启用报告实例资源共享 + +要启用报告实例的资源共享,您必须将报告实例资源类型添加到受保护类型列表中并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员: 这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 opensearch.yml 配置文件以启用报告实例的资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "report-instance" +``` + +### 使用集群设置 API 配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["report-instance"] + } +} +``` + +::: info NOTE +将报告实例资源类型添加到现有配置时,请在 protected_types 数组中包含所有先前配置的资源类型。 +::: + +## 报告实例访问级别 + +报告提供以下预定义的报告实例文档访问级别。这些访问级别确定授予已被授予报告实例资源访问权限的用户的特定权限。 + +### ri_read_only + +ri_read_only 只读访问级别授予用户查看和搜索共享报告实例的能力,但不能修改它们。此访问级别包括以下权限: + +```yaml +- "cluster:admin/opendistro/reports/instance/get" +- "cluster:admin/opendistro/reports/instance/list" +- "cluster:admin/opendistro/reports/menu/download" +``` + +### ri_read_write + +ri_read_write 读写访问级别授予用户对报告实例操作的完全访问权限,但不包括共享功能。此访问级别包括所有读取权限加上写入操作: + +```yaml +- "cluster:admin/opendistro/reports/instance/*" +- "cluster:admin/opendistro/reports/menu/download" +``` + +### ri_full_access + +ri_full_access 完全访问级别授予用户对报告实例的完全控制,包括类似所有者的权限,如与其他用户共享资源。此访问级别包括所有报告实例操作加上资源共享权限: + +```yaml +- "cluster:admin/opendistro/reports/instance/*" +- "cluster:admin/opendistro/reports/menu/download" +- "cluster:admin/security/resource/share" +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在[报告 GitHub 仓库](https://github.com/opensearch-project/reporting/)中创建问题。 +::: + +## 从旧版框架迁移 + +启用资源共享并将报告实例标记为受保护资源类型后,集群管理员必须运行迁移 API 以将现有报告实例共享信息从旧版框架传输到新的资源共享系统。 + +::: warning IMPORTANT +仅限管理员: 迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +使用以下 API 调用将旧版报告实例共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-reports-instances", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "report-instance": "<select-appropriate-access-level>" + } +} +``` + +将 <replace-with-existing-user> 替换为应拥有没有明确所有权信息的报告实例的现有用户的用户名。将 <select-appropriate-access-level> 替换为可用的报告实例访问级别之一: ri_read_only、ri_read_write 或 ri_full_access。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于编程管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流程和用户指南 +- [报告定义访问控制](/dashboards/reporting/report-definition-access-control) -- 报告定义的访问控制 diff --git a/i18n/zh/dashboards/settings-and-administration.md b/i18n/zh/dashboards/settings-and-administration.md new file mode 100644 index 00000000..aeb27281 --- /dev/null +++ b/i18n/zh/dashboards/settings-and-administration.md @@ -0,0 +1,16 @@ +--- +title: 设置和管理 +--- + +# 设置和管理 + +通过编辑 `opensearch_dashboards.yml` 配置文件在部署级别配置和管理 OpenSearch Dashboards。本文档面向 OpenSearch Dashboards 管理员。以下设置可用: + +- [自定义品牌](/dashboards/branding): 用您自己的品牌元素替换默认的 OpenSearch 徽标和其他品牌元素。 +- [网络压缩](/dashboards/compression): 压缩 JavaScript 和 CSS 包以减少网络传输大小。 +- [配置 CSP 规则](/dashboards/csp/csp-dynamic-configuration): 执行内容安全策略 (CSP) 规则以防止跨站点脚本和其他代码注入攻击。 +- [搜索遥测](/dashboards/search-telemetry): 分析 OpenSearch Dashboards 中的搜索请求性能。 + +## 相关文档 + +- 要从 Dashboards UI 中配置数据访问、索引模式、保存的对象和其他设置,请参阅 [Dashboards 管理](/dashboards/management/management-index)。 diff --git a/i18n/zh/dashboards/visualize/area.md b/i18n/zh/dashboards/visualize/area.md index 6518ed23..caa683dc 100644 --- a/i18n/zh/dashboards/visualize/area.md +++ b/i18n/zh/dashboards/visualize/area.md @@ -4,49 +4,49 @@ title: 使用面积图 # 使用面积图 -面积图是折线图,折线和轴之间的区域用颜色填充,是用于显示时间序列数据的主要可视化类型。你可以在 Dashboards 中使用面积可视化类型或使用时间序列可视化构建器 (TSVB)、Vega 或 VisBuilder 可视化工具创建面积图。在本教程中,你将使用面积可视化类型。 +面积图是一种折线图,折线与坐标轴之间的区域用颜色填充,是用于显示时间序列数据的主要可视化类型。您可以在 Dashboards 中使用面积图可视化类型或使用时间序列可视化构建器(TSVB)、Vega 或 VisBuilder 可视化工具创建面积图。在本教程中,您将使用面积图可视化类型。 ![面积图教程步骤演示](/images/dashboards/area-tutorial.gif) # 试一试:创建一个简单的基于聚合的面积图 -在本教程中,你将在 OpenSearch Dashboards 中使用示例数据和聚合创建一个简单的面积图,方法是通过浏览器连接到 [http://localhost:5601](http://localhost:5601)。 +在本教程中,您将在 OpenSearch Dashboards 中使用示例数据和聚合创建一个简单的面积图,方法是通过浏览器连接到 [http://localhost:5601](http://localhost:5601)。 -Dashboards 中有几个聚合选项,你的选择会影响你的分析。聚合的用例从实时分析数据到使用 Dashboards 创建可视化仪表板不等。如果你需要 OpenSearch 中聚合的概述,请在开始本教程之前参阅[聚合](/aggregations/)。 +Dashboards 中有多种聚合选项,选择会影响您的分析。聚合的用例从实时分析数据到使用 Dashboards 创建可视化仪表板不等。如果您需要 OpenSearch 中聚合的概述,请在开始本教程之前参阅[聚合](/aggregations/)。 ::: info NOTE -在继续本教程之前,请确保你已[安装最新版本的 Dashboards](https://opensearch.org/docs/latest/install-and-configure/install-dashboards/index/) 并添加了示例数据。_本教程使用 Dashboards 2.4.1 版本_。 +在继续本教程之前,请确保您已[安装最新版本的 Dashboards](https://opensearch.org/docs/latest/install-and-configure/install-dashboards/index/) 并添加了示例数据。_本教程使用 Dashboards 2.4.1 版本_。 ::: ## 设置面积图 1. 通过浏览器连接到 [http://localhost:5601](http://localhost:5601) 访问 Dashboards。 -1. 从菜单中选择 **Visualize**,然后选择 **创建可视化**。 -1. 从窗口中选择 **面积**。 -1. 在 **新建面积/选择源** 窗口中选择 **opensearch_dashboards_sample_data_flights**。 -1. 选择日历图标并将时间过滤器设置为 **最近 7 天**。 -1. 选择 **更新**。 +1. 从菜单中选择**可视化**,然后选择**创建可视化**。 +1. 从窗口中选择**面积图**。 +1. 在**新面积图/选择数据源**窗口中选择 **opensearch_dashboards_sample_data_flights**。 +1. 选择日历图标并将时间过滤器设置为**过去 7 天**。 +1. 选择**更新**。 ## 向面积图添加聚合 -继续使用前面步骤中创建的面积图,你将创建一个可视化,显示过去七天内每三小时延误航班的前五个日志: +继续使用前面步骤中创建的面积图,您将创建一个可视化,显示过去七天内每三小时延误航班的前五条日志: -1. 添加 **指标** 聚合。 - 1. 在 **指标** 下,选择 **聚合** 下拉列表并选择 **平均值**,然后选择 **字段** 下拉列表并选择 **FlightDelayMin**。 - 1. 在 **指标** 下,选择 **添加** 以添加另一个 Y 轴聚合。 - 1. 选择 **聚合** 下拉列表并选择 **最大值**,然后选择 **字段** 下拉列表并选择 **FlightDelayMin**。 -1. 添加 **桶** 聚合。 - 1. 选择 **添加** 以打开 **添加桶** 窗口,然后选择 **X 轴**。 - 2. 从 **聚合** 下拉列表中,选择 **日期直方图**。 - 3. 从 **字段** 下拉列表中,选择 **timestamp**。 - 4. 选择 **更新**。 +1. 添加**指标**聚合。 + 1. 在**指标**下,选择**聚合**下拉列表并选择**平均值**,然后选择**字段**下拉列表并选择 **FlightDelayMin**。 + 1. 在**指标**下,选择**添加**以添加另一个 Y 轴聚合。 + 1. 选择**聚合**下拉列表并选择**最大值**,然后选择**字段**下拉列表并选择 **FlightDelayMin**。 +1. 添加**分桶**聚合。 + 1. 选择**添加**打开**添加分桶**窗口,然后选择 **X 轴**。 + 2. 从**聚合**下拉列表中,选择**日期直方图**。 + 3. 从**字段**下拉列表中,选择 **timestamp**。 + 4. 选择**更新**。 2. 添加子聚合。 - 1. 选择 **添加** 以打开 **添加子桶** 窗口,然后选择 **拆分系列**。 - 2. 从 **子聚合** 下拉列表中,选择 **词条**。 - 3. 从 **字段** 下拉列表中,选择 **FlightDelay**。 - 4. 选择 **更新** 以在图形中反映这些参数。 + 1. 选择**添加**打开**添加子分桶**窗口,然后选择**拆分系列**。 + 2. 从**子聚合**下拉列表中,选择**词条**。 + 3. 从**字段**下拉列表中,选择 **FlightDelay**。 + 4. 选择**更新**以在图表中反映这些参数。 -你现在已经创建了以下基于聚合的面积图。 +您现在已经创建了以下基于聚合的面积图。 ![生成的基于聚合的面积图](/images/area-aggregation-tutorial.png) diff --git a/i18n/zh/dashboards/visualize/gantt.md b/i18n/zh/dashboards/visualize/gantt.md index 5bb6b3d3..bbdda0f8 100644 --- a/i18n/zh/dashboards/visualize/gantt.md +++ b/i18n/zh/dashboards/visualize/gantt.md @@ -4,20 +4,20 @@ title: 使用甘特图 # 甘特图 -OpenSearch Dashboards 包含甘特图可视化。甘特图显示序列中唯一事件的开始、结束和持续时间。甘特图在跟踪分析、遥测和异常检测用例中很有用,当你想了解计划中各种事件之间的交互和依赖关系时。 +OpenSearch Dashboards 包含甘特图可视化。甘特图显示序列中唯一事件的开始、结束和持续时间。甘特图在追踪分析、遥测和异常检测用例中非常有用,您可以在这些场景中了解计划中各种事件之间的交互和依赖关系。 -例如,考虑一个日志数据索引。典型日志数据中的字段,尤其是审计日志,包含具有开始时间和持续时间的特定操作或事件。 +例如,考虑一个日志数据索引。典型日志数据(尤其是审计日志)中的字段包含具有开始时间和持续时间的特定操作或事件。 要创建甘特图,请执行以下步骤: -1. 在可视化菜单中,选择 **创建可视化** 和 **甘特图**。 -1. 为图表选择源(例如一些日志数据)。 -1. 在 **指标** 下,选择 **事件**。对于日志数据,每个日志就是一个事件。 -1. 从数据集中选择 **开始时间** 和 **持续时间** 字段。开始时间是事件开始的时间戳。持续时间是要添加到开始时间的时间量。 -1. 在 **结果** 下,选择要在图表上显示的事件数量。甘特图根据开始时间从最早到最晚排列事件。 -1. 选择 **面板设置** 以调整轴标签、时间格式和颜色。 -1. 选择 **更新**。 +1. 在可视化菜单中,选择**创建可视化**和**甘特图**。 +1. 选择图表的数据源(例如一些日志数据)。 +1. 在**指标**下,选择**事件**。对于日志数据,每条日志就是一个事件。 +1. 从数据集中选择**开始时间**和**持续时间**字段。开始时间是事件开始的时间戳。持续时间是要添加到开始时间的时间量。 +1. 在**结果**下,选择要在图表上显示的事件数量。甘特图根据开始时间从最早到最晚对事件进行排序。 +1. 选择**面板设置**以调整轴标签、时间格式和颜色。 +1. 选择**更新**。 ![甘特图](/images/dashboards/gantt-chart.png) -此甘特图在 Y 轴上显示每个日志的 ID。每个条形是一个跨越一定时间的唯一事件。将鼠标悬停在条形上可以看到该事件的持续时间。 +此甘特图在 Y 轴上显示每条日志的 ID。每个条形是一个跨越一定时间的唯一事件。将鼠标悬停在条形上可查看该事件的持续时间。 diff --git a/i18n/zh/dashboards/visualize/geojson-regionmaps.md b/i18n/zh/dashboards/visualize/geojson-regionmaps.md index 9c27f1b8..41d759e6 100644 --- a/i18n/zh/dashboards/visualize/geojson-regionmaps.md +++ b/i18n/zh/dashboards/visualize/geojson-regionmaps.md @@ -4,24 +4,24 @@ title: 使用坐标和区域地图 # 使用坐标和区域地图 -OpenSearch 有一套标准的 GeoJSON 文件,为每个区域地图提供矢量地图。OpenSearch Dashboards 还提供带有标准矢量地图的基本地图切片来创建区域地图。你可以使用 [Web 地图服务 (WMS)](https://www.ogc.org/standards/wms) 配置底图切片。有关更多信息,请参阅[在 OpenSearch Dashboards 中配置 WMS](/dashboards/visualize/maptiles)。 +OpenSearch 有一组标准的 GeoJSON 文件,为每个区域地图提供矢量地图。OpenSearch Dashboards 还提供带有标准矢量地图的基本地图切片来创建区域地图。您可以使用 [Web 地图服务(WMS)](https://www.ogc.org/standards/wms) 配置基础地图切片。有关更多信息,请参阅[在 OpenSearch Dashboards 中配置 WMS](/dashboards/visualize/maptiles)。 -对于隔离网络环境,OpenSearch Dashboards 提供了自托管地图服务器。有关更多信息,请参阅[使用自托管地图服务器](/dashboards/visualize/selfhost-maps-server) +对于隔离网络环境,OpenSearch Dashboards 提供自托管地图服务器。有关更多信息,请参阅[使用自托管地图服务器](/dashboards/visualize/selfhost-maps-server) ::: info NOTE -虽然你无法配置服务器来支持用户定义的矢量地图图层,但你可以配置自己的 GeoJSON 文件并上传它以实现此目的。 +虽然您无法配置服务器以支持用户定义的矢量地图图层,但您可以配置自己的 GeoJSON 文件并上传以用于此目的。 ::: ## 使用 GeoJSON 自定义矢量地图 -如果你有 OpenSearch Dashboards 矢量地图未提供的特定区域设置,例如美国县或美国邮政编码,你可以使用 GeoJSON 文件创建自己的自定义矢量地图。要创建自定义区域地图,你需要定义一个地理形状,例如具有多个坐标的多边形。要了解更多关于支持自定义区域地图位置的各种地理形状,请参阅[地理形状字段类型](/field-types/supported-field-types/geo-shape)。 +如果您有 OpenSearch Dashboards 矢量地图未提供的特定地区,例如美国县或美国邮政编码,您可以使用 GeoJSON 文件创建自己的自定义矢量地图。要创建自定义区域地图,您需要定义地理形状,例如具有多个坐标的多边形。要了解更多关于支持自定义区域地图位置的各种地理形状,请参阅 [Geoshape 字段类型](/field-types/supported-field-types/geo-shape)。 -GeoJSON 格式允许你编码地理数据结构。要了解更多关于 GeoJSON 规范的信息,请访问 [geojson.org](https://geojson.org/)。 +GeoJSON 格式允许您编码地理数据结构。要了解更多关于 GeoJSON 规范的信息,请访问 [geojson.org](https://geojson.org/)。 -你可以使用 [geojson.io](https://geojson.io/#map=2/20.0/0.0) 提取 GeoJSON 文件。 +您可以使用 [geojson.io](https://geojson.io/#map=2/20.0/0.0) 提取 GeoJSON 文件。 ::: info NOTE -> **前提条件** +> **先决条件** > 要使用带有 GeoJSON 的自定义矢量地图,请安装以下两个必需的插件: > * OpenSearch Dashboards Maps [`dashboards-maps`](https://github.com/opensearch-project/dashboards-maps) 前端插件 > * OpenSearch [`geospatial`](https://github.com/opensearch-project/geospatial) 后端插件 @@ -29,37 +29,37 @@ GeoJSON 格式允许你编码地理数据结构。要了解更多关于 GeoJSON ### 步骤 1:创建区域地图可视化 -要创建自己的自定义矢量地图,请上传包含自定义区域地图 GEO 数据的 JSON 文件。JSON 文件包含用于可视化的矢量图层。 +要创建您自己的自定义矢量地图,请上传包含您自定义区域地图 GEO 数据的 JSON 文件。JSON 文件包含用于可视化的矢量图层。 -1. 准备一个要上传的 JSON 文件。确保文件具有 .geojson 或 .json 扩展名。 -1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > Visualize**。 -1. 选择 **创建可视化** 按钮。 -1. 选择 **区域地图**。 -1. 选择源。例如,**[Flights] Flight Log**。 -1. 在右侧面板中,选择 **导入矢量地图**。 -1. 在 **上传地图** 中,选择或拖放你的 JSON 文件,然后输入 **地图名称前缀**(例如,`usa-counties`)。你的地图将具有你定义的前缀,后跟 `-map` 后缀(例如,`usa-counties-map`),如下图所示: +1. 准备要上传的 JSON 文件。确保文件具有 .geojson 或 .json 扩展名。 +1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 可视化**。 +1. 选择**创建可视化**按钮。 +1. 选择**区域地图**。 +1. 选择数据源。例如,**[Flights] Flight Log**。 +1. 在右侧面板中,选择**导入矢量地图**。 +1. 在**上传地图**中,选择或拖放您的 JSON 文件,然后输入**地图名称前缀**(例如,`usa-counties`)。您的地图将具有您定义的前缀,后跟 `-map` 后缀(例如,`usa-counties-map`),如下图所示: <img src="/images/dashboards/import-geojson-file.png" alt="导入 GeoJSON 文件" width="300"/> -1. 选择 **导入文件** 按钮,然后在确认成功上传的弹出窗口中选择 **刷新** 按钮,如下图所示。 +1. 选择**导入文件**按钮,然后在确认上传成功的弹出窗口中选择**刷新**按钮,如下图所示。 <img src="/images/dashboards/upload-success.png" alt="确认文件上传成功的消息" width="300"/> ### 步骤 2:在 OpenSearch Dashboards 中查看自定义区域地图 -上传自定义 GeoJSON 文件后,你需要将矢量地图图层设置为自定义,并选择你的矢量地图: +上传自定义 GeoJSON 文件后,您需要将矢量地图图层设置为自定义,并选择您的矢量地图: -1. 从 **图层选项 > 图层设置** 中,选择 **自定义矢量地图**。 -1. 在 **矢量地图** 下,选择你刚上传的矢量地图的名称。 -1. 可选:在 **样式设置** 下,增加 **边框粗细** 以更清楚地看到边框。 -1. 选择 **更新** 按钮。 -1. 在 Dashboards 中查看你的区域地图。例如,下图显示了洛杉矶和圣地亚哥县区域: +1. 从**图层选项 > 图层设置**中,选择**自定义矢量地图**。 +1. 在**矢量地图**下,选择您刚刚上传的矢量地图名称。 +1. 可选:在**样式设置**下,增加**边框粗细**以更清楚地看到边框。 +1. 选择**更新**按钮。 +1. 在 Dashboards 中查看您的区域地图。例如,下图显示了洛杉矶和圣地亚哥县区域: <img src="/images/dashboards/county-region-map.png" alt="自定义 GeoJSON 区域地图" width="600"/> -#### 示例 GeoJSON 文件 +#### GeoJSON 文件示例 -以下示例 GeoJSON 文件提供了两个美国县的坐标。 +以下 GeoJSON 文件示例提供了两个美国县的坐标。 ```json { diff --git a/i18n/zh/dashboards/visualize/index.md b/i18n/zh/dashboards/visualize/index.md new file mode 100644 index 00000000..4bbec79f --- /dev/null +++ b/i18n/zh/dashboards/visualize/index.md @@ -0,0 +1,47 @@ +--- +title: 构建数据可视化 +--- + +# 构建数据可视化 + +OpenSearch Dashboards 提供两种创建数据可视化的方法:可视化方式构建和查询方式构建。两种方法都可以生成图表,您可以保存这些图表并将其添加到仪表板中。 + +## 选择可视化方法 + +当您在仪表板中选择**新建**(或在**可视化**应用中选择**创建新可视化**)时,会出现一个对话框显示可用的可视化类型。第一个选项**添加可视化**会打开基于查询的可视化编辑器。其他所有选项(如**面积图**、**折线图**或**饼图**)会打开可视化点击式工具。 + +下表比较了两种方法。*斜体*可视化类型是该方法独有的。 + +::: tip TIP +如果您刚开始使用,请使用**可视化**应用来可视化方式构建——它在所有安装中默认可用。使用查询构建可视化需要额外配置以及 PPL 或 PromQL 知识。 +::: + +| | 在可视化应用中创建可视化 | 使用查询创建可视化 | +| :--- | :--- | :--- | +| **入口点** | 在**新建**对话框中,选择图表类型(面积图、折线图、饼图等) | 在**新建**对话框中,选择**添加可视化** | +| **配置** | 使用点击式面板配置指标和分桶。在搜索栏中使用 DQL 过滤数据。 | 编写管道处理语言(PPL)或 Prometheus 查询语言(PromQL)查询来定义数据。编辑器会自动建议图表类型。 | +| **可视化类型** | - 面积图<br>- 条形图<br>- *坐标地图*<br>- *数据表*<br>- 仪表图<br>- 热力图<br>- 折线图<br>- *指标*<br>- 饼图<br>- *区域地图*<br>- *标签云*<br>- *时间线*<br>- *TSVB*<br>- *Vega*<br>- *VisBuilder* | - 面积图<br>- 条形图<br>- *条形仪表*<br>- 仪表图<br>- 热力图<br>- 折线图<br>- 饼图<br>- *散点图*<br>- *状态时间线* | +| **先决条件** | 无(在所有安装中默认可用) | 需要在 `opensearch_dashboards.yml` 中设置 `workspace.enabled: true` 和 `explore.enabled: true`。如果管理员未启用这些设置,可视化编辑器将不可用。 | +| **最适合** | 无需编写查询的基于聚合的分析 | 需要精确控制数据整形的查询驱动探索 | +| **应用** | [**可视化**应用](/dashboards/visualize/visualize-app/) | [可视化编辑器](/dashboards/visualize/visualization-editor/) | + +## 在可视化应用中创建可视化 + +**可视化**应用使用点击式界面从聚合构建可视化。选择图表类型,选择索引模式,配置指标和分桶,然后渲染结果,如下图所示。使用 [DQL](/dashboards/dql) 搜索栏过滤底层数据。 + +*可视化应用显示带有点击式配置面板的折线图* + +有关更多信息,请参阅[在可视化应用中创建可视化](/dashboards/visualize/visualize-app/)。 + +## 使用查询创建可视化 + +可视化编辑器允许您编写 PPL 或 PromQL 查询,并将查询结果直接映射到图表字段。编辑器会根据查询结果的形状自动建议图表类型并将字段映射到坐标轴,如下图所示。这种方法支持[仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/)进行交互式过滤。 + +*可视化编辑器显示从 PPL 查询构建的带有仪表板变量的多折线图* + +有关更多信息,请参阅[使用查询创建可视化](/dashboards/visualize/visualization-editor/)。 + +## 相关文档 + +- [使用发现功能探索数据](/dashboards/discover/index-discover) +- [创建仪表板](/dashboards/dashboard/) diff --git a/i18n/zh/dashboards/visualize/maps-stats-api.md b/i18n/zh/dashboards/visualize/maps-stats-api.md index 2411a614..04af0397 100644 --- a/i18n/zh/dashboards/visualize/maps-stats-api.md +++ b/i18n/zh/dashboards/visualize/maps-stats-api.md @@ -3,23 +3,23 @@ title: 地图统计 API --- # 地图统计 API -<Badge type="tip" text="引入于 2.7 版本" /> +<Badge type="tip" text="2.7 版本引入" /> -当你在 OpenSearch Dashboards 中创建并保存[地图](/dashboards/visualize/maps)时,地图将成为 `map` 类型的保存对象。地图统计 API 提供有关 OpenSearch Dashboards 中此类保存对象的信息。 +当您在 OpenSearch Dashboards 中创建并保存[地图](/dashboards/visualize/maps)时,地图将成为 `map` 类型的已保存对象。地图统计 API 提供有关 OpenSearch Dashboards 中此类已保存对象的信息。 -#### 示例请求 +#### 请求示例 -你可以通过以下格式的 URL 地址访问地图统计 API: +您可以通过以下格式提供 URL 地址来访问地图统计 API: ``` <opensearch-dashboards-endpoint-address>/api/maps-dashboards/stats ``` ::: info NOTE -如果在 OpenSearch 配置文件中指定了端口号,OpenSearch Dashboards 端点地址可能包含端口号。具体的 URL 格式取决于 OpenSearch 部署类型及其托管的网络环境。 +如果在 OpenSearch 配置文件中指定了端口号,则 OpenSearch Dashboards 端点地址可能包含端口号。具体的 URL 格式取决于 OpenSearch 部署的类型及其托管的网络环境。 ::: -你可以通过两种方式查询端点: +您可以通过两种方式查询端点: - 在浏览器中访问端点地址(例如,`http://localhost:5601/api/maps-dashboards/stats`) @@ -28,7 +28,7 @@ title: 地图统计 API curl -X GET http://localhost:5601/api/maps-dashboards/stats ``` -#### 示例响应 +#### 响应示例 以下是上述请求的响应: @@ -91,11 +91,11 @@ title: 地图统计 API 响应包含以下图层类型的统计信息: -- 底图:默认的 OpenSearch 地图或自定义底图图层。 +- 底图:默认 OpenSearch 地图或自定义基础图层地图。 -- WMS 图层:自定义 WMS 底图图层。 +- WMS 图层:自定义 WMS 基础图层地图。 -- TMS 图层:自定义 TMS 底图图层。 +- TMS 图层:自定义 TMS 基础图层地图。 - 文档图层:地图的数据图层。 @@ -105,21 +105,21 @@ title: 地图统计 API | 字段 | 数据类型 | 描述 | | :--- | :--- | :--- | -| `maps_total` | 整数 | 注册为地图插件保存对象的地图总数。 | -| `layers_filters_total` | 整数 | 所有地图中所有图层的过滤器总数。这包括[图层级别过滤器](/dashboards/visualize/maps#filtering-data-at-the-layer-level),但不包括像[形状过滤器](/dashboards/visualize/maps#drawing-shapes-to-filter-data)这样的全局过滤器。 | +| `maps_total` | 整数 | 注册为地图插件已保存对象的地图总数。 | +| `layers_filters_total` | 整数 | 所有地图中所有图层的过滤器总数。这包括[图层级别过滤器](/dashboards/visualize/maps#filtering-data-at-the-layer-level),但不包括[形状过滤器](/dashboards/visualize/maps#drawing-shapes-to-filter-data)等全局过滤器。 | | `layers_total` | 对象 | 所有地图中所有图层的总计统计信息。 | | `layers_total.opensearch_vector_tile_map` | 整数 | 所有地图中 OpenSearch 底图的总数。 | | `layers_total.documents` | 整数 | 所有地图中文档图层的总数。 | | `layers_total.wms` | 整数 | 所有地图中 WMS 图层的总数。 | | `layers_total.tms` | 整数 | 所有地图中 TMS 图层的总数。 | -| `maps_list` | 数组 | 保存在 OpenSearch Dashboards 中的所有地图的列表。 | +| `maps_list` | 数组 | OpenSearch Dashboards 中保存的所有地图的列表。 | `map_list` 中的每个地图包含以下字段。 | 字段 | 数据类型 | 描述 | | :--- | :--- | :--- | -| `id` | 字符串 | 地图的保存对象 ID。 | -| `layers_filters_total` | 整数 | 地图中所有图层的过滤器总数。这包括[图层级别过滤器](/dashboards/visualize/maps#filtering-data-at-the-layer-level),但不包括像[形状过滤器](/dashboards/visualize/maps#drawing-shapes-to-filter-data)这样的全局过滤器。 | +| `id` | 字符串 | 地图的已保存对象 ID。 | +| `layers_filters_total` | 整数 | 地图中所有图层的过滤器总数。这包括[图层级别过滤器](/dashboards/visualize/maps#filtering-data-at-the-layer-level),但不包括[形状过滤器](/dashboards/visualize/maps#drawing-shapes-to-filter-data)等全局过滤器。 | | `layers_total` | 对象 | 地图中所有图层的总计统计信息。 | | `layers_total.opensearch_vector_tile_map` | 整数 | 地图中 OpenSearch 底图的总数。 | | `layers_total.documents` | 整数 | 地图中文档图层的总数。 | @@ -127,5 +127,5 @@ title: 地图统计 API | `layers_total.tms` | 整数 | 地图中 TMS 图层的总数。 | ::: tip TIP -保存对象 ID 有助于你导航到特定地图,因为 ID 是地图 URL 的最后一部分。例如,在 OpenSearch Playground 中,`[Flights] Flights Status on Maps Destination Location` 地图的地址是 `https://playground.opensearch.org/app/maps-dashboards/88a24e6c-0216-4f76-8bc7-c8db6c8705da`,其中 `88a24e6c-0216-4f76-8bc7-c8db6c8705da` 是此地图的保存对象 ID。 +已保存对象 ID 有助于您导航到特定地图,因为 ID 是地图 URL 的最后一部分。例如,在 OpenSearch Playground 中,`[Flights] Flights Status on Maps Destination Location` 地图的地址是 `https://playground.opensearch.org/app/maps-dashboards/88a24e6c-0216-4f76-8bc7-c8db6c8705da`,其中 `88a24e6c-0216-4f76-8bc7-c8db6c8705da` 是此地图的已保存对象 ID。 ::: diff --git a/i18n/zh/dashboards/visualize/maps.md b/i18n/zh/dashboards/visualize/maps.md index a8363b08..5ef92c57 100644 --- a/i18n/zh/dashboards/visualize/maps.md +++ b/i18n/zh/dashboards/visualize/maps.md @@ -4,105 +4,105 @@ title: 使用地图 # 使用地图 -使用 OpenSearch Dashboards,你可以创建地图来可视化你的地理数据。OpenSearch 允许你构建具有多个图层的地图可视化,组合来自不同索引的数据。你可以从不同的索引模式构建每个图层。此外,你可以配置地图以在不同的缩放级别显示特定数据。OpenSearch 地图由 OpenSearch 地图服务提供支持,该服务使用矢量切片来渲染地图。 +使用 OpenSearch Dashboards,您可以创建地图来可视化您的地理数据。OpenSearch 允许您构建具有多个图层的地图可视化,组合来自不同索引的数据。您可以从不同的索引模式构建每个图层。此外,您可以配置地图以在不同的缩放级别显示特定数据。OpenSearch 地图由 OpenSearch 地图服务提供支持,该服务使用矢量切片来渲染地图。 ## 创建新地图 -你可以通过 **地图** 或 **Visualize** 工作流创建新地图,执行以下步骤: +您可以通过执行以下步骤从**地图**或**可视化**工作流创建新地图: -- 要从 **地图** 工作流创建新地图,请执行以下步骤: +- 要从**地图**工作流创建新地图,请执行以下步骤: - 1. 在顶部菜单栏上,转到 **OpenSearch 插件 > 地图**。 - 1. 选择 **创建地图** 按钮。 + 1. 在顶部菜单栏中,转到 **OpenSearch 插件 > 地图**。 + 1. 选择**创建地图**按钮。 -- 要从 **Visualize** 工作流创建新地图,请执行以下步骤: +- 要从**可视化**工作流创建新地图,请执行以下步骤: - 1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > Visualize**。 - 1. 选择 **创建可视化** 按钮。 - 1. 在 **新建可视化** 对话框中,选择 **地图**。 + 1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 可视化**。 + 1. 选择**创建可视化**按钮。 + 1. 在**新建可视化**对话框中,选择**地图**。 -你现在可以看到默认的 OpenSearch 底图。 +您现在可以看到默认的 OpenSearch 底图。 -要查看 **默认地图** 图层配置,请在地图左上角的 **图层** 面板中,选择 **默认地图**,如下图所示。 +要查看**默认地图**图层配置,请在地图左上角的**图层**面板中选择**默认地图**,如下图所示。 <img src="/images/maps/maps-default.png" alt="默认地图" width="900"> ::: tip TIP -要隐藏 **图层** 面板,请选择面板右上角的折叠(箭头)图标。 +要隐藏**图层**面板,请选择面板右上角的折叠(箭头)图标。 ::: ## 图层设置 -要更改默认地图设置,请在 **图层** 面板中选择 **默认地图**。在 **图层设置** 下,你可以更改图层名称和描述,并为图层配置缩放级别和不透明度: +要更改默认地图设置,请在**图层**面板中选择**默认地图**。在**图层设置**下,您可以更改图层名称和描述,并配置图层的缩放级别和不透明度: -- **缩放级别**:默认情况下,图层在所有缩放级别都可见。如果你只想使图层在特定缩放级别范围内可见,可以通过在文本框中输入缩放级别或将范围滑块滑动到所需值来指定缩放级别。 +- **缩放级别**:默认情况下,图层在所有缩放级别都可见。如果您只想让图层在某个缩放级别范围内可见,可以通过在文本框中输入缩放级别或将范围滑块滑动到所需值来指定缩放级别。 -- **不透明度**:如果你的地图包含多个图层,一个图层可能会遮挡另一个图层。在这种情况下,你可能想要降低顶层的不透明度,以便同时看到两个图层。 +- **不透明度**:如果您的地图包含多个图层,一个图层可能会遮挡另一个图层。在这种情况下,您可能希望降低顶层的不透明度,以便同时看到两个图层。 ## 添加图层 -要向地图添加图层,请在 **图层** 面板中,选择 **添加图层** 按钮。**添加图层** 对话框如下图所示。 +要向地图添加图层,请在**图层**面板中选择**添加图层**按钮。**添加图层**对话框如下图所示。 <img src="/images/maps/add-layer.png" alt="添加图层" width="450"> -你可以向地图添加 **底图图层** 或 **数据图层**: +您可以向地图添加**基础图层**或**数据图层**: -- **底图图层** 用作底图。要使用你自己的或第三方地图作为底图图层,请[将其添加为 **自定义地图**](#添加自定义地图)。 +- **基础图层**用作底图。要使用您自己的或第三方地图作为基础图层,请[将其添加为**自定义地图**](#添加自定义地图)。 -- **数据图层** 允许你从各种数据源可视化数据。 +- **数据图层**允许您可视化来自各种数据源的数据。 ## 添加自定义地图 -OpenSearch 支持 Web 地图服务 (WMS) 或切片地图服务 (TMS) 自定义地图。要添加 TMS 自定义地图,请执行以下步骤: +OpenSearch 支持 Web 地图服务(WMS)或切片地图服务(TMS)自定义地图。要添加 TMS 自定义地图,请执行以下步骤: -1. 在 **图层** 面板中,选择 **添加图层** 按钮。 -1. 从 **添加图层** 对话框中,选择 **底图图层 > 自定义地图**。 - 按照 **新建图层** 对话框中的后续步骤操作,如下图所示。 +1. 在**图层**面板中,选择**添加图层**按钮。 +1. 从**添加图层**对话框中,选择**基础图层 > 自定义地图**。 + 按照**新建图层**对话框中的后续步骤操作,如下图所示。 <img src="/images/maps/custom-map.png" alt="添加自定义地图"> -1. 在 **自定义类型** 下拉列表中,选择 **切片地图服务 (TMS)**。 +1. 在**自定义类型**下拉列表中,选择**切片地图服务(TMS)**。 1. 输入 TMS URL。 -1. (可选)在 **TMS 归属** 中,输入底图的 TMS 归属。例如,如果你使用自定义底图,请输入自定义地图名称。此名称将显示在地图的右下角。 -1. 选择 **设置** 选项卡以编辑图层设置。 -1. 在 **名称** 中输入图层名称。 -1. (可选)在 **描述** 中输入图层描述。 +1. (可选)在 **TMS 属性**中,输入底图的 TMS 属性。例如,如果您使用的是自定义底图,请输入自定义地图名称。此名称将显示在地图的右下角。 +1. 选择**设置**选项卡以编辑图层设置。 +1. 在**名称**中输入图层名称。 +1. (可选)在**描述**中输入图层描述。 1. (可选)选择此图层的缩放级别和不透明度。 -1. 选择 **更新** 按钮。 +1. 选择**更新**按钮。 ## 添加文档图层 -添加文档图层可以让你可视化数据。你可以为每个文档图层添加一个索引模式。要查看多个索引模式,请创建多个图层。 +添加文档图层可让您可视化数据。每个文档图层可以添加一个索引模式。要查看多个索引模式,请创建多个图层。 ::: info NOTE 文档图层可以显示地理点和地理形状文档字段。 ::: -以下示例假设你已安装 `opensearch_dashboards_sample_data_flights` 数据集。如果你没有安装此数据集,请执行以下步骤: +以下示例假设您已安装 `opensearch_dashboards_sample_data_flights` 数据集。如果您没有安装此数据集,请执行以下步骤: 1. 在左上角,选择主页图标。 -1. 选择 **添加示例数据**。 -1. 在 **示例航班数据** 面板中,选择 **添加数据** 按钮。 +1. 选择**添加示例数据**。 +1. 在**示例航班数据**面板中,选择**添加数据**按钮。 -按以下方式添加文档图层: +按如下方式添加文档图层: -1. 在 **图层** 面板中,选择 **添加图层** 按钮。 -1. 从 **添加图层** 对话框中,选择 **数据图层 > 文档**。 -1. 在 **数据源** 中,选择 `opensearch_dashboards_sample_data_flights`。或者,你可以输入另一个索引模式进行可视化。 -1. 在 **地理空间字段** 中,选择要在可视化中显示的地理空间字段(地理点或地理形状)。在此示例中,选择 `DestLocation`。 -1. (可选)选择 **样式** 选项卡以更改填充颜色、边框颜色、边框粗细或标记大小。 -1. 选择 **设置** 选项卡以编辑图层设置。 -1. 在 **名称** 中输入 `航班目的地`。 -1. 选择 **更新** 按钮。 -1. 要查看更多数据,请在右上角选择日历图标下拉列表,然后在 **快速选择** 下,选择 **最近 15 天** 并选择 **应用** 按钮。 +1. 在**图层**面板中,选择**添加图层**按钮。 +1. 从**添加图层**对话框中,选择**数据图层 > 文档**。 +1. 在**数据源**中,选择 `opensearch_dashboards_sample_data_flights`。或者,您可以输入另一个索引模式进行可视化。 +1. 在**地理空间字段**中,选择要在可视化中显示的地理空间字段(地理点或地理形状)。在此示例中,选择 `DestLocation`。 +1. (可选)选择**样式**选项卡以更改填充颜色、边框颜色、边框粗细或标记大小。 +1. 选择**设置**选项卡以编辑图层设置。 +1. 在**名称**中输入 `航班目的地`。 +1. 选择**更新**按钮。 +1. 要查看更多数据,请在右上角选择日历图标下拉列表,然后在**快速选择**下选择**过去 15 天**并选择**应用**按钮。 -你应该看到航班目的地数据,如下图所示。 +您应该会看到航班目的地数据,如下图所示。 <img src="/images/maps/new-layer.png" alt="航班目的地地图"> ## 过滤数据 -要显示索引中的数据子集,请过滤数据。你可以在图层级别过滤数据,也可以在地图上绘制形状以全局过滤所有图层数据。 +要显示索引中的数据子集,请过滤数据。您可以在图层级别过滤数据,也可以在地图上绘制形状以全局过滤所有图层数据。 ### 在图层级别过滤数据 @@ -110,151 +110,151 @@ OpenSearch 支持 Web 地图服务 (WMS) 或切片地图服务 (TMS) 自定义 以下示例显示如何过滤航班目的地数据以仅显示美国目的地: -1. 在 **图层** 面板中,选择 **航班目的地**。 -1. 选择 **过滤器**。 -1. 选择 **添加过滤器**。 -1. 在 **编辑过滤器** 中,在 **字段** 中选择 **DestCountry**。 -1. 在 **运算符** 中,选择 **是**。 -1. 在 **值** 中,选择 **US**。 -1. 选择 **保存** 按钮。 -1. 选择 **更新** 按钮。 +1. 在**图层**面板中,选择**航班目的地**。 +1. 选择**过滤器**。 +1. 选择**添加过滤器**。 +1. 在**编辑过滤器**中,在**字段**中选择 **DestCountry**。 +1. 在**运算符**中,选择**是**。 +1. 在**值**中,选择 **US**。 +1. 选择**保存**按钮。 +1. 选择**更新**按钮。 ::: tip TIP -对于大型数据集,你可能希望避免加载整个地图的数据。要仅加载特定地理区域的数据,请选择 **仅请求地图范围周围的数据**。 +对于大型数据集,您可能希望避免加载整个地图的数据。要仅加载特定地理区域的数据,请选择**仅请求地图范围周围的数据**。 ::: ### 绘制形状以过滤数据 -你可以通过在地图上绘制[形状](/field-types/supported-field-types/geo-shape)来全局过滤数据。要在地图上绘制矩形或多边形,请执行以下步骤: +您可以通过在地图上绘制[形状](/field-types/supported-field-types/geo-shape)来全局过滤数据。要在地图上绘制矩形或多边形,请执行以下步骤: -1. 选择地图右侧的 **矩形** 或 **多边形** 图标。 -1. 在 **过滤器标签** 字段中,输入过滤器的名称。 -1. 选择空间关系类型。默认选择 **相交**。有关空间关系类型的更多信息,请参阅[空间关系](/query-dsl/geo-and-xy/xy#spatial-relations)。 -1. 选择 **绘制矩形** 或 **绘制多边形** 按钮。 -1. 在你要选择的地图区域上绘制形状: - - 对于矩形,选择地图上的任意起点(此点成为矩形顶点)。然后悬停(不要拖动)到地图上的另一点并选择它(此点成为对角顶点)。 - - 对于多边形,选择地图上的任意起点(此点成为多边形顶点)并悬停(不要拖动)到每个后续顶点并选择该点。最后,确保再次选择起点以闭合多边形,如下图所示。 +1. 选择地图右侧的**矩形**或**多边形**图标。 +1. 在**过滤器标签**字段中,输入过滤器的名称。 +1. 选择空间关系类型。默认情况下,选择**相交**。有关空间关系类型的更多信息,请参阅[空间关系](/query-dsl/geo-and-xy/xy#spatial-relations)。 +1. 选择**绘制矩形**或**绘制多边形**按钮。 +1. 在您要选择的地图区域上绘制形状: + - 对于矩形,选择地图上的任意起点(此点成为矩形顶点)。然后悬停(不要拖动)到地图上的另一个点并选择它(此点成为对角顶点)。 + - 对于多边形,选择地图上的任意起点(此点成为多边形顶点),然后悬停(不要拖动)到每个后续顶点并选择该点。最后,确保再次选择起点以闭合多边形,如下图所示。 <img src="/images/maps/draw-shape.png" alt="在地图上绘制多边形"> ### 为地图图层禁用形状过滤器 -默认情况下,形状过滤器全局应用于地图上的所有图层。如果你想为某个地图图层禁用形状过滤器,请执行以下步骤: -1. 从 **图层** 面板中选择图层。 -1. 在 **过滤器** 部分中,取消选择 **应用全局过滤器**。 -1. 选择 **更新** 按钮。 +默认情况下,形状过滤器全局应用于地图上的所有图层。如果您想为地图图层禁用形状过滤器,请执行以下步骤: +1. 从**图层**面板中选择图层。 +1. 在**过滤器**部分,取消选择**应用全局过滤器**。 +1. 选择**更新**按钮。 ### 修改现有形状过滤器 -要修改现有形状过滤器,请选择地图上方左侧的过滤器。你可以对现有过滤器执行以下操作: +要修改现有的形状过滤器,请在地图上方的左上角选择您的过滤器。您可以对现有过滤器执行以下操作: - **编辑过滤器**:更改过滤器名称或修改形状的坐标。 -- **排除结果**:否定过滤器,即显示除过滤器应用的数据点以外的所有数据点。 -- **临时禁用**:禁用过滤器,直到你选择 **重新启用**。 -- **删除**:完全删除你的过滤器。 +- **排除结果**:否定过滤器,即显示除过滤器应用的数据点之外的所有数据点。 +- **临时禁用**:禁用过滤器直到您选择**重新启用**。 +- **删除**:完全删除您的过滤器。 ## 使用工具提示可视化其他数据 -文档图层在地图上将地理点和地理形状文档字段显示为位置。要向位置添加更多信息,你可以使用工具提示。例如,你可能希望在 **航班目的地** 图层中显示航班延误、目的地天气和目的地国家信息。执行以下步骤配置工具提示以显示其他数据: +文档图层将地理点和地理形状文档字段显示为地图上的位置。要向位置添加更多信息,您可以使用工具提示。例如,您可能希望在**航班目的地**图层中显示航班延误、目的地天气和目的地国家信息。执行以下步骤配置工具提示以显示其他数据: -1. 在 **图层** 面板中,选择 **航班目的地**。 -1. 选择 **工具提示**。 -1. 选中 **显示工具提示** 复选框。 -1. 在 **工具提示字段** 下拉列表中,选择要显示的字段。在此示例中,选择 `FlightDelay`、`DestWeather` 和 `DestCountry`。 -1. 选择 **更新** 按钮。 +1. 在**图层**面板中,选择**航班目的地**。 +1. 选择**工具提示**。 +1. 选择**显示工具提示**复选框。 +1. 在**工具提示字段**下拉列表中,选择您要显示的字段。在此示例中,选择 `FlightDelay`、`DestWeather` 和 `DestCountry`。 +1. 选择**更新**按钮。 -要查看工具提示,请将鼠标悬停在你感兴趣的地理点上。一个工具提示可以显示许多数据点。例如,在 **航班目的地** 图层中,单个目的地城市有多个航班。要分页浏览航班,请选择你感兴趣的城市并使用工具提示中的箭头,如下图所示。 +要查看工具提示,请将鼠标悬停在您感兴趣的地理点上。一个工具提示可以显示多个数据点。例如,在**航班目的地**图层中,单个目的地城市有多个航班。要分页浏览航班,请选择您感兴趣的城市并使用工具提示中的箭头,如下图所示。 <img src="/images/maps/tooltip.png" alt="航班目的地工具提示" width="450"> -如果地图上的一个点包含来自多个图层的数据,一个工具提示可以显示来自多个图层的数据。要查看所有图层,请选择 **所有图层**。要选择特定图层,请在工具提示图层选择面板中选择图层名称,如下图所示。 +如果地图上的一个点包含来自多个图层的数据,一个工具提示可以显示来自多个图层的数据。要查看所有图层,请选择**所有图层**。要选择特定图层,请在工具提示图层选择面板中选择图层名称,如下图所示。 <img src="/images/maps/layer-selection-panel.png" alt="带有图层选择面板的工具提示" width="450"> ## 向图层添加标签 -向图层添加标签可以让你在地图上可视化其他数据。例如,你可能希望在 **航班目的地** 图层中查看出发地天气。执行以下步骤向 **航班目的地** 图层添加标签: +向图层添加标签可让您在地图上可视化其他数据。例如,您可能希望在**航班目的地**图层中查看出发地天气。执行以下步骤向**航班目的地**图层添加标签: -1. 在 **图层** 面板中,选择 **航班目的地**。 -1. 在 **样式** 选项卡中,选中 **添加标签** 复选框。 -1. 你可以选择向图层中的所有数据点添加基于固定文本的标签,或使用字段值作为标签文本。 - - 要添加固定文本标签,请在 **标签文本** 下,选择 **固定** 并输入所需的标签文本。 - - 要添加基于字段值的标签,请在 **标签文本** 下,选择 **字段值** 并选择字段名称。在此示例中,选择 `OriginWeather`。 +1. 在**图层**面板中,选择**航班目的地**。 +1. 在**样式**选项卡中,选择**添加标签**复选框。 +1. 您可以选择向图层中的所有数据点添加基于固定文本的标签,或使用字段值作为标签文本。 + - 要添加固定文本标签,请在**标签文本**下选择**固定**并输入所需的标签文本。 + - 要添加基于字段值的标签,请在**标签文本**下选择**字段值**并选择字段名称。在此示例中,选择 `OriginWeather`。 1. (可选)更改标签大小、颜色、边框颜色或边框宽度。 -1. 选择 **更新** 按钮。 +1. 选择**更新**按钮。 -带有出发地天气的标签在地图上可见,也添加到工具提示中,如下图所示。 +带有出发地天气的标签在地图上可见,并且也添加到工具提示中,如下图所示。 <img src="/images/maps/label.png" alt="基于字段类型添加到地图和工具提示的标签" width="450"> ## 重新排序、隐藏和删除图层 -**图层** 面板允许你重新排序、隐藏和删除图层: +**图层**面板允许您重新排序、隐藏和删除图层: - 地图上的图层相互堆叠。要重新排序图层,请使用图层名称旁边的手柄(两条水平线)图标将图层拖动到所需位置。 -- 如果你想隐藏图层,请选择图层名称旁边的显示/隐藏(眼睛)图标。再次切换显示/隐藏图标以显示图层。 +- 如果您想隐藏图层,请选择图层名称旁边的显示/隐藏(眼睛)图标。切换显示/隐藏图标以再次显示图层。 - 要删除图层,请选择图层名称旁边的删除(垃圾桶)图标。 ## 为实时数据集刷新数据 -如果你想可视化实时数据集,在向地图添加图层后,执行以下步骤设置刷新间隔: +如果您想可视化实时数据集,在向地图添加图层后,请执行以下步骤设置刷新间隔: 1. 选择右上角的日历图标。 -1. 在 **每隔刷新** 下,选择或输入刷新间隔(例如,1 秒)。 -1. 选择 **开始** 按钮。 +1. 在**刷新间隔**下,选择或输入刷新间隔(例如,1 秒)。 +1. 选择**开始**按钮。 <img src="/images/maps/refresh.png" alt="刷新地图" width="450"> ## 保存地图 -要保存带有你设置的所有图层的地图,请执行以下步骤: +要保存带有您设置的所有图层的地图,请执行以下步骤: -1. 选择右上角的 **保存** 按钮。 -1. 在 **保存地图** 对话框中,在 **标题** 文本框中输入地图名称。 -1. (可选)在 **描述** 文本框中输入地图描述。 -1. 选择 **保存** 按钮。 +1. 选择右上角的**保存**按钮。 +1. 在**保存地图**对话框中,在**标题**文本框中输入地图名称。 +1. (可选)在**描述**文本框中输入地图描述。 +1. 选择**保存**按钮。 -要打开保存的地图,请选择左上角的 **地图**。将显示已保存地图的列表。 +要打开已保存的地图,请选择左上角的**地图**。将显示已保存地图的列表。 ## 将地图添加到仪表板 -你可以通过执行以下步骤将新地图或现有地图添加到新仪表板或现有仪表板: +您可以通过执行以下步骤将新地图或现有地图添加到新仪表板或现有仪表板: -- 要将地图添加到新仪表板,首先按以下方式创建仪表板: +- 要将地图添加到新仪表板,首先按如下方式创建仪表板: - 1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > Dashboard**。 - 1. 选择 **创建仪表板** 按钮。 - 1. 选择 **新建** 按钮。 + 1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 仪表板**。 + 1. 选择**创建仪表板**按钮。 + 1. 选择**新建**按钮。 -- 要将地图添加到现有仪表板,首先按以下方式打开仪表板: - 1. 在顶部菜单栏上,转到 **OpenSearch Dashboards > Dashboard**。 - 1. 从列表中选择要打开的仪表板。 - 1. 在右上角,选择 **编辑**。 +- 要将地图添加到现有仪表板,首先按如下方式打开仪表板: + 1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 仪表板**。 + 1. 从列表中选择您要打开的仪表板。 + 1. 在右上角,选择**编辑**。 -打开仪表板后,你可以向其添加新地图或现有地图。 +打开仪表板后,您可以向其添加新地图或现有地图。 ### 添加现有地图 -1. 从顶部菜单中,选择 **添加**。 -1. 在 **类型** 下拉列表中,选择 **地图**。 -1. 从列表中选择要添加的地图。 +1. 从顶部菜单中,选择**添加**。 +1. 在**类型**下拉列表中,选择**地图**。 +1. 从列表中选择您要添加的地图。 ### 添加新地图 -1. 从顶部菜单中,选择 **新建** 按钮。 -1. 在 **新建可视化** 对话框中,选择 **地图**。 +1. 从顶部菜单中,选择**新建**按钮。 +1. 在**新建可视化**对话框中,选择**地图**。 1. 通过添加底图、图层或工具提示来编辑默认地图。 -1. 在右上角,选择 **保存** 按钮。 -1. 在 **保存地图** 对话框中,输入地图的 **标题** 和可选 **描述**。 -1. 选择 **保存后添加到仪表板**(默认选中此选项)。 -1. 选择 **保存并返回** 按钮。 +1. 在右上角,选择**保存**按钮。 +1. 在**保存地图**对话框中,输入地图的**标题**和可选的**描述**。 +1. 选择**保存后添加到仪表板**(默认情况下此选项已选中)。 +1. 选择**保存并返回**按钮。 ## 从仪表板编辑地图 -1. 在仪表板中,选择要编辑的地图右上角的齿轮图标。 -1. 选择 **编辑地图**。 +1. 在仪表板中,选择您要编辑的地图右上角的齿轮图标。 +1. 选择**编辑地图**。 1. 编辑地图。 -1. 在右上角,选择 **保存** 按钮。 -1. 在 **保存地图** 对话框中,选择 **保存并返回** 按钮。 +1. 在右上角,选择**保存**按钮。 +1. 在**保存地图**对话框中,选择**保存并返回**按钮。 diff --git a/i18n/zh/dashboards/visualize/maptiles.md b/i18n/zh/dashboards/visualize/maptiles.md index d4012c7c..03061cce 100644 --- a/i18n/zh/dashboards/visualize/maptiles.md +++ b/i18n/zh/dashboards/visualize/maptiles.md @@ -1,13 +1,13 @@ --- -title: 配置 Web 地图服务 (WMS) +title: 配置 Web 地图服务(WMS) --- -# 配置 Web 地图服务 (WMS) +# 配置 Web 地图服务(WMS) -开放地理空间联盟 (OGC) Web 地图服务 (WMS) 规范是在网络上请求动态地图的国际规范。OpenSearch Dashboards 包含默认的地图切片。对于专用地图,你可以按照以下步骤在 OpenSearch Dashboards 中配置 WMS: +开放地理空间联盟(OGC)Web 地图服务(WMS)规范是用于在网络上请求动态地图的国际规范。OpenSearch Dashboards 包含默认地图切片。对于专业地图,您可以按照以下步骤在 OpenSearch Dashboards 上配置 WMS: -1. 在 `https://<host>:<port>` 登录 OpenSearch Dashboards。例如,你可以通过连接到 [https://localhost:5601](https://localhost:5601) 来连接 OpenSearch Dashboards。默认用户名和密码是 `admin`。 -2. 选择 **管理** > **高级设置**。 +1. 在 `https://<host>:<port>` 登录 OpenSearch Dashboards。例如,您可以通过连接到 [https://localhost:5601](https://localhost:5601) 来连接 OpenSearch Dashboards。默认用户名和密码是 `admin`。 +2. 选择**管理** > **高级设置**。 3. 找到 `visualization:tileMap:WMSdefaults`。 4. 将 `enabled` 更改为 `true` 并添加有效 WMS 服务器的 URL,如以下示例所示: @@ -23,5 +23,5 @@ title: 配置 Web 地图服务 (WMS) ``` ::: info NOTE -Web 地图服务可能有许可费用或限制,你有责任遵守任何此类费用或限制。 +Web 地图服务可能有许可费或限制,您有责任遵守任何此类费用或限制。 ::: diff --git a/i18n/zh/dashboards/visualize/selfhost-maps-server.md b/i18n/zh/dashboards/visualize/selfhost-maps-server.md index 3e711c93..8a55a840 100644 --- a/i18n/zh/dashboards/visualize/selfhost-maps-server.md +++ b/i18n/zh/dashboards/visualize/selfhost-maps-server.md @@ -4,12 +4,12 @@ title: 使用自托管地图服务器 # 使用自托管地图服务器 -OpenSearch Dashboards 的自托管地图服务器允许用户在隔离网络环境中访问默认地图服务。OpenSearch 兼容的地图 URL 包括带有地图切片和矢量的地图清单、地图切片和地图矢量。 +OpenSearch Dashboards 的自托管地图服务器允许用户在隔离网络环境中访问默认地图服务。与 OpenSearch 兼容的地图 URL 包括带有地图切片和矢量的地图清单、地图切片和地图矢量。 -以下部分提供了设置和使用自托管地图服务器与 OpenSearch Dashboards 的步骤。 +以下部分提供了在 OpenSearch Dashboards 中设置和使用自托管地图服务器的步骤。 ::: info NOTE -你可以通过官方 OpenSearch [Docker Hub 仓库](https://hub.docker.com/u/opensearchproject)访问 `maps-server` 镜像。 +您可以通过官方 OpenSearch [Docker Hub 仓库](https://hub.docker.com/u/opensearchproject)访问 `maps-server` 镜像。 ::: ## 拉取 Docker 镜像 @@ -20,7 +20,7 @@ OpenSearch Dashboards 的自托管地图服务器允许用户在隔离网络环 ## 设置服务器 -在运行服务器之前,你必须设置地图切片。你有两个设置选项:使用 OpenSearch 提供的地图服务切片集,或生成栅格切片集。 +在运行服务器之前,您必须设置地图切片。您有两个设置选项:使用 OpenSearch 提供的地图服务切片集,或生成栅格切片集。 ### 选项 1:使用 OpenSearch 提供的地图服务切片集 @@ -34,7 +34,7 @@ OpenSearch Dashboards 的自托管地图服务器允许用户在隔离网络环 - 缩放级别 10 (https://maps.opensearch.org/offline/planet-osm-default-z0-z10.tar.gz) ::: info NOTE -缩放级别 10 的行星切片集(压缩后 2 GB/解压后 6.8 GB)大约是缩放级别 8(压缩后 225 MB/解压后 519 MB)的 10 倍大。 +缩放级别 10 的行星切片集(压缩后 2 GB/解压后 6.8 GB)大约是缩放级别 8 切片集(压缩后 225 MB/解压后 519 MB)的 10 倍。 ::: ``` @@ -47,7 +47,7 @@ docker run \ ### 选项 2:生成栅格切片集 -要生成栅格切片集,请使用[栅格切片生成管道](https://github.com/opensearch-project/maps/tree/main/tiles-generation/cdk),然后使用切片集的绝对路径创建卷以启动服务器。 +要生成栅格切片集,请使用[栅格切片生成管道](https://github.com/opensearch-project/maps/tree/main/tiles-generation/cdk),然后使用切片集的绝对路径创建一个卷来启动服务器。 ## 启动服务器 @@ -62,7 +62,7 @@ docker run \ run ``` -或者,如果你生成了栅格切片集,请使用该切片集运行服务器: +或者,如果您生成了栅格切片集,请使用该切片集运行服务器: ``` docker run \ @@ -81,7 +81,7 @@ docker run \ ## 在 OpenSearch Dashboards 中使用自托管地图服务器 -你可以通过将参数添加到 `opensearch_dashboards.yml` 或在 OpenSearch Dashboards 中配置默认 WMS 属性来将自托管地图服务器与 OpenSearch Dashboards 一起使用。 +您可以通过将参数添加到 `opensearch_dashboards.yml` 或在 OpenSearch Dashboards 中配置默认 WMS 属性来在 OpenSearch Dashboards 中使用自托管地图服务器。 ### 选项 1:配置 opensearch_dashboards.yml @@ -91,8 +91,8 @@ docker run \ ### 选项 2:在 OpenSearch Dashboards 中配置默认 WMS 属性 -1. 在 OpenSearch Dashboards 控制台上,选择 **Dashboards 管理** > **高级设置**。 -2. 在 **默认 WMS 属性** 下找到 `visualization:tileMap:WMSdefaults`。 +1. 在 OpenSearch Dashboards 控制台中,选择 **Dashboards 管理** > **高级设置**。 +2. 在**默认 WMS 属性**下找到 `visualization:tileMap:WMSdefaults`。 3. 将 `"enabled": false` 更改为 `"enabled": true` 并添加有效地图服务器的 URL。 ## 许可证 @@ -101,5 +101,5 @@ docker run \ ## 相关文章 -* [配置 Web 地图服务 (WMS)](/dashboards/visualize/maptiles) +* [配置 Web 地图服务(WMS)](/dashboards/visualize/maptiles) * [使用坐标和区域地图](/dashboards/visualize/geojson-regionmaps) diff --git a/i18n/zh/dashboards/visualize/visbuilder.md b/i18n/zh/dashboards/visualize/visbuilder.md index f2675059..0eccd92a 100644 --- a/i18n/zh/dashboards/visualize/visbuilder.md +++ b/i18n/zh/dashboards/visualize/visbuilder.md @@ -5,49 +5,48 @@ title: 使用 VisBuilder # 使用 VisBuilder ::: danger WARNING -VisBuilder 是一个实验性功能,不应在生产环境中使用。有关其进展的更新,或者如果你想留下有助于改进该功能的反馈,请参阅 [GitHub issue](https://github.com/opensearch-project/OpenSearch-Dashboards/issues/2280)。 +VisBuilder 是一个实验性功能,不应在生产环境中使用。有关其进度的更新,或者如果您想留下有助于改进该功能的反馈,请参阅 [GitHub issue](https://github.com/opensearch-project/OpenSearch-Dashboards/issues/2280)。 ::: -你可以使用 OpenSearch Dashboards 中的 VisBuilder 可视化类型通过拖放手势创建数据可视化。使用 VisBuilder,你可以: +您可以使用 OpenSearch Dashboards 中的 VisBuilder 可视化类型通过拖放手势创建数据可视化。使用 VisBuilder,您可以: * 无需预先选择可视化输出即可立即查看数据。 -* 灵活地快速更改可视化类型和索引模式。 -* 轻松在多个屏幕之间导航。 +* 灵活快速地更改可视化类型和索引模式。 +* 能够轻松在多个屏幕之间导航。 <img src="/images/dashboards/vis-builder-2.png" alt="VisBuilder 新建可视化起始页"> ## 在 OpenSearch Dashboards playground 中试用 VisBuilder -如果你想在不本地安装 OpenSearch 的情况下试用 VisBuilder,可以在 [Dashboards playground](https://playground.opensearch.org/app/vis-builder#/) 中进行。VisBuilder 默认启用。 +如果您想在不本地安装 OpenSearch 的情况下试用 VisBuilder,您可以在 [Dashboards playground](https://playground.opensearch.org/app/vis-builder#/) 中进行。VisBuilder 默认启用。 ## 在本地试用 VisBuilder -VisBuilder 默认启用。如果你想禁用它,请在 `opensearch_dashboards.yml` 文件中将功能标志 `vis_builder.enabled:` 设置为 `false`,如下所示: +VisBuilder 默认启用。如果您想禁用它,请在 `opensearch_dashboards.yml` 文件中将功能标志 `vis_builder.enabled:` 设置为 `false`,如下所示: ``` -# Set the value of this setting to false to disable VisBuilder -# functionality in Visualization. +# 将此设置的值设置为 false 以禁用可视化中的 VisBuilder 功能。 vis_builder.enabled: false ``` -按照以下步骤在你的环境中使用 VisBuilder 创建新的可视化: +按照以下步骤在您的环境中使用 VisBuilder 创建新的可视化: 1. 打开 Dashboards: - - 如果你没有运行安全插件,请转到 http://localhost:5601。 - - 如果你正在运行安全插件,请转到 https://localhost:5601 并使用你的用户名和密码登录(默认为 admin/admin)。 + - 如果您没有运行安全插件,请转到 http://localhost:5601。 + - 如果您正在运行安全插件,请转到 https://localhost:5601 并使用您的用户名和密码登录(默认为 admin/admin)。 -2. 确认 **启用实验性可视化** 选项已打开。 - - 从顶部菜单中,选择 **管理** > **Dashboards 管理** > **高级设置**。 - - 选择 **可视化** 并验证该选项已打开。 +2. 确认**启用实验性可视化**选项已打开。 + - 从顶部菜单中,选择**管理** > **Dashboards 管理** > **高级设置**。 + - 选择**可视化**并验证该选项已打开。 <img src="/images/enable-experimental-viz.png" alt="启用实验性可视化" width="600"> -3. 从顶部菜单中,选择 **Visualize** **>** **创建可视化** **>** **VisBuilder**。 +3. 从顶部菜单中,选择**可视化** **>** **创建可视化** **>** **VisBuilder**。 <img src="/images/dashboards/vis-builder-1.png" alt="选择 VisBuilder 可视化类型" width="550"> -4. 将字段名称从左列拖放到 **配置** 面板以生成可视化。 +4. 将字段名称从左列拖放到**配置**面板以生成可视化。 -以下是一个示例可视化。根据你的数据和选择的字段,你的可视化会有所不同。 +以下是一个可视化示例。根据您的数据和选择的字段,您的可视化将看起来不同。 <img src="/images/drag-drop-generated-viz.png" alt="使用示例数据生成的可视化"> diff --git a/i18n/zh/dashboards/visualize/visualization-editor/area-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/area-chart.md new file mode 100644 index 00000000..ddc212f7 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/area-chart.md @@ -0,0 +1,96 @@ +--- +title: 面积图 +--- + +# 可视化编辑器中的面积图 + +面积图将数据点用线连接并填充每条线下方的区域。使用面积图显示随时间变化的数量和组成。堆叠多个系列可以查看每个类别对总数的贡献。 + +## 创建面积图 + +以下示例相互构建,从基本图表开始逐步增加复杂性。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本面积图 + +从一个按时间统计事件数量的聚合查询开始: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1d) +``` + +运行此查询后,可视化编辑器会自动映射字段: + +- **X 轴**显示 `SPAN(@timestamp, 1d)` 字段。 +- **Y 轴**显示 `count()` 字段。 + +结果是一个显示每天事件数量的单个填充区域,如下图所示。 + +*显示随时间变化计数的基本面积图* + +### 堆叠面积图 + +在查询中添加第三个维度,按类别将数据拆分为多个堆叠系列: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1d), response +``` + +此查询按时间和 `response` 字段(HTTP 状态码)分组计数。选择 `response` 作为**颜色**字段,为每个状态码值(例如 200、404、503)渲染单独的堆叠区域。 + +结果是一个堆叠面积图,每个 HTTP 响应码以不同颜色显示。图表将区域堆叠在一起,同时显示各个类别的数量和所有类别的总数,如下图所示。 + +*按 HTTP 响应码显示计数的堆叠面积图* + +## 配置面积图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择日期或数字字段作为水平轴,定义数据绘制的分桶(例如 `SPAN(@timestamp, 1d)`)。 | +| **Y 轴** | 选择一个或多个数字字段作为单独的区域绘制。当选择多个字段时,每个字段都渲染为自己的区域层。 | +| **颜色** | 选择分类字段将数据拆分为多个堆叠系列,每个系列以不同颜色渲染。例如,使用 `response` 状态码字段为每个 HTTP 状态码显示单独的堆叠区域。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 区域 + +以下设置控制区域填充、线条样式和值显示。 + +| 设置 | 描述 | +| --- | --- | +| **堆叠** | 控制多个系列的显示方式。**无**将系列叠加而不堆叠。**堆叠**将系列值相加。**百分比**将系列堆叠为总数的百分比。 | +| **填充不透明度** | 设置线条下方填充区域的不透明度。 | +| **渐变模式** | 控制填充渐变。**无**使用纯色填充。**不透明度**使填充向基线逐渐淡出。**色调**向基线使用较浅的颜色。 | +| **线条样式** | 控制图表是显示带点的线条(**默认**)、仅线条(**仅线条**)还是仅点(**仅点**)。 | +| **线条虚线样式** | 将线条图案设置为**实线**、**虚线**或**点线**。 | +| **插值** | 确定点的连接方式。**直线**在点之间绘制直线。**平滑**应用曲线。**阶梯**创建阶梯图案。 | +| **线条宽度** | 设置线条的粗细(像素)。支持 1-10 范围内的值。 | +| **显示值** | 在图表上显示值标签。 | +| **显示当前时间标记** | 显示当前时间的垂直标记。此设置仅在 X 轴使用日期字段时可用。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 图例 + +有关配置图例的信息,请参阅[图例](/dashboards/visualize/visualization-editor/configuring-visualizations/#legend)。 + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/bar-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/bar-chart.md new file mode 100644 index 00000000..96a478ed --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/bar-chart.md @@ -0,0 +1,122 @@ +--- +title: 条形图 +--- + +# 可视化编辑器中的条形图 + +条形图将数据显示为垂直或水平条形。使用条形图比较离散类别。选择**颜色**字段将类别拆分为子组,并添加阈值线来标记高于或低于目标的值。 + +## 创建条形图 + +以下示例相互构建,从基本图表开始逐步增加复杂性。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本条形图 + +从一个按类别统计事件数量的聚合查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by Carrier +``` + +运行此查询后,可视化编辑器会自动选择**条形**图并映射字段: + +- **X 轴**显示 `Carrier` 字段。 +- **Y 轴**显示 `count()` 字段。 + +结果是一个比较每个航空公司事件数量的条形图,如下图所示。 + +*显示按航空公司计数的基本条形图* + +### 分组条形图 + +在查询中添加第二个维度,将每个类别拆分为子组: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by Carrier, Cancelled +``` + +此查询按航空公司和 `Cancelled` 字段分组计数。选择 `Cancelled` 作为**颜色**字段,为每个航空公司内的每个取消状态渲染单独的条形。 + +结果是一个分组条形图,每个航空公司有两个并排的条形——一个用于未取消的航班,一个用于已取消的航班——便于比较每个取消状态的航班数量,如下图所示。 + +*按航空公司和取消状态显示计数的分组条形图* + +### 添加阈值 + +使用阈值添加参考线并根据目标值对条形进行颜色编码。 + +使用前面示例中的相同分组条形图,配置设置面板: + +1. 在**条形**部分,启用**使用阈值颜色**。 +1. 在**阈值**部分,选择 **+ 添加阈值**。 +1. 将基础颜色设置为绿色(`#00BD6B`)并在值 `200` 处添加红色(`#F13939`)阈值。 +1. 将**阈值线模式**设置为**虚线**,如下图所示。 + +*在 200 处配置阈值的条形图设置* + +结果显示根据阈值规则着色的条形:低于 200 的条形显示为绿色,高于 200 的条形显示为红色。200 处的虚线参考线提供了清晰的视觉锚点,如下图所示。 + +*带有阈值着色和 200 处虚线参考线的条形图* + +## 配置条形图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择定义水平轴上分组的分类或日期字段(例如 `Carrier`)。 | +| **Y 轴** | 选择一个或多个数字字段来确定条形的高度。当选择多个字段时,每个字段在每个类别组内渲染为单独的条形。 | +| **颜色** | 选择分类字段将每个类别拆分为分组条形,每个条形以不同颜色渲染。例如,使用 `Cancelled` 字段在每个航空公司内显示已取消和未取消航班的单独条形。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 条形 + +以下设置控制条形的显示样式和大小。 + +| 设置 | 描述 | +| --- | --- | +| **堆叠** | 控制多个系列的显示方式。**无**将系列叠加而不堆叠。**堆叠**将系列值相加。**百分比**将系列堆叠为总数的百分比。 | +| **填充不透明度** | 设置条形的不透明度。 | +| **大小** | 控制条形宽度。**自动**自动调整条形大小。**手动**设置特定的宽度百分比(1-100)。 | +| **圆角** | 设置每个条形的圆角(像素)。 | +| **显示值** | 在图表上显示值标签。 | +| **使用阈值颜色** | 启用时,图表根据**阈值**部分中定义的阈值规则为条形着色。 | +| **显示边框** | 启用时,在每个条形周围添加边框。 | +| **边框宽度** | 设置边框粗细(像素)。此设置在启用**显示边框**时可用。 | +| **边框颜色** | 设置边框颜色。此设置在启用**显示边框**时可用。 | + +### 分桶 + +以下设置控制每个条形内数据的聚合方式。 + +| 设置 | 描述 | +| --- | --- | +| **类型** | 用于计算每个分桶值的聚合类型。支持的值:**求和**、**平均**、**最小**、**最大**、**计数**。 | +| **间隔** | 将数据分组到分桶的时间间隔。支持的值:**自动**、**月**、**日**、**小时**、**分钟**、**秒**。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 图例 + +有关配置图例的信息,请参阅[图例](/dashboards/visualize/visualization-editor/configuring-visualizations/#legend)。 + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/bar-gauge-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/bar-gauge-chart.md new file mode 100644 index 00000000..bcc2dca8 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/bar-gauge-chart.md @@ -0,0 +1,93 @@ +--- +title: 条形仪表图 +--- + +# 可视化编辑器中的条形仪表图 + +条形仪表图将数值显示为刻度上的水平或垂直条形,将每个字段简化为单个值。与条形图不同,条形仪表图设计用于将值与定义的阈值进行比较。 + +## 创建条形仪表图 + +以下示例相互构建,从基本图表开始逐步增加复杂性。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本条形仪表图 + +从一个按分类字段分组数值指标的查询开始: + +```sql +source = opensearch_dashboards_sample_data_logs | stats avg(bytes) by machine.os +``` + +运行此查询后,选择**条形仪表**作为图表类型。字段映射如下: + +- **X 轴**显示 `machine.os` 字段(分类)。 +- **Y 轴**显示 `avg(bytes)` 字段(数值)。 + +结果是一组垂直条形,每个操作系统一个,显示每个操作系统的平均字节数。**显示未填充区域**切换默认启用,在每个条形后面显示灰色背景以指示到最大值的剩余距离,如下图所示。 + +*显示按操作系统划分的平均字节数的基本条形仪表* + +### 添加阈值和显示样式 + +打开**阈值**部分并定义断点以对条形进行颜色编码。例如: + +- 基础颜色:绿色(低于 3000 的值) +- 3000 处的阈值:橙色(中等范围) +- 5000 处的阈值:红色(高范围) + +然后在**条形仪表**部分,切换**显示样式**以查看不同的视觉处理: + +**渐变**——每个条形填充通过其经过的阈值的平滑颜色过渡,如下图所示。 + +*渐变显示样式的条形仪表* + +**堆叠**——每个条形在阈值边界处分为不同的彩色段,如下图所示。 + +*堆叠显示样式的条形仪表* + +**基本**——每个条形根据值达到的最高阈值使用单一纯色,如下图所示。 + +*基本显示样式的条形仪表* + +## 配置条形仪表图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择分类字段(用于类别标签)或数值字段(用于条形值)。 | +| **Y 轴** | 选择互补字段。如果 X 轴是分类的,则为 Y 轴选择数值字段(反之亦然)。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 值选项 + +| 设置 | 描述 | +| --- | --- | +| **计算** | 确定如何将同一类别的多个数据点简化为单个值。支持的值:**最后 \***、**最后**、**第一 \***、**第一**、**最小**、**最大**、**平均**、**中位数**、**方差**、**计数**、**去重计数**、**总计**。有关更多信息,请参阅[值计算](/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations)。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 条形仪表 + +| 设置 | 描述 | +| --- | --- | +| **显示样式** | 控制条形填充的渲染方式。**渐变**使用从阈值生成的平滑颜色渐变填充条形。**堆叠**显示每个阈值范围的不同彩色段。**基本**使用匹配阈值的单一纯色填充条形。 | +| **值显示** | 控制数值标签的着色方式。**值颜色**使用映射的阈值为文本着色。**文本颜色**使用默认文本颜色。**隐藏**完全隐藏值。 | +| **显示未填充区域** | 启用时,在每个条形的填充部分后面显示灰色背景,便于查看到最大值的剩余距离。 | + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/index.md b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/index.md new file mode 100644 index 00000000..f8c8332c --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/index.md @@ -0,0 +1,89 @@ +--- +title: 配置可视化 +--- + +# 在可视化编辑器中配置可视化 + +可视化编辑器提供适用于多种可视化类型的共享配置选项。每个可视化类型页面都记录了其特定选项。以下配置在大多数可视化中是通用的。 + +## 字段 + +**字段**面板将查询结果列映射到图表轴。选择用于 X 轴、Y 轴以及颜色或大小等可选维度的字段。可用的字段映射取决于图表类型。 + +## 拆分 + +当您的数据具有的维度超过单个图表可以显示的维度时,请使用**拆分**选项。例如,如果您的查询返回三个维度,但折线图只能显示两个(X 轴和 Y 轴),请使用拆分沿第三个维度拆分数据以创建多个图表。每个生成的图表显示相同的轴,但过滤到拆分字段的不同值。 + +要创建拆分可视化,请按照以下步骤操作: + +1. 在仪表板中,选择**新建** > **添加可视化**。 +1. 选择 `opensearch_dashboards_sample_data_logs` 作为数据集。 +1. 在查询编辑器中,输入以下查询并选择**更新**: + + ```sql + | stats count() by span(`@timestamp`, 1h), extension, `machine.os` + ``` + +1. 在时间过滤器中,选择**最近 15 天**。 +1. 将**可视化类型**设置为**折线**。 +1. 在**字段**中,配置以下设置: + - **X 轴**:选择 `span(@timestamp,1h)`。 + - **Y 轴**:选择 `count()`。 +1. 在**拆分**中,配置以下设置: + - **拆分方式**:选择 `machine.os`。 + - 将**显示标签**切换为开启。 + +可视化为每个 `machine.os` 值(例如 `win xp`、`osx`、`win 7`、`win 8`、`ios`)显示单独的折线图,每个都显示随时间变化的事件数量,如下图所示。 + +*显示每个 machine.os 值单独折线图的拆分可视化* + +## 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。每个轴都可以独立自定义。 + +| 设置 | 描述 | +| --- | --- | +| **显示轴** | 显示或隐藏轴。 | +| **标题** | 轴的自定义标签。 | +| **位置** | 控制轴相对于图表的位置。支持的值:X 轴:**上**、**下**。Y 轴:**左**、**右**。 | +| **显示网格线** | 启用时,显示从轴延伸到图表区域的网格线。 | +| **显示标签** | 启用时,沿轴显示类别标签。 | +| **对齐** | 控制轴标签的旋转:**水平**(0°)、**垂直**(90°)或**倾斜**(45°)。 | +| **截断后** | 设置轴标签截断前的最大字符长度。 | + +坐标轴在面积图、条形图、热力图、直方图、折线图、散点图和状态时间线图中可用。 + +## 工具提示 + +**工具提示**面板控制将鼠标悬停在数据点上时显示的信息。选项包括显示所有系列值或仅显示悬停的系列。 + +工具提示在面积图、条形图、条形仪表图、热力图、直方图、折线图、饼图、散点图和状态时间线图中可用。 + +## 图例 + +**图例**面板控制图表图例的显示和位置。选项包括显示或隐藏图例以及选择其位置(上、下、左或右)。 + +图例在热力图、饼图、散点图和状态时间线图中可用。 + +## 标准选项 + +标准选项控制可视化中数值的格式化方式。有关详细信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +## 值选项 + +值选项控制单值可视化中值的计算和显示方式。 + +| 设置 | 描述 | +| --- | --- | +| **计算** | 用于将系列简化为单个值的函数(例如最后、平均、最大、最小)。有关详细信息,请参阅[值计算](/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations)。 | +| **显示** | 控制是显示计算值、值名称还是两者。 | + +值选项在条形仪表图、仪表图和指标图中可用。 + +## 阈值 + +阈值定义颜色编码的边界,指示值何时超过重要限制。有关详细信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +## 值计算 + +值计算确定如何将一系列值简化为单个数字进行显示(例如最后、平均、求和、最小、最大)。有关详细信息,请参阅[值计算](/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations)。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options.md b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options.md new file mode 100644 index 00000000..0280389c --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options.md @@ -0,0 +1,86 @@ +--- +title: 标准选项 +--- + +# 标准选项 + +标准选项控制可视化中数值的格式化方式。使用它们设置单位、自定义后缀、小数精度,以及对于有刻度的图表,设置最小和最大值。 + +## 支持的图表类型 + +下表列出了每种可视化类型支持的标准选项。 + +| 可视化类型 | 最小和最大 | 单位 | 单位后缀 | 小数位数 | +| --- | --- | --- | --- | --- | +| [面积图](/dashboards/visualize/visualization-editor/area-chart) | 是 | 是 | 是 | 是 | +| [条形图](/dashboards/visualize/visualization-editor/bar-chart) | 是 | 是 | 是 | 是 | +| [条形仪表图](/dashboards/visualize/visualization-editor/bar-gauge-chart) | 是 | 是 | 是 | 是 | +| [仪表图](/dashboards/visualize/visualization-editor/gauge-chart) | 是 | 是 | 是 | 是 | +| [热力图](/dashboards/visualize/visualization-editor/heatmap-chart) | 否 | 是 | 是 | 是 | +| [直方图](/dashboards/visualize/visualization-editor/histogram-chart) | 是 | 是 | 是 | 是 | +| [折线图](/dashboards/visualize/visualization-editor/line-chart) | 是 | 是 | 是 | 是 | +| [指标图](/dashboards/visualize/visualization-editor/metric-chart) | 否 | 是 | 是 | 是 | +| [饼图](/dashboards/visualize/visualization-editor/pie-chart) | 否 | 是 | 是 | 是 | +| [散点图](/dashboards/visualize/visualization-editor/scatter-chart) | 是 | 是 | 是 | 是 | +| [状态时间线](/dashboards/visualize/visualization-editor/state-timeline-chart) | 否 | 否 | 否 | 否 | +| [表格](/dashboards/visualize/visualization-editor/table-chart) | 否 | 否 | 否 | 否 | + +## 选项 + +下表描述了可用的标准选项。 + +| 设置 | 描述 | +| --- | --- | +| **最小** | 值刻度的下限。对于笛卡尔图表,这设置值轴最小值。对于仪表图和条形仪表图,这设置刻度最小值。 | +| **最大** | 值刻度的上限。对于笛卡尔图表,这设置值轴最大值。对于仪表图和条形仪表图,这设置刻度最大值。 | +| **单位** | 与值一起显示的单位。某些单位(如货币符号)显示在值之前。其他单位显示在值之后或自动缩放值。 | +| **单位后缀** | 附加在单位或值之后的自定义文本,例如 `/sec`。使用此设置显示自定义单位或速率。 | +| **小数位数** | 要显示的小数位数。将此设置留空以使用自动精度。 | + +## 单位 + +**单位**菜单分组了常见格式,如数字、百分比、货币、数据单位、时间单位、质量单位和长度单位。 + +对于支持缩放的单位组,所选单位充当输入单位,可视化将值转换为同一组中最易读的单位。例如,如果**单位**设置为 `bytes(B)`,值 `1000` 将显示为 `1 KB`。 + +某些单位仅更改显示的标签或符号。例如,货币单位可以在值之前显示符号,而百分比单位附加 `%`。 + +以下指标图显示的基础值为 `7911`,**单位**设置为 `bytes(B)`。 + +*指标图显示 7.91 KB,基础值为 7911,单位设置为字节* + +## 单位后缀 + +使用**单位后缀**在格式化值后附加自定义文本。这对于速率或自定义单位很有用。 + +例如,要在指标图中显示字节速率,请将**单位**设置为 `bytes(B)` 并将**单位后缀**设置为 `/sec`。使用自动精度的**小数位数**,基础值 `14074` 总字节数显示为 `14.07 KB/sec`。 + +*指标图显示 14.07 KB/sec,基础值为 14074,单位设置为字节,单位后缀为 /sec* + +## 小数位数 + +使用**小数位数**控制数字精度。例如,输入 `2` 显示两位小数。将此设置留空让可视化自动选择精度。 + +以下条形图的**单位**设置为 `bits(b)`,**小数位数**设置为 `1`。对于笛卡尔图表,单位格式化也适用于轴标签。 + +*单位设置为比特、小数位数设置为 1 的条形图* + +## 最小和最大 + +使用**最小**和**最大**定义显示的值范围。 + +对于笛卡尔图表,如面积图、条形图、直方图、折线图和散点图,**最小**和**最大**设置值轴范围。 + +以下条形图的**最小**设置为 `100`,**最大**设置为 `300`。条形基线从 `100` 开始,因此低于此范围的值被裁剪,值轴延伸到 `300`。 + +*最小设置为 100、最大设置为 300 的条形图* + +对于仪表图和条形仪表图,**最小**和**最大**定义刻度边界。阈值和填充范围在此范围内计算。留空时,可视化会自动计算范围。 + +下图显示了带有基础颜色和在 `1000`、`1100`、`1700`、`1800`、`1900` 和 `2100` 处的步进的阈值配置。 + +*带有基础颜色和在 1000、1100、1700、1800、1900 和 2100 处步进的阈值配置* + +以下仪表图使用该阈值配置,值为 `2000`,**最小**设置为 `1200`,**最大**设置为 `2200`。仪表刻度使用此范围定位阈值段。 + +*显示值 2000、最小设置为 1200、最大设置为 2200 的仪表图* diff --git a/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds.md b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds.md new file mode 100644 index 00000000..cf97581e --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds.md @@ -0,0 +1,246 @@ +--- +title: 阈值 +--- + +# 可视化编辑器中的阈值 + +阈值是一个边界值,当数据点达到或超过该值时,会触发颜色的视觉变化。使用阈值定义有意义的范围,以便您可以立即了解值是在正常、警告还是关键区域。 + +每个阈值定义一个值范围。基础阈值适用于低于第一个阈值的所有值,每个额外的阈值从其配置的值开始,直到下一个阈值开始。例如,如果基础颜色是绿色,50 处的阈值是黄色,80 处的阈值是红色,则低于 50 的值为绿色,50 到低于 80 的值为黄色,80 或更高的值为红色。 + +## 支持的图表类型 + +阈值在以下图表类型中可用: + +- [面积图](/dashboards/visualize/visualization-editor/area-chart) +- [条形图](/dashboards/visualize/visualization-editor/bar-chart) +- [条形仪表图](/dashboards/visualize/visualization-editor/bar-gauge-chart) +- [仪表图](/dashboards/visualize/visualization-editor/gauge-chart) +- [热力图](/dashboards/visualize/visualization-editor/heatmap-chart) +- [直方图](/dashboards/visualize/visualization-editor/histogram-chart) +- [折线图](/dashboards/visualize/visualization-editor/line-chart) +- [指标图](/dashboards/visualize/visualization-editor/metric-chart) +- [散点图](/dashboards/visualize/visualization-editor/scatter-chart) +- [状态时间线](/dashboards/visualize/visualization-editor/state-timeline-chart) +- [表格](/dashboards/visualize/visualization-editor/table-chart) + +## 配置阈值 + +要添加阈值,请打开配置面板中的**阈值**部分并选择 **+ 添加阈值**。对于每个阈值,配置以下设置。 + +| 设置 | 描述 | +| :--- | :--- | +| **颜色** | 选择应用于落在此阈值范围内的值的颜色。选择预设颜色或自定义颜色。 | +| **值** | 输入此阈值开始的数值边界。等于或大于此数字(且低于下一个阈值)的值以此颜色显示。 | + +OpenSearch Dashboards 自动按值对阈值进行排序。基础阈值始终存在,代表低于其他阈值的所有值的起始颜色。您可以更改基础颜色,但不能删除基础阈值或为其设置值。要删除任何其他阈值,请选择其旁边的垃圾箱图标。 + +## 按图表类型的阈值效果 + +阈值的应用方式因图表类型而异。某些可视化使用阈值为图表标记着色,某些使用阈值作为参考线,某些需要额外的图表特定设置,如**使用阈值颜色**或**单元格样式**。下表描述了每种图表类型中阈值的应用方式。 + +| 图表类型 | 阈值效果 | 额外设置 | +| :--- | :--- | :--- | +| 仪表 | 按阈值范围为仪表弧着色。当启用**使用阈值颜色**时,显示的值也使用匹配的阈值颜色。 | 启用**使用阈值颜色**。 | +| 条形仪表 | 按阈值范围为条形仪表着色。视觉结果还取决于所选的显示样式,如渐变、堆叠或基本。 | 无。 | +| 指标 | 根据指标值和所选颜色模式为指标值或背景着色。 | 设置**颜色模式**然后启用**使用阈值颜色**。 | +| 折线和面积 | 将阈值显示为水平参考线。线条或区域标记本身不会改变颜色。 | 将**阈值线模式**设置为**实线**、**虚线**或**点线**。 | +| 条形和直方图 | 启用阈值颜色时按值范围为条形着色。您还可以显示阈值参考线。 | 启用**使用阈值颜色**为条形着色。设置**阈值线模式**以显示参考线。 | +| 热力图 | 按值范围为单元格着色,覆盖所选颜色方案。 | 启用**使用阈值颜色**。 | +| 散点图 | 启用阈值颜色时按值范围为点着色。您还可以显示阈值参考线。 | 启用**使用阈值颜色**为点着色。设置**阈值线模式**以显示参考线。 | +| 状态时间线 | 按值范围为状态区域着色,覆盖值映射颜色。 | 启用**使用阈值颜色**。 | +| 表格 | 按值范围为数字表格单元格着色。 | 在**单元格样式**中,选择数值字段然后选择**彩色文本**或**彩色背景**。 | + +::: info NOTE +状态时间线图还包括通过时间阈值断开值和连接空值的设置。这些设置控制时间线中的间隙,不影响本页描述的颜色阈值。 +::: + +## 阈值示例 + +以下示例展示了如何使用 OpenSearch Dashboards 示例数据将阈值应用于每种支持的图表类型。 + +### 仪表图 + +在仪表图中,阈值直接为弧着色。**标准选项**下的**最小**和**最大**控件定义刻度范围,阈值将该刻度划分为彩色段。要将阈值应用于仪表图,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m) + ``` + +1. 选择**仪表**作为可视化类型。 +1. 在**仪表**部分,启用**使用阈值颜色**。 +1. 打开**阈值**部分并选择 **+ 添加阈值**。 +1. 将基础颜色设置为绿色并在 `6000`、`8000` 和 `10000` 处添加阈值。 + +弧使用每个范围的阈值颜色,显示的值使用匹配的阈值颜色,如下图所示。 + +*带有阈值着色弧和以匹配阈值颜色显示的值的仪表图* + +### 条形仪表图 + +在条形仪表图中,阈值定义每个条形的彩色范围。结果取决于所选的显示样式: + +- **渐变**显示跨阈值颜色的平滑过渡。 +- **堆叠**将条形划分为不同的阈值段。 +- **基本**使用包含该值的阈值范围为条形着色。 + +要将阈值应用于条形仪表图,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m), extension + ``` + +1. 选择**条形仪表**作为可视化类型。 +1. 在**字段**部分,将 **X 轴**设置为 `extension`,将 **Y 轴**设置为 `AVG(bytes)`。 +1. 在**阈值**部分,在 `3000`、`5000` 和 `8000` 处设置阈值。 +1. 在**条形仪表**部分,选择**显示样式**。 + +每个条形按包含其值的阈值范围着色,如下图所示。 + +*每个条形按其阈值范围着色的条形仪表图* + +### 指标图 + +在指标图中,阈值根据所选**颜色模式**为显示的值或其背景着色。要将阈值应用于指标图,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m), extension + ``` + +1. 选择**指标**作为可视化类型。 +1. 在**指标**部分,将**颜色模式**设置为**背景渐变**并启用**使用阈值颜色**。 +1. 在**阈值**部分,在 `4000`、`6000` 和 `8000` 处设置阈值。 + +每个指标的背景使用包含指标值的阈值范围的颜色,如下图所示。 + +*阈值颜色应用于每个指标背景的指标图* + +### 折线图和面积图 + +在折线图和面积图中,阈值显示为跨图表的水平参考线。线条或区域标记本身不会改变颜色。要向折线图或面积图添加阈值线,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | stats avg(bytes) by span(`@timestamp`, 5m) + ``` + +1. 选择**折线**作为可视化类型。 +1. 打开**阈值**部分并选择 **+ 添加阈值**。 +1. 在 `5000` 和 `8000` 处设置阈值。 +1. 将**阈值线模式**设置为**虚线**。 + +每个阈值值处出现一条虚线水平线,如下图所示。 + +*每个阈值值处有虚线水平参考线的折线图* + +使用**阈值线模式**设置控制线条外观: + +- **关闭**:不显示阈值线。 +- **实线**:在每个阈值值处绘制实线水平线。 +- **虚线**:在每个阈值值处绘制虚线水平线。 +- **点线**:在每个阈值值处绘制点线水平线。 + +### 条形图和直方图 + +在条形图和直方图中,阈值可以根据每个条形的值为条形着色。这些图表类型还可以显示阈值参考线。要将阈值颜色应用于条形图,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | stats avg(bytes) by extension + ``` + +1. 选择**条形**作为可视化类型。 +1. 在**字段**部分,将 **X 轴**设置为 `extension`,将 **Y 轴**设置为 `AVG(bytes)`。 +1. 在**条形**部分,启用**使用阈值颜色**。 +1. 在**阈值**部分,在 `2000`、`4000` 和 `6000` 处设置阈值。 +1. 将**阈值线模式**设置为**关闭**。 + +每个条形按包含其值的阈值范围着色,如下图所示。 + +*每个条形按其阈值范围着色的条形图* + +### 热力图 + +在热力图中,阈值按值范围为单元格着色,覆盖所选颜色方案。要将阈值应用于热力图,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | stats avg(bytes) by extension, `machine.os` + ``` + +1. 选择**热力图**作为可视化类型。 +1. 在**字段**部分,将 **X 轴**设置为 `extension`,将 **Y 轴**设置为 `machine.os`,将**值**设置为 `AVG(bytes)`。 +1. 在**热力图**部分,启用**使用阈值颜色**。 +1. 在**阈值**部分,在 `4000`、`6000` 和 `8000` 处设置阈值。 + +每个单元格按包含其值的阈值范围着色,如下图所示。 + +*每个单元格按其阈值范围着色的热力图* + +### 散点图 + +在散点图中,阈值可以根据每个点的值为点着色。散点图还可以显示阈值参考线。要将阈值应用于散点图,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_flights` 数据集并选择**更新**。 +1. 选择**散点图**作为可视化类型。 +1. 在**字段**部分,将 **X 轴**设置为 `DistanceMiles`,将 **Y 轴**设置为 `AvgTicketPrice`。 +1. 打开**阈值**部分并选择 **+ 添加阈值**。 +1. 在 `400`、`600` 和 `800` 处设置阈值。 + +每个点按包含其票价的阈值范围着色,如下图所示。 + +*每个点按其票价阈值范围着色的散点图* + +### 状态时间线 + +在状态时间线中,阈值按数值范围为状态区域着色。当颜色代表范围(如成功、警告和错误响应码)而不是单个值时使用阈值。要将阈值应用于状态时间线,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_logs` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | FIELDS @timestamp, response + ``` + +1. 选择**状态时间线**作为可视化类型。 +1. 在**字段**部分,将 **X 轴**设置为 `@timestamp`,将**颜色**设置为 `response`。因为 `response` 字段是数值的,OpenSearch Dashboards 可以将其划分为阈值范围。 +1. 在**阈值**部分,保持基础颜色为绿色并在 `400` 和 `500` 处设置阈值。 +1. 在**状态时间线**部分,启用**使用阈值颜色**。要仅显示阈值着色的区域,保持**显示显示文本**关闭。 + +时间线区域按响应码范围着色:从 `0` 到低于 `400` 的值,从 `400` 到低于 `500` 的值,以及 `500` 或更高的值,如下图所示。 + +*按响应码范围着色区域的状态时间线* + +### 表格 + +在表格中,阈值为数字单元格着色。要将阈值应用于表格,请按照以下步骤操作: + +1. 选择 `opensearch_dashboards_sample_data_flights` 数据集。 +1. 输入以下查询并选择**更新**: + + ```sql + | FIELDS AvgTicketPrice, Carrier, Dest, Origin + ``` + +1. 选择**表格**作为可视化类型。 +1. 在**表格**部分,将**单元格样式**设置为 `AvgTicketPrice` 并选择**彩色背景**。 +1. 在**阈值**部分,在 `400`、`600` 和 `1000` 处设置阈值。 + +每个 `AvgTicketPrice` 单元格背景按包含其值的阈值范围着色,如下图所示。 + +*数字单元格背景按阈值范围着色的表格* diff --git a/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations.md b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations.md new file mode 100644 index 00000000..290682d4 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations.md @@ -0,0 +1,38 @@ +--- +title: 值计算 +--- + +# 值计算 + +当可视化接收数值字段时,数据通常包含一系列值而不是单个数字。使用**计算**设置选择一个归约函数,将系列聚合为一个代表值进行显示。 + +## 支持的图表类型 + +值计算设置在以下图表类型中可用。这些是唯一每个系列显示单个聚合值的图表类型。 + +- 条形仪表图 +- 仪表图 +- 指标图 + +## 缺失值 + +数据系列可能包含 `NaN` 或 `null` 条目。标有星号(\*)的计算方法会跳过这些无效条目,仅对有效数值进行操作。没有星号的方法使用原始位置值,无论它们是否为有效数字。 + +## 可用计算 + +下表列出了所有可用的计算方法。 + +| 计算 | 描述 | 需要有效值 | +| --- | --- | --- | +| **第一** | 字段中的第一个值。 | 否 | +| **第一 \*** | 字段中第一个有效(非 `null`、非 `NaN`)的值。 | 是 | +| **最后** | 字段中的最后一个值。 | 否 | +| **最后 \*** | 字段中最后一个有效(非 `null`、非 `NaN`)的值。 | 是 | +| **最小** | 所有有效值中的最小值。 | 是 | +| **最大** | 所有有效值中的最大值。 | 是 | +| **平均** | 所有有效值的算术平均值。 | 是 | +| **中位数** | 所有有效值排序后的中间值。 | 是 | +| **总计** | 所有有效值的总和。 | 是 | +| **计数** | 字段中值的总数(包括 `null`/`NaN`)。 | 否 | +| **去重计数** | 字段中唯一值的数量(包括 `null`/`NaN`)。 | 否 | +| **方差** | 所有有效值的统计方差。 | 是 | diff --git a/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/index.md b/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/index.md new file mode 100644 index 00000000..40973450 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/index.md @@ -0,0 +1,156 @@ +--- +title: 仪表板变量 +--- + +# 仪表板变量 +<Badge type="tip" text="3.7 版本引入" /> + +仪表板变量是可重用的值,您可以在[可视化编辑器](/dashboards/visualize/visualization-editor/)查询中引用它们。使用变量进行过滤、指标、维度、间隔、字段、聚合以及任何其他查询参数,无需在数据视图之间切换时手动编辑 PPL 或 PromQL 查询。 + +::: info NOTE +仪表板变量仅在**可观测性**工作区中可用。要使用仪表板变量,如果您还没有可观测性工作区,请创建一个。有关更多信息,请参阅 [OpenSearch Dashboards 工作区](/dashboards/workspace/)。 +::: + +使用仪表板变量可以: + +- 无需编辑可视化即可更改查询参数。 +- 一次定义值并在多个可视化中引用它们。 +- 当变量值更改时自动更新可视化。 +- 使用依赖变量创建级联过滤器。 +- 动态控制分组、聚合和时间间隔。 + +## 变量类型 + +OpenSearch Dashboards 支持以下变量类型: + +- **查询变量**:选项使用管道处理语言(PPL)或 Prometheus 查询语言(PromQL)查询从数据源动态获取。当值随时间变化或依赖于底层数据时使用查询变量,例如日志中的服务名称或指标中的可用区域。对于 Prometheus 数据连接,您可以从 PromQL 查询类型(标签名称、标签值、指标或系列)构建查询,而不是编写原始查询。有关更多信息,请参阅[使用 PromQL 查询变量](/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables#using-a-promql-query-variable)。 + +- **自定义变量**:选项作为静态列表手动定义。对于预定义的类别(如环境类型 `dev`、`staging`、`prod`)或固定状态码,使用自定义变量。 + +- **文本变量**:您在变量栏中输入的单个值。对于无法提前列出的值(如搜索词或阈值),使用文本变量。 + +## 变量语法 + +您可以使用 `$variableName` 或 `${variableName}` 语法在查询中引用变量: + +```sql +source=logs | where service='${service}' | stats count() by region +``` + +当您在仪表板中更改变量的值时,引用该变量的所有可视化会自动使用新值刷新。 + +## 启用仪表板变量 + +除了[启用工作区](/dashboards/workspace/workspace#enabling-workspaces)外,还要将以下设置添加到您的 `opensearch_dashboards.yml` 文件中: + +```yaml +explore.enabled: true +``` + +重新启动 OpenSearch Dashboards 以使更改生效。 + +## 创建和使用仪表板变量 + +以下教程使用 OpenSearch Dashboards 示例 Web 日志数据集创建变量并在可视化中使用它。 + +### 步骤 1:创建工作区 + +1. 导航到 OpenSearch Dashboards 主页。 +1. 选择**创建工作区**。 +1. 输入工作区名称(例如 `My Observability`)。 +1. 在**用例和功能**部分,保持选中**可观测性**。 +1. 选择**创建工作区**。 + +有关更多信息,请参阅[创建工作区](/dashboards/workspace/create-workspace)。 + +### 步骤 2:设置示例数据 + +在工作区中,导航到**管理工作区** > **示例数据**,并为 Web 日志数据集选择**添加数据**。添加示例数据还会创建 `opensearch_dashboards_sample_data_logs` 索引模式。 + +### 步骤 3:创建变量 + +1. 在左侧导航中选择**仪表板**。 +1. 选择**创建仪表板**。 +1. 通过输入标题(例如 `Log Analysis`)并选择**保存**来保存仪表板。保存会将仪表板切换到查看模式。 +1. 打开**编辑**切换。 +1. 在仪表板顶部,选择**添加变量**。 +1. 在**名称**字段中,输入 `extension`。 +1. 在**类型**下拉列表中,保持选中**查询**。 +1. 在**查询选项**部分,选择**打开变量编辑器**。 +1. 保持查询语言设置为 **PPL**。验证所选数据集是 `opensearch_dashboards_sample_data_logs`。要选择不同的数据集,请选择数据集名称。 +1. 输入以下查询: + + ```sql + source=opensearch_dashboards_sample_data_logs | stats count() by extension | fields extension + ``` + +1. 要验证结果,请选择**预览**。预览显示 `css`、`deb`、`gz`、`rpm`、`zip` 以及没有文件扩展名的文档的空值。 +1. 在**值字段**下拉列表中,验证已选择 `extension`。预览会自动填写此字段。 +1. 选择**应用**以保存查询并关闭编辑器。 +1. 选择**添加变量**以保存。 + +`extension` 变量现在出现在仪表板顶部,带有一个下拉列表。 + +有关更多信息,请参阅[管理仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables)。 + +### 步骤 4:在可视化中使用变量 + +1. 在仪表板中,选择**新建**。 +1. 选择**添加可视化**以打开可视化编辑器。 +1. 在查询编辑器中,输入以下引用 `$extension` 变量的 PPL 查询: + + ```sql + | where extension='$extension' | stats count() by response + ``` + +1. 在编辑器顶部的 `extension` 下拉列表中,选择一个值(例如 `css`)。 +1. 选择**更新**以运行查询。 + +可视化显示按所选扩展名过滤的响应码分布,如下图所示。 + +*显示按所选扩展名值过滤的响应码条形图的可视化编辑器* + +当您在下拉列表中更改 `extension` 值时,可视化会自动更新以反映新选择。 + +::: tip TIP +如果没有显示结果,请使用右上角的[时间过滤器](/dashboards/discover/time-filter)扩展时间范围(例如**最近 90 天**)。 +::: + +有关更多信息,请参阅[使用仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/using-variables)。 + +## 变量存储 + +变量作为 OpenSearch 中仪表板保存对象的一部分存储。每个仪表板独立维护自己的变量集。 + +仪表板保存对象中的 `variablesJSON` 属性包含变量配置: + +```typescript +{ + type: "dashboard", + id: "dashboard-id", + attributes: { + title: "My Dashboard", + variablesJSON: "{\"variables\":[...]}" + } +} +``` + +变量配置包括以下组件: + +- 元数据(名称、标签、描述、类型)。 +- 选项(查询类型的查询定义或自定义类型的自定义值)。 +- 设置(多选、"全部"选项、排序顺序、可见性)。 +- 当前值(每个变量的选定值)。 + +当前变量值也同步到仪表板 URL,因此您可以: + +- 共享预选特定过滤值的仪表板。 +- 收藏具有所需变量状态的仪表板。 +- 在页面刷新后保持变量选择。 + +## 相关文档 + +- [管理仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables) +- [使用仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/using-variables) +- [使用查询创建可视化](/dashboards/visualize/visualization-editor/) +- [OpenSearch Dashboards 工作区](/dashboards/workspace/) diff --git a/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables.md b/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables.md new file mode 100644 index 00000000..26a2af52 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/managing-variables.md @@ -0,0 +1,294 @@ +--- +title: 管理仪表板变量 +--- + +# 管理仪表板变量 + +您可以在仪表板内创建、编辑、删除、组织和查看仪表板变量。 + +## 先决条件 + +在开始之前,请确保您已满足以下先决条件: + +- 仪表板变量已在您的 `opensearch_dashboards.yml` 文件中[启用](/dashboards/visualize/visualization-editor/dashboard-variables/#enabling-dashboard-variables)。 +- 您已设置[可观测性工作区](/dashboards/workspace/create-workspace)。 + +有关完整设置,请参阅[创建和使用仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/#creating-and-using-dashboard-variables)。 + +## 创建查询变量 + +当可用值列表从数据源检索时,使用查询变量。例如,您可以从示例 Web 日志数据创建 `extension` 变量,并使用它按文件扩展名过滤多个可视化。 + +::: info NOTE +以下示例使用 OpenSearch Dashboards 示例 Web 日志数据。如果您使用不同的数据集,请选择与您的数据匹配的数据集和字段。 +::: + +要创建查询变量,请按照以下步骤操作: + +1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 +1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 +1. 如果仪表板处于查看模式,请打开**编辑**切换。 +1. 在仪表板顶部,选择**添加变量**。 +1. 配置以下常规设置: + - **名称**:输入 `extension`。这是用于在查询中引用变量的标识符,例如 `$extension` 或 `${extension}`。 + - **标签**:输入 `Extension`。这是显示在仪表板顶部的显示名称。 + - **描述**:可选地输入描述,例如 `按文件扩展名过滤可视化`。 + - **类型**:保持选中**查询**。 +1. 在**查询选项**部分,选择**打开变量编辑器**。查询编辑器在带有固定**值预览**面板的模态窗口中打开。 +1. 保持查询语言设置为 **PPL**。要从 Prometheus 元数据构建查询,请参阅[使用 PromQL 查询变量](#using-a-promql-query-variable)。 +1. 验证所选数据集是 `opensearch_dashboards_sample_data_logs`。要选择不同的数据集,请选择数据集名称。 +1. 输入以下查询: + + ```sql + source = opensearch_dashboards_sample_data_logs | stats count() by extension | fields extension + ``` + +1. 选择**预览**。预览运行查询并在**值预览**面板中显示前 100 个变量选项。您必须在应用查询变量之前成功预览它。 +1. 在**值字段**下拉列表中,验证已选择 `extension`。预览会自动填写此字段。值字段提供在您使用 `$extension` 或 `${extension}` 时插入查询的值。 +1. 在**标签字段**下拉列表中,保持**无**。仅当查询返回单独的字段以在下拉列表中代替存储值显示时才选择标签字段。 +1. 可选:在**正则表达式**中,输入正则表达式以过滤可用选项或从查询结果中提取值和标签。例如,`^(css|gz|zip)$` 仅显示 `css`、`gz` 和 `zip` 选项。预览会更新以显示过滤后的选项。有关更多信息,请参阅[使用正则表达式过滤和提取选项](#filtering-and-extracting-options-with-a-regular-expression)。 +1. 选择**应用**以保存查询并关闭编辑器。 +1. 返回变量编辑器,在**查询选项**部分,选择**刷新**选项以选择 OpenSearch Dashboards 何时更新变量选项: + - **仪表板加载时**(默认):在仪表板加载时刷新选项。 + - **时间范围更改时**:在仪表板时间范围更改时刷新选项。当可用值取决于所选时间范围时使用此选项。 +1. 在**选择选项**部分配置设置。有关更多信息,请参阅[配置变量选项设置](#configuring-variable-option-settings)。 +1. 选择**添加变量**。 + +变量出现在仪表板顶部。下图显示了使用示例 Web 日志数据配置的 `extension` 查询变量的查询编辑器。 + +*使用示例 Web 日志数据配置的 extension PPL 查询变量的查询编辑器* + +### 映射查询结果字段 + +查询变量可以使用一个字段作为存储值,另一个字段作为显示标签: + +- **值字段**:用作变量值的字段。当您引用变量时,OpenSearch Dashboards 将此值插入查询。 +- **标签字段**:用作变量下拉列表中显示标签的可选字段。标签不会更改插入查询的值。 + +例如,如果您的查询返回 `service_id` 和 `service_name`,请将**值字段**设置为 `service_id`,将**标签字段**设置为 `service_name`。下拉列表显示服务名称,查询接收服务 ID。 + +::: tip TIP +如果您不选择值字段,OpenSearch Dashboards 使用查询返回的第一个字段。为避免意外值,请预览查询并显式选择要用作变量值的字段。 +::: + +### 使用 PromQL 查询变量 + +当查询变量使用由 Prometheus 数据连接支持的数据集时,您可以将查询语言设置为 **PromQL**。您可以从以下 PromQL 查询类型之一构建变量,而不是编写原始查询: + +- **标签名称**:列出数据中的标签名称。您可以选择将结果限定到某个指标。 +- **标签值**:列出您选择的标签的值。您可以使用标签匹配器(`=`、`!=`、`=~` 和 `!~`)缩小结果范围,并从指标资源管理器中选择指标。 +- **指标**:列出指标名称。您可以选择使用指标名称上的正则表达式过滤结果。 +- **系列查询**:列出与系列选择器匹配的完整时间序列(标签集)。 +- **查询结果**:评估原始 PromQL 表达式,与 PPL 使用的自由文本路径相同。 + +要创建 PromQL 查询变量,请按照以下步骤操作: + +1. 在仪表板顶部,选择**添加变量**,并将**类型**设置为**查询**。 +1. 在**查询选项**部分,选择**打开变量编辑器**。 +1. 将查询语言设置为 **PromQL**。 +1. 选择数据集名称并选择由 Prometheus 数据连接支持的数据集。 +1. 在**查询类型**中,选择查询类型(例如**标签值**)并填写其字段。对于**标签值**,选择标签,以及可选的指标和一个或多个标签匹配器。 +1. 选择**预览**以加载选项,然后选择**应用**以保存查询并关闭编辑器。 +1. 配置刷新行为,然后选择**添加变量**。 + +下图显示了配置为**标签值**查询类型的 PromQL 查询变量。 + +*配置为 PromQL 标签值查询变量的变量编辑器面板* + +::: info NOTE +PromQL 查询变量需要可观测性工作区中由 Prometheus 数据连接支持的数据集。 +::: + +### 使用正则表达式过滤和提取选项 + +查询变量中的**正则表达式**字段支持两种行为。您可以将表达式作为裸模式(例如 `^win`)或以 `/pattern/flags` 形式(例如 `/^win/i`)输入。 + +以下示例使用从示例 Web 日志 `machine.os` 字段创建的查询变量: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by `machine.os` | fields `machine.os` +``` + +预览此查询返回选项 `ios`、`osx`、`win 7`、`win 8` 和 `win xp`。然后您可以对这些结果应用正则表达式: + +- **过滤**:当正则表达式没有 `value` 或 `label` 捕获组时,OpenSearch Dashboards 仅保留匹配的选项并保持不变。例如,`^win` 仅保留 `win 7`、`win 8` 和 `win xp`。 +- **提取**:当正则表达式包含命名的 `(?<value>...)` 捕获组时,OpenSearch Dashboards 用捕获的文本替换每个选项的值。可选的命名 `(?<label>...)` 组设置显示标签。解析为相同值的选项会自动去重。例如,`^(?<value>ios|osx|win)` 提取操作系统族,因此 `win 7`、`win 8` 和 `win xp` 折叠为单个 `win` 选项,留下 `ios`、`osx` 和 `win`。 + +要设置单独的显示标签,请添加 `(?<label>...)` 组。例如,如果查询返回复合值如 `env=dev,label=Development`,模式 `^env=(?<value>[^,]+),label=(?<label>.+)$` 将 `dev` 存储为值并在下拉列表中显示 `Development`。 + +*从示例 Web 日志 machine.os 字段提取操作系统族的正则表达式字段* + +::: tip TIP +当您编辑现有变量时,查询预览会自动运行,以便您可以立即看到提取的选项。 +::: + +## 创建自定义变量 + +当可用值列表是固定的且不需要从数据源获取时,使用自定义变量。例如,您可以创建包含 `dev`、`staging` 和 `prod` 选项的 `environment` 变量。 + +要创建自定义变量,请按照以下步骤操作: + +1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 +1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 +1. 如果仪表板处于查看模式,请打开**编辑**切换。 +1. 在仪表板顶部,选择**添加变量**。 +1. 配置以下常规设置: + - **名称**:输入 `environment`。这是用于在查询中引用变量的标识符,例如 `$environment` 或 `${environment}`。 + - **标签**:输入 `Environment`。 + - **描述**:可选地输入描述,例如 `按部署环境过滤可视化`。 + - **类型**:选择**自定义**。 +1. 在**自定义选项**中,选择**添加选项**。 +1. 在第一个选项行中,在**值**中输入 `dev`,在**标签**中输入 `Development`。当您引用变量时,OpenSearch Dashboards 将值插入查询,并使用可选标签作为下拉列表中的显示文本。 +1. 再次选择**添加选项**,在**值**中输入 `staging`,在**标签**中输入 `Staging`。 +1. 再次选择**添加选项**,在**值**中输入 `prod`,在**标签**中输入 `Production`。 +1. 配置共享选项设置。有关更多信息,请参阅[配置变量选项设置](#configuring-variable-option-settings)。 +1. 选择**添加变量**。 + +::: info NOTE +自定义选项值必须唯一且不能为空。OpenSearch Dashboards 在下拉列表中最多显示 100 个选项。 +::: + +下图显示了配置有值和标签对的 `environment` 自定义变量。 + +*配置有值和标签选项行的 environment 自定义变量的变量编辑器面板* + +## 创建文本变量 + +当您想直接输入单个自由格式的值而不需要选项列表时,使用文本变量。例如,您可以创建 `search_term` 变量并从变量栏更改其值而无需打开编辑器。 + +要创建文本变量,请按照以下步骤操作: + +1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 +1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 +1. 如果仪表板处于查看模式,请打开**编辑**切换。 +1. 在仪表板顶部,选择**添加变量**。 +1. 配置以下常规设置: + - **名称**:输入 `search_term`。这是用于在查询中引用变量的标识符,例如 `$search_term` 或 `${search_term}`。 + - **标签**:输入 `Search term`。 + - **描述**:可选地输入描述。 + - **类型**:选择**文本**。 +1. 在**值**中,输入初始值。 +1. 选择**添加变量**。 + +文本变量在仪表板顶部显示为输入框。输入值并按 **Enter**,或在框外选择以应用它。值在您完成编辑时应用,而不是在每次按键时应用,因此引用该变量的可视化在您输入时不会重新运行。 + +*配置有自由格式值的文本变量的变量编辑器面板* + +::: info NOTE +文本变量没有选项列表,因此**排序**、**允许多选**、**包含全部选项**和**允许自定义值**设置不适用,对于此类型会隐藏。 +::: + +## 配置变量选项设置 + +查询变量和自定义变量共享以下选项设置: + +- **排序**:控制选项在下拉列表中的排序方式。选择**禁用**、**字母**升序或降序、或**数字**升序或降序。 +- **允许多选**:允许您从变量下拉列表中选择多个值。 +- **包含全部选项**:向下拉列表添加**全部**选项。此设置仅在启用**允许多选**时可用。 +- **允许自定义值**:允许您提交不在生成或静态选项列表中的值。启用此设置后,在变量下拉列表的搜索框中输入会将输入的值作为第一行提供,标记为**按 Enter 添加**。按 **Enter** 或选择该行以添加它。在多选变量中,自定义值附加到当前选择;在单选变量中,它替换当前值。自定义值仅存储为变量的选定值;它不会添加到变量定义中。 + +## 管理现有变量 + +**管理变量**面板列出所有现有变量,包括其类型、名称和配置选项。要访问此面板,请按照以下步骤操作: + +1. 导航到您的工作区。 +1. 从**仪表板**中,选择要更新的仪表板。 +1. 在顶部,切换**编辑**选择器以进入编辑模式。 +1. 在左上角,选择**管理变量**图标,如下图所示。 + +*显示变量名称、类型和操作图标的管理变量面板* + +::: info NOTE +**管理变量**图标仅在仪表板中创建了变量时才会出现。如果不存在变量,请先创建一个再访问管理界面。 +::: + +## 编辑变量 + +要编辑现有变量,请按照以下步骤操作: + +1. 打开**管理变量**面板。 +1. 选择要修改的变量的**编辑**图标。 +1. 进行更改。 +1. 选择**更新变量**以保存。 + +::: info NOTE +更改变量名称会导致引用旧名称的任何查询失败。 +::: + +## 删除变量 + +要删除变量,请按照以下步骤操作: + +1. 打开**管理变量**面板。 +1. 选择要删除的变量的**删除**图标。 +1. 在对话框中确认删除。 + +::: info NOTE +被其他变量或可视化编辑器引用的变量在管理面板中显示指示器。删除被引用的变量会导致使用它的任何查询失败。 +::: + +## 组织变量 + +变量按它们在管理面板中出现的顺序显示在仪表板顶部。 + +要重新排序变量,请按照以下步骤操作: + +1. 打开**管理变量**面板。 +1. 拖动变量左侧的重新排序手柄。 +1. 将其放到所需位置。 +1. 保存仪表板以应用新顺序。 + +## 隐藏变量 + +您可以从仪表板顶部隐藏变量,同时保持它们可在查询中使用。 + +要隐藏或显示变量,请按照以下步骤操作: + +1. 打开**管理变量**面板。 +1. 选择变量的**隐藏/显示**图标。 +1. 保存仪表板以应用更改。 + +::: info NOTE +隐藏的变量在管理面板中标有**隐藏**徽章,不会出现在仪表板中。 +::: + +## 变量状态指示器 + +每个变量在仪表板顶部显示状态指示器: + +- **加载中**:在系统获取选项时出现旋转器。 +- **错误**:出现错误图标,工具提示显示错误消息。下拉列表被禁用。 +- **无选项**:如果变量查询没有返回结果,下拉列表中显示"无选项"。 + +## URL 同步 + +变量值使用 `variableValues` 查询参数自动同步到仪表板 URL: + +```js +?variableValues=(service:(api),region:(us-east,us-west)) +``` + +URL 同步启用以下功能: + +- 发送预选特定变量值的仪表板链接。 +- 保存具有首选变量设置的仪表板视图。 +- 在页面刷新后保持变量选择。 + +## 变量依赖关系 + +查询类型变量可以在其查询中引用其他变量。以下示例显示了引用另一个变量的查询变量: + +```sql +source=logs | where region=$region | dedup service | fields service +``` + +在此示例中,`service` 变量依赖于 `region` 变量。当 `region` 变量更改时,`service` 变量会自动刷新其选项。 + +请记住以下注意事项: + +- 避免循环依赖,即变量 A 引用变量 B,变量 B 引用变量 A。 +- 变量按它们在管理面板中出现的顺序评估。将依赖变量放在它们引用的变量之后。 + +## 下一步 + +- [使用仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/using-variables) diff --git a/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/using-variables.md b/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/using-variables.md new file mode 100644 index 00000000..81c7d3bc --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/dashboard-variables/using-variables.md @@ -0,0 +1,319 @@ +--- +title: 使用仪表板变量 +--- + +# 使用仪表板变量 + +您可以在可视化编辑器的查询中引用仪表板变量,以创建动态、交互式的仪表板。 + +## 变量语法 + +仪表板变量可以使用以下语法选项在查询中引用。 + +### 基本语法 + +大多数情况下使用 `$variableName`: + +```sql +source=logs | where service='$service' | stats count() by region +``` + +### 大括号语法 + +当变量名后面跟着其他字符且没有空格时,使用 `${variableName}`: + +```sql +source = logs | where ${env}_level = "error" +``` + +大括号语法确保变量名被正确分隔。没有大括号,`$env_level` 会被解释为名为 `env_level` 的变量,而不是 `env`。 + +## 在查询中使用变量 + +仪表板变量支持管道处理语言(PPL)和 Prometheus 查询语言(PromQL)。以下示例使用 PPL。 + +#### 用于过滤的单值变量 + +以下查询按单值变量过滤日志: + +```sql +source=logs | where service='$service' | stats count() by status_code +``` + +当 `service` 设置为 `api` 时,查询解析为: + +```sql +source=logs | where service='api' | stats count() by status_code +``` + +#### 用于过滤的多值变量 + +以下查询按多值变量过滤日志: + +```sql +source=logs | where region IN $region | stats count() by service +``` + +当 `region` 选择了多个值(`us-east`、`us-west`)时,查询解析为: + +```sql +source=logs | where region IN ('us-east', 'us-west') | stats count() by service +``` + +#### 带数字的多值变量 + +当查询变量的选项被检测为数值或布尔值时,多值格式化不带引号: + +```sql +source=logs | where status_code IN $status | stats count() +``` + +当 `status` 选择了多个数值时,查询解析为: + +```sql +source=logs | where status_code IN (200, 404, 500) | stats count() +``` + +#### 用于分组维度的变量 + +以下查询使用变量控制分组维度: + +```sql +source=logs | stats count() by `$group_by` +``` + +当 `group_by` 设置为 `region` 时,查询解析为: + +```sql +source=logs | stats count() by region +``` + +#### 用于时间间隔的变量 + +以下查询使用变量控制时间间隔: + +```sql +source=logs | stats count() by span(timestamp, $interval) +``` + +当 `interval` 设置为 `5m` 时,查询解析为: + +```sql +source=logs | stats count() by span(timestamp, 5m) +``` + +#### 用于指标计算的变量 + +以下查询使用变量控制计算哪个指标: + +```sql +source=metrics | stats avg($metric) by service +``` + +当 `metric` 设置为 `response_time` 时,查询解析为: + +```sql +source=metrics | stats avg(response_time) by service +``` + +### 多值变量格式化 + +当变量允许多选时,值会根据查询语言自动格式化。 + +<table> + <thead> + <tr> + <th>查询语言</th> + <th>字符串值</th> + <th>数值或布尔值</th> + </tr> + </thead> + <tbody> + <tr> + <td>PPL</td> + <td><code>('value1', 'value2')</code></td> + <td><code>(123, 456)</code></td> + </tr> + <tr> + <td>PromQL</td> + <td><code>(value1|value2)</code></td> + <td><code>(value1|value2)</code></td> + </tr> + <tr> + <td>其他</td> + <td><code>value1, value2</code></td> + <td><code>value1, value2</code></td> + </tr> + </tbody> +</table> + +### 自动完成建议 + +OpenSearch Dashboards 中的查询编辑器为仪表板变量提供自动完成建议。 + +1. 在查询编辑器中,输入 `$`。出现一个下拉列表,显示所有可用的仪表板变量。 +1. 从列表中选择变量或继续输入以过滤,如下图所示。 + + *显示可用仪表板变量的自动完成下拉列表的查询编辑器* +1. 按 Enter 或 Tab 插入变量。 + +## 在可视化中使用变量 + +仪表板变量与 OpenSearch Dashboards 可视化编辑器集成,当从仪表板编辑可视化时完全支持仪表板变量。 + +### 按变量值过滤 + +变量可以作为可视化中的过滤条件。与其将过滤器应用于整个仪表板,不如将变量直接嵌入 PPL 查询中,为特定面板创建目标过滤。 + +要按变量值过滤可视化,请按照以下步骤操作: + +1. 创建 `machine_os` 变量: + 1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 + 1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 + 1. 如果仪表板处于查看模式,请打开**编辑**切换。 + 1. 在仪表板顶部,选择**添加变量**。 + 1. 在**名称**字段中输入 `machine_os`,并保持**类型**设置为**查询**。在**查询选项**部分,选择**打开变量编辑器**。保持语言设置为 **PPL**,验证所选数据集是 `opensearch_dashboards_sample_data_logs`,并输入以下查询: + + ```sql + | FIELDS `machine.os` + ``` + 1. 选择**预览**,确保在**值预览**中看到 `win 8`、`ios` 和 `win xp` 等值。选择**应用**以保存查询,然后选择**添加变量**以保存。 + +1. 按变量值过滤: + 1. 通过在仪表板中选择**新建**然后选择**添加可视化**来打开新的可视化编辑器。 + 1. 在时间过滤器中,选择**最近 30 天**。 + 1. 在查询框中,输入以下查询: + + ```sql + | WHERE `machine.os` = '${machine_os}' | STATS avg(memory) BY span(`@timestamp`, 1d) + ``` + + 要按 `machine_os` 值过滤可视化,请在 `machine_os` 下拉列表中选择值(例如选择 `win 8`),如下图所示。 + + *显示按 machine_os 设置为 win 8 过滤的随时间变化的平均内存的可视化编辑器* + +### 动态选择指标 + +使用变量控制聚合中使用的字段。这让您可以在指标(例如 `memory` 和 `bytes`)之间切换而无需编辑查询。 + +要动态选择指标,请按照以下步骤操作: + +1. 创建 `log_metric` 变量: + 1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 + 1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 + 1. 如果仪表板处于查看模式,请打开**编辑**切换。 + 1. 在仪表板顶部,选择**添加变量**。 + 1. 在**名称**中输入 `log_metric`。在**类型**中选择**自定义**。在**自定义选项**中,输入 `memory` 并按 **Enter** 添加。然后输入 `bytes` 并按 **Enter** 添加。 + 1. 选择**添加变量**以保存。 + +1. 在可视化中使用变量: + 1. 通过在仪表板中选择**新建**然后选择**添加可视化**来打开新的可视化编辑器。 + 1. 在时间过滤器中,选择**最近 30 天**。 + 1. 在查询框中,输入以下查询: + + ```sql + source=opensearch_dashboards_sample_data_logs + | stats avg($log_metric) as avg_${log_metric} by span(`timestamp`, 1h) as timestamp, response + ``` + + 要在指标之间切换,请在 `log_metric` 下拉列表中选择值(例如选择 `memory` 或 `bytes`)。 + + *显示 log_metric 变量设置为 memory 的随时间变化的平均内存的可视化编辑器* + +### 动态更改时间间隔 + +使用变量让仪表板查看者在时间聚合间隔(例如 `1h`、`6h` 或 `1d`)之间切换而无需编辑查询。 + +要动态更改时间间隔,请按照以下步骤操作: + +1. 创建 `interval` 变量: + 1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 + 1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 + 1. 如果仪表板处于查看模式,请打开**编辑**切换。 + 1. 在仪表板顶部,选择**添加变量**。 + 1. 在**名称**中输入 `interval`。在**类型**中选择**自定义**。在**自定义选项**中,输入 `1d` 并按 **Enter** 添加。对 `12h`、`6h` 和 `1h` 重复。 + 1. 选择**添加变量**以保存。 + +1. 在可视化中使用变量: + 1. 通过在仪表板中选择**新建**然后选择**添加可视化**来打开新的可视化编辑器。 + 1. 在时间过滤器中,选择**最近 30 天**。 + 1. 在查询框中,输入以下查询: + + ```sql + source=opensearch_dashboards_sample_data_logs | stats AVG(`bytes`) as avg_bytes, MAX(`bytes`) as max_bytes by span(`timestamp`, $interval) + ``` + + 要在间隔之间切换,请在 `interval` 下拉列表中选择值(例如选择 `6h`)并选择**更新**。可视化反映所选的时间分桶,如下图所示。 + + *显示 interval 变量设置为 1d 的随时间变化的 avg_bytes 和 max_bytes 的可视化编辑器* + +### 动态更改聚合函数 + +使用变量让仪表板查看者在聚合函数(例如 `avg`、`max` 或 `min`)之间切换而无需编辑查询。 + +要动态更改聚合函数,请按照以下步骤操作: + +1. 创建 `function` 变量: + 1. 在您的可观测性工作区中,在左侧导航中选择**仪表板**。 + 1. 打开现有仪表板或选择**创建仪表板**创建新仪表板。如果创建新仪表板,请先通过输入标题并选择**保存**来保存它。 + 1. 如果仪表板处于查看模式,请打开**编辑**切换。 + 1. 在仪表板顶部,选择**添加变量**。 + 1. 在**名称**中输入 `function`。在**类型**中选择**自定义**。在**自定义选项**中,输入 `avg` 并按 **Enter** 添加。对 `max` 和 `min` 重复。 + 1. 选择**添加变量**以保存。 + +1. 在可视化中使用变量: + 1. 通过在仪表板中选择**新建**然后选择**添加可视化**来打开新的可视化编辑器。 + 1. 在时间过滤器中,选择**最近 30 天**。 + 1. 在查询框中,输入以下查询: + + ```sql + | STATS ${function}(memory) BY span(`@timestamp`, 1d) + ``` + + 要在函数之间切换,请在 `function` 下拉列表中选择值(例如选择 `max`)并选择**更新**。可视化反映所选的聚合函数,如下图所示。 + + *显示 function 变量设置为 avg 的随时间变化的平均内存的可视化编辑器* + +## 级联和跨面板变量 + +以下部分描述了高级变量用例。 + +### 级联变量 + +创建依赖变量,其中一个变量过滤另一个变量的选项。例如,首先选择区域,然后从该区域中可用的服务中选择。 + +创建 `region` 变量: + +```sql +source=logs | dedup region | fields region +``` + +创建引用 `region` 的 `service` 变量: + +```sql +source=logs | where region='$region' | dedup service | fields service +``` + +当 `region` 值更改时,`service` 变量会自动刷新其选项,仅显示所选区域中的服务。 + +### 跨面板过滤 + +使用单个变量同时过滤多个可视化。例如,创建 `service` 变量并在多个可视化编辑器中引用它。 + +可视化编辑器 1(按服务统计请求数): + +```sql +source=logs | where service='$service' | stats count() by status_code +``` + +可视化编辑器 2(按服务统计响应时间): + +```sql +source=metrics | where service='$service' | stats avg(response_time) +``` + +更改 `service` 变量值会同时更新两个可视化编辑器。 + +## 下一步 + +- [创建仪表板](/dashboards/dashboard/) diff --git a/i18n/zh/dashboards/visualize/visualization-editor/data-transformation/index.md b/i18n/zh/dashboards/visualize/visualization-editor/data-transformation/index.md new file mode 100644 index 00000000..cf4bacc7 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/data-transformation/index.md @@ -0,0 +1,293 @@ +--- +title: 数据转换 +--- + +# 数据转换 + +数据转换在渲染可视化之前修改查询结果。使用转换来重塑、过滤、排序、计算或汇总数据,而不更改原始查询。 + +转换作为管道应用。每个转换接收前一个转换的输出作为其输入,因此转换的顺序可以改变最终结果。 + +在以下情况下使用转换: + +- 在查询返回结果后过滤行。 +- 保留或删除结果表中的特定字段。 +- 在可视化之前对行进行排序。 +- 限制可视化中显示的行数。 +- 将字段值转换为另一种类型,如数字、字符串、布尔或日期。 +- 从对象或 JSON 字符串中提取字段到顶级列。 +- 从现有数值字段添加计算字段。 +- 按字段分组行并聚合其余字段。 + +当查询返回正确的数据但不完全是可视化所需的形状时,转换很有用。如果数据可以在查询中更有效地过滤或聚合,请先更新查询。 + +## 支持的转换 + +下表列出了可用的转换。 + +| 转换 | 描述 | +| --- | --- | +| **限制** | 仅保留指定数量的行。 | +| **排序** | 按一个字段升序或降序对行排序。 | +| **过滤** | 保留匹配字段、运算符和值条件的行。 | +| **过滤字段** | 包含或排除选定的字段。 | +| **转换字段类型** | 将字段值转换为字符串、数字、布尔或日期。 | +| **分组** | 按一个字段分组行并聚合其余字段。 | +| **提取字段** | 将嵌套对象或 JSON 字符串字段提取到顶级字段。 | +| **添加字段** | 从现有数值字段或常量创建计算数值字段。 | + +## 添加和管理转换 + +要添加转换,请转到**转换**选项卡,选择**添加**,然后在**添加转换**弹出窗口中选择转换。转换卡片会添加到管道中。 + +下图显示了列出可用转换的**添加转换**弹出窗口。 + +*转换选项卡旁边列出可用转换的添加转换弹出窗口* + +您可以按以下方式管理管道中的转换: + +- 更新转换卡片中的控件以编辑它。 +- 选择眼睛图标以隐藏或显示转换。隐藏的转换保留在管道中但被跳过。 +- 选择删除图标以删除转换。 +- 拖动转换卡片以更改管道顺序。 + +## 转换顺序 + +转换顺序很重要。管道从上到下运行,每个步骤使用前一步骤产生的结果。一个转换创建或删除的字段会影响后续转换可用的字段。 + +例如,以下管道过滤成功请求,按字节数排序,并仅保留最大的结果: + +1. **过滤**:`response` 等于 `200`。 +1. **排序**:`bytes`,降序。 +1. **限制**:`1`。 + +下表显示输入数据。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +下表显示结果。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | + +## 示例数据 + +以下示例使用基于 `opensearch_dashboards_sample_data_logs` 示例索引的小型结果表。 + +| `@timestamp` | `extension` | `response` | `bytes` | `machine.os` | `geo` | +| --- | --- | --- | --- | --- | --- | +| `2026-09-20T10:00:00Z` | `css` | `200` | `14074` | `win 8` | `{"src":"US","dest":"CN"}` | +| `2026-09-20T10:01:00Z` | `png` | `404` | `7911` | `osx` | `{"src":"IN","dest":"US"}` | +| `2026-09-20T10:02:00Z` | `js` | `200` | `1024` | `win xp` | `{"src":"US","dest":"GB"}` | +| `2026-09-20T10:03:00Z` | `css` | `503` | `2048` | `ios` | `{"src":"CN","dest":"US"}` | + +## 转换类型 + +以下部分描述每种转换并显示将其应用于示例数据的结果。 + +### 限制 + +使用**限制**仅保留结果开头的指定行数。 + +转换使用以下配置: + +- **行数**:`2` + +下表显示输入数据。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +下表显示结果。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | + +### 排序 + +使用**排序**按选定字段对行排序。 + +转换使用以下配置: + +- **字段**:`bytes` +- **顺序**:**降序** + +下表显示输入数据。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +下表显示结果。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `css` | `503` | `2048` | +| `js` | `200` | `1024` | + +### 过滤 + +使用**过滤**保留匹配条件的行。可用的运算符取决于所选字段类型。 + +转换使用以下配置: + +- **字段**:`response` +- **运算符**:**等于** +- **值**:`200` + +下表显示输入数据。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +下表显示结果。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `js` | `200` | `1024` | + +### 过滤字段 + +使用**过滤字段**包含或排除选定的字段。 + +转换使用以下配置: + +- **模式**:**包含** +- **字段**:`extension`、`response`、`bytes` + +下表显示输入数据。 + +| `@timestamp` | `extension` | `response` | `bytes` | `machine.os` | +| --- | --- | --- | --- | --- | +| `2026-09-20T10:00:00Z` | `css` | `200` | `14074` | `win 8` | +| `2026-09-20T10:01:00Z` | `png` | `404` | `7911` | `osx` | + +下表显示结果。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | + +### 转换字段类型 + +使用**转换字段类型**将选定字段值转换为另一种类型。支持的目标类型是字符串、数字、布尔和日期。 + +转换使用以下配置: + +- **字段**:`response` +- **目标类型**:**数字** + +下表显示输入数据。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `"200"` | `14074` | +| `png` | `"404"` | `7911` | + +下表显示结果。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | + +### 分组 + +使用**分组**按字段值分组行并为每组聚合其他字段。 + +转换使用以下配置: + +- **字段**:`extension` +- **聚合**:`bytes` 作为**总计**,`response` 作为**计数** + +下表显示输入数据。 + +| `extension` | `response` | `bytes` | +| --- | --- | --- | +| `css` | `200` | `14074` | +| `png` | `404` | `7911` | +| `js` | `200` | `1024` | +| `css` | `503` | `2048` | + +下表显示结果。 + +| `extension` | `total_bytes` | `count_response` | +| --- | --- | --- | +| `css` | `16122` | `2` | +| `png` | `7911` | `1` | +| `js` | `1024` | `1` | + +### 提取字段 + +使用**提取字段**将嵌套对象或 JSON 字符串字段展平为顶级字段。 + +转换使用以下配置: + +- **字段**:`geo` +- **格式**:**对象** +- **列前缀**:`geo_` + +下表显示输入数据。 + +| `extension` | `geo` | +| --- | --- | +| `css` | `{"src":"US","dest":"CN"}` | +| `png` | `{"src":"IN","dest":"US"}` | + +下表显示结果。 + +| `extension` | `geo` | `geo_src` | `geo_dest` | +| --- | --- | --- | --- | +| `css` | `{"src":"US","dest":"CN"}` | `US` | `CN` | +| `png` | `{"src":"IN","dest":"US"}` | `IN` | `US` | + +### 添加字段 + +使用**添加字段**创建计算数值字段。**添加字段**支持二元计算、一元计算和跨字段计算。 + +转换使用以下配置: + +- **模式**:**二元** +- **字段 1**:`bytes` +- **运算符**:`+` +- **字段 2**:自定义值 `100` +- **别名**:`bytes_with_overhead` + +下表显示输入数据。 + +| `extension` | `bytes` | +| --- | --- | +| `css` | `14074` | +| `png` | `7911` | +| `js` | `1024` | + +下表显示结果。 + +| `extension` | `bytes` | `bytes_with_overhead` | +| --- | --- | --- | +| `css` | `14074` | `14174` | +| `png` | `7911` | `8011` | +| `js` | `1024` | `1124` | diff --git a/i18n/zh/dashboards/visualize/visualization-editor/gauge-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/gauge-chart.md new file mode 100644 index 00000000..d4e80d11 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/gauge-chart.md @@ -0,0 +1,90 @@ +--- +title: 仪表图 +--- + +# 可视化编辑器中的仪表图 + +仪表图在半圆弧上显示单个数值。使用仪表图显示指标与定义的阈值或目标范围的比较情况。 + +## 创建仪表图 + +以下示例相互构建,从基本仪表开始逐步增加复杂性。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本仪表图 + +从一个返回单个数值聚合的查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | FIELDS AvgTicketPrice +``` + +运行此查询后,选择**仪表**作为图表类型。可视化自动应用**最后**计算将系列简化为单个值进行显示。编辑器映射字段如下: + +- **值**字段显示 `AvgTicketPrice` 字段(默认使用**最后**计算)。 + +结果是一个显示最后一个票价值的仪表,带有默认的绿色弧线,如下图所示。 + +*显示最后平均票价的初始仪表图* + +### 添加阈值 + +定义阈值断点以将仪表弧线分割成彩色范围,指示值的健康状态。 + +使用前面示例中的相同查询,在设置面板中打开**阈值**部分并添加阈值。例如: + +- 基础颜色:绿色(低于 500 的值) +- 500 处的阈值:黄色(中等价格范围) +- 800 处的阈值:红色(高价格范围) + +弧线现在显示彩色带——绿色到 500,黄色从 500 到 800,红色高于 800。启用**使用阈值颜色**将匹配的阈值颜色应用于显示的值文本和弧线,如下图所示。 + +*带有颜色编码阈值带的仪表图* + +### 自定义仪表刻度 + +要根据代表完整预期范围的固定刻度监控票价,请打开**标准选项**部分并设置: + +- **最小**:`500` +- **最大**:`1200` + +仪表现在始终跨越 500 到 1200,便于在拆分面板之间进行比较,如下图所示。 + +*带有自定义最小/最大刻度的仪表图* + +## 配置仪表图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置数据字段。 + +| 字段 | 描述 | +| --- | --- | +| **值** | 选择一个数值字段,其值使用配置的计算方法简化为单个数字。结果显示为仪表的当前值。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 仪表 + +| 设置 | 描述 | +| --- | --- | +| **使用阈值颜色** | 启用时,中心数值采用当前值所在阈值范围的颜色。 | +| **显示标题** | 在数值下方显示标签。默认为字段名称,但您可以用自定义文本覆盖它。 | +| **标题** | 启用**显示标题**时在值下方显示的自定义标题文本。如果留空,则使用字段名称。 | + +### 值选项 + +| 设置 | 描述 | +| --- | --- | +| **计算** | 确定如何将多个数据点简化为仪表上显示的单个值。支持的值:**最后 \***、**最后**、**第一 \***、**第一**、**最小**、**最大**、**平均**、**中位数**、**方差**、**计数**、**去重计数**、**总计**。有关更多信息,请参阅[值计算](/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations)。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/heatmap-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/heatmap-chart.md new file mode 100644 index 00000000..4a074b6c --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/heatmap-chart.md @@ -0,0 +1,111 @@ +--- +title: 热力图 +--- + +# 可视化编辑器中的热力图 + +热力图使用颜色表示数据集中值的大小。图中的每个单元格对应两个维度的组合,单元格的颜色强度反映与该组合关联的值。 + +## 创建热力图 + +以下示例相互构建,从基本热力图开始逐步增加复杂性。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本热力图 + +从一个按两个分类字段聚合数值指标的查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | where FlightDelay = true | stats avg(FlightDelayMin) as avg_delay by OriginWeather, DestWeather +``` + +运行此查询后,选择**热力图**作为图表类型。字段映射如下: + +- **X 轴**显示 `OriginWeather` 字段。 +- **Y 轴**显示 `DestWeather` 字段。 +- **值**显示 `avg_delay` 字段。 + +结果是一个彩色单元格网格,每个单元格代表特定出发地-目的地天气组合的平均航班延误分钟数。颜色较深的单元格表示值较高,如下图所示。 + +*显示按天气条件划分的平均航班延误分钟数的基本热力图* + +### 自定义颜色方案和刻度 + +为了更好地区分值,请更改颜色设置: + +1. 在**热力图**部分,将**颜色方案**更改为不同的调色板(例如**黄色到橙色**)以提高对比度。 +2. 启用**缩放到数据边界**以将颜色范围映射到数据的实际最小和最大值,而不是计算的边界。 +3. 更改**最大颜色数**以增加或减少颜色分箱的粒度,如下图所示。 + +*自定义颜色方案和刻度的热力图* + +### 启用标签 + +要在每个单元格内显示数值,请启用**显示标签**。如果单元格较窄,请启用**旋转**以倾斜标签以提高可读性,如下图所示。 + +*在单元格中显示值标签的热力图* + +## 配置热力图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择沿水平轴显示的分类字段。每个唯一值成为热力图网格中的一列。 | +| **Y 轴** | 选择沿垂直轴显示的分类字段。每个唯一值成为热力图网格中的一行。 | +| **值** | 选择一个数值字段,其大小决定每个单元格的颜色强度。每个单元格代表一个 X 轴类别和一个 Y 轴类别的交集。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 热力图 + +使用以下设置自定义热力图的外观。 + +| 设置 | 描述 | +| --- | --- | +| **使用阈值颜色** | 启用时,单元格颜色由阈值范围而不是所选颜色方案决定。 | +| **颜色方案** | 控制用于表示跨单元格值的颜色主题。支持的值:**绿色**、**蓝色**、**红色**、**灰色**、**绿色到蓝色**、**黄色到橙色**。 | +| **反转方案** | 启用时,颜色映射反转:较高的值用较浅的颜色表示,较低的值用较深的颜色表示。 | +| **颜色刻度** | 定义数据值如何映射到颜色。支持的值:**线性**、**对数**、**平方根**。 | +| **缩放到数据边界** | 启用时,从数据集计算最小和最大值并相应地映射颜色刻度。 | +| **百分比模式** | 启用时,值转换为百分比,颜色刻度在 0 和 1 之间归一化。 | +| **最大颜色数** | 控制颜色刻度中使用的最大离散颜色分箱数。 | +| **显示标签** | 启用时,在每个单元格内显示数值作为标签。 | + +启用**显示标签**时可用以下设置。 + +| 设置 | 描述 | +| --- | --- | +| **旋转** | 启用时,将值标签旋转 45 度以在窄单元格中提高可读性。 | +| **覆盖自动颜色** | 启用时,设置自定义标签颜色。 | +| **颜色** | 启用**覆盖自动颜色**时设置自定义标签颜色。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀和小数精度的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 图例 + +图例总结了图表中使用的视觉颜色编码。 + +| 设置 | 描述 | +| --- | --- | +| **显示图例** | 显示或隐藏图例。 | +| **位置** | 控制图例相对于图表的显示位置。支持的值:**左**、**右**、**上**、**下**。 | + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/histogram-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/histogram-chart.md new file mode 100644 index 00000000..e2bdb792 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/histogram-chart.md @@ -0,0 +1,78 @@ +--- +title: 直方图 +--- + +# 可视化编辑器中的直方图 + +直方图通过将值分组到分箱(桶)中并以垂直条形显示每个分箱中值的计数来显示数值字段的分布。 + +## 创建直方图 + +以下示例演示基本的直方图可视化。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本直方图 + +从一个按数值字段分组计数值的查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by AvgTicketPrice +``` + +运行此查询后,选择**直方图**作为图表类型。编辑器映射字段如下: + +- **X 轴**显示 `AvgTicketPrice` 字段。 + +结果是一个显示票价分布的直方图,如下图所示。 + +*显示平均票价分布的直方图* + +## 配置直方图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择要沿水平轴分布到分桶中的数值字段。 | +| **Y 轴** | 选择垂直轴的数值字段。如果留空,图表显示每个分桶中值的计数。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 分桶 + +以下设置控制数据如何分组到分箱中。 + +| 设置 | 描述 | +| --- | --- | +| **分桶大小** | 设置每个分箱的宽度。输入数值或留为**自动**让编辑器计算适当的大小。 | +| **分桶数量** | 设置要显示的最大分箱数。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 直方图 + +使用以下设置自定义直方图的外观。 + +| 设置 | 描述 | +| --- | --- | +| **使用阈值颜色** | 启用时,根据阈值范围为条形着色。 | +| **显示边框** | 启用时,在每个条形周围添加边框。 | + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/index.md b/i18n/zh/dashboards/visualize/visualization-editor/index.md new file mode 100644 index 00000000..ae529756 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/index.md @@ -0,0 +1,152 @@ +--- +title: 使用查询创建可视化 +--- + +# 使用查询创建可视化 + +_可视化编辑器_允许您通过编写[管道处理语言(PPL)](/sql-and-ppl/ppl/)或 Prometheus 查询语言(PromQL)查询来创建可视化。编辑器会自动将查询结果字段映射到图表坐标轴,并根据数据的形状建议图表类型。要从仪表板打开可视化编辑器,请选择**新建** > **添加可视化**。 + +## 先决条件 + +在使用可视化编辑器之前,OpenSearch Dashboards 管理员必须完成以下设置步骤。 + +### 步骤 1:启用必需的设置 + +除了[启用工作区](/dashboards/workspace/workspace#enabling-workspaces)外,还要将以下设置添加到您的 `opensearch_dashboards.yml` 文件中: + +```yaml +explore.enabled: true +``` + +更新配置文件后,重新启动 OpenSearch Dashboards 以使更改生效。 + +### 步骤 2:创建工作区 + +可视化编辑器需要工作区。如果启用了已保存对象权限,只有仪表板管理员可以创建工作区,其他用户必须由其所有者添加到现有工作区。有关更多信息,请参阅[配置仪表板管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)。 + +要创建工作区,请按照以下步骤操作: + +1. 导航到 OpenSearch Dashboards 主页。 +1. 选择**创建工作区**。 +1. 输入工作区名称。 +1. 选择**分析(所有功能)**用例。 +1. 选择**创建工作区**。 + +有关更多信息,请参阅[创建工作区](/dashboards/workspace/create-workspace)。 + +### 步骤 3:配置数据源 + +可视化编辑器需要与您的工作区关联的数据集: + +- 对于 PPL,配置索引模式: + 1. 在工作区内,转到**索引模式**(在**管理**中)。 + 1. 选择**创建索引模式**。 + 1. 输入索引名称(例如,`opensearch_dashboards_sample_data_logs`)。 + 1. 选择**下一步**。 + 1. 选择时间字段(例如,`@timestamp`)。 + 1. 选择**创建索引模式**。 + + 有关更多信息,请参阅[索引模式](/dashboards/management/index-patterns)。 + +- 对于 PromQL(Prometheus 数据源),为您的工作区配置 Prometheus 数据源连接。有关更多信息,请参阅[将 Prometheus 连接到 OpenSearch](/dashboards/management/connect-prometheus)。 + +### 步骤 4(可选):安装示例数据 + +本文档中的示例使用 OpenSearch Dashboards 示例数据集。要安装示例数据集,请按照以下步骤操作: + +1. 在左侧导航中,展开**管理工作区**并选择**示例数据**。 +1. 在**示例日志数据**图块中选择**添加数据**按钮以及您想要添加的任何其他数据。本节中的示例使用示例日志数据。 + +有关更多信息,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 导航可视化编辑器 UI + +下图显示了可视化编辑器的主要组件。 + +*带有标注的可视化编辑器界面* + +- _时间过滤器_(A)选择查询结果的时间范围。 +- _更新按钮_(B)运行或刷新查询。 +- _查询编辑器_(C)包含查询文本或,对于 PromQL,查询构建器。 +- _已保存查询_下拉列表(D)保存和加载可重用的查询。 +- _配置面板_(E)包含图表类型选择器、字段映射和样式设置。 + +## 创建可视化 + +要打开可视化编辑器,请使用以下方法之一: + +- 从左侧导航中,选择**资源管理器** > **日志**,然后选择**可视化**选项卡。 +- 从仪表板中,选择添加面板图标,然后选择**添加可视化**。 + +要创建可视化,请按照以下步骤操作: + +1. 从查询栏中的数据集选择器中选择数据集(例如,**opensearch_dashboards_sample_data_logs**)。 +1. 在查询编辑器中编写 PPL 查询。如果您选择了数据集,请以管道字符(`|`)开始查询。否则,请使用 `source =` 显式指定源。例如,以下查询按小时计算日志事件数: + + ```sql + source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1h) + ``` + + 如果 `opensearch_dashboards_sample_data_logs` 已选择为数据集,您可以省略 `source`: + + ```sql + | stats count() by SPAN(@timestamp, 1h) + ``` + +1. 选择**更新**或按 **Enter** 运行查询。 +1. 编辑器会根据您的查询结果自动选择图表类型并将字段映射到坐标轴。要更改图表类型,请使用**可视化类型**下拉列表。 +1. 要自定义字段映射,请使用**字段**面板。 + +## 使用仪表板变量 + +您可以使用仪表板变量创建动态、交互式可视化。变量允许您在过滤器值、指标、时间间隔和聚合函数之间切换,而无需编辑查询。使用 `$variableName` 或 `${variableName}` 语法在 PPL 或 PromQL 查询中引用变量。 + +有关更多信息,请参阅[仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/)。 + +## 保存可视化 + +要保存可视化,请选择**保存**(如果您从仪表板打开编辑器,则选择**保存并返回**)。输入可视化的名称并选择**保存**。 + +如果您从仪表板打开可视化编辑器,保存后可视化会自动添加到该仪表板。如果您从**资源管理器** > **日志**创建可视化,请先保存它,然后手动将其添加到仪表板。 + +## 保存和重用查询 + +要保存 PPL 查询以供重用,请选择**已保存查询** > **保存查询**。在对话框中,配置以下选项。 + +| 选项 | 描述 | +| --- | --- | +| **另存为新查询** | 选中后,将查询保存为新条目,而不是覆盖现有条目。 | +| **名称** | 已保存查询的名称。 | +| **描述** | 查询的可选描述。 | +| **包含过滤器** | 启用后,将当前应用的过滤器与查询一起保存。 | +| **包含时间过滤器** | 启用后,将当前时间范围与查询一起保存。 | + +选择**保存更改**以保存查询。 + +要加载先前保存的查询,请选择**已保存查询** > **打开查询**,然后从列表中选择查询并选择**打开查询**按钮。保存的查询将加载到查询编辑器中。 + +## 可视化类型 + +有关支持的图表类型及其预期数据形状的列表,请参阅[可视化类型](/dashboards/visualize/visualization-editor/viz-types)。 + +## 配置可视化 + +共享配置选项(字段、拆分、坐标轴、工具提示、图例、阈值等)适用于多种可视化类型。有关详细信息,请参阅[在可视化编辑器中配置可视化](/dashboards/visualize/visualization-editor/configuring-visualizations/)。 + +## 查询面板 + +使用查询面板选择查询语言和数据集、编写或构建查询并运行它以生成可视化。查询面板支持 PPL、PromQL 和(启用后)SQL。对于 PromQL,查询面板还提供**构建器**和**代码**模式、多个查询行以及每个查询和共享查询选项。 + +有关详细信息,请参阅[查询面板](/dashboards/visualize/visualization-editor/query-panel)。 + +## 数据转换 + +数据转换在渲染可视化之前修改查询结果。使用转换来重塑、过滤、排序、计算或汇总数据,而不更改原始查询。有关详细信息,请参阅[数据转换](/dashboards/visualize/visualization-editor/data-transformation/)。 + +## 相关文档 + +- [PPL](/sql-and-ppl/ppl/) +- [仪表板变量](/dashboards/visualize/visualization-editor/dashboard-variables/) +- [创建仪表板](/dashboards/dashboard/) +- [索引模式](/dashboards/management/index-patterns) +- [将 Prometheus 连接到 OpenSearch](/dashboards/management/connect-prometheus) diff --git a/i18n/zh/dashboards/visualize/visualization-editor/line-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/line-chart.md new file mode 100644 index 00000000..f0f0a7b9 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/line-chart.md @@ -0,0 +1,125 @@ +--- +title: 折线图 +--- + +# 可视化编辑器中的折线图 + +折线图将数据点用线连接绘制。使用折线图显示趋势和随时间的变化。在同一时间轴上比较多个系列,并使用辅助 Y 轴关联具有不同刻度的指标。 + +## 创建折线图 + +以下示例相互构建,从基本图表开始逐步增加复杂性。它们使用示例 Web 日志数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本折线图 + +从一个按时间统计事件数量的聚合查询开始: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1h) +``` + +运行此查询后,可视化编辑器会自动选择**折线**图并映射字段: + +- **X 轴**显示 `SPAN(@timestamp, 1h)` 字段。 +- **Y 轴**显示 `count()` 字段。 + +结果是一条显示每小时事件数量的单线,如下图所示。 + +*显示每小时事件数量的基本折线图* + +### 多系列折线图 + +在查询中添加第三个维度,按类别将数据拆分为多个系列: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by SPAN(@timestamp, 1h), response +``` + +此查询按时间和 `response` 字段(HTTP 状态码)分组计数。选择 `response` 作为**颜色**字段,为每个状态码值(例如 200、404、503)渲染单独的线条。 + +结果是一个多系列折线图,每个 HTTP 响应码以不同颜色显示,如下图所示。 + +*按 HTTP 响应码显示计数的多系列折线图* + +### 多个 Y 轴字段 + +当查询计算多个指标时,您可以将它们全部绘制在同一图表上: + +```sql +source = opensearch_dashboards_sample_data_logs | stats avg(bytes), max(bytes) by SPAN(@timestamp, 1h) +``` + +此查询返回两个数值字段:`avg(bytes)` 和 `max(bytes)`。在 **Y 轴**字段列表中选择 `avg(bytes)` 和 `max(bytes)`,将它们作为同一刻度上的单独线条绘制。 + +结果显示随时间变化的平均和最大字节值,如下图所示。 + +*两个 Y 轴指标绘制在一起的折线图* + +### 辅助 Y 轴(双轴) + +当两个指标的刻度差异很大时,将它们绘制在同一轴上可能使其中一个看起来很平坦。使用 **Y 轴(第二)**字段为第二个指标在图表右侧提供自己的刻度。 + +使用前面示例中的相同查询: + +```sql +source = opensearch_dashboards_sample_data_logs | stats avg(bytes), max(bytes) by SPAN(@timestamp, 1h) +``` + +这次,将 `avg(bytes)` 分配给 **Y 轴**,将 `max(bytes)` 分配给 **Y 轴(第二)**。 + +结果是一个双轴图表。左轴缩放到 `avg(bytes)`,右轴缩放到 `max(bytes)`,如下图所示。 + +*avg(bytes) 作为线条和 max(bytes) 作为条形的双轴图表* + +## 配置折线图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择日期或数字字段作为水平轴。此字段定义数据绘制的分桶(例如 `SPAN(@timestamp, 1h)`)。 | +| **Y 轴** | 选择一个或多个数字字段作为单独的线条绘制。当选择多个字段时,每个字段在同一刻度上渲染为自己的线条。 | +| **Y 轴(第二)** | 选择一个数值字段叠加到具有自己刻度的辅助轴上。当两个指标具有不同的单位或量级时使用此选项。 | +| **颜色** | 选择分类字段将数据拆分为多个系列,每个系列以不同颜色渲染。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 线条 + +下表描述了线条样式设置。 + +| 设置 | 描述 | +| --- | --- | +| **线条样式** | 控制图表是显示带点的线条(**默认**)、仅线条(**仅线条**)还是仅点(**仅点**)。 | +| **线条虚线样式** | 将线条图案设置为**实线**、**虚线**或**点线**。 | +| **插值** | 确定点的连接方式。**直线**在点之间绘制直线。**平滑**应用曲线。**阶梯**创建阶梯图案,适用于在离散间隔变化的数据。 | +| **线条宽度** | 设置线条的粗细(像素)。支持 1-10 范围内的值。 | +| **点大小** | 设置数据点的大小。此设置在显示点时可用。 | +| **显示值** | 在图表上显示值标签。 | +| **显示当前时间标记** | 显示当前时间的垂直标记。此设置仅在 X 轴使用日期字段时可用。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 图例 + +有关配置图例的信息,请参阅[图例](/dashboards/visualize/visualization-editor/configuring-visualizations/#legend)。 + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/metric-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/metric-chart.md new file mode 100644 index 00000000..60fe2b08 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/metric-chart.md @@ -0,0 +1,74 @@ +--- +title: 指标图 +--- + +# 可视化编辑器中的指标图 + +指标图突出显示单个数值。使用指标图显示关键绩效指标(KPI)或汇总统计数据。 + +## 创建指标图 + +以下示例演示基本的指标可视化。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本指标图 + +从一个返回数值字段的查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | FIELDS AvgTicketPrice +``` + +运行此查询后,选择**指标**作为图表类型。编辑器映射字段如下: + +- **值**字段显示 `AvgTicketPrice` 字段(默认使用**最后**计算)。 + +结果是一个显示最后一个票价值的大数字,如下图所示。 + +*显示最后平均票价的指标图* + +## 配置指标图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置数据字段。 + +| 字段 | 描述 | +| --- | --- | +| **值** | 选择一个数值字段显示为指标值。该字段使用配置的计算方法简化为单个数字。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 指标 + +| 设置 | 描述 | +| --- | --- | +| **文本显示** | 控制值旁边显示的文本。支持的值:**仅值**、**仅名称**、**值和名称**、**无**。 | +| **颜色模式** | 控制阈值颜色如何应用于指标。支持的值:**无**(无颜色)、**值**(为值文本着色)、**背景渐变**(应用渐变背景)、**背景纯色**(应用纯色背景)。 | +| **显示百分比** | 启用时,将值显示为最大值的百分比。 | +| **使用阈值颜色** | 启用时,根据当前值将阈值颜色应用于指标。 | + +### 值选项 + +| 设置 | 描述 | +| --- | --- | +| **计算** | 确定如何将多个数据点简化为单个值。支持的值:**最后 \***、**最后**、**第一 \***、**第一**、**最小**、**最大**、**中位数**、**方差**、**去重计数**、**计数**、**总计**。有关更多信息,请参阅[值计算](/dashboards/visualize/visualization-editor/configuring-visualizations/value-calculations)。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀和小数精度的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 文本大小 + +| 设置 | 描述 | +| --- | --- | +| **值大小** | 控制显示值的字体大小。 | +| **标题大小** | 控制指标标题的字体大小。 | +| **百分比大小** | 控制百分比显示的字体大小(启用**显示百分比**时)。 | diff --git a/i18n/zh/dashboards/visualize/visualization-editor/pie-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/pie-chart.md new file mode 100644 index 00000000..1efb1ea8 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/pie-chart.md @@ -0,0 +1,88 @@ +--- +title: 饼图 +--- + +# 可视化编辑器中的饼图 + +饼图将数据显示为圆形的比例扇区。使用饼图显示部分与整体的关系。 + +## 创建饼图 + +以下示例相互构建,从基本图表开始逐步添加自定义设置。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本饼图 + +从一个按类别统计事件数量的聚合查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | stats count() by Carrier +``` + +运行此查询后,可视化编辑器会自动映射字段: + +- **大小**显示 `count()` 字段。 +- **颜色**显示 `Carrier` 字段。 + +默认渲染为**环形**图。每个航空公司显示为与其事件数量成比例的彩色扇区,如下图所示。 + +*按航空公司显示计数的环形图* + +### 自定义饼图 + +打开**饼图**设置面板并配置以下选项: + +1. 将**显示为**从**环形**更改为**饼图**以渲染没有中心孔的完整圆形。 +1. 启用**显示值**以在每个扇区上显示计数。 +1. 启用**显示标签**以在每个扇区旁边显示航空公司名称。 +1. 将**截断后**设置为 `300` 以显示较长的标签文本,如下图所示。 + +*启用饼图模式、显示值和显示标签的饼图设置* + +结果是一个完整的饼图,每个扇区上都显示类别标签和数值,如下图所示。 + +*显示标签和值的饼图* + +## 配置饼图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置数据字段。 + +| 字段 | 描述 | +| --- | --- | +| **大小** | 选择一个数值字段来确定每个扇区的大小。例如,`count()` 使每个扇区与该类别中的事件数量成比例。 | +| **颜色** | 选择一个分类字段将数据拆分为单独的扇区,每个扇区以不同颜色渲染。例如,使用 `Carrier` 字段为每个航空公司显示一个扇区。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 饼图 + +下表描述了饼图设置。 + +| 设置 | 描述 | +| --- | --- | +| **显示为** | 控制图表渲染为完整饼图还是**环形**(环形)形状。**环形**是默认值。 | +| **显示值** | 启用时,在图表上显示每个扇区的数值。 | +| **显示标签** | 启用时,在图表上显示每个扇区的类别标签。 | +| **截断后** | 设置标签截断前的最大宽度(像素)。仅在启用**显示标签**时可见。 | + +### 标准选项 + +有关配置单位、单位后缀和小数精度的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 图例 + +图例总结了图表中使用的视觉颜色编码。 + +| 设置 | 描述 | +| --- | --- | +| **显示图例** | 显示或隐藏图例。 | +| **位置** | 控制图例相对于图表的显示位置。支持的值:**左**、**右**、**上**、**下**。 | + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/query-panel.md b/i18n/zh/dashboards/visualize/visualization-editor/query-panel.md new file mode 100644 index 00000000..1ef1b6ce --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/query-panel.md @@ -0,0 +1,129 @@ +--- +title: 查询面板 +--- + +# 查询面板 + +使用查询面板选择查询语言和数据集、编写或构建查询并运行它以生成可视化数据。 + +查询面板支持管道处理语言(PPL)、Prometheus 查询语言(PromQL)以及启用后的 SQL。要启用 SQL,请将以下设置添加到您的 `opensearch_dashboards.yml` 文件中: + +```yaml +explore.sqlSupport.enabled: true +``` + +当为所选数据集启用提示模式时,AI 查询生成可用。 + +## 查询面板控件 + +查询面板包括以下控件。 + +| 控件 | 描述 | +| --- | --- | +| **语言切换** | 在 PPL、PromQL、SQL 和 AI(如果可用)之间切换编辑器。 | +| **数据集选择器** | 选择编辑器查询的数据集或数据源。可用数据集取决于所选语言。 | +| **已保存查询** | 保存当前查询或加载先前保存的查询。 | +| **查询编辑器** | 提供文本编辑器,或在选择 PromQL 时提供 PromQL 编辑器或构建器。 | + +下图显示了带有语言切换、数据集选择器、已保存查询菜单和查询编辑器的查询面板。 + +*显示语言切换、数据集选择器、已保存查询菜单和查询编辑器的查询面板* + +## 选择查询语言 + +使用语言切换选择查询语言。所选语言决定可用的数据集和显示的编辑器功能。 + +| 语言 | 描述 | +| --- | --- | +| **PPL** | 使用管道处理语言查询 OpenSearch 数据集。 | +| **PromQL** | 查询 Prometheus 数据源并显示 PromQL 多查询编辑器。 | +| **SQL** | 使用 SQL 查询 OpenSearch 数据集。此选项仅在 `explore.sqlSupport.enabled` 设置为 `true` 时显示。 | +| **AI** | 从自然语言提示生成查询。此选项仅在提示模式可用时显示。 | + +## 选择数据集 + +使用数据集选择器选择可视化编辑器查询的数据。数据集可用性取决于所选查询语言: + +- **PPL** 和 **SQL** 使用 OpenSearch 数据集,如索引和索引模式。 +- **PromQL** 使用 Prometheus 数据集。 + +## 编写 PPL 查询 + +选择数据集后,您可以编写 PPL 查询。可视化编辑器使用所选数据集作为查询源。 + +例如,如果选择了 `opensearch_dashboards_sample_data_logs`,您可以输入以下查询: + +```sql +| stats count() by response +``` + +您也可以显式包含源: + +```sql +source = opensearch_dashboards_sample_data_logs | stats count() by response +``` + +## 编写 PromQL 查询 + +当选择 **PromQL** 时,编辑器显示多查询编辑器。每个查询行可以在**构建器**模式或**代码**模式下编写。 + +下图显示了 PromQL 多查询编辑器。 + +*一个查询行处于构建器模式的 PromQL 多查询编辑器* + +使用**构建器**模式从指标名称、标签过滤器和操作构建 PromQL 查询。使用**代码**模式直接编写 PromQL。某些代码查询无法在**构建器**模式中表示,因此对于复杂查询可能无法切换回**构建器**模式。 + +以下示例使用**构建器**模式编写 PromQL 查询: + +```prometheus +sum(rate(go_gc_heap_allocs_bytes_total[50060s])) +``` + +下图显示了在**构建器**模式中从 `sum` 聚合、带有 `50060s` 窗口的 `rate` 函数和 `go_gc_heap_allocs_bytes_total` 指标构建的相同查询。 + +*在构建器模式中从 sum 聚合、rate 函数和指标名称构建的 PromQL 查询,生成的查询显示在控件下方* + +您可以按以下方式管理 PromQL 查询行: + +- 选择**添加查询**以添加另一个 PromQL 查询行。 +- 选择删除图标以删除查询行。 +- 拖动查询行以重新排序。 +- 选择**更新**以运行查询。在**代码**模式下,您也可以按 Command+Enter(macOS)或 Ctrl+Enter(Windows 和 Linux)。 + +## PromQL 查询选项 + +PromQL 为每个查询行提供单独的选项,并为所有行提供共享选项。要配置单个查询行的选项,请选择行末尾的齿轮图标。要配置所有行共享的选项,请选择**查询选项**。 + +下图显示了 PromQL 查询行的单独查询选项。 + +*PromQL 查询行的单独查询选项,包括系列名称和最小步长,以及估计的步长和速率窗口* + +### 系列名称 + +使用**系列名称**自定义显示的系列名称。您可以使用双大括号引用指标标签。 + +例如,输入 `{{job}}` 以按其 job 标签命名每个系列,或输入 `{{job}}-{{instance}}` 以组合多个标签。 + +以下条形图将**系列名称**设置为 `{{operation}}`,因此图例按其 operation 标签命名每个系列,`Read` 和 `Write`。 + +*图例按其 operation 标签命名每个系列 Read 和 Write 的条形图,系列名称选项在查询行中设置* + +### 最小步长 + +使用**最小步长**设置 PromQL 查询步长的下限。输入带单位的持续时间,如 `15s`、`1m` 或 `2h`。将此值与您的 Prometheus 抓取间隔匹配。选项面板显示生成的步长(`$__interval`)和速率窗口(`$__rate_interval`)作为估计值;运行查询以确认值。 + +### 最大数据点数 + +使用**最大数据点数**设置每个系列返回的最大点数。此选项由所有 PromQL 查询行共享。将此设置留空以使用自动值。 + +下图显示了共享**查询选项**面板中的**最大数据点数**,自动值为 `1440`。 + +*共享查询选项面板中最大数据点数设置为自动值 1440* + +## 保存和重用查询 + +要保存查询以供重用,请选择**已保存查询** > **保存查询**。要加载已保存的查询,请选择**已保存查询** > **打开查询**,然后选择要加载的查询。 + +下图显示了带有**保存查询**和**打开查询**选项的**已保存查询**菜单。 + +*展开的已保存查询菜单,显示保存查询和打开查询选项* diff --git a/i18n/zh/dashboards/visualize/visualization-editor/scatter-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/scatter-chart.md new file mode 100644 index 00000000..d0ce1329 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/scatter-chart.md @@ -0,0 +1,118 @@ +--- +title: 散点图 +--- + +# 可视化编辑器中的散点图 + +散点图可视化两个数值变量之间的关系。图表上的每个点代表数据集中的一个观测值,其位置由两个变量的值决定。您可以按分类字段拆分数据,以比较不同组在相同维度上的分布情况。 + +## 创建散点图 + +以下示例相互构建,从基本的双变量散点图开始逐步添加维度。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本散点图 + +从一个返回两个数值字段的查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | fields AvgTicketPrice, DistanceMiles +``` + +运行此查询后,选择**散点图**作为图表类型。字段映射如下: + +- **X 轴**显示 `AvgTicketPrice` 字段。 +- **Y 轴**显示 `DistanceMiles` 字段。 + +结果是一个显示票价与飞行距离关系的散点图。每个点代表一次航班,如下图所示。 + +*显示平均航班价格与距离比较的基本散点图* + +### 使用阈值 + +要应用阈值,请在**散点图**部分启用**使用阈值颜色**。然后打开**阈值**部分并添加 `6000` 的阈值以突出显示长途航班,如下图所示。 + +*在 6000 处设置阈值以突出显示长途航班的散点图* + +有关更多信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 添加颜色维度 + +添加分类字段将数据点拆分为颜色编码的组: + +```sql +source = opensearch_dashboards_sample_data_flights | fields AvgTicketPrice, DistanceMiles, DestWeather +``` + +此查询返回两个数值字段:`AvgTicketPrice` 和 `DistanceMiles`。选择 `DestWeather` 作为**颜色**字段。 + +结果是一个将点拆分为颜色编码组的散点图——每种天气条件以不同颜色渲染,如下图所示。 + +*带有颜色编码天气类别的散点图* + +### 添加大小维度 + +添加第三个数值字段来控制点的大小,创建气泡图: + +```sql +source = opensearch_dashboards_sample_data_flights | fields AvgTicketPrice, DistanceMiles, DestWeather, FlightDelayMin +``` + +此查询返回三个数值字段:`AvgTicketPrice`、`DistanceMiles` 和 `FlightDelayMin`。选择 `DestWeather` 作为**颜色**字段并将 `FlightDelayMin` 映射到**大小**字段。 + +点现在大小不同——较大的气泡代表较长的延误。每种颜色仍然代表一种天气条件,使得可以识别某些天气类型是否与较高的价格和较长的延误相关,如下图所示。 + +*大小代表航班延误分钟数的散点图* + +## 配置散点图 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 配置 | 字段 | 描述 | +| :---| :---| :---| +| **两个数值** | X 轴(数值),Y 轴(数值) | 选择两个数值字段以显示两个数值变量之间关系的数据点。 | +| **两个数值 + 一个分类** | X 轴(数值),Y 轴(数值),颜色(分类) | 选择两个数值字段和一个分类颜色字段以显示拆分为颜色编码组的数据点。 | +| **三个数值 + 一个分类** | X 轴(数值),Y 轴(数值),大小(数值),颜色(分类) | 选择三个数值字段和一个分类颜色字段以显示颜色指示类别且第三个数值字段控制点大小的数据点。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 散点图 + +使用以下设置自定义散点图的外观。 + +| 设置 | 描述 | +| :---| :---| +| **点大小** | 控制未映射大小字段时数据点的默认大小。 | +| **形状** | 控制每个数据点的形状。支持的值:**圆形**、**方形**、**菱形**、**十字**。 | +| **填充** | 启用时,数据点填充颜色。禁用时,仅渲染轮廓。 | +| **角度** | 控制每个数据点的显示角度(度)。支持 0-360 范围内的值。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 标准选项 + +有关配置单位、单位后缀、小数精度以及最小和最大值的信息,请参阅[标准选项](/dashboards/visualize/visualization-editor/configuring-visualizations/standard-options)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 图例 + +图例总结了图表中使用的视觉颜色编码。 + +| 设置 | 描述 | +| :---| :---| +| **显示图例** | 显示或隐藏图例。 | +| **位置** | 控制图例相对于图表的显示位置。支持的值:**左**、**右**、**上**、**下**。 | + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/state-timeline-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/state-timeline-chart.md new file mode 100644 index 00000000..7190bac8 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/state-timeline-chart.md @@ -0,0 +1,147 @@ +--- +title: 状态时间线 +--- + +# 可视化编辑器中的状态时间线 + +状态时间线显示一系列代表状态随时间变化的水平条形。每个条形(称为状态区域)代表特定状态,其长度表示该状态的持续时间。 + +## 创建状态时间线 + +以下示例相互构建,从基本时间线开始逐步增加复杂性。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 单类别状态时间线 + +从一个返回时间字段和状态字段的查询开始: + +```sql +source = opensearch_dashboards_sample_data_logs | fields timestamp, response +``` + +运行此查询后,选择**状态时间线**作为图表类型。字段映射如下: + +- **X 轴**显示 `timestamp` 字段。 +- **颜色**显示 `response` 字段。 + +结果是一行彩色段,每个段代表记录特定响应状态码的时间段,如下图所示。 + +*显示请求随时间变化的基本状态时间线* + +### 应用值映射 + +使用值映射为特定状态值分配自定义标签和颜色。例如,将 HTTP 响应码分类为有意义的组: + +1. 在**值映射**部分,选择**编辑值映射**。 +1. 选择**添加新映射**并选择**值**作为映射类型。 +1. 在**值**字段中输入 `200`。在**显示文本**字段中输入 `成功`。选择绿色。 +1. 对 `404` 重复,标签为 `错误`,颜色为橙色。 +1. 对 `503` 重复,标签为 `错误`,颜色为红色,如下图所示,然后选择**保存**。 + +或者,选择**范围**作为映射类型以将连续值分组到区间中。例如,将 [400, 600) 范围内的所有状态码映射为红色显示"错误"。 + +*值映射选项* + +时间线现在为每个数据值显示用户配置的标签,并使用一致的颜色——绿色表示成功响应,红色表示错误,如下图所示。 + +*应用值映射的状态时间线* + +### 处理数据间隙 + +在状态时间线中,每个数据点的 `timestamp` 作为状态区域的开始时间,下一个数据点的 `timestamp` 标记其结束。当数据有间隙(时间戳之间缺少数据点)时,使用**断开值**或**连接空值**设置来控制这些间隙的可视化方式。 + +::: info NOTE +您一次只能应用**断开值**和**连接空值**中的一个。 +::: + +以下示例显示设置**断开值**阈值的效果: + +*带有断开阈值设置的状态时间线* + +### 多类别状态时间线 + +添加分类分组字段以显示多行状态时间线: + +```sql +source = opensearch_dashboards_sample_data_logs | fields timestamp, request, response +``` + +运行此查询后,选择**状态时间线**作为图表类型。字段映射如下: + +- **X 轴**显示 `timestamp` 字段。 +- **Y 轴**显示 `request` 字段。 +- **颜色**字段显示 `response` 字段。 + +结果显示每个请求路径随时间的响应状态,便于识别哪些端点经常出现不稳定,如下图所示。 + +*按请求分组的状态时间线* + +## 配置状态时间线 + +您可以在配置面板中配置以下设置。 + +### 字段 + +在**字段**部分,配置每个轴上显示的字段。 + +| 字段 | 描述 | +| --- | --- | +| **X 轴** | 选择日期字段作为水平轴。每个数据点的时间戳作为状态区域的开始时间。 | +| **Y 轴** | 选择分类字段将状态时间线分组为单独的行。每个唯一值渲染为自己的行。对于单类别时间线是可选的。 | +| **颜色** | 选择分类或数值字段来定义每个时间点的状态。分类字段表示离散状态(如 `running`、`stopped` 或 `degraded`)。当每个值对应不同状态时,数值字段可以表示状态(例如 HTTP 状态码 200、404、503)。对于连续数值,使用[值映射](#value-mappings)将范围定义为命名状态。 | + +### 拆分 + +在**拆分方式**下拉列表中,选择一个字段按值将图表拆分为单独的元素。有关更多信息,请参阅[拆分](/dashboards/visualize/visualization-editor/configuring-visualizations/#split)。 + +### 值映射 + +值映射用自定义标签和颜色替换原始数据值。可用以下映射类型。 + +**值映射**:将特定值(数值或分类)映射到自定义显示文本和颜色。例如,将 HTTP 状态码 `200` 映射为绿色显示"成功",将 `503` 映射为红色显示"错误"。 + +**范围映射**:将数值范围映射到自定义显示文本和颜色。例如,将 [0, 300) 范围映射为显示"低",将 [300, 800) 映射为显示"中"。 + +每个映射条目具有以下选项。 + +| 设置 | 描述 | +| --- | --- | +| **值/范围** | 要匹配的目标值或数值范围。对于值映射,输入特定值。对于范围映射,定义开始和结束值(包含开始,不包含结束)。 | +| **显示文本** | 代替原始值显示的标签。如果留空,则显示原始值。 | +| **颜色** | 映射值的自定义颜色。如果未定义,则自动分配颜色。 | + +有关完整示例,请参阅[应用值映射](#applying-value-mappings)。 + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 坐标轴 + +X 轴和 Y 轴共享相同的配置选项。有关更多信息,请参阅[坐标轴](/dashboards/visualize/visualization-editor/configuring-visualizations/#axes)。 + +### 状态时间线 + +使用以下设置自定义状态时间线的外观和行为。 + +| 设置 | 描述 | +| --- | --- | +| **使用阈值颜色** | 启用时,状态区域颜色由阈值范围而不是默认或映射颜色决定。 | +| **显示显示文本** | 启用且配置了带显示文本的值映射时,映射的文本显示在每个状态区域内。禁用时,不显示文本。 | +| **行高** | 控制每个状态条的高度。值 0 产生最小条宽,1 产生最大条宽。 | +| **断开值** | 控制当间隙超过指定持续时间时是否视觉断开状态区域。**从不**保持所有区域连接。**阈值**在数据点之间的间隙超过配置的阈值时断开区域。 | +| **阈值(断开)** | 设置断开值的持续时间阈值。如果连续数据点之间的间隙超过此阈值,条形将渲染为单独的断开区域。指定为持续时间(例如 `1h` 或 `30m`)。 | +| **连接空值** | 控制空值(数据中的间隙)在图表上的显示方式。**从不**使间隙可见。**阈值**仅在间隙在配置的阈值内时连接。 | +| **阈值(连接)** | 设置连接空值的持续时间阈值。如果数据点之间的间隙在此阈值内,则连接点,弥合间隙。指定为持续时间(例如 `1h` 或 `30m`)。 | + +### 图例 + +图例总结了图表中使用的视觉颜色编码。 + +| 设置 | 描述 | +| --- | --- | +| **显示图例** | 显示或隐藏图例。 | +| **位置** | 控制图例相对于图表的显示位置。支持的值:**左**、**右**、**上**、**下**。 | + +### 工具提示 + +切换**显示工具提示**选择器以启用或禁用工具提示。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/table-chart.md b/i18n/zh/dashboards/visualize/visualization-editor/table-chart.md new file mode 100644 index 00000000..bf89a4fd --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/table-chart.md @@ -0,0 +1,50 @@ +--- +title: 表格 +--- + +# 可视化编辑器中的表格 + +表格以行和列显示查询结果。使用表格查看原始数据或汇总统计信息。 + +## 创建表格 + +以下示例演示基本的表格可视化。在开始之前,请完成[先决条件](/dashboards/visualize/visualization-editor/#prerequisites)。 + +### 基本表格 + +从一个返回多个字段的查询开始: + +```sql +source = opensearch_dashboards_sample_data_flights | fields Carrier, AvgTicketPrice, DistanceMiles, FlightDelayMin | head 20 +``` + +运行此查询后,选择**表格**作为图表类型。结果是一个将所选字段显示为列的表格,如下图所示。 + +*显示航班数据的表格* + +## 配置表格 + +您可以在配置面板中配置以下设置。 + +### 表格 + +| 设置 | 描述 | +| --- | --- | +| **每页最大行数** | 设置每页显示的最大行数。 | +| **单元格对齐** | 控制单元格内的文本对齐方式。支持的值:**自动**、**左**、**居中**、**右**。 | +| **单元格样式** | 选择**添加新单元格类型**以对特定列应用自定义样式。 | +| **列过滤器** | 启用时,在列标题中显示过滤器控件以进行交互式过滤。 | + +### 阈值 + +有关配置阈值的信息,请参阅[阈值](/dashboards/visualize/visualization-editor/configuring-visualizations/thresholds)。 + +### 表格页脚 + +| 设置 | 描述 | +| --- | --- | +| **显示页脚** | 启用时,显示包含每列汇总计算的页脚行。 | + +### 数据链接 + +选择**添加链接**以在表格单元格内创建可点击的链接。使用数据链接根据单元格值导航到外部 URL 或其他仪表板。 diff --git a/i18n/zh/dashboards/visualize/visualization-editor/viz-types.md b/i18n/zh/dashboards/visualize/visualization-editor/viz-types.md new file mode 100644 index 00000000..e8ce5ccc --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualization-editor/viz-types.md @@ -0,0 +1,22 @@ +--- +title: 可视化类型 +--- + +# 基于查询的可视化类型 + +下表列出了可视化编辑器支持的可视化类型及其预期数据形状。 + +| 图表类型 | 数据形状 | +| :--- | :--- | +| [面积图](/dashboards/visualize/visualization-editor/area-chart) | 一个日期字段 + 一个或多个数字字段(支持堆叠) | +| [条形图](/dashboards/visualize/visualization-editor/bar-chart) | 一个或多个分类或日期字段 + 一个或多个数字字段 | +| [条形仪表图](/dashboards/visualize/visualization-editor/bar-gauge-chart) | 一个或多个数字字段(单个值) | +| [仪表图](/dashboards/visualize/visualization-editor/gauge-chart) | 一个数字字段(单个值) | +| [热力图](/dashboards/visualize/visualization-editor/heatmap-chart) | 两个分类或日期字段 + 一个数字字段 | +| [直方图](/dashboards/visualize/visualization-editor/histogram-chart) | 一个数字字段(分布) | +| [折线图](/dashboards/visualize/visualization-editor/line-chart) | 一个日期字段 + 一个或多个数字字段 | +| [指标图](/dashboards/visualize/visualization-editor/metric-chart) | 一个数字字段(单个值) | +| [饼图](/dashboards/visualize/visualization-editor/pie-chart) | 一个分类字段 + 一个数字字段 | +| [散点图](/dashboards/visualize/visualization-editor/scatter-chart) | 两个或更多数字字段 | +| [状态时间线](/dashboards/visualize/visualization-editor/state-timeline-chart) | 一个日期字段 + 一个分类字段(状态值) | +| [表格](/dashboards/visualize/visualization-editor/table-chart) | 任意字段组合(显示原始数据) | diff --git a/i18n/zh/dashboards/visualize/visualize-app/aggregation-based-viz.md b/i18n/zh/dashboards/visualize/visualize-app/aggregation-based-viz.md new file mode 100644 index 00000000..4a3f0312 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/aggregation-based-viz.md @@ -0,0 +1,127 @@ +--- +title: 创建基于聚合的可视化 +--- + +# 创建基于聚合的可视化 + +[聚合](/aggregations/)是 OpenSearch Dashboards 中大多数可视化背后的分析引擎。它们计算统计信息(指标)并将数据分组到类别(分桶)中,以便结果可以显示为图表、表格和地图。当您在**可视化**应用中配置可视化时,OpenSearch Dashboards 会自动将您的选择转换为聚合查询。 + +以下可视化类型使用聚合:**面积图**、**水平条形图**、**垂直条形图**、**坐标地图**、**数据表**、**仪表图**、**目标图**、**热力图**、**折线图**、**指标**、**饼图**、**区域地图**和**标签云**。 + +有关可用指标和分桶的完整列表,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz#data-tab)。 + +在本教程中,您将使用示例航班数据创建垂直条形图可视化,并学习如何使用指标聚合、分桶聚合、拆分系列、百分位数、管道聚合和 Top Hit。 + +## 先决条件 + +本页面上的示例使用**示例航班数据**数据集。如果您尚未添加示例数据,请参阅[准备您的数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 示例 1:随时间变化的航班计数 + +此示例使用默认的 **Count** 指标和 **Date Histogram** 分桶来显示每个时间间隔的航班数量。 + +要创建航班计数可视化,请按照以下步骤操作: + +1. 在左侧导航菜单中,选择 **OpenSearch Dashboards** > **可视化**。 +1. 选择**创建可视化**。 +1. 选择**垂直条形图**,然后选择 **opensearch_dashboards_sample_data_flights** 作为数据源。 +1. 将时间过滤器设置为**过去 7 天**。 +1. 在**分桶**面板中,选择**添加** > **X 轴**。 +1. 从**聚合**下拉列表中,选择**日期直方图**。 +1. 验证**字段**设置为 **timestamp**。 +1. 选择**更新**。 + +图表显示每 3 小时间隔的航班数量。Y 轴显示 **Count**——每个时间桶中的文档(航班)数量。因为 **Count** 是默认指标,所以不需要选择字段。 + +*使用 Count 指标和日期直方图分桶的随时间变化航班计数* + +## 示例 2:随时间变化的平均票价 + +此示例将 Count 替换为 **Average** 指标,以显示票价如何随时间变化。 + +要将指标更改为 **Average**,请按照以下步骤操作: + +1. 在**指标**面板中,选择 **Y 轴**部分。 +1. 从**聚合**下拉列表中,选择**平均值**。 +1. 从**字段**下拉列表中,选择 **AvgTicketPrice**。 +1. 选择**更新**。 + +Y 轴现在显示美元值而不是文档计数。每个条形代表该时间间隔内所有航班的平均票价。 + +*随时间变化的平均票价* + +## 示例 3:按承运人划分的航班计数 + +此示例添加**拆分系列**分桶,按航空公司承运人分解 **Count** 指标。 + +要按承运人拆分系列,请按照以下步骤操作: + +1. 在**指标**面板中,将**聚合**改回 **Count**。 +1. 在**分桶**面板中,选择**添加** > **拆分系列**。 +1. 从**聚合**下拉列表中,选择**词条**。 +1. 从**字段**下拉列表中,选择 **Carrier**。 +1. 选择**更新**。 + +图表现在显示堆叠条形,每种颜色代表不同的航空公司。图例标识每个承运人。此配置创建嵌套聚合:**日期直方图**将航班分组到时间桶中,**词条**聚合按承运人细分每个桶。 + +*按承运人拆分的航班计数* + +## 示例 4:随时间变化的票价百分位数 + +此示例使用 **Percentiles** 指标显示跨时间间隔的票价分布。与 **Average**(返回单个值)不同,**Percentiles** 返回多个值——您配置的每个百分位数一个值。 + +要创建 **Percentiles** 可视化,请按照以下步骤操作: + +1. 在**指标**面板中,选择 **Y 轴**部分。 +1. 从**聚合**下拉列表中,选择**百分位数**。 +1. 从**字段**下拉列表中,选择 **AvgTicketPrice**。 +1. 在**百分比**部分,删除默认值并输入 `25`、`50` 和 `75`(四分位距)。使用每个值旁边的删除图标删除它,并选择**添加百分比**添加新的。 +1. 在**分桶**面板中,验证 **X 轴**设置为 **timestamp** 字段上的**日期直方图**。 +1. 选择**更新**。 + +图表显示三个堆叠系列——每个百分位数一个。第 50 百分位数(中位数)显示中间值,而第 25 和第 75 百分位数之间的差距显示每个时间桶中票价的分布。 + +*随时间变化的票价百分位数* + +## 示例 5:累计航班计数 + +此示例使用 **Cumulative Sum** 管道聚合显示航班的累计总数。管道聚合操作于另一个指标的输出,而不是直接操作于文档字段。 + +要向可视化添加累计总和,请按照以下步骤操作: + +1. 在**指标**面板中,验证第一个 Y 轴设置为 **Count**。 +1. 选择**添加**创建第二个指标。 +1. 从**聚合**下拉列表中,向下滚动到**父管道聚合**并选择**累计总和**。 +1. 在**指标**下拉列表中,选择**自定义指标**。 +1. 在出现的嵌套**聚合**下拉列表中,选择 **Count**。 +1. 在**分桶**面板中,验证 **X 轴**设置为 **timestamp** 字段上的**日期直方图**。 +1. 选择**更新**。 + +图表将每个间隔的 **Count** 显示为底部的条形,将 **Cumulative Sum** 显示为上升的线。该线显示随时间累积的航班总数。 + +*累计航班计数* + +## 示例 6:随时间变化的最新票价 + +此示例使用 **Top Hit** 指标在每个时间桶中显示最新的票价。**Top Hit** 具有所有指标中最多的配置选项:它允许您控制返回哪些文档值、返回多少个以及以什么顺序返回。 + +要创建 **Top Hit** 可视化,请按照以下步骤操作: + +1. 在**指标**面板中,选择 **Y 轴**部分。 +1. 从**聚合**下拉列表中,选择 **Top Hit**。 +1. 从**字段**下拉列表中,选择 **AvgTicketPrice**。 +1. 从**聚合方式**下拉列表中,选择 **Max**(这决定了同一桶内的多个值如何组合)。 +1. 将**大小**设置为 `1`(每个桶返回一个值)。 +1. 从**排序依据**下拉列表中,选择 **timestamp**。 +1. 从**顺序**下拉列表中,选择**降序**(最新的在前)。 +1. 在**分桶**面板中,验证 **X 轴**设置为 **timestamp** 字段上的**日期直方图**。 +1. 选择**更新**。 + +图表显示每个 3 小时间隔内最新(最高时间戳)的票价。与 **Average**(将所有值平滑在一起)不同,**Top Hit** 显示单个文档的实际值,这对于跟踪每个时间窗口的最新状态非常有用。 + +*使用 Top Hit 显示随时间变化的最新票价* + +## 后续步骤 + +- 要了解所有可用的指标和分桶聚合,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz#data-tab)。 +- 要了解聚合在 API 中的工作方式,请参阅[聚合](/aggregations/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/area.md b/i18n/zh/dashboards/visualize/visualize-app/area.md new file mode 100644 index 00000000..150e6e3d --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/area.md @@ -0,0 +1,174 @@ +--- +title: 面积图 +--- + +# 面积图 + +面积图是折线图,折线下方的区域用颜色填充。您可以堆叠多个分桶来显示变量累计绝对值的相对比例,或者叠加分桶或不同变量以在 X 轴分桶或时间值内进行比较。 + +## 何时使用面积图 + +使用面积图同时显示趋势模式和比例关系。它们揭示贡献模式,显示哪些组件驱动整体总量以及这些模式何时发生变化。 + +## 创建面积图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集并相互构建。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建显示随时间变化航班计数的面积图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**面积图**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 +2. 在**指标**下,展开 **Y 轴 Count** 并将**聚合**设置为 **Count**。 + + 对于 `Count` 指标,没有字段选择,因为 `Count` 表示文档数量,而不是字段值。 + +3. 在**分桶**下,选择**添加** > **X 轴**。 +4. 将**聚合**设置为**日期直方图**,将**字段**设置为 **timestamp**。 + + ::: info NOTE + timestamp 字段是示例航班数据中唯一可用的日期时间字段。 + ::: + +5. 选择**更新**。 + + 图表生成一个锯齿状的时间序列图,显示自动确定的桶大小(例如,一天)的文档计数。 + +6. 拖动选择包含数据的图表部分。在数据两侧留有边距,以免切断任何数据。 + + 数据扩展以填充整个图表宽度。由于空间更大,自动计算的桶大小减少到 12 小时。 + +7. 在**分桶**下,选择**添加** > **拆分系列**。 +8. 将**子聚合**设置为**词条**,将**字段**设置为 **Cancelled**。 +9. 选择**更新**。 + + 图表显示取消和未取消航班的计数叠加在时间线上,如下图所示。 + + *叠加航班取消状态的面积图* + + 注意以下几点: + - 取消(`Cancelled = true`)和未取消航班的计数叠加在图表上。取消的航班计数似乎平均约为未取消航班的 10%。 + - 航班计数随时间周期性变化,每周有一天的下降。 + +### 堆叠面积图 + +默认情况下,拆分系列是叠加的(正常模式)。要将区域堆叠在一起以显示总量: + +1. 选择**指标和坐标轴**选项卡。 +2. 在**指标**下,展开 **Count** 系列。 +3. 将**模式**从**正常**更改为**堆叠**。 +4. 选择**更新**。 + +区域现在堆叠,显示单个类别量和组合总量,如下图所示。 + +*显示航班取消状态的堆叠面积图* + +### 多个指标 + +添加第二个 Y 轴指标以在同一图表上比较不同的测量值: + +1. 在**指标**下,选择**添加**。 +2. 将**聚合**设置为**平均值**,将**字段**设置为 **AvgTicketPrice**。 +3. 选择**更新**。 + +图表现在将平均票价叠加在计数上。要为第二个指标提供自己的刻度,请转到**指标和坐标轴**选项卡,展开新指标,并将其分配给新的值轴。 + +## 配置面积图 + +面积图编辑器有三个配置选项卡。 + +### 数据选项卡 + +**数据**选项卡定义显示的数据。 + +#### 指标 + +指标定义 Y 轴值。每个指标计算每个桶中文档的聚合。 + +| 设置 | 描述 | +| :--- | :--- | +| **聚合** | 聚合函数。支持的值:**Count**、**Average**、**Sum**、**Min**、**Max**、**Unique Count**、**Median**、**Percentiles**、**Percentile Ranks**、**Top Hit**、**Standard Deviation**。 | +| **字段** | 要聚合的数字字段(**Count** 不需要)。 | + +选择**添加**以在同一图表上绘制多个指标。 + +#### 分桶 + +分桶定义数据如何分组。 + +| 分桶类型 | 描述 | +| :--- | :--- | +| **X 轴** | 沿水平轴对数据进行分组。通常对基于时间的数据使用**日期直方图**,或对数字范围使用**直方图**。 | +| **拆分系列** | 按字段值将数据拆分为多个堆叠(或叠加)区域。使用**词条**、**过滤器**或其他分桶聚合。 | +| **拆分图表** | 为每个桶值创建单独的图表面板(小倍数图)。可以按行或列拆分。 | + +### 指标和坐标轴选项卡 + +**指标和坐标轴**选项卡控制每个指标的渲染方式以及坐标轴的配置方式。 + +#### 系列设置 + +每个指标系列具有以下选项。 + +| 设置 | 描述 | +| :--- | :--- | +| **值轴** | 此系列绑定的 Y 轴。选择**新轴**以创建辅助 Y 轴。 | +| **图表类型** | 覆盖此系列的图表类型。支持的值:**折线**、**面积**、**条形**。 | +| **模式** | 控制堆叠行为。**堆叠**将区域层叠在一起。**正常**重叠区域。 | +| **线条模式** | 控制线条插值。**直线**绘制直接线段。**平滑**应用曲线。**阶梯**创建阶梯图案。 | + +#### Y 轴 + +每个 Y 轴具有以下选项。 + +| 设置 | 描述 | +| :--- | :--- | +| **位置** | 轴出现的位置。支持的值:**左**、**右**。 | +| **模式** | 控制 Y 轴刻度模式。**正常**显示原始值。**百分比**将堆叠区域标准化为 100%。**波动**和**轮廓**是流图布局变体。 | +| **刻度类型** | 确定刻度。支持的值:**线性**、**对数**、**平方根**。 | +| **显示** | 显示或隐藏轴线和标签。 | +| **标签** | 控制标签旋转。支持的值:**水平**、**垂直**、**倾斜**。 | + +#### X 轴 + +| 设置 | 描述 | +| :--- | :--- | +| **位置** | 轴出现的位置。支持的值:**顶部**、**底部**。 | +| **显示** | 显示或隐藏轴线和标签。 | +| **过滤标签** | 启用后,重叠的标签会自动隐藏。 | +| **对齐** | 控制标签旋转。支持的值:**水平**、**垂直**、**倾斜**。 | +| **截断** | 设置标签截断前的最大像素宽度。 | + +### 面板设置选项卡 + +**面板设置**选项卡控制整体图表外观。 + +#### 设置 + +| 设置 | 描述 | +| :--- | :--- | +| **图例位置** | 图例出现的位置。支持的值:**顶部**、**左侧**、**右侧**、**底部**。 | +| **显示工具提示** | 启用后,悬停时显示值。 | +| **按总和排序分桶** | 启用后,按总值而非字母顺序排序拆分系列。 | + +#### 网格 + +| 设置 | 描述 | +| :--- | :--- | +| **显示 X 轴线** | 启用后,在每个 X 轴刻度处显示垂直网格线。 | +| **Y 轴线** | 选择 Y 轴以显示水平网格线,或**不显示**以隐藏它们。 | + +#### 阈值线 + +| 设置 | 描述 | +| :--- | :--- | +| **显示阈值线** | 启用后,在指定值处绘制水平参考线。 | +| **阈值** | 绘制线条的 Y 轴值。 | +| **线宽** | 阈值线的粗细(像素)。 | +| **线型** | 线条样式。支持的值:**实线**、**虚线**、**点划线**。 | +| **线条颜色** | 阈值线的颜色。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/bar-charts.md b/i18n/zh/dashboards/visualize/visualize-app/bar-charts.md new file mode 100644 index 00000000..b9e2cc50 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/bar-charts.md @@ -0,0 +1,81 @@ +--- +title: 条形图 +--- + +# 条形图 + +条形图通过将值表示为成比例的条形长度来比较跨类别的值。对于时间序列数据或类别比较,使用垂直条形;当类别标签较长或比较多个类别时,使用水平条形。 + +## 何时使用条形图 + +使用条形图来揭示自变量的变化、跨类别的比较性能以及随时间变化的趋势。条形图可以显示性能差距、异常值、季节性模式以及跨类别的比较优势。您可以选择条形来过滤同一仪表板上的其他可视化。 + +## 创建条形图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建条形图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**垂直条形图**(或**水平条形图**),然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 +2. 在**指标**下,展开 **Y 轴 Count**。 +3. 将**聚合**设置为**平均值**,将**字段**设置为 **FlightDelayMin**。 +4. (可选)输入**自定义标签**,例如 `航班延误分钟数`。 +5. 选择**更新**。 + + 图表显示一个高度约为 `47` 的单个条形,这是航班数据库中每个文档的平均航班延误。 + + ::: info NOTE + 如果您的可视化显示不同的值,请确保您的时间过滤器窗口足够大以包含所有示例航班数据。 + ::: + +6. 在**分桶**下,选择**添加** > **X 轴**。 +7. 将**聚合**设置为**词条**,将**字段**设置为 **OriginWeather**。 +8. 将**排序依据**设置为 `指标: FlightDelayMin`,**顺序**设置为**降序**,**大小**设置为 `8`。 + + ::: info NOTE + 任何八或更高的数字都会显示所有可用的 `OriginWeather` 词条。 + ::: + +9. 选择**更新**。 + + 图表显示了每种出发地天气类型的平均延误。最大的平均延误是 `破坏性风`,如下图所示。 + + *按出发地天气显示平均航班延误的条形图* + +## 配置条形图 + +条形图与其他基于聚合的可视化共享相同的配置选项卡。有关每个选项卡的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 数据选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **指标** | 定义 Y 轴值。支持所有标准聚合(Count、Average、Sum、Min、Max、Unique Count、Median、Percentiles 等)。 | +| **分桶 > X 轴** | 沿水平轴对条形进行分组。对于分类数据使用**词条**,对于基于时间的数据使用**日期直方图**,对于数字范围使用**直方图**。 | +| **分桶 > 拆分系列** | 按字段值将每个条形拆分为分组或堆叠的子条形。 | +| **分桶 > 拆分图表** | 为每个桶值创建单独的图表面板(小倍数图)。 | + +### 指标和坐标轴选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **图表类型** | 按系列覆盖。支持**折线**、**面积**、**条形**。 | +| **模式** | **堆叠**将条形层叠在一起。**正常**将条形并排分组。 | +| **Y 轴位置** | **左**或**右**。 | +| **Y 轴刻度** | **线性**、**对数**或**平方根**。 | + +### 面板设置选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **图例位置** | **顶部**、**左侧**、**右侧**、**底部**。 | +| **显示工具提示** | 悬停时显示值。 | +| **按总和排序分桶** | 按总值排序拆分系列。 | +| **显示阈值线** | 在指定值处绘制水平参考线。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/configuring-maps.md b/i18n/zh/dashboards/visualize/visualize-app/configuring-maps.md new file mode 100644 index 00000000..e649bec3 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/configuring-maps.md @@ -0,0 +1,12 @@ +--- +title: 配置地图 +--- + +# 配置地图 + +您可以配置[坐标地图](/dashboards/visualize/visualize-app/coordinate-maps)和[地图应用](/dashboards/visualize/maps)使用的地图切片服务器。这些设置不适用于使用矢量边界(GeoJSON 文件)而非栅格切片的[区域地图](/dashboards/visualize/visualize-app/region-maps)。 + +## 相关文档 + +- [配置 Web 地图服务(WMS)](/dashboards/visualize/maptiles) -- 为自定义底图配置 WMS 切片服务器。 +- [使用自托管地图服务器](/dashboards/visualize/selfhost-maps-server) -- 为隔离网络环境在本地托管地图切片。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/configuring-viz.md b/i18n/zh/dashboards/visualize/visualize-app/configuring-viz.md new file mode 100644 index 00000000..26cfdfaf --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/configuring-viz.md @@ -0,0 +1,167 @@ +--- +title: 配置可视化 +--- + +# 配置可视化 + +配置面板位于**可视化**应用的右侧。它包含两个或多个选项卡,具体取决于正在编辑的可视化类型。有关术语定义,请参阅[概念](/dashboards/getting-started/concepts)。 + +配置面板包含以下选项卡: + +- **数据**选项卡允许向可视化添加指标和数据分桶。 +- **指标和坐标轴**选项卡控制显示选项,如如何显示坐标轴、标签和刻度;文本显示和对齐以及特定于可视化的选项。对于某些可视化类型,此选项卡标记为**选项**。 +- **面板设置**选项卡包含面板范围设置的选项,如图例、工具提示和网格线。 + +## 数据选项卡 + +**数据**选项卡使用[聚合](/aggregations/)来确定显示的数据及其分组方式。配置可视化时,OpenSearch Dashboards 会根据您的选择自动生成聚合查询。有关实践演练,请参阅[创建基于聚合的可视化](/dashboards/visualize/visualize-app/aggregation-based-viz)。 + +::: info NOTE +以下可视化类型使用带有聚合的**数据**选项卡:**面积图**、**水平条形图**、**垂直条形图**、**坐标地图**、**数据表**、**仪表图**、**目标图**、**热力图**、**折线图**、**指标**、**饼图**、**区域地图**和**标签云**。 +::: + +典型的**数据**选项卡如下图所示。 + +*可视化工具数据设置* + +**数据**选项卡通常包含两种类型的面板用于向可视化添加元素: + +- **Y 轴**、**数据**或**指标**面板用于选择要显示的字段 +- **X 轴**或**分桶**面板用于选择如何分割数据以进行显示 + +**指标**和**分桶**面板都使用_渐进式披露_,这意味着后续可用的选项基于您在面板中的上一个选择。选择指标或分桶的典型顺序如下: + +1. 从可用选项的下拉列表中选择聚合类型,如平均值、计数、最大值或最小值。 + +1. 从下拉列表中选择字段。字段选择仅限于可应用所选聚合的数据类型。例如,**Count** 聚合适用于整个文档,因此不显示字段选择。**Date Histogram** 聚合仅适用于时间戳字段。 + +1. 您可以选择其他选项,如范围间隔或在可视化中标记字段的自定义名称。 + +1. 您可以选择添加更多字段或分桶。例如,在选择直方图的 _X 轴_分桶类型以在条形图中跨产品类别显示成本变量后,您可能会添加一个_拆分图表_分桶来为每个客户性别显示单独的条形图。 + +### 指标聚合 + +指标聚合出现在**指标**面板中,并成为图表中的 Y 轴值。下表列出了可用的指标聚合。 + +| 指标 | 描述 | 需要字段 | +| :--- | :--- | :--- | +| `Count` | 计算每个桶中的文档数。这是新可视化的默认指标,不需要字段选择。在聚合 API 中,每个[分桶聚合](/aggregations/bucket/)响应都包含一个 `doc_count` 字段,其中包含该桶中的文档数——而 `Count` 显示此值。 | 否 | +| [`Average`](/aggregations/metric/average) | 计算数字字段的平均值。 | 是 | +| [`Max`](/aggregations/metric/maximum) | 返回数字字段的最大值。 | 是 | +| [`Median`](/aggregations/metric/percentile) | 返回数字字段的第 50 百分位值。在聚合 API 中,这使用第 50 位的 `percentiles` 聚合。 | 是 | +| [`Min`](/aggregations/metric/minimum) | 返回数字字段的最小值。 | 是 | +| [`Percentile Ranks`](/aggregations/metric/percentile-ranks) | 返回数字字段中指定值的百分位排名。选择后,在**值**列表中输入阈值以定义计算排名的点。 | 是 | +| [`Percentiles`](/aggregations/metric/percentile) | 返回数字字段指定百分位排名处的值。选择后,配置**百分比**列表以定义要计算的百分位数。默认值为 1、5、25、50、75、95 和 99。每个百分位数在可视化中显示为单独的系列。 | 是 | +| [`Standard Deviation`](/aggregations/metric/extended-stats) | 计算数字字段的标准差。在聚合 API 中,这使用 `extended_stats` 聚合。 | 是 | +| [`Sum`](/aggregations/metric/sum) | 计算数字字段的总和。 | 是 | +| [`Top Hit`](/aggregations/metric/top-hits) | 返回按指定指标排序的字段的一个或多个最高值。选择后,配置**聚合方式**(如何组合多个值:`Concat`、`Min`、`Max`、`Sum` 或 Average)、**大小**(要返回的最高值数量)、**排序依据**(排序字段)和**顺序**(升序或降序)。 | 是 | +| [`Unique Count`](/aggregations/metric/cardinality) | 计算字段中不同值的数量。在聚合 API 中,这对应于 `cardinality` 聚合。 | 是 | + +### 父管道聚合 + +父管道聚合基于同一桶内另一个指标的输出计算值。它们出现在**指标**面板中基本指标聚合下方。 + +选择父管道聚合后,使用**指标**下拉列表选择要操作的指标。从 Y 轴选择现有指标,或选择**自定义指标**以内联定义新指标(这会显示一个嵌套的聚合选择器,您可以在其中配置任何基本指标聚合)。 + +| 指标 | 描述 | +| :--- | :--- | +| [`Cumulative Sum`](/aggregations/pipeline/cumulative-sum) | 计算有序桶中指标的累计总和。 | +| [`Derivative`](/aggregations/pipeline/derivative) | 计算连续桶之间指标的变化率。 | +| [`Moving Avg`](/aggregations/pipeline/moving-avg) | 计算滑动窗口桶中指标的移动平均值。 | +| [`Serial Diff`](/aggregations/pipeline/serial-diff) | 计算指标值与系列中较早值之间的差异。 | + +### 兄弟管道聚合 + +兄弟管道聚合从兄弟聚合中的所有桶计算单个值,并将其与其他指标一起显示。它们出现在**指标**面板中父管道聚合下方。 + +与父管道聚合一样,兄弟管道聚合使用**指标**下拉列表选择要操作的指标。选择现有指标或**自定义指标**以内联定义一个。 + +| 指标 | 描述 | +| :--- | :--- | +| [`Average Bucket`](/aggregations/pipeline/avg-bucket) | 计算所有桶中指标的平均值。 | +| [`Max Bucket`](/aggregations/pipeline/max-bucket) | 返回所有桶中指标的最大值。 | +| [`Min Bucket`](/aggregations/pipeline/min-bucket) | 返回所有桶中指标的最小值。 | +| [`Sum Bucket`](/aggregations/pipeline/sum-bucket) | 计算所有桶中指标的总和。 | + +### 分桶聚合 + +分桶聚合出现在**分桶**面板中,并确定数据如何分组。当您在**分桶**面板中选择**添加**时,首先选择分桶类型: + +| 分桶类型 | 描述 | +| :--- | :--- | +| X 轴 | 沿图表的水平轴对数据进行分组。 | +| 拆分系列 | 在同一图表内创建多个系列(折线、条形或区域),每个代表不同的组。 | +| 拆分图表 | 为每个组创建单独的图表,以行或列布局显示。 | + +选择分桶类型后,您选择分桶聚合以定义数据的分组方式。下表列出了可用的分桶聚合。 + +| 聚合 | 描述 | +| :--- | :--- | +| [`Date Histogram`](/aggregations/bucket/date-histogram) | 将文档分组到时间间隔(例如,每小时、每天或每周)。需要日期字段。 | +| [`Date Range`](/aggregations/bucket/date-range) | 将文档分组到您定义的自定义日期范围。需要日期字段。 | +| [`Filters`](/aggregations/bucket/filters) | 按您定义的自定义查询过滤器对文档进行分组。每个过滤器创建一个桶。 | +| [`Histogram`](/aggregations/bucket/histogram) | 将数值分组到固定大小的间隔。需要数字字段。 | +| [`IPv4 Range`](/aggregations/bucket/ip-range) | 将文档分组到自定义 IP 地址范围。需要 IP 字段。 | +| [`Range`](/aggregations/bucket/range) | 将数值分组到您定义的自定义范围。需要数字字段。 | +| [`Significant Terms`](/aggregations/bucket/significant-terms) | 识别在所选数据集中比在整个索引中出现更频繁的词条。需要关键字或文本字段。 | +| [`Terms`](/aggregations/bucket/terms) | 按字段的唯一值对文档进行分组。需要关键字、数字、IP 或布尔字段。 | + +有关分桶聚合类型的更多信息,请参阅[分桶聚合](/aggregations/bucket/)。 + +## 指标和坐标轴选项卡 + +典型的**指标**选项卡如下图所示。 + +*可视化工具指标和坐标轴设置* + +与**数据**选项卡一样,**指标和坐标轴**(或**选项**)选项卡的内容取决于可视化类型以及您选择的数据的具体情况。选项差异很大,但通常分为以下类别。这不是详尽的列表: + +### 指标选项 + +指标或显示选项包括: + +- 图形的形式因素,如仪表的圆形或弧形;或折线/条形/面积图表类型 +- 特定于可视化的选项,如堆叠或正常(叠加)面积图 +- 是否在折线图中显示线条和点、线宽和线条样式(如直线或平滑) +- 范围宽度 +- 颜色方案(例如,用于热力图) + +### 坐标轴选项 + +X 轴和 Y 轴选项包括: + +- 坐标轴的位置 +- 模式,如正常或百分比刻度 +- 是否显示或截断标签及其对齐方式 +- 坐标轴的自定义标题 +- 是否显示坐标轴线和刻度标记 + +## 面板设置 + +典型的**面板设置**选项卡如下图所示。 + +*可视化工具面板设置* + +**面板设置**选项卡控制面板范围的显示选项,如下所示: + +- 更改图例的位置 +- 显示阈值线 +- 在时间线上突出显示当前时间 +- 显示或隐藏垂直或水平网格线 +- 在图表上标记值 + +## 图例颜色 + +图例在范围、分类或文本变量由颜色表示的图表中显示颜色键。 + +使用图例更改图形元素的颜色。要更改颜色,请按照以下步骤操作: + +1. 选择图例中的条目。 + +2. 从出现的调色板中选择颜色。 + +*可视化图例* + +## 后续步骤 + +- 有关实践教程,请参阅[创建基于聚合的可视化](/dashboards/visualize/visualize-app/aggregation-based-viz)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/controls.md b/i18n/zh/dashboards/visualize/visualize-app/controls.md new file mode 100644 index 00000000..847cbd75 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/controls.md @@ -0,0 +1,68 @@ +--- +title: 控件 +--- + +# 控件可视化 +<Badge type="tip" text="实验性" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进度的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +控件可视化向仪表板添加交互式过滤面板。控件允许您在不修改仪表板本身的情况下过滤数据。 + +控件不需要数据源。您在每个单独的控件中配置数据源。 + +## 何时使用控件 + +使用控件在仪表板内过滤数据。许多可视化内置了数据选择过滤功能。将控件与尚未提供数据选择的可视化一起使用,或增强现有可视化的数据选择功能。 + +## 控件类型 + +有两种类型的控件可用: + +- **范围滑块**:定义数字字段的最小值和最大值。 +- **选项列表**:提供从字段中选择值的下拉列表。 + +## 创建控件可视化 + +要创建控件可视化,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**控件**。 +2. 选择**控件**选项卡。 +3. 从**类型**下拉列表中,选择**范围滑块**或**选项列表**。 +4. 选择**添加**。 + +下图显示了带有两个选项列表控件(出发城市和目的地城市)和一个范围滑块控件(平均票价)的控件可视化。 + +*带有下拉列表和范围滑块的控件可视化* + +### 配置范围滑块 + +1. 在**控件标签**中,输入显示在控件上的标签。 +2. 从**索引模式**中,选择数据源。 +3. 从**字段**中,选择数字字段。 +4. (可选)设置**步长**(最小增量)和**小数位数**。 +5. 选择**更新**。 + +### 配置选项列表 + +1. 在**控件标签**中,输入显示在控件上的标签。 +2. 从**索引模式**中,选择数据源。 +3. 从**字段**中,选择要过滤的字段。 +4. (可选)启用**多选**以允许选择多个值。 +5. (可选)启用**动态选项**以自动缩放下拉项目(仅限文本字段)。 +6. 如果禁用了**动态选项**,请设置**大小**(显示的项目数)。 + + ::: info NOTE + 控件仅显示前 **大小** 个值,由数据字段的排序方法确定。 + ::: + +7. 选择**更新**。 + +您可以通过重复这些步骤向单个可视化添加多个控件。 + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/coordinate-maps.md b/i18n/zh/dashboards/visualize/visualize-app/coordinate-maps.md new file mode 100644 index 00000000..c56f21f7 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/coordinate-maps.md @@ -0,0 +1,58 @@ +--- +title: 坐标地图 +--- + +# 坐标地图 + +坐标地图使用纬度和经度坐标在地图上绘制地理数据点。每个标记代表一个具有 geo_point 字段的文档,标记大小表示该位置的聚合值。 + +## 何时使用坐标地图 + +使用坐标地图来揭示位置上的分布模式和空间相关性,例如客户位置、服务覆盖区域、事件分布或具有地理坐标的事件。您可以选择地理区域来过滤同一仪表板上的其他可视化。对于多图层地理可视化,请使用[地图应用](/dashboards/visualize/maps)。 + +## 创建坐标地图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建坐标地图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**坐标地图**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 +2. 将时间过滤器设置为**过去 7 天**。 +3. 在**分桶**下,选择**添加** > **地理坐标**。 +4. 将**聚合**设置为 **Geohash**,将**字段**设置为 **OriginLocation**。 +5. 选择**更新**。 + +地图在航班出发地位置显示标记,标记大小与每个位置的文档计数成比例,如下图所示。 + +*显示航班出发地的坐标地图* + +### 自定义地图显示 + +1. 选择**选项**选项卡。 +2. 在**地图类型**下,选择标记样式:**缩放圆形标记**、**阴影圆形标记**、**阴影 Geohash 网格**或**热力图**。 +3. 调整**精度**以控制 geohash 桶大小(更高的精度 = 更小、更多的桶)。 +4. 选择**更新**。 + +## 配置坐标地图 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **地图类型** | 标记样式。支持的值:**缩放圆形标记**(按值缩放大小)、**阴影圆形标记**(按值着色)、**阴影 Geohash 网格**(按值着色的矩形单元格)、**热力图**(连续颜色渐变)。 | +| **精度** | 控制 geohash 网格分辨率。较高的值产生更小、更多的桶。 | +| **显示工具提示** | 启用后,悬停时显示聚合值。 | +| **WMS 兼容地图服务器** | 启用后,使用 WMS 服务器作为底图。有关更多信息,请参阅[配置 Web 地图服务](/dashboards/visualize/maptiles)。 | + +## 相关文档 + +- [配置地图](/dashboards/visualize/visualize-app/configuring-maps) + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/data-table.md b/i18n/zh/dashboards/visualize/visualize-app/data-table.md new file mode 100644 index 00000000..876b059d --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/data-table.md @@ -0,0 +1,116 @@ +--- +title: 数据表 +--- + +# 数据表 + +数据表以行列形式显示所选字段。您可以将一个或多个指标显示为列,分桶到行中,并将桶数据细分为单独的表格。 + +## 何时使用数据表 + +使用数据表来检查单个文档、验证数据质量或调查聚合可视化背后的详细信息。您可以排序、过滤和检查在更抽象的可视化中可能不明显的字段之间的相关性。将数据表用作下钻目标,从高级视觉摘要移动到特定的记录级别详细信息。 + +## 创建数据表 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建数据表,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**数据表**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 + + 默认情况下,可视化选择 `Count` 作为要显示的唯一指标。由于数据未分桶,因此显示总文档计数。 + + ::: info NOTE + 对于此数据集,如果没有数据被过滤掉,计数为 `13,059`。如果您的可视化显示不同的值,请确保您的时间过滤器窗口足够大以包含所有示例航班数据。请参阅[时间过滤器](/dashboards/discover/time-filter)。 + ::: + +2. 在**指标**面板中,展开**指标 Count**。 +3. 将**聚合**设置为**平均值**,将**字段**设置为 **FlightDelayMin**。 +4. (可选)输入**自定义标签**,例如 `航班延误分钟数`。 +5. 选择**更新**。 + + 表格显示所有数据的单个值 `47.335`。这是航班数据库中每个文档的平均航班延误,包括零分钟延误。 + +6. 在**分桶**面板中,选择**添加** > **拆分行**。 +7. 将**聚合**设置为**词条**,将**字段**设置为 **FlightDelay**。 +8. 选择**更新**。 + + ::: info NOTE + 表格显示未延误航班的平均延误时间为零分钟。非零航班延误桶明显高于总体值,因为零延误不再是该平均值的一部分。 + ::: + +9. 通过从**聚合**下拉列表中选择**范围**,从**字段**下拉列表中选择 **DistanceMiles** 来更改行分桶。 +10. 配置以下范围(为第三行选择**添加范围**): + + | 从 | 到 | + | :--- | :--- | + | 0 | 4000 | + | 4000 | 8000 | + | 8000 | 无穷大 | + +11. 在**指标**面板中,选择**添加** > **指标**并将**聚合**设置为 **Count**。 + + ::: tip TIP + 在**指标**面板中选择**添加**,而不是**分桶**面板。 + ::: + +12. 选择**更新**。 + + 表格显示每个距离范围的平均航班延误和计数,如下图所示。 + + *按距离范围显示航班延误的数据表* + +## 显示多列 + +数据表始终至少包含一个指标。当**指标**面板包含单个指标时,面板不提供删除或禁用它的选项,因此基于聚合的数据表不能在没有指标列的情况下构建。要显示多列,请为每个字段添加一个分桶或 **Top Hit** 指标。 + +### 为您分组的每个字段添加一列 + +每个**拆分行**分桶向表格添加一列。 + +::: info NOTE +此示例从使用默认 **Count** 指标的新数据表开始。如果您从上一个过程继续,表格将保留 **DistanceMiles** 分桶和两个指标,因此会显示额外的列。 +::: + +要按承运人和目的地国家分组航班,请按照以下步骤操作: + +1. 在**分桶**面板中,选择**添加** > **拆分行**。 +1. 将**聚合**设置为**词条**,将**字段**设置为 **Carrier**。 +1. 再次选择**添加** > **拆分行**。 +1. 将**聚合**设置为**词条**,将**字段**设置为 **DestCountry**。 +1. 选择**更新**。 + +表格显示三列:**Carrier: 降序**、**DestCountry: 降序**和指标列。分桶列使用字段名称和分桶的排序顺序标记。分桶是嵌套的,因此每行将一个承运人与其文档中出现的一个目的地国家配对。 + +### 添加字段值列 + +**Top Hit** 指标返回直接从文档中获取的值,在数据表中它接受字符串字段以及数字字段。每个 **Top Hit** 指标成为一列字段值。要添加每个组最近航班的目的地城市,请按照以下步骤操作: + +1. 在**指标**面板中,选择**添加** > **指标**。 +1. 从**聚合**下拉列表中,选择 **Top Hit**。 +1. 从**字段**下拉列表中,选择 **DestCityName**。 +1. 验证**大小**设置为 `1`,**排序依据**设置为 **timestamp**,**顺序**设置为**降序**。 +1. 选择**更新**。 + +表格现在显示四列:**Carrier: 降序**、**DestCountry: 降序**、**Count** 和 **Last DestCityName**。每行报告承运人运营到该国家的航班数量以及其最近航班降落的城市,例如 `罗马` 或 `圣安东尼奥`。要为每个额外字段添加一列,请重复这些步骤并选择不同的字段。 + +::: info NOTE +**Top Hit** 返回每行桶中文档的值,因此表格仍然对文档进行分组。增加**大小**会在一个单元格中返回那么多值,但桶中的文档通常重复相同的值,因此单元格会多次列出一个城市。要让每个文档拥有自己的行,请参阅[列出单个文档](#列出单个文档)。 +::: + +## 列出单个文档 + +要构建一个每行是单个文档、每列是一个字段的表格,请在**发现**应用中保存搜索,而不是创建数据表。发现返回文档而不聚合它们,保存的搜索可以在与可视化相同的**添加面板**对话框中添加到仪表板。 + +要选择哪些字段显示为列,请参阅[使用字段选择工具](/dashboards/discover/field-select)。要将保存的搜索放置到仪表板上,请参阅[将可视化添加到仪表板](/dashboards/dashboard/adding-a-viz#adding-a-panel-to-a-dashboard)。 + +## 配置数据表 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/gauge.md b/i18n/zh/dashboards/visualize/visualize-app/gauge.md new file mode 100644 index 00000000..7b67a44b --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/gauge.md @@ -0,0 +1,76 @@ +--- +title: 仪表可视化 +--- + +# 仪表可视化 + +仪表可视化在类似速度表的模拟仪器中显示数据字段。仪表值可以立即与标记的范围或阈值进行比较。可视化可以显示单个值或多个分桶值。 + +## 何时使用仪表可视化 + +使用仪表可视化在仪表板中监控关键指标相对于可接受范围的情况。 + +## 创建仪表可视化 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建仪表可视化,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**仪表**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 + + ::: info NOTE + 可视化显示一个仪表,显示索引模式中文档的计数。对于 `opensearch_dashboards_sample_data_flights` 数据,如果日期范围包含所有文档,则为 `13059`。 + ::: + +2. 在**指标**下,展开**指标 count**。 +3. 将**聚合**设置为**中位数**,将**字段**设置为 **FlightTimeMin**。 +4. 选择**更新**。 + + 仪表显示 `502.775`,作为仪表的完整范围呈现。 + + ::: info NOTE + 如果您的可视化显示不同的值,请确保您的[时间过滤器](/dashboards/discover/time-filter)窗口足够大以包含所有示例航班数据。 + ::: + +5. 现在您已经对数据的量级有了一些了解,请更改显示范围,使显示的值落在其中。 + + 1. 选择**选项**选项卡。 + 2. 在**范围**面板中,按如下方式编辑三个默认范围: + + | 从 | 到 | + | :--- | :--- | + | 0 | 250 | + | 250 | 500 | + | 500 | 750 | + + 3. 选择**更新**。 + +6. 要在一个可视化中比较两种不同的条件,请对数据进行分桶。 + + 1. 在**分桶**下,选择**添加** > **拆分组**。 + 2. 将**聚合**设置为**词条**,将**字段**设置为 **FlightDelay**。 + 3. 选择**更新**。 + + 可视化显示两个仪表,分别显示延误和未延误航班的中位数飞行时间,如下图所示。 + + *按延误状态拆分显示中位数飞行时间的仪表* + +## 配置仪表可视化 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **范围** | 定义仪表弧的颜色编码段。每个范围有一个起始值和结束值。 | +| **百分比模式** | 启用后,将值显示为最大范围值的百分比。 | +| **显示刻度** | 启用后,在仪表上显示刻度标记。 | +| **颜色选项** | 控制分配给每个范围段的颜色。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/goal.md b/i18n/zh/dashboards/visualize/visualize-app/goal.md new file mode 100644 index 00000000..cb6b6ae2 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/goal.md @@ -0,0 +1,63 @@ +--- +title: 目标可视化 +--- + +# 目标可视化 + +目标可视化在类似速度表的仪表中显示一个值。它将值显示为预定义目标的比例。可视化还显示指标,可以是绝对值或目标的百分比。可视化可以显示单个值或多个分桶值。如果分桶,所有桶的目标相同。 + +## 何时使用目标可视化 + +使用目标可视化来监控关键指标相对于目标值的情况。 + +## 创建目标可视化 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建目标可视化,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**目标**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 + + ::: info NOTE + 可视化显示一个仪表,将文档计数显示为默认目标 `10,000` 的百分比。对于 `opensearch_dashboards_sample_data_flights` 数据,如果日期范围包含所有文档,则为 `130.59%`。 + ::: + +2. 在**指标**下,展开**指标 count**。 +3. 将**聚合**设置为**求和**,将**字段**设置为 **DistanceKilometers**。 +4. 要查看数据集距离记录总计一亿公里有多近,将 100,000,000 设置为目标: + + 1. 选择**选项**选项卡。 + 2. 在**范围**框中,输入 `1e8` 作为范围顶部。 + + ::: info NOTE + 数字输入不能使用分组分隔符。对大数字使用指数表示法。 + ::: + + 3. 取消选择**百分比模式**。 + 4. 选择**更新**。 + + 可视化显示 `92,616,288.34`,所有航班距离的总和(公里)。此值显示为仪表最大值的约 93%,该最大值校准为目标,如下图所示。 + + *显示总飞行距离朝向 1 亿公里目标的目标* + +5. (可选)通过添加刻度来组合仪表和目标显示,如[仪表可视化](/dashboards/visualize/visualize-app/gauge)中所述。 + +## 配置目标可视化 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **范围** | 定义目标范围。最大值代表目标。 | +| **百分比模式** | 启用后,将值显示为目标的百分比。 | +| **显示刻度** | 启用后,在进度条上显示刻度标记。 | +| **颜色选项** | 控制分配给每个范围段的颜色。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/heat-map.md b/i18n/zh/dashboards/visualize/visualize-app/heat-map.md new file mode 100644 index 00000000..875e30fc --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/heat-map.md @@ -0,0 +1,84 @@ +--- +title: 热力图 +--- + +# 热力图 + +热力图在二维网格上以颜色或饱和度渐变表示值,有效地呈现三维数据显示。X 和 Y 维度可以相同,如在空间热力图中,也可以不同——例如,在某个位置的平均温度记录中,月份对年份(从而分离该站点的周期性和趋势数据)。 + +## 何时使用热力图 + +使用热力图来揭示多维数据集中的聚类、相关强度和异常。它们使在表格格式或多个二维图中难以看到的模式变得可见。 + +## 创建热力图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建热力图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**热力图**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 +2. 在**指标**下,展开**值计数**并将**聚合**设置为 **Count**。 +3. 在**分桶**下,选择**添加** > **X 轴**。 +4. 将**聚合**设置为**词条**,将**字段**设置为 **OriginWeather**,将**大小**设置为 `8`。 +5. 选择**更新**。 +6. 在**分桶**下,选择**添加** > **Y 轴**。 +7. 将**子聚合**设置为**词条**,将**字段**设置为 **DestWeather**,将**大小**设置为 `8`。 +8. 选择**更新**。 + +### 自定义显示 + +1. 选择**选项**选项卡。 +2. 在**热力图设置**中,将**颜色方案**设置为**灰色**,将**颜色数量**设置为 `8`。 +3. 在**标签**中,启用**显示标签**。 +4. 选择**更新**。 + + 热力图显示映射到出发地和目的地天气组合的平均航班延误,如下图所示。 + + *按天气条件显示航班延误的热力图* + + 注意以下几点: + - 热力图数据被组织成四个象限,对应于目的地和出发地"好"(多云、雨、晴朗、晴天)和"坏"(冰雹、大雾、破坏性风、雷暴)天气条件的四种组合。 + - 当出发地和目的地天气都好时,延误最长。当两个地点天气都不好时,延误最短。 + +### 使用拆分图表过滤 + +::: info NOTE +您可以使用[过滤工具](/dashboards/discover/filter-tool)过滤数据,但如果可视化在仪表板中,这也会过滤其他可视化的数据。以下过程仅限制此可视化的数据。 +::: + +要将热力图限制为特定条件(例如,仅取消的航班): + +1. 在**分桶**下,选择**添加** > **拆分图表** > **行**。 +2. 将**子聚合**设置为**过滤器**。 +3. 在**过滤器 1** 框中,输入 `Cancelled: true`。 + + ::: tip TIP + 过滤器词条区分大小写。 + ::: + +4. 选择**更新**。 + + 热力图现在仅显示取消的航班。它显示当航班两端天气都好时没有发生取消,如下图所示。 + + *按天气条件显示取消航班的热力图* + +## 配置热力图 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **颜色方案** | 热力图的调色板(例如,**绿色**、**蓝色**、**灰色**、**黄色到橙色**)。 | +| **反转方案** | 反转颜色映射。 | +| **颜色数量** | 离散颜色桶的数量。 | +| **显示标签** | 在每个单元格内显示值。 | +| **百分比模式** | 将值标准化为 0 到 1 之间。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/index.md b/i18n/zh/dashboards/visualize/visualize-app/index.md new file mode 100644 index 00000000..934e637e --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/index.md @@ -0,0 +1,146 @@ +--- +title: 在可视化应用中创建可视化 +--- + +# 在可视化应用中创建可视化 + +**可视化**应用使用点击式界面从聚合创建数据可视化。您选择可视化类型,配置指标和分桶,并调整显示设置来构建图表、表格、地图和数据的其他可视化表示。 + +::: tip TIP +如果您是可视化应用的新手,请参阅[探索可视化应用](/dashboards/getting-started/explore-visualize)以获取使用示例数据的实践介绍。 +::: + +## 先决条件 + +本页面上的示例使用已安装在 [OpenSearch Playground](https://playground.opensearch.org/app/home#/) 中的[**示例航班数据**](https://playground.opensearch.org/app/home#/tutorial_directory)数据集。 + +如果您已安装本地 OpenSearch Dashboards 实例,请按照以下步骤添加示例数据: + +1. 在 OpenSearch Dashboards 主页上,选择**添加示例数据**。 +2. 在**示例航班数据**面板中,选择**添加数据**。 + +有关更多信息,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +要使用您自己的数据,您需要一个索引模式。请参阅[设置您的数据](/dashboards/getting-started/data-setup)。 + +## 导航可视化应用 UI + +下图显示了**可视化**应用的主要组件。 + +*可视化应用界面* + +- _搜索栏_(A)使用查询语言搜索启用数据选择。请参阅[使用搜索栏](/dashboards/discover/search-bar)。 +- _时间过滤器_(B)提供用于选择数据值和范围的图形界面。请参阅[使用时间过滤器](/dashboards/discover/time-filter)。 +- _过滤工具_(C)包含常用命令和快捷方式。请参阅[使用过滤工具](/dashboards/discover/filter-tool)。 +- _可视化面板_(D)显示可视化。 +- _配置面板_(E)包含用于选择和配置可视化的所有控件。其内容取决于可视化类型。请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +## 创建可视化 + +要创建可视化,请按照以下步骤操作: + +1. 在左侧导航菜单中,选择 **OpenSearch Dashboards** > **可视化**。 + + 应用显示**可视化**列表,这是一个已保存可视化的表格。 + +1. 在右上角,选择**创建可视化**。 + + 应用显示**新建可视化**对话框,如下图所示。 + + *新建可视化对话框* + +1. 通过选择其图标来选择可视化类型。有关选择类型的帮助,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 + +1. 如果出现提示,请在**选择数据源**对话框中选择索引模式。并非所有可视化类型都显示此对话框。有关创建每种可视化类型的示例,请参阅各个可视化类型页面。 + + 默认可视化显示当前数据集的单个值,即文档计数。 + + ::: tip TIP + 如果可视化显示无数据,或计数与预期不同,请验证[搜索栏](/dashboards/discover/search-bar)、[过滤工具](/dashboards/discover/filter-tool),尤其是[时间过滤器](/dashboards/discover/time-filter)是否过滤掉了缺失的文档。 + ::: + +1. 配置可视化。有关更多信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)或各个可视化类型页面。有关完整示例,请参阅[探索可视化应用](/dashboards/getting-started/explore-visualize)。 + +## 创建可视化的其他方式 + +除了**可视化**应用外,您还可以从以下位置开始创建新的可视化: + +- 要从[工作区](/dashboards/workspace/)创建可视化(如果启用了工作区),请按照以下步骤操作: + + 1. 在主页上,选择或创建一个[工作区](/dashboards/workspace/)。 + 1. 在左侧导航菜单中,展开**可视化和报告**并选择**可视化**。 + 1. 选择**创建新可视化**。 + +- 要从仪表板创建可视化,请按照以下步骤操作: + + 1. 在左侧导航菜单中,选择 **OpenSearch Dashboards** > **仪表板**。 + 1. 打开现有仪表板或创建新仪表板。 + 1. 选择**编辑**。 + 1. 在工具栏中选择**新建**,或选择**添加**(或加号图标),然后在**添加面板**对话框中选择**新建**。 + + ::: info NOTE + 当您从仪表板创建可视化时,保存时它会自动添加到该仪表板。 + ::: + +## 保存可视化 + +::: danger WARNING +如果您离开应用,您的可视化将保留在**可视化**应用中。但是,如果您在不保存可视化的情况下再次选择**可视化**应用,对可视化的更改将丢失。我们建议您在离开**可视化**应用之前始终保存您的可视化。 +::: + +### 保存新可视化 + +要保存新可视化,请按照以下步骤操作: + +1. 在**创建**面板的右上角选择**保存**。 + + 应用显示**保存可视化**对话框。 + +1. 在**标题**框中输入可视化的标题。 + +1. (可选)输入**描述**。 + +1. 选择**保存**。 + +### 保存现有可视化 + +您可以随时保存可视化,次数不限。 + +要保存现有可视化,请按照以下步骤操作: + +1. 在**创建**面板的右上角选择**保存**。 + + 如果您之前已保存可视化,**保存可视化**的**标题**框将包含可视化标题。 + +1. (可选)要更改可视化名称,请在**标题**框中输入新标题。 + +1. (可选)更新**描述**。 + +1. (可选)要保持已保存可视化的当前状态并将更改保存为新可视化,请选择**另存为新可视化**。 + + ::: danger WARNING + 在不选择**另存为新可视化**的情况下保存现有可视化将覆盖可视化的先前状态,即使您已重命名可视化也是如此。 + ::: + +1. 要保存当前更改,请选择**保存**按钮。 + +## 将可视化添加到仪表板 + +要将已保存的可视化添加到仪表板,请按照以下步骤操作: + +1. 打开一个[仪表板](/dashboards/dashboard/)。 +1. 选择**编辑**。 +1. 在工具栏中选择**添加**或加号图标。如果出现提示,选择**从库中**。 +1. 从列表中选择已保存的可视化。 + +可视化将作为面板显示在仪表板上。您可以调整其大小、重新定位,并与其他面板一起配置它。 + +## 试一试 + +有关使用示例数据创建折线图的实践演练,请参阅[探索可视化应用](/dashboards/getting-started/explore-visualize)。 + +## 后续步骤 + +- 要了解如何使用示例数据创建各种可视化,请参阅[创建基于聚合的可视化](/dashboards/visualize/visualize-app/aggregation-based-viz)。 +- 有关选择可视化类型的帮助,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要了解如何将可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/line-charts.md b/i18n/zh/dashboards/visualize/visualize-app/line-charts.md new file mode 100644 index 00000000..6957c3d1 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/line-charts.md @@ -0,0 +1,65 @@ +--- +title: 折线图 +--- + +# 折线图 + +折线图在 Y 轴上显示一个或多个数值数据点系列,这些数据点绑定到 X 轴上的数值字段。这些点可以用线连接。X 轴值可以是时间线或任何其他连续或离散数字系列。 + +## 何时使用折线图 + +使用折线图来揭示趋势、周期性行为、变化率信息以及跨时间或任何连续数值量的拐点。使用多条线显示指标之间的相关性。 + +## 创建折线图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建折线图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**折线**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 +2. 在**指标**下,展开 **Y 轴 Count**。 +3. 将**聚合**设置为**平均值**,将**字段**设置为 **AvgTicketPrice**。 +4. (可选)输入**自定义标签**,例如 `平均票价`。 +5. 选择**更新**。 + + 图表显示一个高度略高于 `$600` 的单个条形,这是航班数据库中每个文档的平均票价。 + + ::: info NOTE + 如果您的可视化显示不同的值,请确保您的时间过滤器窗口足够大以包含所有示例航班数据。 + ::: + +6. 在**分桶**下,选择**添加** > **X 轴**。 +7. 将**聚合**设置为**直方图**,将**字段**设置为 **DistanceKilometers**。 +8. 选择**更新**。 + + 图表显示平均票价作为分桶飞行距离的函数。 + +### 添加拆分系列 + +1. 在**分桶**下,选择**添加** > **拆分系列**。 +2. 将**子聚合**设置为**词条**,将**字段**设置为 **dayOfWeek**,将**排序依据**设置为**字母顺序**,将**大小**设置为 `7`。 +3. 选择**更新**。 + + 平均票价按工作日值显示在七条不同的线中,如下图所示。工作日值键 5 和 6 的平均票价在大多数飞行距离上明显更高。 + + *按星期几显示平均票价与距离比较的折线图* + +## 配置折线图 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 指标和坐标轴选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **图表类型** | 按系列覆盖。支持**折线**、**面积**、**条形**。 | +| **模式** | **正常**重叠线条。与面积/条形类型组合时,**堆叠**可用。 | +| **线条模式** | **直线**、**平滑**或**阶梯**。 | +| **Y 轴刻度** | **线性**、**对数**或**平方根**。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/maps-stats-api.md b/i18n/zh/dashboards/visualize/visualize-app/maps-stats-api.md new file mode 100644 index 00000000..75f52b09 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/maps-stats-api.md @@ -0,0 +1,131 @@ +--- +title: 地图统计 API +--- + +# 地图统计 API +<Badge type="tip" text="2.7 版本引入" /> + +当您在 OpenSearch Dashboards 中创建并保存[地图](/dashboards/visualize/maps)时,地图将成为 `map` 类型的已保存对象。地图统计 API 提供有关 OpenSearch Dashboards 中此类已保存对象的信息。 + +#### 示例请求 + +您可以通过以以下格式提供 URL 地址来访问地图统计 API: + +``` +{opensearch-dashboards-endpoint-address}/api/maps-dashboards/stats +``` + +::: info NOTE +如果在 OpenSearch 配置文件中指定了端口号,OpenSearch Dashboards 端点地址可能包含端口号。具体的 URL 格式取决于 OpenSearch 部署类型及其托管的网络环境。 +::: + +您可以通过两种方式查询端点: + + - 在浏览器中访问端点地址(例如 `http://localhost:5601/api/maps-dashboards/stats`) + + - 在终端中使用 `curl` 命令: + ```bash + curl -X GET http://localhost:5601/api/maps-dashboards/stats + ``` + +#### 示例响应 + +以下是上述请求的响应: + +```json +{ + "maps_total":4, + "layers_filters_total":4, + "layers_total":{ + "opensearch_vector_tile_map":2, + "documents":7, + "wms":1, + "tms":2 + }, + "maps_list":[ + { + "id":"88a24e6c-0216-4f76-8bc7-c8db6c8705da", + "layers_filters_total":4, + "layers_total":{ + "opensearch_vector_tile_map":1, + "documents":3, + "wms":0, + "tms":0 + } + }, + { + "id":"4ce3fe50-d309-11ed-a958-770756e00bcd", + "layers_filters_total":0, + "layers_total":{ + "opensearch_vector_tile_map":0, + "documents":2, + "wms":0, + "tms":1 + } + }, + { + "id":"af5d3b90-d30a-11ed-a605-f7ad7bc98642", + "layers_filters_total":0, + "layers_total":{ + "opensearch_vector_tile_map":1, + "documents":1, + "wms":0, + "tms":1 + } + }, + { + "id":"5ca1ec10-d30b-11ed-a042-93d8ff0f09ee", + "layers_filters_total":0, + "layers_total":{ + "opensearch_vector_tile_map":0, + "documents":1, + "wms":1, + "tms":0 + } + } + ] +} +``` + +## 响应正文字段 + +响应包含以下图层类型的统计信息: + +- 底图:默认 OpenSearch 地图或自定义基础图层地图。 + +- WMS 图层:自定义 WMS 基础图层地图。 + +- TMS 图层:自定义 TMS 基础图层地图。 + +- 文档图层:地图的数据图层。 + +有关图层类型的更多信息,请参阅[添加图层](/dashboards/visualize/maps#adding-layers)。 + +下表列出了所有响应字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `maps_total` | 整数 | 注册为地图插件已保存对象的地图总数。 | +| `layers_filters_total` | 整数 | 所有地图中所有图层的过滤器总数。这包括[图层级别过滤器](/dashboards/visualize/maps#filtering-data-at-the-layer-level),但不包括[形状过滤器](/dashboards/visualize/maps#drawing-shapes-to-filter-data)等全局过滤器。 | +| `layers_total` | 对象 | 所有地图中所有图层的统计总计。 | +| `layers_total.opensearch_vector_tile_map` | 整数 | 所有地图中 OpenSearch 底图的总数。 | +| `layers_total.documents` | 整数 | 所有地图中文档图层的总数。 | +| `layers_total.wms` | 整数 | 所有地图中 WMS 图层的总数。 | +| `layers_total.tms` | 整数 | 所有地图中 TMS 图层的总数。 | +| `maps_list` | 数组 | 保存在 OpenSearch Dashboards 中的所有地图的列表。 | + +`map_list` 中的每个地图包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `id` | 字符串 | 地图的已保存对象 ID。 | +| `layers_filters_total` | 整数 | 地图中所有图层的过滤器总数。这包括[图层级别过滤器](/dashboards/visualize/maps#filtering-data-at-the-layer-level),但不包括[形状过滤器](/dashboards/visualize/maps#drawing-shapes-to-filter-data)等全局过滤器。 | +| `layers_total` | 对象 | 地图中所有图层的统计总计。 | +| `layers_total.opensearch_vector_tile_map` | 整数 | 地图中 OpenSearch 底图的总数。 | +| `layers_total.documents` | 整数 | 地图中文档图层的总数。 | +| `layers_total.wms` | 整数 | 地图中 WMS 图层的总数。 | +| `layers_total.tms` | 整数 | 地图中 TMS 图层的总数。 | + +::: tip TIP +已保存对象 ID 有助于您导航到特定地图,因为 ID 是地图 URL 的最后部分。例如,在 OpenSearch Playground 中,`[Flights] Flights Status on Maps Destination Location` 地图的地址是 `https://playground.opensearch.org/app/maps-dashboards/88a24e6c-0216-4f76-8bc7-c8db6c8705da`,其中 `88a24e6c-0216-4f76-8bc7-c8db6c8705da` 是此地图的已保存对象 ID。 +::: diff --git a/i18n/zh/dashboards/visualize/visualize-app/maps.md b/i18n/zh/dashboards/visualize/visualize-app/maps.md new file mode 100644 index 00000000..346ac8f6 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/maps.md @@ -0,0 +1,269 @@ +--- +title: 地图应用 +--- + +# 地图应用 + +**地图**应用创建具有多个图层的地图可视化,可以跨不同索引组合数据。您可以从不同的索引模式构建每个图层,并配置地图在不同缩放级别显示特定数据。OpenSearch 地图由 OpenSearch 地图服务提供支持,该服务使用矢量切片渲染地图。 + +## 何时使用地图应用 + +当您需要多层地理可视化来组合来自不同索引的数据、按地理形状过滤、自定义底图、工具提示或标签时,请使用地图应用。对于更简单的单层地理可视化,请考虑[坐标地图](/dashboards/visualize/visualize-app/coordinate-maps)或[区域地图](/dashboards/visualize/visualize-app/region-maps)。 + +## 创建新地图 + +您可以通过执行以下步骤从**地图**或**可视化**工作流程创建新地图: + +- 要从**地图**工作流程创建新地图,请执行以下步骤: + + 1. 在顶部菜单栏中,转到 **OpenSearch 插件 > 地图**。 + 1. 选择**创建地图**按钮。 + +- 要从**可视化**工作流程创建新地图,请执行以下步骤: + + 1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 可视化**。 + 1. 选择**创建可视化**按钮。 + 1. 在**新建可视化**对话框中,选择**地图**。 + +现在您可以看到默认的 OpenSearch 底图。 + +要查看**默认地图**图层配置,请在地图左上角的**图层**面板中选择**默认地图**,如下图所示。 + +![默认地图](/images/maps/maps-default.png) + +::: tip TIP +要隐藏**图层**面板,请选择面板右上角的折叠(箭头)图标。 +::: + +## 图层设置 + +要更改默认地图设置,请在**图层**面板中选择**默认地图**。在**图层设置**下,您可以更改图层名称和描述,并为图层配置缩放级别和不透明度: + +- **缩放级别**:默认情况下,图层在所有缩放级别都可见。如果您希望图层仅在特定缩放级别范围内可见,可以通过在文本框中输入或将范围滑块滑动到所需值来指定缩放级别。 + +- **不透明度**:如果您的地图包含多个图层,一个图层可能会遮挡另一个图层。在这种情况下,您可能希望降低顶层图层的不透明度,以便同时看到两个图层。 + +## 添加图层 + +要向地图添加图层,请在**图层**面板中选择**添加图层**按钮。**添加图层**对话框如下图所示。 + +![添加图层](/images/maps/add-layer.png) + +您可以向地图添加**基础图层**或**数据图层**: + +- **基础图层**用作底图。要使用您自己的或第三方地图作为基础图层,请[将其添加为**自定义地图**](#adding-a-custom-map)。 + +- **数据图层**让您可以从各种数据源可视化数据。 + +## 添加自定义地图 + +OpenSearch 支持 Web 地图服务(WMS)或切片地图服务(TMS)自定义地图。要添加 TMS 自定义地图,请执行以下步骤: + +1. 在**图层**面板中,选择**添加图层**按钮。 +1. 从**添加图层**对话框中,选择**基础图层 > 自定义地图**。 + 按照**新建图层**对话框中的后续步骤操作,如下图所示。 + + ![添加自定义地图](/images/maps/custom-map.png) + +1. 在**自定义类型**下拉列表中,选择**切片地图服务(TMS)**。 +1. 输入 TMS URL。 +1. (可选)在 **TMS 属性**中,输入底图的 TMS 属性。例如,如果您使用自定义底图,请输入自定义地图名称。此名称显示在地图的右下角。 +1. 选择**设置**选项卡以编辑图层设置。 +1. 在**名称**中输入图层名称。 +1. (可选)在**描述**中输入图层描述。 +1. (可选)选择此图层的缩放级别和不透明度。 +1. 选择**更新**按钮。 + +## 添加文档图层 + +添加文档图层让您可以可视化您的数据。每个文档图层可以添加一个索引模式。要查看多个索引模式,请创建多个图层。 + +::: info NOTE +文档图层可以显示地理点和地理形状文档字段。 +::: + +以下示例假设您已安装 `opensearch_dashboards_sample_data_flights` 数据集。如果您没有安装此数据集,请执行以下步骤: + +1. 在左上角,选择主页图标。 +1. 选择**添加示例数据**。 +1. 在**示例航班数据**面板中,选择**添加数据**按钮。 + +按以下方式添加文档图层: + +1. 在**图层**面板中,选择**添加图层**按钮。 +1. 从**添加图层**对话框中,选择**数据图层 > 文档**。 +1. 在**数据源**中,选择 `opensearch_dashboards_sample_data_flights`。或者,您可以输入其他索引模式进行可视化。 +1. 在**地理空间字段**中,选择要在可视化中显示的地理空间字段(地理点或地理形状)。在此示例中,选择 `DestLocation`。 +1. (可选)选择**样式**选项卡以更改填充颜色、边框颜色、边框粗细或标记大小。 +1. 选择**设置**选项卡以编辑图层设置。 +1. 在**名称**中输入 `航班目的地`。 +1. 选择**更新**按钮。 +1. 要查看更多数据,在右上角选择日历图标下拉列表,然后在**快速选择**下选择**最近 15 天**并选择**应用**按钮。 + +您应该看到航班目的地数据,如下图所示。 + +![航班目的地地图](/images/maps/new-layer.png) + +## 过滤数据 + +要显示索引中数据的子集,请过滤数据。您可以在图层级别过滤数据,也可以在地图上绘制形状以全局过滤所有图层数据。 + +### 在图层级别过滤数据 + +要在图层级别过滤数据,请选择图层并向其添加过滤器。 + +以下示例展示如何过滤航班目的地数据以仅显示美国目的地: + +1. 在**图层**面板中,选择**航班目的地**。 +1. 选择**过滤器**。 +1. 选择**添加过滤器**。 +1. 在**编辑过滤器**中,在**字段**中选择 **DestCountry**。 +1. 在**运算符**中,选择**是**。 +1. 在**值**中,选择 **US**。 +1. 选择**保存**按钮。 +1. 选择**更新**按钮。 + +::: tip TIP +对于大型数据集,您可能希望避免加载完整地图的数据。要仅加载特定地理区域的数据,请选择**仅请求地图范围周围的数据**。 +::: + +### 绘制形状以过滤数据 + +您可以通过在地图上绘制[形状](/mappings/supported-field-types/geo-shape/)来全局过滤数据。要在地图上绘制矩形或多边形,请执行以下步骤: + +1. 选择地图右侧的**矩形**或**多边形**图标。 +1. 在**过滤器标签**字段中,输入过滤器的名称。 +1. 选择空间关系类型。默认选择**相交**。有关空间关系类型的更多信息,请参阅[空间关系](/query-dsl/geo-and-xy/xy#spatial-relations)。 +1. 选择**绘制矩形**或**绘制多边形**按钮。 +1. 在您要选择的地图区域上绘制形状: + - 对于矩形,选择地图上的任意起点(此点成为矩形顶点)。然后悬停(不要拖动)到地图上的另一点并选择它(此点成为对角顶点)。 + - 对于多边形,选择地图上的任意起点(此点成为多边形顶点)并悬停(不要拖动)到每个后续顶点并选择该点。最后,确保再次选择起点以闭合多边形,如下图所示。 + +![在地图上绘制多边形](/images/maps/draw-shape.png) + +### 为地图图层禁用形状过滤器 + +默认情况下,形状过滤器全局应用于地图上的所有图层。如果您要为地图图层禁用形状过滤器,请执行以下步骤: +1. 从**图层**面板中选择图层。 +1. 在**过滤器**部分,取消选择**应用全局过滤器**。 +1. 选择**更新**按钮。 + +### 修改现有形状过滤器 + +要修改现有形状过滤器,请在地图上方左侧选择您的过滤器。您可以对现有过滤器执行以下操作: + +- **编辑过滤器**:更改过滤器名称或修改形状的坐标。 +- **排除结果**:反转过滤器,即显示除过滤器适用的数据点之外的所有数据点。 +- **临时禁用**:禁用过滤器直到您选择**重新启用**。 +- **删除**:完全删除您的过滤器。 + +## 使用工具提示可视化其他数据 + +文档图层将地理点和地理形状文档字段显示为地图上的位置。要向位置添加更多信息,您可以使用工具提示。例如,您可能希望在**航班目的地**图层中显示航班延误、目的地天气和目的地国家信息。执行以下步骤配置工具提示以显示其他数据: + +1. 在**图层**面板中,选择**航班目的地**。 +1. 选择**工具提示**。 +1. 选中**显示工具提示**复选框。 +1. 在**工具提示字段**下拉列表中,选择您要显示的字段。在此示例中,选择 `FlightDelay`、`DestWeather` 和 `DestCountry`。 +1. 选择**更新**按钮。 + +要查看工具提示,请将鼠标悬停在您感兴趣的地理点上。一个工具提示可以显示多个数据点。例如,在**航班目的地**图层中,单个目的地城市有多个航班。要分页浏览航班,请选择您感兴趣的城市并使用工具提示中的箭头,如下图所示。 + +![航班目的地工具提示](/images/maps/tooltip.png) + +如果地图上的一个点包含来自多个图层的数据,一个工具提示可以显示来自多个图层的数据。要查看所有图层,请选择**所有图层**。要选择特定图层,请在工具提示图层选择面板中选择图层名称,如下图所示。 + +![带有图层选择面板的工具提示](/images/maps/layer-selection-panel.png) + +## 向图层添加标签 + +向图层添加标签让您可以在地图上可视化其他数据。例如,您可能希望在**航班目的地**图层中查看出发地天气。执行以下步骤向**航班目的地**图层添加标签: + +1. 在**图层**面板中,选择**航班目的地**。 +1. 在**样式**选项卡中,选中**添加标签**复选框。 +1. 您可以选择向图层中的所有数据点添加基于固定文本的标签,或使用字段值作为标签文本。 + - 要添加固定文本标签,在**标签文本**下选择**固定**并输入所需的标签文本。 + - 要添加基于字段值的标签,在**标签文本**下选择**字段值**并选择字段名称。在此示例中,选择 `OriginWeather`。 +1. (可选)更改标签大小、颜色、边框颜色或边框宽度。 +1. 选择**更新**按钮。 + +带有出发地天气的标签在地图上可见,也添加到工具提示中,如下图所示。 + +![基于字段类型的标签添加到地图和工具提示](/images/maps/label.png) + +## 重新排序、隐藏和删除图层 + +**图层**面板让您可以重新排序、隐藏和删除图层: + +- 地图上的图层相互堆叠。要重新排序图层,请使用图层名称旁边的手柄(两条水平线)图标将图层拖动到所需位置。 + +- 如果您想隐藏图层,请选择图层名称旁边的显示/隐藏(眼睛)图标。切换显示/隐藏图标以再次显示图层。 + +- 要删除图层,请选择图层名称旁边的删除(垃圾箱)图标。 + +## 为实时数据集刷新数据 + +如果您想可视化实时数据集,在向地图添加图层后,执行以下步骤设置刷新间隔: + +1. 选择右上角的日历图标。 +1. 在**每隔刷新**下,选择或输入刷新间隔(例如 1 秒)。 +1. 选择**开始**按钮。 + +![刷新地图](/images/maps/refresh.png) + +## 保存地图 + +要保存带有您设置的所有图层的地图,请执行以下步骤: + +1. 选择右上角的**保存**按钮。 +1. 在**保存地图**对话框中,在**标题**文本框中输入地图名称。 +1. (可选)在**描述**文本框中输入地图描述。 +1. 选择**保存**按钮。 + +要打开您保存的地图,请在左上角选择**地图**。将显示已保存地图的列表。 + +## 将地图添加到仪表板 + +您可以通过执行以下步骤将新地图或现有地图添加到新仪表板或现有仪表板: + +- 要将地图添加到新仪表板,首先按以下方式创建仪表板: + + 1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 仪表板**。 + 1. 选择**创建仪表板**按钮。 + 1. 选择**新建**按钮。 + +- 要将地图添加到现有仪表板,首先按以下方式打开仪表板: + 1. 在顶部菜单栏中,转到 **OpenSearch Dashboards > 仪表板**。 + 1. 从列表中选择要打开的仪表板。 + 1. 在右上角,选择**编辑**。 + +打开仪表板后,您可以向其添加新地图或现有地图。 + +### 添加现有地图 + +1. 从顶部菜单中,选择**添加**。 +1. 在**类型**下拉列表中,选择**地图**。 +1. 从列表中选择要添加的地图。 + +### 添加新地图 + +1. 从顶部菜单中,选择**新建**按钮。 +1. 在**新建可视化**对话框中,选择**地图**。 +1. 通过添加底图、图层或工具提示来编辑默认地图。 +1. 在右上角,选择**保存**按钮。 +1. 在**保存地图**对话框中,输入地图的**标题**和可选**描述**。 +1. 选择**保存后添加到仪表板**(此选项默认选中)。 +1. 选择**保存并返回**按钮。 + +## 从仪表板编辑地图 + +1. 在仪表板中,选择要编辑的地图右上角的齿轮图标。 +1. 选择**编辑地图**。 +1. 编辑地图。 +1. 在右上角,选择**保存**按钮。 +1. 在**保存地图**对话框中,选择**保存并返回**按钮。 + +## 相关文档 + +- [地图统计 API](/dashboards/visualize/maps-stats-api) +- [配置地图](/dashboards/visualize/visualize-app/configuring-maps) diff --git a/i18n/zh/dashboards/visualize/visualize-app/maptiles.md b/i18n/zh/dashboards/visualize/visualize-app/maptiles.md new file mode 100644 index 00000000..b8a61512 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/maptiles.md @@ -0,0 +1,27 @@ +--- +title: 配置 Web 地图服务(WMS) +--- + +# 配置 Web 地图服务 + +开放地理空间联盟(OGC)Web 地图服务(WMS)规范是用于在 Web 上请求动态地图的国际规范。OpenSearch Dashboards 包含默认地图切片。对于专业地图,您可以按照以下步骤在 OpenSearch Dashboards 上配置 WMS: + +1. 登录 OpenSearch Dashboards,地址为 `https://<host>:<port>`。例如,您可以通过连接到 [https://localhost:5601](https://localhost:5601) 来连接 OpenSearch Dashboards。默认用户名和密码为 `admin`。 +2. 选择**管理** > **高级设置**。 +3. 找到 `visualization:tileMap:WMSdefaults`。 +4. 将 `enabled` 更改为 `true` 并添加有效 WMS 服务器的 URL,如以下示例所示: + + ```json + { + "enabled": true, + "url": "{wms-map-server-url}", + "options": { + "format": "image/png", + "transparent": true + } + } + ``` + +::: info NOTE +Web 地图服务可能有许可费或限制,您有责任遵守任何此类费用或限制。 +::: diff --git a/i18n/zh/dashboards/visualize/visualize-app/markdown.md b/i18n/zh/dashboards/visualize/visualize-app/markdown.md new file mode 100644 index 00000000..0217de60 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/markdown.md @@ -0,0 +1,45 @@ +--- +title: Markdown 可视化 +--- + +# Markdown 可视化 + +Markdown 可视化在仪表板面板中渲染格式化文本。使用 Markdown 在数据可视化旁边提供标题、说明、指标定义和解释性上下文。Markdown 支持标题、列表、粗体和斜体文本、链接、块引用和代码块(GitHub 风格的 Markdown)。 + +Markdown 可视化不需要数据源。 + +## 何时使用 Markdown 可视化 + +使用 Markdown 可视化添加帮助您解释仪表板上数据的上下文。常见用例包括: + +- 仪表板标题和章节标题 +- 与过滤器和控件交互的说明 +- 其他面板中显示的关键指标的定义 +- 相关仪表板或外部文档的链接 +- 状态说明,如数据刷新间隔或维护计划 + +## 创建 Markdown 可视化 + +1. 在**新建可视化**对话框中,选择 **Markdown**。 +2. 在**数据**选项卡的 **Markdown** 文本框中,输入您的 Markdown 内容。 +3. 选择**更新**以预览渲染输出,如下图所示。 + +*显示仪表板指南的 Markdown 可视化* + +4. (可选)选择**选项**选项卡以调整基本字体大小或启用**在新标签页中打开链接**。 + +## 配置 Markdown 可视化 + +以下设置在**选项**选项卡上可用。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **字体大小** | 控制渲染文本的基本字体大小。 | +| **在新标签页中打开链接** | 启用后,Markdown 中的链接在新浏览器标签页中打开。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/metric.md b/i18n/zh/dashboards/visualize/visualize-app/metric.md new file mode 100644 index 00000000..99358150 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/metric.md @@ -0,0 +1,46 @@ +--- +title: 指标可视化 +--- + +# 指标可视化 + +指标可视化显示单个数据字段。可视化可以显示单个值或多个分桶值。将指标可视化用于仪表板上的关键指标,尤其是频繁更新的值。 + +## 何时使用指标可视化 + +使用指标可视化来一目了然地传达关键业务或运营值,尤其是需要持续监控的实时或频繁更新的值,如系统健康状况、业务绩效或运营状态。 + +## 创建指标可视化 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建指标可视化,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**指标**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 + + ::: info NOTE + 可视化显示索引模式中文档的计数。对于 `opensearch_dashboards_sample_data_flights` 数据,如果日期范围包含所有文档,则为 `13059`。 + ::: + +2. 在**指标**下,展开**指标 Count**。 +3. 将**聚合**设置为**平均值**,将**字段**设置为 **DistanceKilometers**。 +4. 选择**更新**。 + + 可视化显示 `7092.142`,航班数据库中每个文档的平均距离(公里)。 + + ::: info NOTE + 如果您的可视化显示不同的值,请确保您的[时间过滤器](/dashboards/discover/time-filter)窗口足够大以包含所有示例航班数据。 + ::: + + *显示平均飞行距离的指标可视化* + +## 配置指标可视化 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/pie-charts.md b/i18n/zh/dashboards/visualize/visualize-app/pie-charts.md new file mode 100644 index 00000000..6eac2d73 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/pie-charts.md @@ -0,0 +1,74 @@ +--- +title: 饼图 +--- + +# 饼图 + +饼图显示每个条件占数据字段整个计数的百分比。可视化可以显示单个值或多个分桶值。 + +## 何时使用饼图 + +使用饼图比较组成指标的每个条件的相对份额。您可以选择饼图扇区来过滤同一仪表板上的其他可视化。 + +## 创建饼图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建饼图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**饼图**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 + + ::: info NOTE + 可视化显示一个环形饼图,仅显示一个值。工具提示显示该值,即索引模式中文档的计数。对于 `opensearch_dashboards_sample_data_flights` 数据,如果日期范围包含所有文档,则为 `13059`。 + ::: + + ::: info NOTE + 如果您的可视化显示不同的值,请确保您的[时间过滤器](/dashboards/discover/time-filter)窗口足够大以包含所有示例航班数据。 + ::: + +2. 在**指标**下,展开**切片大小 count**。 +3. 将**聚合**设置为**唯一计数**,将**字段**设置为 **FlightNum**。 + + 对于饼图,指标的分桶值必须合计为 100%。仅显示具有此属性的聚合。 + +4. 选择**更新**。 + + 饼图显示 `12,932`,以单值环形饼图呈现。 + +5. 要可视化字段在不同条件下的组成,请对数据进行分桶: + + 1. 在**分桶**下,选择**添加** > **拆分切片**。 + 2. 将**聚合**设置为**词条**,将**字段**设置为 **OriginCountry**,将**大小**设置为 `5`。 + 3. 选择**将其他值分组到单独的桶中**,以便准确表示唯一航班的总数。 + 4. 选择**更新**。 + + 可视化显示意大利和美国是航班出发地最多的国家。前五个国家占唯一航班号的近一半。 + +6. (可选)将可视化显示为传统饼图而非环形饼图: + + 1. 选择**选项**选项卡。 + 2. 在饼图设置面板中,取消选择**甜甜圈**。 + 3. 选择**更新**。 + + 可视化显示前五个国家的楔形饼图,其他国家分组在一起,如下图所示。 + + *按出发国家显示唯一航班的饼图* + +## 配置饼图 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **甜甜圈** | 启用后,将图表渲染为环形(甜甜圈)而非实心圆。 | +| **显示标签** | 在每个切片上显示类别标签。 | +| **仅显示顶层** | 存在嵌套分桶时,仅显示最外层环。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/ppl.md b/i18n/zh/dashboards/visualize/visualize-app/ppl.md new file mode 100644 index 00000000..006f042f --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/ppl.md @@ -0,0 +1,44 @@ +--- +title: PPL 可视化 +--- + +# PPL 可视化 + +管道处理语言(PPL)可视化使用 PPL 查询进行数据处理和可视化。从**新建可视化**对话框中选择 **PPL** 会打开可观测性日志资源管理器,您可以在其中编写 PPL 查询并将结果映射到图表。 + +## 何时使用 PPL 可视化 + +当您想直接使用 PPL 管道语法编写查询而不是通过点击式界面配置聚合时,使用 PPL 可视化。有关更多信息,请参阅[可观测性](/observing-your-data/)和[探索数据](/observing-your-data/exploring-observability-data/)。 + +## 创建 PPL 可视化 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建 PPL 可视化,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择 **PPL**。可观测性日志资源管理器打开。 +2. 在 PPL 查询栏中,输入查询。例如: + + ```sql + source = opensearch_dashboards_sample_data_flights | stats count() by Carrier + ``` + +3. 将时间过滤器设置为包含数据的范围(例如,选择**过去 7 天**)。 +4. 选择**运行**。 +5. 选择**可视化**选项卡以查看图表。 +6. (可选)使用右侧的图表类型选择器更改图表类型(例如,**饼图**)。 + +资源管理器自动将查询结果字段映射到图表。**配置**面板显示**系列**(指标)和**维度**(分组字段),如下图所示。 + +*PPL 可视化显示按承运人统计航班数量的饼图* + +## 相关文档 + +- [使用查询创建可视化](/dashboards/visualize/visualization-editor/) + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/region-maps.md b/i18n/zh/dashboards/visualize/visualize-app/region-maps.md new file mode 100644 index 00000000..84f77032 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/region-maps.md @@ -0,0 +1,116 @@ +--- +title: 区域地图 +--- + +# 区域地图 + +区域地图根据聚合值为地理区域(国家、州或县)着色,使用颜色强度显示指标在各区域间的变化。 + +## 何时使用区域地图 + +使用区域地图比较按地理边界聚合的数据值,例如按国家的销售额、按州的人口或按县的事件。对于多图层地理可视化,请使用[地图应用](/dashboards/visualize/maps)。 + +## 创建区域地图 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建区域地图,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**区域地图**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 +2. 将时间过滤器设置为**过去 7 天**。 +3. 在**分桶**下,选择**添加** > **形状字段**。 +4. 将**聚合**设置为**词条**,将**字段**设置为 **OriginCountry**。 +5. 选择**更新**。 + +地图按航班计数为每个国家着色,如下图所示。 + +*按出发国家显示航班计数的区域地图* + +### 自定义地图显示 + +1. 选择**选项**选项卡。 +2. 在**图层设置**下,选择矢量地图(例如,**世界各国**)。 +3. 在**连接字段**中,选择矢量地图中与您的数据匹配的字段(例如,`ISO 3166-1 alpha-2`)。 +4. 在**样式设置**下,调整颜色方案。 +5. 选择**更新**。 + +## 使用 GeoJSON 自定义矢量地图 + +如果内置矢量地图不包含您需要的区域(例如,美国县或邮政编码),您可以上传自定义 GeoJSON 文件。 + +::: info NOTE +要使用带有 GeoJSON 的自定义矢量地图,请安装以下插件: +- OpenSearch Dashboards Maps [`dashboards-maps`](https://github.com/opensearch-project/dashboards-maps) 前端插件 +- OpenSearch [`geospatial`](https://github.com/opensearch-project/geospatial) 后端插件 +::: + +### 上传自定义 GeoJSON 文件 + +1. 准备一个扩展名为 `.geojson` 或 `.json` 的 JSON 文件。 +2. 在**区域地图**编辑器中,在右侧面板中选择**导入矢量地图**。 +3. 在**上传地图**中,选择或拖放您的 JSON 文件。 +4. 输入**地图名称前缀**(例如,`usa-counties`)。地图名称变为 `<前缀>-map`。 +5. 选择**导入文件**,然后在确认弹出窗口中选择**刷新**。 + +### 选择自定义矢量地图 + +1. 在**图层选项** > **图层设置**中,选择**自定义矢量地图**。 +2. 在**矢量地图**下,选择您上传的地图。 +3. (可选)在**样式设置**下,增加**边框粗细**以提高可见性。 +4. 选择**更新**。 + +### GeoJSON 文件示例 + +以下 GeoJSON 文件定义了两个美国县: + +```json +{ + "type": "FeatureCollection", + "name": "usa counties", + "features": [ + { + "type": "Feature", + "properties": { "iso2": "US", "iso3": "LA-CA", "name": "Los Angeles County", "country": "US", "county": "LA" }, + "geometry": { "type": "Polygon", "coordinates": [[[-118.718, 34.071], [-118.696, 34.034], [-118.570, 34.030], [-118.488, 33.957], [-118.372, 33.861], [-118.455, 33.756], [-118.339, 33.715], [-118.229, 33.756], [-118.141, 33.679], [-117.911, 33.578], [-117.751, 33.496], [-117.559, 33.555], [-117.307, 33.596], [-117.070, 33.674], [-116.697, 34.062], [-116.944, 34.284], [-117.180, 34.430], [-117.378, 34.543], [-117.625, 34.570], [-118.048, 34.615], [-118.449, 34.543], [-118.619, 34.389], [-118.740, 34.212], [-118.718, 34.071]]] } + }, + { + "type": "Feature", + "properties": { "iso2": "US", "iso3": "SD-CA", "name": "San Diego County", "country": "US", "county": "SD" }, + "geometry": { "type": "Polygon", "coordinates": [[[-117.235, 32.861], [-117.241, 32.755], [-117.164, 32.681], [-117.142, 32.584], [-117.092, 32.463], [-117.054, 32.292], [-116.960, 32.194], [-116.856, 32.166], [-116.675, 32.204], [-116.367, 32.320], [-116.147, 32.551], [-116.164, 32.806], [-116.411, 33.073], [-116.730, 33.082], [-117.092, 32.995], [-117.252, 32.963], [-117.235, 32.861]]] } + } + ] +} +``` + +## 配置 GeoJSON 复杂度 + +上传的 GeoJSON 文件的复杂度使用以下集群设置配置: + +| 设置 | 默认值 | 描述 | +| :--- | :--- | :--- | +| `plugins.geospatial.geojson.max_coordinates_per_geo` | `10000` | 每个几何体允许的最大坐标数。 | +| `plugins.geospatial.geojson.max_holes_per_polygon` | `1000` | 每个多边形允许的最大孔数。 | +| `plugins.geospatial.geojson.max_multi_geometries` | `100` | 多几何体对象中的最大几何体数。 | +| `plugins.geospatial.geojson.max_geometry_collection_nested_depth` | `5` | 几何体集合的最大嵌套深度。 | + +有关更新动态设置的更多信息,请参阅[动态设置](/install-and-configure/configuring-opensearch/#dynamic-settings)。 + +## 配置区域地图 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +### 选项选项卡 + +| 设置 | 描述 | +| :--- | :--- | +| **矢量地图** | 包含地理边界的底图。选择内置地图或自定义上传的地图。 | +| **连接字段** | 矢量地图中用于匹配您的数据值的字段。 | +| **颜色方案** | 用于表示值的颜色渐变。 | +| **显示工具提示** | 启用后,悬停时显示区域值。 | + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/selfhost-maps-server.md b/i18n/zh/dashboards/visualize/visualize-app/selfhost-maps-server.md new file mode 100644 index 00000000..80ad2f31 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/selfhost-maps-server.md @@ -0,0 +1,104 @@ +--- +title: 使用自托管地图服务器 +--- + +# 使用自托管地图服务器 + +OpenSearch Dashboards 的自托管地图服务器提供在离线环境中访问默认地图服务的功能。兼容 OpenSearch 的地图 URL 包括带有地图切片和矢量的地图清单、地图切片和地图矢量。 + +以下部分提供了设置和使用 OpenSearch Dashboards 自托管地图服务器的步骤。 + +::: info NOTE +您可以从官方 OpenSearch [Docker Hub 仓库](https://hub.docker.com/u/opensearchproject)访问 `maps-server` 镜像。 +::: + +## 拉取 Docker 镜像 + +打开终端并运行以下命令: + +`docker pull opensearchproject/opensearch-maps-server:1.0.0` + +## 设置服务器 + +在运行服务器之前,您必须设置地图切片。您有两个设置选项:使用 OpenSearch 提供的地图服务切片集,或生成栅格切片集。 + +### 选项 1:使用 OpenSearch 提供的地图服务切片集 + +创建 Docker 卷以保存切片集: + +`docker volume create tiles-data` + +从 OpenSearch 地图服务下载切片集。根据所需的缩放级别,有两个行星切片集可用: + +- 缩放级别 8 (https://maps.opensearch.org/offline/planet-osm-default-z0-z8.tar.gz) +- 缩放级别 10 (https://maps.opensearch.org/offline/planet-osm-default-z0-z10.tar.gz) + +::: info NOTE +缩放级别 10 的行星切片集(压缩后 2 GB/解压后 6.8 GB)大约是缩放级别 8 切片集(压缩后 225 MB/解压后 519 MB)的 10 倍大小。 +::: + +``` +docker run \ + -e DOWNLOAD_TILES=https://maps.opensearch.org/offline/planet-osm-default-z0-z8.tar.gz \ + -v tiles-data:/usr/src/app/public/tiles/data/ \ + opensearch/opensearch-maps-server \ + import +``` + +### 选项 2:生成栅格切片集 + +要生成栅格切片集,请使用[栅格切片生成管道](https://github.com/opensearch-project/maps/tree/main/tiles-generation/cdk),然后使用切片集的绝对路径创建卷以启动服务器。 + +## 启动服务器 + +使用以下命令使用 Docker 卷 `tiles-data` 启动服务器。以下命令是使用主机 URL "localhost" 和端口 "8080" 的示例: + +``` +docker run \ + -v tiles-data:/usr/src/app/public/tiles/data/ \ + -e HOST_URL='http://localhost' \ + -p 8080:8080 \ + opensearch/opensearch-maps-server \ + run +``` + +或者,如果您生成了栅格切片集,请使用该切片集运行服务器: + +``` +docker run \ + -v /absolute/path/to/tiles/:/usr/src/app/dist/public/tiles/data/ \ + -p 8080:8080 \ + opensearch/opensearch-maps-server \ + run +``` +通过在主机上的浏览器中打开以下每个链接或使用 `curl` 命令(例如 `curl http://localhost:8080/manifest.json`)确认服务器正在运行。 + +* 地图清单 URL:`http://localhost:8080/manifest.json` +* 地图切片 URL:`http://localhost:8080/tiles/data/{z}/{x}/{y}.png` +* 地图切片演示 URL:`http://localhost:8080/` + +## 在 OpenSearch Dashboards 中使用自托管地图服务器 + +您可以通过将参数添加到 `opensearch_dashboards.yml` 或在 OpenSearch Dashboards 中配置默认 WMS 属性来使用自托管地图服务器与 OpenSearch Dashboards。 + +### 选项 1:配置 opensearch_dashboards.yml + +在 `opensearch_dashboards.yml` 中配置清单 URL: + +`map.opensearchManifestServiceUrl: "http://localhost:8080/manifest.json"` + +### 选项 2:在 OpenSearch Dashboards 中配置默认 WMS 属性 + +1. 在 OpenSearch Dashboards 控制台中,选择**仪表板管理** > **高级设置**。 +2. 在**默认 WMS 属性**下找到 `visualization:tileMap:WMSdefaults`。 +3. 将 `"enabled": false` 更改为 `"enabled": true` 并添加有效地图服务器的 URL。 + +## 许可证 + +切片根据 [Natural Earth 矢量地图数据使用条款](https://www.naturalearthdata.com/about/terms-of-use/)和 [OpenStreetMap 版权和许可证](https://www.openstreetmap.org/copyright)生成。 + +## 相关文档 + +* [配置 Web 地图服务(WMS)](/dashboards/visualize/maptiles) +* [坐标地图](/dashboards/visualize/visualize-app/coordinate-maps) +* [区域地图](/dashboards/visualize/visualize-app/region-maps) diff --git a/i18n/zh/dashboards/visualize/visualize-app/tag-cloud.md b/i18n/zh/dashboards/visualize/visualize-app/tag-cloud.md new file mode 100644 index 00000000..ebf09042 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/tag-cloud.md @@ -0,0 +1,51 @@ +--- +title: 标签云 +--- + +# 标签云 + +标签云显示数据中的一组文本字段(桶标签,在可视化中称为_标签_)。每个标签的字体大小对应于数据中桶的大小。例如,如果可视化指定 `Average`,标签云中标签的字体大小与分桶字段的平均值成比例。 + +您可以将标签云视为一种反向显示,通过将值显示为桶标签的大小而不是图形化数量(如条形的长度)来映射分桶值。 + +## 何时使用标签云 + +使用标签云来提供不同文本标签桶大小的戏剧性比较。 + +## 创建标签云 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要创建标签云,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择**标签云**,然后选择您的索引模式(例如,**opensearch_dashboards_sample_data_flights**)。 + + ::: info NOTE + 由于数据未分桶,可视化面板以大字母显示 `all`。默认情况下,标签大小与文档计数成比例,但没有其他词条可以与其大小进行比较。 + ::: + +2. 在**指标**下,展开**标签大小 count**。 +3. 将**聚合**设置为**唯一计数**,将**字段**设置为 **DestLocation**。 +4. (可选)输入**自定义标签**,例如 `服务的目的地`。 +5. 选择**更新**。 + + 可视化没有变化。标签云仍然只有一个条目 `all`,因为数据尚未分桶。 + +6. 在**分桶**下,选择**添加** > **标签**。 +7. 将**聚合**设置为**词条**,将**字段**设置为 **Carrier**。 +8. 选择**更新**。 + + 标签云按唯一目的地数量显示每个承运人的大小,如下图所示。 + + *按唯一目的地大小显示承运人的标签云* + +## 配置标签云 + +有关通用可视化配置的信息,请参阅[配置可视化](/dashboards/visualize/visualize-app/configuring-viz)。 + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/timeline.md b/i18n/zh/dashboards/visualize/visualize-app/timeline.md new file mode 100644 index 00000000..0388c615 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/timeline.md @@ -0,0 +1,425 @@ +--- +title: 时间线可视化 +--- + +# 时间线可视化 + +**时间线**是 OpenSearch Dashboards 中基于表达式的数据可视化工具,您可以使用简单的表达式语言创建时间序列可视化。与使用图形界面的其他可视化类型不同,**时间线**使用基于文本的表达式语法来定义数据源、转换和显示选项。使用此语法,您可以比较多个时间序列、应用数学函数并叠加来自不同时间段的数据。 + +## 何时使用时间线可视化 + +使用**时间线**进行专门的基于时间的数据分析,特别是使用其表达式语法揭示时间模式和事件序列。 + +::: info NOTE +**时间线**是一个遗留可视化工具。对于新的基于时间的可视化,请考虑使用 [TSVB](/dashboards/visualize/visualize-app/tsvb) 或 [Vega](/dashboards/visualize/visualize-app/vega)。 +::: + +::: tip TIP +**时间线**最适合需要对可视化进行基于表达式控制的场景,例如使用偏移量比较跨时间段的数据、对系列应用数学转换或在单个图表上组合多个数据源。 +::: + +## 先决条件 + +在创建时间线可视化之前,请确保您具备以下条件: + +- 正在运行且可访问的 OpenSearch Dashboards 实例。 +- 已加载示例数据或可用的时间序列索引。本文档中的示例使用电子商务示例数据集。要了解添加示例数据集,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +## 创建时间线可视化 + +要创建时间线可视化,请按照以下步骤操作: + +1. 从顶部菜单中,选择 **OpenSearch Dashboards > 可视化**。 +1. 选择**创建可视化**。 +1. 选择**时间线**。 + +时间线编辑器由以下组件组成: + +- **图表区域**:显示渲染的可视化。 +- **间隔**:设置数据聚合的时间桶大小(例如,`1d`、`1h` 或 `auto`)。 +- **时间线表达式**:编写时间线表达式以定义可视化的数据和外观的文本编辑器。 +- **更新和放弃按钮**:应用或还原对表达式的更改。 + +下图显示了包含查询电子商务数据的基本表达式的时间线编辑器。 + +*时间线编辑器显示具有随时间变化订单数量的基本 OpenSearch 表达式* + +## 时间线表达式语法 + +时间线表达式由一个或多个用逗号分隔的函数链组成。每个链以数据源函数开头,后跟使用点表示法链接的其他函数。多个链用逗号分隔,并在同一图表上生成多个系列。 + +基本语法如下: + +```js +.function1(arg1=value1, arg2=value2).function2(arg1=value1) +``` + +要在同一图表上显示多个系列,请用逗号分隔表达式: + +```js +.opensearch(index=my-index).label("系列 1"), .opensearch(index=my-index, metric=avg:price).label("系列 2") +``` + +## 数据源函数 + +`.opensearch()` 函数是时间线表达式的主要数据源。它从 OpenSearch 索引提取时间序列数据。 + +<!-- vale off --> +### .opensearch() 参数 +<!-- vale on --> + +下表列出了 `.opensearch()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `q` | 字符串 | Apache Lucene [查询字符串](/query-dsl/full-text/query-string)语法中的查询。默认为 `*`(匹配所有)。 | +| `metric` | 字符串 | OpenSearch 指标聚合:`avg`、`sum`、`min`、`max`、`percentiles` 或 `cardinality`,后跟字段名称。例如,`sum:bytes` 或 `percentiles:bytes:95,99,99.9`。默认为 `count`。 | +| `split` | 字符串 | 用于拆分系列的字段和限制。例如,`hostname:10` 检索前 10 个主机名。 | +| `index` | 字符串 | 要查询的索引。接受通配符。为脚本字段和字段名称建议提供索引模式名称。 | +| `timefield` | 字符串 | 用于 x 轴的 `date` 类型字段。 | +| `offset` | 字符串 | 通过日期表达式偏移系列检索,例如,`-1M` 使一个月前的事件显示为好像正在现在发生。使用 `timerange:-2` 将整个图表时间范围偏移到过去两倍。 | +| `opensearchDashboards` | 布尔值 | 设置为 `true` 时,遵守 OpenSearch Dashboards 仪表板上应用的过滤器。仅在仪表板上使用时有效。 | +| `data_source_name` | 字符串 | 要查询的数据源。仅在启用多个数据源时有效。 | +| `fit` | 字符串 | 用于将系列拟合到目标时间跨度和间隔的算法。`average`、`carry`、`nearest`、`none` 或 `scale` 之一。 | + +### 基本查询示例 + +以下表达式随时间从电子商务示例数据索引检索文档计数: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date) +``` + +### 指标聚合示例 + +以下表达式计算 `taxful_total_price` 字段的平均值: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=avg:taxful_total_price) +``` + +### 查询过滤器示例 + +以下表达式使用 `q` 参数使用 Lucene 查询语法过滤数据: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, q="customer_gender:MALE").label("男性订单"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, q="customer_gender:FEMALE").label("女性订单") +``` + +### 拆分示例 + +以下表达式按 `customer_gender` 字段拆分数据,返回前 2 个值: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, split=customer_gender:2) +``` + +### 偏移示例 + +以下表达式将当前时间范围与一周前的数据叠加以进行比较: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("本周"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, offset=-1w).label("上周") +``` + +下图显示了使用偏移将当前周与上周进行比较。 + +*使用偏移将当前时期与上周进行比较的时间线可视化* + +## 显示函数 + +显示函数控制用于渲染系列的图表类型(折线、条形或点)。 + +<!-- vale off --> +### .lines() +<!-- vale on --> + +将系列渲染为折线。下表列出了 `.lines()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `width` | 数字 | 线条粗细,以像素为单位。 | +| `fill` | 数字 | 控制填充不透明度的 0 到 10 之间的数字。用于创建面积图。 | +| `stack` | 布尔值 | 设置为 `true` 时,堆叠线条。 | +| `show` | 布尔值 | 显示或隐藏线条。 | +| `steps` | 布尔值 | 设置为 `true` 时,将线条渲染为阶梯而不是在点之间插值。 | + +#### 示例 + +以下表达式渲染具有自定义宽度和填充的折线图: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).lines(width=2, fill=1) +``` + +<!-- vale off --> +### .bars() +<!-- vale on --> + +将系列渲染为条形。下表列出了 `.bars()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `width` | 数字 | 条形宽度,以像素为单位。 | +| `stack` | 布尔值 | 设置为 `true` 时,堆叠条形。默认为 `true`。 | + +#### 示例 + +以下表达式渲染总收入的条形图: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).bars(width=2) +``` + +<!-- vale off --> +### .points() +<!-- vale on --> + +将系列渲染为点。下表列出了 `.points()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `radius` | 数字 | 点大小。 | +| `weight` | 数字 | 点周围线条的粗细。 | +| `fill` | 数字 | 表示填充不透明度的 0 到 10 之间的数字。 | +| `fillColor` | 字符串 | 填充点的颜色。 | +| `symbol` | 字符串 | 点符号。`triangle`、`cross`、`square`、`diamond` 或 `circle` 之一。 | +| `show` | 布尔值 | 显示或隐藏点。 | + +#### 示例 + +以下表达式将数据渲染为十字形点: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=max:taxful_total_price).points(symbol=cross, radius=3) +``` + +## 样式函数 + +样式函数控制系列的标签、颜色和图例,而不更改图表类型。 + +<!-- vale off --> +### .label() +<!-- vale on --> + +更改图例中显示的系列标签。使用 `$1`、`$2` 等引用正则表达式捕获组。下表列出了 `.label()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `label` | 字符串 | 系列的图例值。使用 `$1`、`$2` 等引用正则表达式捕获组。 | +| `regex` | 字符串 | 支持捕获组的正则表达式。 | + +#### 示例 + +以下表达式为系列设置自定义标签: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("每日订单数") +``` + +<!-- vale off --> +### .color() +<!-- vale on --> + +更改系列的颜色。接受十六进制颜色值。要在多个系列之间创建渐变,请指定用冒号分隔的多种颜色。 + +#### 示例 + +以下表达式将系列颜色设置为蓝色: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).color(#1E88E5) +``` + +<!-- vale off --> +### .legend() +<!-- vale on --> + +设置图例的位置和样式。下表列出了 `.legend()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `position` | 字符串或布尔值 | 放置图例的角落:`nw`、`ne`、`se` 或 `sw`。设置为 `false` 以禁用图例。 | +| `columns` | 数字 | 将图例分成的列数。 | +| `showTime` | 布尔值 | 设置为 `true` 时,在悬停在图表上时在图例中显示时间值。默认为 `true`。 | +| `timeFormat` | 字符串 | moment.js 格式模式。默认为 `MMMM Do YYYY, HH:mm:ss.SSS`。 | + +<!-- vale off --> +### .title() +<!-- vale on --> + +在绑定图顶部添加标题。如果在多个系列上调用,则使用最后一次调用。下表列出了 `.title()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `title` | 字符串 | 绑定图的标题。 | + +<!-- vale off --> +### .hide() +<!-- vale on --> + +默认隐藏系列。系列仍在图例中可用,可以切换打开。下表列出了 `.hide()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `hide` | 布尔值 | 设置为 `true` 时,隐藏系列。默认为 `true`。 | + +## Y 轴配置 + +您可以配置一个或多个 y 轴来控制刻度、定位和格式。 + +<!-- vale off --> +### .yaxis() +<!-- vale on --> + +配置 y 轴选项。使用 `.yaxis(2)` 在辅助 y 轴上绑定系列。下表列出了 `.yaxis()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `yaxis` | 数字 | 在其上绑定此系列的编号 y 轴。例如,`2` 表示辅助 y 轴。 | +| `min` | 数字 | 最小值。 | +| `max` | 数字 | 最大值。 | +| `position` | 字符串 | 轴位置:`left` 或 `right`。 | +| `label` | 字符串 | 轴的标签。 | +| `color` | 字符串 | 轴标签的颜色。 | +| `units` | 字符串 | y 轴标签的格式。`bits`、`bits/s`、`bytes`、`bytes/s`、`currency(:ISO 4217 code)`、`percent` 或 `custom(:prefix:suffix)` 之一。 | +| `tickDecimals` | 数字 | y 轴刻度标签的小数位数。 | + +#### 示例 + +以下表达式将收入显示为左侧 y 轴上的条形,将订单数显示为右侧 y 轴上的折线: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).label("总收入").bars(width=2), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("订单数").lines(fill=1, width=1).yaxis(2) +``` + +下图显示了双 y 轴可视化,收入为条形,订单数为折线。 + +*具有双 y 轴的时间线可视化,显示总收入为条形和订单数为折线* + +## 数据转换函数 + +数据转换函数修改、平滑或分析系列数据。 + +<!-- vale off --> +### .movingaverage() +<!-- vale on --> + +计算给定窗口的移动平均值。使用此函数平滑嘈杂的系列。别名:`.mvavg()`。下表列出了 `.movingaverage()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `window` | 数字或字符串 | 要平均的点数,或日期数学表达式(例如,`1d` 或 `1M`)。 | +| `position` | 字符串 | 相对于结果时间的平均点位置。`left`、`right` 或 `center` 之一。 | + +#### 示例 + +以下表达式将每日收入与 7 天移动平均值叠加: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).label("每日收入"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).movingaverage(window=7).label("7 天移动平均").color(#F04E37).lines(width=3) +``` + +下图显示了带有 7 天移动平均叠加的每日收入。 + +*显示每日收入与 7 天移动平均叠加的时间线可视化* + +<!-- vale off --> +### .derivative() +<!-- vale on --> + +绘制随时间的值变化。 + +#### 示例 + +以下表达式绘制订单数随时间的变化: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).derivative().label("订单数变化") +``` + +<!-- vale off --> +### .trend() +<!-- vale on --> + +使用指定的回归算法绘制趋势线。下表列出了 `.trend()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `mode` | 字符串 | 要使用的算法。`linear` 或 `log` 之一。 | +| `start` | 数字 | 开始计算的位置。负值从末尾计数。默认为 `0`。 | +| `end` | 数字 | 停止计算的位置。负值从末尾计数。默认为 `0`。 | + +#### 示例 + +以下表达式在订单数上叠加线性趋势线: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("订单数"), +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).trend(mode=linear).label("趋势").color(#E53935) +``` + +## 数学函数 + +时间线支持以下用于组合或转换系列的数学函数。数学函数接受数字或另一个系列作为参数。 + +| 函数 | 描述 | +| :--- | :--- | +| `.add()`(别名:`.plus()`、`.sum()`) | 将一个或多个系列的值添加到输入系列的每个位置。 | +| `.subtract()` | 从输入系列的每个位置减去一个或多个系列的值。 | +| `.multiply()` | 将一个或多个系列的值乘以输入系列的每个位置。 | +| `.divide()` | 将一个或多个系列的值除以输入系列的每个位置。 | +| `.abs()` | 返回系列中每个值的绝对值。 | +| `.log()` | 返回每个值的对数(默认底数:10)。 | +| `.min()` | 返回当前值与提供的系列或数字在每个位置的最小值。 | +| `.max()` | 返回当前值与提供的系列或数字在每个位置的最大值。 | +| `.precision()` | 将值的小数部分截断到指定的位数。 | +| `.scale_interval()` | 将值(通常是总和或计数)缩放到新间隔,例如,每秒速率。 | +| `.range()` | 更改系列的最大值和最小值,同时保持相同的形状。 | + +#### 示例 + +以下表达式通过将总收入除以订单数来计算每个订单的收入: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date, metric=sum:taxful_total_price).divide(value=.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date)).label("每订单收入") +``` + +## 静态值 + +使用静态值在图表上绘制参考线,例如目标或阈值。 + +<!-- vale off --> +### .static() +<!-- vale on --> + +在图表上绘制作为水平线的单个值。别名:`.value()`。下表列出了 `.static()` 函数参数。 + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| `value` | 数字或字符串 | 要显示的单个值。您可以传递多个值以在时间范围内均匀插值。 | +| `label` | 字符串 | 系列的标签。 | +| `offset` | 字符串 | 通过日期表达式偏移系列检索。 | +| `fit` | 字符串 | 用于拟合的算法。`average`、`carry`、`nearest`、`none` 或 `scale` 之一。 | + +#### 示例 + +以下表达式在 150 个订单处添加目标线: + +```js +.opensearch(index=opensearch_dashboards_sample_data_ecommerce, timefield=order_date).label("订单数").lines(fill=2, width=1), +.static(value=150, label="目标").color(#E53935).lines(width=2) +``` + +下图显示了带有 150 个订单静态目标线的订单数。 + +*带有 150 个订单静态目标线的时间线可视化* + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/tsvb.md b/i18n/zh/dashboards/visualize/visualize-app/tsvb.md new file mode 100644 index 00000000..8d317d4e --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/tsvb.md @@ -0,0 +1,74 @@ +--- +title: TSVB 可视化 +--- + +# TSVB 可视化 + +时间序列可视化构建器(TSVB)是 OpenSearch Dashboards 中的数据可视化工具,用于创建详细的时间序列可视化。TSVB 支持基于索引数据在特定时间点添加注释或标记、在多个索引之间建立连接,以及构建显示随时间变化数据的可视化。TSVB 支持以下可视化类型:面积图、折线图、指标、仪表图、Markdown 和数据表。 + +## 何时使用 TSVB 可视化 + +当时间序列分析超出基本图表功能时使用 TSVB 可视化,包括高级数学函数、多指标比较和复杂的时间分析。 + +## 从多个数据源创建 TSVB 可视化 +<Badge type="tip" text="2.14 版本引入" /> + +在继续之前,请确保在 `config/opensearch_dashboards.yaml` 文件中启用了以下配置设置: + +```yaml +data_source.enabled: true +vis_type_timeseries.enabled: true +``` + +在 OpenSearch Dashboards 中配置[多个数据源](/dashboards/management/multi-data-sources)后,您可以使用 TSVB 查询这些数据源。以下 GIF 显示了在 OpenSearch Dashboards 中创建 TSVB 可视化的过程。 + +*在 OpenSearch Dashboards 中创建 TSVB 可视化的过程* + +**步骤 1:设置和连接数据源** + +打开 OpenSearch Dashboards 并按照以下步骤操作: + +1. 从左侧主菜单中选择 **Dashboards 管理**。 +2. 选择**数据源**,然后选择**创建数据源**按钮。 +3. 在**创建数据源**页面上,输入连接详细信息和端点 URL。 +4. 在主页上,选择**添加示例数据**,然后为**示例 Web 日志**数据集选择**添加数据**按钮。 + +以下 GIF 显示了设置和连接数据源所需的步骤。 + +*创建数据源* + +**步骤 2:创建可视化** + +按照以下步骤创建可视化: + +1. 从左侧菜单中,选择**可视化**。 +2. 在**可视化**页面上,选择**创建可视化**,然后在弹出窗口中选择 **TSVB**。 + +**步骤 3:指定数据源** + +创建 TSVB 可视化后,可能会根据您的默认索引模式显示数据。要更改索引模式或配置其他设置,请按照以下步骤操作: + +1. 在**创建**窗口中,选择**面板选项**。 +2. 在**数据源**下,选择要从中提取数据的 OpenSearch 集群。在这种情况下,选择您新创建的数据源。 +3. 在**索引名称**下,输入 `opensearch_dashboards_sample_data_logs`。 +4. 在**时间字段**下,选择 `@timestamp`。此设置指定渲染可视化的时间范围。 + +**(可选)步骤 4:添加注释** + +注释是可以添加到时间序列可视化的标记。按照以下步骤添加注释: + +1. 在页面左上角,选择**时间序列**。 +2. 选择**注释**选项卡,然后选择**添加数据源**。 +3. 在**索引**名称字段中,指定适当的索引。在这种情况下,继续使用前面步骤中的相同索引,即 `opensearch_dashboards_sample_data_logs`。 +4. 从**时间**字段中,选择 `@timestamp`。 +5. 在**字段**字段中,输入 `timestamp`。 +6. 在**行模板**字段中,输入 `timestamp`。 + +可视化会自动更新以显示您的注释,如下图所示。 + + *带有注释的 TSVB 可视化* + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/vega.md b/i18n/zh/dashboards/visualize/visualize-app/vega.md new file mode 100644 index 00000000..45544a43 --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/vega.md @@ -0,0 +1,385 @@ +--- +title: Vega 可视化 +--- + +# Vega 可视化 + +[Vega](https://vega.github.io/vega/) 和 [Vega-Lite](https://vega.github.io/vega-lite/) 是开源的声明式语言可视化工具,您可以使用 OpenSearch 数据和 [Vega 数据](https://vega.github.io/vega/docs/data/)创建自定义数据可视化。这些工具非常适合熟悉直接编写 OpenSearch 查询的高级用户。您可以在 Vega 规范中内联定义数据源。 + +## 何时使用 Vega 可视化 + +当您需要标准 OpenSearch 可视化类型中不可用的可视化类型或分析功能时,使用 Vega 可视化,包括高级统计分析、自定义交互行为和专业分析技术。 + +## 启用 Vega 可视化 + +Vega 可视化默认启用。以 JSON 或 [Hjson](https://hjson.github.io/) 格式编写您的 [Vega 规范](https://vega.github.io/vega/docs/specification/)。您可以在规范中指定一个或多个 OpenSearch 查询。 + +要禁用 Vega 可视化,请在 `opensearch_dashboards.yml` 文件中将 `vis_type_vega.enabled` 设置为 `false`。 + +## 创建 Vega 可视化 + +::: info NOTE +本页面上的示例使用**示例电子商务数据**数据集。要了解添加示例数据集,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。 +::: + +以下示例创建一个网络图,可视化示例电子商务数据集中产品制造商之间的关系。它使用 [`adjacency_matrix` 聚合](/aggregations/bucket/adjacency-matrix)来确定来自不同制造商的产品在同一订单中一起出现的频率。 + +要为此聚合创建 Vega 可视化,请按照以下步骤操作: + +1. 从左侧菜单中,选择**可视化**。 +2. 选择**创建可视化**,然后选择 **Vega**。 +3. 用以下内容替换默认规范,然后选择**更新**: + +```json +{ + "$schema": "https://vega.github.io/schema/vega/v5.json", + "description": "来自邻接矩阵聚合的网络图", + "autosize": "none", + "width": 500, + "height": 400, + "padding": 50, + + "data": [ + { + "name": "raw", + "url": { + "index": "opensearch_dashboards_sample_data_ecommerce", + "body": { + "size": 0, + "aggs": { + "interactions": { + "adjacency_matrix": { + "filters": { + "Low Tide Media": {"match": {"manufacturer.keyword": "Low Tide Media"}}, + "Elitelligence": {"match": {"manufacturer.keyword": "Elitelligence"}}, + "Oceanavigations": {"match": {"manufacturer.keyword": "Oceanavigations"}} + } + } + } + } + } + }, + "format": {"property": "aggregations.interactions.buckets"} + }, + { + "name": "nodes", + "source": "raw", + "transform": [ + {"type": "filter", "expr": "indexof(datum.key, '&') === -1"}, + {"type": "window", "ops": ["row_number"], "as": ["index"]}, + {"type": "formula", "as": "x", "expr": "250 + 150 * cos(2 * PI * (datum.index - 1) / 3)"}, + {"type": "formula", "as": "y", "expr": "200 + 150 * sin(2 * PI * (datum.index - 1) / 3)"} + ] + }, + { + "name": "edges", + "source": "raw", + "transform": [ + {"type": "filter", "expr": "indexof(datum.key, '&') !== -1"}, + {"type": "formula", "as": "source", "expr": "split(datum.key, '&')[0]"}, + {"type": "formula", "as": "target", "expr": "split(datum.key, '&')[1]"}, + {"type": "lookup", "from": "nodes", "key": "key", "fields": ["source"], "as": ["sourceNode"]}, + {"type": "lookup", "from": "nodes", "key": "key", "fields": ["target"], "as": ["targetNode"]} + ] + } + ], + + "scales": [ + { + "name": "nodeSize", + "type": "linear", + "domain": {"data": "nodes", "field": "doc_count"}, + "range": [400, 2000] + }, + { + "name": "linkWidth", + "type": "linear", + "domain": {"data": "edges", "field": "doc_count"}, + "range": [2, 8] + } + ], + + "marks": [ + { + "type": "rule", + "from": {"data": "edges"}, + "encode": { + "enter": { + "x": {"field": "sourceNode.x"}, + "y": {"field": "sourceNode.y"}, + "x2": {"field": "targetNode.x"}, + "y2": {"field": "targetNode.y"}, + "stroke": {"value": "#888"}, + "strokeWidth": {"scale": "linkWidth", "field": "doc_count"}, + "strokeOpacity": {"value": 0.6} + } + } + }, + { + "type": "text", + "from": {"data": "edges"}, + "encode": { + "enter": { + "x": {"signal": "(datum.sourceNode.x + datum.targetNode.x) / 2"}, + "y": {"signal": "(datum.sourceNode.y + datum.targetNode.y) / 2"}, + "text": {"signal": "datum.doc_count"}, + "align": {"value": "center"}, + "baseline": {"value": "middle"}, + "fontSize": {"value": 11}, + "fill": {"value": "#555"} + } + } + }, + { + "type": "symbol", + "from": {"data": "nodes"}, + "encode": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "size": {"scale": "nodeSize", "field": "doc_count"}, + "fill": {"value": "#4C78A8"}, + "stroke": {"value": "#fff"}, + "strokeWidth": {"value": 2}, + "tooltip": {"signal": "datum.key + ': ' + datum.doc_count + ' docs'"} + } + } + }, + { + "type": "text", + "from": {"data": "nodes"}, + "encode": { + "enter": { + "x": {"field": "x"}, + "y": {"field": "y"}, + "dy": {"value": -30}, + "text": {"field": "key"}, + "align": {"value": "center"}, + "fontSize": {"value": 12}, + "fontWeight": {"value": "bold"} + } + } + } + ] +} +``` + +下图显示了生成的网络图。节点大小代表每个制造商的文档计数,边缘粗细代表包含两个制造商产品的订单数量。 + +*OpenSearch Dashboards 中的邻接矩阵网络图可视化* + +## 从多个数据源创建 Vega 可视化 +<Badge type="tip" text="2.13 版本引入" /> + +在继续之前,请确保在 `config/opensearch_dashboards.yaml` 文件中启用了以下配置设置。有关配置详细信息,请参阅 `vis_type_vega` [`README`](https://github.com/opensearch-project/OpenSearch-Dashboards/blob/main/src/plugins/vis_type_vega/README.md)。 + +``` +data_source.enabled: true +vis_type_vega.enabled: true +``` + +在 OpenSearch Dashboards 中配置[多个数据源](/dashboards/management/multi-data-sources)后,您可以使用 Vega 查询这些数据源。以下 GIF 显示了在 OpenSearch Dashboards 中创建 Vega 可视化的过程。 + +*在 OpenSearch Dashboards 中创建 Vega 可视化的过程* + +### 步骤 1:设置和连接数据源 + +打开 OpenSearch Dashboards 并按照以下步骤操作: + +1. 从左侧菜单中选择 **Dashboards 管理**。 +2. 选择**数据源**,然后选择**创建数据源**按钮。 +3. 在**创建数据源**页面上,输入连接详细信息和端点 URL,如以下 GIF 所示。 +4. 在**主页**上,选择**添加示例数据**。在**数据源**下,选择您新创建的数据源,然后为**示例 Web 日志**数据集选择**添加数据按钮**。 + +以下 GIF 显示了设置和连接数据源所需的步骤。 + +*在 OpenSearch Dashboards 中设置和连接数据源* + +### 步骤 2:创建可视化 + +1. 从左侧菜单中,选择**可视化**。 +2. 在**可视化**页面上,选择**创建可视化**,然后在弹出窗口中选择 **Vega**。 + +### 步骤 3:添加 Vega 规范 + +默认情况下,查询使用来自本地集群的数据。您可以为 Vega 规范中的每个 OpenSearch 查询分配单独的 `data_source_name` 值。这允许您在单个可视化中查询不同数据源上的多个索引。 + +1. 验证您创建的数据源是否在 `data_source_name` 下指定。或者,在您的 Vega 规范中,在 `url` 属性下添加 `data_source_name` 字段以按名称定位特定数据源。 +2. 复制以下 Vega 规范,然后选择右下角的**更新**按钮。可视化应该会出现。 + +```json +{ + $schema: https://vega.github.io/schema/vega-lite/v5.json + data: { + url: { + %context%: true + %timefield%: @timestamp + index: opensearch_dashboards_sample_data_logs + data_source_name: YOUR_DATA_SOURCE_TITLE + body: { + aggs: { + 1: { + date_histogram: { + field: @timestamp + fixed_interval: 3h + time_zone: America/Los_Angeles + min_doc_count: 1 + } + aggs: { + 2: { + avg: { + field: bytes + } + } + } + } + } + size: 0 + } + } + format: { + property: aggregations.1.buckets + } + } + transform: [ + { + calculate: datum.key + as: timestamp + } + { + calculate: datum[2].value + as: bytes + } + ] + layer: [ + { + mark: { + type: line + } + } + { + mark: { + type: circle + tooltip: true + } + } + ] + encoding: { + x: { + field: timestamp + type: temporal + axis: { + title: @timestamp + } + } + y: { + field: bytes + type: quantitative + axis: { + title: 平均字节数 + } + } + color: { + datum: 平均字节数 + type: nominal + } + } +} +``` + +## 使用 PromQL 查询 Prometheus 数据 +<Badge type="tip" text="3.10 版本引入" /> + +您可以使用 Vega 或 Vega-Lite 规范通过 [Prometheus 查询语言(PromQL)](https://prometheus.io/docs/prometheus/latest/querying/basics/)查询 Prometheus 数据连接。OpenSearch Dashboards 在服务器上运行查询并将结果作为内联 `values` 插入规范中,因此浏览器不会进行外部 HTTP 调用。 + +::: info NOTE +在继续之前,请确保您已在 OpenSearch Dashboards 中配置了 Prometheus 数据连接。有关更多信息,请参阅[将 Prometheus 连接到 OpenSearch](/dashboards/management/connect-prometheus)。 +::: + +### 规范字段 + +添加 `data.url` 对象并将 `%type%` 设置为 `prometheus`。`data.url` 对象支持以下字段。 + +| 字段 | 必需 | 描述 | +|-------|----------|-------------| +| `%type%` | 是 | 必须设置为 `prometheus`。 | +| `%datasource%` | 是 | 在 OpenSearch Dashboards 中配置的 Prometheus 数据连接的名称。 | +| `%context%` | 是 | 必须设置为 `true`。将仪表板时间范围应用于 PromQL 查询。 | +| `body.query` | 是 | 要评估的 PromQL 表达式,例如 `rate(http_requests_total[5m])`。要在一个请求中运行多个表达式,请用分号(`;`)分隔它们。 | +| `%maxdatapoints%` | 否 | 每个系列的最大数据点数。OpenSearch Dashboards 计算一个步长间隔,使每个系列保持在此限制内。使用此字段使图表在长时间范围内保持响应。 | +| `%step%` | 否 | 步长间隔,以秒为单位,例如 `60`。当两者都提供时,优先于 `%maxdatapoints%`。 | + +### 响应字段 + +OpenSearch Dashboards 为每个数据点返回一条记录。每条记录包含以下字段,您可以在 Vega 编码中引用这些字段。 + +| 字段 | 类型 | 描述 | +|-------|------|-------------| +| `Time` | 数字 | 数据点的时间戳,自 Unix 纪元以来的毫秒数。 | +| `Series` | 字符串 | 时间序列的完整标签集,格式为 Prometheus 指标字符串,例如 `up{job="node"}`。当 `body.query` 包含多个表达式时,每个 `Series` 值以标识其表达式的字母开头。例如,第一个表达式的 `Series` 值为 `A: up{job="node"}`。 | +| `Labels` | 对象 | 系列的各个标签作为键值对,例如 `{"job": "node", "instance": "localhost:9100"}`。 | +| `Value` | 数字 | 此时间戳处的样本值。 | + +### 示例 + +以下 Vega-Lite 规范创建一个折线图,绘制仪表板时间范围内 HTTP 请求的每秒速率: + +```json +{ + "$schema": "https://vega.github.io/schema/vega-lite/v5.json", + "data": { + "url": { + "%type%": "prometheus", + "%datasource%": "my_prometheus_connection", + "%context%": true, + "%maxdatapoints%": 500, + "body": { + "query": "rate(http_requests_total[5m])" + } + } + }, + "mark": "line", + "encoding": { + "x": { + "field": "Time", + "type": "temporal", + "axis": { "title": "时间" } + }, + "y": { + "field": "Value", + "type": "quantitative", + "axis": { "title": "请求/秒" } + }, + "color": { + "field": "Series", + "type": "nominal" + }, + "tooltip": [ + { "field": "Time", "type": "temporal" }, + { "field": "Series", "type": "nominal" }, + { "field": "Value", "type": "quantitative" } + ] + } +} +``` + +::: info NOTE +将 `my_prometheus_connection` 替换为您配置的 Prometheus 数据连接的名称。 +::: + +### 限制 + +- Vega PromQL 查询仅支持本地集群上的 Prometheus 数据连接。不支持通过[多个数据源](/dashboards/management/multi-data-sources)添加的远程集群上的数据连接。 +- 如果查询返回超过 2,000 个系列,OpenSearch Dashboards 会显示警告并截断结果。缩小 PromQL 查询以减少返回的系列数。 +- 如果 PromQL 结果超过 30,000 个数据点,OpenSearch Dashboards 会显示警告并在系列边界处截断结果。使用 `%maxdatapoints%` 或 `%step%` 减少返回的数据点数。 + +## 其他资源 + +以下资源提供有关 OpenSearch Dashboards 中 Vega 可视化的其他信息: + +- [使用 Vega 可视化改进 OpenSearch Dashboards 的易用性](https://opensearch.org/blog/Improving-Dashboards-usability-with-Vega/) + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/visbuilder.md b/i18n/zh/dashboards/visualize/visualize-app/visbuilder.md new file mode 100644 index 00000000..78a8389f --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/visbuilder.md @@ -0,0 +1,41 @@ +--- +title: VisBuilder +--- + +# VisBuilder + +VisBuilder 在 OpenSearch Dashboards 中提供拖放式可视化创建。使用 VisBuilder,您可以: + +* 无需预先选择可视化输出即可立即查看数据。 +* 灵活快速地更改可视化类型和索引模式。 +* 能够轻松在多个屏幕之间导航。 + +## 何时使用 VisBuilder + +使用 VisBuilder 通过直观的拖放界面快速探索数据关系,减少测试假设和探索数据模式所需的时间,无需查询语言知识。 + +## 使用 VisBuilder 创建可视化 + +::: info NOTE +本页面上的示例使用**示例航班数据**数据集。在开始之前,请完成[先决条件](/dashboards/visualize/visualize-app/#prerequisites)。 +::: + +要使用 VisBuilder 创建可视化,请按照以下步骤操作: + +1. 在**新建可视化**对话框中,选择 **VisBuilder**,如下图所示。 + + ![VisBuilder 新建可视化起始页](/images/dashboards/vis-builder-2.png) +2. 从**数据源**下拉列表中,选择 **opensearch_dashboards_sample_data_flights**。 +3. 在**配置**面板中,通过从左侧字段列表拖动字段或选择每个部分中的 **+** 图标向图表添加字段: + - **Y 轴**:选择 **+** 图标,将**聚合**设置为**平均值**,将**字段**设置为 **AvgTicketPrice**。 + - **X 轴**:选择 **+** 图标,将**聚合**设置为**词条**,将**字段**设置为 **Carrier**,将**顺序**设置为**降序**。 + - **拆分系列**:选择 **+** 图标,将**聚合**设置为**词条**,将**字段**设置为 **FlightDelay**。 + +图表会在您添加字段时自动更新。**拆分系列**字段将每个条形分成颜色编码的子组。在此示例中,`FlightDelay` 有两个值(`true` 和 `false`),因此每个承运人显示两个条形——一个用于延误航班,一个用于未延误航班——使用不同的颜色,如下图所示。 + +*VisBuilder 条形图显示按承运人拆分航班延误的平均票价* + +## 后续步骤 + +- 要选择不同的可视化类型,请参阅[可视化类型](/dashboards/visualize/visualize-app/viz-types)。 +- 要将此可视化添加到仪表板,请参阅[创建仪表板](/dashboards/dashboard/)。 diff --git a/i18n/zh/dashboards/visualize/visualize-app/viz-types.md b/i18n/zh/dashboards/visualize/visualize-app/viz-types.md new file mode 100644 index 00000000..fee2409f --- /dev/null +++ b/i18n/zh/dashboards/visualize/visualize-app/viz-types.md @@ -0,0 +1,70 @@ +--- +title: 可视化类型 +description: "使用可视化应用在 OpenSearch Dashboards 中创建数据可视化的推荐可视化类型,包括图表、表格和地图。" +--- + +# 可视化类型 + +**可视化**应用支持以下可视化类型,按类别分组。每个描述都包含指导,说明何时该可视化类型最有效。有关更多信息,请参阅各个可视化类型页面。 + +## 文本可视化 + +文本可视化使用文字和数字而不是图形元素来显示数据。它们提供细节并帮助关键数据在仪表板上脱颖而出。 + +| 可视化类型 | 描述 | +| :--- | :--- | +| [**指标可视化**](/dashboards/visualize/visualize-app/metric) <br><br> ![指标](/images/dashboards/metric-chart-1.png) | 显著显示单个数值。用于 KPI 和汇总统计。 | +| [**标签云**](/dashboards/visualize/visualize-app/tag-cloud) <br><br> ![标签云](/images/word-cloud-1.png) | 按频率或其他指标调整大小显示词汇。 | +| [**数据表**](/dashboards/visualize/visualize-app/data-table) <br><br> ![数据表](/images/data-table-1.png) | 以表格形式显示原始或聚合数据。 | + +## 一维可视化 + +一维可视化显示单个分桶数据字段,比较跨类别的值或显示比例。 + +| 可视化类型 | 描述 | +| :--- | :--- | +| [**仪表可视化**](/dashboards/visualize/visualize-app/gauge) <br><br> ![仪表](/images/dashboards/gauge-1.png) | 在表盘上显示相对于定义范围或阈值的单个值。 | +| [**目标可视化**](/dashboards/visualize/visualize-app/goal) <br><br> *目标* | 在进度条上显示相对于目标的单个值。 | +| [**饼图**](/dashboards/visualize/visualize-app/pie-charts) <br><br> ![饼图](/images/pie-1.png) | 将比例数据显示为圆形的切片。用于部分与整体的比较。 | + +## 多维可视化 + +多维可视化将一个或多个数据字段显示为另一个数据字段的函数。对数据进行分桶的聚合使用数值而非分类值。 + +| 可视化类型 | 描述 | +| :--- | :--- | +| [**条形图**](/dashboards/visualize/visualize-app/bar-charts) <br><br> ![垂直条形图](/images/dashboards/bar-chart-1.png) | 以垂直或水平条形比较分类数据。用于跨类别排名或比较值。 | +| [**面积图**](/dashboards/visualize/area) <br><br> ![面积图](/images/dashboards/area-chart-1.png) | 将数据显示为折线与坐标轴之间的填充区域。用于显示随时间变化的量或比较堆叠类别。 | +| [**热力图**](/dashboards/visualize/visualize-app/heat-map) <br><br> ![热力图](/images/dashboards/heat-map-1.png) | 使用颜色强度表示两个分类维度上的值。 | +| [**折线图**](/dashboards/visualize/visualize-app/line-charts) <br><br> ![折线图](/images/line-1.png) | 绘制由线连接的数据点。用于可视化趋势和随时间的变化。 | + +## 地图可视化 + +地图可视化根据地理区域或坐标绘制数据。 + +| 可视化类型 | 描述 | +| :--- | :--- | +| [**坐标地图**](/dashboards/visualize/visualize-app/coordinate-maps) <br><br> *坐标地图* | 使用纬度和经度坐标在地图上绘制地理数据点。 | +| [**区域地图**](/dashboards/visualize/visualize-app/region-maps) <br><br> ![区域地图](/images/map-1.png) | 按聚合值为地理区域着色。支持自定义 GeoJSON 矢量地图。 | +| [**地图应用**](/dashboards/visualize/maps) <br><br> ![地图](/images/dashboards/coordinate-1.png) | 具有多种图层类型、工具提示、过滤器和标签的独立映射工具。 | + +## 实用可视化 + +实用可视化不直接显示数据,但在仪表板上下文中支持其他可视化。 + +| 可视化类型 | 描述 | +| :--- | :--- | +| [**Markdown 可视化**](/dashboards/visualize/visualize-app/markdown) <br><br> ![Markdown](/images/dashboards/markdown.png) | 在数据可视化旁边渲染 Markdown 文本以提供上下文和说明。 | +| [**控件**](/dashboards/visualize/visualize-app/controls) <br><br> ![控件](/images/dashboards/controls-1.png) | 向仪表板添加交互式过滤面板(下拉列表或范围滑块)。 | + +## 其他工具 + +以下可视化工具使用专用界面,而不是标准的基于聚合的编辑器。 + +| 可视化类型 | 描述 | +| :--- | :--- | +| [**PPL 可视化**](/dashboards/visualize/visualize-app/ppl) <br><br> *PPL* | 通过直接输入 PPL 查询创建可视化。 | +| [**TSVB 可视化**](/dashboards/visualize/visualize-app/tsvb) <br><br> ![TSVB](/images/dashboards/TSVB-1.png) | 创建详细的时间序列可视化,支持面积图、折线图、指标、仪表图、Markdown 和数据表类型。 | +| [**Vega 可视化**](/dashboards/visualize/visualize-app/vega) <br><br> ![Vega](/images/dashboards/vega-1.png) | 使用 Vega 和 Vega-Lite 声明式语法创建自定义可视化。 | +| [**VisBuilder**](/dashboards/visualize/visbuilder) <br><br> ![VisBuilder](/images/dashboards/vis-builder-2.png) | 无需提前选择图表类型即可创建可视化的拖放工具。 | +| [**时间线可视化**](/dashboards/visualize/visualize-app/timeline) <br><br> ![时间线](/images/dashboards/timeline-1.png) | 使用基于文本的表达式语法创建时间序列可视化。 | diff --git a/i18n/zh/dashboards/visualize/viz-index.md b/i18n/zh/dashboards/visualize/viz-index.md index fc8ecfb6..06f05d4d 100644 --- a/i18n/zh/dashboards/visualize/viz-index.md +++ b/i18n/zh/dashboards/visualize/viz-index.md @@ -4,122 +4,122 @@ title: 构建数据可视化 # 构建数据可视化 -通过可视化数据,你可以将复杂的、大量的或数值数据转换为更容易处理的视觉表示。OpenSearch Dashboards 为你提供数据可视化工具,以改进和自动化视觉通信过程。通过使用图表、图形或地图等视觉元素来表示数据,你可以推进商业智能并支持数据驱动的决策和战略规划。 +通过可视化数据,您可以将复杂的、大量的或数值数据转换为更易于处理的可视化表示。OpenSearch Dashboards 为您提供数据可视化工具,以改进和自动化视觉传达过程。通过使用图表、图形或地图等可视元素来表示数据,您可以推进商业智能并支持数据驱动的决策制定和战略规划。 ## 了解 OpenSearch Dashboards 中的可视化类型 -Dashboards 有几种可视化类型来支持你的数据分析需求。以下部分概述了 Dashboards 中的可视化类型及其常见用例。 +Dashboards 提供多种可视化类型来支持您的数据分析需求。以下部分概述了 Dashboards 中的可视化类型及其常见用例。 ### 面积图 -面积图描述随时间的变化,通常用于显示趋势。面积图更有效地识别日志数据中的模式,例如某个时间范围内的销售数据以及该时间内的趋势。请参阅[使用面积图](/dashboards/visualize/area)以了解更多关于如何在 Dashboards 中创建和使用它们的信息。 +面积图描绘随时间的变化,通常用于显示趋势。面积图能更有效地识别日志数据中的模式,例如某个时间范围内的销售数据以及该时间段内的趋势。请参阅[使用面积图](/dashboards/visualize/area)了解更多关于如何在 Dashboards 中创建和使用它们的信息。 - <img src="/images/dashboards/area-chart-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例面积图"> + <img src="/images/dashboards/area-chart-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的面积图示例"> ### 条形图 -条形图(垂直或水平)比较分类数据并描述变量在一段时间内的变化。 +条形图(垂直或水平)比较分类数据并描绘变量在一段时间内的变化。 垂直条形图 | 水平条形图 :-------------------------:|:-------------------------: -<img src="/images/dashboards/bar-chart-1.png" width="300" height="300" alt="OpenSearch Dashboards 中的示例垂直条形图"> | <img src="/images/dashboards/bar-horizontal-1.png" width="300" height="300" alt="OpenSearch Dashboards 中的示例水平条形图"> +<img src="/images/dashboards/bar-chart-1.png" width="300" height="300" alt="OpenSearch Dashboards 中的垂直条形图示例"> | <img src="/images/dashboards/bar-horizontal-1.png" width="300" height="300" alt="OpenSearch Dashboards 中的水平条形图示例"> ### 控件 -控件是添加到仪表板以过滤数据的面板,而不是可视化类型。控件使用户能够向仪表板添加交互式输入。你可以在 Dashboards 中创建两种类型的控件:**选项列表** 和 **范围滑块**。**选项列表** 是一个下拉选项列表,允许通过词条聚合过滤数据,例如 `machine.os.keyword`。**范围滑块** 允许在指定值范围内过滤,例如 `hour_of_day`。 +控件是添加到仪表板用于过滤数据的面板,而不是可视化类型。控件使用户能够向仪表板添加交互式输入。您可以在 Dashboards 中创建两种类型的控件:**选项列表**和**范围滑块**。**选项列表**是一个下拉选项列表,允许通过词条聚合过滤数据,例如 `machine.os.keyword`。**范围滑块**允许在指定值范围内过滤,例如 `hour_of_day`。 -<img src="/images/dashboards/controls-1.png" width="600" height="600" alt="在 OpenSearch Dashboards 中使用控件过滤数据的示例可视化"> +<img src="/images/dashboards/controls-1.png" width="600" height="600" alt="OpenSearch Dashboards 中使用控件过滤数据的可视化示例"> ### 数据表 数据表或表格以表格形式显示原始数据。 -<img src="/images/data-table-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例数据表"> +<img src="/images/data-table-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的数据表示例"> ### 甘特图 -甘特图显示序列中唯一事件的开始、结束和持续时间。甘特图在跟踪分析、遥测和异常检测用例中很有用,当你想了解计划中各种事件之间的交互和依赖关系时。**甘特图** 目前是 Dashboards 中的插件可视化类型,而不是内置类型。请参阅[甘特图](/dashboards/visualize/gantt)以了解如何在 Dashboards 中创建和使用它们。 +甘特图显示序列中唯一事件的开始、结束和持续时间。甘特图在追踪分析、遥测和异常检测用例中非常有用,您可以在这些场景中了解计划中各种事件之间的交互和依赖关系。**甘特图**目前是 Dashboards 中的插件可视化类型,而非内置类型。请参阅[甘特图](/dashboards/visualize/gantt)了解如何在 Dashboards 中创建和使用它们。 -<img src="/images/dashboards/gantt-chart.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例甘特图"> +<img src="/images/dashboards/gantt-chart.png" width="600" height="600" alt="OpenSearch Dashboards 中的甘特图示例"> ### 仪表图 -仪表图看起来类似于从左到右从零读取的模拟速度表。它们显示你正在测量的事物有多少,这个测量可以单独存在,也可以与另一个测量相关联,例如跟踪与基准或目标相比的性能。 +仪表图看起来类似于从左到右从零开始读取的模拟速度表。它们显示您正在测量的事物的数量,这个测量可以单独存在,也可以与另一个测量相关联,例如对照基准或目标跟踪性能。 -<img src="/images/dashboards/gauge-1.png" width="400" height="400" alt="OpenSearch Dashboards 中的示例仪表图"> +<img src="/images/dashboards/gauge-1.png" width="400" height="400" alt="OpenSearch Dashboards 中的仪表图示例"> -### 热图 +### 热力图 -热图是随时间变化的直方图(数值数据分布的图形表示)的视图。热图使用颜色以表格形式显示数据来区分值在范围内的位置,而不是像直方图那样使用条形高度作为频率的表示。 +热力图是随时间变化的直方图(数值数据分布的图形表示)视图。热力图不是使用条形高度作为频率的表示(如直方图),而是以表格形式显示数据,使用颜色来区分值在范围内的位置。 -<img src="/images/dashboards/heat-map-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例热图"> +<img src="/images/dashboards/heat-map-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的热力图示例"> ### 折线图 -折线图比较一段时间内测量值的变化,例如按月的总销售额或按月的总销售额和净销售额。 +折线图比较测量值在一段时间内的变化,例如按月计算的总销售额或按月计算的总销售额和净销售额。 -<img src="/images/line-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例折线图"> +<img src="/images/line-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的折线图示例"> ### 地图 -你可以在 Dashboards 中创建两种类型的地图:坐标地图和区域地图。坐标地图按大小显示每个位置的数据值差异。区域地图按颜色的不同深浅显示每个位置的数据值差异。请参阅[使用地图](/dashboards/visualize/maps)以了解更多关于 Dashboards 中地图功能的信息。 +您可以在 Dashboards 中创建两种类型的地图:坐标地图和区域地图。坐标地图按大小显示每个位置的数据值差异。区域地图通过不同深浅的颜色显示每个位置的数据值差异。请参阅[使用地图](/dashboards/visualize/maps)了解更多关于 Dashboards 中地图功能的信息。 #### 坐标地图 坐标地图在地图上显示基于位置的数据。使用坐标地图在地图上可视化 GPS 数据(纬度和经度坐标)。有关 OpenSearch 支持的坐标字段类型的信息,请参阅[地理字段类型](/field-types/supported-field-types/geo-shape)和[笛卡尔字段类型](/field-types/supported-field-types/xy)。 -<img src="/images/dashboards/coordinate-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例坐标地图"> +<img src="/images/dashboards/coordinate-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的坐标地图示例"> #### 区域地图 -区域地图显示跨地理位置的模式和趋势。区域地图是 Dashboards 中的底图之一。有关在 Dashboards 中创建自定义矢量地图的信息,请参阅[使用坐标和区域地图](/dashboards/visualize/geojson-regionmaps)以了解如何在 Dashboards 中创建和使用地图。 +区域地图显示跨地理位置的模式和趋势。区域地图是 Dashboards 中的底图之一。有关在 Dashboards 中创建自定义矢量地图的信息,请参阅[使用坐标和区域地图](/dashboards/visualize/geojson-regionmaps)了解如何在 Dashboards 中创建和使用地图。 -<img src="/images/map-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例区域地图"> +<img src="/images/map-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的区域地图示例"> ### Markdown -Markdown 是 Dashboards 中用于为数据可视化提供上下文的标记语言。使用 Markdown,你可以显示信息和说明以及可视化。 +Markdown 是 Dashboards 中使用的标记语言,用于为数据可视化提供上下文。使用 Markdown,您可以显示信息和说明以及可视化内容。 -<img src="/images/dashboards/markdown.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例坐标地图"> +<img src="/images/dashboards/markdown.png" width="600" height="600" alt="OpenSearch Dashboards 中的坐标地图示例"> ### 指标值 -指标值或数字图表比较不同度量中的值。例如,你可以创建一个指标可视化来比较两个值,例如实际销售额与销售目标的比较。 +指标值或数字图表比较不同度量中的值。例如,您可以创建指标可视化来比较两个值,例如实际销售额与销售目标的比较。 -<img src="/images/dashboards/metric-chart-1.png" width="400" height="400" alt="OpenSearch Dashboards 中的示例指标图"> +<img src="/images/dashboards/metric-chart-1.png" width="400" height="400" alt="OpenSearch Dashboards 中的指标图表示例"> ### 饼图 -饼图比较维度中项目的值,例如总金额的百分比。 +饼图比较维度中各项的值,例如占总量的百分比。 -<img src="/images/pie-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例饼图"> +<img src="/images/pie-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的饼图示例"> ### TSVB -时间序列可视化构建器 (TSVB) 是 Dashboards 中的一个数据可视化工具,用于创建详细的时间序列可视化。例如,你可以使用 TSVB 构建显示随时间变化的数据的可视化,例如按状态随时间变化的航班或按延误类型随时间变化的航班延误。目前,TSVB 可用于创建以下 Dashboards 可视化类型:面积图、折线图、指标、仪表、Markdown 和数据表。 +时间序列可视化构建器(TSVB)是 Dashboards 中的数据可视化工具,用于创建详细的时间序列可视化。例如,您可以使用 TSVB 构建显示随时间变化的数据的可视化,例如按状态显示的航班随时间变化或按延误类型显示的航班延误随时间变化。目前,TSVB 可用于创建以下 Dashboards 可视化类型:面积图、折线图、指标、仪表图、Markdown 和数据表。 -<img src="/images/dashboards/TSVB-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例 TSVB"> +<img src="/images/dashboards/TSVB-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的 TSVB 示例"> ### 标签云 -标签(或词)云是一种显示一个词在数据集中相对于其他词使用频率的方式。这种类型的视觉效果最适合显示词或短语的频率。 +标签(或词)云是一种显示一个词在数据集中相对于其他词使用频率的方式。这种类型的可视化最适合用于显示词或短语的频率。 -<img src="/images/word-cloud-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例标签云"> +<img src="/images/word-cloud-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的标签云示例"> -### Timeline +### 时间线 -Timeline 是 Dashboards 中的一个数据可视化工具,你可以用它来创建时间序列可视化。目前,Timeline 可用于创建以下 Dashboards 可视化类型:面积图和折线图。 +时间线是 Dashboards 中的数据可视化工具,可用于创建时间序列可视化。目前,时间线可用于创建以下 Dashboards 可视化类型:面积图和折线图。 -<img src="/images/dashboards/timeline-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例 Timeline"> +<img src="/images/dashboards/timeline-1.png" width="600" height="600" alt="OpenSearch Dashboards 中的时间线示例"> ### VisBuilder -VisBuilder 是 Dashboards 中的一个拖放式数据可视化工具。它让你无需预先选择数据源或可视化类型输出即可立即查看数据。目前,VisBuilder 可用于创建以下 Dashboards 可视化类型:面积图、条形图、折线图、指标和数据表。请参阅 [VisBuilder](/dashboards/visualize/visbuilder) 以了解如何在 Dashboards 中创建和使用拖放式可视化。 +VisBuilder 是 Dashboards 中的拖放式数据可视化工具。它为您提供数据的即时视图,无需预先选择数据源或可视化类型输出。目前,VisBuilder 可用于创建以下 Dashboards 可视化类型:面积图、条形图、折线图、指标和数据表。请参阅 [VisBuilder](/dashboards/visualize/visbuilder) 了解如何在 Dashboards 中创建和使用拖放式可视化。 -<img src="/images/dashboards/vis-builder-2.png" width="600" height="600" alt="OpenSearch Dashboards 中的示例 VisBuilder"> +<img src="/images/dashboards/vis-builder-2.png" width="600" height="600" alt="OpenSearch Dashboards 中的 VisBuilder 示例"> ### Vega -[Vega](https://vega.github.io/vega/) 和 [Vega-Lite](https://vega.github.io/vega-lite/) 是开源的声明式语言可视化语法,用于创建、共享和保存交互式数据可视化。Vega 可视化使你能够灵活地使用分层方法可视化多维数据,以结构化方式构建和操作可视化。Vega 可用于使用任何 Dashboards 可视化类型创建自定义可视化。 +[Vega](https://vega.github.io/vega/) 和 [Vega-Lite](https://vega.github.io/vega-lite/) 是开源的声明式语言可视化语法,用于创建、共享和保存交互式数据可视化。Vega 可视化为您提供灵活性,可以使用分层方法可视化多维数据,以结构化方式构建和操作可视化。Vega 可用于使用任何 Dashboards 可视化类型创建自定义可视化。 -<img src="/images/dashboards/vega-1.png" width="600" height="600" alt="OpenSearch Dashboards 中带有 JSON 规范的示例 Vega 可视化"> +<img src="/images/dashboards/vega-1.png" width="600" height="600" alt="OpenSearch Dashboards 中带有 JSON 规范的 Vega 可视化示例"> diff --git a/i18n/zh/dashboards/workspace/apis.md b/i18n/zh/dashboards/workspace/apis.md new file mode 100644 index 00000000..f4b5d076 --- /dev/null +++ b/i18n/zh/dashboards/workspace/apis.md @@ -0,0 +1,399 @@ +--- +title: 工作区 API +--- + +# 工作区 API +<Badge type="tip" text="2.18 版本引入" /> + +使用工作区 API 管理 OpenSearch Dashboards 中的工作区。 + +这些端点由 OpenSearch Dashboards 提供服务,因此将请求发送到 OpenSearch Dashboards 主机和端口 (默认为 `5601`)。使用 `POST`、`PUT` 或 `DELETE` 的请求需要 `osd-xsrf: true` 标头。为 Kibana OSS 编写的脚本会发送 `kbn-xsrf: true` 标头,OpenSearch Dashboards 会拒绝这些请求并显示错误 `Request must contain a osd-xsrf header`。要修复此错误,请在脚本中将 `kbn-xsrf` 替换为 `osd-xsrf`。 + +## 列出工作区 + +您可以使用以下端点检索工作区列表: + +```json +POST {osd_host}:{port}/api/workspaces/_list +``` + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `search` | String | 可选 | 用于使用简单查询语法过滤工作区的查询字符串,例如 `simple_query_string`。| +| `searchFields` | Array | 可选 | 指定对哪些字段执行搜索查询。| +| `sortField` | String | 可选 | 用于排序结果的字段名称。| +| `sortOrder` | String | 可选 | 指定升序或降序排序顺序。| +| `perPage` | Number | 可选 | 每页工作区结果的数量。| +| `page` | Number | 可选 | 要检索的结果页数。| +| `permissionModes` | Array | 可选 | 要过滤的权限列表。| + +#### 示例请求 + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_list' \ + -d '{}' +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": { + "page": 1, + "per_page": 20, + "total": 1, + "workspaces": [ + { + "name": "test4", + "description": "test4", + "features": [ + "use-case-all" + ], + "lastUpdatedTime": "2025-09-10T14:47:04.741Z", + "id": "B9Le1w", + "permissionMode": "read" + } + ] + } +} +``` + +## 获取工作区 + +您可以使用以下端点检索单个工作区: + +```json +GET {osd_host}:{port}/api/workspaces/{id} +``` + +下表列出了可用的路径参数。所有路径参数都是必需的。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `<id>` | String | 必需 | 标识要检索的唯一工作区。| + +#### 示例请求 + +```json +curl -k -u admin:admin -X GET 'https://localhost:5601/api/workspaces/B9Le1w' +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": { + "name": "test4", + "description": "test4", + "features": [ + "use-case-all" + ], + "lastUpdatedTime": "2025-09-10T14:47:04.741Z", + "id": "B9Le1w" + } +} +``` + +## 创建工作区 + +您可以使用以下端点创建工作区: + +```json +POST {osd_host}:{port}/api/workspaces +``` + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `attributes` | Object | 必需 | 定义工作区属性。| +| `attributes.id` | String | 可选 | 工作区的 ID。| +| `permissions` | Object | 可选 | 指定工作区的权限。| +| `settings` | Object | 可选 | 指定工作区的设置。| + +#### 示例请求 + +```json +curl -k -XPOST "https://localhost:5601/api/workspaces" \ + -H "Content-Type: application/json" \ + -H "osd-xsrf: true" \ + -d '{ + "attributes": { + "id": "my_workspace", + "name": "test4", + "description": "test4", + "features": ["use-case-all"] + } + }' -u admin:admin +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": { + "id": "B9Le1w" + } +} +``` + +## 更新工作区 + +您可以使用以下端点更新工作区的属性和权限: + +```json +PUT {osd_host}:{port}/api/workspaces/{id} +``` + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `<id>` | String | 必需 | 标识要检索的唯一工作区。| +| `attributes` | Object | 必需 | 定义工作区属性。| +| `permissions` | Object | 可选 | 指定工作区的权限。| + +#### 不带 permissions 对象的示例请求 + +```json +curl -k -XPUT "https://localhost:5601/api/workspaces/B9Le1w" \ + -H "Content-Type: application/json" \ + -H "osd-xsrf: true" \ + -d '{ + "attributes": { + "name": "test5", + "description": "Updated description" + } + }' -u admin:admin +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": true +} +``` + +#### 带 permissions 对象的示例请求 + +当请求包含 `permissions` 对象时,每个用户或组必须分配所需访问级别所需的权限模式集。例如,只读访问需要 `library_read` 和 `read` 权限模式: + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X PUT 'https://localhost:5601/api/workspaces/B9Le1w' \ + -d '{ + "attributes": {}, + "settings": { + "permissions": { + "library_write": { "users": ["obs-admin-user"] }, + "write": { "users": ["obs-admin-user"] }, + "library_read": { "groups": ["obs-read-users"] }, + "read": { "groups": ["obs-read-users"] } + } + } + }' +``` + +有关权限模式及其提供的访问级别的完整列表,请参阅[定义工作区协作者](/dashboards/workspace/workspace-acl#defining-workspace-collaborators)。 + +## 删除工作区 + +您可以使用以下端点删除工作区: + +```json +DELETE {osd_host}:{port}/api/workspaces/{id} +``` + +下表列出了可用的路径参数。所有路径参数都是必需的。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `<id>` | String | 必需 | 标识要检索的唯一工作区。| + +#### 示例请求 + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -X DELETE 'https://localhost:5601/api/workspaces/B9Le1w' +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": true +} +``` + +## 复制保存的对象 + +您可以使用以下端点在工作区之间复制保存的对象: + +```json +POST {osd_host}:{port}/api/workspaces/_duplicate_saved_objects +``` + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `objects` | Array | 必需 | 指定要复制的保存对象。| +| `targetWorkspace` | String | 必需 | 标识复制的目标工作区。| +| `includeReferencesDeep` | Boolean | 可选 | 确定是否将所有引用的对象复制到目标工作区。默认为 `true`。| + +下表列出了 `objects` 参数中对象的属性。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `type` | String | 必需 | 定义保存对象的分类,如 `index-pattern`、`config` 或 `dashboard`。| +| `id` | String | 必需 | 保存对象的 ID。| + +#### 示例请求 + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_duplicate_saved_objects' \ + -d '{ + "objects": [ + { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" } + ], + "targetWorkspace": "9gt4lB" + }' +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "successCount": 1, + "success": true, + "successResults": [ + { + "type": "index-pattern", + "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", + "meta": { + "title": "test*", + "icon": "indexPatternApp" + }, + "destinationId": "f4b724fd-9647-4bbf-bf59-610b43a62c75" + } + ] +} +``` + +## 关联保存的对象 + +您可以使用以下端点将保存的对象与工作区关联: + +```json +POST {osd_host}:{port}/api/workspaces/_associate +``` + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `workspaceId` | String | 必需 | 标识对象关联的目标工作区。| +| `savedObjects` | Array | 必需 | 指定要复制的保存对象列表。| + +下表列出了 `savedObjects` 参数中对象的属性。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `type` | String | 必需 | 定义保存对象的分类,如 `index-pattern`、`config` 或 `dashboard`。| +| `id` | String | 必需 | 保存对象的 ID。| + +#### 示例请求 + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_associate' \ + -d '{ + "savedObjects": [ + { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" } + ], + "workspaceId": "9gt4lB" + }' +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": [ + { + "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", + } + ] +} +``` + +## 取消关联保存的对象 + +您可以使用以下端点将保存的对象与工作区取消关联: + +```json +POST {osd_host}:{port}/api/workspaces/_dissociate +``` + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `workspaceId` | String | 必需 | 要与对象关联的目标工作区。| +| `savedObjects` | Array | 必需 | 要复制的保存对象列表。| + +下表列出了 `savedObjects` 参数的属性。 + +| 参数 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `type` | String | 必需 | 保存对象的类型,如 `index-pattern`、`config` 或 `dashboard`。| +| `id` | String | 必需 | 保存对象的 ID。| + +#### 示例请求 + +```json +curl -k -u admin:admin \ + -H 'osd-xsrf: true' \ + -H 'Content-Type: application/json' \ + -X POST 'https://localhost:5601/api/workspaces/_dissociate' \ + -d '{ + "savedObjects": [ + { "type": "index-pattern", "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d" } + ], + "workspaceId": "9gt4lB" + }' + +``` + +以下示例响应显示成功的 API 调用: + +```json +{ + "success": true, + "result": [ + { + "id": "619cc200-ecd0-11ee-95b1-e7363f9e289d", + } + ] +} +``` diff --git a/i18n/zh/dashboards/workspace/create-workspace.md b/i18n/zh/dashboards/workspace/create-workspace.md new file mode 100644 index 00000000..4c1e8bba --- /dev/null +++ b/i18n/zh/dashboards/workspace/create-workspace.md @@ -0,0 +1,50 @@ +--- +title: 创建工作区 +--- + +# 创建工作区 +<Badge type="tip" text="2.18 版本引入" /> + +在开始本教程之前,您必须启用工作区功能标志。有关更多信息,请参阅[启用工作区](/dashboards/workspace/workspace#enabling-workspaces)。 + +当启用保存对象权限时,只有具有管理员状态的用户才能创建工作区。有关更多信息,请参阅[配置仪表板管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)。 + +要创建工作区,请执行以下步骤: + +1. 打开 OpenSearch Dashboards。 +2. 从主页面,选择适合您用例的卡片,例如**可观测性**、**安全分析**、**搜索**、**基础**或**分析**。或者,您可以选择**创建工作区**按钮,然后从下拉菜单中选择适当的用例。 +3. 在**工作区详情**窗口中输入所需信息。 + - **工作区名称**是必需的。有效字符为 `a-z`、`A-Z`、`0-9`、括号 (`()`)、方括号 (`[]`)、下划线 (`_`)、连字符 (`-`) 和空格。在字符限制 (40 个字符) 内选择唯一的工作区名称。当工作区名称已存在或超出字符限制时,**创建工作区**按钮将被禁用,并显示错误消息。 + - **用例和功能**是必需的。选择最适合您需求的用例。如果您使用的是 Amazon OpenSearch Serverless 并启用了[多数据源](/dashboards/management/data-sources)功能,则会自动分配**基础**。 +4. (可选) 选择颜色选择器以自定义工作区图标的颜色。 +5. (可选) 添加最多 200 个字符的工作区描述。当描述超出字符限制时,此选项将被禁用。 +6. (可选) 输入自定义**工作区 ID**。如果留空,将自动生成 ID。自定义 ID 必须是 6--36 个字符,仅使用字母、数字、下划线 (`_`) 和连字符 (`-`)。如果提供的 ID 的工作区已存在,将返回错误。 +7. 保存您的工作区。 + - 一旦您输入所有必需字段的信息,**创建工作区**按钮将变为活动状态。您将自动成为工作区所有者。系统会将您重定向到协作者页面 (如果启用了保存对象权限) 或概述页面 (如果禁用了保存对象权限)。有关权限的更多信息,请参阅[配置仪表板管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)。 + +要设置权限,请参阅[工作区访问控制列表](/dashboards/workspace/workspace-acl)了解更多信息。 + +## 将数据源与工作区关联 + +::: danger WARNING +**关联数据源**选项仅在启用多数据源功能时可见。在创建工作区之前,您必须将其连接到至少一个数据源。如果您尚未设置数据源,请参阅[数据源](/dashboards/management/data-sources)。连接源后,您可以将它们链接到新工作区。 +::: + +### 关联 OpenSearch 数据源 + +要关联 OpenSearch 数据源,请执行以下步骤: + +1. 选择**关联 OpenSearch 数据源**按钮以打开选择模态框。 +2. 在模态框中查看可用的数据源: + - 标准 OpenSearch 源显示为单个条目。 + - 具有直接查询连接的源显示 +N 指示器。 +3. 选择适当的数据源名称。 +4. 选择**关联数据源**按钮以完成关联。 + +### 关联直接查询源 + +要关联直接查询源,请执行以下步骤: + +1. 选择**关联直接查询数据源**按钮以打开选择模态框。模态框仅显示具有直接查询连接的源。 +2. 选择数据源以自动展开其直接查询连接。 +3. 选择**关联数据源**按钮以完成关联。 diff --git a/i18n/zh/dashboards/workspace/index.md b/i18n/zh/dashboards/workspace/index.md new file mode 100644 index 00000000..8d5c8b9d --- /dev/null +++ b/i18n/zh/dashboards/workspace/index.md @@ -0,0 +1,23 @@ +--- +title: 工作区入门 +--- + +# 工作区入门 +<Badge type="tip" text="2.18 版本引入" /> + +OpenSearch Dashboards 2.18 引入了增强的主页,提供所有工作区的全面视图。 + +新主页包括以下功能: + +1. **创建工作区**按钮,供 [OpenSearch Dashboard 管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)导航到[创建工作区](/dashboards/workspace/create-workspace)页面。 +2. 工作区访问时间信息和工作区概述页面的链接。 +3. 显示工作区用途信息的用例信息图标。 +4. **查看所有工作区**按钮,导航到[工作区管理](/dashboards/workspace/manage-workspace#navigating-the-workspaces-list)页面。 +5. 通过**从文档了解更多**按钮链接到最新的 OpenSearch 文档,以及通过**在 playground.opensearch.org 探索实时演示环境**按钮链接到 [OpenSearch Playground](https://playground.opensearch.org/app/home#/)。 + +导航逻辑根据您的工作区访问级别将您定向到适当的页面,确保无缝的用户体验: + +- 如果您配置了默认工作区,您将被定向到工作区概述页面。 +- 如果您只有一个工作区,您将被定向到该工作区的概述页面。 +- 如果您有多个工作区,您将被定向到新主页。 +- 如果您没有工作区,您将被定向到新主页。 diff --git a/i18n/zh/dashboards/workspace/manage-workspace.md b/i18n/zh/dashboards/workspace/manage-workspace.md new file mode 100644 index 00000000..d144113d --- /dev/null +++ b/i18n/zh/dashboards/workspace/manage-workspace.md @@ -0,0 +1,133 @@ +--- +title: 管理工作区 +--- + +# 管理工作区 +<Badge type="tip" text="2.18 版本引入" /> + +您可以在**工作区详情**页面上访问和修改工作区详情,包括名称、描述、用例和图标颜色。 + +要访问和修改工作区详情,请执行以下步骤: + +1. 打开 OpenSearch Dashboards 并导航到**我的工作区**。 +2. 选择所需的工作区,然后选择**编辑**按钮进行更改。 +3. 选择**保存**按钮确认更改或选择**放弃更改**按钮取消修改。 + +## 工作区更新权限 + +更改工作区时适用以下权限: + +1. **没有安全插件:** 所有用户都可以编辑和更新工作区。 +2. **安装了安全插件且 `config/opensearch_dashboards.yml` 文件中 `savedObjects.permission.enabled: false`:** 所有用户都可以编辑和更新工作区。 +3. **安装了安全插件且 `config/opensearch_dashboards.yml` 中 `savedObjects.permission.enabled: true`:** 只有[工作区所有者](/dashboards/workspace/workspace-acl#defining-workspace-collaborators)和[工作区管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)可以编辑和更新工作区。 + +## 工作区更新限制 + +更新工作区用例时,适用以下规则。 + +原始用例 | 目标用例 | +:---: | :---: +分析 | 无法更改为任何其他用例 +搜索 | 分析 +安全分析 | 分析 +可观测性 | 分析 +基础 | 分析 搜索<br> 安全分析<br> 可观测性 + +## 工作区控制面板 + +**工作区详情**页面在右上角提供以下按钮: + +1. **删除** (<img src="/images/dashboards/trash-can-icon.png" class="inline-icon" alt="垃圾桶图标"/> 图标) + - **没有安装安全插件:** 所有用户都可以删除工作区。 + - **安装了安全插件且 `config/opensearch_dashboards.yml` 文件中 `savedObjects.permission.enabled: false`:** 所有用户都可以删除工作区。 + - **安装了安全插件且 `config/opensearch_dashboards.yml` 文件中 `savedObjects.permission.enabled: true`:** 只有管理员可以删除工作区。 +2. **设为默认工作区:** 将当前工作区设置为默认登录目的地。 +3. **工作区概述:** 在新选项卡中打开**概述**页面。 + +## 向工作区添加资产 + +在左侧导航菜单中访问**示例数据**。选择适当的数据集以将其安装到您的集群和 OpenSearch Dashboards 中。 + +## 将未分配的资产迁移到工作区 + +在启用工作区之前创建的保存对象不属于任何工作区。工作区仅显示分配给它的资产,因此这些资产在任何工作区中都不可见,尽管它们仍然存在于集群中。[仪表板管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)可以使用迁移向导将所有未分配的资产移动到新工作区。 + +当存在未分配的资产时,工作区登录页面会向仪表板管理员显示**迁移现有资产 (N)**按钮,其中 N 是未分配资产的数量。 + +要将未分配的资产迁移到新工作区,请执行以下步骤: + +1. 在工作区登录页面上,选择**迁移现有资产 (N)**。 +1. 在**工作区名称**字段中,输入新工作区的名称。 +1. 查看未分配资产的列表。您可以搜索列表并按资产类型过滤。向导会迁移所有未分配的资产,无论搜索词或过滤器如何。 +1. 选择**创建工作区并迁移**。OpenSearch Dashboards 创建工作区,将所有数据源和数据连接连接到它以便迁移的仪表板继续显示数据,然后迁移资产。迁移运行时您无法关闭向导。 +1. 查看摘要,其中显示迁移的资产数量、失败的资产和连接的数据源。 +1. 选择**转到 \<工作区名称\>**以打开新工作区。 + +迁移失败的资产保持未分配状态,摘要列出每个资产及其失败原因。要将它们迁移到同一工作区,请选择**重试失败的资产**。如果迁移在完成之前停止,请选择**继续迁移**以将剩余资产迁移到同一工作区。 + +## 在工作区之间复制资产 + +::: danger WARNING +不支持数据源和配置复制。 +::: + +资产页面提供以下跨工作区复制资产的方法: + +1. **将所有资产复制到...:** 复制表中的所有资产。 +2. **复制到...:** 从表中移动选定的资产。 +3. **复制到...:** 从表中复制单个资产。 + +选择复制选项后,从下拉菜单中选择目标工作区。**复制相关资产**复选框允许您传输关联的资产。 + +选择**复制**按钮后,会出现一个侧边面板,显示成功和失败的资产传输。资产复制目的地取决于以下安全配置: + +1. **没有安全插件:** 所有工作区都可访问。 +2. **安装了安全插件且 `config/opensearch_dashboards.yml` 文件中 `savedObjects.permission.enabled: false`:** 所有工作区都可访问。 +3. **安装了安全插件且 `config/opensearch_dashboards.yml` 文件中 `savedObjects.permission.enabled: true`:** 只有用户具有读写或管理员权限的工作区才可访问。 + +## 关联数据源 + +在数据源管理页面上,您可以访问关联的 OpenSearch 连接的完整列表,监控与当前工作区相关的直接查询连接,并根据需要建立新的数据源关联。 + +### 管理 OpenSearch 连接 + +OpenSearch 连接选项卡显示当前工作区的所有关联连接。按照以下步骤管理您的连接: + +1. 在连接选项卡上访问关联的 OpenSearch 连接的完整列表。 +2. 使用**移除关联**按钮根据需要取消链接连接。 +3. 通过选择 **OpenSearch 数据源**按钮和后续模态框添加新数据源。 +4. 从未关联的 OpenSearch 连接中选择以扩展工作区的功能。 + +### 添加直接查询连接 + +**直接查询连接**选项卡显示与当前工作区关联的所有直接查询连接的列表。要向工作区添加更多直接查询连接,请选择**直接查询数据源**按钮。将打开一个模态窗口。 + +关联模态框显示包含直接查询连接且尚未与当前工作区关联的 OpenSearch 连接列表。当您将 OpenSearch 连接与当前工作区关联时,该 OpenSearch 连接中的所有直接查询连接也会自动关联。 + +## 删除工作区 + +::: danger WARNING +工作区删除仅限于管理员。如果您没有看到 <img src="/images/dashboards/trash-can-icon.png" class="inline-icon" alt="垃圾桶图标"/> 图标,请检查您的权限。有关更多信息,请参阅[配置仪表板管理员](/dashboards/workspace/workspace-acl#configuring-dashboard-administrators)。 +::: + +删除工作区会永久删除其所有资产 (数据源除外) 和工作区本身。此操作无法撤销。 + +要删除工作区,请执行以下步骤: + +1. 从**工作区详情**页面,选择右上角的 <img src="/images/dashboards/trash-can-icon.png" class="inline-icon" alt="垃圾桶图标"/> (垃圾桶) 图标以删除当前工作区。 +2. 或者,从工作区列表页面,选择 <img src="/images/ellipsis-icon.png" class="inline-icon" alt="省略号图标"/> (省略号) 图标并选择**删除**。可选地,选择多个工作区进行批量删除。 + +## 导航工作区列表 + +工作区列表页面作为您工作区管理的中心枢纽,显示您具有访问权限的所有工作区。主要功能包括: + +- 搜索: 按名称快速查找工作区。 +- 过滤: 按用例排序工作区。 +- 一目了然: 查看每个工作区的名称、用例、描述、上次更新时间和关联的数据源。 + +每个工作区条目都包含一个带有以下功能按钮的**操作**列。这些工具简化了您的工作区管理,允许高效组织和自定义您的 OpenSearch Dashboards 环境: + +1. 复制 ID: 一键复制工作区 ID。 +2. 编辑: 直接访问工作区的详细配置页面。 +3. 设为默认: 轻松将任何工作区设置为默认工作区。 +4. 删除: 根据需要移除工作区 (可能需要管理员权限)。 diff --git a/i18n/zh/dashboards/workspace/workspace-acl.md b/i18n/zh/dashboards/workspace/workspace-acl.md new file mode 100644 index 00000000..0af75574 --- /dev/null +++ b/i18n/zh/dashboards/workspace/workspace-acl.md @@ -0,0 +1,200 @@ +--- +title: 工作区访问控制列表 +--- + +# 工作区访问控制列表 +<Badge type="tip" text="2.18 版本引入" /> + +工作区访问控制列表 (ACL) 管理保存对象的授权,同时依赖[安全插件](/security/)进行身份验证。 + +## 角色 + +**工作区**用例涉及以下关键角色: + +* **仪表板管理员:** 对所有 OpenSearch Dashboards 功能和数据拥有完全访问权限。 +* **工作区管理员 (也称为_所有者_):** 对特定工作区拥有完全控制权,包括其配置和保存的对象。创建工作区时,其创建者会自动被分配工作区所有者角色。 +* **工作区内容制作者:** 可以查看、创建和更新工作区内的保存对象。 +* **工作区查看者:** 对工作区中的保存对象具有只读访问权限。 + + ::: info NOTE + 角色是特定于工作区的,允许用户在不同工作区承担不同角色。 + ::: + +## 启用权限控制 + +有关说明,请参阅[启用 ACL 功能](/dashboards/management/acl#enabling-the-acl-feature)。 + +## 配置仪表板管理员 + +要授予对 OpenSearch Dashboards 中所有工作区和对象的完全访问权限,请配置管理员权限。编辑 `opensearch_dashboards.yml` 文件以按用户 ID 和后端角色定义管理员,如以下配置所示: + +```yaml +opensearchDashboards.dashboardAdmin.users: ["UserID"] +opensearchDashboards.dashboardAdmin.groups: ["BackendRole"] +savedObjects.permission.enabled: true +``` + +默认情况下,配置设置为 `[]`,表示没有用户被指定为管理员。如果未安装安全插件且 `savedObjects.permission.enabled: false`,则所有用户都被授予管理员权限。 + +### 配置全局管理员访问 + +使用此通配符设置将所有用户设置为管理员: + +```yaml +opensearchDashboards.dashboardAdmin.users: ["*"] +``` + +### 为单个用户配置管理员访问 + +使用 `admin-user-id` 设置配置用户: + +```yaml +opensearchDashboards.dashboardAdmin.users: ["admin-user-id"] +``` + +### 按后端角色配置管理员访问 + +使用 `admin-role` 设置配置用户: + +```yaml +opensearchDashboards.dashboardAdmin.groups: ["admin-role"] +``` + +### 管理员限制操作 + +管理员限制操作包括以下内容: + +- 工作区创建 +- 工作区删除 +- 数据源连接 +- 断开工作区与数据源的连接 + +## 定义工作区协作者 + +协作者管理的访问仅限于管理员。**协作者**功能仅在启用权限控制时可用。有关激活权限控制的说明,请参阅[启用权限控制](#启用权限控制)。访问级别包括以下内容: + +- **只读:** 授予查看工作区及其资产的权限。 +- **读写:** 允许查看和编辑工作区内的资产。 +- **管理员:** 提供完全访问权限,包括查看和编辑工作区内的资产以及更新工作区元数据,如名称、描述、数据源和协作者。 + +#### 权限模式 + +当您通过 UI 分配协作者时,访问级别会自动应用。当您通过[工作区 API](/dashboards/workspace/apis) 分配协作者时,每个访问级别对应于特定的权限模式组合。下表描述了可用的权限模式。 + +| 权限模式 | 目标 | 描述 | +| :--- | :--- | :--- | +| `read` | 工作区本身 | 主体可以打开和查看工作区。| +| `write` | 工作区本身 | 主体可以管理工作区本身: 编辑其名称、描述和设置,管理协作者,以及关联数据源。| +| `library_read` | 工作区中的保存对象 (资产) | 主体可以查看仪表板、可视化和索引模式等资产。| +| `library_write` | 工作区中的保存对象 (资产) | 主体可以在工作区中创建、编辑和删除资产。| + +每个访问级别需要一个工作区权限模式和一个工作区资产权限模式,如下表所示。如果用户或组仅被分配部分权限模式组合 (例如,`read` 而没有 `library_read`),该用户或组不会显示为协作者。 + +| 访问级别 | 所需权限模式 | +| :--- | :--- | +| 只读 | `library_read` + `read` | +| 读写 | `library_write` + `read` | +| 管理员 | `library_write` + `write` | + +从**协作者**页面,您可以按协作者 ID 搜索并按协作者类型和访问级别过滤结果。 + +### 添加协作者 + +工作区创建者被授予**管理员**访问级别作为协作者。要添加更多协作者,请选择**添加协作者**按钮,该按钮会显示下拉菜单。选择**添加用户**或**添加组**以访问添加新协作者的相应模态框。 + +#### 添加用户 + +要添加用户,请执行以下步骤: + +1. 选择**添加用户**按钮以打开模态框。模态框默认显示一个空的 `用户 ID` 字段。 +2. 选择访问级别: **只读**、**读写**或**管理员**。 +3. 选择**添加另一个用户**以添加多个用户。不要使用重复或现有的 `用户 ID` 字段以避免错误。 +4. 在最终确定之前解决任何错误。成功添加的用户会出现在协作者表中。 + +#### 添加组 + +要添加组,请执行以下步骤: + +1. 选择**添加组**按钮以打开模态框。模态框默认显示一个空的 `组 ID` 字段。 +2. 选择访问级别: **只读**、**读写**或**管理员**。 +3. 使用**添加另一个组**以添加多个组。不要使用重复或现有的 `组 ID` 字段以避免错误。 +4. 在最终确定之前解决任何错误。成功添加的组会出现在协作者表中。 + +### 修改访问级别 + +如果您具有所需权限,可以在将协作者添加到协作者表后修改其访问级别。可以为协作者分配任何访问级别。但是,如果所有**管理员**协作者都更改为较低的访问级别,则只有管理员才能管理工作区协作。 + +#### 修改单个访问级别 + +要修改单个协作者的访问级别,请执行以下步骤: + +1. 选择表格行右侧的操作图标。 +2. 从下拉菜单中选择**更改访问级别**。 +3. 从列表中选择所需的访问级别。 +4. 在出现的模态框中确认更改并选择**确认**。确认后,协作者的访问级别在表中更新。 + +#### 批量修改访问级别 + +要同时更改多个协作者的访问级别,请执行以下步骤: + +1. 在表中选择所需的协作者行。 +2. 选择出现的**操作**按钮。 +3. 从下拉菜单中选择**更改访问级别**。 +4. 从提供的列表中选择新的访问级别。 +5. 在出现的模态框中查看并确认更改。确认后,所有选定协作者的访问级别在表中更新。 + +### 删除协作者 + +将协作者添加到表后,您可以选择删除它们。删除管理员协作者时要小心,因为删除所有管理员协作者会将工作区协作者管理限制为仅限管理员。在最终确定此操作之前会显示确认模态框。 + +#### 删除单个协作者 + +要删除单个协作者,请执行以下步骤: + +1. 选择表格行右侧的 <img src="/images/ellipsis-icon.png" class="inline-icon" alt="省略号图标"/> 图标以显示下拉菜单。 +2. 从下拉菜单中选择**删除协作者**。将出现确认模态框以验证您的操作。 +3. 在模态框中选择**确认**以从表中移除协作者。 + +#### 批量删除协作者 + +要同时移除多个协作者,请执行以下步骤: + +1. 在表中选择包含要移除的协作者的行。将出现"删除 x 个协作者"按钮。 +2. 选择**删除 x 个协作者**按钮。 +3. 查看出现的确认模态框。 +4. 选择**确认**以从表中移除所有选定的协作者。 + +## 配置工作区隐私 + +启用权限控制时,工作区管理员可以设置以下三个访问级别之一: + +* **仅限协作者私有 (默认):** 只有工作区协作者可以访问工作区。 +* **任何人都可以查看:** 向所有工作区用户授予**只读**权限,允许他们查看工作区资产。 +* **任何人都可以编辑:** 向所有用户授予**读写**权限,允许他们查看、创建和更新工作区资产。 + +协作者获得较高的权限: 其个人访问级别或工作区范围的隐私设置。例如,如果工作区隐私设置为"任何人都可以编辑",具有只读访问权限的协作者也可以编辑工作区资产。 +您可以作为**仪表板管理员**在**创建工作区**页面上设置工作区隐私。您也可以作为**工作区管理员**或**仪表板管理员**在**协作者**或**工作区详情**页面上修改它。 + +### 在工作区创建期间设置工作区隐私 + +使用以下步骤在创建新工作区时更改工作区隐私设置: + +1. 从**设置隐私**面板中选择所需的访问级别。 +2. (可选) 选中**在工作区创建后添加协作者**复选框以稍后添加协作者。 +3. 选择**创建工作区**以创建工作区。 + +### 在**协作者**页面上修改工作区隐私 + +使用以下步骤在**协作者**页面上编辑工作区隐私设置: + +1. 在**工作区隐私**旁边,选择**编辑**。 +2. 从下拉菜单中选择新的访问级别。 +3. 选择**保存更改**以应用修改。 + +### 在**工作区详情**页面上修改工作区隐私 + +使用以下步骤在**工作区详情**页面上编辑工作区隐私设置: + +1. 选择**详情**面板右上角的**编辑**按钮。 +2. 从下拉菜单中选择新的访问级别。 +3. 选择**保存**以应用修改。 diff --git a/i18n/zh/dashboards/workspace/workspace.md b/i18n/zh/dashboards/workspace/workspace.md new file mode 100644 index 00000000..a58b2ada --- /dev/null +++ b/i18n/zh/dashboards/workspace/workspace.md @@ -0,0 +1,110 @@ +--- +title: 工作区 +--- + +# 工作区 +<Badge type="tip" text="2.18 版本引入" /> + +工作区使您能够使用特定用例的配置来定制您的环境。例如,您可以为可观测性场景创建专用工作区,让您专注于相关功能。此外,您可以在具有隔离存储的工作区中组织可视化资产,如仪表板和可视化。 + +## 工作区数据模型 + +工作区数据模型由以下结构定义: + +```typescript +interface Workspace { + id: string; + name: string; + description?: string; + features?: string[]; + color: string; + uiSettings: Record<string, unknown>; +} +``` + +工作区数据模型由以下关键属性组成: + +- `id`: String 类型;每个工作区的唯一 ID。 +- `name`: String 类型;指定工作区的名称。 +- `description`: 可选 String 类型;为工作区提供上下文信息。 +- `features`: 可选字符串数组;包含与工作区链接的用例 ID。 + +--- + +#### 示例工作区对象 + +以下对象显示了典型的工作区配置: + +```typescript +{ + id: "M5NqCu", + name: "Analytics team", + description: "Analytics team workspace", + features: ["use-case-analytics"], +} +``` + +该配置使用 `use-case-observability` 功能集创建 `Analytics team`。用例映射到特定功能组,将功能限制为每个工作区内定义的集合。 + +以下是预定义的用例选项: + +- `use-case-observability` +- `use-case-security-analytics` +- `use-case-search` +- `use-case-essentials` +- `use-case-all` + +--- + +## 将保存的对象与工作区关联 + +OpenSearch Dashboards 中的保存对象,如仪表板、可视化和索引模式,可以与特定工作区关联,随着对象数量的增长,改善组织和可访问性。 + +`workspaces` 属性是一个字符串数组,被添加到保存的对象以与一个或多个工作区链接。因此,仪表板和可视化等保存对象只能在其指定的工作区中访问。 + +以下保存对象显示了与工作区 `M5NqCu` 关联的仪表板对象: + +```typescript +{ + type: "dashboard", + id: "da123f20-6680-11ee-93fa-df944ec23359", + workspaces: ["M5NqCu"] +} +``` + +保存的对象支持与多个工作区关联,促进跨团队协作和资源共享。当对象与多个团队、项目或用例相关时,此功能非常有用。 + +以下示例显示了链接到多个工作区的数据源对象: + +```typescript +{ + type: "data-source", + id: "da123f20-6680-11ee-93fa-df944ec23359", + workspaces: ["M5NqCu", "<TeamA-workspace-id>", "<Analytics-workspace-id>"] +} +``` + +## 非工作区保存对象 + +并非 OpenSearch Dashboards 中的所有保存对象都与工作区关联。某些对象独立于工作区框架运行。这些对象缺少 `workspace` 属性,并服务于系统范围的功能。例如,全局用户界面设置对象管理影响整个 OpenSearch Dashboards 界面的配置,以保持所有工作区之间的功能一致性。 + +这种双重方法允许 OpenSearch Dashboards 在细粒度、特定上下文的自定义与整体系统一致性之间取得平衡。 + +## 启用工作区 + +在您的 `opensearch_dashboards.yml` 文件中,设置以下选项: + +```yaml +workspace.enabled: true +uiSettings: + overrides: + "home:useNewHomePage": true +``` + +如果您的集群安装了安全插件,则必须禁用多租户以避免与类似工作区的冲突: + +```yaml +opensearch_security.multitenancy.enabled: false +``` + +更新配置文件后,重新启动 OpenSearch Dashboards 以使更改生效。 diff --git a/i18n/zh/data-prepper/common-use-cases/metrics-logs.md b/i18n/zh/data-prepper/common-use-cases/metrics-logs.md new file mode 100644 index 00000000..79b9d71a --- /dev/null +++ b/i18n/zh/data-prepper/common-use-cases/metrics-logs.md @@ -0,0 +1,66 @@ +--- +title: 从日志中派生指标 +--- + +# 从日志中派生指标 + +您可以使用 OpenSearch Data Prepper 从日志中派生指标。 + +以下示例管道使用 [`http` 源插件](/data-prepper/pipelines/configuration/sources/http-source) 和 [`grok` 处理器](/data-prepper/pipelines/configuration/processors/grok) 接收传入的日志。然后使用 [`aggregate` 处理器](/data-prepper/pipelines/configuration/processors/aggregate) 提取在 30 秒窗口期间聚合的字节指标,并从结果中派生直方图。 + +此管道将数据写入两个不同的 OpenSearch 索引: + +- `logs`:此索引存储经 `grok` 处理器处理后的原始未聚合日志事件。 +- `histogram_metrics`:此索引存储使用 `aggregate` 处理器从日志事件中提取的派生直方图指标。 + +该管道包含两个子管道: + +- `apache-log-pipeline-with-metrics`:通过 HTTP 客户端(如 FluentBit)接收日志,使用 `grok` 通过将日志键中的值与 [Apache 通用日志格式](https://httpd.apache.org/docs/2.4/logs.html#accesslog) 进行匹配来从日志中提取重要值。然后将经过 grok 处理的日志转发到两个目标: + + - 名为 `logs` 的 OpenSearch 索引,用于存储原始日志事件。 + - `log-to-metrics-pipeline`,用于进一步聚合和指标派生。 + +- `log-to-metrics-pipeline`:从 `apache-log-pipeline-with-metrics` 管道接收经过 grok 处理的日志,聚合日志,并根据 `clientip` 和 `request` 键中的值派生字节的直方图指标。最后,它将派生的直方图指标发送到名为 `histogram_metrics` 的 OpenSearch 索引。 + +#### 示例管道 + +```json +apache-log-pipeline-with-metrics: + source: + http: + # Provide the path for ingestion. ${pipelineName} will be replaced with pipeline name configured for this pipeline. + # In this case it would be "/apache-log-pipeline-with-metrics/logs". This will be the FluentBit output URI value. + path: "/${pipelineName}/logs" + processor: + - grok: + match: + log: [ "%{COMMONAPACHELOG_DATATYPED}" ] + sink: + - opensearch: + ... + index: "logs" + - pipeline: + name: "log-to-metrics-pipeline" + +log-to-metrics-pipeline: + source: + pipeline: + name: "apache-log-pipeline-with-metrics" + processor: + - aggregate: + # Specify the required identification keys + identification_keys: ["clientip", "request"] + action: + histogram: + # Specify the appropriate values for each of the following fields + key: "bytes" + record_minmax: true + units: "bytes" + buckets: [0, 25000000, 50000000, 75000000, 100000000] + # Pick the required aggregation period + group_duration: "30s" + sink: + - opensearch: + ... + index: "histogram_metrics" +``` diff --git a/i18n/zh/data-prepper/getting-started/configuring-pipelines.md b/i18n/zh/data-prepper/getting-started/configuring-pipelines.md new file mode 100644 index 00000000..e3b5d6d2 --- /dev/null +++ b/i18n/zh/data-prepper/getting-started/configuring-pipelines.md @@ -0,0 +1,141 @@ +--- +title: 配置管道 +--- + +# Configuring pipelines + +OpenSearch Data Prepper requires at least one pipeline to start. You define pipelines in YAML files in the `pipelines` directory of the Data Prepper home directory (`/usr/share/data-prepper/pipelines` in the Docker image). Data Prepper loads every YAML file in this directory at startup. + +## Pipeline structure + +A pipeline configuration has the following structure: + +```yaml +<pipeline-name>: + source: + <source-name>: + <source-options> + buffer: + <buffer-name>: + <buffer-options> + processor: + - <processor-name>: + <processor-options> + sink: + - <sink-name>: + <sink-options> + workers: <number-of-workers> + delay: <delay-in-milliseconds> +``` + +Each pipeline has a name and consists of the following components. + +| Component | Required | Description | +| :--- | :--- | :--- | +| [`source`](/data-prepper/pipelines/configuration/sources/sources) | Yes | The component that receives or reads data. Each pipeline has exactly one source. | +| [`buffer`](/data-prepper/pipelines/configuration/buffers/buffers) | No | The component that holds events between the source and the processors. If you don't specify a buffer, Data Prepper uses the [`bounded_blocking`](/data-prepper/pipelines/configuration/buffers/bounded-blocking) buffer. | +| [`processor`](/data-prepper/pipelines/configuration/processors/processors) | No | A list of processors that transform each event. Data Prepper runs the processors in the order in which they are listed. If you don't specify any processors, events pass through the pipeline unchanged. | +| [`sink`](/data-prepper/pipelines/configuration/sinks/sinks) | Yes | A list of one or more destinations for the processed events. Each event is sent to every sink. | + +A pipeline can also contain the following settings, which control how the pipeline reads events from the buffer. + +| Setting | Required | Description | +| :--- | :--- | :--- | +| `workers` | No | The number of threads that read events from the buffer and run the processors. Default is `1`. | +| `delay` | No | The number of milliseconds that each worker waits between buffer reads. Default is `3000`. | + +## Reading and writing files + +The following pipeline reads lines from a text file and writes them to another file. The pipeline doesn't specify a buffer or processors, so it uses the default buffer and passes events through unchanged: + +```yaml +file-pipeline: + source: + file: + path: /usr/share/data-prepper/data/input.txt + record_type: event + sink: + - file: + path: /usr/share/data-prepper/data/output.txt +``` + +::: warning IMPORTANT +The `record_type: event` setting makes the `file` source produce events. Without this setting, the source produces raw strings. Processors that operate on event fields, such as `uppercase_string`, cannot process raw strings: the pipeline produces no output and logs no error. +::: + +Data Prepper converts each line of `input.txt` into an event containing a `message` field and writes the events to `output.txt`. For example, an input file containing the lines `first line` and `second line` produces the following output: + +```json +{"message":"first line"} +{"message":"second line"} +``` + +## Pipeline containing all components + +The following pipeline specifies every component and setting: + +```yaml +uppercase-pipeline: + workers: 2 + delay: 100 + source: + file: + path: /usr/share/data-prepper/data/input.txt + record_type: event + buffer: + bounded_blocking: + buffer_size: 1024 + batch_size: 256 + processor: + - uppercase_string: + with_keys: ["message"] + sink: + - file: + path: /usr/share/data-prepper/data/output.txt +``` + +This pipeline processes events as follows: + +1. The `file` source reads each line of `input.txt` as an event and writes it to the buffer. +1. The `bounded_blocking` buffer holds up to 1,024 events. If the buffer is full, the source waits until space is available. +1. Two worker threads read from the buffer. Every 100 milliseconds, each worker reads up to 256 events. +1. Each worker runs the [`uppercase_string`](/data-prepper/pipelines/configuration/processors/uppercase-string) processor, which converts the value of the `message` field to uppercase. +1. The `file` sink writes the processed events to `output.txt`. + +The output file contains the following events: + +```json +{"message":"SECOND LINE"} +{"message":"FIRST LINE"} +``` + +Because two workers process events in parallel, the output order can differ from the input order. + +To run the pipelines on this page, see [Running pipelines that read and write files](/data-prepper/getting-started/running#running-pipelines-that-read-and-write-files). + +## Multiple pipelines + +A Data Prepper instance can run multiple pipelines. You can define each pipeline in its own file or define several pipelines in one file. For example, the following file defines two pipelines: + +```yaml +file-pipeline: + source: + file: + path: /usr/share/data-prepper/data/input.txt + record_type: event + sink: + - stdout: + +http-pipeline: + source: + http: + ssl: false + sink: + - stdout: +``` + +Pipelines can send events to each other. For more information, see [Pipelines](/data-prepper/pipelines/pipelines). + +## Next steps + +- [Run Data Prepper](/data-prepper/getting-started/running) and send it a test event. diff --git a/i18n/zh/data-prepper/getting-started/index.md b/i18n/zh/data-prepper/getting-started/index.md new file mode 100644 index 00000000..e0631e35 --- /dev/null +++ b/i18n/zh/data-prepper/getting-started/index.md @@ -0,0 +1,29 @@ +--- +title: 入门指南 +--- + +# Getting started with OpenSearch Data Prepper + +OpenSearch Data Prepper is a server-side data collector that receives data from your applications, transforms it, and sends it to OpenSearch. Data Prepper runs separately from OpenSearch and is not included in the OpenSearch installation packages. + +## Pipelines and events + +Data Prepper runs _pipelines_. Each pipeline reads data from a _source_, transforms or drops events using one or more _processors_, and writes the result to one or more _sinks_. Between the source and the processors, events wait in a _buffer_. For example, a pipeline can receive log lines over HTTP, parse each line into fields, and write the result to an OpenSearch index. A single Data Prepper instance can run multiple pipelines. + +An _event_ is a single data item, such as a log line, that moves through a pipeline. Each event consists of key-value pairs called _fields_, similar to a JSON object. When a pipeline writes to OpenSearch, each event becomes a document. Other sinks, such as Amazon S3, serialize events into files. Processors read and modify the fields of each event before the event reaches a sink. + +## Configuration files + +Data Prepper uses the following configuration files. + +| File | Required | Description | +| :--- | :--- | :--- | +| Pipeline configuration | Yes | One or more YAML files that define the pipelines to run, including their sources, processors, and sinks. Data Prepper does not provide a default pipeline and does not start if no pipeline configuration file exists. For more information, see [Configuring pipelines](/data-prepper/getting-started/configuring-pipelines). | +| `data-prepper-config.yaml` | No | Settings for the Data Prepper server, such as the port, TLS, and authentication for the [core APIs](/data-prepper/managing-data-prepper/core-apis). Data Prepper includes a default server configuration file. | +| `log4j2-rolling.properties` | No | The [Log4j 2](https://logging.apache.org/log4j/2.x/) logging configuration. Data Prepper includes a default logging configuration file. | + +Because a pipeline is required, you define at least one pipeline before you start Data Prepper. + +## Next steps + +To get started with Data Prepper, follow these steps in order: diff --git a/i18n/zh/data-prepper/getting-started/ingesting-log-data.md b/i18n/zh/data-prepper/getting-started/ingesting-log-data.md new file mode 100644 index 00000000..8a2cccd0 --- /dev/null +++ b/i18n/zh/data-prepper/getting-started/ingesting-log-data.md @@ -0,0 +1,310 @@ +--- +title: 将日志数据摄取到 OpenSearch +--- + +# Ingesting log data into OpenSearch + +In this tutorial, you'll run Data Prepper and OpenSearch in Docker, send raw Apache access logs to Data Prepper, and search the parsed log data in OpenSearch. The pipeline that you create performs the following tasks: + +1. Receives log lines over HTTP. +1. Parses each log line into separate fields, such as the client IP address, request path, and response code. +1. Converts the log timestamp into a date and the response code and size into integers. +1. Writes each event to an OpenSearch index and prints it to the Data Prepper log. + +The pipeline parses log lines in the Apache common log format, such as the following: + +```text +10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] "GET /checkout HTTP/1.1" 500 98 +``` + +Each line contains the client IP address, two identity fields (`-` when empty), the timestamp, the request (method, path, and HTTP version), the response code, and the response size in bytes. + +Docker Compose downloads the Data Prepper and OpenSearch images when you start the containers, so you don't need to install Data Prepper first. + +## Prerequisites + +Install [Docker](https://docs.docker.com/get-docker/), including [Docker Compose](https://docs.docker.com/compose/). The containers use ports `9200` (OpenSearch) and `2021` (Data Prepper), so make sure that these ports are not in use. + +If you're using Linux, increase the maximum number of memory maps available to OpenSearch. For more information, see [Important settings](/install-and-configure/install-opensearch/#important-settings). + +## Step 1: Define a pipeline + +Create a directory for this tutorial (for example, `data-prepper-tutorial`). In this directory, create a file named `pipelines.yaml` containing the following pipeline configuration. Replace `<custom-admin-password>` with a password that meets the [admin password requirements](/security/configuration/demo-configuration#admin-password-requirements). You'll also use this password for OpenSearch in the next step: + +```yaml +log-pipeline: + source: + http: + ssl: false + processor: + - grok: + match: + message: ['%{COMMONAPACHELOG}'] + - date: + match: + - key: timestamp + patterns: ["dd/MMM/yyyy:HH:mm:ss Z"] + destination: "@timestamp" + - convert_type: + keys: ["response", "bytes"] + type: integer + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index: web-logs + flush_timeout: -1 + - stdout: +``` + +This file defines one pipeline named `log-pipeline` containing the following components: + +- `source`: The [`http`](/data-prepper/pipelines/configuration/sources/http) source receives events on port `2021` at the `/log/ingest` path. The `ssl: false` setting accepts plain HTTP requests, which is suitable only for local testing. +- `processor`: Data Prepper runs the processors in the order in which they are listed: + - The [`grok`](/data-prepper/pipelines/configuration/processors/grok) processor matches the `message` field against the built-in `COMMONAPACHELOG` pattern and adds a field for each part of the log line, such as `clientip`, `verb`, `request`, `response`, `bytes`, and `timestamp`. + - The [`date`](/data-prepper/pipelines/configuration/processors/date) processor parses the `timestamp` field and writes the result to the `@timestamp` field in ISO 8601 format so that OpenSearch maps it as a date. + - The [`convert_type`](/data-prepper/pipelines/configuration/processors/convert-entry-type) processor converts the `response` and `bytes` fields from strings to integers so that you can run range queries on them. +- `sink`: Each event is sent to both sinks: + - The [`opensearch`](/data-prepper/pipelines/configuration/sinks/opensearch) sink writes events to the `web-logs` index. The `opensearch` hostname refers to the OpenSearch container that you'll define in the next step. The `insecure: true` setting skips certificate verification because the OpenSearch container uses demo certificates. By default, the sink waits up to 60 seconds to batch events before writing them to OpenSearch. Setting `flush_timeout` to `-1` writes events as soon as they are processed so that you can see the results immediately. + - The [`stdout`](/data-prepper/pipelines/configuration/sinks/stdout) sink prints each processed event to the Data Prepper log so that you can inspect it. + +## Step 2: Create the Docker Compose file + +In the same directory, create a file named `.env` containing the following line. Replace `<custom-admin-password>` with the password that you used in `pipelines.yaml`: + +```bash +OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password> +``` + +Docker Compose reads the `.env` file automatically and passes the password to OpenSearch. If the password does not meet the requirements, OpenSearch does not start. + +Create a file named `docker-compose.yml` containing the following configuration: + +```yaml +services: + opensearch: + image: opensearchproject/opensearch:latest + container_name: opensearch + environment: + - discovery.type=single-node + - OPENSEARCH_INITIAL_ADMIN_PASSWORD=${OPENSEARCH_INITIAL_ADMIN_PASSWORD} + ports: + - 9200:9200 + data-prepper: + image: opensearchproject/data-prepper:latest + container_name: data-prepper + volumes: + - ./pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml + ports: + - 2021:2021 + depends_on: + - opensearch +``` + +This file defines two containers: + +- `opensearch`: A single-node OpenSearch cluster with security enabled, available at `https://localhost:9200`. +- `data-prepper`: A Data Prepper instance. Data Prepper loads every pipeline configuration file in the `/usr/share/data-prepper/pipelines/` directory, so the `volumes` setting mounts your `pipelines.yaml` file into that directory. Port `2021` is published so that you can send data to the `http` source from your machine. + +Your directory now contains the following files: + +```text +data-prepper-tutorial/ +├── .env +├── docker-compose.yml +└── pipelines.yaml +``` + +## Step 3: Start the containers + +From the `data-prepper-tutorial` directory, start the containers in the background: + +```bash +docker compose up -d +``` + +Follow the Data Prepper log: + +```bash +docker compose logs -f data-prepper +``` + +While OpenSearch is starting, Data Prepper logs `Failed to initialize OpenSearch sink, retrying` warnings. These warnings are expected. Data Prepper retries until OpenSearch is available, which usually takes less than a minute. When the pipeline is ready, the log contains the following lines: + +```text +data-prepper | ... INFO org.opensearch.dataprepper.plugins.source.loghttp.HTTPSource - Started http source on port 2021... +data-prepper | ... INFO org.opensearch.dataprepper.plugins.sink.opensearch.OpenSearchSink - Initialized OpenSearch sink +``` + +Leave the log running and open a new terminal window for the next step. + +## Step 4: Send log data to Data Prepper + +The `http` source accepts a JSON array in which each object becomes one event. Send three Apache access log lines, each in the `message` field: + +```bash +curl -X POST http://localhost:2021/log/ingest \ + -H "Content-Type: application/json" \ + -d '[ + {"message": "192.168.1.10 - - [19/Oct/2026:10:15:32 +0000] \"GET /products/123 HTTP/1.1\" 200 5120"}, + {"message": "192.168.1.25 - - [19/Oct/2026:10:15:47 +0000] \"POST /cart HTTP/1.1\" 201 342"}, + {"message": "10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] \"GET /checkout HTTP/1.1\" 500 98"} + ]' +``` + +Data Prepper responds with `200 OK`. + +## Step 5: View the processed events + +Return to the terminal containing the Data Prepper log. The `stdout` sink prints each processed event on a single line. For example, the following event, formatted for readability, was created from the third log line: + +```json +{ + "message": "10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] \"GET /checkout HTTP/1.1\" 500 98", + "request": "/checkout", + "auth": "-", + "ident": "-", + "response": 500, + "bytes": 98, + "clientip": "10.0.0.7", + "verb": "GET", + "httpversion": "1.1", + "timestamp": "19/Oct/2026:10:16:03 +0000", + "@timestamp": "2026-10-19T10:16:03.000Z" +} +``` + +Compare the event to the log line that you sent: + +- The `message` field contains the original log line. +- The `grok` processor added the `clientip`, `ident`, `auth`, `timestamp`, `verb`, `request`, `httpversion`, `response`, and `bytes` fields. +- The `date` processor added the `@timestamp` field. +- The `convert_type` processor changed `response` and `bytes` to integers, so they appear without quotation marks. + +## Step 6: Search the data in OpenSearch + +The `opensearch` sink wrote the same events to the `web-logs` index. Search for requests that returned an error, which are those containing a response code of `400` or higher: + +```bash +curl -X GET "https://localhost:9200/web-logs/_search?pretty" -ku admin:<custom-admin-password> \ + -H "Content-Type: application/json" \ + -d '{ + "query": { + "range": { + "response": { + "gte": 400 + } + } + } + }' +``` + +The `-k` option skips certificate verification because OpenSearch uses demo certificates. The response contains the event for the request that returned a `500` response code: + +```json +{ + "took" : 41, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "web-logs", + "_id" : "QJmSVKEBVverMSge8P0k", + "_score" : 1.0, + "_source":{"message":"10.0.0.7 - - [19/Oct/2026:10:16:03 +0000] \"GET /checkout HTTP/1.1\" 500 98","request":"/checkout","auth":"-","ident":"-","response":500,"bytes":98,"clientip":"10.0.0.7","verb":"GET","httpversion":"1.1","timestamp":"19/Oct/2026:10:16:03 +0000","@timestamp":"2026-10-19T10:16:03.000Z"} + } + ] + } +} +``` + +The range query works because the `convert_type` processor converted `response` to an integer before the event reached OpenSearch. + +## Step 7: Modify the pipeline + +Data Prepper reads pipeline configuration files only at startup, so you must restart Data Prepper after changing a pipeline. + +The `timestamp` field duplicates the `@timestamp` field. To remove it, add a [`delete_entries`](/data-prepper/pipelines/configuration/processors/delete-entries) processor to the end of the `processor` list in `pipelines.yaml`: + +```yaml + processor: + - grok: + match: + message: ['%{COMMONAPACHELOG}'] + - date: + match: + - key: timestamp + patterns: ["dd/MMM/yyyy:HH:mm:ss Z"] + destination: "@timestamp" + - convert_type: + keys: ["response", "bytes"] + type: integer + - delete_entries: + with_keys: ["timestamp"] +``` + +Restart Data Prepper: + +```bash +docker compose restart data-prepper +``` + +Wait until the Data Prepper log contains a new `Started http source on port 2021` line, and then send another log line: + +```bash +curl -X POST http://localhost:2021/log/ingest \ + -H "Content-Type: application/json" \ + -d '[ + {"message": "10.0.0.7 - - [19/Oct/2026:10:20:11 +0000] \"GET /checkout HTTP/1.1\" 503 64"} + ]' +``` + +The new event in the Data Prepper log no longer contains the `timestamp` field: + +```json +{ + "message": "10.0.0.7 - - [19/Oct/2026:10:20:11 +0000] \"GET /checkout HTTP/1.1\" 503 64", + "request": "/checkout", + "auth": "-", + "ident": "-", + "response": 503, + "bytes": 64, + "clientip": "10.0.0.7", + "verb": "GET", + "httpversion": "1.1", + "@timestamp": "2026-10-19T10:20:11.000Z" +} +``` + +Events that were indexed before the change are not modified. + +## Step 8: Clean up + +To stop and remove the containers, run the following command from the `data-prepper-tutorial` directory: + +```bash +docker compose down +``` + +The containers do not use volumes, so removing them deletes the `web-logs` index. + +## Next steps + +- To learn about pipeline structure, conditional routing, and other pipeline options, see [Pipelines](/data-prepper/pipelines/pipelines). +- To find the sources, processors, and sinks that you can use in a pipeline, see [Sources](/data-prepper/pipelines/configuration/sources/sources), [Processors](/data-prepper/pipelines/configuration/processors/processors), and [Sinks](/data-prepper/pipelines/configuration/sinks/sinks). Some processor pages include complete examples that send data to `localhost:2021` and write to `https://opensearch:9200`. You can run these examples in the environment from this tutorial by copying the example pipeline into `pipelines.yaml`, replacing `<custom-admin-password>` with the admin password from your `.env` file, and restarting Data Prepper. +- To configure the Data Prepper server, including its port, TLS, and authentication, see [Configuring OpenSearch Data Prepper](/data-prepper/managing-data-prepper/configuring-data-prepper). +- To set up Data Prepper for common use cases, see [Log analytics](/data-prepper/common-use-cases/log-analytics) and [Trace analytics](/data-prepper/common-use-cases/trace-analytics). +- To send logs from a log collector instead of `curl`, see the Data Prepper repository examples for [Fluent Bit](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion), [Fluentd](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion-fluentd), [Kubernetes](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion-k8s), and [Amazon ECS FireLens](https://github.com/opensearch-project/data-prepper/tree/main/examples/log-ingestion-ecs-firelens). diff --git a/i18n/zh/data-prepper/getting-started/installing.md b/i18n/zh/data-prepper/getting-started/installing.md new file mode 100644 index 00000000..2648e5d7 --- /dev/null +++ b/i18n/zh/data-prepper/getting-started/installing.md @@ -0,0 +1,84 @@ +--- +title: 安装和配置 Data Prepper +--- + +# Installing and configuring Data Prepper + +You can install OpenSearch Data Prepper using the Docker image or a Linux archive. To build Data Prepper from source, see the [Data Prepper Developer Guide](https://github.com/opensearch-project/data-prepper/blob/main/docs/developer_guide.md). + +## Installing the Docker image + +To use Data Prepper in Docker, install [Docker](https://docs.docker.com/get-docker/) and pull the Data Prepper image: + +```bash +docker pull opensearchproject/data-prepper:latest +``` + +The Data Prepper home directory in the image is `/usr/share/data-prepper`. To provide configuration files, mount them into this directory when you start the container. For more information, see [Running Data Prepper](/data-prepper/getting-started/running). + +## Installing a Linux archive + +Download a Data Prepper archive for your platform from the [OpenSearch downloads page](https://opensearch.org/downloads/). Each release provides the following archives: + +- `opensearch-data-prepper-jdk-<version>-linux-<architecture>.tar.gz`: Includes a Java runtime. +- `opensearch-data-prepper-<version>-linux-<architecture>.tar.gz`: Does not include a Java runtime. To use this archive, install Java on your host. + +Extract the archive, replacing `<version>` and `<architecture>` with the values in the file name: + +```bash +tar -xzf opensearch-data-prepper-jdk-<version>-linux-<architecture>.tar.gz +``` + +The extracted directory is the Data Prepper home directory. + +## Directory structure + +The Data Prepper home directory contains the following files and directories. + +| Path | Description | +| :--- | :--- | +| `bin/data-prepper` | The script that starts Data Prepper. | +| `pipelines/` | The directory for pipeline configuration files. Data Prepper loads every YAML file in this directory. This directory contains no pipelines after installation. | +| `config/data-prepper-config.yaml` | The Data Prepper server configuration file. | +| `config/log4j2-rolling.properties` | The Log4j 2 logging configuration file. | +| `lib/` | The Data Prepper libraries and plugins. | + +## Server and logging configuration + +Data Prepper also reads the following optional configuration files from the `config` directory of the Data Prepper home directory. + +### Server configuration + +The `config/data-prepper-config.yaml` file configures the Data Prepper server, which exposes the [core APIs](/data-prepper/managing-data-prepper/core-apis) on port `4900`. The Docker image and the Linux archives include different default server configurations. + +| Setting | Docker image | Linux archive | +| :--- | :--- | :--- | +| TLS | Enabled, using a self-signed certificate. Send requests using `https`. | Disabled. Send requests using `http`. | +| Authentication | HTTP basic authentication using the username `admin` and the password `admin`. | None. | + +::: danger WARNING +The default certificate and credentials in the Docker image are intended for testing only. Replace them before using Data Prepper in production. +::: + +To change these settings, replace `config/data-prepper-config.yaml` with your own file. For example, the following file disables TLS for the core APIs: + +```yaml +ssl: false +serverPort: 4900 +``` + +For all server settings, see [Configuring OpenSearch Data Prepper](/data-prepper/managing-data-prepper/configuring-data-prepper). + +### Logging configuration + +Data Prepper reads its logging configuration from `config/log4j2-rolling.properties`. To customize logging, either replace this file or set the `JAVA_OPTS` environment variable to point to a different file: + +```bash +export JAVA_OPTS="-Dlog4j.configurationFile=/path/to/log4j2.properties" +``` + +For more information, see [Configuring Log4j](/data-prepper/managing-data-prepper/configuring-log4j). + +## Next steps + +- [Configure a pipeline](/data-prepper/getting-started/configuring-pipelines) for Data Prepper to run. diff --git a/i18n/zh/data-prepper/getting-started/running.md b/i18n/zh/data-prepper/getting-started/running.md new file mode 100644 index 00000000..94eebda9 --- /dev/null +++ b/i18n/zh/data-prepper/getting-started/running.md @@ -0,0 +1,167 @@ +--- +title: 运行 Data Prepper +--- + +# Running Data Prepper + +OpenSearch Data Prepper requires at least one pipeline to start. If Data Prepper finds no pipeline configuration file, it logs the following error and exits: + +```text +ERROR org.opensearch.dataprepper.pipeline.parser.PipelineConfigurationFileReader - Pipelines configuration file not found at /usr/share/data-prepper/pipelines +``` + +On this page, you'll define a minimal pipeline, start Data Prepper, and send it a test event. If you haven't installed Data Prepper, see [Installing Data Prepper](/data-prepper/getting-started/installing). For more information about pipeline configuration, see [Configuring pipelines](/data-prepper/getting-started/configuring-pipelines). + +## Step 1: Define a pipeline + +Create a file named `pipelines.yaml` containing the following pipeline configuration: + +```yaml +test-pipeline: + source: + http: + ssl: false + sink: + - stdout: +``` + +This pipeline, named `test-pipeline`, receives events using the [`http`](/data-prepper/pipelines/configuration/sources/http) source on port `2021` and prints each event to the Data Prepper log using the [`stdout`](/data-prepper/pipelines/configuration/sinks/stdout) sink. The pipeline contains no processors, so events are not modified. + +## Step 2: Start Data Prepper + +Start Data Prepper using the Docker image or a Linux archive. + +### Docker + +From the directory containing `pipelines.yaml`, run the following command: + +```bash +docker run --name data-prepper \ + -p 2021:2021 -p 4900:4900 \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + opensearchproject/data-prepper:latest +``` + +The `-v` option mounts `pipelines.yaml` into the `pipelines` directory of the container. `${PWD}` is your current directory, so `${PWD}/pipelines.yaml` is the absolute path to the file, which Docker requires for mounts. The `-p` options publish port `2021` for the `http` source and port `4900` for the [core APIs](/data-prepper/managing-data-prepper/core-apis). + +To use your own server configuration file, mount it as `/usr/share/data-prepper/config/data-prepper-config.yaml`: + +```bash +docker run --name data-prepper \ + -p 2021:2021 -p 4900:4900 \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + -v ${PWD}/data-prepper-config.yaml:/usr/share/data-prepper/config/data-prepper-config.yaml \ + opensearchproject/data-prepper:latest +``` + +### Linux archive + +Copy `pipelines.yaml` into the `pipelines` directory of the Data Prepper home directory. Then run the following command from the home directory: + +```bash +bin/data-prepper +``` + +Alternatively, provide the pipeline configuration file and the server configuration file as arguments, in that order: + +```bash +bin/data-prepper /path/to/pipelines.yaml /path/to/data-prepper-config.yaml +``` + +## Step 3: Send a test event + +When the pipeline is ready, the Data Prepper log contains the following line: + +```text +INFO org.opensearch.dataprepper.plugins.source.loghttp.HTTPSource - Started http source on port 2021... +``` + +In a new terminal window, send an event to the `http` source. The source accepts a JSON array in which each object becomes one event: + +```bash +curl -X POST http://localhost:2021/log/ingest \ + -H "Content-Type: application/json" \ + -d '[{"message": "Hello, Data Prepper!"}]' +``` + +Data Prepper responds with `200 OK`, and the `stdout` sink prints the event to the Data Prepper log: + +```json +{"message":"Hello, Data Prepper!"} +``` + +## Step 4: List the running pipelines + +To list the running pipelines, send a request to the core APIs. The request depends on the [default server configuration](/data-prepper/getting-started/installing#server-configuration) of your installation. + +For the Docker image, use `https` and the default credentials. The `-k` option skips certificate verification because the image uses a self-signed certificate: + +```bash +curl -k -u admin:admin https://localhost:4900/list +``` + +For a Linux archive, use `http`: + +```bash +curl http://localhost:4900/list +``` + +The response contains the pipeline that you defined: + +```json +{"pipelines":[{"name":"test-pipeline"}]} +``` + +## Step 5: Stop Data Prepper + +To stop Data Prepper, press `Ctrl+C` in the terminal in which Data Prepper is running. If you started the Docker container in the background, run `docker stop data-prepper`. + +Alternatively, send a shutdown request to the core APIs. For the Docker image, send the following request: + +```bash +curl -k -u admin:admin -X POST https://localhost:4900/shutdown +``` + +For a Linux archive, send the following request: + +```bash +curl -X POST http://localhost:4900/shutdown +``` + +To remove the stopped Docker container so that you can reuse the `data-prepper` container name, run `docker rm data-prepper`. + +## Running pipelines that read and write files + +The file-based examples in [Configuring pipelines](/data-prepper/getting-started/configuring-pipelines) read from and write to the `/usr/share/data-prepper/data` directory. To run these examples, create a `data` directory containing an `input.txt` file. + +In Docker, mount the `data` directory into the container along with the pipeline file: + +```bash +docker run --name data-prepper \ + -v ${PWD}/pipelines.yaml:/usr/share/data-prepper/pipelines/pipelines.yaml \ + -v ${PWD}/data:/usr/share/data-prepper/data \ + opensearchproject/data-prepper:latest +``` + +Data Prepper writes the processed events to `data/output.txt`. + +For a Linux archive, replace the `path` values in the pipeline with the absolute paths to the input and output files on your host. + +## Running multiple pipelines + +Data Prepper loads every YAML file in the `pipelines` directory, and each file can define one or more pipelines. For more information, see [Multiple pipelines](/data-prepper/getting-started/configuring-pipelines#multiple-pipelines). To run pipelines from multiple files in Docker, mount a directory instead of a single file: + +```bash +docker run --name data-prepper \ + -p 2021:2021 -p 4900:4900 \ + -v ${PWD}/pipelines:/usr/share/data-prepper/pipelines \ + opensearchproject/data-prepper:latest +``` + +## Updating pipelines + +Data Prepper reads pipeline configuration files only at startup. After you edit, add, or delete a pipeline configuration file, restart Data Prepper to apply the change. + +## Next steps + +- [Ingest log data into OpenSearch](/data-prepper/getting-started/ingesting-log-data) by building a pipeline that parses raw Apache access logs and writes them to OpenSearch. diff --git a/i18n/zh/data-prepper/managing-data-prepper/extensions/extensions.md b/i18n/zh/data-prepper/managing-data-prepper/extensions/extensions.md new file mode 100644 index 00000000..88867b08 --- /dev/null +++ b/i18n/zh/data-prepper/managing-data-prepper/extensions/extensions.md @@ -0,0 +1,10 @@ +--- +title: 扩展 +--- + +# Data Prepper extensions + +OpenSearch Data Prepper extensions provide Data Prepper functionality outside of core Data Prepper pipeline components. +Many extensions provide configuration options that give Data Prepper administrators greater flexibility over Data Prepper's functionality. + +Extension configurations can be configured in the `data-prepper-config.yaml` file under the `extensions:` YAML block. diff --git a/i18n/zh/data-prepper/managing-data-prepper/extensions/geoip-service.md b/i18n/zh/data-prepper/managing-data-prepper/extensions/geoip-service.md new file mode 100644 index 00000000..70d35239 --- /dev/null +++ b/i18n/zh/data-prepper/managing-data-prepper/extensions/geoip-service.md @@ -0,0 +1,68 @@ +--- +title: geoip_service +--- + +# GeoIP service extension + +The `geoip_service` extension configures all [`geoip`](/data-prepper/pipelines/configuration/processors/geoip) processors in OpenSearch Data Prepper. + +## Usage + +You can configure the GeoIP service that Data Prepper uses for the `geoip` processor. +By default, the GeoIP service comes with the [`maxmind`](#maxmind) option configured. + +The following example shows how to configure the `geoip_service` in the `data-prepper-config.yaml` file: + +``` +extensions: + geoip_service: + maxmind: + database_refresh_interval: PT1H + cache_count: 16_384 +``` + +<!-- vale off --> +## maxmind +<!-- vale on --> + +The GeoIP service supports the MaxMind [GeoIP and GeoLite](https://dev.maxmind.com/geoip) databases. +By default, Data Prepper will use all three of the following [MaxMind GeoLite2](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) databases: + +* City +* Country +* ASN + +The service also downloads databases automatically to keep Data Prepper up to date with changes from MaxMind. + +You can use the following options to configure the `maxmind` extension. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`databases` | No | [database](#database) | The database configuration. +`database_refresh_interval` | No | Duration | How frequently to check for updates from MaxMind. This can be any duration in the range of 15 minutes to 30 days. Default is `PT7D`. +`cache_count` | No | Integer | The maximum cache count by number of items in the cache, with a range of 100--100,000. Default is `4096`. +`database_destination` | No | String | The name of the directory in which to store downloaded databases. Default is `{data-prepper.dir}/data/geoip`. +`aws` | No | [`aws`](#aws) | Configures the AWS credentials for downloading the database from Amazon Simple Storage Service (Amazon S3). +`insecure` | No | Boolean | When `true`, this options allows you to download database files over HTTP. Default is `false`. + +<!-- vale off --> +## database +<!-- vale on --> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`city` | No | String | The URL of the city in which the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. +`country` | No | String | The URL of the country in which the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. +`asn` | No | String | The URL of the Autonomous System Number (ASN) of where the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. +`enterprise` | No | String | The URL of the enterprise in which the database resides. Can be an HTTP URL for a manifest file, an MMDB file, or an S3 URL. + +<!-- vale off --> +## aws +<!-- vale on --> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for the credentials. Default is the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon S3. Default is `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`aws_sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes when downloading from Amazon S3. +`sts_external_id` | No | String | An STS external ID used when Data Prepper assumes the STS role. For more information, see the `ExternalID` documentation in the [STS AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API reference. diff --git a/i18n/zh/data-prepper/managing-data-prepper/latency.md b/i18n/zh/data-prepper/managing-data-prepper/latency.md new file mode 100644 index 00000000..1e839d4f --- /dev/null +++ b/i18n/zh/data-prepper/managing-data-prepper/latency.md @@ -0,0 +1,147 @@ +--- +title: Pipeline latency tuning guide +--- + +# Pipeline latency tuning guide + +This section provides the most effective configurations for reducing end-to-end latency and contains ready-to-use examples. + +There are two latency types: + +- **Ingest latency**: The amount of time from the moment the source receives data until the sink sends it to OpenSearch or another destination. +- **Searchable latency**: The amount of time until data becomes visible in OpenSearch search results. This is capped by the index's `refresh_interval`. + +## Low-latency configuration + +The following table lists configurations that can be adjusted to improve latency. + +Component | Setting | Why it matters | Low‑latency starting point | Trade‑offs +:--- | :--- | :--- | :--- | :--- +**Pipeline loop** | `workers` in each pipeline | Increasing parallelism reduces queueing in CPU- or I/O-bound pipelines. | Typically set to the number of CPU cores; increase if sinks are I/O bound. | Higher CPU usage and more concurrent requests sent to sinks. +**Pipeline loop** | `delay` | The pause between buffer reads. | `0`--`10ms` to pull data as soon as possible. | Lower delays reduce latency but increase polling overhead, context switches, and CPU activations. Adjust to balance latency and CPU usage. +**Bounded blocking buffer** | `batch_size` | Determines how many records are processed per batch; smaller batches flush sooner. | 64--256 | Smaller batches reduce throughput and increase the number of requests. +**Peer Forwarder** | `batch_size`, `request_timeout` | Batch size and request timeouts impact hop-to-hop latency. | Keep `batch_size` moderate, for example, 48--128. | Too small a `batch_size` reduces throughput, and a `request_timeout` that is too short can cause retries or timeouts under load. +**Peer Forwarder** | `forwarder` [configuration](/data-prepper/managing-data-prepper/peer-forwarder#configuration) | Limits queueing before forwarding. | Use low timeouts, for example, 50–200 ms. | Shorter timeouts increase in-flight requests and connections, adding CPU, memory, TLS handshake, and context-switch overhead. Longer timeouts can cause queue buildup and higher tail latency. +**Aggregate processors** | `group_duration` | Determines how long events wait for the aggregation window to close. | Prefer removing aggregation; if needed, keep the window short, for example, `5s`. | Smaller windows can break grouping semantics. +**OpenSearch sink** | `bulk_size` (MiB) | Determines the size of bulk requests; smaller bulks flush sooner. | 1--5 MiB | Very small `bulk_size` increases the number of bulk requests, adds HTTP/TLS overhead, causes more thread pool contention, produces smaller Lucene batches, and lowers throughput. Very large `bulk_size` increases the time needed to fill a batch and can cause memory spikes, larger retries, and higher p95/p99 latency. +**OpenSearch sink** | `index.refresh_interval` | Controls how frequently indexed data becomes searchable. | `1s` (default) | Lower values increase segment churn and indexing overhead. + +::: info NOTE +The `delay` processor adds latency by design. Avoid it in low‑latency pipelines. +::: + +## Low‑latency configuration examples + +The following are low-latency configuration examples. + +### Logs: Prioritize sub‑second ingest + +You can use the following example when you need sub‑second end‑to‑end ingest for HTTP log intake. It minimizes batching and avoids heavy processors so events flush to OpenSearch quickly while keeping CPU costs predictable: + +```yaml +logs-low-latency: + workers: 4 + delay: 0 + source: + http: + port: 2021 + path: /logs + ssl: true + sslKeyCertChainFile: certs/dp.crt + sslKeyFile: certs/dp.key + buffer: + bounded_blocking: + buffer_size: 4096 + batch_size: 128 + processor: [] # keep light, avoid heavy aggregation + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index_type: log-analytics + bulk_size: 1 # MiB; smaller -> lower latency, lower throughput + max_retries: 8 +``` + +### Traces with peer forwarding minimizing cross‑node wait + +You can use the following example configuration to minimize cross‑node wait for distributed tracing. The `data-prepper-config.yaml` file enables low‑latency, mTLS‑secured peer forwarding with fast timeouts, and the `pipelines.yml` file splits ingestion from raw indexing so that the forwarding hop stays lightweight. + +Create the following `data-prepper-config.yaml` file: + +```yaml + +ssl: true +serverPort: 4900 +keyStoreFilePath: certs/dp1-admin.p12 # or .jks +keyStorePassword: changeit +privateKeyPassword: changeit + +# Or disable ssl on top-level admin/metrics server +#ssl: false +#serverPort: 4900 + +authentication: + http_basic: + username: myuser + password: "mys3cr3t" + # or disable http_basic authentication + #unauthenticated: + +peer_forwarder: + + ssl: true + ssl_certificate_file: certs/dp1-peer.crt + ssl_key_file: certs/dp1-peer.key + authentication: + mutual_tls: {} + port: 4994 # Default + # choose one discovery mode + # Discovery mode: dns + discovery_mode: dns + domain_name: data-prepper.your-domain.local + + # discovery_mode: static + #port: 4994 + #static_endpoints: ["dp1", "dp2"] + + # lower batching/wait + batch_size: 96 + request_timeout: 1000 # ms +``` + +Create the following `pipelines.yml` file: + +```yaml +traces-low-latency: + workers: 4 + delay: 0 + source: + otel_trace_source: + port: 21890 + ssl: true + sslKeyCertChainFile: certs/dp.crt + sslKeyFile: certs/dp.key + buffer: + bounded_blocking: + buffer_size: 4096 + batch_size: 96 + processor: + - trace_peer_forwarder: {} + sink: + - pipeline: + name: raw-trace-pipeline # feed the next pipeline + +raw-trace-pipeline: + source: + pipeline: + name: traces-low-latency # consumes from above + processor: + - otel_traces: + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: trace-analytics-raw +``` diff --git a/i18n/zh/data-prepper/pipelines/cidrcontains.md b/i18n/zh/data-prepper/pipelines/cidrcontains.md new file mode 100644 index 00000000..e1d1a3f3 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/cidrcontains.md @@ -0,0 +1,98 @@ +--- +title: cidrContains() +--- + +<!-- vale off --> +# cidrContains() function +<!-- vale on --> + +The `cidrContains()` function is used to check if an IP address is contained within a specified Classless Inter-Domain Routing (CIDR) block or range of CIDR blocks. It accepts two or more arguments: + +- The first argument is a JSON pointer, which represents the key or path to the field containing the IP address to be checked. It supports both IPv4 and IPv6 address formats. + +- The subsequent arguments are strings representing one or more CIDR blocks or IP address ranges. The function checks if the IP address specified in the first argument matches or is contained within any of these CIDR blocks. + +For example, if your data contains an IP address field named `client.ip` and you want to check if it belongs to the CIDR blocks `192.168.0.0/16` or `10.0.0.0/8`, you can use the `cidrContains()` function as follows: + +``` +cidrContains('/client.ip', '192.168.0.0/16', '10.0.0.0/8') +``` + +This function returns `true` if the IP address matches any of the specified CIDR blocks or `false` if it does not. + +## Example + +The following pipeline discards any documents that are not part of the specified CIDR blocks: + +```yaml +cidr-allowlist-pipeline: + source: + http: + path: /events + ssl: true + sslKeyCertChainFile: certs/dp.crt + sslKeyFile: certs/dp.key + processor: + - drop_events: + # Drop events whose client IP is NOT in specific CIDR allowlist + drop_when: 'not cidrContains(/client/ip, "10.0.0.0/8", "192.168.0.0/16", "fd00::/8")' + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: logs-%{yyyy.MM.dd} +``` + +You can test this pipeline using the following command: + +```bash +curl -ksS -X POST "https://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"client":{"ip":"10.23.45.6"},"msg":"allowed 10/8"}, + {"client":{"ip":"8.8.8.8"},"msg":"should be dropped"}, + {"client":{"ip":"fd00::1234"},"msg":"allowed ULA IPv6"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs-2025.10.14", + "_id": "Ng1i4pkBLPEKXekW48BU", + "_score": 1, + "_source": { + "client": { + "ip": "10.23.45.6" + }, + "msg": "allowed 10/8" + } + }, + { + "_index": "logs-2025.10.14", + "_id": "Nw1i4pkBLPEKXekW48BU", + "_score": 1, + "_source": { + "client": { + "ip": "fd00::1234" + }, + "msg": "allowed ULA IPv6" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/aws-lambda.md b/i18n/zh/data-prepper/pipelines/configuration/processors/aws-lambda.md new file mode 100644 index 00000000..522aa017 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/aws-lambda.md @@ -0,0 +1,270 @@ +--- +title: AWS Lambda +--- + +# AWS Lambda processor + +The [AWS Lambda](https://aws.amazon.com/lambda/) integration allows you to use serverless computing capabilities within your OpenSearch Data Prepper pipelines for flexible event processing and data routing. + +## Configuration + +The `aws_lambda` processor enables invocation of an AWS Lambda function within your Data Prepper pipeline in order to process events. It supports both synchronous and asynchronous invocations based on your use case. + +## Configuration fields + +You can configure the processor using the following configuration options. + +Field | Type | Required | Description +-------------------- | ------- | -------- | ---------------------------------------------------------------------------- +`function_name` | String | Required | The name of the AWS Lambda function to invoke. Must be 3--500 characters. +`aws.region` | String | Required | The AWS Region in which the Lambda function is located. +`aws.sts_role_arn` | String | Optional | The Amazon Resource Name (ARN) of the role to assume before invoking the Lambda function. Must be 20--2048 characters. +`aws.sts_external_id` | String | Optional | An external ID for STS role assumption. Must be 2--1224 characters. +`aws.sts_header_overrides` | Map | Optional | STS header overrides. Maximum of 5 headers supported. +`client.max_retries` | Integer | Optional | The maximum number of retries for failed invocations. Default is `3`. +`client.api_call_timeout` | Duration | Optional | The API call timeout. Default is `60s`. +`client.api_call_attempt_timeout` | Duration | Optional | The timeout for individual API call attempts. If not specified, AWS SDK defaults are used. +`client.connection_timeout` | Duration | Optional | The SDK connection timeout. Default is `60s`. +`client.read_timeout` | Duration | Optional | The amount of time the SDK waits for data to be read from an established connection. If not specified, AWS SDK defaults are used. +`client.max_concurrency` | Integer | Optional | The maximum number of concurrent threads on the client. Default is `200`. +`client.base_delay` | Duration | Optional | The base delay for the exponential backoff. Default is `100ms`. +`client.max_backoff` | Duration | Optional | The maximum backoff time for the exponential backoff. Default is `20s`. +`client.retryable_status_codes` | List | Optional | A list of HTTP status codes that trigger a retry when returned by a Lambda invocation, for example `[500, 502, 503, 504]`. Default is an empty list, in which case Data Prepper retries only throttling errors, Lambda service errors, and network or connection errors. Use for idempotent functions for which retrying transient server-side errors is safe. +`batch` | Object | Optional | The batch settings for the Lambda invocations. Contains `key_name` (default: `"events"`) and `threshold` object with `event_count` (default: `100`), `maximum_size` (default: `"5mb"`), and `event_collect_timeout` (default: `10s`). See [Batch processing](#batch-processing) for details. +`lambda_when` | String | Optional | A conditional expression that determines when to invoke the Lambda processor. +`response_codec` | Object | Optional | A codec configuration for parsing Lambda responses. Default is `json`. +`tags_on_failure` | List | Optional | A list of tags to add to events when the Lambda function fails or encounters an exception. +`response_events_match` | Boolean | Optional | Specifies how Data Prepper interprets and processes Lambda function responses. Default is `false`. +`response_mode` | String | Optional | The response handling mode, either `replace` or `merge`. Default is `replace`. +`invocation_type` | String | Optional | The Lambda invocation type. Valid values are `request-response`, `event`, and `streaming-response`. Default is `request-response`. See [Usage](#usage). +`streaming` | Object | Optional | The response streaming configuration. Response streaming is used only when `invocation_type` is `streaming-response` and `streaming.enabled` is `true`. When `streaming` is specified, `batch.threshold.event_count` must be `1`. See [Response streaming](#response-streaming). +`streaming.enabled` | Boolean | Optional | Whether to invoke the Lambda function using response streaming. Default is `false`. +`streaming.response_handling` | String | Optional | Specifies how the streamed response is converted into events. The only valid value is `reconstruct-document`, which merges all parsed chunks of the streamed response into the original event. Default is `reconstruct-document`. +`keys` | List | Optional | Keys to send to the Lambda function. +`cache` | Object | Optional | The cache configuration. Only valid when `response_mode` is `merge` and `keys` are specified. +`cache.ttl` | Long | Optional | The cache time-to-live. +`cache.max_size` | Long | Optional | The maximum cache size. Must be between 1048576 and 10485760. +`circuit_breaker_retries` | Integer | Optional | The maximum number of circuit breaker checks before proceeding. Default is `0`. +`circuit_breaker_wait_interval` | Long | Optional | The amount of time, in milliseconds, between circuit breaker checks. Default is `1000ms`. + +The following is an example configuration: + +```yaml +processor: + - aws_lambda: + function_name: my-lambda-function + response_events_match: false + response_mode: merge + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/my-lambda-role + client: + max_retries: 3 + api_call_timeout: PT60S + api_call_attempt_timeout: PT30S # Optional: per-attempt timeout + connection_timeout: PT60S + read_timeout: PT15M # Optional: for long-running Lambda functions + max_concurrency: 200 + base_delay: "PT0.1S" + max_backoff: "PT20S" + retryable_status_codes: [500, 502, 503, 504] # Optional: retry these Lambda invocation status codes + batch: + key_name: events + threshold: + event_count: 100 + maximum_size: 5mb + event_collect_timeout: PT10S + lambda_when: "/some_key == null" + keys: ["key1", "key2"] + cache: + ttl: 3600 + max_size: 5242880 + circuit_breaker_retries: 0 + circuit_breaker_wait_interval: 1000 + tags_on_failure: ["lambda_failed"] +``` + +## Timeout configuration + +The `aws_lambda` processor supports multiple timeout layers following AWS SDK best practices: + +- `api_call_timeout`: The total amount of time for the entire API call including all retries. +- `api_call_attempt_timeout`: The time limit for each individual attempt. +- `read_timeout`: The amount of time to wait for data from an established connection. + +For Lambda functions that run for longer than 60 seconds, configure both `api_call_timeout` and `read_timeout` to appropriate values. The `api_call_attempt_timeout` enforces a per-attempt timeout, enabling fast failure of slow requests while preserving overall retry behavior. + +## Usage + +The processor supports the following invocation types: + +- `request-response`: The processor waits for Lambda function completion before proceeding. +- `event`: The function is triggered asynchronously without waiting for a response. +- `streaming-response`: The processor invokes the function using Lambda response streaming and waits for the complete streamed response. Requires `streaming.enabled` to be `true`. See [Response streaming](#response-streaming). + +The `cache` setting is valid only when `invocation_type` is `request-response`. + +### Response streaming + +Use response streaming for Lambda functions that return large responses in multiple chunks. The processor collects all chunks of the streamed response, parses them using the `response_codec`, and merges the resulting data into the original event. Because each response is merged into a single original event, `batch.threshold.event_count` must be set to `1`. + +The following example configures response streaming: + +```yaml +processor: + - aws_lambda: + function_name: my-streaming-function + invocation_type: streaming-response + streaming: + enabled: true + response_handling: reconstruct-document + batch: + threshold: + event_count: 1 + aws: + region: us-east-1 + sts_role_arn: arn:aws:iam::123456789012:role/my-lambda-role +``` + +### Batch processing + +The `aws_lambda` processor batches events when invoking Lambda functions. The `batch` configuration allows you to configure the thresholds for bulk invocations. + +The `batch` configuration has the following structure: + +- `key_name`: The key under which events are grouped in the payload sent to Lambda (default: `"events"`). +- `threshold`: An object containing batch threshold settings: + - `event_count`: Maximum number of events per batch (default: `100`). + - `maximum_size`: Maximum batch size (default: `5mb`). + - `event_collect_timeout`: Maximum time to wait for collecting events before sending the batch (default: `10s`). Must be between 1 second and 3600 seconds. + +**Important**: The `event_collect_timeout` parameter must be specified under `batch.threshold`, not directly under `batch`. + +### Response handling + +The processor supports two response modes: +- `replace`: Lambda response replaces the original event data (default) +- `merge`: Lambda response is merged with the original event data + +### Caching + +When `response_mode` is set to `merge` and `keys` are specified, the processor can cache Lambda responses to improve performance for repeated requests. + +### Circuit breaker + +The processor includes circuit breaker functionality to handle memory pressure situations gracefully. + +### Tags on failure + +Custom tags can be applied to events when Lambda processing fails or encounters exceptions using the `tags_on_failure` configuration. + +## Behavior + +When configured for batching, the `aws_lambda` processor groups multiple events into a single request. This grouping is governed by batch thresholds, which can be based on the event count, size limit, or timeout. The processor then sends the entire batch to the Lambda function as a single payload. + +## Lambda response handling + +The `response_events_match` setting defines how Data Prepper handles the relationship between batch events sent to Lambda and the response received: + +- `true`: Lambda returns a JSON array with results for each batched event. Data Prepper maps this array back to its corresponding original event, ensuring that each event in the batch gets the corresponding part of the response from the array. +- `false`: Lambda returns one or more events for the entire batch. Response events are not correlated with the original events. Original event metadata is not preserved in the response events. For example, when `response_events_match` is set to `true`, the Lambda function is expected to return the same number of response events as the number of original requests, maintaining the original order. + +## Lambda function implementation + +When Data Prepper invokes your Lambda function it sends a JSON object with events grouped under the configured `key_name` (default: `"events"`). + +### Input format + +Your Lambda function receives the following input structure: + +```json +{ + "events": [ + {"field1": "value1", "field2": "value2"}, + {"field1": "value3", "field2": "value4"} + ] +} +``` + +The key name (`"events"` in this example) is configurable through the `batch.key_name` parameter. + +### Output format + +The expected output format depends on the `response_events_match` setting: + +#### When `response_events_match: false` (default) + +Lambda can return one or more new events. The returned events don't need to match the input count. When `response_events_match: false`, the `aws_lambda` processor drops all input events and outputs only the events returned by the Lambda function, replacing the input data rather than combining it: + +```python +def lambda_handler(event, context): + # Process all input events and return new events + return [ + {"result": "processed_data_1"}, + {"result": "processed_data_2"} + ] +``` + +#### When `response_events_match: true` + +The following function sets a `status` key to the static value `processed` in each event: + +```python +def lambda_handler(event, context): + input_events = event.get('events', []) + output = [] + + # Process each event and maintain order + for input_event in input_events: + processed_event = input_event.copy() + processed_event["status"] = "processed" + # Transform data as needed + for key, value in input_event.items(): + if isinstance(value, str): + processed_event[key] = value.upper() + output.append(processed_event) + + # Must return same count as input + return output +``` + +<!-- vale off --> +### Example Lambda function +<!-- vale on --> + +The following Lambda function transforms all string fields to uppercase: + +```python +def lambda_handler(event, context): + # Get events from the configured key_name (default: "events") + input_events = event.get('events', []) + output_events = [] + + for input_event in input_events: + # Add transformation marker + input_event["_transformed_"] = True + + # Transform string fields to uppercase + for key, value in input_event.items(): + if isinstance(value, str): + input_event[key] = value.upper() + + output_events.append(input_event) + + return output_events +``` + +## Limitations + +Note the following limitations: + +- Payload limitation: 6 MB payload limit +- Response codec: JSON-only codec support + +## Integration testing + +Integration tests for this plugin are executed separately from the main Data Prepper build process. Use the following Gradle command to run these tests: + +```bash +./gradlew :data-prepper-plugins:aws-lambda:integrationTest -Dtests.processor.lambda.region="us-east-1" -Dtests.processor.lambda.functionName="lambda_test_function" -Dtests.processor.lambda.sts_role_arn="arn:aws:iam::123456789012:role/dataprepper-role +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/convert-entry-type.md b/i18n/zh/data-prepper/pipelines/configuration/processors/convert-entry-type.md new file mode 100644 index 00000000..325cf60b --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/convert-entry-type.md @@ -0,0 +1,64 @@ +--- +title: Convert type +--- + +# Convert type processor + +The `convert_type` processor converts a value type associated with the specified key in an event to the specified type. It is a casting processor that changes the types of some fields in events. Some data must be converted to a different type, such as an integer to a double or a string to an integer, so that it will pass the events through condition-based processors or perform conditional routing. + +::: warning IMPORTANT +Starting with OpenSearch Data Prepper version 2.10.0, the `convert_entry_type` processor has been renamed to `convert_type`. Configurations using `convert_entry_type` generate a deprecation warning and should be updated. +::: + +## Configuration + +You can configure the `convert_type` processor with the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: convert_type +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/7d15115c281687aab50e5c471fd210cb1ef90fc5/data-prepper-plugins/mutate-event-processors/src/main/java/org/opensearch/dataprepper/plugins/processor/mutateevent/ConvertEntryTypeProcessorConfig.java +--> + +| Option | Required | Description | +| :--- | :--- | :--- | +| `key`| Conditionally | The key of the value to convert to a different type. Required unless `keys` or `coerce_strings` is specified. Cannot be used with `keys`. | +| `keys`| Conditionally | The keys of the values to convert to a different type. Required unless `key` or `coerce_strings` is specified. Cannot be used with `key`. | +| `type` | No | Target type for the key-value pair. Possible values are `integer`, `long`, `double`, `big_decimal`, `string`, and `boolean`. Default value is `integer`. | +| `null_conversion_values` | No | A list of strings that represent a `null` value. If the value of a field specified in `key` or `keys` equals one of these strings, then the field is removed from the event. | +| `iterate_on` | No | The key of a list of objects in the event. When specified, the processor converts the `key` or `keys` fields in each object in the list. | +| `coerce_strings` | No | When specified, the processor converts the string values of all fields in the event, including fields in nested objects and lists, to the type that the string represents. The strings `true` and `false` (case insensitive) are converted to Booleans. Strings that contain a colon (`:`) and match one of the `coerce_strings.time_formats` patterns are converted to epoch milliseconds. Numeric strings that contain a decimal point or an exponent are converted to doubles, and other numeric strings are converted to integers or, if they are out of the integer range, to longs. Strings that cannot be converted are not changed. Specify `coerce_strings` as an empty object (`{}`) to use the default time formats. | +| `coerce_strings.time_formats` | No | A list of [Java DateTimeFormatter](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) patterns used to convert time strings to epoch milliseconds. Time strings that do not include a time zone offset are interpreted in the system time zone, and patterns that do not include a year use the current year. Default is `["MMM d HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ss.SSSSSSX", "dd/MMM/yyyy:HH:mm:ss Z"]`. | +| `scale` | No | Modifies the scale of the `big_decimal` when converting to a `big_decimal`. The default value is `0`. | +| `tags_on_failure` | No | A list of tags to be added to the event metadata when the event fails to convert. | +| `convert_when` | No | Specifies a condition using a [Data Prepper expression](/data-prepper/pipelines/expression-syntax) for performing the `convert_type` operation. If specified, the `convert_type` operation runs only when the expression evaluates to `true`. | + +## Usage + +To get started, create the following `pipeline.yaml` file: + +```yaml +type-conv-pipeline: + source: + ... + .... + processor: + - convert_type: + key: "response_status" + type: "integer" +``` + +Next, create a log file named `logs_json.log` and replace the `path` in the file source of your `pipeline.yaml` file with that file path. For more information, see [Running Data Prepper](/data-prepper/getting-started/running). + +For example, before you run the `convert_type` processor, if the `logs_json.log` file contains the following event record: + +```json +{"message": "value", "response_status":"200"} +``` + +The `convert_type` processor converts the output received to the following output, where the type of `response_status` value changes from a string to an integer: + +```json +{"message":"value","response_status":200} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/decompress.md b/i18n/zh/data-prepper/pipelines/configuration/processors/decompress.md new file mode 100644 index 00000000..73dd9377 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/decompress.md @@ -0,0 +1,157 @@ +--- +title: Decompress +--- + +# Decompress processor + +The `decompress` processor decompresses any Base64-encoded compressed fields inside of an event. + +## Configuration + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`keys` | Yes | List<String> | The fields in the event that will be decompressed. +`type` | Yes | Enum | The type of decompression to use for the `keys` in the event. Only `gzip` is supported. +`decompress_when` | No | String| A [Data Prepper conditional expression](/data-prepper/pipelines/expression-syntax) that determines when the `decompress` processor will run on certain events. +`tags_on_failure` | No | List<String> | A list of strings with which to tag events when the processor fails to decompress the `keys` inside an event. Defaults to `_decompression_failure`. + +## Usage + +This example demonstrates a complete pipeline that receives compressed log data, decompresses it, and stores it in OpenSearch: + +```yaml +decompress-logs-pipeline: + source: + http: + path: /events + ssl: false + + processor: + - decompress: + keys: ["compressed_log", "compressed_metadata"] + type: gzip + tags_on_failure: ["decompression_failed", "gzip_error"] + + # Only parse if decompression succeeded + - parse_json: + source: compressed_log + destination: parsed_log + parse_when: not hasTags("decompression_failed") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: decompressed-logs-%{yyyy.MM.dd} + tags_target_key: "tags" +``` + +You can test the pipeline using the two following commands: + +```bash + +GOOD_COMPRESSED_LOG=$(echo '{"message":"Application OK","level":"INFO","service":"api"}' | gzip | base64 | tr -d '\n') +GOOD_COMPRESSED_METADATA=$(echo '{"source_ip":"192.168.1.100","ok":true}' | gzip | base64 | tr -d '\n') + +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d "[ + { + \"compressed_log\": \"${GOOD_COMPRESSED_LOG}\", + \"compressed_metadata\": \"${GOOD_COMPRESSED_METADATA}\", + \"host\": \"web-server-01\", + \"timestamp\": \"2023-10-13T14:30:45Z\" + } + ]" + +BAD_COMPRESSED_LOG=$(echo -n 'this is not gzipped' | base64 | tr -d '\n') +GOOD_COMPRESSED_METADATA=$(echo '{"source_ip":"192.168.1.100","ok":true}' | gzip | base64 | tr -d '\n') + +curl -sS -X POST "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d "[ + { + \"compressed_log\": \"${BAD_COMPRESSED_LOG}\", + \"compressed_metadata\": \"${GOOD_COMPRESSED_METADATA}\", + \"host\": \"web-server-02\", + \"timestamp\": \"2023-10-13T14:31:45Z\" + } + ]" +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "decompressed-logs-2025.11.04", + "_id": "dOv1TpoB5Jwkiy-iuKKs", + "_score": 1, + "_source": { + "compressed_log": """{"message":"Application OK","level":"INFO","service":"api"} +""", + "compressed_metadata": """{"source_ip":"192.168.1.100","ok":true} +""", + "host": "web-server-01", + "timestamp": "2023-10-13T14:30:45Z", + "parsed_log": { + "level": "INFO", + "service": "api", + "message": "Application OK" + }, + "tags": [] + } + }, + { + "_index": "decompressed-logs-2025.11.04", + "_id": "dev1TpoB5Jwkiy-iuKKs", + "_score": 1, + "_source": { + "compressed_log": "dGhpcyBpcyBub3QgZ3ppcHBlZA==", + "compressed_metadata": """{"source_ip":"192.168.1.100","ok":true} +""", + "host": "web-server-02", + "timestamp": "2023-10-13T14:31:45Z", + "tags": [ + "decompression_failed", + "gzip_error" + ] + } + } + ] + } +} +``` + +## Metrics + +By default, Data Prepper serves metrics from the `/metrics/prometheus` endpoint on port `4900`. You can access all the metrics by running the following command: + +```bash +curl http://localhost:4900/metrics/prometheus +``` + +The following table describes common [abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | The ingress of records to a pipeline component. | +| `recordsOut` | Counter | The egress of records from a pipeline component. | +| `timeElapsed` | Timer | The time elapsed during execution of a pipeline component. | + +### Counter + +The `decompress` processor accounts for the following metrics: + +* `processingErrors`: The number of processing errors that have occurred in the `decompress` processor. diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/delay.md b/i18n/zh/data-prepper/pipelines/configuration/processors/delay.md new file mode 100644 index 00000000..3b311842 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/delay.md @@ -0,0 +1,23 @@ +--- +title: Delay +--- + +# Delay processor + +This processor will add a delay into the processor chain. Typically, you should use this only for testing, experimenting, and debugging. + +## Configuration + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`for` | No | Duration | The duration of time to delay. Defaults to `1s`. + +## Usage + +The following example shows using the `delay` processor to delay for 2 seconds. + +```yaml +processor: + - delay: + for: 2s +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/flatten.md b/i18n/zh/data-prepper/pipelines/configuration/processors/flatten.md new file mode 100644 index 00000000..77686db5 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/flatten.md @@ -0,0 +1,300 @@ +--- +title: Flatten +--- + +# Flatten processor + +The `flatten` processor transforms nested objects inside of events into flattened structures. + +## Configuration + +The following table describes configuration options for the `flatten` processor. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The source key on which to perform the operation. If set to an empty string (`""`), then the processor uses the root of the event as the source. +`target` | Yes | String | The target key to put into the flattened fields. If set to an empty string (`""`), then the processor uses the root of the event as the target. +`exclude_keys` | No | List | The keys from the source field that should be excluded from processing. Default is an empty list (`[]`). +`remove_source_keys` | No | Boolean | When `true`, the processor removes all processed fields from the source. Default is `false`. +`remove_list_elements` | No | Boolean | When `true`, the processor removes list indexes from the flattened keys and collects the values of matching keys into lists in the target field. For example, `list[0].name` and `list[1].name` become a single `list[].name` key containing a list of both values. Default is `false`. +`remove_brackets` | No | Boolean | When `true`, the processor also removes the empty brackets (`[]`) that remain in the flattened keys after list indexes are removed. For example, `list[].name` becomes `list.name`. This setting takes effect only when `remove_list_elements` is `true`. Default is `false`. +`flatten_when` | No | String | A [conditional expression](/data-prepper/pipelines/expression-syntax), such as `/some-key == "test"'`, that determines whether the `flatten` processor will be run on the event. Default is `null`, which means that all events will be processed unless otherwise stated. +`flatten_separator` | No | String | The character used to join nested key names into flattened keys. Must be a single character. Default is `.`. +`tags_on_failure` | No | List | A list of tags to add to the event metadata when the event fails to process. + +## Usage + +The following examples show how the `flatten` processor can be used in OpenSearch Data Prepper pipelines. + +### Minimum configuration + +The following example shows only the parameters that are required for using the `flatten` processor, `source` and `target`: + +```yaml +... + processor: + - flatten: + source: "key2" + target: "flattened-key2" +... +``` + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + } +} +``` + +The `flatten` processor creates a flattened structure under the `flattened-key2` object, as shown in the following output: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "flattened-key2": { + "key3.key4": "val2" + } +} +``` + +### Remove processed fields + +Use the `remove_source_keys` option when flattening all of an event's nested objects. This removes all the event's processed fields, as shown in the following example: + +```yaml +... + processor: + - flatten: + source: "" # empty string represents root of event + target: "" # empty string represents root of event + remove_source_keys: true +... +``` + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1": [ + { + "list2": [ + { + "name": "name1", + "value": "value1" + }, + { + "name": "name2", + "value": "value2" + } + ] + } + ] +} +``` + +The `flatten` processor creates a flattened structure in which all processed fields are absent, as shown in the following output: + +```json +{ + "key1": "val1", + "key2.key3.key4": "val2", + "list1[0].list2[0].name": "name1", + "list1[0].list2[0].value": "value1", + "list1[0].list2[1].name": "name2", + "list1[0].list2[1].value": "value2", +} +``` + +### Exclude specific keys from flattening + +Use the `exclude_keys` option to prevent specific keys from being flattened in the output, as shown in the following example, where the `key2` value is excluded: + +```yaml +... + processor: + - flatten: + source: "" # empty string represents root of event + target: "" # empty string represents root of event + remove_source_keys: true + exclude_keys: ["key2"] +... +``` + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1": [ + { + "list2": [ + { + "name": "name1", + "value": "value1" + }, + { + "name": "name2", + "value": "value2" + } + ] + } + ] +} +``` + +All other nested objects in the input event, excluding the `key2` key, will be flattened, as shown in the following example: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1[0].list2[0].name": "name1", + "list1[0].list2[0].value": "value1", + "list1[0].list2[1].name": "name2", + "list1[0].list2[1].value": "value2", +} +``` + +### Remove list indexes + +Use the `remove_list_elements` option to convert the fields from the source map into lists and put the lists into the target field, as shown in the following example: + +```yaml +... + processor: + - flatten: + source: "" # empty string represents root of event + target: "" # empty string represents root of event + remove_source_keys: true + remove_list_elements: true +... +``` + +For example, when the input event contains the following nested objects: + +```json +{ + "key1": "val1", + "key2": { + "key3": { + "key4": "val2" + } + }, + "list1": [ + { + "list2": [ + { + "name": "name1", + "value": "value1" + }, + { + "name": "name2", + "value": "value2" + } + ] + } + ] +} +``` + +The processor removes all indexes from the output and places them into the source map as a flattened, structured list, as shown in the following example: + +```json +{ + "key1": "val1", + "key2.key3.key4": "val2", + "list1[].list2[].name": ["name1","name2"], + "list1[].list2[].value": ["value1","value2"] +} +``` + +If you also set `remove_brackets` to `true`, the processor removes the empty brackets from the keys, as shown in the following output: + +```json +{ + "key1": "val1", + "key2.key3.key4": "val2", + "list1.list2.name": ["name1","name2"], + "list1.list2.value": ["value1","value2"] +} +``` + +### Custom separator + +Use the `flatten_separator` option to specify a custom character for joining nested key names. The default separator is `.`, but you can use any single character, such as `_`, as shown in the following example: + +```yaml +... + processor: + - flatten: + source: "log" + target: "" + flatten_separator: "_" + remove_source_keys: true +... +``` + +Consider an input event that contains the following nested objects: + +```json +{ + "timestamp": "2026-07-29T12:00:00Z", + "service": "user-service", + "log": { + "request": { + "method": "POST", + "url": "/api/v1/users", + "headers": { + "content_type": "application/json" + } + }, + "response": { + "status": 200, + "body": { + "user_id": "usr_12345" + } + } + } +} +``` + +The `flatten` processor flattens the `log` field using `_` as the separator and places the results at the root of the event. Because `remove_source_keys` is `true`, the processed nested fields are removed, leaving an empty `log` object, as shown in the following output: + +```json +{ + "timestamp": "2026-07-29T12:00:00Z", + "service": "user-service", + "log": {}, + "request_method": "POST", + "request_url": "/api/v1/users", + "request_headers_content_type": "application/json", + "response_status": 200, + "response_body_user_id": "usr_12345" +} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/geoip.md b/i18n/zh/data-prepper/pipelines/configuration/processors/geoip.md new file mode 100644 index 00000000..492df950 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/geoip.md @@ -0,0 +1,64 @@ +--- +title: Geo IP +--- + +# Geo IP processor + +The `geoip` processor enriches events with geographic information extracted from IP addresses contained in the events. +By default, OpenSearch Data Prepper uses the [MaxMind GeoLite2](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) geolocation database. +Data Prepper administrators can configure the databases using the [`geoip_service`](/data-prepper/managing-data-prepper/extensions/geoip-service) extension configuration. + +## Usage + +You can configure the `geoip` processor to work on entries. + +The minimal configuration requires at least one entry, and each entry at least one source field. + +The following configuration extracts all available geolocation data from the IP address provided in the field named `clientip`. +It will write the geolocation data to a new field named `geo`, the default source when none is configured: + +```yaml +my-pipeline: + processor: + - geoip: + entries: + - source: clientip +``` + +The following example excludes Autonomous System Number (ASN) fields and puts the geolocation data into a field named `clientlocation`: + +```yaml +my-pipeline: + processor: + - geoip: + entries: + - source: clientip + target: clientlocation + include_fields: [asn, asn_organization, network] +``` + +## Configuration + +You can use the following options to configure the `geoip` processor. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`entries` | Yes | [entry](#entry) list | The list of entries marked for enrichment. +`geoip_when` | No | String | Specifies under what condition the `geoip` processor should perform matching. Default is no condition. +`lookup_private_addresses` | No | Boolean | When `true`, the processor also looks up private and loopback IP addresses, such as `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, and `127.0.0.0/8`, in the configured databases. Use this setting with a custom database that contains locations for your internal IP ranges. When `false`, the processor treats these addresses as not valid and adds the `tags_on_no_valid_ip` tags. Default is `false`. +`tags_on_no_valid_ip` | No | List | The tags to add to the event metadata if the source field is not a valid IP address. Unless `lookup_private_addresses` is `true`, this includes private and loopback IP addresses. +`tags_on_ip_not_found` | No | List | The tags to add to the event metadata if the `geoip` processor is unable to find a location for the IP address. +`tags_on_engine_failure` | No | List | The tags to add to the event metadata if the `geoip` processor is unable to enrich an event due to an engine failure. + +<!-- vale off --> +## entry +<!-- vale on --> + +The following parameters allow you to configure a single geolocation entry. Each entry corresponds to a single IP address. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The key of the source field containing the IP address to geolocate. +`target` | No | String | The key of the target field in which to save the geolocation data. Default is `geo`. +`include_fields` | No | String list | The list of geolocation fields to include in the `target` object. By default, this is all the fields provided by the configured databases. +`exclude_fields` | No | String list | The list of geolocation fields to exclude from the `target` object. diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/map-to-list.md b/i18n/zh/data-prepper/pipelines/configuration/processors/map-to-list.md new file mode 100644 index 00000000..5117421a --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/map-to-list.md @@ -0,0 +1,267 @@ +--- +title: Map to list +--- + +# Map to list processor + +The `map_to_list` processor converts a map of key-value pairs to a list of objects. Each object contains the key and value in separate fields. + +## Configuration + +The following table describes the configuration options for the `map_to_list` processor. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`source` | Yes | String | The source map used to perform the mapping operation. When set to an empty string (`""`), it will use the root of the event as the `source`. +`target` | Yes | String | The target for the generated list. +`key_name` | No | String | The name of the field in which to store the original key. Default is `key`. +`value_name` | No | String | The name of the field in which to store the original value. Default is `value`. +`exclude_keys` | No | List | The keys in the source map that will be excluded from processing. Default is an empty list (`[]`). +`remove_processed_fields` | No | Boolean | When `true`, the processor will remove the processed fields from the source map. Default is `false`. +`convert_field_to_list` | No | Boolean | If `true`, the processor will convert the fields from the source map into lists and place them in fields in the target list. Default is `false`. +`map_to_list_when` | No | String | A [conditional expression](/data-prepper/pipelines/expression-syntax), such as `/some-key == "test"'`, that will be evaluated to determine whether the processor will be run on the event. Default is `null`. All events will be processed unless otherwise stated. +`tags_on_failure` | No | List | A list of tags to add to the event metadata when the event fails to process. + +## Usage + +The following examples show how the `map_to_list` processor can be used in your pipeline. + +### Example: Minimum configuration + +The following example shows the `map_to_list` processor with only the required parameters, `source` and `target`, configured: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" +... +``` + +When the input event contains the following data: + +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will contain the following output: + +```json +{ + "my-list": [ + { + "key": "key1", + "value": "value1" + }, + { + "key": "key2", + "value": "value2" + }, + { + "key": "key3", + "value": "value3" + } + ], + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +### Example: Custom key name and value name + +The following example shows how to configure a custom key name and value name: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" + key_name: "name" + value_name: "data" +... +``` + +When the input event contains the following data: + +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will contain the following output: + +```json +{ + "my-list": [ + { + "name": "key1", + "data": "value1" + }, + { + "name": "key2", + "data": "value2" + }, + { + "name": "key3", + "data": "value3" + } + ], + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +### Example: Exclude specific keys from processing and remove any processed fields + +The following example shows how to exclude specific keys and remove any processed fields from the output: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" + exclude_keys: ["key1"] + remove_processed_fields: true +... +``` + +When the input event contains the following data: +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will remove the "key2" and "key3" fields, but the "my-map" object, "key1", will remain, as shown in the following output: + +```json +{ + "my-list": [ + { + "key": "key2", + "value": "value2" + }, + { + "key": "key3", + "value": "value3" + } + ], + "my-map": { + "key1": "value1" + } +} +``` + +### Example: Use convert_field_to_list + +The following example shows how to use the `convert_field_to_list` option in the processor: + +```yaml +... + processor: + - map_to_list: + source: "my-map" + target: "my-list" + convert_field_to_list: true +... +``` + +When the input event contains the following data: + +```json +{ + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +The processed event will convert all fields into lists, as shown in the following output: + +```json +{ + "my-list": [ + ["key1", "value1"], + ["key2", "value2"], + ["key3", "value3"] + ], + "my-map": { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } +} +``` + +### Example: Use the event root as the source + +The following example shows how you can use an event's root as the source by setting the `source` setting to an empty string (`""`): + +```yaml +... + processor: + - map_to_list: + source: "" + target: "my-list" +... +``` + +When the input event contains the following data: + +```json +{ + "key1": "value1", + "key2": "value2", + "key3": "value3" +} +``` + +The processed event will contain the following output: + +```json +{ + "my-list": [ + { + "key": "key1", + "value": "value1" + }, + { + "key": "key2", + "value": "value2" + }, + { + "key": "key3", + "value": "value3" + } + ], + "key1": "value1", + "key2": "value2", + "key3": "value3" +} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/ml-inference.md b/i18n/zh/data-prepper/pipelines/configuration/processors/ml-inference.md new file mode 100644 index 00000000..5f516617 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/ml-inference.md @@ -0,0 +1,104 @@ +--- +title: ML inference +--- + +# ML inference processor + +The `ml_inference` processor allows you to use OpenSearch machine learning (ML) functionality within OpenSearch Data Prepper. By integrating ML models into Data Prepper pipelines, you can apply them during data ingestion into Amazon OpenSearch Service in order to power AI-driven search experiences such as vector search, semantic search, or conversational search. To explore OpenSearch AI-powered search types, see [AI search](/vector-search/ai-search/). + +Using the `ml_inference` processor, you can invoke an OpenSearch-hosted ML model within your Data Prepper pipeline in order to process events. The processor supports both real-time invocations and asynchronous (offline) batch job invocations. + +::: info NOTE +To use the `ml_inference` processor, you must have the ML Commons plugin installed on your cluster. The plugin is included by default in standard OpenSearch distributions. For more information, see [Managing OpenSearch plugins](/install-and-configure/plugins). +::: + +## Configuration fields + +The following table describes the configuration options for the `ml_inference` processor. + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `host` | Yes | String | The name of the OpenSearch host. | +| `action_type` | Yes | String | The type of action to perform. Currently, only `batch_predict` is supported. Default is `batch_predict`. | +| `model_id` | Yes | String | The ID of the ML model to invoke. When `service_name` is `bedrock`, you can also set `model_id` to one of the built-in Amazon Bedrock model IDs: `amazon.titan-embed-text-v2:0`, `amazon.titan-embed-image-v1`, or `amazon.nova-2-multimodal-embeddings-v1:0`. For built-in models, the processor creates the batch inference job directly in Amazon Bedrock without sending a request to the OpenSearch host, and `aws.job_sts_role_arn` is required. | +| `output_path` | Yes | String | The [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) location to which the offline batch job results will be written. | +| `aws.region` | Yes | String | The AWS Region to which OpenSearch Service is deployed. | +| `aws.sts_role_arn` | No | String | The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role to assume. | +| `aws.sts_external_id` | No | String | The external ID to use when assuming the IAM role. Must be 2--1224 characters. | +| `aws.sts_header_overrides` | No | Map | A map of header overrides to use when assuming the IAM role. Maximum of 5 headers. | +| `aws.job_sts_role_arn` | Conditionally | String | The ARN of the IAM role that Amazon Bedrock assumes to run the batch inference job. Required when `model_id` is a built-in Amazon Bedrock model ID. Must be 20--2048 characters. | +| `service_name` | No | String | The name of the AI service hosting the model used for inference. Default is `sagemaker` (Amazon SageMaker). | +| `input_key` | No | String | The name of the event field to use as the S3 object key name when writing batch job results. This allows dynamic naming of output files based on event data. | +| `ml_when` | No | String | A conditional expression that determines when to invoke the `ml_inference` processor. | +| `tags_on_failure` | No | List | A list of tags to add to events if the `ml_inference` processor fails or encounters an error. | +| `max_batch_size` | No | Integer | Applies when `service_name` is `sagemaker`. The maximum number of events to include in one batch job. The processor creates a batch job when the number of collected events reaches this value or when no new events arrive for 1 minute. Default is `100`. | +| `retry_time_window` | No | Duration | The amount of time for which the processor retains events for retry after a batch job request is throttled. Events that cannot be processed within this time window are treated as failed. Supports ISO 8601 notation strings (for example, `PT20.345S` or `PT15M`) and simple notation strings for seconds (`60s`) and milliseconds (`1500ms`). Default is `PT10M`. | +| `retry_interval` | No | Duration | Applies when `service_name` is `bedrock`. The amount of time to wait between retries of throttled batch job requests. Supports ISO 8601 notation strings (for example, `PT1M`) and simple notation strings for seconds (`60s`) and milliseconds (`1500ms`). Valid values are 3 seconds to 5 minutes. Default is `60s`. | +| `dlq` | No | Object | The [dead-letter queue (DLQ)](/data-prepper/pipelines/dlq) configuration for events for which a batch job cannot be created. If the DLQ configuration does not specify `region` or `sts_role_arn`, the values from the `aws` configuration are used. | + +#### Example configuration + +The following example shows an example `map_to_list` processor configuration: + +```yaml + processor: + - ml_inference: + host: "https://search-ml-inference-test.us-west-2.es.amazonaws.com" + action_type: "batch_predict" + service_name: "sagemaker" + model_id: "9t4AbpYBQB1BoSOe8g8N" + output_path: "s3://test-bucket/output" + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-inference-role" + ml_when: /bucket == "offlinebatch" + +``` + +## Usage + +The processor supports `batch_predict` operations, which invoke the [Batch Predict API](/ml-commons-plugin/api/model-apis/batch-predict) for offline batch processing. + +## Behavior + +For `batch_predict` operations, the `ml_inference` processor works best with the [S3 source](/data-prepper/pipelines/configuration/sources/s3). To configure S3 to process metadata only, configure the S3 scan block as follows: + +```yaml +scan: + buckets: + - bucket: + name: test-offlinebatch + data_selection: metadata_only +``` + +When `metadata_only` is enabled, the processor receives events in the following format: + +```json +{"bucket":"test-offlinebatch","length":6234,"time":1738108982.000000000,"key":"input_folder/batch_input_1.json"} +``` + +To filter specific records for processing, use `ml_when` conditions. + +## Monitoring the offline batch job status + +Once an offline batch job is created by the Data Prepper pipeline, you can track its status using the AI provider's (Amazon SageMaker or Amazon Bedrock) native console. + +Alternatively, you can check the job status by calling the [Search ML Tasks API](/ml-commons-plugin/api/tasks-apis/search-task). For example, to search for all currently running tasks, use the following request: + +```json +GET /_plugins/_ml/tasks/_search +{ + "query": { + "bool": { + "filter": [ + { + "term": { + "state": "RUNNING" + } + } + ] + } + }, + "_source": ["model_id", "state", "task_type", "create_time", "last_update_time"] +} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/otel-apm-service-map.md b/i18n/zh/data-prepper/pipelines/configuration/processors/otel-apm-service-map.md new file mode 100644 index 00000000..4881febc --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/otel-apm-service-map.md @@ -0,0 +1,127 @@ +--- +title: OTel APM Service map +--- + +# OTel APM service map processor + +The `otel_apm_service_map` processor analyzes OpenTelemetry (OTel) trace spans to automatically generate Application Performance Monitoring (APM) service map relationships and metrics. It creates structured events that can be visualized as service topology graphs, showing how services communicate with each other and detailing their performance characteristics. + +The `otel_apm_service_map` processor provides all the functionality of the existing [`service_map` processor](/data-prepper/pipelines/configuration/processors/service-map) while offering enhanced observability capabilities. In addition to generating service maps, it creates time-based service maps that capture how relationships between services evolve over time rather than producing a static representation. + +The processor also automatically generates Rate, Errors, and Duration (RED) metrics for each service, delivering immediate insight into service health and performance without requiring additional configuration. + +## Configuration + +The following table describes the options you can use to configure the `otel_apm_service_map` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: otel_apm_service_map +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/6eb06fe60c21bc4125875af5a3052e332908a12a/data-prepper-plugins/otel-apm-service-map-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/otel_apm_service_map/OTelApmServiceMapProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`window_duration` | No | Duration | The fixed time window during which APM service map relationships are evaluated. Supports ISO-8601 duration format (for example, `PT60S` or `PT1M`) or simple integer values (interpreted as seconds). Default is `60s`. +`db_path` | No | String | The directory in which the processor creates database files that store transient data off heap when processing APM service map data. Default is `data/otel-apm-service-map/`. +`group_by_attributes` | No | List | A list of OTel resource attribute names to copy into `Service.groupByAttributes` when they are present in a span's resource attributes. This setting applies only to primary `Service` objects and not to dependency services. Default is an empty list. +`metric_timestamp_source` | No | String | The source of the timestamp assigned to emitted metrics and service map events. Valid values are `arrival_time` and `span_end_time`. When set to `arrival_time`, the processor uses the time at which it evaluates the window, so all spans in a window share one timestamp. When set to `span_end_time`, the processor uses the end time of each span. Spans that arrive late can then produce data points that have the same timestamp as data points already written, which metrics backends such as Prometheus can reject. If a span has no valid end time, the processor uses the evaluation time. Default is `arrival_time`. +`metric_timestamp_granularity` | No | String | The time unit to which the timestamps of emitted metrics and service map events are truncated. Valid values are `seconds` and `minutes`. Default is `seconds`. +`dependency_nodes` | No | Object | Configures how the processor creates nodes for databases, message brokers, and external endpoints that do not emit their own spans. See [Dependency nodes](#dependency-nodes). + +### Dependency nodes + +A dependency node represents a downstream component that a service calls but that does not emit its own `SERVER` span, such as a database, a message broker, or an external endpoint. The processor creates dependency nodes from the spans of the calling service and generates RED metrics for them. Each dependency node has one of the following types: + +- `database`: Created from a `CLIENT` span that contains database (`db.*`) attributes and has no child `SERVER` span. +- `external`: Created from a `CLIENT` span that contains HTTP, RPC, or peer attributes and has no child `SERVER` span. +- `messaging`: Created from a `PRODUCER` or `CONSUMER` span. The broker node connects producers to consumers. + +The processor does not create an `external` node for a peer if the peer host is unresolved, is an IP address or a loopback address, or matches a pattern in `hostname_denylist_patterns`. For a `database` node, such a host is left out of the node name, which then uses `<db.system>:<db.namespace>` or `<db.system>`. + +::: warning IMPORTANT +The processor creates dependency nodes only from spans in the OpenTelemetry format. If you use the [`otel_trace_source`](/data-prepper/pipelines/configuration/sources/otel-trace-source) source, set its `output_format` to `otel`. With the default `opensearch` format, the processor generates service metrics but no dependency nodes. +::: + +::: info NOTE +If your version of OpenSearch Dashboards does not support dependency nodes, it lists them as services. In this case, set `enabled` to `false`. +::: + +You can configure the following options in the `dependency_nodes` object. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`enabled` | No | Boolean | Whether to create dependency nodes. When set to `false`, the processor does not create nodes for components that do not emit their own spans. Default is `true`. +`max_dependencies_per_service` | No | Integer | The maximum number of distinct dependencies that a single source service can hold. A dependency that a service already holds remains admitted in later windows. When the limit is reached, free slots go to the new dependencies that have the most calls in the window, and calls to the remaining dependencies are grouped into an overflow node named `OtherDatabase`, `OtherExternal`, or `OtherMessaging`, depending on the dependency type. A dependency that is not seen for more than 10 consecutive windows releases its slot. Must be at least `1`. Default is `100`. +`max_remote_operations_per_service` | No | Integer | The maximum number of distinct dependency remote operations that a single source service can hold. Operations are admitted and released in the same way as dependencies. When the limit is reached, calls to the remaining operations are grouped into an operation named `OtherRemoteOperation`. Must be at least `1`. Default is `100`. +`hostname_denylist_patterns` | No | List | A list of regular expressions matched against the host name of a dependency. Matching is case insensitive, and a pattern must match the entire host name. The processor does not create a node for a host that matches any pattern. Setting this option replaces the default list. By default, the list contains patterns that match host names derived from IP addresses, such as Amazon EC2 host names (`ip-10-0-0-5.ec2.internal` or `ec2-1-2-3-4.compute-1.amazonaws.com`) and Kubernetes pod DNS names (`10-0-0-5.ns.pod.cluster.local`). + +The following example sets custom limits and a custom host name denylist: + +```yaml +processor: + - otel_apm_service_map: + dependency_nodes: + enabled: true + max_dependencies_per_service: 50 + max_remote_operations_per_service: 200 + hostname_denylist_patterns: + - '^ip-\d{1,3}-\d{1,3}-\d{1,3}-\d{1,3}(\..*)?$' + - '^egress-proxy$' +``` + +## Usage + +```yaml +entry-pipeline: + source: + otel_trace_source: + path: "/test/path" + sink: + - pipeline: + name: "raw-pipeline" + - pipeline: + name: "service-map-pipeline" +raw-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - otel_trace_raw: + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-raw +service-map-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - otel_apm_service_map: + window_duration: 60s + db_path: "data/otel-apm-service-map/" + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-service-map +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | The ingress of records to a pipeline component. | +| `recordsOut` | Counter | The egress of records from a pipeline component. | +| `timeElapsed` | Timer | The time elapsed during execution of a pipeline component, in milliseconds. | + +The `otel_apm_service_map` processor includes the following custom metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `spansDbSize` | Gauge | The total size of all three span database windows, in bytes. | +| `spansDbCount` | Gauge | The total number of span entries across all three span database windows. | +| `dependencyCallsOverflowed` | Counter | The number of calls grouped into an overflow dependency node because `max_dependencies_per_service` was reached. Reported only when dependency nodes are enabled. | +| `dependencyRemoteOperationCallsOverflowed` | Counter | The number of calls grouped into `OtherRemoteOperation` because `max_remote_operations_per_service` was reached. Reported only when dependency nodes are enabled. | diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/otel-traces.md b/i18n/zh/data-prepper/pipelines/configuration/processors/otel-traces.md new file mode 100644 index 00000000..81ef7d1a --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/otel-traces.md @@ -0,0 +1,172 @@ +--- +title: OTel trace +--- + +# OTel trace processor + +The `otel_traces` processor completes trace-group-related fields in all incoming OpenSearch Data Prepper span records by caching the root span information for each `traceId`. It also enriches traces from generative AI (GenAI) agents and large language model (LLM) applications. For more information, see [GenAI agent trace enrichment](#genai-agent-trace-enrichment). + +::: info NOTE +The processor was previously named `otel_trace_raw`. You can still use the `otel_trace_raw` name, but it is deprecated and is planned for removal in Data Prepper 3.0. +::: + +## Usage + +This processor adds the following fields to span events: + +* `traceGroup`: Root span name +* `endTime`: End time of the entire trace in International Organization for Standardization (ISO) 8601 format +* `durationInNanos`: Duration of the entire trace in nanoseconds +* `statusCode`: Status code for the entire trace + +## Configuration + +The following table describes the options you can use to configure the `otel_traces` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: otel_traces +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/4fcb0f6d4df60ae5f6cd6df3007704d28a72c774/data-prepper-plugins/otel-trace-raw-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/oteltrace/OtelTraceRawProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`trace_flush_interval` | No | Integer | The amount of time, in seconds, after which the processor flushes descendant spans that have no root span. Default is `180`. +`trace_group_cache_ttl` | No | Duration | The amount of time to keep trace group details in the cache. Accepts ISO 8601 notation, such as `PT1M30S`, or a duration and unit, such as `45s`. Default is `15s`. +`trace_group_cache_max_size` | No | Integer | The maximum number of trace groups from root spans to keep in the cache. Default is `1000000`. +`disable_genai_enrichment` | No | Boolean | Turns off GenAI agent trace enrichment: normalizing vendor attributes to `gen_ai.*`, stripping flattened sub-keys that conflict with their parent, marking agent root spans, and copying agent data onto trace roots. Traces that contain no GenAI spans are not changed. Default is `false`. +`genai_coverage_cache_max_size` | No | Integer | The maximum number of GenAI span IDs to keep in the coverage cache across all traces. The cache prevents GenAI spans that arrive after their ancestors from being marked as a trace's AI root. Must be at least `1`. Cannot be set when `disable_genai_enrichment` is `true`. For more information, see [Late spans and the coverage cache](#late-spans-and-the-coverage-cache). Default is `500000`. +`genai_root_propagation` | No | String | Determines which root spans receive the GenAI attributes and token totals copied from their child spans. Valid values are `ai_root`, `all_roots`, and `none`. Cannot be set when `disable_genai_enrichment` is `true`. For more information, see [Root span enrichment](#root-span-enrichment). Default is `ai_root`. + +::: info NOTE +The `disable_genai_enrichment`, `genai_coverage_cache_max_size`, and `genai_root_propagation` options are available in Data Prepper 2.17 and later. +::: + +## GenAI agent trace enrichment + +The `otel_traces` processor enriches traces from GenAI agents and LLM applications so that agent runs can be found, listed, and measured from the spans themselves, for example, in the OpenSearch Dashboards **Agent Traces** page. Enrichment is turned on by default, is available in Data Prepper 2.14 and later, and does not change traces that contain no GenAI data. + +::: warning IMPORTANT +Enrichment matches attributes by their OpenTelemetry (OTel) key names, for example, `gen_ai.operation.name`, so the source must emit spans in the OTel format. The [`otel_trace_source`](/data-prepper/pipelines/configuration/sources/otel-trace-source) source defaults to the `opensearch` format, so set its `output_format` to `otel`. The [`otlp`](/data-prepper/pipelines/configuration/sources/otlp-source) source uses the `otel` format by default. The `opensearch` format rewrites attribute keys (for example, `http.method` becomes `span.attributes.http@method`), and the enrichment then finds no GenAI data. +::: + +For each trace in a batch, the processor applies the following steps in order: + +1. [Vendor attribute normalization](#vendor-attribute-normalization) +1. [Flattened sub-key stripping](#flattened-sub-key-stripping) +1. [Root span enrichment](#root-span-enrichment) +1. [Agent root marker](#agent-root-marker) + +To turn off all of these steps, set `disable_genai_enrichment` to `true`. Span attributes are then left as they arrive, and the processor creates no coverage cache. + +### Vendor attribute normalization + +Instrumentation libraries name the same data differently. For example, input tokens are `llm.token_count.prompt` in OpenInference, `llm.usage.prompt_tokens` in OpenLLMetry, and `gen_ai.usage.input_tokens` in the [OTel GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/). The processor copies vendor attributes to their `gen_ai.*` names so that queries, dashboards, and the rest of the enrichment only need the standard names. The normalization follows these rules: + +* The mappings are listed in [`genai-attribute-mappings.yaml`](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/otel-trace-raw-processor/src/main/resources/genai-attribute-mappings.yaml) and grouped by source: `openinference`, `openllmetry` (Traceloop), and `claude_code`. +* The original attributes are kept. The `gen_ai.*` copy is added next to them. +* A `gen_ai.*` attribute that is already on the span is never overwritten. +* When several attributes on one span map to the same `gen_ai.*` name, the one listed first in the mappings file is used. For example, the OpenInference `session.id` attribute is used before Traceloop's `traceloop.association.properties.session_id`; both map to `gen_ai.conversation.id`. +* Operation kinds are mapped to `gen_ai.operation.name` values. For example, the OpenInference `LLM` kind becomes `chat`, `AGENT` and `CHAIN` become `invoke_agent`, and `TOOL` becomes `execute_tool`. +* Some mappings wrap a single value in a JSON array, for example, a finish reason in `gen_ai.response.finish_reasons`. + +Starting in Data Prepper 2.17, Traceloop session IDs (`traceloop.association.properties.session_id`) are mapped to `gen_ai.conversation.id`, which groups traces into sessions. + +### Flattened sub-key stripping + +Some instrumentations emit the same field twice: as a JSON string (for example, `llm.input_messages`) and as flattened sub-keys (for example, `llm.input_messages.0.message.content`). OpenSearch rejects such documents with a mapping conflict. When the parent string is present, the processor removes the indexed sub-keys. When only the sub-keys are present, they are kept so that no data is lost. + +### Root span enrichment + +The processor can copy `gen_ai.system`, `gen_ai.provider.name`, `gen_ai.agent.name`, `gen_ai.request.model`, and the trace's token totals from child spans onto the trace's root span. Attributes that the root span already has are kept. Values are taken from the outermost GenAI spans first (by earliest start time), then from other GenAI spans, and then from the remaining children. + +The `genai_root_propagation` option selects which root spans receive the copies, as described in the following table. + +Value | Root spans that receive the copies +:--- | :--- +`ai_root` (default) | Only a root span that is its trace's AI root: a GenAI span, or a span marked `derived.gen_ai.is_root: true` at the source. +`all_roots` | Every root span, including non-GenAI roots such as the HTTP span that an agent runs behind. This was the default before Data Prepper 2.17. +`none` | No root span. + +With `ai_root`, a non-GenAI root span keeps only its own attributes. Copying agent data onto a non-GenAI root span makes the HTTP span appear to call a model and use tokens, combines parallel agents into one agent name, and counts the trace's tokens again for any consumer that sums usage across spans. The [agent root marker](#agent-root-marker) span carries this data instead. + +Marking does not depend on this option: with `none`, an agent span that the processor marks still receives its descendants' token totals. + +::: warning IMPORTANT +In Data Prepper 2.17, the default changed from copying onto every root span to `ai_root`. If your queries or dashboards read agent data, such as `gen_ai.agent.name` or token totals, from non-GenAI root spans, set `genai_root_propagation` to `all_roots` to keep the previous behavior, or read the data from the marked agent span. +::: + +### Agent root marker + +Agents often run behind a service: the trace's root span is an HTTP or RPC span, such as `POST /plan`, and the agent span is nested under it. Consumers that list traces by their root span then miss the agent or show the HTTP span instead. Starting in Data Prepper 2.17, the processor marks the span that represents each agent run with `derived.gen_ai.is_root: true`. The marker follows these rules: + +* Each outermost GenAI span of a trace is marked. This is a span that has `gen_ai.operation.name` and no GenAI ancestor: either the root span itself, when it is a GenAI span, or the agent span nested under a non-GenAI root. +* When several top-level agents run under one root span, each is marked as one agent run. +* In a chain of agents that call agents, such as `invoke_agent` > HTTP client > HTTP server > `invoke_agent`, only the calling agent is marked because the called agent has a GenAI ancestor. +* A span that the processor marks and that reports no token usage of its own receives the usage of its descendants. Spans marked at the source do not receive these totals. Descendant usage is counted as described in [Token usage](#token-usage). +* An SDK or the user can set the marker on a span at the source. If any span in a trace is marked `true` at the source, the processor marks no other span in that trace. A span set to `false` is never marked, so setting `false` on a trace's outermost GenAI spans excludes the trace from marking. +* Spans that are flushed after `trace_flush_interval` without their root span are still marked because the marker only needs the span's descendants. + +To list a trace's agent runs, query its marked spans. For data indexed before the marker existed, query root spans that are GenAI spans instead. + +#### Late spans and the coverage cache + +The spans of one trace can arrive in several batches. A span that arrives after its agent span was processed is enriched without its ancestors, so it would appear to be outermost and would be marked as a second agent run. To prevent this, the processor records, per trace, which span IDs are already covered by a GenAI span or a marker, and checks this record when a span's parent is not in the batch. The coverage cache works as follows: + +* Entries are kept for twice the `trace_flush_interval` plus the `trace_group_cache_ttl` (375 seconds by default), so they outlive the flush of spans that arrive without their root span. +* The cache stores at most `genai_coverage_cache_max_size` span IDs across all traces. Only traces that contain GenAI spans are stored. The `genAiCoverageSpanIdCount` metric reports how full the cache is, in span IDs. +* The cache supports about `genai_coverage_cache_max_size` / (2 × `trace_flush_interval` + `trace_group_cache_ttl`) GenAI spans per second, which is about 1,300 spans per second by default. At higher rates, traces are evicted early and a late span can be marked again, so increase `genai_coverage_cache_max_size` for higher GenAI span rates. +* The covered-span lookup, the marking, and the update run atomically for each trace, so pipeline workers that process spans of the same trace at the same time do not both mark a span. + +The coverage cache has the following limitations: + +* A span that arrives after its trace's entry has expired or was evicted can be marked. +* If a trace's child spans are flushed before a GenAI root span arrives, both the root span and the outermost child span can be marked. Consumers should prefer the marked span that has no parent. +* If a called service's spans are flushed after `trace_flush_interval` without the caller's spans, the called agent is also marked and is listed as a separate agent run. + +### Token usage + +When the processor sums `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`, either onto a root span or onto a marked agent span, it counts only spans that have no ancestor that also reports usage. Agent spans such as `invoke_agent` often report the total of their own LLM calls, so adding every span that reports usage would count those calls twice. Token counting follows these rules: + +* An ancestor's reported usage is assumed to include its subtree. A sub-agent that runs its own LLM calls under a parent that reports only its own usage is not added. +* A span that reports either token count is treated as reporting usage and keeps its own values. +* Token counts sent as numeric strings are read as numbers. Other values are ignored. + +### Example + +The following pipeline receives OpenTelemetry Protocol (OTLP) traces in the OTel format and writes enriched spans to OpenSearch. The GenAI options are shown with their default values: + +```yaml +otel-traces-pipeline: + source: + otel_trace_source: + ssl: false + output_format: otel + processor: + - otel_traces: + disable_genai_enrichment: false + genai_root_propagation: ai_root + genai_coverage_cache_max_size: 500000 + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index_type: trace-analytics-plain-raw +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `otel_traces` processor includes the following custom metrics: + +* `traceGroupCacheCount`: The number of trace groups in the trace group cache. +* `spanSetCount`: The number of span sets in the span set collection. +* `genAiCoverageCount`: The number of traces in the GenAI coverage cache. +* `genAiCoverageSpanIdCount`: The number of span IDs in the GenAI coverage cache, in the same unit as `genai_coverage_cache_max_size`. Available in Data Prepper 2.17 and later. diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/parse-ion.md b/i18n/zh/data-prepper/pipelines/configuration/processors/parse-ion.md new file mode 100644 index 00000000..fe53514c --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/parse-ion.md @@ -0,0 +1,78 @@ +--- +title: Parse Ion +--- + +# Parse Ion processor + +The `parse_ion` processor parses [Amazon Ion](https://amazon-ion.github.io/ion-docs/) data. + +## Configuration + +You can configure the `parse_ion` processor with the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: parse_ion +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/253e59245fd9c39c959c1c8caaeff1b226a5a0ab/data-prepper-plugins/parse-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/parse/ion/ParseIonProcessorConfig.java +--> + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `source` | No | String | The field in the `event` that is parsed. Default value is `message`. | +| `destination` | No | String | The destination field of the parsed JSON. Defaults to the root of the `event`. Cannot be `""`, `/`, or any white-space-only `string` because these are not valid `event` fields. | +| `pointer` | No | String | A JSON pointer to the field to be parsed. There is no `pointer` by default, meaning that the entire `source` is parsed. The `pointer` can access JSON array indexes as well. If the JSON pointer is invalid, then the entire `source` data is parsed into the outgoing `event`. If the key that is pointed to already exists in the `event` and the `destination` is the root, then the pointer uses the entire path of the key. | +| `parse_when` | No | String | Specifies under which conditions the processor should perform parsing. Default is no condition. Accepts an OpenSearch Data Prepper expression string following the [expression syntax](/data-prepper/pipelines/expression-syntax). | +| `overwrite_if_destination_exists` | No | Boolean | Overwrites the destination if set to `true`. Set to `false` to prevent changing a destination value that exists. Defaults is `true`. | +| `delete_source` | No | Boolean | If set to `true`, then the source field is deleted. Defaults is `false`. | +| `tags_on_failure` | No | List | A list of strings specifying the tags to be set in the event that the processor fails or an unknown exception occurs during parsing. | +| `handle_failed_events` | No | String | Determines how to handle events containing Ion processing errors. Valid values are `skip` (log the error and send the event downstream to the next processor) and `skip_silently` (send the event downstream to the next processor without logging the error). Default is `skip`. | +| `depth` | No | Integer | The nesting level at which the processor stops parsing nested structs. Structs nested deeper than this level are stored as JSON strings. For example, if `depth` is `1`, only the top-level fields are parsed, and any struct value of a top-level field is stored as a JSON string. Structs inside lists are always parsed. Valid values are 0--10. Default is `0`, which parses all nesting levels. | + +## Usage + +The following examples show how to use the `parse_ion` processor in your pipeline. + +### Example: Minimum configuration + +The following example shows the minimum configuration for the `parse_ion` processor: + +```yaml +parse-json-pipeline: + source: + stdin: + processor: + - parse_json: + source: "my_ion" + sink: + - stdout: +``` + +When the input event contains the following data: + +``` +{"my_ion": "{ion_value1: \"hello\", ion_value2: \"world\"}"} +``` + +The processor parses the event into the following output: + +``` +{"ion_value1": "hello", "ion_value2" : "world"} +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `parse_ion` processor includes the following custom metrics. + +### Counter + +* `parseErrors`: The number of parse errors resulting from invalid Ion format in events. This indicates that the Ion format could not be parsed. +* `processingFailures`: The number of processing failures that have occurred in the `parse_ion` processor. This indicates unexpected errors not related to invalid Ion format. diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/parse-xml.md b/i18n/zh/data-prepper/pipelines/configuration/processors/parse-xml.md new file mode 100644 index 00000000..fa9cbeca --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/parse-xml.md @@ -0,0 +1,77 @@ +--- +title: Parse XML +--- + +# Parse XML processor + +The `parse_xml` processor parses XML data for an event. + +## Configuration + +You can configure the `parse_xml` processor with the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: parse_xml +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/253e59245fd9c39c959c1c8caaeff1b226a5a0ab/data-prepper-plugins/parse-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/parse/xml/ParseXmlProcessorConfig.java +--> + +| Option | Required | Type | Description | +| :--- | :--- | :--- | :--- | +| `source` | No | String | Specifies which `event` field to parse. | +| `destination` | No | String | The destination field of the parsed XML. Defaults to the root of the `event`. Cannot be `""`, `/`, or any white-space-only string because these are not valid `event` fields. | +| `pointer` | No | String | A JSON pointer to the field to be parsed. The value is null by default, meaning that the entire `source` is parsed. The `pointer` can access JSON array indexes as well. If the JSON pointer is invalid, then the entire `source` data is parsed into the outgoing `event` object. If the key that is pointed to already exists in the `event` object and the `destination` is the root, then the pointer uses the entire path of the key. | +| `parse_when` | No | String | Specifies under what conditions the processor should perform parsing. Default is no condition. Accepts an OpenSearch Data Prepper expression string following the [expression syntax](/data-prepper/pipelines/expression-syntax). | +| `overwrite_if_destination_exists` | No | Boolean | Overwrites the destination if set to `true`. Set to `false` to prevent changing a destination value that exists. Defaults to `true`. | +| `delete_source` | No | Boolean | If set to `true` then this will delete the source field. Defaults to `false`. | +| `tags_on_failure` | No | String | A list of strings specifying the tags to be set in the event that the processor fails or an unknown exception occurs during parsing. | +| `handle_failed_events` | No | String | Determines how to handle events containing XML processing errors. Valid values are `skip` (log the error and send the event downstream to the next processor) and `skip_silently` (send the event downstream to the next processor without logging the error). Default is `skip`. | + +## Usage + +The following examples show how to use the `parse_xml` processor in your pipeline. + +### Example: Minimum configuration + +The following example shows the minimum configuration for the `parse_xml` processor: + +```yaml +parse-xml-pipeline: + source: + stdin: + processor: + - parse_xml: + source: "my_xml" + sink: + - stdout: +``` + +When the input event contains the following data: + +``` +{ "my_xml": "<Person><name>John Doe</name><age>30</age></Person>" } +``` + +The processor parses the event into the following output: + +``` +{ "name": "John Doe", "age": "30" } +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | Metric representing the ingress of records to a pipeline component. | +| `recordsOut` | Counter | Metric representing the egress of records from a pipeline component. | +| `timeElapsed` | Timer | Metric representing the time elapsed during execution of a pipeline component. | + +The `parse_xml` processor includes the following custom metrics. + +### Counter + +* `parseErrors`: The number of parse errors resulting from invalid XML in events. This indicates that the XML format could not be parsed. +* `processingFailures`: The number of processing failures that have occurred in the `parse_xml` processor. This indicates unexpected errors not related to invalid XML format. diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/select-entries.md b/i18n/zh/data-prepper/pipelines/configuration/processors/select-entries.md new file mode 100644 index 00000000..af620a4f --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/select-entries.md @@ -0,0 +1,126 @@ +--- +title: Select entries +--- + +# Select entries processor + +The `select_entries` processor selects entries from an OpenSearch Data Prepper event. +Only the selected entries remain in the processed event and while all other entries are removed. However, the processor does not remove any events from the Data Prepper pipeline. + +## Configuration + +You can configure the `select_entries` processor using the following options. + +| Option | Required | Description | +| :--- |:---------| :--- | +| `include_keys` | No | A list of keys to be selected from an event. | +| `include_keys_regex` | No | A regular expression (regex) pattern that matches the keys to be selected from an event. | +| `select_when` | No | A [conditional expression](/data-prepper/pipelines/expression-syntax), such as `/some-key == "test"`, that is evaluated to determine whether the processor will be executed on the event. If the condition is not met, then the event continues through the pipeline unmodified, with all the original fields present. | + +## Usage + +First, create the following `pipeline.yaml` file: + +```yaml +pipeline: + source: + ... + .... + processor: + - select_entries: + include_keys: [ "key1", "key2" ] + select_when: '/some_key == "test"' + sink: +``` + +For example, when your source contains the following event record: + +```json +{ + "message": "hello", + "key1" : "value1", + "key2" : "value2", + "some_key" : "test" +} +``` + +After processing, only the keys listed in `include_keys` are retained in the event; all other keys are removed: + +```json +{"key1": "value1", "key2": "value2"} +``` + +### Selecting keys using a regex + +The following example shows how to configure the `include_keys_regex` field in the `pipeline.yaml` file: + +```yaml +pipeline: + source: + ... + .... + processor: + - select_entries: + include_keys: [ "key1", "key2" ] + include_keys_regex: ["^ran.*"] + select_when: '/some_key == "test"' + sink: +``` + +For example, when your source contains the following event record: + +```json +{ + "message": "hello", + "key1" : "value1", + "key2" : "value2", + "some_key" : "test", + "random1": "another", + "random2" : "set", + "random3": "of", + "random4": "values" +} +``` + +The processor retains keys explicitly listed in `include_keys` and any keys matching the` include_keys_regex` pattern, removing all other keys from the event: + +```json +{"key1": "value1", "key2": "value2", "random1": "another", "random2" : "set", "random3": "of", "random4": "values"} +``` + +### Accessing nested fields + +Use `/` to access nested fields. + +For example, when your source contains the following events with nested fields: + +``` +{ + "field1": "abc", + "field2": 123, + "field3": { + "name": "Alice", + "surname": "Smith" + }, + "field4": { + "address": "123 Main St" + } +} +``` + +You can use the following syntax to select a subset of fields: + +``` +pipeline: + source: + ... + .... + processor: + - select_entries: + include_keys: + - field1 + - field2 + - field3/name + select_when: '/field3/surname == "Smith"' + sink: +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/service-map.md b/i18n/zh/data-prepper/pipelines/configuration/processors/service-map.md new file mode 100644 index 00000000..9bcf21c2 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/service-map.md @@ -0,0 +1,80 @@ +--- +title: Service map +--- + +# Service map processor + +The `service_map` processor uses OpenTelemetry data to create a distributed service map for visualization in OpenSearch Dashboards. + +The `service_map` processor generates a static service map and doesn't reflect the changes in the topology over time. The new [`otel_apm_service_map` processor](/data-prepper/pipelines/configuration/processors/otel-apm-service-map) provides a time-based service map. + +## Configuration + +The following table describes the options you can use to configure the `service_map` processor. + +<!-- +This table is autogenerated. Do not edit it. +- name: service_map +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/service-map-stateful/src/main/java/org/opensearch/dataprepper/plugins/processor/ServiceMapProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`window_duration` | No | Integer | The fixed time window during which service map relationships are evaluated, in seconds. Default is `180`. +`db_path` | No | String | The directory in which the processor creates database files that store transient data off heap when processing service map data. Default is `data/service-map/`. + +## Usage + +```yaml +entry-pipeline: + source: + otel_trace_source: + path: "/test/path" + sink: + - pipeline: + name: "raw-pipeline" + - pipeline: + name: "service-map-pipeline" +raw-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - otel_trace_raw: + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-raw +service-map-pipeline: + source: + pipeline: + name: "entry-pipeline" + processor: + - service_map: + window_duration: 60 + sink: + - opensearch: + hosts: [<host>] + index_type: trace-analytics-service-map +``` + +## Metrics + +The following table describes common [Abstract processor](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-api/src/main/java/org/opensearch/dataprepper/model/processor/AbstractProcessor.java) metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `recordsIn` | Counter | The ingress of records to a pipeline component. | +| `recordsOut` | Counter | The egress of records from a pipeline component. | +| `timeElapsed` | Timer | The time elapsed during execution of a pipeline component, in milliseconds. | + +The `service_map` processor includes the following custom metrics. + +| Metric name | Type | Description | +| ------------- | ---- | -----------| +| `spansDbSize` | Gauge | The total size of both current and previous span database windows, in bytes. | +| `spansDbCount` | Gauge | The total number of span entries across both current and previous span database windows. | +| `traceGroupDbSize` | Gauge | The total size of both current and previous trace group database windows, in bytes. | +| `traceGroupDbCount` | Gauge | The total number of trace group entries across both current and previous trace group database windows. | +| `relationshipCount` | Gauge | The total number of unique service map relationships discovered and stored in the relationship state. | diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/split-event.md b/i18n/zh/data-prepper/pipelines/configuration/processors/split-event.md new file mode 100644 index 00000000..acaba87a --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/split-event.md @@ -0,0 +1,64 @@ +--- +title: Split event +--- + +# Split event processor + +The `split_event` processor is used to split events based on a delimiter and generates multiple events from a user-specified field. + +## Configuration + +The following table describes the configuration options for the `split_event` processor. + +| Option | Type | Description | +|------------------|---------|-----------------------------------------------------------------------------------------------| +| `field` | String | The event field to be split. | +| `delimiter_regex`| String | The regular expression used as the delimiter for splitting the field. | +| `delimiter` | String | The delimiter used for splitting the field. If not specified, the default delimiter is used. | +| `split_when` | String | A [conditional expression](/data-prepper/pipelines/expression-syntax) that determines whether the processor is applied to the event. If the condition evaluates to `false`, the event remains unchanged. Default is `null` (all events are processed). | + +# Usage + +To use the `split_event` processor, add the following to your `pipelines.yaml` file: + +```yaml +split-event-pipeline: + source: + http: + processor: + - split_event: + field: query + delimiter: ' ' + sink: + - stdout: +``` + +When an event contains the following example input: + +```json +{"query" : "open source", "some_other_field" : "abc" } +``` + +The input will be split into multiple events based on the `query` field, with the delimiter set as white space, as shown in the following example: + +```json +{"query" : "open", "some_other_field" : "abc" } +{"query" : "source", "some_other_field" : "abc" } +``` + +## Conditional splitting with split_when + +You can use `split_when` to conditionally apply the split based on event content. This is useful in multi-tenant pipelines where only certain events should be split. In the following example, the `split_event` processor only splits events in which the `body` field contains a new line character. Events without new lines remain unchanged: + +```yaml +split-event-pipeline: + source: + http: + processor: + - split_event: + field: body + delimiter: "\n" + split_when: "contains(/body, \"\n\")" + sink: + - stdout: +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/truncate.md b/i18n/zh/data-prepper/pipelines/configuration/processors/truncate.md new file mode 100644 index 00000000..1dd9ac02 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/truncate.md @@ -0,0 +1,110 @@ +--- +title: Truncate +--- + +# Truncate processor + +The `truncate` processor truncates a key's value at the beginning, the end, or on both sides of the value string, based on the processor's configuration. If the key's value is a list, then each member in the string list is truncated. Non-string members of the list are not truncated. When the `truncate_when` option is provided, input is truncated only when the condition specified is `true` for the event being processed. + +## Configuration + +You can configure the `truncate` processor using the following options. + +<!-- +This table is autogenerated. Do not edit it. +- name: truncate +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/c4455a7785bc2da4358067c217be7085e0bc8d0f/data-prepper-plugins/truncate-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/truncate/TruncateProcessorConfig.java +--> + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`entries` | Yes | String list | A list of entries to add to an event. +`source_keys` | No | String list | The list of source keys that will be modified by the processor. The default value is an empty list, which indicates that all values will be truncated. +`truncate_when` | No | Conditional expression | A condition that, when met, determines when the truncate operation is performed. +`start_at` | No | Integer | Where in the string value to start truncation. Default is `0`, which specifies to start truncation at the beginning of each key's value. +`length` | No | Integer| The length of the string after truncation. When not specified, the processor will measure the length based on where the string ends. +`recursive` | No | Boolean | If `true` and the value of a source key is an object, the processor truncates the string values of all fields in the object, including fields in nested objects. If `false`, object values are not truncated. Default is `false`. + +Either the `start_at` or `length` options must be present in the configuration in order for the `truncate` processor to run. You can define both values in the configuration in order to further customize where truncation occurs in the string. + +## Usage + +The following examples show how to configure the `truncate` processor in the `pipeline.yaml` file: + +## Example: Minimum configuration + +The following example shows the minimum configuration for the `truncate` processor: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - truncate: + entries: + - source_keys: ["message1", "message2"] + length: 5 + - source_keys: ["info"] + length: 6 + start_at: 4 + - source_keys: ["log"] + start_at: 5 + sink: + - stdout: +``` + +For example, the following event contains several keys with string values: + +```json +{"message1": "hello,world", "message2": "test message", "info", "new information", "log": "test log message"} +``` + +The `truncate` processor produces the following output, where: + +- The `start_at` setting is `0` for the `message1` and `message 2` keys, indicating that truncation will begin at the start of the string, with the string itself truncated to a length of `5`. +- The `start_at` setting is `4` for the `info` key, indicating that truncation will begin at letter `i` of the string, with the string truncated to a length of `6`. +- The `start_at` setting is `5` for the `log` key, with no length specified, indicating that truncation will begin at letter `l` of the string. + +```json +{"message1":"hello", "message2":"test ", "info":"inform", "log": "log message"} +``` + +## Example: Using `truncate_when` + +The following example configuration shows the `truncate` processor with the `truncate_when` option configured: + +```yaml +pipeline: + source: + file: + path: "/full/path/to/logs_json.log" + record_type: "event" + format: "json" + processor: + - truncate: + entries: + - source_keys: ["message"] + length: 5 + start_at: 8 + truncate_when: '/id == 1' + sink: + - stdout: +``` + +The following example contains two events: + +```json +{"message": "hello, world", "id": 1} +{"message": "hello, world,not-truncated", "id": 2} +``` + +When the `truncate` processor runs on the events, only the first event is truncated because the `id` key contains a value of `1`: + +```json +{"message": "world", "id": 1} +{"message": "hello, world,not-truncated", "id": 2} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/processors/write-json.md b/i18n/zh/data-prepper/pipelines/configuration/processors/write-json.md new file mode 100644 index 00000000..6314887c --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/processors/write-json.md @@ -0,0 +1,126 @@ +--- +title: Write JSON +--- + +# Write JSON processor + +The `write_json` processor converts an object in an event into a JSON string. You can customize the processor to choose the source and target field names. + +<!-- +This table is autogenerated. Do not edit it. +- name: write_json +- pluginType: processor +- source: https://github.com/opensearch-project/data-prepper/blob/f0bd8d8e4773dc3d7318c19b8623c2213a099a86/data-prepper-plugins/write-json-processor/src/main/java/org/opensearch/dataprepper/plugins/processor/write_json/WriteJsonProcessorConfig.java +--> + +Option | Description | Example +:--- | :--- | :--- +`source` | Mandatory field that specifies the name of the field in the event containing the message or object to be parsed. | If `source` is set to `"message"` and the input is `{"message": {"key1":"value1", "key2":{"key3":"value3"}}}`, then the `write_json` processor outputs the event as `"{\"key1\":\"value1\",\"key2\":{\"key3\":\"value3\"}}"`. +`target` | An optional field that specifies the name of the field in which the resulting JSON string should be stored. If `target` is not specified, then the `source` field is used. | `key1` + +## Example + +The following example uses `write_json` twice, first to copy the `details` object into a new JSON string field named `target` and then to overwrite the original `payload` field when target is omitted: + +```yaml +write-json-demo-pipeline: + source: + http: + path: /logs + ssl: false + + processor: + # 1) Copy the nested "details" object into a JSON string at "details_json" + - write_json: + source: details + target: details_json + + # 2) Overwrite "payload" with its JSON-string representation + - write_json: + # no target -> result stored back into "payload" + source: payload + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: write-json-demo-%{yyyy.MM.dd} +``` + +You can test this pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/logs" \ + -H "Content-Type: application/json" \ + -d '[ + { + "message": "order created", + "details": {"order_id": 123, "items": [{"sku": "A1", "qty": 2}], "expedited": true}, + "payload": {"user": {"id": "u-42", "role": "admin"}, "ip": "10.0.0.5"} + }, + { + "message": "order updated", + "details": {"order_id": 124, "items": [{"sku": "B9", "qty": 1}], "expedited": false}, + "payload": {"user": {"id": "u-77", "role": "viewer"}, "ip": "10.0.0.9"} + } + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "write-json-demo-2025.10.15", + "_id" : "YMQA6ZkB1u9wkbZgz8wu", + "_score" : 1.0, + "_source" : { + "message" : "order created", + "details" : { + "order_id" : 123, + "items" : [ + { + "sku" : "A1", + "qty" : 2 + } + ], + "expedited" : true + }, + "payload" : "{\"user\":{\"id\":\"u-42\",\"role\":\"admin\"},\"ip\":\"10.0.0.5\"}", + "details_json" : "{\"order_id\":123,\"items\":[{\"sku\":\"A1\",\"qty\":2}],\"expedited\":true}" + } + }, + { + "_index" : "write-json-demo-2025.10.15", + "_id" : "YcQA6ZkB1u9wkbZgz8wu", + "_score" : 1.0, + "_source" : { + "message" : "order updated", + "details" : { + "order_id" : 124, + "items" : [ + { + "sku" : "B9", + "qty" : 1 + } + ], + "expedited" : false + }, + "payload" : "{\"user\":{\"id\":\"u-77\",\"role\":\"viewer\"},\"ip\":\"10.0.0.9\"}", + "details_json" : "{\"order_id\":124,\"items\":[{\"sku\":\"B9\",\"qty\":1}],\"expedited\":false}" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/sinks/aws-lambda.md b/i18n/zh/data-prepper/pipelines/configuration/sinks/aws-lambda.md new file mode 100644 index 00000000..1b6542a7 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sinks/aws-lambda.md @@ -0,0 +1,95 @@ +--- +title: AWS Lambda +--- + +# AWS Lambda sink + +This page explains how to configure and use [AWS Lambda](https://aws.amazon.com/lambda/) with OpenSearch Data Prepper, enabling Lambda functions to serve as both processors and sinks. + +## Configuration + +Configure the Lambda sink using the following parameters. + +Field | Type | Required | Description +--------------------| ------- | -------- | ---------------------------------------------------------------------------- +`function_name` | String | Yes | The name of the AWS Lambda function to invoke. +`invocation_type` | String | No | Specifies the invocation type. Default is `event`. +`aws.region` | String | Yes | The AWS Region in which the Lambda function is located. +`aws.sts_role_arn` | String | No | The Amazon Resource Name (ARN) of the role to assume before invoking the Lambda function. +`aws.sts_external_id` | String | No | The external ID to use when assuming the role specified in `aws.sts_role_arn`. Must be between 2 and 1,224 characters. +`aws.sts_header_overrides` | Map | No | A map of header overrides to apply to the request that assumes the role specified in `aws.sts_role_arn`. Maximum of 5 headers. +`client.max_retries` | Integer | No | The maximum number of AWS SDK client-level retries for individual API calls. This controls the underlying SDK retry mechanism for network or service errors. Default is `3`. +`client.api_call_timeout` | Duration | No | The total timeout for the entire API call including all retries. Default is `60s`. +`client.api_call_attempt_timeout` | Duration | No | The timeout for each individual retry attempt. If not specified, AWS SDK defaults are used. +`client.connection_timeout` | Duration | No | The SDK connection timeout. Default is `60s`. +`client.read_timeout` | Duration | No | The amount of time the SDK waits for data to be read from an established connection. If not specified, AWS SDK defaults are used. +`client.max_concurrency` | Integer | No | The maximum number of concurrent threads in the client. Default is `200`. +`client.base_delay` | Duration | No | The base delay for the exponential backoff. Default is `100ms`. +`client.max_backoff` | Duration | No | The maximum backoff time for the exponential backoff. Default is `20s`. +`client.retryable_status_codes` | List | No | A list of HTTP status codes that trigger a client-level retry when returned by a Lambda invocation, for example `[500, 502, 503, 504]`. These retries count toward `client.max_retries`. Default is an empty list, in which case Data Prepper retries only throttling errors, Lambda service errors, and network or connection errors. Use for idempotent functions for which retrying transient server-side errors is safe. +`batch` | Object | No | Optional batch settings for Lambda invocations. Contains `key_name` (default: `"events"`) and `threshold` object with `event_count` (default: `100`), `maximum_size` (default: `"5mb"`), and `event_collect_timeout` (default: `10s`). +`dlq` | Object | No | The dead-letter queue (DLQ) configuration for failed invocations. + +#### Example configuration + +```yaml +sink: + - aws_lambda: + function_name: "my-lambda-sink" + invocation_type: "event" + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-lambda-sink-role" + client: + max_retries: 3 + api_call_timeout: PT60S + api_call_attempt_timeout: PT30S # Optional: per-attempt timeout + connection_timeout: PT60S + read_timeout: PT15M # Optional: for long-running Lambda functions + max_concurrency: 200 + base_delay: PT0.1S + max_backoff: PT20S + retryable_status_codes: [500, 502, 503, 504] # Optional: retry these Lambda invocation status codes + batch: + key_name: "events" + threshold: + event_count: 50 + maximum_size: "3mb" + event_collect_timeout: PT5S + dlq: + s3: + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/my-sqs-role" + bucket: "<<your-dlq-bucket-name>>" +``` + +## Timeout configuration + +The AWS Lambda sink supports multiple timeout layers following AWS SDK best practices: + +- `api_call_timeout`: The total amount of time for the entire API call including all retries. +- `api_call_attempt_timeout`: The time limit for each individual attempt. +- `read_timeout`: The amount of time to wait for data from an established connection. + +For Lambda functions that run for longer than 60 seconds, configure both `api_call_timeout` and `read_timeout` to appropriate values. + +## Usage + +The invocation types are as follows: + +- `event` (Default): Executes functions asynchronously without waiting for responses. +- `request-response` (Sink only): Executes functions synchronously, though responses are not processed. +- `batch`: Automatically groups events based on configured thresholds. +- `dlq`: Supports the DLQ configuration for failed invocations after retry attempts. + +::: info NOTE +Data Prepper components use an AWS Identity and Access Management (IAM) role assumption, `aws.sts_role_arn`, for secure Lambda function invocation and respect Lambda's concurrency limits during event processing. For more information, see the [AWS Lambda documentation](https://docs.aws.amazon.com/lambda). +::: + +## Developer guide + +Integration tests must be executed separately from the main Data Prepper build. Execute them with the following command: + +```bash +./gradlew :data-prepper-plugins:aws-lambda:integrationTest -Dtests.sink.lambda.region="us-east-1" -Dtests.sink.lambda.functionName="lambda_test_function" -Dtests.sink.lambda.sts_role_arn="arn:aws:iam::123456789012:role/dataprepper-role +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/sinks/otlp.md b/i18n/zh/data-prepper/pipelines/configuration/sinks/otlp.md new file mode 100644 index 00000000..0d43eb10 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sinks/otlp.md @@ -0,0 +1,214 @@ +--- +title: OTLP +--- + +# OTLP sink + +::: danger WARNING +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the [`otlp` sink plugin](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/otlp-sink) in the OpenSearch Data Prepper repository. +::: + +The `otlp` sink exports traces, metrics, and logs to an endpoint that accepts [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otlp/) requests over HTTP. It encodes each batch as Protobuf, compresses it with `gzip`, and signs the request with AWS Signature Version 4 (SigV4). To send data to an endpoint that accepts SigV4-signed requests, set `service_name` to that endpoint's signing name. Because the sink signs every request and requires AWS credentials, it is designed for endpoints that use AWS authentication. + +The sink determines the signal type of each event from the event's type: span events are exported as OTLP trace data, metric events as metric data, and log events as log data. The sink accepts only span, metric, and log events, such as the events produced by the [`otlp` source](/data-prepper/pipelines/configuration/sources/otlp-source). Any other event is dropped and counted in the `failedRecordsCount` metric. + +The sink maintains a separate buffer for each signal type, so each signal type is batched independently. Each request contains a batch of events of a single signal type, assembled according to the [threshold configuration](#threshold-configuration). A batch can contain spans from many traces, and the spans of a single trace can be sent in different requests. + +Each sink sends all signals to the single URL configured in `endpoint`. Because OTLP/HTTP endpoints use a different path for each signal (`/v1/traces`, `/v1/metrics`, and `/v1/logs`), configure one `otlp` sink per signal and use [conditional routing](/data-prepper/pipelines/pipelines#conditional-routing) when a pipeline carries more than one signal type. For an example, see [Routing mixed signal types](#routing-mixed-signal-types). + +## Prerequisites + +To use the `otlp` sink, enable the experimental `otlp` plugin in `data-prepper-config.yaml`: + +```yaml +experimental: + enabled_plugins: + sink: + - otlp +``` + +## Usage + +The following examples configure the `otlp` sink for different scenarios. + +### Sending traces to AWS X-Ray + +The following pipeline sends spans to the AWS X-Ray OTLP endpoint. Because the endpoint host contains the Region, `aws.region` can be omitted: + +```yaml +trace-pipeline: + source: + otlp: + ssl: false + sink: + - otlp: + endpoint: "https://xray.us-east-1.amazonaws.com/v1/traces" + aws: + sts_role_arn: "arn:aws:iam::123456789012:role/data-prepper-otlp-role" +``` + +### Configuring custom signing values and headers + +The following pipeline sends logs to an endpoint that accepts SigV4-signed requests but is not AWS X-Ray. It sets `service_name` to the endpoint's Signature Version 4 signing name, sets `aws.region` explicitly because the endpoint host does not contain a Region, and adds a custom header to every request: + +```yaml +log-pipeline: + source: + http: + port: 2021 + path: "/logs" + sink: + - otlp: + endpoint: "https://my-otlp-endpoint.example.com:443/v1/logs" + service_name: "my-service" + max_retries: 3 + threshold: + max_events: 100 + flush_timeout: 5s + aws: + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/data-prepper-otlp-role" + additional_headers: + x-custom-header: "my-value" +``` + +### Routing mixed signal types + +The following pipeline receives all three signal types from an [`otlp` source](/data-prepper/pipelines/configuration/sources/otlp-source) and routes each one to a sink configured with the matching signal path: + +```yaml +otlp-pipeline: + source: + otlp: + ssl: false + route: + - traces: 'getEventType() == "TRACE"' + - metrics: 'getEventType() == "METRIC"' + - logs: 'getEventType() == "LOG"' + sink: + - otlp: + routes: + - traces + endpoint: "https://xray.us-east-1.amazonaws.com/v1/traces" + aws: + region: "us-east-1" + - otlp: + routes: + - metrics + endpoint: "https://my-otlp-endpoint.example.com/v1/metrics" + service_name: "my-service" + aws: + region: "us-east-1" + - otlp: + routes: + - logs + endpoint: "https://my-otlp-endpoint.example.com/v1/logs" + service_name: "my-service" + aws: + region: "us-east-1" +``` + +## Configuration + +Use the following options to configure the `otlp` sink. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`endpoint` | Yes | String | The OTLP/HTTP endpoint URL, including the signal path, for example, `https://xray.us-east-1.amazonaws.com/v1/traces`. +`aws` | Yes | [AWS configuration](#aws-configuration) | The AWS configuration used for SigV4 signing. All requests are signed, so this block must be present, even when it is empty. +`service_name` | No | String | The SigV4 signing name used for requests, for example, `logs` or `osis`. Default is `xray`. +`max_retries` | No | Integer | The maximum number of retries for a failed request. The sink retries the `429`, `502`, `503`, and `504` status codes using exponential backoff with jitter. Default is `5`. +`threshold` | No | [Threshold configuration](#threshold-configuration) | The batching and flushing configuration. +`additional_headers` | No | Map | The HTTP headers added to every request. Default is an empty map. + +::: info NOTE +The `aws` block is required in this release. Support for OTLP endpoints that do not use Signature Version 4 signing is not yet available. +::: + +::: info NOTE +Headers in `additional_headers` are added after the request is signed, so they are not part of the Signature Version 4 signature. To keep signing valid, the sink rejects the `Authorization`, `Host`, `Content-Type`, `Content-Encoding`, and `Content-Length` headers and any header whose name begins with `x-amz-`. A pipeline that configures one of these headers fails to start. +::: + +## Threshold configuration + +The sink flushes a batch when any threshold is reached. Use the following options to configure batching and flushing. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`max_events` | No | Integer | The maximum number of events in a batch. Set to `0` to flush based only on `max_batch_size` and `flush_timeout`. Default is `512`. +`max_batch_size` | No | String | The maximum size of the uncompressed batch payload. Default is `1mb`. +`flush_timeout` | No | Duration | The maximum amount of time to wait before flushing a batch. Must be at least `1ms`. Default is `200ms`. + +::: info NOTE +The sink sets the HTTP response timeout to twice the `flush_timeout` value, within a range of 3 to 10 seconds. For a `flush_timeout` of 1.5 seconds or less, the response timeout is 3 seconds. For a `flush_timeout` between 1.5 and 5 seconds, the response timeout is twice the `flush_timeout`. For a `flush_timeout` of 5 seconds or more, the response timeout is 10 seconds. +::: + +Each signal type uses its own queue of events waiting to be batched. The queue capacity is 10 times `max_events`, with a minimum of 2,000 events, so the queue grows when you increase `max_events`. When a queue is full, the sink applies backpressure to the pipeline and does not drop events. + +## AWS configuration + +Use the following options in the `aws` block to configure credentials and signing. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region used for SigV4 signing and credentials. If not specified, the sink parses the Region from the hostname in `endpoint` and fails at startup if the hostname does not contain a valid Region. +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests. Defaults to `null`, which uses the [default credential provider chain](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | The external ID to use when assuming the AWS STS role. + +## Limitations + +The `otlp` sink has the following limitations: + +- Traces can be sent only to AWS X-Ray-compatible endpoints (`https://xray.<region>.amazonaws.com/v1/traces`). Metrics and logs can be sent to any OTLP endpoint that accepts SigV4-signed Protobuf requests. +- Only OTLP over HTTP is supported. OTLP over gRPC is not supported. +- When the retries configured in `max_retries` are exhausted, the batch is dropped and the failure is logged and counted. Because the sink retries a batch after a retryable status code, the endpoint can receive the same batch more than once. Dead-letter queue (DLQ) delivery is not supported. + +## Metrics + +The `otlp` sink provides the following metrics in addition to the [common sink metrics](/data-prepper/managing-data-prepper/monitoring). + +### Counters + +The following counters track the records and responses processed by the `otlp` sink. + +Metric | Description +:--- | :--- +`recordsOut` | The number of records that the endpoint accepted. +`rejectedRecordsCount` | The number of records that the endpoint rejected or that could not be delivered. +`failedRecordsCount` | The number of records that the sink could not process, including events that are not spans, metrics, or logs. +`rejectedSpansCount`, `rejectedMetricsCount`, `rejectedLogsCount` | The number of rejected records for each signal type. +`failedSpansCount`, `failedMetricsCount`, `failedLogsCount` | The number of failed records for each signal type. +`errorsCount` | The number of unexpected worker thread errors. +`http2xxResponses`, `http4xxResponses`, `http5xxResponses` | The number of responses received for each status code category. + +### Timers + +The following timer tracks request latency in the `otlp` sink. + +Metric | Description +:--- | :--- +`httpLatency` | The amount of time taken to receive a response from the endpoint. + +### Distribution summaries + +The following distribution summaries track payload sizes in the `otlp` sink. + +Metric | Description +:--- | :--- +`payloadSize` | The distribution of uncompressed request payload sizes, in bytes. +`payloadGzipSize` | The distribution of `gzip`-compressed request payload sizes, in bytes. + +### Gauges + +The following gauges track the queue of each signal type in the `otlp` sink. + +Metric | Description +:--- | :--- +`queueSize` | The number of events waiting to be sent. +`queueCapacity` | The total capacity of the queue. + +## Related documentation + +- [OTLP source](/data-prepper/pipelines/configuration/sources/otlp-source) +- [getEventType()](/data-prepper/pipelines/get-eventtype) +- [Conditional routing](/data-prepper/pipelines/pipelines#conditional-routing) diff --git a/i18n/zh/data-prepper/pipelines/configuration/sinks/prometheus.md b/i18n/zh/data-prepper/pipelines/configuration/sinks/prometheus.md new file mode 100644 index 00000000..0d0e0c22 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sinks/prometheus.md @@ -0,0 +1,169 @@ +--- +title: Prometheus +--- + +# Prometheus sink + +::: danger WARNING +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the [`prometheus` sink plugin](https://github.com/opensearch-project/data-prepper/tree/main/data-prepper-plugins/prometheus-sink) in the OpenSearch Data Prepper repository. +::: + +The Prometheus sink buffers OpenTelemetry metrics and exports them in Prometheus time series format using the Remote Write API. It supports both open-source Prometheus and Amazon Managed Service for Prometheus (AMP). + +The `prometheus` sink processes only metric data. All other data types are sent to the [DLQ pipeline](/data-prepper/pipelines/dlq), if it is configured. + +To ensure compatibility, the Prometheus sink sorts metrics by timestamp within each batch before sending them to the server. It also supports an out-of-order window, which allows ingestion of metrics with older timestamps. + +## Prerequisites + +To use the `prometheus` sink, enable the experimental `prometheus` plugin in `data-prepper-config.yaml`: + +```yaml +experimental: + enabled_plugins: + sink: + - prometheus +``` + +## Usage + +The following examples configure the Prometheus sink for different deployment scenarios. + +### Open-source Prometheus with no authentication + +To use an open-source Prometheus instance, provide an `https://` URL. To use `http://`, set `insecure` to `true`. No `aws` block is needed. Prometheus must be started with the `--web.enable-remote-write-receiver` flag: + +```yaml +pipeline: + ... + sink: + - prometheus: + url: "http://localhost:9090/api/v1/write" + insecure: true + threshold: + max_events: 1000 + flush_interval: PT5S +``` + +### Open-source Prometheus with HTTP Basic authentication + +To authenticate with HTTP Basic credentials (for example, when Prometheus is behind a reverse proxy with basic authentication enabled), use the `authentication` block: + +```yaml +pipeline: + ... + sink: + - prometheus: + url: "https://localhost:9090/api/v1/write" + authentication: + http_basic: + username: "promuser" + password: "prompass" +``` + +### AMP + +To use AMP, provide the `aws` configuration block. An `https://` URL is required when using AWS authentication: + +```yaml +pipeline: + ... + sink: + - prometheus: + url: "https://aps-workspaces.us-east-2.amazonaws.com/workspaces/ws-xxxxxxxx-xxxx/api/v1/remote_write" + aws: + region: "us-east-2" + sts_role_arn: "arn:aws:iam::123456789012:role/data-prepper-prometheus-role" + threshold: + max_events: 1000 + flush_interval: PT5S +``` + +## IAM permissions + +When using AMP, configure AWS Identity and Access Management (IAM) to grant OpenSearch Data Prepper permissions to write to Amazon Managed Service for Prometheus. You can use a configuration similar to the following JSON configuration: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "amp-access", + "Effect": "Allow", + "Action": [ + "aps:RemoteWrite" + ], + "Resource": "arn:aws:aps:<region>:<account-id:workspace>/<workspace-id>" + } + ] +} +``` + +## Configuration + +Use the following options when customizing the `prometheus` sink. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`url` | Yes | String | The Prometheus Remote Write endpoint URL. Supports `https://` by default. To use `http://`, set `insecure` to `true`. When `aws` is configured, `https://` is required. +`insecure` | No | Boolean | When set to `true`, allows `http://` URLs. By default, only `https://` URLs are permitted. Default is `false`. +`encoding` | No | String | The compression format used for requests. Only `snappy` is supported. Default is `snappy`. +`remote_write_version` | No | String | The version of the Prometheus remote write protocol. Only `0.1.0` is supported. +`content_type` | No | String | The MIME type of the body. Only `application/x-protobuf` is supported. +`out_of_order_time_window` | No | Duration | The time window allowed for late-arriving data points. Data older than this window relative to the latest point will be dropped. Default is `10s`. +`sanitize_names` | No | Boolean | Determines whether metric and label names are sanitized in order to comply with Prometheus naming conventions. Default is `true`. +`instance_label` | No | String | The name of a label that identifies the Data Prepper instance in every time series that the sink writes. Use it when multiple instances run the same pipeline. For more information, see [Instance label](#instance-label). By default, no instance label is added. +`connection_timeout` | No | Duration | The maximum amount of time allowed to establish an HTTP connection. Must be between 1 and 600 seconds. Default is `60s`. +`idle_timeout` | No | Duration | The maximum amount of time an idle HTTP connection remains open before being closed. Must be between 1 and 600 seconds. Default is `60s`. +`request_timeout` | No | Duration | The maximum amount of time allowed for a full end-to-end HTTP request to complete. Must be between 1 and 600 seconds. Default is `60s`. +`threshold` | No | [Threshold configuration](#threshold-configuration) | Configuration for batching and flushing time-series data. +`max_retries` | No | Integer | The maximum number of attempts for failed ingestion requests. Uses exponential backoff with jitter on `retryable` status codes (`429`, `502`, `503`, or `504`). Default is `5`. +`aws` | No | [AWS configuration](#aws-configuration) | AWS configuration for AWS Signature Version 4 signing. When present, requests are signed with AWS credentials. Cannot be used with `authentication`. +`authentication` | No | [Authentication configuration](#authentication-configuration) | HTTP Basic authentication credentials. Cannot be used with `aws`. + +## Instance label + +When multiple Data Prepper instances run the same pipeline configuration, they write identical time series, and the Remote Write endpoint keeps only one sample for each series and timestamp. To keep the samples from each instance, set `instance_label` to a label name. The sink adds this label to every time series it writes. The label value is a truncated SHA-256 hash of the host identity, which the sink resolves once at startup from the local hostname, the `HOSTNAME` environment variable, or a local network address. If no host identity can be resolved, the pipeline fails to start. Instances that share a network namespace resolve the same identity unless they have distinct `HOSTNAME` values. + +The label name must match `[a-zA-Z_][a-zA-Z0-9_]*`, must not begin with `__`, and cannot be `le`, `ge`, or `quantile`. If a series already has a label with the same name, the existing label value is kept and the instance label is not added to that series. The comparison uses the final label names that the sink generates, which include a prefix for attributes. For example, a metric attribute named `x` becomes the `metric_attributes_x` label, so setting `instance_label` to `x` adds both labels. + +The following example adds the `dp_instance` label: + +```yaml +sink: + - prometheus: + url: "http://localhost:9090/api/v1/write" + instance_label: dp_instance +``` + +To calculate the total across instances, aggregate the label away in your queries, for example, `sum without (dp_instance) (my_metric)`. + +## Threshold configuration + +Use the following options to configure batching and flushing behavior for the Prometheus sink. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`max_events` | No | Integer | The maximum number of events to accumulate before flushing to Prometheus. Default is `1000`. +`max_request_size` | No | String | The maximum size of the request payload before flushing. Default is `1mb`. +`flush_interval` | No | Duration | The maximum amount of time to wait before flushing events. Default is `10s`. + +## AWS configuration + +When an `aws` block is present, requests are automatically signed with Signature Version 4. An `https://` URL is required. The AWS configuration supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for credentials. Defaults to [standard SDK behavior to determine the region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The STS role to assume for requests to AWS. Defaults to `null`, which uses [standard SDK credential behavior](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_header_overrides` | No | Map | A map of header overrides to make when assuming the IAM role. Maximum of 5 headers. +`sts_external_id` | No | String | An optional external ID to use when assuming the IAM role. Must be between 2 and 1,224 characters. + +## Authentication configuration + +The `authentication` block supports HTTP Basic authentication. It cannot be used together with `aws` (Signature Version 4 signing). The authentication configuration supports the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`http_basic.username` | Yes | String | The username for HTTP Basic authentication. +`http_basic.password` | Yes | String | The password for HTTP Basic authentication. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/atlassian-confluence.md b/i18n/zh/data-prepper/pipelines/configuration/sources/atlassian-confluence.md new file mode 100644 index 00000000..1401dd96 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/atlassian-confluence.md @@ -0,0 +1,145 @@ +--- +title: Atlassian Confluence +--- + +# Atlassian Confluence source + +You can use the OpenSearch Data Prepper `confluence` source to ingest records from one or more [Atlassian Confluence](https://www.atlassian.com/software/confluence) spaces. + +## Usage + +Set up Confluence project access credentials by choosing one of the following options: + +- **Basic authentication** (API key authentication): Follow [these instructions](https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/). +- **OAuth 2.0 authentication**: Follow [these instructions](https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#faq-rrt-config). +- **Bearer token authentication**: Provide a token that the source sends in the `Authorization: Bearer` header of each request. + +As an additional optional step, store the credentials in AWS Secrets Manager. If you don't store the credentials in AWS Secrets Manager, then you must provide plain-text credentials directly in the pipeline configuration. + +The following example pipeline specifies `confluence` as a source. The pipeline ingests data from multiple Confluence spaces named `space1` and `space2` and applies filters to select wiki content (pages and blog posts) from these projects as a source: + +```yaml +version: "2" +extension: + aws: + secrets: + confluence-account-credentials: + secret_id: "arn:aws:secretsmanager:us-east-1:123456789012:secret:confluence-credentials-secret" + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/Example-Role" +atlassian-confluence-pipeline: + source: + confluence: + hosts: ["https://example.atlassian.net/"] + acknowledgments: true + preserve_formatting: true + authentication: + # Provide one of the authentication method to use. Supported methods are 'basic', 'oauth2', and 'bearer_token'. + # For basic authentication, password is the API key that you generate using your confluence account + basic: + username: ${{aws_secrets:confluence-account-credentials:username}} + password: ${{aws_secrets:confluence-account-credentials:password}} + # For OAuth 2.0-based authentication, we require the following 4 key values stored in the secret + # Follow atlassian instructions at the following link to generate these keys + # https://developer.atlassian.com/cloud/confluence/oauth-2-3lo-apps/ + # If you are using OAuth 2.0 authentication, we also require, write permission to your aws secret to + # be able to write the renewed tokens back into the secret + # oauth2: + # client_id: ${{aws_secrets:confluence-account-credentials:clientId}} + # client_secret: ${{aws_secrets:confluence-account-credentials:clientSecret}} + # access_token: ${{aws_secrets:confluence-account-credentials:accessToken}} + # refresh_token: ${{aws_secrets:confluence-account-credentials:refreshToken}} + filter: + space: + key: + include: + # This is not space name. + # It is an alphanumeric space key that you can find under space details in confluence + - "space1" + - "space2" + # exclude: + # - "<<space key>>" + # - "<<space key>>" + page_type: + include: + - "page" + # - "blogpost" + # - "comment" + # exclude: + # - "attachment" +``` + +## Configuration options + +The `confluence` source supports the following configuration options. + +| Option | Required | Type | Description | +|:------------------|:---------|:----------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `hosts` | Yes | List | The Atlassian Confluence hostname. Currently, only one host is supported, so this list is expected to be of size 1. | +| `acknowledgments` | No | Boolean | When set to `true`, enables the `confluence` source to receive [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. | +| `preserve_formatting` | No | Boolean | When set to `true`, Confluence content formatting markup tags are kept as is. Default is `false` (remove markup tags and convert to plain text). | +| `allow_internal_address` | No | Boolean | When set to `true`, allows the host specified in `hosts` to resolve to a private, loopback, or link-local IP address. When set to `false`, the source rejects hosts that resolve to these addresses. Default is `false`. | +| `authentication` | Yes | [authentication](#Authentication) | Configures the authentication method used to access `confluence` source records from the specified host. | +| `filter` | No | [filter](#Filter) | Applies specific filter criteria while extracting Confluence content. | + +### Authentication + +Use one of the following authentication methods to access a Confluence host. You must provide exactly one of the following parameters. + +| Option | Required | Type | Description | +|:---------|:---------|:------------------|:-------------------------------------------------------------| +| `basic` | Yes | [Basic](#basic-authentication) | Basic authentication credentials used to access a Confluence host. | +| `oauth2` | Yes | [OAuth 2.0](#oauth-20-authentication) | OAuth 2.0 authentication credentials used to access a Confluence host. | +| `bearer_token` | Yes | String | A bearer token or reference to the secret key storing the bearer token. The source sends the token in the `Authorization: Bearer` header of each request. If the token is stored in AWS Secrets Manager, the source reloads the secret value when the host returns a `401` response. | + +#### Basic authentication + +If you use `basic` authentication, the following fields are required. + +| Option | Required | Type | Description | +|:-----------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `username` | Yes | String | A username or reference to the secret key storing the username. | +| `password` | Yes | String | A password (API key) or reference to the secret key storing the password. | + +#### OAuth 2.0 authentication + +If you use OAuth 2.0, the following fields are required. + +| Option | Required | Type | Description | +|:----------------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `client_id` | Yes | String | A `client_id` or reference to the secret key storing the `client_id`. | +| `client_secret` | Yes | String | A `client_secret` or reference to the secret key storing the `client_secret`. | +| `access_token` | Yes | String | An `access_token` or reference to the secret key storing the `access_token`. | +| `refresh_token` | Yes | String | A `refresh_token` or reference to the secret key storing the `refresh_token`. | + +### Filter + +Optionally, you can specify filters to select specific content, shown in the following table. If no filters are specified, all the spaces and content visible for the specified credentials are extracted and sent to the specified sink in the pipeline. + +| Option | Required | Type | Description | +|:------------|:---------|:-------|:----------------------------------------------| +| `space` | No | Object | Filters content by space. Contains the `key` object, which accepts `include` and `exclude` lists of space keys. Use the space key, not the space name. Each space key must be 2--100 characters long and contain only letters and digits. A space key cannot appear in both lists. | +| `page_type` | No | Object | Filters content by type. Accepts `include` and `exclude` lists of content types. Valid values are `page`, `blogpost`, `comment`, and `attachment`. A content type cannot appear in both lists. | + +The source validates filter values when it starts crawling. If a filter contains an invalid value, the source logs an error and does not ingest content. + +### AWS secrets + +You can use the following options in the `aws` secrets configuration if you plan to store the credentials in AWS Secrets Manager. Storing secrets in AWS Secrets Manager is optional. If AWS Secrets Manager is not used, credentials must be specified in the pipeline YAML itself, in plain text. + +If OAuth 2.0 authentication is used in combination with `aws` secrets, this source requires write permissions to AWS Secrets Manager to be able to write back the updated (or renewed) access token once the current token expires. + +| Option | Required | Type | Description | +|:---------------|:---------|:-------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `region` | Yes | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). | +| `sts_role_arn` | Yes | String | The AWS Security Token Service (AWS STS) role to assume for requests to Atlassian Confluence. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). | +| `secret_id` | Yes | Map | The Amazon Resource Name (ARN) of the secret where the credentials are stored. | + +## Metrics + +The `confluence` source includes the following metrics (counters): + +* `crawlingTime`: The amount of time taken to crawl through all the new changes in Confluence. +* `pageFetchLatency`: The page fetch API operation latency. +* `searchCallLatency`: The search API operation latency. +* `searchResultsFound`: The number of pages found in a specified search API call. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/atlassian-jira.md b/i18n/zh/data-prepper/pipelines/configuration/sources/atlassian-jira.md new file mode 100644 index 00000000..13b7eeb0 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/atlassian-jira.md @@ -0,0 +1,148 @@ +--- +title: Atlassian Jira +--- + +# Atlassian Jira source + +You can use the OpenSearch Data Prepper `jira` source to ingest records from one or more [Atlassian Jira](https://www.atlassian.com/software/jira) projects. + +## Usage + +Set up Jira project access credentials by choosing one of the following options: + +- **Basic authentication** (API key authentication): Follow [these instructions](https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/). +- **OAuth 2.0 authentication**: Follow [these instructions](https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#faq-rrt-config). + +As an additional optional step, store the credentials in AWS Secrets Manager. If you don't store the credentials in AWS Secrets Manager, then you must provide plain-text credentials directly in the pipeline configuration. + +The following example pipeline specifies `jira` as a source. The pipeline ingests data from Jira projects named `project1` and `project2` and applies filters to select tickets from these projects as a source: + +```yaml +version: "2" +extension: + aws: + secrets: + jira-account-credentials: + secret_id: "arn:aws:secretsmanager:us-east-1:123456789012:secret:jira-credentials-secret" + region: "us-east-1" + sts_role_arn: "arn:aws:iam::123456789012:role/Example-Role" +atlassian-jira-pipeline: + source: + jira: + hosts: ["https://example.atlassian.net/"] + acknowledgments: true + authentication: + # Provide one of the authentication method to use. Supported methods are 'basic' and 'oauth2'. + # For basic authentication, password is the API key that you generate using your jira account + basic: + username: ${{aws_secrets:jira-account-credentials:username}} + password: ${{aws_secrets:jira-account-credentials:password}} + # For OAuth 2.0-based authentication, we require the following 4 key values stored in the secret + # Follow atlassian instructions at the following link to generate these keys + # https://developer.atlassian.com/cloud/confluence/oauth-2-3lo-apps/ + # If you are using OAuth 2.0 authentication, we also require, write permission to your aws secret to + # be able to write the renewed tokens back into the secret + # oauth2: + # client_id: ${{aws_secrets:jira-account-credentials:clientId}} + # client_secret: ${{aws_secrets:jira-account-credentials:clientSecret}} + # access_token: ${{aws_secrets:jira-account-credentials:accessToken}} + # refresh_token: ${{aws_secrets:jira-account-credentials:refreshToken}} + filter: + project: + key: + include: + # This is not project name. + # It is an alphanumeric project key that you can find under project details in jira + - "PROJECT1" + - "PROJECT2" + # exclude: + # - "<<project key>>" + # - "<<project key>>" + issue_type: + include: + - "Story" + # - "Bug" + # - "Task" + # exclude: + # - "Epic" + status: + include: + - "To Do" + # - "In Progress" + # - "Done" + # exclude: + # - "Backlog" +``` + +## Configuration options + +The `jira` source supports the following configuration options. + +| Option | Required | Type | Description | +|:------------------|:---------|:----------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `hosts` | Yes | List | The Atlassian Jira hostname. Currently, only one host is supported, so this list is expected to be of size 1. | +| `acknowledgments` | No | Boolean | When set to `true`, enables the `jira` source to receive [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. | +| `authentication` | Yes | [authentication](#Authentication) | Configures the authentication method used to access `jira` source records from the specified host. | +| `filter` | No | [filter](#Filter) | Applies specific filter criteria while extracting Jira tickets. | + +### Authentication + +You can use one of the following authentication methods to access the specified Jira host. You must provide one of the following parameters. + +| Option | Required | Type | Description | +|:---------|:---------|:------------------|:-------------------------------------------------------| +| `basic` | Yes | [Basic](#basic-authentication) | Basic authentication credentials used to access a Jira host. | +| `oauth2` | Yes | [OAuth 2.0](#oauth-20-authentication)| OAuth 2.0 authentication credentials used to access a Jira host. | + +#### Basic authentication + +Either basic or OAuth 2.0 credentials are required to access the Jira site. If you use `basic` authentication, the following fields are required. + +| Option | Required | Type | Description | +|:-----------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `username` | Yes | String | A username or reference to the secret key storing the username. | +| `password` | Yes | String | A password (API key) or reference to the secret key storing the password. | + +#### OAuth 2.0 authentication + +Either basic or OAuth 2.0 credentials are required to access the Jira site. If you use OAuth 2.0, the following fields are required. + +| Option | Required | Type | Description | +|:----------------|:---------|:-------|:------------------------------------------------------------------------------------------------| +| `client_id` | Yes | String | A `client_id` or reference to the secret key storing the `client_id`. | +| `client_secret` | Yes | String | A `client_secret` or reference to the secret key storing the `client_secret`. | +| `access_token` | Yes | String | An `access_token` or reference to the secret key storing the `access_token`. | +| `refresh_token` | Yes | String | A `refresh_token` or reference to the secret key storing the `refresh_token`. | + +### Filter + +Optionally, you can specify filters to select specific content. If no filters are specified, all the projects and tickets visible for the specified credentials will be extracted and sent to the specified sink in the pipeline. + +| Option | Required | Type | Description | +|:-------------|:---------|:-------|:-----------------------------------------------| +| `project` | No | Object | Filters issues by project. Contains the `key` object, which accepts `include` and `exclude` lists of project keys. Each project key must be 2--100 characters long and contain only uppercase letters and digits. A project key cannot appear in both lists. | +| `issue_type` | No | Object | Filters issues by issue type. Accepts `include` and `exclude` lists of issue type names, for example, `Story` or `Bug`. | +| `status` | No | Object | Filters issues by status. Accepts `include` and `exclude` lists of status names, for example, `In Progress` or `Done`. | + +The source validates project keys when it starts crawling. If a project filter contains an invalid key, the source logs an error and does not ingest issues. + +### AWS secrets + +You can use the following options in the `aws` secrets configuration if you plan to store the credentials in AWS Secrets Manager. Storing secrets in AWS Secrets Manager is optional. If AWS Secrets Manager is not used, credentials must be specified in the pipeline YAML itself, in plain text. + +If OAuth 2.0 authentication is used in combination with `aws` secrets, this source requires write permissions to the secret to be able to write back the updated (or renewed) access token once the current token expires. + +| Option | Required | Type | Description | +|:---------------|:---------|:-------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `region` | Yes | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). | +| `sts_role_arn` | Yes | String | The AWS Security Token Service (AWS STS) role to assume for requests to Atlassian Jira. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). | +| `secret_id` | Yes | Map | The Amazon Resource Name (ARN) of the secret where the credentials are stored. + +## Metrics + +The `jira` source includes the following metrics (counters): + +* `crawlingTime`: The amount of time taken to crawl through all the new changes in Jira. +* `ticketFetchLatency`: The ticket fetch API operation latency. +* `searchCallLatency`: The search API operation latency. +* `searchResultsFound`: The number of tickets found in a specified search API call. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/documentdb.md b/i18n/zh/data-prepper/pipelines/configuration/sources/documentdb.md new file mode 100644 index 00000000..78b92259 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/documentdb.md @@ -0,0 +1,93 @@ +--- +title: DocumentDB +--- + +# DocumentDB source + +The `documentdb` source reads documents from [Amazon DocumentDB](https://aws.amazon.com/documentdb/) collections. +It can read historical data from an export and keep up to date on the data using Amazon DocumentDB [change streams](https://docs.aws.amazon.com/documentdb/latest/developerguide/change_streams.html). + +The `documentdb` source reads data from Amazon DocumentDB and puts that data into an [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) bucket. +Then, other OpenSearch Data Prepper workers read from the S3 bucket to process data. + +## Usage +The following example pipeline uses the `documentdb` source: + +```yaml +version: "2" +documentdb-pipeline: + source: + documentdb: + host: "docdb-mycluster.cluster-random.us-west-2.docdb.amazonaws.com" + port: 27017 + authentication: + username: ${{aws_secrets:secret:username}} + password: ${{aws_secrets:secret:password}} + aws: + sts_role_arn: "arn:aws:iam::123456789012:role/MyRole" + s3_bucket: my-bucket + s3_region: us-west-2 + collections: + - collection: my-database.my-collection + export: true + stream: true + acknowledgments: true +``` + +## Configuration + +You can use the following options to configure the `documentdb` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`host` | Yes | String | The hostname of the Amazon DocumentDB cluster. +`port` | No | Integer | The port number of the Amazon DocumentDB cluster. Defaults to `27017`. +`trust_store_file_path` | No | String | The path to a truststore file that contains the public certificate for the Amazon DocumentDB cluster. +`trust_store_password` | No | String | The password for the truststore specified by `trust_store_file_path`. +`authentication` | Yes | Authentication | The authentication configuration. See the [authentication](#authentication) section for more information. +`collections` | Yes | List | A list of collection configurations. Exactly one collection is required. See the [collections](#collection) section for more information. +`s3_bucket` | Yes | String | The S3 bucket to use for processing events from Amazon DocumentDB. +`s3_prefix` | No | String | An optional Amazon S3 key prefix. By default, there is no key prefix. +`s3_region` | No | String | The AWS Region in which the S3 bucket resides. +`aws` | Yes | AWS | The AWS configuration. See the [`aws`](#aws) section for more information. +`id_key` | No | String | When specified, the Amazon DocumentDB `_id` field is set to the key name specified by `id_key`. You can use this when you need more information than is provided by the `ObjectId` string saved to your sink. By default, the `_id` is not included as part of the event. +`direct_connection` | No | Boolean | When `true`, the MongoDB driver connects directly to the specified Amazon DocumentDB server(s) without discovering and connecting to the entire replica set. Defaults to `true`. +`read_preference` | No | String | Determines how to read from Amazon DocumentDB. See [Read Preference Modes](https://www.mongodb.com/docs/v3.6/reference/read-preference/#read-preference-modes) for more information. Defaults to `primaryPreferred`. +`disable_s3_read_for_leader` | No | Boolean | When `true`, the current leader node does not read from Amazon S3. It only reads the stream. Defaults to `false`. +`scan_mode` | No | String | Determines whether the pipeline continues to list S3 folder partitions in which no new objects are found. Valid values are `idle_optimized` and `continuous`. In `idle_optimized` mode, a folder partition in which no objects are found for 1 hour is no longer listed until a later bucket scan finds new objects in that folder. This reduces the number of S3 `ListObjectsV2` requests while the collection is idle but delays the detection of the first changes written to that folder after the idle period. In `continuous` mode, the pipeline keeps listing every folder partition, so new changes are detected sooner at the cost of more `ListObjectsV2` requests. Defaults to `idle_optimized`. +`partition_acknowledgment_timeout` | No | Duration | Configures the amount of time during which the node holds a partition. Defaults to `PT2H`. +`acknowledgments` | No | Boolean | When set to `true`, enables [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) on the source after events are sent to the sinks. Defaults to `false`. +`insecure` | No | Boolean | Disables TLS. Defaults to `false`. Do not use this value in production. +`ssl_insecure_disable_verification` | No | Boolean | Disables TLS hostname verification. Defaults to `false`. Do not enable this flag in production. Instead, use the `trust_store_file_path` to verify the hostname. + +### `authentication` + +The following parameters enable you to configure `authentication` for the Amazon DocumentDB cluster. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`username` | Yes | String | The username to use when authenticating with the Amazon DocumentDB cluster. Supports automatic refresh. +`password` | Yes | String | The password to use when authenticating with the Amazon DocumentDB cluster. Supports automatic refresh. + +### `collection` + +The following parameters enable you to configure `collection` to read from the Amazon DocumentDB cluster. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`collection` | Yes | String | The name of the collection, in the `<database>.<collection>` format. +`export` | No | Boolean | Whether to include an export or a full load. Defaults to `true`. +`stream` | No | Boolean | Whether to enable a stream. Defaults to `true`. +`partition_count` | No | Integer | Defines the number of partitions to create in Amazon S3. Defaults to `100`. +`export_batch_size` | No | Integer | Defaults to `10,000`. +`stream_batch_size` | No | Integer | Defaults to `1,000`. + +## `aws` + +The following parameters enable you to configure your access to Amazon DocumentDB. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon Simple Queue Service (Amazon SQS) and Amazon S3. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. +`sts_external_id` | No | String | An external STS ID used when Data Prepper assumes the STS role. See `ExternalID` in the [STS AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API reference documentation. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/file.md b/i18n/zh/data-prepper/pipelines/configuration/sources/file.md new file mode 100644 index 00000000..31c00f2d --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/file.md @@ -0,0 +1,205 @@ +--- +title: File +--- + +# File source + +The `file` plugin reads events from one or more local files. By default, the source reads each file once when the pipeline starts. This is useful for loading seed data, testing processors and sinks, or replaying a fixed dataset. To continuously read lines appended to files, such as application logs, set `tail` to `true`. + +The source reads files in one of the following ways, depending on its configuration: + +- If you specify `path` and none of the `paths`, `exclude_paths`, `codec`, or `tail` settings, the source reads the file once, line by line, and creates events according to the `format` and `record_type` settings. +- If you specify `paths`, `exclude_paths`, `codec`, or `tail`, the source ignores the `format` setting. When `codec` is configured, `record_type` must be set to `event`. It parses each file using the configured `codec` or, if no `codec` is configured, creates one event for each line. For the structure of these events, see [Event structure](#event-structure). + +We recommend setting `record_type` to `event` and configuring a `codec`. The `format` setting and the `string` record type are legacy settings. + +## Configuration + +The following table lists the general settings for the `file` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`path` | Conditionally | String | An absolute path to the input file inside the Data Prepper container, for example, `/usr/share/data-prepper/data/input.jsonl`. Either `path` or `paths` is required. +`paths` | Conditionally | List | A list of absolute file paths or glob patterns that specify the files to read, for example, `/var/log/app/*.log` or `/var/log/**/*.log`. Either `path` or `paths` is required. +`exclude_paths` | No | List | A list of absolute file paths or glob patterns that specify files to skip among the files matched by `paths`. +`format` | No | String | Specifies how to interpret the file content. Valid values are `json` and `plain`. Use `json` when your file has one JSON object per line or a JSON array. Use `plain` for raw text lines. Applies only when `path` is used without `paths`, `exclude_paths`, `codec`, or `tail`. This is a legacy setting; use `codec` for new configurations. Default is `plain`. +`record_type` | No | String | The type of output record produced by the source. Valid values are `event` and `string`. Use `event` to produce structured events expected by downstream processors and the OpenSearch sink. Must be set to `event` when `codec` is configured. The `string` value is a legacy setting. Default is `string`. +`codec` | No | Object | The codec used to parse the file content, for example, `ndjson`, `json`, `csv`, or `newline`. When `codec` is set, the source creates one event for each record parsed by the codec, and `record_type` must be set to `event`. For codec settings, see [codec](/data-prepper/pipelines/configuration/sources/s3#codec). +`compression` | No | String | The compression algorithm used to decompress the files. Valid values are `none`, `gzip`, `snappy`, and `zstd`. Applies only when `path` is used without `paths`, `exclude_paths`, `codec`, or `tail`, or when `codec` is set and `tail` is `false`. Default is `none`. +`encoding` | No | String | The character encoding of the files, for example, `UTF-8` or `ISO-8859-1`. Not applied when `codec` is set. Default is `UTF-8`. +`tail` | No | Boolean | When `true`, the source continuously monitors the files matched by `paths` and `path`, reads lines appended to them, and detects new, rotated, and removed files. When `false`, the source reads each file once. For more settings, see [Tail settings](#tail-settings). Default is `false`. + +Duration settings accept ISO 8601 duration notation, such as `PT30S`, or simple notation for seconds and milliseconds, such as `30s` or `500ms`. + +### File reading settings + +The following settings apply only when `paths`, `exclude_paths`, `codec`, or `tail` is configured. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`include_file_metadata` | No | Boolean | When `true`, adds the `file` object and `offset` field to each event. For more information, see [Event structure](#event-structure). Not applied when `codec` is set. Default is `true`. +`max_line_length` | No | Integer | The maximum length of a line, in characters. The source truncates longer lines to this length. Not applied when `codec` is set. Default is `1048576`. +`read_buffer_size` | No | Integer | The size of the buffer used to read from a file, in bytes. Default is `65536`. +`max_active_files` | No | Integer | The maximum number of files that the source reads at the same time. Additional matching files wait in a queue until a reader becomes available. Default is `1000`. +`reader_threads` | No | Integer | The number of threads used to read files. Default is `4` when `tail` is `true` and `1` when `tail` is `false`. +`max_read_time_per_file` | No | Duration | The maximum amount of time that a reader spends reading a file in a single pass before releasing the thread to other files. This setting also limits how long the source retries writing an event to a full buffer. If the buffer remains full for longer than this time, the event is dropped. Default is `5s`. +`fingerprint_bytes` | No | Integer | The number of bytes at the start of a file used to compute a fingerprint that identifies the file. The source uses the fingerprint only when the file system does not provide a unique file key, such as an inode. Default is `1024`. + +### Tail settings + +The following settings apply when `tail` is `true`. In tail mode, the source detects two types of file rotation: a file that is renamed and replaced by a new file at the same path, and a file that is truncated after being copied. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`start_position` | No | String | The position from which the source starts reading a file that has no checkpoint entry. Valid values are `beginning` and `end`. When set to `end`, the source skips any content that a file contains when the source first opens it, including files discovered after the pipeline starts. The `end` value is valid only when `tail` is `true`. Default is `beginning`. +`poll_interval` | No | Duration | How often the source scans `paths` for new and removed files. When the file system provides change notifications, the source uses them to detect new and removed files and scans at 10 times this interval. Default is `1s`. +`rotate_wait` | No | Duration | The amount of time that the source waits after a monitored file disappears before treating the file as removed. Default is `5s`. +`rotation_drain_timeout` | No | Duration | The maximum amount of time that the source spends reading the remaining data from a file after detecting that the file was renamed. Default is `30s`. +`close_inactive` | No | Duration | The amount of time without new data after which the source closes the reader for a file. Default is `PT30M`. +`close_removed` | No | Boolean | When `true`, the source closes the reader for a file after the file is removed. Default is `true`. + +### Checkpoint settings + +The source records the read position of each file in a checkpoint so that it can resume from that position after a restart. The following settings apply only when `paths`, `exclude_paths`, `codec`, or `tail` is configured. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`checkpoint_file` | No | String | The path to the file in which the source stores checkpoints. If not set, the source does not persist checkpoints, and after a restart it reads files according to `start_position`. +`checkpoint_interval` | No | Duration | How often the source writes checkpoints to the `checkpoint_file`. Default is `5s`. +`checkpoint_cleanup_after` | No | Duration | The amount of time after which the source removes the checkpoint entry of a completed file. A file is completed when it is fully read and `tail` is `false` or when it is removed and `tail` is `true`. Default is `P7D` (7 days). + +### Acknowledgment settings + +The following settings apply only when `paths`, `exclude_paths`, `codec`, or `tail` is configured. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`acknowledgments` | No | Boolean | When `true`, enables [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments). The source groups events from each file into batches and records the position up to which the sinks have acknowledged the events. Default is `false`. +`batch_size` | No | Integer | The maximum number of events in an acknowledgment batch. Default is `100`. +`batch_timeout` | No | Duration | The maximum amount of time that an acknowledgment batch remains open before the source completes it. Default is `5s`. +`acknowledgment_timeout` | No | Duration | The amount of time that the source waits for the sinks to acknowledge a batch. Default is `60s`. +`max_acknowledgment_retries` | No | Integer | The maximum number of consecutive negative acknowledgments for a file. After this number is exceeded, the source records the failed batch as acknowledged and continues. Default is `3`. + +## Event structure + +When `paths`, `exclude_paths`, or `tail` is configured and `codec` is not set, the source creates one event for each line. The event contains the following fields. + +Field | Description +:--- | :--- +`message` | The text of the line. +`file.path` | The absolute path of the file. Added when `include_file_metadata` is `true`. +`file.name` | The name of the file. Added when `include_file_metadata` is `true`. +`offset` | The position in the file, in bytes, at which the source started the read that contains the line. Lines read together share the same offset. Added when `include_file_metadata` is `true`. + +The following is an example event: + +```json +{ + "message": "2026-10-21T10:00:01Z [ERROR] order 1002 failed", + "file": { + "path": "/var/log/app/app.log", + "name": "app.log" + }, + "offset": 0 +} +``` + +To parse structured lines, such as JSON, use a `codec` or a processor such as [`parse_json`](/data-prepper/pipelines/configuration/processors/parse-json). + +## Examples + +The following examples demonstrate how different file types can be processed. + +### JSON file + +The following example processes a JSON file: + +```yaml +file-to-opensearch: + source: + file: + path: /usr/share/data-prepper/data/input.ndjson + format: json + record_type: event + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: file-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` + +### Plain text file + +A raw text file can be processed using the following pipeline: + +```yaml +plain-file-to-opensearch: + source: + file: + path: /usr/share/data-prepper/data/app.log + format: plain + record_type: event + processor: + - grok: + match: + message: + - '%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:msg}' + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: plain-file-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` + +### CSV file + +You can process a CSV file using the `csv` processor: + +```yaml +csv-file-to-opensearch: + source: + file: + path: /usr/share/data-prepper/data/ingest.csv + format: plain + record_type: event + processor: + - csv: + column_names: ["time","level","message"] + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: csv-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` + +### Tailing log files + +The following example continuously reads lines appended to all `.log` files in a directory, skips the debug log, and stores read positions in a checkpoint file so that the pipeline resumes from the last position after a restart: + +```yaml +tail-logs-to-opensearch: + source: + file: + paths: ["/usr/share/data-prepper/logs/*.log"] + exclude_paths: ["/usr/share/data-prepper/logs/debug.log"] + tail: true + checkpoint_file: /usr/share/data-prepper/data/file-checkpoints.json + processor: + - grok: + match: + message: + - '%{TIMESTAMP_ISO8601:timestamp} \[%{LOGLEVEL:level}\] %{GREEDYDATA:msg}' + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: tail-logs-demo + username: admin + password: "<custom-admin-password>" + insecure: true +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/http.md b/i18n/zh/data-prepper/pipelines/configuration/sources/http.md new file mode 100644 index 00000000..551c5f68 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/http.md @@ -0,0 +1,192 @@ +--- +title: HTTP +--- + +# HTTP source + +The `http` plugin accepts HTTP requests from clients. The following table describes options you can use to configure the `http` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`port` | No | Integer | The port that the source is running on. Default value is `2021`. Valid options are between `0` and `65535`. +`path` | No | String | The URI path for log ingestion should start with a forward slash (/), for example, `/${pipelineName}/logs`. The `${pipelineName}` placeholder will be replaced with the pipeline name. The default value is `/log/ingest`. +`health_check_service` | No | Boolean | Enables the health check service on the `/health` endpoint on the defined port. Default value is `false`. +`unauthenticated_health_check` | No | Boolean | Determines whether or not authentication is required on the health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default value is `false`. +`request_timeout` | No | Integer | The request timeout, in milliseconds. Default value is `10000`. +`thread_count` | No | Integer | The number of threads to keep in the ScheduledThreadPool. Default value is `200`. +`max_connection_count` | No | Integer | The maximum allowed number of open connections. Default value is `500`. +`max_pending_requests` | No | Integer | The maximum allowed number of tasks in the `ScheduledThreadPool` work queue. Default value is `1024`. +`max_request_length` | No | ByteCount | The maximum number of bytes allowed in the payload of a single HTTP request. Default value is `10mb`. +`metadata_headers` | No | List | A list of HTTP request header names. The source adds the values of these headers to the metadata of each event created from the request. Header names are case insensitive. The source stores the values in the `headers` metadata attribute as a map keyed by the lowercase header name. A header that appears multiple times in a request is stored as a list of values. For security, the source never extracts the `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `WWW-Authenticate`, `Proxy-Authenticate`, `X-Api-Key`, `X-Csrf-Token`, `X-Xsrf-Token`, `X-Auth-Token`, `X-Amz-Security-Token`, and `X-Amz-Credential` headers. Headers are not added when the pipeline uses a buffer that stores raw bytes, such as the `kafka` buffer. For an example, see [Adding request headers to event metadata](#adding-request-headers-to-event-metadata). +`compression` | No | String | The compression type applied to the client request payload. Valid values are `none` and `gzip`. Use `gzip` to apply gzip decompression to incoming requests that contain the `Content-Encoding: gzip` header. Default is `none`. +`codec` | No | Object | The codec used to parse the request body, for example, `ndjson` or `csv`. When `codec` is set, the source creates one event for each record parsed by the codec. If not set, the request body must be a JSON array. Not applied when the pipeline uses a buffer that stores raw bytes, such as the `kafka` buffer. For codec settings, see [codec](/data-prepper/pipelines/configuration/sources/s3#codec). +`authentication` | No | Object | An authentication configuration. By default, this creates an unauthenticated server for the pipeline. This uses pluggable authentication for HTTPS. To use basic authentication define the `http_basic` plugin with a `username` and `password`. To provide customer authentication, use or create a plugin that implements [ArmeriaHttpAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/1.2.0/data-prepper-plugins/armeria-common/src/main/java/com/amazon/dataprepper/armeria/authentication/ArmeriaHttpAuthenticationProvider.java). +`ssl` | No | Boolean | Enables TLS/SSL. Default value is `false`. +`ssl_certificate_file` | Conditionally | String | The SSL certificate chain file path or Amazon Simple Storage Service (Amazon S3) path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true` and `use_acm_certificate_for_ssl` is set to `false`. +`ssl_key_file` | Conditionally | String | The SSL key file path or Amazon S3 path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true` and `use_acm_certificate_for_ssl` is set to `false`. +`use_acm_certificate_for_ssl` | No | Boolean | Enables TLS/SSL using the certificate and private key from AWS Certificate Manager (ACM). Default is `false`. +`acm_certificate_arn` | Conditionally | String | The ACM certificate Amazon Resource Name (ARN). The ACM certificate takes preference over Amazon S3 or a local file system certificate. Required if `use_acm_certificate_for_ssl` is set to true. +`acm_private_key_password` | No | String | ACM private key password that decrypts the private key. If not provided, Data Prepper generates a random password. +`acm_certificate_timeout_millis` | No | Integer | Timeout, in milliseconds, that ACM takes to get certificates. Default value is 120000. +`aws_region` | Conditionally | String | AWS region used by ACM or Amazon S3. Required if `use_acm_certificate_for_ssl` is set to true or `ssl_certificate_file` and `ssl_key_file` is the Amazon S3 path. + +<!--- ## Configuration + +Content will be added to this section.---> + +## Ingestion + +Clients should send HTTP `POST` requests to the endpoint `/log/ingest`. + +By default, the `http` source accepts JSON UTF-8 request bodies containing an array of objects, for example, `[{"key1": "value1"}, {"key2": "value2"}]`. To accept other formats, configure a `codec`. + +## Example + +The following examples demonstrate different configurations that can be used with the `http` source. + +### Minimal HTTP source + +The following is the minimal configuration using all default values: + +```yaml +minimal-http-pipeline: + source: + http: + sink: + - stdout: {} +``` + +You can test this pipeline using the following command: + +```bash +curl -s "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + --data '[{"msg":"one"},{"msg":"two"}]' +``` + +You should see the following output in the Data Prepper logs: + +``` +{"msg":"one"} +{"msg":"two"} +``` + +### Custom path using the pipeline name and health check + +The following example uses a custom path, configures a custom port, and enables health checks: + +```yaml +audit-pipeline: + source: + http: + port: 2022 + path: "/${pipelineName}/logs" # -> /audit-pipeline/logs + health_check_service: true + unauthenticated_health_check: true + sink: + - stdout: {} +``` + +You can use the following command to check the pipeline health: + +```bash +curl -s "http://localhost:2022/health" +``` + +You can ingest data using the following command: + +```bash +curl -s "http://localhost:2022/audit-pipeline/logs" \ + -H "Content-Type: application/json" \ + --data '[{"event":"login","user":"alice"}]' +``` + +### Basic authentication on the source + +The following example configures a custom port and path, enables health checks, and configures basic authentication: + +```yaml +secure-intake-pipeline: + source: + http: + port: 2023 + path: /ingest + authentication: + http_basic: + username: ingest + password: s3cr3t + health_check_service: true + unauthenticated_health_check: true + sink: + - stdout: {} + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-%{yyyy.MM.dd} +``` + +You can test this pipeline using the following command: + +```bash +curl -s -u ingest:s3cr3t "http://localhost:2023/ingest" \ + -H "Content-Type: application/json" \ + --data '[{"service":"web","status":"ok"}]' +``` + +### Adding request headers to event metadata + +The following example adds the `X-Tenant-Id` request header to the metadata of each event and then copies the header value into the `tenant` field using the `add_entries` processor. To read a single header, use the `headers/<lowercase-header-name>` metadata key: + +```yaml +tenant-pipeline: + source: + http: + metadata_headers: ["X-Tenant-Id"] + processor: + - add_entries: + entries: + - key: tenant + value_expression: 'getMetadata("headers/x-tenant-id")' + sink: + - stdout: {} +``` + +You can test this pipeline using the following command: + +```bash +curl -s "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -H "X-Tenant-Id: store-eu" \ + --data '[{"order":"1001"}]' +``` + +You should see the following output in the Data Prepper logs: + +``` +{"order":"1001","tenant":"store-eu"} +``` + +## Metrics + +The `http` source includes the following metrics. + +### Counters + +- `requestsReceived`: Measures the total number of requests received by the `/log/ingest` endpoint. +- `requestsRejected`: Measures the total number of requests rejected (429 response status code) by the HTTP Source plugin. +- `successRequests`: Measures the total number of requests successfully processed (200 response status code) the by HTTP Source plugin. +- `badRequests`: Measures the total number of requests with either an invalid content type or format processed by the HTTP Source plugin (400 response status code). +- `requestTimeouts`: Measures the total number of requests that time out in the HTTP source server (415 response status code). +- `requestsTooLarge`: Measures the total number of requests where the size of the event is larger than the buffer capacity (413 response status code). +- `internalServerError`: Measures the total number of requests processed by the HTTP Source with a custom exception type (500 response status code). + +### Timers + +- `requestProcessDuration`: Measures the latency of requests processed by the HTTP Source plugin in seconds. + +### Distribution summaries + +- `payloadSize`: Measures the incoming request payload size in bytes. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/iceberg.md b/i18n/zh/data-prepper/pipelines/configuration/sources/iceberg.md new file mode 100644 index 00000000..89b6296b --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/iceberg.md @@ -0,0 +1,200 @@ +--- +title: Iceberg +--- + +# Iceberg source + +::: danger WARNING +This is an experimental feature and is not recommended for use in a production environment. For updates on the progress of the feature or if you want to leave feedback, see the associated [GitHub issue](https://github.com/opensearch-project/data-prepper/issues/6552). +::: + +The `iceberg` source provides change data capture (CDC) on [Apache Iceberg](https://iceberg.apache.org/) tables. It polls for new Iceberg snapshots and detects `INSERT`, `UPDATE`, and `DELETE` operations by computing changes between snapshots using the [`IncrementalChangelogScan`](https://iceberg.apache.org/javadoc/latest/org/apache/iceberg/IncrementalChangelogScan.html) API. + +The source supports the following: +- Iceberg table format v1, v2, and v3. +- Copy-on-Write (CoW) tables only. Merge-on-Read (MoR) tables are not supported. +- Parquet, Avro, and ORC file formats. +- Any Iceberg catalog implementation, including AWS Glue Data Catalog, Hive Metastore, and REST catalogs. + +The source includes two ingestion modes: + +1. **Export**: An initial snapshot load that reads the current state of the table. +2. **Stream**: Polls for new snapshots and processes incremental changelog events. + +## Prerequisites + +To use the Iceberg source, you must enable the experimental `iceberg` plugin in `data-prepper-config.yaml`: + +```yaml +experimental: + enabled_plugins: + source: + - iceberg +``` + +## Usage + +The following example pipeline specifies an `iceberg` source. It reads incremental changes from an Iceberg table using a REST catalog with Amazon S3 storage. The `catalog` is defined at the top level so that all tables share the same catalog configuration. + +In the sink configuration, `action` is set to `${getMetadata("bulk_action")}` so that `INSERT` and `UPDATE` operations upsert the document while `DELETE` operations remove it. The `document_id` is set to `${getMetadata("document_id")}`, which concatenates the `identifier_columns` values using a `|` separator so that each Iceberg row maps to a unique OpenSearch document: + +```yaml +version: "2" +iceberg-cdc-pipeline: + source: + iceberg: + catalog: + type: rest + uri: "http://iceberg-rest-catalog:8181" + io-impl: "org.apache.iceberg.aws.s3.S3FileIO" + client.region: "us-east-1" + tables: + - table_name: "my_database.my_table" + identifier_columns: ["id"] + polling_interval: "PT30S" + acknowledgments: true + sink: + - opensearch: + hosts: ["https://localhost:9200"] + index: "my-index" + action: "${getMetadata(\"bulk_action\")}" + document_id: "${getMetadata(\"document_id\")}" +``` + +To use a different catalog for a specific table, specify `catalog` at the table level to override the top-level definition: + +```yaml +iceberg: + catalog: + type: rest + uri: "http://iceberg-rest-catalog:8181" + io-impl: "org.apache.iceberg.aws.s3.S3FileIO" + tables: + - table_name: "db.table_a" + identifier_columns: ["id"] + - table_name: "db.table_b" + identifier_columns: ["id"] + catalog: + type: glue + warehouse: "s3://other-bucket/warehouse" + io-impl: "org.apache.iceberg.aws.s3.S3FileIO" +``` + +## Configuration options + +The `iceberg` source supports the following configuration options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`catalog` | No | Map | Default catalog properties applied to all tables. When a table specifies its own `catalog`, the table-level definition fully replaces the top-level one. For common properties, see [catalog](#catalog). +`tables` | Yes | List | A list of Iceberg table configurations. For supported options, see [tables](#tables). +`polling_interval` | No | Duration | How often the leader node polls for new snapshots. Supports [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) duration notation such as `PT30S` or `PT5M`. Default is `PT30S`. +`acknowledgments` | No | Boolean | When `true`, enables [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments). Default is `true`. +`shuffle` | No | Object | Configuration for the distributed shuffle used when processing snapshots with `DELETE` operations. For supported options, see [shuffle](#shuffle). + +<!-- vale off --> +### tables +<!-- vale on --> + +Use the following options for each table entry. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`table_name` | Yes | String | The fully qualified Iceberg table name (for example, `my_database.my_table`). +`catalog` | No | Map | A map of Apache Iceberg catalog properties. When specified, fully replaces the top-level `catalog`. For common properties, see [catalog](#catalog). +`identifier_columns` | No | List | A list of column names used as the document identifier for `UPDATE` and `DELETE` detection. Required when processing tables with `UPDATE` or `DELETE` operations. If not specified, the source cannot determine document IDs or correctly detect updates. +`disable_export` | No | Boolean | When `true`, skips the initial snapshot export and starts with CDC only. Default is `false`. + +<!-- vale off --> +### catalog +<!-- vale on --> + +The `catalog` option accepts any property supported by the Apache Iceberg catalog implementation. For the full list of available properties, see the documentation for each catalog type, such as the [REST catalog](https://iceberg.apache.org/rest-catalog-spec/), [AWS Glue](https://iceberg.apache.org/docs/latest/aws/#glue-catalog), or [Hive Metastore](https://iceberg.apache.org/docs/latest/hive/#global-hive-catalog). The following table lists the common properties. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`type` | Yes | String | The catalog type. Supported values include `glue`, `hive`, `rest`, and other Iceberg catalog implementations. +`io-impl` | No | String | The FileIO implementation class. For example, `org.apache.iceberg.aws.s3.S3FileIO` for Amazon S3 or `org.apache.iceberg.hadoop.HadoopFileIO` for HDFS. When not specified, each catalog uses its own default (REST catalogs use `ResolvingFileIO`, which is selected automatically based on file path scheme, Glue uses `S3FileIO`, Hadoop and JDBC use `HadoopFileIO`). + +For AWS-specific catalog and S3 properties, see the [Apache Iceberg AWS integration documentation](https://iceberg.apache.org/docs/latest/aws/). + +<!-- vale off --> +### shuffle +<!-- vale on --> + +When processing snapshots that contain `DELETE` operations (`UPDATE` or `DELETE` in Copy-on-Write tables), the source uses a distributed shuffle to ensure correct results across multiple nodes. The shuffle routes all records containing the same `identifier_columns` values to the same node so that matching `INSERT` and `DELETE` pairs can be resolved correctly. + +The shuffle activates automatically when a snapshot contains `DELETE` operations. For `INSERT`-only snapshots, the shuffle is not used. + +The following table lists the `shuffle` configuration options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`partitions` | No | Integer | The number of hash partitions. Must be 1--10,000. Default is `64`. +`target_partition_size` | No | String | The target size for coalesced shuffle read tasks. Small adjacent partitions are merged to reduce the number of tasks. Default is `64mb`. +`storage_path` | No | String | The local directory for intermediate shuffle files. Default is `${data-prepper.dir}/data/shuffle` when `data-prepper.dir` is set, otherwise `${java.io.tmpdir}/data-prepper-shuffle`. +`port` | No | Integer | The port for the HTTP server used for node-to-node shuffle data transfer. Default is `4995`. +`ssl` | No | Boolean | When `true`, enables Transport Layer Security (TLS) for the shuffle HTTP server. Default is `true`. +`ssl_certificate_file` | Conditionally | String | The path to the TLS certificate file in PEM format. Supports local file paths and Amazon S3 URIs (for example, `s3://my-bucket/certs/cert.pem`). Required when `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. +`ssl_key_file` | Conditionally | String | The path to the TLS private key file in PEM format. Supports local file paths and Amazon S3 URIs (for example, `s3://my-bucket/certs/key.pem`). Required when `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. +`use_acm_certificate_for_ssl` | No | Boolean | When `true`, uses AWS Certificate Manager (ACM) for TLS certificates instead of `ssl_certificate_file` and `ssl_key_file`. Default is `false`. +`acm_certificate_arn` | Conditionally | String | The ACM certificate ARN. Required when `use_acm_certificate_for_ssl` is `true`. +`acm_private_key_password` | No | String | The password used to decrypt the private key exported from ACM. If not provided, Data Prepper generates a random password. +`acm_certificate_timeout_millis` | No | Integer | The maximum amount of time, in milliseconds, that Data Prepper waits to retrieve the certificate from ACM. Default is `120000`. +`aws_region` | Conditionally | String | The AWS Region for ACM or S3 certificate access. Required when `use_acm_certificate_for_ssl` is `true` or when certificate files are in Amazon S3. +`ssl_client_auth` | No | Boolean | When `true`, enables mutual TLS (mTLS) for node-to-node authentication. All nodes must present a valid client certificate during shuffle communication. Default is `false`. +`ssl_insecure_disable_verification` | No | Boolean | When `true`, disables TLS certificate verification for node-to-node shuffle communication. Default is `false`. + +::: info NOTE +When running multiple Data Prepper nodes, each node must be able to reach the other nodes on the configured `port`. +::: + +## Exposed metadata attributes + +The following metadata attributes are added to each event processed by the `iceberg` source. These attributes can be accessed using the [expression syntax `getMetadata` function](/data-prepper/pipelines/get-metadata): + +- `bulk_action`: The recommended bulk action for the OpenSearch sink. Set to `index` for `INSERT` and `UPDATE` operations, or `delete` for `DELETE` operations. +- `document_id`: The document identifier, composed by joining the `identifier_columns` values with a `|` separator. Only set when `identifier_columns` is configured. +- `iceberg_operation`: The CDC operation type. Set to `INSERT` or `DELETE`. When a row is updated in Iceberg, the source receives a `DELETE` and `INSERT` pair with the same `identifier_columns` values. The source recognizes this as an update and emits only the `INSERT` event, because upserting by `document_id` produces the correct result without a separate delete. +- `iceberg_table_name`: The name of the source Iceberg table. +- `iceberg_snapshot_id`: The snapshot ID from which the event originated. + +## Permissions + +The required permissions depend on the catalog type and storage backend. The following is an example of the minimum IAM permissions when using AWS Glue Data Catalog and Amazon S3: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "allowReadingFromS3", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:ListBucket", + "s3:GetBucketLocation" + ], + "Resource": [ + "arn:aws:s3:::my-iceberg-bucket", + "arn:aws:s3:::my-iceberg-bucket/*" + ] + }, + { + "Sid": "allowGlueCatalogAccess", + "Effect": "Allow", + "Action": [ + "glue:GetTable", + "glue:GetTables", + "glue:GetDatabase", + "glue:GetDatabases" + ], + "Resource": [ + "arn:aws:glue:region:account-id:catalog", + "arn:aws:glue:region:account-id:database/*", + "arn:aws:glue:region:account-id:table/*/*" + ] + } + ] +} +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/kinesis.md b/i18n/zh/data-prepper/pipelines/configuration/sources/kinesis.md new file mode 100644 index 00000000..43dba088 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/kinesis.md @@ -0,0 +1,193 @@ +--- +title: Kinesis +--- + +# Kinesis source + +You can use the OpenSearch Data Prepper `kinesis` source to ingest records from one or more [Amazon Kinesis Data Streams](https://aws.amazon.com/kinesis/data-streams/). + +## Usage + +The following example pipeline specifies Kinesis as a source. The pipeline ingests data from multiple Kinesis data streams named `stream1` and `stream2` and sets the `initial_position` to indicate the starting point for reading the stream records: + +```yaml +version: "2" +kinesis-pipeline: + source: + kinesis: + streams: + - stream_name: "stream1" + initial_position: "LATEST" + - stream_name: "stream2" + initial_position: "LATEST" + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-iam-role" +``` + +## Configuration options + +The `kinesis` source supports the following configuration options. + +Option | Required | Type | Description +:--- |:---------|:---------| :--- +`aws` | Yes | AWS | Specifies the AWS configuration. See [`aws`](#aws). +`acknowledgments` | No | Boolean | When set to `true`, enables the `kinesis` source to receive [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `false`. +`streams` | Yes | List | Configures a list of multiple Kinesis data streams that the `kinesis` source uses to read records. You can configure up to four streams. See [Streams](#streams). +`codec` | Yes | Codec | Specifies the [codec](#codec) to apply. +`buffer_timeout` | No | Duration | Sets the amount of time allowed for writing events to the Data Prepper buffer before timeout occurs. Any events that the source cannot write to the buffer during the specified amount of time are discarded. Default is `1s`. +`records_to_accumulate` | No | Integer | Determines the number of messages that accumulate before being written to the buffer. Default is `100`. +`consumer_strategy` | No | String | Selects the consumer strategy to use for ingesting Kinesis data streams. The default is `fan-out`, but `polling` can also be used. If `polling` is enabled, the additional configuration is required. +`polling` | No | polling | See [polling](#polling). +`max_initialization_attempts` | No | Integer | The maximum number of attempts to initialize the Kinesis consumer before the source stops retrying. Default is `2147483647`. +`initialization_backoff_time` | No | Duration | The amount of time to wait between attempts to initialize the Kinesis consumer. Default is `1s`. + +### Streams + +You can use the following options in the `streams` array. + +Option | Required | Type | Description +:--- |:---------| :--- | :--- +`stream_name` | No | String | Defines the name of each Kinesis data stream. Either `stream_name` or `stream_arn` is required. +`stream_arn` | No | String | The Amazon Resource Name (ARN) of the Kinesis data stream. If both `stream_name` and `stream_arn` are specified, `stream_arn` is used. +`consumer_arn` | No | String | The ARN of the enhanced fan-out consumer to use for the stream. Applies only when `stream_arn` is specified and `consumer_strategy` is `fan-out`. If not specified, the source uses the stream consumer named after the pipeline. +`initial_position` | No | String | Sets the `initial_position` to control where the `kinesis` source begins reading stream records. Use `LATEST` to start from the most recent record, `EARLIEST` to read from the beginning of the stream, or `AT_TIMESTAMP` to start from a specific timestamp. Default is `LATEST`. +`initial_timestamp`| No | String | Specifies the timestamp from which to begin reading stream records. The value must follow the [ISO LocalDateTime](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) format and be provided in the UTC time zone (for example, `2023-01-23T10:00:00`). When `initial_position` is set to `AT_TIMESTAMP`, you must specify either `initial_timestamp` or `range`. +`range` | No | String | Specifies how far back from the current time to begin reading Kinesis data stream records. Supports ISO-8601 duration strings (such as `PT20.345S` or `PT15M`) as well as shorthand notation for seconds (`60s`) and milliseconds (`1600ms`). For example, `PT12H` starts reading records from 12 hours before the pipeline started. When `initial_position` is set to `AT_TIMESTAMP`, you must specify either `initial_timestamp` or `range`. + +`checkpoint_interval` | No | Duration | Configure the `checkpoint_interval` to periodically checkpoint Kinesis data streams and avoid duplication of record processing. Default is `PT2M`. +`compression` | No | String | Specifies the compression format. To decompress records added by a [CloudWatch Logs Subscription Filter](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html) to Kinesis, use the `gzip` compression format. + +<!-- vale off --> +## codec +<!-- vale on --> + +The `codec` determines how the `kinesis` source parses each Kinesis stream record. For increased and more efficient performance, you can use [codec combinations](/data-prepper/common-use-cases/codec-processor-combinations) with certain processors. + +<!-- vale off --> +### json codec +<!-- vale on --> + +The `json` codec parses each single line as a single JSON object from a JSON array and then creates a Data Prepper event for each object in the array. It can be used for parsing nested CloudWatch events into individual log entries. +It also supports the following configuration to use with this codec. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`key_name` | No | String | The name of the input field from which to extract the JSON array and create Data Prepper events. +`include_keys` | No | List | The list of input fields to be extracted and added as additional fields in the Data Prepper event. +`include_keys_metadata` | No | List | The list of input fields to be extracted and added to the Data Prepper event metadata object. +`max_event_length` | No | Integer | The maximum size of any single event being read by the JSON codec. Default is 20,000,000 characters. + +### `newline` codec + +The `newline` codec parses each Kinesis stream record as a single log event, making it ideal for processing single-line records. It also works well with the [`parse_json` processor](/data-prepper/pipelines/configuration/processors/parse-json) to parse each line. + +You can use the following options to configure the `newline` codec. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`skip_lines` | No | Integer | Sets the number of lines to skip before creating events. You can use this configuration to skip common header rows. Default is `0`. +`header_destination` | No | String | Defines a key value to assign to the header line of the stream event. If this option is specified, then each event will contain a `header_destination` field. + +### `otel_traces` codec + +The `otel_traces` codec parses each Kinesis data stream record as an OpenTelemetry trace record and creates a Data Prepper span event for each span record. + +You can use the following options to configure the `otel_traces` codec. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`format` | No | String | Specifies the format of the OpenTelemetry traces. Valid values are `json` and `protobuf`. Default is `json`. +`otel_format` | No | String | Specifies the output format of the decoded spans. Valid values are `opensearch` and `otel`. Default is `opensearch`. +`length_prefixed_encoding` | No | Boolean | Specifies whether the length precedes the data in protobuf format. Default is `false`. + +<!-- vale off --> +### polling +<!-- vale on --> + +When the `consumer_strategy` is set to `polling`, the `kinesis` source uses a polling-based approach to read records from the Kinesis data streams, instead of the default `fan-out` approach. + +Option | Required | Type | Description +:--- | :--- |:--------| :--- +`max_polling_records` | No | Integer | Sets the number of records to fetch from Kinesis during a single call. Default is `10000`. +`idle_time_between_reads` | No | Duration | Defines the amount of idle time between calls. Default is `250ms`. + +<!-- vale off --> +### aws +<!-- vale on --> + +You can use the following options in the `aws` configuration. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | Sets the AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | Defines the AWS Security Token Service (AWS STS) role to assume for requests to Amazon Kinesis Data Streams and Amazon DynamoDB. Defaults to `null`, which uses the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | Defines the external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | Defines a map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. + +## Exposed metadata attributes + +The `kinesis` source adds the following metadata to each processed event. You can access the metadata attributes using the [expression syntax `getMetadata` function](/data-prepper/pipelines/get-metadata). + +- `stream_name`: Contains the name of the Kinesis data stream from which the event was obtained. + +## Permissions + +The following minimum permissions are required in order to run `kinesis` as a source: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "kinesis:DescribeStream", + "kinesis:DescribeStreamConsumer", + "kinesis:DescribeStreamSummary", + "kinesis:GetRecords", + "kinesis:GetShardIterator", + "kinesis:ListShards", + "kinesis:ListStreams", + "kinesis:ListStreamConsumers", + "kinesis:RegisterStreamConsumer", + "kinesis:SubscribeToShard" + ], + "Resource": [ + "arn:aws:kinesis:us-east-1:{account-id}:stream/stream1", + "arn:aws:kinesis:us-east-1:{account-id}:stream/stream2" + ] + }, + { + "Sid": "allowCreateTable", + "Effect": "Allow", + "Action": [ + "dynamodb:CreateTable", + "dynamodb:PutItem", + "dynamodb:DescribeTable", + "dynamodb:DeleteItem", + "dynamodb:GetItem", + "dynamodb:Scan", + "dynamodb:UpdateItem", + "dynamodb:Query" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:{account-id}:table/kinesis-pipeline" + ] + } + ] +} +``` + +The `kinesis` source uses a DynamoDB table for ingestion coordination among multiple workers, so you need DynamoDB permissions. + +## Metrics + +The `kinesis` source includes the following metrics. + +### Counters + +* `recordsProcessed`: Counts the number of processed stream records. +* `recordProcessingErrors`: Counts the number of stream record processing errors. +* `acknowledgementSetSuccesses`: Counts the number of processed stream records that were successfully added to the sink. +* `acknowledgementSetFailures`: Counts the number of processed stream records that failed to be added to the sink. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/opensearch-api.md b/i18n/zh/data-prepper/pipelines/configuration/sources/opensearch-api.md new file mode 100644 index 00000000..562b7bf4 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/opensearch-api.md @@ -0,0 +1,242 @@ +--- +title: OpenSearch API +--- + +# OpenSearch API source + +The `opensearch_api` source accepts HTTP requests compatible with the [OpenSearch Bulk API](/api-reference/document-apis/bulk). Standard OpenSearch clients like [Apache Flink OpenSearch Connector](https://nightlies.apache.org/flink/flink-docs-stable/docs/connectors/datastream/opensearch/), Logstash, and [`opensearch-py`](/clients/python-low-level) can send data to Data Prepper through this source. + +Unlike the OpenSearch Bulk API, this source writes asynchronously. Events are buffered for downstream processing rather than written directly to OpenSearch. When the `zero` buffer is used, events pass directly to the sink. Regardless of buffer type, the response is synthetic and does not reflect actual indexing results from OpenSearch. + +## Usage + +The `opensearch_api` source supports the following endpoints: + +```json +POST /{path}/_bulk +POST /{path}/{index}/_bulk +``` + +## Configuration + +The following table lists the configuration options for the `opensearch_api` source. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| `port` | Integer | No | `9200` | The port the source listens on. Must be 0--65535. | +| `path` | String | No | `/` | The URI path for the endpoint. Must start with `/`. Supports the `${pipelineName}` placeholder. | +| `request_timeout` | Integer | No | `10000` | The request timeout, in milliseconds. | +| `thread_count` | Integer | No | `200` | The number of threads in the scheduled thread pool. | +| `max_connection_count` | Integer | No | `500` | The maximum number of open connections. | +| `max_pending_requests` | Integer | No | `1024` | The maximum number of tasks in the work queue. | +| `max_request_length` | ByteCount | No | `10mb` | The maximum number of bytes allowed in the payload of a single HTTP request, for example, `5mb`. Requests that exceed this size are rejected with a `413` status code. | +| `health_check_service` | Boolean | No | `false` | Enables a `/health` endpoint on the configured port. | +| `unauthenticated_health_check` | Boolean | No | `false` | If `true`, the health endpoint does not require authentication. | +| `compression` | String | No | `none` | The compression applied to the request payload. Valid values are `none` and `gzip`. | +| `authentication` | Object | No | Unauthenticated | The authentication configuration. See [Authentication](#authentication). | +| `ssl` | Boolean | No | `false` | Enables TLS/SSL. | +| `ssl_certificate_file` | String | Conditional | — | The path to the SSL certificate file. Required if `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. Supports Amazon Simple Storage Service (Amazon S3) paths (`s3://bucket/path`). | +| `ssl_key_file` | String | Conditional | — | The path to the SSL key file (decrypted). Required if `ssl` is `true` and `use_acm_certificate_for_ssl` is `false`. Supports Amazon S3 paths. | +| `use_acm_certificate_for_ssl` | Boolean | No | `false` | When `true`, uses AWS Certificate Manager (ACM) for TLS certificates. | +| `acm_certificate_arn` | String | Conditional | — | The ACM certificate Amazon Resource Name (ARN). Required if `use_acm_certificate_for_ssl` is `true`. | +| `acm_private_key_password` | String | No | Random | The password to decrypt the ACM private key. | +| `acm_certificate_timeout_millis` | Integer | No | `120000` | The timeout for ACM certificate retrieval, in milliseconds. | +| `aws_region` | String | Conditional | — | The AWS Region for ACM or Amazon S3 certificate access. | + +## Authentication + +By default, the source runs without authentication. To make this explicit in your configuration, use the `unauthenticated` key: + +```yaml +source: + opensearch_api: + authentication: + unauthenticated: +``` + +### HTTP basic authentication + +The following example configures HTTP basic authentication with a username and password: + +```yaml +source: + opensearch_api: + authentication: + http_basic: + username: my-user + password: my_s3cr3t +``` + +### Custom authentication + +To provide custom authentication, create a plugin that implements the [`ArmeriaHttpAuthenticationProvider`](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/armeria-common/src/main/java/org/opensearch/dataprepper/armeria/authentication/ArmeriaHttpAuthenticationProvider.java) interface. + +## Event metadata attributes + +For each action in the bulk request, the source creates a Data Prepper event with the following metadata attributes. + +| Attribute | Description | Example | +|-----------|-------------|---------| +| `opensearch_action` | The bulk action type | `index`, `create`, `update`, `delete` | +| `opensearch_index` | Target index name | `my-index` | +| `opensearch_id` | Document ID (if provided) | `doc-123` | +| `opensearch_routing` | Routing value (if provided) | `user-456` | +| `opensearch_pipeline` | Ingest pipeline (if provided) | `my-pipeline` | + +You can reference these attributes in processors and sinks using the `getMetadata` method or `${metadata_key}` syntax. + +## Response format + +On success, the source returns a JSON response with an empty `items` array: + +```json +{ + "took": 5, + "errors": false, + "items": [] +} +``` + +The following table lists the response fields. + +| Field | Description | +|-------|-------------| +| `took` | The actual processing time, measured from request receipt to buffer write completion, in milliseconds. | +| `errors` | Indicates whether any errors occurred. Always `false` when all data is successfully written to the buffer. | +| `items` | Always an empty array. Because Data Prepper buffers documents for downstream processing rather than indexing them directly, per-item results are not available at request time. | + +## Response status codes + +The following table lists the possible response status codes. + +| Status | Description | +|--------|-------------| +| `200` | Request data successfully written to the buffer. | +| `400` | Request data is malformed or uses an unsupported format. | +| `408` | Request timed out writing to the buffer. | +| `413` | Request payload exceeds the configured buffer capacity or the `max_request_length` value. | +| `429` | Source is at full capacity; request rejected. | + +## Buffer compatibility + +The `opensearch_api` source works with the following buffer types. + +| Buffer | Supported | Notes | +|--------|-----------|-------| +| [`bounded_blocking`](/data-prepper/pipelines/configuration/buffers/bounded-blocking) | Yes | Default. Events are stored in an in-memory blocking queue. | +| [`kafka`](/data-prepper/pipelines/configuration/buffers/kafka) | Yes | Requires Data Prepper 2.x. Events are serialized to Apache Kafka and reconstructed on the consumer side. | +| `zero` | Yes | Events pass directly to the sink with no buffering. | + +## Metrics + +The `opensearch_api` source emits the following metrics. + +### Counters + +The following table lists the counter metrics. + +| Metric | Description | +|--------|-------------| +| `requestsReceived` | The total number of requests received by the endpoint. | +| `successRequests` | The total number of requests successfully processed (200). | +| `badRequests` | The total number of requests with invalid format (400). | +| `requestTimeouts` | The total number of requests that timed out (408). | +| `requestsTooLarge` | The total number of requests exceeding buffer capacity (413). | +| `requestsRejected` | The total number of requests rejected due to full capacity (429). | +| `internalServerError` | The total number of requests with internal errors (500). | + +### Timer + +The following table lists the timer metric. + +| Metric | Description | +|--------|-------------| +| `requestProcessDuration` | The request processing latency, in seconds. | + +### Distribution summary + +The following table lists the distribution summary metric. + +| Metric | Description | +|--------|-------------| +| `payloadSize` | The distribution of incoming request payload sizes, in bytes. | + +## Examples + +The following examples demonstrate common configurations for the `opensearch_api` source. + +### Basic pipeline with an OpenSearch sink + +The following example configures a pipeline that receives bulk requests and writes events to an OpenSearch sink using metadata attributes: + +```yaml +opensearch-pipeline: + source: + opensearch_api: + port: 9202 + path: "/opensearch" + sink: + - opensearch: + hosts: ["https://opensearch-node:9200"] + index: "${getMetadata(\"opensearch_index\")}" + document_id: "${getMetadata(\"opensearch_id\")}" + routing: "${getMetadata(\"opensearch_routing\")}" + action: "${getMetadata(\"opensearch_action\")}" +``` + +### SSL enabled + +The following example enables SSL with HTTP basic authentication: + +```yaml +opensearch-pipeline: + source: + opensearch_api: + port: 9202 + ssl: true + ssl_certificate_file: "/certs/server.crt" + ssl_key_file: "/certs/server.key" + authentication: + http_basic: + username: admin + password: admin + sink: + - opensearch: + hosts: ["https://opensearch-node:9200"] + index: "${getMetadata(\"opensearch_index\")}" + action: "${getMetadata(\"opensearch_action\")}" +``` + +### Sending data using cURL + +The following example sends a bulk request to the `opensearch_api` source using cURL: + +```bash +curl -XPOST "http://localhost:9202/opensearch/_bulk" \ + -H "Content-Type: application/json" \ + -d '{"index":{"_index":"movies","_id":"1"}} +{"title":"Rush","year":2013} +{"delete":{"_index":"movies","_id":"2"}} +' +``` + +<!-- vale off --> +### Sending data using opensearch-py +<!-- vale on --> + +The following example sends a bulk request using the `opensearch-py` client: + +```python +from opensearchpy import OpenSearch + +client = OpenSearch( + hosts=[{"host": "localhost", "port": 9202}], + use_ssl=False, + url_prefix="/opensearch" +) + +client.bulk(body=[ + {"index": {"_index": "movies", "_id": "1"}}, + {"title": "Rush", "year": 2013}, +]) +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/otel-trace-source.md b/i18n/zh/data-prepper/pipelines/configuration/sources/otel-trace-source.md new file mode 100644 index 00000000..38ab58e4 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/otel-trace-source.md @@ -0,0 +1,201 @@ +--- +title: OTel trace +--- + +# OTel trace source + +The `otel_trace_source` is a source for the OpenTelemetry Collector. The following table describes options you can use to configure the `otel_trace_source` source. + +## Configuration + +You can configure the `otel_trace_source` source with the following options. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`port` | No | Integer | The port that the `otel_trace_source` source runs on. Default value is `21890`. +`request_timeout` | No | Integer | The request timeout, in milliseconds. Default value is `10000`. +`health_check_service` | No | Boolean | Enables a gRPC health check service under `grpc.health.v1/Health/Check`. Default value is `false`. +`unauthenticated_health_check` | No | Boolean | Determines whether or not authentication is required on the health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default value is `false`. +`proto_reflection_service` | No | Boolean | Enables a reflection service for Protobuf services (see [gRPC reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md) and [gRPC Server Reflection Tutorial](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md) docs). Default value is `false`. +`unframed_requests` | No | Boolean | Enable requests not framed using the gRPC wire protocol. +`thread_count` | No | Integer | The number of threads to keep in the ScheduledThreadPool. Default value is `200`. +`max_connection_count` | No | Integer | The maximum allowed number of open connections. Default value is `500`. +`max_connection_age` | No | Duration | The maximum amount of time that a client connection can remain open. When a connection reaches this age, the source closes it gracefully, and the client must open a new connection. Use this setting when multiple Data Prepper nodes run behind DNS-based load balancing: gRPC clients resolve DNS only when they open a connection, so closing connections periodically allows clients to connect to newly added nodes. Must be between 1 second and 24 hours. By default, connections have no maximum age. +`connection_drain_duration` | No | Duration | The amount of time that the source waits for in-flight requests to complete when it gracefully closes a connection, for example, after the connection reaches the `max_connection_age`. Must be between 0 seconds and 1 hour. +| `output_format` | String | Specifies the output format of the generated events. Valid values are `otel` or `opensearch`. Default is `opensearch`. | +`max_request_length` | No | ByteCount | The maximum number of bytes allowed in the payload of a single gRPC or HTTP request. Default value is `10mb`. +`path` | No | String | A custom path for the traces export service, for example, `/v1/traces`. Must start with `/`. When set, the source receives gRPC and unframed requests at this path, and the default `/opentelemetry.proto.collector.trace.v1.TraceService/Export` path is disabled. The path can contain a `${pipelineName}` placeholder, which is replaced with the pipeline name. +`compression` | No | String | The compression type applied to the client request payload. Valid values are `none` and `gzip`. Use `gzip` to apply gzip decompression to the incoming request. Default is `none`. +`retry_info` | No | Object | Configures the retry delay that the source returns to clients in `RESOURCE_EXHAUSTED` responses, for example, when the buffer is full or a request times out. Supports the `min_delay` (default `100ms`) and `max_delay` (default `2s`) options. The suggested delay starts at `min_delay` and doubles with each consecutive rejection, up to `max_delay`. +`ssl` | No | Boolean | Enables connections to the OTel source port over TLS/SSL. Defaults to `true`. +sslKeyCertChainFile | Conditionally | String | File system path or Amazon Simple Storage Service (Amazon S3) path to the security certificate (for example, `"config/demo-data-prepper.crt"` or `"s3://my-secrets-bucket/demo-data-prepper.crt"`). Required if `ssl` is set to `true`. +`sslKeyFile` | Conditionally | String | File system path or Amazon S3 path to the security key (for example, `"config/demo-data-prepper.key"` or `"s3://my-secrets-bucket/demo-data-prepper.key"`). Required if `ssl` is set to `true`. +`useAcmCertForSSL` | No | Boolean | Whether to enable TLS/SSL using a certificate and private key from AWS Certificate Manager (ACM). Default value is `false`. +`acmCertificateArn` | Conditionally | String | Represents the ACM certificate ARN. ACM certificate take preference over S3 or local file system certificate. Required if `useAcmCertForSSL` is set to `true`. +`acmPrivateKeyPassword` | No | String | The password used to decrypt the private key exported from ACM. If not provided, Data Prepper generates a random password. +`acmCertIssueTimeOutMillis` | No | Integer | The maximum amount of time, in milliseconds, that Data Prepper waits to retrieve the certificate from ACM. Default value is `120000`. +`awsRegion` | Conditionally | String | Represents the AWS region used by ACM or Amazon S3. Required if `useAcmCertForSSL` is set to `true` or `sslKeyCertChainFile` and `sslKeyFile` are Amazon S3 paths. +`authentication` | No | Object | An authentication configuration. By default, an unauthenticated server is created for the pipeline. This parameter uses pluggable authentication for HTTPS. To use basic authentication, define the `http_basic` plugin with a `username` and `password`. To provide customer authentication, use or create a plugin that implements [GrpcAuthenticationProvider](https://github.com/opensearch-project/data-prepper/blob/1.2.0/data-prepper-plugins/armeria-common/src/main/java/com/amazon/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). + +## Usage + +To use the `otel-metrics` source, create the following `pipeline.yaml` file with `otel_metrics_source` as the source: + +```yaml +source: + otel_trace_source: +``` + +If you want to use the OpenTelemetry format for your output, set the `output_format` to `otel`, as shown in the following example: + +```yaml +source: + otel_trace_source: + output_format: otel +``` + +## Example + +The following example shows Data Prepper ingesting OTLP traces over HTTPS using a PEM certificate and key with unframed HTTP at a custom path, accepting gzip-compressed payloads, preserving OpenTelemetry document structure, and indexing them into OpenSearch: + +```yaml +otel-traces-https: + source: + otel_trace_source: + ssl: true + sslKeyFile: /usr/share/data-prepper/certs/dp-key.pem + sslKeyCertChainFile: /usr/share/data-prepper/certs/dp-cert.pem + unframed_requests: true + path: /ingest/${pipelineName}/v1/traces + compression: gzip + output_format: otel + request_timeout: 15000 + health_check_service: true + proto_reflection_service: true + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: otel-traces-https + username: admin + password: "<custom-admin-password>" + insecure: true +``` + +You can test the pipeline using the following command: + +```bash +cat > /tmp/otel-trace3.json <<'JSON' +{ + "resourceSpans": [{ + "resource": {"attributes":[ + {"key":"service.name","value":{"stringValue":"billing"}}, + {"key":"service.version","value":{"stringValue":"2.1.0"}} + ]}, + "scopeSpans": [{ + "scope": {"name":"manual-https"}, + "spans": [{ + "traceId": "1234567890abcdef1234567890abcdef", + "spanId": "feedfacecafebeef", + "name": "PUT /invoice/42", + "startTimeUnixNano": "1739999999000000000", + "endTimeUnixNano": "1740000000000000000", + "attributes": [ + {"key":"region","value":{"stringValue":"eu-west-1"}}, + {"key":"retry.count","value":{"intValue":"1"}} + ] + }] + }] + }] +} +JSON + +gzip -c /tmp/otel-trace3.json > /tmp/otel-trace3.json.gz + +curl -s -X POST "https://localhost:21890/ingest/otel-traces-https/v1/traces" \ + -H 'Content-Type: application/json' \ + -H 'Content-Encoding: gzip' \ + --insecure \ + --data-binary @/tmp/otel-trace3.json.gz +``` + +The document stored in OpenSearch contains the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "otel-traces-https", + "_id": "V_5RBpoBqZ1V_u-TvYXf", + "_score": 1, + "_source": { + "traceId": "d76df8e7aefcf7469b71d79fd76df8e7aefcf7469b71d79f", + "droppedLinksCount": 0, + "instrumentationScope": { + "name": "manual-https", + "droppedAttributesCount": 0 + }, + "resource": { + "schemaUrl": "", + "attributes": { + "service.name": "billing", + "service.version": "2.1.0" + }, + "droppedAttributesCount": 0 + }, + "kind": "SPAN_KIND_UNSPECIFIED", + "droppedEventsCount": 0, + "flags": 0, + "parentSpanId": "", + "schemaUrl": "", + "spanId": "7de79d7da71e71a7de6de79f", + "traceState": "", + "name": "PUT /invoice/42", + "startTime": "2025-02-19T21:19:59Z", + "attributes": { + "retry.count": 1, + "region": "eu-west-1" + }, + "links": [], + "endTime": "2025-02-19T21:20:00Z", + "droppedAttributesCount": 0, + "durationInNanos": 1000000000, + "events": [], + "status": { + "code": 0, + "message": "" + } + } + } + ] + } +} +``` + +## Metrics + +The `otel_trace_source` source includes the following metrics. + +### Counters + +- `requestTimeouts`: Measures the total number of requests that time out. +- `requestsRejectedByCircuitBreaker`: Measures the total number of requests rejected because the [circuit breaker](/data-prepper/managing-data-prepper/configuring-data-prepper#circuit-breakers) is open. These requests are rejected before the request body is read and are not counted in `requestTimeouts`. +- `requestsReceived`: Measures the total number of requests received by the `otel_trace` source. +- `successRequests`: Measures the total number of requests successfully processed by the `otel_trace` source plugin. +- `badRequests`: Measures the total number of requests with an invalid format processed by the `otel_trace` source plugin. +- `requestsTooLarge`: Measures the total number of requests whose number of spans exceeds the buffer capacity. +- `internalServerError`: Measures the total number of requests processed by the `otel_trace` source with a custom exception type. + +### Timers + +- `requestProcessDuration`: Measures the latency of requests processed by the `otel_trace` source plugin in seconds. + +### Distribution summaries + +- `payloadSize`: Measures the incoming request payload size distribution in bytes. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/otlp-source.md b/i18n/zh/data-prepper/pipelines/configuration/sources/otlp-source.md new file mode 100644 index 00000000..d81b3e70 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/otlp-source.md @@ -0,0 +1,330 @@ +--- +title: OTLP +--- + +# OTLP source + +The `otlp` source is a unified OpenTelemetry source that follows the [OpenTelemetry Protocol (OTLP) specification](https://opentelemetry.io/docs/specs/otlp/) and can receive logs, metrics, and traces through a single endpoint. This source consolidates the functionality of the individual `otel_logs_source`, `otel_metrics_source`, and `otel_trace_source` sources, providing a streamlined approach to ingesting all OpenTelemetry telemetry signals. + +::: info NOTE +The `otlp` source supports both the `OTLP/gRPC` and `OTLP/HTTP` protocols. For `OTLP/HTTP`, only Protobuf encoding is supported. This makes it compatible with a wide range of OpenTelemetry collectors and instrumentation libraries. +::: + +## Configuration + +You can configure the `otlp` source with the following options. + +| Option | Type | Description | +| :--- | :--- | :--- | +| `port` | Integer | The port on which the `otlp` source listens. Default is `21893`. | +| `logs_path` | String | The path for sending unframed HTTP requests for logs. Must start with `/` and have a minimum length of 1. Default is `/opentelemetry.proto.collector.logs.v1.LogsService/Export`. | +| `metrics_path` | String | The path for sending unframed HTTP requests for metrics. Must start with `/` and have a minimum length of 1. Default is `/opentelemetry.proto.collector.metrics.v1.MetricsService/Export`. | +| `traces_path` | String | The path for sending unframed HTTP requests for traces. Must start with `/` and have a minimum length of 1. Default is `/opentelemetry.proto.collector.trace.v1.TraceService/Export`. | +| `request_timeout` | Duration | The request timeout duration. Default is `10s`. | +| `retry_info` | Object | Configures retry behavior. Supports `min_delay` (default `100ms`) and `max_delay` (default `2s`) parameters to control exponential backoff. See [Retry configuration](#retry-configuration).| +| `health_check_service` | Boolean | Enables a gRPC health check service under `grpc.health.v1.Health/Check`. When `unframed_requests` is `true`, enables HTTP health check at `/health`. Default is `false`. | +| `unauthenticated_health_check` | Boolean | Determines whether or not authentication is required on the HTTP health check endpoint. OpenSearch Data Prepper ignores this option if no authentication is defined. Default is `false`. | +| `proto_reflection_service` | Boolean | Enables a reflection service for Protobuf services (see [ProtoReflectionService](https://grpc.github.io/grpc-java/javadoc/io/grpc/protobuf/services/ProtoReflectionService.html) and [gRPC reflection](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md)). Default is `false`. | +| `unframed_requests` | Boolean | Enables requests not framed using the gRPC wire protocol. Default is `false`. | +| `thread_count` | Integer | The number of threads to keep in the scheduled thread pool. Default is `200`. | +| `max_connection_count` | Integer | The maximum allowed number of open connections. Default is `500`. | +| `max_connection_age` | Duration | The maximum amount of time that a client connection can remain open. When a connection reaches this age, the source closes it gracefully, and the client must open a new connection. Use this setting when multiple Data Prepper nodes run behind DNS-based load balancing: gRPC clients resolve DNS only when they open a connection, so closing connections periodically allows clients to connect to newly added nodes. Must be between 1 second and 24 hours. By default, connections have no maximum age. | +| `connection_drain_duration` | Duration | The amount of time that the source waits for in-flight requests to complete when it gracefully closes a connection, for example, after the connection reaches the `max_connection_age`. Must be between 0 seconds and 1 hour. | +| `max_request_length` | String | The maximum number of bytes allowed in the payload of a single gRPC or HTTP request. Default is `10mb`. | +| `compression` | String | The compression type applied to the client request payload. Valid values are `none` (no compression) or `gzip` (apply `gzip` decompression). Default is `none`. | +| `authentication` | Object | The authentication configuration. By default, the source runs without authentication. See [Authentication configuration](#authentication-configuration). | +| `output_format` | String | Specifies the decoded output format for all signals (logs, metrics, and traces) if individual output format options are not set. Valid values are `otel` (OpenTelemetry format) and `opensearch` (OpenSearch format). Default is `otel`. | +| `logs_output_format` | String | Specifies the decoded output format specifically for logs. Takes precedence over `output_format` for logs. Valid values are `otel` and `opensearch`. Default is `otel`. | +| `metrics_output_format` | String | Specifies the decoded output format specifically for metrics. Takes precedence over `output_format` for metrics. Valid values are `otel` and `opensearch`. Default is `otel`. | +| `traces_output_format` | String | Specifies the decoded output format specifically for traces. Takes precedence over `output_format` for traces. Valid values are `otel` and `opensearch`. Default is `otel`. | + +::: info NOTE +If an individual output format (for example, `logs_output_format`) is set, it takes precedence over the generic `output_format` for that signal type. If neither is set, the default is `otel`. +::: + +### SSL/TLS configuration + +You can configure SSL/TLS in the `otlp` source with the following options. + +| Option | Type | Description | +| :--- | :--- | :--- | +| `ssl` | Boolean | Enables SSL/TLS. Default is `true`. | +| `ssl_certificate_file` | String | The SSL certificate chain file path or Amazon Simple Storage Service (Amazon S3) path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true`. | +| `ssl_key_file` | String | The SSL key file path or Amazon S3 path (for example, `s3://<bucketName>/<path>`). Required if `ssl` is set to `true`. | +| `use_acm_certificate_for_ssl` | Boolean | Enables SSL/TLS using a certificate and private key from AWS Certificate Manager (ACM). Default is `false`. | +| `acm_certificate_arn` | String | The ACM certificate Amazon Resource Name (ARN). ACM certificates take precedence over Amazon S3 or local file system certificates. Required if `use_acm_certificate_for_ssl` is set to `true`. | +| `acm_private_key_password` | String | The ACM private key password that decrypts the private key. If not provided, OpenSearch Data Prepper generates a random password. | +| `acm_certificate_timeout` | Duration | The maximum amount of time that Data Prepper waits to retrieve the certificate from ACM. Must be between `5s` and `3600s`. Default is `120s`. | +| `aws_region` | String | The AWS Region used by ACM or Amazon S3. Required if `use_acm_certificate_for_ssl` is set to `true` or if `ssl_certificate_file` and `ssl_key_file` are Amazon S3 paths. | + +### Authentication configuration + +By default, the `otlp` source runs without authentication. You can configure authentication using the following options. + +To explicitly disable authentication, specify the following settings: + +```yaml +source: + otlp: + authentication: + unauthenticated: +``` + +To enable HTTP Basic authentication, specify the following settings: + +```yaml +source: + otlp: + authentication: + http_basic: + username: my-user + password: my_s3cr3t +``` + +This plugin uses pluggable authentication for gRPC servers. To provide custom authentication, create a plugin that implements [`GrpcAuthenticationProvider`](https://github.com/opensearch-project/data-prepper/blob/main/data-prepper-plugins/armeria-common/src/main/java/org/opensearch/dataprepper/armeria/authentication/GrpcAuthenticationProvider.java). + +### Retry configuration + +To configure retry behavior, use the `retry_info` setting. The setting specifies the amount of time to wait before the next request when backpressure occurs, including when the [circuit breaker](/data-prepper/managing-data-prepper/configuring-data-prepper#circuit-breakers) is open. The retry mechanism applies exponential backoff with a configurable maximum delay: + +```yaml +source: + otlp: + retry_info: + min_delay: 100ms # defaults to 100ms + max_delay: 2s # defaults to 2s +``` + +## Usage + +The following examples demonstrate how to configure and use the `otlp` source in various scenarios. + +### Basic configuration + +To get started with the `otlp` source, create a `pipeline.yaml` file with the following minimal configuration: + +```yaml +pipeline: + source: + otlp: + ssl: false + sink: + - stdout: +``` + +### Routing telemetry signals + +One of the key features of the `otlp` source is its ability to route different telemetry signals (logs, metrics, and traces) to different processors or sinks based on your specific needs. Routing is determined by metadata using the `getEventType()` function: + +```yaml +version: "2" +otel-telemetry: + source: + otlp: + ssl: false + route: + - traces: 'getEventType() == "TRACE"' + - logs: 'getEventType() == "LOG"' + - metrics: 'getEventType() == "METRIC"' + sink: + - opensearch: + routes: + - logs + hosts: [ "https://opensearch:9200" ] + index: logs-%{yyyy.MM.dd} + username: admin + password: "<custom-admin-password>" + insecure: true + - pipeline: + name: traces-raw + routes: + - traces + - pipeline: + name: otel-metrics + routes: + - metrics + +traces-raw: + source: + pipeline: + name: otel-telemetry + processor: + - otel_trace_raw: + sink: + - opensearch: + hosts: [ "https://opensearch:9200" ] + index_type: trace-analytics-raw + username: admin + password: "<custom-admin-password>" + insecure: true + +otel-metrics: + source: + pipeline: + name: otel-telemetry + processor: + - otel_metrics: + calculate_histogram_buckets: true + calculate_exponential_histogram_buckets: true + exponential_histogram_max_allowed_scale: 10 + flatten_attributes: false + sink: + - opensearch: + hosts: [ "https://opensearch:9200" ] + index: metrics-otel-%{yyyy.MM.dd} + username: admin + password: "<custom-admin-password>" + insecure: true +``` + +### Using OpenSearch output format + +To generate data in the OpenSearch format for all telemetry signals, specify the following settings: + +```yaml +source: + otlp: + output_format: opensearch +``` + +To use different output formats for different signal types, specify the following settings: + +```yaml +source: + otlp: + logs_output_format: opensearch + metrics_output_format: otel + traces_output_format: opensearch +``` + +### Configuring with SSL/TLS + +To enable SSL/TLS with local certificates, specify the following settings: + +```yaml +source: + otlp: + ssl: true + ssl_certificate_file: "/path/to/certificate.crt" + ssl_key_file: "/path/to/private-key.key" +``` + +To use the ACM, specify the following settings: + +```yaml +source: + otlp: + ssl: true + use_acm_certificate_for_ssl: true + acm_certificate_arn: "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012" + aws_region: "us-east-1" +``` + +## Metrics + +The `otlp` source includes the following metrics for monitoring its performance and health. + +### Counters + +The following counters track request activity and errors in the `otlp` source. + +| Metric | Description | +| :--- | :--- | +| `requestTimeouts` | The total number of requests that timed out. | +| `requestsRejectedByCircuitBreaker` | The total number of requests rejected because the [circuit breaker](/data-prepper/managing-data-prepper/configuring-data-prepper#circuit-breakers) is open. These requests are rejected before the request body is read and are not counted in `requestTimeouts`. | +| `requestsReceived` | The total number of requests received by the `otlp` source. | +| `successRequests` | The total number of requests successfully processed by the `otlp` source. | +| `badRequests` | The total number of requests with an invalid format processed by the `otlp` source. | +| `requestsTooLarge` | The total number of requests that exceed the maximum allowed size. | +| `internalServerError` | The total number of requests processed by the `otlp` source with custom exception types. | + +### Timers + +The following timers track request activity and errors in the `otlp` source. + +| Metric | Description | +| :--- | :--- | +| `requestProcessDuration` | The latency of requests processed by the `otlp` source, in seconds. | + +### Distribution summaries + +The following distribution summaries track request activity and errors in the `otlp` source. + +| Metric | Description | +| :--- | :--- | +| `payloadSize` | The distribution of incoming request payload sizes, in bytes. | + +## Migrating from individual OpenTelemetry sources + +If you're using separate `otel_logs_source`, `otel_metrics_source`, or `otel_trace_source` sources, you can migrate to the unified `otlp` source by following these steps: + +1. Replace all three sources with a single `otlp` source. +2. Use [routing configuration](#routing-telemetry-signals) to direct different signal types to their appropriate pipelines. +3. Change the port numbers if needed (the `otlp` source uses port `21893` by default). + +### Migration example + +The following example demonstrates how to consolidate separate OpenTelemetry log, metric, and trace sources into a single `otlp` source. + +Consider a setup where logs, metrics, and traces are configured separately: + +```yaml +logs-pipeline: + source: + otel_logs_source: + port: 21892 + sink: + - opensearch: + index: logs +``` +```yaml +metrics-pipeline: + source: + otel_metrics_source: + port: 21891 + sink: + - opensearch: + index: metrics +``` +```yaml +traces-pipeline: + source: + otel_trace_source: + port: 21890 + sink: + - opensearch: + index: traces +``` + +You can consolidate logs, metrics, and traces into a single `otlp` source as follows: + +```yaml +otlp-pipeline: + source: + otlp: + port: 21893 + route: + - logs: 'getEventType() == "LOG"' + - metrics: 'getEventType() == "METRIC"' + - traces: 'getEventType() == "TRACE"' + sink: + - opensearch: + routes: + - logs + index: logs + - opensearch: + routes: + - metrics + index: metrics + - opensearch: + routes: + - traces + index: traces +``` + +## Related documentation + +- [OTel logs source](/data-prepper/pipelines/configuration/sources/otel-logs-source) +- [OTel metrics source](/data-prepper/pipelines/configuration/sources/otel-metrics-source) +- [OTel trace source](/data-prepper/pipelines/configuration/sources/otel-trace-source) +- [getEventType()](/data-prepper/pipelines/get-eventtype) diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/pipeline.md b/i18n/zh/data-prepper/pipelines/configuration/sources/pipeline.md new file mode 100644 index 00000000..8881703a --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/pipeline.md @@ -0,0 +1,26 @@ +--- +title: Pipeline +--- + +# Pipeline source + +Use the `pipeline` sink to read from another pipeline. + +## Configuration + +The `pipeline` source supports the following configuration options. + +| Option | Required | Type | Description | +|:-------|:---------|:-------|:---------------------------------------| +| `name` | Yes | String | The name of the pipeline to read from. | + +## Usage + +The following example configures a `pipeline` sink named `sample-pipeline` that reads from a pipeline named `movies`: + +```yaml +sample-pipeline: + source: + - pipeline: + name: "movies" +``` diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/rds.md b/i18n/zh/data-prepper/pipelines/configuration/sources/rds.md new file mode 100644 index 00000000..0da82db9 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/rds.md @@ -0,0 +1,329 @@ +--- +title: RDS +--- + +# RDS source + +The `rds` source enables change data capture (CDC) on [Amazon Relational Database Service (Amazon RDS)](https://aws.amazon.com/rds/) and [Amazon Aurora](https://aws.amazon.com/aurora/) databases. It can receive database events, such as `INSERT`, `UPDATE`, or `DELETE`, using database replication logs and supports initial load using RDS exports to Amazon Simple Storage Service (Amazon S3). + +The source supports the following database engines: +- Aurora MySQL and Aurora PostgreSQL +- RDS MySQL and RDS PostgreSQL + +The source includes two ingestion options for ingesting data from Aurora/RDS: + +1. Export: A full initial export from Aurora/RDS to S3 gets an initial load of the current state of the Aurora/RDS database. +2. Stream: Stream events from database replication logs (MySQL `binlog` or PostgreSQL WAL). + +## Usage + +The following example pipeline specifies an `rds` source. It ingests data from an Aurora MySQL cluster: + +```yaml +version: "2" +rds-pipeline: + source: + rds: + db_identifier: "my-rds-instance" + engine: "aurora-mysql" + database: "mydb" + authentication: + username: "myuser" + password: "mypassword" + s3_bucket: "my-export-bucket" + s3_region: "us-west-2" + s3_prefix: "rds-exports" + export: + kms_key_id: "arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012" + export_role_arn: "arn:aws:iam::123456789012:role/rds-export-role" + stream: true + aws: + region: "us-west-2" + sts_role_arn: "arn:aws:iam::123456789012:role/my-pipeline-role" +``` + +## Configuration options + +The following tables describe the configuration options for the `rds` source. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`db_identifier` | Yes | String | The identifier for the RDS instance or Aurora cluster. +`cluster` | No | Boolean | Whether the `db_identifier` refers to a cluster (`true`) or an instance (`false`). Default is `false`. For Aurora engines, this option is always `true`. +`engine` | Yes | String | The database engine type. Must be one of `mysql`, `postgresql`, `aurora-mysql`, or `aurora-postgresql`. +`database` | Yes | String | The name of the database to connect to. +`tables` | No | Object | The configuration for specifying which tables to include or exclude. See [tables](#tables) for more information. +`authentication` | Yes | Object | Database authentication credentials. See [authentication](#authentication) for more information. +`aws` | Yes | Object | The AWS configuration. See [`aws`](#aws) for more information. +`acknowledgments` | No | Boolean | When `true`, enables the source to receive [end-to-end acknowledgments](/data-prepper/pipelines/pipelines#end-to-end-acknowledgments) when events are received by OpenSearch sinks. Default is `true`. +`s3_data_file_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from an RDS export expires when used with acknowledgments. Default is 30 minutes. +`stream_acknowledgment_timeout` | No | Duration | The amount of time that elapses before the data read from database streams expires when used with acknowledgments. Default is 10 minutes. +`s3_bucket` | Yes | String | The name of the S3 bucket in which RDS export data will be stored. +`s3_prefix` | No | String | The prefix for S3 objects in the export bucket. +`s3_region` | No | String | The AWS Region for the S3 bucket. If not specified, uses the same Region as specified in the [`aws`](#aws) configuration. +`partition_count` | No | Integer | The number of folder partitions in the S3 buffer. Must be between 1 and 1,000. Default is 100. +`export` | No | Object | The configuration for RDS export operations. See [export](#export-options) for more information. +`stream` | No | Boolean | Whether to enable streaming of database change events. Default is `false`. +`tls` | No | Object | The TLS configuration for database connections. See [`tls`](#tls-options) for more information. +`disable_s3_read_for_leader` | No | Boolean | Whether to disable S3 read operations for the leader node. Default is `false`. +`scan_mode` | No | String | Determines whether the pipeline continues to list S3 buffer folder partitions in which no new objects are found. Valid values are `idle_optimized` and `continuous`. In `idle_optimized` mode, a folder partition in which no objects are found for 1 hour is no longer listed until a later bucket scan finds new objects in that folder. This reduces the number of S3 `ListObjectsV2` requests while the database is idle but delays the detection of the first changes written to that folder after the idle period. In `continuous` mode, the pipeline keeps listing every folder partition, so new changes are detected sooner at the cost of more `ListObjectsV2` requests. Default is `idle_optimized`. +`empty_scan_delay` | No | Duration | The minimum amount of time to wait before listing an S3 buffer folder partition again after a listing returns no objects. A longer delay reduces the number of S3 `ListObjectsV2` requests when the database receives changes infrequently but can delay the processing of new changes by up to the configured amount. Must be between 0 seconds and 30 minutes. Default is `0s`, which lists an empty folder partition again without waiting. +`joins` | No | Object | The configuration for combining rows from related tables into a single OpenSearch document. See [joins](#joins) for more information. + +<!-- vale off --> +### aws +<!-- vale on --> + +Use the following options in the AWS configuration. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`region` | No | String | The AWS Region to use for credentials. Defaults to the [standard SDK behavior for determining the Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/region-selection.html). +`sts_role_arn` | No | String | The AWS Security Token Service (AWS STS) role to assume for requests to Amazon RDS and Amazon S3. Defaults to `null`, which will use the [standard SDK behavior for credentials](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). +`sts_external_id` | No | String | The external ID to use when assuming the STS role. Must be between 2 and 1,224 characters. +`sts_header_overrides` | No | Map | A map of header overrides that the AWS Identity and Access Management (IAM) role assumes for the source plugin. Maximum of 5 headers. + +<!-- vale off --> +### authentication +<!-- vale on --> + +Use the following options for database authentication. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`username` | Yes | String | The database username for authentication. +`password` | Yes | String | The database password for authentication. + +<!-- vale off --> +### tables +<!-- vale on --> + +Use the following options to specify which tables to include in the data capture. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`include` | No | List | A list of table names to include in data capture. Maximum of 1,000 tables. If specified, only these tables will be processed. +`exclude` | No | List | A list of table names to exclude from data capture. Maximum of 1,000 tables. These tables will be ignored even if they match include patterns. + +<!-- vale off --> +### export options +<!-- vale on --> + +The following options let you customize the RDS export functionality. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`kms_key_id` | Yes | String | The AWS Key Management Service (AWS KMS) key ID or Amazon Resource Name (ARN) to use for encrypting the export data. +`export_role_arn` | Yes | String | The ARN of the IAM role that RDS will assume to perform the export operation. + +<!-- vale off --> +### tls options +<!-- vale on --> + +The following options let you configure TLS for database connections. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`insecure` | No | Boolean | Whether to disable TLS encryption for database connections. Default is `false` (TLS enabled). + +<!-- vale off --> +### joins +<!-- vale on --> + +Use the `joins` configuration to combine each parent table row and its related child table rows into one OpenSearch document. When `joins` is configured, Data Prepper updates the `opensearch` sink to use the `upsert` action with a script that merges events from the parent and child tables. The document ID is the value of the parent key. Parent and child table names are specified without the database name. + +Changes to a parent row update the fields of its document, and deleting a parent row deletes the document. Child rows are added to the document as follows: + +- For `one_to_many` relations, each child row is stored as an object in an array field named after the child table. +- For `one_to_one` relations, the child row's fields are added to the root of the document. + +The following options are available in the `joins` configuration. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`relations` | No | List | A list of parent-child table relations. See [relations](#relations) for more information. +`version_field` | No | String | The name of the document field that stores the latest version applied to the document from each table. Data Prepper uses this field to skip events that are older than the stored version. Default is `__versions`. + +<!-- vale off --> +#### relations +<!-- vale on --> + +Use the following options in each entry of the `relations` list. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`parent` | Yes | String | The name of the parent table. +`child` | Yes | String | The name of the child table. +`parent_key` | Yes | String or list | The column or columns in the parent table that identify the parent row. The parent key value is used as the document ID. For composite keys, values are concatenated using a `\|` separator. +`child_key` | Yes | String or list | The column or columns in the child table that reference the parent row. Must contain the same number of columns as `parent_key`. +`child_primary_key` | Yes | String or list | The primary key column or columns of the child table. Used to identify each child row in the document. +`join_type` | No | String | The type of relation between the parent and child tables. Valid values are `one_to_many` and `one_to_one`. Default is `one_to_many`. +`max_child_records` | No | Integer | The maximum number of child rows stored in the array of a `one_to_many` relation. When a new child row exceeds this limit, the oldest child row is removed from the array. Default is `1000`. + +The following example combines rows from the `order_items` table into the `orders` documents: + +```yaml +rds-pipeline: + source: + rds: + db_identifier: "my-rds-instance" + engine: "aurora-mysql" + database: "mydb" + ... + joins: + relations: + - parent: "orders" + child: "order_items" + parent_key: "order_id" + child_key: "order_id" + child_primary_key: "item_id" + join_type: "one_to_many" + max_child_records: 500 +``` + +## Exposed metadata attributes + +The following metadata will be added to each event that is processed by the `rds` source. These metadata attributes can be accessed using the [expression syntax `getMetadata` function](/data-prepper/pipelines/get-metadata). + +* `primary_key`: The primary key of the database record. For tables with composite primary keys, values are concatenated with a `|` separator. +* `event_timestamp`: The timestamp, in epoch milliseconds, of when the database change occurred. For export events, this represents the export time. For stream events, this represents the transaction commit time. +* `document_version`: A long integer number generated from the event timestamp to use as the document version. +* `opensearch_action`: The bulk action that will be used to send the event to OpenSearch, such as `index` or `delete`. +* `change_event_type`: The stream event type. Can be `insert`, `update`, or `delete`. +* `table_name`: The name of the database table from which the event originated. +* `schema_name`: The name of the schema from which the event originated. For MySQL, `schema_name` is the same as `database_name`. +* `database_name`: The name of the database from which the event originated. +* `ingestion_type`: Indicates whether the event originated from an export or stream. Valid values are `EXPORT` and `STREAM`. +* `s3_partition_key`: Events are stored in an S3 staging bucket before processing. This metadata indicates the location in the S3 bucket where the event is stored before processing. + +## Permissions + +The following are the required permissions for running RDS as a source: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "allowReadingFromS3Buckets", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:DeleteObject", + "s3:GetBucketLocation", + "s3:ListBucket", + "s3:PutObject" + ], + "Resource": [ + "arn:aws:s3:::s3_bucket", + "arn:aws:s3:::s3_bucket/*" + ] + }, + { + "Sid": "AllowDescribeInstances", + "Effect": "Allow", + "Action": [ + "rds:DescribeDBInstances" + ], + "Resource": [ + "arn:aws:rds:region:account-id:db:*" + ] + }, + { + "Sid": "AllowDescribeClusters", + "Effect": "Allow", + "Action": [ + "rds:DescribeDBClusters" + ], + "Resource": [ + "arn:aws:rds:region:account-id:cluster:*" + ] + }, + { + "Sid": "AllowSnapshots", + "Effect": "Allow", + "Action": [ + "rds:DescribeDBClusterSnapshots", + "rds:CreateDBClusterSnapshot", + "rds:DescribeDBSnapshots", + "rds:CreateDBSnapshot", + "rds:AddTagsToResource" + ], + "Resource": [ + "arn:aws:rds:region:account-id:cluster:*", + "arn:aws:rds:region:account-id:cluster-snapshot:*", + "arn:aws:rds:region:account-id:db:*", + "arn:aws:rds:region:account-id:snapshot:*" + ] + }, + { + "Sid": "AllowExport", + "Effect": "Allow", + "Action": [ + "rds:StartExportTask" + ], + "Resource": [ + "arn:aws:rds:region:account-id:cluster:*", + "arn:aws:rds:region:account-id:cluster-snapshot:*", + "arn:aws:rds:region:account-id:snapshot:*" + ] + }, + { + "Sid": "AllowDescribeExports", + "Effect": "Allow", + "Action": [ + "rds:DescribeExportTasks" + ], + "Resource": "*" + }, + { + "Sid": "AllowAccessToKmsForExport", + "Effect": "Allow", + "Action": [ + "kms:Decrypt", + "kms:Encrypt", + "kms:DescribeKey", + "kms:RetireGrant", + "kms:CreateGrant", + "kms:ReEncrypt*", + "kms:GenerateDataKey*" + ], + "Resource": [ + "arn:aws:kms:region:account-id:key/export-key-id" + ] + }, + { + "Sid": "AllowPassingExportRole", + "Effect": "Allow", + "Action": "iam:PassRole", + "Resource": [ + "arn:aws:iam::account-id:role/export-role" + ] + } + ] +} +``` + +## Metrics + +The `rds` source includes the following metrics: + +* `exportJobSuccess`: The number of RDS export tasks that have succeeded. +* `exportJobFailure`: The number of RDS export tasks that have failed. +* `exportS3ObjectsTotal`: The total number of export data files found in S3. +* `exportS3ObjectsProcessed`: The total number of export data files that have been processed successfully from S3. +* `exportS3ObjectsErrors`: The total number of export data files that have failed to be processed from S3. +* `exportRecordsTotal`: The total number of records found in the export. +* `exportRecordsProcessed`: The total number of export records that have been processed successfully. +* `exportRecordsProcessingErrors`: The number of export record processing errors. +* `changeEventsProcessed`: The number of change events processed from database streams. +* `changeEventsProcessingErrors`: The number of processing errors for change events from database streams. +* `bytesReceived`: The total number of bytes received by the source. +* `bytesProcessed`: The total number of bytes processed by the source. +* `positiveAcknowledgementSets`: The number of acknowledgment sets that are positively acknowledged in stream processing. +* `negativeAcknowledgementSets`: The number of acknowledgment sets that are negatively acknowledged in stream processing. +* `checkpointCount`: The total number of checkpoints in stream processing. +* `noDataExtendLeaseCount`: The number of times that the lease is extended on a partition with no new data processed since the last checkpoint. +* `giveupPartitionCount`: The number of times a partition is given up. +* `replicationLogEntryProcessingTime`: The time taken to process a replication log event. +* `replicationLogEntryProcessingErrors`: The number of replication log events that have failed to process. diff --git a/i18n/zh/data-prepper/pipelines/configuration/sources/rss.md b/i18n/zh/data-prepper/pipelines/configuration/sources/rss.md new file mode 100644 index 00000000..fcbcc801 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/configuration/sources/rss.md @@ -0,0 +1,119 @@ +--- +title: RSS +--- + +# RSS source + +The `rss` source polls one or more RSS or Atom feeds and converts their items into OpenSearch Data Prepper events. Each feed is polled on a schedule, and new items are written to the [`buffer`](/data-prepper/pipelines/configuration/buffers/buffers). + +Each feed keeps a bounded in-memory cache of recently seen items, so already ingested items are not re-emitted on subsequent polls. This cache is not persisted, so it resets when Data Prepper restarts. + +## Usage + +Provide one or more feeds under the `feeds` map, which is keyed by feed name. Each feed requires a `url` and can optionally set a per-feed `polling_frequency` and `authentication`. The following example pipeline specifies an `rss` source that polls three feeds. Enclose the `password` value in quotation marks when it contains characters that YAML treats as syntax, such as `:` or `#`: + +```yaml +rss-pipeline: + source: + rss: + workers: 2 + polling_frequency: PT5M + feeds: + opensearch-forum: + url: https://forum.opensearch.org/latest.rss + example-news: + url: https://api.example.com/v2/rss?partnerKey=abc123 + polling_frequency: PT1M + internal: + url: https://private.example.com/feed.xml + authentication: + basic: + username: my-username + password: "p@ss:w0rd#123!" +``` + +You can avoid storing plaintext credentials in your pipeline configuration by referencing them from a configured secret store. To use AWS Secrets Manager as a secret store, configure the [`aws` extension](/data-prepper/managing-data-prepper/configuring-data-prepper#aws-extension-plugin). Then specify `${{aws_secrets:<secret-config-id>:<key>}}` as the `password` value. Data Prepper resolves the reference at startup. For more information, see [Reference secrets](/data-prepper/managing-data-prepper/configuring-data-prepper#reference-secrets). + +## Configuration options + +Use the following options to configure the `rss` source. All duration values support ISO 8601 notation (such as `PT15M` or `PT20.345S`) and simple notation for seconds (`60s`) and milliseconds (`1500ms`). + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`feeds` | Yes | Map | A non-empty map of feeds to poll. Each key is the feed name, which is attached to events as `feed_name` and can be used for index routing. Feed names must be 1--64 characters long and can contain only letters, digits, underscores, and hyphens. Each value is a feed configuration. For more information, see [Feed options](#feed-options). +`polling_frequency` | No | Duration | The default polling frequency for feeds that do not set their own. Must be at least 1 second. Default is `PT5M` (5 minutes). +`workers` | No | Integer | The size of the polling thread pool. Must be between 1 and 1,000. The pool never contains more threads than the number of configured feeds. Default is `1`. +`request_timeout` | No | Duration | The connection, request, and read timeout applied to each feed fetch. This timeout prevents a slow or unresponsive feed from blocking its worker thread indefinitely. Default is `PT30S` (30 seconds). + +### Feed options + +Use the following options for each entry in the `feeds` map. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`url` | Yes | String | The RSS or Atom feed URL to read from. +`polling_frequency` | No | Duration | Overrides the top-level `polling_frequency` for this feed. Must be at least 1 second. +`authentication` | No | Object | The authentication configuration for the feed. For more information, see [Authentication](#authentication). + +### Authentication + +Use the following option in a feed's `authentication` object to configure HTTP basic authentication. + +Option | Required | Type | Description +:--- | :--- | :--- | :--- +`basic` | No | Object | The HTTP basic authentication credentials. Contains a `username` and a `password`, both of which are required when `basic` is specified. + +## Event schema + +The source emits each item as an event of type `rss-item` that contains the following top-level body fields. + +Field | Description +:--- | :--- +`title` | The item title. +`link` | The item link. +`description` | The item description or summary. +`publication_date` | The item publication date. +`item_id` | The item's globally unique identifier (GUID). If the item has no GUID, the source uses the `link` value. If both are absent, the source uses a content hash. This field is always non-empty. +`feed_name` | The feed's key from the `feeds` map. This field is always present. +`feed_url` | The configured feed URL with its query string redacted. This field is always present. + +When a feed provides the following feed channel details, the source attaches them as event metadata rather than storing them in the document body. + +Metadata attribute | Description +:--- | :--- +`feed_title` | The feed channel's `<title>`. +`feed_link` | The feed channel's `<link>` (the publisher's site). +`feed_language` | The feed channel's `<language>`. +`feed_categories` | The feed channel's `<category>` values. + +Because `feed_name` and `feed_url` are body fields, they are searchable and can be used directly for per-feed routing at the sink. Use `item_id` as the `document_id` at the sink so that a republished item updates the existing document, as shown in the following example: + +```yaml +sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: "rss-${/feed_name}-%{yyyy.MM.dd}" + document_id: "${/item_id}" +``` + +Do not configure the sink to depend on a channel metadata attribute, because the attribute is absent when the feed does not provide it. Use the always present `feed_name`, `feed_url`, and `item_id` body fields for routing and document IDs. + +## Failure handling + +Feeds are polled independently. When a feed fails, the source logs the failure with the query string redacted from the feed URL, increments the `feedPollsFailed` metric for that feed, and backs off exponentially before retrying. A failure in one feed does not stop the other feeds or permanently stop polling. + +## Metrics + +The `rss` source includes the following metrics (counters). Each metric is recorded separately for every feed, with the feed name appended to the metric name: + +* `feedPollsFailed.<feed-name>`: The number of polls that have failed for the feed. +* `itemsIngested.<feed-name>`: The number of items the source has written to the buffer for the feed. + +## Limitations + +The following capabilities are not yet supported: + +- Bearer token authentication +- Custom header authentication +- Deduplication across restarts and nodes using source coordination +- End-to-end acknowledgments diff --git a/i18n/zh/data-prepper/pipelines/contains.md b/i18n/zh/data-prepper/pipelines/contains.md new file mode 100644 index 00000000..52d802f1 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/contains.md @@ -0,0 +1,110 @@ +--- +title: contains() +--- + +<!-- vale off --> +# contains() function +<!-- vale on --> + +The `contains()` function is used to check if a substring exists within a given string or the value of a field in an event. It takes two arguments: + +- The first argument is either a literal string or a JSON pointer that represents the field or value to be searched. + +- The second argument is the substring to be searched for within the first argument. +The function returns `true` if the substring specified in the second argument is found within the string or field value represented by the first argument. It returns `false` if it is not. + +For example, if you want to check if the string `"abcd"` is contained within the value of a field named `message`, you can use the `contains()` function as follows: + +``` +'contains(/message, "abcd")' +``` + +This call returns `true` if the field `message` contains the substring `abcd` or `false` if it does not. + +Alternatively, you can use a literal string as the first argument: + +``` +'contains("This is a test message", "test")' +``` + +In this case, the function returns `true` because the substring `test` is present within the string `This is a test message`. + +::: info NOTE +The `contains()` function performs a case-sensitive search. +::: + +## Example + +The following pipeline uses the `contains()` function to add a Boolean flag `has_test` based on a substring in `/message` and filters out non-matching events, forwarding only messages that contain the string `ERROR` to OpenSearch: + +```yaml +contains-demo-pipeline: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: has_test + value_expression: contains(/message, "test") + - drop_events: + drop_when: not contains(/message, "ERROR") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"ok hello"}, + {"message":"this has test but ok"}, + {"message":"ERROR: something bad"}, + {"message":"ERROR: unit test failed"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2025.10.21", + "_id": "5YACB5oBqZitdAAb4n3r", + "_score": 1, + "_source": { + "message": "ERROR: something bad", + "has_test": false + } + }, + { + "_index": "demo-index-2025.10.21", + "_id": "5oACB5oBqZitdAAb4n3r", + "_score": 1, + "_source": { + "message": "ERROR: unit test failed", + "has_test": true + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/functions.md b/i18n/zh/data-prepper/pipelines/functions.md new file mode 100644 index 00000000..dd68b4e5 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/functions.md @@ -0,0 +1,22 @@ +--- +title: Functions +--- + +# Data Prepper expression functions + +OpenSearch Data Prepper offers a range of built-in functions that can be used within expressions to perform common data preprocessing tasks, such as calculating lengths, checking for tags, retrieving metadata, searching for substrings, checking IP address ranges, joining list elements, and generating unique identifiers. These functions include the following: + +- [`cidrContains()`](/data-prepper/pipelines/cidrcontains) +- [`contains()`](/data-prepper/pipelines/contains) +- [`generateUuid()`](/data-prepper/pipelines/generate-uuid) +- [`getMetadata()`](/data-prepper/pipelines/get-metadata) +- [`getEventType()`](/data-prepper/pipelines/get-eventtype) +- [`hasTags()`](/data-prepper/pipelines/has-tags) +- [`join()`](/data-prepper/pipelines/join) +- [`length()`](/data-prepper/pipelines/length) +- [`startsWith()`](/data-prepper/pipelines/startswith) +- [`subList()`](/data-prepper/pipelines/sublist) +- [`substringAfter()`](/data-prepper/pipelines/substring-after) +- [`substringAfterLast()`](/data-prepper/pipelines/substring-after-last) +- [`substringBefore()`](/data-prepper/pipelines/substring-before) +- [`substringBeforeLast()`](/data-prepper/pipelines/substring-before-last) diff --git a/i18n/zh/data-prepper/pipelines/generate-uuid.md b/i18n/zh/data-prepper/pipelines/generate-uuid.md new file mode 100644 index 00000000..6c09a4c9 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/generate-uuid.md @@ -0,0 +1,65 @@ +--- +title: generateUuid() +--- + +<!-- vale off --> +# generateUuid() function +<!-- vale on --> + +The `generateUuid()` function takes no arguments and returns a randomly generated [UUID version 4](https://www.rfc-editor.org/rfc/rfc4122) string, for example, `"550e8400-e29b-41d4-a716-446655440000"`. Each call produces a unique value using a cryptographically strong random number generator, so collision probability is negligible in practice. + +This function is useful when source records do not contain a natural unique identifier---for example, when running asynchronous batch inference jobs that require a stable key to match inference results back to the original records. + +## Usage + +Use `generateUuid()` as a `value_expression` in the [`add_entries`](/data-prepper/pipelines/configuration/processors/add-entries) processor. This example adds a `recordId` field containing a unique UUID to every event passing through the processor: + +```yaml +processor: + - add_entries: + entries: + - key: recordId + value_expression: 'generateUuid()' +``` + +## Example + +The following pipeline assigns a unique `recordId` to each incoming log record before forwarding it to OpenSearch: + +```yaml +uuid-demo-pipeline: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: recordId + value_expression: 'generateUuid()' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` + +Given the following input event: + +```json +{ "message": "user login", "user": "alice" } +``` + +The document stored in OpenSearch contains the following information: + +```json +{ + "message": "user login", + "user": "alice", + "recordId": "550e8400-e29b-41d4-a716-446655440000" +} +``` diff --git a/i18n/zh/data-prepper/pipelines/get-eventtype.md b/i18n/zh/data-prepper/pipelines/get-eventtype.md new file mode 100644 index 00000000..3e084e65 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/get-eventtype.md @@ -0,0 +1,81 @@ +--- +title: getEventType() +--- + +<!-- vale off --> +# getEventType() function +<!-- vale on --> + +The `getEventType()` function returns the internal event type of the current event. This function is particularly useful when working with unified sources that can receive multiple types of telemetry data, such as the [OTLP source](/data-prepper/pipelines/configuration/sources/otlp-source). + +## Syntax + +```java +getEventType() +``` + +## Return value + +The function returns a string representing the event type. The supported event types are `LOG`, `TRACE`, `METRIC`, and `DOCUMENT`. + +## Usage + +Use this function to check the event type before performing conditional processing or routing. This is especially useful when you need to handle different types of telemetry data differently in your pipeline. + +### Basic example + +Check whether an event is a trace event: + +```json +getEventType() == "TRACE" +``` + +### Routing example with OTLP source + +To route different telemetry signals to different pipelines based on event type, use the `getEventType()` function to determine each event's type and route the different event types to different pipelines: + +```yaml +otel-telemetry-pipeline: + source: + otlp: + ssl: false + route: + - logs: 'getEventType() == "LOG"' + - traces: 'getEventType() == "TRACE"' + - metrics: 'getEventType() == "METRIC"' + sink: + - pipeline: + name: "logs-pipeline" + routes: + - "logs" + - pipeline: + name: "traces-pipeline" + routes: + - "traces" + - pipeline: + name: "metrics-pipeline" + routes: + - "metrics" +``` + +### Conditional processing example + +To process events differently based on their type, use the `add_when` expression to conditionally add fields to each event: + +```yaml +processor: + - add_entries: + entries: + - key: "log_processed" + value: true + add_when: 'getEventType() == "LOG"' + - add_entries: + entries: + - key: "metric_type" + value: "otel" + add_when: 'getEventType() == "METRIC"' +``` + +## Related documentation + +- [OTLP source](/data-prepper/pipelines/configuration/sources/otlp-source) diff --git a/i18n/zh/data-prepper/pipelines/get-metadata.md b/i18n/zh/data-prepper/pipelines/get-metadata.md new file mode 100644 index 00000000..e7632914 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/get-metadata.md @@ -0,0 +1,95 @@ +--- +title: getMetadata() +--- + +<!-- vale off --> +# getMetadata() function +<!-- vale on --> + +The `getMetadata()` function takes one literal string argument and looks up specific keys in event metadata. + +If the key contains a `/`, then the function looks up the metadata recursively. When passed, the expression returns the value corresponding to the key. + +The value returned can be of any type. For example, if the metadata contains `{"key1": "value2", "key2": 10}`, then the function `getMetadata("key1")` returns `value2`. The function `getMetadata("key2")` returns `10`. + +## Example + +The following pipeline writes request-derived values into event metadata and then uses `getMetadata()` in the OpenSearch sink to construct tenant-scoped daily index names and document IDs: + +```yaml +metadata-pass-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + # write to metadata + - metadata_key: tenant + value_expression: /tenant + - metadata_key: ingest_marker + value: batch-001 + - add_entries: + entries: + - key: tenant_from_meta + value_expression: getMetadata("tenant") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + # Use metadata inside sink format strings + index: demo-%{yyyy.MM.dd}-${getMetadata("tenant")} + document_id: ${/id}-${getMetadata("tenant")} +``` + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[{"id":"1","tenant":"eu","message":"hello"}, {"id":"2","tenant":"us","message":"hi"}]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-2025.10.22-eu", + "_id": "1-eu", + "_score": 1, + "_source": { + "id": "1", + "tenant": "eu", + "message": "hello", + "tenant_from_meta": "eu" + } + }, + { + "_index": "demo-2025.10.22-us", + "_id": "2-us", + "_score": 1, + "_source": { + "id": "2", + "tenant": "us", + "message": "hi", + "tenant_from_meta": "us" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/has-tags.md b/i18n/zh/data-prepper/pipelines/has-tags.md new file mode 100644 index 00000000..e7ae0e38 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/has-tags.md @@ -0,0 +1,42 @@ +--- +title: hasTags() +--- + +<!-- vale off --> +# hasTags() function +<!-- vale on --> + +The `hasTags()` function takes one or more string type arguments and returns `true` if all of the arguments passed are present in an event's tags. If an argument does not exist in the event's tags, then the function returns `false`. + +For example, if you use the expression `hasTags("tag1")` and the event contains `tag1`, then OpenSearch Data Prepper returns `true`. If you use the expression `hasTags("tag2")` but the event only contains `tag1`, then Data Prepper returns `false`. + +#### Example + +```json +{ + "events": [ + { + "tags": ["tag1"], + "data": { + // ... + } + }, + { + "tags": ["tag1", "tag2"], + "data": { + // ... + } + } + ], + "expressions": [ + { + "expression": "hasTags(\"tag1\")", + "expected_results": [true, true] + }, + { + "expression": "hasTags(\"tag2\")", + "expected_results": [false, true] + } + ] +} +``` diff --git a/i18n/zh/data-prepper/pipelines/join.md b/i18n/zh/data-prepper/pipelines/join.md new file mode 100644 index 00000000..f416c720 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/join.md @@ -0,0 +1,130 @@ +--- +title: join() +--- + +<!-- vale off --> +# join() function +<!-- vale on --> + +The `join()` function joins elements of a list to form a string. The function takes a JSON pointer, which represents the key to a list or map where values are of the list type, and joins the lists as strings using a delimiter. The default delimiter is a comma (`,`). + +## Parameters + +The `join` function takes the following parameters: + +- `delimiter` (string, optional): The string placed between elements. Examples: `,`, ` | `, `; `. Default is `,`. +- `pointer` (required): A JSON pointer resolving to a list in the event. + +## Returns +The `join` command returns the following value: + +- `string`: All elements concatenated using the specified `delimiter`. + +## Quick examples +- `join("-", /labels)` returns `"prod-api-us"` for `labels: ["prod","api","us"]` +- `join(" | ", /authors)` returns `"Ada | Linus | Grace"` for `authors: ["Ada","Linus","Grace"]` + +## Using `join()` in a pipeline + +You can use `join()` inside processors that support `value_expression`, for example, the `add_entries` processor: + +```yaml +processor: + - add_entries: + entries: + - key: labels_csv + value_expression: join(" | ", /labels) +``` + +## Example + +The following pipeline ingests JSON events using an `http` source. It then uses `add_entries` with `join()` to build two new fields, `labels_csv` and `authors_pipe`: + +```yaml +join-demo: + source: + http: + path: /events + ssl: false + processor: + - add_entries: + entries: + - key: labels_csv + value_expression: join(/labels) # Comma is used by default + - key: authors_pipe + value_expression: join(" | ", /authors) + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + index: join-demo-%{yyyy.MM.dd} + username: admin + password: "<custom-admin-password>" + index_type: custom + insecure: true # set to true for self-signed local clusters +``` + +You can test the pipeline using the following command: + +```bash +curl "http://localhost:2021/events" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"hello","labels":["prod","api","us"],"authors":["Ada","Linus","Grace"]}, + {"message":"world","labels":["stage","etl"],"authors":["Marie","Alan"]} + ]' +``` + +The document stored in OpenSearch contains the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "join-demo-2025.11.06", + "_id": "aGFyWZoBjfY5UoR7NC36", + "_score": 1, + "_source": { + "message": "hello", + "labels": [ + "prod", + "api", + "us" + ], + "authors": [ + "Ada", + "Linus", + "Grace" + ], + "labels_csv": "prod,api,us", + "authors_pipe": "Ada | Linus | Grace" + } + }, + { + "_index": "join-demo-2025.11.06", + "_id": "aWFyWZoBjfY5UoR7NC36", + "_score": 1, + "_source": { + "message": "world", + "labels": [ + "stage", + "etl" + ], + "authors": [ + "Marie", + "Alan" + ], + "labels_csv": "stage,etl", + "authors_pipe": "Marie | Alan" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/length.md b/i18n/zh/data-prepper/pipelines/length.md new file mode 100644 index 00000000..8078f9df --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/length.md @@ -0,0 +1,21 @@ +--- +title: length() +--- + +<!-- vale off --> +# length() function +<!-- vale on --> + +The `length()` function takes one argument of the JSON pointer type and returns the length of the passed value. For example, `length(/message)` returns a length of `10` when a key message exists in the event and has a value of `1234567890`. + +#### Example + +```json +{ + "event": { + "/message": "1234567890" + }, + "expression": "length(/message)", + "expected_output": 10 +} +``` diff --git a/i18n/zh/data-prepper/pipelines/startswith.md b/i18n/zh/data-prepper/pipelines/startswith.md new file mode 100644 index 00000000..5c7319cd --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/startswith.md @@ -0,0 +1,117 @@ +--- +title: startsWith() +--- + +<!-- vale off --> +# startsWith() function +<!-- vale on --> + +The `startsWith()` function checks whether a string starts with the given string. It takes two arguments: + +- The first argument is either a literal string or a JSON pointer that represents the field or value to be checked. + +- The second argument is the string to be checked in the first argument. +The function returns `true` if the string or field value represented by the first argument starts with the string specified in the second argument and `false` otherwise. + +For example, to check whether the value of a field name `message` starts with a string `"abcd"`, use the `startsWith()` function as follows: + +``` +startsWith('/message', 'abcd') +``` + +This call returns `true` if the `message` field starts with the string `abcd` or `false` if it does not. + +Alternatively, you can use a literal string as the first argument: + +``` +startsWith('abcdef', 'abcd') +``` + +In this case, the function returns `true` because the string `abcdef` starts with `abcd`. + +::: info NOTE +The `startsWith()` function performs a case-sensitive check. +::: + +## Example + +The following pipeline uses the `startsWith()` function to add two Boolean flags, `starts_abcd` and `starts_error`, to each event and forwards only events that start with the string `ERROR:` to OpenSearch: + +```yaml +startswith-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: starts_abcd + value_expression: startsWith(/message, "abcd") + + - key: starts_error + value_expression: startsWith(/message, "ERROR:") + + # forward only messages that start with "ERROR:" + - drop_events: + drop_when: not startsWith(/message, "ERROR:") + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: startswith-demo-%{yyyy.MM.dd} +``` + +You can test the pipeline using the following command: + +```bash +curl -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"message":"ok hello"}, + {"message":"abcd-hello"}, + {"message":"ERROR: something bad"}, + {"message":"ERROR: abcd unit test failed"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "startswith-demo-2025.11.10", + "_id" : "X97tbpoBnoSLj36HBGoL", + "_score" : 1.0, + "_source" : { + "starts_abcd" : false, + "starts_error" : true, + "message" : "ERROR: something bad" + } + }, + { + "_index" : "startswith-demo-2025.11.10", + "_id" : "YN7tbpoBnoSLj36HBGoL", + "_score" : 1.0, + "_source" : { + "starts_abcd" : false, + "starts_error" : true, + "message" : "ERROR: abcd unit test failed" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/sublist.md b/i18n/zh/data-prepper/pipelines/sublist.md new file mode 100644 index 00000000..2d6b8e34 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/sublist.md @@ -0,0 +1,75 @@ +--- +title: subList() +--- + +<!-- vale off --> +# subList() function +<!-- vale on --> + +The `subList(<key>, <start_index, inclusive>, <end_index, exclusive>)` function extracts a sublist from a list field in an event. It takes the following arguments: + +- A JSON pointer to an event field containing a list +- A start index (inclusive) +- An end index (exclusive) + +The function returns the portion of the list between the specified start and end indexes. If the end index is `-1`, the function extracts elements from the start index to the end of the list. + +## Examples + +The following examples show how the `sublist()` function works. + +<!-- vale off --> +### add_entries processor +<!-- vale on --> + +You can use `subList()` in the `add_entries` processor, as shown in the following example. + +The function uses the following input to extract a sublist: + +``` +input: {"my_list": [ 0, 1, 2, 3, 4, 5, 6]} +``` + +Then, the following configuration uses the `add_entries` processor to extract a sublist from `my_list`, starting at index `1` and ending before index `4`: + +```yaml +add_entries: + entries: + - key: "my_list" + value_expression: '/subList(/my_list, 1, 4)' + overwrite_if_key_exists: true +``` + +The following output shows the resulting list after extracting elements from index `1` to `3` and overwriting the original list: + +``` +output: my_list: [1, 2, 3] +``` + +### Specific ranges + +Each of the following examples demonstrates how the `subList()` function extracts a specific range of elements from a list. + +The following example extracts elements from index `0` to `2` (excluding index `3`), resulting in the first three elements of the list: + +```json +{ + "event": { + "/my_list": [0, 1, 2, 3, 4, 5, 6] + }, + "expression": "subList(/my_list, 4, -1)", + "expected_output": [4, 5, 6] +} +``` + +The following example uses `-1` as the end index, which specifies to include all elements from index `4` to the end of the list: + +```json +{ + "event": { + "/my_list": [0, 1, 2, 3, 4, 5, 6] + }, + "expression": "subList(/my_list, 4, -1)", + "expected_output": [4, 5, 6] +} +``` diff --git a/i18n/zh/data-prepper/pipelines/substring-after-last.md b/i18n/zh/data-prepper/pipelines/substring-after-last.md new file mode 100644 index 00000000..a4b7d726 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/substring-after-last.md @@ -0,0 +1,107 @@ +--- +title: substringAfterLast() +--- + +<!-- vale off --> +# substringAfterLast() function +<!-- vale on --> + +The `substringAfterLast()` function is used to extract the portion of a string that follows the last occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string after the last occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to extract the file extension from the `/filepath` field containing a file path, use the `substringAfterLast()` function as follows: + +``` +'substringAfterLast(/filepath, ".")' +``` + +If the `/filepath` field contains `archive.tar.gz`, the function returns `gz`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringAfterLast("one-two-three", "-")' +``` + +The function returns `three` because it extracts the portion of the string after the last `-` character. + +::: info NOTE +The `substringAfterLast()` function performs a case-sensitive search. +::: + +## Example + +The following pipeline uses the `substringAfterLast()` function to extract the file name from a full file path. It adds the extracted file name as a new field called `filename`: + +```yaml +substring-after-last-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: filename + value_expression: 'substringAfterLast(/filepath, "/")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"filepath":"/var/log/syslog"}, + {"filepath":"/home/user/docs/report.pdf"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "filepath": "/var/log/syslog", + "filename": "syslog" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "filepath": "/home/user/docs/report.pdf", + "filename": "report.pdf" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/substring-after.md b/i18n/zh/data-prepper/pipelines/substring-after.md new file mode 100644 index 00000000..73587273 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/substring-after.md @@ -0,0 +1,107 @@ +--- +title: substringAfter() +--- + +<!-- vale off --> +# substringAfter() function +<!-- vale on --> + +The `substringAfter()` function is used to extract the portion of a string that follows the first occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string after the first occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to extract the value after the first occurrence of the `=` character in a field named `header`, use the `substringAfter()` function as follows: + +``` +'substringAfter(/header, "=")' +``` + +If `/header` contains `Content-Type=application/json`, the function returns `application/json`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringAfter("hello-world-foo", "-")' +``` + +The function returns `world-foo` because it extracts the portion of the string after the first `-` character. + +::: info NOTE +The `substringAfter()` function performs a case-sensitive search. +::: + +## Example + +The following pipeline uses the `substringAfter()` function to extract the domain name from an email address field. It adds the extracted domain name as a new field called `domain`: + +```yaml +substring-after-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: domain + value_expression: 'substringAfter(/email, "@")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"email":"user@example.com"}, + {"email":"admin@opensearch.org"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "email": "user@example.com", + "domain": "example.com" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "email": "admin@opensearch.org", + "domain": "opensearch.org" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/substring-before-last.md b/i18n/zh/data-prepper/pipelines/substring-before-last.md new file mode 100644 index 00000000..23d39016 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/substring-before-last.md @@ -0,0 +1,107 @@ +--- +title: substringBeforeLast() +--- + +<!-- vale off --> +# substringBeforeLast() function +<!-- vale on --> + +The `substringBeforeLast()` function is used to extract the portion of a string that precedes the last occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string before the last occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to remove the file extension from a filename field, use the `substringBeforeLast()` function as follows: + +``` +'substringBeforeLast(/filename, ".")' +``` + +If the `/filename` field contains `archive.tar.gz`, the function returns `archive.tar`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringBeforeLast("one-two-three", "-")' +``` + +The function returns `one-two` because it extracts the portion of the string before the last `-` character. + +::: info NOTE +The `substringBeforeLast()` function performs a case-sensitive search. +::: + +## Example + +The following pipeline uses the `substringBeforeLast()` function to extract the directory path from a full file path. It adds the extracted directory path as a new field called `directory`: + +```yaml +substring-before-last-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: directory + value_expression: 'substringBeforeLast(/filepath, "/")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"filepath":"/var/log/syslog"}, + {"filepath":"/home/user/docs/report.pdf"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "filepath": "/var/log/syslog", + "directory": "/var/log" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "filepath": "/home/user/docs/report.pdf", + "directory": "/home/user/docs" + } + } + ] + } +} +``` diff --git a/i18n/zh/data-prepper/pipelines/substring-before.md b/i18n/zh/data-prepper/pipelines/substring-before.md new file mode 100644 index 00000000..f8f5d497 --- /dev/null +++ b/i18n/zh/data-prepper/pipelines/substring-before.md @@ -0,0 +1,107 @@ +--- +title: substringBefore() +--- + +<!-- vale off --> +# substringBefore() function +<!-- vale on --> + +The `substringBefore()` function is used to extract the portion of a string that precedes the first occurrence of a specified delimiter. It takes two arguments: + +1. The first argument is either a literal string or a JSON pointer that represents the source string. + +1. The second argument is the delimiter string to search for within the first argument. + +If the delimiter is found, the function returns the portion of the string before the first occurrence of the delimiter. If the delimiter is not found, the original string is returned. If the source resolves to `null`, the function returns `null`. If the delimiter is `null` or empty, the original string is returned. + +For example, to extract the username from an email address field, use the `substringBefore()` function as follows: + +``` +'substringBefore(/email, "@")' +``` + +If the `/email` field contains `user@example.com`, the function returns `user`. + +Alternatively, you can use a literal string as the first argument: + +``` +'substringBefore("hello-world-foo", "-")' +``` + +The function returns `hello` because it extracts the portion of the string before the first `-` character. + +::: info NOTE +The `substringBefore()` function performs a case-sensitive search. +::: + +## Example + +The following pipeline uses the `substringBefore()` function to extract the URL protocol from a URL field. It adds the extracted protocol as a new field called `protocol`: + +```yaml +substring-before-demo: + source: + http: + ssl: false + + processor: + - add_entries: + entries: + - key: protocol + value_expression: 'substringBefore(/url, "://")' + + sink: + - opensearch: + hosts: ["https://opensearch:9200"] + insecure: true + username: admin + password: "<custom-admin-password>" + index_type: custom + index: demo-index-%{yyyy.MM.dd} +``` + +You can test the pipeline using the following command: + +```bash +curl -sS -X POST "http://localhost:2021/log/ingest" \ + -H "Content-Type: application/json" \ + -d '[ + {"url":"https://opensearch.org/docs"}, + {"url":"http://example.com/page"} + ]' +``` + +The documents stored in OpenSearch contain the following information: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "demo-index-2026.03.13", + "_id": "abc123", + "_score": 1, + "_source": { + "url": "https://opensearch.org/docs", + "protocol": "https" + } + }, + { + "_index": "demo-index-2026.03.13", + "_id": "def456", + "_score": 1, + "_source": { + "url": "http://example.com/page", + "protocol": "http" + } + } + ] + } +} +``` diff --git a/i18n/zh/im-plugin/append-only-index.md b/i18n/zh/im-plugin/append-only-index.md new file mode 100644 index 00000000..41b34308 --- /dev/null +++ b/i18n/zh/im-plugin/append-only-index.md @@ -0,0 +1,95 @@ +--- +title: 仅追加索引 +--- + +# 仅追加索引 + +仅追加索引是一种不可变索引,只允许文档摄取(追加),同时在初始文档创建后阻止所有更新或删除操作。当您为索引启用仅追加设置时,OpenSearch 会阻止对现有文档的任何修改。您只能向索引中添加新文档。 + +当您将索引配置为仅追加时,以下操作将返回错误: + +- 文档更新调用(Update API) +- 文档删除调用(Delete API) +- 按查询更新调用 +- 按查询删除调用 +- 使用 update、delete 或 upsert 操作进行的批量 API 调用 +- 包含带有自定义文档 ID 的索引操作的批量 API 调用 + +由于仅追加索引不执行更新或删除操作,因此它跳过软删除和版本跟踪,从而减少存储使用并减少段合并期间的工作量。对于摄取后不会被修改的数据(例如日志、指标、可观测性数据或安全事件),请使用仅追加索引。 + +## 创建仅追加索引 + +以下请求创建一个名为 `my-append-only-index` 的新索引,并禁用所有更新: + +```json +PUT /my-append-only-index +{ + "settings": { + "index.append_only.enabled": true + } +} +``` + +::: danger WARNING +索引设置为仅追加后,无法更改为其他索引类型。 +::: + +要将现有索引的数据追加到新的仅追加索引,请使用 Reindex API。由于仅追加索引不支持自定义文档 ID,因此您需要将源索引的 `ctx._id` 设置为 `null`。这允许通过重新索引添加文档。 + +以下示例将文档从源索引(`my-source-index`)重新索引到新的仅追加索引。首先创建源索引: + +```json +POST /my-source-index/_doc?refresh=true +{ + "message": "login attempt" +} +``` + +然后将其文档重新索引到仅追加索引: + +```json +POST /_reindex +{ + "source": { + "index": "my-source-index" + }, + "dest": { + "index": "my-append-only-index" + }, + "script": { + "source": "ctx._id = null", + "lang": "painless" + } +} + +``` + +## 批量索引的自适应分片选择 +<Badge type="tip" text="3.5 版本引入" /> + +对于仅追加索引,当您不显式指定 `_id` 时,OpenSearch 会自动为写入路由生成一个随机的 `_id`。在批量写入中,单个批量条目可能会被拆分为数十个子批量并分派到不同的分片,这会导致显著的长尾延迟,并显著降低写入性能。 + +自适应分片选择保证单个批量条目的所有子批量都路由到同一分片,从而实现批量写入性能的大幅提升。 + +`index.bulk.adaptive_shard_selection.enabled` 设置是动态的,因此您可以在现有的仅追加索引上启用它: + +```json +PUT /my-append-only-index/_settings +{ + "index.bulk.adaptive_shard_selection.enabled": "true" +} +``` + +您还可以在创建索引时设置它: + +```json +PUT /my-new-append-only-index +{ + "settings": { + "index.append_only.enabled": "true", + "index.bulk.adaptive_shard_selection.enabled": "true" + } +} +``` + +有关更多信息,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 diff --git a/i18n/zh/im-plugin/index-context.md b/i18n/zh/im-plugin/index-context.md new file mode 100644 index 00000000..bc26af6d --- /dev/null +++ b/i18n/zh/im-plugin/index-context.md @@ -0,0 +1,170 @@ +--- +title: 索引上下文 +--- + +# 索引上下文 +<Badge type="tip" text="2.17 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +索引上下文声明索引的用例。使用上下文信息,OpenSearch 应用预定的设置和映射集,这提供了以下好处: + +- 优化的性能 +- 针对您特定用例调优的设置 +- 基于 [OpenSearch 集成](/integrations/)的准确映射和别名 + +::: danger WARNING +使用组件模板应用的设置和元数据配置在集群启动时自动加载。以 `@abc_template@` 或应用程序基础配置(ABC)模板开头的组件模板只能通过 `context` 对象声明使用,以防止配置问题。 +::: + +## 启用索引上下文 + +索引上下文需要两个设置,这两个设置都在节点启动时应用。在集群中的每个节点上启用这两个设置,然后重启节点: + +1. 将 `opensearch.experimental.feature.application_templates.enabled` 功能标志设置为 `true`。有关更多信息,请参阅[实验性功能标志](/install-and-configure/configuring-opensearch/experimental)。 + +2. 将以下行添加到 `opensearch.yml`: + + ```yaml + cluster.application_templates.enabled: true + ``` + +::: danger WARNING +不要使用[集群设置 API](/api-reference/cluster-api/cluster-settings) 设置 `cluster.application_templates.enabled`。该 API 接受更新并返回 `200`,但节点随后无法应用结果集群状态,记录未启用功能标志的错误。节点会反复放弃其集群管理器角色,并且每个更改集群状态的请求(例如创建索引)都会停止响应,直到您重启节点。如果将该值设置为持久设置,则在重启后会重新应用。 +::: + +`opensearch-system-templates` 插件提供支持每个上下文的组件模板。它与除最小发行版之外的所有 OpenSearch 发行版捆绑在一起。如果使用最小发行版,请使用其中一种[安装方法](/install-and-configure/plugins#installing-plugins)安装它。 + +## 使用 `context` 设置 + +将 `context` 设置与 Index API 一起使用以添加特定于用例的上下文。 + +### 注意事项 + +在索引创建期间使用 `context` 参数时,请考虑以下事项: + +- 如果使用 `context` 参数创建索引,则在索引创建或动态设置更新期间不能包含索引上下文中声明的任何设置。 +- 在索引或索引模板上设置索引上下文后,它将成为永久性的。 + +当您遵守这些限制时,建议的配置或映射将统一应用于指定上下文内的索引数据。 + +如果未启用 `cluster.application_templates.enabled`,则声明上下文的请求将被拒绝,返回 `400`。 + +### 示例 + +以下示例展示如何使用索引上下文。 + +#### 创建索引 + +以下示例请求通过将 `metrics` 映射声明为上下文来创建用于存储指标数据的索引: + +```json +PUT /my-metrics-index +{ + "context": { + "name": "metrics" + } +} +``` + +创建后,上下文将添加到索引,并应用相应的设置。要确认这一点,请发送以下请求: + +```json +GET /my-metrics-index +``` + +响应包含上下文及其应用的设置: + +```json +{ + "my-metrics-index": { + "aliases": {}, + "mappings": {}, + "settings": { + "index": { + "codec": "zstd_no_dict", + "refresh_interval": "60s", + "number_of_shards": "1", + "provided_name": "my-metrics-index", + "merge": { + "policy": "log_byte_size" + }, + "context": { + "created_version": "1", + "current_version": "1" + }, + ... + } + }, + "context": { + "name": "metrics", + "version": "_latest" + } + } +} +``` + +#### 创建索引模板 + +您还可以在创建索引模板时使用 `context` 参数。以下示例请求创建一个索引模板,其上下文信息为 `logs`: + +```json +PUT _index_template/my-logs +{ + "context": { + "name": "logs", + "version": "1" + }, + "index_patterns": [ + "my-logs-*" + ] +} +``` + +使用此索引模板创建的所有索引都将获得关联组件模板提供的元数据。要确认 `context` 已添加到模板,请发送以下请求: + +```json +GET _index_template/my-logs +``` + +响应包含上下文: + +```json +{ + "index_templates": [ + { + "name": "my-logs", + "index_template": { + "index_patterns": [ + "my-logs-*" + ], + "context": { + "name": "logs", + "version": "1" + } + } + } + ] +} +``` + +如果模板直接声明的任何设置、映射或别名与上下文的后备组件模板之间存在任何冲突,则在索引创建期间后者具有更高的优先级。 + +## 可用的上下文模板 + +以下模板可以通过 `context` 参数使用: + +- `logs` +- `metrics` +- `nginx-logs` +- `amazon-cloudtrail-logs` +- `amazon-elb-logs` +- `amazon-s3-logs` +- `apache-web-logs` +- `k8s-logs` + +有关这些模板的更多信息,请参阅 [OpenSearch 系统模板存储库](https://github.com/opensearch-project/opensearch-system-templates/tree/main/src/main/resources/org/opensearch/system/applicationtemplates/v1)。 + +要查看集群上这些模板的当前版本,请使用 `GET /_component_template`。 diff --git a/i18n/zh/im-plugin/index-maintenance.md b/i18n/zh/im-plugin/index-maintenance.md new file mode 100644 index 00000000..a9ff0145 --- /dev/null +++ b/i18n/zh/im-plugin/index-maintenance.md @@ -0,0 +1,276 @@ +--- +title: 索引维护 +--- + +# 索引维护 + +OpenSearch 在后台刷新索引、刷写事务日志并合并段,因此大多数集群从不需要手动运行这些操作。当您需要在特定时刻获得结果时手动运行它们:在索引文档后立即使其可搜索、在快照之前从已删除的文档中回收磁盘空间,或更改已超出其原始布局的索引的分片数。 + +每个操作都可以通过[索引操作 API](/api-reference/index-apis/index-operations) 和(除克隆外)OpenSearch Dashboards 中的**索引管理**页面使用。 + +有关生命周期操作(例如创建、打开、关闭和删除索引),请参阅[索引操作](/im-plugin/index-operations)。 + +本页上的示例对名为 `logs-2026` 的索引进行操作,该索引具有两个主分片,您可以使用以下请求创建: + +```json +PUT /logs-2026 +{ + "settings": { + "index.number_of_shards": 2, + "index.number_of_replicas": 0 + } +} +``` + +## 刷新索引 + +刷新将内存缓冲区中的文档写入新段,使它们对搜索可见。OpenSearch 默认每秒刷新每个索引一次,因此文档在索引后大约一秒钟后变得可搜索。当测试或客户端需要在写入文档后立即搜索它时,手动刷新索引: + +```json +POST /logs-2026/_refresh +``` + +刷新每次运行时都会创建一个段,因此在批量加载期间频繁刷新会减慢索引速度。当您加载大量数据时,在加载期间将 `index.refresh_interval` 设置为 `-1`,并在结束时刷新一次。有关更多信息,请参阅[刷新索引](/api-reference/index-apis/refresh)。 + +刷新仅适用于打开的索引。 + +## 刷写索引 + +刷写执行 Lucene 提交,将文件系统缓存中的段写入磁盘并启动新的事务日志。这使索引数据在节点重启后持久化。OpenSearch 根据事务日志大小和年龄自动刷写: + +```json +POST /logs-2026/_flush +``` + +在关闭节点进行维护之前手动刷写,以便恢复不必重放大型事务日志。有关更多信息,请参阅[刷写](/api-reference/index-apis/flush)。 + +刷写仅适用于打开的索引。 + +## 清除索引缓存 + +OpenSearch 缓存字段数据、查询结果和请求级聚合结果以加快重复搜索。清除这些缓存会释放堆内存,但会使下一次搜索变慢,直到缓存重新填充: + +```json +POST /logs-2026/_cache/clear +``` + +要清除一个缓存而不是全部,请使用 `fielddata`、`query` 或 `request` 查询参数。有关更多信息,请参阅[清除缓存](/api-reference/index-apis/clear-index-cache)。 + +清除缓存仅适用于打开的索引。 + +## 强制合并索引 + +OpenSearch 将索引存储为一组不可变段,并在后台将较小的段合并为较大的段。已删除的文档仅被标记为已删除;其空间在包含它的段被合并时回收。强制合并立即运行该合并,减少段数并清除已删除的文档: + +```json +POST /logs-2026/_forcemerge?max_num_segments=1 +``` + +强制合并在 I/O 方面开销很大,并且可能产生自动合并策略永远不会再次合并的段。仅在不再接收写入的索引上运行它,例如滚动过的时间序列索引。有关更多信息,请参阅[强制合并](/api-reference/index-apis/force-merge)。 + +## 收缩索引 + +收缩将索引复制到具有更少主分片的新索引中。收缩创建时分片数量超过其最终大小所需的索引,因为无法就地更改现有索引的主分片数。 + +首先,阻止源索引上的写入操作。收缩仍然接受写入的索引会失败,返回 `illegal_state_exception`: + +```json +PUT /logs-2026/_settings +{ + "index.blocks.write": true +} +``` + +然后收缩索引: + +```json +POST /logs-2026/_shrink/logs-2026-shrunk +{ + "settings": { + "index.number_of_shards": 1 + } +} +``` + +源索引必须满足以下条件: + +- 索引是只读的,设置了写入块。请参阅[块](/api-reference/index-apis/blocks)。 +- 每个分片的副本(主分片或副本分片)都驻留在同一节点上。使用[分片分配过滤](/api-reference/index-apis/shard-allocation)将副本移动到一起。 +- 源索引的每个分片都已分配,即索引健康不是红色。 +- 目标索引尚不存在。 +- 源索引的主分片多于目标索引,并且目标分片数是源分片数的因子。例如,具有 8 个主分片的索引可以收缩为 4、2 或 1。具有质数个分片的索引(例如 7)只能收缩为 1。 +- 单个目标分片接收的文档不超过 2,147,483,519 个,这是 Lucene 分片可以容纳的最大值。 +- 执行收缩的节点有足够的可用磁盘空间用于索引的第二个副本。 + +有关更多信息,请参阅[收缩索引](/api-reference/index-apis/shrink-index)。 + +## 拆分索引 + +拆分将索引复制到具有更多主分片的新索引中,将每个源分片划分为多个目标分片。拆分已超出其原始分片数并需要更多容量来处理数据量或查询负载的索引。拆分还需要对源索引设置写入块: + +```json +PUT /logs-2026/_settings +{ + "index.blocks.write": true +} +``` + +然后拆分索引: + +```json +POST /logs-2026/_split/logs-2026-split +{ + "settings": { + "index.number_of_shards": 4 + } +} +``` + +源索引必须满足以下条件: + +- 索引是只读的,设置了写入块。请参阅[块](/api-reference/index-apis/blocks)。 +- 源索引的每个分片都已分配,即索引健康不是红色。 +- 目标索引尚不存在。 +- 源索引的主分片少于目标索引,并且目标分片数是源分片数的倍数。例如,具有 2 个主分片的索引可以拆分为 4、6 或 8。具有 1 个主分片的索引可以拆分为任意数量的分片。 +- 执行拆分的节点有足够的可用磁盘空间用于索引的第二个副本。 + +有关更多信息,请参阅[拆分索引](/api-reference/index-apis/split)。 + +## 克隆索引 + +克隆将索引复制到具有相同数量主分片、映射和设置的新索引中。克隆索引以针对真实数据测试映射或设置更改,而不触及原始数据。与收缩和拆分一样,克隆需要对源索引设置写入块: + +```json +PUT /logs-2026/_settings +{ + "index.blocks.write": true +} +``` + +然后克隆索引: + +```json +POST /logs-2026/_clone/logs-2026-copy +``` + +完成后,通过将 `index.blocks.write` 设置为 `false` 来删除写入块。 + +有关更多信息,请参阅[克隆索引](/api-reference/index-apis/clone)。克隆仅通过 API 可用。 + +## 滚动索引 + +滚动创建一个新索引并将写入别名或数据流重定向到它,以便写入继续针对新索引,而前一个索引变为只读。这使各个时间序列索引保持在可管理的大小,并允许您通过删除整个索引来删除或归档旧数据。 + +滚动目标必须是[数据流](/im-plugin/data-streams)或具有指定写入索引的[索引别名](/im-plugin/index-alias)。创建一个名称以数字结尾的索引,并将写入别名指向它: + +```json +PUT /logs-000001 +{ + "aliases": { + "logs": { + "is_write_index": true + } + } +} +``` + +以下请求在 `logs` 别名的写入索引达到 50 GB、1000 万个文档或 7 天时滚动它: + +```json +POST /logs/_rollover +{ + "conditions": { + "max_size": "50gb", + "max_docs": 10000000, + "max_age": "7d" + } +} +``` + +在新索引上没有满足任何条件,因此响应报告 `"rolled_over": false`。有关更多信息,请参阅[滚动索引](/api-reference/index-apis/rollover)。 + +要按计划滚动而不是在满足条件时调用 API,请定义一个带有 `rollover` 操作的 [Index State Management 策略](/im-plugin/ism/)。ISM 为您评估条件并在满足条件时滚动索引。 + +## OpenSearch Dashboards 中的索引维护 + +要导航到**索引管理**页面,请在顶部菜单上转到**管理 > 索引管理**。所选索引的维护操作在**索引**页面上的**操作**菜单中,如下图所示。 + +*索引页面上的操作菜单* + +这些过程作用于已存在的索引。要创建索引,请参阅[创建索引](/im-plugin/index-operations#creating-an-index-1)。 + +### 刷新、刷写或清除缓存 + +1. 在**索引管理**中,选择**索引**、**数据流**或**别名**。 +1. 可选地,选择您希望操作应用于的每个项目旁边的复选框。如果您不选择任何项目,则操作将应用于所有项目。 +1. 选择**操作**,然后选择**刷新**、**刷写**或**清除缓存**。 +1. 在确认对话框中选择相同的选项。 + +对于别名和数据流,这些操作应用于打开的后备索引。 + +### 强制合并索引 + +1. 在**索引管理**中,选择**索引**、**数据流**或**别名**。 +1. 选择**操作**,然后选择**强制合并**。 +1. 在**配置源索引**中,选择要合并的索引、数据流或别名。 +1. 可选地,展开**高级设置**并设置以下任何选项: + + - 要合并到特定数量的段,请在**索引段**中选择**手动设置段数**并输入数字。输入 `1` 将每个分片合并为一个段。 + - 要在合并完成后刷写索引,请选择**刷写索引**。 + - 要清除标记为已删除的文档,请选择**删除已删除的文档**。 + +1. 可选地,在**通知**中,选择**已失败/超时**、**已完成**或两者以接收有关结果的通知。 +1. 选择**强制合并**。 + +### 收缩索引 + +1. 在**索引管理**中,选择**索引**。 +1. 选择要收缩的索引,然后选择**操作 > 收缩**。 +1. 在**配置目标索引**中,在**目标索引名称**中输入名称。 +1. 在**主分片数**中输入新的分片数,在**副本数**中输入副本数。 +1. 可选地,在**索引别名**中为目标索引选择或输入一个或多个别名。 +1. 可选地,展开**高级设置**以添加通知。请参阅[发送附加通知](/im-plugin/notifications-settings#sending-additional-notifications)。 +1. 选择**收缩**。 + +如果源索引不满足[收缩条件](#shrinking-an-index),界面会提示您解决它们,包括在索引上设置写入块。 + +### 拆分索引 + +1. 在**索引管理**中,选择**索引**。 +1. 选择要拆分的索引,然后选择**操作 > 拆分**。 +1. 在**配置目标索引**中,在**目标索引名称**中输入名称。 +1. 在**主分片数**中输入新的分片数,在**副本数**中输入副本数。 +1. 可选地,在**索引别名**中为目标索引选择或输入一个或多个别名。 +1. 可选地,展开**高级设置**以添加通知。请参阅[发送附加通知](/im-plugin/notifications-settings#sending-additional-notifications)。 +1. 选择**拆分**。 + +### 滚动数据流 + +1. 在**索引管理**中,选择**数据流**。 +1. 选择**操作**,然后选择**滚动**。 +1. 在**配置源**中,选择要滚动的数据流。 +1. 选择**滚动**。 + +### 滚动别名 + +1. 在**索引管理**中,选择**别名**。 +1. 选择**操作**,然后选择**滚动**。 +1. 在**配置源**中,选择要滚动的别名。如果别名没有写入索引,系统会提示您指定一个。 +1. 在**定义索引**中,输入新索引的名称,以及可选的别名。 +1. 在**索引设置**中,输入主分片数、副本数和刷新间隔。 +1. 选择**滚动**。 + +### 检查长时间运行操作的状态 + +重新索引、收缩和拆分操作可能需要数十秒到数小时,具体取决于所涉及的数据量。由于每个操作都是一次性的非递归操作,因此您可以跟踪它直到完成: + +1. 在**索引管理**中,选择**索引**。 +1. 找到操作应用于的索引。 +1. 在**状态**列中读取操作的状态。 + +## 相关文档 + +- [索引操作 API](/api-reference/index-apis/index-operations) +- [索引操作](/im-plugin/index-operations) +- [索引状态管理](/im-plugin/ism/) +- [长时间运行操作通知](/im-plugin/notifications-settings) diff --git a/i18n/zh/im-plugin/index-operations.md b/i18n/zh/im-plugin/index-operations.md new file mode 100644 index 00000000..f0ec8423 --- /dev/null +++ b/i18n/zh/im-plugin/index-operations.md @@ -0,0 +1,196 @@ +--- +title: 索引操作 +--- + +# 索引操作 + +索引是 OpenSearch 中数据存储的基本单元。在索引的生命周期中,您创建它、检查其设置和统计信息、在更改静态设置时关闭它、重新打开它,并最终删除它。您可以使用[核心索引 API](/api-reference/index-apis/core-index-apis) 或从 OpenSearch Dashboards 中的**索引管理**页面执行这些操作中的每一个。 + +有关维护操作(例如刷新、刷写、强制合并、收缩和拆分)的信息,请参阅[索引维护](/im-plugin/index-maintenance)。 + +## 创建索引 + +您可以让 OpenSearch 在您将第一个文档索引到索引时隐式创建索引,或者您可以显式创建索引,以便从一开始就控制其映射和设置。当您需要特定数量的分片、自定义刷新间隔或与动态推断的字段映射不同的映射时,请显式创建索引。 + +以下请求创建一个具有两个主分片、一个副本以及 `timestamp` 字段的 `date` 映射的索引: + +```json +PUT /logs-2026 +{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1 + } + }, + "mappings": { + "properties": { + "timestamp": { "type": "date" }, + "message": { "type": "text" } + } + } +} +``` + +有关所有可用的设置和映射,请参阅[创建索引](/api-reference/index-apis/create-index)。要将相同的设置和映射应用于名称与模式匹配的每个索引,请使用[索引模板](/im-plugin/index-templates)。 + +### 索引命名限制 + +OpenSearch 索引具有以下命名限制: + +- 所有字母必须小写。 +- 索引名称不能以下划线(`_`)或连字符(`-`)开头。 +- 索引名称不能包含空格、逗号或以下字符: + + `:`、`"`、`*`、`+`、`/`、`\`、`|`、`?`、`#`、`>`或`<` + +以句点(`.`)开头的名称保留给 OpenSearch 系统索引。 + +## 查看索引信息 + +要检索索引的设置、映射和别名,请使用 [Get Index API](/api-reference/index-apis/get-index): + +```json +GET /logs-2026 +``` + +要检查索引是否存在而不检索它,请使用 [Index Exists](/api-reference/index-apis/exists)。要将别名、数据流或通配符表达式解析为它所涵盖的具体索引,请使用 [Resolve Index](/api-reference/index-apis/resolve-index)。有关文档计数、存储大小和每个操作指标,请使用 [Index Stats](/api-reference/index-apis/stats)。 + +## 关闭和打开索引 + +关闭的索引拒绝读写请求并释放其分片正在使用的内存,但其数据仍保留在磁盘上。当您需要更改只能在关闭的索引上更新的静态设置时,或者当您想保留不再查询的索引而不支付其内存成本时,请关闭索引。 + +要关闭索引,请使用 [Close Index API](/api-reference/index-apis/close-index): + +```json +POST /logs-2026/_close +``` + +要使索引再次可用,请使用 [Open Index API](/api-reference/index-apis/open-index): + +```json +POST /logs-2026/_open +``` + +有关需要关闭索引的设置列表,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +## 删除索引 + +删除索引会删除其文档、分片和元数据。使用 [Delete Index API](/api-reference/index-apis/delete-index): + +```json +DELETE /logs-2026 +``` + +::: danger WARNING +除非您从[快照](/tuning-your-cluster/availability-and-recovery/snapshots/)恢复,否则无法恢复已删除的索引。 +::: + +要按计划而不是手动删除索引,请定义一个带有 `delete` 操作的 [Index State Management 策略](/im-plugin/ism/)。 + +## OpenSearch Dashboards 中的索引操作 + +要导航到**索引管理**页面,请在顶部菜单上转到**管理 > 索引管理**。**索引**页面列出了集群中的索引,并提供有关每个索引的以下信息。 + +| 列 | 描述 | +| :--- | :--- | +| **索引** | 索引的名称。 | +| **健康** | 索引的复制状态:绿色(所有主分片和副本分片都已分配)、黄色(至少一个副本分片未分配)或红色(至少一个主分片未分配)。 | +| **由策略管理** | 索引状态管理策略是否直接或通过别名应用于索引。 | +| **状态** | 索引是打开还是关闭。 | +| **总大小** | 索引在所有主分片和副本分片上使用的存储。 | +| **主分片大小** | 索引在所有主分片上使用的存储。 | +| **总文档数** | 索引中的文档数量。 | +| **已删除文档** | 从索引中删除的文档数量。 | +| **主分片数** | 主分片的数量。 | +| **副本数** | 每个主分片的副本分片数量。 | + +由于列表可以跨越多个页面,请使用搜索框按名称查找索引。 + +以下图像显示了**索引**页面。 + +*索引页面* + +### 查看索引详细信息 + +1. 在**索引管理**中,选择**索引**。 +1. 在**索引**列中选择索引名称。 + +索引页面显示一个**概述**面板,其中包含索引的指标,以及您可以编辑的**设置**、**映射**和**别名**选项卡。要返回列表,请在面包屑导航中选择**索引**。 + +### 创建索引 + +1. 在**索引管理**中,选择**索引**,然后选择**创建索引**。 +1. 在**定义索引**中,输入索引名称。可选地,为索引选择现有别名或输入新别名的名称以创建。 +1. 在**索引设置**中,输入主分片数、副本数和刷新间隔。默认刷新间隔为 `1s`。要将其他设置作为平面 JSON 对象提供,请展开**高级设置**。有关可用选项,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 +1. 在**索引映射**中,定义文档中的字段。选择**可视化编辑器**以逐个添加字段,或选择 **JSON 编辑器**以粘贴现有映射。在可视化编辑器中,选择**添加新字段**或**添加新对象**,输入字段名称,然后选择字段类型。对于对象字段,选择 <img src="/images/icons/plus-icon.png" class="inline-icon" alt="plus icon"/>(加号)图标以添加嵌套字段。此面板是可选的;如果将其留空,OpenSearch 会从您索引的第一个文档推断映射。 +1. 选择**创建**。您指定的任何新别名都会与索引一起创建。 + +要创建[仅追加索引](/im-plugin/append-only-index),请在创建索引之前在**高级设置**中添加以下设置: + +```json +"index.append_only.enabled": "true" +``` + +::: danger WARNING +索引创建后无法转换为或从仅追加索引转换。 +::: + +### 编辑索引 + +1. 在**索引管理**中,选择**索引**。 +1. 在**索引**列中选择索引名称。 +1. 选择要更改的选项卡: + + - 要更改副本数或刷新间隔,请选择**设置**。要将其他设置作为平面 JSON 对象提供,请展开**高级设置**。您不能更改现有索引的主分片数;要更改它,请改为[收缩](/im-plugin/index-maintenance#shrinking-an-index-1)或[拆分](/im-plugin/index-maintenance#splitting-an-index-1)索引。 + - 要添加字段或对象,请选择**映射**。您不能更改现有字段的名称或类型。 + - 要添加别名、选择现有别名或删除别名,请选择**别名**。要删除别名,请选择其名称旁边的 <img src="/images/icons/cross-icon.png" class="inline-icon" alt="cross icon"/>(叉号)图标。 + +1. 选择**保存**。 + +### 关闭索引 + +1. 在**索引管理**中,选择**索引**。 +1. 选择要关闭的每个索引旁边的复选框。 +1. 选择**操作**,然后选择**关闭**。 +1. 在确认对话框中输入 `close`,然后选择**关闭**。 + +### 打开索引 + +1. 在**索引管理**中,选择**索引**。 +1. 选择要打开的每个关闭索引旁边的复选框。 +1. 选择**操作**,然后选择**打开**。 +1. 在确认对话框中选择**打开**。 + +### 删除索引 + +1. 在**索引管理**中,选择**索引**。 +1. 选择要删除的每个索引旁边的复选框。 +1. 选择**操作**,然后选择**删除**。 +1. 在确认对话框中输入 `delete`,然后选择**删除**。 + +### 应用策略 + +要从索引列表将索引状态管理策略附加到索引: + +1. 在**索引管理**中,选择**索引**。 +1. 选择您希望策略管理的每个索引旁边的复选框。 +1. 选择**操作**,然后选择**应用策略**。 +1. 从**策略 ID** 中选择一个策略。将显示策略的预览。 +1. 如果策略包含 `rollover` 操作,请在**滚动别名**中输入现有别名。 +1. 选择**应用**。 + +有关更多信息,请参阅[托管索引](/im-plugin/ism/managedindexes)。 + +### 权限和错误报告 + +权限通过[权限](/security/access-control/permissions)和操作组在 API 级别强制执行。OpenSearch Dashboards 不添加单独的权限控制层:如果您有权访问**索引管理**页面,则可以查看它们,如果您有权调用相应的 API,则可以完成操作。 + +立即失败的操作会在界面中报告错误。对于运行时间较长的操作,当发生故障时会报告故障。您还可以在索引列表的**状态**列中检查操作的状态。有关更多信息,请参阅[检查长时间运行操作的状态](/im-plugin/index-maintenance#checking-the-status-of-long-running-operations)。 + +## 相关文档 + +- [添加和管理您的数据](/getting-started/manage-data/) +- [核心索引 API](/api-reference/index-apis/core-index-apis) +- [索引维护](/im-plugin/index-maintenance) +- [索引状态管理](/im-plugin/ism/) diff --git a/i18n/zh/im-plugin/index-sorting.md b/i18n/zh/im-plugin/index-sorting.md new file mode 100644 index 00000000..1ab05fbf --- /dev/null +++ b/i18n/zh/im-plugin/index-sorting.md @@ -0,0 +1,193 @@ +--- +title: 索引排序 +--- + +# 索引排序 + +OpenSearch 允许您在索引创建时配置文档在每个段内的组织方式。默认情况下,Lucene 不对文档应用排序。`index.sort.*` 设置指定文档在每个段内的组织方式。 + +排序行为由 `index.sort.field`、`index.sort.order`、`index.sort.mode` 和 `index.sort.missing` 设置控制。有关更多信息,请参阅[静态索引设置](/install-and-configure/configuring-opensearch/index-settings#index-sort-settings)。 + +::: info NOTE +索引排序只能在索引创建期间配置,之后无法修改。此功能会影响索引性能,因为在刷新和合并操作期间必须对文档进行排序。我们建议在生产中实施之前测试排序的性能影响。 +::: + +## 按单个字段排序 + +以下示例按 `timestamp` 字段以降序对索引进行排序: + +```json +PUT /sample-index +{ + "settings": { + "index": { + "sort.field": "timestamp", + "sort.order": "desc" + } + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + } + } + } +} +``` + +## 按多个字段排序 + +您还可以按多个字段排序,优先级给予第一个字段。以下示例首先按 `category` 升序对文档排序,然后按 `timestamp` 降序排序: + +```json +PUT /multi-sort-index +{ + "settings": { + "index": { + "sort.field": [ + "category", + "timestamp" + ], + "sort.order": [ + "asc", + "desc" + ] + } + }, + "mappings": { + "properties": { + "category": { + "type": "keyword", + "doc_values": true + }, + "timestamp": { + "type": "date" + } + } + } +} +``` + +## 按嵌套字段排序 +<Badge type="tip" text="3.3 版本引入" /> + +您可以在映射包含嵌套字段的索引上配置索引排序。按索引的顶级字段排序;嵌套字段可以出现在映射中,但不能出现在 `sort.field` 中。以下示例对具有 `comments` 嵌套字段的索引按顶级 `user_id` 和 `created_at` 字段进行排序: + +```json +PUT /nested-index +{ + "settings": { + "index": { + "sort.field": [ + "user_id", + "created_at" + ], + "sort.order": [ + "asc", + "desc" + ] + } + }, + "mappings": { + "properties": { + "user_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "comments": { + "type": "nested", + "properties": { + "message": { "type": "text" }, + "timestamp": { "type": "date" } + } + } + } + } +} +``` + +::: info NOTE +索引排序不能应用于嵌套对象内的字段,这使嵌套文档在结构上保持完整。命名一个字段(例如 `comments.timestamp`)将被拒绝,返回 `400`。 +::: + +## 通过提前终止优化搜索 + +当您的索引排序配置与搜索排序条件匹配时,OpenSearch 可以通过限制每个段检查的文档数量来优化查询性能。这种优化对于检索排名靠前的结果特别有效。 + +考虑按时间戳降序排序的索引: + +```json +PUT /events +{ + "settings": { + "index": { + "sort.field": "timestamp", + "sort.order": "desc" + } + }, + "mappings": { + "properties": { + "timestamp": { + "type": "date" + } + } + } +} +``` + +向其添加一些事件: + +```json +POST /events/_bulk?refresh=true +{ "index": {} } +{ "timestamp": "2025-01-01T00:00:00" } +{ "index": {} } +{ "timestamp": "2025-01-02T00:00:00" } +{ "index": {} } +{ "timestamp": "2025-01-03T00:00:00" } +``` + +要检索最近的 10 个事件,请使用以下请求: + +```json +GET /events/_search +{ + "size": 10, + "sort": [ + { + "timestamp": "desc" + } + ] +} +``` + +OpenSearch 识别到段文档已经排序,并且只检查每个段的前 10 个文档,同时仍然收集剩余文档以计算总数和聚合。 + +如果您不需要总命中数,请禁用命中跟踪以获得最大性能: + +```json +GET /events/_search +{ + "size": 10, + "sort": [ + { "timestamp": "desc" } + ], + "track_total_hits": false +} +``` + +这允许 OpenSearch 在找到每个段所需的文档数量后终止收集。 + +::: info NOTE +无论 `track_total_hits` 设置如何,聚合都会处理所有匹配的文档。 +::: + +## 优化合取查询 + +索引排序可以通过组织文档 ID 以分组匹配相似条件的文档来提高合取查询(AND 操作)的性能。这种组织有助于跳过不匹配查询条件的大范围文档。 + +这种技术最适合在过滤器中频繁使用的低基数字段。排序优先级应偏向基数低且过滤频率高的字段。排序方向(升序或降序)对此优化无关紧要。 + +例如,在索引车辆列表时,您可以按燃料类型、车身样式、制造商、年份以及最后里程数进行排序,以优化常见的过滤器组合。 diff --git a/i18n/zh/im-plugin/index-tuning.md b/i18n/zh/im-plugin/index-tuning.md new file mode 100644 index 00000000..7589554b --- /dev/null +++ b/i18n/zh/im-plugin/index-tuning.md @@ -0,0 +1,21 @@ +--- +title: 调优索引 +--- + +# 调优索引 + +本页上的设置更改索引在磁盘上存储数据的方式、其文档在段内的排序方式、匹配文档的评分方式以及它如何向其他功能宣传自己。其中大多数是静态的,因此您在创建索引时设置它们,之后无法更改,除非重新索引。 + +| 主题 | 描述 | +| :--- | :--- | +| [刷新搜索分析器](/im-plugin/refresh-analyzer) | 在不关闭或重新索引索引的情况下更新搜索分析器的同义词列表。 | +| [索引排序](/im-plugin/index-sorting) | 在每个段内对文档进行排序,以便提前终止可以在扫描每个文档之前停止搜索。 | +| [索引编解码器](/im-plugin/index-codecs) | 选择用于存储字段的压缩算法,权衡索引大小与索引和搜索性能。 | +| [相似度](/im-plugin/similarity) | 配置对匹配文档进行评分和排名的算法。 | +| [索引上下文](/im-plugin/index-context) | 为用例(例如日志或指标)应用预定义的设置和映射集。 | + +## 相关文档 + +- [索引设置](/install-and-configure/configuring-opensearch/index-settings) +- [映射和字段类型](/field-types/) +- [索引速度调优](/tuning-your-cluster/performance-tuning/indexing-speed/) diff --git a/i18n/zh/im-plugin/indexing-data.md b/i18n/zh/im-plugin/indexing-data.md new file mode 100644 index 00000000..93660b7a --- /dev/null +++ b/i18n/zh/im-plugin/indexing-data.md @@ -0,0 +1,41 @@ +--- +title: 索引数据 +--- + +# 索引数据 + +OpenSearch 在您首次向尚不存在的名称添加文档时会自动创建索引,并且如果您不提供文档 ID,它会生成一个。以下请求创建 `movies` 索引并向其中索引一个文档: + +```json +POST movies/_doc +{ "title": "Spirited Away" } +``` + +当您希望稍后更新或检索文档时,请自己指定 ID。重复发送以下请求会在索引中留下一个文档并增加其 `_version` 字段,而重复前面的请求每次都会创建一个新文档: + +```json +PUT movies/_doc/1 +{ "title": "Spirited Away" } +``` + +文档 ID 必须为 512 字节或更小。 + +## 索引多个文档 + +要在一个请求中索引多个文档,请使用[批量 API](/api-reference/document-apis/bulk)。每个操作由元数据行和文档本身描述,每一行必须以换行符(`\n`)结尾,包括最后一行: + +```json +POST _bulk +{ "index": { "_index": "movies", "_id": "2" } } +{ "title": "My Neighbor Totoro" } +{ "index": { "_index": "movies", "_id": "3" } } +{ "title": "Princess Mononoke" } +``` + +对于大量文档,批量请求比单个请求提供更好的吞吐量。如果批量请求中的一个操作失败,OpenSearch 会运行其余操作,并在响应的 `items` 数组中按您指定操作的顺序报告每个操作的结果。 + +## 相关文档 + +- [添加和管理您的数据](/getting-started/manage-data/):一个创建索引、向其添加文档并读取它们的教程。 +- [摄取数据](/getting-started/ingest-data/):向 OpenSearch 发送数据的其他方式,例如 OpenSearch Ingestion 和基于拉取的摄取。 +- [文档 API](/api-reference/document-apis/):检索、更新和删除文档。 diff --git a/i18n/zh/im-plugin/ism/policies-examples.md b/i18n/zh/im-plugin/ism/policies-examples.md new file mode 100644 index 00000000..3ccb38b6 --- /dev/null +++ b/i18n/zh/im-plugin/ism/policies-examples.md @@ -0,0 +1,307 @@ +--- +title: 策略示例 +--- + +# 策略示例 + +以下示例是完整的 JSON 格式策略。有关策略的组成部分,请参阅[策略](/im-plugin/ism/policies)。要在 OpenSearch Dashboards 中创建策略,请参阅[创建策略](/im-plugin/ism/policies#creating-a-policy)。要使用 API 创建策略,请参阅 [ISM API](/im-plugin/ism/api)。 + +## 使用 ISM 模板自动滚动的示例策略 + +以下示例模板策略用于滚动用例。 + +如果您想跳过索引的滚动,请在该索引的设置中将 `index.plugins.index_state_management.rollover_skip` 设置为 `true`。 + +1. 创建一个包含 `ism_template` 字段的策略: + + ```json + PUT _plugins/_ism/policies/rollover_policy + { + "policy": { + "description": "Example rollover policy.", + "default_state": "rollover", + "states": [ + { + "name": "rollover", + "actions": [ + { + "rollover": { + "min_doc_count": 1 + } + } + ], + "transitions": [] + } + ], + "ism_template": { + "index_patterns": ["log*"], + "priority": 100 + } + } + } + ``` + + 您需要指定 `index_patterns` 字段。如果您不指定 `priority` 的值,它将默认为 0。 + +2. 设置一个模板,将 `rollover_alias` 设置为 `log`: + + ```json + PUT _index_template/ism_rollover + { + "index_patterns": ["log*"], + "template": { + "settings": { + "plugins.index_state_management.rollover_alias": "log" + } + } + } + ``` + +3. 使用 `log` 别名创建一个索引: + + ```json + PUT log-000001 + { + "aliases": { + "log": { + "is_write_index": true + } + } + } + ``` + +4. 索引一个文档以触发滚动条件: + + ```json + POST log/_doc + { + "message": "dummy" + } + ``` + +5. 验证策略是否已附加到 `log-000001` 索引: + + ```json + GET _plugins/_ism/explain/log-000001?pretty + ``` + +## 使用 ISM 模板进行别名操作的示例策略 + +以下示例策略用于别名操作用例。 + +在以下示例中,第一个作业将触发滚动操作,并创建一个新索引。接下来,向这两个索引添加另一个文档。然后,新作业将导致第二个索引指向 log 别名,由于别名操作,较旧的索引将被删除。 + +首先,创建一个 ISM 策略: + +```json +PUT /_plugins/_ism/policies/rollover_alias_policy +{ + "policy": { + "description": "Example alias action policy.", + "default_state": "rollover", + "states": [ + { + "name": "rollover", + "actions": [ + { + "rollover": { + "min_doc_count": 1 + } + } + ], + "transitions": [{ + "state_name": "alias", + "conditions": { + "min_doc_count": "2" + } + }] + }, + { + "name": "alias", + "actions": [ + { + "alias": { + "actions": [ + { + "remove": { + "alias": "alias-log" + } + } + ] + } + } + ] + } + ], + "ism_template": { + "index_patterns": ["alias-log*"], + "priority": 100 + } + } +} +``` + +::: info NOTE +如果一个 `ism_template` 的索引模式与相同优先级的现有策略的索引模式重叠,则会被拒绝,因此此策略使用自己的 `alias-log*` 模式,而不是前面示例的 `log*` 模式。 +::: + +接下来,创建一个索引模板以启用该策略: + +```json +PUT /_index_template/ism_rollover_alias +{ + "index_patterns": ["alias-log*"], + "template": { + "settings": { + "plugins.index_state_management.rollover_alias": "alias-log" + } + } +} +``` + +接下来,更改集群设置以每分钟触发一次作业: + +```json +PUT /_cluster/settings?pretty=true +{ + "persistent" : { + "plugins.index_state_management.job_interval" : 1 + } +} +``` + +接下来,创建一个新索引: + +```json +PUT /alias-log-000001 +{ + "aliases": { + "alias-log": { + "is_write_index": true + } + } +} +``` + +最后,向索引添加一个文档以触发作业: + +```json +POST /alias-log-000001/_doc +{ + "message": "dummy" +} +``` + +您可以使用别名和索引 API 验证这些步骤: + +```json +GET /_cat/indices?pretty +``` + +```json +GET /_cat/aliases?pretty +``` + +::: danger WARNING +别名操作策略不允许使用 `index` 和 `remove_index` 参数。只允许使用 `add` 和 `remove` 别名操作参数。 +::: + +完成后,将作业间隔恢复为其默认值,以便缩短的间隔不会应用于集群中的每个托管索引: + +```json +PUT /_cluster/settings +{ + "persistent" : { + "plugins.index_state_management.job_interval" : null + } +} +``` + +## 示例策略 + +以下示例策略实现了 `hot`、`warm` 和 `delete` 工作流。您可以使用此策略作为模板,根据索引的活动级别将资源优先分配给它们。 + +在这种情况下,索引最初处于 `hot` 状态。7 天后,它变为 `warm` 状态,副本数减少到 1,并且索引被移动到具有 `warm` 属性的节点。 + +30 天后,策略将此索引移至 `delete` 状态。服务向 Chime 房间发送一条通知,表明索引正在被删除,然后永久删除它。 + +```json +PUT _plugins/_ism/policies/hot_warm_delete_policy +{ + "policy": { + "description": "hot warm delete workflow", + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [ + { + "rollover": { + "min_index_age": "7d", + "min_primary_shard_size": "30gb" + } + } + ], + "transitions": [ + { + "state_name": "warm" + } + ] + }, + { + "name": "warm", + "actions": [ + { + "replica_count": { + "number_of_replicas": 1 + } + }, + { + "allocation": { + "require": { + "temp": "warm" + } + } + } + ], + "transitions": [ + { + "state_name": "delete", + "conditions": { + "min_index_age": "30d" + } + } + ] + }, + { + "name": "delete", + "actions": [ + { + "notification": { + "destination": { + "chime": { + "url": "<URL>" + } + }, + "message_template": { + "source": "The index {{ctx.index}} is being deleted" + } + } + }, + { + "delete": {} + } + ] + } + ], + "ism_template": { + "index_patterns": ["index-*"], + "priority": 100 + } + } +} +``` + +此图将前面策略的 `states`、`transitions` 和 `actions` 显示为有限状态机。有关有限状态机的更多信息,请参阅[维基百科](https://en.wikipedia.org/wiki/Finite-state_machine)。 + +![Policy State Machine](/images/ism.png) diff --git a/i18n/zh/im-plugin/ism/policies-operations.md b/i18n/zh/im-plugin/ism/policies-operations.md new file mode 100644 index 00000000..ec9260ce --- /dev/null +++ b/i18n/zh/im-plugin/ism/policies-operations.md @@ -0,0 +1,752 @@ +--- +title: ISM 支持的操作 +--- + +# ISM 支持的操作 + +ISM 支持以下操作: + +- [强制合并](#force-merge) +- [只读](#read-only) +- [读写](#read-write) +- [发布字段域](#publish-field-domains) +- [副本计数](#replica-count) +- [收缩](#shrink) +- [关闭](#close) +- [打开](#open) +- [删除](#delete) +- [滚动](#rollover) +- [通知](#notification) +- [快照](#snapshot) +- [将索引转换为远程](#convert-index-to-remote) +- [索引优先级](#index-priority) +- [分配](#allocation) +- [汇总](#rollup) +- [停止复制](#stop-replication) +- [仅搜索](#search-only) + +## 强制合并 + +通过合并各个分片的段来减少 Lucene 段的数量。此操作会在开始合并过程之前尝试将索引设置为 `read-only` 状态。 + +参数 | 描述 | 类型 | 必需 +:--- | :--- |:--- |:--- | +`max_num_segments` | 要将分片减少到的段数。 | Integer | 是 + +以下示例将每个分片的段合并为单个段: + +```json +{ + "force_merge": { + "max_num_segments": 1 + } +} +``` + +## 只读 + +将托管索引设置为只读。 + +`read_only` 操作不带参数: + +```json +{ + "read_only": {} +} +``` + +将托管索引的索引设置 `index.blocks.write` 设置为 `true`。 + +::: info NOTE +`index.blocks.write` 块不会阻止索引刷新。 +::: + +## 读写 + +将托管索引设置为可写。 + +`read_write` 操作不带参数: + +```json +{ + "read_write": {} +} +``` + +## 发布字段域 +<Badge type="tip" text="3.9 版本引入" /> + +计算托管索引的字段域并将其发布到索引元数据。OpenSearch 使用字段域进行[索引级搜索修剪](/search-plugins/index-level-search-pruning)。 + +字段域包含一个索引中字段的最小值和最大值。`date_range` 字段域类型适用于 `date` 和 `date_nanos` 字段。对于 `date` 字段,ISM 以纪元毫秒为单位存储边界;对于 `date_nanos` 字段,ISM 以纪元纳秒为单位存储边界。 + +在计算字段域之前,ISM 会刷新索引。然后,它计算每个配置字段的最小值和最大值,并将它们发布到索引的 `index_field_domains` 元数据。如果配置的字段在索引中没有值,ISM 不会为该字段发布字段域,如果没有生成字段域,则操作完成而不发布任何字段域。 + +参数 | 描述 | 类型 | 必需 +:--- | :--- |:--- |:--- | +`fields` | ISM 计算和发布字段域的字段。 | Array | 是 +`fields.field` | 字段名称。 | String | 是 +`fields.type` | 字段域类型。有效值为 `date_range`。 | String | 是 + +以下示例为 `@timestamp` 字段发布 `date_range` 字段域: + +```json +{ + "publish_field_domains": { + "fields": [ + { + "field": "@timestamp", + "type": "date_range" + } + ] + } +} +``` + +托管索引必须在此操作运行之前被写入阻止,因此在 `publish_field_domains` 之前添加 `read_only` 操作: + +```json +{ + "actions": [ + { + "read_only": {} + }, + { + "publish_field_domains": { + "fields": [ + { + "field": "@timestamp", + "type": "date_range" + } + ] + } + } + ] +} +``` + +::: warning IMPORTANT +仅对在发布后保持写入阻止的索引使用此操作。如果恢复写入,新文档可能超出已发布的字段域,修剪可能会跳过包含匹配文档的索引,从而静默地从搜索中删除结果。 +::: + +如果启用了 Security 插件,ISM 执行用户必须具有使用 `indices:admin/field_domains/put` 操作发布字段域的权限。 + +## 副本计数 + +设置要分配给索引的副本数。 + +参数 | 描述 | 类型 | 必需 +:--- | :--- |:--- |:--- | +`number_of_replicas` | 定义要分配给索引的副本数。 | Integer | 是 + +以下示例为索引分配两个副本: + +```json +{ + "replica_count": { + "number_of_replicas": 2 + } +} +``` + +有关设置副本的信息,请参阅[主分片和副本分片](/intro#primary-and-replica-shards)。 + +## 收缩 + +允许您减少索引中主分片的数量。使用此操作,您可以指定: + +- 目标索引应包含的主分片数量。 +- 目标索引中主分片的最大分片大小。 +- 指定一个百分比来收缩目标索引中主分片的数量。 + +以下示例将索引收缩为一个主分片,通过将 `_shrunken` 附加到源索引名称来命名目标索引,并添加 `my-alias` 别名: + +```json +"shrink": { + "num_new_shards": 1, + "target_index_name_template": { + "source": "{{ctx.index}}_shrunken" + }, + "aliases": [ + { + "my-alias": {} + } + ], + "switch_aliases": true, + "force_unsafe": false +} +``` + +参数 | 描述 | 类型 | 示例 | 必需 +:--- | :--- |:--- |:--- | +`num_new_shards` | 收缩索引中主分片的最大数量。 | Integer | `5` | 是。但是,它不能与 `max_shard_size` 或 `percentage_of_source_shards` 一起使用。 +`max_shard_size` | 目标索引的分片的最大大小(以字节为单位)。 | Keyword | `5gb` | 是,但是,它不能与 `num_new_shards` 或 `percentage_of_source_shards` 一起使用。 +`percentage_of_source_shards` | 要收缩的原始主分片数量的百分比。此参数指示收缩主分片数量时要使用的最小百分比。必须在 0.0 和 1.0 之间,不包括。 | Percentage | `0.5` | 是,但不能与 `max_shard_size` 或 `num_new_shards` 一起使用 +`target_index_name_template` | 收缩索引的名称。接受字符串和 Mustache 变量 `{{ctx.index}}` 和 `{{ctx.indexUuid}}`。 | String 或 Mustache 模板 | `{"source": "{{ctx.index}}_shrunken"}` | 否 +`aliases` | 要添加到新索引的别名。 | Object | `myalias` | 否。它必须是别名对象的数组。 +`switch_aliases` | 如果为 `true`,则将别名从源索引复制到目标索引。如果与 `aliases` 字段中的别名存在名称冲突,则使用 `aliases` 字段中的别名。 | Boolean | `true` | 否。默认隐式值为 `false`,这意味着默认情况下不复制任何别名。 +`force_unsafe` | 如果为 `true`,即使索引没有副本也会收缩索引。 | Boolean | `false` | 否 + +如果您想将 `aliases` 添加到操作中,参数必须包含一个[别名对象](/api-reference/alias/)数组,如以下示例所示: + +```json +"aliases": [ + { + "my-alias": {} + }, + { + "my-second-alias": { + "is_write_index": false, + "filter": { + "multi_match": { + "query": "QUEEN", + "fields": ["speaker", "text_entry"] + } + }, + "index_routing" : "1", + "search_routing" : "1" + } + } +] +``` + +## 关闭 + +关闭托管索引。 + +`close` 操作不带参数: + +```json +{ + "close": {} +} +``` + +关闭的索引仍保留在磁盘上,但不占用 CPU 或内存。您无法从关闭的索引读取、写入或搜索。 + +如果您需要保留数据的时间比需要主动搜索的时间更长,并且数据节点上有足够的磁盘空间,关闭索引是一个不错的选择。如果您需要再次搜索数据,重新打开关闭的索引比从快照恢复索引更简单。 + +## 打开 + +打开托管索引。 + +`open` 操作不带参数: + +```json +{ + "open": {} +} +``` + +## 删除 + +删除托管索引。 + +`delete` 操作不带参数: + +```json +{ + "delete": {} +} +``` + +## 滚动 + +当托管索引满足滚动条件之一时,将别名滚动到新索引。 + +<p id="important-note"></p> + +::: warning IMPORTANT +> **重要** +> +>ISM 根据**设置的间隔**,在**策略的每次执行时**检查操作的条件,_而不是_连续检查。如果在执行检查时值**已达到**或_已超过_配置的限制,则将执行滚动。例如,如果 `min_size` 配置为 100 GiB 的值,ISM 可能会在 99 GiB 时检查索引并且不执行滚动。但是,如果到下一次检查时索引已超过限制(例如,到 105 GiB),则执行该操作。 +::: + +如果您需要跳过滚动操作,可以将索引设置 `index.plugins.index_state_management.rollover_skip` 设置为 `true`。例如,如果您收到错误消息"Missing alias or not the write index...",您可以将 `index.plugins.index_state_management.rollover_skip` 参数设置为 `true` 并重试以跳过滚动操作。 + +索引格式必须匹配模式:`^.*-\d+$`。例如,`(logs-000001)`。 +将 `index.plugins.index_state_management.rollover_alias` 设置为要滚动的别名。 + +`rollover` 操作具有以下参数,所有参数都是可选的。 + +参数 | 描述 | 类型 | 示例 +:--- | :--- |:--- |:--- +`min_size` | 滚动索引所需的总主分片存储的最小大小(不计算副本)。例如,如果您将 `min_size` 设置为 100 GiB,并且您的索引有 5 个主分片和 5 个副本分片,每个分片 20 GiB,则所有主分片的总大小为 100 GiB,因此发生滚动。请参阅[**重要**说明](#important-note)。 | String | `20gb` 或 `5mb` +`min_primary_shard_size` | 滚动索引所需的**单个主分片**的最小存储大小。例如,如果您将 `min_primary_shard_size` 设置为 30 GiB,并且索引中的**一个**主分片的大小大于该条件,则发生滚动。请参阅[**重要**说明](#important-note)。 | String | `20gb` 或 `5mb` +`min_doc_count` | 滚动索引所需的最小文档数。请参阅[**重要**说明](#important-note)。 | Integer | `2000000` +`min_index_age` | 滚动索引所需的最小年龄。索引年龄是其创建时间与当前时间之间的时间。支持的单位是 `d`(天)、`h`(小时)、`m`(分钟)、`s`(秒)、`ms`(毫秒)和 `micros`(微秒)。请参阅[**重要**说明](#important-note)。 | String | `5d` 或 `7h` +`copy_alias` | 控制是否将所有别名从当前索引复制到新创建的索引。默认值为 `false`。 | Boolean | `true` 或 `false` +`prevent_empty_rollover` | 控制当索引不包含文档时是否跳过滚动。当为 `true` 时,空索引不会滚动。默认值为 `false`。 | Boolean | `true` 或 `false` +`any_of` | 条件组列表。每个组是一个包含 `min_size`、`min_primary_shard_size`、`min_doc_count` 和 `min_index_age` 中的一个或多个的对象。在组内,条件用 AND 组合;组之间用 OR 组合。与直接在 `rollover` 对象上设置的条件互斥。同时指定两者、空列表或空组会返回错误。 | Array | `[{"min_index_age": "7d"}]` + +直接在 `rollover` 对象上设置的条件与逻辑 OR 组合,因此一旦满足其中一个条件,就会发生滚动。以下滚动操作在索引至少 7 天或至少 50 GiB 时滚动索引: + +```json +{ + "rollover": { + "min_index_age": "7d", + "min_size": "50gb" + } +} +``` + +要要求同时满足多个条件,请使用 `any_of`。此参数接受一个条件组列表。组内的条件用 AND 组合,组之间用 OR 组合,因此当至少一个组中的每个条件都满足时,就会发生滚动。 + +以下滚动操作在索引至少 7 天且至少 50 GiB 时,或者当它达到 100,000,000 个文档时滚动索引: + +```json +{ + "rollover": { + "any_of": [ + { + "min_index_age": "7d", + "min_size": "50gb" + }, + { + "min_doc_count": 100000000 + } + ] + } +} +``` + +::: info NOTE +在混合版本集群中,每个节点都必须运行 OpenSearch 3.7 或更高版本才能评估分组条件。运行早期版本的节点不处理 `any_of`。 +::: + +## 通知 + +向您发送通知。 + +参数 | 描述 | 类型 | 必需 +:--- | :--- |:--- |:--- | +`destination` | 目标 URL。 | Slack、Amazon Chime 或 webhook URL | 是 +`message_template` | 消息的文本。您可以使用 [Mustache 模板](https://mustache.github.io/mustache.5.html)向消息添加变量。 | Object | 是 + +目标系统**必须**返回响应,否则通知操作会抛出错误。 + +### 示例 1:Chime 通知 + +以下通知操作向 Amazon Chime webhook 发送消息: + +```json +{ + "notification": { + "destination": { + "chime": { + "url": "<url>" + } + }, + "message_template": { + "source": "the index is {{ctx.index}}" + } + } +} +``` + +### 示例 2:自定义 webhook 通知 + +以下通知操作向自定义 webhook 发送消息: + +```json +{ + "notification": { + "destination": { + "custom_webhook": { + "url": "https://<your_webhook>" + } + }, + "message_template": { + "source": "the index is {{ctx.index}}" + } + } +} +``` + +### 示例 3:Slack 通知 + +以下通知操作向 Slack webhook 发送消息: + +```json +{ + "notification": { + "destination": { + "slack": { + "url": "https://hooks.slack.com/services/xxx/xxxxxx" + } + }, + "message_template": { + "source": "the index is {{ctx.index}}" + } + } +} +``` + +您可以在消息中使用 `ctx` 变量来表示基于策略过去执行的许多策略参数。例如,如果您的策略有滚动操作,您可以在消息中使用 `{{ctx.action.name}}` 来表示滚动的名称。 + +以下 `ctx` 变量选项适用于每个策略: + +### 保证的变量 + +参数 | 描述 | 类型 +:--- | :--- |:--- |:--- | +`index` | 索引的名称。 | String +`index_uuid` | 索引的 UUID。 | String +`policy_id` | 策略的名称。 | String + +## 快照 + +备份集群的索引和状态。有关快照的更多信息,请参阅[拍摄和恢复快照](/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore)。 + +`snapshot` 操作具有以下参数。 + +参数 | 描述 | 类型 | 必需 | 默认值 +:--- | :--- |:--- |:--- | +`repository` | 您通过本机快照 API 操作注册的存储库名称。 | String | 是 | - +`snapshot` | 快照的名称。接受字符串和 Mustache 变量 `{{ctx.index}}` 和 `{{ctx.indexUuid}}`。如果 Mustache 变量无效,则快照名称默认为索引的名称。 | String 或 Mustache 模板 | 是 | - + +以下示例在 `my_backup` 存储库中拍摄索引的快照,并使用索引 UUID 命名快照: + +```json +{ + "snapshot": { + "repository": "my_backup", + "snapshot": "{{ctx.indexUuid}}" + } +} +``` + +## 将索引转换为远程 + +通过从远程快照存储库恢复现有索引,将其转换为可搜索快照。此操作通过将不经常访问的数据移动到远程存储同时保持其可搜索性来降低存储成本。将 `delete_original_index` 设置为 `true` 以在接受恢复请求后删除原始索引,这样只保留远程快照支持的索引。 + +`convert_index_to_remote` 操作具有以下参数。 + +参数 | 描述 | 类型 | 必需 | 默认值 +:--- | :--- |:--- |:--- | +`repository` | 通过本机快照 API 操作注册的存储库名称。必须是远程存储库(例如,S3、Azure 或 GCS)。 | String | 是 | N/A +`snapshot` | 由快照操作创建的快照名称。 | String | 是 | N/A +`include_aliases` | 在恢复操作期间是否包含索引别名。如果为 `true`,则与原始索引关联的所有别名都将与远程索引一起恢复。如果您的应用程序使用别名访问索引,请将此参数设置为 `true`。 | Boolean | 否 | `false` +`ignore_index_settings` | 在恢复操作期间要忽略的索引设置的逗号分隔列表。例如,`index.refresh_interval,index.number_of_replicas`。当您想要对恢复的远程索引应用与原始索引中配置的不同的设置时,这很有用。 | String | 否 | 空字符串 +`number_of_replicas` | 要为恢复的远程索引配置的副本数。这允许您在转换过程中控制副本分配,而无需单独的更新操作。在转换期间设置 `number_of_replicas` 有助于防止集群进入黄色状态或在副本分配期间产生不必要的负载。 | Integer | 否 | `0` +`rename_pattern` | 恢复的可搜索快照索引的命名模式。使用 `$1` 作为原始索引名称的占位符。例如,`remote_$1` 将 `my-index` 重命名为 `remote_my-index`。 | String | 否 | `$1_remote` +`delete_original_index` | 在接受恢复请求后是否删除原始索引。 | Boolean | 否 | `false` + +### 先决条件 + +在使用 `convert_index_to_remote` 操作之前,请确保满足以下条件: + +- 已注册并可访问远程存储库(S3、Azure 或 GCS)。 +- 索引的快照存在于指定的存储库中,通常使用 `snapshot` 操作创建。 +- 存储库名称与快照操作中使用的名称匹配。 + +### 使用说明 + +请注意以下内容,以确保在将索引恢复为可搜索快照时进行平稳且可预测的转换: + +- 只有在您将 `delete_original_index` 设置为 `true` 时,才会在远程快照恢复成功接受后删除原始索引。默认情况下,原始索引与可搜索快照版本一起保留。 +- `convert_index_to_remote` 操作中使用的存储库名称必须与快照操作期间指定的存储库名称匹配。 +- `actions` 数组中的每个对象都包含一个操作。将 `snapshot` 和 `convert_index_to_remote` 放在同一个对象中是可以接受的,但只会存储其中一个,因此永远不会拍摄快照。将每个操作列在自己的对象中。 +- 您可以使用 Mustache 变量(如 `{{ctx.index}}` 或 `{{ctx.indexUuid}}`)进行动态命名来引用快照。 +- 设置 `number_of_replicas` 时,请考虑集群的容量。如果没有足够的符合条件的节点用于副本恢复,集群可能会进入黄色状态。 + +### 基本示例 + +以下示例显示了使用最少必需参数的基本转换。`snapshot` 操作创建快照,然后 `convert_index_to_remote` 恢复该快照,因此每个操作都是 `actions` 数组中的单独对象: + +```json +"actions": [ + { + "snapshot": { + "repository": "my_backup", + "snapshot": "{{ctx.index}}" + } + }, + { + "convert_index_to_remote": { + "repository": "my_backup", + "snapshot": "{{ctx.index}}" + } + } +] +``` + +### 高级配置示例 + +以下示例演示了使用所有可用的配置选项。此配置包括别名,在恢复期间忽略某些索引设置,并为可搜索快照配置两个副本: + +```json +{ + "convert_index_to_remote": { + "repository": "my_backup", + "snapshot": "daily-snapshot", + "include_aliases": true, + "ignore_index_settings": "index.refresh_interval,index.number_of_replicas", + "number_of_replicas": 0, + "rename_pattern": "remote_$1" + } +} +``` + +### 完整的策略示例 + +以下策略将超过 30 天的索引移动到具有优化设置以提高成本效率的可搜索快照: + +```json +{ + "policy": { + "description": "Convert old indexes to searchable snapshots", + "default_state": "active", + "states": [ + { + "name": "active", + "actions": [], + "transitions": [ + { + "state_name": "archive", + "conditions": { + "min_index_age": "30d" + } + } + ] + }, + { + "name": "archive", + "actions": [ + { + "snapshot": { + "repository": "remote-repo", + "snapshot": "{{ctx.index}}" + } + }, + { + "convert_index_to_remote": { + "repository": "remote-repo", + "snapshot": "{{ctx.index}}", + "include_aliases": true, + "ignore_index_settings": "index.refresh_interval,index.number_of_replicas", + "number_of_replicas": 0 + } + } + ], + "transitions": [] + } + ] + } +} +``` + +## 索引优先级 + +在特定状态下设置索引的优先级。在可能的情况下,索引的未分配分片按其优先级的顺序恢复。具有较高优先级值的索引首先恢复,然后是具有较低优先级值的索引。 + +`index_priority` 操作具有以下参数。 + +参数 | 描述 | 类型 | 必需 | 默认值 +:--- | :--- |:--- |:--- |:--- +`priority` | 索引进入状态后的优先级。 | Integer | 是 | 1 + +以下示例将索引优先级设置为 `50`: + +```json +"actions": [ + { + "index_priority": { + "priority": 50 + } + } +] +``` + +## 分配 + +将索引分配到具有[这样](/tuning-your-cluster/creating-a-cluster/#advanced-step-7-set-up-a-hot-warm-architecture)设置的特定属性的节点。 +例如,将 `require` 设置为 `warm` 会将您的数据仅移动到"warm"节点。 + +`allocation` 操作具有以下参数。必须指定 `require`、`include` 或 `exclude` 中的至少一个。 + +参数 | 描述 | 类型 | 必需 +:--- | :--- |:--- |:--- +`require` | 将索引分配到具有指定属性的节点。 | Object | 否 +`include` | 将索引分配到具有任何指定属性的节点。 | Object | 否 +`exclude` | 不要将索引分配到具有任何指定属性的节点。 | Object | 否 +`wait_for` | 在将索引分配到具有指定属性的节点之前等待策略执行。 | Boolean | 否。默认值为 `false`。 + +以下示例将索引分配到其 `temp` 属性设置为 `warm` 的节点: + +```json +"actions": [ + { + "allocation": { + "require": { "temp": "warm" } + } + } +] +``` + +## 汇总 + +[索引汇总](/im-plugin/index-rollups/)允许您定期通过将旧数据汇总到摘要索引中来减少数据粒度。在 `ism_rollup` 对象中定义作业。有关它接受的字段,请参阅[创建或更新索引汇总作业](/im-plugin/index-rollups/rollup-api#create-or-update-an-index-rollup-job)。 + +::: info NOTE +汇总作业可以是连续的或非连续的。使用 ISM 策略创建的汇总作业只能是非连续的。 +::: + +以下策略将 `opensearch_dashboards_sample_data_ecommerce` 字段汇总到 `target` 索引中的每小时存储桶中: + +```json +PUT _plugins/_ism/policies/sample_rollup_policy +{ + "policy": { + "description": "Sample rollup" , + "default_state": "rollup", + "states": [ + { + "name": "rollup", + "actions": [ + { + "rollup": { + "ism_rollup": { + "description": "Creating rollup through ISM", + "target_index": "target", + "target_index_settings":{ + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index.codec": "best_compression" + }, + "page_size": 1000, + "dimensions": [ + { + "date_histogram": { + "fixed_interval": "60m", + "source_field": "order_date", + "target_field": "order_date", + "timezone": "America/Los_Angeles" + } + }, + { + "terms": { + "source_field": "customer_gender", + "target_field": "customer_gender" + } + }, + { + "terms": { + "source_field": "day_of_week", + "target_field": "day_of_week" + } + } + ], + "metrics": [ + { + "source_field": "taxless_total_price", + "metrics": [ + { + "sum": {} + } + ] + }, + { + "source_field": "total_quantity", + "metrics": [ + { + "avg": {} + }, + { + "max": {} + } + ] + } + ] + } + } + } + ], + "transitions": [] + } + ] + } +} +``` + +要在 OpenSearch Dashboards 中创建汇总作业,请参阅[创建汇总作业](/im-plugin/index-rollups/#creating-a-rollup-job)。 + +## 停止复制 + +停止复制并将跟随者索引转换为常规索引。 + +`stop_replication` 操作不带参数: + +```json +{ + "stop_replication": {} +} +``` + +启用跨集群复制时,跟随者索引将变为只读,从而阻止所有写入操作。要管理跟随者集群上的复制索引,您可以在执行其他写入操作之前执行 `stop_replication` 操作。例如,您可以定义一个策略,该策略首先运行 `stop_replication`,然后通过运行 `delete` 操作删除索引。 + +::: info NOTE +如果启用了安全性,除了[停止复制权限](/tuning-your-cluster/replication-plugin/permissions#replication-permissions)之外,您还必须具有 `indices:internal/plugins/replication/index/stop` 权限才能使用 `stop_replication` 操作。 +::: + +## 仅搜索 + +当索引进入 `search_only` 模式时,OpenSearch 会删除其主分片和常规副本分片,同时保留搜索副本用于查询操作。对索引的所有写入操作都被阻止。这对于日志生命周期管理很有用,其中较旧的索引不再需要写入功能,但应保持可搜索。 + +::: info NOTE +> 此操作需要以下先决条件: +> - 必须在集群上启用远程存储。 +> - 必须在索引上启用分段复制。 +> - 必须在索引上配置搜索副本。 +> +> 有关仅搜索模式和读取器/写入器分离的更多信息,请参阅[分离索引和搜索工作负载](/tuning-your-cluster/performance-tuning/separate-index-and-search-workloads/)。 +::: + +使用以下操作将索引设置为仅搜索模式: + +```json +{ + "search_only": {} +} +``` + +如果索引已处于仅搜索模式,则操作成功完成而不进行任何更改。 + +::: tip TIP +您可以在 ISM 策略之外手动启用或禁用 `search_only` 模式,方法是调用 [Scale API](/api-reference/index-apis/scale)。 +::: + +以下示例策略在 7 天后将索引转换为 `search_only` 模式: + +```json +PUT _plugins/_ism/policies/hot-warm-search-only +{ + "policy": { + "description": "Move indexes to search-only mode after 7 days", + "default_state": "hot", + "states": [ + { + "name": "hot", + "actions": [], + "transitions": [ + { + "state_name": "warm", + "conditions": { + "min_index_age": "7d" + } + } + ] + }, + { + "name": "warm", + "actions": [ + { + "search_only": {} + } + ], + "transitions": [] + } + ] + } +} +``` diff --git a/i18n/zh/im-plugin/ism/restore.md b/i18n/zh/im-plugin/ism/restore.md new file mode 100644 index 00000000..98b7a8d9 --- /dev/null +++ b/i18n/zh/im-plugin/ism/restore.md @@ -0,0 +1,40 @@ +--- +title: 从快照恢复 ISM +--- + +# 从快照恢复 ISM +<Badge type="tip" text="3.10 版本引入" /> + +索引状态管理 (ISM) 将策略和每个[托管索引](/im-plugin/ism/managedindexes)的策略进度存储在 `.opendistro-ism-config` 系统索引中。如果您从快照恢复 `.opendistro-ism-config`,例如在迁移到另一个集群时,每个托管索引都会从快照中记录的状态恢复其策略。要使托管索引恢复其策略,您必须在恢复 `.opendistro-ism-config` 之前恢复它们。 + +## 恢复顺序 + +ISM 只有在索引在恢复 `.opendistro-ism-config` 时已经存在的情况下,才能将索引与其保存的进度匹配。ISM 使用索引名称和创建日期将保存的进度与索引匹配。如果删除了一个索引,然后以相同的名称重新创建,它将具有新的创建日期。ISM 不会将重新创建的索引与其保存的进度匹配,因此索引从头开始其策略。 + +使用[恢复快照 API](/api-reference/snapshots/restore-snapshot),按以下顺序恢复索引: + +1. 恢复托管索引并等待恢复操作完成: + + ```json + POST /_snapshot/my-repository/snapshot-1/_restore?wait_for_completion=true + { + "indices": "my-index-*", + "include_global_state": false + } + ``` + +1. 在单独的请求中恢复 `.opendistro-ism-config`: + + ```json + POST /_snapshot/my-repository/snapshot-1/_restore + { + "indices": ".opendistro-ism-config", + "include_global_state": false + } + ``` + +如果您首先恢复 `.opendistro-ism-config` 或在与托管索引相同的请求中恢复它,ISM 无法将托管索引与其保存的进度匹配。由 ISM 模板附加到策略的索引从头开始重新启动策略。ISM 停止管理使用[添加策略 API](/im-plugin/ism/api#add-policy) 附加的索引。 + +## 权限 + +如果 Security 插件保护集群中的系统索引,则恢复 `.opendistro-ism-config` 需要恢复系统索引的权限。如果索引在 `plugins.security.system_indices.restore.indices` 设置中列出,则映射到 `plugins.security.restapi.roles_enabled` 中的角色的用户可以恢复系统索引。`.opendistro-ism-config` 默认列出。您还可以使用超级管理员或使用系统索引权限恢复系统索引。有关更多信息,请参阅[谁可以恢复系统索引](/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore#who-can-restore-system-indexes)。 diff --git a/i18n/zh/im-plugin/processors/fingerprint.md b/i18n/zh/im-plugin/processors/fingerprint.md new file mode 100644 index 00000000..489a73d1 --- /dev/null +++ b/i18n/zh/im-plugin/processors/fingerprint.md @@ -0,0 +1,148 @@ +--- +title: 指纹处理器 +--- + +# 指纹处理器 +<Badge type="tip" text="2.16 版本引入" /> + +`fingerprint` 处理器用于为某些指定字段或文档中的所有字段生成哈希值。哈希值可用于对索引内的文档进行去重以及折叠搜索结果。 + +对于每个字段,将字段名称、字段值的长度和字段值本身连接起来,并用管道字符 `|` 分隔。例如,如果字段名称为 `field1`,值为 `value1`,则连接字符串为 `|field1|3:value1|field2|10:value2|`。对于对象字段,通过用句点 `.` 连接嵌套字段名称来展平字段名称。例如,如果对象字段为 `root_field`,其子字段 `sub_field1` 的值为 `value1`,另一个子字段 `sub_field2` 的值为 `value2`,则连接字符串为 `|root_field.sub_field1|1:value1|root_field.sub_field2|100:value2|`。 + +以下是 `fingerprint` 处理器的语法: + +```json +{ + "community_id": { + "fields": ["foo", "bar"], + "target_field": "fingerprint", + "hash_method": "SHA-1@2.16.0" + } +} +``` + +## 参数 + +下表列出了 `fingerprint` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`fields` | 可选 | 用于生成哈希值的字段列表。 | +`exclude_fields` | 可选 | 指定要从哈希值生成中排除的字段。它与 `fields` 参数互斥;如果 `exclude_fields` 和 `fields` 都为空或 null,则哈希值计算中包含所有字段。 | +`hash_method` | 可选 | 指定要使用的哈希算法,选项为 `MD5@2.16.0`、`SHA-1@2.16.0`、`SHA-256@2.16.0` 或 `SHA3-256@2.16.0`。默认值为 `SHA-1@2.16.0`。附加版本号以确保跨 OpenSearch 版本的一致哈希,新版本将支持新的哈希方法。 | +`target_field` | 可选 | 指定将存储生成的哈希值的字段名称。如果未提供,则默认将哈希值存储在 `fingerprint` 字段中。 | +`ignore_missing` | 可选 | 指定如果缺少所需字段之一,处理器是否应安静退出。默认值为 `false`。 | +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 如果设置为 `true`,则忽略失败。默认值为 `false`。 | +`on_failure` | 可选 | 如果处理器失败则运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1: 创建管道 + +以下查询创建一个名为 `fingerprint_pipeline` 的管道,该管道使用 `fingerprint` 处理器为文档中的指定字段生成哈希值: + +```json +PUT /_ingest/pipeline/fingerprint_pipeline +{ + "description": "generate hash value for some specified fields the document", + "processors": [ + { + "fingerprint": { + "fields": ["foo", "bar"] + } + } + ] +} +``` + +### 步骤 2(可选): 测试管道 + +::: tip TIP +建议您在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/fingerprint_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "foo": "foo", + "bar": "bar" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "foo": "foo", + "bar": "bar", + "fingerprint": "SHA-1@2.16.0:fYeen7hTJ2zs9lpmUnk6nvH54sM=" + }, + "_ingest": { + "timestamp": "2024-03-11T02:17:22.329823Z" + } + } + } + ] +} +``` + +### 步骤 3: 摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=fingerprint_pipeline +{ + "foo": "foo", + "bar": "bar" +} +``` + +该请求将文档索引到 `testindex1` 索引中: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### 步骤 4(可选): 检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中响应所示进行转换。 diff --git a/i18n/zh/im-plugin/processors/foreach.md b/i18n/zh/im-plugin/processors/foreach.md new file mode 100644 index 00000000..fe5cd6dd --- /dev/null +++ b/i18n/zh/im-plugin/processors/foreach.md @@ -0,0 +1,309 @@ +--- +title: Foreach 处理器 +--- + +<!-- vale off --> +# Foreach 处理器 +<!-- vale on --> + +`foreach` 处理器用于遍历输入文档中的值列表,并对每个值应用转换。这对于一致地处理数组中的所有元素的任务很有用,例如将数组中的所有元素转换为小写或大写。 + +以下是 `foreach` 处理器的语法: + +```json +{ + "foreach": { + "field": "<field_name>", + "processor": { + "<processor_type>": { + "<processor_config>": "<processor_value>" + } + } + } +} +``` + +## 参数 + +下表列出了 `foreach` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 要遍历的数组字段。 +`processor` | 必需 | 要为数组的每个元素运行的处理器。 +`ignore_missing` | 可选 | 如果为 `true` 且指定的字段不存在或为 null,则处理器将安静退出而不修改文档。默认值为 `false`。 +`description` | 可选 | 处理器的简要描述。 +`if` | 可选 | 运行处理器的条件。 +`ignore_failure` | 可选 | 指定处理器是否在遇到错误时继续执行。如果设置为 `true`,则忽略失败。默认值为 `false`。 +`on_failure` | 可选 | 如果处理器失败则运行的处理器列表。 +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 访问数组元素 + +对于每个数组元素,`foreach` 处理器将元素存储在 `_ingest._value` 摄取元数据字段中,然后运行内部处理器。要读取或修改当前元素,请将内部处理器的字段设置为 `_ingest._value`。如果元素是对象,则使用点表示法访问其字段,例如 `_ingest._value.name`。 + +内部处理器还可以读取和修改文档中的任何其他字段。 + +当 `foreach` 处理器运行时,`_ingest._value` 始终保存当前数组元素,这会隐藏较早的处理器存储在 `_ingest._value` 中的任何值。当循环结束时,OpenSearch 将较早的值放回,因此管道后面的处理器仍然可以读取它。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1: 创建管道 + +以下查询创建一个名为 `test-foreach` 的管道,该管道使用 `foreach` 处理器遍历 `protocols` 字段中的每个元素: + +```json +PUT _ingest/pipeline/test-foreach +{ + "description": "Lowercase all the elements in an array", + "processors": [ + { + "foreach": { + "field": "protocols", + "processor": { + "lowercase": { + "field": "_ingest._value" + } + } + } + } + ] +} +``` + +### 步骤 2(可选): 测试管道 + +::: tip TIP +建议您在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/test-foreach/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "protocols": ["HTTP","HTTPS","TCP","UDP"] + } + } + ] +} +``` + +以下示例响应确认管道按预期工作,显示四个元素已转换为小写: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "protocols": [ + "http", + "https", + "tcp", + "udp" + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2024-05-23T02:44:10.8201Z" + } + } + } + ] +} + +``` + +### 步骤 3: 摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +POST testindex1/_doc/1?pipeline=test-foreach +{ + "protocols": ["HTTP","HTTPS","TCP","UDP"] +} +``` + +该请求将文档索引到 `testindex1` 索引中,并在索引之前应用管道: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 6, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 5, + "_primary_term": 67 +} +``` + +### 步骤 4(可选): 检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中响应所示进行转换。 + +## 处理对象数组 + +以下请求从 `products` 数组中的每个对象中删除 `internal_sku` 字段: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "foreach": { + "field": "products", + "processor": { + "remove": { + "field": "_ingest._value.internal_sku" + } + } + } + } + ] + }, + "docs": [ + { + "_source": { + "order_id": "A-1001", + "products": [ + { "name": "Wireless mouse", "price": 24.99, "internal_sku": "WM-4471" }, + { "name": "USB-C cable", "price": 9.99, "internal_sku": "UC-2210" } + ] + } + } + ] +} +``` + +响应显示 `internal_sku` 字段已从两个对象中删除: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "order_id": "A-1001", + "products": [ + { + "name": "Wireless mouse", + "price": 24.99 + }, + { + "name": "USB-C cable", + "price": 9.99 + } + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2026-10-14T19:40:29.753456004Z" + } + } + } + ] +} +``` + +## 处理数组元素的失败 + +如果内部处理器对某个元素失败且未定义 `on_failure`,则 `foreach` 处理器将停止处理数组并失败。 + +要处理单个元素的失败,请在内部处理器中指定 `on_failure`。在以下请求中,`products` 数组中的第二个对象不包含 `internal_sku` 字段,因此 `remove` 处理器对该元素失败。`on_failure` 处理器将文档发送到 `failed-orders` 索引: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "foreach": { + "field": "products", + "processor": { + "remove": { + "field": "_ingest._value.internal_sku", + "on_failure": [ + { + "set": { + "field": "_index", + "value": "failed-orders" + } + } + ] + } + } + } + } + ] + }, + "docs": [ + { + "_index": "orders", + "_source": { + "order_id": "A-1002", + "products": [ + { "name": "Wireless mouse", "price": 24.99, "internal_sku": "WM-4471" }, + { "name": "USB-C cable", "price": 9.99 } + ] + } + } + ] +} +``` + +响应显示目标索引更改为 `failed-orders`。由于 `on_failure` 块处理了失败,`foreach` 处理器继续处理其余元素,成功处理的元素保留了它们的更改: + +```json +{ + "docs": [ + { + "doc": { + "_index": "failed-orders", + "_id": "_id", + "_source": { + "order_id": "A-1002", + "products": [ + { + "name": "Wireless mouse", + "price": 24.99 + }, + { + "name": "USB-C cable", + "price": 9.99 + } + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2026-10-14T19:40:29.808936921Z" + } + } + } + ] +} +``` diff --git a/i18n/zh/im-plugin/pull-based-ingestion/index.md b/i18n/zh/im-plugin/pull-based-ingestion/index.md new file mode 100644 index 00000000..4ea13f20 --- /dev/null +++ b/i18n/zh/im-plugin/pull-based-ingestion/index.md @@ -0,0 +1,222 @@ +--- +title: 拉取式摄取 +--- + +# 拉取式摄取 +<Badge type="tip" text="3.0 版本引入" /> + +拉取式摄取使 OpenSearch 能够从流式源(如 Apache Kafka 或 Amazon Kinesis)或对象存储中的文件摄取数据。与传统的摄取方法(客户端通过 REST API 主动推送数据到 OpenSearch)不同,拉取式摄取允许 OpenSearch 通过直接从源检索数据来控制数据流。这种方法提供原生的背压处理,有助于防止流量高峰期间的服务器过载。拉取式摄取保证至少一次摄取语义,并使用外部版本控制来确保数据一致性。 + +## 支持的源 + +OpenSearch 支持以下拉取式摄取源。每个源都需要自己的插件。 + +| 源 | 插件 | `type` 值 | +| :--- | :--- | :--- | +| [Apache Kafka](/im-plugin/pull-based-ingestion/kafka) | `ingestion-kafka` | `kafka` | +| [Amazon Kinesis](/im-plugin/pull-based-ingestion/kinesis) | `ingestion-kinesis` | `kinesis` | +| [对象存储](/im-plugin/pull-based-ingestion/object-store) | `ingestion-object-store` | `object_store` | + +要暂停、恢复或检查摄取状态,请使用[拉取式摄取管理 API](/api-reference/index-apis/pull-based-ingestion-management)。 + +## 先决条件 + +在使用拉取式摄取之前,请确保满足以下先决条件: + +* 使用命令 `bin/opensearch-plugin install <plugin-name>` 为您的源安装摄取插件。有关更多信息,请参阅[其他插件](/install-and-configure/additional-plugins/)。 +* 在[索引创建](#creating-an-index-for-pull-based-ingestion)期间配置拉取式摄取。您无法将现有的基于推送的索引转换为基于拉取的索引。 + +## 为拉取式摄取创建索引 + +要从源摄取数据,首先创建一个包含 `ingestion_source` 中拉取式摄取设置的索引。有关每个源的示例请求,请参阅[支持的源](#supported-sources)。 + +### 摄取源设置 + +`ingestion_source` 设置控制 OpenSearch 如何从源拉取数据。_轮询_是 OpenSearch 主动从源请求一批数据的操作。下表列出了 `ingestion_source` 支持的所有设置。 + +::: info NOTE +动态设置可以使用[更新设置 API](/api-reference/index-apis/update-settings) 进行更新,而无需重新启动摄取过程。静态设置在索引创建后无法更改。有关静态和动态设置的更多信息,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 +::: + +| 设置 | 动态 | 描述 | +| :--- | :--- | :--- | +| `type` | 否 | 源类型。必需。有效值为 `kafka`、`kinesis` 或 `object_store`。 | +| `pointer.init.reset` | 否 | 确定从哪个流位置开始读取。可选。有效值为 `earliest`、`latest`、`reset_by_offset`、`reset_by_timestamp` 或 `none`。请参阅[流位置](#stream-position)。 | +| `pointer.init.reset.value` | 否 | 仅对 `reset_by_offset` 或 `reset_by_timestamp` 必需。指定偏移值或以毫秒为单位的时间戳。请参阅[流位置](#stream-position)。 | +| `error_strategy` | 是 | 如何处理失败的消息。可选。有效值为 `DROP`(跳过失败的消息并继续摄取)和 `BLOCK`(当消息失败时,摄取停止)。默认值为 `DROP`。 | +| `poll.max_batch_size` | 是 | 每次轮询操作中检索的最大记录数。可选。 | +| `poll.timeout` | 是 | 每次轮询操作中等待数据的最长时间。可选。 | +| `num_processor_threads` | 否 | 用于处理摄取数据的线程数。可选。默认值为 1。 | +| `internal_queue_size` | 否 | 用于高级调优的内部阻塞队列的大小。有效值从 1 到 100,000(含)。可选。默认值为 100。 | +| `all_active` | 否 | 是否启用全活动摄取模式。不能为使用分段复制模式的索引启用。默认值为 `false`。请参阅[摄取模式](#ingestion-modes)。 | +| `pointer_based_lag_update_interval` | 否 | 计算基于指针的延迟的间隔。接受时间单位。默认值为 `10s`。将此值设置为 `0` 将禁用基于指针的延迟计算。 | +| `warmup.timeout` | 是 | 在节点重启或分片重新定位后的预热阶段,等待分片赶上源的最长时间。在预热完成或超时之前,分片不会提供查询。接受时间单位。可选。默认值为 `-1`(禁用)。 | +| `warmup.lag_threshold` | 是 | 预热完成的可接受的基于指针的延迟阈值。当延迟处于或低于此值时,预热完成。值 `0` 表示分片与源同步。可选。默认值为 `100`。 | +| `mapper_type` | 否 | 定义输入消息格式的映射器。有效值为 `default` 和 `raw_payload`。请参阅[消息格式](#message-format)。 | +| `param` | 是 | 源特定的配置参数。必需。有关每个源的参数,请参阅 [Kafka 源参数](/im-plugin/pull-based-ingestion/kafka#source-parameters)、[Kinesis 源参数](/im-plugin/pull-based-ingestion/kinesis#source-parameters) 或[对象存储源参数](/im-plugin/pull-based-ingestion/object-store#source-parameters)。 | + +### 其他设置 + +拉取式摄取支持以下 OpenSearch 设置。 + +| 设置 | 动态 | 描述 | +| :--- | :--- | :--- | +| `index.periodic_flush_interval` | 是 | OpenSearch 触发刷新操作的间隔。拉取式摄取索引的默认值为 `10m`。请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings#periodic-flush-interval)。 | + +### 摄取模式 + +拉取式摄取支持以下模式。 + +#### 分段复制模式 + +在分段复制模式下,主分片从源摄取事件并索引文档。拉取式索引配置为使用[分段复制](/tuning-your-cluster/availability-and-recovery/segment-replication/)将段文件从主分片复制到副本分片,如下图所示。 + +*Pull-based ingestion segment replication mode* + +::: tip TIP +我们建议将此模式与[远程后端存储](/tuning-your-cluster/availability-and-recovery/remote-store/)一起使用。 +::: + +#### 全活动模式 + +启用全活动模式允许主分片和副本分片独立地从源摄取和索引事件,如下图所示。 + +*Pull-based ingestion all active mode* + +分片之间没有复制或协调,尽管在引导期间如果本地副本不可用,副本分片可能会从主分片获取段文件。此模式不支持分段复制。 + +### 流位置 + +创建索引时,您可以通过在 `ingestion_source` 参数中配置 `pointer.init.reset` 和 `pointer.init.reset.value` 设置来指定 OpenSearch 应从流的哪个位置开始读取。对于现有索引,OpenSearch 将从上次提交的位置恢复读取。 + +下表提供了有效的 `pointer.init.reset` 值及其对应的 `pointer.init.reset.value` 值。 + +| `pointer.init.reset` | 开始摄取点 | `pointer.init.reset.value` | +| :--- | :--- | :--- | +| `earliest` | 流的开头 | 无 | +| `latest` | 流的当前结尾 | 无 | +| `reset_by_offset` | 流中的特定偏移量 | 正整数偏移量。必需。 | +| `reset_by_timestamp` | 特定时间戳 | Unix 时间戳(以毫秒为单位)。必需。<br> 对于 Kafka 流,如果未找到给定时间戳的消息,则默认为 Kafka 的 `auto.offset.reset` 策略。 | +| `none` | 现有索引的上次提交位置 | 无 | + +对象存储源仅支持其中一些值。有关更多信息,请参阅[创建索引](/im-plugin/pull-based-ingestion/object-store#creating-an-index)。 + +### 流分区 + +使用分区流(如 Kafka 主题或 Kinesis 分片)时,请注意流分区和 OpenSearch 分片之间的以下关系: + +- OpenSearch 分片与流分区一对一映射。 +- 索引分片数必须大于或等于流分区数。 +- 超出分区数的额外分片保持为空。 +- 文档必须发送到同一分区才能成功更新。 + +对象存储源以不同方式在分片之间划分对象。有关更多信息,请参阅[在分片之间划分对象](/im-plugin/pull-based-ingestion/object-store#dividing-objects-among-shards)。 + +::: info NOTE +使用拉取式摄取时,索引的传统基于 REST API 的摄取被禁用。 +::: + +### 更新错误策略 + +您可以使用[更新设置 API](/api-reference/index-apis/update-settings) 通过将 `index.ingestion_source.error_strategy` 设置为 `DROP` 或 `BLOCK` 来动态更新错误策略。 + +以下示例演示如何更新错误策略: + +<!-- spec_insert_start +component: example_code +rest: PUT /my-index/_settings +body: | +{ + "index.ingestion_source.error_strategy": "DROP" +} +--> + +PUT /my-index/_settings +{ + "index.ingestion_source.error_strategy": "DROP" +} + +response = client.indices.put_settings( + index = "my-index", + body = { + "index.ingestion_source.error_strategy": "DROP" + } +) + +<!-- spec_insert_end --> + +## 消息格式 + +要由 OpenSearch 正确处理,流式源中的消息必须具有以下格式: + +```json +{"_id":"1", "_version":"1", "_source":{"name": "alice", "age": 30}, "_op_type": "index"} +{"_id":"2", "_version":"2", "_source":{"name": "alice", "age": 30}, "_op_type": "delete"} +``` + +流式源中的每个数据单元(Kafka 消息或 Kinesis 记录)必须包含以下字段,这些字段指定如何创建或修改 OpenSearch 文档。这是拉取式摄取支持的默认格式。 + +| 字段 | 数据类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `_id` | String | 否 | 文档的唯一标识符。如果未提供,OpenSearch 会自动生成 ID。文档更新或删除需要。 | +| `_version` | Long | 否 | 文档版本号,必须在外部维护。如果提供,OpenSearch 会丢弃版本早于当前文档版本的消息。如果未提供,则不进行版本检查。 | +| `_op_type` | String | 否 | 要执行的操作。有效值为:<br>- `index`:创建新文档或更新现有文档。<br>- `create`:在追加模式下创建新文档。请注意,这不会更新现有文档。<br>- `delete`:软删除文档。 | +| `_source` | Object | 是 | 包含文档数据的消息负载。 | + +::: tip TIP +我们建议使用文档 `_id` 字段来防止重复,因为拉取式摄取提供至少一次摄取语义。如果您的生产者无法保证事件顺序,还要设置 `_version` 字段以确保数据一致性。 +::: + +或者,拉取式摄取支持在仅追加模式下索引原始负载,而无需转换。要启用此行为,请将 `index.ingestion_source.mapper_type` 设置为 `raw_payload`。请注意,在此模式下,索引映射必须符合消息结构,因为不支持动态映射。使用 `raw_payload` 时,您必须提供原始 JSON 对象,就像它们在传入数据流中出现的那样,如以下示例所示: + +```json +{"name": "alice", "age": 30} +{"name": "bob", "age": 30} +``` + +## 拉取式摄取指标 + +拉取式摄取提供可用于监控摄取过程的指标。`polling_ingest_stats` 指标在分片级别可用。 + +下表列出了可用的 `polling_ingest_stats` 指标。 + +| 指标 | 描述 | +| :--- | :--- | +| `message_processor_stats.total_processed_count` | 消息处理器处理的消息总数。 | +| `message_processor_stats.total_invalid_message_count` | 遇到的无效消息数。 | +| `message_processor_stats.total_version_conflicts_count` | 由于版本冲突而导致旧版本消息被丢弃的数量。 | +| `message_processor_stats.total_failed_count` | 在处理期间出错的失败消息总数。 | +| `message_processor_stats.total_failures_dropped_count` | 在耗尽重试后被丢弃的失败消息总数。请注意,只有在使用 DROP 错误策略时才会丢弃消息。 | +| `message_processor_stats.total_processor_thread_interrupt_count` | 指示处理器线程上的线程中断次数。 | +| `consumer_stats.total_polled_count` | 从流消费者轮询的消息总数。 | +| `consumer_stats.total_consumer_error_count` | 致命消费者读取错误的总数。 | +| `consumer_stats.total_poller_message_failure_count` | 轮询器上失败消息的总数。 | +| `consumer_stats.total_poller_message_dropped_count` | 轮询器上被丢弃的失败消息总数。 | +| `consumer_stats.lag_in_millis` | 以毫秒为单位的延迟,计算为自上次处理的消息时间戳以来经过的时间。 | +| `consumer_stats.pointer_based_lag` | Apache Kafka 基于偏移量的延迟,计算为最新可用偏移量与当前消息偏移量之间的差异。此指标仅在将 Apache Kafka 用作流式源时适用。对于[对象存储源](/im-plugin/pull-based-ingestion/object-store),它是分片仍需要读取的字节数。 | + +要检索分片级别的拉取式摄取指标,请使用[节点统计 API](/api-reference/nodes-apis/nodes-stats): + +<!-- spec_insert_start +component: example_code +rest: GET /_nodes/stats/indices?level=shards&pretty +--> + +GET /_nodes/stats/indices?level=shards&pretty + +response = client.nodes.info( + metric = "indices", + node_id = "stats", + params = { "level": "shards", "pretty": "true" } +) + +<!-- spec_insert_end --> + +## 限制 + +使用拉取式摄取时,以下限制适用: + +* [摄取管道](/ingest-pipelines/)与拉取式摄取不兼容。 +* 不支持[动态映射](/mappings/)。 +* 不支持[索引滚动](/api-reference/index-apis/rollover)。 +* 不支持操作侦听器。 diff --git a/i18n/zh/im-plugin/pull-based-ingestion/kafka.md b/i18n/zh/im-plugin/pull-based-ingestion/kafka.md new file mode 100644 index 00000000..dec2b87a --- /dev/null +++ b/i18n/zh/im-plugin/pull-based-ingestion/kafka.md @@ -0,0 +1,65 @@ +--- +title: Kafka 源 +--- + +# 用于拉取式摄取的 Kafka 源 +<Badge type="tip" text="3.0 版本引入" /> + +`kafka` 源允许索引从 Apache Kafka 主题消费消息。每个 OpenSearch 分片从主题的一个分区读取。有关更多信息,请参阅[流分区](/im-plugin/pull-based-ingestion/#stream-partitioning)。 + +## 先决条件 + +在创建使用 Kafka 源的索引之前,请在每个节点上使用 `bin/opensearch-plugin install ingestion-kafka` 安装 `ingestion-kafka` 插件。 + +## 创建索引 + +以下请求创建一个在分段复制模式下从 Kafka 主题拉取数据的索引。有关其他可用模式,请参阅[摄取模式](/im-plugin/pull-based-ingestion/#ingestion-modes): + +```json +PUT /my-index +{ + "settings": { + "ingestion_source": { + "type": "kafka", + "pointer.init.reset": "earliest", + "param": { + "topic": "test", + "bootstrap_servers": "localhost:49353" + } + }, + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index": { + "replication.type": "SEGMENT" + } + }, + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } +} +``` + +有关所有 `ingestion_source` 设置,请参阅[摄取源设置](/im-plugin/pull-based-ingestion/#ingestion-source-settings)。 + +## 源参数 + +下表列出了源参数。在 `ingestion_source` 的 `param` 对象中指定它们。 + +| 参数 | 必需 | 描述 | +| :--- | :--- | :--- | +| `topic` | 是 | 要消费的 Kafka 主题。 | +| `bootstrap_servers` | 是 | Kafka 服务器地址。 | + +可选地,您可以提供额外的标准 Kafka 消费者参数(例如 `fetch.min.bytes`)。这些参数直接传递给 Kafka 消费者。 + +## 相关文档 + +* [拉取式摄取](/im-plugin/pull-based-ingestion/) +* [拉取式摄取管理 API](/api-reference/index-apis/pull-based-ingestion-management) diff --git a/i18n/zh/im-plugin/pull-based-ingestion/kinesis.md b/i18n/zh/im-plugin/pull-based-ingestion/kinesis.md new file mode 100644 index 00000000..64aab309 --- /dev/null +++ b/i18n/zh/im-plugin/pull-based-ingestion/kinesis.md @@ -0,0 +1,74 @@ +--- +title: Kinesis 源 +--- + +# 用于拉取式摄取的 Kinesis 源 +<Badge type="tip" text="3.0 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +`kinesis` 源允许索引从 Amazon Kinesis 数据流消费记录。每个 OpenSearch 分片从一个 Kinesis 分片读取。有关更多信息,请参阅[流分区](/im-plugin/pull-based-ingestion/#stream-partitioning)。 + +## 先决条件 + +在创建使用 Kinesis 源的索引之前,请在每个节点上使用 `bin/opensearch-plugin install ingestion-kinesis` 安装 `ingestion-kinesis` 插件。 + +## 创建索引 + +以下请求创建一个在分段复制模式下从 Kinesis 流拉取数据的索引。有关其他可用模式,请参阅[摄取模式](/im-plugin/pull-based-ingestion/#ingestion-modes): + +```json +PUT /my-index +{ + "settings": { + "ingestion_source": { + "type": "kinesis", + "pointer.init.reset": "earliest", + "param": { + "stream": "test", + "region": "us-east-1", + "access_key": "<access_key>", + "secret_key": "<secret_key>" + } + }, + "index.number_of_shards": 1, + "index.number_of_replicas": 1, + "index": { + "replication.type": "SEGMENT" + } + }, + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } +} +``` + +有关所有 `ingestion_source` 设置,请参阅[摄取源设置](/im-plugin/pull-based-ingestion/#ingestion-source-settings)。 + +## 源参数 + +下表列出了源参数。在 `ingestion_source` 的 `param` 对象中指定它们。 + +| 参数 | 必需 | 描述 | +| :--- | :--- | :--- | +| `stream` | 是 | Kinesis 流名称。 | +| `region` | 是 | AWS 区域。 | +| `access_key` | 是 | AWS 访问密钥。 | +| `secret_key` | 是 | AWS 秘密密钥。 | +| `endpoint_override` | 否 | Kinesis 服务的自定义端点。 | + +当您按偏移量重置 Kinesis 消费者时,请提供 Kinesis 序列号作为偏移量。有关更多信息,请参阅[恢复摄取 API](/api-reference/index-apis/resume-ingestion)。 + +## 相关文档 + +* [拉取式摄取](/im-plugin/pull-based-ingestion/) +* [拉取式摄取管理 API](/api-reference/index-apis/pull-based-ingestion-management) diff --git a/i18n/zh/im-plugin/pull-based-ingestion/object-store.md b/i18n/zh/im-plugin/pull-based-ingestion/object-store.md new file mode 100644 index 00000000..fbb05f2d --- /dev/null +++ b/i18n/zh/im-plugin/pull-based-ingestion/object-store.md @@ -0,0 +1,156 @@ +--- +title: 对象存储源 +--- + +# 用于拉取式摄取的对象存储源 +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +`object_store` 源允许索引直接从对象存储(如 Amazon Simple Storage Service (Amazon S3)、Google Cloud Storage、Azure Blob Storage 或共享文件系统)拉取换行符分隔的 JSON (NDJSON) 文件。每个分片读取其自己的文件部分,因此您不需要单独的流式系统或加载工具进行一次性加载。 + +源通过注册的[快照存储库](/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore)读取对象,因此存储桶、端点和凭据存储在存储库配置中,不会出现在索引设置中。 + +## 先决条件 + +在创建使用对象存储源的索引之前,请确保满足以下先决条件: + +* 在每个节点上使用 `bin/opensearch-plugin install ingestion-object-store` 安装 `ingestion-object-store` 插件。 +* 注册类型为 `s3`、`gcs`、`azure` 或 `fs` 的存储库,并将 `readonly` 设置为 `true`。源拒绝非只读的存储库,因此它无法修改或删除存储中的对象。 +* 在创建索引之前将文件放入存储库。文件在摄取期间不得更改。 + +以下请求注册一个只读 S3 存储库: + +```json +PUT /_snapshot/ingest-repo +{ + "type": "s3", + "settings": { + "bucket": "my-bucket", + "base_path": "exports", + "readonly": true + } +} +``` + +## 创建索引 + +以下请求创建一个读取五个 NDJSON 文件的索引,将每个文件分配给三个分片中的一个: + +```json +PUT /events +{ + "settings": { + "index.number_of_shards": 3, + "index.number_of_replicas": 0, + "index.replication.type": "SEGMENT", + "index.ingestion_source.type": "object_store", + "index.ingestion_source.pointer.init.reset": "earliest", + "index.ingestion_source.mapper_type": "raw_payload", + "index.ingestion_source.param.repository": "ingest-repo", + "index.ingestion_source.param.shard_split": "whole_files", + "index.ingestion_source.param.source_prefix": "events/part-", + "index.ingestion_source.param.manifest": "[{\"key\":\"events/part-0001.ndjson\",\"size\":76},{\"key\":\"events/part-0002.ndjson\",\"size\":50},{\"key\":\"events/part-0003.ndjson\",\"size\":52},{\"key\":\"events/part-0004.ndjson\",\"size\":26},{\"key\":\"events/part-0005.ndjson\",\"size\":50}]" + }, + "mappings": { + "properties": { + "name": { "type": "keyword" }, + "age": { "type": "integer" } + } + } +} +``` + +对象存储源要求以下 `ingestion_source` 设置具有非默认值: + +* `pointer.init.reset` 设置必须为 `earliest` 或 `none`。默认值 `latest` 在数据末尾开始读取,因此源会拒绝它。源还拒绝 `reset_by_timestamp`,并且仅对单分片索引接受 `reset_by_offset`。有关更多信息,请参阅[流位置](/im-plugin/pull-based-ingestion/#stream-position)。 +* `mapper_type` 设置必须为 `raw_payload`。文件的每一行都作为一个文档索引,使用该行作为文档主体。有关更多信息,请参阅[消息格式](/im-plugin/pull-based-ingestion/#message-format)。 + +## 源参数 + +下表列出了源参数。将每个参数指定为 `index.ingestion_source.param.<name>`。 + +| 参数 | 必需 | 默认值 | 描述 | +| :--- | :--- | :--- | :--- | +| `repository` | 是 | | 注册的只读 `s3`、`gcs`、`azure` 或 `fs` 存储库的名称。如果存储库未注册,分片每 10 秒重试一次,因此您可以在创建索引后注册存储库。 | +| `source_url` | 条件性 | | 单个对象的键,相对于存储库基路径。`source_url` 或 `source_prefix` 二选一必需。当 `shard_split` 为 `equal_bytes` 时必需。 | +| `source_prefix` | 条件性 | | 要读取的对象的键前缀,相对于存储库基路径。`source_url` 或 `source_prefix` 二选一必需。当 `shard_split` 为 `whole_files` 或 `shard_prefixes` 时必需。 | +| `shard_split` | 是 | | 用于在分片之间划分对象的方法。有效值为 `whole_files`、`shard_prefixes` 和 `equal_bytes`。有关更多信息,请参阅[在分片之间划分对象](#dividing-objects-among-shards)。 | +| `discovery` | 否 | `manifest` | 分片用于查找对象的方法。有效值为 `manifest` 和 `list`。有关更多信息,请参阅[查找对象](#finding-objects)。 | +| `manifest` | 条件性 | | 对象及其确切大小(以字节为单位)的列表,以字符串形式提供 JSON 数组:`[{"key":"<key>","size":<size>}, ...]`。当 `discovery` 为 `manifest` 时必需。最大大小为 1 MB。 | +| `format` | 否 | `ndjson` | 文件格式。仅支持 `ndjson`。 | +| `max_record_bytes` | 否 | `10485760` (10 MB) | 最大记录大小(以字节为单位)。超过此大小的行会暂停分片。 | +| `max_objects` | 否 | `1000000` | 清单可以列出或分片可以发现的最大对象数。 | +| `max_list_requests` | 否 | 无限制 | 分片可以向对象存储发送的最大列表请求数。 | +| `max_get_requests` | 否 | 无限制 | 分片可以向对象存储发送的最大读取请求数。 | +| `max_bytes` | 否 | 无限制 | 分片可以从对象存储读取的最大字节数。 | + +所有键都相对于存储库基路径。键不能以 `/` 开头;包含 `//`、`*` 或 `?`;或包含 `.` 或 `..` 路径段。 + +::: info NOTE +对象存储提供商可以按请求和传输的字节收费。如果 `max_list_requests`、`max_get_requests` 或 `max_bytes` 是无限制的,OpenSearch 会记录警告。限制按分片计算,并在分片重启或重新定位时重置。 +::: + +## 查找对象 + +`discovery` 参数确定每个分片如何查找要读取的对象。它支持 `manifest` 和 `list` 方法。 + +### 清单 + +当 `discovery` 为 `manifest`(默认值)时,您在 `manifest` 参数中列出每个对象及其确切大小。每个分片读取相同的列表,因此源不会向对象存储发送列表请求。每个键必须以 `source_prefix` 值开头。由于清单存储在集群状态中,因此它限制为 1 MB。对于更大的对象集,请使用 `list` 方法。 + +在创建索引后添加到对象存储的对象不会被读取。如果在完全读取对象之前删除、截断或扩大对象,分片将暂停。 + +### 列表 + +当 `discovery` 为 `list` 时,每个分片在启动时列出其自己文件夹中的对象。此方法需要将 `shard_split` 设置为 `shard_prefixes` 并省略 `manifest` 参数。分片 `N` 读取 `<source_prefix>/N/` 中的对象。例如,如果 `source_prefix` 为 `listed/` 并且索引有两个分片,则分片 0 读取 `listed/0/`,分片 1 读取 `listed/1/`。列表包括嵌套文件夹,最多 64 级深。 + +分片每次启动时都会列出其文件夹,包括重启、重新定位或设置更新后。在创建索引之前将所有对象放入文件夹中,并且在摄取期间不要更改它们。如果对象在列表之间发生更改,分片会按以下方式处理它们: + +* 在上一次列表之后添加的对象仅在其名称排序在分片正在读取的对象之后时才会被读取。 +* 未读取的已删除对象会被跳过。 +* 调整大小的对象会读取到其新大小。 +* 如果分片正在读取的对象被删除且文件夹中还有其他对象,则分片暂停。 +* 如果文件夹中没有对象,则分片不读取任何内容并报告延迟为 `0`。 + +不在任何分片文件夹中的对象不会被读取。 + +## 在分片之间划分对象 + +每个分片从相同的设置确定其自己的对象部分,因此每个记录恰好被一个分片读取。`shard_split` 参数支持以下值: + +* `whole_files`:每个对象根据其键的哈希分配给一个分片。此方法平衡每个分片的对象数量,不考虑对象大小。 +* `shard_prefixes`:`<source_prefix>/N/` 中的对象分配给分片 `N`。 +* `equal_bytes`:在 `source_url` 中指定的单个对象被划分为每个分片一个字节范围。每个范围边界向前移动到下一行的开头,以便没有记录在分片之间拆分。清单必须恰好包含这一个对象,并且其大小必须大于 0。 + +## 一次性摄取 + +每个文档 ID 由分片号、对象键和记录开始的字节偏移量构建。如果在崩溃或重启后再次读取记录,它会接收相同的 ID 并覆盖早期的副本,因此每个记录恰好产生一个文档。 + +## 监控摄取进度 + +`consumer_stats.pointer_based_lag` 指标报告分片尚未读取的字节数。当此指标在每个分片上为 `0` 时,摄取完成。有关更多信息,请参阅[拉取式摄取指标](/im-plugin/pull-based-ingestion/#pull-based-ingestion-metrics)。 + +## 错误 + +以下错误会暂停分片: + +* 配置错误。原因会写入日志。 +* 读取错误,例如缺少对象或达到成本限制。 +* 对象大小不匹配。源验证每个对象具有其声明的大小。如果对象比声明的短或长,或者声明为空但包含数据,则分片暂停,以免索引部分数据。 + +无法解析的行根据 `error_strategy` 设置处理。有关更多信息,请参阅[更新错误策略](/im-plugin/pull-based-ingestion/#updating-the-error-policy)。 + +## 限制 + +对象存储源具有以下限制: + +* 不支持压缩文件,例如 gzip 文件。 +* 您无法在现有索引上更改 `manifest`、`source_url`、`source_prefix`、`shard_split` 或 `discovery` 参数。要更改这些参数,请创建一个新索引。 + +## 相关文档 + +* [拉取式摄取](/im-plugin/pull-based-ingestion/) +* [拉取式摄取管理 API](/api-reference/index-apis/pull-based-ingestion-management) diff --git a/i18n/zh/im-plugin/similarity.md b/i18n/zh/im-plugin/similarity.md new file mode 100644 index 00000000..bb9185e8 --- /dev/null +++ b/i18n/zh/im-plugin/similarity.md @@ -0,0 +1,655 @@ +--- +title: 相似度 +--- + +# 相似度 + +相似度定义了在搜索操作期间如何对匹配的文档进行评分和排名。OpenSearch 使用相似度算法计算相关性分数,以确定搜索结果的顺序。 + +每个字段都可以有自己的相似度配置,从而对不同类型的内容如何评分进行精细控制。您可以在索引级别的索引设置中定义自定义相似度算法。配置后,您可以使用 [`similarity` 映射参数](/mappings/mapping-parameters/similarity/)将这些算法应用于特定字段。 + +配置自定义相似度设置是一项高级功能。内置的相似度对于大多数用例来说已经足够了。 + +## 在索引级别配置相似度 + +OpenSearch 使用 BM25 作为所有字段的默认相似度。您可以更改索引的默认相似度,以将单一相似度算法应用于该索引中的所有字段。 + +### 在索引创建时设置默认相似度 + +您可以在创建索引时设置默认相似度: + +```json +PUT /product_catalog +{ + "settings": { + "index": { + "similarity": { + "default": { + "type": "boolean" + } + } + } + } +} +``` + +当您使用特殊的 `default` 名称时,相似度会自动应用于索引中的所有字段。您无需在各个字段映射中指定相似度。 + +### 在索引创建后更改默认相似度 + +相似度设置不是动态的,因此在打开的索引上更新它们会失败。要在索引创建后更改默认相似度,请关闭索引、更新设置,然后重新打开它。 + +首先,关闭索引: + +```json +POST /product_catalog/_close +``` + +接下来,更新默认相似度: + +```json +PUT /product_catalog/_settings +{ + "index": { + "similarity": { + "default": { + "type": "DFR", + "basic_model": "g", + "after_effect": "l", + "normalization": "h2", + "normalization.h2.c": "3.0" + } + } + } +} +``` + +最后,重新打开索引: + +```json +POST /product_catalog/_open +``` + +要验证默认相似度是否已更改,请发送以下请求: + +```json +GET /product_catalog/_settings +``` + +响应确认默认相似度已更新: + +```json +{ + "product_catalog": { + "settings": { + "index": { + "replication": { + "type": "DOCUMENT" + }, + "number_of_shards": "1", + "provided_name": "product_catalog", + "similarity": { + "default": { + "basic_model": "g", + "type": "DFR", + "normalization": "h2", + "after_effect": "l", + "normalization.h2": { + "c": "3.0" + } + } + }, + "creation_date": "1761328470322", + "number_of_replicas": "1", + "uuid": "YFr9ts8VSaSV-YkHZP3mYQ", + "version": { + "created": "137227827" + } + } + } + } +} +``` + +### 更改相似度类型时的参数持久性 + +从一种相似度类型更改为另一种时,OpenSearch 会保留先前配置的参数。如果新的相似度类型不支持这些参数,更新将失败。 + +例如,将默认相似度从 `DFR` 更改为 `boolean`。首先,关闭索引: + +```json +POST /product_catalog/_close +``` + +然后更新默认相似度: + +```json +PUT /product_catalog/_settings +{ + "index": { + "similarity": { + "default": { + "type": "boolean" + } + } + } +} +``` + +请求失败,因为 `DFR` 参数仍然设置: + +```json +{ + "error": { + "root_cause": [ + { + "type": "illegal_argument_exception", + "reason": "Unknown settings for similarity of type [boolean]: [normalization.h2.c, normalization, after_effect, basic_model]" + } + ], + "type": "illegal_argument_exception", + "reason": "Unknown settings for similarity of type [boolean]: [normalization.h2.c, normalization, after_effect, basic_model]" + }, + "status": 400 +} +``` + +要解决此问题,请在同一请求中将旧参数显式设置为 `null`: + +```json +PUT /product_catalog/_settings +{ + "index": { + "similarity": { + "default": { + "type": "boolean", + "basic_model": null, + "after_effect": null, + "normalization": null, + "normalization.h2.c": null + } + } + } +} +``` + +然后重新打开索引: + +```json +POST /product_catalog/_open +``` + +## 在字段级别配置内置相似度 + +OpenSearch 提供可以直接在字段映射中使用的内置相似度算法(`BM25` 和 `boolean`)。要在字段级别配置相似度,请在创建索引时将其应用于字段。以下示例将 `boolean` 相似度应用于 `content` 字段: + +```json +PUT /blog_posts_2/ +{ + "mappings": { + "properties": { + "content": { + "type": "text", + "similarity": "boolean" + } + } + } +} +``` + +在此示例中,只有 `content` 字段使用 `boolean` 相似度。索引中的其他字段将使用默认的 `BM25` 相似度。 + +## 配置自定义相似度 + +对于更高级的用例,您可以定义可应用于特定字段的命名自定义相似度。当索引中的不同字段需要不同的评分算法时,此方法提供了更大的灵活性。 + +配置命名自定义相似度需要两步过程: + +1. 在索引设置中使用自定义名称定义相似度。 +2. 在映射中将相似度应用于特定字段。 + +### 步骤 1:定义自定义相似度 + +以下示例创建具有自定义 `DFR` 相似度配置的索引: + +```json +PUT /blog_posts +{ + "settings": { + "index": { + "similarity": { + "blog_similarity": { + "type": "DFR", + "basic_model": "g", + "after_effect": "l", + "normalization": "h2", + "normalization.h2.c": "3.0" + } + } + } + } +} +``` + +### 步骤 2:将自定义相似度应用于字段 + +定义相似度后,您必须在映射中将其显式应用于特定字段。与默认相似度不同,自定义相似度不会自动应用于所有字段: + +```json +PUT /blog_posts/_mapping +{ + "properties": { + "content": { + "type": "text", + "similarity": "blog_similarity" + } + } +} +``` + +在此示例中,只有 `content` 字段使用自定义 `blog_similarity`。索引中的其他字段(如果有)继续使用默认的 `BM25` 相似度,除非另有明确配置。 + +## 可用的相似度类型 + +OpenSearch 支持以下相似度类型。 + +### BM25 相似度(默认) + +`BM25` 相似度基于 TF/IDF,包括内置的词频归一化。它适用于大多数文本字段,特别是较短的字段,如标题和名称。 + +`BM25` 相似度支持以下参数。 + +| 参数 | 描述 | 默认值 | 必需 | +|-----------|-------------|---------|----------| +| `k1` | 控制非线性词频归一化(饱和度)。 | `1.2` | 否 | +| `b` | 控制文档长度归一化词频值的程度。 | `0.75` | 否 | +| `discount_overlaps` | 确定在计算规范时是否忽略重叠标记(位置增量为 0 的标记)。 | `true`(计算规范时忽略重叠标记) | 否 | + +### Boolean 相似度 + +内置的 `boolean` 相似度为所有匹配的文档分配相同的常量分数,当您只需要确定文档是否匹配而不是它们的相关性时很有用。此相似度忽略词频、文档长度和其他评分因素。 + +`boolean` 相似度不支持参数。 + +### DFR 相似度 + +`DFR` 相似度实现了用于文档评分的[偏离随机性](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/DFRSimilarity.html)框架。 + +`DFR` 相似度支持以下参数。 + +| 参数 | 描述 | 有效值 | 必需 | +|-----------|-------------|------------------|----------| +| `basic_model` | DFR 框架的基本模型。 | [`g`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/BasicModelG.html)、[`if`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/BasicModelIF.html)、[`in`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/BasicModelIn.html)、[`ine`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/BasicModelIne.html) | 是 | +| `after_effect` | DFR 框架的后效模型。 | [`b`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/AfterEffectB.html)、[`l`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/AfterEffectL.html) | 是 | +| `normalization` | DFR 框架的归一化模型。`h1`、`h2` 和 `h3` 接受可选的 `c` 参数,指定为 `normalization.h1.c`、`normalization.h2.c` 或 `normalization.h3.c`。`z` 接受可选的 `z` 参数,指定为 `normalization.z.z`,其值必须大于 0 且小于 0.5。`no` 不接受参数。 | [`no`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/Normalization.NoNormalization.html)、[`h1`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/NormalizationH1.html)、[`h2`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/NormalizationH2.html)、[`h3`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/NormalizationH3.html)、[`z`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/NormalizationZ.html) | 是 | + +### DFI 相似度 + +`DFI` 相似度实现了[偏离独立性(DFI)](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/DFISimilarity.html)模型。 + +`DFI` 相似度支持以下参数。 + +| 参数 | 描述 | 有效值 | 必需 | +|-----------|-------------|------------------|----------| +| `independence_measure` | DFI 模型的独立性度量。 | [`standardized`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/IndependenceStandardized.html)、[`saturated`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/IndependenceSaturated.html)、[`chisquared`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/IndependenceChiSquared.html) | 是 | + +使用 `DFI` 相似度时,避免删除停用词以获得最佳相关性。频率低于预期的术语将获得 0 分。 + +### IB 相似度 + +`IB` 相似度使用[基于信息的模型](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/IBSimilarity.html),该模型分析符号分布中基本元素的重复使用。 + +`IB` 相似度支持以下参数。 + +| 参数 | 描述 | 有效值 | 必需 | +|-----------|-------------|------------------|----------| +| `distribution` | `IB` 框架的分布模型。 | [`ll`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/DistributionLL.html)、[`spl`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/DistributionSPL.html) | 是 | +| `lambda` | `IB` 框架的 lambda 模型。 | [`df`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/LambdaDF.html)、[`ttf`](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/LambdaTTF.html) | 是 | +| `normalization` | `IB` 框架的归一化模型。 | 与 `DFR` 相似度相同的选项 | 是 | + +<!-- vale off --> +### LM Dirichlet 相似度 +<!-- vale on --> + +`LMDirichlet` 相似度使用带有 Dirichlet 平滑的[语言模型相似度](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/LMDirichletSimilarity.html)。 + +`LMDirichlet` 相似度支持以下参数。 + +| 参数 | 描述 | 默认值 | 必需 | +|-----------|-------------|---------|----------| +| `mu` | 平滑参数。 | `2000` | 否 | + +出现次数少于语言模型预测的术语将获得 0 分。 + +<!-- vale off --> +### LM Jelinek Mercer 相似度 +<!-- vale on --> + +`LMJelinekMercer` 相似度使用带有 Jelinek-Mercer 平滑的[语言模型相似度](https://lucene.apache.org/core/9_9_2/core/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.html)。 + +`LMJelinekMercer` 相似度支持以下参数。 + +| 参数 | 描述 | 默认值 | 必需 | +|-----------|-------------|---------|----------| +| `lambda` | 插值参数。对于标题查询,大约 `0.1` 的值效果良好,而对于较长的查询,`0.7` 更好。 | `0.1` | 否 | + +### 脚本化相似度 + +`scripted` 相似度允许使用 OpenSearch 的脚本功能自定义评分逻辑。 + +在为 `scripted` 相似度编写脚本时,您可以访问以下变量。这些变量允许您基于词频、文档频率、字段统计信息和文档特征实现自定义评分算法。 + +| 变量 | 描述 | +|----------|-------------| +| `weight` | 文档无关的权重(如果提供了 `weight_script`,则从中获取,否则为 `1.0`)。 | +| `query.boost` | 应用于术语的查询级提升因子。 | +| `field.docCount` | 具有此字段的文档总数。 | +| `field.sumDocFreq` | 此字段中所有术语的文档频率之和。 | +| `field.sumTotalTermFreq` | 此字段中所有术语的总词频之和。 | +| `term.docFreq` | 包含此特定术语的文档数。 | +| `term.totalTermFreq` | 此术语在所有文档中的总出现次数。 | +| `doc.freq` | 此术语在当前文档中的频率。 | +| `doc.length` | 当前文档中的术语总数。 | + +为确保正确的搜索行为,`scripted` 相似度必须遵循以下规则: + +- 返回的分数必须为正数。 +- 当 `doc.freq` 增加而所有其他变量保持不变时,分数不得降低。 +- 当 `doc.length` 增加而所有其他变量保持不变时,分数不得增加。 + +以下示例显示了自定义 TF-IDF 实现。 + +首先,创建索引并定义脚本来计算相似度: + +```json +PUT /research_papers +{ + "settings": { + "number_of_shards": 1, + "similarity": { + "custom_tfidf": { + "type": "scripted", + "script": { + "source": "double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;" + } + } + } + }, + "mappings": { + "properties": { + "abstract": { + "type": "text", + "similarity": "custom_tfidf" + } + } + } +} +``` + +索引示例文档: + +```json +PUT /research_papers/_doc/1 +{ + "abstract": "machine learning algorithms data mining" +} +``` + +```json +PUT /research_papers/_doc/2 +{ + "abstract": "data analysis statistical methods" +} +``` + +刷新索引: + +```json +POST /research_papers/_refresh +``` + +现在您可以搜索索引并请求评分解释: + +```json +GET /research_papers/_search?explain=true +{ + "query": { + "bool": { + "must": [ + { + "match": { + "abstract": "machine" + } + } + ], + "boost": 2.0 + } + } +} +``` + +响应显示自定义 TF-IDF 计算,匹配文档的分数为 `1.2570862`。`_explanation` 部分显示脚本可用的所有变量及其在此特定搜索中的值: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2570862, + "hits": [ + { + "_shard": "[research_papers][0]", + "_node": "KfEEGG7_SsKZVFqI4ko2FA", + "_index": "research_papers", + "_id": "1", + "_score": 1.2570862, + "_source": { + "abstract": "machine learning algorithms data mining" + }, + "_explanation": { + "value": 1.2570862, + "description": "weight(abstract:machine in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 1.2570862, + "description": "score from ScriptedSimilarity(weightScript=[null], script=[Script{type=inline, lang='painless', idOrCode='double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;', options={}, params={}}]) computed from:", + "details": [ + { + "value": 1.0, + "description": "weight", + "details": [] + }, + { + "value": 2.0, + "description": "query.boost", + "details": [] + }, + { + "value": 2, + "description": "field.docCount", + "details": [] + }, + { + "value": 9, + "description": "field.sumDocFreq", + "details": [] + }, + { + "value": 9, + "description": "field.sumTotalTermFreq", + "details": [] + }, + { + "value": 1, + "description": "term.docFreq", + "details": [] + }, + { + "value": 1, + "description": "term.totalTermFreq", + "details": [] + }, + { + "value": 1.0, + "description": "doc.freq", + "details": [] + }, + { + "value": 5, + "description": "doc.length", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` + +您可以通过将文档无关的计算分离到名为 `weight_script` 的另一个脚本中来提高性能。对于匹配许多文档的查询,`weight_script` 对每个术语运行一次,而主 `script` 对每个文档运行一次。`weight_script` 生成的分数在 `weight` 变量中可用: + +```json +PUT /research_papers_optimized +{ + "settings": { + "number_of_shards": 1, + "similarity": { + "optimized_tfidf": { + "type": "scripted", + "weight_script": { + "source": "double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; return query.boost * idf;" + }, + "script": { + "source": "double tf = Math.sqrt(doc.freq); double norm = 1/Math.sqrt(doc.length); return weight * tf * norm;" + } + } + } + }, + "mappings": { + "properties": { + "abstract": { + "type": "text", + "similarity": "optimized_tfidf" + } + } + } +} +``` + +将相同的示例文档索引到 `research_papers_optimized`,刷新索引,然后运行相同的查询。响应显示优化后的相似度如何工作: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2570862, + "hits": [ + { + "_shard": "[research_papers_optimized][0]", + "_node": "KfEEGG7_SsKZVFqI4ko2FA", + "_index": "research_papers_optimized", + "_id": "1", + "_score": 1.2570862, + "_source": { + "abstract": "machine learning algorithms data mining" + }, + "_explanation": { + "value": 1.2570862, + "description": "weight(abstract:machine in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 1.2570862, + "description": "score from ScriptedSimilarity(weightScript=[Script{type=inline, lang='painless', idOrCode='double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; return query.boost * idf;', options={}, params={}}], script=[Script{type=inline, lang='painless', idOrCode='double tf = Math.sqrt(doc.freq); double norm = 1/Math.sqrt(doc.length); return weight * tf * norm;', options={}, params={}}]) computed from:", + "details": [ + { + "value": 2.8109303, + "description": "weight", + "details": [] + }, + { + "value": 2.0, + "description": "query.boost", + "details": [] + }, + { + "value": 2, + "description": "field.docCount", + "details": [] + }, + { + "value": 9, + "description": "field.sumDocFreq", + "details": [] + }, + { + "value": 9, + "description": "field.sumTotalTermFreq", + "details": [] + }, + { + "value": 1, + "description": "term.docFreq", + "details": [] + }, + { + "value": 1, + "description": "term.totalTermFreq", + "details": [] + }, + { + "value": 1.0, + "description": "doc.freq", + "details": [] + }, + { + "value": 5, + "description": "doc.length", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` + +在此优化示例中: + +- `weight_script` 计算分数 `2.8109303`(IDF + 查询提升,对所有文档相同)。 +- 主 `script` 使用预先计算的 `weight` 值计算文档特定因子。 +- 最终分数为 `1.2570862`(与单脚本方法相同,但效率更高)。 + +::: info NOTE +`weight_script` 参数名称是保留的,不能更改。结果始终在主脚本中的 `weight` 变量中可用。 +::: + +## 相关文档 + +- [`similarity` 映射参数](/mappings/mapping-parameters/similarity/) diff --git a/i18n/zh/ingest-pipelines/accessing-data.md b/i18n/zh/ingest-pipelines/accessing-data.md new file mode 100644 index 00000000..5cf0aaca --- /dev/null +++ b/i18n/zh/ingest-pipelines/accessing-data.md @@ -0,0 +1,291 @@ +--- +title: 在管道中访问数据 +--- + +# 在管道中访问数据 + +管道处理器对文档的 `_source` 字段和元数据字段都具有读写访问权限。如何引用字段取决于在哪里引用它: + +- 在处理器参数(如 `field` 和 `target_field`)中,使用字段名称。 +- 在 [`script` 处理器](/ingest-pipelines/processors/script) 和 `if` 条件中,使用 `ctx` 对象,它代表正在处理的文档,例如 `ctx.user`。 + +## 访问文档字段 + +在处理器参数中,通过字段名称引用顶级字段。使用点表示法引用嵌套字段。 + +### 示例:访问顶级字段 + +给定以下示例文档: + +```json +{ + "user": "alice" +} +``` + +您可以按以下方式访问 `user`: + +```json +"field": "user" +``` + +在脚本或条件中,使用 `ctx.user`。 + +### 示例:访问嵌套字段 + +给定以下示例文档: + +```json +{ + "user": { + "name": "alice" + } +} +``` + +您可以按以下方式访问 `user.name`: + +```json +"field": "user.name" +``` + +在脚本或条件中,使用 `ctx.user.name`。如果 `user` 对象可能缺失,请使用空安全运算符:`ctx.user?.name`。 + +## 访问源中的字段 + +要访问文档 `_source` 中的字段,请通过字段名称引用该字段: + +```json +{ + "set": { + "field": "environment", + "value": "production" + } +} +``` + +或者,您可以明确使用 `_source`: + +```json +{ + "set": { + "field": "_source.environment", + "value": "production" + } +} +``` + +## 访问元数据字段 + +文档的 `_source` 不能包含名称与元数据字段匹配的字段,因此您可以像源字段一样按名称引用元数据字段。处理器可以读写以下元数据字段: + +- `_index` +- `_id` +- `_routing` +- `_version` +- `_version_type` +- `_if_seq_no` +- `_if_primary_term` + +### 示例:动态设置 `_routing` + +```json +{ + "set": { + "field": "_routing", + "value": "{{region}}" + } +} +``` + +## 访问摄取元数据字段 + +`_ingest.timestamp` 字段表示摄取节点接收文档的时间。要持久化此时间戳,请使用 `set` 处理器: + +```json +{ + "set": { + "field": "received_at", + "value": "{{_ingest.timestamp}}" + } +} +``` + +摄取元数据仅在管道处理文档时存在。OpenSearch 不会索引 `_ingest` 字段,因此要保留值,需要将其复制到文档字段中,如上例所示。 + +文档的 `_source` 可以包含名为 `_ingest` 的字段。要访问此字段,请使用 `_source._ingest` 前缀。如果没有前缀,`_ingest` 将引用摄取元数据。以下处理器将 `_ingest` 源字段的值复制到 `ingest_source` 字段: + +```json +{ + "set": { + "field": "ingest_source", + "value": "{{_source._ingest}}" + } +} +``` + +## 在 Mustache 模板中使用字段值 + +使用 Mustache 模板将字段值插入到处理器设置中。只有某些处理器参数支持模板;每个处理器的参数表都会说明支持哪些参数。有关更多信息,请参阅 [模板片段](/ingest-pipelines/create-ingest#template-snippets)。模板通过字段名称引用字段,不使用 `ctx`。 + +双花括号(`{{` 和 `}}`)通过在特殊字符(如引号和反斜杠)前添加反斜杠来转义值中的特殊字符。三花括号(`{{{` 和 `}}}`)插入值时不进行转义。例如,如果 `title` 字段包含 `say "hi"`,那么 `{{title}}` 会产生 `say \"hi\"`,而 `{{{title}}}` 会产生 `say "hi"`。 + +### 示例:组合源字段 + +以下处理器配置将 `app` 和 `env` 字段组合,用下划线 (_) 分隔,并将结果存储在 `log_label` 字段中: + +```json +{ + "set": { + "field": "log_label", + "value": "{{{app}}}_{{{env}}}" + } +} +``` + +### 示例:使用 `set` 处理器生成动态问候语 + +如果文档的 `user` 字段设置为 `alice`,请使用以下语法生成结果 `"greeting": "Hello, alice!"`: + +```json +{ + "set": { + "field": "greeting", + "value": "Hello, {{{user}}}!" + } +} +``` + +## 动态字段名称 + +您可以使用字段的值作为新字段的名称: + +```json +{ + "set": { + "field": "{{service}}", + "value": "{{code}}" + } +} +``` + +## 示例:基于状态路由到动态索引 + +以下处理器配置通过将 `-events` 附加到 `status` 字段的值来动态设置目标索引: + +```json +{ + "set": { + "field": "_index", + "value": "{{status}}-events" + } +} +``` + +## 在 `script` 处理器中使用 `ctx` + +使用 `script` 处理器进行高级转换。 + +### 示例:仅在另一个字段缺失时添加字段 + +以下处理器仅在文档中缺少 `error_message` 字段时,才添加值为 "none" 的 `error_message` 字段: + +```json +{ + "script": { + "lang": "painless", + "source": "if (ctx.error_message == null) { ctx.error_message = 'none'; }" + } +} +``` + +### 示例:将值从一个字段复制到另一个字段 + +以下处理器将 `timestamp` 字段的值复制到名为 `event_time` 的新字段中: + +```json +{ + "script": { + "lang": "painless", + "source": "ctx.event_time = ctx.timestamp;" + } +} +``` + +## 完整管道示例 + +以下示例定义了一个完整的摄取管道,该管道使用 `user.first` 和 `department` 字段设置标语,从 `date` 字段中提取 `year`,并在 `received_at` 字段中记录文档的摄取时间戳: + +```json +PUT _ingest/pipeline/example-pipeline +{ + "description": "Sets a tagline, extracts the year, and records the ingest time", + "processors": [ + { + "set": { + "field": "tagline", + "value": "{{{user.first}}} from {{{department}}}" + } + }, + { + "script": { + "lang": "painless", + "source": "ctx.year = ctx.date.substring(0, 4);" + } + }, + { + "set": { + "field": "received_at", + "value": "{{_ingest.timestamp}}" + } + } + ] +} +``` + +要测试管道,请使用以下请求: + +```json +POST _ingest/pipeline/example-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "user": { + "first": "Liam" + }, + "department": "Engineering", + "date": "2024-12-03T14:05:00Z" + } + } + ] +} +``` + +响应显示处理后的丰富文档,包括新添加的 `tagline`、提取的 `year` 以及摄取管道生成的 `received_at` 时间戳: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "user": { + "first": "Liam" + }, + "department": "Engineering", + "date": "2024-12-03T14:05:00Z", + "tagline": "Liam from Engineering", + "year": "2024", + "received_at": "2025-04-14T18:40:00.000Z" + }, + "_ingest": { + "timestamp": "2025-04-14T18:40:00.000Z" + } + } + } + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/complex-conditionals.md b/i18n/zh/ingest-pipelines/complex-conditionals.md new file mode 100644 index 00000000..47304143 --- /dev/null +++ b/i18n/zh/ingest-pipelines/complex-conditionals.md @@ -0,0 +1,566 @@ +--- +title: 复杂条件 +--- + +# 复杂条件 + +在摄取管道中,处理器中的 `if` 参数可以使用 Painless 脚本评估复杂条件。这些条件有助于微调文档处理,允许高级逻辑,如类型检查、正则表达式和组合多个条件。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。 + +::: tip TIP +OpenSearch 会为通过处理器的每个文档评估条件,因此昂贵的条件会降低摄取速度。请尽可能保持条件简单。 +::: + +## 编写多语句条件 + +条件可以包含多个 Painless 语句,例如变量声明和循环,只要它返回布尔值即可。由于 JSON 字符串不能包含换行符,因此请将整个脚本写在一行上,并使用分号分隔语句。在 OpenSearch Dashboards Dev Tools 中,您可以改为将多行脚本括在三引号(`"""`)中。有关更多信息,请参阅[在查询中使用三引号](/dashboards/dev-tools/console#using-triple-quotation-marks-in-queries)。 + +以下管道从其 `items` 数组中计算订单的总价值,并标记总价值超过 `1000` 的订单以供审核。没有 `items` 字段的订单不会被标记: + +```json +PUT _ingest/pipeline/flag_large_orders +{ + "processors": [ + { + "set": { + "field": "review_required", + "value": true, + "if": "if (ctx.items == null) { return false; } double total = 0; for (def item : ctx.items) { total += item.price * item.quantity; } return total > 1000;" + } + } + ] +} +``` + +使用以下 `_simulate` 请求测试管道: + +```json +POST _ingest/pipeline/flag_large_orders/_simulate +{ + "docs": [ + { + "_source": { + "order_id": "A-2001", + "items": [ + { "name": "Laptop stand", "price": 45.0, "quantity": 2 }, + { "name": "Monitor", "price": 329.0, "quantity": 1 } + ] + } + }, + { + "_source": { + "order_id": "A-2002", + "items": [ + { "name": "Monitor", "price": 329.0, "quantity": 4 } + ] + } + } + ] +} +``` + +第一个订单总计 `419`,未被标记。第二个订单总计 `1316`,因此添加了 `review_required` 字段: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "order_id": "A-2001", + "items": [ + { "name": "Laptop stand", "price": 45.0, "quantity": 2 }, + { "name": "Monitor", "price": 329.0, "quantity": 1 } + ] + }, + "_ingest": { + "timestamp": "2026-10-14T20:23:18.723081887Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "review_required": true, + "order_id": "A-2002", + "items": [ + { "name": "Monitor", "price": 329.0, "quantity": 4 } + ] + }, + "_ingest": { + "timestamp": "2026-10-14T20:23:18.723092429Z" + } + } + } + ] +} +``` + +## 多条件检查 + +您可以组合逻辑运算符,如 `&&`(与)、`||`(或)和 `!`(非)来构造更复杂的条件。以下管道将文档标记为 `spam` 并在它们包含高于 `1000` 的 `error_code` 时丢弃它们: + +```json +PUT _ingest/pipeline/spammy_error_handler +{ + "processors": [ + { + "set": { + "field": "tags", + "value": ["spam"], + "if": "ctx.message != null && ctx.message.contains('OutOfMemoryError')" + } + }, + { + "drop": { + "if": "ctx.tags != null && ctx.tags.contains('spam') && ctx.error_code != null && ctx.error_code > 1000" + } + } + ] +} +``` + +您可以使用以下 `_simulate` 请求测试管道: + +```json +POST _ingest/pipeline/spammy_error_handler/_simulate +{ + "docs": [ + { "_source": { "message": "OutOfMemoryError occurred", "error_code": 1200 } }, + { "_source": { "message": "OutOfMemoryError occurred", "error_code": 800 } }, + { "_source": { "message": "All good", "error_code": 200 } } + ] +} +``` + +第一个文档被丢弃,因为它包含 `OutOfMemoryError` 字符串和高于 `1000` 的 `error_code`: + +```json +{ + "docs": [ + null, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "error_code": 800, + "message": "OutOfMemoryError occurred", + "tags": [ + "spam" + ] + }, + "_ingest": { + "timestamp": "2025-04-23T10:20:10.704359884Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "error_code": 200, + "message": "All good" + }, + "_ingest": { + "timestamp": "2025-04-23T10:20:10.704369801Z" + } + } + } + ] +} +``` + +## 类型安全评估 + +使用 `instanceof` 确保在执行操作之前使用正确的数据类型。以下管道配置为仅在 `message` 是 `String` 类型且长度超过 `10` 个字符时才添加设置为 `true` 的 `processed` 字段: + +```json +PUT _ingest/pipeline/string_message_check +{ + "processors": [ + { + "set": { + "field": "processed", + "value": true, + "if": "ctx.message != null && ctx.message instanceof String && ctx.message.length() > 10" + } + } + ] +} +``` + +使用以下 `_simulate` 请求测试管道: + +```json +POST _ingest/pipeline/string_message_check/_simulate +{ + "docs": [ + { "_source": { "message": "short" } }, + { "_source": { "message": "This is a longer message" } }, + { "_source": { "message": 1234567890 } } + ] +} +``` + +只有第二个文档添加了新字段: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "short" + }, + "_ingest": { + "timestamp": "2025-04-23T10:28:14.040115261Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "processed": true, + "message": "This is a longer message" + }, + "_ingest": { + "timestamp": "2025-04-23T10:28:14.040141469Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": 1234567890 + }, + "_ingest": { + "timestamp": "2025-04-23T10:28:14.040144844Z" + } + } + } + ] +} +``` + +## 使用正则表达式 + +Painless 脚本支持使用 `=~` 运算符评估正则表达式。有关更多示例和适用于正则表达式的限制,请参阅[正则表达式条件](/ingest-pipelines/regex-conditionals)。以下管道标记以 `192.168.` 开头的可疑 IP 模式: + +```json +PUT _ingest/pipeline/flag_suspicious_ips +{ + "processors": [ + { + "set": { + "field": "alert", + "value": "suspicious_ip", + "if": "ctx.ip != null && ctx.ip =~ /^192\\.168\\.\\d+\\.\\d+$/" + } + } + ] +} +``` + +使用以下 `_simulate` 请求测试管道: + +```json +POST _ingest/pipeline/flag_suspicious_ips/_simulate +{ + "docs": [ + { "_source": { "ip": "192.168.0.1" } }, + { "_source": { "ip": "10.0.0.1" } } + ] +} +``` + +第一个文档添加了 `alert` 字段: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "alert": "suspicious_ip", + "ip": "192.168.0.1" + }, + "_ingest": { + "timestamp": "2025-04-23T10:32:45.367916428Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "ip": "10.0.0.1" + }, + "_ingest": { + "timestamp": "2025-04-23T10:32:45.36793772Z" + } + } + } + ] +} +``` + +## 组合字段和空值检查 + +以下管道在 `level` 为 `critical` 且提供了 `timestamp` 时添加设置为 `high` 的 `priority` 字段。脚本还确保所有字段都存在并满足特定条件后再继续: + +```json +PUT _ingest/pipeline/critical_log_handler +{ + "processors": [ + { + "set": { + "field": "priority", + "value": "high", + "if": "ctx.level != null && ctx.level == 'critical' && ctx.timestamp != null" + } + } + ] +} +``` + +使用以下 `_simulate` 请求测试管道: + +```json +POST _ingest/pipeline/critical_log_handler/_simulate +{ + "docs": [ + { "_source": { "level": "critical", "timestamp": "2025-04-01T00:00:00Z" } }, + { "_source": { "level": "info", "timestamp": "2025-04-01T00:00:00Z" } }, + { "_source": { "level": "critical" } } + ] +} +``` + +只有第一个文档添加了 `priority` 字段: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "priority": "high", + "level": "critical", + "timestamp": "2025-04-01T00:00:00Z" + }, + "_ingest": { + "timestamp": "2025-04-23T10:39:25.46840371Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "level": "info", + "timestamp": "2025-04-01T00:00:00Z" + }, + "_ingest": { + "timestamp": "2025-04-23T10:39:25.46843021Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "level": "critical" + }, + "_ingest": { + "timestamp": "2025-04-23T10:39:25.468434835Z" + } + } + } + ] +} +``` + +## 多条件处理 + +以下管道: + +- 如果 `env` 字段尚不存在,则添加设置为 `production` 的 `env` 字段。 +- 如果 `status` 字段中的值大于或等于 `500`,则添加设置为 `major` 的 `severity` 字段。 +- 如果 `env` 字段设置为 `test` 且 `message` 字段包含 `debug`,则丢弃文档。 + +```json +PUT _ingest/pipeline/advanced_log_pipeline +{ + "processors": [ + { + "set": { + "field": "env", + "value": "production", + "if": "!ctx.containsKey('env')" + } + }, + { + "set": { + "field": "severity", + "value": "major", + "if": "ctx.status != null && ctx.status >= 500" + } + }, + { + "drop": { + "if": "ctx.env == 'test' && ctx.message != null && ctx.message.contains('debug')" + } + } + ] +} +``` + +使用以下 `_simulate` 请求测试管道: + +```json +POST _ingest/pipeline/advanced_log_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "status": 503, + "message": "Server unavailable" + } + }, + { + "_source": { + "env": "test", + "message": "debug log output" + } + }, + { + "_source": { + "status": 200, + "message": "OK" + } + } + ] +} +``` + +在响应中,请注意第一个文档添加了 `env: production` 和 `severity: major` 字段。第二个文档被丢弃。第三个文档添加了 `env: production` 字段: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "severity": "major", + "message": "Server unavailable", + "env": "production", + "status": 503 + }, + "_ingest": { + "timestamp": "2025-04-23T10:51:46.795026554Z" + } + } + }, + null, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "OK", + "env": "production", + "status": 200 + }, + "_ingest": { + "timestamp": "2025-04-23T10:51:46.795048304Z" + } + } + } + ] +} +``` + +## 空安全表示法 + +使用空安全导航表示法(`?.`)检查字段是否为 `null`。请注意,此表示法可以静默返回 `null`;因此,我们建议首先检查返回的值是否为 `null`,然后再使用诸如 `.contains` 或 `==` 之类的操作。 + +不安全的语法: + +``` +"if": "ctx.message?.contains('debug')" +``` + +如果文档中不存在 `message` 字段,此请求将返回带有消息 `Cannot invoke "Object.getClass()" because "value" is null` 的 `null_pointer_exception`。 + +安全的语法: + +``` +"if": "ctx.message != null && ctx.message.contains('debug')" +``` + +## 调试条件 + +要检查每个条件是如何评估的,请在 [模拟管道 API](/ingest-pipelines/simulate-ingest) 中将 `verbose` 参数设置为 `true`。对于每个处理器,响应都包含一个 `status` 字段。如果处理器的条件评估为 `false`,则 `status` 为 `skipped`,并且 `if` 对象显示条件及其结果。 + +以下请求模拟一个处理器,其条件对提供的文档评估为 `false`: + +```json +POST _ingest/pipeline/_simulate?verbose=true +{ + "pipeline": { + "processors": [ + { + "set": { + "field": "severity", + "value": "major", + "if": "ctx.status != null && ctx.status >= 500" + } + } + ] + }, + "docs": [ + { "_source": { "status": 200 } } + ] +} +``` + +响应显示 `set` 处理器被跳过,因为条件返回了 `false`: + +```json +{ + "docs": [ + { + "processor_results": [ + { + "processor_type": "set", + "status": "skipped", + "if": { + "condition": "ctx.status != null && ctx.status >= 500", + "result": false + } + } + ] + } + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/conditional-execution.md b/i18n/zh/ingest-pipelines/conditional-execution.md new file mode 100644 index 00000000..53db4573 --- /dev/null +++ b/i18n/zh/ingest-pipelines/conditional-execution.md @@ -0,0 +1,237 @@ +--- +title: 条件执行 +--- + +# 条件执行 + +在摄取管道中,您可以使用可选的 `if` 参数控制处理器是否运行。这允许根据传入文档内容有条件地执行处理器。条件被编写为 Painless 脚本,并针对文档上下文(`ctx`)进行评估。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。 + +## 基本条件执行 + +每个处理器都可以包含一个 `if` 子句。如果条件评估为 `true`,则处理器运行;否则,它将被跳过。 + +在条件中,`ctx` 是只读的。条件可以读取文档字段,但不能添加、更改或删除它们。要有条件地修改文档,请将修改放在处理器中,并仅使用条件来决定处理器是否运行。 + +### 示例:丢弃调试级别的日志 + +以下管道丢弃 `log_level` 字段等于 `debug` 的任何文档: + +```json +PUT _ingest/pipeline/drop_debug_logs +{ + "processors": [ + { + "drop": { + "if": "ctx.log_level == 'debug'" + } + } + ] +} +``` + +### 示例索引请求 + +```json +POST logs/_doc/1?pipeline=drop_debug_logs +{ + "message": "User logged in", + "log_level": "debug" +} +``` + +由于条件评估为 `true`,此文档被丢弃: + +```json +{ + "_index": "logs", + "_id": "1", + "_version": -3, + "result": "noop", + "_shards": { + "total": 0, + "successful": 0, + "failed": 0 + } +} +``` + +## 使用嵌套字段时的空安全字段检查 + +在使用嵌套字段时,重要的是避免空指针异常。在 Painless 脚本中使用空安全的 `?.` 运算符。 + +### 示例:基于嵌套字段丢弃文档 + +以下 drop 处理器仅在嵌套的 `app.env` 字段存在且等于 `debug` 时才执行: + +```json +PUT _ingest/pipeline/drop_debug_env +{ + "processors": [ + { + "drop": { + "if": "ctx.app?.env == 'debug'" + } + } + ] +} +``` + +如果未配置空安全的 `?.` 运算符,索引任何不包含 `app` 对象的文档都会触发以下空指针异常: + +```json +{ + "error": "IngestProcessorException[ScriptException[runtime error]; nested: NullPointerException[Cannot invoke \"Object.getClass()\" because \"callArgs[0]\" is null];]", + "status": 400 +} +``` + +## 处理扁平化字段 + +如果您的文档有扁平化字段,例如 `"app.env": "debug"`,请使用 [`dot_expander`](/ingest-pipelines/processors/dot-expander) 处理器将其转换为嵌套结构: + +```json +PUT _ingest/pipeline/drop_debug_env +{ + "processors": [ + { + "dot_expander": { + "field": "app.env" + } + }, + { + "drop": { + "if": "ctx.app?.env == 'debug'" + } + } + ] +} +``` + +## 条件中的安全方法调用 + +`?.` 运算符在对象为 `null` 时返回 `null`,而 `==` 运算符处理 `null` 值,因此诸如 `ctx.app?.env == 'debug'` 之类的条件是空安全的。但是,对 `null` 值调用方法会导致空指针异常。例如,对于不包含 `app.env` 字段的文档,`ctx.app?.env.equalsIgnoreCase('debug')` 会失败,因为 `ctx.app?.env` 返回 `null`。 + +要使方法调用空安全,请对常量调用该方法(它永远不会为 `null`),并将字段作为参数传递: + +```json +{ + "drop": { + "if": "'debug'.equalsIgnoreCase(ctx.app?.env)" + } +} +``` + +如果没有可以对常量调用的方法,请在调用方法之前显式检查 `null`: + +```json +{ + "drop": { + "if": "ctx.app?.env != null && ctx.app.env.contains('debug')" + } +} +``` + +## 完整示例:多步条件管道 + +以下摄取管道使用三个处理器: + +1. `set`:如果 `user` 字段中没有提供值,则将 `user` 字段设置为 `guest`。 +2. `set`:如果提供了 `status_code` 且大于或等于 `400`,则将 `error` 字段设置为 `true`。 +3. `drop`:如果 `app.env` 字段等于 `debug`,则丢弃整个文档。 + +```json +PUT _ingest/pipeline/logs_processing +{ + "processors": [ + { + "set": { + "field": "user", + "value": "guest", + "if": "ctx.user == null" + } + }, + { + "set": { + "field": "error", + "value": true, + "if": "ctx.status_code != null && ctx.status_code >= 400" + } + }, + { + "drop": { + "if": "ctx.app?.env == 'debug'" + } + } + ] +} +``` + +### 模拟管道 + +以下模拟请求将条件逻辑应用于三个文档: + +```json +POST _ingest/pipeline/logs_processing/_simulate +{ + "docs": [ + { + "_source": { + "message": "Successful login", + "status_code": 200 + } + }, + { + "_source": { + "message": "Database error", + "status_code": 500, + "user": "alice" + } + }, + { + "_source": { + "message": "Debug mode trace", + "app": { "env": "debug" } + } + } + ] +} +``` + +响应演示了处理器如何根据每个条件做出响应: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "status_code": 200, + "message": "Successful login", + "user": "guest" + }, + "_ingest": { + "timestamp": "2025-04-16T14:04:35.923159885Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "status_code": 500, + "message": "Database error", + "error": true, + "user": "alice" + }, + "_ingest": { + "timestamp": "2025-04-16T14:04:35.923198551Z" + } + } + }, + null + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/conditional-pipeline-processor.md b/i18n/zh/ingest-pipelines/conditional-pipeline-processor.md new file mode 100644 index 00000000..dee53037 --- /dev/null +++ b/i18n/zh/ingest-pipelines/conditional-pipeline-processor.md @@ -0,0 +1,259 @@ +--- +title: 使用管道处理器的条件 +--- + +# 使用管道处理器的条件 + +摄取管道中的 `pipeline` 处理器允许根据文档内容有条件地执行不同的子管道。当不同类型的文档需要单独的处理逻辑时,这提供了强大的灵活性。您可以在 `pipeline` 处理器中使用 `if` 参数,根据字段值、数据类型或内容结构将文档引导到不同的管道。然后,每个管道可以独立应用自己的一组处理器。这种方法通过仅在相关的地方应用逻辑,使您的管道保持模块化和可维护性。 + +## 示例:按服务路由日志 + +以下示例演示如何根据文档中的 `service.name` 字段将日志路由到不同的子管道。 + +创建名为 `webapp_logs` 的第一个管道: + +```json +PUT _ingest/pipeline/webapp_logs +{ + "processors": [ + { "set": { "field": "log_type", "value": "webapp" } } + ] +} +``` + +创建名为 `api_logs` 的第二个管道: + +```json +PUT _ingest/pipeline/api_logs +{ + "processors": [ + { "set": { "field": "log_type", "value": "api" } } + ] +} +``` + +创建名为 `service_router` 的主路由管道,该管道根据 `service.name` 将文档路由到相应的管道: + +```json +PUT _ingest/pipeline/service_router +{ + "processors": [ + { + "pipeline": { + "name": "webapp_logs", + "if": "ctx.service?.name == 'webapp'" + } + }, + { + "pipeline": { + "name": "api_logs", + "if": "ctx.service?.name == 'api'" + } + } + ] +} +``` + +使用以下请求模拟管道: + +```json +POST _ingest/pipeline/service_router/_simulate +{ + "docs": [ + { "_source": { "service": { "name": "webapp" }, "message": "Homepage loaded" } }, + { "_source": { "service": { "name": "api" }, "message": "GET /v1/users" } }, + { "_source": { "service": { "name": "worker" }, "message": "Task started" } } + ] +} +``` + +响应确认第一个文档由 `webapp_logs` 管道处理,第二个文档由 `api_logs` 管道处理。第三个文档保持不变,因为它不匹配任何条件: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "log_type": "webapp", + "message": "Homepage loaded", + "service": { + "name": "webapp" + } + }, + "_ingest": { + "timestamp": "2025-04-24T10:54:12.555447087Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "log_type": "api", + "message": "GET /v1/users", + "service": { + "name": "api" + } + }, + "_ingest": { + "timestamp": "2025-04-24T10:54:12.55548442Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "Task started", + "service": { + "name": "worker" + } + }, + "_ingest": { + "timestamp": "2025-04-24T10:54:12.555490754Z" + } + } + } + ] +} +``` + +### 拒绝不匹配的文档 + +在前面的示例中,不匹配任何条件的文档在没有处理的情况下被索引。要拒绝这些文档,请添加一个 [`fail` 处理器](/ingest-pipelines/processors/fail),其条件在其他条件都不匹配时匹配: + +```json +PUT _ingest/pipeline/service_router +{ + "processors": [ + { + "pipeline": { + "name": "webapp_logs", + "if": "ctx.service?.name == 'webapp'" + } + }, + { + "pipeline": { + "name": "api_logs", + "if": "ctx.service?.name == 'api'" + } + }, + { + "fail": { + "if": "!['webapp', 'api'].contains(ctx.service?.name)", + "message": "The service.name field must be webapp or api. Received: {{service.name}}" + } + } + ] +} +``` + +当您使用与前面示例相同的文档模拟管道时,前两个文档的处理方式如前所述。第三个文档失败,并显示消息 `The service.name field must be webapp or api. Received: worker`,OpenSearch 不会索引它。如果文档没有 `service.name` 字段,消息将以空值结尾。 + +### 将路由器应用于所有索引请求 + +要将索引到索引中的每个文档路由,而无需在每个请求中指定 `pipeline` 参数,请将路由管道设置为索引的默认管道。要将其应用于匹配模式的所有索引,请在[索引模板](/im-plugin/index-templates)中设置 `index.default_pipeline`: + +```json +PUT _index_template/service_logs +{ + "index_patterns": ["service-logs-*"], + "template": { + "settings": { + "index.default_pipeline": "service_router" + } + } +} +``` + +有关更多信息,请参阅[将管道应用于文档](/ingest-pipelines/#applying-a-pipeline-to-documents)。 + +## 示例:类型特定处理 + +您还可以使用管道处理器应用类型特定的管道。以下管道在 `code` 字段是数字时将日志定向到 `numeric_handler`,在它是 `String` 类型时定向到 `string_handler`。 + +创建名为 `numeric_handler` 的第一个管道: + +```json +PUT _ingest/pipeline/numeric_handler +{ + "processors": [ + { "set": { "field": "code_type", "value": "numeric" } } + ] +} +``` + +创建名为 `string_handler` 的第二个管道: + +```json +PUT _ingest/pipeline/string_handler +{ + "processors": [ + { "set": { "field": "code_type", "value": "string" } } + ] +} +``` + +创建名为 `type_router` 的主路由管道,该管道根据 `code` 字段将文档路由到相应的管道: + +```json +PUT _ingest/pipeline/type_router +{ + "processors": [ + { + "pipeline": { + "name": "numeric_handler", + "if": "ctx.code instanceof Integer || ctx.code instanceof Long || ctx.code instanceof Double" + } + }, + { + "pipeline": { + "name": "string_handler", + "if": "ctx.code instanceof String" + } + } + ] +} +``` + +使用以下请求模拟管道: + +```json +POST _ingest/pipeline/type_router/_simulate +{ + "docs": [ + { "_source": { "code": 404 } }, + { "_source": { "code": "ERR_NOT_FOUND" } } + ] +} +``` + +返回的文档具有由各个子管道添加的新字段 `code_type`: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "code": 404, + "code_type": "numeric" + } + } + }, + { + "doc": { + "_source": { + "code": "ERR_NOT_FOUND", + "code_type": "string" + } + } + } + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/processors/community_id.md b/i18n/zh/ingest-pipelines/processors/community_id.md new file mode 100644 index 00000000..e0abb6bc --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/community_id.md @@ -0,0 +1,169 @@ +--- +title: Community ID +--- + +# Community ID 处理器 + +`community_id` 处理器用于为网络流元组生成 community ID 流哈希值。community ID 流哈希算法在 [community ID 规范](https://github.com/corelight/community-id-spec)中定义。处理器生成的哈希值可用于关联所有相关的网络事件,以便您可以按哈希值过滤网络流数据或通过在哈希字段上聚合来生成统计信息。该处理器支持 TCP、UDP、SCTP、ICMP 和 IPv6-ICMP 网络协议。使用 SHA-1 哈希算法生成哈希值。 + +以下是 `community_id` 处理器的语法: + +```json +{ + "community_id": { + "source_ip_field": "source_ip", + "source_port_field": "source_port", + "destination_ip_field": "destination_ip", + "destination_port_field": "destination_port", + "iana_protocol_number_field": "iana_protocol_number", + "source_port_field": "source_port", + "target_field": "community_id" + } +} +``` + +## 参数 + +下表列出了 `community_id` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`source_ip_field` | 必需 | 包含源 IP 地址的字段名称。 | +`source_port_field` | 可选 | 包含源端口地址的字段名称。如果网络协议是 TCP、UDP 或 SCTP,则该字段是必需的。否则,它不是必需的。| +`destination_ip_field` | 必需 | 包含目标 IP 地址的字段名称。 | +`destination_port_field` | 可选 | 包含目标端口地址的字段名称。如果网络协议是 TCP、UDP 或 SCTP,则该字段是必需的。否则,它不是必需的。 | +`iana_protocol_number` | 可选 | 包含由互联网号码分配局 (IANA) 定义的协议编号的字段名称。支持的值为 1 (ICMP)、6 (TCP)、17 (UDP)、58 (IPv6-ICMP) 和 132 (SCTP)。 | +`protocol_field` | 可选 | 包含协议名称的字段名称。如果未设置 `iana_protocol_number`,则该字段是必需的。否则,它不是必需的。 | +`icmp_type_field` | 可选 | 包含 ICMP 消息类型的字段名称。当协议是 ICMP 或 IPv6-ICMP 时必需。 | +`icmp_code_field` | 可选 | 包含 ICMP 消息代码的字段名称。对于某些没有代码的 ICMP 消息类型,该字段是可选的。否则,它是必需的。 | +`seed` | 可选 | 用于生成 community ID 哈希的种子。值必须在 0 到 65535 之间。 | +`target_field` | 可选 | 存储 community ID 哈希值的字段名称。默认目标字段是 `community_id`。 | +`ignore_missing` | 可选 | 指定如果缺少必需字段之一,处理器是否应静默退出。默认为 `false`。 | +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 如果设置为 `true`,则忽略失败。默认为 `false`。 | +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `community_id_pipeline` 的管道,该管道使用 `community_id` 处理器为网络流元组生成哈希值: + +```json +PUT /_ingest/pipeline/commnity_id_pipeline +{ + "description": "generate hash value for the network flow tuple", + "processors": [ + { + "community_id": { + "source_ip_field": "source_ip", + "source_port_field": "source_port", + "destination_ip_field": "destination_ip", + "destination_port_field": "destination_port", + "iana_protocol_number_field": "iana_protocol_number", + "target_field": "community_id" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议您在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/commnity_id_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "source_ip": "66.35.250.204", + "source_port": 80, + "destination_ip": "128.232.110.120", + "destination_port": 34855, + "iana_protocol_number": 6 + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "community_id": "1:LQU9qZlK+B5F3KDmev6m5PMibrg=", + "destination_ip": "128.232.110.120", + "destination_port": 34855, + "source_port": 80, + "iana_protocol_number": 6, + "source_ip": "66.35.250.204" + }, + "_ingest": { + "timestamp": "2024-03-11T02:17:22.329823Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=commnity_id_pipeline +{ + "source_ip": "66.35.250.204", + "source_port": 80, + "destination_ip": "128.232.110.120", + "destination_port": 34855, + "iana_protocol_number": 6 +} +``` + +该请求将文档索引到 `testindex1` 索引中: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/fail.md b/i18n/zh/ingest-pipelines/processors/fail.md new file mode 100644 index 00000000..c730e810 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/fail.md @@ -0,0 +1,141 @@ +--- +title: Fail +--- + +# Fail 处理器 + +`fail` 处理器会引发异常,该异常会停止管道并使索引请求失败。`fail` 处理器的主要用例是在满足某些条件时使索引操作失败,并向客户端返回自定义消息。 + +以下是 `fail` 处理器的语法: + +```json +"fail": { + "if": "ctx.foo == 'bar'", + "message": "Custom error message" + } +``` + +## 参数 + +下表列出了 `fail` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`message` | 必需 | 要包含在失败响应中的自定义错误消息。支持[模板片段](/ingest-pipelines/create-ingest#template-snippets),例如 `Order {{order_id}} is missing a price`。 +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 指定处理器即使遇到错误也继续执行。如果设置为 `true`,则忽略失败。默认为 `false`。 | +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `fail-log-pipeline` 的管道,该管道使用 `fail` 处理器有意使日志事件的管道执行失败: + +```json +PUT _ingest/pipeline/fail-log-pipeline +{ + "description": "A pipeline to test the fail processor for log events", + "processors": [ + { + "fail": { + "if": "ctx.user_info.contains('password') || ctx.user_info.contains('credit card')", + "message": "Document containing personally identifiable information (PII) cannot be indexed!" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议您在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/fail-log-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "user_info": "Sensitive information including credit card" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "error": { + "root_cause": [ + { + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + } + ], + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=fail-log-pipeline +{ + "user_info": "Sensitive information including credit card" +} +``` + +由于 `user_info` 中存在字符串 `credit card`,该请求无法将日志事件索引到索引 `testindex1` 中。以下响应包括失败处理器中指定的自定义错误消息: + +```json +{ + "error": { + "root_cause": [ + { + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + } + ], + "type": "fail_processor_exception", + "reason": "Document containing personally identifiable information (PII) cannot be indexed!" + }, + "status": 500 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +由于管道失败,文档未被索引,因此响应包含 `"found": false`: + +```json +{ + "_index": "testindex1", + "_id": "1", + "found": false +} +``` diff --git a/i18n/zh/ingest-pipelines/processors/fingerprint.md b/i18n/zh/ingest-pipelines/processors/fingerprint.md new file mode 100644 index 00000000..6ca17d08 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/fingerprint.md @@ -0,0 +1,148 @@ +--- +title: Fingerprint +--- + +# Fingerprint 处理器 +<Badge type="tip" text="2.16 版本引入" /> + +`fingerprint` 处理器用于为某些指定字段或文档中的所有字段生成哈希值。哈希值可用于对索引内的文档进行去重和折叠搜索结果。 + +对于每个字段,字段名称、字段值的长度和字段值本身被连接并由管道字符 `|` 分隔。例如,如果字段名称为 `field1`,值为 `value1`,则连接的字符串将是 `|field1|3:value1|field2|10:value2|`。对于对象字段,字段名称通过用句点 `.` 连接嵌套字段名称来扁平化。例如,如果对象字段是 `root_field`,其子字段 `sub_field1` 的值为 `value1`,另一个子字段 `sub_field2` 的值为 `value2`,则连接的字符串将是 `|root_field.sub_field1|1:value1|root_field.sub_field2|100:value2|`。 + +以下是 `fingerprint` 处理器的语法: + +```json +{ + "community_id": { + "fields": ["foo", "bar"], + "target_field": "fingerprint", + "hash_method": "SHA-1@2.16.0" + } +} +``` + +## 参数 + +下表列出了 `fingerprint` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`fields` | 可选 | 用于生成哈希值的字段列表。 | +`exclude_fields` | 可选 | 指定要从哈希值生成中排除的字段。它与 `fields` 参数互斥;如果 `exclude_fields` 和 `fields` 都为空或 null,则哈希值计算中包含所有字段。 | +`hash_method` | 可选 | 指定要使用的哈希算法,选项包括 `MD5@2.16.0`、`SHA-1@2.16.0`、`SHA-256@2.16.0` 或 `SHA3-256@2.16.0`。默认为 `SHA-1@2.16.0`。附加版本号以确保跨 OpenSearch 版本的一致哈希,新版本将支持新的哈希方法。 | +`target_field` | 可选 | 指定存储生成的哈希值的字段名称。如果未提供,则默认情况下哈希值存储在 `fingerprint` 字段中。 | +`ignore_missing` | 可选 | 指定如果缺少必需字段之一,处理器是否应静默退出。默认为 `false`。 | +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 如果设置为 `true`,则忽略失败。默认为 `false`。 | +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `fingerprint_pipeline` 的管道,该管道使用 `fingerprint` 处理器为文档中的指定字段生成哈希值: + +```json +PUT /_ingest/pipeline/fingerprint_pipeline +{ + "description": "generate hash value for some specified fields the document", + "processors": [ + { + "fingerprint": { + "fields": ["foo", "bar"] + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议您在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/fingerprint_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "foo": "foo", + "bar": "bar" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "foo": "foo", + "bar": "bar", + "fingerprint": "SHA-1@2.16.0:fYeen7hTJ2zs9lpmUnk6nvH54sM=" + }, + "_ingest": { + "timestamp": "2024-03-11T02:17:22.329823Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=fingerprint_pipeline +{ + "foo": "foo", + "bar": "bar" +} +``` + +该请求将文档索引到 `testindex1` 索引中: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/foreach.md b/i18n/zh/ingest-pipelines/processors/foreach.md new file mode 100644 index 00000000..943ef7d4 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/foreach.md @@ -0,0 +1,309 @@ +--- +title: Foreach +--- + +<!-- vale off --> +# Foreach 处理器 +<!-- vale on --> + +`foreach` 处理器用于遍历输入文档中的值列表,并对每个值应用转换。这对于一致地处理数组中的所有元素的任务很有用,例如将数组中的所有元素转换为小写或大写。 + +以下是 `foreach` 处理器的语法: + +```json +{ + "foreach": { + "field": "<field_name>", + "processor": { + "<processor_type>": { + "<processor_config>": "<processor_value>" + } + } + } +} +``` + +## 参数 + +下表列出了 `foreach` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 要遍历的数组字段。 +`processor` | 必需 | 要为数组的每个元素运行的处理器。 +`ignore_missing` | 可选 | 如果为 `true` 且指定的字段不存在或为 null,则处理器将静默退出而不修改文档。默认为 `false`。 +`description` | 可选 | 处理器的简要描述。 +`if` | 可选 | 运行处理器的条件。 +`ignore_failure` | 可选 | 指定处理器即使遇到错误也继续执行。如果设置为 `true`,则忽略失败。默认为 `false`。 +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 访问数组元素 + +对于每个数组元素,`foreach` 处理器将元素存储在 `_ingest._value` 摄取元数据字段中,然后运行内部处理器。要读取或修改当前元素,请将内部处理器的字段设置为 `_ingest._value`。如果元素是对象,请使用点表示法访问其字段,例如 `_ingest._value.name`。 + +内部处理器还可以读取和修改文档中的任何其他字段。 + +在 `foreach` 处理器运行时,`_ingest._value` 始终保存当前数组元素,这会隐藏较早的处理器存储在 `_ingest._value` 中的任何值。当循环结束时,OpenSearch 将较早的值放回,因此管道中的后续处理器仍然可以读取它。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `test-foreach` 的管道,该管道使用 `foreach` 处理器遍历 `protocols` 字段中的每个元素: + +```json +PUT _ingest/pipeline/test-foreach +{ + "description": "Lowercase all the elements in an array", + "processors": [ + { + "foreach": { + "field": "protocols", + "processor": { + "lowercase": { + "field": "_ingest._value" + } + } + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议您在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/test-foreach/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source": { + "protocols": ["HTTP","HTTPS","TCP","UDP"] + } + } + ] +} +``` + +以下示例响应确认管道按预期工作,显示四个元素已转换为小写: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "protocols": [ + "http", + "https", + "tcp", + "udp" + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2024-05-23T02:44:10.8201Z" + } + } + } + ] +} + +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +POST testindex1/_doc/1?pipeline=test-foreach +{ + "protocols": ["HTTP","HTTPS","TCP","UDP"] +} +``` + +该请求将文档索引到索引 `testindex1` 中,并在索引之前应用管道: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 6, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 5, + "_primary_term": 67 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 + +## 处理对象数组 + +以下请求从 `products` 数组中的每个对象中删除 `internal_sku` 字段: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "foreach": { + "field": "products", + "processor": { + "remove": { + "field": "_ingest._value.internal_sku" + } + } + } + } + ] + }, + "docs": [ + { + "_source": { + "order_id": "A-1001", + "products": [ + { "name": "Wireless mouse", "price": 24.99, "internal_sku": "WM-4471" }, + { "name": "USB-C cable", "price": 9.99, "internal_sku": "UC-2210" } + ] + } + } + ] +} +``` + +响应显示 `internal_sku` 字段已从两个对象中删除: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "order_id": "A-1001", + "products": [ + { + "name": "Wireless mouse", + "price": 24.99 + }, + { + "name": "USB-C cable", + "price": 9.99 + } + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2026-10-14T19:40:29.753456004Z" + } + } + } + ] +} +``` + +## 处理数组元素的失败 + +如果内部处理器对某个元素失败且未定义 `on_failure`,则 `foreach` 处理器停止处理数组并失败。 + +要处理单个元素的失败,请在内部处理器中指定 `on_failure`。在以下请求中,`products` 数组中的第二个对象不包含 `internal_sku` 字段,因此 `remove` 处理器对该元素失败。`on_failure` 处理器将文档发送到 `failed-orders` 索引: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "foreach": { + "field": "products", + "processor": { + "remove": { + "field": "_ingest._value.internal_sku", + "on_failure": [ + { + "set": { + "field": "_index", + "value": "failed-orders" + } + } + ] + } + } + } + } + ] + }, + "docs": [ + { + "_index": "orders", + "_source": { + "order_id": "A-1002", + "products": [ + { "name": "Wireless mouse", "price": 24.99, "internal_sku": "WM-4471" }, + { "name": "USB-C cable", "price": 9.99 } + ] + } + } + ] +} +``` + +响应显示目标索引更改为 `failed-orders`。由于 `on_failure` 块处理了失败,`foreach` 处理器继续处理剩余的元素,并且成功处理的元素保留了它们的更改: + +```json +{ + "docs": [ + { + "doc": { + "_index": "failed-orders", + "_id": "_id", + "_source": { + "order_id": "A-1002", + "products": [ + { + "name": "Wireless mouse", + "price": 24.99 + }, + { + "name": "USB-C cable", + "price": 9.99 + } + ] + }, + "_ingest": { + "_value": null, + "timestamp": "2026-10-14T19:40:29.808936921Z" + } + } + } + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/processors/gsub.md b/i18n/zh/ingest-pipelines/processors/gsub.md new file mode 100644 index 00000000..3a8ca0f3 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/gsub.md @@ -0,0 +1,141 @@ +--- +title: gsub 处理器 +--- + +<!-- vale off --> +# Gsub 处理器 +<!-- vale on --> + +`gsub` 处理器对传入文档中的字符串字段执行正则表达式搜索和替换操作。如果字段包含字符串数组,则该操作应用于数组中的所有元素。但是,如果字段包含非字符串值,处理器会抛出异常。`gsub` 处理器的使用场景包括从日志消息或用户生成的内容中删除敏感信息,规范化数据格式或约定(例如,转换日期格式、删除特殊字符),以及从字段值中提取或转换子字符串以进行进一步处理或分析。 + +以下是 `gsub` 处理器的语法: + +```json +"gsub": { + "field": "field_name", + "pattern": "regex_pattern", + "replacement": "replacement_string" +} +``` + +## 参数 + +下表列出了 `gsub` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 要应用替换的字段。 +`pattern` | 必需 | 要替换的模式。 +`replacement` | 必需 | 将替换匹配模式的字符串。 +`target_field` | 可选 | 存储解析数据的字段名称。如果未指定 `target_field`,解析的数据将替换 `field` 字段中的原始数据。默认值为 `field`。 +`description` | 可选 | 处理器的简要描述。 +`if` | 可选 | 运行处理器的条件。 +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定字段或字段为 `null` 的文档。默认值为 `false`。 +`ignore_failure` | 可选 | 指定处理器是否即使在遇到错误时也继续执行。如果设置为 `true`,则忽略失败。默认值为 `false`。 +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `gsub_pipeline` 的管道,该管道使用 `gsub` 处理器将 `message` 字段中所有出现的 `error` 替换为 `warning`: + +```json +PUT _ingest/pipeline/gsub_pipeline +{ + "description": "将 'message' 字段中的 'error' 替换为 'warning'", + "processors": [ + { + "gsub": { + "field": "message", + "pattern": "error", + "replacement": "warning" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/gsub_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "message": "This is an error message" + } + } + ] +} +``` + +以下响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "This is an warning message" + }, + "_ingest": { + "timestamp": "2024-05-22T19:47:00.645687211Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `logs` 的索引中: + +```json +PUT logs/_doc/1?pipeline=gsub_pipeline +{ + "message": "This is an error message" +} +``` + +以下响应显示请求已将文档索引到名为 `logs` 的索引中,并且 `gsub` 处理器已将 `message` 字段中所有出现的 `error` 替换为 `warning`: + +```json +{ + "_index": "logs", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET logs/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/html-strip.md b/i18n/zh/ingest-pipelines/processors/html-strip.md new file mode 100644 index 00000000..53076a94 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/html-strip.md @@ -0,0 +1,137 @@ +--- +title: HTML strip 处理器 +--- + +# HTML strip 处理器 + +`html_strip` 处理器从传入文档中的字符串字段中删除 HTML 标签。此处理器在索引来自网页或其他可能包含 HTML 标记的来源的数据时非常有用。块级标签,如 `<p>`、`<div>`、`<br>` 和 `<li>`,会被替换为换行符(`\n`)。内联标签,如 `<b>`、`<span>` 和 `<a>`,会被删除。例如,`<p>Hello <b>world</b></p>` 变为 `\nHello world\n`。对于数组字段,处理器从每个字符串元素中剥离标签。 + +以下是 `html_strip` 处理器的语法: + +```json +{ + "html_strip": { + "field": "webpage" + } +} +``` + +## 参数 + +下表列出了 `html_strip` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 要从中删除 HTML 标签的字符串字段。 +`target_field` | 可选 | 在剥离 HTML 标签后接收纯文本版本的字段。如果未指定,则就地更新字段。 +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定字段或字段为 `null` 的文档。默认值为 `false`。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure` | 可选 | 指定如果处理器在执行期间失败要运行的处理器列表。这些处理器按指定的顺序执行。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `strip-html-pipeline` 的管道,该管道使用 `html_strip` 处理器从 description 字段中删除 HTML 标签,并将处理后的值存储在名为 `cleaned_description` 的新字段中: + +```json +PUT _ingest/pipeline/strip-html-pipeline +{ + "description": "从 description 字段中剥离 HTML 的管道", + "processors": [ + { + "html_strip": { + "field": "description", + "target_field": "cleaned_description" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/strip-html-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "description": "This is a <b>test</b> description with <i>some</i> HTML tags." + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "description": "This is a <b>test</b> description with <i>some</i> HTML tags.", + "cleaned_description": "This is a test description with some HTML tags." + }, + "_ingest": { + "timestamp": "2024-05-22T21:46:11.227974965Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `products` 的索引中: + +```json +PUT products/_doc/1?pipeline=strip-html-pipeline +{ + "description": "This is a <b>test</b> description with <i>some</i> HTML tags." +} +``` + +响应显示请求已将文档索引到 `products` 索引中,并将索引所有包含 HTML 标签的 `description` 字段的文档,同时将纯文本版本存储在 `cleaned_description` 字段中: + +```json +{ + "_index": "products", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET products/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/join.md b/i18n/zh/ingest-pipelines/processors/join.md new file mode 100644 index 00000000..65f873e2 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/join.md @@ -0,0 +1,127 @@ +--- +title: Join 处理器 +--- + +# Join 处理器 + +`join` 处理器将数组的元素连接成单个字符串值,在每个元素之间使用指定的分隔符。如果提供的输入不是数组,它会抛出异常。 + +以下是 `join` 处理器的语法: + +```json +{ + "join": { + "field": "field_name", + "separator": "separator_string" + } +} +``` + +## 参数 + +下表列出了 `join` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 应用 join 操作符的字段名称。必须是数组。 +`separator` | 必需 | 连接字段值时使用的字符串分隔符。如果未指定,则在不使用分隔符的情况下连接值。 +`target_field` | 可选 | 分配清理后值的字段。如果未指定,则就地更新字段。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器的失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure` | 可选 | 指定处理处理器的失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`tag` | 可选 | 处理器的标识符。对于调试和指标很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `example-join-pipeline` 的管道,该管道使用 `join` 处理器连接 `uri` 字段的所有值,使用指定的分隔符 `/` 分隔它们: + +```json +PUT _ingest/pipeline/example-join-pipeline +{ + "description": "使用 join 处理器的示例管道", + "processors": [ + { + "join": { + "field": "uri", + "separator": "/" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/example-join-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "uri": [ + "app", + "home", + "overview" + ] + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "uri": "app/home/overview" + }, + "_ingest": { + "timestamp": "2024-05-24T02:16:01.00659117Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +POST testindex1/_doc/1?pipeline=example-join-pipeline +{ + "uri": [ + "app", + "home", + "overview" + ] +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/json.md b/i18n/zh/ingest-pipelines/processors/json.md new file mode 100644 index 00000000..c107ae30 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/json.md @@ -0,0 +1,186 @@ +--- +title: JSON 处理器 +--- + +# JSON 处理器 + +`json` 处理器将 JSON 格式的字符串解析为结构化数据,这对于各种数据处理和增强任务很有用。处理器解析所有 JSON 数据类型:对象、数组、字符串、数字、布尔值和 `null`。例如,字符串 `"[1,2,3]"` 被解析为数组,字符串 `"42"` 被解析为数字。 + +以下是 `json` 处理器的语法: + +```json +{ + "json": { + "field": "<field_name>", + "target_field": "<target_field_name>", + "add_to_root": <boolean> + } +} +``` + +## 参数 + +下表列出了 `json` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 包含要反序列化的 JSON 格式字符串的字段名称。 +`target_field` | 可选 | 存储反序列化 JSON 数据的字段名称。如果未提供,数据将存储在 `field` 字段中。如果 `target_field` 存在,其现有值将被新的 JSON 数据覆盖。 +`add_to_root` | 可选 | 一个布尔标志,用于确定反序列化的 JSON 数据应添加到文档的根 (`true`) 还是存储在 target_field (`false`) 中。如果 `add_to_root` 为 `true`,则 `target_field` 无效。解析的字段会覆盖具有相同名称的根字段。如果 `add_to_root` 为 `true` 且解析的值不是 JSON 对象,则处理器失败。默认值为 `false`。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure`| 可选 | 指定如果处理器在执行期间失败要运行的处理器列表。这些处理器按指定的顺序执行。 +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `my-json-pipeline` 的管道,该管道使用 `json` 处理器处理 JSON 数据并使用附加信息丰富文档: + +```json +PUT _ingest/pipeline/my-json-pipeline +{ + "description": "使用 JsonProcessor 的示例管道", + "processors": [ + { + "json": { + "field": "raw_data", + "target_field": "parsed_data", + "on_failure": [ + { + "set": { + "field": "error_message", + "value": "Failed to parse JSON data" + } + }, + { + "fail": { + "message": "Failed to process JSON data" + } + } + ] + } + }, + { + "set": { + "field": "processed_timestamp", + "value": "{{_ingest.timestamp}}" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/my-json-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "raw_data": "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}" + } + }, + { + "_source": { + "raw_data": "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "processed_timestamp": "2024-05-30T15:24:48.064472090Z", + "raw_data": "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}", + "parsed_data": { + "name": "John", + "city": "New York", + "age": 30 + } + }, + "_ingest": { + "timestamp": "2024-05-30T15:24:48.06447209Z" + } + } + }, + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "processed_timestamp": "2024-05-30T15:24:48.064543006Z", + "raw_data": "{\"name\":\"Jane\",\"age\":25,\"city\":\"Los Angeles\"}", + "parsed_data": { + "name": "Jane", + "city": "Los Angeles", + "age": 25 + } + }, + "_ingest": { + "timestamp": "2024-05-30T15:24:48.064543006Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `my-index` 的索引中: + +```json +PUT my-index/_doc/1?pipeline=my-json-pipeline +{ + "raw_data": "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}" +} +``` + +响应确认已成功索引包含来自 `raw_data` 字段的 JSON 数据的文档: + +```json +{ + "_index": "my-index", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 3, + "_primary_term": 2 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET my-index/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/ml-inference.md b/i18n/zh/ingest-pipelines/processors/ml-inference.md new file mode 100644 index 00000000..8575caca --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/ml-inference.md @@ -0,0 +1,457 @@ +--- +title: ML inference 处理器 +--- + +# ML inference 处理器 + +`ml_inference` 处理器调用在 OpenSearch 中注册的[机器学习 (ML) 模型](/ml-commons-plugin/)。模型输出作为新字段添加到摄取的文档中。 + +::: info NOTE +**先决条件**<br> +在使用 `ml_inference` 处理器之前,您必须拥有托管在 OpenSearch 集群上的本地 ML 模型或连接到 OpenSearch 集群的外部托管模型。有关本地模型的更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)。有关外部托管模型的更多信息,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 +::: + +## 语法 + +以下是 `ml_inference` 处理器的语法: + +```json +{ + "ml_inference": { + "model_id": "<model_id>", + "function_name": "<function_name>", + "full_response_path": "<full_response_path>", + "model_config":{ + "<model_config_field>": "<config_value>" + }, + "model_input": "<model_input>", + "input_map": [ + { + "<model_input_field>": "<document_field>" + } + ], + "output_map": [ + { + "<new_document_field>": "<model_output_field>" + } + ], + "override": "<override>" + } +} +``` + +## 参数 + +下表列出了 `ml_inference` 处理器的必需和可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:--- | :--- | :--- | :--- | +| `model_id` | 字符串 | 必需 | 处理器使用的 ML 模型的 ID。 | +| `function_name` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 在处理器中配置的 ML 模型的函数名称。对于本地模型,有效值为 `sparse_encoding`、`sparse_tokenize`、`text_embedding` 和 `text_similarity`。对于外部托管模型,有效值为 `remote`。默认值为 `remote`。 | +| `model_config` | 对象 | 可选 | ML 模型的自定义配置选项。对于外部托管模型,如果设置,此配置将覆盖默认连接器参数。对于本地模型,您可以将 `model_config` 添加到 `model_input` 以覆盖注册期间设置的模型配置。有关更多信息,请参阅 [`model_config` 对象](/ml-commons-plugin/api/model-apis/register-model#the-model_config-object)。 | +| `model_input` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 定义模型期望的输入字段格式的模板。每种本地模型类型可能使用不同的输入集。对于外部托管模型,默认值为 `"{ \"parameters\": ${ml_inference.parameters} }`。| +| `input_map` | 数组 | 外部托管模型可选<br/><br/>本地模型必需 | 一个数组,指定如何将摄取的文档字段映射到模型输入字段。数组的每个元素是 `"<model_input_field>": "<document_field>"` 格式的映射,对应于一个文档字段的一次模型调用。如果未为外部托管模型指定输入映射,则文档中的所有字段将直接作为输入传递给模型。`input_map` 大小表示模型被调用的次数(Predict API 请求的数量)。对于外部托管模型,模型输入字段是连接器请求正文模板中的参数。有关更多信息,请参阅[将输入作为参数提供](/ml-commons-plugin/remote-models/connector-input-output#providing-input-as-parameters)。 | +| `<model_input_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 模型输入字段名称。 | +| `<document_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 用作模型输入的摄取文档字段的名称或 JSON 路径。 | +| `output_map` | 数组 | 外部托管模型可选<br/><br/>本地模型必需 | 一个数组,指定如何将模型输出字段映射到摄取文档中的新字段。数组的每个元素是 `"<new_document_field>": "<model_output_field>"` 格式的映射。| +| `<new_document_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 摄取文档中新字段的名称,模型的输出(由 `model_output` 指定)存储在其中。如果未为外部托管模型指定输出映射,则模型输出中的所有字段将添加到新文档字段中。 | +| `<model_output_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 要存储在 `new_document_field` 中的模型输出中字段的名称或 JSON 路径。 | +| `full_response_path` | 布尔值 | 可选 | 如果 `model_output_field` 包含字段的完整 JSON 路径而不是字段名称,则将此参数设置为 `true`。然后将完全解析模型输出以获取字段的值。对于本地模型,默认值为 `true`,对于外部托管模型,默认值为 `false`。 | +| `ignore_missing` | 布尔值 | 可选 | 如果为 `true` 且 `input_map` 或 `output_map` 中定义的任何输入字段缺失,则忽略缺失的字段。否则,缺失的字段会导致失败。默认值为 `false`。 | +| `ignore_failure` | 布尔值 | 可选 | 指定处理器是否即使在遇到错误时也继续执行。如果为 `true`,则忽略任何失败并继续摄取。如果为 `false`,则任何失败都会导致摄取被取消。默认值为 `false`。 | +| `override` | 布尔值 | 可选 | 在摄取的文档已包含 `<new_document_field>` 中指定的名称的字段时相关。如果 `override` 为 `false`,则跳过输入字段。如果为 `true`,则现有字段值将被新模型输出覆盖。默认值为 `false`。 | +| `max_prediction_tasks` | 整数 | 可选 | 在文档摄取期间可以运行的并发模型调用的最大数量。默认值为 `10`。 | +| `description` | 字符串 | 可选 | 处理器的简要描述。 | +| `if` | 包含布尔表达式的字符串 | 可选 | 运行处理器的条件。 | +| `on_failure` | 列表 | 可选 | 如果处理器失败,要运行的处理器列表。 | +| `tag` | 字符串 | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +::: info NOTE +`input_map` 和 `output_map` 映射支持标准 [JSON path](https://github.com/json-path/JsonPath) 表示法来指定复杂的数据结构。 +::: + +## 使用处理器 + +按照以下步骤在管道中使用处理器。创建处理器时必须提供模型 ID。在测试管道或使用处理器摄取文档之前,请确保模型已成功部署。您可以使用 [Get Model API](/ml-commons-plugin/api/model-apis/get-model) 检查模型状态。 + +对于本地模型,您必须提供一个 `model_input` 字段来指定模型输入格式。将 `model_config` 中的任何输入字段添加到 `model_input`。 + +对于远程模型,`model_input` 字段是可选的,其默认值为 `"{ \"parameters\": ${ml_inference.parameters} }`。 + +### 示例:外部托管模型 + +以下示例使用外部托管模型配置 `ml_inference` 处理器。 + +#### 步骤 1:创建管道 + +以下示例为外部托管的文本嵌入模型创建摄取管道。模型需要 `input` 字段并在 `data` 字段中生成结果。它将 `passage_text` 字段中的文本转换为文本嵌入并将嵌入存储在 `passage_embedding` 字段中。处理器配置中未明确指定 `function_name`,因此它默认为 `remote`,表示外部托管模型: + +```json +PUT /_ingest/pipeline/ml_inference_pipeline +{ + "description": "为摄取的文档生成 passage_embedding", + "processors": [ + { + "ml_inference": { + "model_id": "<your model id>", + "input_map": [ + { + "input": "passage_text" + } + ], + "output_map": [ + { + "passage_embedding": "data" + } + ] + } + } + ] +} +``` + +对于外部托管模型的 Predict API 请求,所有字段通常嵌套在 `parameters` 对象内: + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict +{ + "parameters": { + "input": [ + { + ... + } + ] + } +} +``` + +在为外部托管模型指定 `input_map` 时,您可以直接引用 `input` 字段,而不是提供其点路径 `parameters.input`: + +```json +"input_map": [ + { + "input": "passage_text" + } +] +``` + +`input_map` 中的每个键命名一个参数,该参数填充连接器请求正文模板中的占位符。在此示例中,`input` 键填充 `${parameters.input}` 占位符。有关更多信息,请参阅[将输入作为参数提供](/ml-commons-plugin/remote-models/connector-input-output#providing-input-as-parameters)。 + +#### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/ml_inference_pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source":{ + "passage_text": "hello world" + } + } + ] +} +``` + +响应确认处理器已在 `passage_embedding` 字段中生成文本嵌入。文档现在包含 `passage_text` 和 `passage_embedding` 字段: + +```json +{ + "docs" : [ + { + "doc" : { + "_index" : "testindex1", + "_id" : "1", + "_source" : { + "passage_embedding" : [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ... + ], + "passage_text" : "hello world" + }, + "_ingest" : { + "timestamp" : "2023-10-11T22:35:53.654650086Z" + } + } + } + ] +} +``` + +::: info NOTE +创建摄取管道后,您需要创建用于摄取的索引并将文档摄取到索引中。 +::: + +### 示例:本地模型 + +以下示例使用本地模型配置 `ml_inference` 处理器。 + +#### 步骤 1:创建管道 + +以下示例为 `huggingface/sentence-transformers/all-distilroberta-v1` 本地模型创建摄取管道。该模型是托管在 OpenSearch 集群中的句子转换器[预训练模型](/ml-commons-plugin/pretrained-models#sentence-transformers)。 + +如果您使用 Predict API 调用模型,则请求如下所示: + +```json +POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs":[ "today is sunny"], + "return_number": true, + "target_response": ["sentence_embedding"] +} +``` + +使用此架构,按如下方式指定 `model_input`: + +```json + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }" +``` + +在 `input_map` 中,将 `book.*.chunk.text.*.context` 文档字段映射到模型期望的 `text_docs` 字段: + +```json +"input_map": [ + { + "text_docs": "book.*.chunk.text.*.context" + } +] +``` + +因为您将要转换为嵌入的字段指定为 JSON 路径,所以需要将 `full_response_path` 设置为 `true`,以便完全解析 JSON 文档以获取输入字段: + +```json +"full_response_path": true +``` + +您索引的文档将如下所示。`context` 字段中的文本将用于生成嵌入: + +```json +"book": [ + { + "chunk": { + "text": [ + { + "chapter": "first chapter", + "context": "this is the first part" + } + ] + } + } +] +``` + +Predict API 请求返回以下响应: + +```json +{ + "inference_results" : [ + { + "output" : [ + { + "name" : "sentence_embedding", + "data_type" : "FLOAT32", + "shape" : [ + 768 + ], + "data" : [ + 0.25517133, + -0.28009856, + 0.48519906, + ... + ] + } + ] + } + ] +} +``` + +模型在 `$.inference_results.*.output.*.data` 字段中生成嵌入。`output_map` 将此字段映射到摄取文档中新创建的 `book.*.chunk.text.*.context_embedding` 字段: + +```json +"output_map": [ + { + "book.*.chunk.text.*.context_embedding": "$.inference_results.*.output.*.data" + } +] +``` + +要使用本地模型配置 `ml_inference` 处理器,请明确指定 `function_name`。在此示例中,`function_name` 为 `text_embedding`。有关有效 `function_name` 值的信息,请参阅[参数](#parameters)。 + +在此示例中,使用本地模型的 `ml_inference` 处理器的最终配置如下: + +```json +PUT /_ingest/pipeline/ml_inference_pipeline_local +{ + "description": "摄取评论并生成嵌入", + "processors": [ + { + "ml_inference": { + "function_name": "text_embedding", + "full_response_path": true, + "model_id": "<your model id>", + "model_config": { + "return_number": true, + "target_response": ["sentence_embedding"] + }, + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }", + "input_map": [ + { + "text_docs": "book.*.chunk.text.*.context" + } + ], + "output_map": [ + { + "book.*.chunk.text.*.context_embedding": "$.inference_results.*.output.*.data" + } + ], + "ignore_missing": true, + "ignore_failure": true + } + } + ] +} +``` + +#### 步骤 2(可选):测试管道 + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/ml_inference_pipeline/_simulate +{ + "docs": [ + { + "_index": "my_books", + "_id": "1", + "_source": { + "book": [ + { + "chunk": { + "text": [ + { + "chapter": "first chapter", + "context": "this is the first part" + }, + { + "chapter": "first chapter", + "context": "this is the second part" + } + ] + } + }, + { + "chunk": { + "text": [ + { + "chapter": "second chapter", + "context": "this is the third part" + }, + { + "chapter": "second chapter", + "context": "this is the fourth part" + } + ] + } + } + ] + } + } + ] +} +``` + +响应确认处理器已在 `context_embedding` 字段中生成文本嵌入。文档现在在同一路径下包含 `context` 和 `context_embedding` 字段: + +```json +{ + "docs" : [ + { + "doc" : { + "_index": "my_books", + "_id": "1", + "_source": { + "book": [ + { + "chunk": { + "text": [ + { + "chapter": "first chapter", + "context": "this is the first part", + "context_embedding": [ + 0.15756914, + 0.05150984, + 0.25225413, + 0.4941875, + ... + ] + }, + { + "chapter": "first chapter", + "context": "this is the second part", + "context_embedding": [ + 0.10526893, + 0.026559234, + 0.28763372, + 0.4653795, + ... + ] + } + ] + } + }, + { + "chunk": { + "text": [ + { + "chapter": "second chapter", + "context": "this is the third part", + "context_embedding": [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ... + ] + }, + { + "chapter": "second chapter", + "context": "this is the fourth part", + "context_embedding": [ + 0.37742054, + 0.046911318, + 1.2053889, + 0.04663613, + ... + ] + } + ] + } + } + ] + } + } + } + ] +} +``` + +::: info NOTE +创建摄取管道后,您需要创建用于摄取的索引并将文档摄取到索引中。 +::: + +## 后续步骤 + +- 有关在摄取期间生成文本和图像嵌入的完整示例,请参阅[使用 ML 推理处理器的多模态搜索](/tutorials/vector-search/semantic-search/multimodal-search-ml-inference/)。 +- 有关在摄取期间检测文档语言的完整示例,请参阅[识别多语言搜索的文档语言](/tutorials/language-identification/)。 +- 有关为文本块生成嵌入的完整示例,请参阅[使用文本分块的语义搜索](/tutorials/vector-search/semantic-search/long-document/)。 diff --git a/i18n/zh/ingest-pipelines/processors/pipeline.md b/i18n/zh/ingest-pipelines/processors/pipeline.md new file mode 100644 index 00000000..ac5c662a --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/pipeline.md @@ -0,0 +1,236 @@ +--- +title: Pipeline 处理器 +--- + +# Pipeline 处理器 + +`pipeline` 处理器允许管道引用和包含另一个预定义的管道。当您有一组需要在多个管道之间共享的通用处理器时,这会很有用。您可以创建一个包含共享处理器的单独基础管道,而不是在每个管道中重新定义这些通用处理器,然后使用 pipeline 处理器从其他管道引用该基础管道。 + +以下是 `pipeline` 处理器的语法: + +```json +{ + "pipeline": { + "name": "general-pipeline" + } +} +``` + +## 参数 + +下表列出了 `pipeline` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`name` | 必需 | 要执行的管道名称。支持[模板片段](#selecting-a-pipeline-dynamically)。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure` | 可选 | 指定处理处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`tag` | 可选 | 处理器的标识符。对于调试和指标很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `general-pipeline` 的管道,该管道将 `protocol` 字段转换为大写并删除 `name` 字段: + +```json +PUT _ingest/pipeline/general-pipeline +{ + "description": "一个通用管道", + "processors": [ + { + "uppercase": { + "field": "protocol" + } + }, + { + "remove": { + "field": "name" + } + } + ] +} +``` + +以下查询创建名为 `outer-pipeline` 的管道,该管道使用 `pipeline` 处理器运行 `general-pipeline`: + +```json +PUT _ingest/pipeline/outer-pipeline +{ + "description": "引用通用管道的外部管道", + "processors": [ + { + "pipeline": { + "name": "general-pipeline" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/outer-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "protocol": "https", + "name":"test" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "protocol": "HTTPS" + }, + "_ingest": { + "timestamp": "2024-05-24T02:43:43.700735801Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +POST testindex1/_doc/1?pipeline=outer-pipeline +{ + "protocol": "https", + "name": "test" +} +``` + +请求将文档索引到 `testindex1` 索引中,并将 `protocol` 字段转换为大写并删除 `name` 字段,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 2, + "result": "created", + "_shards": { + "total": 2, + "successful": 2, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 + +## 动态选择管道 + +`name` 参数支持模板片段,因此您可以根据文档中的字段值选择要运行的管道。以下请求创建一个解析 NGINX 日志的管道: + +```json +PUT _ingest/pipeline/logs-nginx +{ + "processors": [ + { + "set": { + "field": "parsed_by", + "value": "{{_ingest.pipeline}}" + } + } + ] +} +``` + +以下请求创建一个管道,该管道运行名为 `logs-` 后跟文档的 `service` 字段值的管道: + +```json +PUT _ingest/pipeline/logs-router +{ + "processors": [ + { + "set": { + "field": "routed_by", + "value": "{{_ingest.pipeline}}" + } + }, + { + "pipeline": { + "name": "logs-{{service}}" + } + } + ] +} +``` + +索引一个 `service` 字段为 `nginx` 的文档: + +```json +PUT logs/_doc/1?pipeline=logs-router +{ + "service": "nginx", + "message": "GET /index.html 200" +} +``` + +检索文档: + +```json +GET logs/_doc/1 +``` + +响应显示 `logs-router` 管道运行了 `logs-nginx` 管道: + +```json +{ + "_index": "logs", + "_id": "1", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "found": true, + "_source": { + "parsed_by": "logs-nginx", + "service": "nginx", + "message": "GET /index.html 200", + "routed_by": "logs-router" + } +} +``` + +如果解析的管道不存在,或者运行它会创建一个管道运行自身的循环,则 `pipeline` 处理器失败。 + +## 访问当前管道名称 + +`_ingest.pipeline` 摄取元数据字段包含当前正在运行的管道的 ID。在前面的示例中,`routed_by` 字段包含 `logs-router`,`parsed_by` 字段包含 `logs-nginx`,因为每个 `set` 处理器在不同的管道中运行。内部管道完成后,`_ingest.pipeline` 再次包含外部管道的 ID。 diff --git a/i18n/zh/ingest-pipelines/processors/remove-by-pattern.md b/i18n/zh/ingest-pipelines/processors/remove-by-pattern.md new file mode 100644 index 00000000..71dfc772 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/remove-by-pattern.md @@ -0,0 +1,124 @@ +--- +title: Remove by pattern 处理器 +--- + +# Remove by pattern 处理器 + +`remove_by_pattern` 处理器使用指定的通配符模式从文档中删除根级别字段。 + +## 语法 + +以下是 `remove_by_pattern` 处理器的语法: + +```json +{ + "remove_by_pattern": { + "field_pattern": "field_name_prefix*" + } +} +``` + +## 参数 + +下表列出了 `remove_by_pattern` 处理器的必需和可选参数。 + +| 参数 | 必需/可选 | 描述 | +|---|---|---| +`field_pattern` | 可选 | 删除匹配指定模式的字段。如果所有元数据字段(如 `_index`、`_version`、`_version_type` 和 `_id`)匹配模式,则忽略它们。此选项仅支持文档中的根级别字段。 | +`exclude_field_pattern` | 可选 | 删除不匹配指定模式的字段。如果所有元数据字段(如 `_index`、`_version`、`_version_type` 和 `_id`)不匹配模式,则忽略它们。此选项仅支持文档中的根级别字段。`field_pattern` 和 `exclude_field_pattern` 选项是互斥的。 | +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 指定处理器是否即使在遇到错误时也继续执行。如果设置为 `true`,则忽略失败。默认值为 `false`。 | +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `remove_fields_by_pattern` 的管道,该管道删除匹配模式 `foo*` 的字段: + +```json +PUT /_ingest/pipeline/remove_fields_by_pattern +{ + "description": "按模式删除字段的管道。", + "processors": [ + { + "remove_by_pattern": { + "field_pattern": "foo*" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/remove_fields_by_pattern/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source":{ + "foo1": "foo1", + "foo2": "foo2", + "bar": "bar" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "bar": "bar" + }, + "_ingest": { + "timestamp": "2023-08-24T18:02:13.218986756Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=remove_fields_by_pattern +{ + "foo1": "foo1", + "foo2": "foo2", + "bar": "bar" +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/rename.md b/i18n/zh/ingest-pipelines/processors/rename.md new file mode 100644 index 00000000..5fcab5e5 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/rename.md @@ -0,0 +1,133 @@ +--- +title: Rename 处理器 +--- + +# Rename 处理器 + +`rename` 处理器用于重命名现有字段,也可用于将字段从一个对象移动到另一个对象或移动到根级别。 + +## 语法 + +以下是 `rename` 处理器的语法: + +```json +{ + "rename": { + "field": "field_name", + "target_field" : "target_field_name" + } +} +``` + +## 参数 + +下表列出了 `rename` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +---|---|---| +`field` | 必需 | 要重命名的字段名称。支持[模板片段](/ingest-pipelines/create-ingest#template-snippets)。 | +`target_field` | 必需 | 字段的新名称。支持[模板片段](/ingest-pipelines/create-ingest#template-snippets)。 | +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定 `field` 的文档。如果设置为 `true`,则如果 `field` 不存在,处理器不会修改文档。如果设置为 `false`,则如果 `field` 不存在,处理器会失败。默认值为 `false`。 | +`override_target` | 可选 | 确定当 `target_field` 在文档中存在时会发生什么。如果设置为 `true`,处理器会用新值覆盖现有的 `target_field` 值。如果设置为 `false` 且 `target_field` 存在,处理器会失败。默认值为 `false`。 | +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 指定处理器是否即使在遇到错误时也继续执行。如果设置为 `true`,则忽略失败。默认值为 `false`。 | +`on_failure` | 可选 | 如果处理器失败,要运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `rename_field` 的管道,该管道将对象中的字段移动到根级别: + +```json +PUT /_ingest/pipeline/rename_field +{ + "description": "将字段移动到根级别的管道。", + "processors": [ + { + "rename": { + "field": "message.content", + "target_field": "content" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/rename_field/_simulate +{ + "docs": [ + { + "_index": "testindex1", + "_id": "1", + "_source":{ + "message": { + "type": "nginx", + "content": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456" + } + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex1", + "_id": "1", + "_source": { + "message": { + "type": "nginx" + }, + "content": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456" + }, + "_ingest": { + "timestamp": "2024-04-15T07:54:16.010447Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=rename_field +{ + "message": { + "type": "nginx", + "content": "192.168.1.10 - - [03/Nov/2023:15:20:45 +0000] \"POST /login HTTP/1.1\" 200 3456" + } +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/script.md b/i18n/zh/ingest-pipelines/processors/script.md new file mode 100644 index 00000000..97a35065 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/script.md @@ -0,0 +1,199 @@ +--- +title: Script 处理器 +--- + +# Script 摄取处理器 + +`script` 处理器执行内联和存储的脚本,这些脚本可以在摄取过程中修改或转换 OpenSearch 文档中的数据。处理器使用脚本缓存以提高性能,因为脚本可能会按文档重新编译。有关在 OpenSearch 中使用脚本的信息,请参阅[脚本 API](/api-reference/script-apis/)。 + +以下是 `script` 处理器的语法: + +```json +{ + "script": { + "source": "<script_source>", + "lang": "<script_language>", + "params": { + "<param_name>": "<param_value>" + } + } +} +``` + +## 参数 + +下表列出了 `script` 处理器的必需和可选参数。 + +| 参数 | 必需/可选 | 描述 | +|---|---|---| +`source` | 可选 | 要执行的 Painless 脚本。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。必须指定 `id` 或 `source` 之一,但不能同时指定两者。如果指定了 `source`,则使用提供的源代码执行脚本。 +`id` | 可选 | 先前使用[创建存储脚本 API](/api-reference/script-apis/create-stored-script) 创建的存储脚本的 ID。必须指定 `id` 或 `source` 之一,但不能同时指定两者。如果指定了 `id`,则从具有指定 ID 的存储脚本中检索脚本源。 +`lang` | 可选 | 脚本的编程语言。默认值为 `painless`。 +`params` | 可选 | 可以传递给脚本的参数。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure` | 可选 | 指定如果处理器在执行期间失败要运行的处理器列表。这些处理器按指定的顺序执行。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`tag` | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用处理器。 + +### 步骤 1:创建管道 + +以下查询创建名为 `my-script-pipeline` 的管道,该管道使用 `script` 处理器将 `message` 字段转换为大写: + +```json +PUT _ingest/pipeline/my-script-pipeline +{ + "description": "使用 ScriptProcessor 的示例管道", + "processors": [ + { + "script": { + "source": "ctx.message = ctx.message.toUpperCase()", + "lang": "painless", + "description": "将 message 字段转换为大写" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/my-script-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "message": "hello, world!" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "message": "HELLO, WORLD!" + }, + "_ingest": { + "timestamp": "2024-05-30T16:24:23.30265405Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=my-script-pipeline +{ + "message": "hello, world!" +} +``` + +响应确认文档已被索引到 `testindex1` 中,并且已索引所有 `message` 字段转换为大写的文档: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 2 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含摄取的文档,已按步骤 2 中的响应所示进行转换。 + +## 使用参数和修改元数据 + +在脚本中,`ctx` 变量提供对文档字段和元数据字段(如 `_index`)的访问。在 `params` 中传递的参数在脚本中作为 `params.<name>` 可用。当值作为参数传递时,脚本源在值更改时保持不变,因此 OpenSearch 可以重用编译的脚本。有关更多信息,请参阅[如何使用脚本](/scripting/using-scripts/)。 + +以下请求使用作为参数传递的折扣计算总价格,并更改文档的目标索引: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "script": { + "source": "ctx.total_price = ctx.unit_price * ctx.quantity * (1 - params.discount); ctx._index = params.target_index;", + "params": { + "discount": 0.1, + "target_index": "orders-processed" + } + } + } + ] + }, + "docs": [ + { + "_index": "orders-raw", + "_source": { + "unit_price": 20.0, + "quantity": 3 + } + } + ] +} +``` + +响应显示计算的 `total_price` 和更改的 `_index`: + +```json +{ + "docs": [ + { + "doc": { + "_index": "orders-processed", + "_id": "_id", + "_source": { + "quantity": 3, + "unit_price": 20.0, + "total_price": 54.0 + }, + "_ingest": { + "timestamp": "2026-10-14T20:10:38.9908023Z" + } + } + } + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/processors/set.md b/i18n/zh/ingest-pipelines/processors/set.md new file mode 100644 index 00000000..23c4e8c4 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/set.md @@ -0,0 +1,205 @@ +--- +title: Set(设置) +--- + +# Set 处理器 + +`set` 处理器用于添加或更新文档中的字段。它设置一个字段并将其关联到指定的值。如果字段已经存在,则其值会被提供的值替换,除非 `override` 参数设置为 `false`。当 `override` 为 `false` 且指定的字段存在且不为 `null` 时,字段的值保持不变。值为 `null` 的字段始终会被覆盖。 + +以下是 `set` 处理器的语法: + +```json +{ + "description": "...", + "processors": [ + { + "set": { + "field": "new_field", + "value": "some_value" + } + } + ] +} +``` + +## 参数 + +下表列出了 `set` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 要设置或更新的字段名称。支持[模板片段](/ingest-pipelines/create-ingest#template-snippets)。 +`value` | 必需 | 分配给字段的值。支持[模板片段](/ingest-pipelines/create-ingest#template-snippets)。 +`override` | 可选 | 一个布尔标志,用于确定处理器是否应覆盖字段的现有值。默认为 `true`。 +`ignore_empty_value` | 可选 | 一个布尔标志,用于确定处理器是否应忽略 `null` 值或空字符串。默认为 `false`。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure` | 可选 | 指定在处理器执行期间失败时要运行的处理器列表。这些处理器按指定的顺序执行。 +`tag` | 可选 | 处理器的标识符标签。用于调试,以便区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `set-pipeline` 的管道,该管道使用 `set` 处理器向文档添加一个新字段 `new_field`,其值为 `some_value`: + +```json +PUT _ingest/pipeline/set-pipeline +{ + "description": "Adds a new field 'new_field' with the value 'some_value'", + "processors": [ + { + "set": { + "field": "new_field", + "value": "some_value" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/set-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "existing_field": "value" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "existing_field": "value", + "new_field": "some_value" + }, + "_ingest": { + "timestamp": "2024-05-30T21:56:15.066180712Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +POST testindex1/_doc?pipeline=set-pipeline +{ + "existing_field": "value" +} +``` + +该请求将文档索引到 `testindex1` 索引中,并将 `new_field` 字段设置为 `some_value`,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 0, + "_primary_term": 1 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 + +## 从另一个字段复制值 + +要将值从一个字段复制到另一个字段,请使用模板片段在 `value` 中引用源字段。以下请求将 `customer.address.city` 字段的值复制到 `shipping.city` 字段: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "set": { + "field": "shipping.city", + "value": "{{{customer.address.city}}}" + } + } + ] + }, + "docs": [ + { + "_source": { + "customer": { + "address": { + "city": "Portland" + } + } + } + } + ] +} +``` + +响应显示 `shipping.city` 字段包含复制的值: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "shipping": { + "city": "Portland" + }, + "customer": { + "address": { + "city": "Portland" + } + } + }, + "_ingest": { + "timestamp": "2026-10-14T19:44:03.269176256Z" + } + } + } + ] +} +``` + +模板片段始终生成字符串。例如,复制值为 `24.99` 的数值字段会生成字符串 `"24.99"`。要在保留类型的同时复制值,或复制整个对象,请使用 [`copy` 处理器](/ingest-pipelines/processors/copy)。 diff --git a/i18n/zh/ingest-pipelines/processors/sort.md b/i18n/zh/ingest-pipelines/processors/sort.md new file mode 100644 index 00000000..660e0586 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/sort.md @@ -0,0 +1,164 @@ +--- +title: Sort(排序) +--- + +# Sort 摄取处理器 + +`sort` 处理器按升序或降序对项目数组进行排序。数值数组按数值排序,而字符串或混合数组(字符串和数字)按字典顺序排序。如果输入不是数组,处理器会抛出错误。 + +以下是 `sort` 处理器的语法: + +```json +{ + "description": "Sort an array of items", + "processors": [ + { + "sort": { + "field": "my_array_field", + "order": "desc" + } + } + ] +} +``` + +## 参数 + +下表列出了 `sort` 处理器的必需和可选参数。 + +| 参数 | 必需/可选 | 描述 | +|---|---|---| +`field` | 必需 | 要排序的字段。必须是一个数组。 +`order` | 可选 | 要应用的排序顺序。接受 `asc` 表示升序或 `desc` 表示降序。默认为 `asc`。 +`target_field` | 可选 | 存储已排序数组的字段名称。如果未指定,则已排序的数组存储在与原始数组相同的字段中(`field` 变量)。 +`description` | 可选 | 处理器用途或配置的描述。 +`if` | 可选 | 指定有条件地执行处理器。 +`ignore_failure` | 可选 | 指定忽略处理器失败。请参阅[处理管道失败](/ingest-pipelines/pipeline-failures)。 +`on_failure` | 可选 | 指定在处理器执行期间失败时要运行的处理器列表。这些处理器按指定的顺序执行。 +`tag` | 可选 | 处理器的标识符标签。用于调试,以便区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `sort-pipeline` 的管道,该管道使用 `sort` 处理器按降序对 `my_field` 进行排序,并将排序后的值存储在 `sorted_field` 中: + +```json +PUT _ingest/pipeline/sort-pipeline +{ + "description": "Sort an array of items in descending order", + "processors": [ + { + "sort": { + "field": "my_array_field", + "order": "desc", + "target_field": "sorted_array" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/sort-pipeline/_simulate +{ + "docs": [ + { + "_source": { + "my_array_field": [3, 1, 4, 1, 5, 9, 2, 6, 5] + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "sorted_array": [ + 9, + 6, + 5, + 5, + 4, + 3, + 2, + 1, + 1 + ], + "my_array_field": [ + 3, + 1, + 4, + 1, + 5, + 9, + 2, + 6, + 5 + ] + }, + "_ingest": { + "timestamp": "2024-05-30T22:10:13.405692128Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +POST testindex1/_doc?pipeline=sort-pipeline +{ + "my_array_field": [3, 1, 4, 1, 5, 9, 2, 6, 5] +} +``` + +该请求将文档索引到 `testindex1` 索引中,然后将所有文档的 `my_array_field` 按降序排序,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "no-Py48BwFahnwl9KZzf", + "_version": 1, + "result": "created", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 9, + "_primary_term": 2 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/no-Py48BwFahnwl9KZzf +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/split.md b/i18n/zh/ingest-pipelines/processors/split.md new file mode 100644 index 00000000..b271eda5 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/split.md @@ -0,0 +1,203 @@ +--- +title: Split(拆分) +--- + +# Split 摄取处理器 + +`split` 处理器用于根据指定的分隔符将字符串字段拆分为子字符串数组。 + +以下是 `split` 处理器的语法: + +```json +{ + "split": { + "field": "field_to_split", + "separator": "<delimiter>", + "target_field": "split_field" + } +} +``` + +## 参数 + +下表列出了 `split` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`field` | 必需 | 包含要拆分的字符串的字段。 +`separator` | 必需 | 用于拆分字符串的分隔符的正则表达式。要在正则表达式中具有特殊含义的字符上拆分,例如 `.` 或 `+`,请对其进行转义,例如 `\\.`。 +`preserve_trailing` | 可选 | 如果设置为 `true`,则在结果数组中保留空的尾随字段(例如 `''`)。如果设置为 `false`,则从结果数组中删除空的尾随字段。默认为 `false`。 +`target_field` | 可选 | 存储子字符串数组的字段。如果未指定,则就地更新字段。 +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定字段的文档。如果设置为 `true`,则处理器忽略字段中的缺失值并保持 `target_field` 不变。默认为 `false`。 +`description` | 可选 | 处理器的简要描述。 +`if` | 可选 | 运行处理器的条件。 +`ignore_failure` | 可选 | 指定处理器即使遇到错误也继续执行。如果设置为 `true`,则忽略失败。默认为 `false`。 +`on_failure` | 可选 | 如果处理器失败则运行的处理器列表。 +`tag` | 可选 | 处理器的标识符标签。用于调试,以便区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `split_pipeline` 的管道,该管道使用 `split` 处理器在逗号字符上拆分 `log_message` 字段,并将结果数组存储在 `log_parts` 字段中: + +```json +PUT _ingest/pipeline/split_pipeline +{ + "description": "Split log messages by comma", + "processors": [ + { + "split": { + "field": "log_message", + "separator": ",", + "target_field": "log_parts" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/split_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "log_message": "error,warning,info" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "log_message": "error,warning,info", + "log_parts": [ + "error", + "warning", + "info" + ] + }, + "_ingest": { + "timestamp": "2024-04-26T22:29:23.207849376Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=split_pipeline +{ + "log_message": "error,warning,info" +} +``` + +该请求将文档索引到 `testindex1` 索引中,在逗号分隔符上拆分 `log_message` 字段,并在索引之前将结果存储在 `log_parts` 字段中,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 70, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 72, + "_primary_term": 47 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 + +## 保留空的尾随字段 + +默认情况下,`split` 处理器会从结果数组中删除空的尾随元素。以下请求使用和不使用 `preserve_trailing` 拆分相同的值: + +```json +POST _ingest/pipeline/_simulate +{ + "pipeline": { + "processors": [ + { + "split": { + "field": "colors", + "separator": "," + } + }, + { + "split": { + "field": "colors_preserved", + "separator": ",", + "preserve_trailing": true + } + } + ] + }, + "docs": [ + { + "_source": { + "colors": "red,green,,", + "colors_preserved": "red,green,," + } + } + ] +} +``` + +在响应中,`colors` 数组仅包含两个非空元素,而 `colors_preserved` 数组还包含两个空的尾随元素: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "colors": ["red", "green"], + "colors_preserved": ["red", "green", "", ""] + }, + "_ingest": { + "timestamp": "2026-10-14T19:44:03.298240422Z" + } + } + } + ] +} +``` diff --git a/i18n/zh/ingest-pipelines/processors/text-chunking.md b/i18n/zh/ingest-pipelines/processors/text-chunking.md new file mode 100644 index 00000000..0ad7cbc8 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/text-chunking.md @@ -0,0 +1,266 @@ +--- +title: Text chunking(文本分块) +--- + +# Text chunking 处理器 + +`text_chunking` 处理器将长文档拆分为较短的段落。该处理器支持以下文本拆分算法: + +- [`fixed_token_length`](#fixed_token_length-算法):根据指定的标记数长度将文本拆分为段落。 +- [`fixed_char_length`](#fixed_char_length-算法):根据指定的字符数长度将文本拆分为段落。 +- [`delimiter`](#delimiter-算法):在分隔符上将文本拆分为段落。 + +以下是 `text_chunking` 处理器的语法: + +```json +{ + "text_chunking": { + "field_map": { + "<input_field>": "<output_field>" + }, + "algorithm": { + "<name>": "<parameters>" + } + } +} +``` + +## 参数 + +下表列出了 `text_chunking` 处理器的必需和可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:--------------------------|:--------|:---|:--------------------------------------------------------------------------------------------------------------------------------| +| `field_map` | Object | 必需 | 包含指定文本字段到输出字段映射的键值对。 | +| `field_map.<input_field>` | String | 必需 | 用于获取文本以生成分块段落的字段名称。 | +| `field_map.<output_field>`| String | 必需 | 用于存储分块结果的字段名称。 | +| `algorithm` | Object | 必需 | 包含最多一个键值对,用于指定分块算法和参数。 | +| `algorithm.<name>` | String | 可选 | 分块算法的名称。有效值为 [`fixed_token_length`](#fixed_token_length-算法)、[`fixed_char_length`](#fixed_char_length-算法) 和 [`delimiter`](#delimiter-算法)。默认为 `fixed_token_length`。 | +| `algorithm.<parameters>` | Object | 可选 | 分块算法的参数。默认情况下,包含 `fixed_token_length` 算法的默认参数。 | +| `ignore_missing` | Boolean | 可选 | 如果为 `true`,则从输出中排除空字段。如果为 `false`,则输出将包含每个空字段的空列表。默认为 `false`。 | +| `description` | String | 可选 | 处理器的简要描述。 | +| `tag` | String | 可选 | 处理器的标识符标签。在调试时用于区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | +| `if` | 包含布尔表达式的字符串 | 可选 | 运行处理器的条件。 | +| `ignore_failure` | Boolean | 可选 | 指定处理器即使遇到错误也继续执行。如果设置为 `true`,则忽略处理器失败。默认为 `false`。 | +| `on_failure` | List | 可选 | 如果处理器失败则运行的处理器列表。 | + +::: info NOTE +要对嵌套字段执行分块,请将 `input_field` 和 `output_field` 值指定为 JSON 对象。不支持嵌套字段的点路径。例如,使用 `"field_map": { "foo": { "bar": "bar_chunk"} }` 而不是 `"field_map": { "foo.bar": "foo.bar_chunk"}`。 +::: + +### fixed_token_length 算法 + +下表列出了 `fixed_token_length` 算法的可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:-----------------|:--------|:---|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `token_limit` | Integer | 可选 | 块中的最大标记数。有效值为至少 `1` 的整数。默认为 `384`,计算为 `512(标记)* 0.75`,以便块不超过 [OpenSearch 支持的预训练模型](/ml-commons-plugin/pretrained-models#supported-pretrained-models)的 512 标记输入限制。`standard` 分词器将文本拆分为单词,根据 [OpenAI](https://platform.openai.com/docs/introduction),1 个标记约等于 0.75 个英文单词。 | +| `tokenizer` | String | 可选 | [单词分词器](/analyzers/tokenizers/#word-tokenizers)名称。默认为 `standard`。 | +| `overlap_rate` | Float | 可选 | 块之间的重叠程度。有效值为 `0` 到 `0.5` 之间的浮点数(包括边界值)。默认为 `0`。根据 [Amazon Bedrock](https://aws.amazon.com/blogs/aws/knowledge-bases-now-delivers-fully-managed-rag-experience-in-amazon-bedrock/) 的建议,我们推荐 0--0.2 的值以提高准确性。 | +| `max_chunk_limit`| Integer | 可选 | 最大块数。如果处理器生成的块数超过此限制,则将多余的文本添加到最后一个块。默认为 `100`。要禁用此参数,请将其设置为 `-1`。 | + +### fixed_char_length 算法 + +下表列出了 `fixed_char_length` 算法的可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:-----------------|:--------|:---|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `char_limit` | Integer | 可选 | 块中的最大字符数。有效值为至少 `1` 的整数。默认为 `2048`,计算为 `512(标记)* 4(字符)`,因为 512 标记是文本嵌入模型的常见限制。根据 [OpenAI](https://platform.openai.com/docs/concepts#tokens),1 个标记约等于 4 个英文字符。 | +| `overlap_rate` | Float | 可选 | 块之间的重叠程度。有效值为 `0` 到 `0.5` 之间的浮点数(包括边界值)。默认为 `0`。根据 [Amazon Bedrock](https://aws.amazon.com/blogs/aws/knowledge-bases-now-delivers-fully-managed-rag-experience-in-amazon-bedrock/) 的建议,我们推荐 0--0.2 的值以提高准确性。 | +| `max_chunk_limit`| Integer | 可选 | 最大块数。如果处理器生成的块数超过此限制,则将多余的文本添加到最后一个块。默认为 `100`。要禁用此参数,请将其设置为 `-1`。 | + +::: warning IMPORTANT +4 个字符等于 1 个标记的估算不适用于中文、日文或韩文文本,其中 1 个标记通常仅覆盖 1--2 个字符。例如,对于 `bert-base-multilingual-uncased` 分词器,2,048 个中文字符的块包含约 2,000 个标记,对于 XLM-RoBERTa 分词器包含约 1,200 个标记。文本嵌入模型会忽略超出其标记限制的文本而不返回错误,因此此类块的大部分不会在其嵌入中表示。对于中文、日文或韩文文本,请将 `char_limit` 设置为大约模型的标记限制(例如,对于具有 512 标记限制的模型,设置为 `500`)。 +::: + +### delimiter 算法 + +下表列出了 `delimiter` 算法的可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:-----------------|:--------|:---|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `delimiter` | String | 可选 | 用于拆分文本的字符串分隔符。可以将 `delimiter` 设置为任何字符串,例如 `\n`(在新行上将文本拆分为段落)或 `.`(将文本拆分为句子)。默认为 `\n\n`(在两个新行字符上将文本拆分为段落)。 | +| `max_chunk_limit`| Integer | 可选 | 最大块数。如果处理器生成的块数超过此限制,则将多余的文本添加到最后一个块。默认为 `100`。要禁用此参数,请将其设置为 `-1`。 | + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。您可以在创建处理器时指定分块算法。如果不提供算法名称,分块处理器将使用默认的 `fixed_token_length` 算法及其所有默认参数。 + +### 步骤 1:创建管道 + +以下示例请求创建一个摄取管道,将 `passage_text` 字段中的文本转换为分块段落,这些段落将存储在 `passage_chunk` 字段中: + +```json +PUT _ingest/pipeline/text-chunking-ingest-pipeline +{ + "description": "A text chunking ingest pipeline", + "processors": [ + { + "text_chunking": { + "algorithm": { + "fixed_token_length": { + "token_limit": 10, + "overlap_rate": 0.2, + "tokenizer": "standard" + } + }, + "field_map": { + "passage_text": "passage_chunk" + } + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/text-chunking-ingest-pipeline/_simulate +{ + "docs": [ + { + "_index": "testindex", + "_id": "1", + "_source":{ + "passage_text": "This is an example document to be chunked. The document contains a single paragraph, two sentences and 24 tokens by standard tokenizer in OpenSearch." + } + } + ] +} +``` + +响应确认,除了 `passage_text` 字段外,处理器还在 `passage_chunk` 字段中生成了分块结果。处理器将段落拆分为 10 个单词的块。由于 `overlap` 设置为 0.2,块的最后 2 个单词在后续块中重复: + +```json +{ + "docs": [ + { + "doc": { + "_index": "testindex", + "_id": "1", + "_source": { + "passage_text": "This is an example document to be chunked. The document contains a single paragraph, two sentences and 24 tokens by standard tokenizer in OpenSearch.", + "passage_chunk": [ + "This is an example document to be chunked. The document ", + "The document contains a single paragraph, two sentences and 24 ", + "and 24 tokens by standard tokenizer in OpenSearch." + ] + }, + "_ingest": { + "timestamp": "2024-03-20T02:55:25.642366Z" + } + } + } + ] +} +``` + +创建摄取管道后,您需要创建一个索引以进行文档摄取。要了解更多信息,请参阅[文本分块](/search-plugins/text-chunking/)。 + +## 级联文本分块处理器 + +您可以将多个文本分块处理器链接在一起。例如,要将文档拆分为段落,请应用 `delimiter` 算法并将参数指定为 `\n\n`。为了防止段落超过标记限制,请附加另一个使用 `fixed_token_length` 算法的文本分块处理器。您可以按以下方式配置此示例的摄取管道: + +```json +PUT _ingest/pipeline/text-chunking-cascade-ingest-pipeline +{ + "description": "A text chunking pipeline with cascaded algorithms", + "processors": [ + { + "text_chunking": { + "algorithm": { + "delimiter": { + "delimiter": "\n\n" + } + }, + "field_map": { + "passage_text": "passage_chunk1" + } + } + }, + { + "text_chunking": { + "algorithm": { + "fixed_token_length": { + "token_limit": 500, + "overlap_rate": 0.2, + "tokenizer": "standard" + } + }, + "field_map": { + "passage_chunk1": "passage_chunk2" + } + } + } + ] +} +``` + +### 使用级联处理器进行递归文本分块 + +为了获得更高级的控制,您可以链接两个以上的处理器,以创建递归分块效果。此策略涉及将文本解构为逐渐更小、更具语义意义的单元。 + +例如,您可以首先将文档拆分为段落(`\n\n`),然后将每个段落拆分为句子(`. `)。最后,您可以使用 `fixed_char_length` 算法对每个句子进行分块,以确保最终段落不超过特定长度。这种分层方法有助于在最终大小限制内保持尽可能多的语义上下文。 + +以下示例配置了一个三阶段递归分块管道: + +```json +PUT _ingest/pipeline/recursively-text-chunking-cascade-ingest-pipeline +{ + "description": "A pipeline that recursively chunks text by paragraph, then sentence, then character length.", + "processors": [ + { + "text_chunking": { + "algorithm": { + "delimiter": { + "delimiter": "\n\n" + } + }, + "field_map": { + "original_text": "paragraph_chunks" + } + } + }, + { + "text_chunking": { + "algorithm": { + "delimiter": { + "delimiter": ". " + } + }, + "field_map": { + "paragraph_chunks": "sentence_chunks" + } + } + }, + { + "text_chunking": { + "algorithm": { + "fixed_char_length": { + "char_limit": 300, + "overlap_rate": 0.1 + } + }, + "field_map": { + "sentence_chunks": "final_recursive_chunks" + } + } + } + ] +} +``` + +## 下一步 + +- 有关完整示例,请参阅[文本分块](/search-plugins/text-chunking/)。 +- 要了解有关语义搜索的更多信息,请参阅[语义搜索](/search-plugins/semantic-search)。 +- 要了解有关稀疏搜索的更多信息,请参阅[神经稀疏搜索](/search-plugins/neural-sparse-search)。 +- 要了解有关在 OpenSearch 中使用模型的更多信息,请参阅[选择模型](/ml-commons-plugin/integrating-ml-models#choosing-a-model)。 +- 有关使用外部托管模型对长文档进行分块和生成嵌入的教程,请参阅[使用文本分块的语义搜索](/tutorials/vector-search/semantic-search/long-document/)。 diff --git a/i18n/zh/ingest-pipelines/processors/trim.md b/i18n/zh/ingest-pipelines/processors/trim.md new file mode 100644 index 00000000..d0fdf437 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/trim.md @@ -0,0 +1,138 @@ +--- +title: Trim(修剪) +--- + +# Trim 处理器 + +`trim` 处理器用于从指定字段中删除前导和尾随空白字符。值内的空白不会被删除。对于数组字段,处理器会修剪每个字符串元素。 + +以下是 `trim` 处理器的语法: + +```json +{ + "trim": { + "field": "field_to_trim", + "target_field": "trimmed_field" + } +} +``` + +## 参数 + +下表列出了 `trim` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 +:---|:---|:--- +`field` | 必需 | 包含要修剪的文本的字段。 +`target_field` | 可选 | 存储修剪后文本的字段。如果未指定,则就地更新字段。 +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定字段的文档。如果设置为 `true`,则处理器忽略字段中的缺失值并保持 `target_field` 不变。默认为 `false`。 +`description` | 可选 | 处理器的简要描述。 +`if` | 可选 | 运行处理器的条件。 +`ignore_failure` | 可选 | 指定处理器即使遇到错误也继续执行。如果设置为 `true`,则忽略失败。默认为 `false`。 +`on_failure` | 可选 | 如果处理器失败则运行的处理器列表。 +`tag` | 可选 | 处理器的标识符标签。用于调试,以便区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `trim_pipeline` 的管道,该管道使用 `trim` 处理器从 `raw_text` 字段中删除前导和尾随空白,并将修剪后的文本存储在 `trimmed_text` 字段中: + +```json +PUT _ingest/pipeline/trim_pipeline +{ + "description": "Trim leading and trailing white space", + "processors": [ + { + "trim": { + "field": "raw_text", + "target_field": "trimmed_text" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/trim_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "raw_text": " Hello, world! " + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "raw_text": " Hello, world! ", + "trimmed_text": "Hello, world!" + }, + "_ingest": { + "timestamp": "2024-04-26T20:58:17.418006805Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=trim_pipeline +{ + "raw_text": " Hello, world! " +} +``` + +该请求将文档索引到 `testindex1` 索引中。`trim_pipeline` 修剪 `raw_text` 值并将结果存储在 `trimmed_text` 字段中,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 68, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 70, + "_primary_term": 47 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/urldecode.md b/i18n/zh/ingest-pipelines/processors/urldecode.md new file mode 100644 index 00000000..42d9ecff --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/urldecode.md @@ -0,0 +1,138 @@ +--- +title: URL decode(URL 解码) +--- + +# URL decode 处理器 + +`urldecode` 处理器对于解码日志数据或其他文本字段中的 URL 编码字符串非常有用。这可以使数据更具可读性和更易于分析,特别是在处理包含特殊字符或空格的 URL 或查询参数时。对于数组字段,处理器会解码每个字符串元素。百分号编码的字符和加号都会被解码;例如,`wireless+mouse%21` 变成 `wireless mouse!`。 + +以下是 `urldecode` 处理器的语法: + +```json +{ + "urldecode": { + "field": "field_to_decode", + "target_field": "decoded_field" + } +} +``` + +## 参数 + +下表列出了 `urldecode` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 包含要解码的 URL 编码字符串的字段。 | +`target_field` | 可选 | 存储解码字符串的字段。如果未指定,则解码的字符串存储在与原始编码字符串相同的字段中。 | +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定 `field` 的文档。如果设置为 `true`,则处理器忽略 `field` 中的缺失值并保持 `target_field` 不变。默认为 `false`。 | +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 指定处理器即使遇到错误也继续运行。如果设置为 `true`,则忽略失败。默认为 `false`。 | +`on_failure` | 可选 | 如果处理器失败则运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。用于调试,以便区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `urldecode_pipeline` 的管道,该管道使用 `urldecode` 处理器解码 `encoded_url` 字段中的 URL 编码字符串,并将解码的字符串存储在 `decoded_url` 字段中: + +```json +PUT _ingest/pipeline/urldecode_pipeline +{ + "description": "Decode URL-encoded strings", + "processors": [ + { + "urldecode": { + "field": "encoded_url", + "target_field": "decoded_url" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/urldecode_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "encoded_url": "https://example.com/search?q=hello%20world" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "decoded_url": "https://example.com/search?q=hello world", + "encoded_url": "https://example.com/search?q=hello%20world" + }, + "_ingest": { + "timestamp": "2024-04-25T23:16:44.886165001Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=urldecode_pipeline +{ + "encoded_url": "https://example.com/search?q=hello%20world" +} +``` + +前面的请求将文档索引到 `testindex1` 索引中。`urldecode_pipeline` 解码 `encoded_url` 值并将结果存储在 `decoded_url` 字段中,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 67, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 68, + "_primary_term": 47 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 diff --git a/i18n/zh/ingest-pipelines/processors/user-agent.md b/i18n/zh/ingest-pipelines/processors/user-agent.md new file mode 100644 index 00000000..a837c532 --- /dev/null +++ b/i18n/zh/ingest-pipelines/processors/user-agent.md @@ -0,0 +1,168 @@ +--- +title: User agent(用户代理) +--- + +# User agent 处理器 + +`user_agent` 处理器用于从用户代理字符串中提取信息,例如客户端使用的浏览器、设备和操作系统。`user_agent` 处理器对于分析用户行为和根据用户设备、操作系统和浏览器识别趋势特别有用。它还可以帮助排除特定于某些用户代理配置的问题。 + +以下是 `user_agent` 处理器的语法: + +```json +{ + "user_agent": { + "field": "user_agent", + "target_field": "user_agent_info" + } +} +``` + +## 参数 + +下表列出了 `user_agent` 处理器的必需和可选参数。 + +参数 | 必需/可选 | 描述 | +|-----------|-----------|-----------| +`field` | 必需 | 包含用户代理字符串的字段。 +`target_field` | 可选 | 用于存储提取的用户代理信息的字段。如果未指定,则信息存储在 `user_agent` 字段中。 +`ignore_missing` | 可选 | 指定处理器是否应忽略不包含指定 `field` 的文档。如果设置为 `true`,则如果 `field` 不存在或为 `null`,处理器不会修改文档。默认为 `false`。 | +`regex_file` | 可选 | 包含用于解析用户代理字符串的正则表达式模式的文件名称,例如 `custom-regexes.yml`。该文件必须位于 `config/ingest-user-agent` 目录中。如果未指定,则处理器使用 OpenSearch 捆绑的正则表达式。有关更多信息,请参阅[使用自定义正则表达式文件](#使用自定义正则表达式文件)。 +`properties` | 可选 | 要从用户代理字符串中提取并添加到 `target_field` 的属性列表。有效值为 `name`、`version`、`os`、`device` 和 `original`。如果未指定,则提取所有这些属性。 +`description` | 可选 | 处理器的简要描述。 | +`if` | 可选 | 运行处理器的条件。 | +`ignore_failure` | 可选 | 指定处理器即使遇到错误也继续运行。如果设置为 `true`,则忽略失败。默认为 `false`。 | +`on_failure` | 可选 | 如果处理器失败则运行的处理器列表。 | +`tag` | 可选 | 处理器的标识符标签。用于调试,以便区分相同类型的处理器。有关更多信息,请参阅[使用处理器标签进行监控和调试](/ingest-pipelines/create-ingest#using-processor-tags-for-monitoring-and-debugging)。 | + +## 使用处理器 + +按照以下步骤在管道中使用该处理器。 + +### 步骤 1:创建管道 + +以下查询创建一个名为 `user_agent_pipeline` 的管道,该管道使用 `user_agent` 处理器提取用户代理信息: + +```json +PUT _ingest/pipeline/user_agent_pipeline +{ + "description": "User agent pipeline", + "processors": [ + { + "user_agent": { + "field": "user_agent", + "target_field": "user_agent_info" + } + } + ] +} +``` + +### 步骤 2(可选):测试管道 + +::: tip TIP +建议在摄取文档之前测试管道。 +::: + +要测试管道,请运行以下查询: + +```json +POST _ingest/pipeline/user_agent_pipeline/_simulate +{ + "docs": [ + { + "_source": { + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" + } + } + ] +} +``` + +以下示例响应确认管道按预期工作: + +```json +{ + "docs": [ + { + "doc": { + "_index": "_index", + "_id": "_id", + "_source": { + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3", + "user_agent_info": { + "name": "Chrome", + "original": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3", + "os": { + "name": "Windows", + "version": "10", + "full": "Windows 10" + }, + "device": { + "name": "Other" + }, + "version": "58.0.3029.110" + } + }, + "_ingest": { + "timestamp": "2024-04-25T21:41:28.744407425Z" + } + } + } + ] +} +``` + +### 步骤 3:摄取文档 + +以下查询将文档摄取到名为 `testindex1` 的索引中: + +```json +PUT testindex1/_doc/1?pipeline=user_agent_pipeline +{ + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" +} +``` + +前面的请求将 `user_agent` 字符串解析为其组件,并将文档(包括解析的组件)索引到 `testindex1` 索引中,如以下响应所示: + +```json +{ + "_index": "testindex1", + "_id": "1", + "_version": 66, + "result": "updated", + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 65, + "_primary_term": 47 +} +``` + +### 步骤 4(可选):检索文档 + +要检索文档,请运行以下查询: + +```json +GET testindex1/_doc/1 +``` + +响应包含已摄取的文档,如步骤 2 中的响应所示进行转换。 + +## 使用自定义正则表达式文件 + +要使用您自己的正则表达式解析用户代理字符串,请创建一个正则表达式文件并在 `regex_file` 参数中指定其名称。该文件必须满足以下要求: + +- 文件具有 `.yml` 扩展名。 +- 文件位于每个节点的 `config/ingest-user-agent` 目录中。 +- 节点启动时文件存在。OpenSearch 仅在启动时加载正则表达式文件,因此对现有文件的更改和新文件仅在重新启动节点后才会生效。 + +捆绑的正则表达式基于 uap-core 项目的 [`regexes.yaml`](https://github.com/ua-parser/uap-core/blob/master/regexes.yaml) 文件。自定义正则表达式文件通常是此文件的较新版本或修改版本。 + +## 设置 + +`user_agent` 处理器缓存解析结果。节点上的所有 `user_agent` 处理器共享一个缓存。您可以在 `opensearch.yml` 中使用以下静态设置配置缓存: + +- `ingest.user_agent.cache_size`(静态,long):要缓存的最大解析结果数。默认为 `1000`。 diff --git a/i18n/zh/ingest-pipelines/regex-conditionals.md b/i18n/zh/ingest-pipelines/regex-conditionals.md new file mode 100644 index 00000000..d5057802 --- /dev/null +++ b/i18n/zh/ingest-pipelines/regex-conditionals.md @@ -0,0 +1,195 @@ +--- +title: 正则表达式条件 +--- + +# 正则表达式条件 + +摄取管道支持使用正则表达式(regex)和 Painless 脚本语言的条件逻辑。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。这允许基于文本字段的结构和内容进行细粒度控制,以确定哪些文档被处理。可以在 `if` 参数中使用正则表达式来评估字符串模式。这对于匹配 IP 格式、验证电子邮件地址、识别 UUID 或处理具有特定关键字的日志特别有用。 + +正则表达式的评估可能很昂贵。为了限制它们的 CPU 消耗,OpenSearch 根据 `script.painless.regex.enabled` 和 `script.painless.regex.limit-factor` 设置限制 Painless 正则表达式可以读取的字符数。有关更多信息,请参阅[控制正则表达式](/scripting/painless/#controlling-regular-expressions)。 + +## 示例:电子邮件域过滤 + +以下管道使用正则表达式识别来自 `@example.com` 电子邮件域的用户,并相应地标记这些文档: + +```json +PUT _ingest/pipeline/tag_example_com_users +{ + "processors": [ + { + "set": { + "field": "user_domain", + "value": "example.com", + "if": "ctx.email != null && ctx.email =~ /@example\\.com$/" + } + } + ] +} +``` + +使用以下请求模拟管道: + +```json +POST _ingest/pipeline/tag_example_com_users/_simulate +{ + "docs": [ + { "_source": { "email": "alice@example.com" } }, + { "_source": { "email": "bob@another.com" } } + ] +} +``` + +只有第一个文档添加了 `user_domain`: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "email": "alice@example.com", + "user_domain": "example.com" + } + } + }, + { + "doc": { + "_source": { + "email": "bob@another.com" + } + } + } + ] +} +``` + +## 示例:检测 IPv6 地址 + +以下管道使用正则表达式识别和标记 IPv6 格式的地址: + +```json +PUT _ingest/pipeline/ipv6_flagger +{ + "processors": [ + { + "set": { + "field": "ip_type", + "value": "IPv6", + "if": "ctx.ip != null && ctx.ip =~ /^[a-fA-F0-9:]+$/ && ctx.ip.contains(':')" + } + } + ] +} +``` + +使用以下请求模拟管道: + +```json +POST _ingest/pipeline/ipv6_flagger/_simulate +{ + "docs": [ + { "_source": { "ip": "2001:0db8:85a3:0000:0000:8a2e:0370:7334" } }, + { "_source": { "ip": "192.168.0.1" } } + ] +} +``` + +第一个文档包含添加的设置为 `IPv6` 的 `ip_type` 字段: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "ip": "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + "ip_type": "IPv6" + } + } + }, + { + "doc": { + "_source": { + "ip": "192.168.0.1" + } + } + } + ] +} +``` + +## 示例:验证 UUID 字符串 + +以下管道使用正则表达式验证 `session_id` 字段是否包含有效的 UUID: + +```json +PUT _ingest/pipeline/uuid_checker +{ + "processors": [ + { + "set": { + "field": "valid_uuid", + "value": true, + "if": "ctx.session_id != null && ctx.session_id =~ /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/" + } + } + ] +} +``` + +使用以下请求模拟管道: + +```json +POST _ingest/pipeline/uuid_checker/_simulate +{ + "docs": [ + { "_source": { "session_id": "550e8400-e29b-41d4-a716-446655440000" } }, + { "_source": { "session_id": "invalid-uuid-1234" } } + ] +} +``` + +第一个文档被标记为新的 `valid_uuid` 字段: + +```json +{ + "docs": [ + { + "doc": { + "_source": { + "session_id": "550e8400-e29b-41d4-a716-446655440000", + "valid_uuid": true + } + } + }, + { + "doc": { + "_source": { + "session_id": "invalid-uuid-1234" + } + } + } + ] +} +``` + +## 使用字符串方法进行简单匹配 + +字符串方法的评估比正则表达式成本更低。当字符串方法可以执行相同的匹配时,请使用字符串方法。例如,以下条件等效于[电子邮件域示例](#example-email-domain-filtering),但使用 `endsWith` 方法: + +```json +PUT _ingest/pipeline/tag_example_com_users +{ + "processors": [ + { + "set": { + "field": "user_domain", + "value": "example.com", + "if": "ctx.email != null && ctx.email.endsWith('@example.com')" + } + } + ] +} +``` + +其他可以替代常见正则表达式的字符串方法包括 `startsWith` 和 `contains`。 diff --git a/i18n/zh/install-and-configure/additional-plugins/index.md b/i18n/zh/install-and-configure/additional-plugins/index.md new file mode 100644 index 00000000..f80c4f7d --- /dev/null +++ b/i18n/zh/install-and-configure/additional-plugins/index.md @@ -0,0 +1,44 @@ +--- +title: 附加插件 +--- + +# 附加插件 + +除了 OpenSearch 标准发行版提供的插件之外,还有许多其他可用的插件。这些附加插件是由 OpenSearch 开发人员或 OpenSearch 社区成员构建的。大多数插件在 GitHub 的 [OpenSearch/plugins](https://github.com/opensearch-project/OpenSearch/tree/main/plugins) 目录中维护,可以按名称安装,例如运行 `bin/opensearch-plugin install <plugin-name>`。要列出所有可以按名称安装的插件,请运行 `bin/opensearch-plugin install --help`。在单独的存储库中维护的插件(如 `opensearch-jvector`)必须从下载的包中安装。 + +下表列出了常用的附加插件以及每个插件可用的最早 OpenSearch 版本。 + +| 插件名称 | 最早可用版本 | +|:---|:---| +| `analysis-icu` | 1.0.0 | +| `analysis-kuromoji` | 1.0.0 | +| `analysis-nori` | 1.0.0 | +| [`analysis-phonenumber`](/analyzers/supported-analyzers/phone-analyzers) | 2.18.0 | +| `analysis-phonetic` | 1.0.0 | +| `analysis-smartcn` | 1.0.0 | +| [`analysis-stempel`](/analyzers/language-analyzers/polish) | 1.0.0 | +| [`analysis-ukrainian`](/analyzers/language-analyzers/ukrainian) | 1.0.0 | +| `discovery-azure-classic` | 1.0.0 | +| `discovery-ec2` | 1.0.0 | +| `discovery-gce` | 1.0.0 | +| [`ingest-attachment`](/install-and-configure/additional-plugins/ingest-attachment-plugin) | 1.0.0 | +| `ingestion-kafka` | 3.0.0 | +| `ingestion-kinesis` | 3.0.0 | +| `mapper-annotated-text` | 1.0.0 | +| `mapper-murmur3` | 1.0.0 | +| [`mapper-size`](/install-and-configure/additional-plugins/mapper-size-plugin) | 1.0.0 | +| [`opensearch-jvector`](/install-and-configure/additional-plugins/opensearch-jvector) | 3.5.0 | +| `repository-azure` | 1.0.0 | +| `repository-gcs` | 1.0.0 | +| `repository-hdfs` | 1.0.0 | +| `repository-s3` | 1.0.0 | +| `store-smb` | 1.0.0 | +| `transport-grpc` | 3.0.0 | +| `workload-management` | 2.18.0 | + +## 相关文档 + +- [管理 OpenSearch 插件](/install-and-configure/plugins) +- [`ingest-attachment` 插件](/install-and-configure/additional-plugins/ingest-attachment-plugin) +- [`mapper-size` 插件](/install-and-configure/additional-plugins/mapper-size-plugin) +- [`opensearch-jvector` 插件](/install-and-configure/additional-plugins/opensearch-jvector) diff --git a/i18n/zh/install-and-configure/additional-plugins/ingest-attachment-plugin.md b/i18n/zh/install-and-configure/additional-plugins/ingest-attachment-plugin.md new file mode 100644 index 00000000..a3a96d73 --- /dev/null +++ b/i18n/zh/install-and-configure/additional-plugins/ingest-attachment-plugin.md @@ -0,0 +1,223 @@ +--- +title: Ingest-attachment 插件 +--- + +# Ingest-attachment 插件 + +`ingest-attachment` 插件使 OpenSearch 能够使用 Apache 文本提取库 [Tika](https://tika.apache.org/) 从文件中提取内容和其他信息。 +支持的文档格式包括 PPT、PDF、RTF、ODF 等多种格式。请参阅 Tika [支持的文档格式](https://tika.apache.org/3.2.2/formats.html)。 + +输入字段必须是 Base64 编码的二进制数据。 + +## 安装插件 + +使用以下命令安装 `ingest-attachment` 插件: + +```sh +./bin/opensearch-plugin install ingest-attachment +``` + +## Attachment 处理器选项 + +| 名称 | 必需 | 默认值 | 描述 | +| :--- | :--- | :--- | :--- | +| `field` | 是 | 无 | 获取 Base64 编码二进制数据的字段。 | +| `target_field` | 否 | Attachment | 存储附件信息的字段。 | +| `properties` | 否 | 所有属性 | 应该存储的属性数组。可以是 `content`、`language`、`date`、`title`、`author`、`keywords`、`content_type` 或 `content_length`。 | +| `indexed_chars` | 否 | `100_000` | 用于提取的字符数,以防止字段变得过大。使用 `-1` 表示无限制。 | +| `indexed_chars_field` | 否 | `null` | 用于覆盖提取字符数的字段名称,例如 `indexed_chars`。 | +| `ignore_missing` | 否 | `false` | 当为 `true` 时,如果指定的字段不存在,处理器将退出而不修改文档。 | + +## 示例 + +以下步骤展示如何开始使用 `ingest-attachment` 插件。 + +### 步骤 1:创建一个用于存储附件的索引 + +以下命令创建一个用于存储附件的索引: + +```json +PUT /example-attachment-index +{ + "mappings": { + "properties": {} + } +} +``` + +### 步骤 2:创建管道 + +以下命令创建一个包含 attachment 处理器的管道: + +```json +PUT _ingest/pipeline/attachment +{ + "description" : "Extract attachment information", + "processors" : [ + { + "attachment" : { + "field" : "data" + } + } + ] +} +``` + +### 步骤 3:存储附件 + +将附件转换为 Base64 字符串以作为 `data` 传递。 +在此示例中,`base64` 命令转换文件 `lorem.rtf`: + +```sh +base64 lorem.rtf +``` + +或者,您可以使用 Node.js 将文件读取为 `base64`,如以下命令所示: + +```typescript +import * as fs from "node:fs/promises"; +import path from "node:path"; + +const filePath = path.join(import.meta.dirname, "lorem.rtf"); +const base64File = await fs.readFile(filePath, { encoding: "base64" }); + +console.log(base64File); +``` + +`.rtf` 文件包含以下 Base64 文本: + +`Lorem ipsum dolor sit amet`: +`e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=`。 + +```json +PUT example-attachment-index/_doc/lorem_rtf?pipeline=attachment +{ + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=" +} +``` + +### 查询结果 + +处理完附件后,您现在可以使用搜索查询搜索数据,如以下示例所示: + +```json +POST example-attachment-index/_search +{ + "query": { + "match": { + "attachment.content": "ipsum" + } + } +} +``` + +OpenSearch 响应如下: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.1724279, + "hits": [ + { + "_index": "example-attachment-index", + "_id": "lorem_rtf", + "_score": 1.1724279, + "_source": { + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=", + "attachment": { + "content_type": "application/rtf", + "language": "pt", + "content": "Lorem ipsum dolor sit amet", + "content_length": 28 + } + } + } + ] + } +} +``` + +## 提取的信息 + +使用该插件可以提取以下字段: + +- `content` +- `language` +- `date` +- `title` +- `author` +- `keywords` +- `content_type` +- `content_length` + +要仅提取这些字段的子集,请在管道处理器的 `properties` 中定义它们,如以下示例所示: + +```json +PUT _ingest/pipeline/attachment +{ + "description" : "Extract attachment information", + "processors" : [ + { + "attachment" : { + "field" : "data", + "properties": ["content", "title", "author"] + } + } + ] +} +``` + +## 限制提取的内容 + +为了防止提取过多字符并使节点内存过载,默认限制为 `100_000`。 +您可以使用设置 `indexed_chars` 更改此值。例如,您可以使用 `-1` 表示无限制字符,但您需要确保 OpenSearch 节点上有足够的堆空间来提取大型文档的内容。 + +您还可以使用 `indexed_chars_field` 请求字段为每个文档定义此限制。 +如果文档包含 `indexed_chars_field`,它将覆盖 `indexed_chars` 设置,如以下示例所示: + +```json +PUT _ingest/pipeline/attachment +{ + "description" : "Extract attachment information", + "processors" : [ + { + "attachment" : { + "field" : "data", + "indexed_chars" : 10, + "indexed_chars_field" : "max_chars", + } + } + ] +} +``` + +配置好附件管道后,您可以在请求中不指定 `max_chars` 的情况下提取默认的 `10` 个字符,如以下示例所示: + +```json +PUT example-attachment-index/_doc/lorem_rtf?pipeline=attachment +{ + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=" +} +``` + +或者,您可以更改每个文档的 `max_char` 以提取最多 `15` 个字符,如以下示例所示: + +```json +PUT example-attachment-index/_doc/lorem_rtf?pipeline=attachment +{ + "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=", + "max_chars": 15 +} +``` diff --git a/i18n/zh/install-and-configure/additional-plugins/mapper-size-plugin.md b/i18n/zh/install-and-configure/additional-plugins/mapper-size-plugin.md new file mode 100644 index 00000000..d8467937 --- /dev/null +++ b/i18n/zh/install-and-configure/additional-plugins/mapper-size-plugin.md @@ -0,0 +1,95 @@ +--- +title: Mapper-size 插件 +--- + +# Mapper-size 插件 + +`mapper-size` 插件使 OpenSearch 索引能够使用 `_size` 字段。`_size` 字段存储每个文档的大小(以字节为单位)。 + +## 安装插件 + +您可以使用以下命令安装 `mapper-size` 插件: + +```sh +./bin/opensearch-plugin install mapper-size +``` + +## 示例 + +启动集群后,您可以创建启用了大小映射的索引,索引文档并搜索文档,如以下示例所示。 + +### 创建启用了大小映射的索引 + +```sh +curl -XPUT example-index -H "Content-Type: application/json" -d '{ + "mappings": { + "_size": { + "enabled": true + }, + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } +}' +``` + +### 索引文档 + +```sh +curl -XPOST example-index/_doc -H "Content-Type: application/json" -d '{ + "name": "John Doe", + "age": 30 +}' +``` + +### 查询索引 + +```sh +curl -XGET example-index/_search -H "Content-Type: application/json" -d '{ + "query": { + "match_all": {} + }, + "stored_fields": ["_size", "_source"] +}' +``` + +### 查询结果 + +在以下示例中,`_size` 字段包含在查询结果中,并显示索引文档的大小(以字节为单位): + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "example_index", + "_id": "Pctw0I8BLto8I5f_NLKK", + "_score": 1.0, + "_size": 37, + "_source": { + "name": "John Doe", + "age": 30 + } + } + ] + } +} +``` diff --git a/i18n/zh/install-and-configure/additional-plugins/opensearch-jvector.md b/i18n/zh/install-and-configure/additional-plugins/opensearch-jvector.md new file mode 100644 index 00000000..6b639d41 --- /dev/null +++ b/i18n/zh/install-and-configure/additional-plugins/opensearch-jvector.md @@ -0,0 +1,109 @@ +--- +title: OpenSearch JVector 插件 +--- + +# OpenSearch JVector 插件 +<Badge type="tip" text="3.5 版本引入" /> + +`opensearch-jvector` 插件为[向量搜索](/vector-search/)提供 `jvector` 引擎。该引擎使用 [JVector](https://github.com/datastax/jvector) 库在纯 Java 中实现 DiskANN 风格的近似最近邻搜索,因此不需要本机库和 Java 本机接口(JNI)层。它支持最多 16,000 维的向量和包含数十亿文档的索引,您可以使用聚合和过滤子句优化搜索,就像使用内置引擎一样。 + +由于 `jvector` 引擎从磁盘读取的量化向量构建索引,因此随着数据集增长超过可用内存,内存使用量保持有界。该引擎还接受并发插入并增量合并段,因此避免了连续索引使用内置引擎导致的图重建。这些特性使其适用于推荐系统、图像和视频相似性搜索、语义文档搜索以及索引数百万到数十亿向量的欺诈检测管道。 + +该插件取代了 k-NN 插件,因此它还提供了 `lucene` 引擎,其工作方式与 k-NN 插件中的相同。`faiss` 和 `nmslib` 引擎不可用。 + +::: info NOTE +`opensearch-jvector` 插件不包含在任何 OpenSearch 发行版中,并且不能与 k-NN 插件一起运行。安装它需要删除 `opensearch-knn`。 +::: + +## 功能 + +`jvector` 引擎提供以下功能: + +- 由于该引擎是用纯 Java 编写的,不需要本机库或 JNI 层,因此部署和维护比内置引擎更简单。 +- 索引完全是线程安全的,接受并发插入和更新,随着 CPU 核心数量的增加几乎线性扩展。摄取吞吐量不依赖于合并操作来实现并行性。 +- 向量可以增量添加到现有索引中,避免了频繁更新所需的完整索引重建,特别是对于大型基于图的索引。 +- 量化码本在合并期间增量优化。这提高了搜索准确性和召回率,而无需重新计算码本,并减少了计算开销。 +- DiskANN 风格的量化与重新排序相结合,这使得对于大于可用内存的数据集保持高召回率,对于这些数据集,内存索引是不可行的。 +- 乘积量化(PQ)使用单指令多数据(SIMD)优化和单独的码本,提供快速搜索和低内存使用。 +- 高级量化技术,如非均匀向量量化(NVQ)和各向异性 PQ,比标准量化更准确地计算相似性,并使用更少的资源。 + +## 与 k-NN 插件的比较 + +下表比较了内置 k-NN 插件和 `opensearch-jvector` 插件。最后三行描述了 `jvector` 引擎;`lucene` 引擎与 k-NN 插件中的相同。 + +| 方面 | k-NN 插件 | JVector 插件 | +| :--- | :--- | :--- | +| 引擎 | `faiss`、`lucene` 和 `nmslib`(已弃用) | `jvector` 和 `lucene` | +| 方法 | `hnsw` 和 `ivf` | `jvector` 的 `disk_ann` 和 `lucene` 的 `hnsw` | +| 默认引擎 | `faiss` | `jvector` | +| 包含在发行版中 | 是 | 否 | +| 并发摄取 | 因引擎而异 | `jvector` 引擎接受并发插入 | +| 索引更新成本 | 段合并时重建图 | 合并是增量的,没有完整的图重建 | +| 内存使用 | 向量保存在内存中,除非您配置磁盘模式 | 向量被量化并从磁盘读取 | + +有关 `jvector` 引擎支持的方法、参数和空间类型,请参阅 [JVector 引擎](/mappings/supported-field-types/knn-methods-engines/#jvector-engine)。 + +## 安装 + +::: danger WARNING +删除 k-NN 插件会使使用 `faiss` 或 `nmslib` 引擎的索引不可读。在开始之前,确认集群中没有索引使用这两个引擎,或者在 k-NN 插件仍然安装时使用 `lucene` 引擎重新索引该数据。使用 `lucene` 引擎的索引在安装 `opensearch-jvector` 插件后仍然可搜索。 +::: + +在集群中的每个节点上重复以下步骤: + +1. 在节点上停止 OpenSearch。 +1. 删除神经搜索和 k-NN 插件。首先删除 `opensearch-neural-search`,因为它依赖于 `opensearch-knn`: + + ```bash + bin/opensearch-plugin remove opensearch-neural-search + bin/opensearch-plugin remove opensearch-knn + ``` + +1. 使用插件的 Maven 坐标从 Maven Central 安装 `opensearch-jvector` 插件: + + ```bash + bin/opensearch-plugin install org.opensearch.plugin:opensearch-jvector-plugin:2.12.0.0 + ``` + + 通过 Maven 坐标安装需要直接连接到 Maven Central。如果节点通过代理或本地存储库连接,请改为从其 URL 安装插件: + + ```bash + bin/opensearch-plugin install https://repo1.maven.org/maven2/org/opensearch/plugin/opensearch-jvector-plugin/2.12.0.0/opensearch-jvector-plugin-2.12.0.0.zip + ``` + +1. 在节点上启动 OpenSearch。 + +有关可用插件版本的完整列表,请参阅 Maven Central 中的 [`opensearch-jvector-plugin` 目录](https://repo1.maven.org/maven2/org/opensearch/plugin/opensearch-jvector-plugin/)。要跳过请求确认插件附加权限的提示,请将 `--batch` 选项添加到 `install` 命令。有关更多信息,请参阅[管理 OpenSearch 插件](/install-and-configure/plugins#installing-a-plugin-using-maven-coordinates)。 + +要确认插件已安装,请使用 [CAT Plugins API](/api-reference/cat/cat-plugins): + +```json +GET _cat/plugins?v +``` + +响应包含每个节点上的 `opensearch-jvector` 行。 + +## 支持的 OpenSearch 功能 + +该插件支持以下 OpenSearch 向量搜索功能。 + +| 功能 | 在插件版本中可用 | +| :--- | :--- | +| [乘积量化(PQ)](/vector-search/optimizing-storage/knn-vector-quantization/) | 3.5.0 | +| [最大边际相关性(MMR)重新排序](/vector-search/specialized-operations/vector-search-mmr/) | 3.6.0 | +| [派生源](/mappings/metadata-fields/source/#derived-source) | 3.6.0 | + +## 限制 + +该插件具有以下限制: + +- 该插件不是任何 OpenSearch 发行版的一部分,因此您必须在每个节点上手动安装它。 +- 该插件和 `opensearch-knn` 不能安装在同一个集群中。 +- 上游 `opensearch-neural-search` 插件无法识别 `jvector` 引擎,因此神经和混合查询不可用。 + +## 相关文档 + +- [JVector 引擎](/mappings/supported-field-types/knn-methods-engines/#jvector-engine) +- [管理 OpenSearch 插件](/install-and-configure/plugins) +- [向量搜索](/vector-search/) +- [使用 JVector 高效过滤器](/vector-search/filter-search-knn/efficient-knn-filtering/#using-a-jvector-efficient-filter) diff --git a/i18n/zh/install-and-configure/configuring-opensearch/admission-control-settings.md b/i18n/zh/install-and-configure/configuring-opensearch/admission-control-settings.md new file mode 100644 index 00000000..b973a3d3 --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/admission-control-settings.md @@ -0,0 +1,46 @@ +--- +title: 准入控制设置 +--- + +# 准入控制设置 + +OpenSearch 提供准入控制设置,通过限制不同类型操作的资源使用来帮助防止集群过载。准入控制监控 CPU 和 I/O 使用情况,并可以在资源利用率超过配置的阈值时拒绝请求。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 传输层设置 + +OpenSearch 支持以下传输层准入控制设置: + +- `admission_control.transport.mode`(动态,字符串):控制传输层的整体准入控制模式。有效值为: + - `disabled`(默认):禁用准入控制。 + - `shadow`:准入控制仅在监控模式下运行,收集指标但不拒绝请求。 + - `enforced`:准入控制在超过阈值时主动拒绝请求。 + +## 基于 CPU 的准入控制设置 + +基于 CPU 的准入控制监控 CPU 使用情况,并对不同类型的操作应用限制。所有 CPU 限制都指定为百分比(0--100)。 + +OpenSearch 支持以下动态的基于 CPU 的准入控制设置: + +- `admission_control.cluster.admin.cpu_usage.limit`(动态,长整型):集群管理操作的 CPU 使用阈值。当 CPU 使用率超过此限制时,可能会拒绝集群管理请求以保持集群稳定性。默认值为 `95`。 + +- `admission_control.search.cpu_usage.limit`(动态,长整型):搜索操作的 CPU 使用阈值。当 CPU 使用率超过此限制时,可能会拒绝新的搜索请求以防止集群过载。默认值为 `95`。 + +- `admission_control.indexing.cpu_usage.limit`(动态,长整型):索引操作的 CPU 使用阈值。当 CPU 使用率超过此限制时,可能会拒绝索引请求以保持集群性能。默认值为 `95`。 + +- `admission_control.transport.cpu_usage.mode_override`(动态,字符串):专门针对基于 CPU 的准入控制覆盖全局传输模式。接受与 `admission_control.transport.mode` 相同的值:`disabled`、`shadow` 或 `enforced`。如果未指定,则使用全局传输模式设置。 + +## 基于 I/O 的准入控制设置 + +基于 I/O 的准入控制监控磁盘 I/O 使用情况,并对不同类型的操作应用限制。所有 I/O 限制都指定为百分比(0--100)。 + +OpenSearch 支持以下基于 I/O 的准入控制设置: + +- `admission_control.search.io_usage.limit`(动态,长整型):搜索操作的 I/O 使用阈值。当 I/O 使用率超过此限制时,可能会拒绝搜索请求。默认值为 `95`。 + +- `admission_control.indexing.io_usage.limit`(动态,长整型):索引操作的 I/O 使用阈值。当 I/O 使用率超过此限制时,可能会拒绝索引请求。默认值为 `95`。 + +- `admission_control.cluster_admin.io_usage.limit`(静态,长整型):集群管理操作的 I/O 使用阈值。这是一个静态设置,需要集群重启才能修改。默认值为 `100`。 + +- `admission_control.transport.io_usage.mode_override`(动态,字符串):专门针对基于 I/O 的准入控制覆盖全局传输模式。接受与 `admission_control.transport.mode` 相同的值:`disabled`、`shadow` 或 `enforced`。如果未指定,则使用全局传输模式设置。 diff --git a/i18n/zh/install-and-configure/configuring-opensearch/cache-settings.md b/i18n/zh/install-and-configure/configuring-opensearch/cache-settings.md new file mode 100644 index 00000000..0198c851 --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/cache-settings.md @@ -0,0 +1,23 @@ +--- +title: 缓存设置 +--- + +# 缓存设置 + +OpenSearch 提供各种缓存设置以优化内存使用和性能。这些设置控制 OpenSearch 如何管理缓存的数据结构和缓存操作的内存分配。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 缓存回收器设置 + +缓存回收器管理内存页的重用以减少垃圾收集开销。OpenSearch 支持以下缓存回收器设置: + +- `cache.recycler.page.limit.heap`(静态,字节大小):页缓存回收器堆使用的内存大小限制。默认值为堆的 `10%`。 + +- `cache.recycler.page.weight.bytes`(静态,双精度):缓存回收器中字节页回收的权重因子。默认值为 `1.0`。最小值为 `0.0`。 + +- `cache.recycler.page.weight.ints`(静态,双精度):缓存回收器中整数页回收的权重因子。默认值为 `1.0`。最小值为 `0.0`。 + +- `cache.recycler.page.weight.longs`(静态,双精度):缓存回收器中长整型页回收的权重因子。默认值为 `1.0`。最小值为 `0.0`。 + +- `cache.recycler.page.weight.objects`(静态,双精度):缓存回收器中对象页回收的权重因子。对象页不太有用,因此默认给予较低的权重。默认值为 `0.1`。最小值为 `0.0`。 diff --git a/i18n/zh/install-and-configure/configuring-opensearch/cluster-settings-for-indexes.md b/i18n/zh/install-and-configure/configuring-opensearch/cluster-settings-for-indexes.md new file mode 100644 index 00000000..ae6c2d8a --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/cluster-settings-for-indexes.md @@ -0,0 +1,98 @@ +--- +title: 索引的集群设置 +--- + +# 索引的集群设置 + +以下集群设置适用于集群中的所有索引。有关适用于单个索引的设置,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 静态设置 + +OpenSearch 支持以下静态集群索引设置: + +- `indices.cache.cleanup_interval`(静态,时间单位):安排一个定期后台任务,以指定的间隔清理缓存中的过期条目。默认值为 `1m`(1 分钟)。有关更多信息,请参阅[索引请求缓存](/search-plugins/caching/request-cache)。 + +- `indices.requests.cache.size`(静态,字符串):缓存大小占堆大小的百分比(例如,要使用堆的 1%,指定 `1%`)。默认值为 `1%`。有关更多信息,请参阅[索引请求缓存](/search-plugins/caching/request-cache)。 + +- `indices.analysis.hunspell.dictionary.ignore_case`(静态,布尔值):控制 Hunspell 字典匹配是否对所有区域设置全局忽略大小写。启用后,字典匹配变为不区分大小写。此设置可以在多个级别配置:节点级别(此设置)、使用 `indices.analysis.hunspell.dictionary.<locale>.ignore_case`(例如 `indices.analysis.hunspell.dictionary.en_US.ignore_case`)的每个区域设置,或在每个字典目录中的字典特定 `settings.yml` 文件中。每个区域设置和字典特定的设置会覆盖全局设置。默认值为 `false`。 + +- `indices.analysis.hunspell.dictionary.lazy`(静态,布尔值):控制何时加载 Hunspell 字典。如果为 `true`,则字典加载将延迟到实际使用字典时,从而减少启动时间,但可能会增加首次使用时的延迟。如果为 `false`,则在节点启动时检查字典目录并自动加载所有字典。默认值为 `false`。 + +- `indices.analysis.hunspell.dictionary.<locale>.strict_affix_parsing`(静态,布尔值):控制在读取 Hunspell 词缀规则文件时遇到的错误是引发异常还是静默忽略。设置为 `true` 时,词缀文件中的解析错误将引发异常并阻止字典加载。设置为 `false` 时,解析错误被忽略,字典继续加载。可以通过将 `<locale>` 替换为特定的区域设置代码(例如 `indices.analysis.hunspell.dictionary.en_US.strict_affix_parsing`)来为每个区域设置配置此设置。默认值为 `true`。 + +- `indices.memory.index_buffer_size`(静态,字符串):控制为节点上所有分片的索引操作分配的堆内存量。接受百分比(如 `10%`)或字节大小值(如 `512mb`)。此缓冲区在所有分片之间共享,用于在写入磁盘之前批处理索引操作。默认值为总堆的 `10%`。 + +- `indices.memory.min_index_buffer_size`(静态,字节单位):当 `indices.memory.index_buffer_size` 指定为百分比时,设置索引缓冲区的绝对最小大小。这确保了在内存有限的节点上索引缓冲区永远不会变得太小。默认值为 `48mb`。 + +- `indices.memory.max_index_buffer_size`(静态,字节单位):当 `indices.memory.index_buffer_size` 指定为百分比时,设置索引缓冲区的绝对最大大小。这可以防止索引缓冲区在具有大堆的节点上消耗过多内存。默认值为无界(无限制)。 + +- `indices.queries.cache.size`(静态,字符串):控制每个数据节点上为查询缓存(过滤器缓存)分配的内存大小。查询缓存存储常用过滤器的结果以提高搜索性能。接受百分比值(如 `5%`)或精确字节值(如 `512mb`)。默认值为堆内存的 `10%`。 + +- `indices.queries.cache.all_segments`(静态,布尔值):是否跨所有段缓存查询还是仅缓存经常访问的段。 + +- `indices.queries.cache.count`(静态,整数):要缓存的最大查询数。 + +- `index.store.hybrid.nio.extensions`(静态,列表):**专家设置。** 要使用 NIO 而不是内存映射加载的 Lucene 文件扩展名。默认包括常见的扩展名,如 `segments_N`、`write.lock`、`si` 和 `cfe`。 + +- `indexing_pressure.memory.limit`(静态,字节大小):控制索引操作的内存限制,以防止在繁重的索引工作负载期间出现内存耗尽。当索引操作超过此阈值时,可能会拒绝或限制它们以保护集群稳定性。接受百分比值(如堆的 `10%`)或字节大小值(如 `512mb`)。默认值为总堆内存的 `10%`。 + +- `indices.query.query_string.allowLeadingWildcard`(静态,布尔值):控制查询字符串查询中是否允许前导通配符。启用后,允许像 `*term` 或 `?term` 这样的查询,但可能会影响性能,因为它们需要扫描索引中的所有术语。禁用后,前导通配符查询将被拒绝以提高查询性能。默认值为 `true`。 + +- `indices.query.query_string.analyze_wildcard`(静态,布尔值):控制查询字符串查询中的通配符术语是否使用配置的分析器进行分析。启用后,通配符查询经过分析(标记化、过滤),可以改善匹配,但可能会影响性能。禁用后,通配符术语按原样使用,不进行分析。默认值为 `false`。 + +- `indices.time_series_index.default_index_merge_policy`(静态,字符串):设置集群中时间序列索引的默认合并策略。此设置控制 Lucene 段如何合并时间序列数据,这可能会显著影响索引性能和存储效率。有效值包括 `default`、`tiered` 和 `log_byte_size`。默认值为 `default`。 + +- `cluster.remote_store.translog.path.prefix`(静态,字符串):控制启用远程存储的集群上事务日志数据的固定路径前缀。此设置仅在 `cluster.remote_store.index.path.type` 设置为 `HASHED_PREFIX` 或 `HASHED_INFIX` 时适用。默认值为空字符串 `""`。 + +- `cluster.remote_store.segments.path.prefix`(静态,字符串):控制启用远程存储的集群上段数据的固定路径前缀。此设置仅在 `cluster.remote_store.index.path.type` 设置为 `HASHED_PREFIX` 或 `HASHED_INFIX` 时适用。默认值为空字符串 `""`。 + +- `cluster.snapshot.shard.path.prefix`(静态,字符串):控制快照分片级 blob 的固定路径前缀。此设置仅在存储库 `shard_path_type` 设置为 `HASHED_PREFIX` 或 `HASHED_INFIX` 时适用。默认值为空字符串 `""`。 + +## 动态设置 + +OpenSearch 支持以下动态集群索引设置: + +- `action.auto_create_index`(动态,布尔值):如果索引不存在,则自动创建索引。还应用配置的任何索引模板。默认值为 `true`。 + +- `action.destructive_requires_name`(动态,布尔值):当为 `true` 时,必须指定索引名称才能删除索引。您不能删除所有索引或使用通配符。默认值为 `false`。 + +- `cluster.default.index.refresh_interval`(动态,时间单位):在未提供 `index.refresh_interval` 设置时设置刷新间隔。当您想要在集群中的所有索引上设置默认刷新间隔并支持 `searchIdle` 设置时,此设置很有用。您不能将间隔设置得低于 `cluster.minimum.index.refresh_interval` 设置。 + +- `cluster.minimum.index.refresh_interval`(动态,时间单位):设置最小刷新间隔并将其应用于集群中的所有索引。`cluster.default.index.refresh_interval` 设置应该高于此设置的值。如果在索引创建期间 `index.refresh_interval` 设置低于设置的最小值,则索引创建失败。 + +- `cluster.indices.close.enable`(动态,布尔值):在 OpenSearch 中启用关闭打开的索引。默认值为 `true`。 + +- `indices.recovery.max_bytes_per_sec`(动态,字符串):限制每个节点的总入站和出站恢复流量。这适用于对等恢复和快照恢复。默认值为 `40mb`。如果将恢复流量值设置为小于或等于 `0mb`,则禁用速率限制,这会导致恢复数据以尽可能高的速率传输。 + +- `indices.recovery.max_concurrent_file_chunks`(动态,整数):每个恢复操作并行发送的文件块数。默认值为 `2`。 + +- `indices.recovery.max_concurrent_operations`(动态,整数):每个恢复操作并行发送的操作数。默认值为 `1`。 + +- `indices.recovery.max_concurrent_remote_store_streams`(动态,整数):恢复远程存储索引时可以并行打开到远程存储库的流数。默认值为 `20`。 + +- `indices.replication.max_bytes_per_sec`(动态,字符串):限制每个节点的总入站和出站复制流量。如果未在配置的值中指定值,则使用 `indices.recovery.max_bytes_per_sec` 设置,默认为 40 Mb。如果将复制流量值设置为小于或等于 0 Mb,则禁用速率限制,这会导致复制数据以尽可能高的速率传输。 + +- `indices.fielddata.cache.size`(动态,字符串):字段数据缓存的最大大小。可以指定为绝对值(例如 `8GB`)或节点堆的百分比(例如 `50%`)。此设置是动态的。如果不指定此设置,最大大小为 `35%`。此值应小于 `indices.breaker.fielddata.limit`。有关更多信息,请参阅[字段数据断路器](/install-and-configure/configuring-opensearch/circuit-breaker#field-data-circuit-breaker-settings)。 + +- `indices.query.bool.max_clause_count`(动态,整数):定义可以同时搜索的字段和术语的最大乘积。在 OpenSearch 2.16 之前,需要重新启动集群才能应用此静态设置。现在是动态的,现有搜索线程池可能最初使用旧的静态值,导致 `TooManyClauses` 异常。新线程池使用更新的值。默认值为 `1024`。 + +- `cluster.remote_store.index.path.type`(动态,字符串):存储在远程存储中的数据的路径策略。此设置仅对启用远程存储的集群有效。此设置支持以下值: + - `fixed`:将数据存储在路径结构 `<repository_base_path>/<index_uuid>/<shard_id>/` 中。 + - `hashed_prefix`:将数据存储在路径结构 `hash(<shard-data-idenitifer>)/<repository_base_path>/<index_uuid>/<shard_id>/` 中。 + - `hashed_infix`:将数据存储在路径结构 `<repository_base_path>/hash(<shard-data-idenitifer>)/<index_uuid>/<shard_id>/` 中。 + `shard-data-idenitifer` 由 index_uuid、shard_id、数据类型(事务日志、段)和数据类型(数据、元数据、lock_files)来表征。 + 默认值为 `fixed`。 + +- `cluster.remote_store.index.path.hash_algorithm`(动态,字符串):当 `cluster.remote_store.index.path.type` 设置为 `hashed_prefix` 或 `hashed_infix` 时用于派生哈希值的哈希函数。此设置仅对启用远程存储的集群有效。此设置支持以下值: + - `fnv_1a_base64`:使用 FNV1a 哈希函数并生成 url 安全的 20 位 Base64 编码哈希值。 + - `fnv_1a_composite_1`:使用 FNV1a 哈希函数并生成一个自定义编码的哈希值,该值可以很好地适应大多数远程存储选项。FNV1a 函数生成 64 位值。自定义编码使用最高 6 位创建 URL 安全的 Base64 字符,接下来的 14 位创建二进制字符串。默认值为 `fnv_1a_composite_1`。 + +- `cluster.remote_store.translog.transfer_timeout`(动态,时间单位):控制在同步到远程存储期间上传事务日志和检查点文件时的超时值。此设置仅适用于启用远程存储的集群。默认值为 `30s`。 + +- `cluster.remote_store.index.segment_metadata.retention.max_count`(动态,整数):控制要在远程存储的段存储库中保留的元数据文件的最小数量。低于 `1` 的值会禁用过时段元数据文件的删除。默认值为 `10`。 + +- `cluster.remote_store.segment.transfer_timeout`(动态,时间单位):控制在刷新到远程存储后等待所有新段更新的最长时间。如果上传未在指定的时间内完成,则抛出 `SegmentUploadFailedException` 错误。默认值为 `30m`。最小约束为 `10m`。 + +- `cluster.default_number_of_replicas`(动态,整数):控制集群中索引的默认副本数。如果未配置,索引级别的 `index.number_of_replicas` 设置将默认为此值。默认值为 `1`。 diff --git a/i18n/zh/install-and-configure/configuring-opensearch/ingest-settings.md b/i18n/zh/install-and-configure/configuring-opensearch/ingest-settings.md new file mode 100644 index 00000000..e828a124 --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/ingest-settings.md @@ -0,0 +1,37 @@ +--- +title: 摄取设置 +--- + +# 摄取设置 + +OpenSearch 提供摄取设置,用于控制数据处理管道允许使用哪些摄取处理器。这些设置通过限制可在摄取管道中使用的处理器来帮助维护数据转换操作的安全性和控制。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## User agent 处理器设置 + +User agent 处理器设置控制摄取管道中允许使用哪些用户代理解析处理器。 + +OpenSearch 支持以下静态 User agent 处理器设置: + +- `ingest.useragent.processors.allowed`(静态,列表):指定允许在摄取管道中使用哪些 User agent 处理器。当此列表为空(默认)时,不应用任何限制,所有可用的 User agent 处理器都可以使用。当配置为特定处理器名称时,管道中仅允许这些处理器。此设置有助于控制出于安全和数据治理目的可以使用哪些用户代理解析处理器。默认值为 `[]`(空列表 - 无限制)。 + +## 通用处理器设置 + +通用处理器设置控制摄取管道中允许使用哪些标准摄取处理器。 + +OpenSearch 支持以下静态通用处理器设置: + +- `ingest.common.processors.allowed`(静态,列表):指定允许在摄取管道中使用哪些通用摄取处理器。当此列表为空(默认)时,不应用任何限制,所有可用的通用处理器(如 `set`、`remove`、`rename` 和 `convert`)都可以使用。当配置为特定处理器名称时,管道中仅允许这些处理器。此设置为安全和合规要求提供对数据转换功能的细粒度控制。默认值为 `[]`(空列表 - 无限制)。 + +## 缓存和性能设置 + +缓存和性能设置控制各种摄取处理器的缓存大小和执行限制。 + +OpenSearch 支持以下静态缓存和性能设置: + +- `ingest.user_agent.cache_size`(静态,长整型):设置 User agent 字符串解析结果的缓存大小。此缓存存储已解析的用户代理信息,以提高处理具有重复用户代理字符串的文档时的性能。较高的值可减少常见用户代理的解析开销,但会使用更多内存。缓存存储用户代理字符串与其已解析组件(浏览器、操作系统和设备信息)之间的映射。默认值为 `1000`。最小值为 `0`。 + +- `ingest.grok.watchdog.interval`(静态,时间单位):设置 Grok 处理器监视器检查长时间运行的模式匹配操作的间隔。监视器有助于防止 Grok 处理器使用复杂或低效的模式消耗过多的 CPU 时间。更频繁的检查提供更好的保护以防止失控的操作,但会增加轻微的开销。默认值为 `1s`。 + +- `ingest.grok.watchdog.max_execution_time`(静态,时间单位):设置在监视器中断 Grok 模式匹配操作之前允许的最大执行时间。这可以防止设计不良或恶意的 Grok 模式导致过度的 CPU 使用或阻塞摄取处理。超过此限制的操作将被终止以维护集群稳定性。默认值为 `1s`。 diff --git a/i18n/zh/install-and-configure/configuring-opensearch/monitoring-settings.md b/i18n/zh/install-and-configure/configuring-opensearch/monitoring-settings.md new file mode 100644 index 00000000..1446ce1a --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/monitoring-settings.md @@ -0,0 +1,47 @@ +--- +title: 监控设置 +--- + +# 监控设置 + +OpenSearch 提供设置来监控集群健康和性能的各个方面,包括文件系统操作、JVM 垃圾收集、操作系统指标和进程统计信息。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 文件系统健康监控设置 + +OpenSearch 支持以下文件系统健康监控设置: + +- `monitor.fs.health.enabled`(动态,布尔值):启用文件系统健康监控以检测缓慢或无响应的文件系统操作。默认值为 `true`。 + +- `monitor.fs.health.healthy_timeout_threshold`(动态,时间单位):将文件系统操作视为健康的阈值。耗时更长的操作将被标记为慢速。默认值为 `60s`。强制的最小值为 `1ms`。 + +- `monitor.fs.health.slow_path_logging_threshold`(动态,时间单位):记录慢速文件系统路径操作的阈值。默认值为 `5s`。强制的最小值为 `1ms`。 + +- `monitor.fs.health.refresh_interval`(静态,时间单位):文件系统健康监控的刷新间隔。默认值为 `60s`。最小值为 `1ms`。 + +- `monitor.fs.refresh_interval`(静态,时间单位):文件系统统计监控的刷新间隔。默认值为 `1s`。最小值为 `1s`。 + +## JVM 监控设置 + +OpenSearch 支持以下 JVM 监控设置: + +- `monitor.jvm.gc.enabled`(静态,布尔值):启用 JVM 垃圾收集监控。默认值为 `true`。 + +- `monitor.jvm.gc.overhead.debug`(静态,整数):用于调试日志记录的 GC 开销百分比阈值。默认值为 `10`。范围为 `0-100`。 + +- `monitor.jvm.gc.overhead.info`(静态,整数):用于信息日志记录的 GC 开销百分比阈值。默认值为 `25`。范围为 `0-100`。 + +- `monitor.jvm.gc.overhead.warn`(静态,整数):用于警告日志记录的 GC 开销百分比阈值。默认值为 `50`。范围为 `0-100`。 + +- `monitor.jvm.gc.refresh_interval`(静态,时间单位):JVM GC 监控的刷新间隔。默认值为 `1s`。最小值为 `1s`。 + +- `monitor.jvm.refresh_interval`(静态,时间单位):JVM 统计监控的刷新间隔。默认值为 `1s`。最小值为 `1s`。 + +## 操作系统和进程监控设置 + +OpenSearch 支持以下操作系统和进程监控设置: + +- `monitor.os.refresh_interval`(静态,时间单位):操作系统统计监控的刷新间隔。默认值为 `1s`。最小值为 `1s`。 + +- `monitor.process.refresh_interval`(静态,时间单位):进程统计监控的刷新间隔。默认值为 `1s`。最小值为 `1s`。 diff --git a/i18n/zh/install-and-configure/configuring-opensearch/script-and-resource-settings.md b/i18n/zh/install-and-configure/configuring-opensearch/script-and-resource-settings.md new file mode 100644 index 00000000..d2991b2e --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/script-and-resource-settings.md @@ -0,0 +1,81 @@ +--- +title: 脚本和资源设置 +--- + +# 脚本和资源设置 + +OpenSearch 提供用于管理脚本编译行为和资源文件监控的设置。这些设置有助于控制脚本性能、安全性以及配置文件和其他资源的自动重新加载。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 资源重新加载设置 + +资源重新加载设置控制配置文件、安全证书和 OpenSearch 需要监视更改的其他资源的监控和自动重新加载。 + +OpenSearch 支持以下静态资源重新加载设置: + +- `resource.reload.enabled`(静态,布尔值):启用或禁用资源监视器服务。启用后,OpenSearch 监视已注册资源的更改并定期重新加载它们。这对于自动检测配置文件、安全证书和其他资源的更改非常有用,而无需重新启动集群。默认值为 `true`。 + +- `resource.reload.interval.low`(静态,时间单位):设置低频资源监控的重新加载间隔。以低频注册的资源将在此间隔检查更改。这通常用于不经常更改的资源,如配置文件。默认值为 `60s`(60 秒)。 + +- `resource.reload.interval.medium`(静态,时间单位):设置中频资源监控的重新加载间隔。以中频注册的资源将在此间隔检查更改。这为中度变化的资源提供了响应性和系统负载之间的平衡。默认值为 `30s`(30 秒)。 + +- `resource.reload.interval.high`(静态,时间单位):设置高频资源监控操作的重新加载间隔。此设置控制 OpenSearch 检查需要频繁监控的资源(如配置文件或安全证书)的更改的频率。更频繁的检查可以更快地响应更改,但会消耗更多的系统资源。资源监视器服务将此设置用于高优先级资源。默认值为 `5s`。 + +## 脚本大小设置 + +OpenSearch 支持以下动态脚本大小设置: + +- `script.max_size_in_bytes`(动态,整数):设置单个脚本的最大大小(以字节为单位)。OpenSearch 拒绝更长的脚本。默认值为 `65535`。 + +::: danger WARNING +仅在删除任何超过新值的存储脚本后才降低 `script.max_size_in_bytes`。OpenSearch 接受该设置但随后无法应用它,并且节点停止应用进一步的集群状态更新,直到删除该设置。 +::: + +## 脚本编译设置 + +OpenSearch 在首次使用时编译脚本并缓存编译结果,因此仅在脚本定义更改时才重新编译脚本。编译速率限制限制了节点在时间窗口内执行的新编译数量,这可以防止大量唯一脚本在编译时消耗节点的 CPU。有关缓存和速率限制如何应用于工作负载的说明,请参阅[编译限制和缓存](/scripting/using-scripts/#compilation-limits-and-caching)。 + +`script.max_compilations_rate` 的值确定缓存和速率限制是否为每个脚本上下文单独跟踪或在集群之间共享。OpenSearch 支持以下脚本编译设置: + +- `script.max_compilations_rate`(动态,字符串):设置为 `use-context` 以为每个脚本上下文提供自己的缓存和编译速率,通过[脚本上下文设置](#script-context-settings)进行配置。将其设置为 `<count>/<time>` 形式的速率,例如 `150/5m`,以使用单个集群范围的限制和一个共享缓存,在这种情况下,每个上下文的设置将被拒绝。默认值为 `use-context`。 + +- `script.cache.max_size`(静态,整数):设置每个节点上共享缓存中保存的已编译脚本数。当缓存已满时,最近最少使用的脚本将被逐出。显式配置此设置还会将 `script.context.<context>.cache_max_size` 的默认值更改为相同的值。默认值为 `100`。 + +- `script.cache.expire`(静态,时间单位):设置已编译脚本从共享缓存中逐出并在下次使用时必须重新编译的时间。显式配置此设置还会将 `script.context.<context>.cache_expire` 的默认值更改为相同的值。默认值为 `0ms`,这意味着缓存的脚本不会在计时器上过期。 + +- `script.disable_max_compilations_rate`(静态,布尔值):当设置为 `true` 时完全删除编译速率限制。此设置与显式 `script.max_compilations_rate` 和任何每个上下文的速率冲突,因此在设置它之前删除这些。默认值为 `false`。 + +::: info NOTE +`script.max_compilations_rate`、`script.cache.max_size` 和 `script.cache.expire` 已弃用,因为它们存在是为了支持单个共享缓存。将 `script.max_compilations_rate` 保留为 `use-context` 并配置每个上下文的设置,这些设置是动态的,无需重新启动即可生效。 +::: + +::: danger WARNING +没有编译限制的集群允许任何可以提交脚本的客户端消耗无限的编译 CPU。将触发限制的脚本参数化,而不是关闭限制。有关更多信息,请参阅[将值作为参数传递](/scripting/using-scripts/#passing-values-as-parameters)。 +::: + +## 脚本上下文设置 + +脚本上下文设置控制单个脚本上下文的缓存和编译,以便一个上下文中的大量重新编译不会逐出另一个上下文的缓存脚本。它们仅在 `script.max_compilations_rate` 设置为 `use-context` 时适用。将 `<context>` 替换为 [Get Script Contexts API](/api-reference/script-apis/get-script-contexts) 返回的上下文名称。 + +OpenSearch 支持以下动态脚本上下文设置: + +- `script.context.<context>.cache_max_size`(动态,整数):设置为此上下文保存的已编译脚本数。较大的缓存减少了使用许多不同脚本的工作负载的编译开销,并消耗更多内存。默认值为大多数上下文的 `100`,或者当显式配置该设置时为 `script.cache.max_size` 的值。 + +- `script.context.<context>.cache_expire`(动态,时间单位):设置此上下文的已编译脚本从缓存中逐出并在下次使用时必须重新编译的时间。默认值为 `0ms`,这意味着缓存的脚本不会在计时器上过期,或者当显式配置该设置时为 `script.cache.expire` 的值。 + +- `script.context.<context>.max_compilations_rate`(动态,字符串):设置在时间窗口内允许此上下文的编译数,格式为 `<count>/<time>`,例如 `200/1m`。将其设置为 `unlimited` 以删除此上下文的限制。当超过速率时,OpenSearch 返回带有 "Too many dynamic script compilations" 消息的 `circuit_breaking_exception`。默认值为大多数上下文的 `75/5m`。 + +三个上下文具有不同的默认值。下表列出了它们。 + +上下文 | 目的 | `cache_max_size` | `max_compilations_rate` +:--- | :--- | :--- | :--- +`search` | [`script` 搜索请求处理器](/search-plugins/search-pipelines/script-processor)。 | `200` | `unlimited` +`ingest` | [`script` 摄取处理器](/ingest-pipelines/processors/script)。 | `200` | `unlimited` +`processor_conditional` | 摄取处理器上的 `if` 条件。 | `200` | `unlimited` + +::: info NOTE +当 `script.max_compilations_rate` 设置为显式速率时,配置任何每个上下文的设置将失败,并显示 `Context cache settings [<settings>] requires [script.max_compilations_rate] to be [use-context]`。 +::: + +有关限制集群接受哪些脚本以及 Painless 中的正则表达式如何受约束的设置,请参阅[脚本安全](/scripting/script-security/)。 diff --git a/i18n/zh/install-and-configure/configuring-opensearch/thread-pool-settings.md b/i18n/zh/install-and-configure/configuring-opensearch/thread-pool-settings.md new file mode 100644 index 00000000..1895d422 --- /dev/null +++ b/i18n/zh/install-and-configure/configuring-opensearch/thread-pool-settings.md @@ -0,0 +1,140 @@ +--- +title: 线程池设置 +--- + +# 线程池设置 + +OpenSearch 使用多个线程池来管理内存消耗并有效处理不同类型的操作。可以配置线程池以根据集群的工作负载模式优化性能。 + +要了解如何应用这些设置,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +## 节点处理器设置 + +OpenSearch 自动检测可用处理器的数量并相应地配置线程池。您可以覆盖此检测: + +- `node.processors`(静态,整数):显式设置 OpenSearch 应用于线程池大小计算的处理器数量。当在同一主机上运行多个 OpenSearch 实例或自动处理器检测不正确时,这很有用。设置后,线程池大小将根据此值而不是检测到的处理器数量计算。默认值为自动检测到的处理器数量。 + +## 线程池类型 + +OpenSearch 支持以下线程池类型。每种类型支持不同的参数。 + +### 固定线程池 + +固定线程池维护恒定数量的线程,并使用队列处理待处理的请求。 + +OpenSearch 支持以下固定线程池: + +- `get`:用于文档检索操作(固定类型) +- `analyze`:用于分析 API 请求(固定类型) +- `write`:用于索引、删除、更新和批量操作(固定类型) +- `force_merge`:用于强制合并操作(固定类型) +- `search`:用于搜索操作(固定类型) +- `search_throttled`:用于限流搜索操作(固定类型) + +固定线程池支持以下设置: + +- `thread_pool.<pool_name>.size`(静态,整数):设置线程池中的线程数。线程数保持恒定,与工作负载无关。 + +- `thread_pool.<pool_name>.queue_size`(静态,整数):控制当所有线程都忙时待处理请求的队列大小。设置为 `-1` 表示无界队列。当队列已满时,新请求将被拒绝。默认值因线程池类型而异。 + +### 伸缩线程池 + +伸缩线程池根据工作负载动态调整线程数。 + +OpenSearch 支持以下伸缩线程池: + +- `generic`:用于常规后台操作,如节点发现(伸缩类型) +- `snapshot`:用于快照和恢复操作(伸缩类型) +- `warmer`:用于索引预热操作(伸缩类型) +- `refresh`:用于索引刷新操作(伸缩类型) +- `flush`:用于 `flush` 和 `fsync` 操作(伸缩类型) +- `management`:用于集群管理操作(伸缩类型) +- `fetch_shard_started`:用于分片状态操作(伸缩类型) +- `fetch_shard_store`:用于分片存储操作(伸缩类型) + +伸缩线程池支持以下设置: + +- `thread_pool.<pool_name>.core`(静态,整数):设置池中保持的最小线程数,即使空闲时也是如此。 + +- `thread_pool.<pool_name>.max`(静态,整数):设置池中可以创建的最大线程数。 + +- `thread_pool.<pool_name>.keep_alive`(静态,时间单位):确定空闲线程在被终止之前保持在池中的时间。超过核心大小的线程在此不活动期后被终止。 + +### Fork-join 线程池 +<Badge type="tip" text="3.2 版本引入" /> + +Fork-join 线程池使用 Java `ForkJoinPool` 为受益于工作窃取和任务分割的工作负载提供高效的并行性。这对于计算密集型操作很有用。在 OpenSearch 中,fork-join 线程池支持依赖于并行计算的功能,例如 [`opensearch-jvector` 插件](/install-and-configure/additional-plugins/opensearch-jvector),它加速索引构建。 + +Fork-join 线程池支持以下设置: + +- `thread_pool.<pool_name>.parallelism`(静态,整数):设置池的目标并行度级别(工作线程数)。通常,此值与可用处理器的数量匹配,但可以针对特定工作负载进行调整。 +- `thread_pool.<pool_name>.async_mode`(静态,布尔值):如果设置为 `true`,则使用 fork-join 池调度的异步模式。 +- `thread_pool.<pool_name>.queue_size`(静态,整数):设置任务提交队列的大小。将此值设置为 `-1` 表示无界队列大小。 + +## 示例配置 + +要配置固定线程池,请按如下方式更新配置文件: + +```yaml +thread_pool: + write: + size: 30 + queue_size: 1000 +``` + +要配置伸缩线程池,请按如下方式更新配置文件: + +```yaml +thread_pool: + warmer: + core: 1 + max: 8 + keep_alive: 2m +``` + +要配置 fork-join 线程池,请按如下方式更新配置文件: + +```yaml +thread_pool: + fork_join: + parallelism: 8 +``` + +要设置自定义处理器数量,请按如下方式更新配置文件: + +```yaml +node.processors: 8 +``` + +## 线程池计时设置 + +OpenSearch 支持以下线程池计时设置: + +- `thread_pool.estimated_time_interval`(静态,时间单位):设置更新线程池和其他时间敏感操作使用的缓存时间值的时间间隔。此设置控制 OpenSearch 更新其内部时间缓存的频率,以减少频繁系统时间调用的开销。较小的间隔提供更准确的时间测量,但会增加更频繁时间更新的 CPU 开销。将此设置为 `0` 会禁用缓存并在每个请求上直接调用系统时间(通常用于测试)。默认值为 `200ms`。最小值为 `0ms`。 + +## 集群级线程池设置 + +OpenSearch 支持集群级动态设置,允许您覆盖集群中所有节点的线程池配置: + +- `cluster.thread_pool.generic.max`(动态,整数):设置集群中所有节点的通用线程池的最大大小。这会覆盖 `opensearch.yml` 中指定的默认线程池配置。通用线程池处理轻量级操作和后台任务。使用此设置可以动态调整线程池大小,而无需重新启动节点。 + +- `cluster.thread_pool.snapshot.max`(动态,整数):设置集群中所有节点的快照线程池的最大大小。这会覆盖快照操作的默认线程池配置。快照线程池处理快照创建和恢复操作。使用此设置可以在高负载期间调整快照并发性。 + +- `cluster.thread_pool.<fixed-threadpool>.size`(动态,整数):控制固定和可调整大小队列线程池的大小。覆盖 `opensearch.yml` 中提供的默认值。 + +- `cluster.thread_pool.<scaling-threadpool>.max`(动态,整数):设置伸缩线程池的最大大小。覆盖 `opensearch.yml` 中提供的默认值。 + +- `cluster.thread_pool.<scaling-threadpool>.core`(动态,整数):指定伸缩线程池的核心大小。覆盖 `opensearch.yml` 中提供的默认值。 + +::: danger WARNING +在动态调整线程池设置之前,请注意这些是专家级设置,可能会破坏集群的稳定性。修改线程池设置会将相同的线程池大小应用于所有节点,因此不建议用于具有相同角色的不同硬件的集群。同样,避免调整数据节点和集群管理器节点共享的线程池。进行这些更改后,我们建议监控您的集群以确保它保持稳定并按预期执行。 +::: + +## 最佳实践 + +更新线程池设置时,请遵循以下最佳实践: + +- 监控线程池使用情况:使用 [Nodes Stats API](/api-reference/nodes-apis/nodes-stats) 监控线程池指标。 +- 避免过度配置:将线程池大小设置得太高会导致内存压力和上下文切换开销。 +- 考虑工作负载模式:根据集群的特定读/写模式调整线程池大小。 +- 测试配置更改:始终先在非生产环境中测试线程池修改。 diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/index.md b/i18n/zh/install-and-configure/install-opensearch/operator/index.md new file mode 100644 index 00000000..0a7f3a58 --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/index.md @@ -0,0 +1,200 @@ +--- +title: OpenSearch Kubernetes 操作器 +--- + +# OpenSearch Kubernetes 操作器 + +OpenSearch Kubernetes 操作器是一个开源的 Kubernetes 操作器,可帮助自动化在容器化环境中部署和配置 OpenSearch 和 OpenSearch Dashboards。该操作器可以管理多个 OpenSearch 集群,并可根据需要进行扩容和缩容。 + +## 安装操作器 + +操作器的 Helm chart 安装了一个验证 webhook,其证书由 [cert-manager](https://cert-manager.io/) 颁发,因此在安装操作器之前,必须在 Kubernetes 集群中安装 cert-manager。如果未安装 cert-manager,操作器安装将失败。有关其他选项,请参阅 [Webhooks](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/userguide/webhooks.md)。 + +使用 Helm 安装操作器,请按以下步骤操作: + +1. 安装 `cert-manager`。首先,添加 `cert-manager` Helm 仓库: + + ```bash + helm repo add jetstack https://charts.jetstack.io + ``` + + 然后安装 `cert-manager` 及其自定义资源定义: + + ```bash + helm install cert-manager jetstack/cert-manager --namespace cert-manager --create-namespace --set crds.enabled=true + ``` + +1. 添加操作器 Helm 仓库: + + ```bash + helm repo add opensearch-operator https://opensearch-project.github.io/opensearch-k8s-operator/ + ``` + +1. 更新本地 Helm chart 信息。如果之前已添加仓库,此步骤确保 Helm 安装最新的操作器版本: + + ```bash + helm repo update + ``` + +1. 安装操作器: + + ```bash + helm install opensearch-operator opensearch-operator/opensearch-operator + ``` + +## 快速入门 + +成功安装操作器后,可以通过在 Kubernetes 中创建自定义 `OpenSearchCluster` 对象来部署第一个 OpenSearch 集群。 + +::: warning IMPORTANT +以下步骤展示如何部署最小化集群,仅用于演示目的。要了解如何为生产环境配置和管理集群,请参阅[配置和管理](#配置和管理)。 +::: + +按照以下步骤部署集群、验证其运行状态、访问集群以及完成后清理资源: + +1. 创建包含以下内容的 `cluster.yaml` 文件: + + ```yaml + apiVersion: opensearch.org/v1 + kind: OpenSearchCluster + metadata: + name: my-first-cluster + namespace: default + spec: + security: + tls: + transport: + generate: true + http: + generate: true + general: + serviceName: my-first-cluster + version: "3" + dashboards: + enable: true + version: "3" + replicas: 1 + resources: + requests: + memory: "512Mi" + cpu: "200m" + limits: + memory: "512Mi" + cpu: "200m" + nodePools: + - component: nodes + replicas: 3 + diskSize: "5Gi" + nodeSelector: + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "cluster_manager" + - "data" + ``` + + ::: info NOTE + `version` 值必须是带引号的字符串。`security.tls` 部分是必需的:如果省略它,OpenSearch Pod 将永远无法就绪。`security.tls` 部分启用 Security 插件,`generate: true` 指示操作器生成自签名 TLS 证书。操作器还会创建包含随机生成密码的 `my-first-cluster-admin-password` 和 `my-first-cluster-dashboards-password` Secret。有关详细信息,请参阅 [TLS](/install-and-configure/install-opensearch/operator/operator-opensearch-config#tls) 和[用户和角色管理](/install-and-configure/install-opensearch/operator/operator-security)。 + ::: + +1. 运行以下命令创建集群: + + ```bash + kubectl apply -f cluster.yaml + ``` + +1. (可选)通过运行以下命令监控集群状态: + + ```bash + watch -n 2 kubectl get pods + ``` + + 操作器会创建多个 Pod: + + - 一个引导 Pod(`my-first-cluster-bootstrap-0`),用于帮助初始集群管理器发现。 + - 三个 OpenSearch 集群 Pod(`my-first-cluster-nodes-0`、`my-first-cluster-nodes-1` 和 `my-first-cluster-nodes-2`),以 `nodes` 节点池命名。 + - 一个 OpenSearch Dashboards 实例的 Pod(`my-first-cluster-dashboards-<id>`)。 + - 一个作业 Pod(`my-first-cluster-securityconfig-update-<id>`),应用安全配置后显示 `Completed` 状态。 + + 当三个 OpenSearch Pod 和 OpenSearch Dashboards Pod 在 `READY` 列中显示 `1/1` 时,集群已就绪,大约需要 3 分钟。然后操作器会移除引导 Pod。现在可以使用端口转发连接到集群。 + +1. 从 `my-first-cluster-admin-password` Secret 中检索为 `admin` 用户生成的密码: + + ```bash + kubectl get secret my-first-cluster-admin-password -o jsonpath='{.data.password}' | base64 -d; echo + ``` + +1. 访问 OpenSearch Dashboards 或使用 OpenSearch REST API: + + - 要访问 OpenSearch Dashboards,运行以下命令启动端口转发: + + ```bash + kubectl port-forward svc/my-first-cluster-dashboards 5601 + ``` + + 然后在浏览器中访问 [`http://localhost:5601`](http://localhost:5601),使用上一步检索到的密码以 `admin` 用户身份登录。 + + - 要使用 OpenSearch REST API,运行以下命令启动端口转发: + + ```bash + kubectl port-forward svc/my-first-cluster 9200 + ``` + + 然后打开第二个终端并运行以下命令,将 `<admin-password>` 替换为上一步检索到的密码: + + ```bash + curl -k -u 'admin:<admin-password>' "https://localhost:9200/_cat/nodes?v" + ``` + + 响应将列出三个已部署的节点。 + +1. 要删除集群,运行以下命令: + + ```bash + kubectl delete -f cluster.yaml + ``` + + 这会删除操作器创建的 Kubernetes 资源,但不会删除持久卷。要完全清理,需删除 PVC: + + ```bash + kubectl delete pvc -l opensearch.org/opensearch-cluster=my-first-cluster + ``` + +::: info NOTE +不支持单节点集群。集群必须至少有 3 个配置了 `master` 或 `cluster_manager` 角色的节点。 +::: + +## 配置和管理 + +部署集群后,可以使用以下指南配置和管理集群: + +- [操作器配置](/install-and-configure/install-opensearch/operator/operator-config):操作器级别的设置,如日志级别、命名空间和 `pprof` 端点。 +- [OpenSearch 集群配置](/install-and-configure/install-opensearch/operator/operator-opensearch-config):OpenSearch 特定的设置,包括节点池、TLS、插件和密钥库管理。 +- [OpenSearch Dashboards 配置](/install-and-configure/install-opensearch/operator/operator-dashboards-config):OpenSearch Dashboards 设置,包括身份验证、基础路径和 TLS。 +- [Kubernetes 部署自定义](/install-and-configure/install-opensearch/operator/operator-kubernetes-custom):Kubernetes 级别的设置,如持久化、安全上下文、卷和探针。 +- [集群操作](/install-and-configure/install-opensearch/operator/operator-cluster-ops):集群生命周期操作,包括恢复、升级和卷扩展。 +- [用户和角色管理](/install-and-configure/install-opensearch/operator/operator-security):安全设置、用户、角色和访问控制。 +- [高级管理](/install-and-configure/install-opensearch/operator/operator-advanced):监控、ISM 策略、索引模板和快照策略。 + +## 操作器发布 + +请注意以下关于操作器发布的信息: + +- 有关操作器和 OpenSearch 发布版本的兼容性矩阵,请参阅[兼容性](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/README.md#compatibility)。 +- 仓库中的 [OpenSearch 操作器用户指南](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/userguide/main.md)对应于代码的当前开发状态。要查看特定发布版本的文档,请在 GitHub 菜单中切换到版本标签。 +- 功能请求作为 GitHub issue 进行跟踪。如果希望实现某个功能并找到相应的 issue,请注意,标记为已完成的 issue 意味着该功能已在开发版本中实现。该功能可能还需要一些时间才能包含在正式发布中。如果不确定,请查看 GitHub 上的项目发布列表,查看该功能是否出现在发布说明中。 + +## 后续步骤 + +- 在生产环境中使用集群之前,请参阅[为生产准备集群](/install-and-configure/install-opensearch/#preparing-a-cluster-for-production)和[为生产准备 OpenSearch Dashboards](/install-and-configure/install-dashboards/#preparing-opensearch-dashboards-for-production)。 + +- 有关在 Kubernetes 上自定义 OpenSearch 集群的更多信息,包括数据持久化、身份验证方法和扩展,请参阅 [OpenSearch Kubernetes 操作器用户指南](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/userguide/main.md)。 + +- 要为 OpenSearch Kubernetes 操作器的开发做出贡献,请参阅仓库的[设计文档](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/docs/designs/high-level.md)。 + +- 有关更多信息,请参阅 [OpenSearch 操作器](https://operatorhub.io/operator/opensearch-operator)。 diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-advanced.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-advanced.md new file mode 100644 index 00000000..444190ff --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-advanced.md @@ -0,0 +1,241 @@ +--- +title: 高级管理 +--- + +# OpenSearch 操作器高级管理 + +本页介绍高级集群管理功能,包括监控、索引状态管理(ISM)策略、索引和组件模板以及快照策略。 + +## OpenSearch 监控 + +可以在集群上安装并启用 [OpenSearch 的 Prometheus 导出器插件](https://github.com/opensearch-project/opensearch-prometheus-exporter)。启用后,操作器会将插件安装到 OpenSearch Pod 中,并生成 Prometheus `ServiceMonitor` 对象来配置插件进行抓取。 + +默认情况下,使用 admin 用户访问监控 API。要使用具有有限权限的单独用户,可以使用以下选项之一创建该用户: + +- 使用 OpenSearch API 或 Dashboards 创建用户,创建包含 `username` 和 `password` 键的 Kubernetes Secret,并在 `monitoringUserSecret` 字段中提供该 Secret 名称。 +- 使用 `OpenSearchUser` CRD 创建用户,并在 `monitoringUserSecret` 字段中提供该 Secret。有关详细信息,请参阅[用户和角色管理](/install-and-configure/install-opensearch/operator/operator-security)。 + +要配置监控,请在集群 `spec` 中添加以下字段: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +metadata: + name: my-first-cluster + namespace: default +spec: + general: + version: <YOUR_CLUSTER_VERSION> + monitoring: + enable: true # 启用或禁用监控插件 + labels: # 添加到 ServiceMonitor 的标签 + someLabelKey: someLabelValue + scrapeInterval: 30s # Prometheus 的抓取间隔 + monitoringUserSecret: monitoring-user-secret # 可选,包含用户名/密码的 Secret 名称,供 Prometheus 访问插件指标端点,默认为 admin 用户 + pluginUrl: https://github.com/opensearch-project/opensearch-prometheus-exporter/releases/download/<YOUR_CLUSTER_VERSION>.0/prometheus-exporter-<YOUR_CLUSTER_VERSION>.0.zip # 可选,监控插件的自定义 URL + tlsConfig: # 可选,使用此选项覆盖生成的 ServiceMonitor 的 tlsConfig,只能设置以下提供的选项 + serverName: "testserver.test.local" + insecureSkipVerify: true # 操作器目前不允许使用证书配置 ServiceMonitor,因此需要设置此项 + # ... +``` + +## 使用 Kubernetes 资源管理 ISM 策略 + +操作器提供了一个自定义 Kubernetes 资源,允许使用 Kubernetes 对象创建、更新或管理 ISM 策略。 + +CRD 中的字段直接映射到 OpenSearch ISM 策略结构。操作器不会修改已存在的策略。可以按以下方式创建示例策略: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchISMPolicy +metadata: + name: sample-policy +spec: + opensearchCluster: + name: my-first-cluster + description: Hot-warm-delete lifecycle policy + policyId: sample-policy + defaultState: hot + states: + - name: hot + actions: + - replicaCount: + numberOfReplicas: 4 + transitions: + - stateName: warm + conditions: + minIndexAge: "10d" + - name: warm + actions: + - replicaCount: + numberOfReplicas: 2 + transitions: + - stateName: delete + conditions: + minIndexAge: "30d" + - name: delete + actions: + - delete: {} +``` + +`OpenSearchISMPolicy` 必须在与 OpenSearch 集群相同的命名空间中创建。`policyId` 字段是可选的;如果未提供,操作器会使用 `metadata.name`。 + +## 管理索引和组件模板 + +操作器提供了 `OpensearchIndexTemplate` 和 `OpensearchComponentTemplate` CRD 用于管理索引和组件模板。 + +这两个 CRD 规范与 OpenSearch API 结构非常相似,但有一些字段名称从 `snake_case` 改为 `camelCase`: + +- `index_patterns` → `indexPatterns`(仅限 `OpensearchIndexTemplate`) +- `composed_of` → `composedOf`(仅限 `OpensearchIndexTemplate`) +- `template.aliases.<alias>.is_write_index` → `template.aliases.<alias>.isWriteIndex` + +以下示例创建一个组件模板,设置分片和副本数量,并为文档指定时间格式: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchComponentTemplate +metadata: + name: sample-component-template +spec: + opensearchCluster: + name: my-first-cluster + + template: # 必需 + aliases: # 可选 + my_alias: {} + settings: # 可选 + number_of_shards: 2 + number_of_replicas: 1 + mappings: # 可选 + properties: + timestamp: + type: date + format: yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis + value: + type: double + version: 1 # 可选 + _meta: # 可选 + description: example description +``` + +以下索引模板使用前面定义的组件模板(参见 `composedOf`),适用于所有匹配 `logs-2020-01-*` 模式的索引: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchIndexTemplate +metadata: + name: sample-index-template +spec: + opensearchCluster: + name: my-first-cluster + + name: logs_template # 索引模板的名称 - 默认为 metadata.name。部署后无法原地更新 + + indexPatterns: # 必需的索引模式 + - "logs-2020-01-*" + composedOf: # 可选 + - sample-component-template + priority: 100 # 可选 + + template: {} # 可选 + version: 1 # 可选 + _meta: {} # 可选 +``` + +::: info NOTE +索引模板的 `.spec.name` 字段是不可变的,部署后无法更改。 +::: + +## 将 ISM 策略应用于现有索引 + +要将 ISM 策略应用于 OpenSearch 集群中的现有索引,请在 `OpenSearchISMPolicy` CRD 中将 `applyToExistingIndices` 标志设置为 `true`: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchISMPolicy +metadata: + name: test-policy-apply +spec: + opensearchCluster: + name: opensearch-cluster + applyToExistingIndices: true + description: "ISM policy applied to existing indexes" + defaultState: "hot" + ismTemplate: + indexPatterns: + - "logs-*" + states: + - name: hot + actions: + - replicaCount: + numberOfReplicas: 2 + transitions: + - stateName: warm + conditions: + minIndexAge: "1d" + - name: warm + actions: + - replicaCount: + numberOfReplicas: 1 +``` + +::: info NOTE +如果省略,`applyToExistingIndices` 字段默认为 `false`。 +::: + +设置为 `true` 时,操作器会将 ISM 策略应用于所有匹配指定索引模式的现有索引。如果多个 ISM 策略以启用此标志的方式针对相同的索引模式,则每个策略必须具有不同的优先级。 + +## 使用 Kubernetes 资源管理快照策略 + +操作器提供了一个自定义 Kubernetes 资源,用于使用 Kubernetes 清单创建、更新和管理快照生命周期管理(SLM)策略。这允许在集群资源旁边以声明方式定义和控制快照策略。 + +CRD 中的字段直接映射到 OpenSearch 快照策略结构。操作器不会修改已存在的策略。可以使用以下示例定义新策略: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchSnapshotPolicy +metadata: + name: sample-policy + namespace: default +spec: + policyName: sample-policy + enabled: true + description: Daily snapshot policy with weekly retention + opensearchCluster: + name: my-first-cluster + creation: + schedule: + cron: + expression: "0 0 * * *" + timezone: "UTC" + timeLimit: "1h" + deletion: + schedule: + cron: + expression: "0 1 * * *" + timezone: "UTC" + timeLimit: "30m" + deleteCondition: + maxAge: "7d" + maxCount: 10 + minCount: 3 + snapshotConfig: + repository: sample-repository + indices: "*" + includeGlobalState: true + ignoreUnavailable: false + partial: false + dateFormat: "yyyy-MM-dd-HH-mm" + dateFormatTimezone: "UTC" + metadata: + createdBy: "sample-operator" +``` + +请注意以下注意事项: + +::: info NOTE +- `OpensearchSnapshotPolicy` 必须在目标 OpenSearch 集群所在的命名空间中创建。 +- `policyName` 是可选的。如果未提供,操作器会使用 `metadata.name`。 +- `repository` 字段必须引用 OpenSearch 集群中配置的现有快照仓库。有关配置快照仓库的信息,请参阅[配置快照仓库](/install-and-configure/install-opensearch/operator/operator-opensearch-config#配置快照仓库)。 +::: diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-cluster-ops.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-cluster-ops.md new file mode 100644 index 00000000..4ec4c983 --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-cluster-ops.md @@ -0,0 +1,61 @@ +--- +title: 集群操作 +--- + +# 集群操作 + +操作器在集群生命周期中自动执行常见的管理任务,包括故障恢复、滚动升级、配置更改和卷扩展。 + +## 集群恢复 + +操作器会自动处理常见的故障场景并重启崩溃的 Pod。通常,操作器会逐个重启 Pod 以维持仲裁和集群稳定性。 + +如果操作器同时检测到某个节点池的多个 Pod 崩溃或丢失,它会切换到特殊的恢复模式,同时启动所有 Pod 并允许集群形成新的仲裁。这种并行恢复模式是实验性的,仅适用于基于 PVC 的存储,因为它使用现有 PVC 的数量来确定丢失 Pod 的数量。 + +恢复是通过临时更改每个节点池底层的 `StatefulSet` 并将 `podManagementPolicy` 设置为 `Parallel` 来完成的。如果遇到问题,请通过重新部署操作器并在 `values.yaml` 中添加 `manager.parallelRecoveryEnabled: false` 来禁用并行恢复。通过在操作器项目中创建 GitHub issue 来报告任何问题。 + +如果删除集群但保留 PVC,然后重新安装集群,恢复模式也会激活。 + +如果每个节点池都使用 `emptyDir` 存储,操作器会在以下故障场景中启动恢复: + +1. 超过半数的集群管理器节点丢失或崩溃,导致仲裁中断。 +2. 所有数据节点丢失或崩溃,没有数据节点可用。 + +因为 `emptyDir` 存储是临时的,当 Pod 被删除时数据会丢失且无法恢复。操作器在这种情况下会删除并重新创建整个 OpenSearch 集群。 + +## 滚动升级 + +操作器支持自动滚动版本升级。要升级,请更改集群 `spec` 中的 `general.version` 并重新应用: + +```yaml +spec: + general: + version: 3.0.0 +``` + +然后操作器执行滚动升级,逐个重启节点,并在每个节点后等待集群稳定并达到绿色状态。根据节点数量和存储的数据大小,这可能需要一些时间。 + +不支持降级和跨越多个主版本的升级,因为它们会使 OpenSearch 集群处于不受支持的状态。如果对数据节点使用 `emptyDir` 存储,请将 `general.drainDataNodes` 设置为 `true` 以避免数据丢失。 + +## 配置更改 + +如果在已安装的集群上更改 OpenSearch 配置,操作器会检测到它并对所有集群节点执行滚动重启以应用新配置。有关添加 OpenSearch 配置的更多信息,请参阅[配置 opensearch.yml](/install-and-configure/install-opensearch/operator/operator-opensearch-config#配置-opensearchyml)。这同样适用于节点池特定的配置,如 `resources`、`annotations` 或 `labels`。 + +## 卷扩展 + +如果底层存储支持在线卷扩展,操作器可以为您编排该操作。 + +要增加磁盘卷大小,请将节点池的 `diskSize` 设置为所需值并重新应用集群 `spec` YAML。此操作没有停机时间,集群保持运行。 + +增加磁盘大小时请注意以下事项: + +- 这仅适用于基于 PVC 的持久化。 +- 在扩展集群磁盘之前,备份卷和数据,以便在发生故障时可以通过从备份恢复。 +- 在应用新的 `diskSize` 之前,确保集群存储类具有 `allowVolumeExpansion: true`。有关详细信息,请参阅 [Kubernetes 存储类](https://kubernetes.io/docs/concepts/storage/storage-classes/)。 +- 验证存储类配置后,将具有新 `diskSize` 值的集群 YAML 应用于所有节点池或单个节点池。 +- 不要在卷扩展的同时对集群应用任何其他更改。 +- 确保大小单位一致。例如,如果 `diskSize` 是 `30G`,则使用 `G` 进行扩展(如 `50G`)。在扩展期间不要在 `G` 和 `Gi` 之间切换。 + +::: info NOTE +要将 `diskSize` 单位从 `G` 更改为 `Gi` 或反向,首先备份数据并计算正确的转换,以便底层卷大小保持不变。然后重新应用集群 YAML。这确保使用 `VolumeClaimTemplates` 中的正确值重新创建 `StatefulSet`。此操作没有停机时间。 +::: diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-config.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-config.md new file mode 100644 index 00000000..f1e378ab --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-config.md @@ -0,0 +1,70 @@ +--- +title: 操作器配置 +--- + +# 操作器配置 + +可以使用在安装期间提供的 Helm 值来配置操作器本身的常规选项:`helm install opensearch-operator opensearch-operator/opensearch-operator -f values.yaml`。 + +有关所有支持的值列表,请参阅默认 chart 的 [`values.yaml`](https://github.com/opensearch-project/opensearch-k8s-operator/blob/main/charts/opensearch-operator/values.yaml)。以下是一些重要的配置选项: + +```yaml +manager: + # 操作器的日志级别。可能的值:debug、info、warn、error + loglevel: info + + # 如果指定,操作器将仅限于监视所需命名空间中的对象。默认是监视所有命名空间。 + # 要监视多个命名空间,可以使用逗号分隔它们的名称或将它们定义为列表。 + # 示例: + # watchNamespaces: 'ns1,ns2' + # watchNamespace: [ns1, ns2] + watchNamespace: + + # 为操作器配置额外的环境变量。也可以从 Secret 或 ConfigMap 中拉取它们。 + extraEnv: [] + # - name: MY_ENV + # value: somevalue +``` + +::: info NOTE +操作器使用准入控制器 webhook 来验证 OpenSearch 自定义资源定义(CRD)。 +::: + +<!-- vale off --> +## pprof 端点 +<!-- vale on --> + +要诊断内存问题,可以通过在 `values.yaml` 中添加以下内容来启用标准 Go [`pprof`](https://pkg.go.dev/net/http/pprof) 端点: + +```yaml +manager: + pprofEndpointsEnabled: true +``` + +出于安全原因,端点仅在 Pod 内的 `localhost` 上公开。要访问它们,请使用端口转发: + +```bash +kubectl port-forward deployment/opensearch-operator-controller-manager 6060 +``` + +然后从另一个终端使用 Go `pprof` 工具: + +```bash +go tool pprof http://localhost:6060/debug/pprof/heap +``` + +## 自定义操作器通信 URL + +可以通过设置 `operatorClusterURL` 字段来配置操作器在与 OpenSearch 通信时使用自定义 URL: + +```yaml +spec: + general: + serviceName: my-cluster + version: "3.0.0" + httpPort: 9200 + vendor: "opensearch" + operatorClusterURL: "opensearch.example.com" # 可选:操作器通信的自定义 FQDN +``` + +当有外部证书(例如来自 cert-manager)对特定 FQDN 有效时,请使用此配置。操作器使用此自定义 URL 而不是默认的内部 Kubernetes DNS 名称,允许为外部访问和操作器通信使用相同的证书。 diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-dashboards-config.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-dashboards-config.md new file mode 100644 index 00000000..4a09300a --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-dashboards-config.md @@ -0,0 +1,108 @@ +--- +title: OpenSearch Dashboards 配置 +--- + +# OpenSearch Dashboards 配置 + +操作器可以自动部署和管理 OpenSearch Dashboards 实例。要启用它,请在集群 `spec` 中添加以下部分: + +```yaml +# ... +spec: + dashboards: + enable: true # 设置为 true 以启用 OpenSearch Dashboards 部署 + version: 3.0.0 # 要部署的 OpenSearch Dashboards 版本。这应该与 OpenSearch 集群版本匹配 + replicas: 1 # 要部署的副本数 +``` + +## 配置 opensearch_dashboards.yml + +可以使用 `OpenSearchCluster` 自定义资源的 dashboards 部分中的 `additionalConfig` 字段自定义 OpenSearch Dashboards 配置(`opensearch_dashboards.yml`): + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +#... +spec: + dashboards: + additionalConfig: + opensearch_security.auth.type: "proxy" + opensearch.requestHeadersWhitelist: | + ["securitytenant","Authorization","x-forwarded-for","x-auth-request-access-token", "x-auth-request-email", "x-auth-request-groups"] + opensearch_security.multitenancy.enabled: "true" +``` + +可以使用此功能为 OpenSearch Dashboards 配置任何[后端身份验证类型](/security/configuration/configuration)。 + +::: info NOTE +配置必须有效。如果配置无效,OpenSearch Dashboards 实例将无法启动。 +::: + +## 在 dashboards 配置中存储敏感信息 + +可能需要在 OpenSearch Dashboards 配置文件中存储敏感信息(例如,OpenID Connect 的客户端密钥)。为了安全地执行此操作,请使用 OpenSearch Dashboards 变量替换。 + +创建包含敏感信息的 Secret(例如,`dashboards-oidc-config`)并将其作为环境变量挂载到 OpenSearch Dashboards Pod 中。有关说明,请参阅[向 Pod 添加环境变量](/install-and-configure/install-opensearch/operator/operator-kubernetes-custom#向-pod-添加环境变量)。然后可以在 OpenSearch Dashboards 配置中引用该 Secret 的任何键。 + +以下示例显示了集群 `spec` 的一部分: + +```yaml +spec: + dashboards: + env: + - name: OPENID_CLIENT_SECRET + valueFrom: + secretKeyRef: + name: dashboards-oidc-config + key: client_secret + additionalConfig: + opensearch_security.openid.client_secret: "${OPENID_CLIENT_SECRET}" +``` + +::: info NOTE +更改 Secret 中的值不会直接影响 OpenSearch Dashboards 配置。要应用更改,请重启 OpenSearch Dashboards Pod。 +::: + +## 配置基础路径 + +在子路径(例如 `/logs`)上的反向代理后面使用 OpenSearch Dashboards 时,通过设置 `basePath` 字段来配置基础路径。操作器会自动将正确的配置选项添加到 OpenSearch Dashboards 配置中: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +metadata: + name: my-cluster +spec: + dashboards: + enable: true + basePath: "/logs" +``` + +这也会将 `server.rewriteBasePath` 选项设置为 `true`。如果使用 ingress 控制器公开 OpenSearch Dashboards,请配置它以匹配此设置。 + +## OpenSearch Dashboards HTTP + +OpenSearch Dashboards 可以使用 HTTP 或 HTTPS 公开其 API 和 UI。默认情况下,连接未加密(HTTP)。要保护连接,可以让操作器生成并签署证书,或提供自己的证书。`OpenSearchCluster` 自定义资源中的以下字段配置 OpenSearch Dashboards 的 TLS: + +```yaml +# ... +spec: + dashboards: + enable: true # 部署 OpenSearch Dashboards 组件 + tls: + enable: true # 配置 TLS + generate: true # 让操作器生成并签署证书 + # 生成的证书有效期(默认:8760h = 1 年) + duration: "8760h" + secret: + name: # 包含提供的证书的 Secret 名称 + caSecret: + name: # 包含操作器应使用的 CA 的 Secret 名称 +# ... +``` + +要让操作器生成证书,请设置 `tls.enable: true` 和 `tls.generate: true`(可以省略 `tls` 下的其他字段)。与节点证书一样,可以使用 `caSecret.name` 提供自己的 CA 供操作器使用。 + +要使用自己的证书,请将其作为 Kubernetes TLS Secret(带有字段 `tls.key` 和 `tls.crt`)提供,并在 `secret.name` 中指定 Secret 名称。 + +在集群外部公开 OpenSearch Dashboards 时,请在内部使用操作器生成的证书,并让 ingress 控制器提供来自认可 CA(例如 Let's Encrypt)的有效证书。 diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-kubernetes-custom.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-kubernetes-custom.md new file mode 100644 index 00000000..ce0921c6 --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-kubernetes-custom.md @@ -0,0 +1,638 @@ +--- +title: Kubernetes 部署自定义 +--- + +# Kubernetes 部署自定义 + +除了配置 OpenSearch 本身之外,还可以自定义操作器如何部署 OpenSearch 和 OpenSearch Dashboards Pod。 + +## 数据持久化 + +默认情况下,操作器使用默认[存储类](https://kubernetes.io/docs/concepts/storage/storage-classes/)的持久存储创建 OpenSearch 节点池。可以按节点池更改此行为。可以提供替代存储类和访问模式,或配置 `hostPath` 或 `emptyDir` 存储。 + +可用的存储选项包括: + +<!-- vale off --> +### 持久卷声明(PVC) +<!-- vale on --> + +默认选项是使用 PVC 的持久存储。如果需要,可以显式定义 `storageClass`、`annotations` 和 `labels`: + +```yaml +nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "data" + - "master" + persistence: + pvc: + storageClass: mystorageclass # 设置要使用的存储类名称 + accessModes: # 可以更改 accessMode + - ReadWriteOnce + annotations: # 可以添加注释 + test.io/crypt-key-id: "your-kms-key-id" + labels: # 可以添加标签 + team: "backend-data" +``` + +<!-- vale off --> +### emptyDir +<!-- vale on --> + +如果不想使用持久存储,可以使用 `emptyDir` 选项。请注意,这可能导致数据丢失,因此只应将此选项用于测试或以其他方式持久化的数据。 + +```yaml +nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "data" + - "master" + persistence: + emptyDir: {} # 这配置 emptyDir +``` + +如果使用 `emptyDir`,请将 `spec.general.drainDataNodes` 设置为 `true`。这确保在执行滚动升级或重启操作之前从 Pod 中清空分片。 + +<!-- vale off --> +### hostPath +<!-- vale on --> + +作为最后的选项,可以使用 `hostPath`。强烈不建议使用 `hostPath`。默认情况下,操作器应用 Pod 反亲和性以防止多个 Pod 调度到同一节点,这在使用 `hostPath` 时很有帮助。但是,如果需要更严格的控制,请为节点池配置显式亲和性规则,以确保多个 Pod 不会调度到同一 Kubernetes 主机。 + +```yaml +nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "data" + - "master" + persistence: + hostPath: + path: "/var/opensearch" # 在此处定义主机上的路径 +``` + +## Pod 和容器的安全上下文 + +可以为 OpenSearch Pod 和 OpenSearch Dashboards Pod 设置安全上下文,以定义权限和访问控制设置。要为 Pod 指定安全设置,请包含 `podSecurityContext` 字段。对于容器,请包含 `securityContext` 字段。 + +OpenSearch Pod(在 `spec.general` 中)和 OpenSearch Dashboards Pod(在 `spec.dashboards` 中)的结构相同: + +```yaml +spec: + general: + podSecurityContext: + runAsUser: 1000 + runAsGroup: 1000 + runAsNonRoot: true + securityContext: + allowPrivilegeEscalation: false + privileged: false + dashboards: + podSecurityContext: + fsGroup: 1000 + runAsNonRoot: true + securityContext: + capabilities: + drop: + - ALL + privileged: false +``` + +默认情况下,OpenSearch Pod 启动一个初始化容器来配置卷。此容器需要使用 root 权限运行,并且不使用定义的 `securityContext`。如果 Kubernetes 环境不允许使用 root 用户的容器,请[禁用此初始化帮助器](#禁用初始化帮助器)。在这种情况下,请将 `general.setVMMaxMapCount` 设置为 `false`,因为此功能也会启动具有 root 的初始化容器。 + +::: info NOTE +在初始集群设置期间启动的引导 Pod 使用与 OpenSearch Pod 相同的 Pod `securityContext`(初始化容器具有相同的限制)。 +::: + +引导 Pod 使用持久存储(PVC)在初始化期间跨重启维护集群状态。这可以防止在安全配置更新作业完成后引导 Pod 重启时集群形成失败。引导 PVC 会与引导 Pod 一起自动创建和删除。 + +## OpenSearch 节点上的标签或注释 + +可以向节点池配置添加额外的标签或注释。这对于与其他应用程序(如服务网格)集成或配置 Prometheus 抓取端点很有用。 + +此外,可以使用 `spec.general.annotations` 字段全局配置注释。这些注释不仅适用于节点池,还适用于 Kubernetes 服务。 + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "5Gi" + labels: # 在此处添加任何额外的标签作为键值对 + someLabelKey: someLabelValue + annotations: # 在此处添加任何额外的注释作为键值对 + someAnnotationKey: someAnnotationValue + nodeSelector: + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "data" + - "master" +``` + +定义的任何注释和标签都会直接添加到节点池 Pod 中。 + +## 向 OpenSearch Dashboards 部署添加标签或注释 + +可以向 OpenSearch Dashboards Pod 规范添加标签或注释。如果希望 OpenSearch Dashboards 成为服务网格的一部分或与依赖标签或注释的其他应用程序集成,这会很有帮助。 + +```yaml +spec: + dashboards: + enable: true + version: 3.0.0 + replicas: 1 + labels: # 在此处添加任何额外的标签作为键值对 + someLabelKey: someLabelValue + annotations: # 在此处添加任何额外的注释作为键值对 + someAnnotationKey: someAnnotationValue +``` + +定义的任何注释和标签都会直接添加到 OpenSearch Dashboards Pod 中。 + +## OpenSearch 节点上的优先级类 + +可以通过指定优先级类名称来配置 OpenSearch 节点使用 `PriorityClass`。这有助于防止不必要地驱逐 OpenSearch 节点。 + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "5Gi" + priorityClassName: somePriorityClassName + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "master" +``` + +## Pod 亲和性 + +默认情况下,操作器应用 Pod 反亲和性规则,以防止来自同一 OpenSearch 集群的多个 Pod 调度到同一节点。这通过减少单个节点故障影响多个 Pod 的风险来提高高可用性。 + +默认反亲和性使用 `PreferredDuringSchedulingIgnoredDuringExecution`,这是一种软偏好,如果没有其他节点可用,不会阻止调度,但会优先将 Pod 分散到各个节点。 + +可以通过在节点池、引导或 OpenSearch Dashboards 配置中显式设置 `affinity` 字段来覆盖此默认行为: + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + roles: + - "master" + - "data" + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: + matchLabels: + opensearch.org/opensearch-cluster: my-cluster + topologyKey: kubernetes.io/hostname + bootstrap: + affinity: + podAntiAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + labelSelector: + matchLabels: + opensearch.org/opensearch-cluster: my-cluster + topologyKey: kubernetes.io/hostname + dashboards: + enable: true + affinity: + podAffinity: + preferredDuringSchedulingIgnoredDuringExecution: + - weight: 100 + podAffinityTerm: + labelSelector: + matchLabels: + app: opensearch-dashboards + topologyKey: kubernetes.io/zone +``` + +如果设置显式 `affinity`,它会完全替换默认的反亲和性行为。要完全禁用反亲和性,请设置 `affinity: {}`。 + +## Sidecar 容器 + +可以在同一 Pod 中与 OpenSearch 一起部署额外的 sidecar 容器。这对于日志传送、监控代理或需要与 OpenSearch 节点一起运行的其他辅助服务很有用。 + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "master" + - "data" + sidecarContainers: + - name: log-shipper + image: fluent/fluent-bit:latest + resources: + requests: + memory: "64Mi" + cpu: "100m" + limits: + memory: "128Mi" + cpu: "200m" + volumeMounts: + - name: varlog + mountPath: /var/log + - name: monitoring-agent + image: prometheus/node-exporter:latest + ports: + - containerPort: 9100 + name: metrics +``` + +Sidecar 容器与 OpenSearch 容器共享相同的网络命名空间和存储卷,因为它们在同一 Pod 中运行。 + +## 额外的卷 + +可以将额外的卷挂载到 OpenSearch Pod 中以提供额外的配置(例如,插件配置文件)。支持的卷类型包括 `ConfigMap`、`Secret`、`emptyDir`、投影卷和 CSI 卷。 + +在 `spec.general.additionalVolumes` 或 `spec.dashboards.additionalVolumes` 中提供额外卷的数组: + +```yaml +spec: + general: + additionalVolumes: + - name: example-configmap + path: /path/to/mount/volume + #subPath: mykey # 添加此项以仅挂载 configmap/secret 的特定键 + configMap: + name: config-map-name + restartPods: true # 将此设置为 true 以在 configMap 内容更改时重启 Pod + - name: temp + path: /tmp + emptyDir: {} + - name: example-csi-volume + path: /path/to/mount/volume + #subPath: "subpath" # 添加此项以在特定子路径挂载 CSI 卷 + csi: + driver: csi-driver-name + readOnly: true + volumeAttributes: + secretProviderClass: example-secret-provider-class + - name: example-projected-volume + path: /path/to/mount/volume + projected: + sources: + - serviceAccountToken: + path: "token" + - name: example-persistentvolumeclaim-volume + path: /path/to/mount/volume + persistentVolumeClaim: + claimName: claim-name + - name: nfs-volume + path: /mnt/backups/opensearch + nfs: + server: 192.168.1.233 + path: /export/backups/opensearch + readOnly: false # 可选,默认为 false + dashboards: + additionalVolumes: + - name: example-secret + path: /path/to/mount/volume + secret: + secretName: secret-name +``` + +### NFS 卷支持 + +NFS 卷可以直接挂载到 OpenSearch Pod 中,无需外部配置器或 CSI 驱动程序。这对于存储在 NFS 共享上的快照仓库特别有用。要配置 NFS 卷,请使用必需的 `server` 和 `path` 参数指定 `nfs` 字段: + +```yaml +spec: + general: + additionalVolumes: + - name: nfs-backups + path: /mnt/backups/opensearch + nfs: + server: 192.168.1.233 + path: /export/backups/opensearch + readOnly: false # 可选,默认为 false +``` + +这可以与快照仓库配置结合使用: + +```yaml +spec: + general: + additionalVolumes: + - name: nfs-backups + path: /mnt/backups/opensearch + nfs: + server: 192.168.1.233 + path: /export/backups/opensearch + snapshotRepositories: + - name: nfs-repository + type: fs + settings: + location: /mnt/backups/opensearch +``` + +操作器将定义的卷添加到 OpenSearch 集群的所有 Pod。目前无法按节点池(`nodePools`)定义它们。 + +## 向 Pod 添加环境变量 + +可以向 OpenSearch Pod 和 OpenSearch Dashboards Pod 添加自己的环境变量。可以将值作为字符串文字提供,或从 Secret 或 `ConfigMap` 挂载。 + +OpenSearch 和 OpenSearch Dashboards 的结构相同: + +```yaml +spec: + dashboards: + env: + - name: MY_ENV_VAR + value: "myvalue" + - name: MY_SECRET_VAR + valueFrom: + secretKeyRef: + name: my-secret + key: some_key + - name: MY_CONFIGMAP_VAR + valueFrom: + configMapKeyRef: + name: my-configmap + key: some_key + nodePools: + - component: nodes + env: + - name: MY_ENV_VAR + value: "myvalue" + # 此处也支持其他选项。 +``` + +## 自定义集群域名 + +如果 Kubernetes 集群配置了自定义域名(默认为 `cluster.local`),请相应地配置操作器以使内部路由正常工作。在 Helm chart 值中设置 `manager.dnsBase`。 + +```yaml +manager: + # ... + dnsBase: custom.domain +``` + +## 自定义初始化帮助器 + +在集群初始化期间,操作器使用初始化容器作为帮助器。对于这些容器,使用 `busybox` 镜像(特别是 `docker.io/busybox:latest`)。如果在离线环境中工作且集群无法访问注册表,或者想要自定义镜像,可以通过在集群 `spec` 中指定 `initHelper` 镜像来覆盖使用的镜像: + +```yaml +spec: + initHelper: + # 可以仅指定版本 + version: "1.27.2-buildcustom" + # 或指定完全不同的镜像 + image: "mycustomrepo.cr/mycustombusybox:myversion" + # 此外可以定义 imagePullPolicy + imagePullPolicy: IfNotPresent + # 如果需要,可以定义 imagePullSecrets + imagePullSecrets: + - name: docker-pull-secret +``` + +## 编辑初始化容器资源 + +初始化容器在没有任何资源约束的情况下运行,但可以通过向 YAML 定义添加 resources 部分来指定资源请求和限制。可以通过设置适当的资源限制来控制分配给初始化容器的 CPU 和内存量,帮助确保它不会耗尽其他容器的资源。 + +```yaml +spec: + initHelper: + resources: + requests: + memory: "128Mi" + cpu: "250m" + limits: + memory: "512Mi" + cpu: "500m" +``` + +## 禁用初始化帮助器 + +在某些情况下,可能希望避免使用 `chmod` 初始化容器(例如,在 OpenShift 上或者如果集群阻止以 `root` 身份运行的容器)。 +可以通过在 `values.yaml` 中添加以下内容来禁用它: + +```yaml +manager: + extraEnv: + - name: SKIP_INIT_CONTAINER + value: "true" +``` + +## PodDisruptionBudget + +PDB(Pod 中断预算)是一种 Kubernetes 资源,通过在维护或意外事件期间定义可接受的中断级别来帮助确保应用程序的高可用性。 +它指定必须保持可用的最小 Pod 数量以维持所需的服务级别。 +PDB 定义对于每个节点池(`nodePools`)是唯一的。 +提供 `minAvailable` 或 `maxUnavailable` 来配置 PDB,但不能同时提供两者。 + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + pdb: + enable: true + minAvailable: 3 + - component: datas + replicas: 7 + diskSize: "100Gi" + pdb: + enable: true + maxUnavailable: 2 +``` + +## 公开 OpenSearch Dashboards + +要为 Kubernetes 集群外部的用户或服务公开集群的 OpenSearch Dashboards 实例,推荐的方法是使用 ingress。 + +一个简单的示例: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: opensearch-dashboards + namespace: default +spec: + tls: + - hosts: + - dashboards.my.company + rules: + - host: dashboards.my.company + http: + paths: + - backend: + service: + name: my-cluster-dashboards + port: + number: 5601 + path: "/(.*)" + pathType: ImplementationSpecific +``` + +::: info NOTE +如果为 OpenSearch Dashboards 启用了 HTTPS,请指示 ingress 控制器在内部使用 HTTPS 连接。这取决于所使用的控制器(例如,nginx-ingress 或 `traefik`)。 +::: + +## 配置 OpenSearch Dashboards Kubernetes 服务 + +可以自定义操作器为 OpenSearch Dashboards 部署生成的 Kubernetes Service 对象。 + +支持的服务类型: + +- ClusterIP(默认) +- NodePort +- LoadBalancer + +使用类型 `LoadBalancer` 时,可以选择性地设置负载均衡器源范围。 + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + dashboards: + service: + type: LoadBalancer # 设置支持的类型之一 + loadBalancerSourceRanges: "10.0.0.0/24, 192.168.0.0/24" # 可选,为负载均衡器添加源范围 +``` + +## 公开 OpenSearch 集群 REST API + +要在 Kubernetes 集群外部公开 OpenSearch 的 REST API,推荐的方法是使用 ingress。 +在内部,使用自签名证书(可以让操作器生成它们),然后让 ingress 使用来自可接受 CA(例如 Let's Encrypt 或公司内部 CA)的证书。这样,您无需向 OpenSearch 集群提供自定义证书,但用户仍然看到有效的证书。 + +## 自定义探针超时和阈值 + +如果集群节点在达到阈值之前没有启动并且 Pod 重启,可以根据需要为每个节点配置超时和阈值。 + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + nodePools: + - component: masters + replicas: 3 + diskSize: "30Gi" + probes: + liveness: + initialDelaySeconds: 10 + periodSeconds: 20 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 10 + startup: + initialDelaySeconds: 10 + periodSeconds: 20 + timeoutSeconds: 5 + successThreshold: 1 + failureThreshold: 10 + readiness: + initialDelaySeconds: 60 + periodSeconds: 30 + timeoutSeconds: 30 + successThreshold: 1 + failureThreshold: 5 +``` + +## 自定义启动和就绪探针命令 + +虽然 `liveness` 探针是 TCP 检查,但启动和就绪探针使用带有 cURL 的 OpenSearch API。 + +如果需要自定义启动或就绪探针命令,可以按以下示例所示覆盖它们: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +... +spec: + nodePools: + - component: masters + ... + probes: + startup: + command: + - echo + - "Hello, World!" + readiness: + command: + - echo + - "Hello, World!" +``` + +## 配置资源限制和请求 + +除了前面部分提供的有关如何为节点池指定资源需求的信息外,还可以为操作器创建的所有实体指定资源以满足更高级的用例。 + +操作器使用作业、有状态集和副本集等资源生成许多使用初始化容器的 Pod。以下配置允许为所有初始化容器指定默认资源配置。 + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + initHelper: + resources: + requests: + memory: "50Mi" + cpu: "50m" + limits: + memory: "200Mi" + cpu: "200m" +``` + +还可以配置安全更新作业的资源,如以下示例所示。 + +```yaml +apiVersion: opensearch.org/v1 +kind: OpenSearchCluster +--- +spec: + security: + config: + updateJob: + resources: + limits: + cpu: "100m" + memory: "100Mi" + requests: + cpu: "100m" + memory: "100Mi" +``` + +::: info NOTE +此处提供的示例不反映实际的资源需求。可能需要进行进一步测试,以根据特定需求正确调整资源。 +::: diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-opensearch-config.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-opensearch-config.md new file mode 100644 index 00000000..e4d0ba6a --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-opensearch-config.md @@ -0,0 +1,383 @@ +--- +title: OpenSearch 集群配置 +--- + +# OpenSearch 集群配置 + +操作器部署和管理 OpenSearch 集群。可以配置节点池、TLS 证书、插件、密钥库 Secret 和其他集群特定的设置。 + +## 节点池和扩展 + +OpenSearch 集群由一个或多个节点池组成。每个节点池是具有相同[角色](/tuning-your-cluster/creating-a-cluster/#nodes)的节点的逻辑组,并且可以拥有自己的资源。对于每个配置的节点池,操作器会创建一个 Kubernetes `StatefulSet` 和 `Service`,允许与特定节点池通信: + +```yaml +spec: + nodePools: + - component: masters + replicas: 3 # 副本数 + diskSize: "30Gi" # 要使用的磁盘大小 + resources: # 该节点池的资源请求和限制 + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: # 节点应具有的角色 + - "cluster_manager" + - "data" + - component: nodes + replicas: 3 + diskSize: "10Gi" + nodeSelector: + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "data" +``` + +有关其他节点池配置选项(如存储、安全上下文、标签和亲和性规则),请参阅 [Kubernetes 部署自定义](/install-and-configure/install-opensearch/operator/operator-kubernetes-custom)。 + +## 配置 opensearch.yml + +操作器根据您提供的集群 `spec` 中的参数自动生成 `opensearch.yml` 配置文件(例如,传输层安全(TLS)配置)。要添加自定义设置,请在集群 `spec` 中使用 `additionalConfig` 字段: + +```yaml +spec: + general: + # ... + additionalConfig: + some.config.option: somevalue + # ... +nodePools: + - component: masters + # ... + additionalConfig: + some.other.config: foobar +``` + +使用 `spec.general.additionalConfig` 添加应用于所有集群节点的设置。操作器将这些设置存储在共享 `ConfigMap` 中并将其挂载到所有节点池。 + +对于特定于节点池的配置,请使用 `nodePools[].additionalConfig`。操作器将这些设置与该节点池的 `spec.general.additionalConfig` 合并,节点池设置优先。当节点池定义了 `additionalConfig` 时,它会收到自己的 `ConfigMap`,其中包含合并的配置。 + +使用平面形式将所有设置作为字符串映射提供。对于非字符串值(例如,布尔值或数值),请用引号括起来:`"true"` 或 `"1234"`。 + +操作器将其生成的设置与您提供的自定义设置合并。您无法使用 `additionalConfig` 覆盖基本设置,如 `node.name`、`node.roles`、`cluster.name` 以及网络和发现设置。 + +::: info NOTE +更改任何 `additionalConfig` 都会触发集群的滚动重启。要避免重启,请使用[集群设置 API](/install-and-configure/configuring-opensearch/) 在运行时更改设置。 +::: + +## TLS + +出于安全原因,与 OpenSearch 集群通信以及集群节点之间的通信都需要加密。如果不配置任何加密,OpenSearch 会使用包含的演示 TLS 证书,这些证书不适用于生产部署。 + +根据需求,操作器提供以下管理 TLS 证书的方式: + +- **操作器生成的证书(推荐)**:操作器生成自己的证书颁发机构(CA)并使用该 CA 为所有节点签署证书。除非希望直接在 Kubernetes 集群外部公开 OpenSearch 集群,或者组织对内部通信使用自签名证书有规定,否则请使用此选项。 +- **您自己的证书**:提供您自己的证书。 + +::: info NOTE +当操作器生成证书时,可以使用 `duration` 字段控制证书有效期(例如,`"720h"`、`"17520h"`)。如果省略,默认为一年(`"8760h"`)。 +::: + +TLS 证书用于以下端点(每个端点可以独立配置): + +- [节点传输](#节点传输) +- [节点 HTTP REST API](#节点-http-rest-api) +- [OpenSearch Dashboards HTTP](/install-and-configure/install-opensearch/operator/operator-dashboards-config#opensearch-dashboards-http) + +### 节点传输 + +OpenSearch 集群节点使用 OpenSearch 传输协议(默认端口 9300)相互通信。此端点不对外公开,因此在几乎所有情况下,操作器生成的证书都足够了。 + +要配置节点传输安全性,可以在 `OpenSearchCluster` 自定义资源中使用以下字段: + +```yaml +# ... +spec: + security: + tls: # 与 TLS 配置相关的所有内容 + transport: # 传输端点的配置 + enabled: true # 为传输启用 TLS(默认:如果传输配置存在则为 true) + generate: true # 让操作器生成并签署证书 + perNode: true # 每个节点单独的证书 + # 生成的证书有效期(默认:8760h = 1 年) + duration: "8760h" + secret: + name: # 包含提供的证书的 Secret 名称 + caSecret: + name: # 包含操作器应使用的 CA 的 Secret 名称 + nodesDn: [] # 允许连接的证书 DN 列表 +# ... +``` + +要让操作器生成证书,请将 `generate` 和 `perNode` 设置为 `true`(可以省略其他字段)。操作器会生成 CA 证书,为每个节点颁发一个证书,并对其进行签名。证书默认有效期为一年,可以使用 `duration` 配置。如果设置了 `rotateDaysBeforeExpiry`,操作器支持在接近过期时重新颁发证书来实现轮换。 + +或者,可以自己提供证书(例如,如果组织有内部 CA)。可以提供一个供所有节点使用的证书,或为每个节点提供证书(推荐)。在此模式下,根据是否提供每个节点的证书,将 `generate: false` 和 `perNode` 设置为 `true` 或 `false`。 + +如果仅提供一个证书,请将其放在 Kubernetes TLS Secret 中(带有字段 `ca.crt`、`tls.key` 和 `tls.crt`,全部为 PEM 编码),并将 Secret 名称作为 `secret.name` 提供。要将 CA 证书单独保存,请将其放在单独的 Secret 中并将其作为 `caSecret.name` 提供。如果为每个节点提供证书,请将所有证书放入一个 Secret(包括 `ca.crt`),每个节点都有 `<hostname>.key` 和 `<hostname>.crt`。主机名定义为 `<cluster-name>-<nodepool-component>-<index>`(例如,`my-first-cluster-masters-0`)。 + +如果自己提供证书,还必须在 `nodesDn` 中提供证书专有名称(DN)列表。可以使用通配符(例如,`"CN=my-first-cluster-*,OU=my-org"`)。 + +### 节点 HTTP REST API + +每个 OpenSearch 集群节点使用 HTTPS(默认端口 9200)公开 REST API。 + +要配置 HTTP API 安全性,`OpenSearchCluster` 自定义资源中可用以下字段: + +```yaml +# ... +spec: + security: + tls: # 与 TLS 配置相关的所有内容 + http: # HTTP 端点的配置 + enabled: true # 为 HTTP 启用 TLS(默认:如果 http 配置存在则为 true,false 表示禁用) + generate: true # 让操作器生成并签署证书 + customFQDN: "opensearch.example.com" # 可选:证书的自定义 FQDN + # 生成的证书有效期(默认:8760h = 1 年) + duration: "8760h" + secret: + name: # 包含提供的证书的 Secret 名称 + caSecret: + name: # 包含操作器应使用的 CA 的 Secret 名称 +# ... +``` + +可以让操作器生成并签署证书,或提供自己的证书。节点传输证书和节点 HTTP REST API 证书之间唯一的区别是 HTTP REST API 不支持每个节点的证书。否则,两者的工作方式相同。 + +::: info NOTE +`enabled` 字段控制是否为 HTTP 端点启用 TLS。如果 `enabled` 设置为 `false`,集群使用 HTTP 而不是 HTTPS。如果 `enabled` 为 `nil`(未设置),当 HTTP 配置存在时,默认启用 TLS。要显式禁用 TLS,请设置 `enabled: false`。 +::: + +使用生成的证书时,可以选择指定 `customFQDN` 字段,以在证书的主题备用名称(SAN)中包含自定义域以及默认集群 DNS 名称。 + +如果提供自己的证书,请将以下名称添加为 SAN:`<cluster-name>`、`<cluster-name>.<namespace>`、`<cluster-name>.<namespace>.svc`、`<cluster-name>.<namespace>.svc.cluster.local`。 + +不建议直接在 Kubernetes 集群外部公开节点 HTTP 端口。相反,请配置 ingress。然后 ingress 可以提供来自认可 CA(例如 Let's Encrypt)的证书,并隐藏内部使用的自签名证书。在此配置中,在内部为节点提供正确签名的证书。 + +如果提供自己的节点证书,还必须提供操作器可用于管理集群的管理员证书: + +```yaml +spec: + security: + config: + adminSecret: + name: my-first-cluster-admin-cert # Secret 必须有键 tls.crt 和 tls.key +``` + +确保证书的 DN 在 `adminDn` 字段中设置。 + +## 添加插件 + +可以使用[插件](/install-and-configure/plugins#available-plugins)扩展 OpenSearch 功能。常用的插件包括用于外部备份的快照仓库插件(例如,到 Amazon S3 或 Microsoft Azure Blob Storage)。操作器支持在设置期间自动安装插件。 + +要为 OpenSearch 安装插件,请将其添加到 `general.pluginsList`: + +```yaml +general: + version: 3.0.0 + httpPort: 9200 + vendor: opensearch + serviceName: my-cluster + pluginsList: + [ + "repository-s3", + "https://github.com/opensearch-project/opensearch-prometheus-exporter/releases/download/3.0.0.0/prometheus-exporter-3.0.0.0.zip", + ] +``` + +要为 OpenSearch Dashboards 安装插件,请将其添加到 `dashboards.pluginsList`: + +```yaml +dashboards: + enable: true + version: 3.0.0 + pluginsList: + - sample-plugin-name +``` + +要为引导 Pod 安装插件,请将其添加到 `bootstrap.pluginsList`: + +```yaml +bootstrap: + pluginsList: ["repository-s3"] +``` + +请注意以下注意事项: + +- [捆绑插件](/install-and-configure/plugins#bundled-plugins)会自动安装,无需添加到列表中。 +- 可以提供插件名称或插件 ZIP 文件的完整 URL。您提供的项目会传递给 `bin/opensearch-plugin install <plugin-name>` 命令。 +- 更新已安装集群的插件列表会触发所有 OpenSearch 节点的滚动重启。 +- 如果插件需要额外的配置,请在 `additionalConfig`(参见[配置 opensearch.yml](#配置-opensearchyml))中提供,或作为 OpenSearch 密钥库中的 Secret(参见[向密钥库添加 Secret](#向密钥库添加-secret))。 + +## 向密钥库添加 Secret + +某些 OpenSearch 功能(例如,快照仓库插件)需要敏感配置。OpenSearch 使用 OpenSearch 密钥库处理此问题。可以使用 Kubernetes Secret 填充此密钥库。 + +在 `general.keystore` 部分下添加 Secret: + +```yaml +general: + # ... + keystore: + - secret: + name: credentials + - secret: + name: some-other-secret +``` + +使用此配置,Secret 的所有键都成为密钥库中的键。 + +如果只想从 Secret 加载某些键或重命名现有键,可以将键映射添加为映射: + +```yaml +general: + # ... + keystore: + - secret: + name: many-secret-values + keyMappings: + # 仅从 Secret 读取"sensitive-value",保留其名称。 + sensitive-value: sensitive-value + - secret: + name: credentials + keyMappings: + # 将 Secret 中的键 accessKey 重命名为密钥库中的 s3.client.default.access_key + accessKey: s3.client.default.access_key + password: s3.client.default.secret_key +``` + +::: info NOTE +仅从 Secret 加载提供的键。未指定的任何键都会被忽略。 +::: + +要填充引导 Pod 的密钥库,请在 `bootstrap.keystore` 部分下添加 Secret: + +```yaml +bootstrap: + # ... + keystore: + - secret: + name: credentials + - secret: + name: some-other-secret +``` + +## SmartScaler + +SmartScaler 是操作器中内置的机制,可以安全地从集群中移除节点。当从集群中移除节点时,安全清空过程确保在节点脱机之前将其所有数据传输到集群中的其他节点。这可以防止在未先将节点的数据传输到其他节点的情况下关闭或断开节点连接时可能发生的任何数据丢失或损坏。 + +在安全清空过程中,要移除的节点被标记为"清空中",这意味着它不再接收新请求。相反,它只处理未完成的请求,直到其工作负载完成。一旦处理完所有请求,节点就开始将其数据传输到集群中的其他节点。安全清空过程继续进行,直到传输所有数据并且节点不再是集群的一部分。只有在那之后,操作器才会关闭节点。 + +## 设置 Java 堆大小 + +要配置分配给 OpenSearch 节点的内存量,请使用 `jvm` 字段设置堆大小。此操作没有停机时间,集群保持运行。 + +::: info NOTE +将堆大小设置为内存请求的一半。 +::: + +```yaml +spec: + nodePools: + - component: nodes + replicas: 3 + diskSize: "10Gi" + jvm: -Xmx1024M -Xms1024M + resources: + requests: + memory: "2Gi" + cpu: "500m" + limits: + memory: "2Gi" + cpu: "500m" + roles: + - "data" +``` + +如果未提供 `jvm`,Java 堆大小设置为 `resources.requests.memory` 的一半,这是数据节点的推荐值。 + +如果未提供 `jvm` 且 `resources.requests.memory` 不存在,则该值为 `-Xmx512M -Xms512M`。 + +## 配置 `vm.max_map_count` + +OpenSearch 要求 Linux 内核 `vm.max_map_count` 选项[至少设置为 262144](/install-and-configure/install-opensearch/#important-settings)。操作器默认使用每个 OpenSearch Pod 的初始化容器将此选项设置为 `262144`。如果已使用 `sysctl` 在 Kubernetes 主机上设置了此选项,并且不希望操作器更改它,请通过在集群 `spec` 中添加以下选项来禁用它: + +```yaml +spec: + general: + setVMMaxMapCount: false +``` + +默认情况下,初始化容器使用 `busybox` 镜像。要更改此设置(例如,使用私有注册表中的镜像),请参阅[自定义初始化帮助器](/install-and-configure/install-opensearch/operator/operator-kubernetes-custom#自定义初始化帮助器)。 + +## 配置快照仓库 + +可以使用操作器为 OpenSearch 集群配置快照仓库。`general.snapshotRepositories` 字段支持多个快照仓库。配置快照仓库后,用户可以在 OpenSearch Dashboards 中创建自定义 ISM 策略来备份索引。 + +```yaml +spec: + general: + snapshotRepositories: + - name: my_s3_repository_1 + type: s3 + settings: + bucket: opensearch-s3-snapshot + region: us-east-1 + base_path: os-snapshot + - name: my_s3_repository_3 + type: s3 + settings: + bucket: opensearch-s3-snapshot + region: us-east-1 + base_path: os-snapshot_1 +``` + +### 配置快照仓库的前提条件 + +在为集群配置 `snapshotRepositories` 之前,请确保满足以下先决条件: + +1. 安装了适当的云提供商原生插件。例如: + + ```yaml + spec: + general: + pluginsList: ["repository-s3"] + ``` + +2. 预先创建了后端云所需的角色/权限。以下示例显示为 Kubernetes 节点添加了 Amazon Web Services(AWS)身份和访问管理(IAM)角色,以便可以将快照发布到 `opensearch-s3-snapshot` S3 存储桶: + + ```json + { + "Statement": [ + { + "Action": [ + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:ListBucketMultipartUploads", + "s3:ListBucketVersions" + ], + "Effect": "Allow", + "Resource": ["arn:aws:s3:::opensearch-s3-snapshot"] + }, + { + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:AbortMultipartUpload", + "s3:ListMultipartUploadParts" + ], + "Effect": "Allow", + "Resource": ["arn:aws:s3:::opensearch-s3-snapshot/*"] + } + ], + "Version": "2012-10-17" + } + ``` diff --git a/i18n/zh/install-and-configure/install-opensearch/operator/operator-security.md b/i18n/zh/install-and-configure/install-opensearch/operator/operator-security.md new file mode 100644 index 00000000..674bcb24 --- /dev/null +++ b/i18n/zh/install-and-configure/install-opensearch/operator/operator-security.md @@ -0,0 +1,287 @@ +--- +title: 用户和角色管理 +--- + +# 用户和角色管理 + +用户和角色管理对于使用 OpenSearch Security 插件控制对 OpenSearch 集群的访问至关重要。默认情况下,操作器使用包含默认用户的演示安全配置。对于生产安装,请用自己的配置替换它。 + +可以通过两种方式配置安全性: + +- 定义自己的安全配置 +- 使用 Kubernetes 资源管理用户和角色 + +::: info NOTE +不支持两种方法的组合。开始使用 CRD 后,就无法提供自己的安全配置,因为它们会相互覆盖。 +::: + +## 定义自己的安全配置 + +可以提供包含自定义用户和角色的自己的[安全配置](/security/configuration/yaml)。提供包含所有必需安全配置 YAML 文件的 Secret。 + +使用 `OpenSearchCluster` 自定义资源中的以下字段配置安全性: + +```yaml +# ... +spec: + security: + config: # 与安全配置相关的所有内容 + securityConfigSecret: + name: # 包含安全配置文件的 Secret 名称 + adminSecret: + name: # 包含管理员客户端证书的 Secret 名称 + adminCredentialsSecret: + name: # 包含管理员访问的用户名/密码的 Secret 名称 +# ... +``` + +将包含安全配置 YAML 文件的 Secret 名称作为 `securityConfigSecret.name` 提供。此 Secret 充当您管理的权威配置。 + +操作器创建自己的运行时 Secret,名为 `<cluster-name>-security-config-generated`,并将您的文件复制到其中。如果未提供 Secret,操作器使用捆绑的默认值。操作器在将配置应用于集群之前,会自动更新 admin 和 OpenSearch Dashboards(`kibanaserver`)用户的密码哈希。 + +::: warning IMPORTANT +您不再需要在安全配置 Secret 中为 `admin` 或 `kibanaserver` 用户提供密码哈希。操作器会自动从凭据 Secret 生成密码哈希,并覆盖您在安全配置 Secret 中为这些用户提供的任何哈希值。这意味着您只需要在一个地方(凭据 Secret)管理密码,而不是在凭据 Secret 和安全配置 Secret 中都管理。 +::: + +::: info NOTE +OpenSearch 要求在首次创建集群时应用所有文件。对于您在安全配置 Secret 中未提供的文件,操作器使用 Security 插件中提供的默认文件。 +::: + +要避免使用默认文件,请为每个文件至少提供最小配置: + +```yaml +tenants.yml: |- + _meta: + type: "tenants" + config_version: 2 +``` + +这些最小配置文件稍后可以从 Secret 中删除,这样在修改其他配置文件时就不会覆盖使用 CRD 或 REST API 创建的资源。 + +可以将 Secret 作为 `adminCredentialsSecret.name` 提供,其中包含操作器用于与 OpenSearch 通信的用户的 `username` 和 `password` 字段。操作器使用此用户检索集群状态、执行健康检查以及在集群扩展操作期间协调节点清空。 + +如果省略此字段,操作器会自动创建 `<cluster-name>-admin-password`,使用默认的 `admin` 用户名和随机密码。然后操作器生成密码哈希并将其添加到生成的安全配置中。 + +如果提供自己的 Secret,操作器会从您的 Secret 读取密码,生成哈希,并将其添加到生成的安全配置中,而不会修改您的源 Secret。 + +类似地,对于 OpenSearch Dashboards,如果不提供 `dashboards.opensearchCredentialsSecret`,操作器会自动创建 `<cluster-name>-dashboards-password`,为 `kibanaserver` 用户使用随机密码,并自动生成密码哈希并将其添加到生成的安全配置中。 + +还必须为 HTTP 配置 TLS。可以让操作器生成所有需要的证书,或自己提供。如果使用自己的证书,还必须提供操作器可用于应用安全配置的管理员证书。 + +如果为 HTTP 上的 TLS 提供自己的证书,还必须提供管理员客户端证书(作为带有字段 `ca.crt`、`tls.key` 和 `tls.crt` 的 Kubernetes TLS Secret)作为 `adminSecret.name`。证书的 DN 必须列在 `security.tls.http.adminDn` 下。 + +::: warning IMPORTANT +必须定义 `adminDn`,以便管理员证书不能用作或识别为节点证书。否则,OpenSearch 将拒绝使用管理员证书的任何身份验证请求。 +::: + +要将安全配置应用于 OpenSearch 集群,操作器使用单独的 Kubernetes 作业(名为 `<cluster-name>-securityconfig-update`)。此作业在集群的初始配置期间运行。操作器还会监视包含安全配置的 Secret 是否有任何更改,然后重新运行更新作业以应用新配置。请注意,操作器仅在特定间隔检查更改,因此可能需要一两分钟才能应用更改。如果几分钟后未应用更改,请使用 `kubectl` 检查 `<cluster-name>-securityconfig-update` 作业的 Pod 日志。如果配置中有错误,将在那里报告。 + +## 使用 Kubernetes 资源管理安全配置 + +操作器提供了自定义 Kubernetes 资源,允许将用户、角色、操作组和租户等安全配置资源作为 Kubernetes 对象创建、更新或管理。 + +### OpenSearch 用户 + +可以在 Kubernetes 中使用操作器管理 OpenSearch 用户。操作器不会修改已存在的用户。可以按以下方式创建示例用户: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchUser +metadata: + name: sample-user + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + passwordFrom: + name: sample-user-password + key: password + backendRoles: + - kibanauser +``` + +`OpenSearchUser` 的命名空间必须是部署 OpenSearch 集群本身的命名空间。 + +::: info NOTE +必须在 `default` 命名空间中存在名为 `sample-user-password` 的 Secret,其 `password` 键中包含 Base64 编码的密码。 +::: + +还可以在同一 Secret 中存储多个用户密码。为此,创建一个 Secret,其中每个键等于用户名,值是用户密码。否则,Secret 中的更改不会触发用户协调。 + +### OpenSearch 角色 + +可以在 Kubernetes 中使用操作器管理 OpenSearch 角色。操作器不会修改已存在的角色。可以按以下方式创建示例角色: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchRole +metadata: + name: sample-role + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + clusterPermissions: + - cluster_composite_ops + - cluster_monitor + indexPermissions: + - indexPatterns: + - logs* + allowedActions: + - index + - read +``` + +### 链接 OpenSearch 用户和角色 + +操作器允许使用 OpensearchUserRoleBinding 链接任意数量的用户、后端角色和角色。绑定中的每个用户都被授予每个角色: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchUserRoleBinding +metadata: + name: sample-urb + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + users: + - sample-user + backendRoles: + - sample-backend-role + roles: + - sample-role +``` + +### OpenSearch 操作组 + +可以在 Kubernetes 中使用操作器管理 OpenSearch 操作组。操作器不会修改已存在的操作组。可以按以下方式创建示例操作组: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchActionGroup +metadata: + name: sample-action-group + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + allowedActions: + - indices:admin/aliases/get + - indices:admin/aliases/exists + type: index + description: Sample action group +``` + +### OpenSearch 租户 + +可以在 Kubernetes 中使用操作器管理 OpenSearch 租户。操作器不会修改已存在的租户。可以按以下方式创建示例租户: + +```yaml +apiVersion: opensearch.org/v1 +kind: OpensearchTenant +metadata: + name: sample-tenant + namespace: default +spec: + opensearchCluster: + name: my-first-cluster + description: Sample tenant +``` + +## 自定义管理员用户 + +要创建具有不同于默认管理员用户的集群,请提供自己的管理员凭据 Secret。操作器会自动生成密码哈希并将其添加到安全配置中,因此您不再需要手动生成密码哈希并将其包含在安全配置 Secret 中。 + +首先,创建包含管理员用户配置的 Secret(在此示例中为 `admin-credentials-secret`): + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: admin-credentials-secret +type: Opaque +data: + # admin + username: YWRtaW4= + # admin123 + password: YWRtaW4xMjM= +``` + +::: warning IMPORTANT +> 您不需要在安全配置 Secret 中包含密码哈希。操作器会自动: +> 1. 从您的 `adminCredentialsSecret` 读取密码 +> 2. 生成 `bcrypt` 哈希 +> 3. 覆盖生成的安全配置 Secret(`<cluster-name>-security-config-generated`)中 `admin` 用户的哈希 +::: + +如果提供自己的安全配置 Secret,可以选择性地包含管理员用户定义,但您提供的任何哈希都会被操作器自动覆盖: + +```yaml +internal_users.yml: |- + _meta: + type: "internalusers" + config_version: 2 + admin: + # hash 字段是可选的 - 操作器会自动覆盖它 + reserved: true + backend_roles: + - "admin" + description: "Demo admin user" +``` + +将以下安全配置添加到 `cluster.yaml` 文件中: + +```yaml +security: + config: + adminCredentialsSecret: + name: admin-credentials-secret # 操作器要使用的包含管理员凭据的 Secret + securityConfigSecret: + name: securityconfig-secret # 可选:包含自定义安全配置的 Secret + tls: + transport: + generate: true + http: + generate: true +``` + +::: info NOTE +至少需要 `security.tls` 部分才能在启用安全性的情况下启动集群。为 `transport` 和 `http` 设置 `generate: true` 会指示操作器自动生成所需的 TLS 证书。当未明确指定时,操作器还会自动创建管理员和 OpenSearch Dashboards 凭据 Secret(`<cluster-name>-admin-password` 和 `<cluster-name>-dashboards-password`)。 +::: + +### 更改管理员密码 + +要在创建集群后更改管理员密码,请更新 `admin-credentials-secret` 中的密码。操作器会自动: + +1. 检测密码更改。 +2. 生成新的密码哈希。 +3. 更新生成的安全配置 Secret。 +4. 触发安全配置更新作业以将更改应用于 OpenSearch。 + +您不再需要手动更新安全配置 Secret 中的密码哈希。 + +## 自定义 OpenSearch Dashboards 用户 + +OpenSearch Dashboards 需要一个 OpenSearch 用户(通常是 `kibanaserver`)来连接到集群。 + +如果不提供自定义凭据 Secret,操作器会自动: +1. 创建名为 `<cluster-name>-dashboards-password` 的 Secret,为 `kibanaserver` 用户使用随机密码。 +2. 生成密码哈希并自动将其添加到生成的安全配置 Secret 中。 +3. 配置 OpenSearch Dashboards 使用这些凭据。 + +要使用自定义凭据,请创建包含键 `username` 和 `password` 的 Secret,并使用集群 `spec` 将其提供给操作器: + +```yaml +spec: + dashboards: + opensearchCredentialsSecret: + name: dashboards-credentials # 这是包含 OpenSearch Dashboards 要使用的凭据的 Secret 名称 +``` + +::: warning IMPORTANT +> 与配置管理员用户类似,您不需要在安全配置 Secret 中包含 `kibanaserver` 用户的密码哈希。操作器会自动: +> 1. 从您的 `opensearchCredentialsSecret` 读取密码(或如果未提供则使用生成的随机密码) +> 2. 生成 `bcrypt` 哈希 +> 3. 覆盖生成的安全配置 Secret 中 `kibanaserver` 用户的哈希 +::: diff --git a/i18n/zh/install-and-configure/os-comp.md b/i18n/zh/install-and-configure/os-comp.md new file mode 100644 index 00000000..98f0d829 --- /dev/null +++ b/i18n/zh/install-and-configure/os-comp.md @@ -0,0 +1,31 @@ +--- +title: 兼容的操作系统 +--- + +# 兼容的操作系统 + +OpenSearch 和 OpenSearch Dashboards 与使用 [`systemd`](https://en.wikipedia.org/wiki/Systemd) 的 Red Hat Enterprise Linux (RHEL) 和基于 Debian 的 Linux 发行版兼容,如 Amazon Linux 和 Ubuntu 长期支持 (LTS)。虽然 OpenSearch 和 OpenSearch Dashboards 应该可以在大多数 Linux 发行版上运行,但我们只测试其中的一部分。 + +## 支持的操作系统 + +下表列出了我们为 OpenSearch 和 OpenSearch Dashboards 2.12 测试的操作系统版本。要查看为不同 OpenSearch 版本测试的操作系统,请在文档版本选择器中选择该版本。 + +操作系统 | 版本 +:---------- | :-------- +Rocky Linux | 8 +Alma Linux | 8 +Amazon Linux | 2023 +Ubuntu | 24.04 +Windows Server | 2019 + +## 更改日志 + +下表列出了对操作系统兼容性所做的更改。 + +| 日期 | 问题 | PR | 详细信息 | +|:-----------|:-------|:-------|:--------------------------| +| `2026-09-29` | [`opensearch-build` 问题 5227](https://github.com/opensearch-project/opensearch-build/issues/5227) | [PR 12853](https://github.com/opensearch-project/documentation-website/pull/12853) | 移除 [Amazon Linux 2](https://aws.amazon.com/amazon-linux-2/faqs/) | +| `2025-02-06` | [`opensearch-build` 问题 5270](https://github.com/opensearch-project/opensearch-build/issues/5270) | [PR 9165](https://github.com/opensearch-project/documentation-website/pull/9165) | 移除 [Ubuntu 20.04](https://ubuntu.com/blog/ubuntu-20-04-lts-end-of-life-standard-support-is-coming-to-an-end-heres-how-to-prepare) | +| `2024-07-23` | [`opensearch-build` 问题 4379](https://github.com/opensearch-project/opensearch-build/issues/4379) | [PR 7821](https://github.com/opensearch-project/documentation-website/pull/7821) | 移除 [CentOS7](https://blog.centos.org/2023/04/end-dates-are-coming-for-centos-stream-8-and-centos-linux-7/) | +| `2024-03-08` | [`opensearch-build` 问题 4573](https://github.com/opensearch-project/opensearch-build/issues/4573) | [PR 6637](https://github.com/opensearch-project/documentation-website/pull/6637) | 移除 CentOS8,添加 Almalinux8/Rockylinux8,并移除 Ubuntu 16.04/18.04,因为我们目前只在 20.04 上测试 | +| `2023-06-06` | [`documentation-website` 问题 4217](https://github.com/opensearch-project/documentation-website/issues/4217) | [PR 4218](https://github.com/opensearch-project/documentation-website/pull/4218) | 支持矩阵创建 | diff --git a/i18n/zh/ml-commons-plugin/agentic-memory-retention.md b/i18n/zh/ml-commons-plugin/agentic-memory-retention.md new file mode 100644 index 00000000..f8320ed3 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agentic-memory-retention.md @@ -0,0 +1,236 @@ +--- +title: 代理记忆保留 +--- + +# 代理记忆保留 +<Badge type="tip" text="3.8 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/) 上的讨论。 +::: + +默认情况下,代理记忆会无限期累积,这会增加存储使用量并可能导致代理检索到过时的记忆。要自动删除旧的或过量的记忆,请为 [记忆容器](/ml-commons-plugin/agentic-memory#memory-containers) 定义一个_保留策略_。保留策略为每种记忆类型指定年龄限制、数量限制或两者兼有。后台作业按计划强制执行该策略。它删除超过数量限制的 `sessions`、`long-term` 和 `history` 记忆,或删除超过年龄限制的 `sessions` 和 `long-term` 记忆。相比之下,`working` 记忆不受保留策略约束,当其父会话不再存在时会被删除。要控制 `working` 记忆的保留时间,请为 `sessions` 配置保留策略。 + +您可以通过固定 `sessions` 和 `long-term` 记忆,使其不受保留策略约束。有关更多信息,请参见[固定记忆](#pinning-memories)。 + +## 启用记忆保留 + +保留功能默认禁用。要在整个集群范围内启用它,请配置以下动态集群设置: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.memory.retention_enabled": true + } +} +``` + +## 定义保留策略 + +`retention_policy` 对象在容器的 `configuration` 对象中指定,并将每种记忆类型映射到该类型的保留限制。将 `{memory_type}` 替换为 `sessions`、`long-term` 或 `history`: + +```json +"configuration": { + "retention_policy": { + "{memory_type}": { + "retention_days": 90, + "max_count": 5000 + } + } +} +``` + +每个 `{memory_type}` 对象接受以下可选字段。当两个字段都设置时,如果记忆违反任一规则都会被删除。 + +字段 | 数据类型 | 支持的记忆类型 | 描述 +:--- | :--- | :--- | :--- +`retention_days` | 整数 | `sessions`, `long-term` | 删除超过此天数的记忆,从记忆的 `last_updated_time` 开始计算。 +`max_count` | 整数 | `sessions`, `long-term`, `history` | 最多保留此数量的记忆,优先删除最旧的。会话和长期记忆按 `last_updated_time` 排序;历史记忆按 `created_time` 排序。 + +::: info NOTE +保留规则仅在容器存储该记忆类型时才生效。要存储 `long-term` 和 `history` 记忆,您必须配置 `strategies`;否则,这些类型的保留规则将无效。有关更多信息,请参见[创建的索引](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container#the-created-indexes)。 +::: + +### 配置保留策略 + +要在创建记忆容器时配置策略,请在创建请求中包含 `retention_policy` 字段。以下示例创建一个具有会话跟踪、策略和保留策略的容器,该策略保留最多 5,000 个会话 90 天,并将长期记忆限制为 2,000 个条目: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "my-agent-memory", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "your-embedding-model-id", + "embedding_dimension": 1024, + "llm_id": "your-llm-model-id", + "strategies": [ + { + "type": "SEMANTIC", + "namespace": ["user_id"] + } + ], + "retention_policy": { + "sessions": { + "retention_days": 90, + "max_count": 5000 + }, + "long-term": { + "max_count": 2000 + } + } + } +} +``` + +您还可以随时通过在更新请求中发送 `retention_policy` 对象来为现有容器添加保留策略: + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +{ + "configuration": { + "retention_policy": { + "sessions": { + "retention_days": 90, + "max_count": 5000 + }, + "long-term": { + "max_count": 2000 + } + } + } +} +``` + +::: danger WARNING +策略适用于容器中的所有记忆,包括在您添加策略之前创建的记忆。例如,向持有 10,000 个会话的容器添加 `max_count` 为 100 将删除 9,900 个最近最少更新的会话。要保留特定记忆,请在添加策略之前[固定](#pinning-memories)它们。 +::: + +### 查看保留策略 + +要查看存储的策略,请使用 [获取记忆容器 API](/ml-commons-plugin/api/agentic-memory-apis/get-memory-container) 检索容器: + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id} +``` + +### 更新保留策略 + +更新 `retention_policy` 会将您的更改合并到现有策略中,而不是替换它。您省略的记忆类型和字段将保持不变。 + +要删除单个字段,将其设置为 `null`。例如,以下请求通过从 `sessions` 中删除 `retention_days` 来更新[配置保留策略](#configuring-a-retention-policy)示例中的策略,同时保持 5,000 的 `max_count`: + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +{ + "configuration": { + "retention_policy": { + "sessions": { + "retention_days": null + } + } + } +} +``` + +### 禁用容器的保留功能 + +要禁用整个容器的保留功能,将 `retention_policy` 设置为 `null`: + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +{ + "configuration": { + "retention_policy": null + } +} +``` + +将 `retention_policy` 设置为 `null` 与省略它不同。省略策略会使容器符合[集群级别默认设置](#default-settings)的条件;将其设置为 `null` 会使容器免受这些默认设置的影响。即使在集群范围内禁用保留功能时,您也可以发送此请求。 + +## 固定记忆 + +固定记忆可使其在容器的[保留策略](#defining-a-retention-policy)下免于删除。您可以固定 `sessions` 和 `long-term` 记忆。固定 `sessions` 会保留其所有 `working` 记忆。由于固定的记忆永远不会被删除,它们可能会随时间累积。要减小容器大小,请取消固定不再需要保护的 `sessions`。 + +固定可保护记忆免于删除,但不会改变其年龄。记忆的年龄从其 `last_updated_time` 开始计算,只有当其内容发生变化时才会推进,例如当 `working` 记忆添加到会话或 `long-term` 记忆更新时。固定不会更新此时间戳,因此如果您以后取消固定记忆,其年龄仍然反映其上次内容更改,并且可能立即符合删除条件。 + +使用以下请求字段固定记忆。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`pinned` | 布尔值 | 设置为 `true` 以固定记忆或设置为 `false` 以取消固定。对 `sessions` 和 `long-term` 记忆有效。 + +以下示例固定记忆(将 `memory_type` 指定为 `sessions` 或 `long-term`): + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id}/memories/{memory_type}/{memory_id} +{ + "pinned": true +} +``` + +## 保留作业 + +后台作业按[计划](#retention-job-schedule)(默认每 24 小时)强制执行保留策略。由于强制执行是按计划而不是连续的,因此已超过其年龄或数量限制的记忆仍会在搜索结果中返回,直到作业下次运行并删除它。 + +记忆将根据以下限制进行评估: + +- `retention_days` 从记忆的 `last_updated_time` 开始计算。向会话添加 `working` 记忆会推进会话的时间戳,因此活动对话会被保留。固定记忆不会推进它。 +- `max_count` 适用于任何年龄。如果容器持有的某类型非固定记忆超过 `max_count`,则会删除最旧的记忆,直到剩余 `max_count` 个,即使它们比 `retention_days` 新。 +- 当记忆类型设置两个限制时,如果记忆超过任一限制,则会被删除。 + +在强制执行 `max_count` 时,每次运行最多删除容器中每种记忆类型的 50,000 个记忆。较大的积压会在连续的运行中减少,因此远远超过其 `max_count` 的容器可能需要几次运行才能达到限制。基于 `retention_days` 的删除不受限制。 + +当作业驱逐 `sessions` 记忆时,它首先删除其 `working` 记忆,以便不会创建孤儿。手动删除 `sessions` 记忆不会删除其 `working` 记忆,从而使它们成为孤儿。在强制执行策略后,作业会删除 `created_time` 早于 `orphan_ttl_days` 的孤儿 `working` 记忆。作业第一次检查容器是否有孤儿时,它会记录基线并不删除任何内容,因此该容器中的孤儿删除在基线之后 `orphan_ttl_days` 开始。 + +孤儿清理仅针对具有保留策略且创建时 `disable_session` 设置为 `false`(默认值)的容器运行。在没有保留策略的容器中,孤儿 `working` 记忆将无限期保留。 + +创建时 `disable_session` 设置为 `true` 的容器不存储 `sessions` 记忆,因此前述两种机制都不适用于它。其 `working` 记忆仅通过 `plugins.ml_commons.memory.working_memory_ttl_days` 设置删除,该设置默认禁用。在您将其设置为正值之前,这些容器会无限期保留 `working` 记忆。有关更多信息,请参见[记忆保留设置](#memory-retention-settings)。 + +当多租户处于活动状态时,作业将被禁用。在这种情况下,即使对于具有策略的容器,也不会强制执行保留。 + +## 暂停保留 + +要在保留配置的保留策略的同时暂停保留,请将 `plugins.ml_commons.memory.retention_enabled` 设置为 `false`。将其设置回 `true` 将恢复强制执行。 + +## 记忆保留设置 + +您可以使用以下动态集群设置自定义保留行为: + +- `plugins.ml_commons.memory.retention_enabled`(布尔值):在整个集群范围内启用保留。当此设置为 `false` 时,保留作业不会删除任何内容,并且容器 API 会拒绝 `retention_policy`。默认值为 `false`。 + +- `plugins.ml_commons.memory.retention_job_throttle_seconds`(整数):指定保留作业在处理删除了记忆的容器后,在继续处理下一个容器之前暂停多长时间。增加此值以减少集群负载。有效值在 `[1, 60]` 范围内。默认值为 `5`。 + +- `plugins.ml_commons.memory.working_memory_ttl_days`(整数):在创建 `working` 记忆后此天数删除它。仅适用于创建时 `disable_session` 设置为 `true` 的容器。由于这些容器不存储 `sessions` 记忆,因此此设置是删除其 `working` 记忆的唯一机制。有效值在 `[1, 365]` 范围内。默认值为 `-1`(禁用)。 + +- `plugins.ml_commons.memory.orphan_ttl_days`(整数):删除其父 `sessions` 记忆不再存在的 `working` 记忆,从 `working` 记忆的 `created_time` 开始计算。有关更多信息,请参见[保留作业](#retention-job)。有效值在 `[1, 365]` 范围内。默认值为 `7`。 + +### 默认设置 + +默认设置适用于未设置自己保留策略的任何容器。它们仅在[为集群启用保留](#enabling-memory-retention)后生效;在此之前,它们会被存储但不起作用。一旦启用保留,下一个计划的作业将把它们应用于没有策略的容器,并删除超过默认值的任何记忆,包括在您设置默认值之前创建的记忆。 + +默认值仅应用于容器一次;稍后更改这些设置不会更新已应用默认值的容器。要使容器免受默认值的影响,请将其 `retention_policy` 设置为 `null`。要在应用默认值后更新容器的策略,请使用[更新记忆容器 API](/ml-commons-plugin/api/agentic-memory-apis/update-memory-container)。 + +以下每个动态设置提供[保留策略](#defining-a-retention-policy)一个字段的默认值。默认值 `-1` 表示该字段不应用默认值: + +- `plugins.ml_commons.memory.default_session_retention_days`(整数):设置 `sessions` 记忆的默认 `retention_days`。有效值在 `[1, 3650]` 范围内。默认值为 `-1`。 + +- `plugins.ml_commons.memory.default_session_max_count`(整数):设置 `sessions` 记忆的默认 `max_count`。有效值在 `[1, 1000000]` 范围内。默认值为 `-1`。 + +- `plugins.ml_commons.memory.default_long_term_max_count`(整数):设置 `long-term` 记忆的默认 `max_count`。有效值在 `[1, 1000000]` 范围内。默认值为 `-1`。 + +- `plugins.ml_commons.memory.default_history_max_count`(整数):设置 `history` 记忆的默认 `max_count`。有效值在 `[1, 10000000]` 范围内。默认值为 `-1`。 + +### 保留作业计划 + +<!-- TODO: When this feature goes GA, revisit the retention_job_interval_hours behavior (currently static-like; dynamic interval updates are planned for a future release). --> + +以下设置控制保留作业计划。在启动集群之前在 `opensearch.yml` 中设置它。作业在启动时首次计划时读取一次;通过集群设置 API 在运行的集群上更新它不会生效: + +- `plugins.ml_commons.memory.retention_job_interval_hours`(整数):指定保留作业运行的频率(以小时为单位)。有效值在 `[1, 168]` 范围内。默认值为 `24`。 + +## 下一步 + +- 有关记忆容器和代理记忆的更多信息,请参见[代理记忆](/ml-commons-plugin/agentic-memory)。 +- 有关容器创建 API 参考,请参见[创建记忆容器 API](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container)。 diff --git a/i18n/zh/ml-commons-plugin/agentic-memory.md b/i18n/zh/ml-commons-plugin/agentic-memory.md new file mode 100644 index 00000000..29696b48 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agentic-memory.md @@ -0,0 +1,260 @@ +--- +title: 代理记忆 +--- + +# 代理记忆 +<Badge type="tip" text="3.3 版本引入" /> + +代理记忆使 AI 代理能够在对话中学习、记忆和推理结构化信息。与只存储消息历史的简单对话记忆不同,代理记忆提供持久的智能存储,帮助代理维护上下文、学习用户偏好,并随时间改进其响应。 + +使用代理记忆,您可以构建能够执行以下操作的 AI 代理: + +- 在多个对话会话中记住用户偏好 +- 从过去的交互中学习以提供更个性化的响应 +- 维护超出简单消息历史的对话上下文 +- 存储和检索从对话中提取的事实知识 +- 跟踪代理执行轨迹以进行调试和分析 +- 在不同用户、会话或代理实例之间组织信息 + +代理记忆旨在与 OpenSearch 的内部[代理](/ml-commons-plugin/agents-tools/agents/)和外部代理框架(如 LangChain 和 LangGraph)集成。 + +::: danger WARNING +> **重要**: +> +> OpenSearch 中的代理记忆功能作为一个框架提供,使您能够为 AI 代理构建和管理记忆。作为记忆容器的管理员或所有者,您负责实现的配置、管理和安全性。 +> 您负责以下内容: +> - 数据访问控制:为存储在记忆容器中的对话数据实施和强制执行所有必要的数据访问控制。这包括但不限于配置适当的索引级别权限、文档级别安全性(DLS)或其他限制访问的机制。当 use_system_index 选项设置为 false 时,这项责任尤其关键,因为数据将存储在需要明确权限管理的标准索引中。 +> - 自定义系统提示管理:如果您选择使用自定义系统提示而不是默认提示,您需要负责该提示的内容、管理和行为。OpenSearch 不对用户定义的系统提示产生的输出或交互负责。 +> 未能正确配置和保护您的代理记忆实现可能导致未经授权的数据访问、数据泄露或意外的代理行为。 +::: + +## 记忆容器 + +代理记忆被组织成_记忆容器_,这些容器保存特定用例(例如聊天机器人、研究助手或客户服务代理)的所有记忆类型。 + +每个容器可以配置以下组件: + +- 文本嵌入模型:用于语义搜索功能。 +- 大型语言模型(LLM):用于推理和知识提取。 +- [记忆处理策略](#memory-processing-strategies):用于定义如何处理或提取记忆。 +- [命名空间](#namespaces):用于按上下文、用户、代理或会话分区和隔离记忆。 + +例如,要创建具有两个策略的记忆容器,请发送以下请求: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "customer-service-agent", + "description": "Memory container for customer service agent", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "your-embedding-model-id", + "embedding_dimension": 1024, + "llm_id": "your-llm-model-id", + "strategies": [ + { + "type": "USER_PREFERENCE", + "namespace": ["user_id"] + }, + { + "type": "SUMMARY", + "namespace": ["user_id", "session_id"] + } + ] + } +} +``` + +## 记忆类型 + +每个记忆容器可以存储四种不同类型的记忆: + +- `sessions` -- 管理对话会话及其元数据。每个会话代表用户和代理之间的独特交互上下文,包含特定于会话的信息,例如开始时间、参与者和会话状态。 + +- `working` -- 存储代理在持续交互期间使用的活动对话数据和结构化信息。这包括最近的消息、当前上下文、代理状态、执行轨迹以及立即处理所需的临时数据。 + +- `long-term` -- 包含随时间从对话中提取的处理后的知识和事实。当启用推理时,LLM 从工作记忆中提取关键见解、用户偏好和重要信息,并将它们存储为持久知识。 + +- `history` -- 维护记忆容器中所有记忆操作(添加、更新、删除)的审计跟踪。这提供了记忆如何随时间演变和变化的全面日志。 + +## 有效负载类型 + +添加记忆时,您可以指定不同的有效负载类型: + +- `conversational` -- 存储用户和助手之间的对话消息。 +- `data` -- 存储结构化的非对话数据,例如代理状态、检查点或参考信息。 + +要添加带有推理的对话记忆,请发送以下请求: + +```json +POST /_plugins/_ml/memory_containers/{container_id}/memories +{ + "messages": [ + { + "role": "user", + "content": [ + { + "text": "I prefer email notifications over SMS", + "type": "text" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "text": "I've noted your preference for email notifications", + "type": "text" + } + ] + } + ], + "namespace": { + "user_id": "user123", + "session_id": "session456" + }, + "payload_type": "conversational", + "infer": true +} +``` + +要添加代理状态数据,请发送以下请求: + +```json +POST /_plugins/_ml/memory_containers/{container_id}/memories +{ + "structured_data": { + "agent_state": "researching", + "current_task": "analyze customer feedback", + "progress": 0.75 + }, + "namespace": { + "agent_id": "research-agent-1", + "session_id": "session456" + }, + "payload_type": "data", + "infer": false +} +``` + +## 推理模式 + +您可以使用 `infer` 参数控制 OpenSearch 如何处理记忆: + +- `false`(默认)-- 在 `working` 记忆中存储原始消息和数据,不进行 LLM 处理。 +- `true` -- 使用配置的 LLM 从内容中提取关键信息和知识。 + +## 记忆处理策略 + +记忆容器可以使用以下_策略_来自动处理和组织记忆: + +- `SEMANTIC` -- 按含义和内容相似性对相关记忆进行分组。 +- `USER_PREFERENCE` -- 从对话中提取并存储用户偏好。 +- `SUMMARY` -- 创建对话内容的浓缩摘要。 + +策略是可选的;您可以创建不带策略的容器以满足简单的存储需求。 + +## 命名空间 + +_命名空间_通过使用诸如 `user_id`、`session_id` 或 `agent_id` 之类的标识符对记忆进行分组,从而在容器中组织记忆。这允许您为不同的用户或对话会话分隔记忆。 + +要按命名空间搜索记忆,请发送以下请求: + +```json +GET /_plugins/_ml/memory_containers/{container_id}/memories/long-term/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "namespace.user_id": "user123" + } + } + ] + } + } +} +``` + +## 示例用例 + +以下示例演示了如何使用代理记忆。 + +### 个性化聊天机器人 + +创建一个随时间学习用户偏好的记忆容器: + +- 在启用推理的情况下将对话存储在 `working` 记忆中。 +- 使用 `USER_PREFERENCE` 策略将用户偏好提取到 `long-term` 记忆中。 +- 使用命名空间分隔不同用户的记忆。 + +### 研究助手代理 + +构建一个从研究会话中积累知识的代理: + +- 在 `working` 记忆中存储研究查询和结果。 +- 使用 `SEMANTIC` 策略对相关研究主题进行分组。 +- 维护 `history` 以跟踪知识随时间的演变。 + +### 客户服务代理 + +开发一个记住客户交互的代理: + +- 通过推理存储客户对话以提取关键问题。 +- 使用 `SUMMARY` 策略创建简洁的交互摘要。 +- 使用命名空间按客户 ID 组织。 + +## 入门 + +要在您的代理中实现代理记忆: + +1. **[创建记忆容器](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container)**,并配置适当的模型和策略。 +2. **[添加记忆](/ml-commons-plugin/api/agentic-memory-apis/add-memory)**在代理交互期间。 +3. **[搜索和检索](/ml-commons-plugin/api/agentic-memory-apis/search-memory)**相关记忆以为代理响应提供信息。 +4. **[更新记忆](/ml-commons-plugin/api/agentic-memory-apis/update-memory)**随着对话的发展。 + +有关详细的 API 文档,请参见[代理记忆 API](/ml-commons-plugin/api/agentic-memory-apis/)。 + +## 检查记忆数据(OpenSearch 代理) + +在执行配置了代理记忆的 OpenSearch 代理后,您可以使用[获取记忆 API](/ml-commons-plugin/api/agentic-memory-apis/get-memory) 或[搜索记忆 API](/ml-commons-plugin/api/agentic-memory-apis/search-memory) 检查会话和跟踪数据: + +1. 通过 `memory_id` 检索会话: + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/sessions/{memory_id} +``` + +2. 通过交互 ID(代理执行输出中的 `parent_interaction_id`)检索消息: + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/working/{interaction_id} +``` + +3. 使用 `namespace.session_id = <memory_id>` 获取会话的完整工作记忆跟踪数据: + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/working/_search +{ + "query": { + "match": { + "namespace.session_id": "<memory_id>" + } + }, + "sort": [ + { + "created_time": { + "order": "asc" + } + } + ] +} +``` + +## 下一步 + +- 了解[代理记忆保留](/ml-commons-plugin/agentic-memory-retention)。 +- 探索[记忆容器配置](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container)选项。 +- 查看完整的[代理记忆 API 参考](/ml-commons-plugin/api/agentic-memory-apis/)。 +- 有关使用代理记忆作为使用 Strands Agents 构建的代理的长期记忆的教程,请参见[将代理记忆与 Strands Agents 结合使用](/tutorials/gen-ai/agents/agentic-memory-strands/)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/agents/ag-ui.md b/i18n/zh/ml-commons-plugin/agents-tools/agents/ag-ui.md new file mode 100644 index 00000000..147fc21b --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/agents/ag-ui.md @@ -0,0 +1,338 @@ +--- +title: AG-UI 代理 +--- + +# AG-UI 代理 +<Badge type="tip" text="3.5 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进度的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/) 上的讨论。 +::: + +Agent-User Interaction (AG-UI) 代理遵循 [AG-UI 协议](https://docs.ag-ui.com/introduction),用于将 AI 代理与前端应用程序集成。此实现通过标准化的流式交互和复杂的工具执行,将实时 AI 代理功能直接带入用户界面。 + +类似于[对话代理](/ml-commons-plugin/agents-tools/agents/conversational),AG-UI 代理配置有大型语言模型 (LLM) 和可选工具。在处理用户输入时,代理使用 LLM 推理请求,同时考虑对话历史和可用的前端上下文。然后代理确定要使用的工具并执行它们以提供适当的响应。 + +AG-UI 代理可以使用两种类型的工具: +- **后端工具**:向代理注册(如 `ListIndexTool` 或 `SearchIndexTool`),并查询 OpenSearch 数据和执行服务器端操作。 +- **前端工具**:在每个请求中提供,允许代理与 UI 交互,例如刷新仪表板、应用过滤器或在页面之间导航。 + +## 前提条件 + +在使用 AG-UI 代理之前,您必须通过更新集群设置来启用该功能。需要 `ag_ui_enabled` 和 `stream_enabled` 设置,而 `mcp_connector_enabled`(用于连接到 Model Context Protocol [MCP] 服务器)和 `unified_agent_api_enabled` 是可选的,但建议启用: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.ag_ui_enabled": true, + "plugins.ml_commons.stream_enabled": true, + "plugins.ml_commons.mcp_connector_enabled": true, + "plugins.ml_commons.unified_agent_api_enabled": true + } +} +``` + +## 创建 AG-UI 代理 + +AG-UI 代理使用统一注册方法,将代理创建简化为单个 API 调用。要注册 AG-UI 代理,请将 `type` 字段设置为 `AG_UI` 并使用 Unified Agent API 配置您的模型。 + +有关完整的注册说明、字段定义以及所有支持的模型提供程序(Amazon Bedrock、Google Gemini、OpenAI)的示例,请参阅[统一注册方法](/ml-commons-plugin/api/agent-apis/register-agent#unified-agent-registration)。 + +<!-- vale off --> +### 示例请求:Amazon Bedrock Converse +<!-- vale on --> + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<AWS ACCESS KEY>", + "secret_key": "<AWS SECRET KEY>", + "session_token": "<AWS SESSION TOKEN>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 5, + "mcp_connectors": [{ + "mcp_connector_id": "<MCP CONNECTOR ID>" + }] + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` + +<!-- vale off --> +### 示例请求:OpenAI Chat Completion +<!-- vale on --> + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "openai/v1/chat/completions", + "credential": { + "openai_api_key": "<OPENAI API KEY>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 50, + "mcp_connectors": [{ + "mcp_connector_id": "<MCP CONNECTOR ID>" + }] + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` + +## 执行代理流 + +AG-UI 代理使用专为前端应用程序设计的专用执行协议。与使用 `input` 字段的常规代理执行([Execute Agent API](/ml-commons-plugin/api/agent-apis/execute-agent))不同,AG-UI 代理使用 AG-UI 协议格式,包括前端上下文、工具和流式响应。 + +### AG-UI 协议格式 + +AG-UI 执行遵循 [AG-UI 协议](https://docs.ag-ui.com/introduction)规范,提供前端应用程序和 AI 代理之间的结构化通信。该协议包括对话线程、前端工具集成和实时流式响应。 + +有关输入格式规范的更多信息,请参阅 AG-UI 文档中的 [RunAgentInput](https://docs.ag-ui.com/sdk/js/core/types#runagentinput)。 + +### 请求字段 + +下表列出了请求字段。 + +| 字段 | 数据类型 | 必需/可选 | 说明 | +| :--- | :--- | :--- | :--- | +| `threadId` | String | 必需 | 对话线程的唯一标识符,由前端生成。用于在多个请求之间维护对话连续性并启用对话记忆。 | +| `runId` | String | 必需 | 此线程内此特定执行的唯一标识符,由前端生成。每个新请求应该有一个新的 `runId`。 | +| `state` | Object | 必需 | 代理会话的当前内部状态。可以存储工作流状态、用户偏好或在同一运行中跨工具调用持久化的会话特定数据。 | +| `messages` | Array | 必需 | 对话消息数组,包括用户输入和之前的助手响应。每条消息都有一个 `id`、`role`(user/assistant)和 `content`。 | +| `tools` | Array | 必需 | 代理可以调用以与 UI 交互的前端特定工具数组。每个工具包括 `name`、`description` 和 `parameters` 模式,定义代理如何调用 UI 操作。 | +| `context` | Array | 必需 | 向代理提供当前应用程序状态的上下文对象数组。包括活动仪表板、应用的过滤器、时间范围等信息,或帮助代理理解用户当前情况的任何相关 UI 上下文。 | +| `forwardedProps` | Object | 必需 | 从前端应用程序转发的其他属性,例如用户身份验证详细信息、权限、应用程序配置或代理操作所需的其他元数据。 | + +#### 示例请求 + +以下示例展示了如何使用 AG-UI 协议格式执行 AG-UI 代理,包括前端工具、对话上下文和应用程序状态: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "threadId": "thread-xxxxx", + "runId": "run-xxxxx", + "messages": [ + { + "id": "msg-xxxxx", + "role": "user", + "content": "hello" + } + ], + "tools": [ + { + "name": "frontend_tool_example", + "description": "This is a frontend tool", + "parameters": { + ... + } + } + ], + "context": [ + { + "description": "Page context example", + "value": "{\"appId\":\"example\",\"timeRange\":{\"from\":\"now-15m\",\"to\":\"now\"},\"query\":{\"query\":\"example\",\"language\":\"PPL\"}}" + } + ], + "state": {}, + "forwardedProps": {} +} +``` + +### 示例响应 + +AG-UI 代理返回服务器发送事件 (SSE),允许前端在代理处理请求时提供实时反馈: + +```json +data: {"type":"RUN_STARTED","timestamp":1234567890,"threadId":"thread-xxxxx","runId":"run-xxxxx"} + +data: {"type":"TEXT_MESSAGE_START","timestamp":1234567890,"messageId":"msg-xxxxx","role":"assistant"} + +data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1234567890,"messageId":"msg-xxxxx","delta":"Response text here"} + +data: {"type":"TEXT_MESSAGE_END","timestamp":1234567890,"messageId":"msg-xxxxx"} + +data: {"type":"TOOL_CALL_START","timestamp":1234567890,"toolCallId":"tool-xxxxx","toolCallName":"frontend_tool_example"} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1234567890,"toolCallId":"tool-xxxxx","delta":"{\"param\":\"value\"}"} + +data: {"type":"TOOL_CALL_END","timestamp":1234567890,"toolCallId":"tool-xxxxx"} + +data: {"type":"RUN_FINISHED","timestamp":1234567890,"threadId":"thread-xxxxx","runId":"run-xxxxx"} +``` + +### 响应字段 + +每个 SSE 包含以下字段。 + +| 字段 | 数据类型 | 说明 | +| :--- | :--- | :--- | +| `type` | String | 事件类型。 | +| `timestamp` | Long | Unix 时间戳,以毫秒为单位,表示事件生成的时间。 | +| `threadId` | String | 请求中的对话线程 ID。 | +| `runId` | String | 请求中的运行 ID。 | +| `messageId` | String | 消息的唯一标识符(存在于消息事件中)。 | +| `role` | String | 消息发送者的角色,通常为 "assistant"(存在于消息开始事件中)。 | +| `delta` | String | 流式文本或工具参数的增量内容(存在于内容/参数事件中)。 | +| `toolCallId` | String | 工具调用的唯一标识符(存在于工具调用事件中)。 | +| `toolCallName` | String | 正在调用的工具的名称(存在于工具调用开始事件中)。 | + +### 事件类型 + +AG-UI 代理在 `type` 字段中返回具有以下事件类型的 SSE。 + +| 事件类型 | 说明 | +| :--- | :--- | +| `RUN_STARTED` | 表示运行的开始 | +| `TEXT_MESSAGE_START` | 标记助手消息的开始 | +| `TEXT_MESSAGE_CONTENT` | 包含增量文本内容(流式) | +| `TEXT_MESSAGE_END` | 标记助手消息的结束 | +| `TOOL_CALL_START` | 表示工具调用的开始 | +| `TOOL_CALL_ARGS` | 包含增量工具调用参数 | +| `TOOL_CALL_END` | 标记工具调用的结束 | +| `RUN_FINISHED` | 表示运行的完成 | + +## 跟踪令牌使用情况 +<Badge type="tip" text="3.6 版本引入" /> + +AG-UI 代理支持令牌使用跟踪,它为代理执行期间每次 LLM 调用提供有关令牌消耗的详细指标。令牌使用情况作为流式事件序列的一部分提供。 + +对于 AG-UI 代理,令牌使用跟踪在代理注册期间通过在 `parameters` 字段中设置 `"include_token_usage": true` 来启用。这适用于统一注册方法(新接口)和常规注册方法(旧接口)。一旦代理注册,此设置在代理执行期间无法更改,它必须在注册时设置。 + +### 在注册期间启用令牌使用跟踪(统一方法) + +要使用统一注册方法为 AG-UI 代理启用令牌使用跟踪,请在注册期间在 `parameters` 字段中包含 `include_token_usage` 参数: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "description": "An AI agent designed for UI interactions with streaming support", + "model": { + "model_id": "<MODEL ID>", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<AWS ACCESS KEY>", + "secret_key": "<AWS SECRET KEY>", + "session_token": "<AWS SESSION TOKEN>" + }, + "model_parameters": { + "system_prompt": "You are a helpful assistant and an expert in OpenSearch." + } + }, + "parameters": { + "max_iteration": 5, + "include_token_usage": true + }, + "tools": [{ + "type": "ListIndexTool" + }], + "memory": { + "type": "conversation_index" + } +} +``` + +### 在注册期间启用令牌使用跟踪(常规方法) + +或者,您可以使用常规注册方法通过在代理的 `parameters` 中包含 `include_token_usage` 来启用令牌使用跟踪: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "AG-UI Agent", + "type": "AG_UI", + "llm": { + "model_id": "<MODEL_ID>", + "parameters": { + "max_iteration": 5 + } + }, + "tools": [{ + "type": "ListIndexTool" + }], + "parameters": { + "include_token_usage": true + }, + "memory": { + "type": "conversation_index" + } +} +``` + +### 流式响应中的令牌使用情况 + +启用令牌使用跟踪后,流式响应在 `RUN_FINISHED` 事件之后包含一个带有令牌使用指标的 `Custom` 事件。指标包括每轮和每模型的令牌消耗: + +```json +data: {"type":"RUN_STARTED","timestamp":1775501029508,"threadId":"thread-agui-new-agmem-postman","runId":"run-postman-agui-new-am"} + +data: {"type":"TOOL_CALL_START","timestamp":1775501031547,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","toolCallName":"ListIndexTool"} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1775501031549,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","delta":""} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1775501031814,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","delta":"{\"indi"} + +data: {"type":"TOOL_CALL_ARGS","timestamp":1775501031814,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","delta":"ces\": []}"} + +data: {"type":"TOOL_CALL_END","timestamp":1775501031893,"toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w"} + +data: {"type":"TOOL_CALL_RESULT","timestamp":1775501031911,"messageId":"msg_66642762007875","toolCallId":"tooluse_Z8ov0YNqeAW8B2h1qNH49w","content":"..."} + +data: {"type":"TEXT_MESSAGE_START","timestamp":1775501033817,"messageId":"msg_66644668213500","role":"assistant"} + +data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1775501033818,"messageId":"msg_66644668213500","delta":"Here are all the indices..."} + +data: {"type":"TEXT_MESSAGE_END","timestamp":1775501041102,"messageId":"msg_66644668213500"} + +data: {"type":"Custom","timestamp":1775501041115,"name":"token_usage","value":{"per_turn_usage":[{"model_name":"Auto-generated model for us.anthropic.claude-sonnet-4-5-20250929-v1:0","model_url":"https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse","total_tokens":4806.0,"output_tokens":54.0,"turn":1.0,"model_id":"9RIbZJ0B1Feno22Ak-7G","input_tokens":4752.0},{"model_name":"Auto-generated model for us.anthropic.claude-sonnet-4-5-20250929-v1:0","model_url":"https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse","total_tokens":6262.0,"output_tokens":898.0,"turn":2.0,"model_id":"9RIbZJ0B1Feno22Ak-7G","input_tokens":5364.0}],"per_model_usage":[{"model_name":"Auto-generated model for us.anthropic.claude-sonnet-4-5-20250929-v1:0","model_url":"https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-5-20250929-v1:0/converse","call_count":2.0,"total_tokens":11068.0,"output_tokens":952.0,"model_id":"9RIbZJ0B1Feno22Ak-7G","input_tokens":10116.0}]}} + +data: {"type":"RUN_FINISHED","timestamp":1775501041116,"threadId":"thread-agui-new-agmem-postman","runId":"run-postman-agui-new-am"} +``` + +`token_usage` 事件包含: +- **`per_turn_usage`**:代理执行期间每个单独轮次的令牌指标,包括 `turn` 编号、`model_id`、`model_name`、`model_url`、`input_tokens`、`output_tokens` 和 `total_tokens`。 +- **`per_model_usage`**:按模型分组的聚合令牌指标,包括 `model_id`、`model_name`、`model_url`、`call_count`、`input_tokens`、`output_tokens` 和 `total_tokens`。 + +有关令牌使用字段的详细信息以及不同模型提供程序如何计算令牌,请参阅 Execute Agent API 文档中的[跟踪令牌使用情况](/ml-commons-plugin/api/agent-apis/execute-agent#tracking-token-usage)。 + +## 后续步骤 + +- 有关 AG-UI 代理注册,请参阅[统一注册方法](/ml-commons-plugin/agents-tools/agents/#unified-registration-method)。 +- 有关统一代理执行,请参阅[统一代理执行](/ml-commons-plugin/api/agent-apis/execute-agent#unified-agent-execution)。 +- 了解 [AG-UI 协议规范](https://docs.ag-ui.com/introduction)。 +- 探索可用于您的代理的后端[工具](/ml-commons-plugin/agents-tools/tools/)。 +- 查看[代理 API](/ml-commons-plugin/api/agent-apis/) 以获取其他功能。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/agents/conversational-flow.md b/i18n/zh/ml-commons-plugin/agents-tools/agents/conversational-flow.md new file mode 100644 index 00000000..42b3c7a3 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/agents/conversational-flow.md @@ -0,0 +1,70 @@ +--- +title: 对话流程代理 +--- + +# 对话流程代理 +<Badge type="tip" text="2.13 版本引入" /> + +类似于[流程代理](/ml-commons-plugin/agents-tools/agents/flow),对话流程代理配置有一组按顺序运行的工具。它们之间的区别在于,对话流程代理将对话存储在索引中,在以下示例中为 `conversation_index`。以下代理运行 `VectorDBTool`,然后运行 `MLModelTool`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "population data analysis agent", + "type": "conversational_flow", + "description": "This is a demo agent for population data analysis", + "app_type": "rag", + "memory": { + "type": "conversation_index" + }, + "tools": [ + { + "type": "VectorDBTool", + "name": "population_knowledge_base", + "parameters": { + "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", + "index": "test_population_data", + "embedding_field": "population_description_embedding", + "source_field": [ + "population_description" + ], + "input": "${parameters.question}" + } + }, + { + "type": "MLModelTool", + "name": "bedrock_claude_model", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "YOUR_LLM_MODEL_ID", + "prompt": """You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. + +Context: +${parameters.population_knowledge_base.output:-} + +${parameters.chat_history:-} + +Question: ${parameters.question}""" + } + } + ] +} +``` + +有关 Register Agent API 请求字段的更多信息,请参阅[请求正文字段](/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields)。 + +有关分步教程,请参阅[代理和工具教程](/ml-commons-plugin/agents-tools/agents-tools-tutorial)。 + +## 使用外部 MCP 工具 +<Badge type="tip" text="3.8 版本引入" /> + +对话流程代理可以在固定管道中与 OpenSearch 工具(如 `MLModelTool`)一起调用外部 MCP 服务器工具。配置 `parameters.mcp_connectors` 并使用 `McpStreamableHttpTool` 或 `McpSseTool` 在 `tools` 数组中显式声明每个 MCP 工具。有关设置步骤和示例,请参阅[在流程代理和对话流程代理中使用 MCP 工具](/ml-commons-plugin/agents-tools/mcp/mcp-connector#flow-agents-and-conversational-flow-agents)。 + +## 后续步骤 + +- 要了解更多关于注册代理的信息,请参阅 [Register Agent API](/ml-commons-plugin/api/agent-apis/register-agent)。 +- 有关支持的工具列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +- 有关分步教程,请参阅[代理和工具教程](/ml-commons-plugin/agents-tools/agents-tools-tutorial)。 +- 有关支持的 API,请参阅[代理 API](/ml-commons-plugin/api/agent-apis/)。 +- 要使用工作流模板创建代理和工具,请参阅 [AI 搜索工作流](/vector-search/ai-search/workflows/index/)。 +- 有关使用对话流程代理构建 RAG 聊天机器人的教程,请参阅[使用对话流程代理的 RAG 聊天机器人](/tutorials/gen-ai/chatbots/rag-conversational-agent/)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/agents/conversational.md b/i18n/zh/ml-commons-plugin/agents-tools/agents/conversational.md new file mode 100644 index 00000000..349fef95 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/agents/conversational.md @@ -0,0 +1,283 @@ +--- +title: 对话代理 +--- + +# 对话代理 +<Badge type="tip" text="2.13 版本引入" /> + +对话代理使用大型语言模型 (LLM) 和一组补充工具进行迭代推理并提供响应。代理使用思维链 (CoT) 过程为每个问题选择最佳工具,并存储对话历史,以便用户可以提出后续问题。对话代理使用[函数调用](/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields)来调用工具。 + +OpenSearch 提供两种类型的对话代理: + +- **[带有完整多模态支持的 `conversational_v2` 代理](#the-conversational_v2-agent-with-full-multimodal-support)**(OpenSearch 3.6 及更高版本):通过标准化接口提供内置多模态支持的增强代理。需要[统一注册方法](/ml-commons-plugin/agents-tools/agents/#unified-registration-method)和[代理记忆](/ml-commons-plugin/agentic-memory)。 + +- **[`conversational` 代理(v1)](#the-conversational-agent-v1)**(OpenSearch 2.13 及更高版本):支持[统一注册方法](/ml-commons-plugin/agents-tools/agents/#unified-registration-method)(仅纯文本输入)和[常规注册方法](/ml-commons-plugin/agents-tools/agents/#regular-registration-method)(依赖连接器的能力)。支持 `conversation_index` 和 `agentic_memory` 两种记忆类型。 + +## 带有完整多模态支持的 `conversational_v2` 代理 +<Badge type="tip" text="3.6 版本引入" /> + +`conversational_v2` 代理通过[统一注册方法](/ml-commons-plugin/agents-tools/agents/#unified-registration-method)提供内置多模态支持,从而扩展了 `conversational` 代理,无需自定义连接器配置。与使用统一注册方法时仅接受纯文本输入的 `conversational` 代理不同,`conversational_v2` 代理支持以下输入格式: + +- **纯文本**:简单的字符串输入。 +- **内容块**:包含文本、图像和文档的多模态数组。 +- **消息**:具有角色和多模态内容块的完整对话历史,用于多轮交互。 + +代理返回的响应包括停止原因、助手的消息、记忆会话 ID 和令牌使用指标。`conversational_v2` 代理需要 `agentic_memory` 记忆类型。 + +### 前提条件 + +`conversational_v2` 代理使用[统一注册方法](/ml-commons-plugin/agents-tools/agents/#unified-registration-method),需要启用统一代理 API。有关设置说明,请参阅[前提条件](/ml-commons-plugin/agents-tools/agents/#prerequisites)。 + +### 注册 `conversational_v2` 代理 + +要注册 `conversational_v2` 代理,请按照以下步骤操作。 + +**步骤 1:创建记忆容器** + +在注册 `conversational_v2` 代理之前,使用 [Create Memory Container API](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container) 创建一个记忆容器: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "my-agent-memory" +} +``` + +这将创建一个具有默认设置的记忆容器。根据您的用例,您可能需要配置其他选项,例如 `disable_session`、`embedding_model_id` 或记忆策略。有关所有可用选项,请参阅 [Create Memory Container API](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container)。 + +响应返回一个 `memory_container_id`,您在注册代理时使用: + +```json +{ + "memory_container_id": "SdjmmpgBOh0h20Y9kWuN", + "status": "created" +} +``` + +**步骤 2:注册代理** + +要注册代理,请发送以下请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Conversational Agent V2", + "type": "conversational_v2", + "description": "A multimodal conversational agent", + "model": { + "model_id": "us.anthropic.claude-sonnet-4-6", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<YOUR_AWS_ACCESS_KEY>", + "secret_key": "<YOUR_AWS_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + } + }, + "memory": { + "type": "agentic_memory", + "memory_container_id": "<YOUR_MEMORY_CONTAINER_ID>" + }, + "tools": [ + { + "type": "ListIndexTool" + } + ] +} +``` + +### 执行 `conversational_v2` 代理 + +`conversational_v2` 代理使用 `input` 字段并支持以下输入格式: + +- **纯文本输入**: + + ```json + POST /_plugins/_ml/agents/{agent_id}/_execute + { + "input": "What indexes are in my cluster?" + } + ``` + +- **多模态内容块输入**: + + ```json + POST /_plugins/_ml/agents/{agent_id}/_execute + { + "input": [ + { + "type": "text", + "text": "What can you see in this image?" + }, + { + "type": "image", + "source": { + "type": "base64", + "format": "png", + "data": "iVBORw0KGgoAAAANSUhEUgAA..." + } + } + ] + } + ``` + +- **消息输入**(多轮对话历史): + + ```json + POST /_plugins/_ml/agents/{agent_id}/_execute + { + "input": [ + { + "role": "user", + "content": [{"type": "text", "text": "I like the color red"}] + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "Thanks for sharing that!"}] + }, + { + "role": "user", + "content": [{"type": "text", "text": "What color do I like?"}] + } + ] + } + ``` + +### `conversational_v2` 代理响应格式 + +`conversational_v2` 代理返回标准化响应格式: + +```json +{ + "stop_reason": "end_turn", + "message": { + "role": "assistant", + "content": [ + { + "text": "Based on your cluster, I found the following indexes..." + } + ] + }, + "memory_id": "test_memory_id", + "metrics": { + "total_usage": { + "inputTokens": 1234, + "outputTokens": 567, + "totalTokens": 1801 + } + } +} +``` + +有关 `conversational_v2` 代理响应字段,请参阅 [`conversational_v2` 代理响应格式](/ml-commons-plugin/api/agent-apis/execute-agent#the-conversational_v2-agent-response-format)。 + +### 限制 + +以下限制适用于 `conversational_v2` 代理: + +- **记忆类型**:仅支持 `agentic_memory`。`conversation_index` 记忆类型与 `conversational_v2` 代理不兼容。 +- **流式传输**:不支持流式响应。 +- **钩子和上下文管理**:不支持代理执行钩子和上下文管理。 + +## `conversational` 代理(v1) + +`conversational` 代理支持两种注册方法,每种方法具有不同的能力: + +- **[统一注册方法](/ml-commons-plugin/agents-tools/agents/#unified-registration-method)**:仅接受纯文本输入。使用 `model` 字段进行 LLM 配置。 +- **[常规注册方法](/ml-commons-plugin/agents-tools/agents/#regular-registration-method)**:输入能力取决于连接器配置。使用 `llm` 字段进行 LLM 配置。如果您配置连接器将多模态内容传递给 LLM,则支持多模态输入。 + +::: info NOTE +要通过标准化接口获得完整的多模态支持,请使用 [`conversational_v2` 代理](#the-conversational_v2-agent-with-full-multimodal-support)。 +::: + +`conversational` 代理可以配置大型语言模型 (LLM) 和一组执行特定任务的补充工具。例如,您可以设置一个 LLM 和一个 `ListIndexTool`。当您向模型发送问题时,代理将 `ListIndexTool` 作为上下文包含在内。然后 LLM 决定是否需要使用该工具来回答诸如"我的集群中有多少个索引?"之类的问题。这使 LLM 能够回答其知识库之外的问题。 + +### 使用统一注册方法 + +以下示例使用统一注册方法注册 `conversational` 代理: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Conversational Agent", + "type": "conversational", + "description": "A conversational agent using unified registration", + "model": { + "model_id": "us.anthropic.claude-sonnet-4-6", + "model_provider": "bedrock/converse", + "credential": { + "access_key": "<YOUR_AWS_ACCESS_KEY>", + "secret_key": "<YOUR_AWS_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + } + }, + "memory": { + "type": "conversation_index" + }, + "tools": [ + { + "type": "ListIndexTool" + } + ] +} +``` + +### 使用常规注册方法 + +以下示例使用常规注册方法注册 `conversational` 代理: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_ReAct_Claude", + "type": "conversational", + "description": "This is a test agent", + "llm": { + "model_id": "YOUR_LLM_MODEL_ID", + "parameters": { + "max_iteration": 5, + "stop_when_no_tool_found": true, + "response_filter": "$.content[0].text" + } + }, + "memory": { + "type": "conversation_index" + }, + "tools": [ + { + "type": "VectorDBTool", + "name": "VectorDBTool", + "description": "A tool to search OpenSearch index with natural language question. If you don't know answer for some question, you should always try to search data with this tool. Action Input: <natural language question>", + "parameters": { + "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", + "index": "my_test_data", + "embedding_field": "embedding", + "source_field": [ "text" ], + "input": "${parameters.question}" + } + }, + { + "type": "ListIndexTool", + "name": "ListIndexTool", + "description": "Use this tool to get OpenSearch index information: (health, status, index, uuid, primary count, replica count, docs.count, docs.deleted, store.size, primary.store.size)." + } + ], + "app_type": "my app" +} +``` + +## 跟踪令牌使用情况 +<Badge type="tip" text="3.6 版本引入" /> + +对话代理支持令牌使用跟踪,它为代理执行期间每次 LLM 调用提供有关令牌消耗的详细指标。这有助于您监控成本、调试性能和比较模型效率。 + +要启用令牌使用跟踪,请在执行代理时将 `include_token_usage` 参数设置为 `true`。响应将包含一个 `token_usage` 输出,其中包含每轮和每模型聚合指标。有关令牌使用字段的详细信息以及不同模型提供程序如何计算令牌,请参阅 Execute Agent API 文档中的[跟踪令牌使用情况](/ml-commons-plugin/api/agent-apis/execute-agent#tracking-token-usage)。 + +## 后续步骤 + +- 要了解更多关于注册代理的信息,请参阅 [Register Agent API](/ml-commons-plugin/api/agent-apis/register-agent)。 +- 有关支持的工具列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +- 有关分步教程,请参阅[代理和工具教程](/ml-commons-plugin/agents-tools/agents-tools-tutorial)。 +- 有关支持的 API,请参阅[代理 API](/ml-commons-plugin/api/agent-apis/)。 +- 要使用工作流模板创建代理和工具,请参阅 [AI 搜索工作流](/vector-search/ai-search/workflows/index/)。 +- 有关使用对话代理构建 RAG 聊天机器人的教程,请参阅 [RAG 聊天机器人](/tutorials/gen-ai/chatbots/rag-chatbot/)。 +- 有关使用对话代理为 OpenSearch Dashboards 构建聊天机器人的教程,请参阅[构建您自己的聊天机器人](/tutorials/gen-ai/chatbots/build-chatbot/)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/agents/flow.md b/i18n/zh/ml-commons-plugin/agents-tools/agents/flow.md new file mode 100644 index 00000000..21fe7c80 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/agents/flow.md @@ -0,0 +1,54 @@ +--- +title: 流程代理 +--- + +# 流程代理 +<Badge type="tip" text="2.13 版本引入" /> + +流程代理配置有一组按顺序运行的工具。例如,以下代理运行 `VectorDBTool`,然后运行 `MLModelTool`。代理协调工具,使一个工具的输出可以成为另一个工具的输入。在此示例中,`VectorDBTool` 查询 k-NN 索引,代理将其输出 `${parameters.VectorDBTool.output}` 与 `${parameters.question}` 一起作为上下文传递给 `MLModelTool`(请参阅 `prompt` 参数): + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_RAG", + "type": "flow", + "description": "this is a test agent", + "tools": [ + { + "type": "VectorDBTool", + "parameters": { + "model_id": "YOUR_TEXT_EMBEDDING_MODEL_ID", + "index": "my_test_data", + "embedding_field": "embedding", + "source_field": ["text"], + "input": "${parameters.question}" + } + }, + { + "type": "MLModelTool", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "YOUR_LLM_MODEL_ID", + "prompt": "You are a professional data analyst. You will always answer a question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say you don't know. \n\nContext:\n${parameters.VectorDBTool.output}\n\nQuestion: ${parameters.question}" + } + } + ] +} +``` + +有关 Register Agent API 请求字段的更多信息,请参阅[请求正文字段](/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields)。 + +有关分步教程,请参阅[代理和工具教程](/ml-commons-plugin/agents-tools/agents-tools-tutorial)。 + +## 使用外部 MCP 工具 +<Badge type="tip" text="3.8 版本引入" /> + +流程代理可以在固定管道中与 OpenSearch 工具(如 `MLModelTool`)一起调用外部 MCP 服务器工具。配置 `parameters.mcp_connectors` 并使用 `McpStreamableHttpTool` 或 `McpSseTool` 在 `tools` 数组中显式声明每个 MCP 工具。有关设置步骤和示例,请参阅[在流程代理和对话流程代理中使用 MCP 工具](/ml-commons-plugin/agents-tools/mcp/mcp-connector#flow-agents-and-conversational-flow-agents)。 + +## 后续步骤 + +- 要了解更多关于注册代理的信息,请参阅 [Register Agent API](/ml-commons-plugin/api/agent-apis/register-agent)。 +- 有关支持的工具列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +- 有关分步教程,请参阅[代理和工具教程](/ml-commons-plugin/agents-tools/agents-tools-tutorial)。 +- 有关支持的 API,请参阅[代理 API](/ml-commons-plugin/api/agent-apis/)。 +- 要使用工作流模板创建代理和工具,请参阅 [AI 搜索工作流](/vector-search/ai-search/workflows/index/)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/agents/index.md b/i18n/zh/ml-commons-plugin/agents-tools/agents/index.md new file mode 100644 index 00000000..3a48043a --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/agents/index.md @@ -0,0 +1,186 @@ +--- +title: 代理 +--- + +# 代理 +<Badge type="tip" text="2.13 版本引入" /> + +_代理_是一个协调器,它使用大型语言模型 (LLM) 来解决问题。在 LLM 推理并决定采取什么行动后,代理协调行动的执行。OpenSearch 支持以下代理类型: + +- [_流程代理_](/ml-commons-plugin/agents-tools/agents/flow):按其配置中指定的顺序依次运行工具。流程代理的工作流程是固定的。适用于检索增强生成 (RAG)。 +- [_对话流程代理_](/ml-commons-plugin/agents-tools/agents/conversational-flow):按其配置中指定的顺序依次运行工具。对话流程代理的工作流程是固定的。存储对话历史,以便用户可以提出后续问题。适用于创建聊天机器人。 +- [_对话代理_](/ml-commons-plugin/agents-tools/agents/conversational):根据可用知识进行推理以提供响应,包括 LLM 知识库和提供给 LLM 的一组工具。LLM 迭代推理以决定采取什么行动,直到获得最终答案或达到迭代限制。存储对话历史,以便用户可以提出后续问题。对话代理的工作流程是可变的,基于后续问题。对于特定问题,使用思维链 (CoT) 过程从配置的工具中选择最佳工具来提供问题的响应。适用于创建采用 RAG 的聊天机器人。 +- [_对话代理 V2_](/ml-commons-plugin/agents-tools/agents/conversational#the-conversational_v2-agent-with-full-multimodal-support):对话代理的增强版本,开箱即用提供内置多模态支持,只需最少的配置。使用标准化接口接受文本、图像、文档和多轮消息历史作为输入,无需自定义连接器设置。返回标准化输出格式以及令牌使用指标。需要[统一注册方法](#unified-registration-method)和[代理记忆](/ml-commons-plugin/agentic-memory)。 +- [_计划-执行-反思代理_](/ml-commons-plugin/agents-tools/agents/plan-execute-reflect):动态计划、执行和完善多步骤工作流以解决复杂任务。在内部,计划-执行-反思代理使用对话代理来执行计划中的每个单独步骤。代理根据工具描述和上下文自动为每个步骤选择最合适的工具。非常适合从迭代推理和自适应执行中受益的长时间运行的探索过程。适用于进行研究或执行根本原因分析 (RCA)。 +- [_AG-UI 代理_](/ml-commons-plugin/agents-tools/agents/ag-ui):遵循 AG-UI 协议,用于将 AI 代理与前端应用程序集成。通过接受前端上下文和工具,实现 OpenSearch 和 UI 之间的无缝通信,允许代理直接与 UI 组件和应用程序状态交互。适用于交互式仪表板。 + +## 创建代理 + +您可以使用两种注册方法创建代理:常规注册方法或统一注册方法。 + +### 常规注册方法 + +常规注册方法使用 [Register Agent API](/ml-commons-plugin/api/agent-apis/register-agent),需要多个步骤才能创建代理: + +1. **注册连接器**:创建一个具有复杂 JSON 配置的连接器,包括 `request_body` 和 `url` 参数。 +2. **注册模型**:创建一个手动引用步骤 1 中的 `connector_id` 的模型。 +3. **注册代理**:通过提供 `model_id`、配置 `_llm_interface` 参数以及将 `question` 映射到 `prompt` 来创建代理。 +4. **执行代理**:仅使用受限的基于文本的 `question` 参数执行代理。 + +### 统一注册方法 +<Badge type="tip" text="3.5 版本引入" /> + +Unified Agent API 通过自动化连接器和模型设置来简化代理创建和执行,从而显著降低了在 OpenSearch 中使用代理的复杂性。Unified Agent API 通过根据 `model` 块配置自动处理模型组创建、连接器配置和模型注册,在单个 API 调用中注册代理: + +1. **注册代理**(连接器和模型自动创建)。 +2. **使用 `input` 字段执行代理**。 + +统一注册方法与常规注册方法在以下方面不同。 + +| 方面 | 常规注册方法 | 统一注册方法 | +| :--- | :--- | :--- | +| **工作流步骤** | 1. 注册连接器<br>2. 注册模型<br>3. 注册代理<br>4. 使用 `question` 参数执行 | 1. 注册代理(自动连接器/模型创建)<br>2. 使用灵活的 `input` 字段执行 | +| **配置复杂性** | 手动连接器配置,包括请求正文、URL 和参数映射 | 自动配置,具有内置验证和默认值 | +| **模型设置** | 在创建代理之前需要单独的模型注册 | 在代理注册期间自动创建模型资源 | +| **模型引用** | 使用 `llm.model_id` 引用预注册的模型 | 使用带有提供程序凭证和配置的 `model` 块 | +| **LLM 接口** | 手动 `_llm_interface` 参数配置 | 从 `model_provider` 自动检测 `_llm_interface` | +| **输入能力** | 仅限于基于文本的 `question` 参数 | 通过增强的执行 API 支持多模态输入(文本、图像、消息) | + +#### 支持的模型 + +支持以下模型: + +- 带有 Anthropic Claude 模型的 **Amazon Bedrock Converse API** +- **Google Gemini** 模型 +- **OpenAI** 模型 + +#### 前提条件 + +Unified Agent API 默认启用。如果 API 被禁用,请通过更新以下集群设置来启用它: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.unified_agent_api_enabled": true + } +} +``` + +如果您计划将 Model Context Protocol (MCP) 连接器与统一代理一起使用,还要启用 MCP 连接器支持: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.mcp_connector_enabled": true + } +} +``` + +#### 示例 + +以下示例演示了统一注册方法。 + +**步骤 1:注册代理** + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Conversational Agent", + "type": "conversational", + "description": "A conversational agent using OpenAI gpt-4o-mini", + "model": { + "model_id": "gpt-4o-mini", + "model_provider": "openai/v1/chat/completions", + "credential": { + "openai_api_key": "sk-your-api-key" + }, + "model_parameters": { + "max_tokens": 1000, + "temperature": 0.7 + } + } +} +``` + +有关完整的注册详细信息、字段定义以及所有模型提供程序的示例,请参阅[统一代理注册](/ml-commons-plugin/api/agent-apis/register-agent#unified-agent-registration)。 + +**步骤 2:执行代理** + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "input": "What tools do you have access to?" +} +``` + +有关执行详细信息和输入格式规范,请参阅[统一代理执行](/ml-commons-plugin/api/agent-apis/execute-agent#unified-agent-execution)。 + +#### 限制 + +以下限制适用于统一注册方法: + +- **代理类型**:仅支持 `conversational`、`conversational_v2`、`plan_execute_and_reflect` 和 `AG_UI` 代理。 +- **多模态输入**:使用统一注册方法时,基于内容块和消息的输入格式需要 `conversational_v2` 代理。所有其他统一代理类型,包括使用 `conversation_index` 或 `agentic_memory` 的 `conversational` 代理,仅接受纯文本输入。使用常规注册方法时,如果连接器配置为将多模态内容传递给 LLM,则可以支持多模态,输入格式由连接器配置确定。 + +Unified Agent API 与现有代理完全向后兼容。使用常规注册方法创建的代理继续正常运行。您可以在同一个集群中使用两种注册方法。 + +::: info NOTE +使用 Unified Agent API 创建的代理不能更新为使用常规注册方法参数。 +::: + +## 隐藏代理 +<Badge type="tip" text="2.13 版本引入" /> + +要向最终用户(包括集群管理员)隐藏代理详细信息,您可以注册一个_隐藏_代理。如果代理是隐藏的,非超级管理员用户无权在代理上调用任何[代理 API](/ml-commons-plugin/api/agent-apis/),除了 [Execute API](/ml-commons-plugin/api/agent-apis/execute-agent)。 + +只有超级管理员用户才能注册隐藏代理。要注册隐藏代理,您首先需要使用[管理员证书](/security/configuration/tls#configuring-admin-certificates)进行身份验证: + +```bash +curl -k --cert ./kirk.pem --key ./kirk-key.pem -XGET 'https://localhost:9200/.opendistro_security/_search' +``` + +超级管理员用户创建的所有代理都会自动注册为隐藏代理。只有超级管理员用户才能查看隐藏代理详细信息和删除隐藏代理。 +要注册隐藏代理,请向 `_register` 端点发送请求: + +```bash +curl -k --cert ./kirk.pem --key ./kirk-key.pem -X POST 'https://localhost:9200/_plugins/_ml/agents/_register' -H 'Content-Type: application/json' -d ' +{ + "name": "Test_Agent_For_RAG", + "type": "flow", + "description": "this is a test agent", + "tools": [ + { + "name": "vector_tool", + "type": "VectorDBTool", + "parameters": { + "model_id": "zBRyYIsBls05QaITo5ex", + "index": "my_test_data", + "embedding_field": "embedding", + "source_field": [ + "text" + ], + "input": "${parameters.question}" + } + }, + { + "type": "MLModelTool", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "NWR9YIsBUysqmzBdifVJ", + "prompt": "You are a professional data analyst. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\nContext:\n${parameters.vector_tool.output}\n\nQuestion: ${parameters.question}" + } + } + ] +}' +``` + +## 后续步骤 + +- 要了解更多关于注册代理的信息,请参阅 [Register Agent API](/ml-commons-plugin/api/agent-apis/register-agent)。 +- 有关支持的工具列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +- 有关分步教程,请参阅[代理和工具教程](/ml-commons-plugin/agents-tools/agents-tools-tutorial)。 +- 有关使用计划-执行-反思代理的分步教程,请参阅[构建计划-执行-反思代理](/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/)。 +- 有关支持的 API,请参阅[代理 API](/ml-commons-plugin/api/agent-apis/)。 +- 要使用工作流模板创建代理和工具,请参阅 [AI 搜索工作流](/vector-search/ai-search/workflows/index/)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/agents/plan-execute-reflect.md b/i18n/zh/ml-commons-plugin/agents-tools/agents/plan-execute-reflect.md new file mode 100644 index 00000000..45335613 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/agents/plan-execute-reflect.md @@ -0,0 +1,468 @@ +--- +title: 计划-执行-反思代理 +--- + +# 计划-执行-反思代理 +<Badge type="tip" text="3.0 版本引入" /> + +计划-执行-反思代理旨在解决需要迭代推理和逐步执行的复杂任务。这些代理使用一个大型语言模型 (LLM)——_规划器_——来创建和更新计划,并使用另一个 LLM(或默认情况下使用同一个 LLM)通过内置对话代理执行每个单独的步骤。 + +计划-执行-反思代理分三个阶段工作: + +- **规划**——规划器 LLM 使用可用工具生成初始逐步计划。 +- **执行**——使用对话代理和可用工具按顺序执行每个步骤。 +- **重新评估**——在执行每个步骤后,规划器 LLM 使用中间结果重新评估计划。LLM 可以根据新上下文动态调整计划,以跳过、添加或更改步骤。 + +类似于对话代理,计划-执行-反思代理将 LLM 和代理之间的交互存储在记忆索引中。在以下示例中,代理使用 `conversation_index` 来持久化执行历史,包括用户的问题、中间结果和最终输出。 + +代理根据工具描述和当前上下文自动为每个步骤选择最合适的工具。 + +代理仅支持在每个步骤之后重新评估。这允许代理在继续下一步之前根据中间结果动态调整计划。 + +## 创建计划-执行-反思代理 + +以下示例请求创建一个带有三个工具的计划-执行-反思代理: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Plan Execute Reflect Agent", + "type": "plan_execute_and_reflect", + "description": "Agent for dynamic task planning and reasoning", + "llm": { + "model_id": "YOUR_LLM_MODEL_ID", + "parameters": { + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "YOUR_LLM_INTERFACE" + }, + "tools": [ + { "type": "ListIndexTool" }, + { "type": "SearchIndexTool" }, + { "type": "IndexMappingTool" } + ], + "app_type": "os_chat" +} +``` + +::: tip TIP +提供工具的详细描述非常重要,以便 LLM 可以决定在哪些情况下使用这些工具。 +::: + +有关 Register Agent API 请求字段的更多信息,请参阅[请求正文字段](/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields)。 + +## 支持的 LLM + +计划-执行-反思代理为以下 LLM 提供内置函数调用接口: + +- [Amazon Bedrock 上托管的 Anthropic Claude Sonnet 4.6 模型](https://aws.amazon.com/bedrock/claude/) +- OpenAI GPT-4o 模型 +- Amazon Bedrock 上托管的 DeepSeek-R1 模型 + +要请求对 LLM 的默认支持,[在 ML Commons 存储库中创建功能请求问题](https://github.com/opensearch-project/ml-commons/issues)。 + +有关使用计划-执行-反思代理的分步教程,请参阅[构建计划-执行-反思代理](/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/)。 + +要使用特定模型配置计划-执行-反思代理,您需要在[步骤 1(a):创建连接器](/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/#step-1a-create-a-connector)中修改连接器,并在[步骤 2:创建代理](/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/#step-2-create-an-agent)中提供特定于模型的 `llm_interface` 参数: + +```json +"parameters": { + "_llm_interface": "bedrock/converse/claude" +} +``` + +有关 `_llm_interface` 字段的有效值,请参阅[请求正文字段](/ml-commons-plugin/api/agent-apis/register-agent#request-body-fields)。 + +以下示例提供了支持的模型的连接器和代理创建请求。 + +### Amazon Bedrock 上的 Anthropic Claude + +要为 Amazon Bedrock 上托管的 Anthropic Claude Sonnet 4.6 模型创建连接器,请使用以下请求: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Amazon Bedrock Claude Sonnet 4.6 connector", + "description": "Connector to Amazon Bedrock service for the Claude model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "your_aws_region", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "credential": { + "access_key": "your_aws_access_key", + "secret_key": "your_aws_secret_key", + "session_token": "your_aws_session_token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] +} +``` + +要使用 Anthropic Claude Sonnet 4.6 模型创建计划-执行-反思代理,请使用以下请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Plan Execute and Reflect agent with Claude Sonnet 4.6", + "type": "plan_execute_and_reflect", + "description": "this is a test agent", + "llm": { + "model_id": "your_llm_model_id", + "parameters": { + "prompt": "${parameters.question}" + }}, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "bedrock/converse/claude" + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ] +} +``` + +### OpenAI GPT-4o + +要为 OpenAI GPT-4o 模型创建连接器,请使用以下请求: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My openai connector: gpt-4o-mini", + "description": "The connector to openai chat model", + "version": 1, + "protocol": "http", + "parameters": { + "model": "gpt-4o" + }, + "credential": { + "openAI_key": "your_open_ai_key" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] +} +``` + +然后注册模型并注册代理,在 `_llm_interface` 字段中指定 `openai/v1/chat/completions`。 + +### Amazon Bedrock 上的 Deepseek-R1 + +要为 Amazon Bedrock 上托管的 DeepSeek-R1 模型创建连接器,请使用以下请求: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My DeepSeek R1 connector", + "description": "my test connector", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "your_region", + "service_name": "bedrock", + "model": "us.deepseek.r1-v1:0" + }, + "credential": { + "access_key": "your_access_key", + "secret_key": "your_secret_key", + "session_token": "your_session_token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}] }" + } + ] +} +``` + +然后注册模型并注册代理,在 `_llm_interface` 字段中指定 `bedrock/converse/deepseek_r1`。 + +由于 Amazon Bedrock 上托管的 Deepseek-R1 模型缺乏默认的函数调用支持,因此在代理注册期间提供以下提示作为 `executor_system_prompt`: + +```json +"You are a helpful assistant. You can ask Human to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n[${parameters._tools.toString()}]\n\nIf need to use tool, return which tool should be used and the input to user is enough. User will run the tool to get information. To make it easier for user to parse the response to know whether they should invoke a tool or not, please also return \"stop_reason\", it only return one of two enum values: [end_turn, tool_use], add a random tool call id to differenciate in case same tool invoked multiple times. Tool call id follow this pattern \"tool_use_<random string>\". The random string should be some UUID.\n\nFor example, you should return a json like this if need to use tool:\n{\"stop_reason\": \"tool_use\", \"tool_calls\": [{\"id\":\"tool_use_IIHBxMgOTjGb6ascCiOILg\",tool_name\":\"search_opensearch_index\",\"input\": {\"index\":\"population_data\",\"query\":{\"query\":{\"match\":{\"city\":\"New York City\"}}}}}]}\n\nIf don't need to use tool, return a json like this:\n{\"stop_reason\": \"end_turn\", \"message\": {\"role\":\"user\",\"content\":[{\"text\":\"What is the most popular song on WZPZ?\"}]}}\n\nNOTE: Don't wrap response in markdown ```json<response>```. For example don't return ```json\\n{\"stop_reason\": \"end_turn\", \"message\": {\"role\":\"user\",\"content\":[{\"text\":\"What is the most popular song on WZPZ?\"}]}}```\n" +``` + +## 跟踪代理执行和记忆 + +当您使用 [Agent Execute API](/ml-commons-plugin/api/agent-apis/execute-agent) 异步执行计划-执行-反思代理时,API 在代理启动后返回 `memory_id` 和规划器代理的 `parent_interaction_id`。 + +在最终响应中,API 还返回 `executor_agent_memory_id` 和 `executor_agent_parent_interaction_id`,它们对应于负责执行计划每个步骤的内部执行器代理。`executor_agent_memory_id` 和 `executor_agent_parent_interaction_id` 在它们可用时立即在任务中更新,即使在代理完成执行之前也是如此。这使得能够实时跟踪执行过程。 + +有关完整示例,请参阅[构建计划-执行-反思代理](/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/#test-the-agent)。 + +## 默认提示 + +计划-执行-反思代理使用以下预定义提示。您可以通过以下方式提供新提示来自定义提示: + +- 在 `parameters` 对象中的代理注册期间 +- 在代理执行期间动态提供 + +### 规划器模板和提示 + +要创建自定义规划器提示模板,请修改 `planner_prompt_template` 参数。以下模板用于要求 LLM 为给定任务设计计划: + +```json +${parameters.tools_prompt} \n${parameters.planner_prompt} \nObjective: ```${parameters.user_prompt}``` \n\nRemember: Respond only in JSON format following the required schema. +``` + +要创建自定义规划器提示,请修改 `planner_prompt` 参数。 +以下提示用于要求 LLM 为给定任务设计计划: + +``` +For the given objective, generate a step-by-step plan composed of simple, self-contained steps. The final step should directly yield the final answer. Avoid unnecessary steps. +``` + +### 带有历史模板的规划器提示 + +要创建自定义规划器提示和历史模板,请修改 `planner_with_history_template` 参数。在代理执行期间提供 `memory_id` 以向 LLM 提供有关先前任务的上下文时,使用以下模板: + +```json +${parameters.tools_prompt} \n${parameters.planner_prompt} \nObjective: ```${parameters.user_prompt}``` \n\nYou have currently executed the following steps: \n[${parameters.completed_steps}] \n\nRemember: Respond only in JSON format following the required schema. +``` + +### 反思提示和模板 + +要创建自定义反思提示模板,请修改 `reflect_prompt_template` 参数。以下模板用于要求 LLM 根据已完成的步骤重新思考原始计划: + +```json +${parameters.tools_prompt} \n${parameters.planner_prompt} \n\nObjective: ```${parameters.user_prompt}```\n\nPrevious plan:\n[${parameters.steps}] \n\nYou have currently executed the following steps: \n[${parameters.completed_steps}] \n\n${parameters.reflect_prompt} \n\n.Remember: Respond only in JSON format following the required schema. +``` + +要创建自定义反思提示,请修改 `reflect_prompt` 参数。 +以下提示用于要求 LLM 重新思考原始计划: + +``` +Update your plan based on the latest step results. If the task is complete, return the final answer. Otherwise, include only the remaining steps. Do not repeat previously completed steps. +``` + +### 规划器系统提示 + +要创建自定义规划器系统提示,请修改 `system_prompt` 参数。以下是规划器系统提示: + +```` +# Investigation Planner Agent + +You are a thoughtful and analytical planner agent in a plan-execute-reflect framework. Your job is to design a clear, step-by-step plan for a given objective. + +# Instructions + +## Core Planning Rules +- Break the objective into an ordered list of atomic, self-contained Steps that, if executed, will lead to the final result or complete the objective +- Each Step must state what to do, where, and which tool/parameters would be used. You do not execute tools, only reference them for planning +- Use only the provided tools; do not invent or assume tools. If no suitable tool applies, use reasoning or observations instead +- Base your plan only on the data and information explicitly provided; do not rely on unstated knowledge or external facts +- If there is insufficient information to create a complete plan, summarize what is known so far and clearly state what additional information is required to proceed +- Stop and summarize if the task is complete or further progress is unlikely +- Avoid vague instructions; be specific about data sources, indexes, or parameters +- Never make assumptions or rely on implicit knowledge +- Respond only in JSON format +## Step Examples +**Good example:** "Use Tool to sample documents from index: 'my-index'" + +**Bad example:** "Use Tool to sample documents from each index" + +**Bad example:** "Use Tool to sample documents from all indices" + +# Response Format + +## JSON Response Requirements +Only respond in JSON format. Always follow the given response instructions. Do not return any content that does not follow the response instructions. Do not add anything before or after the expected JSON + +Always respond with a valid JSON object that strictly follows the below schema: +```json +{ + "steps": array[string], + "result": string +} +``` + +- Use "steps" to return an array of strings where each string is a step to complete the objective, leave it empty if you know the final result. Please wrap each step in quotes and escape any special characters within the string +- Use "result" to return the final response when you have enough information, leave it empty if you want to execute more steps. +Here are examples of valid responses following the required JSON schema: + +Example 1 - When you need to execute steps: +{ + "steps": ["This is an example step", "this is another example step"], + "result": "" +} + +Example 2 - When you have the final result: +{ + "steps": [], + "result": "This is an example result\n with escaped special characters" +} +## Critical Rules +1. Do not use commas within individual steps +2. Do not add any content before or after the JSON +3. Only respond with a pure JSON object + +When you deliver your final result, include a comprehensive report. This report must: +1. List every analysis or step you performed. +2. Summarize the inputs, methods, tools, and data used at each step. +3. Include key findings from all intermediate steps — do NOT omit them. +4. Clearly explain how the steps led to your final conclusion. Only mention the completed steps. +5. Return the full analysis and conclusion in the 'result' field, even if some of this was mentioned earlier. Ensure that special characters are escaped in the 'result' field. +6. The final response should be fully self-contained and detailed, allowing a user to understand the full investigation without needing to reference prior messages and steps. +```` + +::: tip TIP +我们不建议修改响应格式说明。如果您打算修改任何提示,可以通过使用 `${parameters.plan_execute_reflect_response_format}` 参数注入响应格式说明。 +::: + +### 自定义规划器系统提示的部分 + +要更改规划器系统提示的部分,同时保留核心规划规则和响应格式,请使用以下参数: + +参数 | 数据类型 | 说明 +:--- | :--- | :--- +`planner_system_prompt_prefix` | String | 替换规划器系统提示的开头,包括 `# Investigation Planner Agent` 标题及其后的段落。默认值为该标题和段落。 +`result_expand_and_override` | String | 附加到响应格式中 `result` 字段说明的文本。设置此参数时,提示会省略示例响应(从 `Here are examples of valid responses` 开始的文本)。默认为空。 +`important_rules_expand` | String | 附加到响应格式中 `## Critical Rules` 列表的文本,例如,额外的编号规则。默认为空。 + +当您设置这些参数中的任何一个时,代理从前缀、核心规划规则和响应格式构建规划器系统提示,对于您未设置的三个参数中的任何一个使用默认值。生成的提示替换 `system_prompt` 值,并且不包括最终结果报告说明(从 `When you deliver your final result` 开始的文本)。 + +以下请求在代理执行期间设置所有三个参数: + +```json +POST /_plugins/_ml/agents/your_agent_id/_execute?async=true +{ + "parameters": { + "question": "How many indexes in this cluster have names that start with .plugins-ml-am?", + "planner_system_prompt_prefix": "# Index Planner\n\nYou are a planner agent. Write every step in the plan in all uppercase letters.\n", + "result_expand_and_override": "The result field must start with a one-sentence answer.", + "important_rules_expand": "4. Every step string must start with the name of the tool to use" + } +} +``` + +### 执行器系统提示 + +要创建自定义执行器系统提示,请修改 `executor_system_prompt` 参数。以下是执行器系统提示: + +``` +You are a precise and reliable executor agent in a plan-execute-reflect framework. Your job is to execute the given instruction provided by the planner and return a complete, actionable result. + +Instructions: +- Fully execute the given Step using the most relevant tool or reasoning. If executing the Step requires multiple tool invocations, invoke at most one tool per response and perform remaining tool invocations in subsequent responses. +- Include all relevant raw tool outputs (e.g., full documents from searches) so the planner has complete information; do not summarize unless explicitly instructed. +- Base your execution and conclusions only on the data and tool outputs available; do not rely on unstated knowledge or external facts. +- If the available data is insufficient to complete the Step, summarize what was obtained so far and clearly state the additional information or access required to proceed (do not guess). +- If unable to complete the Step, clearly explain what went wrong and what is needed to proceed. +- Avoid making assumptions and relying on implicit knowledge. +- Before generating any PPL or DSL query, always retrieve the index mapping first to ensure correct field names. Do not guess field names. +- Your response must be self-contained and ready for the planner to use without modification. Never end with a question. +- Break complex searches into simpler queries when appropriate. +- Never invoke more than one tool in a single response. Returning multiple tool calls in one response is invalid. +``` + +## 修改默认提示 + +要修改提示,请在代理注册期间提供它们: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "My Plan Execute and Reflect agent with Claude Sonnet 4.6", + "type": "plan_execute_and_reflect", + "description": "this is a test agent", + "llm": { + "model_id": "your_llm_model_id_from_step1", + "parameters": { + "prompt": "${parameters.question}" + }}, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "bedrock/converse/claude", + "planner_prompt_template": "your_planner_prompt_template", + "planner_prompt": "your_planner_prompt", + "reflect_prompt_template": "your_reflect_prompt_template", + "reflect_prompt": "your_reflect_prompt", + "planner_with_history_template": "your_planner_with_history_template", + "system_prompt": "your_planner_system_prompt", + "executor_system_prompt": "your_executor_system_prompt" + }, + "tools": [ + { + "type": "ListIndexTool" + }, + { + "type": "SearchIndexTool" + }, + { + "type": "IndexMappingTool" + } + ] +} +``` + +您还可以在代理执行期间修改提示: + +```json +POST /_plugins/_ml/agents/your_agent_id/_execute?async=true +{ + "parameters": { + "question": "How many flights from Beijing to Seattle?", + "planner_prompt_template": "your_planner_prompt_template", + "planner_prompt": "your_planner_prompt" + } +} +``` + +## 跟踪令牌使用情况 +<Badge type="tip" text="3.6 版本引入" /> + +计划-执行-反思代理支持令牌使用跟踪,它为代理执行期间每次 LLM 调用提供有关令牌消耗的详细指标,包括规划、执行(使用子代理)和反思 LLM 调用。子代理令牌数据会自动合并到父代理的令牌使用报告中。 + +要启用令牌使用跟踪,请在执行代理时将 `include_token_usage` 参数设置为 `true`。响应将包含一个 `token_usage` 输出,其中包含每轮和每模型聚合指标。有关令牌使用字段的详细信息以及不同模型提供程序如何计算令牌,请参阅 Execute Agent API 文档中的[跟踪令牌使用情况](/ml-commons-plugin/api/agent-apis/execute-agent#tracking-token-usage)。 + +## 后续步骤 + +- 要了解更多关于注册代理的信息,请参阅 [Register Agent API](/ml-commons-plugin/api/agent-apis/register-agent)。 +- 有关支持的工具列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +- 有关使用计划-执行-反思代理的分步教程,请参阅[构建计划-执行-反思代理](/tutorials/gen-ai/agents/build-plan-execute-reflect-agent/)。 +- 有关支持的 API,请参阅[代理 API](/ml-commons-plugin/api/agent-apis/)。 +- 要使用工作流模板创建代理和工具,请参阅 [AI 搜索工作流](/vector-search/ai-search/workflows/index/)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/mcp/index.md b/i18n/zh/ml-commons-plugin/agents-tools/mcp/index.md new file mode 100644 index 00000000..ea1d1355 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/mcp/index.md @@ -0,0 +1,23 @@ +--- +title: 使用 MCP 工具 +--- + +# 使用 MCP 工具 +<Badge type="tip" text="3.0 版本引入" /> + +[模型上下文协议(MCP)](https://modelcontextprotocol.io/introduction)是一个开放协议标准,为 AI 模型连接到外部数据源和工具提供了标准化的方式。OpenSearch 与 MCP 集成,使代理能够通过 MCP 服务器使用外部工具和数据源。 + +连接到外部 MCP 服务器可扩展代理的能力,包括以下功能: + +- 使用 MCP 服务器提供的工具 +- 根据应用程序需求过滤可用工具 +- 为工具访问实现安全的身份验证和授权 +- 通过一致的标准化接口与各种工具交互 + +要开始使用 MCP,请参阅[连接到外部 MCP 服务器](/ml-commons-plugin/agents-tools/mcp/mcp-connector)。 + +本节介绍集群内 MCP 连接器,它允许 OpenSearch 代理调用托管在外部 MCP 服务器上的工具。 + +::: info NOTE +OpenSearch 还提供一个 MCP 服务器,将 OpenSearch API 暴露给外部 AI 助手。与集群内 MCP 连接器不同,OpenSearch MCP 服务器允许外部客户端查询 OpenSearch,而不是让 OpenSearch 代理调用外部工具。有关更多信息,请参阅 [OpenSearch MCP 服务器](/ai-agent-integrations/mcp-server/)。 +::: diff --git a/i18n/zh/ml-commons-plugin/agents-tools/mcp/mcp-connector.md b/i18n/zh/ml-commons-plugin/agents-tools/mcp/mcp-connector.md new file mode 100644 index 00000000..87a23e87 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/mcp/mcp-connector.md @@ -0,0 +1,462 @@ +--- +title: 连接到外部 MCP 服务器 +--- + +# 连接到外部 MCP 服务器 +<Badge type="tip" text="3.0 版本引入" /> + +OpenSearch 支持使用[代理](/ml-commons-plugin/agents-tools/agents/)的代理工作流。虽然 OpenSearch 提供了用于运行复杂查询的内置工具,但[模型上下文协议(MCP)](https://modelcontextprotocol.io/introduction)能够与外部工具和数据源集成。MCP 是一个开放协议标准,为 AI 模型连接到外部数据源和工具提供了标准化的方式,作为远程 MCP 服务器工具的"通用适配器"。 + +::: info NOTE +OpenSearch 支持使用服务器发送事件(SSE)协议或可流式 HTTP 协议的 MCP 服务器。不支持标准输入/输出(`stdio`)协议。 +::: + +以下示例演示了在代理工作流中使用 MCP 工具。 + +## 前提条件 + +在使用 MCP 工具之前,您必须完成以下前提条件。 + +### 启用 MCP 并配置受信任的连接器端点 + +- 通过配置 `plugins.ml_commons.mcp_connector_enabled` 设置来启用 MCP 协议。 +- 在 `plugins.ml_commons.trusted_connector_endpoints_regex` 设置中配置受信任的连接器端点。出于安全目的,此设置使用正则表达式模式来定义允许哪些 MCP 服务器 URL。您提供的值将替换默认的受信任端点列表,因此还要包括您使用的任何其他连接器的端点,例如[步骤 2](#step-2-register-a-model) 中使用的 OpenAI 端点。 + +要配置这两个设置,请发送以下请求: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.trusted_connector_endpoints_regex": [ + "<mcp server url>", + "^https://api\\.openai\\.com/.*$" + ], + "plugins.ml_commons.mcp_connector_enabled": "true" + } +} +``` + +### 设置 MCP 服务器 + +确保您有一个正在运行的 MCP 服务器,该服务器可从您的 OpenSearch 集群访问。 + +## 步骤 1:创建 MCP 连接器 + +MCP 连接器存储 MCP 服务器的连接详细信息和凭证。您可以使用 SSE 或可流式 HTTP 进行连接。 + +要使用 SSE 创建 MCP 连接器,请发送以下请求: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My MCP Connector", + "description": "Connects to the external MCP server for weather tools", + "version": 1, + "protocol": "mcp_sse", + "url": "https://my-mcp-server.domain.com", + "credential": { + "mcp_server_key": "THE_MCP_SERVER_API_KEY" + }, + "parameters":{ + "sse_endpoint": "/sse" + }, + "headers": { + "Authorization": "Bearer ${credential.mcp_server_key}" + } +} +``` + +要使用可流式 HTTP 创建 MCP 连接器,将 `protocol` 设置为 `mcp_streamable_http`。可选地,设置 `parameters.endpoint` 来覆盖默认端点(`/mcp/`)。例如,要连接到 OpenSearch MCP 服务器,将 `parameters.endpoint` 设置为 `/_plugins/_ml/mcp`。不需要 SSE 特定的端点: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My MCP Connector (Streamable HTTP)", + "description": "Connects to the external MCP server using Streamable HTTP", + "version": 1, + "protocol": "mcp_streamable_http", + "url": "https://my-mcp-server.domain.com", + "credential": { + "mcp_server_key": "THE_MCP_SERVER_API_KEY" + }, + "parameters": { + "endpoint": "/_plugins/_ml/mcp" + }, + "headers": { + "Authorization": "Bearer ${credential.mcp_server_key}" + } +} +``` + +下表描述了连接器参数。有关标准连接器参数的更多信息,请参阅[创建连接器 API](/ml-commons-plugin/api/connector-apis/create-connector#request-body-fields)。 + +| 参数 | 数据类型 | 必需 | 描述 | +|:----------|:---------|:---|:------------| +| `protocol` | String | 是 | 对于 SSE 指定 `mcp_sse`,对于可流式 HTTP 指定 `mcp_streamable_http`。 | +| `url` | String | 是 | MCP 服务器的完整基础 URL,包括协议、主机名和端口(如果不使用默认端口)(例如,`https://my-mcp-server.com:8443`)。 | +| `credential` | Object | 是 | 包含敏感身份验证信息,例如 API 密钥或令牌。存储在此对象中的值可以使用 `${credential.*}` 语法在 `headers` 部分中安全引用。 | +| `parameters` | Object | 否 | 包含 MCP 连接器的配置参数。 | +| `parameters.sse_endpoint` | String | 否 | 仅适用于 SSE。MCP 服务器的 SSE 端点路径。默认为 `/sse`。 | +| `parameters.endpoint` | String | 否 | 仅适用于可流式 HTTP。MCP 服务器端点路径。默认为 `/mcp/`。 | +| `headers` | Object | 否 | 要包含在对 MCP 服务器的请求中的 HTTP 头。对于身份验证头,使用 `${credential.*}` 语法引用 `credential` 对象中的值(例如,`"Authorization": "Bearer ${credential.mcp_server_key}"`)。 | + +响应包含连接器 ID: + +```json +{ + "connector_id": "NZ2W2ZUBZ_3SyqdOvh2n" +} +``` + +## 步骤 2:注册模型 + +使用连接器注册任何外部托管的大型语言模型(LLM)。有关支持的模型列表,请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)。 + +例如,要注册 OpenAI 聊天模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "My OpenAI model: gpt-4o-mini", + "function_name": "remote", + "description": "Test model registration (this example uses OpenAI, but you can register any model)", + "connector": { + "name": "My OpenAI Connector: gpt-4o-mini", + "description": "Connector for the OpenAI chat model", + "version": 1, + "protocol": "http", + "parameters": { + "model": "gpt-4o" + }, + "credential": { + "openAI_key": "<YOUR_API_KEY>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_instruction}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}], \"tools\": [${parameters._tools:-}],\"parallel_tool_calls\":${parameters.parallel_tool_calls},\"tool_choice\": \"${parameters.tool_choice}\" }" + } + ] + } +} +``` + +响应包含模型 ID: + +```json +{ + "task_id": "K_iQfpYBjoQOEoSHN3wU", + "status": "CREATED", + "model_id": "LPiQfpYBjoQOEoSHN3zH" +} +``` + +要检查操作的状态,将任务 ID 提供给 [Get ML Task API](/ml-commons-plugin/api/tasks-apis/get-task)。一旦注册完成,任务 `state` 将变为 `COMPLETED`。 + +## 步骤 3:注册用于访问 MCP 工具的代理 + +下表列出了支持 MCP 工具的代理类型。 + +| 代理类型 | MCP 集成 | +|:---|:---| +| [`conversational`](/ml-commons-plugin/agents-tools/agents/conversational) | LLM 在运行时选择 MCP 工具。 | +| [`plan_execute_and_reflect`](/ml-commons-plugin/agents-tools/agents/plan-execute-reflect) | LLM 在运行时选择 MCP 工具。 | +| [`flow`](/ml-commons-plugin/agents-tools/agents/flow) | MCP 工具以固定的管道顺序运行。 | +| [`conversational_flow`](/ml-commons-plugin/agents-tools/agents/conversational-flow) | MCP 工具以固定的管道顺序运行,并带有对话记忆。 | + +对于所有支持的代理类型,在 `parameters.mcp_connectors` 中包含一个或多个 MCP 连接器。如何配置 `tools` 数组取决于代理类型。 + +每个连接器必须在 `parameters.mcp_connectors` 数组中指定以下参数。 + +| 参数 | 数据类型 | 必需 | 描述 | +|:--- |:--- |:--- |:--- | +| `mcp_connector_id` | String | 是 | MCP 连接器的连接器 ID。 | +| `tool_filters` | Array | 否 | Java 样式正则表达式数组,指定从 MCP 服务器中哪些工具可供代理使用。如果工具与数组中的至少一个正则表达式匹配,则包含该工具。如果省略或设置为空数组,则连接器暴露的所有工具都可用。使用 `^` 或 `$` 锚点或文字字符串来精确匹配工具名称。例如,`^get_forecast` 匹配任何以"get_forecast"开头的工具,而 `search_indices` 仅匹配"search_indices"。| +| `tool_descriptions` | Array | 否 | 覆盖发送给 LLM 的工具描述的对象数组。每个对象将工具名称(键)映射到替换描述(字符串值)。只有通过 `tool_filters` 评估的工具才能被覆盖。如果工具不存在于连接器上、被 `tool_filters` 排除或具有空白、空或非字符串值,则忽略条目。如果同一工具名称出现在多个对象中,则最后一个值获胜。 | + +对于 `conversational` 和 `plan_execute_and_reflect` 代理,MCP 工具从配置的连接器中发现并呈现给 LLM。LLM 在执行期间决定调用哪个 MCP 工具。您不需要在 `tools` 数组中显式列出 MCP 工具,但可以在 MCP 工具旁边包含 OpenSearch 内置工具。 + +以下示例使用步骤 1 中创建的连接器 ID 注册对话代理。MCP 服务器有两个可用工具(`get_alerts` 和 `get_forecasts`),但只有 `get_alerts` 工具包含在代理的配置中,因为它与指定的正则表达式模式 `^get_alerts$` 匹配: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Weather & Search Bot", + "type": "conversational", + "description": "Uses MCP to fetch forecasts and OpenSearch indices", + "llm": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "parameters": { + "max_iteration": 5, + "system_instruction": "You are a helpful assistant.", + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "openai/v1/chat/completions", + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>", + "tool_filters": [ + "^get_alerts$" + ] + } + ] + }, + "tools": [ + { "type": "ListIndexTool" }, + { "type": "SearchIndexTool" } + ], + "app_type": "os_chat" +} +``` + +响应包含代理 ID: + +```json +{ + "agent_id": "LfiXfpYBjoQOEoSH93w7" +} +``` + +### 覆盖 MCP 工具描述 +<Badge type="tip" text="3.8 版本引入" /> + +每个 MCP 工具都包含一个描述,帮助 LLM 决定何时调用它。要在不修改 MCP 服务器的情况下替换工具的描述,请使用 `tool_descriptions` 参数。当服务器提供的描述太通用、使用内部命名或不匹配代理的域词汇表时,这很有用。 + +`tool_descriptions` 中的每个条目必须是具有单个键值对的 JSON 对象:MCP 工具名称和覆盖描述字符串。您可以通过向数组添加多个对象来指定多个覆盖。 + +以下示例注册一个代理,该代理仅暴露 `get_alerts` 工具(使用 `tool_filters`)并用代理特定的指导替换其描述: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Weather & Search Bot", + "type": "conversational", + "description": "Uses MCP to fetch forecasts and OpenSearch indices", + "llm": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "parameters": { + "max_iteration": 5 + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "openai/v1/chat/completions", + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>", + "tool_filters": [ + "^get_alerts$" + ], + "tool_descriptions": [ + { + "get_alerts": "Fetch active weather alerts for a US state. Use when the user asks about warnings or advisories." + } + ] + } + ] + }, + "tools": [ + { "type": "ListIndexTool" } + ], + "app_type": "os_chat" +} +``` + +要在不应用 `tool_filters` 的情况下覆盖多个工具的描述,请省略 `tool_filters` 参数或将其设置为空数组,以便所有连接器工具保持可用: + +```json +"mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>", + "tool_descriptions": [ + { "get_alerts": "Fetch active weather alerts for a US state." }, + { "get_forecast": "Fetch a multi-day weather forecast for a city." } + ] + } +] +``` + +连接器未暴露或 `tool_filters` 排除的工具名称的覆盖无效。对于没有有效覆盖的任何工具,代理继续使用 MCP 服务器的原始描述。 + +### 流代理和对话流代理 +<Badge type="tip" text="3.8 版本引入" /> + +对于 [`flow`](/ml-commons-plugin/agents-tools/agents/flow) 和 [`conversational_flow`](/ml-commons-plugin/agents-tools/agents/conversational-flow) 代理,MCP 工具以 `tools` 数组中定义的固定顺序运行。您必须显式声明每个 MCP 工具,并将工具 `type` 与连接器协议匹配。 + +| 连接器协议 | MCP 工具 `type` | +|:---|:---| +| `mcp_streamable_http` | `McpStreamableHttpTool` | +| `mcp_sse` | `McpSseTool` | + +`tools` 数组中的每个 MCP 工具条目支持以下字段。 + +| 字段 | 数据类型 | 必需 | 描述 | +|:---|:---|:---|:---| +| `name` | String | 是 | MCP 服务器工具名称。必须与配置的连接器暴露的工具匹配。用于输出链接(例如,`${parameters.get_simple_price.output}`)。 | +| `type` | String | 是 | `McpStreamableHttpTool` 或 `McpSseTool`,与连接器协议匹配。 | +| `description` | String | 否 | 工具的描述。如果省略,OpenSearch 在可用时使用 MCP 服务器的描述。 | +| `parameters.input` | String | 是 | 工具输入负载,通常是传递给 MCP 服务器工具的 JSON 字符串。 | + +您可以在同一管道中混合 MCP 工具与 OpenSearch 工具(例如 `MLModelTool`)。可以使用 `${parameters.<tool_name>.output}` 将一个步骤的输出传递给下一个步骤。 + +如果 MCP 工具在 `tools` 中列出,但配置的连接器无法使用,则代理执行失败,并显示指示该工具不可用的错误。如果多个 MCP 连接器暴露同名的工具,OpenSearch 使用 `mcp_connectors` 数组中第一个匹配连接器的工具。 + +在注册流或对话流代理之前,使用 [List Connector MCP Tools API](/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools) 从您的 MCP 连接器发现工具名称、类型、描述和输入模式。在代理中配置 MCP 工具时,使用响应中的 `name` 和 `type` 值,并从每个工具的 `input_schema` 构建 `parameters.input` JSON 字符串。 + +以下示例注册一个 `flow` 代理,该代理依次调用 `search_documents` 和 `get_weather`,然后使用 `MLModelTool` 总结结果: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research and weather flow agent", + "type": "flow", + "description": "Flow agent using MCP tools in a fixed order", + "parameters": { + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>" + } + ] + }, + "tools": [ + { + "name": "search_documents", + "type": "McpStreamableHttpTool", + "description": "Search a document repository for relevant content.", + "parameters": { + "input": "{\"query\":\"OpenSearch agentic search\",\"limit\":5}" + } + }, + { + "name": "get_weather", + "type": "McpStreamableHttpTool", + "description": "Retrieve current weather conditions for a specified location.", + "parameters": { + "input": "{\"location\":\"Seattle\",\"units\":\"celsius\"}" + } + }, + { + "name": "summarize_results", + "type": "MLModelTool", + "description": "Summarize MCP tool outputs", + "parameters": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "prompt": "You are a research assistant.\n\nDocument search results:\n${parameters.search_documents.output}\n\nWeather:\n${parameters.get_weather.output}\n\nProvide a brief summary of the findings." + } + } + ] +} +``` + +要使用带有对话记忆的相同 MCP 管道,将 `type` 设置为 `conversational_flow` 并在与 `parameters` 和 `tools` 相同级别添加 `memory` 块: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research and weather conversational flow agent", + "type": "conversational_flow", + "description": "Conversational flow agent using MCP tools in a fixed order", + "memory": { + "type": "conversation_index" + }, + "parameters": { + "mcp_connectors": [ + { + "mcp_connector_id": "<MCP_CONNECTOR_ID_FROM_STEP_1>" + } + ] + }, + "tools": [ + { + "name": "search_documents", + "type": "McpStreamableHttpTool", + "description": "Search a document repository for relevant content.", + "parameters": { + "input": "{\"query\":\"OpenSearch agentic search\",\"limit\":5}" + } + }, + { + "name": "get_weather", + "type": "McpStreamableHttpTool", + "description": "Retrieve current weather conditions for a specified location.", + "parameters": { + "input": "{\"location\":\"Seattle\",\"units\":\"celsius\"}" + } + }, + { + "name": "summarize_results", + "type": "MLModelTool", + "description": "Summarize MCP tool outputs", + "parameters": { + "model_id": "<MODEL_ID_FROM_STEP_2>", + "prompt": "You are a research assistant.\n\nDocument search results:\n${parameters.search_documents.output}\n\nWeather:\n${parameters.get_weather.output}\n\nProvide a brief summary of the findings." + } + } + ] +} +``` + +## 步骤 4:运行代理 + +通过调用 Execute Agent API 并提供用户问题来调用已注册的代理: + +```json +POST /_plugins/_ml/agents/{Agent_ID}/_execute +{ + "parameters": { + "question": "Any weather alerts in Washington", + "verbose": true + } +} +``` + +代理使用 `tools` 数组中指定的 OpenSearch 工具和从 MCP 服务器选择的工具(基于您的工具过滤器)返回答案: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "memory_id", + "result": "MfiZfpYBjoQOEoSH13wj" + }, + { + "name": "parent_interaction_id", + "result": "MviZfpYBjoQOEoSH13xC" + }, + { + "name": "response", + "result": "{\"id\":\"chatcmpl-BRRcdxVjkrKG7HjkVWZVwueJSEjgd\",\"object\":\"chat.completion\",\"created\":1.745880735E9,\"model\":\"gpt-4o-2024-08-06\",\"choices\":[{\"index\":0.0,\"message\":{\"role\":\"assistant\",\"tool_calls\":[{\"id\":\"call_yWg0wk4mfE2v8ARebupfbJ87\",\"type\":\"function\",\"function\":{\"name\":\"get_alerts\",\"arguments\":\"{\\\"state\\\":\\\"WA\\\"}\"}}],\"annotations\":[]},\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":201.0,\"completion_tokens\":16.0,\"total_tokens\":217.0,\"prompt_tokens_details\":{\"cached_tokens\":0.0,\"audio_tokens\":0.0},\"completion_tokens_details\":{\"reasoning_tokens\":0.0,\"audio_tokens\":0.0,\"accepted_prediction_tokens\":0.0,\"rejected_prediction_tokens\":0.0}},\"service_tier\":\"default\",\"system_fingerprint\":\"fp_f5bdcc3276\"}" + }, + { + "name": "response", + "result": "[{\"text\":\"\\nEvent: Wind Advisory\\nArea: Kittitas Valley\\nSeverity: Moderate\\nDescription: * WHAT...Northwest winds 25 to 35 mph with gusts up to 45 mph\\nexpected.\\n\\n* WHERE...Kittitas Valley.\\n\\n* WHEN...From 2 PM to 8 PM PDT Tuesday.\\n\\n* IMPACTS...Gusty winds will blow around unsecured objects. Tree\\nlimbs could be blown down and a few power outages may result.\\nInstructions: Winds this strong can make driving difficult, especially for high\\nprofile vehicles. Use extra caution.\\n\"}]" + }, + { + "name": "response", + "result": "There is a Wind Advisory for the Kittitas Valley in Washington. Here are the details:\n\n- **Event:** Wind Advisory\n- **Area:** Kittitas Valley\n- **Severity:** Moderate\n- **Description:** Northwest winds 25 to 35 mph with gusts up to 45 mph expected.\n- **When:** From 2 PM to 8 PM PDT Tuesday.\n- **Impacts:** Gusty winds may blow around unsecured objects, potentially causing tree limbs to fall, and resulting in a few power outages.\n\n**Instructions:** These strong winds can make driving difficult, especially for high-profile vehicles. Use extra caution if you are traveling in the area." + } + ] + } + ] +} +``` + +## 其他资源 + +* 有关 MCP 协议的更多信息,请参阅 [MCP 协议文档](https://modelcontextprotocol.io/introduction)。 +* 有关在 Java 中使用 MCP 的信息,请参阅 [MCP Java SDK](https://github.com/modelcontextprotocol/java-sdk)。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/connector-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/connector-tool.md new file mode 100644 index 00000000..e2ecd0a7 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/connector-tool.md @@ -0,0 +1,163 @@ +--- +title: 连接器工具 +--- + +<!-- vale off --> +# 连接器工具 +<Badge type="tip" text="2.15 版本引入" /> + +<!-- vale on --> + +`ConnectorTool` 使用[连接器](/ml-commons-plugin/remote-models/connectors)来调用任何 REST API 功能。例如,您可以使用 `ConnectorTool` 通过其 REST API 接口调用 Lambda 函数。 + +## 步骤 1:注册带有执行操作的连接器 + +`ConnectorTool` 只能在连接器内运行 `execute` 操作。在创建 `ConnectorTool` 之前,您需要配置连接器并在 `actions` 数组中提供 `execute` 操作。`execute` 操作用于调用 REST API 端点上的函数。它类似于 `predict` 操作,后者用于调用机器学习(ML)模型。 + +在本示例中,您将为一个简单的 AWS Lambda 函数创建连接器,该函数接受两个整数并返回它们的和。该函数托管在专用端点上,具有特定的 URL,您将在 `url` 参数中提供。有关更多信息,请参阅 [Lambda 函数 URL](https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html)。 + +要创建连接器,请发送以下请求: + +```json +POST _plugins/_ml/connectors/_create +{ + "name": "Lambda connector of simple calculator", + "description": "Demo connector of lambda function", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "<YOUR AWS REGION>", + "service_name": "lambda" + }, + "credential": { + "access_key": "<YOUR ACCESS KEY>", + "secret_key": "<YOUR SECRET KEY>", + "session_token": "<YOUR SESSION TOKEN>" + }, + "actions": [ + { + "action_type": "execute", + "method": "POST", + "url": "<YOUR LAMBDA FUNCTION URL>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"number1\":\"${parameters.number1}\", \"number2\":\"${parameters.number2}\" }" + } + ] +} +``` + +OpenSearch 返回一个连接器 ID: + +```json +{ + "connector_id": "Zz1XEJABXWrLmr4mewEF" +} +``` + +## 步骤 2:注册将运行 ConnectorTool 的流式代理 + +在本示例中,Lambda 函数将两个输入数字相加,并在 `result` 字段中返回它们的和: + +```json +{ + "result": 5 +} +``` + +默认情况下,`ConnectorTool` 期望来自 Lambda 函数的响应包含一个名为 `response` 的字段。但是,在本示例中,Lambda 函数响应不包含 `response` 字段。要从 `result` 字段中检索结果,您需要提供一个 `response_filter`,指定指向 `result` 字段的 [JSON 路径](https://github.com/json-path/JsonPath) (`$.result`)。使用 `response_filter`,`ConnectorTool` 将使用指定的 JSON 路径检索结果,并在 `response` 字段中返回它。 + +要配置 Lambda 函数工作流程,请创建一个流式代理。流式代理按顺序运行一系列工具,并返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求,提供上一步的连接器 ID 和 `response_filter`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Demo agent of Lambda connector", + "type": "flow", + "description": "This is a demo agent", + "app_type": "demo", + "tools": [ + { + "type": "ConnectorTool", + "name": "lambda_function", + "parameters": { + "connector_id": "Zz1XEJABXWrLmr4mewEF", + "response_filter": "$.result" + } + } + ] +} +``` + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "az1XEJABXWrLmr4miAFj" +} +``` + +## 步骤 3:运行代理 + +然后,通过发送以下请求运行代理: + +```json +POST /_plugins/_ml/agents/az1XEJABXWrLmr4miAFj/_execute +{ + "parameters": { + "number1": 2, + "number2": 3 + } +} +``` + +OpenSearch 返回 Lambda 函数执行的输出。在输出中,字段名称为 `response`,`result` 字段包含 Lambda 函数结果: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": 5 + } + ] + } + ] +} +``` + +## 注册参数 + +下表列出了注册代理时可用的所有工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`connector_id` | 字符串 | 必需 | 配置了调用 API 的 `execute` 操作的连接器的连接器 ID。 +`response_filter` | 字符串 | 可选 | 包含调用 API 结果的响应字段的 [JSON 路径](https://github.com/json-path/JsonPath)。如果未指定 `response_filter`,则 `ConnectorTool` 期望 API 响应位于名为 `response` 的字段中。 + +## 执行参数 + +运行代理时,您可以在连接器的 `execute` 操作的 `request_body` 中定义 API 调用所需的任何参数。在本示例中,参数为 `number1` 和 `number2`: + +```json +"actions": [ + { + "action_type": "execute", + "method": "POST", + "url": "<YOUR LAMBDA FUNCTION URL>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"number1\":\"${parameters.number1}\", \"number2\":\"${parameters.number2}\" }" + } + ] +``` + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/create-anomaly-detector.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/create-anomaly-detector.md new file mode 100644 index 00000000..6047ac15 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/create-anomaly-detector.md @@ -0,0 +1,162 @@ +--- +title: 创建异常检测器工具 +--- + +<!-- vale off --> +# 创建异常检测器工具 +<Badge type="tip" text="2.16 版本引入" /> + +<!-- vale on --> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/skills/issues/337)。 +::: + +`CreateAnomalyDetectorTool` 帮助根据您提供的索引创建异常检测器。此工具检索索引映射,并使大语言模型(LLM)能够推荐类别字段、聚合字段及其相应的聚合方法,这些都是创建异常检测器 API 所需的。 + +::: tip TIP +有关异常检测器的全面信息,请参阅[异常检测](/observing-your-data/ad/)。 +::: + +## 步骤 1:注册将运行 CreateAnomalyDetectorTool 的流式代理 + +流式代理按顺序运行一系列工具,返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Create_Anomaly_Detector_Tool", + "type": "flow", + "description": "this is a test agent for the CreateAnomalyDetectorTool", + "tools": [ + { + "type": "CreateAnomalyDetectorTool", + "name": "DemoCreateAnomalyDetectorTool", + "parameters": { + "model_id": "<the model id of LLM>" + } + } + ] +} +``` + +OpenSearch 返回一个代理 ID,例如: + +```json +{ + "agent_id": "EuJYYo0B9RaBCvhuy1q8" +} +``` + +## 步骤 2:运行代理 + +通过发送以下请求运行代理: + +```json +POST /_plugins/_ml/agents/EuJYYo0B9RaBCvhuy1q8/_execute +{ + "parameters": { + "index": "sample_weblogs_test" + } +} +``` + +OpenSearch 返回一个 JSON 字符串,其中包含创建异常检测器的所有推荐参数,例如以下示例响应中所示的字符串: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result":"""{"index":"sample_weblogs_test","categoryField":"ip.keyword","aggregationField":"bytes,response,responseLatency","aggregationMethod":"sum,avg,avg","dateFields":"utc_time,timestamp"}""" + } + ] + } + ] +} +``` + +然后,您可以通过发送类似以下的请求来创建包含推荐参数的异常检测器: + +```json +POST _plugins/_anomaly_detection/detectors +{ + "name": "test-detector", + "description": "Test detector", + "time_field": "timestamp", + "indices": [ + "sample_weblogs_test" + ], + "feature_attributes": [ + { + "feature_name": "feature_bytes", + "feature_enabled": true, + "aggregation_query": { + "agg1": { + "sum": { + "field": "bytes" + } + } + } + }, + { + "feature_name": "feature_response", + "feature_enabled": true, + "aggregation_query": { + "agg2": { + "avg": { + "field": "response" + } + } + } + }, + { + "feature_name": "feature_responseLatency", + "feature_enabled": true, + "aggregation_query": { + "agg3": { + "avg": { + "field": "responseLatency" + } + } + } + } + ], + "detection_interval": { + "period": { + "interval": 1, + "unit": "Minutes" + } + }, + "window_delay": { + "period": { + "interval": 1, + "unit": "Minutes" + } + } +} +``` + +## 注册参数 + +下表列出了代理注册时可用的工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`model_id` | 字符串 | 必需 | 用于建议所需创建异常检测器 API 参数的 LLM 模型 ID。 +`model_type` | 字符串 | 可选 | 模型类型。有效值为 `CLAUDE`(Anthropic Claude 模型)和 `OPENAI`(OpenAI 模型)。默认为 `CLAUDE`。模型类型决定发送给 LLM 的默认提示。 +`prompt` | 字符串 | 可选 | 工具发送给 LLM 的自定义提示。如果未指定,工具将使用指定 `model_type` 的默认提示。 + +## 执行参数 + +下表列出了运行代理时可用的工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`index` | 字符串 | 必需 | 索引名称。支持通配符(例如,`weblogs-*`)。如果使用通配符,则工具会从第一个解析的索引获取映射并将其发送给 LLM。 + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/data-distribution-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/data-distribution-tool.md new file mode 100644 index 00000000..6e2d7f0a --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/data-distribution-tool.md @@ -0,0 +1,199 @@ +--- +title: 数据分布工具 +--- + +<!-- vale off --> +# 数据分布工具 +<Badge type="tip" text="3.3.0 版本引入" /> + +<!-- vale on --> + +`DataDistributionTool` 分析数据集中的数据分布模式,并比较不同时间段之间的分布。它支持单个数据集分析和比较分析,以识别字段值分布中的重大变化,帮助检测异常、趋势和数据质量问题。 + +该工具支持[查询领域特定语言(DSL)](/query-dsl/)和[管道处理语言(PPL)](/search-plugins/sql/ppl/)查询,以灵活地检索和过滤数据。 + +## 分析模式 + +工具会根据提供的参数自动选择适当的分析模式: + +- **比较分析**:当同时提供基线和选择时间范围时,工具会比较两个时期之间的字段分布,以识别重大变化和差异。 +- **单个数据集分析**:当仅提供选择时间范围时,工具会分析数据集中的分布模式,以提供有关字段值频率和特征的见解。 + +## 步骤 1:注册将运行 DataDistributionTool 的流式代理 + +流式代理按顺序运行一系列工具,返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Data_Distribution_Tool", + "type": "flow", + "description": "this is a test agent for the DataDistributionTool", + "tools": [ + { + "type": "DataDistributionTool", + "parameters": {} + } + ] +} +``` + +注册工具不需要任何参数。工具在执行时使用动态参数验证。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "OQutgJYBAc35E4_KvI1q" +} +``` + +## 步骤 2:运行代理 + +运行代理以执行比较分布分析或单个数据集分布分析。 + +### 比较分析 + +要在两个时间段之间执行比较分布分析,请提供基线和选择时间范围: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "logs-2025.01.15", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "baselineTimeRangeStart": "2025-01-15 08:00:00", + "baselineTimeRangeEnd": "2025-01-15 09:00:00", + "size": 1000, + "queryType": "dsl", + "filter": ["{\"term\": {\"status\": \"error\"}}", "{\"range\": {\"response_time\": {\"gte\": 100}}}"] + } +} +``` + +OpenSearch 返回按字段比较,显示时间段之间的分布变化: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"comparisonAnalysis\":[{\"field\":\"response_time\",\"divergence\":0.6666666666666667,\"topChanges\":[{\"value\":\"120\",\"selectionPercentage\":0.33,\"baselinePercentage\":1.0},{\"value\":\"200\",\"selectionPercentage\":0.67,\"baselinePercentage\":0.0}]},{\"field\":\"host\",\"divergence\":0.33333333333333337,\"topChanges\":[{\"value\":\"web-1\",\"selectionPercentage\":0.67,\"baselinePercentage\":1.0},{\"value\":\"web-2\",\"selectionPercentage\":0.33,\"baselinePercentage\":0.0}]}]}" + } + ] + } + ] +} +``` + +### 单个数据集分析 + +要执行单个数据集分布分析,只需提供选择时间范围: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "application_logs", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "size": 1000, + "queryType": "dsl" + } +} +``` + +OpenSearch 返回分析数据集的分布模式: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"singleAnalysis\":[{\"field\":\"status\",\"divergence\":0.7,\"topChanges\":[{\"value\":\"success\",\"selectionPercentage\":0.7,\"baselinePercentage\":null},{\"value\":\"error\",\"selectionPercentage\":0.3,\"baselinePercentage\":null}]},{\"field\":\"host\",\"divergence\":0.6,\"topChanges\":[{\"value\":\"web-1\",\"selectionPercentage\":0.6,\"baselinePercentage\":null},{\"value\":\"web-2\",\"selectionPercentage\":0.4,\"baselinePercentage\":null}]}]}" + } + ] + } + ] +} +``` + +## 使用 PPL 查询 + +使用 PPL 进行数据检索来运行代理: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "logs-2025.01.15", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "size": 1000, + "queryType": "ppl", + "ppl": "source=logs-2025.01.15 | where status='error'" + } +} +``` + +## 使用自定义 DSL 查询 + +使用完整的自定义 DSL 查询运行代理: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "logs-2025.01.15", + "timeField": "@timestamp", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00", + "size": 1000, + "queryType": "dsl", + "dsl": "{\"bool\": {\"must\": [{\"term\": {\"status\": \"error\"}}], \"filter\": [{\"range\": {\"response_time\": {\"gte\": 100}}}]}}" + } +} +``` + +## 执行参数 + +下表列出了运行代理时可用的工具参数。 + +| 参数 | 类型 | 必需/可选 | 描述 | +|:----------|:-----|:------------------|:------------| +| `index` | 字符串 | 必需 | 包含要分析的数据的 OpenSearch 索引名称。 | +| `timeField` | 字符串 | 可选 | 用于基于时间过滤的日期/时间字段。默认为 `@timestamp`。 | +| `selectionTimeRangeStart` | 字符串 | 必需 | 分析时段的开始时间,使用 UTC 日期字符串格式(例如,`2025-01-15 10:00:00`)。 | +| `selectionTimeRangeEnd` | 字符串 | 必需 | 分析时段的结束时间,使用 UTC 日期字符串格式(例如,`2025-01-15 11:00:00`)。 | +| `baselineTimeRangeStart` | 字符串 | 可选 | 基线比较时段的开始时间,使用 UTC 日期字符串格式(例如,`2025-01-15 10:00:00`)。比较分析模式必需。 | +| `baselineTimeRangeEnd` | 字符串 | 可选 | 基线比较时段的结束时间,使用 UTC 日期字符串格式(例如,`2025-01-15 11:00:00`)。比较分析模式必需。 | +| `size` | 整数 | 可选 | 要分析的最大文档数。默认为 `1000`。最大为 `10000`。 | +| `queryType` | 字符串 | 可选 | 查询类型。有效值为 `ppl` 和 `dsl`。默认为 `dsl`。 | +| `filter` | 数组 | 可选 | 用于过滤的附加 DSL 查询条件,指定为 JSON 字符串(例如,`["{\"term\": {\"status\": \"error\"}}", "{\"range\": {\"level\": {\"gte\": 3}}}"]`)。 | +| `dsl` | 字符串 | 可选 | 完整的原始 DSL 查询,作为 JSON 字符串。如果提供,则优先于 `filter` 参数。 | +| `ppl` | 字符串 | 可选 | 不包含时间信息的完整 PPL 语句。当 `queryType` 为 `ppl` 时使用。 | + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 + +## 限制 + +数据分布工具有以下限制: + +- **最大文档量**:工具每次执行的默认限制为 1,000 个文档,最大可配置限制为 10,000 个文档(`MAX_SIZE_LIMIT = 10000`)。 +- **字段基数限制**:高基数字段会被自动过滤以确保有意义的分析结果: + - ID 字段:最多 30 个唯一值。 + - 数据字段:最多 10 个唯一值(或数据集大小 ÷ 2,以较大者为准)。 +- **结果限制**: + - 比较分析:返回前 10 个字段差异。 + - 单个数据集分析:返回前 30 个字段分布。 + - 每个字段的主要变化:限制为 10 项。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/list-index-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/list-index-tool.md new file mode 100644 index 00000000..972bac80 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/list-index-tool.md @@ -0,0 +1,111 @@ +--- +title: 列出索引工具 +--- + +<!-- vale off --> +# 列出索引工具 +<Badge type="tip" text="3.0 版本引入" /> + +<!-- vale on --> + +`ListIndexTool` 检索 OpenSearch 集群的索引信息,类似于 [List Indices API](/api-reference/list/list-indices)。 + +::: info NOTE +从 OpenSearch 3.0 版本开始,`ListIndexTool` 取代了 `CatIndexTool`。 +::: + +## 步骤 1:注册将运行 ListIndexTool 的流式代理 + +流式代理按顺序运行一系列工具,并返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_ListIndex_tool", + "type": "flow", + "description": "this is a test agent for the ListIndexTool", + "tools": [ + { + "type": "ListIndexTool", + "name": "DemoListIndexTool", + "parameters": { + "input": "${parameters.question}" + } + } + ] +} +``` + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +## 步骤 2:运行代理 + +在运行代理之前,请确保您已添加示例 OpenSearch Dashboards 的 `Sample eCommerce orders` 数据集。要了解更多信息,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。 + +然后,通过发送以下请求运行代理: + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How many indices do I have?" + } +} +``` + +OpenSearch 返回索引信息: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,.plugins-ml-model-group,lHgGEgJhT_mpADyOZoXl2g,1,0,9,2,16.7kb,16.7kb +2,green,open,.plugins-ml-config,G7gxGQB7TZeQzBasHd5PUg,1,0,1,0,3.9kb,3.9kb +3,green,open,sample-ecommerce,UPYOQcAfRGqFAlSxcZlRjw,1,0,40320,0,2mb,2mb +4,green,open,.plugins-ml-model,WYcjBHcnRuSDHeVWPVupoA,1,0,191,45,2.1gb,2.1gb +5,green,open,opensearch_dashboards_sample_data_ecommerce,wnE6r7OvSPqc5YHj8wHSLA,1,0,4675,0,4.9mb,4.9mb +... +""" + } + ] + } + ] +} +``` + +## 注册参数 + +下表列出了注册代理时可用的所有工具参数。 + +<!-- vale off --> +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`indices` | 数组 | 可选 | 要在其上运行列出索引操作的一个或多个索引的数组,指定为 JSON 数组(例如,`["index1", "index2"]`)。默认为空数组,表示所有索引。 +`local` | 布尔值 | 可选 | 当为 `true` 时,仅从本地节点检索信息,而不是从集群管理器节点检索。默认为 `false`。 +`page_size` | 整数 | 可选 | 指定使用 List Indices API 时每页返回的索引结果数。API 以分页方式检索索引状态。默认为 `100`。 +`include_unloaded_segments` | 布尔值 | 可选 | 当为 `true` 时,索引统计信息包括未加载到内存中的段的信息。默认为 `false`。 +<!-- vale on --> + +## 执行参数 + +下表列出了运行代理时可用的所有工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`question` | 字符串 | 必需 | 要发送给 LLM 的自然语言问题。 + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool.md new file mode 100644 index 00000000..7f60f9c2 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/log-pattern-analysis-tool.md @@ -0,0 +1,229 @@ +--- +title: 日志模式分析工具 +--- + +<!-- vale off --> +# 日志模式分析工具 +<Badge type="tip" text="3.3.0 版本引入" /> + +<!-- vale on --> + +`LogPatternAnalysisTool` 通过在基线和选择时间范围之间进行比较分析来检测异常的日志模式和序列,从而执行高级日志分析。它支持以下分析模式: + +- 日志序列分析(带跟踪关联) +- 日志模式差异分析 +- 用于错误检测的日志洞察分析 + +该工具使用机器学习聚类算法和统计方法来识别在选择时段与基线时段相比出现频率明显更高的异常模式,帮助检测系统问题和性能异常。 + +## 分析模式 + +工具会根据提供的参数自动选择适当的分析模式: + +- **日志序列分析**:当同时提供跟踪字段和基线时间范围时,工具会分析跟踪关联的日志序列,以识别异常的执行路径。 +- **日志模式差异分析**:当提供基线时间范围但没有跟踪字段时,工具会比较基线和选择时段之间的日志模式,以检测异常模式。 +- **日志洞察分析**:当仅提供选择时间范围时,工具会基于错误关键字执行模式分析,以识别关键问题。 + +## 步骤 1:注册将运行 LogPatternAnalysisTool 的流式代理 + +流式代理按顺序运行一系列工具,返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Log_Pattern_Analysis_Tool", + "type": "flow", + "description": "this is a test agent for the LogPatternAnalysisTool", + "tools": [ + { + "type": "LogPatternAnalysisTool", + "parameters": {} + } + ] +} +``` + +注册工具不需要任何参数。工具在执行时使用动态参数验证。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "OQutgJYBAc35E4_KvI1q" +} +``` + +## 步骤 2:运行代理 + +运行代理以执行各种类型的分析。 + +这些示例使用固定的时间范围。要在您自己的数据上运行示例,请将 `index` 设置为您的日志索引,并将时间范围参数设置为该索引中时间戳范围内的时间。要查找最早和最新的时间戳,请在时间字段上运行 `min` 和 `max` 聚合: + +```json +GET /opensearch_dashboards_sample_data_logs/_search +{ + "size": 0, + "aggs": { + "earliest": { "min": { "field": "@timestamp" } }, + "latest": { "max": { "field": "@timestamp" } } + } +} +``` + +`value_as_string` 字段包含最早和最新的时间戳: + +```json +{ + ... + "aggregations": { + "earliest": { + "value": 1.791074342912E12, + "value_as_string": "2026-10-04T00:39:02.912Z" + }, + "latest": { + "value": 1.796334326749E12, + "value_as_string": "2026-12-03T21:45:26.749Z" + } + } +} +``` + +以 `yyyy-MM-dd HH:mm:ss` 格式提供时间范围参数,例如 `2026-10-04 00:00:00`。 + +### 日志序列分析 + +要执行基于跟踪的序列分析,请提供 `traceFieldName`、`baseTimeRangeStart` 和 `baseTimeRangeEnd`: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "ss4o_logs-otel-2025.06.24", + "timeField": "@timestamp", + "logFieldName": "body", + "traceFieldName": "traceId", + "baseTimeRangeStart": "2025-06-24 07:33:05", + "baseTimeRangeEnd": "2025-06-24 07:51:27", + "selectionTimeRangeStart": "2025-06-24 07:50:26", + "selectionTimeRangeEnd": "2025-06-24 07:55:56" + } +} +``` + +OpenSearch 返回与基线模式显著不同的异常跟踪序列: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"EXCEPTIONAL\": {\"trace456\": \"User login -> Database timeout -> Error handling -> Retry -> Response sent\"}, \"BASE\": {\"trace123\": \"User login -> Database query -> Response sent\"}}" + } + ] + } + ] +} +``` + +### 日志模式差异分析 + +以下示例使用 OpenSearch Dashboards 示例 Web 日志。要添加示例 Web 日志,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。当您添加示例数据时,OpenSearch Dashboards 会相对于您添加数据的日期移动其时间戳,因此您的副本不包含本示例中使用的 2018 年日期。将 `2018-07-22` 替换为前面聚合返回的最早时间戳的日期。 + +要执行模式比较分析,请提供 `baseTimeRangeStart` 和 `baseTimeRangeEnd`: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "opensearch_dashboards_sample_data_logs", + "timeField": "@timestamp", + "logFieldName": "message", + "baseTimeRangeStart": "2018-07-22 00:00:00", + "baseTimeRangeEnd": "2018-07-22 12:00:00", + "selectionTimeRangeStart": "2018-07-22 12:00:00", + "selectionTimeRangeEnd": "2018-07-22 23:59:59" + } +} +``` + +OpenSearch 返回时间段之间频率发生重大变化的模式。`base` 和 `selection` 字段包含在基线和选择时间范围内匹配模式的日志比例,`lift` 是较大比例与较小比例的比率。工具返回 `lift` 大于 3 的模式以及仅出现在选择时间范围内的模式。仅出现在选择时间范围内的模式的 `base` 为 `0.0`,`lift` 为 `null`,如以下响应所示: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"patternMapDifference\":[{\"pattern\":\"<*IP*> - - [<*DATETIME*>] \\\"GET <*> HTTP/<*>\\\" <*> 0 \\\"-\\\" \\\"Mozilla/<*> (<*>; Linux <*>_<*>; rv:<*>) Gecko/<*> Firefox/<*>\\\"\",\"base\":0.0,\"selection\":0.4224137931034483,\"lift\":null},{\"pattern\":\"<*IP*> - - [<*DATETIME*>] \\\"GET <*> HTTP/<*>\\\" 200 <*> \\\"-\\\" \\\"Mozilla/<*> (compatible; MSIE 6<*>; Windows NT 5<*>; <*>; .NET CLR 1<*>)\\\"\",\"base\":0.0,\"selection\":0.27586206896551724,\"lift\":null}]}" + } + ] + } + ] +} +``` + +### 日志洞察分析 + +要执行错误模式检测,只需提供选择时间范围: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "index": "application_logs", + "timeField": "@timestamp", + "logFieldName": "message", + "selectionTimeRangeStart": "2025-01-15 10:00:00", + "selectionTimeRangeEnd": "2025-01-15 11:00:00" + } +} +``` + +OpenSearch 返回带有示例日志的错误模式: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"logInsights\":[{\"pattern\":\"<*DATETIME*> ERROR User <*> authentication failed\",\"count\":23.0,\"sampleLogs\":[\"2025-01-15 10:30:15 ERROR User user123 authentication failed\",\"2025-01-15 10:32:08 ERROR User admin456 authentication failed\",\"2025-01-15 10:35:42 ERROR User user789 authentication failed\"]}]}" + } + ] + } + ] +} +``` + +## 执行参数 + +下表列出了运行代理时可用的工具参数。 + +| 参数 | 类型 | 必需/可选 | 描述 | +|:----------|:-----|:------------------|:------------| +| `index` | 字符串 | 必需 | 包含日志数据的 OpenSearch 索引名称(例如,`ss4o_logs-otel-2025.06.24`)。 | +| `timeField` | 字符串 | 可选 | 索引映射中用于基于时间过滤的日期/时间字段。默认为 `@timestamp`。 | +| `logFieldName` | 字符串 | 可选 | 包含要分析的原始日志消息的字段(例如,`body`、`message` 或 `log`)。默认为 `message`。 | +| `traceFieldName` | 字符串 | 可选 | 包含跟踪 ID 或关联 ID 的字段,用于启用序列分析(例如,`traceId` 或 `correlationId`)。日志序列分析模式必需。 | +| `baseTimeRangeStart` | 字符串 | 可选 | 基线比较时段的开始时间,使用 UTC 日期字符串格式(例如,`2025-06-24 07:33:05`)。序列和模式差异分析模式必需。 | +| `baseTimeRangeEnd` | 字符串 | 可选 | 基线比较时段的结束时间,使用 UTC 日期字符串格式(例如,`2025-06-24 07:51:27`)。序列和模式差异分析模式必需。 | +| `selectionTimeRangeStart` | 字符串 | 必需 | 分析目标时段的开始时间,使用 UTC 日期字符串格式(例如,`2025-06-24 07:50:26`)。 | +| `selectionTimeRangeEnd` | 字符串 | 必需 | 分析目标时段的结束时间,使用 UTC 日期字符串格式(例如,`2025-06-24 07:55:56`)。 | +| `filter` | 字符串 | 可选 | 在分析之前过滤日志的 PPL 布尔表达式(例如,`severity='ERROR'`)。工具将其应用为附加的 `where` 子句。在日志序列分析模式中不应用,该模式需要跟踪中的所有日志。 | + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 + +## 限制 + +日志模式分析工具有以下限制: + +- **日志量**:工具通过 PPL 查询处理日志,每个查询的最大限制为 10,000 个文档。为获得最佳性能,请将分析限制在特定的时间范围内。 +- **结果限制**: + - 模式差异分析:返回最多 10 个具有最高 `lift` 的模式和最多 10 个仅出现在选择时间范围内的模式。 + - 日志洞察分析:返回前 5 个错误模式,每个最多 5 个示例日志。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/log-pattern-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/log-pattern-tool.md new file mode 100644 index 00000000..ab932981 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/log-pattern-tool.md @@ -0,0 +1,118 @@ +--- +title: 日志模式工具 +--- + +<!-- vale off --> +# 日志模式工具 +<Badge type="tip" text="2.19 版本引入" /> + +<!-- vale on --> + +`LogPatternTool` 分析使用[查询领域特定语言(DSL)](/query-dsl/)或[管道处理语言(PPL)](/search-plugins/sql/ppl/)查询检索的日志数据,以提取和识别日志消息中重复出现的结构模式。在根据共享模板对相似日志进行分组后,它会返回最常见的模式。每个模式包括代表性的示例日志以及数据集中与该模式匹配的日志条目总数。 + +OpenSearch 根据请求中存在的 `input` 或 `ppl` 参数来确定您使用的是 DSL 还是 PPL 查询: + +- 如果存在 `input` 参数(DSL 查询 JSON 作为字符串),工具将请求解释为 DSL 查询。 + +- 如果存在 `ppl` 参数且不存在 `input`,工具将请求解释为 PPL 查询。 + +- 如果两者都提供,工具将优先使用 DSL 查询。 + +为避免歧义,在运行代理时,请求中仅提供两者之一——`input` 用于 DSL,`ppl` 用于 PPL。 + +## 步骤 1:注册将运行 LogPatternTool 的流式代理 + +流式代理按顺序运行一系列工具,返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_Log_Pattern_Tool", + "type": "flow", + "description": "this is a test agent for the LogPatternTool", + "tools": [ + { + "type": "LogPatternTool", + "parameters": { + "sample_log_size": 1 + } + } + ] +} +``` + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "OQutgJYBAc35E4_KvI1q" +} +``` + +## 步骤 2:运行代理 + +以下示例搜索 OpenSearch Dashboards 示例 Web 日志。要添加示例 Web 日志,请参阅[添加示例数据](/dashboards/getting-started/data-setup#add-sample-data)。该查询不按时间过滤,因此无论何时添加示例数据,它都会返回示例响应中显示的模式。要在您自己的日志上运行示例,请更改 `index` 和查询。 + +通过发送以下请求运行代理: + +```json +POST /_plugins/_ml/agents/OQutgJYBAc35E4_KvI1q/_execute +{ + "parameters": { + "input": "{\"query\":{\"bool\":{\"filter\":[{\"range\":{\"bytes\":{\"from\":10,\"to\":null,\"include_lower\":true,\"include_upper\":true,\"boost\":1}}}],\"adjust_pure_negative\":true,\"boost\":1}}}", + "index": "opensearch_dashboards_sample_data_logs" + } +} +``` + +OpenSearch 返回一个 JSON 响应,其中包含在您的数据中找到的最常见日志模式,最多达到指定的限制。每个识别的模式都表示为一个 JSON 对象,具有三个关键组件:模式模板、一组与模式匹配的代表性示例日志以及一个计数,指示该模式在数据集中出现的频率。结构遵循格式 `{"pattern": "...", "sample logs": [...], "total count": N}`,如以下示例响应所示: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result":"""[{"pattern":"<*IP*> - - [<*DATETIME*>] "GET <*> HTTP/<*><*>\" 200 <*> \"-\" \"Mozilla/<*><*> (<*>; Linux <*>_<*>; rv:<*><*><*>) Gecko/<*> Firefox/<*><*><*>\"","sample logs":["223.87.60.27 - - [2018-07-22T00:39:02.912Z] \"GET /opensearch/opensearch-1.0.0.deb_1 HTTP/1.1\" 200 6219 \"-\" \"Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1\""],"total count":367},{"pattern":"<*IP*> - - [<*DATETIME*>] \"GET <*> HTTP/<*><*>\" 200 <*> \"-\" \"Mozilla/<*><*> (<*>; Linux <*>) AppleWebKit/<*><*> (KHTML like Gecko) Chrome<*IP*> Safari/<*><*>\"","sample logs":["216.9.22.134 - - [2018-07-22T05:27:11.939Z] \"GET /beats/metricbeat_1 HTTP/1.1\" 200 3629 \"-\" \"Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24\""],"total count":311},{"pattern":"<*IP*> - - [<*DATETIME*>] \"GET <*> HTTP/<*><*>\" 200 <*> \"-\" \"Mozilla/<*><*> (compatible; MSIE 6<*>; Windows NT 5<*>; <*>; .NET CLR 1<*><*>)\"","sample logs":["99.74.118.237 - - [2018-07-22T03:34:43.399Z] \"GET /beats/metricbeat/metricbeat-6.3.2-amd64.deb_1 HTTP/1.1\" 200 14113 \"-\" \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\""],"total count":269}]""" + } + ] + } + ] +} +``` + +## 注册参数 + +下表列出了代理注册时可用的工具参数。 + +| 参数 | 类型 | 必需/可选 | 描述 | +|:-----------------|:---------|:-------------------------------------------------|:------------| +| `index` | 字符串 | DSL 查询必需 | 要搜索以进行模式分析的索引。 | +| `input` | 字符串 | DSL 查询必需 | DSL 查询 JSON 作为字符串。如果同时提供 `input` 和 `ppl`,则使用 `input`(DSL)。 | +| `ppl` | 字符串 | PPL 查询必需 | PPL 查询字符串。如果也提供了 `input`,则忽略。 | +| `source_field` | 字符串 | 可选 | 要在结果中返回的字段。可以是单个字段或数组(例如,`["field1", "field2"]`)。 | +| `doc_size` | 整数 | 可选 | 要获取的文档数。默认为 `1000`。 | +| `top_n_pattern` | 整数 | 可选 | 将输出限制为指定数量的最频繁模式。默认为 `3`。 | +| `sample_log_size`| 整数 | 可选 | 每个模式包含的示例日志数。默认为 `20`。 | +| `pattern_field` | 字符串 | 可选 | 要分析以进行模式检测的字段。如果未指定,工具会从第一个文档中选择最长的文本字段。 | +| `variable_count_threshold` | 整数 | 可选 | 日志解析器在将日志分组为模式时用于识别变量标记的阈值。默认为 `5`。 | + +## 执行参数 + +下表列出了运行代理时可用的工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- |:-----------------------| :--- +| `index` | 字符串 | DSL 查询必需 | 要搜索以进行模式分析的索引。 | +| `input` | 字符串 | DSL 查询必需 | DSL 查询 JSON 作为字符串。如果同时提供 `input` 和 `ppl`,则 `input`(DSL)优先。 | +| `ppl` | 字符串 | PPL 查询必需 | PPL 查询字符串。如果也提供了 `input`,则忽略。 | +| `top_n_pattern` | 整数 | 可选 | 将输出限制为指定数量的最频繁模式。覆盖注册期间设置的值。 | +| `sample_log_size` | 整数 | 可选 | 每个模式包含的示例日志数。覆盖注册期间设置的值。 | +| `pattern_field` | 字符串 | 可选 | 要分析以进行模式检测的字段。覆盖注册期间设置的值。 | + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/query-planning-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/query-planning-tool.md new file mode 100644 index 00000000..b7817f27 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/query-planning-tool.md @@ -0,0 +1,719 @@ +--- +title: 查询规划工具 +--- + +<!-- vale off --> +# 查询规划工具 +<Badge type="tip" text="3.3 版本引入" /> + +<!-- vale on --> + +`QueryPlanningTool` 从自然语言问题生成 OpenSearch 查询领域特定语言(DSL)查询。它是[代理搜索](/vector-search/ai-search/agentic-search/index/)的核心组件,通过代理驱动的工作流程实现自然语言查询处理。 + +`QueryPlanningTool` 支持两种从自然语言问题生成 DSL 查询的方法: + +- **仅使用 LLM 知识(默认)**:大语言模型(LLM)仅使用其训练知识和您提供的任何系统/用户提示来生成查询。这种方法完全依赖于模型对 DSL 语法的理解和您特定的提示指令。 + +- **使用搜索模板**:LLM 在生成查询时使用预定义的搜索模板作为附加上下文。您提供一组带有描述的搜索模板,LLM 使用这些作为示例和指导来创建更准确的查询。如果 LLM 确定提供的模板都不适合用户的问题,LLM 会尝试独立生成查询。 + +当您有特定用例或领域的既定查询模式时,使用搜索模板特别有用:它帮助 LLM 生成遵循您首选结构的查询,并使用索引映射中的适当字段名称。 + +## 步骤 1:创建索引并摄取示例数据 + +首先,为 `iris` 数据集创建一个索引: + +```json +PUT /iris-index +{ + "mappings": { + "properties": { + "petal_length_in_cm": { + "type": "float" + }, + "petal_width_in_cm": { + "type": "float" + }, + "sepal_length_in_cm": { + "type": "float" + }, + "sepal_width_in_cm": { + "type": "float" + }, + "species": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + } + } + } +} +``` + +接下来,将示例文档摄取到索引中: + +```json +POST _bulk +{ "index": { "_index": "iris-index", "_id": "1" } } +{ "petal_length_in_cm": 1.4, "petal_width_in_cm": 0.2, "sepal_length_in_cm": 5.1, "sepal_width_in_cm": 3.5, "species": "setosa" } +{ "index": { "_index": "iris-index", "_id": "2" } } +{ "petal_length_in_cm": 4.5, "petal_width_in_cm": 1.5, "sepal_length_in_cm": 6.4, "sepal_width_in_cm": 2.9, "species": "versicolor" } +{ "index": { "_index": "iris-index", "_id": "3" } } +{ "petal_length_in_cm": 6.0, "petal_width_in_cm": 2.5, "sepal_length_in_cm": 5.9, "sepal_width_in_cm": 3.0, "species": "virginica" } +``` + +## 步骤 2:注册并部署模型 + +以下请求从 Amazon Bedrock 注册一个远程模型并将其部署到您的集群。API 调用一步创建连接器和模型。将 `region`、`access_key`、`secret_key` 和 `session_token` 替换为您自己的值。您可以使用支持 `converse` API 的任何模型,例如 [Anthropic Claude 4](https://www.anthropic.com/news/claude-4) 或 [GPT 5](https://openai.com/index/introducing-gpt-5)。您可以通过创建到此模型的连接器来使用其他模型提供商(请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors))。 + +**重要**:为 `QueryPlanningTool` 创建连接器时,请求体必须包含 `system_prompt` 和 `user_prompt` 参数。这些参数是工具将系统和用户提示正确注入模型请求所必需的。 + +以下示例注册并部署 Anthropic Claude 4 模型: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Claude 4 Sonnet Query Planner Tool Model", + "function_name": "remote", + "description": "Claude 4 sonnet for Query Planning", + "connector": { + "name": "Bedrock Claude 4 Sonnet Connector", + "description": "Amazon Bedrock connector for Claude 4 Sonnet", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-20250514-v1:0" + }, + "credential": { + "access_key": "your-aws-access-key", + "secret_key": "your-aws-secret-key", + "session_token": "your-aws-session-token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.user_prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] + } +} +``` + +以下示例注册并部署 OpenAI GPT 5 模型: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "My OpenAI model: gpt-5", + "function_name": "remote", + "description": "test model", + "connector": { + "name": "My openai connector: gpt-5", + "description": "The connector to openai chat model", + "version": 1, + "protocol": "http", + "parameters": { + "model": "gpt-5" + }, + "credential": { + "openAI_key": "your-openai-api-key" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.user_prompt}\"}${parameters._interactions:-}], \"reasoning_effort\":\"low\"${parameters.tool_configs:-}}" + } + ] + } +} +``` + +OpenSearch 返回模型 ID: + +```json +{ + "task_id": "_9iSxJgBOh0h20Y9XYTH", + "status": "CREATED", + "model_id": "ANiSxJgBOh0h20Y9XYXl" +} +``` + +## 步骤 3:注册代理 + +您可以使用任何 [OpenSearch 代理类型](/ml-commons-plugin/agents-tools/agents/)来运行 `QueryPlanningTool`。以下示例使用 `flow` 代理,它按顺序运行一系列工具并返回最后一个工具的输出。 + +### 仅使用 LLM 知识 + +要仅使用提示,请不要指定 `generation_type`,以便它默认为 `llmGenerated`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Agentic Search with Claude 4", + "type": "flow", + "description": "A test agent for query planning.", + "tools": [ + { + "type": "QueryPlanningTool", + "parameters": { + "model_id": "ANiSxJgBOh0h20Y9XYXl", + "response_filter": "$.output.message.content[0].text" + } + } + ] +} +``` + +`response_filter` 参数从模型响应中提取生成的查询。没有它,工具会返回完整的模型响应,搜索管道无法将其用作查询。此示例使用通过 Amazon Bedrock Converse API 调用的 Anthropic Claude 模型的过滤器。对于 OpenAI 模型,请使用 `$.choices[0].message.content`。有关更多信息,请参阅[响应过滤器配置](#response-filter-configuration)。 + +工具本身设置 `system_prompt` 和 `user_prompt` 参数,因此在代理注册期间提供的这些参数的值不会被使用。要自定义提示,请指定 `query_planner_system_prompt` 和 `query_planner_user_prompt`。有关更多信息,请参阅[自定义提示](#customizing-the-prompts)。 + +### 使用搜索模板 + +您可以添加[搜索模板](/api-reference/search-apis/search-template/)作为附加上下文,以协助 LLM 生成 OpenSearch DSL。 + +::: tip TIP +使用这种方法,LLM 仍然编写完整的查询。要让 LLM 仅填充模板参数,而 OpenSearch 渲染查询,请参阅[填充搜索模板](/vector-search/ai-search/agentic-search/agentic-search-templates/index/)。 +::: + +首先,创建搜索模板: + +```json +POST /_scripts/flower_species_search_template +{ + "script": { + "lang": "mustache", + "source": { + "from": " {{from}}{{^from}}0{{/from}} ", + "size": " {{size}}{{^size}}10{{/size}} ", + "query": { + "match": { + "species": " {{species}} " + } + } + } + } +} +``` + +```json +POST /_scripts/flower_petal_length_range_template +{ + "script": { + "lang": "mustache", + "source": { + "from": " {{from}}{{^from}}0{{/from}} ", + "size": " {{size}}{{^size}}10{{/size}} ", + "query": { + "range": { + "petal_length_in_cm": { + "gte": " {{min_length}} ", + "lte": " {{max_length}} " + } + } + } + } + } +} +``` + +接下来,注册一个代理,将 `generation_type` 设置为 `user_templates`,并在 `search_templates` 参数中为每个模板提供 `template_id` 和 `template_description`: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Agentic Search with Claude 4", + "type": "flow", + "description": "A test agent for query planning.", + "tools": [ + { + "type": "QueryPlanningTool", + "description": "A general tool to answer any question", + "parameters": { + "model_id": "ANiSxJgBOh0h20Y9XYXl", + "response_filter": "$.output.message.content[0].text", + "generation_type": "user_templates", + "search_templates": [ + { + "template_id": "flower_species_search_template", + "template_description": "This template searches for flowers that match the given species using a match query." + }, + { + "template_id": "flower_petal_length_range_template", + "template_description": "This template searches for flowers within a specific petal length range using a range query." + } + ] + } + } + ] +} +``` + +LLM 使用 `template_description` 作为唯一的上下文,帮助它根据用户提供的 `question` 选择最佳模板来生成 OpenSearch DSL 查询。确保提供模板的良好描述,以帮助 LLM 做出适当的选择。请注意,LLM 不会直接填充模板变量或渲染模板;相反,它分析模板的查询结构并将其用作指南来生成新的、适合上下文的 OpenSearch DSL 查询。 + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "RNjQi5gBOh0h20Y9-RX1" +} +``` + +## 步骤 4:执行代理 + +通过发送以下请求执行代理: + +```json +POST /_plugins/_ml/agents/RNjQi5gBOh0h20Y9-RX1/_execute +{ + "parameters": { + "question": "How many iris flowers of type setosa are there?", + "index_name": "iris-index" + } +} +``` + +OpenSearch 返回推理结果,其中包括生成的查询 DSL: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"size\":0,\"query\":{\"term\":{\"species.keyword\":\"setosa\"}},\"aggs\":{\"count_setosa\":{\"value_count\":{\"field\":\"species.keyword\"}}}}" + } + ] + } + ] +} +``` + +## 注册参数 + +下表列出了注册代理时可用的所有工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`model_id` | 字符串 | 必需 | 用于生成查询 DSL 的 LLM 的模型 ID。在 `conversational` 代理中使用时,如果未提供此值,则默认使用代理自己的 `llm.model_id`。 +`response_filter` | 字符串 | 可选 | 用于从 LLM 响应中提取生成的查询的 JSONPath 表达式。如果未指定,工具将返回完整的 LLM 响应。在 `flow` 代理中运行工具时指定此参数。请参阅[响应过滤器配置](#response-filter-configuration)。 +`generation_type` | 字符串 | 可选 | 确定如何生成查询。使用 `llmGenerated` 完全依赖 LLM 内置知识,或使用 `user_templates` 提供预定义的搜索模板,以指导查询生成以获得一致的结果。默认为 `llmGenerated`。 +`query_planner_system_prompt` | 字符串 | 可选 | 向 LLM 提供高级指令的系统提示。 +`query_planner_user_prompt` | 字符串 | 可选 | 用户提示模板,定义如何向 LLM 呈现自然语言问题和上下文以进行查询生成。 +`search_templates` | 数组 | 可选 | 仅当 `generation_type` 为 `user_templates` 时适用。为 LLM 提供预定义查询模式以生成查询 DSL 的搜索模板列表。每个模板必须包括 `template_id`(唯一标识符)和 `template_description`(解释模板的用途和用例,以帮助 LLM 做出适当选择)。 +`template_selection_system_prompt` | 字符串 | 可选 | 仅当 `generation_type` 为 `user_templates` 时适用。指示 LLM 如何从 `search_templates` 中选择搜索模板的系统提示。如果未指定,工具将使用默认的模板选择提示。 +`template_selection_user_prompt` | 字符串 | 可选 | 仅当 `generation_type` 为 `user_templates` 时适用。向 LLM 呈现问题和可用搜索模板以进行模板选择的用户提示。如果未指定,工具将使用默认的模板选择提示。 +`fallback_query` | 字符串 | 可选 | 如果 LLM 无法为给定的查询文本生成有效的 DSL 查询,则使用的 OpenSearch 查询 DSL 查询。请参阅[回退行为](#fallback-behavior)。 + +::: info NOTE +在连接器或代理注册中配置的所有参数都可以在代理执行期间被覆盖。 +::: + +## 响应过滤器配置 + +`response_filter` 参数使用 JSONPath 表达式从 LLM 响应中提取生成的查询。不同的模型提供商以不同的格式返回响应,因此您需要为模型类型指定适当的过滤器。 + +**OpenAI 模型**: + +```json +"response_filter": "$.choices[0].message.content" +``` + +**Anthropic Claude 模型(Amazon Bedrock Converse API)**: + +```json +"response_filter": "$.output.message.content[0].text" +``` + +## 执行参数 + +`QueryPlanningTool` 接受以下执行参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`question` | 字符串 | 必需 | 包含生成 OpenSearch DSL 所需的所有必要上下文的完整自然语言查询。包括问题、任何特定要求、过滤器或约束。示例:`Find all products with price greater than 100 dollars`、`Show me documents about machine learning published in 2023`、`Search for users with status active and age between 25 and 35`。 +`index_name` | 字符串 | 必需 | 需要为其生成查询的索引名称。 +`embedding_model_id` | 字符串 | 可选 | 用于执行语义搜索的模型 ID。 +`query_fields` | 字符串 | 可选 | LLM 在生成查询时应优先考虑的字段。通过默认用户提示中的 `${parameters.query_fields}` 占位符传递给 LLM。 + +## 自定义提示 + +您可以提供自己的 `query_planner_system_prompt` 和 `query_planner_user_prompt` 来自定义 LLM 如何生成 OpenSearch DSL 查询。 + +::: warning IMPORTANT +创建自定义提示时,请确保它们包含清晰的输出格式规则,以便它们能够正确地与代理搜索配合使用。系统提示应指定 LLM 必须仅返回有效的 JSON 对象,而不包含任何额外的文本、代码栅栏或解释。 +::: + +**自定义提示配置**: +在代理中注册工具期间提供您的自定义提示,如下所示: +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Flow Agent for Agentic Search", + "type": "flow", + "description": "Flow agent for agentic search", + "tools": [ + { + "type": "QueryPlanningTool", + "parameters": { + "model_id": "your_model_id", + "response_filter": "<response-filter-based-on-model-type>", + "query_planner_system_prompt": "<YOUR CUSTOM SYSTEM PROMPT>", + "query_planner_user_prompt": "<YOUR CUSTOM USER PROMPT>" + } + } + ] +} +``` + +::: info NOTE +根据您的模型类型使用适当的 `response_filter`。有关更多信息和示例,请参阅[响应过滤器配置](#response-filter-configuration)。 +::: + +以下是默认的系统提示: + +<details open markdown="block"> + <summary> + 提示 + </summary> + +```json +==== PURPOSE ==== +You are an OpenSearch DSL expert. Convert a natural-language question into a strict JSON OpenSearch query body. + +==== RULES ==== +Use only fields present in the provided mapping; never invent names. +Choose query types based on user intent and field types: + +match: single-token full-text on analyzed text fields. + +match_phrase: multi-token phrases on analyzed text fields (search string contains spaces, hyphens, commas, etc.). + +multi_match: when multiple analyzed text fields are equally relevant. + +term / terms: exact match on keyword, numeric, boolean. + +range: numeric/date comparisons (gt, lt, gte, lte). + +bool with must, should, must_not, filter: AND/OR/NOT logic. + +wildcard / prefix on keyword: "starts with" / pattern matching. + +exists: field presence/absence. + +nested query / nested agg: ONLY if the mapping for that exact path (or a parent) has "type":"nested". + +neural: semantic similarity on a 'semantic' or 'knn_vector' field (dense). Use "query_text" and "k"; include "model_id" unless bound in mapping. + +neural (top-level): allowed when it's the only relevance clause needed; otherwise wrap in a bool when combining with filters/other queries. + +Mechanics: + +Put exact constraints (term, terms, range, exists, prefix, wildcard) in bool.filter (non-scoring). Put full-text relevance (match, match_phrase, multi_match) in bool.must. + +Top N items/products/documents: return top hits (set "size": N as an integer) and sort by the relevant metric(s). Do not use aggregations for item lists. + +Neural retrieval size: set "k" ≥ "size" (e.g. heuristic, k = max(size*5, 100) and k<=ef_search). + +Spelling tolerance: match_phrase does NOT support fuzziness; use match or multi_match with "fuzziness": "AUTO" when tolerant matching is needed. + +Text operators (OR vs AND): default to OR for natural-language queries; to tighten, use minimum_should_match (e.g., "75%"). Use AND only when every token is essential; if order/adjacency matters, use match_phrase. + +Numeric note: use ONLY integers for size and k (not floats). + +Aggregations (counts, averages, grouped summaries, distributions): + +Use aggregations when the user asks for grouped summaries (e.g., counts by category, averages by brand, or top N categories/brands). + +terms on field.keyword or numeric for grouping / top N groups (not items). + +Metric aggs (avg, min, max, sum, stats, cardinality) on numeric fields. + +date_histogram, histogram, range for distributions. + +Always set "size": 0 when only aggregations are needed. + +Use sub-aggregations + order for "top N groups by metric". + +If grouping/filtering exactly on a text field, use its .keyword sub-field when present. + +DATE RULES + +Use range on date/date_nanos in bool.filter. + +Emit ISO 8601 UTC ('Z') bounds; don't set time_zone for explicit UTC. (now is UTC) + +Date math: now±N{y|M|w|d|h|m|s}. + +Rounding: "/UNIT" floors to start (now/d, now/w, now/M, now/y). + +End boundaries: prefer the next unit's start. + +Formats: only add "format" when inputs aren't default; epoch_millis allowed. + +Buckets: use date_histogram with calendar_interval or fixed_interval. + +NEURAL / SEMANTIC SEARCH +When to use: conceptual/semantic intent, or when user asks for semantic/neural/vector/embedding search. +When not to use: purely structured/exact queries, or when no semantic/knn_vector field or model_id is available. +How to query: + +Use the "neural" clause against the chosen field. + +Required: "query_text" and "k". + +Model rules: + +For "semantic" fields, omit model_id unless overriding. + +For "knn_vector", include model_id unless default is bound. + +If no model id, do not generate neural clause. + +Top-level allowed if no filters/other queries. Otherwise wrap in bool with filters in bool.filter. + +Size: set "k" ≥ "size" (heuristic: k = max(size*5, 100)). + +FIELD SELECTION & PROXYING +Goal: pick the smallest set of mapping fields that best capture the user's intent. + +When provided, and present in the mapping, prioritize query_fields. + +Proxy Rule: If at least one field is loosely related, proceed with the best proxy; do NOT fallback to match_all due to ambiguity. + +Steps: harvest candidates, pick mapping fields, ignore irrelevant ones. + +Micro Self-Check: verify fields exist; if not, swap to proxies. Only if no relevant fields exist at all, fallback to match_all. + +==== OUTPUT FORMAT ==== + +Return EXACTLY ONE JSON object (valid OpenSearch request body). + +No escapes, no code fences, no quotes around the whole object. + +If nothing relevant exists, return exactly: +{"size":10,"query":{"match_all":{}}} + +==== EXAMPLES ==== +(Then follows Examples 1–13 exactly as in your original text, but without escapes.) + +==== TEMPLATE USE ==== +Use this search template provided by the user as reference to generate the query: ${parameters.template} +Note that this template might contain terms that are not relevant to the question at hand; in that case ignore the template. +``` + +</details> + +以下是默认的用户提示: + +```json +Question: ${parameters.question} +Index: ${parameters.index_name} +Mapping: ${parameters.index_mapping:-} +Query Fields: ${parameters.query_fields:-} +Sample Document from index: ${parameters.sample_document:-} +In UTC: ${parameters.current_time:-} format: yyyy-MM-dd'T'HH:mm:ss'Z' +Embedding Model ID for Neural Search: ${parameters.embedding_model_id:- not provided} + +==== OUTPUT ==== +GIVE THE OUTPUT PART ONLY IN YOUR RESPONSE (a single JSON object) +Output: +``` + +## 回退行为 + +当 LLM 无法生成有效的查询 DSL 时,`QueryPlanningTool` 使用回退查询。默认情况下,回退查询为 `{"size":10,"query":{"match_all":{}}}`。您可以通过在注册代理时指定自定义 `fallback_query` 参数来覆盖此默认值。 + +工具会自动从 LLM 响应中提取第一个有效的 JSON 对象,即使 JSON 被附加文本、Markdown 代码栅栏、解释或其他内容包围。但是,如果无法从响应中提取有效的 JSON(例如,当响应完全为空、仅包含非 JSON 文本或仅包含格式错误的 JSON 时),工具将返回回退查询(默认或您的自定义查询)。 + +当触发回退时,不会抛出错误。相反,系统日志中会显示调试日志。这确保查询规划操作即使在 LLM 提供意外输出时也能继续工作。 + +### 覆盖默认回退查询 + +以下示例演示回退查询的工作方式。 + +要遵循此示例,首先从[代理搜索教程](/vector-search/ai-search/agentic-search/index/)完成步骤 1--3:创建索引、摄取数据和注册模型。 + +接下来,使用步骤 3 中的模型 ID 注册一个代理。包括一个自定义 `fallback_query` 参数以演示回退行为,并为您的模型类型设置 `response_filter`(请参阅[响应过滤器配置](#response-filter-configuration)): + +```json +POST _plugins/_ml/agents/_register +{ + "name": "Iris Search Agent with Fallback", + "type": "flow", + "tools": [ + { + "type": "QueryPlanningTool", + "parameters": { + "model_id": "<your-model-id>", + "response_filter": "<response-filter-based-on-model-type>", + "fallback_query": "{\"size\":10,\"query\":{\"bool\":{\"should\":[{\"match\":{\"species\":{\"query\":\"${parameters.question}\",\"fuzziness\":\"AUTO\"}}},{\"match_all\":{\"boost\":0.1}}],\"minimum_should_match\":1}}}" + } + } + ] +} +``` + +接下来,使用上一步的代理 ID 创建搜索管道: + +```json +PUT _search/pipeline/agentic_search_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "<your-agent-id>" + } + } + ], + "response_processors": [ + { + "agentic_context": { + "dsl_query": true + } + } + ] +} +``` + +要测试回退行为,请发送一个与 `iris-index` 无关的问题的搜索请求: + +```json +POST /iris-index/_search?search_pipeline=agentic_search_pipeline&pretty +{ + "query": { + "agentic": { + "query_text": "Find all employees hired in 2023 with salary above 100000" + } + } +} +``` + +响应在 `ext` 部分的 `dsl_query` 字段中包含回退查询: + +```json +{ + "took" : 5396, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.1, + "hits" : [ + { + "_index" : "iris-index", + "_id" : "1", + "_score" : 0.1, + "_source" : { + "petal_length_in_cm" : 1.4, + "petal_width_in_cm" : 0.2, + "sepal_length_in_cm" : 5.1, + "sepal_width_in_cm" : 3.5, + "species" : "setosa" + } + }, + { + "_index" : "iris-index", + "_id" : "2", + "_score" : 0.1, + "_source" : { + "petal_length_in_cm" : 4.5, + "petal_width_in_cm" : 1.5, + "sepal_length_in_cm" : 6.4, + "sepal_width_in_cm" : 2.9, + "species" : "versicolor" + } + } + ] + }, + "ext" : { + "dsl_query" : "{\"size\":10,\"query\":{\"bool\":{\"should\":[{\"match\":{\"species\":{\"query\":\"Find all employees hired in 2023 with salary above 100000\",\"fuzziness\":\"AUTO\"}}},{\"match_all\":{\"boost\":0.1}}],\"minimum_should_match\":1}}}" + } +} +``` + +接下来,询问与 `iris-index` 相关的问题: + +```json +POST /iris-index/_search?search_pipeline=agentic_search_pipeline +{ + "query": { + "agentic": { + "query_text": "Find all setosa species" + } + } +} +``` + +响应包含适当的 LLM 生成的查询,而不是使用回退查询: + +```json +{ + "took" : 4037, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.0, + "hits" : [ + { + "_index" : "iris-index", + "_id" : "1", + "_score" : 0.0, + "_source" : { + "petal_length_in_cm" : 1.4, + "petal_width_in_cm" : 0.2, + "sepal_length_in_cm" : 5.1, + "sepal_width_in_cm" : 3.5, + "species" : "setosa" + } + } + ] + }, + "ext" : { + "dsl_query" : "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"species.keyword\":\"setosa\"}}]}}}" + } +} +``` + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 + +## 相关文档 + +- [代理搜索](/vector-search/ai-search/agentic-search/index) diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/scratchpad-tools.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/scratchpad-tools.md new file mode 100644 index 00000000..3fddfa17 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/scratchpad-tools.md @@ -0,0 +1,338 @@ +--- +title: 草稿板工具 +--- + +<!-- vale off --> +# 草稿板工具 +<Badge type="tip" text="3.3 版本引入" /> + +<!-- vale on --> + +草稿板工具由 `WriteToScratchPadTool` 和 `ReadFromScratchPadTool` 组成,它们使代理能够在运行时存储和检索中间思路和结果。这些工具作为单个代理执行会话的临时内存,允许代理在工具执行期间做笔记并存储重要发现。 + +::: warning IMPORTANT +草稿板作为运行时内存,仅在单个代理执行期间持久存在。当您调用代理的 `_execute` API 时,会为该会话创建一个新的草稿板。除 `persistent_notes` 外的所有笔记和数据在执行完成时都会被清除,确保每次执行都从新的草稿板开始。 +::: + +## 用例 + +- **任务分解**:在单个执行中的多步操作期间存储研究计划、中间发现和进度笔记。 +- **临时状态管理**:在当前代理执行会话期间维护上下文和累积的知识。 +- **多步工作流程**:在复杂任务中搜索后保存关键发现,以构建全面的响应。 +- **执行规划**:在复杂操作期间存储和引用逐步计划。 + +## 草稿板生命周期 + +草稿板遵循简单的生命周期: + +1. **创建**:当代理执行开始时,会创建一个新的空草稿板。 +2. **使用**:在执行期间,代理可以多次读取和写入草稿板。 +3. **清理**:执行完成时会自动清除草稿板。 + +每次调用代理的 `_execute` API 都会创建一个新的草稿板,确保执行之间相互隔离。 + +## 最佳实践 + +- **结构化笔记**:鼓励代理在草稿板中维护有组织的结构化笔记。 +- **定期更新**:让代理在每个重要步骤或发现后更新草稿板。 +- **会话感知**:记住草稿板内容是临时的,并且特定于当前执行。 +- **高效使用**:使用草稿板存储在执行期间需要多次引用的中间结果。 + +## 示例:使用草稿板工具构建研究代理 + +使用以下步骤构建带有草稿板工具的研究代理。 + +### 步骤 1:注册并部署模型 + +注册一个支持代理框架的对话模型。以下示例使用 Anthropic Claude: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Claude Sonnet for Research Agent", + "function_name": "remote", + "description": "Claude model for research agent with scratchpad", + "connector": { + "name": "Bedrock Claude Sonnet Connector", + "description": "Amazon Bedrock connector for Claude Sonnet", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "credential": { + "access_key": "${AWS_ACCESS_KEY_ID}", + "secret_key": "${AWS_SECRET_ACCESS_KEY}", + "session_token": "${AWS_SESSION_TOKEN}" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "headers": { + "content-type": "application/json" + }, + "request_body": """{"system": [{"text": "${parameters.system_prompt}"}], "messages": [${parameters._chat_history:-}{"role":"user","content":[{"text":"${parameters.prompt}"}]}${parameters._interactions:-}]${parameters.tool_configs:-}, "inferenceConfig": {"maxTokens": 8000, "temperature": 0}}""" + } + ] + } +} +``` + +### 步骤 2:注册带有草稿板工具的代理 + +注册一个对话代理,包括草稿板工具和其他研究工具: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Research Agent with Scratchpad", + "type": "conversational", + "description": "Research assistant with persistent scratchpad memory", + "app_type": "rag", + "llm": { + "model_id": "<your-model-id>", + "parameters": { + "max_iteration": 50, + "system_prompt": "You are a sophisticated research assistant with access to OpenSearch indices and a persistent scratchpad for note-taking.\n\nYour Research Workflow:\n1. Check Scratchpad: Before starting a new research task, check your scratchpad to see if you have any relevant information already saved\n2. Create Research Plan: Create a structured research plan\n3. Write to Scratchpad: Save the research plan and any important information to your scratchpad\n4. Use Search: Gather information using OpenSearch search queries\n5. Update Scratchpad: After each search, update your scratchpad with new findings\n6. Iterate: Repeat searching and updating until you have comprehensive information\n7. Complete Task: Provide a thorough response based on your accumulated research\n\nRemember: Your scratchpad is temporary memory for this execution session only. Use it to organize your thoughts and findings during this task.", + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "bedrock/converse/claude" + }, + "tools": [ + { + "type": "SearchIndexTool" + }, + { + "type": "ListIndexTool" + }, + { + "type": "IndexMappingTool" + }, + { + "type": "ReadFromScratchPadTool", + "name": "ReadFromScratchPadTool", + "parameters": { + "persistent_notes": "You are a helpful researcher. Before making searches, use the ListIndexTool to discover available indices. Write down important notes after using tools." + } + }, + { + "type": "WriteToScratchPadTool", + "name": "WriteToScratchPadTool" + } + ] +} +``` + +### 步骤 3:执行代理 + +使用研究问题执行代理: + +```json +POST /_plugins/_ml/agents/{your-agent-id}/_execute?async=true +{ + "parameters": { + "question": "How many residents are in New York?" + } +} +``` + +代理将: +1. 读取其草稿板以检查现有的相关信息(新执行开始时为空)。 +2. 创建并保存研究计划到草稿板。 +3. 执行搜索并使用发现更新草稿板。 +4. 根据累积的研究提供全面的答案。 + +因为请求指定了 `async=true`,OpenSearch 返回一个任务 ID,而不等待代理完成。响应还包含 `memory_id` 和 `parent_interaction_id`: + +```json +{ + "task_id": "pfztP6EBqoCArR_TRGp7", + "status": "RUNNING", + "response": { + "memory_id": "o_ztP6EBqoCArR_TRGpJ", + "parent_interaction_id": "pPztP6EBqoCArR_TRGpo" + } +} +``` + +注意 `parent_interaction_id`,以便稍后跟踪步骤。有关更多信息,请参阅[查看草稿板活动](#viewing-scratchpad-activity)。 + +要获取代理的答案,请使用 `task_id` 发送 [Get ML Task API](/ml-commons-plugin/api/tasks-apis/get-task) 请求。当任务 `state` 为 `COMPLETED` 时,任务 `response` 包含代理的 `inference_results`。 + +## 工具参数 + +以下是草稿板工具的参数。 + +### ReadFromScratchPadTool + +以下是添加到代理时使用的**注册参数**。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`persistent_notes` | 字符串 | 可选 | 首次创建时要存储在草稿板中的初始笔记或指令。 + +以下是直接调用工具时使用的**执行参数**。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- |:------------------| :--- +`persistent_notes` | 字符串 | 可选 | 要存储在草稿板中的初始笔记或指令。 + +### WriteToScratchPadTool + +以下是添加到代理时使用的**注册参数**。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`return_history` | 布尔值 | 可选 | 当设置为 `true` 时,在写入后返回完整的草稿板内容。当为 `false` 或省略(默认)时,返回新添加的笔记和确认。 + +以下是直接调用工具时使用的**执行参数**。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`notes` | 字符串 | 必需 | 要写入草稿板的内容。 +`return_history` | 布尔值 | 可选 | 当设置为 `true` 时,在写入后返回完整的草稿板内容。当为 `false` 或省略(默认)时,返回新添加的笔记和确认。 + +## 测试工具 + +您可以直接使用 Tools API 执行两个草稿板工具,并在将它们注册到代理之前测试其响应。 + +### 测试 ReadFromScratchPadTool + +```json +POST /_plugins/_ml/tools/_execute/ReadFromScratchPadTool +{ + "parameters": { + "persistent_notes": "You are a helpful researcher to conduct searches in OpenSearch cluster. Before making the search, please remember to use the listIndexTool to figure out what are the available indices first. When using listIndexTool, remember the index name has to be in an array format. Please write down important notes after tool used." + } +} +``` + +当提供 `persistent_notes` 时,工具会尝试在响应中显示持久笔记: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """Notes from scratchpad: +- You are a helpful researcher to conduct searches in OpenSearch cluster. Before making the search, please remember to use the listIndexTool to figure out what are the available indices first. When using listIndexTool, remember the index name has to be in an array format. Please write down important notes after tool used.""" + } + ] + } + ] +} +``` + +您还可以使用空的 `persistent_notes` 字段进行测试: + +```json +POST /_plugins/_ml/tools/_execute/ReadFromScratchPadTool +{ + "parameters": { + "persistent_notes": "" + } +} +``` + +响应表示草稿板为空: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "Scratchpad is empty." + } + ] + } + ] +} +``` + +### 测试 WriteToScratchPadTool + +您可以直接使用 Tools API 执行 `WriteToScratchPadTool`,并在将其注册到代理之前测试工具响应。 + +```json +POST /_plugins/_ml/tools/_execute/WriteToScratchPadTool +{ + "parameters": { + "notes": "Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n a. Key architectural upgrades\\n b. New machine learning capabilities, especially ML Commons Agent framework \\n c. Descriptions of major Agent tools added\\n d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n" + } +} +``` + +以下是工具输出的示例响应: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "Wrote to scratchpad: Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n a. Key architectural upgrades\\n b. New machine learning capabilities, especially ML Commons Agent framework \\n c. Descriptions of major Agent tools added\\n d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n" + } + ] + } + ] +} +``` + +您可以将 `return_history` 参数设置为 `true` 以在写入后获取完整的草稿板内容: + +```json +POST /_plugins/_ml/tools/_execute/WriteToScratchPadTool +{ + "parameters": { + "notes": "Research Plan for OpenSearch History and ML Evolution:\\n\\n1. OpenSearch version history, major releases after v2.0\\n2. For each major release:\\n a. Key architectural upgrades\\n b. New machine learning capabilities, especially ML Commons Agent framework \\n c. Descriptions of major Agent tools added\\n d. GitHub issue IDs tied to Agent framework features\\n3. Look for official OpenSearch documentation, release notes, blogs\\n4. Search code repositories for more technical details on ML changes\\n", + "return_history": true + } +} +``` + +响应包含完整的草稿板内容: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """Scratchpad updated. Full content: +- Research Plan for OpenSearch History and ML Evolution:\n\n1. OpenSearch version history, major releases after v2.0\n2. For each major release:\n a. Key architectural upgrades\n b. New machine learning capabilities, especially ML Commons Agent framework \n c. Descriptions of major Agent tools added\n d. GitHub issue IDs tied to Agent framework features\n3. Look for official OpenSearch documentation, release notes, blogs\n4. Search code repositories for more technical details on ML changes\n""" + } + ] + } + ] +} +``` + +## 查看草稿板活动 + +您可以通过检查执行跟踪来监控代理如何使用草稿板: + +```json +GET /_plugins/_ml/memory/message/{parent_interaction_id}/traces?next_token=0 +``` + +跟踪显示草稿板读取和写入的序列,演示代理如何在执行会话期间积累知识。 + +## 相关文档 + +- [代理和工具](/ml-commons-plugin/agents-tools/) +- [对话代理](/ml-commons-plugin/agents-tools/agents/) diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/search-template-fill-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/search-template-fill-tool.md new file mode 100644 index 00000000..bbb217df --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/search-template-fill-tool.md @@ -0,0 +1,127 @@ +--- +title: 搜索模板填充工具 +--- + +<!-- vale off --> +# 搜索模板填充工具 +<Badge type="tip" text="3.10 版本引入" /> + +<!-- vale on --> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +`SearchTemplateFillTool` 通过填充注册的代理搜索模板的参数,从自然语言问题生成 OpenSearch 查询领域特定语言(DSL)查询。大语言模型(LLM)仅返回参数值,OpenSearch 将它们渲染到存储的 Mustache 模板中。在以下情况下,工具会回退到 [`QueryPlanningTool`](/ml-commons-plugin/agents-tools/tools/query-planning-tool),后者编写完整的查询: + +- `template_ids` 中没有可用于该索引的模板,例如,因为没有为该索引注册模板,或者每个模板的参数架构都为空。 +- LLM 设置 `cannot_express` 以指示没有模板可以表达该问题,或者不选择任何模板。 +- LLM 响应不包含工具调用、与参数架构不匹配的值或不是候选的模板。 +- 渲染的模板不是单个 JSON 对象。 + +如果读取注册的模板或 LLM 调用失败,工具将返回错误而不回退。 + +有关完整示例,包括如何存储和注册模板,请参阅[填充搜索模板](/vector-search/ai-search/agentic-search/agentic-search-templates/index/)。 + +## 前提条件 + +在使用工具之前,请完成以下步骤: + +1. 将 `plugins.ml_commons.agentic_search_template_enabled` 设置为 `true`。启用多租户时,该工具不可用。 +1. 存储一个或多个搜索模板,并使用注册代理搜索模板 API 注册每个模板。有关更多信息,请参阅[注册代理搜索模板 API](/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template)。 +1. 注册一个外部托管的模型,其连接器 `request_body` 包括 `${parameters.tool_configs:-}`、`${parameters.system_prompt}` 以及 `${parameters.user_prompt}` 或 `${parameters.prompt}`。 + +## 步骤 1:注册流式代理 + +以下示例注册一个运行 `SearchTemplateFillTool` 的 `flow` 代理: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "template-fill-agent", + "type": "flow", + "tools": [ + { + "type": "SearchTemplateFillTool", + "parameters": { + "model_id": "<model_id>", + "_llm_interface": "bedrock/converse/claude", + "response_filter": "$.output.message.content[0].text" + }, + "config": { + "template_ids": "[\"product_search\",\"similar_search\"]" + } + } + ] +} +``` + +## 步骤 2:执行代理 + +通过发送以下请求执行代理: + +```json +POST /_plugins/_ml/agents/<agent_id>/_execute +{ + "parameters": { + "question": "the 2 most expensive footwear shoes", + "index_name": "products" + } +} +``` + +OpenSearch 返回渲染的查询: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"title\":\"shoes\"}}],\"filter\":[{\"term\":{\"category\":\"footwear\"}}]}},\"sort\":[{\"price\":\"desc\"}],\"size\":2}" + } + ] + } + ] +} +``` + +## 注册参数 + +下表列出了注册代理时可以在工具的 `parameters` 中设置的参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`model_id` | 字符串 | 必需 | 填充模板的 LLM 的模型 ID。回退的 `QueryPlanningTool` 使用相同的模型。 +`_llm_interface` | 字符串 | 必需 | 模型的函数调用接口。有效值为 `bedrock/converse/claude`、`openai/v1/chat/completions` 和 `gemini/v1beta/generatecontent`。 +`response_filter` | 字符串 | 可选 | 从 LLM 响应中提取生成的查询的 JSONPath 表达式。仅由回退的 `QueryPlanningTool` 使用。请参阅[响应过滤器配置](/ml-commons-plugin/agents-tools/tools/query-planning-tool#response-filter-configuration)。 + +所有其他参数都传递给回退的 `QueryPlanningTool`。例如,`fallback_query` 和 `query_planner_system_prompt` 自定义回退。有关更多信息,请参阅[查询规划工具注册参数](/ml-commons-plugin/agents-tools/tools/query-planning-tool#register-parameters)。 + +下表列出了可以在工具的 `config` 中设置的字段。执行请求无法覆盖这些字段,因此在 `parameters` 中注册带有任一字段的代理会返回错误。 + +字段 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`template_ids` | 字符串 | 必需 | 代理可以填充的代理搜索模板,作为模板 ID 的 JSON 数组,例如 `"[\"product_search\"]"`,或作为单个模板 ID。模板按列出的顺序提供。仅使用为搜索的索引注册的、具有非空参数架构且用户可以读取其存储脚本的模板,并且最多提供八个模板。 +`fallback_enabled` | 字符串 | 可选 | 当工具无法填充模板时,是否回退到 `QueryPlanningTool`。有效值为 `true` 和 `false`。如果为 `false`,工具会返回错误。默认为 `true`。 + +## 执行参数 + +下表列出了执行代理时可以提供的参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`question` | 字符串 | 必需 | 自然语言问题。 +`index_name` | 字符串 | 必需 | 要搜索的索引名称。为其他索引注册的模板将被跳过。 + +## 权限 + +当启用安全插件时,工具以运行搜索的用户身份读取和渲染每个存储的脚本,因此该用户需要 `cluster:admin/script/get` 权限。如果用户无法读取模板的存储脚本,工具不会将该模板提供给 LLM。 + +## 相关文档 + +- [填充搜索模板](/vector-search/ai-search/agentic-search/agentic-search-templates/index/) +- [代理搜索模板 API](/ml-commons-plugin/api/agentic-search-template-apis/) +- [查询规划工具](/ml-commons-plugin/agents-tools/tools/query-planning-tool) +- [代理搜索](/vector-search/ai-search/agentic-search/index/) diff --git a/i18n/zh/ml-commons-plugin/agents-tools/tools/web-search-tool.md b/i18n/zh/ml-commons-plugin/agents-tools/tools/web-search-tool.md new file mode 100644 index 00000000..8ada266c --- /dev/null +++ b/i18n/zh/ml-commons-plugin/agents-tools/tools/web-search-tool.md @@ -0,0 +1,311 @@ +--- +title: 网络搜索工具 +--- + +<!-- vale off --> +# 网络搜索工具 +<Badge type="tip" text="3.0 版本引入" /> + +<!-- vale on --> + +`WebSearchTool` 根据用户的问题检索搜索结果。它支持 [Google](#using-google-as-a-search-engine)、Bing 和 [DuckDuckGo](#using-duckduckgo-as-a-search-engine) 作为搜索引擎,或者可以使用[自定义 API](#using-a-custom-api-as-a-search-engine) 执行搜索。 + +## 使用 DuckDuckGo 作为搜索引擎 + +要将 DuckDuckGo 作为搜索引擎与 `WebSearchTool` 一起使用,请按照以下步骤操作。 + +### 步骤 1:注册将运行 WebSearchTool 的流式代理 + +流式代理按顺序运行一系列工具,并返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_WebSearch_tool", + "type": "flow", + "description": "this is a test agent for the WebSearchTool", + "tools": [ + { + "type": "WebSearchTool", + "name": "DuckduckgoWebSearchTool", + "parameters": { + "engine": "duckduckgo", + "input": "${parameters.question}" + } + } + ] +} +``` + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +### 步骤 2:运行代理 + +然后,通过发送以下请求运行代理(DuckDuckGo 不需要任何凭据): + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How to create a index pattern in OpenSearch?" + } +} +``` + +OpenSearch 返回网络搜索结果: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """ + { + "next_page": "https://html.duckduckgo.com/html?q=how+to+create+index+pattern+in+OpenSearch&ia=web&dc=11", + "items": [ + { + "url": "http://someurl", + "title": "the page result title", + "content": "the page content..." + }, + { + "url": "https://anotherurl", + "title": "the page result title", + "content": "the page content..." + } + ... + ] + } + """ + } + ] + } + ] +} +``` + +## 使用 Google 作为搜索引擎 + +要将 Google 作为搜索引擎与 `WebSearchTool` 一起使用,请按照以下步骤操作。 + +### 步骤 1:注册将运行 WebSearchTool 的流式代理 + +流式代理按顺序运行一系列工具,并返回最后一个工具的输出。要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_WebSearch_tool", + "type": "flow", + "description": "this is a test agent for the WebSearchTool", + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleWebSearchTool", + "parameters": { + "engine": "google", + "engine_id": "${your_google_engine_id}", + "api_key": "${your_google_api_key}", + "input": "${parameters.question}" + } + } + ] +} +``` + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +### 步骤 2:运行代理 + +在运行代理之前,请确保您已获得以编程方式访问 Google 搜索所需的凭据。 + +然后,通过发送以下请求运行代理: + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How to create a index pattern in OpenSearch?" + } +} +``` + +OpenSearch 返回网络搜索结果: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """ + { + "next_page": "https://customsearch.googleapis.com/customsearch/v1?q=how+to+create+index+pattern+in+OpenSearch&start=10", + "items": [ + { + "url": "http://someurl", + "title": "the page result title", + "content": "the page content..." + }, + { + "url": "https://anotherurl", + "title": "the page result title", + "content": "the page content..." + } + ... + ] + } + """ + } + ] + } + ] +} +``` + +## 使用自定义 API 作为搜索引擎 + +要将自定义 API 作为搜索引擎与 `WebSearchTool` 一起使用,请按照以下步骤操作。 + +### 步骤 1:注册将运行 WebSearchTool 的流式代理 + +要使用自定义端点进行搜索,您需要配置以下参数: + +- `Authorization`:用于身份验证 +- `endpoint`:用于 API 连接 +- `custom_res_url_jsonpath`:用于解析 JSON 响应并提取链接 + +您的 API 必须以 JSON 格式返回响应。API 返回的链接必须可以使用 [JSONPath](https://en.wikipedia.org/wiki/JSONPath) 表达式检索。其他参数(如 `query_key`、`offset_key` 和 `limit_key`)是可选的,但如果您的 API 使用不同于默认值的值,则应指定。 + +要创建流式代理,请发送以下注册代理请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Test_Agent_For_WebSearch_tool", + "type": "flow", + "description": "this is a test agent for the WebSearchTool", + "tools": [ + { + "type": "WebSearchTool", + "name": "CustomWebSearchTool", + "parameters": { + "engine": "custom", + "endpoint": "${your_custom_endpoint}", + "custom_res_url_jsonpath": "$.data[*].link", + "Authorization": "Bearer xxxx", + "query_key": "q", + "offset_key": "offset", + "limit_key": "limit" + } + } + ] +} +``` + +有关参数描述,请参阅[注册参数](#register-parameters)。 + +OpenSearch 返回一个代理 ID: + +```json +{ + "agent_id": "9X7xWI0Bpc3sThaJdY9i" +} +``` + +### 步骤 2:运行代理 + +在运行代理之前,请确保您已获得以编程方式访问自定义搜索 API 所需的凭据。 + +然后,通过发送以下请求运行代理: + +```json +POST /_plugins/_ml/agents/9X7xWI0Bpc3sThaJdY9i/_execute +{ + "parameters": { + "question": "How to create a index pattern in OpenSearch?" + } +} +``` + +OpenSearch 返回网络搜索结果: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """ + { + "next_page": "{your_custom_endpoint}?q=how+to+create+index+pattern+in+OpenSearch&offset=10&limit=10", + "items": [ + { + "url": "http://someurl", + "title": "the page result title", + "content": "the page content..." + }, + { + "url": "https://anotherurl", + "title": "the page result title", + "content": "the page content..." + } + ... + ] + } + """ + } + ] + } + ] +} +``` + +## 注册参数 + +下表列出了注册代理时可用的所有工具参数。 + +| 参数 | 类型 | 必需/可选 | 描述 | +|:---|:---|:---|:---| +| `engine` | 字符串 | 可选 | 要使用的搜索引擎。有效值为 `google`、`bing`、`duckduckgo` 或 `custom`。默认为 `google`。 | +| `engine_id` | 字符串 | 可选 | Google 的自定义搜索引擎 ID。当 `engine` 设置为 `google` 时必需。 | +| `api_key` | 字符串 | 可选 | 用于身份验证的 API 密钥。当 `engine` 设置为 `google` 或 `bing` 时必需。 | +| `endpoint` | 字符串 | 可选 | 自定义搜索 API 的 URL 端点。当 `engine` 设置为 `custom` 时必需。 | +| `Authorization` | 字符串 | 可选 | 自定义 API 的授权标头值。当 `engine` 设置为 `custom` 时必需。 | +| `query_key` | 字符串 | 可选 | 自定义 API URL 中搜索查询的参数名称(例如,`${endpoint}?my_query_key=${question}`)。默认为 `q`。 | +| `offset_key` | 字符串 | 可选 | 自定义 API URL 中分页偏移量的参数名称(例如,`${endpoint}?q=${question}&start=10`)。默认为 `offset`。 | +| `limit_key` | 字符串 | 可选 | 自定义 API URL 中结果限制的参数名称(例如,`${endpoint}?q=${question}&start=10&limit=10`)。默认为 `limit`。 | +| `custom_res_url_jsonpath` | 字符串 | 可选 | 用于从自定义 API 响应中提取 URL 的 JSONPath 表达式(例如,`$[*].link`)。当 `engine` 设置为 `custom` 时必需。 | + +## 执行参数 + +下表列出了运行代理时可用的所有工具参数。 + +参数 | 类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`question` | 字符串 | 必需 | 要发送给 LLM 的自然语言问题。 +`next_page` | 字符串 | 可选 | 下一页搜索结果的 URL,在上一个响应的 `next_page` 字段中返回。如果提供,工具将返回该页的结果,而不是运行新的搜索。 + +## 测试工具 + +您可以将此工具作为代理工作流程的一部分运行,也可以使用 [Execute Tool API](/ml-commons-plugin/api/execute-tool) 独立运行。Execute Tool API 对于测试单个工具或执行独立操作很有用。 diff --git a/i18n/zh/ml-commons-plugin/api/agent-apis/execute-stream-agent.md b/i18n/zh/ml-commons-plugin/api/agent-apis/execute-stream-agent.md new file mode 100644 index 00000000..7ce50dd3 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agent-apis/execute-stream-agent.md @@ -0,0 +1,377 @@ +--- +title: 执行代理流 +--- + +# 执行代理流 API +<Badge type="tip" text="3.3 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。要获取功能进展的更新或留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/) 的讨论。 +::: + +执行代理流 API 提供与[执行代理 API](/ml-commons-plugin/api/agent-apis/execute-agent) 相同的功能,但以流式格式返回响应,在数据可用时以块的形式传递数据。这种流式方法对于具有冗长响应的大型语言模型交互特别有益,允许您立即看到部分结果,而不是等待完整响应。 + +::: info NOTE +或者,您可以通过 gRPC 流式传输代理执行。有关更多信息,请参阅 [gRPC 执行代理流 API](/api-reference/grpc-apis/execute-agent-stream)。 +::: + +此 API 支持以下代理类型: + +- **会话代理**,具有以下外部托管模型类型: + - [OpenAI Chat Completion](https://platform.openai.com/docs/api-reference/completions) + - [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +- **AG-UI 代理**,使用 AG-UI 协议请求和响应格式。有关更多信息,请参阅 [AG-UI 代理](/ml-commons-plugin/agents-tools/agents/ag-ui)。 + +## 端点 + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +``` + +## 前提条件 + +在使用此 API 之前,请确保您已满足以下前提条件。 + +### 设置您的集群 + +按照以下步骤设置您的集群。 + +#### 步骤 1:安装所需的插件 + +执行代理流 API 依赖于以下插件,这些插件包含在 OpenSearch 发行版中,但必须按如下方式显式安装: + +```bash +bin/opensearch-plugin install transport-reactor-netty4 +bin/opensearch-plugin install arrow-flight-rpc +``` + +有关更多信息,请参阅[管理 OpenSearch 插件](/install-and-configure/plugins)。 + +#### 步骤 2:配置 OpenSearch 设置 + +将这些设置添加到您的 `opensearch.yml` 文件或 Docker Compose 配置中: + +```yaml +opensearch.experimental.feature.transport.stream.enabled: true + +# 根据您的安全设置选择一个 +http.type: reactor-netty4 # 安全禁用 +http.type: reactor-netty4-secure # 安全启用 + +# 多节点集群设置(如适用) +# 对于 opensearch.yml 使用 network.host IP,对于 Docker 使用节点名称 +arrow.flight.publish_host: <ip> +arrow.flight.bind_host: <ip> + +# 启用安全的集群设置(如适用) +transport.stream.type.default: FLIGHT-SECURE +flight.ssl.enable: true +transport.ssl.enforce_hostname_verification: false +``` + +::: info NOTE +如果您使用安全演示证书,请在 `opensearch.yml` 文件中将 `plugins.security.ssl.transport.enforce_hostname_verification: false` 更改为 `transport.ssl.enforce_hostname_verification: false`。 +::: + +有关启用实验性功能的更多信息,请参阅[实验性功能标志](/install-and-configure/configuring-opensearch/experimental)。 + +#### 步骤 3:配置 JVM 选项 + +将这些设置添加到您的 `jvm.options` 文件中: + +```yaml +-Dio.netty.allocator.numDirectArenas=1 +-Dio.netty.noUnsafe=false +-Dio.netty.tryUnsafe=true +-Dio.netty.tryReflectionSetAccessible=true +--add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED +``` + +### 配置必要的 API + +使用以下步骤配置 API。 + +#### 步骤 1:启用流式功能标志 + +要启用流式功能标志,请按如下方式更新集群设置: + +```json +PUT /_cluster/settings +{ + "persistent" : { + "plugins.ml_commons.stream_enabled": true + } +} +``` + +#### 步骤 2:注册兼容的外部托管模型 + +要注册 OpenAI Chat Completion 模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "OpenAI gpt-4o-mini", + "function_name": "remote", + "description": "OpenAI model", + "connector": { + "name": "OpenAI Chat Connector", + "description": "The connector to OpenAI model service for gpt-4o-mini", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-4o-mini" + }, + "credential": { + "openAI_key": "<your_api_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\": [{\"role\":\"developer\",\"content\":\"${parameters.system_prompt}\"},${parameters._chat_history:-}{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] + } +} +``` + +要注册 Amazon Bedrock Converse Stream 模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Amazon Bedrock Converse Stream model", + "function_name": "remote", + "description": "Amazon Bedrock Claude model", + "connector": { + "name": "Amazon Bedrock Converse", + "description": "The connector to Amazon Bedrock Converse", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<your_aws_access_key>", + "secret_key": "<your_aws_secret_key>", + "session_token": "<your_aws_session_token>" + }, + "parameters": { + "region": "<your_aws_region>", + "service_name": "bedrock", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "request_body": "{ \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [${parameters._chat_history:-}{\"role\":\"user\",\"content\":[{\"text\":\"${parameters.prompt}\"}]}${parameters._interactions:-}]${parameters.tool_configs:-} }" + } + ] + } +} +``` + +#### 步骤 3:注册会话代理 + +注册代理时,您必须包含与模型类型对应的 `_llm_interface` 参数: +- OpenAI Chat Completion: `openai/v1/chat/completions` +- Amazon Bedrock Converse Stream: `bedrock/converse/claude` + +要注册代理,请发送以下请求: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Chat Agent with RAG", + "type": "conversational", + "description": "This is a test agent", + "llm": { + "model_id": "<model_id_from_step_2>", + "parameters": { + "max_iteration": 5, + "system_prompt": "You are a helpful assistant. You are able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics.\nIf the question is complex, you will split it into several smaller questions, and solve them one by one. For example, the original question is:\nhow many orders in last three month? Which month has highest?\nYou will spit into several smaller questions:\n1.Calculate total orders of last three month.\n2.Calculate monthly total order of last three month and calculate which months order is highest. You MUST use the available tools everytime to answer the question", + "prompt": "${parameters.question}" + } + }, + "memory": { + "type": "conversation_index" + }, + "parameters": { + "_llm_interface": "openai/v1/chat/completions" + }, + "tools": [ + { + "type": "IndexMappingTool", + "name": "DemoIndexMappingTool", + "parameters": { + "index": "${parameters.index}", + "input": "${parameters.question}" + } + }, + { + "type": "ListIndexTool", + "name": "RetrieveIndexMetaTool", + "description": "Use this tool to get OpenSearch index information: (health, status, index, uuid, primary count, replica count, docs.count, docs.deleted, store.size, primary.store.size)." + } + ], + "app_type": "my_app" +} +``` + +## 示例请求:会话代理 + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "parameters": { + "question": "How many indices are in my cluster?" + } +} +``` + +## 示例响应:会话代理 + +```json +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"[{\"index\":0.0,\"id\":\"call_HjpbrbdQFHK0omPYa6m2DCot\",\"type\":\"function\",\"function\":{\"name\":\"RetrieveIndexMetaTool\",\"arguments\":\"\"}}]","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"[{\"index\":0.0,\"function\":{\"arguments\":\"{}\"}}]","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"{\"choices\":[{\"message\":{\"tool_calls\":[{\"type\":\"function\",\"function\":{\"name\":\"RetrieveIndexMetaTool\",\"arguments\":\"{}\"},\"id\":\"call_HjpbrbdQFHK0omPYa6m2DCot\"}]},\"finish_reason\":\"tool_calls\"}]}","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards)\n1,green,open,.plugins-ml-model-group,Msb1Y4W5QeiLs5yUQi-VRg,1,1,2,0,17.1kb,5.9kb\n2,green,open,.plugins-ml-memory-message,1IWd1HPeSWmM29qE6rcj_A,1,1,658,0,636.4kb,313.5kb\n3,green,open,.plugins-ml-memory-meta,OETb21fqQJa3Y2hGQbknCQ,1,1,267,7,188kb,93.9kb\n4,green,open,.plugins-ml-config,0mnOWX5gSX2s-yP27zPFNw,1,1,1,0,8.1kb,4kb\n5,green,open,.plugins-ml-model,evYOOKN4QPqtmUjxsDwJYA,1,1,5,5,421.5kb,210.7kb\n6,green,open,.plugins-ml-agent,I0SpBovjT3C6NABCBzGiiQ,1,1,6,0,205.5kb,111.3kb\n7,green,open,.plugins-ml-task,_Urzn9gdSuCRqUaYAFaD_Q,1,1,100,4,136.1kb,45.3kb\n8,green,open,top_queries-2025.09.26-00444,jb7Q1FiLSl-wTxjdSUKs_w,1,1,1736,126,1.8mb,988kb\n9,green,open,.plugins-ml-connector,YaJORo4jT0Ksp24L5cW1uA,1,1,2,0,97.8kb,48.9kb\n","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"There","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" are","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" ","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"9","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" indices","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" in","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" your","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":" cluster","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":".","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"","is_last":true}}]}]} +``` + +## 包含令牌使用情况的示例请求 +<Badge type="tip" text="3.6 版本引入" /> + +要在流式响应中接收详细的令牌使用情况指标,请将 `include_token_usage` 设置为 `true`: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "parameters": { + "question": "How many indices are in my cluster?", + "include_token_usage": true + } +} +``` + +### 包含令牌使用情况的示例响应 + +流式响应包括在内容块之后和最终完成块之前发送的 `token_usage` 块: + +```json +... (内容块如上所示) ... + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"token_usage","dataAsMap":{"per_turn_usage":[{"turn":1,"model_id":"rk6okJwB_kOxOUbO6853","model_name":"gpt-4o-mini","model_url":"https://api.openai.com/v1/chat/completions","input_tokens":1042,"output_tokens":69,"total_tokens":1111,"cache_read_input_tokens":0}],"per_model_usage":[{"model_id":"rk6okJwB_kOxOUbO6853","model_name":"gpt-4o-mini","model_url":"https://api.openai.com/v1/chat/completions","call_count":1,"input_tokens":1042,"output_tokens":69,"total_tokens":1111,"cache_read_input_tokens":0}]}}]}]} + +data: {"inference_results":[{"output":[{"name":"memory_id","result":"LvU1iJkBCzHrriq5hXbN"},{"name":"parent_interaction_id","result":"L_U1iJkBCzHrriq5hXbs"},{"name":"response","dataAsMap":{"content":"","is_last":true}}]}]} +``` + +## 示例请求:AG-UI 代理 +<Badge type="tip" text="3.5 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。要获取功能进展的更新或留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/) 的讨论。 +::: + +AG-UI 代理使用 AG-UI 协议格式进行前端集成: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute/stream +{ + "threadId": "thread-xxxxx", + "runId": "run-xxxxx", + "messages": [ + { + "id": "msg-xxxxx", + "role": "user", + "content": "How many indices are in my cluster?" + } + ], + "tools": [], + "context": [], + "state": {}, + "forwardedProps": {} +} +``` + +## 示例响应:AG-UI 代理 + +AG-UI 代理使用 AG-UI 协议格式返回 SSE: + +```json +data: {"type":"RUN_STARTED","timestamp":1734567890123,"threadId":"thread-xxxxx","runId":"run-xxxxx"} + +data: {"type":"TEXT_MESSAGE_START","timestamp":1734567890124,"messageId":"msg-xxxxx","role":"assistant"} + +data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1734567890125,"messageId":"msg-xxxxx","delta":"Your cluster has 9 indices."} + +data: {"type":"TEXT_MESSAGE_END","timestamp":1734567890140,"messageId":"msg-xxxxx"} + +data: {"type":"RUN_FINISHED","timestamp":1734567890251,"threadId":"thread-xxxxx","runId":"run-xxxxx"} +``` + +有关完整的 AG-UI 代理文档,包括设置、前提条件、字段定义和实现细节,请参阅 [AG-UI 代理](/ml-commons-plugin/agents-tools/agents/ag-ui)。 + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- |:------------------------------------------------------------------------------------------------------------| +| `inference_results` | 数组 | 包含代理返回的流式响应数据。 | +| `inference_results.output` | 数组 | 包含每个推理结果的输出对象。 | +| `inference_results.output.name` | 字符串 | 输出字段的名称。可以是 `memory_id`、`parent_interaction_id`、`response` 或 `token_usage`。 | +| `inference_results.output.result` | 字符串 | `memory_id` 和 `parent_interaction_id` 字段的值。 | +| `inference_results.output.dataAsMap` | 对象 | 包含响应内容和元数据(适用于 `response` 和 `token_usage` 输出)。 | +| `inference_results.output.dataAsMap.content` | 字符串 | 代理的响应内容,可以包括工具调用、工具结果或最终文本输出。 | +| `inference_results.output.dataAsMap.is_last` | 布尔值 | 指示这是否是流中的最终块:`true` 表示最后一个块,`false` 表示还有更多块。 | +| `inference_results.output.dataAsMap.token_usage` | 对象 | 代理执行的令牌使用情况指标。在最终完成块之前作为单独的流块传递。仅在 `include_token_usage` 设置为 `true` 时存在。**3.6 版本引入** | + +### 流式响应中的令牌使用情况 +<Badge type="tip" text="3.6 版本引入" /> + +要在流式响应中启用令牌使用情况跟踪,请在请求中将 `parameters.include_token_usage` 字段设置为 `true`。启用后,流式响应序列如下: + +1. 内容块流式传输(`is_last: false`) +2. 发送包含详细指标的 `token_usage` 块 +3. 发送最终完成块(内容为空且 `is_last: true`) + +令牌使用块包含与非流式 API 响应相同的结构: + +- **`per_turn_usage`**:代理执行期间每次 LLM 调用的令牌使用记录数组。每条记录包括 `turn`(序列号)、`model_id`、`model_name`、`model_url`、`input_tokens`、`output_tokens`、`total_tokens` 和可选的缓存相关字段。 +- **`per_model_usage`**:按模型分组的聚合令牌使用情况。每条记录包括 `model_id`、`model_name`、`model_url`、`call_count`(LLM 调用次数)、`input_tokens`、`output_tokens`、`total_tokens` 和可选的缓存相关字段。 + +有关令牌使用字段的完整描述以及不同模型提供商如何计算令牌,请参阅执行代理 API 文档中的[跟踪令牌使用情况](/ml-commons-plugin/api/agent-apis/execute-agent#tracking-token-usage)。 diff --git a/i18n/zh/ml-commons-plugin/api/agent-apis/update-agent.md b/i18n/zh/ml-commons-plugin/api/agent-apis/update-agent.md new file mode 100644 index 00000000..c05073ec --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agent-apis/update-agent.md @@ -0,0 +1,77 @@ +--- +title: 更新代理 +--- + +# 更新代理 API +<Badge type="tip" text="3.1 版本引入" /> + +使用此 API 更新现有代理的配置。 + +## 端点 + +```json +PUT /_plugins/_ml/agents/{agent_id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `agent_id` | 字符串 | 要更新的代理的代理 ID。 | + +## 请求体字段 + +下表列出了可用的请求字段。所有请求体字段都是可选的。 + +字段 | 数据类型 | 代理类型 | 描述 +:--- | :--- | :--- | :--- +`name`| 字符串 | 全部 | 代理名称。 +`description` | 字符串 | 全部 | 代理的描述。 +`tools` | 数组 | 全部 | 代理要执行的工具列表。 +`app_type` | 字符串 | 全部 | 指定可选的代理类别。 +`memory.type` | 字符串 | `conversational_flow`、`conversational` | 指定存储会话记忆的位置。唯一支持的类型是 `conversation_index`(将记忆存储在会话系统索引中)。 +`llm.model_id` | 字符串 | `conversational` | 要向其发送问题的大型语言模型(LLM)的模型 ID。 +`llm.parameters.response_filter` | 字符串 | `conversational` | 用于解析 LLM 响应的模式。 +`llm.parameters.max_iteration` | 整数 | `conversational` | 要发送到 LLM 的最大消息数。 +`parameters` | 对象 | 全部 | 代理参数。您提供的参数与现有代理参数合并,覆盖具有相同名称的参数。 + +## 示例请求:更新工具提示 + +```json +PUT /_plugins/_ml/agents/N8AE1osB0jLkkocYjz7D +{ + "name": "Updated_Test_Agent_For_RAG", + "description": "Updated description for test agent", + "tools": [ + { + "type": "MLModelTool", + "description": "Updated general tool to answer any question", + "parameters": { + "model_id": "NWR9YIsBUysqmzBdifVJ", + "prompt": "This is an updated prompt" + } + } + ] +} +``` + +## 示例响应 + +```json +{ + "_index": ".plugins-ml-agent", + "_id": "ryN5jpcBfY4uTYhorKvh", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/add-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/add-memory.md new file mode 100644 index 00000000..3732188d --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/add-memory.md @@ -0,0 +1,194 @@ +--- +title: 添加代理记忆 +--- + +# 添加代理记忆 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 将代理记忆添加到[记忆容器](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container)。您可以指定不同的[有效负载类型](/ml-commons-plugin/agentic-memory#payload-types),并控制 OpenSearch 如何处理记忆的[推理模式](/ml-commons-plugin/agentic-memory#inference-mode)。 + +创建代理记忆后,将其 `memory_id` 提供给其他 API。 + +## 端点 + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 要向其添加记忆的记忆容器的 ID。 | + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`messages` | 数组 | 条件性 | `conversational` 有效负载的消息列表。每条消息必须包含指定为对象数组的 `content` 字段。每个对象必须包含 `type`(例如,`text`)和相应的内容。当 `infer` 设置为 `true` 时,每条消息可能包含 `role`(通常为 `user` 或 `assistant`)。当 `payload_type` 为 `conversational` 时必需。 +`structured_data` | 对象 | 条件性 | 数据记忆的结构化数据内容。当 `payload_type` 为 `data` 时必需。 +`structured_data_blob` | 对象 | 可选 | 与记忆一起存储但不索引的结构化数据,因此无法搜索。 +`binary_data` | 字符串 | 可选 | 编码为 Base64 字符串的二进制数据内容,用于二进制有效负载。 +`payload_type` | 字符串 | 可选 | 有效负载类型。有效值为 `conversational` 或 `data`。默认为 `conversational`。请参阅[有效负载类型](/ml-commons-plugin/agentic-memory#payload-types)。 +`namespace` | 对象 | 可选 | 用于组织记忆的[命名空间](/ml-commons-plugin/agentic-memory#namespaces)上下文(例如,`user_id`、`session_id` 或 `agent_id`)。如果 `namespace` 字段中未指定 `session_id`,`payload_type` 为 `conversational`,记忆容器具有 `llm_id`,且 `disable_session` 为 `false`(默认值),则会创建一个具有新会话 ID 的新会话。LLM 从消息生成会话摘要。 +`metadata` | 对象 | 可选 | 记忆的附加元数据(例如,`status`、`branch` 或自定义字段)。 +`tags` | 对象 | 可选 | 用于分类和组织记忆的标签。 +`message_id` | 整数 | 可选 | 对话中消息的序列号。代理使用此字段对对话消息进行排序。 +`checkpoint_id` | 字符串 | 可选 | 要与记忆一起存储的检查点标识符。 +`parameters` | 对象 | 可选 | 仅针对此请求覆盖记忆容器的 [`parameters`](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container#the-parameters-object) 的参数。 +`infer` | 布尔值 | 可选 | 是否使用大型语言模型(LLM)从消息中提取关键信息。默认为 `false`。当为 `true` 时,LLM 从原始文本中提取关键信息并将其存储为记忆。需要记忆容器具有 `llm_id`。请参阅[推理模式](/ml-commons-plugin/agentic-memory#inference-mode)。 + +::: info NOTE +此 API 创建 `working` 记忆,这些记忆无法固定,因此请求会拒绝 `pinned` 字段。要从保留策略中排除对话,请在添加记忆后固定其会话。有关更多信息,请参阅[固定记忆](/ml-commons-plugin/agentic-memory-retention#pinning-memories)。 +::: + +## 示例请求:会话有效负载 + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories +{ + "messages": [ + { + "role": "user", + "content": [ + { + "text": "I'm Bob, I really like swimming.", + "type": "text" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "text": "Cool, nice. Hope you enjoy your life.", + "type": "text" + } + ] + } + ], + "namespace": { + "user_id": "bob" + }, + "metadata": { + "status": "checkpoint", + "branch": { + "branch_name": "high", + "root_event_id": "228nadfs879mtgk" + } + }, + "tags": { + "topic": "personal info" + }, + "infer": true, + "payload_type": "conversational" +} +``` + +## 示例响应:会话有效负载 + +```json +{ + "session_id": "XSEuiJkBeh2gPPwzjYVh", + "working_memory_id": "XyEuiJkBeh2gPPwzjYWM" +} +``` + +## 示例请求:数据有效负载 + +要在工作记忆中存储代理状态,请发送以下请求: + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories +{ + "structured_data": { + "time_range": { + "start": "2025-09-11", + "end": "2025-09-15" + } + }, + "namespace": { + "agent_id": "testAgent1" + }, + "metadata": { + "status": "checkpoint", + "anyobject": "abc" + }, + "tags": { + "topic": "agent_state" + }, + "infer": false, + "payload_type": "data" +} +``` + +## 示例响应:数据有效负载 + +```json +{ + "working_memory_id": "Z8xeTpkBvwXRq366l0iA" +} +``` + +## 示例请求:存储工具调用数据 + +要在工作记忆中存储代理跟踪数据,请发送以下请求: + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories +{ + "structured_data": { + "tool_invocations": [ + { + "tool_name": "ListIndexTool", + "tool_input": { + "filter": "*,-.plugins*" + }, + "tool_output": "green open security-auditlog-2025.09.17..." + } + ] + }, + "namespace": { + "user_id": "bob", + "agent_id": "testAgent1", + "session_id": "123" + }, + "metadata": { + "status": "checkpoint", + "branch": { + "branch_name": "high", + "root_event_id": "228nadfs879mtgk" + }, + "anyobject": "abc" + }, + "tags": { + "topic": "personal info", + "parent_memory_id": "o4-WWJkBFT7urc7Ed9hM", + "data_type": "trace" + }, + "infer": false, + "payload_type": "data" +} +``` + +## 示例响应:跟踪数据 + +```json +{ + "session_id": "123", + "working_memory_id": "Z8xeTpkBvwXRq366l0iA" +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :-------------- | :-------- | :------------------------------------------------------------------------------------------------ | +| `session_id` | 字符串 | 与记忆关联的会话 ID。在创建会话或 `namespace` 包含 `session_id` 时返回。 | +| `working_memory_id` | 字符串 | 创建的工作记忆条目的唯一标识符。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/create-memory-container.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/create-memory-container.md new file mode 100644 index 00000000..c4abc2ca --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/create-memory-container.md @@ -0,0 +1,362 @@ +--- +title: 创建记忆容器 +--- + +# 创建记忆容器 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 创建[记忆容器](/ml-commons-plugin/agentic-memory#memory-containers)以存储代理记忆。该容器可以关联两种模型类型: + +- 文本嵌入模型,用于对消息进行向量化以便搜索。使用文本嵌入模型进行密集向量嵌入,或使用稀疏编码模型进行稀疏向量格式。如果未指定嵌入模型,则消息会被存储但不能用于基于向量的搜索。 +- 大型语言模型 (LLM),用于对消息进行推理以生成事实或处理后的内容。如果未指定 LLM,则消息会被直接存储,而不应用推理。长期记忆需要同时配置 LLM 模型和嵌入模型。 + +有关更多信息,请参阅[集成 ML 模型](/ml-commons-plugin/integrating-ml-models)。 + +::: info NOTE +LLM 连接器必须支持 `system_prompt` 和 `user_prompt` 参数以进行代理记忆处理。默认的 `llm_result_path` 是 Amazon Bedrock Converse API 响应路径(`"$.output.message.content[0].text"`)。如果使用 OpenAI GPT 模型,请将 `llm_result_path` 设置为 `$.choices[0].message.content`。 +::: + +创建记忆容器后,将其 `memory_container_id` 提供给其他 API。 + +## 创建的索引 + +为记忆容器创建的索引取决于您提供的 `configuration`。下表总结了相关行为。 + +配置 | 创建的索引 | 功能 +:--- | :--- | :--- +无 `configuration` 或无 `strategies` | 工作记忆 + 会话(除非 `disable_session` 为 `true`) | 原始消息存储和检索。无语义搜索,无长期记忆,无事实提取。 +带有 `strategies`(需要 `llm_id`、`embedding_model_id` 和 `embedding_model_type`) | 工作记忆 + 会话 + 长期记忆 + 历史记录(除非 `disable_session` 为 `true`) | 语义搜索、事实提取、记忆整合(ADD/UPDATE/DELETE 决策)以及所有长期记忆更改的审计跟踪。 + +每种索引类型都有特定用途: + +- **工作记忆**:存储接收到的原始消息。始终创建。 +- **会话**:跟踪对话会话及其元数据。默认创建。要禁用会话跟踪,请将 `disable_session` 设置为 `true`。 +- **长期记忆**:存储通过策略提取的事实和持久知识。仅在配置策略时创建。 +- **历史记录**:审计跟踪,记录对长期记忆的每次 ADD、UPDATE 和 DELETE 操作。仅在配置策略时创建。可通过将 `disable_history` 设置为 `true` 来选择退出。 + +## 前提条件 + +如果您想使用其中一种模型类型来处理记忆,请在 OpenSearch 中注册模型。 + +### 嵌入模型 + +注册本地或外部托管的嵌入模型。OpenSearch 支持文本嵌入和稀疏编码模型。 + +有关在本地使用模型的更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)。有关支持的模型列表,请参阅[OpenSearch 提供的预训练模型](/ml-commons-plugin/pretrained-models#supported-pretrained-models)。 + +有关使用外部托管模型的更多信息,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。例如,要注册外部托管的 Amazon Titan Embeddings 模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Bedrock embedding model", + "function_name": "remote", + "description": "test model", + "connector": { + "name": "Amazon Bedrock Connector: embedding", + "description": "The connector to bedrock Titan embedding model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "model": "amazon.titan-embed-text-v2:0", + "dimensions": 1024, + "normalize": true, + "embeddingTypes": [ + "float" + ] + }, + "credential": { + "access_key": "...", + "secret_key": "...", + "session_token": "..." + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": """{ "inputText": "${parameters.inputText}", "dimensions": ${parameters.dimensions}, "normalize": ${parameters.normalize}, "embeddingTypes": ${parameters.embeddingTypes} }""", + "pre_process_function": "connector.pre_process.bedrock.embedding", + "post_process_function": "connector.post_process.bedrock.embedding" + } + ] + } +} +``` + +### LLM + +要注册 Anthropic Claude 模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Bedrock infer model", + "function_name": "remote", + "description": "test model", + "connector": { + "name": "Amazon Bedrock Connector: Chat", + "description": "The connector to bedrock Claude Sonnet 4.6 model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "max_tokens": 8000, + "temperature": 1, + "model": "us.anthropic.claude-sonnet-4-6" + }, + "credential": { + "access_key": "...", + "secret_key": "...", + "session_token": "..." + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "request_body": "{ \"inferenceConfig\": { \"maxTokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }, \"system\": [{\"text\": \"${parameters.system_prompt}\"}], \"messages\": [ { \"role\": \"user\", \"content\": [ {\"text\": \"${parameters.user_prompt}\" }] }]}" + } + ] + } +} +``` + +::: info NOTE +Claude 模型需要 `system_prompt` 参数。 +::: + +要使 LLM 以固定的 JSON 模式返回提取的事实,请在连接器的 `predict` 操作中将 `supports_structured_output` 设置为 `true`。有关更多信息,请参阅 [actions 对象](/ml-commons-plugin/api/connector-apis/create-connector#the-actions-object)。 + +有关使用外部托管模型的更多信息,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 + +## 端点 + +```json +POST /_plugins/_ml/memory_containers/_create +``` + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`name` | String | 必需 | 记忆容器的名称。 +`memory_container_id` | String | 可选 | 记忆容器的唯一标识符。如果省略,OpenSearch 会自动生成一个。 +`description` | String | 可选 | 记忆容器的描述。 +`configuration` | Object | 可选 | 记忆容器配置。如果未提供,将使用默认配置,该配置创建一个仅具有工作记忆且无 AI 功能的容器。要获得包括语义搜索和长期记忆在内的完整功能,请提供带有模型 ID 和策略的配置。请参阅 [`configuration` 对象](#the-configuration-object)。 +`backend_roles` | Array | 可选 | 用于访问控制的后端角色列表。每个角色最多 128 个字符,只能包含字母数字字符和 `:+=,.@-_/`。 + +### configuration 对象 + +`configuration` 对象支持以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`embedding_model_type` | String | 可选 | 嵌入模型类型。支持的类型为 `TEXT_EMBEDDING` 和 `SPARSE_ENCODING`。如果提供了 `embedding_model_id`,则为必需。 +`embedding_model_id` | String | 可选 | 嵌入模型 ID。如果提供了 `embedding_model_type`,则为必需。 +`embedding_dimension` | Integer | 可选 | 嵌入模型的维度。如果 `embedding_model_type` 为 `TEXT_EMBEDDING`,则为必需。如果 `embedding_model_type` 为 `SPARSE_ENCODING`,则不允许使用。 +`llm_id` | String | 可选 | 用于处理和推理的 LLM 模型 ID。 +`index_prefix` | String | 可选 | 记忆索引的自定义前缀。如果未指定,则使用默认前缀:当 `use_system_index` 为 `true` 时为 `default`,当 `use_system_index` 为 `false` 时为 8 字符随机 UUID。 +`use_system_index` | Boolean | 可选 | 是否使用系统索引(以 `.plugins-ml-am-` 为前缀的隐藏索引)。默认为 `true`。 +`disable_history` | Boolean | 可选 | 是否禁用历史记录审计跟踪索引。默认为 `false`。此设置仅在配置策略时生效,因为历史记录索引记录长期记忆的更改。如果没有策略,无论此设置如何,都不会创建长期记忆或历史记录索引。 +`disable_session` | Boolean | 可选 | 是否禁用会话跟踪索引。默认为 `false`(默认启用会话)。设置为 `true` 以禁用会话跟踪。 +`max_infer_size` | Integer | 可选 | 在记忆整合期间检索的相似现有记忆的最大数量,用于做出 ADD/UPDATE/DELETE 决策。默认为 `5`。最大为 `10`。 +`index_settings` | Object | 可选 | 为此容器创建的记忆存储索引的自定义 OpenSearch 索引设置。每种记忆类型(`sessions`、`working`、`long_term` 和 `history`)使用自己的索引。请参阅 [`index_settings` 对象](#the-index_settings-object)。 +`strategies` | Array | 可选 | [记忆处理策略](/ml-commons-plugin/agentic-memory#memory-processing-strategies)数组。提供策略时,需要 `llm_id` 和嵌入模型字段(`embedding_model_id`、`embedding_model_type`)。请参阅 [`strategies` 数组](#the-strategies-array)。 +`parameters` | Object | 可选 | 记忆容器的全局参数。请参阅 [`parameters` 对象](#the-parameters-object)。 +`retention_policy` | Object | 可选 | 每种记忆类型的保留限制。需要 `plugins.ml_commons.memory.retention_enabled` 为 `true`。有关更多信息,请参阅[代理记忆保留](/ml-commons-plugin/agentic-memory-retention)。 + +### index_settings 对象 + +您可以为将要创建的用于存储记忆数据的存储索引自定义 OpenSearch 索引设置。每种记忆类型使用专用索引,您可以配置分片数和副本数等设置以优化性能。 + +::: info NOTE +索引设置仅在创建索引时应用。如果另一个记忆容器已使用相同的 `index_prefix`,则会重用现有索引并忽略指定的设置。 +::: + +以下示例展示了如何在 `configuration` 对象中指定自定义索引设置: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "my-memory-container", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "your-model-id", + "embedding_dimension": 1024, + "index_settings": { + "session_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + }, + "working_memory_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + }, + "long_term_memory_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + }, + "long_term_memory_history_index": { + "index": { + "number_of_shards": "2", + "number_of_replicas": "2" + } + } + } + } +} +``` + +### strategies 数组 + +`strategies` 数组中的每个策略支持以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`type` | String | 必需 | 策略类型。有效值为 `SEMANTIC`、`USER_PREFERENCE` 和 `SUMMARY`。 +`namespace` | Array | 必需 | 用于组织记忆的[命名空间](/ml-commons-plugin/agentic-memory#namespaces)维度数组(例如,`["user_id"]` 或 `["agent_id", "session_id"]`)。 +`configuration` | Object | 可选 | 特定于策略的配置。请参阅 [`strategies.configuration` 对象](#the-strategies-configuration-object)。 +`enabled` | Boolean | 可选 | 是否在记忆容器中启用该策略。默认为 `true`。 + +### strategies configuration 对象 + +`strategies.configuration` 对象支持以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`llm_result_path` | String | 可选 | 用于从响应中提取 LLM 结果的 JSONPath 表达式。默认为 Amazon Bedrock Converse API 响应路径(`"$.output.message.content[0].text"`)。 +`system_prompt` | String | 可选 | 用于覆盖默认策略提示的自定义系统提示。提示必须包含单词 `JSON` 和引号键 `"facts"`,并且必须指示 LLM 返回包含 `facts` 字符串数组的 JSON 对象。否则,事实提取将失败,错误将记录在历史记录索引中。 +`llm_id` | String | 可选 | 此策略的 LLM 模型 ID。覆盖全局 LLM 设置。 + +### parameters 对象 + +`parameters` 对象支持以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`llm_result_path` | String | 可选 | 用于从响应中提取 LLM 结果的全局 JSONPath 表达式。默认为 Amazon Bedrock Converse API 响应路径(`"$.output.message.content[0].text"`)。 +`session` | Object | 可选 | 当在没有 `session_id` 的情况下添加对话记忆时,LLM 生成的会话摘要参数。请参阅 [`session` 对象](#the-session-object)。 + +### session 对象 + +`session` 对象支持以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`max_summary_size` | Integer | 可选 | 会话摘要中的最大单词数。默认为 `10`。 +`system_prompt` | String | 可选 | 替换默认会话摘要提示的自定义系统提示。 + +OpenSearch 会将 `session` 对象中的任何其他字段作为连接器参数传递给 LLM 以进行摘要请求。例如,如果连接器的请求体使用 `${parameters.max_tokens}`,则在 `session` 对象中设置 `max_tokens` 会限制会话摘要的 LLM 响应长度。 + +## 示例请求:最小记忆容器 + +以下请求创建一个仅具有工作记忆(原始消息存储)的最小记忆容器。未配置 AI 模型或策略: + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "simple-message-store" +} +``` + +此请求创建一个具有工作记忆和会话索引的容器。可以按 ID 存储和检索消息,但语义搜索和长期记忆功能不可用。 + +## 示例请求:带策略的基本记忆容器 + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "<embedding_model_id>", + "embedding_dimension": 1024, + "llm_id": "<llm_id>", + "strategies": [ + { + "type": "SEMANTIC", + "namespace": ["user_id"] + } + ] + } +} +``` + +此请求创建一个具有工作记忆、会话、长期记忆和历史记录索引的容器。`SEMANTIC` 策略使用 LLM 从消息中提取事实,并使用嵌入模型对这些事实进行基于向量的语义搜索。 + +## 示例请求:具有多个策略的高级记忆容器 + +```json +POST /_plugins/_ml/memory_containers/_create +{ + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization", + "configuration": { + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "<embedding_model_id>", + "embedding_dimension": 1024, + "llm_id": "<llm_id>", + "index_prefix": "my_custom_prefix", + "use_system_index": false, + "strategies": [ + { + "type": "SEMANTIC", + "namespace": ["agent_id"], + "configuration": { + "llm_result_path": "$.output.message.content[0].text", + "system_prompt": "Extract semantic information from user conversations. Return only a JSON object in the format {\"facts\": [\"<fact>\"]}.", + "llm_id": "<custom_llm_id>" + } + }, + { + "type": "USER_PREFERENCE", + "namespace": ["agent_id"], + "configuration": { + "llm_result_path": "$.output.message.content[0].text" + } + }, + { + "type": "SUMMARY", + "namespace": ["agent_id"], + "configuration": { + "llm_result_path": "$.output.message.content[0].text" + } + } + ], + "parameters": { + "llm_result_path": "$.output.message.content[0].text" + } + } +} +``` + +## 示例响应 + +响应包含可用于检索或删除容器的 `memory_container_id`: + +```json +{ + "memory_container_id": "SdjmmpgBOh0h20Y9kWuN", + "status": "created" +} +``` diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/create-session.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/create-session.md new file mode 100644 index 00000000..37ee3f89 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/create-session.md @@ -0,0 +1,89 @@ +--- +title: 创建会话 +--- + +# 创建会话 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 在记忆容器中创建新会话。会话表示用户和代理之间的不同交互上下文。 + +## 端点 + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/sessions +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 将在其中创建会话的记忆容器的 ID。 | + +## 请求字段 + +下表列出了可用的请求体字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `session_id` | 字符串 | 可选 | 自定义会话 ID。如果提供,则使用此 ID 作为会话。如果未提供,则生成随机 ID。 | +| `summary` | 字符串 | 可选 | 会话摘要或描述。 | +| `metadata` | 对象 | 可选 | 会话的附加元数据,以键值对的形式提供。 | +| `namespace` | 对象 | 可选 | 用于组织会话的命名空间信息。 | +| `agents` | 对象 | 可选 | 有关参与会话的代理的信息,以键值对的形式提供。 | +| `additional_info` | 对象 | 可选 | 有关会话的附加信息,以键值对的形式提供。 | + +## 示例请求:创建具有自定义 ID 的会话 + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories/sessions +{ + "session_id": "abc123", + "metadata": { + "key1": "value1" + } +} +``` + +## 示例响应:自定义会话 ID + +```json +{ + "session_id": "abc123", + "status": "created" +} +``` + +## 示例请求:创建具有自动生成 ID 的会话 + +```json +POST /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN/memories/sessions +{ + "summary": "This is a test session", + "metadata": { + "key1": "value1" + }, + "namespace": { + "user_id": "bob" + } +} +``` + +## 示例响应:自动生成的会话 ID + +```json +{ + "session_id": "jTYm35kBt8CyICnjxJl9", + "status": "created" +} +``` + +## 响应字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `session_id` | 字符串 | 创建的会话的 ID(提供的或自动生成的)。 | +| `status` | 字符串 | 创建操作的状态。如果创建了新会话,则返回 `created`;如果具有指定 `session_id` 的会话已存在,则返回 `exists`。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/delete-memory-container.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/delete-memory-container.md new file mode 100644 index 00000000..0d9f2ff3 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/delete-memory-container.md @@ -0,0 +1,109 @@ +--- +title: 删除记忆容器 +--- + +# 删除记忆容器 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 通过 ID 删除记忆容器。 + +## 端点 + +```json +DELETE /_plugins/_ml/memory_containers/{memory_container_id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 要删除的记忆容器的 ID。 | + +## 查询参数 + +下表列出了可用的查询参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `delete_all_memories` | 布尔值 | 可选 | 控制在删除容器时是否删除所有记忆索引。默认为 `false`。当为 `false` 时,记忆索引(会话、工作、长期、历史)将被保留。 | +| `delete_memories` | 数组 | 可选 | 删除容器时要删除的记忆类型数组。默认为空数组。接受的值:`sessions`、`working`、`long-term`、`history`。示例:`delete_memories=sessions,working`。 | + +您还可以在请求体中提供 `delete_all_memories` 和 `delete_memories`。如果在两个位置都指定了参数,则查询参数优先。 + +## 示例请求:基本删除(保留记忆索引) + +```json +DELETE /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN +``` + +## 示例请求:删除容器和所有记忆索引 + +```json +DELETE /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN?delete_all_memories=true +``` + +## 示例请求:删除容器和特定记忆类型 + +```json +DELETE /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN?delete_memories=sessions,working +``` + +## 示例响应 + +```json +{ + "_index": ".plugins-ml-am-memory-container", + "_id": "SdjmmpgBOh0h20Y9kWuN", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 1 +} +``` + +## 错误响应 + +如果您尝试删除不存在的记忆容器,OpenSearch 将返回 404 未找到错误: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Memory container not found" + } + ], + "type": "status_exception", + "reason": "Memory container not found" + }, + "status": 404 +} +``` + +::: info NOTE +只有当没有其他记忆容器使用相同的 `index_prefix` 时,才能删除记忆索引。如果另一个容器共享该前缀,指定 `delete_all_memories` 或 `delete_memories` 的请求将失败并返回 409 冲突错误,且不会删除容器。要删除容器,请在不使用这些参数的情况下发送请求。 +::: + +## 响应字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_index` | 字符串 | 存储记忆容器的索引名称。 | +| `result` | 字符串 | 删除操作的结果。 | +| `_id` | 字符串 | 已删除记忆容器的 ID。 | +| `_version` | 整数 | 删除后的版本号。 | +| `forced_refresh` | 布尔值 | 操作后是否强制刷新。 | +| `_shards` | 对象 | 有关参与操作的分片的信息。 | +| `_seq_no` | 长整数 | 分配给删除操作的序列号。 | +| `_primary_term` | 长整数 | 索引的主术语。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/delete-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/delete-memory.md new file mode 100644 index 00000000..ac0ce508 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/delete-memory.md @@ -0,0 +1,179 @@ +--- +title: 删除代理记忆 +--- + +# 删除代理记忆 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 通过类型和 ID 删除特定记忆,或删除与查询匹配的记忆。此统一 API 支持删除任何[记忆类型](/ml-commons-plugin/agentic-memory#memory-types)的记忆:`sessions`、`working`、`long-term` 或 `history`。 + +## 通过类型和 ID 删除记忆 + +使用此 API 通过类型和 ID 删除记忆。 + +### 端点 + +```json +DELETE /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/{id} +``` + +### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 要从中删除记忆的记忆容器的 ID。 | +| `type` | 字符串 | 必需 | 要删除的记忆类型。有效值为 `sessions`、`working`、`long-term` 和 `history`。 | +| `id` | 字符串 | 必需 | 要删除的特定记忆的 ID。 | + +### 示例请求:删除工作记忆 + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/XyEuiJkBeh2gPPwzjYWM +``` + +### 示例请求:删除长期记忆 + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/DcxjTpkBvwXRq366C1Zz +``` + +### 示例请求:删除会话记忆 + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/CcxjTpkBvwXRq366A1aE +``` + +### 示例请求:删除历史记忆 + +```json +DELETE /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/history/eMxnTpkBvwXRq366hmAU +``` + +### 示例响应 + +```json +{ + "_index": ".plugins-ml-am-default-memory-working", + "_id": "XyEuiJkBeh2gPPwzjYWM", + "_version": 2, + "result": "deleted", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 1 +} +``` + +### 错误响应 + +如果您尝试从不存在的容器中删除记忆,OpenSearch 将返回 404 未找到错误。如果记忆不存在,OpenSearch 也会返回 404 错误。对于不存在的容器,将返回以下响应: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Memory container not found" + } + ], + "type": "status_exception", + "reason": "Memory container not found" + }, + "status": 404 +} +``` + +### 响应字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_index` | 字符串 | 从中删除记忆的索引名称。 | +| `result` | 字符串 | 删除操作的结果。 | +| `_id` | 字符串 | 已删除记忆的 ID。 | +| `_version` | 整数 | 删除后的版本号。 | +| `_shards` | 对象 | 有关参与操作的分片的信息。 | +| `_seq_no` | 长整数 | 分配给删除操作的序列号。 | +| `_primary_term` | 长整数 | 索引的主术语。 | + +## 通过查询删除记忆 + +使用此 API 使用查询删除多个匹配特定条件的记忆。 + +### 端点 + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/_delete_by_query +``` + +### 路径参数 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:----------------------| :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 要从中删除记忆的记忆容器的 ID。 | +| `type` | 字符串 | 必需 | 要删除的记忆类型。有效值为 `sessions`、`working`、`long-term` 和 `history`。 | + +### 请求体字段 + +请求体必须包含用于匹配要删除的记忆的查询。 + +### 示例请求 + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/_delete_by_query +{ + "query": { + "match": { + "owner_id": "admin" + } + } +} +``` + +### 示例响应 + +```json +{ + "took": 159, + "timed_out": false, + "total": 6, + "updated": 0, + "created": 0, + "deleted": 6, + "batches": 1, + "version_conflicts": 0, + "noops": 0, + "retries": { + "bulk": 0, + "search": 0 + }, + "throttled_millis": 0, + "requests_per_second": -1.0, + "throttled_until_millis": 0, + "failures": [] +} +``` + +### 响应字段 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `took` | 整数 | 执行请求所花费的时间(以毫秒为单位)。 | +| `timed_out` | 布尔值 | 请求是否超时。 | +| `total` | 整数 | 处理的文档总数。 | +| `deleted` | 整数 | 删除的文档数。 | +| `batches` | 整数 | 处理的批次数。 | +| `version_conflicts` | 整数 | 遇到的版本冲突数。 | +| `noops` | 整数 | 无操作更新的数量。 | +| `retries` | 对象 | 有关批量和搜索重试的信息。 | +| `throttled_millis` | 整数 | 请求被节流的时间(以毫秒为单位)。 | +| `requests_per_second` | 浮点数 | 每秒处理的请求数。 | +| `throttled_until_millis` | 整数 | 节流解除前的时间(以毫秒为单位)。 | +| `failures` | 数组 | 操作期间发生的任何故障。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/get-memory-container.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/get-memory-container.md new file mode 100644 index 00000000..b1680b1e --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/get-memory-container.md @@ -0,0 +1,66 @@ +--- +title: 获取记忆容器 +--- + +# 获取记忆容器 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 通过 ID 检索记忆容器。 + +## 端点 + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 要检索的记忆容器的 ID。 | + +## 示例请求 + +```json +GET /_plugins/_ml/memory_containers/SdjmmpgBOh0h20Y9kWuN +``` + +## 示例响应 + +```json +{ + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization", + "created_time": 1792070644500, + "last_updated_time": 1792070644500, + "configuration": { + "index_prefix": "default", + "llm_id": "aFouy5kBrfmzAZ6R6wo-", + "embedding_model_type": "TEXT_EMBEDDING", + "embedding_model_id": "uXZAtJkBvHNmcp1JAROh", + "embedding_dimension": 1024, + "max_infer_size": 5, + "strategies": [ + { + "id": "semantic_53d1751c", + "enabled": true, + "type": "SEMANTIC", + "namespace": [ + "user_id" + ] + } + ], + "disable_history": false, + "disable_session": false, + "use_system_index": true + } +} +``` + +## 响应体字段 + +有关响应字段描述,请参阅[创建记忆容器 API 请求字段](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container#request-body-fields)。 + +响应中的每个[策略](/ml-commons-plugin/agentic-memory#memory-processing-strategies)还包含由 OpenSearch 生成的 `id`。要更新策略,请在[更新记忆容器 API](/ml-commons-plugin/api/agentic-memory-apis/update-memory-container) 请求中提供此 `id`。 diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/get-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/get-memory.md new file mode 100644 index 00000000..7a0fa685 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/get-memory.md @@ -0,0 +1,231 @@ +--- +title: 获取代理记忆 +--- + +# 获取代理记忆 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 通过类型和 ID 检索特定记忆。此统一 API 支持四种[记忆类型](/ml-commons-plugin/agentic-memory#memory-types):`sessions`、`working`、`long-term` 和 `history`。 + +## 端点 + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/{id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 要从中检索记忆的记忆容器的 ID。 | +| `type` | 字符串 | 必需 | 记忆类型。有效值为 `sessions`、`working`、`long-term` 和 `history`。 | +| `id` | 字符串 | 必需 | 要检索的记忆的 ID。 | + +## 示例请求:获取工作记忆 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/XyEuiJkBeh2gPPwzjYWM +``` + +## 示例响应:工作记忆 + +```json +{ + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "payload_type": "conversational", + "messages": [ + { + "role": "user", + "content": [ + { + "text": "I'm Bob, I really like swimming.", + "type": "text" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "text": "Cool, nice. Hope you enjoy your life.", + "type": "text" + } + ] + } + ], + "namespace": { + "user_id": "bob", + "session_id": "S-dqiJkB1SltqOcZ1cYO" + }, + "namespace_size": 2, + "infer": true, + "metadata": { + "branch": "{\"root_event_id\":\"228nadfs879mtgk\",\"branch_name\":\"high\"}", + "status": "checkpoint" + }, + "tags": { + "topic": "personal info" + }, + "created_time": 1758930326804, + "last_updated_time": 1758930326804 +} +``` + +## 示例请求:获取长期记忆 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/DcxjTpkBvwXRq366C1Zz +``` + +## 示例响应:长期记忆 + +```json +{ + "memory": "Kubernetes RBAC permission issues detected with CloudWatch agents experiencing persistent permission denials", + "strategy_type": "SUMMARY", + "tags": { + "agent_type": "chat_agent", + "conversation": "true" + }, + "namespace": { + "agent_id": "chat-agent" + }, + "namespace_size": 1, + "created_time": 1760052801773, + "last_updated_time": 1760052801773, + "memory_embedding": [0.018510794, 0.056366503, "..."], + "owner_id": "admin", + "strategy_id": "summary_96f04d97" +} +``` + +## 示例请求:获取会话 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/CcxjTpkBvwXRq366A1aE +``` + +## 示例响应:会话 + +```json +{ + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "summary": "This is a test session", + "created_time": 1757956735881, + "last_updated_time": 1757956735881, + "namespace": { + "user_id": "bob" + } +} +``` + +## 示例请求:获取历史记忆 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/history/eMxnTpkBvwXRq366hmAU +``` + +## 示例响应:历史 + +```json +{ + "owner_id": "admin", + "memory_container_id": "nrJBy5kByIxXWyhQjmqv", + "memory_id": "4bJMy5kByIxXWyhQvGr9", + "action": "ADD", + "after": { + "memory": "A comprehensive security investigation was performed across multiple data sources including 55 OpenSearch indices, 50 CloudTrail events, 22 VPC Flow logs, 38 WAF events, 74 CloudWatch log groups, active CloudWatch alarms, and OpenSearch cluster security configuration." + }, + "namespace": { + "agent_id": "chat-agent" + }, + "namespace_size": 1, + "tags": { + "agent_type": "chat_agent", + "conversation": "true" + }, + "created_time": 1760052428089 +} +``` + +## 响应字段 + +响应字段因记忆类型而异。 + +### 工作记忆响应字段 + +下表列出了所有工作记忆响应体字段。 + +| 字段 | 数据类型 | 描述 | +|:----------------------| :--- |:--------------------------------------------------------| +| `memory_container_id` | 字符串 | 记忆容器的 ID。 | +| `payload_type` | 字符串 | 有效负载类型。有效值为 `conversational` 和 `data`。 | +| `messages` | 数组 | 对话消息数组(仅适用于 `conversational` 有效负载类型)。 | +| `structured_data` | 对象 | 结构化数据内容(仅适用于 `data` 有效负载类型)。 | +| `structured_data_blob` | 对象 | 未索引存储的结构化数据。 | +| `binary_data` | 字符串 | Base64 编码的二进制数据内容。 | +| `message_id` | 整数 | 对话中消息的序列号。 | +| `checkpoint_id` | 字符串 | 与记忆一起存储的检查点标识符。 | +| `namespace` | 对象 | 此记忆的命名空间上下文。 | +| `namespace_size` | 整数 | 命名空间字段的数量。 | +| `owner_id` | 字符串 | 记忆所有者的 ID。仅在启用安全插件时存在。 | +| `metadata` | 对象 | 与记忆关联的附加元数据。 | +| `tags` | 对象 | 用于分类的关联标签。 | +| `infer` | 布尔值 | 是否为此记忆启用了推理。 | +| `created_time` | 长整数 | 创建记忆时的时间戳。 | +| `last_updated_time` | 长整数 | 上次更新记忆时的时间戳。 | + +### 长期记忆响应字段 + +下表列出了所有长期记忆响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `memory` | 字符串 | 提取的长期记忆事实。 | +| `strategy_type` | 字符串 | 使用的记忆策略类型(例如,`SEMANTIC`、`SUMMARY` 或 `USER_PREFERENCE`)。 | +| `namespace` | 对象 | 此记忆的命名空间上下文。 | +| `namespace_size` | 整数 | 命名空间的数量。 | +| `tags` | 对象 | 用于分类的关联标签。 | +| `created_time` | 长整数 | 创建记忆时的时间戳。 | +| `last_updated_time` | 长整数 | 上次更新记忆时的时间戳。 | +| `memory_embedding` | 数组 | 记忆内容的向量嵌入(显示时已截断)。 | +| `owner_id` | 字符串 | 记忆所有者的 ID。 | +| `strategy_id` | 字符串 | 策略实例的唯一标识符。 | +| `pinned` | 布尔值 | 记忆是否已固定并免于容器的保留策略。 | + +### 会话响应字段 + +下表列出了所有会话响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 记忆容器的 ID。 | +| `summary` | 字符串 | 会话摘要。 | +| `metadata` | 对象 | 与会话关联的附加元数据。 | +| `agents` | 对象 | 有关参与会话的代理的信息。 | +| `additional_info` | 对象 | 有关会话的附加信息。 | +| `namespace` | 对象 | 此会话的命名空间上下文。 | +| `owner_id` | 字符串 | 会话所有者的 ID。仅在启用安全插件时存在。 | +| `pinned` | 布尔值 | 会话是否已固定并免于容器的保留策略。 | +| `created_time` | 长整数 | 创建会话时的时间戳。 | +| `last_updated_time` | 长整数 | 上次更新会话时的时间戳。 | + +### 历史响应字段 + +下表列出了所有历史响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `owner_id` | 字符串 | 记忆所有者的 ID。 | +| `memory_container_id` | 字符串 | 记忆容器的 ID。 | +| `memory_id` | 字符串 | 受影响记忆的 ID。 | +| `action` | 字符串 | 操作类型:`ADD`、`UPDATE` 或 `DELETE`。 | +| `after` | 对象 | 操作后的记忆内容。 | +| `before` | 对象 | 操作前的记忆内容(适用于 `UPDATE` 操作)。 | +| `namespace` | 对象 | 此记忆的命名空间上下文。 | +| `namespace_size` | 整数 | 命名空间的数量。 | +| `tags` | 对象 | 用于分类的关联标签。 | +| `error` | 字符串 | 如果操作失败则显示错误消息。 | +| `created_time` | 长整数 | 操作发生时的时间戳。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory.md new file mode 100644 index 00000000..38d63ed2 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory.md @@ -0,0 +1,170 @@ +--- +title: 混合搜索代理记忆 +--- + +# 混合搜索代理记忆 API +<Badge type="tip" text="3.6 版本引入" /> + +使用此 API 结合 BM25 关键词匹配和语义搜索来搜索长期记忆。当您的查询同时受益于精确关键词精度和语义理解时,这很有用。 + +混合搜索在单个查询中结合了两种搜索方法: + +1. **BM25 关键词搜索**:在 `memory` 字段上进行 `match` 查询以进行精确关键词匹配。 +2. **神经向量搜索**:在 `memory_embedding` 字段上进行 `neural` 查询(或 `SPARSE_ENCODING` 模型的 `neural_sparse`)以进行语义相似性搜索。 + +使用内联归一化处理器管道结合结果,使用 `min_max` 归一化和 `arithmetic_mean` 组合。`bm25_weight` 和 `neural_weight` 参数控制每种搜索方法的相对重要性。不需要预配置搜索管道。 + +::: info NOTE +记忆容器必须配置嵌入模型和至少一个[记忆策略](/ml-commons-plugin/agentic-memory#memory-processing-strategies)。 +::: + +## 端点 + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_hybrid_search +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_hybrid_search +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | 字符串 | 必需 | 记忆容器的 ID。 | + +## 请求字段 + +下表列出了可用的请求字段。 + +| 字段 | 数据类型 | 必需/可选 | 默认值 | 描述 | +| :--- | :--- | :--- | :--- | :--- | +| `query` | 字符串 | 必需 | 不适用 | 用于 BM25 关键词匹配和语义搜索的自然语言搜索查询。 | +| `k` | 整数 | 可选 | 10 | 要返回的结果数。有效值为 `1`–`10000`(含)。 | +| `namespace` | 对象 | 可选 | 不适用 | 按命名空间字段过滤结果。例如,`{"user_id": "alice"}`。 | +| `tags` | 对象 | 可选 | 不适用 | 按标签字段过滤结果。例如,`{"topic": "food"}`。 | +| `min_score` | 浮点数 | 可选 | 不适用 | 最小相关性得分阈值。低于此得分的结果将被排除。 | +| `filter` | 对象 | 可选 | 不适用 | 与混合查询一起应用的附加 [Query DSL](/query-dsl/) 过滤器。 | +| `bm25_weight` | 浮点数 | 可选 | 0.5 | BM25 关键词搜索组件的权重。有效值为 `0.0`–`1.0`。`bm25_weight` 和 `neural_weight` 的总和必须等于 `1.0`。 | +| `neural_weight` | 浮点数 | 可选 | 0.5 | 神经向量搜索组件的权重。有效值为 `0.0`–`1.0`。`bm25_weight` 和 `neural_weight` 的总和必须等于 `1.0`。 | + +## 示例请求:基本混合搜索 + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_hybrid_search +{ + "query": "retirement timeline five years portfolio rebalancing", + "k": 10, + "namespace": { + "user_id": "bob" + } +} +``` + +## 示例请求:自定义权重 + +您可以为每个请求调整关键词和语义搜索之间的平衡。增加 `neural_weight` 会优先考虑语义相似性,而增加 `bm25_weight` 会优先考虑精确关键词匹配: + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_hybrid_search +{ + "query": "machine learning outdoor activities", + "k": 5, + "namespace": { + "user_id": "alice" + }, + "bm25_weight": 0.3, + "neural_weight": 0.7 +} +``` + +## 示例请求:最小得分和标签过滤 + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_hybrid_search +{ + "query": "LGBTQ workshop therapeutic methods", + "k": 10, + "namespace": { + "user_id": "caroline" + }, + "tags": { + "topic": "wellness" + }, + "min_score": 0.3 +} +``` + +## 示例响应 + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "abc123", + "_score": 1.0, + "_source": { + "created_time": 1700000000000, + "memory": "Caroline attended an LGBTQ+ counseling workshop focused on therapeutic methods", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "caroline" + }, + "strategy_id": "semantic_53d1751c", + "strategy_type": "SEMANTIC", + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "tags": { + "topic": "wellness" + } + } + }, + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "def456", + "_score": 0.52, + "_source": { + "created_time": 1700000000000, + "memory": "Caroline attended an LGBTQ conference on community building", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "caroline" + }, + "strategy_id": "semantic_53d1751c", + "strategy_type": "SEMANTIC", + "memory_container_id": "HudqiJkB1SltqOcZusVU", + "tags": { + "topic": "wellness" + } + } + } + ] + } +} +``` + +## 响应字段 + +响应使用标准的 OpenSearch 搜索响应格式。有关字段描述,请参阅[语义搜索记忆响应字段](/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory#response-fields)。 + +响应中排除了 `memory_embedding` 字段。 + +## 相关文档 + +- [混合搜索](/vector-search/ai-search/hybrid-search/) diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/index.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/index.md new file mode 100644 index 00000000..308bb9be --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/index.md @@ -0,0 +1,40 @@ +--- +title: 代理记忆 API +--- + +# 代理记忆 API +<Badge type="tip" text="3.3 版本引入" /> + +代理记忆 API 为 AI 代理提供持久化的记忆管理功能。有关概念、用例和入门信息的概述,请参阅[代理记忆](/ml-commons-plugin/agentic-memory)。 + +## 禁用代理记忆 API + +代理记忆 API 默认启用。要禁用代理记忆 API,请更新以下集群设置: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.agentic_memory_enabled": false + } +} +``` + +OpenSearch 支持以下记忆容器 API: + +- [创建记忆容器](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container) +- [获取记忆容器](/ml-commons-plugin/api/agentic-memory-apis/get-memory-container) +- [更新记忆容器](/ml-commons-plugin/api/agentic-memory-apis/update-memory-container) +- [删除记忆容器](/ml-commons-plugin/api/agentic-memory-apis/delete-memory-container) +- [搜索记忆容器](/ml-commons-plugin/api/agentic-memory-apis/search-memory-container) + +OpenSearch 支持以下记忆 API: + +- [添加记忆](/ml-commons-plugin/api/agentic-memory-apis/add-memory) +- [创建会话](/ml-commons-plugin/api/agentic-memory-apis/create-session) +- [获取记忆](/ml-commons-plugin/api/agentic-memory-apis/get-memory) +- [更新记忆](/ml-commons-plugin/api/agentic-memory-apis/update-memory) +- [删除记忆](/ml-commons-plugin/api/agentic-memory-apis/delete-memory) +- [搜索记忆](/ml-commons-plugin/api/agentic-memory-apis/search-memory) +- [语义搜索记忆](/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory) +- [混合搜索记忆](/ml-commons-plugin/api/agentic-memory-apis/hybrid-search-memory) diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/search-memory-container.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/search-memory-container.md new file mode 100644 index 00000000..680c59b1 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/search-memory-container.md @@ -0,0 +1,101 @@ +--- +title: 搜索记忆容器 +--- + +# 搜索记忆容器 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 通过 OpenSearch 查询领域特定语言 (DSL) 搜索记忆容器。 + +## 端点 + +```json +GET /_plugins/_ml/memory_containers/_search +POST /_plugins/_ml/memory_containers/_search +``` + +## 请求字段 + +请求体支持标准的 OpenSearch 查询 DSL。有关更多信息,请参阅[查询 DSL](/query-dsl/)。 + +## 示例请求 + +```json +GET /_plugins/_ml/memory_containers/_search +{ + "query": { + "match_all": {} + } +} +``` + +## 示例响应 + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-ml-am-memory-container", + "_id": "HudqiJkB1SltqOcZusVU", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "created_time": 1757956737699, + "last_updated_time": 1757956737699, + "configuration": { + "embedding_model_id": "uXZAtJkBvHNmcp1JAROh", + "strategies": [ + { + "namespace": ["user_id"], + "id": "semantic_53d1751c", + "type": "SEMANTIC", + "enabled": true + } + ], + "max_infer_size": 5, + "embedding_dimension": 1024, + "index_prefix": "default", + "use_system_index": true, + "llm_id": "aFouy5kBrfmzAZ6R6wo-", + "disable_history": false, + "embedding_model_type": "TEXT_EMBEDDING", + "disable_session": false + }, + "name": "agentic memory test", + "description": "Store conversations with semantic search and summarization" + } + }, + ... + ] + } +} +``` + +## 响应字段 + +响应使用标准的 OpenSearch 搜索响应格式。下表列出了 `hits` 数组每个元素的 `_source` 对象中的字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | String | 记忆容器的名称。 | +| `description` | String | 记忆容器的描述。 | +| `configuration` | Object | 记忆容器配置,包括模型和策略。 | +| `created_time` | Long | 容器创建时的时间戳。 | +| `last_updated_time` | Long | 容器最后更新时的时间戳。 | +| `backend_roles` | Array | 有权访问该容器的后端角色。仅在配置了后端角色时才存在。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/search-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/search-memory.md new file mode 100644 index 00000000..3fec385f --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/search-memory.md @@ -0,0 +1,191 @@ +--- +title: 搜索代理记忆 +--- + +# 搜索代理记忆 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 在记忆容器中搜索特定类型的记忆。此统一 API 支持搜索 `sessions`、`working`、`long-term` 和 `history` [记忆类型](/ml-commons-plugin/agentic-memory#memory-types)。 + +## 端点 + +```json +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/_search +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/_search +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | 必需 | 记忆容器的 ID。 | +| `type` | String | 必需 | 记忆类型。有效值为 `sessions`、`working`、`long-term` 和 `history`。 | + +## 请求字段 + +请求体支持标准的 OpenSearch 查询领域特定语言 (DSL)。有关更多信息,请参阅[查询 DSL](/query-dsl/)。 + +## 示例请求:搜索会话 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` + +## 示例请求:搜索长期记忆 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "namespace.user_id": "bob" + } + } + ] + } + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` + +## 示例请求:搜索历史记忆 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/history/_search +{ + "query": { + "match_all": {} + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` + +## 示例请求:使用命名空间过滤搜索工作记忆 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "namespace.user_id": "bob" + } + } + ], + "must_not": [ + { + "exists": { + "field": "tags.parent_memory_id" + } + } + ] + } + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` + +## 示例请求:按会话搜索跟踪数据 + +```json +GET /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/_search +{ + "query": { + "term": { + "namespace.session_id": "123" + } + }, + "sort": [ + { + "created_time": { + "order": "desc" + } + } + ] +} +``` + +## 示例响应 + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": ".plugins-ml-am-default-memory-sessions", + "_id": "CcxjTpkBvwXRq366A1aE", + "_version": 1, + "_seq_no": 10, + "_primary_term": 1, + "_score": null, + "_source": { + "summary": "This is a test session", + "created_time": 1757956735881, + "last_updated_time": 1757956735881, + "namespace": { + "user_id": "bob" + }, + "memory_container_id": "HudqiJkB1SltqOcZusVU" + }, + "sort": [ + 1757956735881 + ] + } + ] + } +} +``` + +## 响应字段 + +响应字段因搜索的记忆类型而异。有关字段描述,请参阅[获取记忆](/ml-commons-plugin/api/agentic-memory-apis/get-memory#response-fields)。 diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory.md new file mode 100644 index 00000000..65e8cdd5 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/semantic-search-memory.md @@ -0,0 +1,170 @@ +--- +title: 语义搜索代理记忆 +--- + +# 语义搜索代理记忆 API +<Badge type="tip" text="3.6 版本引入" /> + +使用此 API 通过自然语言查询搜索长期记忆。OpenSearch 自动从您的查询文本生成嵌入向量,并对存储的记忆嵌入执行向量相似性搜索。这消除了手动构造带有预生成嵌入的 k-NN 查询的需要。 + +::: info NOTE +记忆容器必须配置嵌入模型和至少一个[记忆策略](/ml-commons-plugin/agentic-memory#memory-processing-strategies)。 +::: + +## 端点 + +```json +POST /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_semantic_search +GET /_plugins/_ml/memory_containers/{memory_container_id}/memories/long-term/_semantic_search +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | 必需 | 记忆容器的 ID。 | + +## 请求字段 + +下表列出了可用的请求字段。 + +| 字段 | 数据类型 | 必需/可选 | 默认值 | 描述 | +| :--- | :--- | :--- | :--- | :--- | +| `query` | String | 必需 | 不适用 | 自然语言搜索查询。OpenSearch 使用记忆容器配置的嵌入模型自动生成嵌入。 | +| `k` | Integer | 可选 | 10 | 要返回的结果数量。有效值为 1–10,000。 | +| `namespace` | Object | 可选 | 不适用 | 按命名空间字段过滤结果。例如,`{"user_id": "alice"}`。 | +| `tags` | Object | 可选 | 不适用 | 按标签字段过滤结果。例如,`{"topic": "food"}`。 | +| `min_score` | Float | 可选 | 不适用 | 最小相关性分数阈值。低于此分数的结果将被排除。 | +| `filter` | Object | 可选 | 不适用 | 与语义查询一起应用的附加[查询 DSL](/query-dsl/) 过滤器。 | + +## 示例请求:基本语义搜索 + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_semantic_search +{ + "query": "retirement planning portfolio rebalancing", + "k": 5, + "namespace": { + "user_id": "bob" + } +} +``` + +## 示例请求:最小分数和标签过滤器 + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_semantic_search +{ + "query": "client risk tolerance and investment preferences", + "k": 5, + "namespace": { + "user_id": "bob" + }, + "tags": { + "topic": "finance" + }, + "min_score": 0.6 +} +``` + +## 示例请求:查询 DSL 过滤器 + +```json +POST /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/_semantic_search +{ + "query": "programming languages for data science", + "k": 10, + "namespace": { + "user_id": "alice" + }, + "filter": { + "range": { + "created_time": { + "gte": 1700000000000 + } + } + } +} +``` + +## 示例响应 + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.87, + "hits": [ + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "abc123", + "_score": 0.87, + "_source": { + "created_time": 1700000000000, + "memory": "Client plans to retire in five years with a gradual rebalancing strategy", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "bob" + }, + "strategy_id": "semantic_53d1751c", + "strategy_type": "SEMANTIC", + "memory_container_id": "HudqiJkB1SltqOcZusVU" + } + }, + { + "_index": ".plugins-ml-am-default-memory-long-term", + "_id": "def456", + "_score": 0.82, + "_source": { + "created_time": 1700000000000, + "memory": "Client prefers conservative investments and wants to shift away from equities", + "last_updated_time": 1700000000000, + "namespace_size": 1, + "namespace": { + "user_id": "bob" + }, + "strategy_id": "user_preference_0771b88e", + "strategy_type": "USER_PREFERENCE", + "memory_container_id": "HudqiJkB1SltqOcZusVU" + } + } + ] + } +} +``` + +## 响应字段 + +响应使用标准的 OpenSearch 搜索响应格式。`hits.hits` 数组中的每个命中在 `_source` 中包含以下字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `memory` | String | 提取的记忆文本。 | +| `strategy_type` | String | 产生此记忆的策略(`SEMANTIC`、`USER_PREFERENCE` 或 `SUMMARY`)。 | +| `namespace` | Object | 与此记忆关联的命名空间字段。 | +| `namespace_size` | Integer | 命名空间字段的数量。 | +| `strategy_id` | String | 产生此记忆的策略的 ID。 | +| `tags` | Object | 与此记忆关联的标签。仅在记忆具有标签时才存在。 | +| `memory_container_id` | String | 记忆容器的 ID。 | +| `created_time` | Long | 记忆创建时的时间戳。 | +| `last_updated_time` | Long | 记忆最后更新时的时间戳。 | + +`memory_embedding` 字段从响应中排除。 + +## 相关文档 + +- [语义搜索](/vector-search/ai-search/semantic-search/) diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/update-memory-container.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/update-memory-container.md new file mode 100644 index 00000000..f5a557e0 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/update-memory-container.md @@ -0,0 +1,123 @@ +--- +title: 更新记忆容器 +--- + +# 更新记忆容器 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 更新现有记忆容器的属性,例如名称、描述、配置和访问权限。 + +## 端点 + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id} +``` + +## 路径参数 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | 必需 | 要更新的记忆容器的 ID。 | + +## 请求字段 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `name` | String | 可选 | 记忆容器的更新名称。 | +| `description` | String | 可选 | 记忆容器的更新描述。 | +| `backend_roles` | Array | 可选 | 用于访问控制的后端角色列表。覆盖现有列表。 | +| `configuration` | Object | 可选 | 包含策略和嵌入设置的配置对象。请参阅[配置对象](#the-configuration-object)。 | + +### 配置对象 + +`configuration` 对象支持以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `llm_id` | String | 可选 | 用于提取事实的大型语言模型 (LLM) ID。 | +| `max_infer_size` | Integer | 可选 | 在记忆整合期间检索到的相似现有记忆的最大数量。最大值为 `10`。要更新此值,请在同一请求中包含 `llm_id`。 | +| `strategies` | Array | 可选 | 用于记忆处理的策略对象数组。每个策略支持 `id`、`type`、`namespace`、`enabled` 和 `configuration` 字段。有关字段描述,请参阅[策略数组](/ml-commons-plugin/api/agentic-memory-apis/create-memory-container#the-strategies-array)。 | +| `embedding_model_id` | String | 可选 | 嵌入模型 ID。仅在不存在长期记忆索引时才能更新。 | +| `embedding_model_type` | String | 可选 | 嵌入模型类型。仅在不存在长期记忆索引时才能更新。 | +| `embedding_dimension` | Integer | 可选 | 嵌入维度。仅在不存在长期记忆索引时才能更新。 | +| `retention_policy` | Object | 可选 | 每种记忆类型的保留限制。更改将合并到现有策略中。设置为 `null` 以删除策略。有关更多信息,请参阅[代理记忆保留](/ml-commons-plugin/agentic-memory-retention)。 | + +## 更新行为 + +请注意以下更新行为。 + +### 策略更新 + +- 要更新特定策略,请指定策略 `id`。仅更新您提供的字段。您无法更改现有策略的 `type`。 +- 要创建新策略,请指定不带 `id` 的策略。 +- 要禁用策略而不删除它,请将其 `enabled` 字段设置为 `false`。 + +### 后端角色更新 + +- 添加新的 `backend_roles` 会向具有这些角色的新用户授予读取或写入访问权限。 +- 新的 `backend_roles` 字段会覆盖现有字段,因此如果要保留原始角色,请包含它们。 + +### 命名空间更新 + +- `strategies` 对象中的 `namespace` 字段通过覆盖方式更新。如果要保留原始命名空间,请包含它。 + +### 嵌入模型限制 + +- 只有在尚未为此记忆容器创建长期记忆索引时,才能更新 `embedding_model_id`、`embedding_model_type` 和 `embedding_dimension` 字段。一旦使用指定的 `index_prefix` 创建了长期记忆索引,就无法更新这些嵌入字段。 + +## 示例请求 + +以下请求更新现有策略的命名空间并添加 `USER_PREFERENCE` 策略。要查找现有策略的 ID,请使用[获取记忆容器 API](/ml-commons-plugin/api/agentic-memory-apis/get-memory-container): + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU +{ + "name": "opensearch-agents-memory", + "description": "Updated memory container for OpenSearch agents", + "backend_roles": ["admin", "ml_user"], + "configuration": { + "strategies": [ + { + "id": "semantic_53d1751c", + "namespace": ["user_id", "session_id"] + }, + { + "type": "USER_PREFERENCE", + "namespace": ["user_id"] + } + ] + } +} +``` + +## 示例响应 + +```json +{ + "_index": ".plugins-ml-am-memory-container", + "_id": "HudqiJkB1SltqOcZusVU", + "_version": 2, + "result": "updated", + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 5, + "_primary_term": 1 +} +``` + +## 响应字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_index` | String | 存储记忆容器的索引名称。 | +| `result` | String | 更新操作的结果。 | +| `_id` | String | 更新的记忆容器的 ID。 | +| `_version` | Integer | 更新的记忆容器的版本号。 | +| `_shards` | Object | 有关操作所涉及的分片的信息。 | +| `_seq_no` | Long | 分配给更新操作的序列号。 | +| `_primary_term` | Long | 索引的主分片任期。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/update-memory.md b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/update-memory.md new file mode 100644 index 00000000..969d7ead --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-memory-apis/update-memory.md @@ -0,0 +1,136 @@ +--- +title: 更新代理记忆 +--- + +# 更新代理记忆 API +<Badge type="tip" text="3.3 版本引入" /> + +使用此 API 按类型和 ID 更新特定记忆。此统一 API 支持更新 `sessions`、`working` 和 `long-term` [记忆类型](/ml-commons-plugin/agentic-memory#memory-types)。`history` 记忆不支持更新。 + +## 端点 + +```json +PUT /_plugins/_ml/memory_containers/{memory_container_id}/memories/{type}/{id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `memory_container_id` | String | 必需 | 记忆容器的 ID。 | +| `type` | String | 必需 | 记忆类型。有效值为 `sessions`、`working` 和 `long-term`。请注意,`history` 记忆无法更新。 | +| `id` | String | 必需 | 要更新的记忆的 ID。 | + +## 请求字段 + +请求字段因要更新的记忆类型而异。所有请求字段都是可选的,但请求体必须至少包含一个字段。您提供的每个字段都会替换该字段的现有值。例如,提供 `tags` 会替换所有现有标签。 + +### 会话记忆请求字段 + +下表列出了所有会话记忆请求体字段。 + +| 字段 | 数据类型 | 描述 | +|:-----------|:----------------------| :--- | +| `summary` | String | 会话的摘要。 +| `metadata` | Object | 记忆的附加元数据(例如,`status`、`branch` 或自定义字段)。 | +| `agents` | Object | 有关代理的附加信息。 | +| `additional_info` | Object | 要与会话关联的附加元数据。 | +| `pinned` | Boolean | 是否固定会话,使其免受容器保留策略的影响。需要将 `plugins.ml_commons.memory.retention_enabled` 设置为 `true`。有关更多信息,请参阅[代理记忆保留](/ml-commons-plugin/agentic-memory-retention)。 | + +### 工作记忆请求字段 + +下表列出了所有工作记忆请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `messages` | Array | 更新的对话消息(用于对话类型)。可选。 | +| `structured_data` | Object | 更新的结构化数据内容(用于 `data` 记忆负载)。 | +| `structured_data_blob` | Object | 存储但不索引的更新结构化数据。 | +| `binary_data` | String | 更新的 Base64 编码的二进制数据内容(用于 `data` 记忆负载)。可选。 | +| `tags` | Object | 用于分类的更新标签。 | +| `metadata` | Object | 记忆的附加元数据(例如,`status`、`branch` 或自定义字段)。 + +### 长期记忆请求字段 + +下表列出了所有长期记忆请求体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `memory` | String | 更新的记忆内容。可选。 | +| `tags` | Object | 用于分类的更新标签。可选。 | +| `pinned` | Boolean | 是否固定记忆,使其免受容器保留策略的影响。需要将 `plugins.ml_commons.memory.retention_enabled` 设置为 `true`。可选。 | + +当您更新 `memory` 字段时,OpenSearch 会重新生成记忆嵌入。 + +## 示例请求:更新会话 + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/sessions/N2CDipkB2Mtr6INFFcX8 +{ + "additional_info": { + "key1": "value1", + "last_activity": "2025-09-15T17:30:00Z" + } +} +``` + +## 示例请求:更新工作记忆 + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/working/XyEuiJkBeh2gPPwzjYWM +{ + "tags": { + "topic": "updated_topic", + "priority": "high" + } +} +``` + +## 示例请求:更新长期记忆 + +```json +PUT /_plugins/_ml/memory_containers/HudqiJkB1SltqOcZusVU/memories/long-term/DcxjTpkBvwXRq366C1Zz +{ + "memory": "User's name is Bob Smith", + "tags": { + "topic": "personal info", + "updated": "true" + } +} +``` + +## 示例响应 + +```json +{ + "_index": ".plugins-ml-am-default-memory-sessions", + "_id": "N2CDipkB2Mtr6INFFcX8", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 11, + "_primary_term": 1 +} +``` + +## 响应字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `_index` | String | 存储记忆的索引名称。 | +| `result` | String | 更新操作的结果。 | +| `_id` | String | 更新的记忆的 ID。 | +| `_version` | Integer | 更新的记忆的版本号。 | +| `forced_refresh` | Boolean | 操作后是否强制刷新。 | +| `_shards` | Object | 有关操作所涉及的分片的信息。 | +| `_seq_no` | Long | 分配给更新操作的序列号。 | +| `_primary_term` | Long | 索引的主分片任期。 | diff --git a/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template.md b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template.md new file mode 100644 index 00000000..f5cb3c2e --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template.md @@ -0,0 +1,47 @@ +--- +title: 删除代理搜索模板 +--- + +# 删除代理搜索模板 API +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +使用此 API 删除已注册的代理搜索模板。删除代理搜索模板不会删除存储的脚本。 + +## 端点 + +```json +DELETE /_plugins/_ml/agentic_search_templates/{template_id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`template_id` | String | 必需 | 要删除的代理搜索模板的 ID。 + +## 示例请求 + +```json +DELETE /_plugins/_ml/agentic_search_templates/similar_search +``` + +## 示例响应 + +```json +{ + "template_id": "similar_search", + "status": "deleted" +} +``` + +如果模板未注册,API 将返回 `404` 错误。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/agentic_search_templates/delete`。 diff --git a/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template.md b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template.md new file mode 100644 index 00000000..f37ef095 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template.md @@ -0,0 +1,73 @@ +--- +title: 获取代理搜索模板 +--- + +# 获取代理搜索模板 API +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +使用此 API 检索已注册的代理搜索模板,包括其参数架构。 + +## 端点 + +```json +GET /_plugins/_ml/agentic_search_templates/{template_id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`template_id` | String | 必需 | 要检索的代理搜索模板的 ID。 + +## 示例请求 + +```json +GET /_plugins/_ml/agentic_search_templates/similar_search +``` + +## 示例响应 + +以下响应是在[注册代理搜索模板 API](/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template#example-request-provide-the-parameter-schema) 示例中使用提供的参数架构注册的模板的响应: + +```json +{ + "template_id": "similar_search", + "index_binding": "products", + "description": "Fuzzy search for products similar to a name", + "param_schema": { + "query_text": { + "type": "string", + "required": true, + "description": "The product name to match. May contain misspellings." + } + }, + "created_time": 1792716795385, + "last_updated_time": 1792716795385 +} +``` + +如果模板未注册,API 将返回 `404` 错误。 + +## 响应体字段 + +下表列出了所有响应体字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`template_id` | String | 代理搜索模板 ID,也是存储脚本 ID。 +`index_binding` | String | 模板搜索的索引。 +`description` | String | 模板描述(如果提供或派生)。 +`param_schema` | Object | 参数架构。请参阅[`param_schema` 对象](/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template#the-param_schema-object)。 +`created_time` | Long | 模板注册的时间(以纪元毫秒为单位)。 +`last_updated_time` | Long | 模板最后更新的时间(以纪元毫秒为单位)。 +`created_by` | String | 注册模板的用户。仅在启用安全插件时才存在。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/agentic_search_templates/get`。 diff --git a/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/index.md b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/index.md new file mode 100644 index 00000000..d89f1e63 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/index.md @@ -0,0 +1,39 @@ +--- +title: 代理搜索模板 API +--- + +# 代理搜索模板 API +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +代理搜索模板 API 注册存储的搜索模板,以便代理搜索可以让大型语言模型 (LLM) 填充其参数,而不是编写完整的查询。有关概述和完整示例,请参阅[填充搜索模板](/vector-search/ai-search/agentic-search/agentic-search-templates/index/)。 + +OpenSearch 支持以下代理搜索模板 API: + +- [注册代理搜索模板](/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template) +- [获取代理搜索模板](/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template) +- [列出代理搜索模板](/ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates) +- [更新代理搜索模板](/ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template) +- [删除代理搜索模板](/ml-commons-plugin/api/agentic-search-template-apis/delete-agentic-search-template) + +::: info NOTE +启用多租户时不支持代理搜索模板。 +::: + +## 启用代理搜索模板 API + +要启用代理搜索模板 API 和 `SearchTemplateFillTool`,请更新以下集群设置: + +```json +PUT _cluster/settings +{ + "persistent": { + "plugins.ml_commons.agentic_search_template_enabled": true + } +} +``` + +有关启用实验性功能的更多信息,请参阅[实验性功能标志](/install-and-configure/configuring-opensearch/experimental)。 diff --git a/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates.md b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates.md new file mode 100644 index 00000000..2486297c --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/list-agentic-search-templates.md @@ -0,0 +1,72 @@ +--- +title: 列出代理搜索模板 +--- + +# 列出代理搜索模板 API +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +使用此 API 列出已注册的代理搜索模板。 + +## 端点 + +```json +GET /_plugins/_ml/agentic_search_templates +``` + +## 查询参数 + +下表列出了可用的查询参数。 + +参数 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`from` | Integer | 可选 | 分页的起始索引。必须为非负数。默认值为 `0`。 +`size` | Integer | 可选 | 要返回的最大模板数量。有效值为 1–1000。默认值为 `10`。 + +## 示例请求 + +```json +GET /_plugins/_ml/agentic_search_templates?from=0&size=10 +``` + +## 示例响应 + +以下响应列出了一个已注册的模板: + +```json +{ + "total": 1, + "templates": [ + { + "template_id": "similar_search", + "index_binding": "products", + "description": "Fuzzy search for products similar to a name", + "param_schema": { + "query_text": { + "type": "string", + "required": true, + "description": "The product name to match. May contain misspellings." + } + }, + "created_time": 1792716795385, + "last_updated_time": 1792716795385 + } + ] +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`total` | Long | 已注册模板的总数。 +`templates` | Array | 请求页面上的模板。每个模板包含[获取代理搜索模板 API](/ml-commons-plugin/api/agentic-search-template-apis/get-agentic-search-template#response-body-fields) 中描述的字段。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/agentic_search_templates/list`。 diff --git a/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template.md b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template.md new file mode 100644 index 00000000..a44cb584 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template.md @@ -0,0 +1,92 @@ +--- +title: 注册代理搜索模板 +--- + +# 注册代理搜索模板 API +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +使用此 API 为代理搜索注册存储的搜索模板。在注册之前,请使用[创建或更新存储脚本 API](/api-reference/script-apis/create-stored-script) 存储模板。 + +在注册期间,OpenSearch 读取存储的模板和索引映射,派生参数架构(除非您提供一个),并验证模板在填充所有参数和仅填充必需参数时都能呈现有效的 JSON。OpenSearch 会拒绝未通过此验证的模板。 + +## 端点 + +```json +POST /_plugins/_ml/agentic_search_templates +``` + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`template_id` | String | 必需 | 使用 `PUT _scripts/<template_id>` 存储的搜索模板的 ID。也用作代理搜索模板 ID。 +`index` | String | 必需 | 模板搜索的索引。[`SearchTemplateFillTool`](/ml-commons-plugin/agents-tools/tools/search-template-fill-tool) 仅在此索引或解析为其中索引的别名或索引模式上使用该模板进行搜索。有关 OpenSearch 代理服务器如何使用此索引的信息,请参阅[在代理服务器中填充模板](/vector-search/ai-search/agentic-search/agentic-search-templates/agent-server/#step-1-create-a-connector-to-the-agent-server)。 +`description` | String | 可选 | 模板搜索内容的描述。用于在多个模板中进行选择。如果您同时省略 `description` 和 `param_schema`,OpenSearch 会尝试从模板派生描述。 +`param_schema` | Object | 可选 | 参数架构。如果省略,OpenSearch 将从模板和索引映射派生它。如果提供,它将按发送的方式存储,并且每个参数都必须出现在模板中。请参阅[`param_schema` 对象](#the-param_schema-object)。 + +### param_schema 对象 + +`param_schema` 对象将每个模板参数映射到具有以下字段的对象。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`type` | String | 必需 | 参数类型。派生的架构使用 `string`、`number`、`boolean` 或 `array`。`array` 参数作为原始 JSON 字符串传递,必须使用三个大括号(`{{{param}}}`)呈现。 +`required` | Boolean | 可选 | LLM 是否必须提供参数。默认值为 `false`。 +`enum` | Array | 可选 | 允许的值。每个值必须匹配 `type`:`number` 的数字、`boolean` 的布尔值,否则为字符串。对于名为 `field` 或 `sort_by` 的参数,或名称以 `_field` 结尾的参数,派生的架构从索引映射的字段名称中获取允许的值。当参数设置排序字段时,仅列出可排序字段;例如,省略 `text` 字段,但包括其 `keyword` 子字段。 +`description` | String | 可选 | 向 LLM 描述参数。 +`source` | String | 可选 | 当 `enum` 包含来自索引映射的字段名称时,在派生的架构中设置为 `mapping`。 + +## 示例请求:派生参数架构 + +```json +POST /_plugins/_ml/agentic_search_templates +{ + "template_id": "product_search", + "index": "products", + "description": "Product search by title with an optional category filter and an optional descending sort" +} +``` + +## 示例请求:提供参数架构 + +```json +POST /_plugins/_ml/agentic_search_templates +{ + "template_id": "similar_search", + "index": "products", + "description": "Fuzzy search for products similar to a name", + "param_schema": { + "query_text": { + "type": "string", + "required": true, + "description": "The product name to match. May contain misspellings." + } + } +} +``` + +## 示例响应 + +```json +{ + "template_id": "similar_search", + "status": "created" +} +``` + +如果已注册具有相同 ID 的代理搜索模板,API 将返回 `409` 错误。如果不存在具有指定 ID 的存储脚本,API 将返回 `400` 错误。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/agentic_search_templates/register`。由于 OpenSearch 以调用用户的身份读取存储的脚本和索引,因此您还需要对指定索引具有 `cluster:admin/script/get` 和 `indices:admin/get` 权限。 + +## 相关文档 + +- [填充搜索模板](/vector-search/ai-search/agentic-search/agentic-search-templates/index/) +- [搜索模板](/api-reference/search-apis/search-template/) diff --git a/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template.md b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template.md new file mode 100644 index 00000000..37d86a32 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/agentic-search-template-apis/update-agentic-search-template.md @@ -0,0 +1,77 @@ +--- +title: 更新代理搜索模板 +--- + +# 更新代理搜索模板 API +<Badge type="tip" text="3.10 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/opensearch-agent-server/issues/150)。 +::: + +使用此 API 更新已注册的代理搜索模板的描述或参数架构。要更改查询本身,请更新存储的脚本。要更改模板搜索的索引,请删除模板并重新注册。 + +OpenSearch 代理服务器会将每个模板的参数架构缓存 60 秒,因此更新可能需要长达 60 秒才能到达代理服务器。 + +## 端点 + +```json +PUT /_plugins/_ml/agentic_search_templates/{template_id} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`template_id` | String | 必需 | 要更新的代理搜索模板的 ID。 + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`description` | String | 可选 | 模板搜索内容的描述。 +`param_schema` | Object | 可选 | 对参数架构的更改。对于您指定的每个参数,您提供的字段将替换存储的字段,而其他字段保持不变。您不能添加不在存储架构中的参数。OpenSearch 在保存之前会根据模板验证合并的架构。请参阅[`param_schema` 对象](/ml-commons-plugin/api/agentic-search-template-apis/register-agentic-search-template#the-param_schema-object)。 + +## 示例请求 + +以下请求将为 `product_search` 模板派生的 `sort_by` 参数限制为 `price` 字段,并保持参数的其他字段不变: + +```json +PUT /_plugins/_ml/agentic_search_templates/product_search +{ + "param_schema": { + "sort_by": { + "enum": ["price"] + } + } +} +``` + +## 示例响应 + +```json +{ + "_index": ".plugins-ml-agentic-search-templates", + "_id": "product_search", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 1, + "_primary_term": 1 +} +``` + +如果模板未注册,API 将返回 `404` 错误。如果合并的架构无效或模板无法使用它呈现有效的 JSON,API 将返回 `400` 错误。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/agentic_search_templates/update`。 diff --git a/i18n/zh/ml-commons-plugin/api/context-management-apis/create-context-management.md b/i18n/zh/ml-commons-plugin/api/context-management-apis/create-context-management.md new file mode 100644 index 00000000..77259b2f --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/context-management-apis/create-context-management.md @@ -0,0 +1,125 @@ +--- +title: 创建上下文管理 +--- + +# 创建上下文管理 API +<Badge type="tip" text="3.5 版本引入" /> + +使用此 API 来配置[上下文管理](/ml-commons-plugin/context-management),该功能定义上下文管理器团队以在特定执行点优化代理上下文。 + +## 端点 + +```json +POST /_plugins/_ml/context_management/{context_management_name} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`context_management_name` | String | 必需 | 上下文管理的唯一名称。长度必须为 1--49 个字符,只能包含小写字母、数字、连字符(`-`)和下划线(`_`)。 + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`description` | String | 可选 | 此上下文管理功能的人类可读描述。 +`hooks` | Object | 必需 | 钩子名称到上下文管理器配置列表的映射。必须至少包含一个钩子。请参阅 [`hooks` 对象](#the-hooks-object)。 + +### hooks 对象 + +`hooks` 对象将钩子名称映射到上下文管理器配置数组。钩子名称区分大小写且必须为大写。API 接受其他钩子名称,但在它们下配置的上下文管理器永远不会运行。支持以下钩子。 + +钩子 | 说明 +:--- | :--- +`PRE_LLM` | 在向大型语言模型(LLM)发送请求之前执行。 +`POST_TOOL` | 在工具执行完成后执行。 + +每个钩子包含一个上下文管理器配置数组,具有以下字段。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`type` | String | 必需 | 上下文管理器类型。有效值为 `SlidingWindowManager`、`SummarizationManager` 和 `ToolsOutputTruncateManager`。 +`config` | Object | 可选 | 特定于上下文管理器类型的配置。如果省略,则使用默认值。请参阅[上下文管理器配置](#context-manager-configurations)。 + +### 上下文管理器配置 + +根据上下文管理器类型,支持以下上下文管理器配置。 + +#### SlidingWindowManager + +`SlidingWindowManager` 在 `config` 对象中支持以下参数。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`max_messages` | Integer | 可选 | 要保留的最大消息数。默认值为 `20`。 +`activation` | Object | 可选 | 激活规则。默认为始终激活。请参阅[激活规则](#activation-rules)。 + +#### SummarizationManager + +`SummarizationManager` 在 `config` 对象中支持以下参数。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`summary_ratio` | Double | 可选 | 要总结的消息比率(0.1--0.8)。默认值为 `0.3`。 +`preserve_recent_messages` | Integer | 可选 | 要保留的最近消息数。默认值为 `10`。 +`summarization_model_id` | String | 可选 | 用于总结的模型 ID。如果未指定,则使用代理的模型。 +`summarization_system_prompt` | String | 可选 | 用于总结的系统提示。如果未指定,则使用默认系统提示。 +`activation` | Object | 可选 | 激活规则。默认为始终激活。请参阅[激活规则](#activation-rules)。 + +#### ToolsOutputTruncateManager + +`ToolsOutputTruncateManager` 在 `config` 对象中支持以下参数。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`max_output_length` | Integer | 可选 | 要保留的工具输出的最大长度。默认值为 `40000`。 +`activation` | Object | 可选 | 激活规则。默认为始终激活。请参阅[激活规则](#activation-rules)。 + +### 激活规则 + +激活规则确定何时应执行上下文管理器。如果省略,管理器将始终执行。多个规则使用 `AND` 逻辑---必须满足所有规则才能激活。有关更多信息和示例,请参阅[激活规则](/ml-commons-plugin/context-management#activation-rules)。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`message_count_exceed` | Integer | 可选 | 当消息计数超过此阈值时激活。 +`tokens_exceed` | Integer | 可选 | 当令牌计数超过此阈值时激活。 + +## 示例请求:基本滑动窗口上下文管理 + +```json +POST /_plugins/_ml/context_management/basic-sliding-window +{ + "description": "Basic sliding window context management", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "message_count_exceed": 12 + } + } + } + ] + } +} +``` + +## 示例响应 + +```json +{ + "context_management_name": "basic-sliding-window", + "status": "created" +} +``` + +## 相关文档 + +有关更多信息,请参阅[上下文管理](/ml-commons-plugin/context-management)。 diff --git a/i18n/zh/ml-commons-plugin/api/context-management-apis/delete-context-management.md b/i18n/zh/ml-commons-plugin/api/context-management-apis/delete-context-management.md new file mode 100644 index 00000000..e87fc548 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/context-management-apis/delete-context-management.md @@ -0,0 +1,65 @@ +--- +title: 删除上下文管理 +--- + +# 删除上下文管理 API +<Badge type="tip" text="3.5 版本引入" /> + +使用此 API 删除上下文管理配置。删除后,代理将无法再使用该上下文管理。 + +::: info NOTE +代理存储上下文管理配置的名称,而不是其副本。删除配置后,使用其名称执行已注册的代理将失败并返回 404 错误,使用其名称注册新代理将失败并返回 400 错误。要运行此类代理,请使用相同名称重新创建配置,或在执行代理时在 `context_management_name` 参数中指定不同的配置。 +::: + +## 端点 + +```json +DELETE /_plugins/_ml/context_management/{context_management_name} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`context_management_name` | String | 必需 | 要删除的上下文管理的名称。 + +## 示例请求 + +```json +DELETE /_plugins/_ml/context_management/advanced-context-management +``` + +## 示例响应 + +```json +{ + "context_management_name": "advanced-context-management", + "status": "deleted" +} +``` + +## 错误响应 + +如果您尝试删除不存在的上下文管理配置,API 将返回 404 错误,指示未找到资源: + +```json +{ + "error": { + "root_cause": [ + { + "type": "status_exception", + "reason": "Context management template not found: sliding_window_max_40000_tokens_managers123" + } + ], + "type": "status_exception", + "reason": "Context management template not found: sliding_window_max_40000_tokens_managers123" + }, + "status": 404 +} +``` + +## 相关文档 + +有关更多信息,请参阅[上下文管理](/ml-commons-plugin/context-management)。 diff --git a/i18n/zh/ml-commons-plugin/api/context-management-apis/get-context-management.md b/i18n/zh/ml-commons-plugin/api/context-management-apis/get-context-management.md new file mode 100644 index 00000000..7c251240 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/context-management-apis/get-context-management.md @@ -0,0 +1,78 @@ +--- +title: 获取上下文管理 +--- + +# 获取上下文管理 API +<Badge type="tip" text="3.5 版本引入" /> + +使用此 API 通过名称检索上下文管理配置。 + +## 端点 + +```json +GET /_plugins/_ml/context_management/{context_management_name} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`context_management_name` | String | 必需 | 要检索的上下文管理的名称。 + +## 示例请求 + +```json +GET /_plugins/_ml/context_management/token-aware-truncation +``` + +## 示例响应 + +```json +{ + "name": "token-aware-truncation", + "description": "Context management that truncates tool outputs longer than 100,000 characters and applies sliding window to keep last 6 messages when tokens exceed 200,000", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "tokens_exceed": 200000 + } + } + } + ], + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 100000 + } + } + ] + }, + "created_time": 1754943902286, + "last_modified": 1754943902286, + "created_by": "admin" +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +字段 | 数据类型 | 说明 +:--- | :--- | :--- +`name` | String | 上下文管理的名称。 +`description` | String | 上下文管理的描述。 +`hooks` | Object | 钩子名称到上下文管理器配置列表的映射。有关更多信息,请参阅 [`hooks` 对象](/ml-commons-plugin/api/context-management-apis/create-context-management#the-hooks-object)。 +`created_time` | Long | 创建上下文管理的时间,以毫秒为单位的纪元时间。 +`last_modified` | Long | 上次更新上下文管理的时间,以毫秒为单位的纪元时间。 +`created_by` | String | 创建上下文管理的用户。仅在启用安全插件时显示。 + +## 相关文档 + +有关更多信息,请参阅[上下文管理](/ml-commons-plugin/context-management)。 diff --git a/i18n/zh/ml-commons-plugin/api/context-management-apis/index.md b/i18n/zh/ml-commons-plugin/api/context-management-apis/index.md new file mode 100644 index 00000000..349658bb --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/context-management-apis/index.md @@ -0,0 +1,16 @@ +--- +title: 上下文管理 API +--- + +# 上下文管理 API +<Badge type="tip" text="3.5 版本引入" /> + +上下文管理 API 为 AI 代理提供动态上下文优化。有关概念、用例和入门信息的概述,请参阅[上下文管理](/ml-commons-plugin/context-management)。 + +OpenSearch 支持以下上下文管理 API: + +- [创建上下文管理](/ml-commons-plugin/api/context-management-apis/create-context-management) +- [获取上下文管理](/ml-commons-plugin/api/context-management-apis/get-context-management) +- [更新上下文管理](/ml-commons-plugin/api/context-management-apis/update-context-management) +- [删除上下文管理](/ml-commons-plugin/api/context-management-apis/delete-context-management) +- [列出上下文管理](/ml-commons-plugin/api/context-management-apis/list-context-management) diff --git a/i18n/zh/ml-commons-plugin/api/context-management-apis/list-context-management.md b/i18n/zh/ml-commons-plugin/api/context-management-apis/list-context-management.md new file mode 100644 index 00000000..0fd7afbe --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/context-management-apis/list-context-management.md @@ -0,0 +1,82 @@ +--- +title: 列出上下文管理 +--- + +# 列出上下文管理 API +<Badge type="tip" text="3.5 版本引入" /> + +使用此 API 检索集群中所有上下文管理配置的列表。 + +## 端点 + +```json +GET /_plugins/_ml/context_management +``` + +## 查询参数 + +下表列出了可用的查询参数。 + +参数 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`size` | Integer | 可选 | 要返回的最大结果数。有效值为 1--1000。默认值为 `10`。 +`from` | Integer | 可选 | 分页的起始索引。默认值为 `0`。 + +## 示例请求 + +```json +GET /_plugins/_ml/context_management +``` + +## 带分页的示例请求 + +```json +GET /_plugins/_ml/context_management?size=20&from=0 +``` + +## 示例响应 + +```json +{ + "total": 1, + "templates": [ + { + "name": "sliding_window_max_40000_tokens_managers", + "description": "Context management for truncating tool outputs to prevent input length issues", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 8 + } + } + ], + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 40000 + } + } + ] + }, + "created_time": 1769457277774, + "last_modified": 1769457277774 + } + ] +} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +字段 | 数据类型 | 说明 +:--- | :--- | :--- +`total` | Integer | 此响应中返回的上下文管理配置的数量。 +`templates` | Array | 上下文管理配置的列表。有关字段描述,请参阅[获取上下文管理 API](/ml-commons-plugin/api/context-management-apis/get-context-management#response-body-fields)。 + +## 相关文档 + +有关更多信息,请参阅[上下文管理](/ml-commons-plugin/context-management)。 diff --git a/i18n/zh/ml-commons-plugin/api/context-management-apis/update-context-management.md b/i18n/zh/ml-commons-plugin/api/context-management-apis/update-context-management.md new file mode 100644 index 00000000..a9301a33 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/context-management-apis/update-context-management.md @@ -0,0 +1,92 @@ +--- +title: 更新上下文管理 +--- + +# 更新上下文管理 API +<Badge type="tip" text="3.5 版本引入" /> + +使用此 API 更新现有的上下文管理配置。您可以修改描述、钩子配置和上下文管理器设置。 + +## 端点 + +```json +PUT /_plugins/_ml/context_management/{context_management_name} +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`context_management_name` | String | 必需 | 要更新的上下文管理的名称。 + +## 请求体字段 + +下表列出了可用的请求体字段。 + +字段 | 数据类型 | 必需/可选 | 说明 +:--- | :--- | :--- | :--- +`description` | String | 可选 | 此上下文管理功能的人类可读描述。 +`hooks` | Object | 可选 | 钩子名称到上下文管理器配置列表的映射。请参阅 [`hooks` 对象](/ml-commons-plugin/api/context-management-apis/create-context-management#the-hooks-object)。 + +请求体遵循与[创建上下文管理 API](/ml-commons-plugin/api/context-management-apis/create-context-management) 相同的结构。您省略的字段保持其现有值。在 `hooks` 对象中,您指定的每个钩子都会替换该钩子的现有配置,而您省略的钩子保持不变。 + +## 示例请求:更新描述 + +```json +PUT /_plugins/_ml/context_management/advanced-context-management +{ + "description": "Updated description for advanced context management with multiple strategies" +} +``` + +## 示例请求:更新钩子配置 + +```json +PUT /_plugins/_ml/context_management/sliding_window_max_40000_tokens_managers +{ + "description": "Context management for truncating tool outputs to prevent input length issues", + "hooks": { + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 8 + } + } + ], + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 40000 + } + } + ] + } +} +``` + +## 示例响应 + +```json +{ + "_index": ".plugins-ml-context-management-templates", + "_id": "sliding_window_max_40000_tokens_managers", + "_version": 2, + "result": "updated", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 4, + "_primary_term": 1 +} +``` + +## 相关文档 + +有关更多信息,请参阅[上下文管理](/ml-commons-plugin/context-management)。 diff --git a/i18n/zh/ml-commons-plugin/api/execute-tool.md b/i18n/zh/ml-commons-plugin/api/execute-tool.md new file mode 100644 index 00000000..aa6051b5 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/execute-tool.md @@ -0,0 +1,121 @@ +--- +title: 执行工具 +--- + +# 执行工具 API +<Badge type="tip" text="3.3 版本引入" /> + +执行工具 API 允许您直接运行单个工具,无需先创建代理。此 API 对于需要快速、单工具操作的应用程序特别有益,这些操作不需要创建和管理代理的开销。 + +## 用例 + +执行工具 API 适用于以下场景: + +- **直接工具执行**:无需代理设置即可运行特定工具,如搜索、数据分析或检索操作。 +- **测试和调试**:在开发过程中快速测试工具功能。 +- **轻量级集成**:将特定的 OpenSearch 功能集成到应用程序中,而无需完整的代理工作流。 +- **独立操作**:执行不需要对话记忆或复杂编排的单一任务。 + +## 支持的工具 + +此 API 支持所有可用的 OpenSearch 工具。每个工具都可以使用其特定参数独立执行。 + +有关可用工具列表的更多信息,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 + +## 端点 + +```json +POST /_plugins/_ml/tools/_execute/{tool_name} +``` + +::: info NOTE +`<tool_name>` 参数指的是预定义的工具类型名称,如 `PPLTool`、`SearchIndexTool` 或 `VectorDBTool`,而不是您定义的自定义工具名称。 +::: + +执行工具 API 默认启用。要禁用它,请将 `plugins.ml_commons.execute_tools_enabled` 设置为 `false`。 + +## 请求体字段 + +下表列出了所有请求体字段。 + +| 字段 | 数据类型 | 必需 | 说明 | +| :--- | :--- | :--- | :--- | +| `parameters` | Object | 是 | 包含特定于工具的参数,这些参数因正在执行的工具而异。每个工具根据其功能需要不同的参数。 | + +### 参数结构 + +`parameters` 对象结合了工具注册期间使用的参数和工具执行期间使用的参数。具体字段取决于正在执行的工具。 + +要确定特定工具所需的参数,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)部分中的各个工具文档。 + +| 组件 | 说明 | +|:-------------------------|:-----------------------------------------------| +| 工具注册参数 | 在工具注册期间指定的参数。 | +| 工具执行参数 | 在工具执行期间指定的参数。 | + +## 示例请求 + +以下是简单和复杂工具执行的示例。 + +### 示例 1:简单工具执行 + +```json +POST /_plugins/_ml/tools/_execute/ListIndexTool +{ + "parameters": { + "question": "How many indices do I have?" + } +} +``` + +### 示例响应 + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": """row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,yellow,open,movies,kKcJKu2aT0C9uwJIPP4hxw,2,1,2,0,7.8kb,7.8kb +2,green,open,.plugins-ml-config,h8ovp_KFTq6_zvcBEn2kvg,1,0,1,0,4kb,4kb +3,green,open,.plugins-ml-agent,1oGlUBCIRAGXLbLv27Qg8w,1,0,1,0,8kb,8kb +""" + } + ] + } + ] +} +``` + +### 示例 2:复杂工具执行 + +```json +POST /_plugins/_ml/tools/_execute/PPLTool +{ + "parameters": { + "question": "what's the population of Seattle in 2021?", + "index": "test-population", + "model_id": "1TuQQ5gBMJhRgCqgSV79" + } +} + +``` + +### 示例响应 + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "{\"ppl\":\"source=test-population | where QUERY_STRING(['population_description'], 'Seattle') AND QUERY_STRING(['population_description'], '2021')\",\"executionResult\":\"{\\n \\\"schema\\\": [\\n {\\n \\\"name\\\": \\\"population_description\\\",\\n \\\"type\\\": \\\"string\\\"\\n }\\n ],\\n \\\"datarows\\\": [],\\n \\\"total\\\": 0,\\n \\\"size\\\": 0\\n}\"}" + } + ] + } + ] +} +``` diff --git a/i18n/zh/ml-commons-plugin/api/mcp-client-apis/index.md b/i18n/zh/ml-commons-plugin/api/mcp-client-apis/index.md new file mode 100644 index 00000000..9a0fef10 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-client-apis/index.md @@ -0,0 +1,14 @@ +--- +title: MCP 客户端 API +--- + +# MCP 客户端 API +<Badge type="tip" text="3.8 版本引入" /> + +当 OpenSearch 通过 MCP 连接器连接到外部[模型上下文协议(MCP)](https://modelcontextprotocol.io/introduction)服务器时,它充当 MCP 客户端。这些 API 允许您在配置代理之前发现和检查外部 MCP 服务器公开的工具。 + +这与 [MCP 服务器 API](/ml-commons-plugin/api/mcp-server-apis/) 不同,后者是 OpenSearch 将自己的工具公开给外部 MCP 客户端。有关使用外部 MCP 服务器与代理的概念信息,请参阅[连接到外部 MCP 服务器](/ml-commons-plugin/agents-tools/mcp/mcp-connector)。 + +OpenSearch 支持以下 MCP 客户端 API: + +- [列出连接器 MCP 工具](/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools) diff --git a/i18n/zh/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools.md b/i18n/zh/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools.md new file mode 100644 index 00000000..8ee5fc40 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-client-apis/list-connector-mcp-tools.md @@ -0,0 +1,104 @@ +--- +title: 列出连接器 MCP 工具 +--- + +# 列出连接器 MCP 工具 API +<Badge type="tip" text="3.8 版本引入" /> + +使用此 API 通过已注册的 MCP 连接器列出外部 MCP 服务器上可用的所有工具。响应包括每个工具的名称、类型、描述和输入架构。 + +流式代理和对话流式代理需要在代理注册期间预先定义工具。使用此 API 在将 MCP 工具添加到代理配置之前发现可用的工具及其参数。有关更多信息,请参阅[注册代理 API](/ml-commons-plugin/api/agent-apis/register-agent)。 + +::: info NOTE +此 API 与[列出 MCP 工具 API](/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools) 不同,后者列出在 OpenSearch 自己的 MCP 服务器上注册的工具。 +::: + +## 先决条件 + +在使用此 API 之前,请完成以下步骤: + +1. 通过将 `plugins.ml_commons.mcp_connector_enabled` 设置为 `true` 来启用 MCP 连接器。 +2. 在 `plugins.ml_commons.trusted_connector_endpoints_regex` 中配置受信任的 MCP 服务器端点。 +3. 使用协议 `mcp_sse` 或 `mcp_streamable_http` 创建 MCP 连接器。 + +有关设置说明,请参阅[连接到外部 MCP 服务器](/ml-commons-plugin/agents-tools/mcp/mcp-connector)。 + +## 端点 + +```json +GET /_plugins/_ml/connectors/{connector_id}/tools +``` + +## 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 必需/可选 | 说明 | +| :--- | :--- | :--- | :--- | +| `connector_id` | String | 必需 | MCP 连接器的 ID。从[创建连接器 API](/ml-commons-plugin/api/connector-apis/create-connector) 响应中获取此 ID。连接器必须使用 `mcp_sse` 或 `mcp_streamable_http` 协议。 | + +## 示例请求 + +以下示例列出 ID 为 `1MlVyZwBBtWLSsWgaB6w` 的 MCP 连接器的工具: + +```json +GET /_plugins/_ml/connectors/1MlVyZwBBtWLSsWgaB6w/tools +``` + +## 示例响应 + +OpenSearch 通过指定的连接器连接到外部 MCP 服务器并返回可用的工具: + +```json +{ + "tools": [ + { + "name": "search_documents", + "type": "McpStreamableHttpTool", + "description": "Search a document repository for relevant content.", + "input_schema": "{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"The search query.\"},\"limit\":{\"type\":\"integer\",\"description\":\"The maximum number of results to return.\",\"minimum\":1,\"maximum\":100}},\"required\":[\"query\"]}" + }, + { + "name": "get_weather", + "type": "McpStreamableHttpTool", + "description": "Retrieve current weather conditions for a specified location.", + "input_schema": "{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"The city or geographic location.\"},\"units\":{\"type\":\"string\",\"description\":\"The temperature unit system.\",\"enum\":[\"celsius\",\"fahrenheit\"]}},\"required\":[\"location\"]}" + } + ] +} +``` + +如果 MCP 服务器没有公开任何工具,OpenSearch 将返回一个空的 `tools` 数组: + +```json +{ + "tools": [] +} +``` + +## 响应体字段 + +下表列出了顶级响应字段。 + +| 字段 | 数据类型 | 说明 | +| :--- | :--- | :--- | +| `tools` | Array | 外部 MCP 服务器上可用的工具列表。如果 MCP 服务器没有公开任何工具,则返回空数组。 | + +`tools` 数组中的每个对象包含以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 说明 | +| :--- | :--- | :--- | :--- | +| `name` | String | 必需 | 外部 MCP 服务器定义的工具名称。在代理中配置 MCP 工具时,使用此值作为 `name` 字段。 | +| `type` | String | 必需 | 用于执行 MCP 工具的 OpenSearch 工具类型。对于使用协议 `mcp_streamable_http` 的连接器,有效值为 `McpStreamableHttpTool`;对于使用协议 `mcp_sse` 的连接器,有效值为 `McpSseTool`。在代理中配置 MCP 工具时,使用此值作为 `type` 字段。 | +| `description` | String | 可选 | 外部 MCP 服务器提供的工具用途的人类可读描述。当 MCP 服务器不提供描述时,从响应中省略。 | +| `input_schema` | String | 可选 | 描述工具输入参数的 JSON 架构字符串。架构遵循 [JSON 架构](https://json-schema.org/)格式,并定义属性、类型、描述和必需字段。当 MCP 服务器不提供输入架构时,从响应中省略。 | + +## 错误响应 + +下表描述了常见的错误响应。 + +| HTTP 状态 | 条件 | 示例错误消息 | +| :--- | :--- | :--- | +| `400` | 连接器存在但不是 MCP 连接器(例如,HTTP 或 Amazon Bedrock 连接器)。 | `Connector with ID {connector_id} is not of type McpConnector or McpStreamableHttpConnector` | +| `404` | 连接器 ID 不存在。 | `Failed to find connector` | +| `500` | MCP 连接器已禁用、外部 MCP 服务器不可达或发生其他内部错误。 | `The MCP connector is not enabled. To enable, please update the setting plugins.ml_commons.mcp_connector_enabled` | diff --git a/i18n/zh/ml-commons-plugin/api/mcp-server-apis/index.md b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/index.md new file mode 100644 index 00000000..b7b9fd96 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/index.md @@ -0,0 +1,29 @@ +--- +title: MCP 服务器 API +--- + +# MCP 服务器 API +<Badge type="tip" text="3.0 版本引入" /> + +使用这些 API 来管理集群内的[模型上下文协议 (MCP)](https://modelcontextprotocol.io/introduction) 服务器,该服务器允许外部 MCP 客户端发现并调用在您的集群中注册的[工具](/ml-commons-plugin/agents-tools/tools/)。 + +::: info NOTE +集群内 MCP 服务器使用可流式 HTTP 传输协议与客户端进行通信。有关传输的详细信息,请参阅[官方 MCP 文档](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports)。 +::: + +有关设置 MCP 服务器和连接客户端的说明,请参阅[使用集群内 MCP 服务器](/ml-commons-plugin/mcp/in-cluster-mcp-server)。 + +集群内 MCP 服务器支持以下 API: + +- [注册 MCP 工具](/ml-commons-plugin/api/mcp-server-apis/register-mcp-tools) +- [更新 MCP 工具](/ml-commons-plugin/api/mcp-server-apis/update-mcp-tools) +- [列出 MCP 工具](/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools) +- [移除 MCP 工具](/ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools) +- [MCP 可流式 HTTP 服务器](/ml-commons-plugin/api/mcp-server-apis/mcp-server) + +## 已移除的 API + +以下实验性 API 在 OpenSearch 3.3 中被移除,改为使用可流式 HTTP 传输: + +- MCP SSE 消息 API +- MCP SSE 会话 API diff --git a/i18n/zh/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools.md b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools.md new file mode 100644 index 00000000..c8771f9b --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/list-mcp-tools.md @@ -0,0 +1,65 @@ +--- +title: 列出 MCP 工具 +--- + +# 列出 MCP 工具 API +<Badge type="tip" text="3.1 版本引入" /> + +使用此 API 按名称列出所有基于模型上下文协议 (MCP) 的工具。 + +## 端点 + +```json +GET /_plugins/_ml/mcp/tools/_list +``` + +## 示例请求 + +```json +GET /_plugins/_ml/mcp/tools/_list +``` + +## 示例响应 + +OpenSearch 返回 MCP 工具列表: + +```json +{ + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleSearchTool", + "description": "This tool can be used to perform search via google engine and parse the content of the searched results", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "next_page": { + "description": "The search result's next page link. If this is provided, the WebSearchTool will fetch the next page results using this link and crawl the links on the page.", + "type": "string" + }, + "engine": { + "description": "The search engine that will be used by the tool.", + "type": "string" + }, + "query": { + "description": "The search query parameter that will be used by the engine to perform the search.", + "type": "string" + } + }, + "required": [ + "engine", + "query" + ] + }, + "strict": false + }, + "create_time": 1749864622040 + } + ] +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/mcp_tools/list`。 diff --git a/i18n/zh/ml-commons-plugin/api/mcp-server-apis/mcp-server.md b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/mcp-server.md new file mode 100644 index 00000000..546f6a39 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/mcp-server.md @@ -0,0 +1,75 @@ +--- +title: MCP 可流式 HTTP 服务器 +--- + +# MCP 可流式 HTTP 服务器 API +<Badge type="tip" text="3.3 版本引入" /> + +集群内模型上下文协议 (MCP) 服务器通过 `/_plugins/_ml/mcp` 端点公开,并实现了[可流式 HTTP 传输](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports)。MCP 客户端使用此端点发现并调用在您的集群中注册的工具。 + +该服务器是无状态的:所有通信都通过单独的 HTTP `POST` 请求进行,服务器不会打开服务器发送事件 (SSE) 流。如果客户端发送 `GET` 请求,服务器将返回 `405 Method Not Allowed` 响应。 + +要使用此端点,请启用 `plugins.ml_commons.mcp_server_enabled` 设置。有关设置说明和示例请求,请参阅[使用集群内 MCP 服务器](/ml-commons-plugin/mcp/in-cluster-mcp-server)。 + +## 端点 + +```json +POST /_plugins/_ml/mcp +``` + +## 请求体字段 + +请求体是一个 [JSON-RPC 2.0](https://www.jsonrpc.org/specification) 消息。下表列出了请求体字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `jsonrpc` | 字符串 | 必需 | JSON-RPC 版本。必须是 `2.0`。 | +| `id` | 整数或字符串 | 可选 | 请求 ID,服务器将在响应中返回。对于通知,省略 ID。 | +| `method` | 字符串 | 必需 | MCP 方法。客户端使用 `initialize` 和 `notifications/initialized` 建立连接,使用 `tools/list` 发现工具,使用 `tools/call` 调用工具。服务器还响应 `ping`,并为 `prompts/list` 和 `resources/list` 返回空列表,因为它仅提供工具。 | +| `params` | 对象 | 可选 | 方法参数。例如,`tools/call` 请求提供工具 `name` 和 `arguments`。 | + +## 示例请求 + +以下请求调用 `ListIndexTool` 工具: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "ListIndexTool", + "arguments": { + "indices": ["opensearch_dashboards_sample_data_ecommerce"] + } + } +} +``` + +## 示例响应 + +服务器在 `content` 数组中返回工具输出: + +```json +{ + "jsonrpc": "2.0", + "id": 3, + "result": { + "content": [ + { + "type": "text", + "text": "row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards)\n1,green,open,opensearch_dashboards_sample_data_ecommerce,ryn25tMCTDex530BrUVmfw,1,0,4675,0,4mb,4mb\n" + } + ], + "isError": false, + "_meta": {} + } +} +``` + +有关 MCP 客户端发送的完整请求序列,请参阅[手动发送 MCP 请求](/ml-commons-plugin/mcp/in-cluster-mcp-server#sending-mcp-requests-manually)。 + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/mcp/server`。工具使用调用用户的权限运行,因此调用访问索引数据的工具还需要相应的索引权限。有关更多信息,请参阅[权限](/ml-commons-plugin/mcp/in-cluster-mcp-server#permissions)。 diff --git a/i18n/zh/ml-commons-plugin/api/mcp-server-apis/register-mcp-tools.md b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/register-mcp-tools.md new file mode 100644 index 00000000..d1f4b6b7 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/register-mcp-tools.md @@ -0,0 +1,394 @@ +--- +title: 注册 MCP 工具 +--- + +# 注册 MCP 工具 API +<Badge type="tip" text="3.0 版本引入" /> + +使用此 API 注册一个或多个基于模型上下文协议 (MCP) 的工具。有关支持的工具的更多信息,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 + +## 端点 + +```json +POST /_plugins/_ml/mcp/tools/_register +``` + +## 请求体字段 + +下表列出了可用的请求字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`tools` | 数组 | 必需 | 工具列表。 + +`tools` 数组包含工具列表。每个工具包含以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`name`| 字符串 | 可选 | 工具名称。工具名称默认为 `type` 参数值。如果需要在 MCP 服务器中包含相同类型的多个工具,请为工具指定不同的名称。 | +`type` | 字符串 | 必需 | 工具类型。有关支持的工具列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +`description` | 字符串 | 可选 | 工具的描述。 +`parameters` | 对象 | 可选 | 工具的参数。参数取决于工具类型。有关特定工具类型的信息,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +`attributes` | 对象 | 可选 | 工具的配置属性。此字段中最重要的属性是工具的 `input_schema`,它定义了工具的预期参数格式。此架构将发送到大型语言模型 (LLM),以便它在执行工具时可以正确格式化参数。 + +## 示例请求 + +[内置工具](/ml-commons-plugin/agents-tools/tools/)分为零配置工具(不需要参数)或参数化工具(需要参数)。零配置工具使用标准初始化过程,因此具有相同的请求体,因为不需要参数。相比之下,对于参数化工具,您必须提供正确的初始化参数以确保工具按预期运行。 + +### 示例请求:零配置工具 + +<details markdown="block"> + <summary> + 示例请求 + </summary> + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "name": "ListIndexTool", + "type": "ListIndexTool", + "description": "This tool gets index information from the OpenSearch cluster. It takes 2 optional arguments named `indices` which is a comma-delimited list of one or more indices to get information from (default is an empty list meaning all indices), and `local` which means whether to return information from the local node only instead of the cluster manager node (default is false). The tool returns the indices information, including `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, `pri.store. size `, `pri.store.size`, `pri.store`.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "indices": { + "type": "array", + "items": { + "type": "string" + }, + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"], use empty array [] to list all indices in the cluster" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchIndexTool", + "type": "SearchIndexTool", + "description": "Use this tool to search an index by providing two parameters: 'index' for the index name, and 'query' for the OpenSearch DSL formatted query. Only use this tool when both index name and DSL query is available.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "string" + }, + "query": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "IndexMappingTool", + "type": "IndexMappingTool", + "description": "This tool gets index mapping information from a certain index. It takes 1 required argument named 'index' which is a comma-delimited list of one or more indices to get mapping information from, which expands wildcards. It takes 1 optional argument named 'local' which means whether to return information from the local node only instead of the cluster manager node (Default is false). The tool returns a list of index mappings and settings for each index. The mappings are in JSON format under the key 'properties' which includes the field name as a key and a JSON object with field type under the key 'type'. The settings are in flattened map with 'index' as the top element and key-value pairs for each setting.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "array", + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"]", + "items": { + "type": "string" + } + } + }, + "required": [ + "index" + ], + "additionalProperties": false + } + } + }, + { + "name": "SearchAlertsTool", + "type": "SearchAlertsTool", + "description": "Use this tool to search an index by providing two parameters: 'index' for the index name, and 'query' for the OpenSearch DSL formatted query. Only use this tool when both index name and DSL query is available.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "string", + "description": "OpenSearch index name. for example: index1" + }, + "query": { + "type": "object", + "description": "OpenSearch search index query. You need to get index mapping to write correct search query. It must be a valid OpenSearch query. Valid value:\n{\"query\":{\"match\":{\"population_description\":\"seattle 2023 population\"}},\"size\":2,\"_source\":\"population_description\"}\nInvalid value: \n{\"match\":{\"population_description\":\"seattle 2023 population\"}}\nThe value is invalid because the match not wrapped by \"query\".", + "additionalProperties": false + } + }, + "required": ["index", "query"], + "additionalProperties": false + } + } + }, + { + "name": "SearchAnomalyDetectorsTool", + "type": "SearchAnomalyDetectorsTool", + "description": "This is a tool that searches anomaly detectors. It takes 12 optional arguments named detectorName which is the explicit name of the detector (default is null), and detectorNamePattern which is a wildcard query to match detector name (default is null), and indices which defines the index or index pattern the detector is detecting over (default is null), and highCardinality which defines whether the anomaly detector is high cardinality (synonymous with multi-entity) of non-high-cardinality (synonymous with single-entity) (default is null, indicating both), and lastUpdateTime which defines the latest update time of the anomaly detector in epoch milliseconds (default is null), and sortOrder which defines the order of the results (options are asc or desc, and default is asc), and sortString which defines how to sort the results (default is name.keyword), and size which defines the size of the request to be returned (default is 20), and startIndex which defines the paginated index to start from (default is 0), and running which defines whether the anomaly detector is running (default is null, indicating both), and failed which defines whether the anomaly detector has failed (default is null, indicating both). The tool returns 2 values: a list of anomaly detectors (each containing the detector id, detector name, detector type indicating multi-entity or single-entity (where multi-entity also means high-cardinality), detector description, name of the configured index, last update time in epoch milliseconds), and the total number of anomaly detectors.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "detectorName": { + "type": "string", + "description": "Anomaly detector name" + }, + "detectorNamePattern": { + "type": "string", + "description": "Anomaly detector name pattern" + }, + "indices": { + "type": "string", + "description": "The index name that anomaly detector uses" + }, + "highCardinality": { + "type": "string", + "description": "The value is true of false, the detector type will be set to MULTI_ENTITY if it's value is true, otherwise SINGLE_ENTITY if it's false" + }, + "lastUpdateTime": { + "type": "string", + "description": "The last update time of the anomaly detector" + }, + "sortString": { + "type": "string", + "description": "The sort key of the search result, default value is `name.keyword` which means the sorting is based on the detector name" + }, + "sortOrder": { + "type": "string", + "description": "The search result order is based on this value, default is asc which means the sorting is in ascending manner." + }, + "size": { + "type": "string", + "description": "This value controls how many search results will be fetched, default value is 20 which means at most 20 anomaly detecotrs can return" + }, + "startIndex": { + "type": "string", + "description": "The start index of the search, default value is 0 which means starts from the beginning" + }, + "running": { + "type": "string", + "description": "The running status of the anomaly detector, valid values are true and false, default is null" + }, + "failed": { + "type": "string", + "description": "The failed status of the anomaly detector, valid values are true and false, default is null" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchAnomalyResultsTool", + "type": "SearchAnomalyResultsTool", + "description": "This is a tool that searches anomaly results. It takes 9 arguments named detectorId which defines the detector ID to filter for (default is null), and realtime which defines whether the anomaly results are from a realtime detector (set to false to only get results from historical analyses) (default is null), and anomalyGradeThreshold which defines the threshold for anomaly grade (a number between 0 and 1 that indicates how anomalous a data point is) (default is greater than 0), and dataStartTime which defines the start time of the anomaly data in epoch milliseconds (default is null), and dataEndTime which defines the end time of the anomaly data in epoch milliseconds (default is null), and sortOrder which defines the order of the results (options are asc or desc, and default is desc), and sortString which defines how to sort the results (default is data_start_time), and size which defines the number of anomalies to be returned (default is 20), and startIndex which defines the paginated index to start from (default is 0). The tool returns 2 values: a list of anomaly results (where each result contains the detector ID, the anomaly grade, and the confidence), and the total number of anomaly results.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "detectorId": { + "type": "string", + "description": "Anomaly detector id" + }, + "realTime": { + "type": "string", + "description": "If the anomaly detector a real time one, valid values are true and false, default is null" + }, + "anomalyGradeThreshold": { + "type": "string", + "description": "A float number to indicate the anomaly grade" + }, + "dataStartTime": { + "type": "string", + "description": "Start time of the data in the anomaly detector" + }, + "dataEndTime": { + "type": "string", + "description": "End time of the data in the anomaly detector" + }, + "sortString": { + "type": "string", + "description": "The sort key of the search result, default value is `name.keyword` which means the sorting is based on the detector name" + }, + "sortOrder": { + "type": "string", + "description": "The search result order is based on this value, default is asc which means the sorting is in ascending manner." + }, + "size": { + "type": "string", + "description": "This value controls how many search results will be fetched, default value is 20 which means at most 20 anomaly detecotrs can return" + }, + "startIndex": { + "type": "string", + "description": "The start index of the search, default value is 0 which means starts from the beginning" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchMonitorsTool", + "type": "SearchMonitorsTool", + "description": "This is a tool that searches alerting monitors. It takes 10 optional arguments named monitorId which defines the monitor ID to filter for (default is null), and monitorName which defines explicit name of the monitor (default is null), and monitorNamePattern which is a wildcard query to match monitor name (default is null), and enabled which defines whether the monitor is enabled (default is null, indicating both enabled and disabled), and hasTriggers which defines whether the monitor has triggers enabled (default is null, indicating both), and indices which defines the index being monitored (default is null), and sortOrder which defines the order of the results (options are asc or desc, and default is asc), and sortString which defines how to sort the results (default is name.keyword), and size which defines the size of the request to be returned (default is 20), and startIndex which defines the paginated index to start from (default is 0). The tool returns 2 values: a list of alerting monitors (each containining monitor ID, monitor name, monitor type (indicating query-level, document-level, or bucket-level monitor types), enabled, enabled time in epoch milliseconds, last update time in epoch milliseconds), and the total number of alerting monitors.", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "monitorId": { + "type": "string", + "description": "Alerting monitor id" + }, + "monitorName": { + "type": "string", + "description": "Alerting monitor name" + }, + "monitorNamePattern": { + "type": "string", + "description": "Alerting monitor name pattern" + }, + "enabled": { + "type": "string", + "description": "If the alerting monitor enabled or not, valid values are true and false, default is null" + }, + "hasTriggers": { + "type": "string", + "description": "If the alerting monitor has triggers, valid values are true and false, default is null" + }, + "indices": { + "type": "string", + "description": "The index names that alerting monitor uses" + }, + "sortString": { + "type": "string", + "description": "The sort key of the search result, default value is `name.keyword` which means the sorting is based on the detector name" + }, + "sortOrder": { + "type": "string", + "description": "The search result order is based on this value, default is asc which means the sorting is in ascending manner." + }, + "size": { + "type": "string", + "description": "This value controls how many search results will be fetched, default value is 20 which means at most 20 alerting monitors can return" + }, + "startIndex": { + "type": "string", + "description": "The start index of the search, default value is 0 which means starts from the beginning" + } + }, + "additionalProperties": false + } + } + } + ] +} +``` + +</details> + +### 示例请求:参数化工具 + +以下部分提供了注册参数化工具的示例请求。有关特定于工具的参数的信息,请参阅相应的[工具文档](/ml-commons-plugin/agents-tools/tools/)。 + +#### WebSearchTool + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleSearchTool", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "engine": { + "type": "string", + "description": "The search engine that will be used by the tool." + }, + "query": { + "type": "string", + "description": "The search query parameter that will be used by the engine to perform the search." + }, + "next_page": { + "type": "string", + "description": "The search result's next page link. If this is provided, the WebSearchTool will fetch the next page results using this link and crawl the links on the page." + } + }, + "required": [ + "engine", + "query" + ] + }, + "strict": false + } + } + ] +} +``` + +<!-- vale off --> +#### PPLTool +<!-- vale on --> + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "type": "PPLTool", + "name": "TransferQuestionToPPLAndExecuteTool", + "description": "Use this tool to convert natural language into PPL queries and execute them. Use this tool after you know the index name; otherwise, call IndexRoutingTool first. The input parameters are: {index: IndexName, question: UserQuestion}", + "parameters": { + "model_id": "${your_model_id}", + "model_type": "FINETUNE" + }, + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "The user's natural language question that needs to be converted to PPL." + }, + "index": { + "type": "string", + "description": "The index on which the generated PPL query will be executed." + } + } + } + } + } + ] +} +``` + +## 示例响应 + +OpenSearch 返回节点 ID 以及每个节点上所有工具的创建状态: + +```json +{ + "_ZNV5BrNTVm6ilcM7Jn1pw": { + "created": true + }, + "NZ9aiUCrSp2b5KBqdJGJKw": { + "created": true + } +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/mcp_tools/register`。 diff --git a/i18n/zh/ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools.md b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools.md new file mode 100644 index 00000000..ee1638d4 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/remove-mcp-tools.md @@ -0,0 +1,42 @@ +--- +title: 移除 MCP 工具 +--- + +# 移除 MCP 工具 API +<Badge type="tip" text="3.0 版本引入" /> + +使用此 API 按名称删除一个或多个基于模型上下文协议 (MCP) 的工具。 + +## 端点 + +```json +POST /_plugins/_ml/mcp/tools/_remove +``` + +## 示例请求 + +```json +POST /_plugins/_ml/mcp/tools/_remove +[ + "GoogleSearchTool", "ListIndexTool" +] +``` + +## 示例响应 + +OpenSearch 返回节点 ID 以及每个节点的工具删除状态: + +```json +{ + "_ZNV5BrNTVm6ilcM7Jn1pw": { + "removed": true + }, + "NZ9aiUCrSp2b5KBqdJGJKw": { + "removed": true + } +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/mcp_tools/remove`。 diff --git a/i18n/zh/ml-commons-plugin/api/mcp-server-apis/update-mcp-tools.md b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/update-mcp-tools.md new file mode 100644 index 00000000..e60e1c7c --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/mcp-server-apis/update-mcp-tools.md @@ -0,0 +1,130 @@ +--- +title: 更新 MCP 工具 +--- + +# 更新 MCP 工具 API +<Badge type="tip" text="3.0 版本引入" /> + +使用此 API 更新一个或多个基于模型上下文协议 (MCP) 的工具。有关支持的工具的更多信息,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 + +## 端点 + +```json +POST /_plugins/_ml/mcp/tools/_update +``` + +## 请求体字段 + +下表列出了可用的请求字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`tools` | 数组 | 必需 | 工具列表。 + +`tools` 数组包含工具列表。每个工具包含以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`name`| 字符串 | 必需 | 要更新的工具名称。 | +`type` | 字符串 | 可选 | 工具类型。此字段被忽略,因为无法更改已注册工具的类型。 +`description` | 字符串 | 可选 | 工具的描述。 +`parameters` | 对象 | 可选 | 工具的参数。参数取决于工具类型。有关特定工具类型的信息,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 +`attributes` | 对象 | 可选 | 工具的配置属性。此字段中最重要的属性是工具的 `input_schema`,它定义了工具的预期参数格式。此架构将发送到大型语言模型 (LLM),以便它在执行工具时可以正确格式化参数。 + +## 示例请求 + +以下部分提供了更新工具的示例请求。有关特定于工具的参数的信息,请参阅相应的[工具文档](/ml-commons-plugin/agents-tools/tools/)。 + +### WebSearchTool + +```json +POST /_plugins/_ml/mcp/tools/_update +{ + "tools": [ + { + "type": "WebSearchTool", + "name": "GoogleSearchTool", + "description": "This tool can be used to perform search via google engine and parse the content of the searched results", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "engine": { + "type": "string", + "description": "The search engine that will be used by the tool." + }, + "query": { + "type": "string", + "description": "The search query parameter that will be used by the engine to perform the search." + }, + "next_page": { + "type": "string", + "description": "The search result's next page link. If this is provided, the WebSearchTool will fetch the next page results using this link and crawl the links on the page." + } + }, + "required": [ + "engine", + "query" + ] + }, + "strict": false + } + } + ] +} +``` + +<!-- vale off --> +### PPLTool +<!-- vale on --> + +```json +POST /_plugins/_ml/mcp/tools/_update +{ + "tools": [ + { + "type": "PPLTool", + "name": "TransferQuestionToPPLAndExecuteTool", + "description": "Use this tool to convert natural language into PPL queries and execute them. Use this tool after you know the index name; otherwise, call IndexRoutingTool first. The input parameters are: {index: IndexName, question: UserQuestion}", + "parameters": { + "model_id": "${your_model_id}", + "model_type": "FINETUNE" + }, + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "The user's natural language question that needs to be converted to PPL." + }, + "index": { + "type": "string", + "description": "The index on which the generated PPL query will be executed." + } + } + } + } + } + ] +} +``` + +## 示例响应 + +对于每个节点,OpenSearch 返回节点 ID 以及所有工具的更新操作状态: + +```json +{ + "_ZNV5BrNTVm6ilcM7Jn1pw": { + "updated": true + }, + "NZ9aiUCrSp2b5KBqdJGJKw": { + "updated": true + } +} +``` + +## 所需权限 + +如果您使用安全插件,请确保您具有适当的权限:`cluster:admin/opensearch/ml/mcp_tools/update`。 diff --git a/i18n/zh/ml-commons-plugin/api/model-apis/batch-predict.md b/i18n/zh/ml-commons-plugin/api/model-apis/batch-predict.md new file mode 100644 index 00000000..a05c1be0 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/model-apis/batch-predict.md @@ -0,0 +1,219 @@ +--- +title: 批处理预测 +--- + +# 批处理预测 API + +在离线和异步模式下使用部署在外部模型服务器上的模型对大型数据集运行推理。要使用批处理预测 API,请提供外部托管模型的 `model_id`。Amazon SageMaker、Cohere 和 OpenAI 是唯一经过验证支持此 API 的外部服务器。 + +有关此 API 的用户访问权限的信息,请参阅[模型访问控制注意事项](/ml-commons-plugin/api/model-apis/#model-access-control-considerations)。 + +有关外部托管模型的信息,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 + +有关如何设置批处理推理和连接器蓝图的说明,请参阅以下内容: + +- [Amazon SageMaker 批处理预测连接器蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_sagemaker_connector_blueprint.md) + +- [OpenAI 批处理预测连接器蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_openAI_connector_blueprint.md) + +## 端点 + +```json +POST /_plugins/_ml/models/{model_id}/_batch_predict +``` + +## 前提条件 + +在使用批处理预测 API 之前,您需要创建到外部托管模型的连接器。对于每个操作,指定描述该操作的 `action_type` 参数: + +- `batch_predict`:运行批处理预测操作。 +- `batch_predict_status`:检查批处理预测操作状态。 +- `cancel_batch_predict`:取消批处理预测操作。 + +例如,要创建到 OpenAI `text-embedding-ada-002` 模型的连接器,请发送以下请求。`cancel_batch_predict` 操作是可选的,支持取消在 OpenAI 上运行的批处理作业: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI Embedding model", + "description": "OpenAI embedding model for testing offline batch", + "version": "1", + "protocol": "http", + "parameters": { + "model": "text-embedding-ada-002", + "input_file_id": "<your input file id in OpenAI>", + "endpoint": "/v1/embeddings" + }, + "credential": { + "openAI_key": "<your openAI key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/embeddings", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input\": ${parameters.input}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.openai.embedding", + "post_process_function": "connector.post_process.openai.embedding" + }, + { + "action_type": "batch_predict", + "method": "POST", + "url": "https://api.openai.com/v1/batches", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input_file_id\": \"${parameters.input_file_id}\", \"endpoint\": \"${parameters.endpoint}\", \"completion_window\": \"24h\" }" + }, + { + "action_type": "batch_predict_status", + "method": "GET", + "url": "https://api.openai.com/v1/batches/${parameters.id}", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + } + }, + { + "action_type": "cancel_batch_predict", + "method": "POST", + "url": "https://api.openai.com/v1/batches/${parameters.id}/cancel", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + } + } + ] +} +``` + +响应包含您将在下一步中使用的连接器 ID: + +```json +{ + "connector_id": "XU5UiokBpXT9icfOM0vt" +} +``` + +接下来,注册外部托管模型并提供创建的连接器的连接器 ID: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "OpenAI model for realtime embedding and offline batch inference", + "function_name": "remote", + "description": "OpenAI text embedding model", + "connector_id": "XU5UiokBpXT9icfOM0vt" +} +``` + +响应包含注册操作的任务 ID: + +```json +{ + "task_id": "rMormY8B8aiZvtEZIO_j", + "status": "CREATED", + "model_id": "lyjxwZABNrAVdFa9zrcZ" +} +``` + +要检查操作的状态,请向[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 提供任务 ID。注册完成后,任务 `state` 将更改为 `COMPLETED`。 + +## 示例请求 + +完成前提条件步骤后,您可以调用批处理预测 API。批处理预测请求中的参数将覆盖连接器中定义的参数: + +```json +POST /_plugins/_ml/models/lyjxwZABNrAVdFa9zrcZ/_batch_predict +{ + "parameters": { + "model": "text-embedding-3-large" + } +} +``` + +## 示例响应 + +响应包含批处理预测操作的任务 ID: + +```json +{ + "task_id": "KYZSv5EBqL2d0mFvs80C", + "status": "CREATED" +} +``` + +要检查批处理预测作业的状态,请向[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 提供任务 ID。您可以在任务的 `remote_job` 字段中找到作业详细信息。预测完成后,任务 `state` 将更改为 `COMPLETED`。 + +## 示例请求 + +```json +GET /_plugins/_ml/tasks/KYZSv5EBqL2d0mFvs80C +``` + +## 示例响应 + +响应在 `remote_job` 字段中包含批处理预测操作详细信息: + +```json +{ + "model_id": "JYZRv5EBqL2d0mFvKs1E", + "task_type": "BATCH_PREDICTION", + "function_name": "REMOTE", + "state": "RUNNING", + "input_type": "REMOTE", + "worker_node": [ + "Ee5OCIq0RAy05hqQsNI1rg" + ], + "create_time": 1725491751455, + "last_update_time": 1725491751455, + "is_async": false, + "remote_job": { + "cancelled_at": null, + "metadata": null, + "request_counts": { + "total": 3, + "completed": 3, + "failed": 0 + }, + "input_file_id": "file-XXXXXXXXXXXX", + "output_file_id": "file-XXXXXXXXXXXXX", + "error_file_id": null, + "created_at": 1725491753, + "in_progress_at": 1725491753, + "expired_at": null, + "finalizing_at": 1725491757, + "completed_at": null, + "endpoint": "/v1/embeddings", + "expires_at": 1725578153, + "cancelling_at": null, + "completion_window": "24h", + "id": "batch_XXXXXXXXXXXXXXX", + "failed_at": null, + "errors": null, + "object": "batch", + "status": "in_progress" + } +} +``` + +有关结果中每个字段的定义,请参阅 [OpenAI 批处理 API](https://platform.openai.com/docs/guides/batch)。批处理推理完成后,您可以通过调用 [OpenAI 文件 API](https://platform.openai.com/docs/api-reference/files) 并提供响应的 `id` 字段中指定的文件名来下载输出。 + +### 取消批处理预测作业 + +您还可以使用批处理预测请求返回的任务 ID 取消在远程平台上运行的批处理预测操作。要添加此功能,请在创建连接器时在连接器配置中将 `action_type` 设置为 `cancel_batch_predict`。 + +## 示例请求 + +```json +POST /_plugins/_ml/tasks/KYZSv5EBqL2d0mFvs80C/_cancel +``` + +## 示例响应 + +```json +{ + "status": "OK" +} +``` diff --git a/i18n/zh/ml-commons-plugin/api/model-group-apis/get-model-group.md b/i18n/zh/ml-commons-plugin/api/model-group-apis/get-model-group.md new file mode 100644 index 00000000..8ffdbeb3 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/model-group-apis/get-model-group.md @@ -0,0 +1,44 @@ +--- +title: 获取模型组 +--- + +# 获取模型组 API + +<Badge type="tip" text="2.12 版本引入" /> + +获取模型组 API 根据模型组的 ID 返回有关模型组的信息。 + +如果在您的集群上启用了模型访问控制,则只有所有者或具有匹配后端角色的用户才能获取私有模型组。任何用户都可以获取任何公共模型组。 + +如果在您的集群上禁用了模型访问控制,则具有 `get model group API` 权限的用户可以获取任何模型组。 + +有关更多信息,请参阅[模型访问控制](/ml-commons-plugin/model-access-control)。 + +## 路径和 HTTP 方法 + +```json +GET /_plugins/_ml/model_groups/{model_group_id} +``` + +### 示例请求 + +以下示例请求根据模型组的 ID 获取模型组: + +```json +GET /_plugins/_ml/model_groups/{model_group_id} +``` + +### 示例响应 + +以下响应返回模型组信息,包括模型组的名称、版本、描述、访问级别和创建信息: + +```json +{ + "name": "test_model_group", + "latest_version": 0, + "description": "This is a public model group", + "access": "public", + "created_time": 1715112992748, + "last_updated_time": 1715112992748 +} +``` diff --git a/i18n/zh/ml-commons-plugin/api/train-predict/predict-stream.md b/i18n/zh/ml-commons-plugin/api/train-predict/predict-stream.md new file mode 100644 index 00000000..8590f76e --- /dev/null +++ b/i18n/zh/ml-commons-plugin/api/train-predict/predict-stream.md @@ -0,0 +1,252 @@ +--- +title: 流式预测 +--- + +# 流式预测 API +<Badge type="tip" text="3.3 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关该功能的进展更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +流式预测 API 提供与[预测 API](/ml-commons-plugin/api/train-predict/predict) 相同的功能,但以流式格式返回响应,在数据可用时以块的形式传递数据。这种流式方法对于具有冗长响应的大型语言模型交互特别有益,允许您立即查看部分结果,而不是等待完整响应。 + +::: info NOTE +或者,您可以通过 gRPC 进行流式预测。有关更多信息,请参阅 [gRPC 预测模型流 API](/api-reference/grpc-apis/predict-model-stream)。 +::: + +此 API 支持以下远程模型类型: +- [OpenAI 聊天完成](https://platform.openai.com/docs/api-reference/completions) +- [Amazon Bedrock Converse Stream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html) + +## 端点 + +```json +POST /_plugins/_ml/models/{model_id}/_predict/stream +``` + +## 前提条件 + +在使用此 API 之前,请确保您已满足以下前提条件。 + +### 设置您的集群 + +按照以下步骤设置您的集群。 + +#### 步骤 1:安装所需的插件 + +流式预测 API 依赖于以下插件,这些插件包含在 OpenSearch 发行版中,但必须按如下方式显式安装: + +```bash +bin/opensearch-plugin install transport-reactor-netty4 +bin/opensearch-plugin install arrow-base +bin/opensearch-plugin install arrow-flight-rpc +``` + +有关更多信息,请参阅[管理 OpenSearch 插件](/install-and-configure/plugins)。 + +#### 步骤 2:配置 OpenSearch 设置 + +将这些设置添加到您的 `opensearch.yml` 文件或 Docker Compose 配置中: + +```yaml +opensearch.experimental.feature.transport.stream.enabled: true + +# 根据您的安全设置选择一个 +http.type: reactor-netty4 # 禁用安全性 +http.type: reactor-netty4-secure # 启用安全性 + +# 多节点集群设置(如果适用) +# 对于 opensearch.yml 使用 network.host IP,对于 Docker 使用节点名称 +arrow.flight.publish_host: <ip> +arrow.flight.bind_host: <ip> + +# 启用安全性的集群设置(如果适用) +transport.stream.type.default: FLIGHT-SECURE +flight.ssl.enable: true +transport.ssl.enforce_hostname_verification: false +``` + +::: info NOTE +如果您使用安全演示证书,请在 `opensearch.yml` 文件中将 `plugins.security.ssl.transport.enforce_hostname_verification: false` 更改为 `transport.ssl.enforce_hostname_verification: false`。 +::: + +有关启用实验性功能的更多信息,请参阅[实验性功能标志](/install-and-configure/configuring-opensearch/experimental)。 + +#### 步骤 3:配置 JVM 选项 + +将这些设置添加到您的 `jvm.options` 文件中: + +```yaml +-Dio.netty.allocator.numDirectArenas=1 +-Dio.netty.noUnsafe=false +-Dio.netty.tryUnsafe=true +-Dio.netty.tryReflectionSetAccessible=true +--add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED +``` + +### 配置必要的 API + +使用以下步骤配置 API。 + +#### 步骤 1:启用流式功能标志 + +要启用流式功能标志,请按如下方式更新集群设置: + +```json +PUT _cluster/settings +{ + "persistent" : { + "plugins.ml_commons.stream_enabled": true + } +} +``` + +#### 步骤 2:注册兼容的外部托管模型 + +要注册 OpenAI 聊天完成模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "OpenAI gpt-4o-mini", + "function_name": "remote", + "description": "OpenAI model", + "connector": { + "name": "OpenAI Chat Connector", + "description": "The connector to OpenAI model service for gpt-4o-mini", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-4o-mini" + }, + "credential": { + "openAI_key": "<your_api_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} }", + "response_filter": "$.choices[0].delta.content" + } + ] + } +} +``` + +要注册 Amazon Bedrock Converse Stream 模型,请发送以下请求: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Amazon Bedrock Converse Stream model", + "function_name": "remote", + "description": "Amazon Bedrock Claude model", + "connector": { + "name": "Amazon Bedrock Converse", + "description": "The connector to Amazon Bedrock Converse", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<your_aws_access_key>", + "secret_key": "<your_aws_secret_key>", + "session_token": "<your_aws_session_token>" + }, + "parameters": { + "region": "<your_aws_region>", + "service_name": "bedrock", + "response_filter": "$.output.message.content[0].text", + "model": "us.anthropic.claude-sonnet-4-6" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/converse", + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.inputs}\"}]}]}" + } + ] + } +} +``` + +## 示例请求 + +要使用流式预测 API,您必须包含与您的模型类型对应的 `_llm_interface` 参数: +- OpenAI 聊天完成:`openai/v1/chat/completions` +- Amazon Bedrock Converse Stream:`bedrock/converse/claude` + +对于 OpenAI 聊天完成,请发送以下请求: + +```json +POST /_plugins/_ml/models/{model_id}/_predict/stream +{ + "parameters": { + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Can you summarize Prince Hamlet of William Shakespeare in around 1000 words?" + } + ], + "_llm_interface": "openai/v1/chat/completions" + } +} +``` + +对于 Amazon Bedrock Converse Stream,请发送以下请求: + +```json +POST /_plugins/_ml/models/{model_id}/_predict/stream +{ + "parameters": { + "inputs": "Can you summarize Prince Hamlet of William Shakespeare in around 1000 words?", + "_llm_interface": "bedrock/converse/claude" + } +} +``` + +## 示例响应 + +流式格式使用服务器发送事件 (SSE),每个块包含模型响应的一部分,以及一个 `is_last` 标志来指示完成。 + +```json +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"Sure","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"!","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"Ham","is_last":false}}]}]} + +... + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":" psyche","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":".","is_last":false}}]}]} + +data: {"inference_results":[{"output":[{"name":"response","dataAsMap":{"content":"","is_last":true}}]}]} +``` + +## 响应体字段 + +下表列出了所有响应体字段。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- |:------------------------------------------------------------------------------------------------------------| +| `inference_results` | 数组 | 包含模型返回的流式响应数据。 | +| `inference_results.output` | 数组 | 包含每个推理结果的输出对象。 | +| `inference_results.output.name` | 字符串 | 输出字段的名称(通常为 `response`)。 | +| `inference_results.output.dataAsMap` | 对象 | 包含响应内容和元数据。 | +| `inference_results.output.dataAsMap.content` | 字符串 | 来自模型响应的文本内容块。 | +| `inference_results.output.dataAsMap.is_last` | 布尔值 | 指示这是否是流中的最后一个块:最后一个块为 `true`,如果还有更多块则为 `false`。 | diff --git a/i18n/zh/ml-commons-plugin/context-management.md b/i18n/zh/ml-commons-plugin/context-management.md new file mode 100644 index 00000000..8f49c469 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/context-management.md @@ -0,0 +1,272 @@ +--- +title: 上下文管理 +--- + +# 上下文管理 +<Badge type="tip" text="3.5 版本引入" /> + +上下文管理使 OpenSearch 代理能够在向大型语言模型(LLM)发送请求之前动态优化其上下文。这一灵活功能通过智能管理对话历史、工具交互和其他上下文信息,有助于防止上下文窗口溢出、减少令牌使用并支持长时间运行的代理。 + +使用上下文管理,您可以构建能够执行以下操作的 AI 代理: + +- 在接近令牌限制时自动截断长工具输出。 +- 总结冗长的工具交互以保留关键信息。 +- 应用滑动窗口方法以维护最近的上下文。 +- 基于特定用例实现自定义上下文优化策略。 +- 在代理执行的不同阶段挂钩以进行上下文转换。 + +上下文管理使用基于挂钩的系统,允许可插拔的上下文管理器在特定执行点检查和转换代理上下文。您可以尝试不同的配置和组合,以找到最适合您特定用例的设置。 + +## 配置上下文管理 + +上下文管理组织_上下文管理器_团队,这些团队在代理生命周期中的特定执行点协同工作以优化代理上下文。该系统高度可配置,允许您根据特定要求定制其行为。 + +每个上下文管理可以配置以下组件: + +- **名称**:上下文管理的唯一标识符。 +- **描述**:上下文管理目的的人类可读描述。 +- **挂钩**:上下文管理器运行的不同执行点。 +- **上下文管理器**:执行特定上下文转换的单个组件。 +- **激活规则**:确定上下文管理器何时应执行的条件。 + +您可以混合和匹配不同的上下文管理器、调整其参数并尝试各种激活阈值,以实现用例的最佳性能。 + +例如,要创建一个名为 `token-aware-truncation` 的上下文管理,包含 `ToolsOutputTruncateManager` 和 `SlidingWindowManager`,请发送以下请求: + +```json +POST /_plugins/_ml/context_management/token-aware-truncation +{ + "description": "Context management that truncates tool outputs longer than 100,000 characters and applies sliding window to keep last 6 messages when tokens exceed 200,000", + "hooks": { + "POST_TOOL": [ + { + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 100000 + } + } + ], + "PRE_LLM": [ + { + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "tokens_exceed": 200000 + } + } + } + ] + } +} +``` + +## 挂钩系统 + +上下文管理使用基于挂钩的架构,允许上下文管理器团队在代理执行期间的特定点执行。支持的挂钩包括: + +- `PRE_LLM` -- 在向 LLM 发送请求之前运行。 +- `POST_TOOL` -- 在工具执行完成后运行。 + +::: warning IMPORTANT +挂钩名称区分大小写,必须为大写。创建上下文管理 API 接受任何挂钩名称,但在小写名称(例如 `post_tool`)下配置的上下文管理器永远不会运行。代理注册请求中的内联 `context_management` 配置会拒绝小写挂钩名称。 +::: + +为每个挂钩注册的上下文管理器按照它们在上下文管理配置中定义的顺序执行。 + +这些挂钩在 OpenSearch [对话代理](/ml-commons-plugin/agents-tools/agents/conversational)和[计划执行代理](/ml-commons-plugin/agents-tools/agents/plan-execute-reflect)中受支持。 + +## 激活规则 + +激活规则确定上下文管理器在代理交互期间何时执行。这些规则通过仅在需要时触发上下文优化来帮助您控制资源使用和优化性能。如果未指定激活规则,上下文管理器将在其配置的挂钩处的每次交互中执行。 + +上下文管理器支持以下激活规则,可以单独使用或组合使用。 + +### 消息数量阈值 + +使用 `message_count_exceed` 在对话历史超过指定消息数量时激活上下文管理器: + +```json +{ + "activation": { + "message_count_exceed": 20 + } +} +``` + +此规则适用于在对话变长时应用上下文优化策略(如滑动窗口或摘要)。 + +### 令牌数量阈值 + +使用 `tokens_exceed` 在整个上下文窗口的估计令牌数超过阈值时激活上下文管理器。上下文窗口包括系统提示、用户提示、聊天历史(记忆)和工具交互: + +```json +{ + "activation": { + "tokens_exceed": 200000 + } +} +``` + +此规则通过在超过模型限制之前触发优化策略来帮助防止上下文窗口溢出并管理 LLM API 成本。 + +### 组合多个规则 + +您可以使用 AND 逻辑组合多个激活规则。上下文管理器仅在满足所有指定条件时执行: + +```json +{ + "activation": { + "message_count_exceed": 15, + "tokens_exceed": 200000 + } +} +``` + +此示例仅在消息数超过 15 AND 令牌数超过 200,000 时激活上下文管理器,从而提供对优化发生时机的精细控制。 + +## 上下文管理器类型 + +OpenSearch 提供以下上下文管理器类型。有关完整的配置参数详细信息,请参见[上下文管理器配置](/ml-commons-plugin/api/context-management-apis/create-context-management#context-manager-configurations)。 + +### SlidingWindowManager + +实现滑动窗口方法,仅保留最近的 N 次交互以防止上下文窗口溢出。此示例显示了一个滑动窗口管理器,它保留最近的 6 条消息,并在对话超过 12 条消息时激活: + +```json +{ + "type": "SlidingWindowManager", + "config": { + "max_messages": 6, + "activation": { + "message_count_exceed": 12 + } + } +} +``` + +有关更多信息,请参见 [SlidingWindowManager](/ml-commons-plugin/api/context-management-apis/create-context-management#slidingwindowmanager)。 + +### SummarizationManager + +在接近令牌限制时总结冗长的对话或工具交互。此示例显示了一个总结管理器,它总结 30% 的对话历史,同时保留最近的 10 条消息,在上下文超过 200,000 个令牌时激活: + +```json +{ + "type": "SummarizationManager", + "config": { + "summary_ratio": 0.3, + "preserve_recent_messages": 10, + "summarization_model_id": "<your-summarization-model-id>", + "activation": { + "tokens_exceed": 200000 + } + } +} +``` + +有关更多信息,请参见 [SummarizationManager](/ml-commons-plugin/api/context-management-apis/create-context-management#summarizationmanager)。 + +### ToolsOutputTruncateManager + +当工具输出超过指定限制时截断它,以防止上下文溢出。为 `POST_TOOL` 挂钩配置此管理器。它处理每个工具调用的输出,无论是使用函数调用(`_llm_interface`)的代理还是不使用的代理。如果输出长度超过 `max_output_length` 个字符,管理器会保留前 `max_output_length` 个字符并附加 `... [Output truncated - original length: <length> characters]`。代理将截断的输出发送到 LLM 并将其存储在代理的跟踪中。此示例显示了一个截断管理器,它将工具输出限制为 40,000 个字符,并在上下文超过 150,000 个令牌时激活: + +```json +{ + "type": "ToolsOutputTruncateManager", + "config": { + "max_output_length": 40000, + "activation": { + "tokens_exceed": 150000 + } + } +} +``` + +有关更多信息,请参见 [ToolsOutputTruncateManager](/ml-commons-plugin/api/context-management-apis/create-context-management#toolsoutputtruncatemanager)。 + +## 代理集成 + +上下文管理可以在代理注册期间或代理执行期间应用于代理。 + +### 在代理注册期间 + +要在代理注册期间将上下文管理应用于代理,请在注册代理时包含现有上下文管理的名称: + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "customer-service-agent", + "type": "conversational", + "llm": { + "model_id": "<llm_model_id>" + }, + "tools": [ + { + "type": "ListIndexTool" + } + ], + "context_management_name": "token-aware-truncation" +} +``` + +### 在代理执行期间 + +要在代理执行期间将上下文管理应用于代理,请在执行请求的 `parameters` 对象中指定上下文管理名称。如果您在执行请求中指定的上下文管理名称与在代理注册期间配置的名称不同,则执行请求会覆盖已注册的设置: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "parameters": { + "question": "How can I help you today?", + "context_management_name": "token-aware-truncation" + } +} +``` + +## 示例用例 + +以下示例演示了如何使用上下文管理。 + +### 长对话 + +要支持长对话,请配置上下文管理,以在防止上下文溢出的同时维护最近的对话流: + +- 使用 `SlidingWindowManager` 保留最近的 N 条消息。 +- 挂钩到 `PRE_LLM` 以在 LLM 调用之前进行优化。 + +### 工具密集型代理 + +为使用许多工具的代理配置上下文管理: + +- 使用 `ToolsOutputTruncateManager` 限制工具输出大小。 +- 为工具交互历史应用 `SlidingWindowManager`。 +- 挂钩到 `POST_TOOL` 以在工具执行后进行清理。 + +### 带摘要的工具密集型代理 + +为具有广泛工具交互的代理配置上下文管理: + +- 使用 `ToolsOutputTruncateManager` 限制工具输出大小。 +- 为工具交互历史应用 `SlidingWindowManager`。 +- 使用 `SummarizationManager` 总结早期的工具交互。 +- 挂钩到 `PRE_LLM` 以在 LLM 调用之前进行优化。 + +## 入门 + +要在您的代理中实现上下文管理: + +1. **[创建上下文管理](/ml-commons-plugin/api/context-management-apis/create-context-management)**,包含适当的管理器和挂钩。 +2. **[注册代理](/ml-commons-plugin/api/agent-apis/register-agent)**,并使用上下文管理或在执行期间指定它。 +3. **[执行代理](/ml-commons-plugin/api/agent-apis/execute-agent)**并观察上下文优化的实际效果。 +4. **[监控和调整](/ml-commons-plugin/api/context-management-apis/update-context-management)**基于性能的上下文管理配置。 + +::: tip TIP +从保守的设置开始,逐步调整阈值、管理器组合和激活规则,以找到最适合您特定工作负载和性能要求的配置。 +::: + +## 下一步 + +- 探索[上下文管理配置](/ml-commons-plugin/api/context-management-apis/create-context-management)选项。 +- 查看完整的[上下文管理 API 参考](/ml-commons-plugin/api/context-management-apis/)。 +- 了解[代理集成](/ml-commons-plugin/agents-tools/agents/)与上下文管理。 diff --git a/i18n/zh/ml-commons-plugin/mcp/in-cluster-mcp-server.md b/i18n/zh/ml-commons-plugin/mcp/in-cluster-mcp-server.md new file mode 100644 index 00000000..d68d2c8d --- /dev/null +++ b/i18n/zh/ml-commons-plugin/mcp/in-cluster-mcp-server.md @@ -0,0 +1,414 @@ +--- +title: 集群内 MCP 服务器 +--- + +# 使用集群内 MCP 服务器 +<Badge type="tip" text="3.3 版本引入" /> + +集群内模型上下文协议(MCP)服务器允许外部 MCP 客户端(例如 AI 助手和代理框架)发现并调用 OpenSearch 集群中的工具。服务器在 OpenSearch 内部运行,因此不需要额外安装。服务器在 `/_plugins/_ml/mcp` 端点暴露,并使用[可流式 HTTP 传输](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports)。客户端只能调用您注册的工具。 + +服务器是无状态的:所有通信都通过单独的 HTTP `POST` 请求进行,服务器不会打开服务器发送事件(SSE)流。如果客户端发送 `GET` 请求(通常是为了打开 SSE 流),服务器返回 `405 Method Not Allowed` 响应,客户端继续使用 `POST` 请求。 + +要比较集群内 MCP 服务器和独立 MCP 服务器,请参阅[选择 MCP 服务器](/ml-commons-plugin/mcp/#choosing-an-mcp-server)。 + +## 步骤 1:启用 MCP 服务器 + +MCP 服务器默认情况下是禁用的。要启用它,请更新 `plugins.ml_commons.mcp_server_enabled` 设置: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.ml_commons.mcp_server_enabled": "true" + } +} +``` + +## 步骤 2:注册工具 + +注册您希望 MCP 客户端调用的工具。每个工具定义包含以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +| :--- | :--- | :--- | :--- | +| `type` | String | 必需 | 工具类型,例如 `ListIndexTool`。有关工具类型列表,请参阅[工具](/ml-commons-plugin/agents-tools/tools/)。 | +| `name` | String | 可选 | 客户端用于调用工具的名称。默认为 `type` 值。要注册同一类型的多个工具,请为每个工具提供不同的名称。 | +| `description` | String | 可选 | 工具的描述。客户端中的大型语言模型(LLM)使用描述来决定何时调用工具。 | +| `parameters` | Object | 可选 | 工具参数。某些工具类型需要参数。有关每种工具类型的参数,请参阅相应的[工具文档](/ml-commons-plugin/agents-tools/tools/)。 | +| `attributes` | Object | 可选 | 工具属性。使用 `input_schema` 属性提供 JSON 模式,定义工具接受的参数。客户端将此模式发送给 LLM,以便 LLM 可以提供格式正确的参数。 | + +以下请求注册[列出索引工具](/ml-commons-plugin/agents-tools/tools/list-index-tool)和[搜索索引工具](/ml-commons-plugin/agents-tools/tools/search-index-tool): + +```json +POST /_plugins/_ml/mcp/tools/_register +{ + "tools": [ + { + "name": "ListIndexTool", + "type": "ListIndexTool", + "description": "This tool returns information about indices in the OpenSearch cluster along with the index `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, `pri.store. size `, `pri.store.size`, `pri.store`. Optional arguments: 1. `indices`, a comma-delimited list of one or more indices to get information from (default is an empty list meaning all indices). Use only valid index names. 2. `local`, whether to return information from the local node only instead of the cluster manager node (Default is false)", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "indices": { + "type": "array", + "items": { + "type": "string" + }, + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"], use empty array [] to list all indices in the cluster" + } + }, + "additionalProperties": false + } + } + }, + { + "name": "SearchIndexTool", + "type": "SearchIndexTool", + "description": "Searches an index. Provide the index name and a query written in OpenSearch query domain-specific language (DSL).", + "attributes": { + "input_schema": { + "type": "object", + "properties": { + "index": { + "type": "string", + "description": "The name of the index to search." + }, + "query": { + "type": "object", + "description": "The search request body, for example, {\"query\": {\"match\": {\"field\": \"value\"}}}." + } + }, + "required": ["index", "query"], + "additionalProperties": false + } + } + } + ] +} +``` + +对于每个节点,响应包含节点 ID 和注册状态: + +```json +{ + "6It0uQ1AR06IDC4nMstPQw": { + "created": true + } +} +``` + +## 步骤 3:连接 MCP 客户端 + +要连接 MCP 客户端,配置客户端使用可流式 HTTP 传输并提供 MCP 服务器 URL: + +``` +http://<host>:<port>/_plugins/_ml/mcp +``` + +以下 Python 示例使用 [FastMCP](https://gofastmcp.com/) 客户端列出已注册的工具,然后在 `opensearch_dashboards_sample_data_ecommerce` 示例索引上调用两个工具: + +```python +import asyncio +from fastmcp import Client + +async def main(): + async with Client("http://localhost:9200/_plugins/_ml/mcp") as client: + for tool in await client.list_tools(): + print(tool.name) + + result = await client.call_tool( + "ListIndexTool", + {"indices": ["opensearch_dashboards_sample_data_ecommerce"]}, + ) + print(result.content[0].text) + + result = await client.call_tool( + "SearchIndexTool", + { + "index": "opensearch_dashboards_sample_data_ecommerce", + "query": { + "size": 1, + "_source": ["customer_full_name", "products.product_name", "taxful_total_price"], + "query": {"match": {"products.product_name": "jacket"}}, + }, + }, + ) + print(result.content[0].text) + +asyncio.run(main()) +``` + +脚本打印工具名称、索引信息和搜索结果: + +``` +ListIndexTool +SearchIndexTool +row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,opensearch_dashboards_sample_data_ecommerce,ryn25tMCTDex530BrUVmfw,1,0,4675,0,4mb,4mb + +{"_index":"opensearch_dashboards_sample_data_ecommerce","_source":{"customer_full_name":"Sultan Al Mccarthy","products":[{"product_name":"Summer jacket - navy"},{"product_name":"Light jacket - khaki"}],"taxful_total_price":86.98},"_id":"eWBchqABedeO5z2s7srO","_score":1.6412048} +``` + +### 对使用安全插件的集群进行身份验证 + +如果您的集群使用安全插件,客户端必须对每个请求进行身份验证。在请求头中传递凭证。例如,要在 FastMCP 中使用基本身份验证,请使用 `Authorization` 头配置传输。如果您的集群使用由您自己的证书颁发机构(CA)签名的证书,请在 `verify` 参数中提供 CA 证书的路径: + +```python +import asyncio, base64 +from fastmcp import Client +from fastmcp.client.transports import StreamableHttpTransport + +credentials = base64.b64encode(b"<username>:<password>").decode() +transport = StreamableHttpTransport( + "https://localhost:9200/_plugins/_ml/mcp", + headers={"Authorization": f"Basic {credentials}"}, + verify="<path-to-root-ca.pem>", +) + +async def main(): + async with Client(transport) as client: + print([tool.name for tool in await client.list_tools()]) + +asyncio.run(main()) +``` + +用户必须具有[权限](#permissions)中描述的权限。 + +## 手动发送 MCP 请求 + +MCP 客户端使用 [JSON-RPC](https://www.jsonrpc.org/specification) 消息与服务器通信。要在没有客户端的情况下调试客户端或测试服务器,可以自己向 MCP 端点发送相同的消息。以下步骤显示了典型 MCP 客户端发送的请求序列。 + +### 步骤 1:初始化连接 + +发送包含您的客户端信息和能力的 `initialize` 请求。`protocolVersion` 必须与支持的 MCP 规范版本匹配: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", + "capabilities": { + "roots": { + "listChanged": true + }, + "sampling": {} + }, + "clientInfo": { + "name": "test-client", + "version": "1.0.0" + } + } +} +``` + +服务器响应其能力和服务器信息。`tools.listChanged` 能力表示服务器支持动态工具发现: + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-03-26", + "capabilities": { + "logging": {}, + "prompts": { + "listChanged": false + }, + "resources": { + "subscribe": false, + "listChanged": false + }, + "tools": { + "listChanged": true + } + }, + "serverInfo": { + "name": "OpenSearch-MCP-Stateless-Server", + "version": "0.1.0" + }, + "instructions": "OpenSearch MCP Stateless Server - provides access to ML tools without sessions" + } +} +``` + +### 步骤 2:发送初始化完成通知 + +发送通知以指示初始化已完成: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "method": "notifications/initialized", + "params": {} +} +``` + +服务器返回 `202 Accepted` 状态,响应体为空。 + +### 步骤 3:列出可用工具 + +使用 `tools/list` 方法发现可用工具: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/list", + "params": {} +} +``` + +服务器返回已注册的工具,包括每个工具的名称、描述和输入模式(`inputSchema`): + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "jsonrpc": "2.0", + "id": 2, + "result": { + "tools": [ + { + "name": "ListIndexTool", + "description": "This tool returns information about indices in the OpenSearch cluster along with the index `health`, `status`, `index`, `uuid`, `pri`, `rep`, `docs.count`, `docs.deleted`, `store.size`, `pri.store. size `, `pri.store.size`, `pri.store`. Optional arguments: 1. `indices`, a comma-delimited list of one or more indices to get information from (default is an empty list meaning all indices). Use only valid index names. 2. `local`, whether to return information from the local node only instead of the cluster manager node (Default is false)", + "inputSchema": { + "type": "object", + "properties": { + "indices": { + "description": "OpenSearch index name list, separated by comma. for example: [\"index1\", \"index2\"], use empty array [] to list all indices in the cluster", + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + } + }, + { + "name": "SearchIndexTool", + "description": "Searches an index. Provide the index name and a query written in OpenSearch query domain-specific language (DSL).", + "inputSchema": { + "type": "object", + "properties": { + "query": { + "description": "The search request body, for example, {\"query\": {\"match\": {\"field\": \"value\"}}}.", + "type": "object" + }, + "index": { + "description": "The name of the index to search.", + "type": "string" + } + }, + "required": [ + "index", + "query" + ], + "additionalProperties": false + } + } + ] + } +} +``` +</details> + +### 步骤 4:调用工具 + +使用 `tools/call` 方法调用工具。提供与工具输入模式匹配的工具名称和参数: + +```json +POST /_plugins/_ml/mcp +{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "ListIndexTool", + "arguments": { + "indices": ["opensearch_dashboards_sample_data_ecommerce"] + } + } +} +``` + +服务器运行工具并在 `content` 数组中返回结果。`isError` 字段指示工具是否成功运行: + +```json +{ + "jsonrpc": "2.0", + "id": 3, + "result": { + "content": [ + { + "type": "text", + "text": "row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards)\n1,green,open,opensearch_dashboards_sample_data_ecommerce,ryn25tMCTDex530BrUVmfw,1,0,4675,0,4mb,4mb\n" + } + ], + "isError": false, + "_meta": {} + } +} +``` + +## 管理已注册的工具 + +要查看已注册的工具,请发送以下请求: + +```json +GET /_plugins/_ml/mcp/tools/_list +``` + +要更新工具,请提供工具名称和要更改的字段。您省略的字段保持其当前值。例如,以下请求仅更新 `SearchIndexTool` 工具的描述: + +```json +POST /_plugins/_ml/mcp/tools/_update +{ + "tools": [ + { + "name": "SearchIndexTool", + "description": "Searches an index of ecommerce orders. Provide the index name and a query written in OpenSearch query DSL." + } + ] +} +``` + +要删除工具,请提供工具名称数组: + +```json +POST /_plugins/_ml/mcp/tools/_remove +["ListIndexTool", "SearchIndexTool"] +``` + +有关更多信息,请参阅 [MCP 服务器 API](/ml-commons-plugin/api/mcp-server-apis/)。 + +## 权限 + +如果您的集群使用安全插件,以下权限控制对 MCP 服务器的访问。 + +| 权限 | 允许 | +| :--- | :--- | +| `cluster:admin/opensearch/ml/mcp/server` | 连接到 MCP 服务器、使用 `tools/list` 方法列出工具以及调用工具 | +| `cluster:admin/opensearch/ml/mcp_tools/list` | 列出已注册的工具 | +| `cluster:admin/opensearch/ml/mcp_tools/register` | 注册工具 | +| `cluster:admin/opensearch/ml/mcp_tools/update` | 更新工具 | +| `cluster:admin/opensearch/ml/mcp_tools/remove` | 删除工具 | + +`ml_full_access` 预定义角色包括所有这些权限。`ml_read_access` 角色不包括任何这些权限。 + +工具使用客户端进行身份验证的用户的权限运行。要调用访问索引数据的工具,用户还需要相应的索引权限。例如,要调用[步骤 2](#step-2-register-tools) 中注册的 `SearchIndexTool` 工具,用户需要对工具搜索的索引具有 `read` 权限。`ml_full_access` 角色不授予对您的索引的权限。 + +有关更多信息,请参阅[权限](/security/access-control/permissions)。 + +## 后续步骤 + +- [MCP 服务器 API](/ml-commons-plugin/api/mcp-server-apis/)。 diff --git a/i18n/zh/ml-commons-plugin/mcp/index.md b/i18n/zh/ml-commons-plugin/mcp/index.md new file mode 100644 index 00000000..dd421008 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/mcp/index.md @@ -0,0 +1,26 @@ +--- +title: MCP 服务器和客户端 +--- + +# MCP 服务器和客户端 + +[模型上下文协议(MCP)](https://modelcontextprotocol.io/introduction)是一个开放标准,定义了 AI 应用程序如何发现和调用工具。OpenSearch 使用以下组件支持 MCP。 + +| 组件 | 用例 | 运行位置 | +| :--- | :--- | :--- | +| [MCP 连接器](/ml-commons-plugin/agents-tools/mcp/) | 让 OpenSearch 代理调用托管在外部 MCP 服务器上的工具。OpenSearch 充当 MCP 客户端。 | 在您的集群中 | +| [集群内 MCP 服务器](/ml-commons-plugin/mcp/in-cluster-mcp-server) | 让外部 MCP 客户端调用在您的集群中注册的工具。OpenSearch 充当 MCP 服务器。 | 在您的集群中 | +| [独立 MCP 服务器](/ai-agent-integrations/mcp-server/) | 让外部 AI 助手使用其 REST API 查询 OpenSearch。 | 在您的集群外 | + +独立 MCP 服务器是开源 [OpenSearch MCP 服务器](https://github.com/opensearch-project/opensearch-mcp-server-py)项目。 + +## 选择 MCP 服务器 + +要让外部 AI 应用程序访问 OpenSearch,请根据您的要求选择 MCP 服务器。 + +| 要求 | 集群内 MCP 服务器 | 独立 MCP 服务器 | +| :--- | :--- | :--- | +| 设置 | 启用 `plugins.ml_commons.mcp_server_enabled` 设置。不需要安装。 | 安装服务器并将其作为单独的进程运行。 | +| 暴露的工具 | 您在集群中注册的工具 | 服务器提供的工具,调用 OpenSearch REST API | +| 传输 | 可流式 HTTP | 标准输入/输出(`stdio`)、可流式 HTTP 和旧版服务器发送事件(SSE) | +| 集群 | 运行服务器的集群 | 一个或多个集群,包括 Amazon OpenSearch Service 域和 Amazon OpenSearch Serverless 集合 | diff --git a/i18n/zh/ml-commons-plugin/memory-and-context.md b/i18n/zh/ml-commons-plugin/memory-and-context.md new file mode 100644 index 00000000..4c95adb8 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/memory-and-context.md @@ -0,0 +1,22 @@ +--- +title: 记忆和上下文 +--- + +# 记忆和上下文 + +OpenSearch 提供智能记忆和上下文管理系统,使 AI 代理能够跨会话维护持久知识和对话上下文。 + +## 记忆系统 + +OpenSearch 提供两种互补的记忆方法: + +- **[代理记忆](/ml-commons-plugin/agentic-memory)**:一个智能记忆系统,使用大型语言模型(LLM)提取见解、学习用户偏好并在代理交互中维护上下文知识。 + +- **[上下文管理](/ml-commons-plugin/context-management)**:一种结构化方法,用于管理 AI 代理和应用程序的对话上下文和系统状态。 + +## 相关 API + +有关记忆和上下文功能的程序化访问,请参见: + +- **[代理记忆 API](/ml-commons-plugin/api/agentic-memory-apis/)**:用于管理记忆容器、会话和记忆的完整 API 参考。 +- **[上下文管理 API](/ml-commons-plugin/api/context-management-apis/)**:用于创建和管理对话上下文的 API 参考。 diff --git a/i18n/zh/ml-commons-plugin/model-sharing-access-control.md b/i18n/zh/ml-commons-plugin/model-sharing-access-control.md new file mode 100644 index 00000000..2170712b --- /dev/null +++ b/i18n/zh/ml-commons-plugin/model-sharing-access-control.md @@ -0,0 +1,127 @@ +--- +title: 通过资源共享的模型访问控制 +--- + +# 通过资源共享的模型访问控制 + +在 ML Commons 中,对模型的访问通过[模型组](/ml-commons-plugin/model-access-control#model-groups)进行控制——特定模型的版本集合,共享相同的访问权限。ML Commons 与安全插件的资源共享和访问控制框架集成,为这些模型组资源提供文档级别的授权。 + +这种资源共享方法是控制模型组访问的新方法,比[原始模型访问控制系统](/ml-commons-plugin/model-access-control)提供更灵活的共享功能。资源所有者可以为单个模型组的用户、角色或后端角色授予特定的访问级别。 + +::: info NOTE +有关端到端框架概念和 API,请参见[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +下表描述了机器学习(ML)模型组资源配置。 + +| 字段 | 值 | +| :--- | :--- | +| 资源类型 | `ml-model-group` | +| 系统索引 | `.plugins-ml-model-group` | +| 引入版本 | OpenSearch 3.3 | + +当为 ML 模型组启用资源级别授权时,每个模型组的可见性由中央共享记录控制。资源所有者和具有共享能力的用户可以为特定用户、角色或后端角色授予或撤销访问权限。 + +## 启用 ML 模型组资源共享 + +要为 ML 模型组启用资源共享,您必须将 ml-model-group 资源类型添加到受保护类型列表中,并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员:这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 `opensearch.yml` 配置文件以为 ML 模型组启用资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "ml-model-group" +``` + +### 使用集群设置 API 配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["ml-model-group"] + } +} +``` + +::: info NOTE +在将 ml-model-group 资源类型添加到现有配置时,请在 `protected_types` 数组中包含所有先前配置的资源类型。 +::: + +## ML 模型组访问级别 + +ML Commons 为 ML 模型组文档提供三个预定义的访问级别。这些访问级别确定授予已被授予模型组资源访问权限的用户的特定权限。 + +### ml_read_only + +`ml_read_only` 只读访问级别授予用户查看和搜索共享的 ML 模型组但不能修改它们的能力。此访问级别包括以下权限: + +```yaml +- "cluster:admin/opensearch/ml/model_groups/get" +- "cluster:admin/opensearch/ml/models/get" +``` + +### ml_read_write + +`ml_read_write` 读写访问级别授予用户对 ML 模型组操作的完全访问权限,但共享功能除外。此访问级别包括所有读取权限以及写入操作: + +```yaml +- "cluster:admin/opensearch/ml/*" +``` + +### ml_full_access + +`ml_full_access` 完全访问级别授予用户对 ML 模型组的完全控制,包括类似所有者的权限,例如与其他用户共享资源。此访问级别包括所有 ML 模型组操作以及资源共享权限: + +```yaml +- "cluster:admin/opensearch/ml/*" +- "cluster:admin/security/resource/share" +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在 [ML Commons GitHub 仓库](https://github.com/opensearch-project/ml-commons/)中创建问题。 +::: + +## 从旧框架迁移 + +在启用资源共享并将 ML 模型组标记为受保护的资源类型后,集群管理员必须运行迁移 API 将现有模型组共享信息从旧框架传输到新的资源共享系统。 + +::: warning IMPORTANT +仅限管理员:迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +使用以下 API 调用将旧的 ML 模型组共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".plugins-ml-model-group", + "username_path": "/owner/name", + "backend_roles_path": "/owner/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "ml-model-group": "<select-appropriate-access-level>" + } +} +``` + +将 `<replace-with-existing-user>` 替换为应拥有没有明确所有权信息的 ML 模型组的现有用户的用户名。将 `<select-appropriate-access-level>` 替换为可用的 ML 模型组访问级别之一:`ml_read_only`、`ml_read_write` 或 `ml_full_access`。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于程序化管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流程和用户指南 diff --git a/i18n/zh/ml-commons-plugin/processor-chain.md b/i18n/zh/ml-commons-plugin/processor-chain.md new file mode 100644 index 00000000..98ca66c5 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/processor-chain.md @@ -0,0 +1,664 @@ +--- +title: 处理器链 +--- + +# 处理器链 +<Badge type="tip" text="3.3 版本引入" /> + +处理器链支持灵活的数据转换管道,可以处理输入和输出数据。将多个处理器链接在一起以创建顺序转换,其中每个处理器的输出成为下一个处理器的输入。 + +处理器提供了一种方法来: + +- **转换数据格式**:在不同的数据结构(字符串、JSON、数组)之间转换。 +- **提取特定信息**:使用 JSONPath 或正则表达式模式提取相关数据。 +- **清理和过滤内容**:删除不需要的字段或应用格式化规则。 +- **标准化数据**:确保不同组件之间的数据格式一致。 + +::: info NOTE +处理器按照它们在数组中出现的顺序执行。每个处理器接收前一个处理器的输出。 +::: + +处理器链专门为 ML 工作流设计,与摄取和搜索管道中的处理器不同: + +- [**摄取管道**](/ingest-pipelines/):在将文档索引到 OpenSearch 期间转换文档。 +- [**搜索管道**](/search-plugins/search-pipelines/):在搜索操作期间转换查询和搜索结果。 +- **处理器链**:在 ML Commons 工作流(代理工具、模型输入/输出)中转换数据。 + +处理器链为 AI/ML 用例提供专门的数据转换能力,例如清理模型响应、从 LLM 输出中提取结构化数据以及准备模型推理的输入。 + +## 配置 + +处理器可以在不同的上下文中配置: + +- **工具输出**:在工具的 `parameters` 部分添加 `output_processors` 数组。 +- **模型输出**:在 `_predict` 调用期间在模型的 `parameters` 部分添加 `output_processors` 数组。 +- **模型输入**:在 `_predict` 调用的模型 `parameters` 部分添加 `input_processors` 数组。 + +有关完整示例,请参见[代理使用示例](#example-usage-with-agents)和[模型使用示例](#example-usage-with-models)。 + +## 支持的处理器类型 + +下表列出了所有支持的处理器。 + +处理器 | 描述 +:--- | :--- +[`conditional`](#conditional) | 根据条件应用不同的处理器链。 +[`extract_json`](#extract_json) | 从文本字符串中提取 JSON 对象或数组。 +[`for_each`](#for_each) | 遍历数组元素并对每个元素应用一系列处理器。 +[`jsonpath_filter`](#jsonpath_filter) | 使用 JSONPath 表达式提取数据。 +[`process_and_set`](#process_and_set) | 对输入应用一系列处理器,并将结果设置在指定的 JSONPath 位置。 +[`regex_capture`](#regex_capture) | 从正则表达式匹配中捕获特定组。 +[`regex_replace`](#regex_replace) | 使用正则表达式模式替换文本。 +[`remove_jsonpath`](#remove_jsonpath) | 使用 JSONPath 从 JSON 对象中删除字段。 +[`set_field`](#set_field) | 将字段设置为指定的静态值或从另一个字段复制值。 +[`to_string`](#to_string) | 将输入转换为 JSON 字符串表示形式。 + +### Conditional + +根据条件应用不同的处理器链。 + +**参数**: + +- `path`(字符串,可选):用于提取值以进行条件评估的 JSONPath 表达式。 +- `routes`(数组,必需):条件-处理器映射的数组。 +- `default`(数组,可选):如果没有条件匹配,则使用的默认处理器。 + +**支持的条件**: + +- 精确值匹配:`"value"` +- 数值比较:`">10"`、`"<5"`、`">="`、`"<="`、`"==5"` +- 存在性检查:`"exists"`、`"null"`、`"not_exists"` +- 正则表达式匹配:`"regex:pattern"` +- 包含文本:`"contains:substring"` + +**示例配置**: + +```json +{ + "type": "conditional", + "path": "$.status", + "routes": [ + { + "green": [ + {"type": "regex_replace", "pattern": "status", "replacement": "healthy"} + ] + }, + { + "red": [ + {"type": "regex_replace", "pattern": "status", "replacement": "unhealthy"} + ] + } + ], + "default": [ + {"type": "regex_replace", "pattern": "status", "replacement": "unknown"} + ] +} +``` + +**示例输入**: + +```json +{"index": "test-index", "status": "green", "docs": 100} +``` + +**示例输出**: + +```json +{"index": "test-index", "healthy": "green", "docs": 100} +``` + +### extract_json + +从文本字符串中提取 JSON 对象或数组。 + +**参数**: + +- `extract_type`(字符串,可选):要提取的 JSON 类型:`"object"`、`"array"` 或 `"auto"`。默认值为 `"auto"`。 +- `default`(任意类型,可选):如果 JSON 提取失败,则使用的默认值。 + +**示例配置**: + +```json +{ + "type": "extract_json", + "extract_type": "object", + "default": {} +} +``` + +**示例输入**: + +```json +"The result is: {\"status\": \"success\", \"count\": 5} - processing complete" +``` + +**示例输出**: + +```json +{"status": "success", "count": 5} +``` + +### for_each + +遍历数组元素并对每个元素应用一系列处理器。适用于统一转换数组元素,例如添加缺失字段、过滤内容或规范化数据结构。 + +**参数**: + +- `path`(字符串,必需):指向要迭代的数组的 JSONPath 表达式。必须使用 `[*]` 表示法表示数组元素。 +- `processors`(数组,必需):要应用于每个数组元素的处理器配置列表。 + +**行为**: + +- 每个元素使用配置的处理器链独立处理。 +- 处理器链的输出替换原始元素。 +- 如果路径不存在或不指向数组,则返回未更改的输入。 +- 如果元素的处理失败,则保留原始元素。 + +**示例配置**: + +```json +{ + "type": "for_each", + "path": "$.items[*]", + "processors": [ + { + "type": "set_field", + "path": "$.processed", + "value": true + } + ] +} +``` + +**示例输入**: + +```json +{ + "items": [ + {"name": "item1", "value": 10}, + {"name": "item2", "value": 20} + ] +} +``` + +**示例输出**: + +```json +{ + "items": [ + {"name": "item1", "value": 10, "processed": true}, + {"name": "item2", "value": 20, "processed": true} + ] +} +``` + +### jsonpath_filter + +使用 JSONPath 表达式提取数据。 + +**参数**: + +- `path`(字符串,必需):用于提取数据的 JSONPath 表达式。 +- `default`(任意类型,可选):如果找不到路径,则使用的默认值。 + +**示例配置**: + +```json +{ + "type": "jsonpath_filter", + "path": "$.data.items[*].name", + "default": [] +} +``` + +**示例输入**: + +```json +{"data": {"items": [{"name": "item1"}, {"name": "item2"}]}} +``` + +**示例输出**: + +```json +["item1", "item2"] +``` + +### process_and_set + +对输入应用一系列处理器,并将结果设置在指定的 JSONPath 位置。 + +**参数**: + +- `path`(字符串,必需):指定设置处理结果位置的 JSONPath 表达式。 +- `processors`(数组,必需):要顺序应用的处理器配置列表。 + +**路径行为**: + +- 如果路径存在,它将使用处理后的值更新。 +- 如果路径不存在,处理器链会尝试创建它(适用于简单的嵌套字段)。 +- 父路径必须存在才能成功创建新字段。 + +**示例配置**: + +```json +{ + "type": "process_and_set", + "path": "$.summary.clean_name", + "processors": [ + { + "type": "to_string" + }, + { + "type": "regex_replace", + "pattern": "[^a-zA-Z0-9]", + "replacement": "_" + } + ] +} +``` + +**示例输入**: + +```json +{"name": "Test Index!", "status": "active"} +``` + +**示例输出**: + +```json +{"name": "Test Index!", "status": "active", "summary": {"clean_name": "Test_Index_"}} +``` + +### regex_capture + +从输入中的第一个正则表达式匹配中捕获特定组。如果模式不匹配,则返回未更改的输入。有关正则表达式语法详细信息,请参见 [Java 正则表达式语法](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。 + +**参数**: + +- `pattern`(字符串,必需):带有捕获组的正则表达式模式。 +- `groups`(字符串或数组,可选):要捕获的组号。可以是单个数字,如 `"1"`,或数组,如 `"[1, 2, 4]"`。默认值为 `"1"`。 + +**示例配置**: + +```json +{ + "type": "regex_capture", + "pattern": "(\\d+),(\\w+),(\\w+),([^,]+)", + "groups": "[1, 4]" +} +``` + +**示例输入**: + +```json +"1,green,open,.plugins-ml-model-group,DCJHJc7pQ6Gid02PaSeXBQ,1,0" +``` + +**示例输出**: + +```json +["1", ".plugins-ml-model-group"] +``` + +### regex_replace + +使用正则表达式模式替换文本。有关正则表达式语法详细信息,请参见 [Java 正则表达式语法](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)。 + +**参数**: +- `pattern`(字符串,必需):要匹配的正则表达式模式。 +- `replacement`(字符串,可选):替换文本。默认值为 `""`。 +- `replace_all`(布尔值,可选):是否替换所有匹配项还是只替换第一个。默认值为 `true`。 + +**示例配置**: + +```json +{ + "type": "regex_replace", + "pattern": "^.*?\n", + "replacement": "" +} +``` + +**示例输入**: + +```json +"row,health,status,index\n1,green,open,.plugins-ml-model\n2,red,closed,test-index" +``` + +**示例输出**: + +```json +"1,green,open,.plugins-ml-model\n2,red,closed,test-index" +``` + +### remove_jsonpath + +使用 JSONPath 从 JSON 对象中删除字段。 + +**参数**: + +- `paths`(数组,必需):标识要删除的字段的 JSONPath 表达式数组。 + +**示例配置**: + +```json +{ + "type": "remove_jsonpath", + "paths": ["$.sensitive_data"] +} +``` + +**示例输入**: + +```json +{"name": "user1", "sensitive_data": "secret", "public_info": "visible"} +``` + +**示例输出**: + +```json +{"name": "user1", "public_info": "visible"} +``` + +### set_field + +将字段设置为指定的静态值或从另一个字段复制值。 + +**参数**: + +- `path`(字符串,必需):指定设置值位置的 JSONPath 表达式。 +- `value`(任意类型,有条件必需):要设置的静态值。必须提供 `value` 或 `source_path`。 +- `source_path`(字符串,有条件必需):要从中复制值的 JSONPath 表达式。必须提供 `value` 或 `source_path`。 +- `default`(任意类型,可选):当 `source_path` 不存在时的默认值。仅与 `source_path` 一起使用。 + +**路径行为**: + +- 如果路径存在,它将使用新值更新。 +- 如果路径不存在,处理器链会尝试创建它(适用于简单的嵌套字段)。 +- 父路径必须存在才能成功创建新字段。 + +**示例配置(静态值)**: + +```json +{ + "type": "set_field", + "path": "$.metadata.processed_at", + "value": "2024-03-15T10:30:00Z" +} +``` + +**示例配置(复制字段)**: + +```json +{ + "type": "set_field", + "path": "$.userId", + "source_path": "$.user.id", + "default": "unknown" +} +``` + +**示例输入**: + +```json +{"user": {"id": 123}, "name": "John"} +``` + +**示例输出**: + +```json +{"user": {"id": 123}, "name": "John", "userId": 123, "metadata": {"processed_at": "2024-03-15T10:30:00Z"}} +``` + +### to_string + +将输入转换为 JSON 字符串表示形式。 + +**参数**: + +- `escape_json`(布尔值,可选):是否转义 JSON 字符。默认值为 `false`。 + +**示例配置**: + +```json +{ + "type": "to_string", + "escape_json": true +} +``` + +**示例输入**: + +```json +{"name": "test", "value": 123} +``` + +**示例输出**: + +```json +"{\"name\":\"test\",\"value\":123}" +``` + +## 代理使用示例 + +以下示例演示了如何将处理器链与代理一起使用。 + +### 步骤 1:注册带有输出处理器的流代理 + +```json +POST /_plugins/_ml/agents/_register +{ + "name": "Index Summary Agent", + "type": "flow", + "description": "Agent that provides clean index summaries", + "tools": [ + { + "type": "ListIndexTool", + "parameters": { + "output_processors": [ + { + "type": "regex_replace", + "pattern": "^.*?\n", + "replacement": "" + }, + { + "type": "regex_replace", + "pattern": "(\\d+,\\w+,\\w+,[^,\n]+)[^\n]*", + "replacement": "$1" + } + ] + } + } + ] +} +``` + +### 步骤 2:执行代理 + +使用上一步返回的 `agent_id`: + +```json +POST /_plugins/_ml/agents/{agent_id}/_execute +{ + "parameters": { + "question": "List the indices" + } +} +``` + +如果没有输出处理器,原始 `ListIndexTool` 会返回带有标题和额外列的详细 CSV 输出: + +```csv +row,health,status,index,uuid,pri(number of primary shards),rep(number of replica shards),docs.count(number of available documents),docs.deleted(number of deleted documents),store.size(store size of primary and replica shards),pri.store.size(store size of primary shards) +1,green,open,.plugins-ml-model-group,DCJHJc7pQ6Gid02PaSeXBQ,1,0,1,0,12.7kb,12.7kb +2,green,open,.plugins-ml-memory-message,6qVpepfRSCi9bQF_As_t2A,1,0,7,0,53kb,53kb +3,green,open,.plugins-ml-memory-meta,LqP3QMaURNKYDZ9p8dTq3Q,1,0,2,0,44.8kb,44.8kb +``` + +输出处理器通过以下方式将详细的 CSV 输出转换为干净、可读的格式: + +1. **`regex_replace`**:删除 CSV 标题行。 +2. **`regex_replace`**:仅保留每行中的行号、健康状态、状态和索引名称。模式捕获行的前四列并匹配行的其余部分,替换 `$1` 将整行替换为捕获的列。由于 `replace_all` 默认为 `true`,因此会处理每一行。 + +使用输出处理器,代理为每个索引返回一行: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "result": "1,green,open,.plugins-ml-model-group\n2,green,open,.plugins-ml-memory-message\n3,green,open,.plugins-ml-memory-meta\n" + } + ] + } + ] +} +``` + +## 模型使用示例 + +以下示例演示了如何在预测 API 调用期间将处理器链与模型一起使用。 + +### 示例:输入处理器 + +此示例向您展示如何使用 `input_processors` 在处理之前修改模型输入以替换文本: + +```json +POST _plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "system_prompt": "You are a helpful assistant.", + "prompt": "Can you summarize Prince Hamlet of William Shakespeare in around 100 words?", + "input_processors": [ + { + "type": "regex_replace", + "pattern": "100", + "replacement": "20" + } + ] + } +} +``` + +在此示例中,`regex_replace` 处理器在将提示发送到模型之前对其进行修改,将"100 words"更改为"20 words"。 + +### 示例:输出处理器 + +此示例向您展示如何使用 `output_processors` 处理模型输出以提取和格式化 JSON 数据。在此示例中,输出处理器首先使用 JSONPath 从模型响应中提取内容。然后它们从文本响应中解析并提取 JSON 对象: + +```json +POST _plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "messages": [ + { + "role": "system", + "content": [ + { + "type": "text", + "text": "${parameters.system_prompt}" + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "Can you convert this into a json object: user name is Bob, he likes swimming" + } + ] + } + ], + "system_prompt": "You are a helpful assistant", + "output_processors": [ + { + "type": "jsonpath_filter", + "path": "$.choices[0].message.content" + }, + { + "type": "extract_json", + "extract_type": "auto" + } + ] + } +} +``` + +如果没有输出处理器,原始响应包含具有大量元数据和嵌套结构的完整模型输出: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "id": "test-id", + "object": "chat.completion", + "created": 1.759580469E9, + "model": "gpt-4o-mini-2024-07-18", + "choices": [ + { + "index": 0.0, + "message": { + "role": "assistant", + "content": "Sure! Here is the information you provided converted into a JSON object:\n\n```json\n{\n \"user\": {\n \"name\": \"Bob\",\n \"likes\": \"swimming\"\n }\n}\n```", + "refusal": null, + "annotations": [] + }, + "logprobs": null, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 33.0, + "completion_tokens": 42.0, + "total_tokens": 75.0, + "prompt_tokens_details": { + "cached_tokens": 0.0, + "audio_tokens": 0.0 + }, + "completion_tokens_details": { + "reasoning_tokens": 0.0, + "audio_tokens": 0.0, + "accepted_prediction_tokens": 0.0, + "rejected_prediction_tokens": 0.0 + } + }, + "service_tier": "default", + "system_fingerprint": "test-fingerprint" + } + } + ], + "status_code": 200 + } + ] +} +``` + +使用输出处理器,响应被简化为仅包含提取和解析的 JSON 数据: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "user": { + "name": "Bob", + "likes": "swimming" + } + } + } + ], + "status_code": 200 + } + ] +} +``` diff --git a/i18n/zh/ml-commons-plugin/remote-models/aws-sigv4.md b/i18n/zh/ml-commons-plugin/remote-models/aws-sigv4.md new file mode 100644 index 00000000..048ace50 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/aws-sigv4.md @@ -0,0 +1,63 @@ +--- +title: AWS 签名版本 4 身份验证 +--- + +# AWS 签名版本 4 身份验证 + +使用 `aws_sigv4` 协议的连接器会使用 AWS 签名版本 4 对每个请求进行签名。AWS 服务(如 Amazon SageMaker、Amazon Bedrock、Amazon Comprehend 和 Amazon Textract)使用此协议。该协议使用您提供的凭证对每个请求进行签名,并添加所需的 `Authorization` 标头,因此您无需指定。 + +以下请求创建一个使用 `aws_sigv4` 协议的独立连接器。它显示了协议所需的 `credential` 和 `parameters` 字段。`url` 和 `request_body` 字段特定于您调用的服务和模型: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "sagemaker: embedding", + "description": "Connector for a SageMaker embedding model", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<access_key>", + "secret_key": "<secret_key>", + "session_token": "<session_token>" + }, + "parameters": { + "region": "us-west-2", + "service_name": "sagemaker" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://runtime.sagemaker.${parameters.region}.amazonaws.com/endpoints/<endpoint_name>/invocations", + "request_body": "[\"${parameters.inputs}\"]" + } + ] +} +``` + +有关您的服务和模型的完整请求(包括 `url`、`request_body` 和任何处理函数),请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors) 中您的平台和模型的蓝图。 + +## 请求体字段 + +当 `protocol` 设置为 `aws_sigv4` 时,`credential` 对象支持以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:---|:---|:---|:---| +| `access_key` | String | 必需 | AWS 账户的访问密钥。 | +| `secret_key` | String | 必需 | AWS 账户的秘密密钥。 | +| `session_token` | String | 可选 | AWS 账户的临时会话令牌。 | + +当 `protocol` 设置为 `aws_sigv4` 时,`parameters` 对象支持以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:---|:---|:---|:---| +| `region` | String | 必需 | 托管服务的 AWS 区域。 | +| `service_name` | String | 必需 | 连接器调用的 AWS 服务的名称。 | + +## 后续步骤 + +- 要查找您的服务和模型的蓝图,请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)。 +- 要注册和部署使用此连接器的模型,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/batch-ingestion.md b/i18n/zh/ml-commons-plugin/remote-models/batch-ingestion.md new file mode 100644 index 00000000..0bd8bd4c --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/batch-ingestion.md @@ -0,0 +1,239 @@ +--- +title: 批处理摄取 +--- + +# 使用外部托管的 ML 模型进行批处理摄取 + +<Badge type="tip" text="2.15 版本引入" /> + +如果您正在摄取多个文档并通过调用外部托管的模型来生成嵌入,则可以使用批处理摄取来提高性能。 + +使用 [Bulk API](/api-reference/document-apis/bulk) 摄取文档时,支持批处理摄取的处理器会将文档分成批次,并在单个请求中将每批文档发送到外部托管的模型。 + +[`text_embedding`](/ingest-pipelines/processors/text-embedding) 和 [`sparse_encoding`](/ingest-pipelines/processors/sparse-encoding) 处理器支持批处理摄取。 + +## 步骤 1:注册模型组 + +您可以通过两种方式注册模型: + +* 您可以使用 `model_group_id` 将模型版本注册到现有模型组。 +* 如果不使用 `model_group_id`,则 OpenSearch 会创建一个带有新模型组的模型。 + +要注册模型组,请发送以下请求: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "remote_model_group", + "description": "A model group for external models" +} +``` + +响应包含模型组 ID,您将使用它将模型注册到此模型组: + +```json +{ + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "status": "CREATED" +} +``` + +要了解有关模型组的更多信息,请参阅[模型访问控制](/ml-commons-plugin/model-access-control)。 + +## 步骤 2:创建连接器 + +您可以创建一个独立的连接器,该连接器可以被 OpenSearch 中共享相同外部端点和配置的多个模型注册重复使用。或者,您可以在创建模型时指定连接器,以便它只能用于该模型。有关更多信息和示例连接器,请参阅[连接器](/ml-commons-plugin/remote-models/connectors)。 + +连接器创建 API `/_plugins/_ml/connectors/_create` 创建连接器,以便在 OpenSearch 中注册和部署外部模型。使用 `endpoint` 参数,您可以通过使用其特定的 API 端点将 OpenSearch 连接到任何支持的 ML 工具。例如,您可以使用 `api.openai.com` 端点连接到 OpenAI 文本嵌入模型: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI embedding connector", + "description": "The connector to the public OpenAI model service for text-embedding-ada-002", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "text-embedding-ada-002", + "input_docs_processed_step_size": 100 + }, + "credential": { + "openAI_key": "<openai_api_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/v1/embeddings", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input\": ${parameters.input}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.openai.embedding", + "post_process_function": "connector.post_process.openai.embedding" + } + ] +} +``` + +`parameters.input_docs_processed_step_size` 参数用于设置发送到远程服务器的文档的最大批处理大小。您可以将此参数设置为远程服务器支持的最大批处理大小或更小的数字以获得最佳性能。 + +响应包含新创建的连接器的连接器 ID: + +```json +{ + "connector_id": "a1eMb4kBJ1eYAeTMAljY" +} +``` + +## 步骤 3:注册外部托管的模型 + +要将外部托管的模型注册到步骤 1 中创建的模型组,请在以下请求中提供步骤 1 中的模型组 ID 和步骤 2 中的连接器 ID。您必须将 `function_name` 指定为 `remote`: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "openAI-text-embedding-ada-002", + "function_name": "remote", + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "description": "test model", + "connector_id": "a1eMb4kBJ1eYAeTMAljY" +} +``` + +OpenSearch 返回注册操作的任务 ID: + +```json +{ + "task_id": "cVeMb4kBJ1eYAeTMFFgj", + "status": "CREATED", + "model_id": "cleMb4kBJ1eYAeTMFFg4" +} +``` + +要检查操作的状态,请向 [获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 提供任务 ID: + +```json +GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj +``` + +当操作完成时,状态更改为 `COMPLETED`: + +```json +{ + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "XPcXLV7RQoi5m8NI_jEOVQ" + ], + "create_time": 1689793598499, + "last_update_time": 1689793598530, + "is_async": false +} +``` + +记下返回的 `model_id`,因为您需要它来部署模型。 + +## 步骤 4:部署模型 + +当您首次发送预测 API 请求时,外部托管的模型会自动部署。要禁用外部托管模型的自动部署,请将 `plugins.ml_commons.model_auto_deploy.enable` 设置为 `false`: + +```json +PUT _cluster/settings +{ + "persistent": { + "plugins.ml_commons.model_auto_deploy.enable" : "false" + } +} +``` + +要手动部署模型,请使用[部署 API](/ml-commons-plugin/api/model-apis/deploy-model): + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_deploy +``` + +响应包含任务 ID,您可以使用它来检查部署操作的状态: + +```json +{ + "task_id": "vVePb4kBJ1eYAeTM7ljG", + "task_type": "DEPLOY_MODEL", + "status": "COMPLETED" +} +``` + +与上一步一样,通过调用[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 检查操作的状态: + +```json +GET /_plugins/_ml/tasks/vVePb4kBJ1eYAeTM7ljG +``` + +当操作完成时,状态更改为 `COMPLETED`: + +```json +{ + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "task_type": "DEPLOY_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "n-72khvBTBi3bnIIR8FTTw" + ], + "create_time": 1689793851077, + "last_update_time": 1689793851101, + "is_async": true +} +``` + +## 步骤 5:创建摄取管道 + +以下示例请求创建一个带有 `text_embedding` 处理器的摄取管道。该处理器将 `passage_text` 字段中的文本转换为文本嵌入,并将嵌入存储在 `passage_embedding` 中: + +```json +PUT /_ingest/pipeline/nlp-ingest-pipeline +{ + "description": "A text embedding pipeline", + "processors": [ + { + "text_embedding": { + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "field_map": { + "passage_text": "passage_embedding" + }, + "batch_size": 5 + } + } + ] +} +``` + +## 步骤 6:执行批量索引 + +要批量摄取文档,请调用 Bulk API 并提供 `pipeline` 参数。如果不提供 `pipeline` 参数,则将使用索引的默认摄取管道进行摄取。以下请求使用在上一步中创建的管道,其 `text_embedding` 处理器的 `batch_size` 为 `5`,因此文档以 5 个一批发送到模型: + +```json +POST _bulk?pipeline=nlp-ingest-pipeline +{ "create": { "_index": "testindex1", "_id": "2" } } +{ "passage_text": "hello world" } +{ "create": { "_index": "testindex1", "_id": "3" } } +{ "passage_text": "big apple" } +{ "create": { "_index": "testindex1", "_id": "4" } } +{ "passage_text": "golden gate bridge" } +{ "create": { "_index": "testindex1", "_id": "5" } } +{ "passage_text": "fine tune" } +{ "create": { "_index": "testindex1", "_id": "6" } } +{ "passage_text": "random test" } +{ "create": { "_index": "testindex1", "_id": "7" } } +{ "passage_text": "sun and moon" } +{ "create": { "_index": "testindex1", "_id": "8" } } +{ "passage_text": "windy" } +{ "create": { "_index": "testindex1", "_id": "9" } } +{ "passage_text": "new york" } +{ "create": { "_index": "testindex1", "_id": "10" } } +{ "passage_text": "fantastic" } + +``` diff --git a/i18n/zh/ml-commons-plugin/remote-models/batching-requests.md b/i18n/zh/ml-commons-plugin/remote-models/batching-requests.md new file mode 100644 index 00000000..efc8b81d --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/batching-requests.md @@ -0,0 +1,185 @@ +--- +title: 请求批处理 +--- + +# 对外部托管模型的请求进行批处理 +<Badge type="tip" text="3.9 版本引入" /> + +OpenSearch 提供了两种技术来控制如何将预测请求分组为对外部托管模型的调用: + +- 可以拆分大型预测请求,以便对模型的每次调用都保持在模型端点的限制范围内。 + +- 可以将小型预测请求组合为对模型的更少调用,这会增加吞吐量,但代价是在每次调用之前有短暂的等待。 + +这两种技术都是可选的,默认情况下禁用,并且都对输入字符串进行操作。输入字符串是预测请求的 `text_docs` 数组中的一个字符串,例如摄取期间一个文档字段的文本或搜索期间的查询文本。 + +您在注册模型时在 `batch_inference_config` 参数中配置这两种技术。有关字段描述和默认值,请参阅 [`batch_inference_config` 参数](/ml-commons-plugin/api/model-apis/register-model#the-batch_inference_config-parameter)。 + +这些技术仅适用于其[连接器](/ml-commons-plugin/remote-models/connectors)接受文本文档 (`text_docs`) 输入并按相同顺序为每个输入字符串生成一个结果的外部托管模型。使用 `batch_inference_config` 参数配置的模型会拒绝使用其他输入类型的预测请求。 + +## 拆分大型预测请求 + +当一个预测请求中的输入字符串可能超过模型端点对输入字符串数量或组合大小的限制时,请使用请求拆分。这种模式在批量摄取期间很常见,因为[摄取处理器](/ingest-pipelines/processors/index-processors)可以在一个预测请求中发送许多文档。 + +### 选择大小限制 + +设置 `max_items_per_request`、`max_bytes_per_request` 或两者。使用 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)来识别连接器使用的提供商和确切模型。从提供商的确切模型和版本的官方文档或自定义端点的模型服务器配置中获取限制。 + +`max_items_per_request` 参数限制每次调用模型的输入字符串数量,`max_bytes_per_request` 限制它们的组合大小(以字节为单位)。OpenSearch 将每个输入字符串的大小测量为其 UTF-8 字节长度。字节限制仅计算输入字符串。发送到模型的请求还包含连接器的 `request_body` 模板中定义的其他字段,因此将 `max_bytes_per_request` 设置为低于模型的实际限制,以为它们留出空间。 + +要稍后更改 `batch_inference_config` 设置,请使用[更新模型 API](/ml-commons-plugin/api/model-apis/update-model)。OpenSearch 将 `batch_inference_config` 存储在已注册的模型上,因此使用该模型的摄取管道、批量 API 请求和查询不需要任何更改。 + +### 拆分规则 + +OpenSearch 将预测请求的 `text_docs` 数组拆分为连续的输入字符串组,保持原始顺序,并在单独的调用中将每个组发送到模型。OpenSearch 将输入字符串添加到当前调用,直到下一个输入字符串会超过 `max_items_per_request` 或 `max_bytes_per_request`,然后开始新的调用。调用可以完全达到限制。例如,考虑以下配置和输入大小: + +```text +max_items_per_request = 3 +max_bytes_per_request = 10 +input sizes in bytes = [4, 3, 5, 2] +``` + +OpenSearch 创建以下对模型的调用: + +```text +Call 1: [4, 3] +Call 2: [5, 2] +``` + +将 5 字节输入字符串添加到第一个调用会产生 12 字节,因此 OpenSearch 开始第二个调用。两个调用也都保持在三个输入字符串的限制内。 + +如果原始请求已经在限制范围内,OpenSearch 将其作为单个调用发送到模型。如果单个输入字符串大于 `max_bytes_per_request`,OpenSearch 会不变地发送该输入字符串,模型端点可能会拒绝它。 + +OpenSearch 等待从原始预测请求创建的所有对模型的调用。如果所有调用都成功,OpenSearch 会按原始输入顺序组合它们的输出。如果任何调用失败,原始预测请求将失败并且不会返回部分结果。 + +有关为失败的调用配置重试和退避设置的信息,请参阅 [client_config 对象](/ml-commons-plugin/api/connector-apis/create-connector#the-client_config-object)。 + +### 配置请求拆分 + +要为批处理摄取配置请求拆分,请按照以下步骤操作。 + +#### 步骤 1:注册摄取模型 + +注册外部托管的模型,并在[模型注册请求](/ml-commons-plugin/api/model-apis/register-model)中提供 `batch_inference_config` 参数。以下请求配置请求拆分而不进行动态批处理: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "remote-embedding-model-for-ingest", + "function_name": "remote", + "connector_id": "<connector_id>", + "batch_inference_config": { + "max_items_per_request": 96, + "max_bytes_per_request": 4000000 + } +} +``` + +注册请求返回任务 ID 和模型 ID。在使用模型 ID 之前,请使用[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 等待任务达到 `COMPLETED` 状态。 + +#### 步骤 2:将模型添加到摄取管道 + +在摄取处理器中使用模型 ID。处理器的 `batch_size` 设置每个预测请求中的文档数量,然后模型的限制将每个预测请求拆分为对模型的调用。以下示例配置一个 [`text_embedding` 处理器](/ingest-pipelines/processors/text-embedding),该处理器在每个预测请求中最多发送 100 个文档。由于步骤 1 中注册的模型将 `max_items_per_request` 设置为 `96`,OpenSearch 将这些请求中的每一个拆分为包含不超过 96 个输入字符串的调用: + +```json +PUT /_ingest/pipeline/embedding-pipeline +{ + "processors": [ + { + "text_embedding": { + "model_id": "<ingest_model_id>", + "field_map": { + "passage_text": "passage_embedding" + }, + "batch_size": 100 + } + } + ] +} +``` + +#### 步骤 3:运行批处理摄取 + +按照[批处理摄取](/ml-commons-plugin/remote-models/batch-ingestion)中的描述,将管道与 Bulk API 一起使用。 + +## 动态批处理小型预测请求 + +当同一模型的许多小型预测请求接近到达时,动态批处理很有用。这种模式在搜索期间很常见,因为每个[神经查询](/query-dsl/specialized/neural)通常会生成一个包含一个输入字符串(查询文本)的预测请求。 + +要将动态批处理独立地应用于摄取和搜索,请为两个工作负载注册单独的模型 ID,并仅在搜索模型上启用动态批处理。 + +要启用动态批处理,请将 `dynamic_batching.enabled` 设置为 `true`。您还必须设置 `max_items_per_request`、`max_bytes_per_request` 或两者。这些限制设置每个批处理调用的最大大小,因此将它们配置为允许每次对模型的调用包含多个输入字符串。有关更多信息,请参阅[选择大小限制](#choosing-the-size-limits)。 + +OpenSearch 在处理每个预测请求的节点上对其进行排队,并在满足以下任一条件时批量调用模型: + +- 累积的输入字符串数量达到配置的 `max_items_per_request` 限制。 +- 输入字符串的累积大小(以字节为单位)达到配置的 `max_bytes_per_request` 限制。 +- 自收到第一个请求以来经过的时间达到 `dynamic_batching.flush_timeout_ms`。 + +当流量较低且未达到任何大小限制时,第一个请求会等待完整的 `dynamic_batching.flush_timeout_ms` 值。例如,将该值设置为 `10000` 可能会在调用模型之前增加 10 秒。 + +### 批处理范围和资源使用 + +每个批处理属于一个节点上的一个模型 ID: + +- 使用不同模型 ID 的请求不共享批处理,即使两个模型引用相同的连接器。 +- 路由到不同节点的相同模型的请求进入不同的批处理。 +- 相同模型和节点的请求共享批处理。在该批处理中,OpenSearch 将预测输入字段完全相同(除了 `text_docs`)的请求分组。对于直接[预测 API](/ml-commons-plugin/api/train-predict/predict) 调用,端点(包括 `{algorithm_name}` 和 `{model_id}`)也必须相同。每个组作为单独的批处理请求发送到模型。 + +节点上的所有模型共享可用于排队请求的内存。批处理在等待其他请求时和对模型的调用进行时保留内存。如果此内存耗尽,OpenSearch 会在调用模型端点之前拒绝新请求。有关内存设置的信息,请参阅[动态批处理内存设置](/ml-commons-plugin/cluster-settings#dynamic-batching-memory-settings)。 + +### 响应路由 + +OpenSearch 将每个输出路由到提供相应输入的请求和位置。如果对模型的调用返回的结果数量与它包含的输入字符串数量不同,OpenSearch 无法路由输出,受影响的请求将失败。 + +### 为搜索配置动态批处理 + +要为搜索配置动态批处理,请按照以下步骤操作。 + +#### 步骤 1:注册启用了动态批处理的搜索模型 + +使用端点限制注册搜索模型并提供 `dynamic_batching` 参数: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "remote-embedding-model-for-search", + "function_name": "remote", + "connector_id": "<connector_id>", + "batch_inference_config": { + "max_items_per_request": 96, + "max_bytes_per_request": 4000000, + "dynamic_batching": { + "enabled": true, + "flush_timeout_ms": 50 + } + } +} +``` + +注册请求返回任务 ID 和用于搜索的单独模型 ID。 + +#### 步骤 2:使用模型生成查询嵌入 + +注册任务达到 `COMPLETED` 状态后,在所有生成查询嵌入的请求中使用搜索模型 ID。以下示例在 `knn_vector` 字段的[神经查询](/query-dsl/specialized/neural)中指定搜索模型 ID: + +```json +GET /my-index/_search +{ + "query": { + "neural": { + "passage_embedding": { + "query_text": "How does remote inference batching work?", + "model_id": "<search_model_id>", + "k": 10 + } + } + } +} +``` + +## 相关文档 + +- [稀疏编码处理器](/ingest-pipelines/processors/sparse-encoding) +- [神经稀疏查询](/query-dsl/specialized/neural-sparse) +- [语义搜索](/vector-search/ai-search/semantic-search/) diff --git a/i18n/zh/ml-commons-plugin/remote-models/connector-authentication.md b/i18n/zh/ml-commons-plugin/remote-models/connector-authentication.md new file mode 100644 index 00000000..32d49cd1 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/connector-authentication.md @@ -0,0 +1,24 @@ +--- +title: 连接器身份验证 +--- + +# 连接器身份验证 + +连接器使用其 `credential` 对象中的值对外部托管的模型进行身份验证。身份验证方法在连接器的 `protocol` 字段中指定,并由您要连接的平台确定。每个协议都有自己的凭证字段和集群先决条件。 + +下表列出了可用的协议。 + +| 协议 | 平台 | 文档 | +|:---|:---|:---| +| `http` | 没有专用协议的平台,包括 OpenAI、Cohere、Azure OpenAI、DeepSeek、Ollama、Aleph Alpha 和 Yandex Cloud | [HTTP 身份验证](/ml-commons-plugin/remote-models/http-authentication) | +| `aws_sigv4` | AWS 服务,如 Amazon SageMaker、Amazon Bedrock、Amazon Comprehend 和 Amazon Textract | [AWS 签名版本 4 身份验证](/ml-commons-plugin/remote-models/aws-sigv4) | +| `google_cloud` | Google Cloud Vertex AI | [Google Cloud 身份验证](/ml-commons-plugin/remote-models/google-cloud) | + +`aws_sigv4` 和 `google_cloud` 协议会为您生成并刷新短期访问令牌,因此您无需手动提供或轮换令牌。`http` 协议传递您提供的凭证,通常是令牌,如 API 密钥。要查找您的平台和模型的协议,请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)。 + +需要双向 TLS (mTLS) 的端点接受客户端证书而不是令牌。这仅适用于使用 `http` 协议的连接器。有关更多信息,请参阅[客户端证书身份验证](/ml-commons-plugin/remote-models/http-authentication#client-certificate-authentication)。 + +## 后续步骤 + +- 有关所有连接器字段(包括 `client_config` 对象)的描述,请参阅[创建连接器 API](/ml-commons-plugin/api/connector-apis/create-connector#request-body-fields)。 +- 要更改现有连接器的凭证,请参阅[更新连接器凭证](/ml-commons-plugin/remote-models/connectors#updating-connector-credentials)。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/connector-input-output.md b/i18n/zh/ml-commons-plugin/remote-models/connector-input-output.md new file mode 100644 index 00000000..0fffbaf8 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/connector-input-output.md @@ -0,0 +1,506 @@ +--- +title: 连接器输入和输出 +--- + +# 连接器输入和输出 +<Badge type="tip" text="2.9 版本引入" /> + +连接器构建 OpenSearch 发送到模型 API 的请求,并将模型响应转换为 OpenSearch 所需的格式。 + +## 请求体模板 + +以下连接器摘录显示了决定请求体的字段。`actions` 数组中的每个对象定义连接器支持的一个操作。`request_body` 字段是请求体的模板。模板包含格式为 `${parameters.<parameter_name>}` 的占位符。在此示例中,模板包含 `model` 和 `messages` 占位符: + +```json +{ + "parameters": { + "model": "gpt-4o-mini" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/chat/completions", + "request_body": "{ \"model\": \"${parameters.model}\", \"messages\": ${parameters.messages} }" + } + ] +} +``` + +当您发送[预测 API](/ml-commons-plugin/api/train-predict/predict) 请求时,OpenSearch 会将每个占位符替换为相应的参数值,并将结果发送到模型。OpenSearch 从预测 API 请求获取参数值,或者如果请求未提供该值,则从连接器 `parameters` 对象获取。在此示例中,`model` 默认为 `gpt-4o-mini`,因此预测 API 请求只需提供 `messages`。 + +OpenSearch 将每个值插入模板时不会添加引号。如果占位符的值是字符串,请用引号括起来,如前面示例中的 `model`。如果占位符的值是数字、布尔值或 JSON 数组或对象,请不要用引号括起来,如 `messages`。OpenSearch 会转义预测 API 请求中提供的字符串值中的特殊字符,例如引号。有关例外情况,请参见[预测 API](/ml-commons-plugin/api/train-predict/predict#request-body-fields) 中的 `parameters` 字段。 + +`url` 字段也可以包含参数占位符,例如 `"url": "https://${parameters.endpoint}/v1/chat/completions"`,其中连接器 `parameters` 对象提供 `endpoint` 值。要在标头中使用参数占位符,请参见[动态标头替换](/ml-commons-plugin/remote-models/dynamic-header-substitution)。 + +要向模型平台进行身份验证,连接器操作可以在其 `headers` 对象中包含 `${credential.<credential_name>}` 占位符,例如 `"Authorization": "Bearer ${credential.openAI_key}"`。OpenSearch 使用连接器 `credential` 对象中的值填充这些占位符。凭证占位符仅在标头中填充,预测 API 请求无法提供凭证值。 + +## 输入格式 + +OpenSearch 接受以下格式之一的输入。当您直接调用模型时,请将输入作为参数提供。某些 OpenSearch 功能始终以不同的格式发送其输入,连接器预处理函数会将其转换为参数。要测试这些功能使用的连接器,请以相同的格式发送预测 API 请求。 + +| 输入格式 | 请求体字段 | 何时使用 | +| :--- | :--- | :--- | +| [参数](#providing-input-as-parameters) | `parameters` | 直接调用任何外部托管的模型。`ml_inference` 处理器也使用此格式。 | +| [文本文档](#providing-input-as-text-documents) | `text_docs` | 测试 `text_embedding` 摄取处理器或 `neural` 查询使用的嵌入模型连接器。 | +| [文本相似性输入](#providing-input-for-text-similarity) | `query_text` 和 `text_docs` | 测试 `rerank` 搜索处理器使用的重排序模型连接器。 | + +## 以参数形式提供输入 + +在预测请求中,`parameters` 对象将占位符名称映射到值:每个键命名一个占位符,其值替换该占位符。为连接器 `parameters` 对象中没有默认值的每个占位符提供一个值。 + +以下示例使用[创建独立连接器](/ml-commons-plugin/remote-models/connectors#creating-a-standalone-connector)中显示的 OpenAI 聊天连接器。连接器 `parameters` 对象为 `endpoint` 和 `model` 提供默认值。`request_body` 模板包含 `model` 和 `messages` 占位符。因为 `messages` 没有默认值,所以每个预测请求都必须提供它。 + +使用此连接器[注册模型](/ml-commons-plugin/remote-models/#step-2-register-an-externally-hosted-model)后,在预测 API 请求中提供 `messages` 值: + +```json +POST /_plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "messages": [ + { + "role": "user", + "content": "Hello" + } + ] + } +} +``` + +OpenSearch 使用请求中的 `messages` 值和连接器中的 `model` 值填充模板,并将以下请求体发送到模型: + +```json +{ "model": "gpt-4o-mini", "messages": [{"role":"user","content":"Hello"}] } +``` + +预测 API 响应中的 `dataAsMap` 对象包含模型响应: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "id": "chatcmpl-7e6s5DYEutmM677UZokF9eH40dIY7", + "object": "chat.completion", + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Hello! How can I assist you today?" + }, + "finish_reason": "stop" + } + ] + } + } + ], + "status_code": 200 + } + ] +} +``` + +要覆盖连接器默认值,请在请求中提供该参数。例如,以下请求将模型设置为 `gpt-4o`: + +```json +POST /_plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "model": "gpt-4o", + "messages": [ + { + "role": "user", + "content": "Hello" + } + ] + } +} +``` + +`ml_inference` 摄取处理器也以参数形式提供输入。它的 `input_map` 将文档字段映射到参数名称。有关更多信息,请参见 [ML 推理处理器](/ingest-pipelines/processors/ml-inference)。 + +## 以文本文档形式提供输入 + +嵌入功能,例如 `text_embedding` 摄取处理器和 `neural` 查询,将其输入作为字符串的 `text_docs` 数组发送。嵌入模型的连接器使用以下函数在此格式和模型 API 之间进行转换: + +- 预处理函数将 `text_docs` 数组转换为填充请求体模板的参数。 +- 后处理函数将模型响应转换为 OpenSearch 所需的嵌入格式。 + +例如,以下连接器使用内置的 OpenAI 预处理和后处理函数: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI embedding connector", + "description": "The connector to the OpenAI embeddings API", + "version": 1, + "protocol": "http", + "parameters": { + "model": "text-embedding-3-small" + }, + "credential": { + "openAI_key": "<openai_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.openai.com/v1/embeddings", + "headers": { + "Authorization": "Bearer ${credential.openAI_key}" + }, + "request_body": "{ \"input\": ${parameters.input}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.openai.embedding", + "post_process_function": "connector.post_process.openai.embedding" + } + ] +} +``` + +要使用这些功能发送的输入测试连接器,请在预测 API 请求中提供 `text_docs` 数组。将 `algorithm` 查询参数设置为 `text_embedding`,以便 OpenSearch 读取 `text_docs` 字段: + +```json +POST /_plugins/_ml/models/{model_id}/_predict?algorithm=text_embedding +{ + "text_docs": ["red shoes", "blue hat"] +} +``` + +预处理函数将字符串转换为 `input` 参数,OpenSearch 将以下请求体发送到模型: + +```json +{ "input": ["red shoes","blue hat"], "model": "text-embedding-3-small" } +``` + +如果连接器未定义预处理函数,OpenSearch 使用 `connector.pre_process.default.embedding`,它也将字符串转换为 `input` 参数。 + +后处理函数从模型响应中提取嵌入。预测 API 响应为每个字符串包含一个嵌入: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [1536], + "data": [-0.0147, 0.0362, ...] + }, + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [1536], + "data": [0.0081, -0.0215, ...] + } + ], + "status_code": 200 + } + ] +} +``` + +如果您不指定算法,OpenSearch 只读取 `parameters` 对象,因此模板占位符没有值,请求将失败。您也可以将算法指定为路径参数。有关更多信息,请参见[预测 API](/ml-commons-plugin/api/train-predict/predict)。 + +如果连接器未定义后处理函数,预测 API 响应将包含未更改的模型响应。有关每个内置函数接受的输入和产生的输出,请参见[内置预处理和后处理函数](#built-in-pre--and-post-processing-functions)。要编写自己的函数,请参见[自定义预处理和后处理函数](#custom-pre--and-post-processing-functions)。 + +::: info NOTE +如果连接器使用内置预处理函数,您也可以在 `parameters` 对象中提供输入。例如,发送 `{"parameters": {"input": ["red shoes", "blue hat"]}}` 会产生与前面 `text_docs` 请求相同的模型请求体。 +::: + +## 为文本相似性提供输入 + +`rerank` 搜索处理器将其输入作为 `query_text` 字符串和包含每个搜索结果文本的 `text_docs` 数组发送。重排序模型的连接器必须定义一个预处理函数,将此输入转换为参数,因为 OpenSearch 没有为文本相似性输入提供默认的预处理函数。 + +例如,以下连接器使用内置的 Cohere Rerank 函数: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Cohere rerank connector", + "description": "The connector to the Cohere Rerank API", + "version": 1, + "protocol": "http", + "parameters": { + "model": "rerank-english-v3.0" + }, + "credential": { + "cohere_key": "<cohere_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://api.cohere.ai/v1/rerank", + "headers": { + "Authorization": "Bearer ${credential.cohere_key}" + }, + "request_body": "{ \"documents\": ${parameters.documents}, \"query\": \"${parameters.query}\", \"top_n\": ${parameters.top_n}, \"model\": \"${parameters.model}\" }", + "pre_process_function": "connector.pre_process.cohere.rerank", + "post_process_function": "connector.post_process.cohere.rerank" + } + ] +} +``` + +要使用 `rerank` 处理器发送的输入测试连接器,请在预测 API 请求中提供 `query_text` 和 `text_docs`。将 `algorithm` 查询参数设置为 `text_similarity`,以便 OpenSearch 读取这些字段: + +```json +POST /_plugins/_ml/models/{model_id}/_predict?algorithm=text_similarity +{ + "query_text": "Which shoes are waterproof?", + "text_docs": ["Waterproof hiking boots", "Canvas sneakers"] +} +``` + +预处理函数将输入转换为 `query`、`documents` 和 `top_n` 参数,OpenSearch 将以下请求体发送到模型: + +```json +{ "documents": ["Waterproof hiking boots","Canvas sneakers"], "query": "Which shoes are waterproof?", "top_n": 2, "model": "rerank-english-v3.0" } +``` + +后处理函数从模型响应中提取相关性分数。预测 API 响应为 `text_docs` 中的每个字符串包含一个分数,顺序相同: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "similarity", + "data_type": "FLOAT32", + "shape": [1], + "data": [0.9] + }, + { + "name": "similarity", + "data_type": "FLOAT32", + "shape": [1], + "data": [0.6] + } + ], + "status_code": 200 + } + ] +} +``` + +有关重排序搜索结果的更多信息,请参见[重排序搜索结果](/search-plugins/search-relevance/reranking-search-results)。 + +## 内置预处理和后处理函数 + +预处理函数将 `text_docs` 输入或文本相似性输入转换为填充连接器请求体模板的参数。后处理函数将模型响应转换为 OpenSearch 所需的格式。要使用内置函数,请在连接器 `actions` 数组元素的 `pre_process_function` 或 `post_process_function` 字段中指定其名称。有关输入格式的更多信息,请参见[输入格式](#input-formats)。 + +如果输入是 `text_docs` 且连接器未定义预处理函数,OpenSearch 使用 `connector.pre_process.default.embedding` 函数。文本相似性输入需要预处理函数。如果输入是 `parameters` 对象,OpenSearch 使用对象中的值填充请求体模板。 + +下表列出了内置预处理函数。 + +| 函数 | 用于 | 输入 | 返回的参数 | +| :--- | :--- | :--- | :--- | +| `connector.pre_process.default.embedding` | Amazon SageMaker 模型或其他接受字符串数组的嵌入模型 | `text_docs` | 返回包含 `text_docs` 数组的 `input` 参数。 | +| `connector.pre_process.openai.embedding` | OpenAI 和 Azure OpenAI 嵌入模型 | `text_docs` | 返回包含 `text_docs` 数组的 `input` 参数。 | +| `connector.pre_process.cohere.embedding` | Cohere Embed 模型,包括 Amazon Bedrock 中的 Cohere Embed 模型 | `text_docs` | 返回包含 `text_docs` 数组的 `texts` 参数。 | +| `connector.pre_process.cohere.multimodal_embedding` | Cohere Embed 模型,用于图像输入 | 包含图像数据 URI 的 `text_docs` | 返回包含 `text_docs` 数组的 `images` 参数。 | +| `connector.pre_process.bedrock.embedding` | Amazon Bedrock 中的 Amazon Titan Text Embeddings 模型 | `text_docs` | 返回包含 `text_docs` 中第一个字符串的 `inputText` 参数。 | +| `connector.pre_process.bedrock.multimodal_embedding` | Amazon Bedrock 中的 Amazon Titan Multimodal Embeddings | 包含文本(可选后跟图像)的 `text_docs` | 返回包含 `text_docs` 中第一个字符串的 `inputText` 参数,如果 `text_docs` 包含第二个字符串,则返回包含该字符串的 `inputImage` 参数。 | +| `connector.pre_process.bedrock.nova.embedding` | Amazon Bedrock 中的 Amazon Nova Multimodal Embeddings | `text_docs`,其中第一个字符串是纯文本或包含 `text`、`image`、`video` 或 `audio` 字段的 JSON 对象 | 返回包含匹配字段值的 `text`、`image`、`video` 或 `audio` 参数。纯文本输入返回 `text` 参数。 | +| `connector.pre_process.bedrock.nova.text_embedding` | Amazon Bedrock 中的 Amazon Nova Multimodal Embeddings,用于文本输入 | `text_docs` | 返回包含 `text_docs` 中第一个字符串的 `inputText` 参数。 | +| `connector.pre_process.bedrock.nova.image_embedding` | Amazon Bedrock 中的 Amazon Nova Multimodal Embeddings,用于图像输入 | `text_docs` | 返回包含 `text_docs` 中第一个字符串的 `inputImage` 参数。 | +| `connector.pre_process.bedrock.nova.video_embedding` | Amazon Bedrock 中的 Amazon Nova Multimodal Embeddings,用于视频输入 | `text_docs` | 返回包含 `text_docs` 中第一个字符串的 `inputVideo` 参数。 | +| `connector.pre_process.bedrock.nova.audio_embedding` | Amazon Bedrock 中的 Amazon Nova Multimodal Embeddings,用于音频输入 | `text_docs` | 返回包含 `text_docs` 中第一个字符串的 `inputAudio` 参数。 | +| `connector.pre_process.default.rerank` | 接受查询、文档数组和要返回的结果数量的重排序模型,例如您在 Amazon SageMaker 上部署的模型 | `query_text` 和 `text_docs`(文本相似性输入,例如来自 `rerank` 搜索处理器) | 返回包含查询文本的 `query` 参数、包含 `text_docs` 数组的 `documents` 参数,以及包含 `text_docs` 中字符串数量的 `top_n` 参数。 | +| `connector.pre_process.cohere.rerank` | Cohere Rerank 模型 | `query_text` 和 `text_docs`(文本相似性输入,例如来自 `rerank` 搜索处理器) | 返回包含查询文本的 `query` 参数、包含 `text_docs` 数组的 `documents` 参数,以及包含 `text_docs` 中字符串数量的 `top_n` 参数。 | +| `connector.pre_process.bedrock.rerank` | 通过 Amazon Bedrock Rerank API 访问的重排序模型,例如 Amazon Rerank。有关示例,请参见[使用 Amazon Bedrock 模型重排序搜索结果](/tutorials/reranking/reranking-bedrock/)。 | `query_text` 和 `text_docs`(文本相似性输入,例如来自 `rerank` 搜索处理器) | 以 Amazon Bedrock Rerank API 格式返回 `queries`、`sources` 和 `numberOfResults` 参数。 | + +下表列出了内置后处理函数。对于每个函数,该表提供了包含嵌入或结果的模型响应字段的 JSON 路径。 + +| 函数 | 用于 | 响应字段(JSON 路径) | +| :--- | :--- | :--- | +| `connector.post_process.default.embedding` | Amazon SageMaker 模型或其他返回二维数组的嵌入模型 | `$[*]`:顶级数组的每个条目。 | +| `connector.post_process.openai.embedding` | OpenAI 和 Azure OpenAI 嵌入模型 | `$.data[*].embedding` | +| `connector.post_process.cohere.embedding` | Cohere Embed 模型,包括 Amazon Bedrock 中的 Cohere Embed 模型 | `$.embeddings` | +| `connector.post_process.cohere_v2.embedding.float` | 使用 v2 API 的 Cohere Embed 模型,用于 `float` 嵌入 | `$.embeddings.float` | +| `connector.post_process.cohere_v2.embedding.int8` | 使用 v2 API 的 Cohere Embed 模型,用于 `int8` 嵌入 | `$.embeddings.int8` | +| `connector.post_process.cohere_v2.embedding.uint8` | 使用 v2 API 的 Cohere Embed 模型,用于 `uint8` 嵌入 | `$.embeddings.uint8` | +| `connector.post_process.cohere_v2.embedding.binary` | 使用 v2 API 的 Cohere Embed 模型,用于 `binary` 嵌入 | `$.embeddings.binary` | +| `connector.post_process.cohere_v2.embedding.ubinary` | 使用 v2 API 的 Cohere Embed 模型,用于 `ubinary` 嵌入 | `$.embeddings.ubinary` | +| `connector.post_process.bedrock.embedding` | Amazon Bedrock 中的 Amazon Titan Text Embeddings V1 和 Amazon Titan Multimodal Embeddings | `$.embedding` | +| `connector.post_process.bedrock_v2.embedding.float` | Amazon Bedrock 中的 Amazon Titan Text Embeddings V2,用于 `float` 嵌入 | `$.embeddingsByType.float` | +| `connector.post_process.bedrock_v2.embedding.binary` | Amazon Bedrock 中的 Amazon Titan Text Embeddings V2,用于 `binary` 嵌入 | `$.embeddingsByType.binary` | +| `connector.post_process.bedrock.nova.embedding` | Amazon Bedrock 中的 Amazon Nova Multimodal Embeddings | `$.embeddings[*].embedding` | +| `connector.post_process.default.rerank` | 返回包含 `index` 和 `relevance_score` 的结果顶级数组的重排序模型,例如您在 Amazon SageMaker 上部署的模型 | `$[*]`:顶级数组的每个条目。预测 API 响应按输入文档的顺序为每个文档包含一个分数。 | +| `connector.post_process.cohere.rerank` | Cohere Rerank 模型 | `$.results` | +| `connector.post_process.bedrock.rerank` | 通过 Amazon Bedrock Rerank API 访问的重排序模型,例如 Amazon Rerank。有关示例,请参见[使用 Amazon Bedrock 模型重排序搜索结果](/tutorials/reranking/reranking-bedrock/)。 | `$.results` | +| `connector.post_process.mlcommons.passthrough` | 以预测 API 格式返回响应的端点,例如另一个 OpenSearch 集群中的 ML Commons 或 OpenSearch Agent Server。有关示例,请参见[在代理服务器中填充模板](/vector-search/ai-search/agentic-search/agentic-search-templates/agent-server/)。 | `$`:整个响应。如果响应包含 `inference_results` 数组,该函数返回数组中的 `output` 对象,因此预测 API 响应不会包含嵌套在另一个 `inference_results` 数组中的一个 `inference_results` 数组。 | + +## 默认嵌入函数 + +当您使用[语义搜索](/vector-search/ai-search/semantic-search/)时,OpenSearch 将文本发送到模型并需要返回嵌入。[OpenSearch 提供的预训练模型](/ml-commons-plugin/pretrained-models)接受并返回这些格式。但是,托管在外部平台上的模型可能期望不同的格式。例如,部署在 Amazon SageMaker 上的模型可能接受字符串数组并为每个字符串返回一个嵌入。默认嵌入函数 `connector.pre_process.default.embedding` 和 `connector.post_process.default.embedding` 在这些格式之间进行转换。 + +以下示例请求创建一个使用默认函数的 Amazon SageMaker 文本嵌入连接器。连接器未定义预处理函数,因此 OpenSearch 使用 `connector.pre_process.default.embedding`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Sagemaker text embedding connector", + "description": "The connector to Sagemaker", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<YOUR SAGEMAKER ACCESS KEY>", + "secret_key": "<YOUR SAGEMAKER SECRET KEY>", + "session_token": "<YOUR AWS SECURITY TOKEN>" + }, + "parameters": { + "region": "ap-northeast-1", + "service_name": "sagemaker" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://runtime.sagemaker.ap-northeast-1.amazonaws.com/endpoints/<endpoint_name>/invocations", + "headers": { + "content-type": "application/json" + }, + "post_process_function": "connector.post_process.default.embedding", + "request_body": "${parameters.input}" + } + ] +} +``` + +::: warning IMPORTANT +将 `request_body` 模板设置为 `${parameters.input}`,以便 OpenSearch 将字符串数组作为整个请求体发送。 +::: + +### 预处理函数 + +`connector.pre_process.default.embedding` 函数将 `text_docs` 输入转换为 `input` 参数。例如,以下输入包含两个字符串: + +```json +{ + "text_docs": ["hello", "world"] +} +``` + +该函数将此输入转换为以下参数: + +```json +{ + "parameters": { + "input": ["hello", "world"] + } +} +``` + +然后 `${parameters.input}` 请求体模板将列表发送到模型,因此模型输入格式必须是字符串列表,例如: + +```json +["hello", "world"] +``` + +### 后处理函数 + +`connector.post_process.default.embedding` 函数解析模型响应并将其转换为 OpenSearch 所需的嵌入格式。 + +远程文本嵌入模型输出必须是二维浮点数组,其中每个元素表示输入列表中一个字符串的嵌入。例如,以下二维数组对应于列表 `["hello", "world"]` 的嵌入: + +```json +[ + [ + -0.048237994, + -0.07612697, + ... + ], + [ + 0.32621247, + 0.02328475, + ... + ] +] +``` + +## 自定义预处理和后处理函数 + +如果内置函数不支持您的模型 API 的请求或响应格式,请将您自己的函数编写为 [Painless](/scripting/painless/) 脚本。 + +自定义预处理函数从 `params` 读取输入,例如 `params.text_docs`,并返回包含 `parameters` 对象的 JSON 字符串。`parameters` 对象中的值填充 `request_body` 模板。 + +自定义后处理函数从 `params` 读取模型响应。如果响应是 JSON 对象,`params` 包含其字段,例如 `params.embedding`。如果响应是 JSON 数组,`params.result` 包含该数组。该函数返回包含一个输出对象或输出对象数组的 JSON 字符串。每个输出对象包含一个 `name` 字段,以及用于嵌入的 `data_type`、`shape` 和 `data` 字段,或用于其他输出的 `dataAsMap` 对象。要转义插入到返回 JSON 中的字符串中的特殊字符,请调用内置的 `escape()` 函数。如果函数返回的字符串不是有效的 JSON,预测 API 响应将在 `dataAsMap.response` 中包含该字符串。 + +例如,以下预处理函数将 `text_docs` 中的第一个字符串发送到 `inputText` 参数中的 Amazon Bedrock Titan 嵌入模型: + +```js +StringBuilder builder = new StringBuilder(); +builder.append("\""); +String first = params.text_docs[0]; +builder.append(first); +builder.append("\""); +def parameters = "{" + "\"inputText\":" + builder + "}"; +return "{" + "\"parameters\":" + parameters + "}"; +``` + +以下后处理函数将模型响应的 `embedding` 字段转换为输出对象: + +```js +def name = "sentence_embedding"; +def dataType = "FLOAT32"; +if (params.embedding == null || params.embedding.length == 0) { + return params.message; +} +def shape = [params.embedding.length]; +def json = "{" + + "\"name\":\"" + name + "\"," + + "\"data_type\":\"" + dataType + "\"," + + "\"shape\":" + shape + "," + + "\"data\":" + params.embedding + + "}"; +return json; +``` + +要使用这些函数,请在连接器操作的 `pre_process_function` 和 `post_process_function` 字段中将每个脚本作为字符串提供: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Amazon Bedrock Connector: embedding", + "description": "The connector to the Bedrock Titan embedding model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "<YOUR AWS REGION>", + "service_name": "bedrock" + }, + "credential": { + "access_key": "<YOUR AWS ACCESS KEY>", + "secret_key": "<YOUR AWS SECRET KEY>", + "session_token": "<YOUR AWS SECURITY TOKEN>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-embed-text-v1/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{ \"inputText\": \"${parameters.inputText}\" }", + "pre_process_function": "\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\\"\");\n String first = params.text_docs[0];\n builder.append(first);\n builder.append(\"\\\"\");\n def parameters = \"{\" +\"\\\"inputText\\\":\" + builder + \"}\";\n return \"{\" +\"\\\"parameters\\\":\" + parameters + \"}\";", + "post_process_function": "\n def name = \"sentence_embedding\";\n def dataType = \"FLOAT32\";\n if (params.embedding == null || params.embedding.length == 0) {\n return params.message;\n }\n def shape = [params.embedding.length];\n def json = \"{\" +\n \"\\\"name\\\":\\\"\" + name + \"\\\",\" +\n \"\\\"data_type\\\":\\\"\" + dataType + \"\\\",\" +\n \"\\\"shape\\\":\" + shape + \",\" +\n \"\\\"data\\\":\" + params.embedding +\n \"}\";\n return json;\n " + } + ] +} +``` + +## 下一步 + +- 要为没有 OpenSearch 提供的蓝图的模型编写连接器定义,请参见[创建自定义蓝图](/ml-commons-plugin/remote-models/blueprints)。 +- 有关所有连接器字段的描述,请参见[创建连接器 API](/ml-commons-plugin/api/connector-apis/create-connector#request-body-fields)。 +- 有关所有预测 API 参数和请求字段,请参见[预测 API](/ml-commons-plugin/api/train-predict/predict)。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/dynamic-header-substitution.md b/i18n/zh/ml-commons-plugin/remote-models/dynamic-header-substitution.md new file mode 100644 index 00000000..c658265f --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/dynamic-header-substitution.md @@ -0,0 +1,110 @@ +--- +title: 动态标头替换 +--- + +# 动态标头替换 +<Badge type="tip" text="3.7 版本引入" /> + +默认情况下,连接器标头在连接器创建时解析一次。动态连接器标头允许您在标头值中使用 `${parameters.*}` 占位符,以便在预测时替换每个请求的值。这对于将请求范围的元数据(如事务 ID、关联 ID 或跟踪令牌)传递给外部托管的模型端点很有用。 + +## 配置动态标头 + +要配置动态标头,请在连接器的 `actions[].headers` 字段中使用 `${parameters.*}` 占位符定义标头。您可以选择在顶级 `parameters` 字段中为参数设置默认值。 + +以下示例使用占位符端点 `api.example.com`。连接器 URL 必须与 `plugins.ml_commons.trusted_connector_endpoints_regex` 中的模式匹配,因此请将端点替换为您的模型端点或将其添加到受信任的端点。有关更多信息,请参阅[添加受信任的端点](/ml-commons-plugin/remote-models/#adding-trusted-endpoints)。 + +要创建包含动态标头的连接器,请发送以下请求: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "My connector", + "description": "Connector with dynamic headers", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.example.com", + "request_id": "default-request-id" + }, + "credential": { + "api_key": "test-api-key" + }, + "actions": [{ + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/predict", + "headers": { + "Authorization": "${credential.api_key}", + "X-Test-Request-Id": "${parameters.request_id}" + }, + "request_body": "{ \"input\": \"${parameters.input}\" }" + }] +} +``` + +在预测时,在 `_predict` 请求的 `parameters` 字段中传递运行时值: + +```json +POST /_plugins/_ml/models/{model_id}/_predict +{ + "parameters": { + "request_id": "request-123", + "input": "hello world" + } +} +``` + +发送到远程端点的结果 HTTP 请求包括替换的标头: + +```json +POST https://api.example.com/predict +Authorization: test-api-key +X-Test-Request-Id: request-123 +``` + +如果未提供运行时值且未在连接器的 `parameters` 字段中设置默认值,则预测请求将被拒绝并返回 400 错误。要避免这种情况,请在连接器的 `parameters` 字段中为参数定义默认值。如果未提供运行时值,则使用默认值。 + +## 安全限制 + +以下标头不能包含 `${parameters.*}` 占位符。使用它们会在连接器创建或更新时返回 400 错误。请改用 `${credential.*}` 进行身份验证标头: + +- 凭证标头: + - `Authorization` + - `Proxy-Authorization` + - `Cookie` + - `X-API-Key` + - `X-Auth-Token` + - `X-Auth-Header` + +- IP 和主机欺骗标头: + - `Host` + - `X-Forwarded-Host` + - `X-Forwarded-Server` + - `X-Forwarded-For` + - `Forwarded` + - `X-Real-IP` + - `X-Client-IP` + - `CF-Connecting-IP` + - `True-Client-IP` + - `X-Originating-IP` + +## 运行时验证 + +在替换之前,OpenSearch 会转义 `_predict` 请求中参数值中的特殊字符。运行时值中的换行符作为两个字符 `\n` 到达标头,其他控制字符作为转义序列(如 `\u0001`)到达。以下值在替换时不转义: + +- `_predict` 请求的 `no_escape_params` 参数中列出的参数值 +- 有效的 JSON 对象或数组的值 +- 来自连接器的 `parameters` 字段的默认值 + +在预测时,在将请求发送到模型端点之前,会验证替换的标头值。标头未通过以下任何检查的预测请求将返回 400 错误: + +- 包含回车符 (`\r`)、换行符 (`\n`) 或其他控制字符(`0x00–0x1F`,制表符除外,以及 `0x7F`)的标头值将被拒绝,以防止 HTTP 响应拆分。由于运行时值已转义,这仅适用于在不转义的情况下替换的值。 +- 每个标头(包括其名称和值)不得超过 8 KB(8,192 个字符)。 +- 所有标头名称和值的组合大小不得超过 64 KB(65,536 个字符)。 + +大小限制适用于转义值,因此转义序列计入它们。例如,运行时值中的 `"` 字符计为两个字符 (`\"`)。 + +## 后续步骤 + +- 有关所有连接器字段的描述,请参阅[创建连接器 API](/ml-commons-plugin/api/connector-apis/create-connector#request-body-fields)。 +- 有关向连接器提供身份验证凭证的信息,请参阅[连接器身份验证](/ml-commons-plugin/remote-models/connector-authentication)中您平台协议的身份验证方法。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/google-cloud.md b/i18n/zh/ml-commons-plugin/remote-models/google-cloud.md new file mode 100644 index 00000000..f3ff6569 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/google-cloud.md @@ -0,0 +1,152 @@ +--- +title: Google Cloud 身份验证 +--- + +# Google Cloud 身份验证 +<Badge type="tip" text="3.9 版本引入" /> + +`google_cloud` 连接器协议使 OpenSearch 能够调用 Google Cloud Vertex AI 模型。OpenSearch 生成并刷新 Google Cloud OAuth 2.0 访问令牌,并向每个请求添加 `Authorization` 标头,因此您无需手动提供或轮换令牌。此协议是 AWS 服务的 [`aws_sigv4` 协议](/ml-commons-plugin/remote-models/aws-sigv4)的 Google Cloud 等效协议。 + +::: info NOTE +Google 已将 Vertex AI 重命名为 Gemini Enterprise Agent Platform。连接器调用的 API 端点(如 `aiplatform.googleapis.com`)未更改,因此现有连接器不需要修改。 +::: + +## 先决条件 + +在创建 `google_cloud` 连接器之前,请在您的 Google Cloud 项目中启用 Vertex AI,并准备服务帐户密钥或(对于托管在 Google Cloud 上的节点)工作负载身份。然后按照以下步骤配置集群设置: + +1. 启用 `google_cloud` 协议,该协议默认情况下处于禁用状态。要启用它,请将 `plugins.ml_commons.connector.vertexai_enabled` 集群设置设置为 `true`: + + ```json + PUT /_cluster/settings + { + "persistent": { + "plugins.ml_commons.connector.vertexai_enabled": true + } + } + ``` + +1. 如果您更改了 `plugins.ml_commons.trusted_connector_endpoints_regex` 设置或使用早于 3.10 的 OpenSearch 版本,请将 Vertex AI 主机添加到受信任的连接器端点。从 OpenSearch 3.10 开始,此设置的默认值包括 Vertex AI 主机。 + + 首先,检索当前列表: + + ```json + GET /_cluster/settings?include_defaults=true&filter_path=**.trusted_connector_endpoints_regex + ``` + + 然后通过附加 Vertex AI 模式来更新列表: + + ```json + PUT /_cluster/settings + { + "persistent": { + "plugins.ml_commons.trusted_connector_endpoints_regex": [ + "<every pattern from the preceding response>", + "^https://([a-z0-9][a-z0-9-]*-)?aiplatform\\.googleapis\\.com/.*$" + ] + } + } + ``` + + ::: danger WARNING + 新列表会覆盖现有列表。如果它只包含 Vertex AI 模式,则 OpenSearch 会阻止连接到其他提供商(如 Amazon Bedrock 或 OpenAI)。有关默认列表,请参阅[添加受信任的端点](/ml-commons-plugin/remote-models/#adding-trusted-endpoints)。 + ::: + +## 身份验证模式 + +`google_cloud` 协议支持两种身份验证模式。 + +### 服务帐户密钥模式 + +在 `credential` 对象中提供服务帐户的 `private_key` 和 `client_email`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Vertex AI Connector: Gemini", + "description": "Vertex AI Gemini generateContent connector", + "version": 1, + "protocol": "google_cloud", + "parameters": { + "project_id": "<project_id>", + "location": "us-central1", + "model": "gemini-2.5-flash", + "scopes": "https://www.googleapis.com/auth/cloud-platform" + }, + "credential": { + "private_key": "<private_key>", + "client_email": "<client_email>", + "token_uri": "https://oauth2.googleapis.com/token" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.location}-aiplatform.googleapis.com/v1/projects/${parameters.project_id}/locations/${parameters.location}/publishers/google/models/${parameters.model}:generateContent", + "headers": { + "Content-Type": "application/json" + }, + "request_body": "{\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":\"${parameters.prompt}\"}]}]}" + } + ] +} +``` + +### 应用程序默认凭证模式 + +在托管在 Google Cloud 上的节点上,使用应用程序默认凭证 (ADC) 或工作负载身份而不是服务帐户密钥。在 `parameters` 中将 `auth_mode` 设置为 `adc`,并省略 `credential` 对象: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Vertex AI Connector: Gemini (ADC)", + "description": "Vertex AI Gemini generateContent connector using ADC", + "version": 1, + "protocol": "google_cloud", + "parameters": { + "project_id": "<project_id>", + "location": "us-central1", + "model": "gemini-2.5-flash", + "auth_mode": "adc", + "scopes": "https://www.googleapis.com/auth/cloud-platform" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.location}-aiplatform.googleapis.com/v1/projects/${parameters.project_id}/locations/${parameters.location}/publishers/google/models/${parameters.model}:generateContent", + "headers": { + "Content-Type": "application/json" + }, + "request_body": "{\"contents\":[{\"role\":\"user\",\"parts\":[{\"text\":\"${parameters.prompt}\"}]}]}" + } + ] +} +``` + +仅在托管在 Google Cloud 上的节点上使用 ADC 模式。ADC 从节点环境解析凭证,这需要联系 Google Cloud 元数据服务器。服务帐户密钥和 ADC 模式是互斥的:如果在 ADC 模式下包含 `credential` 对象,则它不得包含 `private_key` 或 `client_email`。否则 OpenSearch 会拒绝连接器。 + +## 请求体字段 + +当 `protocol` 设置为 `google_cloud` 时,`credential` 对象支持以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:---|:---|:---|:---| +| `private_key` | String | 服务帐户密钥模式下必需 | 服务帐户的私钥。在 ADC 模式下省略。 | +| `client_email` | String | 服务帐户密钥模式下必需 | 服务帐户的客户端电子邮件。在 ADC 模式下省略。 | +| `token_uri` | String | 可选 | Google OAuth 2.0 令牌端点。默认值为 `https://oauth2.googleapis.com/token`。URL 必须使用 HTTPS,主机必须是 `oauth2.googleapis.com`,端口必须是 `443` 或省略。 | + +当 `protocol` 设置为 `google_cloud` 时,`parameters` 对象支持以下字段。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:---|:---|:---|:---| +| `project_id` | String | 必需 | 您的 Google Cloud 项目 ID。 | +| `location` | String | 必需 | Vertex AI 区域,例如 `us-central1`。 | +| `model` | String | 必需 | Vertex AI 模型 ID,例如 `gemini-2.5-flash`。 | +| `auth_mode` | String | 可选 | 设置为 `adc` 以使用应用程序默认凭证或工作负载身份。在服务帐户密钥模式下省略。 | +| `scopes` | String | 可选 | 要请求的 OAuth 2.0 范围。指定单个范围。默认值为 `https://www.googleapis.com/auth/cloud-platform`。 | + +## 后续步骤 + +- 要查找您的模型的蓝图(包括 Gemini、嵌入、流式传输和批量推理),请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)。 +- 要注册和部署使用此连接器的模型,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/guardrails.md b/i18n/zh/ml-commons-plugin/remote-models/guardrails.md new file mode 100644 index 00000000..ed28d876 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/guardrails.md @@ -0,0 +1,614 @@ +--- +title: 护栏 +--- + +# 配置模型护栏 +<Badge type="tip" text="2.13 版本引入" /> + +护栏可以引导大型语言模型 (LLM) 朝着期望的行为发展。它们充当过滤器,防止 LLM 生成有害或违反道德原则的输出,并促进更安全地使用 AI。护栏还会导致 LLM 产生更集中和相关的输出。 + +您可以使用以下方法为 LLM 配置护栏: +- 提供要在模型的输入或输出中禁止的单词列表。或者,您可以提供一个正则表达式,模型输入或输出将与之匹配。有关更多信息,请参阅[使用停用词和正则表达式验证输入/输出](#validating-inputoutput-using-stopwords-and-regex)。 +- 配置一个单独的 LLM,其目的是验证用户输入和 LLM 输出。 + +## 先决条件 + +在开始之前,请确保您已满足连接到外部托管模型的[先决条件](/ml-commons-plugin/remote-models/#prerequisites)。 + +## 使用停用词和正则表达式验证输入/输出 +<Badge type="tip" text="2.13 版本引入" /> + +验证用户输入和 LLM 输出的简单方法是提供一组禁用词(停用词)或用于验证的正则表达式。 + +### 步骤 1:创建护栏索引 + +首先,创建一个索引来存储排除的单词(_停用词_)。在索引设置中,指定一个 `title` 字段(将包含排除的单词)和一个 [percolator](/mappings/supported-field-types/percolator/) 类型的 `query` 字段。percolator 查询将用于匹配 LLM 输入或输出: + +```json +PUT /words0 +{ + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "query": { + "type": "percolator" + } + } + } +} +``` + +### 步骤 2:索引排除的单词或短语 + +接下来,索引一个查询字符串查询,该查询将用于匹配模型输入或输出中的排除单词: + +```json +PUT /words0/_doc/1?refresh +{ + "query": { + "query_string": { + "query": "title: blacklist" + } + } +} +``` + +```json +PUT /words0/_doc/2?refresh +{ + "query": { + "query_string": { + "query": "title: \"Master slave architecture\"" + } + } +} +``` + +有关更多查询字符串选项,请参阅[查询字符串查询](/query-dsl/full-text/query-string)。 + +### 步骤 3:注册模型组 + +要注册模型组,请发送以下请求: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "bedrock", + "description": "This is a public model group." +} +``` + +响应包含模型组 ID,您将使用它将模型注册到此模型组: + +```json +{ + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "status": "CREATED" +} +``` + +要了解有关模型组的更多信息,请参阅[模型访问控制](/ml-commons-plugin/model-access-control)。 + +### 步骤 4:创建连接器 + +现在您可以为模型创建连接器。在此示例中,您将创建一个连接到托管在 Amazon Bedrock 上的 Anthropic Claude 模型的连接器: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "BedRock test claude Connector", + "description": "The connector to BedRock service for claude model", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "anthropic_version": "bedrock-2023-05-31", + "endpoint": "bedrock.us-east-1.amazonaws.com", + "auth": "Sig_V4", + "content_type": "application/json", + "max_tokens": 8000, + "temperature": 0.0001, + "response_filter": "$.content[0].text" + }, + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" + } + ] +} +``` + +响应包含新创建的连接器的连接器 ID: + +```json +{ + "connector_id": "a1eMb4kBJ1eYAeTMAljY" +} +``` + +### 步骤 5:注册和部署带有护栏的模型 + +要注册外部托管的模型,请在以下请求中提供步骤 3 中的模型组 ID 和步骤 4 中的连接器 ID。要配置护栏,请包括 `guardrails` 对象: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Bedrock Claude Sonnet 4.6 model", + "function_name": "remote", + "model_group_id": "wlcnb4kBJ1eYAeTMHlV6", + "description": "test model", + "connector_id": "a1eMb4kBJ1eYAeTMAljY", + "guardrails": { + "type": "local_regex", + "input_guardrail": { + "stop_words": [ + { + "index_name": "words0", + "source_fields": [ + "title" + ] + } + ], + "regex": [ + ".*abort.*", + ".*kill.*" + ] + }, + "output_guardrail": { + "stop_words": [ + { + "index_name": "words0", + "source_fields": [ + "title" + ] + } + ], + "regex": [ + ".*abort.*", + ".*kill.*" + ] + } + } +} +``` + +有关更多信息,请参阅 [`guardrails` 参数](/ml-commons-plugin/api/model-apis/register-model#the-guardrails-parameter)。 + +OpenSearch 返回注册操作的任务 ID 和已注册模型的模型 ID: + +```json +{ + "task_id": "cVeMb4kBJ1eYAeTMFFgj", + "status": "CREATED", + "model_id": "cleMb4kBJ1eYAeTMFFg4" +} +``` + +要检查操作的状态,请向[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 提供任务 ID: + +```json +GET /_plugins/_ml/tasks/cVeMb4kBJ1eYAeTMFFgj +``` + +当操作完成时,状态更改为 `COMPLETED`: + +```json +{ + "model_id": "cleMb4kBJ1eYAeTMFFg4", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "n-72khvBTBi3bnIIR8FTTw" + ], + "create_time": 1689793851077, + "last_update_time": 1689793851101, + "is_async": false +} +``` + +### 步骤 6(可选):测试模型 + +为了演示如何应用护栏,首先运行不包含任何排除单词的预测操作: + +```json +POST /_plugins/_ml/models/p94dYo4BrXGpZpgPp98E/_predict +{ + "parameters": { + "prompt": "this is a test" + } +} +``` + +响应包含 LLM 答案: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "This is a response!\n\nYour message came through successfully. How can I help you today?" + } + } + ], + "status_code": 200 + } + ] +} +``` + +然后运行包含排除单词的预测操作: + +```json +POST /_plugins/_ml/models/p94dYo4BrXGpZpgPp98E/_predict +{ + "parameters": { + "prompt": "this is a test of Master slave architecture" + } +} +``` + +响应包含错误消息,因为护栏被触发: + +```json +{ + "error": { + "root_cause": [ + { + "type": "illegal_argument_exception", + "reason": "guardrails triggered for user input" + } + ], + "type": "illegal_argument_exception", + "reason": "guardrails triggered for user input" + }, + "status": 400 +} +``` + +当提示匹配提供的正则表达式时,也会触发护栏。 + +## 使用护栏模型验证输入/输出 +<Badge type="tip" text="2.15 版本引入" /> + +对于更高级的验证,您可以配置护栏模型 --- 一个单独的 LLM,其目的是验证用户输入和 LLM 输出。在此示例中,您将配置两个模型: +- 聊天模型:托管在 Amazon Bedrock 上的 Anthropic Claude 模型,其目的是与用户进行对话。 +- 护栏模型:OpenAI 模型,其目的是验证用户输入和 Anthropic Claude 输出。 + +### 步骤 1:为护栏模型创建连接器 + +首先,创建一个到 OpenAI 护栏模型的连接器。请注意,OpenAI 提示指示模型仅响应单词 `accept` 或 `reject`,具体取决于输入/输出是否可接受。此外,请求包含 `response_filter` 参数,该参数指定护栏模型将在其中提供验证结果的字段: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "openai", + "description": "openai", + "version": "1", + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "max_tokens": 7, + "temperature": 0, + "model": "gpt-4o-mini", + "prompt": "You are a helpful assistant and an expert judge of content quality. Your task is to identify whether the input string below contains content that may be malicious, violent, hateful, sexual, or political in nature. Your answer should consist of a single word, either reject or accept. If the input belongs to any of these categories, please write reject. Otherwise, write accept. \\n\\nHere is the input: ${parameters.question}. \\n\\nYour answer: ", + "response_filter": "$.choices[0].message.content" + }, + "credential": { + "openAI_key": "<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\": [{\"role\": \"user\", \"content\": \"${parameters.prompt}\"}], \"max_tokens\": ${parameters.max_tokens}, \"temperature\": ${parameters.temperature} }" + } + ] +} +``` + +响应包含在后续步骤中使用的连接器 ID: + +```json +{ + "connector_id": "j3JVDZABNFJeYR3IVPRz" +} +``` + +### 步骤 2:为护栏模型注册模型组 + +要为 OpenAI 护栏模型注册模型组,请发送以下请求: + +```json +POST /_plugins/_ml/model_groups/_register +{ + "name": "guardrail model group", + "description": "This is a guardrail model group." +} +``` + +响应包含用于将模型注册到此模型组的模型组 ID: + +```json +{ + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "status": "CREATED" +} +``` + +要了解有关模型组的更多信息,请参阅[模型访问控制](/ml-commons-plugin/model-access-control)。 + +### 步骤 3:注册和部署护栏模型 + +使用连接器 ID 和模型组 ID,注册和部署 OpenAI 护栏模型: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "openai guardrails model", + "function_name": "remote", + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "description": "guardrails test model", + "connector_id": "j3JVDZABNFJeYR3IVPRz" +} +``` + +OpenSearch 返回注册操作的任务 ID 和已注册模型的模型 ID: + +```json +{ + "task_id": "onJaDZABNFJeYR3I2fQ1", + "status": "CREATED", + "model_id": "o3JaDZABNFJeYR3I2fRV" +} +``` + +要检查操作的状态,请向[获取 ML 任务 API](/ml-commons-plugin/api/tasks-apis/get-task) 提供任务 ID: + +```json +GET /_plugins/_ml/tasks/onJaDZABNFJeYR3I2fQ1 +``` + +当操作完成时,状态更改为 `COMPLETED`: + +```json +{ + "model_id": "o3JaDZABNFJeYR3I2fRV", + "task_type": "REGISTER_MODEL", + "function_name": "REMOTE", + "state": "COMPLETED", + "worker_node": [ + "n-72khvBTBi3bnIIR8FTTw" + ], + "create_time": 1689793851077, + "last_update_time": 1689793851101, + "is_async": false +} +``` + +### 步骤 4(可选):测试护栏模型 + +您可以通过发送包含和不包含攻击性单词的请求来测试护栏模型用户输入验证。 + +首先,发送一个不包含攻击性单词的请求: + +```json +POST /_plugins/_ml/models/o3JaDZABNFJeYR3I2fRV/_predict +{ + "parameters": { + "question": "how many indices do i have in my cluster" + } +} +``` + +护栏模型接受前面的请求: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "accept" + } + } + ], + "status_code": 200 + } + ] +} +``` + +接下来,发送包含攻击性单词的请求: + +```json +POST /_plugins/_ml/models/o3JaDZABNFJeYR3I2fRV/_predict +{ + "parameters": { + "question": "how to rob a bank" + } +} +``` + +护栏模型拒绝前面的请求: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "reject" + } + } + ], + "status_code": 200 + } + ] +} +``` + +### 步骤 5:为聊天模型创建连接器 + +在此示例中,聊天模型将是托管在 Amazon Bedrock 上的 Anthropic Claude 模型。要为模型创建连接器,请发送以下请求。请注意,`response_filter` 参数指定护栏模型将在其中提供验证结果的字段: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "BedRock claude Connector", + "description": "BedRock claude Connector", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "bedrock", + "anthropic_version": "bedrock-2023-05-31", + "endpoint": "bedrock.us-east-1.amazonaws.com", + "auth": "Sig_V4", + "content_type": "application/json", + "max_tokens": 8000, + "temperature": 0.0001, + "response_filter": "$.content[0].text" + }, + "credential": { + "access_key": "<access_key>", + "secret_key": "<secret_key>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/invoke", + "headers": { + "content-type": "application/json", + "x-amz-content-sha256": "required" + }, + "request_body": "{\"messages\":[{\"role\":\"user\",\"content\":\"${parameters.prompt}\"}], \"max_tokens\":${parameters.max_tokens}, \"temperature\":${parameters.temperature}, \"anthropic_version\":\"${parameters.anthropic_version}\" }" + } + ] +} +``` + +响应包含在后续步骤中使用的连接器 ID: + +```json +{ + "connector_id": "xnJjDZABNFJeYR3IPvTO" +} +``` + +### 步骤 6:注册和部署带有护栏的聊天模型 + +要注册和部署 Anthropic Claude 聊天模型,请发送以下请求。请注意,`guardrails` 对象包含一个 `response_validation_regex` 参数,该参数指定仅在护栏模型响应单词 `accept` 的变体时才将输入/输出视为有效: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "Bedrock Claude Sonnet 4.6 model with openai guardrails model", + "function_name": "remote", + "model_group_id": "ppSmpo8Bi-GZ0tf1i7cD", + "description": "Bedrock Claude Sonnet 4.6 model with openai guardrails model", + "connector_id": "xnJjDZABNFJeYR3IPvTO", + "guardrails": { + "input_guardrail": { + "model_id": "o3JaDZABNFJeYR3I2fRV", + "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$" + }, + "output_guardrail": { + "model_id": "o3JaDZABNFJeYR3I2fRV", + "response_validation_regex": "^\\s*\"[Aa]ccept\"\\s*$" + }, + "type": "model" + } +} +``` + +OpenSearch 返回注册操作的任务 ID 和已注册模型的模型 ID: + +```json +{ + "task_id": "1nJnDZABNFJeYR3IvfRL", + "status": "CREATED", + "model_id": "43JqDZABNFJeYR3IQPQH" +} +``` + +### 步骤 7(可选):测试带有护栏的聊天模型 + +您可以通过发送包含和不包含攻击性单词的预测请求来测试带有护栏的 Anthropic Claude 聊天模型。 + +首先,发送一个不包含攻击性单词的请求: + +```json +POST /_plugins/_ml/models/43JqDZABNFJeYR3IQPQH/_predict +{ + "parameters": { + "prompt": "${parameters.question}", + "question": "hello" + } +} +``` + +OpenSearch 响应 LLM 答案: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": "Hello! How are you doing? Is there something I can help you with today?" + } + } + ], + "status_code": 200 + } + ] +} +``` + +接下来,发送包含攻击性单词的请求: + +```json +POST /_plugins/_ml/models/43JqDZABNFJeYR3IQPQH/_predict +{ + "parameters": { + "prompt": "${parameters.question}", + "question": "how to rob a bank" + } +} +``` + +OpenSearch 响应错误。 + +## 后续步骤 + +- 有关配置护栏的更多信息,请参阅 [`guardrails` 参数](/ml-commons-plugin/api/model-apis/register-model#the-guardrails-parameter)。 +- 有关演示如何使用 Amazon Bedrock 护栏的教程,请参阅 [Amazon Bedrock 模型护栏](/tutorials/gen-ai/model-controls/bedrock-guardrails/)。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/http-authentication.md b/i18n/zh/ml-commons-plugin/remote-models/http-authentication.md new file mode 100644 index 00000000..d74c8c4e --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/http-authentication.md @@ -0,0 +1,211 @@ +--- +title: HTTP 身份验证 +--- + +# HTTP 身份验证 + +使用 `http` 协议的连接器使用连接器的 `credential` 对象中的值对外部托管的模型进行身份验证。大多数端点接受令牌(如 API 密钥),连接器在请求标头中传递该令牌。需要双向 TLS (mTLS) 的端点接受客户端证书。 + +## 令牌身份验证 + +要使用令牌进行身份验证,请在 `credential` 对象中提供令牌,并使用 `${credential.*}` 占位符从请求标头引用它。字段名称是任意的 --- 您的平台的蓝图指定要使用的名称,例如 `openAI_key` 或 `cohere_key`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "OpenAI Chat Connector", + "description": "The connector to public OpenAI model service for gpt-4o-mini", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.openai.com", + "model": "gpt-4o-mini" + }, + "credential": { + "openAI_key": "<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} }" + } + ] +} +``` + +有关您的平台期望的令牌字段名称和标头格式,请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)中您的平台和模型的蓝图。 + +## 客户端证书身份验证 +<Badge type="tip" text="3.9 版本引入" /> + +客户端证书身份验证(也称为双向 TLS (mTLS))允许连接器在连接到外部托管的模型时提供客户端证书。连接的双方在 TLS 握手期间相互验证:端点使用服务器证书证明其身份,连接器使用客户端证书证明其身份。当模型端点需要客户端证书而不是在请求标头中传递的令牌时,请使用 mTLS。 + +要启用 mTLS,请在连接器的 `client_config` 对象中将 `mutual_tls_enabled` 设置为 `true`,并在连接器的 `credential` 对象中提供证书材料。 + +### 请求体字段 + +当 `mutual_tls_enabled` 设置为 `true` 时,`credential` 对象支持以下证书字段。提供证书内容本身,可以是将换行符转义为 `\n` 的 PEM 文本,也可以是 Base64 编码的内容;不支持文件路径。OpenSearch 以与任何其他凭证相同的方式加密这些字段,并使它们在每个节点上可用,因此您无需将证书文件复制到各个节点。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:---|:---|:---|:---| +| `client_cert_pem` | String | 当 `keystore_type` 为 `PEM` 时必需 | PEM 格式的客户端证书。要提供由中间证书颁发机构 (CA) 颁发的证书,请包括完整的链,首先按叶证书排序。 | +| `client_key_pem` | String | 当 `keystore_type` 为 `PEM` 时必需 | PEM 格式的客户端私钥。必须是未加密的 PKCS #8 密钥(`-----BEGIN PRIVATE KEY-----`);不支持 PKCS #1 密钥。 | +| `client_cert_pkcs12` | String | 当 `keystore_type` 为 `PKCS12` 时必需 | 包含客户端证书和私钥的 Base64 编码的 PKCS12 密钥库。 | +| `keystore_password` | String | 可选 | 保护 PKCS12 密钥库的密码。对于没有密码的密钥库,请省略它。 | +| `ca_cert_pem` | String | 可选 | PEM 格式的一个或多个 CA 证书,用于验证端点的服务器证书。接受中间证书和根证书的捆绑包。如果省略,则使用 Java 默认信任库。当端点使用私有 CA 时提供此字段。 | + +`mutual_tls_enabled` 和 `keystore_type` 字段属于连接器的 `client_config` 对象。有关两者的描述,请参阅 [client_config 对象](/ml-commons-plugin/api/connector-apis/create-connector#the-client_config-object)。 + +### 先决条件 + +在配置 mTLS 之前,请确保满足以下要求: + +- 在集群上启用客户端证书身份验证。它默认情况下处于禁用状态,将 `mutual_tls_enabled` 设置为 `true` 的连接器请求将被拒绝并返回 `403` 错误,直到您启用它。要启用它,请将 `plugins.ml_commons.connector.mutual_tls_enabled` 集群设置设置为 `true`: + + ```json + PUT /_cluster/settings + { + "persistent": { + "plugins.ml_commons.connector.mutual_tls_enabled": true + } + } + ``` + +- 连接器使用 `http` 协议。有关更多信息,请参阅[限制](#restrictions)。 +- 端点 URL 与受信任的端点匹配。有关更多信息,请参阅[添加受信任的端点](/ml-commons-plugin/remote-models/#adding-trusted-endpoints)。 +- PEM 格式的私钥未加密且使用 PKCS #8 编码(`-----BEGIN PRIVATE KEY-----`)。不支持 PKCS #1 密钥(`-----BEGIN RSA PRIVATE KEY-----`)。要将 PKCS #1 密钥转换为 PKCS #8,请使用以下命令: + +```bash +openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in rsa_key.pem -out pkcs8_key.pem +``` + +Base64 编码的 PEM 值会自动检测和解码。由于 Base64 编码避免了手动转义换行符,因此它是多行证书的更方便选项。要对证书或密钥进行 Base64 编码,请使用以下命令: + +```bash +base64 -i client-cert.pem +``` + +### 使用 PEM 证书 + +要使用 PEM 证书和私钥进行身份验证,请将 `keystore_type` 设置为 `PEM` 并提供 `client_cert_pem` 和 `client_key_pem`: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Externally hosted model connector with mutual TLS", + "description": "A connector that authenticates using a client certificate", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.example.com" + }, + "credential": { + "client_cert_pem": "<BASE64-ENCODED CLIENT CERTIFICATE>", + "client_key_pem": "<BASE64-ENCODED PRIVATE KEY>", + "ca_cert_pem": "<BASE64-ENCODED CA CERTIFICATE>" + }, + "client_config": { + "mutual_tls_enabled": true, + "keystore_type": "PEM" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/predict", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"input\": \"${parameters.input}\" }" + } + ] +} +``` + +::: info NOTE +由于 `PEM` 是默认值,因此在使用 PEM 证书时可以省略 `keystore_type`。 +::: + +### 使用 PKCS12 密钥库 + +要使用 PKCS12 密钥库进行身份验证,请将 `keystore_type` 设置为 `PKCS12` 并在 `client_cert_pkcs12` 中提供 Base64 编码的密钥库。PKCS12 密钥库是二进制的,因此必须始终进行 Base64 编码: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Externally hosted model connector with a PKCS12 keystore", + "description": "A connector that authenticates using a client certificate", + "version": 1, + "protocol": "http", + "parameters": { + "endpoint": "api.example.com" + }, + "credential": { + "client_cert_pkcs12": "<BASE64-ENCODED PKCS12 KEYSTORE>", + "keystore_password": "<KEYSTORE PASSWORD>", + "ca_cert_pem": "<BASE64-ENCODED CA CERTIFICATE>" + }, + "client_config": { + "mutual_tls_enabled": true, + "keystore_type": "PKCS12" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "https://${parameters.endpoint}/predict", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"input\": \"${parameters.input}\" }" + } + ] +} +``` + +要从现有的 PEM 证书和密钥创建 PKCS12 密钥库并对其进行 Base64 编码,请使用以下命令: + +```bash +openssl pkcs12 -export -in client-cert.pem -inkey client-key.pem -out client.p12 -name client +base64 -i client.p12 +``` + +### 证书链和自定义 CA 证书 + +如果您的客户端证书由中间证书颁发机构 (CA) 颁发,请在 `client_cert_pem` 中包含完整的链。首先按叶排序链,然后是每个颁发的中间证书,以便每个证书由其后面的证书颁发。错序的链将被拒绝,并显示标识所涉及证书的错误。 + +`ca_cert_pem` 字段是可选的,它控制如何验证端点的服务器证书: + +- 如果您提供 `ca_cert_pem`,OpenSearch 仅根据它包含的证书验证服务器证书。该字段接受捆绑包,因此您可以包括中间证书和根证书。当端点使用私有 CA 时提供此字段。 +- 如果省略 `ca_cert_pem`,OpenSearch 将根据 Java 默认信任库验证服务器证书。 + +::: warning IMPORTANT +由于私有 CA 通常不存在于默认信任库中,请提供 `ca_cert_pem` 而不是将 `skip_ssl_verification` 设置为 `true`。启用 mTLS 时会拒绝跳过验证。 +::: + +### 轮换证书 + +要轮换即将到期的证书,请在更新请求中发送新的证书材料,如[更新连接器凭证](/ml-commons-plugin/remote-models/connectors#updating-connector-credentials)中所述。您无需取消部署模型或重新启动任何节点。 + +OpenSearch 检测到更改并为后续预测请求构建新的 HTTP 客户端。被替换的客户端在宽限期后关闭,因此已在进行中的请求针对先前的证书完成。 + +### 限制 + +以下限制适用于客户端证书身份验证: + +- mTLS 仅适用于使用 `http` 协议的连接器,不适用于流式请求。创建使用另一个协议(如 `aws_sigv4`)且 `mutual_tls_enabled` 设置为 `true` 的连接器会返回 `400` 错误。 +- `skip_ssl_verification` 和 `mutual_tls_enabled` 不能都设置为 `true`。禁用服务器证书验证会删除双向 TLS 的双向部分,因此请提供 `ca_cert_pem` 以根据私有 CA 验证服务器证书。 +- 启用 mTLS 时,`credential` 对象不能包含 `api_key`。OpenSearch 强制执行仅证书身份验证并拒绝混合身份验证方法。 +- 证书字段不支持文件路径。提供证书内容本身。 +- 证书材料以及前面的 `skip_ssl_verification` 和 `api_key` 限制在第一个预测请求时验证。具有无效证书配置的连接器已成功创建,并在首次使用时失败。 + +## 后续步骤 + +- 要查找您的平台和模型的蓝图,请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors)。 +- 要注册和部署使用此连接器的模型,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 +- 有关所有连接器字段(包括 `client_config` 对象)的描述,请参阅[创建连接器 API](/ml-commons-plugin/api/connector-apis/create-connector#request-body-fields)。 diff --git a/i18n/zh/ml-commons-plugin/remote-models/supported-connectors.md b/i18n/zh/ml-commons-plugin/remote-models/supported-connectors.md new file mode 100644 index 00000000..5d356ff9 --- /dev/null +++ b/i18n/zh/ml-commons-plugin/remote-models/supported-connectors.md @@ -0,0 +1,84 @@ +--- +title: OpenSearch 提供的连接器蓝图 +--- + +# OpenSearch 提供的连接器蓝图 + +OpenSearch 提供两种类型的连接器蓝图: + +- **标准蓝图(建议用于 OpenSearch 2.14+)**: + + - 专为将输入直接传递给模型并返回其原始输出而无需额外转换的连接器而设计。 + - 使用没有任何预处理或后处理函数的已注册模型。 + - 与机器学习 (ML) 推理处理器兼容:[摄取处理器](/ingest-pipelines/processors/ml-inference)、[搜索请求处理器](/search-plugins/search-pipelines/ml-inference-search-request)和[搜索响应处理器](/search-plugins/search-pipelines/ml-inference-search-response)。 + - 适用于 OpenSearch 2.14 及更高版本中的新实现。 + +- **传统蓝图**: + + - 适用于特定的输入和输出格式要求。 + - 包括预处理和后处理函数。 + - 建议用于现有实现。 + - 与[语义搜索](/vector-search/ai-search/semantic-search/)兼容。 + +## 查找您的模型和平台 + +OpenSearch 为以下平台和模型提供连接器蓝图。每个蓝图链接都提供了创建连接器的示例请求(包括所有必需参数)和示例预测 API 请求。**协议**列链接到该平台身份验证方法的凭证字段和集群先决条件。有关可用协议的概述,请参阅[连接器身份验证](/ml-commons-plugin/remote-models/connector-authentication)。 + +| 平台 | 模型 | 协议 | 传统蓝图 | 标准蓝图 | +|:-------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [Aleph Alpha](https://aleph-alpha.com/) | [Luminous-Base 嵌入模型](https://docs.aleph-alpha.com/products/pharia-ai/pharia-os/references/inference/endpoints/semantic_embed/) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/aleph_alpha_connector_luminous_base_embedding_blueprint.md) | N/A | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [AI21 Labs Jurassic-2 Mid](https://aws.amazon.com/bedrock/jurassic/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_ai21labs_jurassic_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v2](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v3](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v3.7](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3.7_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude3.7_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Anthropic Claude v4](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude4_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_anthropic_claude4_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Cohere Embed 模型 v3 - 英语](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-embed.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_cohere_cohere.embed-english-v3_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_cohere_cohere.embed-english-v3_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Cohere Embed 模型 v3 - 多语言](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-embed.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_cohere_cohere.embed-multilingual-v3_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_cohere_cohere.embed-multilingual-v3_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Titan 文本嵌入](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_titan_embedding_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_titan_embedding_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Titan 多模态嵌入](https://docs.aws.amazon.com/bedrock/latest/userguide/titan-multiemb-models.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_titan_multimodal_embedding_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/bedrock_connector_titan_multimodal_embedding_standard_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [Nova 多模态嵌入](https://docs.aws.amazon.com/nova/latest/userguide/modalities.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_nova_multimodal_model_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_nova_multimodal_model_blueprint.md) | +| [Amazon Bedrock](https://aws.amazon.com/bedrock/) | [OpenAI GPT-OSS](https://aws.amazon.com/bedrock/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_openai_gpt-oss_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_openai_gpt-oss_blueprint.md) | +| [Amazon Bedrock Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) | [Anthropic Claude 3 Sonnet](https://aws.amazon.com/bedrock/claude/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_converse_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/bedrock_connector_converse_blueprint.md) | +| [Amazon Comprehend](https://aws.amazon.com/comprehend/) | [元数据嵌入模型](https://docs.aws.amazon.com/comprehend/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_comprehend_connector_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_comprehend_connector_blueprint.md) | +| [Amazon Textract](https://aws.amazon.com/textract/) | [Amazon Textract 模型](https://docs.aws.amazon.com/textract/) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_textract_connector_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/amazon_textract_connector_blueprint.md) | +| [Amazon SageMaker](https://aws.amazon.com/sagemaker/) | [批量推理的文本嵌入模型](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_sagemaker_connector_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_sagemaker_connector_blueprint.md) | +| [Amazon SageMaker](https://aws.amazon.com/sagemaker/) | [文本嵌入模型](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/sagemaker_connector_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/sagemaker_connector_blueprint.md) | +| [Amazon SageMaker](https://aws.amazon.com/sagemaker/) | [语义高亮器模型](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | N/A | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/sagemaker_semantic_highlighter_standard_blueprint.md) | +| [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) | [聊天模型](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=global-standard%2Cstandard-chat-completions#gpt-4)(例如 `gpt-4`) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/azure_openai_connector_chat_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/azure_openai_connector_chat_blueprint.md) | +| [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service) | [文本嵌入模型](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings)(例如 `text-embedding-ada-002`) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/azure_openai_connector_embedding_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/azure_openai_connector_embedding_standard_blueprint.md) | +| [Cohere](https://cohere.com/) | [聊天模型](https://docs.cohere.com/reference/chat) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_chat_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_chat_blueprint.md) | +| [Cohere](https://cohere.com/) | [多模态嵌入模型](https://docs.cohere.com/reference/embed)(例如 `embed-english-v3.0`) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_image_embedding_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/cohere_connector_image_embedding_standard_blueprint.md) | +| [Cohere](https://cohere.com/) | [文本嵌入模型](https://docs.cohere.com/reference/embed) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/cohere_connector_embedding_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/cohere_connector_text_embedding_standard_blueprint.md) | +| [DeepSeek](https://www.deepseek.com/) | [聊天模型](https://api-docs.deepseek.com/api/create-chat-completion) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/deepseek_connector_chat_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/deepseek_connector_chat_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI Gemini](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini) | [`google_cloud`](/ml-commons-plugin/remote-models/google-cloud) | N/A | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_gemini_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI 文本嵌入](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings) | [`google_cloud`](/ml-commons-plugin/remote-models/google-cloud) | N/A | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_embedding_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI 文本嵌入](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings)(手动刷新令牌) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | N/A | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_connector_embedding_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI Gemini 流式传输](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini) | [`google_cloud`](/ml-commons-plugin/remote-models/google-cloud) | N/A | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_streaming_blueprint.md) | +| [Google Cloud](https://cloud.google.com/) | [Vertex AI 批量推理](https://cloud.google.com/vertex-ai/docs/predictions/get-batch-predictions) | [`google_cloud`](/ml-commons-plugin/remote-models/google-cloud) | N/A | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/gcp_vertexai_batch_blueprint.md) | +| [Ollama](https://ollama.ai/) | [聊天模型](https://ollama.ai/library) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/ollama_connector_chat_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/ollama_connector_chat_blueprint.md) | +| [OpenAI](https://openai.com/) | [聊天模型](https://platform.openai.com/docs/models)(例如 `gpt-4o-mini`) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_chat_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_chat_blueprint.md) | +| [OpenAI](https://openai.com/) | [完成模型](https://platform.openai.com/docs/models)(传统;OpenAI 已停用 `/v1/completions` 端点) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_completion_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/open_ai_connector_completion_blueprint.md) | +| [OpenAI](https://openai.com/) | [文本嵌入模型](https://platform.openai.com/docs/models#embeddings)(例如 `text-embedding-ada-002`) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/openai_connector_embedding_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/openai_connector_embedding_standard_blueprint.md) | +| [OpenAI](https://openai.com/) | [批量推理的文本嵌入模型](https://platform.openai.com/docs/guides/batch/overview#model-availability) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_openAI_connector_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/batch_inference_openAI_connector_blueprint.md) | +| [Yandex Cloud](https://yandex.cloud/en) | [文本嵌入模型](https://yandex.cloud/en/docs/ai-studio/concepts/embeddings) | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/yandexcloud_connector_embedding_legacy_blueprint.md) | [蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/standard_blueprints/yandexcloud_connector_embedding_standard_blueprint.md) | + +## 搜索相关性工作台的 LLM 判断蓝图 + +[搜索相关性工作台](/search-plugins/search-relevance/using-search-relevance-workbench)使用聊天模型使用 LLM-as-a-Judge 生成相关性评级。有关这些蓝图的概述,请参阅 [LLM 判断蓝图](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/README.md)。下表列出了用于将搜索相关性工作台连接到聊天模型的可用蓝图。 + +| 提供商 | 协议 | 蓝图 | +|:---|:---|:---| +| OpenAI | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [GPT-5、GPT-4.1、GPT-4o](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/openai_chat_blueprint.md) | +| Azure OpenAI | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [GPT-5、GPT-4.1、GPT-4o](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/azure_openai_chat_blueprint.md) | +| DeepSeek | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [DeepSeek-V3、DeepSeek-R1](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/deepseek_chat_blueprint.md) | +| Ollama 和其他本地 OpenAI 兼容服务器 | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [Qwen 3、Llama 3.3、Mistral、Phi-4、Gemma 3](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/ollama_chat_blueprint.md) | +| Google Gemini | [`http`](/ml-commons-plugin/remote-models/http-authentication) | [Gemini 2.5 Pro、Gemini 2.5 Flash](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/google_gemini_chat_blueprint.md) | +| Amazon Bedrock | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [Anthropic Claude(原生 `invoke` API)](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/anthropic_claude_bedrock_blueprint.md) | +| Amazon Bedrock Converse | [`aws_sigv4`](/ml-commons-plugin/remote-models/aws-sigv4) | [Anthropic Claude、Amazon Nova、Meta Llama、Mistral、AI21、Cohere](https://github.com/opensearch-project/ml-commons/blob/main/docs/remote_inference_blueprints/llm_judgment/bedrock_converse_blueprint.md) | + +有关将这些蓝图与搜索相关性工作台一起使用的更多信息,请参阅[使用不同的 LLM 提供商](/search-plugins/search-relevance/judgments#using-different-llm-providers)。 + +## 后续步骤 + +- 要注册和部署使用您的连接器的模型,请参阅[连接到外部托管的模型](/ml-commons-plugin/remote-models/)。 +- 要为没有提供蓝图的平台或模型创建连接器,请参阅[创建自定义蓝图](/ml-commons-plugin/remote-models/blueprints)。 diff --git a/i18n/zh/observing-your-data/ad/detector-access-control.md b/i18n/zh/observing-your-data/ad/detector-access-control.md new file mode 100644 index 00000000..8682bbef --- /dev/null +++ b/i18n/zh/observing-your-data/ad/detector-access-control.md @@ -0,0 +1,136 @@ +--- +title: 异常检测器访问控制 +--- + +# 异常检测器访问控制 + +异常检测与安全插件的资源共享和访问控制框架集成,为异常检测器资源提供文档级授权。这取代了旧版的 `plugins.anomaly_detection.filter_by_backend_roles` 设置,采用更灵活的共享系统,允许资源所有者向用户、角色或后端角色授予特定访问级别。 + +有关预定义的异常检测角色和权限,请参阅[异常检测安全](/observing-your-data/ad/security)。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +下表描述了异常检测器资源配置。 + +| 字段 | 值 | +| :--- | :--- | +| 资源类型 | `anomaly-detector` | +| 系统索引 | `.opendistro-anomaly-detectors` | +| 加入版本 | OpenSearch 3.3 | + +当为异常检测器启用资源级授权时,每个检测器的可见性由中央共享记录管理。资源所有者和具有共享能力的用户可以为特定用户、角色或后端角色授予或撤销访问权限。 + +## 启用异常检测器资源共享 + +要为异常检测器启用资源共享,您必须将 anomaly-detector 资源类型添加到受保护类型列表中,并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员:这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 `opensearch.yml` 配置文件以启用异常检测器的资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "anomaly-detector" +``` + +### 使用集群设置 API 配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["anomaly-detector"] + } +} +``` + +::: info NOTE +在向现有配置添加 anomaly-detector 资源类型时,请在 `protected_types` 数组中包含所有先前配置的资源类型。 +::: + +## 异常检测器访问级别 + +异常检测为异常检测器文档提供三个预定义的访问级别。这些访问级别决定了被授予检测器资源访问权限的用户可获得的特定权限。 + +### ad_read_only + +`ad_read_only` 只读访问级别授予用户查看和搜索共享异常检测器的能力,但不能修改它们。此访问级别包括以下权限: + +```yaml +- 'cluster:admin/opendistro/ad/detector/info' +- 'cluster:admin/opendistro/ad/detector/validate' +- 'cluster:admin/opendistro/ad/detector/preview' +- 'cluster:admin/opendistro/ad/detectors/get' +- 'cluster:admin/opendistro/ad/result/topAnomalies' +``` + +### ad_read_write + +`ad_read_write` 读写访问级别授予用户对异常检测器操作的完全访问权限,但共享能力除外。此访问级别包括所有读取权限以及写入操作: + +```yaml +- "cluster:admin/opendistro/ad/*" +- 'cluster:monitor/*' +- "cluster:admin/ingest/pipeline/delete" +- "cluster:admin/ingest/pipeline/put" +``` + +### ad_full_access + +`ad_full_access` 完全访问级别授予用户对异常检测器的完全控制权,包括类似所有者的权限,如与其他用户共享资源。此访问级别包括所有异常检测器操作以及资源共享权限: + +```yaml +- "cluster:admin/ingest/pipeline/delete" +- "cluster:admin/ingest/pipeline/put" +- "cluster:admin/opendistro/ad/*" +- 'cluster:monitor/*' +- "cluster:admin/security/resource/share" +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在[异常检测 GitHub 仓库](https://github.com/opensearch-project/anomaly-detection/)中创建问题。 +::: + +## 从旧版框架迁移 + +启用资源共享并将异常检测器标记为受保护的资源类型后,集群管理员必须运行迁移 API,将现有检测器共享信息从旧版框架传输到新的资源共享系统。 + +::: warning IMPORTANT +仅限管理员:迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +使用以下 API 调用将旧版异常检测器共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-anomaly-detectors", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "anomaly-detector": "<select-appropriate-access-level>" + } +} +``` + +将 `<replace-with-existing-user>` 替换为应拥有没有明确所有权信息的异常检测器的现有用户的用户名。将 `<select-appropriate-access-level>` 替换为可用的异常检测器访问级别之一:`ad_read_only`、`ad_read_write` 或 `ad_full_access`。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于程序化管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流和用户指南 diff --git a/i18n/zh/observing-your-data/ad/managing-anomalies.md b/i18n/zh/observing-your-data/ad/managing-anomalies.md new file mode 100644 index 00000000..9ad61daf --- /dev/null +++ b/i18n/zh/observing-your-data/ad/managing-anomalies.md @@ -0,0 +1,186 @@ +--- +title: 配置异常告警 +--- + +# 配置异常告警 + +创建[异常检测器](/observing-your-data/ad/)后,您可以配置告警以便在异常发生时收到通知。要配置告警,请创建一个[告警监控器](/observing-your-data/alerting/),如下图所示。有关如何创建告警监控器的说明,请参阅[创建告警监控器](/observing-your-data/alerting/#creating-an-alert-monitor)。 + +*告警编辑器* + +在**监控器定义方法**中,选择以下方法之一来定义您的监控器: + +- **异常检测器**:用于监控单个检测器的结果,对异常等级和置信度设置阈值。 +- **提取查询编辑器**:用于监控多个检测器、编写复杂查询或创建高级触发器条件。 + +## 告警监控器示例 + +以下监控器专为高基数检测器设计。您可以修改调度、查询和聚合以匹配您的特定用例: + +```json +{ + "name": "ad-monitor", + "type": "monitor", + "monitor_type": "query_level_monitor", + "enabled": true, + "schedule": { + "period": { + "unit": "MINUTES", + "interval": 2 + } + }, + "inputs": [ + { + "search": { + "indices": [ + ".opendistro-anomaly-results*" + ], + "query": { + "size": 1, + "sort": [ + { + "anomaly_grade": "desc" + }, + { + "confidence": "desc" + } + ], + "query": { + "bool": { + "filter": [ + { + "range": { + "execution_end_time": { + "from": "{{period_end}}||-2m", + "to": "{{period_end}}", + "include_lower": true, + "include_upper": true + } + } + }, + { + "term": { + "detector_id": { + "value": "oJzeoZkB8KmRTvydzJDF" + } + } + } + ] + } + }, + "aggregations": { + "max_anomaly_grade": { + "max": { + "field": "anomaly_grade" + } + } + } + } + } + } + ], + "triggers": [ + { + "query_level_trigger": { + "id": "i5zuoZkB8KmRTvydn5Hg", + "name": "ad-trigger", + "severity": "1", + "condition": { + "script": { + "source": "return ctx.results != null && ctx.results.length > 0 && ctx.results[0].aggregations != null && ctx.results[0].aggregations.max_anomaly_grade != null && ctx.results[0].hits.total.value > 0 && ctx.results[0].hits.hits[0]._source != null && ctx.results[0].hits.hits[0]._source.confidence != null && ctx.results[0].aggregations.max_anomaly_grade.value != null && ctx.results[0].aggregations.max_anomaly_grade.value > 0.7 && ctx.results[0].hits.hits[0]._source.confidence > 0.7", + "lang": "painless" + } + }, + "actions": [ + { + "id": "notification606448", + "name": "ad-action", + "destination_id": "fpzsoZkB8KmRTvydkZGQ", + "message_template": { + "source": "Monitor **{{ctx.monitor.name}}** entered **ALERT** state — please investigate.\n\nTrigger : {{ctx.trigger.name}}\nSeverity : {{ctx.trigger.severity}}\nTime range : {{ctx.periodStart}} → {{ctx.periodEnd}} UTC\n\nEntity\n{{#ctx.results.0.hits.hits.0._source.entity}}\n • {{name}} = {{value}}\n{{/ctx.results.0.hits.hits.0._source.entity}}\n", + "lang": "mustache" + }, + "throttle_enabled": true, + "subject_template": { + "source": "Alerting Notification action", + "lang": "mustache" + }, + "throttle": { + "value": 2, + "unit": "MINUTES" + } + } + ] + } + } + ], + "ui_metadata": { + "schedule": { + "timezone": null, + "frequency": "interval", + "period": { + "unit": "MINUTES", + "interval": 2 + }, + "daily": 0, + "weekly": { + "tue": false, + "wed": false, + "thur": false, + "sat": false, + "fri": false, + "mon": false, + "sun": false + }, + "monthly": { + "type": "day", + "day": 1 + }, + "cronExpression": "0 */2 * * *" + }, + "monitor_type": "query_level_monitor", + "search": { + "searchType": "ad", + "timeField": "", + "aggregations": [], + "groupBy": [], + "bucketValue": 1, + "bucketUnitOfTime": "h", + "filters": [] + } + } +} +``` + +注意示例告警监控器中的以下关键配置: + +- 搜索输入中的 **`"size": 1`**:检索单个文档,以便您可以在通知中引用 `ctx.results.0.hits.hits.0` 来识别触发告警的实体(例如 `host` 或 `service`)。 + +- **`execution_end_time` 范围 `"{{period_end}}||-2m"` → `"{{period_end}}"`**:根据检测器的 `execution_end_time` 过滤结果——即检测器完成运行并索引结果的时间。由于 OpenSearch 以近实时方式运行(结果不是即时的),索引和刷新操作会在文档变得可搜索之前引入延迟。为了考虑这种写入到搜索的延迟,此示例包含一个小的重叠时间(`-2m`)。根据您系统的最坏情况延迟指定重叠时间。避免使用 `data_end_time`(桶的逻辑结束时间),因为这可能会错过稍后到达的结果。 + +- **`"indices": [".opendistro-anomaly-results*"]`**:匹配默认结果索引模式。如果您将结果路由到自定义索引(如 `opensearch-ad-plugin-result-abc*`),请更新此模式。 + +- **`"detector_id": {"value": "oJzeoZkB8KmRTvydzJDF"}`**(可选):使用此过滤器定位特定检测器,避免匹配来自其他检测器的不相关异常。 + +- **`"max_anomaly_grade"` 聚合**:检测时间窗口中最严重的异常。您可以使用异常结果索引中的任何字段进行聚合。有关其他字段,请参阅[异常结果映射](/observing-your-data/ad/result-mapping)。 + +- **每 2 分钟的监控器调度**:每 2 分钟评估一次结果以快速检测异常。结合 2 分钟的告警节流,这可以避免同一事件的重复通知。 + +- **触发器条件 `max_anomaly_grade.value > 0.7 && confidence > 0.7`**:设置适当的阈值,可靠地指示异常。根据您对误报和漏报的容忍度调整这些值。 + +- **带有实体块的 Mustache 模板**:在通知中显示单维度(`host=server_3`)和多维度(`host=server_3`、`service=auth`)实体值。您还可以包含指向预过滤仪表板的链接,以加快故障分类。 + +## 告警通知示例 + +以下示例显示了当异常超过定义阈值时监控器生成的示例告警电子邮件。在这种情况下,监控器正在跟踪高基数检测器,并为特定实体(`host = server_3`)触发了告警: + +```md +Monitor **ad-monitor** entered **ALERT** state — please investigate. + +Trigger : ad-trigger +Severity : 1 +Time range : 2025-10-01T23:42:33.699Z → 2025-10-01T23:44:33.699Z UTC + +Entity + • host = server_3 +``` diff --git a/i18n/zh/observing-your-data/agent-traces/agent-tracing.md b/i18n/zh/observing-your-data/agent-traces/agent-tracing.md new file mode 100644 index 00000000..8e09a93a --- /dev/null +++ b/i18n/zh/observing-your-data/agent-traces/agent-tracing.md @@ -0,0 +1,167 @@ +--- +title: 查看代理追踪 +--- + +# 查看代理追踪 +<Badge type="tip" text="3.6 版本引入" /> + +OpenSearch Dashboards 中的**代理追踪**页面允许您探索、调试和监控大语言模型(LLM)代理执行追踪。您可以在多个同步可视化中查看追踪、检查 span 详细信息,并分析代理 AI 应用的指标。 + +## 启用代理追踪 + +代理追踪功能包含在默认的 OpenSearch 发行版中。要启用代理追踪,请将以下功能标志添加到您的 `opensearch_dashboards.yml` 配置文件中: + +```yaml +workspace.enabled: true +explore.enabled: true +explore.agentTraces.enabled: true +``` + +更新配置后,重新启动 OpenSearch Dashboards 以使更改生效。 + +::: info NOTE +默认的 OpenSearch 发行版默认启用 [PPL](/search-plugins/sql/ppl/) 查询支持。如果您运行的是最小发行版的 OpenSearch,请在使用代理追踪之前[安装 SQL 插件](/install-and-configure/plugins)。 +::: + +## 理解追踪和 span + +在代理追踪中,**追踪**代表完整的执行流程(例如单个代理调用),而 **span** 代表该追踪中的各个操作(例如 LLM 调用、工具执行或检索操作)。每个追踪由一个或多个以父子层次结构组织的 span 组成。 + +### Span 类别 + +代理追踪根据 `gen_ai.operation.name` 属性将 span 分类。每个类别在**代理追踪**页面中都有不同的颜色和图标。 + +| 类别 | 操作名称 | 描述 | +| :--- | :--- | :--- | +| Agent | `invoke_agent`、`create_agent` | 代理调用和初始化。 | +| LLM | `chat`、`text_completion`、`generate_content` | LLM 聊天完成、文本完成和内容生成请求。 | +| Tool | `execute_tool` | 工具和函数调用。 | +| Embeddings | `embeddings` | 嵌入生成请求。 | +| Retrieval | `retrieval` | 文档或数据检索操作。 | +| Other | 未映射的操作 | 不匹配已知类别的操作。 | + +### Span 属性 + +当您使用 [`opensearch-genai-observability-sdk-py` SDK](/observing-your-data/agent-traces/instrument) 检测应用时,会自动创建具有所需属性的 span。下表列出了核心 OpenTelemetry 属性和生成式 AI 语义约定属性。 + +#### 核心属性 + +下表列出了核心 OpenTelemetry 属性。 + +| 属性 | 必需 | 描述 | +| :--- | :--- | :--- | +| `traceId` | 是 | 追踪的唯一标识符。 | +| `spanId` | 是 | span 的唯一标识符。 | +| `parentSpanId` | 否 | 父 span 的标识符。对于根 span 为空。 | +| `startTime` | 是 | span 开始时间戳。 | +| `endTime` | 是 | span 结束时间戳。 | +| `durationInNanos` | 是 | span 持续时间,以纳秒为单位。 | +| `status.code` | 是 | span 状态代码。有效值为 `OK`(成功)、`ERROR`(失败)或 `UNSET`(未显式设置时的默认状态)。 | + +#### 生成式 AI 属性 + +下表列出了生成式 AI 语义约定属性。 + +| 属性 | 必需 | 描述 | +| :--- | :--- | :--- | +| `gen_ai.operation.name` | 是 | 操作类型。有效值为 `chat`、`invoke_agent`、`execute_tool`、`create_agent`、`text_completion`、`embeddings` 或 `retrieval`。用于 span 分类、过滤和选项卡查询。 | +| `gen_ai.provider.name` | 是 | 生成式 AI 提供商名称(例如 `openai`、`anthropic`)。 | +| `gen_ai.agent.name` | 可选 | GenAI 代理的人类可读名称。 | +| `gen_ai.request.model` | 可选 | 请求发送到的模型名称。 | +| `gen_ai.usage.input_tokens` | 可选 | 消耗的输入令牌数。 | +| `gen_ai.usage.output_tokens` | 可选 | 生成的输出令牌数。 | +| `gen_ai.input.messages` | 可选 | 作为模型输入提供的聊天历史或提示。 | +| `gen_ai.output.messages` | 可选 | 模型返回的消息或完成。 | +| `gen_ai.tool.name` | 可选 | 代理使用的工具名称。仅适用于 `execute_tool` 操作 span。 | +| `gen_ai.tool.call.id` | 可选 | 工具调用标识符。仅适用于 `execute_tool` 操作 span。 | + +## 数据管道 + +代理追踪遵循以下数据管道: + +1. 经过检测的 LLM 应用通过 gRPC 或 HTTP 发送 OpenTelemetry Protocol (OTLP) 数据。 +2. OpenTelemetry Collector 处理和路由数据。 +3. [Data Prepper](/data-prepper/) 使用 `otel_trace_raw` 处理器将数据摄取到 OpenSearch。 +4. OpenSearch 将追踪数据存储在 `otel-v1-apm-span-*` 索引中。 +5. OpenSearch Dashboards 在**代理追踪**页面中显示追踪。 + +## 使用界面 + +要访问代理追踪,在您的可观测性工作区中,在左侧导航中选择**代理监控** > **追踪**或**代理监控** > **Span**。两者都会打开**代理追踪**页面,分别位于**追踪**选项卡或 **Span** 选项卡上。 + +**代理追踪**页面包括以下组件。 + +### 追踪选项卡 + +追踪选项卡在分页表中显示根级追踪。您可以展开一行以内联查看子 span。 + +下图显示了追踪选项卡。 + +*显示根级代理追踪的追踪选项卡* + +### Span 选项卡 + +Span 选项卡显示所有生成式 AI span,而不仅仅是根追踪。使用此选项卡可检查多个追踪中的各个操作。该表包含与[追踪选项卡](#追踪选项卡)相同的列。 + +下图显示了 Span 选项卡。 + +*显示所有生成式 AI span 的 Span 选项卡* + +## 追踪详细信息 + +在追踪或 Span 选项卡中选择一行以打开追踪详细信息。追踪详细信息提供三个同步可视化视图和一个 span 详细信息面板。在任何视图中选择一个 span 都会在所有三个视图中突出显示它。 + +### 代理图 + +代理图使用 Dagre 布局算法将追踪呈现为有向无环图 (DAG)。父 span 向下流向子 span,兄弟 span 水平排列。 + +下图显示了代理图视图。 + +*显示 DAG 可视化的代理图* + +图中的每个节点包括以下元素: + +- 指示 span 类别(例如 Agent、LLM 或 Tool)的颜色编码徽章。 +- span 名称,截断为 37 个字符。 +- 显示 span 持续时间占总追踪时间百分比的条形图。 +- 对于状态为 `ERROR` 的 span 显示的红色徽章。 + +代理图提供以下控件: + +- 将缩放从 0.1x 调整到 2x。 +- 重置视口以显示所有节点。 + +选择一个节点以在 span 详细信息面板中查看其详细信息。选择背景以取消选择节点。 + +### 追踪树视图 + +追踪树视图在可展开的层次结构中显示所有 span。每行显示以下信息: + +- 颜色编码的 span 类别。 +- 操作名称。 +- 操作消耗的令牌数。 +- span 持续时间。 + +展开或折叠节点以导航父子关系。 + +下图显示了追踪树视图。 + +*显示层次 span 结构的追踪树视图* + +### 时间线视图 + +时间线视图呈现一个甘特图样式的图表,按时间顺序显示 span 持续时间。每个 span 显示为具有以下特征的水平条: + +- 条形宽度对应于 span 持续时间。 +- 条形颜色与 span 类别颜色匹配。 +- 缩进反映 span 层次深度。 + +重叠的条形指示并发操作。使用此视图可识别瓶颈并了解代理的顺序和并行执行模式。 + +下图显示了时间线视图。 + +*显示甘特图样式 span 图表的时间线视图* + +### Span 详细信息面板 + +右侧面板显示有关所选 span 的详细信息,包括所有 JSON 属性和执行时间。 diff --git a/i18n/zh/observing-your-data/agent-traces/index.md b/i18n/zh/observing-your-data/agent-traces/index.md new file mode 100644 index 00000000..27ad2ab4 --- /dev/null +++ b/i18n/zh/observing-your-data/agent-traces/index.md @@ -0,0 +1,45 @@ +--- +title: 代理监控 +--- + +# 代理监控 +<Badge type="tip" text="3.6 版本引入" /> + +代理监控为生成式 AI 应用和大语言模型(LLM)代理提供可观测性。它使用代理追踪,记录 LLM 调用、令牌使用、工具调用和代理推理流程,遵循 OpenTelemetry [生成式 AI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)。 + +## 前提条件 + +代理监控需要以下组件: + +- OpenSearch 集群,将追踪数据存储在 `otel-v1-apm-span-*` 索引中。 +- OpenSearch Dashboards 配备可观测性工作区,并将 `explore.enabled` 和 `explore.agentTraces.enabled` 设置设为 `true`。有关更多信息,请参阅[可观测性工作区应用](/observing-your-data/exploring-observability-data/)。 +- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)。 +- [OpenSearch Data Prepper](/data-prepper/),处理追踪数据并将其写入 OpenSearch。 +- 使用 OpenTelemetry [生成式 AI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)检测的应用。有关更多信息,请参阅[检测您的应用](/observing-your-data/agent-traces/instrument)。 + +## 代理追踪工作流 + +代理追踪工作流包括以下阶段: + +1. **检测**:为您的 AI 应用添加可观测性: + - 使用 [GenAI SDK](https://observability.opensearch.org/docs/send-data/ai-agents/),其中包含装饰器、增强函数和自动 LLM 检测,支持 OpenAI、Anthropic、Amazon Bedrock 和 LangChain 等库。 + +2. **规范化**:OpenTelemetry Collector 使用[生成式 AI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)标准化 span,确保跨提供商的属性名称一致。 + +3. **使用本地工具**(可选):在开发期间使用 [Agent Health](https://observability.opensearch.org/docs/agent-health/) 进行本地调试、评分和评估。 + +4. **处理**:[OpenSearch Data Prepper](/data-prepper/) 将 OpenTelemetry Protocol (OTLP) 数据路由到 OpenSearch,创建服务地图、关联追踪和聚合指标。 + +5. **查看**:[OpenSearch Dashboards](/observing-your-data/agent-traces/agent-tracing) 将代理追踪显示为层次树、有向无环图 (DAG) 和时间线,以及用于生产监控的指标。 + +代理追踪支持以下框架和提供商: + +- **框架**:Strands Agents、LangGraph、CrewAI 和 OpenAI Agents SDK。 +- **提供商**:OpenAI、Anthropic、Amazon Bedrock、LangChain、LlamaIndex 和其他 LLM 提供商。 + +## 入门 + +要开始使用代理追踪,请探索以下主题: + +- [检测您的应用](/observing-your-data/agent-traces/instrument) -- 安装 SDK 并为您的 AI 代理添加追踪。 +- [查看代理追踪](/observing-your-data/agent-traces/agent-tracing) -- 在 OpenSearch Dashboards 中配置和探索代理追踪。 diff --git a/i18n/zh/observing-your-data/agent-traces/instrument.md b/i18n/zh/observing-your-data/agent-traces/instrument.md new file mode 100644 index 00000000..7476487d --- /dev/null +++ b/i18n/zh/observing-your-data/agent-traces/instrument.md @@ -0,0 +1,181 @@ +--- +title: 检测您的应用 +--- + +# 检测您的应用 +<Badge type="tip" text="3.6 版本引入" /> + +`opensearch-genai-observability-sdk-py` 包使用 [OpenTelemetry](https://opentelemetry.io/) 检测 Python AI 代理。SDK 提供两种检测方法: + +- **自动检测**:自动捕获受支持提供商(OpenAI、Anthropic、Amazon Bedrock、LangChain、LlamaIndex)的 LLM 调用,无需代码更改。 +- **手动检测**:使用 `@observe` 装饰器追踪自定义代理逻辑、工具调用和编排代码。 + +对于大多数应用,结合两种方法:为 LLM 调用启用自动检测,并为特定于应用的操作使用 `@observe`。 + +## 前提条件 + +在开始之前,请确保您具有以下内容: + +- Python 3.10 或更高版本。 +- 配置了用于追踪摄取的 [Data Prepper](/data-prepper/) 的 OpenSearch 集群。 +- 用于使用生成式 AI 语义约定规范化 span 的 [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)。 + +## 安装 + +安装基础包: + +```bash +pip install opensearch-genai-observability-sdk-py +``` + +要为特定提供商启用自动检测,请安装相应的可选依赖项。例如,要检测 OpenAI 和 LangChain: + +```bash +pip install opensearch-genai-observability-sdk-py[openai,langchain] +``` + +以下提供商支持自动检测: + +| 提供商 | 包名称 | +| :--- | :--- | +| OpenAI | `openai` | +| Anthropic | `anthropic` | +| Amazon Bedrock | `bedrock` | +| Google | `google` | +| LangChain | `langchain` | +| LlamaIndex | `llamaindex` | + +## 核心 API + +以下部分描述了核心 API 函数。 + +<!-- vale off --> +### register() +<!-- vale on --> + +`register()` 函数配置 OpenTelemetry 追踪器和导出器。在应用启动时调用一次: + +```python +from opentelemetry_genai_sdk import register + +register( + endpoint="http://localhost:4318", + service_name="my-agent-app", + protocol="http", + auto_instrument=True +) +``` + +下表描述了 `register()` 参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `endpoint` | String | OpenTelemetry Protocol (OTLP) 端点 URL。默认为 OpenTelemetry Collector 的 `http://localhost:4318`。 | +| `service_name` | String | 追踪数据中应用的标识符。 | +| `protocol` | String | 传输协议。有效值为 `http` 和 `grpc`。 | +| `auto_instrument` | Boolean | 当为 `true` 时,自动发现并启用已安装的提供商检测包。默认为 `false`。 | + +<!-- vale off --> +### @observe 装饰器 +<!-- vale on --> + +`@observe` 装饰器包装函数以自动创建 span。使用它追踪代理调用、工具调用和其他操作: + +```python +from opentelemetry_genai_sdk import observe, Op + +@observe(op=Op.INVOKE_AGENT) +def run_agent(prompt: str): + # 代理逻辑 + return response + +@observe(op=Op.EXECUTE_TOOL) +def search_database(query: str): + # 工具逻辑 + return results +``` + +装饰器支持同步函数、异步函数、生成器和异步生成器。Span 名称从函数名称自动生成,或者您可以使用 `name_from` 参数提供自定义名称。 + +<!-- vale off --> +### enrich() +<!-- vale on --> + +`enrich()` 函数向活动 span 添加 GenAI 语义属性: + +```python +from opentelemetry_genai_sdk import enrich + +enrich( + model="gpt-4o-mini", + provider="openai", + input_tokens=150, + output_tokens=50, + finish_reason="stop" +) +``` + +<!-- vale off --> +### score() +<!-- vale on --> + +`score()` 函数将评估指标附加到追踪或单个 span: + +```python +from opentelemetry_genai_sdk import score + +score( + trace_id="abc123", + name="relevance", + value=0.95, + explanation="Response directly addresses the query" +) +``` + +## 操作类型 + +`Op` 类提供标准化的操作名称,映射到 [GenAI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)。这些操作类型决定了 span 在**代理追踪**页面中的分类和显示方式。 + +| 操作 | 常量 | 描述 | +| :--- | :--- | :--- | +| 调用代理 | `Op.INVOKE_AGENT` | 根级代理调用。 | +| 执行工具 | `Op.EXECUTE_TOOL` | 代理内的工具或函数调用。 | +| 聊天 | `Op.CHAT` | LLM 聊天完成请求。 | +| 创建代理 | `Op.CREATE_AGENT` | 代理初始化。 | +| 检索 | `Op.RETRIEVAL` | 文档或数据检索操作。 | +| 嵌入 | `Op.EMBEDDINGS` | 嵌入生成请求。 | +| 文本完成 | `Op.TEXT_COMPLETION` | 文本完成请求。 | + +## 框架集成 + +SDK 与流行的代理框架集成。通用模式是将自动检测(用于 LLM 调用)与手动 `@observe` 装饰器(用于特定于代理的逻辑)结合使用。 + +### Strands Agents + +Strands 支持两种方法: +- **原生 OpenTelemetry**:使用 `StrandsTelemetry` 自动为代理调用、工具执行和 LLM 交互发出 span。 +- **手动装饰**:在自定义函数上使用 `@observe` 进行额外检测。 + +### LangGraph + +使用 `@observe` 包装 LangGraph 节点和编排层。启用自动检测以自动捕获节点内的模型调用。 + +<!-- vale off --> +### CrewAI +<!-- vale on --> + +使用 `@observe` 包装 crew 执行函数。安装适当的提供商包(例如 `[openai]`)以自动捕获 crew 成员进行的 LLM 调用。 + +<!-- vale off --> +### OpenAI Agents SDK +<!-- vale on --> + +启用自动检测以实现全面的 LLM 覆盖。使用 `@observe` 补充顶层协调逻辑和自定义操作。 + +### Amazon Bedrock + +安装 `[bedrock]` 以自动捕获 `converse` 和 `invoke_model` 调用。对代理编排和自定义工具实现使用 `@observe`。 + +## 下一步 + +检测应用后,配置 OpenSearch Dashboards 以查看您的追踪。有关配置和可视化选项,请参阅[查看代理追踪](/observing-your-data/agent-traces/agent-tracing)。 diff --git a/i18n/zh/observing-your-data/alerting/alerting-access-control.md b/i18n/zh/observing-your-data/alerting/alerting-access-control.md new file mode 100644 index 00000000..70c00d8f --- /dev/null +++ b/i18n/zh/observing-your-data/alerting/alerting-access-control.md @@ -0,0 +1,151 @@ +--- +title: 告警资源访问控制 +--- + +# 告警资源访问控制 + +告警与安全插件的资源共享和访问控制框架集成,为监控器和工作流提供文档级授权。这取代了旧版的 `plugins.alerting.filter_by_backend_roles` 设置,采用更灵活的共享系统,允许资源所有者向用户、角色或后端角色授予特定访问级别。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +告警注册两种资源类型,都存储在同一个配置索引中。下表描述了告警资源配置。 + +| 资源类型 | 系统索引 | 加入版本 | +| :--- | :--- | :--- | +| `monitor` | `.opendistro-alerting-config` | OpenSearch 3.8 | +| `alerting-workflow` | `.opendistro-alerting-config` | OpenSearch 3.8 | + +工作流资源类型命名为 `alerting-workflow`,以避免与 Flow Framework 插件注册的 `workflow` 资源类型名称冲突。由于两种告警类型共享 `.opendistro-alerting-config` 索引,框架通过每个文档中的字段来区分它们。 + +当启用资源级授权时,每个监控器和工作流的可见性由中央共享记录管理。资源所有者和具有共享能力的用户可以为特定用户、角色或后端角色授予或撤销访问权限。 + +告警和评论从属于它们的监控器。它们不是注册的资源类型,因此对它们的访问派生自对产生它们的监控器的访问。可以访问监控器的用户可以读取其告警。添加评论需要具有读写或完全访问级别的监控器访问权限。 + +## 启用告警资源共享 + +要为告警启用资源共享,请将告警资源类型添加到受保护类型列表中,并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员:这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 `opensearch.yml` 配置文件以启用告警的资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "monitor" + - "alerting-workflow" +``` + +### 使用集群设置 API 配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["monitor", "alerting-workflow"] + } +} +``` + +::: info NOTE +在向现有配置添加告警资源类型时,请在 `protected_types` 数组中包含所有先前配置的资源类型。 +::: + +## 告警访问级别 + +告警提供三个预定义的访问级别,适用于 `monitor` 和 `alerting-workflow` 资源类型。这些访问级别决定了被授予监控器或工作流资源访问权限的用户可获得的特定权限。 + +### alerting_read_only + +`alerting_read_only` 只读访问级别授予用户查看和搜索共享监控器、工作流及其告警的能力,但不能修改它们。此访问级别包括以下权限: + +```yaml +- 'cluster:admin/opendistro/alerting/monitor/get' +- 'cluster:admin/opendistro/alerting/monitor/search' +- 'cluster:admin/opendistro/alerting/alerts/get' +- 'cluster:admin/opensearch/alerting/workflow/get' +- 'cluster:admin/opensearch/alerting/workflow_alerts/get' +- 'cluster:admin/opensearch/alerting/findings/get' +- 'cluster:admin/opendistro/alerting/destination/get' +``` + +### alerting_read_write + +`alerting_read_write` 读写访问级别授予用户对监控器和工作流操作(包括告警和评论)的完全访问权限,但共享能力除外。此访问级别包括所有读取权限以及写入操作: + +```yaml +- 'cluster:admin/opendistro/alerting/monitor/*' +- 'cluster:admin/opensearch/alerting/workflow/*' +- 'cluster:admin/opendistro/alerting/alerts/*' +- 'cluster:admin/opensearch/alerting/workflow_alerts/*' +- 'cluster:admin/opensearch/alerting/findings/*' +- 'cluster:admin/opendistro/alerting/destination/*' +- 'cluster:admin/opensearch/alerting/comments/*' +``` + +### alerting_full_access + +`alerting_full_access` 完全访问级别授予用户对监控器或工作流的完全控制权,包括类似所有者的权限,如与其他用户共享资源。此访问级别包括所有读写权限以及远程索引和资源共享权限: + +```yaml +- 'cluster:admin/opendistro/alerting/monitor/*' +- 'cluster:admin/opensearch/alerting/workflow/*' +- 'cluster:admin/opendistro/alerting/alerts/*' +- 'cluster:admin/opensearch/alerting/workflow_alerts/*' +- 'cluster:admin/opensearch/alerting/findings/*' +- 'cluster:admin/opendistro/alerting/destination/*' +- 'cluster:admin/opensearch/alerting/comments/*' +- 'cluster:admin/opensearch/alerting/remote/indexes/get' +- 'cluster:admin/security/resource/share' +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在[告警 GitHub 仓库](https://github.com/opensearch-project/alerting/)中创建问题。 +::: + +## 从旧版框架迁移 + +启用资源共享并将告警资源类型标记为受保护后,集群管理员必须运行迁移 API,将现有监控器和工作流共享信息从旧版框架传输到新的资源共享系统。 + +::: warning IMPORTANT +仅限管理员:迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +两种告警资源类型存储在同一个索引中,但在不同路径下保留所有者信息(`monitor.user` 和 `workflow.user`)。告警在其资源提供程序上声明这些按类型的路径,因此框架为每个文档从正确的路径读取所有者。请求级别的 `username_path` 和 `backend_roles_path` 参数仍然是必需的,并用作回退。 + +使用以下 API 调用将旧版告警共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opendistro-alerting-config", + "username_path": "/monitor/user/name", + "backend_roles_path": "/monitor/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "monitor": "<select-appropriate-access-level>", + "alerting-workflow": "<select-appropriate-access-level>" + } +} +``` + +将 `<replace-with-existing-user>` 替换为应拥有没有明确所有权信息的监控器和工作流的现有用户的用户名。将 `<select-appropriate-access-level>` 替换为可用的告警访问级别之一:`alerting_read_only`、`alerting_read_write` 或 `alerting_full_access`。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于程序化管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流和用户指南 +- [告警安全](/observing-your-data/alerting/security) -- 内置告警角色和旧版后端角色过滤 diff --git a/i18n/zh/observing-your-data/alerting/comments.md b/i18n/zh/observing-your-data/alerting/comments.md new file mode 100644 index 00000000..f27b68d9 --- /dev/null +++ b/i18n/zh/observing-your-data/alerting/comments.md @@ -0,0 +1,17 @@ +--- +title: 添加评论 +--- + +# 添加告警评论 + +当生成告警时,添加评论以共享有关其根本原因的信息并促进解决。通过使用 [`cluster/settings` API](/observing-your-data/alerting/settings) 将 `plugins.alerting.comments_enabled` 设置为 `true` 来启用评论。 + +可以通过在告警行中选择评论图标,从告警表视图访问评论。从那里,可以添加、编辑或删除评论。还提供告警评论 API 用于程序化评论管理。有关更多信息,请参阅[告警 API](/observing-your-data/alerting/api)。 + +## 查看评论作者 + +如果安装了安全插件,则显示评论的作者。否则,显示 `Unknown`。 + +## 分配权限 + +评论权限由与告警关联的后端角色决定。这些后端角色从生成告警的监控器继承。有关如何根据后端角色限制访问的更多信息,请参阅[按后端角色限制访问](/observing-your-data/alerting/security#advanced-limit-access-by-backend-role)。 diff --git a/i18n/zh/observing-your-data/alerting/composite-monitors-api.md b/i18n/zh/observing-your-data/alerting/composite-monitors-api.md new file mode 100644 index 00000000..ed9849e2 --- /dev/null +++ b/i18n/zh/observing-your-data/alerting/composite-monitors-api.md @@ -0,0 +1,558 @@ +--- +title: 复合监控器 API +--- + +# 复合监控器 API + +使用复合监控器 API 创建和管理[复合监控器](/observing-your-data/alerting/composite-monitors)及其链式告警。在 API 中,复合监控器称为 _workflow_(工作流),其 ID 为 workflow ID。 + +## 创建复合监控器 + +创建一个复合监控器。 + +### 端点 + +```json +POST _plugins/_alerting/workflows +``` + +### 请求正文字段 + +下表列出了可用的请求正文字段。 + +字段 | 数据类型 | 必需 | 描述 +:--- | :--- | :--- | :--- +`name` | String | 必需 | 复合监控器的名称。 +`workflow_type` | String | 必需 | 设置为 `composite`。 +`schedule` | Object | 必需 | 复合监控器的运行频率。请参阅 [`schedule` 对象](#the-schedule-object)。 +`inputs` | Array | 必需 | 委托监控器及其运行顺序。请参阅 [`inputs` 数组](#the-inputs-array)。 +`triggers` | Array | 可选 | 生成链式告警的触发器。请参阅 [`triggers` 数组](#the-triggers-array)。 +`enabled` | Boolean | 可选 | 复合监控器是否启用。默认值为 `true`。 + +### `schedule` 对象 + +`schedule` 对象包含 `period` 对象,该对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`interval` | Integer | 运行之间的时间单位数。 +`unit` | String | 间隔的时间单位。有效值为 `MINUTES`、`HOURS` 和 `DAYS`。 + +### `inputs` 数组 + +`inputs` 数组包含一个带有 `composite_input.sequence.delegates` 数组的对象。`delegates` 数组中的每个对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`order` | Integer | 委托监控器在序列中的位置。委托监控器按升序运行。 +`monitor_id` | String | 委托监控器的 ID。复合监控器支持按查询、按桶和按文档监控器作为委托监控器。 + +### `triggers` 数组 + +`triggers` 数组中的每个对象包含一个 `chained_alert_trigger` 对象,该对象包含以下字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`id` | String | 触发器 ID。 +`name` | String | 触发器名称。 +`severity` | String | 告警严重性,从 `1`(最高)到 `5`(最低)。 +`condition` | Object | 触发器条件。包含一个 `script` 对象,其中 `source` 是生成链式告警的 Painless 条件,`lang` 是 `painless`。请参阅[定义链式告警触发器条件](#defining-chained-alert-trigger-conditions)。 +`actions` | Array | 满足触发器条件时执行的操作。有关操作字段,请参阅[操作](/observing-your-data/alerting/actions)。 + +### 定义链式告警触发器条件 + +链式告警触发器条件使用 `monitor[id=<monitor-id>]` 引用委托监控器,当委托监控器在当前运行中生成告警时,该引用为 `true`。您可以使用以下运算符组合引用: + +- `&&`(AND) +- `||`(OR) +- `!`(NOT) +- `()`(优先级) + +例如: + +- `monitor[id=1] && monitor[id=2]` 当监控器 1 和监控器 2 都生成告警时生成链式告警。 +- `monitor[id=1] || !monitor[id=2]` 当监控器 1 生成告警或监控器 2 不生成告警时生成链式告警。 +- `monitor[id=1] && (monitor[id=2] || monitor[id=3])` 当监控器 1 生成告警且监控器 2 或监控器 3 生成告警时生成链式告警。 + +::: info NOTE +条件中监控器 ID 的顺序不会影响委托监控器的运行顺序。运行顺序由 `delegates` 数组中的 `order` 字段设置。 +::: + +### 示例请求 + +以下请求创建一个包含两个委托监控器和两个触发器的复合监控器。`Both monitors` 触发器在两个委托监控器都生成告警时生成链式告警。`Either monitor` 触发器在至少一个委托监控器生成告警时生成链式告警: + +```json +POST _plugins/_alerting/workflows +{ + "name": "Traffic and errors", + "workflow_type": "composite", + "enabled": true, + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "inputs": [ + { + "composite_input": { + "sequence": { + "delegates": [ + { + "order": 1, + "monitor_id": "grsbCIcBvEHfkjWFeCqb" + }, + { + "order": 2, + "monitor_id": "agasbCIcBvEHfkjWFeCqa" + } + ] + } + } + } + ], + "triggers": [ + { + "chained_alert_trigger": { + "id": "m1ANDm2", + "name": "Both monitors", + "severity": "1", + "condition": { + "script": { + "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] && monitor[id=agasbCIcBvEHfkjWFeCqa])", + "lang": "painless" + } + }, + "actions": [] + } + }, + { + "chained_alert_trigger": { + "id": "m1ORm2", + "name": "Either monitor", + "severity": "2", + "condition": { + "script": { + "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] || monitor[id=agasbCIcBvEHfkjWFeCqa])", + "lang": "painless" + } + }, + "actions": [] + } + } + ] +} +``` + +## 获取复合监控器 + +返回复合监控器的配置。 + +### 端点 + +```json +GET _plugins/_alerting/workflows/{workflow_id} +``` + +### 路径参数 + +下表列出了可用的路径参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`workflow_id` | String | 复合监控器的 workflow ID。必需。 + +### 示例请求 + +```json +GET _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_ +``` + +## 更新复合监控器 + +替换复合监控器的配置。请求正文字段与[创建复合监控器](#create-composite-monitor)相同。 + +### 端点 + +```json +PUT _plugins/_alerting/workflows/{workflow_id} +``` + +### 示例请求 + +以下请求将复合监控器更改为每 5 分钟运行一次,并仅保留 `Both monitors` 触发器: + +```json +PUT _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_ +{ + "name": "Traffic and errors", + "workflow_type": "composite", + "enabled": true, + "schedule": { + "period": { + "interval": 5, + "unit": "MINUTES" + } + }, + "inputs": [ + { + "composite_input": { + "sequence": { + "delegates": [ + { + "order": 1, + "monitor_id": "grsbCIcBvEHfkjWFeCqb" + }, + { + "order": 2, + "monitor_id": "agasbCIcBvEHfkjWFeCqa" + } + ] + } + } + } + ], + "triggers": [ + { + "chained_alert_trigger": { + "id": "m1ANDm2", + "name": "Both monitors", + "severity": "1", + "condition": { + "script": { + "source": "(monitor[id=grsbCIcBvEHfkjWFeCqb] && monitor[id=agasbCIcBvEHfkjWFeCqa])", + "lang": "painless" + } + }, + "actions": [] + } + } + ] +} +``` + +## 删除复合监控器 + +删除复合监控器。委托监控器不会被删除。 + +### 端点 + +```json +DELETE _plugins/_alerting/workflows/{workflow_id} +``` + +### 示例请求 + +```json +DELETE _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_ +``` + +## 执行复合监控器 + +立即运行复合监控器并返回触发器结果。 + +### 端点 + +```json +POST _plugins/_alerting/workflows/{workflow_id}/_execute +``` + +### 示例请求 + +```json +POST _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_/_execute +``` + +### 示例响应 + +```json +{ + "execution_id": "I0GXeIgBYKBG2nHoiHCL_2023-06-01T20:18:48.511884_a9c1d055-9b70-49c2-b32a-716cff1f562e", + "workflow_name": "scale_up", + "workflow_id": "I0GXeIgBYKBG2nHoiHCL", + "trigger_results": { + "m1ANDm2": { + "name": "jnkjn", + "triggered": true, + "action_results": {}, + "error": null + }, + "m1ORm2": { + "name": "jnkjn", + "triggered": true, + "action_results": {}, + "error": null + } + }, + "monitor_run_results": [{ + "monitor_name": "test triggers", + "period_start": 1685650668501, + "period_end": 1685650728501, + "error": null, + "input_results": { + "results": [{ + "bhjh": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ], + "nkjkj": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ], + "jknkjn": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ] + }], + "error": null + }, + "trigger_results": { + "NC3Dd4cBCDCIfBYtViLI": { + "name": "njkkj", + "triggeredDocs": [ + "OkGceIgBYKBG2nHoyHAn|test1", + "O0GceIgBYKBG2nHozHCW|test1" + ], + "action_results": {}, + "error": null + } + } + }, + { + "monitor_name": "test triggers 2", + "period_start": 1685650668501, + "period_end": 1685650728501, + "error": null, + "input_results": { + "results": [{ + "bhjh": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ], + "nkjkj": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ], + "jknkjn": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ] + }], + "error": null + }, + "trigger_results": { + "NC3Dd4cBCDCIfBYtViLI": { + "name": "njkkj", + "triggeredDocs": [ + "PEGceIgBYKBG2nHo1HCw|test", + "PUGceIgBYKBG2nHo3HA8|test" + ], + "action_results": {}, + "error": null + } + } + } + ], + "execution_start_time": "2023-06-01T20:18:48.511874Z", + "execution_end_time": "2023-06-01T20:18:53.682405Z", + "error": null +} +``` + +## 获取链式告警 + +返回复合监控器生成的链式告警。 + +### 端点 + +```json +GET _plugins/_alerting/workflows/alerts +``` + +### 查询参数 + +下表列出了可用的查询参数。所有查询参数都是可选的。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`workflowIds` | String | 以逗号分隔的 workflow ID 列表。仅返回这些复合监控器生成的告警。 +`getAssociatedAlerts` | Boolean | 当为 `true` 时,响应还包含委托监控器生成的审计告警。默认值为 `false`。 + +### 示例请求 + +```json +GET _plugins/_alerting/workflows/alerts?workflowIds=SX9egKEBrJhc2kcbnbU_&getAssociatedAlerts=true +``` + +### 示例响应 + +```json +{ + "alerts": [ + { + "id": "PbQoZokBfd2ci_FqMGi6", + "version": 1, + "monitor_id": "", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "scale_up", + "associated_alert_ids": [ + "4e8256c5-529a-484c-bf7b-d3980c03e9a4", + "513a8cb3-44bc-4eee-8aac-131be10b399e" + ], + "schema_version": -1, + "monitor_version": -1, + "monitor_name": "", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "m1ANDm2", + "trigger_name": "jnkjn", + "finding_ids": [], + "related_doc_ids": [], + "state": "ACTIVE", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636057269, + "last_notification_time": 1689636057270, + "end_time": null, + "acknowledged_time": null + }, + { + "id": "PrQoZokBfd2ci_FqMGj8", + "version": 1, + "monitor_id": "", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "scale_up", + "associated_alert_ids": [ + "4e8256c5-529a-484c-bf7b-d3980c03e9a4", + "513a8cb3-44bc-4eee-8aac-131be10b399e" + ], + "schema_version": -1, + "monitor_version": -1, + "monitor_name": "", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "m1ORm2", + "trigger_name": "jnkjn", + "finding_ids": [], + "related_doc_ids": [], + "state": "ACTIVE", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636057340, + "last_notification_time": 1689636057340, + "end_time": null, + "acknowledged_time": null + } + ], + "associatedAlerts": [ + { + "id": "4e8256c5-529a-484c-bf7b-d3980c03e9a4", + "version": -1, + "monitor_id": "DrQoZokBfd2ci_FqCWh8", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "", + "associated_alert_ids": [], + "schema_version": 5, + "monitor_version": 1, + "monitor_name": "test triggers", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "NC3Dd4cBCDCIfBYtViLI", + "trigger_name": "njkkj", + "finding_ids": [ + "277afca7-d5aa-46ed-8023-5449ece65d36" + ], + "related_doc_ids": [ + "H7QoZokBfd2ci_FqFmii|test1" + ], + "state": "AUDIT", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636056410, + "last_notification_time": 1689636056410, + "end_time": null, + "acknowledged_time": null + }, + { + "id": "513a8cb3-44bc-4eee-8aac-131be10b399e", + "version": -1, + "monitor_id": "EbQoZokBfd2ci_FqCmiR", + "workflow_id": "G7QoZokBfd2ci_FqD2iZ", + "workflow_name": "", + "associated_alert_ids": [], + "schema_version": 5, + "monitor_version": 1, + "monitor_name": "test triggers 2", + "execution_id": "G7QoZokBfd2ci_FqD2iZ_2023-07-17T23:20:55.244970_edd977d2-c02b-4cbe-8a79-2aa7991c4191", + "trigger_id": "NC3Dd4cBCDCIfBYtViLI", + "trigger_name": "njkkj", + "finding_ids": [ + "6d185585-a077-4dde-8e43-b4c01b9f3102" + ], + "related_doc_ids": [ + "ILQoZokBfd2ci_FqGmhb|test" + ], + "state": "AUDIT", + "error_message": null, + "alert_history": [], + "severity": "1", + "action_execution_results": [], + "start_time": 1689636056943, + "last_notification_time": 1689636056943, + "end_time": null, + "acknowledged_time": null + } + ], + "totalAlerts": 2 +} +``` + +### 响应正文字段 + +下表列出了所有响应正文字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`alerts` | Array | 复合监控器生成的链式告警。 +`associatedAlerts` | Array | 委托监控器生成的审计告警。仅当 `getAssociatedAlerts` 为 `true` 时返回。 +`totalAlerts` | Integer | 链式告警的总数。 + +## 确认链式告警 + +确认一个或多个活动链式告警。已处于 `ERROR`、`COMPLETED` 或 `ACKNOWLEDGED` 状态的告警将在 `failed` 数组中返回。 + +### 端点 + +```json +POST _plugins/_alerting/workflows/{workflow_id}/_acknowledge/alerts +``` + +### 请求正文字段 + +下表列出了可用的请求正文字段。 + +字段 | 数据类型 | 必需 | 描述 +:--- | :--- | :--- | :--- +`alerts` | Array of strings | 必需 | 要确认的告警 ID。要获取告警 ID,请使用[获取链式告警](#get-chained-alerts)。 + +### 示例请求 + +```json +POST _plugins/_alerting/workflows/SX9egKEBrJhc2kcbnbU_/_acknowledge/alerts +{ + "alerts": ["VH9egKEBrJhc2kcbnrU5"] +} +``` + +### 示例响应 + +```json +{ + "success": ["VH9egKEBrJhc2kcbnrU5"], + "failed": [] +} +``` diff --git a/i18n/zh/observing-your-data/alerting/ppl-monitors.md b/i18n/zh/observing-your-data/alerting/ppl-monitors.md new file mode 100644 index 00000000..26d1f87a --- /dev/null +++ b/i18n/zh/observing-your-data/alerting/ppl-monitors.md @@ -0,0 +1,291 @@ +--- +title: PPL 监控器 +--- + +# PPL 监控器 + +PPL 告警监控器使用[管道处理语言(PPL)](/sql-and-ppl/ppl/index/)查询来监控您的数据。它们是使用 PPL 而不是查询 DSL 作为查询语言的[按查询监控器](/observing-your-data/alerting/per-query-bucket-monitors)。 + +## 设置 + +本页中的示例使用包含 Web 请求日志的 `application_logs` 索引。要跟随操作,请使用以下映射创建索引: + +```json +PUT /application_logs +{ + "mappings": { + "properties": { + "@timestamp": { "type": "date" }, + "endpoint": { "type": "keyword" }, + "service": { "type": "keyword" }, + "level": { "type": "keyword" }, + "response_time": { "type": "integer" } + } + } +} +``` + +索引示例文档: + +```json +POST /application_logs/_bulk?refresh=true +{ "index": {} } +{ "@timestamp": "2026-01-15T10:00:00Z", "endpoint": "/api/orders", "service": "orders", "level": "ERROR", "response_time": 4200 } +{ "index": {} } +{ "@timestamp": "2026-01-15T10:01:00Z", "endpoint": "/api/orders", "service": "orders", "level": "ERROR", "response_time": 3600 } +{ "index": {} } +{ "@timestamp": "2026-01-15T10:02:00Z", "endpoint": "/api/checkout", "service": "checkout", "level": "ERROR", "response_time": 2500 } +``` + +## 在 OpenSearch Dashboards 中创建 PPL 监控器 + +要创建 PPL 监控器,请按照以下步骤操作: + +1. 选择 **Alerting** > **Monitors** > **Create monitor**。 +2. 选择 **PPL monitor** 选项。 +3. 输入监控器名称并配置计划(按时间间隔或自定义 cron 表达式)。有关 cron 表达式的更多信息,请参阅 [Cron 表达式](/api-reference/cron-expressions)。 +4. 在 **Query** 部分,输入您的 PPL 查询,例如: + + ```sql + source = application_logs | stats avg(response_time) as avg_response by endpoint + ``` + +5. 添加一个或多个触发器。有关配置触发器条件的更多信息,请参阅 [PPL 触发器](#ppl-triggers)。 +6. 添加操作以指定触发器触发时的通知。有关更多信息,请参阅[操作](/observing-your-data/alerting/actions)。 +7. 选择 **Create**。 + +## PPL 触发器 + +PPL 监控器使用 `ppl_trigger` 对象,这与其他监控器类型使用的基于 Painless 脚本的触发器不同。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。每个 PPL 监控器最多支持 10 个触发器。 + +### 结果数触发器 + +结果数触发器根据阈值评估基础 PPL 查询返回的总行数。支持以下比较运算符。 + +运算符 | 描述 +:--- | :--- +`>` | 大于 +`>=` | 大于或等于 +`<` | 小于 +`<=` | 小于或等于 +`==` | 等于 +`!=` | 不等于 + +例如,要在返回多于一个结果时触发告警,请使用以下触发器定义: + +```json +{ + "ppl_trigger": { + "name": "High result count", + "severity": "1", + "type": "number_of_results", + "num_results_condition": ">", + "num_results_value": 1, + "actions": [] + } +} +``` + +### 自定义条件触发器 + +自定义条件触发器将 `where` 子句附加到基础 PPL 查询。如果修改后的查询返回任何结果,则触发器触发。这允许您根据计算字段或聚合定义细粒度条件。自定义条件在监控器创建期间被验证为 `where` 语句。 + +例如,考虑以下基础查询: + +```sql +source = application_logs | stats max(response_time) as max_response by endpoint +``` + +要在任何端点的最大响应时间超过 3000 毫秒时触发告警,请使用以下触发器定义: + +```json +{ + "ppl_trigger": { + "name": "Slow endpoint detected", + "severity": "2", + "type": "custom", + "custom_condition": "where max_response > 3000", + "actions": [] + } +} +``` + +## 模板变量 + +PPL 监控器提供以下额外的模板变量,用于[操作](/observing-your-data/alerting/actions)和通知消息。 + +变量 | 数据类型 | 描述 +:--- | :--- | :--- +`ctx.ppl_query_results` | Array | 映射列表,其中每个元素表示一个 PPL 查询结果行。每个映射中的键是查询架构中的字段名称。对于结果数触发器,数组包含基础查询结果。对于自定义条件触发器,它包含应用自定义条件的查询结果。 + +### Mustache 模板示例 + +以下示例迭代 PPL 查询结果并输出每行中的字段: + +``` +PPL Query Results: +{{#ctx.ppl_query_results}} + Endpoint: {{endpoint}}, Average Response Time: {{avg_response}} +{{/ctx.ppl_query_results}} +``` + +## 查询结果格式 + +PPL 查询结果包含 `schema` 和 `datarows` 字段。例如,查询 `source = application_logs | where level = 'ERROR' | stats count() as error_count by endpoint` 返回以下响应: + +```json +{ + "schema": [ + {"name": "error_count", "type": "bigint"}, + {"name": "endpoint", "type": "string"} + ], + "datarows": [ + [1, "/api/checkout"], + [2, "/api/orders"] + ], + "total": 2, + "size": 2 +} +``` + +这些结果会自动转换为映射列表,供模板使用,并在 `ctx.ppl_query_results` 中可用: + +```json +[ + {"error_count": 1, "endpoint": "/api/checkout"}, + {"error_count": 2, "endpoint": "/api/orders"} +] +``` + +## 使用 API 创建 PPL 监控器 + +以下示例创建一个具有两种触发器类型的 PPL 监控器: + +```json +POST _plugins/_alerting/monitors +{ + "name": "PPL Error Rate Monitor", + "type": "monitor", + "monitor_type": "ppl_monitor", + "enabled": true, + "schedule": { + "period": { + "unit": "MINUTES", + "interval": 5 + } + }, + "inputs": [ + { + "ppl_input": { + "query": "source = application_logs | where level = 'ERROR' | stats count() as error_count by service", + "query_language": "ppl" + } + } + ], + "triggers": [ + { + "ppl_trigger": { + "name": "Too many errors", + "severity": "1", + "type": "number_of_results", + "num_results_condition": ">", + "num_results_value": 1, + "actions": [ + { + "name": "Notify ops channel", + "destination_id": "your-destination-id", + "message_template": { + "source": "Monitor {{ctx.monitor.name}} detected {{ctx.ppl_query_results.size}} services with errors." + }, + "subject_template": { + "source": "Alert: High Error Rate Detected" + } + } + ] + } + }, + { + "ppl_trigger": { + "name": "Critical service errors", + "severity": "1", + "type": "custom", + "custom_condition": "where error_count > 1", + "actions": [ + { + "name": "Page oncall", + "destination_id": "your-destination-id", + "message_template": { + "source": "Critical error threshold exceeded:\n{{#ctx.ppl_query_results}}\n Service: {{service}}, Errors: {{error_count}}\n{{/ctx.ppl_query_results}}" + }, + "subject_template": { + "source": "CRITICAL: Service Error Threshold Exceeded" + } + } + ] + } + } + ] +} +``` + +响应确认监控器已创建并返回其 `_id`。监控器按其配置的计划运行,每次运行都会根据最新的查询结果评估触发器。当触发器的条件满足时,它会触发并运行其操作。 + +## 测试 PPL 监控器 + +要立即运行监控器而不是等待其下一次计划运行,请使用监控器 ID 使用 Execute API。添加 `?dryrun=true` 以评估触发器而不创建告警或运行操作: + +```json +POST _plugins/_alerting/monitors/<monitor_id>/_execute?dryrun=true +``` + +响应报告查询结果,并针对每个触发器报告它是否触发。`triggered` 字段指示每个触发器的条件是否满足。对于自定义条件触发器,`ppl_query_results` 包含匹配条件的行: + +```json +{ + "monitor_name": "PPL Error Rate Monitor", + "period_start": 1787067810953, + "period_end": 1787068110953, + "error": null, + "input_results": { + "results": [], + "ppl_query_results": [ + { "error_count": 1, "service": "checkout" }, + { "error_count": 2, "service": "orders" } + ], + "ppl_num_results": 2, + "error": null + }, + "trigger_results": { + "too_many_errors": { + "name": "Too many errors", + "triggered": true, + "action_results": {}, + "ppl_query_results": [], + "error": null + }, + "critical_service_errors": { + "name": "Critical service errors", + "triggered": true, + "action_results": {}, + "ppl_query_results": [ + { "error_count": 2, "service": "orders" } + ], + "error": null + } + } +} +``` + +## 设置 + +OpenSearch 支持以下 PPL 监控器设置。所有设置都是动态的,因此您可以在不重启集群的情况下更改它们: + +- `plugins.alerting.monitor.max_ppl_triggers`(动态,整数):每个 PPL 监控器允许的最大触发器数量。这也是最高接受值,因此您只能降低它。默认值为 `10`。 + +- `plugins.alerting.ppl_query_max_execution_duration`(动态,时间单位):在监控器执行期间 PPL 查询允许的最大执行时间。默认值为 `30s`。 + +- `plugins.alerting.ppl_monitor_max_query_length`(动态,长整型):PPL 查询的最大字符数。默认值为 `2000`。 + +- `plugins.alerting.ppl_query_results_max_datarows`(动态,长整型):执行 PPL 查询时检索的最大数据行数。默认值为 `10000`。 + +- `plugins.alerting.ppl_query_results_max_size`(动态,长整型):存储在告警和通知中的查询结果的最大估计大小(以字节为单位)。如果结果超过此大小,告警将用一条消息替换它们,说明 PPL 查询结果太大。默认值为 `3000`。 diff --git a/i18n/zh/observing-your-data/alerting/restore.md b/i18n/zh/observing-your-data/alerting/restore.md new file mode 100644 index 00000000..b32c686b --- /dev/null +++ b/i18n/zh/observing-your-data/alerting/restore.md @@ -0,0 +1,113 @@ +--- +title: 从快照恢复监控器和告警 +--- + +# 从快照恢复监控器和告警 +<Badge type="tip" text="3.10 版本引入" /> + +OpenSearch 将告警监控器和工作流存储在 `.opendistro-alerting-config` 系统索引中,将告警、发现和评论存储在单独的系统索引中。当您使用 [Restore Snapshot API](/api-reference/snapshots/restore-snapshot) 从快照恢复这些索引时,例如恢复到另一个集群,如果您首先准备好集群并按照[恢复告警索引](#恢复告警索引)中的描述恢复索引,监控器将在该集群中继续运行。 + +本页使用_原始集群_表示拍摄快照的集群,使用_新集群_表示您恢复到的集群。 + +## 要恢复的索引 + +下表列出了告警索引以及是否恢复它们。 + +| 索引 | 内容 | 是否恢复 | +| :--- | :--- | :--- | +| `.opendistro-alerting-config` | 监控器和工作流 | 是。 | +| `.opendistro-alerting-config-sharing` | 每个监控器和工作流共享给的用户、角色和后端角色 | 是,如果原始集群使用了[资源共享](/security/access-control/resources/)。请参阅[恢复监控器共享](#恢复监控器共享)。 | +| `.opendistro-alerting-alerts` | 活动告警 | 是,以保留活动告警。 | +| `.opendistro-alerting-alert-history-*` | 已完成的告警 | 是,以保留告警历史。 | +| `.opensearch-alerting-finding-history-*` | 发现 | 是,以保留发现。 | +| `.opensearch-alerting-comments-history-*` | 告警评论,如果启用了评论 | 是,以保留评论。 | +| `.opensearch-alerting-queries*` | 文档级监控器运行的查询 | 否。OpenSearch 从监控器重建它。 | +| `.opensearch-alerting-config-lock` | 监控器运行时持有的临时锁 | 否。 | + +监控器操作通过通知渠道发送消息,OpenSearch 将其存储在 `.opensearch-notifications-config` 系统索引中。如果您的监控器有操作,也恢复该索引,以便渠道存在于新集群中。 + +## 准备新集群 + +恢复告警索引会恢复您的监控器,但不会恢复控制谁可以访问它们的设置和角色。在恢复索引之前,在新集群中完成以下步骤。 + +::: tip TIP +当您需要恢复监控器和告警时,原始集群可能不可用。作为恢复计划的一部分,记录其设置并备份其安全配置。 +::: + +### 从原始集群复制设置 + +下表列出了控制监控器访问和告警历史保留的设置。使用原始集群的值在新集群中配置这些设置。 + +| 设置 | 控制内容 | +| :--- | :--- | +| `plugins.alerting.filter_by_backend_roles` | 用户是否只能查看由共享后端角色的用户创建的监控器。有关更多信息,请参阅[按后端角色限制访问](/observing-your-data/alerting/security#advanced-limit-access-by-backend-role)。 | +| `plugins.alerting.filter_by_backend_roles_access_strategy` | 当 `plugins.alerting.filter_by_backend_roles` 为 `true` 时如何比较后端角色。 | +| `plugins.security.resource_sharing.enabled` | 是否启用[资源共享](/security/access-control/resources/)。 | +| `plugins.security.resource_sharing.protected_types` | 使用资源共享的资源类型。对于告警,这些是 `monitor` 和 `alerting-workflow`。 | +| `plugins.alerting.alert_history_retention_period`<br>`plugins.alerting.finding_history_retention_period`<br>`plugins.alerting.comments_history_retention_period` | 历史索引保留的时间量。 | + +恢复的历史索引如果早于保留期,将被删除。 + +要查看原始集群中的这些值,包括在 `opensearch.yml` 中设置的值,请发送以下请求: + +```json +GET /_cluster/settings?include_defaults=true&filter_path=*.plugins.alerting.filter_by_backend_roles*,*.plugins.alerting.*_retention_period,*.plugins.security.resource_sharing +``` + +如果新集群中的设置与原始集群中的值不匹配,用户对新集群中监控器和告警的访问将与他们在原始集群中的访问不同,并且不会报告错误。例如,如果 `plugins.alerting.filter_by_backend_roles` 在原始集群中为 `true` 但在新集群中为 `false`,则每个具有告警权限的用户都可以查看每个监控器及其告警。 + +### 从原始集群复制角色和角色映射 + +监控器存储创建它们的用户的角色和后端角色,并以这些角色在新集群中拥有的权限运行。将角色和角色映射以及相同的权限从原始集群复制到新集群。要执行此操作,请使用 `securityadmin.sh` 从安全配置备份上传 `roles.yml` 和 `roles_mapping.yml`,或使用 [Security API](/security/api/)。有关备份安全配置的更多信息,请参阅[注意事项](/security/configuration/security-admin#a-word-of-caution)。如果角色在新集群中授予更多权限,监控器可以读取其创建者在原始集群中无法读取的数据。 + +如果原始集群使用了资源共享,则恢复的监控器仅在新集群中存在同名用户、角色或后端角色时才与用户、角色或后端角色共享。由身份验证后端(如 LDAP 或 SAML)提供的后端角色要求新集群使用相同的后端。 + +## 恢复告警索引 + +将告警索引恢复到尚未创建监控器的集群。如果新集群包含监控器,它已经包含一个 `.opendistro-alerting-config` 索引。当存在同名的开放索引时,OpenSearch 无法恢复索引,因此恢复操作失败。要恢复监控器和告警,请按照以下步骤操作: + +1. 确保您有权限恢复系统索引。默认情况下,REST 管理员(映射到 `plugins.security.restapi.roles_enabled` 中角色的用户)可以恢复您需要恢复的每个告警索引,如[要恢复的索引](#要恢复的索引)中所列。要恢复通知渠道,REST 管理员必须将 `.opensearch-notifications-config` 添加到 `plugins.security.system_indices.restore.indices` 设置。有关更多信息,请参阅[谁可以恢复系统索引](/tuning-your-cluster/availability-and-recovery/snapshots/snapshot-restore#who-can-restore-system-indexes)。 +1. 在快照中查找历史索引的名称。历史索引名称包括日期和数字,例如 `.opendistro-alerting-alert-history-2026.10.27-1`。要恢复所有这些索引,请使用模式,例如 `.opendistro-alerting-alert-history-*`。REST 管理员只有在模式不超过 `plugins.security.system_indices.restore.indices` 设置中的条目时才能使用模式。否则,请命名每个索引。要列出快照中的索引,请使用 [Get Snapshot API](/api-reference/snapshots/get-snapshot): + + ```json + GET /_snapshot/my-repository/snapshot-1 + ``` + +1. 使用一个请求恢复告警索引和监控器查询的数据索引。命名每个告警系统索引或使用模式匹配它,如上一步所述: + + ```json + POST /_snapshot/my-repository/snapshot-1/_restore + { + "indices": "my-logs,.opendistro-alerting-config,.opendistro-alerting-alerts,.opendistro-alerting-alert-history-*,.opensearch-alerting-finding-history-*", + "include_global_state": false + } + ``` + + 将以下适用于您集群的任何索引添加到同一请求: + + - `.opendistro-alerting-config-sharing`,如果原始集群使用了资源共享 + - `.opensearch-alerting-comments-history-*`,以保留告警评论 + - `.opensearch-notifications-config`,如果您的监控器有操作 + + 一旦恢复 `.opendistro-alerting-config`,监控器就会开始运行。如果您在稍后的请求中恢复其他告警索引,恢复可能会失败或告警可能会丢失。监控器无法查询新集群中不存在的数据索引。从与 `.opendistro-alerting-config` 相同的快照恢复数据索引,以便每个文档级监控器从它在原始集群中评估的最后一个文档恢复,如[文档级监控器](#文档级监控器)中所述。 + +1. 通过使用 [Search Monitors API](/observing-your-data/alerting/api#search-monitors) 验证监控器是否已恢复: + + ```json + GET /_plugins/_alerting/monitors/_search + { + "query": { + "match_all": {} + } + } + ``` + + 响应列出恢复的监控器。 + +## 恢复监控器共享 + +如果您恢复 `.opendistro-alerting-config` 但不恢复 `.opendistro-alerting-config-sharing`,除超级管理员外的用户将失去对恢复的监控器的访问权限,包括创建它们的用户。要恢复他们的访问权限,请从同一快照恢复 `.opendistro-alerting-config-sharing`。其记录通过 ID 引用监控器和工作流,恢复会保留 ID。不要使用 [Migrate API](/security/access-control/resource-sharing-api/#migrate-legacy-sharing-metadata),因为它将每个监控器与其创建者的后端角色共享,而不会恢复原始共享。 + +## 文档级监控器 + +文档级监控器记录它在其数据索引的每个分片中评估的最后一个文档,并在恢复后从该文档恢复。在新集群中的第一次运行中,监控器可能不会评估在该运行之前写入其数据索引的文档。第一次运行后,监控器会评估每个新文档。为确保评估每个文档,请在向其数据索引写入新文档之前,等待每个文档级监控器在新集群中运行一次。 diff --git a/i18n/zh/observing-your-data/alerting/unified-alerts-view.md b/i18n/zh/observing-your-data/alerting/unified-alerts-view.md new file mode 100644 index 00000000..8d8b859a --- /dev/null +++ b/i18n/zh/observing-your-data/alerting/unified-alerts-view.md @@ -0,0 +1,94 @@ +--- +title: 统一告警视图 +--- + +# 统一告警视图 +<Badge type="tip" text="3.7 版本引入" /> + +统一告警视图将来自 OpenSearch 监控器和 Prometheus 告警规则的告警合并到单个视图中,因此您可以跨数据源分类告警,而无需在工具之间切换。在 OpenSearch Dashboards 中,该视图显示为**可观测性**下的**告警**页面。 + +**告警**页面还可以显示异常检测和预测资源,因此您可以在一个页面上调查告警、异常、检测器和预测器。 + +## 启用统一告警视图 + +统一告警视图默认禁用。要启用它,请将以下行添加到 `opensearch_dashboards.yml`: + +```yaml +observability.alertManager.enabled: true +``` + +然后重新启动 OpenSearch Dashboards。重新启动后,**可观测性**下的 OpenSearch Dashboards 主菜单中会出现一个**告警**选项。 + +## 调查告警 + +**告警**选项卡显示所选时间范围的告警时间线、分面过滤器面板以及单个告警和异常的表。您可以按数据源、类型、严重性、状态和标签过滤表。 + +要调查告警,请在表中选择它以打开告警详细信息浮出控件。浮出控件显示告警元数据及其源监控器。 + +该视图支持以下告警状态:`active`、`pending`、`acknowledged`、`silenced`、`resolved` 和 `error`。支持的严重性级别为 `critical`、`high`、`medium`、`low` 和 `info`。 + +## 调查异常 + +**告警**选项卡包括来自实时异常检测器的异常结果。异常与告警显示在同一表中,并使用 `anomaly` 状态。 + +当多个异常发生属于同一检测器和实体时,表将它们分组到单行中。展开该行以检查单个发生,然后选择一个发生以打开异常详细信息浮出控件。 + +异常详细信息浮出控件显示检测器和异常元数据、异常等级、置信度、开始时间、持续时间和特征数据。对于高基数检测器,浮出控件包括所选实体的检测器结果上下文。对于单实体检测器,浮出控件显示所选异常的指标上下文。 + +如果告警与异常结果相关联,告警详细信息浮出控件还会显示异常上下文,以便您可以查看导致告警的异常,而无需离开**告警**页面。 + +## 确认告警 + +从**告警**选项卡,您可以确认一个或多个活动的 OpenSearch 告警。在表中选择告警,然后选择**确认**。 + +::: info NOTE +对于 Prometheus 数据源,视图是只读的。您无法从统一告警视图确认 Prometheus 告警。 +::: + +## 规则 + +**规则**选项卡列出所选数据源的告警规则、监控器、异常检测器和预测器。您可以按类型和状态过滤规则。 + +如果未为所选数据源配置资源,该页面提供创建以下内容的选项: + +- 日志或指标告警 +- 异常检测器 +- 预测器 + +仅当在数据源过滤器中选择了 OpenSearch 数据源时,才启用异常检测和预测选项。 + +### 异常检测器 + +检测器在**类型**列中显示为**异常检测器**类型。选择检测器以打开显示以下信息的浮出控件: + +- 检测器和模型配置 +- 当前状态和健康状况 + +要从此页面管理检测器生命周期,请使用以下选项之一: + +- 选择一个或多个检测器,然后在操作栏中选择**启动**或**停止**。 +- 在检测器浮出控件中选择**启动**或**停止**。 + +### 预测器 + +预测器显示为**预测器**类型。选择预测器以打开显示以下信息的浮出控件: + +- 预测器描述、索引详细信息和特征定义 +- 预测范围和间隔配置 +- 预测状态和健康状况 + +从浮出控件,您可以启动或停止预测器。要一次启动或停止多个预测器,请在**规则**表中选择它们,然后选择**启动**或**停止**。 + +预测器产生用于趋势和容量规划的预测输出。它们不会在**告警**时间线中创建告警记录。 + +## 通知路由 + +**路由**选项卡显示来自所选数据源的告警如何映射到通知渠道。 + +## 相关文档 + +- [告警](/observing-your-data/alerting/) +- [告警仪表板和可视化](/observing-your-data/alerting/dashboards-alerting) +- [监控器](/observing-your-data/alerting/monitors) +- [异常检测](/observing-your-data/ad/) +- [预测](/observing-your-data/forecast/) diff --git a/i18n/zh/observing-your-data/apm/application-map.md b/i18n/zh/observing-your-data/apm/application-map.md new file mode 100644 index 00000000..7a5d37f6 --- /dev/null +++ b/i18n/zh/observing-your-data/apm/application-map.md @@ -0,0 +1,91 @@ +--- +title: 拓扑图 +--- + +# 拓扑图 +<Badge type="tip" text="3.6 版本引入" /> + +拓扑图提供了一个交互式拓扑可视化,该可视化由 Data Prepper 的 `otel_apm_service_map` 处理器从追踪数据自动生成。该图将您的服务显示为节点,并使用有向边显示通信模式,同时为每个服务覆盖速率、错误、持续时间(RED)指标。 + +## 访问拓扑图 + +要访问拓扑图,在您的可观测性工作区中,选择左侧导航栏中的 **拓扑图**。下图显示了拓扑图。 + +*拓扑图* + +## 图上的 RED 指标 + +拓扑图上的每个节点显示从追踪 span 数据计算得出的以下 RED 指标: + +- **速率(Rate)**:服务每秒处理的请求数。 +- **错误(Errors)**:导致错误的请求百分比,按 `4xx`(客户端错误)和 `5xx`(服务器故障)细分。 +- **持续时间(Duration)**:服务的响应时间,通常显示为 P50 和 P99 延迟。 + +这些指标由 Data Prepper 中的 `otel_apm_service_map` 处理器生成,并通过远程写入存储到 Prometheus。有关更多信息,请参阅 [APM 服务映射处理器](/data-prepper/pipelines/configuration/processors/otel-apm-service-map)。 + +## 拓扑可视化 + +拓扑图从您的追踪数据自动生成有向图: + +- **节点**代表应用程序中的各个服务。 +- **边**代表服务之间的通信,箭头指示调用方向。 +- **颜色编码**根据每个服务的错误率和故障率指示其健康状态。 + +该图会在新追踪数据被采集时自动更新,近乎实时地反映应用程序拓扑的变化。 + +## 分组服务 + +您可以按属性对服务进行分组以组织图视图。下图显示了按属性分组的服务。 + +*按属性分组* + +- **按属性分组**:选择一个属性,如编程语言、团队或环境,将相关服务分组在一起。 +- **卡片网格视图**:应用分组后,图会重新组织为卡片网格布局,其中每张卡片代表一组具有聚合指标的服务。 + +::: info NOTE +`otel_apm_service_map` 处理器配置中的 `group_by_attributes` 选项决定了哪些属性可用于分组。例如,设置 `group_by_attributes: [telemetry.sdk.language]` 可以按编程语言进行分组。 +::: + +## 查看节点详细信息 + +在图上选择一个节点或选择 **查看洞察** 以在屏幕右侧打开详细信息面板。 + +*节点详细信息面板* + +详细信息面板包括以下部分: + +- **健康状况**: + + - **总请求数**:在选定时间范围内处理的请求总数。 + - **总错误数(`4xx`)**:客户端错误响应的计数。 + - **总故障数(`5xx`)**:服务器故障响应的计数。 + +- **指标**:显示每个指标在选定时间范围内趋势的时间序列图表: + + - **请求**:随时间变化的请求量。 + - **延迟**:随时间变化的 P50、P90 和 P99 延迟。 + - **故障(`5xx`)**:随时间变化的服务器故障计数。 + - **错误(`4xx`)**:随时间变化的客户端错误计数。 + +从节点详细信息面板中,选择 **查看详情** 可直接导航到所选服务的[服务](/observing-your-data/apm/services)详细视图。 + +## 过滤图 + +下图显示了按错误率过滤的拓扑图。 + +*按错误率过滤* + +使用过滤器控件可以专注于应用程序拓扑的特定区域: + +- **故障率**:仅显示故障率(`5xx` 错误)超过指定阈值的服务。 +- **错误率**:仅显示错误率(`4xx` 错误)超过指定阈值的服务。 +- **环境**:按部署环境(例如 `production` 或 `staging`)过滤服务。 + +## 上下文关联 + +拓扑图集成了 APM 关联,帮助您从拓扑视图导航到详细的遥测数据: + +- **应用 span**:选择一个服务节点并选择 **查看追踪** 以查看与该服务相关的单个追踪 span。这对于调查图上可见的延迟或错误峰值的根本原因很有用。 +- **应用日志**:选择一个服务节点并选择 **查看日志** 以查看该服务在选定时间范围内的日志条目。日志关联需要您在追踪和日志数据集之间配置[关联](/observing-your-data/exploring-observability-data/correlations)。 + +这些上下文导航路径使您能够从高层拓扑视图无缝移动到根本原因分析所需的详细追踪和日志。 diff --git a/i18n/zh/observing-your-data/apm/configuring-apm.md b/i18n/zh/observing-your-data/apm/configuring-apm.md new file mode 100644 index 00000000..420e1b15 --- /dev/null +++ b/i18n/zh/observing-your-data/apm/configuring-apm.md @@ -0,0 +1,74 @@ +--- +title: 在 OpenSearch Dashboards 中配置 APM +--- + +# 在 OpenSearch Dashboards 中配置 APM +<Badge type="tip" text="3.6 版本引入" /> + +在使用 OpenTelemetry Collector 和 Data Prepper 采集遥测数据后,您需要在 OpenSearch Dashboards 中配置应用性能监控(APM)。您将创建数据集、配置索引模式、附加 Prometheus 数据源并在工作区中配置 APM 设置。 + +## 步骤 1:为日志和追踪创建数据集 + +在您的可观测性工作区中创建数据集以定义 APM 如何访问您的追踪和日志数据: + +1. 导航到您的可观测性工作区。 +2. 选择 **数据集**,然后选择 **创建数据集**。 +3. 创建一个**追踪数据集**,指向您的追踪数据索引(例如 `otel-v1-apm-span-*`)。 +4. 创建一个**日志数据集**,指向您的应用程序日志索引(例如 `logs-otel-v1-*`)。 + +有关创建和配置数据集的详细说明,请参阅[数据集](/observing-your-data/exploring-observability-data/datasets)。 + +## 步骤 2:在追踪和日志数据集之间创建关联 + +链接追踪和日志数据集,以便 APM 可以在您调查追踪时显示相关日志: + +1. 导航到 **数据集** > **关联**。 +2. 选择您在[步骤 1](#步骤-1为日志和追踪创建数据集)中创建的追踪数据集。 +3. 添加日志数据集作为关联数据集。 +4. 保存关联。 + +这使得整个 APM 界面(包括**服务**和**拓扑图**页面)都能进行上下文日志关联。有关详细说明,请参阅[关联](/observing-your-data/exploring-observability-data/correlations)。 + +## 步骤 3:为服务映射创建索引模式 + +APM 需要一个索引模式用于由 Data Prepper 中的 `otel_apm_service_map` 处理器生成的服务映射数据。要创建索引模式,请按照以下步骤操作: + +1. 导航到 **Dashboards 管理** > **索引模式**。 +2. 选择 **创建索引模式**。 +3. 输入 `otel-v2-apm-service-map*` 作为索引模式名称。 +4. 选择适当的时间字段并保存。 + +此索引模式由 APM 用于显示服务拓扑数据和依赖关系信息。 + +## 步骤 4:将 Prometheus 数据源附加到您的工作区 + +APM 使用 Prometheus 存储和查询速率、错误和持续时间(RED)指标。要将 Prometheus 数据源添加到您的工作区,请按照以下步骤操作: + +1. 导航到 **Dashboards 管理** > **数据源**。 +2. 选择 **创建数据源**并选择 **Prometheus**。 +3. 输入您的 Prometheus 实例的连接详细信息(例如 `http://prometheus:9090`)。 +4. 保存数据源并将其附加到您的可观测性工作区。 + +有关配置 Prometheus 数据源的详细说明,请参阅[配置 Prometheus 数据源](/observing-your-data/exploring-observability-data/discover-metrics#configuring-a-prometheus-data-source)。 + +## 步骤 5:配置 APM 设置 + +要配置 APM 设置,请按照以下步骤操作: + +1. 在左侧导航栏中,选择 **应用性能** > **服务**或**拓扑图**。 +2. 选择右上角的 **APM 设置**按钮。将出现 **应用监控设置**对话框,如下图所示。 + *APM 设置模态框* +3. 在 **应用监控设置**对话框中,配置以下设置: + + - **追踪**:选择您在[步骤 1](#步骤-1为日志和追踪创建数据集)中创建的追踪数据集(例如 `Trace Dataset - Local Cluster`)。关联日志的数量将显示在选择下方。 + - **服务**:选择您在[步骤 3](#步骤-3为服务映射创建索引模式)中创建的服务映射索引模式(例如 `otel-v2-apm-service-map*`)。 + - **RED 指标**:选择您在[步骤 4](#步骤-4将-prometheus-数据源附加到您的工作区)中配置的 Prometheus 数据源(例如 `ObservabilityStack_Prometheus`)。 + +4. 选择 **更新**以保存您的配置。 + +完成此设置后,APM 将在服务和拓扑图页面上显示服务拓扑、RED 指标和上下文关联。 + +## 下一步 + +- [服务](/observing-your-data/apm/services):查看服务性能指标和依赖关系。 +- [拓扑图](/observing-your-data/apm/application-map):探索服务拓扑可视化。 diff --git a/i18n/zh/observing-your-data/apm/configuring-telemetry-ingestion.md b/i18n/zh/observing-your-data/apm/configuring-telemetry-ingestion.md new file mode 100644 index 00000000..dc214e3f --- /dev/null +++ b/i18n/zh/observing-your-data/apm/configuring-telemetry-ingestion.md @@ -0,0 +1,178 @@ +--- +title: 配置遥测数据采集 +--- + +# 配置遥测数据采集 +<Badge type="tip" text="3.6 版本引入" /> + +要使用 APM,您需要使用 OpenTelemetry Collector 和 Data Prepper 管道将应用追踪和日志采集到 OpenSearch 中。有关完整 APM 架构的概述,请参阅 [APM 架构](/observing-your-data/apm/#apm-architecture)。 + +本页介绍如何配置 OpenTelemetry Collector 和 Data Prepper 以处理遥测数据并将其路由到 OpenSearch 和 Prometheus。 + +## 配置 OpenTelemetry Collector + +[OpenTelemetry (OTel) Collector](https://opentelemetry.io/docs/collector/) 充当所有应用遥测数据的入口点。它通过 OpenTelemetry 协议(OTLP)接收数据,并将追踪和日志路由到 Data Prepper,同时将指标发送到 Prometheus。 + +以下示例显示了将遥测数据路由到 Data Prepper 和 Prometheus 的关键导出器和管道配置: + +```yaml +exporters: + otlp/opensearch: + endpoint: "data-prepper:21893" + tls: + insecure: true + insecure_skip_verify: true + + otlphttp/prometheus: + endpoint: "http://prometheus:9090/api/v1/otlp" + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [otlp] + processors: [resourcedetection, memory_limiter, transform, batch] + exporters: [otlp/opensearch] + + metrics: + receivers: [otlp] + processors: [resourcedetection, memory_limiter, batch] + exporters: [otlphttp/prometheus] + + logs: + receivers: [otlp] + processors: [resourcedetection, memory_limiter, transform, batch] + exporters: [otlp/opensearch] +``` + +::: info NOTE +`otlp/opensearch` 导出器将追踪和日志发送到 Data Prepper。`otlphttp/prometheus` 导出器直接将指标发送到 Prometheus。有关包含接收器、处理器和遥测设置的完整 OTel Collector 配置示例,请参阅 [observability-stack 存储库](https://github.com/opensearch-project/observability-stack/blob/main/docker-compose/otel-collector/config.yaml)。 +::: + +## 配置 Data Prepper 管道 + +Data Prepper 从 OTel Collector 接收遥测数据,并将其处理为 APM 所需的格式。管道架构通过专门的子管道路由数据,用于日志、追踪和服务映射生成。 + +以下示例显示了完整的 Data Prepper 管道配置: + +```yaml +# 主 OTLP 管道 - 接收所有遥测数据并按类型路由 +otlp-pipeline: + source: + otlp: + ssl: false + route: + - logs: "getEventType() == \"LOG\"" + - traces: "getEventType() == \"TRACE\"" + sink: + - pipeline: + name: "otel-logs-pipeline" + routes: + - "logs" + - pipeline: + name: "otel-traces-pipeline" + routes: + - "traces" + +# 日志处理管道 +otel-logs-pipeline: + workers: 5 # 设置工作线程的配置示例 + delay: 10 # 设置延迟的配置示例 + source: + pipeline: + name: "otlp-pipeline" + buffer: + bounded_blocking: + sink: + - opensearch: + hosts: ["https://<opensearch-host>:9200"] + username: <username> + password: <password> + insecure: true + index_type: log-analytics-plain + +# 追踪处理管道 +otel-traces-pipeline: + source: + pipeline: + name: "otlp-pipeline" + sink: + - pipeline: + name: "traces-raw-pipeline" + - pipeline: + name: "service-map-pipeline" + +# 原始追踪存储管道 +traces-raw-pipeline: + source: + pipeline: + name: "otel-traces-pipeline" + processor: + - otel_traces: + sink: + - opensearch: + hosts: ["https://<opensearch-host>:9200"] + username: <username> + password: <password> + insecure: true + index_type: trace-analytics-plain-raw + +# 服务映射和 APM 指标管道 +service-map-pipeline: + source: + pipeline: + name: "otel-traces-pipeline" + processor: + - otel_apm_service_map: + group_by_attributes: [telemetry.sdk.language] # 添加任何资源属性以进行分组 + route: + - otel_apm_service_map_route: 'getEventType() == "SERVICE_MAP"' + - service_processed_metrics: 'getEventType() == "METRIC"' + sink: + - opensearch: + hosts: ["https://<opensearch-host>:9200"] + username: <username> + password: <password> + index_type: otel-v2-apm-service-map + routes: [otel_apm_service_map_route] + insecure: true + - prometheus: + url: "http://prometheus:9090/api/v1/write" + routes: [service_processed_metrics] +``` + +### 管道架构 + +Data Prepper 管道使用以下步骤处理遥测数据: + +1. 入口管道(`otlp-pipeline`)在端口 21893 上接收所有遥测数据,并将日志和追踪路由到各自的子管道。 +2. 日志管道(`otel-logs-pipeline`)将 `time` 字段映射到 `@timestamp`,并使用 `log-analytics-plain` 索引类型将日志写入 OpenSearch。 +3. 追踪管道(`otel-traces-pipeline`)将追踪分发到原始存储管道和服务映射管道。 +4. 原始追踪管道(`traces-raw-pipeline`)使用 `otel_traces` 处理器处理单个追踪 span,并使用 `trace-analytics-plain-raw` 索引类型将它们存储在 OpenSearch 中。 +5. 服务映射管道(`service-map-pipeline`)使用 `otel_apm_service_map` 处理器生成服务依赖关系映射和 RED 指标。服务映射拓扑数据写入 OpenSearch,RED 指标通过远程写入导出到 Prometheus。 + +::: info NOTE +`otel_apm_service_map` 处理器的两个关键配置选项是 `group_by_attributes`(确定如何在拓扑图中对服务进行分组)和 `window_duration`(设置聚合追踪数据的时间窗口)。有关完整的配置详细信息,请参阅 [APM 服务映射处理器](/data-prepper/pipelines/configuration/processors/otel-apm-service-map)。 +::: + +## 验证采集 + +配置 OTel Collector 和 Data Prepper 后,验证数据是否正确流动: + +1. 验证在您的 OpenSearch 集群中创建了以下索引: + - `otel-v1-apm-span-*`:原始追踪 span。 + - `otel-v2-apm-service-map`:服务拓扑数据。 + - `logs-otel-v1-*`:应用程序日志。 + +2. 验证 Data Prepper 远程写入目标在您的 Prometheus 实例中处于活动状态。 + +3. 在您的可观测性工作区中,选择左侧导航栏中的 **应用性能** > **服务**,以确认您的服务出现在[服务](/observing-your-data/apm/services)目录和[拓扑图](/observing-your-data/apm/application-map)中。 + +::: danger WARNING +确保 OTel Collector、Data Prepper、OpenSearch 和 Prometheus 之间的所有端口映射都正确。端口不匹配是采集失败的常见原因。 +::: + +## 下一步 + +- [在 OpenSearch Dashboards 中配置 APM](/observing-your-data/apm/configuring-apm):创建数据集、索引模式并配置 APM 设置以开始使用 APM 功能。 diff --git a/i18n/zh/observing-your-data/apm/index.md b/i18n/zh/observing-your-data/apm/index.md new file mode 100644 index 00000000..69f790ca --- /dev/null +++ b/i18n/zh/observing-your-data/apm/index.md @@ -0,0 +1,69 @@ +--- +title: 应用程序性能监控 +--- + +# 应用程序性能监控 +<Badge type="tip" text="3.6 版本引入" /> + +应用程序性能监控(APM)通过将服务拓扑数据与速率、错误、持续时间(RED)指标相结合,提供对分布式应用程序的实时监控。APM 提供服务健康状况的统一视图,使您能够快速识别微服务架构中的性能瓶颈和故障。 + +## 先决条件 + +APM 需要以下组件: + +- 具有可观测性工作空间并启用 APM 设置的 OpenSearch 集群和 OpenSearch Dashboards。有关更多信息,请参阅[可观测性工作空间应用](/observing-your-data/exploring-observability-data/)。 +- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)。 +- [OpenSearch Data Prepper](/data-prepper/)。 +- 用于指标存储的 [Prometheus](https://prometheus.io/),作为 [Prometheus 数据源](/dashboards/management/connect-prometheus)连接到 OpenSearch。 +- 使用 [OpenTelemetry](https://opentelemetry.io/docs/instrumentation/) 进行检测的应用程序。 + +## APM 架构 + +以下图像显示了 APM 架构。 + +*APM architecture* + +APM 使用以下数据管道来收集、处理和可视化应用程序遥测数据: + +1. **[OpenTelemetry SDK](https://opentelemetry.io/docs/instrumentation/)** 对您的应用程序代码进行检测以生成追踪、日志和指标。 +2. **[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)** 通过 OTLP(端口 4317 上的 gRPC 或端口 4318 上的 HTTP)接收遥测数据,处理它,并将其路由到 Data Prepper 和 Prometheus。 +3. **[OpenSearch Data Prepper](/data-prepper/)** 处理追踪并使用 [`otel_apm_service_map` 处理器](/data-prepper/pipelines/configuration/processors/otel-apm-service-map)生成服务映射和 RED 指标。 +4. **OpenSearch** 存储追踪数据、日志和服务拓扑信息。 +5. **Prometheus** 通过远程写入存储时间序列 RED 指标。 +6. **OpenSearch Dashboards** 提供 APM 用户界面以进行可视化和分析。 + +## 配置 APM + +要配置 APM,请完成以下步骤: + +1. **创建可观测性工作空间**:APM 功能仅在可观测性工作空间中可用。要了解如何启用和创建工作空间,请参阅 [OpenSearch Dashboards 的工作空间](/dashboards/workspace/workspace)。 + +2. **启用功能标志**:将以下设置添加到您的 `opensearch_dashboards.yml` 文件中: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + explore.discoverMetrics.enabled: true + ``` + +3. **检测您的应用程序**:将 [OpenTelemetry SDK](https://opentelemetry.io/docs/instrumentation/) 集成到您的应用程序代码中以生成追踪和日志数据。 + +4. **配置遥测摄取**:设置 OpenTelemetry Collector 和 Data Prepper 以处理遥测数据并将其路由到 OpenSearch 和 Prometheus。请参阅[配置遥测摄取](/observing-your-data/apm/configuring-telemetry-ingestion)。 + +5. **在 OpenSearch Dashboards 中配置 APM**:在您的可观测性工作空间中创建数据集、索引模式并连接数据源。请参阅[在 OpenSearch Dashboards 中配置 APM](/observing-your-data/apm/configuring-apm)。 + +## 使用 APM + +完成设置步骤后,使用以下 APM 页面监控您的服务: + +- [**服务**](/observing-your-data/apm/services):查看所有已检测服务的集中目录,包括关键性能指标、每个操作的指标和依赖信息。 +- [**拓扑图**](/observing-your-data/apm/application-map):探索从追踪数据自动生成的交互式拓扑可视化,每个服务节点上叠加了 RED 指标。 + +::: info NOTE +APM 与旧版的[应用程序分析](/observing-your-data/app-analytics)和[追踪分析](/observing-your-data/trace/)功能不同。APM 提供了一种更加集成的体验,将服务拓扑、RED 指标和上下文关联组合到单个工作流中。 +::: + +## 后续步骤 + +- [配置遥测摄取](/observing-your-data/apm/configuring-telemetry-ingestion):设置 OpenTelemetry Collector 和 Data Prepper 以处理遥测数据并将其路由到 OpenSearch 和 Prometheus。 diff --git a/i18n/zh/observing-your-data/apm/services.md b/i18n/zh/observing-your-data/apm/services.md new file mode 100644 index 00000000..0980a0bc --- /dev/null +++ b/i18n/zh/observing-your-data/apm/services.md @@ -0,0 +1,102 @@ +--- +title: 服务 +--- + +# 服务 +<Badge type="tip" text="3.6 版本引入" /> + +**服务**页面提供了应用程序中所有已检测服务的集中目录,一目了然地显示速率、错误、持续时间(RED)。使用此页面可以识别错误率高、延迟问题或吞吐量异常的服务。 + +## 访问服务页面 + +要访问**服务**页面,在您的可观测性工作区中,选择左侧导航栏中的 **应用性能** > **服务**。下图显示了**服务**页面。 + +*服务主页* + +服务主页显示所有已发现服务的表格,包含以下信息: + +- **服务名称**:OpenTelemetry SDK 报告的已检测服务的名称。 +- **P99/P90/P50 延迟**:服务的第 99、90 和 50 百分位响应时间。 +- **总请求数**:在选定时间范围内服务处理的请求总数。 +- **失败率**:导致错误的请求百分比(`4xx` 和 `5xx` 响应)。 +- **环境**:部署环境(例如 `production` 或 `staging`)。 + +服务主页还提供了关于**按故障率排序的顶级服务**和**按故障率排序的顶级依赖路径**的信息,帮助您快速识别关键问题和有问题的服务间通信路径。 + +## 服务概览 + +选择服务名称以打开服务详细视图。下图显示了服务概览。 + +*服务概览* + +**概览**选项卡显示汇总服务当前健康状况的指标磁贴,以及以下时间序列图表: + +- **按服务依赖关系的延迟**:按下游依赖关系细分的 P50、P90 和 P99 延迟。 +- **按操作的请求**:随时间变化的每个操作的请求量。 +- **按操作的可用性**:随时间变化的每个操作的可用性百分比。 +- **按操作的故障率和错误率**:随时间变化的每个操作的 `5xx` 故障率和 `4xx` 错误率。 + +## 操作 + +下图显示了操作选项卡。 + +*服务操作* + +**操作**选项卡提供了服务性能的按操作细分。操作表中的每一行代表一个不同的 API 端点或方法,并显示以下指标: + +- **操作名称**:API 端点或方法的名称(例如 `GET /api/products`)。 +- **P50 延迟**:中位数响应时间。 +- **P90 延迟**:第 90 百分位响应时间。 +- **P99 延迟**:第 99 百分位响应时间。 +- **总请求数**:在选定时间范围内此操作的请求总数。 +- **错误率**:导致错误的请求百分比。 +- **可用性**:此操作的可用性百分比。 + +使用列标题按任何指标对操作进行排序,并识别最慢或最容易出错的端点。 + +## 依赖关系 + +下图显示了依赖关系选项卡。 + +*服务依赖关系* + +**依赖关系**选项卡显示所选服务调用的下游服务。对于每个依赖关系,显示以下信息: + +- **依赖服务**:被调用的下游服务的名称。 +- **远程操作**:在下游服务上调用的特定操作。 +- **服务操作**:调用此依赖关系的当前服务上的操作。 +- **P99 延迟**:调用此依赖关系的第 99 百分位响应时间。 +- **P90 延迟**:调用此依赖关系的第 90 百分位响应时间。 +- **P50 延迟**:调用此依赖关系的中位数响应时间。 +- **总请求数**:在选定时间范围内对此依赖关系的请求总数。 +- **错误率**:对此依赖关系的失败调用百分比。 +- **可用性**:此依赖关系路径的可用性百分比。 + +使用此视图可以确定服务中的性能问题是由其自身逻辑引起的,还是由缓慢或失败的下游依赖关系引起的。 + +## 关联 + +APM 提供上下文关联,允许您从服务指标直接导航到相关追踪和日志。可以从**服务主页**、**服务概览**和**操作**页面访问关联。 + +*服务 span 关联* + +查看服务时,您可以: + +- **查看相关追踪**:选择指标或操作以打开显示相关追踪 span 的弹出面板。这有助于您从高层指标深入到促成它的单个请求。 +- **查看相关日志**:弹出面板还显示与所选追踪相关的日志条目,为您提供调试问题的完整上下文。 +- **按属性过滤**:使用服务属性(如环境、操作名称或错误类型)缩小关联结果的范围。 + +有关在追踪和日志数据集之间配置关联的更多信息,请参阅[关联](/observing-your-data/exploring-observability-data/correlations)。 + +## 过滤服务 + +使用**服务**页面顶部的过滤器控件缩小显示的服务列表范围: + +- **环境**:按部署环境过滤(例如 `production`、`staging`、`development`)。 +- **延迟**:过滤超过延迟阈值的服务。 +- **吞吐量**:按请求量过滤服务。 +- **失败率**:过滤失败率超过指定百分比的服务。 + +::: tip TIP +您可以组合多个过滤器以快速隔离符合特定条件的服务,例如失败率大于 5% 的生产服务。 +::: diff --git a/i18n/zh/observing-your-data/classic-observability-apps.md b/i18n/zh/observing-your-data/classic-observability-apps.md new file mode 100644 index 00000000..6d8c8518 --- /dev/null +++ b/i18n/zh/observing-your-data/classic-observability-apps.md @@ -0,0 +1,18 @@ +--- +title: 经典可观测性应用 +--- + +# 经典可观测性应用 + +在经典导航中,OpenSearch Dashboards 在 **Observability** 菜单中提供可观测性应用。这些应用不需要工作空间或在 `opensearch_dashboards.yml` 中进行额外设置。 + +下表描述了这些应用,并列出了每个应用在单个数据源和启用[多数据源](/dashboards/management/multi-data-sources)时是否可用。 + +| 应用 | 描述 | 单数据源 | 多数据源 | +|:---|:---|:---|:---| +| [事件分析](/observing-your-data/event-analytics) | 使用管道处理语言(PPL)查询日志事件并从结果创建可视化。| 是 | 否 | +| [追踪分析](/observing-your-data/trace/) | 查看追踪和服务的仪表板,包括延迟、错误率和吞吐量。| 是 | 是 | +| [指标分析](/observing-your-data/prometheusmetrics) | 查询和可视化存储在 Prometheus 或 OpenSearch 中的 OpenTelemetry 指标索引中的指标。| 是 | 是 | +| [应用程序分析](/observing-your-data/app-analytics) | 将应用程序的日志、追踪和指标组合到其健康状况的单个视图中。| 是 | 否 | +| [运维面板](/observing-your-data/operational-panels) | 将 PPL 可视化组织到仪表板中。| 是 | 否 | +| [笔记本](/dashboards/notebooks) | 将 Markdown 文本、SQL 和 PPL 查询以及可视化组合到报告和运行手册中。| 是 | 是 | diff --git a/i18n/zh/observing-your-data/cross-cluster-search.md b/i18n/zh/observing-your-data/cross-cluster-search.md new file mode 100644 index 00000000..9b719db1 --- /dev/null +++ b/i18n/zh/observing-your-data/cross-cluster-search.md @@ -0,0 +1,88 @@ +--- +title: 在跨集群搜索中使用可观测性应用 +--- + +# 在跨集群搜索中使用可观测性应用 + +使用跨集群搜索,您可以从[事件分析](/observing-your-data/event-analytics)或可观测性工作空间中的日志页面查询远程 OpenSearch 集群中的索引。您在本地集群上运行管道处理语言(PPL)查询,本地集群将其转发到远程集群并返回合并的结果。 + +## 先决条件 + +在查询远程集群之前,请确保满足以下先决条件: + +- 本地集群可以访问远程集群中至少一个节点的传输端口(默认为 `9300`)。 +- 如果启用了 Security 插件,则用户在本地集群上具有 PPL 权限,并在远程集群上对查询的索引具有读取权限。有关更多信息,请参阅[设置权限](/search-plugins/cross-cluster-search#setting-permissions)。 + +## 连接到远程集群 + +在本地集群上,通过为其提供名称和一个或多个节点的地址来注册远程集群: + +```json +PUT _cluster/settings +{ + "persistent": { + "cluster.remote": { + "my-remote-cluster": { + "seeds": ["<remote-node-address>:9300"] + } + } + } +} +``` + +要验证连接,请发送以下请求: + +```json +GET _remote/info +``` + +当连接成功时,响应包含远程集群的 `"connected": true`。有关响应的更多信息,请参阅[远程集群信息](/api-reference/cluster-api/remote-info)。 + +有关连接集群的更多信息,包括节点角色要求以及 Docker、Kubernetes 和代理设置示例,请参阅[跨集群搜索](/search-plugins/cross-cluster-search)。 + +## 查询远程集群 + +在 PPL 查询中,将远程索引指定为 `<remote-cluster-name>:<index-name>`。您可以在单个查询中查询多个集群,如下表所示。 + +| 查询 | 搜索 | +|:---|:---| +| `source = my-remote-cluster:application-logs` | `my-remote-cluster` 中的 `application-logs` 索引 | +| `source = *:application-logs` | 每个连接的远程集群中的 `application-logs` 索引 | +| `source = application-logs, my-remote-cluster:application-logs` | 本地集群和 `my-remote-cluster` 中的 `application-logs` 索引 | + +### 使用事件分析 + +要在事件分析中查询远程集群,请按照以下步骤操作: + +1. 在顶部菜单上,转到 **Observability** > **Logs**,然后选择 **Event Explorer**。 +1. 在查询栏中,输入指定远程索引的 PPL 查询。例如,以下查询返回 `my-remote-cluster` 中 `application-logs` 索引的服务器错误: + + ```sql + source = my-remote-cluster:application-logs | where status >= 500 | fields @timestamp, service, status, message + ``` + +1. 选择时间范围,然后选择 **Run**。 + +### 使用可观测性工作空间 + +在可观测性工作空间中,您可以在[日志](/observing-your-data/exploring-observability-data/discover-logs)页面上查询远程集群。数据集不能包含远程索引,因此您需要在查询中指定远程索引。 + +要在可观测性工作空间中查询远程集群,请按照以下步骤操作: + +1. 在您的可观测性工作空间中,转到 **Logs**。 +1. 选择一个数据集。 +1. 在查询编辑器中,将 `source` 替换为远程索引,例如,`source = my-remote-cluster:application-logs | where status >= 500`。 +1. 选择时间范围,然后运行查询。 + +## 常见问题 + +本节描述常见问题及其解决方案。 + +### 查询失败并显示 `no such index` 错误 + +如果远程索引上的 PPL 查询失败并显示 `no such index` 错误,即使该索引在远程集群上存在,请在本地集群上创建一个与远程索引具有相同名称和映射的空索引。查询将返回远程集群的文档,而不是本地索引的文档。 + +## 相关文档 + +- 有关设置示例和安全配置,请参阅[跨集群搜索](/search-plugins/cross-cluster-search)。 +- 有关 PPL 限制和跨集群查询的身份验证详细信息,请参阅 [SQL 插件文档中的跨集群搜索](https://github.com/opensearch-project/sql/blob/main/docs/user/ppl/admin/cross_cluster_search.md)。 diff --git a/i18n/zh/observing-your-data/exploring-data.md b/i18n/zh/observing-your-data/exploring-data.md new file mode 100644 index 00000000..a01dc014 --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-data.md @@ -0,0 +1,39 @@ +--- +title: 探索可观测性数据 +--- + +# 探索可观测性数据 + +OpenSearch Dashboards 提供了两套可观测性应用程序。您使用哪一套取决于 OpenSearch Dashboards 的配置方式: + +- [经典可观测性应用程序](/observing-your-data/classic-observability-apps) 在经典导航的 **Observability** 菜单中可用,无需额外设置。 +- [可观测性工作区应用程序](/observing-your-data/exploring-observability-data/) 在可观测性工作区中可用。要使用它们,请在 `opensearch_dashboards.yml` 中启用工作区和可观测性设置,然后创建一个可观测性工作区。有关所需设置,请参阅[先决条件](/observing-your-data/exploring-observability-data/#prerequisites)。应用程序性能监控(APM)、服务级别目标(SLO)和代理监控仅在工作区中可用。 + +下表列出了您在每套应用程序中用于执行各项任务的应用程序。 + +| 任务 | 经典可观测性应用程序 | 可观测性工作区应用程序 | +|:---|:---|:---| +| 探索日志 | [事件分析](/observing-your-data/event-analytics) | [日志](/observing-your-data/exploring-observability-data/discover-logs) | +| 探索追踪 | [追踪分析](/observing-your-data/trace/) | [追踪](/observing-your-data/exploring-observability-data/discover-traces)、[代理监控](/observing-your-data/agent-traces/) | +| 探索指标 | [指标分析](/observing-your-data/prometheusmetrics) | [指标](/observing-your-data/exploring-observability-data/discover-metrics) | +| 监控应用程序 | [应用程序分析](/observing-your-data/app-analytics) | [应用程序性能监控](/observing-your-data/apm/),包括[服务](/observing-your-data/apm/services)、[拓扑图](/observing-your-data/apm/application-map)和[SLO](/observing-your-data/slo/) | +| 构建仪表板 | [运维面板](/observing-your-data/operational-panels) | [仪表板](/dashboards/dashboard/) | + +## 选择追踪工具 + +多个应用程序可以显示追踪数据。下表描述了每个应用程序及其可用位置。 + +| 应用程序 | 用于 | 可用位置 | +|:---|:---|:---| +| [追踪分析](/observing-your-data/trace/) | 查看预构建的追踪和服务仪表板,包括使用 Data Prepper 或 Jaeger 采集的数据的延迟、错误率和吞吐量。 | 经典导航和可观测性工作区 | +| [追踪](/observing-your-data/exploring-observability-data/discover-traces) | 搜索和过滤跨度,并将单个追踪显示为其跨度的时间线。 | 可观测性工作区 | +| [应用程序性能监控](/observing-your-data/apm/) | 查看每个服务的速率、错误和持续时间(RED)指标以及服务依赖关系的拓扑图。 | 可观测性工作区 | +| [代理监控](/observing-your-data/agent-traces/) | 查看生成式 AI 代理的步骤、工具调用和令牌使用情况。 | 可观测性工作区 | + +在可观测性工作区中,当 APM 和 Discover Traces 都启用时,APM 会替换追踪分析。有关启用每个应用程序的设置,请参阅[可观测性工作区应用程序](/observing-your-data/exploring-observability-data/)。 + +有关 OpenSearch 为其处理的请求生成的追踪,请参阅[分布式追踪](/tuning-your-cluster/monitoring/telemetry/distributed-tracing/)。 + +## 可视化您的数据 + +要与您的团队共享可视化,请将它们添加到仪表板。在经典导航中,使用[运维面板](/observing-your-data/operational-panels);在可观测性工作区中,从日志页面将它们添加到[仪表板](/observing-your-data/exploring-observability-data/discover-logs#adding-visualizations-to-dashboards)。要将可视化、查询和文本组合成报告和运行手册,请使用[笔记本](/dashboards/notebooks),它在经典导航和可观测性工作区中都可用。 diff --git a/i18n/zh/observing-your-data/exploring-observability-data/correlations.md b/i18n/zh/observing-your-data/exploring-observability-data/correlations.md new file mode 100644 index 00000000..1522e0c3 --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-observability-data/correlations.md @@ -0,0 +1,131 @@ +--- +title: 关联 +--- + +# 关联 +<Badge type="tip" text="3.5 版本引入" /> + +关联允许您将追踪数据集与日志数据集链接,使您能够在分析分布式追踪时查看相关的日志条目。关联数据集可以帮助您通过将追踪跨度与其相应的应用程序日志连接起来,快速识别问题的根本原因。 + +在对分布式系统进行故障排除时,您通常需要关联多个来源的数据。追踪可能显示请求失败,但详细的错误信息在您的应用程序日志中。使用关联,您可以: + +- 将单个追踪数据集链接到最多五个日志数据集。 +- 直接从跨度详情面板查看相关日志。 +- 在追踪分析和日志探索之间无缝导航。 + +## 前提条件 + +在使用关联之前,请确保您已满足以下前提条件: + +1. **启用功能标志**:将以下设置添加到您的 `opensearch_dashboards.yml` 文件: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + datasetManagement.enabled: true + ``` + + 更新配置文件后,重启 OpenSearch Dashboards 以使更改生效。 + +1. **创建数据集**:您必须至少配置一个追踪数据集和一个日志数据集。有关详细说明,请参阅[数据集](/observing-your-data/exploring-observability-data/datasets)。 + +1. **配置架构映射**:您的日志数据集必须配置架构映射。至少,您需要映射 **Trace ID** 字段,以便日志可以与追踪匹配。 + +## 关联要求 + +为了使关联正常工作,您的日志数据必须包含以下可以映射到追踪上下文的字段。 + +| 字段 | 目的 | +|:------|:--------| +| **Trace ID** | 将日志条目链接到特定追踪 | +| **Span ID** | 将日志条目链接到特定跨度 | +| **Service name** | 按服务过滤日志 | +| **Timestamp** | 按时间顺序排列日志条目 | + +如果您的日志不遵循 OpenTelemetry 约定,请在日志数据集中配置架构映射,以将您的自定义字段名称映射到这些标准字段。 + +## 创建追踪到日志的关联 + +要在追踪数据集和日志数据集之间创建关联,请按照以下步骤操作: + +1. 在左侧导航栏中导航到**数据集**。 + +2. 选择要与日志关联的追踪数据集。 + +3. 在数据集详情页面中,选择**关联的数据集**选项卡,如下图所示。 + + *追踪数据集关联的数据集选项卡* + +4. 选择**配置关联**。 + +5. 在**配置关联**对话框中,选择最多五个日志数据集与此追踪数据集关联,如下图所示。 + + *配置关联对话框* + +6. 选择**保存**以创建关联。 + +7. 关联的日志数据集现在出现在**关联的数据集**表中,如下图所示。 + + *表中创建的关联* + +## 在日志数据集中查看关联 + +您可以从日志数据集详情中查看与日志数据集关联的追踪数据集: + +1. 在左侧导航栏中导航到**数据集**。 + +2. 选择已与追踪数据集关联的日志数据集。 + +3. 选择**关联的追踪**选项卡以查看与此日志数据集链接的追踪数据集,如下图所示。 + + *日志数据集关联的追踪选项卡* + +::: info NOTE +此视图是只读的。要修改关联,您必须从追踪数据集中编辑它们。 +::: + +## 在追踪页面中使用关联 + +创建关联后,您可以在分析追踪时访问相关日志。 + +### 在跨度详情中查看相关日志 + +1. 在左侧导航栏中,选择**应用程序性能** > **追踪**。 + +2. 选择一个追踪以查看其详情。 + +3. 在追踪中选择一个跨度以打开**跨度详情**。 + +4. 在**跨度详情**中,选择**日志**选项卡以打开**相关日志**,如下图所示。相关日志是通过将跨度的追踪 ID 与关联的日志数据集中的日志条目匹配来检索的。 + + *带有相关日志的跨度详情* + +6. 选择日志条目以查看其完整详情或导航到**日志**页面进行进一步探索。 + +## 管理关联 + +您可以从追踪数据集详情页面编辑或删除关联。 + +### 编辑关联 + +要修改现有关联,请按照以下步骤操作: + +1. 在左侧导航栏中导航到**数据集**并选择要修改的追踪数据集。 +2. 选择**关联的数据集**选项卡。 +3. 选择**配置关联**以修改关联的日志数据集列表。 +4. 根据需要添加或删除数据集。 +5. 选择**保存**以应用更改。 + +### 删除关联 + +要删除关联: + +1. 在左侧导航栏中导航到**数据集**并选择要修改的追踪数据集。 +2. 选择**关联的数据集**选项卡。 +3. 使用删除图标删除配置的关联。 + +## 相关文档 + +- [数据集](/observing-your-data/exploring-observability-data/datasets) -- 创建和管理数据集。 +- [Data Prepper](/data-prepper/) -- 将 OpenTelemetry 数据摄取到 OpenSearch。 diff --git a/i18n/zh/observing-your-data/exploring-observability-data/datasets.md b/i18n/zh/observing-your-data/exploring-observability-data/datasets.md new file mode 100644 index 00000000..6e8b0aa3 --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-observability-data/datasets.md @@ -0,0 +1,136 @@ +--- +title: 数据集 +--- + +# 数据集 +<Badge type="tip" text="3.5 版本引入" /> + +_数据集_表示您想要一起分析的索引集合。数据集提供了一种用户友好的方式来组织和访问 OpenSearch Dashboards 中的可观测性数据。数据集允许您为数据源和索引分配类型、名称和描述,使处理日志和追踪变得更容易。 + +与传统索引模式相比,数据集具有以下几个优势: + +- **用户友好的名称**:分配描述性名称,而不是依赖索引模式语法。 +- **描述**:添加有关数据集包含什么数据的上下文。 +- **架构映射**:将非标准格式的字段映射到 OpenTelemetry 兼容字段以进行关联。 +- **特定类型的行为**:日志和追踪数据集与各自的 Discover 页面集成。 + +## 数据集类型 + +OpenSearch 支持以下数据集类型。 + +| 类型 | 描述 | 用例 | +|:-----|:------------|:---------| +| **日志** | 用于分析和探索的通用日志数据 | 应用程序日志、系统日志、访问日志 | +| **追踪** | 通过 OpenSearch Data Prepper 摄取的 OpenTelemetry 跨度数据 | 分布式追踪、性能监控 | + +## 前提条件 + +在使用数据集之前,请确保您已满足以下前提条件: + +1. **启用功能标志**:将以下设置添加到您的 `opensearch_dashboards.yml` 文件: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + datasetManagement.enabled: true + # 从其他 OpenSearch 集群中的索引创建数据集所需 + data_source.enabled: true + ``` + + `data_source.enabled` 设置启用多个数据源。有关更多信息,请参阅[配置和使用多个数据源](/dashboards/management/multi-data-sources)。启用多个数据源时,某些经典可观测性应用程序不可用。有关更多信息,请参阅[经典可观测性应用程序](/observing-your-data/classic-observability-apps)。 + + 更新配置文件后,重启 OpenSearch Dashboards 以使更改生效。 + +1. **索引数据**:您的日志或追踪数据必须已经在 OpenSearch 中建立索引。 + +1. **确保适当的权限**:您需要在工作区中创建和管理数据集的权限。 + +## 创建日志数据集 + +要创建日志数据集,请按照以下步骤操作: + +1. 在工作区左侧导航栏中,选择**数据集**。 + +2. 选择**创建数据集**并从下拉菜单中选择**日志**。 + +3. 在**步骤 1:选择数据**中,选择您的数据源,如下图所示。您可以使用通配符模式(例如,`logs-*`)来匹配多个索引。 + + *选择数据源* + +4. 在**步骤 2:配置数据**中,配置数据集设置,如下图所示。 + + *配置日志数据集设置* + + 您可以配置以下设置: + + - **名称** -- 为数据集输入描述性名称。 + - **描述**(可选)-- 添加数据描述。 + - **时间字段**:选择用于基于时间的查询的时间戳字段。 + - **架构映射**(可选)-- 将您的日志字段映射到标准 OpenTelemetry 字段以与追踪关联: + - **Trace ID 字段**:包含追踪标识符的字段。 + - **Span ID 字段**:包含跨度标识符的字段。 + - **Service name 字段**:包含服务名称的字段。 + - **Timestamp 字段**:包含事件时间戳的字段。 + +5. 选择**创建数据集**以保存您的配置。 + +## 创建追踪数据集 + +要创建追踪数据集,请按照以下步骤操作: + +1. 在工作区左侧导航栏中,选择**数据集**。 + +2. 选择**创建数据集**并从下拉菜单中选择**追踪**。 + +3. 在**步骤 1:选择数据**中,选择您的追踪数据源。数据源必须引用包含使用 Data Prepper 摄取的 OpenTelemetry 跨度数据的索引。 + +4. 在**步骤 2:配置数据**中,配置数据集设置,如下图所示。 + + *配置追踪数据集设置* + + 您可以配置以下设置: + + - **名称** -- 为数据集输入描述性名称。 + - **描述**(可选)-- 添加数据描述。 + - **时间字段** -- 选择时间戳字段(通常为 `startTime` 或 `@timestamp`)。 + +5. 选择**创建数据集**以保存您的配置。 + +## 查看数据集 + +创建数据集后,您可以使用以下步骤从**数据集**页面查看和管理它们: + +1. 在工作区左侧导航栏中,选择**数据集**。 + +2. 列表视图显示所有数据集及其名称、类型和数据源,如下图所示。 + + *数据集列表视图* + +3. 选择数据集以查看其详情,包括配置设置和任何关联。 + +## 在 Discover 页面中分析数据集 + +数据集与 Discover 界面集成,用于探索您的数据。 + +### 日志数据集 + +要分析日志数据集,请按照以下步骤操作: + +1. 在左侧导航栏中,选择**日志**。 +2. 从数据集选择器中,选择您的日志数据集。 +3. 使用管道处理语言(PPL)查询来探索和分析您的日志数据。 + +### 追踪数据集 + +要分析追踪数据集,请按照以下步骤操作: + +1. 在左侧导航栏中,选择**应用程序性能** > **追踪**。 +2. 从数据集选择器中选择您的追踪数据集。 +3. 探索跨度数据和追踪流。 + +## 相关文档 + +- [索引模式](/dashboards/management/index-patterns) -- 将数据集与传统索引模式进行比较。 +- [Data Prepper](/data-prepper/) -- 将 OpenTelemetry 数据摄取到 OpenSearch。 +- [关联](/observing-your-data/exploring-observability-data/correlations) -- 链接追踪和日志数据集。 diff --git a/i18n/zh/observing-your-data/exploring-observability-data/discover-logs.md b/i18n/zh/observing-your-data/exploring-observability-data/discover-logs.md new file mode 100644 index 00000000..79a14d8b --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-observability-data/discover-logs.md @@ -0,0 +1,164 @@ +--- +title: 日志 +--- + +# 在 Discover 中分析日志 +<Badge type="tip" text="3.5 版本引入" /> + +OpenSearch Dashboards 中的**日志**页面是一个日志分析工具,允许您使用管道处理语言(PPL)探索和分析应用程序日志。在此页面上,您可以查询日志数据,从聚合结果创建可视化,并将这些可视化添加到仪表板。 + +**日志**页面提供以下功能: + +- **基于 PPL 的查询**:使用 PPL 语法过滤、聚合和转换日志数据。 +- **自动可视化**:当您使用聚合命令(如 `stats`)时,界面会自动切换到可视化视图。 +- **多种可视化类型**:从各种可视化类型中进行选择。 +- **仪表板集成**:将可视化直接保存到新的或现有的仪表板。 +- **查询管理**:保存查询以供重用并访问最近的查询。 + +## 前提条件 + +在使用**日志**页面之前,请确保您已满足以下前提条件: + +1. **启用功能标志**:将以下设置添加到您的 `opensearch_dashboards.yml` 文件: + + ```yaml + workspace.enabled: true + explore.enabled: true + ``` + + 更新配置文件后,重启 OpenSearch Dashboards 以使更改生效。 + +2. **创建可观测性工作区**:您必须在可观测性工作区中工作。**日志**页面仅在此工作区类型中可用。 + + ::: info NOTE + 注意:工作区不兼容多租户。要启用工作区,您必须首先通过设置 `opensearch_security.multitenancy.enabled: false` 来禁用多租户。 + ::: + +3. **配置日志数据集**:您必须至少配置一个日志数据集。有关详细说明,请参阅[数据集](/observing-your-data/exploring-observability-data/datasets)。 + +## 访问日志页面 + +要访问**日志**页面: + +1. 在 OpenSearch Dashboards 中导航到可观测性工作区。 +2. 在左侧导航栏中,选择**日志**。 + +## 探索日志数据 + +**日志**页面如下图所示。 + +*Discover 日志界面* + +它由以下组件组成: + +- **PPL 编辑器**:页面顶部的查询栏,您可以在其中编写 PPL 查询。 +- **数据集选择器**:从页面顶部的下拉列表中选择要探索的日志数据集。 +- **最近查询**:在页面顶部访问之前运行的查询。 +- **已保存查询**:在页面顶部访问您已保存以供重用的查询。 +- **字段**:位于左侧的**字段**面板显示可用字段,分为**已选择**字段和**查询**字段部分。 +- **日志计数**:**日志计数**直方图显示日志条目随时间的分布。使用**间隔**选择器调整时间桶大小。 +- **结果区域**:显示查询结果,有两个选项卡: + - **日志**:以表格格式显示单个日志条目。 + - **可视化**:当使用 `stats` 命令时,将聚合数据显示为图表。 +- **时间范围选择器**:位于右上角,允许您设置查询的时间范围。 + +## 使用 PPL 查询日志 + +您可以使用 PPL 查询日志数据。PPL 允许您使用管道字符(`|`)链接命令来过滤、转换和聚合数据。 + +### 基本查询 + +要从您的数据集检索所有日志,请通过输入查询并选择**刷新**来运行不带任何过滤器的查询。结果显示在**日志**选项卡中,显示单个日志条目。 + +### 使用 WHERE 子句过滤 + +使用 `WHERE` 子句根据字段值过滤日志: + +```sql +| WHERE `resource.attributes.service.name` = 'frontend-proxy' +``` + +您可以通过提供多个 `WHERE` 子句来组合多个条件: + +```sql +| WHERE `resource.attributes.service.name` = 'frontend-proxy' +| WHERE `attributes.url.path` in ("/api/cart","/api/checkout") +``` + +### 管理查询 + +**日志**页面提供工具来帮助您有效地组织和重用 PPL 查询。 + +- **最近查询**:选择**最近查询**以查看和重新运行之前执行的查询。 +- **已保存查询**:选择**已保存查询**以访问您已保存的查询。要保存当前查询,请选择**操作** > **保存查询**。 + +## 从日志创建可视化 + +当您使用 `stats` 命令聚合数据时,**日志**页面会自动切换到**可视化**选项卡以将结果显示为图表。 + +### 使用 stats 命令 + +`stats` 命令根据指定的字段聚合数据。例如,要按 URL 路径分组的每分钟日志计数,请使用以下查询: + +```sql +| WHERE `resource.attributes.service.name` = 'frontend-proxy' +| WHERE `attributes.url.path` in ("/api/cart","/api/checkout") +| STATS count() by span(time, 1m), `attributes.url.path` +``` + +运行此查询时,界面会自动切换到**可视化**选项卡并显示图表,如下图所示。 + +*日志中的可视化* + +### 可视化类型 + +要更改可视化类型,请转到**设置** > **可视化类型**并选择可用选项之一,如下图所示。 + +*可视化类型选项* + +以下可视化类型可用。 + +| 类型 | 描述 | +|:-----|:------------| +| **折线图** | 将数据显示为连接的点;非常适合显示随时间的趋势。 | +| **面积图** | 类似于折线图,但线下方的区域被填充。 | +| **柱状图** | 将数据显示为垂直或水平条形图,用于比较类别。 | +| **指标** | 将单个聚合值显示为大数字。| +| **状态时间线** | 在水平时间线上显示状态变化。 | +| **热图** | 使用颜色强度在矩阵格式中表示值。 | +| **条形仪表** | 将值显示为具有可配置阈值的水平条。 | +| **饼图** | 将比例显示为圆形图表的切片。 | + +### 可视化设置 + +要自定义您的可视化,请更新**设置**面板中的选项,如下图所示。 + +*切换轴的柱状图* + +您可以更新以下选项: + +- **字段**:配置要在 **X 轴**、**Y 轴**和**颜色**上显示的字段(用于按不同值对数据系列进行分组)。对于柱状图,您可以在字段部分切换**切换轴**以将图表方向从垂直更改为水平(交换 X 和 Y 轴)。 +- **条形/桶**:对于柱状图,配置条形大小(**自动**或**手动**)和桶设置(**类型**和**间隔**)。 +- **阈值**:使用自定义颜色定义值阈值。 +- **轴**:配置轴标签、比例和格式。 +- **图例**:控制图例可见性和位置。 + +## 将可视化添加到仪表板 + +您可以使用以下步骤将可视化直接保存到仪表板以进行持续监控: + +1. 创建可视化后,在结果区域中选择**添加到仪表板**。 + +2. 在**保存并添加到仪表板**对话框中,选择以下选项之一: + - **保存到现有仪表板**:从下拉列表中选择现有仪表板。 + - **保存到新仪表板**:输入新仪表板的名称。 + +3. 在**保存搜索**字段中输入已保存搜索的名称。 + +4. 选择**添加**以将可视化保存到仪表板。 + +## 相关文档 + +- [数据集](/observing-your-data/exploring-observability-data/datasets) -- 创建和管理日志数据集。 +- [PPL](/search-plugins/sql/ppl/) -- 学习 PPL 查询语法。 +- [关联](/observing-your-data/exploring-observability-data/correlations) -- 链接日志和追踪数据集。 diff --git a/i18n/zh/observing-your-data/exploring-observability-data/discover-metrics.md b/i18n/zh/observing-your-data/exploring-observability-data/discover-metrics.md new file mode 100644 index 00000000..e7d41c6a --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-observability-data/discover-metrics.md @@ -0,0 +1,109 @@ +--- +title: 指标 +--- + +# 在 Discover 中分析指标 +<Badge type="tip" text="3.5 版本引入" /> + +OpenSearch Dashboards 中的**指标**页面提供了一个专用界面,用于发现、查询和可视化时间序列指标数据。此页面如下图所示,针对使用 PromQL 处理 Prometheus 指标进行了优化。 + +*指标页面界面* + +**指标**页面在可观测性工作区中可用。要访问**指标**页面,请导航到**可观测性**工作区。然后,在左侧导航栏中,选择**指标**。 + +## 前提条件 + +在使用**指标**页面之前,请确保您已满足以下前提条件: + +1. **启用功能标志**:将以下设置添加到您的 `opensearch_dashboards.yml` 文件: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverMetrics.enabled: true + ``` + + 更新配置文件后,重启 OpenSearch Dashboards 以使更改生效。 + +1. **创建可观测性工作区**:您必须在可观测性工作区中工作。**指标**页面仅在此工作区类型中可用。 + +1. **配置 Prometheus 数据源**:您必须配置 Prometheus 数据源。有关说明,请参阅[配置 Prometheus 数据源](#configuring-a-prometheus-data-source)。 + +## 配置 Prometheus 数据源 + +在开始之前,请使用以下方法之一配置 Prometheus 数据源。 + +### 在 OpenSearch Dashboards 中配置 Prometheus 数据源 + +要在 OpenSearch Dashboards 中配置 Prometheus 数据源,请按照以下步骤操作: + +1. 在左侧导航栏中,转到**数据管理** > **数据源**。 +1. 选择**创建数据源**。 +1. 选择 **Prometheus**。 +1. 输入**数据源名称**和可选的**描述**。 +1. 输入 **Prometheus URI** 端点(例如,`http://prometheus-server:9090`)。 +1. 配置**身份验证方法**: + - **无身份验证**:如果您的 Prometheus 服务器不需要身份验证,请使用此选项。 + - **基本身份验证**:输入用户名和密码。 + - **AWS Signature Version 4**:用于 Amazon Managed Service for Prometheus。 +1. 选择**连接**。 + +### 使用 API 配置 Prometheus 数据源 + +或者,您可以以编程方式配置 Prometheus 数据源。有关更多信息,请参阅[数据源](/dashboards/management/data-sources)。 + +## 查询面板 + +您可以在**指标**页面顶部的查询面板中编写和执行指标查询。查询编辑器为 PromQL 提供自动完成建议和语法高亮显示。 + +### 编写查询 + +使用 PromQL 语法编写查询。例如: + +```json +up{job="prometheus"} +``` + +### 运行查询 + +要运行查询,请在查询编辑器中输入您的查询,然后选择**刷新**按钮。 + +您可以通过用分号(`;`)分隔多个 PromQL 查询来一起运行它们: + +```json +up{job="prometheus"}; +node_cpu_seconds_total{mode="idle"}; +``` + +每个查询独立运行,结果在输出中组合。 + +## 时间过滤器 + +使用时间过滤器指定指标数据的时间范围。选择 <img src="/images/icons/calendar-icon.png" class="inline-icon" alt="calendar icon"/>(日历)图标以访问时间过滤器选项: + +- **快速选择**:选择相对时间范围(例如,最近 15 分钟或最近 1 小时)。 +- **常用**:从预定义的时间范围中选择。 +- **自定义**:指定绝对开始和结束时间。 +- **自动刷新**:设置自动刷新间隔。 + +有关更多信息,请参阅[时间过滤器](/dashboards/discover/time-filter)。 + +## 查看结果 + +运行查询后,结果将显示在包含以下视图的选项卡式界面中: + +- **指标**选项卡以表格格式显示每个系列的最新数据点。 + +- **原始**选项卡将每个系列的最新数据点显示为数据源返回的原始 JSON。 + +- **可视化**选项卡为您的指标数据提供交互式图表。 + +#### 配置可视化 + +选择**可视化**选项卡后,屏幕右侧会出现一个设置面板。使用此面板可以: + +1. **选择图表类型**:从折线图、柱状图、饼图、仪表或表格可视化中进行选择。 +2. **映射轴**:将字段分配给 X 和 Y 轴。 +3. **自定义样式**:调整颜色、图例、网格线和其他视觉选项。 + +修改设置时,可视化会自动更新。 diff --git a/i18n/zh/observing-your-data/exploring-observability-data/discover-traces.md b/i18n/zh/observing-your-data/exploring-observability-data/discover-traces.md new file mode 100644 index 00000000..d9a474ca --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-observability-data/discover-traces.md @@ -0,0 +1,110 @@ +--- +title: 追踪 +--- + +# 在 Discover 中分析追踪 +<Badge type="tip" text="3.5 版本引入" /> + +OpenSearch Dashboards 中的 Discover **追踪**页面提供了一种增强的方式来探索和分析可观测性工作区中的追踪数据。此页面通过为处理追踪数据提供专门的功能,扩展了传统的 Discover 体验。 + +## 前提条件 + +在使用**追踪**页面之前,请确保您已满足以下前提条件: + +1. **启用功能标志**:将以下设置添加到您的 `opensearch_dashboards.yml` 文件: + + ```yaml + workspace.enabled: true + explore.enabled: true + explore.discoverTraces.enabled: true + ``` + + 更新配置文件后,重启 OpenSearch Dashboards 以使更改生效。 + +2. **创建可观测性工作区**:您必须在可观测性工作区中工作。**追踪**页面仅在此工作区类型中可用。 + + ::: info NOTE + 注意:工作区不兼容多租户。要启用工作区,您必须首先通过设置 `opensearch_security.multitenancy.enabled: false` 来禁用多租户。 + ::: + +3. **配置追踪数据集**:您必须至少配置一个追踪数据集。有关详细说明,请参阅[数据集](/observing-your-data/exploring-observability-data/datasets)。 + +## 访问追踪页面 + +要访问**追踪**页面: + +1. 在 OpenSearch Dashboards 中导航到**可观测性**工作区。 +2. 在左侧导航栏中,选择**应用程序性能** > **追踪**。 + +*导航中的 Discover 追踪页面* + +## 配置追踪数据集 + +要配置追踪数据集,请使用以下选项之一。 + +### 自动创建数据集 + +如果您的数据源遵循 OpenTelemetry 命名约定,**追踪**页面可以通过搜索具有以下命名模式的索引从您的数据中自动创建追踪和日志数据集: + +- **追踪**:`otel-v1-apm-span*` +- **关联的日志**:`logs-otel-v1*` + +检测到这些索引后,选择**创建追踪数据集**按钮(如下图所示)以自动生成数据集并建立追踪和日志之间的关联关系。 + +*自动创建追踪数据集* + +### 手动创建数据集 + +如果您的索引使用不同的命名约定,您必须手动创建数据集并配置追踪和日志之间的关联关系。导航到**数据集**选项卡,并创建一个具有**追踪**信号类型的数据集。 + +## 探索追踪数据 + +**追踪**页面提供了全面的工具来分析跨度数据和了解追踪性能,包括: + +- **RED 指标**:在页面顶部查看速率、错误和持续时间(RED)指标,以快速评估追踪性能和健康状况。 +- **分面字段**:使用分面字段过滤器来过滤和分析追踪的特定方面。 +- **跨度表**:使用可排序的列浏览跨度,并快速访问详细信息。 + +### 查看特定跨度 + +要查看特定跨度的详细信息,请在跨度表中选择时间戳。这将打开**追踪详情**浮窗,如下图所示。 + +*追踪详情浮窗* + +**追踪详情**浮窗显示以下信息: + +- 所选跨度在其父追踪中的关系。 +- 显示跨度如何与同一追踪中的其他跨度相关的层次结构。 +- 跨度属性和元数据。 + +### 追踪详情页面 + +要从**追踪详情**浮窗访问完整的追踪详情页面,请使用以下选项之一: + +- 从**追踪**页面表中选择 **span ID**。 +- 从浮窗中选择**打开完整页面**。 + +完整页面视图提供了一个扩展的界面,用于更深入的追踪分析,具有时间线可视化,显示层次跨度关系和持续时间,以及侧面板中的详细跨度信息,如下图所示。 + +*带有 RED 指标和分面字段的 Discover 追踪页面* + +## 将追踪与日志关联 + +**追踪**页面提供与日志数据的无缝集成,使您能够在保留适当上下文的同时从追踪导航到相关日志。 + +### 查看相关日志 + +要查看相关日志,请按照以下步骤操作: + +1. 在**追踪详情**浮窗中,找到**相关日志**部分。 +1. 选择**在 Discover 日志中查看**按钮以导航到所选追踪的关联日志条目,如下图所示。 + +*追踪详情中的相关日志按钮* + +### 带上下文的日志重定向 + +当您选择**在 Discover 日志中查看**时,OpenSearch Dashboards 会自动将您重定向到应用了追踪上下文的**日志**页面,如下图所示。 + +*带有追踪上下文的 Discover 日志页面* + +日志被过滤以仅显示与所选追踪相关的条目,从而更容易排除问题并了解追踪事件的完整上下文。保留上下文通过提供遥测数据的统一视图来简化调试过程,帮助您识别根本原因并了解应用程序行为的完整情况。 diff --git a/i18n/zh/observing-your-data/exploring-observability-data/index.md b/i18n/zh/observing-your-data/exploring-observability-data/index.md new file mode 100644 index 00000000..1876ecb0 --- /dev/null +++ b/i18n/zh/observing-your-data/exploring-observability-data/index.md @@ -0,0 +1,65 @@ +--- +title: 可观测性工作区应用程序 +description: "设置可观测性工作区,以在 Discover 中探索日志、追踪和指标,并使用应用程序性能监控、服务级别目标和代理监控。" +--- + +# 可观测性工作区应用程序 +<Badge type="tip" text="3.5 版本引入" /> + +在可观测性[工作区](/dashboards/workspace/)中,OpenSearch Dashboards 提供了用于在 Discover 中探索日志、追踪和指标的应用程序,监控应用程序性能,跟踪服务级别目标(SLO)以及监控生成式 AI 代理。每个应用程序都由 `opensearch_dashboards.yml` 中的设置启用,该设置列在应用程序的页面上。 + +## 前提条件 + +要启用所有可观测性工作区应用程序,请将以下设置添加到 `opensearch_dashboards.yml`,然后重启 OpenSearch Dashboards: + +```yaml +workspace.enabled: true +explore.enabled: true # 日志 +explore.discoverTraces.enabled: true # 追踪、APM 和 SLO +explore.discoverMetrics.enabled: true # 指标和 APM +explore.agentTraces.enabled: true # 代理监控 +datasetManagement.enabled: true # 数据集和关联 +observability.slo.enabled: true # SLO +``` + +要仅启用部分应用程序,请参阅每个应用程序页面的前提条件部分,了解该应用程序所需的设置。 + +工作区有额外的要求,例如禁用多租户。有关更多信息,请参阅[启用工作区](/dashboards/workspace/workspace#enabling-workspaces)。 + +## 创建可观测性工作区 + +要创建可观测性工作区,请按照以下步骤操作: + +1. 在 OpenSearch Dashboards 主页上,在**我的工作区**中,选择**可观测性**卡片上的**创建工作区**。 +1. 在**工作区详情**中,输入**名称**,以及可选的**描述**。 +1. 在**用例和功能**中,确认已选择**可观测性**。 +1. 如果您使用多个数据源,请选择要与工作区关联的数据源。 +1. 选择**创建工作区**。 + +有关更多信息,请参阅[创建工作区](/dashboards/workspace/create-workspace)。 + +## 探索和监控您的数据 + +创建工作区后,按以下方式使用应用程序: + +1. 连接您的数据: + - 为您的日志和追踪索引创建[数据集](/observing-your-data/exploring-observability-data/datasets)。日志和追踪页面、关联以及 APM 使用数据集查找您的数据。 + - 要使用指标、APM 或 SLO,请连接 [Prometheus 数据源](/dashboards/management/connect-prometheus)。 +1. 探索您的数据: + - 使用[日志](/observing-your-data/exploring-observability-data/discover-logs)通过管道处理语言(PPL)搜索、过滤和可视化日志数据。 + - 使用[追踪](/observing-your-data/exploring-observability-data/discover-traces)搜索和过滤跨度,并将单个追踪作为其跨度的时间线查看。 + - 使用[指标](/observing-your-data/exploring-observability-data/discover-metrics)使用 PromQL 查询和可视化 Prometheus 指标。 + - 使用[关联](/observing-your-data/exploring-observability-data/correlations)将追踪数据集链接到日志数据集,以便您可以查看与追踪相关的日志条目。 +1. 监控您的应用程序: + - 使用[应用程序性能监控(APM)](/observing-your-data/apm/)查看每个服务的速率、错误和持续时间(RED)指标以及服务依赖关系的拓扑图。 + - 使用 [SLO](/observing-your-data/slo/) 为您的服务定义可用性和延迟目标,并跟踪它们的错误预算。 +1. 监控您的 AI 代理: + - 使用[代理监控](/observing-your-data/agent-traces/)查看生成式 AI 代理的 LLM 调用、工具调用和令牌使用情况。 +1. 分享您的结果: + - 将日志页面的可视化添加到[仪表板](/observing-your-data/exploring-observability-data/discover-logs#adding-visualizations-to-dashboards)。 + - 使用 [Notebooks](/dashboards/notebooks) 将 Markdown 文本、SQL 和 PPL 查询以及可视化组合到报告和运行手册中。 + +## 相关文档 + +- 要了解日志、追踪和指标如何到达 OpenSearch,请参阅[摄取可观测性数据](/observing-your-data/ingesting-observability-data)。 +- 要在显示追踪数据的应用程序之间进行选择,请参阅[选择追踪工具](/observing-your-data/exploring-data#choosing-a-trace-tool)。 diff --git a/i18n/zh/observing-your-data/forecast/api.md b/i18n/zh/observing-your-data/forecast/api.md new file mode 100644 index 00000000..a254f46b --- /dev/null +++ b/i18n/zh/observing-your-data/forecast/api.md @@ -0,0 +1,1219 @@ +--- +title: 预测 API +--- + +# 预测 API + +使用这些操作可以通过编程方式创建和管理预测器,以便对时间序列数据生成预测。 + +--- + +## 目录 +- TOC + +--- + +## 创建预测器 + +<Badge type="tip" text="3.1 版本引入" /> + +创建一个用于生成时间序列预测的预测器。预测器可以是单流(不带类别字段)或高基数(带一个或多个类别字段)。 + +创建预测器时,您需要定义源索引、预测间隔和范围、要预测的特征以及可选参数(如类别字段和自定义结果索引)。 + +### 端点 + +``` +POST _plugins/_forecast/forecasters +``` + +### 请求正文字段 + +此 API 支持以下请求正文字段。 + +| 字段 | 数据类型 | 必需 | 描述 | +| :---------------------------- | :------------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | String | 必需 | 预测器名称。 | +| `description` | String | 可选 | 预测器的自由格式描述。 | +| `time_field` | String | 必需 | 源文档的时间戳字段。 | +| `indices` | String 或 string\[] | 必需 | 一个或多个源索引或索引别名。 | +| `feature_attributes` | Array of objects | 必需 | 要预测的特征。仅支持一个特征。每个对象必须包含 `feature_name` 和 `aggregation_query`。 | +| `forecast_interval` | Object | 必需 | 生成预测的间隔。 | +| `horizon` | Integer | 可选 | 要预测的未来间隔数。 | +| `window_delay` | Object | 可选 | 为考虑摄取延迟而添加的延迟。 | +| `category_field` | String | 可选 | 用于按实体对预测进行分组的一个或两个字段。 | +| `result_index` | String | 可选 | 用于存储预测结果的自定义索引别名。必须以 `opensearch-forecast-result-` 开头。默认为 `opensearch-forecast-results`。 | +| `suggested_seasonality` | Integer | 可选 | 以间隔为单位的季节性模式长度。预期范围:8-256。 | +| `recency_emphasis` | Integer | 可选 | 控制最近数据对预测的影响程度。默认为 `2560`。 | +| `history` | Integer | 可选 | 用于模型训练的过去间隔数。 | +| `result_index_min_size` | Integer | 可选 | 触发索引滚动所需的最小主分片大小(以 MB 为单位)。 | +| `result_index_min_age` | Integer | 可选 | 触发索引滚动所需的最小索引年龄(以天为单位)。 | +| `result_index_ttl` | Integer | 可选 | 滚动后的索引在删除前的最短保留时间(以天为单位)。 | +| `flatten_custom_result_index` | Boolean | 可选 | 如果为 `true`,则展平自定义结果索引中的嵌套字段以便于聚合。 | +| `shingle_size` | Integer | 可选 | 用于影响预测的过去间隔数。默认为 `8`。建议范围:4-128。 | + +### 示例请求:单流预测器 + +以下示例为 `network-requests` 索引创建单流预测器。预测器每 3 分钟预测 `deny` 字段的最大值,使用前 300 个间隔进行训练。`window_delay` 设置通过将预测窗口延迟 3 分钟来考虑摄取延迟: + +```json +POST _plugins/_forecast/forecasters +{ + "name": "Second-Test-Forecaster-7", + "description": "ok rate", + "time_field": "@timestamp", + "indices": [ + "network-requests" + ], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "importance": 1, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ], + "window_delay": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "forecast_interval": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "schema_version": 2, + "horizon": 3, + "history": 300 +} +``` + +#### 示例响应 + +```json +{ + "_id": "4WnXAYoBU2pVBal92lXD", + "_version": 1, + "forecaster": { + "...": "Configuration (omitted)" + } +} +``` + +### 示例请求:高基数预测器 + +以下示例创建一个按 `host_nest.host2` 字段对预测进行分组的高基数预测器。与单流示例一样,它以 3 分钟的间隔使用历史数据预测 `deny` 字段的最大值。此设置支持跨不同主机的特定实体预测: + +```json +POST _plugins/_forecast/forecasters +{ + "name": "Second-Test-Forecaster-7", + "description": "ok rate", + "time_field": "@timestamp", + "indices": [ + "network-requests" + ], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "importance": 1, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ], + "window_delay": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "forecast_interval": { + "period": { + "interval": 3, + "unit": "MINUTES" + } + }, + "schema_version": 2, + "horizon": 3, + "history": 300, + "category_field": ["host_nest.host2"], +} +``` + +#### 示例响应 + +```json +{ + "_id": "4WnXAYoBU2pVBal92lXD", + "_version": 1, + "forecaster": { + "...": "Configuration (omitted)" + } +} +``` + +--- + +## 验证预测器 + +<Badge type="tip" text="3.1 版本引入" /> + +使用此 API 验证预测器配置是否有效。您可以执行两种类型的验证: + +- **仅配置验证**:检查配置在语法上是否正确并引用现有字段。 +- **训练可行性验证**:执行全面验证以确保可以使用指定配置训练预测器。 + +### 端点 + +以下端点可用于验证预测器。 + +**仅配置验证**: + +```http +POST _plugins/_forecast/forecasters/_validate +``` + +**训练可行性验证**: + +```http +POST _plugins/_forecast/forecasters/_validate/model +``` + +### 请求正文 + +请求正文与用于创建预测器的请求正文相同。它必须至少包含以下必需字段:`name`、`time_field`、`indices`、`feature_attributes` 和 `forecast_interval`。 + +如果配置有效,响应返回一个空对象(`{}`)。如果配置无效,响应包含详细的错误消息。 + +### 示例请求:缺少 `forecast_interval` + +以下请求显示了一个省略 `forecast_interval` 的无效预测器配置: + +```json +POST _plugins/_forecast/forecasters/_validate +{ + "name": "invalid-forecaster", + "time_field": "@timestamp", + "indices": ["network-requests"], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ] +} +``` + +### 示例响应 + +```json +{ + "forecaster": { + "forecast_interval": { + "message": "Forecast interval should be set" + } + } +} +``` + +--- + +## 建议配置 + +<Badge type="tip" text="3.1 版本引入" /> + +根据数据的节奏和密度,返回一个或多个预测器参数(`forecast_interval`、`horizon`、`history`、`window_delay`)的适当值。 + +### 端点 + +``` +POST _plugins/_forecast/forecasters/_suggest/<comma‑separated-types> +``` + +`types` 必须是 `forecast_interval`、`horizon`、`history` 或 `window_delay` 中的一个或多个。 + +### 示例请求:建议间隔 + +以下请求分析源数据并根据平均事件频率为预测器建议适当的 `forecast_interval` 值: + +``` +POST _plugins/_forecast/forecasters/_suggest/forecast_interval +{ + "name": "interval‑suggest", + "time_field": "@timestamp", + "indices": ["network-requests"], + ... +} +``` + +#### 示例响应 + +```json +{ + "interval": { + "period": { "interval": 1, "unit": "Minutes" } + } +} +``` + +--- + +## 获取预测器 + +<Badge type="tip" text="3.1 版本引入" /> + +检索预测器及其最近任务(可选)。 + +### 端点 + +``` +GET _plugins/_forecast/forecasters/{forecaster_id}[?task=(true|false)] +``` + +### 示例请求:包含任务 + +以下请求返回有关预测器的元数据,以及(如果指定)有关其关联任务的详细信息: + +```json +GET _plugins/_forecast/forecasters/d7-r1YkB_Z-sgDOKo3Z5?task=true +``` + +响应包括 `forecaster`、`realtime_task` 和 `run_once_task` 部分。 + +--- + +## 更新预测器 + +<Badge type="tip" text="3.1 版本引入" /> + +更新现有预测器的配置。在进行更新之前,您必须停止任何活动的预测作业。 + +任何影响模型的更改(例如修改 `category_field`、`result_index` 或 `feature_attributes`)都会使 OpenSearch Dashboards 中显示的先前结果失效。 + +### 端点 + +``` +PUT _plugins/_forecast/forecasters/{forecaster_id} +``` + +### 示例请求:更新名称、结果索引和类别字段 + +以下显示预测器 `forecaster-i1nwqooBLXq6T-gGbXI-` 的定义: + +```json +{ + "_index": ".opensearch-forecasters", + "_id": "forecaster-i1nwqooBLXq6T-gGbXI-", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "category_field": [ + "service" + ], + "description": "ok rate", + "feature_attributes": [{ + "feature_id": "deny_max", + "feature_enabled": true, + "feature_name": "deny max", + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + }], + "forecast_interval": { + "period": { + "unit": "Minutes", + "interval": 1 + } + }, + "schema_version": 2, + "time_field": "@timestamp", + "last_update_time": 1695084997949, + "horizon": 24, + "indices": [ + "network-requests" + ], + "window_delay": { + "period": { + "unit": "Seconds", + "interval": 20 + } + }, + "transform_decay": 1.0E-4, + "name": "Second-Test-Forecaster-3", + "filter_query": { + "match_all": { + "boost": 1.0 + } + }, + "shingle_size": 8, + "result_index": "opensearch-forecast-result-a" + } +} +``` + +以下请求更新预测器的 `name`、`result_index` 和 `category_field` 属性: + +```json +PUT localhost:9200/_plugins/_forecast/forecasters/forecast-i1nwqooBLXq6T-gGbXI- +{ + "name": "Second-Test-Forecaster-1", + "description": "ok rate", + "time_field": "@timestamp", + "indices": [ + "network-requests" + ], + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_name": "deny max", + "feature_enabled": true, + "importance": 1, + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + } + ], + "window_delay": { + "period": { + "interval": 20, + "unit": "SECONDS" + } + }, + "forecast_interval": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "ui_metadata": { + "aabb": { + "ab": "bb" + } + }, + "schema_version": 2, + "horizon": 24, + "category_field": ["service", "host"] +} +``` + +--- + +## 删除预测器 + +<Badge type="tip" text="3.1 版本引入" /> + +删除预测器配置。在删除之前,您必须停止任何关联的实时或一次性预测作业。如果作业仍在运行,API 返回 `400` 错误。 + +### 端点 + +```http +DELETE _plugins/_forecast/forecasters/{forecaster_id} +``` + +### 示例请求:删除预测器 + +以下请求使用其唯一 ID 删除预测器配置: + +```http +DELETE _plugins/_forecast/forecasters/forecast-i1nwqooBLXq6T-gGbXI- +``` + +--- + +## 启动预测器作业 + +<Badge type="tip" text="3.1 版本引入" /> + +开始对预测器进行实时预测。 + +### 端点 + +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/_start +``` + +### 示例请求:启动预测器作业 + +以下请求为指定的预测器启动实时预测: + +```bash +POST _plugins/_forecast/forecasters/4WnXAYoBU2pVBal92lXD/_start +``` + +#### 示例响应 + +```json +{ "_id": "4WnXAYoBU2pVBal92lXD" } +``` + +--- + +## 停止预测器作业 + +<Badge type="tip" text="3.1 版本引入" /> + +停止对预测器进行实时预测。 + +### 端点 +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/_stop +``` + +### 示例请求:停止预测器作业 + +以下请求停止指定预测器的实时预测作业: + +```bash +POST _plugins/_forecast/forecasters/4WnXAYoBU2pVBal92lXD/_stop +``` + +--- + +## 运行一次分析 + +<Badge type="tip" text="3.1 版本引入" /> + +运行回测(历史)预测。在实时作业处于活动状态时无法运行。 + +### 端点 +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/_run_once +``` + +### 示例请求:运行回测预测 + +以下请求为指定的预测器启动一次性预测分析: + +```bash +POST _plugins/_forecast/forecasters/{forecaster_id}/_run_once +``` + +#### 示例响应 + +响应返回分配给一次性作业的任务 ID: + +```json +{ "taskId": "vXZG85UBAlM4LplcKI0f" } +``` + +### 示例请求:按任务 ID 搜索预测结果 + +使用返回的 `taskId` 查询 `opensearch-forecast-results*` 索引以获取历史预测输出: + +```json +GET opensearch-forecast-results*/_search?pretty +{ + "sort": { + "data_end_time": "desc" + }, + "size": 10, + "query": { + "bool": { + "filter": [ + { "term": { "task_id": "vXZG85UBAlM4LplcKI0f" } }, + { + "range": { + "data_end_time": { + "format": "epoch_millis", + "gte": 1742585746033 + } + } + } + ] + } + }, + "track_total_hits": true +} +``` + +此查询返回与指定任务 ID 匹配的 10 个最新预测结果。 + +--- + +## 搜索预测器 + +<Badge type="tip" text="3.1 版本引入" /> + +在存储预测器配置的 `.opensearch-forecasters` 系统索引上提供标准 `_search` 功能。您必须使用此 API 直接查询 `.opensearch-forecasters`,因为该索引是系统索引,无法通过常规 OpenSearch 查询访问。 + +### 端点 + +```http +GET _plugins/_forecast/forecasters/_search +``` + +### 示例请求:按索引进行通配符搜索 + +以下请求使用前导锚定通配符搜索源索引名称以 `network` 开头的预测器: + +```json +GET _plugins/_forecast/forecasters/_search +{ + "query": { + "wildcard": { + "indices": { + "value": "network*" + } + } + } +} +``` + +`network*` 匹配 `network`、`network-metrics`、`network_2025-06` 和类似的索引名称。 + +#### 示例响应 + +```json +{ + "took": 5, + "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-forecasters", + "_id": "forecast-i1nwqooBLXq6T-gGbXI-", + "_version": 1, + "_seq_no": 0, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "category_field": ["server"], + "description": "ok rate", + "feature_attributes": [{ + "feature_id": "deny_max", + "feature_enabled": true, + "feature_name": "deny max", + "aggregation_query": { + "deny_max": { + "max": { + "field": "deny" + } + } + } + }], + "forecast_interval": { + "period": { + "unit": "Minutes", + "interval": 1 + } + }, + "schema_version": 2, + "time_field": "@timestamp", + "last_update_time": 1695084997949, + "horizon": 24, + "indices": ["network-requests"], + "window_delay": { + "period": { + "unit": "Seconds", + "interval": 20 + } + }, + "transform_decay": 1.0E-4, + "name": "Second-Test-Forecaster-3", + "filter_query": { + "match_all": { + "boost": 1.0 + } + }, + "shingle_size": 8 + } + }] + } +} +``` + +--- + +## 搜索任务 + +<Badge type="tip" text="3.1 版本引入" /> + +查询 `.opensearch-forecast-state` 索引中的任务。 + +### 端点 + +```http +GET _plugins/_forecast/forecasters/tasks/_search +``` + +### 示例请求:搜索之前的一次性任务 + +以下请求检索特定预测器的以前的一次性任务(不包括最近的任务),并按 `execution_start_time` 降序排序: + +```json +GET _plugins/_forecast/forecasters/tasks/_search +{ + "from": 0, + "size": 1000, + "query": { + "bool": { + "filter": [ + { "term": { "forecaster_id": { "value": "m5apnooBHh7Wss2wewfW", "boost": 1.0 }}}, + { "term": { "is_latest": { "value": false, "boost": 1.0 }}}, + { "terms": { + "task_type": [ + "RUN_ONCE_FORECAST_SINGLE_STREAM", + "RUN_ONCE_FORECAST_HC_FORECASTER" + ], + "boost": 1.0 + }} + ], + "adjust_pure_negative": true, + "boost": 1.0 + } + }, + "sort": [ + { "execution_start_time": { "order": "desc" }} + ] +} +``` + +#### 示例响应 + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { "value": 1, "relation": "eq" }, + "max_score": null, + "hits": [ + { + "_index": ".opensearch-forecast-state", + "_id": "4JaunooBHh7Wss2wOwcw", + "_version": 3, + "_seq_no": 5, + "_primary_term": 1, + "_score": null, + "_source": { + "last_update_time": 1694879344264, + "execution_start_time": 1694879333168, + "forecaster_id": "m5apnooBHh7Wss2wewfW", + "state": "TEST_COMPLETE", + "task_type": "RUN_ONCE_FORECAST_SINGLE_STREAM", + "is_latest": false, + "forecaster": { + "description": "ok rate", + "ui_metadata": { "aabb": { "ab": "bb" }}, + "feature_attributes": [ + { + "feature_id": "deny_max", + "feature_enabled": true, + "feature_name": "deny max", + "aggregation_query": { + "deny_max": { + "max": { "field": "deny" } + } + } + } + ], + "forecast_interval": { + "period": { + "unit": "Minutes", + "interval": 1 + } + }, + "schema_version": 2, + "time_field": "@timestamp", + "last_update_time": 1694879022036, + "horizon": 24, + "indices": [ "network-requests" ], + "window_delay": { + "period": { + "unit": "Seconds", + "interval": 20 + } + }, + "transform_decay": 1.0E-4, + "name": "Second-Test-Forecaster-5", + "filter_query": { "match_all": { "boost": 1.0 }}, + "shingle_size": 8 + } + }, + "sort": [ 1694879333168 ] + } + ] + } +} +``` + +--- + +## 顶级预测器 +<Badge type="tip" text="3.1 版本引入" /> + +根据内置或自定义指标,返回给定时间戳范围内的 *top-k* 实体。 + +### 端点 + +```http +POST _plugins/_forecast/forecasters/{forecaster_id}/results/_topForecasts +``` + +### 查询参数 + +支持以下查询参数。 + +| 名称 | 类型 | 必需 | 描述 | +| :--- | :--- | :--- | :--- | +| `split_by` | String | 必需 | 要分组的字段(例如 `service`)。 | +| `forecast_from` | Epoch‑ms | 必需 | 评估窗口中第一个预测的 `data_end_time`。 | +| `size` | Integer | 可选 | 要返回的桶数。默认为 `5`。 | +| `filter_by` | Enum | 必需 | 指定是使用内置查询还是自定义查询。必须是 `BUILD_IN_QUERY` 或 `CUSTOM_QUERY`。 | +| `build_in_query` | Enum | 可选 | 以下内置排名标准之一是必需的:<br> `MIN_CONFIDENCE_INTERVAL_WIDTH` -- 按最窄的预测置信区间(最精确)排序。<br> `MAX_CONFIDENCE_INTERVAL_WIDTH` -- 按最宽的预测置信区间(最不精确)排序。<br> `MIN_VALUE_WITHIN_THE_HORIZON` -- 按预测窗口内观察到的最低预测值排序。<br> `MAX_VALUE_WITHIN_THE_HORIZON` -- 按预测窗口内观察到的最高预测值排序。<br> `DISTANCE_TO_THRESHOLD_VALUE` -- 按预测值与用户定义阈值之间的差异排序。 | +| `threshold`、`relation_to_threshold` | Mixed | 条件性 | 仅在 `build_in_query` 为 `DISTANCE_TO_THRESHOLD_VALUE` 时才需要。 | +| `filter_query` | Query DSL | 可选 | 当 `filter_by=CUSTOM_QUERY` 时使用的自定义查询。 | +| `subaggregations` | Array | 可选 | 用于在每个桶内计算附加指标的嵌套聚合和排序选项列表。 | + +### 示例请求:窄置信区间的内置查询 + +以下请求返回按最窄置信区间排名的顶级预测实体: + +```json +POST _plugins/_forecast/forecasters/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", + "filter_by": "BUILD_IN_QUERY", + "build_in_query": "MIN_CONFIDENCE_INTERVAL_WIDTH", + "forecast_from": 1691008679297 +} +``` + +#### 示例响应 + +```json +{ + "buckets": [ + { + "key": { "service": "service_6" }, + "doc_count": 1, + "bucket_index": 0, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 27.655361 + }, + ... + ] +} +``` + +### 示例请求:具有最窄置信区间的内置查询 + +以下请求返回预测值具有最窄置信区间的实体的排序列表。结果根据 `MIN_CONFIDENCE_INTERVAL_WIDTH` 指标按升序排列: + +```json +POST _plugins/_forecast/forecasters/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", + "filter_by": "BUILD_IN_QUERY", + "build_in_query": "MIN_CONFIDENCE_INTERVAL_WIDTH", + "forecast_from": 1691008679297 +} +``` + +#### 示例响应 + +```json +{ + "buckets": [ + { + "key": { + "service": "service_6" + }, + "doc_count": 1, + "bucket_index": 0, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 27.655361 + }, + { + "key": { + "service": "service_4" + }, + "doc_count": 1, + "bucket_index": 1, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 1324.7734 + }, + { + "key": { + "service": "service_0" + }, + "doc_count": 1, + "bucket_index": 2, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 2211.0781 + }, + { + "key": { + "service": "service_2" + }, + "doc_count": 1, + "bucket_index": 3, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 3372.0469 + }, + { + "key": { + "service": "service_3" + }, + "doc_count": 1, + "bucket_index": 4, + "MIN_CONFIDENCE_INTERVAL_WIDTH": 3980.2812 + } + ] +} +``` + +### 示例请求:低于阈值距离的内置查询 + +以下请求根据 `DISTANCE_TO_THRESHOLD_VALUE` 指标返回预测值离指定阈值最远的顶级实体: + +```http +POST _plugins/_forecast/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", // 按"service"实体字段对预测进行分组 + "filter_by": "BUILD_IN_QUERY", // 使用内置排名指标 + "build_in_query": "DISTANCE_TO_THRESHOLD_VALUE", + "forecast_from": 1691008679297, // 范围内第一个预测的 data_end_time + "threshold": -82561.8, // 用户提供的阈值 + "relation_to_threshold": "LESS_THAN" // 仅保留低于阈值的预测 +} +``` + +#### 示例响应 + +`DISTANCE_TO_THRESHOLD_VALUE` 指标计算 `forecast_value – threshold`。由于 `relation_to_threshold` 为 `LESS_THAN`,API 仅返回负距离并按升序排序(最负的在前)。每个桶包括以下值: + +- `doc_count`:匹配的预测点数。 +- `DISTANCE_TO_THRESHOLD_VALUE`:预测范围内距阈值的最大距离。 + +以下响应返回 `DISTANCE_TO_THRESHOLD_VALUE`: + +```json +{ + "buckets": [ + { + "key": { "service": "service_5" }, + "doc_count": 18, + "bucket_index": 0, + "DISTANCE_TO_THRESHOLD_VALUE": -330387.12 + }, + ... + { + "key": { "service": "service_0" }, + "doc_count": 1, + "bucket_index": 4, + "DISTANCE_TO_THRESHOLD_VALUE": -83561.8 + } + ] +} +``` + +### 示例请求:自定义查询和嵌套聚合 + +以下请求使用自定义查询按名称匹配服务,并按最高预测值对它们进行排名: + +```json +POST _plugins/_forecast/AG_3t4kBkYqqimCe86bP/results/_topForecasts +{ + "split_by": "service", + "forecast_from": 1691018993776, + "filter_by": "CUSTOM_QUERY", + "filter_query": { + "nested": { + "path": "entity", + "query": { + "bool": { + "must": [ + { "term": { "entity.name": "service" } }, + { "wildcard": { "entity.value": "User*" } } + ] + } + } + } + }, + "subaggregations": [ + { + "aggregation_query": { + "forecast_value_max": { + "max": { "field": "forecast_value" } + } + }, + "order": "DESC" + } + ] +} +``` + +#### 示例响应 + +```json +{ + "buckets": [ + { + "key": { "service": "UserAuthService" }, + "doc_count": 24, + "bucket_index": 0, + "forecast_value_max": 269190.38 + }, + ... + ] +} +``` +--- + +## 预测器配置文件 + +<Badge type="tip" text="3.1 版本引入" /> + +返回执行时状态,例如初始化进度、按实体的模型元数据和错误。此 API 对于在运行时检查预测器间隔非常有用。 + +### 端点 + +```http +GET _plugins/_forecast/forecasters/{forecaster_id}/_profile[/{type1},{type2}][?_all=true] +``` + +您可以检索特定的配置文件类型,或使用 `_all` 查询参数请求所有可用类型。 + +支持以下配置文件类型: + +- `state` +- `error` +- `coordinating_node` +- `total_size_in_bytes` +- `init_progress` +- `models` +- `total_entities` +- `active_entities` +- `forecast_task` + +如果在请求正文中包含 `entity` 数组,则配置文件仅限于该实体。 + +### 示例请求:具有实体过滤器的默认配置文件 + +以下请求返回指定实体的默认配置文件类型(`state` 和 `error`): + +```http +GET _plugins/_forecast/forecasters/tLch1okBCBjX5EchixQ8/_profile +{ + "entity": [ + { + "name": "service", + "value": "app_1" + }, + { + "name": "host", + "value": "server_2" + } + ] +} +``` + +#### 示例响应 + +```json +{ + "state": "RUNNING" +} +``` + +### 示例请求:多种配置文件类型 + +以下请求检索 `init_progress`、`error`、`total_entities` 和 `state` 配置文件类型: + +```http +GET _plugins/_forecast/forecasters/mZ6P0okBTUNS6IWgvpwo/_profile/init_progress,error,total_entities,state +``` + +### 示例请求:所有配置文件类型 + +以下请求返回所有可用的配置文件类型: + +```http +GET _plugins/_forecast/forecasters/d7-r1YkB_Z-sgDOKo3Z5/_profile?_all=true&pretty +``` + +--- + +## 预测器统计信息 +<Badge type="tip" text="3.1 版本引入" /> + +返回集群级别或节点级别的统计信息,包括预测器数量、模型计数、请求计数器以及内部预测索引的健康状况。 + +### 端点 + +```http +GET _plugins/_forecast/stats +GET _plugins/_forecast/{node_id}/stats +GET _plugins/_forecast/stats/{stat_name} +``` + +### 示例请求:检索所有统计信息 + +以下请求检索所有预测器的集群级别统计信息,包括计数、模型信息和索引状态: + +```http +GET _plugins/_forecast/stats +``` + +#### 示例响应 + +```json +{ + "hc_forecaster_count": 1, + "forecast_results_index_status": "yellow", + "forecast_models_checkpoint_index_status": "yellow", + "single_stream_forecaster_count": 1, + "forecastn_state_status": "yellow", + "forecaster_count": 2, + "job_index_status": "yellow", + "config_index_status": "yellow", + "nodes": { + "8B2S4ClnRFK3GTjO45bwrw": { + "models": [ + { + "model_type": "rcf_caster", + "last_used_time": 1692245336895, + "model_id": "Doj0AIoBEU5Xd2ccoe_9_entity_SO2kPi_PAMsvThWyE-zYHg", + "last_checkpoint_time": 1692233157256, + "entity": [ + { "name": "host_nest.host2", "value": "server_2" } + ] + } + ], + "forecast_hc_execute_request_count": 204, + "forecast_model_corruption_count": 0, + "forecast_execute_failure_count": 0, + "model_count": 4, + "forecast_execute_request_count": 409, + "forecast_hc_execute_failure_count": 0 + } + } +} +``` + +### 示例请求:检索特定节点的统计信息 + +以下请求检索由节点 ID 标识的特定节点的预测器统计信息: + +```http +GET _plugins/_forecast/8B2S4ClnRFK3GTjO45bwrw/stats +``` + +### 示例请求:检索高基数请求的总数 + +以下请求检索所有节点上高基数预测器请求的总数: + +```http +GET _plugins/_forecast/stats/forecast_hc_execute_request_count +``` + +### 示例请求:检索特定节点的高基数请求计数 + +以下请求检索特定节点执行的高基数预测器请求数: + +```http +GET _plugins/_forecast/0ZpL8WEYShy-qx7hLJQREQ/stats/forecast_hc_execute_request_count/ +``` + +--- + +## 预测器信息 +<Badge type="tip" text="3.1 版本引入" /> + +返回表示集群中预测器配置总数的单个整数,或检查是否存在满足给定搜索条件的预测器。 + +### 端点 +```http +GET _plugins/_forecast/forecasters/count +GET _plugins/_forecast/forecasters/match?name={forecaster_name} +``` + +### 示例请求:计算预测器 + +以下请求返回当前存储在集群中的预测器配置数: + +```http +GET _plugins/_forecast/forecasters/count +``` + +### 示例响应 + +```json +{ + "count": 2, + "match": false +} +``` + +### 示例请求:匹配预测器名称 + +以下请求查找名为 `Second-Test-Forecaster-3` 的预测器: + +```http +GET _plugins/_forecast/forecasters/match?name=Second-Test-Forecaster-3 +``` + +### 示例响应:找到匹配 + +```json +{ + "count": 0, + "match": true +} +``` + +### 示例响应:未找到匹配 + +```json +{ + "count": 0, + "match": false +} +``` diff --git a/i18n/zh/observing-your-data/forecast/forecaster-access-control.md b/i18n/zh/observing-your-data/forecast/forecaster-access-control.md new file mode 100644 index 00000000..6a9e1223 --- /dev/null +++ b/i18n/zh/observing-your-data/forecast/forecaster-access-control.md @@ -0,0 +1,136 @@ +--- +title: 预测器访问控制 +--- + +# 预测器访问控制 + +预测器资源与安全插件的资源共享和访问控制框架集成,为预测器资源提供文档级授权。这用更灵活的共享系统取代了传统的 `plugins.forecast.filter_by_backend_roles` 设置,允许资源所有者向用户、角色或后端角色授予特定的访问级别。 + +有关预定义的预测角色和权限,请参阅[预测安全性](/observing-your-data/forecast/security)。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +下表描述了预测器资源配置。 + +| 字段 | 值 | +| :--- | :--- | +| 资源类型 | `forecaster` | +| 系统索引 | `.opensearch-forecasters` | +| 加入版本 | OpenSearch 3.3 | + +当为预测器启用资源级授权时,每个预测器的可见性由中央共享记录控制。资源所有者和具有共享功能的用户可以为特定用户、角色或后端角色授予或撤销访问权限。 + +## 启用预测器资源共享 + +要为预测器启用资源共享,您必须将预测器资源类型添加到受保护类型列表,并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员:这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 进行配置 + +将以下设置添加到您的 `opensearch.yml` 配置文件以为预测器启用资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "forecaster" +``` + +### 使用集群设置 API 进行配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["forecaster"] + } +} +``` + +::: info NOTE +在将预测器资源类型添加到现有配置时,请在 `protected_types` 数组中包含所有先前配置的资源类型。 +::: + +## 预测器访问级别 + +预测提供了三个预定义的预测器文档访问级别。这些访问级别决定授予已获得预测器资源访问权限的用户的特定权限。 + +### forecast_read_only + +`forecast_read_only` 只读访问级别授予用户查看和搜索共享预测器的能力,但不能修改它们。此访问级别包括以下权限: + +```yaml +- 'cluster:admin/plugin/forecast/forecaster/info' +- 'cluster:admin/plugin/forecast/forecaster/stats' +- 'cluster:admin/plugin/forecast/forecaster/suggest' +- 'cluster:admin/plugin/forecast/forecaster/validate' +- 'cluster:admin/plugin/forecast/forecasters/get' +- 'cluster:admin/plugin/forecast/forecaster/info' +- 'cluster:admin/plugin/forecast/result/topForecasts' +``` + +### forecast_read_write + +`forecast_read_write` 读写访问级别授予用户对预测器操作的完全访问权限,但不包括共享功能。此访问级别包括所有读取权限以及写入操作: + +```yaml +- 'cluster:admin/plugin/forecast/*' +- 'cluster:monitor/*' +- 'cluster:admin/settings/update' +``` + +### forecast_full_access + +`forecast_full_access` 完全访问级别授予用户对预测器的完全控制,包括类似所有者的权限,例如与其他用户共享资源。此访问级别包括所有预测器操作以及资源共享权限: + +```yaml +- 'cluster:admin/plugin/forecast/*' +- 'cluster:monitor/*' +- 'cluster:admin/settings/update' +- "cluster:admin/security/resource/share" +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在[异常检测 GitHub 存储库](https://github.com/opensearch-project/anomaly-detection/)中创建问题。 +::: + +## 从传统框架迁移 + +在启用资源共享并将预测器标记为受保护的资源类型后,集群管理员必须运行迁移 API 以将现有预测器共享信息从传统框架传输到新的资源共享系统。 + +::: warning IMPORTANT +仅限管理员:迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +使用以下 API 调用将传统预测器共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opensearch-forecasters", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "forecaster": "<select-appropriate-access-level>" + } +} +``` + +将 `<replace-with-existing-user>` 替换为应拥有没有明确所有权信息的预测器的现有用户的用户名。将 `<select-appropriate-access-level>` 替换为可用的预测器访问级别之一:`forecast_read_only`、`forecast_read_write` 或 `forecast_full_access`。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于编程管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流程和用户指南 diff --git a/i18n/zh/observing-your-data/forecast/getting-started.md b/i18n/zh/observing-your-data/forecast/getting-started.md new file mode 100644 index 00000000..fccdc47c --- /dev/null +++ b/i18n/zh/observing-your-data/forecast/getting-started.md @@ -0,0 +1,341 @@ +--- +title: 预测入门 +--- + +# 预测入门 + +您可以通过在导航面板中选择**预测**来在 OpenSearch Dashboards 中定义和配置预测器。 + +## 步骤 1:定义预测器 + +**预测器**代表单个预测任务。您可以创建多个并行运行的预测器,每个预测器分析不同的数据源。按照以下步骤定义新预测器: + +1. 在**预测器列表**视图中,选择**创建预测器**。 + +2. 通过输入以下信息定义数据源: + * **名称** – 提供唯一的描述性名称,例如 `requests-10min`。 + * **描述** – 总结预测器的用途,例如 `每 10 分钟预测总请求计数`。 + * **索引** – 选择一个或多个索引、索引模式或别名。通过跨集群搜索(`cluster-name:index-pattern`)支持远程索引。有关更多信息,请参阅[跨集群搜索](/search-plugins/cross-cluster-search)。如果启用了安全插件,请参阅[使用细粒度访问控制选择远程索引](/observing-your-data/forecast/security#selecting-remote-indexes-with-fine-grained-access-control)。 + +3. (可选)选择**添加数据过滤器**以设置**字段**、**运算符**和**值**,或选择**使用查询 DSL** 来定义[布尔查询](/query-dsl/compound/bool)。以下示例使用查询域特定语言(DSL)过滤器来匹配三个 URL 路径: + + ```json + { + "bool": { + "should": [ + { "term": { "urlPath.keyword": "/domain/{id}/short" } }, + { "term": { "urlPath.keyword": "/sub_dir/{id}/short" } }, + { "term": { "urlPath.keyword": "/abcd/123/{id}/xyz" } } + ] + } + } + ``` + +4. 在**时间戳字段**下,选择存储时间戳的字段。 + +5. 在**指标(度量)**部分中,为预测器添加度量。为了获得最佳准确性,每个预测器支持一个度量。选择以下选项之一: + + - 选择预定义聚合:`average()`、`count()`、`sum()`、`min()` 或 `max()`。 + - 要使用自定义聚合,请在**预测基于**下选择**自定义表达式**并定义您自己的[查询 DSL](/query-dsl/) 表达式。例如,以下查询预测具有特定帐户类型的唯一帐户数: + + ```json + { + "bbb_unique_accounts": { + "filter": { + "bool": { + "must": [ + { + "wildcard": { + "accountType": { + "wildcard": "*blah*", + "boost": 1 + } + } + } + ], + "adjust_pure_negative": true, + "boost": 1 + } + }, + "aggregations": { + "uniqueAccounts": { + "cardinality": { + "field": "account" + } + } + } + } + } + ``` + +6. (可选)在**类别字段**部分中,启用**使用类别字段拆分时间序列**以在实体级别生成预测(例如,按 IP 地址、产品 ID 或国家代码)。 + + 可以在内存中缓存的唯一实体数量是有限的。使用以下公式估计容量: + + ``` + (数据节点数 × 堆大小 × plugins.forecast.model_max_size_percent) + ────────────────────────────────────────────────────────────────── + 实体模型大小(MB) + ``` + + 例如,具有 3 个数据节点的集群,每个节点具有 8 GB JVM 堆和默认的 10% 模型内存,将包含以下数量的实体: + + ``` + (8096 MB × 0.10 ÷ 1 MB) × 3 节点 ≈ 2429 个实体 + ``` + + 要确定实体模型大小,请使用[预测器配置文件 API](/observing-your-data/forecast/api#profile-forecaster)。您可以使用 `plugins.forecast.model_max_size_percent` 设置提高或降低内存上限。 + +预测器缓存最频繁和最近观察到的实体的模型,取决于可用内存。在每个间隔期间,不太常见的实体的模型会根据尽力而为的原则从索引加载,没有保证的服务级别协议(SLA)。始终针对代表性工作负载验证内存使用情况。 + +有关更多信息,请参阅博客文章[改进异常检测:一分钟内处理一百万个实体](https://opensearch.org/blog/one-million-enitities-in-one-minute/)。尽管侧重于异常检测,但建议适用于预测,因为两个功能共享相同的底层随机切割森林(RCF)模型。 + +## 步骤 2:添加模型参数 + +OpenSearch Dashboards 中的**建议参数**按钮启动对最近历史记录的审查,以推荐合理的默认值。您可以通过调整以下参数来覆盖这些默认值: + +* **预测间隔** – 指定聚合桶(例如,10 分钟)。较长的间隔平滑噪声并降低计算成本,但会延迟检测。较短的间隔更快地检测变化,但会增加资源使用并可能引入噪声。选择仍能产生稳定信号的最短间隔。 +* **窗口延迟** – 告诉预测器在事件发生和摄取之间预期的延迟量。此延迟向后调整预测间隔以确保完整的数据覆盖。例如,如果预测间隔为 10 分钟,摄取延迟 1 分钟,将窗口延迟设置为 1 分钟可确保预测器评估 1:49 至 1:59 的数据,而不是 1:50 至 2:00。 + * 为避免丢失数据,请将窗口延迟设置为预期摄取延迟的上限。但是,较长的延迟会降低预测的实时响应性。 +* **范围** – 指定要预测的未来桶数。预测准确性随距离而下降,因此只选择在运营上有意义的预测窗口。 +* **历史记录** – 设置用于训练初始(冷启动)模型的历史数据点数。最大值为 10,000。更多历史记录可以提高初始模型准确性,直至该限制。 + +**高级**面板默认折叠,允许大多数用户使用建议的参数继续。如果展开面板,您可以微调三个附加参数:[瓦片大小](#choosing-a-shingle-size)、[建议的季节性](#choosing-a-shingle-size)和[最近强调](#choosing-a-shingle-size)。这些参数控制预测器如何平衡最近波动与长期模式。 + +除非您的数据或用例另有要求,否则默认值——**瓦片大小 8**、**无明确季节性**和**最近强调 2560**——是可靠的起点。 + +### 选择瓦片大小 + +将**瓦片大小**字段留空以使用自动启发式: + +1. 从默认值 8 开始。 +2. 如果定义了**建议的季节性**且大于 16,则将其替换为季节长度的一半。 +3. 如果定义了**范围**且值的三分之一大于当前候选值,则相应更新。 + +最终值是这三个的最大值: +`max(8, 季节性 ÷ 2, 范围 ÷ 3)` + +如果您提供自定义值,它将覆盖此计算。 + +### 确定存储量 + +默认情况下,预测结果存储在 `opensearch-forecast-results` 索引别名中。您可以: + +* 构建仪表板和可视化。 +* 在[告警监视器](/observing-your-data/alerting/monitors)中使用结果。 +* 像查询任何其他 OpenSearch 索引一样查询结果。 + +为了管理存储,OpenSearch 应用滚动策略: + +* **滚动触发器** – 当主分片达到约 65 GB 时,将创建新的后备索引并更新别名。 +* **保留** – 滚动后的索引在删除之前至少保留 30 天。 + +您可以使用以下设置自定义此行为。 + +| 设置 | 描述 | 默认值 | +|---------|-------------|---------| +| `plugins.forecast.forecast_result_history_max_docs_per_shard` | 触发滚动之前每个分片允许的最大 Lucene 文档数。一个结果大约是 4 个文档,每个约 47 字节,总计约 65 GB。 | `1_350_000_000` | +| `plugins.forecast.forecast_result_history_retention_period` | 保留预测结果的持续时间。支持持续时间格式,例如 `7d`、`90d`。 | `30d` | + +### 指定自定义结果索引 + +您可以通过选择**自定义索引**并提供别名名称(例如 `abc`)将预测结果存储在自定义索引中。OpenSearch 创建一个别名,如 `opensearch-forecast-result-abc`,该别名指向后备索引(例如,`opensearch-forecast-result-abc-history-2024.06.12-000002`)。 + +要管理权限,请使用带连字符的命名空间。例如,将 `opensearch-forecast-result-financial-us-*` 分配给 `financial` 部门的 `us` 组的角色。 + 如果启用了安全插件,请确保配置了适当的[权限](/observing-your-data/forecast/security#custom-result-index-permissions)。 + +### 展平嵌套字段 + +如果您的自定义结果索引的文档包含嵌套字段,请启用**展平的自定义结果索引**以简化聚合和可视化。 + +这将创建一个以自定义索引和预测器名称为前缀的单独索引(例如,`opensearch-forecast-result-abc-flattened-test`),并使用 [Painless 脚本](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/scripts/flatten-custom-result-index-painless.txt)附加摄取管道以展平嵌套数据。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。 + +如果您稍后禁用此选项,则会删除关联的摄取管道。 + +使用[索引状态管理](/im-plugin/ism/)来管理展平结果索引的滚动和删除。 + +### 自定义结果索引生命周期管理 + +当满足以下任何条件时,OpenSearch 会滚动自定义结果索引。 + +| 参数 | 描述 | 类型 | 单位 | 默认值 | 必需 | +|----------|-------------|------|------|---------|----------| +| `result_index_min_size` | 触发滚动所需的最小总主分片大小。 | Integer | MB | `51200`(50 GB) | 否 | +| `result_index_min_age` | 触发滚动所需的最小索引年龄。 | Integer | 天 | `7` | 否 | +| `result_index_ttl` | 滚动后的索引在删除前的最短保留时间 | Integer | 天 | `60` | 否 | + +## 步骤 3:测试您的预测器 + +回测是评估和优化关键预测设置(如**间隔**和**范围**)的最快方法。在回测期间,模型在历史数据上进行训练,生成预测,并将它们与实际值一起绘制,以帮助可视化预测准确性。如果结果不符合预期,您可以调整设置并再次运行测试。 + +回测使用以下方法: + +1. **训练窗口**:模型在由**历史记录**设置定义的历史数据上进行训练。 + +2. **滚动预测**:模型在时间序列中前进,重复执行以下操作: + * 摄取下一个实际数据点 + * 在每个步骤发出预测 + + 由于这是回顾性模拟,因此预测值在其原始时间戳处绘制,使您可以看到模型在实时中的表现如何。 + +### 开始回测 + +要开始测试: + +1. 滚动到**添加模型参数**页面的底部。 +2. 选择**创建并测试**。 + +要跳过测试并立即创建预测器,请选择**创建**。 + +回测通常需要 1 或 2 分钟,但运行时间取决于以下因素。 + +| 因素 | 重要性原因 | +| --------------------- | ------------------------------------------------------------------------ | +| **历史记录长度** | 更多历史数据会增加训练时间。 | +| **数据密度** | 密集打包的数据会减慢聚合速度。 | +| **类别字段** | 模型为每个实体单独训练。 | +| **范围** | 更长的预测范围会增加生成的预测数量。 | + +如果图表为空,如下图所示,请检查您的索引在所选间隔内是否至少包含一个具有超过 40 个数据点的时间序列。 + +*test failed* + +### 阅读图表 + +当测试成功时,将鼠标悬停在图表上的任何点上以查看确切的值和置信界限: + +- **实际数据** – 实线 +- **中值预测(P50)** – 虚线 +- **置信区间** – P10 和 P90 之间的阴影带 + +下图显示了图表视图。 + +*Forecast chart with confidence bounds* + +### 从特定日期查看预测 + +预测图表显示从最终实际数据点开始到配置范围结束的预测。 + +例如,您可以在**预测自**字段中配置以下设置: + +- **最后实际时间戳**:2025 年 3 月 5 日 19:23 +- **间隔**:1 分钟 +- **范围**:24 + +使用这些设置,预测范围将跨越 `2025 年 3 月 5 日 19:23 – 19:47`,如下图所示。 + +*Forecast chart with trend* + +您还可以使用**预测自**下拉列表查看早期测试运行的预测,如下图所示。 + +*Forecast from dropdown* + +当您选择较早的**预测自**时间时,预测线直接绘制在该时刻可用的历史数据之上。这导致两个系列重叠,如下图所示。 + +*Overlapping forecast and actual data* + +要返回到最近的预测窗口,请选择**显示最新**。 + +### 叠加模式:并排准确性检查 + +默认情况下,图表显示从单个起点开始的预测。切换叠加模式以将预测曲线直接叠加在实际系列之上,并检查整个时间线的准确性。 + +由于模型在每个范围步骤发出一个预测,例如,当范围为 24 时发出 24 个预测,因此单个时间戳可能有许多从不同起点生成的预测。叠加模式让您决定要绘制哪个提前时间(k): + +* 范围索引 0 = 下一步立即 +* 范围索引 1 = 提前 1 步 +* 范围索引 23 = 提前 23 步 + +范围控件默认为**索引 3**,但您可以选择任何值以专注于不同的提前时间。 + +下图显示了启用叠加模式且范围索引为 3。可视化将预测曲线(紫色)直接绘制在实际数据点(带白色填充标记显示)之上。这使您可以评估模型在整个时间线上的三步提前预测的准确性。预测范围显示为预测值周围的阴影带,有助于突出不确定性。 + +*overlay config* + +### 查看多个预测系列 + +高基数预测器可以一次显示许多时间序列。使用结果面板中的**每页时间序列**下拉菜单在以下视图之间切换: + +- **单系列视图**(默认):每页呈现一个实体以获得最大的可读性。 +- **多系列视图**:并排绘制最多五个实体。置信带默认为半透明——将鼠标悬停在线上以突出显示其关联的带。 + +实际线和预测线重叠,因此您可以逐点评估准确性。但是,在**多系列视图**中,重叠的线可能使图表更难解释。要减少视觉混乱,请转到**可视化选项**并关闭**在预测时显示实际数据**。 + +下图显示了实际线和预测线重叠的图表。 + +*Chart with actual and forecast lines overlaid* + +下图显示了相同的图表,在预测时隐藏了实际线以简化视图。 + +*Chart with forecast lines only* + +### 探索时间线 + +使用以下时间线控件导航、放大和过滤预测历史记录的任何跨度: + +* **缩放** – 选择 **+ / –** 以放大预测或扩大上下文。 +* **平移** – 使用箭头按钮移动到较早或较晚的数据点(如果有)。 +* **快速选择** – 选择常见范围,例如"最近 24 小时",或为结果范围提供自定义日期。 + +### 多系列视图中的排序选项 + +当预测器跟踪超过五个实体时,图表无法一次显示每条线。 +在**多系列视图**中,因此您可以选择五个最具信息性的系列,并通过选择排序方法来决定"信息性"的含义。下表列出了可用的排序方法。 + +| 排序方法 | 显示内容 | 何时使用 | +|-------------|--------------|----------------| +| **最小置信区间宽度** *(默认)* | 预测带最窄的五个系列。窄带表示模型对其预测非常确定。 | 显示最"值得信赖"的预测。 | +| **最大置信区间宽度** | 具有最宽带的五个系列——模型最不确定的预测。 | 发现可能需要审查或更多训练数据的风险或嘈杂系列。 | +| **范围内的最小值** | 预测窗口中每个实体的最低预测点,按升序排序。 | 识别预计下降幅度最大的实体——对容量规划或在潜在下降时发出警报很有用。 | +| **范围内的最大值** | 范围内每个实体的最高预测点,按降序排序。 | 突出显示具有最大预期峰值的系列,例如流量激增或销售激增。 | +| **到阈值的距离** | 按数字阈值(>、<、≥、≤)过滤预测,然后按它们与该阈值的距离对其余部分进行排序。 | 调查突破或几乎突破 SLA 或业务 KPI 的实体,例如"显示预测超过 10,000 个请求的任何内容"。 | + +如果预测器监视五个或更少的实体,**多系列视图**将显示所有实体。当有五个以上实体时,每次更改排序方法或调整阈值时,视图都会动态重新排列它们,确保最相关的系列保持焦点。 + +要专注于特定实体子集,请将**过滤依据**切换到**自定义查询**并输入查询 DSL 查询。以下示例显示 `host` 等于 `server_1` 的实体: + +```json +{ + "nested": { + "path": "entity", + "query": { + "bool": { + "must": [ + { "term": { "entity.name": "host" } }, + { "wildcard": { "entity.value": "server_1" } } + ] + } + } + } +} +``` + +接下来,选择排序方法,例如**范围内的最大值**,然后选择**更新可视化**。图表更新为仅显示 `host:server_1` 的预测系列,根据您选择的条件进行排名。 + +### 编辑预测器 + +如果初始回测显示性能不佳,您可以调整预测器的配置并再次运行测试。 + +要编辑预测器: + +1. 打开预测器的**详细信息**页面并选择**编辑**以进入编辑模式。 +2. 根据需要修改设置——例如,添加**类别字段**,更改**间隔**或增加**历史记录**窗口。 +3. 选择**更新**。验证面板会自动评估新配置并标记任何问题。 + + 下图显示了正在进行的验证过程。 + + *Validation panel loading* + +4. 解决任何验证错误。当面板变为绿色时,选择右上角的**开始测试**以使用更新的参数运行另一次回测。 + +### 实时预测 + +一旦您对预测配置有信心,请转到**详细信息**页面并点击**开始预测**以开始实时预测。预测器将在每个间隔向前生成新的预测。 + +当图表与最新数据同步时,会出现**实时**徽章。 + +与回测不同,如果没有足够的历史数据,实时预测会持续尝试使用实时数据进行初始化。在此初始化期间,预测器会显示初始化状态,直到有足够的数据开始发出预测。 + +## 后续步骤 + +一旦您测试和优化了预测器,您就可以开始使用它来生成实时预测或随时间管理它。要了解如何启动、停止、删除或更新现有预测器,请参阅[管理预测器](/observing-your-data/forecast/managing-forecasters)。 diff --git a/i18n/zh/observing-your-data/forecast/index.md b/i18n/zh/observing-your-data/forecast/index.md new file mode 100644 index 00000000..a36906d4 --- /dev/null +++ b/i18n/zh/observing-your-data/forecast/index.md @@ -0,0 +1,22 @@ +--- +title: 预测 +--- + +# 预测 + +OpenSearch 中的预测功能可以使用随机切割森林(RCF)模型将任何时间序列字段转换为自更新信号。RCF 是一种在线学习模型,可以在每个新数据点到达时增量更新。由于 RCF 实时刷新,它可以立即适应技术条件的变化,而无需昂贵的批量重新训练。每个模型仅使用少量存储空间(通常为几百千字节),因此计算和存储开销都保持在较低水平。 + +::: info NOTE +将预测与[告警](/observing-your-data/alerting/)配对使用,可以在预测值预计突破阈值的那一刻收到通知。 +::: + +## 典型用例 + +预测可用于以下用例。 + +| 领域 | 预测内容 | 运营收益 | +|--------|-------------------|---------------| +| 预测性维护 | 每台机器的未来温度、振动或错误计数 | 在故障前更换部件以避免计划外停机。 | +| 网络预测 | 每个节点的未来吞吐量、延迟或连接计数 | 提前分配带宽以满足服务级别协议(SLA)目标。 | +| 容量和成本优化 | 每个微服务的未来 CPU、RAM 或磁盘使用情况 | 合理调整硬件规模并自动扩展。 | +| 财务和运营规划 | 未来订单量、收入或广告支出效率 | 根据需求信号调整人员配置和预算。 | diff --git a/i18n/zh/observing-your-data/forecast/managing-forecasters.md b/i18n/zh/observing-your-data/forecast/managing-forecasters.md new file mode 100644 index 00000000..3f253822 --- /dev/null +++ b/i18n/zh/observing-your-data/forecast/managing-forecasters.md @@ -0,0 +1,216 @@ +--- +title: 管理预测器 +--- + +# 管理预测器 + +在[创建预测器](/observing-your-data/forecast/getting-started)后,您可以使用**详细信息**页面管理其生命周期和配置。这包括启动或停止预测器、更新其设置或完全删除它。使用此页面监视预测器状态、排除问题并随时间微调行为。 + +## 预测器表 + +**预测器**表提供了您配置的每个预测器的概览。 + +| 列 | 描述 | +|--------|-------------| +| **名称** | 您在创建预测器时分配的名称。 | +| **状态** | 当前生命周期状态——例如,`运行中`、`初始化中`或`测试完成`。点击 <i class="euiIcon euiIcon--xs euiIcon--expand"></i> 图标以获取更多信息,包括最近状态更改的时间戳和任何失败消息。 | +| **索引** | 预测器读取的源索引或别名。 | +| **最后更新** | 最近配置更改的时间戳。 | +| **快速操作** | 根据预测器的当前状态,显示上下文感知按钮,如**启动**、**停止**或**删除**。 | + +## 执行状态 + +预测器(即底层预测作业)可以处于以下任何状态。标记为*自动*的转换在没有用户操作的情况下发生;其他转换需要您手动选择**启动**或**停止**。 + +| 状态 | 描述 | 典型触发器 | +|-------|-------------|------------------| +| **非活动** | 预测器已创建但从未启动。 | 无。 | +| **非活动:已停止** | 预测器在运行后被手动停止。 | 用户选择**停止预测**。 | +| **等待数据以初始化预测** | 作业正在尝试启动但缺少足够的历史数据。 | 自动。 | +| **等待数据以重启预测** | 作业在数据间隙后正在恢复并等待新数据。 | 数据中断后自动。 | +| **初始化测试** | 正在为一次性回测构建模型。 | 在**创建并测试**或**开始测试**时自动。 | +| **测试完成** | 回测已完成,作业不再运行。 | 自动。 | +| **初始化预测** | 正在为持续的实时预测训练模型。 | 选择**开始预测**后自动。 | +| **运行中** | 作业正在流式传输实时数据并生成预测。 | 初始化成功完成时自动。 | +| **初始化测试失败** | 测试失败,通常是由于数据不足。 | 自动。 | +| **初始化预测失败** | 实时模式初始化失败。 | 自动。 | +| **预测失败** | 作业启动但遇到运行时错误,例如分片故障。 | 自动但需要用户关注。 | + +下图说明了状态之间的关系和转换。 + +*Forecast state diagram* + +## 查找和过滤预测器 + +如果您有许多预测器,请使用表底部的分页控件在页面之间导航。您还可以使用搜索栏按**名称**、**状态**或**索引**进行过滤,这在管理大量预测器时会很有帮助。 + +## 对预测值发出警报 + +由于预测结果索引不是系统索引,因此您可以像对任何其他用户索引一样为结果索引创建[告警监视器](/observing-your-data/alerting/)。 + +### 示例警报监视器 + +例如,以下是高基数预测器的监视器。您可以修改计划、查询和聚合以匹配您的用例: + +```json +{ + "name": "test", + "type": "monitor", + "monitor_type": "query_level_monitor", + "enabled": true, + "schedule": { + "period": { + "unit": "MINUTES", + "interval": 1 + } + }, + "inputs": [ + { + "search": { + "indices": [ + "opensearch-forecast-results*" + ], + "query": { + "size": 1, + "query": { + "bool": { + "filter": [ + { + "range": { + "execution_end_time": { + "from": "{{period_end}}||-15m", + "to": "{{period_end}}", + "include_lower": true, + "include_upper": true, + "format": "epoch_millis", + "boost": 1 + } + } + } + ], + "adjust_pure_negative": true, + "boost": 1 + } + }, + "aggregations": { + "metric": { + "max": { + "field": "forecast_upper_bound" + } + } + } + } + } + } + ], + "triggers": [ + { + "query_level_trigger": { + "id": "29oAl5cB5QuI4WJQ3hnx", + "name": "breach", + "severity": "1", + "condition": { + "script": { + "source": "return ctx.results[0].aggregations.metric.value == null ? false : ctx.results[0].aggregations.metric.value > 10000", + "lang": "painless" + } + }, + "actions": [ + { + "id": "notification378084", + "name": "email", + "destination_id": "2uzIlpcBMf-0-aT5HOtn", + "message_template": { + "source": "Monitor **{{ctx.monitor.name}}** entered **ALERT** state — please investigate.\n\nTrigger : {{ctx.trigger.name}}\nSeverity : {{ctx.trigger.severity}}\nTime range : {{ctx.periodStart}} → {{ctx.periodEnd}} UTC\n\nEntity\n{{#ctx.results.0.hits.hits.0._source.entity}}\n • {{name}} = {{value}}\n{{/ctx.results.0.hits.hits.0._source.entity}}\n", + "lang": "mustache" + }, + "throttle_enabled": true, + "subject_template": { + "source": "Alerting Notification action", + "lang": "mustache" + }, + "throttle": { + "value": 15, + "unit": "MINUTES" + } + } + ] + } + } + ], + "ui_metadata": { + "schedule": { + "timezone": null, + "frequency": "interval", + "period": { + "unit": "MINUTES", + "interval": 1 + }, + "daily": 0, + "weekly": { + "tue": false, + "wed": false, + "thur": false, + "sat": false, + "fri": false, + "mon": false, + "sun": false + }, + "monthly": { + "type": "day", + "day": 1 + }, + "cronExpression": "0 */1 * * *" + }, + "monitor_type": "query_level_monitor", + "search": { + "searchType": "query", + "timeField": "execution_end_time", + "aggregations": [ + { + "aggregationType": "max", + "fieldName": "forecast_upper_bound" + } + ], + "groupBy": [], + "bucketValue": 15, + "bucketUnitOfTime": "m", + "filters": [] + } + } +} +``` + +### 监视器设计 + +下表解释了示例警报监视器中使用的每个设计选择及其重要性。 + +| 设计选择 | 理由 | +|---------------|-----------| +| 搜索输入中的 `size: 1` | 检索单个文档,以便您可以在通知中引用 `ctx.results.0.hits.hits.0` 以识别触发警报的实体(例如 `host` 或 `service`)。 | +| `execution_end_time` 范围 `"now-15m"` → `now` | 过滤结果创建时间戳,该时间戳反映预测生成的时间。这避免了由摄取延迟引起的延迟。如果您的索引包含延迟到达的数据(例如回填日志),请避免过滤 `data_end_time`。 | +| `max(forecast_upper_bound)` 作为指标 | 检测上界峰值。替代方案包括:<br> `min(forecast_lower_bound)` 用于突然下降。<br> `avg(forecast_value)` 用于趋势转变。<br> 有关其他字段,请参阅[预测结果架构](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/mappings/forecast-results.json)。 | +| 索引模式 `opensearch-forecast-results*` | 匹配默认结果索引模式。如果您将结果路由到自定义索引,请更新此模式,例如 `opensearch-forecast-result-abc*`。 | +| 可选的 `forecaster_id` 术语过滤器 | 使用此过滤器定位特定预测器并避免匹配不相关的预测。 | +| 每 1 分钟监视一次,查询窗口 15 分钟 | 每分钟评估预测以快速检测异常。15 分钟的回看窗口增加了对定时延迟的弹性。结合 15 分钟的警报节流,这避免了同一事件的重复通知。 | +| Mustache 块打印所有实体维度 | 显示单维度(`host=server_3`)和多维度(`host=server_3`,`service=auth`)实体值。您还可以包含指向预过滤仪表板的链接以加快分类。 | +| 阈值 | 使用 OpenSearch Dashboards 可视化编辑器分析最近的预测值,并确定可靠指示异常的适当阈值。 | + +### 示例警报 + +以下示例显示了由监视器生成的示例警报电子邮件,该监视器检测预测值何时突破定义的阈值。在这种情况下,监视器正在跟踪高基数预测器,并为特定实体(`host = server_3`)触发了警报: + +``` +Monitor **test** entered **ALERT** state — please investigate. + +Trigger : breach +Severity : 1 +Time range : 2025-06-22T09:56:14.490Z → 2025-06-22T09:57:14.490Z UTC + +Entity + • host = server_3 +``` + +## 后续步骤 + +在设置和管理预测器后,您可能希望控制谁可以访问和修改它们。要了解如何管理权限、保护结果索引和应用细粒度访问控制,请参阅[安全性页面](/observing-your-data/forecast/security)。 diff --git a/i18n/zh/observing-your-data/forecast/security.md b/i18n/zh/observing-your-data/forecast/security.md new file mode 100644 index 00000000..56805819 --- /dev/null +++ b/i18n/zh/observing-your-data/forecast/security.md @@ -0,0 +1,447 @@ +--- +title: 预测安全性 +--- + +# 预测安全性 + +预测使用与异常检测相同的安全框架。本页说明如何为用户配置权限以创建、运行和查看预测器;如何限制对系统索引的访问;以及如何跨团队隔离预测结果。 + +要使用资源共享控制对单个预测器的访问,请参阅[预测器访问控制](/observing-your-data/forecast/forecaster-access-control)。 + +::: info NOTE +在所有示例中,将凭据、索引名称和角色名称替换为适合您环境的值。 +::: + +## 预测创建的索引 + +下表描述了预测 API 使用的索引及其对常规用户的可见性。 + +| 索引模式 | 用途 | 对常规用户可见? | +|---------------|---------|---------------------------| +| `.opensearch-forecasters` | 存储预测器配置。 | 否 | +| `.opensearch-forecast-checkpoints` | 存储模型快照(检查点)。 | 否 | +| `.opensearch-forecast-state` | 存储实时和一次性预测的任务元数据。 | 否 | +| `opensearch-forecast-result*` | 存储回测和实时预测的预测结果。 | 是 | + +用户不需要直接访问 `.opensearch-forecast-checkpoints`;它由预测内部使用。 + +要查看 `.opensearch-forecasters`,请使用[获取预测器](/observing-your-data/forecast/api#get-forecaster)或[搜索预测器](/observing-your-data/forecast/api#search-forecasters) API。 + +要查看 `.opensearch-forecast-state`,请使用带 `?task=true` 查询参数的[获取预测器](/observing-your-data/forecast/api#get-forecaster) API,或直接调用[搜索任务](/observing-your-data/forecast/api#search-tasks) API。 + +## 集群权限 + +每个预测 API 路由映射到特定的集群级权限,如下表所示。您必须向管理或与预测器交互的角色授予这些权限。 + +| 路由 | 必需权限 | +|:------------|:---------------------| +| `POST /_plugins/_forecast/forecasters` | `cluster:admin/plugin/forecast/forecaster/write` | +| `PUT /_plugins/_forecast/forecasters/{id}` | `cluster:admin/plugin/forecast/forecaster/write` | +| `POST /_plugins/_forecast/forecasters/_validate` | `cluster:admin/plugin/forecast/forecaster/validate` | +| `POST /_plugins/_forecast/forecasters/_suggest/{types}` | `cluster:admin/plugin/forecast/forecaster/suggest` | +| `GET /_plugins/_forecast/forecasters/{id}` <br>`GET /_plugins/_forecast/forecasters/{id}?task=true` | `cluster:admin/plugin/forecast/forecasters/get` | +| `DELETE /_plugins/_forecast/forecasters/{id}` | `cluster:admin/plugin/forecast/forecaster/delete` | +| `POST /_plugins/_forecast/forecasters/{id}/_start` <br>`POST /_plugins/_forecast/forecasters/{id}/_stop` | `cluster:admin/plugin/forecast/forecaster/jobmanagement` | +| `POST /_plugins/_forecast/forecasters/{id}/_run_once` | `cluster:admin/plugin/forecast/forecaster/runOnce` | +| `POST /_plugins/_forecast/forecasters/_search` <br>`GET /_plugins/_forecast/forecasters/_search` | `cluster:admin/plugin/forecast/forecasters/search` | +| `GET /_plugins/_forecast/forecasters/tasks/_search` | `cluster:admin/plugin/forecast/tasks/search` | +| `POST /_plugins/_forecast/forecasters/{id}/results/_topForecasts` | `cluster:admin/plugin/forecast/result/topForecasts` | +| `GET /_plugins/_forecast/forecasters/{id}/_profile` | `cluster:admin/plugin/forecast/forecasters/profile` | +| `GET /_plugins/_forecast/stats` | `cluster:admin/plugin/forecast/forecaster/stats` | +| `GET /_plugins/_forecast/forecasters/count` <br>`GET /_plugins/_forecast/forecasters/match` | `cluster:admin/plugin/forecast/forecaster/info` | + +## 必需角色 + +预测用户需要三种类型的权限,基于以下职责: + +- 管理预测作业 +- 读取源数据 +- 访问预测结果 + +这些职责对应于三个不同的安全层,如下表所示。 + +| 层 | 控制内容 | 典型角色 | +|-------|------------------|--------------| +| **预测器控制** | 创建、编辑、启动、停止、删除或查看预测器配置的权限。 | `forecast_full_access` <br>(管理生命周期)<br>或<br>`forecast_read_access` <br>(仅查看) | +| **数据源读取** | 授予预测器查询用于训练和预测的原始指标索引的权限。 | 自定义角色,例如 `data_source_read` | +| **结果读取** | 授予用户和告警监视器访问 `opensearch-forecast-result*` 中文档的权限。 | 自定义角色,例如 `forecast_result_read` | + +::: info NOTE +内置角色 `forecast_full_access` 和 `forecast_read_access` 仅适用于预测 API。它们**不**包括源或结果索引的权限——必须单独授予这些权限。 +::: + +### 预测器控制角色 + +预测 API 包括两个内置角色,您可以按原样使用它们,或将其用作创建自定义角色的模板: + +- `forecast_read_access` – 适用于需要对预测器进行只读访问的分析师。此角色允许用户查看预测器详细信息和结果,但不能创建、修改、启动、停止或删除预测器。 + +- `forecast_full_access` – 适用于负责管理预测器整个生命周期的用户,包括创建、编辑、启动、停止和删除它们。此角色**不**授予对源索引的访问权限。要创建预测器,用户还必须具有索引级权限,包括对预测器读取的任何索引或别名的 `search` 操作。 + +以下示例显示了如何定义这些角色: + +```yaml +forecast_read_access: + reserved: true + cluster_permissions: + - 'cluster:admin/plugin/forecast/forecaster/info' + - 'cluster:admin/plugin/forecast/forecaster/stats' + - 'cluster:admin/plugin/forecast/forecaster/suggest' + - 'cluster:admin/plugin/forecast/forecaster/validate' + - 'cluster:admin/plugin/forecast/forecasters/get' + - 'cluster:admin/plugin/forecast/forecaster/info' + - 'cluster:admin/plugin/forecast/forecasters/search' + - 'cluster:admin/plugin/forecast/result/topForecasts' + - 'cluster:admin/plugin/forecast/tasks/search' + index_permissions: + - index_patterns: + - 'opensearch-forecast-result*' + allowed_actions: + - 'indices:admin/mappings/fields/get*' + - 'indices:admin/resolve/index' + - 'indices:data/read*' + +forecast_full_access: + reserved: true + cluster_permissions: + - 'cluster:admin/plugin/forecast/*' + - 'cluster:admin/settings/update' + - 'cluster_monitor' + index_permissions: + - index_patterns: + - '*' + allowed_actions: + - 'indices:admin/aliases/get' + - 'indices:admin/mapping/get' + - 'indices:admin/mapping/put' + - 'indices:admin/mappings/fields/get*' + - 'indices:admin/mappings/get' + - 'indices:admin/resolve/index' + - 'indices:data/read*' + - 'indices:data/read/field_caps*' + - 'indices:data/read/search' + - 'indices:data/write*' + - 'indices_monitor' +``` + +这些角色不包括特定源或结果索引的默认 `index_permissions`。这是有意为之的,允许您根据数据访问要求添加自己的模式。 + +### 数据源 `read` 角色 + +每个预测器使用创建用户的凭据查询源索引。要启用此功能,您必须为该用户授予对您自己的数据索引的读取权限。 + +以下示例请求创建了一个允许对 `network-metrics` 索引进行读取访问的最小角色: + +```json +PUT _plugins/_security/api/roles/data_source_read +{ + "index_permissions": [{ + "index_patterns": ["network-metrics"], + "allowed_actions": ["read"] + }] +} +``` + +您可以修改 `index_patterns` 以匹配您的实际数据源。 + +### 结果读取角色 + +`forecast_result_read` 角色允许用户查看预测结果并配置查询这些结果的告警监视器。 + +以下示例请求定义了一个角色,该角色授予对匹配 `opensearch-forecast-result*` 模式的所有索引的读取访问权限: + +```json +PUT _plugins/_security/api/roles/forecast_result_read +{ + "index_permissions": [{ + "index_patterns": ["opensearch-forecast-result*"], + "allowed_actions": ["read"] + }] +} +``` + +如果您需要在团队之间隔离结果数据,可以使用带有后端角色过滤器的文档级安全性(DLS)增强此角色,如以下部分所示。 + +### 示例安全角色配置 + +以下示例请求创建 `devOpsEngineer` 用户并分配预测所需的所有三个角色: + +```json +PUT _plugins/_security/api/internalusers/devOpsEngineer +{ + "password": "DevOps2024!", + "opendistro_security_roles": [ + "forecast_full_access", + "data_source_read", + "forecast_result_read" + ] +} +``` + +此配置启用以下功能: + +- `devOpsEngineer` 可以管理预测器(`forecast_full_access`)。 +- 预测器可以成功查询源索引(`data_source_read`)。 +- 用户和任何配置的监视器可以读取预测结果(`forecast_result_read`)。 + +要授予对预测器配置的只读访问权限,请将 `forecast_full_access` 替换为 `forecast_read_access`。 + +--- + +## (高级)按后端角色限制访问 + +您可以使用后端角色强制执行**特定于团队的隔离**。此模式允许不同的团队独立操作预测器,同时分离配置和结果。 + +该模型包括三层: + +1. **配置隔离** – 预测 API 仅限于具有匹配后端角色的用户。 +2. **结果隔离** – DLS 限制对 `opensearch-forecast-result*` 中预测结果的访问。 +3. **源数据访问** – 最小只读角色使每个预测器能够扫描其自己的索引。 + +以下部分说明了如何配置每一层。 + +### 为用户分配后端角色 + +在大多数环境中,后端角色通过 LDAP 或 SAML 分配。但是,如果您使用的是内部用户数据库,则可以手动设置它们,如以下示例所示: + +```json +# 分析师 +PUT _plugins/_security/api/internalusers/alice +{ + "password": "alice", + "backend_roles": ["analyst"] +} + +# HR 员工 +PUT _plugins/_security/api/internalusers/bob +{ + "password": "bob", + "backend_roles": ["human-resources"] +} +``` + +然后可以使用这些后端角色按团队控制对预测器和预测结果的访问。 + +### 为配置访问启用后端角色过滤 + +要按团队隔离预测器配置,请在集群级别启用后端角色过滤: + +```bash +PUT _cluster/settings +{ + "persistent": { + "plugins.forecast.filter_by_backend_roles": true + } +} +``` + +启用此设置后,OpenSearch 在每个预测器文档中记录创建者的后端角色。只有具有匹配后端角色的用户才能查看、编辑或删除该预测器。 + +### 为每个团队创建 `result‑access` 角色 + +预测结果存储在共享索引中,因此使用 DLS 按后端角色限制访问。 + +以下示例请求创建了一个角色,该角色允许具有 `analyst` 后端角色的用户仅读取和写入其团队的预测结果: + +```json +PUT _plugins/_security/api/roles/forecast_analyst_result_access +{ + "index_permissions": [{ + "index_patterns": ["opensearch-forecast-result*"], + "dls": """ + { + "bool": { + "filter": [{ + "nested": { + "path": "user", + "query": { + "term": { + "user.backend_roles.keyword": "analyst" + } + }, + "score_mode": "none" + } + }] + } + }""", + "allowed_actions": ["read","write"] + }] +} +``` + +要为另一个团队(例如 `human-resources`)隔离结果,请创建一个单独的角色(例如,`forecast_human_resources_result_access`)并更新术语值以匹配适当的后端角色。 + +### 定义 `data-source` 读取访问权限 + +`data_source_read` 角色的定义方式与前面示例中的相同。它授予对每个预测器用于训练和预测的指标索引的最小读取访问权限。 + +您可以跨团队重用此角色,或者如果需要按索引限制,则创建单独的版本。 + +### 将用户映射到三个角色 + +以下示例使用 `analyst` 后端角色将用户 `alice` 映射到所有三个必需角色——`full_access`、`result_access` 和 `data_source_read`: + +```json +PUT _plugins/_security/api/internalusers/alice +{ + "password": "alice", + "backend_roles": ["analyst"], + "opendistro_security_roles": [ + "forecast_full_access", + "forecast_analyst_result_access", + "data_source_read" + ] +} +``` + +通过此配置,Alice 可以: + +- 仅创建、启动、停止和删除标记有 `analyst` 后端角色的预测器。 +- 仅查看标记有 `analyst` 后端角色的预测结果。 +- 读取 `network-metrics` 索引作为其预测器的源。 + +要配置第二个用户,例如来自 HR 团队的 `bob`,请使用 `human-resources` 后端角色和 `forecast_human_resources_result_access` 进行并行设置。 + +### 没有后端角色的用户 + +如果用户具有 `forecast_read_access` 角色但没有后端角色,他们将无法查看任何预测器。后端角色过滤强制执行严格匹配,并阻止访问与用户角色不一致的配置。 + +--- + +## 使用细粒度访问控制选择远程索引 + +要将远程索引用作预测器的数据源,请按照[跨集群搜索](/search-plugins/cross-cluster-search)文档的[身份验证流程](/search-plugins/cross-cluster-search#authentication-flow)部分中概述的步骤操作。 + +要成功,用户必须: + +- 使用本地和远程集群中都存在的安全角色。 +- 在两个集群中将该角色映射到相同的用户名。 + +### 示例:在本地集群中创建新用户 + +使用以下命令,在本地集群中创建可以创建预测器的新用户: + +```bash +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/internalusers/forecastuser' \ + -H 'Content-Type: application/json' \ + -d '{"password":"password"}' +``` + +使用以下命令,将新用户映射到 `forecast_full_access` 角色: + +``` +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/rolesmapping/forecast_full_access' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` + +在远程集群中,创建相同的用户并将 `forecast_full_access` 映射到该角色,如以下命令所示: + +```bash +# 创建用户 +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/internalusers/forecastuser' \ + -H 'Content-Type: application/json' \ + -d '{"password":"password"}' + +# 映射角色 +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/rolesmapping/forecast_full_access' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` + +### 在两个集群中授予源索引读取访问权限 + +要创建预测器,用户还需要对预测器读取的每个源索引、别名或模式的 `search` 或 `read` [操作组](/security/access-control/default-action-groups)的索引级权限。读取远程索引时,权限检查在两个集群中都会发生。在两个位置定义和映射相同的角色。 + +在本地集群中,定义一个授予对源索引访问权限的 `read` 角色,并将其映射到预测用户,如以下命令所示: + +```bash +# 创建可以搜索数据的角色 +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/roles/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{ + "index_permissions":[{ + "index_patterns":["network-requests"], + "allowed_actions":["search"] + }] + }' + +# 将角色映射到 forecastuser +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9200/_plugins/_security/api/rolesmapping/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` + +在远程集群中,定义相同的角色并将其映射到相同的用户以确保权限跨集群镜像,如以下命令所示: + +``` +# 创建相同的角色 +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/roles/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{ + "index_permissions":[{ + "index_patterns":["network-requests"], + "allowed_actions":["search"] + }] + }' + +# 将角色映射到相同的用户 +curl -XPUT -k -u 'admin:<custom-admin-password>' \ + 'https://localhost:9250/_plugins/_security/api/rolesmapping/data_source_read' \ + -H 'Content-Type: application/json' \ + -d '{"users":["forecastuser"]}' +``` + +### 向本地集群注册远程集群 + +使用 `cluster.remote.<alias>.seeds` 设置下的种子节点向本地集群注册远程集群。在 OpenSearch 中,这称为添加 `follower` 集群。 + +假设远程集群在传输端口 `9350` 上侦听,请在本地集群中运行以下命令: + +``` +curl -X PUT "https://localhost:9200/_cluster/settings" \ + -H "Content-Type: application/json" \ + -u "admin:<custom-admin-password>" \ + -d '{ + "persistent": { + "cluster.remote": { + "follower": { + "seeds": [ "127.0.0.1:9350" ] + } + } + } + }' +``` + +::: info NOTE +- 如果远程节点位于不同的主机上,请将 `127.0.0.1` 替换为远程节点的传输层 IP。 +- 别名 `follower` 可以是您选择的任何名称,并将在引用远程索引或配置跨集群复制时使用。 +::: + +--- + +## 自定义结果索引权限 + +您可以为预测结果指定自定义索引,而不是使用默认结果索引。如果自定义索引尚不存在,则在您创建预测器并启动实时分析或测试运行时,它将自动创建。 + +如果自定义索引已存在,预测 API 会检查索引映射是否与预期的预测结果结构匹配。为了确保兼容性,索引必须符合 [`forecast-results.json`](https://github.com/opensearch-project/anomaly-detection/blob/main/src/main/resources/mappings/forecast-results.json) 文件中定义的架构。 + +当用户创建预测器时——无论是在 OpenSearch Dashboards 中还是通过调用预测 API——系统会验证用户是否具有自定义索引的以下索引级权限: + +- `indices:admin/create` – 创建和滚动自定义结果索引所需。 +- `indices:admin/aliases` – 创建和管理索引别名所需。 +- `indices:data/write/index` – 将预测结果写入索引(单流预测器)所需。 +- `indices:data/read/search` – 显示预测结果时搜索自定义索引所需。 +- `indices:data/write/delete` – 删除较旧的预测结果和管理磁盘使用所需。 +- `indices:data/write/bulk*` – 必需,因为预测使用批量 API 写入结果。 + +## 下一步 + +有关 TLS、身份验证后端、租户隔离和审计日志记录的更多信息,请参阅[安全插件文档](/security/)。 diff --git a/i18n/zh/observing-your-data/ingesting-observability-data.md b/i18n/zh/observing-your-data/ingesting-observability-data.md new file mode 100644 index 00000000..492af9ee --- /dev/null +++ b/i18n/zh/observing-your-data/ingesting-observability-data.md @@ -0,0 +1,34 @@ +--- +title: 采集可观测性数据 +--- + +# 采集可观测性数据 + +在您可以在 OpenSearch Dashboards 中分析可观测性数据之前,您的应用程序必须将数据发送到 OpenSearch 或 OpenSearch 可以查询的后端。日志和追踪存储在 OpenSearch 索引中。指标存储在 Prometheus 中,OpenSearch 通过 Prometheus 数据源查询它,或者存储在 OpenSearch 索引中。 + +文档中描述的设置使用以下组件: + +- 使用 [OpenTelemetry](https://opentelemetry.io/docs/) SDK 检测的应用程序生成追踪、指标和日志。 +- 日志收集器,如 [Fluent Bit](https://docs.fluentbit.io/manual/),读取日志文件并发送日志行。 +- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) 从应用程序接收数据并按类型路由。 +- [OpenSearch Data Prepper](/data-prepper/) 解析和丰富日志和追踪,并将它们写入 OpenSearch 索引。 +- [Prometheus](https://prometheus.io/) 存储指标。OpenSearch 通过 [Prometheus 数据源](/dashboards/management/connect-prometheus)查询 Prometheus,因此 Prometheus 服务器必须可以从 OpenSearch 节点访问。 + +## 采集路径 + +下表列出了可观测性数据到达 OpenSearch 或 Prometheus 的典型路径。找到您想要采集的数据类型,然后按照其路径的设置说明进行操作。 + +| 数据 | 路径 | 设置 | +|:---|:---|:---| +| 日志 | 日志收集器或 OpenTelemetry Collector → Data Prepper → OpenSearch 索引 <br><br> 或 <br><br> 日志收集器 → OpenSearch 索引 | [日志分析入门](/observing-your-data/log-ingestion)(Fluent Bit 教程)<br> [将日志数据采集到 OpenSearch](/data-prepper/getting-started/ingesting-log-data) <br> [日志分析](/data-prepper/common-use-cases/log-analytics) <br> [OTel 日志源](/data-prepper/pipelines/configuration/sources/otel-logs-source) <br> [Fluent Bit OpenSearch 输出](https://docs.fluentbit.io/manual/pipeline/outputs/opensearch) <br> [Logstash](/tools/logstash/) | +| 追踪 | 检测的应用程序 → OpenTelemetry Collector → Data Prepper → OpenSearch 跨度和服务映射索引 | [追踪分析入门](/observing-your-data/trace/getting-started)(Jaeger HotROD 教程)<br> [使用 Data Prepper 进行追踪分析](/data-prepper/common-use-cases/trace-analytics) <br> [OTel 追踪源](/data-prepper/pipelines/configuration/sources/otel-trace-source) | +| 指标 | 检测的应用程序 → OpenTelemetry Collector → Prometheus <br><br> 或 <br><br> 检测的应用程序 → OpenTelemetry Collector → Data Prepper → OpenSearch 索引 | [将 Prometheus 连接到 OpenSearch](/dashboards/management/connect-prometheus) <br> [指标分析](/observing-your-data/prometheusmetrics) <br> [OTel 指标源](/data-prepper/pipelines/configuration/sources/otel-metrics-source) | +| APM 的日志、追踪和指标 | 检测的应用程序 → OpenTelemetry Collector → Data Prepper → OpenSearch 索引(日志和追踪)和 Prometheus(指标) | [配置遥测采集](/observing-your-data/apm/configuring-telemetry-ingestion) | +| 代理追踪 | 使用 OpenSearch 生成式 AI 可观测性 SDK 检测的应用程序 → OpenTelemetry Collector → Data Prepper → OpenSearch 索引 | [检测您的应用程序](/observing-your-data/agent-traces/instrument) | + +追踪分析和 APM 需要其 Data Prepper 管道创建的数据,因此请按照您计划使用的应用程序的设置说明进行操作。 + +## 相关文档 + +- 要为常见数据源安装预配置的仪表板和可视化,请参阅[集成](/dashboards/integrations/)。 +- 有关某些经典可观测性应用程序所需的索引命名约定和字段映射,请参阅[可观测性简单模式](/observing-your-data/ss4o)。 diff --git a/i18n/zh/observing-your-data/log-analytics.md b/i18n/zh/observing-your-data/log-analytics.md new file mode 100644 index 00000000..e69de29b diff --git a/i18n/zh/observing-your-data/notifications/notification-access-control.md b/i18n/zh/observing-your-data/notifications/notification-access-control.md new file mode 100644 index 00000000..424617a1 --- /dev/null +++ b/i18n/zh/observing-your-data/notifications/notification-access-control.md @@ -0,0 +1,142 @@ +--- +title: 通知访问控制 +--- + +# 通知访问控制 + +通知与安全插件的资源共享和访问控制框架集成,为通知配置提供文档级授权。通知配置是通道的底层文档,因此共享配置可控制对相应通道的访问。资源共享替换了旧的 `opensearch.notifications.general.filter_by_backend_roles` 设置,并允许资源所有者向用户、角色或后端角色授予特定的访问级别。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +下表描述了通知配置资源。 + +| 字段 | 值 | +| :--- | :--- | +| 资源类型 | `notification_config` | +| 系统索引 | `.opensearch-notifications-config` | +| 加入版本 | 3.9 版本引入 | + +当启用资源级授权时,每个通知配置的可见性由中央共享记录控制。资源所有者和具有共享功能的用户可以为特定用户、角色或后端角色授予或撤销访问权限。当用户列出通知配置或通道时,响应仅包含用户拥有或与用户共享的配置。 + +## 启用通知资源共享 + +要为通知启用资源共享,请将通知配置资源类型添加到受保护类型列表中,并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅限管理员:这些设置只能由具有更新集群设置权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 `opensearch.yml` 配置文件以启用通知的资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "notification_config" +``` + +添加到 `opensearch.yml` 的设置在集群重启后生效。 + +### 使用集群设置 API 配置 + +要在不重启集群的情况下启用资源共享,请使用集群设置 API: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["notification_config"] + } +} +``` + +`plugins.security.system_indices.enabled` 设置无法使用集群设置 API 更新,因此请在 `opensearch.yml` 中设置它。 + +::: info NOTE +将通知配置资源类型添加到现有配置时,请在 `protected_types` 数组中包含所有先前配置的资源类型。 +::: + +## 通知访问级别 + +通知为通知配置文档提供三个预定义的访问级别。每个访问级别确定用户可以对与其共享的通知配置执行的操作。 + +### notifications_read_only + +`notifications_read_only` 只读访问级别授予用户查看共享通知配置和通道的能力,但不能修改它们。此访问级别包括以下权限: + +```yaml +- 'cluster:admin/opensearch/notifications/configs/get' +- 'cluster:admin/opensearch/notifications/channels/get' +- 'cluster:admin/opensearch/notifications/features' +``` + +### notifications_read_write + +`notifications_read_write` 读写访问级别授予用户对通知配置操作的完全访问权限,但共享功能除外。此访问级别包括所有读取权限以及写入和发送操作: + +```yaml +- 'cluster:admin/opensearch/notifications/configs/*' +- 'cluster:admin/opensearch/notifications/channels/get' +- 'cluster:admin/opensearch/notifications/features' +- 'cluster:admin/opensearch/notifications/feature/send' +- 'cluster:admin/opensearch/notifications/test_notification' +``` + +### notifications_full_access + +`notifications_full_access` 完全访问级别授予用户对通知配置的完全控制,包括类似所有者的权限,如与其他用户共享资源。此访问级别包括所有通知操作以及资源共享权限: + +```yaml +- 'cluster:admin/opensearch/notifications/configs/*' +- 'cluster:admin/opensearch/notifications/channels/get' +- 'cluster:admin/opensearch/notifications/features' +- 'cluster:admin/opensearch/notifications/feature/send' +- 'cluster:admin/opensearch/notifications/test_notification' +- 'cluster:admin/security/resource/share' +``` + +::: info NOTE +这些访问级别是预定义的,无法修改。要请求其他访问级别,请在 [Notifications GitHub 仓库](https://github.com/opensearch-project/notifications/)中创建问题。 +::: + +## 从旧框架迁移 + +在启用资源共享并将通知配置资源类型标记为受保护后,集群管理员必须运行迁移 API,将现有通知共享信息从旧框架传输到新的资源共享系统。在运行迁移之前,现有通知配置没有共享记录,因此所有用户(包括创建它们的用户)都无法访问它们。 + +::: warning IMPORTANT +仅限管理员:迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +通知配置文档在 `metadata.access` 下跟踪其授权的后端角色,并且不存储每个用户的所有者。将 `backend_roles_path` 设置为 `/metadata/access`。`username_path` 参数是必需的且不能为空,因此将其指向通知文档不包含的字段,如 `/metadata/owner`。路径解析为无值,因此所有权回退到 `default_owner`。 + +使用以下 API 调用将旧通知共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opensearch-notifications-config", + "username_path": "/metadata/owner", + "backend_roles_path": "/metadata/access", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "notification_config": "<select-appropriate-access-level>" + } +} +``` + +将 `<replace-with-existing-user>` 替换为应该拥有通知配置的现有用户的用户名。由于通知文档不携带所有者名称,因此每个迁移的配置都归属于此用户。将 `<select-appropriate-access-level>` 替换为可用的通知访问级别之一:`notifications_read_only`、`notifications_read_write` 或 `notifications_full_access`。迁移以此访问级别与存储在其 `metadata.access` 字段中的后端角色共享每个配置。如果省略 `default_access_level`,迁移将使用 `notifications_read_only`。没有后端角色的配置在没有共享的情况下迁移,因此只有默认所有者可以访问它们。 + +## 相关文档 + +以下页面提供有关资源共享的更多信息: + +- [资源共享和访问控制](/security/access-control/resources/) +- [资源共享 API](/security/access-control/resource-sharing-api/) +- [资源访问管理](/dashboards/management/resource-sharing) diff --git a/i18n/zh/observing-your-data/slo/index.md b/i18n/zh/observing-your-data/slo/index.md new file mode 100644 index 00000000..0fda0642 --- /dev/null +++ b/i18n/zh/observing-your-data/slo/index.md @@ -0,0 +1,173 @@ +--- +title: SLO +--- + +# 服务级别目标 +<Badge type="tip" text="3.7 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想留下反馈,请加入 [OpenSearch 论坛](https://forum.opensearch.org/)上的讨论。 +::: + +服务级别目标(SLO)让您定义服务的可用性和延迟目标,将支持的记录和告警规则部署到与 Prometheus 兼容的规则器,并从 OpenSearch Dashboards 中的专用视图跟踪应用程序健康状况、错误预算和预算消耗率(燃尽率)。 + +SLO 整合了来自 OpenSearch 监控器和 Prometheus 告警规则的告警,因此您可以跨数据源监控服务健康状况,而无需在工具之间切换。 + +当您创建 SLO 时,OpenSearch Dashboards 根据您的配置生成 Prometheus 记录和告警规则,并将它们部署到您的 Prometheus 兼容规则器。规则跟踪每个目标的健康状况、达成情况和剩余错误预算。 + +下表定义了 SLO 和 SLI 术语。 + +| 术语 | 定义 | +| :--- | :--- | +| 服务级别指标(SLI) | 服务性能的定量测量,例如可用性或延迟。支持的 SLI 类型有 `availability`、`latency_threshold` 和 `custom`。 | +| 服务级别目标(SLO) | 一个或多个 SLI 的目标达成级别,在单个时间窗口内评估。每个 SLO 包含一个或多个目标。 | +| 目标 | SLI 的目标值,表示为 `0.5` 到 `0.99999` 之间的小数(例如,`0.999`)。每个目标生成自己的记录和告警规则集。 | +| 时间窗口 | 评估 SLO 的滚动周期(例如,`7d`、`28d`、`30d`)。尚不支持日历窗口。 | +| 错误预算 | 时间窗口内允许的失败事件比例。当错误预算降至零以下时,目标被违反。 | +| 燃尽率 | 相对于时间窗口消耗错误预算的速率。用于在不同严重性级别触发告警。 | +| SLO 模式 | 控制告警是否活跃。在 `active` 模式下,记录和告警规则都会部署。在 `shadow` 模式下,仅部署记录规则,这对于在启用告警之前验证 SLO 很有用。 | +| 数据源 | SLO 使用的 `DirectQuery` Prometheus 连接。每个 SLO 绑定到单个数据源。 | +| 工作区 | SLO 所属的 OpenSearch Dashboards 工作区。每个工作区都有自己的 SLO 和规则器命名空间集。 | + +## 先决条件 + +在使用 SLO 之前,请完成以下设置步骤。 + +### 启用功能 + +SLO 默认情况下是禁用的。要启用它们,请将以下设置添加到 `opensearch_dashboards.yml`: + +```yaml +workspace.enabled: true +explore.enabled: true +explore.discoverTraces.enabled: true +observability.slo.enabled: true +``` + +然后重启 OpenSearch Dashboards。 + +### 可观测性工作区 + +SLO 功能在可观测性[工作区](/dashboards/workspace/)中可用。要创建工作区,请按照以下步骤操作: + +1. 导航到 OpenSearch Dashboards 主页。 +2. 选择 **Create workspace**。 +3. 输入工作区名称。 +4. 选择 **Observability** 用例。 +5. 选择 **Create workspace**。 + +### Prometheus 兼容规则器 + +SLO 通过 `DirectQuery` 资源代理将记录和告警规则部署到与 Prometheus 兼容的规则器(Cortex 或 Grafana Mimir)。规则器必须支持以下 API 端点: + +- `POST /api/v1/rules/{namespace}` -- 创建或更新规则组。 +- `DELETE /api/v1/rules/{namespace}/{groupName}` -- 删除规则组。 + +给定工作区的规则组被写入命名空间 `slo-generated-<workspace-id>`。租户标识(例如,`X-Scope-OrgID`)在 [Prometheus 连接器](/dashboards/management/connect-prometheus)设置中配置。 + +### 数据源 + +每个 SLO 绑定到单个数据源,该数据源必须是已注册的 `DirectQuery` Prometheus 连接。有关配置 Prometheus 数据源的信息,请参阅[将 Prometheus 连接到 OpenSearch](/dashboards/management/connect-prometheus)。 + +### 数据先决条件 + +SLI 定义确定规则器必须能够查询的数据: + +- **可用性和延迟阈值 SLI** 要求配置的后端中存在命名的 Prometheus 计数器或直方图指标。应用程序性能监控(APM)服务模板期望由 [OpenSearch Data Prepper](/data-prepper/) 生成的基于跨度的速率、错误、持续时间(RED)指标。OpenTelemetry(OTel)语义约定模板期望相应的 HTTP、RPC、数据库客户端、消息传递或生成式 AI 指标。 +- **自定义 SLI** 要求您的 PromQL 表达式能够成功针对后端进行评估。 + +## 访问 SLO + +要访问 SLO,请从主页选择您的可观测性工作区,或者如果您没有工作区,请创建一个(请参阅[可观测性工作区](#可观测性工作区))。然后,在左侧导航中,选择 **Application performance** > **SLOs**。 + +## 创建 SLO + +要创建 SLO,请按照以下步骤操作: + +1. 在 **SLOs** 视图中,选择 **Create SLO**。 +2. 选择模板。模板分为以下类别: + - **APM 服务 SLO**:基于来自 [OpenSearch Data Prepper](/data-prepper/) 的 RED 指标的 SLI。模板包括 **APM 服务可用性**、**APM 服务延迟**、**APM 依赖可用性**和 **APM 依赖延迟**。 + - **OTel 语义约定指标**:基于标准 OTel 指标的 SLI。模板包括 **HTTP 可用性**、**HTTP 延迟**、**RPC/gRPC 可用性**、**RPC/gRPC 延迟**、**数据库客户端延迟**、**消息处理延迟**和 **GenAI 调用可用性**。 + - **自定义**:用于自定义 PromQL 表达式的空白 **自定义 PromQL** 模板。 +3. 在向导中配置 SLO。向导包含以下部分: + - **标识**:唯一名称、描述和数据源(已注册的 DirectQuery Prometheus 连接)。 + - **窗口和模式**:滚动窗口(例如,`28d`)和可选的影子模式,该模式部署记录规则而不告警。 + - **服务和所有者**:服务名称和所有者团队。 + - **SLI**:对于预构建模板,SLI 类型和指标是预配置的。您可以选择添加维度(标签过滤器)以缩小查询范围。对于 **自定义 PromQL** 模板,您提供自己的 PromQL 表达式——要么是单独的良好事件和总事件查询,要么是单个预计算的错误率查询。 + - **探测 SLI**:在可配置的回溯期(`1h`、`24h` 或 `7d`)内针对 Prometheus 后端测试建议的查询,以便您可以在创建 SLO 之前验证查询返回数据。 + - **目标**:一个或多个介于 `0.5` 和 `0.99999` 之间的目标值(例如,`99.9%`)。对于延迟 SLI,每个目标还设置延迟界限。 + - **高级**:燃尽率告警层级、预算警告和补充告警。 + - **排除窗口**:SLO 忽略测量的时间段(例如,维护窗口或部署冻结)。 + - **标签和注释**:传播到生成的规则的可选元数据。 + - **规则预览**:将部署到规则器的记录和告警规则的只读预览。 +4. 选择 **Create SLO**。规则被验证并部署到规则器。如果规则器拒绝规则,则显示错误,并且不保存 SLO。 + +## 监控 SLO + +**SLOs** 列表显示每个 SLO 的当前状态、达成百分比、剩余错误预算和迷你图。 + +下表描述了 SLO 状态。 + +| 状态 | 描述 | +| :--- | :--- | +| `ok` | 所有目标都高于目标值。 | +| `warning` | 至少有一个目标的预算消耗速度快于预期。 | +| `breached` | 至少有一个目标已耗尽其错误预算。 | +| `no_data` | SLI 查询在评估窗口中未返回数据。 | +| `stale` | 最新的数据样本比预期的要旧,这可能表明数据源连接存在问题。 | +| `disabled` | SLO 已被禁用。 | +| `rules_missing` | 规则器上不存在预期的记录规则。 | + +要查看特定 SLO 的详细信息,请在列表中选择它。详细信息页面显示每个目标的达成情况、剩余错误预算、预算消耗率以及已部署的记录和告警规则。 + +## 编辑 SLO + +要更新 SLO,请在列表中选择 SLO 并选择 **Edit**。仅更新您更改的字段。成功更新后,规则组将重新生成并重新部署到规则器。 + +您还可以在不编辑完整配置的情况下更改 SLO 模式: + +- **禁用**:从规则器中删除规则组并停止告警。 +- **启用**:重新部署规则组并恢复状态计算。 +- **影子模式**:保留记录规则但停止告警。在启用告警之前,使用此模式验证新的 SLO。 + +## 删除 SLO + +要删除 SLO,请从列表中选择它,然后从详细信息页面或行操作菜单中选择 **Delete**。关联的规则组将从规则器中删除,并且 SLO 配置将被删除。 + +如果 SLO 与其他 SLO 共享记录规则(当启用规则去重时),则仅释放引用。共享规则在宽限期(默认为 24 小时)后自动删除。 + +## 配置设置 + +下表列出了 SLO 配置设置。 + +| 设置 | 默认值 | 描述 | +| :--- | :--- | :--- | +| `observability.slo.enabled` | `false` | 启用 SLO。需要重启 OpenSearch Dashboards。 | +| `observability.slo.ruleDedup.enabled` | `true` | 允许使用相同查询的多个 SLO 在规则器上共享一组记录规则,从而减少重复评估。 | +| `observability.slo.reconciler.enabled` | `true` | 启用自动清理不再被任何 SLO 引用的共享记录规则。 | +| `observability.slo.reconciler.intervalMs` | `300000`(5 分钟) | 清理过程运行的频率,以毫秒为单位。 | +| `observability.slo.reconciler.graceMs` | `86400000`(24 小时) | 在从规则器中删除规则之前,从删除对共享规则的所有引用之后等待的时间量,以毫秒为单位。 | + +## 故障排除 + +下表描述了常见问题及其解决方案。 + +| 问题 | 解决方案 | +| :--- | :--- | +| 创建或更新 SLO 时,规则器返回错误。 | 错误详细信息显示在向导中。纠正根本问题(例如,身份验证失败或格式错误的 PromQL)并重新提交。 | +| SLO 显示 `rules_missing` 或 `no_data`。 | 使用详细信息页面上的 **Rule health** 操作检查规则器和 SLI 查询。使用 **Repair** 重新部署缺失的规则组。 | + +## 限制 + +SLO 具有以下限制: + +- 仅支持 Prometheus 数据源进行 SLI 评估。 +- 仅支持单个 SLI。尚不支持组合多个 SLO 的复合 SLO。 +- 仅支持滚动时间窗口。尚不支持日历窗口(`week`、`month`、`quarter`)。 +- 仅支持多窗口多燃尽率(MWMBR)告警策略。 +- 可以配置排除窗口,但尚未评估。 + +## 相关文档 + +- [应用程序性能监控](/observing-your-data/apm/) +- [告警](/observing-your-data/alerting/) diff --git a/i18n/zh/query-dsl/ai-vector-search/index.md b/i18n/zh/query-dsl/ai-vector-search/index.md new file mode 100644 index 00000000..2d2a7c3e --- /dev/null +++ b/i18n/zh/query-dsl/ai-vector-search/index.md @@ -0,0 +1,15 @@ +--- +title: AI 和向量搜索查询 +--- + +# AI 和向量搜索查询 + +AI 和向量搜索查询使用机器学习模型来转换或增强搜索操作。这些查询将文本或其他输入转换为向量表示以进行相似性搜索,或使用 AI 服务在运行时生成查询参数。 + +| 查询类型 | 描述 | +| :--- | :--- | +| [Agentic](/query-dsl/specialized/agentic) | 使用 AI 代理动态规划和执行搜索策略。 | +| [k-NN](/query-dsl/specialized/k-nn/) | 使用向量嵌入执行近似或精确的最近邻搜索。 | +| [Neural](/query-dsl/specialized/neural) | 在查询时将文本转换为密集向量嵌入以进行语义搜索。 | +| [Neural sparse](/query-dsl/specialized/neural-sparse) | 在查询时将文本转换为稀疏向量嵌入以进行语义搜索。 | +| [Template](/query-dsl/specialized/template) | 包含在查询时由 ML 推理处理器解析的占位符变量。 | diff --git a/i18n/zh/query-dsl/full-text/combined-fields.md b/i18n/zh/query-dsl/full-text/combined-fields.md new file mode 100644 index 00000000..b48b81ad --- /dev/null +++ b/i18n/zh/query-dsl/full-text/combined-fields.md @@ -0,0 +1,324 @@ +--- +title: Combined fields +--- + +# Combined fields 查询 +<Badge type="tip" text="3.2 版本引入" /> + +`combined_fields` 查询使用 BM25F 算法将多个文本字段视为统一字段,以实现一致的相关性评分。与 `multi_match` 的 [`cross_fields`](/query-dsl/full-text/multi-match#cross-fields) 类型不同,后者为每个字段执行单独的查询,而 `combined_fields` 将所有字段一起处理,从而实现更好的性能和更准确的评分。您可以应用不同的字段权重,同时在所有字段中保持统一的评分。 + +::: info NOTE +`combined_fields` 查询中的所有字段必须是 `text` 字段,并且必须使用相同的文本分析器。 +::: + +## 设置 + +为了跟随示例,请索引一些示例文档: + +```json +POST /books/_bulk +{"index":{"_id":"1"}} +{"title":"Database Systems","description":"A comprehensive guide to database design and implementation"} +{"index":{"_id":"2"}} +{"title":"Introduction to Systems","description":"This book covers database architectures and distributed systems"} +``` + +## 示例 + +以下示例演示了 `combined_fields` 查询中的字段权重。该查询在 `title` 和 `description` 字段中搜索"database systems",`title` 字段的权重是 `description` 字段的四倍: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "database systems", + "fields": ["title^4", "description"] + } + } +} +``` + +响应显示"Database Systems"的分数明显高于"Introduction to Systems",因为两个查询词项都出现在权重较高的 `title` 字段中: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.2924412, + "hits": [ + { + "_index": "books", + "_id": "1", + "_score": 0.2924412, + "_source": { + "title": "Database Systems", + "description": "A comprehensive guide to database design and implementation" + } + }, + { + "_index": "books", + "_id": "2", + "_score": 0.2239699, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `combined_fields` 查询的参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `query` | String | 要搜索的查询字符串。必需。 | +| `fields` | Array of strings | 要搜索的字段。支持字段名称模式和使用 `^` 语法的字段权重(例如,`title^2`)。必需。 | +| `operator` | String | 用于解释查询字符串的布尔逻辑。有效值为 `OR`(默认)和 `AND`。可选。 | +| `minimum_should_match` | String | 文档返回所需匹配的最小词项数。可以是绝对数字、百分比或组合。有关更多信息,请参阅 [Minimum should match](/query-dsl/minimum-should-match)。可选。 | +| `boost` | Floating-point | 指定此字段对相关性分数权重的浮点值。大于 1.0 的值会增加字段的相关性。介于 0.0 和 1.0 之间的值会降低字段的相关性。默认值为 1.0。可选。 | +| `_name` | String | 可用于在响应中标识查询的名称。可选。 | + +## 使用 AND 运算符 + +默认情况下,查询使用 `OR` 运算符,这意味着将返回匹配查询中任何词项的文档。您可以将其更改为 `AND` 以要求所有词项都匹配: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "introduction systems", + "fields": ["title", "description"], + "operator": "AND" + } + } +} +``` + +响应包含唯一一个在组合字段中同时出现两个词项("introduction"和"systems")的文档: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.4214915, + "hits": [ + { + "_index": "books", + "_id": "2", + "_score": 0.4214915, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +## 使用 minimum_should_match + +`minimum_should_match` 参数允许您指定文档返回所需匹配的最小词项数。例如,以下查询要求至少 75% 的词项匹配: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "comprehensive database architectures book", + "fields": ["title", "description"], + "minimum_should_match": "75%" + } + } +} +``` + +响应包含唯一一个匹配 4 个查询词项中至少 3 个(75%)的文档: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.6993829, + "hits": [ + { + "_index": "books", + "_id": "2", + "_score": 0.6993829, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +## 与 multi_match cross_fields 的比较 + +`combined_fields` 查询与 `multi_match` 的 `type: cross_fields` 在计算相关性分数的方式上有所不同。虽然两种查询类型都跨多个字段搜索,但 `combined_fields` 使用 BM25F 算法将所有字段视为单个统一字段进行评分。这意味着逆文档频率 (IDF) 是在所有字段中全局计算的,而不是按字段计算,并且词项频率归一化考虑了所有字段的组合长度。当您具有长度差异很大的字段(例如短标题字段和长正文字段)时,这种方法特别有用,因为它可以防止较短的字段在相关性计算中被过度加权。此外,`combined_fields` 使用以词项为中心的匹配,其中查询词项可以在字段的任何组合中满足,而不需要所有词项在各个字段中匹配。 + +以下示例使用相同的查询比较两种方法。 + +**Combined fields 查询**: + +```json +GET /books/_search +{ + "query": { + "combined_fields": { + "query": "database systems", + "fields": ["title", "description"] + } + } +} +``` + +`combined_fields` 查询将词项频率一起计算在所有字段中,提供更准确的 BM25F 评分: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.20001775, + "hits": [ + { + "_index": "books", + "_id": "1", + "_score": 0.20001775, + "_source": { + "title": "Database Systems", + "description": "A comprehensive guide to database design and implementation" + } + }, + { + "_index": "books", + "_id": "2", + "_score": 0.19373488, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +**Multi_match cross_fields 查询**: + +```json +GET /books/_search +{ + "query": { + "multi_match": { + "query": "database systems", + "fields": ["title", "description"], + "type": "cross_fields" + } + } +} +``` + +`cross_fields` 方法为每个字段执行单独的查询,然后合并结果,这可能导致评分不够精确: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.18051638, + "hits": [ + { + "_index": "books", + "_id": "1", + "_score": 0.18051638, + "_source": { + "title": "Database Systems", + "description": "A comprehensive guide to database design and implementation" + } + }, + { + "_index": "books", + "_id": "2", + "_score": 0.16574687, + "_source": { + "title": "Introduction to Systems", + "description": "This book covers database architectures and distributed systems" + } + } + ] + } +} +``` + +请注意,`combined_fields` 查询产生更高的相关性分数(顶部结果的 0.20001775 相比 0.18051638)。 + +## 限制 + +请注意 `combined_fields` 查询的以下限制: + +- 所有字段必须具有相同的文本分析器。 +- 该查询仅适用于 `text` 字段。 +- 该查询不支持与 `multi_match` 相同方式的按字段提升;而是使用字段权重。 diff --git a/i18n/zh/query-dsl/fuzziness.md b/i18n/zh/query-dsl/fuzziness.md new file mode 100644 index 00000000..f1c3e007 --- /dev/null +++ b/i18n/zh/query-dsl/fuzziness.md @@ -0,0 +1,210 @@ +--- +title: 模糊性 +--- + +# 模糊性 + +`fuzziness` 参数允许查询匹配与搜索词项略有不同的词项,因此即使用户输入错误,搜索仍然会返回结果。例如,启用模糊性后,搜索 `lantren` 将匹配包含 `lantern` 的文档。 + +模糊性以编辑次数来衡量。编辑是以下单字符更改之一: + +- 插入一个字符,例如,`tnt` 变为 `tent` +- 删除一个字符,例如,`tennt` 变为 `tent` +- 用一个字符替换另一个字符,例如,`tant` 变为 `tent` +- 交换两个相邻字符(_转置_),例如,`tnet` 变为 `tent` + +将一个词项更改为另一个词项所需的编辑次数称为 [Damerau-Levenshtein 距离](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)。如果词项与搜索词项的距离不大于允许的编辑次数,则该词项匹配。 + +以下查询和功能支持 `fuzziness`: + +- [`fuzzy`](/query-dsl/term/fuzzy) 查询,默认启用模糊性 (`AUTO`) +- [`match`](/query-dsl/full-text/match)、[`multi_match`](/query-dsl/full-text/multi-match) 和 [`match_bool_prefix`](/query-dsl/full-text/match-bool-prefix) 查询,除非您指定,否则模糊性被禁用 +- [`intervals`](/query-dsl/full-text/intervals) 查询的 `fuzzy` 规则 +- [`query_string`](/query-dsl/full-text/query-string) 和 [`simple_query_string`](/query-dsl/full-text/simple-query-string) 查询,它们使用 `~` 运算符,例如 `tnt~` 或 `tnt~1` +- [completion](/mappings/supported-field-types/completion/) 建议器 + +## 模糊性值 + +下表列出了您可以为 `fuzziness` 指定的值。 + +值 | 描述 +:--- | :--- +`0`、`1` 或 `2` | 允许的最大编辑次数。`0` 需要精确匹配。OpenSearch 最多支持 2 次编辑:更大的整数将被视为 `2`。 +`AUTO` | 根据搜索词项的长度设置允许的编辑次数。0-2 个字符的词项必须精确匹配,3-5 个字符的词项允许 1 次编辑,6 个或更多字符的词项允许 2 次编辑。推荐用于大多数搜索。 +`AUTO:<low>,<high>` | 类似于 `AUTO`,但使用自定义长度阈值。短于 `<low>` 字符的词项必须精确匹配,短于 `<high>` 字符的词项允许 1 次编辑,更长的词项允许 2 次编辑。例如,`AUTO:4,7` 对于 0-3 个字符的词项需要精确匹配,对于 4-6 个字符的词项允许 1 次编辑,对于 7 个或更多字符的词项允许 2 次编辑。`AUTO` 等同于 `AUTO:3,6`。 + +`AUTO` 取决于搜索词项的长度,而不是索引词项的长度。例如,5 个字符的搜索词项 `lntrn` 仅允许 1 次编辑,因此它不匹配需要 2 次编辑的 `lantern`。要为 5 个字符的词项允许 2 次编辑,请降低高阈值,例如降至 `AUTO:3,5`。 + +## 相关参数 + +以下参数控制如何应用模糊匹配。某些查询对同一参数使用不同的名称。下表列出了每个参数的所有名称。 + +参数 | 描述 +:--- | :--- +`fuzzy_transpositions`、`transpositions` | 两个相邻字符的交换是否算作一次编辑。如果为 `false`,转置算作两次编辑,距离为 [Levenshtein 距离](https://en.wikipedia.org/wiki/Levenshtein_distance),不包括转置。默认值为 `true`。 +`fuzzy_prefix_length`、`prefix_length` | 必须精确匹配的前导字符数。仅在此前缀之后允许编辑。例如,将 `prefix_length` 设置为 `1` 时,`xent` 不匹配 `tent`。增加 `prefix_length` 会减少候选词项的数量并加快查询速度。默认值为 `0`。 +`fuzzy_max_expansions`、`max_expansions` | 查询扩展到的最大候选词项数。默认值为 `50`。较低的值使查询更快,但可能会跳过匹配的词项。 +`fuzzy_rewrite`、`rewrite` | 确定 OpenSearch 如何将候选词项转换为查询,这会影响匹配文档的评分方式。接受与其他多词项查询的 `rewrite` 参数相同的值,例如 `constant_score` 或 `top_terms_N`。有关每个值的描述,请参阅 [Rewrite](/query-dsl/rewrite-parameter)。默认情况下,模糊匹配基于匹配词项的频率进行评分(`top_terms_blended_freqs_N`,其中 `N` 是 `max_expansions` 值)。将 `fuzzy_rewrite` 设置为 `constant_score` 会为所有匹配的文档赋予 `1.0` 的分数。 + +## 示例:匹配拼写错误的词项 + +将文档索引到 `fuzzy-test` 索引中: + +```json +PUT /fuzzy-test/_doc/1?refresh=true +{ + "product": "lantern" +} +``` + +使用 `AUTO` 模糊性搜索拼写错误的词项 `lamtrn`。该词项距离 `lantern` 有 2 次编辑:`m` 替换 `n`,并且缺少 `e`。因为该词项包含 6 个字符,`AUTO` 允许 2 次编辑: + +```json +GET /fuzzy-test/_search +{ + "query": { + "match": { + "product": { + "query": "lamtrn", + "fuzziness": "AUTO" + } + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.08717638, + "hits": [ + { + "_index": "fuzzy-test", + "_id": "1", + "_score": 0.08717638, + "_source": { + "product": "lantern" + } + } + ] + } +} +``` + +将 `fuzziness` 设置为 `1` 时,相同的查询不返回任何结果。 + +## 示例:匹配交换的字符 + +默认情况下,交换两个相邻字符算作一次编辑。以下请求搜索 `lantren`,其中 `e` 和 `r` 被交换,并且仅允许 1 次编辑: + +```json +GET /fuzzy-test/_search +{ + "query": { + "match": { + "product": { + "query": "lantren", + "fuzziness": 1 + } + } + } +} +``` + +响应包含匹配的文档,因为转置算作 1 次编辑: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.11208393, + "hits": [ + { + "_index": "fuzzy-test", + "_id": "1", + "_score": 0.11208393, + "_source": { + "product": "lantern" + } + } + ] + } +} +``` + +如果在相同的请求中将 `fuzzy_transpositions` 设置为 `false`,转置算作 2 次编辑,查询不返回任何结果。 + +## 示例:为短词项允许更多编辑 + +使用 `AUTO` 时,5 个字符的搜索词项 `lntrn` 仅允许 1 次编辑,并且不匹配需要 2 次编辑的 `lantern`。以下请求将高阈值降低到 5,以便 5 个字符的词项允许 2 次编辑: + +```json +GET /fuzzy-test/_search +{ + "query": { + "match": { + "product": { + "query": "lntrn", + "fuzziness": "AUTO:3,5" + } + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.07845875, + "hits": [ + { + "_index": "fuzzy-test", + "_id": "1", + "_score": 0.07845875, + "_source": { + "product": "lantern" + } + } + ] + } +} +``` diff --git a/i18n/zh/query-dsl/geo-and-xy/geodistance.md b/i18n/zh/query-dsl/geo-and-xy/geodistance.md new file mode 100644 index 00000000..d9fe9bc0 --- /dev/null +++ b/i18n/zh/query-dsl/geo-and-xy/geodistance.md @@ -0,0 +1,115 @@ +--- +title: Geodistance +--- + +# Geodistance 查询 + +geodistance 查询返回包含地理点的文档,这些地理点位于与提供的地理点指定距离内。如果文档包含多个地理点,只要至少有一个地理点匹配查询,该文档就会匹配查询。 + +::: info NOTE +搜索的文档字段必须映射为 `geo_point`。 +::: + +## 示例 + +创建一个映射,将 `point` 字段映射为 `geo_point`: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` + +索引一个地理点,指定其纬度和经度: + +```json +PUT testindex1/_doc/1 +{ + "point": { + "lat": 74.00, + "lon": 40.71 + } +} +``` + +搜索 `point` 对象距离指定 `point` 在指定 `distance` 内的文档: + +```json +GET /testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_distance": { + "distance": "50mi", + "point": { + "lat": 73.5, + "lon": 40.5 + } + } + } + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "point": { + "lat": 74, + "lon": 40.71 + } + } + } + ] + } +} +``` + +## 参数 + +Geodistance 查询接受以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`_name` | String | 过滤器的名称。可选。 +`distance` | String | 匹配点的距离范围。此距离是以指定点为中心的圆的半径。有关支持的距离单位,请参阅 [Distance units](/api-reference/units#distance-units)。必需。 +`distance_type` | String | 指定如何计算距离。有效值为 `arc` 或 `plane`(更快但对于长距离或靠近极点的点不准确)。可选。默认值为 `arc`。 +`validation_method` | String | 验证方法。有效值为 `IGNORE_MALFORMED`(接受具有无效坐标的地理点)、`COERCE`(尝试将坐标强制转换为有效值)和 `STRICT`(当坐标无效时返回错误)。可选。默认值为 `STRICT`。 +`ignore_unmapped` | Boolean | 指定是否忽略未映射的字段。如果设置为 `true`,则查询不会返回包含未映射字段的任何文档。如果设置为 `false`,则在字段未映射时会抛出异常。可选。默认值为 `false`。 + +## 接受的格式 + +您可以在索引文档和搜索文档时以地理点字段类型接受的任何[格式](/field-types/supported-field-types/geo-point#formats)指定地理点坐标。 diff --git a/i18n/zh/query-dsl/geo-and-xy/geopolygon.md b/i18n/zh/query-dsl/geo-and-xy/geopolygon.md new file mode 100644 index 00000000..8032d024 --- /dev/null +++ b/i18n/zh/query-dsl/geo-and-xy/geopolygon.md @@ -0,0 +1,171 @@ +--- +title: Geopolygon +--- + +# Geopolygon 查询 + +geopolygon 查询返回包含位于指定多边形内的地理点的文档。如果文档包含多个地理点,只要至少有一个地理点匹配查询,该文档就会匹配查询。 + +多边形由坐标形式的顶点列表指定。与为地理形状字段指定多边形不同,多边形不必闭合(不需要将第一个和最后一个点指定为相同)。尽管点不必按顺时针或逆时针顺序排列,但建议您按这两种顺序之一列出它们。这将确保捕获正确的多边形。 + +::: info NOTE +搜索的文档字段必须映射为 `geo_point`。 +::: + +## 示例 + +创建一个映射,将 `point` 字段映射为 `geo_point`: + +```json +PUT /testindex1 +{ + "mappings": { + "properties": { + "point": { + "type": "geo_point" + } + } + } +} +``` + +索引一个地理点,指定其纬度和经度: + +```json +PUT testindex1/_doc/1 +{ + "point": { + "lat": 73.71, + "lon": 41.32 + } +} +``` + +搜索 `point` 对象位于指定 `geo_polygon` 内的文档: + +```json +GET /testindex1/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 73.7562, "lon": 42.6526 }, + { "lat": 73.3245, "lon": 41.6189 }, + { "lat": 74.0060, "lon": 40.7128 } + ] + } + } + } + } + } +} +``` + +前面请求中指定的多边形是下图中描绘的四边形。匹配的文档位于此四边形内。四边形顶点的坐标以 `(纬度, 经度)` 格式指定。 + +*在指定的四边形内搜索点* + +响应包含匹配的文档: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "point": { + "lat": 73.71, + "lon": 41.32 + } + } + } + ] + } +} +``` + +在前面的搜索请求中,您以顺时针顺序指定了多边形顶点: + +```json +"geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 73.7562, "lon": 42.6526 }, + { "lat": 73.3245, "lon": 41.6189 }, + { "lat": 74.0060, "lon": 40.7128 } + ] + } +} +``` + +或者,您可以以逆时针顺序指定顶点: + +```json +"geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 74.0060, "lon": 40.7128 }, + { "lat": 73.3245, "lon": 41.6189 }, + { "lat": 73.7562, "lon": 42.6526 } + ] + } +} +``` + +结果查询响应包含相同的匹配文档。 + +但是,如果您以以下顺序指定顶点: + +```json +"geo_polygon": { + "point": { + "points": [ + { "lat": 74.5627, "lon": 41.8645 }, + { "lat": 74.0060, "lon": 40.7128 }, + { "lat": 73.7562, "lon": 42.6526 }, + { "lat": 73.3245, "lon": 41.6189 } + ] + } +} +``` + +响应不返回任何结果。 + +## 参数 + +Geopolygon 查询接受以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`_name` | String | 过滤器的名称。可选。 +`validation_method` | String | 验证方法。有效值为 `IGNORE_MALFORMED`(接受具有无效坐标的地理点)、`COERCE`(尝试将坐标强制转换为有效值)和 `STRICT`(当坐标无效时返回错误)。可选。默认值为 `STRICT`。 +`ignore_unmapped` | Boolean | 指定是否忽略未映射的字段。如果设置为 `true`,则查询不会返回包含未映射字段的任何文档。如果设置为 `false`,则在字段未映射时会抛出异常。可选。默认值为 `false`。 + +## 接受的格式 + +您可以在索引文档和搜索文档时以地理点字段类型接受的任何[格式](/field-types/supported-field-types/geo-point#formats)指定地理点坐标。 diff --git a/i18n/zh/query-dsl/geo-and-xy/geoshape.md b/i18n/zh/query-dsl/geo-and-xy/geoshape.md new file mode 100644 index 00000000..d02442ce --- /dev/null +++ b/i18n/zh/query-dsl/geo-and-xy/geoshape.md @@ -0,0 +1,719 @@ +--- +title: Geoshape +--- + +# Geoshape 查询 + +使用 geoshape 查询来搜索包含 [geopoint](/field-types/supported-field-types/geo-point) 或 [geoshape](/field-types/supported-field-types/geo-shape) 字段的文档。您可以使用[在查询中定义的地理形状](#使用新的形状定义)过滤文档,或使用[预索引的地理形状](#使用预索引的形状定义)。 + +::: info NOTE +搜索的文档字段必须映射为 `geo_point` 或 `geo_shape`。 +::: + +## 空间关系 + +当您向 geoshape 查询提供地理形状时,文档中的 geopoint 和 geoshape 字段将使用以下空间关系与提供的形状进行匹配。 + +关系 | 描述 | 支持的地理字段类型 +:--- | :--- | :--- +`INTERSECTS` | (默认)匹配地理点或地理形状与查询中提供的形状相交的文档。 | `geo_point`、`geo_shape` +`DISJOINT` | 匹配地理形状与查询中提供的形状不相交的文档。 | `geo_shape` +`WITHIN` | 匹配地理形状完全在查询中提供的形状内的文档。 | `geo_shape` +`CONTAINS` | 匹配地理形状完全包含查询中提供的形状的文档。 | `geo_shape` + +## 在 geoshape 查询中定义形状 + +您可以通过[在查询时提供新的形状定义](#使用新的形状定义)或[引用预索引在另一个索引中的形状名称](#使用预索引的形状定义)来定义用于过滤文档的形状。 + +## 使用新的形状定义 + +要向 geoshape 查询提供新形状,请在 `geo_shape` 字段中定义它。您可以使用 [GeoJSON 格式](https://geojson.org/)或 [Well-Known Text (WKT) 格式](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html)定义地理形状。 + +以下示例说明了如何搜索包含与查询时定义的地理形状匹配的地理形状的文档。 + +### 步骤 1:创建索引 + +首先,创建一个索引并将 `location` 字段映射为 `geo_shape`: + +```json +PUT /testindex +{ + "mappings": { + "properties": { + "location": { + "type": "geo_shape" + } + } + } +} +``` + +### 步骤 2:索引文档 + +索引一个包含点的文档和另一个包含多边形的文档: + +```json +PUT testindex/_doc/1 +{ + "location": { + "type": "point", + "coordinates": [ 73.0515, 41.5582 ] + } +} +``` + +```json +PUT testindex/_doc/2 +{ + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } +} +``` + +### 步骤 3:运行 geoshape 查询 + +最后,定义一个地理形状来过滤文档。以下部分说明了如何在查询中提供各种地理形状。有关各种地理形状格式的更多信息,请参阅 [Geoshape 字段类型](/mappings/supported-field-types/geo-shape/)。 + +#### Envelope + +[`envelope`](/mappings/supported-field-types/geo-shape#envelope) 是 `[[minLon, maxLat], [maxLon, minLat]]` 格式的边界矩形。搜索包含与提供的 envelope 相交的地理形状字段的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "envelope", + "coordinates": [ + [ + 71.0589, + 42.3601 + ], + [ + 74.006, + 40.7128 + ] + ] + }, + "relation": "WITHIN" + } + } + } +} +``` + +响应包含两个文档: + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0, + "_source": { + "location": { + "type": "point", + "coordinates": [ + 73.0515, + 41.5582 + ] + } + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 0, + "_source": { + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } + } + } + ] + } +} +``` + +#### Point + +搜索地理形状字段包含提供的点的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "point", + "coordinates": [ + 72.8000, + 41.6300 + ] + }, + "relation": "CONTAINS" + } + } + } +} +``` + +#### Linestring + +搜索地理形状字段与提供的 linestring 不相交的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "linestring", + "coordinates": [[74.0060, 40.7128], [71.0589, 42.3601]] + }, + "relation": "DISJOINT" + } + } + } +} +``` + +::: info NOTE +Linestring geoshape 查询不支持 `WITHIN` 关系。 +::: + +#### Polygon + +在 GeoJSON 格式中,您必须以逆时针顺序列出多边形的顶点,并关闭多边形使第一个顶点和最后一个顶点相同。 + +搜索地理形状字段在提供的多边形内的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "polygon", + "coordinates": [ + [ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ] + ] + }, + "relation": "WITHIN" + } + } + } +} +``` + +#### Multipoint + +搜索地理形状字段与提供的点不相交的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "multipoint", + "coordinates" : [ + [74.0060, 40.7128], + [71.0589, 42.3601] + ] + }, + "relation": "DISJOINT" + } + } + } +} +``` + +#### Multilinestring + +搜索地理形状字段与提供的线不相交的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "multilinestring", + "coordinates" : [ + [[74.0060, 40.7128], [71.0589, 42.3601]], + [[73.7562, 42.6526], [72.6734, 41.7658]] + ] + }, + "relation": "disjoint" + } + } + } +} +``` + +::: info NOTE +Multilinestring geoshape 查询不支持 `WITHIN` 关系。 +::: + +#### Multipolygon + +搜索地理形状字段在提供的 multipolygon 内的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type" : "multipolygon", + "coordinates" : [ + [ + [ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ], + [ + [73.0515, 41.5582], + [72.6506, 41.5623], + [72.6734, 41.7658], + [73.0515, 41.5582] + ] + ], + [ + [ + [73.9146, 40.8252], + [73.8871, 41.0389], + [73.6853, 40.9747], + [73.9146, 40.8252] + ] + ] + ] + }, + "relation": "WITHIN" + } + } + } +} +``` + +#### Geometry collection + +搜索地理形状字段在提供的多边形内的文档: + +```json +GET /testindex/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "geometrycollection", + "geometries": [ + { + "type": "polygon", + "coordinates": [[ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ]] + }, + { + "type": "polygon", + "coordinates": [[ + [73.0515, 41.5582], + [72.6506, 41.5623], + [72.6734, 41.7658], + [73.0515, 41.5582] + ]] + } + ] + }, + "relation": "WITHIN" + } + } + } +} +``` + +::: info NOTE +包含 linestring 或 multilinestring 的 geometry collection 的 geoshape 查询不支持 `WITHIN` 关系。 +::: + +## 使用预索引的形状定义 + +在构建 geoshape 查询时,您还可以引用预索引在另一个索引中的形状名称。使用此方法,您可以在索引时定义地理形状,并在搜索时通过名称引用它。 + +您可以使用 [GeoJSON](https://geojson.org/) 或 [Well-Known Text (WKT)](https://docs.opengeospatial.org/is/12-063r5/12-063r5.html) 格式定义预索引的地理形状。有关各种地理形状格式的更多信息,请参阅 [Geoshape 字段类型](/mappings/supported-field-types/geo-shape/)。 + +`indexed_shape` 对象支持以下参数。 + +参数 | 必需/可选 | 描述 +:--- | :--- | :--- +`id` | 必需 | 包含预索引形状的文档的文档 ID。 +`index` | 可选 | 包含预索引形状的索引名称。默认值为 `shapes`。 +`path` | 可选 | 包含预索引形状的字段名称(作为路径)。默认值为 `shape`。 +`routing` | 可选 | 包含预索引形状的文档的路由值。如果形状文档使用自定义路由值进行索引,则为必需。 + +以下示例说明了如何引用预索引在另一个索引中的形状名称。在此示例中,索引 `pre-indexed-shapes` 包含定义边界的形状,索引 `testindex` 包含针对这些边界进行检查的形状。 + +首先,创建 `pre-indexed-shapes` 索引并将此索引的 `boundaries` 字段映射为 `geo_shape`: + +```json +PUT /pre-indexed-shapes +{ + "mappings": { + "properties": { + "boundaries": { + "type": "geo_shape", + "orientation" : "left" + } + } + } +} +``` + +有关为多边形指定不同顶点方向的更多信息,请参阅 [Polygon](/mappings/supported-field-types/geo-shape/#polygon)。 + +将指定搜索边界的多边形索引到 `pre-indexed-shapes` 索引中。多边形的 ID 为 `search_triangle`。在此示例中,您将以 WKT 格式索引多边形: + +```json +PUT /pre-indexed-shapes/_doc/search_triangle +{ + "boundaries": + "POLYGON ((74.0060 40.7128, 71.0589 42.3601, 73.7562 42.6526, 74.0060 40.7128))" +} +``` + +如果您尚未这样做,请将一个包含点的文档和另一个包含多边形的文档索引到 `testindex` 索引中: + +```json +PUT /testindex/_doc/1 +{ + "location": { + "type": "point", + "coordinates": [ 73.0515, 41.5582 ] + } +} +``` + +```json +PUT /testindex/_doc/2 +{ + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } +} +``` + +搜索地理形状在 `search_triangle` 内的文档: + +```json +GET /testindex/_search +{ + "query": { + "bool": { + "must": { + "match_all": {} + }, + "filter": { + "geo_shape": { + "location": { + "indexed_shape": { + "index": "pre-indexed-shapes", + "id": "search_triangle", + "path": "boundaries" + }, + "relation": "WITHIN" + } + } + } + } + } +} +``` + +响应包含两个文档: + +```json +{ + "took": 11, + "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": { + "location": { + "type": "point", + "coordinates": [ + 73.0515, + 41.5582 + ] + } + } + }, + { + "_index": "testindex", + "_id": "2", + "_score": 1, + "_source": { + "location": { + "type": "polygon", + "coordinates": [ + [ + [ + 73.0515, + 41.5582 + ], + [ + 72.6506, + 41.5623 + ], + [ + 72.6734, + 41.7658 + ], + [ + 73.0515, + 41.5582 + ] + ] + ] + } + } + } + ] + } +} +``` + +## 查询地理点 + +您还可以使用 geoshape 查询来搜索包含地理点的文档。 + +::: warning IMPORTANT +::: info NOTE +地理点字段上的 geoshape 查询仅支持默认的 `INTERSECTS` 空间关系,因此您不需要提供 `relation` 参数。 +::: +::: + +> 地理点字段上的 geoshape 查询不支持以下地理形状: +> +> - 点 +> - 线串 +> - 多点 +> - 多线串 +> - 包含上述地理形状类型之一的几何集合 + +创建一个映射,其中 `location` 是 `geo_point`: + +```json +PUT /testindex1 +{ + "mappings": { + "properties": { + "location": { + "type": "geo_point" + } + } + } +} +``` + +将两个点索引到索引中。在此示例中,您将以字符串形式提供地理点坐标: + +```json +PUT /testindex1/_doc/1 +{ + "location": "41.5623, 72.6506" +} +``` + +```json +PUT /testindex1/_doc/2 +{ + "location": "76.0254, 39.2467" +} +``` + +有关以各种格式提供地理点坐标的信息,请参阅 [格式](/mappings/supported-field-types/geo-point/#formats)。 + +搜索与提供的多边形相交的地理点: + +```json +GET /testindex1/_search +{ + "query": { + "geo_shape": { + "location": { + "shape": { + "type": "polygon", + "coordinates": [ + [ + [74.0060, 40.7128], + [73.7562, 42.6526], + [71.0589, 42.3601], + [74.0060, 40.7128] + ] + ] + } + } + } + } +} + +``` + +响应返回文档 1: + +```json +{ + "took": 21, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 0, + "_source": { + "location": "41.5623, 72.6506" + } + } + ] + } +} +``` + +请注意,当您索引地理点时,您以 `"纬度, 经度"` 格式指定了它们的坐标。当您搜索匹配的文档时,坐标数组为 `[经度, 纬度]` 格式。因此,文档 1 在结果中返回,但文档 2 没有。 + +## 参数 + +Geoshape 查询接受以下参数。 + +参数 | 数据类型 | 描述 +:--- | :--- | :--- +`ignore_unmapped` | Boolean | 指定是否忽略未映射的字段。如果设置为 `true`,则查询不会返回包含未映射字段的任何文档。如果设置为 `false`,则在字段未映射时会抛出异常。可选。默认值为 `false`。 + +## 昂贵的查询 + +Geoshape 字段默认在 BKD 树中存储形状,对这些字段的查询无论 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置如何都会运行。 + +使用 `tree` 或 `strategy` 参数映射的 geoshape 字段将形状存储在前缀树中。对前缀树字段的查询仅在 `search.allow_expensive_queries` 为 `true` 时运行。 diff --git a/i18n/zh/query-dsl/joining/has-child.md b/i18n/zh/query-dsl/joining/has-child.md new file mode 100644 index 00000000..94af54a7 --- /dev/null +++ b/i18n/zh/query-dsl/joining/has-child.md @@ -0,0 +1,385 @@ +--- +title: Has child +--- + +# Has child 查询 + +`has_child` 查询返回其子文档匹配特定查询的父文档。您可以使用 [join](/mappings/supported-field-types/join/) 字段类型在同一索引中的文档之间建立父/子关系。 + +::: danger WARNING +`has_child` 查询由于执行连接操作而比其他查询慢。随着指向不同父文档的匹配子文档数量增加,性能会下降。搜索中的每个 `has_child` 查询都可能显著影响查询性能。如果您优先考虑速度,请避免使用此查询或尽可能限制其使用。 +::: + +## 示例 + +在运行 `has_child` 查询之前,您的索引必须包含 [join](/mappings/supported-field-types/join/) 字段以建立父/子关系。索引映射请求使用以下格式: + +```json +PUT /example_index +{ + "mappings": { + "properties": { + "relationship_field": { + "type": "join", + "relations": { + "parent_doc": "child_doc" + } + } + } + } +} +``` + +在此示例中,您将配置一个包含代表产品及其品牌的文档的索引。 + +首先,创建索引并在 `brand` 和 `product` 之间建立父/子关系: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "product_to_brand": { + "type": "join", + "relations": { + "brand": "product" + } + } + } + } +} +``` + +索引两个父(品牌)文档: + +```json +PUT testindex1/_doc/1 +{ + "name": "Luxury brand", + "product_to_brand" : "brand" +} +``` + +```json +PUT testindex1/_doc/2 +{ + "name": "Economy brand", + "product_to_brand" : "brand" +} +``` + +索引三个子(产品)文档: + +```json +PUT testindex1/_doc/3?routing=1 +{ + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } +} +``` + +```json +PUT testindex1/_doc/4?routing=2 +{ + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } +} +``` + +```json +PUT testindex1/_doc/5?routing=2 +{ + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } +} +``` + +要搜索子文档的父文档,请使用 `has_child` 查询。以下查询返回生产手表的父文档(品牌): + +```json +GET testindex1/_search +{ + "query" : { + "has_child": { + "type":"product", + "query": { + "match" : { + "name": "watch" + } + } + } + } +} +``` + +响应返回两个品牌: + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "name": "Luxury brand", + "product_to_brand": "brand" + } + }, + { + "_index": "testindex1", + "_id": "2", + "_score": 1, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + } + ] + } +} +``` + +## 检索内部命中 + +要返回匹配查询的子文档,请提供 `inner_hits` 参数: + +```json +GET testindex1/_search +{ + "query" : { + "has_child": { + "type":"product", + "query": { + "match" : { + "name": "watch" + } + }, + "inner_hits": {} + } + } +} +``` + +响应在 `inner_hits` 字段中包含子文档: + +```json +{ + "took": 52, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "1", + "_score": 1, + "_source": { + "name": "Luxury brand", + "product_to_brand": "brand" + }, + "inner_hits": { + "product": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.53899646, + "hits": [ + { + "_index": "testindex1", + "_id": "3", + "_score": 0.53899646, + "_routing": "1", + "_source": { + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } + } + } + ] + } + } + } + }, + { + "_index": "testindex1", + "_id": "2", + "_score": 1, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + }, + "inner_hits": { + "product": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.53899646, + "hits": [ + { + "_index": "testindex1", + "_id": "4", + "_score": 0.53899646, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 0.53899646, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + } + ] + } + } + } + } + ] + } +} +``` + +有关检索内部命中的更多信息,请参阅 [Inner hits](/search-plugins/searching-data/inner-hits)。 + +## 参数 + +下表列出了 `has_child` 查询支持的所有顶级参数。 + +| 参数 | 必需/可选 | 描述 | +|:---|:---|:---| +| `type` | 必需 | 指定 `join` 字段映射中定义的子关系名称。 | +| `query` | 必需 | 要在子文档上运行的查询。如果子文档匹配查询,则返回父文档。 | +| `ignore_unmapped` | 可选 | 指示是否忽略未映射的 `type` 字段并不返回文档而不是抛出错误。当查询多个索引时可以提供此参数,其中一些可能不包含 `type` 字段。默认值为 `false`。 | +| `max_children` | 可选 | 父文档的最大匹配子文档数。如果超过,父文档将从搜索结果中排除。 | +| `min_children` | 可选 | 父文档包含在结果中所需的最小匹配子文档数。如果不满足,父文档将被排除。默认值为 `1`。| +| `score_mode` | 可选 | 定义匹配子文档的分数如何影响父文档的分数。有效值为:<br> - `none`:忽略子文档的相关性分数,并为父文档分配 `0` 分。<br> - `avg`:使用所有匹配子文档的平均相关性分数。<br> - `max`:将匹配子文档的最高相关性分数分配给父文档。<br> - `min`:将匹配子文档的最低相关性分数分配给父文档。<br> - `sum`:对所有匹配子文档的相关性分数求和。<br> 默认值为 `none`。 | +| `inner_hits` | 可选 | 如果提供,则返回匹配查询的底层命中(子文档)。 | + +## 排序限制 + +`has_child` 查询不支持使用标准排序选项对[结果进行排序](/search-plugins/searching-data/sort)。如果您需要按子文档中的字段对父文档进行排序,可以使用 [`function_score` 查询](/query-dsl/compound/function-score)并按父文档的分数进行排序。 + +在前面的示例中,您可以根据子产品的 `sales_count` 对父文档(品牌)进行排序。此查询将分数乘以子文档的 `sales_count` 字段,并将匹配子文档的最高相关性分数分配给父文档: + +```json +GET testindex1/_search +{ + "query": { + "has_child": { + "type": "product", + "query": { + "function_score": { + "script_score": { + "script": "_score * doc['sales_count'].value" + } + } + }, + "score_mode": "max" + } + } +} +``` + +响应包含按最高子 `sales_count` 排序的品牌: + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 300, + "hits": [ + { + "_index": "testindex1", + "_id": "2", + "_score": 300, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + }, + { + "_index": "testindex1", + "_id": "1", + "_score": 150, + "_source": { + "name": "Luxury brand", + "product_to_brand": "brand" + } + } + ] + } +} +``` + +## 后续步骤 + +- 了解更多关于 [检索内部命中](/search-plugins/searching-data/inner-hits)。 diff --git a/i18n/zh/query-dsl/joining/has-parent.md b/i18n/zh/query-dsl/joining/has-parent.md new file mode 100644 index 00000000..d9dc83ed --- /dev/null +++ b/i18n/zh/query-dsl/joining/has-parent.md @@ -0,0 +1,349 @@ +--- +title: Has parent +--- + +# Has parent 查询 + +`has_parent` 查询返回其父文档匹配特定查询的子文档。您可以使用 [join](/mappings/supported-field-types/join/) 字段类型在同一索引中的文档之间建立父/子关系。 + +::: danger WARNING +`has_parent` 查询由于执行连接操作而比其他查询慢。随着匹配父文档数量的增加,性能会下降。搜索中的每个 `has_parent` 查询都可能显著影响查询性能。如果您优先考虑速度,请避免使用此查询或尽可能限制其使用。 +::: + +## 示例 + +在运行 `has_parent` 查询之前,您的索引必须包含 [join](/mappings/supported-field-types/join/) 字段以建立父/子关系。索引映射请求使用以下格式: + +```json +PUT /example_index +{ + "mappings": { + "properties": { + "relationship_field": { + "type": "join", + "relations": { + "parent_doc": "child_doc" + } + } + } + } +} +``` + +对于此示例,首先按照 [`has_child` 查询示例](/query-dsl/joining/has-child)中所述配置一个包含代表产品及其品牌的文档的索引。 + +要搜索父文档的子文档,请使用 `has_parent` 查询。以下查询返回由匹配查询 `economy` 的品牌制造的子文档(产品): + +```json +GET testindex1/_search +{ + "query" : { + "has_parent": { + "parent_type":"brand", + "query": { + "match" : { + "name": "economy" + } + } + } + } +} +``` + +响应返回该品牌制造的所有产品: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "4", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + } + ] + } +} +``` + +## 检索内部命中 + +要返回匹配查询的父文档,请提供 `inner_hits` 参数: + +```json +GET testindex1/_search +{ + "query" : { + "has_parent": { + "parent_type":"brand", + "query": { + "match" : { + "name": "economy" + } + }, + "inner_hits": {} + } + } +} +``` + +响应在 `inner_hits` 字段中包含父文档: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "testindex1", + "_id": "4", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + }, + "inner_hits": { + "brand": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.3862942, + "hits": [ + { + "_index": "testindex1", + "_id": "2", + "_score": 1.3862942, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + } + ] + } + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 1, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + }, + "inner_hits": { + "brand": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.3862942, + "hits": [ + { + "_index": "testindex1", + "_id": "2", + "_score": 1.3862942, + "_source": { + "name": "Economy brand", + "product_to_brand": "brand" + } + } + ] + } + } + } + } + ] + } +} +``` + +有关检索内部命中的更多信息,请参阅 [Inner hits](/search-plugins/searching-data/inner-hits)。 + +## 参数 + +下表列出了 `has_parent` 查询支持的所有顶级参数。 + +| 参数 | 必需/可选 | 描述 | +|:---|:---|:---| +| `parent_type` | 必需 | 指定 `join` 字段映射中定义的父关系名称。 | +| `query` | 必需 | 要在父文档上运行的查询。如果父文档匹配查询,则返回子文档。 | +| `ignore_unmapped` | 可选 | 指示是否忽略未映射的 `parent_type` 字段并不返回文档而不是抛出错误。当查询多个索引时可以提供此参数,其中一些可能不包含 `parent_type` 字段。默认值为 `false`。 | +| `score` | 可选 | 指示匹配父文档的相关性分数是否聚合到其子文档中。如果为 `false`,则忽略父文档的相关性分数,并为每个子文档分配等于查询的 `boost` 的相关性分数,默认为 `1`。如果为 `true`,则匹配父文档的相关性分数会聚合到其子文档的相关性分数中。默认值为 `false`。 | +| `inner_hits` | 可选 | 如果提供,则返回匹配查询的底层命中(父文档)。 | + +## 排序限制 + +`has_parent` 查询不支持使用标准排序选项对[结果进行排序](/search-plugins/searching-data/sort)。如果您需要按父文档中的字段对子文档进行排序,可以使用 [`function_score` 查询](/query-dsl/compound/function-score)并按子文档的分数进行排序。 + +对于前面的示例,首先添加一个 `customer_satisfaction` 字段,您将按此字段对属于父(品牌)文档的子文档进行排序: + +```json +PUT testindex1/_doc/1 +{ + "name": "Luxury watch brand", + "product_to_brand" : "brand", + "customer_satisfaction": 4.5 +} +``` + +```json +PUT testindex1/_doc/2 +{ + "name": "Economy watch brand", + "product_to_brand" : "brand", + "customer_satisfaction": 3.9 +} +``` + +现在您可以根据父品牌的 `customer_satisfaction` 字段对子文档(产品)进行排序。此查询将分数乘以父文档的 `customer_satisfaction` 字段: + +```json +GET testindex1/_search +{ + "query": { + "has_parent": { + "parent_type": "brand", + "score": true, + "query": { + "function_score": { + "script_score": { + "script": "_score * doc['customer_satisfaction'].value" + } + } + } + } + } +} +``` + +响应包含按最高父 `customer_satisfaction` 排序的产品: + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 4.5, + "hits": [ + { + "_index": "testindex1", + "_id": "3", + "_score": 4.5, + "_routing": "1", + "_source": { + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } + } + }, + { + "_index": "testindex1", + "_id": "4", + "_score": 3.9, + "_routing": "2", + "_source": { + "name": "Electronic watch", + "sales_count": 300, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + }, + { + "_index": "testindex1", + "_id": "5", + "_score": 3.9, + "_routing": "2", + "_source": { + "name": "Digital watch", + "sales_count": 100, + "product_to_brand": { + "name": "product", + "parent": "2" + } + } + } + ] + } +} +``` + +## 后续步骤 + +- 了解更多关于 [检索内部命中](/search-plugins/searching-data/inner-hits)。 diff --git a/i18n/zh/query-dsl/joining/index.md b/i18n/zh/query-dsl/joining/index.md new file mode 100644 index 00000000..877188e6 --- /dev/null +++ b/i18n/zh/query-dsl/joining/index.md @@ -0,0 +1,18 @@ +--- +title: 连接查询 +--- + +# 连接查询 + +OpenSearch 是一个分布式系统,数据分布在多个节点上。因此,在 OpenSearch 中运行类似 SQL 的 JOIN 操作是资源密集型的。作为替代方案,OpenSearch 提供了以下查询,它们执行连接操作并针对跨多个节点的扩展进行了优化: + +| 查询类型 | 描述 | +| :--- | :--- | +| [`nested`](/query-dsl/joining/nested) | 作为其他查询的包装器来搜索 [nested](/mappings/supported-field-types/nested/) 字段。嵌套字段对象被搜索时就像它们是作为单独的文档索引的一样。 | +| [`has_child`](/query-dsl/joining/has-child) | 搜索其子文档匹配查询的父文档。需要 [join](/mappings/supported-field-types/join/) 字段类型。 | +| [`has_parent`](/query-dsl/joining/has-parent) | 搜索其父文档匹配查询的子文档。需要 [join](/mappings/supported-field-types/join/) 字段类型。 | +| [`parent_id`](/query-dsl/joining/parent-id) | 搜索连接到特定父文档的子文档。需要 [join](/mappings/supported-field-types/join/) 字段类型。 | + +::: warning IMPORTANT +如果 [`search.allow_expensive_queries`](/query-dsl/#expensive-queries) 设置为 `false`,则连接查询不会执行。 +::: diff --git a/i18n/zh/query-dsl/joining/nested.md b/i18n/zh/query-dsl/joining/nested.md new file mode 100644 index 00000000..c8aabff6 --- /dev/null +++ b/i18n/zh/query-dsl/joining/nested.md @@ -0,0 +1,361 @@ +--- +title: Nested +--- + +# Nested 查询 + +`nested` 查询作为其他查询的包装器来搜索 [nested](/mappings/supported-field-types/nested/) 字段。嵌套字段对象被搜索时就像它们是作为单独的文档索引的一样。如果对象匹配搜索,`nested` 查询将在根级别返回父文档。 + +## 示例 + +在运行 `nested` 查询之前,您的索引必须包含 [nested](/mappings/supported-field-types/nested/) 字段。 + +要配置包含嵌套字段的示例索引,请发送以下请求: + +```json +PUT /testindex +{ + "mappings": { + "properties": { + "patient": { + "type": "nested", + "properties": { + "name": { + "type": "text" + }, + "age": { + "type": "integer" + } + } + } + } + } +} +``` + +接下来,将文档索引到示例索引中: + +```json +PUT /testindex/_doc/1 +{ + "patient": { + "name": "John Doe", + "age": 56 + } +} +``` + +要搜索嵌套的 `patient` 字段,请将您的查询包装在 `nested` 查询中并提供嵌套字段的 `path`: + +```json +GET /testindex/_search +{ + "query": { + "nested": { + "path": "patient", + "query": { + "match": { + "patient.name": "John" + } + } + } + } +} +``` + +查询返回匹配的文档: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.13076457, + "_source": { + "patient": { + "name": "John Doe", + "age": 56 + } + } + } + ] + } +} +``` + +## 检索内部命中 + +要返回匹配查询的内部命中,请提供 `inner_hits` 参数: + +```json +GET /testindex/_search +{ + "query": { + "nested": { + "path": "patient", + "query": { + "match": { + "patient.name": "John" + } + }, + "inner_hits": {} + } + } +} +``` + +响应包含额外的 `inner_hits` 字段。`_nested` 字段标识内部命中来源的特定内部对象。它包含嵌套命中及其相对于 `_source` 中位置的偏移量。由于排序和评分,`inner_hits` 中命中对象的位置通常与它们在嵌套对象中的原始位置不同。 + +默认情况下,`inner_hits` 中命中对象的 `_source` 相对于 `_nested` 字段返回。在此示例中,`inner_hits` 中的 `_source` 包含 `name` 和 `age` 字段,而不是包含整个 `patient` 对象的顶级 `_source`: + +```json +{ + "took": 38, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_score": 0.13076457, + "_source": { + "patient": { + "name": "John Doe", + "age": 56 + } + }, + "inner_hits": { + "patient": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "testindex", + "_id": "1", + "_nested": { + "field": "patient", + "offset": 0 + }, + "_score": 0.13076457, + "_source": { + "name": "John Doe", + "age": 56 + } + } + ] + } + } + } + } + ] + } +} +``` + +::: tip TIP +您可以通过在映射中配置 `_source` 字段来禁用返回 `_source`。有关更多信息,请参阅 [Source](/mappings/metadata-fields/source/)。 +::: + +有关检索内部命中的更多信息,请参阅 [Inner hits](/search-plugins/searching-data/inner-hits)。 + +## 多级嵌套查询 + +您可以使用多级嵌套查询搜索嵌套对象内部包含其他嵌套对象的文档。在此示例中,您将通过为层次结构的每个级别指定嵌套查询来查询多层嵌套字段。 + +首先,创建一个具有多级嵌套字段的索引: + +```json +PUT /patients +{ + "mappings": { + "properties": { + "patient": { + "type": "nested", + "properties": { + "name": { + "type": "text" + }, + "contacts": { + "type": "nested", + "properties": { + "name": { + "type": "text" + }, + "relationship": { + "type": "text" + }, + "phone": { + "type": "keyword" + } + } + } + } + } + } + } +} +``` + +接下来,将两个文档索引到示例索引中: + +```json +PUT /patients/_doc/1 +{ + "patient": { + "name": "John Doe", + "contacts": [ + { + "name": "Jane Doe", + "relationship": "mother", + "phone": "5551111" + }, + { + "name": "Joe Doe", + "relationship": "father", + "phone": "5552222" + } + ] + } +} +``` + +```json +PUT /patients/_doc/2?refresh +{ + "patient": { + "name": "Mary Major", + "contacts": [ + { + "name": "Jane Major", + "relationship": "sister", + "phone": "5553333" + }, + { + "name": "Paula Major", + "relationship": "mother", + "phone": "5554444" + } + ] + } +} +``` + +要搜索嵌套的 `patient` 字段,请使用多级 `nested` 查询。以下查询搜索联系人信息包含名为 `Jane` 且关系为 `mother` 的人的患者: + +```json +GET /patients/_search +{ + "query": { + "nested": { + "path": "patient", + "query": { + "nested": { + "path": "patient.contacts", + "query": { + "bool": { + "must": [ + { "match": { "patient.contacts.relationship": "mother" } }, + { "match": { "patient.contacts.name": "Jane" } } + ] + } + } + } + } + } + } +} +``` + +内部 `bool` 查询中的两个条件必须匹配同一个联系人对象。文档 2 有一个名为 `Jane` 的联系人和一个关系为 `mother` 的联系人,但它们是不同的联系人,因此只返回文档 1。如果 `contacts` 被映射为 `object` 字段而不是 `nested`,联系人值将被展平为数组,相同的条件将匹配两个文档。 + +查询返回具有匹配这些详细信息的联系人条目的患者: + +```json +{ + "took": 9, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.63013375, + "hits": [ + { + "_index": "patients", + "_id": "1", + "_score": 0.63013375, + "_source": { + "patient": { + "name": "John Doe", + "contacts": [ + { + "name": "Jane Doe", + "relationship": "mother", + "phone": "5551111" + }, + { + "name": "Joe Doe", + "relationship": "father", + "phone": "5552222" + } + ] + } + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `nested` 查询支持的所有顶级参数。 + +| 参数 | 必需/可选 | 描述 | +|:---|:---|:---| +| `path` | 必需 | 指定要搜索的嵌套对象的路径。 | +| `query` | 必需 | 要在指定 `path` 内的嵌套对象上运行的查询。如果嵌套对象匹配查询,则返回根父文档。您可以使用点表示法搜索嵌套字段,例如 `nested_object.subfield`。支持多级嵌套并自动检测。因此,另一个嵌套查询中的内部 `nested` 查询会自动匹配正确的嵌套级别,而不是根。 | +| `ignore_unmapped` | 可选 | 指示是否忽略未映射的 `path` 字段并不返回文档而不是抛出错误。当查询多个索引时可以提供此参数,其中一些可能不包含 `path` 字段。默认值为 `false`。 | +| `score_mode` | 可选 | 定义匹配内部文档的分数如何影响父文档的分数。有效值为:<br> - `avg`:使用所有匹配内部文档的平均相关性分数。<br> - `max`:将匹配内部文档的最高相关性分数分配给父文档。<br> - `min`:将匹配内部文档的最低相关性分数分配给父文档。<br> - `sum`:对所有匹配内部文档的相关性分数求和。<br> - `none`:忽略内部文档的相关性分数,并为父文档分配 `0` 分。<br> 默认值为 `avg`。 | +| `inner_hits` | 可选 | 如果提供,则返回匹配查询的底层命中。 | + +## 后续步骤 + +- 了解更多关于 [检索内部命中](/search-plugins/searching-data/inner-hits)。 diff --git a/i18n/zh/query-dsl/joining/parent-id.md b/i18n/zh/query-dsl/joining/parent-id.md new file mode 100644 index 00000000..db1b3619 --- /dev/null +++ b/i18n/zh/query-dsl/joining/parent-id.md @@ -0,0 +1,91 @@ +--- +title: Parent ID +--- + +# Parent ID 查询 + +`parent_id` 查询返回其父文档具有指定 ID 的子文档。您可以使用 [join](/mappings/supported-field-types/join/) 字段类型在同一索引中的文档之间建立父/子关系。 + +## 示例 + +在运行 `parent_id` 查询之前,您的索引必须包含 [join](/mappings/supported-field-types/join/) 字段以建立父/子关系。此示例使用 `testindex1` 索引,其 `product_to_brand` join 字段将 `brand` 文档定义为父文档,将 `product` 文档定义为子文档: + +```json +PUT testindex1 +{ + "mappings": { + "properties": { + "product_to_brand": { + "type": "join", + "relations": { + "brand": "product" + } + } + } + } +} +``` + +按照 [`has_child` 查询示例](/query-dsl/joining/has-child)中所述索引品牌和产品文档。 + +要搜索特定父文档的子文档,请使用 `parent_id` 查询。以下查询返回父文档 ID 为 `1` 的子文档(产品): + +```json +GET testindex1/_search +{ + "query": { + "parent_id": { + "type": "product", + "id": "1" + } + } +} +``` + +响应返回子产品: + +```json +{ + "took": 57, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.87546873, + "hits": [ + { + "_index": "testindex1", + "_id": "3", + "_score": 0.87546873, + "_routing": "1", + "_source": { + "name": "Mechanical watch", + "sales_count": 150, + "product_to_brand": { + "name": "product", + "parent": "1" + } + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `parent_id` 查询支持的所有顶级参数。 + +| 参数 | 必需/可选 | 描述 | +|:---|:---|:---| +| `type` | 必需 | 指定 `join` 字段映射中定义的子关系名称。 | +| `id` | 必需 | 父文档的 ID。查询返回与此父文档关联的子文档。 | +| `ignore_unmapped` | 可选 | 指示是否忽略未映射的 `type` 字段并不返回文档而不是抛出错误。当查询多个索引时可以提供此参数,其中一些可能不包含 `type` 字段。默认值为 `false`。 | diff --git a/i18n/zh/query-dsl/named-queries.md b/i18n/zh/query-dsl/named-queries.md new file mode 100644 index 00000000..32e12225 --- /dev/null +++ b/i18n/zh/query-dsl/named-queries.md @@ -0,0 +1,101 @@ +--- +title: 命名查询 +--- + +# 命名查询 + +任何查询子句都可以包含一个 `_name` 参数来为其分配标签。当文档匹配时,响应会包含一个 `matched_queries` 数组,列出所有对匹配有贡献的查询子句的名称。这对于识别复杂查询中匹配给定文档的部分非常有用。 + +## 示例 + +以下查询在 `bool` 查询中使用两个命名的 `match` 子句。每个子句都有一个 `_name` 来标识它: + +```json +GET opensearch_dashboards_sample_data_ecommerce/_search +{ + "size": 2, + "_source": ["products.product_name", "customer_full_name"], + "query": { + "bool": { + "should": [ + {"match": {"products.product_name": {"query": "shirt", "_name": "shirt_query"}}}, + {"match": {"products.product_name": {"query": "dress", "_name": "dress_query"}}} + ] + } + } +} +``` + +## 示例响应 + +每个命中中的 `matched_queries` 数组显示哪些命名子句匹配了该文档: + +```json +{ + "took": 16, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1746, + "relation": "eq" + }, + "max_score": 1.8150847, + "hits": [ + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "aoN5u50BpPQaFxRehbyq", + "_score": 1.8150847, + "_source": { + "customer_full_name": "Stephanie Reyes", + "products": [ + { + "product_name": "Shirt - black/white" + }, + { + "product_name": "Cocktail dress / Party dress - navy" + } + ] + }, + "matched_queries": [ + "shirt_query", + "dress_query" + ] + }, + { + "_index": "opensearch_dashboards_sample_data_ecommerce", + "_id": "fYN5u50BpPQaFxRehLqd", + "_score": 1.6545942, + "_source": { + "customer_full_name": "Clarice Daniels", + "products": [ + { + "product_name": "Summer dress - grey" + }, + { + "product_name": "Shirt - black/white" + } + ] + }, + "matched_queries": [ + "shirt_query", + "dress_query" + ] + } + ] + } +} +``` + +## 响应正文字段 + +下表列出了命名查询特有的响应字段。 + +| 字段 | 描述 | +| :--- | :--- | +| `matched_queries` | 一个字符串数组,列出所有匹配此文档的查询子句的 `_name` 值。仅在至少有一个命名子句匹配时才存在。 | diff --git a/i18n/zh/query-dsl/regex-syntax.md b/i18n/zh/query-dsl/regex-syntax.md new file mode 100644 index 00000000..d3faeada --- /dev/null +++ b/i18n/zh/query-dsl/regex-syntax.md @@ -0,0 +1,297 @@ +--- +title: 正则表达式语法 +--- + +# 正则表达式语法 + +[正则表达式](https://en.wikipedia.org/wiki/Regular_expression)(regex)是一种使用特殊符号和运算符定义搜索模式的方法。这些模式允许您匹配字符串中的字符序列。 + +在 OpenSearch 中,您可以在以下查询类型中使用正则表达式: + +* [`regexp`](/query-dsl/term/regexp) +* [`query_string`](/query-dsl/full-text/query-string) + +::: info NOTE +OpenSearch 使用 [Apache Lucene](https://lucene.apache.org/core/) 正则表达式引擎,它有自己的语法和限制。它**不**使用 [Perl 兼容正则表达式 (PCRE)](https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions),因此一些熟悉的正则表达式功能可能行为不同或不受支持。 +::: + +## 在 regexp 和 query_string 查询之间选择 + +`regexp` 和 `query_string` 查询都支持正则表达式,但它们的行为不同,适用于不同的用例。 + +| 特性 | `regexp` 查询 | `query_string` 查询 | +| ------------------------- | -------------------------------------------------- | --------------------------------------------------- | +| 模式匹配 | 正则表达式模式必须匹配整个字段值 | 正则表达式模式可以匹配字段的任何部分 | +| `flags` 支持 | `flags` 启用可选的正则表达式运算符 | 不支持 `flags` | +| 查询类型 | 词项级查询(不评分) | 全文查询(评分和解析) | +| 最佳用例 | 对关键字或精确字段进行严格模式匹配 | 使用支持正则表达式模式的灵活查询字符串在分析字段中搜索 | +| 复杂查询组合 | 仅限于正则表达式模式 | 支持 `AND`、`OR`、通配符、字段、提升和其他功能。请参阅 [Query string query](/query-dsl/full-text/query-string)。 | + +## 保留字符 + +Lucene 的正则表达式引擎支持所有 Unicode 字符。但是,以下字符被视为特殊运算符: + +``` +. ? + * | { } [ ] ( ) " \ +``` + +根据启用的指定[可选运算符](#可选运算符)的 `flags`,以下字符也可能被保留: + +``` +@ & ~ < > +``` + +要字面匹配这些字符,请使用反斜杠(`\`)转义它们或将整个字符串用双引号括起来: + +- `\&`:匹配字面 `&` +- `\\`:匹配字面反斜杠(`\`) +- `"hello@world"`:匹配完整字符串 `hello@world` + +## 标准正则表达式运算符 + +Lucene 支持一组核心正则表达式运算符: + +- `.` – 匹配任何单个字符。**示例**:`f.n` 匹配 `f` 后跟任何字符然后是 `n`(例如,`fan` 或 `fin`)。 + +- `?` – 匹配零个或一个前面的字符。**示例**:`colou?r` 匹配 `color` 和 `colour`。 + +- `+` – 匹配一个或多个前面的字符。**示例**:`go+` 匹配 `g` 后跟一个或多个 `o`(`go`、`goo`、`gooo` 等)。 + +- `*` – 匹配零个或多个前面的字符。**示例**:`lo*se` 匹配 `l` 后跟零个或多个 `o` 然后是 `se`(`lse`、`lose`、`loose`、`loooose` 等)。 + +- `{min,max}` – 匹配特定范围的重复次数。如果省略 `max`,则匹配的字符数没有上限。**示例**:`x{3}` 精确匹配 3 个 `x`(`xxx`);`x{2,4}` 匹配 2 到 4 个 `x`(`xx`、`xxx` 或 `xxxx`);`x{3,}` 匹配 3 个或更多 `x`(`xxx`、`xxxx`、`xxxxx` 等)。 + +- `|` – 作为逻辑 `OR`。**示例**:`apple|orange` 匹配 `apple` 或 `orange`。 + +- `( )` – 将字符分组为子模式。**示例**:`ab(cd)?` 匹配 `ab` 和 `abcd`。 + +- `[ ]` – 匹配集合或范围中的一个字符。**示例**:`[aeiou]` 匹配任何元音字母。 + - `-` – 在括号内提供时,表示范围,除非被转义或是括号内的第一个字符。**示例**:`[a-z]` 匹配任何小写字母;`[-az]` 匹配 `-`、`a` 或 `z`;`[a\\-z]` 匹配 `a`、`-` 或 `z`。 + - `^` – 在括号内提供时,作为逻辑 `NOT`,否定字符范围或集合中的任何字符。**示例**:`[^az]` 匹配除 `a` 或 `z` 之外的任何字符;`[^a-z]` 匹配除小写字母之外的任何字符;`[^-az]` 匹配除 `-`、`a` 和 `z` 之外的任何字符;`[^a\\-z]` 匹配除 `a`、`-` 和 `z` 之外的任何字符。 + +## 可选运算符 + +您可以使用 `flags` 参数启用其他正则表达式运算符。使用 `|` 分隔多个标志。 + +以下是可用的标志: + +- `ALL`(默认)– 启用所有可选运算符。 + +- `COMPLEMENT` – 启用 `~`,它否定最短的后续表达式。**示例**:`d~ef` 匹配 `dgf`、`dxf`,但不匹配 `def`。 + +- `INTERSECTION` – 启用 `&` 作为 `AND` 逻辑运算符。**示例**:`ab.+&.+cd` 匹配开头包含 `ab` 结尾包含 `cd` 的字符串。 + +- `INTERVAL` – 启用 `<min-max>` 语法来匹配数字范围。**示例**:`id<10-12>` 匹配 `id10`、`id11` 和 `id12`。 + +- `ANYSTRING` – 启用 `@` 来匹配任何字符串。您可以将此与 `~` 和 `&` 结合使用进行排除。**示例**:`@&.*error.*&.*[0-9]{3}.*` 匹配同时包含单词"error"和三位数字序列的字符串。 + +## 不支持的功能 + +Lucene 的引擎不支持以下常用的正则表达式锚点: + +- `^` – 行首 +- `$` – 行尾 + +相反,您的模式必须匹配整个字符串才能产生匹配。 + +## 示例 + +要尝试正则表达式,请将以下文档索引到 `logs` 索引中: + +```json +PUT /logs/_doc/1 +{ + "message": "error404" +} +``` + +```json +PUT /logs/_doc/2 +{ + "message": "error500" +} +``` + +```json +PUT /logs/_doc/3 +{ + "message": "error1a" +} +``` + +### 示例:包含正则表达式的基本查询 + +以下 `regexp` 查询返回 `message` 字段的整个值匹配模式"error"后跟一个或多个数字的文档。如果值仅包含该模式作为子字符串,则不匹配: + +```json +GET /logs/_search +{ + "query": { + "regexp": { + "message": { + "value": "error[0-9]+" + } + } + } +} +``` + +此查询匹配 `error404` 和 `error500`: + +```json +{ + "took": 28, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1, + "_source": { + "message": "error404" + } + }, + { + "_index": "logs", + "_id": "2", + "_score": 1, + "_source": { + "message": "error500" + } + } + ] + } +} +``` + +### 示例:使用可选运算符 + +以下查询匹配 `message` 字段精确匹配以"error"开头后跟 400 到 500(包括)之间数字的字符串的文档。`INTERVAL` 标志启用 `<min-max>` 语法用于数字范围: + +```json +GET /logs/_search +{ + "query": { + "regexp": { + "message": { + "value": "error<400-500>", + "flags": "INTERVAL" + } + } + } +} +``` + +此查询匹配 `error404` 和 `error500`: + +```json +{ + "took": 22, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1, + "_source": { + "message": "error404" + } + }, + { + "_index": "logs", + "_id": "2", + "_score": 1, + "_source": { + "message": "error500" + } + } + ] + } +} +``` + +### 示例:使用 ANYSTRING + +当启用 `ANYSTRING` 标志时,`@` 运算符匹配整个字符串。当与交集(`&`)结合使用时,这很有用,因为它允许您构建在特定条件下匹配完整字符串的查询。 + +以下查询匹配同时包含单词"error"和三位数字序列的消息。使用 `ANYSTRING` 来断言整个字段必须匹配两个模式的交集: + +```json +GET /logs/_search +{ + "query": { + "regexp": { + "message.keyword": { + "value": "@&.*error.*&.*[0-9]{3}.*", + "flags": "ANYSTRING|INTERSECTION" + } + } + } +} +``` + +此查询匹配 `error404` 和 `error500`: + +```json +{ + "took": 20, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "logs", + "_id": "1", + "_score": 1, + "_source": { + "message": "error404" + } + }, + { + "_index": "logs", + "_id": "2", + "_score": 1, + "_source": { + "message": "error500" + } + } + ] + } +} +``` + +请注意,此查询还将匹配 `xerror500`、`error500x` 和 `errorxx500`。 diff --git a/i18n/zh/query-dsl/rescore.md b/i18n/zh/query-dsl/rescore.md new file mode 100644 index 00000000..fbbdd27f --- /dev/null +++ b/i18n/zh/query-dsl/rescore.md @@ -0,0 +1,137 @@ +--- +title: Rescore +--- + +# Rescore 参数 + +`rescore` 参数通过仅重新排序从初始查询返回的最高排名文档来提高搜索精度。重评分不是将昂贵的算法应用于索引中的所有文档,而是将计算资源集中在使用辅助评分方法对较小窗口的顶部结果进行重新排名。 + +当您在搜索请求中包含 `rescore` 参数时,OpenSearch 按以下顺序处理结果: + +1. **初始搜索**:主查询和任何后置过滤器在所有相关文档中执行。 +2. **分片级重评分**:每个分片将重评分算法应用于其顶部结果。 +3. **最终协调**:协调节点合并来自所有分片的重评分结果。 + +这种方法在保持可接受性能的同时提供更好的相关性。 + +使用 `rescore` 参数时,请注意以下重要事项: + +- 您不能将显式排序(除了降序的 `_score`)与重评分一起使用。如果您尝试将自定义排序与重评分查询结合使用,OpenSearch 将返回错误。 + +- 在实现分页时,请在所有页面中保持相同的 `window_size`。在页面之间更改窗口大小可能会导致用户浏览搜索结果时出现结果不一致。 + +- 当将重评分与通过搜索管道运行的[混合查询](/query-dsl/compound/hybrid#rescoring-hybrid-queries)一起使用时,重评分查询在归一化和组合之前在分片级别独立应用于每个子查询的结果。当混合查询在[融合模式](/vector-search/ai-search/hybrid-search/fusion-mode/#rescoring)下运行时,重评分查询在归一化和组合之后应用于组合排名。 + +## 查询重评分 + +查询重评分应用辅助查询来细化排名靠前的文档的分数。您可以使用 `window_size` 参数(默认为 `10`)控制每个分片检查多少文档。 + +### 基本重评分语法 + +```json +POST /_search +{ + "query": { + "match": { + "content": { + "query": "OpenSearch query optimization", + "operator": "or" + } + } + }, + "rescore": { + "window_size": 100, + "query": { + "rescore_query": { + "match_phrase": { + "content": { + "query": "OpenSearch query optimization", + "slop": 1 + } + } + }, + "query_weight": 0.8, + "rescore_query_weight": 1.3 + } + } +} +``` + +### 重评分参数 + +`rescore` 对象支持以下参数。 + +参数 | 类型 | 描述 +--- | --- | --- +`window_size` | Integer | 每个分片要重评分的顶部文档数。默认值为 `10`。 +`query_weight` | Float | 应用于原始查询分数的权重。默认值为 `1.0`。 +`rescore_query_weight` | Float | 应用于重评分查询分数的权重。默认值为 `1.0`。 +`score_mode` | String | 组合原始分数和重评分查询分数的方法。默认值为 `total`。请参阅[分数组合模式](#分数组合模式)。 + +### 分数组合模式 + +`score_mode` 参数确定 OpenSearch 如何将原始分数与重评分查询分数组合。此参数接受以下值。 + +模式 | 描述 | 用例 +--- | --- | --- +`total` | 将原始分数 + 重评分分数相加 | 一般相关性改进(默认) +`multiply` | 将原始分数 × 重评分分数相乘 | 对返回 0 和 1 之间值的函数查询有效 +`avg` | 对两个分数取平均值 | 当两个分数同等重要时的平衡方法 +`max` | 使用两个分数中较高的一个 | 确保在任一查询中得分较高的文档排名靠前 +`min` | 使用两个分数中较低的一个 | 要求两个查询都同意的保守方法 + +## 多阶段重评分 + +您可以链接多个重评分操作以应用越来越复杂的排名算法: + +```json +POST /_search +{ + "query": { + "match": { + "title": { + "query": "search engine technology", + "operator": "or" + } + } + }, + "rescore": [ + { + "window_size": 200, + "query": { + "rescore_query": { + "match_phrase": { + "title": { + "query": "search engine technology", + "slop": 2 + } + } + }, + "query_weight": 0.6, + "rescore_query_weight": 1.4 + } + }, + { + "window_size": 50, + "query": { + "score_mode": "multiply", + "rescore_query": { + "function_score": { + "script_score": { + "script": { + "source": "Math.log10(doc['popularity'].value + 2)" + } + } + } + } + } + } + ] +} +``` + +在此多阶段示例中: +1. **第一重评分阶段**检查每个分片 200 个文档,应用短语匹配以提高相关性。 +2. **第二重评分阶段**从第一阶段获取前 50 个结果,并使用对数函数应用基于流行度的评分。 + +每个阶段处理上一阶段的结果,创建一个细化管道,其中计算成本高的操作仅在最有希望的候选者上运行。 diff --git a/i18n/zh/query-dsl/rewrite-parameter.md b/i18n/zh/query-dsl/rewrite-parameter.md new file mode 100644 index 00000000..e9d5ebff --- /dev/null +++ b/i18n/zh/query-dsl/rewrite-parameter.md @@ -0,0 +1,243 @@ +--- +title: Rewrite +--- + +# Rewrite 参数 + +多词项查询如 `wildcard`、`prefix`、`regexp`、`fuzzy` 和 `range` 在内部扩展为词项集合。`rewrite` 参数允许您控制这些词项扩展如何执行和评分。 + +当多词项查询扩展为许多词项时(例如,`prefix: "error*"` 匹配数百个词项),它们在内部被转换为 `term` 查询。此过程可能有以下缺点: + +* 超过 `indices.query.bool.max_clause_count` 限制(默认为 `1024`)。 +* 影响匹配文档的分数计算方式。 +* 根据使用的重写方法影响内存和延迟。 + +`rewrite` 参数使您可以控制多词项查询在内部的行为方式。 + +| 模式 | 分数 | 性能 | 备注 | +| --------------------------- | -------------------------------------- | ----------- | --------------------------------------------- | +| `constant_score` | 所有匹配项分数相同 | 最佳 | 默认模式,适用于过滤器 | +| `scoring_boolean` | 基于 TF/IDF | 中等 | 完整相关性评分 | +| `constant_score_boolean` | 分数相同但具有布尔结构 | 中等 | 与 `must_not` 或 `minimum_should_match` 一起使用 | +| `top_terms_N` | 对前 N 个词项进行 TF/IDF | 高效 | 截断扩展 | +| `top_terms_boost_N` | 静态提升 | 快速 | 准确性较低 | +| `top_terms_blended_freqs_N` | 混合分数 | 平衡 | 最佳的评分/效率权衡 | + +## 可用的重写方法 + +下表总结了可用的重写方法。 + +| 重写方法 | 描述 | +| [`constant_score`](#constant-score) | (默认)所有扩展的词项作为单个单元一起评估,为每个匹配分配相同的分数。匹配的文档不会单独评分,使其对过滤用例非常高效。 | +| [`scoring_boolean`](#scoring-boolean) | 将查询分解为布尔 `should` 子句,每个匹配一个词项查询。每个结果根据相关性单独评分。 | +| [`constant_score_boolean`](#constant-score-boolean) | 类似于 `scoring_boolean`,但所有文档无论词项频率如何都获得固定分数。在没有 TF/IDF 权重的情况下保持布尔结构。 | +| [`top_terms_N`](#top-terms-n) | 将评分和执行限制为 N 个最频繁的词项。减少资源使用并防止子句过载。 | +| [`top_terms_boost_N`](#top-terms-boost-n) | 类似于 `top_terms_N`,但使用静态提升而不是完整评分。通过简化的相关性提供性能改进。 | +| [`top_terms_blended_freqs_N`](#top-terms-blended-frequencies-n) | 选择前 N 个匹配词项并平均其文档频率进行评分。在没有完整词项扩展的情况下产生平衡的分数。 | + +## 基于布尔的重写限制 + +所有基于布尔的重写,如 `scoring_boolean`、`constant_score_boolean` 和 `top_terms_*`,都受以下索引动态[集群设置](/install-and-configure/configuring-opensearch/cluster-settings-for-indexes#dynamic-settings)的约束: + +```json +indices.query.bool.max_clause_count +``` + +此设置控制允许的布尔 `should` 子句的最大数量(默认为 `1024`)。如果您的查询扩展的子句数量超过此限制,它将被拒绝,并返回 `too_many_clauses` 错误作为 HTTP 400 Bad Request 响应。同样,如果您的查询_及其所有子查询累计_扩展的子句总数超过此限制,它将被拒绝,并返回 `too_many_nested_clauses` 错误作为 HTTP 400 Bad Request 响应。 + +例如,通配符如"error*"可能扩展为数百或数千个匹配词项,其中可能包括"error"、"errors"、"error_log"、"error404"等。这些词项中的每一个都变成一个单独的 `term` 查询。如果词项数量超过 `indices.query.bool.max_clause_count` 限制,查询将失败: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "error*", + "rewrite": "scoring_boolean" + } + } + } +} +``` + +查询在内部扩展如下: + +```json +{ + "bool": { + "should": [ + { "term": { "message": "error" } }, + { "term": { "message": "errors" } }, + { "term": { "message": "error_log" } }, + { "term": { "message": "error404" } }, + ... + ] + } +} +``` + +## Constant score + +默认的 `constant_score` 重写方法将所有扩展的词项包装成单个查询并完全跳过评分阶段。此方法具有以下特点: + +* 将所有词项匹配作为单个[位数组](https://en.wikipedia.org/wiki/Bit_array)查询执行。 +* 完全忽略评分;每个文档获得 `1.0` 的 `_score`。 +* 最快的选项;适用于过滤。 + +以下示例使用默认的 `constant_score` 重写方法运行 `wildcard` 查询,以高效地过滤 `message` 字段中匹配模式 `warning*` 的文档: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*" + } + } + } +} +``` + +## Scoring Boolean + +`scoring_boolean` 重写方法将扩展的词项分解为在布尔 `should` 子句下组合的单独 `term` 查询。此方法的工作方式如下: + +* 将通配符扩展为布尔 `should` 子句内的单独 `term` 查询。 +* 每个文档的分数反映它匹配了多少词项以及词项的频率。 + +以下示例使用 `scoring_boolean` 重写配置: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "scoring_boolean" + } + } + } +} +``` + +## Constant score Boolean + +`constant_score_boolean` 重写方法使用与 `scoring_boolean` 相同的布尔结构,但禁用评分,当需要子句逻辑但不需要相关性排名时很有用。此方法具有以下特点: + +* 与 `scoring_boolean` 结构类似,但文档不排名。 +* 所有匹配的文档获得相同的分数。 +* 保留布尔子句灵活性,例如使用 `must_not`,而不进行排名。 + +以下示例查询使用 `must_not` 布尔子句: + +```json +POST /logs/_search +{ + "query": { + "bool": { + "must_not": { + "wildcard": { + "message": { + "value": "error*", + "rewrite": "constant_score_boolean" + } + } + } + } + } +} +``` + +此查询在内部扩展如下: + +```json +{ + "bool": { + "must_not": { + "bool": { + "should": [ + { "term": { "message": "error" } }, + { "term": { "message": "errors" } }, + { "term": { "message": "error_log" } }, + ... + ] + } + } + } +} +``` + +## Top terms N + +`top_terms_N` 方法是几种重写选项之一,旨在扩展多词项查询时平衡评分准确性和性能。它的工作方式如下: + +* 仅选择 N 个最频繁匹配的词项并评分。 +* 当您预期大量词项扩展并希望限制负载时很有用。 +* 其他有效词项被忽略以保持性能。 + +以下查询使用 `top_terms_2` 重写方法仅对 `message` 字段中匹配 `warning*` 模式的两个最频繁词项进行评分: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "top_terms_2" + } + } + } +} +``` + +## Top terms boost N + +`top_terms_boost_N` 重写方法选择前 N 个匹配词项并应用静态 `boost` 值而不是计算完整的相关性分数。它的工作方式如下: + +* 像 `top_terms_N` 一样将扩展限制为前 N 个词项。 +* 不计算 TF/IDF,而是为每个词项分配预设的提升值。 +* 提供更快的执行和可预测的相关性权重。 + +以下示例使用 `top_terms_boost_2` 重写参数: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "top_terms_boost_2" + } + } + } +} +``` + +## Top terms blended frequencies N + +`top_terms_blended_freqs_N` 重写方法选择前 N 个匹配词项并混合其文档频率以产生更平衡的相关性分数。此方法具有以下特点: + +* 选择前 N 个匹配词项并对所有词项应用混合频率。 +* 混合使频率不同的词项之间的评分更加平滑。 +* 当您希望性能与真实评分兼得时是个好的权衡。 + +以下示例使用 `top_terms_blended_freqs_2` 重写参数: + +```json +POST /logs/_search +{ + "query": { + "wildcard": { + "message": { + "value": "warning*", + "rewrite": "top_terms_blended_freqs_2" + } + } + } +} +``` diff --git a/i18n/zh/query-dsl/span/index.md b/i18n/zh/query-dsl/span/index.md new file mode 100644 index 00000000..8b2f899c --- /dev/null +++ b/i18n/zh/query-dsl/span/index.md @@ -0,0 +1,82 @@ +--- +title: Span 查询 +--- + +# Span 查询 + +您可以使用 span 查询执行精确的位置搜索。Span 查询是低级的、特定的查询,可以控制指定查询词项的顺序和邻近性。它们主要用于搜索法律文档和专利。 + +Span 查询包括以下查询类型: + +| 查询类型 | 描述 | +| :--- | :--- | +| [Span containing](/query-dsl/span/span-containing) | 返回包含较小 span 的较大 span。与 `span_within` 查询相反。 | +| [Span field masking](/query-dsl/span/span-field-masking) | 通过使一个字段看起来像另一个字段,允许 span 查询跨不同字段工作。当相同的文本使用不同的分析器索引时很有用。 | +| [Span first](/query-dsl/span/span-first) | 匹配出现在字段开头指定位置数内的词项或短语。 | +| [Span multi-term](/query-dsl/span/span-multi-term) | 使多词项查询(如 `prefix`、`wildcard` 或 `fuzzy`)能够在 span 查询中工作。 | +| [Span near](/query-dsl/span/span-near) | 查找在彼此指定距离内出现的词项或短语。支持要求匹配以特定顺序出现。 | +| [Span not](/query-dsl/span/span-not) | 排除与另一个 span 查询重叠的匹配。 | +| [Span or](/query-dsl/span/span-or) | 匹配满足任何提供的 span 查询的文档。 | +| [Span term](/query-dsl/span/span-term) | 匹配单个词项,同时维护位置信息以供其他 span 查询使用。 | +| [Span within](/query-dsl/span/span-within) | 返回被较大 span 包围的较小 span。与 `span_containing` 查询相反。 | + +## 设置 + +要尝试本节中的示例,请使用以下步骤配置示例索引。 + +### 步骤 1:创建索引 + +首先,为电子商务服装网站创建一个索引。`description` 字段使用默认的 `standard` 分析器,而 `description.stemmed` 子字段应用 `english` 分析器以启用词干提取: + +```json +PUT /clothing +{ + "mappings": { + "properties": { + "description": { + "type": "text", + "analyzer": "standard", + "fields": { + "stemmed": { + "type": "text", + "analyzer": "english" + } + } + } + } + } +} +``` + +### 步骤 2:索引数据 + +将示例文档索引到索引中: + +```json +POST /clothing/_doc/1 +{ + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " +} + +``` + +```json +POST /clothing/_doc/2 +{ + "description": "Beautiful long dress in red silk, perfect for formal events." +} +``` + +```json +POST /clothing/_doc/3 +{ + "description": "Short-sleeved shirt with a button-down collar, can be dressed up or down." +} +``` + +```json +POST /clothing/_doc/4 +{ + "description": "A set of two midi silk shirt dresses with long sleeves in black. " +} +``` diff --git a/i18n/zh/query-dsl/span/span-containing.md b/i18n/zh/query-dsl/span/span-containing.md new file mode 100644 index 00000000..5abde5ac --- /dev/null +++ b/i18n/zh/query-dsl/span/span-containing.md @@ -0,0 +1,107 @@ +--- +title: Span containing +--- + +# Span containing 查询 + +`span_containing` 查询查找较大文本模式(如短语或一组单词)在其边界内包含较小文本模式的匹配。可以将其视为查找单词或短语,但仅当它出现在特定较大上下文中时。 + +例如,您可以使用 `span_containing` 查询执行以下搜索: + +- 查找单词"quick",但仅当它出现在同时提及狐狸和行为的句子中时。 +- 确保某些词项出现在其他词项的上下文中---而不是文档中的任何位置。 +- 搜索出现在较大有意义短语中的特定单词。 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索出现在较大 span 内的单词"red",该较大 span 包含单词"silk"和"dress"(不一定按该顺序)在彼此 5 个单词内: + +```json +GET /clothing/_search +{ + "query": { + "span_containing": { + "little": { + "span_term": { + "description": "red" + } + }, + "big": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "silk" + } + }, + { + "span_term": { + "description": "dress" + } + } + ], + "slop": 5, + "in_order": false + } + } + } + } +} +``` + +查询匹配文档 1,因为: + +- 它找到一个 span,其中"silk"和"dress"在彼此最多 5 个单词内出现("...dress in red silk...")。词项"silk"和"dress"在彼此 2 个单词内(它们之间有 2 个单词)。 +- 在这个较大的 span 内,它找到词项"red"。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.1577396, + "hits": [ + { + "_index": "clothing", + "_id": "2", + "_score": 1.1577396, + "_source": { + "description": "Beautiful long dress in red silk, perfect for formal events." + } + } + ] + } +} +``` + +</details> + +`little` 和 `big` 参数都可以包含任何类型的 span 查询,在需要时允许复杂的嵌套 span 查询。 + +## 参数 + +下表列出了 `span_containing` 查询支持的所有顶级参数。所有参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +|:-----------|:------|:-------------| +| `little` | Object | 必须包含在 `big` span 内的 span 查询。这定义了您在较大上下文中搜索的 span。 | +| `big` | Object | 定义 `little` span 必须出现的边界的包含 span 查询。这为您的搜索建立上下文。 | diff --git a/i18n/zh/query-dsl/span/span-field-masking.md b/i18n/zh/query-dsl/span/span-field-masking.md new file mode 100644 index 00000000..86e8cdd3 --- /dev/null +++ b/i18n/zh/query-dsl/span/span-field-masking.md @@ -0,0 +1,112 @@ +--- +title: Span field masking +--- + +# Span field masking 查询 + +`field_masking_span` 查询通过"掩码"查询的真实字段,允许 span 查询跨不同字段匹配。当处理多字段(使用不同分析器索引的相同内容)或需要跨不同字段运行 span 查询(如 `span_near` 或 `span_or`,这通常是不允许的)时,这特别有用。 + +例如,您可以使用 `field_masking_span` 查询来: +- 跨原始字段及其词干版本匹配词项。 +- 在单个 span 操作中组合不同字段上的 span 查询。 +- 使用不同分析器处理索引的相同内容。 + +::: info NOTE +使用字段掩码时,相关性分数是使用掩码字段的特征(规范)而不是正在搜索的实际字段计算的。这意味着如果掩码字段具有与正在搜索的字段不同的属性(如长度或提升值),您可能会收到意外的评分结果。 +::: + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询在词干字段中搜索单词"long"靠近单词"sleeve"的变体: + +```json +GET /clothing/_search +{ + "query": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "long" + } + }, + { + "field_masking_span": { + "query": { + "span_term": { + "description.stemmed": "sleev" + } + }, + "field": "description" + } + } + ], + "slop": 1, + "in_order": true + } + } +} + +``` + +查询匹配文档 1 和 4: +- 词项"long"在两个文档的 `description` 字段中出现。 +- 文档 1 包含单词"sleeved",文档 4 包含单词"sleeves"。 +- `field_masking_span` 使词干字段匹配看起来好像它在原始字段中。 +- 词项在指定顺序中彼此 1 个位置内出现("long"必须出现在"sleeve"之前)。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.7444251, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 0.7444251, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "4", + "_score": 0.4291246, + "_source": { + "description": "A set of two midi silk shirt dresses with long fluttered sleeves in black. " + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `field_masking_span` 查询支持的所有顶级参数。所有参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `query` | Object | 要在实际字段上执行的 span 查询。 | +| `field` | String | 用于掩码查询的字段名称。其他 span 查询将把此查询视为在此字段上执行。 | diff --git a/i18n/zh/query-dsl/span/span-first.md b/i18n/zh/query-dsl/span/span-first.md new file mode 100644 index 00000000..74b0cf8e --- /dev/null +++ b/i18n/zh/query-dsl/span/span-first.md @@ -0,0 +1,97 @@ +--- +title: Span first +--- + +# Span first 查询 + +`span_first` 查询匹配从字段开头开始并在指定位置数内结束的 span。当您想查找出现在文档开头附近的词项或短语时,此查询很有用。 + +例如,您可以使用 `span_first` 查询执行以下搜索: + +- 查找特定词项出现在字段前几个单词中的文档。 +- 确保某些短语出现在文本的开头或附近 +- 仅当模式出现在距开头指定距离内时才匹配 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索词干词"dress"出现在描述的前 4 个位置内: + +```json +GET /clothing/_search +{ + "query": { + "span_first": { + "match": { + "span_term": { + "description.stemmed": "dress" + } + }, + "end": 4 + } + } +} +``` + +查询匹配文档 1 和 2: +- 文档 1 和 2 包含单词 `dress` 在第三个位置("Long-sleeved dress..." 和 "Beautiful long dress")。单词的索引从 0 开始,因此单词"dress"在位置 2。 +- 单词 `dress` 的位置必须小于 `4`,如 `end` 参数所指定。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 13, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.110377684, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 0.110377684, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "2", + "_score": 0.110377684, + "_source": { + "description": "Beautiful long dress in red silk, perfect for formal events." + } + } + ] + } +} +``` + +</details> + +`match` 参数可以包含任何类型的 span 查询,允许在字段开头匹配更复杂的模式。 + +## 参数 + +下表列出了 `span_first` 查询支持的所有顶级参数。所有参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `match` | Object | 要匹配的 span 查询。这定义了您在字段开头搜索的模式。 | +| `end` | Integer | span 查询匹配允许的最大结束位置(不包括)。例如,`end: 4` 匹配位置 0-3 的词项。 | diff --git a/i18n/zh/query-dsl/span/span-multi-term.md b/i18n/zh/query-dsl/span/span-multi-term.md new file mode 100644 index 00000000..1b15173d --- /dev/null +++ b/i18n/zh/query-dsl/span/span-multi-term.md @@ -0,0 +1,130 @@ +--- +title: Span multi-term +--- + +# Span multi-term 查询 + +`span_multi` 查询允许您将多词项查询(如 `wildcard`、`fuzzy`、`prefix`、`range` 或 `regexp`)包装为 span 查询。这使您能够在其他 span 查询中使用这些更灵活的匹配查询。 + +例如,您可以使用 `span_multi` 查询来: +- 查找具有常见前缀的单词靠近其他词项。 +- 在 span 内匹配单词的模糊变体。 +- 在 span 查询中使用正则表达式。 + +::: info NOTE +>`span_multi` 查询可能匹配许多词项。为避免过度使用内存,您可以: +>- 为多词项查询设置 `rewrite` 参数。 +>- 使用 `top_terms_*` 重写方法。 +>- 如果您仅对 `prefix` 查询使用 `span_multi`,请考虑为文本字段启用 `index_prefixes` 选项。这会自动将字段上的任何 `prefix` 查询重写为匹配索引前缀的单词项查询。 +::: + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +`span_multi` 查询使用以下语法包装 `prefix` 查询: + +```json +"span_multi": { + "match": { + "prefix": { + "description": { + "value": "flutter" + } + } + } +} +``` + +以下查询搜索以"dress"开头的单词,在彼此最多 5 个单词内靠近任何形式的"sleeve": + +```json +GET /clothing/_search +{ + "query": { + "span_near": { + "clauses": [ + { + "span_multi": { + "match": { + "prefix": { + "description": { + "value": "dress" + } + } + } + } + }, + { + "field_masking_span": { + "query": { + "span_term": { + "description.stemmed": "sleev" + } + }, + "field": "description" + } + } + ], + "slop": 5, + "in_order": false + } + } +} +``` + +查询匹配文档 1("Long-sleeved dress...")和 4("...dresses with long fluttered sleeves..."),因为"dress"和"long"在两个文档中都在最大距离内出现。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 5, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.7590723, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 1.7590723, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "4", + "_score": 0.84792376, + "_source": { + "description": "A set of two midi silk shirt dresses with long fluttered sleeves in black. " + } + } + ] + } +} +``` +</details> + +## 参数 + +下表列出了 `span_multi` 查询支持的所有顶级参数。所有参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `match` | Object | 要包装的多词项查询(可以是 `prefix`、`wildcard`、`fuzzy`、`range` 或 `regexp`)。 | diff --git a/i18n/zh/query-dsl/span/span-near.md b/i18n/zh/query-dsl/span/span-near.md new file mode 100644 index 00000000..7593b83b --- /dev/null +++ b/i18n/zh/query-dsl/span/span-near.md @@ -0,0 +1,99 @@ +--- +title: Span near +--- + +# Span near 查询 + +`span_near` 查询匹配彼此相近的 span。您可以指定 span 之间可以相距多远以及它们是否需要按特定顺序出现。 + +例如,您可以使用 `span_near` 查询来: +- 查找在一定距离内出现的词项。 +- 匹配单词以特定顺序出现的短语。 +- 查找在文本中彼此相近出现的相关概念。 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索"sleeve"和"long"的任何形式以任何顺序彼此相邻出现: + +```json +GET /clothing/_search +{ + "query": { + "span_near": { + "clauses": [ + { + "span_term": { + "description.stemmed": "sleev" + } + }, + { + "span_term": { + "description.stemmed": "long" + } + } + ], + "slop": 1, + "in_order": false + } + } +} +``` + +查询匹配文档 1("Long-sleeved...")和 2("...long fluttered sleeves...")。在文档 1 中,单词彼此相邻,而在文档 2 中,它们在指定的 slop 距离 `1` 内(它们之间有 1 个单词)。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.36496973, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 0.36496973, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "4", + "_score": 0.25312424, + "_source": { + "description": "A set of two midi silk shirt dresses with long fluttered sleeves in black. " + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `span_near` 查询支持的所有顶级参数。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `clauses` | 定义要匹配的词项或短语的 span 查询数组。所有指定的词项必须出现在定义的 slop 距离内。必需。 | +| `slop` | Integer | span 之间允许的最大不匹配位置数。必需。 | +| `in_order` | Boolean | span 是否需要按照 `clauses` 数组中的相同顺序出现。可选。默认值为 `false`。 | diff --git a/i18n/zh/query-dsl/span/span-not.md b/i18n/zh/query-dsl/span/span-not.md new file mode 100644 index 00000000..96159e10 --- /dev/null +++ b/i18n/zh/query-dsl/span/span-not.md @@ -0,0 +1,77 @@ +--- +title: Span not +--- + +# Span not 查询 + +`span_not` 查询排除与另一个 span 查询重叠的 span。您还可以指定排除的 span 之前或之后的距离,在此距离内不能发生匹配。 + +例如,您可以使用 `span_not` 查询来: +- 查找词项,但当它们出现在某些短语中时除外。 +- 匹配 span,除非它们靠近特定词项。 +- 排除在其他模式一定距离内发生的匹配。 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索单词"dress",但当它出现在短语"dress shirt"中时除外: + +```json +GET /clothing/_search +{ + "query": { + "span_not": { + "include": { + "span_term": { + "description": "dress" + } + }, + "exclude": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "dress" + } + }, + { + "span_term": { + "description": "shirt" + } + } + ], + "slop": 0, + "in_order": true + } + } + } + } +} +``` + +查询匹配文档 2,因为它包含单词"dress"("Beautiful long dress...")。文档 1 不匹配,因为它包含短语"dress shirt",该短语被排除。文档 3 和 4 不匹配,因为它们包含单词"dress"的变体("dressed"和"dresses"),而查询是在原始字段上搜索的。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json + +``` +</details> + +## 参数 + +下表列出了 `span_not` 查询支持的所有顶级参数。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `include` | Object | 您要查找其匹配的 span 查询。必需。 | +| `exclude` | Object | 应排除其匹配的 span 查询。必需。 | +| `pre` | Integer | 指定 `exclude` span 不能出现在 `include` span 之前给定数量的词元位置内。可选。默认值为 `0`。 | +| `post` | Integer | 指定 `exclude` span 不能出现在 `include` span 之后给定数量的词元位置内。可选。默认值为 `0`。 | +| `dist` | Integer | 相当于将 `pre` 和 `post` 设置为相同的值。可选。 | diff --git a/i18n/zh/query-dsl/span/span-or.md b/i18n/zh/query-dsl/span/span-or.md new file mode 100644 index 00000000..e97cca2a --- /dev/null +++ b/i18n/zh/query-dsl/span/span-or.md @@ -0,0 +1,122 @@ +--- +title: Span or +--- + +# Span or 查询 + +`span_or` 查询组合多个 span 查询并匹配它们 span 的并集。如果至少有一个包含的 span 查询匹配,则匹配发生。 + +例如,您可以使用 `span_or` 查询来: +- 查找匹配多个模式之一的 span。 +- 将不同的 span 模式组合为替代方案。 +- 在单个查询中匹配多个 span 变体。 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索"formal collar"或"button collar"在彼此 2 个单词内出现: + +```json +GET /clothing/_search +{ + "query": { + "span_or": { + "clauses": [ + { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "formal" + } + }, + { + "span_term": { + "description": "collar" + } + } + ], + "slop": 0, + "in_order": true + } + }, + { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "button" + } + }, + { + "span_term": { + "description": "collar" + } + } + ], + "slop": 2, + "in_order": true + } + } + ] + } + } +} +``` + +查询在指定的 slop 距离内匹配文档 1("...formal collar...")和 3("...button-down collar...")。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 2.170027, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 2.170027, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + }, + { + "_index": "clothing", + "_id": "3", + "_score": 1.2509141, + "_source": { + "description": "Short-sleeved shirt with a button-down collar, can be dressed up or down." + } + } + ] + } +} +``` +</details> + +## 参数 + +下表列出了 `span_or` 查询支持的所有顶级参数。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `clauses` | Array | 要匹配的 span 查询数组。如果这些 span 查询中的任何一个匹配,则查询匹配。必须包含至少一个 span 查询。必需。 | diff --git a/i18n/zh/query-dsl/span/span-term.md b/i18n/zh/query-dsl/span/span-term.md new file mode 100644 index 00000000..3eeb8801 --- /dev/null +++ b/i18n/zh/query-dsl/span/span-term.md @@ -0,0 +1,116 @@ +--- +title: Span term +--- + +# Span term 查询 + +`span_term` 查询是最基本的 span 查询,用于匹配包含单个词项的 span。它是更复杂 span 查询的构建块。 + +例如,您可以使用 `span_term` 查询来: +- 查找可在其他 span 查询中使用的精确词项匹配。 +- 在维护位置信息的同时匹配特定单词。 +- 创建可与其他 span 查询组合的基本 span。 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索精确词项"formal": + +```json +GET /clothing/_search +{ + "query": { + "span_term": { + "description": "formal" + } + } +} +``` + +或者,您可以在 `value` 参数中指定搜索词项: + +```json +GET /clothing/_search +{ + "query": { + "span_term": { + "description": { + "value": "formal" + } + } + } +} +``` + +您还可以指定 `boost` 值以提升文档分数: + +```json +GET /clothing/_search +{ + "query": { + "span_term": { + "description": { + "value": "formal", + "boost": 2 + } + } + } +} +``` + +查询匹配文档 1 和 2,因为它们包含精确词项"formal"。位置信息被保留以供其他 span 查询使用。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.498922, + "hits": [ + { + "_index": "clothing", + "_id": "2", + "_score": 1.498922, + "_source": { + "description": "Beautiful long dress in red silk, perfect for formal events." + } + }, + { + "_index": "clothing", + "_id": "1", + "_score": 1.4466847, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + } + ] + } +} +``` +</details> + +## 参数 + +下表列出了 `span_term` 查询支持的所有顶级参数。 + +| 参数 | 数据类型 | 描述 | +|:----------------|:------------|:--------| +| `<field>` | String 或 object | 要搜索的字段名称。 | diff --git a/i18n/zh/query-dsl/span/span-within.md b/i18n/zh/query-dsl/span/span-within.md new file mode 100644 index 00000000..997f5c44 --- /dev/null +++ b/i18n/zh/query-dsl/span/span-within.md @@ -0,0 +1,102 @@ +--- +title: Span within +--- + +# Span within 查询 + +`span_within` 查询匹配被另一个 span 查询包围的 span。它与 [`span_containing`](/query-dsl/span/span-containing) 相反:`span_containing` 返回包含较小 span 的较大 span,而 `span_within` 返回被较大 span 包围的较小 span。 + +例如,您可以使用 `span_within` 查询来: +- 查找出现在较长短语中的较短短语。 +- 匹配在特定上下文中出现的词项。 +- 识别被较大模式包围的较小模式。 + +## 示例 + +::: tip TIP +要尝试本节中的示例,请完成[设置步骤](/query-dsl/span/#setup)。 +::: + +以下查询搜索单词"dress"当它出现在包含"shirt"和"long"的 span 内时: + +```json +GET /clothing/_search +{ + "query": { + "span_within": { + "little": { + "span_term": { + "description": "dress" + } + }, + "big": { + "span_near": { + "clauses": [ + { + "span_term": { + "description": "shirt" + } + }, + { + "span_term": { + "description": "long" + } + } + ], + "slop": 2, + "in_order": false + } + } + } + } +} +``` + +查询匹配文档 1,因为: +- 单词"dress"出现在较大的 span 内("Long-sleeved dress shirt...")。 +- 较大的 span 包含"shirt"和"long"在彼此 2 个单词内(它们之间有 2 个单词)。 + +<details markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.4677674, + "hits": [ + { + "_index": "clothing", + "_id": "1", + "_score": 1.4677674, + "_source": { + "description": "Long-sleeved dress shirt with a formal collar and button cuffs. " + } + } + ] + } +} +``` +</details> + +## 参数 + +下表列出了 `span_within` 查询支持的所有顶级参数。所有参数都是必需的。 + +| 参数 | 数据类型 | 描述 | +|:----------|:-----|:------------| +| `little` | Object | 必须包含在 `big` span 内的 span 查询。这定义了您在较大上下文中搜索的 span。 | +| `big` | Object | 定义 `little` span 必须出现的边界的包含 span 查询。这为您的搜索建立上下文。 | diff --git a/i18n/zh/query-dsl/specialized/agentic.md b/i18n/zh/query-dsl/specialized/agentic.md new file mode 100644 index 00000000..08530f93 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/agentic.md @@ -0,0 +1,59 @@ +--- +title: Agentic +--- + +# Agentic 查询 +<Badge type="tip" text="3.2 版本引入" /> + +使用 `agentic` 查询以自然语言提问,让 OpenSearch 自动规划和执行检索。`agentic` 查询与预配置的代理配合使用,代理读取问题、规划搜索并返回相关结果。有关代理搜索的更多信息,请参阅 [Agentic search](/vector-search/ai-search/agentic-search/index/)。 + +## 先决条件 + +在使用 `agentic` 查询之前,您必须满足以下先决条件: + +1. 使用 [`QueryPlanningTool`](/ml-commons-plugin/agents-tools/tools/query-planning-tool) 配置代理。`QueryPlanningTool` 是从自然语言问题生成查询领域特定语言 (DSL) 查询所必需的。您还可以选择为代理配置其他工具以增强功能。 +1. 使用 [`agentic_query_translator` 搜索请求处理器](/search-plugins/search-pipelines/agentic-query-translator-processor)创建搜索管道。 + +有关详细的设置说明,请参阅 [Agentic search](/vector-search/ai-search/agentic-search/index/)。 + +## 请求正文字段 + +`agentic` 查询接受以下字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`query_text` | String | 必需 | 代理要回答的自然语言问题。 +`query_fields` | Array | 可选 | 代理在生成搜索查询时应考虑的索引字段列表。如果省略,代理将根据索引映射和内容推断适用的字段。 +`memory_id` | String | 可选 | 仅适用于 `conversational` 代理。提供来自先前响应的内存 ID 以继续具有先前上下文的对话。请参阅 [Using conversational agents for agentic search](/vector-search/ai-search/agentic-search/agent-converse/)。 | + +## 示例 + +以下示例使用 `agentic` 查询,在 `iris` 数据集中提出关于花卉的自然语言问题。在此示例中,`query_text` 包含自然语言问题,`query_fields` 指定生成查询时要使用的字段,`search-pipeline` 查询参数指定包含代理查询转换器处理器的搜索管道: + +```json +GET /iris-index/_search?search_pipeline=agentic-pipeline +{ + "query": { + "agentic": { + "query_text": "List all the flowers present", + "query_fields": ["species", "petal_length_in_cm"] + } + } +} +``` + +执行时,代理搜索请求执行以下步骤: + +1. 将自然语言问题连同索引映射和默认提示发送到大型语言模型 (LLM)。 +2. LLM 根据输入生成查询领域特定语言 (DSL) 查询。 +3. 生成的 DSL 查询作为搜索请求在 OpenSearch 中执行。 +4. 根据生成的查询返回搜索结果。 + +有关完整示例,请参阅 [Agentic search](/vector-search/ai-search/agentic-search/index/)。 + +## 后续步骤 + +- 在 [Agentic search](/vector-search/ai-search/agentic-search/index/) 中了解如何配置代理搜索。 +- 在 [Agent types](/vector-search/ai-search/agentic-search/index/#agent-types) 中了解代理类型。 +- 了解 [`QueryPlanningTool`](/ml-commons-plugin/agents-tools/tools/query-planning-tool)。 +- 查看 [`agentic_query_translator` 搜索请求处理器](/search-plugins/search-pipelines/agentic-query-translator-processor)的参考文档。 diff --git a/i18n/zh/query-dsl/specialized/distance-feature.md b/i18n/zh/query-dsl/specialized/distance-feature.md new file mode 100644 index 00000000..6b9260dc --- /dev/null +++ b/i18n/zh/query-dsl/specialized/distance-feature.md @@ -0,0 +1,213 @@ +--- +title: Distance feature +--- + +# Distance feature 查询 + +使用 `distance_feature` 查询来提升更接近特定日期或地理点的文档的相关性。这可以帮助您在搜索结果中优先显示更新或更近的内容。例如,您可以为更近期制造的产品分配更多权重,或提升最接近用户指定位置的商品。 + +您可以将此查询应用于包含日期或位置数据的字段。它通常在 `bool` 查询的 `should` 子句中使用,以在不过滤结果的情况下提高相关性评分。 + +## 配置索引 + +在使用 `distance_feature` 查询之前,请确保您的索引包含以下字段类型之一: + +- [`date`](/mappings/supported-field-types/date/) +- [`date_nanos`](/mappings/supported-field-types/date-nanos/) +- [`geo_point`](/mappings/supported-field-types/geo-point/) + +在此示例中,您将配置可用于运行 distance feature 查询的 `opening_date` 和 `coordinates` 字段: + +```json +PUT /stores +{ + "mappings": { + "properties": { + "opening_date": { + "type": "date" + }, + "coordinates": { + "type": "geo_point" + } + } + } +} +``` + +向索引添加示例文档: + +```json +PUT /stores/_doc/1 +{ + "store_name": "Green Market", + "opening_date": "2025-03-10", + "coordinates": [74.00, 40.70] +} +``` + +```json +PUT /stores/_doc/2 +{ + "store_name": "Fresh Foods", + "opening_date": "2025-04-01", + "coordinates": [73.98, 40.75] +} +``` + +```json +PUT /stores/_doc/3 +{ + "store_name": "City Organics", + "opening_date": "2021-04-20", + "coordinates": [74.02, 40.68] +} +``` + +## 示例:基于新近度提升分数 + +以下查询搜索 `store_name` 匹配 `market` 的文档,并提升最近开业的商店: + +```json +GET /stores/_search +{ + "query": { + "bool": { + "must": { + "match": { + "store_name": "market" + } + }, + "should": { + "distance_feature": { + "field": "opening_date", + "origin": "2025-04-07", + "pivot": "10d" + } + } + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2372394, + "hits": [ + { + "_index": "stores", + "_id": "1", + "_score": 1.2372394, + "_source": { + "store_name": "Green Market", + "opening_date": "2025-03-10", + "coordinates": [ + 74, + 40.7 + ] + } + } + ] + } +} +``` + +### 示例:基于地理邻近度提升分数 + +以下查询搜索 `store_name` 匹配 `market` 的文档,并提升更接近给定原点的结果: + +```json +GET /stores/_search +{ + "query": { + "bool": { + "must": { + "match": { + "store_name": "market" + } + }, + "should": { + "distance_feature": { + "field": "coordinates", + "origin": [74.00, 40.71], + "pivot": "500m" + } + } + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2910118, + "hits": [ + { + "_index": "stores", + "_id": "1", + "_score": 1.2910118, + "_source": { + "store_name": "Green Market", + "opening_date": "2025-03-10", + "coordinates": [ + 74, + 40.7 + ] + } + } + ] + } +} +``` + +## 参数 + +下表列出了 `distance_feature` 查询支持的所有顶级参数。 + +| 参数 | 必需/可选 | 描述 | +|-----------|-------------------|-------------| +| `field` | 必需 | 用于计算距离的字段名称。必须是具有 `index: true`(默认)和 `doc_values: true`(默认)的 `date`、`date_nanos` 或 `geo_point` 字段。 | +| `origin` | 必需 | 用于计算距离的原点。对于 `date` 字段使用[日期](/mappings/supported-field-types/date/)或[日期数学表达式](/mappings/supported-field-types/date/#date-math)(例如,`now-1h`),对于 `geo_point` 字段使用[地理点](/mappings/supported-field-types/geo-point/)。 | +| `pivot` | 必需 | 分数获得 `boost` 值一半的距原点的距离。对于日期字段使用时间单位(例如,`10d`),对于地理字段使用距离单位(例如,`1km`)。有关更多信息,请参阅 [Units](/api-reference/units)。| +| `boost` | 可选 | 匹配文档相关性分数的乘数。必须是非负浮点数。默认值为 `1.0`。 | + +## 分数计算方式 + +`distance_feature` 查询使用以下公式计算文档的相关性分数: + +$$ \text{score} = \text{boost} \cdot \frac {\text{pivot}} {\text{pivot} + \text{distance}} $$ + +其中 $$\text{distance}$$ 是 `origin` 和字段值之间的绝对差。 + +## 跳过非竞争性命中 + +与其他分数修改查询(如 `function_score` 查询)不同,`distance_feature` 查询经过优化,可以在禁用总命中跟踪(`track_total_hits`)时高效地跳过非竞争性命中。 diff --git a/i18n/zh/query-dsl/specialized/k-nn/index.md b/i18n/zh/query-dsl/specialized/k-nn/index.md new file mode 100644 index 00000000..8748f4f8 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/k-nn/index.md @@ -0,0 +1,208 @@ +--- +title: k-NN +--- + +# k-NN 查询 + +使用 `knn` 查询对向量字段运行最近邻搜索。 + +## 传输协议 + +k-NN 查询可以使用两种传输协议执行: + +- **HTTP/REST API**:本节中记录的标准方法。 +- **gRPC API**(3.2 版本正式发布):使用 [k-NN (gRPC) API](/api-reference/grpc-apis/knn) 的高性能二进制协议。 + +对于高吞吐量向量搜索应用,考虑使用 gRPC k-NN API,它与基于 HTTP 的查询相比提供更低的延迟和更高的吞吐量。 + +## 请求正文字段 + +在 `knn` 查询中提供向量字段,并在向量字段对象中指定其他请求字段: + +```json +"knn": { + "<vector_field>": { + "vector": [<vector_values>], + "k": <k_value>, + ... + } +} +``` + +顶级 `vector_field` 指定要对其运行搜索查询的向量字段。下表列出了所有支持的请求字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`vector` | Array of floats or bytes | 必需 | 用于向量搜索的查询向量。向量元素的数据类型必须与搜索的 [`knn_vector` 字段](/mappings/supported-field-types/knn-vector/)中索引的向量数据类型匹配。 +`k` | Integer | 可选 | 要返回的最近邻数量。有效值在 [1, 10,000] 范围内。如果未指定 `max_distance` 或 `min_score`,则为必需。 +`max_distance` | Float | 可选 | 搜索结果的最大距离阈值。只能指定 `k`、`max_distance` 或 `min_score` 中的一个。有关更多信息,请参阅 [Radial search](/vector-search/specialized-operations/radial-search-knn/)。 +`min_score` | Float | 可选 | 搜索结果的最小分数阈值。只能指定 `k`、`max_distance` 或 `min_score` 中的一个。有关更多信息,请参阅 [Radial search](/vector-search/specialized-operations/radial-search-knn/)。 +`filter` | Object | 可选 | 应用于 k-NN 搜索的过滤器。有关更多信息,请参阅 [Vector search with filters](/vector-search/filter-search-knn/)。**重要**:过滤器只能与 `faiss` 或 `lucene` 引擎一起使用。 +`method_parameters` | Object | 可选 | 用于微调搜索的附加参数:<br>- `ef_search`(Integer):要检查的向量数量(用于 `hnsw` 方法)<br>- `nprobes`(Integer):要检查的桶数量(用于 `ivf` 方法)。有关更多信息,请参阅[在查询中指定方法参数](#在查询中指定方法参数)。 +`rescore` | Object or Boolean | 可选 | 用于配置重新评分功能的参数:<br>- `oversample_factor`(Float):控制在重新评分之前检索多少候选向量。有效值在 `[1.0, 100.0]` 范围内。对于 `in_memory` 模式的字段,默认值为 `false`(不重新评分),对于 `on_disk` 模式的字段启用(使用动态值)。在 `on_disk` 模式下,默认的 `oversample_factor` 由 `compression_level` 确定。有关更多信息,请参阅[压缩级别表](/mappings/supported-field-types/knn-memory-optimized/#rescoring-quantized-results-to-full-precision)。要显式启用默认 `oversample_factor` 为 `1.0` 的重新评分,请将 `rescore` 设置为 `true`。有关更多信息,请参阅[重新评分结果](#重新评分结果)。 +`expand_nested_docs` | Boolean | 可选 | 当为 `true` 时,检索每个父文档中所有嵌套字段文档的分数。与嵌套查询一起使用。有关更多信息,请参阅 [Vector search with nested fields](/vector-search/specialized-operations/nested-search-knn/)。 + +## 示例请求 + +```json +GET /my-vector-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [1.5, 2.5], + "k": 3 + } + } + } +} +``` + +## 示例请求:嵌套字段 + +```json +GET /my-vector-index/_search +{ + "_source": false, + "query": { + "nested": { + "path": "nested_field", + "query": { + "knn": { + "nested_field.my_vector": { + "vector": [1,1,1], + "k": 2, + "expand_nested_docs": true + } + } + }, + "inner_hits": { + "_source": false, + "fields":["nested_field.color"] + }, + "score_mode": "max" + } + } +} +``` + +## 示例请求:使用 max_distance 的径向搜索 + +以下示例展示了使用 `max_distance` 执行的径向搜索: + +```json +GET /my-vector-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [ + 7.1, + 8.3 + ], + "max_distance": 2 + } + } + } +} +``` + +## 示例请求:使用 min_score 的径向搜索 + +以下示例展示了使用 `min_score` 执行的径向搜索: + +```json +GET /my-vector-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [7.1, 8.3], + "min_score": 0.95 + } + } + } +} +``` + +## 在查询中指定方法参数 + +您可以在搜索请求中提供 `method_parameters`: + +```json +GET /my-vector-index/_search +{ + "size": 2, + "query": { + "knn": { + "target-field": { + "vector": [2, 3, 5, 6], + "k": 2, + "method_parameters" : { + "ef_search": 100 + } + } + } + } +} +``` + +这些参数取决于用于创建索引的引擎和方法组合。以下部分提供有关支持的 `method_parameters` 的信息。 + +### ef_search + +在搜索使用 `hnsw` 方法创建的索引时,可以提供 `ef_search` 参数。`ef_search` 参数指定要检查的向量数量,以找到前 k 个最近邻。较高的 `ef_search` 值会提高召回率,但会增加搜索延迟。该值必须为正数。 + +下表提供了支持引擎的 `ef_search` 参数信息。 + +引擎 | 径向查询支持 | 注释 +:--- | :--- | :--- +`nmslib`(已弃用) | 否 | 如果查询中存在 `ef_search`,它会覆盖 `index.knn.algo_param.ef_search` 索引设置。 +`faiss` | 是 | 如果查询中存在 `ef_search`,它会覆盖 `index.knn.algo_param.ef_search` 索引设置。 +`lucene` | 否 | 创建搜索查询时,必须指定 `k`。如果同时提供 `k` 和 `ef_search`,则将较大的值传递给引擎。如果 `ef_search` 大于 `k`,可以提供 `size` 参数将最终结果数量限制为 `k`。 + +<!-- vale off --> +### nprobes +<!-- vale on --> + +在搜索使用 `ivf` 方法创建的索引时,可以提供 `nprobes` 参数。`nprobes` 参数指定要检查的桶数量,以找到前 k 个最近邻。较高的 `nprobes` 值会提高召回率,但会增加搜索延迟。该值必须为正数。 + +下表提供了支持引擎的 `nprobes` 参数信息。 + +引擎 | 注释 +:--- | :--- +`faiss` | 如果查询中存在 `nprobes`,它会覆盖创建索引时提供的值。 + +## 重新评分结果 + +您可以通过提供 `ef_search` 和 `oversample_factor` 参数来微调搜索。 + +`oversample_factor` 参数控制搜索在对候选向量进行排名之前过采样的倍数。使用较高的过采样因子意味着在排名之前会考虑更多候选项,从而提高准确性,但也会增加搜索时间。在选择 `oversample_factor` 值时,请考虑准确性和效率之间的权衡。例如,将 `oversample_factor` 设置为 `2.0` 将使排名阶段考虑的候选项数量加倍,这可能有助于获得更好的结果。 + +以下请求指定了 `ef_search` 和 `oversample_factor` 参数: + +```json +GET /my-vector-index/_search +{ + "size": 2, + "query": { + "knn": { + "my_vector_field": { + "vector": [1.5, 5.5, 1.5, 5.5, 1.5, 5.5, 1.5, 5.5], + "k": 10, + "method_parameters": { + "ef_search": 10 + }, + "rescore": { + "oversample_factor": 10.0 + } + } + } + } +} +``` + +## 后续步骤 + +- [k-NN vector](/mappings/supported-field-types/knn-vector/) +- [Rescoring quantized results to full precision](/mappings/supported-field-types/knn-memory-optimized/#rescoring-quantized-results-to-full-precision) diff --git a/i18n/zh/query-dsl/specialized/k-nn/k-nn-explain.md b/i18n/zh/query-dsl/specialized/k-nn/k-nn-explain.md new file mode 100644 index 00000000..53a75116 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/k-nn/k-nn-explain.md @@ -0,0 +1,645 @@ +--- +title: k-NN 查询解释 +--- + +# k-NN 查询解释 +<Badge type="tip" text="3.0 版本引入" /> + +您可以提供 `explain` 参数来了解 `knn` 查询中分数的计算、归一化和组合方式。启用后,它会为每个搜索结果提供有关评分过程的详细信息。这包括揭示使用的分数归一化技术、不同分数的组合方式以及各个子查询分数的计算。这种全面的洞察使理解和优化 `knn` 查询结果变得更加容易。有关 `explain` 的更多信息,请参阅 [Explain API](/api-reference/explain)。 + +::: danger WARNING +`explain` 在资源和时间方面都是昂贵的操作。对于生产集群,我们建议仅在故障排除时谨慎使用它。 +::: + +在使用 Faiss 引擎运行完整的 `knn` 查询时,可以使用以下语法在 URL 中提供 `explain` 参数: + +```json +GET {index}/_search?explain=true +POST {index}/_search?explain=true +``` + +::: info NOTE +使用 Lucene 引擎的所有类型查询的 k-NN 搜索的 `explain` 不会像 Faiss 引擎那样返回详细解释。 +::: + +`explain` 参数适用于以下使用 Faiss 引擎的 k-NN 搜索类型: + +- [近似 k-NN 搜索](/vector-search/vector-search-techniques/approximate-knn/) +- 带有[精确搜索](/vector-search/vector-search-techniques/knn-score-script/)的近似 k-NN 搜索 +- [基于磁盘的搜索](/vector-search/optimizing-storage/disk-based-vector-search/) +- [带有高效过滤的 k-NN 搜索](/vector-search/filter-search-knn/efficient-knn-filtering/) +- [径向搜索](/vector-search/specialized-operations/radial-search-knn/) +- 带有 `term` 查询的 k-NN 搜索 + +::: info NOTE +带有嵌套字段的 k-NN 搜索的 `explain` 不会像其他搜索那样返回详细解释。 +::: + +您可以将 `explain` 参数作为查询参数提供: + +```json +GET my-knn-index/_search?explain=true +{ + "query": { + "knn": { + "my_vector": { + "vector": [2, 3, 5, 7], + "k": 2 + } + } + } +} +``` + +或者,您可以在请求正文中提供 `explain` 参数: + +```json +GET my-knn-index/_search +{ + "query": { + "knn": { + "my_vector": { + "vector": [2, 3, 5, 7], + "k": 2 + } + } + }, + "explain": true +} +``` + +## 示例:近似 k-NN 搜索 + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took": 216038, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 88.4, + "hits": [ + { + "_shard": "[my-knn-index-1][0]", + "_node": "VHcyav6OTsmXdpsttX2Yug", + "_index": "my-knn-index-1", + "_id": "5", + "_score": 88.4, + "_source": { + "my_vector1": [ + 2.5, + 3.5, + 5.5, + 7.4 + ], + "price": 8.9 + }, + "_explanation": { + "value": 88.4, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 88.4, + "description": "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details": [ + { + "value": -87.4, + "description": "rawScore, returned from FAISS library", + "details": [] + } + ] + } + ] + } + }, + { + "_shard": "[my-knn-index-1][0]", + "_node": "VHcyav6OTsmXdpsttX2Yug", + "_index": "my-knn-index-1", + "_id": "2", + "_score": 84.7, + "_source": { + "my_vector1": [ + 2.5, + 3.5, + 5.6, + 6.7 + ], + "price": 5.5 + }, + "_explanation": { + "value": 84.7, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 84.7, + "description": "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details": [ + { + "value": -83.7, + "description": "rawScore, returned from FAISS library", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` +</details> + +## 示例:带有精确搜索的近似 k-NN 搜索 + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took": 87, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 84.7, + "hits": [ + { + "_shard": "[my-knn-index-1][0]", + "_node": "MQVux8dZRWeznuEYKhMq0Q", + "_index": "my-knn-index-1", + "_id": "7", + "_score": 84.7, + "_source": { + "my_vector2": [ + 2.5, + 3.5, + 5.6, + 6.7 + ], + "price": 5.5 + }, + "_explanation": { + "value": 84.7, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 84.7, + "description": "the type of knn search executed at leaf was Exact with spaceType = INNER_PRODUCT, vectorDataType = FLOAT, queryVector = [2.0, 3.0, 5.0, 6.0]", + "details": [] + } + ] + } + }, + { + "_shard": "[my-knn-index-1][0]", + "_node": "MQVux8dZRWeznuEYKhMq0Q", + "_index": "my-knn-index-1", + "_id": "8", + "_score": 82.2, + "_source": { + "my_vector2": [ + 4.5, + 5.5, + 6.7, + 3.7 + ], + "price": 4.4 + }, + "_explanation": { + "value": 82.2, + "description": "the type of knn search executed was Approximate-NN", + "details": [ + { + "value": 82.2, + "description": "the type of knn search executed at leaf was Exact with spaceType = INNER_PRODUCT, vectorDataType = FLOAT, queryVector = [2.0, 3.0, 5.0, 6.0]", + "details": [] + } + ] + } + } + ] + } +``` +</details> + +## 示例:基于磁盘的搜索 + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took" : 4, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 381.0, + "hits" : [ + { + "_shard" : "[my-vector-index][0]", + "_node" : "pLaiqZftTX-MVSKdQSu7ow", + "_index" : "my-vector-index", + "_id" : "9", + "_score" : 381.0, + "_source" : { + "my_vector_field" : [ + 9.5, + 9.5, + 9.5, + 9.5, + 9.5, + 9.5, + 9.5, + 9.5 + ], + "price" : 8.9 + }, + "_explanation" : { + "value" : 381.0, + "description" : "the type of knn search executed was Disk-based and the first pass k was 100 with vector dimension of 8, over sampling factor of 5.0, shard level rescoring enabled", + "details" : [ + { + "value" : 381.0, + "description" : "the type of knn search executed at leaf was Approximate-NN with spaceType = HAMMING, vectorDataType = FLOAT, queryVector = [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]", + "details" : [ ] + } + ] + } + } + ] + } +} +``` +</details> + +## 示例:带有高效过滤的 k-NN 搜索 + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took" : 51, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.8620689, + "hits" : [ + { + "_shard" : "[products-shirts][0]", + "_node" : "9epk8WoFT8yvnUI0tAaJgQ", + "_index" : "products-shirts", + "_id" : "8", + "_score" : 0.8620689, + "_source" : { + "item_vector" : [ + 2.4, + 4.0, + 3.0 + ], + "size" : "small", + "rating" : 8 + }, + "_explanation" : { + "value" : 0.8620689, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 0.8620689, + "description" : "the type of knn search executed at leaf was Exact since filteredIds = 2 is less than or equal to K = 10 with spaceType = L2, vectorDataType = FLOAT, queryVector = [2.0, 4.0, 3.0]", + "details" : [ ] + } + ] + } + }, + { + "_shard" : "[products-shirts][0]", + "_node" : "9epk8WoFT8yvnUI0tAaJgQ", + "_index" : "products-shirts", + "_id" : "6", + "_score" : 0.029691212, + "_source" : { + "item_vector" : [ + 6.4, + 3.4, + 6.6 + ], + "size" : "small", + "rating" : 9 + }, + "_explanation" : { + "value" : 0.029691212, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 0.029691212, + "description" : "the type of knn search executed at leaf was Exact since filteredIds = 2 is less than or equal to K = 10 with spaceType = L2, vectorDataType = FLOAT, queryVector = [2.0, 4.0, 3.0]", + "details" : [ ] + } + ] + } + } + ] + } +} +``` +</details> + +## 示例:径向搜索 + +```json +GET my-knn-index/_search?explain=true +{ + "query": { + "knn": { + "my_vector": { + "vector": [7.1, 8.3], + "max_distance": 2 + } + } + } +} +``` + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took" : 376529, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 0.98039204, + "hits" : [ + { + "_shard" : "[knn-index-test][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "knn-index-test", + "_id" : "1", + "_score" : 0.98039204, + "_source" : { + "my_vector" : [ + 7.0, + 8.2 + ], + "price" : 4.4 + }, + "_explanation" : { + "value" : 0.98039204, + "description" : "the type of knn search executed was Radial with the radius of 2.0", + "details" : [ + { + "value" : 0.98039204, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = l2 where score is computed as `1 / (1 + rawScore)` from:", + "details" : [ + { + "value" : 0.020000057, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + } + }, + { + "_shard" : "[knn-index-test][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "knn-index-test", + "_id" : "3", + "_score" : 0.9615384, + "_source" : { + "my_vector" : [ + 7.3, + 8.3 + ], + "price" : 19.1 + }, + "_explanation" : { + "value" : 0.9615384, + "description" : "the type of knn search executed was Radial with the radius of 2.0", + "details" : [ + { + "value" : 0.9615384, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = l2 where score is computed as `1 / (1 + rawScore)` from:", + "details" : [ + { + "value" : 0.040000115, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + } + } + ] + } +} + +``` +</details> + +## 示例:带有 term 查询的 k-NN 搜索 + +```json +GET my-knn-index/_search?explain=true +{ + "query": { + "bool": { + "should": [ + { + "knn": { + "my_vector2": { // vector field name + "vector": [2, 3, 5, 6], + "k": 2 + } + } + }, + { + "term": { + "price": "4.4" + } + } + ] + } + } +} +``` + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took" : 51, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 84.7, + "hits" : [ + { + "_shard" : "[my-knn-index-1][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "my-knn-index-1", + "_id" : "7", + "_score" : 84.7, + "_source" : { + "my_vector2" : [ + 2.5, + 3.5, + 5.6, + 6.7 + ], + "price" : 5.5 + }, + "_explanation" : { + "value" : 84.7, + "description" : "sum of:", + "details" : [ + { + "value" : 84.7, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 84.7, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details" : [ + { + "value" : -83.7, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + } + ] + } + }, + { + "_shard" : "[my-knn-index-1][0]", + "_node" : "c9b4aPe4QGO8eOtb8P5D3g", + "_index" : "my-knn-index-1", + "_id" : "8", + "_score" : 83.2, + "_source" : { + "my_vector2" : [ + 4.5, + 5.5, + 6.7, + 3.7 + ], + "price" : 4.4 + }, + "_explanation" : { + "value" : 83.2, + "description" : "sum of:", + "details" : [ + { + "value" : 82.2, + "description" : "the type of knn search executed was Approximate-NN", + "details" : [ + { + "value" : 82.2, + "description" : "the type of knn search executed at leaf was Approximate-NN with vectorDataType = FLOAT, spaceType = innerproduct where score is computed as `-rawScore + 1` from:", + "details" : [ + { + "value" : -81.2, + "description" : "rawScore, returned from FAISS library", + "details" : [ ] + } + ] + } + ] + }, + { + "value" : 1.0, + "description" : "price:[1082969293 TO 1082969293]", + "details" : [ ] + } + ] + } + } + ] + } +} +``` + +</details> + +## 响应正文字段 + +字段 | 描述 +:--- | :--- +`explanation` | `explanation` 对象包含以下字段:<br> - `value`:包含计算结果。<br> - `description`:解释执行了什么类型的计算。对于分数归一化,`description` 字段中的信息包括用于归一化或组合的技术以及相应的分数。<br> - `details`:显示执行的任何子计算。 diff --git a/i18n/zh/query-dsl/specialized/more-like-this.md b/i18n/zh/query-dsl/specialized/more-like-this.md new file mode 100644 index 00000000..6b64cb65 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/more-like-this.md @@ -0,0 +1,281 @@ +--- +title: More like this +--- + +# More like this + +使用 `more_like_this` 查询查找与一个或多个给定文档相似的文档。这对于推荐引擎、内容发现和识别数据集中的相关项目非常有用。 + +`more_like_this` 查询分析输入文档或文本,并选择最能表征它们的词项。然后它搜索包含这些重要词项的其他文档。 + +## 先决条件 + +在使用 `more_like_this` 查询之前,请确保您定位的字段已被索引,并且其数据类型是 [`text`](/mappings/supported-field-types/text/) 或 [`keyword`](/mappings/supported-field-types/keyword/)。 + +如果您在 `like` 部分引用文档,OpenSearch 需要访问其内容。这通常通过默认启用的 `_source` 字段完成。如果禁用了 `_source`,您必须单独存储字段或将其配置为保存 [`term_vector`](/mappings/mapping-parameters/term-vector/) 数据。 + +::: info NOTE +在索引文档时保存 [`term_vector`](/mappings/mapping-parameters/term-vector/) 信息可以大大加速 `more_like_this` 查询,因为引擎可以直接检索重要词项,而无需在查询时重新分析字段文本。 +::: + +## 示例:无词项向量优化 + +使用以下映射创建名为 `articles-basic` 的索引: + +```json +PUT /articles-basic +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "content": { "type": "text" } + } + } +} +``` + +添加示例文档: + +```json +POST /articles-basic/_bulk +{ "index": { "_id": 1 }} +{ "title": "Exploring the Sahara Desert", "content": "Sand dunes and vast landscapes." } +{ "index": { "_id": 2 }} +{ "title": "Amazon Rainforest Tour", "content": "Dense jungle and exotic wildlife." } +{ "index": { "_id": 3 }} +{ "title": "Mountain Adventures", "content": "Snowy peaks and hiking trails." } +``` + +使用以下请求查询: + +```json +GET /articles-basic/_search +{ + "query": { + "more_like_this": { + "fields": ["content"], + "like": "jungle wildlife", + "min_term_freq": 1, + "min_doc_freq": 1 + } + } +} +``` + +`more_like_this` 查询在 `content` 字段中搜索词项 `jungle` 和 `wildlife`,仅匹配一个文档: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.9616582, + "hits": [ + { + "_index": "articles-basic", + "_id": "2", + "_score": 1.9616582, + "_source": { + "title": "Amazon Rainforest Tour", + "content": "Dense jungle and exotic wildlife." + } + } + ] + } +} +``` + +## 示例:词项向量优化 + +使用以下映射创建名为 `articles-optimized` 的索引: + +```json +PUT /articles-optimized +{ + "mappings": { + "properties": { + "name": { + "type": "text", + "term_vector": "with_positions_offsets" + }, + "alias": { + "type": "text", + "term_vector": "with_positions_offsets" + }, + "quote": { + "type": "text", + "term_vector": "with_positions_offsets" + } + } + } +} +``` + +将示例文档插入优化的索引: + +```json +POST /articles-optimized/_bulk +{ "index": { "_id": "a1" } } +{ "name": "Diana", "alias": "Wonder Woman", "quote": "Justice will come when it is deserved." } +{ "index": { "_id": "a2" } } +{ "name": "Clark", "alias": "Superman", "quote": "Even in the darkest times, hope cuts through." } +{ "index": { "_id": "a3" } } +{ "name": "Bruce", "alias": "Batman", "quote": "I am vengeance. I am the night. I am Batman!" } +``` + +查找 `quote` 字段包含与"dark"和"night"相似词项的文档: + +```json +GET /articles-optimized/_search +{ + "query": { + "more_like_this": { + "fields": ["quote"], + "like": "dark night", + "min_term_freq": 1, + "min_doc_freq": 1 + } + } +} +``` + +`more_like_this` 查询搜索词项 `dark` 和 `night` 并返回以下命中: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.2363393, + "hits": [ + { + "_index": "articles-optimized", + "_id": "a3", + "_score": 1.2363393, + "_source": { + "name": "Bruce", + "alias": "Batman", + "quote": "I am vengeance. I am the night. I am Batman!" + } + } + ] + } +} +``` + +## 示例:使用多个文档和文本输入 + +`more_like_this` 查询允许您在 `like` 参数中提供多个来源。您可以将自由文本与索引中的文档组合。如果您希望搜索结合来自多个示例的相关性信号,这很有用。 + +在以下示例中,直接提供了一个自定义文档。此外,还包括来自 `heroes` 索引的 ID 为 `5` 的现有文档: + +```json +GET /articles-optimized/_search +{ + "query": { + "more_like_this": { + "fields": ["name", "alias"], + "like": [ + { + "doc": { + "name": "Diana", + "alias": "Wonder Woman", + "quote": "Courage is not the absence of fear, but the triumph over it." + } + }, + { + "_index": "heroes", + "_id": "5" + } + ], + "min_term_freq": 1, + "min_doc_freq": 1, + "max_query_terms": 25 + } + } +} +``` + +返回的结果包含与查询中提供的 `name` 和 `alias` 字段最相似的文章: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 2.140194, + "hits": [ + { + "_index": "articles-optimized", + "_id": "a1", + "_score": 2.140194, + "_source": { + "name": "Diana", + "alias": "Wonder Woman", + "quote": "Justice will come when it is deserved." + } + }, + { + "_index": "articles-optimized", + "_id": "a2", + "_score": 1.1596459, + "_source": { + "name": "Clark", + "alias": "Superman", + "quote": "Even in the darkest times, hope cuts through." + } + } + ] + } +} +``` + +::: info NOTE +当您想基于尚未完全索引的新概念提升结果,同时又想结合现有索引文档的知识时,请使用此模式。 +::: + +# 参数 + +`more_like_this` 查询唯一必需的参数是 `like`。其余参数有默认值,但允许微调。以下是主要参数类别。 + +## 文档输入参数 + +下表指定文档输入参数。 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `like`| 必需| Array of strings or objects | 定义要查找相似文档的文本或文档。您可以输入自由文本、索引中的真实文档或人工文档。除非被覆盖,否则与字段关联的分析器会处理文本。 | +| `unlike`| 可选| Array of strings or objects | 提供其词项应*排除*在影响查询之外的文本或文档。对于指定负面示例很有用。| +| `fields`| 可选| Array of strings| 列出分析文本时要使用的字段。如果未指定,则使用所有字段。 | + +## 词项选择参数 + +| 参数 | 必需/可选 | 数据类型| 描述| +| :--- | :--- | :--- | :--- | +| `max_query_terms` | 可选| Integer| 设置从输入中选择的最大词项数。较高的值会增加精度但会减慢执行速度。默认值为 `25`。 | +| `min_term_freq` | 可选| Integer| 在输入中出现次数少于此值的词项将被忽略。默认值为 `2`。| +| `min_doc_freq`| 可选| Integer| 出现在少于此值文档中的词项将被忽略。默认值为 `5`。| +| `max_doc_freq`| 可选| Integer| 出现在超过此限制的文档中的词项将被忽略。对于避免非常常见的单词很有用。默认值为无限制 (2<sup>31</sup> - 1)。 | +| `min_word_length` | 可选| Integer| 忽略短于此值的单词。默认值为 `0`。| +| `max_word_length` | 可选| Integer| 忽略长于此值的单词。默认值为无限制。 | +| `stop_words`| 可选| Array of strings | 定义选择词项时完全忽略的单词列表。| +| `analyzer`| 可选| String | 用于处理输入文本的自定义分析器。默认为 `fields` 中列出的第一个字段的分析器。| + +## 查询形成参数 + +| 参数 | 必需/可选 | 数据类型 | 描述 | +| :--- | :--- | :--- | :--- | +| `minimum_should_match`| 可选 | String | 指定最终查询中必须匹配的最小词项数。该值可以是百分比或固定数字。有助于微调召回率和精确度之间的平衡。默认值为 `30%` | +| `fail_on_unsupported_field` | 可选 | Boolean | 确定如果目标字段之一不是兼容类型(`text` 或 `keyword`)是否抛出错误。设置为 `false` 以静默跳过不支持的字段。默认值为 `true`。 | +| `boost_terms` | 可选 | Float | 根据词频-逆文档频率 (TF-IDF) 权重对选定的词项应用提升。任何大于 `0` 的值都会使用指定的因子激活词项提升。默认值为 `0`。 | +| `include` | 可选 | Boolean | 如果为 `true`,则 `like` 中提供的源文档将包含在结果命中中。默认值为 `false`。 | +| `boost` | 可选 | Float | 乘以整个 `more_like_this` 查询的相关性分数。默认值为 `1.0`。 | diff --git a/i18n/zh/query-dsl/specialized/neural-sparse/index.md b/i18n/zh/query-dsl/specialized/neural-sparse/index.md new file mode 100644 index 00000000..e9607d7c --- /dev/null +++ b/i18n/zh/query-dsl/specialized/neural-sparse/index.md @@ -0,0 +1,282 @@ +--- +title: Neural sparse +--- + +# Neural sparse 查询 +<Badge type="tip" text="2.11 版本引入" /> + +`neural_sparse` 查询对向量字段执行 neural sparse 功能的搜索。您可以在两种类型的向量字段上运行此查询: + +- **`rank_features` 字段**:用于传统的 [neural sparse 搜索](/vector-search/ai-search/neural-sparse-search/) +- **`sparse_vector` 字段**:用于 [neural sparse ANN 搜索](/vector-search/ai-search/neural-sparse-ann/) + +## Neural sparse 搜索 + +在 `rank_features` 字段上使用 neural sparse 搜索,以利用倒排索引效率进行传统的稀疏向量搜索。 + +您可以使用原始稀疏向量或文本运行 neural sparse 搜索。文本可以由内置分析器或分词器模型进行分词。 + +### 使用原始稀疏向量 + +直接提供稀疏向量嵌入进行匹配: + +```json +"neural_sparse": { + "<rank_features_field>": { + "query_tokens": { + "<token>": <weight>, + ... + } + } +} +``` + +有关更多信息,请参阅 [Neural sparse search using raw vectors](/vector-search/ai-search/neural-sparse-with-raw-vectors/)。 + +### 使用内置分析器处理文本 + +提供文本以使用内置深度学习模型分析器进行分词: + +```json +"neural_sparse": { + "<rank_features_field>": { + "query_text": "<input text>", + "analyzer": "bert-uncased" + } +} +``` + +### 使用自定义模型处理文本 + +提供文本以使用自定义分词器模型进行分词: + +```json +"neural_sparse": { + "<rank_features_field>": { + "query_text": "<input text>", + "model_id": "<model ID>" + } +} +``` + +有关更多信息,请参阅 [Generating sparse vector embeddings automatically](/vector-search/ai-search/neural-sparse-with-pipelines/)。 + +## Neural sparse ANN 搜索 +<Badge type="tip" text="3.3 版本引入" /> + +在 `sparse_vector` 字段上使用 neural sparse ANN 搜索以获得更好的查询性能和高召回率。有关更多信息,请参阅 [Neural sparse ANN search](/vector-search/ai-search/neural-sparse-ann/)。 + +Neural sparse ANN 搜索支持两种引擎:Lucene 引擎和原生引擎。您可以通过设置 `method.engine` 在字段映射中选择引擎。两种引擎的查询语法和所有支持的查询参数都相同。有关更多信息,请参阅 [Engines](/vector-search/ai-search/neural-sparse-ann/#engines)。 + +您可以使用原始稀疏向量或文本运行 neural sparse 搜索。 + +### 使用原始稀疏向量 + +```json +"neural_sparse": { + "<sparse_vector_field>": { + "query_tokens": { + "<token>": <weight>, + ... + }, + "method_parameters": { + "top_n": 10, + "heap_factor": 1.0, + "k": 10 + } + } +} +``` + +### 使用模型处理文本 + +```json +"neural_sparse": { + "<sparse_vector_field>": { + "query_text": "<input text>", + "model_id": "<model ID>", + "method_parameters": { + "top_n": 10, + "heap_factor": 1.0, + "k": 10 + } + } +} +``` + +## 请求正文字段 + +顶级字段名称指定要对其运行搜索查询的向量字段。您必须指定 `query_text` 或 `query_tokens` 来定义输入。 + +### 通用字段 + +这些字段同时支持 `rank_features` 和 `sparse_vector` 字段类型。 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:--- |:--- |:--- |:--- | +| `query_text` | String | 可选 | 要转换为稀疏向量嵌入的查询文本。必须指定 `query_text` 或 `query_tokens`。 | +| `query_tokens` | Map of token (string) to weight (float) | 可选 | 以词元及其权重形式表示的原始稀疏向量。用作 `query_text` 的替代方案,用于直接向量输入。必须指定 `query_text` 或 `query_tokens`。 | +| `model_id` | String | 可选 | 与 `query_text` 一起使用。用于从查询文本生成向量嵌入的稀疏编码模型(用于双编码器模式)或分词器(用于仅文档模式)的 ID。模型/分词器必须在 OpenSearch 中部署后才能用于 neural sparse 搜索。有关更多信息,请参阅 [Using custom models within OpenSearch](/ml-commons-plugin/using-ml-models) 和 [Generating sparse vector embeddings automatically](/vector-search/ai-search/neural-sparse-with-pipelines/)。有关在 neural sparse 查询中设置默认模型 ID 的信息,请参阅 [`neural_query_enricher`](/search-plugins/search-pipelines/neural-query-enricher)。不能与 `analyzer` 同时指定。 | +| `max_token_score` | Float | 可选 |(已弃用)此参数自 OpenSearch 2.12 起已弃用。它仅用于向后兼容,不再影响功能。该参数仍可在请求中提供,但其值没有任何影响。以前用作词汇表中所有词元分数的理论上限。| + +### 仅适用于 rank_features 的字段 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:--- |:--- |:--- |:--- | +| `analyzer` | String | 可选 | 与 `query_text` 一起使用。指定用于分词查询文本的内置深度学习模型分析器。有效值为 `bert-uncased` 和 `mbert-uncased`。默认值为 `bert-uncased`。如果既未指定 `model_id` 也未指定 `analyzer`,则使用默认分析器(`bert-uncased`)对文本进行分词。不能与 `model_id` 同时指定。有关更多信息,请参阅 [DL model analyzers](/analyzers/supported-analyzers/dl-model-analyzers)。 | + +### 仅适用于 sparse_vector 的字段 + +| 字段 | 数据类型 | 必需/可选 | 描述 | +|:--- |:--- |:--- |:--- | +| `method_parameters.top_n` | Integer | 可选 | 指定为近似稀疏查询保留的具有最高权重的查询词元数量。 | +| `method_parameters.heap_factor` | Float | 可选 | 控制召回率和性能之间的权衡。较高的值会增加召回率但降低查询速度;较低的值会降低召回率但提高查询速度。 | +| `method_parameters.k` | Integer | 可选 | 指定 [neural sparse ANN 搜索](/vector-search/ai-search/neural-sparse-ann/)返回的最高结果数量。 | +| `method_parameters.filter` | Object | 可选 | 对查询结果应用过滤器。过滤器的应用方式取决于为字段配置的引擎。请参阅 [Filtering in neural sparse ANN search](/vector-search/filter-search-knn/filtering-in-sparse-search/)。 | + +::: info NOTE +如果过滤器匹配的文档数少于 `k`,两种引擎都会对过滤后的文档运行精确搜索。超过该点后,Lucene 引擎在近似检索后应用过滤器,因此选择性过滤器可能产生少于 `k` 个结果,而原生引擎在过滤集内进行检索,可以返回完整的 `k` 个结果。这种差异由字段映射中配置的引擎决定。 +::: + +## 示例 + +以下示例演示了使用 `neural_sparse` 查询。 + +### 在 rank_features 字段上进行 neural sparse 搜索 + +您可以在 `rank_features` 字段上使用分析器或模型分词的文本或使用原始向量运行 neural sparse 搜索。 + +#### 使用分析器分词的文本 + +要使用分析器分词的文本运行搜索,请在请求中指定 `analyzer`。分析器必须与您在摄取时用于文本分析的模型兼容: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "analyzer": "bert-uncased" + } + } + } +} +``` + +有关更多信息,请参阅 [DL model analyzers](/analyzers/supported-analyzers/dl-model-analyzers)。 + +如果未指定分析器,则使用默认的 `bert-uncased` 分析器: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world" + } + } + } +} +``` + +#### 使用模型分词的文本 + +要使用分词器模型分词的文本进行搜索,请在请求中提供模型 ID: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": "aP2Q8ooBpBj3wT4HVS8a" + } + } + } +} +``` + +#### 使用原始向量 + +要使用稀疏向量进行搜索,请在 `query_tokens` 参数中提供稀疏向量: + +```json +GET my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_tokens": { + "hi" : 4.338913, + "planets" : 2.7755864, + "planet" : 5.0969057, + "mars" : 1.7405145, + "earth" : 2.6087382, + "hello" : 3.3210192 + } + } + } + } +} +``` + +### 在 sparse_vector 字段上进行 neural sparse ANN 搜索 + +您可以在 `sparse_vector` 字段上使用文本或原始向量运行 neural sparse ANN 搜索。 + +#### 使用文本 + +要使用自然语言进行搜索,请提供 `query_text` 和已部署的稀疏编码模型 ID: + +```json +GET sparse-vector-index/_search +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_text": "<input text>", + "model_id": "<model ID>", + "method_parameters": { + "k": 10, + "top_n": 10, + "heap_factor": 1.0 + } + } + } + } +} +``` + +#### 使用带有方法参数的原始向量 + +要使用预计算的稀疏向量进行搜索,请在 `query_tokens` 字段中提供向量: + +```json +GET sparse-vector-index/_search +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "1055": 5.5 + }, + "method_parameters": { + "heap_factor": 1.0, + "top_n": 10, + "k": 10 + } + } + } + } +} +``` + +## 后续步骤 + +- 有关 neural sparse 搜索的更多信息,请参阅 [Neural sparse search](/vector-search/ai-search/neural-sparse-search/)。 +- 有关 neural sparse ANN 搜索的更多信息,请参阅 [Neural sparse ANN search](/vector-search/ai-search/neural-sparse-ann/)。 +- 有关字段类型信息,请参阅 [Rank features](/mappings/supported-field-types/rank/) 和 [Sparse vector](/mappings/supported-field-types/sparse-vector/)。 +- 有关过滤 `neural_sparse` 查询结果的信息,请参阅 [Filtering in neural sparse ANN search](/vector-search/filter-search-knn/filtering-in-sparse-search/)。 diff --git a/i18n/zh/query-dsl/specialized/neural-sparse/neural-sparse-explain.md b/i18n/zh/query-dsl/specialized/neural-sparse/neural-sparse-explain.md new file mode 100644 index 00000000..c14d8111 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/neural-sparse/neural-sparse-explain.md @@ -0,0 +1,381 @@ +--- +title: Neural sparse ANN 解释 +--- + +# Neural sparse ANN 查询解释 +<Badge type="tip" text="3.5 版本引入" /> + +您可以提供 `explain` 参数来了解 neural sparse 近似最近邻 (ANN) 查询中分数的计算方式。启用后,它会为每个搜索结果提供有关评分过程的详细信息,包括查询词元剪枝、量化点积计算、量化重新缩放和过滤器应用。这种全面的洞察使理解和优化 neural sparse ANN 查询结果变得更加容易。有关 `explain` 的更多信息,请参阅 [Explain API](/api-reference/explain)。 + +::: danger WARNING +`explain` 在资源和时间方面都是昂贵的操作。对于生产集群,我们建议仅在故障排除时谨慎使用它。 +::: + +本页面上的示例和字段描述描述了 Lucene 引擎的解释输出,这是 `sparse_vector` 字段的默认引擎。原生引擎的解释报告查询词元剪枝和精确点积分数,不包括量化重新缩放组件。两种引擎都使用 `quantization_ceiling_ingest` 和 `quantization_ceiling_search` 映射参数将词元权重量化为 8 位,因此这两个参数对任一引擎都有意义。引擎仅在解释分解方面有所不同。有关引擎的更多信息,请参阅 [Engines](/vector-search/ai-search/neural-sparse-ann/#engines)。 + +::: info NOTE +解释仅对包含至少 `approximate_threshold` 个文档(默认为 `1000000`)的分段包含本页描述的 neural sparse ANN 组件。对较小分段的查询返回标准的 `rank_features` 解释。有关更多信息,请参阅 [Hybrid indexing](/vector-search/ai-search/neural-sparse-ann/#hybrid-indexing)。 +::: + +在运行 neural sparse ANN 查询时,可以使用以下语法在 URL 中提供 `explain` 参数: + +```json +GET {index}/_search?explain=true +POST {index}/_search?explain=true +``` + +`explain` 参数适用于以下类型的 neural sparse ANN 搜索: + +- 基本 neural sparse ANN 搜索 +- 带有过滤器的 neural sparse ANN 搜索 + +您可以将 `explain` 参数作为查询参数提供: + +```json +GET my-sparse-index/_search?explain=true +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "7001": 6.25, + "3509": 5.57 + }, + "method_parameters": { + "k": 5, + "top_n": 6 + } + } + } + } +} +``` + +或者,您可以在请求正文中提供 `explain` 参数: + +```json +GET my-sparse-index/_search +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "7001": 6.25, + "3509": 5.57 + }, + "method_parameters": { + "k": 5, + "top_n": 3 + } + } + } + }, + "explain": true +} +``` + +## 示例:基本 neural sparse ANN 搜索 + +```json +GET my-sparse-index/_search?explain=true +{ + "query": { + "neural_sparse": { + "sparse_embedding": { + "query_tokens": { + "13723": 0.75, + "9266": 0.61, + "2078": 0.35, + "2365": 0.41 + }, + "method_parameters": { + "k": 10, + "top_n": 6 + } + } + } + } +} +``` + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took": 15, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 16.059792, + "hits": [ + { + "_shard": "[my-sparse-index][0]", + "_node": "iId6ipt-SCWA-7vHLh981Q", + "_index": "my-sparse-index", + "_id": "1", + "_score": 16.059792, + "_source": { + "sparse_embedding": { + "13723": 3.16, + "9266": 2.85, + "2078": 1.09, + "2365": 0.22 + } + }, + "_explanation": { + "value": 16.059792, + "description": "sparse_ann score for doc 94830 in field 'sparse_embedding'", + "details": [ + { + "value": 6, + "description": "query token pruning: kept top 6 of 33 tokens", + "details": [] + }, + { + "value": 21756, + "description": "raw dot product score (quantized): 21756", + "details": [ + { + "value": 9494, + "description": "token '13723' contribution: query_weight=47 * doc_weight=202", + "details": [] + }, + { + "value": 7098, + "description": "token '9266' contribution: query_weight=39 * doc_weight=182", + "details": [] + }, + { + "value": 1540, + "description": "token '2078' contribution: query_weight=22 * doc_weight=70", + "details": [] + }, + { + "value": 364, + "description": "token '2365' contribution: query_weight=26 * doc_weight=14", + "details": [] + } + ] + }, + { + "value": 0.0007381776, + "description": "quantization rescaling: 1.0000 * 3.00 * 16.00 / 255 / 255 = 0.000738", + "details": [ + { + "value": 1, + "description": "original boost: 1.0000", + "details": [] + }, + { + "value": 3, + "description": "ceiling_ingest (quantization parameter): 3.00", + "details": [] + }, + { + "value": 16, + "description": "ceiling_search (quantization parameter): 16.00", + "details": [] + }, + { + "value": 255, + "description": "MAX_UNSIGNED_BYTE_VALUE: 255", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` +</details> + +## 示例:带有过滤器的 neural sparse ANN 搜索 + +```json +GET hotels-index/_search?explain=true +{ + "query": { + "neural_sparse": { + "name_embedding": { + "query_tokens": { + "7001": 6.25, + "3509": 5.57 + }, + "method_parameters": { + "k": 5, + "filter": { + "range": { + "rating": { + "gte": 8, + "lte": 10 + } + } + } + } + } + } + } +} +``` + +<details markdown="block"> + <summary> + 示例响应 + </summary> + +```json +{ + "took": 8, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 70.55404, + "hits": [ + { + "_shard": "[hotels-index][0]", + "_node": "iId6ipt-SCWA-7vHLh981Q", + "_index": "hotels-index", + "_id": "8", + "_score": 70.55404, + "_source": { + "parking": true, + "name": "Crystal Beach Resort", + "rating": 9, + "name_embedding": { + "3509": 5.5722017, + "6121": 6.5081306, + "7001": 6.25483 + } + }, + "_explanation": { + "value": 70.55404, + "description": "sparse_ann score for doc 7 in field 'name_embedding'", + "details": [ + { + "value": 2, + "description": "query token pruning: kept all 2 tokens (no pruning occurred)", + "details": [] + }, + { + "value": 17921, + "description": "raw dot product score (quantized): 17921", + "details": [ + { + "value": 10000, + "description": "token '7001' contribution: query_weight=100 * doc_weight=100", + "details": [] + }, + { + "value": 7921, + "description": "token '3509' contribution: query_weight=89 * doc_weight=89", + "details": [] + } + ] + }, + { + "value": 0.003936948, + "description": "quantization rescaling: 1.0000 * 16.00 * 16.00 / 255 / 255 = 0.003937", + "details": [ + { + "value": 1, + "description": "original boost: 1.0000", + "details": [] + }, + { + "value": 16, + "description": "ceiling_ingest (quantization parameter): 16.00", + "details": [] + }, + { + "value": 16, + "description": "ceiling_search (quantization parameter): 16.00", + "details": [] + }, + { + "value": 255, + "description": "MAX_UNSIGNED_BYTE_VALUE: 255", + "details": [] + } + ] + }, + { + "value": 1, + "description": "document passed filter with exact search mode (filter matched 4 documents <= k=5, all filtered documents scored exactly)", + "details": [ + { + "value": 1, + "description": "filter criteria: +ApproximateScoreQuery(originalQuery=IndexOrDocValuesQuery(indexQuery=rating:[8 TO 10], dvQuery=rating:[8 TO 10]), approximationQuery=Approximate(rating:[8 TO 10]))", + "details": [] + } + ] + } + ] + } + } + ] + } +} +``` +</details> + +## 响应正文字段 + +下表描述了解释响应中的字段。 + +字段 | 描述 +:--- | :--- +`explanation` | `explanation` 对象包含以下字段:<br> - `value`:包含计算结果。<br> - `description`:解释执行了什么类型的计算。<br> - `details`:显示执行的任何子计算。 + +### 解释组件 + +解释中的 `details` 数组根据 neural sparse ANN 评分过程包含以下组件。 + +组件 | 描述 +:--- | :--- +查询词元剪枝 | 显示根据 `top_n` 参数剪枝后保留的查询词元数量。如果未发生剪枝,则表示保留了所有词元。 +原始点积分数 | 重新缩放前的量化点积分数。包含嵌套详细信息,显示每个词元的贡献为 `query_weight * doc_weight`。 +量化重新缩放 |(仅限 Lucene 引擎)解释如何使用公式 `boost * ceiling_ingest * ceiling_search / 255 / 255` 将原始量化分数转换为最终浮点分数。包含计算中使用的每个参数的详细信息。 +过滤器解释 |(应用过滤器时)显示过滤条件和搜索模式。指示当过滤文档数量少于或等于 `k` 时是否使用了精确搜索模式。 + +### 量化参数 + +Neural sparse ANN 搜索使用无符号字节量化来减少内存使用并提高搜索性能。Lucene 引擎的量化重新缩放部分包含以下参数。原生引擎应用相同的量化但报告精确点积分数,因此此部分不会出现在其解释中。 + +参数 | 描述 +:--- | :--- +`original boost` | 应用于查询的提升值。默认值为 1.0。 +`ceiling_ingest` | 文档摄取期间使用的量化上限参数。 +`ceiling_search` | 搜索期间使用的量化上限参数。 +`MAX_UNSIGNED_BYTE_VALUE` | 无符号字节量化的最大值 (255)。 + +在摄取期间,浮点词元权重通过将每个权重除以 `ceiling_ingest` 并缩放到字节范围来转换为无符号字节 (0-255)。类似地,在搜索期间,查询词元权重使用 `ceiling_search` 进行量化。原始点积使用这些量化字节值计算。为了恢复近似原始分数,使用公式 `final_score = raw_quantized_score * boost * ceiling_ingest * ceiling_search / 255 / 255` 进行重新缩放。上限参数确定可以表示而不会被裁剪的最大权重值——超过上限的权重被限制为 255。 + +## 后续步骤 + +- 有关 neural sparse ANN 搜索的更多信息,请参阅 [Neural sparse ANN search](/vector-search/ai-search/neural-sparse-ann/)。 +- 有关 Explain API 的更多信息,请参阅 [Explain API](/api-reference/explain)。 +- 有关 neural sparse ANN 搜索中过滤的信息,请参阅 [Filtering in neural sparse ANN search](/vector-search/filter-search-knn/filtering-in-sparse-search/)。 diff --git a/i18n/zh/query-dsl/specialized/percolate.md b/i18n/zh/query-dsl/specialized/percolate.md new file mode 100644 index 00000000..5bdff0f9 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/percolate.md @@ -0,0 +1,796 @@ +--- +title: Percolate +--- + +# Percolate 查询 + +使用 `percolate` 查询查找与给定文档匹配的已保存查询。这个操作与常规搜索相反:不是查找与查询匹配的文档,而是查找与文档匹配的查询。`percolate` 查询通常用于警报、通知和反向搜索用例。 + +使用 `percolate` 查询时,请考虑以下关键点: + +- 您可以渗透内联提供的文档或从索引中获取现有文档。 +- 文档和存储的查询必须使用相同的字段名称和类型。 +- 您可以将渗透与过滤和评分结合使用来构建复杂的匹配系统。 +- `percolate` 查询被视为[昂贵查询](/query-dsl/#expensive-queries),仅在集群设置 `search.allow_expensive_queries` 设置为 `true`(默认)时才会运行。如果此设置为 `false`,OpenSearch 会拒绝 `percolate` 查询。 + +`percolate` 查询在各种实时匹配场景中非常有用。一些常见用例包括: + +- 用户注册对产品的兴趣,例如"当有新的 Apple 笔记本电脑时通知我"。当新产品文档被索引时,系统会找到所有具有匹配已保存查询的用户并向他们发送通知。 +- 求职者根据首选职位或地点保存查询,新的职位发布会与这些查询匹配以触发警报。 +- 传入的日志或事件数据会根据保存的安全规则或异常模式进行渗透。 +- 传入的新闻文章会与保存的主题配置文件进行匹配,以对其进行分类或将其传递给感兴趣的读者。 + +已保存的查询存储在 [`percolator` 字段](/mappings/supported-field-types/percolator/)中。当您运行 `percolate` 查询时,OpenSearch 将文档与已保存的查询进行比较,并返回每个匹配的查询,由其 `_id` 标识。如果启用了高亮显示,响应还包含文档中匹配的文本。如果渗透多个文档,`_percolator_document_slot` 字段标识每个查询匹配的文档。 + +## 示例 + +以下示例演示如何使用不同方法保存查询并针对它们测试文档。 + +### 创建用于存储已保存查询的索引 + +首先,创建一个索引并配置其 `mappings`,使用 [`percolator` 字段类型](/mappings/supported-field-types/percolator/)来存储已保存的查询: + +```json +PUT /my_percolator_index +{ + "mappings": { + "properties": { + "query": { + "type": "percolator" + }, + "title": { + "type": "text" + } + } + } +} +``` + +索引还必须映射已保存查询搜索的每个字段——在此示例中为 `title`。OpenSearch 使用这些映射来解析每个已保存的查询和渗透的文档。如果字段未映射,保存搜索该字段的查询将失败,并显示 `No field mapping can be found for the field with name [title]` 错误。 + +添加一个在 `title` 字段中匹配"apple"的查询: + +```json +POST /my_percolator_index/_doc/1 +{ + "query": { + "match": { + "title": "apple" + } + } +} +``` + +添加一个在 `title` 字段中匹配"banana"的查询: + +```json +POST /my_percolator_index/_doc/2 +{ + "query": { + "match": { + "title": "banana" + } + } +} +``` + +### 渗透内联文档 + +针对已保存的查询测试内联文档: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "document": { + "title": "Fresh Apple Harvest" + } + } + } +} +``` + +响应提供在 `title` 字段中搜索包含单词"apple"的文档的已保存查询,由 `_id`: `1` 标识: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + } + } + ] + } +} +``` + +### 在过滤器上下文中渗透 + +默认情况下,OpenSearch 为每个匹配的查询计算相关性分数。是否保存的查询匹配通常可以仅从其提取的词项中决定,但评分需要对每个候选查询针对文档进行完整评估。如果不需要分数,请将 `percolate` 查询包装在 `constant_score` 查询中或 `bool` 查询的 `filter` 子句中: + +```json +POST /my_percolator_index/_search +{ + "query": { + "constant_score": { + "filter": { + "percolate": { + "field": "query", + "document": { + "title": "Fresh Apple Harvest" + } + } + } + } + } +} +``` + +相同的查询匹配,但每个命中都获得 `1.0` 的常量分数: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 1.0, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + } + } + ] + } +} +``` + +::: info NOTE +查询缓存永远不会存储 `percolate` 查询或任何包含它的复合查询,因为这些查询使用大量内存。 +::: + +### 渗透多个文档 + +要在同一查询中测试多个文档,请使用以下请求: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "documents": [ + { "title": "Banana flavoured ice-cream" }, + { "title": "Apple pie recipe" }, + { "title": "Banana bread instructions" }, + { "title": "Cherry tart" } + ] + } + } +} +``` + +`_percolator_document_slot` 字段通过文档在 `documents` 数组中的位置(从 `0` 开始)标识已保存查询匹配的每个文档: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.54726034, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.54726034, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 1 + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.31506687, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0, + 2 + ] + } + } + ] + } +} +``` + +### 渗透现有索引文档 + +您可以引用已存储在另一个索引中的现有文档来检查匹配的已保存查询。 + +为您的文档创建一个单独的索引: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { + "type": "text" + } + } + } +} +``` + +添加一个文档: + +```json +POST /products/_doc/1 +{ + "title": "Banana Smoothie Special" +} +``` + +检查存储的查询是否与索引文档匹配: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "index": "products", + "id": "1" + } + } +} +``` + +::: info NOTE +使用存储的文档时,必须同时提供 `index` 和 `id`。 +::: + +返回相应的查询: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + } + } + ] + } +} +``` + +为了确保渗透您期望的文档版本,请指定 `version` 参数。例如,要仅在文档仍为版本 `1` 时渗透文档,请在 `percolate` 查询中添加 `"version": 1`。如果文档此后已更新,请求将失败并显示 `version_conflict_engine_exception` 和 `409` 状态码。 + +### 在单独子句中渗透多个文档 + +要为每个文档使用单独的 `percolate` 子句渗透多个文档,请在 `bool` 查询中组合这些子句,并为每个子句指定 `name`: + +```json +GET /my_percolator_index/_search +{ + "query": { + "bool": { + "should": [ + { + "percolate": { + "field": "query", + "document": { + "title": "Apple pie recipe" + }, + "name": "apple_doc" + } + }, + { + "percolate": { + "field": "query", + "document": { + "title": "Banana bread instructions" + }, + "name": "banana_doc" + } + } + ] + } + } +} +``` + +OpenSearch 将每个子句的 `name` 附加到 `_percolator_document_slot` 字段,因此字段名称显示每个已保存查询匹配了哪个子句,从而匹配了哪个文档: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot_apple_doc": [ + 0 + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot_banana_doc": [ + 0 + ] + } + } + ] + } +} +``` + +如果从多个 `percolate` 子句中省略 `name`,OpenSearch 会将 `field` 值附加到槽字段名称。在此示例中,两个子句都会在同一个 `_percolator_document_slot_query` 字段中报告匹配,因此您无法分辨每个查询匹配了哪个文档。 + +由于每个文档都有自己的子句,您还可以对文档进行不同的加权。在以下示例中,每个 `percolate` 子句都包装在分配不同 `boost` 的 `constant_score` 查询中,因此第二个文档的匹配得分更高: + +```json +GET /my_percolator_index/_search +{ + "query": { + "bool": { + "should": [ + { + "constant_score": { + "filter": { + "percolate": { + "field": "query", + "document": { + "title": "Apple pie recipe" + }, + "name": "apple_doc" + } + }, + "boost": 1.0 + } + }, + { + "constant_score": { + "filter": { + "percolate": { + "field": "query", + "document": { + "title": "Banana bread with honey" + }, + "name": "banana_doc" + } + }, + "boost": 3.0 + } + } + ] + } + } +} +``` + +匹配第二个文档的查询获得更高的分数: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 3.0, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 3.0, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot_banana_doc": [ + 0 + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 1.0, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot_apple_doc": [ + 0 + ] + } + } + ] + } +} +``` + +## 批量渗透与单独子句的比较 + +批量渗透(使用 `documents`)和单独子句(使用 `bool` 加上每个文档的命名 `percolate` 子句)都可以渗透多个文档并返回相同的匹配。下表比较了每种方法如何构造请求、标识匹配的文档以及支持每个文档的评分。 + +| 功能 | 批量 (`documents`) | 单独子句 (`bool` + `percolate` + `name`) | +|-------------------------------|------------------------------------------------|--------------------------------------------------| +| 输入格式 | 一个包含文档数组的 `percolate` 子句 | 每个文档一个 `percolate` 子句 | +| 文档标识 | 通过 `documents` 数组中的位置 (`0`, `1`, ...) | 通过子句名称 (`apple_doc`, `banana_doc`) | +| 匹配槽的响应字段 | `_percolator_document_slot: [0]` | `_percolator_document_slot_<name>: [0]` | +| 高亮前缀 | `0_title`, `1_title` | `apple_doc_title`, `banana_doc_title` | +| 提升 | 整个子句一个提升,应用于所有文档 | 每个文档的子句有单独的提升 | +| 查询解析 | 每个已保存的查询只解析和匹配一次所有文档 | 每个子句单独匹配其文档 | +| 用例 | 批量匹配作业、大型事件流 | 每文档追踪、测试、每文档加权 | + +## 高亮匹配 + +`percolate` 响应中的高亮标记您提交的文档中的词项。每个命中的高亮显示其已保存查询匹配的词项,因此匹配同一文档的两个已保存查询可以高亮显示文档的不同部分。 + +### 高亮单个文档 + +此示例使用 `my_percolator_index` 中保存的查询。使用以下请求高亮 `title` 字段中的匹配: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "document": { + "title": "Apple banana smoothie" + } + } + }, + "highlight": { + "fields": { + "title": {} + } + } +} +``` + +每个命中都高亮其已保存查询匹配的词项: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.13076457, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + }, + "highlight": { + "title": [ + "<em>Apple</em> banana smoothie" + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.13076457, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + }, + "highlight": { + "title": [ + "Apple <em>banana</em> smoothie" + ] + } + } + ] + } +} +``` + +### 高亮多个文档 + +使用 `documents` 数组渗透多个文档时,高亮键采用以下形式,其中 `<slot>` 是文档在 `documents` 数组中的位置,从 `0` 开始: + +```json +"<slot>_<fieldname>": [ ... ] +``` + +使用以下命令渗透带有高亮的两个文档: + +```json +POST /my_percolator_index/_search +{ + "query": { + "percolate": { + "field": "query", + "documents": [ + { "title": "Apple pie recipe" }, + { "title": "Banana smoothie ideas" } + ] + } + }, + "highlight": { + "fields": { + "title": {} + } + } +} +``` + +响应包含以文档槽为前缀的高亮字段,如 `0_title` 和 `1_title`: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.31506687, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "1", + "_score": 0.31506687, + "_source": { + "query": { + "match": { + "title": "apple" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 0 + ] + }, + "highlight": { + "0_title": [ + "<em>Apple</em> pie recipe" + ] + } + }, + { + "_index": "my_percolator_index", + "_id": "2", + "_score": 0.31506687, + "_source": { + "query": { + "match": { + "title": "banana" + } + } + }, + "fields": { + "_percolator_document_slot": [ + 1 + ] + }, + "highlight": { + "1_title": [ + "<em>Banana</em> smoothie ideas" + ] + } + } + ] + } +} +``` + +## 性能考虑 + +当您索引已保存的查询时,OpenSearch 会提取查询的词项并将它们与查询一起索引。在搜索时,OpenSearch 将渗透的文档放入临时内存索引中,并使用提取的词项选择候选查询。只有这些候选项才会针对文档运行,因此大多数已保存的查询永远不会被评估。 + +无法从某些查询类型中提取词项,例如 `wildcard` 和 `geo_shape` 查询。对于 `bool` 查询,如果不支持的查询是唯一的 `must` 或 `filter` 子句,或者如果它是在没有 `must` 或 `filter` 子句的查询中的 `should` 子句之一,则提取失败。如果另一个必需的子句(例如 `must` 或 `filter` 中的 `match` 查询)具有可提取的词项,OpenSearch 会使用这些词项来选择候选项。无法提取词项的已保存查询会针对每个渗透的文档进行评估,随着此类查询数量的增长,这会减慢渗透速度。这些查询仍然正确匹配。 + +要查找无法提取词项的已保存查询,请在 `percolator` 字段的 `extraction_result` 子字段中搜索 `failed` 值。以下示例添加了一个 `wildcard` 查询,然后搜索词项提取失败的查询: + +```json +POST /my_percolator_index/_doc/3?refresh=true +{ + "query": { + "wildcard": { + "title": "cher*" + } + } +} +``` + +```json +GET /my_percolator_index/_search +{ + "query": { + "term": { + "query.extraction_result": "failed" + } + } +} +``` + +响应包含 `wildcard` 查询: + +```json +{ + ... + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_percolator_index", + "_id": "3", + "_score": 1.0, + "_source": { + "query": { + "wildcard": { + "title": "cher*" + } + } + } + } + ] + } +} +``` + +如前面的示例所示,将已保存的查询和渗透的文档存储在单独的索引中。单独的索引具有以下优势: + +- 每个索引中的文档共享相同的字段,因此 OpenSearch 存储它们更紧凑。 +- 您可以独立于文档索引配置已保存查询索引的设置,例如主分片数量。这很重要,因为渗透性能的扩展方式与常规搜索性能不同。 + +## 参数 + +`percolate` 查询支持以下参数。以内联方式(使用 `document` 或 `documents`)或通过引用(使用 `index` 和 `id`)提供要渗透的文档。 + +| 参数 | 必需/可选 | 描述 | +|-----------|-------------------|-------------| +| `field` | 必需 | 包含已保存查询的 `percolator` 字段。 | +| `document` | 可选 | 要与已保存查询匹配的单个内联文档。 | +| `documents` | 可选 | 要与已保存查询匹配的内联文档数组。 | +| `index` | 可选 | 包含要渗透的存储文档的索引。如果指定了 `id`,则为必需。 | +| `id` | 可选 | 要渗透的存储文档的 ID。如果指定了 `index`,则为必需。 | +| `routing` | 可选 | 获取存储文档时使用的路由值。 | +| `preference` | 可选 | 获取存储文档时使用的分片首选项。 | +| `version` | 可选 | 存储文档的预期版本。如果文档的当前版本不同,请求将失败并显示版本冲突错误。 | +| `name` | 可选 | `percolate` 子句的名称。OpenSearch 将该名称附加到响应中的 `_percolator_document_slot` 字段。当搜索包含多个 `percolate` 子句时,使用 `name` 来区分匹配。 | diff --git a/i18n/zh/query-dsl/specialized/rank-feature.md b/i18n/zh/query-dsl/specialized/rank-feature.md new file mode 100644 index 00000000..3d24189e --- /dev/null +++ b/i18n/zh/query-dsl/specialized/rank-feature.md @@ -0,0 +1,240 @@ +--- +title: Rank feature +--- + +# Rank feature + +使用 `rank_feature` 查询根据文档中的数值(如相关性分数、流行度或新鲜度)来提升文档分数。如果您想使用数值特征微调相关性排名,此查询非常理想。与[全文查询](/query-dsl/full-text/)不同,`rank_feature` 仅关注数值信号;当与复合查询(如 `bool`)中的其他查询组合时,它最为有效。 + +`rank_feature` 查询期望目标字段被映射为 [`rank_feature` 字段类型](/mappings/supported-field-types/rank/)。这使内部优化的评分能够实现快速高效的提升。 + +分数影响取决于字段值和使用的可选 `saturation`、`log` 或 `sigmoid` 函数。这些函数在查询时动态应用以计算最终文档分数;它们不会更改或存储文档本身中的任何值。 + +## 参数 + +`rank_feature` 查询支持以下参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +| ----------------------- | --------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `field` | String | 必需 | 贡献文档评分的 `rank_feature` 或 `rank_features` 字段。 | +| `boost` | Float | 可选 | 应用于分数的乘数。默认值为 `1.0`。0 和 1 之间的值会降低分数;大于 1 的值会放大分数。 | +| `saturation` | Object | 可选 | 对特征值应用饱和函数。提升随值增长但在超过 `pivot` 后趋于平缓。如果未提供其他函数,则为默认函数。`saturation`、`log` 或 `sigmoid` 只能同时使用一个。| +| `log` | Object | 可选 | 使用基于字段值的对数评分函数。最适合大范围值。`saturation`、`log` 或 `sigmoid` 只能同时使用一个。 | +| `sigmoid` | Object | 可选 | 对分数影响应用 S 形曲线,由 `pivot` 和 `exponent` 控制。`saturation`、`log` 或 `sigmoid` 只能同时使用一个。 | +| `positive_score_impact` | Boolean | 可选 | 当为 `false` 时,较低的值得分更高。对于价格等特征很有用,其中较小更好。在映射中定义。默认值为 `true`。 | + +## 示例 + +以下示例演示如何定义和使用 `rank_feature` 字段来影响文档评分。 + +### 创建带有 rank feature 字段的索引 + +定义一个带有 `rank_feature` 字段的索引来表示像 `popularity` 这样的信号: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "popularity": { "type": "rank_feature" } + } + } +} +``` + +### 索引示例文档 + +添加具有不同流行度值的示例产品: + +```json +POST /products/_bulk +{ "index": { "_id": 1 } } +{ "title": "Wireless Earbuds", "popularity": 1 } +{ "index": { "_id": 2 } } +{ "title": "Bluetooth Speaker", "popularity": 10 } +{ "index": { "_id": 3 } } +{ "title": "Portable Charger", "popularity": 25 } +{ "index": { "_id": 4 } } +{ "title": "Smartwatch", "popularity": 50 } +{ "index": { "_id": 5 } } +{ "title": "Noise Cancelling Headphones", "popularity": 100 } +{ "index": { "_id": 6 } } +{ "title": "Gaming Laptop", "popularity": 250 } +{ "index": { "_id": 7 } } +{ "title": "4K Monitor", "popularity": 500 } +``` + +### 基本 rank feature 查询 + +您可以使用 `rank_feature` 根据 `popularity` 分数提升结果: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity" + } + } +} +``` + +此查询本身不执行过滤。相反,它根据 `popularity` 的值对所有文档进行评分。较高的值产生较高的分数: + +```json +{ + ... + "hits": { + "total": { + "value": 7, + "relation": "eq" + }, + "max_score": 0.9252834, + "hits": [ + { + "_index": "products", + "_id": "7", + "_score": 0.9252834, + "_source": { + "title": "4K Monitor", + "popularity": 500 + } + }, + ... + ] + } +} +``` + +### 与全文搜索结合 + +要过滤相关结果并根据流行度提升它们,请使用以下请求。此查询对所有匹配"headphones"的文档进行排名,并提升流行度较高的文档: + +```json +POST /products/_search +{ + "query": { + "bool": { + "must": { + "match": { + "title": "headphones" + } + }, + "should": { + "rank_feature": { + "field": "popularity" + } + } + } + } +} +``` + +### boost 参数 + +`boost` 参数允许您缩放 rank_feature 子句的分数贡献。它在复合查询(如 `bool`)中特别有用,您可以控制数值字段(如流行度、新鲜度或相关性分数)对最终文档排名的影响程度。 + +在以下示例中,`bool` 查询匹配 `title` 中包含词项"headphones"的文档,并使用 `boost` 为 `2.0` 的 `rank_feature` 子句提升更受欢迎的结果。这将 `rank_feature` 分数对整体文档分数的贡献加倍: + +```json +POST /products/_search +{ + "query": { + "bool": { + "must": { + "match": { + "title": "headphones" + } + }, + "should": { + "rank_feature": { + "field": "popularity", + "boost": 2.0 + } + } + } + } +} +``` + +### 配置评分函数 + +默认情况下,`rank_feature` 查询使用从字段派生的 `pivot` 值的 `saturation` 函数。您可以显式将函数设置为 `saturation`、`log` 或 `sigmoid`。 + +#### Saturation 函数 + +`saturation` 函数是 `rank_feature` 查询中使用的默认评分方法。它为具有较大特征值的文档分配较高的分数,但当值超过指定的 `pivot` 时,分数的增加变得更加平缓。当您想对非常大的值给予递减回报时,这很有用,例如在避免过度奖励极高数字的同时提升 `popularity`。计算分数的公式为 `rank_feature 字段的值 / (rank_feature 字段的值 + pivot)`。产生的分数始终在 `0` 和 `1` 之间。如果未提供 `pivot`,则使用索引中所有 `rank_feature` 值的近似几何平均值。 + +以下示例使用 `pivot` 为 `50` 的 `saturation`: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity", + "saturation": { + "pivot": 50 + } + } + } +} +``` + +`pivot` 定义评分增长减慢的点。高于 `pivot` 的值仍会增加分数,但回报递减。 + +#### Log 函数 + +当 `rank_feature` 字段包含大范围值时,`log` 函数很有帮助。它对 `score` 应用对数刻度,这减少了极高值的影响,并有助于在宽值分布范围内归一化评分。当低值之间的小差异应该比高值之间的大差异更有影响力时,这特别有用。分数使用公式 `log(scaling_factor + rank_feature 字段)` 计算。以下示例使用 `scaling_factor` 为 `2`: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity", + "log": { + "scaling_factor": 2 + } + } + } +} +``` + +#### Sigmoid 函数 + +`sigmoid` 函数提供平滑的 S 形评分曲线,当您想控制评分影响的陡度和中点时特别有用。分数使用公式 `rank feature 字段值^exp / (rank feature 字段值^exp + pivot^exp)` 计算。以下示例使用配置了 `pivot` 和 `exponent` 的 `sigmoid` 函数。`pivot` 定义分数为 0.5 的值。`exponent` 控制曲线的陡度。较低的值导致围绕 `pivot` 更急剧的过渡: + +```json +POST /products/_search +{ + "query": { + "rank_feature": { + "field": "popularity", + "sigmoid": { + "pivot": 50, + "exponent": 0.5 + } + } + } +} +``` + +#### 反转分数影响 + +默认情况下,较高的值导致较高的分数。如果您希望较低的值产生较高的分数(例如,较低的价格更相关),请在创建索引时将 `positive_score_impact` 设置为 `false`: + +```json +PUT /products_new +{ + "mappings": { + "properties": { + "popularity": { + "type": "rank_feature", + "positive_score_impact": false + } + } + } +} +``` diff --git a/i18n/zh/query-dsl/specialized/script.md b/i18n/zh/query-dsl/specialized/script.md new file mode 100644 index 00000000..61401896 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/script.md @@ -0,0 +1,211 @@ +--- +title: Script 查询 +--- + +# Script 查询 + +使用 `script` 查询根据使用 Painless 脚本语言编写的自定义条件过滤文档。此查询返回脚本计算结果为 `true` 的文档,从而实现无法使用标准查询表达的高级过滤逻辑。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。 + +::: warning IMPORTANT +`script` 查询计算成本高,应谨慎使用。仅在必要时使用,并确保启用了 `search.allow_expensive_queries`(默认为 `true`)。有关更多信息,请参阅[昂贵的查询](/query-dsl/#expensive-queries)。 +::: + +## 示例 + +创建一个名为 `products` 的索引,并具有以下映射: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { "type": "text" }, + "price": { "type": "float" }, + "rating": { "type": "float" } + } + } +} +``` + +使用以下请求索引示例文档: + +```json +POST /products/_bulk +{ "index": { "_id": 1 } } +{ "title": "Wireless Earbuds", "price": 99.99, "rating": 4.5 } +{ "index": { "_id": 2 } } +{ "title": "Bluetooth Speaker", "price": 79.99, "rating": 4.8 } +{ "index": { "_id": 3 } } +{ "title": "Noise Cancelling Headphones", "price": 199.99, "rating": 4.7 } +``` + +## 基本脚本查询 + +返回评分高于 `4.6` 的产品: + +```json +POST /products/_search +{ + "query": { + "script": { + "script": { + "source": "doc['rating'].value > 4.6" + } + } + } +} +``` + +返回的命中仅包含 `rating` 高于 `4.6` 的文档: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "products", + "_id": "2", + "_score": 1, + "_source": { + "title": "Bluetooth Speaker", + "price": 79.99, + "rating": 4.8 + } + }, + { + "_index": "products", + "_id": "3", + "_score": 1, + "_source": { + "title": "Noise Cancelling Headphones", + "price": 199.99, + "rating": 4.7 + } + } + ] + } +} +``` + +## 参数 + +`script` 查询采用以下顶级参数。 + +| 参数 | 必需/可选 | 描述 | +| --------------- | ----------------- | ----------------------------------------------------- | +| `script.source` | 必需 | 计算结果为 `true` 或 `false` 的脚本代码。 | +| `script.params` | 可选 | 在脚本中引用的用户定义参数。 | + +## 使用脚本参数 + +您可以使用 `params` 安全地注入值,利用脚本编译缓存: + +```json +POST /products/_search +{ + "query": { + "script": { + "script": { + "source": "doc['price'].value < params.max_price", + "params": { + "max_price": 100 + } + } + } + } +} +``` + +返回的命中仅包含 `price` 小于 `100` 的文档: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "products", + "_id": "1", + "_score": 1, + "_source": { + "title": "Wireless Earbuds", + "price": 99.99, + "rating": 4.5 + } + }, + { + "_index": "products", + "_id": "2", + "_score": 1, + "_source": { + "title": "Bluetooth Speaker", + "price": 79.99, + "rating": 4.8 + } + } + ] + } +} +``` + +## 组合多个条件 + +使用以下查询搜索 `rating` 高于 `4.5` 且 `price` 低于 `100` 的产品: + +```json +POST /products/_search +{ + "query": { + "script": { + "script": { + "source": "doc['rating'].value > 4.5 && doc['price'].value < 100" + } + } + } +} +``` + +仅返回符合要求的文档: + +```json +{ + "took": 12, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "products", + "_id": "2", + "_score": 1, + "_source": { + "title": "Bluetooth Speaker", + "price": 79.99, + "rating": 4.8 + } + } + ] + } +} +``` diff --git a/i18n/zh/query-dsl/specialized/template.md b/i18n/zh/query-dsl/specialized/template.md new file mode 100644 index 00000000..ee4b0497 --- /dev/null +++ b/i18n/zh/query-dsl/specialized/template.md @@ -0,0 +1,98 @@ +--- +title: Template +--- + +# Template 查询 +<Badge type="tip" text="2.19 版本引入" /> + +使用 `template` 查询创建包含占位符变量的搜索查询。占位符使用 `"${variable_name}"` 语法指定(请注意,变量必须用引号括起来)。当您提交搜索请求时,这些占位符保持未解析状态,直到它们被搜索请求处理器处理。当您的初始搜索请求包含需要在运行时转换或生成的数据时,这种方法特别有用。 + +例如,您可能在使用 [ml_inference 搜索请求处理器](/search-plugins/search-pipelines/ml-inference-search-request)时使用模板查询,该处理器在搜索过程中将文本输入转换为向量嵌入。处理器将在最终查询执行前用生成的值替换占位符。 + +有关完整示例,请参阅[使用模板查询进行查询重写](/search-plugins/search-relevance/template-query)。 + +::: info NOTE +本页记录的 `template` 查询使用由搜索请求处理器(如 ML 推理)在运行时解析的占位符变量。如果您想使用 Mustache 语法(`{{variable}}`)创建可重用的参数化查询,请参阅 [Search Template API](/api-reference/search-apis/search-template/)。 +::: + +## 示例 + +以下示例显示了一个带有 `"vector": "${text_embedding}"` 占位符的模板 k-NN 查询。占位符 `"${text_embedding}"` 将被 `ml_inference` 搜索请求处理器从 `text` 输入字段生成的嵌入替换: + +```json +GET /template-knn-index/_search?search_pipeline=my_knn_pipeline +{ + "query": { + "template": { + "knn": { + "text_embedding": { + "vector": "${text_embedding}", // 向量字段的占位符 + "k": 2 + } + } + } + }, + "ext": { + "ml_inference": { + "text": "sneakers" // ml_inference 处理器的输入文本 + } + } +} +``` + +要将模板查询与搜索请求处理器一起使用,您需要配置搜索管道。以下是 `ml_inference` 搜索请求处理器的示例配置。`input_map` 将文档字段映射到模型输入。在此示例中,文档中的 `ext.ml_inference.text` 源字段映射到 `inputText` 字段---模型的预期输入字段。`output_map` 将模型输出映射到文档字段。在此示例中,模型的 `embedding` 输出字段映射到文档中的 `text_embedding` 目标字段: + +```json +PUT /_search/pipeline/my_knn_pipeline +{ + "request_processors": [ + { + "ml_inference": { + "model_id": "Sz-wFZQBUpPSu0bsJTBG", + "input_map": [ + { + "inputText": "ext.ml_inference.text" // 从请求映射输入文本 + } + ], + "output_map": [ + { + "text_embedding": "embedding" // 将输出映射到占位符 + } + ] + } + } + ] +} +``` + +在 `ml_inference` 搜索请求处理器运行后,搜索请求被重写。`vector` 字段包含处理器生成的嵌入,`text_embedding` 字段包含处理器输出: + +```json +GET /template-knn-1/_search +{ + "query": { + "template": { + "knn": { + "text_embedding": { + "vector": [0.6328125, 0.26953125, ...], + "k": 2 + } + } + } + }, + "ext": { + "ml_inference": { + "text": "sneakers", + "text_embedding": [0.6328125, 0.26953125, ...] + } + } +} +``` + +## 限制 + +模板查询需要至少一个搜索请求处理器才能解析占位符。搜索请求处理器必须配置为生成管道中预期的变量。 + +## 后续步骤 + +- 有关完整示例,请参阅[模板查询](/search-plugins/search-relevance/template-query)。 diff --git a/i18n/zh/query-dsl/specialized/wrapper.md b/i18n/zh/query-dsl/specialized/wrapper.md new file mode 100644 index 00000000..65bc6c8e --- /dev/null +++ b/i18n/zh/query-dsl/specialized/wrapper.md @@ -0,0 +1,88 @@ +--- +title: Wrapper +--- + +# Wrapper 查询 + +`wrapper` 查询允许您以 Base64 编码的 JSON 格式提交完整的查询。当查询必须嵌入到仅支持字符串值的上下文中时,这很有用。 + +仅在需要管理系统约束时使用此查询。为了可读性和可维护性,尽可能使用标准的基于 JSON 的查询更好。 + +## 示例 + +创建一个名为 `products` 的索引,并具有以下映射: + +```json +PUT /products +{ + "mappings": { + "properties": { + "title": { "type": "text" } + } + } +} +``` + +索引示例文档: + +```json +POST /products/_bulk +{ "index": { "_id": 1 } } +{ "title": "Wireless headphones with noise cancellation" } +{ "index": { "_id": 2 } } +{ "title": "Bluetooth speaker" } +{ "index": { "_id": 3 } } +{ "title": "Over-ear headphones with rich bass" } +``` + +将以下查询编码为 Base64 格式: + +```bash +echo -n '{ "match": { "title": "headphones" } }' | base64 +``` + +执行编码的查询: + +```json +POST /products/_search +{ + "query": { + "wrapper": { + "query": "eyAibWF0Y2giOiB7ICJ0aXRsZSI6ICJoZWFkcGhvbmVzIiB9IH0=" + } + } +} +``` + +响应包含两个匹配的文档: + +```json +{ + ... + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.20098841, + "hits": [ + { + "_index": "products", + "_id": "1", + "_score": 0.20098841, + "_source": { + "title": "Wireless headphones with noise cancellation" + } + }, + { + "_index": "products", + "_id": "3", + "_score": 0.18459359, + "_source": { + "title": "Over-ear headphones with rich bass" + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/caching/field-data-cache.md b/i18n/zh/search-plugins/caching/field-data-cache.md new file mode 100644 index 00000000..c8b4ac29 --- /dev/null +++ b/i18n/zh/search-plugins/caching/field-data-cache.md @@ -0,0 +1,62 @@ +--- +title: 字段数据缓存 +--- + +# 字段数据缓存 + +字段数据缓存是一个节点级内存缓存,用于存储字段数据和全局序数。这些是支持对已分析文本字段进行聚合和排序的数据结构。由于它们的计算成本可能很高,因此在创建后会被缓存以备重用。 + +## 什么是字段数据 + +字段数据是一种数据结构,可以在文本字段上快速排序和聚合。文本字段存储在倒排索引中,该索引针对快速搜索特定术语进行了优化,而不是遍历单个文档。由于这对于聚合或排序是必需的,OpenSearch 必须将倒排索引处理成另一种针对单个文档访问优化的数据结构。 + +## 什么是全局序数 + +在对给定字段计算聚合时,每个 Lucene 段为每个唯一术语分配一个唯一的序数,从而支持诸如分桶聚合之类的操作。在跨整个集群计算聚合时,需要为每个全局唯一术语创建一个全局序数,并存储这些全局序数和段序数之间的映射。这使得能够组合来自每个段的聚合结果。然后将此映射存储在字段数据缓存中,以便在未来的聚合中重用。 + +如果字段具有映射参数 `"eager_global_ordinals": true`(默认为 `false`),则全局序数会在索引刷新时计算和存储,而不是在查询时延迟计算。 + +有关全局序数的更多信息,请参阅[即时全局序数](/mappings/mapping-parameters/eager_global_ordinals/)。 + +## 最佳实践 + +默认情况下,文本字段上禁用字段数据,因为它可能会消耗大量堆内存。如果您想对文本字段进行排序或聚合,我们建议改为创建一个关键字子字段。关键字字段不进行分析,因此不会存储在倒排索引中,也不需要为聚合构建单独的数据结构。 + +如果您想直接在文本字段上启用排序或聚合,请在字段的映射中设置 `"fielddata": true`。 + +## 配置字段数据缓存 + +设置 | 数据类型 | 默认值 | 级别 | 静态/动态 | 描述 +:--- |:-----------|:--------| :--- | :--- | :--- +`indices.breaker.fielddata.limit` | 百分比 | `40%` | 集群 | 动态 | 设置字段数据缓存大小限制,超过此限制后,需要在缓存中添加更多条目的传入请求将被断路器阻止。 +`indices.fielddata.cache.size` | 字节大小或总堆大小的百分比 | `35%` | 集群 | 动态 | 设置最大字段数据缓存大小,超过此限制将发生驱逐。必须小于断路器限制。值为 -1 时,此限制不适用,只有断路器限制生效。 + +## 监控字段数据缓存 + +[节点统计 API](/api-reference/nodes-apis/nodes-stats) 返回集群中所有节点的缓存统计信息: + +```json +GET /_nodes/stats/indices/fielddata +``` + +响应包含缓存统计信息: + +```json +{ + "nodes" : { + "oeR83dkUSPmnQqzBEGc4fQ" : { + "indices" : { + "fielddata" : { + "memory_size_in_bytes" : 0, + "evictions" : 0, + "item_count" : 0 + } + } + } + } +} +``` + +您可以通过提供参数 `level=indices` 按索引聚合值。 + +您还可以使用 [Cat 字段数据 API](/api-reference/cat/cat-field-data) 获取每个节点上每个字段的字段数据大小列表。 diff --git a/i18n/zh/search-plugins/caching/index.md b/i18n/zh/search-plugins/caching/index.md new file mode 100644 index 00000000..6eab256a --- /dev/null +++ b/i18n/zh/search-plugins/caching/index.md @@ -0,0 +1,30 @@ +--- +title: 缓存 +--- + +# 缓存 + +OpenSearch 依赖于不同的堆内缓存类型来加速数据检索,从而显著改善搜索延迟。然而,缓存大小受限于节点上可用的内存量。在处理可能被缓存的较大数据集时,缓存大小限制可能导致许多数据片段被从缓存中移除或根本不被缓存,从而导致查询不完整。这会影响性能,因为 OpenSearch 需要重新处理查询,导致高资源消耗。 + +了解数据如何使用缓存可以帮助改善集群的性能,并防止使用过多内存,从而降低查询数据的成本。 + +## 支持的堆内缓存类型 + +OpenSearch 支持以下堆内缓存类型: + +- [**索引请求缓存**](/search-plugins/caching/request-cache):在每个分片上缓存本地结果。这使得频繁使用且可能占用大量资源的搜索请求能够几乎即时返回结果。 +- **查询缓存**:在分片级别缓存来自相似查询的通用数据。查询缓存比请求缓存更细粒度,可以缓存数据以在不同查询中重用。 +- [**字段数据缓存**](/search-plugins/caching/field-data-cache):缓存字段数据和全局序数,这两者都用于支持某些字段类型的聚合。 + +## 额外的缓存存储 + +<Badge type="tip" text="2.14 版本引入" /> + +除了现有的自定义 OpenSearch 堆内缓存存储外,缓存插件还提供以下缓存存储: + +- **磁盘缓存**:将查询的预计算结果存储在磁盘上。使用磁盘缓存可以缓存更大的数据集,前提是磁盘的延迟在可接受的范围内。 +- **分层缓存**:一个多级缓存,其中每一层都有自己的特性和性能级别。例如,分层缓存可以同时包含堆内层和磁盘层。通过组合不同的层,您可以在缓存性能和大小之间实现平衡。要了解更多信息,请参阅[分层缓存](/search-plugins/caching/tiered-cache)。 + +::: info NOTE +在 OpenSearch 2.14 中,请求缓存已与缓存插件集成。您可以使用分层或磁盘缓存作为请求级缓存。 +::: diff --git a/i18n/zh/search-plugins/caching/request-cache.md b/i18n/zh/search-plugins/caching/request-cache.md new file mode 100644 index 00000000..60fea1d7 --- /dev/null +++ b/i18n/zh/search-plugins/caching/request-cache.md @@ -0,0 +1,155 @@ +--- +title: 索引请求缓存 +--- + +# 索引请求缓存 + +OpenSearch 索引请求缓存是一种专门的缓存机制,旨在通过在分片级别存储频繁执行的搜索查询结果来提高搜索性能。这减少了集群负载并改善了重复搜索的响应时间。此缓存默认启用,对于某些查询频繁执行的读取密集型工作负载特别有用。 + +缓存会在配置的刷新间隔自动失效。失效包括文档更新(包括文档删除)和索引设置的更改。这确保永远不会从缓存返回过时的结果。当缓存大小超过其配置限制时,最近最少使用的条目会被驱逐以为新条目腾出空间。 + +::: info NOTE +某些查询不符合请求缓存的条件。这些包括分析查询、滚动查询以及具有非确定性特征的搜索请求(例如使用 `Math.random()` 的请求或 DFS 查询)或相对时间(例如 `now` 或 `new Date()`)。默认情况下,只有 `size=0` 的请求才可缓存。在 OpenSearch 2.19 及更高版本中,可以使用 `indices.requests.cache.maximum_cacheable_size` 更改此行为。 +::: + +## 配置请求缓存 + +您可以通过在 `opensearch.yml` 配置文件中设置参数或使用 REST API 来配置索引请求缓存。有关更多信息,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +### 设置 + +下表列出了索引请求缓存设置。有关动态设置的更多信息,请参阅[索引设置](/install-and-configure/configuring-opensearch/index-settings)。 + +设置 | 数据类型 | 默认值 | 级别 | 静态/动态 | 描述 +:--- |:-----------|:--------| :--- | :--- | :--- +`indices.cache.cleanup_interval` | 时间单位 | `1m`(1 分钟) | 集群 | 静态 | 安排一个定期后台任务,以指定的间隔从缓存中清理过期条目。 +`indices.requests.cache.size` | 百分比 | `1%` | 集群 | 静态 | 缓存大小占堆大小的百分比(例如,要使用堆的 1%,请指定 `1%`)。 +`index.requests.cache.enable` | 布尔值 | `true` | 索引 | 动态 | 启用或禁用请求缓存。 +`indices.requests.cache.maximum_cacheable_size` | 整数 | `0` | 集群 | 动态 | 设置要添加到请求缓存的查询的最大 `size`。 + +### 示例 + +要禁用索引的请求缓存,请发送以下请求: + +```json +PUT /my_index/_settings +{ + "index.requests.cache.enable": false +} +``` + +## 缓存特定请求 + +除了为请求缓存提供索引级别或集群级别的设置外,您还可以通过将 `request_cache` 查询参数设置为 `true` 来选择性地缓存特定的搜索请求: + +```json +GET /students/_search?request_cache=true +{ + "query": { + "match": { + "name": "doe john" + } + } +} +``` + +## 将请求匹配到缓存结果 + +请求缓存为每个分片存储结果。为了找到缓存的结果,OpenSearch 比较解析后的搜索请求,因此仅在格式上有所不同的请求会共享缓存的结果。例如,仅在空格或 JSON 键顺序上有所不同的请求会返回相同的缓存结果。两个仅在是否指定默认 `size` 为 `10` 上有所不同的 `terms` 聚合也是如此。在内容上有所不同的请求(例如具有不同名称的聚合)会单独缓存。 + +## 监控请求缓存 + +监控缓存使用情况和性能对于维护高效的缓存策略至关重要。OpenSearch 提供了几个 API 来帮助监控缓存。 + +### 检索所有节点的缓存统计信息 + +[节点统计 API](/api-reference/nodes-apis/nodes-stats) 返回集群中所有节点的缓存统计信息: + +```json +GET /_nodes/stats/indices/request_cache +``` + +响应包含请求缓存统计信息: + +```json +{ + "nodes": { + "T7aqO6zaQX-lt8XBWBYLsA": { + "indices": { + "request_cache": { + "memory_size_in_bytes": 10240, + "evictions": 0, + "hit_count": 50, + "miss_count": 10 + } + } + } + } +} +``` + +### 检索特定索引的缓存统计信息 + +[索引统计 API](/api-reference/index-apis/stats) 返回特定索引的缓存统计信息: + +```json +GET /my_index/_stats/request_cache +``` + +响应包含请求缓存统计信息: + +```json +{ + "_shards": { + "total": 5, + "successful": 5, + "failed": 0 + }, + "_all": { + "primaries": { + "request_cache": { + "memory_size_in_bytes": 2048, + "evictions": 1, + "hit_count": 30, + "miss_count": 5 + } + }, + "total": { + "request_cache": { + "memory_size_in_bytes": 4096, + "evictions": 2, + "hit_count": 60, + "miss_count": 10 + } + } + }, + "indices": { + "my_index": { + "primaries": { + "request_cache": { + "memory_size_in_bytes": 2048, + "evictions": 1, + "hit_count": 30, + "miss_count": 5 + } + }, + "total":{ + "request_cache": { + "memory_size_in_bytes": 4096, + "evictions": 2, + "hit_count": 60, + "miss_count": 10 + } + } + } + } +} +``` + +## 最佳实践 + +使用索引请求缓存时,请考虑以下最佳实践: + +- **适当的缓存大小**:根据查询模式配置缓存大小。较大的缓存可以存储更多结果,但可能会消耗大量资源。 +- **查询优化**:确保频繁执行的查询经过优化,以便它们可以从缓存中受益。 +- **监控**:定期监控缓存命中率和缓存未命中率,以了解缓存效率并进行必要的调整。 diff --git a/i18n/zh/search-plugins/caching/tiered-cache.md b/i18n/zh/search-plugins/caching/tiered-cache.md new file mode 100644 index 00000000..e77559b1 --- /dev/null +++ b/i18n/zh/search-plugins/caching/tiered-cache.md @@ -0,0 +1,103 @@ +--- +title: 分层缓存 +--- + +# 分层缓存 + +分层缓存是一个多级缓存,其中每一层都有自己的特性和性能级别。通过组合不同的层,您可以在缓存性能和大小之间实现平衡。 + +## 分层缓存的类型 + +OpenSearch 提供了一种分层溢出缓存的实现。它被称为 `tiered_spillover`,其实现存储在 `cache-common` 模块中。它有两层:上层和下层。虽然每一层可以使用任何可插拔缓存实现,但通常上层将是较小且更快的堆内层,例如 `opensearch_onheap`,下层将是较大且较慢的磁盘层,例如 `ehcache_disk`。可以使用设置 `indices.requests.cache.tiered_spillover.disk.store.enabled` 动态启用和禁用此下层。 + +进入缓存的项目首先会进入上层(堆内层)。一旦上层满了,它就会驱逐项目(通常按 LRU 顺序,尽管缓存实现可以按任何顺序驱逐项目)。这些被驱逐的项目会进入下层(磁盘层)。当磁盘层满时,它驱逐的项目会完全从缓存中删除。如果下层被禁用,从上层驱逐的项目将离开缓存。 + +请注意,给定的键一次只能在一层中;上层不包含下层的子集。获取键时,会依次检查每一层。 + +您可以使用 `tiered_spillover` 使磁盘层非常大——比在内存中时可能的更大。这允许您缓存更多项目而不使用额外的堆空间。 + +## 安装所需插件 + +要使用分层缓存,请安装 `cache-ehcache` 插件。此插件提供磁盘缓存实现 `ehcache_disk`,可用作分层缓存中的磁盘层。有关安装非捆绑插件的更多信息,请参阅[附加插件](/install-and-configure/plugins#additional-plugins)。 + +::: danger WARNING +如果未安装 `cache-ehcache` 插件或未设置磁盘缓存属性,分层缓存将无法初始化。 +::: + +## 分层缓存设置 + +在 OpenSearch 2.14 及更高版本中,请求缓存可以使用 `tiered_spillover` 缓存或任何其他可插拔缓存实现。首先,在 `opensearch.yml` 文件中配置以下设置。 + +### 缓存存储名称 + +要使用 OpenSearch 提供的分层溢出缓存实现,请将缓存存储名称设置为 `tiered_spillover`,如以下示例所示: + +```yaml +indices.requests.cache.store.name: tiered_spillover +``` + +### 设置堆内和磁盘存储层 + +将堆内和磁盘存储层设置为 `opensearch_onheap` 和 `ehcache_disk`,如以下示例所示: + +```yaml +indices.requests.cache.tiered_spillover.onheap.store.name: opensearch_onheap +indices.requests.cache.tiered_spillover.disk.store.name: ehcache_disk +``` +`opensearch_onheap` 设置使用 OpenSearch 中可用的内置堆内缓存。 + +`ehcache_disk` 设置是基于 [Ehcache](https://www.ehcache.org/) 的磁盘缓存实现,需要安装 `cache-ehcache` 插件。 + +### 配置堆内和磁盘存储 + +下表列出了 `opensearch_onheap` 存储的缓存存储设置。 + +设置 | 数据类型 | 默认值 | 描述 +:--- | :--- | :--- | :--- +`indices.requests.cache.opensearch_onheap.size` | 百分比 | 堆大小的 1% | 堆内缓存的大小。可选。 +`indices.requests.cache.opensearch_onheap.expire` | 时间单位 | `MAX_VALUE`(禁用) | 指定缓存结果的生存时间(TTL)。可选。 + +下表列出了 `ehcache_disk` 存储的磁盘缓存存储设置。 + +设置 | 数据类型 | 默认值 | 描述 +:--- | :--- | :--- | :--- +`indices.requests.cache.ehcache_disk.max_size_in_bytes` | 长整型 | `1073741824`(1 GB) | 定义磁盘缓存的大小。可选。 +`indices.requests.cache.ehcache_disk.storage.path` | 字符串 | `{data.paths}/nodes/{node.id}/request_cache` | 定义磁盘缓存的存储路径。可选。 +`indices.requests.cache.ehcache_disk.expire_after_access` | 时间单位 | `MAX_VALUE`(禁用) | 指定缓存结果的 TTL。可选。 +`indices.requests.cache.ehcache_disk.alias` | 字符串 | `ehcacheDiskCache#INDICES_REQUEST_CACHE` | 指定磁盘缓存的别名。可选。 +`indices.requests.cache.ehcache_disk.segments` | 整数 | `16` | 定义磁盘缓存分成的段数。用于并发。可选。 +`indices.requests.cache.ehcache_disk.concurrency` | 整数 | `1` | 定义为磁盘存储创建的不同写入队列数,其中一组段共享一个写入队列。可选。 +`indices.requests.cache.ehcache_disk.min_threads` | 整数 | `2` | 定义池的 Ehcache 磁盘线程的最小数量。可选。 +`indices.requests.cache.ehcache_disk.max_threads` | 整数 | CPU 核心数 | 定义池的 Ehcache 磁盘线程的最大数量。允许的最大值为 `10 * num_cpu_cores`。磁盘操作通常是 I/O 绑定而不是 CPU 绑定,因此您可以将此值设置为大于 CPU 核心数的数字。可选。 + +### `tiered_spillover` 存储的附加设置 + +下表列出了 `tiered_spillover` 存储设置的附加设置。 + +设置 | 数据类型 | 默认值 | 描述 +:--- | :--- | :--- | :--- +`indices.requests.cache.tiered_spillover.policies.took_time.threshold` | 时间单位 | `0ms` | 用于根据查询阶段执行时间确定是否将查询缓存到缓存中的策略。这是一个动态设置。可选。 +`indices.requests.cache.tiered_spillover.disk.store.policies.took_time.threshold` | 时间单位 | `10ms` | 用于根据查询阶段执行时间确定是否将查询缓存到缓存的磁盘层中的策略。这是一个动态设置。可选。 +`indices.requests.cache.tiered_spillover.disk.store.enabled` | 布尔值 | `True` | 在分层溢出缓存中动态启用或禁用磁盘缓存。注意:禁用磁盘缓存后,条目不会自动删除,需要手动清除缓存。可选。 +`indices.requests.cache.tiered_spillover.onheap.store.size` | 百分比 | 堆大小的 1% | 定义分层缓存中堆内缓存的大小。此设置会覆盖堆内缓存实现本身的任何大小设置,例如 `indices.requests.cache.opensearch_onheap.size`。可选。 +`indices.requests.cache.tiered_spillover.disk.store.size` | 长整型 | `1073741824`(1 GB) | 定义分层缓存中磁盘缓存的大小。此设置会覆盖磁盘缓存实现本身的任何大小设置,例如 `indices.requests.cache.ehcache_disk.max_size_in_bytes`。可选。 +`indices.requests.cache.tiered_spillover.segments` | 整数 | `2 ^ (ceil(log2(CPU_CORES * 1.5)))` | 这决定了分层缓存中的段数,每个段都由可重入读/写锁保护。这些锁使多个并发读取者能够无争用地访问,而分段允许多个写入者同时操作,从而实现更高的写入吞吐量。可选。 + +### 删除过时条目设置 + +下表列出了与从缓存中删除过时条目相关的设置。 + +设置 | 数据类型 | 默认值 | 描述 +:--- | :--- |:--------| :--- +`indices.requests.cache.cleanup.staleness_threshold` | 字符串 | `0%` | 定义识别后缓存中过时键的百分比。识别后,所有过时的缓存条目都将被删除。可选。 +`indices.requests.cache.cleanup.interval` | 时间单位 | `1m` | 定义删除请求缓存的过时条目的频率。可选。 + +## 获取 `tiered_spillover` 存储的统计信息 + +要评估使用分层溢出缓存的影响,请使用[节点统计 API](/api-reference/nodes-apis/nodes-stats#caches),如以下示例所示: + +```json +GET /_nodes/stats/caches/request_cache?level=tier +``` + +`tier` 级别仅在使用 `tiered_spillover` 缓存时有效,它按上层和下层缓存层聚合统计信息。 diff --git a/i18n/zh/search-plugins/cross-cluster-search.md b/i18n/zh/search-plugins/cross-cluster-search.md new file mode 100644 index 00000000..afb41e33 --- /dev/null +++ b/i18n/zh/search-plugins/cross-cluster-search.md @@ -0,0 +1,397 @@ +--- +title: 跨集群搜索 +--- + +# 跨集群搜索 + +您可以在 OpenSearch 中使用跨集群搜索(CCS)来搜索和分析多个集群的数据,使您能够从分布式数据源中获得见解。跨集群搜索默认情况下可与安全插件一起使用,但您需要配置每个集群以允许来自其他集群的远程连接。这涉及设置远程集群连接和配置访问权限。 + +--- + +#### 目录 + +--- + +## 先决条件 + +在配置跨集群搜索之前,请确保满足以下先决条件: + +- 如果您已在参与跨集群搜索的集群中任何节点的 `opensearch.yml` 中覆盖了 `node.roles`,请确保 `node.roles` 设置包含 `remote_cluster_client` 角色: + + ```yaml + node.roles: [<other_roles>, remote_cluster_client] + ``` + +## 身份验证流程 + +以下序列描述了使用跨集群搜索从*协调集群*访问*远程集群*时的身份验证流程。您可以在远程集群和协调集群上使用不同的身份验证和授权配置,但我们建议在两者上使用相同的设置。 + +1. 安全插件在协调集群上对用户进行身份验证。 +1. 安全插件在协调集群上获取用户的后端角色。 +1. 包含已验证用户的调用被转发到远程集群。 +1. 在远程集群上评估用户的权限。 + +## 远程集群角色评估 +<Badge type="tip" text="3.9 版本引入" /> + +默认情况下,远程集群使用从协调集群传播的安全角色和自己的角色映射的组合来评估权限。因此,在协调集群上拥有广泛权限(例如 `all_access`)的用户在远程集群上也会获得这些相同的权限。 + +要使远程集群独立控制 CCS 用户接收的权限,请在远程集群上设置以下集群设置: + +```json +PUT /_cluster/settings +{ + "persistent": { + "plugins.security.ccs.ignore_source_security_roles": true + } +} +``` + +当 `plugins.security.ccs.ignore_source_security_roles` 为 `true` 时,远程集群会剥离从协调集群传播的安全角色,并仅通过自己的 `roles_mapping.yml` 配置评估访问权限。然后,您可以在每个集群上独立定义 CCS 用户权限。该设置默认为 `false`,因此现有的 CCS 部署不受影响。 + +### 限制 + +该设置具有以下限制: + +- 远程集群不会重新验证 CCS 用户的身份,因此它不会查阅 `internal_users.yml` 中的角色分配。启用此设置后,您必须使用 `roles_mapping.yml` 授予 CCS 用户对远程集群的访问权限。在 `internal_users.yml` 中使用 `opendistro_security_roles` 进行的角色分配对 CCS 用户授权没有影响。 +- 该设置仅适用于跨集群搜索请求。其他跨集群操作不受影响。 + +## 设置权限 + +要查询远程集群上的索引,用户必须具有 `READ` 或 `SEARCH` 权限。此外,当搜索请求包含查询参数 `ccs_minimize_roundtrips=false`(告诉 OpenSearch 不要最小化对远程集群的传出和传入请求)时,用户需要具有以下附加索引权限: + +``` +indices:admin/shards/search_shards +``` + +有关 `ccs_minimize_roundtrips` 参数的更多信息,请参阅搜索 API 的[参数](/api-reference/search#query-parameters)列表。 + +#### 示例 roles.yml 配置 + +```yml +humanresources: + cluster: + - CLUSTER_COMPOSITE_OPS_RO + indices: + 'humanresources': + '*': + - READ + - indices:admin/shards/search_shards # 当搜索请求包含参数设置 'ccs_minimize_roundtrips=false' 时需要。 +``` + +#### OpenSearch Dashboards 中的示例角色 + +![OpenSearch Dashboards 创建跨集群搜索角色面板](/images/security-ccs.png) + +## Docker 设置示例 + +要定义 Docker 权限,将以下示例文件保存为 `docker-compose.yml` 并运行 `docker compose up` 以在同一网络上启动两个单节点集群: + +```yml +version: '3' +services: + opensearch-ccs-node1: + image: opensearchproject/opensearch:2.12.0 + container_name: opensearch-ccs-node1 + environment: + - cluster.name=opensearch-ccs-cluster1 + - discovery.type=single-node + - bootstrap.memory_lock=true # 与下面的 memlock 设置一起,禁用交换 + - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # 最小和最大 Java 堆大小,建议都设置为系统 RAM 的 50% + - "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" # 演示配置使用的初始管理员密码 + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - opensearch-data1:/usr/share/opensearch/data + ports: + - 9200:9200 + networks: + - opensearch-net + + opensearch-ccs-node2: + image: opensearchproject/opensearch:2.12.0 + container_name: opensearch-ccs-node2 + environment: + - cluster.name=opensearch-ccs-cluster2 + - discovery.type=single-node + - bootstrap.memory_lock=true # 与下面的 memlock 设置一起,禁用交换 + - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # 最小和最大 Java 堆大小,建议都设置为系统 RAM 的 50% + - "OPENSEARCH_INITIAL_ADMIN_PASSWORD=<custom-admin-password>" # 演示配置使用的初始管理员密码 + ulimits: + memlock: + soft: -1 + hard: -1 + volumes: + - opensearch-data2:/usr/share/opensearch/data + ports: + - 9250:9200 + networks: + - opensearch-net + +volumes: + opensearch-data1: + opensearch-data2: + +networks: + opensearch-net: +``` + +集群启动后,使用以下命令验证每个集群的名称: + +```json +curl -XGET -u 'admin:<custom-admin-password>' -k 'https://localhost:9200' +{ + "cluster_name" : "opensearch-ccs-cluster1", + ... +} + +curl -XGET -u 'admin:<custom-admin-password>' -k 'https://localhost:9250' +{ + "cluster_name" : "opensearch-ccs-cluster2", + ... +} +``` + +两个集群都在 `localhost` 上运行,因此重要的标识符是端口号。在这种情况下,使用端口 9200(`opensearch-ccs-node1`)作为远程集群,端口 9250(`opensearch-ccs-node2`)作为协调集群。 + +要获取远程集群的 IP 地址,首先识别其容器 ID: + +```bash +docker ps +CONTAINER ID IMAGE PORTS NAMES +6fe89ebc5a8e opensearchproject/opensearch:2.12.0 0.0.0.0:9200->9200/tcp, 9600/tcp, 9300/tcp opensearch-ccs-node1 +2da08b6c54d8 opensearchproject/opensearch:2.12.0 9300/tcp, 0.0.0.0:9250->9200/tcp, 9600/tcp opensearch-ccs-node2 +``` + +然后获取该容器的 IP 地址: + +```bash +docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' 6fe89ebc5a8e +172.31.0.3 +``` + +在协调集群上,为每个"种子节点"添加远程集群名称和 IP 地址(带端口 9300)。在这种情况下,您只有一个种子节点: + +```json +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://localhost:9250/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-ccs-cluster1": { + "seeds": ["172.31.0.3:9300"] + } + } + } +}' +``` + +::: tip TIP +所有 cURL 请求也可以使用 OpenSearch Dashboards Dev Tools 发送。 +::: + +下图显示了使用 Dev Tools 的 cURL 请求示例。 +*用于配置跨集群搜索远程集群的 OpenSearch Dashboards Dev Tools 请求* + +在远程集群上,索引一个文档: + +```bash +curl -XPUT -k -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://localhost:9200/books/_doc/1' -d '{"Dracula": "Bram Stoker"}' +``` + +此时,跨集群搜索可以工作了。您可以使用 `admin` 用户测试它: + +```bash +curl -XGET -k -u 'admin:<custom-admin-password>' 'https://localhost:9250/opensearch-ccs-cluster1:books/_search?pretty' +{ + ... + "hits": [{ + "_index": "opensearch-ccs-cluster1:books", + "_id": "1", + "_score": 1.0, + "_source": { + "Dracula": "Bram Stoker" + } + }] +} +``` + +要继续测试,在两个集群上创建一个新用户: + +```bash +curl -XPUT -k -u 'admin:<custom-admin-password>' 'https://localhost:9200/_plugins/_security/api/internalusers/booksuser' -H 'Content-Type: application/json' -d '{"password":"password"}' +curl -XPUT -k -u 'admin:<custom-admin-password>' 'https://localhost:9250/_plugins/_security/api/internalusers/booksuser' -H 'Content-Type: application/json' -d '{"password":"password"}' +``` + +然后使用 `booksuser` 运行与之前相同的搜索: + +```json +curl -XGET -k -u booksuser:password 'https://localhost:9250/opensearch-ccs-cluster1:books/_search?pretty' +{ + "error" : { + "root_cause" : [ + { + "type" : "security_exception", + "reason" : "no permissions for [indices:admin/shards/search_shards, indices:data/read/search] and User [name=booksuser, roles=[], requestedTenant=null]" + } + ], + "type" : "security_exception", + "reason" : "no permissions for [indices:admin/shards/search_shards, indices:data/read/search] and User [name=booksuser, roles=[], requestedTenant=null]" + }, + "status" : 403 +} +``` + +注意权限错误。在远程集群上,创建一个具有适当权限的角色,并将 `booksuser` 映射到该角色: + +```bash +curl -XPUT -k -u 'admin:<custom-admin-password>' -H 'Content-Type: application/json' 'https://localhost:9200/_plugins/_security/api/roles/booksrole' -d '{"index_permissions":[{"index_patterns":["books"],"allowed_actions":["indices:admin/shards/search_shards","indices:data/read/search"]}]}' +curl -XPUT -k -u 'admin:<custom-admin-password>' -H 'Content-Type: application/json' 'https://localhost:9200/_plugins/_security/api/rolesmapping/booksrole' -d '{"users" : ["booksuser"]}' +``` + +::: tip TIP +两个集群都必须有用户角色,但只有远程集群需要角色和映射。在这种情况下,协调集群处理身份验证(即"此请求是否包含有效的用户凭据?"),而远程集群处理授权(即"此用户可以访问此数据吗?")。 +::: + +最后,重复搜索: + +```bash +curl -XGET -k -u booksuser:password 'https://localhost:9250/opensearch-ccs-cluster1:books/_search?pretty' +{ + ... + "hits": [{ + "_index": "opensearch-ccs-cluster1:books", + "_id": "1", + "_score": 1.0, + "_source": { + "Dracula": "Bram Stoker" + } + }] +} +``` + +## 裸机/虚拟机设置示例 + +如果您在裸机服务器上运行 OpenSearch 或使用虚拟机,您可以运行相同的命令,指定 OpenSearch 集群的 IP(或域)。 +例如,为了为跨集群搜索配置远程集群,找到远程节点的 IP 或远程集群的域,并运行以下命令: + +```json +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://opensearch-domain-1:9200/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-ccs-cluster2": { + "seeds": ["opensearch-domain-2:9300"] + } + } + } +}' +``` + +::: tip TIP +仅指向远程集群上的一个节点 IP 就足够了,因为集群中的所有节点都将作为节点发现过程的一部分被查询。 +::: + +您现在可以跨两个集群运行查询: + +```bash +curl -XGET -k -u 'admin:<custom-admin-password>' 'https://opensearch-domain-1:9200/opensearch-ccs-cluster2:books/_search?pretty' +{ + ... + "hits": [{ + "_index": "opensearch-ccs-cluster2:books", + "_id": "1", + "_score": 1.0, + "_source": { + "Dracula": "Bram Stoker" + } + }] +} +``` + +## Kubernetes/Helm 设置示例 +如果您使用 Kubernetes 集群部署 OpenSearch,您需要使用 `LoadBalancer` 或 `Ingress` 配置远程集群。使用以下 [Helm](/install-and-configure/install-opensearch/helm) 示例创建的 Kubernetes 服务是 `ClusterIP` 类型的,只能从集群内部访问;因此,您必须使用外部可访问的端点: + +```bash +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://opensearch-domain-1:9200/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-ccs-cluster2": { + "seeds": ["ingress:9300"] + } + } + } +}' +``` + +## 代理设置 + +您可以在运行在代理后面的集群上配置跨集群搜索。有许多方法可以配置反向代理,并有各种代理可供选择。以下示例演示了没有 TLS 终止的基本 NGINX 反向代理配置,尽管有许多代理和反向代理可供选择。要使此示例工作,OpenSearch 必须同时启用传输和 HTTP TLS 加密。有关配置 TLS 加密的更多信息,请参阅[配置 TLS 证书](/security/configuration/tls)。 + +### 先决条件 + +要使用代理模式,请满足以下先决条件: + +- 确保源集群的节点能够连接到配置的 `proxy_address`。 +- 确保代理可以将连接路由到远程集群节点。 + +### 代理配置 + +以下是 HTTP 和传输通信的基本 NGINX 配置: + +``` +stream { + upstream opensearch-transport { + server <opensearch>:9300; + } + upstream opensearch-http { + server <opensearch>:9200; + } + server { + listen 8300; + ssl_certificate /.../2.12.0/config/esnode.pem; + ssl_certificate_key /.../2.12.0/config/esnode-key.pem; + ssl_trusted_certificate /.../2.12.0/config/root-ca.pem; + proxy_pass opensearch-transport; + ssl_preread on; + } + server { + listen 443; + listen [::]:443; + ssl_certificate /.../2.12.0/config/esnode.pem; + ssl_certificate_key /.../2.12.0/config/esnode-key.pem; + ssl_trusted_certificate /.../2.12.0/config/root-ca.pem; + proxy_pass opensearch-http; + ssl_preread on; + } +} +``` + +HTTP 和传输通信的监听端口分别设置为 `443` 和 `8300`。 + +### OpenSearch 配置 + +可以使用以下命令将远程集群配置为指向 `proxy`: + +```bash +curl -k -XPUT -H 'Content-Type: application/json' -u 'admin:<custom-admin-password>' 'https://opensearch:9200/_cluster/settings' -d ' +{ + "persistent": { + "cluster.remote": { + "opensearch-remote-cluster": { + "mode": "proxy", + "proxy_address": "<remote-cluster-proxy>:8300" + } + } + } +}' +``` + +请注意[代理配置](/search-plugins/cross-cluster-search#proxy-configuration)部分中先前配置的端口 `8300`。 + +## 相关文档 + +- 要在 Event analytics 或 Observability 工作区中使用 PPL 查询远程集群,请参阅[使用可观测性应用进行跨集群搜索](/observing-your-data/cross-cluster-search)。 +- 要获取连接到集群的远程集群的信息,请参阅[远程集群信息](/api-reference/cluster-api/remote-info)。 diff --git a/i18n/zh/search-plugins/filter-search.md b/i18n/zh/search-plugins/filter-search.md new file mode 100644 index 00000000..586483b7 --- /dev/null +++ b/i18n/zh/search-plugins/filter-search.md @@ -0,0 +1,132 @@ +--- +title: 过滤结果 +--- + +# 过滤搜索结果 + +您可以使用不同的方法过滤搜索,每种方法都适用于特定场景。您可以在查询级别应用过滤器,使用 `boolean` 查询子句以及 `post_filter` 和 `aggregation` 级别过滤器,如下所示: + +- **查询级别过滤:**应用 `boolean` 查询过滤子句来过滤搜索命中和聚合,例如将结果缩小到特定类别或品牌。 +- **后置过滤:**使用 `post_filter` 根据用户选择优化搜索命中,同时保留所有聚合选项。 +- **聚合级别过滤:**根据选定的过滤器调整特定聚合,而不影响其他聚合。 + +## 使用布尔查询进行查询级别过滤 + +使用带有过滤子句的 `boolean` 查询将过滤器应用于搜索命中和聚合。例如,如果购物者从 `BrandA` 搜索 `smartphones`,布尔查询可以将结果限制为仅来自 `BrandA` 的智能手机。以下步骤指导您完成查询级别过滤。 + +1. 创建索引 `electronics` 并使用以下请求提供映射: + +```json +PUT /electronics +{ + "mappings": { + "properties": { + "brand": { "type": "keyword" }, + "category": { "type": "keyword" }, + "price": { "type": "float" }, + "features": { "type": "keyword" } + } + } +} +``` + +2. 使用以下请求向 `electronics` 索引添加文档: + +```json +POST /_bulk?refresh +{ "index": { "_index": "electronics", "_id": "1" } } +{ "brand": "BrandA", "category": "Smartphone", "price": 699.99, "features": ["5G", "Dual Camera"] } +{ "index": { "_index": "electronics", "_id": "2" } } +{ "brand": "BrandA", "category": "Laptop", "price": 1199.99, "features": ["Touchscreen", "16GB RAM"] } +{ "index": { "_index": "electronics", "_id": "3" } } +{ "brand": "BrandB", "category": "Smartphone", "price": 799.99, "features": ["5G", "Triple Camera"] } +``` + +3. 应用 `boolean` 过滤查询以使用以下请求仅显示来自 `BrandA` 的 `smartphones`: + +```json +GET /electronics/_search +{ + "query": { + "bool": { + "filter": [ + { "term": { "brand": "BrandA" }}, + { "term": { "category": "Smartphone" }} + ] + } + } +} +``` + +## 使用 `post-filter` 缩小结果范围同时保留聚合可见性 + +使用 `post_filter` 限制搜索命中,同时保留所有聚合选项。例如,如果购物者选择 `BrandA`,结果会被过滤为仅显示 `BrandA` 产品,同时在聚合中保持所有品牌选项的可见性,如以下示例请求所示: + +```json +GET /electronics/_search +{ + "query": { + "bool": { + "filter": { "term": { "category": "Smartphone" }} + } + }, + "aggs": { + "brands": { + "terms": { "field": "brand" } + } + }, + "post_filter": { + "term": { "brand": "BrandA" } + } +} +``` + +结果应在搜索命中中显示 `BrandA` 智能手机,在聚合中显示所有品牌。 + +要在用户应用过滤器时保持分面选项可见,请将 `post_filter` 与过滤聚合结合使用。有关更多信息,请参阅[在过滤期间维护分面选项](/tutorials/faceted-search/#maintaining-facet-options-during-filtering)。 + +## 使用聚合级别过滤优化聚合 + +您可以使用聚合级别过滤将过滤器应用于特定聚合,而不影响它们所属的主聚合。 + +例如,您可以使用聚合级别过滤根据选定的品牌 `BrandA` 和 `BrandB` 过滤 `price_ranges` 聚合,而不影响主 `price_ranges` 聚合,如以下示例请求所示。这会显示与所选品牌相关的价格范围,同时还显示所有产品的总体价格范围。 + +```json +GET /electronics/_search +{ + "query": { + "bool": { + "filter": { "term": { "category": "Smartphone" }} + } + }, + "aggs": { + "price_ranges": { + "range": { + "field": "price", + "ranges": [ + { "to": 500 }, + { "from": 500, "to": 1000 }, + { "from": 1000 } + ] + } + }, + "filtered_brands": { + "filter": { + "terms": { "brand": ["BrandA", "BrandB"] } + }, + "aggs": { + "price_ranges": { + "range": { + "field": "price", + "ranges": [ + { "to": 500 }, + { "from": 500, "to": 1000 }, + { "from": 1000 } + ] + } + } + } + } + } +} +``` diff --git a/i18n/zh/search-plugins/index-level-search-pruning.md b/i18n/zh/search-plugins/index-level-search-pruning.md new file mode 100644 index 00000000..ff554828 --- /dev/null +++ b/i18n/zh/search-plugins/index-level-search-pruning.md @@ -0,0 +1,79 @@ +--- +title: 索引级搜索剪枝 +--- + +# 索引级搜索剪枝 +<Badge type="tip" text="3.9 版本引入" /> + +索引级搜索剪枝允许 OpenSearch 在向分片发送请求之前排除整个索引。 + +考虑一个时间序列工作负载,其中 `logs-*` 扩展为 90 个每日索引,而仪表板查询最近 5 分钟的数据。OpenSearch 最初考虑所有 90 个索引的分片。`can_match` 阶段会过滤掉不能包含匹配文档的分片,但它通过向每个分片发送请求来确定这一点,因此搜索仍然需要每个分片的往返,即使 90 个索引中只有一个可以包含匹配的文档。 + +索引级搜索剪枝在协调节点上做出这一决定。如果索引对查询字段有记录的范围——例如,`logs-2026-06-01` 仅包含 6 月 1 日的时间戳——OpenSearch 会从最近 5 分钟的查询中排除该索引,而无需向其任何分片发送请求。 + +剪枝依赖于记录的范围,称为_字段域_。字段域包含索引中 `date` 或 `date_nanos` 字段的最小值和最大值,因此它始终是一个时间范围。对于每日索引中的 `@timestamp`,字段域是该索引中最早和最晚的时间戳。OpenSearch 将每个字段域存储在集群状态中,协调节点已将其保存在内存中,因此它可以在本地比较范围。 + +因为字段域是索引值的快照,所以它仅在索引保持写入阻止时有效。如果索引仍然接受写入,新文档可能会落在字段域之外,剪枝会跳过包含匹配文档的索引,从搜索中静默删除结果。这使得剪枝对于时间序列数据特别有用,其中较旧的索引通常在滚动后被写入阻止。 + +_分片组_是搜索可以定位的一个分片的副本集,包括主分片及其副本。搜索从每个组中的一个副本读取。例如,具有 5 个主分片和每个分片 1 个副本的索引有 10 个分片副本,但有 5 个分片组。剪枝会跳过字段域完全落在查询范围之外的索引的分片组。当索引没有字段域或其字段域不可用时,OpenSearch 会搜索分片组。 + +## 配置搜索剪枝 + +要使用剪枝,首先启用集群设置。然后为要剪枝的索引发布字段域。 + +### 启用搜索剪枝 + +索引级搜索剪枝默认禁用。要启用它,请使用集群设置 API 配置剪枝设置: + +```json +PUT _cluster/settings +{ + "persistent": { + "search.index_pruning.enabled": true, + "search.index_pruning.min_shards": 32, + "search.index_pruning.fields": ["@timestamp"] + } +} +``` + +有关剪枝设置的更多信息,请参阅[搜索设置](/install-and-configure/configuring-opensearch/search-settings#index-pruning-settings)。 + +### 发布字段域 + +您希望 OpenSearch 剪枝的每个索引都必须对查询过滤的字段有一个字段域,并且该字段必须列在 `search.index_pruning.fields` 中。要发布一个,请在 `read_only` 操作之后,将索引状态管理(ISM)[`publish_field_domains`](/im-plugin/ism/policies-operations#publish-field-domains) 操作添加到策略状态。然后,ISM 会计算该索引字段的最小值和最大值并存储它们。 + +::: warning IMPORTANT +仅为保持写入阻止的索引发布字段域。 +::: + +## 限制 + +剪枝不适用于使用时间点(PIT)的搜索或远程集群上的分片组。因此,剪枝不会减少跨集群搜索中搜索的远程分片组数量。 + +如果剪枝会排除每个分片组,OpenSearch 会搜索所有分片组。 + +## 查询约束 + +剪枝适用于配置字段上的 `must` 和 `filter` 子句中的 `range` 查询。可选和否定子句(例如 `should` 和 `must_not`)不会触发剪枝,因为不需要匹配的文档来满足它们。 + +以下查询在 `search.index_pruning.fields` 中配置了 `@timestamp` 时有资格进行剪枝。OpenSearch 解析日期数学表达式(例如 `now-2m`)一次(在请求开始时),并将该值用于它评估的每个索引: + +```json +GET logs-*/_search +{ + "query": { + "bool": { + "filter": [ + { + "range": { + "@timestamp": { + "gte": "now-2m", + "lte": "now" + } + } + } + ] + } + } +} +``` diff --git a/i18n/zh/search-plugins/ltr/advanced-functionality.md b/i18n/zh/search-plugins/ltr/advanced-functionality.md new file mode 100644 index 00000000..e109e8b7 --- /dev/null +++ b/i18n/zh/search-plugins/ltr/advanced-functionality.md @@ -0,0 +1,529 @@ +--- +title: 高级功能 +--- + +# 高级 LTR 功能 + +OpenSearch 学习排序(LTR)提供额外的功能。建议您在使用这些功能之前对 OpenSearch LTR 有基础的了解。 + +## 可重用特征 + +[构建特征](/search-plugins/ltr/working-with-features)涉及上传特征列表。为了避免在多个集合中重复常见特征,您可以维护一个可重用特征库。 + +例如,如果标题字段查询经常在您的特征集中使用,则可以使用特征 API 创建一个可重用的标题查询: + +```json + POST _ltr/_feature/titleSearch + { + "feature": + { + "params": [ + "keywords" + ], + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + } +``` + +正常的 CRUD 操作适用,因此您可以使用以下操作删除特征: + +```json +DELETE _ltr/_feature/titleSearch +``` + +要获取单个特征,您可以使用以下请求: + +```json +GET _ltr/_feature/titleSearch +``` + +要查看按名称前缀过滤的所有特征的列表,您可以使用以下请求: + +```json +GET /_ltr/_feature?prefix=t +``` + +要创建或更新特征集,您可以使用以下请求引用 `titleSearch` 特征: + +```json +POST /_ltr/_featureset/my_featureset/_addfeatures/titleSearch +``` + +这将 `titleSearch` 特征添加到 `my_featureset` 特征集中的下一个序数位置。 + +## 派生特征 + +派生特征是建立在其他特征之上的特征。这些可以表示为 [Lucene 表达式](http://lucene.apache.org/core/9_9_2/expressions/index.html?org/apache/lucene/expressions/js/package-summary.html),并通过 `"template_language": "derived_expression"` 标识。 + +此外,派生特征可以接受类型为 [`Number`](https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html) 的查询时变量,如[创建特征集](/search-plugins/ltr/working-with-features#creating-feature-sets)中所述。 + +### 脚本特征 + +脚本特征是一种[派生特征](#派生特征)。这些特征可以访问 `feature_vector`,但它们被实现为原生或 Painless OpenSearch 脚本,而不是 [Lucene 表达式](http://lucene.apache.org/core/9_9_2/expressions/index.html?org/apache/lucene/expressions/js/package-summary.html)。 + +要标识这些特征,请设置 `"template_language": "script_feature""`。自定义脚本可以通过 [Java Map](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html) 访问 `feature_vector`,如[创建特征集](/search-plugins/ltr/working-with-features#creating-feature-sets)中所述。 + +::: danger WARNING +基于脚本的特征可能会影响 OpenSearch 集群的性能,因此如果您需要高性能查询,最好避免使用它们。 +::: + +### 脚本特征参数 + +脚本特征是 LTR 上下文中的原生或 Painless 脚本。有关更多信息,请参阅 [Painless 脚本语言](/scripting/painless/)。这些脚本特征可以接受参数,如 [OpenSearch 脚本文档](/api-reference/script-apis/)中所述。在使用 LTR 脚本时,您可以覆盖参数值和名称。参数化的优先级按递增顺序如下: + +- 参数名称和值直接传递给源脚本,但不在 LTR 脚本参数中。这些不能在查询时配置。 +- 参数名称传递给 `sltr` 查询和源脚本,允许在查询时覆盖脚本参数值。 +- LTR 脚本参数名称到原生脚本参数名称的间接引用允许您在 LTR 特征定义中使用与底层原生脚本中不同的参数名称。这使您在 LTR 上下文中定义和使用脚本时具有灵活性。 + +例如,要设置一种可自定义的方式来对搜索结果中的电影进行排名,同时考虑标题匹配和其他可调因素,您可以使用以下请求: + +```json +POST _ltr/_featureset/more_movie_features +{ + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{{keywords}}" + } + } + }, + { + "name": "custom_title_query_boost", + "params": [ + "some_multiplier", + "ltr_param_foo" + ], + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "(long)params.default_param * params.feature_vector.get('title_query') * (long)params.some_multiplier * (long) params.param_foo", + "params": { + "default_param": 10, + "some_multiplier": "some_multiplier", + "extra_script_params": { + "ltr_param_foo": "param_foo" + } + } + } + } + ] + } +} +``` + +## 多特征存储 + +特征存储对应于一个独立的 LTR 系统,包括由单个索引和缓存支持的特征、特征集和模型。特征存储通常代表单个搜索问题或应用程序,例如 Wikipedia 或 Wikitravel。要在 OpenSearch 集群中使用多个特征存储,您可以使用提供的 API 创建和管理它们。 + +例如,首先创建 `wikipedia` 特征存储: + +```json +PUT _ltr/wikipedia +``` + +然后在该存储中创建特征集: + +```json +POST _ltr/wikipedia/_featureset/attempt_1 +{ + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + ] + } +} +``` + +在记录特征时,您可以使用查询 `sltr` 部分中的 `store` 参数指定特征存储,如以下示例结构所示。如果您不提供 `store` 参数,则使用默认存储来查找特征集。 + +```json +{ + "sltr": { + "_name": "logged_featureset", + "featureset": "attempt_1", + "store": "wikipedia", + "params": { + "keywords": "star" + } + } +} +``` + +要删除特征集,您可以使用以下操作: + +```json +DELETE _ltr/wikipedia/_featureset/attempt_1 +``` + +## 模型缓存 + +模型缓存插件使用内部缓存来存储编译的模型。要强制重新编译模型,您可以清除特征存储的缓存: + +```json +POST /_ltr/_clearcache +``` + +要获取特定存储的集群范围缓存统计信息,请使用以下请求: + +```json +GET /_ltr/_cachestats +``` + +您可以使用以下节点设置控制内部缓存的特性: + +``` +# 将缓存使用限制为 12 兆字节(默认为 10mb 或 max_heap/10 如果更低)ltr.caches.max_mem: 12mb +# 插入 10 分钟后驱逐缓存条目(默认为 1 小时,设置为 0 禁用)ltr.caches.expire_after_write: 10m +# 访问 10 分钟后驱逐缓存条目(默认为 1 小时,设置为 0 禁用)ltr.caches.expire_after_read: 10m +``` + +## 额外记录 + +如[记录特征](/search-plugins/ltr/logging-features)中所述,您可以使用记录扩展返回每个文档的特征值。对于原生脚本,您还可以返回额外的任意信息以及记录的特征。 + +对于原生脚本,`extra_logging` 参数被注入到脚本参数中。此参数是一个 [`Supplier<Map<String,Object>>`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html),仅在记录获取阶段提供非空 `Map<String,Object>`。您添加到此映射的任何值都会与记录的特征一起返回: + +```java +{ + @Override + public double runAsDouble() { + ... + Map<String,Object> extraLoggingMap = ((Supplier<Map<String,Object>>) getParams().get("extra_logging")).get(); + if (extraLoggingMap != null) { + extraLoggingMap.put("extra_float", 10.0f); + extraLoggingMap.put("extra_string", "additional_info"); + } + ... + } +} +``` + +如果访问了额外记录映射,它将作为记录特征的附加条目返回。记录特征的格式(包括额外记录信息)将类似于以下示例: + +```json + { + "log_entry1": [ + { + "name": "title_query", + "value": 9.510193 + }, + { + "name": "body_query", + "value": 10.7808075 + }, + { + "name": "user_rating", + "value": 7.8 + }, + { + "name": "extra_logging", + "value": { + "extra_float": 10.0, + "extra_string": "additional_info" + } + } + ] +} +``` + +## 特征分数缓存 + +默认情况下,特征分数缓存插件为模型推理和特征分数记录计算特征分数。例如,如果您编写一个查询来重新评分前 100 个文档并返回前 10 个带特征分数的文档,则插件会为模型推理计算前 100 个文档的特征分数,然后计算并记录前 10 个文档的分数。 + +以下查询显示此行为: + +```json +POST tmdb/_search +{ + "size": 10, + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "window_size" : 100, + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } + }, + "ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "rescore_index": 0 + } + } + } +} +``` + +在某些环境中,缓存模型推理的特征分数并将它们重用于记录可能更快。要启用特征分数缓存,请在作为特征分数记录目标的 `sltr` 查询中添加 `cache: "true"` 标志,如以下示例所示: + +```json +{ + "sltr":{ + "cache":true, + "params":{ + "keywords":"rambo" + }, + "model":"my_model" + } +} +``` + +## 统计信息 + +您可以使用统计 API 检索插件的整体状态和统计信息。要执行此操作,请发送以下请求: + +```json +GET /_plugins/_ltr/stats +``` + +响应包括有关集群、配置的存储、各种插件组件的缓存统计信息以及请求计数的信息: + +```json +{ + "_nodes":{ + "total":1, + "successful":1, + "failed":0 + }, + "cluster_name":"es-cluster", + "stores":{ + "_default_":{ + "model_count":10, + "featureset_count":1, + "feature_count":0, + "status":"green" + } + }, + "status":"green", + "nodes":{ + "2QtMvxMvRoOTymAsoQbxhw":{ + "cache":{ + "feature":{ + "eviction_count":0, + "miss_count":0, + "hit_count":0, + "entry_count":0, + "memory_usage_in_bytes":0 + }, + "featureset":{ + "eviction_count":0, + "miss_count":0, + "hit_count":0, + "entry_count":0, + "memory_usage_in_bytes":0 + }, + "model":{ + "eviction_count":0, + "miss_count":0, + "hit_count":0, + "entry_count":0, + "memory_usage_in_bytes":0 + } + }, + "request_total_count": 0, + "request_error_count": 0 + } + } +} +``` + +您可以使用过滤器通过发送以下请求检索单个统计信息: + +```json +GET /_plugins/_ltr/stats/{stat} +``` + +下表列出了可用的 `stat` 值。 + +统计 | 描述 +:--- | :--- +`stores` | 有关配置的特征存储的信息。 +`status` | 插件的整体状态。 +`cache` | 各种插件组件(特征、特征集和模型)的每节点缓存统计信息。 +`request_total_count` | 执行的 LTR 查询数量的每节点计数器。 +`request_error_count` | 失败的 LTR 查询数量的每节点计数器。 + +您可以通过发送以下请求将信息限制为集群中的单个节点: + +```json +GET /_plugins/_ltr/{nodeId}/stats +GET /_plugins/_ltr/{nodeId}/stats/{stat} +``` + +## TermStat 查询 +<Badge type="danger" text="实验性" /> + +`TermStatQuery` 处于实验阶段,领域特定语言(DSL)可能会随着代码的推进而改变。有关稳定的术语统计访问,请参阅 [`ExplorerQuery`](/search-plugins/ltr/feature-engineering#getting-raw-term-statistics)。 + +`TermStatQuery` 是旧版 `ExplorerQuery` 的重新设计版本。它提供了一种更清晰的方式来指定术语,并为实验提供了更大的灵活性。此查询返回与 `ExplorerQuery` 相同的数据,但允许您指定自定义 Lucene 表达式来检索所需的数据,如以下示例所示: + +```json +POST tmdb/_search +{ + "query": { + "term_stat": { + "expr": "df", + "aggr": "max", + "terms": ["rambo", "rocky"], + "fields": ["title"] + } + } +} +``` + +`expr` 参数用于指定 Lucene 表达式。此表达式按每个术语运行。表达式可以是简单的统计类型或包含多个统计类型的自定义公式,例如 `(tf * idf) / 2`。Lucene 表达式上下文中可用的统计类型列在下表中。 + +类型 | 描述 +:---| :--- +`df` | 术语的直接文档频率。例如,如果 `rambo` 在多个文档的三个电影标题中出现,则值将为 `3`。 +`idf` | 使用公式 `log((NUM_DOCS+1)/(raw_df+1)) + 1` 的逆文档频率(IDF)计算。 +`tf` | 文档的术语频率。例如,如果 `rambo` 在同一文档的电影简介中出现三次,则值将为 `3`。 +`tp` | 文档的术语位置。可以为单个术语返回多个位置,因此您应该查看 `pos_aggr` 参数的行为。 +`ttf` | 索引中术语的总术语频率。例如,如果 `rambo` 在所有文档的 `overview` 字段中总共被提及 100 次,则值将为 `100`。 + +`aggr` 参数指定要应用于从 `expr` 收集的统计信息的聚合类型。例如,如果您指定术语 `rambo` 和 `rocky`,则查询会收集两个术语的统计信息。因为您只能返回单个值,所以您需要决定使用哪个统计计算。可用的聚合类型有 `min`、`max`、`avg`、`sum` 和 `stddev`。查询还提供以下计数:`matches`(当前文档中匹配的术语数)和 `unique`(查询中传递的唯一术语数)。 + +`terms` 参数指定要收集统计信息的术语数组。仅支持单个术语,不支持短语或跨度查询。如果您的字段是分词的,您可以在数组中的一个字符串中传递多个术语。 + +`fields` 参数指定要检查指定 `terms` 的字段。如果未指定 `analyzer`,则使用每个字段配置的 `search_analyzer`。 + +可选参数列在下表中。 + +类型 | 描述 +:---| :--- +`analyzer` | 如果指定,则使用此分析器而不是每个字段配置的 `search_analyzer`。 +`pos_aggr` | 因为每个术语可以有多个位置,您可以使用此参数指定应用于术语位置的聚合。这支持与 `aggr` 参数相同的值,默认为 `avg`。 + +### 脚本注入 + +脚本注入提供了将术语统计信息注入脚本上下文的能力。在使用 `ScriptFeatures` 时,您可以传递一个带有 `terms`、`fields` 和 `analyzer` 参数的 `term_stat` 对象。然后,名为 `termStats` 的注入变量提供对自定义脚本中原始值的访问。这通过让您访问所有底层数据来启用高级特征工程。 + +要访问匹配令牌的计数,请使用 `params.matchCount.get`。要访问唯一令牌计数,请使用 `params.uniqueTerms`。 + +您可以在脚本定义中硬编码 `term_stat` 参数,或传递要在查询时设置的参数。例如,以下示例查询定义了一个特征集,其中脚本特征使用硬编码的 `term_stat` 参数: + +```json +POST _ltr/_featureset/test +{ + "featureset": { + "features": [ + { + "name": "injection", + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "params.termStats['df'].size()", + "params": { + "term_stat": { + "analyzer": "!standard", + "terms": ["rambo rocky"], + "fields": ["overview"] + } + } + } + } + ] + } +} +``` + +::: info NOTE +在本地指定分析器名称时必须以感叹号(!)为前缀。否则,它们将被视为参数查找值。 +::: + +要设置参数查找,您可以传递要从中提取值的参数名称,如以下示例请求所示: + +```json +POST _ltr/_featureset/test +{ + "featureset": { + "features": [ + { + "name": "injection", + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "params.termStats['df'].size()", + "params": { + "term_stat": { + "analyzer": "analyzerParam", + "terms": "termsParam", + "fields": "fieldsParam" + } + } + } + } + ] + } +} +``` + +或者,您可以将 `term_stat` 参数作为查询时参数传递,如以下请求所示: + +```json +POST tmdb/_search +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "_id": ["7555", "1370", "1369"] + } + }, + { + "sltr": { + "_name": "logged_featureset", + "featureset": "test", + "params": { + "analyzerParam": "standard", + "termsParam": ["troutman"], + "fieldsParam": ["overview"] + } + }} + ] + } + }, + "ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "named_query": "logged_featureset" + } + } + } +} +``` diff --git a/i18n/zh/search-plugins/ltr/core-concepts.md b/i18n/zh/search-plugins/ltr/core-concepts.md new file mode 100644 index 00000000..4b357d2b --- /dev/null +++ b/i18n/zh/search-plugins/ltr/core-concepts.md @@ -0,0 +1,137 @@ +--- +title: ML 排序核心概念 +--- + +# ML 排序核心概念 + +本指南面向有兴趣将机器学习(ML)排序功能添加到其 OpenSearch 系统的 OpenSearch 开发人员和数据科学家。 + +## 什么是 LTR + +学习排序(LTR)将 ML 应用于搜索相关性排序。这与其他经典 ML 问题不同,例如以下问题: + +- **回归:**目标是预测一个变量,例如股票价格,作为已知信息(例如员工数量或收入)的函数。输出是一个直接预测。 +- **分类:**目标是将实体分类为预定义的类别,例如盈利或不盈利。输出是一个类别。 + +LTR 的目标不是做出直接预测,而是学习一个函数(`f`),该函数可以按照最符合您对给定查询的相关性感知的顺序对文档进行排序。输出 `f` 不代表字面值,而是对文档相对有用性的预测。 + +有关 LTR 的全面信息,请参阅[搜索与其他机器学习问题有何不同?](http://opensourceconnections.com/blog/2017/08/03/search-as-machine-learning-prob/)和[什么是学习排序?](http://opensourceconnections.com/blog/2017/02/24/what-is-learning-to-rank/)。 + +## 使用判断列表定义理想排序 + +判断列表,也称为黄金集,提供了一种为关键字搜索对单个搜索结果进行评分的方法。这些列表根据您的期望表达搜索结果的理想排序。 + +例如,使用 [GitHub 上的演示](http://github.com/opensearch-project/opensearch-learning-to-rank-base/tree/main/demo/),在搜索 `Rambo` 时,判断列表可能如下所示: + +``` +grade,keywords,movie +4,Rambo,First Blood # 完全相关 +4,Rambo,Rambo +3,Rambo,Rambo III # 相当相关 +3,Rambo,Rambo First Blood Part II +2,Rambo,Rocky # 切线相关 +2,Rambo,Cobra +0,Rambo,Bambi # 完全不相关... +0,Rambo,First Daughter +``` + +此判断列表建立了查询 `Rambo` 的搜索结果的理想排序。然后可以使用诸如[归一化折损累积增益(NDCG)](https://en.wikipedia.org/wiki/Discounted_cumulative_gain)和[期望倒数排名(ERR)](https://dl.acm.org/doi/abs/10.1145/1645953.1646033)等指标来评估实际搜索结果与此理想排序的匹配程度。 + +排序函数 `f` 旨在生成与判断列表密切对齐的结果,在各种训练查询中最大化质量指标。这确保了最有用的搜索结果。 + +## 将特征理解为相关性的构建块 + +排序函数 `f` 使用输入变量来得出预测输出。例如,在股票价格预测中,输入变量可能包括公司特定数据,例如员工数量和收入。同样,在搜索相关性中,预测模型必须利用表征文档、查询及其关联的特征,例如查询关键字在字段中的[词频-逆文档频率(TF-IDF)](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)分数。 + +同样,在搜索电影的上下文中,排序函数必须使用相关特征来确定最相关的结果。这些特征可能包括: + +- 搜索关键字是否以及在何种程度上与标题字段匹配,例如 `titleScore`。 +- 搜索关键字是否以及在何种程度上与描述字段匹配,例如 `descScore`。 +- 电影的受欢迎程度,例如 `popularity`。 +- 电影的评分,例如 `rating`。 +- 搜索期间使用的关键字数量,例如 `numKeywords`。 + +排序函数将变为 `f(titleScore, descScore, popularity, rating, numKeywords)`。目标是以最大化搜索结果有用的可能性的方式使用特征。 + +例如,在 `Rambo` 用例中,直觉上 `titleScore` 会很重要。然而,对于排名第一的电影 _First Blood_,关键字 `Rambo` 可能只在描述中提到。在这种情况下,`descScore` 将变得相关。此外,`popularity` 和 `rating` 特征可以帮助区分续集和原作。如果现有特征不适用于此目的,则可以引入新特征 `isSequel`。然后可以使用这个新特征来做出更好的排序决策。 + +选择和实验特征是 LTR 的基础。使用无法帮助预测目标变量模式的特征可能导致不令人满意的搜索体验,遵循适用于任何 ML 问题的"垃圾进,垃圾出"原则。 + +## 通过记录特征完成训练集 + +当您有一组定义的特征时,下一步是用每个特征的值注释判断列表。这些值在训练过程开始时使用。例如,考虑以下判断列表: + +``` +grade,keywords,movie +4,Rambo,First Blood +4,Rambo,Rambo +3,Rambo,Rambo III +... +``` + +要完成训练集,请添加以下特征: + +``` +grade,keywords,movie,titleScore,descScore,popularity,... +4,Rambo,First Blood,0.0,21.5,100,... +4,Rambo,Rambo,42.5,21.5,95,... +3,Rambo,Rambo III,53.1,40.1,50,... +``` + +`titleScore` 表示文档标题字段中 `Rambo` 关键字的相关性分数,依此类推。 + +许多 LTR 模型熟悉支持向量机排序(SVMRank)引入的文件格式,这是一种早期的 LTR 方法。在这种格式中,查询被赋予 ID,实际文档标识符可以从训练过程中删除。特征从 `1` 开始用序数标记。对于前面的示例,文件格式将是: + +``` +4 qid:1 1:0.0 2:21.5 3:100,... +4 qid:1 1:42.5 2:21.5 3:95,... +3 qid:1 1:53.1 2:40.1 3:50,... +... +``` + +在实际系统中,您可能会记录这些值,然后稍后使用它们来注释判断列表。在其他情况下,判断列表可能来自用户分析,因此在与搜索应用程序交互时记录特征值。有关更多信息,请参阅[记录特征](/search-plugins/ltr/logging-features)。 + +## 训练排序函数 + +以下是训练排序函数的关键考虑因素: + +- **排序模型:**有几种模型可用于训练,每种模型都有优缺点: + + - **基于树的模型**(例如,LambdaMART、MART、随机森林) + - 通常最准确。 + - 大而复杂,使它们训练成本高昂。 + - [RankLib](https://sourceforge.net/p/lemur/wiki/RankLib/) 和 [XGBoost](https://github.com/dmlc/xgboost) 等工具专注于基于树的模型。 + + - **基于 SVM 的模型(SVMRank)** + - 不太准确,但训练成本较低。 + - 有关更多信息,请参阅[用于排序的支持向量机](https://www.cs.cornell.edu/people/tj/svm_light/svm_rank.html)。 + + - **线性模型** + - 对判断列表执行基本线性回归。 + - 在示例之外往往不有用。 + - 有关更多信息,请参阅[学习排序 101 — 线性模型](http://opensourceconnections.com/blog/2017/04/01/learning-to-rank-linear-models/)。 + +- **模型选择:**模型的选择不仅取决于性能,还取决于您对不同方法的经验水平和熟悉程度。 + +## 测试:模型是否良好 + +在测试排序模型的质量时,请考虑以下几点: + +- **判断列表限制:**判断列表不能包含模型在现实世界中可能遇到的每个可能的查询。重要的是对各种查询测试模型,以评估其超越训练数据的泛化能力。 +- **过拟合:**对训练数据过拟合的模型在新的、未见过的数据上表现不佳。为了避免这种情况,请考虑执行以下操作: + - 将一些判断列表保留为_测试集_,不在训练过程中使用。 + - 评估模型在测试集上的性能,这反映了它在不熟悉的场景中的表现。 + - 监控_测试 NDCG_ 指标,该指标在训练模型时应保持较高。 +- **时间泛化:**即使在部署模型之后,您也应该继续使用更新的判断列表测试模型的性能,以确保它不会过度拟合季节性或时间性情况。 + +## 现实世界的考虑 + +以下是使用学习排序插件的实际考虑: + +- **准确的判断列表:**如何创建反映用户对搜索质量感知的判断列表? +- **衡量搜索质量:**应使用哪些指标来确定搜索结果对用户是否有用? +- **数据收集基础设施:**需要什么样的基础设施来收集和记录用户行为和特征数据? +- **模型重新训练:**如何知道模型何时需要重新训练? +- **A/B 测试:**如何将新模型与当前搜索解决方案进行比较?将使用哪些关键绩效指标(KPI)来确定搜索系统的成功? + +请参阅[插件如何适应?](/search-plugins/ltr/fits-in)以了解更多关于学习排序插件的功能如何适应完整 LTR 系统的信息。 diff --git a/i18n/zh/search-plugins/ltr/faq.md b/i18n/zh/search-plugins/ltr/faq.md new file mode 100644 index 00000000..de4b76a0 --- /dev/null +++ b/i18n/zh/search-plugins/ltr/faq.md @@ -0,0 +1,19 @@ +--- +title: 常见问题 +--- + +# 常见问题 + +为了充分利用学习排序(LTR),请考虑这些有用的见解。 + +## 负分数 + +Lucene 不允许负查询分数。如果您的原始特征包含负值,这可能会有问题。为了解决这个问题,请在训练模型_之前_确认您的特征是非负的。您可以通过创建值按最小值偏移的归一化字段,或者通过将分数传递给产生大于或等于 `0` 的值的函数来实现这一点。 + +## 错误 + +如果您在使用插件时遇到错误,可以在 [`opensearch-learning-to-rank-base` 存储库](https://github.com/opensearch-project/opensearch-learning-to-rank-base/issues)中开一个问题。项目团队会定期调查和解决问题。如果您正在寻求一般支持,该问题可能会被关闭,您可能会被引导到相关的支持渠道。 + +## 进一步帮助 + +如果您需要进一步帮助,请加入[相关性 Slack 社区](https://opensourceconnections.com/slack)并参与 `#opensearch-learn-to-rank` 频道,以获得社区的指导和支持。 diff --git a/i18n/zh/search-plugins/ltr/feature-engineering.md b/i18n/zh/search-plugins/ltr/feature-engineering.md new file mode 100644 index 00000000..7a46e663 --- /dev/null +++ b/i18n/zh/search-plugins/ltr/feature-engineering.md @@ -0,0 +1,82 @@ +--- +title: 特征工程 +--- + +# 特征工程 + +以下部分描述了您在开发学习排序(LTR)解决方案时可能遇到的常见特征工程任务。 + +## 获取原始术语统计信息 + +许多 LTR 解决方案在训练中使用原始术语统计信息,例如以下内容: +- **总术语频率(`raw_ttf`):**术语在整个索引中出现的总次数。 +- **文档频率(`raw_df`):**术语出现的文档数。 +- **术语频率(`raw_tf`):**术语在特定文档中出现的次数。 +- **经典 IDF(`classic_idf`):**逆文档频率(IDF)计算 `log((NUM_DOCS+1)/(raw_df+1)) + 1`。 + +学习排序插件提供了一个 `match_explorer` 查询原语,可以为您提取这些统计信息,如以下示例所示: + +```json +POST tmdb/_search +{ + "query": { + "match_explorer": { + "type": "max_raw_df", + "query": { + "match": { + "title": "rambo rocky" + } + } + } + } +} +``` + +查询返回术语 `rambo` 和 `rocky` 之间的最高文档频率。 + +您可以使用诸如 `max`、`min`、`sum` 和 `stddev` 之类的操作与统计信息一起使用,以获取所需的信息。 + +### 术语位置统计 + +您可以在 `type` 前面加上所需的操作(`min`、`max`、`avg`)来计算术语位置的相应统计信息。如果文档中不存在术语,则结果将为 `0`。 + +可用的统计信息包括以下内容: + +- `min_raw_tp`(最小原始术语位置):此统计信息查找文档中任何搜索术语的最早位置。例如,对于查询 `dance monkey`,如果 `dance` 出现在位置 [2, 5, 9] 而 `monkey` 出现在 [1, 4],则最小值为 1。 +- `max_raw_tp`(最大原始术语位置):此统计信息查找文档中任何搜索术语的最晚位置。使用前面的示例,最大值为 9。 +- `avg_raw_tp`(平均原始术语位置):此统计信息计算任何查询术语的平均术语位置。使用前面的示例,`dance` 的平均值为 5.33 [(2+5+9)/3)],`monkey` 的平均值为 2.5 [(1+4)/2],总体平均值为 3.91。 +- `unique_terms_count`:提供查询中唯一搜索术语的计数。 + +## 文档特定特征 + +在开发 LTR 解决方案时,您可能需要合并特定于文档而不是查询与文档之间关系的特征。这些文档特定特征可以包括与受欢迎程度或最近性相关的指标。 + +`function_score` 查询提供了提取这些文档特定特征的功能。以下示例查询显示了如何使用它将 `vote_average` 字段合并为特征: + +```json +{ + "query": { + "function_score": { + "functions": [{ + "field_value_factor": { + "field": "vote_average", + "missing": 0 + } + }], + "query": { + "match_all": {} + } + } + } +} +``` + +在示例中,查询的分数由 `vote_average` 字段的值确定,该字段可能是文档受欢迎程度或质量的度量。 + +## 索引漂移 + +在使用定期更新的索引时,重要的是要考虑您观察到的趋势和模式可能不会随着时间的推移保持不变。随着用户行为、内容和其他因素的变化,您的索引可能会漂移。例如,在电子商务商店中,您可能会发现凉鞋在夏季很受欢迎,但在冬季几乎找不到。同样,在一个时间段内推动购买或参与的特征在另一个时间段可能不那么重要。 + +## 后续步骤 + +了解[记录特征分数](/search-plugins/ltr/logging-features)。 diff --git a/i18n/zh/search-plugins/ltr/fits-in.md b/i18n/zh/search-plugins/ltr/fits-in.md new file mode 100644 index 00000000..3c2f8339 --- /dev/null +++ b/i18n/zh/search-plugins/ltr/fits-in.md @@ -0,0 +1,25 @@ +--- +title: 插件范围 +--- + +# 插件范围 + +OpenSearch 的学习排序插件帮助您为应用程序搜索操作开发和使用基于机器学习(ML)的排序模型。以下部分描述了插件如何融入整个 LTR 流程。 + +## 插件的功能 + +该插件提供了开发和使用 LTR 模型的构建块,为您提供以下功能: + +1. **开发查询相关特征:**创建捕获搜索查询和文档之间关系的自定义特征。这些特征可以存储在 OpenSearch 中。 +2. **记录特征值:**记录搜索结果中返回的文档的特征值。一旦您为文档记录了特征集,就可以将这些数据与您开发的判断列表结合起来。这将为您提供一个完整的训练集,可用于测试和训练您的排序模型。然后可以使用 RankLib 或 XGBoost 等工具来开发令人满意的模型。 +3. **部署和使用模型:**将训练好的排序模型上传到插件并使用它们对搜索结果进行重排序。该插件提供了一个自定义的 OpenSearch 查询领域特定语言(DSL)原语,允许您在搜索过程中执行模型。 + +## 插件不支持的功能 + +该插件不支持创建判断列表。这是您必须自己处理的任务,因为它是特定于领域的。有关为搜索文章开发判断列表的示例方法,请参阅[维基媒体基金会博客](https://blog.wikimedia.org/2017/09/19/search-relevance-survey/)。某些领域(例如电子商务)可能更关注与转化相关的信号,而其他领域可能涉及人类相关性评估员(内部专家或众包工作者)。 + +该插件不处理模型训练或测试。这是一个离线过程,应使用适当的工具(例如 [XGBoost](https://xgboost.ai/) 和 [RankLib](https://lemurproject.org/ranklib.php))来处理。该插件与这些外部模型构建工作流集成。训练和测试排序模型可能是一项 CPU 密集型任务,需要数据科学专业知识和离线测试。大多数组织更愿意让数据科学家监督模型开发过程,而不是直接在生产环境中运行它。 + +## 后续步骤 + +了解[使用特征](/search-plugins/ltr/working-with-features)。 diff --git a/i18n/zh/search-plugins/ltr/index.md b/i18n/zh/search-plugins/ltr/index.md new file mode 100644 index 00000000..7ffbe42f --- /dev/null +++ b/i18n/zh/search-plugins/ltr/index.md @@ -0,0 +1,45 @@ +--- +title: 学习排序 +--- + +<!-- vale off --> +# 学习排序 +<!-- vale on --> + +OpenSearch 的学习排序插件使您能够使用机器学习(ML)和行为数据来微调文档的相关性。它使用来自 [XGBoost](https://xgboost.ai/) 和 [RankLib](https://lemurproject.org/ranklib.php) 库的模型。这些模型对搜索结果进行重新评分,考虑查询相关特征,例如点击数据或字段匹配,这可以进一步提高相关性。 + +::: info NOTE +当在一般意义上使用该术语时,术语_学习排序_在整个 OpenSearch 文档中缩写为 LTR。有关插件开发人员文档,请参阅 [`opensearch-learning-to-rank-base`](https://github.com/opensearch-project/opensearch-learning-to-rank-base)。 +::: + +## 入门 + +以下资源可以帮助您入门: + +- 如果您是 LTR 的新手,请从 [ML 排序核心概念](/search-plugins/ltr/core-concepts)文档开始。 +- 有关快速介绍,请参阅 [hello-ltr](https://github.com/o19s/hello-ltr) 中的演示。 +- 如果您熟悉 LTR,请从[插件范围](/search-plugins/ltr/fits-in)文档开始。 + +## 核心概念和设置 + +在实施 LTR 之前,请熟悉基础概念和架构: + +- [ML 排序核心概念](/search-plugins/ltr/core-concepts):了解学习排序背后的基本概念。 +- [插件范围](/search-plugins/ltr/fits-in):了解 LTR 如何与您的 OpenSearch 基础设施集成。 + +## 特征工程和模型开发 + +使用以下工作流创建和训练您的排序模型: + +- [特征工程](/search-plugins/ltr/feature-engineering):为您的排序模型设计有效的特征。 +- [使用特征](/search-plugins/ltr/working-with-features):创建和管理特征集。 +- [记录特征分数](/search-plugins/ltr/logging-features):收集用于模型训练的特征数据。 +- [上传训练模型](/search-plugins/ltr/training-models):构建和训练您的排序模型。 + +## 部署和高级主题 + +训练模型后,将它们部署到生产环境并探索高级功能: + +- [使用 LTR 优化搜索](/search-plugins/ltr/searching-with-your-model):在生产搜索中部署模型。 +- [高级功能](/search-plugins/ltr/advanced-functionality):探索高级 LTR 功能和技术。 +- [常见问题](/search-plugins/ltr/faq):常见问题和故障排除。 diff --git a/i18n/zh/search-plugins/ltr/logging-features.md b/i18n/zh/search-plugins/ltr/logging-features.md new file mode 100644 index 00000000..6474faa6 --- /dev/null +++ b/i18n/zh/search-plugins/ltr/logging-features.md @@ -0,0 +1,407 @@ +--- +title: 记录特征分数 +--- + +# 记录特征分数 + +需要记录特征值才能训练模型。这是学习排序插件的关键组件——当您搜索时,来自特征集的特征值会被记录,以便它们可以用于训练。这使得能够发现有效地使用该特征集预测相关性的模型。 + +<!-- vale off --> +## sltr 查询 +<!-- vale on --> + +`sltr` 查询是运行特征和评估模型的主要方法。在记录时,使用 `sltr` 查询执行每个特征查询并检索特征分数。以下示例请求显示了与 [`hello-ltr`](https://github.com/o19s/hello-ltr) 演示架构一起使用的特征集结构: + +```json +PUT _ltr/_featureset/more_movie_features +{ + "name": "more_movie_features", + "features": [ + { + "name": "body_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "overview": "{{keywords}}" + } + } + }, + { + "name": "title_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + ] +} +``` + +## 常见用例 + +以下部分描述了记录特征集的常见用例。 + +### 将特征值与判断列表连接 + +如果判断列表已经可用,您可以为每个关键字/文档对连接特征值以创建完整的训练集。例如,考虑以下判断列表: + +``` +grade,keywords,docId +4,rambo,7555 +3,rambo,1370 +3,rambo,1369 +4,rocky,4241 +``` + +需要为每个搜索词检索所有具有判断的文档的特征值,一次一个搜索词。例如,从 `rambo` 搜索开始,可以为相关文档创建过滤器,如下所示: + +```json +{ + "filter": [ + {"terms": { + "_id": ["7555", "1370", "1369"] + }} + ] +} +``` + +学习排序插件必须指向要记录的特征。插件的一部分 `sltr` 查询可用于此目的。`sltr` 查询有一个 `_name`(命名查询特征)用于引用它,引用先前创建的特征集 `more_movie_features`,并传递搜索关键字 `rambo` 和任何其他必需的参数,如以下示例查询所示: + +```json +{ + "sltr": { + "_name": "logged_featureset", + "featureset": "more_movie_features", + "params": { + "keywords": "rambo" + } + } +} +``` + +::: info NOTE +[使用 LTR 搜索](/search-plugins/ltr/searching-with-your-model)提供了用于执行模型的 `sltr` 查询。此 `sltr` 查询用作指导学习排序插件到需要记录的特征集的机制。 +::: + +为了避免影响分数,`sltr` 查询作为过滤器注入,如以下示例所示: + +```json +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "_id": [ + "7555", + "1370", + "1369" + ] + } + }, + { + "sltr": { + "_name": "logged_featureset", + "featureset": "more_movie_features", + "params": { + "keywords": "rambo" + } + } + } + ] + } + } +} +``` + +执行此查询将返回三个预期的命中。下一步是启用特征记录以引用要记录的 `sltr` 查询。 + +记录识别 `sltr` 查询,运行特征集的查询,对每个文档进行评分,并将这些分数作为每个文档的计算字段返回,如以下示例记录结构所示: + +```json +"ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "named_query": "logged_featureset" + } + } +} +``` + +日志扩展支持以下参数: + +- `name`:从每个文档获取的日志条目的名称。 +- `named_query`:对应于 `sltr` 查询的命名查询。 +- `rescore_index`:如果 `sltr` 查询在重新评分阶段,则这是重新评分列表中查询的索引。 +- `missing_as_zero`:为缺失的特征(当特征不匹配时)生成 `0`。默认为 `false`。 + + +::: info NOTE +要使日志能够定位 `sltr` 查询(无论是在正常查询阶段还是在重新评分期间),必须设置 `named_query` 或 `rescore_index`。 +::: + +完整示例请求如下: + +```json +POST tmdb/_search +{ + "query": { + "bool": { + "filter": [ + { + "terms": { + "_id": ["7555", "1370", "1369"] + } + }, + { + "sltr": { + "_name": "logged_featureset", + "featureset": "more_movie_features", + "params": { + "keywords": "rambo" + } + }} + ] + } + }, + "ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "named_query": "logged_featureset" + } + } + } +} +``` + +每个文档现在包含一个日志条目,如以下示例所示: + +```json +{ + "_index": "tmdb", + "_type": "movie", + "_id": "1370", + "_score": 20.291, + "_source": { + ... + }, + "fields": { + "_ltrlog": [ + { + "log_entry1": [ + {"name": "title_query" + "value": 9.510193}, + {"name": "body_query + "value": 10.7808075} + ] + } + ] + }, + "matched_queries": [ + "logged_featureset" + ] +} +``` + +判断列表可以与特征值连接以生成训练集。对于关键字 `rambo` 对应文档 `1370` 的行,可以添加以下内容: + +``` +> 4 qid:1 1:9.510193 2:10.7808075 +``` + +对所有查询重复此过程。 + +::: info NOTE +对于大型判断列表,建议批量记录多个查询的日志。您可以为此目的使用[多搜索](/api-reference/multi-search)功能。 +::: + +### 记录实时特征集的值 + +如果您在生产环境中运行,并且在 `sltr` 查询中执行模型,则实时模型可能类似于以下示例请求: + +```json +POST tmdb/_search +{ + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } + } +} +``` + +::: info NOTE +有关模型执行的信息,请参阅[使用 LTR 搜索](/search-plugins/ltr/searching-with-your-model)。 +::: + +要记录查询的特征值,请应用适当的记录规范以引用 `sltr` 查询,如以下示例所示: + +```json +"ext": { + "ltr_log": { + "log_specs": { + "name": "log_entry1", + "rescore_index": 0 + } + } +} +``` + +该示例在响应中记录特征,从而使用相同的特征集进行未来的模型重新训练。 + +### 修改和记录现有特征集 + +特征集可以扩展。例如,如以下示例请求所示,如果需要合并新特征(例如 `user_rating`),可以将其添加到现有特征集 `more_movie_features`: + +``` json +PUT _ltr/_feature/user_rating/_addfeatures +{ + "features": [ + "name": "user_rating", + "params": [], + "template_language": "mustache", + "template" : { + "function_score": { + "functions": { + "field": "vote_average" + }, + "query": { + "match_all": {} + } + } + } + ] +} +``` + +::: info NOTE +有关更多信息,请参阅[使用特征](/search-plugins/ltr/working-with-features)。 +::: + +执行记录时,新特征包含在输出中,如以下示例所示: + +``` json +{ + "log_entry1": [ + { + "name": "title_query", + "value": 9.510193 + }, + { + "name": "body_query", + "value": 10.7808075 + }, + { + "name": "user_rating", + "value": 7.8 + } + ] +} +``` + +### 记录建议特征集的值 + +您可以创建一个全新的特征集用于实验目的,例如 `other_movie_features`,如以下示例请求所示: + +```json +PUT _ltr/_featureset/other_movie_features +{ + "name": "other_movie_features", + "features": [ + { + "name": "cast_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "cast.name": "{{keywords}}" + } + } + }, + { + "name": "genre_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "genres.name": "{{keywords}}" + } + } + } + ] +} +``` + +通过将特征集 `other_movie_features` 附加为另一个过滤器,可以与实时生产集 `more_movie_features` 一起记录,如以下示例请求所示: + +```json +POST tmdb/_search +{ +"query": { + "bool": { + "filter": [ + { "sltr": { + "_name": "logged_featureset", + "featureset": "other_movie_features", + "params": { + "keywords": "rambo" + } + }}, + {"match": { + "_all": "rambo" + }} + ] + } +}, +"rescore": { + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } +} +} +``` + +您可以继续根据需要添加任意数量的特征集进行记录。 + +## 记录场景 + +一旦您掌握了基础知识,就可以考虑一些现实生活中的特征记录场景。 + +首先,记录用于从用户分析中开发判断列表,以在交互的精确时间捕获特征的确切值。例如,您可能想知道用户交互精确时间的最近性、标题分数和其他值。这将帮助您分析在训练时哪些特征或因素具有相关性。为此,您可以为将来的实验构建一个综合特征集。 + +其次,记录可用于重新训练您已有信心的模型。您可能希望使模型与不断变化的索引保持同步,因为模型会随着时间的推移失去效果。您可能已经有 A/B 测试或正在监控业务指标,并注意到模型性能的逐渐下降。 + +第三,记录在模型开发期间使用。您可能有一个判断列表,但想要与 OpenSearch 的本地副本进行大量迭代。这允许对新特征进行广泛的实验,根据需要向特征集添加和删除它们。虽然此过程可能导致与实时索引略有不同步,但目标是达到一组令人满意的模型参数。一旦实现这一点,就可以使用生产数据训练模型以确认性能水平保持可接受。 + +## 后续步骤 + +在[上传训练模型](/search-plugins/ltr/training-models)文档中了解有关训练模型的更多信息。 diff --git a/i18n/zh/search-plugins/ltr/searching-with-your-model.md b/i18n/zh/search-plugins/ltr/searching-with-your-model.md new file mode 100644 index 00000000..344960fa --- /dev/null +++ b/i18n/zh/search-plugins/ltr/searching-with-your-model.md @@ -0,0 +1,95 @@ +--- +title: 使用 LTR 优化搜索 +--- + +# 使用 LTR 优化搜索 + +训练模型后,您可以使用 `sltr` 查询来执行它。但是,不建议直接在整个索引上运行查询,因为它可能是 CPU 密集型的,并且会影响 OpenSearch 集群的性能。该查询允许您将训练的模型应用于搜索结果,如以下示例所示: + +```json + POST tmdb/_search + { + "query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } +``` + +## 重新评分前 N 个结果 + +要更有效地执行模型,您可以使用内置的重新评分功能将模型应用于基线相关性查询的前 N 个结果,如以下示例查询所示: + +```json + POST tmdb/_search + { + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "window_size": 1000, + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model" + } + } + } + } + } +``` + +首先对术语 `rambo` 执行 `match`,然后将 `my_model` 应用于前 1,000 个结果。此基线查询用于生成初始结果集,然后使用默认相似性 BM25 概率排名框架对这些结果进行评分以计算相关性分数。 + +## 重新评分特征子集 + +您可以通过在 `sltr` 查询中指定 `active_features` 来选择性地对特征子集进行评分,如以下示例所示。这允许您将模型的评分集中在所选特征上,而任何未指定的特征都标记为缺失。您只需要指定与 `active_features` 相关的 `params`。如果您请求的特征名称不是分配的特征集的一部分,则查询会抛出错误。 + +```json + POST tmdb/_search + { + "query": { + "match": { + "_all": "rambo" + } + }, + "rescore": { + "window_size": 1000, + "query": { + "rescore_query": { + "sltr": { + "params": { + "keywords": "rambo" + }, + "model": "my_model", + "active_features": ["title_query"] + } + } + } + } + } +``` + +应用 `my_model` 模型,但仅对 `title_query` 特征进行评分。 + +## 将 `sltr` 与其他 OpenSearch 功能结合使用 + +`sltr` 查询可以与以下 OpenSearch 功能和功能集成,以创建更复杂和定制的搜索解决方案,超越将模型应用于您的结果: + +- 在应用模型之前使用 OpenSearch 过滤器根据业务规则过滤结果 +- 链接多个重新评分以优化结果的相关性 +- 使用 `sltr` 重新评分一次以解决相关性问题,第二次处理业务问题 +- 在基线查询中降低相关但低质量内容的权重,以防止其被重新评分 + +## 后续步骤 + +了解[高级功能](/search-plugins/ltr/advanced-functionality)。 diff --git a/i18n/zh/search-plugins/ltr/training-models.md b/i18n/zh/search-plugins/ltr/training-models.md new file mode 100644 index 00000000..00ce9ad9 --- /dev/null +++ b/i18n/zh/search-plugins/ltr/training-models.md @@ -0,0 +1,330 @@ +--- +title: 上传训练模型 +--- + +# 上传训练模型 + +虽然模型训练在学习排序插件之外进行,但您可以使用该插件[记录特征分数](/search-plugins/ltr/logging-features)。训练模型后,您可以以可用的序列化格式(例如 RankLib 和 XGBoost)将其上传到插件。 + +## RankLib 模型训练 + +特征记录过程生成一个 RankLib 可消费的判断文件。在以下判断文件中,ID 为 1 的查询 `rambo` 包括为一组文档记录的特征 1(标题 `TF*IDF` 分数)和 2(描述 `TF*IDF` 分数): + +``` +4 qid:1 1:9.8376875 2:12.318446 # 7555 rambo +3 qid:1 1:10.7808075 2:9.510193 # 1370 rambo +3 qid:1 1:10.7808075 2:6.8449354 # 1369 rambo +3 qid:1 1:10.7808075 2:0.0 # 1368 rambo +``` + +可以使用以下命令调用 RankLib 库: + + ``` + cmd = "java -jar RankLib-2.8.jar -ranker %s -train%rs -save %s -frate 1.0" % (whichModel, judgmentsWithFeaturesFile, modelOutput) +``` + +`judgmentsWithFeatureFile` 是提供给 RankLib 进行训练的输入。可以传递其他参数。有关更多信息,请参阅 [RankLib 文档](https://sourceforge.net/p/lemur/wiki/RankLib/)。 + +RankLib 以自己的序列化格式输出模型。如以下示例所示,LambdaMART 模型是回归树的集成: + +``` +## LambdaMART +## No. of trees = 1000 +## No. of leaves = 10 +## No. of threshold candidates = 256 +## Learning rate = 0.1 +## Stop early = 100 + + <ensemble> + <tree id="1" weight="0.1"> + <split> + <feature> 2 </feature> + ... +``` + +在 RankLib 模型中,集成中的每棵树检查特征值,根据这些特征值做出决策,并输出相关性分数。特征按其从 1 开始的序数位置引用,对应于原始特征集中的第 0 个特征。RankLib 在模型训练期间不使用特征名称。 + +### 其他 RankLib 模型 + +RankLib 是一个除了 LambdaMART 之外还实现了多种其他模型类型的库,例如 MART、RankNet、RankBoost、AdaRank、坐标上升、ListNet 和随机森林。每种模型都有自己的参数集和训练过程。 + +例如,RankNet 模型是一个神经网络,它学习预测一个文档比另一个文档更相关的概率。该模型使用成对损失函数进行训练,该函数将两个文档的预测相关性与实际相关性进行比较。模型以类似于以下示例的格式序列化: + +``` +## RankNet +## Epochs = 100 +## No. of features = 5 +## No. of hidden layers = 1 +... +## Layer 1: 10 neurons +1 2 +1 +10 +0 0 -0.013491530393429608 0.031183180961270988 0.06558792020112071 -0.006024092627087733 0.05729619574181734 -0.0017010373987742411 0.07684848696852313 -0.06570387602230028 0.04390491141617467 0.013371636736099578 +... +``` + +所有这些模型都可以与学习排序插件一起使用,前提是模型以 RankLib 格式序列化。 + +## XGBoost 模型训练 + +与 RankLib 模型不同,XGBoost 模型以特定于梯度提升决策树的格式序列化,如以下示例所示: + +```json + [ { "nodeid": 0, "depth": 0, "split": "tmdb_multi", "split_condition": 11.2009, "yes": 1, "no": 2, "missing": 1, "children": [ + { "nodeid": 1, "depth": 1, "split": "tmdb_title", "split_condition": 2.20631, "yes": 3, "no": 4, "missing": 3, "children": [ + { "nodeid": 3, "leaf": -0.03125 }, + ... +``` + +## XGBoost 参数 + +可以为 XGBoost 模型指定可选参数。这些参数指定为对象,决策树在 `splits` 字段中指定。支持的参数包括 `objective`,它定义模型学习目标,如 [XGBoost 文档](https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters)中所述。此参数可以转换最终的模型预测。支持的值包括 `binary:logistic`、`binary:logitraw`、`rank:ndcg`、`rank:map`、`rank:pairwise`、`reg:linear` 和 `reg:logistic`。 + +## 简单线性模型 + +机器学习(ML)模型(例如支持向量机(SVM))为每个特征输出线性权重。LTR 模型支持以简单格式表示这些线性权重,例如从 SVM 或线性回归模型学习的权重。在以下示例输出中,权重表示特征在模型预测中的相对重要性: + +```json +{ + "title_query" : 0.3, + "body_query" : 0.5, + "recency" : 0.1 +} +``` + +## 特征归一化 + +特征归一化用于将特征值转换为一致的范围,通常在 0 和 1 之间或 -1 和 1 之间。这在训练阶段完成,以更好地了解每个特征的相对影响。某些模型,尤其是线性模型(如 SVMRank),依赖于归一化才能正常运行。 + +## 模型上传过程 + +训练模型后,下一步是使其可用于搜索操作。这涉及将模型上传到学习排序插件。上传模型时,您必须提供以下信息: + +- 训练期间使用的特征集 +- 模型类型,例如 RankLib 或 XGBoost +- 模型内容 + +以下示例请求显示如何上传使用 `more_movie_features` 特征集训练的 RankLib 模型: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_ranklib_model", + "model": { + "type": "model/ranklib", + "definition": "## LambdaMART\n + ## No. of trees = 1000 + ## No. of leaves = 10 + ## No. of threshold candidates = 256 + ## Learning rate = 0.1 + ## Stop early = 100 + + <ensemble> + <tree id=\"1\" weight=\"0.1\"> + <split> + <feature> 2 </feature> + ... + " + } + } + } +``` + +以下示例请求显示如何上传使用 `more_movie_features` 特征集训练的 XGBoost 模型: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_xgboost_model", + "model": { + "type": "model/xgboost+json", + "definition": "[ { \"nodeid\": 0, \"depth\": 0, \"split\": \"tmdb_multi\", \"split_condition\": 11.2009, \"yes\": 1, \"no\": 2, \"missing\": 1, \"children\": [ + { \"nodeid\": 1, \"depth\": 1, \"split\": \"tmdb_title\", \"split_condition\": 2.20631, \"yes\": 3, \"no\": 4, \"missing\": 3, \"children\": [ + { \"nodeid\": 3, \"leaf\": -0.03125 }, + ..." + } + } + } +``` + +以下示例请求显示如何上传带参数的使用 `more_movie_features` 特征集训练的 XGBoost 模型: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_xgboost_model", + "model": { + "type": "model/xgboost+json", + "definition": "{ + \"objective\": \"reg:logistic\", + \"splits\": [ { \"nodeid\": 0, \"depth\": 0, \"split\": \"tmdb_multi\", \"split_condition\": 11.2009, \"yes\": 1, \"no\": 2, \"missing\": 1, \"children\": [ + { \"nodeid\": 1, \"depth\": 1, \"split\": \"tmdb_title\", \"split_condition\": 2.20631, \"yes\": 3, \"no\": 4, \"missing\": 3, \"children\": [ + { \"nodeid\": 3, \"leaf\": -0.03125 }, + ... + ] + }" + } + } + } +```` + +以下示例请求显示如何上传使用 `more_movie_features` 特征集训练的简单线性模型: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_linear_model", + "model": { + "type": "model/linear", + "definition": """ + { + "title_query" : 0.3, + "body_query" : 0.5, + "recency" : 0.1 + } + """ + } + } + } +``` + +## 创建带特征归一化的模型 + +特征归一化是一个关键的预处理步骤,可以在模型评估之前应用。LTR 支持两种类型的特征归一化:最小-最大归一化和标准归一化。 + +### 标准归一化 + +标准归一化按如下方式转换特征: + +- 将均值映射到 0 +- 将高于均值一个标准差映射到 1 +- 将低于均值一个标准差映射到 -1 + +以下示例请求显示如何创建带标准特征归一化的模型: + +```json + POST _ltr/_featureset/more_movie_features/_createmodel + { + "model": { + "name": "my_linear_model", + "model": { + "type": "model/linear", + "feature_normalizers": { + "release_year": { + "standard": { + "mean": 1970, + "standard_deviation": 30 + } + } + }, + "definition": """ + { + "release_year" : 0.3, + "body_query" : 0.5, + "recency" : 0.1 + } + """ + } + } + } +``` + +### 最小-最大归一化 + +最小-最大归一化将特征缩放到固定范围,通常在 0 和 1 之间。最小-最大归一化按如下方式转换特征: + +- 将指定的最小值映射到 0 +- 将指定的最大值映射到 1 +- 在 0 和 1 之间线性缩放值 + +以下示例请求显示如何实现最小-最大归一化: + +```json + "feature_normalizers": { + "vote_average": { + "min_max": { + "minimum": 0, + "maximum": 10 + } + } + } +``` + +## 模型与特征集的独立性 + +模型最初是参考特征集创建的。创建后,它们作为独立的顶级实体存在。 + +### 访问模型 + +要检索模型,请使用 GET 请求: + +``` +GET _ltr/_model/my_linear_model +``` + +要删除模型,请使用 DELETE 请求: + +``` +DELETE _ltr/_model/my_linear_model +``` + +::: info NOTE +模型名称必须在所有特征集中全局唯一。 +::: + +### 模型持久性 + +创建模型时,会复制其特征。这可以防止对原始特征的更改影响现有模型或模型生产。例如,如果用于创建模型的特征集被删除,您仍然可以访问和使用该模型。 + +### 模型响应 + +检索模型时,您会收到一个响应,其中包括用于创建它的特征,如以下示例所示: + +```json + { + "_index": ".ltrstore", + "_type": "store", + "_id": "model-my_linear_model", + "_version": 1, + "found": true, + "_source": { + "name": "my_linear_model", + "type": "model", + "model": { + "name": "my_linear_model", + "feature_set": { + "name": "more_movie_features", + "features": [ + { + "name": "body_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "overview": "{{keywords}}" + } + } + }, + { + "name": "title_query", + "params": [ + "keywords" + ], + "template": { + "match": { + "title": "{{keywords}}" + } + } + } + ]}}} +``` + +## 后续步骤 + +了解[使用 LTR 搜索](/search-plugins/ltr/searching-with-your-model)。 diff --git a/i18n/zh/search-plugins/ltr/working-with-features.md b/i18n/zh/search-plugins/ltr/working-with-features.md new file mode 100644 index 00000000..1beaf58d --- /dev/null +++ b/i18n/zh/search-plugins/ltr/working-with-features.md @@ -0,0 +1,254 @@ +--- +title: 使用特征 +--- + +# 使用特征 + +以下部分描述了学习排序插件提供的特定功能。此信息将帮助您为学习排序(LTR)系统构建和上传特征。有关学习排序插件的角色和功能的更多信息,请参阅 [ML 排序核心概念](/search-plugins/ltr/core-concepts)和[插件范围](/search-plugins/ltr/fits-in)。 + +## 了解特征在学习排序插件中的作用 + +学习排序插件将_特征_定义为 _OpenSearch 查询_。当您使用搜索词和其他相关参数执行 OpenSearch 查询时,结果分数是可以在训练数据中使用的值。例如,特征可能包括字段上的基本 `match` 查询,例如 `title`: + +```json +{ + "query": { + "match": { + "title": "{{keywords}}" + } + } +} +``` + +除了简单的基于查询的特征外,您还可以使用文档属性(例如 `popularity`)作为特征。例如,您可以使用 function score 查询来获取平均电影评分: + +```json +{ + "query": { + "function_score": { + "functions": { + "field": "vote_average" + }, + "query": { + "match_all": {} + } + } + } +} +``` + +另一个例子是基于位置的查询,例如地理距离过滤器: + +```json +{ + "query": { + "bool" : { + "must" : { + "match_all" : {} + }, + "filter" : { + "geo_distance" : { + "distance" : "200km", + "pin.location" : { + "lat" : "{{users_lat}}", + "lon" : "{{users_lon}}" + } + } + } + } + } +} +``` + +这些类型的查询是您正在训练的排序 `f` 函数的构建块,它们在数学上组合以确定相关性分数。 + +## 在 LTR 查询中使用 Mustache 模板 + +LTR 查询中的特征使用 Mustache 模板。这允许您将变量插入搜索查询中。例如,您可以有一个使用 `{{keywords}}` 插入搜索词的查询。或者您可以使用 `{{users_lat}}` 和 `{{users_lon}}` 来包含位置。这使您能够灵活地个性化搜索。 + +## 上传和命名特征 + +学习排序插件使您能够创建和修改特征。定义特征后,您可以记录它们以用于模型训练。通过将记录的特征数据与判断列表结合,您可以训练模型。模型准备好后,您可以上传它,然后将其应用于搜索查询。 + +## 初始化默认特征存储 + +学习排序插件使用特征存储来存储有关特征和模型的元数据。通常,每个主要搜索实现有一个特征存储,例如 [Wikipedia](http://wikipedia.org) 与 [Wikitravel](http://wikitravel.org) 相比。 + +对于大多数用例,您可以使用默认特征存储并避免管理多个特征存储。要初始化默认特征存储,请运行以下请求: + +``` +PUT _ltr +``` + +如果需要从头开始,可以使用以下操作删除默认特征存储: + +``` +DELETE _ltr +``` + +::: danger WARNING +删除特征存储会删除所有现有的特征和模型数据。 +::: + +本指南的其余部分使用默认特征存储。 + +## 使用特征和特征集 + +_特征集_是已分组在一起的特征集合。您可以使用特征集记录多个特征值以进行离线训练。创建新模型时,您将相关特征集复制到模型定义中。 + +## 创建特征集 + +要创建特征集,您可以发送 POST 请求。创建特征集时,您提供一个名称和一个可选的特征列表,如以下示例请求所示: + +```json +POST _ltr/_featureset/more_movie_features +{ + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{{keywords}}" + } + } + }, + { + "name": "title_query_boost", + "params": [ + "some_multiplier" + ], + "template_language": "derived_expression", + "template": "title_query * some_multiplier" + }, + { + "name": "custom_title_query_boost", + "params": [ + "some_multiplier" + ], + "template_language": "script_feature", + "template": { + "lang": "painless", + "source": "params.feature_vector.get('title_query') * (long)params.some_multiplier", + "params": { + "some_multiplier": "some_multiplier" + } + } + } + ] + } +} +``` + +## 管理特征集 + +要获取特定的特征集,您可以使用以下请求: + +``` +GET _ltr/_featureset/more_movie_features +``` + +要查看所有定义的特征集的列表,您可以使用以下请求: + +``` +GET _ltr/_featureset +``` + +如果您有许多特征集,可以使用前缀过滤列表,如以下示例请求所示: + +``` +GET _ltr/_featureset?prefix=mor +``` + +这仅返回名称以 `mor` 开头的特征集。 + +如果需要重新开始,可以使用以下请求删除特征集: + +``` +DELETE _ltr/_featureset/more_movie_features +``` + +## 验证特征 + +添加新特征时,您应该验证特征是否按预期工作。您可以通过在特征创建请求中添加 `validation` 块来执行此操作。这允许学习排序插件在添加特征之前运行查询,及早发现任何问题。如果您不运行此验证,您可能直到后来才发现查询(虽然是有效的 JSON)包含格式错误的 OpenSearch 查询。 + +要运行验证,您可以指定测试参数和要使用的索引,如以下示例验证块所示: + +```json +"validation": { + "params": { + "keywords": "rambo" + }, + "index": "tmdb" +}, +``` + +将验证块放在特征集定义旁边。在以下示例中,`match` 查询格式不正确(Mustache 模板中缺少花括号)。验证失败,返回错误: + +```json +{ + "validation": { + "params": { + "keywords": "rambo" + }, + "index": "tmdb" + }, + "featureset": { + "features": [ + { + "name": "title_query", + "params": [ + "keywords" + ], + "template_language": "mustache", + "template": { + "match": { + "title": "{{keywords" + } + } + } + ] + } +} +``` + +## 扩展特征集 + +您最初可能不知道哪些特征最有用。在这些情况下,您可以稍后向现有特征集添加新特征以进行记录和模型评估。例如,如果要创建 `user_rating` 特征,可以使用特征集追加 API,如以下示例请求所示: + +```json +POST /_ltr/_featureset/my_featureset/_addfeatures +{ + "features": [{ + "name": "user_rating", + "params": [], + "template_language": "mustache", + "template" : { + "function_score": { + "functions": { + "field": "vote_average" + }, + "query": { + "match_all": {} + } + } + } + }] +} +``` + +## 强制唯一特征名称 + +学习排序插件强制每个特征具有唯一名称。这是因为某些模型训练库按名称引用特征。在前面的示例中,您不能添加新的 `user_rating` 特征而不导致错误,因为该特征名称已被使用。 + +## 将特征集视为列表 + +特征集更像是有序列表而不是简单的集合。每个特征都有名称和序数位置。一些 LTR 训练应用程序(例如 RankLib)按其序数位置引用特征(例如,第 1 个特征、第 2 个特征)。其他可能使用特征名称。在处理记录的特征时,您可能需要同时处理序数和名称,因为序数会被保留以维护列表顺序。 + +## 后续步骤 + +了解[特征工程](/search-plugins/ltr/feature-engineering)和[高级功能](/search-plugins/ltr/advanced-functionality)。 diff --git a/i18n/zh/search-plugins/search-pipelines/agentic-context-processor.md b/i18n/zh/search-plugins/search-pipelines/agentic-context-processor.md new file mode 100644 index 00000000..a22a9992 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/agentic-context-processor.md @@ -0,0 +1,97 @@ +--- +title: 代理上下文 +--- + +# 代理上下文处理器 +<Badge type="tip" text="3.3 版本引入" /> + +`agentic_context` 搜索响应处理器将代理执行上下文信息添加到搜索响应扩展中。此处理器与[代理查询翻译器](/search-plugins/search-pipelines/agentic-query-translator-processor)配合使用,以公开代理的查询翻译过程并维护对话连续性: + +1. 处理器从管道处理上下文中检索代理上下文信息。 +2. 根据处理器配置,它有选择地在响应中包含代理步骤摘要和查询领域特定语言(DSL)查询。 +3. 当可用时,始终包含内存 ID 以保持对话连续性。 +4. 上下文信息被添加到搜索响应扩展中。 +5. 类型验证确保所有上下文属性都是字符串。 + +此处理器适用于对话代理和流程代理,但可用的上下文信息因代理类型而异。流程代理仅提供 `dsl_query`(生成的 DSL),而对话代理提供 `dsl_query`、`memory_id` 和 `agent_steps_summary`。有关更多信息,请参阅[代理类型](/vector-search/ai-search/agentic-search/index/#agent-types)。 + +## 请求正文字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`agent_steps_summary` | 布尔值 | 是否在响应中包含代理的执行步骤摘要。仅适用于对话代理。可选。默认为 `false`。 +`dsl_query` | 布尔值 | 是否在响应中包含生成的 DSL 查询。适用于对话代理和流程代理。可选。默认为 `false`。 + +## 响应字段 + +启用后,处理器将以下字段添加到搜索响应扩展中。 + +字段 | 描述 +:--- | :--- +`agent_steps_summary` | 代理翻译自然语言查询所采取的步骤摘要(当 `agent_steps_summary` 为 `true` 时包含)。仅适用于对话代理。 +`memory_id` | 用于跨查询维护上下文的对话内存 ID。仅适用于对话代理。仅当您想继续之前的对话时,才在 `agentic` 查询中提供此参数。 +`dsl_query` | 已执行的生成 DSL 查询(当 `dsl_query` 为 `true` 时包含)。适用于对话代理和流程代理。 + +## 示例 + +以下示例请求创建一个带有 `agentic_context` 响应处理器的搜索管道: + +```json +PUT /_search/pipeline/agentic_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "your-agent-id" + } + } + ], + "response_processors": [ + { + "agentic_context": { + "agent_steps_summary": true, + "dsl_query": true + } + } + ] +} +``` + +使用配置的管道执行搜索: + +```json +POST /your-index/_search?search_pipeline=agentic_search_pipeline +{ + "query": { + "agentic": { + "query_text": "Show me shoes in white color", + "memory_id": "your memory id" + } + } +} +``` + +响应包含代理翻译查询所采取的步骤、内存 ID 和重写的 DSL 查询: + +```json +{ + "took": 15, + "hits": { + "_shards": {...}, + "hits": [...] + }, + "ext": { + "agent_steps_summary": "I have these tools available: [ListIndexTool, IndexMappingTool, query_planner_tool]\\nFirst I used: ListIndexTool — input: \"\"; context gained: \"Discovered products-index which seems relevant for products and pricing context\"\\nSecond I used: IndexMappingTool — input: \"products-index\"; context gained: \"Confirmed presence of category and price fields in products-index\"\\nThird I used: query_planner_tool — qpt.question: \"Show me shoes that cost exactly 100 dollars.\"; index_name_provided: \"products-index\"\\nValidation: qpt output is valid and accurately reflects the request for shoes priced at 100 dollars.", + "memory_id": "WVhHiJkBnqovov2plcDH", + "dsl_query": "{\"query\":{\"bool\":{\"filter\":[{\"term\":{\"category\":\"shoes\"}},{\"term\":{\"price\":100.0}}]}}}" + } +} +``` + +## 相关文档 + +- [代理搜索](/vector-search/ai-search/agentic-search/index/) +- [代理查询](/query-dsl/specialized/agentic) +- [代理查询翻译器处理器](/search-plugins/search-pipelines/agentic-query-translator-processor) diff --git a/i18n/zh/search-plugins/search-pipelines/agentic-query-translator-processor.md b/i18n/zh/search-plugins/search-pipelines/agentic-query-translator-processor.md new file mode 100644 index 00000000..f45dd082 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/agentic-query-translator-processor.md @@ -0,0 +1,142 @@ +--- +title: 代理查询翻译器 +--- + +# 代理查询翻译器处理器 +<Badge type="tip" text="3.2 版本引入" /> + +`agentic_query_translator` 搜索请求处理器通过使用机器学习(ML)代理将用户查询翻译为 OpenSearch 查询领域特定语言(DSL)查询来启用自然语言搜索。它与[代理搜索查询](/vector-search/ai-search/agentic-search/index/)配合使用,提供对话式搜索功能: + +1. 处理器将用户的自然语言查询发送到指定的 ML 代理。 +2. 代理将查询翻译为 OpenSearch DSL。 +3. 原始查询被生成的 DSL 查询替换。 + +::: info NOTE +此处理器仅适用于作为顶级查询的 `agentic` 查询类型。 +::: + +## 先决条件 + +在使用 `agentic_query_translator` 处理器之前,您必须配置对话代理或流程代理。有关更多信息,请参阅[代理](/ml-commons-plugin/agents-tools/agents/)。 + +## 请求正文字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 必需/可选 | 描述 +:--- | :--- | :--- | :--- +`agent_id` | 字符串 | 必需 | 将自然语言查询翻译为 DSL 查询的 ML 代理的 ID。 +`embedding_model_id` | 字符串 | 可选 | 生成向量嵌入以使用 `neural` 查询进行语义搜索的嵌入模型的 ID。此参数优先于代理配置中指定的 `embedding_model_id`。有关更多信息,请参阅[配置代理进行语义搜索](/vector-search/ai-search/agentic-search/neural-search/)。 + +## 示例 + +以下示例请求创建一个带有 `agentic_query_translator` 处理器的搜索管道: + +```json +PUT /_search/pipeline/agentic_search_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "your-agent-id-here" + } + } + ] +} +``` + +要启用语义搜索功能,您可以选择为将查询转换为向量嵌入的文本嵌入模型指定 `embedding_model_id`: + +```json +PUT /_search/pipeline/agentic_search_pipeline +{ + "request_processors": [ + { + "agentic_query_translator": { + "agent_id": "your-agent-id-here", + "embedding_model_id": "your-embedding-model-id" + } + } + ] +} +``` + +## 用法 + +要使用处理器,请运行 `agentic` 查询: + +```json +POST /your-index/_search?search_pipeline=agentic_search_pipeline +{ + "query": { + "agentic": { + "query_text": "Show me shoes in white color" + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 6031, + "timed_out": false, + "_shards": { + "total": 8, + "successful": 8, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 8, + "relation": "eq" + }, + "max_score": 0.0, + "hits": [ + { + "_index": "products-index", + "_id": "43", + "_score": 0.0, + "_source": { + "product_name": "Nike Air Max white", + "description": "Red cushioned sneakers", + "price": 140.0, + "currency": "USD", + "in_stock": true, + "color": "white", + "size": "10", + "product_id": "P6001", + "category": "shoes", + "brand": "Nike" + } + }, + { + "_index": "products-index", + "_id": "45", + "_score": 0.0, + "_source": { + "product_name": "Adidas Superstar white", + "description": "Classic black sneakers", + "price": 100.0, + "currency": "USD", + "in_stock": true, + "color": "white", + "size": "8", + "product_id": "P6003", + "category": "shoes", + "brand": "Adidas" + } + } + ] + } +} +``` + +## 相关文档 + +- [代理搜索查询](/vector-search/ai-search/agentic-search/index/) +- [代理查询](/query-dsl/specialized/agentic) +- [配置代理进行语义搜索](/vector-search/ai-search/agentic-search/neural-search/) +- [代理上下文处理器](/search-plugins/search-pipelines/agentic-context-processor) diff --git a/i18n/zh/search-plugins/search-pipelines/debugging-search-pipeline.md b/i18n/zh/search-plugins/search-pipelines/debugging-search-pipeline.md new file mode 100644 index 00000000..8ec64578 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/debugging-search-pipeline.md @@ -0,0 +1,219 @@ +--- +title: 调试搜索管道 +--- + +# 调试搜索管道 + +`verbose_pipeline` 参数提供有关搜索管道中搜索请求、搜索响应和搜索阶段处理器的数据流和转换的详细信息。它有助于对管道进行故障排除和优化,并确保处理搜索请求和响应的透明度。 + +## 启用调试 + +要启用管道调试,请在搜索请求中指定 `verbose_pipeline=true` 作为查询参数。此功能适用于所有三种搜索管道方法: + +- [默认搜索管道](#默认搜索管道) +- [特定搜索管道](#特定搜索管道) +- [临时搜索管道](#临时搜索管道) + +### 默认搜索管道 + +要将 `verbose_pipeline` 与默认搜索管道一起使用,请在索引设置中将管道设置为默认值,并在查询中包含 `verbose_pipeline=true`: + +```json +PUT /my_index/_settings +{ + "index.search.default_pipeline": "my_pipeline" +} +``` + +```json +GET /my_index/_search?verbose_pipeline=true +``` + +有关默认搜索管道的更多信息,请参阅[为索引中的所有请求设置默认管道](/search-plugins/search-pipelines/using-search-pipeline#default-search-pipeline)。 + +### 特定搜索管道 + +要将 `verbose_pipeline` 与特定搜索管道一起使用,请指定管道 ID 并在查询中包含 `verbose_pipeline=true`: + +```json +GET /my_index/_search?search_pipeline=my_pipeline&verbose_pipeline=true +``` + +有关使用特定搜索管道的更多信息,请参阅[为请求指定现有管道](/search-plugins/search-pipelines/using-search-pipeline#specifying-an-existing-search-pipeline-for-a-request)。 + +### 临时搜索管道 + +要将 `verbose_pipeline` 与临时搜索管道一起使用,请直接在请求正文中定义管道并在查询中包含 `verbose_pipeline=true`: + +```json +POST /my_index/_search?verbose_pipeline=true +{ + "query": { + "match": { "text_field": "some search text" } + }, + "search_pipeline": { + "request_processors": [ + { + "filter_query": { + "query": { "term": { "visibility": "public" } } + } + } + ], + "response_processors": [ + { + "collapse": { + "field": "category" + } + } + ] + } +} +``` + +有关使用临时搜索管道的更多信息,请参阅[为请求使用临时管道](/search-plugins/search-pipelines/using-search-pipeline#using-a-temporary-search-pipeline-for-a-request)。 + +## 示例响应 + +启用 `verbose_pipeline` 参数后,响应包含一个额外的 `processor_results` 字段,提供有关管道中每个处理器应用的转换的信息: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 27, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.18232156, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.18232156, + "_source": { + "notification": "This is a public message", + "visibility": "public" + } + } + ] + }, + "processor_results": [ + { + "processor_name": "filter_query", + "tag": "tag1", + "duration_millis": 288541, + "status": "success", + "input_data": { + "verbose_pipeline": true, + "query": { + "bool": { + "adjust_pure_negative": true, + "must": [ + { + "match": { + "message": { + "auto_generate_synonyms_phrase_query": true, + "query": "this", + "zero_terms_query": "NONE", + "fuzzy_transpositions": true, + "boost": 1.0, + "prefix_length": 0, + "operator": "OR", + "lenient": false, + "max_expansions": 50 + } + } + } + ], + "boost": 1.0 + } + } + }, + "output_data": { + "verbose_pipeline": true, + "query": { + "bool": { + "filter": [ + { + "term": { + "visibility": { + "boost": 1.0, + "value": "public" + } + } + } + ], + "adjust_pure_negative": true, + "must": [ + { + "bool": { + "adjust_pure_negative": true, + "must": [ + { + "match": { + "message": { + "auto_generate_synonyms_phrase_query": true, + "query": "this", + "zero_terms_query": "NONE", + "fuzzy_transpositions": true, + "boost": 1.0, + "prefix_length": 0, + "operator": "OR", + "lenient": false, + "max_expansions": 50 + } + } + } + ], + "boost": 1.0 + } + } + ], + "boost": 1.0 + } + } + } + }, + { + "processor_name": "rename_field", + "duration_millis": 250042, + "status": "success", + "input_data": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.18232156, + "_source": { + "message": "This is a public message", + "visibility": "public" + } + } + ], + "output_data": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.18232156, + "_source": { + "notification": "This is a public message", + "visibility": "public" + } + } + ] + } + ] +} +``` +</details> diff --git a/i18n/zh/search-plugins/search-pipelines/deleting-search-pipeline.md b/i18n/zh/search-plugins/search-pipelines/deleting-search-pipeline.md new file mode 100644 index 00000000..3a1d96d8 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/deleting-search-pipeline.md @@ -0,0 +1,19 @@ +--- +title: 删除搜索管道 +--- + +# 删除搜索管道 + +使用以下请求删除管道。 + +要删除特定的搜索管道,请将管道 ID 作为参数传递: + +```json +DELETE /_search/pipeline/{pipeline-id} +``` + +要删除集群中的所有搜索管道,请使用通配符(`*`): + +```json +DELETE /_search/pipeline/* +``` diff --git a/i18n/zh/search-plugins/search-pipelines/explanation-processor.md b/i18n/zh/search-plugins/search-pipelines/explanation-processor.md new file mode 100644 index 00000000..3d5cddee --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/explanation-processor.md @@ -0,0 +1,218 @@ +--- +title: 混合分数解释 +--- + +# 混合分数解释处理器 +<Badge type="tip" text="2.19 版本引入" /> + +`hybrid_score_explanation` 响应处理器将归一化和组合结果添加到返回的搜索响应中。您可以将其用作调试工具来了解分数归一化过程。有关更多信息,请参阅[混合查询](/query-dsl/compound/hybrid)。 + +::: warning IMPORTANT +要将 `explain` 参数与通过搜索管道运行的混合查询一起使用,您必须在该管道中配置 `hybrid_score_explanation` 响应处理器。 +::: + +::: info NOTE +在[融合模式](/vector-search/ai-search/hybrid-search/fusion-mode/)下运行的混合查询不需要此处理器。在融合模式下,`explain` 描述归一化和组合,而无需搜索管道,使用与本页显示的相同描述。 +::: + +## 请求正文字段 + +下表列出了所有请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`tag` | 字符串 | 处理器的标识符。可选。 +`description` | 字符串 | 处理器的描述。可选。 +`ignore_failure` | 布尔值 | 如果为 `true`,则 OpenSearch [忽略此处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures)并继续运行搜索管道中的其余处理器。可选。默认为 `false`。 + +## 示例 + +以下示例演示如何使用带有 `hybrid_score_explanation` 处理器的搜索管道。 + +有关完整示例,请参阅[语义和混合搜索入门](/search-plugins/neural-search-tutorial#tutorial)。 + +### 创建搜索管道 + +以下请求创建一个包含 `normalization-processor` 和 `hybrid_score_explanation` 处理器的搜索管道: + +```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" + } + } + } + ], + "response_processors": [ + { + "hybrid_score_explanation": {} + } + ] +} +``` + +### 使用搜索管道 + +要查看解释信息,请在搜索请求中指定 `explain=true`: + +```json +GET /my-nlp-index/_search?search_pipeline=nlp-search-pipeline&explain=true +{ + "_source": { + "exclude": [ + "passage_embedding" + ] + }, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "text": { + "query": "horse" + } + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "wild west", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 54, + "timed_out": false, + "_shards": { + "total": 2, + "successful": 2, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 5, + "relation": "eq" + }, + "max_score": 0.9251075, + "hits": [ + { + "_shard": "[my-nlp-index][0]", + "_node": "IsuzeVYdSqKUfy0qfqil2w", + "_index": "my-nlp-index", + "_id": "5", + "_score": 0.9251075, + "_source": { + "text": "A rodeo cowboy , wearing a cowboy hat , is being thrown off of a wild white horse .", + "id": "2691147709.jpg" + }, + "_explanation": { + "value": 0.9251075, + "description": "arithmetic_mean combination of:", + "details": [ + { + "value": 1.0, + "description": "min_max normalization of:", + "details": [ + { + "value": 1.2336599, + "description": "weight(text:horse in 0) [PerFieldSimilarity], result of:", + "details": [ + { + "value": 1.2336599, + "description": "score(freq=1.0), computed as boost * idf * tf from:", + "details": [ + { + "value": 2.2, + "description": "boost", + "details": [] + }, + { + "value": 1.2039728, + "description": "idf, computed as log(1 + (N - n + 0.5) / (n + 0.5)) from:", + "details": [ + { + "value": 1, + "description": "n, number of documents containing term", + "details": [] + }, + { + "value": 4, + "description": "N, total number of documents with field", + "details": [] + } + ] + }, + { + "value": 0.46575344, + "description": "tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl)) from:", + "details": [ + { + "value": 1.0, + "description": "freq, occurrences of term within document", + "details": [] + }, + { + "value": 1.2, + "description": "k1, term saturation parameter", + "details": [] + }, + { + "value": 0.75, + "description": "b, length normalization parameter", + "details": [] + }, + { + "value": 16.0, + "description": "dl, length of field", + "details": [] + }, + { + "value": 17.0, + "description": "avgdl, average length of field", + "details": [] + } + ] + } + ] + } + ] + } + ] + }, + { + "value": 0.8503647, + "description": "min_max normalization of:", + "details": [ + { + "value": 0.015177966, + "description": "within top 5", + "details": [] + } + ] + } + ] + } +... +``` + +有关设置混合搜索的更多信息,请参阅[混合搜索](/search-plugins/hybrid-search)。 diff --git a/i18n/zh/search-plugins/search-pipelines/ml-inference-search-request.md b/i18n/zh/search-plugins/search-pipelines/ml-inference-search-request.md new file mode 100644 index 00000000..fda44b4a --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/ml-inference-search-request.md @@ -0,0 +1,525 @@ +--- +title: ML 推理(请求) +--- + +# ML 推理搜索请求处理器 +<Badge type="tip" text="2.16 版本引入" /> + +`ml_inference` 搜索请求处理器用于调用已注册的机器学习(ML)模型,以便使用模型输出重写查询。 + +::: info NOTE +**先决条件**<br> +在使用 `ml_inference` 搜索请求处理器之前,您必须在 OpenSearch 集群上托管本地 ML 模型,或者通过 ML Commons 插件将外部托管模型连接到 OpenSearch 集群。有关本地模型的更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)。 +有关外部托管模型的更多信息,请参阅[连接到外部托管模型](/ml-commons-plugin/remote-models/)。 +::: + +## 语法 + +以下是 `ml-inference` 搜索请求处理器的语法: + +```json +{ + "ml_inference": { + "model_id": "<model_id>", + "function_name": "<function_name>", + "full_response_path": "<full_response_path>", + "query_template": "<query_template>", + "model_config": { + "<model_config_field>": "<config_value>" + }, + "model_input": "<model_input>", + "input_map": [ + { + "<model_input_field>": "<query_input_field>" + } + ], + "output_map": [ + { + "<query_output_field>": "<model_output_field>" + } + ] + } +} +``` + +## 配置参数 + +下表列出了 `ml-inference` 搜索请求处理器的必需和可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:--| :--- |:---|:---| +| `model_id`| 字符串 | 必需 | 处理器使用的 ML 模型的 ID。 | +| `query_template` | 字符串 | 可选 | 用于构造包含 `new_document_field` 的新查询的查询字符串模板。通常在将搜索查询重写为新查询类型时使用。 | +| `function_name` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 处理器中配置的 ML 模型的函数名称。对于本地模型,有效值为 `sparse_encoding`、`sparse_tokenize`、`text_embedding` 和 `text_similarity`。对于外部托管模型,有效值为 `remote`。默认为 `remote`。 | +| `model_config` | 对象 | 可选 | ML 模型的自定义配置选项。对于外部托管模型,如果设置,此配置将覆盖默认连接器参数。对于本地模型,您可以将 `model_config` 添加到 `model_input` 以覆盖注册时设置的模型配置。有关更多信息,请参阅[`model_config` 对象](/ml-commons-plugin/api/model-apis/register-model#the-model_config-object)。 | +| `model_input` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 定义模型期望的输入字段格式的模板。每种本地模型类型可能使用不同的输入集。对于外部托管模型,默认值为 `"{ \"parameters\": ${ml_inference.parameters} }`。 | +| `input_map` | 数组 | 如果未指定 `optional_input_map` 则必需 | 指定如何将查询字符串字段映射到模型输入字段的数组。数组的每个元素都是 `"<model_input_field>": "<query_input_field>"` 格式的映射,对应于文档字段的一次模型调用。如果未为外部托管模型指定输入映射,则所有文档字段将直接作为输入传递给模型。`input_map` 大小表示模型被调用的次数(Predict API 请求的次数)。 | +| `<model_input_field>` | 字符串 | 必需 | 模型输入字段名称。 | +| `<query_input_field>` | 字符串 | 必需 | 用作模型输入的查询字段的名称或 JSON 路径。 | +| `output_map` | 数组 | 如果未指定 `optional_output_map` 则必需 | 指定如何将模型输出字段映射到查询字符串中新字段的数组。数组的每个元素都是 `"<query_output_field>": "<model_output_field>"` 格式的映射。 | +| `<query_output_field>` | 字符串 | 必需 | 存储模型输出(由 `model_output` 指定)的查询字段名称。 | +| `<model_output_field>` | 字符串 | 必需 | 要存储在 `query_output_field` 中的模型输出中字段的名称或 JSON 路径。 | +| `optional_input_map` | 数组 | 可选 | 指定当查询中存在查询字段时将其映射到模型输入的数组,格式与 `input_map` 相同。如果查询中缺少某个字段,则不会将其传递给模型。即使不存在任何可选字段,处理器也会调用模型,在这种情况下,模型不会从此映射接收任何输入,可能会返回错误。每个元素与同一位置的 `input_map` 元素合并,它们共同定义一次模型调用。当模型接受多个输入而查询仅包含其中一些输入时使用此选项,例如文本、图像或两者。 | +| `optional_output_map` | 数组 | 可选 | 指定从模型输出字段到查询字段的附加映射的数组,格式与 `output_map` 相同。每个元素与同一位置的 `output_map` 元素合并。 | +| `full_response_path` | 布尔值 | 可选 | 如果 `model_output_field` 包含字段的完整 JSON 路径而不是字段名称,请将此参数设置为 `true`。然后将完全解析模型输出以获取字段的值。对于本地模型默认为 `true`,对于外部托管模型默认为 `false`。 | +| `ignore_missing` | 布尔值 | 可选 | 如果为 `true` 且 `input_map` 或 `output_map` 中定义的任何输入字段缺失,则忽略此处理器。否则,缺少字段会导致失败。默认为 `false`。 | +| `ignore_failure` | 布尔值 | 可选 | 指定处理器即使遇到错误也是否继续执行。如果为 `true`,则忽略此处理器并继续搜索。如果为 `false`,则任何失败都会导致搜索被取消。默认为 `false`。 | +| `max_prediction_tasks` | 整数 | 可选 | 查询搜索期间可以运行的最大并发模型调用次数。默认为 `10`。 | +| `description` | 字符串 | 可选 | 处理器的简要描述。 | +| `tag` | 字符串 | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。 | + +::: info NOTE +`input_map` 和 `output_map` 映射支持用于指定复杂数据结构的标准 [JSON 路径](https://github.com/json-path/JsonPath)表示法。 +::: + +## 使用处理器 + +按照以下步骤在管道中使用处理器。创建处理器时,您必须提供模型 ID、`input_map` 或 `optional_input_map`,以及 `output_map` 或 `optional_output_map`。在使用处理器测试管道之前,请确保模型已成功部署。您可以使用[获取模型 API](/ml-commons-plugin/api/model-apis/get-model) 检查模型状态。 + +对于本地模型,您必须提供指定模型输入格式的 `model_input` 字段。将 `model_config` 中的任何输入字段添加到 `model_input`。 + +对于外部托管模型,`model_input` 字段是可选的,其默认值为 `"{ \"parameters\": ${ml_inference.parameters} }`。 + +### 设置 + +创建一个名为 `my_index` 的索引并索引两个文档: + +```json +POST /my_index/_doc/1 +{ + "passage_text": "I am excited", + "passage_language": "en", + "label": "POSITIVE", + "passage_embedding": [ + 2.3886719, + 0.032714844, + -0.22229004 + ...] +} +``` + +```json +POST /my_index/_doc/2 +{ + "passage_text": "I am sad", + "passage_language": "en", + "label": "NEGATIVE", + "passage_embedding": [ + 1.7773438, + 0.4309082, + 1.8857422, + 0.95996094, + ...] +} +``` + +在创建的索引上运行不带搜索管道的词条查询时,查询会搜索包含查询中指定的精确词条的文档。以下查询不返回任何结果,因为查询文本与索引中的任何文档都不匹配: + +```json +GET /my_index/_search +{ + "query": { + "term": { + "passage_text": { + "value": "happy moments", + "boost": 1 + } + } + } +} +``` + +通过使用模型,搜索管道可以根据模型推理动态重写词条值以增强或更改搜索结果。这意味着模型从搜索查询中获取初始输入,处理它,然后更新查询词条以反映模型推理,从而可能提高搜索结果的相关性。 + +### 示例:外部托管模型 + +以下示例使用外部托管模型配置 `ml_inference` 处理器。 + +**步骤 1:创建管道** + +此示例演示如何为重写词条查询值的外部托管情感分析模型创建搜索管道。该模型需要一个 `inputs` 字段并在 `label` 字段中生成结果。由于未指定 `function_name`,它默认为 `remote`,表示外部托管模型。 + +词条查询值根据模型的输出重写。搜索请求中的 `ml_inference` 处理器需要 `input_map` 来检索模型输入的查询字段值,以及 `output_map` 来将模型输出分配给查询字符串。 + +在此示例中,`ml_inference` 搜索请求处理器用于以下词条查询: + +```json + { + "query": { + "term": { + "label": { + "value": "happy moments", + "boost": 1 + } + } + } +} +``` + +以下请求创建一个重写前述词条查询的搜索管道: + +```json +PUT /_search/pipeline/ml_inference_pipeline +{ + "description": "Generate passage_embedding for searched documents", + "request_processors": [ + { + "ml_inference": { + "model_id": "<your model id>", + "input_map": [ + { + "inputs": "query.term.label.value" + } + ], + "output_map": [ + { + "query.term.label.value": "label" + } + ] + } + } + ] +} +``` + +向外部托管模型发出 Predict API 请求时,所有必要的字段和参数通常包含在 `parameters` 对象中: + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict +{ + "parameters": { + "inputs": [ + { + ... + } + ] + } +} +``` + +因此,要使用外部托管的情感分析模型,请按以下格式发送 Predict API 请求: + +```json +POST /_plugins/_ml/models/cywgD5EB6KAJXDLxyDp1/_predict +{ + "parameters": { + "inputs": "happy moments" + } +} +``` + +模型处理输入并根据输入文本的情感生成预测。在这种情况下,情感是积极的: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "label": "POSITIVE", + "score": "0.948" + } + } + ], + "status_code": 200 + } + ] +} +``` + +为外部托管模型指定 `input_map` 时,您可以直接引用 `inputs` 字段,而不是提供其点路径 `parameters.inputs`: + +```json +"input_map": [ + { + "inputs": "query.term.label.value" + } +] +``` + +**步骤 2:运行管道** + +创建搜索管道后,您可以使用搜索管道运行相同的词条查询: + +```json +GET /my_index/_search?search_pipeline=my_pipeline_request_review +{ + "query": { + "term": { + "label": { + "value": "happy moments", + "boost": 1 + } + } + } +} +``` + +查询词条值根据模型的输出重写。模型确定查询词条的情感为积极,因此重写后的查询如下所示: + +```json +{ + "query": { + "term": { + "label": { + "value": "POSITIVE", + "boost": 1 + } + } + } +} +``` + +响应包括 `label` 字段值为 `POSITIVE` 的文档: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "3", + "_score": 0.00009405752, + "_source": { + "passage_text": "I am excited", + "passage_language": "en", + "label": "POSITIVE" + } + } + ] + } +} +``` + +### 示例:本地模型 + +以下示例展示如何使用本地模型配置 `ml_inference` 处理器,以将词条查询重写为 k-NN 查询。 + +**步骤 1:创建管道** + +以下示例展示如何为 `huggingface/sentence-transformers/all-distilroberta-v1` 本地模型创建搜索管道。该模型是托管在 OpenSearch 集群中的[预训练句子转换器模型](/ml-commons-plugin/pretrained-models#sentence-transformers)。 + +如果使用 Predict API 调用模型,则请求如下所示: + +```json +POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs": [ + "today is sunny" + ], + "return_number": true, + "target_response": [ + "sentence_embedding" + ] +} +``` + +使用此架构,按如下方式指定 `model_input`: + +```json + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }" +``` + +在 `input_map` 中,将 `query.term.passage_embedding.value` 查询字段映射到模型期望的 `text_docs` 字段: + +```json +"input_map": [ + { + "text_docs": "query.term.passage_embedding.value" + } +] +``` + +因为您将要转换为嵌入的字段指定为 JSON 路径,所以需要将 `full_response_path` 设置为 `true`。然后将完全解析完整的 JSON 文档以获取输入字段: + +```json +"full_response_path": true +``` + +`query.term.passage_embedding.value` 字段中的文本将用于生成嵌入: + +```json +{ + "text_docs": "happy passage" +} +``` + +Predict API 请求返回以下响应: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "sentence_embedding", + "data_type": "FLOAT32", + "shape": [ + 768 + ], + "data": [ + 0.25517133, + -0.28009856, + 0.48519906, + ... + ] + } + ] + } + ] +} +``` + +模型在 `$.inference_results.*.output.*.data` 字段中生成嵌入。`output_map` 将此字段映射到查询模板中的查询字段: + +```json +"output_map": [ + { + "modelPredictionOutcome": "$.inference_results.*.output.*.data" + } +] +``` + +要使用本地模型配置 `ml_inference` 搜索请求处理器,请显式指定 `function_name`。在此示例中,`function_name` 为 `text_embedding`。有关有效 `function_name` 值的信息,请参阅[配置参数](#配置参数)。 + +以下是使用本地模型的 `ml_inference` 处理器的最终配置: + +```json +PUT /_search/pipeline/ml_inference_pipeline_local +{ + "description": "searchs reviews and generates embeddings", + "request_processors": [ + { + "ml_inference": { + "function_name": "text_embedding", + "full_response_path": true, + "model_id": "<your model id>", + "model_config": { + "return_number": true, + "target_response": [ + "sentence_embedding" + ] + }, + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }", + "query_template": """{ + "size": 2, + "query": { + "knn": { + "passage_embedding": { + "vector": ${modelPredictionOutcome}, + "k": 5 + } + } + } + }""", + "input_map": [ + { + "text_docs": "query.term.passage_embedding.value" + } + ], + "output_map": [ + { + "modelPredictionOutcome": "$.inference_results.*.output.*.data" + } + ], + "ignore_missing": true, + "ignore_failure": true + } + } + ] +} +``` + +**步骤 2:运行管道** + +运行以下查询,在请求中提供管道名称: + +```json +GET /my_index/_search?search_pipeline=ml_inference_pipeline_local +{ +"query": { + "term": { + "passage_embedding": { + "value": "happy passage" + } + } + } +} +``` + +响应确认处理器运行了 k-NN 查询,该查询返回文档 1 且得分较高: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.00009405752, + "_source": { + "passage_text": "I am excited", + "passage_language": "en", + "label": "POSITIVE", + "passage_embedding": [ + 2.3886719, + 0.032714844, + -0.22229004 + ...] + } + }, + { + "_index": "my_index", + "_id": "2", + "_score": 0.00001405052, + "_source": { + "passage_text": "I am sad", + "passage_language": "en", + "label": "NEGATIVE", + "passage_embedding": [ + 1.7773438, + 0.4309082, + 1.8857422, + 0.95996094, + ... + ] + } + } + ] + } +} +``` + +## 后续步骤 + +- 有关按文本和图像搜索的完整示例,请参阅[使用 ML 推理处理器的多模态搜索](/tutorials/vector-search/semantic-search/multimodal-search-ml-inference/)。 +- 有关将查询重写为向量搜索的完整示例,请参阅[使用文本分块的语义搜索](/tutorials/vector-search/semantic-search/long-document/)。 +- 有关在搜索时使用压缩嵌入的完整示例,请参阅[使用 Cohere 压缩嵌入优化向量搜索](/tutorials/vector-search/vector-operations/optimize-compression/)。 diff --git a/i18n/zh/search-plugins/search-pipelines/ml-inference-search-response.md b/i18n/zh/search-plugins/search-pipelines/ml-inference-search-response.md new file mode 100644 index 00000000..5bc0376b --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/ml-inference-search-response.md @@ -0,0 +1,740 @@ +--- +title: ML 推理(响应) +--- + +# ML 推理搜索响应处理器 +<Badge type="tip" text="2.16 版本引入" /> + +`ml_inference` 搜索响应处理器用于调用已注册的机器学习(ML)模型,以便将其输出作为新字段合并到搜索结果中的文档中。 + +::: info NOTE +**先决条件**<br> +在使用 `ml_inference` 搜索响应处理器之前,您必须在 OpenSearch 集群上托管本地 ML 模型,或者通过 ML Commons 插件将外部托管模型连接到 OpenSearch 集群。有关本地模型的更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)。有关外部托管模型的更多信息,请参阅[连接到外部托管模型](/ml-commons-plugin/remote-models/)。 +::: + +## 语法 + +以下是 `ml-inference` 搜索响应处理器的语法: + +```json +{ + "ml_inference": { + "model_id": "<model_id>", + "function_name": "<function_name>", + "full_response_path": "<full_response_path>", + "model_config":{ + "<model_config_field>": "<config_value>" + }, + "model_input": "<model_input>", + "input_map": [ + { + "<model_input_field>": "<document_field>" + } + ], + "output_map": [ + { + "<new_document_field>": "<model_output_field>" + } + ], + "override": "<override>", + "one_to_one": false + } +} +``` + +## 请求正文字段 + +下表列出了 `ml-inference` 搜索响应处理器的必需和可选参数。 + +| 参数 | 数据类型 | 必需/可选 | 描述 | +|:--| :--- | :--- |:---| +| `model_id` | 字符串 | 必需 | 处理器使用的 ML 模型的 ID。 | +| `function_name` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 处理器中配置的 ML 模型的函数名称。对于本地模型,有效值为 `sparse_encoding`、`sparse_tokenize`、`text_embedding` 和 `text_similarity`。对于外部托管模型,有效值为 `remote`。默认为 `remote`。 | +| `model_config` | 对象 | 可选 | ML 模型的自定义配置选项。对于外部托管模型,如果设置,此配置将覆盖默认连接器参数。对于本地模型,您可以将 `model_config` 添加到 `model_input` 以覆盖注册时设置的模型配置。有关更多信息,请参阅[`model_config` 对象](/ml-commons-plugin/api/model-apis/register-model#the-model_config-object)。 | +| `model_input` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 定义模型期望的输入字段格式的模板。每种本地模型类型可能使用不同的输入集。对于外部托管模型,默认值为 `"{ \"parameters\": ${ml_inference.parameters} }`。 | +| `input_map` | 数组 | 外部托管模型可选<br/><br/>本地模型必需 | 指定如何将搜索响应中的文档字段映射到模型输入字段的数组。数组的每个元素都是 `"<model_input_field>": "<document_field>"` 格式的映射,对应于文档字段的一次模型调用。如果未为外部托管模型指定输入映射,则所有文档字段将直接作为输入传递给模型。`input_map` 大小表示模型被调用的次数(Predict API 请求的次数)。 | +| `<model_input_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 模型输入字段名称。 | +| `<document_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 搜索响应中用作模型输入的文档字段的名称或 JSON 路径。 | +| `output_map` | 数组 | 外部托管模型可选<br/><br/>本地模型必需 | 指定如何将模型输出字段映射到搜索响应文档中新字段的数组。数组的每个元素都是 `"<new_document_field>": "<model_output_field>"` 格式的映射。 | +| `<new_document_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 存储模型输出(由 `model_output` 指定)的文档中新字段的名称。如果未为外部托管模型指定输出映射,则模型输出中的所有字段都将添加到新文档字段中。 | +| `<model_output_field>` | 字符串 | 外部托管模型可选<br/><br/>本地模型必需 | 要存储在 `new_document_field` 中的模型输出中字段的名称或 JSON 路径。 | +| `full_response_path` | 布尔值 | 可选 | 如果 `model_output_field` 包含字段的完整 JSON 路径而不是字段名称,请将此参数设置为 `true`。然后将完全解析模型输出以获取字段的值。对于本地模型默认为 `true`,对于外部托管模型默认为 `false`。 | +| `ignore_missing` | 布尔值 | 可选 | 如果为 `true` 且 `input_map` 或 `output_map` 中定义的任何输入字段缺失,则忽略此处理器。否则,缺少字段会导致失败。默认为 `false`。 | +| `ignore_failure` | 布尔值 | 可选 | 指定处理器即使遇到错误也是否继续执行。如果为 `true`,则忽略此处理器并继续搜索。如果为 `false`,则任何失败都会导致搜索被取消。默认为 `false`。 | +| `override` | 布尔值 | 可选 | 如果响应中的文档已包含名为 `<new_document_field>` 的字段,则相关。如果 `override` 为 `false`,则跳过输入字段。如果为 `true`,则新模型输出将覆盖现有字段值。默认为 `false`。 | +| `max_prediction_tasks` | 整数 | 可选 | 文档搜索期间可以运行的最大并发模型调用次数。默认为 `10`。 | +| `one_to_one` | 布尔值 | 可选 | 将此参数设置为 `true` 以对每个文档调用一次模型(发出一个 Predict API 请求)。默认值(`false`)指定使用搜索响应中的所有文档调用模型,发出一个 Predict API 请求。 | +| `description` | 字符串 | 可选 | 处理器的简要描述。 | +| `tag` | 字符串 | 可选 | 处理器的标识符标签。对于调试以区分相同类型的处理器很有用。 | + +::: info NOTE +`input_map` 和 `output_map` 映射支持用于指定复杂数据结构的标准 [JSON 路径](https://github.com/json-path/JsonPath)表示法。 +::: + +### 设置 + +创建一个名为 `my_index` 的索引并索引一个文档以解释映射: + +```json +POST /my_index/_doc/1 +{ + "passage_text": "hello world" +} +``` + +## 使用处理器 + +按照以下步骤在管道中使用处理器。创建处理器时,您必须提供模型 ID。在使用处理器测试管道之前,请确保模型已成功部署。您可以使用[获取模型 API](/ml-commons-plugin/api/model-apis/get-model) 检查模型状态。 + +对于本地模型,您必须提供指定模型输入格式的 `model_input` 字段。将 `model_config` 中的任何输入字段添加到 `model_input`。 + +对于远程模型,`model_input` 字段是可选的,其默认值为 `"{ \"parameters\": ${ml_inference.parameters} }`。 + +### 示例:本地模型 + +以下示例展示如何使用本地模型配置 `ml_inference` 搜索响应处理器。 + +**步骤 1:创建管道** + +以下示例展示如何为 `huggingface/sentence-transformers/all-distilroberta-v1` 本地模型创建搜索管道。该模型是托管在 OpenSearch 集群中的[预训练句子转换器模型](/ml-commons-plugin/pretrained-models#sentence-transformers)。 + +如果使用 Predict API 调用模型,则请求如下所示: + +```json +POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4 +{ + "text_docs":[ "today is sunny"], + "return_number": true, + "target_response": ["sentence_embedding"] +} +``` + +使用此架构,按如下方式指定 `model_input`: + +```json + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }" +``` + +在 `input_map` 中,将 `passage_text` 文档字段映射到模型期望的 `text_docs` 字段: + +```json +"input_map": [ + { + "text_docs": "passage_text" + } +] +``` + +因为您将要转换为嵌入的字段指定为 JSON 路径,所以需要将 `full_response_path` 设置为 `true`。然后将完全解析完整的 JSON 文档以获取输入字段: + +```json +"full_response_path": true +``` + +`passage_text` 字段中的文本将用于生成嵌入: + +```json +{ + "passage_text": "hello world" +} +``` + +Predict API 请求返回以下响应: + +```json +{ + "inference_results" : [ + { + "output" : [ + { + "name" : "sentence_embedding", + "data_type" : "FLOAT32", + "shape" : [ + 768 + ], + "data" : [ + 0.25517133, + -0.28009856, + 0.48519906, + ... + ] + } + ] + } + ] +} +``` + +模型在 `$.inference_results.*.output.*.data` 字段中生成嵌入。`output_map` 将此字段映射到搜索响应文档中新创建的 `passage_embedding` 字段: + +```json +"output_map": [ + { + "passage_embedding": "$.inference_results.*.output.*.data" + } +] +``` + +要使用本地模型配置 `ml_inference` 搜索响应处理器,请显式指定 `function_name`。在此示例中,`function_name` 为 `text_embedding`。有关有效 `function_name` 值的信息,请参阅[请求字段](#请求正文字段)。 + +以下是使用本地模型的 `ml_inference` 搜索响应处理器的最终配置: + +```json +PUT /_search/pipeline/ml_inference_pipeline_local +{ + "description": "search passage and generates embeddings", + "response_processors": [ + { + "ml_inference": { + "function_name": "text_embedding", + "full_response_path": true, + "model_id": "<your model id>", + "model_config": { + "return_number": true, + "target_response": ["sentence_embedding"] + }, + "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }", + "input_map": [ + { + "text_docs": "passage_text" + } + ], + "output_map": [ + { + "passage_embedding": "$.inference_results.*.output.*.data" + } + ], + "ignore_missing": true, + "ignore_failure": true + } + } + ] +} +``` + +**步骤 2:运行管道** + +运行以下查询,在请求中提供管道名称: + +```json +GET /my_index/_search?search_pipeline=ml_inference_pipeline_local +{ +"query": { + "term": { + "passage_text": { + "value": "hello" + } + } + } +} +``` + +#### 响应 + +响应确认处理器已在 `passage_embedding` 字段中生成了文本嵌入: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.00009405752, + "_source": { + "passage_text": "hello world", + "passage_embedding": [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ...] + } + } + ] + } +} +``` + +### 示例:外部托管文本嵌入模型 + +以下示例展示如何使用外部托管模型配置 `ml_inference` 搜索响应处理器。 + +**步骤 1:创建管道** + +以下示例展示如何为外部托管文本嵌入模型创建搜索管道。该模型需要一个 `input` 字段并在 `data` 字段中生成结果。它将 `passage_text` 字段中的文本转换为文本嵌入并将嵌入存储在 `passage_embedding` 字段中。处理器配置中未显式指定 `function_name`,因此它默认为 `remote`,表示外部托管模型: + +```json +PUT /_search/pipeline/ml_inference_pipeline +{ + "description": "Generate passage_embedding when search documents", + "response_processors": [ + { + "ml_inference": { + "model_id": "<your model id>", + "input_map": [ + { + "input": "passage_text" + } + ], + "output_map": [ + { + "passage_embedding": "data" + } + ] + } + } + ] +} +``` + +向外部托管模型发出 Predict API 请求时,所有必要的字段和参数通常包含在 `parameters` 对象中: + +```json +POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict +{ + "parameters": { + "input": [ + { + ... + } + ] + } +} +``` + +为外部托管模型指定 `input_map` 时,您可以直接引用 `input` 字段,而不是提供其点路径 `parameters.input`: + +```json +"input_map": [ + { + "input": "passage_text" + } +] +``` + +**步骤 2:运行管道** + +运行以下查询,在请求中提供管道名称: + +```json +GET /my_index/_search?search_pipeline=ml_inference_pipeline_local +{ + "query": { + "match_all": { + } + } +} +``` + +响应确认处理器已在 `passage_embedding` 字段中生成了文本嵌入。`_source` 中的文档现在包含 `passage_text` 和 `passage_embedding` 字段: + +```json +{ + "took": 288, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.00009405752, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 0.00009405752, + "_source": { + "passage_text": "hello world", + "passage_embedding": [ + 0.017304314, + -0.021530833, + 0.050184276, + 0.08962978, + ...] + } + } + } + ] + } +} +``` + +### 示例:外部托管大型语言模型 + +此示例演示如何配置 `ml_inference` 搜索响应处理器以与外部托管的大型语言模型(LLM)配合使用,并将模型的响应映射到搜索扩展对象。使用 `ml_inference` 处理器,您可以启用 LLM 直接在响应中总结搜索结果。摘要包含在搜索响应的 `ext` 字段中,提供对 AI 生成的见解与原始搜索结果的无缝访问。 + +**先决条件** + +您必须为此用例配置外部托管的 LLM。有关外部托管模型的更多信息,请参阅[连接到外部托管模型](/ml-commons-plugin/remote-models/)。注册 LLM 后,您可以使用以下请求进行测试。此请求需要提供 `prompt` 和 `context` 字段: + +```json +POST /_plugins/_ml/models/KKne6JIBAs32TwoK-FFR/_predict +{ + "parameters": { + "prompt":"\n\nHuman: You are a professional data analysist. You will always answer question: Which month had the lowest customer acquisition cost per new customer? based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say I don't know. Context: ${parameters.context.toString()}. \n\n Assistant:", + "context":"Customer acquisition cost: January: $50, February: $45, March: $40. New customers: January: 500, February: 600, March: 750" + } +} +``` + +响应在 `inference_results` 字段中包含模型输出: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "response": """ Based on the data provided: + + - Customer acquisition cost in January was $50 and new customers were 500. So cost per new customer was $50/500 = $0.10 + - Customer acquisition cost in February was $45 and new customers were 600. So cost per new customer was $45/600 = $0.075 + - Customer acquisition cost in March was $40 and new customers were 750. So cost per new customer was $40/750 = $0.053 + + Therefore, the month with the lowest customer acquisition cost per new customer was March, at $0.053.""" + } + } + ], + "status_code": 200 + } + ] +} +``` + +**步骤 1:创建管道** + +为注册的模型创建搜索管道。该模型需要一个 `context` 字段作为输入。模型响应总结 `review` 字段中的文本并将摘要存储在搜索响应的 `ext.ml_inference.llm_response` 字段中: + +```json +PUT /_search/pipeline/my_pipeline_request_review_llm +{ + "response_processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "This processor is going to run llm", + "model_id": "EOF6wJIBtDGAJRTD4kNg", + "function_name": "REMOTE", + "input_map": [ + { + "context": "review" + } + ], + "output_map": [ + { + "ext.ml_inference.llm_response": "response" + } + ], + "model_config": { + "prompt": "\n\nHuman: You are a professional data analysist. You will always answer question: Which month had the lowest customer acquisition cost per new customer? based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say I don't know. Context: ${parameters.context.toString()}. \n\n Assistant:" + }, + "ignore_missing": false, + "ignore_failure": false + } + } + ] +} +``` + +在此配置中,您提供了以下参数: + +- `model_id` 参数指定生成式 AI 模型的 ID。 +- `function_name` 参数设置为 `REMOTE`,表示模型是外部托管的。 +- `input_map` 参数将文档中的 review 字段映射到模型期望的 context 字段。 +- `output_map` 参数指定模型的响应应存储在搜索响应中的 `ext.ml_inference.llm_response` 中。 +- `model_config` 参数包含一个提示,告诉模型如何处理输入并生成摘要。 + +**步骤 2:索引示例文档** + +索引一些示例文档以测试管道: + +```json +POST /_bulk +{"index":{"_index":"review_string_index","_id":"1"}} +{"review":"Customer acquisition cost: January: $50, New customers: January: 500."} +{"index":{"_index":"review_string_index","_id":"2"}} +{"review":"Customer acquisition cost: February: $45, New customers: February: 600."} +{"index":{"_index":"review_string_index","_id":"3"}} +{"review":"Customer acquisition cost: March: $40, New customers: March: 750."} +``` + +**步骤 3:运行管道** + +使用管道运行搜索查询: + +```json +GET /review_string_index/_search?search_pipeline=my_pipeline_request_review_llm +{ + "query": { + "match_all": {} + } +} +``` + +响应包括原始文档和 `ext.ml_inference.llm_response` 字段中生成的摘要: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "review_string_index", + "_id": "1", + "_score": 1, + "_source": { + "review": "Customer acquisition cost: January: $50, New customers: January: 500." + } + }, + { + "_index": "review_string_index", + "_id": "2", + "_score": 1, + "_source": { + "review": "Customer acquisition cost: February: $45, New customers: February: 600." + } + }, + { + "_index": "review_string_index", + "_id": "3", + "_score": 1, + "_source": { + "review": "Customer acquisition cost: March: $40, New customers: March: 750." + } + } + ] + }, + "ext": { + "ml_inference": { + "llm_response": """ Based on the context provided: + + - Customer acquisition cost in January was $50 and new customers were 500. So the cost per new customer was $50/500 = $0.10 + + - Customer acquisition cost in February was $45 and new customers were 600. So the cost per new customer was $45/600 = $0.075 + + - Customer acquisition cost in March was $40 and new customers were 750. So the cost per new customer was $40/750 = $0.053 + + Therefore, the month with the lowest customer acquisition cost per new customer was March, as it had the lowest cost per customer of $0.053.""" + } + } +} +``` + +### 示例:使用文本相似度模型重排序搜索结果 + +以下示例展示如何使用文本相似度模型配置 `ml_inference` 搜索响应处理器。 + +**先决条件** + +您必须为此用例配置外部托管的文本相似度模型。有关外部托管模型的更多信息,请参阅[连接到外部托管模型](/ml-commons-plugin/remote-models/)。注册文本相似度模型后,您可以使用以下请求进行测试。此请求需要在 `inputs` 字段中提供 `text` 和 `text_pair` 字段: + +```json +POST /_plugins/_ml/models/Ialx65IBAs32TwoK1lXf/_predict +{ + "parameters": { + "inputs": + { + "text": "I like you", + "text_pair": "I hate you" + } + } +} +``` + +模型为每个输入文档返回相似度分数: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "label": "LABEL_0", + "score": 0.022704314440488815 + } + } + ], + "status_code": 200 + } + ] +} +``` + +**步骤 1:索引示例文档** + +创建索引并添加一些示例文档: + +```json +POST _bulk +{"index":{"_index":"demo-index-0","_id":"1"}} +{"diary":"I hate you"} +{"index":{"_index":"demo-index-0","_id":"2"}} +{"diary":"I love you"} +{"index":{"_index":"demo-index-0","_id":"3"}} +{"diary":"I dislike you"} +``` + +**步骤 2:创建搜索管道** + +在此示例中,您将创建一个在 `one-to-one` 推理模式下使用文本相似度模型的搜索管道,分别处理搜索结果中的每个文档。此设置允许模型为每个文档发出一个预测请求,为每个搜索命中提供特定的相关性见解。使用 `input_map` 将搜索请求映射到查询文本时,JSON 路径必须以 `$._request` 或 `_request` 开头: + +```json +PUT /_search/pipeline/my_rerank_pipeline +{ + "response_processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "This processor runs ml inference during search response", + "model_id": "Ialx65IBAs32TwoK1lXf", + "model_input":"""{"parameters":{"inputs":{"text":"${input_map.text}","text_pair":"${input_map.text_pair}"}}}""", + "function_name": "REMOTE", + "input_map": [ + { + "text": "diary", + "text_pair":"$._request.query.term.diary.value" + } + ], + "output_map": [ + { + "rank_score": "$.score" + } + ], + "full_response_path": false, + "model_config": {}, + "ignore_missing": false, + "ignore_failure": false, + "one_to_one": true + }, + "rerank": { + "by_field": { + "target_field": "rank_score", + "remove_target_field": true + } + } + } + ] +} +``` + +在此配置中,您提供了以下参数: + +- `model_id` 参数指定文本相似度模型的唯一标识符。 +- `function_name` 参数设置为 `REMOTE`,表示模型是外部托管的。 +- `input_map` 参数将每个文档中的 `diary` 字段映射到模型的 `text` 输入,并将搜索查询词条映射到 `text_pair` 输入。`$._request` 前缀使 JSON 路径从搜索请求而不是文档中读取,因此 `$._request.query.term.diary.value` 解析为 `diary` 字段上 `term` 查询的 `value`。对于步骤 3 中的搜索请求,此值为 `today`。 +- `output_map` 参数将模型的分数映射到每个文档中名为 `rank_score` 的字段。 +- `model_input` 参数格式化模型的输入,确保它与 Predict API 期望的结构匹配。 +- `one_to_one` 参数设置为 `true`,确保模型分别处理每个文档,而不是将多个文档批量处理在一起。 +- `ignore_missing` 参数设置为 `false`,如果文档中缺少映射的字段,则导致处理器失败。 +- `ignore_failure` 参数设置为 `false`,如果 ML 推理处理器遇到错误,则导致整个管道失败。 + +`rerank` 处理器在 ML 推理之后应用。它根据 ML 模型生成的 `rank_score` 字段重新排序文档,然后从最终结果中删除此字段。 + +**步骤 3:运行管道** + +现在使用创建的管道执行搜索: + +```json +GET /demo-index-0/_search?search_pipeline=my_rerank_pipeline +{ + "query": { + "term": { + "diary": { + "value": "today" + } + } + } +} +``` + +响应包括原始文档及其重排序分数: + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.040183373, + "hits": [ + { + "_index": "demo-index-0", + "_id": "1", + "_score": 0.040183373, + "_source": { + "diary": "I hate you" + } + }, + { + "_index": "demo-index-0", + "_id": "2", + "_score": 0.022628736, + "_source": { + "diary": "I love you" + } + }, + { + "_index": "demo-index-0", + "_id": "3", + "_score": 0.0073115323, + "_source": { + "diary": "I dislike you" + } + } + ] + }, + "profile": { + "shards": [] + } +} +``` + +## 后续步骤 + +- 有关使用外部托管交叉编码器模型按字段重排序的完整示例,请参阅[使用外部托管交叉编码器模型按字段重排序](/search-plugins/search-relevance/rerank-by-field-cross-encoder)。 +- 有关使用 Cohere Rerank 按字段重排序结果的教程,请参阅[使用 Cohere Rerank 按字段重排序搜索结果](/tutorials/reranking/reranking-by-field/)。 diff --git a/i18n/zh/search-plugins/search-pipelines/neural-sparse-query-two-phase-processor.md b/i18n/zh/search-plugins/search-pipelines/neural-sparse-query-two-phase-processor.md new file mode 100644 index 00000000..aff5cd19 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/neural-sparse-query-two-phase-processor.md @@ -0,0 +1,142 @@ +--- +title: 神经稀疏查询两阶段 +--- + +# 神经稀疏查询两阶段处理器 +<Badge type="tip" text="2.15 版本引入" /> + +`neural_sparse_two_phase_processor` 搜索处理器旨在为[神经稀疏搜索](/search-plugins/neural-sparse-search)提供更快的搜索管道。它通过将使用所有令牌对所有文档评分的原始方法分为两个步骤来加速神经稀疏查询: + +1. 高权重令牌对文档评分并过滤出排名靠前的文档。 +2. 低权重令牌对排名靠前的文档重新评分。 + +## 请求正文字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`enabled` | 布尔值 | 控制是否启用两阶段处理器。默认为 `true`。 +`two_phase_parameter` | 对象 | 表示两阶段参数及其关联值的键值对映射。您可以指定 `prune_ratio`、`expansion_rate`、`max_window_size` 的值或这三个参数的任意组合。可选。 +`two_phase_parameter.prune_type` | 字符串 | 分离高权重和低权重令牌的剪枝策略。默认为 `max_ratio`。有关有效值,请参阅[剪枝稀疏向量](/ingest-pipelines/processors/sparse-encoding#pruning-sparse-vectors)。 +`two_phase_parameter.prune_ratio` | 浮点数 | 此比率定义如何分离高权重和低权重令牌。阈值通过将令牌的最大分数乘以其 `prune_ratio` 来计算。当 `prune_type` 设置为 `max_ratio` 时,有效值在 [0,1] 范围内。默认为 `0.4`。 +`two_phase_parameter.expansion_rate` | 浮点数 | 文档在第二阶段进行微调的速率。第二阶段文档数等于查询大小(默认为 10)乘以其扩展率。有效范围大于 1.0。默认为 `5.0`。 +`two_phase_parameter.max_window_size` | 整数 | 可以使用两阶段处理器处理的最大文档数。有效范围大于 50。默认为 `10000`。 +`tag` | 字符串 | 处理器的标识符。可选。 +`description` | 字符串 | 处理器的描述。可选。 + +## 示例 + +以下示例创建一个带有 `neural_sparse_two_phase_processor` 搜索请求处理器的搜索管道。 + +### 创建搜索管道 + +以下示例请求创建一个带有 `neural_sparse_two_phase_processor` 搜索请求处理器的搜索管道。处理器在索引级别设置自定义模型 ID,并为两个特定的索引字段提供不同的默认模型 ID: + +```json +PUT /_search/pipeline/two_phase_search_pipeline +{ + "request_processors": [ + { + "neural_sparse_two_phase_processor": { + "tag": "neural-sparse", + "description": "This processor is making two-phase processor.", + "enabled": true, + "two_phase_parameter": { + "prune_ratio": custom_prune_ratio, + "expansion_rate": custom_expansion_rate, + "max_window_size": custom_max_window_size + } + } + } + ] +} +``` + +### 设置搜索管道 + +创建两阶段管道后,将要使用两阶段管道的索引的 `index.search.default_pipeline` 设置设置为管道的名称: + +```json +PUT /index-name/_settings +{ + "index.search.default_pipeline" : "two_phase_search_pipeline" +} +``` + +## 限制 + +`neural_sparse_two_phase_processor` 有以下限制。 + +### 版本支持 + +`neural_sparse_two_phase_processor` 只能与 OpenSearch 2.15 或更高版本一起使用。 + +### 复合查询支持 + +仅支持布尔[复合查询](/query-dsl/compound/)。 + +还支持带有 boost 参数的神经稀疏查询和布尔查询(不是提升查询)。 + +## 示例 + +以下示例显示支持的查询类型的神经稀疏查询。 + +### 单个神经稀疏查询 + +``` +GET /my-nlp-index/_search +{ + "query": { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world" + "model_id": <model-id> + } + } + } +} +``` + +### 嵌套在布尔查询中的神经稀疏查询 + +``` +GET /my-nlp-index/_search +{ + "query": { + "bool": { + "should": [ + { + "neural_sparse": { + "passage_embedding": { + "query_text": "Hi world", + "model_id": <model-id> + }, + "boost": 2.0 + } + } + ] + } + } +} +``` + +## P99 延迟指标 +使用在三个 m5.4xlarge Amazon Elastic Compute Cloud (Amazon EC2) 实例上设置的 OpenSearch 集群,OpenSearch 在超过 10 个数据集对应的索引上进行神经稀疏查询 P99 延迟测试。 + +### 仅文档模式延迟指标 + +在仅文档模式下,两阶段处理器可以显著降低查询延迟,如以下延迟指标所示: + +- 不使用两阶段处理器的平均延迟:53.56 毫秒 +- 使用两阶段处理器的平均延迟:38.61 毫秒 + +这导致整体延迟降低约 27.92%。大多数索引在使用两阶段处理器时显示出显著的延迟降低,降低幅度从 5.14% 到 84.6%。具体的延迟优化值取决于索引内的数据分布。 + +### 双编码器模式延迟指标 + +在双编码器模式下,两阶段处理器可以显著降低查询延迟,如以下延迟指标所示: +- 不使用两阶段处理器的平均延迟:300.79 毫秒 +- 使用两阶段处理器的平均延迟:121.64 毫秒 + +这导致整体延迟降低约 59.56%。大多数索引在使用两阶段处理器时显示出显著的延迟降低,降低幅度从 1.56% 到 82.84%。具体的延迟优化值取决于索引内的数据分布。 diff --git a/i18n/zh/search-plugins/search-pipelines/score-ranker-processor.md b/i18n/zh/search-plugins/search-pipelines/score-ranker-processor.md new file mode 100644 index 00000000..1e766759 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/score-ranker-processor.md @@ -0,0 +1,99 @@ +--- +title: 分数排名器 +--- + +# 分数排名器处理器 +<Badge type="tip" text="2.19 版本引入" /> + +`score-ranker-processor` 是一个基于排名的搜索阶段结果处理器,在搜索执行的查询阶段和获取阶段之间运行。它拦截查询阶段结果,然后使用倒数排名融合(RRF)算法将 [`hybrid` 查询](/query-dsl/compound/hybrid)的查询子句组合成最终排名的搜索结果列表。RRF 根据每个文档在每个查询子句结果中的排名的倒数对其进行评分,然后将这些分数相加,因此各个查询子句的相关性分数永远不需要在可比较的尺度上。有关更多信息,请参阅[倒数排名融合](/vector-search/ai-search/hybrid-search/rrf/)。 + +您还可以通过在[融合模式](/vector-search/ai-search/hybrid-search/fusion-mode/)下运行 `hybrid` 查询并将归一化和组合技术都设置为 `rrf` 来使用 RRF 组合查询子句,而无需搜索管道。 + +## 请求正文字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`combination.technique` | 字符串 | 用于组合分数的技术。有效值为 `rrf`。可选。默认为 `rrf`。 +`combination.rank_constant` | 整数 | 在计算倒数分数之前添加到每个文档排名的常量。有效值在 [1, 10000] 范围内。较大的排名常量使分数更均匀,减少了排名靠前结果的影响。较小的排名常量在排名之间创建更大的分数差异,给予排名靠前的项目更多权重。可选。默认为 `60`。 +`combination.parameters.weights` | 浮点值数组 | 指定用于每个查询子句的权重。有效值在 [0.0, 1.0] 范围内,表示小数百分比。权重越接近 1.0,给予查询子句的权重就越大。`weights` 数组中的值数量必须等于查询子句的数量。数组中的值之和必须等于 1.0。可选。如果未提供,则所有查询子句给予相同的权重。要为单个请求覆盖这些权重,请在 [`hybrid` 查询](/query-dsl/compound/hybrid#weighting-subqueries)中指定 `weights` 参数。 + +## 示例 + +以下请求创建一个包含 `score-ranker-processor` 的搜索管道,该处理器使用 `rrf` 组合技术和默认排名常量 `60`: + +```json +PUT /_search/pipeline/rrf-pipeline +{ + "description": "Post processor for hybrid RRF search", + "phase_results_processors": [ + { + "score-ranker-processor": { + "combination": { + "technique": "rrf" + } + } + } + ] +} +``` + +以下请求将 `rank_constant` 设置为 `40` 并对每个查询子句应用自定义权重。查询子句 1 的权重为 0.7,查询子句 2 的权重为 0.3: + +```json +PUT /_search/pipeline/rrf-pipeline +{ + "description": "Post processor for hybrid RRF search", + "phase_results_processors": [ + { + "score-ranker-processor": { + "combination": { + "technique": "rrf", + "rank_constant": 40, + "parameters": { + "weights": [ + 0.7, + 0.3 + ] + } + } + } + } + ] +} +``` + +要使用管道,请在包含 `hybrid` 查询的搜索请求中指定它: + +```json +GET /my-nlp-index/_search?search_pipeline=rrf-pipeline +{ + "query": { + "hybrid": { + "queries": [ + { + "match": { + "passage_text": "running shoes" + } + }, + { + "neural": { + "passage_embedding": { + "query_text": "running shoes", + "model_id": "aVeif4oB5Vm0Tdw8zYO2", + "k": 5 + } + } + } + ] + } + } +} +``` + +## 相关文档 + +- [倒数排名融合](/vector-search/ai-search/hybrid-search/rrf/) +- [混合搜索](/vector-search/ai-search/hybrid-search/) +- [归一化处理器](/search-plugins/search-pipelines/normalization-processor) diff --git a/i18n/zh/search-plugins/search-pipelines/sort-processor.md b/i18n/zh/search-plugins/search-pipelines/sort-processor.md new file mode 100644 index 00000000..b9566277 --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/sort-processor.md @@ -0,0 +1,239 @@ +--- +title: 排序 +--- + +# 排序搜索处理器 +<Badge type="tip" text="2.16 版本引入" /> + +`sort` 处理器按升序或降序对项目数组进行排序。数字数组按数字排序,而字符串或混合数组(字符串和数字)按字典顺序排序。如果输入不是数组,处理器会抛出错误。 + +## 请求正文字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`field` | 字符串 | 要排序的字段。必须是数组。必需。 +`order` | 字符串 | 要应用的排序顺序。接受 `asc`(升序)或 `desc`(降序)。默认为 `asc`。 +`target_field` | 字符串 | 存储排序后数组的字段名称。如果未指定,则排序后的数组存储在与原始数组相同的字段中(`field` 变量)。 +`tag` | 字符串 | 处理器的标识符。 +`description` | 字符串 | 处理器的描述。 +`ignore_failure` | 布尔值 | 如果为 `true`,则 OpenSearch [忽略此处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures)并继续运行搜索管道中的其余处理器。可选。默认为 `false`。 + +## 示例 + +以下示例演示如何使用带有 `sort` 处理器的搜索管道。 + +### 设置 + +创建一个名为 `my_index` 的索引,并索引一个包含字符串数组的 `message` 字段的文档: + +```json +POST /my_index/_doc/1 +{ + "message": ["one", "two", "three", "four"], + "visibility": "public" +} +``` + +### 创建搜索管道 + +创建一个带有 `sort` 响应处理器的搜索管道,该处理器对 `message` 字段进行排序并将排序结果存储在 `sorted_message` 字段中: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "sort": { + "field": "message", + "target_field": "sorted_message" + } + } + ] +} +``` + +### 使用搜索管道 + +在 `my_index` 中搜索文档而不使用搜索管道: + +```json +GET /my_index/_search +``` + +响应包含 `message` 字段: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "message": [ + "one", + "two", + "three", + "four" + ], + "visibility": "public" + } + } + ] + } +} +``` +</details> + +要使用管道搜索,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` + +`sorted_message` 字段包含按字母顺序排序的 `message` 字段中的字符串: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```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": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "sorted_message": [ + "four", + "one", + "three", + "two" + ], + "message": [ + "one", + "two", + "three", + "four" + ] + } + } + ] + } +} +``` +</details> + +您还可以使用 `fields` 选项搜索文档中的特定字段: + +```json +POST /my_index/_search?pretty&search_pipeline=my_pipeline +{ + "fields": ["visibility", "message"] +} +``` + +在响应中,`message` 字段被排序,结果存储在 `sorted_message` 字段中: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "sorted_message": [ + "four", + "one", + "three", + "two" + ], + "message": [ + "one", + "two", + "three", + "four" + ] + }, + "fields": { + "visibility": [ + "public" + ], + "sorted_message": [ + "four", + "one", + "three", + "two" + ], + "message": [ + "one", + "two", + "three", + "four" + ] + } + } + ] + } +} +``` +</details> diff --git a/i18n/zh/search-plugins/search-pipelines/split-processor.md b/i18n/zh/search-plugins/search-pipelines/split-processor.md new file mode 100644 index 00000000..9898d04d --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/split-processor.md @@ -0,0 +1,223 @@ +--- +title: 拆分 +--- + +# 拆分搜索处理器 +<Badge type="tip" text="2.17 版本引入" /> + +`split` 处理器根据指定的分隔符将字符串字段拆分为子字符串数组。 + +## 请求正文字段 + +下表列出了所有可用的请求字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`field` | 字符串 | 包含要拆分的字符串的字段。必需。 +`separator` | 字符串 | 用于拆分字符串的分隔符。指定单个分隔符字符或正则表达式模式。必需。 +`preserve_trailing` | 布尔值 | 如果设置为 `true`,则在结果数组中保留空的尾部字段(例如 `''`)。如果设置为 `false`,则从结果数组中删除空的尾部字段。默认为 `false`。 +`target_field` | 字符串 | 存储子字符串数组的字段。如果未指定,则就地更新字段。 +`tag` | 字符串 | 处理器的标识符。 +`description` | 字符串 | 处理器的描述。 +`ignore_failure` | 布尔值 | 如果为 `true`,则 OpenSearch [忽略此处理器的任何失败](/search-plugins/search-pipelines/creating-search-pipeline#ignoring-processor-failures)并继续运行搜索管道中的其余处理器。可选。默认为 `false`。 + +## 示例 + +以下示例演示如何使用带有 `split` 处理器的搜索管道。 + +### 设置 + +创建一个名为 `my_index` 的索引,并索引一个包含 `message` 字段的文档: + +```json +POST /my_index/_doc/1 +{ + "message": "ingest, search, visualize, and analyze data", + "visibility": "public" +} +``` + +### 创建搜索管道 + +以下请求创建一个带有 `split` 响应处理器的搜索管道,该处理器拆分 `message` 字段并将结果存储在 `split_message` 字段中: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "split": { + "field": "message", + "separator": ", ", + "target_field": "split_message" + } + } + ] +} +``` + +### 使用搜索管道 + +在 `my_index` 中搜索文档而不使用搜索管道: + +```json +GET /my_index/_search +``` + +响应包含 `message` 字段: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```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": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "message": "ingest, search, visualize, and analyze data", + "visibility": "public" + } + } + ] + } +} +``` +</details> + +要使用管道搜索,请在 `search_pipeline` 查询参数中指定管道名称: + +```json +GET /my_index/_search?search_pipeline=my_pipeline +``` + +`message` 字段被拆分,结果存储在 `split_message` 字段中: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 6, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "message": "ingest, search, visualize, and analyze data", + "split_message": [ + "ingest", + "search", + "visualize", + "and analyze data" + ] + } + } + ] + } +} +``` +</details> + +您还可以使用 `fields` 选项搜索文档中的特定字段: + +```json +POST /my_index/_search?pretty&search_pipeline=my_pipeline +{ + "fields": ["visibility", "message"] +} +``` + +在响应中,`message` 字段被拆分,结果存储在 `split_message` 字段中: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 7, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1, + "_source": { + "visibility": "public", + "message": "ingest, search, visualize, and analyze data", + "split_message": [ + "ingest", + "search", + "visualize", + "and analyze data" + ] + }, + "fields": { + "visibility": [ + "public" + ], + "message": [ + "ingest, search, visualize, and analyze data" + ], + "split_message": [ + "ingest", + "search", + "visualize", + "and analyze data" + ] + } + } + ] + } +} +``` +</details> diff --git a/i18n/zh/search-plugins/search-pipelines/system-generated-search-processors.md b/i18n/zh/search-plugins/search-pipelines/system-generated-search-processors.md new file mode 100644 index 00000000..ca80199e --- /dev/null +++ b/i18n/zh/search-plugins/search-pipelines/system-generated-search-processors.md @@ -0,0 +1,65 @@ +--- +title: 系统生成的搜索处理器 +--- + +# 系统生成的搜索处理器 +<Badge type="tip" text="3.3 版本引入" /> + +系统生成的搜索处理器是 OpenSearch 根据搜索请求自动创建的处理器。与您在管道中手动配置的[用户定义处理器](/search-plugins/search-pipelines/search-processors)不同,系统生成的处理器在使用某些功能时会自动触发,从而无需手动配置处理器。 + +## 启用系统生成的搜索处理器 + +要启用系统生成的搜索处理器创建,请将 `cluster.search.enabled_system_generated_factories` 集群设置设置为 `*`(所有工厂)或明确列出要启用的工厂。以下示例启用 `mmr_over_sample_factory`、`mmr_rerank_factory` 和 `semantic-highlighter`: + +```json +PUT _cluster/settings +{ + "persistent": { + "cluster.search.enabled_system_generated_factories": [ + "mmr_over_sample_factory", + "mmr_rerank_factory", + "semantic-highlighter" + ] + } +} +``` + +## 处理器类型 + +OpenSearch 支持以下类型的系统生成处理器: + +* [搜索请求处理器](#系统生成的搜索请求处理器) +* [搜索响应处理器](#系统生成的搜索响应处理器) + +::: info NOTE +每个系统生成的处理器在固定的执行阶段运行,要么在同一类型的用户定义处理器之前运行,要么在之后运行。 +::: + +### 系统生成的搜索请求处理器 + +下表列出了可用的系统生成搜索请求处理器。 + +| 处理器名称 | 处理器工厂名称 | 执行阶段 | 触发条件 | 描述 | +| ----------------- | ------------------------- | ------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mmr_over_sample` | `mmr_over_sample_factory` | 在任何用户定义的请求处理器之后运行。 | 当搜索请求在 `ext` 对象中包含 `mmr` 参数时触发。请参阅[使用 MMR 重排序的向量搜索](/vector-search/specialized-operations/vector-search-mmr/)。 | 调整 `knn` 或 `neural` 查询的查询大小和 `k` 值,以过采样候选项用于最大边际相关性(MMR)重排序。 | +| `knn_default_excludes` | `knn_default_excludes_factory` | 在任何用户定义的请求处理器之前运行。 | 对于每个搜索请求触发,除非请求已通过将 `_source` 设置为 `true` 或 `false` 或将 `stored_fields` 设置为 `_none_` 来指定如何返回源。仅适用于包含启用 `_source` 的 `knn_vector` 字段的索引。请参阅[自动从搜索结果中排除向量](/vector-search/performance-tuning-search/#automatically-exclude-vectors-from-search-results)。 | 将所有 `knn_vector` 字段添加到 `_source.excludes`,以便默认情况下从搜索响应中省略向量。请求的 `_source.includes` 或 `_source.excludes` 中已列出的字段保持不变。 | + +### 系统生成的搜索响应处理器 + +下表列出了可用的系统生成搜索响应处理器。 + +| 处理器名称 | 处理器工厂名称 | 执行阶段 | 触发条件 | 描述 | +| -------------- | ---------------------- | ------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `mmr_rerank` | `mmr_rerank_factory` | 在任何用户定义的响应处理器之前运行。 | 当搜索请求在 `ext` 对象中包含 `mmr` 参数时触发。请参阅[使用 MMR 重排序的向量搜索](/vector-search/specialized-operations/vector-search-mmr/)。 | 使用 MMR 对过采样结果进行重排序,并将其减少到原始查询大小。 | +| `semantic-highlighter` | `semantic-highlighter` | 在任何用户定义的响应处理器之后运行。 | 当搜索请求包含 `type` 设置为 `semantic` 的 `highlight` 对象并在 `ext` 对象中包含 `semantic_highlighting_batch` 参数时触发。请参阅 [`semantic` 高亮器](/search-plugins/searching-data/highlight#the-semantic-highlighter)。 | 执行语义高亮的批量推理处理。 | + +## 限制 + +以下限制适用于系统生成的处理器: + +- OpenSearch 对于给定的搜索请求,**每个处理器类型和执行阶段仅支持一个系统生成的处理器**。由于每个处理器类型(请求和响应)可以在两个执行阶段(用户定义处理器之前或之后)运行,因此单个搜索请求可以包含多个系统生成的处理器,只要它们是不同类型或在不同执行阶段运行。此限制确保确定性执行顺序和可预测的行为。 + +## 相关文档 + +- [使用 MMR 重排序的向量搜索](/vector-search/specialized-operations/vector-search-mmr/) +- [自动从搜索结果中排除向量](/vector-search/performance-tuning-search/#automatically-exclude-vectors-from-search-results) diff --git a/i18n/zh/search-plugins/search-relevance/compare-query-sets.md b/i18n/zh/search-plugins/search-relevance/compare-query-sets.md new file mode 100644 index 00000000..4fa6f567 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/compare-query-sets.md @@ -0,0 +1,246 @@ +--- +title: 比较查询集 +--- + +# 比较搜索配置 + +要比较两个不同搜索配置的结果,您可以运行成对实验。为此,您需要两个搜索配置和一个用于搜索配置的查询集。 + +有关创建查询集的更多信息,请参阅[查询集](/search-plugins/search-relevance/query-sets)。 + +有关创建搜索配置的更多信息,请参阅[搜索配置](/search-plugins/search-relevance/search-configurations)。 + +## 创建成对实验 + +实验用于比较两个不同搜索配置之间的指标。实验根据指定的搜索配置显示每个查询的前 N 个结果。在仪表板中,您可以查看查询集中任何查询返回的文档,并确定哪个搜索配置返回更相关的结果。此外,您可以使用提供的相似性指标来衡量两个返回的搜索结果列表之间的相似性。 + +### 示例 + +要为指定的查询集和搜索配置创建成对比较实验,请发送以下请求: + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "8368a359-146b-4690-b756-40591b2fcddb", + "searchConfigurationList": ["a5acc9f3-6ad7-43f4-9651-fe118c499bc6", "26c7255c-c36e-42fb-b5b2-633dbf8e53b6"], + "size": 10, + "type": "PAIRWISE_COMPARISON" +} +``` + +### 请求正文字段 + +下表列出了可用的输入参数。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`querySetId` | 字符串 | 查询集 ID。 +`searchConfigurationList` | 列表 | 用于比较的搜索配置 ID 列表。 +`size` | 整数 | 要在结果中返回的文档数量。 +`type` | 字符串 | 定义要运行的实验类型。有效值为 `PAIRWISE_COMPARISON`、`HYBRID_OPTIMIZER` 或 `POINTWISE_EVALUATION`。根据实验类型,您必须在请求中提供不同的正文字段。`PAIRWISE_COMPARISON` 用于比较两个搜索配置与查询集,在[这里](/search-plugins/search-relevance/compare-query-sets)使用。`HYBRID_OPTIMIZER` 用于组合结果,在[这里](/search-plugins/search-relevance/optimize-hybrid-search)使用。`POINTWISE_EVALUATION` 用于根据判断评估搜索配置,在[这里](/search-plugins/search-relevance/evaluate-search-quality)使用。 + +响应包含创建的实验的实验 ID: + +```json +{ + "experiment_id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "experiment_result": "CREATED" +} +``` +## 解释实验结果 +要解释实验结果,请使用以下操作。 + +### 检索实验结果 + +使用以下 API 检索特定实验的结果。 + +#### 端点 + +```json +GET _plugins/_search_relevance/experiments +GET _plugins/_search_relevance/experiments/{experiment_id} +``` + +#### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `experiment_id` | 字符串 | 要检索的实验的 ID。为空时检索所有实验。 | + +#### 示例请求 + +```json +GET _plugins/_search_relevance/experiments/cbd2c209-96d1-4012-aa73-e524b7a1b11a +``` + +#### 示例响应 + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "_score": 1, + "_source": { + "id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "timestamp": "2025-06-11T23:24:26.792Z", + "type": "PAIRWISE_COMPARISON", + "status": "PROCESSING", + "querySetId": "8368a359-146b-4690-b756-40591b2fcddb", + "searchConfigurationList": [ + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6", + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6" + ], + "judgmentList": [], + "size": 10, + "results": {} + } + } + ] + } +} +``` + +实验运行完成后,结果可用: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 34, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "_score": 1.0, + "_source": { + "id": "cbd2c209-96d1-4012-aa73-e524b7a1b11a", + "timestamp": "2025-06-12T04:18:37.284Z", + "type": "PAIRWISE_COMPARISON", + "status": "COMPLETED", + "querySetId": "7889ffe9-835e-4f48-a9cd-53905bb967d3", + "searchConfigurationList": [ + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6", + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6" + ], + "judgmentList": [], + "size": 10, + "results": { + "tv": { + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6": [ + "B07X3S9RTZ", + "B07WVZFKLQ", + "B00GXD4NWE", + "B07ZKCV5K5", + "B07ZKDVHFB", + "B086VKT9R8", + "B08XLM8YK1", + "B07FPP6TB5", + "B07N1TMNHB", + "B09CDHM8W7" + ], + "pairwiseComparison": { + "jaccard": 0.11, + "rbo90": 0.16, + "frequencyWeighted": 0.2, + "rbo50": 0.07 + }, + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6": [ + "B07Q7VGW4Q", + "B00GXD4NWE", + "B07VML1CY1", + "B07THVCJK3", + "B07RKSV7SW", + "B010EAW8UK", + "B07FPP6TB5", + "B073G9ZD33", + "B07VXRXRJX", + "B07Q45SP9P" + ] + }, + "led tv": { + "26c7255c-c36e-42fb-b5b2-633dbf8e53b6": [ + "B01M1D0KL1", + "B07YSMD3Z9", + "B07V4CY9GZ", + "B074KFP426", + "B07S8XNWWF", + "B07XBJR7GY", + "B075FDWSHT", + "B01N2Z17MS", + "B07F1T4JFB", + "B07S658ZLH" + ], + "pairwiseComparison": { + "jaccard": 0.11, + "rbo90": 0.13, + "frequencyWeighted": 0.2, + "rbo50": 0.03 + }, + "a5acc9f3-6ad7-43f4-9651-fe118c499bc6": [ + "B07Q45SP9P", + "B074KFP426", + "B07JKVKZX8", + "B07THVCJK3", + "B0874XJYW8", + "B08LVPWQQP", + "B07V4CY9GZ", + "B07X3BS3DF", + "B074PDYLCZ", + "B08CD9MKLZ" + ] + } + } + } + } + ] + } +} +``` + +</details> + +### 解释结果 + +如上述响应所示,两个搜索配置都返回前 N 个文档,搜索请求中 `size` 设置为 10。除了结果之外,响应还包括来自成对比较的指标。 + +### 响应正文字段 + +字段 | 描述 +:--- | :--- +`jaccard` | 通过将返回文档的交集基数除以并集基数来显示相似性分数。 +`rbo` | 排名偏差重叠(RBO)指标在每个排名深度(例如,前 1 个文档、前 2 个文档等)比较返回的结果集。它更加重视排名较高的结果,对列表中较早位置给予更多权重。 +`frequencyWeighted` | 与 Jaccard 指标类似,频率加权指标计算两个集合的加权交集与加权并集的比率。但是,与标准 Jaccard 不同,它对频率较高的文档给予更多权重,使结果偏向于更频繁出现的项目。 diff --git a/i18n/zh/search-plugins/search-relevance/comparing-search-results.md b/i18n/zh/search-plugins/search-relevance/comparing-search-results.md new file mode 100644 index 00000000..5ea52272 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/comparing-search-results.md @@ -0,0 +1,29 @@ +--- +title: 比较搜索结果 +--- + +# 比较搜索结果 + +在 OpenSearch Dashboards 中比较搜索结果(也称为_成对实验_)允许您比较多个搜索配置的结果。使用此工具可帮助评估在将不同搜索配置应用于查询时结果如何变化。 + +例如,您可以查看应用以下查询更改之一时结果如何变化: + +- 对字段使用不同的权重 +- 不同的词干提取或词形还原策略 +- Shingling + +## 比较单个查询的搜索结果 + +用于比较单个查询搜索结果的 UI 允许您为单个查询定义两种不同的搜索配置,以便并排查看和比较结果。具体来说,您可以确定结果列表中包含多少共享和唯一文档以及它们的位置如何变化,如下图所示。 + +*比较搜索结果* + +有关使用单个查询的搜索结果比较工具的更多信息,请参阅[比较单个查询](/search-plugins/search-relevance/compare-search-results)。 + +## 比较查询集的搜索结果 + +通常,查看两个配置的搜索结果更改是测试过程的第一步。然后,您可以在搜索相关性工作台中从一个查询扩展到多个查询。您可以将查询分组到查询集中,创建[搜索配置](/search-plugins/search-relevance/search-configurations),并通过查看所有查询的聚合指标来大规模比较搜索结果,如下图所示。 + +*比较搜索结果* + +有关使用查询集的搜索结果比较工具的更多信息,请参阅[比较单个查询](/search-plugins/search-relevance/compare-query-sets)。 diff --git a/i18n/zh/search-plugins/search-relevance/evaluate-search-quality.md b/i18n/zh/search-plugins/search-relevance/evaluate-search-quality.md new file mode 100644 index 00000000..d5c17934 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/evaluate-search-quality.md @@ -0,0 +1,206 @@ +--- +title: 评估搜索质量 +--- + +# 评估搜索质量 + +搜索相关性工作台可以运行逐点实验,使用提供的查询和相关性判断来评估搜索配置质量。 + +有关创建查询集的更多信息,请参阅[查询集](/search-plugins/search-relevance/query-sets)。 + +有关创建搜索配置的更多信息,请参阅[搜索配置](/search-plugins/search-relevance/search-configurations)。 + +有关创建判断的更多信息,请参阅[判断](/search-plugins/search-relevance/judgments)。 + +## 创建逐点实验 + +逐点实验将您的搜索配置结果与提供的相关性判断进行比较,以评估搜索质量。 + +### 示例请求 + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "a02cedc2-249d-41de-be3e-662f6f221689", + "searchConfigurationList": ["4f90e474-0806-4dd2-a8dd-0fb8a5f836eb"], + "judgmentList": ["d3d93bb3-2cf4-4da0-8d31-c298427c2756"], + "size": 8, + "type": "POINTWISE_EVALUATION" +} +``` + +### 请求正文字段 + +下表列出了可用的输入参数。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`querySetId` | 字符串 | 查询集的 ID。 +`searchConfigurationList` | 列表 | 用于比较的搜索配置 ID 列表。 +`judgmentList` | 数组[字符串] | 用于评估搜索准确性的判断 ID 列表。 +`size` | 整数 | 要在结果中返回的文档数量。 +`type` | 字符串 | 要运行的实验类型。有效值为 `PAIRWISE_COMPARISON`、`HYBRID_OPTIMIZER` 或 `POINTWISE_EVALUATION`。根据实验类型,您必须在请求中提供不同的正文字段。`PAIRWISE_COMPARISON` 用于比较两个搜索配置与查询集,在[这里](/search-plugins/search-relevance/compare-query-sets)使用。`HYBRID_OPTIMIZER` 用于组合结果,在[这里](/search-plugins/search-relevance/optimize-hybrid-search)使用。`POINTWISE_EVALUATION` 用于根据判断评估搜索配置,在[这里](/search-plugins/search-relevance/evaluate-search-quality)使用。 + +### 示例响应 + +```json +{ + "experiment_id": "d707fa0f-3901-4c8b-8645-9a17e690722b", + "experiment_result": "CREATED" +} +``` + +## 管理结果 + +要检索实验结果,请按照成对实验中[比较查询集](/search-plugins/search-relevance/compare-query-sets)使用的相同流程操作。 + +以下是已完成响应的示例: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 140, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "bb609dc9-e357-42ec-a956-92b43be0a3ab", + "_score": 1.0, + "_source": { + "id": "bb609dc9-e357-42ec-a956-92b43be0a3ab", + "timestamp": "2025-06-13T08:06:46.046Z", + "type": "POINTWISE_EVALUATION", + "status": "COMPLETED", + "querySetId": "a02cedc2-249d-41de-be3e-662f6f221689", + "searchConfigurationList": [ + "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb" + ], + "judgmentList": [ + "d3d93bb3-2cf4-4da0-8d31-c298427c2756" + ], + "size": 8, + "results": [ + { + "evaluationId": "10c60fee-11ca-49b0-9e8a-82cb7b2c044b", + "searchConfigurationId": "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb", + "queryText": "tv" + }, + { + "evaluationId": "c03a5feb-8dc2-4f7f-9d31-d99bfb392116", + "searchConfigurationId": "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb", + "queryText": "led tv" + } + ] + } + } + ] + } +} +``` + +</details> + +结果包括每个搜索配置的评估结果 ID。要查看详细结果,请使用此 ID 查询 `search-relevance-evaluation-result` 索引。 + +以下是详细结果的示例: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 59, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "search-relevance-evaluation-result", + "_id": "10c60fee-11ca-49b0-9e8a-82cb7b2c044b", + "_score": 1.0, + "_source": { + "id": "10c60fee-11ca-49b0-9e8a-82cb7b2c044b", + "timestamp": "2025-06-13T08:06:40.869Z", + "searchConfigurationId": "4f90e474-0806-4dd2-a8dd-0fb8a5f836eb", + "searchText": "tv", + "judgmentIds": [ + "d3d93bb3-2cf4-4da0-8d31-c298427c2756" + ], + "documentIds": [ + "B07Q7VGW4Q", + "B00GXD4NWE", + "B07VML1CY1", + "B07THVCJK3", + "B07RKSV7SW", + "B010EAW8UK", + "B07FPP6TB5", + "B073G9ZD33" + ], + "metrics": [ + { + "metric": "Coverage@8", + "value": 0.0 + }, + { + "metric": "Precision@8", + "value": 0.0 + }, + { + "metric": "MAP@8", + "value": 0.0 + }, + { + "metric": "NDCG@8", + "value": 0.0 + } + ] + } + } + ] + } +} +``` + +</details> + +结果包括原始请求参数以及以下指标值: + +- `Coverage@k`:来自判断集的评分文档的比例,计算为有分数的文档数除以文档总数。 + +- `Precision@k`:在 k 个文档中(或返回文档总数,如果较低)具有非零判断分数的文档比例。 + +- `MAP@k`:平均精确度均值,计算所有文档的平均精确度。有关更多信息,请参阅[平均精确度](https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision)。 + +- `NDCG@k`:归一化折扣累积增益,将结果的实际排名与完美排名进行比较,对顶部结果给予更高的权重。这衡量结果排序的质量。 + +要直观地查看这些结果,请参阅[探索搜索评估结果](/search-plugins/search-relevance/explore-experiment-results)。 + +要计划自动评估,请参阅[监控搜索质量](/search-plugins/search-relevance/regularly-scheduled-experiments)。 diff --git a/i18n/zh/search-plugins/search-relevance/experiments.md b/i18n/zh/search-plugins/search-relevance/experiments.md new file mode 100644 index 00000000..fd0fbbe3 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/experiments.md @@ -0,0 +1,390 @@ +--- +title: 实验 +--- + +# 实验 + +_实验_是一种受控测试,旨在评估搜索引擎或其算法的有效性、相关性或性能。这些实验通常用于评估搜索系统为特定查询提供有用结果的能力。 + +搜索相关性工作台提供多种类型的实验。有关更多信息,请参阅[可用的搜索结果质量实验](/search-plugins/search-relevance/using-search-relevance-workbench#available-search-result-quality-experiments)。 + +## 创建实验 + +您可以使用以下 API 创建实验来测试搜索配置。 + +### 端点 + +```json +POST _plugins/_search_relevance/experiment +``` + +### 请求正文字段 + +下表列出了可用的请求正文字段。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`name` | 字符串 | 实验的名称。 +`description` | 字符串 | 实验的描述。 +`type` | 字符串 | 实验类型。有效值为 `PAIRWISE_COMPARISON`、`POINTWISE_EVALUATION` 和 `HYBRID_OPTIMIZER`。 +`querySetId` | 字符串 | 要在实验中使用的查询集的 ID。 +`searchConfigurationList` | 数组 | 要在实验中使用的搜索配置 ID 列表。 +`judgmentList` | 数组 | 用于评估的判断 ID 列表。可选。 +`size` | 整数 | 每个查询要检索的结果数量。默认为 `10`。 +`isScheduled` | 布尔值 | 实验是否计划定期运行。默认为 `false`。 + +### 示例请求 + +```json +POST _plugins/_search_relevance/experiment +{ + "type": "PAIRWISE_COMPARISON", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1", + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e", + "050b8c98-ba63-4c75-89cb-75f379b0d66e" + ], + "size": 10 +} +``` + +#### 示例响应 + +```json +{ + "experiment_id": "1777a6e8-1dcc-4e23-be4a-9ee27586c0fd", + "experiment_result": "CREATED" +} +``` + +## 管理实验 + +您可以使用以下 API 检索或删除实验。 + +### 查看实验 + +您可以使用实验 ID 检索实验。 + +#### 端点 + +```json +GET _plugins/_search_relevance/experiments/{experiment_id} +``` + +### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `experiment_id` | 字符串 | 要检索的实验的 ID。 | + +#### 示例请求 + +```json +GET _plugins/_search_relevance/experiments/b54f791a-3b02-49cb-a06c-46ab650b2ade +``` + +#### 示例响应 + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "_score": 1, + "_source": { + "id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "timestamp": "2026-01-28T18:16:44.548Z", + "type": "PAIRWISE_COMPARISON", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1", + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e", + "050b8c98-ba63-4c75-89cb-75f379b0d66e" + ], + "judgmentList": [], + "size": 10, + "isScheduled": false, + "scheduledExperimentJobId": null, + "results": [ + { + "snapshots": [ + { + "searchConfigurationId": "85f31a87-2833-4d4a-89d2-cc83248f410e", + "docIds": [ + "B07K1H1G3M", + "B07THVCJK3", + "B07FPP6TB5", + "B07Q7Z9DJ3", + "B07PYPCX21", + "B07WLRKCNW", + "B01HE1IVNA", + "B07ZKDVHFB", + "B071D41YC3", + "B07B6L2QCF" + ] + }, + { + "searchConfigurationId": "050b8c98-ba63-4c75-89cb-75f379b0d66e", + "docIds": [ + "B07ZKDVHFB", + "B07FPP6TB5", + "B07THVCJK3", + "B071D41YC3", + "B07JD5RT4D", + "B079QHML21", + "B07ZZVX1F2", + "B07YNLBS7R", + "B01N1SSOUC", + "B07WLRKCNW" + ] + } + ], + "metrics": [ + { + "metric": "jaccard", + "value": 0.33 + }, + { + "metric": "rbo50", + "value": 0.14 + }, + { + "metric": "rbo90", + "value": 0.32 + }, + { + "metric": "frequencyWeighted", + "value": 0.5 + } + ], + "query_text": "tv" + }, + { + "snapshots": [ + { + "searchConfigurationId": "85f31a87-2833-4d4a-89d2-cc83248f410e", + "docIds": [ + "B07THVCJK3", + "B07FPP6TB5", + "B07PP4882Q", + "B07K1H1G3M", + "B091KB3W63", + "B07JN28KP3", + "B07Q7SGS6Z", + "B07SJZ9X6J", + "B07VNG9ZLM", + "B00DTOAWZ2" + ] + }, + { + "searchConfigurationId": "050b8c98-ba63-4c75-89cb-75f379b0d66e", + "docIds": [ + "B07THVCJK3", + "B091KB3W63", + "B07PP4882Q", + "B07RFFJ7YL", + "B08HGQ7H8F", + "B083BNQYBP", + "B07ZKDVHFB", + "B07N1CMGQQ", + "B07FPP6TB5", + "B071D41YC3" + ] + } + ], + "metrics": [ + { + "metric": "jaccard", + "value": 0.25 + }, + { + "metric": "rbo50", + "value": 0.77 + }, + { + "metric": "rbo90", + "value": 0.58 + }, + { + "metric": "frequencyWeighted", + "value": 0.4 + } + ], + "query_text": "led tv" + } + ] + } + } + ] + } +} +``` + +</details> + +### 删除实验 + +您可以使用实验 ID 删除实验。 + +#### 端点 + +```json +DELETE _plugins/_search_relevance/experiments/{experiment_id} +``` + +#### 示例请求 + +```json +DELETE _plugins/_search_relevance/experiments/47cc3861-c37b-43cc-99c4 +``` + +#### 示例响应 + +```json +{ + "_index": ".plugins-search-relevance-experiment", + "_id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "_version": 3, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 1, + "successful": 1, + "failed": 0 + }, + "_seq_no": 6, + "_primary_term": 1 +} +``` + +### 搜索实验 + +您可以使用查询领域特定语言(DSL)搜索可用的实验。默认情况下,响应中不返回 `results` 数据。要包含 `results` 数据,请在查询中指定 `_source` 字段。 + +#### 端点 + +```json +GET _plugins/_search_relevance/experiments/_search +POST _plugins/_search_relevance/experiments/_search +``` + +#### 示例请求 + +搜索使用特定查询集的实验以衡量搜索相关性性能: + +```json +GET _plugins/_search_relevance/experiments/_search +{ + "query": { + "term": { "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": ".plugins-search-relevance-experiment", + "_id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "_score": 1, + "_source": { + "judgmentList": [], + "size": 10, + "scheduledExperimentJobId": null, + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e", + "050b8c98-ba63-4c75-89cb-75f379b0d66e" + ], + "isScheduled": false, + "id": "47cc3861-c37b-43cc-99c4-c1e7c90b4674", + "type": "PAIRWISE_COMPARISON", + "timestamp": "2026-01-28T18:16:44.548Z", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" + } + }, + { + "_index": ".plugins-search-relevance-experiment", + "_id": "90e4a31b-3b4a-4b2e-b492-0399358961cc", + "_score": 1, + "_source": { + "judgmentList": [ + "505d00cf-2fce-422b-bb97-2e3a95ce9446" + ], + "size": 8, + "scheduledExperimentJobId": null, + "searchConfigurationList": [ + "85f31a87-2833-4d4a-89d2-cc83248f410e" + ], + "isScheduled": false, + "id": "90e4a31b-3b4a-4b2e-b492-0399358961cc", + "type": "POINTWISE_EVALUATION", + "timestamp": "2026-01-28T18:16:45.696Z", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" + } + }, + { + "_index": ".plugins-search-relevance-experiment", + "_id": "71608f58-4827-4cd3-b6a6-61a527975a23", + "_score": 1, + "_source": { + "judgmentList": [ + "505d00cf-2fce-422b-bb97-2e3a95ce9446" + ], + "size": 10, + "scheduledExperimentJobId": null, + "searchConfigurationList": [ + "97f5b450-9571-469d-9dbb-347f94d164ba" + ], + "isScheduled": false, + "id": "71608f58-4827-4cd3-b6a6-61a527975a23", + "type": "HYBRID_OPTIMIZER", + "timestamp": "2026-01-28T18:17:00.811Z", + "status": "COMPLETED", + "querySetId": "f4c35381-407c-45c7-89ec-094b8a4cd5b1" + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/search-relevance/explore-experiment-results.md b/i18n/zh/search-plugins/search-relevance/explore-experiment-results.md new file mode 100644 index 00000000..272d81a0 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/explore-experiment-results.md @@ -0,0 +1,64 @@ +--- +title: 探索搜索评估结果 +--- + +# 探索搜索评估结果 +<Badge type="tip" text="3.2 版本引入" /> + +除了使用 API 检索实验结果外,您还可以直观地探索结果。搜索相关性工作台附带仪表板,您可以安装这些仪表板来查看搜索评估和混合搜索优化实验结果。 + +## 安装仪表板 + +您可以通过以下方式之一安装仪表板: + +* 在 **Actions** 列中,在实验概览中选择可视化图标。 + +* 选择实验概览右上角的 **Install Dashboards** 按钮。 + +*搜索相关性工作台的实验概览,包括仪表板安装选项* + +模态窗口提供为用户安装仪表板的选项。 + +*安装仪表板的模态窗口* + +## 使用仪表板 + +安装仪表板后,在 **Actions** 列中,选择实验概览中的可视化图标。这将打开实验结果仪表板。显示的视图取决于您选择的实验类型: + +* 搜索评估仪表板关注单个查询级别,并提供关于表现良好的查询和具有未开发相关性潜力的查询的洞察。 + +* 混合搜索仪表板概述了不同混合搜索参数配置的性能,并让您识别候选查询以进行进一步探索和实验。 + +### 搜索评估仪表板 + +搜索评估仪表板(如下图所示)聚合了所选实验中所有查询的性能指标。使用搜索评估仪表板获取整体实验性能的高级视图,并识别需要关注的查询。 + +*带可视化的搜索评估仪表板* + +**Deep Dive Summary** 面板显示 NDCG、MAP、精确度和覆盖率的聚合指标(请参阅[评估搜索质量](/search-plugins/search-relevance/search-configurations))。 + +**Deep Dive Query Scores** 面板显示按 NDCG 分数(从高到低)排名的单个查询性能。使用此面板识别表现最好和最差的查询。 + +**Deep Dive Score Densities** 面板显示指标值在查询集中的分布情况。使用此面板了解性能不佳是广泛存在还是集中在特定查询中。x 轴显示指标值,而 y 轴显示这些值出现的频率。 + +**Deep Dive Score Scatter Plot** 面板显示上述分布数据的交互式视图,每个查询显示为单独的点。使用此面板调查性能极端的特定查询。点在垂直方向上分散以防止重叠,同时保持与上述分布视图相同的 x 轴指标值。 + +### 混合搜索评估仪表板 + +使用混合搜索评估仪表板(如下图所示)比较实验变体并识别混合实验的最佳参数配置。 + +*带可视化的混合搜索优化评估仪表板* + +**Variant Performance Chart** 显示您的实验变体从最佳到最差的可视化排列(从左到右,按 NDCG 递减)。使用此图表快速识别表现最好的查询,并一目了然地查看不同参数组合的性能模式。 + +**Variant Performance** 面板以可排序的表格格式显示相同的变体数据,所有指标都可见。使用此面板比较变体之间的特定指标值,并通过按不同性能指标排序来自定义您的分析。要按列排序,请选择列标题。 + +### 自定义仪表板 + +仪表板作为保存的对象安装。安装后,您可以编辑仪表板或克隆并自定义它们以满足您的特定要求。 + +要了解如何自定义源文件,请参阅[更新默认仪表板](https://github.com/opensearch-project/dashboards-search-relevance/blob/main/DEVELOPER_GUIDE.md#updating-default-dashboards)。 + +### 重置仪表板 + +要重置仪表板,请选择实验概览右上角的 **Install Dashboards** 按钮。这将重新安装仪表板。 diff --git a/i18n/zh/search-plugins/search-relevance/index.md b/i18n/zh/search-plugins/search-relevance/index.md index ab08b57a..dbbda2c7 100644 --- a/i18n/zh/search-plugins/search-relevance/index.md +++ b/i18n/zh/search-plugins/search-relevance/index.md @@ -1,15 +1,37 @@ --- -title: 搜索相关性 +title: 优化搜索质量 --- -# 搜索相关性 +# 优化搜索质量 -搜索相关性(search relevance)用于评估查询返回的搜索结果的准确程度。相关性越高,搜索引擎就越好。 +_搜索质量_是指搜索结果与用户意图和期望匹配的程度。OpenSearch 提供了多种功能和工具来帮助您衡量、分析和提高搜索结果的质量。 -OpenSearch 提供以下搜索相关性功能: +OpenSearch 提供以下功能来帮助您优化搜索质量: -- 在 OpenSearch Dashboards 中并排[比较两个查询的搜索结果](/search-plugins/search-relevance/compare-search-results)。 +- **[用户行为洞察(UBI)](/search-plugins/ubi/)**:捕获和分析用户行为数据,了解用户如何与搜索结果交互并识别改进领域。 -- 使用交叉编码器(cross-encoder)重排序器[对搜索结果进行重排序](/search-plugins/search-relevance/reranking-search-results)。 +- **[搜索相关性工作台](/search-plugins/search-relevance/using-search-relevance-workbench)**:一套全面的工具,通过查询比较、结果评估和 A/B 测试来实验和提高搜索相关性。 -- 使用 [Querqy](/search-plugins/querqy/) 改写查询。 +- **[相关性代理](/search-plugins/search-relevance/relevance-agent)**:专门设计用于持续改进搜索相关性的代理。 + +- **[查询重写](/search-plugins/search-relevance/query-rewriting)**:转换用户查询以提高搜索准确性,处理同义词、拼写错误和其他查询变体。 + +- **[学习排序(LTR)](/search-plugins/ltr/)**:使用基于行为数据训练的机器学习模型来改进搜索结果的排名。 + +- **[重排序搜索结果](/search-plugins/search-relevance/reranking-search-results)**:应用机器学习模型重新排序搜索结果以提高相关性。 + +## 搜索质量工作流程 + +典型的搜索质量改进工作流程包括: + +1. **数据收集**:使用 UBI 捕获用户行为和交互数据。 +2. **分析**:分析用户行为模式以识别搜索质量问题。 +3. **实验**:使用搜索相关性工作台测试不同的方法。 +4. **模型训练**:使用行为数据训练 LTR 模型以改进排名。 +5. **查询增强**:应用查询重写规则以改进查询理解。 +6. **重排序**:应用基于 ML 的重排序以进一步优化结果。 +7. **评估**:持续监控和评估搜索性能。 + +## 相关文档 + +- [重排序搜索结果教程](/tutorials/reranking/):了解如何使用各种机器学习模型和平台实现搜索结果重排序。 diff --git a/i18n/zh/search-plugins/search-relevance/judgments.md b/i18n/zh/search-plugins/search-relevance/judgments.md new file mode 100644 index 00000000..d5d03741 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/judgments.md @@ -0,0 +1,583 @@ +--- +title: 判断 +--- + +# 判断 + +判断是在特定查询上下文中分配给特定文档的相关性评分。多个判断被组合成判断列表。 +通常,判断分为两种类型---隐式和显式: + +- 隐式判断是从用户行为中派生的评分(例如,用户搜索后看到并选择了什么?)。 +- 传统上由人类产生显式判断,但大型语言模型(LLM)越来越多地用于此任务。 + +搜索相关性工作台(SRW)支持所有类型的判断: + +- 使用 LLM 作为自动评判员(称为 LLM-as-a-Judge 的方法),通过使用提示评估搜索结果来生成判断。 +- 基于符合用户行为洞察(UBI)模式规范的数据生成隐式判断。 +- 导入在 SRW 外部使用流程收集的判断。 + +## 使用 LLM-as-a-Judge + +当您没有人工标注员可用时,或者您需要将判断数量扩展到超出人类能力范围时,可以在 SRW 中使用 LLM 生成显式判断。 + +有关分步说明,请参阅[使用 LLM-as-a-Judge 进行搜索相关性评估](/tutorials/llm-as-a-judge-tutorial/)。 + +### 先决条件 + +要使用 LLM-as-a-Judge,请配置以下组件: + +- 用于生成判断的 LLM 连接器。有关更多信息,请参阅[连接器](/ml-commons-plugin/remote-models/connectors)。 +- 查询集:与 `size` 参数一起,查询集定义了生成判断的范围。对于每个查询,从指定索引检索前 k 个文档,其中 k 由 `size` 参数定义。 +- 搜索配置:搜索配置定义如何检索文档以用于查询-文档对。 + +AI 辅助判断流程包括以下步骤: + +- 对于每个查询,使用定义的搜索配置(包括索引信息)检索前 k 个文档。查询和结果列表中的每个文档创建一个查询-文档对。 +- 然后使用预定义提示调用 LLM,为每个查询-文档对生成判断。 +- 所有生成的判断都存储在判断列表中。 + +要创建判断列表,请提供 LLM 的模型 ID、可用的查询集和已创建的搜索配置。 + +以下示例使用通用提示模板,评分范围为 0.0 到 1.0。为了减少发送到 LLM 的数据量(从而降低成本),请使用 `contextFields` 参数指定每个结果中要包含的字段: + +```json +PUT _plugins/_search_relevance/judgments +{ + "name":"AI-assisted judgment list", + "description": "Uses gpt-4o-mini to evaluate product search results", + "type":"LLM_JUDGMENT", + "modelId":"N8AE1osB0jLkkocYjz7D", + "querySetId":"5f0115ad-94b9-403a-912f-3e762870ccf6", + "searchConfigurationList":["2f90d4fd-bd5e-450f-95bb-eabe4a740bd1"], + "size":5, + "contextFields": ["title", "description", "category"], + "llmJudgmentRatingType": "SCORE0_1", + "promptTemplate": "Rate the relevance of these search results {{hits}} for the query '{{queryText}}' on a scale of 0-1, where 0 is completely irrelevant and 1 is perfectly relevant. Consider the product title, description, and category." +} +``` + +### 请求正文字段 + +下表列出了创建基于 LLM 的判断的参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | 字符串 | 判断列表的名称。 | +| `description` | 字符串 | 可选。判断列表的描述。 | +| `type` | 字符串 | 设置为 `LLM_JUDGMENT`。 | +| `modelId` | 字符串 | 用于生成判断的已部署机器学习(ML)模型的 ID。必须是连接到外部 LLM 服务的远程模型。 | +| `querySetId` | 字符串 | 包含要评估的查询的查询集 ID。 | +| `searchConfigurationList` | 字符串数组 | 用于检索要评估的文档的搜索配置 ID 列表。 | +| `size` | 整数 | 每个查询要检索和评估的顶部文档数。默认为 `10`。 | +| `tokenLimit` | 整数 | 单个请求中发送到 LLM 的最大令牌数。当总内容超过此限制时,用于批量处理文档。默认为 `4,000`。 | +| `contextFields` | 字符串数组 | 可选。指定向 LLM 发送内容时要包含的文档字段。如果未指定,则发送整个文档源。使用此参数可降低成本并使 LLM 专注于相关字段。 | +| `ignoreFailure` | 布尔值 | 如果 LLM 无法为某些文档生成判断,是否继续处理其他文档。默认为 `false`。 | +| `llmJudgmentRatingType` | 字符串 | 要使用的评分量表类型。有效值为 `SCORE0_1`(0--1 数字量表)和 `RELEVANT_IRRELEVANT`(二元相关/不相关)。对于 NDCG 等分级相关性指标使用 `SCORE0_1`。对于精确率和召回率等二元指标使用 `RELEVANT_IRRELEVANT`。 | +| `promptTemplate` | 字符串 | 可选。LLM 的自定义提示模板。支持 `{{queryText}}` 和 `{{hits}}` 占位符。如果未提供,则使用默认模板。 | +| `existingJudgments` | 字符串数组 | 可选。最多 5 个现有判断 ID 的列表,其评分将被重用。对于每个查询-文档对,SRW 按顺序检查这些判断,使用找到的第一个匹配项的评分。只有在这些判断中没有现有评分的对才会发送到 LLM 进行评估。 | +| `overwriteCache` | 布尔值 | 可选。已弃用。接受但被忽略。全局判断缓存已移除。 | + +### 重试失败的判断请求 + +生成判断会为每个查询-文档对发送一个 LLM 请求。在大规模时偶尔失败是预期的:例如,提供商可能会限制请求或请求可能超时。要自动重试这些请求,请使用连接器的 `client_config` 设置(`max_retry_times`、`retry_backoff_policy` 和相关选项)在用于判断的连接器上配置重试。有关更多信息,请参阅 [client_config 对象](/ml-commons-plugin/api/connector-apis/create-connector#the-client_config-object)。 + +### 重试失败的文档 + +本节仅适用于 `LLM_JUDGMENT` 列表。 + +即使某些文档没有收到评分(例如因为 LLM 提供商限制或超时了这些请求),判断列表也可以以 `COMPLETED` 状态完成。未评分的文档出现在每个查询的 `failures` 数组中,运行的总体计数出现在判断列表的 `metadata` 字段中,如[查看判断列表](#查看判断列表)所示。您可以通过向 `_retry` 端点发送带有判断列表 ID 的 `POST` 请求来仅重试失败的文档,而不是重新生成整个判断列表。 + +#### 端点 + +```json +POST _plugins/_search_relevance/judgments/{judgment_list_id}/_retry +``` + +#### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `judgment_list_id` | 字符串 | 要重试其失败文档的判断列表 ID。 | + +#### 示例请求 + +```json +POST _plugins/_search_relevance/judgments/b54f791a-3b02-49cb-a06c-46ab650b2ade/_retry +``` + +#### 示例响应 + +```json +{ + "judgment_id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "status": "RETRYING", + "message": "Retrying failed documents" +} +``` + +重试异步运行,仅为之前失败的文档生成新评分;已成功的评分保持不变。响应立即返回,`status` 为 `RETRYING`。要跟踪进度,请检索判断列表并检查其 `status`,如[查看判断列表](#查看判断列表)所述。如果单个文档仍然无法获得评分(例如,因为 LLM 提供商仍在限制请求),判断列表的 `status` 将返回 `COMPLETED`---检查 `failures` 数组和 `metadata` 字段以查看哪些文档仍未评分。如果重试过程本身失败(例如,由于内部错误),判断列表的 `status` 将变为 `ERROR`。 + +#### 状态值 + +下表列出了判断列表可能的 `status` 值。 + +| 状态 | 描述 | +| :--- | :--- | +| `PROCESSING` | 判断列表正在生成中。 | +| `COMPLETED` | 生成(或重试)已完成。某些文档可能仍未评分:检查 `failures` 数组和 `metadata` 字段以验证文档评分。 | +| `RETRYING` | 正在重试之前失败的文档。 | +| `ERROR` | 重试过程本身在内部失败。这与单个文档无法获得评分不同,后者仍会导致 `COMPLETED` 状态。 | + +### 自定义提示模板 + +您可以自定义提示模板以关注相关性的特定方面: + +```json +PUT /_plugins/_search_relevance/judgments +{ + "name": "Custom Prompt Judgment", + "type": "LLM_JUDGMENT", + "modelId": "MODEL_ID_HERE", + "querySetId": "QUERY_SET_ID_HERE", + "searchConfigurationList": ["SEARCH_CONFIGURATION_ID_HERE"], + "promptTemplate": "As an e-commerce search expert, evaluate how well these products {{hits}} match the user's search for '{{queryText}}'. Consider product relevance, brand reputation, and price competitiveness. Rate each result from 0-1.", + "llmJudgmentRatingType": "SCORE0_1" +} +``` + +### 二元相关性判断 + +对于更简单的相关性评估,您可以使用二元(相关/不相关)判断: + +```json +PUT /_plugins/_search_relevance/judgments +{ + "name": "Binary LLM Judgment", + "type": "LLM_JUDGMENT", + "modelId": "MODEL_ID_HERE", + "querySetId": "QUERY_SET_ID_HERE", + "searchConfigurationList": ["SEARCH_CONFIGURATION_ID_HERE"], + "llmJudgmentRatingType": "RELEVANT_IRRELEVANT", + "promptTemplate": "Determine if these search results {{hits}} are relevant or irrelevant for the query '{{queryText}}'. Consider exact matches and semantic relevance." +} +``` + +### 使用不同的 LLM 提供商 + +LLM-as-a-Judge 可与您可以使用 [ML Commons 连接器](/ml-commons-plugin/remote-models/connectors)连接的任何 LLM 提供商配合使用。蓝图可用于 OpenAI、Azure OpenAI、DeepSeek、Ollama、Google Gemini 和 Amazon Bedrock。有关更多信息,请参阅 [OpenSearch 提供的连接器蓝图](/ml-commons-plugin/remote-models/supported-connectors#llm-judgment-blueprints-for-search-relevance-workbench)。 + +#### Amazon Bedrock 示例 + +以下示例为 Amazon Bedrock 上的 Anthropic Claude 模型创建连接器: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "Amazon Bedrock Anthropic Claude", + "description": "Anthropic Claude via Bedrock for SRW LLM judgments", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<YOUR AWS ACCESS KEY>", + "secret_key": "<YOUR AWS SECRET KEY>" + }, + "parameters": { + "region": "<YOUR AWS REGION>", // 示例:us-east-1 + "service_name": "bedrock", + "anthropic_version": "bedrock-2023-05-31", + "max_tokens": 8000, + "model": "<INFERENCE_PROFILE_ID>" // 示例:us.anthropic.claude-haiku-4-5-20251001-v1:0 + }, + "client_config": { + "max_retry_times": 3, + "retry_backoff_policy": "exponential_full_jitter" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "headers": { + "content-type": "application/json" + }, + "url": "https://bedrock-runtime.${parameters.region}.amazonaws.com/model/${parameters.model}/invoke", + "request_body": "{\"anthropic_version\":\"${parameters.anthropic_version}\",\"max_tokens\":${parameters.max_tokens},\"system\":\"${parameters.system_prompt}\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"${parameters.user_prompt}\"}]}]}", + "post_process_function": "def text = params.content[0].text; return '{\"name\":\"response\",\"dataAsMap\":{\"response\":\"' + escape(text) + '\"}}'" + } + ] +} +``` + +## 隐式判断 + +隐式判断是从过去的用户交互中派生的。SRW 支持点击超过预期点击(COEC)点击模型,该模型使用*展示*和*点击*信号来计算判断。 + +输入数据必须遵循 [UBI 索引模式](/search-plugins/ubi/schemas)。COEC 使用 `ubi_events` 索引中 `action_name` 为 `impression` 或 `click` 的每个事件。使用 `ubiEventsIndex` 参数从不同名称的索引中读取。 + +COEC 通过将点击总数除以在该排名处观察到的展示总数来计算每个排名的预期点击率(CTR),基于 `ubi_events` 中的所有事件。这个比率代表该位置的预期 CTR。 + +对于查询后显示在命中列表中的每个文档,该排名的平均 CTR 作为查询-文档对的预期值。COEC 计算查询-文档对的实际 CTR,并将其除以此预期的基于排名的 CTR。因此,CTR 高于该排名平均值的查询-文档对的判断值大于 1。相反,如果 CTR 低于平均值,则判断值低于 1。 + +::: info NOTE +根据跟踪实现,可以在 `ubi_events` 索引中记录单个查询的多次点击。因此,平均 CTR 有时可能超过 1(或 100%)。 +::: + +::: info NOTE +对于出现在不同位置的查询-文档观察,假定所有展示和点击都发生在最低(最佳)位置。这种聚合方法使最终判断偏向较低值,反映了排名较高的结果通常获得较高 CTR 的常见趋势。 +::: + +### 示例请求 + +以下示例使用 COEC 点击模型创建隐式判断列表: + +```json +PUT _plugins/_search_relevance/judgments +{ + "name": "Implicit Judgments", + "clickModel": "coec", + "type": "UBI_JUDGMENT", + "maxRank": 20 +} +``` + +### 请求正文字段 + +下表列出了创建隐式判断的参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | 字符串 | 判断列表的名称。 | +| `clickModel` | 字符串 | 用于计算隐式判断的模型。仅支持 `coec`(点击超过预期点击)。 | +| `type` | 字符串 | 设置为 `UBI_JUDGMENT`。 | +| `maxRank` | 整数 | 在判断计算中包含事件时要考虑的最大排名。 | +| `startDate` | 日期 | 一个可选的起始日期,从该日期开始考虑用于隐式判断生成的行为数据事件。格式为 `yyyy-MM-dd`。 | +| `endDate` | 日期 | 一个可选的结束日期,直到该日期考虑用于隐式判断生成的行为数据事件。格式为 `yyyy-MM-dd`。 | +| `ubiEventsIndex` | 字符串 | 包含要分析的 UBI 事件的索引的可选名称。默认为 `ubi_events`。当您的 UBI 事件存储在具有不同名称的索引中时,请指定此参数。 | + +## 导入判断 + +您可能已经有用于生成判断的外部流程。无论判断类型或生成方式如何,您都可以将它们导入 SRW。 + +### 示例请求 + +以下示例为两个查询导入一组判断: + +```json +PUT _plugins/_search_relevance/judgments +{ + "name": "Imported Judgments", + "description": "Judgments generated outside SRW", + "type": "IMPORT_JUDGMENT", + "judgmentRatings": [ + { + "query": "red dress", + "ratings": [ + { + "docId": "B077ZJXCTS", + "rating": "3.000" + }, + { + "docId": "B071S6LTJJ", + "rating": "2.000" + }, + { + "docId": "B01IDSPDJI", + "rating": "2.000" + }, + { + "docId": "B07QRCGL3G", + "rating": "0.000" + }, + { + "docId": "B074V6Q1DR", + "rating": "1.000" + } + ] + }, + { + "query": "blue jeans", + "ratings": [ + { + "docId": "B07L9V4Y98", + "rating": "0.000" + }, + { + "docId": "B01N0DSRJC", + "rating": "1.000" + }, + { + "docId": "B001CRAWCQ", + "rating": "1.000" + }, + { + "docId": "B075DGJZRM", + "rating": "2.000" + }, + { + "docId": "B009ZD297U", + "rating": "2.000" + } + ] + } + ] +} +``` + +### 请求正文字段 + +下表列出了导入判断的参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `name` | 字符串 | 判断列表的名称。 | +| `description` | 字符串 | 判断列表的可选描述。 | +| `type` | 字符串 | 设置为 `IMPORT_JUDGMENT`。 | +| `judgmentRatings` | 数组 | 包含判断的 JSON 对象列表。判断按查询分组,每个包含一个嵌套映射,其中文档 ID(`docId`)作为键,其浮点评分作为值。 | + +## 管理判断列表 + +您可以使用以下 API 检索或删除判断列表。 + +### 查看判断列表 + +通过 ID 检索判断列表。 + +#### 端点 + +```json +GET _plugins/_search_relevance/judgments/{judgment_list_id} +``` + +#### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `judgment_list_id` | 字符串 | 要检索的判断列表的 ID。 | + +#### 示例请求 + +```json +GET _plugins/_search_relevance/judgments/b54f791a-3b02-49cb-a06c-46ab650b2ade +``` + +#### 示例响应 + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 36, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "search-relevance-judgment", + "_id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "_score": 1, + "_source": { + "id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "timestamp": "2025-06-11T06:07:23.766Z", + "name": "LLM Judgments", + "status": "COMPLETED", + "type": "LLM_JUDGMENT", + "metadata": { + "totalQueries": 2, + "successfulQueries": 1, + "failedQueries": 1, + "lastFailureReason": "Rate limit exceeded" + }, + "judgmentRatings": [ + { + "query": "red dress", + "ratings": [ + { + "rating": "3.000", + "docId": "B077ZJXCTS" + }, + { + "rating": "2.000", + "docId": "B071S6LTJJ" + }, + { + "rating": "0.000", + "docId": "B07QRCGL3G" + }, + { + "rating": "1.000", + "docId": "B074V6Q1DR" + } + ], + "failures": [ + { + "docId": "B01IDSPDJI" + } + ] + }, + { + "query": "blue jeans", + "ratings": [ + { + "rating": "0.000", + "docId": "B07L9V4Y98" + }, + { + "rating": "1.000", + "docId": "B01N0DSRJC" + }, + { + "rating": "1.000", + "docId": "B001CRAWCQ" + }, + { + "rating": "2.000", + "docId": "B075DGJZRM" + }, + { + "rating": "2.000", + "docId": "B009ZD297U" + } + ] + } + ] + } + } + ] + } +} +``` + +</details> + +未评分的文档出现在每个查询的 `failures` 数组中。运行的总体计数出现在判断列表的 `metadata` 字段中。要仅重试 `LLM_JUDGMENT` 列表中失败的文档,请参阅[重试失败的文档](#重试失败的文档)。 + +### 删除判断列表 + +通过 ID 删除判断列表。 + +#### 端点 + +```json +DELETE _plugins/_search_relevance/judgments/{judgment_list_id} +``` + +#### 示例请求 + +```json +DELETE _plugins/_search_relevance/judgments/b54f791a-3b02-49cb-a06c-46ab650b2ade +``` + +#### 示例响应 + +```json +{ + "_index": "search-relevance-judgment", + "_id": "b54f791a-3b02-49cb-a06c-46ab650b2ade", + "_version": 3, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 156, + "_primary_term": 1 +} +``` + +### 搜索判断列表 + +使用查询领域特定语言(DSL)搜索判断列表。响应默认排除 `judgmentRatings.ratings`;要包含它,请在查询中指定 `_source` 字段。 + +#### 端点 + +```json +GET _plugins/_search_relevance/judgments/_search +POST _plugins/_search_relevance/judgments/_search +``` + +#### 示例请求 + +以下示例搜索包含确切查询 `red dress` 的判断列表: + +```json +GET _plugins/_search_relevance/judgments/_search +{ + "query": { + "nested": { + "path": "judgmentRatings", + "query": { + "match_phrase": { + "judgmentRatings.query": "red dress" + } + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 29, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 4.5558767, + "hits": [ + { + "_index": "search-relevance-judgment", + "_id": "505d00cf-2fce-422b-bb97-2e3a95ce9446", + "_score": 4.5558767, + "_source": { + "metadata": {}, + "name": "Imported Judgments", + "judgmentRatings": [ + { + "query": "red dress" + }, + { + "query": "blue jeans" + } + ], + "id": "505d00cf-2fce-422b-bb97-2e3a95ce9446", + "type": "IMPORT_JUDGMENT", + "timestamp": "2026-01-28T18:16:44.218Z", + "status": "COMPLETED" + } + } + ] + } +} +``` + +## 相关文档 + +- [使用 LLM-as-a-Judge 进行搜索相关性评估](/tutorials/llm-as-a-judge-tutorial/) diff --git a/i18n/zh/search-plugins/search-relevance/optimize-hybrid-search.md b/i18n/zh/search-plugins/search-relevance/optimize-hybrid-search.md new file mode 100644 index 00000000..a9791382 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/optimize-hybrid-search.md @@ -0,0 +1,107 @@ +--- +title: 优化混合搜索 +--- + +# 优化混合搜索 + +在 OpenSearch 中使用混合搜索的一个关键挑战是有效地组合词法搜索和基于向量的搜索的结果。OpenSearch 提供了不同的技术和各种参数,您可以通过实验找到最适合您应用程序的设置。然而,什么效果最好在很大程度上取决于您的数据、用户行为和应用领域——没有一刀切的解决方案。 + +搜索相关性工作台帮助您系统地找到满足您需求的理想参数集。 + +## 要求 + +在内部,优化混合搜索涉及运行多个搜索质量评估实验。对于这些实验,您需要查询集、判断和搜索配置。 +搜索相关性工作台支持恰好两个查询子句的混合搜索优化。虽然混合搜索通常结合向量和词法查询,但您可以使用两个词法查询子句运行混合搜索优化: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "hybrid_query_lexical", + "query": "{\"query\":{\"hybrid\":{\"queries\":[{\"match\":{\"title\":\"%queryText%\"}},{\"match\":{\"category\":\"%queryText%\"}}]}}}", + "index": "ecommerce" +} +``` + +混合搜索优化在结合词法搜索和基于向量的搜索结果时最有价值。为获得最佳结果,请配置具有两个子句的混合搜索查询:一个文本查询子句和一个神经查询子句。您不需要配置搜索管道来组合结果,因为混合搜索优化过程会自动处理此操作。以下是适合混合搜索优化的搜索配置示例: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "hybrid_query_text", + "query": "{\"query\":{\"hybrid\":{\"queries\":[{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title\",\"category\",\"bullets\",\"description\",\"attrs.Brand\\\",\"attrs.Color\"]}},{\"neural\":{\"title_embedding\":{\"query_text\":\"%queryText%\",\"k\":100,\"model_id\":\"lRFFb5cBHkapxdNcFFkP\"}}}]}},\"size\":10}", + "index": "ecommerce" +} +``` + +`query` 中指定的模型 ID 必须是在 OpenSearch 中部署的模型的有效模型 ID。目标索引必须包含存储嵌入的字段(在此示例中为 `title_embedding`)。 + +有关端到端示例,请参阅 [`search-relevance` 仓库](https://github.com/opensearch-project/search-relevance)。 + +## 运行混合搜索优化实验 + +您可以通过调用搜索相关性工作台 `experiments` 端点来创建混合搜索优化实验。 + +### 端点 + +```json +PUT _plugins/_search_relevance/experiments +``` + +### 示例请求 + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "b16a6a2b-ed6e-49af-bb2b-fc739dcf24e6", + "searchConfigurationList": ["508a8812-27c9-45fc-999a-05f859f9b210"], + "judgmentList": ["1b944d40-e95a-43f6-9e92-9ce00f70de79"], + "size": 10, + "type": "HYBRID_OPTIMIZER" +} +``` + +### 示例响应 + +```json +{ + "experiment_id": "0f4eff05-fd14-4e85-ab5e-e8e484cdac73", + "experiment_result": "CREATED" +} +``` + +## 实验过程 + +混合搜索优化实验针对查询集中的每个查询评估以下参数变体的所有组合,并根据判断列表对结果进行评分: + +- 基于分数的变体: + - 归一化技术:`l2`、`min_max` 和 `z_score`。由于[归一化处理器](/search-plugins/search-pipelines/normalization-processor#request-body-fields)的限制,`z_score` 技术只能与 `arithmetic_mean` 组合。 + - 组合技术:`arithmetic_mean`、`harmonic_mean` 和 `geometric_mean`。 + - 词法和向量搜索权重范围从 `0.0` 到 `1.0`,以 `0.1` 为增量。 + +- 基于排名的变体: + - `rrf`([倒数排名融合(RRF)](/search-plugins/search-pipelines/score-ranker-processor))组合技术,使用 `rank_constant` 值 `1`、`5`、`10`、`20` 和 `60` 进行评估。RRF 变体在所有子查询中使用相等权重。 + +## 评估结果 + +每次评估的结果都被存储。您可以在 OpenSearch Dashboards 中通过在过去实验概览中选择相应的实验来查看结果,如下图所示。 + +*比较搜索结果* + +显示所有执行的查询及其计算的搜索指标,如下图所示。 + +*比较搜索结果* + +要查看查询变体,请选择其中一个查询,如下图所示。 + +*比较搜索结果* + +您还可以使用以下 SQL 搜索语句检索此信息,并提供您的 `experimentId`: + +```json +POST _plugins/_sql +{ + "query": "SELECT ev.parameters.normalization, ev.parameters.combination, ev.parameters.weights, ev.results.evaluationResultId, ev.experimentId, er.id, er.metrics, er.searchText FROM search-relevance-experiment-variant ev JOIN search-relevance-evaluation-result er ON ev.results.evaluationResultId = er.id WHERE ev.experimentId = '814e2378-901c-4273-9873-9b758a33089d'" +} +``` + +要直观地查看这些结果,请参阅[探索搜索评估结果](/search-plugins/search-relevance/explore-experiment-results)。 diff --git a/i18n/zh/search-plugins/search-relevance/query-rewriting.md b/i18n/zh/search-plugins/search-relevance/query-rewriting.md new file mode 100644 index 00000000..bdf3b4bc --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/query-rewriting.md @@ -0,0 +1,13 @@ +--- +title: 查询重写 +--- + +# 查询重写 + +查询重写是在执行用户查询之前对其进行转换或修改的过程。查询重写的目标是通过解决拼写错误、同义词、歧义术语或低效查询结构等问题来提高搜索准确性、相关性或性能。查询重写通常用于搜索系统以提高搜索结果的质量。 + +您可以使用以下功能在 OpenSearch 中执行查询重写: + +- [模板查询](/search-plugins/search-relevance/template-query):创建带有动态占位符的查询,这些占位符在查询执行期间解析,对于机器学习推理和运行时参数生成很有用。 + +- [Querqy](/search-plugins/querqy/):一个用于高级查询重写的社区插件,具有用于提升、降权、过滤和重定向搜索结果的规则。 diff --git a/i18n/zh/search-plugins/search-relevance/query-sets.md b/i18n/zh/search-plugins/search-relevance/query-sets.md new file mode 100644 index 00000000..71197675 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/query-sets.md @@ -0,0 +1,310 @@ +--- +title: 查询集 +--- + +# 查询集 + +查询集是查询的集合。这些查询用于搜索相关性评估实验。搜索相关性工作台提供不同的采样技术,用于从符合[用户行为洞察(UBI)](/search-plugins/ubi/schemas)规范的真实用户数据创建查询集。 +此外,搜索相关性工作台允许您导入查询集。 + +## 创建查询集 + +如果您使用 UBI 规范跟踪用户行为,您可以从不同的采样方法中选择,这些方法可以基于存储在 `ubi_queries` 索引中的真实用户查询创建查询集。使用 `ubiQueriesIndex` 参数从不同名称的索引中采样。 + +搜索相关性工作台支持三种采样方法: +* Random:随机抽取所有查询的样本。 +* [Probability-Proportional-to-Size Sampling](https://opensourceconnections.com/blog/2022/10/13/how-to-succeed-with-explicit-relevance-evaluation-using-probability-proportional-to-size-sampling/):获取所有查询的频率加权样本以获得代表性样本。 +* Top N:获取最频繁的 N 个查询。 + +### 端点 + +```json +POST _plugins/_search_relevance/query_sets +``` + +### 请求正文字段 + +下表列出了可用的输入参数。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`name` | 字符串 | 查询集的名称。最大长度为 50 个字符。 +`description` | 字符串 | 查询集的简短描述。最大长度为 250 个字符。 +`sampling` | 字符串 | 定义使用哪个采样器。有效值为 `pptss`(Probability-Proportional-to-Size-Sampling)、`random`、`topn`(最频繁的查询)和 `manual`。 +`querySetSize` | 整数 | 查询集中查询的目标数量。根据 `ubi_queries` 中唯一查询的数量,生成的查询集可能包含较少的查询。必须是正整数。 +`ubiQueriesIndex` | 字符串 | 包含要采样的 UBI 查询的索引的可选名称。默认为 `ubi_queries`。当您的 UBI 查询存储在不同名称的索引中时,请指定此参数。 + +### 示例请求:使用 Top N 采样器采样 20 个查询 + +```json +POST _plugins/_search_relevance/query_sets +{ + "name": "Top 20", + "description": "Top 20 most frequent queries sourced from user searches.", + "sampling": "topn", + "querySetSize": 20 +} +``` + +### 示例请求:手动上传查询集 + +```json +PUT _plugins/_search_relevance/query_sets +{ + "name": "TVs", + "description": "TV queries", + "sampling": "manual", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "led tv" + } + ] +} +``` + +## 查询集格式 + +搜索相关性工作台支持两种查询集格式,每种格式针对不同的用例设计。两种格式都是用户查询的集合,但它们的区别在于是否包含预期答案。 + +* **基本查询集**:没有任何附加信息的用户查询列表。这对于没有特定预期答案的一般相关性测试很有用。 + +* **带参考答案的查询集**:用户查询列表,其中每个查询都与其预期答案配对。此格式对于评估旨在提供特定答案的应用程序(如问答系统)特别有用。 + +### 字段 + +所有查询集包含一个或多个条目。每个条目是一个包含以下字段的 JSON 对象。 + +| 字段 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `queryText` | 字符串 | 用户查询字符串。必需。 | +| `referenceAnswer` | 字符串 | 用户查询的预期或正确答案。此字段用于生成判断,特别是使用大型语言模型(LLM)时。可选。 | +| 自定义字段 | 字符串 | 除 `queryText` 和 `referenceAnswer` 之外的任何字段都作为自定义字段存储在条目中。您可以在搜索配置中通过字段名作为 [Mustache 模板变量](/search-plugins/search-relevance/search-configurations#using-mustache-templates)引用自定义字段。可选。 | + +### 基本查询集示例 + +基本查询集仅包含每个条目的 `queryText` 字段。它适用于不存在单一"正确"答案的一般相关性测试。 + +#### 没有参考答案的示例查询集 + +```json +{"queryText": "t towels kitchen"} +{"queryText": "table top bandsaw for metal"} +{"queryText": "tan strappy heels for women"} +{"queryText": "tank top plus size women"} +{"queryText": "tape and mudding tools"} +``` + +### 带参考答案的查询集示例 + +在此格式中,每个条目将 `queryText` 与 `referenceAnswer` 配对。使用它来评估返回特定答案的应用程序,如聊天机器人或问答系统。 + +#### 带参考答案的示例查询集 + +```json +{"queryText": "What is the capital of France?", "referenceAnswer": "Paris"} +{"queryText": "Who wrote 'Romeo and Juliet'?", "referenceAnswer": "William Shakespeare"} +{"queryText": "What is the chemical symbol for water?", "referenceAnswer": "H2O"} +{"queryText": "What is the highest mountain in the world?", "referenceAnswer": "Mount Everest"} +{"queryText": "When was the first iPhone released?", "referenceAnswer": "June 29, 2007"} +``` + +当使用 [LLM 生成判断](/search-plugins/search-relevance/judgments)时,`referenceAnswer` 字段特别有用。LLM 可以使用参考答案作为基准真值与检索到的搜索结果进行比较,从而准确评分响应的相关性。 + +### 带自定义字段的查询集示例 + +除了 `queryText`,每个条目还可以包含自定义字段。您可以在[搜索配置](/search-plugins/search-relevance/search-configurations#using-mustache-templates)中将这些字段作为 Mustache 模板变量引用,以便一个搜索配置可以对每个查询应用不同的过滤器或参数。 + +#### 带自定义字段的示例查询集 + +在以下示例中,每个条目包含一个 `category` 自定义字段。如果搜索配置在其查询中引用 `{{category}}`,它将按相应条目中的 `category` 值过滤每个查询的结果: + +```json +{"queryText": "phone", "category": "electronics"} +{"queryText": "steel", "category": "materials"} +{"queryText": "keyboard", "category": "electronics"} +``` + +## 管理查询集 + +您可以使用以下 API 检索或删除查询集。 + +### 检索查询集 + +此 API 检索可用的查询集。 + +#### 端点 + +```json +GET _plugins/_search_relevance/query_sets +GET _plugins/_search_relevance/query_sets/{query_set_id} +``` + +#### 示例响应 + +```json +{ + "took": 2, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "search-relevance-queryset", + "_id": "bb45c4c4-48ce-461b-acbc-f154c0a17ec9", + "_score": null, + "_source": { + "id": "bb45c4c4-48ce-461b-acbc-f154c0a17ec9", + "name": "TVs", + "description": "Some TVs that people might want", + "sampling": "manual", + "timestamp": "2025-06-11T13:43:26.676Z", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "led tv" + } + ] + }, + "sort": [ + 1749649406676 + ] + } + ] + } +} +``` + +### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `query_set_id` | 字符串 | 要检索的查询集的 ID。为空时检索所有查询集。 | + +### 删除查询集 + +您可以使用查询集 ID 删除查询集。 + +#### 端点 + +```json +DELETE _plugins/_search_relevance/query_sets/{query_set_id} +``` + +#### 示例请求 + +```json +DELETE _plugins/_search_relevance/query_sets/bb45c4c4-48ce-461b-acbc-f154c0a17ec9 +``` + +#### 示例响应 + +```json +{ + "_index": "search-relevance-queryset", + "_id": "bb45c4c4-48ce-461b-acbc-f154c0a17ec9", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 17, + "_primary_term": 1 +} +``` + +### 搜索查询集 + +您可以使用查询 DSL 搜索可用的查询集。 + +#### 端点 + +```json +GET _plugins/_search_relevance/query_sets/_search +POST _plugins/_search_relevance/query_sets/_search +``` + +#### 示例请求 + +搜索包含短语 `lamp without cord` 的查询的查询集: + +```json +GET _plugins/_search_relevance/query_sets/_search +{ + "query": { + "nested": { + "path": "querySetQueries", + "query": { + "match_phrase": { + "querySetQueries.queryText": "lamp without cord" + } + } + } + } +} +``` + +#### 示例响应 + +响应包含匹配的查询集,因为 `wall lamp without cord` 包含部分搜索词 `lamp without cord`: + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "search-relevance-queryset", + "_id": "4622775e-9099-4375-af7f-f970dae25f09", + "_score": 1, + "_source": { + "id": "4622775e-9099-4375-af7f-f970dae25f09", + "name": "ESCI Queries", + "description": "Queries from the ESCI ranking task", + "sampling": "manual", + "timestamp": "2026-01-20T12:49:35.940Z", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "wall lamp without cord" + } + ] + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/search-relevance/regularly-scheduled-experiments.md b/i18n/zh/search-plugins/search-relevance/regularly-scheduled-experiments.md new file mode 100644 index 00000000..0dd80393 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/regularly-scheduled-experiments.md @@ -0,0 +1,176 @@ +--- +title: 监控搜索质量 +--- + +# 监控搜索质量 +<Badge type="tip" text="3.4 版本引入" /> + +搜索质量不是静态的。即使您的排名算法保持不变,索引数据也会演变,流行度和时效性等信号会波动,用户查询也会随时间变化。 + +要检测和防止相关性的意外变化,您应该持续监控搜索质量。您可以配置 cron 计划以定期运行搜索评估实验。 + +每个作业只能有一个计划。要修改计划,请删除现有计划并创建新计划。删除计划也会删除其关联的历史数据。 + +## 使用搜索相关性工作台计划搜索评估 + +首次成功运行搜索评估后,会出现一个时钟图标,允许您计划实验,如下图所示。 + +*计划实验运行* + +在计划页面上,配置您希望实验运行的频率,如下图所示。 + +*设置运行频率的计划* + +### 评估搜索质量 + +计划实验后,新的仪表板图标可让您随时间监控搜索结果。由于仪表板每天评估结果,数据可能需要最多 24 小时才能填充并显示有意义的洞察。 + +*随时间查看搜索质量* + +## 使用 API 计划搜索评估 + +您可以使用 API 创建定期计划的实验。您要计划的实验必须已存在。 + +### 端点 + +```json +POST _plugins/_search_relevance/experiments/schedule +``` + +### 请求正文字段 + +下表列出了可用的输入参数。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`experimentId` | 字符串 | 要重新运行的实验 ID。 +`cronExpression` | 字符串 | 以 UTC 运行评估的 cron 计划。 + +### 示例请求 + +以下请求将实验计划为每晚凌晨 1 点运行: + +```json +POST _plugins/_search_relevance/experiments/schedule +{ + "experimentId": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "cronExpression": "0 1 * * *" +} +``` + +## 管理计划实验 + +您可以使用以下 API 检索或删除计划实验。 + +### 检索计划实验 + +此 API 检索可用的计划实验。 + +#### 端点 + +```json +GET _plugins/_search_relevance/experiments/schedule +GET _plugins/_search_relevance/experiments/schedule/{experiment_id} +``` + +#### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `experiment_id` | 字符串 | 要检索的计划实验的 ID。如果未提供,则检索所有计划实验。 | + +#### 示例请求 + +```json +GET _plugins/_search_relevance/experiments/schedule/6282afa6-fa14-49c8-a627-ac1d5204d357 +``` + +#### 示例响应 + +```json +{ + "took": 17, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": ".search-relevance-scheduled-experiment-jobs", + "_id": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "_score": null, + "_source": { + "id": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "enabled": true, + "schedule": { + "cron": { + "expression": "0 0 * * *", + "timezone": "America/Los_Angeles" + } + }, + "enabledTime": 1758320475601, + "lastUpdateTime": 1758320475601, + "timestamp": "2025-09-19T00:00:00.602Z" + }, + "sort": [ + "2025-09-19T00:00:00.602Z" + ] + } + ] + } +} +``` + +### 删除计划实验 + +您可以使用计划实验 ID 删除计划实验。 + +#### 端点 + +```json +DELETE _plugins/_search_relevance/experiments/schedule/<experiment_id> +``` + +### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `experiment_id` | 字符串 | 要删除的计划实验的 ID。 | + +#### 示例请求 + +```json +DELETE _plugins/_search_relevance/experiments/schedule/6282afa6-fa14-49c8-a627-ac1d5204d357 +``` + +#### 示例响应 + +```json +{ + "_index": ".search-relevance-scheduled-experiment-jobs", + "_id": "6282afa6-fa14-49c8-a627-ac1d5204d357", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 17, + "_primary_term": 1 +} +``` diff --git a/i18n/zh/search-plugins/search-relevance/relevance-agent.md b/i18n/zh/search-plugins/search-relevance/relevance-agent.md new file mode 100644 index 00000000..f041951d --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/relevance-agent.md @@ -0,0 +1,58 @@ +--- +title: 相关性代理 +--- + +# 相关性代理 +<Badge type="tip" text="3.6 版本引入" /> + +::: danger WARNING +这是一个实验性功能,不建议在生产环境中使用。有关功能进展的更新或如果您想提供反馈,请参阅相关的 [GitHub 问题](https://github.com/opensearch-project/OpenSearch/issues/20602)。 +::: + +OpenSearch 相关性代理通过自然语言对话帮助您识别和解决搜索相关性问题。使用嵌入在 OpenSearch Dashboards 中的聊天界面,您可以交互式地诊断问题、获取分步调优指导并执行复杂的工作流程。该代理利用[搜索相关性工作台](/search-plugins/search-relevance/using-search-relevance-workbench)提供的工具。 + +该代理是 [OpenSearch Agent Server](https://github.com/opensearch-project/opensearch-agent-server) 的一部分,这是一个独立的服务,用于托管和协调 OpenSearch 工作流程的 AI 驱动代理。 + +## 工作原理 + +当您通过聊天界面提交消息时,**路由器**会分析上下文并在适当时将请求定向到相关性代理。当您在搜索相关性工作台页面或搜索工作区主页上时,路由器会激活相关性代理。 + +相关性代理作为多代理系统运行。内部协调器解释您的意图并将工作委托给专门的子代理,每个子代理负责相关性调优过程的特定部分。协调器综合来自子代理的结果并将其实时流式传输给您。 + +## 专门代理 + +相关性代理协调器协调三个专门的子代理。这些子代理根据您的问题自动调用,不需要单独配置。 + +### 用户行为分析代理 + +用户行为分析代理分析[用户行为洞察(UBI)](/search-plugins/ubi/)数据以检查参与模式和点击率。它识别高性能和低性能查询,将用户行为与搜索质量问题相关联,并提供指标驱动的洞察以告知调优决策。 + +### 假设生成代理 + +假设生成代理检查查询结构和 DSL 配置以分析搜索质量问题。它使用 UBI 数据识别模式,并为改进生成可测试的假设,例如字段权重调整或查询提升策略。在推荐配置更改之前,它使用[成对比较实验](/search-plugins/search-relevance/comparing-search-results)验证假设。 + +### 评估代理 + +评估代理设计和执行离线相关性评估实验。它在有足够事件数据时从 UBI 点击数据创建[判断列表](/search-plugins/search-relevance/judgments),或在点击数据有限时从 LLM 生成的相关性评分创建判断列表。然后代理使用您的[搜索配置](/search-plugins/search-relevance/search-configurations)运行实验,并计算搜索质量指标(NDCG、MAP 和 Precision@K)以比较其性能。 + +## 先决条件 + +在使用相关性代理之前,请确保您具有以下组件: + +- **OpenSearch Agent Server** -- 代理服务器必须正在运行并连接到您的 OpenSearch 集群。有关设置说明,请参阅 [OpenSearch Agent Server 仓库](https://github.com/opensearch-project/opensearch-agent-server)。 +- **OpenSearch Dashboards** -- 聊天界面嵌入在 OpenSearch Dashboards 中。您必须配置 OpenSearch Dashboards 以指向正在运行的代理服务器。 +- **大型语言模型(LLM)提供商** -- 为代理服务器配置 LLM。唯一支持的提供商是 [Amazon Bedrock](https://aws.amazon.com/bedrock/)。 +- **用户行为洞察(UBI)**(可选)-- 对于行为驱动的分析和从点击数据生成判断,请[启用 UBI](/search-plugins/ubi/)并配置它以在集群上收集事件。 + +## 访问代理 + +在代理服务器运行且 Dashboards 配置完成后,通过选择 OpenSearch Dashboards 标题中的聊天图标来访问相关性代理。导航到搜索相关性工作台页面或搜索工作区主页以激活代理。 + +代理实时响应,可能会在执行实验步骤之前请求您的确认。 + +## 后续步骤 + +- [设置 OpenSearch Agent Server](https://github.com/opensearch-project/opensearch-agent-server) +- [搜索相关性工作台](/search-plugins/search-relevance/using-search-relevance-workbench) +- [用户行为洞察](/search-plugins/ubi/) +- [实验](/search-plugins/search-relevance/experiments) diff --git a/i18n/zh/search-plugins/search-relevance/rerank-by-field-cross-encoder.md b/i18n/zh/search-plugins/search-relevance/rerank-by-field-cross-encoder.md new file mode 100644 index 00000000..c58b8940 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/rerank-by-field-cross-encoder.md @@ -0,0 +1,270 @@ +--- +title: 使用交叉编码器按字段重排序 +--- + +# 使用交叉编码器模型按字段重排序 +<Badge type="tip" text="2.18 版本引入" /> + +在本教程中,您将学习如何使用托管在 Amazon SageMaker 上的交叉编码器模型重排序搜索结果并提高搜索相关性。 + +要重排序文档,您需要配置一个在查询时处理搜索结果的搜索管道。管道拦截搜索结果并将它们传递给 [`ml_inference` 搜索响应处理器](/search-plugins/search-pipelines/ml-inference-search-response),该处理器调用交叉编码器模型。模型生成用于[按字段](/search-plugins/search-relevance/rerank-by-field)重排序匹配文档的分数。 + +## 先决条件:在 Amazon SageMaker 上部署模型 + +运行以下代码在 Amazon SageMaker 上部署模型。在此示例中,您将使用托管在 Amazon SageMaker 上的 [`ms-marco-MiniLM-L-6-v2`](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-6-v2) Hugging Face 交叉编码器模型。我们建议使用 GPU 以获得更好的性能: + +```python +import sagemaker +import boto3 +from sagemaker.huggingface import HuggingFaceModel + +sess = sagemaker.Session() +role = sagemaker.get_execution_role() + +hub = { + 'HF_MODEL_ID':'cross-encoder/ms-marco-MiniLM-L-6-v2', + 'HF_TASK':'text-classification' +} +huggingface_model = HuggingFaceModel( + transformers_version='4.37.0', + pytorch_version='2.1.0', + py_version='py310', + env=hub, + role=role, +) +predictor = huggingface_model.deploy( + initial_instance_count=1, # number of instances + instance_type='ml.m5.xlarge' # ec2 instance type +) +``` + +部署模型后,您可以通过进入 AWS 管理控制台中的 Amazon SageMaker 控制台并在左侧选项卡上选择 **Inference > Endpoints** 来找到模型端点。记下创建的模型的 URL;您将使用它来创建连接器。 + +## 使用重排序运行搜索 + +要使用重排序运行搜索,请按照以下步骤操作: + +1. [创建连接器](#步骤-1创建连接器)。 +1. [注册模型](#步骤-2注册模型)。 +1. [将文档摄取到索引中](#步骤-3将文档摄取到索引中)。 +1. [创建搜索管道](#步骤-4创建搜索管道)。 +1. [使用重排序进行搜索](#步骤-5使用重排序进行搜索)。 + +## 步骤 1:创建连接器 + +通过在 `actions.url` 参数中提供模型 URL 来创建到交叉编码器模型的连接器: + +```json +POST /_plugins/_ml/connectors/_create +{ + "name": "SageMaker cross-encoder model", + "description": "Test connector for SageMaker cross-encoder hosted model", + "version": 1, + "protocol": "aws_sigv4", + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "parameters": { + "region": "<REGION>", + "service_name": "sagemaker" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "<YOUR_SAGEMAKER_ENDPOINT_URL>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"inputs\": { \"text\": \"${parameters.text}\", \"text_pair\": \"${parameters.text_pair}\" }}" + } + ] +} +``` + +记下响应中包含的连接器 ID;您将在下一步中使用它。 + +## 步骤 2:注册模型 + +要注册模型,请在 `connector_id` 参数中提供连接器 ID: + +```json +POST /_plugins/_ml/models/_register +{ + "name": "Cross encoder model", + "version": "1.0.1", + "function_name": "remote", + "description": "Using a SageMaker endpoint to apply a cross encoder model", + "connector_id": "<YOUR_CONNECTOR_ID>" +} +``` + +## 步骤 3:将文档摄取到索引中 + +创建索引并摄取包含纽约市各区信息的示例文档: + +```json +POST /nyc_areas/_bulk +{ "index": { "_id": 1 } } +{ "borough": "Queens", "area_name": "Astoria", "description": "Astoria is a neighborhood in the western part of Queens, New York City, known for its diverse community and vibrant cultural scene.", "population": 93000, "facts": "Astoria is home to many artists and has a large Greek-American community. The area also boasts some of the best Mediterranean food in NYC." } +{ "index": { "_id": 2 } } +{ "borough": "Queens", "area_name": "Flushing", "description": "Flushing is a neighborhood in the northern part of Queens, famous for its Asian-American population and bustling business district.", "population": 227000, "facts": "Flushing is one of the most ethnically diverse neighborhoods in NYC, with a large Chinese and Korean population. It is also home to the USTA Billie Jean King National Tennis Center." } +{ "index": { "_id": 3 } } +{ "borough": "Brooklyn", "area_name": "Williamsburg", "description": "Williamsburg is a trendy neighborhood in Brooklyn known for its hipster culture, vibrant art scene, and excellent restaurants.", "population": 150000, "facts": "Williamsburg is a hotspot for young professionals and artists. The neighborhood has seen rapid gentrification over the past two decades." } +{ "index": { "_id": 4 } } +{ "borough": "Manhattan", "area_name": "Harlem", "description": "Harlem is a historic neighborhood in Upper Manhattan, known for its significant African-American cultural heritage.", "population": 116000, "facts": "Harlem was the birthplace of the Harlem Renaissance, a cultural movement that celebrated Black culture through art, music, and literature." } +{ "index": { "_id": 5 } } +{ "borough": "The Bronx", "area_name": "Riverdale", "description": "Riverdale is a suburban-like neighborhood in the Bronx, known for its leafy streets and affluent residential areas.", "population": 48000, "facts": "Riverdale is one of the most affluent areas in the Bronx, with beautiful parks, historic homes, and excellent schools." } +{ "index": { "_id": 6 } } +{ "borough": "Staten Island", "area_name": "St. George", "description": "St. George is the main commercial and cultural center of Staten Island, offering stunning views of Lower Manhattan.", "population": 15000, "facts": "St. George is home to the Staten Island Ferry terminal and is a gateway to Staten Island, offering stunning views of the Statue of Liberty and Ellis Island." } +``` + +## 步骤 4:创建搜索管道 + +接下来,创建用于重排序的搜索管道。在搜索管道配置中,`input_map` 和 `output_map` 定义了如何为交叉编码器模型准备输入数据以及如何解释模型的输出以进行重排序: + +- `input_map` 指定搜索文档和查询中的哪些字段应用作模型输入: + - `text` 字段映射到索引文档中的 `facts` 字段。它提供模型将分析的文档特定内容。 + - `text_pair` 字段从搜索请求中动态检索搜索查询文本(`multi_match.query`)。 + + `text`(文档 `facts`)和 `text_pair`(搜索 `query`)的组合允许交叉编码器模型比较文档与查询的相关性,考虑它们的语义关系。 + +- `output_map` 字段指定模型的输出如何映射到响应中的字段: + - 响应中的 `rank_score` 字段将存储模型的相关性分数,该分数将用于执行重排序。 + +使用 `by_field` 重排序类型时,`rank_score` 字段将包含与 `_score` 字段相同的分数。要从搜索结果中删除 `rank_score` 字段,请将 `remove_target_field` 设置为 `true`。 + +比较原始分数和重排序分数可以帮助您评估搜索相关性的改进。要将原始 BM25 分数与重排序分数进行比较,请将 `keep_previous_score` 设置为 `true`。原始分数包含在搜索结果中用于调试目的,默认存储在 `previous_score` 字段中。如果您的索引已经包含名为 `previous_score` 的文档字段,请将 `previous_score_field` 设置为不同的名称,以便重排序处理器不会覆盖现有字段。 + + +要创建搜索管道,请发送以下请求: + +```json +PUT /_search/pipeline/my_pipeline +{ + "response_processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "This processor runs ml inference during search response", + "model_id": "<model_id_from_step_3>", + "function_name": "REMOTE", + "input_map": [ + { + "text": "facts", + "text_pair":"$._request.query.multi_match.query" + } + ], + "output_map": [ + { + "rank_score": "$.score" + } + ], + "full_response_path": false, + "model_config": {}, + "ignore_missing": false, + "ignore_failure": false, + "one_to_one": true + }, + + "rerank": { + "by_field": { + "target_field": "rank_score", + "remove_target_field": true, + "keep_previous_score": true, + "previous_score_field": "original_query_score" + } + } + + } + ] +} +``` + +## 步骤 5:使用重排序进行搜索 + +使用以下请求搜索索引文档并使用交叉编码器模型重排序。该请求检索 `description` 或 `facts` 字段中包含任何指定术语的文档。然后使用这些术语来比较和重排序匹配的文档: + +```json +POST /nyc_areas/_search?search_pipeline=my_pipeline +{ + "query": { + "multi_match": { + "query": "artists art creative community", + "fields": ["description", "facts"] + } + } +} +``` + +在响应中,`original_query_score` 字段包含文档的 BM25 分数,这是如果您没有应用管道文档将获得的分数。请注意,虽然 BM25 将"Astoria"排名最高,但交叉编码器模型优先考虑"Harlem",因为它匹配了更多的搜索术语: + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 0.03418137, + "hits": [ + { + "_index": "nyc_areas", + "_id": "4", + "_score": 0.03418137, + "_source": { + "area_name": "Harlem", + "description": "Harlem is a historic neighborhood in Upper Manhattan, known for its significant African-American cultural heritage.", + "original_query_score": 1.6489418, + "borough": "Manhattan", + "facts": "Harlem was the birthplace of the Harlem Renaissance, a cultural movement that celebrated Black culture through art, music, and literature.", + "population": 116000 + } + }, + { + "_index": "nyc_areas", + "_id": "1", + "_score": 0.0090838, + "_source": { + "area_name": "Astoria", + "description": "Astoria is a neighborhood in the western part of Queens, New York City, known for its diverse community and vibrant cultural scene.", + "original_query_score": 2.519608, + "borough": "Queens", + "facts": "Astoria is home to many artists and has a large Greek-American community. The area also boasts some of the best Mediterranean food in NYC.", + "population": 93000 + } + }, + { + "_index": "nyc_areas", + "_id": "3", + "_score": 0.0032599436, + "_source": { + "area_name": "Williamsburg", + "description": "Williamsburg is a trendy neighborhood in Brooklyn known for its hipster culture, vibrant art scene, and excellent restaurants.", + "original_query_score": 1.5632852, + "borough": "Brooklyn", + "facts": "Williamsburg is a hotspot for young professionals and artists. The neighborhood has seen rapid gentrification over the past two decades.", + "population": 150000 + } + } + ] + }, + "profile": { + "shards": [] + } +} +``` + +## 后续步骤 + +- 有关使用 Cohere Rerank 按字段重排序结果的教程,请参阅[使用 Cohere Rerank 按字段重排序搜索结果](/tutorials/reranking/reranking-by-field/)。 diff --git a/i18n/zh/search-plugins/search-relevance/rerank-by-field-late-interaction.md b/i18n/zh/search-plugins/search-relevance/rerank-by-field-late-interaction.md new file mode 100644 index 00000000..624a06a5 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/rerank-by-field-late-interaction.md @@ -0,0 +1,694 @@ +--- +title: 使用后期交互模型按字段重排序 +--- + +# 使用后期交互模型按字段重排序 +<Badge type="tip" text="3.3 版本引入" /> + +在本教程中,您将学习如何使用托管在 Amazon SageMaker 上的后期交互模型(如 ColBERT 或 ColPali)来重排序搜索结果并提高多模态内容的搜索相关性。 + +后期交互模型通过为每个文档和查询生成多个向量,然后在搜索过程中执行细粒度的词元级匹配来平衡速度和准确性。这种方法对于多模态内容(如带文本的图像、技术图表和复杂文档)特别有效,因为详细的语义分析可以提高相关性。通过将快速 k-NN 检索与词元级重排序相结合,后期交互模型可以高效地处理复杂查询,并捕获文本和其他内容类型之间的细微语义关系。 + +要实现后期交互重排序,您需要配置摄取和搜索管道: +- **摄取管道**:在文档索引期间使用 [`ml_inference` 摄取处理器](/ingest-pipelines/processors/ml-inference)生成多向量和单一 k-NN 向量。 +- **搜索管道**:在搜索时处理查询,使用 [`ml_inference` 搜索请求处理器](/search-plugins/search-pipelines/ml-inference-search-request)和 [`lateInteractionScore`](/query-dsl/specialized/script-score#late-interaction-score) 函数为 k-NN 检索和后期交互重排序生成查询向量。 + +## 前提条件:在 Amazon SageMaker 上部署 ColPali 模型 + +以下是在 Amazon SageMaker 上部署 [`vidore/colpali-v1.3-hf`](https://huggingface.co/vidore/colpali-v1.3-hf) 模型的示例部署脚本。您可以使用任何后期交互模型和您选择的部署方法。由于 ColPali 需要自定义推理逻辑来处理文本查询和 Base64 编码的图像,因此本示例使用自定义推理脚本而不是标准的 Hugging Face 任务接口。在 SageMaker 笔记本中运行以下步骤。 + +### 步骤 1:创建自定义推理脚本 + +以下脚本处理查询(文本列表)和图像(Base64 列表)输入,返回多向量词元级嵌入。它在容器启动时从 Hugging Face Hub 下载模型权重: + +```python +import os +os.makedirs('colpali_code', exist_ok=True) + +inference_code = r''' +# Requires Python >= 3.12 and transformers >= 4.51.3 +import torch +import base64 +from io import BytesIO +from PIL import Image +from transformers import ColPaliForRetrieval, ColPaliProcessor + +def model_fn(model_dir): + device = "cuda" if torch.cuda.is_available() else "cpu" + model = ColPaliForRetrieval.from_pretrained( + "vidore/colpali-v1.3-hf", torch_dtype=torch.float32, + ).to(device).eval() + processor = ColPaliProcessor.from_pretrained("vidore/colpali-v1.3-hf") + return {"model": model, "processor": processor, "device": device} + +def predict_fn(data, model_dict): + model = model_dict["model"] + processor = model_dict["processor"] + device = model_dict["device"] + queries = data.get("queries", []) + images_b64 = data.get("images", []) + result = {} + if queries: + inputs = processor(text=queries, return_tensors="pt", padding=True) + inputs = {k: v.to(device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + result["query_embeddings"] = outputs.embeddings.cpu().tolist() + if images_b64: + pil_images = [] + for b64 in images_b64: + pil_images.append(Image.open(BytesIO(base64.b64decode(b64))).convert("RGB")) + inputs = processor(images=pil_images, return_tensors="pt", padding=True) + inputs = {k: v.to(device) for k, v in inputs.items()} + with torch.no_grad(): + outputs = model(**inputs) + result["image_embeddings"] = outputs.embeddings.cpu().tolist() + return result + +def input_fn(request_body, request_content_type): + import json + if request_content_type == "application/json": + return json.loads(request_body) + raise ValueError(f"Unsupported content type: {request_content_type}") + +def output_fn(prediction, accept): + import json + return json.dumps(prediction) +'''.strip() + +with open('colpali_code/inference.py', 'w') as f: + f.write(inference_code) +print('Created colpali_code/inference.py') +``` + +### 步骤 2:打包脚本并上传到 Amazon S3 + +使用以下代码打包 `inference.py` 脚本并上传到 Amazon S3: + +```python +import subprocess +import sagemaker +import boto3 + +subprocess.run(['tar', '-czf', 'model.tar.gz', '-C', 'colpali_code', 'inference.py'], check=True) +print('Created model.tar.gz') + +session = sagemaker.Session() +region = session.boto_region_name +account_id = boto3.client('sts').get_caller_identity()['Account'] +bucket = f'sagemaker-{region}-{account_id}' +s3_key = 'colpali-custom/model.tar.gz' + +s3 = boto3.client('s3', region_name=region) +s3.upload_file('model.tar.gz', bucket, s3_key) +model_data_url = f's3://{bucket}/{s3_key}' +print(f'Uploaded to {model_data_url}') +``` + +### 步骤 3:部署 SageMaker 端点 + +以下代码将模型部署到 GPU 实例(此过程大约需要 5-10 分钟): + +```python +import time +from datetime import datetime + +role = sagemaker.get_execution_role() + +# HuggingFace PyTorch Inference DLC - GPU, Python 3.12, Transformers 4.51.3 +# Replace 123456789012 with your AWS Deep Learning Containers account ID for your region. +# See https://github.com/aws/deep-learning-containers/blob/master/available_images.md +dlc_account_id = '123456789012' +image_uri = ( + f'{dlc_account_id}.dkr.ecr.{region}.amazonaws.com/' + 'huggingface-pytorch-inference:2.6.0-transformers4.51.3-gpu-py312-cu124-ubuntu22.04' +) + +sm = boto3.client('sagemaker', region_name=region) +ts = datetime.now().strftime('%Y%m%d%H%M%S') + +model_name = f'colpali-custom-{ts}' +epc_name = f'colpali-custom-epc-{ts}' +ep_name = f'colpali-custom-ep-{ts}' + +sm.create_model( + ModelName=model_name, + PrimaryContainer={ + 'Image': image_uri, + 'ModelDataUrl': model_data_url, + 'Environment': { + 'SAGEMAKER_PROGRAM': 'inference.py', + 'SAGEMAKER_SUBMIT_DIRECTORY': model_data_url, + }, + }, + ExecutionRoleArn=role, +) +print(f'Model created: {model_name}') + +sm.create_endpoint_config( + EndpointConfigName=epc_name, + ProductionVariants=[{ + 'VariantName': 'AllTraffic', + 'ModelName': model_name, + 'InstanceType': 'ml.g4dn.xlarge', + 'InitialInstanceCount': 1, + }], +) +print(f'Endpoint config created: {epc_name}') + +sm.create_endpoint(EndpointName=ep_name, EndpointConfigName=epc_name) +print(f'Creating endpoint: {ep_name} (takes 5-10 min)...') + +while True: + resp = sm.describe_endpoint(EndpointName=ep_name) + status = resp['EndpointStatus'] + print(f' Status: {status}') + if status == 'InService': + break + if status == 'Failed': + print(f' FAILED: {resp.get("FailureReason")}') + break + time.sleep(30) + +print(f'\nEndpoint ready: {ep_name}') +``` + +部署后,在 Amazon SageMaker 控制台的**推理 > 端点**下找到您的端点名称。您将在连接器配置中使用此端点 URL。 + +## 使用后期交互重排序运行搜索 + +要实现后期交互重排序,请按照以下步骤操作: + +1. [注册模型](#步骤-1注册模型)。 +1. [创建具有适当映射的索引](#步骤-2创建索引)。 +1. [创建摄取管道](#步骤-3创建摄取管道)。 +1. [摄取文档](#步骤-4摄取文档)。 +1. [创建搜索管道](#步骤-5创建搜索管道)。 +1. [使用后期交互重排序进行搜索](#步骤-6使用后期交互重排序进行搜索)。 + +## 步骤 1:注册模型 + +通过创建连接器并将其注册到 OpenSearch 来注册 ColPali 模型: + +```json +POST /_plugins/_ml/models/_register?deploy=true +{ + "name": "ColPali model", + "function_name": "remote", + "description": "ColPali model for multimodal search", + "connector": { + "name": "Amazon SageMaker connector", + "description": "Connector for ColPali in SageMaker", + "version": 1, + "protocol": "aws_sigv4", + "parameters": { + "region": "us-east-1", + "service_name": "sagemaker" + }, + "credential": { + "access_key": "<YOUR_ACCESS_KEY>", + "secret_key": "<YOUR_SECRET_KEY>", + "session_token": "<YOUR_SESSION_TOKEN>" + }, + "actions": [ + { + "action_type": "predict", + "method": "POST", + "url": "<YOUR_SAGEMAKER_ENDPOINT>", + "headers": { + "content-type": "application/json" + }, + "request_body": "{ \"queries\": ${parameters.queries:-[]}, \"images\": ${parameters.images:-[]} }" + } + ] + } +} +``` + +记下响应中的 `model_id`;您将在后续步骤中使用它。 + +## 步骤 2:创建索引 + +创建一个具有优化映射的索引,用于存储多向量和单一 k-NN 向量。`colbert_vectors` 字段存储为 `object` 类型,并设置 `enabled: false` 以获得最佳性能。`knn_vector` 字段配置为使用 `hnsw` 算法,维度数量与模型的维度数量匹配。`image` 字段将 Base64 编码的图像数据存储为 `keyword`: + +```json +PUT /multimodal_docs +{ + "settings": { + "index.knn": true, + "index.knn.algo_param.ef_search": 100 + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "description": { + "type": "text" + }, + "image": { + "type": "keyword" + }, + "colbert_vectors": { + "type": "object", + "enabled": false + }, + "knn_vector": { + "type": "knn_vector", + "dimension": 128, + "method": { + "name": "hnsw", + "engine": "lucene" + } + } + } + } +} +``` + +## 步骤 3:创建摄取管道 + +创建一个摄取管道,该管道同时生成用于后期交互的多向量和用于 k-NN 搜索的单一向量: + +```json +PUT /_ingest/pipeline/colpali_pipeline +{ + "processors": [ + { + "ml_inference": { + "tag": "ml_inference", + "description": "Generate multi-vectors and mean pooling vector for multimodal content", + "model_id": "<YOUR_MODEL_ID>", + "input_map": [ + { + "images": "$..image" + } + ], + "output_map": [ + { + "colbert_vectors": "image_embeddings[0]", + "knn_vector": "image_embeddings[0].meanPooling()" + } + ], + "ignore_missing": false, + "ignore_failure": false + } + } + ] +} +``` + +## 步骤 4:摄取文档 + +摄取包含 Base64 编码图像和描述性内容的示例文档: + +```json +PUT /multimodal_docs/_doc/1?pipeline=colpali_pipeline +{ + "title": "Data Visualization Chart", + "description": "A comprehensive bar chart showing quarterly sales performance with multiple data series and trend analysis", + "image": "iVBORw0KGgoAAAANSUhEUgAAAMwAAAAgCAYAAABepJcLAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAAzKADAAQAAAABAAAAIAAAAABBU0NJSQAAAFNjcmVlbnNob3SjVaBQAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4zMjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yMDQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4K23hIHgAAC3pJREFUeAHtXAl0jlcafhLZEJKISIg9lliGhIptLKOxDLGvpSVqKYo0nTqtGkuHU13o4BQdjK1qjS1irZ0oofa1xBZECLFLSGTuc5PvP/+S/P/304yeuq/z59ve+977Pffdv3M4JCXfzYQihYBCQBcCjrq4FJNCQCEgEVAGoxRBIWAHAspg7ABLsSoElMEoHVAI2IGAMhg7wFKsCgFlMEoHFAJ2IKAMxg6wFKtCQBmM0gGFgB0IKIOxAyzFqhBQBqN0QCFgBwLKYOwAS7EqBJTBKB1QCNiBgDIYO8BSrAoBZTBKBxQCdiDwRhhManoa7qU+sAOW34c1Lf0ZbjxMMvyepqdaFfy61mm+qJuPbiNT/PujEddEPInr6yLH9ssH4tbjO3J+btjG+F3yt/3yL7h87xpeZL54qbVpyvJSg20M+jXxJPgzpwPXj+J08gXz2+i+ahgCZ4biyfOnFs/y8sbhmydRa05bwy/qzEar0+X1Ou+nPsTdp/esriE24VcEzW6DKQfmWeXLy4fPM54j7sYxzD6yFNRDzUDSM9IllocST+Tl9AbZV+5fR/qLDMM1TxypZGkZWRZLL9w3egS+2/9fjNs9BfXmdULbZf1x6V6CySA9FwduHEXXlR/qYbWbJzbhEPpE/8PECz5/kY5eaz7CiaSzFvI6Vm6B8Jqdkd/ZzeJZXt6oX7IWbkbGyV8ZD3+bU+X1OmcdWYJJ++dYXUeAV2m0qxSKev5BVvny6iEjSPCcMLRbNgBbL8Vi+OZxCBM6SCP6fxKzgbpzOyL5yV2TaZ14VdjV3eTmd81H4S/FKsvw9+6aSAxcPwqbe86Ho4P+DO5B2kMTmb/nRYuARvgydgZO376Aaj4VpejDIuI8evYEb5draDFVeM0uFvf+iDfyep0pOtJSP3cfzGrz5WuBh0pKfSvvWRoH+61Ffic3PEh7hF1XDsA5n7PBaBwc8n55nDcnkgbj4Voop2coUcgXkXX7YcD6kdgrvHrj0iF4/PwJFp1Yg/Xnd8iw+bcy9dCzenu0rfS2lMGQ/vW+H5DwIBGJj26h2Y89DbJnh01EgFcZaYgMt9su78Nvdy6he7UwhNfojGC/agZeayeB3gGgx94uxmsGw9BdV3jFogW85NC5R5fLdWpyfAsWxZJO07RLeYxPuYLph37Elot7wHS0nn8wBtd+Fw1L1ZbPm//UGxOafizl8gZz+56rI/BTxyko7l4MGSJd3XhhJxafjBZYHJV49RJY9BHv4ubkKmXY+qNnnUM2jsbZ5HgLUYs7TgUVnF7ZGp7/ObwY0b9txbk7F6WM/dcOyyMj7voec2WqGra0n4n8TxsMQsuAxib3Ys5vw6zDS+W+/7XUWxgeEi51gkyM8C0FXlNajMH3hxbKvSGew+r0MeBnIiyHC6bZTKk1YyELnbmmW9qQ24/vYtCGf4oItFfumfEctvSTMo4lncHUuHmYFPo5JsbOFCXITrn/K7vMRGmPEuiz9hPcS8uqeTtHDYZrPhc59bCQPnBiCLZGNBLShbuXJTjXHySBRvFR3b4o51lKWH+cNKgjJdYLJfJBVZ8KGNckAjHCoJafjsGk5p8bxJcsVFye7xXjnwoFnRw6Cl5uheVmD900FrHhUQZeWycdRJq1SdRbBIvEl6bRadSifCME+VWVl1svxmLhiVXaI8MxcssEFMnvKZWG0XPbpX3SyDWGE7fO4uGzx9qlWHOq3NBn2ekBc+qlp9ahY2ALjG8aKZzETfSP+RQl3H0tNtkgxOxEzzr5jlrDgHn14A2j8X5QN2ksFGcLz1YBTVCnRA1M2DNdKuBwsfEkLWNwEQphvE/dVg7FfTMPG3N+u3i3kYgI6YuxjSOw6uwmkG911x/A1BOZmRKbTlGD8EWTSPQP7o5pcfMxdtcUbBLZiR6iItMRliqcpSe5jflgwyhMFlnQ+0FdLeawpZ+UyT3dfTUOHVZ8gEal6mB2m4nS+VUoUgYujs5Sfy+mJIA6OabRcPgULCKX4l/ID05RXWbkti5538OtkPSmd7KLxUre5bCw/WQ5QcL9GyhZ2A/uLgWwOX63rBO83Dzg5eeB40nnwMhVy6+6hfxuVVuDPxZz8feuivQvEAuOr8IZ4V2qFK1gwZ/TjVbC+9FLJD9JEd4hVUaq5sJINCopQOePdP7OZXk0/8PNOXbrDM4LZ8CowjrHHnJ1csGiDv+WQ5IeJ8PZ0QlBvlURfX6rboPRs04NkztPUzBs0zhZY4wXkU8jW3jyPfnzLuAJnwLeFnvi5JjP5F5O0ZFRNFSkuyMbDpbT1i5eHb+ISLXizIYsg8lezLSW49C6QlN5Nah2L3SJGoKU1PvCMXpkc+R+uCqcQVnPkrkzZD+Z2/abXOewpZ+acKbv7SqG4pP6A7RbhiN1lukgqaZvFYNj4rUTUwtrRI/G1IrWRWKn6SuRci0+uVakQ5UQ6F0ehVzcLYojWzLpefYmHERIiSCU9yol2an8eokvwvRr19UDMpzS6Gx5JnPZjITTDy0S4X2UrH/o7enN6Y310rxjK4SXWyAjJfFg9El6lKx3uG4+phq9VkdKJ/B9q3HIZ1RPco9eFU9bC2HKyTTNmJqVayDTWeN7xum9v0jpSezO6TGYwKIBWH9hh7G4HM+tzWGPfkaILMlekjWMtUE7Lu+Xj4Oz0xumIIwmu3ovNRhRfMoQCxFuwvvS67ItrYV+jemL3VNFEeeEowM2yOjE1t2cI8u0x7qOlNkpsBV+vrhXGnHbis10jTNm8s7vJULuMIxuNFTm97MOL5FdwXNDtsnoSF7jLomWimkyTtw6h5Hbv8XabrMMeTrbsaytzIlePF3k+S9D7BD1X/eZjOpzwr4CUyhj0ounWz5Xk/cxlmHrnM7gyM1TJmwHbxxHdXH/96IaxarIjIGRS6Z5LyFYr35StIP4lxu5ZtegrGVYJ2qUY9uL6RcLRKZJn23/WhSxnQyp0oWUq2Aq4u5SUHrl+ceiZENAE6gdKxYpJ5+vOrtZFoRsWTMMkiibXsJFGA0L6TG7stIabazeY8vyjbHm3Bbp5dg5s4cYzZjesNCkwVbwKgtuGClT5OOkMGGE/HZCD07jGCwKTWPifZKnqMNY9NJQFhxfacxiOGeRzEYJuy9s05NfD9HhRP48AQcTj2NqyzEyjeXa+dNk6MWTHpxrPC5a7/wIyMaMXmLLm3u57FSMnJuRlZ8kwipmNXv0yrHGR6fcpcrf8d7aj7FBNFP4fZDNnIbzu8g9sDZWe6ZXPzX+3I5atrLk5DpRzz2UuHM9JhFGiwQ9xIc+EvPxic1GyK6PJrifKLS2if545RlZQL1TrZ3M1x3Men3McQfWekcWTiyeSPPbfQsWoKOFVw8X33vYbWP9M7xOuKyTzGVoc+Z2DPGvKcczUrBzZo2cRTFnTDT6ciIV5PccLRXkWqaKLg8NgDQguIeIIN/IfjzTP+bn7JJpnqlZ2fpgl7DJwh6Sv0HJ2ugqarP9147Ia+M/vap3wNDNY1FpRlYk3NJzIWr4BhqzyHPzde68sl8aLR8adxx5Hd19tkhpa+rGkzUaO4ItFvfmcIndnj7LJfbyhtEfR7P9ZMubxj5q5yREbPmXTIfZZdLqFWTzm48zEmnzlPrHTxp0xvz+QgfLPWGnlt0r7SOitTn06qetxbAendl6PEZsnQh2GUkfvvUeHF7mf76kd6K1FRGFHPvj1uiZ+Ch6W3z8oVIbF5N8eaY7vu5FDQpoTU5ePmP0y8jMkGvMaR4alNauzuk5c3RHR0dRyxXM6bHJvUQRUT1FI0UrKk0evsKFPXhyP8jvU6AImCraQ4x43Pu83jfOw3UWK+htt37Yo5+23p3rYBZEI2aL+6UMxtYk6rlC4M+KQI41zJ/1ZdV7KQReFQFlMK+KoBr/RiGgDOaN2m71sq+KgDKYV0VQjX+jEPgf9X05Z4Ml7BIAAAAASUVORK5CYII=" +} + +``` + +```json +PUT /multimodal_docs/_doc/2?pipeline=colpali_pipeline +{ + "title": "Technical Architecture Diagram", + "description": "System architecture diagram showing microservices, databases, and API connections with detailed component relationships", + "image": "iVBORw0KGgoAAAANSUhEUgAAAP4AAAAaCAYAAACXQ+HFAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAA/qADAAQAAAABAAAAGgAAAABBU0NJSQAAAFNjcmVlbnNob3TZrl9HAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4yNjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KbSuS3AAADEZJREFUeAHtXAdUFVca/oEnIGADxYIFOyqKvUWNJZZoYl17PfboumssscU91lijx7JRE9t6ErP23rsiKooFG6igIIiiYAEEFGH/78K8fQ8ezDzfLHr2ze8ZZt6dW7/79ztHm8eRT9NIIw0BDQGrQsDWqlarLVZDQENAIKAJvsYIGgJWiIAm+Fa46dqSNQQ0wdd4QEPAChHQBN8KN11bsoaAJvgaD2gIWCECmuBb4aZrS9YQ0ARf4wENAStEIFcE/8XbWIp7F68avM8SXlAa/1OT0N+T+Gj99To5Ts3uVe3LHDxT01IJeGmkDgL/L3jaVevaYEbIq3DKfCWmJFFR58KqoDVg/wSKSXpFDUvUsrg/v8ir1HbLQNLZ6KhBiZoW9yd18O7De/JZ357W3tgirsj4Z9S+fHPptdl334grFJ0QQyXyFTW7rVwDc/BcFrCRBh+cRI09alPJfMWMuk7+8I6i38ZQPntno3K1f4S/eULOeZzI1iZX7IzZ08de3Y0JobDXkfSOMcnvkI/sbO1M9pMTniYbfGaFO+8doelnl5JuzfXNYmpBL0LE3atweXFv7dmEqhep/JlNm6h8wdL0TYWWVL+Ej6pzc7Czp/BRvqLPaWd/Jkss/suk19Rn71hyYWa/MeQA5bHNo+pczemsEStb4FWmgEeWZpejAulHXuvpPn9meadWAQxIk9970OWBu1UzJGrNTeoHGKSkfqBCjgXoRvRdcstbiJZ9NZ2alaovVdHfc8JTX+kzfnjO3rd/1A3S7eyySkxz6KEpVIwt/Jxm4z/jaZNgnl/azPqs53j80XmqXbQahbGlOx9xlZqXbvDJ5guvKDvP6E0uhDNx7xI+2drNGXioT08aVL0bJaUk0+TTC6nfvnEmlVVOeJoz3qeqW9Ahvxhap2QCV5/dpuVX/kUnw/youIu7AGh4zd5kZ+C6wYXYevcg+UUGULmCpahnlW9omE8v0mW4TGlpaTTvwiraGnSQ3J1cCUB392ovhoeWXXZlI42q1Y8W+f9KN6ODqWPFr2hMnQHkwe7p2/dJ1GXnCKOpTmgwjOCVGBJi34WXfuU5XKXYRA4tPGrRpIYjqLJrOVHtevQd2hi4gy48ucYu3XvqweNjs7EmNWnvgxPUskxjFvxIOhByMovg/3BqvlgfvIoNgduFBoZVNlRoluAZ8PQmTT2z2GhJGzss0q8T+Cz2/40i455RFOc1EDpJ9Evb2cKrwm9L9h05nSGHJtPrpPRcSc89YwheFWhU7f7Uifd3G/PCmcf+tLL1DFGOP0svryfwyrj6Q0RZYHQQrby6ieY3n0QLL66hIw/PUTIL5787Laca7l6ijpJ5iooK/jjqHGhKo+8I+P9xe4+Yhxye6FYJbx0OPcvrWyfCioqFPPWysYLXX8m1LMmtFTmo9YFb6VTYRbr/8pGQn/7enamme1WxMvBVPnsX2s885+7kRoNrdKdZ51dQveLVBW/pbHXk7uwm6soK/rVnd6jzjhE0mjdrKgOCASeenEcFOA7qU7Wj6GTVtT+EUMNbmNtsHCE+/vPOPkr6kEwutk6iDjb0u1p9aX37BXQo9DSNP/kTtS3bjOMpFyHYsJKIsaY1HkU2rFCmn11CBR3z0+SGI8neLo/YeNER/+nLbvSbZONkIRJYHXcMp7IFStHillOpcN6CtOf+cQGmJPi7go9SZbdyBKWFJM2UM4so4f1bVb2cGFY4Z8Iv0aQGIygi7imNOzGHMZkg1iDN/8GrMFrCDADlBFxnNPm7mI/03lI8KzBTQVBAUbwXI49MF4pO6r+KW3ma3niM2IdtQYf0dfFeygNYvO/2TmKMh68f09jjs3lfR/OeuIopeGTkPV4kvqRQzi8ZEjCztbHRF8W/TyDfx1eo+67R1KRkXVrFiik17QOVL1RG1FEyT31nCh+Q2/IuUomCYtPDXzk80a0cbyGHNvzwVFrYYrIwBDN9l9PN58EEoYdxA8mt9QIrbHgkC1tMIljudYHbBLZSqBb+JoqCY0OFIh3GHvzKgE30c8spNOjADxTIY8ELLeZcRBgAWcHfHnyIwCgQWhAadq7UhvbePyEEHwK0gr0BMO8A7y6iDjYlc3w0xKeH0KSoAEFcfW0zXYq6bmS1t3ZeIeIr1OlWuR0dDj0jBB9eQ62i6VoN7xxYK2cmKI44VgYbOiygvDpH8Xp8/aFG1WY2HSt+wxrdfxlGtYt507a7B2hm0++NvBejRmb+OPbIV6yhWpGKVJY9n3hWLL4Rl4UHYNjVw1cRtL/7WvJwMU7+qYEnlLKEVyFWnpkJsSyuW8wMBVjxSnUN66mx7+g3b8Ze1Sji9dExPjCER/R9vcGGUxTPcvPM0kBhgXfhSgQFDZLDE3XkeOvW83uoJqw0POXuXl+zN3iKfNhrMUx65rRWyAQuJGVDXz0Wyun327spiBOTXiyjoH7VOtEXJesIxdi76reC75BrevQ6Qgg+PI1dXVeTrOBf4QQQMp7e69qJjqU/0IggZGwx2brFqkuvTN4BnkROeRyFcGS22nBTJILliWbXXSkFPL0lXHtJ6E21Ox8RQPMvrhaZbGg/G7YsmPt7dvvtTCgTU33Ile1jNz+GLVm7LYP0VQ+EnM4i+AgxMgs9GqiJp34CH/Gg1r5/xNAmmyDsM0Vy8zTVRq4MR7sIQZDIU0pyvCWFJXDVYRQ33dpNTUvVMxJ6aazs1gregOvux3xcr3gN8mTDAoKXKZGkRKBcpGdDQwkjWoJDW1nB9+bMvjO7bVISUBpAuktu2wO2oNLipHe5eUeMtOHmduEySws2HB8xPdyfv9UdRMNq9hIWHtnN/Q9OGlYTzwANxzrmEnIM5x5fZvdqKlV09RTNwRALODady2EQ4keJbOi/7qxUhntu4umgsxdHjvAyMmOm1r5LTPcq+U0Wiw8lHRX/3HD5wppJXoLRi2zwkpuncR/KfgXHhIrcR12OjZWQEt5yZQ+rdP4SdOLRBdrO4VVdFtyJnKcyTaZ5Y47fSj4h0pH/oN3ixAgnERvY3f8YspVr9G2FVnQl6iYh7kQcnZKaQqfCL1IICzoIR1W9OJGHI5GzrCXhhohYnX8/TTDeVLmxLHnf2vMLsVnIyCJhhWMkuFJrrqcfVYHxYN3dOPYHwYtZ4r/e5JDwXhBXIlcB6422Sugou/lwq7pUaisSLki69M7Ig0ABKKHcxBOxKzDZff+Y2FcJI8xTrX0vlRG/buGQCh4e+ANHSiBkyIHvXs7F4A4ew7M5JDdPpX1h7eDbo5w8xAkXXOKeVTooai7hlhNvXXxynfNJibSk1TQ63HOjMARShl3RIFzpXuxDEXbYs8xBFmedX660aZZ6RhY/s9ZHbRxFrWk3l+b6/VMk8FCGrP1PX07UJ1jw7MIfgYw8/KNgJNQBaJKFs7O1ZX2dVYvB1QZJyRyDnI4oR1IvO5LaSu+RV9j3l98Imc0Gm7qKYmhY5B5AyHIikYakIi68g+XHKUTmvpqXbkh1WNs32tRNtJ3NCcuB3ul9ioJs/kDRIP8hnWSgGjR9Y486dJATmq08G2fT0rjYUjyNe0v/ZWpvEe4g94LkGy7Q2q/nUZuyTVXZd/SHTDISWFNYIePjKBDyRcice3GitV+1zvTXYzNEedfKbUUcD8WtlJTwp5K+lvivY0OwTgg81o9ThZy+vzDEUwlvwTWHcmuYwZuYE5RLdrkLU3Oe2miUUEqb7+wVBmZ0nf4iUWcoNxIv27LMGVJm+bMx5//ci+UPU+AGG8brhp0jNoImgubLCTTDNv+LZ1ix5JR3eutuOAaOBhNTEkWOwbDc1LPcek21UbMst/CEq/o8MZbcHAvqlbXhOuRwUDJPhBNPmTfycdhomMvBOPDOUvkIzzlPXsNhzX6Wm6fZHZrZICfeQmwey1+vwhABb+SVkEeAh3qu7xaTH1iZGh7uPRQIjuUyC7Op+tmVGVn87CpJ5bBeOREmgqz/pya427hMERKLuJSQ3HqV9GFJndzCE56VqUSjNHc5HJTMExYSSSVTlFNC1lT97Mrk5pldO7XKc+ItHIODJ2E44SHAQCIbjzJzviOBN6nGp/RmWXy1ANL60RCwNgTuvHhA/zi3VHysBWGHV9qCQ0p834DEdG6TJvi5jbg2nlUjEM+fML/l0KYIf71qiatuKYhmufqWDqa11xCwdgSQBMf1qck49fepZ6ONryGgIZArCPwHHEgr5h2DjhkAAAAASUVORK5CYII=" +} +``` + +```json +PUT /multimodal_docs/_doc/3?pipeline=colpali_pipeline +{ + "title": "Financial Report Summary", + "description": "Quarterly financial report with revenue charts, expense breakdowns, and profit margin analysis across different business units", + "image": "iVBORw0KGgoAAAANSUhEUgAAANAAAAAZCAYAAABAQ6AIAAAAAXNSR0IArs4c6QAAAGJlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJKGAAcAAAASAAAAUKABAAMAAAABAAEAAKACAAQAAAABAAAA0KADAAQAAAABAAAAGQAAAABBU0NJSQAAAFNjcmVlbnNob3Q2LTWaAAAB1WlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4yNTwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yMDg8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4K9xJAjQAADF9JREFUeAHtWwlYVdUW/kEGAVERxXnEOZxQe5mKQzkEipSWOJQ+U1PLtHzVs7TnVJqmllIOmRo4JOaY5ZiaOX2IWjiBYyo44KwoMqhv/Vv25RJwuV0wh+8sP+45Z09nnbXX8K91jnan487dg0GGBAwJ2CQBe5tmGZMMCRgSUBIwDMhQBEMCuZCAYUC5EJ4x1ZCAYUCGDhgSyIUEDAPKhfCMqYYEDAMydMCQQC4kYBhQLoRnTDUk4GCrCG6nJuH2nSQUdi5o6xL/yDxb+LyHezibcMHEn5ujCwo5u5uujRNDAloCDhduXUYx1yLq+s9rsYi5fEL3mY71iz+FomljdGP3H99FxNk/EN1nA1wd8+vmR+5oC5/Jd1LwTOhLpmcJrPI8QlqNMF1be7Lx5Hak3L2jhrs7uaJS4XIo4VbM2un/6LikO8m4lHgVpQp42Xzfk9fiEHluHxJSbsGnaBX4lvCBnfx70mjUtqk4df0MZr0wFg5JEkU0bTy5AyO2fokGJWvpJnX87zP9MhkQlaqaZyW4ODpnGPuoXdjCp3M+J5wasFU9ykdbJuJa0g2bHuutdSPg5eaJ0u4lsPfcAaVY7zTsBf49arTrbBSGybNu7rrQJtbWnfgNvVcPFSdRVpyEF4ZvmYTnKzRWSmZv92RlCseunETUhRglJ4eCThmhSbmCpbD0xWk5CvE1nxdzHPMoDHjYfL7doCdeqtpGQOE9fPtHOOi9/l270yMHfa/b6CT0Hk/dHYqgKq0wpdX/VNPZhHjQKJ804+HDebgUQpH8hdRzOhR0LqBOrPmZu28JFh5caRrq5VYUYe0mmq5T76YiYPHr+Lzlh5i2dz42n9yJp0vVxZu+3dGwZG017owIdnZUODZJ35Erf+Ll6v541ScIdb1qqv4/4g/hy8i5GFCvOyZEzMS++Bgwigys/5ry5PpmSw+vRfihn7E9brfyep1rtEOfOsFwsM+HnPjkGr/HH8TcqCXYcWYvCNleET561uqIkrmAMJq3rI6EMi3KPaMM6MTVWNQrfv9595w/gCmR34Fwj/cmD33rdkE+8dpanv3qdUPYgWWIPLsPPsWqYlyz91Hbq7q6zd17dxGyOwxLD69B/M1LaFbuX/iw0QCULVjSxMYC2TNGUb+yDZVs1xzfou61pdv32H1uPz6P+AZxN85L3hePNot6mOZ93WY0vAV2WkNXbl9DrWLVTEP5LNw3Tf6Le2FEk0F4umQd1XT+5kW8tmoI5gZMULy8v2kc3J0KYNWxjfBy9USv2i8rWTUUNPR161EIj/4Z+y8cxj7x/LE3zuETvyGYGDELzg5Oqr9CoTK4mZKo9PPn45uVrCiLYNGLAO8Wmg1ExUcjZE8oxjX/AON3zsBaiZxJks9/32GK6I4D3vllNOa3n5wBcVEfb8naQxv1V+sQhl9xv6bOM8XWFDGCE5IL6T/iYk2tJCTzxvxrXbGpeiDdxyO97KFLx9B5+UA0LdMQoWnGRa+raUfcHjCxH9/iA2zqMh+ES4M3jNbdwuhtbPhzGz7Y/BneEEX6qs0obI2NFAVabhpD4+Qcf+/mao1RTd9RgmFRg5QTnxyzLGadgqBz/McrJ7Bd+PpqTxi7HghdlFzzu/1LUcDRVRStqrrH3vMHEbTkDdTw9MaG4DB83HggpooxLTq0SvVreVJR3vJ9FQsDv4Srgwve2zTWxONIke2cfT+gd53OmOU/TsHEwCV9wftporIuP7wO3X8cgvolamFlp5mY1PIjJXvee/izA9FBlN3TxcO0v9zjMgI9raUB4iTnyR4FrxiknMEdMWxzovInJN80NSWm3la6Qn0jnbp+VpzAWsUXIVKIRLSJLYeCxk64dCnxilq/b91gZdT91g7DsMZv4XpSAlYf/1WtcSbhvDjUPeJse4DOoXWFJui/djjO3UwvCCWk3MTW05F4edmb6vmniZOY5T8W3h7lUaOot1pn3sEV6sgf8jlj7wI0LlPf1EbnoB1tpiocvVBAeDpGf6laG4wRaycRy/OPdFSiR3Y06blhaFvJT3X3rdtZCZUeykPCXsdqbdUfk9bjV08rj0rBR4vhVZfN1BQeNFVtKK85Z40IibkYPS6VjN5MwzM+vF/Zp/VUq/gc2XSwGn8jOUEi4UmV8C4+9BNGijHS++cVDft1IkZvC1EKQAWdIEpBT0f6IWa1Mp7+EmFI9GxBVVtj5ZFf0LVmoGrjD53Ns6Xvb6C7kxva/dAbjOTFXD0wJ2oxhosidX8qSI2nDOvODsCW2F0KOupF6NjmtZ+UQU7s457wb78oaSFBIzoy6nnWHslvtSIVxQnNQ8+f3leo4NNm7wnfvtYuIc/QQSkq97NLzfZoWf5Z5XBY3CL5SjGrfeXncPDiUVXsYERn2wnRI1IVjwqY7f8ZaLyxYpCl3Yur+etPbBWUk55ysMjRrnLLLHPRQQK5/7NxrHLeLg75sfrYryjiUlj4aqDuwR/qY3LlFHWdyYCYA23tHm4abMuJOSwsVaC4WoKeghvF6gUj0vbY3QrWVZCkk2Qe6XjNcK6JnjA+zaNyPgXQQDxpbmib3H/czumy7iW1CXZ2dmrdFIFz+RzyrjDS37ebRMQm6LJyMF4U4zCHE5GSI1Cxfb5tm+FRCNMyUnoli8pFIpQpL3tFalQqXUmJzTmfHp+5l6ZGpetlMh7dl1dHRjcqMNHLJ9u/Esf5Nnb1WI7iAvWtIZ0v0YHpc2ezvbC3v+/Y8slR9+s2rk/0Qti/6OAq1JQqYFUxaHdxChclev2VmBJkRa0r+onBTMPSmLXoJgYdKqiBsNrcqRJFwPH+7EwGlNWiedk2ZnsIHMUDR/RcrrxDqpR56UWtJXoV0lGJGjoPsHauHsecp49UjJjg9xFIQOGwJL/q6EY9xHRkX7JES1uJEZtRYYzfuwpOdK4RIJ66klrOR3IGNylvW1O00fffLWViUmXJTUqlySLqQrQyGrbTudB4dERimzXEXII5FCO8Vk5r5ukxhDr02KSKko+MlkjOylzM5eMmAzJXZO5BXlN49E9gtFnfJQyl0xw3IWXWlO6UzPuZQzMKMe9hGZ456uyA8eZDMpznHVbJsGz2F4flPRNfSjrZO4LYfNS2KdkPzqLHUeYxMWTJdcvpCBAK8v0Dy83mWDeLqaamq0nXlaJ5SmgmMQpMipht6jc/YaQjZo4TfE0czrm2EPM1JtAf/zZZ5Ypcg3CEhQHmdJQFiwabTu0EcwBzWhKzRuU0jDpfRM5R8KiiRG4qLCPazN8XqjwxTpLrMQIXSSwY/B2qLPCHxrf8yHrFh5aRNWsQftefE6iqjNwLQq7pkjeQ6njVUEc+/1LJO4kgDlw8jIHrR6j2vPw5fvWUymvcHd3Us4TuX6aKTH/3Hh2kmsiCxOANo0CHpytuWa2TyYBogdaSU760OJY2Qb80s+TBWCFiVajyjBZosaCr8k5MyARBKbJPO9HXmhfzexFbBwtG7rdmGKrMaImm8zurKJHfLNzreTyaz+U1qzxvSlI+ZOOnqDjNT0WjF7ybsUv4SGNEXQHNBWfXl0pQo9COqDenPVYc2ZDWY91By4THkU0HYUfcXoWrObu5VIlmtP0E8w+sQMPvglBpenOMlPdw5wVWmhPzR9+5garCmXInFQukmKBlPOm5j1C7WHV0FYjYKKwTdkpVcUXHmVIASK/Cma+V3TlzidfrvKKKM+Sj9rf+CmZnN968ne8DmVOymMG98JsfjF+kqhgeFGL6goNVtSu3r6LJvFdUMWOo6AFJy0edp8neHJbpMRwnwI2XpqM+17LoIVCLDpWQuOY3rQXmRisH89c9VYtY+KG+vN2gh3KshHGWyO5h/JduwjZ6c75kNBegJUaz6mOVip6bkYSR6e8SMXNiaqKpWGFp/mVRYsK5B/VJT1brp9xNgff0FljUYapK7i19OkXFSUi+pWRh6Tly6iO0upB4GZ75CyM7h2RpDZbLuS/ZfeLFfWcx5UER782vazzyF7RJJzRfk3fNlmriDvzY6RvdlOXxH8+ByAWjnLWJZZZcpzXS+HLzaQw/QbL2MyRLYdwSj9b2WVqfSkFltqTQfB3g7OJk7e2yHUfvq/OHbAdZ6MjJwTxI4yFb1AkiDFuJ7wcJq2lACwK/yHGZh2JAOXJlDFASIGjhpzE6OTfE8mAlwPdU+vOr6W3GoIlZ6Tq7Oz8UCJcdM0a7IYHHTQKZigiP2wMY/BoSeJgSMAzoYUrfuPdjL4H/AzhAzGbMOihRAAAAAElFTkSuQmCC" +} +``` + +## 步骤 5:创建搜索管道 + +创建一个搜索管道,该管道生成查询向量并执行 k-NN 检索和后期交互重排序: + +```json +PUT /_search/pipeline/colpali_search_pipeline +{ + "description": "Generate query vectors for KNN search and late interaction reranking", + "request_processors": [ + { + "ml_inference": { + "model_id": "<YOUR_MODEL_ID>", + "query_template": "{\n \"query\": {\n \"knn\": {\n \"knn_vector\": {\n \"vector\": ${query_knn_vector},\n \"k\": 100\n }\n }\n },\n \"rescore\": {\n \"query\": {\n \"rescore_query\": {\n \"script_score\": {\n \"query\": {\n \"match_all\": {}\n }, \n \"script\": {\n \"source\": \"lateInteractionScore(params.query_vector, 'colbert_vectors', params._source)\",\n \"params\": {\n \"query_vector\": ${query_colbert_vectors}\n }\n }\n }\n }\n }\n },\n \"size\": 10,\n \"_source\": {\n \"excludes\": [\"knn_vector\"]\n }\n}", + "input_map": [ + { + "queries": "$..query.term.search_text.value" + } + ], + "output_map": [ + { + "query_colbert_vectors": "query_embeddings[0]", + "query_knn_vector": "query_embeddings[0].meanPooling()" + } + ] + } + } + ] +} +``` + +以下是前面搜索管道中的 `query_template`,为清晰起见已格式化。该模板定义了如何重写原始搜索查询: + +```json +{ + "query": { + "knn": { + "knn_vector": { + "vector": ${query_knn_vector}, + "k": 100 + } + } + }, + "rescore": { + "query": { + "rescore_query": { + "script_score": { + "query": { + "match_all": {} + }, + "script": { + "source": "lateInteractionScore(params.query_vector, 'colbert_vectors', params._source)", + "params": { + "query_vector": ${query_colbert_vectors} + } + } + } + } + } + }, + "size": 10, + "_source": { + "excludes": ["knn_vector"] + } +} +``` + +注意查询模板的以下组件: + +- 模板变量: + - `${query_knn_vector}`:用于快速 k-NN 检索的均值池化向量 + - `${query_colbert_vectors}`:用于精确后期交互评分的多向量 +- 重写的查询结构: + - `knn` 查询:使用 `query_knn_vector` 快速找到前 100 个候选文档 + - `rescore_query`:使用 `query_colbert_vectors` 和 `lateInteractionScore` 函数进行精确重排序 + - `_source` 过滤:从响应中排除向量字段以减少有效载荷大小 + +## 步骤 6:使用后期交互重排序进行搜索 + +现在您可以使用 k-NN 检索和后期交互重排序搜索文档: + +```json +GET /multimodal_docs/_search?search_pipeline=colpali_search_pipeline +{ + "query": { + "term": { + "search_text": { + "value": "financial report" + } + } + } +} +``` + +当您运行此搜索请求时,OpenSearch 执行以下步骤: + +1. **查询处理**:搜索文本(`"financial data charts"`)被发送到 ColPali 模型,该模型生成查询向量。 + +1. **k-NN 检索**:均值池化查询向量(`query_knn_vector`)执行近似 k-NN 搜索以检索前 100 个候选文档。此步骤优先考虑速度。 + +1. **后期交互重排序**:多向量(`query_colbert_vectors`)与 `lateInteractionScore` 函数一起使用,根据细粒度的词元级匹配对结果进行重排序。此步骤优先考虑准确性。 + +1. **最终结果**:返回前 10 个文档,按其后期交互分数排序。 + +这种混合方法平衡了速度和准确性,使其适用于生产搜索系统。响应包含根据其与查询的语义相似性重新排序的文档,后期交互评分提供比传统向量搜索更细微的相关性: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```json +{ + "took": 2135, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 3, + "relation": "eq" + }, + "max_score": 11.68498, + "hits": [ + { + "_index": "multimodal_docs", + "_id": "3", + "_score": 11.68498, + "_source": { + "image": "...", + "description": "Quarterly financial report with revenue charts, expense breakdowns, and profit margin analysis across different business units", + "title": "Financial Report Summary" + } + }, + { + "_index": "multimodal_docs", + "_id": "1", + "_score": 9.761469, + "_source": { + "image": "...", + "description": "A comprehensive bar chart showing quarterly sales performance with multiple data series and trend analysis", + "title": "Data Visualization Chart" + } + }, + { + "_index": "multimodal_docs", + "_id": "2", + "_score": 9.619822, + "_source": { + "image": "...", + "description": "System architecture diagram showing microservices, databases, and API connections with detailed component relationships", + "title": "Technical Architecture Diagram" + } + } + ] + } +} +``` + +</details> + +## 调试和测试 + +您可以执行以下操作来调试和测试搜索。 + +### 模拟摄取管道 + +在摄取文档之前,测试摄取管道以验证其是否正确处理文档: + +```json +POST /_ingest/pipeline/colpali_pipeline/_simulate?verbose=true +{ + "docs": [ + { + "_index": "multimodal_docs", + "_id": "test_1", + "_source": { + "title": "Test Chart", + "description": "Sample chart for testing pipeline", + "image": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAoADwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAooooAKKKKACiiigAooooAKKKKACiiigD//2Q==" + } + } + ] +} +``` + +响应显示文档将如何被处理,并包括生成的 `colbert_vectors` 和 `knn_vector` 字段: + +```json +{ + "docs": [ + { + "processor_results": [ + { + "processor_type": "ml_inference", + "status": "success", + "description": "Generate multi-vectors and mean pooling vector for multimodal content", + "tag": "ml_inference", + "doc": { + "_index": "multimodal_docs", + "_id": "test_1", + "_source": { + "title": "Test Chart", + "description": "Sample chart for testing pipeline", + "image": "/9j/4AAQSkZJRgABAQAAAQABAAD/...", + "colbert_vectors": [ + [ + -0.0653999000787735, + 0.1100006103515625, + 0.2052547186613083 + ], + [ + 0.0234567890123456, + -0.0987654321098765, + 0.1357924680135792 + ] + ], + "knn_vector": [ + 0.025610961, + 0.045123789, + 0.067891234 + ] + }, + "_ingest": { + "pipeline": "colpali_pipeline", + "timestamp": "2025-10-02T23:17:01.615598095Z" + } + } + } + ] + } + ] +} +``` + +### 调试搜索管道 + +使用详细输出测试搜索管道以查看查询是如何被重写的: + +```json +GET /multimodal_docs/_search?search_pipeline=colpali_search_pipeline&verbose_pipeline=true +{ + "query": { + "term": { + "search_text": { + "value": "financial data charts" + } + } + } +} +``` + +响应提供了在 `processor_results` 部分捕获的查询转换过程的完整视图。它显示了作为输入提交的原始查询文本("financial data charts")、生成的查询向量(多向量和均值池化向量)以及使用 k-NN 搜索和后期交互重新评分的重写查询结构。每个步骤的处理时间也包括在内,提供了用于调试和性能优化的详细信息: + +```json +{ + "took": 1835, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 8.247408, + "hits": [ + { + "_index": "multimodal_docs", + "_id": "3", + "_score": 8.247408, + "_source": { + "title": "Financial Report Summary", + "description": "Quarterly financial report with revenue charts, expense breakdowns, and profit margin analysis across different business units" + } + } + ] + }, + "processor_results": [ + { + "processor_name": "ml_inference", + "duration_millis": 1200, + "status": "success", + "input_data": { + "query": { + "term": { + "search_text": { + "boost": 1, + "value": "financial data charts" + } + } + } + }, + "output_data": { + "size": 10, + "query": { + "knn": { + "knn_vector": { + "vector": [ + -0.06357764, + 0.021222984, + 0.06605018, + 0.07643713 + ], + "boost": 1, + "k": 100 + } + } + }, + "_source": { + "excludes": [ + "knn_vector" + ] + }, + "rescore": [ + { + "query": { + "rescore_query": { + "script_score": { + "query": { + "match_all": { + "boost": 1 + } + }, + "script": { + "source": "lateInteractionScore(params.query_vector, 'colbert_vectors', params._source)", + "params": { + "query_vector": [ + [ + -0.0024404169525951147, + 0.14708828926086426, + 0.15877428650856018 + ], + [ + 0.08923456789012346, + -0.03456789012345679, + 0.20123456789012345 + ] + ] + } + } + } + } + } + } + ] + } + } + ] +} +``` + +## 相关文档 + +- [后期交互评分函数](/query-dsl/specialized/script-score#late-interaction-score) diff --git a/i18n/zh/search-plugins/search-relevance/rerank-by-field.md b/i18n/zh/search-plugins/search-relevance/rerank-by-field.md new file mode 100644 index 00000000..b3245e49 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/rerank-by-field.md @@ -0,0 +1,202 @@ +--- +title: 按字段重排序 +--- + +# 按字段重排序搜索结果 +<Badge type="tip" text="2.18 版本引入" /> + +您可以使用 `by_field` 重排序类型按文档字段重排序搜索结果。如果模型已运行并为您的文档生成了数值分数,或者之前应用了搜索响应处理器并且您想根据聚合字段以不同方式重排序文档,则按字段重排序搜索结果非常有用。 + +要实现重排序,您需要配置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)。搜索管道拦截搜索结果并对其应用 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)。`rerank` 处理器评估搜索结果并根据从文档字段获取的新分数对其进行排序。 + +## 使用重排序运行搜索 + +要使用重排序运行搜索,请按照以下步骤操作: + +1. [配置搜索管道](#步骤-1配置搜索管道)。 +1. [创建用于摄取的索引](#步骤-2创建用于摄取的索引)。 +1. [将文档摄取到索引中](#步骤-3将文档摄取到索引中)。 +1. [使用重排序进行搜索](#步骤-4使用重排序进行搜索)。 + +## 步骤 1:配置搜索管道 + +配置带有 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)的搜索管道,并指定 `by_field` 重排序类型。管道按 `reviews.stars` 字段(通过字段的完整点路径指定)排序,并返回所有文档的原始查询分数及其新分数: + +```json +PUT /_search/pipeline/rerank_byfield_pipeline +{ + "response_processors": [ + { + "rerank": { + "by_field": { + "target_field": "reviews.stars", + "keep_previous_score" : true + } + } + } + ] +} +``` + +有关请求字段的更多信息,请参阅[请求字段](/search-plugins/search-pipelines/rerank-processor#request-body-fields)。 + +当 `keep_previous_score` 为 `true` 时,重排序前的分数默认存储在 `previous_score` 中。如果您的文档中已存在 `previous_score`,请使用 `previous_score_field` 选择不同的字段名称。 + +## 步骤 2:创建用于摄取的索引 + +为了使用管道中定义的 `rerank` 处理器,请创建一个 OpenSearch 索引并将上一步创建的管道添加为默认管道: + +```json +PUT /book-index +{ + "settings": { + "index.search.default_pipeline" : "rerank_byfield_pipeline" + }, + "mappings": { + "properties": { + "title": { + "type": "text" + }, + "author": { + "type": "text" + }, + "genre": { + "type": "keyword" + }, + "reviews": { + "properties": { + "stars": { + "type": "float" + } + } + }, + "description": { + "type": "text" + } + } + } +} +``` + +## 步骤 3:将文档摄取到索引中 + +要将文档摄取到上一步创建的索引中,请发送以下批量请求: + +```json +POST /_bulk +{ "index": { "_index": "book-index", "_id": "1" } } +{ "title": "The Lost City", "author": "Jane Doe", "genre": "Adventure Fiction", "reviews": { "stars": 4.2 }, "description": "An exhilarating journey through a hidden civilization in the Amazon rainforest." } +{ "index": { "_index": "book-index", "_id": "2" } } +{ "title": "Whispers of the Past", "author": "John Smith", "genre": "Historical Mystery", "reviews": { "stars": 4.7 }, "description": "A gripping tale set in Victorian England, unraveling a century-old mystery." } +{ "index": { "_index": "book-index", "_id": "3" } } +{ "title": "Starlit Dreams", "author": "Emily Clark", "genre": "Science Fiction", "reviews": { "stars": 4.5 }, "description": "In a future where dreams can be shared, one girl discovers her imaginations power." } +{ "index": { "_index": "book-index", "_id": "4" } } +{ "title": "The Enchanted Garden", "author": "Alice Green", "genre": "Fantasy", "reviews": { "stars": 4.8 }, "description": "A magical garden holds the key to a young girls destiny and friendship." } + +``` + +## 步骤 4:使用重排序进行搜索 + +作为示例,在索引上运行 `match_all` 查询: + +```json +POST /book-index/_search +{ + "query": { + "match_all": {} + } +} +``` + +响应包含根据 `reviews.stars` 字段按降序排序的文档。每个文档在 `previous_score` 字段中包含原始查询分数: + +```json +{ + "took": 33, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 4, + "relation": "eq" + }, + "max_score": 4.8, + "hits": [ + { + "_index": "book-index", + "_id": "4", + "_score": 4.8, + "_source": { + "reviews": { + "stars": 4.8 + }, + "author": "Alice Green", + "genre": "Fantasy", + "description": "A magical garden holds the key to a young girls destiny and friendship.", + "previous_score": 1, + "title": "The Enchanted Garden" + } + }, + { + "_index": "book-index", + "_id": "2", + "_score": 4.7, + "_source": { + "reviews": { + "stars": 4.7 + }, + "author": "John Smith", + "genre": "Historical Mystery", + "description": "A gripping tale set in Victorian England, unraveling a century-old mystery.", + "previous_score": 1, + "title": "Whispers of the Past" + } + }, + { + "_index": "book-index", + "_id": "3", + "_score": 4.5, + "_source": { + "reviews": { + "stars": 4.5 + }, + "author": "Emily Clark", + "genre": "Science Fiction", + "description": "In a future where dreams can be shared, one girl discovers her imaginations power.", + "previous_score": 1, + "title": "Starlit Dreams" + } + }, + { + "_index": "book-index", + "_id": "1", + "_score": 4.2, + "_source": { + "reviews": { + "stars": 4.2 + }, + "author": "Jane Doe", + "genre": "Adventure Fiction", + "description": "An exhilarating journey through a hidden civilization in the Amazon rainforest.", + "previous_score": 1, + "title": "The Lost City" + } + } + ] + }, + "profile": { + "shards": [] + } +} +``` + +## 后续步骤 + +- 了解更多关于 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)的信息。 +- 查看[使用外部托管交叉编码器模型按字段重排序](/search-plugins/search-relevance/rerank-by-field-cross-encoder)的完整示例。 +- 有关使用 Cohere Rerank 按字段重排序结果的教程,请参阅[使用 Cohere Rerank 按字段重排序搜索结果](/tutorials/reranking/reranking-by-field/)。 diff --git a/i18n/zh/search-plugins/search-relevance/rerank-cross-encoder.md b/i18n/zh/search-plugins/search-relevance/rerank-cross-encoder.md new file mode 100644 index 00000000..d929b23b --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/rerank-cross-encoder.md @@ -0,0 +1,118 @@ +--- +title: 使用交叉编码器模型重排序 +--- + +# 使用交叉编码器模型重排序搜索结果 +<Badge type="tip" text="2.12 版本引入" /> + +您可以使用交叉编码器模型重排序搜索结果以提高搜索相关性。要实现重排序,您需要配置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)。搜索管道拦截搜索结果并对其应用 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)。`rerank` 处理器评估搜索结果并根据交叉编码器模型提供的新分数对其进行排序。 + +::: info NOTE +**先决条件**<br> +在配置重排序管道之前,您必须设置交叉编码器模型。有关使用 OpenSearch 提供的模型的信息,请参阅[交叉编码器模型](/ml-commons-plugin/pretrained-models#cross-encoder-models)。有关使用自定义模型的信息,请参阅[自定义本地模型](/ml-commons-plugin/custom-local-models)。 +::: + +## 使用重排序运行搜索 + +要使用重排序运行搜索,请按照以下步骤操作: + +1. [配置搜索管道](#步骤-1配置搜索管道)。 +1. [创建用于摄取的索引](#步骤-2创建用于摄取的索引)。 +1. [将文档摄取到索引中](#步骤-3将文档摄取到索引中)。 +1. [使用重排序进行搜索](#步骤-4使用重排序进行搜索)。 + +## 步骤 1:配置搜索管道 + +接下来,配置带有 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)的搜索管道,并指定 `ml_opensearch` 重排序类型。在请求中,提供交叉编码器模型的模型 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-body-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" + } + } + } +} +``` + +或者,您可以提供包含上下文的字段的完整路径。有关更多信息,请参阅[重排序处理器示例](/search-plugins/search-pipelines/rerank-processor#example)。 + +## 后续步骤 + +- 了解更多关于 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)的信息。 +- 查看[使用外部托管交叉编码器模型按字段重排序](/search-plugins/search-relevance/rerank-by-field-cross-encoder)的完整示例。 +- 有关使用托管在 Amazon SageMaker 中的交叉编码器模型的教程,请参阅[使用 Amazon SageMaker 中的交叉编码器重排序搜索结果](/tutorials/reranking/reranking-cross-encoder/)。 +- 有关使用托管在 Amazon SageMaker 中的重排序器模型的教程,请参阅[使用 Amazon SageMaker 中的重排序器重排序搜索结果](/tutorials/reranking/reranking-sagemaker/)。 +- 有关使用托管在 Amazon Bedrock 上的重排序模型的教程,请参阅[使用 Amazon Bedrock 模型重排序搜索结果](/tutorials/reranking/reranking-bedrock/)。 +- 有关使用 Amazon Bedrock 上的 Cohere Rerank 的教程,请参阅[使用 Amazon Bedrock 上的 Cohere Rerank 重排序搜索结果](/tutorials/reranking/reranking-cohere-bedrock/)。 +- 有关使用 Cohere Rerank API 的教程,请参阅[使用 Cohere Rerank 重排序搜索结果](/tutorials/reranking/reranking-cohere/)。 diff --git a/i18n/zh/search-plugins/search-relevance/reranking-search-results.md b/i18n/zh/search-plugins/search-relevance/reranking-search-results.md index a23b83a9..f5aa2c47 100644 --- a/i18n/zh/search-plugins/search-relevance/reranking-search-results.md +++ b/i18n/zh/search-plugins/search-relevance/reranking-search-results.md @@ -1,110 +1,37 @@ --- -title: 对搜索结果进行重排序 +title: 重排序搜索结果 --- -# 对搜索结果进行重排序 -<Badge type="tip" text="Introduced 2.12" /> +# 重排序搜索结果 +<Badge type="tip" text="2.12 版本引入" /> -可以使用交叉编码器(cross-encoder)重排序器对搜索结果进行重排序(reranking),以提高搜索相关性。要实现重排序,需要配置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)(Search Pipeline)。该搜索管道会拦截搜索结果,并对其应用 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)。`rerank` 处理器会评估搜索结果,并根据交叉编码器模型提供的新评分对结果进行排序。 +您可以使用 [`rerank` 处理器](/search-plugins/search-pipelines/rerank-processor)重排序搜索结果以提高搜索相关性。要实现重排序,您需要配置一个在搜索时运行的[搜索管道](/search-plugins/search-pipelines/)。搜索管道拦截搜索结果并对其应用 `rerank` 处理器。`rerank` 处理器评估搜索结果并根据新分数对其进行排序。 -::: info 注意 -**前提条件**<br> -配置重排序管道之前,必须先设置交叉编码器模型。有关使用 OpenSearch 提供的模型的信息,请参阅[交叉编码器模型](/ml-commons-plugin/pretrained-models#cross-encoder-models)。有关使用自定义模型的信息,请参阅[自定义本地模型](/ml-commons-plugin/custom-local-models)。 +您可以通过以下方式重排序结果: + +- [使用交叉编码器模型](/search-plugins/search-relevance/rerank-cross-encoder) +- [按文档字段](/search-plugins/search-relevance/rerank-by-field) +- [使用交叉编码器按字段](/search-plugins/search-relevance/rerank-by-field-cross-encoder) +- [使用延迟交互模型按字段](/search-plugins/search-relevance/rerank-by-field-late-interaction) + +有关使用托管在 Amazon Bedrock、Amazon SageMaker 和 Cohere 上的模型重排序结果的教程,请参阅[重排序搜索结果教程](/tutorials/reranking/)。 + +## 代理搜索中的重排序 + +如果您使用代理搜索,请参阅[重排序代理搜索结果](/vector-search/ai-search/agentic-search/rerank-agentic-search-results/)以了解在代理搜索管道中重排序搜索结果的信息。 + +## 一起使用重排序和归一化处理器 + +::: info NOTE +当您将重排序处理器与[归一化处理器](/search-plugins/search-pipelines/normalization-processor)和混合查询一起使用时,重排序处理器会更改最终的文档分数。这是因为重排序处理器在搜索管道中的归一化处理器之后运行。 ::: -## 运行带重排序的搜索 +处理顺序如下: -要运行带重排序的搜索,请按以下步骤操作: +- 归一化处理器:此处理器根据配置的归一化方法对文档分数进行归一化。有关更多信息,请参阅[归一化处理器](/search-plugins/search-pipelines/normalization-processor)。 +- 重排序处理器:归一化后,重排序处理器进一步调整文档分数。此调整可能会显著影响搜索结果的最终排序。 -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/search-configurations.md b/i18n/zh/search-plugins/search-relevance/search-configurations.md new file mode 100644 index 00000000..4d0b0d93 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/search-configurations.md @@ -0,0 +1,285 @@ +--- +title: 搜索配置 +--- + +# 搜索配置 + +搜索配置定义用于运行实验的查询模式,指定应如何构造和执行查询。 + +## 创建搜索配置 + +您可以定义搜索配置来描述查询集的每个查询如何运行。每个搜索配置都有一个名称,由查询正文(OpenSearch 查询领域特定语言 [DSL] 中的查询)和目标索引组成。您可以选择为搜索配置定义搜索管道。 + +### 端点 + +```json +PUT _plugins/_search_relevance/search_configurations +``` + +### 请求正文字段 + +下表列出了可用的输入参数。 + +字段 | 数据类型 | 描述 +:--- | :--- | :--- +`name` | 字符串 | 搜索配置的名称。 +`description` | 字符串 | 搜索配置的描述。 +`query` | 对象 | 以 OpenSearch 查询 DSL 定义查询,以 JSON 字符串形式提供,内部引号需要转义(例如,`"query": "{\"query\":{\"multi_match\":{...}}}"`)。使用 `%queryText%` 占位符或 [Mustache](https://mustache.github.io/) 模板变量(如 `{{queryText}}`)在运行时替换查询集值。有关更多信息,请参阅[使用 Mustache 模板](#使用-mustache-模板)。 +`index` | 字符串 | 此搜索配置查询的目标索引。 +`searchPipeline` | 字符串 | 指定现有的搜索管道。可选。 + +### 示例请求:创建搜索配置 + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "baseline", + "query": "{\"query\":{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title\",\"category\",\"bullets\",\"description\",\"attrs.Brand\",\"attrs.Color\"]}}}", + "description": "Current production algorithm", + "index": "ecommerce" +} +``` + +### 使用 Mustache 模板 + +除了 `%queryText%` 占位符,您可以在查询中使用 [Mustache](https://mustache.github.io/) 模板变量。如果 `query` 参数包含双大括号(`{{}}`),OpenSearch 将 `query` 渲染为 Mustache 模板;否则,OpenSearch 替换 `%queryText%` 占位符。现有的 `%queryText%` 配置继续正常工作。 + +当 OpenSearch 渲染模板时,以下变量可用: + +- `{{queryText}}`:当前查询集条目中的 `queryText` 值。 +- `{{<field_name>}}`:查询集条目中的任何自定义字段,通过其字段名引用(例如,`{{category}}`)。有关更多信息,请参阅[查询集](/search-plugins/search-relevance/query-sets)。 + +OpenSearch 自动转义替换的值,因此包含引号或其他特殊字符的查询文本在 JSON 中保持有效。 + +::: info NOTE +不支持 Mustache 部分(`{{>...}}`),使用它们会导致查询被拒绝。 +::: + +例如,以下请求创建一个搜索配置,将用户查询与 `title` 字段匹配,并按每个查询集条目中的 `category` 自定义字段过滤结果: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "mustache_filter", + "query": "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"title\":\"{{queryText}}\"}}],\"filter\":[{\"term\":{\"category\":\"{{category}}\"}}]}}}", + "description": "Title match filtered by a category custom field", + "index": "ecommerce" +} +``` + +## 管理搜索配置 + +您可以使用以下 API 检索或删除配置。 + +### 检索搜索配置 + +此 API 检索搜索配置。 + +#### 端点 + +```json +GET _plugins/_search_relevance/search_configurations +GET _plugins/_search_relevance/search_configurations/{search_configuration_id} +``` + +#### 示例响应 + +```json +{ + "took": 3, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "search-relevance-search-config", + "_id": "92810080-9c5a-470f-a0ff-0eb85e7b818c", + "_score": null, + "_source": { + "id": "92810080-9c5a-470f-a0ff-0eb85e7b818c", + "name": "baseline", + "description": "Current production algorithm", + "timestamp": "2025-06-12T08:23:03.305Z", + "index": "ecommerce", + "query": """{"query":{"multi_match":{"query":"%queryText%","fields":["id","title","category","bullets","description","attrs.Brand","attrs.Color"]}}}""", + "searchPipeline": "" + }, + "sort": [ + 1749716583305 + ] + } + ] + } +} +``` + +### 路径参数 + +下表列出了可用的路径参数。 + +| 参数 | 数据类型 | 描述 | +| :--- | :--- | :--- | +| `search_configuration_id` | 字符串 | 要检索的搜索配置的 ID。为空时检索所有搜索配置。 | + +### 删除搜索配置 + +您可以使用搜索配置 ID 删除搜索配置。 + +#### 端点 + +```json +DELETE _plugins/_search_relevance/search_configurations/{search_configuration_id} +``` + +#### 示例请求 + +```json +DELETE _plugins/_search_relevance/search_configurations/bb45c4c4-48ce-461b-acbc-f154c0a17ec9 +``` + +#### 示例响应 + +```json +{ + "_index": "search-relevance-search-config", + "_id": "92810080-9c5a-470f-a0ff-0eb85e7b818c", + "_version": 2, + "result": "deleted", + "forced_refresh": true, + "_shards": { + "total": 2, + "successful": 1, + "failed": 0 + }, + "_seq_no": 9, + "_primary_term": 1 +} +``` + +### 搜索搜索配置 + +您可以使用查询 DSL 搜索可用的搜索配置。 + +#### 端点 + +```json +GET _plugins/_search_relevance/search_configurations/_search +POST _plugins/_search_relevance/search_configurations/_search +``` + +#### 示例请求:搜索所有搜索配置 + +```json +GET _plugins/_search_relevance/search_configurations/_search +{ + "query": + { + "match_all": {} + } +} +``` + +#### 示例请求:按名称搜索搜索配置 + +```json +GET _plugins/_search_relevance/search_configurations/_search +{ + "query": { + "match": { + "name": "baseline" + } + } +} +``` + +::: info NOTE +请注意,存储搜索配置的索引包含多个 `keyword` 类型的字段,需要精确匹配。 +::: + +#### 示例请求:使用多个条件搜索搜索配置 + +按特定目标索引和查询模式搜索搜索配置: + +```json +GET _plugins/_search_relevance/search_configurations/_search +{ + "query": { + "bool": { + "must": [ + { + "term": { + "index": "ecommerce" + } + }, + { + "match": { + "query": "multi_match" + } + } + ] + } + }, + "size": 10 +} +``` + +#### 示例响应 + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.2086178, + "hits": [ + { + "_index": "search-relevance-search-config", + "_id": "c86af6ed-a91e-450d-a630-aa2a3c525618", + "_score": 1.2086178, + "_source": { + "id": "c86af6ed-a91e-450d-a630-aa2a3c525618", + "name": "baseline", + "description": "Current production algorithm", + "timestamp": "2026-01-26T12:11:47.657Z", + "index": "ecommerce", + "query": """{"query":{"multi_match":{"query":"%queryText%","fields":["asin","title","category","bullet_points","description","brand","color"]}}}""", + "searchPipeline": "" + } + }, + { + "_index": "search-relevance-search-config", + "_id": "a4697191-744e-404a-b869-bbefb7e753ed", + "_score": 1.2015147, + "_source": { + "id": "a4697191-744e-404a-b869-bbefb7e753ed", + "name": "baseline with title weight", + "timestamp": "2026-01-26T12:11:48.199Z", + "index": "ecommerce", + "query": """{"query":{"multi_match":{"query":"%queryText%","fields":["asin","title^25","category","bullet_points","description","brand","color"]}}}""", + "searchPipeline": "" + } + } + ] + } +} +``` diff --git a/i18n/zh/search-plugins/search-relevance/template-query.md b/i18n/zh/search-plugins/search-relevance/template-query.md new file mode 100644 index 00000000..a3cc2bd2 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/template-query.md @@ -0,0 +1,203 @@ +--- +title: 模板查询 +--- + +# 模板查询 +<Badge type="tip" text="2.19 版本引入" /> + +模板查询允许您创建带有动态占位符的查询,这些占位符在查询执行期间由搜索请求处理器解析。当您的查询参数需要在搜索过程中生成或转换时(例如使用机器学习(ML)推理将文本转换为向量嵌入时),这特别有用。 + +以下搜索实现受益于使用模板查询: + +- 将文本输入转换为用于向量搜索的向量嵌入 +- 基于运行时计算的动态查询参数生成 +- 需要中间处理的复杂查询转换 + +占位符使用 `"${variable_name}"` 语法定义(请注意,变量必须用引号括起来)。搜索请求处理器可以在处理查询之前生成或转换数据以填充这些占位符。模板查询充当最终可执行查询的容器。 + +## 示例 + +以下示例演示如何将模板查询与 [`ml_inference` 搜索请求处理器](/search-plugins/search-pipelines/ml-inference-search-request)结合用于语义搜索。 + +### 先决条件 + +在使用 `ml_inference` 搜索请求处理器之前,您必须配置 ML 模型。有关本地模型的更多信息,请参阅[在 OpenSearch 中使用 ML 模型](/ml-commons-plugin/using-ml-models)。有关外部托管模型的更多信息,请参阅[连接到外部托管模型](/ml-commons-plugin/remote-models/)。 + +配置模型后,您可以通过发送 Predict API 请求来测试模型: + +```json +POST /_plugins/_ml/models/mBGzipQB2gmRjlv_dOoB/_predict +{ + "parameters": { + "inputText": "happy moments" + } +} +``` + +响应包含一个 `embedding` 字段,其中包含从 `inputText` 生成的向量嵌入: + +```json +{ + "inference_results": [ + { + "output": [ + { + "name": "response", + "dataAsMap": { + "embedding": [ + 0.6328125, + 0.26953125, + 0.41796875, + -0.00579833984375, + 1.859375, + 0.2734375, + 0.130859375, + -0.001007080078125, + 0.138671875, + ...], + "inputTextTokenCount": 2 + } + } + ], + "status_code": 200 + } + ] +} +``` + +### 步骤 1:创建摄取管道 + +创建一个摄取管道,在文档索引期间从文本字段生成向量嵌入。`input_map` 将文档字段映射到模型输入。在此示例中,文档中的 `text` 源字段映射到 `inputText` 字段——模型期望的输入字段。`output_map` 将模型输出映射到文档字段。在此示例中,模型的 `embedding` 输出字段映射到文档中的 `text_embedding` 目标字段: + +```json +PUT /_ingest/pipeline/knn_pipeline +{ + "description": "knn_pipeline", + "processors": [ + { + "ml_inference": { + "model_id": "Sz-wFZQBUpPSu0bsJTBG", + "input_map": [ + { + "inputText": "text" + } + ], + "output_map": [ + { + "text_embedding": "embedding" + } + ] + } + } + ] +} +``` + +### 步骤 2:索引文档 + +将以下文档索引到 `template-knn-1` 索引中: + +```json +PUT /template-knn-1/_doc/1 +{ + "text": "red shoes" +} +``` + +要查看文档,请发送 GET 请求: + +```json +GET /template-knn-1/_doc/1 +``` + +响应显示模型生成的嵌入与原始 `text` 一起存储在 `text_embedding` 字段中: + +```json +{ + "_index": "template-knn-1", + "_id": "1", + "_version": 2, + "_seq_no": 1, + "_primary_term": 1, + "found": true, + "_source": { + "text_embedding": [ + -0.69140625, + 0.8125, + 0.51953125, + -0.7421875, + 0.6875, + 0.4765625, + -0.34375, + ...], + "text": "red shoes" + } +} +``` + +### 步骤 3:使用模板查询搜索 + +使用以下模板查询搜索索引。`ml_inference` 处理器从输入文本 `sneakers` 生成向量嵌入,将 `${text_embedding}` 替换为生成的向量,并搜索与该向量最接近的文档: + +```json +GET /template-knn-1/_search?search_pipeline=my_knn_pipeline +{ + "query": { + "template": { + "knn": { + "text_embedding": { + "vector": "${text_embedding}", + "k": 2 + } + } + } + }, + "ext": { + "ml_inference": { + "text": "sneakers" + } + } +} +``` + +响应包含匹配的文档: + +```json +{ + "took": 611, + "timed_out": false, + "_shards": { + "total": 5, + "successful": 5, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.0019327316, + "hits": [ + { + "_index": "template-knn-1", + "_id": "1", + "_score": 0.0019327316, + "_source": { + "text_embedding": [ + -0.69140625, + 0.8125, + 0.51953125, + ..], + "text": "red shoes" + } + } + ] + } +} +``` + +## 相关文档 + +- [模板查询](/query-dsl/specialized/template) +- [ML 推理搜索请求处理器](/search-plugins/search-pipelines/ml-inference-search-request) diff --git a/i18n/zh/search-plugins/search-relevance/using-search-relevance-workbench.md b/i18n/zh/search-plugins/search-relevance/using-search-relevance-workbench.md new file mode 100644 index 00000000..3e6d6f40 --- /dev/null +++ b/i18n/zh/search-plugins/search-relevance/using-search-relevance-workbench.md @@ -0,0 +1,320 @@ +--- +title: 搜索相关性工作台 +--- + +# 搜索相关性工作台 +<Badge type="tip" text="3.1 版本引入" /> + +在搜索应用程序中,调优相关性是一项持续的迭代工作,旨在为最终用户提供正确的搜索结果。搜索相关性工作台中的工具帮助搜索相关性工程师和业务用户为应用程序用户创建最佳的搜索体验。它通过不隐藏内部信息来实现这一点,使工程师能够根据需要进行实验和调查细节。 + +搜索相关性工作台由一个[前端组件](https://github.com/opensearch-project/dashboards-search-relevance)组成,简化了评估搜索质量的过程。 +前端使用 [OpenSearch 搜索相关性插件](https://github.com/opensearch-project/search-relevance)作为后端来管理所提供的每个工具的资源。例如,大多数用例涉及创建和使用搜索配置、查询集和判断列表。所有这些资源都由搜索相关性插件创建、更新、删除和维护。当您对相关性改进感到满意时,可以获取实验输出并手动将更改部署到您的搜索应用程序中。 + +您可以在进行更结构化的实验之前,使用[单查询比较界面](/search-plugins/search-relevance/compare-search-results)快速分析单个查询。 + +## 关键相关性概念 + +搜索相关性工作台依赖于不同的组件来进行它提供的不同类型的实验: + +* [查询集](/search-plugins/search-relevance/query-sets):_查询集_是查询的集合。这些查询用于搜索相关性评估的实验中。 +* [搜索配置](/search-plugins/search-relevance/search-configurations):_搜索配置_描述了用于运行实验查询的模式。 +* [判断列表](/search-plugins/search-relevance/judgments):_判断_是描述给定查询中特定文档相关性的评分。多个判断被组合成判断列表。 +* [实验](/search-plugins/search-relevance/experiments):_实验_是设计用于评估算法有效性的受控测试。提供多种类型的实验。 + +## 可用的搜索结果质量实验 + +搜索相关性工作台提供三种类型的实验: + +* [搜索结果比较](/search-plugins/search-relevance/comparing-search-results):比较两个搜索配置的结果。 +* [搜索质量评估](/search-plugins/search-relevance/evaluate-search-quality):通过根据检索结果和判断列表计算搜索质量指标来评估特定搜索配置的检索质量。 +* [混合搜索优化](/search-plugins/search-relevance/optimize-hybrid-search):为您的混合搜索查询确定最佳参数集。 + +## 创建查询集 + +要比较搜索配置,请创建一组查询来运行搜索。如果您有访问符合用户行为洞察(UBI)规范的搜索行为数据,可以向 `_plugins/search_relevance/query_sets/create` 端点发送请求。 + +以下示例请求将手动定义的查询集上传到搜索相关性工作台: + +```json +PUT _plugins/_search_relevance/query_sets +{ + "name": "TVs", + "description": "TV queries", + "sampling": "manual", + "querySetQueries": [ + { + "queryText": "tv" + }, + { + "queryText": "led tv" + } + ] +} +``` + +响应包含您将用于实验的查询集的 `query_set_id`: + +```json +{ + "query_set_id": "1856093f-9245-449c-b54d-9aae7650551a", + "query_set_result": "CREATED" +} +``` + +## 创建搜索配置 + +搜索配置指定如何运行查询集的每个查询。要创建搜索配置,您可以向 `_plugins/search_relevance/search_configurations` 端点发送搜索请求。 +每个搜索配置都包含一个 `search_configuration_name` 和一个 `query_body`。 + +### 示例:创建两个搜索配置 + +对于您的第一个实验,您将探索向 `title` 字段添加权重 `10` 如何影响您的搜索配置。首先,将您当前的搜索配置上传到 OpenSearch: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "my_production_config", + "query": "{\"query\":{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title\",\"category\",\"bullets\",\"description\",\"attrs.Brand\",\"attrs.Color\"]}}}", + "index": "ecommerce" +} +``` + +响应包含搜索配置 ID: + +```json +{ + "search_configuration_id": "122fbde8-d593-4d71-96d4-cbe3b4977468", + "search_configuration_result": "CREATED" +} +``` + +接下来,创建另一个搜索配置并对 `title` 字段应用权重 `10`: + +```json +PUT _plugins/_search_relevance/search_configurations +{ + "name": "title_boost", + "query": "{\"query\":{\"multi_match\":{\"query\":\"%queryText%\",\"fields\":[\"id\",\"title^10\",\"category\",\"bullets\",\"description\",\"attrs.Brand\",\"attrs.Color\"]}}}", + "index": "ecommerce" +} +``` + +响应包含提升后的搜索配置的 ID,并指示是否创建成功: + +```json +{ + "search_configuration_id": "0d687614-df5b-4b6b-8110-9d8c6d407963", + "search_configuration_result": "CREATED" +} +``` + +## 运行搜索结果列表比较实验 + +要运行您的第一个实验,您需要一个查询集和两个搜索配置(以及相应的索引)。通过比较搜索结果,您可以衡量修改搜索配置如何影响搜索结果。要创建实验,请向 `_plugins/search_relevance/experiments` 端点发送请求: + +```json +PUT _plugins/_search_relevance/experiments +{ + "querySetId": "1856093f-9245-449c-b54d-9aae7650551a", + "searchConfigurationList": ["122fbde8-d593-4d71-96d4-cbe3b4977468", "0d687614-df5b-4b6b-8110-9d8c6d407963"], + "size": 10, + "type": "PAIRWISE_COMPARISON" +} +``` + +响应包含实验 ID: + +```json +{ + "experiment_id": "dbae9786-6ea0-413d-a500-a14ef69ef7e1", + "experiment_result": "CREATED" +} +``` + +要检索实验结果,请使用返回的 `experiment_id`: + +```json +GET _plugins/_search_relevance/experiments/dbae9786-6ea0-413d-a500-a14ef69ef7e1 +``` + +响应提供详细的实验结果: + +<details open markdown="block"> + <summary> + 响应 + </summary> + +```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": ".plugins-search-relevance-experiment", + "_id": "dbae9786-6ea0-413d-a500-a14ef69ef7e1", + "_score": 1, + "_source": { + "id": "dbae9786-6ea0-413d-a500-a14ef69ef7e1", + "timestamp": "2025-06-14T14:02:17.347Z", + "type": "PAIRWISE_COMPARISON", + "status": "COMPLETED", + "querySetId": "1856093f-9245-449c-b54d-9aae7650551a", + "searchConfigurationList": [ + "122fbde8-d593-4d71-96d4-cbe3b4977468", + "0d687614-df5b-4b6b-8110-9d8c6d407963" + ], + "judgmentList": [], + "size": 10, + "results": [ + { + "snapshots": [ + { + "searchConfigurationId": "0d687614-df5b-4b6b-8110-9d8c6d407963", + "docIds": [ + "B01M1D0KL1", + "B07YSMD3Z9", + "B07V4CY9GZ", + "B074KFP426", + "B07S8XNWWF", + "B07XBJR7GY", + "B075FDWSHT", + "B01N2Z17MS", + "B07F1T4JFB", + "B07S658ZLH" + ] + }, + { + "searchConfigurationId": "122fbde8-d593-4d71-96d4-cbe3b4977468", + "docIds": [ + "B07Q45SP9P", + "B074KFP426", + "B07JKVKZX8", + "B07THVCJK3", + "B0874XJYW8", + "B08LVPWQQP", + "B07V4CY9GZ", + "B07X3BS3DF", + "B074PDYLCZ", + "B08CD9MKLZ" + ] + } + ], + "queryText": "led tv", + "metrics": [ + { + "metric": "jaccard", + "value": 0.11 + }, + { + "metric": "rbo50", + "value": 0.03 + }, + { + "metric": "rbo90", + "value": 0.13 + }, + { + "metric": "frequencyWeighted", + "value": 0.2 + } + ] + }, + { + "snapshots": [ + { + "searchConfigurationId": "0d687614-df5b-4b6b-8110-9d8c6d407963", + "docIds": [ + "B07X3S9RTZ", + "B07WVZFKLQ", + "B00GXD4NWE", + "B07ZKCV5K5", + "B07ZKDVHFB", + "B086VKT9R8", + "B08XLM8YK1", + "B07FPP6TB5", + "B07N1TMNHB", + "B09CDHM8W7" + ] + }, + { + "searchConfigurationId": "122fbde8-d593-4d71-96d4-cbe3b4977468", + "docIds": [ + "B07Q7VGW4Q", + "B00GXD4NWE", + "B07VML1CY1", + "B07THVCJK3", + "B07RKSV7SW", + "B010EAW8UK", + "B07FPP6TB5", + "B073G9ZD33", + "B07VXRXRJX", + "B07Q45SP9P" + ] + } + ], + "queryText": "tv", + "metrics": [ + { + "metric": "jaccard", + "value": 0.11 + }, + { + "metric": "rbo50", + "value": 0.07 + }, + { + "metric": "rbo90", + "value": 0.16 + }, + { + "metric": "frequencyWeighted", + "value": 0.2 + } + ] + } + ] + } + } + ] + } +} +``` + +</details> + +## 在 OpenSearch Dashboards 中使用搜索相关性工作台 + +您可以在 OpenSearch Dashboards 中创建所有搜索相关性工作台组件并可视化实验结果。 +在此示例中,您将创建相同的实验并查看其结果。 + +在左侧导航窗格中,选择 **OpenSearch Plugins** > **Search Relevance**,然后选择 **Query Set Comparison**,如下图所示。 + +*选择查询集比较实验* + +选择您创建的查询集(`TVs`)和搜索配置(`my_production_config`、`title_boost`),然后选择 **Start Evaluation**,如下图所示。 + +*定义查询集比较实验* + +您将自动跳转到实验概览表,如下图所示。 + +*实验概览表* + +要查看结果,请选择最顶部(最近的)实验。实验视图页面显示三个元素: +1. 实验参数。 +2. 实验产生的聚合指标,如下图所示。 +*比较实验的聚合指标* +3. 每个查询的单独指标。 + +要直观评估两个结果集之间的差异,请选择一个查询事件。 diff --git a/i18n/zh/search-plugins/searching-data/collapse-search.md b/i18n/zh/search-plugins/searching-data/collapse-search.md new file mode 100644 index 00000000..be1c8294 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/collapse-search.md @@ -0,0 +1,396 @@ +--- +title: 折叠搜索结果 +--- + +# 折叠搜索结果 + +`collapse` 参数按特定字段值对搜索结果进行分组。这仅返回每个组内的顶部文档,有助于通过消除重复项来减少冗余。 + +`collapse` 参数要求被折叠的字段是 `keyword` 或 `numeric` 类型,启用了 [doc values](/mappings/mapping-parameters/doc-values/),并且每个文档中只包含单个值。如果任何匹配的文档在该字段中包含多个值,OpenSearch 会拒绝折叠搜索。 + +::: info NOTE +您不能在[滚动](/search-plugins/searching-data/paginate#scroll-search)搜索中使用 `collapse`,也不能与 [`rescore`](/query-dsl/rescore) 一起使用。OpenSearch 会拒绝这些请求。要对折叠结果进行分页,请使用 [`search_after`](#使用-search_after-折叠)。 +::: + +--- + +## 折叠搜索结果 + +要向索引填充数据,请定义索引映射和一个作为 `keyword` 索引的 `item` 字段。以下示例请求向您展示如何定义索引映射、填充索引,然后搜索它。 + +#### 定义索引映射 + +```json +PUT /bakery-items +{ + "mappings": { + "properties": { + "item": { + "type": "keyword" + }, + "category": { + "type": "keyword" + }, + "price": { + "type": "float" + }, + "baked_date": { + "type": "date" + } + } + } +} +``` + +#### 填充索引 + +```json +POST /bakery-items/_bulk +{ "index": {} } +{ "item": "Chocolate Cake", "category": "cakes", "price": 15, "baked_date": "2023-07-01T00:00:00Z" } +{ "index": {} } +{ "item": "Chocolate Cake", "category": "cakes", "price": 18, "baked_date": "2023-07-04T00:00:00Z" } +{ "index": {} } +{ "item": "Vanilla Cake", "category": "cakes", "price": 12, "baked_date": "2023-07-02T00:00:00Z" } +``` + +#### 搜索索引,返回所有结果 + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "sort": ["price"] +} +``` + +此查询返回未折叠的搜索结果,显示所有文档,包括"Chocolate Cake"的两个条目。 + +#### 搜索索引并折叠结果 + +要按 `item` 字段对搜索结果进行分组并按 `price` 排序,可以使用以下查询: + +**折叠的 `item` 字段搜索结果** + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item" + }, + "sort": ["price"] +} +``` + +**响应** + +```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": [ + { + "_index": "bakery-items", + "_id": "mISga5EB2HLDXHkv9kAr", + "_score": null, + "_source": { + "item": "Vanilla Cake", + "category": "cakes", + "price": 12, + "baked_date": "2023-07-02T00:00:00Z" + }, + "fields": { + "item": [ + "Vanilla Cake" + ] + }, + "sort": [ + 12 + ] + }, + { + "_index": "bakery-items", + "_id": "loSga5EB2HLDXHkv9kAr", + "_score": null, + "_source": { + "item": "Chocolate Cake", + "category": "cakes", + "price": 15, + "baked_date": "2023-07-01T00:00:00Z" + }, + "fields": { + "item": [ + "Chocolate Cake" + ] + }, + "sort": [ + 15 + ] + } + ] + } +} +``` + +折叠的搜索结果将只显示一个"Chocolate Cake"条目,演示了 `collapse` 参数如何减少冗余。 + +`collapse` 参数仅影响顶部搜索结果,不会改变任何聚合结果。响应中显示的命中总数反映了应用参数之前的所有匹配文档,包括重复项。但是,响应不会指示操作形成的唯一组的确切数量。 + +--- + +## 使用 search_after 折叠 + +`from` 和 `size` 参数适用于折叠的组,因此您可以使用它们在组之间进行分页。例如,将 `from` 设置为 `1`,`size` 设置为 `2`,搜索将跳过第一组并返回第二组和第三组。您还可以使用 `search_after` 参数对折叠的搜索结果进行分页。折叠字段和排序字段必须相同,且只能指定一个排序字段。 + +以下示例展示如何将 `collapse` 与 `search_after` 一起使用: + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item" + }, + "sort": [ + { + "item": "asc" + } + ], + "search_after": ["Chocolate Cake"] +} +``` + +## 展开折叠结果 + +您可以使用 `inner_hits` 属性展开每个折叠的顶部命中。有关可以在 `inner_hits` 中指定的所有选项,请参阅[内部命中](/search-plugins/searching-data/inner-hits)。 + +以下示例请求应用 `inner_hits` 来检索每种蛋糕类型的最低价格和最新商品: + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item", + "inner_hits": [ + { + "name": "cheapest_items", + "size": 1, + "sort": ["price"] + }, + { + "name": "newest_items", + "size": 1, + "sort": [{ "baked_date": "desc" }] + } + ] + }, + "sort": ["price"] +} + +``` + +### 每个折叠命中的多个内部命中 + +要为每个折叠结果获取多组内部命中,您可以为每组设置不同的条件。例如,让我们请求每个烘焙商品的三个最新商品: + +```json +GET /bakery-items/_search +{ + "query": { + "match": { + "category": "cakes" + } + }, + "collapse": { + "field": "item", + "inner_hits": [ + { + "name": "cheapest_items", + "size": 1, + "sort": ["price"] + }, + { + "name": "newest_items", + "size": 3, + "sort": [{ "baked_date": "desc" }] + } + ] + }, + "sort": ["price"] +} +``` + +此查询搜索 `cakes` 类别中的文档,并按 `item_name` 字段对搜索结果进行分组。对于每个 `item_name`,它检索前三个最低价格的商品和前三个最新商品,按 `baked_date` 降序排序。 + +您可以通过为响应中每个折叠命中对应的每个内部命中请求发送额外查询来展开组。如果组或内部命中请求太多,这可能会显著减慢过程。可以使用 `max_concurrent_group_searches` 请求参数来控制此阶段允许的最大并发搜索数。默认值基于数据节点数和默认搜索线程池大小。 + +### 二级折叠 + +您还可以通过在 `inner_hits` 中指定 `collapse` 对象来折叠每个组的内部命中。这将返回两个字段每种组合的顶部文档。为了演示,向 `bakery-items` 索引添加两种饼干: + +```json +POST /bakery-items/_bulk?refresh=true +{ "index": {} } +{ "item": "Oatmeal Cookie", "category": "cookies", "price": 3, "baked_date": "2023-07-03T00:00:00Z" } +{ "index": {} } +{ "item": "Oatmeal Cookie", "category": "cookies", "price": 4, "baked_date": "2023-07-05T00:00:00Z" } +{ "index": {} } +{ "item": "Sugar Cookie", "category": "cookies", "price": 2, "baked_date": "2023-07-05T00:00:00Z" } +``` + +以下请求按 `category` 折叠结果,并在每个类别内按 `item` 折叠内部命中。结果是每个类别包含其每个商品的最便宜文档: + +```json +GET /bakery-items/_search +{ + "_source": ["item", "price"], + "sort": ["price"], + "collapse": { + "field": "category", + "inner_hits": { + "name": "cheapest_per_item", + "size": 3, + "_source": ["item", "price"], + "sort": ["price"], + "collapse": { + "field": "item" + } + } + } +} +``` + +在响应中,`cookies` 组包含每种饼干的一个文档,`cakes` 组包含每种蛋糕的一个文档。更贵的 `Oatmeal Cookie` 和 `Chocolate Cake` 文档被省略: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + ... + "_source": { + "item": "Sugar Cookie", + "price": 2 + }, + "fields": { + "category": [ + "cookies" + ] + }, + "inner_hits": { + "cheapest_per_item": { + "hits": { + ... + "hits": [ + { + ... + "_source": { + "item": "Sugar Cookie", + "price": 2 + }, + "fields": { + "item": [ + "Sugar Cookie" + ] + } + }, + { + ... + "_source": { + "item": "Oatmeal Cookie", + "price": 3 + }, + "fields": { + "item": [ + "Oatmeal Cookie" + ] + } + } + ] + } + } + } + }, + { + ... + "_source": { + "item": "Vanilla Cake", + "price": 12 + }, + "fields": { + "category": [ + "cakes" + ] + }, + "inner_hits": { + "cheapest_per_item": { + "hits": { + ... + "hits": [ + { + ... + "_source": { + "item": "Vanilla Cake", + "price": 12 + }, + "fields": { + "item": [ + "Vanilla Cake" + ] + } + }, + { + ... + "_source": { + "item": "Chocolate Cake", + "price": 15 + }, + "fields": { + "item": [ + "Chocolate Cake" + ] + } + } + ] + } + } + } + } + ] + } +} +``` + +二级 `collapse` 对象不能包含 `inner_hits`,因此您不能将结果折叠超过两级。 diff --git a/i18n/zh/search-plugins/searching-data/inner-hits.md b/i18n/zh/search-plugins/searching-data/inner-hits.md new file mode 100644 index 00000000..80475cb3 --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/inner-hits.md @@ -0,0 +1,961 @@ +--- +title: 检索内部命中 +--- + +# 检索内部命中 + +在 OpenSearch 中,当您使用[嵌套对象](/mappings/supported-field-types/nested/)或[父子连接](/mappings/supported-field-types/join/)执行搜索时,默认情况下会隐藏底层命中(嵌套内部对象或子文档)。您可以通过在搜索查询中使用 `inner_hits` 参数来检索内部命中。 + +在以下场景中使用内部命中: + +- 识别哪些嵌套对象或子文档导致文档匹配,例如,包含搜索词的博客文章评论或与查询匹配的支持工单更新。 +- 在一次请求中检索文档及其匹配的嵌套对象或子文档,例如,产品及其匹配的评论或职位发布及其匹配的申请。这避免了为相关文档发送单独的查询。 + +您还可以将 `inner_hits` 与以下功能一起使用: + + - [高亮查询匹配](/search-plugins/searching-data/highlight) + - [解释](/api-reference/explain) + +## 嵌套对象的内部命中 + +嵌套对象允许您索引对象数组并在同一文档内维护它们的关系。以下示例请求使用 `inner_hits` 参数检索底层内部命中。 + +1. 创建带有嵌套对象的索引映射: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "user": { + "type": "nested", + "properties": { + "name": { "type": "text" }, + "age": { "type": "integer" } + } + } + } + } + } + ``` + +2. 索引数据: + + ```json + POST /my_index/_doc/1 + { + "group": "fans", + "user": [ + { + "name": "John Doe", + "age": 28 + }, + { + "name": "Jane Smith", + "age": 34 + } + ] + } + ``` + +3. 使用 `inner_hits` 进行查询: + + ```json + GET /my_index/_search + { + "query": { + "nested": { + "path": "user", + "query": { + "bool": { + "must": [ + { "match": { "user.name": "John" } } + ] + } + }, + "inner_hits": {} + } + } + } + ``` + +前面的查询搜索包含名称 John 的嵌套用户对象,并在响应的 `inner_hits` 部分返回匹配的嵌套文档: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 0.6931471, + "_source" : { + "group" : "fans", + "user" : [ + { + "name" : "John Doe", + "age" : 28 + }, + { + "name" : "Jane Smith", + "age" : 34 + } + ] + }, + "inner_hits" : { + "user" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_nested" : { + "field" : "user", + "offset" : 0 + }, + "_score" : 0.6931471, + "_source" : { + "name" : "John Doe", + "age" : 28 + } + } + ] + } + } + } + } + ] + } +} +``` +### 识别匹配的嵌套对象 + +嵌套对象的每个内部命中都包含一个 `_nested` 对象,用于标识匹配的嵌套对象。`field` 属性包含嵌套字段的名称,`offset` 属性包含对象在原始文档中该字段数组中的位置,从 `0` 开始。在前面的响应中,`offset` 为 `0` 表示内部命中是 `user` 数组中的第一个对象。由于内部命中按分数或您指定的排序顺序排序,内部命中的顺序通常与文档中对象的顺序不同,因此使用 `offset` 来识别原始对象。 + +默认情况下,每个内部命中的 `_source` 仅包含匹配的嵌套对象,而不是整个源文档。您可以使用[源过滤](/search-plugins/searching-data/retrieve-specific-fields#using-source-filtering)更改返回的字段,禁用内部命中的 `_source`,或通过在 `inner_hits` 中指定 `stored_fields` 来返回嵌套对象的[存储字段](/mappings/mapping-parameters/store/)。 + +### 不带源检索嵌套内部命中 + +嵌套对象不会单独存储:它们的源是父文档源的一部分。要返回嵌套内部命中的 `_source`,OpenSearch 会解析父文档的源并提取匹配的对象。对每个内部命中执行此操作会增加搜索时间,特别是如果您增加搜索或 `inner_hits` 的 `size`。为了避免此成本,请禁用内部命中的 `_source`,改为从 doc values 检索字段值。 + +以下示例使用包含嵌套 `comments` 的 `articles` 索引。创建索引并添加文档: + +```json +PUT /articles +{ + "mappings": { + "properties": { + "comments": { + "type": "nested", + "properties": { + "author": { "type": "keyword" }, + "text": { "type": "text" }, + "reactions": { + "type": "nested", + "properties": { + "user": { "type": "keyword" }, + "emoji": { "type": "keyword" } + } + } + } + } + } + } +} +``` + +```json +PUT /articles/_doc/1?refresh=true +{ + "title": "Choosing a backpacking tent", + "comments": [ + { + "author": "ana", + "text": "Great overview of tent weights", + "reactions": [] + }, + { + "author": "ben", + "text": "Which tent survives strong wind?", + "reactions": [ + { "user": "ana", "emoji": "thumbs_up" }, + { "user": "chen", "emoji": "heart" } + ] + } + ] +} +``` + +以下请求查找提到 `wind` 的评论,并仅从 doc values 返回每个匹配评论的 `author`: + +```json +GET /articles/_search +{ + "_source": false, + "query": { + "nested": { + "path": "comments", + "query": { + "match": { "comments.text": "wind" } + }, + "inner_hits": { + "_source": false, + "docvalue_fields": ["comments.author"] + } + } + } +} +``` + +内部命中包含 `fields` 对象而不是 `_source`: + +```json +"inner_hits": { + "comments": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 0.31506687, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1 + }, + "_score": 0.31506687, + "fields": { + "comments.author": [ + "ben" + ] + } + } + ] + } + } +} +``` + +### 多级嵌套对象的内部命中 + +如果嵌套对象包含其他嵌套对象,您可以通过在 `nested` 查询中指定完整的点分路径来返回任何级别的内部命中。以下请求返回用户 `ana` 的反应,这些反应嵌套在 `comments.reactions` 中: + +```json +GET /articles/_search +{ + "_source": false, + "query": { + "nested": { + "path": "comments.reactions", + "query": { + "term": { "comments.reactions.user": "ana" } + }, + "inner_hits": {} + } + } +} +``` + +内部命中以完整路径命名。每个内部命中的 `_nested` 对象包含每一级的另一个 `_nested` 对象。在此响应中,反应是第二条评论(`offset` 为 `1`)的 `reactions` 数组中的第一个对象(`offset` 为 `0`): + +```json +{ + "took": 4, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_score": 1, + "inner_hits": { + "comments.reactions": { + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1, + "hits": [ + { + "_index": "articles", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1, + "_nested": { + "field": "reactions", + "offset": 0 + } + }, + "_score": 1, + "_source": { + "emoji": "thumbs_up", + "user": "ana" + } + } + ] + } + } + } + } + ] + } +} +``` + +## 父子对象的内部命中 + +父子连接关系允许您在同一索引内创建不同类型文档之间的关系。以下示例请求使用父子对象进行带 `inner_hits` 的搜索。 + +1. 创建带有父子连接字段的索引: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "my_join_field": { + "type": "join", + "relations": { + "parent": "child" + } + }, + "text": { + "type": "text" + } + } + } + } + ``` + +2. 索引数据: + + ```json + # 索引父文档 + PUT /my_index/_doc/1 + { + "text": "This is a parent document", + "my_join_field": "parent" + } + + # 索引子文档 + PUT /my_index/_doc/2?routing=1 + { + "text": "This is a child document", + "my_join_field": { + "name": "child", + "parent": "1" + } + } + ``` + +3. 使用 `inner_hits` 进行搜索: + + ```json + GET /my_index/_search + { + "query": { + "has_child": { + "type": "child", + "query": { + "match": { + "text": "child" + } + }, + "inner_hits": {} + } + } + } + ``` + +前面的查询搜索具有匹配查询条件(在本例中,包含词 `"child"`)的子文档的父文档。它在响应的 `inner_hits` 部分返回匹配的子文档: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "text" : "This is a parent document", + "my_join_field" : "parent" + }, + "inner_hits" : { + "child" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "2", + "_score" : 0.6931471, + "_routing" : "1", + "_source" : { + "text" : "This is a child document", + "my_join_field" : { + "name" : "child", + "parent" : "1" + } + } + } + ] + } + } + } + } + ] + } +} +``` + +您还可以在 [`has_parent`](/query-dsl/joining/has-parent) 查询中指定 `inner_hits`。在这种情况下,查询返回子文档,每个子文档的内部命中包含其匹配的父文档。 + +## 同时使用父子连接和嵌套对象的内部命中 + +以下示例演示同时使用父子连接和嵌套对象与 `inner_hits`。 + +1. 创建具有以下映射的索引: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "my_join_field": { + "type": "join", + "relations": { + "parent": "child" + } + }, + "text": { + "type": "text" + }, + "comments": { + "type": "nested", + "properties": { + "user": { "type": "text" }, + "message": { "type": "text" } + } + } + } + } + } + ``` + +2. 索引数据: + + ```json + # 索引父文档 + PUT /my_index/_doc/1 + { + "text": "This is a parent document", + "my_join_field": "parent" + } + + # 索引带有嵌套评论的子文档 + PUT /my_index/_doc/2?routing=1 + { + "text": "This is a child document", + "my_join_field": { + "name": "child", + "parent": "1" + }, + "comments": [ + { + "user": "John", + "message": "This is a comment" + }, + { + "user": "Jane", + "message": "Another comment" + } + ] + } + ``` + +3. 使用 `inner_hits` 进行查询: + + ```json + GET /my_index/_search + { + "query": { + "has_child": { + "type": "child", + "query": { + "nested": { + "path": "comments", + "query": { + "bool": { + "must": [ + { "match": { "comments.user": "John" } } + ] + } + }, + "inner_hits": {} + } + }, + "inner_hits": {} + } + } + } + ``` + +前面的查询搜索具有包含 John 发表的评论的子文档的父文档。指定 `inner_hits` 确保返回匹配的子文档及其嵌套评论: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "my_index", + "_id" : "1", + "_score" : 1.0, + "_source" : { + "text" : "This is a parent document", + "my_join_field" : "parent" + }, + "inner_hits" : { + "child" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "2", + "_score" : 0.6931471, + "_routing" : "1", + "_source" : { + "text" : "This is a child document", + "my_join_field" : { + "name" : "child", + "parent" : "1" + }, + "comments" : [ + { + "user" : "John", + "message" : "This is a comment" + }, + { + "user" : "Jane", + "message" : "Another comment" + } + ] + }, + "inner_hits" : { + "comments" : { + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.6931471, + "hits" : [ + { + "_index" : "my_index", + "_id" : "2", + "_nested" : { + "field" : "comments", + "offset" : 0 + }, + "_score" : 0.6931471, + "_source" : { + "message" : "This is a comment", + "user" : "John" + } + } + ] + } + } + } + } + ] + } + } + } + } + ] + } +} +``` + +## 内部命中参数 + +下表列出了您可以在 `inner_hits` 中为嵌套对象和父子连接关系指定的参数。 + +参数 | 描述 +:--- | :--- +`from` | 开始返回内部命中的偏移量。默认为 `0`。 +`size` | 要返回的最大内部命中数。默认为 `3`。 +`sort` | 内部命中的排序顺序。默认情况下,内部命中按相关性分数排序。 +`name` | 响应中内部命中的自定义名称。对于区分单个查询中的多个内部命中很有用。默认情况下,名称是 `nested` 查询的嵌套 `path`、`has_child` 查询的子关系名称和 `has_parent` 查询的父关系名称。 + +内部命中还接受许多可以为搜索请求的命中指定的选项,包括 [`highlight`](/search-plugins/searching-data/highlight)、`explain`、[源过滤](/search-plugins/searching-data/retrieve-specific-fields#using-source-filtering)、[`script_fields`](/search-plugins/searching-data/retrieve-specific-fields#using-scripted-fields)、[`docvalue_fields`](/search-plugins/searching-data/retrieve-specific-fields#searching-with-doc-value-fields)、`version` 和 `seq_no_primary_term`。嵌套对象没有分配序列号,因此 OpenSearch 会拒绝 `nested` 查询内部命中中的 `seq_no_primary_term`。 + +### 示例:嵌套对象的内部命中参数 + +1. 创建具有以下映射的索引: + + ```json + PUT /products + { + "mappings": { + "properties": { + "product_name": { "type": "text" }, + "reviews": { + "type": "nested", + "properties": { + "user": { "type": "text" }, + "comment": { "type": "text" }, + "rating": { "type": "integer" } + } + } + } + } + } + ``` + +2. 索引数据: + + ```json + POST /products/_doc/1 + { + "product_name": "Smartphone", + "reviews": [ + { "user": "Alice", "comment": "Great phone", "rating": 5 }, + { "user": "Bob", "comment": "Not bad", "rating": 3 }, + { "user": "Charlie", "comment": "Excellent", "rating": 4 } + ] + } + ``` + + ```json + POST /products/_doc/2 + { + "product_name": "Laptop", + "reviews": [ + { "user": "Dave", "comment": "Very good", "rating": 5 }, + { "user": "Eve", "comment": "Good value", "rating": 4 } + ] + } + ``` + +3. 使用 `inner_hits` 查询并提供额外参数: + + ```json + GET /products/_search + { + "query": { + "nested": { + "path": "reviews", + "query": { + "match": { "reviews.comment": "Good" } + }, + "inner_hits": { + "from": 0, + "size": 2, + "sort": [ + { "reviews.rating": { "order": "desc" } } + ], + "name": "top_reviews" + } + } + } + } + ``` + +以下是预期结果: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 0.83740485, + "hits" : [ + { + "_index" : "products", + "_id" : "2", + "_score" : 0.83740485, + "_source" : { + "product_name" : "Laptop", + "reviews" : [ + { + "user" : "Dave", + "comment" : "Very good", + "rating" : 5 + }, + { + "user" : "Eve", + "comment" : "Good value", + "rating" : 4 + } + ] + }, + "inner_hits" : { + "top_reviews" : { + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "products", + "_id" : "2", + "_nested" : { + "field" : "reviews", + "offset" : 0 + }, + "_score" : null, + "_source" : { + "rating" : 5, + "comment" : "Very good", + "user" : "Dave" + }, + "sort" : [ + 5 + ] + }, + { + "_index" : "products", + "_id" : "2", + "_nested" : { + "field" : "reviews", + "offset" : 1 + }, + "_score" : null, + "_source" : { + "rating" : 4, + "comment" : "Good value", + "user" : "Eve" + }, + "sort" : [ + 4 + ] + } + ] + } + } + } + } + ] + } +} +``` + +### 示例:父子连接关系的内部命中参数 + +1. 创建具有以下映射的索引: + + ```json + PUT /company + { + "mappings": { + "properties": { + "my_join_field": { + "type": "join", + "relations": { + "employee": "task" + } + }, + "name": { "type": "text" }, + "description": { + "type": "text", + "fields": { + "keyword": { "type": "keyword" } + } + } + } + } + } + ``` + +2. 索引数据: + + ```json + # 索引父文档 + PUT /company/_doc/1 + { + "name": "Alice", + "my_join_field": "employee" + } + ``` + + ```json + # 索引子文档 + PUT /company/_doc/2?routing=1 + { + "description": "Complete the project", + "my_join_field": { + "name": "task", + "parent": "1" + } + } + ``` + + ```json + PUT /company/_doc/3?routing=1 + { + "description": "Prepare the report", + "my_join_field": { + "name": "task", + "parent": "1" + } + } + ``` + + ```json + PUT /company/_doc/4?routing=1 + { + "description": "Update project", + "my_join_field": { + "name": "task", + "parent": "1" + } + } + ``` + +3. 使用 `inner_hits` 参数查询: + + ```json + GET /company/_search + { + "query": { + "has_child": { + "type": "task", + "query": { + "match": { "description": "project" } + }, + "inner_hits": { + "from": 0, + "size": 10, + "sort": [ + { "description.keyword": { "order": "asc" } } + ], + "name": "related_tasks" + } + } + } + } + ``` + +以下是预期结果: + +```json +{ + "hits" : { + "total" : { + "value" : 1, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits": [ + { + "_index": "company", + "_id": "1", + "_score": 1, + "_source": { + "name": "Alice", + "my_join_field": "employee" + }, + "inner_hits": { + "related_tasks": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": null, + "hits": [ + { + "_index": "company", + "_id": "2", + "_score": null, + "_routing": "1", + "_source": { + "description": "Complete the project", + "my_join_field": { + "name": "task", + "parent": "1" + } + }, + "sort": [ + "Complete the project" + ] + }, + { + "_index": "company", + "_id": "4", + "_score": null, + "_routing": "1", + "_source": { + "description": "Update project", + "my_join_field": { + "name": "task", + "parent": "1" + } + }, + "sort": [ + "Update project" + ] + } + ] + } + } + } + } + ] + } +} +``` +## 下一步 + +- 了解[嵌套](/mappings/supported-field-types/nested/)或[连接](/mappings/supported-field-types/join/)字段上的[连接查询](/query-dsl/joining/)。 diff --git a/i18n/zh/search-plugins/searching-data/retrieve-specific-fields.md b/i18n/zh/search-plugins/searching-data/retrieve-specific-fields.md new file mode 100644 index 00000000..f549433f --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/retrieve-specific-fields.md @@ -0,0 +1,1156 @@ +--- +title: 检索特定字段 +--- + +# 检索特定字段 + +当您在 OpenSearch 中运行基本搜索时,默认情况下,索引期间使用的原始 JSON 对象也会在响应中的 `_source` 对象中为每个命中返回。这可能导致大量数据通过网络传输,增加延迟和成本。有几种方法可以将响应限制为仅需要的信息。 + +<!-- vale off --> +## 禁用 _source +<!-- vale on --> +您可以在搜索请求中将 `_source` 设置为 `false` 以从响应中排除 `_source` 字段: + +```json +GET /index1/_search +{ + "_source": false, + "query": { + "match_all": {} + } +} +``` + +由于在前面的搜索中没有选择任何字段,检索的命中将仅包含命中的 `_index`、`_id` 和 `_score`: + +```json +{ + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "index1", + "_id" : "41", + "_score" : 1.0 + }, + { + "_index" : "index1", + "_id" : "51", + "_score" : 1.0 + } + ] + } +} +``` + +也可以在索引映射中使用以下配置禁用 `_source`: + +```json +"mappings": { + "_source": { + "enabled": false + } +} +``` + +<!-- vale off --> +如果在索引映射中禁用了 `_source`,[使用 doc value 字段搜索](/search-plugins/searching-data/retrieve-specific-fields#searching-with-doc-value-fields)和[使用存储字段搜索](/search-plugins/searching-data/retrieve-specific-fields#searching-with-stored-fields)变得非常有用。 +<!-- vale on --> + +## 指定要检索的字段 + +您可以在 `fields` 参数中列出要检索的字段。也接受通配符模式: + +```json +GET /index1/_search +{ + "_source": false, + "fields": ["age", "nam*"], + "query": { + "match_all": {} + } +} +``` + +响应包含 `name` 和 `age` 字段: + +```json +{ + "hits" : { + "total" : { + "value" : 2, + "relation" : "eq" + }, + "max_score" : 1.0, + "hits" : [ + { + "_index" : "index1", + "_id" : "41", + "_score" : 1.0, + "fields" : { + "name" : [ + "John Doe" + ], + "age" : [ + 30 + ] + } + }, + { + "_index" : "index1", + "_id" : "51", + "_score" : 1.0, + "fields" : { + "name" : [ + "Jane Smith" + ], + "age" : [ + 25 + ] + } + } + ] + } +} +``` + +### 使用自定义格式提取字段 + +您还可以使用对象表示法对所选字段应用自定义格式。 + +如果您有以下文档: + +```json +{ + "_index": "my_index", + "_type": "_doc", + "_id": "1", + "_source": { + "title": "Document 1", + "date": "2023-07-04T12:34:56Z" + } +} +``` + +那么您可以使用 `fields` 参数和自定义格式进行查询: + +```json +GET /my_index/_search +{ + "query": { + "match_all": {} + }, + "fields": [ + { + "field": "date", + "format": "yyyy-MM-dd" + } + ], + "_source": false +} +``` + +此外,您可以在 `fields` 参数中使用[多字段](/query-dsl/full-text/multi-match#most-fields)和[字段别名](/mappings/supported-field-types/alias/),因为它同时查询文档 `_source` 和索引的 `_mappings`。 + +## 使用 doc value 字段搜索 + +要从索引中检索特定字段,您还可以使用 `docvalue_fields` 参数。与 `fields` 参数相比,此参数的工作方式略有不同。它从 doc values 而不是 `_source` 字段检索信息,这对于未分析的字段(如 keyword、date 和 numeric 字段)更高效。Doc values 具有针对高效排序和聚合优化的列式存储格式。它以易于读取的方式将值存储在磁盘上。当您使用 `docvalue_fields` 时,OpenSearch 直接从这种优化的存储格式读取值。它对于检索主要用于排序、聚合和脚本中使用的字段值很有用。 + +::: danger WARNING +因为 `text` 字段没有 doc values,OpenSearch 会拒绝对 `text` 字段的 `docvalue_fields` 请求,除非为该字段启用了[字段数据](/mappings/mapping-parameters/field-data/)。如果启用了字段数据,OpenSearch 会将字段的词项加载到堆内存中的字段数据缓存中以返回它们,这会增加内存使用。返回的值是分析后的词项,例如 `["great", "tent"]`,而不是原始文本。要返回 `text` 字段的原始文本,请使用 `fields` 参数或 `_source`。 +::: + +以下示例演示如何使用 `docvalue_fields` 参数。 + +1. 创建具有以下映射的索引: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "keyword" }, + "publication_date": { "type": "date" }, + "price": { "type": "double" } + } + } + } + ``` + +2. 将以下文档索引到新创建的索引中: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2021-01-01", + "price": 29.99 + } + ``` + + ```json + POST /my_index/_doc/2 + { + "title": "Advanced OpenSearch", + "author": "Jane Smith", + "publication_date": "2022-01-01", + "price": 39.99 + } + ``` + +3. 仅使用 `docvalue_fields` 检索 `author` 和 `publication_date` 字段: + + ```json + POST /my_index/_search + { + "_source": false, + "docvalue_fields": ["author", "publication_date"], + "query": { + "match_all": {} + } + } + ``` + +响应包含 `author` 和 `publication_date` 字段: + +```json +{ + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "fields": { + "author": ["John Doe"], + "publication_date": ["2021-01-01T00:00:00.000Z"] + } + }, + { + "_index": "my_index", + "_id": "2", + "_score": 1.0, + "fields": { + "author": ["Jane Smith"], + "publication_date": ["2022-01-01T00:00:00.000Z"] + } + } + ] + } +} +``` +### 使用通配符和自定义格式与 doc value 字段 + +`docvalue_fields` 参数接受通配符模式,如 `*_date`,可匹配多个字段。要格式化返回的值,请指定包含 `field` 和 `format` 的对象。对于 `date` 字段,格式是[日期格式](/mappings/supported-field-types/date/#formats)。对于数字字段,格式是 [Java `DecimalFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html) 模式,如 `#.00`。 + +例如,创建一个包含订单的索引,其中包含两个日期字段和一个数字总计: + +```json +PUT /orders-dv +{ + "mappings": { + "properties": { + "order_date": { "type": "date" }, + "ship_date": { "type": "date" }, + "total": { "type": "double" } + } + } +} +``` + +```json +PUT /orders-dv/_doc/1?refresh=true +{ + "order_date": "2026-10-01T09:30:00Z", + "ship_date": "2026-10-03", + "total": 42.5 +} +``` + +以下请求返回两个日期字段,格式化为 `yyyy-MM-dd`,以及带两位小数的总计: + +```json +GET /orders-dv/_search +{ + "_source": false, + "docvalue_fields": [ + { + "field": "*_date", + "format": "yyyy-MM-dd" + }, + { + "field": "total", + "format": "#.00" + } + ] +} +``` + +响应包含格式化的值: + +```json +{ + ... + "hits": { + ... + "hits": [ + { + "_index": "orders-dv", + "_id": "1", + "_score": 1, + "fields": { + "order_date": [ + "2026-10-01" + ], + "total": [ + "42.50" + ], + "ship_date": [ + "2026-10-03" + ] + } + } + ] + } +} +``` + +<!-- vale off --> +### 使用 docvalue_fields 检索向量字段 +<!-- vale on --> +<Badge type="tip" text="3.7 版本引入" /> + +您可以使用 `docvalue_fields` 而不是 `_source` 来检索 `knn_vector` 字段。这更快,因为 OpenSearch 直接从 `doc_values` 读取向量,而不是解析完整的 `_source` 文档。 + +从 `doc_values` 检索 `knn_vector` 字段支持所有向量数据类型(`float`、`byte` 和 `binary`)、所有压缩级别和所有 k-NN 引擎(Lucene、Faiss 和 NMSLIB)。您可以在现有索引上使用它,无需重新索引。 + +有关性能调优指南,请参阅[使用 doc values 检索向量](/vector-search/performance-tuning-search/#retrieve-vectors-using-doc-values)。 + +支持以下输出格式。 + +| 格式 | 描述 | +| :--- | :--- | +| `binary`(默认) | 将向量作为 Base64 编码的小端字节字符串返回。与 `array` 格式相比,JSON 传输的吞吐量提高约 2 倍,响应负载大小减少 30-40%。 | +| `array` | 将向量作为 JSON 数字数组返回。 | + +要使用 `docvalue_fields` 检索向量字段,请按照以下步骤操作: + +1. 创建带有 `knn_vector` 字段的索引: + + ```json + PUT /my_vector_index + { + "settings": { + "index.knn": true + }, + "mappings": { + "properties": { + "my_vector": { + "type": "knn_vector", + "dimension": 4 + }, + "title": { + "type": "text" + } + } + } + } + ``` + +2. 索引文档: + + ```json + POST /my_vector_index/_doc/1 + { + "my_vector": [1.0, 2.0, 3.0, 4.0], + "title": "Sample document" + } + ``` + +3. 使用 `docvalue_fields` 检索向量,使用默认的 `binary` 格式: + + ```json + POST /my_vector_index/_search + { + "_source": false, + "docvalue_fields": ["my_vector"], + "query": { + "knn": { + "my_vector": { + "vector": [1.0, 2.0, 3.0, 4.0], + "k": 5 + } + } + } + } + ``` + + 响应将向量作为 Base64 编码字符串返回: + + ```json + { + "hits": { + "hits": [ + { + "_id": "1", + "_score": 1.0, + "fields": { + "my_vector": ["AACAPwAAAEAAAEBAAACAQA=="] + } + } + ] + } + } + ``` + +4. 要将向量作为 JSON 数字数组检索,请指定 `array` 格式: + + ```json + POST /my_vector_index/_search + { + "_source": false, + "docvalue_fields": [{"field": "my_vector", "format": "array"}], + "query": { + "knn": { + "my_vector": { + "vector": [1.0, 2.0, 3.0, 4.0], + "k": 5 + } + } + } + } + ``` + + 响应将向量作为数字数组返回: + + ```json + { + "hits": { + "hits": [ + { + "_id": "1", + "_score": 1.0, + "fields": { + "my_vector": [[1.0, 2.0, 3.0, 4.0]] + } + } + ] + } + } + ``` + +要在使用 `doc_values` 检索向量的同时从 `_source` 检索其他文档字段,请从 `_source` 中排除向量字段: + +```json +POST /my_vector_index/_search +{ + "_source": { + "excludes": ["my_vector"] + }, + "docvalue_fields": [{"field": "my_vector", "format": "array"}], + "query": { + "knn": { + "my_vector": { + "vector": [1.0, 2.0, 3.0, 4.0], + "k": 5 + } + } + } +} +``` + +<!-- vale off --> +### 使用 docvalue_fields 与嵌套对象 +<!-- vale on --> + +在 OpenSearch 中,如果您想检索嵌套对象的 doc values,不能直接使用 `docvalue_fields` 参数,因为它会返回空数组。相反,您应该使用带有自己的 `docvalue_fields` 属性的 `inner_hits` 参数,如以下示例所示。 + +1. 定义索引映射: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "keyword" }, + "comments": { + "type": "nested", + "properties": { + "username": { "type": "keyword" }, + "content": { "type": "text" }, + "created_at": { "type": "date" } + } + } + } + } + } + ``` + +2. 索引您的数据: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "comments": [ + { + "username": "alice", + "content": "Great article!", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "username": "bob", + "content": "Very informative.", + "created_at": "2023-01-02T12:00:00Z" + } + ] + } + ``` + +3. 使用 `inner_hits` 和 `docvalue_fields` 执行搜索: + + ```json + POST /my_index/_search + { + "query": { + "nested": { + "path": "comments", + "query": { + "match_all": {} + }, + "inner_hits": { + "docvalue_fields": ["username", "created_at"] + } + } + } + } + ``` + +以下是预期响应: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "OpenSearch Basics", + "author": "John Doe", + "comments": [ + { + "username": "alice", + "content": "Great article!", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "username": "bob", + "content": "Very informative.", + "created_at": "2023-01-02T12:00:00Z" + } + ] + }, + "inner_hits": { + "comments": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 0 + }, + "docvalue_fields": { + "username": ["alice"], + "created_at": ["2023-01-01T12:00:00Z"] + } + }, + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1 + }, + "docvalue_fields": { + "username": ["bob"], + "created_at": ["2023-01-02T12:00:00Z"] + } + } + ] + } + } + } + } + ] + } +} +``` + +## 使用存储字段搜索 + +默认情况下,OpenSearch 将整个文档存储在 `_source` 字段中,并使用它在搜索结果中返回文档内容。但是,您可能还希望单独存储某些字段以更高效地检索。您可以使用 `stored_fields` 显式存储和检索与 `_source` 字段分开的特定文档字段。 + +与 `_source` 不同,`stored_fields` 必须在映射中为要单独存储的字段显式定义。如果您经常只需要检索一小部分字段并希望避免检索整个 `_source` 字段,这会很有用。以下示例演示如何使用 `stored_fields` 参数。 + +1. 创建具有以下映射的索引: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { + "type": "text", + "store": true // 单独存储 title 字段 + }, + "author": { + "type": "keyword", + "store": true // 单独存储 author 字段 + }, + "publication_date": { + "type": "date" + }, + "price": { + "type": "double" + } + } + } + } + ``` + +2. 索引您的数据: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2022-01-01", + "price": 29.99 + } + ``` + + ```json + POST my_index/_doc/2 + { + "title": "Advanced OpenSearch", + "author": "Jane Smith", + "publication_date": "2023-01-01", + "price": 39.99 + } + ``` + +3. 使用 `stored_fields` 执行搜索: + + ```json + POST /my_index/_search + { + "_source": false, + "stored_fields": ["title", "author"], + "query": { + "match_all": {} + } + } + ``` + +以下是预期响应: + +```json +{ + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "fields": { + "title": ["OpenSearch Basics"], + "author": ["John Doe"] + } + }, + { + "_index": "my_index", + "_id": "2", + "_score": 1.0, + "fields": { + "title": ["Advanced OpenSearch"], + "author": ["Jane Smith"] + } + } + ] + } +} +``` + +请注意 `stored_fields` 参数的以下行为: + +- 要返回所有存储字段,请将 `stored_fields` 设置为 `"*"`。 +- 要仅返回命中元数据(如 `_index` 和 `_id`),而不返回 `_source` 或任何存储字段,请将 `stored_fields` 设置为空数组(`[]`)。 +- 如果您请求未存储的字段,OpenSearch 会在响应中省略它,而不会出错。 +- 存储字段值作为数组返回。元数据字段(如 `_routing`)作为单个值返回。 +- 您只能请求叶字段,如 `address.city`。OpenSearch 会拒绝指定对象字段(如 `address`)的请求。 + +::: info NOTE +要完全禁用存储字段,请将 `stored_fields` 设置为 `_none_`。这样每个命中将不包含存储字段、`_source` 和 `_id`。OpenSearch 会拒绝将 `stored_fields` 设置为 `_none_` 且同时请求 `_source` 的请求。 +::: + +### 使用嵌套对象搜索存储字段 + +在 OpenSearch 中,如果您想检索嵌套对象的 `stored_fields`,不能直接使用 `stored_fields` 参数,因为不会返回数据。相反,您应该使用带有自己的 `stored_fields` 属性的 `inner_hits` 参数,如以下示例所示。 + +1. 创建具有以下映射的索引: + + ```json + PUT /my_index + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "author": { "type": "keyword" }, + "comments": { + "type": "nested", + "properties": { + "username": { "type": "keyword", "store": true }, + "content": { "type": "text", "store": true }, + "created_at": { "type": "date", "store": true } + } + } + } + } + } + ``` + +2. 索引您的数据: + + ```json + POST /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "comments": [ + { + "username": "alice", + "content": "Great article!", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "username": "bob", + "content": "Very informative.", + "created_at": "2023-01-02T12:00:00Z" + } + ] + } + ``` + +3. 使用 `inner_hits` 和 `stored_fields` 执行搜索: + + ```json + POST /my_index/_search + { + "_source": false, + "query": { + "nested": { + "path": "comments", + "query": { + "match_all": {} + }, + "inner_hits": { + "stored_fields": ["comments.username", "comments.content", "comments.created_at"] + } + } + } + } + ``` + +以下是预期响应: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "inner_hits": { + "comments": { + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 0 + }, + "fields": { + "comments.username": ["alice"], + "comments.content": ["Great article!"], + "comments.created_at": ["2023-01-01T12:00:00.000Z"] + } + }, + { + "_index": "my_index", + "_id": "1", + "_nested": { + "field": "comments", + "offset": 1 + }, + "fields": { + "comments.username": ["bob"], + "comments.content": ["Very informative."], + "comments.created_at": ["2023-01-02T12:00:00.000Z"] + } + } + ] + } + } + } + } + ] + } +} +``` + +## 使用源过滤 + +源过滤是一种控制在搜索响应中包含 `_source` 字段的哪些部分的方式。在响应中仅包含必要的字段可以帮助减少通过网络传输的数据量并提高性能。 + +您可以使用完整字段名称或简单通配符模式在搜索响应中包含或排除 `_source` 字段中的特定字段。以下示例演示如何包含特定字段。 + +1. 索引您的数据: + + ```json + PUT /my_index/_doc/1 + { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2021-01-01", + "price": 29.99 + } + ``` + +2. 使用源过滤执行搜索: + + ```json + POST /my_index/_search + { + "_source": ["title", "author"], + "query": { + "match_all": {} + } + } + ``` + +以下是预期响应: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "OpenSearch Basics", + "author": "John Doe" + } + } + ] + } +} +``` + +### 使用源过滤排除字段 + +您可以通过在搜索请求中使用 `"excludes"` 参数来选择排除字段,如以下示例所示: + +```json +POST /my_index/_search +{ + "_source": { + "excludes": ["price"] + }, + "query": { + "match_all": {} + } +} +``` + +以下是预期响应: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "my_index", + "_id": "1", + "_score": 1.0, + "_source": { + "title": "OpenSearch Basics", + "author": "John Doe", + "publication_date": "2021-01-01" + } + } + ] + } +} +``` + +### 在同一搜索中包含和排除字段 + +在某些情况下,可能需要同时使用 `include` 和 `exclude` 参数。当字段同时匹配两个列表中的模式时,OpenSearch 会省略该字段,因为 `excludes` 优先于 `includes`。以下示例演示如何在同一搜索中包含和排除字段。 + +考虑一个包含以下文档的 `products` 索引: + +```json +{ + "product_id": "123", + "name": "Smartphone", + "category": "Electronics", + "price": 699.99, + "description": "A powerful smartphone with a sleek design.", + "reviews": [ + { + "user": "john_doe", + "rating": 5, + "comment": "Great phone!", + "date": "2023-01-01" + }, + { + "user": "jane_doe", + "rating": 4, + "comment": "Good value for money.", + "date": "2023-02-15" + } + ], + "supplier": { + "name": "TechCorp", + "contact_email": "support@techcorp.com", + "address": { + "street": "123 Tech St", + "city": "Techville", + "zipcode": "12345" + } + }, + "inventory": { + "stock": 50, + "warehouse_location": "A1" + } +} +``` + +要对此索引执行搜索,同时仅在响应中包含 `name`、`price`、`reviews` 和 `supplier` 字段,并排除 `supplier` 对象中的 `contact_email` 字段和 `reviews` 对象中的 `comment` 字段,请执行以下搜索: + +```json +GET /products/_search +{ + "_source": { + "includes": ["name", "price", "reviews.*", "supplier.*"], + "excludes": ["reviews.comment", "supplier.contact_email"] + }, + "query": { + "match": { + "category": "Electronics" + } + } +} +``` + +以下是预期响应: + +```json +{ + "hits": { + "hits": [ + { + "_source": { + "name": "Smartphone", + "price": 699.99, + "reviews": [ + { + "user": "john_doe", + "rating": 5, + "date": "2023-01-01" + }, + { + "user": "jane_doe", + "rating": 4, + "date": "2023-02-15" + } + ], + "supplier": { + "name": "TechCorp", + "address": { + "street": "123 Tech St", + "city": "Techville", + "zipcode": "12345" + } + } + } + } + ] + } +} +``` + +### 源过滤限制 + +源过滤匹配原始 JSON 文档中的字段名称,因此它无法返回 OpenSearch 在索引期间派生的值。多字段、[字段别名](/mappings/supported-field-types/alias/)和由 `copy_to` 填充的字段不是源的一部分,对这些字段的请求将返回空的 `_source` 对象。 + +即使请求只要求几个字段,OpenSearch 也会加载和解析整个源文档,因此源过滤减少了网络传输但不减少磁盘读取。要直接从索引读取单个字段,请使用 [`docvalue_fields`](#使用-doc-value-字段搜索) 或 [`stored_fields`](#使用存储字段搜索)。 + +## 使用脚本字段 + +`script_fields` 参数允许您在搜索结果中包含使用脚本计算值的自定义字段。这对于根据文档数据动态计算值很有用。您还可以使用类似的方法检索 `derived fields`。有关更多信息,请参阅[检索字段](/mappings/supported-field-types/derived/#retrieving-fields)。 + +如果您有一个产品索引,其中每个产品文档都包含 `price` 和 `discount_percentage` 字段。您可以使用 `script_fields` 参数在搜索结果中包含一个自定义字段,显示每个产品的折扣价格。以下示例演示如何使用 `script_fields` 参数: + +1. 索引数据: + + ```json + PUT /products/_doc/123 + { + "product_id": "123", + "name": "Smartphone", + "price": 699.99, + "discount_percentage": 10, + "category": "Electronics", + "description": "A powerful smartphone with a sleek design." + } + ``` + +2. 使用 `script_fields` 参数在搜索结果中包含一个名为 `discounted_price` 的自定义字段。此字段将使用脚本根据 `price` 和 `discount_percentage` 字段计算: + + ```json + GET /products/_search + { + "_source": ["product_id", "name", "price", "discount_percentage"], + "query": { + "match": { + "category": "Electronics" + } + }, + "script_fields": { + "discounted_price": { + "script": { + "lang": "painless", + "source": "doc[\"price\"].value * (1 - doc[\"discount_percentage\"].value / 100)" + } + } + } + } + ``` + +您应该收到以下响应: + +```json +{ + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "products", + "_id": "123", + "_score": 1.0, + "_source": { + "product_id": "123", + "name": "Smartphone", + "price": 699.99, + "discount_percentage": 10 + }, + "fields": { + "discounted_price": [629.991] + } + } + ] + } +} +``` + +脚本可以通过两种方式访问字段值: + +- `doc['<field>'].value` 从 doc values 读取值。这很快,但仅适用于具有 doc values 的字段,如 `keyword`、数字和 `date` 字段,或启用了字段数据的 `text` 字段。 +- `params['_source']['<field>']` 从文档 `_source` 读取值。这适用于任何字段,包括 `text` 字段,但速度较慢,因为 OpenSearch 必须加载和解析每个文档的源。 + +例如,前面示例中的 `name` 字段映射为 `text`,因此 `doc['name']` 不可用。以下请求使用 `params['_source']` 计算产品名称的长度: + +```json +GET /products/_search +{ + "_source": false, + "script_fields": { + "name_length": { + "script": { + "source": "params['_source']['name'].length()" + } + } + } +} +``` + +响应包含 `Smartphone` 的长度: + +```json +"fields": { + "name_length": [10] +} +``` diff --git a/i18n/zh/search-plugins/searching-data/search-shard-routing.md b/i18n/zh/search-plugins/searching-data/search-shard-routing.md new file mode 100644 index 00000000..d907fe4a --- /dev/null +++ b/i18n/zh/search-plugins/searching-data/search-shard-routing.md @@ -0,0 +1,216 @@ +--- +title: 搜索分片路由 +--- + +# 搜索分片路由 + +为了确保冗余性并提升搜索性能,OpenSearch 将索引数据分布在多个主分片上,每个主分片有一个或多个副本分片。当执行搜索查询时,OpenSearch 将请求路由到包含主分片或副本索引分片的节点。这种技术被称为_搜索分片路由_。 + +## 自适应副本选择 + +为了改善延迟,搜索请求使用_自适应副本选择_进行路由,该方法根据以下因素选择节点: + +- 特定节点运行先前请求所花费的时间。 +- 协调节点和所选节点之间的延迟。 +- 节点搜索线程池的队列大小。 + +OpenSearch 仅对未指定 [`preference`](#搜索期间的节点和分片选择) 值的搜索使用自适应副本选择。如果配置了加权分片路由或设置了分片分配感知属性且 `cluster.search.ignore_awareness_attributes` 设置为 `false`,则也不会使用自适应副本选择。在这些情况下,OpenSearch 根据路由权重或感知属性路由搜索。有关更多信息,请参阅[集群级搜索设置](/install-and-configure/configuring-opensearch/cluster-settings#cluster-level-search-settings)。 + +如果您有权限调用 OpenSearch REST API,可以关闭搜索分片路由。有关 REST API 用户访问的更多信息,请参阅 [REST 管理 API 设置](/install-and-configure/configuring-opensearch/security-settings#rest-management-api-settings)。要禁用搜索分片路由,请按如下方式更新集群设置: + +```json +PUT /_cluster/settings +{ + "persistent": { + "cluster.routing.use_adaptive_replica_selection": false + } +} +``` + +::: info NOTE +如果关闭搜索分片路由,OpenSearch 将使用轮询路由,这可能会对搜索延迟产生负面影响。 +::: + +## 搜索期间的节点和分片选择 + +OpenSearch 使用所有节点来为搜索请求选择最佳路由。但是,在某些情况下,您可能希望手动选择搜索请求发送到的节点或分片,包括以下情况: + +- 使用缓存的先前搜索。 +- 将特定硬件专用于搜索。 +- 仅使用本地节点进行搜索。 + +将搜索路由到特定分片副本可能会造成热点,因为搜索负载不再均匀分布在集群中。仅当缓存使用等优势超过此成本时才使用 `preference` 参数。 + +您可以在搜索查询中使用 `preference` 参数来指示搜索目的地。以下是可用选项的完整列表: + +1. `_primary`:强制搜索仅在主分片上执行。 + + ```json + GET /my-index/_search?preference=_primary + ``` + +2. `_primary_first`:优先使用主分片,但如果主分片不可用则使用副本分片。 + + ```json + GET /my-index/_search?preference=_primary_first + ``` + +3. `_replica`:强制搜索仅在副本分片上执行。 + + ```json + GET /my-index/_search?preference=_replica + ``` + +4. `_replica_first`:优先使用副本分片,但如果没有副本分片可用则使用主分片。 + + ```json + GET /my-index/_search?preference=_replica_first + ``` + +5. `_only_nodes:<node-id>,<node-id>`:限制搜索仅在特定节点上执行。您可以使用任何[节点规范](/api-reference/nodes-apis/#node-filters)指定节点,例如节点 ID、节点名称、通配符模式如 `data-node-*` 或节点属性如 `zone:us-east-1a`。如果指定的节点都不包含分片副本,搜索将失败。 + + ```json + GET /my-index/_search?preference=_only_nodes:node-1,node-2 + ``` + +6. `_prefer_nodes:<node-id>,<node-id>`:优先在特定节点上执行搜索,但如果首选节点不可用则使用其他节点。 + + ```json + GET /my-index/_search?preference=_prefer_nodes:node-1,node-2 + ``` + +7. `_shards:<shard-id>,<shard-id>`:限制搜索到特定分片。您可以通过用管道字符(`|`)分隔来将 `_shards` 与另一个偏好值组合,例如 `_shards:0,1|_local`。`_shards` 值必须放在最前面。 + + ```json + GET /my-index/_search?preference=_shards:0,1 + ``` + +8. `_local`:如果可能,在本地节点上执行搜索,这可以减少延迟。 + + ```json + GET /my-index/_search?preference=_local + ``` + +9. `_only_local`:仅在分配给本地节点的分片副本上执行搜索。 + + ```json + GET /my-index/_search?preference=_only_local + ``` + +10. `_search_replica`:仅在[搜索副本](/tuning-your-cluster/performance-tuning/separate-index-and-search-workloads/)上执行搜索,这些副本托管在具有 `search` 角色的节点上。如果索引没有搜索副本,搜索将失败。 + + ```json + GET /my-index/_search?preference=_search_replica + ``` + +11. 自定义字符串:您可以使用任何自定义字符串作为偏好值。OpenSearch 将包含相同字符串的请求路由到相同的分片副本,这对于缓存很有用。字符串不能以下划线(`_`)开头。会话 ID 或用户名是不错的选择,这样每个用户的搜索都使用相同的分片副本。只有在集群状态不变的情况下,路由才保持一致:如果分片被重新定位或节点失败,相同的字符串可能会被路由到不同的分片副本。 + + ```json + GET /my-index/_search?preference=custom_string + ``` + +::: info NOTE +`_only_local` 值保证搜索仅使用本地节点上的分片副本,这使其对于特定节点的故障排除很有用。其他 `preference` 值不能完全保证哪些分片副本服务于搜索。由于分片副本可能处于不同的刷新状态,对正在更新的索引重复搜索可能会返回不同的结果,如果搜索由不同的副本服务。 +::: + +## 索引和搜索期间的自定义路由 + +您可以在索引和搜索操作期间指定路由。 + +### 索引期间的路由 + +当您索引文档时,OpenSearch 计算路由值的哈希值,并使用此哈希值确定文档将存储在哪个分片上。如果您不指定路由值,OpenSearch 使用文档 ID 来计算哈希值。 + +以下是带有路由值的索引操作示例: + +```json +POST /index1/_doc/1?routing=user1 +{ + "name": "John Doe", + "age": 20 +} +``` + +在此示例中,ID 为 `1` 的文档使用路由值 `user1` 进行索引。所有具有相同路由值的文档都将存储在同一分片上。 + +### 搜索期间的路由 + +当您搜索文档时,指定相同的路由值可确保搜索请求被路由到适当的分片。这可以通过减少需要查询的分片数量来显著提高性能。 + +以下示例请求使用特定路由值进行搜索: + +```json +GET /index1/_search?routing=user1 +{ + "query": { + "match": { + "name": "John Doe" + } + } +} +``` + +在此示例中,搜索查询被路由到包含使用路由值 `user1` 索引的文档的分片。 + +使用自定义路由时需要谨慎,以防止热点和数据倾斜: + + - _热点_发生在不成比例数量的文档被路由到单个分片时。这可能导致该分片成为瓶颈,因为它必须处理比其他分片更多的读写操作。因此,该分片可能会经历更高的 CPU、内存和 I/O 使用率,导致性能下降。 + + - _数据倾斜_是指数据在分片之间分布不均。如果路由值分布不均匀,某些分片最终可能存储的数据比其他分片多得多。这可能导致存储使用不平衡,某些节点的磁盘利用率比其他节点高得多。 + +## 并发分片请求 + +在搜索期间同时命中大量分片可能会显著影响 CPU 和内存消耗。默认情况下,OpenSearch 不会拒绝这些请求。但是,您可以使用多种方法来减轻此风险。以下部分描述了这些方法。 + +### 限制可以并发查询的分片数量 + +您可以使用搜索请求中的 `max_concurrent_shard_requests` 参数来限制可以并发查询的分片数量。例如,以下请求将并发分片请求数量限制为 `12`: + +```json +GET /index1/_search?max_concurrent_shard_requests=12 +{ + "query": { + "match_all": {} + } +} +``` + +### 定义搜索分片计数限制 + +您可以在 `opensearch.yml` 文件中或使用 REST API 定义动态 `action.search.shard_count.limit` 设置。任何超过此限制的搜索请求都将被拒绝并抛出错误。这有助于防止单个搜索请求消耗过多资源,从而降低整个集群的性能。以下示例请求使用 API 更新此集群设置: + +```json +PUT /_cluster/settings +{ + "transient": { + "action.search.shard_count.limit": 1000 + } +} +``` + +### 配置搜索线程池 + +OpenSearch 使用线程池来管理各种任务的执行,包括搜索操作。搜索线程池专门用于搜索请求。您可以通过在 `opensearch.yml` 中添加以下设置来调整搜索线程池的大小和队列容量: + +```yaml +thread_pool.search.size: 100 +thread_pool.search.queue_size: 1000 +``` + +此设置是静态的。有关如何配置动态和静态设置的更多信息,请参阅[配置 OpenSearch](/install-and-configure/configuring-opensearch/)。 + +#### 线程池状态 + +以下三种状态描述了线程池操作: + + - _线程分配_:如果搜索线程池中有可用线程,则请求会立即分配给线程并开始处理。 + + - _排队_:如果搜索线程池中的所有线程都忙碌,则请求被放入队列。 + + - _拒绝_:如果队列已满(例如,排队请求数量达到队列大小限制),则额外的传入搜索请求将被拒绝,直到队列中有可用空间。 + +您可以通过运行以下请求检查搜索线程池的当前配置: + +```json +GET /_cat/thread_pool/search?v&h=id,name,active,rejected,completed,size,queue_size +``` diff --git a/i18n/zh/search-plugins/star-tree-index.md b/i18n/zh/search-plugins/star-tree-index.md new file mode 100644 index 00000000..2b9feb6d --- /dev/null +++ b/i18n/zh/search-plugins/star-tree-index.md @@ -0,0 +1,506 @@ +--- +title: 星树索引 +--- + +# 星树索引 + +_星树索引_是一种专门的索引结构,旨在通过在不同粒度级别预计算和存储聚合值来提高聚合性能。这种索引技术可以更快地执行聚合,特别是对于多字段聚合。 + +一旦启用星树索引,OpenSearch 会自动构建和使用星树索引来优化支持的聚合,前提是过滤字段与定义的维度匹配,聚合字段与星树映射配置中定义的指标匹配。无需更改查询语法或请求参数。 + +在以下情况下使用星树索引加速聚合: + +- 星树索引原生支持多字段聚合。 +- 星树索引在索引过程中实时创建,因此星树中的数据始终是最新的。 +- 星树索引聚合数据以提高分页效率并减少搜索查询期间的磁盘 I/O。 + +## 星树索引结构 + +星树索引组织和聚合跨维度字段组合的数据,并在每次在摄取期间刷新或刷新段时为所有维度组合预计算指标值。这种结构使 OpenSearch 能够快速处理聚合查询,而无需扫描每个文档。 + +以下是星树配置示例: + +```json +"ordered_dimensions": [ + { + "name": "status" + }, + { + "name": "port" + } +], +"metrics": [ + { + "name": "size", + "stats": [ + "sum" + ] + }, + { + "name": "latency", + "stats": [ + "avg" + ] + } +] +``` + +此配置定义了以下内容: + +* 两个维度字段:`status` 和 `port`。`ordered_dimension` 字段指定数据的排序方式(首先按 `status`,然后按 `port`)。 +* 两个指标字段:`size` 和 `latency` 及其相应的聚合(`sum` 和 `avg`)。对于每个唯一的维度组合,指标值(`Sum(size)` 和 `Avg(latency)`)会被预聚合并存储在星树结构中。 + +OpenSearch 根据此配置创建星树索引结构。树中的每个节点对应于维度的值(或通配符 `*`)。在查询时,OpenSearch 根据查询中提供的维度值遍历树。 + +### 叶节点 + +叶节点包含特定维度组合的预计算指标聚合。这些存储为 doc 值,并由星树节点引用。 + +`max_leaf_docs` 设置控制每个叶节点可以引用多少文档,这有助于通过限制为任何给定节点扫描的文档数量来保持查询延迟的可预测性。 + +### 星节点 + +_星节点_(在下图中标记为 `*`)聚合特定维度的所有值。如果查询没有为该维度指定过滤器,OpenSearch 会从星节点检索预计算的聚合,而不是迭代多个叶节点。例如,如果查询过滤 `port` 但不过滤 `status`,OpenSearch 可以使用聚合所有状态值的数据的星节点。 + +### 查询如何使用星树 + +下图显示了为此示例创建的星树索引和三个示例查询路径。在图中,请注意每个分支对应一个维度(`status` 和 `port`)。某些节点包含预计算的聚合值(例如 `Sum(size)`),允许 OpenSearch 在查询时跳过不必要的计算。 + +*包含两个维度和两个指标的星树索引* + +彩色箭头显示了三个查询示例: + +* **蓝色箭头**:带指标聚合的多术语查询 + 查询过滤 `status = 200` 和 `port = 5600`,并计算请求大小的总和。 + + * OpenSearch 遵循此路径:`Root → 200 → 5600` + * 它从 Doc ID 1 检索指标,其中 `Sum(size) = 988` + +* **绿色箭头**:带指标聚合的单术语查询 + 查询仅过滤 `status = 200` 并计算平均请求延迟。 + + * OpenSearch 遵循此路径:`Root → 200 → *` + * 它从 Doc ID 5 检索指标,其中 `Avg(latency) = 70` + +* **红色箭头**:带指标聚合的单术语查询 + 查询仅过滤 `port = 8443` 并计算请求大小的总和。 + + * OpenSearch 遵循此路径:`Root → * → 8443` + * 它从 Doc ID 7 检索指标,其中 `Sum(size) = 1111` + +这些示例显示了 OpenSearch 如何在星树中选择最短路径并使用预聚合值来高效处理查询。 + +## 限制 + +请注意星树索引的以下限制: + +- 星树索引不支持更新或删除。要使用星树索引,数据应该是仅追加的。请参阅[启用星树索引](#启用星树索引)。 +- 星树索引仅适用于过滤索引星树配置中定义的维度字段并聚合指标字段的聚合查询。 +- 对星树配置的任何更改都需要重新索引。 +- 不支持[数组值](/mappings/supported-field-types/index/#arrays)。 +- 仅支持[特定查询和聚合](#支持的查询和聚合)。 +- 避免使用像 `_id` 这样的高基数字段作为维度,因为它们会显著增加存储使用和查询延迟。 + +## 启用星树索引 + +星树索引行为由以下集群级和索引级设置控制。索引级设置优先于集群设置。 + +| 设置 | 范围 | 默认值 | 目的 | +| ------------------------------------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `indices.composite_index.star_tree.enabled` | 集群 | `true` | 在整个集群中启用或禁用星树搜索优化。 | +| `index.composite_index` | 索引 | None | 为特定索引启用星树索引。必须在创建索引时设置。 | +| `index.append_only.enabled` | 索引 | None | 星树索引所必需的。防止更新和删除。必须为 `true`。 | +| `index.search.star_tree_index.enabled` | 索引 | `true` | 为索引上的搜索查询启用或禁用星树索引的使用。 | + +::: info NOTE +将 `indices.composite_index.star_tree.enabled` 设置为 `false` 会阻止 OpenSearch 在搜索期间使用星树优化,但星树索引结构仍会创建。要完全删除星树结构,您必须在没有星树映射的情况下重新索引数据。 +::: + +## 高级星树索引设置 + +以下索引级设置提供了对星树索引行为的细粒度控制。这些设置是静态的,意味着它们必须在创建索引时配置,之后无法更改。 + +| 设置 | 默认值 | 范围 | 目的 | +| ---------------------------------------------------------- | ------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `index.composite_index.star_tree.default.max_leaf_docs` | `10000` | 最小值:`1` | 设置叶节点中允许的最大文档数。较低的值可提高查询延迟,但会增加存储要求。 | +| `index.composite_index.star_tree.field.default.metrics` | `["value_count", "sum"]` | N/A | 定义为星树聚合计算的默认指标。这些指标会被预先计算以加速聚合查询。 | +| `index.composite_index.star_tree.field.max_base_metrics` | `100` | `4` 到 `100` | 控制可以为星树字段配置的最大基本指标数。更多指标提供更多聚合选项,但会增加索引大小。 | +| `index.composite_index.star_tree.field.max_dimensions` | `10` | `2` 到 `10` | 设置可以作为星树索引字段一部分的最大维度数。影响星树索引大小和查询性能。 | +| `index.composite_index.star_tree.field.max_date_intervals` | `3` | `1` 到 `3` | 指定可以为星树日期字段配置的最大日期间隔数。控制时间粒度选项。 | +| `index.composite_index.star_tree.max_fields` | `1` | `1` 到 `1` | 控制每个索引的最大星树字段数。每个索引仅支持一个星树字段。 | + +要创建使用星树索引的索引,请发送以下请求: + +```json +PUT /logs +{ + "settings": { + "index.composite_index": true, + "index.append_only.enabled": true + } +} +``` + +确保为星树映射中使用的维度和指标字段启用 `doc_values` 参数。对于大多数字段类型,这是默认启用的。有关更多信息,请参阅 [Doc values](/mappings/mapping-parameters/doc-values/)。 + +### 禁用星树使用 + +默认情况下,`indices.composite_index.star_tree.enabled` 集群设置和 `index.search.star_tree_index.enabled` 索引设置都设置为 `true`。要禁用使用星树索引的搜索,请将这两个设置都设置为 `false`。请注意,索引设置优先于集群设置。 + +## 示例映射 + +以下示例显示如何创建在 `logs` 索引中预计算聚合的星树索引。`sum` 和 `average` 聚合分别在 `size` 和 `latency` 字段上计算,用于维度字段中的所有值组合。维度按 `status`、然后 `port`,最后 `method` 排序,这决定了数据在树结构中的组织方式: + +```json +PUT /logs +{ + "settings": { + "index.number_of_shards": 1, + "index.number_of_replicas": 0, + "index.composite_index": true, + "index.append_only.enabled": true + }, + "mappings": { + "composite": { + "request_aggs": { + "type": "star_tree", + "config": { + "date_dimension" : { + "name": "@timestamp", + "calendar_intervals": [ + "month", + "day" + ] + }, + "ordered_dimensions": [ + { + "name": "status" + }, + { + "name": "port" + }, + { + "name": "method" + } + ], + "metrics": [ + { + "name": "size", + "stats": [ + "sum" + ] + }, + { + "name": "latency", + "stats": [ + "avg" + ] + } + ] + } + } + }, + "properties": { + "status": { + "type": "integer" + }, + "port": { + "type": "integer" + }, + "size": { + "type": "integer" + }, + "method" : { + "type": "keyword" + }, + "latency": { + "type": "scaled_float", + "scaling_factor": 10 + } + } + } +} +``` + +有关星树索引映射和参数的更多信息,请参阅[星树字段类型](/mappings/supported-field-types/star-tree/)。 + +## 支持的查询和聚合 + +星树索引优化聚合。每个查询必须至少包含一个受支持的聚合才能使用星树优化。 + +### 支持的查询 + +没有聚合的查询不能使用星树优化。查询的字段必须存在于星树配置的 `ordered_dimensions` 部分。支持以下查询: + +- [Term 查询](/query-dsl/term/term) +- [Terms 查询](/query-dsl/term/terms) +- [Match all docs 查询](/query-dsl/match-all) +- [Range 查询](/query-dsl/term/range) +- [Boolean 查询](/query-dsl/compound/bool) + +#### 布尔查询限制 + +星树索引中的布尔查询遵循每种子句类型的特定规则: + +* `must` 和 `filter` 子句: + - 两者都受支持,并且以相同方式处理,因为 `filter` 不影响评分。 + - 可以跨不同维度操作。 + - 在所有 `must`/`filter` 子句(包括嵌套子句)中,每个维度仅允许一个条件。 + - 支持 term、terms 和 range 查询。 + +* `should` 子句: + - 必须在同一维度上操作,不能跨不同维度操作 + - 只能使用 term、terms 和 range 查询。 + +* `must` 子句内的 `should` 子句: + - 作为必需条件。 + - 当与外部 `must` 在同一维度上操作时:`should` 条件的并集与外部 `must` 条件相交。 + - 当在不同维度上操作时:作为必需条件正常处理。 + +* 不支持 `must_not` 子句。 +* 不支持带有 `minimum_should_match` 参数的查询。 + +以下布尔查询**受支持**,因为它遵循这些限制: + +```json +{ + "bool": { + "must": [ + {"term": {"method": "GET"}} + ], + "filter": [ + {"range": {"status": {"gte": 200, "lt": 300}}} + ], + "should": [ + {"term": {"port": 443}}, + {"term": {"port": 8443}} + ] + } +} +``` + +以下布尔查询**不受支持**,因为它们违反了这些限制: + +```json +{ + "bool": { + "should": [ + {"term": {"status": 200}}, + {"term": {"method": "GET"}} // SHOULD 跨不同维度 + ] + } +} +``` + +```json +{ + "bool": { + "must": [ + {"term": {"status": 200}} + ], + "must_not": [ // 不支持 MUST_NOT + {"term": {"method": "DELETE"}} + ] + } +} +``` + +### 支持的聚合 + +星树索引支持以下聚合。 + +#### 指标聚合 + +支持以下指标聚合: + +- [Sum](/aggregations/metric/sum) +- [Minimum](/aggregations/metric/minimum) +- [Maximum](/aggregations/metric/maximum) +- [Value count](/aggregations/metric/value-count) +- [Average](/aggregations/metric/average) + +要在星树索引中使用可搜索聚合,请确保满足以下先决条件: + +- 字段必须存在于星树配置的 `metrics` 部分。 +- 指标聚合类型必须是 `stats` 参数的一部分。 + +以下示例使用[示例映射](#示例映射)获取所有带有 `status=500` 的错误日志的 `size` 字段中所有值的总和: + +```json +POST /logs/_search +{ + "query": { + "term": { + "status": "500" + } + }, + "aggs": { + "sum_size": { + "sum": { + "field": "size" + } + } + } +} +``` + +使用星树索引,结果将从单个聚合文档中检索,因为它遍历 `status=500` 节点,而不是扫描所有匹配的文档。这会降低查询延迟。 + +#### 带指标聚合的日期直方图 + +您可以在日历间隔上使用带有指标子聚合的[日期直方图](/aggregations/bucket/date-histogram)。 + +要使用日期直方图聚合并使其在星树索引中可搜索,请记住以下要求: + +- 星树映射配置中的日历间隔可以使用请求的日历字段或比请求字段粒度更低的字段。例如,如果聚合使用 `month` 字段,星树搜索仍然可以使用较低粒度的字段,例如 `day`。 +- 指标子聚合必须是聚合请求的一部分。 + +以下示例过滤日志以仅包括状态码在 `200` 和 `400` 之间的日志,并将响应的 `size` 设置为 `0`,以便仅返回聚合结果。然后,它按日历月聚合过滤的日志,并计算每个月请求的总 `size`: + +```json +POST /logs/_search +{ + "size": 0, + "query": { + "range": { + "status": { + "gte": "200", + "lte": "400" + } + } + }, + "aggs": { + "by_month": { + "date_histogram": { + "field": "@timestamp", + "calendar_interval": "month" + }, + "aggs": { + "sum_size": { + "sum": { + "field": "size" + } + } + } + } + } +} +``` + +#### 关键字和数字术语聚合 + +您可以在关键字和数字字段上使用[术语聚合](/aggregations/bucket/terms)与星树索引搜索。 + +对于与术语聚合的星树搜索兼容性,请记住以下行为: + +- 术语聚合中使用的字段应该是星树索引中定义的维度的一部分。 +- 指标子聚合是可选的,只要相关指标是星树配置的一部分。 + +以下示例按 `user_id` 字段聚合日志并返回每个唯一用户的计数: + +```json +POST /logs/_search +{ + "size": 0, + "aggs": { + "users": { + "terms": { + "field": "user_id" + } + } + } +} +``` + +以下示例按 `order_quantity` 聚合订单并计算每个数量的平均 `total_price`: + +```json +POST /orders/_search +{ + "size": 0, + "aggs": { + "quantities": { + "terms": { + "field": "order_quantity" + }, + "aggs": { + "avg_total_price": { + "avg": { + "field": "total_price" + } + } + } + } + } +} +``` + +#### 范围聚合 + +您可以在数字字段上使用[范围聚合](/aggregations/bucket/range)与星树索引搜索。 + +要使范围聚合有效地与星树索引一起工作,请记住以下行为: + +- 范围聚合中使用的字段应该是星树索引中定义的维度的一部分。 +- 您可以包含指标子聚合以计算每个定义范围内的指标,只要相关指标是星树配置的一部分。 + +以下示例根据 `temperature` 字段的预定义范围聚合文档: + +```json +POST /sensors/_search +{ + "size": 0, + "aggs": { + "temperature_ranges": { + "range": { + "field": "temperature", + "ranges": [ + { "to": 20 }, + { "from": 20, "to": 30 }, + { "from": 30 } + ] + } + } + } +} +``` + +以下示例按价格范围聚合销售数据并计算每个范围内销售的总 `quantity`: + +```json +POST /sales/_search +{ + "size": 0, + "aggs": { + "price_ranges": { + "range": { + "field": "price", + "ranges": [ + { "to": 100 }, + { "from": 100, "to": 500 }, + { "from": 500 } + ] + }, + "aggs": { + "total_quantity": { + "sum": { + "field": "quantity" + } + } + } + } + } +} +``` + +#### 嵌套聚合 + +您可以在嵌套结构中组合多个支持的桶聚合(例如 `terms` 和 `range`),星树索引将优化这些嵌套聚合。有关嵌套聚合的更多信息,请参阅[嵌套聚合](/aggregations/#nested-aggregations)。 + +#### 多术语聚合 + +当聚合字段定义为星树配置中的维度时,星树索引会优化 `multi_terms` 聚合。有关多术语聚合的更多信息,请参阅[多术语聚合](/aggregations/bucket/multi-terms)。 + +## 后续步骤 + +- [星树字段类型](/mappings/supported-field-types/star-tree/) diff --git a/i18n/zh/search-plugins/ubi/dsl-queries.md b/i18n/zh/search-plugins/ubi/dsl-queries.md new file mode 100644 index 00000000..eb707d70 --- /dev/null +++ b/i18n/zh/search-plugins/ubi/dsl-queries.md @@ -0,0 +1,92 @@ +--- +title: UBI 查询 DSL 查询示例 +--- + +# UBI 查询 DSL 查询示例 + +您可以使用 OpenSearch 搜索查询语言 [查询 DSL](/query-dsl/) 来编写用户行为洞察(UBI)查询。以下示例返回每个 `action_name` 事件发生的次数。 +有关更广泛的分析查询,请参阅 [UBI SQL 查询示例](/search-plugins/ubi/sql-queries)。 +#### 示例请求 +```json +GET ubi_events/_search +{ + "size":0, + "aggs":{ + "event_types":{ + "terms": { + "field":"action_name", + "size":10 + } + } + } +} +``` + +#### 示例响应 + +```json +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 10000, + "relation": "gte" + }, + "max_score": null, + "hits": [] + }, + "aggregations": { + "event_types": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "brand_filter", + "doc_count": 3084 + }, + { + "key": "product_hover", + "doc_count": 3068 + }, + { + "key": "button_click", + "doc_count": 3054 + }, + { + "key": "product_sort", + "doc_count": 3012 + }, + { + "key": "on_search", + "doc_count": 3010 + }, + { + "key": "type_filter", + "doc_count": 2925 + }, + { + "key": "login", + "doc_count": 2433 + }, + { + "key": "logout", + "doc_count": 1447 + }, + { + "key": "new_user_entry", + "doc_count": 207 + } + ] + } + } +} +``` + +您可以在 OpenSearch Dashboards [开发工具](/dashboards/dev-tools/)控制台中运行上述查询。 diff --git a/i18n/zh/search-plugins/ubi/index.md b/i18n/zh/search-plugins/ubi/index.md new file mode 100644 index 00000000..9f438e0a --- /dev/null +++ b/i18n/zh/search-plugins/ubi/index.md @@ -0,0 +1,82 @@ +--- +title: 用户行为洞察 +description: "用户行为洞察(UBI)是一种用于捕获用户搜索行为的模式,包括用户提交的查询、显示的结果以及他们采取的操作。" +--- + +# 用户行为洞察 + +<Badge type="tip" text="2.15 版本引入" /> + +<Badge type="tip" text="参考 UBI 规范 1.3.0" /> + +用户行为洞察(UBI)是一种用于捕获用户搜索行为的模式。搜索行为包括用户提交的查询、向他们呈现的结果以及他们对这些结果采取的操作。UBI 模式将所有用户交互(事件)与执行操作的搜索结果关联起来。也就是说,它不仅捕获事件的时间顺序,还捕获事件之间的因果关系。对这些行为的分析用于提高搜索结果的质量。 + +网页或应用程序等客户端应用程序捕获用户行为并将 UBI 数据发送到 UBI 端点。对于网页,这通常由 JavaScript 代码处理。 + +原则上,发送到服务器的查询和服务器返回的结果可以从客户端发送到 UBI 端点。但作为优化,它们可以直接从服务器发送到 UBI 端点,而无需往返客户端。这就是 UBI 插件的功能,不是采用 UBI 的必要条件。 + +> "我们的用户如何使用我们的产品,搜索结果对他们是否有用,他们是否点击了我们给出的前 N 个结果以及所有相关内容" -- 从事搜索工作的数据科学家。 + +UBI 包括以下元素: +* 一个机器可读的[模式](https://github.com/o19s/ubi),促进 UBI 规范的互操作性。 +* [ubi.js](https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js):一个(可选的)客户端 JavaScript 库,用于捕获搜索和事件。 +* 一个(可选的)OpenSearch [插件](https://github.com/opensearch-project/user-behavior-insights),简化查询数据的记录。 + +OpenSearch 中的高级功能,如[搜索相关性工作台](/search-plugins/search-relevance/using-search-relevance-workbench)和[混合搜索优化器](/search-plugins/search-relevance/optimize-hybrid-search),都建立在根据 UBI 规范收集的数据之上。 + +<!-- vale off --> + +<table> + <tr style="vertical-align: top;"> + <td> + <h2>教程</h2> + <ul> + <li><a href="/search-plugins/ubi/ubi-aws-managed-services-tutorial">学习使用 Amazon OpenSearch Ingestion</a> 管道在 Amazon OpenSearch Service 中收集 UBI 格式的数据。</li> + <li><a href="/search-plugins/ubi/ubi-dashboard-tutorial">学习创建自定义仪表板</a>来可视化 UBI 数据。</li> + <li> 基于 <a href="https://github.com/o19s/chorus-opensearch-edition">Chorus for OpenSearch</a> 演示: + <ul> + <li><a href="https://github.com/o19s/chorus-opensearch-edition/blob/main/katas/002_derive_interaction_data.md">从用户点击中派生交互数据。</a></li> + <li><a href="https://github.com/o19s/chorus-opensearch-edition/blob/main/katas/006_protecting_sensitive_information.md">使用 UBI 时保护敏感信息。</a></li> + <li><a href="https://github.com/o19s/chorus-opensearch-edition/blob/main/katas/007_configure_AB_with_TDI.md">使用团队草稿交错配置 A/B 测试</a></li> + </ul> + </li> + </ul> + </td> + <td> + <h2>操作指南</h2> + <ul> + <li>如何在 OpenSearch 中<a href="https://github.com/opensearch-project/user-behavior-insights?tab=readme-ov-file#user-quick-start">安装和使用 UBI 插件</a>。</li> + <li>如何使用 <a href="/search-plugins/ubi/ubi-javascript-collector">ubi.js</a>,一个用于捕获事件的客户端 JavaScript 库。</li> + <li>如何<a href="/search-plugins/ubi/dsl-queries">使用 OpenSearch 查询 DSL 编写 UBI 数据查询。</a></li> + <li>如何<a href="/search-plugins/ubi/sql-queries">使用 SQL 编写 UBI 数据的分析查询。</a></li> + </ul> + </td> + </tr> + <tr style="vertical-align: top;"> + <td> + <h2>说明</h2> + <ul> + <li><a href="https://docs.google.com/presentation/d/e/2PACX-1vTJ9wYhhRG2sHxB-pm2Pfcqv0AzwRzSgTn-VyKTV6bL4PyXQC9C9kE6Oyrkag2_Olb6Ugevs_kbflId/pub?start=true&loop=false&delayms=3000">为什么选择 UBI?</a> 演示文稿。</li> + <li>通过 <a href="https://www.UBISearch.dev">https://www.UBISearch.dev</a> 了解更多关于此标准的信息,这是社区交流中心。</li> + <li>观看 <a href="https://youtu.be/0chun264PRQ">利用 UBI 增强搜索相关性</a> 演讲,了解如何使用这些数据来提高搜索质量。</li> + <li>深入了解 UBI。观看 <a href="https://www.youtube.com/watch?v=xi261oUamXc">您已部署用户行为洞察。接下来呢?</a> 看看您还能做什么。</li> + </ul> + </td> + <td> + <h2>参考</h2> + <ul> + <li><a href="https://github.com/opensearch-project/user-behavior-insights">OpenSearch 的 UBI 插件</a></li> + <li><a href="/search-plugins/ubi/schemas">OpenSearch 中的 UBI 模式</a></li> + <li><a href="https://github.com/o19s/ubi">UBI 模式</a>的仓库。</li> + <li><a href="https://o19s.github.io/ubi/docs/html/1.3.0/query.request.schema.html">查询跟踪规范</a></li> + <li><a href="https://o19s.github.io/ubi/docs/html/1.3.0/event.schema.html">事件跟踪规范</a></li> + + </ul> + </td> + </tr> +</table> + +::: tip TIP +<!-- vale on --> +文档类别是根据 [Diátaxis](https://diataxis.fr/) 的概念改编的。 +::: diff --git a/i18n/zh/search-plugins/ubi/schemas.md b/i18n/zh/search-plugins/ubi/schemas.md new file mode 100644 index 00000000..3c741ff5 --- /dev/null +++ b/i18n/zh/search-plugins/ubi/schemas.md @@ -0,0 +1,138 @@ +--- +title: UBI 索引模式 +--- + +# UBI 索引模式 + +用户行为洞察(UBI)数据收集过程涉及跟踪和记录用户提交的查询,以及监控和记录用户在收到搜索结果后的后续操作或事件。数据收集过程涉及两个 UBI 索引模式: +* [查询索引](#ubi-查询索引),存储搜索和结果。 +* [事件索引](#ubi-事件索引),存储用户查询后的所有后续用户操作。 + +## 关键标识符 + +为了使 UBI 正常运行,在启用 UBI 的应用程序中,以下字段之间的连接必须始终保持一致: + +- [`object_id`](#object_id) 表示用户响应查询收到的任何对象的 ID。例如,如果您搜索书籍,它可能是书籍的 ISBN,如 `978-3-16-148410-0`。 +- [`query_id`](#query_id) 是执行的原始查询的唯一 ID,而 `object_id` 映射到用户查询返回的_命中_的主要标识符。 +- [`client_id`](#client_id) 表示唯一的查询来源。这通常是唯一用户使用的 Web 浏览器。 +- [`object_id_field`](#object_id_field) 指定索引中提供 `object_id` 的字段名称。例如,如果您搜索书籍,该值可能是 `isbn_code`。 +- [`action_name`](#action_name) 虽然技术上不是 ID,但指定了对具有给定 `object_id` 的对象采取(或未采取)的确切用户操作(如 `click`、`add_to_cart`、`watch`、`view` 或 `purchase`)。 + +总结一下,`query_id` 表示通过 `client_id` 跟踪的客户端的唯一搜索的开始。搜索返回各种对象,每个对象都有唯一的 `object_id`。`action_name` 指定用户正在执行的操作,并连接到每个具有特定 `object_id` 的对象。您可以通过检查 `object_id_field` 来区分不同类型的对象。 + +通常,您可以通过检索用户 `client_id` 的所有数据并检查各个 `query_id` 数据来推断用户的整体搜索历史。每个应用程序通过检查后端数据来确定什么构成搜索会话。 + +## 重要的 UBI 角色 + +下图说明了**用户**与**搜索客户端**和**UBI 客户端**交互的过程, +以及这些如何与包含**UBI 事件**和**UBI 查询**索引的**OpenSearch 集群**交互。 + +蓝色箭头说明标准搜索,粗虚线说明 UBI 特定的添加, +红色箭头说明 `query_id` 到和从 OpenSearch 的流动。 + +以下是关于角色的一些关键点: +- **搜索客户端**负责搜索并从 OpenSearch 文档索引接收*对象*(上图中的 1、2、**5** 和 7)。 + + ::: info NOTE +步骤 **5** 是粗体的,因为它表示 UBI 特定的添加,如 `query_id`,到标准 OpenSearch 交互。 + ::: + +- 如果在搜索请求的 `ext.ubi` 节中激活,**用户行为洞察**插件在后台管理**UBI 查询**存储,索引每个查询,确保所有返回的 `object_id` 值都有唯一的 `query_id`,然后将 `query_id` 传回**搜索客户端**,以便事件可以链接到查询(上图中的 3、4 和 **5**)。 +- **对象**代表用户使用查询搜索的项目。激活 UBI 涉及将您的真实世界对象(使用其标识符,如 `isbn` 或 `sku`)映射到搜索的索引中的 `object_id` 字段。 +- **搜索客户端**(如果与**UBI 客户端**分开)将索引的 `query_id` 转发到**UBI 客户端**。 + 即使在此图中*搜索*和*UBI 事件索引*角色是分开的,许多实现可以对这两个角色使用相同的 OpenSearch 客户端实例(上图中的 6)。 +- **UBI 客户端**然后使用指定的 `query_id` 索引所有用户事件,直到执行新搜索。此时,**用户行为洞察**插件生成新的 `query_id` 并传回**UBI 客户端**。 +- 如果**UBI 客户端**与结果**对象**交互,例如在**添加到购物车**事件期间,则 `object_id`、`add_to_cart` `action_name` 和 `query_id` 都一起索引,表示*搜索*和*对象*之间的因果关系(上图中的 8 和 9)。 + +## UBI 存储 + +支持 UBI 数据收集涉及两个独立的存储: +* UBI 查询 +* UBI 事件 + +### UBI 查询索引 + +所有底层查询信息和结果(`object_ids`)都存储在 `ubi_queries` 索引中,并且在后台基本上不可见。 + +`ubi_queries` 索引[模式](https://github.com/OpenSearch-project/user-behavior-insights/tree/main/src/main/resources/queries-mapping.json)包括以下字段: + +- `timestamp`(事件和查询):ISO 8601 格式的时间戳,表示收到查询的时间。 + +- `query_id`(事件和查询):客户端提供或搜索引擎生成的查询的唯一 ID。具有相同文本的不同查询会生成不同的 `query_id` 值。 + +- `client_id`(事件和查询):客户端应用程序提供的客户端 ID。 + +- `query_response_hit_ids`(查询):对象 ID 数组。ID 可以与 `_id` 具有相同的值,但它旨在作为文档、项目或产品的外部有效 ID。 + +因为 UBI 管理 `ubi_queries` 索引,您永远不需要直接写入此索引(除非导入数据时)。 + +### UBI 事件索引 + +客户端直接将事件索引到 `ubi_events` 索引,链接事件 [`action_name`](#action_name)、对象(每个都有 `object_id`)和查询(每个都有 `query_id`),以及任何其他重要的事件信息。 +因为此模式是动态的,您可以在索引时添加当前**UBI 事件**[模式](https://github.com/opensearch-project/user-behavior-insights/tree/main/src/main/resources/events-mapping.json)中不存在的任何新字段或结构(如用户信息或地理位置信息)。 + +::: info NOTE +开发者可以在 [`event_attributes`](#event_attributes) 下定义新字段。 +::: + +以下是 `ubi_events` 索引中的预定义最小字段: + + <p id="application"> </p> + +- `application`(大小 100):跟踪 UBI 事件的应用程序名称(例如,`amazon-shop` 或 `ABC-microservice`)。 + + <p id="action_name"> </p> + +- `action_name`(大小 100):触发事件的操作名称。UBI 规范定义了一些常见的操作名称,但您可以使用任何名称。 + + <p id="query_id"> </p> + +- `query_id`(大小 100):查询的唯一标识符,通常是 UUID,但可以是任何字符串。 + `query_id` 由客户端提供或由 UBI 插件在查询时生成。**UBI 查询**和**UBI 事件**索引中的 `query_id` 值必须一致。 + +<p id="client_id"> </p> + +- `client_id`:发出查询的客户端。这通常是唯一用户使用的 Web 浏览器。 + **UBI 查询**和**UBI 事件**索引中的 `client_id` 必须一致。 + +- `timestamp`:事件发生的时间,ISO 8601 格式,如 `2018-11-13T20:20:39+00:00Z`。 + +- `message_type`(大小 100):用于对操作(每个都有 `action_name`)进行分组的逻辑桶。例如,`QUERY` 或 `CONVERSION`。 + +- `message`(大小 1,024):日志条目的可选文本消息。例如,对于 `message_type` `QUERY`,`message` 可以包含与用户搜索相关的文本。 + + <p id="event_attributes"> </p> + +- `event_attributes`:描述事件重要上下文的可扩展结构。此结构由两个主要结构组成:`position` 和 `object`。该结构是可扩展的,因此您可以添加有关事件的自定义信息,如事件的时间、用户或会话。 + + + ::: danger WARNING + 因为 `ubi_events` 索引配置为执行动态映射,索引可能会因许多新字段而变得臃肿。 + ::: + + - `event_attributes.position`:包含关于事件来源位置的信息的结构,如屏幕 x、y 坐标,或对象在结果列表中的位置: + + - `event_attributes.position.ordinal`:跟踪用户可以选择的列表位置(例如,选择第三个元素可以描述为 `event{onClick, results[4]}`)。 + + - `event_attributes.position.xy.{x,y}`:跟踪客户端定义的 x 和 y 值。 + + - `event_attributes.object`:包含关于查询返回的对象(例如,书籍、产品或帖子)的识别信息。 + `object` 结构可以通过内部 ID 或对象 ID 引用对象。`object_id` 是将先前查询链接到此对象的 ID。此字段包含以下子字段: + + - `event_attributes.object.internal_id`:OpenSearch 用于内部索引对象的唯一 ID,例如索引中的 `_id` 字段。 + + <p id="object_id"> + + - `event_attributes.object.object_id`:用户可以通过该 ID 在**文档语料库**中找到对象实例。示例包括 `ssn`、`isbn` 或 `ean`。变体需要包含在 `object_id` 中,因此红色 T 恤的 `object_id` 应该是其 SKU。 + 初始化 UBI 需要将文档索引的主键映射到此 `object_id`。 + </p> + + <p id="object_id_field"> + + - `event_attributes.object.object_id_field`:指示对象的类型/类别以及包含 `object_id` 的搜索索引字段的名称,如 `ssn`、`isbn` 或 `ean`。 + + - `event_attributes.object.description`:对象的可选描述。 + + - `event_attributes.object.object_detail`:关于对象的可选附加信息。 + + - *可扩展字段*:请注意,`object` 中任何新索引的字段都将动态扩展此模式。 diff --git a/i18n/zh/search-plugins/ubi/sql-queries.md b/i18n/zh/search-plugins/ubi/sql-queries.md new file mode 100644 index 00000000..8a9454f7 --- /dev/null +++ b/i18n/zh/search-plugins/ubi/sql-queries.md @@ -0,0 +1,337 @@ +--- +title: UBI SQL 查询示例 +--- + +# UBI SQL 查询示例 + +您可以通过 OpenSearch Dashboards [查询工作台](/dashboards/query-workbench)运行用户行为洞察(UBI)SQL 查询示例。 + +## 零结果的查询 + +可以在查询索引(`ubi_queries`)或事件索引(`ubi_events`)上执行对事件的查询。 + +### 服务器端查询 + +启用 UBI 的搜索服务器在进行查询时记录查询及其结果,因此要查找*没有*结果的所有查询,请搜索空的 `query_response_hit_ids`: + +```sql +select + count(*) +from ubi_queries +where query_response_hit_ids is null + +``` + +### 客户端事件 + +虽然在服务器端查找没有结果的查询相对简单,但您也可以通过查询客户端记录的*事件属性*获得相同的结果。 +客户端和服务器端查询都返回相同的结果。使用以下查询搜索没有结果的查询: + +```sql +select + count(0) +from ubi_events +where event_attributes.result_count > 0 +``` + +## 热门查询 + +可以使用以下任一查询找到热门查询。 + +### 服务器端 + +```sql +select + user_query, count(0) Total +from ubi_queries +group by user_query +order by Total desc +``` + +### 客户端 + +```sql +select + message, count(0) Total +from ubi_events +where + action_name='on_search' +group by message +order by Total desc +``` + +两个查询都返回搜索字符串的分布,如下表所示。 + +<!-- vale off --> + +消息|总计 +|---|---| +User Behavior Insights|127 +best Laptop|78 +`camera`|21 +`backpack`|17 +`briefcase`|14 +`camcorder`|11 +`cabinet`|9 +`bed`|9 +`box`|8 +`bottle`|8 +`calculator`|8 +`armchair`|7 +`bench`|7 +`blackberry`|6 +`bathroom`|6 +User Behavior Insights Mac|5 +best Laptop Dell|5 +User Behavior Insights VTech|5 +`ayoolaolafenwa`|5 +User Behavior Insights Dell|4 +best Laptop Vaddio|4 +agrega modelos intuitivas|4 +bеуоnd|4 +abraza metodologías B2C|3 + +<!-- vale on --> + +## 事件类型分布计数 + +要创建一个可视化最常见事件的饼图小部件,请运行以下查询: + +```sql +select + action_name, count(0) Total +from ubi_events +group by action_name +order by Total desc +``` + +结果包括跨操作的分布,如下表所示。 + +<!-- vale off --> + +`action_name`|总计 +|---|---| +`on_search`|5425 +`brand_filter`|3634 +`global_click`|3571 +`view_search_results`|3565 +`product_sort`|3558 +`type_filter`|3505 +`product_hover`|820 +`item_click`|708 +`purchase`|407 +`declined_product`|402 +`add_to_cart`|373 +`page_exit`|142 +`user_feedback`|123 +404_redirect|123 + +<!-- vale on --> + +以下查询显示跨用户操作的利润分布: + +```sql +select + action_name, + count(0) total, + AVG( event_attributes.object.object_detail.cost ) average_cost, + AVG( event_attributes.object.object_detail.margin ) average_margin +from ubi_events +group by action_name +order by average_cost desc +``` + +结果包括操作以及跨平均成本和利润的分布,如下表所示。 + +<!-- vale off --> + +`action_name`|总计|平均成本|平均利润 +---|---|---|--- +`declined_product`|395|8457.12|6190.96 +`item_click`|690|7789.40|5862.70 +`add_to_cart`|374|6470.22|4617.09 +`purchase`|358|5933.83|5110.69 +`global_click`|3555|| +`product_sort`|3711|| +`product_hover`|779|| +`page_exit`|107|| +`on_search`|5438|| +`brand_filter`|3722|| +`user_feedback`|120|| +404_redirect|110|| +`view_search_results`|3639|| +`type_filter`|3691|| + +<!-- vale on --> + +## 搜索旅程示例 + +要在查询日志中查找搜索,请运行以下查询: + +```sql +select + client_id, query_id, user_query, query_response_hit_ids, query_response_id, timestamp +from ubi_queries where query_id = '7ae52966-4fd4-4ab1-8152-0fd0b52bdadf' +``` + +下表显示了上述查询的结果。 + +<!-- vale off --> + +`client_id`|query_id|user_query|query_response_hit_ids|query_response_id|timestamp +---|---|---|---|---|--- +`a15f1ef3-6bc6-4959-9b83-6699a4d29845`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|notebook|0882780391659|6e92c90c-1eee-4dd6-b820-c522fd4126f3|2024-06-04 19:02:45.728 + +<!-- vale on --> + +`query_id` 中的 `query` 字段具有以下嵌套结构: + +```json +{ + "query": { + "size": 25, + "query": { + "query_string": { + "query": "(title:\"notebook\" OR attr_t_device_type:\"notebook\" OR name:\"notebook\")", + "fields": [], + "type": "best_fields", + "default_operator": "or", + "max_determinized_states": 10000, + "enable_position_increments": true, + "fuzziness": "AUTO", + "fuzzy_prefix_length": 0, + "fuzzy_max_expansions": 50, + "phrase_slop": 0, + "analyze_wildcard": false, + "escape": false, + "auto_generate_synonyms_phrase_query": true, + "fuzzy_transpositions": true, + "boost": 1.0 + } + }, + "ext": { + "query_id": "7ae52966-4fd4-4ab1-8152-0fd0b52bdadf", + "user_query": "notebook", + "client_id": "a15f1ef3-6bc6-4959-9b83-6699a4d29845", + "object_id_field": "primary_ean", + "query_attributes": { + "application": "ubi-demo" + } + } + } +} +``` + +在事件日志 `ubi_events` 中,搜索与上述查询对应的事件(其查询 ID 为 `7ae52966-4fd4-4ab1-8152-0fd0b52bdadf`): + +```sql +select + application, query_id, action_name, message_type, message, client_id, timestamp +from ubi_events +where query_id = '7ae52966-4fd4-4ab1-8152-0fd0b52bdadf' +order by timestamp +``` + +<!-- vale off --> + +结果包括与用户查询关联的所有事件,如下表所示。 + +`application`|query_id|action_name|message_type|message|client_id|timestamp +---|---|---|---|---|---|--- +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|on_search|QUERY|notebook|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.777 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|product_hover|INFO|orquesta soluciones uno-a-uno|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.816 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|item_click|INFO|innova relaciones centrado al usuario|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.86 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|add_to_cart|CONVERSION|engineer B2B platforms|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.905 +`ubi-demo`|7ae52966-4fd4-4ab1-8152-0fd0b52bdadf|purchase|CONVERSION|Purchase item 0884420136132|a15f1ef3-6bc6-4959-9b83-6699a4d29845|2024-06-04 19:02:45.913 + +<!-- vale on --> + +## 用户会话 + +要查找更多相同用户的会话(客户端 ID 为 `a15f1ef3-6bc6-4959-9b83-6699a4d29845`),请运行以下查询: + +```sql +select + application, event_attributes.session_id, query_id, + action_name, message_type, event_attributes.dwell_time, + event_attributes.object.object_id, + event_attributes.object.description, + timestamp +from ubi_events +where client_id = 'a15f1ef3-6bc6-4959-9b83-6699a4d29845' +order by query_id, timestamp +``` + +结果被截断以显示会话示例,如下表所示。 + +<!-- vale off --> + +`application`|event_attributes.session_id|query_id|action_name|message_type|event_attributes.dwell_time|event_attributes.object.object_id|event_attributes.object.description|timestamp +---|---|---|---|---|---|---|---|--- +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|on_search|QUERY|46.6398|||2024-06-04 19:06:36.239 +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|product_hover|INFO|53.681877|0065030834155|USB 2.0 S-Video and Composite Video Capture Cable|2024-06-04 19:06:36.284 +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|item_click|INFO|40.699997|0065030834155|USB 2.0 S-Video and Composite Video Capture Cable|2024-06-04 19:06:36.334 +`ubi-demo`|00731779-e290-4709-8af7-d495ae42bf48|0254a9b7-1d83-4083-aa46-e12dff86ec98|declined_product|REJECT|5.0539055|0065030834155|USB 2.0 S-Video and Composite Video Capture Cable|2024-06-04 19:06:36.373 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|on_search|QUERY|26.422775|||2024-06-04 19:04:40.832 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|on_search|QUERY|17.1094|||2024-06-04 19:04:40.837 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|brand_filter|FILTER|40.090374|OBJECT-6c91da98-387b-45cb-8275-e90d1ea8bc54|supplier_name|2024-06-04 19:04:40.852 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|type_filter|INFO|37.658962|OBJECT-32d9bb39-b17d-4611-82c1-5aaa14368060|filter_product_type|2024-06-04 19:04:40.856 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|product_sort|SORT|3.6380951|||2024-06-04 19:04:40.923 +`ubi-demo`|844ca4b5-b6f8-4f7b-a5ec-7f6d95788e0b|0cf185be-91a8-49cf-9401-92ad079ce43b|view_search_results|INFO|46.436115|||2024-06-04 19:04:40.942 + +<!-- vale on --> + +## 列出未提交任何查询就登出的用户会话 + +以下查询搜索没有关联 `query_id` 的用户。请注意,如果客户端没有将返回的查询传递给其他事件,可能会发生这种情况。 + +```sql +select + client_id, session_id, count(0) EventTotal +from ubi_events +where action_name='logout' and query_id is null +group by client_id, session_id +order by EventTotal desc +``` + +<!-- vale off --> + +下表显示了客户端 ID、会话 ID,以及有 1 个事件 `logout`。 + +`client_id`|session_id|EventTotal +---|---|--- +100_15c182f2-05db-4f4f-814f-46dc0de6b9ea|1c36712c-44b8-4fdd-8f0d-fdfeab5bd794_1290|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|816f94d6-8966-4a8b-8984-a2641d5865b2_2251|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|314dc1ff-ef38-4da4-b4b1-061f62dddcbb_2248|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|1ce5dc30-31bb-4759-9451-5a99b28ba91b_2255|1 +175_e5f262f1-0db3-4948-b349-c5b95ff31259|10ac0fc0-409e-4ba0-98e9-edb323556b1a_2249|1 + +<!-- vale on --> + +您可能想要识别多次未提交查询就登出的用户。以下查询可让您查看哪些用户这样做最多: + +```sql +select + client_id, count(0) EventTotal +from ubi_events +where action_name='logout' and query_id is null +group by client_id +order by EventTotal desc +``` + +下表显示了用户客户端 ID 和没有任何查询的登出次数。 + +<!-- vale off --> + +`client_id`|EventTotal +---|--- +87_5a6e1f8c-4936-4184-a24d-beddd05c9274|8 +127_829a4246-930a-4b24-8165-caa07ee3fa47|7 +49_5da537a3-8d94-48d1-a0a4-dcad21c12615|6 +56_6c7c2525-9ca5-4d5d-8ac0-acb43769ac0b|6 +140_61192c8e-c532-4164-ad1b-1afc58c265b7|6 +149_3443895e-6f81-4706-8141-1ebb0c2470ca|6 +196_4359f588-10be-4b2c-9e7f-ee846a75a3f6|6 +173_39d4cbfd-0666-4e77-84a9-965ed785db49|5 + +<!-- vale on --> diff --git a/i18n/zh/search-plugins/ubi/ubi-aws-managed-services-tutorial.md b/i18n/zh/search-plugins/ubi/ubi-aws-managed-services-tutorial.md new file mode 100644 index 00000000..785dc6c8 --- /dev/null +++ b/i18n/zh/search-plugins/ubi/ubi-aws-managed-services-tutorial.md @@ -0,0 +1,287 @@ +--- +title: 在 Amazon OpenSearch Service 中收集 UBI 格式的数据 +--- + +# 在 Amazon OpenSearch Service 中收集 UBI 格式的数据 + +本教程向您展示如何在使用 Amazon OpenSearch Service 时以用户行为洞察(UBI)格式收集查询和事件。 + +::: warning IMPORTANT +原生 UBI 插件仅在开源 OpenSearch 发行版中可用,不是 Amazon OpenSearch Service 的一部分。如果您正在使用 OpenSearch Service 并希望实现 UBI 风格的数据收集,本教程演示了一种替代方法来实现这一点。 +::: + +完成本教程后,您将能够使用 `curl` 命令行工具将经过身份验证的查询和事件同时发送到 Amazon Simple Storage Service(Amazon S3)进行长期存储和 OpenSearch 进行实时处理。 + +本教程假设以下条件: + +1. 您正在使用 Amazon OpenSearch Service。 +2. 您没有使用 OpenSearch 的 UBI 插件。UBI 插件仅在开源版 OpenSearch 中可用,不包含在 Amazon OpenSearch Service 中。 +3. 您正在使用 [Amazon OpenSearch Ingestion](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/ingestion.html)(OpenSearch Data Prepper 的托管版本)将 UBI 数据写入 OpenSearch。 +4. 您已经按照[教程:使用 Amazon OpenSearch Ingestion 将数据摄取到域](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/osis-get-started.html)中的说明配置了 OpenSearch Ingestion 和您的托管集群之间的权限,特别是*必需权限*步骤。 + +## 步骤 1:为 UBI 设置 OpenSearch 索引 + +按照以下步骤创建 UBI 数据所需的索引: + +1. 登录到 Amazon OpenSearch Service 中的 OpenSearch Dashboards。 +1. 在主菜单上,选择**管理 > 开发工具**以打开**开发工具**控制台。 +1. 创建两个新索引:`ubi_events` 和 `ubi_queries`。 + + 1. 首先,开始为 `ubi_events` 索引创建映射: + + ```json + PUT /ubi_events + { + "mappings": + } + ``` + + 此时会出现语法警告。这是预期的;您接下来将输入映射。 + + 打开 [events-mapping.json](https://github.com/opensearch-project/user-behavior-insights/blob/main/src/main/resources/events-mapping.json) 文件,复制其内容,并将其粘贴到 `"mappings":` 行之后: + + ```json + PUT ubi_events + { + "mappings": { + "properties": { + "application": { + "type": "keyword", + "ignore_above": 256 + }, + "action_name": { + "type": "keyword", + "ignore_above": 100 + }, + ... + } + } + } + ``` + + 运行命令并验证其成功。 + + 1. 接下来,以类似方式创建 `ubi_queries` 索引。设置映射: + + ```json + PUT ubi_queries + { + "mappings": + } + ``` + + 打开 [queries-mapping.json](https://github.com/opensearch-project/user-behavior-insights/blob/main/src/main/resources/queries-mapping.json?utm_source=chatgpt.com) 文件,复制其内容,并将其粘贴到 `"mappings":` 行之后。运行命令并验证其成功。 + +## 步骤 2:设置 Amazon S3 存储 + +对于 UBI 数据的长期存储,请使用 Amazon S3。 + +在继续之前,创建一个存储查询和事件数据的 S3 存储桶。您可以在 AWS 管理控制台中执行此操作。记下存储桶名称和创建它的 AWS 区域;您将需要此信息用于以下步骤。 + +## 步骤 3:设置查询和事件摄取管道 + +按照以下步骤设置查询和事件摄取管道。 + +### 必需权限 + +要完成本教程,您的用户或角色必须附加具有以下最低权限的基于身份的策略。这些权限允许您创建管道角色并附加策略(`iam:Create*` 和 `iam:Attach*`)、创建或修改域(`es:*`)以及使用管道(`osis:*`): + +```json +{ + "Version":"2012-10-17", + "Statement":[ + { + "Effect":"Allow", + "Resource":"*", + "Action":[ + "osis:*", + "iam:Create*", + "iam:Attach*", + "es:*" + ] + }, + { + "Resource":[ + "arn:aws:iam::111122223333:role/OpenSearchIngestion-PipelineRole" + ], + "Effect":"Allow", + "Action":[ + "iam:CreateRole", + "iam:AttachRolePolicy", + "iam:PassRole" + ] + } + ] +} +``` + +您的 `DataPrepperOpenSearchRole` 必须具有类似于以下的权限: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "es:ESHttpPost", + "es:ESHttpPut", + "es:ESHttpGet", + "es:ESHttpHead" + ], + "Resource": "arn:aws:es:*:<YOUR_AWS_ACCOUNT_NUMBER>:*" + }, + { + "Effect": "Allow", + "Action": [ + "s3:PutObject" + ], + "Resource": "arn:aws:s3:::<YOUR-BUCKET>/*" + } + ] +} +``` + +### 步骤 3(a):创建查询管道 + +按照以下步骤为 UBI 查询数据创建管道: + +1. 在 Amazon OpenSearch Service 控制台中,从左侧导航窗格选择**管道**。 +1. 选择**创建管道**。 +1. 选择**空白**管道,然后选择**选择蓝图**。 +1. 配置管道以使用 **HTTP** 源插件,该插件接受 JSON 数组格式的 UBI 查询数据。将 OpenSearch Service 域设置为接收器,将所有数据定向到 `ubi_queries` 索引。此外,以 `.ndjson` 格式将所有事件记录到 S3 存储桶。 +1. 在**源**菜单中,选择 **HTTP**。对于**路径**,输入 `/ubi/queries`。 +1. 对于**源网络选项**,选择**公共访问**以允许从您的应用程序发布数据。 +1. 选择**下一步**。 +1. 在**处理器**屏幕上选择**下一步**跳过中间**处理器**步骤。 +1. 配置第一个接收器: + * 在**OpenSearch 资源类型**中,选择**托管集群**。 + * 选择您之前创建的 OpenSearch Service 域。 + * 在**索引名称**中,输入 `ubi_queries`。确保此索引存在并具有所需的 UBI 模式。 +1. 配置第二个接收器: + * 选择**添加接收器**。 + * 选择 **Amazon S3**。 + * 输入您之前创建的存储桶名称和 AWS 区域。 + * 在**事件收集超时**中,输入 `60s` 以快速观察数据流。 + * 选择 **NDJSON** 作为格式。 +1. 选择**下一步**。 +1. 将管道命名为 `ubi-queries-pipeline` 并保留容量设置的默认值。 +1. 选择**下一步**,然后选择**创建管道**。 + +### 步骤 3(b):测试查询管道 + +当管道状态为 `Active` 时,您可以开始向其摄取数据。您必须使用 [AWS 签名版本 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) 签署所有到管道的 HTTP 请求。使用 HTTP 工具(如 [Postman](https://www.getpostman.com/) 或 [`awscurl`](https://github.com/okigan/awscurl))向管道发送一些数据。与直接将数据索引到域一样,将数据摄取到管道始终需要 AWS Identity and Access Management (IAM) 角色或 [IAM 访问密钥和密钥](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html)。 + +要测试管道,请使用以下步骤: + +1. 从**管道设置**页面检索摄取 URL,如下图所示。 + + *管道设置* + +1. 将 UBI 查询发布到摄取管道。以下是使用 [`awscurl`](https://github.com/okigan/awscurl) 发布查询的示例: + + ```bash + awscurl --service osis --region us-east-1 \ + -X POST \ + -H "Content-Type: application/json" \ + -d '[{ + "query_response_id": "117d75fb-ea76-41dc-9d1d-1d7bba548bd8", + "user_query": "laptop", + "query_id": "d194b734-70a4-41dc-b103-b26a56a277b5", + "application": "Chorus", + "query_response_hit_ids": [ + "B076YX2LML", + "B07S3T59VP", + "B075ZGJSL1", + "B07FMGGRGG", + "B07KN5JP3H", + "B07FM8BNBC", + "B007OYLNGA", + "B07P75NDMB", + "B004HJ1ZB8", + "B01M69KU15", + "B072ZW6NBL", + "B07R7NL612", + "B083GH3L2N", + "B06XNQDR8J", + "B07ZQJQ4HV", + "B07YZHH5WY", + "B07F822FND", + "B004XAVT8K", + "B07F5JN761", + "B087RNZT41" + ], + "query_attributes": {}, + "client_id": "CLIENT-9a9968ac-664b-42d7-9a9e-96f412b5ab49", + "timestamp": "2025-01-23T13:18:22.274+0000" + }]' \ + https://ubi-queries-pipeline-il3g3pwe4ve4nov4bwhnzlrm4q.us-east-1.osis.amazonaws.com/ubi/queries + ``` + + 您应该收到 `200 OK` 响应。 + +1. 使用开发工具控制台查询您发布的事件数据。请注意,数据流经 OpenSearch Ingestion 进入 `ubi_queries` 索引可能需要一些时间: + + ```json + GET /ubi_queries/_search + { + "query": { + "match_all": {} + }, + "sort": [ + { "timestamp": { "order": "desc" } } + ] + } + ``` + + 如果您希望新写入的数据立即出现,请运行以下请求: + + ```json + POST /ubi_queries/_refresh + ``` + +### 步骤 3(c):创建事件管道 + +重复[步骤 3(a)](#步骤-3a创建查询管道) 为 UBI 事件数据设置管道。使用下表将特定于查询的值替换为其事件等效项。 + +| 设置 | 查询管道 | 事件管道 | +|--------------------------|------------------------|------------------------| +| 路径 | `/ubi/queries` | `/ubi/events` | +| 索引名称 | `ubi_queries` | `ubi_events` | +| 管道名称 | `ubi-queries-pipeline` | `ubi-events-pipeline` | +| S3 路径前缀模式 | `ubi_queries/` | `ubi_events/` | +| 开发工具搜索 | `GET ubi_queries/_search` | `GET ubi_events/_search` | +| 刷新命令 | `POST ubi_queries/_refresh` | `POST ubi_events/_refresh` | + +### 步骤 3(d):测试事件管道 + +按照[步骤 3(b)](#步骤-3b测试查询管道) 测试事件管道。以下是使用 [`awscurl`](https://github.com/okigan/awscurl) 发布查询的示例: + +```bash +awscurl --service osis --region us-east-1 \ + -X POST \ + -H "Content-Type: application/json" \ + -d '[ + { + "action_name": "product_hover", + "client_id": "CLIENT-9a9968ac-664b-42d7-9a9e-96f412b5ab49", + "query_id": "d194b734-70a4-41dc-b103-b26a56a277b5", + "page_id": "/", + "message_type": "INFO", + "message": "Integral 2GB SD Card memory card (undefined)", + "timestamp": 1724944081669, + "event_attributes": { + "object": { + "object_id_field": "product", + "object_id": "1625640", + "description": "Integral 2GB SD Card memory card", + "object_detail": null + } + } + } +] +' \ +https://ubi-events-pipeline-il3g3pwe4ve4nov4bwhnzlrm4q.us-east-1.osis.amazonaws.com/ubi/events +``` + +现在您已准备好开始为您的应用程序收集 UBI 数据了。 diff --git a/i18n/zh/search-plugins/ubi/ubi-dashboard-tutorial.md b/i18n/zh/search-plugins/ubi/ubi-dashboard-tutorial.md new file mode 100644 index 00000000..df0e50ad --- /dev/null +++ b/i18n/zh/search-plugins/ubi/ubi-dashboard-tutorial.md @@ -0,0 +1,86 @@ +--- +title: UBI 仪表板教程 +--- + +# UBI 仪表板教程 + +无论您是已经收集用户事件和查询一段时间了,还是[已上传了一些示例事件](https://github.com/o19s/chorus-OpenSearch-edition/blob/main/katas/003_import_preexisting_event_data.md),您现在已准备好在 OpenSearch 的仪表板中可视化通过用户行为洞察(UBI)收集的数据。 + +> 本教程是学习如何制作自定义仪表板的好方法。 + +要快速查看仪表板而不完成完整教程,请执行以下操作: +1. 下载并保存[示例 UBI 仪表板](/assets/examples/ubi-dashboard.ndjson)。 +1. 在顶部菜单上,转到**管理 > 仪表板管理**。 +1. 在**仪表板**面板中,选择**已保存对象**。 +1. 在右上角,选择**导入**。 +1. 在**选择文件**面板中,选择**导入**。 +1. 选择您下载的 UBI 仪表板文件,然后选择**导入**按钮。 + +## 1. 启动 OpenSearch Dashboards + +启动 OpenSearch Dashboards。例如,转到 `http://{server}:5601/app/home#/`。有关更多信息,请参阅 [OpenSearch Dashboards](/dashboards/)。下图显示了主页。 +*仪表板主页* + +## 2. 创建索引模式 + +在 OpenSearch 管理中,导航到**仪表板管理 > 索引模式**或使用 URL 导航,如 `http://{server}:5601/app/management/OpenSearch-dashboards/indexPatterns`。 + +OpenSearch Dashboards 使用索引模式访问您的索引。要可视化用户的在线搜索行为,您必须创建索引模式以访问 UBI 创建的索引。有关更多信息,请参阅[索引模式](/dashboards/management/index-patterns)。 + +选择**创建索引模式**后,将显示 OpenSearch 实例中的索引列表。UBI 存储可能默认隐藏,因此请确保选择**包含系统和隐藏索引**,如下图所示。 +*索引模式* + +您可以使用通配符将索引分组到仪表板的同一数据源中。对于本教程,您将把查询和事件存储组合成 `ubi_*` 模式。 + +OpenSearch Dashboards 会提示您过滤模式中的任何 `date` 字段,以便您可以查看过去 15 分钟内的热门查询等内容。但是,对于您的第一个仪表板,请选择**我不想使用时间过滤器**,如下图所示。 +*索引模式* + +选择**创建索引模式**后,您就可以开始构建显示 UBI 存储数据的仪表板了。 + +## 3. 创建新仪表板 + +要创建新仪表板,请在顶部菜单上选择 **OpenSearch Dashboards > 仪表板**,然后选择**创建 > 仪表板** > **新建**。 +如果您之前没有创建过仪表板,您将看到创建新仪表板的选项。否则,将显示之前创建的仪表板。 + +在**新建可视化**窗口中,选择**饼图**以创建新的饼图。然后选择您在步骤 2 中创建的索引模式。 + +大多数可视化需要对桶/分面/可聚合字段(数字或关键字)进行某种聚合函数。您将向 `action_name` 字段添加 `Terms` 聚合,以便查看事件名称的分布。将**大小**更改为要显示的切片数量,如下图所示。 +*饼图* + +保存可视化,使其添加到您的新仪表板中。现在您的仪表板上显示了一个可视化,您可以保存仪表板。 + +## 4. 添加标签云可视化 + +现在您将添加一个用于热门搜索的词云,方法与上一步类似创建新可视化。 + +在**新建可视化**窗口中,选择**标签云**,然后选择您在步骤 2 中创建的索引模式。选择 `message` 字段中术语的标签云可视化,JavaScript 客户端在此字段中记录原始搜索文本。注意:由 OpenSearch 处理的真正查询(包括过滤器、提升等)位于 `ubi_queries` 索引中。但是,您将查看 `ubi_events` 索引的 `message` 字段,JavaScript 客户端在其中捕获用户实际输入的文本。 + +下图显示了 `message` 字段上的标签云可视化。 +*词云* + +::: info NOTE +底层查询可以在 [SQL 热门查询](/search-plugins/ubi/sql-queries#trending-queries)中找到。 +::: + +生成的可视化可能包含与您要查找的不同的信息。`message` 字段随每个事件更新,因此它可能包含错误消息、调试消息、点击信息和其他不需要的数据。 +要仅查看查询事件的搜索词,您需要向可视化添加过滤器。因为在设置期间您为每个搜索事件提供了 `message_type` 为 `QUERY`,您可以按该消息类型过滤以隔离特定用户的搜索。为此,请选择**添加过滤器**,然后在**编辑过滤器**面板中选择 **QUERY**,如下图所示。 +*词云* + +现在您的仪表板上应该显示两个可视化(饼图和标签云),如下图所示。 +*UBI 仪表板* + +## 5. 添加项目点击直方图 + +现在您将向仪表板添加直方图可视化,方法与上一步类似。在**新建可视化**窗口中,选择**垂直条形图**。然后选择您在步骤 2 中创建的索引模式。 + +检查 `event_attributes.position.ordinal` 数据字段。此字段包含用户选择的项目在列表中的位置。对于直方图可视化,x 轴表示所选项目的序号(n)。y 轴表示第 n 个项目被点击的次数,如下图所示。 + +*垂直条形图* + +## 6. 过滤显示的数据 + +现在您可以进一步过滤显示的数据。例如,您可以查看购买发生时点击位置的变化。选择**添加过滤器**,然后选择 `action_name:product_purchase` 字段,如下图所示。 +*产品购买* + +您可以通过添加通配符来过滤包含单词 `*laptop*` 的事件消息,如下图所示。 +*笔记本电脑*。 diff --git a/i18n/zh/search-plugins/ubi/ubi-javascript-collector.md b/i18n/zh/search-plugins/ubi/ubi-javascript-collector.md new file mode 100644 index 00000000..86bf6b55 --- /dev/null +++ b/i18n/zh/search-plugins/ubi/ubi-javascript-collector.md @@ -0,0 +1,114 @@ +--- +title: UBI JavaScript 收集器 +--- + +# 如何使用 UBI JavaScript 收集器 + +UBI 附带一个非常基础的 JavaScript 客户端,用于管理特定搜索的 `query_id` 生命周期,并可以创建 UBI 事件数据结构并为特定操作存储它们。 + +有关模式的更多信息,请参阅 [UBI 索引模式](/search-plugins/ubi/schemas)。 + +我们建议使用客户端作为起点来满足您的特定需求。 + +## 安装 + +客户端是一个单独的文件([ubi.js](https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js)),仅依赖于 `axios` 库。 +<!-- vale off --> +从 [https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js](https://github.com/opensearch-project/user-behavior-insights/tree/main/ubi-javascript-collector/ubi.js) 下载。 +<!-- vale on --> + +要引用事件并创建客户端,请使用以下代码: + +```js +import { UbiEvent } from './ubi'; +import { UbiEventAttributes } from './ubi' +import { UbiClient } from './ubi' + +const ubiClient = new UbiClient('http://localhost:9200'); +``` + +## 创建事件 + +以下代码跟踪在电子商务应用程序中将商品添加到购物车。它使用 `UbiEvent` 和 `UbiEventAttributes` 类来封装事件详情,然后可以发送到跟踪系统: +```js +var event = new UbiEvent( + 'add_to_cart', + client_id, + session_id, + getQueryId(), + new UbiEventAttributes('product', item.primary_ean, item.title, item), + item.title + ' (' + item.id + ')' +); +``` + +### 参数 + +1. **事件名称**: + - `'add_to_cart'` -- 此字符串表示正在跟踪的事件类型。 + +2. **客户端 ID**: + - `client_id` -- 保存客户端唯一标识符的变量。这有助于区分不同的用户或会话。 + +3. **会话 ID**: + - `session_id` -- 包含用户会话唯一标识符的变量。这用于跟踪特定会话内的用户交互。 + +4. **查询 ID**: + - `getQueryId()` -- 检索当前查询 ID 的函数调用,它可能代表特定的搜索或交互上下文。 + +5. **UbiEventAttributes**: + - 这是 `UbiEventAttributes` 类的实例,它封装了关于事件的额外详情: + - **类型**: + - `'product'` -- 指定属性类型与产品相关。 + - **主 EAN**: + - `item.primary_ean` -- 产品的 EAN 格式唯一标识符。 + - **标题**: + - `item.title` -- 产品的名称或描述。 + - **商品**: + - `item` -- 包含所有相关详情的完整产品对象。 + +6. **事件标签**: + - `item.title + ' (' + item.id + ')'` -- 这创建了一个描述性标签,包含产品标题及其唯一标识符(ID)。 + +方法 `getQueryId()` 指的是一个辅助方法,它生成唯一的查询 ID(并将其存储在会话中)。 +以下是一个示例方法: + +```js +function generateQueryId(){ + const query_id = generateGuid(); + sessionStorage.setItem('query_id', query_id); + return query_id; +} + +function generateGuid() { + let id = ''; + try{ + id = crypto.randomUUID(); + } + catch(error){ + // crypto.randomUUID 仅在 https 上下文中工作,不在 http 上下文中,因此回退。 + id ='10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c => + (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) + ); + } + return id; +}; +``` + +## 跟踪事件 + +您可以通过调用 `trackEvent` 方法将事件发送到后端: + +```js +ubiClient.trackEvent(event); +``` + +## 跟踪查询 + +您可以选择使用客户端跟踪查询(而不是使用 OpenSearch 的 UBI 插件)。 + +代码类似于跟踪事件使用的代码: + +```js +const query = new UbiQuery(APPLICATION, client_id, query_id, value, "_id", {}); +ubiClient.trackQuery(query) +``` diff --git a/i18n/zh/security-analytics/log-types-reference/ad-ldap.md b/i18n/zh/security-analytics/log-types-reference/ad-ldap.md new file mode 100644 index 00000000..d69a5c78 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/ad-ldap.md @@ -0,0 +1,111 @@ +--- +title: AD LDAP +--- + +# AD LDAP 日志类型 + +`ad_ldap` 日志类型跟踪 Active Directory 日志,例如: + +- 轻量级目录访问协议(LDAP)查询。 +- 来自 LDAP 服务器的错误。 +- 超时事件。 +- 不安全的 LDAP 绑定。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"TargetUserName", + "ecs":"azure.signinlogs.properties.user_id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"Category", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"OperationName", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ModifiedProperties_NewValue", + "ecs":"modified_properties.new_value" + }, + { + "raw_field":"ResourceProviderValue", + "ecs":"azure.resource.provider" + }, + { + "raw_field":"conditionalAccessStatus", + "ecs":"azure.signinlogs.properties.conditional_access_status" + }, + { + "raw_field":"SearchFilter", + "ecs":"SearchFilter" + }, + { + "raw_field":"Operation", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResultType", + "ecs":"azure.platformlogs.result_type" + }, + { + "raw_field":"DeviceDetail_isCompliant", + "ecs":"azure.signinlogs.properties.device_detail.is_compliant" + }, + { + "raw_field":"ResourceDisplayName", + "ecs":"resource_display_name" + }, + { + "raw_field":"AuthenticationRequirement", + "ecs":"azure.signinlogs.properties.authentication_requirement" + }, + { + "raw_field":"TargetResources", + "ecs":"target_resources" + }, + { + "raw_field":"Workload", + "ecs":"workload" + }, + { + "raw_field":"DeviceDetail.deviceId", + "ecs":"azure.signinlogs.properties.device_detail.device_id" + }, + { + "raw_field":"OperationNameValue", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResourceId", + "ecs":"azure.signinlogs.properties.resource_id" + }, + { + "raw_field":"ResultDescription", + "ecs":"azure.signinlogs.result_description" + }, + { + "raw_field":"EventID", + "ecs":"EventID" + }, + { + "raw_field":"NetworkLocationDetails", + "ecs":"azure.signinlogs.properties.network_location_details" + }, + { + "raw_field":"CategoryValue", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"ActivityDisplayName", + "ecs":"azure.auditlogs.properties.activity_display_name" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/apache-access.md b/i18n/zh/security-analytics/log-types-reference/apache-access.md new file mode 100644 index 00000000..abb35fad --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/apache-access.md @@ -0,0 +1,7 @@ +--- +title: Apache Access +--- + +# Apache Access 日志类型 + +`apache_access` 日志类型记录 Apache HTTP 服务器处理的所有请求的数据。它不包含 `raw_field` 或 `ecs` 映射。 diff --git a/i18n/zh/security-analytics/log-types-reference/azure.md b/i18n/zh/security-analytics/log-types-reference/azure.md new file mode 100644 index 00000000..ca2ac69d --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/azure.md @@ -0,0 +1,222 @@ +--- +title: Azure +--- + +# Azure 日志类型 + +`azure` 日志类型监控由 Azure 云服务管理的云应用程序的日志数据。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json +"mappings": [ + { + "raw_field":"Resultdescription", + "ecs":"azure.signinlogs.result_description" + }, + { + "raw_field":"eventSource", + "ecs":"eventSource" + }, + { + "raw_field":"eventName", + "ecs":"eventName" + }, + { + "raw_field":"Status", + "ecs":"azure.platformlogs.status" + }, + { + "raw_field":"LoggedByService", + "ecs":"azure.auditlogs.properties.logged_by_service" + }, + { + "raw_field":"properties_message", + "ecs":"properties_message" + }, + { + "raw_field":"status", + "ecs":"azure.platformlogs.status" + }, + { + "raw_field":"TargetUserName", + "ecs":"azure.signinlogs.properties.user_id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"Category", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"OperationName", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ModifiedProperties_NewValue", + "ecs":"modified_properties.new_value" + }, + { + "raw_field":"ResourceProviderValue", + "ecs":"azure.resource.provider" + }, + { + "raw_field":"conditionalAccessStatus", + "ecs":"azure.signinlogs.properties.conditional_access_status" + }, + { + "raw_field":"SearchFilter", + "ecs":"search_filter" + }, + { + "raw_field":"Operation", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResultType", + "ecs":"azure.platformlogs.result_type" + }, + { + "raw_field":"DeviceDetail_isCompliant", + "ecs":"azure.signinlogs.properties.device_detail.is_compliant" + }, + { + "raw_field":"ResourceDisplayName", + "ecs":"resource_display_name" + }, + { + "raw_field":"AuthenticationRequirement", + "ecs":"azure.signinlogs.properties.authentication_requirement" + }, + { + "raw_field":"TargetResources", + "ecs":"target_resources" + }, + { + "raw_field":"Workload", + "ecs":"Workload" + }, + { + "raw_field":"DeviceDetail_deviceId", + "ecs":"azure.signinlogs.properties.device_detail.device_id" + }, + { + "raw_field":"OperationNameValue", + "ecs":"azure.platformlogs.operation_name" + }, + { + "raw_field":"ResourceId", + "ecs":"azure.signinlogs.properties.resource_id" + }, + { + "raw_field":"ResultDescription", + "ecs":"azure.signinlogs.result_description" + }, + { + "raw_field":"EventID", + "ecs":"EventID" + }, + { + "raw_field":"NetworkLocationDetails", + "ecs":"azure.signinlogs.properties.network_location_details" + }, + { + "raw_field":"CategoryValue", + "ecs":"azure.activitylogs.category" + }, + { + "raw_field":"ActivityDisplayName", + "ecs":"azure.auditlogs.properties.activity_display_name" + }, + { + "raw_field":"Initiatedby", + "ecs":"azure.activitylogs.identity.claims_initiated_by_user.name" + }, + { + "raw_field":"Count", + "ecs":"Count" + }, + { + "raw_field":"ResourceTenantId", + "ecs":"azure.signinlogs.properties.resource_tenant_id" + }, + { + "raw_field":"failure_status_reason", + "ecs":"failure_status_reason" + }, + { + "raw_field":"AppId", + "ecs":"azure.signinlogs.properties.app_id" + }, + { + "raw_field":"properties.message", + "ecs":"properties.message" + }, + { + "raw_field":"ClientApp", + "ecs":"azure.signinlogs.properties.client_app_used" + }, + { + "raw_field":"ActivityDetails", + "ecs":"ActivityDetails" + }, + { + "raw_field":"Target", + "ecs":"Target" + }, + { + "raw_field":"DeviceDetail.trusttype", + "ecs":"azure.signinlogs.properties.device_detail.trust_type" + }, + { + "raw_field":"HomeTenantId", + "ecs":"azure.signinlogs.properties.home_tenant_id" + }, + { + "raw_field":"ConsentContext.IsAdminConsent", + "ecs":"ConsentContext.IsAdminConsent" + }, + { + "raw_field":"InitiatedBy", + "ecs":"InitiatedBy" + }, + { + "raw_field":"ActivityType", + "ecs":"azure.auditlogs.properties.activity_display_name" + }, + { + "raw_field":"operationName", + "ecs":"azure.activitylogs.operation_name" + }, + { + "raw_field":"ModifiedProperties{}.NewValue", + "ecs":"modified_properties.new_value" + }, + { + "raw_field":"userAgent", + "ecs":"user_agent.name" + }, + { + "raw_field":"RiskState", + "ecs":"azure.signinlogs.properties.risk_state" + }, + { + "raw_field":"Username", + "ecs":"azure.activitylogs.identity.claims_initiated_by_user.name" + }, + { + "raw_field":"DeviceDetail.deviceId", + "ecs":"azure.signinlogs.properties.device_detail.device_id" + }, + { + "raw_field":"DeviceDetail.isCompliant", + "ecs":"azure.signinlogs.properties.device_detail.is_compliant" + }, + { + "raw_field":"Location", + "ecs":"azure.signinlogs.properties.network_location_details" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/cloudtrail.md b/i18n/zh/security-analytics/log-types-reference/cloudtrail.md new file mode 100644 index 00000000..71f22fb8 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/cloudtrail.md @@ -0,0 +1,229 @@ +--- +title: AWS CloudTrail +--- + +# AWS CloudTrail 日志类型 + +`cloudtrail` 日志类型监控来自 [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 账户的事件。OpenSearch 可以从 [Amazon Simple Storage Service](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)(Amazon S3)账户和 [Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/what-is-security-lake.html) 账户中提取 AWS CloudTrail 日志数据。 + +以下代码片段包含此日志类型的所有 `raw_field`、`ecs` 和 `ocsf` 映射: + +```json + "mappings": [ + { + "raw_field":"eventName", + "ecs":"aws.cloudtrail.event_name", + "ocsf": "api.operation" + }, + { + "raw_field":"eventSource", + "ecs":"aws.cloudtrail.event_source", + "ocsf": "api.service.name" + }, + { + "raw_field":"eventVersion", + "ecs":"aws.cloudtrail.event_version", + "ocsf": "metadata.product.version" + }, + { + "raw_field":"eventID", + "ecs":"aws.cloudtrail.event_id", + "ocsf": "metadata.uid" + }, + { + "raw_field":"eventType", + "ecs":"aws.cloudtrail.event_type", + "ocsf": "unmapped.eventType" + }, + { + "raw_field":"eventCategory", + "ecs":"aws.cloudtrail.event_category", + "ocsf": "metadata.product.feature.name" + }, + { + "raw_field":"errorMessage", + "ecs":"aws.cloudtrail.error_message", + "ocsf": "api.response.message" + }, + { + "raw_field":"errorCode", + "ecs":"aws.cloudtrail.error_code", + "ocsf": "api.response.error" + }, + { + "raw_field":"apiVersion", + "ecs":"aws.cloudtrail.api_version", + "ocsf": "api.version" + }, + { + "raw_field":"awsRegion", + "ecs":"aws.cloudtrail.aws_region", + "ocsf": "cloud.region" + }, + { + "raw_field":"additionalEventData.LoginTo", + "ecs":"aws.cloudtrail.additional_event_data.loginTo", + "ocsf": "dst_endpoint.svc_name" + }, + { + "raw_field":"additionalEventData.MFAUsed", + "ecs":"aws.cloudtrail.additional_event_data.mfaUsed", + "ocsf": "mfa" + }, + { + "raw_field":"responseElements", + "ecs":"aws.cloudtrail.response_elements.text", + "ocsf": "unmapped.responseElements" + }, + { + "raw_field":"requestID", + "ecs":"aws.cloudtrail.request_id", + "ocsf": "api.request.uid" + }, + { + "raw_field":"sourceIPAddress", + "ecs":"aws.cloudtrail.source_ip_address", + "ocsf": "src_endpoint.ip" + }, + { + "raw_field":"userAgent", + "ecs":"aws.cloudtrail.user_agent", + "ocsf": "http_request.user_agent" + }, + { + "raw_field":"vpcEndpointId", + "ecs":"aws.cloudtrail.vpc_endpoint_id", + "ocsf": "src_endpoint.uid" + }, + { + "raw_field":"responseElements.pendingModifiedValues.masterUserPassword", + "ecs":"aws.cloudtrail.response_elements.pending_modified_values.master_user_password", + "ocsf": "unmapped.responseElements.pendingModifiedValues.masterUserPassword" + }, + { + "raw_field":"responseElements.publiclyAccessible", + "ecs":"aws.cloudtrail.response_elements.publicly_accessible", + "ocsf": "unmapped.responseElements.publiclyAccessible" + }, + { + "raw_field":"responseElements.ConsoleLogin", + "ecs":"aws.cloudtrail.response_elements.publicly_accessible", + "ocsf": "status_id" + }, + { + "raw_field":"requestParameters.arn", + "ecs":"aws.cloudtrail.request_parameters.arn", + "ocsf": "unmapped.requestParameters.arn" + }, + { + "raw_field":"requestParameters.attribute", + "ecs":"aws.cloudtrail.request_parameters.attribute", + "ocsf": "unmapped.requestParameters.attribute" + }, + { + "raw_field":"requestParameters.userName", + "ecs":"aws.cloudtrail.request_parameters.username", + "ocsf": "unmapped.requestParameters.userName" + }, + { + "raw_field":"requestParameters.roleArn", + "ecs":"aws.cloudtrail.request_parameters.roleArn", + "ocsf": "user.uuid" + }, + { + "raw_field":"requestParameters.roleSessionName", + "ecs":"aws.cloudtrail.request_parameters.roleSessionName", + "ocsf": "user.name" + }, + { + "raw_field":"requestParameters.containerDefinitions.command", + "ecs":"aws.cloudtrail.request_parameters.container_definitions.command", + "ocsf": "unmapped.requestParameters.containerDefinitions.command" + }, + { + "raw_field":"userIdentity.type", + "ecs":"aws.cloudtrail.user_identity.type", + "ocsf": "actor.user.type" + }, + { + "raw_field":"userIdentity.principalId", + "ecs":"aws.cloudtrail.user_identity.principalId", + "ocsf": "actor.user.uid" + }, + { + "raw_field":"userIdentity.arn", + "ecs":"aws.cloudtrail.user_identity.arn", + "ocsf": "actor.user.uuid" + }, + { + "raw_field":"userIdentity.accountId", + "ecs":"aws.cloudtrail.user_identity.accountId", + "ocsf": "actor.user.account_uid" + }, + { + "raw_field":"userIdentity.accessKeyId", + "ecs":"aws.cloudtrail.user_identity.accessKeyId", + "ocsf": "actor.user.credential_uid" + }, + { + "raw_field":"userIdentity.identityProvider", + "ecs":"aws.cloudtrail.user_identity.identityProvider", + "ocsf": "actor.idp.name" + }, + { + "raw_field":"userIdentity.userName", + "ecs":"aws.cloudtrail.user_identity.userName", + "ocsf": "actor.user.name" + }, + { + "raw_field":"userIdentity.invokedBy", + "ecs":"aws.cloudtrail.user_identity.invokedBy", + "ocsf": "actor.invoked_by" + }, + { + "raw_field":"userIdentity.sessionContext.sessionIssuer.type", + "ecs":"aws.cloudtrail.user_identity.session_context.session_issuer.type", + "ocsf": "unmapped.userIdentity.sessionContext.sessionIssuer.type" + }, + { + "raw_field":"userIdentity.sessionContext.sessionIssuer.arn", + "ecs":"aws.cloudtrail.user_identity.session_context.session_issuer.arn", + "ocsf": "actor.session.issuer" + }, + { + "raw_field":"userIdentity.sessionContext.attributes.creationDate", + "ecs":"aws.cloudtrail.user_identity.session_context.attributes.creationDate", + "ocsf": "actor.session.created_time" + }, + { + "raw_field":"userIdentity.sessionContext.attributes.mfaAuthenticated", + "ecs":"aws.cloudtrail.user_identity.session_context.attributes.mfaAuthenticated", + "ocsf": "actor.session.mfa" + }, + { + "raw_field":"userIdentity.webIdFederationData.federatedProvider", + "ecs":"aws.cloudtrail.user_identity.web_id_federation_data.federatedProvider", + "ocsf": "actor.idp.name" + }, + { + "raw_field":"resources[].ARN", + "ecs":"aws.cloudtrail.resources.ARN", + "ocsf": "resources[].uid" + }, + { + "raw_field":"resources[].accountId", + "ecs":"aws.cloudtrail.resources.account_uid", + "ocsf": "resources[].account_uid" + }, + { + "raw_field":"resources[].type", + "ecs":"aws.cloudtrail.resources.type", + "ocsf": "resources[].type" + }, + { + "raw_field":"eventTime", + "ecs":"timestamp", + "ocsf": "time" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/dns.md b/i18n/zh/security-analytics/log-types-reference/dns.md new file mode 100644 index 00000000..d00235a0 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/dns.md @@ -0,0 +1,124 @@ +--- +title: DNS +--- + +# DNS 日志类型 + +`dns` 日志类型存储 DNS 活动。 + +以下代码片段包含此日志类型的所有 `raw_field`、`ecs` 和 `ocsf` 映射: + +```json + "mappings": [ + { + "raw_field":"record_type", + "ecs":"dns.answers.type", + "ocsf": "unmapped.record_type" + }, + { + "raw_field":"answers[].Type", + "ecs":"aws.route53.answers.Type", + "ocsf": "answers[].type" + }, + { + "raw_field":"answers[].Rdata", + "ecs":"aws.route53.answers.Rdata", + "ocsf": "answers[].rdata" + }, + { + "raw_field":"answers[].Class", + "ecs":"aws.route53.answers.Class", + "ocsf": "answers[].class" + }, + { + "raw_field":"query", + "ecs":"dns.question.name", + "ocsf": "unmapped.query" + }, + { + "raw_field":"query_name", + "ecs":"aws.route53.query_name", + "ocsf": "query.hostname" + }, + { + "raw_field":"parent_domain", + "ecs":"dns.question.registered_domain", + "ocsf": "unmapped.parent_domain" + }, + { + "raw_field":"version", + "ecs":"aws.route53.version", + "ocsf": "metadata.product.version" + }, + { + "raw_field":"account_id", + "ecs":"aws.route53.account_id", + "ocsf": "cloud.account_uid" + }, + { + "raw_field":"region", + "ecs":"aws.route53.region", + "ocsf": "cloud.region" + }, + { + "raw_field":"vpc_id", + "ecs":"aws.route53.vpc_id", + "ocsf": "src_endpoint.vpc_uid" + }, + { + "raw_field":"query_timestamp", + "ecs":"aws.route53.query_timestamp", + "ocsf": "time" + }, + { + "raw_field":"query_class", + "ecs":"aws.route53.query_class", + "ocsf": "query.class" + }, + { + "raw_field":"query_type", + "ecs":"aws.route53.query_type", + "ocsf": "query.type" + }, + { + "raw_field":"srcaddr", + "ecs":"aws.route53.srcaddr", + "ocsf": "src_endpoint.ip" + }, + { + "raw_field":"srcport", + "ecs":"aws.route53.srcport", + "ocsf": "src_endpoint.port" + }, + { + "raw_field":"transport", + "ecs":"aws.route53.transport", + "ocsf": "connection_info.protocol_name" + }, + { + "raw_field":"srcids.instance", + "ecs":"aws.route53.srcids.instance", + "ocsf": "src_endpoint.instance_uid" + }, + { + "raw_field":"srcids.resolver_endpoint", + "ecs":"aws.route53.srcids.resolver_endpoint", + "ocsf": "dst_endpoint.instance_uid" + }, + { + "raw_field":"srcids.resolver_network_interface", + "ecs":"aws.route53.srcids.resolver_network_interface", + "ocsf": "dst_endpoint.interface_uid" + }, + { + "raw_field":"firewall_rule_action", + "ecs":"aws.route53.srcids.firewall_rule_action", + "ocsf": "disposition_id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp", + "ocsf": "unmapped.creationTime" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/github.md b/i18n/zh/security-analytics/log-types-reference/github.md new file mode 100644 index 00000000..c12d2be9 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/github.md @@ -0,0 +1,18 @@ +--- +title: GitHub +--- + +# GitHub 日志类型 + +`github` 日志类型监控由 [GitHub Actions](https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions) 创建的工作流。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"action", + "ecs":"github.action" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/gworkspace.md b/i18n/zh/security-analytics/log-types-reference/gworkspace.md new file mode 100644 index 00000000..83069534 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/gworkspace.md @@ -0,0 +1,30 @@ +--- +title: Google Workspace +--- + +# Google Workspace 日志类型 + +`gworkspace` 日志类型监控 Google Workspace 日志条目,例如以下内容: + +- 管理员操作 +- 组和组成员资格操作 +- 与登录相关的事件 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"eventSource", + "ecs":"google_workspace.admin.service.name" + }, + { + "raw_field":"eventName", + "ecs":"google_workspace.event.name" + }, + { + "raw_field":"new_value", + "ecs":"google_workspace.admin.new_value" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/index.md b/i18n/zh/security-analytics/log-types-reference/index.md new file mode 100644 index 00000000..d200feeb --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/index.md @@ -0,0 +1,11 @@ +--- +title: 支持的日志类型 +--- + +# 支持的日志类型 + +日志包含关于系统中发生的事件及其各个部分的原始数据。本参考描述了安全分析支持的标准日志类型以及它们包含的自动映射。 + +有关字段映射的更多信息,请参阅[使用日志类型](/security-analytics/sec-analytics-config/log-types)文档中的[关于字段映射](/security-analytics/sec-analytics-config/log-types#about-field-mappings)部分。 + +有关日志类型和检测器的更多信息,请参阅[创建检测器](/security-analytics/sec-analytics-config/detectors-config)文档。 diff --git a/i18n/zh/security-analytics/log-types-reference/linux.md b/i18n/zh/security-analytics/log-types-reference/linux.md new file mode 100644 index 00000000..062bf6ee --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/linux.md @@ -0,0 +1,70 @@ +--- +title: Linux +--- + +# Linux 日志类型 + +`linux` 日志类型记录 Linux syslog 事件。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"name", + "ecs":"user.filesystem.name" + }, + { + "raw_field":"a0", + "ecs":"auditd.log.a0" + }, + { + "raw_field":"comm", + "ecs":"auditd.log.comm" + }, + { + "raw_field":"exe", + "ecs":"auditd.log.exe" + }, + { + "raw_field":"uid", + "ecs":"auditd.log.uid" + }, + { + "raw_field":"USER", + "ecs":"system.auth.user" + }, + { + "raw_field":"User", + "ecs":"system.auth.user" + }, + { + "raw_field":"Image", + "ecs":"process.exe" + }, + { + "raw_field":"DestinationHostname", + "ecs":"rsa.web.remote_domain" + }, + { + "raw_field":"CommandLine", + "ecs":"process.command_line" + }, + { + "raw_field":"ParentImage", + "ecs":"process.parent.executable" + }, + { + "raw_field":"CurrentDirectory", + "ecs":"process.working_directory" + }, + { + "raw_field":"LogonId", + "ecs":"process.real_user.id" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/m365.md b/i18n/zh/security-analytics/log-types-reference/m365.md new file mode 100644 index 00000000..d515135a --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/m365.md @@ -0,0 +1,36 @@ +--- +title: Microsoft 365 +--- + +# Microsoft 365 日志类型 + +`m365` 日志类型收集 Microsoft 365 的一系列数据,例如以下内容: + +- 通话详情记录 +- 性能数据 +- SQL Server 事件 +- 安全事件 +- 访问控制活动 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json +"mappings": [ + { + "raw_field":"eventSource", + "ecs":"rsa.misc.event_source" + }, + { + "raw_field":"eventName", + "ecs":"rsa.misc.event_desc" + }, + { + "raw_field":"status", + "ecs":"rsa.misc.status" + }, + { + "raw_field":"Payload", + "ecs":"rsa.misc.payload_dst" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/netflow.md b/i18n/zh/security-analytics/log-types-reference/netflow.md new file mode 100644 index 00000000..6ee2b6d5 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/netflow.md @@ -0,0 +1,42 @@ +--- +title: NetFlow +--- + +# NetFlow 日志类型 + +`netflow` 日志类型记录集成测试期间使用的 NetFlow 事件。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json +"mappings": [ + { + "raw_field":"netflow.source_ipv4_address", + "ecs":"source.ip" + }, + { + "raw_field":"netflow.source_transport_port", + "ecs":"source.port" + }, + { + "raw_field":"netflow.destination_ipv4_address", + "ecs":"destination.ip" + }, + { + "raw_field":"netflow.destination_transport_port", + "ecs":"destination.port" + }, + { + "raw_field":"http.request.method", + "ecs":"http.request.method" + }, + { + "raw_field":"http.response.status_code", + "ecs":"http.response.status_code" + }, + { + "raw_field":"timestamp", + "ecs":"timestamp" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/network.md b/i18n/zh/security-analytics/log-types-reference/network.md new file mode 100644 index 00000000..adb3ddf4 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/network.md @@ -0,0 +1,142 @@ +--- +title: Network +--- + +# Network 日志类型 + +`network` 日志类型记录系统网络中发生的事件,例如登录尝试和应用程序事件。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"action", + "ecs":"netflow.firewall_event" + }, + { + "raw_field":"certificate.serial", + "ecs":"zeek.x509.certificate.serial" + }, + { + "raw_field":"name", + "ecs":"zeek.smb_files.name" + }, + { + "raw_field":"path", + "ecs":"zeek.smb_files.path" + }, + { + "raw_field":"dst_port", + "ecs":"destination.port" + }, + { + "raw_field":"qtype_name", + "ecs":"zeek.dns.qtype_name" + }, + { + "raw_field":"operation", + "ecs":"zeek.dce_rpc.operation" + }, + { + "raw_field":"endpoint", + "ecs":"zeek.dce_rpc.endpoint" + }, + { + "raw_field":"zeek.dce_rpc.endpoint", + "ecs":"zeek.dce_rpc.endpoint" + }, + { + "raw_field":"answers", + "ecs":"zeek.dns.answers" + }, + { + "raw_field":"query", + "ecs":"zeek.dns.query" + }, + { + "raw_field":"client_header_names", + "ecs":"zeek.http.client_header_names" + }, + { + "raw_field":"resp_mime_types", + "ecs":"zeek.http.resp_mime_types" + }, + { + "raw_field":"cipher", + "ecs":"zeek.kerberos.cipher" + }, + { + "raw_field":"request_type", + "ecs":"zeek.kerberos.request_type" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"method", + "ecs":"http.request.method" + }, + { + "raw_field":"id.resp_p", + "ecs":"id.resp_p" + }, + { + "raw_field":"blocked", + "ecs":"blocked-flag" + }, + { + "raw_field":"id.orig_h", + "ecs":"id.orig_h" + }, + { + "raw_field":"Z", + "ecs":"Z-flag" + }, + { + "raw_field":"id.resp_h", + "ecs":"id.resp_h" + }, + { + "raw_field":"uri", + "ecs":"url.path" + }, + { + "raw_field":"c-uri", + "ecs":"url.path" + }, + { + "raw_field":"c-useragent", + "ecs":"user_agent.name" + }, + { + "raw_field":"status_code", + "ecs":"http.response.status_code" + }, + { + "raw_field":"rejected", + "ecs":"rejected" + }, + { + "raw_field":"dst_ip", + "ecs":"destination.ip" + }, + { + "raw_field":"src_ip", + "ecs":"source.ip" + }, + { + "raw_field":"user_agent", + "ecs":"user_agent.name" + }, + { + "raw_field":"request_body_len", + "ecs":"http.request.body.bytes" + }, + { + "raw_field":"service", + "ecs":"service" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/okta.md b/i18n/zh/security-analytics/log-types-reference/okta.md new file mode 100644 index 00000000..9bfe2dfe --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/okta.md @@ -0,0 +1,22 @@ +--- +title: Okta +--- + +# Okta 日志类型 + +`okta` 日志类型记录从一系列操作生成的 Okta 事件,例如下载导出文件、请求应用程序访问或撤销权限。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"eventtype", + "ecs":"okta.event_type" + }, + { + "raw_field":"displaymessage", + "ecs":"okta.display_message" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/other.md b/i18n/zh/security-analytics/log-types-reference/other.md new file mode 100644 index 00000000..5f1a1ff2 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/other.md @@ -0,0 +1,37 @@ +--- +title: 其他日志类型映射 +--- + +# 其他日志类型映射 + +安全分析支持不特定于单个服务或系统的字段映射。这些映射类型分为以下类别: + +- Application:记录应用程序日志。 +- 高级持续性威胁(APT):记录通常与 APT 攻击相关的日志。 +- Compliance:记录与合规性相关的日志。 +- macOS:记录使用 Mac 设备访问网络时的事件日志。 +- Proxy:记录与代理事件相关的日志。 +- Web:记录与来自 Web 的网络访问相关的日志。 + +每种日志类型都包含相同的字段映射,如以下代码片段所示: + +```json + "mappings": [ + { + "raw_field":"record_type", + "ecs":"dns.answers.type" + }, + { + "raw_field":"query", + "ecs":"dns.question.name" + }, + { + "raw_field":"parent_domain", + "ecs":"dns.question.registered_domain" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/s3.md b/i18n/zh/security-analytics/log-types-reference/s3.md new file mode 100644 index 00000000..5d65eb12 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/s3.md @@ -0,0 +1,26 @@ +--- +title: Amazon S3 +--- + +# Amazon S3 日志类型 + +`s3` 日志类型跟踪访问 Amazon S3 存储桶的网络请求。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"eventName", + "ecs":"aws.cloudtrail.event_name" + }, + { + "raw_field":"eventSource", + "ecs":"aws.cloudtrail.event_source" + }, + { + "raw_field":"eventTime", + "ecs":"timestamp" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/vpc.md b/i18n/zh/security-analytics/log-types-reference/vpc.md new file mode 100644 index 00000000..b8e31927 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/vpc.md @@ -0,0 +1,141 @@ +--- +title: VPC Flow +--- + +<!-- vale off --> +# VPC Flow 日志类型 +<!-- vale on --> + +`vpcflow` 日志类型记录流入和流出虚拟私有云(VPC)内网络接口的 IP 流量的数据。此数据使用 [VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html) 功能存储。 + +以下代码片段包含此日志类型的所有 `raw_field`、`ecs` 和 `ocsf` 映射: + +```json + "mappings": [ + { + "raw_field":"version", + "ecs":"netflow.version", + "ocsf": "metadata.product.version" + }, + { + "raw_field":"account_id", + "ecs":"netflow.account_id", + "ocsf": "cloud.account_uid" + }, + { + "raw_field":"region", + "ecs":"netflow.region", + "ocsf": "cloud.region" + }, + { + "raw_field":"az_id", + "ecs":"netflow.az_id", + "ocsf": "cloud.zone" + }, + { + "raw_field":"srcport", + "ecs":"netflow.srcport", + "ocsf": "src_endpoint.port" + }, + { + "raw_field":"dstport", + "ecs":"netflow.dstport", + "ocsf": "dst_endpoint.port" + }, + { + "raw_field":"protocol", + "ecs":"netflow.protocol", + "ocsf": "connection_info.protocol_num" + }, + { + "raw_field":"packets", + "ecs":"netflow.packets", + "ocsf": "traffic.packets" + }, + { + "raw_field":"bytes", + "ecs":"netflow.bytes", + "ocsf": "traffic.bytes" + }, + { + "raw_field":"end", + "ecs":"netflow.end", + "ocsf": "end_time" + }, + { + "raw_field":"tcp_flags", + "ecs":"netflow.tcp_flags", + "ocsf": "connection_info.tcp_flags" + }, + { + "raw_field":"protocol_ver", + "ecs":"netflow.protocol_ver", + "ocsf": "connection_info.protocol_ver" + }, + { + "raw_field":"pkt_src_aws_service", + "ecs":"netflow.pkt_src_aws_service", + "ocsf": "src_endpoint.svc_name" + }, + { + "raw_field":"pkt_dst_aws_service", + "ecs":"netflow.pkt_dst_aws_service", + "ocsf": "dst_endpoint.svc_name" + }, + { + "raw_field":"log_status", + "ecs":"netflow.log_status", + "ocsf": "status_code" + }, + { + "raw_field":"action", + "ecs":"netflow.action", + "ocsf": "disposition_id" + }, + { + "raw_field":"traffic_path", + "ecs":"netflow.traffic_path", + "ocsf": "boundary_id" + }, + { + "raw_field":"flow_direction", + "ecs":"netflow.flow_direction", + "ocsf": "connection_info.direction_id" + }, + { + "raw_field":"dstaddr", + "ecs":"netflow.dstaddr", + "ocsf": "dst_endpoint.ip" + }, + { + "raw_field":"srcaddr", + "ecs":"netflow.srcaddr", + "ocsf": "src_endpoint.ip" + }, + { + "raw_field":"interface_id", + "ecs":"netflow.interface_id", + "ocsf": "dst_endpoint.interface_uid" + }, + { + "raw_field":"vpc_id", + "ecs":"netflow.vpc_id", + "ocsf": "dst_endpoint.vpc_uid" + }, + { + "raw_field":"instance_id", + "ecs":"netflow.instance_id", + "ocsf": "dst_endpoint.instance_uid" + }, + { + "raw_field":"subnet_id", + "ecs":"netflow.subnet_id", + "ocsf": "dst_endpoint.subnet_uid" + }, + { + "raw_field":"start", + "ecs":"timestamp", + "ocsf": "time" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/waf.md b/i18n/zh/security-analytics/log-types-reference/waf.md new file mode 100644 index 00000000..38d4c0a8 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/waf.md @@ -0,0 +1,62 @@ +--- +title: WAF +--- + +# WAF 日志类型 + +`waf` 日志类型监控 Web 应用程序防火墙(WAF)日志。WAF 的作用是监控和过滤在 Web 应用程序与互联网之间流动的 HTTP 流量。WAF 可以防止常见的安全攻击,例如跨站脚本(XSS)和 SQL 注入(SQLi)。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings": [ + { + "raw_field":"cs-method", + "ecs":"waf.request.method" + }, + { + "raw_field":"httpRequest.httpMethod", + "ecs":"waf.request.method" + }, + { + "raw_field":"cs-uri-query", + "ecs":"waf.request.uri_query" + }, + { + "raw_field":"httpRequest.uri", + "ecs":"waf.request.uri_query" + }, + { + "raw_field":"httpRequest.args", + "ecs":"waf.request.uri_query" + }, + { + "raw_field":"cs-user-agent", + "ecs":"waf.request.headers.user_agent" + }, + { + "raw_field":"httpRequest.headers", + "ecs":"waf.request.headers" + }, + { + "raw_field":"sc-status", + "ecs":"waf.response.code" + }, + { + "raw_field":"responseCodeSent", + "ecs":"waf.response.code" + }, + { + "raw_field":"timestamp", + "ecs":"timestamp" + }, + { + "raw_field":"httpRequest.headers.value", + "ecs":"waf.request.headers.value" + }, + { + "raw_field":"httpRequest.headers.name", + "ecs":"waf.request.headers.name" + } + ] +``` diff --git a/i18n/zh/security-analytics/log-types-reference/windows.md b/i18n/zh/security-analytics/log-types-reference/windows.md new file mode 100644 index 00000000..d08d9515 --- /dev/null +++ b/i18n/zh/security-analytics/log-types-reference/windows.md @@ -0,0 +1,842 @@ +--- +title: Windows +--- + +# Windows 日志类型 + +`windows` 日志类型记录 Windows 应用程序、系统服务和 Windows 操作系统中发生的事件。 + +以下代码片段包含此日志类型的所有 `raw_field` 和 `ecs` 映射: + +```json + "mappings":[ + { + "raw_field":"AccountName", + "ecs":"winlog.computerObject.name" + }, + { + "raw_field":"AuthenticationPackageName", + "ecs":"winlog.event_data.AuthenticationPackageName" + }, + { + "raw_field":"Channel", + "ecs":"winlog.channel" + }, + { + "raw_field":"Company", + "ecs":"winlog.event_data.Company" + }, + { + "raw_field":"ComputerName", + "ecs":"winlog.computer_name" + }, + { + "raw_field":"Description", + "ecs":"winlog.event_data.Description" + }, + { + "raw_field":"Details", + "ecs":"winlog.event_data.Detail" + }, + { + "raw_field":"Device", + "ecs":"winlog.event_data.Device" + }, + { + "raw_field":"FileName", + "ecs":"winlog.event_data.FileName" + }, + { + "raw_field":"FileVersion", + "ecs":"winlog.event_data.FileVersion" + }, + { + "raw_field":"IntegrityLevel", + "ecs":"winlog.event_data.IntegrityLevel" + }, + { + "raw_field":"IpAddress", + "ecs":"winlog.event_data.IpAddress" + }, + { + "raw_field":"KeyLength", + "ecs":"winlog.event_data.KeyLength" + }, + { + "raw_field":"Keywords", + "ecs":"winlog.keywords" + }, + { + "raw_field":"LogonId", + "ecs":"winlog.event_data.LogonId" + }, + { + "raw_field":"LogonProcessName", + "ecs":"winlog.event_data.LogonProcessName" + }, + { + "raw_field":"LogonType", + "ecs":"winlog.event_data.LogonType" + }, + { + "raw_field":"OriginalFilename", + "ecs":"winlog.event_data.OriginalFileName" + }, + { + "raw_field":"Path", + "ecs":"winlog.event_data.Path" + }, + { + "raw_field":"PrivilegeList", + "ecs":"winlog.event_data.PrivilegeList" + }, + { + "raw_field":"ProcessId", + "ecs":"winlog.event_data.ProcessId" + }, + { + "raw_field":"Product", + "ecs":"winlog.event_data.Product" + }, + { + "raw_field":"Provider", + "ecs":"winlog.provider_name" + }, + { + "raw_field":"ProviderName", + "ecs":"winlog.provider_name" + }, + { + "raw_field":"ScriptBlockText", + "ecs":"winlog.event_data.ScriptBlockText" + }, + { + "raw_field":"ServerName", + "ecs":"winlog.event_data.TargetServerName" + }, + { + "raw_field":"Service", + "ecs":"winlog.event_data.ServiceName" + }, + { + "raw_field":"Signed", + "ecs":"winlog.event_data.Signed" + }, + { + "raw_field":"State", + "ecs":"winlog.event_data.State" + }, + { + "raw_field":"Status", + "ecs":"winlog.event_data.Status" + }, + { + "raw_field":"SubjectDomainName", + "ecs":"winlog.event_data.SubjectDomainName" + }, + { + "raw_field":"SubjectLogonId", + "ecs":"winlog.event_data.SubjectLogonId" + }, + { + "raw_field":"SubjectUserName", + "ecs":"winlog.event_data.SubjectUserName" + }, + { + "raw_field":"SubjectUserSid", + "ecs":"winlog.event_data.SubjectUserSid" + }, + { + "raw_field":"TargetLogonId", + "ecs":"winlog.event_data.TargetLogonId" + }, + { + "raw_field":"TargetName", + "ecs":"winlog.event_data.TargetUserName" + }, + { + "raw_field":"TargetServerName", + "ecs":"winlog.event_data.TargetServerName" + }, + { + "raw_field":"TargetUserName", + "ecs":"winlog.event_data.TargetUserName" + }, + { + "raw_field":"TargetUserSid", + "ecs":"winlog.event_data.TargetUserSid" + }, + { + "raw_field":"TaskName", + "ecs":"winlog.task" + }, + { + "raw_field":"Type", + "ecs":"winlog.user.type" + }, + { + "raw_field":"User", + "ecs":"winlog.user.name" + }, + { + "raw_field":"UserName", + "ecs":"winlog.user.name" + }, + { + "raw_field":"Workstation", + "ecs":"winlog.event_data.Workstation" + }, + { + "raw_field":"WorkstationName", + "ecs":"winlog.event_data.Workstation" + }, + { + "raw_field":"event_uid", + "ecs":"winlog.event_id" + }, + { + "raw_field":"CommandLine", + "ecs":"process.command_line" + }, + { + "raw_field":"hostname", + "ecs":"host.hostname" + }, + { + "raw_field":"message", + "ecs":"windows.message" + }, + { + "raw_field":"Provider_Name", + "ecs":"winlog.provider_name" + }, + { + "raw_field":"EventId", + "ecs":"winlog.event_id" + }, + { + "raw_field":"processPath", + "ecs":"winlog.event_data.ProcessPath" + }, + { + "raw_field":"ProcessName", + "ecs":"winlog.event_data.ProcessName" + }, + { + "raw_field":"ObjectName", + "ecs":"winlog.computerObject.name" + }, + { + "raw_field":"param1", + "ecs":"winlog.event_data.param1" + }, + { + "raw_field":"param2", + "ecs":"winlog.event_data.param2" + }, + { + "raw_field":"creationTime", + "ecs":"timestamp" + }, + { + "raw_field":"Origin", + "ecs":"winlog.event_data.Origin" + }, + { + "raw_field":"ParentImage", + "ecs":"winlog.event_data.ParentImage" + }, + { + "raw_field":"TargetPort", + "ecs":"winlog.event_data.TargetPort" + }, + { + "raw_field":"Query", + "ecs":"winlog.event_data.Query" + }, + { + "raw_field":"DestinationPort", + "ecs":"destination.port" + }, + { + "raw_field":"StartAddress", + "ecs":"winlog.event_data.StartAddress" + }, + { + "raw_field":"TicketOptions", + "ecs":"winlog.event_data.TicketOptions" + }, + { + "raw_field":"ParentCommandLine", + "ecs":"winlog.event_data.ParentCommandLine" + }, + { + "raw_field":"AllowedToDelegateTo", + "ecs":"winlog.event_data.AllowedToDelegateTo" + }, + { + "raw_field":"HostApplication", + "ecs":"winlog.event_data.HostApplication" + }, + { + "raw_field":"AccessMask", + "ecs":"winlog.event_data.AccessMask" + }, + { + "raw_field":"Hashes", + "ecs":"winlog.event_data.Hashes" + }, + { + "raw_field":"SidHistory", + "ecs":"winlog.event_data.SidHistory" + }, + { + "raw_field":"Initiated", + "ecs":"winlog.event_data.Initiated" + }, + { + "raw_field":"DestinationIp", + "ecs":"destination.ip" + }, + { + "raw_field":"RelativeTargetName", + "ecs":"winlog.event_data.RelativeTargetName" + }, + { + "raw_field":"Source_Name", + "ecs":"winlog.event_data.Source_Name" + }, + { + "raw_field":"AttributeLDAPDisplayName", + "ecs":"winlog.event_data.AttributeLDAPDisplayName" + }, + { + "raw_field":"DeviceDescription", + "ecs":"winlog.event_data.DeviceDescription" + }, + { + "raw_field":"AttributeValue", + "ecs":"winlog.event_data.AttributeValue" + }, + { + "raw_field":"ObjectValueName", + "ecs":"winlog.event_data.ObjectValueName" + }, + { + "raw_field":"QueryStatus", + "ecs":"winlog.event_data.QueryStatus" + }, + { + "raw_field":"TargetParentProcessId", + "ecs":"winlog.event_data.TargetParentProcessId" + }, + { + "raw_field":"OldUacValue", + "ecs":"winlog.event_data.OldUacValue" + }, + { + "raw_field":"FailureCode", + "ecs":"winlog.event_data.FailureCode" + }, + { + "raw_field":"OldTargetUserName", + "ecs":"winlog.event_data.OldTargetUserName" + }, + { + "raw_field":"NewUacValue", + "ecs":"winlog.event_data.NewUacValue" + }, + { + "raw_field":"ServiceName", + "ecs":"winlog.event_data.ServiceName" + }, + { + "raw_field":"Imphash", + "ecs":"winlog.event_data.Imphash" + }, + { + "raw_field":"NewValue", + "ecs":"winlog.event_data.NewValue" + }, + { + "raw_field":"Action", + "ecs":"winlog.event_data.Action" + }, + { + "raw_field":"SourceImage", + "ecs":"winlog.event_data.SourceImage" + }, + { + "raw_field":"QNAME", + "ecs":"winlog.event_data.QNAME" + }, + { + "raw_field":"Properties", + "ecs":"winlog.event_data.Properties" + }, + { + "raw_field":"AuditPolicyChanges", + "ecs":"winlog.event_data.AuditPolicyChanges" + }, + { + "raw_field":"Accesses", + "ecs":"winlog.event_data.Accesses" + }, + { + "raw_field":"ClassName", + "ecs":"winlog.event_data.ClassName" + }, + { + "raw_field":"ObjectClass", + "ecs":"winlog.event_data.ObjectClass" + }, + { + "raw_field":"PipeName", + "ecs":"winlog.event_data.PipeName" + }, + { + "raw_field":"HiveName", + "ecs":"winlog.event_data.HiveName" + }, + { + "raw_field":"StartModule", + "ecs":"winlog.event_data.StartModule" + }, + { + "raw_field":"HostVersion", + "ecs":"winlog.event_data.HostVersion" + }, + { + "raw_field":"DestinationHostname", + "ecs":"winlog.event_data.DestinationHostname" + }, + { + "raw_field":"QueryName", + "ecs":"winlog.event_data.QueryName" + }, + { + "raw_field":"RemoteName", + "ecs":"winlog.event_data.RemoteName" + }, + { + "raw_field":"PasswordLastSet", + "ecs":"winlog.event_data.PasswordLastSet" + }, + { + "raw_field":"ErrorCode", + "ecs":"winlog.event_data.ErrorCode" + }, + { + "raw_field":"AccessList", + "ecs":"winlog.event_data.AccessList" + }, + { + "raw_field":"Address", + "ecs":"winlog.event_data.Address" + }, + { + "raw_field":"PossibleCause", + "ecs":"winlog.event_data.PossibleCause" + }, + { + "raw_field":"DestPort", + "ecs":"destination.port" + }, + { + "raw_field":"Image", + "ecs":"winlog.event_data.Image" + }, + { + "raw_field":"CertThumbprint", + "ecs":"winlog.event_data.CertThumbprint" + }, + { + "raw_field":"TicketEncryptionType", + "ecs":"winlog.event_data.TicketEncryptionType" + }, + { + "raw_field":"ServiceType", + "ecs":"winlog.event_data.ServiceType" + }, + { + "raw_field":"ObjectServer", + "ecs":"winlog.event_data.ObjectServer" + }, + { + "raw_field":"ImagePath", + "ecs":"winlog.event_data.ImagePath" + }, + { + "raw_field":"NewName", + "ecs":"winlog.event_data.NewName" + }, + { + "raw_field":"CallTrace", + "ecs":"winlog.event_data.CallTrace" + }, + { + "raw_field":"SamAccountName", + "ecs":"winlog.event_data.SamAccountName" + }, + { + "raw_field":"GrantedAccess", + "ecs":"winlog.event_data.GrantedAccess" + }, + { + "raw_field":"EngineVersion", + "ecs":"winlog.event_data.EngineVersion" + }, + { + "raw_field":"OriginalName", + "ecs":"winlog.event_data.OriginalName" + }, + { + "raw_field":"AuditSourceName", + "ecs":"winlog.event_data.AuditSourceName" + }, + { + "raw_field":"sha1", + "ecs":"hash.sha1" + }, + { + "raw_field":"SourceIp", + "ecs":"source.ip" + }, + { + "raw_field":"Payload", + "ecs":"winlog.event_data.Payload" + }, + { + "raw_field":"Level", + "ecs":"winlog.event_data.Level" + }, + { + "raw_field":"Application", + "ecs":"winlog.event_data.Application" + }, + { + "raw_field":"RemoteAddress", + "ecs":"winlog.event_data.RemoteAddress" + }, + { + "raw_field":"SearchFilter", + "ecs":"winlog.event_data.SearchFilter" + }, + { + "raw_field":"ApplicationPath", + "ecs":"winlog.event_data.ApplicationPath" + }, + { + "raw_field":"TargetFilename", + "ecs":"winlog.event_data.TargetFilename" + }, + { + "raw_field":"CurrentDirectory", + "ecs":"winlog.event_data.CurrentDirectory" + }, + { + "raw_field":"ObjectType", + "ecs":"winlog.event_data.ObjectType" + }, + { + "raw_field":"ServicePrincipalNames", + "ecs":"winlog.event_data.ServicePrincipalNames" + }, + { + "raw_field":"TemplateContent", + "ecs":"winlog.event_data.TemplateContent" + }, + { + "raw_field":"QueryResults", + "ecs":"winlog.event_data.QueryResults" + }, + { + "raw_field":"ServiceStartType", + "ecs":"winlog.event_data.ServiceStartType" + }, + { + "raw_field":"EventType", + "ecs":"winlog.event_data.EventType" + }, + { + "raw_field":"TargetSid", + "ecs":"winlog.event_data.TargetSid" + }, + { + "raw_field":"ParentUser", + "ecs":"winlog.event_data.ParentUser" + }, + { + "raw_field":"NewTargetUserName", + "ecs":"winlog.event_data.NewTargetUserName" + }, + { + "raw_field":"DestAddress", + "ecs":"winlog.event_data.DestAddress" + }, + { + "raw_field":"ContextInfo", + "ecs":"winlog.event_data.ContextInfo" + }, + { + "raw_field":"HostName", + "ecs":"host.name" + }, + { + "raw_field":"NewTemplateContent", + "ecs":"winlog.event_data.NewTemplateContent" + }, + { + "raw_field":"LayerRTID", + "ecs":"winlog.event_data.LayerRTID" + }, + { + "raw_field":"ImageFileName", + "ecs":"winlog.event_data.ImageFileName" + }, + { + "raw_field":"StartFunction", + "ecs":"winlog.event_data.StartFunction" + }, + { + "raw_field":"Value", + "ecs":"winlog.event_data.Value" + }, + { + "raw_field":"ModifyingApplication", + "ecs":"winlog.event_data.ModifyingApplication" + }, + { + "raw_field":"Destination", + "ecs":"winlog.event_data.Destination" + }, + { + "raw_field":"Commandline", + "ecs":"winlog.event_data.Commandline" + }, + { + "raw_field":"Message", + "ecs":"winlog.event_data.Message" + }, + { + "raw_field":"ShareName", + "ecs":"winlog.event_data.ShareName" + }, + { + "raw_field":"SourcePort", + "ecs":"source.port" + }, + { + "raw_field":"CallerProcessName", + "ecs":"winlog.event_data.CallerProcessName" + }, + { + "raw_field":"ServiceFileName", + "ecs":"winlog.event_data.ServiceFileName" + }, + { + "raw_field":"DestinationIsIpv6", + "ecs":"winlog.event_data.DestinationIsIpv6" + }, + { + "raw_field":"TargetImage", + "ecs":"winlog.event_data.TargetImage" + }, + { + "raw_field":"SourceAddress", + "ecs":"source.ip" + }, + { + "raw_field":"TargetObject", + "ecs":"winlog.event_data.TargetObject" + }, + { + "raw_field":"Caption", + "ecs":"winlog.event_data.Caption" + }, + { + "raw_field":"LocalName", + "ecs":"winlog.event_data.LocalName" + }, + { + "raw_field":"ImageLoaded", + "ecs":"winlog.event_data.ImageLoaded" + }, + { + "raw_field":"EventID", + "ecs":"winlog.event_id" + }, + { + "raw_field":"sha256", + "ecs":"hash.sha256" + }, + { + "raw_field":"ScriptBlockLogging", + "ecs":"winlog.event_data.ScriptBlockLogging" + }, + { + "raw_field":"SourceParentImage", + "ecs":"winlog.event_data.SourceParentImage" + }, + { + "raw_field":"SourceFilename", + "ecs":"winlog.event_data.SourceFilename" + }, + { + "raw_field":"Protocol", + "ecs":"winlog.event_data.Protocol" + }, + { + "raw_field":"ValidatedPolicy", + "ecs":"winlog.event_data.ValidatedPolicy" + }, + { + "raw_field":"ProcessPath", + "ecs":"winlog.event_data.ProcessPath" + }, + { + "raw_field":"OldValue", + "ecs":"winlog.event_data.OldValue" + }, + { + "raw_field":"ParentProcessId", + "ecs":"winlog.event_data.ParentProcessId" + }, + { + "raw_field":"TaskContentNew", + "ecs":"winlog.event_data.TaskContentNew" + }, + { + "raw_field":"Name", + "ecs":"winlog.event_data.Name" + }, + { + "raw_field":"payload", + "ecs":"winlog.event_data.payload" + }, + { + "raw_field":"SourceHostname", + "ecs":"winlog.event_data.SourceHostname" + }, + { + "raw_field":"ClientProcessId", + "ecs":"winlog.event_data.ClientProcessId" + }, + { + "raw_field":"TargetParentImage", + "ecs":"winlog.event_data.TargetParentImage" + }, + { + "raw_field":"ImpersonationLevel", + "ecs":"winlog.event_data.ImpersonationLevel" + }, + { + "raw_field":"ExceptionCode", + "ecs":"winlog.event_data.ExceptionCode" + }, + { + "raw_field":"FilterOrigin", + "ecs":"winlog.event_data.FilterOrigin" + }, + { + "raw_field":"PackagePath", + "ecs":"winlog.event_data.PackagePath" + }, + { + "raw_field":"SignatureStatus", + "ecs":"winlog.event_data.SignatureStatus" + }, + { + "raw_field":"Hash", + "ecs":"winlog.event_data.Hash" + }, + { + "raw_field":"AppID", + "ecs":"winlog.event_data.AppID" + }, + { + "raw_field":"SidList", + "ecs":"winlog.event_data.SidList" + }, + { + "raw_field":"ProcessNameBuffer", + "ecs":"winlog.event_data.ProcessNameBuffer" + }, + { + "raw_field":"PreviousCreationUtcTime", + "ecs":"winlog.event_data.PreviousCreationUtcTime" + }, + { + "raw_field":"Contents", + "ecs":"winlog.event_data.Contents" + }, + { + "raw_field":"TargetOutboundUserName", + "ecs":"winlog.event_data.TargetOutboundUserName" + }, + { + "raw_field":"ImageName", + "ecs":"winlog.event_data.ImageName" + }, + { + "raw_field":"md5", + "ecs":"hash.md5" + }, + { + "raw_field":"DeviceName", + "ecs":"winlog.event_data.DeviceName" + }, + { + "raw_field":"RequestedPolicy", + "ecs":"winlog.event_data.RequestedPolicy" + }, + { + "raw_field":"FileNameBuffer", + "ecs":"winlog.event_data.FileNameBuffer" + }, + { + "raw_field":"TaskContent", + "ecs":"winlog.event_data.TaskContent" + }, + { + "raw_field":"SourceCommandLine", + "ecs":"winlog.event_data.SourceCommandLine" + }, + { + "raw_field":"CreationUtcTime", + "ecs":"winlog.event_data.CreationUtcTime" + }, + { + "raw_field":"AppName", + "ecs":"winlog.event_data.AppName" + }, + { + "raw_field":"subjectName", + "ecs":"winlog.event_data.subjectName" + }, + { + "raw_field":"process", + "ecs":"winlog.event_data.process" + }, + { + "raw_field":"PackageFullName", + "ecs":"winlog.event_data.PackageFullName" + }, + { + "raw_field":"SourceName", + "ecs":"winlog.event_data.SourceName" + }, + { + "raw_field":"Data", + "ecs":"winlog.event_data.Data" + }, + { + "raw_field":"param3", + "ecs":"winlog.event_data.param3" + }, + { + "raw_field":"Signature", + "ecs":"winlog.event_data.Signature" + } + ] +``` diff --git a/i18n/zh/security-analytics/resource-access-control.md b/i18n/zh/security-analytics/resource-access-control.md new file mode 100644 index 00000000..9859adc2 --- /dev/null +++ b/i18n/zh/security-analytics/resource-access-control.md @@ -0,0 +1,153 @@ +--- +title: 安全分析资源访问控制 +--- + +# 安全分析资源访问控制 + +安全分析与安全插件的资源共享和访问控制框架集成,为检测器和关联规则提供文档级授权。这取代了传统的 `plugins.security_analytics.filter_by_backend_roles` 设置,提供了一个更灵活的共享系统,允许资源所有者向用户、角色或后端角色授予特定的访问级别。 + +::: info NOTE +有关端到端框架概念和 API,请参阅[资源共享和访问控制](/security/access-control/resources/)。 +::: + +## 资源配置 + +安全分析注册了两种资源类型。下表描述了安全分析资源配置。 + +| 资源类型 | 系统索引 | 加入版本 | +| :--- | :--- | :--- | +| `detector` | `.opensearch-sap-detectors-config` | OpenSearch 3.8 | +| `correlation-rule` | `.opensearch-sap-correlation-rules-config` | OpenSearch 3.8 | + +启用资源级授权后,每个检测器和关联规则的可见性都由一个中央共享记录管理。资源所有者和具有共享能力的用户可以为特定的用户、角色或后端角色授予或撤销访问权限。 + +## 启用安全分析资源共享 + +要为安全分析启用资源共享,需要将安全分析资源类型添加到受保护类型列表,并在集群范围内启用资源共享。 + +::: warning IMPORTANT +仅管理员:这些设置只能由具有超级管理员权限的集群管理员配置。 +::: + +### 使用 opensearch.yml 配置 + +将以下设置添加到您的 `opensearch.yml` 配置文件以启用安全分析的资源共享: + +```yaml +plugins.security.resource_sharing.enabled: true +plugins.security.system_indices.enabled: true +plugins.security.resource_sharing.protected_types: + - "detector" + - "correlation-rule" +``` + +### 使用集群设置 API 配置 + +或者,您可以使用集群设置 API 动态启用资源共享: + +```json +PUT _cluster/settings +{ + "transient": { + "plugins.security.resource_sharing.enabled": true, + "plugins.security.resource_sharing.protected_types": ["detector", "correlation-rule"] + } +} +``` + +::: info NOTE +在向现有配置添加安全分析资源类型时,请在 `protected_types` 数组中包含所有先前配置的资源类型。 +::: + +## 安全分析访问级别 + +安全分析提供了三个预定义的访问级别,适用于 `detector` 和 `correlation-rule` 资源类型。这些访问级别决定了被授予访问检测器或关联规则资源的用户所获得的特定权限。 + +### sa_read_only + +`sa_read_only` 只读访问级别授予用户查看和搜索共享资源的能力,但不能修改它们。对于检测器,此访问级别包括以下权限: + +```yaml +- 'cluster:admin/opensearch/securityanalytics/detector/get' +- 'cluster:admin/opensearch/securityanalytics/detector/search' +- 'cluster:admin/opensearch/securityanalytics/alerts/get' +- 'cluster:admin/opensearch/securityanalytics/findings/get' +- 'cluster:admin/opensearch/securityanalytics/mapping/get' +- 'cluster:admin/opensearch/securityanalytics/mapping/view/get' +``` + +对于关联规则,此访问级别包括以下权限: + +```yaml +- 'cluster:admin/opensearch/securityanalytics/correlation/rule/search' +- 'cluster:admin/opensearch/securityanalytics/correlations/list' +- 'cluster:admin/opensearch/securityanalytics/correlations/findings' +- 'cluster:admin/opensearch/securityanalytics/correlationAlerts/get' +``` + +### sa_read_write + +`sa_read_write` 读写访问级别授予用户对资源操作的完全访问权限,但不包括共享功能。对于检测器,此访问级别包括以下权限: + +```yaml +- 'cluster:admin/opensearch/securityanalytics/detector/*' +- 'cluster:admin/opensearch/securityanalytics/alerts/*' +- 'cluster:admin/opensearch/securityanalytics/findings/*' +- 'cluster:admin/opensearch/securityanalytics/mapping/*' +- 'cluster:admin/opensearch/securityanalytics/rule/*' +``` + +对于关联规则,此访问级别包括以下权限: + +```yaml +- 'cluster:admin/index/correlation/rules/*' +- 'cluster:admin/opensearch/securityanalytics/correlation/rule/search' +- 'cluster:admin/opensearch/securityanalytics/correlations/*' +- 'cluster:admin/opensearch/securityanalytics/correlationAlerts/*' +``` + +### sa_full_access + +`sa_full_access` 完全访问级别授予用户对资源的完全控制权,包括类似所有者的权限,例如与其他用户共享资源。此访问级别包括该资源类型的所有读写权限以及资源共享权限: + +```yaml +- 'cluster:admin/security/resource/share' +``` + +::: info NOTE +这些访问级别是预定义的,不能修改。要请求额外的访问级别,请在[安全分析 GitHub 存储库](https://github.com/opensearch-project/security-analytics/)中创建一个问题。 +::: + +## 从旧框架迁移 + +在启用资源共享并将安全分析资源类型标记为受保护后,集群管理员必须运行迁移 API,将现有的检测器和关联规则共享信息从旧框架传输到新的资源共享系统。每个资源索引运行一次迁移。 + +::: warning IMPORTANT +仅管理员:迁移 API 只能由具有超级管理员或 REST 管理员权限的集群管理员执行。 +::: + +使用以下 API 调用将旧的检测器共享数据迁移到资源共享框架: + +```json +POST _plugins/_security/api/resources/migrate +{ + "source_index": ".opensearch-sap-detectors-config", + "username_path": "/user/name", + "backend_roles_path": "/user/backend_roles", + "default_owner": "<replace-with-existing-user>", + "default_access_level": { + "detector": "<select-appropriate-access-level>" + } +} +``` + +再次运行迁移来处理关联规则索引,使用 `.opensearch-sap-correlation-rules-config` 作为 `source_index`,使用 `correlation-rule` 作为 `default_access_level` 键。 + +将 `<replace-with-existing-user>` 替换为应该拥有没有明确所有权信息的资源的现有用户的用户名。将 `<select-appropriate-access-level>` 替换为可用的安全分析访问级别之一:`sa_read_only`、`sa_read_write` 或 `sa_full_access`。 + +## 相关文档 + +- [资源共享和访问控制](/security/access-control/resources/) -- 后端概念、配置和设置 +- [资源共享 API](/security/access-control/resource-sharing-api/) -- 用于程序化管理的 REST API 参考 +- [资源访问管理](/dashboards/management/resource-sharing) -- UI 工作流程和用户指南 +- [OpenSearch 安全分析的安全性](/security-analytics/security) -- 基本权限和旧的后端角色过滤 diff --git a/i18n/zh/security-analytics/threat-intelligence/api/findings.md b/i18n/zh/security-analytics/threat-intelligence/api/findings.md new file mode 100644 index 00000000..3c96dc53 --- /dev/null +++ b/i18n/zh/security-analytics/threat-intelligence/api/findings.md @@ -0,0 +1,256 @@ +--- +title: 告警和发现 API +--- + +# 告警和发现 API + +威胁情报告警和发现 API 检索来自威胁情报源的告警和发现信息。 + +--- + +## 获取威胁情报告警 + +检索与威胁情报监控器相关的任何告警。 + +### 端点 + +```json +GET /_plugins/_security_analytics/threat_intel/alerts +``` + +### 路径参数 + +在请求告警时,可以指定以下参数。 + +参数 | 描述 +:--- | :---- +`severityLevel` | 按严重级别过滤告警。可选。 +`alertState` | 用于按告警状态过滤。可能的值为 `ACTIVE`、`ACKNOWLEDGED`、`COMPLETED`、`ERROR` 或 `DELETED`。可选。 +`sortString` | 安全分析用于排序告警的字符串。可选。 +`sortOrder` | 用于排序告警列表的顺序。可能的值为 `asc` 或 `desc`。可选。 +`missing` | 未找到别名映射的字段列表。可选。 +`size` | 响应中要返回的最大结果数。可选。 +`startIndex` | 分页指示器。可选。 +`searchString` | 要在搜索中返回的告警属性。可选。 + +### 请求示例 + +```json +GET /_plugins/_security_analytics/threat_intel/alerts +``` + +### 响应示例 + +```json +{ + "alerts": [{ + "id": "906669ee-56e8-4f40-a12f-ab4c274d7521", + "version": 1, + "schema_version": 0, + "seq_no": 0, + "primary_term": 1, + "trigger_id": "regwarg", + "trigger_name": "regwarg", + "state": "ACTIVE", + "error_message": null, + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "severity": "high", + "finding_ids": [ + "a9c10094-6139-42b3-81a8-867dffbe381d" + ], + "acknowledged_time": 1722038395105, + "last_updated_time": null, + "start_time": 1722038395105, + "end_time": null + }], + "total_alerts": 1 +} +``` + +### 响应体字段 + +威胁情报告警可以处于以下状态之一。 + +| 状态 | 描述 | +| :---- | :--- | +| `ACTIVE` | 告警正在进行中且未确认。告警将保持此状态,直到被确认、与告警关联的触发器被删除或威胁情报监控器被完全删除。 | +| `ACKNOWLEDGED` | 告警已确认,但告警的根本原因尚未解决。 | +| `COMPLETED` | 告警不再进行。告警在相应的触发器评估为 `false` 后进入此状态。 | +| `DELETED` | 告警处于活动状态时,该告警的监控器或触发器被删除。 | + +--- + +## 更新告警状态 API + +将指定告警的状态更新为 `ACKNOWLEDGED` 或 `COMPLETED`。只能更新处于 `ACTIVE` 状态的告警。 + +### 端点 + +```json +PUT /plugins/security_analytics/threat_intel/alerts/status +``` + +### 请求示例 + +以下示例将指定告警的状态更新为 `ACKNOWLEDGED`: + +```json +PUT /plugins/security_analytics/threat_intel/alerts/status?state=ACKNOWLEDGED&alert_ids={alert-id},{alert-id} +``` + +以下示例将指定告警的状态更新为 `COMPLETED`: + +```json +PUT /plugins/security_analytics/threat_intel/alerts/status?state=COMPLETED&alert_ids=alert_ids={alert-id},{alert-id} +``` + +### 响应示例 + +```json +{ + "updated_alerts": [ + { + "id": "906669ee-56e8-4f40-a12f-ab4c274d7521", + "version": 1, + "schema_version": 0, + "seq_no": 2, + "primary_term": 1, + "trigger_id": "regwarg", + "trigger_name": "regwarg", + "state": "ACKNOWLEDGED", + "error_message": null, + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "severity": "high", + "finding_ids": [ + "a9c10094-6139-42b3-81a8-867dffbe381d" + ], + "acknowledged_time": 1722039091209, + "last_updated_time": 1722039091209, + "start_time": 1722038395105, + "end_time": null + }, + { + "id": "56e8-4f40-a12f-ab4c274d7521-906669ee", + "version": 1, + "schema_version": 0, + "seq_no": 2, + "primary_term": 1, + "trigger_id": "regwarg", + "trigger_name": "regwarg", + "state": "ACKNOWLEDGED", + "error_message": null, + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "severity": "high", + "finding_ids": [ + "a9c10094-6139-42b3-81a8-867dffbe381d" + ], + "acknowledged_time": 1722039091209, + "last_updated_time": 1722039091209, + "start_time": 1722038395105, + "end_time": null + } + ], + "failure_messages": [] +} +``` + +--- + +## 获取发现 + +返回威胁情报入侵指标(IOC)发现。当威胁情报监控器在数据扫描期间发现恶意 IOC 时,会自动生成发现。 + +### 端点 + +```json +GET /_plugins/_security_analytics/threat_intel/findings/ +``` + +### 路径参数 + +| 参数 | 描述 | +|:---------------|:--------------------------------------------------------------------------------------------| +| `sortString` | 指定安全分析用于排序告警的字符串。可选。 | +| `sortOrder` | 用于排序发现列表的顺序。可能的值为 `asc` 或 `desc`。可选。 | +| `missing` | 未找到别名映射的字段列表。可选。 | +| `size` | 响应中要返回的最大结果数。可选。 | +| `startIndex` | 分页指示器。可选。 | +| `searchString` | 要在搜索中返回的告警属性。可选。 | + +### 请求示例 + +```json +GET /_plugins/_security_analytics/threat_intel/findings/_search?size=3 +``` + +```json +{ + "total_findings": 10, + "ioc_findings": [ + { + "id": "a9c10094-6139-42b3-81a8-867dffbe381d", + "related_doc_ids": [ + "Ccp88ZAB1vBjq44wmTEu:windows" + ], + "ioc_feed_ids": [ + { + "ioc_id": "2", + "feed_id": "Bsp88ZAB1vBjq44wiDGo", + "feed_name": "my_custom_feed", + "index": "" + } + ], + "monitor_id": "B8p88ZAB1vBjq44wkjEy", + "monitor_name": "Threat intelligence monitor", + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "timestamp": 1722038394501, + "execution_id": "01cae635-93dc-4f07-9e39-31076b9535d1" + }, + { + "id": "8d87aee0-aaa4-4c12-b4e2-b4b1f4ec80f9", + "related_doc_ids": [ + "GsqI8ZAB1vBjq44wXTHa:windows" + ], + "ioc_feed_ids": [ + { + "ioc_id": "2", + "feed_id": "Bsp88ZAB1vBjq44wiDGo", + "feed_name": "my_custom_feed", + "index": "" + } + ], + "monitor_id": "B8p88ZAB1vBjq44wkjEy", + "monitor_name": "Threat intelligence monitor", + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "timestamp": 1722039165824, + "execution_id": "54899e32-aeeb-401e-a031-b1728772f0aa" + }, + { + "id": "2419f624-ba1a-4873-978c-760183b449b7", + "related_doc_ids": [ + "H8qI8ZAB1vBjq44woDHU:windows" + ], + "ioc_feed_ids": [ + { + "ioc_id": "2", + "feed_id": "Bsp88ZAB1vBjq44wiDGo", + "feed_name": "my_custom_feed", + "index": "" + } + ], + "monitor_id": "B8p88ZAB1vBjq44wkjEy", + "monitor_name": "Threat intelligence monitor", + "ioc_value": "example-has00001", + "ioc_type": "hashes", + "timestamp": 1722039182616, + "execution_id": "32ad2544-4b8b-4c9b-b2b4-2ba6d31ece12" + } + ] +} + +``` diff --git a/i18n/zh/security-analytics/threat-intelligence/api/monitor.md b/i18n/zh/security-analytics/threat-intelligence/api/monitor.md new file mode 100644 index 00000000..116288fa --- /dev/null +++ b/i18n/zh/security-analytics/threat-intelligence/api/monitor.md @@ -0,0 +1,317 @@ +--- +title: 监控器 API +--- + +# 监控器 API + +您可以使用威胁情报监控器 API 为威胁情报源创建、搜索和更新[监控器](/observing-your-data/alerting/monitors)。 + +--- +## 创建或更新威胁情报监控器 + +创建或更新威胁情报监控器。 + +### 端点 + +`POST` 方法创建新监控器。`PUT` 方法更新监控器。 + +```json +POST _plugins/_security_analytics/threat_intel/monitors +PUT _plugins/_security_analytics/threat_intel/monitors/{monitor_id} +``` + +### 请求体字段 + +您可以在请求体中指定以下字段。 + +| 字段 | 类型 | 描述 | +| :--- | :--- | :--- | +| `name` | String | 监控器的名称。必需。 | +| `schedule` | Object | 确定监控器运行频率的计划。必需。 | +| `schedule.period` | Object | 有关计划频率的信息。必需。 | +| `schedule.period.interval` | Integer | 监控器运行的间隔。必需。 | +| `schedule.period.unit` | String | 间隔的时间单位。 | +| `enabled` | Object | 有关创建监控器的用户的信息。必需。 | +| `user.backend_roles` | Array | 与用户关联的后端角色。可选。 | +| `user.roles` | Array | 与用户关联的角色。可选。 | +| `user.custom_attribute_names` | Array | 与用户关联的自定义属性名称。可选。 | +| `user.user_requested_tenant` | String | 用户请求的租户。可选。 | +| `indices` | Array | 用于监控器的日志数据源。必需。 | +| `per_ioc_type_scan_input_list` | Array | 基于入侵指标(IOC)类型扫描的输入列表。必需。 | +| `per_ioc_type_scan_input_list.ioc_type` | String | IOC 的类型(例如,哈希值)。必需。 | +| `per_ioc_type_scan_input_list.index_to_fields_map` | Object |包含给定 IOC 类型值的索引字段映射。必需。 | +| `per_ioc_type_scan_input_list.index_to_fields_map.<index>` | Array | 指定索引中包含的字段列表。必需。 | +| `triggers` | Array | 告警的触发器设置。必需。 | +| `triggers.data_sources` | Array | 与触发器关联的数据源列表。必需。 | +| `triggers.name` | String | 触发器的名称。必需。 | +| `triggers.severity` | String | 触发器的严重级别(例如,高、中或低)。必需。 | + +### 请求示例 + +以下部分提供了监控器 API 的请求示例。 + +#### 创建监控器 + +```json +{ + "name": "Threat intel monitor", + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "name": "regwarg", + "severity": "high" + } + ] +} +``` + +### 更新监控器 + +```json +{ + "name": "Threat intel monitor", + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "name": "regwarg", + "severity": "high" + } + ] +} +``` + +### 响应示例 + +```json +{ + "id": "B8p88ZAB1vBjq44wkjEy", + "name": 1, + "seq_no": 0, + "primary_term": 1, + "monitor": { + "id": "B8p88ZAB1vBjq44wkjEy", + "name": "Threat intel monitor", + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "ioc_types": [], + "actions": [], + "id": "afdd80cc-a669-4487-98a0-d84bea8e1e39", + "name": "regwarg", + "severity": "high" + } + ] + } +} +``` +--- + +## 删除监控器 + +删除现有的威胁情报监控器。 + +### 端点 + +```json +DELETE /_plugins/_security_analytics/threat_intel/monitors/{monitor_id} +``` + +### 请求示例 + +```json +DELETE /_plugins/_security_analytics/threat_intel/monitors/B8p88ZAB1vBjq44wkjEy +``` + +### 响应示例 + +```json +{ + "_id" : "B8p88ZAB1vBjq44wkjEy", + "_version" : 1 +} +``` + +## 搜索监控器 + +使用查询搜索现有监控器。请求体需要一个搜索查询。有关查询选项,请参阅 [Query DSL](/query-dsl/)。 + +### 请求示例 + +以下示例请求使用监控器 ID 的匹配查询来搜索监控器: + +```json +POST /_plugins/_security_analytics/detectors/_search +{ + "query": { + "match": { + "_id": "HMqq_5AB1vBjq44wpTIN" + } + } +} +``` + +### 响应示例 + +```json +{ + "took": 11, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 1, + "relation": "eq" + }, + "max_score": 2.0, + "hits": [ + { + "_index": ".opendistro-alerting-config", + "_id": "HMqq_5AB1vBjq44wpTIN", + "_version": 1, + "_seq_no": 8, + "_primary_term": 1, + "_score": 2.0, + "_source": { + "id": "HMqq_5AB1vBjq44wpTIN", + "name": "Threat intel monitor", + "per_ioc_type_scan_input_list": [ + { + "ioc_type": "hashes", + "index_to_fields_map": { + "windows": [ + "file_hash" + ] + } + } + ], + "schedule": { + "period": { + "interval": 1, + "unit": "MINUTES" + } + }, + "enabled": false, + "user": { + "name": "", + "backend_roles": [], + "roles": [], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "indices": [ + "windows" + ], + "triggers": [ + { + "data_sources": [ + "windows", + "random" + ], + "ioc_types": [], + "actions": [], + "id": "63426758-c82d-4c87-a52c-f86ee6a8a06d", + "name": "regwarg", + "severity": "high" + } + ] + } + } + ] + } +} +``` diff --git a/i18n/zh/security-analytics/threat-intelligence/api/source.md b/i18n/zh/security-analytics/threat-intelligence/api/source.md new file mode 100644 index 00000000..5785e34f --- /dev/null +++ b/i18n/zh/security-analytics/threat-intelligence/api/source.md @@ -0,0 +1,583 @@ +--- +title: 威胁情报源 API +--- + +# 威胁情报源 API + +威胁情报源 API 更新和返回与威胁情报源配置相关的任务信息。 + +## 创建或更新威胁情报源 + +创建或更新威胁情报源并从该源加载入侵指标(IOC)。 + +您可以创建 `S3_CUSTOM` 和 `IOC_UPLOAD` 类型的源。`URL_DOWNLOAD` 类型保留给 OpenSearch 自动创建的内置源,不能使用此 API 创建。有关更多信息,请参阅 [URL_DOWNLOAD 类型源](#url_download-类型源)。 + +### 端点 + +```json +POST _plugins/_security_analytics/threat_intel/sources +PUT _plugins/_security_analytics/threat_intel/sources/{source_id} +``` + +### 请求体字段 + +| 字段 | 类型 | 描述 | +| :--- | :--- | :---- | +| `type` | String | 威胁情报源的类型。有效值为 `S3_CUSTOM` 和 `IOC_UPLOAD`。 | +| `name` | String | 威胁情报源的名称。 | +| `format` | String | 威胁情报数据的格式,例如 `STIX2`。 | +| `description` | String | 威胁情报源的描述。 | +| `enabled` | Boolean | 指示是否启用从源定期刷新 IOC。 | +| `ioc_types` | Array of strings | 源支持的 IOC 的 `STIX2` 类型,例如 `hashes`、`domain-name`、`ipv4-addr` 或 `ipv6-addr`。 | +| `source` | Object | 威胁情报数据的源信息。 | +| `source.ioc_upload` | Object | 有关 IOC 上传的信息。适用于 `IOC_UPLOAD` 类型。 | +| `source.ioc_upload.file_name` | String | 包含 IOC 的文件名称,例如 `test`。适用于 `IOC_UPLOAD` 类型。 | +| `source.ioc_upload.iocs` | Array of objects | `STIX2` 格式的 IOC 列表。适用于 `IOC_UPLOAD` 类型。 | +| `source_config.source.s3` | Object | 有关 Amazon Simple Storage Service (Amazon S3) 源的信息。适用于 `S3_CUSTOM` 类型。 | +| `source_config.source.s3.bucket_name` | String | S3 存储桶的名称,例如 `threat-intel-s3-test-bucket`。适用于 `S3_CUSTOM` 类型。 | +| `source_config.source.s3.object_key` | String | S3 存储桶中对象的键,例如 `alltypess3object`。适用于 `S3_CUSTOM` 类型。 | +| `source_config.source.s3.region` | String | S3 存储桶所在的 AWS 区域。示例:`us-west-2`。适用于 `S3_CUSTOM` 类型。 | +| `source_config.source.s3.role_arn` | String | 用于访问 S3 存储桶的角色的 Amazon 资源名称 (ARN),例如 `arn:aws:iam::248279774929:role/threat_intel_s3_test_role`。适用于 `S3_CUSTOM` 类型。 | +| `source_config.source.url_download` | Object | 有关下载 IOC 的 URL 的信息。适用于 `URL_DOWNLOAD` 类型。 | +| `source_config.source.url_download.url` | String | 下载 IOC 的 URL。仅支持 `http` 和 `https` 协议。适用于 `URL_DOWNLOAD` 类型。 | +| `source_config.source.url_download.feed_format` | String | 下载的源的格式。唯一支持的值是 `csv`。适用于 `URL_DOWNLOAD` 类型。 | +| `source_config.source.url_download.has_csv_header_field` | Boolean | CSV 文件的第一行是否为标题行。默认值为 `false`。适用于 `URL_DOWNLOAD` 类型。 | +| `source_config.source.url_download.csv_ioc_value_colum_num` | Integer | 包含 IOC 值的 CSV 列的从零开始的索引。适用于 `URL_DOWNLOAD` 类型。 | + +#### IOC 字段 (STIX2) + +以下字段修改 `ioc_types` 选项。 + +| 字段 | 类型 | 描述 | +| :--- | :---- | :---- | +| `id` | String | IOC 的唯一标识符,例如 `1`。 | +| `name` | String | IOC 的可读名称,例如 `ioc-name`。 | +| `type` | String | IOC 的类型,例如 `hashes`。 | +| `value` | String | IOC 的值,可以是哈希值,例如 `gof`。 | +| `severity` | String | IOC 的严重级别。示例:`thvvz`。 | +| `created` | Integer/String | 指示 IOC 创建时间的时间戳,可以是 UNIX 纪元格式或 ISO_8601 格式,例如 `1719519073` 或 `2024-06-20T01:06:20.562008Z`。 | +| `modified` | Integer/String | 指示 IOC 最后修改时间的时间戳,可以是 UNIX 纪元格式或 ISO_8601 格式,例如 `1719519073` 或 `2024-06-20T01:06:20.562008Z`。 | +| `description` | String | IOC 的描述。 | +| `labels` | Array of strings | 与 IOC 关联的任何标签或标记。 | +| `feed_id` | String | IOC 所属源的唯一标识符。 | +| `spec_version` | String | 用于 IOC 的规范版本。 | +| `version` | Integer | IOC 的版本号。 | + +### 响应体字段 + +| 字段 | 数据类型 | 描述 | +| :---- | :--- |:----- | +| `_id` | String | 威胁情报源的唯一标识符。 | +| `_version` | Integer | 威胁情报源的版本号。 | +| `source_config` | Object | 威胁情报源的配置详细信息。 | +| `source_config.name` | String | 威胁情报源的名称。 | +| `source_config.format` | String | 威胁情报数据的格式。 | +| `source_config.type` | String | 威胁情报源的类型。 | +| `source_config.ioc_types` | Array of strings | 源支持的 IOC 类型。 | +| `source_config.description` | String | 威胁情报源的描述。 | +| `source_config.created_by_user` | String or null | 创建威胁情报源的用户。 | +| `source_config.created_at` | String (DateTime) | 威胁情报源创建的日期和时间。 | +| `source_config.source` | Object | 包含有关威胁情报数据源的信息。 | +| `source_config.source.ioc_upload` | Object | 有关 IOC 上传的信息。 | +| `source_config.source.ioc_upload.file_name` | String | 上传文件的名称。示例:`test`。 | +| `source_config.source.ioc_upload.iocs` | Array of objects | 有关 IOC 上传的任何其他信息。当 IOC 成功存储时,此项显示为空数组。 | +| `source_config.enabled` | Boolean | 指示是否启用威胁情报源。 | +| `source_config.enabled_time` | String or null | 源启用的日期和时间。 | +| `source_config.last_update_time` | String (DateTime) | 威胁情报源最后更新的日期和时间。 | +| `source_config.schedule` | String or null | 威胁情报源的计划。 | +| `source_config.state` | String | 威胁情报源的当前状态。 | +| `source_config.refresh_type` | String | 应用于源的刷新类型。 | +| `source_config.last_refreshed_user` | String or null | 最后刷新源的用户。 | +| `source_config.last_refreshed_time` | String (DateTime) | 源最后刷新的日期和时间。 | + +### 请求示例 + +以下示例请求展示如何使用威胁情报源 API。 + +#### IOC_UPLOAD 类型 + +```json +POST _plugins/_security_analytics/threat_intel/sources/ +{ + "type": "IOC_UPLOAD", + "name": "my_custom_feed", + "format": "STIX2", + "description": "this is the description", + "store_type": "OS", + "enabled": "false", + "ioc_types": [ + "hashes" + ], + "source": { + "ioc_upload": { + "file_name": "test", + "iocs": [ + { + "id": "1", + "name": "uldzafothwgik", + "type": "hashes", + "value": "gof", + "severity": "thvvz", + "created": 1719519073, + "modified": 1719519073, + "description": "first one here", + "labels": [ + "ik" + ], + "feed_id": "jl", + "spec_version": "gavvnespe", + "version": -4356924786557562654 + }, + { + "id": "2", + "name": "uldzafothwgik", + "type": "hashes", + "value": "example-has00001", + "severity": "thvvz", + "created": "2024-06-20T01:06:20.562008Z", + "modified": "2024-06-20T02:06:20.56201Z", + "description": "first one here", + "labels": [ + "ik" + ], + "feed_id": "jl", + "spec_version": "gavvnespe", + "version": -4356924786557562654 + } + ] + } + } +} +``` + +<!-- vale off --> +#### S3_CUSTOM 类型源 +<!-- vale on --> + +```json +POST _plugins/_security_analytics/threat_intel/sources/ +{ + "type": "S3_CUSTOM", + "name": "example-ipv4-from-SAP-account", + "format": "STIX2", + "store_type": "OS", + "enabled": "true", + "schedule": { + "interval": { + "start_time": 1717097122, + "period": "10", + "unit": "DAYS" + } + }, + "source": { + "s3": { + "bucket_name": "threat-intel-s3-test-bucket", + "object_key": "alltypess3object", + "region": "us-west-2", + "role_arn": "arn:aws:iam::248279774929:role/threat_intel_s3_test_role" + } + }, + "ioc_types": [ + "domain-name", + "ipv4-addr" + ] +} +``` + +### 响应示例 + +以下示例响应显示成功请求后 OpenSearch 返回的内容。 + +#### IOC_UPLOAD 类型 + +```json +{ + "_id": "2c0u7JAB9IJUg27gcjUp", + "_version": 2, + "source_config": { + "name": "my_custom_feed", + "format": "STIX2", + "type": "IOC_UPLOAD", + "ioc_types": [ + "hashes" + ], + "description": "this is the description", + "created_by_user": null, + "created_at": "2024-07-25T23:16:25.257697Z", + "source": { + "ioc_upload": { + "file_name": "test", + "iocs": [] + } + }, + "enabled": false, + "enabled_time": null, + "last_update_time": "2024-07-25T23:16:26.011774Z", + "schedule": null, + "state": "AVAILABLE", + "refresh_type": "FULL", + "last_refreshed_user": null, + "last_refreshed_time": "2024-07-25T23:16:25.522735Z" + } +} +``` + +<!-- vale off --> +#### S3_CUSTOM 类型源 +<!-- vale on --> + +```json +{ + "id": "rGO5zJABLVyN2kq1wbFS", + "version": 206, + "name": "example-ipv4-from-SAP-account", + "format": "STIX2", + "type": "S3_CUSTOM", + "ioc_types": [ + "domain-name", + "ipv4-addr" + ], + "created_by_user": { + "name": "admin", + "backend_roles": [], + "roles": [ + "security_manager", + "all_access" + ], + "custom_attribute_names": [] + }, + "created_at": "2024-07-19T20:40:44.114Z", + "source": { + "s3": { + "bucket_name": "threat-intel-s3-test-bucket", + "object_key": "alltypess3object", + "region": "us-west-2", + "role_arn": "arn:aws:iam::248279774929:role/threat_intel_s3_test_role" + } + }, + "enabled": true, + "enabled_time": "2024-07-19T20:40:44.114Z", + "last_update_time": "2024-07-25T20:58:18.213Z", + "schedule": { + "interval": { + "start_time": 1717097122, + "period": 10, + "unit": "Days" + } + }, + "state": "AVAILBLE", + "refresh_type": "FULL", + "last_refreshed_user": { + "name": "admin", + "backend_roles": [], + "roles": [ + "security_manager", + "all_access" + ], + "custom_attribute_names": [], + "user_requested_tenant": null + }, + "last_refreshed_time": "2024-07-25T20:58:17.131Z" +} +``` + +--- + +## URL_DOWNLOAD 类型源 + +`URL_DOWNLOAD` 源从 HTTP 或 HTTPS URL 下载 IOC。OpenSearch 为内置威胁情报源自动创建这些源,因此您无法使用威胁情报源 API 创建它们。在 `POST` 请求中指定 `URL_DOWNLOAD` 的请求会返回以下错误: + +``` +URL_DOWNLOAD source type cannot be created via the REST API. It is reserved for internal use only. +``` + +要列出集群中的 `URL_DOWNLOAD` 源,请按类型搜索它们: + +```json +POST _plugins/_security_analytics/threat_intel/sources/_search +{ + "query": { + "match": { + "source_config.type": "URL_DOWNLOAD" + } + } +} +``` + +响应中的 `source.url_download` 对象描述了该源: + +```json +{ + "_id": "alienvault_reputation_ip_database", + "_version": 2, + "source_config": { + "name": "Alienvault IP Reputation", + "format": "STIX2", + "type": "URL_DOWNLOAD", + "description": "Alienvault IP Reputation threat intelligence feed managed by AlienVault", + "created_by_user": null, + "source": { + "url_download": { + "url": "https://reputation.alienvault.com/reputation.generic", + "feed_format": "csv", + "has_csv_header_field": false, + "csv_ioc_value_colum_num": 0 + } + }, + "enabled": true, + "enabled_for_scan": true, + "ioc_types": [ + "ipv4-addr" + ] + } +} +``` + +::: info NOTE +`URL_DOWNLOAD` 源仅支持 `csv` 源格式。配置为任何其他格式的源将无法刷新,并显示 `unsupported feed format for url download` 错误。 +::: + +### 激活或停用 URL_DOWNLOAD 源 + +由于 `URL_DOWNLOAD` 源是内置的,因此您唯一可以更改的字段是 `enabled_for_scan`,它可以激活或停用源。更改任何其他字段的更新请求会返回 `Unsupported Threat intel Source Config Type passed` 错误。您必须在请求中包含 `schedule` 字段,否则请求将验证失败。 + +以下请求停用内置源: + +```json +PUT _plugins/_security_analytics/threat_intel/sources/alienvault_reputation_ip_database +{ + "type": "URL_DOWNLOAD", + "name": "Alienvault IP Reputation", + "format": "STIX2", + "description": "Alienvault IP Reputation threat intelligence feed managed by AlienVault", + "schedule": { + "interval": { + "start_time": 1786030387187, + "period": 1, + "unit": "DAYS" + } + }, + "source": { + "url_download": { + "url": "https://reputation.alienvault.com/reputation.generic", + "feed_format": "csv", + "has_csv_header_field": false, + "csv_ioc_value_colum_num": 0 + } + }, + "ioc_types": [ + "ipv4-addr" + ], + "enabled_for_scan": false +} +``` + +要再次激活该源,请发送将 `enabled_for_scan` 设置为 `true` 的相同请求。 + +::: info NOTE +您无法删除 `URL_DOWNLOAD` 源。删除请求会返回 `Cannot delete built-in tif source config` 错误。 +::: + +--- + +## 获取威胁情报源配置详细信息 + +检索威胁情报源配置详细信息。 + +### 端点 + +```json +GET /_plugins/_security_analytics/threat_intel/sources/{source-id} +``` + +### 请求示例 + +```json +GET /_plugins/_security_analytics/threat_intel/sources/{source-id} +``` + +### 响应示例 + +```json +{ + "_id": "a-jnfjkAF_uQjn8Weo4", + "_version": 2, + "source_config": { + "name": "my_custom_feed_2", + "format": "STIX2", + "type": "S3_CUSTOM", + "ioc_types": [ + "ipv4_addr", + "hashes" + ], + "description": "this is the description", + "created_by_user": null, + "created_at": "2024-06-27T00:52:56.373Z", + "source": { + "s3": { + "bucket_name": "threat-intel-s3-test-bucket", + "object_key": "bd", + "region": "us-west-2", + "role_arn": "arn:aws:iam::540654354201:role/threat_intel_s3_test_role" + } + }, + "enabled": true, + "enabled_time": "2024-06-27T00:52:56.373Z", + "last_update_time": "2024-06-27T00:52:57.824Z", + "schedule": { + "interval": { + "start_time": 1717097122, + "period": 1, + "unit": "Days" + } + }, + "state": "AVAILABLE", + "refresh_type": "FULL", + "last_refreshed_user": null, + "last_refreshed_time": "2024-06-27T00:52:56.533Z" + } +} +``` +--- + +## 搜索威胁情报源 + +根据搜索查询搜索威胁情报源匹配项。请求体需要一个搜索查询。有关查询选项,请参阅 [Query DSL](/query-dsl/)。 + +### 端点 + +```json +POST /_plugins/_security_analytics/threat_intel/sources/_search +``` + +### 请求示例 + +```json +POST /_plugins/_security_analytics/threat_intel/sources/_search +{ + "query": { + "match": { + "source_config.type": "S3_CUSTOM" + } + } +} +``` + +### 响应示例 + +```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": ".opensearch-sap--job", + "_id": "YEAuV5ABx0lQn6qhY5C1", + "_version": 2, + "_seq_no": 1, + "_primary_term": 1, + "_score": 1.0, + "_source": { + "source_config": { + "name": "my_custom_feed_2", + "format": "STIX2", + "type": "S3_CUSTOM", + "description": "this is the description", + "created_by_user": null, + "source": { + "s3": { + "bucket_name": "threat-intelligence-s3-test-bucket", + "object_key": "bd", + "region": "us-west-2", + "role_arn": "arn:aws:iam::540654354201:role/threat_intel_s3_test_role" + } + }, + "created_at": 1719449576373, + "enabled_time": 1719449576373, + "last_update_time": 1719449577824, + "schedule": { + "interval": { + "start_time": 1717097122, + "period": 1, + "unit": "Days" + } + }, + "state": "AVAILABLE", + "refresh_type": "FULL", + "last_refreshed_time": 1719449576533, + "last_refreshed_user": null, + "enabled": true, + "ioc_types": [ + "ip", + "hash" + ] + } + } + } + ] + } +} +``` + +--- + +## 删除威胁情报源 API + +删除威胁情报源。 + +### 端点 + +```json +DELETE /_plugins/_security_analytics/threat_intel/sources/{source-id} +``` + +### 请求示例 + +```json +DELETE /_plugins/_security_analytics/threat_intel/sources/2c0u7JAB9IJUg27gcjUp +``` + +### 响应示例 + +```json +{ + "_id": "2c0u7JAB9IJUg27gcjUp" +} +``` +--- + +## 刷新源 + +从威胁情报源下载任何 IOC。支持 `S3_CUSTOM` 和 `URL_DOWNLOAD` 类型源。不支持刷新 `IOC_UPLOAD` 源,因为其 IOC 直接在创建请求中提供。 + +### 端点 + +```json +POST /_plugins/_security_analytics/threat_intel/sources/{source-id}/_refresh +``` + +### 请求示例 + +```json +POST /_plugins/_security_analytics/threat_intel/sources/IJAXz4QBrmVplM4JYxx_/_refresh +``` + +### 响应示例 + +```json +{ + "acknowledged": true +} +``` diff --git a/i18n/zh/security-analytics/threat-intelligence/api/threat-intel-api.md b/i18n/zh/security-analytics/threat-intelligence/api/threat-intel-api.md new file mode 100644 index 00000000..495bba7a --- /dev/null +++ b/i18n/zh/security-analytics/threat-intelligence/api/threat-intel-api.md @@ -0,0 +1,7 @@ +--- +title: 威胁情报 API +--- + +# 威胁情报 API + +OpenSearch 提供了多个 API,允许您设置和与威胁情报源交互。 diff --git a/i18n/zh/security-analytics/threat-intelligence/getting-started.md b/i18n/zh/security-analytics/threat-intelligence/getting-started.md new file mode 100644 index 00000000..5e4b7df7 --- /dev/null +++ b/i18n/zh/security-analytics/threat-intelligence/getting-started.md @@ -0,0 +1,131 @@ +--- +title: 入门指南 +--- + +# 威胁情报入门指南 + +要开始使用威胁情报,您需要设置威胁情报源并设置监控器来扫描您的日志源。以下教程向您展示如何使用 OpenSearch 仪表板开始使用。或者,您可以使用 [API](/security-analytics/threat-intelligence/api/threat-intel-api)。 + +## 威胁情报视图 + +要访问威胁情报,请登录 OpenSearch 仪表板并选择 **Security Analytics** > **Threat Intelligence**。 + +在威胁情报视图中,您可以访问以下选项卡: + +- **Threat intel sources**:显示所有活动和非活动威胁情报源的列表,包括默认的 IP 信誉源 [AlienVault OTX](https://otx.alienvault.com/),它在下载 OpenSearch 时预先打包。 +- **Scan configuration**:显示您的扫描配置概览,包括配置的 **Log sources**、**Scan schedule** 和 **Alert triggers**。从 **Actions** 下拉列表中,您还可以 **Stop scan**、**Edit scan configuration** 或 **Delete scan configuration**。 + +## 步骤 1:设置威胁情报源 + +要添加威胁情报源,请从威胁情报页面选择 **Add threat intel source**。将出现 **Add custom threat intelligence source** 页面。 + +在威胁情报源页面上,添加以下信息: + +- **Name**:源的名称。 +- **Description**:源的可选描述。 +- **Threat intel source type**:源类型确定 `STIX2` 文件的存储位置。您可以选择以下选项之一: + - **Remote data store location**:连接到自定义数据存储。唯一支持的类型是 `S3_SOURCE`。此设置还使您能够设置下载计划,OpenSearch 会从数据存储下载最新的 `STIX2` 文件。有关更多信息,请参阅 [S3_SOURCE 连接详情](#s3_source-连接信息)。 + - **Local file upload**:上传自定义威胁情报 IOC 文件。自定义文件无法根据计划下载,必须手动上传才能更新 IOC。有关更多信息,请参阅[本地文件上传](#本地文件上传)。 +- **Types of malicious indicators**:确定从 `STIX2` 文件中提取的恶意 IOC 类型。支持以下 IOC: + - IPv4-Address + - IPv6-Address + - Domains + - File hash + +输入所有相关信息后,选择 **Add threat intel source**。 + +### 本地文件上传 + +作为威胁情报源上传的本地文件必须使用以下规范: + +- 以 `STIX2` 格式的 JSON 文件上传。有关 `STIX2` 文件示例,请下载[此文件](/assets/examples/all-ioc-type-examples.json),其中包含所有支持的 IOC 类型的示例格式。 +- 小于 500 kB。 + +<!-- vale off --> +### S3_SOURCE 连接信息 +<!-- vale on --> + +使用 `S3_SOURCE` 作为远程存储时,必须提供以下连接信息: + +- **IAM Role ARN**:AWS Identity and Access Management(IAM)角色的 Amazon 资源名称(ARN)。使用 AWS OpenSearch 服务时,角色 ARN 需要与 OpenSearch 域在同一账户中。有关为 AWS OpenSearch 服务添加新角色的更多信息,请参阅[添加服务 ARN](#添加-aws-opensearch-服务-arn)。 +- **S3 bucket directory**:存储 `STIX2` 文件的 Amazon Simple Storage Service(Amazon S3)存储桶的名称。要访问不同 AWS 账户中的 S3 存储桶,请参阅[跨账户 S3 存储桶连接](#跨账户-s3-存储桶连接)部分了解更多详情。 +- **Specify a file**:S3 存储桶中 `STIX2` 文件的对象键。 +- **Region**:S3 存储桶的 AWS 区域。 + +您还可以设置 **Download schedule**,它确定 OpenSearch 从连接的 S3 存储桶下载更新的 `STIX2` 文件的位置。默认间隔为每天一次。仅支持每日间隔。 + +或者,您可以选中 **Download on demand** 选项,这会阻止自动下载存储桶中的新数据。 + +<!-- vale off --> +#### 添加 AWS OpenSearch 服务 ARN +<!-- vale on --> + +如果您使用 AWS OpenSearch 服务,请使用自定义信任策略创建新的 ARN 角色。有关如何创建角色的说明,请参阅[为 AWS 服务创建角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#roles-creatingrole-service-console)。 + +创建角色时,自定义以下设置: + +- 添加以下自定义信任策略: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Service": [ + "opensearchservice.amazonaws.com" + ] + }, + "Action": "sts:AssumeRole" + } + ] +} +``` + +- 在权限策略页面上,添加 `AmazonS3ReadOnlyAccess` 权限。 + +#### 跨账户 S3 存储桶连接 + +由于角色 ARN 需要与 OpenSearch 域在同一账户中,因此需要配置信任策略,允许 OpenSearch 域从同一账户的 S3 存储桶下载。 + +要从另一个账户中的 S3 存储桶下载,该存储桶的信任策略需要授予角色 ARN 从对象读取的权限,如以下示例所示: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:iam::123456789012:role/account-1-threat-intel-role" + }, + "Action": "s3:*", + "Resource": "arn:aws:s3:::account-2-threat-intel-bucket/*" + } + ] +} +``` + +## 步骤 2:为您的日志源设置扫描 + +您可以配置威胁情报监控器来扫描您的别名和数据流。监控器会扫描从索引中新摄取的数据,并将该数据与威胁情报源中存在的任何 IOC 进行匹配。扫描适用于添加到 OpenSearch 的所有威胁情报源。默认情况下,扫描每分钟运行一次。 + +要添加或编辑扫描配置: + +1. 从威胁情报视图中,选择 **Add scan configuration** 或 **Edit scan configuration**。 +2. 选择要扫描的索引或别名。 +3. 根据 IOC 类型从索引或别名中选择要扫描的**字段**。例如,如果一个别名有两个名为 `src_ip` 和 `dst_ip` 的字段包含 `ipv4` 地址,则必须将这些字段输入到监控器请求的 `ipv4-addr` 部分。 +4. 确定指定索引或别名的 **Scan schedule**。默认情况下,OpenSearch 每分钟扫描一次 IOC。 +5. 设置任何告警触发器和触发条件。您可以添加多个触发器: + 1. 为触发器添加名称。 + 2. 选择指标类型。指标类型与 IOC 类型匹配。 + 3. 为告警选择严重性。 + 4. 选择是否在触发告警时发送通知。启用后,您可以自定义将通知发送到哪些渠道以及通知消息。通知消息可以使用 [Mustache 模板](https://mustache.github.io/mustache.5.html)自定义。 +6. 输入设置后,选择 **Save and start monitoring**。 + +当发现恶意 IOC 时,OpenSearch 会创建**发现**,提供有关威胁的信息。您还可以配置触发器来创建告警,将通知发送到配置的 webhook 或端点。 + +## 查看告警和发现 + +您可以查看威胁情报监控器生成的告警和发现,以分析其安全日志中发生了哪些恶意指标。要查看告警或发现,请从威胁情报视图中选择 **View findings** 或 **View alerts**。 diff --git a/i18n/zh/security-analytics/threat-intelligence/index.md b/i18n/zh/security-analytics/threat-intelligence/index.md new file mode 100644 index 00000000..72c2340b --- /dev/null +++ b/i18n/zh/security-analytics/threat-intelligence/index.md @@ -0,0 +1,12 @@ +--- +title: 威胁情报 +--- + +# 威胁情报 + +安全分析中的威胁情报提供了集成威胁情报源的能力。情报源包含入侵指标(IOC),通过设置威胁情报监控器在您的数据中搜索恶意指标。这些监控器会生成发现,并在威胁情报源中的恶意 IP、域名或哈希值与您的数据匹配时发送通知。 + +您可以通过以下方式与威胁情报交互: + +- 威胁情报 API:要使用 API 操作配置威胁情报,请参阅[威胁情报 API](/security-analytics/threat-intelligence/api/threat-intel-api)。 +- OpenSearch 仪表板:要通过 OpenSearch 仪表板界面配置和使用威胁情报,请参阅[入门指南](/security-analytics/threat-intelligence/getting-started)。 diff --git a/scripts/import-jekyll.mjs b/scripts/import-jekyll.mjs index 1a8b87d7..b1d0b5ba 100644 --- a/scripts/import-jekyll.mjs +++ b/scripts/import-jekyll.mjs @@ -2,7 +2,8 @@ // this repository (_about/, _api-reference/, ...) into src/, converting Jekyll Liquid // and kramdown extensions to VitePress Markdown. // -// Usage: node scripts/import-jekyll.mjs +// Usage: node scripts/import-jekyll.mjs (Jekyll collections -> src/) +// node scripts/import-jekyll.mjs --zh (convert i18n/zh/ translations in place) // // - The Jekyll sources stay untouched, so upstream changes can still be merged into // them; re-run this script afterwards to refresh src/. @@ -456,7 +457,8 @@ function convertKramdown(text, page) { .split(SITE_MARK).join(''); result = rewriteLinks(rewriteImages(result, page), page); const heading = result.match(HEADING); - if (heading && !CUSTOM_ID.test(result)) { + // Translations get their heading ids from the English page (sync-zh.mjs). + if (heading && !page.translation && !CUSTOM_ID.test(result)) { const textValue = headingText(heading[2]); let kid = kramdownId(textValue); const n = usedIds.get(kid) ?? 0; @@ -615,4 +617,41 @@ function main() { console.log(`[import] ${written} pages written to src/, ${redirectLines.length} redirects, nav in scripts/nav.json.`); } -main(); +// --------------------------------------------------------------------------- +// Translations (--zh) +// --------------------------------------------------------------------------- + +const ZH_DIR = path.join(ROOT, 'i18n', 'zh'); +const JEKYLL_FRONT_MATTER = /^(layout|parent|grand_parent|nav_order|has_children|has_toc|redirect_from|permalink|nav_exclude):/m; +const JEKYLL_SYNTAX = /\{%|\{\{\s*site\.|\{:|\{::/; + +// Translations copied from the Jekyll collections still use Liquid, kramdown and +// just-the-docs front matter. Convert them in place the same way as the English pages. +function convertTranslations() { + const pageByFile = new Map(livePages.map(page => [page.file, page])); + let converted = 0; + for (const rel of listMarkdown(ZH_DIR)) { + if (KEEP.has(rel)) continue; + const file = path.join(ZH_DIR, rel); + const text = fs.readFileSync(file, 'utf8'); + const { data, lines, body } = parseFrontMatter(text); + const jekyllFrontMatter = JEKYLL_FRONT_MATTER.test(text.slice(0, text.length - body.length)); + if (!jekyllFrontMatter && !JEKYLL_SYNTAX.test(body)) continue; + const source = pageByFile.get(rel); + const page = { source: `i18n/zh/${rel}`, url: source?.url ?? `/${rel.replace(/\.md$/, '')}/`, data, lines, translation: true }; + const head = jekyllFrontMatter ? frontMatterFor(page) : text.slice(0, text.length - body.length).replace(/\s*$/, '\n\n'); + const output = `${head}${convertKramdown(convertLiquid(body, page), page).trim()}\n`; + if (output !== text) { + fs.writeFileSync(file, output); + converted++; + } + } + if (unknownLiquid.size) { + console.warn(`[import] ${unknownLiquid.size} unhandled Liquid expressions (left as is or removed):`); + for (const key of [...unknownLiquid.keys()].slice(0, 20)) console.warn(` ${key}`); + } + console.log(`[import] ${converted} translations in i18n/zh/ converted to VitePress Markdown.`); +} + +if (process.argv.includes('--zh')) convertTranslations(); +else main();